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