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