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