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