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