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