ovs-ofctl: Fix a typo in documentation.
[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 "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/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 dump;
746     const struct nlattr *key;
747     const struct nlattr *mask;
748     size_t actions_len;
749     struct dpif *dpif;
750     size_t key_len;
751     size_t mask_len;
752     struct ds ds;
753     char *name;
754
755     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
756     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
757     free(name);
758
759     ds_init(&ds);
760     dpif_flow_dump_start(&dump, dpif);
761     while (dpif_flow_dump_next(&dump, &key, &key_len,
762                                &mask, &mask_len,
763                                &actions, &actions_len, &stats)) {
764         ds_clear(&ds);
765         odp_flow_format(key, key_len, mask, mask_len, &ds, verbosity);
766         ds_put_cstr(&ds, ", ");
767
768         dpif_flow_stats_format(stats, &ds);
769         ds_put_cstr(&ds, ", actions:");
770         format_odp_actions(&ds, actions, actions_len);
771         printf("%s\n", ds_cstr(&ds));
772     }
773     dpif_flow_dump_done(&dump);
774     ds_destroy(&ds);
775     dpif_close(dpif);
776 }
777
778 static void
779 dpctl_put_flow(int argc, char *argv[], enum dpif_flow_put_flags flags)
780 {
781     const char *key_s = argv[argc - 2];
782     const char *actions_s = argv[argc - 1];
783     struct dpif_flow_stats stats;
784     struct ofpbuf actions;
785     struct ofpbuf key;
786     struct ofpbuf mask;
787     struct dpif *dpif;
788     struct ds s;
789     char *dp_name;
790
791     ds_init(&s);
792     ofpbuf_init(&key, 0);
793     ofpbuf_init(&mask, 0);
794     run(odp_flow_from_string(key_s, NULL, &key, &mask), "parsing flow key");
795
796     ofpbuf_init(&actions, 0);
797     run(odp_actions_from_string(actions_s, NULL, &actions), "parsing actions");
798
799     dp_name = argc == 4 ? xstrdup(argv[1]) : get_one_dp();
800     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
801     free(dp_name);
802
803     run(dpif_flow_put(dpif, flags,
804                       key.data, key.size,
805                       mask.size == 0 ? NULL : mask.data, mask.size,
806                       actions.data, actions.size,
807                       print_statistics ? &stats : NULL),
808         "updating flow table");
809
810     ofpbuf_uninit(&key);
811     ofpbuf_uninit(&mask);
812     ofpbuf_uninit(&actions);
813
814     if (print_statistics) {
815         struct ds s;
816
817         ds_init(&s);
818         dpif_flow_stats_format(&stats, &s);
819         puts(ds_cstr(&s));
820         ds_destroy(&s);
821     }
822 }
823
824 static void
825 dpctl_add_flow(int argc, char *argv[])
826 {
827     dpctl_put_flow(argc, argv, DPIF_FP_CREATE);
828 }
829
830 static void
831 dpctl_mod_flow(int argc OVS_UNUSED, char *argv[])
832 {
833     enum dpif_flow_put_flags flags;
834
835     flags = DPIF_FP_MODIFY;
836     if (may_create) {
837         flags |= DPIF_FP_CREATE;
838     }
839     if (zero_statistics) {
840         flags |= DPIF_FP_ZERO_STATS;
841     }
842
843     dpctl_put_flow(argc, argv, flags);
844 }
845
846 static void
847 dpctl_del_flow(int argc, char *argv[])
848 {
849     const char *key_s = argv[argc - 1];
850     struct dpif_flow_stats stats;
851     struct ofpbuf key;
852     struct ofpbuf mask; /* To be ignored. */
853     struct dpif *dpif;
854     char *dp_name;
855
856     ofpbuf_init(&key, 0);
857     ofpbuf_init(&mask, 0);
858     run(odp_flow_from_string(key_s, NULL, &key, &mask), "parsing flow key");
859
860     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp();
861     run(parsed_dpif_open(dp_name, false, &dpif), "opening datapath");
862     free(dp_name);
863
864     run(dpif_flow_del(dpif,
865                       key.data, key.size,
866                       print_statistics ? &stats : NULL), "deleting flow");
867
868     ofpbuf_uninit(&key);
869     ofpbuf_uninit(&mask);
870
871     if (print_statistics) {
872         struct ds s;
873
874         ds_init(&s);
875         dpif_flow_stats_format(&stats, &s);
876         puts(ds_cstr(&s));
877         ds_destroy(&s);
878     }
879 }
880
881 static void
882 dpctl_del_flows(int argc, char *argv[])
883 {
884     struct dpif *dpif;
885     char *name;
886
887     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
888     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
889     free(name);
890
891     run(dpif_flow_flush(dpif), "deleting all flows");
892     dpif_close(dpif);
893 }
894
895 static void
896 dpctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
897 {
898     usage();
899 }
900 \f
901 /* Undocumented commands for unit testing. */
902
903 static void
904 dpctl_parse_actions(int argc, char *argv[])
905 {
906     int i;
907
908     for (i = 1; i < argc; i++) {
909         struct ofpbuf actions;
910         struct ds s;
911
912         ofpbuf_init(&actions, 0);
913         run(odp_actions_from_string(argv[i], NULL, &actions),
914             "odp_actions_from_string");
915
916         ds_init(&s);
917         format_odp_actions(&s, actions.data, actions.size);
918         puts(ds_cstr(&s));
919         ds_destroy(&s);
920
921         ofpbuf_uninit(&actions);
922     }
923 }
924
925 struct actions_for_flow {
926     struct hmap_node hmap_node;
927     struct flow flow;
928     struct ofpbuf actions;
929 };
930
931 static struct actions_for_flow *
932 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
933 {
934     uint32_t hash = flow_hash(flow, 0);
935     struct actions_for_flow *af;
936
937     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
938         if (flow_equal(&af->flow, flow)) {
939             return af;
940         }
941     }
942
943     af = xmalloc(sizeof *af);
944     af->flow = *flow;
945     ofpbuf_init(&af->actions, 0);
946     hmap_insert(actions_per_flow, &af->hmap_node, hash);
947     return af;
948 }
949
950 static int
951 compare_actions_for_flow(const void *a_, const void *b_)
952 {
953     struct actions_for_flow *const *a = a_;
954     struct actions_for_flow *const *b = b_;
955
956     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
957 }
958
959 static int
960 compare_output_actions(const void *a_, const void *b_)
961 {
962     const struct nlattr *a = a_;
963     const struct nlattr *b = b_;
964     uint32_t a_port = nl_attr_get_u32(a);
965     uint32_t b_port = nl_attr_get_u32(b);
966
967     return a_port < b_port ? -1 : a_port > b_port;
968 }
969
970 static void
971 sort_output_actions__(struct nlattr *first, struct nlattr *end)
972 {
973     size_t bytes = (uint8_t *) end - (uint8_t *) first;
974     size_t n = bytes / NL_A_U32_SIZE;
975
976     ovs_assert(bytes % NL_A_U32_SIZE == 0);
977     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
978 }
979
980 static void
981 sort_output_actions(struct nlattr *actions, size_t length)
982 {
983     struct nlattr *first_output = NULL;
984     struct nlattr *a;
985     int left;
986
987     NL_ATTR_FOR_EACH (a, left, actions, length) {
988         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
989             if (!first_output) {
990                 first_output = a;
991             }
992         } else {
993             if (first_output) {
994                 sort_output_actions__(first_output, a);
995                 first_output = NULL;
996             }
997         }
998     }
999     if (first_output) {
1000         uint8_t *end = (uint8_t *) actions + length;
1001         sort_output_actions__(first_output,
1002                               ALIGNED_CAST(struct nlattr *, end));
1003     }
1004 }
1005
1006 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
1007  * have the syntax used by "ovs-dpctl dump-flows".
1008  *
1009  * This command prints ACTIONS in a format that shows what happens for each
1010  * VLAN, independent of the order of the ACTIONS.  For example, there is more
1011  * than one way to output a packet on VLANs 9 and 11, but this command will
1012  * print the same output for any form.
1013  *
1014  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
1015  * so far the implementation only covers VLANs. */
1016 static void
1017 dpctl_normalize_actions(int argc, char *argv[])
1018 {
1019     struct simap port_names;
1020     struct ofpbuf keybuf;
1021     struct flow flow;
1022     struct ofpbuf odp_actions;
1023     struct hmap actions_per_flow;
1024     struct actions_for_flow **afs;
1025     struct actions_for_flow *af;
1026     struct nlattr *a;
1027     size_t n_afs;
1028     struct ds s;
1029     int left;
1030     int i;
1031
1032     ds_init(&s);
1033
1034     simap_init(&port_names);
1035     for (i = 3; i < argc; i++) {
1036         char name[16];
1037         int number;
1038         int n = -1;
1039
1040         if (sscanf(argv[i], "%15[^=]=%d%n", name, &number, &n) > 0 && n > 0) {
1041             uintptr_t n = number;
1042             simap_put(&port_names, name, n);
1043         } else {
1044             ovs_fatal(0, "%s: expected NAME=NUMBER", argv[i]);
1045         }
1046     }
1047
1048     /* Parse flow key. */
1049     ofpbuf_init(&keybuf, 0);
1050     run(odp_flow_from_string(argv[1], &port_names, &keybuf, NULL),
1051         "odp_flow_key_from_string");
1052
1053     ds_clear(&s);
1054     odp_flow_format(keybuf.data, keybuf.size, NULL, 0, &s, verbosity);
1055     printf("input flow: %s\n", ds_cstr(&s));
1056
1057     run(odp_flow_key_to_flow(keybuf.data, keybuf.size, &flow),
1058         "odp_flow_key_to_flow");
1059     ofpbuf_uninit(&keybuf);
1060
1061     /* Parse actions. */
1062     ofpbuf_init(&odp_actions, 0);
1063     run(odp_actions_from_string(argv[2], &port_names, &odp_actions),
1064         "odp_actions_from_string");
1065     simap_destroy(&port_names);
1066
1067     if (verbosity) {
1068         ds_clear(&s);
1069         format_odp_actions(&s, odp_actions.data, odp_actions.size);
1070         printf("input actions: %s\n", ds_cstr(&s));
1071     }
1072
1073     hmap_init(&actions_per_flow);
1074     NL_ATTR_FOR_EACH (a, left, odp_actions.data, odp_actions.size) {
1075         const struct ovs_action_push_vlan *push;
1076         switch(nl_attr_type(a)) {
1077         case OVS_ACTION_ATTR_POP_VLAN:
1078             flow.vlan_tci = htons(0);
1079             continue;
1080
1081         case OVS_ACTION_ATTR_PUSH_VLAN:
1082             push = nl_attr_get_unspec(a, sizeof *push);
1083             flow.vlan_tci = push->vlan_tci;
1084             continue;
1085         }
1086
1087         af = get_actions_for_flow(&actions_per_flow, &flow);
1088         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
1089                           nl_attr_get(a), nl_attr_get_size(a));
1090     }
1091
1092     n_afs = hmap_count(&actions_per_flow);
1093     afs = xmalloc(n_afs * sizeof *afs);
1094     i = 0;
1095     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
1096         afs[i++] = af;
1097     }
1098     ovs_assert(i == n_afs);
1099
1100     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
1101
1102     for (i = 0; i < n_afs; i++) {
1103         const struct actions_for_flow *af = afs[i];
1104
1105         sort_output_actions(af->actions.data, af->actions.size);
1106
1107         if (af->flow.vlan_tci != htons(0)) {
1108             printf("vlan(vid=%"PRIu16",pcp=%d): ",
1109                    vlan_tci_to_vid(af->flow.vlan_tci),
1110                    vlan_tci_to_pcp(af->flow.vlan_tci));
1111         } else {
1112             printf("no vlan: ");
1113         }
1114
1115         if (af->flow.mpls_depth) {
1116             printf("mpls(label=%"PRIu32",tc=%d,ttl=%d): ",
1117                    mpls_lse_to_label(af->flow.mpls_lse),
1118                    mpls_lse_to_tc(af->flow.mpls_lse),
1119                    mpls_lse_to_ttl(af->flow.mpls_lse));
1120         } else {
1121             printf("no mpls: ");
1122         }
1123
1124         ds_clear(&s);
1125         format_odp_actions(&s, af->actions.data, af->actions.size);
1126         puts(ds_cstr(&s));
1127     }
1128     ds_destroy(&s);
1129 }
1130
1131 static const struct command all_commands[] = {
1132     { "add-dp", 1, INT_MAX, dpctl_add_dp },
1133     { "del-dp", 1, 1, dpctl_del_dp },
1134     { "add-if", 2, INT_MAX, dpctl_add_if },
1135     { "del-if", 2, INT_MAX, dpctl_del_if },
1136     { "set-if", 2, INT_MAX, dpctl_set_if },
1137     { "dump-dps", 0, 0, dpctl_dump_dps },
1138     { "show", 0, INT_MAX, dpctl_show },
1139     { "dump-flows", 0, 1, dpctl_dump_flows },
1140     { "add-flow", 2, 3, dpctl_add_flow },
1141     { "mod-flow", 2, 3, dpctl_mod_flow },
1142     { "del-flow", 1, 2, dpctl_del_flow },
1143     { "del-flows", 0, 1, dpctl_del_flows },
1144     { "help", 0, INT_MAX, dpctl_help },
1145
1146     /* Undocumented commands for testing. */
1147     { "parse-actions", 1, INT_MAX, dpctl_parse_actions },
1148     { "normalize-actions", 2, INT_MAX, dpctl_normalize_actions },
1149
1150     { NULL, 0, 0, NULL },
1151 };
1152
1153 static const struct command *get_all_commands(void)
1154 {
1155     return all_commands;
1156 }