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