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