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