ofproto-dpif: Introduce "internal flows" for handling flow table misses.
[sliver-openvswitch.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
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/ofproto-provider.h"
20
21 #include <errno.h>
22
23 #include "autopath.h"
24 #include "bond.h"
25 #include "bundle.h"
26 #include "byte-order.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "cfm.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "fail-open.h"
33 #include "hmapx.h"
34 #include "lacp.h"
35 #include "learn.h"
36 #include "mac-learning.h"
37 #include "meta-flow.h"
38 #include "multipath.h"
39 #include "netdev.h"
40 #include "netlink.h"
41 #include "nx-match.h"
42 #include "odp-util.h"
43 #include "ofp-util.h"
44 #include "ofpbuf.h"
45 #include "ofp-parse.h"
46 #include "ofp-print.h"
47 #include "ofproto-dpif-governor.h"
48 #include "ofproto-dpif-sflow.h"
49 #include "poll-loop.h"
50 #include "timer.h"
51 #include "unaligned.h"
52 #include "unixctl.h"
53 #include "vlan-bitmap.h"
54 #include "vlog.h"
55
56 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
57
58 COVERAGE_DEFINE(ofproto_dpif_ctlr_action);
59 COVERAGE_DEFINE(ofproto_dpif_expired);
60 COVERAGE_DEFINE(ofproto_dpif_xlate);
61 COVERAGE_DEFINE(facet_changed_rule);
62 COVERAGE_DEFINE(facet_invalidated);
63 COVERAGE_DEFINE(facet_revalidate);
64 COVERAGE_DEFINE(facet_unexpected);
65 COVERAGE_DEFINE(facet_suppress);
66
67 /* Maximum depth of flow table recursion (due to resubmit actions) in a
68  * flow translation. */
69 #define MAX_RESUBMIT_RECURSION 32
70
71 /* Number of implemented OpenFlow tables. */
72 enum { N_TABLES = 255 };
73 enum { TBL_INTERNAL = N_TABLES - 1 };    /* Used for internal hidden rules. */
74 BUILD_ASSERT_DECL(N_TABLES >= 2 && N_TABLES <= 255);
75
76 struct ofport_dpif;
77 struct ofproto_dpif;
78
79 struct rule_dpif {
80     struct rule up;
81
82     /* These statistics:
83      *
84      *   - Do include packets and bytes from facets that have been deleted or
85      *     whose own statistics have been folded into the rule.
86      *
87      *   - Do include packets and bytes sent "by hand" that were accounted to
88      *     the rule without any facet being involved (this is a rare corner
89      *     case in rule_execute()).
90      *
91      *   - Do not include packet or bytes that can be obtained from any facet's
92      *     packet_count or byte_count member or that can be obtained from the
93      *     datapath by, e.g., dpif_flow_get() for any subfacet.
94      */
95     uint64_t packet_count;       /* Number of packets received. */
96     uint64_t byte_count;         /* Number of bytes received. */
97
98     tag_type tag;                /* Caches rule_calculate_tag() result. */
99
100     struct list facets;          /* List of "struct facet"s. */
101 };
102
103 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
104 {
105     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
106 }
107
108 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
109                                           const struct flow *);
110 static struct rule_dpif *rule_dpif_lookup__(struct ofproto_dpif *,
111                                             const struct flow *,
112                                             uint8_t table);
113
114 static void rule_credit_stats(struct rule_dpif *,
115                               const struct dpif_flow_stats *);
116 static void flow_push_stats(struct rule_dpif *, const struct flow *,
117                             const struct dpif_flow_stats *);
118 static tag_type rule_calculate_tag(const struct flow *,
119                                    const struct flow_wildcards *,
120                                    uint32_t basis);
121 static void rule_invalidate(const struct rule_dpif *);
122
123 #define MAX_MIRRORS 32
124 typedef uint32_t mirror_mask_t;
125 #define MIRROR_MASK_C(X) UINT32_C(X)
126 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
127 struct ofmirror {
128     struct ofproto_dpif *ofproto; /* Owning ofproto. */
129     size_t idx;                 /* In ofproto's "mirrors" array. */
130     void *aux;                  /* Key supplied by ofproto's client. */
131     char *name;                 /* Identifier for log messages. */
132
133     /* Selection criteria. */
134     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
135     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
136     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
137
138     /* Output (exactly one of out == NULL and out_vlan == -1 is true). */
139     struct ofbundle *out;       /* Output port or NULL. */
140     int out_vlan;               /* Output VLAN or -1. */
141     mirror_mask_t dup_mirrors;  /* Bitmap of mirrors with the same output. */
142
143     /* Counters. */
144     int64_t packet_count;       /* Number of packets sent. */
145     int64_t byte_count;         /* Number of bytes sent. */
146 };
147
148 static void mirror_destroy(struct ofmirror *);
149 static void update_mirror_stats(struct ofproto_dpif *ofproto,
150                                 mirror_mask_t mirrors,
151                                 uint64_t packets, uint64_t bytes);
152
153 struct ofbundle {
154     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
155     struct ofproto_dpif *ofproto; /* Owning ofproto. */
156     void *aux;                  /* Key supplied by ofproto's client. */
157     char *name;                 /* Identifier for log messages. */
158
159     /* Configuration. */
160     struct list ports;          /* Contains "struct ofport"s. */
161     enum port_vlan_mode vlan_mode; /* VLAN mode */
162     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
163     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
164                                  * NULL if all VLANs are trunked. */
165     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
166     struct bond *bond;          /* Nonnull iff more than one port. */
167     bool use_priority_tags;     /* Use 802.1p tag for frames in VLAN 0? */
168
169     /* Status. */
170     bool floodable;          /* True if no port has OFPUTIL_PC_NO_FLOOD set. */
171
172     /* Port mirroring info. */
173     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
174     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
175     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
176 };
177
178 static void bundle_remove(struct ofport *);
179 static void bundle_update(struct ofbundle *);
180 static void bundle_destroy(struct ofbundle *);
181 static void bundle_del_port(struct ofport_dpif *);
182 static void bundle_run(struct ofbundle *);
183 static void bundle_wait(struct ofbundle *);
184 static struct ofbundle *lookup_input_bundle(struct ofproto_dpif *,
185                                             uint16_t in_port, bool warn,
186                                             struct ofport_dpif **in_ofportp);
187
188 /* A controller may use OFPP_NONE as the ingress port to indicate that
189  * it did not arrive on a "real" port.  'ofpp_none_bundle' exists for
190  * when an input bundle is needed for validation (e.g., mirroring or
191  * OFPP_NORMAL processing).  It is not connected to an 'ofproto' or have
192  * any 'port' structs, so care must be taken when dealing with it. */
193 static struct ofbundle ofpp_none_bundle = {
194     .name      = "OFPP_NONE",
195     .vlan_mode = PORT_VLAN_TRUNK
196 };
197
198 static void stp_run(struct ofproto_dpif *ofproto);
199 static void stp_wait(struct ofproto_dpif *ofproto);
200 static int set_stp_port(struct ofport *,
201                         const struct ofproto_port_stp_settings *);
202
203 static bool ofbundle_includes_vlan(const struct ofbundle *, uint16_t vlan);
204
205 struct action_xlate_ctx {
206 /* action_xlate_ctx_init() initializes these members. */
207
208     /* The ofproto. */
209     struct ofproto_dpif *ofproto;
210
211     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
212      * this flow when actions change header fields. */
213     struct flow flow;
214
215     /* The packet corresponding to 'flow', or a null pointer if we are
216      * revalidating without a packet to refer to. */
217     const struct ofpbuf *packet;
218
219     /* Should OFPP_NORMAL update the MAC learning table?  Should "learn"
220      * actions update the flow table?
221      *
222      * We want to update these tables if we are actually processing a packet,
223      * or if we are accounting for packets that the datapath has processed, but
224      * not if we are just revalidating. */
225     bool may_learn;
226
227     /* The rule that we are currently translating, or NULL. */
228     struct rule_dpif *rule;
229
230     /* Union of the set of TCP flags seen so far in this flow.  (Used only by
231      * NXAST_FIN_TIMEOUT.  Set to zero to avoid updating updating rules'
232      * timeouts.) */
233     uint8_t tcp_flags;
234
235     /* If nonnull, flow translation calls this function just before executing a
236      * resubmit or OFPP_TABLE action.  In addition, disables logging of traces
237      * when the recursion depth is exceeded.
238      *
239      * 'rule' is the rule being submitted into.  It will be null if the
240      * resubmit or OFPP_TABLE action didn't find a matching rule.
241      *
242      * This is normally null so the client has to set it manually after
243      * calling action_xlate_ctx_init(). */
244     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *rule);
245
246     /* If nonnull, flow translation credits the specified statistics to each
247      * rule reached through a resubmit or OFPP_TABLE action.
248      *
249      * This is normally null so the client has to set it manually after
250      * calling action_xlate_ctx_init(). */
251     const struct dpif_flow_stats *resubmit_stats;
252
253 /* xlate_actions() initializes and uses these members.  The client might want
254  * to look at them after it returns. */
255
256     struct ofpbuf *odp_actions; /* Datapath actions. */
257     tag_type tags;              /* Tags associated with actions. */
258     bool may_set_up_flow;       /* True ordinarily; false if the actions must
259                                  * be reassessed for every packet. */
260     bool has_learn;             /* Actions include NXAST_LEARN? */
261     bool has_normal;            /* Actions output to OFPP_NORMAL? */
262     bool has_fin_timeout;       /* Actions include NXAST_FIN_TIMEOUT? */
263     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
264     mirror_mask_t mirrors;      /* Bitmap of associated mirrors. */
265
266 /* xlate_actions() initializes and uses these members, but the client has no
267  * reason to look at them. */
268
269     int recurse;                /* Recursion level, via xlate_table_action. */
270     bool max_resubmit_trigger;  /* Recursed too deeply during translation. */
271     struct flow base_flow;      /* Flow at the last commit. */
272     uint32_t orig_skb_priority; /* Priority when packet arrived. */
273     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
274     uint32_t sflow_n_outputs;   /* Number of output ports. */
275     uint16_t sflow_odp_port;    /* Output port for composing sFlow action. */
276     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
277     bool exit;                  /* No further actions should be processed. */
278     struct flow orig_flow;      /* Copy of original flow. */
279 };
280
281 static void action_xlate_ctx_init(struct action_xlate_ctx *,
282                                   struct ofproto_dpif *, const struct flow *,
283                                   ovs_be16 initial_tci, struct rule_dpif *,
284                                   uint8_t tcp_flags, const struct ofpbuf *);
285 static void xlate_actions(struct action_xlate_ctx *,
286                           const union ofp_action *in, size_t n_in,
287                           struct ofpbuf *odp_actions);
288 static void xlate_actions_for_side_effects(struct action_xlate_ctx *,
289                                            const union ofp_action *in,
290                                            size_t n_in);
291
292 /* A dpif flow and actions associated with a facet.
293  *
294  * See also the large comment on struct facet. */
295 struct subfacet {
296     /* Owners. */
297     struct hmap_node hmap_node; /* In struct ofproto_dpif 'subfacets' list. */
298     struct list list_node;      /* In struct facet's 'facets' list. */
299     struct facet *facet;        /* Owning facet. */
300
301     /* Key.
302      *
303      * To save memory in the common case, 'key' is NULL if 'key_fitness' is
304      * ODP_FIT_PERFECT, that is, odp_flow_key_from_flow() can accurately
305      * regenerate the ODP flow key from ->facet->flow. */
306     enum odp_key_fitness key_fitness;
307     struct nlattr *key;
308     int key_len;
309
310     long long int used;         /* Time last used; time created if not used. */
311
312     uint64_t dp_packet_count;   /* Last known packet count in the datapath. */
313     uint64_t dp_byte_count;     /* Last known byte count in the datapath. */
314
315     /* Datapath actions.
316      *
317      * These should be essentially identical for every subfacet in a facet, but
318      * may differ in trivial ways due to VLAN splinters. */
319     size_t actions_len;         /* Number of bytes in actions[]. */
320     struct nlattr *actions;     /* Datapath actions. */
321
322     bool installed;             /* Installed in datapath? */
323
324     /* This value is normally the same as ->facet->flow.vlan_tci.  Only VLAN
325      * splinters can cause it to differ.  This value should be removed when
326      * the VLAN splinters feature is no longer needed.  */
327     ovs_be16 initial_tci;       /* Initial VLAN TCI value. */
328 };
329
330 static struct subfacet *subfacet_create(struct facet *, enum odp_key_fitness,
331                                         const struct nlattr *key,
332                                         size_t key_len, ovs_be16 initial_tci);
333 static struct subfacet *subfacet_find(struct ofproto_dpif *,
334                                       const struct nlattr *key, size_t key_len);
335 static void subfacet_destroy(struct subfacet *);
336 static void subfacet_destroy__(struct subfacet *);
337 static void subfacet_get_key(struct subfacet *, struct odputil_keybuf *,
338                              struct ofpbuf *key);
339 static void subfacet_reset_dp_stats(struct subfacet *,
340                                     struct dpif_flow_stats *);
341 static void subfacet_update_time(struct subfacet *, long long int used);
342 static void subfacet_update_stats(struct subfacet *,
343                                   const struct dpif_flow_stats *);
344 static void subfacet_make_actions(struct subfacet *,
345                                   const struct ofpbuf *packet,
346                                   struct ofpbuf *odp_actions);
347 static int subfacet_install(struct subfacet *,
348                             const struct nlattr *actions, size_t actions_len,
349                             struct dpif_flow_stats *);
350 static void subfacet_uninstall(struct subfacet *);
351
352 /* An exact-match instantiation of an OpenFlow flow.
353  *
354  * A facet associates a "struct flow", which represents the Open vSwitch
355  * userspace idea of an exact-match flow, with one or more subfacets.  Each
356  * subfacet tracks the datapath's idea of the exact-match flow equivalent to
357  * the facet.  When the kernel module (or other dpif implementation) and Open
358  * vSwitch userspace agree on the definition of a flow key, there is exactly
359  * one subfacet per facet.  If the dpif implementation supports more-specific
360  * flow matching than userspace, however, a facet can have more than one
361  * subfacet, each of which corresponds to some distinction in flow that
362  * userspace simply doesn't understand.
363  *
364  * Flow expiration works in terms of subfacets, so a facet must have at least
365  * one subfacet or it will never expire, leaking memory. */
366 struct facet {
367     /* Owners. */
368     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
369     struct list list_node;       /* In owning rule's 'facets' list. */
370     struct rule_dpif *rule;      /* Owning rule. */
371
372     /* Owned data. */
373     struct list subfacets;
374     long long int used;         /* Time last used; time created if not used. */
375
376     /* Key. */
377     struct flow flow;
378
379     /* These statistics:
380      *
381      *   - Do include packets and bytes sent "by hand", e.g. with
382      *     dpif_execute().
383      *
384      *   - Do include packets and bytes that were obtained from the datapath
385      *     when a subfacet's statistics were reset (e.g. dpif_flow_put() with
386      *     DPIF_FP_ZERO_STATS).
387      *
388      *   - Do not include packets or bytes that can be obtained from the
389      *     datapath for any existing subfacet.
390      */
391     uint64_t packet_count;       /* Number of packets received. */
392     uint64_t byte_count;         /* Number of bytes received. */
393
394     /* Resubmit statistics. */
395     uint64_t prev_packet_count;  /* Number of packets from last stats push. */
396     uint64_t prev_byte_count;    /* Number of bytes from last stats push. */
397     long long int prev_used;     /* Used time from last stats push. */
398
399     /* Accounting. */
400     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
401     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
402     uint8_t tcp_flags;           /* TCP flags seen for this 'rule'. */
403
404     /* Properties of datapath actions.
405      *
406      * Every subfacet has its own actions because actions can differ slightly
407      * between splintered and non-splintered subfacets due to the VLAN tag
408      * being initially different (present vs. absent).  All of them have these
409      * properties in common so we just store one copy of them here. */
410     bool may_install;            /* Reassess actions for every packet? */
411     bool has_learn;              /* Actions include NXAST_LEARN? */
412     bool has_normal;             /* Actions output to OFPP_NORMAL? */
413     bool has_fin_timeout;        /* Actions include NXAST_FIN_TIMEOUT? */
414     tag_type tags;               /* Tags that would require revalidation. */
415     mirror_mask_t mirrors;       /* Bitmap of dependent mirrors. */
416
417     /* Storage for a single subfacet, to reduce malloc() time and space
418      * overhead.  (A facet always has at least one subfacet and in the common
419      * case has exactly one subfacet.) */
420     struct subfacet one_subfacet;
421 };
422
423 static struct facet *facet_create(struct rule_dpif *,
424                                   const struct flow *, uint32_t hash);
425 static void facet_remove(struct facet *);
426 static void facet_free(struct facet *);
427
428 static struct facet *facet_find(struct ofproto_dpif *,
429                                 const struct flow *, uint32_t hash);
430 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
431                                         const struct flow *, uint32_t hash);
432 static void facet_revalidate(struct facet *);
433 static bool facet_check_consistency(struct facet *);
434
435 static void facet_flush_stats(struct facet *);
436
437 static void facet_update_time(struct facet *, long long int used);
438 static void facet_reset_counters(struct facet *);
439 static void facet_push_stats(struct facet *);
440 static void facet_learn(struct facet *);
441 static void facet_account(struct facet *);
442
443 static bool facet_is_controller_flow(struct facet *);
444
445 struct ofport_dpif {
446     struct ofport up;
447
448     uint32_t odp_port;
449     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
450     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
451     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
452     tag_type tag;               /* Tag associated with this port. */
453     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
454     bool may_enable;            /* May be enabled in bonds. */
455     long long int carrier_seq;  /* Carrier status changes. */
456
457     /* Spanning tree. */
458     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
459     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
460     long long int stp_state_entered;
461
462     struct hmap priorities;     /* Map of attached 'priority_to_dscp's. */
463
464     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
465      *
466      * This is deprecated.  It is only for compatibility with broken device
467      * drivers in old versions of Linux that do not properly support VLANs when
468      * VLAN devices are not used.  When broken device drivers are no longer in
469      * widespread use, we will delete these interfaces. */
470     uint16_t realdev_ofp_port;
471     int vlandev_vid;
472 };
473
474 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
475  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
476  * traffic egressing the 'ofport' with that priority should be marked with. */
477 struct priority_to_dscp {
478     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
479     uint32_t priority;          /* Priority of this queue (see struct flow). */
480
481     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
482 };
483
484 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
485  *
486  * This is deprecated.  It is only for compatibility with broken device drivers
487  * in old versions of Linux that do not properly support VLANs when VLAN
488  * devices are not used.  When broken device drivers are no longer in
489  * widespread use, we will delete these interfaces. */
490 struct vlan_splinter {
491     struct hmap_node realdev_vid_node;
492     struct hmap_node vlandev_node;
493     uint16_t realdev_ofp_port;
494     uint16_t vlandev_ofp_port;
495     int vid;
496 };
497
498 static uint32_t vsp_realdev_to_vlandev(const struct ofproto_dpif *,
499                                        uint32_t realdev, ovs_be16 vlan_tci);
500 static uint16_t vsp_vlandev_to_realdev(const struct ofproto_dpif *,
501                                        uint16_t vlandev, int *vid);
502 static bool vsp_adjust_flow(const struct ofproto_dpif *, struct flow *);
503 static void vsp_remove(struct ofport_dpif *);
504 static void vsp_add(struct ofport_dpif *, uint16_t realdev_ofp_port, int vid);
505
506 static struct ofport_dpif *
507 ofport_dpif_cast(const struct ofport *ofport)
508 {
509     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
510     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
511 }
512
513 static void port_run(struct ofport_dpif *);
514 static void port_wait(struct ofport_dpif *);
515 static int set_cfm(struct ofport *, const struct cfm_settings *);
516 static void ofport_clear_priorities(struct ofport_dpif *);
517
518 struct dpif_completion {
519     struct list list_node;
520     struct ofoperation *op;
521 };
522
523 /* Extra information about a classifier table.
524  * Currently used just for optimized flow revalidation. */
525 struct table_dpif {
526     /* If either of these is nonnull, then this table has a form that allows
527      * flows to be tagged to avoid revalidating most flows for the most common
528      * kinds of flow table changes. */
529     struct cls_table *catchall_table; /* Table that wildcards all fields. */
530     struct cls_table *other_table;    /* Table with any other wildcard set. */
531     uint32_t basis;                   /* Keeps each table's tags separate. */
532 };
533
534 struct ofproto_dpif {
535     struct hmap_node all_ofproto_dpifs_node; /* In 'all_ofproto_dpifs'. */
536     struct ofproto up;
537     struct dpif *dpif;
538     int max_ports;
539
540     /* Special OpenFlow rules. */
541     struct rule_dpif *miss_rule; /* Sends flow table misses to controller. */
542     struct rule_dpif *no_packet_in_rule; /* Drops flow table misses. */
543
544     /* Statistics. */
545     uint64_t n_matches;
546
547     /* Bridging. */
548     struct netflow *netflow;
549     struct dpif_sflow *sflow;
550     struct hmap bundles;        /* Contains "struct ofbundle"s. */
551     struct mac_learning *ml;
552     struct ofmirror *mirrors[MAX_MIRRORS];
553     bool has_mirrors;
554     bool has_bonded_bundles;
555
556     /* Expiration. */
557     struct timer next_expiration;
558
559     /* Facets. */
560     struct hmap facets;
561     struct hmap subfacets;
562     struct governor *governor;
563
564     /* Revalidation. */
565     struct table_dpif tables[N_TABLES];
566     bool need_revalidate;
567     struct tag_set revalidate_set;
568
569     /* Support for debugging async flow mods. */
570     struct list completions;
571
572     bool has_bundle_action; /* True when the first bundle action appears. */
573     struct netdev_stats stats; /* To account packets generated and consumed in
574                                 * userspace. */
575
576     /* Spanning tree. */
577     struct stp *stp;
578     long long int stp_last_tick;
579
580     /* VLAN splinters. */
581     struct hmap realdev_vid_map; /* (realdev,vid) -> vlandev. */
582     struct hmap vlandev_map;     /* vlandev -> (realdev,vid). */
583 };
584
585 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
586  * for debugging the asynchronous flow_mod implementation.) */
587 static bool clogged;
588
589 /* All existing ofproto_dpif instances, indexed by ->up.name. */
590 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
591
592 static void ofproto_dpif_unixctl_init(void);
593
594 static struct ofproto_dpif *
595 ofproto_dpif_cast(const struct ofproto *ofproto)
596 {
597     assert(ofproto->ofproto_class == &ofproto_dpif_class);
598     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
599 }
600
601 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
602                                         uint16_t ofp_port);
603 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
604                                         uint32_t odp_port);
605 static void ofproto_trace(struct ofproto_dpif *, const struct flow *,
606                           const struct ofpbuf *, ovs_be16 initial_tci,
607                           struct ds *);
608
609 /* Packet processing. */
610 static void update_learning_table(struct ofproto_dpif *,
611                                   const struct flow *, int vlan,
612                                   struct ofbundle *);
613 /* Upcalls. */
614 #define FLOW_MISS_MAX_BATCH 50
615 static int handle_upcalls(struct ofproto_dpif *, unsigned int max_batch);
616
617 /* Flow expiration. */
618 static int expire(struct ofproto_dpif *);
619
620 /* NetFlow. */
621 static void send_netflow_active_timeouts(struct ofproto_dpif *);
622
623 /* Utilities. */
624 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
625 static size_t compose_sflow_action(const struct ofproto_dpif *,
626                                    struct ofpbuf *odp_actions,
627                                    const struct flow *, uint32_t odp_port);
628 static void add_mirror_actions(struct action_xlate_ctx *ctx,
629                                const struct flow *flow);
630 /* Global variables. */
631 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
632 \f
633 /* Factory functions. */
634
635 static void
636 enumerate_types(struct sset *types)
637 {
638     dp_enumerate_types(types);
639 }
640
641 static int
642 enumerate_names(const char *type, struct sset *names)
643 {
644     return dp_enumerate_names(type, names);
645 }
646
647 static int
648 del(const char *type, const char *name)
649 {
650     struct dpif *dpif;
651     int error;
652
653     error = dpif_open(name, type, &dpif);
654     if (!error) {
655         error = dpif_delete(dpif);
656         dpif_close(dpif);
657     }
658     return error;
659 }
660 \f
661 /* Basic life-cycle. */
662
663 static int add_internal_flows(struct ofproto_dpif *);
664
665 static struct ofproto *
666 alloc(void)
667 {
668     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
669     return &ofproto->up;
670 }
671
672 static void
673 dealloc(struct ofproto *ofproto_)
674 {
675     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
676     free(ofproto);
677 }
678
679 static int
680 construct(struct ofproto *ofproto_)
681 {
682     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
683     const char *name = ofproto->up.name;
684     int error;
685     int i;
686
687     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
688     if (error) {
689         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
690         return error;
691     }
692
693     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
694     ofproto->n_matches = 0;
695
696     dpif_flow_flush(ofproto->dpif);
697     dpif_recv_purge(ofproto->dpif);
698
699     error = dpif_recv_set(ofproto->dpif, true);
700     if (error) {
701         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
702         dpif_close(ofproto->dpif);
703         return error;
704     }
705
706     ofproto->netflow = NULL;
707     ofproto->sflow = NULL;
708     ofproto->stp = NULL;
709     hmap_init(&ofproto->bundles);
710     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
711     for (i = 0; i < MAX_MIRRORS; i++) {
712         ofproto->mirrors[i] = NULL;
713     }
714     ofproto->has_bonded_bundles = false;
715
716     timer_set_duration(&ofproto->next_expiration, 1000);
717
718     hmap_init(&ofproto->facets);
719     hmap_init(&ofproto->subfacets);
720     ofproto->governor = NULL;
721
722     for (i = 0; i < N_TABLES; i++) {
723         struct table_dpif *table = &ofproto->tables[i];
724
725         table->catchall_table = NULL;
726         table->other_table = NULL;
727         table->basis = random_uint32();
728     }
729     ofproto->need_revalidate = false;
730     tag_set_init(&ofproto->revalidate_set);
731
732     list_init(&ofproto->completions);
733
734     ofproto_dpif_unixctl_init();
735
736     ofproto->has_mirrors = false;
737     ofproto->has_bundle_action = false;
738
739     hmap_init(&ofproto->vlandev_map);
740     hmap_init(&ofproto->realdev_vid_map);
741
742     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
743                 hash_string(ofproto->up.name, 0));
744     memset(&ofproto->stats, 0, sizeof ofproto->stats);
745
746     ofproto_init_tables(ofproto_, N_TABLES);
747     error = add_internal_flows(ofproto);
748     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
749
750     return error;
751 }
752
753 static int
754 add_internal_flow(struct ofproto_dpif *ofproto, int id,
755                   const struct ofpbuf *actions, struct rule_dpif **rulep)
756 {
757     struct ofputil_flow_mod fm;
758     int error;
759
760     cls_rule_init_catchall(&fm.cr, 0);
761     cls_rule_set_reg(&fm.cr, 0, id);
762     fm.cookie = htonll(0);
763     fm.cookie_mask = htonll(0);
764     fm.table_id = TBL_INTERNAL;
765     fm.command = OFPFC_ADD;
766     fm.idle_timeout = 0;
767     fm.hard_timeout = 0;
768     fm.buffer_id = 0;
769     fm.out_port = 0;
770     fm.flags = 0;
771     fm.actions = actions->data;
772     fm.n_actions = actions->size / sizeof(union ofp_action);
773
774     error = ofproto_flow_mod(&ofproto->up, &fm);
775     if (error) {
776         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
777                     id, ofperr_to_string(error));
778         return error;
779     }
780
781     *rulep = rule_dpif_lookup__(ofproto, &fm.cr.flow, TBL_INTERNAL);
782     assert(*rulep != NULL);
783
784     return 0;
785 }
786
787 static int
788 add_internal_flows(struct ofproto_dpif *ofproto)
789 {
790     struct nx_action_controller *nac;
791     uint64_t actions_stub[128 / 8];
792     struct ofpbuf actions;
793     int error;
794     int id;
795
796     ofpbuf_use_stack(&actions, actions_stub, sizeof actions_stub);
797     id = 1;
798
799     nac = ofputil_put_NXAST_CONTROLLER(&actions);
800     nac->max_len = htons(UINT16_MAX);
801     nac->controller_id = htons(0);
802     nac->reason = OFPR_NO_MATCH;
803     error = add_internal_flow(ofproto, id++, &actions, &ofproto->miss_rule);
804     if (error) {
805         return error;
806     }
807
808     ofpbuf_clear(&actions);
809     error = add_internal_flow(ofproto, id++, &actions,
810                               &ofproto->no_packet_in_rule);
811     return error;
812 }
813
814 static void
815 complete_operations(struct ofproto_dpif *ofproto)
816 {
817     struct dpif_completion *c, *next;
818
819     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
820         ofoperation_complete(c->op, 0);
821         list_remove(&c->list_node);
822         free(c);
823     }
824 }
825
826 static void
827 destruct(struct ofproto *ofproto_)
828 {
829     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
830     struct rule_dpif *rule, *next_rule;
831     struct oftable *table;
832     int i;
833
834     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
835     complete_operations(ofproto);
836
837     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
838         struct cls_cursor cursor;
839
840         cls_cursor_init(&cursor, &table->cls, NULL);
841         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
842             ofproto_rule_destroy(&rule->up);
843         }
844     }
845
846     for (i = 0; i < MAX_MIRRORS; i++) {
847         mirror_destroy(ofproto->mirrors[i]);
848     }
849
850     netflow_destroy(ofproto->netflow);
851     dpif_sflow_destroy(ofproto->sflow);
852     hmap_destroy(&ofproto->bundles);
853     mac_learning_destroy(ofproto->ml);
854
855     hmap_destroy(&ofproto->facets);
856     hmap_destroy(&ofproto->subfacets);
857     governor_destroy(ofproto->governor);
858
859     hmap_destroy(&ofproto->vlandev_map);
860     hmap_destroy(&ofproto->realdev_vid_map);
861
862     dpif_close(ofproto->dpif);
863 }
864
865 static int
866 run_fast(struct ofproto *ofproto_)
867 {
868     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
869     unsigned int work;
870
871     /* Handle one or more batches of upcalls, until there's nothing left to do
872      * or until we do a fixed total amount of work.
873      *
874      * We do work in batches because it can be much cheaper to set up a number
875      * of flows and fire off their patches all at once.  We do multiple batches
876      * because in some cases handling a packet can cause another packet to be
877      * queued almost immediately as part of the return flow.  Both
878      * optimizations can make major improvements on some benchmarks and
879      * presumably for real traffic as well. */
880     work = 0;
881     while (work < FLOW_MISS_MAX_BATCH) {
882         int retval = handle_upcalls(ofproto, FLOW_MISS_MAX_BATCH - work);
883         if (retval <= 0) {
884             return -retval;
885         }
886         work += retval;
887     }
888     return 0;
889 }
890
891 static int
892 run(struct ofproto *ofproto_)
893 {
894     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
895     struct ofport_dpif *ofport;
896     struct ofbundle *bundle;
897     int error;
898
899     if (!clogged) {
900         complete_operations(ofproto);
901     }
902     dpif_run(ofproto->dpif);
903
904     error = run_fast(ofproto_);
905     if (error) {
906         return error;
907     }
908
909     if (timer_expired(&ofproto->next_expiration)) {
910         int delay = expire(ofproto);
911         timer_set_duration(&ofproto->next_expiration, delay);
912     }
913
914     if (ofproto->netflow) {
915         if (netflow_run(ofproto->netflow)) {
916             send_netflow_active_timeouts(ofproto);
917         }
918     }
919     if (ofproto->sflow) {
920         dpif_sflow_run(ofproto->sflow);
921     }
922
923     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
924         port_run(ofport);
925     }
926     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
927         bundle_run(bundle);
928     }
929
930     stp_run(ofproto);
931     mac_learning_run(ofproto->ml, &ofproto->revalidate_set);
932
933     /* Now revalidate if there's anything to do. */
934     if (ofproto->need_revalidate
935         || !tag_set_is_empty(&ofproto->revalidate_set)) {
936         struct tag_set revalidate_set = ofproto->revalidate_set;
937         bool revalidate_all = ofproto->need_revalidate;
938         struct facet *facet;
939
940         /* Clear the revalidation flags. */
941         tag_set_init(&ofproto->revalidate_set);
942         ofproto->need_revalidate = false;
943
944         HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
945             if (revalidate_all
946                 || tag_set_intersects(&revalidate_set, facet->tags)) {
947                 facet_revalidate(facet);
948             }
949         }
950     }
951
952     /* Check the consistency of a random facet, to aid debugging. */
953     if (!hmap_is_empty(&ofproto->facets) && !ofproto->need_revalidate) {
954         struct facet *facet;
955
956         facet = CONTAINER_OF(hmap_random_node(&ofproto->facets),
957                              struct facet, hmap_node);
958         if (!tag_set_intersects(&ofproto->revalidate_set, facet->tags)) {
959             if (!facet_check_consistency(facet)) {
960                 ofproto->need_revalidate = true;
961             }
962         }
963     }
964
965     if (ofproto->governor) {
966         size_t n_subfacets;
967
968         governor_run(ofproto->governor);
969
970         /* If the governor has shrunk to its minimum size and the number of
971          * subfacets has dwindled, then drop the governor entirely.
972          *
973          * For hysteresis, the number of subfacets to drop the governor is
974          * smaller than the number needed to trigger its creation. */
975         n_subfacets = hmap_count(&ofproto->subfacets);
976         if (n_subfacets * 4 < ofproto->up.flow_eviction_threshold
977             && governor_is_idle(ofproto->governor)) {
978             governor_destroy(ofproto->governor);
979             ofproto->governor = NULL;
980         }
981     }
982
983     return 0;
984 }
985
986 static void
987 wait(struct ofproto *ofproto_)
988 {
989     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
990     struct ofport_dpif *ofport;
991     struct ofbundle *bundle;
992
993     if (!clogged && !list_is_empty(&ofproto->completions)) {
994         poll_immediate_wake();
995     }
996
997     dpif_wait(ofproto->dpif);
998     dpif_recv_wait(ofproto->dpif);
999     if (ofproto->sflow) {
1000         dpif_sflow_wait(ofproto->sflow);
1001     }
1002     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
1003         poll_immediate_wake();
1004     }
1005     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1006         port_wait(ofport);
1007     }
1008     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1009         bundle_wait(bundle);
1010     }
1011     if (ofproto->netflow) {
1012         netflow_wait(ofproto->netflow);
1013     }
1014     mac_learning_wait(ofproto->ml);
1015     stp_wait(ofproto);
1016     if (ofproto->need_revalidate) {
1017         /* Shouldn't happen, but if it does just go around again. */
1018         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1019         poll_immediate_wake();
1020     } else {
1021         timer_wait(&ofproto->next_expiration);
1022     }
1023     if (ofproto->governor) {
1024         governor_wait(ofproto->governor);
1025     }
1026 }
1027
1028 static void
1029 flush(struct ofproto *ofproto_)
1030 {
1031     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1032     struct facet *facet, *next_facet;
1033
1034     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1035         /* Mark the facet as not installed so that facet_remove() doesn't
1036          * bother trying to uninstall it.  There is no point in uninstalling it
1037          * individually since we are about to blow away all the facets with
1038          * dpif_flow_flush(). */
1039         struct subfacet *subfacet;
1040
1041         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
1042             subfacet->installed = false;
1043             subfacet->dp_packet_count = 0;
1044             subfacet->dp_byte_count = 0;
1045         }
1046         facet_remove(facet);
1047     }
1048     dpif_flow_flush(ofproto->dpif);
1049 }
1050
1051 static void
1052 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1053              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1054 {
1055     *arp_match_ip = true;
1056     *actions = (OFPUTIL_A_OUTPUT |
1057                 OFPUTIL_A_SET_VLAN_VID |
1058                 OFPUTIL_A_SET_VLAN_PCP |
1059                 OFPUTIL_A_STRIP_VLAN |
1060                 OFPUTIL_A_SET_DL_SRC |
1061                 OFPUTIL_A_SET_DL_DST |
1062                 OFPUTIL_A_SET_NW_SRC |
1063                 OFPUTIL_A_SET_NW_DST |
1064                 OFPUTIL_A_SET_NW_TOS |
1065                 OFPUTIL_A_SET_TP_SRC |
1066                 OFPUTIL_A_SET_TP_DST |
1067                 OFPUTIL_A_ENQUEUE);
1068 }
1069
1070 static void
1071 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
1072 {
1073     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1074     struct dpif_dp_stats s;
1075
1076     strcpy(ots->name, "classifier");
1077
1078     dpif_get_dp_stats(ofproto->dpif, &s);
1079     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
1080     put_32aligned_be64(&ots->matched_count,
1081                        htonll(s.n_hit + ofproto->n_matches));
1082 }
1083
1084 static struct ofport *
1085 port_alloc(void)
1086 {
1087     struct ofport_dpif *port = xmalloc(sizeof *port);
1088     return &port->up;
1089 }
1090
1091 static void
1092 port_dealloc(struct ofport *port_)
1093 {
1094     struct ofport_dpif *port = ofport_dpif_cast(port_);
1095     free(port);
1096 }
1097
1098 static int
1099 port_construct(struct ofport *port_)
1100 {
1101     struct ofport_dpif *port = ofport_dpif_cast(port_);
1102     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1103
1104     ofproto->need_revalidate = true;
1105     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
1106     port->bundle = NULL;
1107     port->cfm = NULL;
1108     port->tag = tag_create_random();
1109     port->may_enable = true;
1110     port->stp_port = NULL;
1111     port->stp_state = STP_DISABLED;
1112     hmap_init(&port->priorities);
1113     port->realdev_ofp_port = 0;
1114     port->vlandev_vid = 0;
1115     port->carrier_seq = netdev_get_carrier_resets(port->up.netdev);
1116
1117     if (ofproto->sflow) {
1118         dpif_sflow_add_port(ofproto->sflow, port_);
1119     }
1120
1121     return 0;
1122 }
1123
1124 static void
1125 port_destruct(struct ofport *port_)
1126 {
1127     struct ofport_dpif *port = ofport_dpif_cast(port_);
1128     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1129
1130     ofproto->need_revalidate = true;
1131     bundle_remove(port_);
1132     set_cfm(port_, NULL);
1133     if (ofproto->sflow) {
1134         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1135     }
1136
1137     ofport_clear_priorities(port);
1138     hmap_destroy(&port->priorities);
1139 }
1140
1141 static void
1142 port_modified(struct ofport *port_)
1143 {
1144     struct ofport_dpif *port = ofport_dpif_cast(port_);
1145
1146     if (port->bundle && port->bundle->bond) {
1147         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1148     }
1149 }
1150
1151 static void
1152 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1153 {
1154     struct ofport_dpif *port = ofport_dpif_cast(port_);
1155     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1156     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1157
1158     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1159                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1160                    OFPUTIL_PC_NO_PACKET_IN)) {
1161         ofproto->need_revalidate = true;
1162
1163         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1164             bundle_update(port->bundle);
1165         }
1166     }
1167 }
1168
1169 static int
1170 set_sflow(struct ofproto *ofproto_,
1171           const struct ofproto_sflow_options *sflow_options)
1172 {
1173     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1174     struct dpif_sflow *ds = ofproto->sflow;
1175
1176     if (sflow_options) {
1177         if (!ds) {
1178             struct ofport_dpif *ofport;
1179
1180             ds = ofproto->sflow = dpif_sflow_create(ofproto->dpif);
1181             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1182                 dpif_sflow_add_port(ds, &ofport->up);
1183             }
1184             ofproto->need_revalidate = true;
1185         }
1186         dpif_sflow_set_options(ds, sflow_options);
1187     } else {
1188         if (ds) {
1189             dpif_sflow_destroy(ds);
1190             ofproto->need_revalidate = true;
1191             ofproto->sflow = NULL;
1192         }
1193     }
1194     return 0;
1195 }
1196
1197 static int
1198 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1199 {
1200     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1201     int error;
1202
1203     if (!s) {
1204         error = 0;
1205     } else {
1206         if (!ofport->cfm) {
1207             struct ofproto_dpif *ofproto;
1208
1209             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1210             ofproto->need_revalidate = true;
1211             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
1212         }
1213
1214         if (cfm_configure(ofport->cfm, s)) {
1215             return 0;
1216         }
1217
1218         error = EINVAL;
1219     }
1220     cfm_destroy(ofport->cfm);
1221     ofport->cfm = NULL;
1222     return error;
1223 }
1224
1225 static int
1226 get_cfm_fault(const struct ofport *ofport_)
1227 {
1228     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1229
1230     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
1231 }
1232
1233 static int
1234 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
1235                      size_t *n_rmps)
1236 {
1237     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1238
1239     if (ofport->cfm) {
1240         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
1241         return 0;
1242     } else {
1243         return -1;
1244     }
1245 }
1246
1247 static int
1248 get_cfm_health(const struct ofport *ofport_)
1249 {
1250     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1251
1252     return ofport->cfm ? cfm_get_health(ofport->cfm) : -1;
1253 }
1254 \f
1255 /* Spanning Tree. */
1256
1257 static void
1258 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1259 {
1260     struct ofproto_dpif *ofproto = ofproto_;
1261     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1262     struct ofport_dpif *ofport;
1263
1264     ofport = stp_port_get_aux(sp);
1265     if (!ofport) {
1266         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1267                      ofproto->up.name, port_num);
1268     } else {
1269         struct eth_header *eth = pkt->l2;
1270
1271         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1272         if (eth_addr_is_zero(eth->eth_src)) {
1273             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1274                          "with unknown MAC", ofproto->up.name, port_num);
1275         } else {
1276             send_packet(ofport, pkt);
1277         }
1278     }
1279     ofpbuf_delete(pkt);
1280 }
1281
1282 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1283 static int
1284 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1285 {
1286     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1287
1288     /* Only revalidate flows if the configuration changed. */
1289     if (!s != !ofproto->stp) {
1290         ofproto->need_revalidate = true;
1291     }
1292
1293     if (s) {
1294         if (!ofproto->stp) {
1295             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1296                                       send_bpdu_cb, ofproto);
1297             ofproto->stp_last_tick = time_msec();
1298         }
1299
1300         stp_set_bridge_id(ofproto->stp, s->system_id);
1301         stp_set_bridge_priority(ofproto->stp, s->priority);
1302         stp_set_hello_time(ofproto->stp, s->hello_time);
1303         stp_set_max_age(ofproto->stp, s->max_age);
1304         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1305     }  else {
1306         struct ofport *ofport;
1307
1308         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1309             set_stp_port(ofport, NULL);
1310         }
1311
1312         stp_destroy(ofproto->stp);
1313         ofproto->stp = NULL;
1314     }
1315
1316     return 0;
1317 }
1318
1319 static int
1320 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1321 {
1322     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1323
1324     if (ofproto->stp) {
1325         s->enabled = true;
1326         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1327         s->designated_root = stp_get_designated_root(ofproto->stp);
1328         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1329     } else {
1330         s->enabled = false;
1331     }
1332
1333     return 0;
1334 }
1335
1336 static void
1337 update_stp_port_state(struct ofport_dpif *ofport)
1338 {
1339     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1340     enum stp_state state;
1341
1342     /* Figure out new state. */
1343     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1344                              : STP_DISABLED;
1345
1346     /* Update state. */
1347     if (ofport->stp_state != state) {
1348         enum ofputil_port_state of_state;
1349         bool fwd_change;
1350
1351         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1352                     netdev_get_name(ofport->up.netdev),
1353                     stp_state_name(ofport->stp_state),
1354                     stp_state_name(state));
1355         if (stp_learn_in_state(ofport->stp_state)
1356                 != stp_learn_in_state(state)) {
1357             /* xxx Learning action flows should also be flushed. */
1358             mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
1359         }
1360         fwd_change = stp_forward_in_state(ofport->stp_state)
1361                         != stp_forward_in_state(state);
1362
1363         ofproto->need_revalidate = true;
1364         ofport->stp_state = state;
1365         ofport->stp_state_entered = time_msec();
1366
1367         if (fwd_change && ofport->bundle) {
1368             bundle_update(ofport->bundle);
1369         }
1370
1371         /* Update the STP state bits in the OpenFlow port description. */
1372         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1373         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1374                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1375                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1376                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1377                      : 0);
1378         ofproto_port_set_state(&ofport->up, of_state);
1379     }
1380 }
1381
1382 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1383  * caller is responsible for assigning STP port numbers and ensuring
1384  * there are no duplicates. */
1385 static int
1386 set_stp_port(struct ofport *ofport_,
1387              const struct ofproto_port_stp_settings *s)
1388 {
1389     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1390     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1391     struct stp_port *sp = ofport->stp_port;
1392
1393     if (!s || !s->enable) {
1394         if (sp) {
1395             ofport->stp_port = NULL;
1396             stp_port_disable(sp);
1397             update_stp_port_state(ofport);
1398         }
1399         return 0;
1400     } else if (sp && stp_port_no(sp) != s->port_num
1401             && ofport == stp_port_get_aux(sp)) {
1402         /* The port-id changed, so disable the old one if it's not
1403          * already in use by another port. */
1404         stp_port_disable(sp);
1405     }
1406
1407     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1408     stp_port_enable(sp);
1409
1410     stp_port_set_aux(sp, ofport);
1411     stp_port_set_priority(sp, s->priority);
1412     stp_port_set_path_cost(sp, s->path_cost);
1413
1414     update_stp_port_state(ofport);
1415
1416     return 0;
1417 }
1418
1419 static int
1420 get_stp_port_status(struct ofport *ofport_,
1421                     struct ofproto_port_stp_status *s)
1422 {
1423     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1424     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1425     struct stp_port *sp = ofport->stp_port;
1426
1427     if (!ofproto->stp || !sp) {
1428         s->enabled = false;
1429         return 0;
1430     }
1431
1432     s->enabled = true;
1433     s->port_id = stp_port_get_id(sp);
1434     s->state = stp_port_get_state(sp);
1435     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1436     s->role = stp_port_get_role(sp);
1437     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1438
1439     return 0;
1440 }
1441
1442 static void
1443 stp_run(struct ofproto_dpif *ofproto)
1444 {
1445     if (ofproto->stp) {
1446         long long int now = time_msec();
1447         long long int elapsed = now - ofproto->stp_last_tick;
1448         struct stp_port *sp;
1449
1450         if (elapsed > 0) {
1451             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1452             ofproto->stp_last_tick = now;
1453         }
1454         while (stp_get_changed_port(ofproto->stp, &sp)) {
1455             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1456
1457             if (ofport) {
1458                 update_stp_port_state(ofport);
1459             }
1460         }
1461
1462         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
1463             mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
1464         }
1465     }
1466 }
1467
1468 static void
1469 stp_wait(struct ofproto_dpif *ofproto)
1470 {
1471     if (ofproto->stp) {
1472         poll_timer_wait(1000);
1473     }
1474 }
1475
1476 /* Returns true if STP should process 'flow'. */
1477 static bool
1478 stp_should_process_flow(const struct flow *flow)
1479 {
1480     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1481 }
1482
1483 static void
1484 stp_process_packet(const struct ofport_dpif *ofport,
1485                    const struct ofpbuf *packet)
1486 {
1487     struct ofpbuf payload = *packet;
1488     struct eth_header *eth = payload.data;
1489     struct stp_port *sp = ofport->stp_port;
1490
1491     /* Sink packets on ports that have STP disabled when the bridge has
1492      * STP enabled. */
1493     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1494         return;
1495     }
1496
1497     /* Trim off padding on payload. */
1498     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1499         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1500     }
1501
1502     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1503         stp_received_bpdu(sp, payload.data, payload.size);
1504     }
1505 }
1506 \f
1507 static struct priority_to_dscp *
1508 get_priority(const struct ofport_dpif *ofport, uint32_t priority)
1509 {
1510     struct priority_to_dscp *pdscp;
1511     uint32_t hash;
1512
1513     hash = hash_int(priority, 0);
1514     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &ofport->priorities) {
1515         if (pdscp->priority == priority) {
1516             return pdscp;
1517         }
1518     }
1519     return NULL;
1520 }
1521
1522 static void
1523 ofport_clear_priorities(struct ofport_dpif *ofport)
1524 {
1525     struct priority_to_dscp *pdscp, *next;
1526
1527     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &ofport->priorities) {
1528         hmap_remove(&ofport->priorities, &pdscp->hmap_node);
1529         free(pdscp);
1530     }
1531 }
1532
1533 static int
1534 set_queues(struct ofport *ofport_,
1535            const struct ofproto_port_queue *qdscp_list,
1536            size_t n_qdscp)
1537 {
1538     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1539     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1540     struct hmap new = HMAP_INITIALIZER(&new);
1541     size_t i;
1542
1543     for (i = 0; i < n_qdscp; i++) {
1544         struct priority_to_dscp *pdscp;
1545         uint32_t priority;
1546         uint8_t dscp;
1547
1548         dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
1549         if (dpif_queue_to_priority(ofproto->dpif, qdscp_list[i].queue,
1550                                    &priority)) {
1551             continue;
1552         }
1553
1554         pdscp = get_priority(ofport, priority);
1555         if (pdscp) {
1556             hmap_remove(&ofport->priorities, &pdscp->hmap_node);
1557         } else {
1558             pdscp = xmalloc(sizeof *pdscp);
1559             pdscp->priority = priority;
1560             pdscp->dscp = dscp;
1561             ofproto->need_revalidate = true;
1562         }
1563
1564         if (pdscp->dscp != dscp) {
1565             pdscp->dscp = dscp;
1566             ofproto->need_revalidate = true;
1567         }
1568
1569         hmap_insert(&new, &pdscp->hmap_node, hash_int(pdscp->priority, 0));
1570     }
1571
1572     if (!hmap_is_empty(&ofport->priorities)) {
1573         ofport_clear_priorities(ofport);
1574         ofproto->need_revalidate = true;
1575     }
1576
1577     hmap_swap(&new, &ofport->priorities);
1578     hmap_destroy(&new);
1579
1580     return 0;
1581 }
1582 \f
1583 /* Bundles. */
1584
1585 /* Expires all MAC learning entries associated with 'bundle' and forces its
1586  * ofproto to revalidate every flow.
1587  *
1588  * Normally MAC learning entries are removed only from the ofproto associated
1589  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
1590  * are removed from every ofproto.  When patch ports and SLB bonds are in use
1591  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
1592  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
1593  * with the host from which it migrated. */
1594 static void
1595 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
1596 {
1597     struct ofproto_dpif *ofproto = bundle->ofproto;
1598     struct mac_learning *ml = ofproto->ml;
1599     struct mac_entry *mac, *next_mac;
1600
1601     ofproto->need_revalidate = true;
1602     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
1603         if (mac->port.p == bundle) {
1604             if (all_ofprotos) {
1605                 struct ofproto_dpif *o;
1606
1607                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
1608                     if (o != ofproto) {
1609                         struct mac_entry *e;
1610
1611                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan,
1612                                                 NULL);
1613                         if (e) {
1614                             tag_set_add(&o->revalidate_set, e->tag);
1615                             mac_learning_expire(o->ml, e);
1616                         }
1617                     }
1618                 }
1619             }
1620
1621             mac_learning_expire(ml, mac);
1622         }
1623     }
1624 }
1625
1626 static struct ofbundle *
1627 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
1628 {
1629     struct ofbundle *bundle;
1630
1631     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
1632                              &ofproto->bundles) {
1633         if (bundle->aux == aux) {
1634             return bundle;
1635         }
1636     }
1637     return NULL;
1638 }
1639
1640 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
1641  * ones that are found to 'bundles'. */
1642 static void
1643 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
1644                        void **auxes, size_t n_auxes,
1645                        struct hmapx *bundles)
1646 {
1647     size_t i;
1648
1649     hmapx_init(bundles);
1650     for (i = 0; i < n_auxes; i++) {
1651         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
1652         if (bundle) {
1653             hmapx_add(bundles, bundle);
1654         }
1655     }
1656 }
1657
1658 static void
1659 bundle_update(struct ofbundle *bundle)
1660 {
1661     struct ofport_dpif *port;
1662
1663     bundle->floodable = true;
1664     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1665         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
1666             || !stp_forward_in_state(port->stp_state)) {
1667             bundle->floodable = false;
1668             break;
1669         }
1670     }
1671 }
1672
1673 static void
1674 bundle_del_port(struct ofport_dpif *port)
1675 {
1676     struct ofbundle *bundle = port->bundle;
1677
1678     bundle->ofproto->need_revalidate = true;
1679
1680     list_remove(&port->bundle_node);
1681     port->bundle = NULL;
1682
1683     if (bundle->lacp) {
1684         lacp_slave_unregister(bundle->lacp, port);
1685     }
1686     if (bundle->bond) {
1687         bond_slave_unregister(bundle->bond, port);
1688     }
1689
1690     bundle_update(bundle);
1691 }
1692
1693 static bool
1694 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
1695                 struct lacp_slave_settings *lacp,
1696                 uint32_t bond_stable_id)
1697 {
1698     struct ofport_dpif *port;
1699
1700     port = get_ofp_port(bundle->ofproto, ofp_port);
1701     if (!port) {
1702         return false;
1703     }
1704
1705     if (port->bundle != bundle) {
1706         bundle->ofproto->need_revalidate = true;
1707         if (port->bundle) {
1708             bundle_del_port(port);
1709         }
1710
1711         port->bundle = bundle;
1712         list_push_back(&bundle->ports, &port->bundle_node);
1713         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
1714             || !stp_forward_in_state(port->stp_state)) {
1715             bundle->floodable = false;
1716         }
1717     }
1718     if (lacp) {
1719         port->bundle->ofproto->need_revalidate = true;
1720         lacp_slave_register(bundle->lacp, port, lacp);
1721     }
1722
1723     port->bond_stable_id = bond_stable_id;
1724
1725     return true;
1726 }
1727
1728 static void
1729 bundle_destroy(struct ofbundle *bundle)
1730 {
1731     struct ofproto_dpif *ofproto;
1732     struct ofport_dpif *port, *next_port;
1733     int i;
1734
1735     if (!bundle) {
1736         return;
1737     }
1738
1739     ofproto = bundle->ofproto;
1740     for (i = 0; i < MAX_MIRRORS; i++) {
1741         struct ofmirror *m = ofproto->mirrors[i];
1742         if (m) {
1743             if (m->out == bundle) {
1744                 mirror_destroy(m);
1745             } else if (hmapx_find_and_delete(&m->srcs, bundle)
1746                        || hmapx_find_and_delete(&m->dsts, bundle)) {
1747                 ofproto->need_revalidate = true;
1748             }
1749         }
1750     }
1751
1752     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1753         bundle_del_port(port);
1754     }
1755
1756     bundle_flush_macs(bundle, true);
1757     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
1758     free(bundle->name);
1759     free(bundle->trunks);
1760     lacp_destroy(bundle->lacp);
1761     bond_destroy(bundle->bond);
1762     free(bundle);
1763 }
1764
1765 static int
1766 bundle_set(struct ofproto *ofproto_, void *aux,
1767            const struct ofproto_bundle_settings *s)
1768 {
1769     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1770     bool need_flush = false;
1771     struct ofport_dpif *port;
1772     struct ofbundle *bundle;
1773     unsigned long *trunks;
1774     int vlan;
1775     size_t i;
1776     bool ok;
1777
1778     if (!s) {
1779         bundle_destroy(bundle_lookup(ofproto, aux));
1780         return 0;
1781     }
1782
1783     assert(s->n_slaves == 1 || s->bond != NULL);
1784     assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
1785
1786     bundle = bundle_lookup(ofproto, aux);
1787     if (!bundle) {
1788         bundle = xmalloc(sizeof *bundle);
1789
1790         bundle->ofproto = ofproto;
1791         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
1792                     hash_pointer(aux, 0));
1793         bundle->aux = aux;
1794         bundle->name = NULL;
1795
1796         list_init(&bundle->ports);
1797         bundle->vlan_mode = PORT_VLAN_TRUNK;
1798         bundle->vlan = -1;
1799         bundle->trunks = NULL;
1800         bundle->use_priority_tags = s->use_priority_tags;
1801         bundle->lacp = NULL;
1802         bundle->bond = NULL;
1803
1804         bundle->floodable = true;
1805
1806         bundle->src_mirrors = 0;
1807         bundle->dst_mirrors = 0;
1808         bundle->mirror_out = 0;
1809     }
1810
1811     if (!bundle->name || strcmp(s->name, bundle->name)) {
1812         free(bundle->name);
1813         bundle->name = xstrdup(s->name);
1814     }
1815
1816     /* LACP. */
1817     if (s->lacp) {
1818         if (!bundle->lacp) {
1819             ofproto->need_revalidate = true;
1820             bundle->lacp = lacp_create();
1821         }
1822         lacp_configure(bundle->lacp, s->lacp);
1823     } else {
1824         lacp_destroy(bundle->lacp);
1825         bundle->lacp = NULL;
1826     }
1827
1828     /* Update set of ports. */
1829     ok = true;
1830     for (i = 0; i < s->n_slaves; i++) {
1831         if (!bundle_add_port(bundle, s->slaves[i],
1832                              s->lacp ? &s->lacp_slaves[i] : NULL,
1833                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
1834             ok = false;
1835         }
1836     }
1837     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
1838         struct ofport_dpif *next_port;
1839
1840         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1841             for (i = 0; i < s->n_slaves; i++) {
1842                 if (s->slaves[i] == port->up.ofp_port) {
1843                     goto found;
1844                 }
1845             }
1846
1847             bundle_del_port(port);
1848         found: ;
1849         }
1850     }
1851     assert(list_size(&bundle->ports) <= s->n_slaves);
1852
1853     if (list_is_empty(&bundle->ports)) {
1854         bundle_destroy(bundle);
1855         return EINVAL;
1856     }
1857
1858     /* Set VLAN tagging mode */
1859     if (s->vlan_mode != bundle->vlan_mode
1860         || s->use_priority_tags != bundle->use_priority_tags) {
1861         bundle->vlan_mode = s->vlan_mode;
1862         bundle->use_priority_tags = s->use_priority_tags;
1863         need_flush = true;
1864     }
1865
1866     /* Set VLAN tag. */
1867     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
1868             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
1869             : 0);
1870     if (vlan != bundle->vlan) {
1871         bundle->vlan = vlan;
1872         need_flush = true;
1873     }
1874
1875     /* Get trunked VLANs. */
1876     switch (s->vlan_mode) {
1877     case PORT_VLAN_ACCESS:
1878         trunks = NULL;
1879         break;
1880
1881     case PORT_VLAN_TRUNK:
1882         trunks = (unsigned long *) s->trunks;
1883         break;
1884
1885     case PORT_VLAN_NATIVE_UNTAGGED:
1886     case PORT_VLAN_NATIVE_TAGGED:
1887         if (vlan != 0 && (!s->trunks
1888                           || !bitmap_is_set(s->trunks, vlan)
1889                           || bitmap_is_set(s->trunks, 0))) {
1890             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
1891             if (s->trunks) {
1892                 trunks = bitmap_clone(s->trunks, 4096);
1893             } else {
1894                 trunks = bitmap_allocate1(4096);
1895             }
1896             bitmap_set1(trunks, vlan);
1897             bitmap_set0(trunks, 0);
1898         } else {
1899             trunks = (unsigned long *) s->trunks;
1900         }
1901         break;
1902
1903     default:
1904         NOT_REACHED();
1905     }
1906     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
1907         free(bundle->trunks);
1908         if (trunks == s->trunks) {
1909             bundle->trunks = vlan_bitmap_clone(trunks);
1910         } else {
1911             bundle->trunks = trunks;
1912             trunks = NULL;
1913         }
1914         need_flush = true;
1915     }
1916     if (trunks != s->trunks) {
1917         free(trunks);
1918     }
1919
1920     /* Bonding. */
1921     if (!list_is_short(&bundle->ports)) {
1922         bundle->ofproto->has_bonded_bundles = true;
1923         if (bundle->bond) {
1924             if (bond_reconfigure(bundle->bond, s->bond)) {
1925                 ofproto->need_revalidate = true;
1926             }
1927         } else {
1928             bundle->bond = bond_create(s->bond);
1929             ofproto->need_revalidate = true;
1930         }
1931
1932         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1933             bond_slave_register(bundle->bond, port, port->bond_stable_id,
1934                                 port->up.netdev);
1935         }
1936     } else {
1937         bond_destroy(bundle->bond);
1938         bundle->bond = NULL;
1939     }
1940
1941     /* If we changed something that would affect MAC learning, un-learn
1942      * everything on this port and force flow revalidation. */
1943     if (need_flush) {
1944         bundle_flush_macs(bundle, false);
1945     }
1946
1947     return 0;
1948 }
1949
1950 static void
1951 bundle_remove(struct ofport *port_)
1952 {
1953     struct ofport_dpif *port = ofport_dpif_cast(port_);
1954     struct ofbundle *bundle = port->bundle;
1955
1956     if (bundle) {
1957         bundle_del_port(port);
1958         if (list_is_empty(&bundle->ports)) {
1959             bundle_destroy(bundle);
1960         } else if (list_is_short(&bundle->ports)) {
1961             bond_destroy(bundle->bond);
1962             bundle->bond = NULL;
1963         }
1964     }
1965 }
1966
1967 static void
1968 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
1969 {
1970     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1971     struct ofport_dpif *port = port_;
1972     uint8_t ea[ETH_ADDR_LEN];
1973     int error;
1974
1975     error = netdev_get_etheraddr(port->up.netdev, ea);
1976     if (!error) {
1977         struct ofpbuf packet;
1978         void *packet_pdu;
1979
1980         ofpbuf_init(&packet, 0);
1981         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
1982                                  pdu_size);
1983         memcpy(packet_pdu, pdu, pdu_size);
1984
1985         send_packet(port, &packet);
1986         ofpbuf_uninit(&packet);
1987     } else {
1988         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
1989                     "%s (%s)", port->bundle->name,
1990                     netdev_get_name(port->up.netdev), strerror(error));
1991     }
1992 }
1993
1994 static void
1995 bundle_send_learning_packets(struct ofbundle *bundle)
1996 {
1997     struct ofproto_dpif *ofproto = bundle->ofproto;
1998     int error, n_packets, n_errors;
1999     struct mac_entry *e;
2000
2001     error = n_packets = n_errors = 0;
2002     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2003         if (e->port.p != bundle) {
2004             struct ofpbuf *learning_packet;
2005             struct ofport_dpif *port;
2006             void *port_void;
2007             int ret;
2008
2009             /* The assignment to "port" is unnecessary but makes "grep"ing for
2010              * struct ofport_dpif more effective. */
2011             learning_packet = bond_compose_learning_packet(bundle->bond,
2012                                                            e->mac, e->vlan,
2013                                                            &port_void);
2014             port = port_void;
2015             ret = send_packet(port, learning_packet);
2016             ofpbuf_delete(learning_packet);
2017             if (ret) {
2018                 error = ret;
2019                 n_errors++;
2020             }
2021             n_packets++;
2022         }
2023     }
2024
2025     if (n_errors) {
2026         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2027         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2028                      "packets, last error was: %s",
2029                      bundle->name, n_errors, n_packets, strerror(error));
2030     } else {
2031         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2032                  bundle->name, n_packets);
2033     }
2034 }
2035
2036 static void
2037 bundle_run(struct ofbundle *bundle)
2038 {
2039     if (bundle->lacp) {
2040         lacp_run(bundle->lacp, send_pdu_cb);
2041     }
2042     if (bundle->bond) {
2043         struct ofport_dpif *port;
2044
2045         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2046             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2047         }
2048
2049         bond_run(bundle->bond, &bundle->ofproto->revalidate_set,
2050                  lacp_status(bundle->lacp));
2051         if (bond_should_send_learning_packets(bundle->bond)) {
2052             bundle_send_learning_packets(bundle);
2053         }
2054     }
2055 }
2056
2057 static void
2058 bundle_wait(struct ofbundle *bundle)
2059 {
2060     if (bundle->lacp) {
2061         lacp_wait(bundle->lacp);
2062     }
2063     if (bundle->bond) {
2064         bond_wait(bundle->bond);
2065     }
2066 }
2067 \f
2068 /* Mirrors. */
2069
2070 static int
2071 mirror_scan(struct ofproto_dpif *ofproto)
2072 {
2073     int idx;
2074
2075     for (idx = 0; idx < MAX_MIRRORS; idx++) {
2076         if (!ofproto->mirrors[idx]) {
2077             return idx;
2078         }
2079     }
2080     return -1;
2081 }
2082
2083 static struct ofmirror *
2084 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
2085 {
2086     int i;
2087
2088     for (i = 0; i < MAX_MIRRORS; i++) {
2089         struct ofmirror *mirror = ofproto->mirrors[i];
2090         if (mirror && mirror->aux == aux) {
2091             return mirror;
2092         }
2093     }
2094
2095     return NULL;
2096 }
2097
2098 /* Update the 'dup_mirrors' member of each of the ofmirrors in 'ofproto'. */
2099 static void
2100 mirror_update_dups(struct ofproto_dpif *ofproto)
2101 {
2102     int i;
2103
2104     for (i = 0; i < MAX_MIRRORS; i++) {
2105         struct ofmirror *m = ofproto->mirrors[i];
2106
2107         if (m) {
2108             m->dup_mirrors = MIRROR_MASK_C(1) << i;
2109         }
2110     }
2111
2112     for (i = 0; i < MAX_MIRRORS; i++) {
2113         struct ofmirror *m1 = ofproto->mirrors[i];
2114         int j;
2115
2116         if (!m1) {
2117             continue;
2118         }
2119
2120         for (j = i + 1; j < MAX_MIRRORS; j++) {
2121             struct ofmirror *m2 = ofproto->mirrors[j];
2122
2123             if (m2 && m1->out == m2->out && m1->out_vlan == m2->out_vlan) {
2124                 m1->dup_mirrors |= MIRROR_MASK_C(1) << j;
2125                 m2->dup_mirrors |= m1->dup_mirrors;
2126             }
2127         }
2128     }
2129 }
2130
2131 static int
2132 mirror_set(struct ofproto *ofproto_, void *aux,
2133            const struct ofproto_mirror_settings *s)
2134 {
2135     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2136     mirror_mask_t mirror_bit;
2137     struct ofbundle *bundle;
2138     struct ofmirror *mirror;
2139     struct ofbundle *out;
2140     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
2141     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
2142     int out_vlan;
2143
2144     mirror = mirror_lookup(ofproto, aux);
2145     if (!s) {
2146         mirror_destroy(mirror);
2147         return 0;
2148     }
2149     if (!mirror) {
2150         int idx;
2151
2152         idx = mirror_scan(ofproto);
2153         if (idx < 0) {
2154             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
2155                       "cannot create %s",
2156                       ofproto->up.name, MAX_MIRRORS, s->name);
2157             return EFBIG;
2158         }
2159
2160         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
2161         mirror->ofproto = ofproto;
2162         mirror->idx = idx;
2163         mirror->aux = aux;
2164         mirror->out_vlan = -1;
2165         mirror->name = NULL;
2166     }
2167
2168     if (!mirror->name || strcmp(s->name, mirror->name)) {
2169         free(mirror->name);
2170         mirror->name = xstrdup(s->name);
2171     }
2172
2173     /* Get the new configuration. */
2174     if (s->out_bundle) {
2175         out = bundle_lookup(ofproto, s->out_bundle);
2176         if (!out) {
2177             mirror_destroy(mirror);
2178             return EINVAL;
2179         }
2180         out_vlan = -1;
2181     } else {
2182         out = NULL;
2183         out_vlan = s->out_vlan;
2184     }
2185     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
2186     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
2187
2188     /* If the configuration has not changed, do nothing. */
2189     if (hmapx_equals(&srcs, &mirror->srcs)
2190         && hmapx_equals(&dsts, &mirror->dsts)
2191         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
2192         && mirror->out == out
2193         && mirror->out_vlan == out_vlan)
2194     {
2195         hmapx_destroy(&srcs);
2196         hmapx_destroy(&dsts);
2197         return 0;
2198     }
2199
2200     hmapx_swap(&srcs, &mirror->srcs);
2201     hmapx_destroy(&srcs);
2202
2203     hmapx_swap(&dsts, &mirror->dsts);
2204     hmapx_destroy(&dsts);
2205
2206     free(mirror->vlans);
2207     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
2208
2209     mirror->out = out;
2210     mirror->out_vlan = out_vlan;
2211
2212     /* Update bundles. */
2213     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2214     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
2215         if (hmapx_contains(&mirror->srcs, bundle)) {
2216             bundle->src_mirrors |= mirror_bit;
2217         } else {
2218             bundle->src_mirrors &= ~mirror_bit;
2219         }
2220
2221         if (hmapx_contains(&mirror->dsts, bundle)) {
2222             bundle->dst_mirrors |= mirror_bit;
2223         } else {
2224             bundle->dst_mirrors &= ~mirror_bit;
2225         }
2226
2227         if (mirror->out == bundle) {
2228             bundle->mirror_out |= mirror_bit;
2229         } else {
2230             bundle->mirror_out &= ~mirror_bit;
2231         }
2232     }
2233
2234     ofproto->need_revalidate = true;
2235     ofproto->has_mirrors = true;
2236     mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
2237     mirror_update_dups(ofproto);
2238
2239     return 0;
2240 }
2241
2242 static void
2243 mirror_destroy(struct ofmirror *mirror)
2244 {
2245     struct ofproto_dpif *ofproto;
2246     mirror_mask_t mirror_bit;
2247     struct ofbundle *bundle;
2248     int i;
2249
2250     if (!mirror) {
2251         return;
2252     }
2253
2254     ofproto = mirror->ofproto;
2255     ofproto->need_revalidate = true;
2256     mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
2257
2258     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2259     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2260         bundle->src_mirrors &= ~mirror_bit;
2261         bundle->dst_mirrors &= ~mirror_bit;
2262         bundle->mirror_out &= ~mirror_bit;
2263     }
2264
2265     hmapx_destroy(&mirror->srcs);
2266     hmapx_destroy(&mirror->dsts);
2267     free(mirror->vlans);
2268
2269     ofproto->mirrors[mirror->idx] = NULL;
2270     free(mirror->name);
2271     free(mirror);
2272
2273     mirror_update_dups(ofproto);
2274
2275     ofproto->has_mirrors = false;
2276     for (i = 0; i < MAX_MIRRORS; i++) {
2277         if (ofproto->mirrors[i]) {
2278             ofproto->has_mirrors = true;
2279             break;
2280         }
2281     }
2282 }
2283
2284 static int
2285 mirror_get_stats(struct ofproto *ofproto_, void *aux,
2286                  uint64_t *packets, uint64_t *bytes)
2287 {
2288     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2289     struct ofmirror *mirror = mirror_lookup(ofproto, aux);
2290
2291     if (!mirror) {
2292         *packets = *bytes = UINT64_MAX;
2293         return 0;
2294     }
2295
2296     *packets = mirror->packet_count;
2297     *bytes = mirror->byte_count;
2298
2299     return 0;
2300 }
2301
2302 static int
2303 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2304 {
2305     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2306     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2307         mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
2308     }
2309     return 0;
2310 }
2311
2312 static bool
2313 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2314 {
2315     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2316     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2317     return bundle && bundle->mirror_out != 0;
2318 }
2319
2320 static void
2321 forward_bpdu_changed(struct ofproto *ofproto_)
2322 {
2323     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2324     /* Revalidate cached flows whenever forward_bpdu option changes. */
2325     ofproto->need_revalidate = true;
2326 }
2327
2328 static void
2329 set_mac_idle_time(struct ofproto *ofproto_, unsigned int idle_time)
2330 {
2331     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2332     mac_learning_set_idle_time(ofproto->ml, idle_time);
2333 }
2334 \f
2335 /* Ports. */
2336
2337 static struct ofport_dpif *
2338 get_ofp_port(struct ofproto_dpif *ofproto, uint16_t ofp_port)
2339 {
2340     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2341     return ofport ? ofport_dpif_cast(ofport) : NULL;
2342 }
2343
2344 static struct ofport_dpif *
2345 get_odp_port(struct ofproto_dpif *ofproto, uint32_t odp_port)
2346 {
2347     return get_ofp_port(ofproto, odp_port_to_ofp_port(odp_port));
2348 }
2349
2350 static void
2351 ofproto_port_from_dpif_port(struct ofproto_port *ofproto_port,
2352                             struct dpif_port *dpif_port)
2353 {
2354     ofproto_port->name = dpif_port->name;
2355     ofproto_port->type = dpif_port->type;
2356     ofproto_port->ofp_port = odp_port_to_ofp_port(dpif_port->port_no);
2357 }
2358
2359 static void
2360 port_run(struct ofport_dpif *ofport)
2361 {
2362     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2363     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2364     bool enable = netdev_get_carrier(ofport->up.netdev);
2365
2366     ofport->carrier_seq = carrier_seq;
2367
2368     if (ofport->cfm) {
2369         cfm_run(ofport->cfm);
2370
2371         if (cfm_should_send_ccm(ofport->cfm)) {
2372             struct ofpbuf packet;
2373
2374             ofpbuf_init(&packet, 0);
2375             cfm_compose_ccm(ofport->cfm, &packet, ofport->up.pp.hw_addr);
2376             send_packet(ofport, &packet);
2377             ofpbuf_uninit(&packet);
2378         }
2379
2380         enable = enable && !cfm_get_fault(ofport->cfm)
2381             && cfm_get_opup(ofport->cfm);
2382     }
2383
2384     if (ofport->bundle) {
2385         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2386         if (carrier_changed) {
2387             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2388         }
2389     }
2390
2391     if (ofport->may_enable != enable) {
2392         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2393
2394         if (ofproto->has_bundle_action) {
2395             ofproto->need_revalidate = true;
2396         }
2397     }
2398
2399     ofport->may_enable = enable;
2400 }
2401
2402 static void
2403 port_wait(struct ofport_dpif *ofport)
2404 {
2405     if (ofport->cfm) {
2406         cfm_wait(ofport->cfm);
2407     }
2408 }
2409
2410 static int
2411 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2412                    struct ofproto_port *ofproto_port)
2413 {
2414     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2415     struct dpif_port dpif_port;
2416     int error;
2417
2418     error = dpif_port_query_by_name(ofproto->dpif, devname, &dpif_port);
2419     if (!error) {
2420         ofproto_port_from_dpif_port(ofproto_port, &dpif_port);
2421     }
2422     return error;
2423 }
2424
2425 static int
2426 port_add(struct ofproto *ofproto_, struct netdev *netdev, uint16_t *ofp_portp)
2427 {
2428     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2429     uint16_t odp_port;
2430     int error;
2431
2432     error = dpif_port_add(ofproto->dpif, netdev, &odp_port);
2433     if (!error) {
2434         *ofp_portp = odp_port_to_ofp_port(odp_port);
2435     }
2436     return error;
2437 }
2438
2439 static int
2440 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
2441 {
2442     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2443     int error;
2444
2445     error = dpif_port_del(ofproto->dpif, ofp_port_to_odp_port(ofp_port));
2446     if (!error) {
2447         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
2448         if (ofport) {
2449             /* The caller is going to close ofport->up.netdev.  If this is a
2450              * bonded port, then the bond is using that netdev, so remove it
2451              * from the bond.  The client will need to reconfigure everything
2452              * after deleting ports, so then the slave will get re-added. */
2453             bundle_remove(&ofport->up);
2454         }
2455     }
2456     return error;
2457 }
2458
2459 static int
2460 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
2461 {
2462     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2463     int error;
2464
2465     error = netdev_get_stats(ofport->up.netdev, stats);
2466
2467     if (!error && ofport->odp_port == OVSP_LOCAL) {
2468         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2469
2470         /* ofproto->stats.tx_packets represents packets that we created
2471          * internally and sent to some port (e.g. packets sent with
2472          * send_packet()).  Account for them as if they had come from
2473          * OFPP_LOCAL and got forwarded. */
2474
2475         if (stats->rx_packets != UINT64_MAX) {
2476             stats->rx_packets += ofproto->stats.tx_packets;
2477         }
2478
2479         if (stats->rx_bytes != UINT64_MAX) {
2480             stats->rx_bytes += ofproto->stats.tx_bytes;
2481         }
2482
2483         /* ofproto->stats.rx_packets represents packets that were received on
2484          * some port and we processed internally and dropped (e.g. STP).
2485          * Account fro them as if they had been forwarded to OFPP_LOCAL. */
2486
2487         if (stats->tx_packets != UINT64_MAX) {
2488             stats->tx_packets += ofproto->stats.rx_packets;
2489         }
2490
2491         if (stats->tx_bytes != UINT64_MAX) {
2492             stats->tx_bytes += ofproto->stats.rx_bytes;
2493         }
2494     }
2495
2496     return error;
2497 }
2498
2499 /* Account packets for LOCAL port. */
2500 static void
2501 ofproto_update_local_port_stats(const struct ofproto *ofproto_,
2502                                 size_t tx_size, size_t rx_size)
2503 {
2504     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2505
2506     if (rx_size) {
2507         ofproto->stats.rx_packets++;
2508         ofproto->stats.rx_bytes += rx_size;
2509     }
2510     if (tx_size) {
2511         ofproto->stats.tx_packets++;
2512         ofproto->stats.tx_bytes += tx_size;
2513     }
2514 }
2515
2516 struct port_dump_state {
2517     struct dpif_port_dump dump;
2518     bool done;
2519 };
2520
2521 static int
2522 port_dump_start(const struct ofproto *ofproto_, void **statep)
2523 {
2524     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2525     struct port_dump_state *state;
2526
2527     *statep = state = xmalloc(sizeof *state);
2528     dpif_port_dump_start(&state->dump, ofproto->dpif);
2529     state->done = false;
2530     return 0;
2531 }
2532
2533 static int
2534 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
2535                struct ofproto_port *port)
2536 {
2537     struct port_dump_state *state = state_;
2538     struct dpif_port dpif_port;
2539
2540     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
2541         ofproto_port_from_dpif_port(port, &dpif_port);
2542         return 0;
2543     } else {
2544         int error = dpif_port_dump_done(&state->dump);
2545         state->done = true;
2546         return error ? error : EOF;
2547     }
2548 }
2549
2550 static int
2551 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
2552 {
2553     struct port_dump_state *state = state_;
2554
2555     if (!state->done) {
2556         dpif_port_dump_done(&state->dump);
2557     }
2558     free(state);
2559     return 0;
2560 }
2561
2562 static int
2563 port_poll(const struct ofproto *ofproto_, char **devnamep)
2564 {
2565     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2566     return dpif_port_poll(ofproto->dpif, devnamep);
2567 }
2568
2569 static void
2570 port_poll_wait(const struct ofproto *ofproto_)
2571 {
2572     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2573     dpif_port_poll_wait(ofproto->dpif);
2574 }
2575
2576 static int
2577 port_is_lacp_current(const struct ofport *ofport_)
2578 {
2579     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2580     return (ofport->bundle && ofport->bundle->lacp
2581             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2582             : -1);
2583 }
2584 \f
2585 /* Upcall handling. */
2586
2587 /* Flow miss batching.
2588  *
2589  * Some dpifs implement operations faster when you hand them off in a batch.
2590  * To allow batching, "struct flow_miss" queues the dpif-related work needed
2591  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
2592  * more packets, plus possibly installing the flow in the dpif.
2593  *
2594  * So far we only batch the operations that affect flow setup time the most.
2595  * It's possible to batch more than that, but the benefit might be minimal. */
2596 struct flow_miss {
2597     struct hmap_node hmap_node;
2598     struct flow flow;
2599     enum odp_key_fitness key_fitness;
2600     const struct nlattr *key;
2601     size_t key_len;
2602     ovs_be16 initial_tci;
2603     struct list packets;
2604 };
2605
2606 struct flow_miss_op {
2607     struct dpif_op dpif_op;
2608     struct subfacet *subfacet;  /* Subfacet  */
2609     void *garbage;              /* Pointer to pass to free(), NULL if none. */
2610     uint64_t stub[1024 / 8];    /* Temporary buffer. */
2611 };
2612
2613 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
2614  * OpenFlow controller as necessary according to their individual
2615  * configurations. */
2616 static void
2617 send_packet_in_miss(struct ofproto_dpif *ofproto, const struct ofpbuf *packet,
2618                     const struct flow *flow)
2619 {
2620     struct ofputil_packet_in pin;
2621
2622     pin.packet = packet->data;
2623     pin.packet_len = packet->size;
2624     pin.reason = OFPR_NO_MATCH;
2625     pin.controller_id = 0;
2626
2627     pin.table_id = 0;
2628     pin.cookie = 0;
2629
2630     pin.send_len = 0;           /* not used for flow table misses */
2631
2632     flow_get_metadata(flow, &pin.fmd);
2633
2634     /* Registers aren't meaningful on a miss. */
2635     memset(pin.fmd.reg_masks, 0, sizeof pin.fmd.reg_masks);
2636
2637     connmgr_send_packet_in(ofproto->up.connmgr, &pin);
2638 }
2639
2640 static bool
2641 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
2642                 const struct ofpbuf *packet)
2643 {
2644     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
2645
2646     if (!ofport) {
2647         return false;
2648     }
2649
2650     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
2651         if (packet) {
2652             cfm_process_heartbeat(ofport->cfm, packet);
2653         }
2654         return true;
2655     } else if (ofport->bundle && ofport->bundle->lacp
2656                && flow->dl_type == htons(ETH_TYPE_LACP)) {
2657         if (packet) {
2658             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
2659         }
2660         return true;
2661     } else if (ofproto->stp && stp_should_process_flow(flow)) {
2662         if (packet) {
2663             stp_process_packet(ofport, packet);
2664         }
2665         return true;
2666     }
2667     return false;
2668 }
2669
2670 static struct flow_miss *
2671 flow_miss_find(struct hmap *todo, const struct flow *flow, uint32_t hash)
2672 {
2673     struct flow_miss *miss;
2674
2675     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
2676         if (flow_equal(&miss->flow, flow)) {
2677             return miss;
2678         }
2679     }
2680
2681     return NULL;
2682 }
2683
2684 /* Partially Initializes 'op' as an "execute" operation for 'miss' and
2685  * 'packet'.  The caller must initialize op->actions and op->actions_len.  If
2686  * 'miss' is associated with a subfacet the caller must also initialize the
2687  * returned op->subfacet, and if anything needs to be freed after processing
2688  * the op, the caller must initialize op->garbage also. */
2689 static void
2690 init_flow_miss_execute_op(struct flow_miss *miss, struct ofpbuf *packet,
2691                           struct flow_miss_op *op)
2692 {
2693     if (miss->flow.vlan_tci != miss->initial_tci) {
2694         /* This packet was received on a VLAN splinter port.  We
2695          * added a VLAN to the packet to make the packet resemble
2696          * the flow, but the actions were composed assuming that
2697          * the packet contained no VLAN.  So, we must remove the
2698          * VLAN header from the packet before trying to execute the
2699          * actions. */
2700         eth_pop_vlan(packet);
2701     }
2702
2703     op->subfacet = NULL;
2704     op->garbage = NULL;
2705     op->dpif_op.type = DPIF_OP_EXECUTE;
2706     op->dpif_op.u.execute.key = miss->key;
2707     op->dpif_op.u.execute.key_len = miss->key_len;
2708     op->dpif_op.u.execute.packet = packet;
2709 }
2710
2711 /* Helper for handle_flow_miss_without_facet() and
2712  * handle_flow_miss_with_facet(). */
2713 static void
2714 handle_flow_miss_common(struct rule_dpif *rule,
2715                         struct ofpbuf *packet, const struct flow *flow)
2716 {
2717     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2718
2719     ofproto->n_matches++;
2720
2721     if (rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
2722         /*
2723          * Extra-special case for fail-open mode.
2724          *
2725          * We are in fail-open mode and the packet matched the fail-open
2726          * rule, but we are connected to a controller too.  We should send
2727          * the packet up to the controller in the hope that it will try to
2728          * set up a flow and thereby allow us to exit fail-open.
2729          *
2730          * See the top-level comment in fail-open.c for more information.
2731          */
2732         send_packet_in_miss(ofproto, packet, flow);
2733     }
2734 }
2735
2736 /* Figures out whether a flow that missed in 'ofproto', whose details are in
2737  * 'miss', is likely to be worth tracking in detail in userspace and (usually)
2738  * installing a datapath flow.  The answer is usually "yes" (a return value of
2739  * true).  However, for short flows the cost of bookkeeping is much higher than
2740  * the benefits, so when the datapath holds a large number of flows we impose
2741  * some heuristics to decide which flows are likely to be worth tracking. */
2742 static bool
2743 flow_miss_should_make_facet(struct ofproto_dpif *ofproto,
2744                             struct flow_miss *miss, uint32_t hash)
2745 {
2746     if (!ofproto->governor) {
2747         size_t n_subfacets;
2748
2749         n_subfacets = hmap_count(&ofproto->subfacets);
2750         if (n_subfacets * 2 <= ofproto->up.flow_eviction_threshold) {
2751             return true;
2752         }
2753
2754         ofproto->governor = governor_create(ofproto->up.name);
2755     }
2756
2757     return governor_should_install_flow(ofproto->governor, hash,
2758                                         list_size(&miss->packets));
2759 }
2760
2761 /* Handles 'miss', which matches 'rule', without creating a facet or subfacet
2762  * or creating any datapath flow.  May add an "execute" operation to 'ops' and
2763  * increment '*n_ops'. */
2764 static void
2765 handle_flow_miss_without_facet(struct flow_miss *miss,
2766                                struct rule_dpif *rule,
2767                                struct flow_miss_op *ops, size_t *n_ops)
2768 {
2769     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2770     struct action_xlate_ctx ctx;
2771     struct ofpbuf *packet;
2772
2773     LIST_FOR_EACH (packet, list_node, &miss->packets) {
2774         struct flow_miss_op *op = &ops[*n_ops];
2775         struct dpif_flow_stats stats;
2776         struct ofpbuf odp_actions;
2777
2778         COVERAGE_INC(facet_suppress);
2779
2780         ofpbuf_use_stub(&odp_actions, op->stub, sizeof op->stub);
2781
2782         dpif_flow_stats_extract(&miss->flow, packet, &stats);
2783         rule_credit_stats(rule, &stats);
2784
2785         action_xlate_ctx_init(&ctx, ofproto, &miss->flow, miss->initial_tci,
2786                               rule, 0, packet);
2787         ctx.resubmit_stats = &stats;
2788         xlate_actions(&ctx, rule->up.actions, rule->up.n_actions,
2789                       &odp_actions);
2790
2791         if (odp_actions.size) {
2792             struct dpif_execute *execute = &op->dpif_op.u.execute;
2793
2794             init_flow_miss_execute_op(miss, packet, op);
2795             execute->actions = odp_actions.data;
2796             execute->actions_len = odp_actions.size;
2797             op->garbage = ofpbuf_get_uninit_pointer(&odp_actions);
2798
2799             (*n_ops)++;
2800         } else {
2801             ofpbuf_uninit(&odp_actions);
2802         }
2803     }
2804 }
2805
2806 /* Handles 'miss', which matches 'facet'.  May add any required datapath
2807  * operations to 'ops', incrementing '*n_ops' for each new op. */
2808 static void
2809 handle_flow_miss_with_facet(struct flow_miss *miss, struct facet *facet,
2810                             struct flow_miss_op *ops, size_t *n_ops)
2811 {
2812     struct subfacet *subfacet;
2813     struct ofpbuf *packet;
2814
2815     subfacet = subfacet_create(facet,
2816                                miss->key_fitness, miss->key, miss->key_len,
2817                                miss->initial_tci);
2818
2819     LIST_FOR_EACH (packet, list_node, &miss->packets) {
2820         struct flow_miss_op *op = &ops[*n_ops];
2821         struct dpif_flow_stats stats;
2822         struct ofpbuf odp_actions;
2823
2824         handle_flow_miss_common(facet->rule, packet, &miss->flow);
2825
2826         ofpbuf_use_stub(&odp_actions, op->stub, sizeof op->stub);
2827         if (!facet->may_install || !subfacet->actions) {
2828             subfacet_make_actions(subfacet, packet, &odp_actions);
2829         }
2830
2831         dpif_flow_stats_extract(&facet->flow, packet, &stats);
2832         subfacet_update_stats(subfacet, &stats);
2833
2834         if (subfacet->actions_len) {
2835             struct dpif_execute *execute = &op->dpif_op.u.execute;
2836
2837             init_flow_miss_execute_op(miss, packet, op);
2838             op->subfacet = subfacet;
2839             if (facet->may_install) {
2840                 execute->actions = subfacet->actions;
2841                 execute->actions_len = subfacet->actions_len;
2842                 ofpbuf_uninit(&odp_actions);
2843             } else {
2844                 execute->actions = odp_actions.data;
2845                 execute->actions_len = odp_actions.size;
2846                 op->garbage = ofpbuf_get_uninit_pointer(&odp_actions);
2847             }
2848
2849             (*n_ops)++;
2850         } else {
2851             ofpbuf_uninit(&odp_actions);
2852         }
2853     }
2854
2855     if (facet->may_install && subfacet->key_fitness != ODP_FIT_TOO_LITTLE) {
2856         struct flow_miss_op *op = &ops[(*n_ops)++];
2857         struct dpif_flow_put *put = &op->dpif_op.u.flow_put;
2858
2859         op->subfacet = subfacet;
2860         op->garbage = NULL;
2861         op->dpif_op.type = DPIF_OP_FLOW_PUT;
2862         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2863         put->key = miss->key;
2864         put->key_len = miss->key_len;
2865         put->actions = subfacet->actions;
2866         put->actions_len = subfacet->actions_len;
2867         put->stats = NULL;
2868     }
2869 }
2870
2871 /* Handles flow miss 'miss' on 'ofproto'.  May add any required datapath
2872  * operations to 'ops', incrementing '*n_ops' for each new op. */
2873 static void
2874 handle_flow_miss(struct ofproto_dpif *ofproto, struct flow_miss *miss,
2875                  struct flow_miss_op *ops, size_t *n_ops)
2876 {
2877     struct facet *facet;
2878     uint32_t hash;
2879
2880     /* The caller must ensure that miss->hmap_node.hash contains
2881      * flow_hash(miss->flow, 0). */
2882     hash = miss->hmap_node.hash;
2883
2884     facet = facet_lookup_valid(ofproto, &miss->flow, hash);
2885     if (!facet) {
2886         struct rule_dpif *rule = rule_dpif_lookup(ofproto, &miss->flow);
2887
2888         if (!flow_miss_should_make_facet(ofproto, miss, hash)) {
2889             handle_flow_miss_without_facet(miss, rule, ops, n_ops);
2890             return;
2891         }
2892
2893         facet = facet_create(rule, &miss->flow, hash);
2894     }
2895     handle_flow_miss_with_facet(miss, facet, ops, n_ops);
2896 }
2897
2898 /* Like odp_flow_key_to_flow(), this function converts the 'key_len' bytes of
2899  * OVS_KEY_ATTR_* attributes in 'key' to a flow structure in 'flow' and returns
2900  * an ODP_FIT_* value that indicates how well 'key' fits our expectations for
2901  * what a flow key should contain.
2902  *
2903  * This function also includes some logic to help make VLAN splinters
2904  * transparent to the rest of the upcall processing logic.  In particular, if
2905  * the extracted in_port is a VLAN splinter port, it replaces flow->in_port by
2906  * the "real" port, sets flow->vlan_tci correctly for the VLAN of the VLAN
2907  * splinter port, and pushes a VLAN header onto 'packet' (if it is nonnull).
2908  *
2909  * Sets '*initial_tci' to the VLAN TCI with which the packet was really
2910  * received, that is, the actual VLAN TCI extracted by odp_flow_key_to_flow().
2911  * (This differs from the value returned in flow->vlan_tci only for packets
2912  * received on VLAN splinters.)
2913  */
2914 static enum odp_key_fitness
2915 ofproto_dpif_extract_flow_key(const struct ofproto_dpif *ofproto,
2916                               const struct nlattr *key, size_t key_len,
2917                               struct flow *flow, ovs_be16 *initial_tci,
2918                               struct ofpbuf *packet)
2919 {
2920     enum odp_key_fitness fitness;
2921
2922     fitness = odp_flow_key_to_flow(key, key_len, flow);
2923     if (fitness == ODP_FIT_ERROR) {
2924         return fitness;
2925     }
2926     *initial_tci = flow->vlan_tci;
2927
2928     if (vsp_adjust_flow(ofproto, flow)) {
2929         if (packet) {
2930             /* Make the packet resemble the flow, so that it gets sent to an
2931              * OpenFlow controller properly, so that it looks correct for
2932              * sFlow, and so that flow_extract() will get the correct vlan_tci
2933              * if it is called on 'packet'.
2934              *
2935              * The allocated space inside 'packet' probably also contains
2936              * 'key', that is, both 'packet' and 'key' are probably part of a
2937              * struct dpif_upcall (see the large comment on that structure
2938              * definition), so pushing data on 'packet' is in general not a
2939              * good idea since it could overwrite 'key' or free it as a side
2940              * effect.  However, it's OK in this special case because we know
2941              * that 'packet' is inside a Netlink attribute: pushing 4 bytes
2942              * will just overwrite the 4-byte "struct nlattr", which is fine
2943              * since we don't need that header anymore. */
2944             eth_push_vlan(packet, flow->vlan_tci);
2945         }
2946
2947         /* Let the caller know that we can't reproduce 'key' from 'flow'. */
2948         if (fitness == ODP_FIT_PERFECT) {
2949             fitness = ODP_FIT_TOO_MUCH;
2950         }
2951     }
2952
2953     return fitness;
2954 }
2955
2956 static void
2957 handle_miss_upcalls(struct ofproto_dpif *ofproto, struct dpif_upcall *upcalls,
2958                     size_t n_upcalls)
2959 {
2960     struct dpif_upcall *upcall;
2961     struct flow_miss *miss;
2962     struct flow_miss misses[FLOW_MISS_MAX_BATCH];
2963     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
2964     struct dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
2965     struct hmap todo;
2966     int n_misses;
2967     size_t n_ops;
2968     size_t i;
2969
2970     if (!n_upcalls) {
2971         return;
2972     }
2973
2974     /* Construct the to-do list.
2975      *
2976      * This just amounts to extracting the flow from each packet and sticking
2977      * the packets that have the same flow in the same "flow_miss" structure so
2978      * that we can process them together. */
2979     hmap_init(&todo);
2980     n_misses = 0;
2981     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
2982         struct flow_miss *miss = &misses[n_misses];
2983         struct flow_miss *existing_miss;
2984         uint32_t hash;
2985
2986         /* Obtain metadata and check userspace/kernel agreement on flow match,
2987          * then set 'flow''s header pointers. */
2988         miss->key_fitness = ofproto_dpif_extract_flow_key(
2989             ofproto, upcall->key, upcall->key_len,
2990             &miss->flow, &miss->initial_tci, upcall->packet);
2991         if (miss->key_fitness == ODP_FIT_ERROR) {
2992             continue;
2993         }
2994         flow_extract(upcall->packet, miss->flow.skb_priority,
2995                      miss->flow.tun_id, miss->flow.in_port, &miss->flow);
2996
2997         /* Handle 802.1ag, LACP, and STP specially. */
2998         if (process_special(ofproto, &miss->flow, upcall->packet)) {
2999             ofproto_update_local_port_stats(&ofproto->up,
3000                                             0, upcall->packet->size);
3001             ofproto->n_matches++;
3002             continue;
3003         }
3004
3005         /* Add other packets to a to-do list. */
3006         hash = flow_hash(&miss->flow, 0);
3007         existing_miss = flow_miss_find(&todo, &miss->flow, hash);
3008         if (!existing_miss) {
3009             hmap_insert(&todo, &miss->hmap_node, hash);
3010             miss->key = upcall->key;
3011             miss->key_len = upcall->key_len;
3012             list_init(&miss->packets);
3013
3014             n_misses++;
3015         } else {
3016             miss = existing_miss;
3017         }
3018         list_push_back(&miss->packets, &upcall->packet->list_node);
3019     }
3020
3021     /* Process each element in the to-do list, constructing the set of
3022      * operations to batch. */
3023     n_ops = 0;
3024     HMAP_FOR_EACH (miss, hmap_node, &todo) {
3025         handle_flow_miss(ofproto, miss, flow_miss_ops, &n_ops);
3026     }
3027     assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
3028
3029     /* Execute batch. */
3030     for (i = 0; i < n_ops; i++) {
3031         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
3032     }
3033     dpif_operate(ofproto->dpif, dpif_ops, n_ops);
3034
3035     /* Free memory and update facets. */
3036     for (i = 0; i < n_ops; i++) {
3037         struct flow_miss_op *op = &flow_miss_ops[i];
3038
3039         switch (op->dpif_op.type) {
3040         case DPIF_OP_EXECUTE:
3041             break;
3042
3043         case DPIF_OP_FLOW_PUT:
3044             if (!op->dpif_op.error) {
3045                 op->subfacet->installed = true;
3046             }
3047             break;
3048
3049         case DPIF_OP_FLOW_DEL:
3050             NOT_REACHED();
3051         }
3052
3053         free(op->garbage);
3054     }
3055     hmap_destroy(&todo);
3056 }
3057
3058 static void
3059 handle_userspace_upcall(struct ofproto_dpif *ofproto,
3060                         struct dpif_upcall *upcall)
3061 {
3062     union user_action_cookie cookie;
3063     enum odp_key_fitness fitness;
3064     ovs_be16 initial_tci;
3065     struct flow flow;
3066
3067     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
3068
3069     fitness = ofproto_dpif_extract_flow_key(ofproto, upcall->key,
3070                                             upcall->key_len, &flow,
3071                                             &initial_tci, upcall->packet);
3072     if (fitness == ODP_FIT_ERROR) {
3073         return;
3074     }
3075
3076     switch (cookie.type) {
3077     case USER_ACTION_COOKIE_SFLOW:
3078         if (ofproto->sflow) {
3079             dpif_sflow_received(ofproto->sflow, upcall->packet, &flow,
3080                                 &cookie);
3081         }
3082         break;
3083
3084     case USER_ACTION_COOKIE_UNSPEC:
3085     default:
3086         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
3087         break;
3088     }
3089 }
3090
3091 static int
3092 handle_upcalls(struct ofproto_dpif *ofproto, unsigned int max_batch)
3093 {
3094     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
3095     struct ofpbuf miss_bufs[FLOW_MISS_MAX_BATCH];
3096     uint64_t miss_buf_stubs[FLOW_MISS_MAX_BATCH][4096 / 8];
3097     int n_processed;
3098     int n_misses;
3099     int i;
3100
3101     assert(max_batch <= FLOW_MISS_MAX_BATCH);
3102
3103     n_processed = 0;
3104     n_misses = 0;
3105     for (n_processed = 0; n_processed < max_batch; n_processed++) {
3106         struct dpif_upcall *upcall = &misses[n_misses];
3107         struct ofpbuf *buf = &miss_bufs[n_misses];
3108         int error;
3109
3110         ofpbuf_use_stub(buf, miss_buf_stubs[n_misses],
3111                         sizeof miss_buf_stubs[n_misses]);
3112         error = dpif_recv(ofproto->dpif, upcall, buf);
3113         if (error) {
3114             ofpbuf_uninit(buf);
3115             break;
3116         }
3117
3118         switch (upcall->type) {
3119         case DPIF_UC_ACTION:
3120             handle_userspace_upcall(ofproto, upcall);
3121             ofpbuf_uninit(buf);
3122             break;
3123
3124         case DPIF_UC_MISS:
3125             /* Handle it later. */
3126             n_misses++;
3127             break;
3128
3129         case DPIF_N_UC_TYPES:
3130         default:
3131             VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32,
3132                          upcall->type);
3133             break;
3134         }
3135     }
3136
3137     handle_miss_upcalls(ofproto, misses, n_misses);
3138     for (i = 0; i < n_misses; i++) {
3139         ofpbuf_uninit(&miss_bufs[i]);
3140     }
3141
3142     return n_processed;
3143 }
3144 \f
3145 /* Flow expiration. */
3146
3147 static int subfacet_max_idle(const struct ofproto_dpif *);
3148 static void update_stats(struct ofproto_dpif *);
3149 static void rule_expire(struct rule_dpif *);
3150 static void expire_subfacets(struct ofproto_dpif *, int dp_max_idle);
3151
3152 /* This function is called periodically by run().  Its job is to collect
3153  * updates for the flows that have been installed into the datapath, most
3154  * importantly when they last were used, and then use that information to
3155  * expire flows that have not been used recently.
3156  *
3157  * Returns the number of milliseconds after which it should be called again. */
3158 static int
3159 expire(struct ofproto_dpif *ofproto)
3160 {
3161     struct rule_dpif *rule, *next_rule;
3162     struct oftable *table;
3163     int dp_max_idle;
3164
3165     /* Update stats for each flow in the datapath. */
3166     update_stats(ofproto);
3167
3168     /* Expire subfacets that have been idle too long. */
3169     dp_max_idle = subfacet_max_idle(ofproto);
3170     expire_subfacets(ofproto, dp_max_idle);
3171
3172     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
3173     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
3174         struct cls_cursor cursor;
3175
3176         cls_cursor_init(&cursor, &table->cls, NULL);
3177         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
3178             rule_expire(rule);
3179         }
3180     }
3181
3182     /* All outstanding data in existing flows has been accounted, so it's a
3183      * good time to do bond rebalancing. */
3184     if (ofproto->has_bonded_bundles) {
3185         struct ofbundle *bundle;
3186
3187         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
3188             if (bundle->bond) {
3189                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
3190             }
3191         }
3192     }
3193
3194     return MIN(dp_max_idle, 1000);
3195 }
3196
3197 /* Updates flow table statistics given that the datapath just reported 'stats'
3198  * as 'subfacet''s statistics. */
3199 static void
3200 update_subfacet_stats(struct subfacet *subfacet,
3201                       const struct dpif_flow_stats *stats)
3202 {
3203     struct facet *facet = subfacet->facet;
3204
3205     if (stats->n_packets >= subfacet->dp_packet_count) {
3206         uint64_t extra = stats->n_packets - subfacet->dp_packet_count;
3207         facet->packet_count += extra;
3208     } else {
3209         VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
3210     }
3211
3212     if (stats->n_bytes >= subfacet->dp_byte_count) {
3213         facet->byte_count += stats->n_bytes - subfacet->dp_byte_count;
3214     } else {
3215         VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
3216     }
3217
3218     subfacet->dp_packet_count = stats->n_packets;
3219     subfacet->dp_byte_count = stats->n_bytes;
3220
3221     facet->tcp_flags |= stats->tcp_flags;
3222
3223     subfacet_update_time(subfacet, stats->used);
3224     if (facet->accounted_bytes < facet->byte_count) {
3225         facet_learn(facet);
3226         facet_account(facet);
3227         facet->accounted_bytes = facet->byte_count;
3228     }
3229     facet_push_stats(facet);
3230 }
3231
3232 /* 'key' with length 'key_len' bytes is a flow in 'dpif' that we know nothing
3233  * about, or a flow that shouldn't be installed but was anyway.  Delete it. */
3234 static void
3235 delete_unexpected_flow(struct dpif *dpif,
3236                        const struct nlattr *key, size_t key_len)
3237 {
3238     if (!VLOG_DROP_WARN(&rl)) {
3239         struct ds s;
3240
3241         ds_init(&s);
3242         odp_flow_key_format(key, key_len, &s);
3243         VLOG_WARN("unexpected flow from datapath %s", ds_cstr(&s));
3244         ds_destroy(&s);
3245     }
3246
3247     COVERAGE_INC(facet_unexpected);
3248     dpif_flow_del(dpif, key, key_len, NULL);
3249 }
3250
3251 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
3252  *
3253  * This function also pushes statistics updates to rules which each facet
3254  * resubmits into.  Generally these statistics will be accurate.  However, if a
3255  * facet changes the rule it resubmits into at some time in between
3256  * update_stats() runs, it is possible that statistics accrued to the
3257  * old rule will be incorrectly attributed to the new rule.  This could be
3258  * avoided by calling update_stats() whenever rules are created or
3259  * deleted.  However, the performance impact of making so many calls to the
3260  * datapath do not justify the benefit of having perfectly accurate statistics.
3261  */
3262 static void
3263 update_stats(struct ofproto_dpif *p)
3264 {
3265     const struct dpif_flow_stats *stats;
3266     struct dpif_flow_dump dump;
3267     const struct nlattr *key;
3268     size_t key_len;
3269
3270     dpif_flow_dump_start(&dump, p->dpif);
3271     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
3272         struct subfacet *subfacet;
3273
3274         subfacet = subfacet_find(p, key, key_len);
3275         if (subfacet && subfacet->installed) {
3276             update_subfacet_stats(subfacet, stats);
3277         } else {
3278             delete_unexpected_flow(p->dpif, key, key_len);
3279         }
3280     }
3281     dpif_flow_dump_done(&dump);
3282 }
3283
3284 /* Calculates and returns the number of milliseconds of idle time after which
3285  * subfacets should expire from the datapath.  When a subfacet expires, we fold
3286  * its statistics into its facet, and when a facet's last subfacet expires, we
3287  * fold its statistic into its rule. */
3288 static int
3289 subfacet_max_idle(const struct ofproto_dpif *ofproto)
3290 {
3291     /*
3292      * Idle time histogram.
3293      *
3294      * Most of the time a switch has a relatively small number of subfacets.
3295      * When this is the case we might as well keep statistics for all of them
3296      * in userspace and to cache them in the kernel datapath for performance as
3297      * well.
3298      *
3299      * As the number of subfacets increases, the memory required to maintain
3300      * statistics about them in userspace and in the kernel becomes
3301      * significant.  However, with a large number of subfacets it is likely
3302      * that only a few of them are "heavy hitters" that consume a large amount
3303      * of bandwidth.  At this point, only heavy hitters are worth caching in
3304      * the kernel and maintaining in userspaces; other subfacets we can
3305      * discard.
3306      *
3307      * The technique used to compute the idle time is to build a histogram with
3308      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
3309      * that is installed in the kernel gets dropped in the appropriate bucket.
3310      * After the histogram has been built, we compute the cutoff so that only
3311      * the most-recently-used 1% of subfacets (but at least
3312      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
3313      * the most-recently-used bucket of subfacets is kept, so actually an
3314      * arbitrary number of subfacets can be kept in any given expiration run
3315      * (though the next run will delete most of those unless they receive
3316      * additional data).
3317      *
3318      * This requires a second pass through the subfacets, in addition to the
3319      * pass made by update_stats(), because the former function never looks at
3320      * uninstallable subfacets.
3321      */
3322     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
3323     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
3324     int buckets[N_BUCKETS] = { 0 };
3325     int total, subtotal, bucket;
3326     struct subfacet *subfacet;
3327     long long int now;
3328     int i;
3329
3330     total = hmap_count(&ofproto->subfacets);
3331     if (total <= ofproto->up.flow_eviction_threshold) {
3332         return N_BUCKETS * BUCKET_WIDTH;
3333     }
3334
3335     /* Build histogram. */
3336     now = time_msec();
3337     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
3338         long long int idle = now - subfacet->used;
3339         int bucket = (idle <= 0 ? 0
3340                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
3341                       : (unsigned int) idle / BUCKET_WIDTH);
3342         buckets[bucket]++;
3343     }
3344
3345     /* Find the first bucket whose flows should be expired. */
3346     subtotal = bucket = 0;
3347     do {
3348         subtotal += buckets[bucket++];
3349     } while (bucket < N_BUCKETS &&
3350              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
3351
3352     if (VLOG_IS_DBG_ENABLED()) {
3353         struct ds s;
3354
3355         ds_init(&s);
3356         ds_put_cstr(&s, "keep");
3357         for (i = 0; i < N_BUCKETS; i++) {
3358             if (i == bucket) {
3359                 ds_put_cstr(&s, ", drop");
3360             }
3361             if (buckets[i]) {
3362                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
3363             }
3364         }
3365         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
3366         ds_destroy(&s);
3367     }
3368
3369     return bucket * BUCKET_WIDTH;
3370 }
3371
3372 enum { EXPIRE_MAX_BATCH = 50 };
3373
3374 static void
3375 expire_batch(struct ofproto_dpif *ofproto, struct subfacet **subfacets, int n)
3376 {
3377     struct odputil_keybuf keybufs[EXPIRE_MAX_BATCH];
3378     struct dpif_op ops[EXPIRE_MAX_BATCH];
3379     struct dpif_op *opsp[EXPIRE_MAX_BATCH];
3380     struct ofpbuf keys[EXPIRE_MAX_BATCH];
3381     struct dpif_flow_stats stats[EXPIRE_MAX_BATCH];
3382     int i;
3383
3384     for (i = 0; i < n; i++) {
3385         ops[i].type = DPIF_OP_FLOW_DEL;
3386         subfacet_get_key(subfacets[i], &keybufs[i], &keys[i]);
3387         ops[i].u.flow_del.key = keys[i].data;
3388         ops[i].u.flow_del.key_len = keys[i].size;
3389         ops[i].u.flow_del.stats = &stats[i];
3390         opsp[i] = &ops[i];
3391     }
3392
3393     dpif_operate(ofproto->dpif, opsp, n);
3394     for (i = 0; i < n; i++) {
3395         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
3396         subfacets[i]->installed = false;
3397         subfacet_destroy(subfacets[i]);
3398     }
3399 }
3400
3401 static void
3402 expire_subfacets(struct ofproto_dpif *ofproto, int dp_max_idle)
3403 {
3404     long long int cutoff = time_msec() - dp_max_idle;
3405
3406     struct subfacet *subfacet, *next_subfacet;
3407     struct subfacet *batch[EXPIRE_MAX_BATCH];
3408     int n_batch;
3409
3410     n_batch = 0;
3411     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
3412                         &ofproto->subfacets) {
3413         if (subfacet->used < cutoff) {
3414             if (subfacet->installed) {
3415                 batch[n_batch++] = subfacet;
3416                 if (n_batch >= EXPIRE_MAX_BATCH) {
3417                     expire_batch(ofproto, batch, n_batch);
3418                     n_batch = 0;
3419                 }
3420             } else {
3421                 subfacet_destroy(subfacet);
3422             }
3423         }
3424     }
3425
3426     if (n_batch > 0) {
3427         expire_batch(ofproto, batch, n_batch);
3428     }
3429 }
3430
3431 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
3432  * then delete it entirely. */
3433 static void
3434 rule_expire(struct rule_dpif *rule)
3435 {
3436     struct facet *facet, *next_facet;
3437     long long int now;
3438     uint8_t reason;
3439
3440     /* Has 'rule' expired? */
3441     now = time_msec();
3442     if (rule->up.hard_timeout
3443         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
3444         reason = OFPRR_HARD_TIMEOUT;
3445     } else if (rule->up.idle_timeout
3446                && now > rule->up.used + rule->up.idle_timeout * 1000) {
3447         reason = OFPRR_IDLE_TIMEOUT;
3448     } else {
3449         return;
3450     }
3451
3452     COVERAGE_INC(ofproto_dpif_expired);
3453
3454     /* Update stats.  (This is a no-op if the rule expired due to an idle
3455      * timeout, because that only happens when the rule has no facets left.) */
3456     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3457         facet_remove(facet);
3458     }
3459
3460     /* Get rid of the rule. */
3461     ofproto_rule_expire(&rule->up, reason);
3462 }
3463 \f
3464 /* Facets. */
3465
3466 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
3467  *
3468  * The caller must already have determined that no facet with an identical
3469  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
3470  * the ofproto's classifier table.
3471  *
3472  * 'hash' must be the return value of flow_hash(flow, 0).
3473  *
3474  * The facet will initially have no subfacets.  The caller should create (at
3475  * least) one subfacet with subfacet_create(). */
3476 static struct facet *
3477 facet_create(struct rule_dpif *rule, const struct flow *flow, uint32_t hash)
3478 {
3479     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3480     struct facet *facet;
3481
3482     facet = xzalloc(sizeof *facet);
3483     facet->used = time_msec();
3484     hmap_insert(&ofproto->facets, &facet->hmap_node, hash);
3485     list_push_back(&rule->facets, &facet->list_node);
3486     facet->rule = rule;
3487     facet->flow = *flow;
3488     list_init(&facet->subfacets);
3489     netflow_flow_init(&facet->nf_flow);
3490     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
3491
3492     return facet;
3493 }
3494
3495 static void
3496 facet_free(struct facet *facet)
3497 {
3498     free(facet);
3499 }
3500
3501 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
3502  * 'packet', which arrived on 'in_port'.
3503  *
3504  * Takes ownership of 'packet'. */
3505 static bool
3506 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
3507                     const struct nlattr *odp_actions, size_t actions_len,
3508                     struct ofpbuf *packet)
3509 {
3510     struct odputil_keybuf keybuf;
3511     struct ofpbuf key;
3512     int error;
3513
3514     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3515     odp_flow_key_from_flow(&key, flow);
3516
3517     error = dpif_execute(ofproto->dpif, key.data, key.size,
3518                          odp_actions, actions_len, packet);
3519
3520     ofpbuf_delete(packet);
3521     return !error;
3522 }
3523
3524 /* Remove 'facet' from 'ofproto' and free up the associated memory:
3525  *
3526  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
3527  *     rule's statistics, via subfacet_uninstall().
3528  *
3529  *   - Removes 'facet' from its rule and from ofproto->facets.
3530  */
3531 static void
3532 facet_remove(struct facet *facet)
3533 {
3534     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3535     struct subfacet *subfacet, *next_subfacet;
3536
3537     assert(!list_is_empty(&facet->subfacets));
3538
3539     /* First uninstall all of the subfacets to get final statistics. */
3540     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3541         subfacet_uninstall(subfacet);
3542     }
3543
3544     /* Flush the final stats to the rule.
3545      *
3546      * This might require us to have at least one subfacet around so that we
3547      * can use its actions for accounting in facet_account(), which is why we
3548      * have uninstalled but not yet destroyed the subfacets. */
3549     facet_flush_stats(facet);
3550
3551     /* Now we're really all done so destroy everything. */
3552     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
3553                         &facet->subfacets) {
3554         subfacet_destroy__(subfacet);
3555     }
3556     hmap_remove(&ofproto->facets, &facet->hmap_node);
3557     list_remove(&facet->list_node);
3558     facet_free(facet);
3559 }
3560
3561 /* Feed information from 'facet' back into the learning table to keep it in
3562  * sync with what is actually flowing through the datapath. */
3563 static void
3564 facet_learn(struct facet *facet)
3565 {
3566     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3567     struct action_xlate_ctx ctx;
3568
3569     if (!facet->has_learn
3570         && !facet->has_normal
3571         && (!facet->has_fin_timeout
3572             || !(facet->tcp_flags & (TCP_FIN | TCP_RST)))) {
3573         return;
3574     }
3575
3576     action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3577                           facet->flow.vlan_tci,
3578                           facet->rule, facet->tcp_flags, NULL);
3579     ctx.may_learn = true;
3580     xlate_actions_for_side_effects(&ctx, facet->rule->up.actions,
3581                                    facet->rule->up.n_actions);
3582 }
3583
3584 static void
3585 facet_account(struct facet *facet)
3586 {
3587     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3588     struct subfacet *subfacet;
3589     const struct nlattr *a;
3590     unsigned int left;
3591     ovs_be16 vlan_tci;
3592     uint64_t n_bytes;
3593
3594     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
3595         return;
3596     }
3597     n_bytes = facet->byte_count - facet->accounted_bytes;
3598
3599     /* This loop feeds byte counters to bond_account() for rebalancing to use
3600      * as a basis.  We also need to track the actual VLAN on which the packet
3601      * is going to be sent to ensure that it matches the one passed to
3602      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
3603      * hash bucket.)
3604      *
3605      * We use the actions from an arbitrary subfacet because they should all
3606      * be equally valid for our purpose. */
3607     subfacet = CONTAINER_OF(list_front(&facet->subfacets),
3608                             struct subfacet, list_node);
3609     vlan_tci = facet->flow.vlan_tci;
3610     NL_ATTR_FOR_EACH_UNSAFE (a, left,
3611                              subfacet->actions, subfacet->actions_len) {
3612         const struct ovs_action_push_vlan *vlan;
3613         struct ofport_dpif *port;
3614
3615         switch (nl_attr_type(a)) {
3616         case OVS_ACTION_ATTR_OUTPUT:
3617             port = get_odp_port(ofproto, nl_attr_get_u32(a));
3618             if (port && port->bundle && port->bundle->bond) {
3619                 bond_account(port->bundle->bond, &facet->flow,
3620                              vlan_tci_to_vid(vlan_tci), n_bytes);
3621             }
3622             break;
3623
3624         case OVS_ACTION_ATTR_POP_VLAN:
3625             vlan_tci = htons(0);
3626             break;
3627
3628         case OVS_ACTION_ATTR_PUSH_VLAN:
3629             vlan = nl_attr_get(a);
3630             vlan_tci = vlan->vlan_tci;
3631             break;
3632         }
3633     }
3634 }
3635
3636 /* Returns true if the only action for 'facet' is to send to the controller.
3637  * (We don't report NetFlow expiration messages for such facets because they
3638  * are just part of the control logic for the network, not real traffic). */
3639 static bool
3640 facet_is_controller_flow(struct facet *facet)
3641 {
3642     return (facet
3643             && facet->rule->up.n_actions == 1
3644             && action_outputs_to_port(&facet->rule->up.actions[0],
3645                                       htons(OFPP_CONTROLLER)));
3646 }
3647
3648 /* Folds all of 'facet''s statistics into its rule.  Also updates the
3649  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
3650  * 'facet''s statistics in the datapath should have been zeroed and folded into
3651  * its packet and byte counts before this function is called. */
3652 static void
3653 facet_flush_stats(struct facet *facet)
3654 {
3655     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3656     struct subfacet *subfacet;
3657
3658     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3659         assert(!subfacet->dp_byte_count);
3660         assert(!subfacet->dp_packet_count);
3661     }
3662
3663     facet_push_stats(facet);
3664     if (facet->accounted_bytes < facet->byte_count) {
3665         facet_account(facet);
3666         facet->accounted_bytes = facet->byte_count;
3667     }
3668
3669     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
3670         struct ofexpired expired;
3671         expired.flow = facet->flow;
3672         expired.packet_count = facet->packet_count;
3673         expired.byte_count = facet->byte_count;
3674         expired.used = facet->used;
3675         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
3676     }
3677
3678     facet->rule->packet_count += facet->packet_count;
3679     facet->rule->byte_count += facet->byte_count;
3680
3681     /* Reset counters to prevent double counting if 'facet' ever gets
3682      * reinstalled. */
3683     facet_reset_counters(facet);
3684
3685     netflow_flow_clear(&facet->nf_flow);
3686     facet->tcp_flags = 0;
3687 }
3688
3689 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3690  * Returns it if found, otherwise a null pointer.
3691  *
3692  * 'hash' must be the return value of flow_hash(flow, 0).
3693  *
3694  * The returned facet might need revalidation; use facet_lookup_valid()
3695  * instead if that is important. */
3696 static struct facet *
3697 facet_find(struct ofproto_dpif *ofproto,
3698            const struct flow *flow, uint32_t hash)
3699 {
3700     struct facet *facet;
3701
3702     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, hash, &ofproto->facets) {
3703         if (flow_equal(flow, &facet->flow)) {
3704             return facet;
3705         }
3706     }
3707
3708     return NULL;
3709 }
3710
3711 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3712  * Returns it if found, otherwise a null pointer.
3713  *
3714  * 'hash' must be the return value of flow_hash(flow, 0).
3715  *
3716  * The returned facet is guaranteed to be valid. */
3717 static struct facet *
3718 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow,
3719                    uint32_t hash)
3720 {
3721     struct facet *facet;
3722
3723     facet = facet_find(ofproto, flow, hash);
3724     if (facet
3725         && (ofproto->need_revalidate
3726             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))) {
3727         facet_revalidate(facet);
3728     }
3729
3730     return facet;
3731 }
3732
3733 static bool
3734 facet_check_consistency(struct facet *facet)
3735 {
3736     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
3737
3738     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3739
3740     uint64_t odp_actions_stub[1024 / 8];
3741     struct ofpbuf odp_actions;
3742
3743     struct rule_dpif *rule;
3744     struct subfacet *subfacet;
3745     bool may_log = false;
3746     bool ok;
3747
3748     /* Check the rule for consistency. */
3749     rule = rule_dpif_lookup(ofproto, &facet->flow);
3750     ok = rule == facet->rule;
3751     if (!ok) {
3752         may_log = !VLOG_DROP_WARN(&rl);
3753         if (may_log) {
3754             struct ds s;
3755
3756             ds_init(&s);
3757             flow_format(&s, &facet->flow);
3758             ds_put_format(&s, ": facet associated with wrong rule (was "
3759                           "table=%"PRIu8",", facet->rule->up.table_id);
3760             cls_rule_format(&facet->rule->up.cr, &s);
3761             ds_put_format(&s, ") (should have been table=%"PRIu8",",
3762                           rule->up.table_id);
3763             cls_rule_format(&rule->up.cr, &s);
3764             ds_put_char(&s, ')');
3765
3766             VLOG_WARN("%s", ds_cstr(&s));
3767             ds_destroy(&s);
3768         }
3769     }
3770
3771     /* Check the datapath actions for consistency. */
3772     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
3773     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3774         struct odputil_keybuf keybuf;
3775         struct action_xlate_ctx ctx;
3776         bool actions_changed;
3777         bool should_install;
3778         struct ofpbuf key;
3779         struct ds s;
3780
3781         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3782                               subfacet->initial_tci, rule, 0, NULL);
3783         xlate_actions(&ctx, rule->up.actions, rule->up.n_actions,
3784                       &odp_actions);
3785
3786         should_install = (ctx.may_set_up_flow
3787                           && subfacet->key_fitness != ODP_FIT_TOO_LITTLE);
3788         if (!should_install && !subfacet->installed) {
3789             /* The actions for uninstallable flows may vary from one packet to
3790              * the next, so don't compare the actions. */
3791             continue;
3792         }
3793
3794         actions_changed = (subfacet->actions_len != odp_actions.size
3795                            || memcmp(subfacet->actions, odp_actions.data,
3796                                      subfacet->actions_len));
3797         if (should_install == subfacet->installed && !actions_changed) {
3798             continue;
3799         }
3800
3801         /* Inconsistency! */
3802         if (ok) {
3803             may_log = !VLOG_DROP_WARN(&rl);
3804             ok = false;
3805         }
3806         if (!may_log) {
3807             /* Rate-limited, skip reporting. */
3808             continue;
3809         }
3810
3811         ds_init(&s);
3812         subfacet_get_key(subfacet, &keybuf, &key);
3813         odp_flow_key_format(key.data, key.size, &s);
3814
3815         ds_put_cstr(&s, ": inconsistency in subfacet");
3816         if (should_install != subfacet->installed) {
3817             enum odp_key_fitness fitness = subfacet->key_fitness;
3818
3819             ds_put_format(&s, " (should%s have been installed)",
3820                           should_install ? "" : " not");
3821             ds_put_format(&s, " (may_set_up_flow=%s, fitness=%s)",
3822                           ctx.may_set_up_flow ? "true" : "false",
3823                           odp_key_fitness_to_string(fitness));
3824         }
3825         if (actions_changed) {
3826             ds_put_cstr(&s, " (actions were: ");
3827             format_odp_actions(&s, subfacet->actions,
3828                                subfacet->actions_len);
3829             ds_put_cstr(&s, ") (correct actions: ");
3830             format_odp_actions(&s, odp_actions.data, odp_actions.size);
3831             ds_put_char(&s, ')');
3832         } else {
3833             ds_put_cstr(&s, " (actions: ");
3834             format_odp_actions(&s, subfacet->actions,
3835                                subfacet->actions_len);
3836             ds_put_char(&s, ')');
3837         }
3838         VLOG_WARN("%s", ds_cstr(&s));
3839         ds_destroy(&s);
3840     }
3841     ofpbuf_uninit(&odp_actions);
3842
3843     return ok;
3844 }
3845
3846 /* Re-searches the classifier for 'facet':
3847  *
3848  *   - If the rule found is different from 'facet''s current rule, moves
3849  *     'facet' to the new rule and recompiles its actions.
3850  *
3851  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
3852  *     where it is and recompiles its actions anyway. */
3853 static void
3854 facet_revalidate(struct facet *facet)
3855 {
3856     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3857     struct actions {
3858         struct nlattr *odp_actions;
3859         size_t actions_len;
3860     };
3861     struct actions *new_actions;
3862
3863     struct action_xlate_ctx ctx;
3864     uint64_t odp_actions_stub[1024 / 8];
3865     struct ofpbuf odp_actions;
3866
3867     struct rule_dpif *new_rule;
3868     struct subfacet *subfacet;
3869     bool actions_changed;
3870     int i;
3871
3872     COVERAGE_INC(facet_revalidate);
3873
3874     new_rule = rule_dpif_lookup(ofproto, &facet->flow);
3875
3876     /* Calculate new datapath actions.
3877      *
3878      * We do not modify any 'facet' state yet, because we might need to, e.g.,
3879      * emit a NetFlow expiration and, if so, we need to have the old state
3880      * around to properly compose it. */
3881
3882     /* If the datapath actions changed or the installability changed,
3883      * then we need to talk to the datapath. */
3884     i = 0;
3885     new_actions = NULL;
3886     memset(&ctx, 0, sizeof ctx);
3887     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
3888     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3889         bool should_install;
3890
3891         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3892                               subfacet->initial_tci, new_rule, 0, NULL);
3893         xlate_actions(&ctx, new_rule->up.actions, new_rule->up.n_actions,
3894                       &odp_actions);
3895         actions_changed = (subfacet->actions_len != odp_actions.size
3896                            || memcmp(subfacet->actions, odp_actions.data,
3897                                      subfacet->actions_len));
3898
3899         should_install = (ctx.may_set_up_flow
3900                           && subfacet->key_fitness != ODP_FIT_TOO_LITTLE);
3901         if (actions_changed || should_install != subfacet->installed) {
3902             if (should_install) {
3903                 struct dpif_flow_stats stats;
3904
3905                 subfacet_install(subfacet,
3906                                  odp_actions.data, odp_actions.size, &stats);
3907                 subfacet_update_stats(subfacet, &stats);
3908             } else {
3909                 subfacet_uninstall(subfacet);
3910             }
3911
3912             if (!new_actions) {
3913                 new_actions = xcalloc(list_size(&facet->subfacets),
3914                                       sizeof *new_actions);
3915             }
3916             new_actions[i].odp_actions = xmemdup(odp_actions.data,
3917                                                  odp_actions.size);
3918             new_actions[i].actions_len = odp_actions.size;
3919         }
3920
3921         i++;
3922     }
3923     ofpbuf_uninit(&odp_actions);
3924
3925     if (new_actions) {
3926         facet_flush_stats(facet);
3927     }
3928
3929     /* Update 'facet' now that we've taken care of all the old state. */
3930     facet->tags = ctx.tags;
3931     facet->nf_flow.output_iface = ctx.nf_output_iface;
3932     facet->may_install = ctx.may_set_up_flow;
3933     facet->has_learn = ctx.has_learn;
3934     facet->has_normal = ctx.has_normal;
3935     facet->has_fin_timeout = ctx.has_fin_timeout;
3936     facet->mirrors = ctx.mirrors;
3937     if (new_actions) {
3938         i = 0;
3939         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3940             if (new_actions[i].odp_actions) {
3941                 free(subfacet->actions);
3942                 subfacet->actions = new_actions[i].odp_actions;
3943                 subfacet->actions_len = new_actions[i].actions_len;
3944             }
3945             i++;
3946         }
3947         free(new_actions);
3948     }
3949     if (facet->rule != new_rule) {
3950         COVERAGE_INC(facet_changed_rule);
3951         list_remove(&facet->list_node);
3952         list_push_back(&new_rule->facets, &facet->list_node);
3953         facet->rule = new_rule;
3954         facet->used = new_rule->up.created;
3955         facet->prev_used = facet->used;
3956     }
3957 }
3958
3959 /* Updates 'facet''s used time.  Caller is responsible for calling
3960  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3961 static void
3962 facet_update_time(struct facet *facet, long long int used)
3963 {
3964     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3965     if (used > facet->used) {
3966         facet->used = used;
3967         ofproto_rule_update_used(&facet->rule->up, used);
3968         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3969     }
3970 }
3971
3972 static void
3973 facet_reset_counters(struct facet *facet)
3974 {
3975     facet->packet_count = 0;
3976     facet->byte_count = 0;
3977     facet->prev_packet_count = 0;
3978     facet->prev_byte_count = 0;
3979     facet->accounted_bytes = 0;
3980 }
3981
3982 static void
3983 facet_push_stats(struct facet *facet)
3984 {
3985     struct dpif_flow_stats stats;
3986
3987     assert(facet->packet_count >= facet->prev_packet_count);
3988     assert(facet->byte_count >= facet->prev_byte_count);
3989     assert(facet->used >= facet->prev_used);
3990
3991     stats.n_packets = facet->packet_count - facet->prev_packet_count;
3992     stats.n_bytes = facet->byte_count - facet->prev_byte_count;
3993     stats.used = facet->used;
3994     stats.tcp_flags = 0;
3995
3996     if (stats.n_packets || stats.n_bytes || facet->used > facet->prev_used) {
3997         facet->prev_packet_count = facet->packet_count;
3998         facet->prev_byte_count = facet->byte_count;
3999         facet->prev_used = facet->used;
4000
4001         flow_push_stats(facet->rule, &facet->flow, &stats);
4002
4003         update_mirror_stats(ofproto_dpif_cast(facet->rule->up.ofproto),
4004                             facet->mirrors, stats.n_packets, stats.n_bytes);
4005     }
4006 }
4007
4008 static void
4009 rule_credit_stats(struct rule_dpif *rule, const struct dpif_flow_stats *stats)
4010 {
4011     rule->packet_count += stats->n_packets;
4012     rule->byte_count += stats->n_bytes;
4013     ofproto_rule_update_used(&rule->up, stats->used);
4014 }
4015
4016 /* Pushes flow statistics to the rules which 'flow' resubmits into given
4017  * 'rule''s actions and mirrors. */
4018 static void
4019 flow_push_stats(struct rule_dpif *rule,
4020                 const struct flow *flow, const struct dpif_flow_stats *stats)
4021 {
4022     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4023     struct action_xlate_ctx ctx;
4024
4025     ofproto_rule_update_used(&rule->up, stats->used);
4026
4027     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, rule,
4028                           0, NULL);
4029     ctx.resubmit_stats = stats;
4030     xlate_actions_for_side_effects(&ctx, rule->up.actions, rule->up.n_actions);
4031 }
4032 \f
4033 /* Subfacets. */
4034
4035 static struct subfacet *
4036 subfacet_find__(struct ofproto_dpif *ofproto,
4037                 const struct nlattr *key, size_t key_len, uint32_t key_hash,
4038                 const struct flow *flow)
4039 {
4040     struct subfacet *subfacet;
4041
4042     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
4043                              &ofproto->subfacets) {
4044         if (subfacet->key
4045             ? (subfacet->key_len == key_len
4046                && !memcmp(key, subfacet->key, key_len))
4047             : flow_equal(flow, &subfacet->facet->flow)) {
4048             return subfacet;
4049         }
4050     }
4051
4052     return NULL;
4053 }
4054
4055 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
4056  * 'key_fitness', 'key', and 'key_len'.  Returns the existing subfacet if
4057  * there is one, otherwise creates and returns a new subfacet.
4058  *
4059  * If the returned subfacet is new, then subfacet->actions will be NULL, in
4060  * which case the caller must populate the actions with
4061  * subfacet_make_actions(). */
4062 static struct subfacet *
4063 subfacet_create(struct facet *facet, enum odp_key_fitness key_fitness,
4064                 const struct nlattr *key, size_t key_len, ovs_be16 initial_tci)
4065 {
4066     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4067     uint32_t key_hash = odp_flow_key_hash(key, key_len);
4068     struct subfacet *subfacet;
4069
4070     subfacet = subfacet_find__(ofproto, key, key_len, key_hash, &facet->flow);
4071     if (subfacet) {
4072         if (subfacet->facet == facet) {
4073             return subfacet;
4074         }
4075
4076         /* This shouldn't happen. */
4077         VLOG_ERR_RL(&rl, "subfacet with wrong facet");
4078         subfacet_destroy(subfacet);
4079     }
4080
4081     subfacet = (list_is_empty(&facet->subfacets)
4082                 ? &facet->one_subfacet
4083                 : xmalloc(sizeof *subfacet));
4084     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
4085     list_push_back(&facet->subfacets, &subfacet->list_node);
4086     subfacet->facet = facet;
4087     subfacet->key_fitness = key_fitness;
4088     if (key_fitness != ODP_FIT_PERFECT) {
4089         subfacet->key = xmemdup(key, key_len);
4090         subfacet->key_len = key_len;
4091     } else {
4092         subfacet->key = NULL;
4093         subfacet->key_len = 0;
4094     }
4095     subfacet->used = time_msec();
4096     subfacet->dp_packet_count = 0;
4097     subfacet->dp_byte_count = 0;
4098     subfacet->actions_len = 0;
4099     subfacet->actions = NULL;
4100     subfacet->installed = false;
4101     subfacet->initial_tci = initial_tci;
4102
4103     return subfacet;
4104 }
4105
4106 /* Searches 'ofproto' for a subfacet with the given 'key', 'key_len', and
4107  * 'flow'.  Returns the subfacet if one exists, otherwise NULL. */
4108 static struct subfacet *
4109 subfacet_find(struct ofproto_dpif *ofproto,
4110               const struct nlattr *key, size_t key_len)
4111 {
4112     uint32_t key_hash = odp_flow_key_hash(key, key_len);
4113     enum odp_key_fitness fitness;
4114     struct flow flow;
4115
4116     fitness = odp_flow_key_to_flow(key, key_len, &flow);
4117     if (fitness == ODP_FIT_ERROR) {
4118         return NULL;
4119     }
4120
4121     return subfacet_find__(ofproto, key, key_len, key_hash, &flow);
4122 }
4123
4124 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
4125  * its facet within 'ofproto', and frees it. */
4126 static void
4127 subfacet_destroy__(struct subfacet *subfacet)
4128 {
4129     struct facet *facet = subfacet->facet;
4130     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4131
4132     subfacet_uninstall(subfacet);
4133     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
4134     list_remove(&subfacet->list_node);
4135     free(subfacet->key);
4136     free(subfacet->actions);
4137     if (subfacet != &facet->one_subfacet) {
4138         free(subfacet);
4139     }
4140 }
4141
4142 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
4143  * last remaining subfacet in its facet destroys the facet too. */
4144 static void
4145 subfacet_destroy(struct subfacet *subfacet)
4146 {
4147     struct facet *facet = subfacet->facet;
4148
4149     if (list_is_singleton(&facet->subfacets)) {
4150         /* facet_remove() needs at least one subfacet (it will remove it). */
4151         facet_remove(facet);
4152     } else {
4153         subfacet_destroy__(subfacet);
4154     }
4155 }
4156
4157 /* Initializes 'key' with the sequence of OVS_KEY_ATTR_* Netlink attributes
4158  * that can be used to refer to 'subfacet'.  The caller must provide 'keybuf'
4159  * for use as temporary storage. */
4160 static void
4161 subfacet_get_key(struct subfacet *subfacet, struct odputil_keybuf *keybuf,
4162                  struct ofpbuf *key)
4163 {
4164     if (!subfacet->key) {
4165         ofpbuf_use_stack(key, keybuf, sizeof *keybuf);
4166         odp_flow_key_from_flow(key, &subfacet->facet->flow);
4167     } else {
4168         ofpbuf_use_const(key, subfacet->key, subfacet->key_len);
4169     }
4170 }
4171
4172 /* Composes the datapath actions for 'subfacet' based on its rule's actions.
4173  * Translates the actions into 'odp_actions', which the caller must have
4174  * initialized and is responsible for uninitializing. */
4175 static void
4176 subfacet_make_actions(struct subfacet *subfacet, const struct ofpbuf *packet,
4177                       struct ofpbuf *odp_actions)
4178 {
4179     struct facet *facet = subfacet->facet;
4180     struct rule_dpif *rule = facet->rule;
4181     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4182
4183     struct action_xlate_ctx ctx;
4184
4185     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, subfacet->initial_tci,
4186                           rule, 0, packet);
4187     xlate_actions(&ctx, rule->up.actions, rule->up.n_actions, odp_actions);
4188     facet->tags = ctx.tags;
4189     facet->may_install = ctx.may_set_up_flow;
4190     facet->has_learn = ctx.has_learn;
4191     facet->has_normal = ctx.has_normal;
4192     facet->has_fin_timeout = ctx.has_fin_timeout;
4193     facet->nf_flow.output_iface = ctx.nf_output_iface;
4194     facet->mirrors = ctx.mirrors;
4195
4196     if (subfacet->actions_len != odp_actions->size
4197         || memcmp(subfacet->actions, odp_actions->data, odp_actions->size)) {
4198         free(subfacet->actions);
4199         subfacet->actions_len = odp_actions->size;
4200         subfacet->actions = xmemdup(odp_actions->data, odp_actions->size);
4201     }
4202 }
4203
4204 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
4205  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
4206  * in the datapath will be zeroed and 'stats' will be updated with traffic new
4207  * since 'subfacet' was last updated.
4208  *
4209  * Returns 0 if successful, otherwise a positive errno value. */
4210 static int
4211 subfacet_install(struct subfacet *subfacet,
4212                  const struct nlattr *actions, size_t actions_len,
4213                  struct dpif_flow_stats *stats)
4214 {
4215     struct facet *facet = subfacet->facet;
4216     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4217     struct odputil_keybuf keybuf;
4218     enum dpif_flow_put_flags flags;
4219     struct ofpbuf key;
4220     int ret;
4221
4222     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
4223     if (stats) {
4224         flags |= DPIF_FP_ZERO_STATS;
4225     }
4226
4227     subfacet_get_key(subfacet, &keybuf, &key);
4228     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
4229                         actions, actions_len, stats);
4230
4231     if (stats) {
4232         subfacet_reset_dp_stats(subfacet, stats);
4233     }
4234
4235     return ret;
4236 }
4237
4238 /* If 'subfacet' is installed in the datapath, uninstalls it. */
4239 static void
4240 subfacet_uninstall(struct subfacet *subfacet)
4241 {
4242     if (subfacet->installed) {
4243         struct rule_dpif *rule = subfacet->facet->rule;
4244         struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4245         struct odputil_keybuf keybuf;
4246         struct dpif_flow_stats stats;
4247         struct ofpbuf key;
4248         int error;
4249
4250         subfacet_get_key(subfacet, &keybuf, &key);
4251         error = dpif_flow_del(ofproto->dpif, key.data, key.size, &stats);
4252         subfacet_reset_dp_stats(subfacet, &stats);
4253         if (!error) {
4254             subfacet_update_stats(subfacet, &stats);
4255         }
4256         subfacet->installed = false;
4257     } else {
4258         assert(subfacet->dp_packet_count == 0);
4259         assert(subfacet->dp_byte_count == 0);
4260     }
4261 }
4262
4263 /* Resets 'subfacet''s datapath statistics counters.  This should be called
4264  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
4265  * non-null, it should contain the statistics returned by dpif when 'subfacet'
4266  * was reset in the datapath.  'stats' will be modified to include only
4267  * statistics new since 'subfacet' was last updated. */
4268 static void
4269 subfacet_reset_dp_stats(struct subfacet *subfacet,
4270                         struct dpif_flow_stats *stats)
4271 {
4272     if (stats
4273         && subfacet->dp_packet_count <= stats->n_packets
4274         && subfacet->dp_byte_count <= stats->n_bytes) {
4275         stats->n_packets -= subfacet->dp_packet_count;
4276         stats->n_bytes -= subfacet->dp_byte_count;
4277     }
4278
4279     subfacet->dp_packet_count = 0;
4280     subfacet->dp_byte_count = 0;
4281 }
4282
4283 /* Updates 'subfacet''s used time.  The caller is responsible for calling
4284  * facet_push_stats() to update the flows which 'subfacet' resubmits into. */
4285 static void
4286 subfacet_update_time(struct subfacet *subfacet, long long int used)
4287 {
4288     if (used > subfacet->used) {
4289         subfacet->used = used;
4290         facet_update_time(subfacet->facet, used);
4291     }
4292 }
4293
4294 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
4295  *
4296  * Because of the meaning of a subfacet's counters, it only makes sense to do
4297  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
4298  * represents a packet that was sent by hand or if it represents statistics
4299  * that have been cleared out of the datapath. */
4300 static void
4301 subfacet_update_stats(struct subfacet *subfacet,
4302                       const struct dpif_flow_stats *stats)
4303 {
4304     if (stats->n_packets || stats->used > subfacet->used) {
4305         struct facet *facet = subfacet->facet;
4306
4307         subfacet_update_time(subfacet, stats->used);
4308         facet->packet_count += stats->n_packets;
4309         facet->byte_count += stats->n_bytes;
4310         facet->tcp_flags |= stats->tcp_flags;
4311         facet_push_stats(facet);
4312         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
4313     }
4314 }
4315 \f
4316 /* Rules. */
4317
4318 static struct rule_dpif *
4319 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow)
4320 {
4321     struct ofport_dpif *port;
4322     struct rule_dpif *rule;
4323
4324     rule = rule_dpif_lookup__(ofproto, flow, 0);
4325     if (rule) {
4326         return rule;
4327     }
4328
4329     port = get_ofp_port(ofproto, flow->in_port);
4330     if (!port) {
4331         VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, flow->in_port);
4332         return ofproto->miss_rule;
4333     }
4334
4335     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
4336         return ofproto->no_packet_in_rule;
4337     }
4338     return ofproto->miss_rule;
4339 }
4340
4341 static struct rule_dpif *
4342 rule_dpif_lookup__(struct ofproto_dpif *ofproto, const struct flow *flow,
4343                    uint8_t table_id)
4344 {
4345     struct cls_rule *cls_rule;
4346     struct classifier *cls;
4347
4348     if (table_id >= N_TABLES) {
4349         return NULL;
4350     }
4351
4352     cls = &ofproto->up.tables[table_id].cls;
4353     if (flow->nw_frag & FLOW_NW_FRAG_ANY
4354         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
4355         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
4356          * are unavailable. */
4357         struct flow ofpc_normal_flow = *flow;
4358         ofpc_normal_flow.tp_src = htons(0);
4359         ofpc_normal_flow.tp_dst = htons(0);
4360         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
4361     } else {
4362         cls_rule = classifier_lookup(cls, flow);
4363     }
4364     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
4365 }
4366
4367 static void
4368 complete_operation(struct rule_dpif *rule)
4369 {
4370     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4371
4372     rule_invalidate(rule);
4373     if (clogged) {
4374         struct dpif_completion *c = xmalloc(sizeof *c);
4375         c->op = rule->up.pending;
4376         list_push_back(&ofproto->completions, &c->list_node);
4377     } else {
4378         ofoperation_complete(rule->up.pending, 0);
4379     }
4380 }
4381
4382 static struct rule *
4383 rule_alloc(void)
4384 {
4385     struct rule_dpif *rule = xmalloc(sizeof *rule);
4386     return &rule->up;
4387 }
4388
4389 static void
4390 rule_dealloc(struct rule *rule_)
4391 {
4392     struct rule_dpif *rule = rule_dpif_cast(rule_);
4393     free(rule);
4394 }
4395
4396 static enum ofperr
4397 rule_construct(struct rule *rule_)
4398 {
4399     struct rule_dpif *rule = rule_dpif_cast(rule_);
4400     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4401     struct rule_dpif *victim;
4402     uint8_t table_id;
4403     enum ofperr error;
4404
4405     error = validate_actions(rule->up.actions, rule->up.n_actions,
4406                              &rule->up.cr.flow, ofproto->max_ports);
4407     if (error) {
4408         return error;
4409     }
4410
4411     rule->packet_count = 0;
4412     rule->byte_count = 0;
4413
4414     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
4415     if (victim && !list_is_empty(&victim->facets)) {
4416         struct facet *facet;
4417
4418         rule->facets = victim->facets;
4419         list_moved(&rule->facets);
4420         LIST_FOR_EACH (facet, list_node, &rule->facets) {
4421             /* XXX: We're only clearing our local counters here.  It's possible
4422              * that quite a few packets are unaccounted for in the datapath
4423              * statistics.  These will be accounted to the new rule instead of
4424              * cleared as required.  This could be fixed by clearing out the
4425              * datapath statistics for this facet, but currently it doesn't
4426              * seem worth it. */
4427             facet_reset_counters(facet);
4428             facet->rule = rule;
4429         }
4430     } else {
4431         /* Must avoid list_moved() in this case. */
4432         list_init(&rule->facets);
4433     }
4434
4435     table_id = rule->up.table_id;
4436     rule->tag = (victim ? victim->tag
4437                  : table_id == 0 ? 0
4438                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
4439                                       ofproto->tables[table_id].basis));
4440
4441     complete_operation(rule);
4442     return 0;
4443 }
4444
4445 static void
4446 rule_destruct(struct rule *rule_)
4447 {
4448     struct rule_dpif *rule = rule_dpif_cast(rule_);
4449     struct facet *facet, *next_facet;
4450
4451     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4452         facet_revalidate(facet);
4453     }
4454
4455     complete_operation(rule);
4456 }
4457
4458 static void
4459 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
4460 {
4461     struct rule_dpif *rule = rule_dpif_cast(rule_);
4462     struct facet *facet;
4463
4464     /* Start from historical data for 'rule' itself that are no longer tracked
4465      * in facets.  This counts, for example, facets that have expired. */
4466     *packets = rule->packet_count;
4467     *bytes = rule->byte_count;
4468
4469     /* Add any statistics that are tracked by facets.  This includes
4470      * statistical data recently updated by ofproto_update_stats() as well as
4471      * stats for packets that were executed "by hand" via dpif_execute(). */
4472     LIST_FOR_EACH (facet, list_node, &rule->facets) {
4473         *packets += facet->packet_count;
4474         *bytes += facet->byte_count;
4475     }
4476 }
4477
4478 static enum ofperr
4479 rule_execute(struct rule *rule_, const struct flow *flow,
4480              struct ofpbuf *packet)
4481 {
4482     struct rule_dpif *rule = rule_dpif_cast(rule_);
4483     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4484
4485     struct dpif_flow_stats stats;
4486
4487     struct action_xlate_ctx ctx;
4488     uint64_t odp_actions_stub[1024 / 8];
4489     struct ofpbuf odp_actions;
4490
4491     dpif_flow_stats_extract(flow, packet, &stats);
4492     rule_credit_stats(rule, &stats);
4493
4494     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
4495     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci,
4496                           rule, stats.tcp_flags, packet);
4497     ctx.resubmit_stats = &stats;
4498     xlate_actions(&ctx, rule->up.actions, rule->up.n_actions, &odp_actions);
4499
4500     execute_odp_actions(ofproto, flow, odp_actions.data,
4501                         odp_actions.size, packet);
4502
4503     ofpbuf_uninit(&odp_actions);
4504
4505     return 0;
4506 }
4507
4508 static void
4509 rule_modify_actions(struct rule *rule_)
4510 {
4511     struct rule_dpif *rule = rule_dpif_cast(rule_);
4512     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4513     enum ofperr error;
4514
4515     error = validate_actions(rule->up.actions, rule->up.n_actions,
4516                              &rule->up.cr.flow, ofproto->max_ports);
4517     if (error) {
4518         ofoperation_complete(rule->up.pending, error);
4519         return;
4520     }
4521
4522     complete_operation(rule);
4523 }
4524 \f
4525 /* Sends 'packet' out 'ofport'.
4526  * May modify 'packet'.
4527  * Returns 0 if successful, otherwise a positive errno value. */
4528 static int
4529 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
4530 {
4531     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
4532     struct ofpbuf key, odp_actions;
4533     struct odputil_keybuf keybuf;
4534     uint16_t odp_port;
4535     struct flow flow;
4536     int error;
4537
4538     flow_extract((struct ofpbuf *) packet, 0, 0, 0, &flow);
4539     odp_port = vsp_realdev_to_vlandev(ofproto, ofport->odp_port,
4540                                       flow.vlan_tci);
4541     if (odp_port != ofport->odp_port) {
4542         eth_pop_vlan(packet);
4543         flow.vlan_tci = htons(0);
4544     }
4545
4546     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
4547     odp_flow_key_from_flow(&key, &flow);
4548
4549     ofpbuf_init(&odp_actions, 32);
4550     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
4551
4552     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
4553     error = dpif_execute(ofproto->dpif,
4554                          key.data, key.size,
4555                          odp_actions.data, odp_actions.size,
4556                          packet);
4557     ofpbuf_uninit(&odp_actions);
4558
4559     if (error) {
4560         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
4561                      ofproto->up.name, odp_port, strerror(error));
4562     }
4563     ofproto_update_local_port_stats(ofport->up.ofproto, packet->size, 0);
4564     return error;
4565 }
4566 \f
4567 /* OpenFlow to datapath action translation. */
4568
4569 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
4570                              struct action_xlate_ctx *ctx);
4571 static void xlate_normal(struct action_xlate_ctx *);
4572
4573 static size_t
4574 put_userspace_action(const struct ofproto_dpif *ofproto,
4575                      struct ofpbuf *odp_actions,
4576                      const struct flow *flow,
4577                      const union user_action_cookie *cookie)
4578 {
4579     uint32_t pid;
4580
4581     pid = dpif_port_get_pid(ofproto->dpif,
4582                             ofp_port_to_odp_port(flow->in_port));
4583
4584     return odp_put_userspace_action(pid, cookie, odp_actions);
4585 }
4586
4587 static void
4588 compose_sflow_cookie(const struct ofproto_dpif *ofproto,
4589                      ovs_be16 vlan_tci, uint32_t odp_port,
4590                      unsigned int n_outputs, union user_action_cookie *cookie)
4591 {
4592     int ifindex;
4593
4594     cookie->type = USER_ACTION_COOKIE_SFLOW;
4595     cookie->sflow.vlan_tci = vlan_tci;
4596
4597     /* See http://www.sflow.org/sflow_version_5.txt (search for "Input/output
4598      * port information") for the interpretation of cookie->output. */
4599     switch (n_outputs) {
4600     case 0:
4601         /* 0x40000000 | 256 means "packet dropped for unknown reason". */
4602         cookie->sflow.output = 0x40000000 | 256;
4603         break;
4604
4605     case 1:
4606         ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
4607         if (ifindex) {
4608             cookie->sflow.output = ifindex;
4609             break;
4610         }
4611         /* Fall through. */
4612     default:
4613         /* 0x80000000 means "multiple output ports. */
4614         cookie->sflow.output = 0x80000000 | n_outputs;
4615         break;
4616     }
4617 }
4618
4619 /* Compose SAMPLE action for sFlow. */
4620 static size_t
4621 compose_sflow_action(const struct ofproto_dpif *ofproto,
4622                      struct ofpbuf *odp_actions,
4623                      const struct flow *flow,
4624                      uint32_t odp_port)
4625 {
4626     uint32_t probability;
4627     union user_action_cookie cookie;
4628     size_t sample_offset, actions_offset;
4629     int cookie_offset;
4630
4631     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
4632         return 0;
4633     }
4634
4635     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
4636
4637     /* Number of packets out of UINT_MAX to sample. */
4638     probability = dpif_sflow_get_probability(ofproto->sflow);
4639     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
4640
4641     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
4642     compose_sflow_cookie(ofproto, htons(0), odp_port,
4643                          odp_port == OVSP_NONE ? 0 : 1, &cookie);
4644     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
4645
4646     nl_msg_end_nested(odp_actions, actions_offset);
4647     nl_msg_end_nested(odp_actions, sample_offset);
4648     return cookie_offset;
4649 }
4650
4651 /* SAMPLE action must be first action in any given list of actions.
4652  * At this point we do not have all information required to build it. So try to
4653  * build sample action as complete as possible. */
4654 static void
4655 add_sflow_action(struct action_xlate_ctx *ctx)
4656 {
4657     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
4658                                                    ctx->odp_actions,
4659                                                    &ctx->flow, OVSP_NONE);
4660     ctx->sflow_odp_port = 0;
4661     ctx->sflow_n_outputs = 0;
4662 }
4663
4664 /* Fix SAMPLE action according to data collected while composing ODP actions.
4665  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
4666  * USERSPACE action's user-cookie which is required for sflow. */
4667 static void
4668 fix_sflow_action(struct action_xlate_ctx *ctx)
4669 {
4670     const struct flow *base = &ctx->base_flow;
4671     union user_action_cookie *cookie;
4672
4673     if (!ctx->user_cookie_offset) {
4674         return;
4675     }
4676
4677     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
4678                        sizeof(*cookie));
4679     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
4680
4681     compose_sflow_cookie(ctx->ofproto, base->vlan_tci,
4682                          ctx->sflow_odp_port, ctx->sflow_n_outputs, cookie);
4683 }
4684
4685 static void
4686 compose_output_action__(struct action_xlate_ctx *ctx, uint16_t ofp_port,
4687                         bool check_stp)
4688 {
4689     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
4690     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
4691     ovs_be16 flow_vlan_tci = ctx->flow.vlan_tci;
4692     uint8_t flow_nw_tos = ctx->flow.nw_tos;
4693     uint16_t out_port;
4694
4695     if (ofport) {
4696         struct priority_to_dscp *pdscp;
4697
4698         if (ofport->up.pp.config & OFPUTIL_PC_NO_FWD
4699             || (check_stp && !stp_forward_in_state(ofport->stp_state))) {
4700             return;
4701         }
4702
4703         pdscp = get_priority(ofport, ctx->flow.skb_priority);
4704         if (pdscp) {
4705             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
4706             ctx->flow.nw_tos |= pdscp->dscp;
4707         }
4708     } else {
4709         /* We may not have an ofport record for this port, but it doesn't hurt
4710          * to allow forwarding to it anyhow.  Maybe such a port will appear
4711          * later and we're pre-populating the flow table.  */
4712     }
4713
4714     out_port = vsp_realdev_to_vlandev(ctx->ofproto, odp_port,
4715                                       ctx->flow.vlan_tci);
4716     if (out_port != odp_port) {
4717         ctx->flow.vlan_tci = htons(0);
4718     }
4719     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
4720     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, out_port);
4721
4722     ctx->sflow_odp_port = odp_port;
4723     ctx->sflow_n_outputs++;
4724     ctx->nf_output_iface = ofp_port;
4725     ctx->flow.vlan_tci = flow_vlan_tci;
4726     ctx->flow.nw_tos = flow_nw_tos;
4727 }
4728
4729 static void
4730 compose_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
4731 {
4732     compose_output_action__(ctx, ofp_port, true);
4733 }
4734
4735 static void
4736 xlate_table_action(struct action_xlate_ctx *ctx,
4737                    uint16_t in_port, uint8_t table_id)
4738 {
4739     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
4740         struct ofproto_dpif *ofproto = ctx->ofproto;
4741         struct rule_dpif *rule;
4742         uint16_t old_in_port;
4743         uint8_t old_table_id;
4744
4745         old_table_id = ctx->table_id;
4746         ctx->table_id = table_id;
4747
4748         /* Look up a flow with 'in_port' as the input port. */
4749         old_in_port = ctx->flow.in_port;
4750         ctx->flow.in_port = in_port;
4751         rule = rule_dpif_lookup__(ofproto, &ctx->flow, table_id);
4752
4753         /* Tag the flow. */
4754         if (table_id > 0 && table_id < N_TABLES) {
4755             struct table_dpif *table = &ofproto->tables[table_id];
4756             if (table->other_table) {
4757                 ctx->tags |= (rule && rule->tag
4758                               ? rule->tag
4759                               : rule_calculate_tag(&ctx->flow,
4760                                                    &table->other_table->wc,
4761                                                    table->basis));
4762             }
4763         }
4764
4765         /* Restore the original input port.  Otherwise OFPP_NORMAL and
4766          * OFPP_IN_PORT will have surprising behavior. */
4767         ctx->flow.in_port = old_in_port;
4768
4769         if (ctx->resubmit_hook) {
4770             ctx->resubmit_hook(ctx, rule);
4771         }
4772
4773         if (rule) {
4774             struct rule_dpif *old_rule = ctx->rule;
4775
4776             if (ctx->resubmit_stats) {
4777                 rule_credit_stats(rule, ctx->resubmit_stats);
4778             }
4779
4780             ctx->recurse++;
4781             ctx->rule = rule;
4782             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
4783             ctx->rule = old_rule;
4784             ctx->recurse--;
4785         }
4786
4787         ctx->table_id = old_table_id;
4788     } else {
4789         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
4790
4791         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
4792                     MAX_RESUBMIT_RECURSION);
4793         ctx->max_resubmit_trigger = true;
4794     }
4795 }
4796
4797 static void
4798 xlate_resubmit_table(struct action_xlate_ctx *ctx,
4799                      const struct nx_action_resubmit *nar)
4800 {
4801     uint16_t in_port;
4802     uint8_t table_id;
4803
4804     in_port = (nar->in_port == htons(OFPP_IN_PORT)
4805                ? ctx->flow.in_port
4806                : ntohs(nar->in_port));
4807     table_id = nar->table == 255 ? ctx->table_id : nar->table;
4808
4809     xlate_table_action(ctx, in_port, table_id);
4810 }
4811
4812 static void
4813 flood_packets(struct action_xlate_ctx *ctx, bool all)
4814 {
4815     struct ofport_dpif *ofport;
4816
4817     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
4818         uint16_t ofp_port = ofport->up.ofp_port;
4819
4820         if (ofp_port == ctx->flow.in_port) {
4821             continue;
4822         }
4823
4824         if (all) {
4825             compose_output_action__(ctx, ofp_port, false);
4826         } else if (!(ofport->up.pp.config & OFPUTIL_PC_NO_FLOOD)) {
4827             compose_output_action(ctx, ofp_port);
4828         }
4829     }
4830
4831     ctx->nf_output_iface = NF_OUT_FLOOD;
4832 }
4833
4834 static void
4835 execute_controller_action(struct action_xlate_ctx *ctx, int len,
4836                           enum ofp_packet_in_reason reason,
4837                           uint16_t controller_id)
4838 {
4839     struct ofputil_packet_in pin;
4840     struct ofpbuf *packet;
4841
4842     ctx->may_set_up_flow = false;
4843     if (!ctx->packet) {
4844         return;
4845     }
4846
4847     packet = ofpbuf_clone(ctx->packet);
4848
4849     if (packet->l2 && packet->l3) {
4850         struct eth_header *eh;
4851
4852         eth_pop_vlan(packet);
4853         eh = packet->l2;
4854
4855         /* If the Ethernet type is less than ETH_TYPE_MIN, it's likely an 802.2
4856          * LLC frame.  Calculating the Ethernet type of these frames is more
4857          * trouble than seems appropriate for a simple assertion. */
4858         assert(ntohs(eh->eth_type) < ETH_TYPE_MIN
4859                || eh->eth_type == ctx->flow.dl_type);
4860
4861         memcpy(eh->eth_src, ctx->flow.dl_src, sizeof eh->eth_src);
4862         memcpy(eh->eth_dst, ctx->flow.dl_dst, sizeof eh->eth_dst);
4863
4864         if (ctx->flow.vlan_tci & htons(VLAN_CFI)) {
4865             eth_push_vlan(packet, ctx->flow.vlan_tci);
4866         }
4867
4868         if (packet->l4) {
4869             if (ctx->flow.dl_type == htons(ETH_TYPE_IP)) {
4870                 packet_set_ipv4(packet, ctx->flow.nw_src, ctx->flow.nw_dst,
4871                                 ctx->flow.nw_tos, ctx->flow.nw_ttl);
4872             }
4873
4874             if (packet->l7) {
4875                 if (ctx->flow.nw_proto == IPPROTO_TCP) {
4876                     packet_set_tcp_port(packet, ctx->flow.tp_src,
4877                                         ctx->flow.tp_dst);
4878                 } else if (ctx->flow.nw_proto == IPPROTO_UDP) {
4879                     packet_set_udp_port(packet, ctx->flow.tp_src,
4880                                         ctx->flow.tp_dst);
4881                 }
4882             }
4883         }
4884     }
4885
4886     pin.packet = packet->data;
4887     pin.packet_len = packet->size;
4888     pin.reason = reason;
4889     pin.controller_id = controller_id;
4890     pin.table_id = ctx->table_id;
4891     pin.cookie = ctx->rule ? ctx->rule->up.flow_cookie : 0;
4892
4893     pin.send_len = len;
4894     flow_get_metadata(&ctx->flow, &pin.fmd);
4895
4896     connmgr_send_packet_in(ctx->ofproto->up.connmgr, &pin);
4897     ofpbuf_delete(packet);
4898 }
4899
4900 static bool
4901 compose_dec_ttl(struct action_xlate_ctx *ctx)
4902 {
4903     if (ctx->flow.dl_type != htons(ETH_TYPE_IP) &&
4904         ctx->flow.dl_type != htons(ETH_TYPE_IPV6)) {
4905         return false;
4906     }
4907
4908     if (ctx->flow.nw_ttl > 1) {
4909         ctx->flow.nw_ttl--;
4910         return false;
4911     } else {
4912         execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL, 0);
4913
4914         /* Stop processing for current table. */
4915         return true;
4916     }
4917 }
4918
4919 static void
4920 xlate_output_action__(struct action_xlate_ctx *ctx,
4921                       uint16_t port, uint16_t max_len)
4922 {
4923     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
4924
4925     ctx->nf_output_iface = NF_OUT_DROP;
4926
4927     switch (port) {
4928     case OFPP_IN_PORT:
4929         compose_output_action(ctx, ctx->flow.in_port);
4930         break;
4931     case OFPP_TABLE:
4932         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
4933         break;
4934     case OFPP_NORMAL:
4935         xlate_normal(ctx);
4936         break;
4937     case OFPP_FLOOD:
4938         flood_packets(ctx,  false);
4939         break;
4940     case OFPP_ALL:
4941         flood_packets(ctx, true);
4942         break;
4943     case OFPP_CONTROLLER:
4944         execute_controller_action(ctx, max_len, OFPR_ACTION, 0);
4945         break;
4946     case OFPP_NONE:
4947         break;
4948     case OFPP_LOCAL:
4949     default:
4950         if (port != ctx->flow.in_port) {
4951             compose_output_action(ctx, port);
4952         }
4953         break;
4954     }
4955
4956     if (prev_nf_output_iface == NF_OUT_FLOOD) {
4957         ctx->nf_output_iface = NF_OUT_FLOOD;
4958     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
4959         ctx->nf_output_iface = prev_nf_output_iface;
4960     } else if (prev_nf_output_iface != NF_OUT_DROP &&
4961                ctx->nf_output_iface != NF_OUT_FLOOD) {
4962         ctx->nf_output_iface = NF_OUT_MULTI;
4963     }
4964 }
4965
4966 static void
4967 xlate_output_reg_action(struct action_xlate_ctx *ctx,
4968                         const struct nx_action_output_reg *naor)
4969 {
4970     struct mf_subfield src;
4971     uint64_t ofp_port;
4972
4973     nxm_decode(&src, naor->src, naor->ofs_nbits);
4974     ofp_port = mf_get_subfield(&src, &ctx->flow);
4975
4976     if (ofp_port <= UINT16_MAX) {
4977         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
4978     }
4979 }
4980
4981 static void
4982 xlate_output_action(struct action_xlate_ctx *ctx,
4983                     const struct ofp_action_output *oao)
4984 {
4985     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
4986 }
4987
4988 static void
4989 xlate_enqueue_action(struct action_xlate_ctx *ctx,
4990                      const struct ofp_action_enqueue *oae)
4991 {
4992     uint16_t ofp_port;
4993     uint32_t flow_priority, priority;
4994     int error;
4995
4996     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
4997                                    &priority);
4998     if (error) {
4999         /* Fall back to ordinary output action. */
5000         xlate_output_action__(ctx, ntohs(oae->port), 0);
5001         return;
5002     }
5003
5004     /* Figure out datapath output port. */
5005     ofp_port = ntohs(oae->port);
5006     if (ofp_port == OFPP_IN_PORT) {
5007         ofp_port = ctx->flow.in_port;
5008     } else if (ofp_port == ctx->flow.in_port) {
5009         return;
5010     }
5011
5012     /* Add datapath actions. */
5013     flow_priority = ctx->flow.skb_priority;
5014     ctx->flow.skb_priority = priority;
5015     compose_output_action(ctx, ofp_port);
5016     ctx->flow.skb_priority = flow_priority;
5017
5018     /* Update NetFlow output port. */
5019     if (ctx->nf_output_iface == NF_OUT_DROP) {
5020         ctx->nf_output_iface = ofp_port;
5021     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
5022         ctx->nf_output_iface = NF_OUT_MULTI;
5023     }
5024 }
5025
5026 static void
5027 xlate_set_queue_action(struct action_xlate_ctx *ctx,
5028                        const struct nx_action_set_queue *nasq)
5029 {
5030     uint32_t priority;
5031     int error;
5032
5033     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
5034                                    &priority);
5035     if (error) {
5036         /* Couldn't translate queue to a priority, so ignore.  A warning
5037          * has already been logged. */
5038         return;
5039     }
5040
5041     ctx->flow.skb_priority = priority;
5042 }
5043
5044 struct xlate_reg_state {
5045     ovs_be16 vlan_tci;
5046     ovs_be64 tun_id;
5047 };
5048
5049 static void
5050 xlate_autopath(struct action_xlate_ctx *ctx,
5051                const struct nx_action_autopath *naa)
5052 {
5053     uint16_t ofp_port = ntohl(naa->id);
5054     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
5055
5056     if (!port || !port->bundle) {
5057         ofp_port = OFPP_NONE;
5058     } else if (port->bundle->bond) {
5059         /* Autopath does not support VLAN hashing. */
5060         struct ofport_dpif *slave = bond_choose_output_slave(
5061             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
5062         if (slave) {
5063             ofp_port = slave->up.ofp_port;
5064         }
5065     }
5066     autopath_execute(naa, &ctx->flow, ofp_port);
5067 }
5068
5069 static bool
5070 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
5071 {
5072     struct ofproto_dpif *ofproto = ofproto_;
5073     struct ofport_dpif *port;
5074
5075     switch (ofp_port) {
5076     case OFPP_IN_PORT:
5077     case OFPP_TABLE:
5078     case OFPP_NORMAL:
5079     case OFPP_FLOOD:
5080     case OFPP_ALL:
5081     case OFPP_NONE:
5082         return true;
5083     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
5084         return false;
5085     default:
5086         port = get_ofp_port(ofproto, ofp_port);
5087         return port ? port->may_enable : false;
5088     }
5089 }
5090
5091 static void
5092 xlate_learn_action(struct action_xlate_ctx *ctx,
5093                    const struct nx_action_learn *learn)
5094 {
5095     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
5096     struct ofputil_flow_mod fm;
5097     int error;
5098
5099     learn_execute(learn, &ctx->flow, &fm);
5100
5101     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
5102     if (error && !VLOG_DROP_WARN(&rl)) {
5103         VLOG_WARN("learning action failed to modify flow table (%s)",
5104                   ofperr_get_name(error));
5105     }
5106
5107     free(fm.actions);
5108 }
5109
5110 /* Reduces '*timeout' to no more than 'max'.  A value of zero in either case
5111  * means "infinite". */
5112 static void
5113 reduce_timeout(uint16_t max, uint16_t *timeout)
5114 {
5115     if (max && (!*timeout || *timeout > max)) {
5116         *timeout = max;
5117     }
5118 }
5119
5120 static void
5121 xlate_fin_timeout(struct action_xlate_ctx *ctx,
5122                   const struct nx_action_fin_timeout *naft)
5123 {
5124     if (ctx->tcp_flags & (TCP_FIN | TCP_RST) && ctx->rule) {
5125         struct rule_dpif *rule = ctx->rule;
5126
5127         reduce_timeout(ntohs(naft->fin_idle_timeout), &rule->up.idle_timeout);
5128         reduce_timeout(ntohs(naft->fin_hard_timeout), &rule->up.hard_timeout);
5129     }
5130 }
5131
5132 static bool
5133 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
5134 {
5135     if (port->up.pp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
5136                               ? OFPUTIL_PC_NO_RECV_STP
5137                               : OFPUTIL_PC_NO_RECV)) {
5138         return false;
5139     }
5140
5141     /* Only drop packets here if both forwarding and learning are
5142      * disabled.  If just learning is enabled, we need to have
5143      * OFPP_NORMAL and the learning action have a look at the packet
5144      * before we can drop it. */
5145     if (!stp_forward_in_state(port->stp_state)
5146             && !stp_learn_in_state(port->stp_state)) {
5147         return false;
5148     }
5149
5150     return true;
5151 }
5152
5153 static void
5154 do_xlate_actions(const union ofp_action *in, size_t n_in,
5155                  struct action_xlate_ctx *ctx)
5156 {
5157     const struct ofport_dpif *port;
5158     const union ofp_action *ia;
5159     bool was_evictable = true;
5160     size_t left;
5161
5162     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
5163     if (port && !may_receive(port, ctx)) {
5164         /* Drop this flow. */
5165         return;
5166     }
5167
5168     if (ctx->rule) {
5169         /* Don't let the rule we're working on get evicted underneath us. */
5170         was_evictable = ctx->rule->up.evictable;
5171         ctx->rule->up.evictable = false;
5172     }
5173     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
5174         const struct ofp_action_dl_addr *oada;
5175         const struct nx_action_resubmit *nar;
5176         const struct nx_action_set_tunnel *nast;
5177         const struct nx_action_set_queue *nasq;
5178         const struct nx_action_multipath *nam;
5179         const struct nx_action_autopath *naa;
5180         const struct nx_action_bundle *nab;
5181         const struct nx_action_output_reg *naor;
5182         const struct nx_action_controller *nac;
5183         enum ofputil_action_code code;
5184         ovs_be64 tun_id;
5185
5186         if (ctx->exit) {
5187             break;
5188         }
5189
5190         code = ofputil_decode_action_unsafe(ia);
5191         switch (code) {
5192         case OFPUTIL_OFPAT10_OUTPUT:
5193             xlate_output_action(ctx, &ia->output);
5194             break;
5195
5196         case OFPUTIL_OFPAT10_SET_VLAN_VID:
5197             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
5198             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
5199             break;
5200
5201         case OFPUTIL_OFPAT10_SET_VLAN_PCP:
5202             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
5203             ctx->flow.vlan_tci |= htons(
5204                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
5205             break;
5206
5207         case OFPUTIL_OFPAT10_STRIP_VLAN:
5208             ctx->flow.vlan_tci = htons(0);
5209             break;
5210
5211         case OFPUTIL_OFPAT10_SET_DL_SRC:
5212             oada = ((struct ofp_action_dl_addr *) ia);
5213             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
5214             break;
5215
5216         case OFPUTIL_OFPAT10_SET_DL_DST:
5217             oada = ((struct ofp_action_dl_addr *) ia);
5218             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
5219             break;
5220
5221         case OFPUTIL_OFPAT10_SET_NW_SRC:
5222             ctx->flow.nw_src = ia->nw_addr.nw_addr;
5223             break;
5224
5225         case OFPUTIL_OFPAT10_SET_NW_DST:
5226             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
5227             break;
5228
5229         case OFPUTIL_OFPAT10_SET_NW_TOS:
5230             /* OpenFlow 1.0 only supports IPv4. */
5231             if (ctx->flow.dl_type == htons(ETH_TYPE_IP)) {
5232                 ctx->flow.nw_tos &= ~IP_DSCP_MASK;
5233                 ctx->flow.nw_tos |= ia->nw_tos.nw_tos & IP_DSCP_MASK;
5234             }
5235             break;
5236
5237         case OFPUTIL_OFPAT10_SET_TP_SRC:
5238             ctx->flow.tp_src = ia->tp_port.tp_port;
5239             break;
5240
5241         case OFPUTIL_OFPAT10_SET_TP_DST:
5242             ctx->flow.tp_dst = ia->tp_port.tp_port;
5243             break;
5244
5245         case OFPUTIL_OFPAT10_ENQUEUE:
5246             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
5247             break;
5248
5249         case OFPUTIL_NXAST_RESUBMIT:
5250             nar = (const struct nx_action_resubmit *) ia;
5251             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
5252             break;
5253
5254         case OFPUTIL_NXAST_RESUBMIT_TABLE:
5255             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
5256             break;
5257
5258         case OFPUTIL_NXAST_SET_TUNNEL:
5259             nast = (const struct nx_action_set_tunnel *) ia;
5260             tun_id = htonll(ntohl(nast->tun_id));
5261             ctx->flow.tun_id = tun_id;
5262             break;
5263
5264         case OFPUTIL_NXAST_SET_QUEUE:
5265             nasq = (const struct nx_action_set_queue *) ia;
5266             xlate_set_queue_action(ctx, nasq);
5267             break;
5268
5269         case OFPUTIL_NXAST_POP_QUEUE:
5270             ctx->flow.skb_priority = ctx->orig_skb_priority;
5271             break;
5272
5273         case OFPUTIL_NXAST_REG_MOVE:
5274             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
5275                                  &ctx->flow);
5276             break;
5277
5278         case OFPUTIL_NXAST_REG_LOAD:
5279             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
5280                                  &ctx->flow);
5281             break;
5282
5283         case OFPUTIL_NXAST_NOTE:
5284             /* Nothing to do. */
5285             break;
5286
5287         case OFPUTIL_NXAST_SET_TUNNEL64:
5288             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
5289             ctx->flow.tun_id = tun_id;
5290             break;
5291
5292         case OFPUTIL_NXAST_MULTIPATH:
5293             nam = (const struct nx_action_multipath *) ia;
5294             multipath_execute(nam, &ctx->flow);
5295             break;
5296
5297         case OFPUTIL_NXAST_AUTOPATH:
5298             naa = (const struct nx_action_autopath *) ia;
5299             xlate_autopath(ctx, naa);
5300             break;
5301
5302         case OFPUTIL_NXAST_BUNDLE:
5303             ctx->ofproto->has_bundle_action = true;
5304             nab = (const struct nx_action_bundle *) ia;
5305             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
5306                                                       slave_enabled_cb,
5307                                                       ctx->ofproto), 0);
5308             break;
5309
5310         case OFPUTIL_NXAST_BUNDLE_LOAD:
5311             ctx->ofproto->has_bundle_action = true;
5312             nab = (const struct nx_action_bundle *) ia;
5313             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
5314                                 ctx->ofproto);
5315             break;
5316
5317         case OFPUTIL_NXAST_OUTPUT_REG:
5318             naor = (const struct nx_action_output_reg *) ia;
5319             xlate_output_reg_action(ctx, naor);
5320             break;
5321
5322         case OFPUTIL_NXAST_LEARN:
5323             ctx->has_learn = true;
5324             if (ctx->may_learn) {
5325                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
5326             }
5327             break;
5328
5329         case OFPUTIL_NXAST_DEC_TTL:
5330             if (compose_dec_ttl(ctx)) {
5331                 goto out;
5332             }
5333             break;
5334
5335         case OFPUTIL_NXAST_EXIT:
5336             ctx->exit = true;
5337             break;
5338
5339         case OFPUTIL_NXAST_FIN_TIMEOUT:
5340             ctx->has_fin_timeout = true;
5341             xlate_fin_timeout(ctx, (const struct nx_action_fin_timeout *) ia);
5342             break;
5343
5344         case OFPUTIL_NXAST_CONTROLLER:
5345             nac = (const struct nx_action_controller *) ia;
5346             execute_controller_action(ctx, ntohs(nac->max_len), nac->reason,
5347                                       ntohs(nac->controller_id));
5348             break;
5349         }
5350     }
5351
5352 out:
5353     /* We've let OFPP_NORMAL and the learning action look at the packet,
5354      * so drop it now if forwarding is disabled. */
5355     if (port && !stp_forward_in_state(port->stp_state)) {
5356         ofpbuf_clear(ctx->odp_actions);
5357         add_sflow_action(ctx);
5358     }
5359     if (ctx->rule) {
5360         ctx->rule->up.evictable = was_evictable;
5361     }
5362 }
5363
5364 static void
5365 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
5366                       struct ofproto_dpif *ofproto, const struct flow *flow,
5367                       ovs_be16 initial_tci, struct rule_dpif *rule,
5368                       uint8_t tcp_flags, const struct ofpbuf *packet)
5369 {
5370     ctx->ofproto = ofproto;
5371     ctx->flow = *flow;
5372     ctx->base_flow = ctx->flow;
5373     ctx->base_flow.tun_id = 0;
5374     ctx->base_flow.vlan_tci = initial_tci;
5375     ctx->rule = rule;
5376     ctx->packet = packet;
5377     ctx->may_learn = packet != NULL;
5378     ctx->tcp_flags = tcp_flags;
5379     ctx->resubmit_hook = NULL;
5380     ctx->resubmit_stats = NULL;
5381 }
5382
5383 /* Translates the 'n_in' "union ofp_action"s in 'in' into datapath actions in
5384  * 'odp_actions', using 'ctx'. */
5385 static void
5386 xlate_actions(struct action_xlate_ctx *ctx,
5387               const union ofp_action *in, size_t n_in,
5388               struct ofpbuf *odp_actions)
5389 {
5390     /* Normally false.  Set to true if we ever hit MAX_RESUBMIT_RECURSION, so
5391      * that in the future we always keep a copy of the original flow for
5392      * tracing purposes. */
5393     static bool hit_resubmit_limit;
5394
5395     COVERAGE_INC(ofproto_dpif_xlate);
5396
5397     ofpbuf_clear(odp_actions);
5398     ofpbuf_reserve(odp_actions, NL_A_U32_SIZE);
5399
5400     ctx->odp_actions = odp_actions;
5401     ctx->tags = 0;
5402     ctx->may_set_up_flow = true;
5403     ctx->has_learn = false;
5404     ctx->has_normal = false;
5405     ctx->has_fin_timeout = false;
5406     ctx->nf_output_iface = NF_OUT_DROP;
5407     ctx->mirrors = 0;
5408     ctx->recurse = 0;
5409     ctx->max_resubmit_trigger = false;
5410     ctx->orig_skb_priority = ctx->flow.skb_priority;
5411     ctx->table_id = 0;
5412     ctx->exit = false;
5413
5414     if (ctx->ofproto->has_mirrors || hit_resubmit_limit) {
5415         /* Do this conditionally because the copy is expensive enough that it
5416          * shows up in profiles.
5417          *
5418          * We keep orig_flow in 'ctx' only because I couldn't make GCC 4.4
5419          * believe that I wasn't using it without initializing it if I kept it
5420          * in a local variable. */
5421         ctx->orig_flow = ctx->flow;
5422     }
5423
5424     if (ctx->flow.nw_frag & FLOW_NW_FRAG_ANY) {
5425         switch (ctx->ofproto->up.frag_handling) {
5426         case OFPC_FRAG_NORMAL:
5427             /* We must pretend that transport ports are unavailable. */
5428             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
5429             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
5430             break;
5431
5432         case OFPC_FRAG_DROP:
5433             return;
5434
5435         case OFPC_FRAG_REASM:
5436             NOT_REACHED();
5437
5438         case OFPC_FRAG_NX_MATCH:
5439             /* Nothing to do. */
5440             break;
5441
5442         case OFPC_INVALID_TTL_TO_CONTROLLER:
5443             NOT_REACHED();
5444         }
5445     }
5446
5447     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
5448         ctx->may_set_up_flow = false;
5449     } else {
5450         static struct vlog_rate_limit trace_rl = VLOG_RATE_LIMIT_INIT(1, 1);
5451         ovs_be16 initial_tci = ctx->base_flow.vlan_tci;
5452
5453         add_sflow_action(ctx);
5454         do_xlate_actions(in, n_in, ctx);
5455
5456         if (ctx->max_resubmit_trigger && !ctx->resubmit_hook) {
5457             if (!hit_resubmit_limit) {
5458                 /* We didn't record the original flow.  Make sure we do from
5459                  * now on. */
5460                 hit_resubmit_limit = true;
5461             } else if (!VLOG_DROP_ERR(&trace_rl)) {
5462                 struct ds ds = DS_EMPTY_INITIALIZER;
5463
5464                 ofproto_trace(ctx->ofproto, &ctx->orig_flow, ctx->packet,
5465                               initial_tci, &ds);
5466                 VLOG_ERR("Trace triggered by excessive resubmit "
5467                          "recursion:\n%s", ds_cstr(&ds));
5468                 ds_destroy(&ds);
5469             }
5470         }
5471
5472         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
5473                                      ctx->odp_actions->data,
5474                                      ctx->odp_actions->size)) {
5475             ctx->may_set_up_flow = false;
5476             if (ctx->packet
5477                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
5478                                        ctx->packet)) {
5479                 compose_output_action(ctx, OFPP_LOCAL);
5480             }
5481         }
5482         if (ctx->ofproto->has_mirrors) {
5483             add_mirror_actions(ctx, &ctx->orig_flow);
5484         }
5485         fix_sflow_action(ctx);
5486     }
5487 }
5488
5489 /* Translates the 'n_in' "union ofp_action"s in 'in' into datapath actions,
5490  * using 'ctx', and discards the datapath actions. */
5491 static void
5492 xlate_actions_for_side_effects(struct action_xlate_ctx *ctx,
5493                                const union ofp_action *in, size_t n_in)
5494 {
5495     uint64_t odp_actions_stub[1024 / 8];
5496     struct ofpbuf odp_actions;
5497
5498     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5499     xlate_actions(ctx, in, n_in, &odp_actions);
5500     ofpbuf_uninit(&odp_actions);
5501 }
5502 \f
5503 /* OFPP_NORMAL implementation. */
5504
5505 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
5506
5507 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
5508  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
5509  * the bundle on which the packet was received, returns the VLAN to which the
5510  * packet belongs.
5511  *
5512  * Both 'vid' and the return value are in the range 0...4095. */
5513 static uint16_t
5514 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
5515 {
5516     switch (in_bundle->vlan_mode) {
5517     case PORT_VLAN_ACCESS:
5518         return in_bundle->vlan;
5519         break;
5520
5521     case PORT_VLAN_TRUNK:
5522         return vid;
5523
5524     case PORT_VLAN_NATIVE_UNTAGGED:
5525     case PORT_VLAN_NATIVE_TAGGED:
5526         return vid ? vid : in_bundle->vlan;
5527
5528     default:
5529         NOT_REACHED();
5530     }
5531 }
5532
5533 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
5534  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
5535  * a warning.
5536  *
5537  * 'vid' should be the VID obtained from the 802.1Q header that was received as
5538  * part of a packet (specify 0 if there was no 802.1Q header), in the range
5539  * 0...4095. */
5540 static bool
5541 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
5542 {
5543     /* Allow any VID on the OFPP_NONE port. */
5544     if (in_bundle == &ofpp_none_bundle) {
5545         return true;
5546     }
5547
5548     switch (in_bundle->vlan_mode) {
5549     case PORT_VLAN_ACCESS:
5550         if (vid) {
5551             if (warn) {
5552                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5553                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
5554                              "packet received on port %s configured as VLAN "
5555                              "%"PRIu16" access port",
5556                              in_bundle->ofproto->up.name, vid,
5557                              in_bundle->name, in_bundle->vlan);
5558             }
5559             return false;
5560         }
5561         return true;
5562
5563     case PORT_VLAN_NATIVE_UNTAGGED:
5564     case PORT_VLAN_NATIVE_TAGGED:
5565         if (!vid) {
5566             /* Port must always carry its native VLAN. */
5567             return true;
5568         }
5569         /* Fall through. */
5570     case PORT_VLAN_TRUNK:
5571         if (!ofbundle_includes_vlan(in_bundle, vid)) {
5572             if (warn) {
5573                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5574                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
5575                              "received on port %s not configured for trunking "
5576                              "VLAN %"PRIu16,
5577                              in_bundle->ofproto->up.name, vid,
5578                              in_bundle->name, vid);
5579             }
5580             return false;
5581         }
5582         return true;
5583
5584     default:
5585         NOT_REACHED();
5586     }
5587
5588 }
5589
5590 /* Given 'vlan', the VLAN that a packet belongs to, and
5591  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
5592  * that should be included in the 802.1Q header.  (If the return value is 0,
5593  * then the 802.1Q header should only be included in the packet if there is a
5594  * nonzero PCP.)
5595  *
5596  * Both 'vlan' and the return value are in the range 0...4095. */
5597 static uint16_t
5598 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
5599 {
5600     switch (out_bundle->vlan_mode) {
5601     case PORT_VLAN_ACCESS:
5602         return 0;
5603
5604     case PORT_VLAN_TRUNK:
5605     case PORT_VLAN_NATIVE_TAGGED:
5606         return vlan;
5607
5608     case PORT_VLAN_NATIVE_UNTAGGED:
5609         return vlan == out_bundle->vlan ? 0 : vlan;
5610
5611     default:
5612         NOT_REACHED();
5613     }
5614 }
5615
5616 static void
5617 output_normal(struct action_xlate_ctx *ctx, const struct ofbundle *out_bundle,
5618               uint16_t vlan)
5619 {
5620     struct ofport_dpif *port;
5621     uint16_t vid;
5622     ovs_be16 tci, old_tci;
5623
5624     vid = output_vlan_to_vid(out_bundle, vlan);
5625     if (!out_bundle->bond) {
5626         port = ofbundle_get_a_port(out_bundle);
5627     } else {
5628         port = bond_choose_output_slave(out_bundle->bond, &ctx->flow,
5629                                         vid, &ctx->tags);
5630         if (!port) {
5631             /* No slaves enabled, so drop packet. */
5632             return;
5633         }
5634     }
5635
5636     old_tci = ctx->flow.vlan_tci;
5637     tci = htons(vid);
5638     if (tci || out_bundle->use_priority_tags) {
5639         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
5640         if (tci) {
5641             tci |= htons(VLAN_CFI);
5642         }
5643     }
5644     ctx->flow.vlan_tci = tci;
5645
5646     compose_output_action(ctx, port->up.ofp_port);
5647     ctx->flow.vlan_tci = old_tci;
5648 }
5649
5650 static int
5651 mirror_mask_ffs(mirror_mask_t mask)
5652 {
5653     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
5654     return ffs(mask);
5655 }
5656
5657 static bool
5658 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
5659 {
5660     return (bundle->vlan_mode != PORT_VLAN_ACCESS
5661             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
5662 }
5663
5664 static bool
5665 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
5666 {
5667     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
5668 }
5669
5670 /* Returns an arbitrary interface within 'bundle'. */
5671 static struct ofport_dpif *
5672 ofbundle_get_a_port(const struct ofbundle *bundle)
5673 {
5674     return CONTAINER_OF(list_front(&bundle->ports),
5675                         struct ofport_dpif, bundle_node);
5676 }
5677
5678 static bool
5679 vlan_is_mirrored(const struct ofmirror *m, int vlan)
5680 {
5681     return !m->vlans || bitmap_is_set(m->vlans, vlan);
5682 }
5683
5684 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
5685  * to a VLAN.  In general most packets may be mirrored but we want to drop
5686  * protocols that may confuse switches. */
5687 static bool
5688 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
5689 {
5690     /* If you change this function's behavior, please update corresponding
5691      * documentation in vswitch.xml at the same time. */
5692     if (dst[0] != 0x01) {
5693         /* All the currently banned MACs happen to start with 01 currently, so
5694          * this is a quick way to eliminate most of the good ones. */
5695     } else {
5696         if (eth_addr_is_reserved(dst)) {
5697             /* Drop STP, IEEE pause frames, and other reserved protocols
5698              * (01-80-c2-00-00-0x). */
5699             return false;
5700         }
5701
5702         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
5703             /* Cisco OUI. */
5704             if ((dst[3] & 0xfe) == 0xcc &&
5705                 (dst[4] & 0xfe) == 0xcc &&
5706                 (dst[5] & 0xfe) == 0xcc) {
5707                 /* Drop the following protocols plus others following the same
5708                    pattern:
5709
5710                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
5711                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
5712                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
5713                 return false;
5714             }
5715
5716             if (!(dst[3] | dst[4] | dst[5])) {
5717                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
5718                 return false;
5719             }
5720         }
5721     }
5722     return true;
5723 }
5724
5725 static void
5726 add_mirror_actions(struct action_xlate_ctx *ctx, const struct flow *orig_flow)
5727 {
5728     struct ofproto_dpif *ofproto = ctx->ofproto;
5729     mirror_mask_t mirrors;
5730     struct ofbundle *in_bundle;
5731     uint16_t vlan;
5732     uint16_t vid;
5733     const struct nlattr *a;
5734     size_t left;
5735
5736     in_bundle = lookup_input_bundle(ctx->ofproto, orig_flow->in_port,
5737                                     ctx->packet != NULL, NULL);
5738     if (!in_bundle) {
5739         return;
5740     }
5741     mirrors = in_bundle->src_mirrors;
5742
5743     /* Drop frames on bundles reserved for mirroring. */
5744     if (in_bundle->mirror_out) {
5745         if (ctx->packet != NULL) {
5746             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5747             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
5748                          "%s, which is reserved exclusively for mirroring",
5749                          ctx->ofproto->up.name, in_bundle->name);
5750         }
5751         return;
5752     }
5753
5754     /* Check VLAN. */
5755     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
5756     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
5757         return;
5758     }
5759     vlan = input_vid_to_vlan(in_bundle, vid);
5760
5761     /* Look at the output ports to check for destination selections. */
5762
5763     NL_ATTR_FOR_EACH (a, left, ctx->odp_actions->data,
5764                       ctx->odp_actions->size) {
5765         enum ovs_action_attr type = nl_attr_type(a);
5766         struct ofport_dpif *ofport;
5767
5768         if (type != OVS_ACTION_ATTR_OUTPUT) {
5769             continue;
5770         }
5771
5772         ofport = get_odp_port(ofproto, nl_attr_get_u32(a));
5773         if (ofport && ofport->bundle) {
5774             mirrors |= ofport->bundle->dst_mirrors;
5775         }
5776     }
5777
5778     if (!mirrors) {
5779         return;
5780     }
5781
5782     /* Restore the original packet before adding the mirror actions. */
5783     ctx->flow = *orig_flow;
5784
5785     while (mirrors) {
5786         struct ofmirror *m;
5787
5788         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
5789
5790         if (!vlan_is_mirrored(m, vlan)) {
5791             mirrors &= mirrors - 1;
5792             continue;
5793         }
5794
5795         mirrors &= ~m->dup_mirrors;
5796         ctx->mirrors |= m->dup_mirrors;
5797         if (m->out) {
5798             output_normal(ctx, m->out, vlan);
5799         } else if (eth_dst_may_rspan(orig_flow->dl_dst)
5800                    && vlan != m->out_vlan) {
5801             struct ofbundle *bundle;
5802
5803             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
5804                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
5805                     && !bundle->mirror_out) {
5806                     output_normal(ctx, bundle, m->out_vlan);
5807                 }
5808             }
5809         }
5810     }
5811 }
5812
5813 static void
5814 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
5815                     uint64_t packets, uint64_t bytes)
5816 {
5817     if (!mirrors) {
5818         return;
5819     }
5820
5821     for (; mirrors; mirrors &= mirrors - 1) {
5822         struct ofmirror *m;
5823
5824         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
5825
5826         if (!m) {
5827             /* In normal circumstances 'm' will not be NULL.  However,
5828              * if mirrors are reconfigured, we can temporarily get out
5829              * of sync in facet_revalidate().  We could "correct" the
5830              * mirror list before reaching here, but doing that would
5831              * not properly account the traffic stats we've currently
5832              * accumulated for previous mirror configuration. */
5833             continue;
5834         }
5835
5836         m->packet_count += packets;
5837         m->byte_count += bytes;
5838     }
5839 }
5840
5841 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
5842  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
5843  * indicate this; newer upstream kernels use gratuitous ARP requests. */
5844 static bool
5845 is_gratuitous_arp(const struct flow *flow)
5846 {
5847     return (flow->dl_type == htons(ETH_TYPE_ARP)
5848             && eth_addr_is_broadcast(flow->dl_dst)
5849             && (flow->nw_proto == ARP_OP_REPLY
5850                 || (flow->nw_proto == ARP_OP_REQUEST
5851                     && flow->nw_src == flow->nw_dst)));
5852 }
5853
5854 static void
5855 update_learning_table(struct ofproto_dpif *ofproto,
5856                       const struct flow *flow, int vlan,
5857                       struct ofbundle *in_bundle)
5858 {
5859     struct mac_entry *mac;
5860
5861     /* Don't learn the OFPP_NONE port. */
5862     if (in_bundle == &ofpp_none_bundle) {
5863         return;
5864     }
5865
5866     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
5867         return;
5868     }
5869
5870     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
5871     if (is_gratuitous_arp(flow)) {
5872         /* We don't want to learn from gratuitous ARP packets that are
5873          * reflected back over bond slaves so we lock the learning table. */
5874         if (!in_bundle->bond) {
5875             mac_entry_set_grat_arp_lock(mac);
5876         } else if (mac_entry_is_grat_arp_locked(mac)) {
5877             return;
5878         }
5879     }
5880
5881     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
5882         /* The log messages here could actually be useful in debugging,
5883          * so keep the rate limit relatively high. */
5884         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5885         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
5886                     "on port %s in VLAN %d",
5887                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
5888                     in_bundle->name, vlan);
5889
5890         mac->port.p = in_bundle;
5891         tag_set_add(&ofproto->revalidate_set,
5892                     mac_learning_changed(ofproto->ml, mac));
5893     }
5894 }
5895
5896 static struct ofbundle *
5897 lookup_input_bundle(struct ofproto_dpif *ofproto, uint16_t in_port, bool warn,
5898                     struct ofport_dpif **in_ofportp)
5899 {
5900     struct ofport_dpif *ofport;
5901
5902     /* Find the port and bundle for the received packet. */
5903     ofport = get_ofp_port(ofproto, in_port);
5904     if (in_ofportp) {
5905         *in_ofportp = ofport;
5906     }
5907     if (ofport && ofport->bundle) {
5908         return ofport->bundle;
5909     }
5910
5911     /* Special-case OFPP_NONE, which a controller may use as the ingress
5912      * port for traffic that it is sourcing. */
5913     if (in_port == OFPP_NONE) {
5914         return &ofpp_none_bundle;
5915     }
5916
5917     /* Odd.  A few possible reasons here:
5918      *
5919      * - We deleted a port but there are still a few packets queued up
5920      *   from it.
5921      *
5922      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
5923      *   we don't know about.
5924      *
5925      * - The ofproto client didn't configure the port as part of a bundle.
5926      */
5927     if (warn) {
5928         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5929
5930         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
5931                      "port %"PRIu16, ofproto->up.name, in_port);
5932     }
5933     return NULL;
5934 }
5935
5936 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
5937  * dropped.  Returns true if they may be forwarded, false if they should be
5938  * dropped.
5939  *
5940  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
5941  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
5942  *
5943  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
5944  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
5945  * checked by input_vid_is_valid().
5946  *
5947  * May also add tags to '*tags', although the current implementation only does
5948  * so in one special case.
5949  */
5950 static bool
5951 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
5952               struct ofport_dpif *in_port, uint16_t vlan, tag_type *tags)
5953 {
5954     struct ofbundle *in_bundle = in_port->bundle;
5955
5956     /* Drop frames for reserved multicast addresses
5957      * only if forward_bpdu option is absent. */
5958     if (eth_addr_is_reserved(flow->dl_dst) && !ofproto->up.forward_bpdu) {
5959         return false;
5960     }
5961
5962     if (in_bundle->bond) {
5963         struct mac_entry *mac;
5964
5965         switch (bond_check_admissibility(in_bundle->bond, in_port,
5966                                          flow->dl_dst, tags)) {
5967         case BV_ACCEPT:
5968             break;
5969
5970         case BV_DROP:
5971             return false;
5972
5973         case BV_DROP_IF_MOVED:
5974             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
5975             if (mac && mac->port.p != in_bundle &&
5976                 (!is_gratuitous_arp(flow)
5977                  || mac_entry_is_grat_arp_locked(mac))) {
5978                 return false;
5979             }
5980             break;
5981         }
5982     }
5983
5984     return true;
5985 }
5986
5987 static void
5988 xlate_normal(struct action_xlate_ctx *ctx)
5989 {
5990     struct ofport_dpif *in_port;
5991     struct ofbundle *in_bundle;
5992     struct mac_entry *mac;
5993     uint16_t vlan;
5994     uint16_t vid;
5995
5996     ctx->has_normal = true;
5997
5998     in_bundle = lookup_input_bundle(ctx->ofproto, ctx->flow.in_port,
5999                                     ctx->packet != NULL, &in_port);
6000     if (!in_bundle) {
6001         return;
6002     }
6003
6004     /* Drop malformed frames. */
6005     if (ctx->flow.dl_type == htons(ETH_TYPE_VLAN) &&
6006         !(ctx->flow.vlan_tci & htons(VLAN_CFI))) {
6007         if (ctx->packet != NULL) {
6008             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6009             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
6010                          "VLAN tag received on port %s",
6011                          ctx->ofproto->up.name, in_bundle->name);
6012         }
6013         return;
6014     }
6015
6016     /* Drop frames on bundles reserved for mirroring. */
6017     if (in_bundle->mirror_out) {
6018         if (ctx->packet != NULL) {
6019             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6020             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
6021                          "%s, which is reserved exclusively for mirroring",
6022                          ctx->ofproto->up.name, in_bundle->name);
6023         }
6024         return;
6025     }
6026
6027     /* Check VLAN. */
6028     vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
6029     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
6030         return;
6031     }
6032     vlan = input_vid_to_vlan(in_bundle, vid);
6033
6034     /* Check other admissibility requirements. */
6035     if (in_port &&
6036          !is_admissible(ctx->ofproto, &ctx->flow, in_port, vlan, &ctx->tags)) {
6037         return;
6038     }
6039
6040     /* Learn source MAC. */
6041     if (ctx->may_learn) {
6042         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
6043     }
6044
6045     /* Determine output bundle. */
6046     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
6047                               &ctx->tags);
6048     if (mac) {
6049         if (mac->port.p != in_bundle) {
6050             output_normal(ctx, mac->port.p, vlan);
6051         }
6052     } else {
6053         struct ofbundle *bundle;
6054
6055         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
6056             if (bundle != in_bundle
6057                 && ofbundle_includes_vlan(bundle, vlan)
6058                 && bundle->floodable
6059                 && !bundle->mirror_out) {
6060                 output_normal(ctx, bundle, vlan);
6061             }
6062         }
6063         ctx->nf_output_iface = NF_OUT_FLOOD;
6064     }
6065 }
6066 \f
6067 /* Optimized flow revalidation.
6068  *
6069  * It's a difficult problem, in general, to tell which facets need to have
6070  * their actions recalculated whenever the OpenFlow flow table changes.  We
6071  * don't try to solve that general problem: for most kinds of OpenFlow flow
6072  * table changes, we recalculate the actions for every facet.  This is
6073  * relatively expensive, but it's good enough if the OpenFlow flow table
6074  * doesn't change very often.
6075  *
6076  * However, we can expect one particular kind of OpenFlow flow table change to
6077  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
6078  * of CPU on revalidating every facet whenever MAC learning modifies the flow
6079  * table, we add a special case that applies to flow tables in which every rule
6080  * has the same form (that is, the same wildcards), except that the table is
6081  * also allowed to have a single "catch-all" flow that matches all packets.  We
6082  * optimize this case by tagging all of the facets that resubmit into the table
6083  * and invalidating the same tag whenever a flow changes in that table.  The
6084  * end result is that we revalidate just the facets that need it (and sometimes
6085  * a few more, but not all of the facets or even all of the facets that
6086  * resubmit to the table modified by MAC learning). */
6087
6088 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
6089  * into an OpenFlow table with the given 'basis'. */
6090 static tag_type
6091 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
6092                    uint32_t secret)
6093 {
6094     if (flow_wildcards_is_catchall(wc)) {
6095         return 0;
6096     } else {
6097         struct flow tag_flow = *flow;
6098         flow_zero_wildcards(&tag_flow, wc);
6099         return tag_create_deterministic(flow_hash(&tag_flow, secret));
6100     }
6101 }
6102
6103 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
6104  * taggability of that table.
6105  *
6106  * This function must be called after *each* change to a flow table.  If you
6107  * skip calling it on some changes then the pointer comparisons at the end can
6108  * be invalid if you get unlucky.  For example, if a flow removal causes a
6109  * cls_table to be destroyed and then a flow insertion causes a cls_table with
6110  * different wildcards to be created with the same address, then this function
6111  * will incorrectly skip revalidation. */
6112 static void
6113 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
6114 {
6115     struct table_dpif *table = &ofproto->tables[table_id];
6116     const struct oftable *oftable = &ofproto->up.tables[table_id];
6117     struct cls_table *catchall, *other;
6118     struct cls_table *t;
6119
6120     catchall = other = NULL;
6121
6122     switch (hmap_count(&oftable->cls.tables)) {
6123     case 0:
6124         /* We could tag this OpenFlow table but it would make the logic a
6125          * little harder and it's a corner case that doesn't seem worth it
6126          * yet. */
6127         break;
6128
6129     case 1:
6130     case 2:
6131         HMAP_FOR_EACH (t, hmap_node, &oftable->cls.tables) {
6132             if (cls_table_is_catchall(t)) {
6133                 catchall = t;
6134             } else if (!other) {
6135                 other = t;
6136             } else {
6137                 /* Indicate that we can't tag this by setting both tables to
6138                  * NULL.  (We know that 'catchall' is already NULL.) */
6139                 other = NULL;
6140             }
6141         }
6142         break;
6143
6144     default:
6145         /* Can't tag this table. */
6146         break;
6147     }
6148
6149     if (table->catchall_table != catchall || table->other_table != other) {
6150         table->catchall_table = catchall;
6151         table->other_table = other;
6152         ofproto->need_revalidate = true;
6153     }
6154 }
6155
6156 /* Given 'rule' that has changed in some way (either it is a rule being
6157  * inserted, a rule being deleted, or a rule whose actions are being
6158  * modified), marks facets for revalidation to ensure that packets will be
6159  * forwarded correctly according to the new state of the flow table.
6160  *
6161  * This function must be called after *each* change to a flow table.  See
6162  * the comment on table_update_taggable() for more information. */
6163 static void
6164 rule_invalidate(const struct rule_dpif *rule)
6165 {
6166     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
6167
6168     table_update_taggable(ofproto, rule->up.table_id);
6169
6170     if (!ofproto->need_revalidate) {
6171         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
6172
6173         if (table->other_table && rule->tag) {
6174             tag_set_add(&ofproto->revalidate_set, rule->tag);
6175         } else {
6176             ofproto->need_revalidate = true;
6177         }
6178     }
6179 }
6180 \f
6181 static bool
6182 set_frag_handling(struct ofproto *ofproto_,
6183                   enum ofp_config_flags frag_handling)
6184 {
6185     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
6186
6187     if (frag_handling != OFPC_FRAG_REASM) {
6188         ofproto->need_revalidate = true;
6189         return true;
6190     } else {
6191         return false;
6192     }
6193 }
6194
6195 static enum ofperr
6196 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
6197            const struct flow *flow,
6198            const union ofp_action *ofp_actions, size_t n_ofp_actions)
6199 {
6200     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
6201     enum ofperr error;
6202
6203     if (flow->in_port >= ofproto->max_ports && flow->in_port < OFPP_MAX) {
6204         return OFPERR_NXBRC_BAD_IN_PORT;
6205     }
6206
6207     error = validate_actions(ofp_actions, n_ofp_actions, flow,
6208                              ofproto->max_ports);
6209     if (!error) {
6210         struct odputil_keybuf keybuf;
6211         struct dpif_flow_stats stats;
6212
6213         struct ofpbuf key;
6214
6215         struct action_xlate_ctx ctx;
6216         uint64_t odp_actions_stub[1024 / 8];
6217         struct ofpbuf odp_actions;
6218
6219         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
6220         odp_flow_key_from_flow(&key, flow);
6221
6222         dpif_flow_stats_extract(flow, packet, &stats);
6223
6224         action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, NULL,
6225                               packet_get_tcp_flags(packet, flow), packet);
6226         ctx.resubmit_stats = &stats;
6227
6228         ofpbuf_use_stub(&odp_actions,
6229                         odp_actions_stub, sizeof odp_actions_stub);
6230         xlate_actions(&ctx, ofp_actions, n_ofp_actions, &odp_actions);
6231         dpif_execute(ofproto->dpif, key.data, key.size,
6232                      odp_actions.data, odp_actions.size, packet);
6233         ofpbuf_uninit(&odp_actions);
6234     }
6235     return error;
6236 }
6237 \f
6238 /* NetFlow. */
6239
6240 static int
6241 set_netflow(struct ofproto *ofproto_,
6242             const struct netflow_options *netflow_options)
6243 {
6244     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
6245
6246     if (netflow_options) {
6247         if (!ofproto->netflow) {
6248             ofproto->netflow = netflow_create();
6249         }
6250         return netflow_set_options(ofproto->netflow, netflow_options);
6251     } else {
6252         netflow_destroy(ofproto->netflow);
6253         ofproto->netflow = NULL;
6254         return 0;
6255     }
6256 }
6257
6258 static void
6259 get_netflow_ids(const struct ofproto *ofproto_,
6260                 uint8_t *engine_type, uint8_t *engine_id)
6261 {
6262     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
6263
6264     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
6265 }
6266
6267 static void
6268 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
6269 {
6270     if (!facet_is_controller_flow(facet) &&
6271         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
6272         struct subfacet *subfacet;
6273         struct ofexpired expired;
6274
6275         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
6276             if (subfacet->installed) {
6277                 struct dpif_flow_stats stats;
6278
6279                 subfacet_install(subfacet, subfacet->actions,
6280                                  subfacet->actions_len, &stats);
6281                 subfacet_update_stats(subfacet, &stats);
6282             }
6283         }
6284
6285         expired.flow = facet->flow;
6286         expired.packet_count = facet->packet_count;
6287         expired.byte_count = facet->byte_count;
6288         expired.used = facet->used;
6289         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
6290     }
6291 }
6292
6293 static void
6294 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
6295 {
6296     struct facet *facet;
6297
6298     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
6299         send_active_timeout(ofproto, facet);
6300     }
6301 }
6302 \f
6303 static struct ofproto_dpif *
6304 ofproto_dpif_lookup(const char *name)
6305 {
6306     struct ofproto_dpif *ofproto;
6307
6308     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
6309                              hash_string(name, 0), &all_ofproto_dpifs) {
6310         if (!strcmp(ofproto->up.name, name)) {
6311             return ofproto;
6312         }
6313     }
6314     return NULL;
6315 }
6316
6317 static void
6318 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
6319                           const char *argv[], void *aux OVS_UNUSED)
6320 {
6321     struct ofproto_dpif *ofproto;
6322
6323     if (argc > 1) {
6324         ofproto = ofproto_dpif_lookup(argv[1]);
6325         if (!ofproto) {
6326             unixctl_command_reply_error(conn, "no such bridge");
6327             return;
6328         }
6329         mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
6330     } else {
6331         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6332             mac_learning_flush(ofproto->ml, &ofproto->revalidate_set);
6333         }
6334     }
6335
6336     unixctl_command_reply(conn, "table successfully flushed");
6337 }
6338
6339 static void
6340 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
6341                          const char *argv[], void *aux OVS_UNUSED)
6342 {
6343     struct ds ds = DS_EMPTY_INITIALIZER;
6344     const struct ofproto_dpif *ofproto;
6345     const struct mac_entry *e;
6346
6347     ofproto = ofproto_dpif_lookup(argv[1]);
6348     if (!ofproto) {
6349         unixctl_command_reply_error(conn, "no such bridge");
6350         return;
6351     }
6352
6353     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
6354     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
6355         struct ofbundle *bundle = e->port.p;
6356         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
6357                       ofbundle_get_a_port(bundle)->odp_port,
6358                       e->vlan, ETH_ADDR_ARGS(e->mac),
6359                       mac_entry_age(ofproto->ml, e));
6360     }
6361     unixctl_command_reply(conn, ds_cstr(&ds));
6362     ds_destroy(&ds);
6363 }
6364
6365 struct trace_ctx {
6366     struct action_xlate_ctx ctx;
6367     struct flow flow;
6368     struct ds *result;
6369 };
6370
6371 static void
6372 trace_format_rule(struct ds *result, uint8_t table_id, int level,
6373                   const struct rule_dpif *rule)
6374 {
6375     ds_put_char_multiple(result, '\t', level);
6376     if (!rule) {
6377         ds_put_cstr(result, "No match\n");
6378         return;
6379     }
6380
6381     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
6382                   table_id, ntohll(rule->up.flow_cookie));
6383     cls_rule_format(&rule->up.cr, result);
6384     ds_put_char(result, '\n');
6385
6386     ds_put_char_multiple(result, '\t', level);
6387     ds_put_cstr(result, "OpenFlow ");
6388     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
6389     ds_put_char(result, '\n');
6390 }
6391
6392 static void
6393 trace_format_flow(struct ds *result, int level, const char *title,
6394                  struct trace_ctx *trace)
6395 {
6396     ds_put_char_multiple(result, '\t', level);
6397     ds_put_format(result, "%s: ", title);
6398     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
6399         ds_put_cstr(result, "unchanged");
6400     } else {
6401         flow_format(result, &trace->ctx.flow);
6402         trace->flow = trace->ctx.flow;
6403     }
6404     ds_put_char(result, '\n');
6405 }
6406
6407 static void
6408 trace_format_regs(struct ds *result, int level, const char *title,
6409                   struct trace_ctx *trace)
6410 {
6411     size_t i;
6412
6413     ds_put_char_multiple(result, '\t', level);
6414     ds_put_format(result, "%s:", title);
6415     for (i = 0; i < FLOW_N_REGS; i++) {
6416         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
6417     }
6418     ds_put_char(result, '\n');
6419 }
6420
6421 static void
6422 trace_format_odp(struct ds *result, int level, const char *title,
6423                  struct trace_ctx *trace)
6424 {
6425     struct ofpbuf *odp_actions = trace->ctx.odp_actions;
6426
6427     ds_put_char_multiple(result, '\t', level);
6428     ds_put_format(result, "%s: ", title);
6429     format_odp_actions(result, odp_actions->data, odp_actions->size);
6430     ds_put_char(result, '\n');
6431 }
6432
6433 static void
6434 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
6435 {
6436     struct trace_ctx *trace = CONTAINER_OF(ctx, struct trace_ctx, ctx);
6437     struct ds *result = trace->result;
6438
6439     ds_put_char(result, '\n');
6440     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
6441     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
6442     trace_format_odp(result,  ctx->recurse + 1, "Resubmitted  odp", trace);
6443     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
6444 }
6445
6446 static void
6447 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
6448                       void *aux OVS_UNUSED)
6449 {
6450     const char *dpname = argv[1];
6451     struct ofproto_dpif *ofproto;
6452     struct ofpbuf odp_key;
6453     struct ofpbuf *packet;
6454     ovs_be16 initial_tci;
6455     struct ds result;
6456     struct flow flow;
6457     char *s;
6458
6459     packet = NULL;
6460     ofpbuf_init(&odp_key, 0);
6461     ds_init(&result);
6462
6463     ofproto = ofproto_dpif_lookup(dpname);
6464     if (!ofproto) {
6465         unixctl_command_reply_error(conn, "Unknown ofproto (use ofproto/list "
6466                                     "for help)");
6467         goto exit;
6468     }
6469     if (argc == 3 || (argc == 4 && !strcmp(argv[3], "-generate"))) {
6470         /* ofproto/trace dpname flow [-generate] */
6471         const char *flow_s = argv[2];
6472         const char *generate_s = argv[3];
6473
6474         /* Allow 'flow_s' to be either a datapath flow or an OpenFlow-like
6475          * flow.  We guess which type it is based on whether 'flow_s' contains
6476          * an '(', since a datapath flow always contains '(') but an
6477          * OpenFlow-like flow should not (in fact it's allowed but I believe
6478          * that's not documented anywhere).
6479          *
6480          * An alternative would be to try to parse 'flow_s' both ways, but then
6481          * it would be tricky giving a sensible error message.  After all, do
6482          * you just say "syntax error" or do you present both error messages?
6483          * Both choices seem lousy. */
6484         if (strchr(flow_s, '(')) {
6485             int error;
6486
6487             /* Convert string to datapath key. */
6488             ofpbuf_init(&odp_key, 0);
6489             error = odp_flow_key_from_string(flow_s, NULL, &odp_key);
6490             if (error) {
6491                 unixctl_command_reply_error(conn, "Bad flow syntax");
6492                 goto exit;
6493             }
6494
6495             /* Convert odp_key to flow. */
6496             error = ofproto_dpif_extract_flow_key(ofproto, odp_key.data,
6497                                                   odp_key.size, &flow,
6498                                                   &initial_tci, NULL);
6499             if (error == ODP_FIT_ERROR) {
6500                 unixctl_command_reply_error(conn, "Invalid flow");
6501                 goto exit;
6502             }
6503         } else {
6504             char *error_s;
6505
6506             error_s = parse_ofp_exact_flow(&flow, argv[2]);
6507             if (error_s) {
6508                 unixctl_command_reply_error(conn, error_s);
6509                 free(error_s);
6510                 goto exit;
6511             }
6512
6513             initial_tci = flow.vlan_tci;
6514             vsp_adjust_flow(ofproto, &flow);
6515         }
6516
6517         /* Generate a packet, if requested. */
6518         if (generate_s) {
6519             packet = ofpbuf_new(0);
6520             flow_compose(packet, &flow);
6521         }
6522     } else if (argc == 6) {
6523         /* ofproto/trace dpname priority tun_id in_port packet */
6524         const char *priority_s = argv[2];
6525         const char *tun_id_s = argv[3];
6526         const char *in_port_s = argv[4];
6527         const char *packet_s = argv[5];
6528         uint16_t in_port = ofp_port_to_odp_port(atoi(in_port_s));
6529         ovs_be64 tun_id = htonll(strtoull(tun_id_s, NULL, 0));
6530         uint32_t priority = atoi(priority_s);
6531         const char *msg;
6532
6533         msg = eth_from_hex(packet_s, &packet);
6534         if (msg) {
6535             unixctl_command_reply_error(conn, msg);
6536             goto exit;
6537         }
6538
6539         ds_put_cstr(&result, "Packet: ");
6540         s = ofp_packet_to_string(packet->data, packet->size);
6541         ds_put_cstr(&result, s);
6542         free(s);
6543
6544         flow_extract(packet, priority, tun_id, in_port, &flow);
6545         initial_tci = flow.vlan_tci;
6546     } else {
6547         unixctl_command_reply_error(conn, "Bad command syntax");
6548         goto exit;
6549     }
6550
6551     ofproto_trace(ofproto, &flow, packet, initial_tci, &result);
6552     unixctl_command_reply(conn, ds_cstr(&result));
6553
6554 exit:
6555     ds_destroy(&result);
6556     ofpbuf_delete(packet);
6557     ofpbuf_uninit(&odp_key);
6558 }
6559
6560 static void
6561 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
6562               const struct ofpbuf *packet, ovs_be16 initial_tci,
6563               struct ds *ds)
6564 {
6565     struct rule_dpif *rule;
6566
6567     ds_put_cstr(ds, "Flow: ");
6568     flow_format(ds, flow);
6569     ds_put_char(ds, '\n');
6570
6571     rule = rule_dpif_lookup(ofproto, flow);
6572
6573     trace_format_rule(ds, 0, 0, rule);
6574     if (rule == ofproto->miss_rule) {
6575         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
6576     } else if (rule == ofproto->no_packet_in_rule) {
6577         ds_put_cstr(ds, "\nNo match, packets dropped because "
6578                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
6579     }
6580
6581     if (rule) {
6582         uint64_t odp_actions_stub[1024 / 8];
6583         struct ofpbuf odp_actions;
6584
6585         struct trace_ctx trace;
6586         uint8_t tcp_flags;
6587
6588         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
6589         trace.result = ds;
6590         trace.flow = *flow;
6591         ofpbuf_use_stub(&odp_actions,
6592                         odp_actions_stub, sizeof odp_actions_stub);
6593         action_xlate_ctx_init(&trace.ctx, ofproto, flow, initial_tci,
6594                               rule, tcp_flags, packet);
6595         trace.ctx.resubmit_hook = trace_resubmit;
6596         xlate_actions(&trace.ctx, rule->up.actions, rule->up.n_actions,
6597                       &odp_actions);
6598
6599         ds_put_char(ds, '\n');
6600         trace_format_flow(ds, 0, "Final flow", &trace);
6601         ds_put_cstr(ds, "Datapath actions: ");
6602         format_odp_actions(ds, odp_actions.data, odp_actions.size);
6603         ofpbuf_uninit(&odp_actions);
6604
6605         if (!trace.ctx.may_set_up_flow) {
6606             if (packet) {
6607                 ds_put_cstr(ds, "\nThis flow is not cachable.");
6608             } else {
6609                 ds_put_cstr(ds, "\nThe datapath actions are incomplete--"
6610                             "for complete actions, please supply a packet.");
6611             }
6612         }
6613     }
6614 }
6615
6616 static void
6617 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
6618                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6619 {
6620     clogged = true;
6621     unixctl_command_reply(conn, NULL);
6622 }
6623
6624 static void
6625 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
6626                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6627 {
6628     clogged = false;
6629     unixctl_command_reply(conn, NULL);
6630 }
6631
6632 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
6633  * 'reply' describing the results. */
6634 static void
6635 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
6636 {
6637     struct facet *facet;
6638     int errors;
6639
6640     errors = 0;
6641     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
6642         if (!facet_check_consistency(facet)) {
6643             errors++;
6644         }
6645     }
6646     if (errors) {
6647         ofproto->need_revalidate = true;
6648     }
6649
6650     if (errors) {
6651         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
6652                       ofproto->up.name, errors);
6653     } else {
6654         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
6655     }
6656 }
6657
6658 static void
6659 ofproto_dpif_self_check(struct unixctl_conn *conn,
6660                         int argc, const char *argv[], void *aux OVS_UNUSED)
6661 {
6662     struct ds reply = DS_EMPTY_INITIALIZER;
6663     struct ofproto_dpif *ofproto;
6664
6665     if (argc > 1) {
6666         ofproto = ofproto_dpif_lookup(argv[1]);
6667         if (!ofproto) {
6668             unixctl_command_reply_error(conn, "Unknown ofproto (use "
6669                                         "ofproto/list for help)");
6670             return;
6671         }
6672         ofproto_dpif_self_check__(ofproto, &reply);
6673     } else {
6674         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6675             ofproto_dpif_self_check__(ofproto, &reply);
6676         }
6677     }
6678
6679     unixctl_command_reply(conn, ds_cstr(&reply));
6680     ds_destroy(&reply);
6681 }
6682
6683 static void
6684 ofproto_dpif_unixctl_init(void)
6685 {
6686     static bool registered;
6687     if (registered) {
6688         return;
6689     }
6690     registered = true;
6691
6692     unixctl_command_register(
6693         "ofproto/trace",
6694         "bridge {tun_id in_port packet | odp_flow [-generate]}",
6695         2, 5, ofproto_unixctl_trace, NULL);
6696     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
6697                              ofproto_unixctl_fdb_flush, NULL);
6698     unixctl_command_register("fdb/show", "bridge", 1, 1,
6699                              ofproto_unixctl_fdb_show, NULL);
6700     unixctl_command_register("ofproto/clog", "", 0, 0,
6701                              ofproto_dpif_clog, NULL);
6702     unixctl_command_register("ofproto/unclog", "", 0, 0,
6703                              ofproto_dpif_unclog, NULL);
6704     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
6705                              ofproto_dpif_self_check, NULL);
6706 }
6707 \f
6708 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6709  *
6710  * This is deprecated.  It is only for compatibility with broken device drivers
6711  * in old versions of Linux that do not properly support VLANs when VLAN
6712  * devices are not used.  When broken device drivers are no longer in
6713  * widespread use, we will delete these interfaces. */
6714
6715 static int
6716 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
6717 {
6718     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
6719     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
6720
6721     if (realdev_ofp_port == ofport->realdev_ofp_port
6722         && vid == ofport->vlandev_vid) {
6723         return 0;
6724     }
6725
6726     ofproto->need_revalidate = true;
6727
6728     if (ofport->realdev_ofp_port) {
6729         vsp_remove(ofport);
6730     }
6731     if (realdev_ofp_port && ofport->bundle) {
6732         /* vlandevs are enslaved to their realdevs, so they are not allowed to
6733          * themselves be part of a bundle. */
6734         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
6735     }
6736
6737     ofport->realdev_ofp_port = realdev_ofp_port;
6738     ofport->vlandev_vid = vid;
6739
6740     if (realdev_ofp_port) {
6741         vsp_add(ofport, realdev_ofp_port, vid);
6742     }
6743
6744     return 0;
6745 }
6746
6747 static uint32_t
6748 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
6749 {
6750     return hash_2words(realdev_ofp_port, vid);
6751 }
6752
6753 /* Returns the ODP port number of the Linux VLAN device that corresponds to
6754  * 'vlan_tci' on the network device with port number 'realdev_odp_port' in
6755  * 'ofproto'.  For example, given 'realdev_odp_port' of eth0 and 'vlan_tci' 9,
6756  * it would return the port number of eth0.9.
6757  *
6758  * Unless VLAN splinters are enabled for port 'realdev_odp_port', this
6759  * function just returns its 'realdev_odp_port' argument. */
6760 static uint32_t
6761 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
6762                        uint32_t realdev_odp_port, ovs_be16 vlan_tci)
6763 {
6764     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
6765         uint16_t realdev_ofp_port = odp_port_to_ofp_port(realdev_odp_port);
6766         int vid = vlan_tci_to_vid(vlan_tci);
6767         const struct vlan_splinter *vsp;
6768
6769         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
6770                                  hash_realdev_vid(realdev_ofp_port, vid),
6771                                  &ofproto->realdev_vid_map) {
6772             if (vsp->realdev_ofp_port == realdev_ofp_port
6773                 && vsp->vid == vid) {
6774                 return ofp_port_to_odp_port(vsp->vlandev_ofp_port);
6775             }
6776         }
6777     }
6778     return realdev_odp_port;
6779 }
6780
6781 static struct vlan_splinter *
6782 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
6783 {
6784     struct vlan_splinter *vsp;
6785
6786     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
6787                              &ofproto->vlandev_map) {
6788         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
6789             return vsp;
6790         }
6791     }
6792
6793     return NULL;
6794 }
6795
6796 /* Returns the OpenFlow port number of the "real" device underlying the Linux
6797  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
6798  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
6799  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
6800  * eth0 and store 9 in '*vid'.
6801  *
6802  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
6803  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
6804  * always does.*/
6805 static uint16_t
6806 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
6807                        uint16_t vlandev_ofp_port, int *vid)
6808 {
6809     if (!hmap_is_empty(&ofproto->vlandev_map)) {
6810         const struct vlan_splinter *vsp;
6811
6812         vsp = vlandev_find(ofproto, vlandev_ofp_port);
6813         if (vsp) {
6814             if (vid) {
6815                 *vid = vsp->vid;
6816             }
6817             return vsp->realdev_ofp_port;
6818         }
6819     }
6820     return 0;
6821 }
6822
6823 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
6824  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
6825  * 'flow->in_port' to the "real" device backing the VLAN device, sets
6826  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
6827  * always the case unless VLAN splinters are enabled), returns false without
6828  * making any changes. */
6829 static bool
6830 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
6831 {
6832     uint16_t realdev;
6833     int vid;
6834
6835     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port, &vid);
6836     if (!realdev) {
6837         return false;
6838     }
6839
6840     /* Cause the flow to be processed as if it came in on the real device with
6841      * the VLAN device's VLAN ID. */
6842     flow->in_port = realdev;
6843     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
6844     return true;
6845 }
6846
6847 static void
6848 vsp_remove(struct ofport_dpif *port)
6849 {
6850     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6851     struct vlan_splinter *vsp;
6852
6853     vsp = vlandev_find(ofproto, port->up.ofp_port);
6854     if (vsp) {
6855         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
6856         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
6857         free(vsp);
6858
6859         port->realdev_ofp_port = 0;
6860     } else {
6861         VLOG_ERR("missing vlan device record");
6862     }
6863 }
6864
6865 static void
6866 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
6867 {
6868     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6869
6870     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
6871         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
6872             == realdev_ofp_port)) {
6873         struct vlan_splinter *vsp;
6874
6875         vsp = xmalloc(sizeof *vsp);
6876         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
6877                     hash_int(port->up.ofp_port, 0));
6878         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
6879                     hash_realdev_vid(realdev_ofp_port, vid));
6880         vsp->realdev_ofp_port = realdev_ofp_port;
6881         vsp->vlandev_ofp_port = port->up.ofp_port;
6882         vsp->vid = vid;
6883
6884         port->realdev_ofp_port = realdev_ofp_port;
6885     } else {
6886         VLOG_ERR("duplicate vlan device record");
6887     }
6888 }
6889 \f
6890 const struct ofproto_class ofproto_dpif_class = {
6891     enumerate_types,
6892     enumerate_names,
6893     del,
6894     alloc,
6895     construct,
6896     destruct,
6897     dealloc,
6898     run,
6899     run_fast,
6900     wait,
6901     flush,
6902     get_features,
6903     get_tables,
6904     port_alloc,
6905     port_construct,
6906     port_destruct,
6907     port_dealloc,
6908     port_modified,
6909     port_reconfigured,
6910     port_query_by_name,
6911     port_add,
6912     port_del,
6913     port_get_stats,
6914     port_dump_start,
6915     port_dump_next,
6916     port_dump_done,
6917     port_poll,
6918     port_poll_wait,
6919     port_is_lacp_current,
6920     NULL,                       /* rule_choose_table */
6921     rule_alloc,
6922     rule_construct,
6923     rule_destruct,
6924     rule_dealloc,
6925     rule_get_stats,
6926     rule_execute,
6927     rule_modify_actions,
6928     set_frag_handling,
6929     packet_out,
6930     set_netflow,
6931     get_netflow_ids,
6932     set_sflow,
6933     set_cfm,
6934     get_cfm_fault,
6935     get_cfm_remote_mpids,
6936     get_cfm_health,
6937     set_stp,
6938     get_stp_status,
6939     set_stp_port,
6940     get_stp_port_status,
6941     set_queues,
6942     bundle_set,
6943     bundle_remove,
6944     mirror_set,
6945     mirror_get_stats,
6946     set_flood_vlans,
6947     is_mirror_output_bundle,
6948     forward_bpdu_changed,
6949     set_mac_idle_time,
6950     set_realdev,
6951 };