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