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