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