dpif: Refactor flow dumping interface to make better sense for batching.
[cascardo/ovs.git] / utilities / ovs-dpctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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, NULL);
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, NULL);
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     struct dpif *dpif;
751     struct ds ds;
752     char *name;
753
754     char *filter = NULL;
755     struct flow flow_filter;
756     struct flow_wildcards wc_filter;
757
758     struct dpif_port_dump port_dump;
759     struct dpif_port dpif_port;
760     struct hmap portno_names;
761     struct simap names_portno;
762
763     struct dpif_flow_dump_thread *flow_dump_thread;
764     struct dpif_flow_dump *flow_dump;
765     struct dpif_flow f;
766
767     int error;
768
769     if (argc > 1 && !strncmp(argv[argc - 1], "filter=", 7)) {
770         filter = xstrdup(argv[--argc] + 7);
771     }
772     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
773
774     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
775     free(name);
776
777     hmap_init(&portno_names);
778     simap_init(&names_portno);
779     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
780         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
781         simap_put(&names_portno, dpif_port.name,
782                   odp_to_u32(dpif_port.port_no));
783     }
784
785     if (filter) {
786         char *err = parse_ofp_exact_flow(&flow_filter, &wc_filter.masks,
787                                          filter, &names_portno);
788         if (err) {
789             ovs_fatal(0, "Failed to parse filter (%s)", err);
790         }
791     }
792
793     ds_init(&ds);
794     flow_dump = dpif_flow_dump_create(dpif);
795     flow_dump_thread = dpif_flow_dump_thread_create(flow_dump);
796     while (dpif_flow_dump_next(flow_dump_thread, &f, 1)) {
797         if (filter) {
798             struct flow flow;
799             struct flow_wildcards wc;
800             struct match match, match_filter;
801             struct minimatch minimatch;
802
803             odp_flow_key_to_flow(f.key, f.key_len, &flow);
804             odp_flow_key_to_mask(f.mask, f.mask_len, &wc.masks, &flow);
805             match_init(&match, &flow, &wc);
806
807             match_init(&match_filter, &flow_filter, &wc);
808             match_init(&match_filter, &match_filter.flow, &wc_filter);
809             minimatch_init(&minimatch, &match_filter);
810
811             if (!minimatch_matches_flow(&minimatch, &match.flow)) {
812                 minimatch_destroy(&minimatch);
813                 continue;
814             }
815             minimatch_destroy(&minimatch);
816         }
817         ds_clear(&ds);
818         odp_flow_format(f.key, f.key_len, f.mask, f.mask_len,
819                         &portno_names, &ds, verbosity);
820         ds_put_cstr(&ds, ", ");
821
822         dpif_flow_stats_format(&f.stats, &ds);
823         ds_put_cstr(&ds, ", actions:");
824         format_odp_actions(&ds, f.actions, f.actions_len);
825         printf("%s\n", ds_cstr(&ds));
826     }
827     dpif_flow_dump_thread_destroy(flow_dump_thread);
828     error = dpif_flow_dump_destroy(flow_dump);
829
830     if (error) {
831         ovs_fatal(error, "Failed to dump flows from datapath");
832     }
833     free(filter);
834     odp_portno_names_destroy(&portno_names);
835     hmap_destroy(&portno_names);
836     simap_destroy(&names_portno);
837     ds_destroy(&ds);
838     dpif_close(dpif);
839 }
840
841 static void
842 dpctl_put_flow(int argc, char *argv[], enum dpif_flow_put_flags flags)
843 {
844     const char *key_s = argv[argc - 2];
845     const char *actions_s = argv[argc - 1];
846     struct dpif_flow_stats stats;
847     struct dpif_port dpif_port;
848     struct dpif_port_dump port_dump;
849     struct ofpbuf actions;
850     struct ofpbuf key;
851     struct ofpbuf mask;
852     struct dpif *dpif;
853     struct ds s;
854     char *dp_name;
855     struct simap port_names;
856
857     dp_name = argc == 4 ? xstrdup(argv[1]) : get_one_dp();
858     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
859     free(dp_name);
860
861
862     simap_init(&port_names);
863     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
864         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
865     }
866
867     ds_init(&s);
868     ofpbuf_init(&key, 0);
869     ofpbuf_init(&mask, 0);
870     run(odp_flow_from_string(key_s, &port_names, &key, &mask),
871         "parsing flow key");
872
873     simap_destroy(&port_names);
874
875     ofpbuf_init(&actions, 0);
876     run(odp_actions_from_string(actions_s, NULL, &actions), "parsing actions");
877
878     run(dpif_flow_put(dpif, flags,
879                       ofpbuf_data(&key), ofpbuf_size(&key),
880                       ofpbuf_size(&mask) == 0 ? NULL : ofpbuf_data(&mask),
881                       ofpbuf_size(&mask),
882                       ofpbuf_data(&actions), ofpbuf_size(&actions),
883                       print_statistics ? &stats : NULL),
884         "updating flow table");
885
886     ofpbuf_uninit(&key);
887     ofpbuf_uninit(&mask);
888     ofpbuf_uninit(&actions);
889
890     if (print_statistics) {
891         struct ds s;
892
893         ds_init(&s);
894         dpif_flow_stats_format(&stats, &s);
895         puts(ds_cstr(&s));
896         ds_destroy(&s);
897     }
898 }
899
900 static void
901 dpctl_add_flow(int argc, char *argv[])
902 {
903     dpctl_put_flow(argc, argv, DPIF_FP_CREATE);
904 }
905
906 static void
907 dpctl_mod_flow(int argc OVS_UNUSED, char *argv[])
908 {
909     enum dpif_flow_put_flags flags;
910
911     flags = DPIF_FP_MODIFY;
912     if (may_create) {
913         flags |= DPIF_FP_CREATE;
914     }
915     if (zero_statistics) {
916         flags |= DPIF_FP_ZERO_STATS;
917     }
918
919     dpctl_put_flow(argc, argv, flags);
920 }
921
922 static void
923 dpctl_del_flow(int argc, char *argv[])
924 {
925     const char *key_s = argv[argc - 1];
926     struct dpif_flow_stats stats;
927     struct dpif_port dpif_port;
928     struct dpif_port_dump port_dump;
929     struct ofpbuf key;
930     struct ofpbuf mask; /* To be ignored. */
931     struct dpif *dpif;
932     char *dp_name;
933     struct simap port_names;
934
935     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp();
936     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
937     free(dp_name);
938
939     simap_init(&port_names);
940     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
941         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
942     }
943
944     ofpbuf_init(&key, 0);
945     ofpbuf_init(&mask, 0);
946     run(odp_flow_from_string(key_s, &port_names, &key, &mask), "parsing flow key");
947
948     run(dpif_flow_del(dpif,
949                       ofpbuf_data(&key), ofpbuf_size(&key),
950                       print_statistics ? &stats : NULL), "deleting flow");
951
952     simap_destroy(&port_names);
953     ofpbuf_uninit(&key);
954     ofpbuf_uninit(&mask);
955
956     if (print_statistics) {
957         struct ds s;
958
959         ds_init(&s);
960         dpif_flow_stats_format(&stats, &s);
961         puts(ds_cstr(&s));
962         ds_destroy(&s);
963     }
964 }
965
966 static void
967 dpctl_del_flows(int argc, char *argv[])
968 {
969     struct dpif *dpif;
970     char *name;
971
972     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
973     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
974     free(name);
975
976     run(dpif_flow_flush(dpif), "deleting all flows");
977     dpif_close(dpif);
978 }
979
980 static void
981 dpctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
982 {
983     usage();
984 }
985 \f
986 /* Undocumented commands for unit testing. */
987
988 static void
989 dpctl_parse_actions(int argc, char *argv[])
990 {
991     int i;
992
993     for (i = 1; i < argc; i++) {
994         struct ofpbuf actions;
995         struct ds s;
996
997         ofpbuf_init(&actions, 0);
998         run(odp_actions_from_string(argv[i], NULL, &actions),
999             "odp_actions_from_string");
1000
1001         ds_init(&s);
1002         format_odp_actions(&s, ofpbuf_data(&actions), ofpbuf_size(&actions));
1003         puts(ds_cstr(&s));
1004         ds_destroy(&s);
1005
1006         ofpbuf_uninit(&actions);
1007     }
1008 }
1009
1010 struct actions_for_flow {
1011     struct hmap_node hmap_node;
1012     struct flow flow;
1013     struct ofpbuf actions;
1014 };
1015
1016 static struct actions_for_flow *
1017 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
1018 {
1019     uint32_t hash = flow_hash(flow, 0);
1020     struct actions_for_flow *af;
1021
1022     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
1023         if (flow_equal(&af->flow, flow)) {
1024             return af;
1025         }
1026     }
1027
1028     af = xmalloc(sizeof *af);
1029     af->flow = *flow;
1030     ofpbuf_init(&af->actions, 0);
1031     hmap_insert(actions_per_flow, &af->hmap_node, hash);
1032     return af;
1033 }
1034
1035 static int
1036 compare_actions_for_flow(const void *a_, const void *b_)
1037 {
1038     struct actions_for_flow *const *a = a_;
1039     struct actions_for_flow *const *b = b_;
1040
1041     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
1042 }
1043
1044 static int
1045 compare_output_actions(const void *a_, const void *b_)
1046 {
1047     const struct nlattr *a = a_;
1048     const struct nlattr *b = b_;
1049     uint32_t a_port = nl_attr_get_u32(a);
1050     uint32_t b_port = nl_attr_get_u32(b);
1051
1052     return a_port < b_port ? -1 : a_port > b_port;
1053 }
1054
1055 static void
1056 sort_output_actions__(struct nlattr *first, struct nlattr *end)
1057 {
1058     size_t bytes = (uint8_t *) end - (uint8_t *) first;
1059     size_t n = bytes / NL_A_U32_SIZE;
1060
1061     ovs_assert(bytes % NL_A_U32_SIZE == 0);
1062     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
1063 }
1064
1065 static void
1066 sort_output_actions(struct nlattr *actions, size_t length)
1067 {
1068     struct nlattr *first_output = NULL;
1069     struct nlattr *a;
1070     int left;
1071
1072     NL_ATTR_FOR_EACH (a, left, actions, length) {
1073         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
1074             if (!first_output) {
1075                 first_output = a;
1076             }
1077         } else {
1078             if (first_output) {
1079                 sort_output_actions__(first_output, a);
1080                 first_output = NULL;
1081             }
1082         }
1083     }
1084     if (first_output) {
1085         uint8_t *end = (uint8_t *) actions + length;
1086         sort_output_actions__(first_output,
1087                               ALIGNED_CAST(struct nlattr *, end));
1088     }
1089 }
1090
1091 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
1092  * have the syntax used by "ovs-dpctl dump-flows".
1093  *
1094  * This command prints ACTIONS in a format that shows what happens for each
1095  * VLAN, independent of the order of the ACTIONS.  For example, there is more
1096  * than one way to output a packet on VLANs 9 and 11, but this command will
1097  * print the same output for any form.
1098  *
1099  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
1100  * so far the implementation only covers VLANs. */
1101 static void
1102 dpctl_normalize_actions(int argc, char *argv[])
1103 {
1104     struct simap port_names;
1105     struct ofpbuf keybuf;
1106     struct flow flow;
1107     struct ofpbuf odp_actions;
1108     struct hmap actions_per_flow;
1109     struct actions_for_flow **afs;
1110     struct actions_for_flow *af;
1111     struct nlattr *a;
1112     size_t n_afs;
1113     struct ds s;
1114     int left;
1115     int i;
1116
1117     ds_init(&s);
1118
1119     simap_init(&port_names);
1120     for (i = 3; i < argc; i++) {
1121         char name[16];
1122         int number;
1123
1124         if (ovs_scan(argv[i], "%15[^=]=%d", name, &number)) {
1125             uintptr_t n = number;
1126             simap_put(&port_names, name, n);
1127         } else {
1128             ovs_fatal(0, "%s: expected NAME=NUMBER", argv[i]);
1129         }
1130     }
1131
1132     /* Parse flow key. */
1133     ofpbuf_init(&keybuf, 0);
1134     run(odp_flow_from_string(argv[1], &port_names, &keybuf, NULL),
1135         "odp_flow_key_from_string");
1136
1137     ds_clear(&s);
1138     odp_flow_format(ofpbuf_data(&keybuf), ofpbuf_size(&keybuf), NULL, 0, NULL, &s, verbosity);
1139     printf("input flow: %s\n", ds_cstr(&s));
1140
1141     run(odp_flow_key_to_flow(ofpbuf_data(&keybuf), ofpbuf_size(&keybuf), &flow),
1142         "odp_flow_key_to_flow");
1143     ofpbuf_uninit(&keybuf);
1144
1145     /* Parse actions. */
1146     ofpbuf_init(&odp_actions, 0);
1147     run(odp_actions_from_string(argv[2], &port_names, &odp_actions),
1148         "odp_actions_from_string");
1149     simap_destroy(&port_names);
1150
1151     if (verbosity) {
1152         ds_clear(&s);
1153         format_odp_actions(&s, ofpbuf_data(&odp_actions), ofpbuf_size(&odp_actions));
1154         printf("input actions: %s\n", ds_cstr(&s));
1155     }
1156
1157     hmap_init(&actions_per_flow);
1158     NL_ATTR_FOR_EACH (a, left, ofpbuf_data(&odp_actions), ofpbuf_size(&odp_actions)) {
1159         const struct ovs_action_push_vlan *push;
1160         switch(nl_attr_type(a)) {
1161         case OVS_ACTION_ATTR_POP_VLAN:
1162             flow.vlan_tci = htons(0);
1163             continue;
1164
1165         case OVS_ACTION_ATTR_PUSH_VLAN:
1166             push = nl_attr_get_unspec(a, sizeof *push);
1167             flow.vlan_tci = push->vlan_tci;
1168             continue;
1169         }
1170
1171         af = get_actions_for_flow(&actions_per_flow, &flow);
1172         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
1173                           nl_attr_get(a), nl_attr_get_size(a));
1174     }
1175
1176     n_afs = hmap_count(&actions_per_flow);
1177     afs = xmalloc(n_afs * sizeof *afs);
1178     i = 0;
1179     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
1180         afs[i++] = af;
1181     }
1182     ovs_assert(i == n_afs);
1183
1184     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
1185
1186     for (i = 0; i < n_afs; i++) {
1187         const struct actions_for_flow *af = afs[i];
1188
1189         sort_output_actions(ofpbuf_data(&af->actions), ofpbuf_size(&af->actions));
1190
1191         if (af->flow.vlan_tci != htons(0)) {
1192             printf("vlan(vid=%"PRIu16",pcp=%d): ",
1193                    vlan_tci_to_vid(af->flow.vlan_tci),
1194                    vlan_tci_to_pcp(af->flow.vlan_tci));
1195         } else {
1196             printf("no vlan: ");
1197         }
1198
1199         if (eth_type_mpls(af->flow.dl_type)) {
1200             printf("mpls(label=%"PRIu32",tc=%d,ttl=%d): ",
1201                    mpls_lse_to_label(af->flow.mpls_lse[0]),
1202                    mpls_lse_to_tc(af->flow.mpls_lse[0]),
1203                    mpls_lse_to_ttl(af->flow.mpls_lse[0]));
1204         } else {
1205             printf("no mpls: ");
1206         }
1207
1208         ds_clear(&s);
1209         format_odp_actions(&s, ofpbuf_data(&af->actions), ofpbuf_size(&af->actions));
1210         puts(ds_cstr(&s));
1211     }
1212     ds_destroy(&s);
1213 }
1214
1215 static const struct command all_commands[] = {
1216     { "add-dp", 1, INT_MAX, dpctl_add_dp },
1217     { "del-dp", 1, 1, dpctl_del_dp },
1218     { "add-if", 2, INT_MAX, dpctl_add_if },
1219     { "del-if", 2, INT_MAX, dpctl_del_if },
1220     { "set-if", 2, INT_MAX, dpctl_set_if },
1221     { "dump-dps", 0, 0, dpctl_dump_dps },
1222     { "show", 0, INT_MAX, dpctl_show },
1223     { "dump-flows", 0, 2, dpctl_dump_flows },
1224     { "add-flow", 2, 3, dpctl_add_flow },
1225     { "mod-flow", 2, 3, dpctl_mod_flow },
1226     { "del-flow", 1, 2, dpctl_del_flow },
1227     { "del-flows", 0, 1, dpctl_del_flows },
1228     { "help", 0, INT_MAX, dpctl_help },
1229
1230     /* Undocumented commands for testing. */
1231     { "parse-actions", 1, INT_MAX, dpctl_parse_actions },
1232     { "normalize-actions", 2, INT_MAX, dpctl_normalize_actions },
1233
1234     { NULL, 0, 0, NULL },
1235 };
1236
1237 static const struct command *get_all_commands(void)
1238 {
1239     return all_commands;
1240 }