ofproto-dpif: Delete un-fit flow from datapath.
[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);
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)) {
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 static bool
3003 execute_controller_action(struct ofproto_dpif *ofproto,
3004                           const struct flow *flow,
3005                           const struct nlattr *odp_actions, size_t actions_len,
3006                           struct ofpbuf *packet)
3007 {
3008     if (actions_len
3009         && odp_actions->nla_type == OVS_ACTION_ATTR_USERSPACE
3010         && NLA_ALIGN(odp_actions->nla_len) == actions_len) {
3011         /* As an optimization, avoid a round-trip from userspace to kernel to
3012          * userspace.  This also avoids possibly filling up kernel packet
3013          * buffers along the way.
3014          *
3015          * This optimization will not accidentally catch sFlow
3016          * OVS_ACTION_ATTR_USERSPACE actions, since those are encapsulated
3017          * inside OVS_ACTION_ATTR_SAMPLE. */
3018         const struct nlattr *nla;
3019
3020         nla = nl_attr_find_nested(odp_actions, OVS_USERSPACE_ATTR_USERDATA);
3021         send_packet_in_action(ofproto, packet, nl_attr_get_u64(nla), flow,
3022                               false);
3023         return true;
3024     } else {
3025         return false;
3026     }
3027 }
3028
3029 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
3030  * 'packet', which arrived on 'in_port'.
3031  *
3032  * Takes ownership of 'packet'. */
3033 static bool
3034 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
3035                     const struct nlattr *odp_actions, size_t actions_len,
3036                     struct ofpbuf *packet)
3037 {
3038     struct odputil_keybuf keybuf;
3039     struct ofpbuf key;
3040     int error;
3041
3042     if (execute_controller_action(ofproto, flow, odp_actions, actions_len,
3043                                   packet)) {
3044         return true;
3045     }
3046
3047     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3048     odp_flow_key_from_flow(&key, flow);
3049
3050     error = dpif_execute(ofproto->dpif, key.data, key.size,
3051                          odp_actions, actions_len, packet);
3052
3053     ofpbuf_delete(packet);
3054     return !error;
3055 }
3056
3057 /* Remove 'facet' from 'ofproto' and free up the associated memory:
3058  *
3059  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
3060  *     rule's statistics, via subfacet_uninstall().
3061  *
3062  *   - Removes 'facet' from its rule and from ofproto->facets.
3063  */
3064 static void
3065 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
3066 {
3067     struct subfacet *subfacet, *next_subfacet;
3068
3069     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
3070                         &facet->subfacets) {
3071         subfacet_destroy__(ofproto, subfacet);
3072     }
3073
3074     facet_flush_stats(ofproto, facet);
3075     hmap_remove(&ofproto->facets, &facet->hmap_node);
3076     list_remove(&facet->list_node);
3077     facet_free(facet);
3078 }
3079
3080 static void
3081 facet_account(struct ofproto_dpif *ofproto, struct facet *facet)
3082 {
3083     uint64_t n_bytes;
3084     struct subfacet *subfacet;
3085     const struct nlattr *a;
3086     unsigned int left;
3087     ovs_be16 vlan_tci;
3088
3089     if (facet->byte_count <= facet->accounted_bytes) {
3090         return;
3091     }
3092     n_bytes = facet->byte_count - facet->accounted_bytes;
3093     facet->accounted_bytes = facet->byte_count;
3094
3095     /* Feed information from the active flows back into the learning table to
3096      * ensure that table is always in sync with what is actually flowing
3097      * through the datapath. */
3098     if (facet->has_learn || facet->has_normal) {
3099         struct action_xlate_ctx ctx;
3100
3101         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3102                               facet->flow.vlan_tci, NULL);
3103         ctx.may_learn = true;
3104         ofpbuf_delete(xlate_actions(&ctx, facet->rule->up.actions,
3105                                     facet->rule->up.n_actions));
3106     }
3107
3108     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
3109         return;
3110     }
3111
3112     /* This loop feeds byte counters to bond_account() for rebalancing to use
3113      * as a basis.  We also need to track the actual VLAN on which the packet
3114      * is going to be sent to ensure that it matches the one passed to
3115      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
3116      * hash bucket.)
3117      *
3118      * We use the actions from an arbitrary subfacet because they should all
3119      * be equally valid for our purpose. */
3120     subfacet = CONTAINER_OF(list_front(&facet->subfacets),
3121                             struct subfacet, list_node);
3122     vlan_tci = facet->flow.vlan_tci;
3123     NL_ATTR_FOR_EACH_UNSAFE (a, left,
3124                              subfacet->actions, subfacet->actions_len) {
3125         const struct ovs_action_push_vlan *vlan;
3126         struct ofport_dpif *port;
3127
3128         switch (nl_attr_type(a)) {
3129         case OVS_ACTION_ATTR_OUTPUT:
3130             port = get_odp_port(ofproto, nl_attr_get_u32(a));
3131             if (port && port->bundle && port->bundle->bond) {
3132                 bond_account(port->bundle->bond, &facet->flow,
3133                              vlan_tci_to_vid(vlan_tci), n_bytes);
3134             }
3135             break;
3136
3137         case OVS_ACTION_ATTR_POP_VLAN:
3138             vlan_tci = htons(0);
3139             break;
3140
3141         case OVS_ACTION_ATTR_PUSH_VLAN:
3142             vlan = nl_attr_get(a);
3143             vlan_tci = vlan->vlan_tci;
3144             break;
3145         }
3146     }
3147 }
3148
3149 /* Returns true if the only action for 'facet' is to send to the controller.
3150  * (We don't report NetFlow expiration messages for such facets because they
3151  * are just part of the control logic for the network, not real traffic). */
3152 static bool
3153 facet_is_controller_flow(struct facet *facet)
3154 {
3155     return (facet
3156             && facet->rule->up.n_actions == 1
3157             && action_outputs_to_port(&facet->rule->up.actions[0],
3158                                       htons(OFPP_CONTROLLER)));
3159 }
3160
3161 /* Folds all of 'facet''s statistics into its rule.  Also updates the
3162  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
3163  * 'facet''s statistics in the datapath should have been zeroed and folded into
3164  * its packet and byte counts before this function is called. */
3165 static void
3166 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
3167 {
3168     struct subfacet *subfacet;
3169
3170     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3171         assert(!subfacet->dp_byte_count);
3172         assert(!subfacet->dp_packet_count);
3173     }
3174
3175     facet_push_stats(facet);
3176     facet_account(ofproto, facet);
3177
3178     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
3179         struct ofexpired expired;
3180         expired.flow = facet->flow;
3181         expired.packet_count = facet->packet_count;
3182         expired.byte_count = facet->byte_count;
3183         expired.used = facet->used;
3184         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
3185     }
3186
3187     facet->rule->packet_count += facet->packet_count;
3188     facet->rule->byte_count += facet->byte_count;
3189
3190     /* Reset counters to prevent double counting if 'facet' ever gets
3191      * reinstalled. */
3192     facet_reset_counters(facet);
3193
3194     netflow_flow_clear(&facet->nf_flow);
3195 }
3196
3197 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3198  * Returns it if found, otherwise a null pointer.
3199  *
3200  * The returned facet might need revalidation; use facet_lookup_valid()
3201  * instead if that is important. */
3202 static struct facet *
3203 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
3204 {
3205     struct facet *facet;
3206
3207     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
3208                              &ofproto->facets) {
3209         if (flow_equal(flow, &facet->flow)) {
3210             return facet;
3211         }
3212     }
3213
3214     return NULL;
3215 }
3216
3217 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3218  * Returns it if found, otherwise a null pointer.
3219  *
3220  * The returned facet is guaranteed to be valid. */
3221 static struct facet *
3222 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
3223 {
3224     struct facet *facet = facet_find(ofproto, flow);
3225
3226     /* The facet we found might not be valid, since we could be in need of
3227      * revalidation.  If it is not valid, don't return it. */
3228     if (facet
3229         && (ofproto->need_revalidate
3230             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
3231         && !facet_revalidate(ofproto, facet)) {
3232         COVERAGE_INC(facet_invalidated);
3233         return NULL;
3234     }
3235
3236     return facet;
3237 }
3238
3239 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
3240  *
3241  *   - If the rule found is different from 'facet''s current rule, moves
3242  *     'facet' to the new rule and recompiles its actions.
3243  *
3244  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
3245  *     where it is and recompiles its actions anyway.
3246  *
3247  *   - If there is none, destroys 'facet'.
3248  *
3249  * Returns true if 'facet' still exists, false if it has been destroyed. */
3250 static bool
3251 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
3252 {
3253     struct actions {
3254         struct nlattr *odp_actions;
3255         size_t actions_len;
3256     };
3257     struct actions *new_actions;
3258
3259     struct action_xlate_ctx ctx;
3260     struct rule_dpif *new_rule;
3261     struct subfacet *subfacet;
3262     bool actions_changed;
3263     int i;
3264
3265     COVERAGE_INC(facet_revalidate);
3266
3267     /* Determine the new rule. */
3268     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
3269     if (!new_rule) {
3270         /* No new rule, so delete the facet. */
3271         facet_remove(ofproto, facet);
3272         return false;
3273     }
3274
3275     /* Calculate new datapath actions.
3276      *
3277      * We do not modify any 'facet' state yet, because we might need to, e.g.,
3278      * emit a NetFlow expiration and, if so, we need to have the old state
3279      * around to properly compose it. */
3280
3281     /* If the datapath actions changed or the installability changed,
3282      * then we need to talk to the datapath. */
3283     i = 0;
3284     new_actions = NULL;
3285     memset(&ctx, 0, sizeof ctx);
3286     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3287         struct ofpbuf *odp_actions;
3288         bool should_install;
3289
3290         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3291                               subfacet->initial_tci, NULL);
3292         odp_actions = xlate_actions(&ctx, new_rule->up.actions,
3293                                     new_rule->up.n_actions);
3294         actions_changed = (subfacet->actions_len != odp_actions->size
3295                            || memcmp(subfacet->actions, odp_actions->data,
3296                                      subfacet->actions_len));
3297
3298         should_install = (ctx.may_set_up_flow
3299                           && subfacet->key_fitness != ODP_FIT_TOO_LITTLE);
3300         if (actions_changed || should_install != subfacet->installed) {
3301             if (should_install) {
3302                 struct dpif_flow_stats stats;
3303
3304                 subfacet_install(ofproto, subfacet,
3305                                  odp_actions->data, odp_actions->size, &stats);
3306                 subfacet_update_stats(ofproto, subfacet, &stats);
3307             } else {
3308                 subfacet_uninstall(ofproto, subfacet);
3309             }
3310
3311             if (!new_actions) {
3312                 new_actions = xcalloc(list_size(&facet->subfacets),
3313                                       sizeof *new_actions);
3314             }
3315             new_actions[i].odp_actions = xmemdup(odp_actions->data,
3316                                                  odp_actions->size);
3317             new_actions[i].actions_len = odp_actions->size;
3318         }
3319
3320         ofpbuf_delete(odp_actions);
3321         i++;
3322     }
3323     if (new_actions) {
3324         facet_flush_stats(ofproto, facet);
3325     }
3326
3327     /* Update 'facet' now that we've taken care of all the old state. */
3328     facet->tags = ctx.tags;
3329     facet->nf_flow.output_iface = ctx.nf_output_iface;
3330     facet->may_install = ctx.may_set_up_flow;
3331     facet->has_learn = ctx.has_learn;
3332     facet->has_normal = ctx.has_normal;
3333     facet->mirrors = ctx.mirrors;
3334     if (new_actions) {
3335         i = 0;
3336         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3337             if (new_actions[i].odp_actions) {
3338                 free(subfacet->actions);
3339                 subfacet->actions = new_actions[i].odp_actions;
3340                 subfacet->actions_len = new_actions[i].actions_len;
3341             }
3342             i++;
3343         }
3344         free(new_actions);
3345     }
3346     if (facet->rule != new_rule) {
3347         COVERAGE_INC(facet_changed_rule);
3348         list_remove(&facet->list_node);
3349         list_push_back(&new_rule->facets, &facet->list_node);
3350         facet->rule = new_rule;
3351         facet->used = new_rule->up.created;
3352         facet->prev_used = facet->used;
3353     }
3354
3355     return true;
3356 }
3357
3358 /* Updates 'facet''s used time.  Caller is responsible for calling
3359  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3360 static void
3361 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
3362                   long long int used)
3363 {
3364     if (used > facet->used) {
3365         facet->used = used;
3366         if (used > facet->rule->used) {
3367             facet->rule->used = used;
3368         }
3369         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3370     }
3371 }
3372
3373 static void
3374 facet_reset_counters(struct facet *facet)
3375 {
3376     facet->packet_count = 0;
3377     facet->byte_count = 0;
3378     facet->prev_packet_count = 0;
3379     facet->prev_byte_count = 0;
3380     facet->accounted_bytes = 0;
3381 }
3382
3383 static void
3384 facet_push_stats(struct facet *facet)
3385 {
3386     uint64_t new_packets, new_bytes;
3387
3388     assert(facet->packet_count >= facet->prev_packet_count);
3389     assert(facet->byte_count >= facet->prev_byte_count);
3390     assert(facet->used >= facet->prev_used);
3391
3392     new_packets = facet->packet_count - facet->prev_packet_count;
3393     new_bytes = facet->byte_count - facet->prev_byte_count;
3394
3395     if (new_packets || new_bytes || facet->used > facet->prev_used) {
3396         facet->prev_packet_count = facet->packet_count;
3397         facet->prev_byte_count = facet->byte_count;
3398         facet->prev_used = facet->used;
3399
3400         flow_push_stats(facet->rule, &facet->flow,
3401                         new_packets, new_bytes, facet->used);
3402
3403         update_mirror_stats(ofproto_dpif_cast(facet->rule->up.ofproto),
3404                             facet->mirrors, new_packets, new_bytes);
3405     }
3406 }
3407
3408 struct ofproto_push {
3409     struct action_xlate_ctx ctx;
3410     uint64_t packets;
3411     uint64_t bytes;
3412     long long int used;
3413 };
3414
3415 static void
3416 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
3417 {
3418     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
3419
3420     if (rule) {
3421         rule->packet_count += push->packets;
3422         rule->byte_count += push->bytes;
3423         rule->used = MAX(push->used, rule->used);
3424     }
3425 }
3426
3427 /* Pushes flow statistics to the rules which 'flow' resubmits into given
3428  * 'rule''s actions and mirrors. */
3429 static void
3430 flow_push_stats(const struct rule_dpif *rule,
3431                 const struct flow *flow, uint64_t packets, uint64_t bytes,
3432                 long long int used)
3433 {
3434     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3435     struct ofproto_push push;
3436
3437     push.packets = packets;
3438     push.bytes = bytes;
3439     push.used = used;
3440
3441     action_xlate_ctx_init(&push.ctx, ofproto, flow, flow->vlan_tci, NULL);
3442     push.ctx.resubmit_hook = push_resubmit;
3443     ofpbuf_delete(xlate_actions(&push.ctx,
3444                                 rule->up.actions, rule->up.n_actions));
3445 }
3446 \f
3447 /* Subfacets. */
3448
3449 static struct subfacet *
3450 subfacet_find__(struct ofproto_dpif *ofproto,
3451                 const struct nlattr *key, size_t key_len, uint32_t key_hash,
3452                 const struct flow *flow)
3453 {
3454     struct subfacet *subfacet;
3455
3456     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
3457                              &ofproto->subfacets) {
3458         if (subfacet->key
3459             ? (subfacet->key_len == key_len
3460                && !memcmp(key, subfacet->key, key_len))
3461             : flow_equal(flow, &subfacet->facet->flow)) {
3462             return subfacet;
3463         }
3464     }
3465
3466     return NULL;
3467 }
3468
3469 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
3470  * 'key_fitness', 'key', and 'key_len'.  Returns the existing subfacet if
3471  * there is one, otherwise creates and returns a new subfacet.
3472  *
3473  * If the returned subfacet is new, then subfacet->actions will be NULL, in
3474  * which case the caller must populate the actions with
3475  * subfacet_make_actions(). */
3476 static struct subfacet *
3477 subfacet_create(struct ofproto_dpif *ofproto, struct facet *facet,
3478                 enum odp_key_fitness key_fitness,
3479                 const struct nlattr *key, size_t key_len, ovs_be16 initial_tci)
3480 {
3481     uint32_t key_hash = odp_flow_key_hash(key, key_len);
3482     struct subfacet *subfacet;
3483
3484     subfacet = subfacet_find__(ofproto, key, key_len, key_hash, &facet->flow);
3485     if (subfacet) {
3486         if (subfacet->facet == facet) {
3487             return subfacet;
3488         }
3489
3490         /* This shouldn't happen. */
3491         VLOG_ERR_RL(&rl, "subfacet with wrong facet");
3492         subfacet_destroy(ofproto, subfacet);
3493     }
3494
3495     subfacet = xzalloc(sizeof *subfacet);
3496     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
3497     list_push_back(&facet->subfacets, &subfacet->list_node);
3498     subfacet->facet = facet;
3499     subfacet->used = time_msec();
3500     subfacet->key_fitness = key_fitness;
3501     if (key_fitness != ODP_FIT_PERFECT) {
3502         subfacet->key = xmemdup(key, key_len);
3503         subfacet->key_len = key_len;
3504     }
3505     subfacet->installed = false;
3506     subfacet->initial_tci = initial_tci;
3507
3508     return subfacet;
3509 }
3510
3511 /* Searches 'ofproto' for a subfacet with the given 'key', 'key_len', and
3512  * 'flow'.  Returns the subfacet if one exists, otherwise NULL. */
3513 static struct subfacet *
3514 subfacet_find(struct ofproto_dpif *ofproto,
3515               const struct nlattr *key, size_t key_len)
3516 {
3517     uint32_t key_hash = odp_flow_key_hash(key, key_len);
3518     enum odp_key_fitness fitness;
3519     struct flow flow;
3520
3521     fitness = odp_flow_key_to_flow(key, key_len, &flow);
3522     if (fitness == ODP_FIT_ERROR) {
3523         return NULL;
3524     }
3525
3526     return subfacet_find__(ofproto, key, key_len, key_hash, &flow);
3527 }
3528
3529 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
3530  * its facet within 'ofproto', and frees it. */
3531 static void
3532 subfacet_destroy__(struct ofproto_dpif *ofproto, struct subfacet *subfacet)
3533 {
3534     subfacet_uninstall(ofproto, subfacet);
3535     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
3536     list_remove(&subfacet->list_node);
3537     free(subfacet->key);
3538     free(subfacet->actions);
3539     free(subfacet);
3540 }
3541
3542 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
3543  * last remaining subfacet in its facet destroys the facet too. */
3544 static void
3545 subfacet_destroy(struct ofproto_dpif *ofproto, struct subfacet *subfacet)
3546 {
3547     struct facet *facet = subfacet->facet;
3548
3549     subfacet_destroy__(ofproto, subfacet);
3550     if (list_is_empty(&facet->subfacets)) {
3551         facet_remove(ofproto, facet);
3552     }
3553 }
3554
3555 /* Initializes 'key' with the sequence of OVS_KEY_ATTR_* Netlink attributes
3556  * that can be used to refer to 'subfacet'.  The caller must provide 'keybuf'
3557  * for use as temporary storage. */
3558 static void
3559 subfacet_get_key(struct subfacet *subfacet, struct odputil_keybuf *keybuf,
3560                  struct ofpbuf *key)
3561 {
3562     if (!subfacet->key) {
3563         ofpbuf_use_stack(key, keybuf, sizeof *keybuf);
3564         odp_flow_key_from_flow(key, &subfacet->facet->flow);
3565     } else {
3566         ofpbuf_use_const(key, subfacet->key, subfacet->key_len);
3567     }
3568 }
3569
3570 /* Composes the datapath actions for 'subfacet' based on its rule's actions. */
3571 static void
3572 subfacet_make_actions(struct ofproto_dpif *p, struct subfacet *subfacet,
3573                       const struct ofpbuf *packet)
3574 {
3575     struct facet *facet = subfacet->facet;
3576     const struct rule_dpif *rule = facet->rule;
3577     struct ofpbuf *odp_actions;
3578     struct action_xlate_ctx ctx;
3579
3580     action_xlate_ctx_init(&ctx, p, &facet->flow, subfacet->initial_tci,
3581                           packet);
3582     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3583     facet->tags = ctx.tags;
3584     facet->may_install = ctx.may_set_up_flow;
3585     facet->has_learn = ctx.has_learn;
3586     facet->has_normal = ctx.has_normal;
3587     facet->nf_flow.output_iface = ctx.nf_output_iface;
3588     facet->mirrors = ctx.mirrors;
3589
3590     if (subfacet->actions_len != odp_actions->size
3591         || memcmp(subfacet->actions, odp_actions->data, odp_actions->size)) {
3592         free(subfacet->actions);
3593         subfacet->actions_len = odp_actions->size;
3594         subfacet->actions = xmemdup(odp_actions->data, odp_actions->size);
3595     }
3596
3597     ofpbuf_delete(odp_actions);
3598 }
3599
3600 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
3601  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
3602  * in the datapath will be zeroed and 'stats' will be updated with traffic new
3603  * since 'subfacet' was last updated.
3604  *
3605  * Returns 0 if successful, otherwise a positive errno value. */
3606 static int
3607 subfacet_install(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3608                  const struct nlattr *actions, size_t actions_len,
3609                  struct dpif_flow_stats *stats)
3610 {
3611     struct odputil_keybuf keybuf;
3612     enum dpif_flow_put_flags flags;
3613     struct ofpbuf key;
3614     int ret;
3615
3616     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3617     if (stats) {
3618         flags |= DPIF_FP_ZERO_STATS;
3619     }
3620
3621     subfacet_get_key(subfacet, &keybuf, &key);
3622     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
3623                         actions, actions_len, stats);
3624
3625     if (stats) {
3626         subfacet_reset_dp_stats(subfacet, stats);
3627     }
3628
3629     return ret;
3630 }
3631
3632 /* If 'subfacet' is installed in the datapath, uninstalls it. */
3633 static void
3634 subfacet_uninstall(struct ofproto_dpif *p, struct subfacet *subfacet)
3635 {
3636     if (subfacet->installed) {
3637         struct odputil_keybuf keybuf;
3638         struct dpif_flow_stats stats;
3639         struct ofpbuf key;
3640         int error;
3641
3642         subfacet_get_key(subfacet, &keybuf, &key);
3643         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
3644         subfacet_reset_dp_stats(subfacet, &stats);
3645         if (!error) {
3646             subfacet_update_stats(p, subfacet, &stats);
3647         }
3648         subfacet->installed = false;
3649     } else {
3650         assert(subfacet->dp_packet_count == 0);
3651         assert(subfacet->dp_byte_count == 0);
3652     }
3653 }
3654
3655 /* Resets 'subfacet''s datapath statistics counters.  This should be called
3656  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
3657  * non-null, it should contain the statistics returned by dpif when 'subfacet'
3658  * was reset in the datapath.  'stats' will be modified to include only
3659  * statistics new since 'subfacet' was last updated. */
3660 static void
3661 subfacet_reset_dp_stats(struct subfacet *subfacet,
3662                         struct dpif_flow_stats *stats)
3663 {
3664     if (stats
3665         && subfacet->dp_packet_count <= stats->n_packets
3666         && subfacet->dp_byte_count <= stats->n_bytes) {
3667         stats->n_packets -= subfacet->dp_packet_count;
3668         stats->n_bytes -= subfacet->dp_byte_count;
3669     }
3670
3671     subfacet->dp_packet_count = 0;
3672     subfacet->dp_byte_count = 0;
3673 }
3674
3675 /* Updates 'subfacet''s used time.  The caller is responsible for calling
3676  * facet_push_stats() to update the flows which 'subfacet' resubmits into. */
3677 static void
3678 subfacet_update_time(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3679                      long long int used)
3680 {
3681     if (used > subfacet->used) {
3682         subfacet->used = used;
3683         facet_update_time(ofproto, subfacet->facet, used);
3684     }
3685 }
3686
3687 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
3688  *
3689  * Because of the meaning of a subfacet's counters, it only makes sense to do
3690  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
3691  * represents a packet that was sent by hand or if it represents statistics
3692  * that have been cleared out of the datapath. */
3693 static void
3694 subfacet_update_stats(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3695                       const struct dpif_flow_stats *stats)
3696 {
3697     if (stats->n_packets || stats->used > subfacet->used) {
3698         struct facet *facet = subfacet->facet;
3699
3700         subfacet_update_time(ofproto, subfacet, stats->used);
3701         facet->packet_count += stats->n_packets;
3702         facet->byte_count += stats->n_bytes;
3703         facet_push_stats(facet);
3704         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3705     }
3706 }
3707 \f
3708 /* Rules. */
3709
3710 static struct rule_dpif *
3711 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
3712                  uint8_t table_id)
3713 {
3714     struct cls_rule *cls_rule;
3715     struct classifier *cls;
3716
3717     if (table_id >= N_TABLES) {
3718         return NULL;
3719     }
3720
3721     cls = &ofproto->up.tables[table_id];
3722     if (flow->nw_frag & FLOW_NW_FRAG_ANY
3723         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3724         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
3725          * are unavailable. */
3726         struct flow ofpc_normal_flow = *flow;
3727         ofpc_normal_flow.tp_src = htons(0);
3728         ofpc_normal_flow.tp_dst = htons(0);
3729         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
3730     } else {
3731         cls_rule = classifier_lookup(cls, flow);
3732     }
3733     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
3734 }
3735
3736 static void
3737 complete_operation(struct rule_dpif *rule)
3738 {
3739     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3740
3741     rule_invalidate(rule);
3742     if (clogged) {
3743         struct dpif_completion *c = xmalloc(sizeof *c);
3744         c->op = rule->up.pending;
3745         list_push_back(&ofproto->completions, &c->list_node);
3746     } else {
3747         ofoperation_complete(rule->up.pending, 0);
3748     }
3749 }
3750
3751 static struct rule *
3752 rule_alloc(void)
3753 {
3754     struct rule_dpif *rule = xmalloc(sizeof *rule);
3755     return &rule->up;
3756 }
3757
3758 static void
3759 rule_dealloc(struct rule *rule_)
3760 {
3761     struct rule_dpif *rule = rule_dpif_cast(rule_);
3762     free(rule);
3763 }
3764
3765 static int
3766 rule_construct(struct rule *rule_)
3767 {
3768     struct rule_dpif *rule = rule_dpif_cast(rule_);
3769     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3770     struct rule_dpif *victim;
3771     uint8_t table_id;
3772     int error;
3773
3774     error = validate_actions(rule->up.actions, rule->up.n_actions,
3775                              &rule->up.cr.flow, ofproto->max_ports);
3776     if (error) {
3777         return error;
3778     }
3779
3780     rule->used = rule->up.created;
3781     rule->packet_count = 0;
3782     rule->byte_count = 0;
3783
3784     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
3785     if (victim && !list_is_empty(&victim->facets)) {
3786         struct facet *facet;
3787
3788         rule->facets = victim->facets;
3789         list_moved(&rule->facets);
3790         LIST_FOR_EACH (facet, list_node, &rule->facets) {
3791             /* XXX: We're only clearing our local counters here.  It's possible
3792              * that quite a few packets are unaccounted for in the datapath
3793              * statistics.  These will be accounted to the new rule instead of
3794              * cleared as required.  This could be fixed by clearing out the
3795              * datapath statistics for this facet, but currently it doesn't
3796              * seem worth it. */
3797             facet_reset_counters(facet);
3798             facet->rule = rule;
3799         }
3800     } else {
3801         /* Must avoid list_moved() in this case. */
3802         list_init(&rule->facets);
3803     }
3804
3805     table_id = rule->up.table_id;
3806     rule->tag = (victim ? victim->tag
3807                  : table_id == 0 ? 0
3808                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
3809                                       ofproto->tables[table_id].basis));
3810
3811     complete_operation(rule);
3812     return 0;
3813 }
3814
3815 static void
3816 rule_destruct(struct rule *rule_)
3817 {
3818     struct rule_dpif *rule = rule_dpif_cast(rule_);
3819     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3820     struct facet *facet, *next_facet;
3821
3822     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3823         facet_revalidate(ofproto, facet);
3824     }
3825
3826     complete_operation(rule);
3827 }
3828
3829 static void
3830 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3831 {
3832     struct rule_dpif *rule = rule_dpif_cast(rule_);
3833     struct facet *facet;
3834
3835     /* Start from historical data for 'rule' itself that are no longer tracked
3836      * in facets.  This counts, for example, facets that have expired. */
3837     *packets = rule->packet_count;
3838     *bytes = rule->byte_count;
3839
3840     /* Add any statistics that are tracked by facets.  This includes
3841      * statistical data recently updated by ofproto_update_stats() as well as
3842      * stats for packets that were executed "by hand" via dpif_execute(). */
3843     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3844         *packets += facet->packet_count;
3845         *bytes += facet->byte_count;
3846     }
3847 }
3848
3849 static int
3850 rule_execute(struct rule *rule_, const struct flow *flow,
3851              struct ofpbuf *packet)
3852 {
3853     struct rule_dpif *rule = rule_dpif_cast(rule_);
3854     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3855     struct action_xlate_ctx ctx;
3856     struct ofpbuf *odp_actions;
3857     size_t size;
3858
3859     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, packet);
3860     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3861     size = packet->size;
3862     if (execute_odp_actions(ofproto, flow, odp_actions->data,
3863                             odp_actions->size, packet)) {
3864         rule->used = time_msec();
3865         rule->packet_count++;
3866         rule->byte_count += size;
3867         flow_push_stats(rule, flow, 1, size, rule->used);
3868     }
3869     ofpbuf_delete(odp_actions);
3870
3871     return 0;
3872 }
3873
3874 static void
3875 rule_modify_actions(struct rule *rule_)
3876 {
3877     struct rule_dpif *rule = rule_dpif_cast(rule_);
3878     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3879     int error;
3880
3881     error = validate_actions(rule->up.actions, rule->up.n_actions,
3882                              &rule->up.cr.flow, ofproto->max_ports);
3883     if (error) {
3884         ofoperation_complete(rule->up.pending, error);
3885         return;
3886     }
3887
3888     complete_operation(rule);
3889 }
3890 \f
3891 /* Sends 'packet' out 'ofport'.
3892  * May modify 'packet'.
3893  * Returns 0 if successful, otherwise a positive errno value. */
3894 static int
3895 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
3896 {
3897     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3898     struct ofpbuf key, odp_actions;
3899     struct odputil_keybuf keybuf;
3900     uint16_t odp_port;
3901     struct flow flow;
3902     int error;
3903
3904     flow_extract((struct ofpbuf *) packet, 0, 0, 0, &flow);
3905     odp_port = vsp_realdev_to_vlandev(ofproto, ofport->odp_port,
3906                                       flow.vlan_tci);
3907     if (odp_port != ofport->odp_port) {
3908         eth_pop_vlan(packet);
3909         flow.vlan_tci = htons(0);
3910     }
3911
3912     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3913     odp_flow_key_from_flow(&key, &flow);
3914
3915     ofpbuf_init(&odp_actions, 32);
3916     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
3917
3918     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3919     error = dpif_execute(ofproto->dpif,
3920                          key.data, key.size,
3921                          odp_actions.data, odp_actions.size,
3922                          packet);
3923     ofpbuf_uninit(&odp_actions);
3924
3925     if (error) {
3926         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
3927                      ofproto->up.name, odp_port, strerror(error));
3928     }
3929     return error;
3930 }
3931 \f
3932 /* OpenFlow to datapath action translation. */
3933
3934 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3935                              struct action_xlate_ctx *ctx);
3936 static void xlate_normal(struct action_xlate_ctx *);
3937
3938 static size_t
3939 put_userspace_action(const struct ofproto_dpif *ofproto,
3940                      struct ofpbuf *odp_actions,
3941                      const struct flow *flow,
3942                      const struct user_action_cookie *cookie)
3943 {
3944     uint32_t pid;
3945
3946     pid = dpif_port_get_pid(ofproto->dpif,
3947                             ofp_port_to_odp_port(flow->in_port));
3948
3949     return odp_put_userspace_action(pid, cookie, odp_actions);
3950 }
3951
3952 /* Compose SAMPLE action for sFlow. */
3953 static size_t
3954 compose_sflow_action(const struct ofproto_dpif *ofproto,
3955                      struct ofpbuf *odp_actions,
3956                      const struct flow *flow,
3957                      uint32_t odp_port)
3958 {
3959     uint32_t port_ifindex;
3960     uint32_t probability;
3961     struct user_action_cookie cookie;
3962     size_t sample_offset, actions_offset;
3963     int cookie_offset, n_output;
3964
3965     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
3966         return 0;
3967     }
3968
3969     if (odp_port == OVSP_NONE) {
3970         port_ifindex = 0;
3971         n_output = 0;
3972     } else {
3973         port_ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
3974         n_output = 1;
3975     }
3976
3977     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
3978
3979     /* Number of packets out of UINT_MAX to sample. */
3980     probability = dpif_sflow_get_probability(ofproto->sflow);
3981     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
3982
3983     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
3984
3985     cookie.type = USER_ACTION_COOKIE_SFLOW;
3986     cookie.data = port_ifindex;
3987     cookie.n_output = n_output;
3988     cookie.vlan_tci = 0;
3989     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
3990
3991     nl_msg_end_nested(odp_actions, actions_offset);
3992     nl_msg_end_nested(odp_actions, sample_offset);
3993     return cookie_offset;
3994 }
3995
3996 /* SAMPLE action must be first action in any given list of actions.
3997  * At this point we do not have all information required to build it. So try to
3998  * build sample action as complete as possible. */
3999 static void
4000 add_sflow_action(struct action_xlate_ctx *ctx)
4001 {
4002     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
4003                                                    ctx->odp_actions,
4004                                                    &ctx->flow, OVSP_NONE);
4005     ctx->sflow_odp_port = 0;
4006     ctx->sflow_n_outputs = 0;
4007 }
4008
4009 /* Fix SAMPLE action according to data collected while composing ODP actions.
4010  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
4011  * USERSPACE action's user-cookie which is required for sflow. */
4012 static void
4013 fix_sflow_action(struct action_xlate_ctx *ctx)
4014 {
4015     const struct flow *base = &ctx->base_flow;
4016     struct user_action_cookie *cookie;
4017
4018     if (!ctx->user_cookie_offset) {
4019         return;
4020     }
4021
4022     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
4023                      sizeof(*cookie));
4024     assert(cookie != NULL);
4025     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
4026
4027     if (ctx->sflow_n_outputs) {
4028         cookie->data = dpif_sflow_odp_port_to_ifindex(ctx->ofproto->sflow,
4029                                                     ctx->sflow_odp_port);
4030     }
4031     if (ctx->sflow_n_outputs >= 255) {
4032         cookie->n_output = 255;
4033     } else {
4034         cookie->n_output = ctx->sflow_n_outputs;
4035     }
4036     cookie->vlan_tci = base->vlan_tci;
4037 }
4038
4039 static void
4040 compose_output_action__(struct action_xlate_ctx *ctx, uint16_t ofp_port,
4041                         bool check_stp)
4042 {
4043     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
4044     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
4045     ovs_be16 flow_vlan_tci = ctx->flow.vlan_tci;
4046     uint8_t flow_nw_tos = ctx->flow.nw_tos;
4047     uint16_t out_port;
4048
4049     if (ofport) {
4050         struct priority_to_dscp *pdscp;
4051
4052         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)
4053             || (check_stp && !stp_forward_in_state(ofport->stp_state))) {
4054             return;
4055         }
4056
4057         pdscp = get_priority(ofport, ctx->flow.priority);
4058         if (pdscp) {
4059             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
4060             ctx->flow.nw_tos |= pdscp->dscp;
4061         }
4062     } else {
4063         /* We may not have an ofport record for this port, but it doesn't hurt
4064          * to allow forwarding to it anyhow.  Maybe such a port will appear
4065          * later and we're pre-populating the flow table.  */
4066     }
4067
4068     out_port = vsp_realdev_to_vlandev(ctx->ofproto, odp_port,
4069                                       ctx->flow.vlan_tci);
4070     if (out_port != odp_port) {
4071         ctx->flow.vlan_tci = htons(0);
4072     }
4073     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
4074     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, out_port);
4075
4076     ctx->sflow_odp_port = odp_port;
4077     ctx->sflow_n_outputs++;
4078     ctx->nf_output_iface = ofp_port;
4079     ctx->flow.vlan_tci = flow_vlan_tci;
4080     ctx->flow.nw_tos = flow_nw_tos;
4081 }
4082
4083 static void
4084 compose_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
4085 {
4086     compose_output_action__(ctx, ofp_port, true);
4087 }
4088
4089 static void
4090 xlate_table_action(struct action_xlate_ctx *ctx,
4091                    uint16_t in_port, uint8_t table_id)
4092 {
4093     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
4094         struct ofproto_dpif *ofproto = ctx->ofproto;
4095         struct rule_dpif *rule;
4096         uint16_t old_in_port;
4097         uint8_t old_table_id;
4098
4099         old_table_id = ctx->table_id;
4100         ctx->table_id = table_id;
4101
4102         /* Look up a flow with 'in_port' as the input port. */
4103         old_in_port = ctx->flow.in_port;
4104         ctx->flow.in_port = in_port;
4105         rule = rule_dpif_lookup(ofproto, &ctx->flow, table_id);
4106
4107         /* Tag the flow. */
4108         if (table_id > 0 && table_id < N_TABLES) {
4109             struct table_dpif *table = &ofproto->tables[table_id];
4110             if (table->other_table) {
4111                 ctx->tags |= (rule
4112                               ? rule->tag
4113                               : rule_calculate_tag(&ctx->flow,
4114                                                    &table->other_table->wc,
4115                                                    table->basis));
4116             }
4117         }
4118
4119         /* Restore the original input port.  Otherwise OFPP_NORMAL and
4120          * OFPP_IN_PORT will have surprising behavior. */
4121         ctx->flow.in_port = old_in_port;
4122
4123         if (ctx->resubmit_hook) {
4124             ctx->resubmit_hook(ctx, rule);
4125         }
4126
4127         if (rule) {
4128             ctx->recurse++;
4129             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
4130             ctx->recurse--;
4131         }
4132
4133         ctx->table_id = old_table_id;
4134     } else {
4135         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
4136
4137         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
4138                     MAX_RESUBMIT_RECURSION);
4139     }
4140 }
4141
4142 static void
4143 xlate_resubmit_table(struct action_xlate_ctx *ctx,
4144                      const struct nx_action_resubmit *nar)
4145 {
4146     uint16_t in_port;
4147     uint8_t table_id;
4148
4149     in_port = (nar->in_port == htons(OFPP_IN_PORT)
4150                ? ctx->flow.in_port
4151                : ntohs(nar->in_port));
4152     table_id = nar->table == 255 ? ctx->table_id : nar->table;
4153
4154     xlate_table_action(ctx, in_port, table_id);
4155 }
4156
4157 static void
4158 flood_packets(struct action_xlate_ctx *ctx, bool all)
4159 {
4160     struct ofport_dpif *ofport;
4161
4162     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
4163         uint16_t ofp_port = ofport->up.ofp_port;
4164
4165         if (ofp_port == ctx->flow.in_port) {
4166             continue;
4167         }
4168
4169         if (all) {
4170             compose_output_action__(ctx, ofp_port, false);
4171         } else if (!(ofport->up.opp.config & htonl(OFPPC_NO_FLOOD))) {
4172             compose_output_action(ctx, ofp_port);
4173         }
4174     }
4175
4176     ctx->nf_output_iface = NF_OUT_FLOOD;
4177 }
4178
4179 static void
4180 compose_controller_action(struct action_xlate_ctx *ctx, int len)
4181 {
4182     struct user_action_cookie cookie;
4183
4184     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
4185     cookie.type = USER_ACTION_COOKIE_CONTROLLER;
4186     cookie.data = len;
4187     cookie.n_output = 0;
4188     cookie.vlan_tci = 0;
4189     put_userspace_action(ctx->ofproto, ctx->odp_actions, &ctx->flow, &cookie);
4190 }
4191
4192 static void
4193 xlate_output_action__(struct action_xlate_ctx *ctx,
4194                       uint16_t port, uint16_t max_len)
4195 {
4196     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
4197
4198     ctx->nf_output_iface = NF_OUT_DROP;
4199
4200     switch (port) {
4201     case OFPP_IN_PORT:
4202         compose_output_action(ctx, ctx->flow.in_port);
4203         break;
4204     case OFPP_TABLE:
4205         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
4206         break;
4207     case OFPP_NORMAL:
4208         xlate_normal(ctx);
4209         break;
4210     case OFPP_FLOOD:
4211         flood_packets(ctx,  false);
4212         break;
4213     case OFPP_ALL:
4214         flood_packets(ctx, true);
4215         break;
4216     case OFPP_CONTROLLER:
4217         compose_controller_action(ctx, max_len);
4218         break;
4219     case OFPP_LOCAL:
4220         compose_output_action(ctx, OFPP_LOCAL);
4221         break;
4222     case OFPP_NONE:
4223         break;
4224     default:
4225         if (port != ctx->flow.in_port) {
4226             compose_output_action(ctx, port);
4227         }
4228         break;
4229     }
4230
4231     if (prev_nf_output_iface == NF_OUT_FLOOD) {
4232         ctx->nf_output_iface = NF_OUT_FLOOD;
4233     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
4234         ctx->nf_output_iface = prev_nf_output_iface;
4235     } else if (prev_nf_output_iface != NF_OUT_DROP &&
4236                ctx->nf_output_iface != NF_OUT_FLOOD) {
4237         ctx->nf_output_iface = NF_OUT_MULTI;
4238     }
4239 }
4240
4241 static void
4242 xlate_output_reg_action(struct action_xlate_ctx *ctx,
4243                         const struct nx_action_output_reg *naor)
4244 {
4245     uint64_t ofp_port;
4246
4247     ofp_port = nxm_read_field_bits(naor->src, naor->ofs_nbits, &ctx->flow);
4248
4249     if (ofp_port <= UINT16_MAX) {
4250         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
4251     }
4252 }
4253
4254 static void
4255 xlate_output_action(struct action_xlate_ctx *ctx,
4256                     const struct ofp_action_output *oao)
4257 {
4258     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
4259 }
4260
4261 static void
4262 xlate_enqueue_action(struct action_xlate_ctx *ctx,
4263                      const struct ofp_action_enqueue *oae)
4264 {
4265     uint16_t ofp_port;
4266     uint32_t flow_priority, priority;
4267     int error;
4268
4269     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
4270                                    &priority);
4271     if (error) {
4272         /* Fall back to ordinary output action. */
4273         xlate_output_action__(ctx, ntohs(oae->port), 0);
4274         return;
4275     }
4276
4277     /* Figure out datapath output port. */
4278     ofp_port = ntohs(oae->port);
4279     if (ofp_port == OFPP_IN_PORT) {
4280         ofp_port = ctx->flow.in_port;
4281     } else if (ofp_port == ctx->flow.in_port) {
4282         return;
4283     }
4284
4285     /* Add datapath actions. */
4286     flow_priority = ctx->flow.priority;
4287     ctx->flow.priority = priority;
4288     compose_output_action(ctx, ofp_port);
4289     ctx->flow.priority = flow_priority;
4290
4291     /* Update NetFlow output port. */
4292     if (ctx->nf_output_iface == NF_OUT_DROP) {
4293         ctx->nf_output_iface = ofp_port;
4294     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
4295         ctx->nf_output_iface = NF_OUT_MULTI;
4296     }
4297 }
4298
4299 static void
4300 xlate_set_queue_action(struct action_xlate_ctx *ctx,
4301                        const struct nx_action_set_queue *nasq)
4302 {
4303     uint32_t priority;
4304     int error;
4305
4306     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
4307                                    &priority);
4308     if (error) {
4309         /* Couldn't translate queue to a priority, so ignore.  A warning
4310          * has already been logged. */
4311         return;
4312     }
4313
4314     ctx->flow.priority = priority;
4315 }
4316
4317 struct xlate_reg_state {
4318     ovs_be16 vlan_tci;
4319     ovs_be64 tun_id;
4320 };
4321
4322 static void
4323 xlate_autopath(struct action_xlate_ctx *ctx,
4324                const struct nx_action_autopath *naa)
4325 {
4326     uint16_t ofp_port = ntohl(naa->id);
4327     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
4328
4329     if (!port || !port->bundle) {
4330         ofp_port = OFPP_NONE;
4331     } else if (port->bundle->bond) {
4332         /* Autopath does not support VLAN hashing. */
4333         struct ofport_dpif *slave = bond_choose_output_slave(
4334             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
4335         if (slave) {
4336             ofp_port = slave->up.ofp_port;
4337         }
4338     }
4339     autopath_execute(naa, &ctx->flow, ofp_port);
4340 }
4341
4342 static bool
4343 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
4344 {
4345     struct ofproto_dpif *ofproto = ofproto_;
4346     struct ofport_dpif *port;
4347
4348     switch (ofp_port) {
4349     case OFPP_IN_PORT:
4350     case OFPP_TABLE:
4351     case OFPP_NORMAL:
4352     case OFPP_FLOOD:
4353     case OFPP_ALL:
4354     case OFPP_NONE:
4355         return true;
4356     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
4357         return false;
4358     default:
4359         port = get_ofp_port(ofproto, ofp_port);
4360         return port ? port->may_enable : false;
4361     }
4362 }
4363
4364 static void
4365 xlate_learn_action(struct action_xlate_ctx *ctx,
4366                    const struct nx_action_learn *learn)
4367 {
4368     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
4369     struct ofputil_flow_mod fm;
4370     int error;
4371
4372     learn_execute(learn, &ctx->flow, &fm);
4373
4374     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
4375     if (error && !VLOG_DROP_WARN(&rl)) {
4376         char *msg = ofputil_error_to_string(error);
4377         VLOG_WARN("learning action failed to modify flow table (%s)", msg);
4378         free(msg);
4379     }
4380
4381     free(fm.actions);
4382 }
4383
4384 static bool
4385 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
4386 {
4387     if (port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
4388                                ? htonl(OFPPC_NO_RECV_STP)
4389                                : htonl(OFPPC_NO_RECV))) {
4390         return false;
4391     }
4392
4393     /* Only drop packets here if both forwarding and learning are
4394      * disabled.  If just learning is enabled, we need to have
4395      * OFPP_NORMAL and the learning action have a look at the packet
4396      * before we can drop it. */
4397     if (!stp_forward_in_state(port->stp_state)
4398             && !stp_learn_in_state(port->stp_state)) {
4399         return false;
4400     }
4401
4402     return true;
4403 }
4404
4405 static void
4406 do_xlate_actions(const union ofp_action *in, size_t n_in,
4407                  struct action_xlate_ctx *ctx)
4408 {
4409     const struct ofport_dpif *port;
4410     const union ofp_action *ia;
4411     size_t left;
4412
4413     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
4414     if (port && !may_receive(port, ctx)) {
4415         /* Drop this flow. */
4416         return;
4417     }
4418
4419     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
4420         const struct ofp_action_dl_addr *oada;
4421         const struct nx_action_resubmit *nar;
4422         const struct nx_action_set_tunnel *nast;
4423         const struct nx_action_set_queue *nasq;
4424         const struct nx_action_multipath *nam;
4425         const struct nx_action_autopath *naa;
4426         const struct nx_action_bundle *nab;
4427         const struct nx_action_output_reg *naor;
4428         enum ofputil_action_code code;
4429         ovs_be64 tun_id;
4430
4431         if (ctx->exit) {
4432             break;
4433         }
4434
4435         code = ofputil_decode_action_unsafe(ia);
4436         switch (code) {
4437         case OFPUTIL_OFPAT_OUTPUT:
4438             xlate_output_action(ctx, &ia->output);
4439             break;
4440
4441         case OFPUTIL_OFPAT_SET_VLAN_VID:
4442             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
4443             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
4444             break;
4445
4446         case OFPUTIL_OFPAT_SET_VLAN_PCP:
4447             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
4448             ctx->flow.vlan_tci |= htons(
4449                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
4450             break;
4451
4452         case OFPUTIL_OFPAT_STRIP_VLAN:
4453             ctx->flow.vlan_tci = htons(0);
4454             break;
4455
4456         case OFPUTIL_OFPAT_SET_DL_SRC:
4457             oada = ((struct ofp_action_dl_addr *) ia);
4458             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
4459             break;
4460
4461         case OFPUTIL_OFPAT_SET_DL_DST:
4462             oada = ((struct ofp_action_dl_addr *) ia);
4463             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
4464             break;
4465
4466         case OFPUTIL_OFPAT_SET_NW_SRC:
4467             ctx->flow.nw_src = ia->nw_addr.nw_addr;
4468             break;
4469
4470         case OFPUTIL_OFPAT_SET_NW_DST:
4471             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
4472             break;
4473
4474         case OFPUTIL_OFPAT_SET_NW_TOS:
4475             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
4476             ctx->flow.nw_tos |= ia->nw_tos.nw_tos & IP_DSCP_MASK;
4477             break;
4478
4479         case OFPUTIL_OFPAT_SET_TP_SRC:
4480             ctx->flow.tp_src = ia->tp_port.tp_port;
4481             break;
4482
4483         case OFPUTIL_OFPAT_SET_TP_DST:
4484             ctx->flow.tp_dst = ia->tp_port.tp_port;
4485             break;
4486
4487         case OFPUTIL_OFPAT_ENQUEUE:
4488             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
4489             break;
4490
4491         case OFPUTIL_NXAST_RESUBMIT:
4492             nar = (const struct nx_action_resubmit *) ia;
4493             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
4494             break;
4495
4496         case OFPUTIL_NXAST_RESUBMIT_TABLE:
4497             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
4498             break;
4499
4500         case OFPUTIL_NXAST_SET_TUNNEL:
4501             nast = (const struct nx_action_set_tunnel *) ia;
4502             tun_id = htonll(ntohl(nast->tun_id));
4503             ctx->flow.tun_id = tun_id;
4504             break;
4505
4506         case OFPUTIL_NXAST_SET_QUEUE:
4507             nasq = (const struct nx_action_set_queue *) ia;
4508             xlate_set_queue_action(ctx, nasq);
4509             break;
4510
4511         case OFPUTIL_NXAST_POP_QUEUE:
4512             ctx->flow.priority = ctx->original_priority;
4513             break;
4514
4515         case OFPUTIL_NXAST_REG_MOVE:
4516             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
4517                                  &ctx->flow);
4518             break;
4519
4520         case OFPUTIL_NXAST_REG_LOAD:
4521             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
4522                                  &ctx->flow);
4523             break;
4524
4525         case OFPUTIL_NXAST_NOTE:
4526             /* Nothing to do. */
4527             break;
4528
4529         case OFPUTIL_NXAST_SET_TUNNEL64:
4530             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
4531             ctx->flow.tun_id = tun_id;
4532             break;
4533
4534         case OFPUTIL_NXAST_MULTIPATH:
4535             nam = (const struct nx_action_multipath *) ia;
4536             multipath_execute(nam, &ctx->flow);
4537             break;
4538
4539         case OFPUTIL_NXAST_AUTOPATH:
4540             naa = (const struct nx_action_autopath *) ia;
4541             xlate_autopath(ctx, naa);
4542             break;
4543
4544         case OFPUTIL_NXAST_BUNDLE:
4545             ctx->ofproto->has_bundle_action = true;
4546             nab = (const struct nx_action_bundle *) ia;
4547             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
4548                                                       slave_enabled_cb,
4549                                                       ctx->ofproto), 0);
4550             break;
4551
4552         case OFPUTIL_NXAST_BUNDLE_LOAD:
4553             ctx->ofproto->has_bundle_action = true;
4554             nab = (const struct nx_action_bundle *) ia;
4555             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
4556                                 ctx->ofproto);
4557             break;
4558
4559         case OFPUTIL_NXAST_OUTPUT_REG:
4560             naor = (const struct nx_action_output_reg *) ia;
4561             xlate_output_reg_action(ctx, naor);
4562             break;
4563
4564         case OFPUTIL_NXAST_LEARN:
4565             ctx->has_learn = true;
4566             if (ctx->may_learn) {
4567                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
4568             }
4569             break;
4570
4571         case OFPUTIL_NXAST_EXIT:
4572             ctx->exit = true;
4573             break;
4574         }
4575     }
4576
4577     /* We've let OFPP_NORMAL and the learning action look at the packet,
4578      * so drop it now if forwarding is disabled. */
4579     if (port && !stp_forward_in_state(port->stp_state)) {
4580         ofpbuf_clear(ctx->odp_actions);
4581         add_sflow_action(ctx);
4582     }
4583 }
4584
4585 static void
4586 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
4587                       struct ofproto_dpif *ofproto, const struct flow *flow,
4588                       ovs_be16 initial_tci, const struct ofpbuf *packet)
4589 {
4590     ctx->ofproto = ofproto;
4591     ctx->flow = *flow;
4592     ctx->base_flow = ctx->flow;
4593     ctx->base_flow.tun_id = 0;
4594     ctx->base_flow.vlan_tci = initial_tci;
4595     ctx->packet = packet;
4596     ctx->may_learn = packet != NULL;
4597     ctx->resubmit_hook = NULL;
4598 }
4599
4600 static struct ofpbuf *
4601 xlate_actions(struct action_xlate_ctx *ctx,
4602               const union ofp_action *in, size_t n_in)
4603 {
4604     struct flow orig_flow = ctx->flow;
4605
4606     COVERAGE_INC(ofproto_dpif_xlate);
4607
4608     ctx->odp_actions = ofpbuf_new(512);
4609     ofpbuf_reserve(ctx->odp_actions, NL_A_U32_SIZE);
4610     ctx->tags = 0;
4611     ctx->may_set_up_flow = true;
4612     ctx->has_learn = false;
4613     ctx->has_normal = false;
4614     ctx->nf_output_iface = NF_OUT_DROP;
4615     ctx->mirrors = 0;
4616     ctx->recurse = 0;
4617     ctx->original_priority = ctx->flow.priority;
4618     ctx->table_id = 0;
4619     ctx->exit = false;
4620
4621     if (ctx->flow.nw_frag & FLOW_NW_FRAG_ANY) {
4622         switch (ctx->ofproto->up.frag_handling) {
4623         case OFPC_FRAG_NORMAL:
4624             /* We must pretend that transport ports are unavailable. */
4625             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
4626             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
4627             break;
4628
4629         case OFPC_FRAG_DROP:
4630             return ctx->odp_actions;
4631
4632         case OFPC_FRAG_REASM:
4633             NOT_REACHED();
4634
4635         case OFPC_FRAG_NX_MATCH:
4636             /* Nothing to do. */
4637             break;
4638         }
4639     }
4640
4641     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
4642         ctx->may_set_up_flow = false;
4643         return ctx->odp_actions;
4644     } else {
4645         add_sflow_action(ctx);
4646         do_xlate_actions(in, n_in, ctx);
4647
4648         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
4649                                      ctx->odp_actions->data,
4650                                      ctx->odp_actions->size)) {
4651             ctx->may_set_up_flow = false;
4652             if (ctx->packet
4653                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
4654                                        ctx->packet)) {
4655                 compose_output_action(ctx, OFPP_LOCAL);
4656             }
4657         }
4658         add_mirror_actions(ctx, &orig_flow);
4659         fix_sflow_action(ctx);
4660     }
4661
4662     return ctx->odp_actions;
4663 }
4664 \f
4665 /* OFPP_NORMAL implementation. */
4666
4667 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
4668
4669 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
4670  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
4671  * the bundle on which the packet was received, returns the VLAN to which the
4672  * packet belongs.
4673  *
4674  * Both 'vid' and the return value are in the range 0...4095. */
4675 static uint16_t
4676 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
4677 {
4678     switch (in_bundle->vlan_mode) {
4679     case PORT_VLAN_ACCESS:
4680         return in_bundle->vlan;
4681         break;
4682
4683     case PORT_VLAN_TRUNK:
4684         return vid;
4685
4686     case PORT_VLAN_NATIVE_UNTAGGED:
4687     case PORT_VLAN_NATIVE_TAGGED:
4688         return vid ? vid : in_bundle->vlan;
4689
4690     default:
4691         NOT_REACHED();
4692     }
4693 }
4694
4695 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
4696  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
4697  * a warning.
4698  *
4699  * 'vid' should be the VID obtained from the 802.1Q header that was received as
4700  * part of a packet (specify 0 if there was no 802.1Q header), in the range
4701  * 0...4095. */
4702 static bool
4703 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
4704 {
4705     switch (in_bundle->vlan_mode) {
4706     case PORT_VLAN_ACCESS:
4707         if (vid) {
4708             if (warn) {
4709                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4710                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
4711                              "packet received on port %s configured as VLAN "
4712                              "%"PRIu16" access port",
4713                              in_bundle->ofproto->up.name, vid,
4714                              in_bundle->name, in_bundle->vlan);
4715             }
4716             return false;
4717         }
4718         return true;
4719
4720     case PORT_VLAN_NATIVE_UNTAGGED:
4721     case PORT_VLAN_NATIVE_TAGGED:
4722         if (!vid) {
4723             /* Port must always carry its native VLAN. */
4724             return true;
4725         }
4726         /* Fall through. */
4727     case PORT_VLAN_TRUNK:
4728         if (!ofbundle_includes_vlan(in_bundle, vid)) {
4729             if (warn) {
4730                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4731                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
4732                              "received on port %s not configured for trunking "
4733                              "VLAN %"PRIu16,
4734                              in_bundle->ofproto->up.name, vid,
4735                              in_bundle->name, vid);
4736             }
4737             return false;
4738         }
4739         return true;
4740
4741     default:
4742         NOT_REACHED();
4743     }
4744
4745 }
4746
4747 /* Given 'vlan', the VLAN that a packet belongs to, and
4748  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
4749  * that should be included in the 802.1Q header.  (If the return value is 0,
4750  * then the 802.1Q header should only be included in the packet if there is a
4751  * nonzero PCP.)
4752  *
4753  * Both 'vlan' and the return value are in the range 0...4095. */
4754 static uint16_t
4755 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
4756 {
4757     switch (out_bundle->vlan_mode) {
4758     case PORT_VLAN_ACCESS:
4759         return 0;
4760
4761     case PORT_VLAN_TRUNK:
4762     case PORT_VLAN_NATIVE_TAGGED:
4763         return vlan;
4764
4765     case PORT_VLAN_NATIVE_UNTAGGED:
4766         return vlan == out_bundle->vlan ? 0 : vlan;
4767
4768     default:
4769         NOT_REACHED();
4770     }
4771 }
4772
4773 static void
4774 output_normal(struct action_xlate_ctx *ctx, const struct ofbundle *out_bundle,
4775               uint16_t vlan)
4776 {
4777     struct ofport_dpif *port;
4778     uint16_t vid;
4779     ovs_be16 tci, old_tci;
4780
4781     vid = output_vlan_to_vid(out_bundle, vlan);
4782     if (!out_bundle->bond) {
4783         port = ofbundle_get_a_port(out_bundle);
4784     } else {
4785         port = bond_choose_output_slave(out_bundle->bond, &ctx->flow,
4786                                         vid, &ctx->tags);
4787         if (!port) {
4788             /* No slaves enabled, so drop packet. */
4789             return;
4790         }
4791     }
4792
4793     old_tci = ctx->flow.vlan_tci;
4794     tci = htons(vid);
4795     if (tci || out_bundle->use_priority_tags) {
4796         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
4797         if (tci) {
4798             tci |= htons(VLAN_CFI);
4799         }
4800     }
4801     ctx->flow.vlan_tci = tci;
4802
4803     compose_output_action(ctx, port->up.ofp_port);
4804     ctx->flow.vlan_tci = old_tci;
4805 }
4806
4807 static int
4808 mirror_mask_ffs(mirror_mask_t mask)
4809 {
4810     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
4811     return ffs(mask);
4812 }
4813
4814 static bool
4815 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
4816 {
4817     return (bundle->vlan_mode != PORT_VLAN_ACCESS
4818             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
4819 }
4820
4821 static bool
4822 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
4823 {
4824     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
4825 }
4826
4827 /* Returns an arbitrary interface within 'bundle'. */
4828 static struct ofport_dpif *
4829 ofbundle_get_a_port(const struct ofbundle *bundle)
4830 {
4831     return CONTAINER_OF(list_front(&bundle->ports),
4832                         struct ofport_dpif, bundle_node);
4833 }
4834
4835 static bool
4836 vlan_is_mirrored(const struct ofmirror *m, int vlan)
4837 {
4838     return !m->vlans || bitmap_is_set(m->vlans, vlan);
4839 }
4840
4841 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
4842  * to a VLAN.  In general most packets may be mirrored but we want to drop
4843  * protocols that may confuse switches. */
4844 static bool
4845 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
4846 {
4847     /* If you change this function's behavior, please update corresponding
4848      * documentation in vswitch.xml at the same time. */
4849     if (dst[0] != 0x01) {
4850         /* All the currently banned MACs happen to start with 01 currently, so
4851          * this is a quick way to eliminate most of the good ones. */
4852     } else {
4853         if (eth_addr_is_reserved(dst)) {
4854             /* Drop STP, IEEE pause frames, and other reserved protocols
4855              * (01-80-c2-00-00-0x). */
4856             return false;
4857         }
4858
4859         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
4860             /* Cisco OUI. */
4861             if ((dst[3] & 0xfe) == 0xcc &&
4862                 (dst[4] & 0xfe) == 0xcc &&
4863                 (dst[5] & 0xfe) == 0xcc) {
4864                 /* Drop the following protocols plus others following the same
4865                    pattern:
4866
4867                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
4868                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
4869                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
4870                 return false;
4871             }
4872
4873             if (!(dst[3] | dst[4] | dst[5])) {
4874                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
4875                 return false;
4876             }
4877         }
4878     }
4879     return true;
4880 }
4881
4882 static void
4883 add_mirror_actions(struct action_xlate_ctx *ctx, const struct flow *orig_flow)
4884 {
4885     struct ofproto_dpif *ofproto = ctx->ofproto;
4886     mirror_mask_t mirrors;
4887     struct ofport_dpif *in_port;
4888     struct ofbundle *in_bundle;
4889     uint16_t vlan;
4890     uint16_t vid;
4891     const struct nlattr *a;
4892     size_t left;
4893
4894     /* Obtain in_port from orig_flow.in_port.
4895      *
4896      * lookup_input_bundle() also ensures that in_port belongs to a bundle. */
4897     in_port = lookup_input_bundle(ctx->ofproto, orig_flow->in_port,
4898                                   ctx->packet != NULL);
4899     if (!in_port) {
4900         return;
4901     }
4902     in_bundle = in_port->bundle;
4903     mirrors = in_bundle->src_mirrors;
4904
4905     /* Drop frames on bundles reserved for mirroring. */
4906     if (in_bundle->mirror_out) {
4907         if (ctx->packet != NULL) {
4908             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4909             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
4910                          "%s, which is reserved exclusively for mirroring",
4911                          ctx->ofproto->up.name, in_bundle->name);
4912         }
4913         return;
4914     }
4915
4916     /* Check VLAN. */
4917     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
4918     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
4919         return;
4920     }
4921     vlan = input_vid_to_vlan(in_bundle, vid);
4922
4923     /* Look at the output ports to check for destination selections. */
4924
4925     NL_ATTR_FOR_EACH (a, left, ctx->odp_actions->data,
4926                       ctx->odp_actions->size) {
4927         enum ovs_action_attr type = nl_attr_type(a);
4928         struct ofport_dpif *ofport;
4929
4930         if (type != OVS_ACTION_ATTR_OUTPUT) {
4931             continue;
4932         }
4933
4934         ofport = get_odp_port(ofproto, nl_attr_get_u32(a));
4935         mirrors |= ofport ? ofport->bundle->dst_mirrors : 0;
4936     }
4937
4938     if (!mirrors) {
4939         return;
4940     }
4941
4942     /* Restore the original packet before adding the mirror actions. */
4943     ctx->flow = *orig_flow;
4944
4945     while (mirrors) {
4946         struct ofmirror *m;
4947
4948         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
4949
4950         if (!vlan_is_mirrored(m, vlan)) {
4951             mirrors &= mirrors - 1;
4952             continue;
4953         }
4954
4955         mirrors &= ~m->dup_mirrors;
4956         ctx->mirrors |= m->dup_mirrors;
4957         if (m->out) {
4958             output_normal(ctx, m->out, vlan);
4959         } else if (eth_dst_may_rspan(orig_flow->dl_dst)
4960                    && vlan != m->out_vlan) {
4961             struct ofbundle *bundle;
4962
4963             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4964                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
4965                     && !bundle->mirror_out) {
4966                     output_normal(ctx, bundle, m->out_vlan);
4967                 }
4968             }
4969         }
4970     }
4971 }
4972
4973 static void
4974 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
4975                     uint64_t packets, uint64_t bytes)
4976 {
4977     if (!mirrors) {
4978         return;
4979     }
4980
4981     for (; mirrors; mirrors &= mirrors - 1) {
4982         struct ofmirror *m;
4983
4984         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
4985
4986         if (!m) {
4987             /* In normal circumstances 'm' will not be NULL.  However,
4988              * if mirrors are reconfigured, we can temporarily get out
4989              * of sync in facet_revalidate().  We could "correct" the
4990              * mirror list before reaching here, but doing that would
4991              * not properly account the traffic stats we've currently
4992              * accumulated for previous mirror configuration. */
4993             continue;
4994         }
4995
4996         m->packet_count += packets;
4997         m->byte_count += bytes;
4998     }
4999 }
5000
5001 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
5002  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
5003  * indicate this; newer upstream kernels use gratuitous ARP requests. */
5004 static bool
5005 is_gratuitous_arp(const struct flow *flow)
5006 {
5007     return (flow->dl_type == htons(ETH_TYPE_ARP)
5008             && eth_addr_is_broadcast(flow->dl_dst)
5009             && (flow->nw_proto == ARP_OP_REPLY
5010                 || (flow->nw_proto == ARP_OP_REQUEST
5011                     && flow->nw_src == flow->nw_dst)));
5012 }
5013
5014 static void
5015 update_learning_table(struct ofproto_dpif *ofproto,
5016                       const struct flow *flow, int vlan,
5017                       struct ofbundle *in_bundle)
5018 {
5019     struct mac_entry *mac;
5020
5021     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
5022         return;
5023     }
5024
5025     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
5026     if (is_gratuitous_arp(flow)) {
5027         /* We don't want to learn from gratuitous ARP packets that are
5028          * reflected back over bond slaves so we lock the learning table. */
5029         if (!in_bundle->bond) {
5030             mac_entry_set_grat_arp_lock(mac);
5031         } else if (mac_entry_is_grat_arp_locked(mac)) {
5032             return;
5033         }
5034     }
5035
5036     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
5037         /* The log messages here could actually be useful in debugging,
5038          * so keep the rate limit relatively high. */
5039         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5040         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
5041                     "on port %s in VLAN %d",
5042                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
5043                     in_bundle->name, vlan);
5044
5045         mac->port.p = in_bundle;
5046         tag_set_add(&ofproto->revalidate_set,
5047                     mac_learning_changed(ofproto->ml, mac));
5048     }
5049 }
5050
5051 static struct ofport_dpif *
5052 lookup_input_bundle(struct ofproto_dpif *ofproto, uint16_t in_port, bool warn)
5053 {
5054     struct ofport_dpif *ofport;
5055
5056     /* Find the port and bundle for the received packet. */
5057     ofport = get_ofp_port(ofproto, in_port);
5058     if (ofport && ofport->bundle) {
5059         return ofport;
5060     }
5061
5062     /* Odd.  A few possible reasons here:
5063      *
5064      * - We deleted a port but there are still a few packets queued up
5065      *   from it.
5066      *
5067      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
5068      *   we don't know about.
5069      *
5070      * - The ofproto client didn't configure the port as part of a bundle.
5071      */
5072     if (warn) {
5073         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5074
5075         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
5076                      "port %"PRIu16, ofproto->up.name, in_port);
5077     }
5078     return NULL;
5079 }
5080
5081 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
5082  * dropped.  Returns true if they may be forwarded, false if they should be
5083  * dropped.
5084  *
5085  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
5086  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
5087  *
5088  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
5089  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
5090  * checked by input_vid_is_valid().
5091  *
5092  * May also add tags to '*tags', although the current implementation only does
5093  * so in one special case.
5094  */
5095 static bool
5096 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
5097               struct ofport_dpif *in_port, uint16_t vlan, tag_type *tags)
5098 {
5099     struct ofbundle *in_bundle = in_port->bundle;
5100
5101     /* Drop frames for reserved multicast addresses
5102      * only if forward_bpdu option is absent. */
5103     if (eth_addr_is_reserved(flow->dl_dst) && !ofproto->up.forward_bpdu) {
5104         return false;
5105     }
5106
5107     if (in_bundle->bond) {
5108         struct mac_entry *mac;
5109
5110         switch (bond_check_admissibility(in_bundle->bond, in_port,
5111                                          flow->dl_dst, tags)) {
5112         case BV_ACCEPT:
5113             break;
5114
5115         case BV_DROP:
5116             return false;
5117
5118         case BV_DROP_IF_MOVED:
5119             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
5120             if (mac && mac->port.p != in_bundle &&
5121                 (!is_gratuitous_arp(flow)
5122                  || mac_entry_is_grat_arp_locked(mac))) {
5123                 return false;
5124             }
5125             break;
5126         }
5127     }
5128
5129     return true;
5130 }
5131
5132 static void
5133 xlate_normal(struct action_xlate_ctx *ctx)
5134 {
5135     struct ofport_dpif *in_port;
5136     struct ofbundle *in_bundle;
5137     struct mac_entry *mac;
5138     uint16_t vlan;
5139     uint16_t vid;
5140
5141     ctx->has_normal = true;
5142
5143     /* Obtain in_port from ctx->flow.in_port.
5144      *
5145      * lookup_input_bundle() also ensures that in_port belongs to a bundle. */
5146     in_port = lookup_input_bundle(ctx->ofproto, ctx->flow.in_port,
5147                                   ctx->packet != NULL);
5148     if (!in_port) {
5149         return;
5150     }
5151     in_bundle = in_port->bundle;
5152
5153     /* Drop malformed frames. */
5154     if (ctx->flow.dl_type == htons(ETH_TYPE_VLAN) &&
5155         !(ctx->flow.vlan_tci & htons(VLAN_CFI))) {
5156         if (ctx->packet != NULL) {
5157             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5158             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
5159                          "VLAN tag received on port %s",
5160                          ctx->ofproto->up.name, in_bundle->name);
5161         }
5162         return;
5163     }
5164
5165     /* Drop frames on bundles reserved for mirroring. */
5166     if (in_bundle->mirror_out) {
5167         if (ctx->packet != NULL) {
5168             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5169             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
5170                          "%s, which is reserved exclusively for mirroring",
5171                          ctx->ofproto->up.name, in_bundle->name);
5172         }
5173         return;
5174     }
5175
5176     /* Check VLAN. */
5177     vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
5178     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
5179         return;
5180     }
5181     vlan = input_vid_to_vlan(in_bundle, vid);
5182
5183     /* Check other admissibility requirements. */
5184     if (!is_admissible(ctx->ofproto, &ctx->flow, in_port, vlan, &ctx->tags)) {
5185         return;
5186     }
5187
5188     /* Learn source MAC. */
5189     if (ctx->may_learn) {
5190         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
5191     }
5192
5193     /* Determine output bundle. */
5194     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
5195                               &ctx->tags);
5196     if (mac) {
5197         if (mac->port.p != in_bundle) {
5198             output_normal(ctx, mac->port.p, vlan);
5199         }
5200     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
5201         /* If we are revalidating but don't have a learning entry then eject
5202          * the flow.  Installing a flow that floods packets opens up a window
5203          * of time where we could learn from a packet reflected on a bond and
5204          * blackhole packets before the learning table is updated to reflect
5205          * the correct port. */
5206         ctx->may_set_up_flow = false;
5207         return;
5208     } else {
5209         struct ofbundle *bundle;
5210
5211         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
5212             if (bundle != in_bundle
5213                 && ofbundle_includes_vlan(bundle, vlan)
5214                 && bundle->floodable
5215                 && !bundle->mirror_out) {
5216                 output_normal(ctx, bundle, vlan);
5217             }
5218         }
5219         ctx->nf_output_iface = NF_OUT_FLOOD;
5220     }
5221 }
5222 \f
5223 /* Optimized flow revalidation.
5224  *
5225  * It's a difficult problem, in general, to tell which facets need to have
5226  * their actions recalculated whenever the OpenFlow flow table changes.  We
5227  * don't try to solve that general problem: for most kinds of OpenFlow flow
5228  * table changes, we recalculate the actions for every facet.  This is
5229  * relatively expensive, but it's good enough if the OpenFlow flow table
5230  * doesn't change very often.
5231  *
5232  * However, we can expect one particular kind of OpenFlow flow table change to
5233  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
5234  * of CPU on revalidating every facet whenever MAC learning modifies the flow
5235  * table, we add a special case that applies to flow tables in which every rule
5236  * has the same form (that is, the same wildcards), except that the table is
5237  * also allowed to have a single "catch-all" flow that matches all packets.  We
5238  * optimize this case by tagging all of the facets that resubmit into the table
5239  * and invalidating the same tag whenever a flow changes in that table.  The
5240  * end result is that we revalidate just the facets that need it (and sometimes
5241  * a few more, but not all of the facets or even all of the facets that
5242  * resubmit to the table modified by MAC learning). */
5243
5244 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
5245  * into an OpenFlow table with the given 'basis'. */
5246 static uint32_t
5247 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
5248                    uint32_t secret)
5249 {
5250     if (flow_wildcards_is_catchall(wc)) {
5251         return 0;
5252     } else {
5253         struct flow tag_flow = *flow;
5254         flow_zero_wildcards(&tag_flow, wc);
5255         return tag_create_deterministic(flow_hash(&tag_flow, secret));
5256     }
5257 }
5258
5259 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
5260  * taggability of that table.
5261  *
5262  * This function must be called after *each* change to a flow table.  If you
5263  * skip calling it on some changes then the pointer comparisons at the end can
5264  * be invalid if you get unlucky.  For example, if a flow removal causes a
5265  * cls_table to be destroyed and then a flow insertion causes a cls_table with
5266  * different wildcards to be created with the same address, then this function
5267  * will incorrectly skip revalidation. */
5268 static void
5269 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
5270 {
5271     struct table_dpif *table = &ofproto->tables[table_id];
5272     const struct classifier *cls = &ofproto->up.tables[table_id];
5273     struct cls_table *catchall, *other;
5274     struct cls_table *t;
5275
5276     catchall = other = NULL;
5277
5278     switch (hmap_count(&cls->tables)) {
5279     case 0:
5280         /* We could tag this OpenFlow table but it would make the logic a
5281          * little harder and it's a corner case that doesn't seem worth it
5282          * yet. */
5283         break;
5284
5285     case 1:
5286     case 2:
5287         HMAP_FOR_EACH (t, hmap_node, &cls->tables) {
5288             if (cls_table_is_catchall(t)) {
5289                 catchall = t;
5290             } else if (!other) {
5291                 other = t;
5292             } else {
5293                 /* Indicate that we can't tag this by setting both tables to
5294                  * NULL.  (We know that 'catchall' is already NULL.) */
5295                 other = NULL;
5296             }
5297         }
5298         break;
5299
5300     default:
5301         /* Can't tag this table. */
5302         break;
5303     }
5304
5305     if (table->catchall_table != catchall || table->other_table != other) {
5306         table->catchall_table = catchall;
5307         table->other_table = other;
5308         ofproto->need_revalidate = true;
5309     }
5310 }
5311
5312 /* Given 'rule' that has changed in some way (either it is a rule being
5313  * inserted, a rule being deleted, or a rule whose actions are being
5314  * modified), marks facets for revalidation to ensure that packets will be
5315  * forwarded correctly according to the new state of the flow table.
5316  *
5317  * This function must be called after *each* change to a flow table.  See
5318  * the comment on table_update_taggable() for more information. */
5319 static void
5320 rule_invalidate(const struct rule_dpif *rule)
5321 {
5322     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5323
5324     table_update_taggable(ofproto, rule->up.table_id);
5325
5326     if (!ofproto->need_revalidate) {
5327         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5328
5329         if (table->other_table && rule->tag) {
5330             tag_set_add(&ofproto->revalidate_set, rule->tag);
5331         } else {
5332             ofproto->need_revalidate = true;
5333         }
5334     }
5335 }
5336 \f
5337 static bool
5338 set_frag_handling(struct ofproto *ofproto_,
5339                   enum ofp_config_flags frag_handling)
5340 {
5341     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5342
5343     if (frag_handling != OFPC_FRAG_REASM) {
5344         ofproto->need_revalidate = true;
5345         return true;
5346     } else {
5347         return false;
5348     }
5349 }
5350
5351 static int
5352 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5353            const struct flow *flow,
5354            const union ofp_action *ofp_actions, size_t n_ofp_actions)
5355 {
5356     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5357     int error;
5358
5359     if (flow->in_port >= ofproto->max_ports && flow->in_port < OFPP_MAX) {
5360         return ofp_mkerr_nicira(OFPET_BAD_REQUEST, NXBRC_BAD_IN_PORT);
5361     }
5362
5363     error = validate_actions(ofp_actions, n_ofp_actions, flow,
5364                              ofproto->max_ports);
5365     if (!error) {
5366         struct odputil_keybuf keybuf;
5367         struct action_xlate_ctx ctx;
5368         struct ofpbuf *odp_actions;
5369         struct ofpbuf key;
5370
5371         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5372         odp_flow_key_from_flow(&key, flow);
5373
5374         action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, packet);
5375         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
5376         dpif_execute(ofproto->dpif, key.data, key.size,
5377                      odp_actions->data, odp_actions->size, packet);
5378         ofpbuf_delete(odp_actions);
5379     }
5380     return error;
5381 }
5382 \f
5383 /* NetFlow. */
5384
5385 static int
5386 set_netflow(struct ofproto *ofproto_,
5387             const struct netflow_options *netflow_options)
5388 {
5389     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5390
5391     if (netflow_options) {
5392         if (!ofproto->netflow) {
5393             ofproto->netflow = netflow_create();
5394         }
5395         return netflow_set_options(ofproto->netflow, netflow_options);
5396     } else {
5397         netflow_destroy(ofproto->netflow);
5398         ofproto->netflow = NULL;
5399         return 0;
5400     }
5401 }
5402
5403 static void
5404 get_netflow_ids(const struct ofproto *ofproto_,
5405                 uint8_t *engine_type, uint8_t *engine_id)
5406 {
5407     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5408
5409     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
5410 }
5411
5412 static void
5413 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
5414 {
5415     if (!facet_is_controller_flow(facet) &&
5416         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5417         struct subfacet *subfacet;
5418         struct ofexpired expired;
5419
5420         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5421             if (subfacet->installed) {
5422                 struct dpif_flow_stats stats;
5423
5424                 subfacet_install(ofproto, subfacet, subfacet->actions,
5425                                  subfacet->actions_len, &stats);
5426                 subfacet_update_stats(ofproto, subfacet, &stats);
5427             }
5428         }
5429
5430         expired.flow = facet->flow;
5431         expired.packet_count = facet->packet_count;
5432         expired.byte_count = facet->byte_count;
5433         expired.used = facet->used;
5434         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5435     }
5436 }
5437
5438 static void
5439 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
5440 {
5441     struct facet *facet;
5442
5443     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
5444         send_active_timeout(ofproto, facet);
5445     }
5446 }
5447 \f
5448 static struct ofproto_dpif *
5449 ofproto_dpif_lookup(const char *name)
5450 {
5451     struct ofproto *ofproto = ofproto_lookup(name);
5452     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
5453             ? ofproto_dpif_cast(ofproto)
5454             : NULL);
5455 }
5456
5457 static void
5458 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn,
5459                          const char *args, void *aux OVS_UNUSED)
5460 {
5461     const struct ofproto_dpif *ofproto;
5462
5463     ofproto = ofproto_dpif_lookup(args);
5464     if (!ofproto) {
5465         unixctl_command_reply(conn, 501, "no such bridge");
5466         return;
5467     }
5468     mac_learning_flush(ofproto->ml);
5469
5470     unixctl_command_reply(conn, 200, "table successfully flushed");
5471 }
5472
5473 static void
5474 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
5475                          const char *args, void *aux OVS_UNUSED)
5476 {
5477     struct ds ds = DS_EMPTY_INITIALIZER;
5478     const struct ofproto_dpif *ofproto;
5479     const struct mac_entry *e;
5480
5481     ofproto = ofproto_dpif_lookup(args);
5482     if (!ofproto) {
5483         unixctl_command_reply(conn, 501, "no such bridge");
5484         return;
5485     }
5486
5487     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5488     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5489         struct ofbundle *bundle = e->port.p;
5490         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5491                       ofbundle_get_a_port(bundle)->odp_port,
5492                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
5493     }
5494     unixctl_command_reply(conn, 200, ds_cstr(&ds));
5495     ds_destroy(&ds);
5496 }
5497
5498 struct ofproto_trace {
5499     struct action_xlate_ctx ctx;
5500     struct flow flow;
5501     struct ds *result;
5502 };
5503
5504 static void
5505 trace_format_rule(struct ds *result, uint8_t table_id, int level,
5506                   const struct rule_dpif *rule)
5507 {
5508     ds_put_char_multiple(result, '\t', level);
5509     if (!rule) {
5510         ds_put_cstr(result, "No match\n");
5511         return;
5512     }
5513
5514     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5515                   table_id, ntohll(rule->up.flow_cookie));
5516     cls_rule_format(&rule->up.cr, result);
5517     ds_put_char(result, '\n');
5518
5519     ds_put_char_multiple(result, '\t', level);
5520     ds_put_cstr(result, "OpenFlow ");
5521     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
5522     ds_put_char(result, '\n');
5523 }
5524
5525 static void
5526 trace_format_flow(struct ds *result, int level, const char *title,
5527                  struct ofproto_trace *trace)
5528 {
5529     ds_put_char_multiple(result, '\t', level);
5530     ds_put_format(result, "%s: ", title);
5531     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5532         ds_put_cstr(result, "unchanged");
5533     } else {
5534         flow_format(result, &trace->ctx.flow);
5535         trace->flow = trace->ctx.flow;
5536     }
5537     ds_put_char(result, '\n');
5538 }
5539
5540 static void
5541 trace_format_regs(struct ds *result, int level, const char *title,
5542                   struct ofproto_trace *trace)
5543 {
5544     size_t i;
5545
5546     ds_put_char_multiple(result, '\t', level);
5547     ds_put_format(result, "%s:", title);
5548     for (i = 0; i < FLOW_N_REGS; i++) {
5549         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5550     }
5551     ds_put_char(result, '\n');
5552 }
5553
5554 static void
5555 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
5556 {
5557     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5558     struct ds *result = trace->result;
5559
5560     ds_put_char(result, '\n');
5561     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5562     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
5563     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
5564 }
5565
5566 static void
5567 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5568                       void *aux OVS_UNUSED)
5569 {
5570     char *dpname, *arg1, *arg2, *arg3, *arg4;
5571     char *args = xstrdup(args_);
5572     char *save_ptr = NULL;
5573     struct ofproto_dpif *ofproto;
5574     struct ofpbuf odp_key;
5575     struct ofpbuf *packet;
5576     struct rule_dpif *rule;
5577     ovs_be16 initial_tci;
5578     struct ds result;
5579     struct flow flow;
5580     char *s;
5581
5582     packet = NULL;
5583     ofpbuf_init(&odp_key, 0);
5584     ds_init(&result);
5585
5586     dpname = strtok_r(args, " ", &save_ptr);
5587     if (!dpname) {
5588         unixctl_command_reply(conn, 501, "Bad command syntax");
5589         goto exit;
5590     }
5591
5592     ofproto = ofproto_dpif_lookup(dpname);
5593     if (!ofproto) {
5594         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5595                               "for help)");
5596         goto exit;
5597     }
5598     arg1 = strtok_r(NULL, " ", &save_ptr);
5599     arg2 = strtok_r(NULL, " ", &save_ptr);
5600     arg3 = strtok_r(NULL, " ", &save_ptr);
5601     arg4 = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5602     if (dpname && arg1 && (!arg2 || !strcmp(arg2, "-generate")) && !arg3) {
5603         /* ofproto/trace dpname flow [-generate] */
5604         int error;
5605
5606         /* Convert string to datapath key. */
5607         ofpbuf_init(&odp_key, 0);
5608         error = odp_flow_key_from_string(arg1, NULL, &odp_key);
5609         if (error) {
5610             unixctl_command_reply(conn, 501, "Bad flow syntax");
5611             goto exit;
5612         }
5613
5614         /* Convert odp_key to flow. */
5615         error = ofproto_dpif_extract_flow_key(ofproto, odp_key.data,
5616                                               odp_key.size, &flow,
5617                                               &initial_tci);
5618         if (error == ODP_FIT_ERROR) {
5619             unixctl_command_reply(conn, 501, "Invalid flow");
5620             goto exit;
5621         }
5622
5623         /* Generate a packet, if requested. */
5624         if (arg2) {
5625             packet = ofpbuf_new(0);
5626             flow_compose(packet, &flow);
5627         }
5628     } else if (dpname && arg1 && arg2 && arg3 && arg4) {
5629         /* ofproto/trace dpname priority tun_id in_port packet */
5630         uint16_t in_port;
5631         ovs_be64 tun_id;
5632         uint32_t priority;
5633
5634         priority = atoi(arg1);
5635         tun_id = htonll(strtoull(arg2, NULL, 0));
5636         in_port = ofp_port_to_odp_port(atoi(arg3));
5637
5638         packet = ofpbuf_new(strlen(args) / 2);
5639         arg4 = ofpbuf_put_hex(packet, arg4, NULL);
5640         arg4 += strspn(arg4, " ");
5641         if (*arg4 != '\0') {
5642             unixctl_command_reply(conn, 501, "Trailing garbage in command");
5643             goto exit;
5644         }
5645         if (packet->size < ETH_HEADER_LEN) {
5646             unixctl_command_reply(conn, 501,
5647                                   "Packet data too short for Ethernet");
5648             goto exit;
5649         }
5650
5651         ds_put_cstr(&result, "Packet: ");
5652         s = ofp_packet_to_string(packet->data, packet->size, packet->size);
5653         ds_put_cstr(&result, s);
5654         free(s);
5655
5656         flow_extract(packet, priority, tun_id, in_port, &flow);
5657         initial_tci = flow.vlan_tci;
5658     } else {
5659         unixctl_command_reply(conn, 501, "Bad command syntax");
5660         goto exit;
5661     }
5662
5663     ds_put_cstr(&result, "Flow: ");
5664     flow_format(&result, &flow);
5665     ds_put_char(&result, '\n');
5666
5667     rule = rule_dpif_lookup(ofproto, &flow, 0);
5668     trace_format_rule(&result, 0, 0, rule);
5669     if (rule) {
5670         struct ofproto_trace trace;
5671         struct ofpbuf *odp_actions;
5672
5673         trace.result = &result;
5674         trace.flow = flow;
5675         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, initial_tci, packet);
5676         trace.ctx.resubmit_hook = trace_resubmit;
5677         odp_actions = xlate_actions(&trace.ctx,
5678                                     rule->up.actions, rule->up.n_actions);
5679
5680         ds_put_char(&result, '\n');
5681         trace_format_flow(&result, 0, "Final flow", &trace);
5682         ds_put_cstr(&result, "Datapath actions: ");
5683         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5684         ofpbuf_delete(odp_actions);
5685
5686         if (!trace.ctx.may_set_up_flow) {
5687             if (packet) {
5688                 ds_put_cstr(&result, "\nThis flow is not cachable.");
5689             } else {
5690                 ds_put_cstr(&result, "\nThe datapath actions are incomplete--"
5691                             "for complete actions, please supply a packet.");
5692             }
5693         }
5694     }
5695
5696     unixctl_command_reply(conn, 200, ds_cstr(&result));
5697
5698 exit:
5699     ds_destroy(&result);
5700     ofpbuf_delete(packet);
5701     ofpbuf_uninit(&odp_key);
5702     free(args);
5703 }
5704
5705 static void
5706 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED,
5707                   const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5708 {
5709     clogged = true;
5710     unixctl_command_reply(conn, 200, NULL);
5711 }
5712
5713 static void
5714 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED,
5715                     const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5716 {
5717     clogged = false;
5718     unixctl_command_reply(conn, 200, NULL);
5719 }
5720
5721 static void
5722 ofproto_dpif_unixctl_init(void)
5723 {
5724     static bool registered;
5725     if (registered) {
5726         return;
5727     }
5728     registered = true;
5729
5730     unixctl_command_register("ofproto/trace",
5731                       "bridge {tun_id in_port packet | odp_flow [-generate]}",
5732                       ofproto_unixctl_trace, NULL);
5733     unixctl_command_register("fdb/flush", "bridge", ofproto_unixctl_fdb_flush,
5734                              NULL);
5735     unixctl_command_register("fdb/show", "bridge", ofproto_unixctl_fdb_show,
5736                              NULL);
5737     unixctl_command_register("ofproto/clog", "", ofproto_dpif_clog, NULL);
5738     unixctl_command_register("ofproto/unclog", "", ofproto_dpif_unclog, NULL);
5739 }
5740 \f
5741 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5742  *
5743  * This is deprecated.  It is only for compatibility with broken device drivers
5744  * in old versions of Linux that do not properly support VLANs when VLAN
5745  * devices are not used.  When broken device drivers are no longer in
5746  * widespread use, we will delete these interfaces. */
5747
5748 static int
5749 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
5750 {
5751     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
5752     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
5753
5754     if (realdev_ofp_port == ofport->realdev_ofp_port
5755         && vid == ofport->vlandev_vid) {
5756         return 0;
5757     }
5758
5759     ofproto->need_revalidate = true;
5760
5761     if (ofport->realdev_ofp_port) {
5762         vsp_remove(ofport);
5763     }
5764     if (realdev_ofp_port && ofport->bundle) {
5765         /* vlandevs are enslaved to their realdevs, so they are not allowed to
5766          * themselves be part of a bundle. */
5767         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
5768     }
5769
5770     ofport->realdev_ofp_port = realdev_ofp_port;
5771     ofport->vlandev_vid = vid;
5772
5773     if (realdev_ofp_port) {
5774         vsp_add(ofport, realdev_ofp_port, vid);
5775     }
5776
5777     return 0;
5778 }
5779
5780 static uint32_t
5781 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
5782 {
5783     return hash_2words(realdev_ofp_port, vid);
5784 }
5785
5786 static uint32_t
5787 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
5788                        uint32_t realdev_odp_port, ovs_be16 vlan_tci)
5789 {
5790     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
5791         uint16_t realdev_ofp_port = odp_port_to_ofp_port(realdev_odp_port);
5792         int vid = vlan_tci_to_vid(vlan_tci);
5793         const struct vlan_splinter *vsp;
5794
5795         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
5796                                  hash_realdev_vid(realdev_ofp_port, vid),
5797                                  &ofproto->realdev_vid_map) {
5798             if (vsp->realdev_ofp_port == realdev_ofp_port
5799                 && vsp->vid == vid) {
5800                 return ofp_port_to_odp_port(vsp->vlandev_ofp_port);
5801             }
5802         }
5803     }
5804     return realdev_odp_port;
5805 }
5806
5807 static struct vlan_splinter *
5808 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
5809 {
5810     struct vlan_splinter *vsp;
5811
5812     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
5813                              &ofproto->vlandev_map) {
5814         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
5815             return vsp;
5816         }
5817     }
5818
5819     return NULL;
5820 }
5821
5822 static uint16_t
5823 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
5824                    uint16_t vlandev_ofp_port, int *vid)
5825 {
5826     if (!hmap_is_empty(&ofproto->vlandev_map)) {
5827         const struct vlan_splinter *vsp;
5828
5829         vsp = vlandev_find(ofproto, vlandev_ofp_port);
5830         if (vsp) {
5831             if (vid) {
5832                 *vid = vsp->vid;
5833             }
5834             return vsp->realdev_ofp_port;
5835         }
5836     }
5837     return 0;
5838 }
5839
5840 static void
5841 vsp_remove(struct ofport_dpif *port)
5842 {
5843     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5844     struct vlan_splinter *vsp;
5845
5846     vsp = vlandev_find(ofproto, port->up.ofp_port);
5847     if (vsp) {
5848         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
5849         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
5850         free(vsp);
5851
5852         port->realdev_ofp_port = 0;
5853     } else {
5854         VLOG_ERR("missing vlan device record");
5855     }
5856 }
5857
5858 static void
5859 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
5860 {
5861     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5862
5863     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
5864         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
5865             == realdev_ofp_port)) {
5866         struct vlan_splinter *vsp;
5867
5868         vsp = xmalloc(sizeof *vsp);
5869         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
5870                     hash_int(port->up.ofp_port, 0));
5871         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
5872                     hash_realdev_vid(realdev_ofp_port, vid));
5873         vsp->realdev_ofp_port = realdev_ofp_port;
5874         vsp->vlandev_ofp_port = port->up.ofp_port;
5875         vsp->vid = vid;
5876
5877         port->realdev_ofp_port = realdev_ofp_port;
5878     } else {
5879         VLOG_ERR("duplicate vlan device record");
5880     }
5881 }
5882 \f
5883 const struct ofproto_class ofproto_dpif_class = {
5884     enumerate_types,
5885     enumerate_names,
5886     del,
5887     alloc,
5888     construct,
5889     destruct,
5890     dealloc,
5891     run,
5892     run_fast,
5893     wait,
5894     flush,
5895     get_features,
5896     get_tables,
5897     port_alloc,
5898     port_construct,
5899     port_destruct,
5900     port_dealloc,
5901     port_modified,
5902     port_reconfigured,
5903     port_query_by_name,
5904     port_add,
5905     port_del,
5906     port_dump_start,
5907     port_dump_next,
5908     port_dump_done,
5909     port_poll,
5910     port_poll_wait,
5911     port_is_lacp_current,
5912     NULL,                       /* rule_choose_table */
5913     rule_alloc,
5914     rule_construct,
5915     rule_destruct,
5916     rule_dealloc,
5917     rule_get_stats,
5918     rule_execute,
5919     rule_modify_actions,
5920     set_frag_handling,
5921     packet_out,
5922     set_netflow,
5923     get_netflow_ids,
5924     set_sflow,
5925     set_cfm,
5926     get_cfm_fault,
5927     get_cfm_remote_mpids,
5928     set_stp,
5929     get_stp_status,
5930     set_stp_port,
5931     get_stp_port_status,
5932     set_queues,
5933     bundle_set,
5934     bundle_remove,
5935     mirror_set,
5936     mirror_get_stats,
5937     set_flood_vlans,
5938     is_mirror_output_bundle,
5939     forward_bpdu_changed,
5940     set_realdev,
5941 };