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