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