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