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