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