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