sflow: Use ofproto_port_get_stats().
[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 static void subfacet_destroy(struct ofproto_dpif *, struct subfacet *);
378 static void subfacet_destroy__(struct ofproto_dpif *, struct subfacet *);
379 static void subfacet_reset_dp_stats(struct subfacet *,
380                                     struct dpif_flow_stats *);
381 static void subfacet_update_time(struct ofproto_dpif *, struct subfacet *,
382                                  long long int used);
383 static void subfacet_update_stats(struct ofproto_dpif *, struct subfacet *,
384                                   const struct dpif_flow_stats *);
385 static void subfacet_make_actions(struct ofproto_dpif *, struct subfacet *,
386                                   const struct ofpbuf *packet);
387 static int subfacet_install(struct ofproto_dpif *, struct subfacet *,
388                             const struct nlattr *actions, size_t actions_len,
389                             struct dpif_flow_stats *);
390 static void subfacet_uninstall(struct ofproto_dpif *, struct subfacet *);
391
392 struct ofport_dpif {
393     struct ofport up;
394
395     uint32_t odp_port;
396     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
397     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
398     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
399     tag_type tag;               /* Tag associated with this port. */
400     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
401     bool may_enable;            /* May be enabled in bonds. */
402
403     /* Spanning tree. */
404     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
405     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
406     long long int stp_state_entered;
407
408     struct hmap priorities;     /* Map of attached 'priority_to_dscp's. */
409
410     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
411      *
412      * This is deprecated.  It is only for compatibility with broken device
413      * drivers in old versions of Linux that do not properly support VLANs when
414      * VLAN devices are not used.  When broken device drivers are no longer in
415      * widespread use, we will delete these interfaces. */
416     uint16_t realdev_ofp_port;
417     int vlandev_vid;
418 };
419
420 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
421  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
422  * traffic egressing the 'ofport' with that priority should be marked with. */
423 struct priority_to_dscp {
424     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
425     uint32_t priority;          /* Priority of this queue (see struct flow). */
426
427     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
428 };
429
430 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
431  *
432  * This is deprecated.  It is only for compatibility with broken device drivers
433  * in old versions of Linux that do not properly support VLANs when VLAN
434  * devices are not used.  When broken device drivers are no longer in
435  * widespread use, we will delete these interfaces. */
436 struct vlan_splinter {
437     struct hmap_node realdev_vid_node;
438     struct hmap_node vlandev_node;
439     uint16_t realdev_ofp_port;
440     uint16_t vlandev_ofp_port;
441     int vid;
442 };
443
444 static uint32_t vsp_realdev_to_vlandev(const struct ofproto_dpif *,
445                                        uint32_t realdev, ovs_be16 vlan_tci);
446 static uint16_t vsp_vlandev_to_realdev(const struct ofproto_dpif *,
447                                        uint16_t vlandev, int *vid);
448 static void vsp_remove(struct ofport_dpif *);
449 static void vsp_add(struct ofport_dpif *, uint16_t realdev_ofp_port, int vid);
450
451 static struct ofport_dpif *
452 ofport_dpif_cast(const struct ofport *ofport)
453 {
454     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
455     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
456 }
457
458 static void port_run(struct ofport_dpif *);
459 static void port_wait(struct ofport_dpif *);
460 static int set_cfm(struct ofport *, const struct cfm_settings *);
461 static void ofport_clear_priorities(struct ofport_dpif *);
462
463 struct dpif_completion {
464     struct list list_node;
465     struct ofoperation *op;
466 };
467
468 /* Extra information about a classifier table.
469  * Currently used just for optimized flow revalidation. */
470 struct table_dpif {
471     /* If either of these is nonnull, then this table has a form that allows
472      * flows to be tagged to avoid revalidating most flows for the most common
473      * kinds of flow table changes. */
474     struct cls_table *catchall_table; /* Table that wildcards all fields. */
475     struct cls_table *other_table;    /* Table with any other wildcard set. */
476     uint32_t basis;                   /* Keeps each table's tags separate. */
477 };
478
479 struct ofproto_dpif {
480     struct ofproto up;
481     struct dpif *dpif;
482     int max_ports;
483
484     /* Statistics. */
485     uint64_t n_matches;
486
487     /* Bridging. */
488     struct netflow *netflow;
489     struct dpif_sflow *sflow;
490     struct hmap bundles;        /* Contains "struct ofbundle"s. */
491     struct mac_learning *ml;
492     struct ofmirror *mirrors[MAX_MIRRORS];
493     bool has_bonded_bundles;
494
495     /* Expiration. */
496     struct timer next_expiration;
497
498     /* Facets. */
499     struct hmap facets;
500     struct hmap subfacets;
501
502     /* Revalidation. */
503     struct table_dpif tables[N_TABLES];
504     bool need_revalidate;
505     struct tag_set revalidate_set;
506
507     /* Support for debugging async flow mods. */
508     struct list completions;
509
510     bool has_bundle_action; /* True when the first bundle action appears. */
511     struct netdev_stats stats; /* To account packets generated and consumed in
512                                 * userspace. */
513
514     /* Spanning tree. */
515     struct stp *stp;
516     long long int stp_last_tick;
517
518     /* VLAN splinters. */
519     struct hmap realdev_vid_map; /* (realdev,vid) -> vlandev. */
520     struct hmap vlandev_map;     /* vlandev -> (realdev,vid). */
521 };
522
523 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
524  * for debugging the asynchronous flow_mod implementation.) */
525 static bool clogged;
526
527 static void ofproto_dpif_unixctl_init(void);
528
529 static struct ofproto_dpif *
530 ofproto_dpif_cast(const struct ofproto *ofproto)
531 {
532     assert(ofproto->ofproto_class == &ofproto_dpif_class);
533     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
534 }
535
536 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
537                                         uint16_t ofp_port);
538 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
539                                         uint32_t odp_port);
540
541 /* Packet processing. */
542 static void update_learning_table(struct ofproto_dpif *,
543                                   const struct flow *, int vlan,
544                                   struct ofbundle *);
545 /* Upcalls. */
546 #define FLOW_MISS_MAX_BATCH 50
547 static int handle_upcalls(struct ofproto_dpif *, unsigned int max_batch);
548
549 /* Flow expiration. */
550 static int expire(struct ofproto_dpif *);
551
552 /* NetFlow. */
553 static void send_netflow_active_timeouts(struct ofproto_dpif *);
554
555 /* Utilities. */
556 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
557 static size_t
558 compose_sflow_action(const struct ofproto_dpif *, struct ofpbuf *odp_actions,
559                      const struct flow *, uint32_t odp_port);
560 static void add_mirror_actions(struct action_xlate_ctx *ctx,
561                                const struct flow *flow);
562 /* Global variables. */
563 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
564 \f
565 /* Factory functions. */
566
567 static void
568 enumerate_types(struct sset *types)
569 {
570     dp_enumerate_types(types);
571 }
572
573 static int
574 enumerate_names(const char *type, struct sset *names)
575 {
576     return dp_enumerate_names(type, names);
577 }
578
579 static int
580 del(const char *type, const char *name)
581 {
582     struct dpif *dpif;
583     int error;
584
585     error = dpif_open(name, type, &dpif);
586     if (!error) {
587         error = dpif_delete(dpif);
588         dpif_close(dpif);
589     }
590     return error;
591 }
592 \f
593 /* Basic life-cycle. */
594
595 static struct ofproto *
596 alloc(void)
597 {
598     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
599     return &ofproto->up;
600 }
601
602 static void
603 dealloc(struct ofproto *ofproto_)
604 {
605     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
606     free(ofproto);
607 }
608
609 static int
610 construct(struct ofproto *ofproto_, int *n_tablesp)
611 {
612     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
613     const char *name = ofproto->up.name;
614     int error;
615     int i;
616
617     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
618     if (error) {
619         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
620         return error;
621     }
622
623     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
624     ofproto->n_matches = 0;
625
626     dpif_flow_flush(ofproto->dpif);
627     dpif_recv_purge(ofproto->dpif);
628
629     error = dpif_recv_set_mask(ofproto->dpif,
630                                ((1u << DPIF_UC_MISS) |
631                                 (1u << DPIF_UC_ACTION)));
632     if (error) {
633         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
634         dpif_close(ofproto->dpif);
635         return error;
636     }
637
638     ofproto->netflow = NULL;
639     ofproto->sflow = NULL;
640     ofproto->stp = NULL;
641     hmap_init(&ofproto->bundles);
642     ofproto->ml = mac_learning_create();
643     for (i = 0; i < MAX_MIRRORS; i++) {
644         ofproto->mirrors[i] = NULL;
645     }
646     ofproto->has_bonded_bundles = false;
647
648     timer_set_duration(&ofproto->next_expiration, 1000);
649
650     hmap_init(&ofproto->facets);
651     hmap_init(&ofproto->subfacets);
652
653     for (i = 0; i < N_TABLES; i++) {
654         struct table_dpif *table = &ofproto->tables[i];
655
656         table->catchall_table = NULL;
657         table->other_table = NULL;
658         table->basis = random_uint32();
659     }
660     ofproto->need_revalidate = false;
661     tag_set_init(&ofproto->revalidate_set);
662
663     list_init(&ofproto->completions);
664
665     ofproto_dpif_unixctl_init();
666
667     ofproto->has_bundle_action = false;
668
669     hmap_init(&ofproto->vlandev_map);
670     hmap_init(&ofproto->realdev_vid_map);
671
672     *n_tablesp = N_TABLES;
673     memset(&ofproto->stats, 0, sizeof ofproto->stats);
674     return 0;
675 }
676
677 static void
678 complete_operations(struct ofproto_dpif *ofproto)
679 {
680     struct dpif_completion *c, *next;
681
682     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
683         ofoperation_complete(c->op, 0);
684         list_remove(&c->list_node);
685         free(c);
686     }
687 }
688
689 static void
690 destruct(struct ofproto *ofproto_)
691 {
692     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
693     struct rule_dpif *rule, *next_rule;
694     struct classifier *table;
695     int i;
696
697     complete_operations(ofproto);
698
699     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
700         struct cls_cursor cursor;
701
702         cls_cursor_init(&cursor, table, NULL);
703         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
704             ofproto_rule_destroy(&rule->up);
705         }
706     }
707
708     for (i = 0; i < MAX_MIRRORS; i++) {
709         mirror_destroy(ofproto->mirrors[i]);
710     }
711
712     netflow_destroy(ofproto->netflow);
713     dpif_sflow_destroy(ofproto->sflow);
714     hmap_destroy(&ofproto->bundles);
715     mac_learning_destroy(ofproto->ml);
716
717     hmap_destroy(&ofproto->facets);
718     hmap_destroy(&ofproto->subfacets);
719
720     hmap_destroy(&ofproto->vlandev_map);
721     hmap_destroy(&ofproto->realdev_vid_map);
722
723     dpif_close(ofproto->dpif);
724 }
725
726 static int
727 run_fast(struct ofproto *ofproto_)
728 {
729     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
730     unsigned int work;
731
732     /* Handle one or more batches of upcalls, until there's nothing left to do
733      * or until we do a fixed total amount of work.
734      *
735      * We do work in batches because it can be much cheaper to set up a number
736      * of flows and fire off their patches all at once.  We do multiple batches
737      * because in some cases handling a packet can cause another packet to be
738      * queued almost immediately as part of the return flow.  Both
739      * optimizations can make major improvements on some benchmarks and
740      * presumably for real traffic as well. */
741     work = 0;
742     while (work < FLOW_MISS_MAX_BATCH) {
743         int retval = handle_upcalls(ofproto, FLOW_MISS_MAX_BATCH - work);
744         if (retval <= 0) {
745             return -retval;
746         }
747         work += retval;
748     }
749     return 0;
750 }
751
752 static int
753 run(struct ofproto *ofproto_)
754 {
755     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
756     struct ofport_dpif *ofport;
757     struct ofbundle *bundle;
758     int error;
759
760     if (!clogged) {
761         complete_operations(ofproto);
762     }
763     dpif_run(ofproto->dpif);
764
765     error = run_fast(ofproto_);
766     if (error) {
767         return error;
768     }
769
770     if (timer_expired(&ofproto->next_expiration)) {
771         int delay = expire(ofproto);
772         timer_set_duration(&ofproto->next_expiration, delay);
773     }
774
775     if (ofproto->netflow) {
776         if (netflow_run(ofproto->netflow)) {
777             send_netflow_active_timeouts(ofproto);
778         }
779     }
780     if (ofproto->sflow) {
781         dpif_sflow_run(ofproto->sflow);
782     }
783
784     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
785         port_run(ofport);
786     }
787     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
788         bundle_run(bundle);
789     }
790
791     stp_run(ofproto);
792     mac_learning_run(ofproto->ml, &ofproto->revalidate_set);
793
794     /* Now revalidate if there's anything to do. */
795     if (ofproto->need_revalidate
796         || !tag_set_is_empty(&ofproto->revalidate_set)) {
797         struct tag_set revalidate_set = ofproto->revalidate_set;
798         bool revalidate_all = ofproto->need_revalidate;
799         struct facet *facet, *next;
800
801         /* Clear the revalidation flags. */
802         tag_set_init(&ofproto->revalidate_set);
803         ofproto->need_revalidate = false;
804
805         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &ofproto->facets) {
806             if (revalidate_all
807                 || tag_set_intersects(&revalidate_set, facet->tags)) {
808                 facet_revalidate(ofproto, facet);
809             }
810         }
811     }
812
813     return 0;
814 }
815
816 static void
817 wait(struct ofproto *ofproto_)
818 {
819     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
820     struct ofport_dpif *ofport;
821     struct ofbundle *bundle;
822
823     if (!clogged && !list_is_empty(&ofproto->completions)) {
824         poll_immediate_wake();
825     }
826
827     dpif_wait(ofproto->dpif);
828     dpif_recv_wait(ofproto->dpif);
829     if (ofproto->sflow) {
830         dpif_sflow_wait(ofproto->sflow);
831     }
832     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
833         poll_immediate_wake();
834     }
835     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
836         port_wait(ofport);
837     }
838     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
839         bundle_wait(bundle);
840     }
841     if (ofproto->netflow) {
842         netflow_wait(ofproto->netflow);
843     }
844     mac_learning_wait(ofproto->ml);
845     stp_wait(ofproto);
846     if (ofproto->need_revalidate) {
847         /* Shouldn't happen, but if it does just go around again. */
848         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
849         poll_immediate_wake();
850     } else {
851         timer_wait(&ofproto->next_expiration);
852     }
853 }
854
855 static void
856 flush(struct ofproto *ofproto_)
857 {
858     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
859     struct facet *facet, *next_facet;
860
861     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
862         /* Mark the facet as not installed so that facet_remove() doesn't
863          * bother trying to uninstall it.  There is no point in uninstalling it
864          * individually since we are about to blow away all the facets with
865          * dpif_flow_flush(). */
866         struct subfacet *subfacet;
867
868         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
869             subfacet->installed = false;
870             subfacet->dp_packet_count = 0;
871             subfacet->dp_byte_count = 0;
872         }
873         facet_remove(ofproto, facet);
874     }
875     dpif_flow_flush(ofproto->dpif);
876 }
877
878 static void
879 get_features(struct ofproto *ofproto_ OVS_UNUSED,
880              bool *arp_match_ip, uint32_t *actions)
881 {
882     *arp_match_ip = true;
883     *actions = ((1u << OFPAT_OUTPUT) |
884                 (1u << OFPAT_SET_VLAN_VID) |
885                 (1u << OFPAT_SET_VLAN_PCP) |
886                 (1u << OFPAT_STRIP_VLAN) |
887                 (1u << OFPAT_SET_DL_SRC) |
888                 (1u << OFPAT_SET_DL_DST) |
889                 (1u << OFPAT_SET_NW_SRC) |
890                 (1u << OFPAT_SET_NW_DST) |
891                 (1u << OFPAT_SET_NW_TOS) |
892                 (1u << OFPAT_SET_TP_SRC) |
893                 (1u << OFPAT_SET_TP_DST) |
894                 (1u << OFPAT_ENQUEUE));
895 }
896
897 static void
898 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
899 {
900     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
901     struct dpif_dp_stats s;
902
903     strcpy(ots->name, "classifier");
904
905     dpif_get_dp_stats(ofproto->dpif, &s);
906     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
907     put_32aligned_be64(&ots->matched_count,
908                        htonll(s.n_hit + ofproto->n_matches));
909 }
910
911 static struct ofport *
912 port_alloc(void)
913 {
914     struct ofport_dpif *port = xmalloc(sizeof *port);
915     return &port->up;
916 }
917
918 static void
919 port_dealloc(struct ofport *port_)
920 {
921     struct ofport_dpif *port = ofport_dpif_cast(port_);
922     free(port);
923 }
924
925 static int
926 port_construct(struct ofport *port_)
927 {
928     struct ofport_dpif *port = ofport_dpif_cast(port_);
929     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
930
931     ofproto->need_revalidate = true;
932     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
933     port->bundle = NULL;
934     port->cfm = NULL;
935     port->tag = tag_create_random();
936     port->may_enable = true;
937     port->stp_port = NULL;
938     port->stp_state = STP_DISABLED;
939     hmap_init(&port->priorities);
940     port->realdev_ofp_port = 0;
941     port->vlandev_vid = 0;
942
943     if (ofproto->sflow) {
944         dpif_sflow_add_port(ofproto->sflow, port_);
945     }
946
947     return 0;
948 }
949
950 static void
951 port_destruct(struct ofport *port_)
952 {
953     struct ofport_dpif *port = ofport_dpif_cast(port_);
954     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
955
956     ofproto->need_revalidate = true;
957     bundle_remove(port_);
958     set_cfm(port_, NULL);
959     if (ofproto->sflow) {
960         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
961     }
962
963     ofport_clear_priorities(port);
964     hmap_destroy(&port->priorities);
965 }
966
967 static void
968 port_modified(struct ofport *port_)
969 {
970     struct ofport_dpif *port = ofport_dpif_cast(port_);
971
972     if (port->bundle && port->bundle->bond) {
973         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
974     }
975 }
976
977 static void
978 port_reconfigured(struct ofport *port_, ovs_be32 old_config)
979 {
980     struct ofport_dpif *port = ofport_dpif_cast(port_);
981     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
982     ovs_be32 changed = old_config ^ port->up.opp.config;
983
984     if (changed & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
985                         OFPPC_NO_FWD | OFPPC_NO_FLOOD)) {
986         ofproto->need_revalidate = true;
987
988         if (changed & htonl(OFPPC_NO_FLOOD) && port->bundle) {
989             bundle_update(port->bundle);
990         }
991     }
992 }
993
994 static int
995 set_sflow(struct ofproto *ofproto_,
996           const struct ofproto_sflow_options *sflow_options)
997 {
998     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
999     struct dpif_sflow *ds = ofproto->sflow;
1000
1001     if (sflow_options) {
1002         if (!ds) {
1003             struct ofport_dpif *ofport;
1004
1005             ds = ofproto->sflow = dpif_sflow_create(ofproto->dpif);
1006             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1007                 dpif_sflow_add_port(ds, &ofport->up);
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 static int
2214 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
2215 {
2216     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2217     int error;
2218
2219     error = netdev_get_stats(ofport->up.netdev, stats);
2220
2221     if (!error && ofport->odp_port == OVSP_LOCAL) {
2222         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2223
2224         /* ofproto->stats.tx_packets represents packets that we created
2225          * internally and sent to some port (e.g. packets sent with
2226          * send_packet()).  Account for them as if they had come from
2227          * OFPP_LOCAL and got forwarded. */
2228
2229         if (stats->rx_packets != UINT64_MAX) {
2230             stats->rx_packets += ofproto->stats.tx_packets;
2231         }
2232
2233         if (stats->rx_bytes != UINT64_MAX) {
2234             stats->rx_bytes += ofproto->stats.tx_bytes;
2235         }
2236
2237         /* ofproto->stats.rx_packets represents packets that were received on
2238          * some port and we processed internally and dropped (e.g. STP).
2239          * Account fro them as if they had been forwarded to OFPP_LOCAL. */
2240
2241         if (stats->tx_packets != UINT64_MAX) {
2242             stats->tx_packets += ofproto->stats.rx_packets;
2243         }
2244
2245         if (stats->tx_bytes != UINT64_MAX) {
2246             stats->tx_bytes += ofproto->stats.rx_bytes;
2247         }
2248     }
2249
2250     return error;
2251 }
2252
2253 /* Account packets for LOCAL port. */
2254 static void
2255 ofproto_update_local_port_stats(const struct ofproto *ofproto_,
2256                                 size_t tx_size, size_t rx_size)
2257 {
2258     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2259
2260     if (rx_size) {
2261         ofproto->stats.rx_packets++;
2262         ofproto->stats.rx_bytes += rx_size;
2263     }
2264     if (tx_size) {
2265         ofproto->stats.tx_packets++;
2266         ofproto->stats.tx_bytes += tx_size;
2267     }
2268 }
2269
2270 struct port_dump_state {
2271     struct dpif_port_dump dump;
2272     bool done;
2273 };
2274
2275 static int
2276 port_dump_start(const struct ofproto *ofproto_, void **statep)
2277 {
2278     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2279     struct port_dump_state *state;
2280
2281     *statep = state = xmalloc(sizeof *state);
2282     dpif_port_dump_start(&state->dump, ofproto->dpif);
2283     state->done = false;
2284     return 0;
2285 }
2286
2287 static int
2288 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
2289                struct ofproto_port *port)
2290 {
2291     struct port_dump_state *state = state_;
2292     struct dpif_port dpif_port;
2293
2294     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
2295         ofproto_port_from_dpif_port(port, &dpif_port);
2296         return 0;
2297     } else {
2298         int error = dpif_port_dump_done(&state->dump);
2299         state->done = true;
2300         return error ? error : EOF;
2301     }
2302 }
2303
2304 static int
2305 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
2306 {
2307     struct port_dump_state *state = state_;
2308
2309     if (!state->done) {
2310         dpif_port_dump_done(&state->dump);
2311     }
2312     free(state);
2313     return 0;
2314 }
2315
2316 static int
2317 port_poll(const struct ofproto *ofproto_, char **devnamep)
2318 {
2319     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2320     return dpif_port_poll(ofproto->dpif, devnamep);
2321 }
2322
2323 static void
2324 port_poll_wait(const struct ofproto *ofproto_)
2325 {
2326     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2327     dpif_port_poll_wait(ofproto->dpif);
2328 }
2329
2330 static int
2331 port_is_lacp_current(const struct ofport *ofport_)
2332 {
2333     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2334     return (ofport->bundle && ofport->bundle->lacp
2335             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2336             : -1);
2337 }
2338 \f
2339 /* Upcall handling. */
2340
2341 /* Flow miss batching.
2342  *
2343  * Some dpifs implement operations faster when you hand them off in a batch.
2344  * To allow batching, "struct flow_miss" queues the dpif-related work needed
2345  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
2346  * more packets, plus possibly installing the flow in the dpif.
2347  *
2348  * So far we only batch the operations that affect flow setup time the most.
2349  * It's possible to batch more than that, but the benefit might be minimal. */
2350 struct flow_miss {
2351     struct hmap_node hmap_node;
2352     struct flow flow;
2353     enum odp_key_fitness key_fitness;
2354     const struct nlattr *key;
2355     size_t key_len;
2356     ovs_be16 initial_tci;
2357     struct list packets;
2358 };
2359
2360 struct flow_miss_op {
2361     union dpif_op dpif_op;
2362     struct subfacet *subfacet;
2363 };
2364
2365 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
2366  * OpenFlow controller as necessary according to their individual
2367  * configurations.
2368  *
2369  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
2370  * ownership is transferred to this function. */
2371 static void
2372 send_packet_in_miss(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2373                     const struct flow *flow, bool clone)
2374 {
2375     struct ofputil_packet_in pin;
2376
2377     pin.packet = packet;
2378     pin.in_port = flow->in_port;
2379     pin.reason = OFPR_NO_MATCH;
2380     pin.buffer_id = 0;          /* not yet known */
2381     pin.send_len = 0;           /* not used for flow table misses */
2382     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2383                            clone ? NULL : packet);
2384 }
2385
2386 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_ACTION to each
2387  * OpenFlow controller as necessary according to their individual
2388  * configurations.
2389  *
2390  * 'send_len' should be the number of bytes of 'packet' to send to the
2391  * controller, as specified in the action that caused the packet to be sent.
2392  *
2393  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
2394  * Otherwise, ownership is transferred to this function. */
2395 static void
2396 send_packet_in_action(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2397                       uint64_t userdata, const struct flow *flow, bool clone)
2398 {
2399     struct ofputil_packet_in pin;
2400     struct user_action_cookie cookie;
2401
2402     memcpy(&cookie, &userdata, sizeof(cookie));
2403
2404     pin.packet = packet;
2405     pin.in_port = flow->in_port;
2406     pin.reason = OFPR_ACTION;
2407     pin.buffer_id = 0;          /* not yet known */
2408     pin.send_len = cookie.data;
2409     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2410                            clone ? NULL : packet);
2411 }
2412
2413 static bool
2414 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
2415                 const struct ofpbuf *packet)
2416 {
2417     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
2418
2419     if (!ofport) {
2420         return false;
2421     }
2422
2423     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
2424         if (packet) {
2425             cfm_process_heartbeat(ofport->cfm, packet);
2426         }
2427         return true;
2428     } else if (ofport->bundle && ofport->bundle->lacp
2429                && flow->dl_type == htons(ETH_TYPE_LACP)) {
2430         if (packet) {
2431             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
2432         }
2433         return true;
2434     } else if (ofproto->stp && stp_should_process_flow(flow)) {
2435         if (packet) {
2436             stp_process_packet(ofport, packet);
2437         }
2438         return true;
2439     }
2440     return false;
2441 }
2442
2443 static struct flow_miss *
2444 flow_miss_create(struct hmap *todo, const struct flow *flow,
2445                  enum odp_key_fitness key_fitness,
2446                  const struct nlattr *key, size_t key_len,
2447                  ovs_be16 initial_tci)
2448 {
2449     uint32_t hash = flow_hash(flow, 0);
2450     struct flow_miss *miss;
2451
2452     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
2453         if (flow_equal(&miss->flow, flow)) {
2454             return miss;
2455         }
2456     }
2457
2458     miss = xmalloc(sizeof *miss);
2459     hmap_insert(todo, &miss->hmap_node, hash);
2460     miss->flow = *flow;
2461     miss->key_fitness = key_fitness;
2462     miss->key = key;
2463     miss->key_len = key_len;
2464     miss->initial_tci = initial_tci;
2465     list_init(&miss->packets);
2466     return miss;
2467 }
2468
2469 static void
2470 handle_flow_miss(struct ofproto_dpif *ofproto, struct flow_miss *miss,
2471                  struct flow_miss_op *ops, size_t *n_ops)
2472 {
2473     const struct flow *flow = &miss->flow;
2474     struct ofpbuf *packet, *next_packet;
2475     struct subfacet *subfacet;
2476     struct facet *facet;
2477
2478     facet = facet_lookup_valid(ofproto, flow);
2479     if (!facet) {
2480         struct rule_dpif *rule;
2481
2482         rule = rule_dpif_lookup(ofproto, flow, 0);
2483         if (!rule) {
2484             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
2485             struct ofport_dpif *port = get_ofp_port(ofproto, flow->in_port);
2486             if (port) {
2487                 if (port->up.opp.config & htonl(OFPPC_NO_PACKET_IN)) {
2488                     COVERAGE_INC(ofproto_dpif_no_packet_in);
2489                     /* XXX install 'drop' flow entry */
2490                     return;
2491                 }
2492             } else {
2493                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
2494                              flow->in_port);
2495             }
2496
2497             LIST_FOR_EACH_SAFE (packet, next_packet, list_node,
2498                                 &miss->packets) {
2499                 list_remove(&packet->list_node);
2500                 send_packet_in_miss(ofproto, packet, flow, false);
2501             }
2502
2503             return;
2504         }
2505
2506         facet = facet_create(rule, flow);
2507     }
2508
2509     subfacet = subfacet_create(ofproto, facet,
2510                                miss->key_fitness, miss->key, miss->key_len,
2511                                miss->initial_tci);
2512
2513     LIST_FOR_EACH_SAFE (packet, next_packet, list_node, &miss->packets) {
2514         list_remove(&packet->list_node);
2515         ofproto->n_matches++;
2516
2517         if (facet->rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
2518             /*
2519              * Extra-special case for fail-open mode.
2520              *
2521              * We are in fail-open mode and the packet matched the fail-open
2522              * rule, but we are connected to a controller too.  We should send
2523              * the packet up to the controller in the hope that it will try to
2524              * set up a flow and thereby allow us to exit fail-open.
2525              *
2526              * See the top-level comment in fail-open.c for more information.
2527              */
2528             send_packet_in_miss(ofproto, packet, flow, true);
2529         }
2530
2531         if (!facet->may_install || !subfacet->actions) {
2532             subfacet_make_actions(ofproto, subfacet, packet);
2533         }
2534         if (!execute_controller_action(ofproto, &facet->flow,
2535                                        subfacet->actions,
2536                                        subfacet->actions_len, packet)) {
2537             struct flow_miss_op *op = &ops[(*n_ops)++];
2538             struct dpif_execute *execute = &op->dpif_op.execute;
2539
2540             op->subfacet = subfacet;
2541             execute->type = DPIF_OP_EXECUTE;
2542             execute->key = miss->key;
2543             execute->key_len = miss->key_len;
2544             execute->actions
2545                 = (facet->may_install
2546                    ? subfacet->actions
2547                    : xmemdup(subfacet->actions, subfacet->actions_len));
2548             execute->actions_len = subfacet->actions_len;
2549             execute->packet = packet;
2550         }
2551     }
2552
2553     if (facet->may_install && subfacet->key_fitness != ODP_FIT_TOO_LITTLE) {
2554         struct flow_miss_op *op = &ops[(*n_ops)++];
2555         struct dpif_flow_put *put = &op->dpif_op.flow_put;
2556
2557         op->subfacet = subfacet;
2558         put->type = DPIF_OP_FLOW_PUT;
2559         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2560         put->key = miss->key;
2561         put->key_len = miss->key_len;
2562         put->actions = subfacet->actions;
2563         put->actions_len = subfacet->actions_len;
2564         put->stats = NULL;
2565     }
2566 }
2567
2568 static enum odp_key_fitness
2569 ofproto_dpif_extract_flow_key(const struct ofproto_dpif *ofproto,
2570                               const struct nlattr *key, size_t key_len,
2571                               struct flow *flow, ovs_be16 *initial_tci)
2572 {
2573     enum odp_key_fitness fitness;
2574     uint16_t realdev;
2575     int vid;
2576
2577     fitness = odp_flow_key_to_flow(key, key_len, flow);
2578     if (fitness == ODP_FIT_ERROR) {
2579         return fitness;
2580     }
2581     *initial_tci = flow->vlan_tci;
2582
2583     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port, &vid);
2584     if (realdev) {
2585         /* Cause the flow to be processed as if it came in on the real device
2586          * with the VLAN device's VLAN ID. */
2587         flow->in_port = realdev;
2588         flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
2589
2590         /* Let the caller know that we can't reproduce 'key' from 'flow'. */
2591         if (fitness == ODP_FIT_PERFECT) {
2592             fitness = ODP_FIT_TOO_MUCH;
2593         }
2594     }
2595
2596     return fitness;
2597 }
2598
2599 static void
2600 handle_miss_upcalls(struct ofproto_dpif *ofproto, struct dpif_upcall *upcalls,
2601                     size_t n_upcalls)
2602 {
2603     struct dpif_upcall *upcall;
2604     struct flow_miss *miss, *next_miss;
2605     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
2606     union dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
2607     struct hmap todo;
2608     size_t n_ops;
2609     size_t i;
2610
2611     if (!n_upcalls) {
2612         return;
2613     }
2614
2615     /* Construct the to-do list.
2616      *
2617      * This just amounts to extracting the flow from each packet and sticking
2618      * the packets that have the same flow in the same "flow_miss" structure so
2619      * that we can process them together. */
2620     hmap_init(&todo);
2621     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
2622         enum odp_key_fitness fitness;
2623         struct flow_miss *miss;
2624         ovs_be16 initial_tci;
2625         struct flow flow;
2626
2627         /* Obtain metadata and check userspace/kernel agreement on flow match,
2628          * then set 'flow''s header pointers. */
2629         fitness = ofproto_dpif_extract_flow_key(ofproto,
2630                                                 upcall->key, upcall->key_len,
2631                                                 &flow, &initial_tci);
2632         if (fitness == ODP_FIT_ERROR) {
2633             ofpbuf_delete(upcall->packet);
2634             continue;
2635         }
2636         flow_extract(upcall->packet, flow.priority, flow.tun_id,
2637                      flow.in_port, &flow);
2638
2639         /* Handle 802.1ag, LACP, and STP specially. */
2640         if (process_special(ofproto, &flow, upcall->packet)) {
2641             ofproto_update_local_port_stats(&ofproto->up,
2642                                             0, upcall->packet->size);
2643             ofpbuf_delete(upcall->packet);
2644             ofproto->n_matches++;
2645             continue;
2646         }
2647
2648         /* Add other packets to a to-do list. */
2649         miss = flow_miss_create(&todo, &flow, fitness,
2650                                 upcall->key, upcall->key_len, initial_tci);
2651         list_push_back(&miss->packets, &upcall->packet->list_node);
2652     }
2653
2654     /* Process each element in the to-do list, constructing the set of
2655      * operations to batch. */
2656     n_ops = 0;
2657     HMAP_FOR_EACH_SAFE (miss, next_miss, hmap_node, &todo) {
2658         handle_flow_miss(ofproto, miss, flow_miss_ops, &n_ops);
2659         ofpbuf_list_delete(&miss->packets);
2660         hmap_remove(&todo, &miss->hmap_node);
2661         free(miss);
2662     }
2663     assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
2664     hmap_destroy(&todo);
2665
2666     /* Execute batch. */
2667     for (i = 0; i < n_ops; i++) {
2668         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
2669     }
2670     dpif_operate(ofproto->dpif, dpif_ops, n_ops);
2671
2672     /* Free memory and update facets. */
2673     for (i = 0; i < n_ops; i++) {
2674         struct flow_miss_op *op = &flow_miss_ops[i];
2675         struct dpif_execute *execute;
2676         struct dpif_flow_put *put;
2677
2678         switch (op->dpif_op.type) {
2679         case DPIF_OP_EXECUTE:
2680             execute = &op->dpif_op.execute;
2681             if (op->subfacet->actions != execute->actions) {
2682                 free((struct nlattr *) execute->actions);
2683             }
2684             ofpbuf_delete((struct ofpbuf *) execute->packet);
2685             break;
2686
2687         case DPIF_OP_FLOW_PUT:
2688             put = &op->dpif_op.flow_put;
2689             if (!put->error) {
2690                 op->subfacet->installed = true;
2691             }
2692             break;
2693         }
2694     }
2695 }
2696
2697 static void
2698 handle_userspace_upcall(struct ofproto_dpif *ofproto,
2699                         struct dpif_upcall *upcall)
2700 {
2701     struct user_action_cookie cookie;
2702     enum odp_key_fitness fitness;
2703     ovs_be16 initial_tci;
2704     struct flow flow;
2705
2706     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
2707
2708     fitness = ofproto_dpif_extract_flow_key(ofproto, upcall->key,
2709                                             upcall->key_len, &flow,
2710                                             &initial_tci);
2711     if (fitness == ODP_FIT_ERROR) {
2712         ofpbuf_delete(upcall->packet);
2713         return;
2714     }
2715
2716     if (cookie.type == USER_ACTION_COOKIE_SFLOW) {
2717         if (ofproto->sflow) {
2718             dpif_sflow_received(ofproto->sflow, upcall->packet, &flow,
2719                                 &cookie);
2720         }
2721         ofpbuf_delete(upcall->packet);
2722     } else if (cookie.type == USER_ACTION_COOKIE_CONTROLLER) {
2723         COVERAGE_INC(ofproto_dpif_ctlr_action);
2724         send_packet_in_action(ofproto, upcall->packet, upcall->userdata,
2725                               &flow, false);
2726     } else {
2727         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
2728         ofpbuf_delete(upcall->packet);
2729     }
2730 }
2731
2732 static int
2733 handle_upcalls(struct ofproto_dpif *ofproto, unsigned int max_batch)
2734 {
2735     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
2736     int n_misses;
2737     int i;
2738
2739     assert (max_batch <= FLOW_MISS_MAX_BATCH);
2740
2741     n_misses = 0;
2742     for (i = 0; i < max_batch; i++) {
2743         struct dpif_upcall *upcall = &misses[n_misses];
2744         int error;
2745
2746         error = dpif_recv(ofproto->dpif, upcall);
2747         if (error) {
2748             break;
2749         }
2750
2751         switch (upcall->type) {
2752         case DPIF_UC_ACTION:
2753             handle_userspace_upcall(ofproto, upcall);
2754             break;
2755
2756         case DPIF_UC_MISS:
2757             /* Handle it later. */
2758             n_misses++;
2759             break;
2760
2761         case DPIF_N_UC_TYPES:
2762         default:
2763             VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32,
2764                          upcall->type);
2765             break;
2766         }
2767     }
2768
2769     handle_miss_upcalls(ofproto, misses, n_misses);
2770
2771     return i;
2772 }
2773 \f
2774 /* Flow expiration. */
2775
2776 static int subfacet_max_idle(const struct ofproto_dpif *);
2777 static void update_stats(struct ofproto_dpif *);
2778 static void rule_expire(struct rule_dpif *);
2779 static void expire_subfacets(struct ofproto_dpif *, int dp_max_idle);
2780
2781 /* This function is called periodically by run().  Its job is to collect
2782  * updates for the flows that have been installed into the datapath, most
2783  * importantly when they last were used, and then use that information to
2784  * expire flows that have not been used recently.
2785  *
2786  * Returns the number of milliseconds after which it should be called again. */
2787 static int
2788 expire(struct ofproto_dpif *ofproto)
2789 {
2790     struct rule_dpif *rule, *next_rule;
2791     struct classifier *table;
2792     int dp_max_idle;
2793
2794     /* Update stats for each flow in the datapath. */
2795     update_stats(ofproto);
2796
2797     /* Expire subfacets that have been idle too long. */
2798     dp_max_idle = subfacet_max_idle(ofproto);
2799     expire_subfacets(ofproto, dp_max_idle);
2800
2801     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
2802     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
2803         struct cls_cursor cursor;
2804
2805         cls_cursor_init(&cursor, table, NULL);
2806         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
2807             rule_expire(rule);
2808         }
2809     }
2810
2811     /* All outstanding data in existing flows has been accounted, so it's a
2812      * good time to do bond rebalancing. */
2813     if (ofproto->has_bonded_bundles) {
2814         struct ofbundle *bundle;
2815
2816         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2817             if (bundle->bond) {
2818                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
2819             }
2820         }
2821     }
2822
2823     return MIN(dp_max_idle, 1000);
2824 }
2825
2826 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
2827  *
2828  * This function also pushes statistics updates to rules which each facet
2829  * resubmits into.  Generally these statistics will be accurate.  However, if a
2830  * facet changes the rule it resubmits into at some time in between
2831  * update_stats() runs, it is possible that statistics accrued to the
2832  * old rule will be incorrectly attributed to the new rule.  This could be
2833  * avoided by calling update_stats() whenever rules are created or
2834  * deleted.  However, the performance impact of making so many calls to the
2835  * datapath do not justify the benefit of having perfectly accurate statistics.
2836  */
2837 static void
2838 update_stats(struct ofproto_dpif *p)
2839 {
2840     const struct dpif_flow_stats *stats;
2841     struct dpif_flow_dump dump;
2842     const struct nlattr *key;
2843     size_t key_len;
2844
2845     dpif_flow_dump_start(&dump, p->dpif);
2846     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
2847         struct subfacet *subfacet;
2848
2849         subfacet = subfacet_find(p, key, key_len);
2850         if (subfacet && subfacet->installed) {
2851             struct facet *facet = subfacet->facet;
2852
2853             if (stats->n_packets >= subfacet->dp_packet_count) {
2854                 uint64_t extra = stats->n_packets - subfacet->dp_packet_count;
2855                 facet->packet_count += extra;
2856             } else {
2857                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
2858             }
2859
2860             if (stats->n_bytes >= subfacet->dp_byte_count) {
2861                 facet->byte_count += stats->n_bytes - subfacet->dp_byte_count;
2862             } else {
2863                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
2864             }
2865
2866             subfacet->dp_packet_count = stats->n_packets;
2867             subfacet->dp_byte_count = stats->n_bytes;
2868
2869             subfacet_update_time(p, subfacet, stats->used);
2870             facet_account(p, facet);
2871             facet_push_stats(facet);
2872         } else {
2873             if (!VLOG_DROP_WARN(&rl)) {
2874                 struct ds s;
2875
2876                 ds_init(&s);
2877                 odp_flow_key_format(key, key_len, &s);
2878                 VLOG_WARN("unexpected flow from datapath %s", ds_cstr(&s));
2879                 ds_destroy(&s);
2880             }
2881
2882             COVERAGE_INC(facet_unexpected);
2883             /* There's a flow in the datapath that we know nothing about, or a
2884              * flow that shouldn't be installed but was anyway.  Delete it. */
2885             dpif_flow_del(p->dpif, key, key_len, NULL);
2886         }
2887     }
2888     dpif_flow_dump_done(&dump);
2889 }
2890
2891 /* Calculates and returns the number of milliseconds of idle time after which
2892  * subfacets should expire from the datapath.  When a subfacet expires, we fold
2893  * its statistics into its facet, and when a facet's last subfacet expires, we
2894  * fold its statistic into its rule. */
2895 static int
2896 subfacet_max_idle(const struct ofproto_dpif *ofproto)
2897 {
2898     /*
2899      * Idle time histogram.
2900      *
2901      * Most of the time a switch has a relatively small number of subfacets.
2902      * When this is the case we might as well keep statistics for all of them
2903      * in userspace and to cache them in the kernel datapath for performance as
2904      * well.
2905      *
2906      * As the number of subfacets increases, the memory required to maintain
2907      * statistics about them in userspace and in the kernel becomes
2908      * significant.  However, with a large number of subfacets it is likely
2909      * that only a few of them are "heavy hitters" that consume a large amount
2910      * of bandwidth.  At this point, only heavy hitters are worth caching in
2911      * the kernel and maintaining in userspaces; other subfacets we can
2912      * discard.
2913      *
2914      * The technique used to compute the idle time is to build a histogram with
2915      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
2916      * that is installed in the kernel gets dropped in the appropriate bucket.
2917      * After the histogram has been built, we compute the cutoff so that only
2918      * the most-recently-used 1% of subfacets (but at least
2919      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
2920      * the most-recently-used bucket of subfacets is kept, so actually an
2921      * arbitrary number of subfacets can be kept in any given expiration run
2922      * (though the next run will delete most of those unless they receive
2923      * additional data).
2924      *
2925      * This requires a second pass through the subfacets, in addition to the
2926      * pass made by update_stats(), because the former function never looks at
2927      * uninstallable subfacets.
2928      */
2929     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
2930     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
2931     int buckets[N_BUCKETS] = { 0 };
2932     int total, subtotal, bucket;
2933     struct subfacet *subfacet;
2934     long long int now;
2935     int i;
2936
2937     total = hmap_count(&ofproto->subfacets);
2938     if (total <= ofproto->up.flow_eviction_threshold) {
2939         return N_BUCKETS * BUCKET_WIDTH;
2940     }
2941
2942     /* Build histogram. */
2943     now = time_msec();
2944     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
2945         long long int idle = now - subfacet->used;
2946         int bucket = (idle <= 0 ? 0
2947                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
2948                       : (unsigned int) idle / BUCKET_WIDTH);
2949         buckets[bucket]++;
2950     }
2951
2952     /* Find the first bucket whose flows should be expired. */
2953     subtotal = bucket = 0;
2954     do {
2955         subtotal += buckets[bucket++];
2956     } while (bucket < N_BUCKETS &&
2957              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
2958
2959     if (VLOG_IS_DBG_ENABLED()) {
2960         struct ds s;
2961
2962         ds_init(&s);
2963         ds_put_cstr(&s, "keep");
2964         for (i = 0; i < N_BUCKETS; i++) {
2965             if (i == bucket) {
2966                 ds_put_cstr(&s, ", drop");
2967             }
2968             if (buckets[i]) {
2969                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
2970             }
2971         }
2972         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
2973         ds_destroy(&s);
2974     }
2975
2976     return bucket * BUCKET_WIDTH;
2977 }
2978
2979 static void
2980 expire_subfacets(struct ofproto_dpif *ofproto, int dp_max_idle)
2981 {
2982     long long int cutoff = time_msec() - dp_max_idle;
2983     struct subfacet *subfacet, *next_subfacet;
2984
2985     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
2986                         &ofproto->subfacets) {
2987         if (subfacet->used < cutoff) {
2988             subfacet_destroy(ofproto, subfacet);
2989         }
2990     }
2991 }
2992
2993 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
2994  * then delete it entirely. */
2995 static void
2996 rule_expire(struct rule_dpif *rule)
2997 {
2998     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2999     struct facet *facet, *next_facet;
3000     long long int now;
3001     uint8_t reason;
3002
3003     /* Has 'rule' expired? */
3004     now = time_msec();
3005     if (rule->up.hard_timeout
3006         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
3007         reason = OFPRR_HARD_TIMEOUT;
3008     } else if (rule->up.idle_timeout && list_is_empty(&rule->facets)
3009                && now > rule->used + rule->up.idle_timeout * 1000) {
3010         reason = OFPRR_IDLE_TIMEOUT;
3011     } else {
3012         return;
3013     }
3014
3015     COVERAGE_INC(ofproto_dpif_expired);
3016
3017     /* Update stats.  (This is a no-op if the rule expired due to an idle
3018      * timeout, because that only happens when the rule has no facets left.) */
3019     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3020         facet_remove(ofproto, facet);
3021     }
3022
3023     /* Get rid of the rule. */
3024     ofproto_rule_expire(&rule->up, reason);
3025 }
3026 \f
3027 /* Facets. */
3028
3029 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
3030  *
3031  * The caller must already have determined that no facet with an identical
3032  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
3033  * the ofproto's classifier table.
3034  *
3035  * The facet will initially have no subfacets.  The caller should create (at
3036  * least) one subfacet with subfacet_create(). */
3037 static struct facet *
3038 facet_create(struct rule_dpif *rule, const struct flow *flow)
3039 {
3040     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3041     struct facet *facet;
3042
3043     facet = xzalloc(sizeof *facet);
3044     facet->used = time_msec();
3045     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
3046     list_push_back(&rule->facets, &facet->list_node);
3047     facet->rule = rule;
3048     facet->flow = *flow;
3049     list_init(&facet->subfacets);
3050     netflow_flow_init(&facet->nf_flow);
3051     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
3052
3053     return facet;
3054 }
3055
3056 static void
3057 facet_free(struct facet *facet)
3058 {
3059     free(facet);
3060 }
3061
3062 static bool
3063 execute_controller_action(struct ofproto_dpif *ofproto,
3064                           const struct flow *flow,
3065                           const struct nlattr *odp_actions, size_t actions_len,
3066                           struct ofpbuf *packet)
3067 {
3068     if (actions_len
3069         && odp_actions->nla_type == OVS_ACTION_ATTR_USERSPACE
3070         && NLA_ALIGN(odp_actions->nla_len) == actions_len) {
3071         /* As an optimization, avoid a round-trip from userspace to kernel to
3072          * userspace.  This also avoids possibly filling up kernel packet
3073          * buffers along the way.
3074          *
3075          * This optimization will not accidentally catch sFlow
3076          * OVS_ACTION_ATTR_USERSPACE actions, since those are encapsulated
3077          * inside OVS_ACTION_ATTR_SAMPLE. */
3078         const struct nlattr *nla;
3079
3080         nla = nl_attr_find_nested(odp_actions, OVS_USERSPACE_ATTR_USERDATA);
3081         send_packet_in_action(ofproto, packet, nl_attr_get_u64(nla), flow,
3082                               false);
3083         return true;
3084     } else {
3085         return false;
3086     }
3087 }
3088
3089 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
3090  * 'packet', which arrived on 'in_port'.
3091  *
3092  * Takes ownership of 'packet'. */
3093 static bool
3094 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
3095                     const struct nlattr *odp_actions, size_t actions_len,
3096                     struct ofpbuf *packet)
3097 {
3098     struct odputil_keybuf keybuf;
3099     struct ofpbuf key;
3100     int error;
3101
3102     if (execute_controller_action(ofproto, flow, odp_actions, actions_len,
3103                                   packet)) {
3104         return true;
3105     }
3106
3107     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3108     odp_flow_key_from_flow(&key, flow);
3109
3110     error = dpif_execute(ofproto->dpif, key.data, key.size,
3111                          odp_actions, actions_len, packet);
3112
3113     ofpbuf_delete(packet);
3114     return !error;
3115 }
3116
3117 /* Remove 'facet' from 'ofproto' and free up the associated memory:
3118  *
3119  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
3120  *     rule's statistics, via subfacet_uninstall().
3121  *
3122  *   - Removes 'facet' from its rule and from ofproto->facets.
3123  */
3124 static void
3125 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
3126 {
3127     struct subfacet *subfacet, *next_subfacet;
3128
3129     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
3130                         &facet->subfacets) {
3131         subfacet_destroy__(ofproto, subfacet);
3132     }
3133
3134     facet_flush_stats(ofproto, facet);
3135     hmap_remove(&ofproto->facets, &facet->hmap_node);
3136     list_remove(&facet->list_node);
3137     facet_free(facet);
3138 }
3139
3140 static void
3141 facet_account(struct ofproto_dpif *ofproto, struct facet *facet)
3142 {
3143     uint64_t n_bytes;
3144     struct subfacet *subfacet;
3145     const struct nlattr *a;
3146     unsigned int left;
3147     ovs_be16 vlan_tci;
3148
3149     if (facet->byte_count <= facet->accounted_bytes) {
3150         return;
3151     }
3152     n_bytes = facet->byte_count - facet->accounted_bytes;
3153     facet->accounted_bytes = facet->byte_count;
3154
3155     /* Feed information from the active flows back into the learning table to
3156      * ensure that table is always in sync with what is actually flowing
3157      * through the datapath. */
3158     if (facet->has_learn || facet->has_normal) {
3159         struct action_xlate_ctx ctx;
3160
3161         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3162                               facet->flow.vlan_tci, NULL);
3163         ctx.may_learn = true;
3164         ofpbuf_delete(xlate_actions(&ctx, facet->rule->up.actions,
3165                                     facet->rule->up.n_actions));
3166     }
3167
3168     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
3169         return;
3170     }
3171
3172     /* This loop feeds byte counters to bond_account() for rebalancing to use
3173      * as a basis.  We also need to track the actual VLAN on which the packet
3174      * is going to be sent to ensure that it matches the one passed to
3175      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
3176      * hash bucket.)
3177      *
3178      * We use the actions from an arbitrary subfacet because they should all
3179      * be equally valid for our purpose. */
3180     subfacet = CONTAINER_OF(list_front(&facet->subfacets),
3181                             struct subfacet, list_node);
3182     vlan_tci = facet->flow.vlan_tci;
3183     NL_ATTR_FOR_EACH_UNSAFE (a, left,
3184                              subfacet->actions, subfacet->actions_len) {
3185         const struct ovs_action_push_vlan *vlan;
3186         struct ofport_dpif *port;
3187
3188         switch (nl_attr_type(a)) {
3189         case OVS_ACTION_ATTR_OUTPUT:
3190             port = get_odp_port(ofproto, nl_attr_get_u32(a));
3191             if (port && port->bundle && port->bundle->bond) {
3192                 bond_account(port->bundle->bond, &facet->flow,
3193                              vlan_tci_to_vid(vlan_tci), n_bytes);
3194             }
3195             break;
3196
3197         case OVS_ACTION_ATTR_POP_VLAN:
3198             vlan_tci = htons(0);
3199             break;
3200
3201         case OVS_ACTION_ATTR_PUSH_VLAN:
3202             vlan = nl_attr_get(a);
3203             vlan_tci = vlan->vlan_tci;
3204             break;
3205         }
3206     }
3207 }
3208
3209 /* Returns true if the only action for 'facet' is to send to the controller.
3210  * (We don't report NetFlow expiration messages for such facets because they
3211  * are just part of the control logic for the network, not real traffic). */
3212 static bool
3213 facet_is_controller_flow(struct facet *facet)
3214 {
3215     return (facet
3216             && facet->rule->up.n_actions == 1
3217             && action_outputs_to_port(&facet->rule->up.actions[0],
3218                                       htons(OFPP_CONTROLLER)));
3219 }
3220
3221 /* Folds all of 'facet''s statistics into its rule.  Also updates the
3222  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
3223  * 'facet''s statistics in the datapath should have been zeroed and folded into
3224  * its packet and byte counts before this function is called. */
3225 static void
3226 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
3227 {
3228     struct subfacet *subfacet;
3229
3230     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3231         assert(!subfacet->dp_byte_count);
3232         assert(!subfacet->dp_packet_count);
3233     }
3234
3235     facet_push_stats(facet);
3236     facet_account(ofproto, facet);
3237
3238     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
3239         struct ofexpired expired;
3240         expired.flow = facet->flow;
3241         expired.packet_count = facet->packet_count;
3242         expired.byte_count = facet->byte_count;
3243         expired.used = facet->used;
3244         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
3245     }
3246
3247     facet->rule->packet_count += facet->packet_count;
3248     facet->rule->byte_count += facet->byte_count;
3249
3250     /* Reset counters to prevent double counting if 'facet' ever gets
3251      * reinstalled. */
3252     facet_reset_counters(facet);
3253
3254     netflow_flow_clear(&facet->nf_flow);
3255 }
3256
3257 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3258  * Returns it if found, otherwise a null pointer.
3259  *
3260  * The returned facet might need revalidation; use facet_lookup_valid()
3261  * instead if that is important. */
3262 static struct facet *
3263 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
3264 {
3265     struct facet *facet;
3266
3267     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
3268                              &ofproto->facets) {
3269         if (flow_equal(flow, &facet->flow)) {
3270             return facet;
3271         }
3272     }
3273
3274     return NULL;
3275 }
3276
3277 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3278  * Returns it if found, otherwise a null pointer.
3279  *
3280  * The returned facet is guaranteed to be valid. */
3281 static struct facet *
3282 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
3283 {
3284     struct facet *facet = facet_find(ofproto, flow);
3285
3286     /* The facet we found might not be valid, since we could be in need of
3287      * revalidation.  If it is not valid, don't return it. */
3288     if (facet
3289         && (ofproto->need_revalidate
3290             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
3291         && !facet_revalidate(ofproto, facet)) {
3292         COVERAGE_INC(facet_invalidated);
3293         return NULL;
3294     }
3295
3296     return facet;
3297 }
3298
3299 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
3300  *
3301  *   - If the rule found is different from 'facet''s current rule, moves
3302  *     'facet' to the new rule and recompiles its actions.
3303  *
3304  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
3305  *     where it is and recompiles its actions anyway.
3306  *
3307  *   - If there is none, destroys 'facet'.
3308  *
3309  * Returns true if 'facet' still exists, false if it has been destroyed. */
3310 static bool
3311 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
3312 {
3313     struct actions {
3314         struct nlattr *odp_actions;
3315         size_t actions_len;
3316     };
3317     struct actions *new_actions;
3318
3319     struct action_xlate_ctx ctx;
3320     struct rule_dpif *new_rule;
3321     struct subfacet *subfacet;
3322     bool actions_changed;
3323     int i;
3324
3325     COVERAGE_INC(facet_revalidate);
3326
3327     /* Determine the new rule. */
3328     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
3329     if (!new_rule) {
3330         /* No new rule, so delete the facet. */
3331         facet_remove(ofproto, facet);
3332         return false;
3333     }
3334
3335     /* Calculate new datapath actions.
3336      *
3337      * We do not modify any 'facet' state yet, because we might need to, e.g.,
3338      * emit a NetFlow expiration and, if so, we need to have the old state
3339      * around to properly compose it. */
3340
3341     /* If the datapath actions changed or the installability changed,
3342      * then we need to talk to the datapath. */
3343     i = 0;
3344     new_actions = NULL;
3345     memset(&ctx, 0, sizeof ctx);
3346     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3347         struct ofpbuf *odp_actions;
3348         bool should_install;
3349
3350         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
3351                               subfacet->initial_tci, NULL);
3352         odp_actions = xlate_actions(&ctx, new_rule->up.actions,
3353                                     new_rule->up.n_actions);
3354         actions_changed = (subfacet->actions_len != odp_actions->size
3355                            || memcmp(subfacet->actions, odp_actions->data,
3356                                      subfacet->actions_len));
3357
3358         should_install = (ctx.may_set_up_flow
3359                           && subfacet->key_fitness != ODP_FIT_TOO_LITTLE);
3360         if (actions_changed || should_install != subfacet->installed) {
3361             if (should_install) {
3362                 struct dpif_flow_stats stats;
3363
3364                 subfacet_install(ofproto, subfacet,
3365                                  odp_actions->data, odp_actions->size, &stats);
3366                 subfacet_update_stats(ofproto, subfacet, &stats);
3367             } else {
3368                 subfacet_uninstall(ofproto, subfacet);
3369             }
3370
3371             if (!new_actions) {
3372                 new_actions = xcalloc(list_size(&facet->subfacets),
3373                                       sizeof *new_actions);
3374             }
3375             new_actions[i].odp_actions = xmemdup(odp_actions->data,
3376                                                  odp_actions->size);
3377             new_actions[i].actions_len = odp_actions->size;
3378         }
3379
3380         ofpbuf_delete(odp_actions);
3381         i++;
3382     }
3383     if (new_actions) {
3384         facet_flush_stats(ofproto, facet);
3385     }
3386
3387     /* Update 'facet' now that we've taken care of all the old state. */
3388     facet->tags = ctx.tags;
3389     facet->nf_flow.output_iface = ctx.nf_output_iface;
3390     facet->may_install = ctx.may_set_up_flow;
3391     facet->has_learn = ctx.has_learn;
3392     facet->has_normal = ctx.has_normal;
3393     facet->mirrors = ctx.mirrors;
3394     if (new_actions) {
3395         i = 0;
3396         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3397             if (new_actions[i].odp_actions) {
3398                 free(subfacet->actions);
3399                 subfacet->actions = new_actions[i].odp_actions;
3400                 subfacet->actions_len = new_actions[i].actions_len;
3401             }
3402             i++;
3403         }
3404         free(new_actions);
3405     }
3406     if (facet->rule != new_rule) {
3407         COVERAGE_INC(facet_changed_rule);
3408         list_remove(&facet->list_node);
3409         list_push_back(&new_rule->facets, &facet->list_node);
3410         facet->rule = new_rule;
3411         facet->used = new_rule->up.created;
3412         facet->prev_used = facet->used;
3413     }
3414
3415     return true;
3416 }
3417
3418 /* Updates 'facet''s used time.  Caller is responsible for calling
3419  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3420 static void
3421 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
3422                   long long int used)
3423 {
3424     if (used > facet->used) {
3425         facet->used = used;
3426         if (used > facet->rule->used) {
3427             facet->rule->used = used;
3428         }
3429         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3430     }
3431 }
3432
3433 static void
3434 facet_reset_counters(struct facet *facet)
3435 {
3436     facet->packet_count = 0;
3437     facet->byte_count = 0;
3438     facet->prev_packet_count = 0;
3439     facet->prev_byte_count = 0;
3440     facet->accounted_bytes = 0;
3441 }
3442
3443 static void
3444 facet_push_stats(struct facet *facet)
3445 {
3446     uint64_t new_packets, new_bytes;
3447
3448     assert(facet->packet_count >= facet->prev_packet_count);
3449     assert(facet->byte_count >= facet->prev_byte_count);
3450     assert(facet->used >= facet->prev_used);
3451
3452     new_packets = facet->packet_count - facet->prev_packet_count;
3453     new_bytes = facet->byte_count - facet->prev_byte_count;
3454
3455     if (new_packets || new_bytes || facet->used > facet->prev_used) {
3456         facet->prev_packet_count = facet->packet_count;
3457         facet->prev_byte_count = facet->byte_count;
3458         facet->prev_used = facet->used;
3459
3460         flow_push_stats(facet->rule, &facet->flow,
3461                         new_packets, new_bytes, facet->used);
3462
3463         update_mirror_stats(ofproto_dpif_cast(facet->rule->up.ofproto),
3464                             facet->mirrors, new_packets, new_bytes);
3465     }
3466 }
3467
3468 struct ofproto_push {
3469     struct action_xlate_ctx ctx;
3470     uint64_t packets;
3471     uint64_t bytes;
3472     long long int used;
3473 };
3474
3475 static void
3476 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
3477 {
3478     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
3479
3480     if (rule) {
3481         rule->packet_count += push->packets;
3482         rule->byte_count += push->bytes;
3483         rule->used = MAX(push->used, rule->used);
3484     }
3485 }
3486
3487 /* Pushes flow statistics to the rules which 'flow' resubmits into given
3488  * 'rule''s actions and mirrors. */
3489 static void
3490 flow_push_stats(const struct rule_dpif *rule,
3491                 const struct flow *flow, uint64_t packets, uint64_t bytes,
3492                 long long int used)
3493 {
3494     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3495     struct ofproto_push push;
3496
3497     push.packets = packets;
3498     push.bytes = bytes;
3499     push.used = used;
3500
3501     action_xlate_ctx_init(&push.ctx, ofproto, flow, flow->vlan_tci, NULL);
3502     push.ctx.resubmit_hook = push_resubmit;
3503     ofpbuf_delete(xlate_actions(&push.ctx,
3504                                 rule->up.actions, rule->up.n_actions));
3505 }
3506 \f
3507 /* Subfacets. */
3508
3509 static struct subfacet *
3510 subfacet_find__(struct ofproto_dpif *ofproto,
3511                 const struct nlattr *key, size_t key_len, uint32_t key_hash,
3512                 const struct flow *flow)
3513 {
3514     struct subfacet *subfacet;
3515
3516     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
3517                              &ofproto->subfacets) {
3518         if (subfacet->key
3519             ? (subfacet->key_len == key_len
3520                && !memcmp(key, subfacet->key, key_len))
3521             : flow_equal(flow, &subfacet->facet->flow)) {
3522             return subfacet;
3523         }
3524     }
3525
3526     return NULL;
3527 }
3528
3529 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
3530  * 'key_fitness', 'key', and 'key_len'.  Returns the existing subfacet if
3531  * there is one, otherwise creates and returns a new subfacet.
3532  *
3533  * If the returned subfacet is new, then subfacet->actions will be NULL, in
3534  * which case the caller must populate the actions with
3535  * subfacet_make_actions(). */
3536 static struct subfacet *
3537 subfacet_create(struct ofproto_dpif *ofproto, struct facet *facet,
3538                 enum odp_key_fitness key_fitness,
3539                 const struct nlattr *key, size_t key_len, ovs_be16 initial_tci)
3540 {
3541     uint32_t key_hash = odp_flow_key_hash(key, key_len);
3542     struct subfacet *subfacet;
3543
3544     subfacet = subfacet_find__(ofproto, key, key_len, key_hash, &facet->flow);
3545     if (subfacet) {
3546         if (subfacet->facet == facet) {
3547             return subfacet;
3548         }
3549
3550         /* This shouldn't happen. */
3551         VLOG_ERR_RL(&rl, "subfacet with wrong facet");
3552         subfacet_destroy(ofproto, subfacet);
3553     }
3554
3555     subfacet = xzalloc(sizeof *subfacet);
3556     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
3557     list_push_back(&facet->subfacets, &subfacet->list_node);
3558     subfacet->facet = facet;
3559     subfacet->used = time_msec();
3560     subfacet->key_fitness = key_fitness;
3561     if (key_fitness != ODP_FIT_PERFECT) {
3562         subfacet->key = xmemdup(key, key_len);
3563         subfacet->key_len = key_len;
3564     }
3565     subfacet->installed = false;
3566     subfacet->initial_tci = initial_tci;
3567
3568     return subfacet;
3569 }
3570
3571 /* Searches 'ofproto' for a subfacet with the given 'key', 'key_len', and
3572  * 'flow'.  Returns the subfacet if one exists, otherwise NULL. */
3573 static struct subfacet *
3574 subfacet_find(struct ofproto_dpif *ofproto,
3575               const struct nlattr *key, size_t key_len)
3576 {
3577     uint32_t key_hash = odp_flow_key_hash(key, key_len);
3578     enum odp_key_fitness fitness;
3579     struct flow flow;
3580
3581     fitness = odp_flow_key_to_flow(key, key_len, &flow);
3582     if (fitness == ODP_FIT_ERROR) {
3583         return NULL;
3584     }
3585
3586     return subfacet_find__(ofproto, key, key_len, key_hash, &flow);
3587 }
3588
3589 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
3590  * its facet within 'ofproto', and frees it. */
3591 static void
3592 subfacet_destroy__(struct ofproto_dpif *ofproto, struct subfacet *subfacet)
3593 {
3594     subfacet_uninstall(ofproto, subfacet);
3595     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
3596     list_remove(&subfacet->list_node);
3597     free(subfacet->key);
3598     free(subfacet->actions);
3599     free(subfacet);
3600 }
3601
3602 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
3603  * last remaining subfacet in its facet destroys the facet too. */
3604 static void
3605 subfacet_destroy(struct ofproto_dpif *ofproto, struct subfacet *subfacet)
3606 {
3607     struct facet *facet = subfacet->facet;
3608
3609     subfacet_destroy__(ofproto, subfacet);
3610     if (list_is_empty(&facet->subfacets)) {
3611         facet_remove(ofproto, facet);
3612     }
3613 }
3614
3615 /* Initializes 'key' with the sequence of OVS_KEY_ATTR_* Netlink attributes
3616  * that can be used to refer to 'subfacet'.  The caller must provide 'keybuf'
3617  * for use as temporary storage. */
3618 static void
3619 subfacet_get_key(struct subfacet *subfacet, struct odputil_keybuf *keybuf,
3620                  struct ofpbuf *key)
3621 {
3622     if (!subfacet->key) {
3623         ofpbuf_use_stack(key, keybuf, sizeof *keybuf);
3624         odp_flow_key_from_flow(key, &subfacet->facet->flow);
3625     } else {
3626         ofpbuf_use_const(key, subfacet->key, subfacet->key_len);
3627     }
3628 }
3629
3630 /* Composes the datapath actions for 'subfacet' based on its rule's actions. */
3631 static void
3632 subfacet_make_actions(struct ofproto_dpif *p, struct subfacet *subfacet,
3633                       const struct ofpbuf *packet)
3634 {
3635     struct facet *facet = subfacet->facet;
3636     const struct rule_dpif *rule = facet->rule;
3637     struct ofpbuf *odp_actions;
3638     struct action_xlate_ctx ctx;
3639
3640     action_xlate_ctx_init(&ctx, p, &facet->flow, subfacet->initial_tci,
3641                           packet);
3642     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3643     facet->tags = ctx.tags;
3644     facet->may_install = ctx.may_set_up_flow;
3645     facet->has_learn = ctx.has_learn;
3646     facet->has_normal = ctx.has_normal;
3647     facet->nf_flow.output_iface = ctx.nf_output_iface;
3648     facet->mirrors = ctx.mirrors;
3649
3650     if (subfacet->actions_len != odp_actions->size
3651         || memcmp(subfacet->actions, odp_actions->data, odp_actions->size)) {
3652         free(subfacet->actions);
3653         subfacet->actions_len = odp_actions->size;
3654         subfacet->actions = xmemdup(odp_actions->data, odp_actions->size);
3655     }
3656
3657     ofpbuf_delete(odp_actions);
3658 }
3659
3660 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
3661  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
3662  * in the datapath will be zeroed and 'stats' will be updated with traffic new
3663  * since 'subfacet' was last updated.
3664  *
3665  * Returns 0 if successful, otherwise a positive errno value. */
3666 static int
3667 subfacet_install(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3668                  const struct nlattr *actions, size_t actions_len,
3669                  struct dpif_flow_stats *stats)
3670 {
3671     struct odputil_keybuf keybuf;
3672     enum dpif_flow_put_flags flags;
3673     struct ofpbuf key;
3674     int ret;
3675
3676     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3677     if (stats) {
3678         flags |= DPIF_FP_ZERO_STATS;
3679     }
3680
3681     subfacet_get_key(subfacet, &keybuf, &key);
3682     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
3683                         actions, actions_len, stats);
3684
3685     if (stats) {
3686         subfacet_reset_dp_stats(subfacet, stats);
3687     }
3688
3689     return ret;
3690 }
3691
3692 /* If 'subfacet' is installed in the datapath, uninstalls it. */
3693 static void
3694 subfacet_uninstall(struct ofproto_dpif *p, struct subfacet *subfacet)
3695 {
3696     if (subfacet->installed) {
3697         struct odputil_keybuf keybuf;
3698         struct dpif_flow_stats stats;
3699         struct ofpbuf key;
3700         int error;
3701
3702         subfacet_get_key(subfacet, &keybuf, &key);
3703         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
3704         subfacet_reset_dp_stats(subfacet, &stats);
3705         if (!error) {
3706             subfacet_update_stats(p, subfacet, &stats);
3707         }
3708         subfacet->installed = false;
3709     } else {
3710         assert(subfacet->dp_packet_count == 0);
3711         assert(subfacet->dp_byte_count == 0);
3712     }
3713 }
3714
3715 /* Resets 'subfacet''s datapath statistics counters.  This should be called
3716  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
3717  * non-null, it should contain the statistics returned by dpif when 'subfacet'
3718  * was reset in the datapath.  'stats' will be modified to include only
3719  * statistics new since 'subfacet' was last updated. */
3720 static void
3721 subfacet_reset_dp_stats(struct subfacet *subfacet,
3722                         struct dpif_flow_stats *stats)
3723 {
3724     if (stats
3725         && subfacet->dp_packet_count <= stats->n_packets
3726         && subfacet->dp_byte_count <= stats->n_bytes) {
3727         stats->n_packets -= subfacet->dp_packet_count;
3728         stats->n_bytes -= subfacet->dp_byte_count;
3729     }
3730
3731     subfacet->dp_packet_count = 0;
3732     subfacet->dp_byte_count = 0;
3733 }
3734
3735 /* Updates 'subfacet''s used time.  The caller is responsible for calling
3736  * facet_push_stats() to update the flows which 'subfacet' resubmits into. */
3737 static void
3738 subfacet_update_time(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3739                      long long int used)
3740 {
3741     if (used > subfacet->used) {
3742         subfacet->used = used;
3743         facet_update_time(ofproto, subfacet->facet, used);
3744     }
3745 }
3746
3747 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
3748  *
3749  * Because of the meaning of a subfacet's counters, it only makes sense to do
3750  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
3751  * represents a packet that was sent by hand or if it represents statistics
3752  * that have been cleared out of the datapath. */
3753 static void
3754 subfacet_update_stats(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3755                       const struct dpif_flow_stats *stats)
3756 {
3757     if (stats->n_packets || stats->used > subfacet->used) {
3758         struct facet *facet = subfacet->facet;
3759
3760         subfacet_update_time(ofproto, subfacet, stats->used);
3761         facet->packet_count += stats->n_packets;
3762         facet->byte_count += stats->n_bytes;
3763         facet_push_stats(facet);
3764         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3765     }
3766 }
3767 \f
3768 /* Rules. */
3769
3770 static struct rule_dpif *
3771 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
3772                  uint8_t table_id)
3773 {
3774     struct cls_rule *cls_rule;
3775     struct classifier *cls;
3776
3777     if (table_id >= N_TABLES) {
3778         return NULL;
3779     }
3780
3781     cls = &ofproto->up.tables[table_id];
3782     if (flow->nw_frag & FLOW_NW_FRAG_ANY
3783         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3784         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
3785          * are unavailable. */
3786         struct flow ofpc_normal_flow = *flow;
3787         ofpc_normal_flow.tp_src = htons(0);
3788         ofpc_normal_flow.tp_dst = htons(0);
3789         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
3790     } else {
3791         cls_rule = classifier_lookup(cls, flow);
3792     }
3793     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
3794 }
3795
3796 static void
3797 complete_operation(struct rule_dpif *rule)
3798 {
3799     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3800
3801     rule_invalidate(rule);
3802     if (clogged) {
3803         struct dpif_completion *c = xmalloc(sizeof *c);
3804         c->op = rule->up.pending;
3805         list_push_back(&ofproto->completions, &c->list_node);
3806     } else {
3807         ofoperation_complete(rule->up.pending, 0);
3808     }
3809 }
3810
3811 static struct rule *
3812 rule_alloc(void)
3813 {
3814     struct rule_dpif *rule = xmalloc(sizeof *rule);
3815     return &rule->up;
3816 }
3817
3818 static void
3819 rule_dealloc(struct rule *rule_)
3820 {
3821     struct rule_dpif *rule = rule_dpif_cast(rule_);
3822     free(rule);
3823 }
3824
3825 static int
3826 rule_construct(struct rule *rule_)
3827 {
3828     struct rule_dpif *rule = rule_dpif_cast(rule_);
3829     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3830     struct rule_dpif *victim;
3831     uint8_t table_id;
3832     int error;
3833
3834     error = validate_actions(rule->up.actions, rule->up.n_actions,
3835                              &rule->up.cr.flow, ofproto->max_ports);
3836     if (error) {
3837         return error;
3838     }
3839
3840     rule->used = rule->up.created;
3841     rule->packet_count = 0;
3842     rule->byte_count = 0;
3843
3844     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
3845     if (victim && !list_is_empty(&victim->facets)) {
3846         struct facet *facet;
3847
3848         rule->facets = victim->facets;
3849         list_moved(&rule->facets);
3850         LIST_FOR_EACH (facet, list_node, &rule->facets) {
3851             /* XXX: We're only clearing our local counters here.  It's possible
3852              * that quite a few packets are unaccounted for in the datapath
3853              * statistics.  These will be accounted to the new rule instead of
3854              * cleared as required.  This could be fixed by clearing out the
3855              * datapath statistics for this facet, but currently it doesn't
3856              * seem worth it. */
3857             facet_reset_counters(facet);
3858             facet->rule = rule;
3859         }
3860     } else {
3861         /* Must avoid list_moved() in this case. */
3862         list_init(&rule->facets);
3863     }
3864
3865     table_id = rule->up.table_id;
3866     rule->tag = (victim ? victim->tag
3867                  : table_id == 0 ? 0
3868                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
3869                                       ofproto->tables[table_id].basis));
3870
3871     complete_operation(rule);
3872     return 0;
3873 }
3874
3875 static void
3876 rule_destruct(struct rule *rule_)
3877 {
3878     struct rule_dpif *rule = rule_dpif_cast(rule_);
3879     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3880     struct facet *facet, *next_facet;
3881
3882     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3883         facet_revalidate(ofproto, facet);
3884     }
3885
3886     complete_operation(rule);
3887 }
3888
3889 static void
3890 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3891 {
3892     struct rule_dpif *rule = rule_dpif_cast(rule_);
3893     struct facet *facet;
3894
3895     /* Start from historical data for 'rule' itself that are no longer tracked
3896      * in facets.  This counts, for example, facets that have expired. */
3897     *packets = rule->packet_count;
3898     *bytes = rule->byte_count;
3899
3900     /* Add any statistics that are tracked by facets.  This includes
3901      * statistical data recently updated by ofproto_update_stats() as well as
3902      * stats for packets that were executed "by hand" via dpif_execute(). */
3903     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3904         *packets += facet->packet_count;
3905         *bytes += facet->byte_count;
3906     }
3907 }
3908
3909 static int
3910 rule_execute(struct rule *rule_, const struct flow *flow,
3911              struct ofpbuf *packet)
3912 {
3913     struct rule_dpif *rule = rule_dpif_cast(rule_);
3914     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3915     struct action_xlate_ctx ctx;
3916     struct ofpbuf *odp_actions;
3917     size_t size;
3918
3919     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, packet);
3920     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3921     size = packet->size;
3922     if (execute_odp_actions(ofproto, flow, odp_actions->data,
3923                             odp_actions->size, packet)) {
3924         rule->used = time_msec();
3925         rule->packet_count++;
3926         rule->byte_count += size;
3927         flow_push_stats(rule, flow, 1, size, rule->used);
3928     }
3929     ofpbuf_delete(odp_actions);
3930
3931     return 0;
3932 }
3933
3934 static void
3935 rule_modify_actions(struct rule *rule_)
3936 {
3937     struct rule_dpif *rule = rule_dpif_cast(rule_);
3938     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3939     int error;
3940
3941     error = validate_actions(rule->up.actions, rule->up.n_actions,
3942                              &rule->up.cr.flow, ofproto->max_ports);
3943     if (error) {
3944         ofoperation_complete(rule->up.pending, error);
3945         return;
3946     }
3947
3948     complete_operation(rule);
3949 }
3950 \f
3951 /* Sends 'packet' out 'ofport'.
3952  * May modify 'packet'.
3953  * Returns 0 if successful, otherwise a positive errno value. */
3954 static int
3955 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
3956 {
3957     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3958     struct ofpbuf key, odp_actions;
3959     struct odputil_keybuf keybuf;
3960     uint16_t odp_port;
3961     struct flow flow;
3962     int error;
3963
3964     flow_extract((struct ofpbuf *) packet, 0, 0, 0, &flow);
3965     odp_port = vsp_realdev_to_vlandev(ofproto, ofport->odp_port,
3966                                       flow.vlan_tci);
3967     if (odp_port != ofport->odp_port) {
3968         eth_pop_vlan(packet);
3969         flow.vlan_tci = htons(0);
3970     }
3971
3972     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3973     odp_flow_key_from_flow(&key, &flow);
3974
3975     ofpbuf_init(&odp_actions, 32);
3976     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
3977
3978     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3979     error = dpif_execute(ofproto->dpif,
3980                          key.data, key.size,
3981                          odp_actions.data, odp_actions.size,
3982                          packet);
3983     ofpbuf_uninit(&odp_actions);
3984
3985     if (error) {
3986         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
3987                      ofproto->up.name, odp_port, strerror(error));
3988     }
3989     ofproto_update_local_port_stats(ofport->up.ofproto, packet->size, 0);
3990     return error;
3991 }
3992 \f
3993 /* OpenFlow to datapath action translation. */
3994
3995 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3996                              struct action_xlate_ctx *ctx);
3997 static void xlate_normal(struct action_xlate_ctx *);
3998
3999 static size_t
4000 put_userspace_action(const struct ofproto_dpif *ofproto,
4001                      struct ofpbuf *odp_actions,
4002                      const struct flow *flow,
4003                      const struct user_action_cookie *cookie)
4004 {
4005     uint32_t pid;
4006
4007     pid = dpif_port_get_pid(ofproto->dpif,
4008                             ofp_port_to_odp_port(flow->in_port));
4009
4010     return odp_put_userspace_action(pid, cookie, odp_actions);
4011 }
4012
4013 /* Compose SAMPLE action for sFlow. */
4014 static size_t
4015 compose_sflow_action(const struct ofproto_dpif *ofproto,
4016                      struct ofpbuf *odp_actions,
4017                      const struct flow *flow,
4018                      uint32_t odp_port)
4019 {
4020     uint32_t port_ifindex;
4021     uint32_t probability;
4022     struct user_action_cookie cookie;
4023     size_t sample_offset, actions_offset;
4024     int cookie_offset, n_output;
4025
4026     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
4027         return 0;
4028     }
4029
4030     if (odp_port == OVSP_NONE) {
4031         port_ifindex = 0;
4032         n_output = 0;
4033     } else {
4034         port_ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
4035         n_output = 1;
4036     }
4037
4038     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
4039
4040     /* Number of packets out of UINT_MAX to sample. */
4041     probability = dpif_sflow_get_probability(ofproto->sflow);
4042     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
4043
4044     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
4045
4046     cookie.type = USER_ACTION_COOKIE_SFLOW;
4047     cookie.data = port_ifindex;
4048     cookie.n_output = n_output;
4049     cookie.vlan_tci = 0;
4050     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
4051
4052     nl_msg_end_nested(odp_actions, actions_offset);
4053     nl_msg_end_nested(odp_actions, sample_offset);
4054     return cookie_offset;
4055 }
4056
4057 /* SAMPLE action must be first action in any given list of actions.
4058  * At this point we do not have all information required to build it. So try to
4059  * build sample action as complete as possible. */
4060 static void
4061 add_sflow_action(struct action_xlate_ctx *ctx)
4062 {
4063     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
4064                                                    ctx->odp_actions,
4065                                                    &ctx->flow, OVSP_NONE);
4066     ctx->sflow_odp_port = 0;
4067     ctx->sflow_n_outputs = 0;
4068 }
4069
4070 /* Fix SAMPLE action according to data collected while composing ODP actions.
4071  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
4072  * USERSPACE action's user-cookie which is required for sflow. */
4073 static void
4074 fix_sflow_action(struct action_xlate_ctx *ctx)
4075 {
4076     const struct flow *base = &ctx->base_flow;
4077     struct user_action_cookie *cookie;
4078
4079     if (!ctx->user_cookie_offset) {
4080         return;
4081     }
4082
4083     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
4084                      sizeof(*cookie));
4085     assert(cookie != NULL);
4086     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
4087
4088     if (ctx->sflow_n_outputs) {
4089         cookie->data = dpif_sflow_odp_port_to_ifindex(ctx->ofproto->sflow,
4090                                                     ctx->sflow_odp_port);
4091     }
4092     if (ctx->sflow_n_outputs >= 255) {
4093         cookie->n_output = 255;
4094     } else {
4095         cookie->n_output = ctx->sflow_n_outputs;
4096     }
4097     cookie->vlan_tci = base->vlan_tci;
4098 }
4099
4100 static void
4101 compose_output_action__(struct action_xlate_ctx *ctx, uint16_t ofp_port,
4102                         bool check_stp)
4103 {
4104     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
4105     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
4106     ovs_be16 flow_vlan_tci = ctx->flow.vlan_tci;
4107     uint8_t flow_nw_tos = ctx->flow.nw_tos;
4108     uint16_t out_port;
4109
4110     if (ofport) {
4111         struct priority_to_dscp *pdscp;
4112
4113         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)
4114             || (check_stp && !stp_forward_in_state(ofport->stp_state))) {
4115             return;
4116         }
4117
4118         pdscp = get_priority(ofport, ctx->flow.priority);
4119         if (pdscp) {
4120             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
4121             ctx->flow.nw_tos |= pdscp->dscp;
4122         }
4123     } else {
4124         /* We may not have an ofport record for this port, but it doesn't hurt
4125          * to allow forwarding to it anyhow.  Maybe such a port will appear
4126          * later and we're pre-populating the flow table.  */
4127     }
4128
4129     out_port = vsp_realdev_to_vlandev(ctx->ofproto, odp_port,
4130                                       ctx->flow.vlan_tci);
4131     if (out_port != odp_port) {
4132         ctx->flow.vlan_tci = htons(0);
4133     }
4134     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
4135     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, out_port);
4136
4137     ctx->sflow_odp_port = odp_port;
4138     ctx->sflow_n_outputs++;
4139     ctx->nf_output_iface = ofp_port;
4140     ctx->flow.vlan_tci = flow_vlan_tci;
4141     ctx->flow.nw_tos = flow_nw_tos;
4142 }
4143
4144 static void
4145 compose_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
4146 {
4147     compose_output_action__(ctx, ofp_port, true);
4148 }
4149
4150 static void
4151 xlate_table_action(struct action_xlate_ctx *ctx,
4152                    uint16_t in_port, uint8_t table_id)
4153 {
4154     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
4155         struct ofproto_dpif *ofproto = ctx->ofproto;
4156         struct rule_dpif *rule;
4157         uint16_t old_in_port;
4158         uint8_t old_table_id;
4159
4160         old_table_id = ctx->table_id;
4161         ctx->table_id = table_id;
4162
4163         /* Look up a flow with 'in_port' as the input port. */
4164         old_in_port = ctx->flow.in_port;
4165         ctx->flow.in_port = in_port;
4166         rule = rule_dpif_lookup(ofproto, &ctx->flow, table_id);
4167
4168         /* Tag the flow. */
4169         if (table_id > 0 && table_id < N_TABLES) {
4170             struct table_dpif *table = &ofproto->tables[table_id];
4171             if (table->other_table) {
4172                 ctx->tags |= (rule
4173                               ? rule->tag
4174                               : rule_calculate_tag(&ctx->flow,
4175                                                    &table->other_table->wc,
4176                                                    table->basis));
4177             }
4178         }
4179
4180         /* Restore the original input port.  Otherwise OFPP_NORMAL and
4181          * OFPP_IN_PORT will have surprising behavior. */
4182         ctx->flow.in_port = old_in_port;
4183
4184         if (ctx->resubmit_hook) {
4185             ctx->resubmit_hook(ctx, rule);
4186         }
4187
4188         if (rule) {
4189             ctx->recurse++;
4190             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
4191             ctx->recurse--;
4192         }
4193
4194         ctx->table_id = old_table_id;
4195     } else {
4196         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
4197
4198         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
4199                     MAX_RESUBMIT_RECURSION);
4200     }
4201 }
4202
4203 static void
4204 xlate_resubmit_table(struct action_xlate_ctx *ctx,
4205                      const struct nx_action_resubmit *nar)
4206 {
4207     uint16_t in_port;
4208     uint8_t table_id;
4209
4210     in_port = (nar->in_port == htons(OFPP_IN_PORT)
4211                ? ctx->flow.in_port
4212                : ntohs(nar->in_port));
4213     table_id = nar->table == 255 ? ctx->table_id : nar->table;
4214
4215     xlate_table_action(ctx, in_port, table_id);
4216 }
4217
4218 static void
4219 flood_packets(struct action_xlate_ctx *ctx, bool all)
4220 {
4221     struct ofport_dpif *ofport;
4222
4223     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
4224         uint16_t ofp_port = ofport->up.ofp_port;
4225
4226         if (ofp_port == ctx->flow.in_port) {
4227             continue;
4228         }
4229
4230         if (all) {
4231             compose_output_action__(ctx, ofp_port, false);
4232         } else if (!(ofport->up.opp.config & htonl(OFPPC_NO_FLOOD))) {
4233             compose_output_action(ctx, ofp_port);
4234         }
4235     }
4236
4237     ctx->nf_output_iface = NF_OUT_FLOOD;
4238 }
4239
4240 static void
4241 compose_controller_action(struct action_xlate_ctx *ctx, int len)
4242 {
4243     struct user_action_cookie cookie;
4244
4245     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
4246     cookie.type = USER_ACTION_COOKIE_CONTROLLER;
4247     cookie.data = len;
4248     cookie.n_output = 0;
4249     cookie.vlan_tci = 0;
4250     put_userspace_action(ctx->ofproto, ctx->odp_actions, &ctx->flow, &cookie);
4251 }
4252
4253 static void
4254 xlate_output_action__(struct action_xlate_ctx *ctx,
4255                       uint16_t port, uint16_t max_len)
4256 {
4257     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
4258
4259     ctx->nf_output_iface = NF_OUT_DROP;
4260
4261     switch (port) {
4262     case OFPP_IN_PORT:
4263         compose_output_action(ctx, ctx->flow.in_port);
4264         break;
4265     case OFPP_TABLE:
4266         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
4267         break;
4268     case OFPP_NORMAL:
4269         xlate_normal(ctx);
4270         break;
4271     case OFPP_FLOOD:
4272         flood_packets(ctx,  false);
4273         break;
4274     case OFPP_ALL:
4275         flood_packets(ctx, true);
4276         break;
4277     case OFPP_CONTROLLER:
4278         compose_controller_action(ctx, max_len);
4279         break;
4280     case OFPP_LOCAL:
4281         compose_output_action(ctx, OFPP_LOCAL);
4282         break;
4283     case OFPP_NONE:
4284         break;
4285     default:
4286         if (port != ctx->flow.in_port) {
4287             compose_output_action(ctx, port);
4288         }
4289         break;
4290     }
4291
4292     if (prev_nf_output_iface == NF_OUT_FLOOD) {
4293         ctx->nf_output_iface = NF_OUT_FLOOD;
4294     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
4295         ctx->nf_output_iface = prev_nf_output_iface;
4296     } else if (prev_nf_output_iface != NF_OUT_DROP &&
4297                ctx->nf_output_iface != NF_OUT_FLOOD) {
4298         ctx->nf_output_iface = NF_OUT_MULTI;
4299     }
4300 }
4301
4302 static void
4303 xlate_output_reg_action(struct action_xlate_ctx *ctx,
4304                         const struct nx_action_output_reg *naor)
4305 {
4306     uint64_t ofp_port;
4307
4308     ofp_port = nxm_read_field_bits(naor->src, naor->ofs_nbits, &ctx->flow);
4309
4310     if (ofp_port <= UINT16_MAX) {
4311         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
4312     }
4313 }
4314
4315 static void
4316 xlate_output_action(struct action_xlate_ctx *ctx,
4317                     const struct ofp_action_output *oao)
4318 {
4319     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
4320 }
4321
4322 static void
4323 xlate_enqueue_action(struct action_xlate_ctx *ctx,
4324                      const struct ofp_action_enqueue *oae)
4325 {
4326     uint16_t ofp_port;
4327     uint32_t flow_priority, priority;
4328     int error;
4329
4330     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
4331                                    &priority);
4332     if (error) {
4333         /* Fall back to ordinary output action. */
4334         xlate_output_action__(ctx, ntohs(oae->port), 0);
4335         return;
4336     }
4337
4338     /* Figure out datapath output port. */
4339     ofp_port = ntohs(oae->port);
4340     if (ofp_port == OFPP_IN_PORT) {
4341         ofp_port = ctx->flow.in_port;
4342     } else if (ofp_port == ctx->flow.in_port) {
4343         return;
4344     }
4345
4346     /* Add datapath actions. */
4347     flow_priority = ctx->flow.priority;
4348     ctx->flow.priority = priority;
4349     compose_output_action(ctx, ofp_port);
4350     ctx->flow.priority = flow_priority;
4351
4352     /* Update NetFlow output port. */
4353     if (ctx->nf_output_iface == NF_OUT_DROP) {
4354         ctx->nf_output_iface = ofp_port;
4355     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
4356         ctx->nf_output_iface = NF_OUT_MULTI;
4357     }
4358 }
4359
4360 static void
4361 xlate_set_queue_action(struct action_xlate_ctx *ctx,
4362                        const struct nx_action_set_queue *nasq)
4363 {
4364     uint32_t priority;
4365     int error;
4366
4367     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
4368                                    &priority);
4369     if (error) {
4370         /* Couldn't translate queue to a priority, so ignore.  A warning
4371          * has already been logged. */
4372         return;
4373     }
4374
4375     ctx->flow.priority = priority;
4376 }
4377
4378 struct xlate_reg_state {
4379     ovs_be16 vlan_tci;
4380     ovs_be64 tun_id;
4381 };
4382
4383 static void
4384 xlate_autopath(struct action_xlate_ctx *ctx,
4385                const struct nx_action_autopath *naa)
4386 {
4387     uint16_t ofp_port = ntohl(naa->id);
4388     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
4389
4390     if (!port || !port->bundle) {
4391         ofp_port = OFPP_NONE;
4392     } else if (port->bundle->bond) {
4393         /* Autopath does not support VLAN hashing. */
4394         struct ofport_dpif *slave = bond_choose_output_slave(
4395             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
4396         if (slave) {
4397             ofp_port = slave->up.ofp_port;
4398         }
4399     }
4400     autopath_execute(naa, &ctx->flow, ofp_port);
4401 }
4402
4403 static bool
4404 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
4405 {
4406     struct ofproto_dpif *ofproto = ofproto_;
4407     struct ofport_dpif *port;
4408
4409     switch (ofp_port) {
4410     case OFPP_IN_PORT:
4411     case OFPP_TABLE:
4412     case OFPP_NORMAL:
4413     case OFPP_FLOOD:
4414     case OFPP_ALL:
4415     case OFPP_NONE:
4416         return true;
4417     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
4418         return false;
4419     default:
4420         port = get_ofp_port(ofproto, ofp_port);
4421         return port ? port->may_enable : false;
4422     }
4423 }
4424
4425 static void
4426 xlate_learn_action(struct action_xlate_ctx *ctx,
4427                    const struct nx_action_learn *learn)
4428 {
4429     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
4430     struct ofputil_flow_mod fm;
4431     int error;
4432
4433     learn_execute(learn, &ctx->flow, &fm);
4434
4435     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
4436     if (error && !VLOG_DROP_WARN(&rl)) {
4437         char *msg = ofputil_error_to_string(error);
4438         VLOG_WARN("learning action failed to modify flow table (%s)", msg);
4439         free(msg);
4440     }
4441
4442     free(fm.actions);
4443 }
4444
4445 static bool
4446 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
4447 {
4448     if (port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
4449                                ? htonl(OFPPC_NO_RECV_STP)
4450                                : htonl(OFPPC_NO_RECV))) {
4451         return false;
4452     }
4453
4454     /* Only drop packets here if both forwarding and learning are
4455      * disabled.  If just learning is enabled, we need to have
4456      * OFPP_NORMAL and the learning action have a look at the packet
4457      * before we can drop it. */
4458     if (!stp_forward_in_state(port->stp_state)
4459             && !stp_learn_in_state(port->stp_state)) {
4460         return false;
4461     }
4462
4463     return true;
4464 }
4465
4466 static void
4467 do_xlate_actions(const union ofp_action *in, size_t n_in,
4468                  struct action_xlate_ctx *ctx)
4469 {
4470     const struct ofport_dpif *port;
4471     const union ofp_action *ia;
4472     size_t left;
4473
4474     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
4475     if (port && !may_receive(port, ctx)) {
4476         /* Drop this flow. */
4477         return;
4478     }
4479
4480     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
4481         const struct ofp_action_dl_addr *oada;
4482         const struct nx_action_resubmit *nar;
4483         const struct nx_action_set_tunnel *nast;
4484         const struct nx_action_set_queue *nasq;
4485         const struct nx_action_multipath *nam;
4486         const struct nx_action_autopath *naa;
4487         const struct nx_action_bundle *nab;
4488         const struct nx_action_output_reg *naor;
4489         enum ofputil_action_code code;
4490         ovs_be64 tun_id;
4491
4492         if (ctx->exit) {
4493             break;
4494         }
4495
4496         code = ofputil_decode_action_unsafe(ia);
4497         switch (code) {
4498         case OFPUTIL_OFPAT_OUTPUT:
4499             xlate_output_action(ctx, &ia->output);
4500             break;
4501
4502         case OFPUTIL_OFPAT_SET_VLAN_VID:
4503             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
4504             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
4505             break;
4506
4507         case OFPUTIL_OFPAT_SET_VLAN_PCP:
4508             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
4509             ctx->flow.vlan_tci |= htons(
4510                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
4511             break;
4512
4513         case OFPUTIL_OFPAT_STRIP_VLAN:
4514             ctx->flow.vlan_tci = htons(0);
4515             break;
4516
4517         case OFPUTIL_OFPAT_SET_DL_SRC:
4518             oada = ((struct ofp_action_dl_addr *) ia);
4519             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
4520             break;
4521
4522         case OFPUTIL_OFPAT_SET_DL_DST:
4523             oada = ((struct ofp_action_dl_addr *) ia);
4524             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
4525             break;
4526
4527         case OFPUTIL_OFPAT_SET_NW_SRC:
4528             ctx->flow.nw_src = ia->nw_addr.nw_addr;
4529             break;
4530
4531         case OFPUTIL_OFPAT_SET_NW_DST:
4532             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
4533             break;
4534
4535         case OFPUTIL_OFPAT_SET_NW_TOS:
4536             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
4537             ctx->flow.nw_tos |= ia->nw_tos.nw_tos & IP_DSCP_MASK;
4538             break;
4539
4540         case OFPUTIL_OFPAT_SET_TP_SRC:
4541             ctx->flow.tp_src = ia->tp_port.tp_port;
4542             break;
4543
4544         case OFPUTIL_OFPAT_SET_TP_DST:
4545             ctx->flow.tp_dst = ia->tp_port.tp_port;
4546             break;
4547
4548         case OFPUTIL_OFPAT_ENQUEUE:
4549             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
4550             break;
4551
4552         case OFPUTIL_NXAST_RESUBMIT:
4553             nar = (const struct nx_action_resubmit *) ia;
4554             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
4555             break;
4556
4557         case OFPUTIL_NXAST_RESUBMIT_TABLE:
4558             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
4559             break;
4560
4561         case OFPUTIL_NXAST_SET_TUNNEL:
4562             nast = (const struct nx_action_set_tunnel *) ia;
4563             tun_id = htonll(ntohl(nast->tun_id));
4564             ctx->flow.tun_id = tun_id;
4565             break;
4566
4567         case OFPUTIL_NXAST_SET_QUEUE:
4568             nasq = (const struct nx_action_set_queue *) ia;
4569             xlate_set_queue_action(ctx, nasq);
4570             break;
4571
4572         case OFPUTIL_NXAST_POP_QUEUE:
4573             ctx->flow.priority = ctx->original_priority;
4574             break;
4575
4576         case OFPUTIL_NXAST_REG_MOVE:
4577             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
4578                                  &ctx->flow);
4579             break;
4580
4581         case OFPUTIL_NXAST_REG_LOAD:
4582             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
4583                                  &ctx->flow);
4584             break;
4585
4586         case OFPUTIL_NXAST_NOTE:
4587             /* Nothing to do. */
4588             break;
4589
4590         case OFPUTIL_NXAST_SET_TUNNEL64:
4591             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
4592             ctx->flow.tun_id = tun_id;
4593             break;
4594
4595         case OFPUTIL_NXAST_MULTIPATH:
4596             nam = (const struct nx_action_multipath *) ia;
4597             multipath_execute(nam, &ctx->flow);
4598             break;
4599
4600         case OFPUTIL_NXAST_AUTOPATH:
4601             naa = (const struct nx_action_autopath *) ia;
4602             xlate_autopath(ctx, naa);
4603             break;
4604
4605         case OFPUTIL_NXAST_BUNDLE:
4606             ctx->ofproto->has_bundle_action = true;
4607             nab = (const struct nx_action_bundle *) ia;
4608             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
4609                                                       slave_enabled_cb,
4610                                                       ctx->ofproto), 0);
4611             break;
4612
4613         case OFPUTIL_NXAST_BUNDLE_LOAD:
4614             ctx->ofproto->has_bundle_action = true;
4615             nab = (const struct nx_action_bundle *) ia;
4616             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
4617                                 ctx->ofproto);
4618             break;
4619
4620         case OFPUTIL_NXAST_OUTPUT_REG:
4621             naor = (const struct nx_action_output_reg *) ia;
4622             xlate_output_reg_action(ctx, naor);
4623             break;
4624
4625         case OFPUTIL_NXAST_LEARN:
4626             ctx->has_learn = true;
4627             if (ctx->may_learn) {
4628                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
4629             }
4630             break;
4631
4632         case OFPUTIL_NXAST_EXIT:
4633             ctx->exit = true;
4634             break;
4635         }
4636     }
4637
4638     /* We've let OFPP_NORMAL and the learning action look at the packet,
4639      * so drop it now if forwarding is disabled. */
4640     if (port && !stp_forward_in_state(port->stp_state)) {
4641         ofpbuf_clear(ctx->odp_actions);
4642         add_sflow_action(ctx);
4643     }
4644 }
4645
4646 static void
4647 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
4648                       struct ofproto_dpif *ofproto, const struct flow *flow,
4649                       ovs_be16 initial_tci, const struct ofpbuf *packet)
4650 {
4651     ctx->ofproto = ofproto;
4652     ctx->flow = *flow;
4653     ctx->base_flow = ctx->flow;
4654     ctx->base_flow.tun_id = 0;
4655     ctx->base_flow.vlan_tci = initial_tci;
4656     ctx->packet = packet;
4657     ctx->may_learn = packet != NULL;
4658     ctx->resubmit_hook = NULL;
4659 }
4660
4661 static struct ofpbuf *
4662 xlate_actions(struct action_xlate_ctx *ctx,
4663               const union ofp_action *in, size_t n_in)
4664 {
4665     struct flow orig_flow = ctx->flow;
4666
4667     COVERAGE_INC(ofproto_dpif_xlate);
4668
4669     ctx->odp_actions = ofpbuf_new(512);
4670     ofpbuf_reserve(ctx->odp_actions, NL_A_U32_SIZE);
4671     ctx->tags = 0;
4672     ctx->may_set_up_flow = true;
4673     ctx->has_learn = false;
4674     ctx->has_normal = false;
4675     ctx->nf_output_iface = NF_OUT_DROP;
4676     ctx->mirrors = 0;
4677     ctx->recurse = 0;
4678     ctx->original_priority = ctx->flow.priority;
4679     ctx->table_id = 0;
4680     ctx->exit = false;
4681
4682     if (ctx->flow.nw_frag & FLOW_NW_FRAG_ANY) {
4683         switch (ctx->ofproto->up.frag_handling) {
4684         case OFPC_FRAG_NORMAL:
4685             /* We must pretend that transport ports are unavailable. */
4686             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
4687             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
4688             break;
4689
4690         case OFPC_FRAG_DROP:
4691             return ctx->odp_actions;
4692
4693         case OFPC_FRAG_REASM:
4694             NOT_REACHED();
4695
4696         case OFPC_FRAG_NX_MATCH:
4697             /* Nothing to do. */
4698             break;
4699         }
4700     }
4701
4702     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
4703         ctx->may_set_up_flow = false;
4704         return ctx->odp_actions;
4705     } else {
4706         add_sflow_action(ctx);
4707         do_xlate_actions(in, n_in, ctx);
4708
4709         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
4710                                      ctx->odp_actions->data,
4711                                      ctx->odp_actions->size)) {
4712             ctx->may_set_up_flow = false;
4713             if (ctx->packet
4714                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
4715                                        ctx->packet)) {
4716                 compose_output_action(ctx, OFPP_LOCAL);
4717             }
4718         }
4719         add_mirror_actions(ctx, &orig_flow);
4720         fix_sflow_action(ctx);
4721     }
4722
4723     return ctx->odp_actions;
4724 }
4725 \f
4726 /* OFPP_NORMAL implementation. */
4727
4728 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
4729
4730 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
4731  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
4732  * the bundle on which the packet was received, returns the VLAN to which the
4733  * packet belongs.
4734  *
4735  * Both 'vid' and the return value are in the range 0...4095. */
4736 static uint16_t
4737 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
4738 {
4739     switch (in_bundle->vlan_mode) {
4740     case PORT_VLAN_ACCESS:
4741         return in_bundle->vlan;
4742         break;
4743
4744     case PORT_VLAN_TRUNK:
4745         return vid;
4746
4747     case PORT_VLAN_NATIVE_UNTAGGED:
4748     case PORT_VLAN_NATIVE_TAGGED:
4749         return vid ? vid : in_bundle->vlan;
4750
4751     default:
4752         NOT_REACHED();
4753     }
4754 }
4755
4756 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
4757  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
4758  * a warning.
4759  *
4760  * 'vid' should be the VID obtained from the 802.1Q header that was received as
4761  * part of a packet (specify 0 if there was no 802.1Q header), in the range
4762  * 0...4095. */
4763 static bool
4764 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
4765 {
4766     switch (in_bundle->vlan_mode) {
4767     case PORT_VLAN_ACCESS:
4768         if (vid) {
4769             if (warn) {
4770                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4771                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
4772                              "packet received on port %s configured as VLAN "
4773                              "%"PRIu16" access port",
4774                              in_bundle->ofproto->up.name, vid,
4775                              in_bundle->name, in_bundle->vlan);
4776             }
4777             return false;
4778         }
4779         return true;
4780
4781     case PORT_VLAN_NATIVE_UNTAGGED:
4782     case PORT_VLAN_NATIVE_TAGGED:
4783         if (!vid) {
4784             /* Port must always carry its native VLAN. */
4785             return true;
4786         }
4787         /* Fall through. */
4788     case PORT_VLAN_TRUNK:
4789         if (!ofbundle_includes_vlan(in_bundle, vid)) {
4790             if (warn) {
4791                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4792                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
4793                              "received on port %s not configured for trunking "
4794                              "VLAN %"PRIu16,
4795                              in_bundle->ofproto->up.name, vid,
4796                              in_bundle->name, vid);
4797             }
4798             return false;
4799         }
4800         return true;
4801
4802     default:
4803         NOT_REACHED();
4804     }
4805
4806 }
4807
4808 /* Given 'vlan', the VLAN that a packet belongs to, and
4809  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
4810  * that should be included in the 802.1Q header.  (If the return value is 0,
4811  * then the 802.1Q header should only be included in the packet if there is a
4812  * nonzero PCP.)
4813  *
4814  * Both 'vlan' and the return value are in the range 0...4095. */
4815 static uint16_t
4816 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
4817 {
4818     switch (out_bundle->vlan_mode) {
4819     case PORT_VLAN_ACCESS:
4820         return 0;
4821
4822     case PORT_VLAN_TRUNK:
4823     case PORT_VLAN_NATIVE_TAGGED:
4824         return vlan;
4825
4826     case PORT_VLAN_NATIVE_UNTAGGED:
4827         return vlan == out_bundle->vlan ? 0 : vlan;
4828
4829     default:
4830         NOT_REACHED();
4831     }
4832 }
4833
4834 static void
4835 output_normal(struct action_xlate_ctx *ctx, const struct ofbundle *out_bundle,
4836               uint16_t vlan)
4837 {
4838     struct ofport_dpif *port;
4839     uint16_t vid;
4840     ovs_be16 tci, old_tci;
4841
4842     vid = output_vlan_to_vid(out_bundle, vlan);
4843     if (!out_bundle->bond) {
4844         port = ofbundle_get_a_port(out_bundle);
4845     } else {
4846         port = bond_choose_output_slave(out_bundle->bond, &ctx->flow,
4847                                         vid, &ctx->tags);
4848         if (!port) {
4849             /* No slaves enabled, so drop packet. */
4850             return;
4851         }
4852     }
4853
4854     old_tci = ctx->flow.vlan_tci;
4855     tci = htons(vid);
4856     if (tci || out_bundle->use_priority_tags) {
4857         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
4858         if (tci) {
4859             tci |= htons(VLAN_CFI);
4860         }
4861     }
4862     ctx->flow.vlan_tci = tci;
4863
4864     compose_output_action(ctx, port->up.ofp_port);
4865     ctx->flow.vlan_tci = old_tci;
4866 }
4867
4868 static int
4869 mirror_mask_ffs(mirror_mask_t mask)
4870 {
4871     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
4872     return ffs(mask);
4873 }
4874
4875 static bool
4876 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
4877 {
4878     return (bundle->vlan_mode != PORT_VLAN_ACCESS
4879             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
4880 }
4881
4882 static bool
4883 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
4884 {
4885     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
4886 }
4887
4888 /* Returns an arbitrary interface within 'bundle'. */
4889 static struct ofport_dpif *
4890 ofbundle_get_a_port(const struct ofbundle *bundle)
4891 {
4892     return CONTAINER_OF(list_front(&bundle->ports),
4893                         struct ofport_dpif, bundle_node);
4894 }
4895
4896 static bool
4897 vlan_is_mirrored(const struct ofmirror *m, int vlan)
4898 {
4899     return !m->vlans || bitmap_is_set(m->vlans, vlan);
4900 }
4901
4902 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
4903  * to a VLAN.  In general most packets may be mirrored but we want to drop
4904  * protocols that may confuse switches. */
4905 static bool
4906 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
4907 {
4908     /* If you change this function's behavior, please update corresponding
4909      * documentation in vswitch.xml at the same time. */
4910     if (dst[0] != 0x01) {
4911         /* All the currently banned MACs happen to start with 01 currently, so
4912          * this is a quick way to eliminate most of the good ones. */
4913     } else {
4914         if (eth_addr_is_reserved(dst)) {
4915             /* Drop STP, IEEE pause frames, and other reserved protocols
4916              * (01-80-c2-00-00-0x). */
4917             return false;
4918         }
4919
4920         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
4921             /* Cisco OUI. */
4922             if ((dst[3] & 0xfe) == 0xcc &&
4923                 (dst[4] & 0xfe) == 0xcc &&
4924                 (dst[5] & 0xfe) == 0xcc) {
4925                 /* Drop the following protocols plus others following the same
4926                    pattern:
4927
4928                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
4929                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
4930                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
4931                 return false;
4932             }
4933
4934             if (!(dst[3] | dst[4] | dst[5])) {
4935                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
4936                 return false;
4937             }
4938         }
4939     }
4940     return true;
4941 }
4942
4943 static void
4944 add_mirror_actions(struct action_xlate_ctx *ctx, const struct flow *orig_flow)
4945 {
4946     struct ofproto_dpif *ofproto = ctx->ofproto;
4947     mirror_mask_t mirrors;
4948     struct ofport_dpif *in_port;
4949     struct ofbundle *in_bundle;
4950     uint16_t vlan;
4951     uint16_t vid;
4952     const struct nlattr *a;
4953     size_t left;
4954
4955     /* Obtain in_port from orig_flow.in_port.
4956      *
4957      * lookup_input_bundle() also ensures that in_port belongs to a bundle. */
4958     in_port = lookup_input_bundle(ctx->ofproto, orig_flow->in_port,
4959                                   ctx->packet != NULL);
4960     if (!in_port) {
4961         return;
4962     }
4963     in_bundle = in_port->bundle;
4964     mirrors = in_bundle->src_mirrors;
4965
4966     /* Drop frames on bundles reserved for mirroring. */
4967     if (in_bundle->mirror_out) {
4968         if (ctx->packet != NULL) {
4969             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4970             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
4971                          "%s, which is reserved exclusively for mirroring",
4972                          ctx->ofproto->up.name, in_bundle->name);
4973         }
4974         return;
4975     }
4976
4977     /* Check VLAN. */
4978     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
4979     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
4980         return;
4981     }
4982     vlan = input_vid_to_vlan(in_bundle, vid);
4983
4984     /* Look at the output ports to check for destination selections. */
4985
4986     NL_ATTR_FOR_EACH (a, left, ctx->odp_actions->data,
4987                       ctx->odp_actions->size) {
4988         enum ovs_action_attr type = nl_attr_type(a);
4989         struct ofport_dpif *ofport;
4990
4991         if (type != OVS_ACTION_ATTR_OUTPUT) {
4992             continue;
4993         }
4994
4995         ofport = get_odp_port(ofproto, nl_attr_get_u32(a));
4996         mirrors |= ofport ? ofport->bundle->dst_mirrors : 0;
4997     }
4998
4999     if (!mirrors) {
5000         return;
5001     }
5002
5003     /* Restore the original packet before adding the mirror actions. */
5004     ctx->flow = *orig_flow;
5005
5006     while (mirrors) {
5007         struct ofmirror *m;
5008
5009         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
5010
5011         if (!vlan_is_mirrored(m, vlan)) {
5012             mirrors &= mirrors - 1;
5013             continue;
5014         }
5015
5016         mirrors &= ~m->dup_mirrors;
5017         ctx->mirrors |= m->dup_mirrors;
5018         if (m->out) {
5019             output_normal(ctx, m->out, vlan);
5020         } else if (eth_dst_may_rspan(orig_flow->dl_dst)
5021                    && vlan != m->out_vlan) {
5022             struct ofbundle *bundle;
5023
5024             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
5025                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
5026                     && !bundle->mirror_out) {
5027                     output_normal(ctx, bundle, m->out_vlan);
5028                 }
5029             }
5030         }
5031     }
5032 }
5033
5034 static void
5035 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
5036                     uint64_t packets, uint64_t bytes)
5037 {
5038     if (!mirrors) {
5039         return;
5040     }
5041
5042     for (; mirrors; mirrors &= mirrors - 1) {
5043         struct ofmirror *m;
5044
5045         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
5046
5047         if (!m) {
5048             /* In normal circumstances 'm' will not be NULL.  However,
5049              * if mirrors are reconfigured, we can temporarily get out
5050              * of sync in facet_revalidate().  We could "correct" the
5051              * mirror list before reaching here, but doing that would
5052              * not properly account the traffic stats we've currently
5053              * accumulated for previous mirror configuration. */
5054             continue;
5055         }
5056
5057         m->packet_count += packets;
5058         m->byte_count += bytes;
5059     }
5060 }
5061
5062 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
5063  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
5064  * indicate this; newer upstream kernels use gratuitous ARP requests. */
5065 static bool
5066 is_gratuitous_arp(const struct flow *flow)
5067 {
5068     return (flow->dl_type == htons(ETH_TYPE_ARP)
5069             && eth_addr_is_broadcast(flow->dl_dst)
5070             && (flow->nw_proto == ARP_OP_REPLY
5071                 || (flow->nw_proto == ARP_OP_REQUEST
5072                     && flow->nw_src == flow->nw_dst)));
5073 }
5074
5075 static void
5076 update_learning_table(struct ofproto_dpif *ofproto,
5077                       const struct flow *flow, int vlan,
5078                       struct ofbundle *in_bundle)
5079 {
5080     struct mac_entry *mac;
5081
5082     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
5083         return;
5084     }
5085
5086     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
5087     if (is_gratuitous_arp(flow)) {
5088         /* We don't want to learn from gratuitous ARP packets that are
5089          * reflected back over bond slaves so we lock the learning table. */
5090         if (!in_bundle->bond) {
5091             mac_entry_set_grat_arp_lock(mac);
5092         } else if (mac_entry_is_grat_arp_locked(mac)) {
5093             return;
5094         }
5095     }
5096
5097     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
5098         /* The log messages here could actually be useful in debugging,
5099          * so keep the rate limit relatively high. */
5100         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5101         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
5102                     "on port %s in VLAN %d",
5103                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
5104                     in_bundle->name, vlan);
5105
5106         mac->port.p = in_bundle;
5107         tag_set_add(&ofproto->revalidate_set,
5108                     mac_learning_changed(ofproto->ml, mac));
5109     }
5110 }
5111
5112 static struct ofport_dpif *
5113 lookup_input_bundle(struct ofproto_dpif *ofproto, uint16_t in_port, bool warn)
5114 {
5115     struct ofport_dpif *ofport;
5116
5117     /* Find the port and bundle for the received packet. */
5118     ofport = get_ofp_port(ofproto, in_port);
5119     if (ofport && ofport->bundle) {
5120         return ofport;
5121     }
5122
5123     /* Odd.  A few possible reasons here:
5124      *
5125      * - We deleted a port but there are still a few packets queued up
5126      *   from it.
5127      *
5128      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
5129      *   we don't know about.
5130      *
5131      * - The ofproto client didn't configure the port as part of a bundle.
5132      */
5133     if (warn) {
5134         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5135
5136         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
5137                      "port %"PRIu16, ofproto->up.name, in_port);
5138     }
5139     return NULL;
5140 }
5141
5142 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
5143  * dropped.  Returns true if they may be forwarded, false if they should be
5144  * dropped.
5145  *
5146  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
5147  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
5148  *
5149  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
5150  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
5151  * checked by input_vid_is_valid().
5152  *
5153  * May also add tags to '*tags', although the current implementation only does
5154  * so in one special case.
5155  */
5156 static bool
5157 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
5158               struct ofport_dpif *in_port, uint16_t vlan, tag_type *tags)
5159 {
5160     struct ofbundle *in_bundle = in_port->bundle;
5161
5162     /* Drop frames for reserved multicast addresses
5163      * only if forward_bpdu option is absent. */
5164     if (eth_addr_is_reserved(flow->dl_dst) && !ofproto->up.forward_bpdu) {
5165         return false;
5166     }
5167
5168     if (in_bundle->bond) {
5169         struct mac_entry *mac;
5170
5171         switch (bond_check_admissibility(in_bundle->bond, in_port,
5172                                          flow->dl_dst, tags)) {
5173         case BV_ACCEPT:
5174             break;
5175
5176         case BV_DROP:
5177             return false;
5178
5179         case BV_DROP_IF_MOVED:
5180             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
5181             if (mac && mac->port.p != in_bundle &&
5182                 (!is_gratuitous_arp(flow)
5183                  || mac_entry_is_grat_arp_locked(mac))) {
5184                 return false;
5185             }
5186             break;
5187         }
5188     }
5189
5190     return true;
5191 }
5192
5193 static void
5194 xlate_normal(struct action_xlate_ctx *ctx)
5195 {
5196     struct ofport_dpif *in_port;
5197     struct ofbundle *in_bundle;
5198     struct mac_entry *mac;
5199     uint16_t vlan;
5200     uint16_t vid;
5201
5202     ctx->has_normal = true;
5203
5204     /* Obtain in_port from ctx->flow.in_port.
5205      *
5206      * lookup_input_bundle() also ensures that in_port belongs to a bundle. */
5207     in_port = lookup_input_bundle(ctx->ofproto, ctx->flow.in_port,
5208                                   ctx->packet != NULL);
5209     if (!in_port) {
5210         return;
5211     }
5212     in_bundle = in_port->bundle;
5213
5214     /* Drop malformed frames. */
5215     if (ctx->flow.dl_type == htons(ETH_TYPE_VLAN) &&
5216         !(ctx->flow.vlan_tci & htons(VLAN_CFI))) {
5217         if (ctx->packet != NULL) {
5218             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5219             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
5220                          "VLAN tag received on port %s",
5221                          ctx->ofproto->up.name, in_bundle->name);
5222         }
5223         return;
5224     }
5225
5226     /* Drop frames on bundles reserved for mirroring. */
5227     if (in_bundle->mirror_out) {
5228         if (ctx->packet != NULL) {
5229             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5230             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
5231                          "%s, which is reserved exclusively for mirroring",
5232                          ctx->ofproto->up.name, in_bundle->name);
5233         }
5234         return;
5235     }
5236
5237     /* Check VLAN. */
5238     vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
5239     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
5240         return;
5241     }
5242     vlan = input_vid_to_vlan(in_bundle, vid);
5243
5244     /* Check other admissibility requirements. */
5245     if (!is_admissible(ctx->ofproto, &ctx->flow, in_port, vlan, &ctx->tags)) {
5246         return;
5247     }
5248
5249     /* Learn source MAC. */
5250     if (ctx->may_learn) {
5251         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
5252     }
5253
5254     /* Determine output bundle. */
5255     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
5256                               &ctx->tags);
5257     if (mac) {
5258         if (mac->port.p != in_bundle) {
5259             output_normal(ctx, mac->port.p, vlan);
5260         }
5261     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
5262         /* If we are revalidating but don't have a learning entry then eject
5263          * the flow.  Installing a flow that floods packets opens up a window
5264          * of time where we could learn from a packet reflected on a bond and
5265          * blackhole packets before the learning table is updated to reflect
5266          * the correct port. */
5267         ctx->may_set_up_flow = false;
5268         return;
5269     } else {
5270         struct ofbundle *bundle;
5271
5272         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
5273             if (bundle != in_bundle
5274                 && ofbundle_includes_vlan(bundle, vlan)
5275                 && bundle->floodable
5276                 && !bundle->mirror_out) {
5277                 output_normal(ctx, bundle, vlan);
5278             }
5279         }
5280         ctx->nf_output_iface = NF_OUT_FLOOD;
5281     }
5282 }
5283 \f
5284 /* Optimized flow revalidation.
5285  *
5286  * It's a difficult problem, in general, to tell which facets need to have
5287  * their actions recalculated whenever the OpenFlow flow table changes.  We
5288  * don't try to solve that general problem: for most kinds of OpenFlow flow
5289  * table changes, we recalculate the actions for every facet.  This is
5290  * relatively expensive, but it's good enough if the OpenFlow flow table
5291  * doesn't change very often.
5292  *
5293  * However, we can expect one particular kind of OpenFlow flow table change to
5294  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
5295  * of CPU on revalidating every facet whenever MAC learning modifies the flow
5296  * table, we add a special case that applies to flow tables in which every rule
5297  * has the same form (that is, the same wildcards), except that the table is
5298  * also allowed to have a single "catch-all" flow that matches all packets.  We
5299  * optimize this case by tagging all of the facets that resubmit into the table
5300  * and invalidating the same tag whenever a flow changes in that table.  The
5301  * end result is that we revalidate just the facets that need it (and sometimes
5302  * a few more, but not all of the facets or even all of the facets that
5303  * resubmit to the table modified by MAC learning). */
5304
5305 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
5306  * into an OpenFlow table with the given 'basis'. */
5307 static uint32_t
5308 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
5309                    uint32_t secret)
5310 {
5311     if (flow_wildcards_is_catchall(wc)) {
5312         return 0;
5313     } else {
5314         struct flow tag_flow = *flow;
5315         flow_zero_wildcards(&tag_flow, wc);
5316         return tag_create_deterministic(flow_hash(&tag_flow, secret));
5317     }
5318 }
5319
5320 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
5321  * taggability of that table.
5322  *
5323  * This function must be called after *each* change to a flow table.  If you
5324  * skip calling it on some changes then the pointer comparisons at the end can
5325  * be invalid if you get unlucky.  For example, if a flow removal causes a
5326  * cls_table to be destroyed and then a flow insertion causes a cls_table with
5327  * different wildcards to be created with the same address, then this function
5328  * will incorrectly skip revalidation. */
5329 static void
5330 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
5331 {
5332     struct table_dpif *table = &ofproto->tables[table_id];
5333     const struct classifier *cls = &ofproto->up.tables[table_id];
5334     struct cls_table *catchall, *other;
5335     struct cls_table *t;
5336
5337     catchall = other = NULL;
5338
5339     switch (hmap_count(&cls->tables)) {
5340     case 0:
5341         /* We could tag this OpenFlow table but it would make the logic a
5342          * little harder and it's a corner case that doesn't seem worth it
5343          * yet. */
5344         break;
5345
5346     case 1:
5347     case 2:
5348         HMAP_FOR_EACH (t, hmap_node, &cls->tables) {
5349             if (cls_table_is_catchall(t)) {
5350                 catchall = t;
5351             } else if (!other) {
5352                 other = t;
5353             } else {
5354                 /* Indicate that we can't tag this by setting both tables to
5355                  * NULL.  (We know that 'catchall' is already NULL.) */
5356                 other = NULL;
5357             }
5358         }
5359         break;
5360
5361     default:
5362         /* Can't tag this table. */
5363         break;
5364     }
5365
5366     if (table->catchall_table != catchall || table->other_table != other) {
5367         table->catchall_table = catchall;
5368         table->other_table = other;
5369         ofproto->need_revalidate = true;
5370     }
5371 }
5372
5373 /* Given 'rule' that has changed in some way (either it is a rule being
5374  * inserted, a rule being deleted, or a rule whose actions are being
5375  * modified), marks facets for revalidation to ensure that packets will be
5376  * forwarded correctly according to the new state of the flow table.
5377  *
5378  * This function must be called after *each* change to a flow table.  See
5379  * the comment on table_update_taggable() for more information. */
5380 static void
5381 rule_invalidate(const struct rule_dpif *rule)
5382 {
5383     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5384
5385     table_update_taggable(ofproto, rule->up.table_id);
5386
5387     if (!ofproto->need_revalidate) {
5388         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5389
5390         if (table->other_table && rule->tag) {
5391             tag_set_add(&ofproto->revalidate_set, rule->tag);
5392         } else {
5393             ofproto->need_revalidate = true;
5394         }
5395     }
5396 }
5397 \f
5398 static bool
5399 set_frag_handling(struct ofproto *ofproto_,
5400                   enum ofp_config_flags frag_handling)
5401 {
5402     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5403
5404     if (frag_handling != OFPC_FRAG_REASM) {
5405         ofproto->need_revalidate = true;
5406         return true;
5407     } else {
5408         return false;
5409     }
5410 }
5411
5412 static int
5413 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5414            const struct flow *flow,
5415            const union ofp_action *ofp_actions, size_t n_ofp_actions)
5416 {
5417     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5418     int error;
5419
5420     if (flow->in_port >= ofproto->max_ports && flow->in_port < OFPP_MAX) {
5421         return ofp_mkerr_nicira(OFPET_BAD_REQUEST, NXBRC_BAD_IN_PORT);
5422     }
5423
5424     error = validate_actions(ofp_actions, n_ofp_actions, flow,
5425                              ofproto->max_ports);
5426     if (!error) {
5427         struct odputil_keybuf keybuf;
5428         struct action_xlate_ctx ctx;
5429         struct ofpbuf *odp_actions;
5430         struct ofpbuf key;
5431
5432         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5433         odp_flow_key_from_flow(&key, flow);
5434
5435         action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, packet);
5436         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
5437         dpif_execute(ofproto->dpif, key.data, key.size,
5438                      odp_actions->data, odp_actions->size, packet);
5439         ofpbuf_delete(odp_actions);
5440     }
5441     return error;
5442 }
5443 \f
5444 /* NetFlow. */
5445
5446 static int
5447 set_netflow(struct ofproto *ofproto_,
5448             const struct netflow_options *netflow_options)
5449 {
5450     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5451
5452     if (netflow_options) {
5453         if (!ofproto->netflow) {
5454             ofproto->netflow = netflow_create();
5455         }
5456         return netflow_set_options(ofproto->netflow, netflow_options);
5457     } else {
5458         netflow_destroy(ofproto->netflow);
5459         ofproto->netflow = NULL;
5460         return 0;
5461     }
5462 }
5463
5464 static void
5465 get_netflow_ids(const struct ofproto *ofproto_,
5466                 uint8_t *engine_type, uint8_t *engine_id)
5467 {
5468     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5469
5470     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
5471 }
5472
5473 static void
5474 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
5475 {
5476     if (!facet_is_controller_flow(facet) &&
5477         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5478         struct subfacet *subfacet;
5479         struct ofexpired expired;
5480
5481         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5482             if (subfacet->installed) {
5483                 struct dpif_flow_stats stats;
5484
5485                 subfacet_install(ofproto, subfacet, subfacet->actions,
5486                                  subfacet->actions_len, &stats);
5487                 subfacet_update_stats(ofproto, subfacet, &stats);
5488             }
5489         }
5490
5491         expired.flow = facet->flow;
5492         expired.packet_count = facet->packet_count;
5493         expired.byte_count = facet->byte_count;
5494         expired.used = facet->used;
5495         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5496     }
5497 }
5498
5499 static void
5500 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
5501 {
5502     struct facet *facet;
5503
5504     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
5505         send_active_timeout(ofproto, facet);
5506     }
5507 }
5508 \f
5509 static struct ofproto_dpif *
5510 ofproto_dpif_lookup(const char *name)
5511 {
5512     struct ofproto *ofproto = ofproto_lookup(name);
5513     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
5514             ? ofproto_dpif_cast(ofproto)
5515             : NULL);
5516 }
5517
5518 static void
5519 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn,
5520                          const char *args, void *aux OVS_UNUSED)
5521 {
5522     const struct ofproto_dpif *ofproto;
5523
5524     ofproto = ofproto_dpif_lookup(args);
5525     if (!ofproto) {
5526         unixctl_command_reply(conn, 501, "no such bridge");
5527         return;
5528     }
5529     mac_learning_flush(ofproto->ml);
5530
5531     unixctl_command_reply(conn, 200, "table successfully flushed");
5532 }
5533
5534 static void
5535 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
5536                          const char *args, void *aux OVS_UNUSED)
5537 {
5538     struct ds ds = DS_EMPTY_INITIALIZER;
5539     const struct ofproto_dpif *ofproto;
5540     const struct mac_entry *e;
5541
5542     ofproto = ofproto_dpif_lookup(args);
5543     if (!ofproto) {
5544         unixctl_command_reply(conn, 501, "no such bridge");
5545         return;
5546     }
5547
5548     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5549     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5550         struct ofbundle *bundle = e->port.p;
5551         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5552                       ofbundle_get_a_port(bundle)->odp_port,
5553                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
5554     }
5555     unixctl_command_reply(conn, 200, ds_cstr(&ds));
5556     ds_destroy(&ds);
5557 }
5558
5559 struct ofproto_trace {
5560     struct action_xlate_ctx ctx;
5561     struct flow flow;
5562     struct ds *result;
5563 };
5564
5565 static void
5566 trace_format_rule(struct ds *result, uint8_t table_id, int level,
5567                   const struct rule_dpif *rule)
5568 {
5569     ds_put_char_multiple(result, '\t', level);
5570     if (!rule) {
5571         ds_put_cstr(result, "No match\n");
5572         return;
5573     }
5574
5575     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5576                   table_id, ntohll(rule->up.flow_cookie));
5577     cls_rule_format(&rule->up.cr, result);
5578     ds_put_char(result, '\n');
5579
5580     ds_put_char_multiple(result, '\t', level);
5581     ds_put_cstr(result, "OpenFlow ");
5582     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
5583     ds_put_char(result, '\n');
5584 }
5585
5586 static void
5587 trace_format_flow(struct ds *result, int level, const char *title,
5588                  struct ofproto_trace *trace)
5589 {
5590     ds_put_char_multiple(result, '\t', level);
5591     ds_put_format(result, "%s: ", title);
5592     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5593         ds_put_cstr(result, "unchanged");
5594     } else {
5595         flow_format(result, &trace->ctx.flow);
5596         trace->flow = trace->ctx.flow;
5597     }
5598     ds_put_char(result, '\n');
5599 }
5600
5601 static void
5602 trace_format_regs(struct ds *result, int level, const char *title,
5603                   struct ofproto_trace *trace)
5604 {
5605     size_t i;
5606
5607     ds_put_char_multiple(result, '\t', level);
5608     ds_put_format(result, "%s:", title);
5609     for (i = 0; i < FLOW_N_REGS; i++) {
5610         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5611     }
5612     ds_put_char(result, '\n');
5613 }
5614
5615 static void
5616 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
5617 {
5618     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5619     struct ds *result = trace->result;
5620
5621     ds_put_char(result, '\n');
5622     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5623     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
5624     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
5625 }
5626
5627 static void
5628 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5629                       void *aux OVS_UNUSED)
5630 {
5631     char *dpname, *arg1, *arg2, *arg3, *arg4;
5632     char *args = xstrdup(args_);
5633     char *save_ptr = NULL;
5634     struct ofproto_dpif *ofproto;
5635     struct ofpbuf odp_key;
5636     struct ofpbuf *packet;
5637     struct rule_dpif *rule;
5638     ovs_be16 initial_tci;
5639     struct ds result;
5640     struct flow flow;
5641     char *s;
5642
5643     packet = NULL;
5644     ofpbuf_init(&odp_key, 0);
5645     ds_init(&result);
5646
5647     dpname = strtok_r(args, " ", &save_ptr);
5648     if (!dpname) {
5649         unixctl_command_reply(conn, 501, "Bad command syntax");
5650         goto exit;
5651     }
5652
5653     ofproto = ofproto_dpif_lookup(dpname);
5654     if (!ofproto) {
5655         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5656                               "for help)");
5657         goto exit;
5658     }
5659     arg1 = strtok_r(NULL, " ", &save_ptr);
5660     arg2 = strtok_r(NULL, " ", &save_ptr);
5661     arg3 = strtok_r(NULL, " ", &save_ptr);
5662     arg4 = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5663     if (dpname && arg1 && (!arg2 || !strcmp(arg2, "-generate")) && !arg3) {
5664         /* ofproto/trace dpname flow [-generate] */
5665         int error;
5666
5667         /* Convert string to datapath key. */
5668         ofpbuf_init(&odp_key, 0);
5669         error = odp_flow_key_from_string(arg1, NULL, &odp_key);
5670         if (error) {
5671             unixctl_command_reply(conn, 501, "Bad flow syntax");
5672             goto exit;
5673         }
5674
5675         /* Convert odp_key to flow. */
5676         error = ofproto_dpif_extract_flow_key(ofproto, odp_key.data,
5677                                               odp_key.size, &flow,
5678                                               &initial_tci);
5679         if (error == ODP_FIT_ERROR) {
5680             unixctl_command_reply(conn, 501, "Invalid flow");
5681             goto exit;
5682         }
5683
5684         /* Generate a packet, if requested. */
5685         if (arg2) {
5686             packet = ofpbuf_new(0);
5687             flow_compose(packet, &flow);
5688         }
5689     } else if (dpname && arg1 && arg2 && arg3 && arg4) {
5690         /* ofproto/trace dpname priority tun_id in_port packet */
5691         uint16_t in_port;
5692         ovs_be64 tun_id;
5693         uint32_t priority;
5694
5695         priority = atoi(arg1);
5696         tun_id = htonll(strtoull(arg2, NULL, 0));
5697         in_port = ofp_port_to_odp_port(atoi(arg3));
5698
5699         packet = ofpbuf_new(strlen(args) / 2);
5700         arg4 = ofpbuf_put_hex(packet, arg4, NULL);
5701         arg4 += strspn(arg4, " ");
5702         if (*arg4 != '\0') {
5703             unixctl_command_reply(conn, 501, "Trailing garbage in command");
5704             goto exit;
5705         }
5706         if (packet->size < ETH_HEADER_LEN) {
5707             unixctl_command_reply(conn, 501,
5708                                   "Packet data too short for Ethernet");
5709             goto exit;
5710         }
5711
5712         ds_put_cstr(&result, "Packet: ");
5713         s = ofp_packet_to_string(packet->data, packet->size, packet->size);
5714         ds_put_cstr(&result, s);
5715         free(s);
5716
5717         flow_extract(packet, priority, tun_id, in_port, &flow);
5718         initial_tci = flow.vlan_tci;
5719     } else {
5720         unixctl_command_reply(conn, 501, "Bad command syntax");
5721         goto exit;
5722     }
5723
5724     ds_put_cstr(&result, "Flow: ");
5725     flow_format(&result, &flow);
5726     ds_put_char(&result, '\n');
5727
5728     rule = rule_dpif_lookup(ofproto, &flow, 0);
5729     trace_format_rule(&result, 0, 0, rule);
5730     if (rule) {
5731         struct ofproto_trace trace;
5732         struct ofpbuf *odp_actions;
5733
5734         trace.result = &result;
5735         trace.flow = flow;
5736         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, initial_tci, packet);
5737         trace.ctx.resubmit_hook = trace_resubmit;
5738         odp_actions = xlate_actions(&trace.ctx,
5739                                     rule->up.actions, rule->up.n_actions);
5740
5741         ds_put_char(&result, '\n');
5742         trace_format_flow(&result, 0, "Final flow", &trace);
5743         ds_put_cstr(&result, "Datapath actions: ");
5744         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5745         ofpbuf_delete(odp_actions);
5746
5747         if (!trace.ctx.may_set_up_flow) {
5748             if (packet) {
5749                 ds_put_cstr(&result, "\nThis flow is not cachable.");
5750             } else {
5751                 ds_put_cstr(&result, "\nThe datapath actions are incomplete--"
5752                             "for complete actions, please supply a packet.");
5753             }
5754         }
5755     }
5756
5757     unixctl_command_reply(conn, 200, ds_cstr(&result));
5758
5759 exit:
5760     ds_destroy(&result);
5761     ofpbuf_delete(packet);
5762     ofpbuf_uninit(&odp_key);
5763     free(args);
5764 }
5765
5766 static void
5767 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED,
5768                   const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5769 {
5770     clogged = true;
5771     unixctl_command_reply(conn, 200, NULL);
5772 }
5773
5774 static void
5775 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED,
5776                     const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5777 {
5778     clogged = false;
5779     unixctl_command_reply(conn, 200, NULL);
5780 }
5781
5782 static void
5783 ofproto_dpif_unixctl_init(void)
5784 {
5785     static bool registered;
5786     if (registered) {
5787         return;
5788     }
5789     registered = true;
5790
5791     unixctl_command_register("ofproto/trace",
5792                       "bridge {tun_id in_port packet | odp_flow [-generate]}",
5793                       ofproto_unixctl_trace, NULL);
5794     unixctl_command_register("fdb/flush", "bridge", ofproto_unixctl_fdb_flush,
5795                              NULL);
5796     unixctl_command_register("fdb/show", "bridge", ofproto_unixctl_fdb_show,
5797                              NULL);
5798     unixctl_command_register("ofproto/clog", "", ofproto_dpif_clog, NULL);
5799     unixctl_command_register("ofproto/unclog", "", ofproto_dpif_unclog, NULL);
5800 }
5801 \f
5802 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5803  *
5804  * This is deprecated.  It is only for compatibility with broken device drivers
5805  * in old versions of Linux that do not properly support VLANs when VLAN
5806  * devices are not used.  When broken device drivers are no longer in
5807  * widespread use, we will delete these interfaces. */
5808
5809 static int
5810 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
5811 {
5812     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
5813     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
5814
5815     if (realdev_ofp_port == ofport->realdev_ofp_port
5816         && vid == ofport->vlandev_vid) {
5817         return 0;
5818     }
5819
5820     ofproto->need_revalidate = true;
5821
5822     if (ofport->realdev_ofp_port) {
5823         vsp_remove(ofport);
5824     }
5825     if (realdev_ofp_port && ofport->bundle) {
5826         /* vlandevs are enslaved to their realdevs, so they are not allowed to
5827          * themselves be part of a bundle. */
5828         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
5829     }
5830
5831     ofport->realdev_ofp_port = realdev_ofp_port;
5832     ofport->vlandev_vid = vid;
5833
5834     if (realdev_ofp_port) {
5835         vsp_add(ofport, realdev_ofp_port, vid);
5836     }
5837
5838     return 0;
5839 }
5840
5841 static uint32_t
5842 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
5843 {
5844     return hash_2words(realdev_ofp_port, vid);
5845 }
5846
5847 static uint32_t
5848 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
5849                        uint32_t realdev_odp_port, ovs_be16 vlan_tci)
5850 {
5851     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
5852         uint16_t realdev_ofp_port = odp_port_to_ofp_port(realdev_odp_port);
5853         int vid = vlan_tci_to_vid(vlan_tci);
5854         const struct vlan_splinter *vsp;
5855
5856         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
5857                                  hash_realdev_vid(realdev_ofp_port, vid),
5858                                  &ofproto->realdev_vid_map) {
5859             if (vsp->realdev_ofp_port == realdev_ofp_port
5860                 && vsp->vid == vid) {
5861                 return ofp_port_to_odp_port(vsp->vlandev_ofp_port);
5862             }
5863         }
5864     }
5865     return realdev_odp_port;
5866 }
5867
5868 static struct vlan_splinter *
5869 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
5870 {
5871     struct vlan_splinter *vsp;
5872
5873     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
5874                              &ofproto->vlandev_map) {
5875         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
5876             return vsp;
5877         }
5878     }
5879
5880     return NULL;
5881 }
5882
5883 static uint16_t
5884 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
5885                    uint16_t vlandev_ofp_port, int *vid)
5886 {
5887     if (!hmap_is_empty(&ofproto->vlandev_map)) {
5888         const struct vlan_splinter *vsp;
5889
5890         vsp = vlandev_find(ofproto, vlandev_ofp_port);
5891         if (vsp) {
5892             if (vid) {
5893                 *vid = vsp->vid;
5894             }
5895             return vsp->realdev_ofp_port;
5896         }
5897     }
5898     return 0;
5899 }
5900
5901 static void
5902 vsp_remove(struct ofport_dpif *port)
5903 {
5904     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5905     struct vlan_splinter *vsp;
5906
5907     vsp = vlandev_find(ofproto, port->up.ofp_port);
5908     if (vsp) {
5909         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
5910         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
5911         free(vsp);
5912
5913         port->realdev_ofp_port = 0;
5914     } else {
5915         VLOG_ERR("missing vlan device record");
5916     }
5917 }
5918
5919 static void
5920 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
5921 {
5922     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5923
5924     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
5925         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
5926             == realdev_ofp_port)) {
5927         struct vlan_splinter *vsp;
5928
5929         vsp = xmalloc(sizeof *vsp);
5930         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
5931                     hash_int(port->up.ofp_port, 0));
5932         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
5933                     hash_realdev_vid(realdev_ofp_port, vid));
5934         vsp->realdev_ofp_port = realdev_ofp_port;
5935         vsp->vlandev_ofp_port = port->up.ofp_port;
5936         vsp->vid = vid;
5937
5938         port->realdev_ofp_port = realdev_ofp_port;
5939     } else {
5940         VLOG_ERR("duplicate vlan device record");
5941     }
5942 }
5943 \f
5944 const struct ofproto_class ofproto_dpif_class = {
5945     enumerate_types,
5946     enumerate_names,
5947     del,
5948     alloc,
5949     construct,
5950     destruct,
5951     dealloc,
5952     run,
5953     run_fast,
5954     wait,
5955     flush,
5956     get_features,
5957     get_tables,
5958     port_alloc,
5959     port_construct,
5960     port_destruct,
5961     port_dealloc,
5962     port_modified,
5963     port_reconfigured,
5964     port_query_by_name,
5965     port_add,
5966     port_del,
5967     port_get_stats,
5968     port_dump_start,
5969     port_dump_next,
5970     port_dump_done,
5971     port_poll,
5972     port_poll_wait,
5973     port_is_lacp_current,
5974     NULL,                       /* rule_choose_table */
5975     rule_alloc,
5976     rule_construct,
5977     rule_destruct,
5978     rule_dealloc,
5979     rule_get_stats,
5980     rule_execute,
5981     rule_modify_actions,
5982     set_frag_handling,
5983     packet_out,
5984     set_netflow,
5985     get_netflow_ids,
5986     set_sflow,
5987     set_cfm,
5988     get_cfm_fault,
5989     get_cfm_remote_mpids,
5990     set_stp,
5991     get_stp_status,
5992     set_stp_port,
5993     get_stp_port_status,
5994     set_queues,
5995     bundle_set,
5996     bundle_remove,
5997     mirror_set,
5998     mirror_get_stats,
5999     set_flood_vlans,
6000     is_mirror_output_bundle,
6001     forward_bpdu_changed,
6002     set_realdev,
6003 };