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