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