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