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