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