Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.git] / utilities / ovs-dpctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <arpa/inet.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <sys/socket.h>
23 #include <net/if.h>
24 #include <netinet/in.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31 #include <sys/time.h>
32
33 #include "command-line.h"
34 #include "compiler.h"
35 #include "dirs.h"
36 #include "dpif.h"
37 #include "dynamic-string.h"
38 #include "fatal-signal.h"
39 #include "flow.h"
40 #include "match.h"
41 #include "netdev.h"
42 #include "netlink.h"
43 #include "odp-util.h"
44 #include "ofp-parse.h"
45 #include "ofpbuf.h"
46 #include "packets.h"
47 #include "shash.h"
48 #include "simap.h"
49 #include "smap.h"
50 #include "sset.h"
51 #include "timeval.h"
52 #include "util.h"
53 #include "vlog.h"
54
55 /* -s, --statistics: Print port/flow statistics? */
56 static bool print_statistics;
57
58 /* --clear: Reset existing statistics to zero when modifying a flow? */
59 static bool zero_statistics;
60
61 /* --may-create: Allow mod-flows command to create a new flow? */
62 static bool may_create;
63
64 /* -m, --more: Increase output verbosity. */
65 static int verbosity;
66
67 static const struct command *get_all_commands(void);
68
69 static void usage(void) NO_RETURN;
70 static void parse_options(int argc, char *argv[]);
71
72 int
73 main(int argc, char *argv[])
74 {
75     set_program_name(argv[0]);
76     parse_options(argc, argv);
77     fatal_ignore_sigpipe();
78     run_command(argc - optind, argv + optind, get_all_commands());
79     return 0;
80 }
81
82 static void
83 parse_options(int argc, char *argv[])
84 {
85     enum {
86         OPT_CLEAR = UCHAR_MAX + 1,
87         OPT_MAY_CREATE,
88         VLOG_OPTION_ENUMS
89     };
90     static const struct option long_options[] = {
91         {"statistics", no_argument, NULL, 's'},
92         {"clear", no_argument, NULL, OPT_CLEAR},
93         {"may-create", no_argument, NULL, OPT_MAY_CREATE},
94         {"more", no_argument, NULL, 'm'},
95         {"timeout", required_argument, NULL, 't'},
96         {"help", no_argument, NULL, 'h'},
97         {"version", no_argument, NULL, 'V'},
98         VLOG_LONG_OPTIONS,
99         {NULL, 0, NULL, 0},
100     };
101     char *short_options = long_options_to_short_options(long_options);
102
103     for (;;) {
104         unsigned long int timeout;
105         int c;
106
107         c = getopt_long(argc, argv, short_options, long_options, NULL);
108         if (c == -1) {
109             break;
110         }
111
112         switch (c) {
113         case 's':
114             print_statistics = true;
115             break;
116
117         case OPT_CLEAR:
118             zero_statistics = true;
119             break;
120
121         case OPT_MAY_CREATE:
122             may_create = true;
123             break;
124
125         case 'm':
126             verbosity++;
127             break;
128
129         case 't':
130             timeout = strtoul(optarg, NULL, 10);
131             if (timeout <= 0) {
132                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
133                           optarg);
134             } else {
135                 time_alarm(timeout);
136             }
137             break;
138
139         case 'h':
140             usage();
141
142         case 'V':
143             ovs_print_version(0, 0);
144             exit(EXIT_SUCCESS);
145
146         VLOG_OPTION_HANDLERS
147
148         case '?':
149             exit(EXIT_FAILURE);
150
151         default:
152             abort();
153         }
154     }
155     free(short_options);
156 }
157
158 static void
159 usage(void)
160 {
161     printf("%s: Open vSwitch datapath management utility\n"
162            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
163            "  add-dp DP [IFACE...]     add new datapath DP (with IFACEs)\n"
164            "  del-dp DP                delete local datapath DP\n"
165            "  add-if DP IFACE...       add each IFACE as a port on DP\n"
166            "  set-if DP IFACE...       reconfigure each IFACE within DP\n"
167            "  del-if DP IFACE...       delete each IFACE from DP\n"
168            "  dump-dps                 display names of all datapaths\n"
169            "  show                     show basic info on all datapaths\n"
170            "  show DP...               show basic info on each DP\n"
171            "  dump-flows [DP]          display flows in DP\n"
172            "  add-flow [DP] FLOW ACTIONS add FLOW with ACTIONS to DP\n"
173            "  mod-flow [DP] FLOW ACTIONS change FLOW actions to ACTIONS in DP\n"
174            "  del-flow [DP] FLOW         delete FLOW from DP\n"
175            "  del-flows [DP]             delete all flows from DP\n"
176            "Each IFACE on add-dp, add-if, and set-if may be followed by\n"
177            "comma-separated options.  See ovs-dpctl(8) for syntax, or the\n"
178            "Interface table in ovs-vswitchd.conf.db(5) for an options list.\n"
179            "For COMMAND dump-flows, add-flow, mod-flow, del-flow and\n"
180            "del-flows, DP is optional if there is only one datapath.\n",
181            program_name, program_name);
182     vlog_usage();
183     printf("\nOptions for show and mod-flow:\n"
184            "  -s,  --statistics           print statistics for port or flow\n"
185            "\nOptions for dump-flows:\n"
186            "  -m, --more                  increase verbosity of output\n"
187            "\nOptions for mod-flow:\n"
188            "  --may-create                create flow if it doesn't exist\n"
189            "  --clear                     reset existing stats to zero\n"
190            "\nOther options:\n"
191            "  -t, --timeout=SECS          give up after SECS seconds\n"
192            "  -h, --help                  display this help message\n"
193            "  -V, --version               display version information\n");
194     exit(EXIT_SUCCESS);
195 }
196
197 static void run(int retval, const char *message, ...)
198     PRINTF_FORMAT(2, 3);
199
200 static void run(int retval, const char *message, ...)
201 {
202     if (retval) {
203         va_list args;
204
205         va_start(args, message);
206         ovs_fatal_valist(retval, message, args);
207     }
208 }
209 \f
210 static void dpctl_add_if(int argc, char *argv[]);
211
212 static int if_up(const char *netdev_name)
213 {
214     struct netdev *netdev;
215     int retval;
216
217     retval = netdev_open(netdev_name, "system", &netdev);
218     if (!retval) {
219         retval = netdev_turn_flags_on(netdev, NETDEV_UP, NULL);
220         netdev_close(netdev);
221     }
222     return retval;
223 }
224
225 /* Retrieve the name of the datapath if exactly one exists.  The caller
226  * is responsible for freeing the returned string.  If there is not one
227  * datapath, aborts with an error message. */
228 static char *
229 get_one_dp(void)
230 {
231     struct sset types;
232     const char *type;
233     char *dp_name = NULL;
234     size_t count = 0;
235
236     sset_init(&types);
237     dp_enumerate_types(&types);
238     SSET_FOR_EACH (type, &types) {
239         struct sset names;
240
241         sset_init(&names);
242         if (!dp_enumerate_names(type, &names)) {
243             count += sset_count(&names);
244             if (!dp_name && count == 1) {
245                 dp_name = xasprintf("%s@%s", type, SSET_FIRST(&names));
246             }
247         }
248         sset_destroy(&names);
249     }
250     sset_destroy(&types);
251
252     if (!count) {
253         ovs_fatal(0, "no datapaths exist");
254     } else if (count > 1) {
255         ovs_fatal(0, "multiple datapaths, specify one");
256     }
257
258     return dp_name;
259 }
260
261 static int
262 parsed_dpif_open(const char *arg_, bool create, struct dpif **dpifp)
263 {
264     int result;
265     char *name, *type;
266
267     dp_parse_name(arg_, &name, &type);
268
269     if (create) {
270         result = dpif_create(name, type, dpifp);
271     } else {
272         result = dpif_open(name, type, dpifp);
273     }
274
275     free(name);
276     free(type);
277     return result;
278 }
279
280 static void
281 dpctl_add_dp(int argc OVS_UNUSED, char *argv[])
282 {
283     struct dpif *dpif;
284     run(parsed_dpif_open(argv[1], true, &dpif), "add_dp");
285     dpif_close(dpif);
286     if (argc > 2) {
287         dpctl_add_if(argc, argv);
288     }
289 }
290
291 static void
292 dpctl_del_dp(int argc OVS_UNUSED, char *argv[])
293 {
294     struct dpif *dpif;
295     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
296     run(dpif_delete(dpif), "del_dp");
297     dpif_close(dpif);
298 }
299
300 static void
301 dpctl_add_if(int argc OVS_UNUSED, char *argv[])
302 {
303     bool failure = false;
304     struct dpif *dpif;
305     int i;
306
307     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
308     for (i = 2; i < argc; i++) {
309         const char *name, *type;
310         char *save_ptr = NULL;
311         struct netdev *netdev = NULL;
312         struct smap args;
313         odp_port_t port_no = ODPP_NONE;
314         char *option;
315         int error;
316
317         name = strtok_r(argv[i], ",", &save_ptr);
318         type = "system";
319
320         if (!name) {
321             ovs_error(0, "%s is not a valid network device name", argv[i]);
322             failure = true;
323             continue;
324         }
325
326         smap_init(&args);
327         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
328             char *save_ptr_2 = NULL;
329             char *key, *value;
330
331             key = strtok_r(option, "=", &save_ptr_2);
332             value = strtok_r(NULL, "", &save_ptr_2);
333             if (!value) {
334                 value = "";
335             }
336
337             if (!strcmp(key, "type")) {
338                 type = value;
339             } else if (!strcmp(key, "port_no")) {
340                 port_no = u32_to_odp(atoi(value));
341             } else if (!smap_add_once(&args, key, value)) {
342                 ovs_error(0, "duplicate \"%s\" option", key);
343             }
344         }
345
346         error = netdev_open(name, type, &netdev);
347         if (error) {
348             ovs_error(error, "%s: failed to open network device", name);
349             goto next;
350         }
351
352         error = netdev_set_config(netdev, &args);
353         if (error) {
354             goto next;
355         }
356
357         error = dpif_port_add(dpif, netdev, &port_no);
358         if (error) {
359             ovs_error(error, "adding %s to %s failed", name, argv[1]);
360             goto next;
361         }
362
363         error = if_up(name);
364
365 next:
366         netdev_close(netdev);
367         if (error) {
368             failure = true;
369         }
370     }
371     dpif_close(dpif);
372     if (failure) {
373         exit(EXIT_FAILURE);
374     }
375 }
376
377 static void
378 dpctl_set_if(int argc, char *argv[])
379 {
380     bool failure = false;
381     struct dpif *dpif;
382     int i;
383
384     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
385     for (i = 2; i < argc; i++) {
386         struct netdev *netdev = NULL;
387         struct dpif_port dpif_port;
388         char *save_ptr = NULL;
389         char *type = NULL;
390         const char *name;
391         struct smap args;
392         odp_port_t port_no;
393         char *option;
394         int error;
395
396         name = strtok_r(argv[i], ",", &save_ptr);
397         if (!name) {
398             ovs_error(0, "%s is not a valid network device name", argv[i]);
399             failure = true;
400             continue;
401         }
402
403         /* Get the port's type from the datapath. */
404         error = dpif_port_query_by_name(dpif, name, &dpif_port);
405         if (error) {
406             ovs_error(error, "%s: failed to query port in %s", name, argv[1]);
407             goto next;
408         }
409         type = xstrdup(dpif_port.type);
410         port_no = dpif_port.port_no;
411         dpif_port_destroy(&dpif_port);
412
413         /* Retrieve its existing configuration. */
414         error = netdev_open(name, type, &netdev);
415         if (error) {
416             ovs_error(error, "%s: failed to open network device", name);
417             goto next;
418         }
419
420         smap_init(&args);
421         error = netdev_get_config(netdev, &args);
422         if (error) {
423             ovs_error(error, "%s: failed to fetch configuration", name);
424             goto next;
425         }
426
427         /* Parse changes to configuration. */
428         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
429             char *save_ptr_2 = NULL;
430             char *key, *value;
431
432             key = strtok_r(option, "=", &save_ptr_2);
433             value = strtok_r(NULL, "", &save_ptr_2);
434             if (!value) {
435                 value = "";
436             }
437
438             if (!strcmp(key, "type")) {
439                 if (strcmp(value, type)) {
440                     ovs_error(0, "%s: can't change type from %s to %s",
441                               name, type, value);
442                     failure = true;
443                 }
444             } else if (!strcmp(key, "port_no")) {
445                 if (port_no != u32_to_odp(atoi(value))) {
446                     ovs_error(0, "%s: can't change port number from "
447                               "%"PRIu32" to %d",
448                               name, port_no, atoi(value));
449                     failure = true;
450                 }
451             } else if (value[0] == '\0') {
452                 smap_remove(&args, key);
453             } else {
454                 smap_replace(&args, key, value);
455             }
456         }
457
458         /* Update configuration. */
459         error = netdev_set_config(netdev, &args);
460         smap_destroy(&args);
461         if (error) {
462             goto next;
463         }
464
465 next:
466         free(type);
467         netdev_close(netdev);
468         if (error) {
469             failure = true;
470         }
471     }
472     dpif_close(dpif);
473     if (failure) {
474         exit(EXIT_FAILURE);
475     }
476 }
477
478 static bool
479 get_port_number(struct dpif *dpif, const char *name, odp_port_t *port)
480 {
481     struct dpif_port dpif_port;
482
483     if (!dpif_port_query_by_name(dpif, name, &dpif_port)) {
484         *port = dpif_port.port_no;
485         dpif_port_destroy(&dpif_port);
486         return true;
487     } else {
488         ovs_error(0, "no port named %s", name);
489         return false;
490     }
491 }
492
493 static void
494 dpctl_del_if(int argc OVS_UNUSED, char *argv[])
495 {
496     bool failure = false;
497     struct dpif *dpif;
498     int i;
499
500     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
501     for (i = 2; i < argc; i++) {
502         const char *name = argv[i];
503         odp_port_t port;
504         int error;
505
506         if (!name[strspn(name, "0123456789")]) {
507             port = u32_to_odp(atoi(name));
508         } else if (!get_port_number(dpif, name, &port)) {
509             failure = true;
510             continue;
511         }
512
513         error = dpif_port_del(dpif, port);
514         if (error) {
515             ovs_error(error, "deleting port %s from %s failed", name, argv[1]);
516             failure = true;
517         }
518     }
519     dpif_close(dpif);
520     if (failure) {
521         exit(EXIT_FAILURE);
522     }
523 }
524
525 static void
526 print_stat(const char *leader, uint64_t value)
527 {
528     fputs(leader, stdout);
529     if (value != UINT64_MAX) {
530         printf("%"PRIu64, value);
531     } else {
532         putchar('?');
533     }
534 }
535
536 static void
537 print_human_size(uint64_t value)
538 {
539     if (value == UINT64_MAX) {
540         /* Nothing to do. */
541     } else if (value >= 1024ULL * 1024 * 1024 * 1024) {
542         printf(" (%.1f TiB)", value / (1024.0 * 1024 * 1024 * 1024));
543     } else if (value >= 1024ULL * 1024 * 1024) {
544         printf(" (%.1f GiB)", value / (1024.0 * 1024 * 1024));
545     } else if (value >= 1024ULL * 1024) {
546         printf(" (%.1f MiB)", value / (1024.0 * 1024));
547     } else if (value >= 1024) {
548         printf(" (%.1f KiB)", value / 1024.0);
549     }
550 }
551
552 static void
553 show_dpif(struct dpif *dpif)
554 {
555     struct dpif_port_dump dump;
556     struct dpif_port dpif_port;
557     struct dpif_dp_stats stats;
558     struct netdev *netdev;
559
560     printf("%s:\n", dpif_name(dpif));
561     if (!dpif_get_dp_stats(dpif, &stats)) {
562         printf("\tlookups: hit:%"PRIu64" missed:%"PRIu64" lost:%"PRIu64"\n"
563                "\tflows: %"PRIu64"\n",
564                stats.n_hit, stats.n_missed, stats.n_lost, stats.n_flows);
565         if (stats.n_masks != UINT32_MAX) {
566             uint64_t n_pkts = stats.n_hit + stats.n_missed;
567             double avg = n_pkts ? (double) stats.n_mask_hit / n_pkts : 0.0;
568
569             printf("\tmasks: hit:%"PRIu64" total:%"PRIu32" hit/pkt:%.2f\n",
570                    stats.n_mask_hit, stats.n_masks, avg);
571         }
572     }
573
574     DPIF_PORT_FOR_EACH (&dpif_port, &dump, dpif) {
575         printf("\tport %u: %s", dpif_port.port_no, dpif_port.name);
576
577         if (strcmp(dpif_port.type, "system")) {
578             int error;
579
580             printf (" (%s", dpif_port.type);
581
582             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
583             if (!error) {
584                 struct smap config;
585
586                 smap_init(&config);
587                 error = netdev_get_config(netdev, &config);
588                 if (!error) {
589                     const struct smap_node **nodes;
590                     size_t i;
591
592                     nodes = smap_sort(&config);
593                     for (i = 0; i < smap_count(&config); i++) {
594                         const struct smap_node *node = nodes[i];
595                         printf("%c %s=%s", i ? ',' : ':', node->key,
596                                node->value);
597                     }
598                     free(nodes);
599                 } else {
600                     printf(", could not retrieve configuration (%s)",
601                            ovs_strerror(error));
602                 }
603                 smap_destroy(&config);
604
605                 netdev_close(netdev);
606             } else {
607                 printf(": open failed (%s)", ovs_strerror(error));
608             }
609             putchar(')');
610         }
611         putchar('\n');
612
613         if (print_statistics) {
614             struct netdev_stats s;
615             int error;
616
617             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
618             if (error) {
619                 printf(", open failed (%s)", ovs_strerror(error));
620                 continue;
621             }
622             error = netdev_get_stats(netdev, &s);
623             if (error) {
624                 printf(", could not retrieve stats (%s)", ovs_strerror(error));
625                 continue;
626             }
627
628             netdev_close(netdev);
629             print_stat("\t\tRX packets:", s.rx_packets);
630             print_stat(" errors:", s.rx_errors);
631             print_stat(" dropped:", s.rx_dropped);
632             print_stat(" overruns:", s.rx_over_errors);
633             print_stat(" frame:", s.rx_frame_errors);
634             printf("\n");
635
636             print_stat("\t\tTX packets:", s.tx_packets);
637             print_stat(" errors:", s.tx_errors);
638             print_stat(" dropped:", s.tx_dropped);
639             print_stat(" aborted:", s.tx_aborted_errors);
640             print_stat(" carrier:", s.tx_carrier_errors);
641             printf("\n");
642
643             print_stat("\t\tcollisions:", s.collisions);
644             printf("\n");
645
646             print_stat("\t\tRX bytes:", s.rx_bytes);
647             print_human_size(s.rx_bytes);
648             print_stat("  TX bytes:", s.tx_bytes);
649             print_human_size(s.tx_bytes);
650             printf("\n");
651         }
652     }
653     dpif_close(dpif);
654 }
655
656 static void
657 dpctl_show(int argc, char *argv[])
658 {
659     bool failure = false;
660     if (argc > 1) {
661         int i;
662         for (i = 1; i < argc; i++) {
663             const char *name = argv[i];
664             struct dpif *dpif;
665             int error;
666
667             error = parsed_dpif_open(name, false, &dpif);
668             if (!error) {
669                 show_dpif(dpif);
670             } else {
671                 ovs_error(error, "opening datapath %s failed", name);
672                 failure = true;
673             }
674         }
675     } else {
676         struct sset types;
677         const char *type;
678
679         sset_init(&types);
680         dp_enumerate_types(&types);
681         SSET_FOR_EACH (type, &types) {
682             struct sset names;
683             const char *name;
684
685             sset_init(&names);
686             if (dp_enumerate_names(type, &names)) {
687                 failure = true;
688                 continue;
689             }
690             SSET_FOR_EACH (name, &names) {
691                 struct dpif *dpif;
692                 int error;
693
694                 error = dpif_open(name, type, &dpif);
695                 if (!error) {
696                     show_dpif(dpif);
697                 } else {
698                     ovs_error(error, "opening datapath %s failed", name);
699                     failure = true;
700                 }
701             }
702             sset_destroy(&names);
703         }
704         sset_destroy(&types);
705     }
706     if (failure) {
707         exit(EXIT_FAILURE);
708     }
709 }
710
711 static void
712 dpctl_dump_dps(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
713 {
714     struct sset dpif_names, dpif_types;
715     const char *type;
716     int error = 0;
717
718     sset_init(&dpif_names);
719     sset_init(&dpif_types);
720     dp_enumerate_types(&dpif_types);
721
722     SSET_FOR_EACH (type, &dpif_types) {
723         const char *name;
724         int retval;
725
726         retval = dp_enumerate_names(type, &dpif_names);
727         if (retval) {
728             error = retval;
729         }
730
731         SSET_FOR_EACH (name, &dpif_names) {
732             struct dpif *dpif;
733             if (!dpif_open(name, type, &dpif)) {
734                 printf("%s\n", dpif_name(dpif));
735                 dpif_close(dpif);
736             }
737         }
738     }
739
740     sset_destroy(&dpif_names);
741     sset_destroy(&dpif_types);
742     if (error) {
743         exit(EXIT_FAILURE);
744     }
745 }
746
747 static void
748 dpctl_dump_flows(int argc, char *argv[])
749 {
750     const struct dpif_flow_stats *stats;
751     const struct nlattr *actions;
752     struct dpif_flow_dump flow_dump;
753     const struct nlattr *key;
754     const struct nlattr *mask;
755     struct dpif_port dpif_port;
756     struct dpif_port_dump port_dump;
757     struct hmap portno_names;
758     struct simap names_portno;
759     size_t actions_len;
760     struct dpif *dpif;
761     size_t key_len;
762     size_t mask_len;
763     struct ds ds;
764     char *name, *filter = NULL;
765     struct flow flow_filter;
766     struct flow_wildcards wc_filter;
767     void *state = NULL;
768     int error;
769
770     if (argc > 1 && !strncmp(argv[argc - 1], "filter=", 7)) {
771         filter = xstrdup(argv[--argc] + 7);
772     }
773     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
774
775     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
776     free(name);
777
778     hmap_init(&portno_names);
779     simap_init(&names_portno);
780     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
781         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
782         simap_put(&names_portno, dpif_port.name,
783                   odp_to_u32(dpif_port.port_no));
784     }
785
786     if (filter) {
787         char *err = parse_ofp_exact_flow(&flow_filter, &wc_filter.masks,
788                                          filter, &names_portno);
789         if (err) {
790             ovs_fatal(0, "Failed to parse filter (%s)", err);
791         }
792     }
793
794     ds_init(&ds);
795     error = dpif_flow_dump_start(&flow_dump, dpif);
796     if (error) {
797         goto exit;
798     }
799     dpif_flow_dump_state_init(dpif, &state);
800     while (dpif_flow_dump_next(&flow_dump, state, &key, &key_len,
801                                &mask, &mask_len, &actions, &actions_len,
802                                &stats)) {
803         if (filter) {
804             struct flow flow;
805             struct flow_wildcards wc;
806             struct match match, match_filter;
807             struct minimatch minimatch;
808
809             odp_flow_key_to_flow(key, key_len, &flow);
810             odp_flow_key_to_mask(mask, mask_len, &wc.masks, &flow);
811             match_init(&match, &flow, &wc);
812
813             match_init(&match_filter, &flow_filter, &wc);
814             match_init(&match_filter, &match_filter.flow, &wc_filter);
815             minimatch_init(&minimatch, &match_filter);
816
817             if (!minimatch_matches_flow(&minimatch, &match.flow)) {
818                 minimatch_destroy(&minimatch);
819                 continue;
820             }
821             minimatch_destroy(&minimatch);
822         }
823         ds_clear(&ds);
824         odp_flow_format(key, key_len, mask, mask_len, &portno_names, &ds,
825                         verbosity);
826         ds_put_cstr(&ds, ", ");
827
828         dpif_flow_stats_format(stats, &ds);
829         ds_put_cstr(&ds, ", actions:");
830         format_odp_actions(&ds, actions, actions_len);
831         printf("%s\n", ds_cstr(&ds));
832     }
833     dpif_flow_dump_state_uninit(dpif, state);
834     error = dpif_flow_dump_done(&flow_dump);
835
836 exit:
837     if (error) {
838         ovs_fatal(error, "Failed to dump flows from datapath");
839     }
840     free(filter);
841     odp_portno_names_destroy(&portno_names);
842     hmap_destroy(&portno_names);
843     simap_destroy(&names_portno);
844     ds_destroy(&ds);
845     dpif_close(dpif);
846 }
847
848 static void
849 dpctl_put_flow(int argc, char *argv[], enum dpif_flow_put_flags flags)
850 {
851     const char *key_s = argv[argc - 2];
852     const char *actions_s = argv[argc - 1];
853     struct dpif_flow_stats stats;
854     struct dpif_port dpif_port;
855     struct dpif_port_dump port_dump;
856     struct ofpbuf actions;
857     struct ofpbuf key;
858     struct ofpbuf mask;
859     struct dpif *dpif;
860     struct ds s;
861     char *dp_name;
862     struct simap port_names;
863
864     dp_name = argc == 4 ? xstrdup(argv[1]) : get_one_dp();
865     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
866     free(dp_name);
867
868
869     simap_init(&port_names);
870     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
871         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
872     }
873
874     ds_init(&s);
875     ofpbuf_init(&key, 0);
876     ofpbuf_init(&mask, 0);
877     run(odp_flow_from_string(key_s, &port_names, &key, &mask),
878         "parsing flow key");
879
880     simap_destroy(&port_names);
881
882     ofpbuf_init(&actions, 0);
883     run(odp_actions_from_string(actions_s, NULL, &actions), "parsing actions");
884
885     run(dpif_flow_put(dpif, flags,
886                       ofpbuf_data(&key), ofpbuf_size(&key),
887                       ofpbuf_size(&mask) == 0 ? NULL : ofpbuf_data(&mask),
888                       ofpbuf_size(&mask),
889                       ofpbuf_data(&actions), ofpbuf_size(&actions),
890                       print_statistics ? &stats : NULL),
891         "updating flow table");
892
893     ofpbuf_uninit(&key);
894     ofpbuf_uninit(&mask);
895     ofpbuf_uninit(&actions);
896
897     if (print_statistics) {
898         struct ds s;
899
900         ds_init(&s);
901         dpif_flow_stats_format(&stats, &s);
902         puts(ds_cstr(&s));
903         ds_destroy(&s);
904     }
905 }
906
907 static void
908 dpctl_add_flow(int argc, char *argv[])
909 {
910     dpctl_put_flow(argc, argv, DPIF_FP_CREATE);
911 }
912
913 static void
914 dpctl_mod_flow(int argc OVS_UNUSED, char *argv[])
915 {
916     enum dpif_flow_put_flags flags;
917
918     flags = DPIF_FP_MODIFY;
919     if (may_create) {
920         flags |= DPIF_FP_CREATE;
921     }
922     if (zero_statistics) {
923         flags |= DPIF_FP_ZERO_STATS;
924     }
925
926     dpctl_put_flow(argc, argv, flags);
927 }
928
929 static void
930 dpctl_del_flow(int argc, char *argv[])
931 {
932     const char *key_s = argv[argc - 1];
933     struct dpif_flow_stats stats;
934     struct dpif_port dpif_port;
935     struct dpif_port_dump port_dump;
936     struct ofpbuf key;
937     struct ofpbuf mask; /* To be ignored. */
938     struct dpif *dpif;
939     char *dp_name;
940     struct simap port_names;
941
942     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp();
943     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
944     free(dp_name);
945
946     simap_init(&port_names);
947     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
948         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
949     }
950
951     ofpbuf_init(&key, 0);
952     ofpbuf_init(&mask, 0);
953     run(odp_flow_from_string(key_s, &port_names, &key, &mask), "parsing flow key");
954
955     run(dpif_flow_del(dpif,
956                       ofpbuf_data(&key), ofpbuf_size(&key),
957                       print_statistics ? &stats : NULL), "deleting flow");
958
959     simap_destroy(&port_names);
960     ofpbuf_uninit(&key);
961     ofpbuf_uninit(&mask);
962
963     if (print_statistics) {
964         struct ds s;
965
966         ds_init(&s);
967         dpif_flow_stats_format(&stats, &s);
968         puts(ds_cstr(&s));
969         ds_destroy(&s);
970     }
971 }
972
973 static void
974 dpctl_del_flows(int argc, char *argv[])
975 {
976     struct dpif *dpif;
977     char *name;
978
979     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
980     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
981     free(name);
982
983     run(dpif_flow_flush(dpif), "deleting all flows");
984     dpif_close(dpif);
985 }
986
987 static void
988 dpctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
989 {
990     usage();
991 }
992 \f
993 /* Undocumented commands for unit testing. */
994
995 static void
996 dpctl_parse_actions(int argc, char *argv[])
997 {
998     int i;
999
1000     for (i = 1; i < argc; i++) {
1001         struct ofpbuf actions;
1002         struct ds s;
1003
1004         ofpbuf_init(&actions, 0);
1005         run(odp_actions_from_string(argv[i], NULL, &actions),
1006             "odp_actions_from_string");
1007
1008         ds_init(&s);
1009         format_odp_actions(&s, ofpbuf_data(&actions), ofpbuf_size(&actions));
1010         puts(ds_cstr(&s));
1011         ds_destroy(&s);
1012
1013         ofpbuf_uninit(&actions);
1014     }
1015 }
1016
1017 struct actions_for_flow {
1018     struct hmap_node hmap_node;
1019     struct flow flow;
1020     struct ofpbuf actions;
1021 };
1022
1023 static struct actions_for_flow *
1024 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
1025 {
1026     uint32_t hash = flow_hash(flow, 0);
1027     struct actions_for_flow *af;
1028
1029     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
1030         if (flow_equal(&af->flow, flow)) {
1031             return af;
1032         }
1033     }
1034
1035     af = xmalloc(sizeof *af);
1036     af->flow = *flow;
1037     ofpbuf_init(&af->actions, 0);
1038     hmap_insert(actions_per_flow, &af->hmap_node, hash);
1039     return af;
1040 }
1041
1042 static int
1043 compare_actions_for_flow(const void *a_, const void *b_)
1044 {
1045     struct actions_for_flow *const *a = a_;
1046     struct actions_for_flow *const *b = b_;
1047
1048     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
1049 }
1050
1051 static int
1052 compare_output_actions(const void *a_, const void *b_)
1053 {
1054     const struct nlattr *a = a_;
1055     const struct nlattr *b = b_;
1056     uint32_t a_port = nl_attr_get_u32(a);
1057     uint32_t b_port = nl_attr_get_u32(b);
1058
1059     return a_port < b_port ? -1 : a_port > b_port;
1060 }
1061
1062 static void
1063 sort_output_actions__(struct nlattr *first, struct nlattr *end)
1064 {
1065     size_t bytes = (uint8_t *) end - (uint8_t *) first;
1066     size_t n = bytes / NL_A_U32_SIZE;
1067
1068     ovs_assert(bytes % NL_A_U32_SIZE == 0);
1069     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
1070 }
1071
1072 static void
1073 sort_output_actions(struct nlattr *actions, size_t length)
1074 {
1075     struct nlattr *first_output = NULL;
1076     struct nlattr *a;
1077     int left;
1078
1079     NL_ATTR_FOR_EACH (a, left, actions, length) {
1080         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
1081             if (!first_output) {
1082                 first_output = a;
1083             }
1084         } else {
1085             if (first_output) {
1086                 sort_output_actions__(first_output, a);
1087                 first_output = NULL;
1088             }
1089         }
1090     }
1091     if (first_output) {
1092         uint8_t *end = (uint8_t *) actions + length;
1093         sort_output_actions__(first_output,
1094                               ALIGNED_CAST(struct nlattr *, end));
1095     }
1096 }
1097
1098 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
1099  * have the syntax used by "ovs-dpctl dump-flows".
1100  *
1101  * This command prints ACTIONS in a format that shows what happens for each
1102  * VLAN, independent of the order of the ACTIONS.  For example, there is more
1103  * than one way to output a packet on VLANs 9 and 11, but this command will
1104  * print the same output for any form.
1105  *
1106  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
1107  * so far the implementation only covers VLANs. */
1108 static void
1109 dpctl_normalize_actions(int argc, char *argv[])
1110 {
1111     struct simap port_names;
1112     struct ofpbuf keybuf;
1113     struct flow flow;
1114     struct ofpbuf odp_actions;
1115     struct hmap actions_per_flow;
1116     struct actions_for_flow **afs;
1117     struct actions_for_flow *af;
1118     struct nlattr *a;
1119     size_t n_afs;
1120     struct ds s;
1121     int left;
1122     int i;
1123
1124     ds_init(&s);
1125
1126     simap_init(&port_names);
1127     for (i = 3; i < argc; i++) {
1128         char name[16];
1129         int number;
1130
1131         if (ovs_scan(argv[i], "%15[^=]=%d", name, &number)) {
1132             uintptr_t n = number;
1133             simap_put(&port_names, name, n);
1134         } else {
1135             ovs_fatal(0, "%s: expected NAME=NUMBER", argv[i]);
1136         }
1137     }
1138
1139     /* Parse flow key. */
1140     ofpbuf_init(&keybuf, 0);
1141     run(odp_flow_from_string(argv[1], &port_names, &keybuf, NULL),
1142         "odp_flow_key_from_string");
1143
1144     ds_clear(&s);
1145     odp_flow_format(ofpbuf_data(&keybuf), ofpbuf_size(&keybuf), NULL, 0, NULL, &s, verbosity);
1146     printf("input flow: %s\n", ds_cstr(&s));
1147
1148     run(odp_flow_key_to_flow(ofpbuf_data(&keybuf), ofpbuf_size(&keybuf), &flow),
1149         "odp_flow_key_to_flow");
1150     ofpbuf_uninit(&keybuf);
1151
1152     /* Parse actions. */
1153     ofpbuf_init(&odp_actions, 0);
1154     run(odp_actions_from_string(argv[2], &port_names, &odp_actions),
1155         "odp_actions_from_string");
1156     simap_destroy(&port_names);
1157
1158     if (verbosity) {
1159         ds_clear(&s);
1160         format_odp_actions(&s, ofpbuf_data(&odp_actions), ofpbuf_size(&odp_actions));
1161         printf("input actions: %s\n", ds_cstr(&s));
1162     }
1163
1164     hmap_init(&actions_per_flow);
1165     NL_ATTR_FOR_EACH (a, left, ofpbuf_data(&odp_actions), ofpbuf_size(&odp_actions)) {
1166         const struct ovs_action_push_vlan *push;
1167         switch(nl_attr_type(a)) {
1168         case OVS_ACTION_ATTR_POP_VLAN:
1169             flow.vlan_tci = htons(0);
1170             continue;
1171
1172         case OVS_ACTION_ATTR_PUSH_VLAN:
1173             push = nl_attr_get_unspec(a, sizeof *push);
1174             flow.vlan_tci = push->vlan_tci;
1175             continue;
1176         }
1177
1178         af = get_actions_for_flow(&actions_per_flow, &flow);
1179         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
1180                           nl_attr_get(a), nl_attr_get_size(a));
1181     }
1182
1183     n_afs = hmap_count(&actions_per_flow);
1184     afs = xmalloc(n_afs * sizeof *afs);
1185     i = 0;
1186     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
1187         afs[i++] = af;
1188     }
1189     ovs_assert(i == n_afs);
1190
1191     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
1192
1193     for (i = 0; i < n_afs; i++) {
1194         const struct actions_for_flow *af = afs[i];
1195
1196         sort_output_actions(ofpbuf_data(&af->actions), ofpbuf_size(&af->actions));
1197
1198         if (af->flow.vlan_tci != htons(0)) {
1199             printf("vlan(vid=%"PRIu16",pcp=%d): ",
1200                    vlan_tci_to_vid(af->flow.vlan_tci),
1201                    vlan_tci_to_pcp(af->flow.vlan_tci));
1202         } else {
1203             printf("no vlan: ");
1204         }
1205
1206         if (eth_type_mpls(af->flow.dl_type)) {
1207             printf("mpls(label=%"PRIu32",tc=%d,ttl=%d): ",
1208                    mpls_lse_to_label(af->flow.mpls_lse[0]),
1209                    mpls_lse_to_tc(af->flow.mpls_lse[0]),
1210                    mpls_lse_to_ttl(af->flow.mpls_lse[0]));
1211         } else {
1212             printf("no mpls: ");
1213         }
1214
1215         ds_clear(&s);
1216         format_odp_actions(&s, ofpbuf_data(&af->actions), ofpbuf_size(&af->actions));
1217         puts(ds_cstr(&s));
1218     }
1219     ds_destroy(&s);
1220 }
1221
1222 static const struct command all_commands[] = {
1223     { "add-dp", 1, INT_MAX, dpctl_add_dp },
1224     { "del-dp", 1, 1, dpctl_del_dp },
1225     { "add-if", 2, INT_MAX, dpctl_add_if },
1226     { "del-if", 2, INT_MAX, dpctl_del_if },
1227     { "set-if", 2, INT_MAX, dpctl_set_if },
1228     { "dump-dps", 0, 0, dpctl_dump_dps },
1229     { "show", 0, INT_MAX, dpctl_show },
1230     { "dump-flows", 0, 2, dpctl_dump_flows },
1231     { "add-flow", 2, 3, dpctl_add_flow },
1232     { "mod-flow", 2, 3, dpctl_mod_flow },
1233     { "del-flow", 1, 2, dpctl_del_flow },
1234     { "del-flows", 0, 1, dpctl_del_flows },
1235     { "help", 0, INT_MAX, dpctl_help },
1236
1237     /* Undocumented commands for testing. */
1238     { "parse-actions", 1, INT_MAX, dpctl_parse_actions },
1239     { "normalize-actions", 2, INT_MAX, dpctl_normalize_actions },
1240
1241     { NULL, 0, 0, NULL },
1242 };
1243
1244 static const struct command *get_all_commands(void)
1245 {
1246     return all_commands;
1247 }