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