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