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