Merge 'next' into 'master'.
[sliver-openvswitch.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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
19 #include "ofproto/private.h"
20
21 #include <errno.h>
22
23 #include "autopath.h"
24 #include "bond.h"
25 #include "byte-order.h"
26 #include "connmgr.h"
27 #include "coverage.h"
28 #include "cfm.h"
29 #include "dpif.h"
30 #include "dynamic-string.h"
31 #include "fail-open.h"
32 #include "hmapx.h"
33 #include "lacp.h"
34 #include "mac-learning.h"
35 #include "multipath.h"
36 #include "netdev.h"
37 #include "netlink.h"
38 #include "nx-match.h"
39 #include "odp-util.h"
40 #include "ofp-util.h"
41 #include "ofpbuf.h"
42 #include "ofp-print.h"
43 #include "ofproto-sflow.h"
44 #include "poll-loop.h"
45 #include "timer.h"
46 #include "unaligned.h"
47 #include "unixctl.h"
48 #include "vlan-bitmap.h"
49 #include "vlog.h"
50
51 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
52
53 COVERAGE_DEFINE(ofproto_dpif_ctlr_action);
54 COVERAGE_DEFINE(ofproto_dpif_expired);
55 COVERAGE_DEFINE(ofproto_dpif_no_packet_in);
56 COVERAGE_DEFINE(ofproto_dpif_xlate);
57 COVERAGE_DEFINE(facet_changed_rule);
58 COVERAGE_DEFINE(facet_invalidated);
59 COVERAGE_DEFINE(facet_revalidate);
60 COVERAGE_DEFINE(facet_unexpected);
61
62 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
63  * flow translation. */
64 #define MAX_RESUBMIT_RECURSION 16
65
66 struct ofport_dpif;
67 struct ofproto_dpif;
68
69 struct rule_dpif {
70     struct rule up;
71
72     long long int used;         /* Time last used; time created if not used. */
73
74     /* These statistics:
75      *
76      *   - Do include packets and bytes from facets that have been deleted or
77      *     whose own statistics have been folded into the rule.
78      *
79      *   - Do include packets and bytes sent "by hand" that were accounted to
80      *     the rule without any facet being involved (this is a rare corner
81      *     case in rule_execute()).
82      *
83      *   - Do not include packet or bytes that can be obtained from any facet's
84      *     packet_count or byte_count member or that can be obtained from the
85      *     datapath by, e.g., dpif_flow_get() for any facet.
86      */
87     uint64_t packet_count;       /* Number of packets received. */
88     uint64_t byte_count;         /* Number of bytes received. */
89
90     struct list facets;          /* List of "struct facet"s. */
91 };
92
93 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
94 {
95     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
96 }
97
98 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *ofproto,
99                                           const struct flow *flow);
100
101 #define MAX_MIRRORS 32
102 typedef uint32_t mirror_mask_t;
103 #define MIRROR_MASK_C(X) UINT32_C(X)
104 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
105 struct ofmirror {
106     struct ofproto_dpif *ofproto; /* Owning ofproto. */
107     size_t idx;                 /* In ofproto's "mirrors" array. */
108     void *aux;                  /* Key supplied by ofproto's client. */
109     char *name;                 /* Identifier for log messages. */
110
111     /* Selection criteria. */
112     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
113     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
114     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
115
116     /* Output (mutually exclusive). */
117     struct ofbundle *out;       /* Output port or NULL. */
118     int out_vlan;               /* Output VLAN or -1. */
119 };
120
121 static void mirror_destroy(struct ofmirror *);
122
123 /* A group of one or more OpenFlow ports. */
124 #define OFBUNDLE_FLOOD ((struct ofbundle *) 1)
125 struct ofbundle {
126     struct ofproto_dpif *ofproto; /* Owning ofproto. */
127     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
128     void *aux;                  /* Key supplied by ofproto's client. */
129     char *name;                 /* Identifier for log messages. */
130
131     /* Configuration. */
132     struct list ports;          /* Contains "struct ofport"s. */
133     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
134     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
135                                  * NULL if all VLANs are trunked. */
136     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
137     struct bond *bond;          /* Nonnull iff more than one port. */
138
139     /* Status. */
140     bool floodable;             /* True if no port has OFPPC_NO_FLOOD set. */
141
142     /* Port mirroring info. */
143     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
144     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
145     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
146 };
147
148 static void bundle_remove(struct ofport *);
149 static void bundle_destroy(struct ofbundle *);
150 static void bundle_del_port(struct ofport_dpif *);
151 static void bundle_run(struct ofbundle *);
152 static void bundle_wait(struct ofbundle *);
153
154 struct action_xlate_ctx {
155 /* action_xlate_ctx_init() initializes these members. */
156
157     /* The ofproto. */
158     struct ofproto_dpif *ofproto;
159
160     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
161      * this flow when actions change header fields. */
162     struct flow flow;
163
164     /* The packet corresponding to 'flow', or a null pointer if we are
165      * revalidating without a packet to refer to. */
166     const struct ofpbuf *packet;
167
168     /* If nonnull, called just before executing a resubmit action.
169      *
170      * This is normally null so the client has to set it manually after
171      * calling action_xlate_ctx_init(). */
172     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *);
173
174 /* xlate_actions() initializes and uses these members.  The client might want
175  * to look at them after it returns. */
176
177     struct ofpbuf *odp_actions; /* Datapath actions. */
178     tag_type tags;              /* Tags associated with OFPP_NORMAL actions. */
179     bool may_set_up_flow;       /* True ordinarily; false if the actions must
180                                  * be reassessed for every packet. */
181     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
182
183 /* xlate_actions() initializes and uses these members, but the client has no
184  * reason to look at them. */
185
186     int recurse;                /* Recursion level, via xlate_table_action. */
187     int last_pop_priority;      /* Offset in 'odp_actions' just past most
188                                  * recent ODP_ACTION_ATTR_SET_PRIORITY. */
189 };
190
191 static void action_xlate_ctx_init(struct action_xlate_ctx *,
192                                   struct ofproto_dpif *, const struct flow *,
193                                   const struct ofpbuf *);
194 static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
195                                     const union ofp_action *in, size_t n_in);
196
197 /* An exact-match instantiation of an OpenFlow flow. */
198 struct facet {
199     long long int used;         /* Time last used; time created if not used. */
200
201     /* These statistics:
202      *
203      *   - Do include packets and bytes sent "by hand", e.g. with
204      *     dpif_execute().
205      *
206      *   - Do include packets and bytes that were obtained from the datapath
207      *     when a flow was deleted (e.g. dpif_flow_del()) or when its
208      *     statistics were reset (e.g. dpif_flow_put() with
209      *     DPIF_FP_ZERO_STATS).
210      *
211      *   - Do not include any packets or bytes that can currently be obtained
212      *     from the datapath by, e.g., dpif_flow_get().
213      */
214     uint64_t packet_count;       /* Number of packets received. */
215     uint64_t byte_count;         /* Number of bytes received. */
216
217     uint64_t dp_packet_count;    /* Last known packet count in the datapath. */
218     uint64_t dp_byte_count;      /* Last known byte count in the datapath. */
219
220     uint64_t rs_packet_count;    /* Packets pushed to resubmit children. */
221     uint64_t rs_byte_count;      /* Bytes pushed to resubmit children. */
222     long long int rs_used;       /* Used time pushed to resubmit children. */
223
224     /* Number of bytes passed to account_cb.  This may include bytes that can
225      * currently obtained from the datapath (thus, it can be greater than
226      * byte_count). */
227     uint64_t accounted_bytes;
228
229     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
230     struct list list_node;       /* In owning rule's 'facets' list. */
231     struct rule_dpif *rule;      /* Owning rule. */
232     struct flow flow;            /* Exact-match flow. */
233     bool installed;              /* Installed in datapath? */
234     bool may_install;            /* True ordinarily; false if actions must
235                                   * be reassessed for every packet. */
236     size_t actions_len;          /* Number of bytes in actions[]. */
237     struct nlattr *actions;      /* Datapath actions. */
238     tag_type tags;               /* Tags. */
239     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
240 };
241
242 static struct facet *facet_create(struct rule_dpif *, const struct flow *,
243                                   const struct ofpbuf *packet);
244 static void facet_remove(struct ofproto_dpif *, struct facet *);
245 static void facet_free(struct facet *);
246
247 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
248 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
249                                         const struct flow *);
250 static bool facet_revalidate(struct ofproto_dpif *, struct facet *);
251
252 static void facet_execute(struct ofproto_dpif *, struct facet *,
253                           struct ofpbuf *packet);
254
255 static int facet_put__(struct ofproto_dpif *, struct facet *,
256                        const struct nlattr *actions, size_t actions_len,
257                        struct dpif_flow_stats *);
258 static void facet_install(struct ofproto_dpif *, struct facet *,
259                           bool zero_stats);
260 static void facet_uninstall(struct ofproto_dpif *, struct facet *);
261 static void facet_flush_stats(struct ofproto_dpif *, struct facet *);
262
263 static void facet_make_actions(struct ofproto_dpif *, struct facet *,
264                                const struct ofpbuf *packet);
265 static void facet_update_time(struct ofproto_dpif *, struct facet *,
266                               long long int used);
267 static void facet_update_stats(struct ofproto_dpif *, struct facet *,
268                                const struct dpif_flow_stats *);
269 static void facet_push_stats(struct facet *);
270 static void facet_account(struct ofproto_dpif *, struct facet *,
271                           uint64_t extra_bytes);
272
273 static bool facet_is_controller_flow(struct facet *);
274
275 static void flow_push_stats(const struct rule_dpif *,
276                             struct flow *, uint64_t packets, uint64_t bytes,
277                             long long int used);
278
279 struct ofport_dpif {
280     struct ofport up;
281
282     uint32_t odp_port;
283     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
284     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
285     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
286     tag_type tag;               /* Tag associated with this port. */
287     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
288 };
289
290 static struct ofport_dpif *
291 ofport_dpif_cast(const struct ofport *ofport)
292 {
293     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
294     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
295 }
296
297 static void port_run(struct ofport_dpif *);
298 static void port_wait(struct ofport_dpif *);
299 static int set_cfm(struct ofport *, const struct cfm *,
300                    const uint16_t *remote_mps, size_t n_remote_mps);
301
302 struct ofproto_dpif {
303     struct ofproto up;
304     struct dpif *dpif;
305     int max_ports;
306
307     /* Statistics. */
308     uint64_t n_matches;
309
310     /* Bridging. */
311     struct netflow *netflow;
312     struct ofproto_sflow *sflow;
313     struct hmap bundles;        /* Contains "struct ofbundle"s. */
314     struct mac_learning *ml;
315     struct ofmirror *mirrors[MAX_MIRRORS];
316     bool has_bonded_bundles;
317
318     /* Expiration. */
319     struct timer next_expiration;
320
321     /* Facets. */
322     struct hmap facets;
323     bool need_revalidate;
324     struct tag_set revalidate_set;
325 };
326
327 static void ofproto_dpif_unixctl_init(void);
328
329 static struct ofproto_dpif *
330 ofproto_dpif_cast(const struct ofproto *ofproto)
331 {
332     assert(ofproto->ofproto_class == &ofproto_dpif_class);
333     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
334 }
335
336 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
337                                         uint16_t ofp_port);
338 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
339                                         uint32_t odp_port);
340
341 /* Packet processing. */
342 static void update_learning_table(struct ofproto_dpif *,
343                                   const struct flow *, int vlan,
344                                   struct ofbundle *);
345 static bool is_admissible(struct ofproto_dpif *, const struct flow *,
346                           bool have_packet, tag_type *, int *vlanp,
347                           struct ofbundle **in_bundlep);
348 static void handle_upcall(struct ofproto_dpif *, struct dpif_upcall *);
349
350 /* Flow expiration. */
351 static int expire(struct ofproto_dpif *);
352
353 /* Utilities. */
354 static int send_packet(struct ofproto_dpif *, uint32_t odp_port,
355                        const struct ofpbuf *packet);
356
357 /* Global variables. */
358 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
359 \f
360 /* Factory functions. */
361
362 static void
363 enumerate_types(struct sset *types)
364 {
365     dp_enumerate_types(types);
366 }
367
368 static int
369 enumerate_names(const char *type, struct sset *names)
370 {
371     return dp_enumerate_names(type, names);
372 }
373
374 static int
375 del(const char *type, const char *name)
376 {
377     struct dpif *dpif;
378     int error;
379
380     error = dpif_open(name, type, &dpif);
381     if (!error) {
382         error = dpif_delete(dpif);
383         dpif_close(dpif);
384     }
385     return error;
386 }
387 \f
388 /* Basic life-cycle. */
389
390 static struct ofproto *
391 alloc(void)
392 {
393     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
394     return &ofproto->up;
395 }
396
397 static void
398 dealloc(struct ofproto *ofproto_)
399 {
400     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
401     free(ofproto);
402 }
403
404 static int
405 construct(struct ofproto *ofproto_)
406 {
407     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
408     const char *name = ofproto->up.name;
409     int error;
410     int i;
411
412     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
413     if (error) {
414         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
415         return error;
416     }
417
418     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
419     ofproto->n_matches = 0;
420
421     error = dpif_recv_set_mask(ofproto->dpif,
422                                ((1u << DPIF_UC_MISS) |
423                                 (1u << DPIF_UC_ACTION) |
424                                 (1u << DPIF_UC_SAMPLE)));
425     if (error) {
426         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
427         dpif_close(ofproto->dpif);
428         return error;
429     }
430     dpif_flow_flush(ofproto->dpif);
431     dpif_recv_purge(ofproto->dpif);
432
433     ofproto->netflow = NULL;
434     ofproto->sflow = NULL;
435     hmap_init(&ofproto->bundles);
436     ofproto->ml = mac_learning_create();
437     for (i = 0; i < MAX_MIRRORS; i++) {
438         ofproto->mirrors[i] = NULL;
439     }
440     ofproto->has_bonded_bundles = false;
441
442     timer_set_duration(&ofproto->next_expiration, 1000);
443
444     hmap_init(&ofproto->facets);
445     ofproto->need_revalidate = false;
446     tag_set_init(&ofproto->revalidate_set);
447
448     ofproto->up.tables = xmalloc(sizeof *ofproto->up.tables);
449     classifier_init(&ofproto->up.tables[0]);
450     ofproto->up.n_tables = 1;
451
452     ofproto_dpif_unixctl_init();
453
454     return 0;
455 }
456
457 static void
458 destruct(struct ofproto *ofproto_)
459 {
460     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
461     int i;
462
463     for (i = 0; i < MAX_MIRRORS; i++) {
464         mirror_destroy(ofproto->mirrors[i]);
465     }
466
467     netflow_destroy(ofproto->netflow);
468     ofproto_sflow_destroy(ofproto->sflow);
469     hmap_destroy(&ofproto->bundles);
470     mac_learning_destroy(ofproto->ml);
471
472     hmap_destroy(&ofproto->facets);
473
474     dpif_close(ofproto->dpif);
475 }
476
477 static int
478 run(struct ofproto *ofproto_)
479 {
480     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
481     struct ofport_dpif *ofport;
482     struct ofbundle *bundle;
483     int i;
484
485     dpif_run(ofproto->dpif);
486
487     for (i = 0; i < 50; i++) {
488         struct dpif_upcall packet;
489         int error;
490
491         error = dpif_recv(ofproto->dpif, &packet);
492         if (error) {
493             if (error == ENODEV) {
494                 /* Datapath destroyed. */
495                 return error;
496             }
497             break;
498         }
499
500         handle_upcall(ofproto, &packet);
501     }
502
503     if (timer_expired(&ofproto->next_expiration)) {
504         int delay = expire(ofproto);
505         timer_set_duration(&ofproto->next_expiration, delay);
506     }
507
508     if (ofproto->netflow) {
509         netflow_run(ofproto->netflow);
510     }
511     if (ofproto->sflow) {
512         ofproto_sflow_run(ofproto->sflow);
513     }
514
515     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
516         port_run(ofport);
517     }
518     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
519         bundle_run(bundle);
520     }
521
522     /* Now revalidate if there's anything to do. */
523     if (ofproto->need_revalidate
524         || !tag_set_is_empty(&ofproto->revalidate_set)) {
525         struct tag_set revalidate_set = ofproto->revalidate_set;
526         bool revalidate_all = ofproto->need_revalidate;
527         struct facet *facet, *next;
528
529         /* Clear the revalidation flags. */
530         tag_set_init(&ofproto->revalidate_set);
531         ofproto->need_revalidate = false;
532
533         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &ofproto->facets) {
534             if (revalidate_all
535                 || tag_set_intersects(&revalidate_set, facet->tags)) {
536                 facet_revalidate(ofproto, facet);
537             }
538         }
539     }
540
541     return 0;
542 }
543
544 static void
545 wait(struct ofproto *ofproto_)
546 {
547     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
548     struct ofport_dpif *ofport;
549     struct ofbundle *bundle;
550
551     dpif_wait(ofproto->dpif);
552     dpif_recv_wait(ofproto->dpif);
553     if (ofproto->sflow) {
554         ofproto_sflow_wait(ofproto->sflow);
555     }
556     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
557         poll_immediate_wake();
558     }
559     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
560         port_wait(ofport);
561     }
562     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
563         bundle_wait(bundle);
564     }
565     if (ofproto->need_revalidate) {
566         /* Shouldn't happen, but if it does just go around again. */
567         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
568         poll_immediate_wake();
569     } else {
570         timer_wait(&ofproto->next_expiration);
571     }
572 }
573
574 static void
575 flush(struct ofproto *ofproto_)
576 {
577     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
578     struct facet *facet, *next_facet;
579
580     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
581         /* Mark the facet as not installed so that facet_remove() doesn't
582          * bother trying to uninstall it.  There is no point in uninstalling it
583          * individually since we are about to blow away all the facets with
584          * dpif_flow_flush(). */
585         facet->installed = false;
586         facet->dp_packet_count = 0;
587         facet->dp_byte_count = 0;
588         facet_remove(ofproto, facet);
589     }
590     dpif_flow_flush(ofproto->dpif);
591 }
592
593 static void
594 get_features(struct ofproto *ofproto_ OVS_UNUSED,
595              bool *arp_match_ip, uint32_t *actions)
596 {
597     *arp_match_ip = true;
598     *actions = ((1u << OFPAT_OUTPUT) |
599                 (1u << OFPAT_SET_VLAN_VID) |
600                 (1u << OFPAT_SET_VLAN_PCP) |
601                 (1u << OFPAT_STRIP_VLAN) |
602                 (1u << OFPAT_SET_DL_SRC) |
603                 (1u << OFPAT_SET_DL_DST) |
604                 (1u << OFPAT_SET_NW_SRC) |
605                 (1u << OFPAT_SET_NW_DST) |
606                 (1u << OFPAT_SET_NW_TOS) |
607                 (1u << OFPAT_SET_TP_SRC) |
608                 (1u << OFPAT_SET_TP_DST) |
609                 (1u << OFPAT_ENQUEUE));
610 }
611
612 static void
613 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
614 {
615     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
616     struct odp_stats s;
617
618     strcpy(ots->name, "classifier");
619
620     dpif_get_dp_stats(ofproto->dpif, &s);
621     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
622     put_32aligned_be64(&ots->matched_count,
623                        htonll(s.n_hit + ofproto->n_matches));
624 }
625
626 static int
627 set_netflow(struct ofproto *ofproto_,
628             const struct netflow_options *netflow_options)
629 {
630     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
631
632     if (netflow_options) {
633         if (!ofproto->netflow) {
634             ofproto->netflow = netflow_create();
635         }
636         return netflow_set_options(ofproto->netflow, netflow_options);
637     } else {
638         netflow_destroy(ofproto->netflow);
639         ofproto->netflow = NULL;
640         return 0;
641     }
642 }
643
644 static struct ofport *
645 port_alloc(void)
646 {
647     struct ofport_dpif *port = xmalloc(sizeof *port);
648     return &port->up;
649 }
650
651 static void
652 port_dealloc(struct ofport *port_)
653 {
654     struct ofport_dpif *port = ofport_dpif_cast(port_);
655     free(port);
656 }
657
658 static int
659 port_construct(struct ofport *port_)
660 {
661     struct ofport_dpif *port = ofport_dpif_cast(port_);
662     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
663
664     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
665     port->bundle = NULL;
666     port->cfm = NULL;
667     port->tag = tag_create_random();
668
669     if (ofproto->sflow) {
670         ofproto_sflow_add_port(ofproto->sflow, port->odp_port,
671                                netdev_get_name(port->up.netdev));
672     }
673
674     return 0;
675 }
676
677 static void
678 port_destruct(struct ofport *port_)
679 {
680     struct ofport_dpif *port = ofport_dpif_cast(port_);
681     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
682
683     bundle_remove(port_);
684     set_cfm(port_, NULL, NULL, 0);
685     if (ofproto->sflow) {
686         ofproto_sflow_del_port(ofproto->sflow, port->odp_port);
687     }
688 }
689
690 static void
691 port_modified(struct ofport *port_)
692 {
693     struct ofport_dpif *port = ofport_dpif_cast(port_);
694
695     if (port->bundle && port->bundle->bond) {
696         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
697     }
698 }
699
700 static void
701 port_reconfigured(struct ofport *port_, ovs_be32 old_config)
702 {
703     struct ofport_dpif *port = ofport_dpif_cast(port_);
704     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
705     ovs_be32 changed = old_config ^ port->up.opp.config;
706
707     if (changed & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
708                         OFPPC_NO_FWD | OFPPC_NO_FLOOD)) {
709         ofproto->need_revalidate = true;
710     }
711 }
712
713 static int
714 set_sflow(struct ofproto *ofproto_,
715           const struct ofproto_sflow_options *sflow_options)
716 {
717     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
718     struct ofproto_sflow *os = ofproto->sflow;
719     if (sflow_options) {
720         if (!os) {
721             struct ofport_dpif *ofport;
722
723             os = ofproto->sflow = ofproto_sflow_create(ofproto->dpif);
724             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
725                 ofproto_sflow_add_port(os, ofport->odp_port,
726                                        netdev_get_name(ofport->up.netdev));
727             }
728         }
729         ofproto_sflow_set_options(os, sflow_options);
730     } else {
731         ofproto_sflow_destroy(os);
732         ofproto->sflow = NULL;
733     }
734     return 0;
735 }
736
737 static int
738 set_cfm(struct ofport *ofport_, const struct cfm *cfm,
739         const uint16_t *remote_mps, size_t n_remote_mps)
740 {
741     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
742     int error;
743
744     if (!cfm) {
745         error = 0;
746     } else {
747         if (!ofport->cfm) {
748             ofport->cfm = cfm_create();
749         }
750
751         ofport->cfm->mpid = cfm->mpid;
752         ofport->cfm->interval = cfm->interval;
753         memcpy(ofport->cfm->maid, cfm->maid, CCM_MAID_LEN);
754
755         cfm_update_remote_mps(ofport->cfm, remote_mps, n_remote_mps);
756
757         if (cfm_configure(ofport->cfm)) {
758             return 0;
759         }
760
761         error = EINVAL;
762     }
763     cfm_destroy(ofport->cfm);
764     ofport->cfm = NULL;
765     return error;
766 }
767
768 static int
769 get_cfm(struct ofport *ofport_, const struct cfm **cfmp)
770 {
771     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
772     *cfmp = ofport->cfm;
773     return 0;
774 }
775 \f
776 /* Bundles. */
777
778 /* Expires all MAC learning entries associated with 'port' and forces ofproto
779  * to revalidate every flow. */
780 static void
781 bundle_flush_macs(struct ofbundle *bundle)
782 {
783     struct ofproto_dpif *ofproto = bundle->ofproto;
784     struct mac_learning *ml = ofproto->ml;
785     struct mac_entry *mac, *next_mac;
786
787     ofproto->need_revalidate = true;
788     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
789         if (mac->port.p == bundle) {
790             mac_learning_expire(ml, mac);
791         }
792     }
793 }
794
795 static struct ofbundle *
796 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
797 {
798     struct ofbundle *bundle;
799
800     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
801                              &ofproto->bundles) {
802         if (bundle->aux == aux) {
803             return bundle;
804         }
805     }
806     return NULL;
807 }
808
809 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
810  * ones that are found to 'bundles'. */
811 static void
812 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
813                        void **auxes, size_t n_auxes,
814                        struct hmapx *bundles)
815 {
816     size_t i;
817
818     hmapx_init(bundles);
819     for (i = 0; i < n_auxes; i++) {
820         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
821         if (bundle) {
822             hmapx_add(bundles, bundle);
823         }
824     }
825 }
826
827 static void
828 bundle_del_port(struct ofport_dpif *port)
829 {
830     struct ofbundle *bundle = port->bundle;
831
832     bundle->ofproto->need_revalidate = true;
833
834     list_remove(&port->bundle_node);
835     port->bundle = NULL;
836
837     if (bundle->lacp) {
838         lacp_slave_unregister(bundle->lacp, port);
839     }
840     if (bundle->bond) {
841         bond_slave_unregister(bundle->bond, port);
842     }
843
844     bundle->floodable = true;
845     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
846         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)) {
847             bundle->floodable = false;
848         }
849     }
850 }
851
852 static bool
853 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
854                 struct lacp_slave_settings *lacp,
855                 uint32_t bond_stable_id)
856 {
857     struct ofport_dpif *port;
858
859     port = get_ofp_port(bundle->ofproto, ofp_port);
860     if (!port) {
861         return false;
862     }
863
864     if (port->bundle != bundle) {
865         bundle->ofproto->need_revalidate = true;
866         if (port->bundle) {
867             bundle_del_port(port);
868         }
869
870         port->bundle = bundle;
871         list_push_back(&bundle->ports, &port->bundle_node);
872         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)) {
873             bundle->floodable = false;
874         }
875     }
876     if (lacp) {
877         lacp_slave_register(bundle->lacp, port, lacp);
878     }
879
880     port->bond_stable_id = bond_stable_id;
881
882     return true;
883 }
884
885 static void
886 bundle_destroy(struct ofbundle *bundle)
887 {
888     struct ofproto_dpif *ofproto;
889     struct ofport_dpif *port, *next_port;
890     int i;
891
892     if (!bundle) {
893         return;
894     }
895
896     ofproto = bundle->ofproto;
897     for (i = 0; i < MAX_MIRRORS; i++) {
898         struct ofmirror *m = ofproto->mirrors[i];
899         if (m) {
900             if (m->out == bundle) {
901                 mirror_destroy(m);
902             } else if (hmapx_find_and_delete(&m->srcs, bundle)
903                        || hmapx_find_and_delete(&m->dsts, bundle)) {
904                 ofproto->need_revalidate = true;
905             }
906         }
907     }
908
909     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
910         bundle_del_port(port);
911     }
912
913     bundle_flush_macs(bundle);
914     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
915     free(bundle->name);
916     free(bundle->trunks);
917     lacp_destroy(bundle->lacp);
918     bond_destroy(bundle->bond);
919     free(bundle);
920 }
921
922 static int
923 bundle_set(struct ofproto *ofproto_, void *aux,
924            const struct ofproto_bundle_settings *s)
925 {
926     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
927     bool need_flush = false;
928     const unsigned long *trunks;
929     struct ofport_dpif *port;
930     struct ofbundle *bundle;
931     size_t i;
932     bool ok;
933
934     if (!s) {
935         bundle_destroy(bundle_lookup(ofproto, aux));
936         return 0;
937     }
938
939     assert(s->n_slaves == 1 || s->bond != NULL);
940     assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
941
942     bundle = bundle_lookup(ofproto, aux);
943     if (!bundle) {
944         bundle = xmalloc(sizeof *bundle);
945
946         bundle->ofproto = ofproto;
947         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
948                     hash_pointer(aux, 0));
949         bundle->aux = aux;
950         bundle->name = NULL;
951
952         list_init(&bundle->ports);
953         bundle->vlan = -1;
954         bundle->trunks = NULL;
955         bundle->lacp = NULL;
956         bundle->bond = NULL;
957
958         bundle->floodable = true;
959
960         bundle->src_mirrors = 0;
961         bundle->dst_mirrors = 0;
962         bundle->mirror_out = 0;
963     }
964
965     if (!bundle->name || strcmp(s->name, bundle->name)) {
966         free(bundle->name);
967         bundle->name = xstrdup(s->name);
968     }
969
970     /* LACP. */
971     if (s->lacp) {
972         if (!bundle->lacp) {
973             bundle->lacp = lacp_create();
974         }
975         lacp_configure(bundle->lacp, s->lacp);
976     } else {
977         lacp_destroy(bundle->lacp);
978         bundle->lacp = NULL;
979     }
980
981     /* Update set of ports. */
982     ok = true;
983     for (i = 0; i < s->n_slaves; i++) {
984         if (!bundle_add_port(bundle, s->slaves[i],
985                              s->lacp ? &s->lacp_slaves[i] : NULL,
986                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
987             ok = false;
988         }
989     }
990     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
991         struct ofport_dpif *next_port;
992
993         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
994             for (i = 0; i < s->n_slaves; i++) {
995                 if (s->slaves[i] == port->up.ofp_port) {
996                     goto found;
997                 }
998             }
999
1000             bundle_del_port(port);
1001         found: ;
1002         }
1003     }
1004     assert(list_size(&bundle->ports) <= s->n_slaves);
1005
1006     if (list_is_empty(&bundle->ports)) {
1007         bundle_destroy(bundle);
1008         return EINVAL;
1009     }
1010
1011     /* Set VLAN tag. */
1012     if (s->vlan != bundle->vlan) {
1013         bundle->vlan = s->vlan;
1014         need_flush = true;
1015     }
1016
1017     /* Get trunked VLANs. */
1018     trunks = s->vlan == -1 ? NULL : s->trunks;
1019     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
1020         free(bundle->trunks);
1021         bundle->trunks = vlan_bitmap_clone(trunks);
1022         need_flush = true;
1023     }
1024
1025     /* Bonding. */
1026     if (!list_is_short(&bundle->ports)) {
1027         bundle->ofproto->has_bonded_bundles = true;
1028         if (bundle->bond) {
1029             if (bond_reconfigure(bundle->bond, s->bond)) {
1030                 ofproto->need_revalidate = true;
1031             }
1032         } else {
1033             bundle->bond = bond_create(s->bond);
1034             ofproto->need_revalidate = true;
1035         }
1036
1037         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1038             bond_slave_register(bundle->bond, port, port->bond_stable_id,
1039                                 port->up.netdev);
1040         }
1041     } else {
1042         bond_destroy(bundle->bond);
1043         bundle->bond = NULL;
1044     }
1045
1046     /* If we changed something that would affect MAC learning, un-learn
1047      * everything on this port and force flow revalidation. */
1048     if (need_flush) {
1049         bundle_flush_macs(bundle);
1050     }
1051
1052     return 0;
1053 }
1054
1055 static void
1056 bundle_remove(struct ofport *port_)
1057 {
1058     struct ofport_dpif *port = ofport_dpif_cast(port_);
1059     struct ofbundle *bundle = port->bundle;
1060
1061     if (bundle) {
1062         bundle_del_port(port);
1063         if (list_is_empty(&bundle->ports)) {
1064             bundle_destroy(bundle);
1065         } else if (list_is_short(&bundle->ports)) {
1066             bond_destroy(bundle->bond);
1067             bundle->bond = NULL;
1068         }
1069     }
1070 }
1071
1072 static void
1073 send_pdu_cb(void *port_, const struct lacp_pdu *pdu)
1074 {
1075     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1076     struct ofport_dpif *port = port_;
1077     uint8_t ea[ETH_ADDR_LEN];
1078     int error;
1079
1080     error = netdev_get_etheraddr(port->up.netdev, ea);
1081     if (!error) {
1082         struct lacp_pdu *packet_pdu;
1083         struct ofpbuf packet;
1084
1085         ofpbuf_init(&packet, 0);
1086         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
1087                                  sizeof *packet_pdu);
1088         *packet_pdu = *pdu;
1089         error = netdev_send(port->up.netdev, &packet);
1090         if (error) {
1091             VLOG_WARN_RL(&rl, "port %s: sending LACP PDU on iface %s failed "
1092                          "(%s)", port->bundle->name,
1093                          netdev_get_name(port->up.netdev), strerror(error));
1094         }
1095         ofpbuf_uninit(&packet);
1096     } else {
1097         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
1098                     "%s (%s)", port->bundle->name,
1099                     netdev_get_name(port->up.netdev), strerror(error));
1100     }
1101 }
1102
1103 static void
1104 bundle_send_learning_packets(struct ofbundle *bundle)
1105 {
1106     struct ofproto_dpif *ofproto = bundle->ofproto;
1107     int error, n_packets, n_errors;
1108     struct mac_entry *e;
1109
1110     error = n_packets = n_errors = 0;
1111     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
1112         if (e->port.p != bundle) {
1113             int ret = bond_send_learning_packet(bundle->bond, e->mac, e->vlan);
1114             if (ret) {
1115                 error = ret;
1116                 n_errors++;
1117             }
1118             n_packets++;
1119         }
1120     }
1121
1122     if (n_errors) {
1123         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1124         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
1125                      "packets, last error was: %s",
1126                      bundle->name, n_errors, n_packets, strerror(error));
1127     } else {
1128         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
1129                  bundle->name, n_packets);
1130     }
1131 }
1132
1133 static void
1134 bundle_run(struct ofbundle *bundle)
1135 {
1136     if (bundle->lacp) {
1137         lacp_run(bundle->lacp, send_pdu_cb);
1138     }
1139     if (bundle->bond) {
1140         struct ofport_dpif *port;
1141
1142         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1143             bool may_enable = lacp_slave_may_enable(bundle->lacp, port);
1144             bond_slave_set_lacp_may_enable(bundle->bond, port, may_enable);
1145         }
1146
1147         bond_run(bundle->bond, &bundle->ofproto->revalidate_set,
1148                  lacp_negotiated(bundle->lacp));
1149         if (bond_should_send_learning_packets(bundle->bond)) {
1150             bundle_send_learning_packets(bundle);
1151         }
1152     }
1153 }
1154
1155 static void
1156 bundle_wait(struct ofbundle *bundle)
1157 {
1158     if (bundle->lacp) {
1159         lacp_wait(bundle->lacp);
1160     }
1161     if (bundle->bond) {
1162         bond_wait(bundle->bond);
1163     }
1164 }
1165 \f
1166 /* Mirrors. */
1167
1168 static int
1169 mirror_scan(struct ofproto_dpif *ofproto)
1170 {
1171     int idx;
1172
1173     for (idx = 0; idx < MAX_MIRRORS; idx++) {
1174         if (!ofproto->mirrors[idx]) {
1175             return idx;
1176         }
1177     }
1178     return -1;
1179 }
1180
1181 static struct ofmirror *
1182 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
1183 {
1184     int i;
1185
1186     for (i = 0; i < MAX_MIRRORS; i++) {
1187         struct ofmirror *mirror = ofproto->mirrors[i];
1188         if (mirror && mirror->aux == aux) {
1189             return mirror;
1190         }
1191     }
1192
1193     return NULL;
1194 }
1195
1196 static int
1197 mirror_set(struct ofproto *ofproto_, void *aux,
1198            const struct ofproto_mirror_settings *s)
1199 {
1200     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1201     mirror_mask_t mirror_bit;
1202     struct ofbundle *bundle;
1203     struct ofmirror *mirror;
1204     struct ofbundle *out;
1205     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
1206     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
1207     int out_vlan;
1208
1209     mirror = mirror_lookup(ofproto, aux);
1210     if (!s) {
1211         mirror_destroy(mirror);
1212         return 0;
1213     }
1214     if (!mirror) {
1215         int idx;
1216
1217         idx = mirror_scan(ofproto);
1218         if (idx < 0) {
1219             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
1220                       "cannot create %s",
1221                       ofproto->up.name, MAX_MIRRORS, s->name);
1222             return EFBIG;
1223         }
1224
1225         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
1226         mirror->ofproto = ofproto;
1227         mirror->idx = idx;
1228         mirror->out_vlan = -1;
1229         mirror->name = NULL;
1230     }
1231
1232     if (!mirror->name || strcmp(s->name, mirror->name)) {
1233         free(mirror->name);
1234         mirror->name = xstrdup(s->name);
1235     }
1236
1237     /* Get the new configuration. */
1238     if (s->out_bundle) {
1239         out = bundle_lookup(ofproto, s->out_bundle);
1240         if (!out) {
1241             mirror_destroy(mirror);
1242             return EINVAL;
1243         }
1244         out_vlan = -1;
1245     } else {
1246         out = NULL;
1247         out_vlan = s->out_vlan;
1248     }
1249     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
1250     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
1251
1252     /* If the configuration has not changed, do nothing. */
1253     if (hmapx_equals(&srcs, &mirror->srcs)
1254         && hmapx_equals(&dsts, &mirror->dsts)
1255         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
1256         && mirror->out == out
1257         && mirror->out_vlan == out_vlan)
1258     {
1259         hmapx_destroy(&srcs);
1260         hmapx_destroy(&dsts);
1261         return 0;
1262     }
1263
1264     hmapx_swap(&srcs, &mirror->srcs);
1265     hmapx_destroy(&srcs);
1266
1267     hmapx_swap(&dsts, &mirror->dsts);
1268     hmapx_destroy(&dsts);
1269
1270     free(mirror->vlans);
1271     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
1272
1273     mirror->out = out;
1274     mirror->out_vlan = out_vlan;
1275
1276     /* Update bundles. */
1277     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1278     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
1279         if (hmapx_contains(&mirror->srcs, bundle)) {
1280             bundle->src_mirrors |= mirror_bit;
1281         } else {
1282             bundle->src_mirrors &= ~mirror_bit;
1283         }
1284
1285         if (hmapx_contains(&mirror->dsts, bundle)) {
1286             bundle->dst_mirrors |= mirror_bit;
1287         } else {
1288             bundle->dst_mirrors &= ~mirror_bit;
1289         }
1290
1291         if (mirror->out == bundle) {
1292             bundle->mirror_out |= mirror_bit;
1293         } else {
1294             bundle->mirror_out &= ~mirror_bit;
1295         }
1296     }
1297
1298     ofproto->need_revalidate = true;
1299     mac_learning_flush(ofproto->ml);
1300
1301     return 0;
1302 }
1303
1304 static void
1305 mirror_destroy(struct ofmirror *mirror)
1306 {
1307     struct ofproto_dpif *ofproto;
1308     mirror_mask_t mirror_bit;
1309     struct ofbundle *bundle;
1310
1311     if (!mirror) {
1312         return;
1313     }
1314
1315     ofproto = mirror->ofproto;
1316     ofproto->need_revalidate = true;
1317     mac_learning_flush(ofproto->ml);
1318
1319     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1320     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1321         bundle->src_mirrors &= ~mirror_bit;
1322         bundle->dst_mirrors &= ~mirror_bit;
1323         bundle->mirror_out &= ~mirror_bit;
1324     }
1325
1326     hmapx_destroy(&mirror->srcs);
1327     hmapx_destroy(&mirror->dsts);
1328     free(mirror->vlans);
1329
1330     ofproto->mirrors[mirror->idx] = NULL;
1331     free(mirror->name);
1332     free(mirror);
1333 }
1334
1335 static int
1336 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
1337 {
1338     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1339     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
1340         ofproto->need_revalidate = true;
1341         mac_learning_flush(ofproto->ml);
1342     }
1343     return 0;
1344 }
1345
1346 static bool
1347 is_mirror_output_bundle(struct ofproto *ofproto_, void *aux)
1348 {
1349     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1350     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
1351     return bundle && bundle->mirror_out != 0;
1352 }
1353 \f
1354 /* Ports. */
1355
1356 static struct ofport_dpif *
1357 get_ofp_port(struct ofproto_dpif *ofproto, uint16_t ofp_port)
1358 {
1359     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
1360     return ofport ? ofport_dpif_cast(ofport) : NULL;
1361 }
1362
1363 static struct ofport_dpif *
1364 get_odp_port(struct ofproto_dpif *ofproto, uint32_t odp_port)
1365 {
1366     return get_ofp_port(ofproto, odp_port_to_ofp_port(odp_port));
1367 }
1368
1369 static void
1370 ofproto_port_from_dpif_port(struct ofproto_port *ofproto_port,
1371                             struct dpif_port *dpif_port)
1372 {
1373     ofproto_port->name = dpif_port->name;
1374     ofproto_port->type = dpif_port->type;
1375     ofproto_port->ofp_port = odp_port_to_ofp_port(dpif_port->port_no);
1376 }
1377
1378 static void
1379 port_run(struct ofport_dpif *ofport)
1380 {
1381     if (ofport->cfm) {
1382         cfm_run(ofport->cfm);
1383
1384         if (cfm_should_send_ccm(ofport->cfm)) {
1385             struct ofpbuf packet;
1386             struct ccm *ccm;
1387
1388             ofpbuf_init(&packet, 0);
1389             ccm = eth_compose(&packet, eth_addr_ccm, ofport->up.opp.hw_addr,
1390                               ETH_TYPE_CFM, sizeof *ccm);
1391             cfm_compose_ccm(ofport->cfm, ccm);
1392             send_packet(ofproto_dpif_cast(ofport->up.ofproto),
1393                         ofport->odp_port, &packet);
1394             ofpbuf_uninit(&packet);
1395         }
1396     }
1397 }
1398
1399 static void
1400 port_wait(struct ofport_dpif *ofport)
1401 {
1402     if (ofport->cfm) {
1403         cfm_wait(ofport->cfm);
1404     }
1405 }
1406
1407 static int
1408 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
1409                    struct ofproto_port *ofproto_port)
1410 {
1411     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1412     struct dpif_port dpif_port;
1413     int error;
1414
1415     error = dpif_port_query_by_name(ofproto->dpif, devname, &dpif_port);
1416     if (!error) {
1417         ofproto_port_from_dpif_port(ofproto_port, &dpif_port);
1418     }
1419     return error;
1420 }
1421
1422 static int
1423 port_add(struct ofproto *ofproto_, struct netdev *netdev, uint16_t *ofp_portp)
1424 {
1425     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1426     uint16_t odp_port;
1427     int error;
1428
1429     error = dpif_port_add(ofproto->dpif, netdev, &odp_port);
1430     if (!error) {
1431         *ofp_portp = odp_port_to_ofp_port(odp_port);
1432     }
1433     return error;
1434 }
1435
1436 static int
1437 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
1438 {
1439     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1440     int error;
1441
1442     error = dpif_port_del(ofproto->dpif, ofp_port_to_odp_port(ofp_port));
1443     if (!error) {
1444         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
1445         if (ofport) {
1446             /* The caller is going to close ofport->up.netdev.  If this is a
1447              * bonded port, then the bond is using that netdev, so remove it
1448              * from the bond.  The client will need to reconfigure everything
1449              * after deleting ports, so then the slave will get re-added. */
1450             bundle_remove(&ofport->up);
1451         }
1452     }
1453     return error;
1454 }
1455
1456 struct port_dump_state {
1457     struct dpif_port_dump dump;
1458     bool done;
1459 };
1460
1461 static int
1462 port_dump_start(const struct ofproto *ofproto_, void **statep)
1463 {
1464     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1465     struct port_dump_state *state;
1466
1467     *statep = state = xmalloc(sizeof *state);
1468     dpif_port_dump_start(&state->dump, ofproto->dpif);
1469     state->done = false;
1470     return 0;
1471 }
1472
1473 static int
1474 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
1475                struct ofproto_port *port)
1476 {
1477     struct port_dump_state *state = state_;
1478     struct dpif_port dpif_port;
1479
1480     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
1481         ofproto_port_from_dpif_port(port, &dpif_port);
1482         return 0;
1483     } else {
1484         int error = dpif_port_dump_done(&state->dump);
1485         state->done = true;
1486         return error ? error : EOF;
1487     }
1488 }
1489
1490 static int
1491 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
1492 {
1493     struct port_dump_state *state = state_;
1494
1495     if (!state->done) {
1496         dpif_port_dump_done(&state->dump);
1497     }
1498     free(state);
1499     return 0;
1500 }
1501
1502 static int
1503 port_poll(const struct ofproto *ofproto_, char **devnamep)
1504 {
1505     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1506     return dpif_port_poll(ofproto->dpif, devnamep);
1507 }
1508
1509 static void
1510 port_poll_wait(const struct ofproto *ofproto_)
1511 {
1512     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1513     dpif_port_poll_wait(ofproto->dpif);
1514 }
1515
1516 static int
1517 port_is_lacp_current(const struct ofport *ofport_)
1518 {
1519     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1520     return (ofport->bundle && ofport->bundle->lacp
1521             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
1522             : -1);
1523 }
1524 \f
1525 /* Upcall handling. */
1526
1527 /* Given 'upcall', of type DPIF_UC_ACTION or DPIF_UC_MISS, sends an
1528  * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
1529  * their individual configurations.
1530  *
1531  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
1532  * Otherwise, ownership is transferred to this function. */
1533 static void
1534 send_packet_in(struct ofproto_dpif *ofproto, struct dpif_upcall *upcall,
1535                const struct flow *flow, bool clone)
1536 {
1537     struct ofputil_packet_in pin;
1538
1539     pin.packet = upcall->packet;
1540     pin.in_port = flow->in_port;
1541     pin.reason = upcall->type == DPIF_UC_MISS ? OFPR_NO_MATCH : OFPR_ACTION;
1542     pin.buffer_id = 0;          /* not yet known */
1543     pin.send_len = upcall->userdata;
1544     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
1545                            clone ? NULL : upcall->packet);
1546 }
1547
1548 static bool
1549 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
1550                 const struct ofpbuf *packet)
1551 {
1552     if (cfm_should_process_flow(flow)) {
1553         struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
1554         if (ofport && ofport->cfm) {
1555             cfm_process_heartbeat(ofport->cfm, packet);
1556         }
1557         return true;
1558     } else if (flow->dl_type == htons(ETH_TYPE_LACP)) {
1559         struct ofport_dpif *port = get_ofp_port(ofproto, flow->in_port);
1560         if (port && port->bundle && port->bundle->lacp) {
1561             const struct lacp_pdu *pdu = parse_lacp_packet(packet);
1562             if (pdu) {
1563                 lacp_process_pdu(port->bundle->lacp, port, pdu);
1564             }
1565             return true;
1566         }
1567     }
1568     return false;
1569 }
1570
1571 static void
1572 handle_miss_upcall(struct ofproto_dpif *ofproto, struct dpif_upcall *upcall)
1573 {
1574     struct facet *facet;
1575     struct flow flow;
1576
1577     /* Obtain in_port and tun_id, at least. */
1578     odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
1579
1580     /* Set header pointers in 'flow'. */
1581     flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
1582
1583     /* Handle 802.1ag and LACP. */
1584     if (process_special(ofproto, &flow, upcall->packet)) {
1585         ofpbuf_delete(upcall->packet);
1586         ofproto->n_matches++;
1587         return;
1588     }
1589
1590     /* Check with in-band control to see if this packet should be sent
1591      * to the local port regardless of the flow table. */
1592     if (connmgr_msg_in_hook(ofproto->up.connmgr, &flow, upcall->packet)) {
1593         send_packet(ofproto, OFPP_LOCAL, upcall->packet);
1594     }
1595
1596     facet = facet_lookup_valid(ofproto, &flow);
1597     if (!facet) {
1598         struct rule_dpif *rule = rule_dpif_lookup(ofproto, &flow);
1599         if (!rule) {
1600             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
1601             struct ofport_dpif *port = get_ofp_port(ofproto, flow.in_port);
1602             if (port) {
1603                 if (port->up.opp.config & htonl(OFPPC_NO_PACKET_IN)) {
1604                     COVERAGE_INC(ofproto_dpif_no_packet_in);
1605                     /* XXX install 'drop' flow entry */
1606                     ofpbuf_delete(upcall->packet);
1607                     return;
1608                 }
1609             } else {
1610                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
1611                              flow.in_port);
1612             }
1613
1614             send_packet_in(ofproto, upcall, &flow, false);
1615             return;
1616         }
1617
1618         facet = facet_create(rule, &flow, upcall->packet);
1619     } else if (!facet->may_install) {
1620         /* The facet is not installable, that is, we need to process every
1621          * packet, so process the current packet's actions into 'facet'. */
1622         facet_make_actions(ofproto, facet, upcall->packet);
1623     }
1624
1625     if (facet->rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
1626         /*
1627          * Extra-special case for fail-open mode.
1628          *
1629          * We are in fail-open mode and the packet matched the fail-open rule,
1630          * but we are connected to a controller too.  We should send the packet
1631          * up to the controller in the hope that it will try to set up a flow
1632          * and thereby allow us to exit fail-open.
1633          *
1634          * See the top-level comment in fail-open.c for more information.
1635          */
1636         send_packet_in(ofproto, upcall, &flow, true);
1637     }
1638
1639     facet_execute(ofproto, facet, upcall->packet);
1640     facet_install(ofproto, facet, false);
1641     ofproto->n_matches++;
1642 }
1643
1644 static void
1645 handle_upcall(struct ofproto_dpif *ofproto, struct dpif_upcall *upcall)
1646 {
1647     struct flow flow;
1648
1649     switch (upcall->type) {
1650     case DPIF_UC_ACTION:
1651         COVERAGE_INC(ofproto_dpif_ctlr_action);
1652         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
1653         send_packet_in(ofproto, upcall, &flow, false);
1654         break;
1655
1656     case DPIF_UC_SAMPLE:
1657         if (ofproto->sflow) {
1658             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
1659             ofproto_sflow_received(ofproto->sflow, upcall, &flow);
1660         }
1661         ofpbuf_delete(upcall->packet);
1662         break;
1663
1664     case DPIF_UC_MISS:
1665         handle_miss_upcall(ofproto, upcall);
1666         break;
1667
1668     case DPIF_N_UC_TYPES:
1669     default:
1670         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
1671         break;
1672     }
1673 }
1674 \f
1675 /* Flow expiration. */
1676
1677 static int facet_max_idle(const struct ofproto_dpif *);
1678 static void update_stats(struct ofproto_dpif *);
1679 static void rule_expire(struct rule_dpif *);
1680 static void expire_facets(struct ofproto_dpif *, int dp_max_idle);
1681
1682 /* This function is called periodically by run().  Its job is to collect
1683  * updates for the flows that have been installed into the datapath, most
1684  * importantly when they last were used, and then use that information to
1685  * expire flows that have not been used recently.
1686  *
1687  * Returns the number of milliseconds after which it should be called again. */
1688 static int
1689 expire(struct ofproto_dpif *ofproto)
1690 {
1691     struct rule_dpif *rule, *next_rule;
1692     struct cls_cursor cursor;
1693     int dp_max_idle;
1694
1695     /* Update stats for each flow in the datapath. */
1696     update_stats(ofproto);
1697
1698     /* Expire facets that have been idle too long. */
1699     dp_max_idle = facet_max_idle(ofproto);
1700     expire_facets(ofproto, dp_max_idle);
1701
1702     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
1703     cls_cursor_init(&cursor, &ofproto->up.tables[0], NULL);
1704     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1705         rule_expire(rule);
1706     }
1707
1708     /* All outstanding data in existing flows has been accounted, so it's a
1709      * good time to do bond rebalancing. */
1710     if (ofproto->has_bonded_bundles) {
1711         struct ofbundle *bundle;
1712
1713         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1714             if (bundle->bond) {
1715                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
1716             }
1717         }
1718     }
1719
1720     return MIN(dp_max_idle, 1000);
1721 }
1722
1723 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
1724  *
1725  * This function also pushes statistics updates to rules which each facet
1726  * resubmits into.  Generally these statistics will be accurate.  However, if a
1727  * facet changes the rule it resubmits into at some time in between
1728  * update_stats() runs, it is possible that statistics accrued to the
1729  * old rule will be incorrectly attributed to the new rule.  This could be
1730  * avoided by calling update_stats() whenever rules are created or
1731  * deleted.  However, the performance impact of making so many calls to the
1732  * datapath do not justify the benefit of having perfectly accurate statistics.
1733  */
1734 static void
1735 update_stats(struct ofproto_dpif *p)
1736 {
1737     const struct dpif_flow_stats *stats;
1738     struct dpif_flow_dump dump;
1739     const struct nlattr *key;
1740     size_t key_len;
1741
1742     dpif_flow_dump_start(&dump, p->dpif);
1743     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
1744         struct facet *facet;
1745         struct flow flow;
1746
1747         if (odp_flow_key_to_flow(key, key_len, &flow)) {
1748             struct ds s;
1749
1750             ds_init(&s);
1751             odp_flow_key_format(key, key_len, &s);
1752             VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
1753                          ds_cstr(&s));
1754             ds_destroy(&s);
1755
1756             continue;
1757         }
1758         facet = facet_find(p, &flow);
1759
1760         if (facet && facet->installed) {
1761
1762             if (stats->n_packets >= facet->dp_packet_count) {
1763                 uint64_t extra = stats->n_packets - facet->dp_packet_count;
1764                 facet->packet_count += extra;
1765             } else {
1766                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
1767             }
1768
1769             if (stats->n_bytes >= facet->dp_byte_count) {
1770                 facet->byte_count += stats->n_bytes - facet->dp_byte_count;
1771             } else {
1772                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
1773             }
1774
1775             facet->dp_packet_count = stats->n_packets;
1776             facet->dp_byte_count = stats->n_bytes;
1777
1778             facet_update_time(p, facet, stats->used);
1779             facet_account(p, facet, stats->n_bytes);
1780             facet_push_stats(facet);
1781         } else {
1782             /* There's a flow in the datapath that we know nothing about.
1783              * Delete it. */
1784             COVERAGE_INC(facet_unexpected);
1785             dpif_flow_del(p->dpif, key, key_len, NULL);
1786         }
1787     }
1788     dpif_flow_dump_done(&dump);
1789 }
1790
1791 /* Calculates and returns the number of milliseconds of idle time after which
1792  * facets should expire from the datapath and we should fold their statistics
1793  * into their parent rules in userspace. */
1794 static int
1795 facet_max_idle(const struct ofproto_dpif *ofproto)
1796 {
1797     /*
1798      * Idle time histogram.
1799      *
1800      * Most of the time a switch has a relatively small number of facets.  When
1801      * this is the case we might as well keep statistics for all of them in
1802      * userspace and to cache them in the kernel datapath for performance as
1803      * well.
1804      *
1805      * As the number of facets increases, the memory required to maintain
1806      * statistics about them in userspace and in the kernel becomes
1807      * significant.  However, with a large number of facets it is likely that
1808      * only a few of them are "heavy hitters" that consume a large amount of
1809      * bandwidth.  At this point, only heavy hitters are worth caching in the
1810      * kernel and maintaining in userspaces; other facets we can discard.
1811      *
1812      * The technique used to compute the idle time is to build a histogram with
1813      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
1814      * that is installed in the kernel gets dropped in the appropriate bucket.
1815      * After the histogram has been built, we compute the cutoff so that only
1816      * the most-recently-used 1% of facets (but at least 1000 flows) are kept
1817      * cached.  At least the most-recently-used bucket of facets is kept, so
1818      * actually an arbitrary number of facets can be kept in any given
1819      * expiration run (though the next run will delete most of those unless
1820      * they receive additional data).
1821      *
1822      * This requires a second pass through the facets, in addition to the pass
1823      * made by update_stats(), because the former function never looks
1824      * at uninstallable facets.
1825      */
1826     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
1827     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
1828     int buckets[N_BUCKETS] = { 0 };
1829     struct facet *facet;
1830     int total, bucket;
1831     long long int now;
1832     int i;
1833
1834     total = hmap_count(&ofproto->facets);
1835     if (total <= 1000) {
1836         return N_BUCKETS * BUCKET_WIDTH;
1837     }
1838
1839     /* Build histogram. */
1840     now = time_msec();
1841     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
1842         long long int idle = now - facet->used;
1843         int bucket = (idle <= 0 ? 0
1844                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
1845                       : (unsigned int) idle / BUCKET_WIDTH);
1846         buckets[bucket]++;
1847     }
1848
1849     /* Find the first bucket whose flows should be expired. */
1850     for (bucket = 0; bucket < N_BUCKETS; bucket++) {
1851         if (buckets[bucket]) {
1852             int subtotal = 0;
1853             do {
1854                 subtotal += buckets[bucket++];
1855             } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
1856             break;
1857         }
1858     }
1859
1860     if (VLOG_IS_DBG_ENABLED()) {
1861         struct ds s;
1862
1863         ds_init(&s);
1864         ds_put_cstr(&s, "keep");
1865         for (i = 0; i < N_BUCKETS; i++) {
1866             if (i == bucket) {
1867                 ds_put_cstr(&s, ", drop");
1868             }
1869             if (buckets[i]) {
1870                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
1871             }
1872         }
1873         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
1874         ds_destroy(&s);
1875     }
1876
1877     return bucket * BUCKET_WIDTH;
1878 }
1879
1880 static void
1881 facet_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
1882 {
1883     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
1884         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
1885         struct ofexpired expired;
1886
1887         if (facet->installed) {
1888             struct dpif_flow_stats stats;
1889
1890             facet_put__(ofproto, facet, facet->actions, facet->actions_len,
1891                         &stats);
1892             facet_update_stats(ofproto, facet, &stats);
1893         }
1894
1895         expired.flow = facet->flow;
1896         expired.packet_count = facet->packet_count;
1897         expired.byte_count = facet->byte_count;
1898         expired.used = facet->used;
1899         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
1900     }
1901 }
1902
1903 static void
1904 expire_facets(struct ofproto_dpif *ofproto, int dp_max_idle)
1905 {
1906     long long int cutoff = time_msec() - dp_max_idle;
1907     struct facet *facet, *next_facet;
1908
1909     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1910         facet_active_timeout(ofproto, facet);
1911         if (facet->used < cutoff) {
1912             facet_remove(ofproto, facet);
1913         }
1914     }
1915 }
1916
1917 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
1918  * then delete it entirely. */
1919 static void
1920 rule_expire(struct rule_dpif *rule)
1921 {
1922     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
1923     struct facet *facet, *next_facet;
1924     long long int now;
1925     uint8_t reason;
1926
1927     /* Has 'rule' expired? */
1928     now = time_msec();
1929     if (rule->up.hard_timeout
1930         && now > rule->up.created + rule->up.hard_timeout * 1000) {
1931         reason = OFPRR_HARD_TIMEOUT;
1932     } else if (rule->up.idle_timeout && list_is_empty(&rule->facets)
1933                && now > rule->used + rule->up.idle_timeout * 1000) {
1934         reason = OFPRR_IDLE_TIMEOUT;
1935     } else {
1936         return;
1937     }
1938
1939     COVERAGE_INC(ofproto_dpif_expired);
1940
1941     /* Update stats.  (This is a no-op if the rule expired due to an idle
1942      * timeout, because that only happens when the rule has no facets left.) */
1943     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
1944         facet_remove(ofproto, facet);
1945     }
1946
1947     /* Get rid of the rule. */
1948     ofproto_rule_expire(&rule->up, reason);
1949 }
1950 \f
1951 /* Facets. */
1952
1953 /* Creates and returns a new facet owned by 'rule', given a 'flow' and an
1954  * example 'packet' within that flow.
1955  *
1956  * The caller must already have determined that no facet with an identical
1957  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
1958  * the ofproto's classifier table. */
1959 static struct facet *
1960 facet_create(struct rule_dpif *rule, const struct flow *flow,
1961              const struct ofpbuf *packet)
1962 {
1963     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
1964     struct facet *facet;
1965
1966     facet = xzalloc(sizeof *facet);
1967     facet->used = time_msec();
1968     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
1969     list_push_back(&rule->facets, &facet->list_node);
1970     facet->rule = rule;
1971     facet->flow = *flow;
1972     netflow_flow_init(&facet->nf_flow);
1973     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
1974
1975     facet_make_actions(ofproto, facet, packet);
1976
1977     return facet;
1978 }
1979
1980 static void
1981 facet_free(struct facet *facet)
1982 {
1983     free(facet->actions);
1984     free(facet);
1985 }
1986
1987 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
1988  * 'packet', which arrived on 'in_port'.
1989  *
1990  * Takes ownership of 'packet'. */
1991 static bool
1992 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
1993                     const struct nlattr *odp_actions, size_t actions_len,
1994                     struct ofpbuf *packet)
1995 {
1996     if (actions_len == NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t))
1997         && odp_actions->nla_type == ODP_ACTION_ATTR_CONTROLLER) {
1998         /* As an optimization, avoid a round-trip from userspace to kernel to
1999          * userspace.  This also avoids possibly filling up kernel packet
2000          * buffers along the way. */
2001         struct dpif_upcall upcall;
2002
2003         upcall.type = DPIF_UC_ACTION;
2004         upcall.packet = packet;
2005         upcall.key = NULL;
2006         upcall.key_len = 0;
2007         upcall.userdata = nl_attr_get_u64(odp_actions);
2008         upcall.sample_pool = 0;
2009         upcall.actions = NULL;
2010         upcall.actions_len = 0;
2011
2012         send_packet_in(ofproto, &upcall, flow, false);
2013
2014         return true;
2015     } else {
2016         int error;
2017
2018         error = dpif_execute(ofproto->dpif, odp_actions, actions_len, packet);
2019         ofpbuf_delete(packet);
2020         return !error;
2021     }
2022 }
2023
2024 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2025  * statistics appropriately.  'packet' must have at least sizeof(struct
2026  * ofp_packet_in) bytes of headroom.
2027  *
2028  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2029  * applying flow_extract() to 'packet' would yield the same flow as
2030  * 'facet->flow'.
2031  *
2032  * 'facet' must have accurately composed ODP actions; that is, it must not be
2033  * in need of revalidation.
2034  *
2035  * Takes ownership of 'packet'. */
2036 static void
2037 facet_execute(struct ofproto_dpif *ofproto, struct facet *facet,
2038               struct ofpbuf *packet)
2039 {
2040     struct dpif_flow_stats stats;
2041
2042     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2043
2044     flow_extract_stats(&facet->flow, packet, &stats);
2045     stats.used = time_msec();
2046     if (execute_odp_actions(ofproto, &facet->flow,
2047                             facet->actions, facet->actions_len, packet)) {
2048         facet_update_stats(ofproto, facet, &stats);
2049     }
2050 }
2051
2052 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2053  *
2054  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2055  *     rule's statistics, via facet_uninstall().
2056  *
2057  *   - Removes 'facet' from its rule and from ofproto->facets.
2058  */
2059 static void
2060 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
2061 {
2062     facet_uninstall(ofproto, facet);
2063     facet_flush_stats(ofproto, facet);
2064     hmap_remove(&ofproto->facets, &facet->hmap_node);
2065     list_remove(&facet->list_node);
2066     facet_free(facet);
2067 }
2068
2069 /* Composes the ODP actions for 'facet' based on its rule's actions. */
2070 static void
2071 facet_make_actions(struct ofproto_dpif *p, struct facet *facet,
2072                    const struct ofpbuf *packet)
2073 {
2074     const struct rule_dpif *rule = facet->rule;
2075     struct ofpbuf *odp_actions;
2076     struct action_xlate_ctx ctx;
2077
2078     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2079     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
2080     facet->tags = ctx.tags;
2081     facet->may_install = ctx.may_set_up_flow;
2082     facet->nf_flow.output_iface = ctx.nf_output_iface;
2083
2084     if (facet->actions_len != odp_actions->size
2085         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2086         free(facet->actions);
2087         facet->actions_len = odp_actions->size;
2088         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2089     }
2090
2091     ofpbuf_delete(odp_actions);
2092 }
2093
2094 static int
2095 facet_put__(struct ofproto_dpif *ofproto, struct facet *facet,
2096             const struct nlattr *actions, size_t actions_len,
2097             struct dpif_flow_stats *stats)
2098 {
2099     struct odputil_keybuf keybuf;
2100     enum dpif_flow_put_flags flags;
2101     struct ofpbuf key;
2102
2103     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2104     if (stats) {
2105         flags |= DPIF_FP_ZERO_STATS;
2106         facet->dp_packet_count = 0;
2107         facet->dp_byte_count = 0;
2108     }
2109
2110     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2111     odp_flow_key_from_flow(&key, &facet->flow);
2112
2113     return dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2114                          actions, actions_len, stats);
2115 }
2116
2117 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2118  * 'zero_stats' is true, clears any existing statistics from the datapath for
2119  * 'facet'. */
2120 static void
2121 facet_install(struct ofproto_dpif *p, struct facet *facet, bool zero_stats)
2122 {
2123     struct dpif_flow_stats stats;
2124
2125     if (facet->may_install
2126         && !facet_put__(p, facet, facet->actions, facet->actions_len,
2127                         zero_stats ? &stats : NULL)) {
2128         facet->installed = true;
2129     }
2130 }
2131
2132 static void
2133 facet_account(struct ofproto_dpif *ofproto,
2134               struct facet *facet, uint64_t extra_bytes)
2135 {
2136     uint64_t total_bytes, n_bytes;
2137     struct ofbundle *in_bundle;
2138     const struct nlattr *a;
2139     tag_type dummy = 0;
2140     unsigned int left;
2141     int vlan;
2142
2143     total_bytes = facet->byte_count + extra_bytes;
2144     if (total_bytes <= facet->accounted_bytes) {
2145         return;
2146     }
2147     n_bytes = total_bytes - facet->accounted_bytes;
2148     facet->accounted_bytes = total_bytes;
2149
2150     /* Test that 'tags' is nonzero to ensure that only flows that include an
2151      * OFPP_NORMAL action are used for learning and bond slave rebalancing.
2152      * This works because OFPP_NORMAL always sets a nonzero tag value.
2153      *
2154      * Feed information from the active flows back into the learning table to
2155      * ensure that table is always in sync with what is actually flowing
2156      * through the datapath. */
2157     if (!facet->tags
2158         || !is_admissible(ofproto, &facet->flow, false, &dummy,
2159                           &vlan, &in_bundle)) {
2160         return;
2161     }
2162
2163     update_learning_table(ofproto, &facet->flow, vlan, in_bundle);
2164
2165     if (!ofproto->has_bonded_bundles) {
2166         return;
2167     }
2168     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->actions, facet->actions_len) {
2169         if (nl_attr_type(a) == ODP_ACTION_ATTR_OUTPUT) {
2170             struct ofport_dpif *port;
2171
2172             port = get_odp_port(ofproto, nl_attr_get_u32(a));
2173             if (port && port->bundle && port->bundle->bond) {
2174                 bond_account(port->bundle->bond, &facet->flow, vlan, n_bytes);
2175             }
2176         }
2177     }
2178 }
2179
2180 /* If 'rule' is installed in the datapath, uninstalls it. */
2181 static void
2182 facet_uninstall(struct ofproto_dpif *p, struct facet *facet)
2183 {
2184     if (facet->installed) {
2185         struct odputil_keybuf keybuf;
2186         struct dpif_flow_stats stats;
2187         struct ofpbuf key;
2188
2189         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2190         odp_flow_key_from_flow(&key, &facet->flow);
2191
2192         if (!dpif_flow_del(p->dpif, key.data, key.size, &stats)) {
2193             facet_update_stats(p, facet, &stats);
2194         }
2195         facet->installed = false;
2196         facet->dp_packet_count = 0;
2197         facet->dp_byte_count = 0;
2198     } else {
2199         assert(facet->dp_packet_count == 0);
2200         assert(facet->dp_byte_count == 0);
2201     }
2202 }
2203
2204 /* Returns true if the only action for 'facet' is to send to the controller.
2205  * (We don't report NetFlow expiration messages for such facets because they
2206  * are just part of the control logic for the network, not real traffic). */
2207 static bool
2208 facet_is_controller_flow(struct facet *facet)
2209 {
2210     return (facet
2211             && facet->rule->up.n_actions == 1
2212             && action_outputs_to_port(&facet->rule->up.actions[0],
2213                                       htons(OFPP_CONTROLLER)));
2214 }
2215
2216 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2217  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
2218  * 'facet''s statistics in the datapath should have been zeroed and folded into
2219  * its packet and byte counts before this function is called. */
2220 static void
2221 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
2222 {
2223     assert(!facet->dp_byte_count);
2224     assert(!facet->dp_packet_count);
2225
2226     facet_push_stats(facet);
2227     facet_account(ofproto, facet, 0);
2228
2229     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2230         struct ofexpired expired;
2231         expired.flow = facet->flow;
2232         expired.packet_count = facet->packet_count;
2233         expired.byte_count = facet->byte_count;
2234         expired.used = facet->used;
2235         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2236     }
2237
2238     facet->rule->packet_count += facet->packet_count;
2239     facet->rule->byte_count += facet->byte_count;
2240
2241     /* Reset counters to prevent double counting if 'facet' ever gets
2242      * reinstalled. */
2243     facet->packet_count = 0;
2244     facet->byte_count = 0;
2245     facet->rs_packet_count = 0;
2246     facet->rs_byte_count = 0;
2247     facet->accounted_bytes = 0;
2248
2249     netflow_flow_clear(&facet->nf_flow);
2250 }
2251
2252 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2253  * Returns it if found, otherwise a null pointer.
2254  *
2255  * The returned facet might need revalidation; use facet_lookup_valid()
2256  * instead if that is important. */
2257 static struct facet *
2258 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
2259 {
2260     struct facet *facet;
2261
2262     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2263                              &ofproto->facets) {
2264         if (flow_equal(flow, &facet->flow)) {
2265             return facet;
2266         }
2267     }
2268
2269     return NULL;
2270 }
2271
2272 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2273  * Returns it if found, otherwise a null pointer.
2274  *
2275  * The returned facet is guaranteed to be valid. */
2276 static struct facet *
2277 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
2278 {
2279     struct facet *facet = facet_find(ofproto, flow);
2280
2281     /* The facet we found might not be valid, since we could be in need of
2282      * revalidation.  If it is not valid, don't return it. */
2283     if (facet
2284         && ofproto->need_revalidate
2285         && !facet_revalidate(ofproto, facet)) {
2286         COVERAGE_INC(facet_invalidated);
2287         return NULL;
2288     }
2289
2290     return facet;
2291 }
2292
2293 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2294  *
2295  *   - If the rule found is different from 'facet''s current rule, moves
2296  *     'facet' to the new rule and recompiles its actions.
2297  *
2298  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2299  *     where it is and recompiles its actions anyway.
2300  *
2301  *   - If there is none, destroys 'facet'.
2302  *
2303  * Returns true if 'facet' still exists, false if it has been destroyed. */
2304 static bool
2305 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
2306 {
2307     struct action_xlate_ctx ctx;
2308     struct ofpbuf *odp_actions;
2309     struct rule_dpif *new_rule;
2310     bool actions_changed;
2311
2312     COVERAGE_INC(facet_revalidate);
2313
2314     /* Determine the new rule. */
2315     new_rule = rule_dpif_lookup(ofproto, &facet->flow);
2316     if (!new_rule) {
2317         /* No new rule, so delete the facet. */
2318         facet_remove(ofproto, facet);
2319         return false;
2320     }
2321
2322     /* Calculate new ODP actions.
2323      *
2324      * We do not modify any 'facet' state yet, because we might need to, e.g.,
2325      * emit a NetFlow expiration and, if so, we need to have the old state
2326      * around to properly compose it. */
2327     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2328     odp_actions = xlate_actions(&ctx,
2329                                 new_rule->up.actions, new_rule->up.n_actions);
2330     actions_changed = (facet->actions_len != odp_actions->size
2331                        || memcmp(facet->actions, odp_actions->data,
2332                                  facet->actions_len));
2333
2334     /* If the ODP actions changed or the installability changed, then we need
2335      * to talk to the datapath. */
2336     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
2337         if (ctx.may_set_up_flow) {
2338             struct dpif_flow_stats stats;
2339
2340             facet_put__(ofproto, facet,
2341                         odp_actions->data, odp_actions->size, &stats);
2342             facet_update_stats(ofproto, facet, &stats);
2343         } else {
2344             facet_uninstall(ofproto, facet);
2345         }
2346
2347         /* The datapath flow is gone or has zeroed stats, so push stats out of
2348          * 'facet' into 'rule'. */
2349         facet_flush_stats(ofproto, facet);
2350     }
2351
2352     /* Update 'facet' now that we've taken care of all the old state. */
2353     facet->tags = ctx.tags;
2354     facet->nf_flow.output_iface = ctx.nf_output_iface;
2355     facet->may_install = ctx.may_set_up_flow;
2356     if (actions_changed) {
2357         free(facet->actions);
2358         facet->actions_len = odp_actions->size;
2359         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2360     }
2361     if (facet->rule != new_rule) {
2362         COVERAGE_INC(facet_changed_rule);
2363         list_remove(&facet->list_node);
2364         list_push_back(&new_rule->facets, &facet->list_node);
2365         facet->rule = new_rule;
2366         facet->used = new_rule->up.created;
2367         facet->rs_used = facet->used;
2368     }
2369
2370     ofpbuf_delete(odp_actions);
2371
2372     return true;
2373 }
2374
2375 /* Updates 'facet''s used time.  Caller is responsible for calling
2376  * facet_push_stats() to update the flows which 'facet' resubmits into. */
2377 static void
2378 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
2379                   long long int used)
2380 {
2381     if (used > facet->used) {
2382         facet->used = used;
2383         if (used > facet->rule->used) {
2384             facet->rule->used = used;
2385         }
2386         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
2387     }
2388 }
2389
2390 /* Folds the statistics from 'stats' into the counters in 'facet'.
2391  *
2392  * Because of the meaning of a facet's counters, it only makes sense to do this
2393  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
2394  * packet that was sent by hand or if it represents statistics that have been
2395  * cleared out of the datapath. */
2396 static void
2397 facet_update_stats(struct ofproto_dpif *ofproto, struct facet *facet,
2398                    const struct dpif_flow_stats *stats)
2399 {
2400     if (stats->n_packets || stats->used > facet->used) {
2401         facet_update_time(ofproto, facet, stats->used);
2402         facet->packet_count += stats->n_packets;
2403         facet->byte_count += stats->n_bytes;
2404         facet_push_stats(facet);
2405         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
2406     }
2407 }
2408
2409 static void
2410 facet_push_stats(struct facet *facet)
2411 {
2412     uint64_t rs_packets, rs_bytes;
2413
2414     assert(facet->packet_count >= facet->rs_packet_count);
2415     assert(facet->byte_count >= facet->rs_byte_count);
2416     assert(facet->used >= facet->rs_used);
2417
2418     rs_packets = facet->packet_count - facet->rs_packet_count;
2419     rs_bytes = facet->byte_count - facet->rs_byte_count;
2420
2421     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
2422         facet->rs_packet_count = facet->packet_count;
2423         facet->rs_byte_count = facet->byte_count;
2424         facet->rs_used = facet->used;
2425
2426         flow_push_stats(facet->rule, &facet->flow,
2427                         rs_packets, rs_bytes, facet->used);
2428     }
2429 }
2430
2431 struct ofproto_push {
2432     struct action_xlate_ctx ctx;
2433     uint64_t packets;
2434     uint64_t bytes;
2435     long long int used;
2436 };
2437
2438 static void
2439 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
2440 {
2441     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
2442
2443     if (rule) {
2444         rule->packet_count += push->packets;
2445         rule->byte_count += push->bytes;
2446         rule->used = MAX(push->used, rule->used);
2447     }
2448 }
2449
2450 /* Pushes flow statistics to the rules which 'flow' resubmits into given
2451  * 'rule''s actions. */
2452 static void
2453 flow_push_stats(const struct rule_dpif *rule,
2454                 struct flow *flow, uint64_t packets, uint64_t bytes,
2455                 long long int used)
2456 {
2457     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2458     struct ofproto_push push;
2459
2460     push.packets = packets;
2461     push.bytes = bytes;
2462     push.used = used;
2463
2464     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
2465     push.ctx.resubmit_hook = push_resubmit;
2466     ofpbuf_delete(xlate_actions(&push.ctx,
2467                                 rule->up.actions, rule->up.n_actions));
2468 }
2469 \f
2470 /* Rules. */
2471
2472 static struct rule_dpif *
2473 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow)
2474 {
2475     return rule_dpif_cast(rule_from_cls_rule(
2476                               classifier_lookup(&ofproto->up.tables[0],
2477                                                 flow)));
2478 }
2479
2480 static struct rule *
2481 rule_alloc(void)
2482 {
2483     struct rule_dpif *rule = xmalloc(sizeof *rule);
2484     return &rule->up;
2485 }
2486
2487 static void
2488 rule_dealloc(struct rule *rule_)
2489 {
2490     struct rule_dpif *rule = rule_dpif_cast(rule_);
2491     free(rule);
2492 }
2493
2494 static int
2495 rule_construct(struct rule *rule_)
2496 {
2497     struct rule_dpif *rule = rule_dpif_cast(rule_);
2498     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2499     struct rule_dpif *old_rule;
2500     int error;
2501
2502     error = validate_actions(rule->up.actions, rule->up.n_actions,
2503                              &rule->up.cr.flow, ofproto->max_ports);
2504     if (error) {
2505         return error;
2506     }
2507
2508     old_rule = rule_dpif_cast(rule_from_cls_rule(classifier_find_rule_exactly(
2509                                                      &ofproto->up.tables[0],
2510                                                      &rule->up.cr)));
2511     if (old_rule) {
2512         ofproto_rule_destroy(&old_rule->up);
2513     }
2514
2515     rule->used = rule->up.created;
2516     rule->packet_count = 0;
2517     rule->byte_count = 0;
2518     list_init(&rule->facets);
2519     classifier_insert(&ofproto->up.tables[0], &rule->up.cr);
2520
2521     ofproto->need_revalidate = true;
2522
2523     return 0;
2524 }
2525
2526 static void
2527 rule_destruct(struct rule *rule_)
2528 {
2529     struct rule_dpif *rule = rule_dpif_cast(rule_);
2530     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2531     struct facet *facet, *next_facet;
2532
2533     classifier_remove(&ofproto->up.tables[0], &rule->up.cr);
2534     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2535         facet_revalidate(ofproto, facet);
2536     }
2537     ofproto->need_revalidate = true;
2538 }
2539
2540 static void
2541 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
2542 {
2543     struct rule_dpif *rule = rule_dpif_cast(rule_);
2544     struct facet *facet;
2545
2546     /* Start from historical data for 'rule' itself that are no longer tracked
2547      * in facets.  This counts, for example, facets that have expired. */
2548     *packets = rule->packet_count;
2549     *bytes = rule->byte_count;
2550
2551     /* Add any statistics that are tracked by facets.  This includes
2552      * statistical data recently updated by ofproto_update_stats() as well as
2553      * stats for packets that were executed "by hand" via dpif_execute(). */
2554     LIST_FOR_EACH (facet, list_node, &rule->facets) {
2555         *packets += facet->packet_count;
2556         *bytes += facet->byte_count;
2557     }
2558 }
2559
2560 static int
2561 rule_execute(struct rule *rule_, struct flow *flow, struct ofpbuf *packet)
2562 {
2563     struct rule_dpif *rule = rule_dpif_cast(rule_);
2564     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2565     struct action_xlate_ctx ctx;
2566     struct ofpbuf *odp_actions;
2567     struct facet *facet;
2568     size_t size;
2569
2570     /* First look for a related facet.  If we find one, account it to that. */
2571     facet = facet_lookup_valid(ofproto, flow);
2572     if (facet && facet->rule == rule) {
2573         facet_execute(ofproto, facet, packet);
2574         return 0;
2575     }
2576
2577     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2578      * create a new facet for it and use that. */
2579     if (rule_dpif_lookup(ofproto, flow) == rule) {
2580         facet = facet_create(rule, flow, packet);
2581         facet_execute(ofproto, facet, packet);
2582         facet_install(ofproto, facet, true);
2583         return 0;
2584     }
2585
2586     /* We can't account anything to a facet.  If we were to try, then that
2587      * facet would have a non-matching rule, busting our invariants. */
2588     action_xlate_ctx_init(&ctx, ofproto, flow, packet);
2589     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
2590     size = packet->size;
2591     if (execute_odp_actions(ofproto, flow, odp_actions->data,
2592                             odp_actions->size, packet)) {
2593         rule->used = time_msec();
2594         rule->packet_count++;
2595         rule->byte_count += size;
2596         flow_push_stats(rule, flow, 1, size, rule->used);
2597     }
2598     ofpbuf_delete(odp_actions);
2599
2600     return 0;
2601 }
2602
2603 static int
2604 rule_modify_actions(struct rule *rule_,
2605                     const union ofp_action *actions, size_t n_actions)
2606 {
2607     struct rule_dpif *rule = rule_dpif_cast(rule_);
2608     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2609     int error;
2610
2611     error = validate_actions(actions, n_actions, &rule->up.cr.flow,
2612                              ofproto->max_ports);
2613     if (!error) {
2614         ofproto->need_revalidate = true;
2615     }
2616     return error;
2617 }
2618 \f
2619 /* Sends 'packet' out of port 'odp_port' within 'p'.
2620  * Returns 0 if successful, otherwise a positive errno value. */
2621 static int
2622 send_packet(struct ofproto_dpif *ofproto, uint32_t odp_port,
2623             const struct ofpbuf *packet)
2624 {
2625     struct ofpbuf odp_actions;
2626     int error;
2627
2628     ofpbuf_init(&odp_actions, 32);
2629     nl_msg_put_u32(&odp_actions, ODP_ACTION_ATTR_OUTPUT, odp_port);
2630     error = dpif_execute(ofproto->dpif, odp_actions.data, odp_actions.size,
2631                          packet);
2632     ofpbuf_uninit(&odp_actions);
2633
2634     if (error) {
2635         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
2636                      ofproto->up.name, odp_port, strerror(error));
2637     }
2638     return error;
2639 }
2640 \f
2641 /* OpenFlow to ODP action translation. */
2642
2643 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2644                              struct action_xlate_ctx *ctx);
2645 static bool xlate_normal(struct action_xlate_ctx *);
2646
2647 static void
2648 add_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
2649 {
2650     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
2651     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
2652
2653     if (ofport) {
2654         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)) {
2655             /* Forwarding disabled on port. */
2656             return;
2657         }
2658     } else {
2659         /*
2660          * We don't have an ofport record for this port, but it doesn't hurt to
2661          * allow forwarding to it anyhow.  Maybe such a port will appear later
2662          * and we're pre-populating the flow table.
2663          */
2664     }
2665
2666     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_OUTPUT, odp_port);
2667     ctx->nf_output_iface = ofp_port;
2668 }
2669
2670 static void
2671 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2672 {
2673     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2674         struct rule_dpif *rule;
2675         uint16_t old_in_port;
2676
2677         /* Look up a flow with 'in_port' as the input port.  Then restore the
2678          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2679          * have surprising behavior). */
2680         old_in_port = ctx->flow.in_port;
2681         ctx->flow.in_port = in_port;
2682         rule = rule_dpif_lookup(ctx->ofproto, &ctx->flow);
2683         ctx->flow.in_port = old_in_port;
2684
2685         if (ctx->resubmit_hook) {
2686             ctx->resubmit_hook(ctx, rule);
2687         }
2688
2689         if (rule) {
2690             ctx->recurse++;
2691             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
2692             ctx->recurse--;
2693         }
2694     } else {
2695         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2696
2697         VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2698                     MAX_RESUBMIT_RECURSION);
2699     }
2700 }
2701
2702 static void
2703 flood_packets(struct ofproto_dpif *ofproto,
2704               uint16_t ofp_in_port, ovs_be32 mask,
2705               uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
2706 {
2707     struct ofport_dpif *ofport;
2708
2709     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
2710         uint16_t ofp_port = ofport->up.ofp_port;
2711         if (ofp_port != ofp_in_port && !(ofport->up.opp.config & mask)) {
2712             nl_msg_put_u32(odp_actions, ODP_ACTION_ATTR_OUTPUT,
2713                            ofport->odp_port);
2714         }
2715     }
2716     *nf_output_iface = NF_OUT_FLOOD;
2717 }
2718
2719 static void
2720 xlate_output_action__(struct action_xlate_ctx *ctx,
2721                       uint16_t port, uint16_t max_len)
2722 {
2723     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2724
2725     ctx->nf_output_iface = NF_OUT_DROP;
2726
2727     switch (port) {
2728     case OFPP_IN_PORT:
2729         add_output_action(ctx, ctx->flow.in_port);
2730         break;
2731     case OFPP_TABLE:
2732         xlate_table_action(ctx, ctx->flow.in_port);
2733         break;
2734     case OFPP_NORMAL:
2735         xlate_normal(ctx);
2736         break;
2737     case OFPP_FLOOD:
2738         flood_packets(ctx->ofproto, ctx->flow.in_port, htonl(OFPPC_NO_FLOOD),
2739                       &ctx->nf_output_iface, ctx->odp_actions);
2740         break;
2741     case OFPP_ALL:
2742         flood_packets(ctx->ofproto, ctx->flow.in_port, htonl(0),
2743                       &ctx->nf_output_iface, ctx->odp_actions);
2744         break;
2745     case OFPP_CONTROLLER:
2746         nl_msg_put_u64(ctx->odp_actions, ODP_ACTION_ATTR_CONTROLLER, max_len);
2747         break;
2748     case OFPP_LOCAL:
2749         add_output_action(ctx, OFPP_LOCAL);
2750         break;
2751     default:
2752         if (port != ctx->flow.in_port) {
2753             add_output_action(ctx, port);
2754         }
2755         break;
2756     }
2757
2758     if (prev_nf_output_iface == NF_OUT_FLOOD) {
2759         ctx->nf_output_iface = NF_OUT_FLOOD;
2760     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2761         ctx->nf_output_iface = prev_nf_output_iface;
2762     } else if (prev_nf_output_iface != NF_OUT_DROP &&
2763                ctx->nf_output_iface != NF_OUT_FLOOD) {
2764         ctx->nf_output_iface = NF_OUT_MULTI;
2765     }
2766 }
2767
2768 static void
2769 xlate_output_action(struct action_xlate_ctx *ctx,
2770                     const struct ofp_action_output *oao)
2771 {
2772     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2773 }
2774
2775 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2776  * optimization, because we're going to add another action that sets the
2777  * priority immediately after, or because there are no actions following the
2778  * pop.  */
2779 static void
2780 remove_pop_action(struct action_xlate_ctx *ctx)
2781 {
2782     if (ctx->odp_actions->size == ctx->last_pop_priority) {
2783         ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2784         ctx->last_pop_priority = -1;
2785     }
2786 }
2787
2788 static void
2789 add_pop_action(struct action_xlate_ctx *ctx)
2790 {
2791     if (ctx->odp_actions->size != ctx->last_pop_priority) {
2792         nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_POP_PRIORITY);
2793         ctx->last_pop_priority = ctx->odp_actions->size;
2794     }
2795 }
2796
2797 static void
2798 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2799                      const struct ofp_action_enqueue *oae)
2800 {
2801     uint16_t ofp_port, odp_port;
2802     uint32_t priority;
2803     int error;
2804
2805     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2806                                    &priority);
2807     if (error) {
2808         /* Fall back to ordinary output action. */
2809         xlate_output_action__(ctx, ntohs(oae->port), 0);
2810         return;
2811     }
2812
2813     /* Figure out ODP output port. */
2814     ofp_port = ntohs(oae->port);
2815     if (ofp_port == OFPP_IN_PORT) {
2816         ofp_port = ctx->flow.in_port;
2817     }
2818     odp_port = ofp_port_to_odp_port(ofp_port);
2819
2820     /* Add ODP actions. */
2821     remove_pop_action(ctx);
2822     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_SET_PRIORITY, priority);
2823     add_output_action(ctx, odp_port);
2824     add_pop_action(ctx);
2825
2826     /* Update NetFlow output port. */
2827     if (ctx->nf_output_iface == NF_OUT_DROP) {
2828         ctx->nf_output_iface = odp_port;
2829     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2830         ctx->nf_output_iface = NF_OUT_MULTI;
2831     }
2832 }
2833
2834 static void
2835 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2836                        const struct nx_action_set_queue *nasq)
2837 {
2838     uint32_t priority;
2839     int error;
2840
2841     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2842                                    &priority);
2843     if (error) {
2844         /* Couldn't translate queue to a priority, so ignore.  A warning
2845          * has already been logged. */
2846         return;
2847     }
2848
2849     remove_pop_action(ctx);
2850     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_SET_PRIORITY, priority);
2851 }
2852
2853 static void
2854 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2855 {
2856     ovs_be16 tci = ctx->flow.vlan_tci;
2857     if (!(tci & htons(VLAN_CFI))) {
2858         nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_STRIP_VLAN);
2859     } else {
2860         nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_TCI,
2861                         tci & ~htons(VLAN_CFI));
2862     }
2863 }
2864
2865 struct xlate_reg_state {
2866     ovs_be16 vlan_tci;
2867     ovs_be64 tun_id;
2868 };
2869
2870 static void
2871 save_reg_state(const struct action_xlate_ctx *ctx,
2872                struct xlate_reg_state *state)
2873 {
2874     state->vlan_tci = ctx->flow.vlan_tci;
2875     state->tun_id = ctx->flow.tun_id;
2876 }
2877
2878 static void
2879 update_reg_state(struct action_xlate_ctx *ctx,
2880                  const struct xlate_reg_state *state)
2881 {
2882     if (ctx->flow.vlan_tci != state->vlan_tci) {
2883         xlate_set_dl_tci(ctx);
2884     }
2885     if (ctx->flow.tun_id != state->tun_id) {
2886         nl_msg_put_be64(ctx->odp_actions,
2887                         ODP_ACTION_ATTR_SET_TUNNEL, ctx->flow.tun_id);
2888     }
2889 }
2890
2891 static void
2892 xlate_autopath(struct action_xlate_ctx *ctx,
2893                const struct nx_action_autopath *naa)
2894 {
2895     uint16_t ofp_port = ntohl(naa->id);
2896     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
2897
2898     if (!port || !port->bundle) {
2899         ofp_port = OFPP_NONE;
2900     } else if (port->bundle->bond) {
2901         /* Autopath does not support VLAN hashing. */
2902         struct ofport_dpif *slave = bond_choose_output_slave(
2903             port->bundle->bond, &ctx->flow, OFP_VLAN_NONE, &ctx->tags);
2904         if (slave) {
2905             ofp_port = slave->up.ofp_port;
2906         }
2907     }
2908     autopath_execute(naa, &ctx->flow, ofp_port);
2909 }
2910
2911 static void
2912 xlate_nicira_action(struct action_xlate_ctx *ctx,
2913                     const struct nx_action_header *nah)
2914 {
2915     const struct nx_action_resubmit *nar;
2916     const struct nx_action_set_tunnel *nast;
2917     const struct nx_action_set_queue *nasq;
2918     const struct nx_action_multipath *nam;
2919     const struct nx_action_autopath *naa;
2920     enum nx_action_subtype subtype = ntohs(nah->subtype);
2921     struct xlate_reg_state state;
2922     ovs_be64 tun_id;
2923
2924     assert(nah->vendor == htonl(NX_VENDOR_ID));
2925     switch (subtype) {
2926     case NXAST_RESUBMIT:
2927         nar = (const struct nx_action_resubmit *) nah;
2928         xlate_table_action(ctx, ntohs(nar->in_port));
2929         break;
2930
2931     case NXAST_SET_TUNNEL:
2932         nast = (const struct nx_action_set_tunnel *) nah;
2933         tun_id = htonll(ntohl(nast->tun_id));
2934         nl_msg_put_be64(ctx->odp_actions, ODP_ACTION_ATTR_SET_TUNNEL, tun_id);
2935         ctx->flow.tun_id = tun_id;
2936         break;
2937
2938     case NXAST_DROP_SPOOFED_ARP:
2939         if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2940             nl_msg_put_flag(ctx->odp_actions,
2941                             ODP_ACTION_ATTR_DROP_SPOOFED_ARP);
2942         }
2943         break;
2944
2945     case NXAST_SET_QUEUE:
2946         nasq = (const struct nx_action_set_queue *) nah;
2947         xlate_set_queue_action(ctx, nasq);
2948         break;
2949
2950     case NXAST_POP_QUEUE:
2951         add_pop_action(ctx);
2952         break;
2953
2954     case NXAST_REG_MOVE:
2955         save_reg_state(ctx, &state);
2956         nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2957                              &ctx->flow);
2958         update_reg_state(ctx, &state);
2959         break;
2960
2961     case NXAST_REG_LOAD:
2962         save_reg_state(ctx, &state);
2963         nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
2964                              &ctx->flow);
2965         update_reg_state(ctx, &state);
2966         break;
2967
2968     case NXAST_NOTE:
2969         /* Nothing to do. */
2970         break;
2971
2972     case NXAST_SET_TUNNEL64:
2973         tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
2974         nl_msg_put_be64(ctx->odp_actions, ODP_ACTION_ATTR_SET_TUNNEL, tun_id);
2975         ctx->flow.tun_id = tun_id;
2976         break;
2977
2978     case NXAST_MULTIPATH:
2979         nam = (const struct nx_action_multipath *) nah;
2980         multipath_execute(nam, &ctx->flow);
2981         break;
2982
2983     case NXAST_AUTOPATH:
2984         naa = (const struct nx_action_autopath *) nah;
2985         xlate_autopath(ctx, naa);
2986         break;
2987
2988     /* If you add a new action here that modifies flow data, don't forget to
2989      * update the flow key in ctx->flow at the same time. */
2990
2991     case NXAST_SNAT__OBSOLETE:
2992     default:
2993         VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
2994         break;
2995     }
2996 }
2997
2998 static void
2999 do_xlate_actions(const union ofp_action *in, size_t n_in,
3000                  struct action_xlate_ctx *ctx)
3001 {
3002     const struct ofport_dpif *port;
3003     struct actions_iterator iter;
3004     const union ofp_action *ia;
3005
3006     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
3007     if (port
3008         && port->up.opp.config & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3009         port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3010                                ? htonl(OFPPC_NO_RECV_STP)
3011                                : htonl(OFPPC_NO_RECV))) {
3012         /* Drop this flow. */
3013         return;
3014     }
3015
3016     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
3017         enum ofp_action_type type = ntohs(ia->type);
3018         const struct ofp_action_dl_addr *oada;
3019
3020         switch (type) {
3021         case OFPAT_OUTPUT:
3022             xlate_output_action(ctx, &ia->output);
3023             break;
3024
3025         case OFPAT_SET_VLAN_VID:
3026             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3027             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3028             xlate_set_dl_tci(ctx);
3029             break;
3030
3031         case OFPAT_SET_VLAN_PCP:
3032             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3033             ctx->flow.vlan_tci |= htons(
3034                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3035             xlate_set_dl_tci(ctx);
3036             break;
3037
3038         case OFPAT_STRIP_VLAN:
3039             ctx->flow.vlan_tci = htons(0);
3040             xlate_set_dl_tci(ctx);
3041             break;
3042
3043         case OFPAT_SET_DL_SRC:
3044             oada = ((struct ofp_action_dl_addr *) ia);
3045             nl_msg_put_unspec(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_SRC,
3046                               oada->dl_addr, ETH_ADDR_LEN);
3047             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3048             break;
3049
3050         case OFPAT_SET_DL_DST:
3051             oada = ((struct ofp_action_dl_addr *) ia);
3052             nl_msg_put_unspec(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_DST,
3053                               oada->dl_addr, ETH_ADDR_LEN);
3054             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3055             break;
3056
3057         case OFPAT_SET_NW_SRC:
3058             nl_msg_put_be32(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_SRC,
3059                             ia->nw_addr.nw_addr);
3060             ctx->flow.nw_src = ia->nw_addr.nw_addr;
3061             break;
3062
3063         case OFPAT_SET_NW_DST:
3064             nl_msg_put_be32(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_DST,
3065                             ia->nw_addr.nw_addr);
3066             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3067             break;
3068
3069         case OFPAT_SET_NW_TOS:
3070             nl_msg_put_u8(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_TOS,
3071                           ia->nw_tos.nw_tos);
3072             ctx->flow.nw_tos = ia->nw_tos.nw_tos;
3073             break;
3074
3075         case OFPAT_SET_TP_SRC:
3076             nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_TP_SRC,
3077                             ia->tp_port.tp_port);
3078             ctx->flow.tp_src = ia->tp_port.tp_port;
3079             break;
3080
3081         case OFPAT_SET_TP_DST:
3082             nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_TP_DST,
3083                             ia->tp_port.tp_port);
3084             ctx->flow.tp_dst = ia->tp_port.tp_port;
3085             break;
3086
3087         case OFPAT_VENDOR:
3088             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3089             break;
3090
3091         case OFPAT_ENQUEUE:
3092             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3093             break;
3094
3095         default:
3096             VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
3097             break;
3098         }
3099     }
3100 }
3101
3102 static void
3103 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3104                       struct ofproto_dpif *ofproto, const struct flow *flow,
3105                       const struct ofpbuf *packet)
3106 {
3107     ctx->ofproto = ofproto;
3108     ctx->flow = *flow;
3109     ctx->packet = packet;
3110     ctx->resubmit_hook = NULL;
3111 }
3112
3113 static struct ofpbuf *
3114 xlate_actions(struct action_xlate_ctx *ctx,
3115               const union ofp_action *in, size_t n_in)
3116 {
3117     COVERAGE_INC(ofproto_dpif_xlate);
3118
3119     ctx->odp_actions = ofpbuf_new(512);
3120     ctx->tags = 0;
3121     ctx->may_set_up_flow = true;
3122     ctx->nf_output_iface = NF_OUT_DROP;
3123     ctx->recurse = 0;
3124     ctx->last_pop_priority = -1;
3125
3126     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
3127         ctx->may_set_up_flow = false;
3128     } else {
3129         do_xlate_actions(in, n_in, ctx);
3130     }
3131
3132     remove_pop_action(ctx);
3133
3134     /* Check with in-band control to see if we're allowed to set up this
3135      * flow. */
3136     if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
3137                                  ctx->odp_actions->data,
3138                                  ctx->odp_actions->size)) {
3139         ctx->may_set_up_flow = false;
3140     }
3141
3142     return ctx->odp_actions;
3143 }
3144 \f
3145 /* OFPP_NORMAL implementation. */
3146
3147 struct dst {
3148     struct ofport_dpif *port;
3149     uint16_t vlan;
3150 };
3151
3152 struct dst_set {
3153     struct dst builtin[32];
3154     struct dst *dsts;
3155     size_t n, allocated;
3156 };
3157
3158 static void dst_set_init(struct dst_set *);
3159 static void dst_set_add(struct dst_set *, const struct dst *);
3160 static void dst_set_free(struct dst_set *);
3161
3162 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
3163
3164 static bool
3165 set_dst(struct action_xlate_ctx *ctx, struct dst *dst,
3166         const struct ofbundle *in_bundle, const struct ofbundle *out_bundle)
3167 {
3168     dst->vlan = (out_bundle->vlan >= 0 ? OFP_VLAN_NONE
3169                  : in_bundle->vlan >= 0 ? in_bundle->vlan
3170                  : ctx->flow.vlan_tci == 0 ? OFP_VLAN_NONE
3171                  : vlan_tci_to_vid(ctx->flow.vlan_tci));
3172
3173     dst->port = (!out_bundle->bond
3174                  ? ofbundle_get_a_port(out_bundle)
3175                  : bond_choose_output_slave(out_bundle->bond, &ctx->flow,
3176                                             dst->vlan, &ctx->tags));
3177
3178     return dst->port != NULL;
3179 }
3180
3181 static int
3182 mirror_mask_ffs(mirror_mask_t mask)
3183 {
3184     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
3185     return ffs(mask);
3186 }
3187
3188 static void
3189 dst_set_init(struct dst_set *set)
3190 {
3191     set->dsts = set->builtin;
3192     set->n = 0;
3193     set->allocated = ARRAY_SIZE(set->builtin);
3194 }
3195
3196 static void
3197 dst_set_add(struct dst_set *set, const struct dst *dst)
3198 {
3199     if (set->n >= set->allocated) {
3200         size_t new_allocated;
3201         struct dst *new_dsts;
3202
3203         new_allocated = set->allocated * 2;
3204         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
3205         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
3206
3207         dst_set_free(set);
3208
3209         set->dsts = new_dsts;
3210         set->allocated = new_allocated;
3211     }
3212     set->dsts[set->n++] = *dst;
3213 }
3214
3215 static void
3216 dst_set_free(struct dst_set *set)
3217 {
3218     if (set->dsts != set->builtin) {
3219         free(set->dsts);
3220     }
3221 }
3222
3223 static bool
3224 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
3225 {
3226     size_t i;
3227     for (i = 0; i < set->n; i++) {
3228         if (set->dsts[i].vlan == test->vlan
3229             && set->dsts[i].port == test->port) {
3230             return true;
3231         }
3232     }
3233     return false;
3234 }
3235
3236 static bool
3237 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
3238 {
3239     return bundle->vlan < 0 && vlan_bitmap_contains(bundle->trunks, vlan);
3240 }
3241
3242 static bool
3243 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
3244 {
3245     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
3246 }
3247
3248 /* Returns an arbitrary interface within 'bundle'. */
3249 static struct ofport_dpif *
3250 ofbundle_get_a_port(const struct ofbundle *bundle)
3251 {
3252     return CONTAINER_OF(list_front(&bundle->ports),
3253                         struct ofport_dpif, bundle_node);
3254 }
3255
3256 static void
3257 compose_dsts(struct action_xlate_ctx *ctx, uint16_t vlan,
3258              const struct ofbundle *in_bundle,
3259              const struct ofbundle *out_bundle, struct dst_set *set)
3260 {
3261     struct dst dst;
3262
3263     if (out_bundle == OFBUNDLE_FLOOD) {
3264         struct ofbundle *bundle;
3265
3266         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
3267             if (bundle != in_bundle
3268                 && ofbundle_includes_vlan(bundle, vlan)
3269                 && bundle->floodable
3270                 && !bundle->mirror_out
3271                 && set_dst(ctx, &dst, in_bundle, bundle)) {
3272                 dst_set_add(set, &dst);
3273             }
3274         }
3275         ctx->nf_output_iface = NF_OUT_FLOOD;
3276     } else if (out_bundle && set_dst(ctx, &dst, in_bundle, out_bundle)) {
3277         dst_set_add(set, &dst);
3278         ctx->nf_output_iface = dst.port->odp_port;
3279     }
3280 }
3281
3282 static bool
3283 vlan_is_mirrored(const struct ofmirror *m, int vlan)
3284 {
3285     return vlan_bitmap_contains(m->vlans, vlan);
3286 }
3287
3288 static void
3289 compose_mirror_dsts(struct action_xlate_ctx *ctx,
3290                     uint16_t vlan, const struct ofbundle *in_bundle,
3291                     struct dst_set *set)
3292 {
3293     struct ofproto_dpif *ofproto = ctx->ofproto;
3294     mirror_mask_t mirrors;
3295     int flow_vlan;
3296     size_t i;
3297
3298     mirrors = in_bundle->src_mirrors;
3299     for (i = 0; i < set->n; i++) {
3300         mirrors |= set->dsts[i].port->bundle->dst_mirrors;
3301     }
3302
3303     if (!mirrors) {
3304         return;
3305     }
3306
3307     flow_vlan = vlan_tci_to_vid(ctx->flow.vlan_tci);
3308     if (flow_vlan == 0) {
3309         flow_vlan = OFP_VLAN_NONE;
3310     }
3311
3312     while (mirrors) {
3313         struct ofmirror *m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
3314         if (vlan_is_mirrored(m, vlan)) {
3315             struct dst dst;
3316
3317             if (m->out) {
3318                 if (set_dst(ctx, &dst, in_bundle, m->out)
3319                     && !dst_is_duplicate(set, &dst)) {
3320                     dst_set_add(set, &dst);
3321                 }
3322             } else {
3323                 struct ofbundle *bundle;
3324
3325                 HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
3326                     if (ofbundle_includes_vlan(bundle, m->out_vlan)
3327                         && set_dst(ctx, &dst, in_bundle, bundle))
3328                     {
3329                         if (bundle->vlan < 0) {
3330                             dst.vlan = m->out_vlan;
3331                         }
3332                         if (dst_is_duplicate(set, &dst)) {
3333                             continue;
3334                         }
3335
3336                         /* Use the vlan tag on the original flow instead of
3337                          * the one passed in the vlan parameter.  This ensures
3338                          * that we compare the vlan from before any implicit
3339                          * tagging tags place. This is necessary because
3340                          * dst->vlan is the final vlan, after removing implicit
3341                          * tags. */
3342                         if (bundle == in_bundle && dst.vlan == flow_vlan) {
3343                             /* Don't send out input port on same VLAN. */
3344                             continue;
3345                         }
3346                         dst_set_add(set, &dst);
3347                     }
3348                 }
3349             }
3350         }
3351         mirrors &= mirrors - 1;
3352     }
3353 }
3354
3355 static void
3356 compose_actions(struct action_xlate_ctx *ctx, uint16_t vlan,
3357                 const struct ofbundle *in_bundle,
3358                 const struct ofbundle *out_bundle)
3359 {
3360     uint16_t initial_vlan, cur_vlan;
3361     const struct dst *dst;
3362     struct dst_set set;
3363
3364     dst_set_init(&set);
3365     compose_dsts(ctx, vlan, in_bundle, out_bundle, &set);
3366     compose_mirror_dsts(ctx, vlan, in_bundle, &set);
3367
3368     /* Output all the packets we can without having to change the VLAN. */
3369     initial_vlan = vlan_tci_to_vid(ctx->flow.vlan_tci);
3370     if (initial_vlan == 0) {
3371         initial_vlan = OFP_VLAN_NONE;
3372     }
3373     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
3374         if (dst->vlan != initial_vlan) {
3375             continue;
3376         }
3377         nl_msg_put_u32(ctx->odp_actions,
3378                        ODP_ACTION_ATTR_OUTPUT, dst->port->odp_port);
3379     }
3380
3381     /* Then output the rest. */
3382     cur_vlan = initial_vlan;
3383     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
3384         if (dst->vlan == initial_vlan) {
3385             continue;
3386         }
3387         if (dst->vlan != cur_vlan) {
3388             if (dst->vlan == OFP_VLAN_NONE) {
3389                 nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_STRIP_VLAN);
3390             } else {
3391                 ovs_be16 tci;
3392                 tci = htons(dst->vlan & VLAN_VID_MASK);
3393                 tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
3394                 nl_msg_put_be16(ctx->odp_actions,
3395                                 ODP_ACTION_ATTR_SET_DL_TCI, tci);
3396             }
3397             cur_vlan = dst->vlan;
3398         }
3399         nl_msg_put_u32(ctx->odp_actions,
3400                        ODP_ACTION_ATTR_OUTPUT, dst->port->odp_port);
3401     }
3402
3403     dst_set_free(&set);
3404 }
3405
3406 /* Returns the effective vlan of a packet, taking into account both the
3407  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
3408  * the packet is untagged and -1 indicates it has an invalid header and
3409  * should be dropped. */
3410 static int
3411 flow_get_vlan(struct ofproto_dpif *ofproto, const struct flow *flow,
3412               struct ofbundle *in_bundle, bool have_packet)
3413 {
3414     int vlan = vlan_tci_to_vid(flow->vlan_tci);
3415     if (in_bundle->vlan >= 0) {
3416         if (vlan) {
3417             if (have_packet) {
3418                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3419                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
3420                              "packet received on port %s configured with "
3421                              "implicit VLAN %"PRIu16,
3422                              ofproto->up.name, vlan,
3423                              in_bundle->name, in_bundle->vlan);
3424             }
3425             return -1;
3426         }
3427         vlan = in_bundle->vlan;
3428     } else {
3429         if (!ofbundle_includes_vlan(in_bundle, vlan)) {
3430             if (have_packet) {
3431                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3432                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
3433                              "packet received on port %s not configured for "
3434                              "trunking VLAN %d",
3435                              ofproto->up.name, vlan, in_bundle->name, vlan);
3436             }
3437             return -1;
3438         }
3439     }
3440
3441     return vlan;
3442 }
3443
3444 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
3445  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
3446  * indicate this; newer upstream kernels use gratuitous ARP requests. */
3447 static bool
3448 is_gratuitous_arp(const struct flow *flow)
3449 {
3450     return (flow->dl_type == htons(ETH_TYPE_ARP)
3451             && eth_addr_is_broadcast(flow->dl_dst)
3452             && (flow->nw_proto == ARP_OP_REPLY
3453                 || (flow->nw_proto == ARP_OP_REQUEST
3454                     && flow->nw_src == flow->nw_dst)));
3455 }
3456
3457 static void
3458 update_learning_table(struct ofproto_dpif *ofproto,
3459                       const struct flow *flow, int vlan,
3460                       struct ofbundle *in_bundle)
3461 {
3462     struct mac_entry *mac;
3463
3464     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
3465         return;
3466     }
3467
3468     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
3469     if (is_gratuitous_arp(flow)) {
3470         /* We don't want to learn from gratuitous ARP packets that are
3471          * reflected back over bond slaves so we lock the learning table. */
3472         if (!in_bundle->bond) {
3473             mac_entry_set_grat_arp_lock(mac);
3474         } else if (mac_entry_is_grat_arp_locked(mac)) {
3475             return;
3476         }
3477     }
3478
3479     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
3480         /* The log messages here could actually be useful in debugging,
3481          * so keep the rate limit relatively high. */
3482         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
3483         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
3484                     "on port %s in VLAN %d",
3485                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
3486                     in_bundle->name, vlan);
3487
3488         mac->port.p = in_bundle;
3489         tag_set_add(&ofproto->revalidate_set,
3490                     mac_learning_changed(ofproto->ml, mac));
3491     }
3492 }
3493
3494 /* Determines whether packets in 'flow' within 'br' should be forwarded or
3495  * dropped.  Returns true if they may be forwarded, false if they should be
3496  * dropped.
3497  *
3498  * If 'have_packet' is true, it indicates that the caller is processing a
3499  * received packet.  If 'have_packet' is false, then the caller is just
3500  * revalidating an existing flow because configuration has changed.  Either
3501  * way, 'have_packet' only affects logging (there is no point in logging errors
3502  * during revalidation).
3503  *
3504  * Sets '*in_portp' to the input port.  This will be a null pointer if
3505  * flow->in_port does not designate a known input port (in which case
3506  * is_admissible() returns false).
3507  *
3508  * When returning true, sets '*vlanp' to the effective VLAN of the input
3509  * packet, as returned by flow_get_vlan().
3510  *
3511  * May also add tags to '*tags', although the current implementation only does
3512  * so in one special case.
3513  */
3514 static bool
3515 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
3516               bool have_packet,
3517               tag_type *tags, int *vlanp, struct ofbundle **in_bundlep)
3518 {
3519     struct ofport_dpif *in_port;
3520     struct ofbundle *in_bundle;
3521     int vlan;
3522
3523     /* Find the port and bundle for the received packet. */
3524     in_port = get_ofp_port(ofproto, flow->in_port);
3525     *in_bundlep = in_bundle = in_port ? in_port->bundle : NULL;
3526     if (!in_port || !in_bundle) {
3527         /* No interface?  Something fishy... */
3528         if (have_packet) {
3529             /* Odd.  A few possible reasons here:
3530              *
3531              * - We deleted a port but there are still a few packets queued up
3532              *   from it.
3533              *
3534              * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
3535              *   we don't know about.
3536              *
3537              * - Packet arrived on the local port but the local port is not
3538              *   part of a bundle.
3539              */
3540             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3541
3542             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
3543                          "port %"PRIu16,
3544                          ofproto->up.name, flow->in_port);
3545         }
3546         return false;
3547     }
3548     *vlanp = vlan = flow_get_vlan(ofproto, flow, in_bundle, have_packet);
3549     if (vlan < 0) {
3550         return false;
3551     }
3552
3553     /* Drop frames for reserved multicast addresses. */
3554     if (eth_addr_is_reserved(flow->dl_dst)) {
3555         return false;
3556     }
3557
3558     /* Drop frames on bundles reserved for mirroring. */
3559     if (in_bundle->mirror_out) {
3560         if (have_packet) {
3561             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3562             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
3563                          "%s, which is reserved exclusively for mirroring",
3564                          ofproto->up.name, in_bundle->name);
3565         }
3566         return false;
3567     }
3568
3569     if (in_bundle->bond) {
3570         struct mac_entry *mac;
3571
3572         switch (bond_check_admissibility(in_bundle->bond, in_port,
3573                                          flow->dl_dst, tags)) {
3574         case BV_ACCEPT:
3575             break;
3576
3577         case BV_DROP:
3578             return false;
3579
3580         case BV_DROP_IF_MOVED:
3581             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
3582             if (mac && mac->port.p != in_bundle &&
3583                 (!is_gratuitous_arp(flow)
3584                  || mac_entry_is_grat_arp_locked(mac))) {
3585                 return false;
3586             }
3587             break;
3588         }
3589     }
3590
3591     return true;
3592 }
3593
3594 /* If the composed actions may be applied to any packet in the given 'flow',
3595  * returns true.  Otherwise, the actions should only be applied to 'packet', or
3596  * not at all, if 'packet' was NULL. */
3597 static bool
3598 xlate_normal(struct action_xlate_ctx *ctx)
3599 {
3600     struct ofbundle *in_bundle;
3601     struct ofbundle *out_bundle;
3602     struct mac_entry *mac;
3603     int vlan;
3604
3605     /* Check whether we should drop packets in this flow. */
3606     if (!is_admissible(ctx->ofproto, &ctx->flow, ctx->packet != NULL,
3607                        &ctx->tags, &vlan, &in_bundle)) {
3608         out_bundle = NULL;
3609         goto done;
3610     }
3611
3612     /* Learn source MAC (but don't try to learn from revalidation). */
3613     if (ctx->packet) {
3614         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
3615     }
3616
3617     /* Determine output bundle. */
3618     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
3619                               &ctx->tags);
3620     if (mac) {
3621         out_bundle = mac->port.p;
3622     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
3623         /* If we are revalidating but don't have a learning entry then eject
3624          * the flow.  Installing a flow that floods packets opens up a window
3625          * of time where we could learn from a packet reflected on a bond and
3626          * blackhole packets before the learning table is updated to reflect
3627          * the correct port. */
3628         return false;
3629     } else {
3630         out_bundle = OFBUNDLE_FLOOD;
3631     }
3632
3633     /* Don't send packets out their input bundles. */
3634     if (in_bundle == out_bundle) {
3635         out_bundle = NULL;
3636     }
3637
3638 done:
3639     if (in_bundle) {
3640         compose_actions(ctx, vlan, in_bundle, out_bundle);
3641     }
3642
3643     return true;
3644 }
3645 \f
3646 static bool
3647 get_drop_frags(struct ofproto *ofproto_)
3648 {
3649     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3650     bool drop_frags;
3651
3652     dpif_get_drop_frags(ofproto->dpif, &drop_frags);
3653     return drop_frags;
3654 }
3655
3656 static void
3657 set_drop_frags(struct ofproto *ofproto_, bool drop_frags)
3658 {
3659     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3660
3661     dpif_set_drop_frags(ofproto->dpif, drop_frags);
3662 }
3663
3664 static int
3665 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
3666            const struct flow *flow,
3667            const union ofp_action *ofp_actions, size_t n_ofp_actions)
3668 {
3669     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3670     int error;
3671
3672     error = validate_actions(ofp_actions, n_ofp_actions, flow,
3673                              ofproto->max_ports);
3674     if (!error) {
3675         struct action_xlate_ctx ctx;
3676         struct ofpbuf *odp_actions;
3677
3678         action_xlate_ctx_init(&ctx, ofproto, flow, packet);
3679         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3680         dpif_execute(ofproto->dpif, odp_actions->data, odp_actions->size,
3681                      packet);
3682         ofpbuf_delete(odp_actions);
3683     }
3684     return error;
3685 }
3686
3687 static void
3688 get_netflow_ids(const struct ofproto *ofproto_,
3689                 uint8_t *engine_type, uint8_t *engine_id)
3690 {
3691     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3692
3693     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
3694 }
3695 \f
3696 static struct ofproto_dpif *
3697 ofproto_dpif_lookup(const char *name)
3698 {
3699     struct ofproto *ofproto = ofproto_lookup(name);
3700     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
3701             ? ofproto_dpif_cast(ofproto)
3702             : NULL);
3703 }
3704
3705 static void
3706 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
3707                          const char *args, void *aux OVS_UNUSED)
3708 {
3709     struct ds ds = DS_EMPTY_INITIALIZER;
3710     const struct ofproto_dpif *ofproto;
3711     const struct mac_entry *e;
3712
3713     ofproto = ofproto_dpif_lookup(args);
3714     if (!ofproto) {
3715         unixctl_command_reply(conn, 501, "no such bridge");
3716         return;
3717     }
3718
3719     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
3720     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
3721         struct ofbundle *bundle = e->port.p;
3722         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
3723                       ofbundle_get_a_port(bundle)->odp_port,
3724                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
3725     }
3726     unixctl_command_reply(conn, 200, ds_cstr(&ds));
3727     ds_destroy(&ds);
3728 }
3729
3730 struct ofproto_trace {
3731     struct action_xlate_ctx ctx;
3732     struct flow flow;
3733     struct ds *result;
3734 };
3735
3736 static void
3737 trace_format_rule(struct ds *result, int level, const struct rule *rule)
3738 {
3739     ds_put_char_multiple(result, '\t', level);
3740     if (!rule) {
3741         ds_put_cstr(result, "No match\n");
3742         return;
3743     }
3744
3745     ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
3746                   ntohll(rule->flow_cookie));
3747     cls_rule_format(&rule->cr, result);
3748     ds_put_char(result, '\n');
3749
3750     ds_put_char_multiple(result, '\t', level);
3751     ds_put_cstr(result, "OpenFlow ");
3752     ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
3753                       rule->n_actions * sizeof *rule->actions);
3754     ds_put_char(result, '\n');
3755 }
3756
3757 static void
3758 trace_format_flow(struct ds *result, int level, const char *title,
3759                  struct ofproto_trace *trace)
3760 {
3761     ds_put_char_multiple(result, '\t', level);
3762     ds_put_format(result, "%s: ", title);
3763     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
3764         ds_put_cstr(result, "unchanged");
3765     } else {
3766         flow_format(result, &trace->ctx.flow);
3767         trace->flow = trace->ctx.flow;
3768     }
3769     ds_put_char(result, '\n');
3770 }
3771
3772 static void
3773 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
3774 {
3775     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
3776     struct ds *result = trace->result;
3777
3778     ds_put_char(result, '\n');
3779     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
3780     trace_format_rule(result, ctx->recurse + 1, &rule->up);
3781 }
3782
3783 static void
3784 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
3785                       void *aux OVS_UNUSED)
3786 {
3787     char *dpname, *in_port_s, *tun_id_s, *packet_s;
3788     char *args = xstrdup(args_);
3789     char *save_ptr = NULL;
3790     struct ofproto_dpif *ofproto;
3791     struct ofpbuf packet;
3792     struct rule_dpif *rule;
3793     struct ds result;
3794     struct flow flow;
3795     uint16_t in_port;
3796     ovs_be64 tun_id;
3797     char *s;
3798
3799     ofpbuf_init(&packet, strlen(args) / 2);
3800     ds_init(&result);
3801
3802     dpname = strtok_r(args, " ", &save_ptr);
3803     tun_id_s = strtok_r(NULL, " ", &save_ptr);
3804     in_port_s = strtok_r(NULL, " ", &save_ptr);
3805     packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
3806     if (!dpname || !in_port_s || !packet_s) {
3807         unixctl_command_reply(conn, 501, "Bad command syntax");
3808         goto exit;
3809     }
3810
3811     ofproto = ofproto_dpif_lookup(dpname);
3812     if (!ofproto) {
3813         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
3814                               "for help)");
3815         goto exit;
3816     }
3817
3818     tun_id = htonll(strtoull(tun_id_s, NULL, 0));
3819     in_port = ofp_port_to_odp_port(atoi(in_port_s));
3820
3821     packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
3822     packet_s += strspn(packet_s, " ");
3823     if (*packet_s != '\0') {
3824         unixctl_command_reply(conn, 501, "Trailing garbage in command");
3825         goto exit;
3826     }
3827     if (packet.size < ETH_HEADER_LEN) {
3828         unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
3829         goto exit;
3830     }
3831
3832     ds_put_cstr(&result, "Packet: ");
3833     s = ofp_packet_to_string(packet.data, packet.size, packet.size);
3834     ds_put_cstr(&result, s);
3835     free(s);
3836
3837     flow_extract(&packet, tun_id, in_port, &flow);
3838     ds_put_cstr(&result, "Flow: ");
3839     flow_format(&result, &flow);
3840     ds_put_char(&result, '\n');
3841
3842     rule = rule_dpif_lookup(ofproto, &flow);
3843     trace_format_rule(&result, 0, &rule->up);
3844     if (rule) {
3845         struct ofproto_trace trace;
3846         struct ofpbuf *odp_actions;
3847
3848         trace.result = &result;
3849         trace.flow = flow;
3850         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
3851         trace.ctx.resubmit_hook = trace_resubmit;
3852         odp_actions = xlate_actions(&trace.ctx,
3853                                     rule->up.actions, rule->up.n_actions);
3854
3855         ds_put_char(&result, '\n');
3856         trace_format_flow(&result, 0, "Final flow", &trace);
3857         ds_put_cstr(&result, "Datapath actions: ");
3858         format_odp_actions(&result, odp_actions->data, odp_actions->size);
3859         ofpbuf_delete(odp_actions);
3860     }
3861
3862     unixctl_command_reply(conn, 200, ds_cstr(&result));
3863
3864 exit:
3865     ds_destroy(&result);
3866     ofpbuf_uninit(&packet);
3867     free(args);
3868 }
3869
3870 static void
3871 ofproto_dpif_unixctl_init(void)
3872 {
3873     static bool registered;
3874     if (registered) {
3875         return;
3876     }
3877     registered = true;
3878
3879     unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
3880     unixctl_command_register("fdb/show", ofproto_unixctl_fdb_show, NULL);
3881 }
3882 \f
3883 const struct ofproto_class ofproto_dpif_class = {
3884     enumerate_types,
3885     enumerate_names,
3886     del,
3887     alloc,
3888     construct,
3889     destruct,
3890     dealloc,
3891     run,
3892     wait,
3893     flush,
3894     get_features,
3895     get_tables,
3896     port_alloc,
3897     port_construct,
3898     port_destruct,
3899     port_dealloc,
3900     port_modified,
3901     port_reconfigured,
3902     port_query_by_name,
3903     port_add,
3904     port_del,
3905     port_dump_start,
3906     port_dump_next,
3907     port_dump_done,
3908     port_poll,
3909     port_poll_wait,
3910     port_is_lacp_current,
3911     rule_alloc,
3912     rule_construct,
3913     rule_destruct,
3914     rule_dealloc,
3915     rule_get_stats,
3916     rule_execute,
3917     rule_modify_actions,
3918     get_drop_frags,
3919     set_drop_frags,
3920     packet_out,
3921     set_netflow,
3922     get_netflow_ids,
3923     set_sflow,
3924     set_cfm,
3925     get_cfm,
3926     bundle_set,
3927     bundle_remove,
3928     mirror_set,
3929     set_flood_vlans,
3930     is_mirror_output_bundle,
3931 };