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