netdev-dpdk: fix mbuf leaks
[cascardo/ovs.git] / lib / dpctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 <inttypes.h>
21 #include <sys/socket.h>
22 #include <net/if.h>
23 #include <netinet/in.h>
24 #include <stdarg.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28
29 #include "command-line.h"
30 #include "compiler.h"
31 #include "ct-dpif.h"
32 #include "dirs.h"
33 #include "dpctl.h"
34 #include "dpif.h"
35 #include "dynamic-string.h"
36 #include "flow.h"
37 #include "match.h"
38 #include "netdev.h"
39 #include "netdev-dpdk.h"
40 #include "netlink.h"
41 #include "odp-util.h"
42 #include "ofp-parse.h"
43 #include "ofpbuf.h"
44 #include "ovs-numa.h"
45 #include "packets.h"
46 #include "shash.h"
47 #include "simap.h"
48 #include "smap.h"
49 #include "sset.h"
50 #include "timeval.h"
51 #include "unixctl.h"
52 #include "util.h"
53
54 typedef int dpctl_command_handler(int argc, const char *argv[],
55                                   struct dpctl_params *);
56 struct dpctl_command {
57     const char *name;
58     const char *usage;
59     int min_args;
60     int max_args;
61     dpctl_command_handler *handler;
62 };
63 static const struct dpctl_command *get_all_dpctl_commands(void);
64 static void dpctl_print(struct dpctl_params *dpctl_p, const char *fmt, ...)
65     OVS_PRINTF_FORMAT(2, 3);
66 static void dpctl_error(struct dpctl_params* dpctl_p, int err_no,
67                         const char *fmt, ...)
68     OVS_PRINTF_FORMAT(3, 4);
69
70 static void
71 dpctl_puts(struct dpctl_params *dpctl_p, bool error, const char *string)
72 {
73     dpctl_p->output(dpctl_p->aux, error, string);
74 }
75
76 static void
77 dpctl_print(struct dpctl_params *dpctl_p, const char *fmt, ...)
78 {
79     char *string;
80     va_list args;
81
82     va_start(args, fmt);
83     string = xvasprintf(fmt, args);
84     va_end(args);
85
86     dpctl_puts(dpctl_p, false, string);
87     free(string);
88 }
89
90 static void
91 dpctl_error(struct dpctl_params* dpctl_p, int err_no, const char *fmt, ...)
92 {
93     const char *subprogram_name = get_subprogram_name();
94     struct ds ds = DS_EMPTY_INITIALIZER;
95     int save_errno = errno;
96     va_list args;
97
98
99     if (subprogram_name[0]) {
100         ds_put_format(&ds, "%s(%s): ", program_name,subprogram_name);
101     } else {
102         ds_put_format(&ds, "%s: ", program_name);
103     }
104
105     va_start(args, fmt);
106     ds_put_format_valist(&ds, fmt, args);
107     va_end(args);
108
109     if (err_no != 0) {
110         ds_put_format(&ds, " (%s)", ovs_retval_to_string(err_no));
111     }
112     ds_put_cstr(&ds, "\n");
113
114     dpctl_puts(dpctl_p, true, ds_cstr(&ds));
115
116     ds_destroy(&ds);
117
118     errno = save_errno;
119 }
120 \f
121 static int dpctl_add_if(int argc, const char *argv[], struct dpctl_params *);
122
123 static int
124 if_up(struct netdev *netdev)
125 {
126     return netdev_turn_flags_on(netdev, NETDEV_UP, NULL);
127 }
128
129 /* Retrieve the name of the datapath if exactly one exists.  The caller
130  * is responsible for freeing the returned string.  If there is not one
131  * datapath, aborts with an error message. */
132 static char *
133 get_one_dp(struct dpctl_params *dpctl_p)
134 {
135     struct sset types;
136     const char *type;
137     char *dp_name = NULL;
138     size_t count = 0;
139
140     sset_init(&types);
141     dp_enumerate_types(&types);
142     SSET_FOR_EACH (type, &types) {
143         struct sset names;
144
145         sset_init(&names);
146         if (!dp_enumerate_names(type, &names)) {
147             count += sset_count(&names);
148             if (!dp_name && count == 1) {
149                 dp_name = xasprintf("%s@%s", type, SSET_FIRST(&names));
150             }
151         }
152         sset_destroy(&names);
153     }
154     sset_destroy(&types);
155
156     if (!count) {
157         dpctl_error(dpctl_p, 0, "no datapaths exist");
158     } else if (count > 1) {
159         dpctl_error(dpctl_p, 0, "multiple datapaths, specify one");
160         free(dp_name);
161         dp_name = NULL;
162     }
163
164     return dp_name;
165 }
166
167 static int
168 parsed_dpif_open(const char *arg_, bool create, struct dpif **dpifp)
169 {
170     int result;
171     char *name, *type;
172
173     dp_parse_name(arg_, &name, &type);
174
175     if (create) {
176         result = dpif_create(name, type, dpifp);
177     } else {
178         result = dpif_open(name, type, dpifp);
179     }
180
181     free(name);
182     free(type);
183     return result;
184 }
185
186 static int
187 dpctl_add_dp(int argc, const char *argv[],
188              struct dpctl_params *dpctl_p)
189 {
190     struct dpif *dpif;
191     int error;
192
193     error = parsed_dpif_open(argv[1], true, &dpif);
194     if (error) {
195         dpctl_error(dpctl_p, error, "add_dp");
196         return error;
197     }
198     dpif_close(dpif);
199     if (argc > 2) {
200         error = dpctl_add_if(argc, argv, dpctl_p);
201     }
202     return error;
203 }
204
205 static int
206 dpctl_del_dp(int argc OVS_UNUSED, const char *argv[],
207              struct dpctl_params *dpctl_p)
208 {
209     struct dpif *dpif;
210     int error;
211
212     error = parsed_dpif_open(argv[1], false, &dpif);
213     if (error) {
214         dpctl_error(dpctl_p, error, "opening datapath");
215         return error;
216     }
217     error = dpif_delete(dpif);
218     if (error) {
219         dpctl_error(dpctl_p, error, "del_dp");
220     }
221
222     dpif_close(dpif);
223     return error;
224 }
225
226 static int
227 dpctl_add_if(int argc OVS_UNUSED, const char *argv[],
228              struct dpctl_params *dpctl_p)
229 {
230     struct dpif *dpif;
231     int i, error, lasterror = 0;
232
233     error = parsed_dpif_open(argv[1], false, &dpif);
234     if (error) {
235         dpctl_error(dpctl_p, error, "opening datapath");
236         return error;
237     }
238     for (i = 2; i < argc; i++) {
239         const char *name, *type;
240         char *save_ptr = NULL, *argcopy;
241         struct netdev *netdev = NULL;
242         struct smap args;
243         odp_port_t port_no = ODPP_NONE;
244         char *option;
245
246         argcopy = xstrdup(argv[i]);
247         name = strtok_r(argcopy, ",", &save_ptr);
248         type = "system";
249
250         if (!name) {
251             dpctl_error(dpctl_p, 0, "%s is not a valid network device name",
252                         argv[i]);
253             error = EINVAL;
254             goto next;
255         }
256
257         smap_init(&args);
258         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
259             char *save_ptr_2 = NULL;
260             char *key, *value;
261
262             key = strtok_r(option, "=", &save_ptr_2);
263             value = strtok_r(NULL, "", &save_ptr_2);
264             if (!value) {
265                 value = "";
266             }
267
268             if (!strcmp(key, "type")) {
269                 type = value;
270             } else if (!strcmp(key, "port_no")) {
271                 port_no = u32_to_odp(atoi(value));
272             } else if (!smap_add_once(&args, key, value)) {
273                 dpctl_error(dpctl_p, 0, "duplicate \"%s\" option", key);
274             }
275         }
276
277         error = netdev_open(name, type, &netdev);
278         if (error) {
279             dpctl_error(dpctl_p, error, "%s: failed to open network device",
280                         name);
281             goto next_destroy_args;
282         }
283
284         error = netdev_set_config(netdev, &args, NULL);
285         if (error) {
286             goto next_destroy_args;
287         }
288
289         error = dpif_port_add(dpif, netdev, &port_no);
290         if (error) {
291             dpctl_error(dpctl_p, error, "adding %s to %s failed", name,
292                         argv[1]);
293             goto next_destroy_args;
294         }
295
296         error = if_up(netdev);
297         if (error) {
298             dpctl_error(dpctl_p, error, "%s: failed bringing interface up",
299                         name);
300         }
301
302 next_destroy_args:
303         netdev_close(netdev);
304         smap_destroy(&args);
305 next:
306         free(argcopy);
307         if (error) {
308             lasterror = error;
309         }
310     }
311     dpif_close(dpif);
312
313     return lasterror;
314 }
315
316 static int
317 dpctl_set_if(int argc, const char *argv[], struct dpctl_params *dpctl_p)
318 {
319     struct dpif *dpif;
320     int i, error, lasterror = 0;
321
322     error = parsed_dpif_open(argv[1], false, &dpif);
323     if (error) {
324         dpctl_error(dpctl_p, error, "opening datapath");
325         return error;
326     }
327     for (i = 2; i < argc; i++) {
328         struct netdev *netdev = NULL;
329         struct dpif_port dpif_port;
330         char *save_ptr = NULL;
331         char *type = NULL;
332         char *argcopy;
333         const char *name;
334         struct smap args;
335         odp_port_t port_no;
336         char *option;
337         int error = 0;
338
339         argcopy = xstrdup(argv[i]);
340         name = strtok_r(argcopy, ",", &save_ptr);
341         if (!name) {
342             dpctl_error(dpctl_p, 0, "%s is not a valid network device name",
343                         argv[i]);
344             goto next;
345         }
346
347         /* Get the port's type from the datapath. */
348         error = dpif_port_query_by_name(dpif, name, &dpif_port);
349         if (error) {
350             dpctl_error(dpctl_p, error, "%s: failed to query port in %s", name,
351                         argv[1]);
352             goto next;
353         }
354         type = xstrdup(dpif_port.type);
355         port_no = dpif_port.port_no;
356         dpif_port_destroy(&dpif_port);
357
358         /* Retrieve its existing configuration. */
359         error = netdev_open(name, type, &netdev);
360         if (error) {
361             dpctl_error(dpctl_p, error, "%s: failed to open network device",
362                         name);
363             goto next;
364         }
365
366         smap_init(&args);
367         error = netdev_get_config(netdev, &args);
368         if (error) {
369             dpctl_error(dpctl_p, error, "%s: failed to fetch configuration",
370                         name);
371             goto next_destroy_args;
372         }
373
374         /* Parse changes to configuration. */
375         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
376             char *save_ptr_2 = NULL;
377             char *key, *value;
378
379             key = strtok_r(option, "=", &save_ptr_2);
380             value = strtok_r(NULL, "", &save_ptr_2);
381             if (!value) {
382                 value = "";
383             }
384
385             if (!strcmp(key, "type")) {
386                 if (strcmp(value, type)) {
387                     dpctl_error(dpctl_p, 0,
388                                 "%s: can't change type from %s to %s",
389                                  name, type, value);
390                     error = EINVAL;
391                     goto next_destroy_args;
392                 }
393             } else if (!strcmp(key, "port_no")) {
394                 if (port_no != u32_to_odp(atoi(value))) {
395                     dpctl_error(dpctl_p, 0, "%s: can't change port number from"
396                               " %"PRIu32" to %d", name, port_no, atoi(value));
397                     error = EINVAL;
398                     goto next_destroy_args;
399                 }
400             } else if (value[0] == '\0') {
401                 smap_remove(&args, key);
402             } else {
403                 smap_replace(&args, key, value);
404             }
405         }
406
407         /* Update configuration. */
408         char *err_s = NULL;
409         error = netdev_set_config(netdev, &args, &err_s);
410         if (err_s || error) {
411             dpctl_error(dpctl_p, error, "%s",
412                         err_s ? err_s : "Error updating configuration");
413             free(err_s);
414         }
415         if (error) {
416             goto next_destroy_args;
417         }
418
419 next_destroy_args:
420         smap_destroy(&args);
421 next:
422         netdev_close(netdev);
423         free(type);
424         free(argcopy);
425         if (error) {
426             lasterror = error;
427         }
428     }
429     dpif_close(dpif);
430
431     return lasterror;
432 }
433
434 static bool
435 get_port_number(struct dpif *dpif, const char *name, odp_port_t *port,
436                 struct dpctl_params *dpctl_p)
437 {
438     struct dpif_port dpif_port;
439
440     if (!dpif_port_query_by_name(dpif, name, &dpif_port)) {
441         *port = dpif_port.port_no;
442         dpif_port_destroy(&dpif_port);
443         return true;
444     } else {
445         dpctl_error(dpctl_p, 0, "no port named %s", name);
446         return false;
447     }
448 }
449
450 static int
451 dpctl_del_if(int argc, const char *argv[], struct dpctl_params *dpctl_p)
452 {
453     struct dpif *dpif;
454     int i, error, lasterror = 0;
455
456     error = parsed_dpif_open(argv[1], false, &dpif);
457     if (error) {
458         dpctl_error(dpctl_p, error, "opening datapath");
459         return error;
460     }
461     for (i = 2; i < argc; i++) {
462         const char *name = argv[i];
463         odp_port_t port;
464
465         if (!name[strspn(name, "0123456789")]) {
466             port = u32_to_odp(atoi(name));
467         } else if (!get_port_number(dpif, name, &port, dpctl_p)) {
468             lasterror = ENOENT;
469             continue;
470         }
471
472         error = dpif_port_del(dpif, port);
473         if (error) {
474             dpctl_error(dpctl_p, error, "deleting port %s from %s failed",
475                         name, argv[1]);
476             lasterror = error;
477         }
478     }
479     dpif_close(dpif);
480     return lasterror;
481 }
482
483 static void
484 print_stat(struct dpctl_params *dpctl_p, const char *leader, uint64_t value)
485 {
486     dpctl_print(dpctl_p, "%s", leader);
487     if (value != UINT64_MAX) {
488         dpctl_print(dpctl_p, "%"PRIu64, value);
489     } else {
490         dpctl_print(dpctl_p, "?");
491     }
492 }
493
494 static void
495 print_human_size(struct dpctl_params *dpctl_p, uint64_t value)
496 {
497     if (value == UINT64_MAX) {
498         /* Nothing to do. */
499     } else if (value >= 1024ULL * 1024 * 1024 * 1024) {
500         dpctl_print(dpctl_p, " (%.1f TiB)",
501                     value / (1024.0 * 1024 * 1024 * 1024));
502     } else if (value >= 1024ULL * 1024 * 1024) {
503         dpctl_print(dpctl_p, " (%.1f GiB)", value / (1024.0 * 1024 * 1024));
504     } else if (value >= 1024ULL * 1024) {
505         dpctl_print(dpctl_p, " (%.1f MiB)", value / (1024.0 * 1024));
506     } else if (value >= 1024) {
507         dpctl_print(dpctl_p, " (%.1f KiB)", value / 1024.0);
508     }
509 }
510
511 static void
512 show_dpif(struct dpif *dpif, struct dpctl_params *dpctl_p)
513 {
514     struct dpif_port_dump dump;
515     struct dpif_port dpif_port;
516     struct dpif_dp_stats stats;
517     struct netdev *netdev;
518
519     dpctl_print(dpctl_p, "%s:\n", dpif_name(dpif));
520     if (!dpif_get_dp_stats(dpif, &stats)) {
521         dpctl_print(dpctl_p, "\tlookups: hit:%"PRIu64" missed:%"PRIu64
522                              " lost:%"PRIu64"\n\tflows: %"PRIu64"\n",
523                     stats.n_hit, stats.n_missed, stats.n_lost, stats.n_flows);
524         if (stats.n_masks != UINT32_MAX) {
525             uint64_t n_pkts = stats.n_hit + stats.n_missed;
526             double avg = n_pkts ? (double) stats.n_mask_hit / n_pkts : 0.0;
527
528             dpctl_print(dpctl_p, "\tmasks: hit:%"PRIu64" total:%"PRIu32
529                                  " hit/pkt:%.2f\n",
530                         stats.n_mask_hit, stats.n_masks, avg);
531         }
532     }
533
534     DPIF_PORT_FOR_EACH (&dpif_port, &dump, dpif) {
535         dpctl_print(dpctl_p, "\tport %u: %s",
536                     dpif_port.port_no, dpif_port.name);
537
538         if (strcmp(dpif_port.type, "system")) {
539             int error;
540
541             dpctl_print(dpctl_p, " (%s", dpif_port.type);
542
543             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
544             if (!error) {
545                 struct smap config;
546
547                 smap_init(&config);
548                 error = netdev_get_config(netdev, &config);
549                 if (!error) {
550                     const struct smap_node **nodes;
551                     size_t i;
552
553                     nodes = smap_sort(&config);
554                     for (i = 0; i < smap_count(&config); i++) {
555                         const struct smap_node *node = nodes[i];
556                         dpctl_print(dpctl_p, "%c %s=%s", i ? ',' : ':',
557                                     node->key, node->value);
558                     }
559                     free(nodes);
560                 } else {
561                     dpctl_print(dpctl_p, ", could not retrieve configuration "
562                                          "(%s)",  ovs_strerror(error));
563                 }
564                 smap_destroy(&config);
565
566                 netdev_close(netdev);
567             } else {
568                 dpctl_print(dpctl_p, ": open failed (%s)",
569                             ovs_strerror(error));
570             }
571             dpctl_print(dpctl_p, ")");
572         }
573         dpctl_print(dpctl_p, "\n");
574
575         if (dpctl_p->print_statistics) {
576             struct netdev_stats s;
577             int error;
578
579             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
580             if (error) {
581                 dpctl_print(dpctl_p, ", open failed (%s)",
582                             ovs_strerror(error));
583                 continue;
584             }
585             error = netdev_get_stats(netdev, &s);
586             if (!error) {
587                 netdev_close(netdev);
588                 print_stat(dpctl_p, "\t\tRX packets:", s.rx_packets);
589                 print_stat(dpctl_p, " errors:", s.rx_errors);
590                 print_stat(dpctl_p, " dropped:", s.rx_dropped);
591                 print_stat(dpctl_p, " overruns:", s.rx_over_errors);
592                 print_stat(dpctl_p, " frame:", s.rx_frame_errors);
593                 dpctl_print(dpctl_p, "\n");
594
595                 print_stat(dpctl_p, "\t\tTX packets:", s.tx_packets);
596                 print_stat(dpctl_p, " errors:", s.tx_errors);
597                 print_stat(dpctl_p, " dropped:", s.tx_dropped);
598                 print_stat(dpctl_p, " aborted:", s.tx_aborted_errors);
599                 print_stat(dpctl_p, " carrier:", s.tx_carrier_errors);
600                 dpctl_print(dpctl_p, "\n");
601
602                 print_stat(dpctl_p, "\t\tcollisions:", s.collisions);
603                 dpctl_print(dpctl_p, "\n");
604
605                 print_stat(dpctl_p, "\t\tRX bytes:", s.rx_bytes);
606                 print_human_size(dpctl_p, s.rx_bytes);
607                 print_stat(dpctl_p, "  TX bytes:", s.tx_bytes);
608                 print_human_size(dpctl_p, s.tx_bytes);
609                 dpctl_print(dpctl_p, "\n");
610             } else {
611                 dpctl_print(dpctl_p, ", could not retrieve stats (%s)",
612                             ovs_strerror(error));
613             }
614         }
615     }
616 }
617
618 typedef void (*dps_for_each_cb)(struct dpif *, struct dpctl_params *);
619
620 static int
621 dps_for_each(struct dpctl_params *dpctl_p, dps_for_each_cb cb)
622 {
623     struct sset dpif_names = SSET_INITIALIZER(&dpif_names),
624                 dpif_types = SSET_INITIALIZER(&dpif_types);
625     int error, openerror = 0, enumerror = 0;
626     const char *type, *name;
627     bool at_least_one = false;
628
629     dp_enumerate_types(&dpif_types);
630
631     SSET_FOR_EACH (type, &dpif_types) {
632         error = dp_enumerate_names(type, &dpif_names);
633         if (error) {
634             enumerror = error;
635         }
636
637         SSET_FOR_EACH (name, &dpif_names) {
638             struct dpif *dpif;
639
640             at_least_one = true;
641             error = dpif_open(name, type, &dpif);
642             if (!error) {
643                 cb(dpif, dpctl_p);
644                 dpif_close(dpif);
645             } else {
646                 openerror = error;
647                 dpctl_error(dpctl_p, error, "opening datapath %s failed",
648                             name);
649             }
650         }
651     }
652
653     sset_destroy(&dpif_names);
654     sset_destroy(&dpif_types);
655
656     /* If there has been an error while opening a datapath it should be
657      * reported.  Otherwise, we want to ignore the errors generated by
658      * dp_enumerate_names() if at least one datapath has been discovered,
659      * because they're not interesting for the user.  This happens, for
660      * example, if OVS is using a userspace datapath and the kernel module
661      * is not loaded. */
662     if (openerror) {
663         return openerror;
664     } else {
665         return at_least_one ? 0 : enumerror;
666     }
667 }
668
669 static int
670 dpctl_show(int argc, const char *argv[], struct dpctl_params *dpctl_p)
671 {
672     int error, lasterror = 0;
673     if (argc > 1) {
674         int i;
675         for (i = 1; i < argc; i++) {
676             const char *name = argv[i];
677             struct dpif *dpif;
678
679             error = parsed_dpif_open(name, false, &dpif);
680             if (!error) {
681                 show_dpif(dpif, dpctl_p);
682                 dpif_close(dpif);
683             } else {
684                 dpctl_error(dpctl_p, error, "opening datapath %s failed",
685                             name);
686                 lasterror = error;
687             }
688         }
689     } else {
690         lasterror = dps_for_each(dpctl_p, show_dpif);
691     }
692
693     return lasterror;
694 }
695
696 static void
697 dump_cb(struct dpif *dpif, struct dpctl_params *dpctl_p)
698 {
699     dpctl_print(dpctl_p, "%s\n", dpif_name(dpif));
700 }
701
702 static int
703 dpctl_dump_dps(int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
704                struct dpctl_params *dpctl_p)
705 {
706     return dps_for_each(dpctl_p, dump_cb);
707 }
708
709 static void
710 format_dpif_flow(struct ds *ds, const struct dpif_flow *f, struct hmap *ports,
711                  struct dpctl_params *dpctl_p)
712 {
713     if (dpctl_p->verbosity && f->ufid_present) {
714         odp_format_ufid(&f->ufid, ds);
715         ds_put_cstr(ds, ", ");
716     }
717     odp_flow_format(f->key, f->key_len, f->mask, f->mask_len, ports, ds,
718                     dpctl_p->verbosity);
719     ds_put_cstr(ds, ", ");
720
721     dpif_flow_stats_format(&f->stats, ds);
722     ds_put_cstr(ds, ", actions:");
723     format_odp_actions(ds, f->actions, f->actions_len);
724 }
725
726 static int
727 dpctl_dump_flows(int argc, const char *argv[], struct dpctl_params *dpctl_p)
728 {
729     struct dpif *dpif;
730     struct ds ds;
731     char *name;
732
733     char *filter = NULL;
734     struct flow flow_filter;
735     struct flow_wildcards wc_filter;
736
737     struct dpif_port_dump port_dump;
738     struct dpif_port dpif_port;
739     struct hmap portno_names;
740     struct simap names_portno;
741
742     struct dpif_flow_dump_thread *flow_dump_thread;
743     struct dpif_flow_dump *flow_dump;
744     struct dpif_flow f;
745     int pmd_id = PMD_ID_NULL;
746     int error;
747
748     if (argc > 1 && !strncmp(argv[argc - 1], "filter=", 7)) {
749         filter = xstrdup(argv[--argc] + 7);
750     }
751     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
752     if (!name) {
753         error = EINVAL;
754         goto out_freefilter;
755     }
756
757     error = parsed_dpif_open(name, false, &dpif);
758     free(name);
759     if (error) {
760         dpctl_error(dpctl_p, error, "opening datapath");
761         goto out_freefilter;
762     }
763
764
765     hmap_init(&portno_names);
766     simap_init(&names_portno);
767     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
768         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
769         simap_put(&names_portno, dpif_port.name,
770                   odp_to_u32(dpif_port.port_no));
771     }
772
773     if (filter) {
774         char *err = parse_ofp_exact_flow(&flow_filter, &wc_filter.masks,
775                                          filter, &names_portno);
776         if (err) {
777             dpctl_error(dpctl_p, 0, "Failed to parse filter (%s)", err);
778             error = EINVAL;
779             goto out_dpifclose;
780         }
781     }
782
783     /* Make sure that these values are different. PMD_ID_NULL means that the
784      * pmd is unspecified (e.g. because the datapath doesn't have different
785      * pmd threads), while NON_PMD_CORE_ID refers to every non pmd threads
786      * in the userspace datapath */
787     BUILD_ASSERT(PMD_ID_NULL != NON_PMD_CORE_ID);
788
789     ds_init(&ds);
790     flow_dump = dpif_flow_dump_create(dpif, false);
791     flow_dump_thread = dpif_flow_dump_thread_create(flow_dump);
792     while (dpif_flow_dump_next(flow_dump_thread, &f, 1)) {
793         if (filter) {
794             struct flow flow;
795             struct flow_wildcards wc;
796             struct match match, match_filter;
797             struct minimatch minimatch;
798
799             odp_flow_key_to_flow(f.key, f.key_len, &flow);
800             odp_flow_key_to_mask(f.mask, f.mask_len, f.key, f.key_len,
801                                  &wc, &flow);
802             match_init(&match, &flow, &wc);
803
804             match_init(&match_filter, &flow_filter, &wc);
805             match_init(&match_filter, &match_filter.flow, &wc_filter);
806             minimatch_init(&minimatch, &match_filter);
807
808             if (!minimatch_matches_flow(&minimatch, &match.flow)) {
809                 minimatch_destroy(&minimatch);
810                 continue;
811             }
812             minimatch_destroy(&minimatch);
813         }
814         ds_clear(&ds);
815         /* If 'pmd_id' is specified, overlapping flows could be dumped from
816          * different pmd threads.  So, separates dumps from different pmds
817          * by printing a title line. */
818         if (pmd_id != f.pmd_id) {
819             if (f.pmd_id == NON_PMD_CORE_ID) {
820                 ds_put_format(&ds, "flow-dump from non-dpdk interfaces:\n");
821             } else {
822                 ds_put_format(&ds, "flow-dump from pmd on cpu core: %d\n",
823                               f.pmd_id);
824             }
825             pmd_id = f.pmd_id;
826         }
827         format_dpif_flow(&ds, &f, &portno_names, dpctl_p);
828         dpctl_print(dpctl_p, "%s\n", ds_cstr(&ds));
829     }
830     dpif_flow_dump_thread_destroy(flow_dump_thread);
831     error = dpif_flow_dump_destroy(flow_dump);
832
833     if (error) {
834         dpctl_error(dpctl_p, error, "Failed to dump flows from datapath");
835     }
836     ds_destroy(&ds);
837
838 out_dpifclose:
839     odp_portno_names_destroy(&portno_names);
840     simap_destroy(&names_portno);
841     hmap_destroy(&portno_names);
842     dpif_close(dpif);
843 out_freefilter:
844     free(filter);
845     return error;
846 }
847
848 /* Extracts the in_port from the parsed keys, and returns the reference
849  * to the 'struct netdev *' of the dpif port.  On error, returns NULL.
850  * Users must call 'netdev_close()' after finish using the returned
851  * reference. */
852 static struct netdev *
853 get_in_port_netdev_from_key(struct dpif *dpif, const struct ofpbuf *key)
854 {
855     const struct nlattr *in_port_nla;
856     struct netdev *dev = NULL;
857
858     in_port_nla = nl_attr_find(key, 0, OVS_KEY_ATTR_IN_PORT);
859     if (in_port_nla) {
860         struct dpif_port dpif_port;
861         odp_port_t port_no;
862         int error;
863
864         port_no = ODP_PORT_C(nl_attr_get_u32(in_port_nla));
865         error = dpif_port_query_by_number(dpif, port_no, &dpif_port);
866         if (error) {
867             goto out;
868         }
869
870         netdev_open(dpif_port.name, dpif_port.type, &dev);
871         dpif_port_destroy(&dpif_port);
872     }
873
874 out:
875     return dev;
876 }
877
878 static int
879 dpctl_put_flow(int argc, const char *argv[], enum dpif_flow_put_flags flags,
880                struct dpctl_params *dpctl_p)
881 {
882     const char *key_s = argv[argc - 2];
883     const char *actions_s = argv[argc - 1];
884     struct netdev *in_port_netdev = NULL;
885     struct dpif_flow_stats stats;
886     struct dpif_port dpif_port;
887     struct dpif_port_dump port_dump;
888     struct ofpbuf actions;
889     struct ofpbuf key;
890     struct ofpbuf mask;
891     struct dpif *dpif;
892     ovs_u128 ufid;
893     bool ufid_present;
894     char *dp_name;
895     struct simap port_names;
896     int n, error;
897
898     dp_name = argc == 4 ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
899     if (!dp_name) {
900         return EINVAL;
901     }
902     error = parsed_dpif_open(dp_name, false, &dpif);
903     free(dp_name);
904     if (error) {
905         dpctl_error(dpctl_p, error, "opening datapath");
906         return error;
907     }
908
909     ufid_present = false;
910     n = odp_ufid_from_string(key_s, &ufid);
911     if (n < 0) {
912         dpctl_error(dpctl_p, -n, "parsing flow ufid");
913         return -n;
914     } else if (n) {
915         key_s += n;
916         ufid_present = true;
917     }
918
919     simap_init(&port_names);
920     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
921         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
922     }
923
924     ofpbuf_init(&key, 0);
925     ofpbuf_init(&mask, 0);
926     error = odp_flow_from_string(key_s, &port_names, &key, &mask);
927     simap_destroy(&port_names);
928     if (error) {
929         dpctl_error(dpctl_p, error, "parsing flow key");
930         goto out_freekeymask;
931     }
932
933     ofpbuf_init(&actions, 0);
934     error = odp_actions_from_string(actions_s, NULL, &actions);
935     if (error) {
936         dpctl_error(dpctl_p, error, "parsing actions");
937         goto out_freeactions;
938     }
939
940     /* For DPDK interface, applies the operation to all pmd threads
941      * on the same numa node. */
942     in_port_netdev = get_in_port_netdev_from_key(dpif, &key);
943     if (in_port_netdev && netdev_is_pmd(in_port_netdev)) {
944         int numa_id;
945
946         numa_id = netdev_get_numa_id(in_port_netdev);
947         if (ovs_numa_numa_id_is_valid(numa_id)) {
948             struct ovs_numa_dump *dump = ovs_numa_dump_cores_on_numa(numa_id);
949             struct ovs_numa_info *iter;
950
951             FOR_EACH_CORE_ON_NUMA (iter, dump) {
952                 if (ovs_numa_core_is_pinned(iter->core_id)) {
953                     error = dpif_flow_put(dpif, flags,
954                                           key.data, key.size,
955                                           mask.size == 0 ? NULL : mask.data,
956                                           mask.size, actions.data,
957                                           actions.size, ufid_present ? &ufid : NULL,
958                                           iter->core_id, dpctl_p->print_statistics ? &stats : NULL);
959                 }
960             }
961             ovs_numa_dump_destroy(dump);
962         } else {
963             error = EINVAL;
964         }
965     } else {
966         error = dpif_flow_put(dpif, flags,
967                               key.data, key.size,
968                               mask.size == 0 ? NULL : mask.data,
969                               mask.size, actions.data,
970                               actions.size, ufid_present ? &ufid : NULL,
971                               PMD_ID_NULL, dpctl_p->print_statistics ? &stats : NULL);
972     }
973     if (error) {
974         dpctl_error(dpctl_p, error, "updating flow table");
975         goto out_freeactions;
976     }
977
978     if (dpctl_p->print_statistics) {
979         struct ds s;
980
981         ds_init(&s);
982         dpif_flow_stats_format(&stats, &s);
983         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
984         ds_destroy(&s);
985     }
986
987 out_freeactions:
988     ofpbuf_uninit(&actions);
989 out_freekeymask:
990     ofpbuf_uninit(&mask);
991     ofpbuf_uninit(&key);
992     dpif_close(dpif);
993     netdev_close(in_port_netdev);
994     return error;
995 }
996
997 static int
998 dpctl_add_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
999 {
1000     return dpctl_put_flow(argc, argv, DPIF_FP_CREATE, dpctl_p);
1001 }
1002
1003 static int
1004 dpctl_mod_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1005 {
1006     enum dpif_flow_put_flags flags;
1007
1008     flags = DPIF_FP_MODIFY;
1009     if (dpctl_p->may_create) {
1010         flags |= DPIF_FP_CREATE;
1011     }
1012     if (dpctl_p->zero_statistics) {
1013         flags |= DPIF_FP_ZERO_STATS;
1014     }
1015
1016     return dpctl_put_flow(argc, argv, flags, dpctl_p);
1017 }
1018
1019 static int
1020 dpctl_get_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1021 {
1022     const char *key_s = argv[argc - 1];
1023     struct dpif_flow flow;
1024     struct dpif_port dpif_port;
1025     struct dpif_port_dump port_dump;
1026     struct dpif *dpif;
1027     char *dp_name;
1028     struct hmap portno_names;
1029     ovs_u128 ufid;
1030     struct ofpbuf buf;
1031     uint64_t stub[DPIF_FLOW_BUFSIZE / 8];
1032     struct ds ds;
1033     int n, error;
1034
1035     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1036     if (!dp_name) {
1037         return EINVAL;
1038     }
1039     error = parsed_dpif_open(dp_name, false, &dpif);
1040     free(dp_name);
1041     if (error) {
1042         dpctl_error(dpctl_p, error, "opening datapath");
1043         return error;
1044     }
1045
1046     ofpbuf_use_stub(&buf, &stub, sizeof stub);
1047     hmap_init(&portno_names);
1048     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
1049         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
1050     }
1051
1052     n = odp_ufid_from_string(key_s, &ufid);
1053     if (n <= 0) {
1054         dpctl_error(dpctl_p, -n, "parsing flow ufid");
1055         goto out;
1056     }
1057
1058     /* Does not work for DPDK, since do not know which 'pmd' to apply the
1059      * operation.  So, just uses PMD_ID_NULL. */
1060     error = dpif_flow_get(dpif, NULL, 0, &ufid, PMD_ID_NULL, &buf, &flow);
1061     if (error) {
1062         dpctl_error(dpctl_p, error, "getting flow");
1063         goto out;
1064     }
1065
1066     ds_init(&ds);
1067     format_dpif_flow(&ds, &flow, &portno_names, dpctl_p);
1068     dpctl_print(dpctl_p, "%s\n", ds_cstr(&ds));
1069     ds_destroy(&ds);
1070
1071 out:
1072     odp_portno_names_destroy(&portno_names);
1073     hmap_destroy(&portno_names);
1074     ofpbuf_uninit(&buf);
1075     dpif_close(dpif);
1076     return error;
1077 }
1078
1079 static int
1080 dpctl_del_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1081 {
1082     const char *key_s = argv[argc - 1];
1083     struct netdev *in_port_netdev = NULL;
1084     struct dpif_flow_stats stats;
1085     struct dpif_port dpif_port;
1086     struct dpif_port_dump port_dump;
1087     struct ofpbuf key;
1088     struct ofpbuf mask; /* To be ignored. */
1089     struct dpif *dpif;
1090     ovs_u128 ufid;
1091     bool ufid_present;
1092     char *dp_name;
1093     struct simap port_names;
1094     int n, error;
1095
1096     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1097     if (!dp_name) {
1098         return EINVAL;
1099     }
1100     error = parsed_dpif_open(dp_name, false, &dpif);
1101     free(dp_name);
1102     if (error) {
1103         dpctl_error(dpctl_p, error, "opening datapath");
1104         return error;
1105     }
1106
1107     ufid_present = false;
1108     n = odp_ufid_from_string(key_s, &ufid);
1109     if (n < 0) {
1110         dpctl_error(dpctl_p, -n, "parsing flow ufid");
1111         return -n;
1112     } else if (n) {
1113         key_s += n;
1114         ufid_present = true;
1115     }
1116
1117     simap_init(&port_names);
1118     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
1119         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
1120     }
1121
1122     ofpbuf_init(&key, 0);
1123     ofpbuf_init(&mask, 0);
1124
1125     error = odp_flow_from_string(key_s, &port_names, &key, &mask);
1126     if (error) {
1127         dpctl_error(dpctl_p, error, "parsing flow key");
1128         goto out;
1129     }
1130
1131     /* For DPDK interface, applies the operation to all pmd threads
1132      * on the same numa node. */
1133     in_port_netdev = get_in_port_netdev_from_key(dpif, &key);
1134     if (in_port_netdev && netdev_is_pmd(in_port_netdev)) {
1135         int numa_id;
1136
1137         numa_id = netdev_get_numa_id(in_port_netdev);
1138         if (ovs_numa_numa_id_is_valid(numa_id)) {
1139             struct ovs_numa_dump *dump = ovs_numa_dump_cores_on_numa(numa_id);
1140             struct ovs_numa_info *iter;
1141
1142             FOR_EACH_CORE_ON_NUMA (iter, dump) {
1143                 if (ovs_numa_core_is_pinned(iter->core_id)) {
1144                     error = dpif_flow_del(dpif, key.data,
1145                                           key.size, ufid_present ? &ufid : NULL,
1146                                           iter->core_id, dpctl_p->print_statistics ? &stats : NULL);
1147                 }
1148             }
1149             ovs_numa_dump_destroy(dump);
1150         } else {
1151             error = EINVAL;
1152         }
1153     } else {
1154         error = dpif_flow_del(dpif, key.data, key.size,
1155                               ufid_present ? &ufid : NULL, PMD_ID_NULL,
1156                               dpctl_p->print_statistics ? &stats : NULL);
1157     }
1158     if (error) {
1159         dpctl_error(dpctl_p, error, "deleting flow");
1160         if (error == ENOENT && !ufid_present) {
1161             struct ds s;
1162
1163             ds_init(&s);
1164             ds_put_format(&s, "Perhaps you need to specify a UFID?");
1165             dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1166             ds_destroy(&s);
1167         }
1168         goto out;
1169     }
1170
1171     if (dpctl_p->print_statistics) {
1172         struct ds s;
1173
1174         ds_init(&s);
1175         dpif_flow_stats_format(&stats, &s);
1176         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1177         ds_destroy(&s);
1178     }
1179
1180 out:
1181     ofpbuf_uninit(&mask);
1182     ofpbuf_uninit(&key);
1183     simap_destroy(&port_names);
1184     dpif_close(dpif);
1185     netdev_close(in_port_netdev);
1186     return error;
1187 }
1188
1189 static int
1190 dpctl_del_flows(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1191 {
1192     struct dpif *dpif;
1193     char *name;
1194     int error;
1195
1196     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1197     if (!name) {
1198         return EINVAL;
1199     }
1200     error = parsed_dpif_open(name, false, &dpif);
1201     free(name);
1202     if (error) {
1203         dpctl_error(dpctl_p, error, "opening datapath");
1204         return error;
1205     }
1206
1207     error = dpif_flow_flush(dpif);
1208     if (error) {
1209         dpctl_error(dpctl_p, error, "deleting all flows");
1210     }
1211     dpif_close(dpif);
1212     return error;
1213 }
1214
1215 static int
1216 dpctl_help(int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
1217            struct dpctl_params *dpctl_p)
1218 {
1219     if (dpctl_p->usage) {
1220         dpctl_p->usage(dpctl_p->aux);
1221     }
1222
1223     return 0;
1224 }
1225
1226 static int
1227 dpctl_list_commands(int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
1228                     struct dpctl_params *dpctl_p)
1229 {
1230     struct ds ds = DS_EMPTY_INITIALIZER;
1231     const struct dpctl_command *commands = get_all_dpctl_commands();
1232
1233     ds_put_cstr(&ds, "The available commands are:\n");
1234     for (; commands->name; commands++) {
1235         const struct dpctl_command *c = commands;
1236
1237         ds_put_format(&ds, "  %s%-23s %s\n", dpctl_p->is_appctl ? "dpctl/" : "",
1238                       c->name, c->usage);
1239     }
1240     dpctl_puts(dpctl_p, false, ds.string);
1241     ds_destroy(&ds);
1242
1243     return 0;
1244 }
1245
1246 static int
1247 dpctl_dump_conntrack(int argc, const char *argv[],
1248                      struct dpctl_params *dpctl_p)
1249 {
1250     struct ct_dpif_dump_state *dump;
1251     struct ct_dpif_entry cte;
1252     uint16_t zone, *pzone = NULL;
1253     struct dpif *dpif;
1254     char *name;
1255     int error;
1256
1257     if (argc > 1 && ovs_scan(argv[argc - 1], "zone=%"SCNu16, &zone)) {
1258         pzone = &zone;
1259         argc--;
1260     }
1261     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1262     if (!name) {
1263         return EINVAL;
1264     }
1265     error = parsed_dpif_open(name, false, &dpif);
1266     free(name);
1267     if (error) {
1268         dpctl_error(dpctl_p, error, "opening datapath");
1269         return error;
1270     }
1271
1272     error = ct_dpif_dump_start(dpif, &dump, pzone);
1273     if (error) {
1274         dpctl_error(dpctl_p, error, "starting conntrack dump");
1275         dpif_close(dpif);
1276         return error;
1277     }
1278
1279     while (!ct_dpif_dump_next(dump, &cte)) {
1280         struct ds s = DS_EMPTY_INITIALIZER;
1281
1282         ct_dpif_format_entry(&cte, &s, dpctl_p->verbosity,
1283                              dpctl_p->print_statistics);
1284         ct_dpif_entry_uninit(&cte);
1285
1286         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1287         ds_destroy(&s);
1288     }
1289     ct_dpif_dump_done(dump);
1290     dpif_close(dpif);
1291     return error;
1292 }
1293
1294 static int
1295 dpctl_flush_conntrack(int argc, const char *argv[],
1296                       struct dpctl_params *dpctl_p)
1297 {
1298     struct dpif *dpif;
1299     uint16_t zone, *pzone = NULL;
1300     char *name;
1301     int error;
1302
1303     if (argc > 1 && ovs_scan(argv[argc - 1], "zone=%"SCNu16, &zone)) {
1304         pzone = &zone;
1305         argc--;
1306     }
1307     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1308     if (!name) {
1309         return EINVAL;
1310     }
1311     error = parsed_dpif_open(name, false, &dpif);
1312     free(name);
1313     if (error) {
1314         dpctl_error(dpctl_p, error, "opening datapath");
1315         return error;
1316     }
1317
1318     error = ct_dpif_flush(dpif, pzone);
1319
1320     dpif_close(dpif);
1321     return error;
1322 }
1323 \f
1324 /* Undocumented commands for unit testing. */
1325
1326 static int
1327 dpctl_parse_actions(int argc, const char *argv[], struct dpctl_params* dpctl_p)
1328 {
1329     int i, error = 0;
1330
1331     for (i = 1; i < argc; i++) {
1332         struct ofpbuf actions;
1333         struct ds s;
1334
1335         ofpbuf_init(&actions, 0);
1336         error = odp_actions_from_string(argv[i], NULL, &actions);
1337
1338         if (error) {
1339             ofpbuf_uninit(&actions);
1340             dpctl_error(dpctl_p, error, "odp_actions_from_string");
1341             return error;
1342         }
1343
1344         ds_init(&s);
1345         format_odp_actions(&s, actions.data, actions.size);
1346         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1347         ds_destroy(&s);
1348
1349         ofpbuf_uninit(&actions);
1350     }
1351
1352     return error;
1353 }
1354
1355 struct actions_for_flow {
1356     struct hmap_node hmap_node;
1357     struct flow flow;
1358     struct ofpbuf actions;
1359 };
1360
1361 static struct actions_for_flow *
1362 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
1363 {
1364     uint32_t hash = flow_hash(flow, 0);
1365     struct actions_for_flow *af;
1366
1367     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
1368         if (flow_equal(&af->flow, flow)) {
1369             return af;
1370         }
1371     }
1372
1373     af = xmalloc(sizeof *af);
1374     af->flow = *flow;
1375     ofpbuf_init(&af->actions, 0);
1376     hmap_insert(actions_per_flow, &af->hmap_node, hash);
1377     return af;
1378 }
1379
1380 static int
1381 compare_actions_for_flow(const void *a_, const void *b_)
1382 {
1383     struct actions_for_flow *const *a = a_;
1384     struct actions_for_flow *const *b = b_;
1385
1386     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
1387 }
1388
1389 static int
1390 compare_output_actions(const void *a_, const void *b_)
1391 {
1392     const struct nlattr *a = a_;
1393     const struct nlattr *b = b_;
1394     uint32_t a_port = nl_attr_get_u32(a);
1395     uint32_t b_port = nl_attr_get_u32(b);
1396
1397     return a_port < b_port ? -1 : a_port > b_port;
1398 }
1399
1400 static void
1401 sort_output_actions__(struct nlattr *first, struct nlattr *end)
1402 {
1403     size_t bytes = (uint8_t *) end - (uint8_t *) first;
1404     size_t n = bytes / NL_A_U32_SIZE;
1405
1406     ovs_assert(bytes % NL_A_U32_SIZE == 0);
1407     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
1408 }
1409
1410 static void
1411 sort_output_actions(struct nlattr *actions, size_t length)
1412 {
1413     struct nlattr *first_output = NULL;
1414     struct nlattr *a;
1415     int left;
1416
1417     NL_ATTR_FOR_EACH (a, left, actions, length) {
1418         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
1419             if (!first_output) {
1420                 first_output = a;
1421             }
1422         } else {
1423             if (first_output) {
1424                 sort_output_actions__(first_output, a);
1425                 first_output = NULL;
1426             }
1427         }
1428     }
1429     if (first_output) {
1430         uint8_t *end = (uint8_t *) actions + length;
1431         sort_output_actions__(first_output,
1432                               ALIGNED_CAST(struct nlattr *, end));
1433     }
1434 }
1435
1436 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
1437  * have the syntax used by "ovs-dpctl dump-flows".
1438  *
1439  * This command prints ACTIONS in a format that shows what happens for each
1440  * VLAN, independent of the order of the ACTIONS.  For example, there is more
1441  * than one way to output a packet on VLANs 9 and 11, but this command will
1442  * print the same output for any form.
1443  *
1444  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
1445  * so far the implementation only covers VLANs. */
1446 static int
1447 dpctl_normalize_actions(int argc, const char *argv[],
1448                         struct dpctl_params *dpctl_p)
1449 {
1450     struct simap port_names;
1451     struct ofpbuf keybuf;
1452     struct flow flow;
1453     struct ofpbuf odp_actions;
1454     struct hmap actions_per_flow;
1455     struct actions_for_flow **afs;
1456     struct actions_for_flow *af;
1457     struct nlattr *a;
1458     size_t n_afs;
1459     struct ds s;
1460     int left;
1461     int i, error;
1462
1463     ds_init(&s);
1464
1465     simap_init(&port_names);
1466     for (i = 3; i < argc; i++) {
1467         char name[16];
1468         int number;
1469
1470         if (ovs_scan(argv[i], "%15[^=]=%d", name, &number)) {
1471             uintptr_t n = number;
1472             simap_put(&port_names, name, n);
1473         } else {
1474             dpctl_error(dpctl_p, 0, "%s: expected NAME=NUMBER", argv[i]);
1475             error = EINVAL;
1476             goto out;
1477         }
1478     }
1479
1480     /* Parse flow key. */
1481     ofpbuf_init(&keybuf, 0);
1482     error = odp_flow_from_string(argv[1], &port_names, &keybuf, NULL);
1483     if (error) {
1484         dpctl_error(dpctl_p, error, "odp_flow_key_from_string");
1485         goto out_freekeybuf;
1486     }
1487
1488     ds_clear(&s);
1489     odp_flow_format(keybuf.data, keybuf.size, NULL, 0, NULL,
1490                     &s, dpctl_p->verbosity);
1491     dpctl_print(dpctl_p, "input flow: %s\n", ds_cstr(&s));
1492
1493     error = odp_flow_key_to_flow(keybuf.data, keybuf.size, &flow);
1494     if (error) {
1495         dpctl_error(dpctl_p, error, "odp_flow_key_to_flow");
1496         goto out_freekeybuf;
1497     }
1498
1499     /* Parse actions. */
1500     ofpbuf_init(&odp_actions, 0);
1501     error = odp_actions_from_string(argv[2], &port_names, &odp_actions);
1502     if (error) {
1503         dpctl_error(dpctl_p, error, "odp_actions_from_string");
1504         goto out_freeactions;
1505     }
1506
1507     if (dpctl_p->verbosity) {
1508         ds_clear(&s);
1509         format_odp_actions(&s, odp_actions.data, odp_actions.size);
1510         dpctl_print(dpctl_p, "input actions: %s\n", ds_cstr(&s));
1511     }
1512
1513     hmap_init(&actions_per_flow);
1514     NL_ATTR_FOR_EACH (a, left, odp_actions.data, odp_actions.size) {
1515         const struct ovs_action_push_vlan *push;
1516         switch(nl_attr_type(a)) {
1517         case OVS_ACTION_ATTR_POP_VLAN:
1518             flow.vlan_tci = htons(0);
1519             continue;
1520
1521         case OVS_ACTION_ATTR_PUSH_VLAN:
1522             push = nl_attr_get_unspec(a, sizeof *push);
1523             flow.vlan_tci = push->vlan_tci;
1524             continue;
1525         }
1526
1527         af = get_actions_for_flow(&actions_per_flow, &flow);
1528         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
1529                           nl_attr_get(a), nl_attr_get_size(a));
1530     }
1531
1532     n_afs = hmap_count(&actions_per_flow);
1533     afs = xmalloc(n_afs * sizeof *afs);
1534     i = 0;
1535     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
1536         afs[i++] = af;
1537     }
1538
1539     ovs_assert(i == n_afs);
1540     hmap_destroy(&actions_per_flow);
1541
1542     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
1543
1544     for (i = 0; i < n_afs; i++) {
1545         struct actions_for_flow *af = afs[i];
1546
1547         sort_output_actions(af->actions.data, af->actions.size);
1548
1549         if (af->flow.vlan_tci != htons(0)) {
1550             dpctl_print(dpctl_p, "vlan(vid=%"PRIu16",pcp=%d): ",
1551                         vlan_tci_to_vid(af->flow.vlan_tci),
1552                         vlan_tci_to_pcp(af->flow.vlan_tci));
1553         } else {
1554             dpctl_print(dpctl_p, "no vlan: ");
1555         }
1556
1557         if (eth_type_mpls(af->flow.dl_type)) {
1558             dpctl_print(dpctl_p, "mpls(label=%"PRIu32",tc=%d,ttl=%d): ",
1559                         mpls_lse_to_label(af->flow.mpls_lse[0]),
1560                         mpls_lse_to_tc(af->flow.mpls_lse[0]),
1561                         mpls_lse_to_ttl(af->flow.mpls_lse[0]));
1562         } else {
1563             dpctl_print(dpctl_p, "no mpls: ");
1564         }
1565
1566         ds_clear(&s);
1567         format_odp_actions(&s, af->actions.data, af->actions.size);
1568         dpctl_puts(dpctl_p, false, ds_cstr(&s));
1569
1570         ofpbuf_uninit(&af->actions);
1571         free(af);
1572     }
1573     free(afs);
1574
1575
1576 out_freeactions:
1577     ofpbuf_uninit(&odp_actions);
1578 out_freekeybuf:
1579     ofpbuf_uninit(&keybuf);
1580 out:
1581     simap_destroy(&port_names);
1582     ds_destroy(&s);
1583
1584     return error;
1585 }
1586 \f
1587 static const struct dpctl_command all_commands[] = {
1588     { "add-dp", "add-dp dp [iface...]", 1, INT_MAX, dpctl_add_dp },
1589     { "del-dp", "del-dp dp", 1, 1, dpctl_del_dp },
1590     { "add-if", "add-if dp iface...", 2, INT_MAX, dpctl_add_if },
1591     { "del-if", "del-if dp iface...", 2, INT_MAX, dpctl_del_if },
1592     { "set-if", "set-if dp iface...", 2, INT_MAX, dpctl_set_if },
1593     { "dump-dps", "", 0, 0, dpctl_dump_dps },
1594     { "show", "[dp...]", 0, INT_MAX, dpctl_show },
1595     { "dump-flows", "[dp]", 0, 2, dpctl_dump_flows },
1596     { "add-flow", "add-flow [dp] flow actions", 2, 3, dpctl_add_flow },
1597     { "mod-flow", "mod-flow [dp] flow actions", 2, 3, dpctl_mod_flow },
1598     { "get-flow", "get-flow [dp] ufid", 1, 2, dpctl_get_flow },
1599     { "del-flow", "del-flow [dp] flow", 1, 2, dpctl_del_flow },
1600     { "del-flows", "[dp]", 0, 1, dpctl_del_flows },
1601     { "dump-conntrack", "[dp] [zone=N]", 0, 2, dpctl_dump_conntrack },
1602     { "flush-conntrack", "[dp] [zone=N]", 0, 2, dpctl_flush_conntrack },
1603     { "help", "", 0, INT_MAX, dpctl_help },
1604     { "list-commands", "", 0, INT_MAX, dpctl_list_commands },
1605
1606     /* Undocumented commands for testing. */
1607     { "parse-actions", "actions", 1, INT_MAX, dpctl_parse_actions },
1608     { "normalize-actions", "actions", 2, INT_MAX, dpctl_normalize_actions },
1609
1610     { NULL, NULL, 0, 0, NULL },
1611 };
1612
1613 static const struct dpctl_command *get_all_dpctl_commands(void)
1614 {
1615     return all_commands;
1616 }
1617
1618 /* Runs the command designated by argv[0] within the command table specified by
1619  * 'commands', which must be terminated by a command whose 'name' member is a
1620  * null pointer. */
1621 int
1622 dpctl_run_command(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1623 {
1624     const struct dpctl_command *p;
1625
1626     if (argc < 1) {
1627         dpctl_error(dpctl_p, 0, "missing command name; use --help for help");
1628         return EINVAL;
1629     }
1630
1631     for (p = all_commands; p->name != NULL; p++) {
1632         if (!strcmp(p->name, argv[0])) {
1633             int n_arg = argc - 1;
1634             if (n_arg < p->min_args) {
1635                 dpctl_error(dpctl_p, 0,
1636                             "'%s' command requires at least %d arguments",
1637                             p->name, p->min_args);
1638                 return EINVAL;
1639             } else if (n_arg > p->max_args) {
1640                 dpctl_error(dpctl_p, 0,
1641                             "'%s' command takes at most %d arguments",
1642                             p->name, p->max_args);
1643                 return EINVAL;
1644             } else {
1645                 return p->handler(argc, argv, dpctl_p);
1646             }
1647         }
1648     }
1649
1650     dpctl_error(dpctl_p, 0, "unknown command '%s'; use --help for help",
1651                 argv[0]);
1652     return EINVAL;
1653 }
1654 \f
1655 static void
1656 dpctl_unixctl_print(void *userdata, bool error OVS_UNUSED, const char *msg)
1657 {
1658     struct ds *ds = userdata;
1659     ds_put_cstr(ds, msg);
1660 }
1661
1662 static void
1663 dpctl_unixctl_handler(struct unixctl_conn *conn, int argc, const char *argv[],
1664                       void *aux)
1665 {
1666     struct ds ds = DS_EMPTY_INITIALIZER;
1667     bool error = false;
1668
1669     struct dpctl_params dpctl_p = {
1670         .is_appctl = true,
1671         .output = dpctl_unixctl_print,
1672         .aux = &ds,
1673     };
1674
1675     /* Parse options (like getopt). Unfortunately it does
1676      * not seem a good idea to call getopt_long() here, since it uses global
1677      * variables */
1678     while (argc > 1 && !error) {
1679         const char *arg = argv[1];
1680         if (!strncmp(arg, "--", 2)) {
1681             /* Long option */
1682             if (!strcmp(arg, "--statistics")) {
1683                 dpctl_p.print_statistics = true;
1684             } else if (!strcmp(arg, "--clear")) {
1685                 dpctl_p.zero_statistics = true;
1686             } else if (!strcmp(arg, "--may-create")) {
1687                 dpctl_p.may_create = true;
1688             } else if (!strcmp(arg, "--more")) {
1689                 dpctl_p.verbosity++;
1690             } else {
1691                 ds_put_format(&ds, "Unrecognized option %s", argv[1]);
1692                 error = true;
1693             }
1694         } else if (arg[0] == '-' && arg[1] != '\0') {
1695             /* Short option[s] */
1696             const char *opt = &arg[1];
1697
1698             while (*opt && !error) {
1699                 switch (*opt) {
1700                 case 'm':
1701                     dpctl_p.verbosity++;
1702                     break;
1703                 case 's':
1704                     dpctl_p.print_statistics = true;
1705                     break;
1706                 default:
1707                     ds_put_format(&ds, "Unrecognized option -%c", *opt);
1708                     error = true;
1709                     break;
1710                 }
1711                 opt++;
1712             }
1713         } else {
1714             /* Doesn't start with -, not an option */
1715             break;
1716         }
1717
1718         if (error) {
1719             break;
1720         }
1721         argv++;
1722         argc--;
1723     }
1724
1725     if (!error) {
1726         dpctl_command_handler *handler = (dpctl_command_handler *) aux;
1727         error = handler(argc, argv, &dpctl_p) != 0;
1728     }
1729
1730     if (error) {
1731         unixctl_command_reply_error(conn, ds_cstr(&ds));
1732     } else {
1733         unixctl_command_reply(conn, ds_cstr(&ds));
1734     }
1735
1736     ds_destroy(&ds);
1737 }
1738
1739 void
1740 dpctl_unixctl_register(void)
1741 {
1742     const struct dpctl_command *p;
1743
1744     for (p = all_commands; p->name != NULL; p++) {
1745         if (strcmp(p->name, "help")) {
1746             char *cmd_name = xasprintf("dpctl/%s", p->name);
1747             unixctl_command_register(cmd_name, "", p->min_args, p->max_args,
1748                                      dpctl_unixctl_handler, p->handler);
1749             free(cmd_name);
1750         }
1751     }
1752 }