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