ovs-numa: Remove non-linux stubs.
[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 "openvswitch/dynamic-string.h"
36 #include "flow.h"
37 #include "openvswitch/match.h"
38 #include "netdev.h"
39 #include "netdev-dpdk.h"
40 #include "netlink.h"
41 #include "odp-util.h"
42 #include "openvswitch/ofpbuf.h"
43 #include "ovs-numa.h"
44 #include "packets.h"
45 #include "shash.h"
46 #include "simap.h"
47 #include "smap.h"
48 #include "sset.h"
49 #include "timeval.h"
50 #include "unixctl.h"
51 #include "util.h"
52 #include "openvswitch/ofp-parse.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 /* qsort comparison function. */
512 static int
513 compare_port_nos(const void *a_, const void *b_)
514 {
515     const odp_port_t *ap = a_;
516     const odp_port_t *bp = b_;
517     uint32_t a = odp_to_u32(*ap);
518     uint32_t b = odp_to_u32(*bp);
519
520     return a < b ? -1 : a > b;
521 }
522
523 static void
524 show_dpif(struct dpif *dpif, struct dpctl_params *dpctl_p)
525 {
526     struct dpif_port_dump dump;
527     struct dpif_port dpif_port;
528     struct dpif_dp_stats stats;
529     struct netdev *netdev;
530
531     dpctl_print(dpctl_p, "%s:\n", dpif_name(dpif));
532     if (!dpif_get_dp_stats(dpif, &stats)) {
533         dpctl_print(dpctl_p, "\tlookups: hit:%"PRIu64" missed:%"PRIu64
534                              " lost:%"PRIu64"\n\tflows: %"PRIu64"\n",
535                     stats.n_hit, stats.n_missed, stats.n_lost, stats.n_flows);
536         if (stats.n_masks != UINT32_MAX) {
537             uint64_t n_pkts = stats.n_hit + stats.n_missed;
538             double avg = n_pkts ? (double) stats.n_mask_hit / n_pkts : 0.0;
539
540             dpctl_print(dpctl_p, "\tmasks: hit:%"PRIu64" total:%"PRIu32
541                                  " hit/pkt:%.2f\n",
542                         stats.n_mask_hit, stats.n_masks, avg);
543         }
544     }
545
546     odp_port_t *port_nos = NULL;
547     size_t allocated_port_nos = 0, n_port_nos = 0;
548     DPIF_PORT_FOR_EACH (&dpif_port, &dump, dpif) {
549         if (n_port_nos >= allocated_port_nos) {
550             port_nos = x2nrealloc(port_nos, &allocated_port_nos,
551                                   sizeof *port_nos);
552         }
553
554         port_nos[n_port_nos] = dpif_port.port_no;
555         n_port_nos++;
556     }
557
558     qsort(port_nos, n_port_nos, sizeof *port_nos, compare_port_nos);
559
560     for (int i = 0; i < n_port_nos; i++) {
561         if (dpif_port_query_by_number(dpif, port_nos[i], &dpif_port)) {
562             continue;
563         }
564
565         dpctl_print(dpctl_p, "\tport %u: %s",
566                     dpif_port.port_no, dpif_port.name);
567
568         if (strcmp(dpif_port.type, "system")) {
569             int error;
570
571             dpctl_print(dpctl_p, " (%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                         dpctl_print(dpctl_p, "%c %s=%s", i ? ',' : ':',
587                                     node->key, node->value);
588                     }
589                     free(nodes);
590                 } else {
591                     dpctl_print(dpctl_p, ", could not retrieve configuration "
592                                          "(%s)",  ovs_strerror(error));
593                 }
594                 smap_destroy(&config);
595
596                 netdev_close(netdev);
597             } else {
598                 dpctl_print(dpctl_p, ": open failed (%s)",
599                             ovs_strerror(error));
600             }
601             dpctl_print(dpctl_p, ")");
602         }
603         dpctl_print(dpctl_p, "\n");
604
605         if (dpctl_p->print_statistics) {
606             struct netdev_stats s;
607             int error;
608
609             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
610             if (error) {
611                 dpctl_print(dpctl_p, ", open failed (%s)",
612                             ovs_strerror(error));
613                 dpif_port_destroy(&dpif_port);
614                 continue;
615             }
616             error = netdev_get_stats(netdev, &s);
617             if (!error) {
618                 netdev_close(netdev);
619                 print_stat(dpctl_p, "\t\tRX packets:", s.rx_packets);
620                 print_stat(dpctl_p, " errors:", s.rx_errors);
621                 print_stat(dpctl_p, " dropped:", s.rx_dropped);
622                 print_stat(dpctl_p, " overruns:", s.rx_over_errors);
623                 print_stat(dpctl_p, " frame:", s.rx_frame_errors);
624                 dpctl_print(dpctl_p, "\n");
625
626                 print_stat(dpctl_p, "\t\tTX packets:", s.tx_packets);
627                 print_stat(dpctl_p, " errors:", s.tx_errors);
628                 print_stat(dpctl_p, " dropped:", s.tx_dropped);
629                 print_stat(dpctl_p, " aborted:", s.tx_aborted_errors);
630                 print_stat(dpctl_p, " carrier:", s.tx_carrier_errors);
631                 dpctl_print(dpctl_p, "\n");
632
633                 print_stat(dpctl_p, "\t\tcollisions:", s.collisions);
634                 dpctl_print(dpctl_p, "\n");
635
636                 print_stat(dpctl_p, "\t\tRX bytes:", s.rx_bytes);
637                 print_human_size(dpctl_p, s.rx_bytes);
638                 print_stat(dpctl_p, "  TX bytes:", s.tx_bytes);
639                 print_human_size(dpctl_p, s.tx_bytes);
640                 dpctl_print(dpctl_p, "\n");
641             } else {
642                 dpctl_print(dpctl_p, ", could not retrieve stats (%s)",
643                             ovs_strerror(error));
644             }
645         }
646         dpif_port_destroy(&dpif_port);
647     }
648
649     free(port_nos);
650 }
651
652 typedef void (*dps_for_each_cb)(struct dpif *, struct dpctl_params *);
653
654 static int
655 dps_for_each(struct dpctl_params *dpctl_p, dps_for_each_cb cb)
656 {
657     struct sset dpif_names = SSET_INITIALIZER(&dpif_names),
658                 dpif_types = SSET_INITIALIZER(&dpif_types);
659     int error, openerror = 0, enumerror = 0;
660     const char *type, *name;
661     bool at_least_one = false;
662
663     dp_enumerate_types(&dpif_types);
664
665     SSET_FOR_EACH (type, &dpif_types) {
666         error = dp_enumerate_names(type, &dpif_names);
667         if (error) {
668             enumerror = error;
669         }
670
671         SSET_FOR_EACH (name, &dpif_names) {
672             struct dpif *dpif;
673
674             at_least_one = true;
675             error = dpif_open(name, type, &dpif);
676             if (!error) {
677                 cb(dpif, dpctl_p);
678                 dpif_close(dpif);
679             } else {
680                 openerror = error;
681                 dpctl_error(dpctl_p, error, "opening datapath %s failed",
682                             name);
683             }
684         }
685     }
686
687     sset_destroy(&dpif_names);
688     sset_destroy(&dpif_types);
689
690     /* If there has been an error while opening a datapath it should be
691      * reported.  Otherwise, we want to ignore the errors generated by
692      * dp_enumerate_names() if at least one datapath has been discovered,
693      * because they're not interesting for the user.  This happens, for
694      * example, if OVS is using a userspace datapath and the kernel module
695      * is not loaded. */
696     if (openerror) {
697         return openerror;
698     } else {
699         return at_least_one ? 0 : enumerror;
700     }
701 }
702
703 static int
704 dpctl_show(int argc, const char *argv[], struct dpctl_params *dpctl_p)
705 {
706     int error, lasterror = 0;
707     if (argc > 1) {
708         int i;
709         for (i = 1; i < argc; i++) {
710             const char *name = argv[i];
711             struct dpif *dpif;
712
713             error = parsed_dpif_open(name, false, &dpif);
714             if (!error) {
715                 show_dpif(dpif, dpctl_p);
716                 dpif_close(dpif);
717             } else {
718                 dpctl_error(dpctl_p, error, "opening datapath %s failed",
719                             name);
720                 lasterror = error;
721             }
722         }
723     } else {
724         lasterror = dps_for_each(dpctl_p, show_dpif);
725     }
726
727     return lasterror;
728 }
729
730 static void
731 dump_cb(struct dpif *dpif, struct dpctl_params *dpctl_p)
732 {
733     dpctl_print(dpctl_p, "%s\n", dpif_name(dpif));
734 }
735
736 static int
737 dpctl_dump_dps(int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
738                struct dpctl_params *dpctl_p)
739 {
740     return dps_for_each(dpctl_p, dump_cb);
741 }
742
743 static void
744 format_dpif_flow(struct ds *ds, const struct dpif_flow *f, struct hmap *ports,
745                  struct dpctl_params *dpctl_p)
746 {
747     if (dpctl_p->verbosity && f->ufid_present) {
748         odp_format_ufid(&f->ufid, ds);
749         ds_put_cstr(ds, ", ");
750     }
751     odp_flow_format(f->key, f->key_len, f->mask, f->mask_len, ports, ds,
752                     dpctl_p->verbosity);
753     ds_put_cstr(ds, ", ");
754
755     dpif_flow_stats_format(&f->stats, ds);
756     ds_put_cstr(ds, ", actions:");
757     format_odp_actions(ds, f->actions, f->actions_len);
758 }
759
760 static int
761 dpctl_dump_flows(int argc, const char *argv[], struct dpctl_params *dpctl_p)
762 {
763     struct dpif *dpif;
764     struct ds ds;
765     char *name;
766
767     char *filter = NULL;
768     struct flow flow_filter;
769     struct flow_wildcards wc_filter;
770
771     struct dpif_port_dump port_dump;
772     struct dpif_port dpif_port;
773     struct hmap portno_names;
774     struct simap names_portno;
775
776     struct dpif_flow_dump_thread *flow_dump_thread;
777     struct dpif_flow_dump *flow_dump;
778     struct dpif_flow f;
779     int pmd_id = PMD_ID_NULL;
780     int error;
781
782     if (argc > 1 && !strncmp(argv[argc - 1], "filter=", 7)) {
783         filter = xstrdup(argv[--argc] + 7);
784     }
785     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
786     if (!name) {
787         error = EINVAL;
788         goto out_freefilter;
789     }
790
791     error = parsed_dpif_open(name, false, &dpif);
792     free(name);
793     if (error) {
794         dpctl_error(dpctl_p, error, "opening datapath");
795         goto out_freefilter;
796     }
797
798
799     hmap_init(&portno_names);
800     simap_init(&names_portno);
801     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
802         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
803         simap_put(&names_portno, dpif_port.name,
804                   odp_to_u32(dpif_port.port_no));
805     }
806
807     if (filter) {
808         char *err = parse_ofp_exact_flow(&flow_filter, &wc_filter.masks,
809                                          filter, &names_portno);
810         if (err) {
811             dpctl_error(dpctl_p, 0, "Failed to parse filter (%s)", err);
812             error = EINVAL;
813             goto out_dpifclose;
814         }
815     }
816
817     /* Make sure that these values are different. PMD_ID_NULL means that the
818      * pmd is unspecified (e.g. because the datapath doesn't have different
819      * pmd threads), while NON_PMD_CORE_ID refers to every non pmd threads
820      * in the userspace datapath */
821     BUILD_ASSERT(PMD_ID_NULL != NON_PMD_CORE_ID);
822
823     ds_init(&ds);
824     flow_dump = dpif_flow_dump_create(dpif, false);
825     flow_dump_thread = dpif_flow_dump_thread_create(flow_dump);
826     while (dpif_flow_dump_next(flow_dump_thread, &f, 1)) {
827         if (filter) {
828             struct flow flow;
829             struct flow_wildcards wc;
830             struct match match, match_filter;
831             struct minimatch minimatch;
832
833             odp_flow_key_to_flow(f.key, f.key_len, &flow);
834             odp_flow_key_to_mask(f.mask, f.mask_len, f.key, f.key_len,
835                                  &wc, &flow);
836             match_init(&match, &flow, &wc);
837
838             match_init(&match_filter, &flow_filter, &wc);
839             match_init(&match_filter, &match_filter.flow, &wc_filter);
840             minimatch_init(&minimatch, &match_filter);
841
842             if (!minimatch_matches_flow(&minimatch, &match.flow)) {
843                 minimatch_destroy(&minimatch);
844                 continue;
845             }
846             minimatch_destroy(&minimatch);
847         }
848         ds_clear(&ds);
849         /* If 'pmd_id' is specified, overlapping flows could be dumped from
850          * different pmd threads.  So, separates dumps from different pmds
851          * by printing a title line. */
852         if (pmd_id != f.pmd_id) {
853             if (f.pmd_id == NON_PMD_CORE_ID) {
854                 ds_put_format(&ds, "flow-dump from non-dpdk interfaces:\n");
855             } else {
856                 ds_put_format(&ds, "flow-dump from pmd on cpu core: %d\n",
857                               f.pmd_id);
858             }
859             pmd_id = f.pmd_id;
860         }
861         format_dpif_flow(&ds, &f, &portno_names, dpctl_p);
862         dpctl_print(dpctl_p, "%s\n", ds_cstr(&ds));
863     }
864     dpif_flow_dump_thread_destroy(flow_dump_thread);
865     error = dpif_flow_dump_destroy(flow_dump);
866
867     if (error) {
868         dpctl_error(dpctl_p, error, "Failed to dump flows from datapath");
869     }
870     ds_destroy(&ds);
871
872 out_dpifclose:
873     odp_portno_names_destroy(&portno_names);
874     simap_destroy(&names_portno);
875     hmap_destroy(&portno_names);
876     dpif_close(dpif);
877 out_freefilter:
878     free(filter);
879     return error;
880 }
881
882 /* Extracts the in_port from the parsed keys, and returns the reference
883  * to the 'struct netdev *' of the dpif port.  On error, returns NULL.
884  * Users must call 'netdev_close()' after finish using the returned
885  * reference. */
886 static struct netdev *
887 get_in_port_netdev_from_key(struct dpif *dpif, const struct ofpbuf *key)
888 {
889     const struct nlattr *in_port_nla;
890     struct netdev *dev = NULL;
891
892     in_port_nla = nl_attr_find(key, 0, OVS_KEY_ATTR_IN_PORT);
893     if (in_port_nla) {
894         struct dpif_port dpif_port;
895         odp_port_t port_no;
896         int error;
897
898         port_no = ODP_PORT_C(nl_attr_get_u32(in_port_nla));
899         error = dpif_port_query_by_number(dpif, port_no, &dpif_port);
900         if (error) {
901             goto out;
902         }
903
904         netdev_open(dpif_port.name, dpif_port.type, &dev);
905         dpif_port_destroy(&dpif_port);
906     }
907
908 out:
909     return dev;
910 }
911
912 static int
913 dpctl_put_flow(int argc, const char *argv[], enum dpif_flow_put_flags flags,
914                struct dpctl_params *dpctl_p)
915 {
916     const char *key_s = argv[argc - 2];
917     const char *actions_s = argv[argc - 1];
918     struct netdev *in_port_netdev = NULL;
919     struct dpif_flow_stats stats;
920     struct dpif_port dpif_port;
921     struct dpif_port_dump port_dump;
922     struct ofpbuf actions;
923     struct ofpbuf key;
924     struct ofpbuf mask;
925     struct dpif *dpif;
926     ovs_u128 ufid;
927     bool ufid_present;
928     char *dp_name;
929     struct simap port_names;
930     int n, error;
931
932     dp_name = argc == 4 ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
933     if (!dp_name) {
934         return EINVAL;
935     }
936     error = parsed_dpif_open(dp_name, false, &dpif);
937     free(dp_name);
938     if (error) {
939         dpctl_error(dpctl_p, error, "opening datapath");
940         return error;
941     }
942
943     ufid_present = false;
944     n = odp_ufid_from_string(key_s, &ufid);
945     if (n < 0) {
946         dpctl_error(dpctl_p, -n, "parsing flow ufid");
947         return -n;
948     } else if (n) {
949         key_s += n;
950         ufid_present = true;
951     }
952
953     simap_init(&port_names);
954     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
955         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
956     }
957
958     ofpbuf_init(&key, 0);
959     ofpbuf_init(&mask, 0);
960     error = odp_flow_from_string(key_s, &port_names, &key, &mask);
961     simap_destroy(&port_names);
962     if (error) {
963         dpctl_error(dpctl_p, error, "parsing flow key");
964         goto out_freekeymask;
965     }
966
967     ofpbuf_init(&actions, 0);
968     error = odp_actions_from_string(actions_s, NULL, &actions);
969     if (error) {
970         dpctl_error(dpctl_p, error, "parsing actions");
971         goto out_freeactions;
972     }
973
974     /* For DPDK interface, applies the operation to all pmd threads
975      * on the same numa node. */
976     in_port_netdev = get_in_port_netdev_from_key(dpif, &key);
977     if (in_port_netdev && netdev_is_pmd(in_port_netdev)) {
978         int numa_id;
979
980         numa_id = netdev_get_numa_id(in_port_netdev);
981         if (ovs_numa_numa_id_is_valid(numa_id)) {
982             struct ovs_numa_dump *dump = ovs_numa_dump_cores_on_numa(numa_id);
983             struct ovs_numa_info *iter;
984
985             FOR_EACH_CORE_ON_NUMA (iter, dump) {
986                 if (ovs_numa_core_is_pinned(iter->core_id)) {
987                     error = dpif_flow_put(dpif, flags,
988                                           key.data, key.size,
989                                           mask.size == 0 ? NULL : mask.data,
990                                           mask.size, actions.data,
991                                           actions.size, ufid_present ? &ufid : NULL,
992                                           iter->core_id, dpctl_p->print_statistics ? &stats : NULL);
993                 }
994             }
995             ovs_numa_dump_destroy(dump);
996         } else {
997             error = EINVAL;
998         }
999     } else {
1000         error = dpif_flow_put(dpif, flags,
1001                               key.data, key.size,
1002                               mask.size == 0 ? NULL : mask.data,
1003                               mask.size, actions.data,
1004                               actions.size, ufid_present ? &ufid : NULL,
1005                               PMD_ID_NULL, dpctl_p->print_statistics ? &stats : NULL);
1006     }
1007     if (error) {
1008         dpctl_error(dpctl_p, error, "updating flow table");
1009         goto out_freeactions;
1010     }
1011
1012     if (dpctl_p->print_statistics) {
1013         struct ds s;
1014
1015         ds_init(&s);
1016         dpif_flow_stats_format(&stats, &s);
1017         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1018         ds_destroy(&s);
1019     }
1020
1021 out_freeactions:
1022     ofpbuf_uninit(&actions);
1023 out_freekeymask:
1024     ofpbuf_uninit(&mask);
1025     ofpbuf_uninit(&key);
1026     dpif_close(dpif);
1027     netdev_close(in_port_netdev);
1028     return error;
1029 }
1030
1031 static int
1032 dpctl_add_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1033 {
1034     return dpctl_put_flow(argc, argv, DPIF_FP_CREATE, dpctl_p);
1035 }
1036
1037 static int
1038 dpctl_mod_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1039 {
1040     enum dpif_flow_put_flags flags;
1041
1042     flags = DPIF_FP_MODIFY;
1043     if (dpctl_p->may_create) {
1044         flags |= DPIF_FP_CREATE;
1045     }
1046     if (dpctl_p->zero_statistics) {
1047         flags |= DPIF_FP_ZERO_STATS;
1048     }
1049
1050     return dpctl_put_flow(argc, argv, flags, dpctl_p);
1051 }
1052
1053 static int
1054 dpctl_get_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1055 {
1056     const char *key_s = argv[argc - 1];
1057     struct dpif_flow flow;
1058     struct dpif_port dpif_port;
1059     struct dpif_port_dump port_dump;
1060     struct dpif *dpif;
1061     char *dp_name;
1062     struct hmap portno_names;
1063     ovs_u128 ufid;
1064     struct ofpbuf buf;
1065     uint64_t stub[DPIF_FLOW_BUFSIZE / 8];
1066     struct ds ds;
1067     int n, error;
1068
1069     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1070     if (!dp_name) {
1071         return EINVAL;
1072     }
1073     error = parsed_dpif_open(dp_name, false, &dpif);
1074     free(dp_name);
1075     if (error) {
1076         dpctl_error(dpctl_p, error, "opening datapath");
1077         return error;
1078     }
1079
1080     ofpbuf_use_stub(&buf, &stub, sizeof stub);
1081     hmap_init(&portno_names);
1082     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
1083         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
1084     }
1085
1086     n = odp_ufid_from_string(key_s, &ufid);
1087     if (n <= 0) {
1088         dpctl_error(dpctl_p, -n, "parsing flow ufid");
1089         goto out;
1090     }
1091
1092     /* In case of PMD will be returned flow from first PMD thread with match. */
1093     error = dpif_flow_get(dpif, NULL, 0, &ufid, PMD_ID_NULL, &buf, &flow);
1094     if (error) {
1095         dpctl_error(dpctl_p, error, "getting flow");
1096         goto out;
1097     }
1098
1099     ds_init(&ds);
1100     format_dpif_flow(&ds, &flow, &portno_names, dpctl_p);
1101     dpctl_print(dpctl_p, "%s\n", ds_cstr(&ds));
1102     ds_destroy(&ds);
1103
1104 out:
1105     odp_portno_names_destroy(&portno_names);
1106     hmap_destroy(&portno_names);
1107     ofpbuf_uninit(&buf);
1108     dpif_close(dpif);
1109     return error;
1110 }
1111
1112 static int
1113 dpctl_del_flow(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1114 {
1115     const char *key_s = argv[argc - 1];
1116     struct netdev *in_port_netdev = NULL;
1117     struct dpif_flow_stats stats;
1118     struct dpif_port dpif_port;
1119     struct dpif_port_dump port_dump;
1120     struct ofpbuf key;
1121     struct ofpbuf mask; /* To be ignored. */
1122     struct dpif *dpif;
1123     ovs_u128 ufid;
1124     bool ufid_present;
1125     char *dp_name;
1126     struct simap port_names;
1127     int n, error;
1128
1129     dp_name = argc == 3 ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1130     if (!dp_name) {
1131         return EINVAL;
1132     }
1133     error = parsed_dpif_open(dp_name, false, &dpif);
1134     free(dp_name);
1135     if (error) {
1136         dpctl_error(dpctl_p, error, "opening datapath");
1137         return error;
1138     }
1139
1140     ufid_present = false;
1141     n = odp_ufid_from_string(key_s, &ufid);
1142     if (n < 0) {
1143         dpctl_error(dpctl_p, -n, "parsing flow ufid");
1144         return -n;
1145     } else if (n) {
1146         key_s += n;
1147         ufid_present = true;
1148     }
1149
1150     simap_init(&port_names);
1151     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, dpif) {
1152         simap_put(&port_names, dpif_port.name, odp_to_u32(dpif_port.port_no));
1153     }
1154
1155     ofpbuf_init(&key, 0);
1156     ofpbuf_init(&mask, 0);
1157
1158     error = odp_flow_from_string(key_s, &port_names, &key, &mask);
1159     if (error) {
1160         dpctl_error(dpctl_p, error, "parsing flow key");
1161         goto out;
1162     }
1163
1164     /* For DPDK interface, applies the operation to all pmd threads
1165      * on the same numa node. */
1166     in_port_netdev = get_in_port_netdev_from_key(dpif, &key);
1167     if (in_port_netdev && netdev_is_pmd(in_port_netdev)) {
1168         int numa_id;
1169
1170         numa_id = netdev_get_numa_id(in_port_netdev);
1171         if (ovs_numa_numa_id_is_valid(numa_id)) {
1172             struct ovs_numa_dump *dump = ovs_numa_dump_cores_on_numa(numa_id);
1173             struct ovs_numa_info *iter;
1174
1175             FOR_EACH_CORE_ON_NUMA (iter, dump) {
1176                 if (ovs_numa_core_is_pinned(iter->core_id)) {
1177                     error = dpif_flow_del(dpif, key.data,
1178                                           key.size, ufid_present ? &ufid : NULL,
1179                                           iter->core_id, dpctl_p->print_statistics ? &stats : NULL);
1180                 }
1181             }
1182             ovs_numa_dump_destroy(dump);
1183         } else {
1184             error = EINVAL;
1185         }
1186     } else {
1187         error = dpif_flow_del(dpif, key.data, key.size,
1188                               ufid_present ? &ufid : NULL, PMD_ID_NULL,
1189                               dpctl_p->print_statistics ? &stats : NULL);
1190     }
1191     if (error) {
1192         dpctl_error(dpctl_p, error, "deleting flow");
1193         if (error == ENOENT && !ufid_present) {
1194             struct ds s;
1195
1196             ds_init(&s);
1197             ds_put_format(&s, "Perhaps you need to specify a UFID?");
1198             dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1199             ds_destroy(&s);
1200         }
1201         goto out;
1202     }
1203
1204     if (dpctl_p->print_statistics) {
1205         struct ds s;
1206
1207         ds_init(&s);
1208         dpif_flow_stats_format(&stats, &s);
1209         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1210         ds_destroy(&s);
1211     }
1212
1213 out:
1214     ofpbuf_uninit(&mask);
1215     ofpbuf_uninit(&key);
1216     simap_destroy(&port_names);
1217     dpif_close(dpif);
1218     netdev_close(in_port_netdev);
1219     return error;
1220 }
1221
1222 static int
1223 dpctl_del_flows(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1224 {
1225     struct dpif *dpif;
1226     char *name;
1227     int error;
1228
1229     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1230     if (!name) {
1231         return EINVAL;
1232     }
1233     error = parsed_dpif_open(name, false, &dpif);
1234     free(name);
1235     if (error) {
1236         dpctl_error(dpctl_p, error, "opening datapath");
1237         return error;
1238     }
1239
1240     error = dpif_flow_flush(dpif);
1241     if (error) {
1242         dpctl_error(dpctl_p, error, "deleting all flows");
1243     }
1244     dpif_close(dpif);
1245     return error;
1246 }
1247
1248 static int
1249 dpctl_help(int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
1250            struct dpctl_params *dpctl_p)
1251 {
1252     if (dpctl_p->usage) {
1253         dpctl_p->usage(dpctl_p->aux);
1254     }
1255
1256     return 0;
1257 }
1258
1259 static int
1260 dpctl_list_commands(int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
1261                     struct dpctl_params *dpctl_p)
1262 {
1263     struct ds ds = DS_EMPTY_INITIALIZER;
1264     const struct dpctl_command *commands = get_all_dpctl_commands();
1265
1266     ds_put_cstr(&ds, "The available commands are:\n");
1267     for (; commands->name; commands++) {
1268         const struct dpctl_command *c = commands;
1269
1270         ds_put_format(&ds, "  %s%-23s %s\n", dpctl_p->is_appctl ? "dpctl/" : "",
1271                       c->name, c->usage);
1272     }
1273     dpctl_puts(dpctl_p, false, ds.string);
1274     ds_destroy(&ds);
1275
1276     return 0;
1277 }
1278
1279 static int
1280 dpctl_dump_conntrack(int argc, const char *argv[],
1281                      struct dpctl_params *dpctl_p)
1282 {
1283     struct ct_dpif_dump_state *dump;
1284     struct ct_dpif_entry cte;
1285     uint16_t zone, *pzone = NULL;
1286     struct dpif *dpif;
1287     char *name;
1288     int error;
1289
1290     if (argc > 1 && ovs_scan(argv[argc - 1], "zone=%"SCNu16, &zone)) {
1291         pzone = &zone;
1292         argc--;
1293     }
1294     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1295     if (!name) {
1296         return EINVAL;
1297     }
1298     error = parsed_dpif_open(name, false, &dpif);
1299     free(name);
1300     if (error) {
1301         dpctl_error(dpctl_p, error, "opening datapath");
1302         return error;
1303     }
1304
1305     error = ct_dpif_dump_start(dpif, &dump, pzone);
1306     if (error) {
1307         dpctl_error(dpctl_p, error, "starting conntrack dump");
1308         dpif_close(dpif);
1309         return error;
1310     }
1311
1312     while (!ct_dpif_dump_next(dump, &cte)) {
1313         struct ds s = DS_EMPTY_INITIALIZER;
1314
1315         ct_dpif_format_entry(&cte, &s, dpctl_p->verbosity,
1316                              dpctl_p->print_statistics);
1317         ct_dpif_entry_uninit(&cte);
1318
1319         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1320         ds_destroy(&s);
1321     }
1322     ct_dpif_dump_done(dump);
1323     dpif_close(dpif);
1324     return error;
1325 }
1326
1327 static int
1328 dpctl_flush_conntrack(int argc, const char *argv[],
1329                       struct dpctl_params *dpctl_p)
1330 {
1331     struct dpif *dpif;
1332     uint16_t zone, *pzone = NULL;
1333     char *name;
1334     int error;
1335
1336     if (argc > 1 && ovs_scan(argv[argc - 1], "zone=%"SCNu16, &zone)) {
1337         pzone = &zone;
1338         argc--;
1339     }
1340     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp(dpctl_p);
1341     if (!name) {
1342         return EINVAL;
1343     }
1344     error = parsed_dpif_open(name, false, &dpif);
1345     free(name);
1346     if (error) {
1347         dpctl_error(dpctl_p, error, "opening datapath");
1348         return error;
1349     }
1350
1351     error = ct_dpif_flush(dpif, pzone);
1352
1353     dpif_close(dpif);
1354     return error;
1355 }
1356 \f
1357 /* Undocumented commands for unit testing. */
1358
1359 static int
1360 dpctl_parse_actions(int argc, const char *argv[], struct dpctl_params* dpctl_p)
1361 {
1362     int i, error = 0;
1363
1364     for (i = 1; i < argc; i++) {
1365         struct ofpbuf actions;
1366         struct ds s;
1367
1368         ofpbuf_init(&actions, 0);
1369         error = odp_actions_from_string(argv[i], NULL, &actions);
1370
1371         if (error) {
1372             ofpbuf_uninit(&actions);
1373             dpctl_error(dpctl_p, error, "odp_actions_from_string");
1374             return error;
1375         }
1376
1377         ds_init(&s);
1378         format_odp_actions(&s, actions.data, actions.size);
1379         dpctl_print(dpctl_p, "%s\n", ds_cstr(&s));
1380         ds_destroy(&s);
1381
1382         ofpbuf_uninit(&actions);
1383     }
1384
1385     return error;
1386 }
1387
1388 struct actions_for_flow {
1389     struct hmap_node hmap_node;
1390     struct flow flow;
1391     struct ofpbuf actions;
1392 };
1393
1394 static struct actions_for_flow *
1395 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
1396 {
1397     uint32_t hash = flow_hash(flow, 0);
1398     struct actions_for_flow *af;
1399
1400     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
1401         if (flow_equal(&af->flow, flow)) {
1402             return af;
1403         }
1404     }
1405
1406     af = xmalloc(sizeof *af);
1407     af->flow = *flow;
1408     ofpbuf_init(&af->actions, 0);
1409     hmap_insert(actions_per_flow, &af->hmap_node, hash);
1410     return af;
1411 }
1412
1413 static int
1414 compare_actions_for_flow(const void *a_, const void *b_)
1415 {
1416     struct actions_for_flow *const *a = a_;
1417     struct actions_for_flow *const *b = b_;
1418
1419     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
1420 }
1421
1422 static int
1423 compare_output_actions(const void *a_, const void *b_)
1424 {
1425     const struct nlattr *a = a_;
1426     const struct nlattr *b = b_;
1427     uint32_t a_port = nl_attr_get_u32(a);
1428     uint32_t b_port = nl_attr_get_u32(b);
1429
1430     return a_port < b_port ? -1 : a_port > b_port;
1431 }
1432
1433 static void
1434 sort_output_actions__(struct nlattr *first, struct nlattr *end)
1435 {
1436     size_t bytes = (uint8_t *) end - (uint8_t *) first;
1437     size_t n = bytes / NL_A_U32_SIZE;
1438
1439     ovs_assert(bytes % NL_A_U32_SIZE == 0);
1440     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
1441 }
1442
1443 static void
1444 sort_output_actions(struct nlattr *actions, size_t length)
1445 {
1446     struct nlattr *first_output = NULL;
1447     struct nlattr *a;
1448     int left;
1449
1450     NL_ATTR_FOR_EACH (a, left, actions, length) {
1451         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
1452             if (!first_output) {
1453                 first_output = a;
1454             }
1455         } else {
1456             if (first_output) {
1457                 sort_output_actions__(first_output, a);
1458                 first_output = NULL;
1459             }
1460         }
1461     }
1462     if (first_output) {
1463         uint8_t *end = (uint8_t *) actions + length;
1464         sort_output_actions__(first_output,
1465                               ALIGNED_CAST(struct nlattr *, end));
1466     }
1467 }
1468
1469 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
1470  * have the syntax used by "ovs-dpctl dump-flows".
1471  *
1472  * This command prints ACTIONS in a format that shows what happens for each
1473  * VLAN, independent of the order of the ACTIONS.  For example, there is more
1474  * than one way to output a packet on VLANs 9 and 11, but this command will
1475  * print the same output for any form.
1476  *
1477  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
1478  * so far the implementation only covers VLANs. */
1479 static int
1480 dpctl_normalize_actions(int argc, const char *argv[],
1481                         struct dpctl_params *dpctl_p)
1482 {
1483     struct simap port_names;
1484     struct ofpbuf keybuf;
1485     struct flow flow;
1486     struct ofpbuf odp_actions;
1487     struct hmap actions_per_flow;
1488     struct actions_for_flow **afs;
1489     struct actions_for_flow *af;
1490     struct nlattr *a;
1491     size_t n_afs;
1492     struct ds s;
1493     int left;
1494     int i, error;
1495
1496     ds_init(&s);
1497
1498     simap_init(&port_names);
1499     for (i = 3; i < argc; i++) {
1500         char name[16];
1501         int number;
1502
1503         if (ovs_scan(argv[i], "%15[^=]=%d", name, &number)) {
1504             uintptr_t n = number;
1505             simap_put(&port_names, name, n);
1506         } else {
1507             dpctl_error(dpctl_p, 0, "%s: expected NAME=NUMBER", argv[i]);
1508             error = EINVAL;
1509             goto out;
1510         }
1511     }
1512
1513     /* Parse flow key. */
1514     ofpbuf_init(&keybuf, 0);
1515     error = odp_flow_from_string(argv[1], &port_names, &keybuf, NULL);
1516     if (error) {
1517         dpctl_error(dpctl_p, error, "odp_flow_key_from_string");
1518         goto out_freekeybuf;
1519     }
1520
1521     ds_clear(&s);
1522     odp_flow_format(keybuf.data, keybuf.size, NULL, 0, NULL,
1523                     &s, dpctl_p->verbosity);
1524     dpctl_print(dpctl_p, "input flow: %s\n", ds_cstr(&s));
1525
1526     error = odp_flow_key_to_flow(keybuf.data, keybuf.size, &flow);
1527     if (error) {
1528         dpctl_error(dpctl_p, error, "odp_flow_key_to_flow");
1529         goto out_freekeybuf;
1530     }
1531
1532     /* Parse actions. */
1533     ofpbuf_init(&odp_actions, 0);
1534     error = odp_actions_from_string(argv[2], &port_names, &odp_actions);
1535     if (error) {
1536         dpctl_error(dpctl_p, error, "odp_actions_from_string");
1537         goto out_freeactions;
1538     }
1539
1540     if (dpctl_p->verbosity) {
1541         ds_clear(&s);
1542         format_odp_actions(&s, odp_actions.data, odp_actions.size);
1543         dpctl_print(dpctl_p, "input actions: %s\n", ds_cstr(&s));
1544     }
1545
1546     hmap_init(&actions_per_flow);
1547     NL_ATTR_FOR_EACH (a, left, odp_actions.data, odp_actions.size) {
1548         const struct ovs_action_push_vlan *push;
1549         switch(nl_attr_type(a)) {
1550         case OVS_ACTION_ATTR_POP_VLAN:
1551             flow.vlan_tci = htons(0);
1552             continue;
1553
1554         case OVS_ACTION_ATTR_PUSH_VLAN:
1555             push = nl_attr_get_unspec(a, sizeof *push);
1556             flow.vlan_tci = push->vlan_tci;
1557             continue;
1558         }
1559
1560         af = get_actions_for_flow(&actions_per_flow, &flow);
1561         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
1562                           nl_attr_get(a), nl_attr_get_size(a));
1563     }
1564
1565     n_afs = hmap_count(&actions_per_flow);
1566     afs = xmalloc(n_afs * sizeof *afs);
1567     i = 0;
1568     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
1569         afs[i++] = af;
1570     }
1571
1572     ovs_assert(i == n_afs);
1573     hmap_destroy(&actions_per_flow);
1574
1575     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
1576
1577     for (i = 0; i < n_afs; i++) {
1578         struct actions_for_flow *af = afs[i];
1579
1580         sort_output_actions(af->actions.data, af->actions.size);
1581
1582         if (af->flow.vlan_tci != htons(0)) {
1583             dpctl_print(dpctl_p, "vlan(vid=%"PRIu16",pcp=%d): ",
1584                         vlan_tci_to_vid(af->flow.vlan_tci),
1585                         vlan_tci_to_pcp(af->flow.vlan_tci));
1586         } else {
1587             dpctl_print(dpctl_p, "no vlan: ");
1588         }
1589
1590         if (eth_type_mpls(af->flow.dl_type)) {
1591             dpctl_print(dpctl_p, "mpls(label=%"PRIu32",tc=%d,ttl=%d): ",
1592                         mpls_lse_to_label(af->flow.mpls_lse[0]),
1593                         mpls_lse_to_tc(af->flow.mpls_lse[0]),
1594                         mpls_lse_to_ttl(af->flow.mpls_lse[0]));
1595         } else {
1596             dpctl_print(dpctl_p, "no mpls: ");
1597         }
1598
1599         ds_clear(&s);
1600         format_odp_actions(&s, af->actions.data, af->actions.size);
1601         dpctl_puts(dpctl_p, false, ds_cstr(&s));
1602
1603         ofpbuf_uninit(&af->actions);
1604         free(af);
1605     }
1606     free(afs);
1607
1608
1609 out_freeactions:
1610     ofpbuf_uninit(&odp_actions);
1611 out_freekeybuf:
1612     ofpbuf_uninit(&keybuf);
1613 out:
1614     simap_destroy(&port_names);
1615     ds_destroy(&s);
1616
1617     return error;
1618 }
1619 \f
1620 static const struct dpctl_command all_commands[] = {
1621     { "add-dp", "add-dp dp [iface...]", 1, INT_MAX, dpctl_add_dp },
1622     { "del-dp", "del-dp dp", 1, 1, dpctl_del_dp },
1623     { "add-if", "add-if dp iface...", 2, INT_MAX, dpctl_add_if },
1624     { "del-if", "del-if dp iface...", 2, INT_MAX, dpctl_del_if },
1625     { "set-if", "set-if dp iface...", 2, INT_MAX, dpctl_set_if },
1626     { "dump-dps", "", 0, 0, dpctl_dump_dps },
1627     { "show", "[dp...]", 0, INT_MAX, dpctl_show },
1628     { "dump-flows", "[dp]", 0, 2, dpctl_dump_flows },
1629     { "add-flow", "add-flow [dp] flow actions", 2, 3, dpctl_add_flow },
1630     { "mod-flow", "mod-flow [dp] flow actions", 2, 3, dpctl_mod_flow },
1631     { "get-flow", "get-flow [dp] ufid", 1, 2, dpctl_get_flow },
1632     { "del-flow", "del-flow [dp] flow", 1, 2, dpctl_del_flow },
1633     { "del-flows", "[dp]", 0, 1, dpctl_del_flows },
1634     { "dump-conntrack", "[dp] [zone=N]", 0, 2, dpctl_dump_conntrack },
1635     { "flush-conntrack", "[dp] [zone=N]", 0, 2, dpctl_flush_conntrack },
1636     { "help", "", 0, INT_MAX, dpctl_help },
1637     { "list-commands", "", 0, INT_MAX, dpctl_list_commands },
1638
1639     /* Undocumented commands for testing. */
1640     { "parse-actions", "actions", 1, INT_MAX, dpctl_parse_actions },
1641     { "normalize-actions", "actions", 2, INT_MAX, dpctl_normalize_actions },
1642
1643     { NULL, NULL, 0, 0, NULL },
1644 };
1645
1646 static const struct dpctl_command *get_all_dpctl_commands(void)
1647 {
1648     return all_commands;
1649 }
1650
1651 /* Runs the command designated by argv[0] within the command table specified by
1652  * 'commands', which must be terminated by a command whose 'name' member is a
1653  * null pointer. */
1654 int
1655 dpctl_run_command(int argc, const char *argv[], struct dpctl_params *dpctl_p)
1656 {
1657     const struct dpctl_command *p;
1658
1659     if (argc < 1) {
1660         dpctl_error(dpctl_p, 0, "missing command name; use --help for help");
1661         return EINVAL;
1662     }
1663
1664     for (p = all_commands; p->name != NULL; p++) {
1665         if (!strcmp(p->name, argv[0])) {
1666             int n_arg = argc - 1;
1667             if (n_arg < p->min_args) {
1668                 dpctl_error(dpctl_p, 0,
1669                             "'%s' command requires at least %d arguments",
1670                             p->name, p->min_args);
1671                 return EINVAL;
1672             } else if (n_arg > p->max_args) {
1673                 dpctl_error(dpctl_p, 0,
1674                             "'%s' command takes at most %d arguments",
1675                             p->name, p->max_args);
1676                 return EINVAL;
1677             } else {
1678                 return p->handler(argc, argv, dpctl_p);
1679             }
1680         }
1681     }
1682
1683     dpctl_error(dpctl_p, 0, "unknown command '%s'; use --help for help",
1684                 argv[0]);
1685     return EINVAL;
1686 }
1687 \f
1688 static void
1689 dpctl_unixctl_print(void *userdata, bool error OVS_UNUSED, const char *msg)
1690 {
1691     struct ds *ds = userdata;
1692     ds_put_cstr(ds, msg);
1693 }
1694
1695 static void
1696 dpctl_unixctl_handler(struct unixctl_conn *conn, int argc, const char *argv[],
1697                       void *aux)
1698 {
1699     struct ds ds = DS_EMPTY_INITIALIZER;
1700     bool error = false;
1701
1702     struct dpctl_params dpctl_p = {
1703         .is_appctl = true,
1704         .output = dpctl_unixctl_print,
1705         .aux = &ds,
1706     };
1707
1708     /* Parse options (like getopt). Unfortunately it does
1709      * not seem a good idea to call getopt_long() here, since it uses global
1710      * variables */
1711     while (argc > 1 && !error) {
1712         const char *arg = argv[1];
1713         if (!strncmp(arg, "--", 2)) {
1714             /* Long option */
1715             if (!strcmp(arg, "--statistics")) {
1716                 dpctl_p.print_statistics = true;
1717             } else if (!strcmp(arg, "--clear")) {
1718                 dpctl_p.zero_statistics = true;
1719             } else if (!strcmp(arg, "--may-create")) {
1720                 dpctl_p.may_create = true;
1721             } else if (!strcmp(arg, "--more")) {
1722                 dpctl_p.verbosity++;
1723             } else {
1724                 ds_put_format(&ds, "Unrecognized option %s", argv[1]);
1725                 error = true;
1726             }
1727         } else if (arg[0] == '-' && arg[1] != '\0') {
1728             /* Short option[s] */
1729             const char *opt = &arg[1];
1730
1731             while (*opt && !error) {
1732                 switch (*opt) {
1733                 case 'm':
1734                     dpctl_p.verbosity++;
1735                     break;
1736                 case 's':
1737                     dpctl_p.print_statistics = true;
1738                     break;
1739                 default:
1740                     ds_put_format(&ds, "Unrecognized option -%c", *opt);
1741                     error = true;
1742                     break;
1743                 }
1744                 opt++;
1745             }
1746         } else {
1747             /* Doesn't start with -, not an option */
1748             break;
1749         }
1750
1751         if (error) {
1752             break;
1753         }
1754         argv++;
1755         argc--;
1756     }
1757
1758     if (!error) {
1759         dpctl_command_handler *handler = (dpctl_command_handler *) aux;
1760         error = handler(argc, argv, &dpctl_p) != 0;
1761     }
1762
1763     if (error) {
1764         unixctl_command_reply_error(conn, ds_cstr(&ds));
1765     } else {
1766         unixctl_command_reply(conn, ds_cstr(&ds));
1767     }
1768
1769     ds_destroy(&ds);
1770 }
1771
1772 void
1773 dpctl_unixctl_register(void)
1774 {
1775     const struct dpctl_command *p;
1776
1777     for (p = all_commands; p->name != NULL; p++) {
1778         if (strcmp(p->name, "help")) {
1779             char *cmd_name = xasprintf("dpctl/%s", p->name);
1780             unixctl_command_register(cmd_name, "", p->min_args, p->max_args,
1781                                      dpctl_unixctl_handler, p->handler);
1782             free(cmd_name);
1783         }
1784     }
1785 }