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