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