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