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