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