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