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