dpif-linux: collect and display mega flow mask stats
[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             ovs_error(error, "%s: failed to configure network device", name);
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             ovs_error(error, "%s: failed to configure network device", name);
463             goto next;
464         }
465
466 next:
467         free(type);
468         netdev_close(netdev);
469         if (error) {
470             failure = true;
471         }
472     }
473     dpif_close(dpif);
474     if (failure) {
475         exit(EXIT_FAILURE);
476     }
477 }
478
479 static bool
480 get_port_number(struct dpif *dpif, const char *name, odp_port_t *port)
481 {
482     struct dpif_port dpif_port;
483
484     if (!dpif_port_query_by_name(dpif, name, &dpif_port)) {
485         *port = dpif_port.port_no;
486         dpif_port_destroy(&dpif_port);
487         return true;
488     } else {
489         ovs_error(0, "no port named %s", name);
490         return false;
491     }
492 }
493
494 static void
495 dpctl_del_if(int argc OVS_UNUSED, char *argv[])
496 {
497     bool failure = false;
498     struct dpif *dpif;
499     int i;
500
501     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
502     for (i = 2; i < argc; i++) {
503         const char *name = argv[i];
504         odp_port_t port;
505         int error;
506
507         if (!name[strspn(name, "0123456789")]) {
508             port = u32_to_odp(atoi(name));
509         } else if (!get_port_number(dpif, name, &port)) {
510             failure = true;
511             continue;
512         }
513
514         error = dpif_port_del(dpif, port);
515         if (error) {
516             ovs_error(error, "deleting port %s from %s failed", name, argv[1]);
517             failure = true;
518         }
519     }
520     dpif_close(dpif);
521     if (failure) {
522         exit(EXIT_FAILURE);
523     }
524 }
525
526 static void
527 print_stat(const char *leader, uint64_t value)
528 {
529     fputs(leader, stdout);
530     if (value != UINT64_MAX) {
531         printf("%"PRIu64, value);
532     } else {
533         putchar('?');
534     }
535 }
536
537 static void
538 print_human_size(uint64_t value)
539 {
540     if (value == UINT64_MAX) {
541         /* Nothing to do. */
542     } else if (value >= 1024ULL * 1024 * 1024 * 1024) {
543         printf(" (%.1f TiB)", value / (1024.0 * 1024 * 1024 * 1024));
544     } else if (value >= 1024ULL * 1024 * 1024) {
545         printf(" (%.1f GiB)", value / (1024.0 * 1024 * 1024));
546     } else if (value >= 1024ULL * 1024) {
547         printf(" (%.1f MiB)", value / (1024.0 * 1024));
548     } else if (value >= 1024) {
549         printf(" (%.1f KiB)", value / 1024.0);
550     }
551 }
552
553 static void
554 show_dpif(struct dpif *dpif)
555 {
556     struct dpif_port_dump dump;
557     struct dpif_port dpif_port;
558     struct dpif_dp_stats stats;
559     struct netdev *netdev;
560
561     printf("%s:\n", dpif_name(dpif));
562     if (!dpif_get_dp_stats(dpif, &stats)) {
563         printf("\tlookups: hit:%"PRIu64" missed:%"PRIu64" lost:%"PRIu64"\n"
564                "\tflows: %"PRIu64"\n",
565                stats.n_hit, stats.n_missed, stats.n_lost, stats.n_flows);
566         if (stats.n_masks != UINT64_MAX) {
567             uint64_t n_pkts = stats.n_hit + stats.n_missed;
568             double avg = n_pkts ? (double) stats.n_mask_hit / n_pkts : 0.0;
569
570             printf("\tmasks: hit:%"PRIu64" total:%"PRIu64" hit/pkt:%.2f\n",
571                    stats.n_mask_hit, stats.n_masks, avg);
572         }
573     }
574
575     DPIF_PORT_FOR_EACH (&dpif_port, &dump, dpif) {
576         printf("\tport %u: %s", dpif_port.port_no, dpif_port.name);
577
578         if (strcmp(dpif_port.type, "system")) {
579             int error;
580
581             printf (" (%s", dpif_port.type);
582
583             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
584             if (!error) {
585                 struct smap config;
586
587                 smap_init(&config);
588                 error = netdev_get_config(netdev, &config);
589                 if (!error) {
590                     const struct smap_node **nodes;
591                     size_t i;
592
593                     nodes = smap_sort(&config);
594                     for (i = 0; i < smap_count(&config); i++) {
595                         const struct smap_node *node = nodes[i];
596                         printf("%c %s=%s", i ? ',' : ':', node->key,
597                                node->value);
598                     }
599                     free(nodes);
600                 } else {
601                     printf(", could not retrieve configuration (%s)",
602                            ovs_strerror(error));
603                 }
604                 smap_destroy(&config);
605
606                 netdev_close(netdev);
607             } else {
608                 printf(": open failed (%s)", ovs_strerror(error));
609             }
610             putchar(')');
611         }
612         putchar('\n');
613
614         if (print_statistics) {
615             struct netdev_stats s;
616             int error;
617
618             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
619             if (error) {
620                 printf(", open failed (%s)", ovs_strerror(error));
621                 continue;
622             }
623             error = netdev_get_stats(netdev, &s);
624             if (error) {
625                 printf(", could not retrieve stats (%s)", ovs_strerror(error));
626                 continue;
627             }
628
629             netdev_close(netdev);
630             print_stat("\t\tRX packets:", s.rx_packets);
631             print_stat(" errors:", s.rx_errors);
632             print_stat(" dropped:", s.rx_dropped);
633             print_stat(" overruns:", s.rx_over_errors);
634             print_stat(" frame:", s.rx_frame_errors);
635             printf("\n");
636
637             print_stat("\t\tTX packets:", s.tx_packets);
638             print_stat(" errors:", s.tx_errors);
639             print_stat(" dropped:", s.tx_dropped);
640             print_stat(" aborted:", s.tx_aborted_errors);
641             print_stat(" carrier:", s.tx_carrier_errors);
642             printf("\n");
643
644             print_stat("\t\tcollisions:", s.collisions);
645             printf("\n");
646
647             print_stat("\t\tRX bytes:", s.rx_bytes);
648             print_human_size(s.rx_bytes);
649             print_stat("  TX bytes:", s.tx_bytes);
650             print_human_size(s.tx_bytes);
651             printf("\n");
652         }
653     }
654     dpif_close(dpif);
655 }
656
657 static void
658 dpctl_show(int argc, char *argv[])
659 {
660     bool failure = false;
661     if (argc > 1) {
662         int i;
663         for (i = 1; i < argc; i++) {
664             const char *name = argv[i];
665             struct dpif *dpif;
666             int error;
667
668             error = parsed_dpif_open(name, false, &dpif);
669             if (!error) {
670                 show_dpif(dpif);
671             } else {
672                 ovs_error(error, "opening datapath %s failed", name);
673                 failure = true;
674             }
675         }
676     } else {
677         struct sset types;
678         const char *type;
679
680         sset_init(&types);
681         dp_enumerate_types(&types);
682         SSET_FOR_EACH (type, &types) {
683             struct sset names;
684             const char *name;
685
686             sset_init(&names);
687             if (dp_enumerate_names(type, &names)) {
688                 failure = true;
689                 continue;
690             }
691             SSET_FOR_EACH (name, &names) {
692                 struct dpif *dpif;
693                 int error;
694
695                 error = dpif_open(name, type, &dpif);
696                 if (!error) {
697                     show_dpif(dpif);
698                 } else {
699                     ovs_error(error, "opening datapath %s failed", name);
700                     failure = true;
701                 }
702             }
703             sset_destroy(&names);
704         }
705         sset_destroy(&types);
706     }
707     if (failure) {
708         exit(EXIT_FAILURE);
709     }
710 }
711
712 static void
713 dpctl_dump_dps(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
714 {
715     struct sset dpif_names, dpif_types;
716     const char *type;
717     int error = 0;
718
719     sset_init(&dpif_names);
720     sset_init(&dpif_types);
721     dp_enumerate_types(&dpif_types);
722
723     SSET_FOR_EACH (type, &dpif_types) {
724         const char *name;
725         int retval;
726
727         retval = dp_enumerate_names(type, &dpif_names);
728         if (retval) {
729             error = retval;
730         }
731
732         SSET_FOR_EACH (name, &dpif_names) {
733             struct dpif *dpif;
734             if (!dpif_open(name, type, &dpif)) {
735                 printf("%s\n", dpif_name(dpif));
736                 dpif_close(dpif);
737             }
738         }
739     }
740
741     sset_destroy(&dpif_names);
742     sset_destroy(&dpif_types);
743     if (error) {
744         exit(EXIT_FAILURE);
745     }
746 }
747
748 static void
749 dpctl_dump_flows(int argc, char *argv[])
750 {
751     const struct dpif_flow_stats *stats;
752     const struct nlattr *actions;
753     struct dpif_flow_dump flow_dump;
754     const struct nlattr *key;
755     const struct nlattr *mask;
756     struct dpif_port dpif_port;
757     struct dpif_port_dump port_dump;
758     struct hmap portno_names;
759     struct simap names_portno;
760     size_t actions_len;
761     struct dpif *dpif;
762     size_t key_len;
763     size_t mask_len;
764     struct ds ds;
765     char *name, *error, *filter = NULL;
766     struct flow flow_filter;
767     struct flow_wildcards wc_filter;
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         error = parse_ofp_exact_flow(&flow_filter, &wc_filter.masks, filter,
787                                      &names_portno);
788         if (error) {
789             ovs_fatal(0, "Failed to parse filter (%s)", error);
790         }
791     }
792
793     ds_init(&ds);
794     dpif_flow_dump_start(&flow_dump, dpif);
795     while (dpif_flow_dump_next(&flow_dump, &key, &key_len,
796                                &mask, &mask_len,
797                                &actions, &actions_len, &stats)) {
798         if (filter) {
799             struct flow flow;
800             struct flow_wildcards wc;
801             struct match match, match_filter;
802             struct minimatch minimatch;
803
804             odp_flow_key_to_flow(key, key_len, &flow);
805             odp_flow_key_to_mask(mask, mask_len, &wc.masks, &flow);
806             match_init(&match, &flow, &wc);
807
808             match_init(&match_filter, &flow_filter, &wc);
809             match_init(&match_filter, &match_filter.flow, &wc_filter);
810             minimatch_init(&minimatch, &match_filter);
811
812             if (!minimatch_matches_flow(&minimatch, &match.flow)) {
813                 minimatch_destroy(&minimatch);
814                 continue;
815             }
816             minimatch_destroy(&minimatch);
817         }
818         ds_clear(&ds);
819         odp_flow_format(key, key_len, mask, mask_len, &portno_names, &ds,
820                         verbosity);
821         ds_put_cstr(&ds, ", ");
822
823         dpif_flow_stats_format(stats, &ds);
824         ds_put_cstr(&ds, ", actions:");
825         format_odp_actions(&ds, actions, actions_len);
826         printf("%s\n", ds_cstr(&ds));
827     }
828     dpif_flow_dump_done(&flow_dump);
829
830     free(filter);
831     odp_portno_names_destroy(&portno_names);
832     hmap_destroy(&portno_names);
833     simap_destroy(&names_portno);
834     ds_destroy(&ds);
835     dpif_close(dpif);
836 }
837
838 static void
839 dpctl_put_flow(int argc, char *argv[], enum dpif_flow_put_flags flags)
840 {
841     const char *key_s = argv[argc - 2];
842     const char *actions_s = argv[argc - 1];
843     struct dpif_flow_stats stats;
844     struct dpif_port dpif_port;
845     struct dpif_port_dump port_dump;
846     struct ofpbuf actions;
847     struct ofpbuf key;
848     struct ofpbuf mask;
849     struct dpif *dpif;
850     struct ds s;
851     char *dp_name;
852     struct simap port_names;
853
854     dp_name = argc == 4 ? xstrdup(argv[1]) : get_one_dp();
855     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
856     free(dp_name);
857
858
859     simap_init(&port_names);
860     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
861         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
862     }
863
864     ds_init(&s);
865     ofpbuf_init(&key, 0);
866     ofpbuf_init(&mask, 0);
867     run(odp_flow_from_string(key_s, &port_names, &key, &mask),
868         "parsing flow key");
869
870     simap_destroy(&port_names);
871
872     ofpbuf_init(&actions, 0);
873     run(odp_actions_from_string(actions_s, NULL, &actions), "parsing actions");
874
875     run(dpif_flow_put(dpif, flags,
876                       key.data, key.size,
877                       mask.size == 0 ? NULL : mask.data, mask.size,
878                       actions.data, actions.size,
879                       print_statistics ? &stats : NULL),
880         "updating flow table");
881
882     ofpbuf_uninit(&key);
883     ofpbuf_uninit(&mask);
884     ofpbuf_uninit(&actions);
885
886     if (print_statistics) {
887         struct ds s;
888
889         ds_init(&s);
890         dpif_flow_stats_format(&stats, &s);
891         puts(ds_cstr(&s));
892         ds_destroy(&s);
893     }
894 }
895
896 static void
897 dpctl_add_flow(int argc, char *argv[])
898 {
899     dpctl_put_flow(argc, argv, DPIF_FP_CREATE);
900 }
901
902 static void
903 dpctl_mod_flow(int argc OVS_UNUSED, char *argv[])
904 {
905     enum dpif_flow_put_flags flags;
906
907     flags = DPIF_FP_MODIFY;
908     if (may_create) {
909         flags |= DPIF_FP_CREATE;
910     }
911     if (zero_statistics) {
912         flags |= DPIF_FP_ZERO_STATS;
913     }
914
915     dpctl_put_flow(argc, argv, flags);
916 }
917
918 static void
919 dpctl_del_flow(int argc, char *argv[])
920 {
921     const char *key_s = argv[argc - 1];
922     struct dpif_flow_stats stats;
923     struct dpif_port dpif_port;
924     struct dpif_port_dump port_dump;
925     struct ofpbuf key;
926     struct ofpbuf mask; /* To be ignored. */
927     struct dpif *dpif;
928     char *dp_name;
929     struct simap port_names;
930
931     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp();
932     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
933     free(dp_name);
934
935     simap_init(&port_names);
936     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
937         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
938     }
939
940     ofpbuf_init(&key, 0);
941     ofpbuf_init(&mask, 0);
942     run(odp_flow_from_string(key_s, &port_names, &key, &mask), "parsing flow key");
943
944     run(dpif_flow_del(dpif,
945                       key.data, key.size,
946                       print_statistics ? &stats : NULL), "deleting flow");
947
948     simap_destroy(&port_names);
949     ofpbuf_uninit(&key);
950     ofpbuf_uninit(&mask);
951
952     if (print_statistics) {
953         struct ds s;
954
955         ds_init(&s);
956         dpif_flow_stats_format(&stats, &s);
957         puts(ds_cstr(&s));
958         ds_destroy(&s);
959     }
960 }
961
962 static void
963 dpctl_del_flows(int argc, char *argv[])
964 {
965     struct dpif *dpif;
966     char *name;
967
968     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
969     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
970     free(name);
971
972     run(dpif_flow_flush(dpif), "deleting all flows");
973     dpif_close(dpif);
974 }
975
976 static void
977 dpctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
978 {
979     usage();
980 }
981 \f
982 /* Undocumented commands for unit testing. */
983
984 static void
985 dpctl_parse_actions(int argc, char *argv[])
986 {
987     int i;
988
989     for (i = 1; i < argc; i++) {
990         struct ofpbuf actions;
991         struct ds s;
992
993         ofpbuf_init(&actions, 0);
994         run(odp_actions_from_string(argv[i], NULL, &actions),
995             "odp_actions_from_string");
996
997         ds_init(&s);
998         format_odp_actions(&s, actions.data, actions.size);
999         puts(ds_cstr(&s));
1000         ds_destroy(&s);
1001
1002         ofpbuf_uninit(&actions);
1003     }
1004 }
1005
1006 struct actions_for_flow {
1007     struct hmap_node hmap_node;
1008     struct flow flow;
1009     struct ofpbuf actions;
1010 };
1011
1012 static struct actions_for_flow *
1013 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
1014 {
1015     uint32_t hash = flow_hash(flow, 0);
1016     struct actions_for_flow *af;
1017
1018     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
1019         if (flow_equal(&af->flow, flow)) {
1020             return af;
1021         }
1022     }
1023
1024     af = xmalloc(sizeof *af);
1025     af->flow = *flow;
1026     ofpbuf_init(&af->actions, 0);
1027     hmap_insert(actions_per_flow, &af->hmap_node, hash);
1028     return af;
1029 }
1030
1031 static int
1032 compare_actions_for_flow(const void *a_, const void *b_)
1033 {
1034     struct actions_for_flow *const *a = a_;
1035     struct actions_for_flow *const *b = b_;
1036
1037     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
1038 }
1039
1040 static int
1041 compare_output_actions(const void *a_, const void *b_)
1042 {
1043     const struct nlattr *a = a_;
1044     const struct nlattr *b = b_;
1045     uint32_t a_port = nl_attr_get_u32(a);
1046     uint32_t b_port = nl_attr_get_u32(b);
1047
1048     return a_port < b_port ? -1 : a_port > b_port;
1049 }
1050
1051 static void
1052 sort_output_actions__(struct nlattr *first, struct nlattr *end)
1053 {
1054     size_t bytes = (uint8_t *) end - (uint8_t *) first;
1055     size_t n = bytes / NL_A_U32_SIZE;
1056
1057     ovs_assert(bytes % NL_A_U32_SIZE == 0);
1058     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
1059 }
1060
1061 static void
1062 sort_output_actions(struct nlattr *actions, size_t length)
1063 {
1064     struct nlattr *first_output = NULL;
1065     struct nlattr *a;
1066     int left;
1067
1068     NL_ATTR_FOR_EACH (a, left, actions, length) {
1069         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
1070             if (!first_output) {
1071                 first_output = a;
1072             }
1073         } else {
1074             if (first_output) {
1075                 sort_output_actions__(first_output, a);
1076                 first_output = NULL;
1077             }
1078         }
1079     }
1080     if (first_output) {
1081         uint8_t *end = (uint8_t *) actions + length;
1082         sort_output_actions__(first_output,
1083                               ALIGNED_CAST(struct nlattr *, end));
1084     }
1085 }
1086
1087 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
1088  * have the syntax used by "ovs-dpctl dump-flows".
1089  *
1090  * This command prints ACTIONS in a format that shows what happens for each
1091  * VLAN, independent of the order of the ACTIONS.  For example, there is more
1092  * than one way to output a packet on VLANs 9 and 11, but this command will
1093  * print the same output for any form.
1094  *
1095  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
1096  * so far the implementation only covers VLANs. */
1097 static void
1098 dpctl_normalize_actions(int argc, char *argv[])
1099 {
1100     struct simap port_names;
1101     struct ofpbuf keybuf;
1102     struct flow flow;
1103     struct ofpbuf odp_actions;
1104     struct hmap actions_per_flow;
1105     struct actions_for_flow **afs;
1106     struct actions_for_flow *af;
1107     struct nlattr *a;
1108     size_t n_afs;
1109     struct ds s;
1110     int left;
1111     int i;
1112
1113     ds_init(&s);
1114
1115     simap_init(&port_names);
1116     for (i = 3; i < argc; i++) {
1117         char name[16];
1118         int number;
1119         int n = -1;
1120
1121         if (sscanf(argv[i], "%15[^=]=%d%n", name, &number, &n) > 0 && n > 0) {
1122             uintptr_t n = number;
1123             simap_put(&port_names, name, n);
1124         } else {
1125             ovs_fatal(0, "%s: expected NAME=NUMBER", argv[i]);
1126         }
1127     }
1128
1129     /* Parse flow key. */
1130     ofpbuf_init(&keybuf, 0);
1131     run(odp_flow_from_string(argv[1], &port_names, &keybuf, NULL),
1132         "odp_flow_key_from_string");
1133
1134     ds_clear(&s);
1135     odp_flow_format(keybuf.data, keybuf.size, NULL, 0, NULL, &s, verbosity);
1136     printf("input flow: %s\n", ds_cstr(&s));
1137
1138     run(odp_flow_key_to_flow(keybuf.data, keybuf.size, &flow),
1139         "odp_flow_key_to_flow");
1140     ofpbuf_uninit(&keybuf);
1141
1142     /* Parse actions. */
1143     ofpbuf_init(&odp_actions, 0);
1144     run(odp_actions_from_string(argv[2], &port_names, &odp_actions),
1145         "odp_actions_from_string");
1146     simap_destroy(&port_names);
1147
1148     if (verbosity) {
1149         ds_clear(&s);
1150         format_odp_actions(&s, odp_actions.data, odp_actions.size);
1151         printf("input actions: %s\n", ds_cstr(&s));
1152     }
1153
1154     hmap_init(&actions_per_flow);
1155     NL_ATTR_FOR_EACH (a, left, odp_actions.data, odp_actions.size) {
1156         const struct ovs_action_push_vlan *push;
1157         switch(nl_attr_type(a)) {
1158         case OVS_ACTION_ATTR_POP_VLAN:
1159             flow.vlan_tci = htons(0);
1160             continue;
1161
1162         case OVS_ACTION_ATTR_PUSH_VLAN:
1163             push = nl_attr_get_unspec(a, sizeof *push);
1164             flow.vlan_tci = push->vlan_tci;
1165             continue;
1166         }
1167
1168         af = get_actions_for_flow(&actions_per_flow, &flow);
1169         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
1170                           nl_attr_get(a), nl_attr_get_size(a));
1171     }
1172
1173     n_afs = hmap_count(&actions_per_flow);
1174     afs = xmalloc(n_afs * sizeof *afs);
1175     i = 0;
1176     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
1177         afs[i++] = af;
1178     }
1179     ovs_assert(i == n_afs);
1180
1181     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
1182
1183     for (i = 0; i < n_afs; i++) {
1184         const struct actions_for_flow *af = afs[i];
1185
1186         sort_output_actions(af->actions.data, af->actions.size);
1187
1188         if (af->flow.vlan_tci != htons(0)) {
1189             printf("vlan(vid=%"PRIu16",pcp=%d): ",
1190                    vlan_tci_to_vid(af->flow.vlan_tci),
1191                    vlan_tci_to_pcp(af->flow.vlan_tci));
1192         } else {
1193             printf("no vlan: ");
1194         }
1195
1196         if (eth_type_mpls(af->flow.dl_type)) {
1197             printf("mpls(label=%"PRIu32",tc=%d,ttl=%d): ",
1198                    mpls_lse_to_label(af->flow.mpls_lse),
1199                    mpls_lse_to_tc(af->flow.mpls_lse),
1200                    mpls_lse_to_ttl(af->flow.mpls_lse));
1201         } else {
1202             printf("no mpls: ");
1203         }
1204
1205         ds_clear(&s);
1206         format_odp_actions(&s, af->actions.data, af->actions.size);
1207         puts(ds_cstr(&s));
1208     }
1209     ds_destroy(&s);
1210 }
1211
1212 static const struct command all_commands[] = {
1213     { "add-dp", 1, INT_MAX, dpctl_add_dp },
1214     { "del-dp", 1, 1, dpctl_del_dp },
1215     { "add-if", 2, INT_MAX, dpctl_add_if },
1216     { "del-if", 2, INT_MAX, dpctl_del_if },
1217     { "set-if", 2, INT_MAX, dpctl_set_if },
1218     { "dump-dps", 0, 0, dpctl_dump_dps },
1219     { "show", 0, INT_MAX, dpctl_show },
1220     { "dump-flows", 0, 2, dpctl_dump_flows },
1221     { "add-flow", 2, 3, dpctl_add_flow },
1222     { "mod-flow", 2, 3, dpctl_mod_flow },
1223     { "del-flow", 1, 2, dpctl_del_flow },
1224     { "del-flows", 0, 1, dpctl_del_flows },
1225     { "help", 0, INT_MAX, dpctl_help },
1226
1227     /* Undocumented commands for testing. */
1228     { "parse-actions", 1, INT_MAX, dpctl_parse_actions },
1229     { "normalize-actions", 2, INT_MAX, dpctl_normalize_actions },
1230
1231     { NULL, 0, 0, NULL },
1232 };
1233
1234 static const struct command *get_all_commands(void)
1235 {
1236     return all_commands;
1237 }