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