ofproto-dpif: Fix in-band action for sFlow.
[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 16
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         case OVS_ACTION_ATTR_OUTPUT:
2607             port = get_odp_port(ofproto, nl_attr_get_u32(a));
2608             if (port && port->bundle && port->bundle->bond) {
2609                 bond_account(port->bundle->bond, &facet->flow,
2610                              vlan_tci_to_vid(vlan_tci), n_bytes);
2611             }
2612             break;
2613
2614         case OVS_ACTION_ATTR_POP_VLAN:
2615             vlan_tci = htons(0);
2616             break;
2617
2618         case OVS_ACTION_ATTR_PUSH_VLAN:
2619             vlan_tci = nl_attr_get_be16(a);
2620             break;
2621         }
2622     }
2623 }
2624
2625 /* If 'rule' is installed in the datapath, uninstalls it. */
2626 static void
2627 facet_uninstall(struct ofproto_dpif *p, struct facet *facet)
2628 {
2629     if (facet->installed) {
2630         struct odputil_keybuf keybuf;
2631         struct dpif_flow_stats stats;
2632         struct ofpbuf key;
2633         int error;
2634
2635         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2636         odp_flow_key_from_flow(&key, &facet->flow);
2637
2638         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
2639         facet_reset_dp_stats(facet, &stats);
2640         if (!error) {
2641             facet_update_stats(p, facet, &stats);
2642         }
2643         facet->installed = false;
2644     } else {
2645         assert(facet->dp_packet_count == 0);
2646         assert(facet->dp_byte_count == 0);
2647     }
2648 }
2649
2650 /* Returns true if the only action for 'facet' is to send to the controller.
2651  * (We don't report NetFlow expiration messages for such facets because they
2652  * are just part of the control logic for the network, not real traffic). */
2653 static bool
2654 facet_is_controller_flow(struct facet *facet)
2655 {
2656     return (facet
2657             && facet->rule->up.n_actions == 1
2658             && action_outputs_to_port(&facet->rule->up.actions[0],
2659                                       htons(OFPP_CONTROLLER)));
2660 }
2661
2662 /* Resets 'facet''s datapath statistics counters.  This should be called when
2663  * 'facet''s statistics are cleared in the datapath.  If 'stats' is non-null,
2664  * it should contain the statistics returned by dpif when 'facet' was reset in
2665  * the datapath.  'stats' will be modified to only included statistics new
2666  * since 'facet' was last updated. */
2667 static void
2668 facet_reset_dp_stats(struct facet *facet, struct dpif_flow_stats *stats)
2669 {
2670     if (stats && facet->dp_packet_count <= stats->n_packets
2671         && facet->dp_byte_count <= stats->n_bytes) {
2672         stats->n_packets -= facet->dp_packet_count;
2673         stats->n_bytes -= facet->dp_byte_count;
2674     }
2675
2676     facet->dp_packet_count = 0;
2677     facet->dp_byte_count = 0;
2678 }
2679
2680 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2681  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
2682  * 'facet''s statistics in the datapath should have been zeroed and folded into
2683  * its packet and byte counts before this function is called. */
2684 static void
2685 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
2686 {
2687     assert(!facet->dp_byte_count);
2688     assert(!facet->dp_packet_count);
2689
2690     facet_push_stats(facet);
2691     facet_account(ofproto, facet);
2692
2693     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2694         struct ofexpired expired;
2695         expired.flow = facet->flow;
2696         expired.packet_count = facet->packet_count;
2697         expired.byte_count = facet->byte_count;
2698         expired.used = facet->used;
2699         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2700     }
2701
2702     facet->rule->packet_count += facet->packet_count;
2703     facet->rule->byte_count += facet->byte_count;
2704
2705     /* Reset counters to prevent double counting if 'facet' ever gets
2706      * reinstalled. */
2707     facet_reset_counters(facet);
2708
2709     netflow_flow_clear(&facet->nf_flow);
2710 }
2711
2712 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2713  * Returns it if found, otherwise a null pointer.
2714  *
2715  * The returned facet might need revalidation; use facet_lookup_valid()
2716  * instead if that is important. */
2717 static struct facet *
2718 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
2719 {
2720     struct facet *facet;
2721
2722     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2723                              &ofproto->facets) {
2724         if (flow_equal(flow, &facet->flow)) {
2725             return facet;
2726         }
2727     }
2728
2729     return NULL;
2730 }
2731
2732 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2733  * Returns it if found, otherwise a null pointer.
2734  *
2735  * The returned facet is guaranteed to be valid. */
2736 static struct facet *
2737 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
2738 {
2739     struct facet *facet = facet_find(ofproto, flow);
2740
2741     /* The facet we found might not be valid, since we could be in need of
2742      * revalidation.  If it is not valid, don't return it. */
2743     if (facet
2744         && (ofproto->need_revalidate
2745             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
2746         && !facet_revalidate(ofproto, facet)) {
2747         COVERAGE_INC(facet_invalidated);
2748         return NULL;
2749     }
2750
2751     return facet;
2752 }
2753
2754 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2755  *
2756  *   - If the rule found is different from 'facet''s current rule, moves
2757  *     'facet' to the new rule and recompiles its actions.
2758  *
2759  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2760  *     where it is and recompiles its actions anyway.
2761  *
2762  *   - If there is none, destroys 'facet'.
2763  *
2764  * Returns true if 'facet' still exists, false if it has been destroyed. */
2765 static bool
2766 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
2767 {
2768     struct action_xlate_ctx ctx;
2769     struct ofpbuf *odp_actions;
2770     struct rule_dpif *new_rule;
2771     bool actions_changed;
2772
2773     COVERAGE_INC(facet_revalidate);
2774
2775     /* Determine the new rule. */
2776     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
2777     if (!new_rule) {
2778         /* No new rule, so delete the facet. */
2779         facet_remove(ofproto, facet);
2780         return false;
2781     }
2782
2783     /* Calculate new datapath actions.
2784      *
2785      * We do not modify any 'facet' state yet, because we might need to, e.g.,
2786      * emit a NetFlow expiration and, if so, we need to have the old state
2787      * around to properly compose it. */
2788     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2789     odp_actions = xlate_actions(&ctx,
2790                                 new_rule->up.actions, new_rule->up.n_actions);
2791     actions_changed = (facet->actions_len != odp_actions->size
2792                        || memcmp(facet->actions, odp_actions->data,
2793                                  facet->actions_len));
2794
2795     /* If the datapath actions changed or the installability changed,
2796      * then we need to talk to the datapath. */
2797     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
2798         if (ctx.may_set_up_flow) {
2799             struct dpif_flow_stats stats;
2800
2801             facet_put__(ofproto, facet,
2802                         odp_actions->data, odp_actions->size, &stats);
2803             facet_update_stats(ofproto, facet, &stats);
2804         } else {
2805             facet_uninstall(ofproto, facet);
2806         }
2807
2808         /* The datapath flow is gone or has zeroed stats, so push stats out of
2809          * 'facet' into 'rule'. */
2810         facet_flush_stats(ofproto, facet);
2811     }
2812
2813     /* Update 'facet' now that we've taken care of all the old state. */
2814     facet->tags = ctx.tags;
2815     facet->nf_flow.output_iface = ctx.nf_output_iface;
2816     facet->may_install = ctx.may_set_up_flow;
2817     facet->has_learn = ctx.has_learn;
2818     facet->has_normal = ctx.has_normal;
2819     if (actions_changed) {
2820         free(facet->actions);
2821         facet->actions_len = odp_actions->size;
2822         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2823     }
2824     if (facet->rule != new_rule) {
2825         COVERAGE_INC(facet_changed_rule);
2826         list_remove(&facet->list_node);
2827         list_push_back(&new_rule->facets, &facet->list_node);
2828         facet->rule = new_rule;
2829         facet->used = new_rule->up.created;
2830         facet->rs_used = facet->used;
2831     }
2832
2833     ofpbuf_delete(odp_actions);
2834
2835     return true;
2836 }
2837
2838 /* Updates 'facet''s used time.  Caller is responsible for calling
2839  * facet_push_stats() to update the flows which 'facet' resubmits into. */
2840 static void
2841 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
2842                   long long int used)
2843 {
2844     if (used > facet->used) {
2845         facet->used = used;
2846         if (used > facet->rule->used) {
2847             facet->rule->used = used;
2848         }
2849         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
2850     }
2851 }
2852
2853 /* Folds the statistics from 'stats' into the counters in 'facet'.
2854  *
2855  * Because of the meaning of a facet's counters, it only makes sense to do this
2856  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
2857  * packet that was sent by hand or if it represents statistics that have been
2858  * cleared out of the datapath. */
2859 static void
2860 facet_update_stats(struct ofproto_dpif *ofproto, struct facet *facet,
2861                    const struct dpif_flow_stats *stats)
2862 {
2863     if (stats->n_packets || stats->used > facet->used) {
2864         facet_update_time(ofproto, facet, stats->used);
2865         facet->packet_count += stats->n_packets;
2866         facet->byte_count += stats->n_bytes;
2867         facet_push_stats(facet);
2868         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
2869     }
2870 }
2871
2872 static void
2873 facet_reset_counters(struct facet *facet)
2874 {
2875     facet->packet_count = 0;
2876     facet->byte_count = 0;
2877     facet->rs_packet_count = 0;
2878     facet->rs_byte_count = 0;
2879     facet->accounted_bytes = 0;
2880 }
2881
2882 static void
2883 facet_push_stats(struct facet *facet)
2884 {
2885     uint64_t rs_packets, rs_bytes;
2886
2887     assert(facet->packet_count >= facet->rs_packet_count);
2888     assert(facet->byte_count >= facet->rs_byte_count);
2889     assert(facet->used >= facet->rs_used);
2890
2891     rs_packets = facet->packet_count - facet->rs_packet_count;
2892     rs_bytes = facet->byte_count - facet->rs_byte_count;
2893
2894     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
2895         facet->rs_packet_count = facet->packet_count;
2896         facet->rs_byte_count = facet->byte_count;
2897         facet->rs_used = facet->used;
2898
2899         flow_push_stats(facet->rule, &facet->flow,
2900                         rs_packets, rs_bytes, facet->used);
2901     }
2902 }
2903
2904 struct ofproto_push {
2905     struct action_xlate_ctx ctx;
2906     uint64_t packets;
2907     uint64_t bytes;
2908     long long int used;
2909 };
2910
2911 static void
2912 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
2913 {
2914     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
2915
2916     if (rule) {
2917         rule->packet_count += push->packets;
2918         rule->byte_count += push->bytes;
2919         rule->used = MAX(push->used, rule->used);
2920     }
2921 }
2922
2923 /* Pushes flow statistics to the rules which 'flow' resubmits into given
2924  * 'rule''s actions. */
2925 static void
2926 flow_push_stats(const struct rule_dpif *rule,
2927                 struct flow *flow, uint64_t packets, uint64_t bytes,
2928                 long long int used)
2929 {
2930     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2931     struct ofproto_push push;
2932
2933     push.packets = packets;
2934     push.bytes = bytes;
2935     push.used = used;
2936
2937     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
2938     push.ctx.resubmit_hook = push_resubmit;
2939     ofpbuf_delete(xlate_actions(&push.ctx,
2940                                 rule->up.actions, rule->up.n_actions));
2941 }
2942 \f
2943 /* Rules. */
2944
2945 static struct rule_dpif *
2946 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
2947                  uint8_t table_id)
2948 {
2949     if (table_id >= N_TABLES) {
2950         return NULL;
2951     }
2952
2953     return rule_dpif_cast(rule_from_cls_rule(
2954                               classifier_lookup(&ofproto->up.tables[table_id],
2955                                                 flow)));
2956 }
2957
2958 static void
2959 complete_operation(struct rule_dpif *rule)
2960 {
2961     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2962
2963     rule_invalidate(rule);
2964     if (clogged) {
2965         struct dpif_completion *c = xmalloc(sizeof *c);
2966         c->op = rule->up.pending;
2967         list_push_back(&ofproto->completions, &c->list_node);
2968     } else {
2969         ofoperation_complete(rule->up.pending, 0);
2970     }
2971 }
2972
2973 static struct rule *
2974 rule_alloc(void)
2975 {
2976     struct rule_dpif *rule = xmalloc(sizeof *rule);
2977     return &rule->up;
2978 }
2979
2980 static void
2981 rule_dealloc(struct rule *rule_)
2982 {
2983     struct rule_dpif *rule = rule_dpif_cast(rule_);
2984     free(rule);
2985 }
2986
2987 static int
2988 rule_construct(struct rule *rule_)
2989 {
2990     struct rule_dpif *rule = rule_dpif_cast(rule_);
2991     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2992     struct rule_dpif *victim;
2993     uint8_t table_id;
2994     int error;
2995
2996     error = validate_actions(rule->up.actions, rule->up.n_actions,
2997                              &rule->up.cr.flow, ofproto->max_ports);
2998     if (error) {
2999         return error;
3000     }
3001
3002     rule->used = rule->up.created;
3003     rule->packet_count = 0;
3004     rule->byte_count = 0;
3005
3006     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
3007     if (victim && !list_is_empty(&victim->facets)) {
3008         struct facet *facet;
3009
3010         rule->facets = victim->facets;
3011         list_moved(&rule->facets);
3012         LIST_FOR_EACH (facet, list_node, &rule->facets) {
3013             /* XXX: We're only clearing our local counters here.  It's possible
3014              * that quite a few packets are unaccounted for in the datapath
3015              * statistics.  These will be accounted to the new rule instead of
3016              * cleared as required.  This could be fixed by clearing out the
3017              * datapath statistics for this facet, but currently it doesn't
3018              * seem worth it. */
3019             facet_reset_counters(facet);
3020             facet->rule = rule;
3021         }
3022     } else {
3023         /* Must avoid list_moved() in this case. */
3024         list_init(&rule->facets);
3025     }
3026
3027     table_id = rule->up.table_id;
3028     rule->tag = (victim ? victim->tag
3029                  : table_id == 0 ? 0
3030                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
3031                                       ofproto->tables[table_id].basis));
3032
3033     complete_operation(rule);
3034     return 0;
3035 }
3036
3037 static void
3038 rule_destruct(struct rule *rule_)
3039 {
3040     struct rule_dpif *rule = rule_dpif_cast(rule_);
3041     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3042     struct facet *facet, *next_facet;
3043
3044     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3045         facet_revalidate(ofproto, facet);
3046     }
3047
3048     complete_operation(rule);
3049 }
3050
3051 static void
3052 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3053 {
3054     struct rule_dpif *rule = rule_dpif_cast(rule_);
3055     struct facet *facet;
3056
3057     /* Start from historical data for 'rule' itself that are no longer tracked
3058      * in facets.  This counts, for example, facets that have expired. */
3059     *packets = rule->packet_count;
3060     *bytes = rule->byte_count;
3061
3062     /* Add any statistics that are tracked by facets.  This includes
3063      * statistical data recently updated by ofproto_update_stats() as well as
3064      * stats for packets that were executed "by hand" via dpif_execute(). */
3065     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3066         *packets += facet->packet_count;
3067         *bytes += facet->byte_count;
3068     }
3069 }
3070
3071 static int
3072 rule_execute(struct rule *rule_, struct flow *flow, struct ofpbuf *packet)
3073 {
3074     struct rule_dpif *rule = rule_dpif_cast(rule_);
3075     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3076     struct action_xlate_ctx ctx;
3077     struct ofpbuf *odp_actions;
3078     struct facet *facet;
3079     size_t size;
3080
3081     /* First look for a related facet.  If we find one, account it to that. */
3082     facet = facet_lookup_valid(ofproto, flow);
3083     if (facet && facet->rule == rule) {
3084         if (!facet->may_install) {
3085             facet_make_actions(ofproto, facet, packet);
3086         }
3087         facet_execute(ofproto, facet, packet);
3088         return 0;
3089     }
3090
3091     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
3092      * create a new facet for it and use that. */
3093     if (rule_dpif_lookup(ofproto, flow, 0) == rule) {
3094         facet = facet_create(rule, flow);
3095         facet_make_actions(ofproto, facet, packet);
3096         facet_execute(ofproto, facet, packet);
3097         facet_install(ofproto, facet, true);
3098         return 0;
3099     }
3100
3101     /* We can't account anything to a facet.  If we were to try, then that
3102      * facet would have a non-matching rule, busting our invariants. */
3103     action_xlate_ctx_init(&ctx, ofproto, flow, packet);
3104     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3105     size = packet->size;
3106     if (execute_odp_actions(ofproto, flow, odp_actions->data,
3107                             odp_actions->size, packet)) {
3108         rule->used = time_msec();
3109         rule->packet_count++;
3110         rule->byte_count += size;
3111         flow_push_stats(rule, flow, 1, size, rule->used);
3112     }
3113     ofpbuf_delete(odp_actions);
3114
3115     return 0;
3116 }
3117
3118 static void
3119 rule_modify_actions(struct rule *rule_)
3120 {
3121     struct rule_dpif *rule = rule_dpif_cast(rule_);
3122     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3123     int error;
3124
3125     error = validate_actions(rule->up.actions, rule->up.n_actions,
3126                              &rule->up.cr.flow, ofproto->max_ports);
3127     if (error) {
3128         ofoperation_complete(rule->up.pending, error);
3129         return;
3130     }
3131
3132     complete_operation(rule);
3133 }
3134 \f
3135 /* Sends 'packet' out of port 'odp_port' within 'ofproto'.
3136  * Returns 0 if successful, otherwise a positive errno value. */
3137 static int
3138 send_packet(struct ofproto_dpif *ofproto, uint32_t odp_port,
3139             const struct ofpbuf *packet)
3140 {
3141     struct ofpbuf key, odp_actions;
3142     struct odputil_keybuf keybuf;
3143     struct flow flow;
3144     int error;
3145
3146     flow_extract((struct ofpbuf *) packet, 0, 0, &flow);
3147     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3148     odp_flow_key_from_flow(&key, &flow);
3149
3150     ofpbuf_init(&odp_actions, 32);
3151     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
3152
3153     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3154     error = dpif_execute(ofproto->dpif,
3155                          key.data, key.size,
3156                          odp_actions.data, odp_actions.size,
3157                          packet);
3158     ofpbuf_uninit(&odp_actions);
3159
3160     if (error) {
3161         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
3162                      ofproto->up.name, odp_port, strerror(error));
3163     }
3164     return error;
3165 }
3166 \f
3167 /* OpenFlow to datapath action translation. */
3168
3169 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3170                              struct action_xlate_ctx *ctx);
3171 static void xlate_normal(struct action_xlate_ctx *);
3172
3173 static size_t
3174 put_userspace_action(const struct ofproto_dpif *ofproto,
3175                      struct ofpbuf *odp_actions,
3176                      const struct flow *flow,
3177                      const struct user_action_cookie *cookie)
3178 {
3179     size_t offset;
3180     uint32_t pid;
3181
3182     pid = dpif_port_get_pid(ofproto->dpif,
3183                             ofp_port_to_odp_port(flow->in_port));
3184
3185     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
3186     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
3187     nl_msg_put_unspec(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
3188                       cookie, sizeof *cookie);
3189     nl_msg_end_nested(odp_actions, offset);
3190
3191     return odp_actions->size - NLA_ALIGN(sizeof *cookie);
3192 }
3193
3194 /* Compose SAMPLE action for sFlow. */
3195 static size_t
3196 compose_sflow_action(const struct ofproto_dpif *ofproto,
3197                      struct ofpbuf *odp_actions,
3198                      const struct flow *flow,
3199                      uint32_t odp_port)
3200 {
3201     uint32_t port_ifindex;
3202     uint32_t probability;
3203     struct user_action_cookie cookie;
3204     size_t sample_offset, actions_offset;
3205     int cookie_offset, n_output;
3206
3207     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
3208         return 0;
3209     }
3210
3211     if (odp_port == OVSP_NONE) {
3212         port_ifindex = 0;
3213         n_output = 0;
3214     } else {
3215         port_ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
3216         n_output = 1;
3217     }
3218
3219     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
3220
3221     /* Number of packets out of UINT_MAX to sample. */
3222     probability = dpif_sflow_get_probability(ofproto->sflow);
3223     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
3224
3225     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
3226
3227     cookie.type = USER_ACTION_COOKIE_SFLOW;
3228     cookie.data = port_ifindex;
3229     cookie.n_output = n_output;
3230     cookie.vlan_tci = 0;
3231     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
3232
3233     nl_msg_end_nested(odp_actions, actions_offset);
3234     nl_msg_end_nested(odp_actions, sample_offset);
3235     return cookie_offset;
3236 }
3237
3238 /* SAMPLE action must be first action in any given list of actions.
3239  * At this point we do not have all information required to build it. So try to
3240  * build sample action as complete as possible. */
3241 static void
3242 add_sflow_action(struct action_xlate_ctx *ctx)
3243 {
3244     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
3245                                                    ctx->odp_actions,
3246                                                    &ctx->flow, OVSP_NONE);
3247     ctx->sflow_odp_port = 0;
3248     ctx->sflow_n_outputs = 0;
3249 }
3250
3251 /* Fix SAMPLE action according to data collected while composing ODP actions.
3252  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
3253  * USERSPACE action's user-cookie which is required for sflow. */
3254 static void
3255 fix_sflow_action(struct action_xlate_ctx *ctx)
3256 {
3257     const struct flow *base = &ctx->base_flow;
3258     struct user_action_cookie *cookie;
3259
3260     if (!ctx->user_cookie_offset) {
3261         return;
3262     }
3263
3264     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
3265                      sizeof(*cookie));
3266     assert(cookie != NULL);
3267     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
3268
3269     if (ctx->sflow_n_outputs) {
3270         cookie->data = dpif_sflow_odp_port_to_ifindex(ctx->ofproto->sflow,
3271                                                     ctx->sflow_odp_port);
3272     }
3273     if (ctx->sflow_n_outputs >= 255) {
3274         cookie->n_output = 255;
3275     } else {
3276         cookie->n_output = ctx->sflow_n_outputs;
3277     }
3278     cookie->vlan_tci = base->vlan_tci;
3279 }
3280
3281 static void
3282 commit_vlan_tci(struct action_xlate_ctx *ctx, ovs_be16 vlan_tci)
3283 {
3284     struct flow *base = &ctx->base_flow;
3285     struct ofpbuf *odp_actions = ctx->odp_actions;
3286
3287     if (base->vlan_tci != vlan_tci) {
3288         if (!(vlan_tci & htons(VLAN_CFI))) {
3289             nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
3290         } else {
3291             if (base->vlan_tci != htons(0)) {
3292                 nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
3293             }
3294             nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
3295                             vlan_tci & ~htons(VLAN_CFI));
3296         }
3297         base->vlan_tci = vlan_tci;
3298     }
3299 }
3300
3301 static void
3302 commit_odp_actions(struct action_xlate_ctx *ctx)
3303 {
3304     const struct flow *flow = &ctx->flow;
3305     struct flow *base = &ctx->base_flow;
3306     struct ofpbuf *odp_actions = ctx->odp_actions;
3307
3308     if (base->tun_id != flow->tun_id) {
3309         nl_msg_put_be64(odp_actions, OVS_ACTION_ATTR_SET_TUNNEL, flow->tun_id);
3310         base->tun_id = flow->tun_id;
3311     }
3312
3313     if (base->nw_src != flow->nw_src) {
3314         nl_msg_put_be32(odp_actions, OVS_ACTION_ATTR_SET_NW_SRC, flow->nw_src);
3315         base->nw_src = flow->nw_src;
3316     }
3317
3318     if (base->nw_dst != flow->nw_dst) {
3319         nl_msg_put_be32(odp_actions, OVS_ACTION_ATTR_SET_NW_DST, flow->nw_dst);
3320         base->nw_dst = flow->nw_dst;
3321     }
3322
3323     if (base->nw_tos != flow->nw_tos) {
3324         nl_msg_put_u8(odp_actions, OVS_ACTION_ATTR_SET_NW_TOS, flow->nw_tos);
3325         base->nw_tos = flow->nw_tos;
3326     }
3327
3328     commit_vlan_tci(ctx, flow->vlan_tci);
3329
3330     if (base->tp_src != flow->tp_src) {
3331         nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_SET_TP_SRC, flow->tp_src);
3332         base->tp_src = flow->tp_src;
3333     }
3334
3335     if (base->tp_dst != flow->tp_dst) {
3336         nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_SET_TP_DST, flow->tp_dst);
3337         base->tp_dst = flow->tp_dst;
3338     }
3339
3340     if (!eth_addr_equals(base->dl_src, flow->dl_src)) {
3341         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_SET_DL_SRC,
3342                           flow->dl_src, ETH_ADDR_LEN);
3343         memcpy(base->dl_src, flow->dl_src, ETH_ADDR_LEN);
3344     }
3345
3346     if (!eth_addr_equals(base->dl_dst, flow->dl_dst)) {
3347         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_SET_DL_DST,
3348                           flow->dl_dst, ETH_ADDR_LEN);
3349         memcpy(base->dl_dst, flow->dl_dst, ETH_ADDR_LEN);
3350     }
3351
3352     if (ctx->base_priority != ctx->priority) {
3353         if (ctx->priority) {
3354             nl_msg_put_u32(odp_actions, OVS_ACTION_ATTR_SET_PRIORITY,
3355                            ctx->priority);
3356         } else {
3357             nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_PRIORITY);
3358         }
3359         ctx->base_priority = ctx->priority;
3360     }
3361 }
3362
3363 static void
3364 compose_output_action(struct action_xlate_ctx *ctx, uint16_t odp_port)
3365 {
3366     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3367     ctx->sflow_odp_port = odp_port;
3368     ctx->sflow_n_outputs++;
3369 }
3370
3371 static void
3372 add_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
3373 {
3374     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
3375     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
3376
3377     if (ofport) {
3378         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)) {
3379             /* Forwarding disabled on port. */
3380             return;
3381         }
3382     } else {
3383         /*
3384          * We don't have an ofport record for this port, but it doesn't hurt to
3385          * allow forwarding to it anyhow.  Maybe such a port will appear later
3386          * and we're pre-populating the flow table.
3387          */
3388     }
3389
3390     commit_odp_actions(ctx);
3391     compose_output_action(ctx, odp_port);
3392     ctx->nf_output_iface = ofp_port;
3393 }
3394
3395 static void
3396 xlate_table_action(struct action_xlate_ctx *ctx,
3397                    uint16_t in_port, uint8_t table_id)
3398 {
3399     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
3400         struct ofproto_dpif *ofproto = ctx->ofproto;
3401         struct rule_dpif *rule;
3402         uint16_t old_in_port;
3403         uint8_t old_table_id;
3404
3405         old_table_id = ctx->table_id;
3406         ctx->table_id = table_id;
3407
3408         /* Look up a flow with 'in_port' as the input port. */
3409         old_in_port = ctx->flow.in_port;
3410         ctx->flow.in_port = in_port;
3411         rule = rule_dpif_lookup(ofproto, &ctx->flow, table_id);
3412
3413         /* Tag the flow. */
3414         if (table_id > 0 && table_id < N_TABLES) {
3415             struct table_dpif *table = &ofproto->tables[table_id];
3416             if (table->other_table) {
3417                 ctx->tags |= (rule
3418                               ? rule->tag
3419                               : rule_calculate_tag(&ctx->flow,
3420                                                    &table->other_table->wc,
3421                                                    table->basis));
3422             }
3423         }
3424
3425         /* Restore the original input port.  Otherwise OFPP_NORMAL and
3426          * OFPP_IN_PORT will have surprising behavior. */
3427         ctx->flow.in_port = old_in_port;
3428
3429         if (ctx->resubmit_hook) {
3430             ctx->resubmit_hook(ctx, rule);
3431         }
3432
3433         if (rule) {
3434             ctx->recurse++;
3435             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
3436             ctx->recurse--;
3437         }
3438
3439         ctx->table_id = old_table_id;
3440     } else {
3441         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
3442
3443         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
3444                     MAX_RESUBMIT_RECURSION);
3445     }
3446 }
3447
3448 static void
3449 xlate_resubmit_table(struct action_xlate_ctx *ctx,
3450                      const struct nx_action_resubmit *nar)
3451 {
3452     uint16_t in_port;
3453     uint8_t table_id;
3454
3455     in_port = (nar->in_port == htons(OFPP_IN_PORT)
3456                ? ctx->flow.in_port
3457                : ntohs(nar->in_port));
3458     table_id = nar->table == 255 ? ctx->table_id : nar->table;
3459
3460     xlate_table_action(ctx, in_port, table_id);
3461 }
3462
3463 static void
3464 flood_packets(struct action_xlate_ctx *ctx, ovs_be32 mask)
3465 {
3466     struct ofport_dpif *ofport;
3467
3468     commit_odp_actions(ctx);
3469     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
3470         uint16_t ofp_port = ofport->up.ofp_port;
3471         if (ofp_port != ctx->flow.in_port && !(ofport->up.opp.config & mask)) {
3472             compose_output_action(ctx, ofport->odp_port);
3473         }
3474     }
3475
3476     ctx->nf_output_iface = NF_OUT_FLOOD;
3477 }
3478
3479 static void
3480 compose_controller_action(struct action_xlate_ctx *ctx, int len)
3481 {
3482     struct user_action_cookie cookie;
3483
3484     cookie.type = USER_ACTION_COOKIE_CONTROLLER;
3485     cookie.data = len;
3486     cookie.n_output = 0;
3487     cookie.vlan_tci = 0;
3488     put_userspace_action(ctx->ofproto, ctx->odp_actions, &ctx->flow, &cookie);
3489 }
3490
3491 static void
3492 xlate_output_action__(struct action_xlate_ctx *ctx,
3493                       uint16_t port, uint16_t max_len)
3494 {
3495     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
3496
3497     ctx->nf_output_iface = NF_OUT_DROP;
3498
3499     switch (port) {
3500     case OFPP_IN_PORT:
3501         add_output_action(ctx, ctx->flow.in_port);
3502         break;
3503     case OFPP_TABLE:
3504         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
3505         break;
3506     case OFPP_NORMAL:
3507         xlate_normal(ctx);
3508         break;
3509     case OFPP_FLOOD:
3510         flood_packets(ctx,  htonl(OFPPC_NO_FLOOD));
3511         break;
3512     case OFPP_ALL:
3513         flood_packets(ctx, htonl(0));
3514         break;
3515     case OFPP_CONTROLLER:
3516         commit_odp_actions(ctx);
3517         compose_controller_action(ctx, max_len);
3518         break;
3519     case OFPP_LOCAL:
3520         add_output_action(ctx, OFPP_LOCAL);
3521         break;
3522     case OFPP_NONE:
3523         break;
3524     default:
3525         if (port != ctx->flow.in_port) {
3526             add_output_action(ctx, port);
3527         }
3528         break;
3529     }
3530
3531     if (prev_nf_output_iface == NF_OUT_FLOOD) {
3532         ctx->nf_output_iface = NF_OUT_FLOOD;
3533     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
3534         ctx->nf_output_iface = prev_nf_output_iface;
3535     } else if (prev_nf_output_iface != NF_OUT_DROP &&
3536                ctx->nf_output_iface != NF_OUT_FLOOD) {
3537         ctx->nf_output_iface = NF_OUT_MULTI;
3538     }
3539 }
3540
3541 static void
3542 xlate_output_reg_action(struct action_xlate_ctx *ctx,
3543                         const struct nx_action_output_reg *naor)
3544 {
3545     uint64_t ofp_port;
3546
3547     ofp_port = nxm_read_field_bits(naor->src, naor->ofs_nbits, &ctx->flow);
3548
3549     if (ofp_port <= UINT16_MAX) {
3550         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
3551     }
3552 }
3553
3554 static void
3555 xlate_output_action(struct action_xlate_ctx *ctx,
3556                     const struct ofp_action_output *oao)
3557 {
3558     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
3559 }
3560
3561 static void
3562 xlate_enqueue_action(struct action_xlate_ctx *ctx,
3563                      const struct ofp_action_enqueue *oae)
3564 {
3565     uint16_t ofp_port, odp_port;
3566     uint32_t ctx_priority, priority;
3567     int error;
3568
3569     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
3570                                    &priority);
3571     if (error) {
3572         /* Fall back to ordinary output action. */
3573         xlate_output_action__(ctx, ntohs(oae->port), 0);
3574         return;
3575     }
3576
3577     /* Figure out datapath output port. */
3578     ofp_port = ntohs(oae->port);
3579     if (ofp_port == OFPP_IN_PORT) {
3580         ofp_port = ctx->flow.in_port;
3581     }
3582     odp_port = ofp_port_to_odp_port(ofp_port);
3583
3584     /* Add datapath actions. */
3585     ctx_priority = ctx->priority;
3586     ctx->priority = priority;
3587     add_output_action(ctx, odp_port);
3588     ctx->priority = ctx_priority;
3589
3590     /* Update NetFlow output port. */
3591     if (ctx->nf_output_iface == NF_OUT_DROP) {
3592         ctx->nf_output_iface = odp_port;
3593     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
3594         ctx->nf_output_iface = NF_OUT_MULTI;
3595     }
3596 }
3597
3598 static void
3599 xlate_set_queue_action(struct action_xlate_ctx *ctx,
3600                        const struct nx_action_set_queue *nasq)
3601 {
3602     uint32_t priority;
3603     int error;
3604
3605     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
3606                                    &priority);
3607     if (error) {
3608         /* Couldn't translate queue to a priority, so ignore.  A warning
3609          * has already been logged. */
3610         return;
3611     }
3612
3613     ctx->priority = priority;
3614 }
3615
3616 struct xlate_reg_state {
3617     ovs_be16 vlan_tci;
3618     ovs_be64 tun_id;
3619 };
3620
3621 static void
3622 xlate_autopath(struct action_xlate_ctx *ctx,
3623                const struct nx_action_autopath *naa)
3624 {
3625     uint16_t ofp_port = ntohl(naa->id);
3626     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
3627
3628     if (!port || !port->bundle) {
3629         ofp_port = OFPP_NONE;
3630     } else if (port->bundle->bond) {
3631         /* Autopath does not support VLAN hashing. */
3632         struct ofport_dpif *slave = bond_choose_output_slave(
3633             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
3634         if (slave) {
3635             ofp_port = slave->up.ofp_port;
3636         }
3637     }
3638     autopath_execute(naa, &ctx->flow, ofp_port);
3639 }
3640
3641 static bool
3642 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
3643 {
3644     struct ofproto_dpif *ofproto = ofproto_;
3645     struct ofport_dpif *port;
3646
3647     switch (ofp_port) {
3648     case OFPP_IN_PORT:
3649     case OFPP_TABLE:
3650     case OFPP_NORMAL:
3651     case OFPP_FLOOD:
3652     case OFPP_ALL:
3653     case OFPP_LOCAL:
3654         return true;
3655     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
3656         return false;
3657     default:
3658         port = get_ofp_port(ofproto, ofp_port);
3659         return port ? port->may_enable : false;
3660     }
3661 }
3662
3663 static void
3664 xlate_learn_action(struct action_xlate_ctx *ctx,
3665                    const struct nx_action_learn *learn)
3666 {
3667     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
3668     struct ofputil_flow_mod fm;
3669     int error;
3670
3671     learn_execute(learn, &ctx->flow, &fm);
3672
3673     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
3674     if (error && !VLOG_DROP_WARN(&rl)) {
3675         char *msg = ofputil_error_to_string(error);
3676         VLOG_WARN("learning action failed to modify flow table (%s)", msg);
3677         free(msg);
3678     }
3679
3680     free(fm.actions);
3681 }
3682
3683 static void
3684 do_xlate_actions(const union ofp_action *in, size_t n_in,
3685                  struct action_xlate_ctx *ctx)
3686 {
3687     const struct ofport_dpif *port;
3688     const union ofp_action *ia;
3689     size_t left;
3690
3691     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
3692     if (port
3693         && port->up.opp.config & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3694         port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3695                                ? htonl(OFPPC_NO_RECV_STP)
3696                                : htonl(OFPPC_NO_RECV))) {
3697         /* Drop this flow. */
3698         return;
3699     }
3700
3701     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
3702         const struct ofp_action_dl_addr *oada;
3703         const struct nx_action_resubmit *nar;
3704         const struct nx_action_set_tunnel *nast;
3705         const struct nx_action_set_queue *nasq;
3706         const struct nx_action_multipath *nam;
3707         const struct nx_action_autopath *naa;
3708         const struct nx_action_bundle *nab;
3709         const struct nx_action_output_reg *naor;
3710         enum ofputil_action_code code;
3711         ovs_be64 tun_id;
3712
3713         code = ofputil_decode_action_unsafe(ia);
3714         switch (code) {
3715         case OFPUTIL_OFPAT_OUTPUT:
3716             xlate_output_action(ctx, &ia->output);
3717             break;
3718
3719         case OFPUTIL_OFPAT_SET_VLAN_VID:
3720             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3721             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3722             break;
3723
3724         case OFPUTIL_OFPAT_SET_VLAN_PCP:
3725             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3726             ctx->flow.vlan_tci |= htons(
3727                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3728             break;
3729
3730         case OFPUTIL_OFPAT_STRIP_VLAN:
3731             ctx->flow.vlan_tci = htons(0);
3732             break;
3733
3734         case OFPUTIL_OFPAT_SET_DL_SRC:
3735             oada = ((struct ofp_action_dl_addr *) ia);
3736             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3737             break;
3738
3739         case OFPUTIL_OFPAT_SET_DL_DST:
3740             oada = ((struct ofp_action_dl_addr *) ia);
3741             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3742             break;
3743
3744         case OFPUTIL_OFPAT_SET_NW_SRC:
3745             ctx->flow.nw_src = ia->nw_addr.nw_addr;
3746             break;
3747
3748         case OFPUTIL_OFPAT_SET_NW_DST:
3749             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3750             break;
3751
3752         case OFPUTIL_OFPAT_SET_NW_TOS:
3753             ctx->flow.nw_tos = ia->nw_tos.nw_tos & IP_DSCP_MASK;
3754             break;
3755
3756         case OFPUTIL_OFPAT_SET_TP_SRC:
3757             ctx->flow.tp_src = ia->tp_port.tp_port;
3758             break;
3759
3760         case OFPUTIL_OFPAT_SET_TP_DST:
3761             ctx->flow.tp_dst = ia->tp_port.tp_port;
3762             break;
3763
3764         case OFPUTIL_OFPAT_ENQUEUE:
3765             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3766             break;
3767
3768         case OFPUTIL_NXAST_RESUBMIT:
3769             nar = (const struct nx_action_resubmit *) ia;
3770             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
3771             break;
3772
3773         case OFPUTIL_NXAST_RESUBMIT_TABLE:
3774             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
3775             break;
3776
3777         case OFPUTIL_NXAST_SET_TUNNEL:
3778             nast = (const struct nx_action_set_tunnel *) ia;
3779             tun_id = htonll(ntohl(nast->tun_id));
3780             ctx->flow.tun_id = tun_id;
3781             break;
3782
3783         case OFPUTIL_NXAST_SET_QUEUE:
3784             nasq = (const struct nx_action_set_queue *) ia;
3785             xlate_set_queue_action(ctx, nasq);
3786             break;
3787
3788         case OFPUTIL_NXAST_POP_QUEUE:
3789             ctx->priority = 0;
3790             break;
3791
3792         case OFPUTIL_NXAST_REG_MOVE:
3793             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
3794                                  &ctx->flow);
3795             break;
3796
3797         case OFPUTIL_NXAST_REG_LOAD:
3798             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
3799                                  &ctx->flow);
3800             break;
3801
3802         case OFPUTIL_NXAST_NOTE:
3803             /* Nothing to do. */
3804             break;
3805
3806         case OFPUTIL_NXAST_SET_TUNNEL64:
3807             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
3808             ctx->flow.tun_id = tun_id;
3809             break;
3810
3811         case OFPUTIL_NXAST_MULTIPATH:
3812             nam = (const struct nx_action_multipath *) ia;
3813             multipath_execute(nam, &ctx->flow);
3814             break;
3815
3816         case OFPUTIL_NXAST_AUTOPATH:
3817             naa = (const struct nx_action_autopath *) ia;
3818             xlate_autopath(ctx, naa);
3819             break;
3820
3821         case OFPUTIL_NXAST_BUNDLE:
3822             ctx->ofproto->has_bundle_action = true;
3823             nab = (const struct nx_action_bundle *) ia;
3824             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
3825                                                       slave_enabled_cb,
3826                                                       ctx->ofproto), 0);
3827             break;
3828
3829         case OFPUTIL_NXAST_BUNDLE_LOAD:
3830             ctx->ofproto->has_bundle_action = true;
3831             nab = (const struct nx_action_bundle *) ia;
3832             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
3833                                 ctx->ofproto);
3834             break;
3835
3836         case OFPUTIL_NXAST_OUTPUT_REG:
3837             naor = (const struct nx_action_output_reg *) ia;
3838             xlate_output_reg_action(ctx, naor);
3839             break;
3840
3841         case OFPUTIL_NXAST_LEARN:
3842             ctx->has_learn = true;
3843             if (ctx->may_learn) {
3844                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
3845             }
3846             break;
3847         }
3848     }
3849 }
3850
3851 static void
3852 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3853                       struct ofproto_dpif *ofproto, const struct flow *flow,
3854                       const struct ofpbuf *packet)
3855 {
3856     ctx->ofproto = ofproto;
3857     ctx->flow = *flow;
3858     ctx->packet = packet;
3859     ctx->may_learn = packet != NULL;
3860     ctx->resubmit_hook = NULL;
3861 }
3862
3863 static struct ofpbuf *
3864 xlate_actions(struct action_xlate_ctx *ctx,
3865               const union ofp_action *in, size_t n_in)
3866 {
3867     COVERAGE_INC(ofproto_dpif_xlate);
3868
3869     ctx->odp_actions = ofpbuf_new(512);
3870     ofpbuf_reserve(ctx->odp_actions, NL_A_U32_SIZE);
3871     ctx->tags = 0;
3872     ctx->may_set_up_flow = true;
3873     ctx->has_learn = false;
3874     ctx->has_normal = false;
3875     ctx->nf_output_iface = NF_OUT_DROP;
3876     ctx->recurse = 0;
3877     ctx->priority = 0;
3878     ctx->base_priority = 0;
3879     ctx->base_flow = ctx->flow;
3880     ctx->base_flow.tun_id = 0;
3881     ctx->table_id = 0;
3882
3883     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
3884         ctx->may_set_up_flow = false;
3885         return ctx->odp_actions;
3886     } else {
3887         add_sflow_action(ctx);
3888         do_xlate_actions(in, n_in, ctx);
3889
3890         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
3891                                      ctx->odp_actions->data,
3892                                      ctx->odp_actions->size)) {
3893             ctx->may_set_up_flow = false;
3894             if (ctx->packet
3895                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
3896                                        ctx->packet)) {
3897                 compose_output_action(ctx, OVSP_LOCAL);
3898             }
3899         }
3900         fix_sflow_action(ctx);
3901     }
3902
3903     return ctx->odp_actions;
3904 }
3905 \f
3906 /* OFPP_NORMAL implementation. */
3907
3908 struct dst {
3909     struct ofport_dpif *port;
3910     uint16_t vid;
3911 };
3912
3913 struct dst_set {
3914     struct dst builtin[32];
3915     struct dst *dsts;
3916     size_t n, allocated;
3917 };
3918
3919 static void dst_set_init(struct dst_set *);
3920 static void dst_set_add(struct dst_set *, const struct dst *);
3921 static void dst_set_free(struct dst_set *);
3922
3923 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
3924
3925 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
3926  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
3927  * the bundle on which the packet was received, returns the VLAN to which the
3928  * packet belongs.
3929  *
3930  * Both 'vid' and the return value are in the range 0...4095. */
3931 static uint16_t
3932 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
3933 {
3934     switch (in_bundle->vlan_mode) {
3935     case PORT_VLAN_ACCESS:
3936         return in_bundle->vlan;
3937         break;
3938
3939     case PORT_VLAN_TRUNK:
3940         return vid;
3941
3942     case PORT_VLAN_NATIVE_UNTAGGED:
3943     case PORT_VLAN_NATIVE_TAGGED:
3944         return vid ? vid : in_bundle->vlan;
3945
3946     default:
3947         NOT_REACHED();
3948     }
3949 }
3950
3951 /* Given 'vlan', the VLAN that a packet belongs to, and
3952  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
3953  * that should be included in the 802.1Q header.  (If the return value is 0,
3954  * then the 802.1Q header should only be included in the packet if there is a
3955  * nonzero PCP.)
3956  *
3957  * Both 'vlan' and the return value are in the range 0...4095. */
3958 static uint16_t
3959 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
3960 {
3961     switch (out_bundle->vlan_mode) {
3962     case PORT_VLAN_ACCESS:
3963         return 0;
3964
3965     case PORT_VLAN_TRUNK:
3966     case PORT_VLAN_NATIVE_TAGGED:
3967         return vlan;
3968
3969     case PORT_VLAN_NATIVE_UNTAGGED:
3970         return vlan == out_bundle->vlan ? 0 : vlan;
3971
3972     default:
3973         NOT_REACHED();
3974     }
3975 }
3976
3977 static bool
3978 set_dst(struct action_xlate_ctx *ctx, struct dst *dst,
3979         const struct ofbundle *in_bundle, const struct ofbundle *out_bundle)
3980 {
3981     uint16_t vlan;
3982
3983     vlan = input_vid_to_vlan(in_bundle, vlan_tci_to_vid(ctx->flow.vlan_tci));
3984     dst->vid = output_vlan_to_vid(out_bundle, vlan);
3985
3986     dst->port = (!out_bundle->bond
3987                  ? ofbundle_get_a_port(out_bundle)
3988                  : bond_choose_output_slave(out_bundle->bond, &ctx->flow,
3989                                             dst->vid, &ctx->tags));
3990     return dst->port != NULL;
3991 }
3992
3993 static int
3994 mirror_mask_ffs(mirror_mask_t mask)
3995 {
3996     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
3997     return ffs(mask);
3998 }
3999
4000 static void
4001 dst_set_init(struct dst_set *set)
4002 {
4003     set->dsts = set->builtin;
4004     set->n = 0;
4005     set->allocated = ARRAY_SIZE(set->builtin);
4006 }
4007
4008 static void
4009 dst_set_add(struct dst_set *set, const struct dst *dst)
4010 {
4011     if (set->n >= set->allocated) {
4012         size_t new_allocated;
4013         struct dst *new_dsts;
4014
4015         new_allocated = set->allocated * 2;
4016         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
4017         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
4018
4019         dst_set_free(set);
4020
4021         set->dsts = new_dsts;
4022         set->allocated = new_allocated;
4023     }
4024     set->dsts[set->n++] = *dst;
4025 }
4026
4027 static void
4028 dst_set_free(struct dst_set *set)
4029 {
4030     if (set->dsts != set->builtin) {
4031         free(set->dsts);
4032     }
4033 }
4034
4035 static bool
4036 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
4037 {
4038     size_t i;
4039     for (i = 0; i < set->n; i++) {
4040         if (set->dsts[i].vid == test->vid
4041             && set->dsts[i].port == test->port) {
4042             return true;
4043         }
4044     }
4045     return false;
4046 }
4047
4048 static bool
4049 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
4050 {
4051     return (bundle->vlan_mode != PORT_VLAN_ACCESS
4052             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
4053 }
4054
4055 static bool
4056 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
4057 {
4058     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
4059 }
4060
4061 /* Returns an arbitrary interface within 'bundle'. */
4062 static struct ofport_dpif *
4063 ofbundle_get_a_port(const struct ofbundle *bundle)
4064 {
4065     return CONTAINER_OF(list_front(&bundle->ports),
4066                         struct ofport_dpif, bundle_node);
4067 }
4068
4069 static void
4070 compose_dsts(struct action_xlate_ctx *ctx, uint16_t vlan,
4071              const struct ofbundle *in_bundle,
4072              const struct ofbundle *out_bundle, struct dst_set *set)
4073 {
4074     struct dst dst;
4075
4076     if (out_bundle == OFBUNDLE_FLOOD) {
4077         struct ofbundle *bundle;
4078
4079         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
4080             if (bundle != in_bundle
4081                 && ofbundle_includes_vlan(bundle, vlan)
4082                 && bundle->floodable
4083                 && !bundle->mirror_out
4084                 && set_dst(ctx, &dst, in_bundle, bundle)) {
4085                 dst_set_add(set, &dst);
4086             }
4087         }
4088         ctx->nf_output_iface = NF_OUT_FLOOD;
4089     } else if (out_bundle && set_dst(ctx, &dst, in_bundle, out_bundle)) {
4090         dst_set_add(set, &dst);
4091         ctx->nf_output_iface = dst.port->odp_port;
4092     }
4093 }
4094
4095 static bool
4096 vlan_is_mirrored(const struct ofmirror *m, int vlan)
4097 {
4098     return !m->vlans || bitmap_is_set(m->vlans, vlan);
4099 }
4100
4101 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
4102  * to a VLAN.  In general most packets may be mirrored but we want to drop
4103  * protocols that may confuse switches. */
4104 static bool
4105 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
4106 {
4107     /* If you change this function's behavior, please update corresponding
4108      * documentation in vswitch.xml at the same time. */
4109     if (dst[0] != 0x01) {
4110         /* All the currently banned MACs happen to start with 01 currently, so
4111          * this is a quick way to eliminate most of the good ones. */
4112     } else {
4113         if (eth_addr_is_reserved(dst)) {
4114             /* Drop STP, IEEE pause frames, and other reserved protocols
4115              * (01-80-c2-00-00-0x). */
4116             return false;
4117         }
4118
4119         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
4120             /* Cisco OUI. */
4121             if ((dst[3] & 0xfe) == 0xcc &&
4122                 (dst[4] & 0xfe) == 0xcc &&
4123                 (dst[5] & 0xfe) == 0xcc) {
4124                 /* Drop the following protocols plus others following the same
4125                    pattern:
4126
4127                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
4128                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
4129                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
4130                 return false;
4131             }
4132
4133             if (!(dst[3] | dst[4] | dst[5])) {
4134                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
4135                 return false;
4136             }
4137         }
4138     }
4139     return true;
4140 }
4141
4142 static void
4143 compose_mirror_dsts(struct action_xlate_ctx *ctx,
4144                     uint16_t vlan, const struct ofbundle *in_bundle,
4145                     struct dst_set *set)
4146 {
4147     struct ofproto_dpif *ofproto = ctx->ofproto;
4148     mirror_mask_t mirrors;
4149     uint16_t flow_vid;
4150     size_t i;
4151
4152     mirrors = in_bundle->src_mirrors;
4153     for (i = 0; i < set->n; i++) {
4154         mirrors |= set->dsts[i].port->bundle->dst_mirrors;
4155     }
4156
4157     if (!mirrors) {
4158         return;
4159     }
4160
4161     flow_vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
4162     while (mirrors) {
4163         struct ofmirror *m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
4164         if (vlan_is_mirrored(m, vlan)) {
4165             struct dst dst;
4166
4167             if (m->out) {
4168                 if (set_dst(ctx, &dst, in_bundle, m->out)
4169                     && !dst_is_duplicate(set, &dst)) {
4170                     dst_set_add(set, &dst);
4171                 }
4172             } else if (eth_dst_may_rspan(ctx->flow.dl_dst)) {
4173                 struct ofbundle *bundle;
4174
4175                 HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4176                     if (ofbundle_includes_vlan(bundle, m->out_vlan)
4177                         && set_dst(ctx, &dst, in_bundle, bundle))
4178                     {
4179                         /* set_dst() got dst->vid from the input packet's VLAN,
4180                          * not from m->out_vlan, so recompute it. */
4181                         dst.vid = output_vlan_to_vid(bundle, m->out_vlan);
4182
4183                         if (dst_is_duplicate(set, &dst)) {
4184                             continue;
4185                         }
4186
4187                         if (bundle == in_bundle && dst.vid == flow_vid) {
4188                             /* Don't send out input port on same VLAN. */
4189                             continue;
4190                         }
4191                         dst_set_add(set, &dst);
4192                     }
4193                 }
4194             }
4195         }
4196         mirrors &= mirrors - 1;
4197     }
4198 }
4199
4200 static void
4201 compose_actions(struct action_xlate_ctx *ctx, uint16_t vlan,
4202                 const struct ofbundle *in_bundle,
4203                 const struct ofbundle *out_bundle)
4204 {
4205     uint16_t initial_vid, cur_vid;
4206     const struct dst *dst;
4207     struct dst_set set;
4208
4209     dst_set_init(&set);
4210     compose_dsts(ctx, vlan, in_bundle, out_bundle, &set);
4211     compose_mirror_dsts(ctx, vlan, in_bundle, &set);
4212     if (!set.n) {
4213         dst_set_free(&set);
4214         return;
4215     }
4216
4217     /* Output all the packets we can without having to change the VLAN. */
4218     commit_odp_actions(ctx);
4219     initial_vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
4220     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
4221         if (dst->vid != initial_vid) {
4222             continue;
4223         }
4224         compose_output_action(ctx, dst->port->odp_port);
4225     }
4226
4227     /* Then output the rest. */
4228     cur_vid = initial_vid;
4229     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
4230         if (dst->vid == initial_vid) {
4231             continue;
4232         }
4233         if (dst->vid != cur_vid) {
4234             ovs_be16 tci;
4235
4236             tci = htons(dst->vid);
4237             tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
4238             if (tci) {
4239                 tci |= htons(VLAN_CFI);
4240             }
4241             commit_vlan_tci(ctx, tci);
4242
4243             cur_vid = dst->vid;
4244         }
4245         compose_output_action(ctx, dst->port->odp_port);
4246     }
4247
4248     dst_set_free(&set);
4249 }
4250
4251 /* Returns the effective vlan of a packet, taking into account both the
4252  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
4253  * the packet is untagged and -1 indicates it has an invalid header and
4254  * should be dropped. */
4255 static int
4256 flow_get_vlan(struct ofproto_dpif *ofproto, const struct flow *flow,
4257               struct ofbundle *in_bundle, bool have_packet)
4258 {
4259     int vlan = vlan_tci_to_vid(flow->vlan_tci);
4260     if (vlan) {
4261         if (in_bundle->vlan_mode == PORT_VLAN_ACCESS) {
4262             /* Drop tagged packet on access port */
4263             if (have_packet) {
4264                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4265                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
4266                              "packet received on port %s configured with "
4267                              "implicit VLAN %"PRIu16,
4268                              ofproto->up.name, vlan,
4269                              in_bundle->name, in_bundle->vlan);
4270             }
4271             return -1;
4272         } else if (ofbundle_includes_vlan(in_bundle, vlan)) {
4273             return vlan;
4274         } else {
4275             /* Drop packets from a VLAN not member of the trunk */
4276             if (have_packet) {
4277                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4278                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
4279                              "packet received on port %s not configured for "
4280                              "trunking VLAN %d",
4281                              ofproto->up.name, vlan, in_bundle->name, vlan);
4282             }
4283             return -1;
4284         }
4285     } else {
4286         if (in_bundle->vlan_mode != PORT_VLAN_TRUNK) {
4287             return in_bundle->vlan;
4288         } else {
4289             return ofbundle_includes_vlan(in_bundle, 0) ? 0 : -1;
4290         }
4291     }
4292 }
4293
4294 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
4295  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
4296  * indicate this; newer upstream kernels use gratuitous ARP requests. */
4297 static bool
4298 is_gratuitous_arp(const struct flow *flow)
4299 {
4300     return (flow->dl_type == htons(ETH_TYPE_ARP)
4301             && eth_addr_is_broadcast(flow->dl_dst)
4302             && (flow->nw_proto == ARP_OP_REPLY
4303                 || (flow->nw_proto == ARP_OP_REQUEST
4304                     && flow->nw_src == flow->nw_dst)));
4305 }
4306
4307 static void
4308 update_learning_table(struct ofproto_dpif *ofproto,
4309                       const struct flow *flow, int vlan,
4310                       struct ofbundle *in_bundle)
4311 {
4312     struct mac_entry *mac;
4313
4314     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
4315         return;
4316     }
4317
4318     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
4319     if (is_gratuitous_arp(flow)) {
4320         /* We don't want to learn from gratuitous ARP packets that are
4321          * reflected back over bond slaves so we lock the learning table. */
4322         if (!in_bundle->bond) {
4323             mac_entry_set_grat_arp_lock(mac);
4324         } else if (mac_entry_is_grat_arp_locked(mac)) {
4325             return;
4326         }
4327     }
4328
4329     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
4330         /* The log messages here could actually be useful in debugging,
4331          * so keep the rate limit relatively high. */
4332         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
4333         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
4334                     "on port %s in VLAN %d",
4335                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
4336                     in_bundle->name, vlan);
4337
4338         mac->port.p = in_bundle;
4339         tag_set_add(&ofproto->revalidate_set,
4340                     mac_learning_changed(ofproto->ml, mac));
4341     }
4342 }
4343
4344 /* Determines whether packets in 'flow' within 'br' should be forwarded or
4345  * dropped.  Returns true if they may be forwarded, false if they should be
4346  * dropped.
4347  *
4348  * If 'have_packet' is true, it indicates that the caller is processing a
4349  * received packet.  If 'have_packet' is false, then the caller is just
4350  * revalidating an existing flow because configuration has changed.  Either
4351  * way, 'have_packet' only affects logging (there is no point in logging errors
4352  * during revalidation).
4353  *
4354  * Sets '*in_portp' to the input port.  This will be a null pointer if
4355  * flow->in_port does not designate a known input port (in which case
4356  * is_admissible() returns false).
4357  *
4358  * When returning true, sets '*vlanp' to the effective VLAN of the input
4359  * packet, as returned by flow_get_vlan().
4360  *
4361  * May also add tags to '*tags', although the current implementation only does
4362  * so in one special case.
4363  */
4364 static bool
4365 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
4366               bool have_packet,
4367               tag_type *tags, int *vlanp, struct ofbundle **in_bundlep)
4368 {
4369     struct ofport_dpif *in_port;
4370     struct ofbundle *in_bundle;
4371     int vlan;
4372
4373     /* Find the port and bundle for the received packet. */
4374     in_port = get_ofp_port(ofproto, flow->in_port);
4375     *in_bundlep = in_bundle = in_port ? in_port->bundle : NULL;
4376     if (!in_port || !in_bundle) {
4377         /* No interface?  Something fishy... */
4378         if (have_packet) {
4379             /* Odd.  A few possible reasons here:
4380              *
4381              * - We deleted a port but there are still a few packets queued up
4382              *   from it.
4383              *
4384              * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
4385              *   we don't know about.
4386              *
4387              * - Packet arrived on the local port but the local port is not
4388              *   part of a bundle.
4389              */
4390             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4391
4392             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
4393                          "port %"PRIu16,
4394                          ofproto->up.name, flow->in_port);
4395         }
4396         *vlanp = -1;
4397         return false;
4398     }
4399     *vlanp = vlan = flow_get_vlan(ofproto, flow, in_bundle, have_packet);
4400     if (vlan < 0) {
4401         return false;
4402     }
4403
4404     /* Drop frames for reserved multicast addresses
4405      * only if forward_bpdu option is absent. */
4406     if (eth_addr_is_reserved(flow->dl_dst) &&
4407         !ofproto->up.forward_bpdu) {
4408         return false;
4409     }
4410
4411     /* Drop frames on bundles reserved for mirroring. */
4412     if (in_bundle->mirror_out) {
4413         if (have_packet) {
4414             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4415             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
4416                          "%s, which is reserved exclusively for mirroring",
4417                          ofproto->up.name, in_bundle->name);
4418         }
4419         return false;
4420     }
4421
4422     if (in_bundle->bond) {
4423         struct mac_entry *mac;
4424
4425         switch (bond_check_admissibility(in_bundle->bond, in_port,
4426                                          flow->dl_dst, tags)) {
4427         case BV_ACCEPT:
4428             break;
4429
4430         case BV_DROP:
4431             return false;
4432
4433         case BV_DROP_IF_MOVED:
4434             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
4435             if (mac && mac->port.p != in_bundle &&
4436                 (!is_gratuitous_arp(flow)
4437                  || mac_entry_is_grat_arp_locked(mac))) {
4438                 return false;
4439             }
4440             break;
4441         }
4442     }
4443
4444     return true;
4445 }
4446
4447 static void
4448 xlate_normal(struct action_xlate_ctx *ctx)
4449 {
4450     struct ofbundle *in_bundle;
4451     struct ofbundle *out_bundle;
4452     struct mac_entry *mac;
4453     int vlan;
4454
4455     ctx->has_normal = true;
4456
4457     /* Check whether we should drop packets in this flow. */
4458     if (!is_admissible(ctx->ofproto, &ctx->flow, ctx->packet != NULL,
4459                        &ctx->tags, &vlan, &in_bundle)) {
4460         out_bundle = NULL;
4461         goto done;
4462     }
4463
4464     /* Learn source MAC. */
4465     if (ctx->may_learn) {
4466         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
4467     }
4468
4469     /* Determine output bundle. */
4470     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
4471                               &ctx->tags);
4472     if (mac) {
4473         out_bundle = mac->port.p;
4474     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
4475         /* If we are revalidating but don't have a learning entry then eject
4476          * the flow.  Installing a flow that floods packets opens up a window
4477          * of time where we could learn from a packet reflected on a bond and
4478          * blackhole packets before the learning table is updated to reflect
4479          * the correct port. */
4480         ctx->may_set_up_flow = false;
4481         return;
4482     } else {
4483         out_bundle = OFBUNDLE_FLOOD;
4484     }
4485
4486     /* Don't send packets out their input bundles. */
4487     if (in_bundle == out_bundle) {
4488         out_bundle = NULL;
4489     }
4490
4491 done:
4492     if (in_bundle) {
4493         compose_actions(ctx, vlan, in_bundle, out_bundle);
4494     }
4495 }
4496 \f
4497 /* Optimized flow revalidation.
4498  *
4499  * It's a difficult problem, in general, to tell which facets need to have
4500  * their actions recalculated whenever the OpenFlow flow table changes.  We
4501  * don't try to solve that general problem: for most kinds of OpenFlow flow
4502  * table changes, we recalculate the actions for every facet.  This is
4503  * relatively expensive, but it's good enough if the OpenFlow flow table
4504  * doesn't change very often.
4505  *
4506  * However, we can expect one particular kind of OpenFlow flow table change to
4507  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
4508  * of CPU on revalidating every facet whenever MAC learning modifies the flow
4509  * table, we add a special case that applies to flow tables in which every rule
4510  * has the same form (that is, the same wildcards), except that the table is
4511  * also allowed to have a single "catch-all" flow that matches all packets.  We
4512  * optimize this case by tagging all of the facets that resubmit into the table
4513  * and invalidating the same tag whenever a flow changes in that table.  The
4514  * end result is that we revalidate just the facets that need it (and sometimes
4515  * a few more, but not all of the facets or even all of the facets that
4516  * resubmit to the table modified by MAC learning). */
4517
4518 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
4519  * into an OpenFlow table with the given 'basis'. */
4520 static uint32_t
4521 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
4522                    uint32_t secret)
4523 {
4524     if (flow_wildcards_is_catchall(wc)) {
4525         return 0;
4526     } else {
4527         struct flow tag_flow = *flow;
4528         flow_zero_wildcards(&tag_flow, wc);
4529         return tag_create_deterministic(flow_hash(&tag_flow, secret));
4530     }
4531 }
4532
4533 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
4534  * taggability of that table.
4535  *
4536  * This function must be called after *each* change to a flow table.  If you
4537  * skip calling it on some changes then the pointer comparisons at the end can
4538  * be invalid if you get unlucky.  For example, if a flow removal causes a
4539  * cls_table to be destroyed and then a flow insertion causes a cls_table with
4540  * different wildcards to be created with the same address, then this function
4541  * will incorrectly skip revalidation. */
4542 static void
4543 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
4544 {
4545     struct table_dpif *table = &ofproto->tables[table_id];
4546     const struct classifier *cls = &ofproto->up.tables[table_id];
4547     struct cls_table *catchall, *other;
4548     struct cls_table *t;
4549
4550     catchall = other = NULL;
4551
4552     switch (hmap_count(&cls->tables)) {
4553     case 0:
4554         /* We could tag this OpenFlow table but it would make the logic a
4555          * little harder and it's a corner case that doesn't seem worth it
4556          * yet. */
4557         break;
4558
4559     case 1:
4560     case 2:
4561         HMAP_FOR_EACH (t, hmap_node, &cls->tables) {
4562             if (cls_table_is_catchall(t)) {
4563                 catchall = t;
4564             } else if (!other) {
4565                 other = t;
4566             } else {
4567                 /* Indicate that we can't tag this by setting both tables to
4568                  * NULL.  (We know that 'catchall' is already NULL.) */
4569                 other = NULL;
4570             }
4571         }
4572         break;
4573
4574     default:
4575         /* Can't tag this table. */
4576         break;
4577     }
4578
4579     if (table->catchall_table != catchall || table->other_table != other) {
4580         table->catchall_table = catchall;
4581         table->other_table = other;
4582         ofproto->need_revalidate = true;
4583     }
4584 }
4585
4586 /* Given 'rule' that has changed in some way (either it is a rule being
4587  * inserted, a rule being deleted, or a rule whose actions are being
4588  * modified), marks facets for revalidation to ensure that packets will be
4589  * forwarded correctly according to the new state of the flow table.
4590  *
4591  * This function must be called after *each* change to a flow table.  See
4592  * the comment on table_update_taggable() for more information. */
4593 static void
4594 rule_invalidate(const struct rule_dpif *rule)
4595 {
4596     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4597
4598     table_update_taggable(ofproto, rule->up.table_id);
4599
4600     if (!ofproto->need_revalidate) {
4601         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
4602
4603         if (table->other_table && rule->tag) {
4604             tag_set_add(&ofproto->revalidate_set, rule->tag);
4605         } else {
4606             ofproto->need_revalidate = true;
4607         }
4608     }
4609 }
4610 \f
4611 static bool
4612 get_drop_frags(struct ofproto *ofproto_)
4613 {
4614     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4615     bool drop_frags;
4616
4617     dpif_get_drop_frags(ofproto->dpif, &drop_frags);
4618     return drop_frags;
4619 }
4620
4621 static void
4622 set_drop_frags(struct ofproto *ofproto_, bool drop_frags)
4623 {
4624     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4625
4626     dpif_set_drop_frags(ofproto->dpif, drop_frags);
4627 }
4628
4629 static int
4630 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
4631            const struct flow *flow,
4632            const union ofp_action *ofp_actions, size_t n_ofp_actions)
4633 {
4634     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4635     int error;
4636
4637     error = validate_actions(ofp_actions, n_ofp_actions, flow,
4638                              ofproto->max_ports);
4639     if (!error) {
4640         struct odputil_keybuf keybuf;
4641         struct action_xlate_ctx ctx;
4642         struct ofpbuf *odp_actions;
4643         struct ofpbuf key;
4644
4645         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
4646         odp_flow_key_from_flow(&key, flow);
4647
4648         action_xlate_ctx_init(&ctx, ofproto, flow, packet);
4649         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
4650         dpif_execute(ofproto->dpif, key.data, key.size,
4651                      odp_actions->data, odp_actions->size, packet);
4652         ofpbuf_delete(odp_actions);
4653     }
4654     return error;
4655 }
4656
4657 static void
4658 get_netflow_ids(const struct ofproto *ofproto_,
4659                 uint8_t *engine_type, uint8_t *engine_id)
4660 {
4661     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4662
4663     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
4664 }
4665 \f
4666 static struct ofproto_dpif *
4667 ofproto_dpif_lookup(const char *name)
4668 {
4669     struct ofproto *ofproto = ofproto_lookup(name);
4670     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
4671             ? ofproto_dpif_cast(ofproto)
4672             : NULL);
4673 }
4674
4675 static void
4676 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
4677                          const char *args, void *aux OVS_UNUSED)
4678 {
4679     struct ds ds = DS_EMPTY_INITIALIZER;
4680     const struct ofproto_dpif *ofproto;
4681     const struct mac_entry *e;
4682
4683     ofproto = ofproto_dpif_lookup(args);
4684     if (!ofproto) {
4685         unixctl_command_reply(conn, 501, "no such bridge");
4686         return;
4687     }
4688
4689     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
4690     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
4691         struct ofbundle *bundle = e->port.p;
4692         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
4693                       ofbundle_get_a_port(bundle)->odp_port,
4694                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
4695     }
4696     unixctl_command_reply(conn, 200, ds_cstr(&ds));
4697     ds_destroy(&ds);
4698 }
4699
4700 struct ofproto_trace {
4701     struct action_xlate_ctx ctx;
4702     struct flow flow;
4703     struct ds *result;
4704 };
4705
4706 static void
4707 trace_format_rule(struct ds *result, uint8_t table_id, int level,
4708                   const struct rule_dpif *rule)
4709 {
4710     ds_put_char_multiple(result, '\t', level);
4711     if (!rule) {
4712         ds_put_cstr(result, "No match\n");
4713         return;
4714     }
4715
4716     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
4717                   table_id, ntohll(rule->up.flow_cookie));
4718     cls_rule_format(&rule->up.cr, result);
4719     ds_put_char(result, '\n');
4720
4721     ds_put_char_multiple(result, '\t', level);
4722     ds_put_cstr(result, "OpenFlow ");
4723     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
4724     ds_put_char(result, '\n');
4725 }
4726
4727 static void
4728 trace_format_flow(struct ds *result, int level, const char *title,
4729                  struct ofproto_trace *trace)
4730 {
4731     ds_put_char_multiple(result, '\t', level);
4732     ds_put_format(result, "%s: ", title);
4733     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
4734         ds_put_cstr(result, "unchanged");
4735     } else {
4736         flow_format(result, &trace->ctx.flow);
4737         trace->flow = trace->ctx.flow;
4738     }
4739     ds_put_char(result, '\n');
4740 }
4741
4742 static void
4743 trace_format_regs(struct ds *result, int level, const char *title,
4744                   struct ofproto_trace *trace)
4745 {
4746     size_t i;
4747
4748     ds_put_char_multiple(result, '\t', level);
4749     ds_put_format(result, "%s:", title);
4750     for (i = 0; i < FLOW_N_REGS; i++) {
4751         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
4752     }
4753     ds_put_char(result, '\n');
4754 }
4755
4756 static void
4757 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
4758 {
4759     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
4760     struct ds *result = trace->result;
4761
4762     ds_put_char(result, '\n');
4763     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
4764     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
4765     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
4766 }
4767
4768 static void
4769 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
4770                       void *aux OVS_UNUSED)
4771 {
4772     char *dpname, *arg1, *arg2, *arg3;
4773     char *args = xstrdup(args_);
4774     char *save_ptr = NULL;
4775     struct ofproto_dpif *ofproto;
4776     struct ofpbuf odp_key;
4777     struct ofpbuf *packet;
4778     struct rule_dpif *rule;
4779     struct ds result;
4780     struct flow flow;
4781     char *s;
4782
4783     packet = NULL;
4784     ofpbuf_init(&odp_key, 0);
4785     ds_init(&result);
4786
4787     dpname = strtok_r(args, " ", &save_ptr);
4788     arg1 = strtok_r(NULL, " ", &save_ptr);
4789     arg2 = strtok_r(NULL, " ", &save_ptr);
4790     arg3 = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
4791     if (dpname && arg1 && (!arg2 || !strcmp(arg2, "-generate")) && !arg3) {
4792         /* ofproto/trace dpname flow [-generate] */
4793         int error;
4794
4795         /* Convert string to datapath key. */
4796         ofpbuf_init(&odp_key, 0);
4797         error = odp_flow_key_from_string(arg1, &odp_key);
4798         if (error) {
4799             unixctl_command_reply(conn, 501, "Bad flow syntax");
4800             goto exit;
4801         }
4802
4803         /* Convert odp_key to flow. */
4804         error = odp_flow_key_to_flow(odp_key.data, odp_key.size, &flow);
4805         if (error) {
4806             unixctl_command_reply(conn, 501, "Invalid flow");
4807             goto exit;
4808         }
4809
4810         /* Generate a packet, if requested. */
4811         if (arg2) {
4812             packet = ofpbuf_new(0);
4813             flow_compose(packet, &flow);
4814         }
4815     } else if (dpname && arg1 && arg2 && arg3) {
4816         /* ofproto/trace dpname tun_id in_port packet */
4817         uint16_t in_port;
4818         ovs_be64 tun_id;
4819
4820         tun_id = htonll(strtoull(arg1, NULL, 0));
4821         in_port = ofp_port_to_odp_port(atoi(arg2));
4822
4823         packet = ofpbuf_new(strlen(args) / 2);
4824         arg3 = ofpbuf_put_hex(packet, arg3, NULL);
4825         arg3 += strspn(arg3, " ");
4826         if (*arg3 != '\0') {
4827             unixctl_command_reply(conn, 501, "Trailing garbage in command");
4828             goto exit;
4829         }
4830         if (packet->size < ETH_HEADER_LEN) {
4831             unixctl_command_reply(conn, 501,
4832                                   "Packet data too short for Ethernet");
4833             goto exit;
4834         }
4835
4836         ds_put_cstr(&result, "Packet: ");
4837         s = ofp_packet_to_string(packet->data, packet->size, packet->size);
4838         ds_put_cstr(&result, s);
4839         free(s);
4840
4841         flow_extract(packet, tun_id, in_port, &flow);
4842     } else {
4843         unixctl_command_reply(conn, 501, "Bad command syntax");
4844         goto exit;
4845     }
4846
4847     ofproto = ofproto_dpif_lookup(dpname);
4848     if (!ofproto) {
4849         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
4850                               "for help)");
4851         goto exit;
4852     }
4853
4854     ds_put_cstr(&result, "Flow: ");
4855     flow_format(&result, &flow);
4856     ds_put_char(&result, '\n');
4857
4858     rule = rule_dpif_lookup(ofproto, &flow, 0);
4859     trace_format_rule(&result, 0, 0, rule);
4860     if (rule) {
4861         struct ofproto_trace trace;
4862         struct ofpbuf *odp_actions;
4863
4864         trace.result = &result;
4865         trace.flow = flow;
4866         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, packet);
4867         trace.ctx.resubmit_hook = trace_resubmit;
4868         odp_actions = xlate_actions(&trace.ctx,
4869                                     rule->up.actions, rule->up.n_actions);
4870
4871         ds_put_char(&result, '\n');
4872         trace_format_flow(&result, 0, "Final flow", &trace);
4873         ds_put_cstr(&result, "Datapath actions: ");
4874         format_odp_actions(&result, odp_actions->data, odp_actions->size);
4875         ofpbuf_delete(odp_actions);
4876
4877         if (!trace.ctx.may_set_up_flow) {
4878             if (packet) {
4879                 ds_put_cstr(&result, "\nThis flow is not cachable.");
4880             } else {
4881                 ds_put_cstr(&result, "\nThe datapath actions are incomplete--"
4882                             "for complete actions, please supply a packet.");
4883             }
4884         }
4885     }
4886
4887     unixctl_command_reply(conn, 200, ds_cstr(&result));
4888
4889 exit:
4890     ds_destroy(&result);
4891     ofpbuf_delete(packet);
4892     ofpbuf_uninit(&odp_key);
4893     free(args);
4894 }
4895
4896 static void
4897 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED,
4898                   const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
4899 {
4900     clogged = true;
4901     unixctl_command_reply(conn, 200, NULL);
4902 }
4903
4904 static void
4905 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED,
4906                     const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
4907 {
4908     clogged = false;
4909     unixctl_command_reply(conn, 200, NULL);
4910 }
4911
4912 static void
4913 ofproto_dpif_unixctl_init(void)
4914 {
4915     static bool registered;
4916     if (registered) {
4917         return;
4918     }
4919     registered = true;
4920
4921     unixctl_command_register("ofproto/trace",
4922                       "bridge {tun_id in_port packet | odp_flow [-generate]}",
4923                       ofproto_unixctl_trace, NULL);
4924     unixctl_command_register("fdb/show", "bridge", ofproto_unixctl_fdb_show,
4925                              NULL); 
4926     unixctl_command_register("ofproto/clog", "", ofproto_dpif_clog, NULL);
4927     unixctl_command_register("ofproto/unclog", "", ofproto_dpif_unclog, NULL);
4928 }
4929 \f
4930 const struct ofproto_class ofproto_dpif_class = {
4931     enumerate_types,
4932     enumerate_names,
4933     del,
4934     alloc,
4935     construct,
4936     destruct,
4937     dealloc,
4938     run,
4939     wait,
4940     flush,
4941     get_features,
4942     get_tables,
4943     port_alloc,
4944     port_construct,
4945     port_destruct,
4946     port_dealloc,
4947     port_modified,
4948     port_reconfigured,
4949     port_query_by_name,
4950     port_add,
4951     port_del,
4952     port_dump_start,
4953     port_dump_next,
4954     port_dump_done,
4955     port_poll,
4956     port_poll_wait,
4957     port_is_lacp_current,
4958     NULL,                       /* rule_choose_table */
4959     rule_alloc,
4960     rule_construct,
4961     rule_destruct,
4962     rule_dealloc,
4963     rule_get_stats,
4964     rule_execute,
4965     rule_modify_actions,
4966     get_drop_frags,
4967     set_drop_frags,
4968     packet_out,
4969     set_netflow,
4970     get_netflow_ids,
4971     set_sflow,
4972     set_cfm,
4973     get_cfm_fault,
4974     get_cfm_remote_mpids,
4975     bundle_set,
4976     bundle_remove,
4977     mirror_set,
4978     set_flood_vlans,
4979     is_mirror_output_bundle,
4980     forward_bpdu_changed,
4981 };