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