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