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