ofproto-dpif: Store patch port peer in struct ofport_dpif.
[sliver-openvswitch.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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-dpif.h"
20 #include "ofproto/ofproto-provider.h"
21
22 #include <errno.h>
23
24 #include "bfd.h"
25 #include "bond.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "connmgr.h"
29 #include "coverage.h"
30 #include "cfm.h"
31 #include "dpif.h"
32 #include "dynamic-string.h"
33 #include "fail-open.h"
34 #include "hmapx.h"
35 #include "lacp.h"
36 #include "learn.h"
37 #include "mac-learning.h"
38 #include "meta-flow.h"
39 #include "multipath.h"
40 #include "netdev-vport.h"
41 #include "netdev.h"
42 #include "netlink.h"
43 #include "nx-match.h"
44 #include "odp-util.h"
45 #include "odp-execute.h"
46 #include "ofp-util.h"
47 #include "ofpbuf.h"
48 #include "ofp-actions.h"
49 #include "ofp-parse.h"
50 #include "ofp-print.h"
51 #include "ofproto-dpif-governor.h"
52 #include "ofproto-dpif-ipfix.h"
53 #include "ofproto-dpif-sflow.h"
54 #include "ofproto-dpif-xlate.h"
55 #include "poll-loop.h"
56 #include "simap.h"
57 #include "smap.h"
58 #include "timer.h"
59 #include "tunnel.h"
60 #include "unaligned.h"
61 #include "unixctl.h"
62 #include "vlan-bitmap.h"
63 #include "vlog.h"
64
65 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
66
67 COVERAGE_DEFINE(ofproto_dpif_expired);
68 COVERAGE_DEFINE(facet_changed_rule);
69 COVERAGE_DEFINE(facet_revalidate);
70 COVERAGE_DEFINE(facet_unexpected);
71 COVERAGE_DEFINE(facet_suppress);
72
73 struct flow_miss;
74 struct facet;
75
76 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
77                                           const struct flow *,
78                                           struct flow_wildcards *wc);
79
80 static void rule_get_stats(struct rule *, uint64_t *packets, uint64_t *bytes);
81 static void rule_invalidate(const struct rule_dpif *);
82
83 static void mirror_destroy(struct ofmirror *);
84 static void update_mirror_stats(struct ofproto_dpif *ofproto,
85                                 mirror_mask_t mirrors,
86                                 uint64_t packets, uint64_t bytes);
87
88 static void bundle_remove(struct ofport *);
89 static void bundle_update(struct ofbundle *);
90 static void bundle_destroy(struct ofbundle *);
91 static void bundle_del_port(struct ofport_dpif *);
92 static void bundle_run(struct ofbundle *);
93 static void bundle_wait(struct ofbundle *);
94
95 static void stp_run(struct ofproto_dpif *ofproto);
96 static void stp_wait(struct ofproto_dpif *ofproto);
97 static int set_stp_port(struct ofport *,
98                         const struct ofproto_port_stp_settings *);
99
100 static void compose_slow_path(const struct ofproto_dpif *, const struct flow *,
101                               enum slow_path_reason,
102                               uint64_t *stub, size_t stub_size,
103                               const struct nlattr **actionsp,
104                               size_t *actions_lenp);
105
106 /* A subfacet (see "struct subfacet" below) has three possible installation
107  * states:
108  *
109  *   - SF_NOT_INSTALLED: Not installed in the datapath.  This will only be the
110  *     case just after the subfacet is created, just before the subfacet is
111  *     destroyed, or if the datapath returns an error when we try to install a
112  *     subfacet.
113  *
114  *   - SF_FAST_PATH: The subfacet's actions are installed in the datapath.
115  *
116  *   - SF_SLOW_PATH: An action that sends every packet for the subfacet through
117  *     ofproto_dpif is installed in the datapath.
118  */
119 enum subfacet_path {
120     SF_NOT_INSTALLED,           /* No datapath flow for this subfacet. */
121     SF_FAST_PATH,               /* Full actions are installed. */
122     SF_SLOW_PATH,               /* Send-to-userspace action is installed. */
123 };
124
125 /* A dpif flow and actions associated with a facet.
126  *
127  * See also the large comment on struct facet. */
128 struct subfacet {
129     /* Owners. */
130     struct hmap_node hmap_node; /* In struct ofproto_dpif 'subfacets' list. */
131     struct list list_node;      /* In struct facet's 'facets' list. */
132     struct facet *facet;        /* Owning facet. */
133     struct dpif_backer *backer; /* Owning backer. */
134
135     enum odp_key_fitness key_fitness;
136     struct nlattr *key;
137     int key_len;
138
139     long long int used;         /* Time last used; time created if not used. */
140     long long int created;      /* Time created. */
141
142     uint64_t dp_packet_count;   /* Last known packet count in the datapath. */
143     uint64_t dp_byte_count;     /* Last known byte count in the datapath. */
144
145     enum subfacet_path path;    /* Installed in datapath? */
146 };
147
148 #define SUBFACET_DESTROY_MAX_BATCH 50
149
150 static struct subfacet *subfacet_create(struct facet *, struct flow_miss *miss,
151                                         long long int now);
152 static struct subfacet *subfacet_find(struct dpif_backer *,
153                                       const struct nlattr *key, size_t key_len,
154                                       uint32_t key_hash);
155 static void subfacet_destroy(struct subfacet *);
156 static void subfacet_destroy__(struct subfacet *);
157 static void subfacet_destroy_batch(struct dpif_backer *,
158                                    struct subfacet **, int n);
159 static void subfacet_reset_dp_stats(struct subfacet *,
160                                     struct dpif_flow_stats *);
161 static void subfacet_update_stats(struct subfacet *,
162                                   const struct dpif_flow_stats *);
163 static int subfacet_install(struct subfacet *,
164                             const struct ofpbuf *odp_actions,
165                             struct dpif_flow_stats *);
166 static void subfacet_uninstall(struct subfacet *);
167
168 /* A unique, non-overlapping instantiation of an OpenFlow flow.
169  *
170  * A facet associates a "struct flow", which represents the Open vSwitch
171  * userspace idea of an exact-match flow, with one or more subfacets.
172  * While the facet is created based on an exact-match flow, it is stored
173  * within the ofproto based on the wildcards that could be expressed
174  * based on the flow table and other configuration.  (See the 'wc'
175  * description in "struct xlate_out" for more details.)
176  *
177  * Each subfacet tracks the datapath's idea of the flow equivalent to
178  * the facet.  When the kernel module (or other dpif implementation) and
179  * Open vSwitch userspace agree on the definition of a flow key, there
180  * is exactly one subfacet per facet.  If the dpif implementation
181  * supports more-specific flow matching than userspace, however, a facet
182  * can have more than one subfacet.  Examples include the dpif
183  * implementation not supporting the same wildcards as userspace or some
184  * distinction in flow that userspace simply doesn't understand.
185  *
186  * Flow expiration works in terms of subfacets, so a facet must have at
187  * least one subfacet or it will never expire, leaking memory. */
188 struct facet {
189     /* Owners. */
190     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
191     struct list list_node;       /* In owning rule's 'facets' list. */
192     struct rule_dpif *rule;      /* Owning rule. */
193
194     /* Owned data. */
195     struct list subfacets;
196     long long int used;         /* Time last used; time created if not used. */
197
198     /* Key. */
199     struct flow flow;           /* Flow of the creating subfacet. */
200     struct cls_rule cr;         /* In 'ofproto_dpif's facets classifier. */
201
202     /* These statistics:
203      *
204      *   - Do include packets and bytes sent "by hand", e.g. with
205      *     dpif_execute().
206      *
207      *   - Do include packets and bytes that were obtained from the datapath
208      *     when a subfacet's statistics were reset (e.g. dpif_flow_put() with
209      *     DPIF_FP_ZERO_STATS).
210      *
211      *   - Do not include packets or bytes that can be obtained from the
212      *     datapath for any existing subfacet.
213      */
214     uint64_t packet_count;       /* Number of packets received. */
215     uint64_t byte_count;         /* Number of bytes received. */
216
217     /* Resubmit statistics. */
218     uint64_t prev_packet_count;  /* Number of packets from last stats push. */
219     uint64_t prev_byte_count;    /* Number of bytes from last stats push. */
220     long long int prev_used;     /* Used time from last stats push. */
221
222     /* Accounting. */
223     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
224     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
225     uint8_t tcp_flags;           /* TCP flags seen for this 'rule'. */
226
227     struct xlate_out xout;
228
229     /* Storage for a single subfacet, to reduce malloc() time and space
230      * overhead.  (A facet always has at least one subfacet and in the common
231      * case has exactly one subfacet.  However, 'one_subfacet' may not
232      * always be valid, since it could have been removed after newer
233      * subfacets were pushed onto the 'subfacets' list.) */
234     struct subfacet one_subfacet;
235
236     long long int learn_rl;      /* Rate limiter for facet_learn(). */
237 };
238
239 static struct facet *facet_create(const struct flow_miss *, struct rule_dpif *,
240                                   struct xlate_out *,
241                                   struct dpif_flow_stats *);
242 static void facet_remove(struct facet *);
243 static void facet_free(struct facet *);
244
245 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
246 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
247                                         const struct flow *);
248 static bool facet_revalidate(struct facet *);
249 static bool facet_check_consistency(struct facet *);
250
251 static void facet_flush_stats(struct facet *);
252
253 static void facet_reset_counters(struct facet *);
254 static void facet_push_stats(struct facet *, bool may_learn);
255 static void facet_learn(struct facet *);
256 static void facet_account(struct facet *);
257 static void push_all_stats(void);
258
259 static bool facet_is_controller_flow(struct facet *);
260
261 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
262  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
263  * traffic egressing the 'ofport' with that priority should be marked with. */
264 struct priority_to_dscp {
265     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
266     uint32_t priority;          /* Priority of this queue (see struct flow). */
267
268     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
269 };
270
271 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
272  *
273  * This is deprecated.  It is only for compatibility with broken device drivers
274  * in old versions of Linux that do not properly support VLANs when VLAN
275  * devices are not used.  When broken device drivers are no longer in
276  * widespread use, we will delete these interfaces. */
277 struct vlan_splinter {
278     struct hmap_node realdev_vid_node;
279     struct hmap_node vlandev_node;
280     uint16_t realdev_ofp_port;
281     uint16_t vlandev_ofp_port;
282     int vid;
283 };
284
285 static bool vsp_adjust_flow(const struct ofproto_dpif *, struct flow *);
286 static void vsp_remove(struct ofport_dpif *);
287 static void vsp_add(struct ofport_dpif *, uint16_t realdev_ofp_port, int vid);
288
289 static uint16_t odp_port_to_ofp_port(const struct ofproto_dpif *,
290                                      uint32_t odp_port);
291
292 static struct ofport_dpif *
293 ofport_dpif_cast(const struct ofport *ofport)
294 {
295     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
296 }
297
298 static void port_run(struct ofport_dpif *);
299 static void port_run_fast(struct ofport_dpif *);
300 static void port_wait(struct ofport_dpif *);
301 static int set_bfd(struct ofport *, const struct smap *);
302 static int set_cfm(struct ofport *, const struct cfm_settings *);
303 static void ofport_clear_priorities(struct ofport_dpif *);
304 static void ofport_update_peer(struct ofport_dpif *);
305 static void run_fast_rl(void);
306
307 struct dpif_completion {
308     struct list list_node;
309     struct ofoperation *op;
310 };
311
312 /* Reasons that we might need to revalidate every facet, and corresponding
313  * coverage counters.
314  *
315  * A value of 0 means that there is no need to revalidate.
316  *
317  * It would be nice to have some cleaner way to integrate with coverage
318  * counters, but with only a few reasons I guess this is good enough for
319  * now. */
320 enum revalidate_reason {
321     REV_RECONFIGURE = 1,       /* Switch configuration changed. */
322     REV_STP,                   /* Spanning tree protocol port status change. */
323     REV_PORT_TOGGLED,          /* Port enabled or disabled by CFM, LACP, ...*/
324     REV_FLOW_TABLE,            /* Flow table changed. */
325     REV_INCONSISTENCY          /* Facet self-check failed. */
326 };
327 COVERAGE_DEFINE(rev_reconfigure);
328 COVERAGE_DEFINE(rev_stp);
329 COVERAGE_DEFINE(rev_port_toggled);
330 COVERAGE_DEFINE(rev_flow_table);
331 COVERAGE_DEFINE(rev_inconsistency);
332
333 /* Drop keys are odp flow keys which have drop flows installed in the kernel.
334  * These are datapath flows which have no associated ofproto, if they did we
335  * would use facets. */
336 struct drop_key {
337     struct hmap_node hmap_node;
338     struct nlattr *key;
339     size_t key_len;
340 };
341
342 struct avg_subfacet_rates {
343     double add_rate;   /* Moving average of new flows created per minute. */
344     double del_rate;   /* Moving average of flows deleted per minute. */
345 };
346
347 /* All datapaths of a given type share a single dpif backer instance. */
348 struct dpif_backer {
349     char *type;
350     int refcount;
351     struct dpif *dpif;
352     struct timer next_expiration;
353     struct hmap odp_to_ofport_map; /* ODP port to ofport mapping. */
354
355     struct simap tnl_backers;      /* Set of dpif ports backing tunnels. */
356
357     /* Facet revalidation flags applying to facets which use this backer. */
358     enum revalidate_reason need_revalidate; /* Revalidate every facet. */
359     struct tag_set revalidate_set; /* Revalidate only matching facets. */
360
361     struct hmap drop_keys; /* Set of dropped odp keys. */
362     bool recv_set_enable; /* Enables or disables receiving packets. */
363
364     struct hmap subfacets;
365     struct governor *governor;
366
367     /* Subfacet statistics.
368      *
369      * These keep track of the total number of subfacets added and deleted and
370      * flow life span.  They are useful for computing the flow rates stats
371      * exposed via "ovs-appctl dpif/show".  The goal is to learn about
372      * traffic patterns in ways that we can use later to improve Open vSwitch
373      * performance in new situations.  */
374     long long int created;           /* Time when it is created. */
375     unsigned max_n_subfacet;         /* Maximum number of flows */
376     unsigned avg_n_subfacet;         /* Average number of flows. */
377     long long int avg_subfacet_life; /* Average life span of subfacets. */
378
379     /* The average number of subfacets... */
380     struct avg_subfacet_rates hourly;   /* ...over the last hour. */
381     struct avg_subfacet_rates daily;    /* ...over the last day. */
382     struct avg_subfacet_rates lifetime; /* ...over the switch lifetime. */
383     long long int last_minute;          /* Last time 'hourly' was updated. */
384
385     /* Number of subfacets added or deleted since 'last_minute'. */
386     unsigned subfacet_add_count;
387     unsigned subfacet_del_count;
388
389     /* Number of subfacets added or deleted from 'created' to 'last_minute.' */
390     unsigned long long int total_subfacet_add_count;
391     unsigned long long int total_subfacet_del_count;
392 };
393
394 /* All existing ofproto_backer instances, indexed by ofproto->up.type. */
395 static struct shash all_dpif_backers = SHASH_INITIALIZER(&all_dpif_backers);
396
397 static void drop_key_clear(struct dpif_backer *);
398 static struct ofport_dpif *
399 odp_port_to_ofport(const struct dpif_backer *, uint32_t odp_port);
400 static void update_moving_averages(struct dpif_backer *backer);
401
402 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
403  * for debugging the asynchronous flow_mod implementation.) */
404 static bool clogged;
405
406 /* All existing ofproto_dpif instances, indexed by ->up.name. */
407 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
408
409 static void ofproto_dpif_unixctl_init(void);
410
411 /* Upcalls. */
412 #define FLOW_MISS_MAX_BATCH 50
413 static int handle_upcalls(struct dpif_backer *, unsigned int max_batch);
414
415 /* Flow expiration. */
416 static int expire(struct dpif_backer *);
417
418 /* NetFlow. */
419 static void send_netflow_active_timeouts(struct ofproto_dpif *);
420
421 /* Utilities. */
422 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
423
424 /* Global variables. */
425 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
426
427 /* Initial mappings of port to bridge mappings. */
428 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
429 \f
430 /* Factory functions. */
431
432 static void
433 init(const struct shash *iface_hints)
434 {
435     struct shash_node *node;
436
437     /* Make a local copy, since we don't own 'iface_hints' elements. */
438     SHASH_FOR_EACH(node, iface_hints) {
439         const struct iface_hint *orig_hint = node->data;
440         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
441
442         new_hint->br_name = xstrdup(orig_hint->br_name);
443         new_hint->br_type = xstrdup(orig_hint->br_type);
444         new_hint->ofp_port = orig_hint->ofp_port;
445
446         shash_add(&init_ofp_ports, node->name, new_hint);
447     }
448 }
449
450 static void
451 enumerate_types(struct sset *types)
452 {
453     dp_enumerate_types(types);
454 }
455
456 static int
457 enumerate_names(const char *type, struct sset *names)
458 {
459     struct ofproto_dpif *ofproto;
460
461     sset_clear(names);
462     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
463         if (strcmp(type, ofproto->up.type)) {
464             continue;
465         }
466         sset_add(names, ofproto->up.name);
467     }
468
469     return 0;
470 }
471
472 static int
473 del(const char *type, const char *name)
474 {
475     struct dpif *dpif;
476     int error;
477
478     error = dpif_open(name, type, &dpif);
479     if (!error) {
480         error = dpif_delete(dpif);
481         dpif_close(dpif);
482     }
483     return error;
484 }
485 \f
486 static const char *
487 port_open_type(const char *datapath_type, const char *port_type)
488 {
489     return dpif_port_open_type(datapath_type, port_type);
490 }
491
492 /* Type functions. */
493
494 static struct ofproto_dpif *
495 lookup_ofproto_dpif_by_port_name(const char *name)
496 {
497     struct ofproto_dpif *ofproto;
498
499     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
500         if (sset_contains(&ofproto->ports, name)) {
501             return ofproto;
502         }
503     }
504
505     return NULL;
506 }
507
508 static int
509 type_run(const char *type)
510 {
511     static long long int push_timer = LLONG_MIN;
512     struct dpif_backer *backer;
513     char *devname;
514     int error;
515
516     backer = shash_find_data(&all_dpif_backers, type);
517     if (!backer) {
518         /* This is not necessarily a problem, since backers are only
519          * created on demand. */
520         return 0;
521     }
522
523     dpif_run(backer->dpif);
524
525     /* The most natural place to push facet statistics is when they're pulled
526      * from the datapath.  However, when there are many flows in the datapath,
527      * this expensive operation can occur so frequently, that it reduces our
528      * ability to quickly set up flows.  To reduce the cost, we push statistics
529      * here instead. */
530     if (time_msec() > push_timer) {
531         push_timer = time_msec() + 2000;
532         push_all_stats();
533     }
534
535     /* If vswitchd started with other_config:flow_restore_wait set as "true",
536      * and the configuration has now changed to "false", enable receiving
537      * packets from the datapath. */
538     if (!backer->recv_set_enable && !ofproto_get_flow_restore_wait()) {
539         backer->recv_set_enable = true;
540
541         error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
542         if (error) {
543             VLOG_ERR("Failed to enable receiving packets in dpif.");
544             return error;
545         }
546         dpif_flow_flush(backer->dpif);
547         backer->need_revalidate = REV_RECONFIGURE;
548     }
549
550     if (backer->need_revalidate
551         || !tag_set_is_empty(&backer->revalidate_set)) {
552         struct tag_set revalidate_set = backer->revalidate_set;
553         bool need_revalidate = backer->need_revalidate;
554         struct ofproto_dpif *ofproto;
555         struct simap_node *node;
556         struct simap tmp_backers;
557
558         /* Handle tunnel garbage collection. */
559         simap_init(&tmp_backers);
560         simap_swap(&backer->tnl_backers, &tmp_backers);
561
562         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
563             struct ofport_dpif *iter;
564
565             if (backer != ofproto->backer) {
566                 continue;
567             }
568
569             HMAP_FOR_EACH (iter, up.hmap_node, &ofproto->up.ports) {
570                 char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
571                 const char *dp_port;
572
573                 if (!iter->tnl_port) {
574                     continue;
575                 }
576
577                 dp_port = netdev_vport_get_dpif_port(iter->up.netdev,
578                                                      namebuf, sizeof namebuf);
579                 node = simap_find(&tmp_backers, dp_port);
580                 if (node) {
581                     simap_put(&backer->tnl_backers, dp_port, node->data);
582                     simap_delete(&tmp_backers, node);
583                     node = simap_find(&backer->tnl_backers, dp_port);
584                 } else {
585                     node = simap_find(&backer->tnl_backers, dp_port);
586                     if (!node) {
587                         uint32_t odp_port = UINT32_MAX;
588
589                         if (!dpif_port_add(backer->dpif, iter->up.netdev,
590                                            &odp_port)) {
591                             simap_put(&backer->tnl_backers, dp_port, odp_port);
592                             node = simap_find(&backer->tnl_backers, dp_port);
593                         }
594                     }
595                 }
596
597                 iter->odp_port = node ? node->data : OVSP_NONE;
598                 if (tnl_port_reconfigure(&iter->up, iter->odp_port,
599                                          &iter->tnl_port)) {
600                     backer->need_revalidate = REV_RECONFIGURE;
601                 }
602             }
603         }
604
605         SIMAP_FOR_EACH (node, &tmp_backers) {
606             dpif_port_del(backer->dpif, node->data);
607         }
608         simap_destroy(&tmp_backers);
609
610         switch (backer->need_revalidate) {
611         case REV_RECONFIGURE:   COVERAGE_INC(rev_reconfigure);   break;
612         case REV_STP:           COVERAGE_INC(rev_stp);           break;
613         case REV_PORT_TOGGLED:  COVERAGE_INC(rev_port_toggled);  break;
614         case REV_FLOW_TABLE:    COVERAGE_INC(rev_flow_table);    break;
615         case REV_INCONSISTENCY: COVERAGE_INC(rev_inconsistency); break;
616         }
617
618         if (backer->need_revalidate) {
619             /* Clear the drop_keys in case we should now be accepting some
620              * formerly dropped flows. */
621             drop_key_clear(backer);
622         }
623
624         /* Clear the revalidation flags. */
625         tag_set_init(&backer->revalidate_set);
626         backer->need_revalidate = 0;
627
628         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
629             struct facet *facet, *next;
630             struct cls_cursor cursor;
631
632             if (ofproto->backer != backer) {
633                 continue;
634             }
635
636             cls_cursor_init(&cursor, &ofproto->facets, NULL);
637             CLS_CURSOR_FOR_EACH_SAFE (facet, next, cr, &cursor) {
638                 if (need_revalidate
639                     || tag_set_intersects(&revalidate_set, facet->xout.tags)) {
640                     facet_revalidate(facet);
641                     run_fast_rl();
642                 }
643             }
644         }
645     }
646
647     if (!backer->recv_set_enable) {
648         /* Wake up before a max of 1000ms. */
649         timer_set_duration(&backer->next_expiration, 1000);
650     } else if (timer_expired(&backer->next_expiration)) {
651         int delay = expire(backer);
652         timer_set_duration(&backer->next_expiration, delay);
653     }
654
655     /* Check for port changes in the dpif. */
656     while ((error = dpif_port_poll(backer->dpif, &devname)) == 0) {
657         struct ofproto_dpif *ofproto;
658         struct dpif_port port;
659
660         /* Don't report on the datapath's device. */
661         if (!strcmp(devname, dpif_base_name(backer->dpif))) {
662             goto next;
663         }
664
665         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
666                        &all_ofproto_dpifs) {
667             if (simap_contains(&ofproto->backer->tnl_backers, devname)) {
668                 goto next;
669             }
670         }
671
672         ofproto = lookup_ofproto_dpif_by_port_name(devname);
673         if (dpif_port_query_by_name(backer->dpif, devname, &port)) {
674             /* The port was removed.  If we know the datapath,
675              * report it through poll_set().  If we don't, it may be
676              * notifying us of a removal we initiated, so ignore it.
677              * If there's a pending ENOBUFS, let it stand, since
678              * everything will be reevaluated. */
679             if (ofproto && ofproto->port_poll_errno != ENOBUFS) {
680                 sset_add(&ofproto->port_poll_set, devname);
681                 ofproto->port_poll_errno = 0;
682             }
683         } else if (!ofproto) {
684             /* The port was added, but we don't know with which
685              * ofproto we should associate it.  Delete it. */
686             dpif_port_del(backer->dpif, port.port_no);
687         }
688         dpif_port_destroy(&port);
689
690     next:
691         free(devname);
692     }
693
694     if (error != EAGAIN) {
695         struct ofproto_dpif *ofproto;
696
697         /* There was some sort of error, so propagate it to all
698          * ofprotos that use this backer. */
699         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
700                        &all_ofproto_dpifs) {
701             if (ofproto->backer == backer) {
702                 sset_clear(&ofproto->port_poll_set);
703                 ofproto->port_poll_errno = error;
704             }
705         }
706     }
707
708     if (backer->governor) {
709         size_t n_subfacets;
710
711         governor_run(backer->governor);
712
713         /* If the governor has shrunk to its minimum size and the number of
714          * subfacets has dwindled, then drop the governor entirely.
715          *
716          * For hysteresis, the number of subfacets to drop the governor is
717          * smaller than the number needed to trigger its creation. */
718         n_subfacets = hmap_count(&backer->subfacets);
719         if (n_subfacets * 4 < flow_eviction_threshold
720             && governor_is_idle(backer->governor)) {
721             governor_destroy(backer->governor);
722             backer->governor = NULL;
723         }
724     }
725
726     return 0;
727 }
728
729 static int
730 dpif_backer_run_fast(struct dpif_backer *backer, int max_batch)
731 {
732     unsigned int work;
733
734     /* If recv_set_enable is false, we should not handle upcalls. */
735     if (!backer->recv_set_enable) {
736         return 0;
737     }
738
739     /* Handle one or more batches of upcalls, until there's nothing left to do
740      * or until we do a fixed total amount of work.
741      *
742      * We do work in batches because it can be much cheaper to set up a number
743      * of flows and fire off their patches all at once.  We do multiple batches
744      * because in some cases handling a packet can cause another packet to be
745      * queued almost immediately as part of the return flow.  Both
746      * optimizations can make major improvements on some benchmarks and
747      * presumably for real traffic as well. */
748     work = 0;
749     while (work < max_batch) {
750         int retval = handle_upcalls(backer, max_batch - work);
751         if (retval <= 0) {
752             return -retval;
753         }
754         work += retval;
755     }
756
757     return 0;
758 }
759
760 static int
761 type_run_fast(const char *type)
762 {
763     struct dpif_backer *backer;
764
765     backer = shash_find_data(&all_dpif_backers, type);
766     if (!backer) {
767         /* This is not necessarily a problem, since backers are only
768          * created on demand. */
769         return 0;
770     }
771
772     return dpif_backer_run_fast(backer, FLOW_MISS_MAX_BATCH);
773 }
774
775 static void
776 run_fast_rl(void)
777 {
778     static long long int port_rl = LLONG_MIN;
779     static unsigned int backer_rl = 0;
780
781     if (time_msec() >= port_rl) {
782         struct ofproto_dpif *ofproto;
783         struct ofport_dpif *ofport;
784
785         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
786
787             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
788                 port_run_fast(ofport);
789             }
790         }
791         port_rl = time_msec() + 200;
792     }
793
794     /* XXX: We have to be careful not to do too much work in this function.  If
795      * we call dpif_backer_run_fast() too often, or with too large a batch,
796      * performance improves signifcantly, but at a cost.  It's possible for the
797      * number of flows in the datapath to increase without bound, and for poll
798      * loops to take 10s of seconds.   The correct solution to this problem,
799      * long term, is to separate flow miss handling into it's own thread so it
800      * isn't affected by revalidations, and expirations.  Until then, this is
801      * the best we can do. */
802     if (++backer_rl >= 10) {
803         struct shash_node *node;
804
805         backer_rl = 0;
806         SHASH_FOR_EACH (node, &all_dpif_backers) {
807             dpif_backer_run_fast(node->data, 1);
808         }
809     }
810 }
811
812 static void
813 type_wait(const char *type)
814 {
815     struct dpif_backer *backer;
816
817     backer = shash_find_data(&all_dpif_backers, type);
818     if (!backer) {
819         /* This is not necessarily a problem, since backers are only
820          * created on demand. */
821         return;
822     }
823
824     if (backer->governor) {
825         governor_wait(backer->governor);
826     }
827
828     timer_wait(&backer->next_expiration);
829 }
830 \f
831 /* Basic life-cycle. */
832
833 static int add_internal_flows(struct ofproto_dpif *);
834
835 static struct ofproto *
836 alloc(void)
837 {
838     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
839     return &ofproto->up;
840 }
841
842 static void
843 dealloc(struct ofproto *ofproto_)
844 {
845     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
846     free(ofproto);
847 }
848
849 static void
850 close_dpif_backer(struct dpif_backer *backer)
851 {
852     struct shash_node *node;
853
854     ovs_assert(backer->refcount > 0);
855
856     if (--backer->refcount) {
857         return;
858     }
859
860     drop_key_clear(backer);
861     hmap_destroy(&backer->drop_keys);
862
863     simap_destroy(&backer->tnl_backers);
864     hmap_destroy(&backer->odp_to_ofport_map);
865     node = shash_find(&all_dpif_backers, backer->type);
866     free(backer->type);
867     shash_delete(&all_dpif_backers, node);
868     dpif_close(backer->dpif);
869
870     ovs_assert(hmap_is_empty(&backer->subfacets));
871     hmap_destroy(&backer->subfacets);
872     governor_destroy(backer->governor);
873
874     free(backer);
875 }
876
877 /* Datapath port slated for removal from datapath. */
878 struct odp_garbage {
879     struct list list_node;
880     uint32_t odp_port;
881 };
882
883 static int
884 open_dpif_backer(const char *type, struct dpif_backer **backerp)
885 {
886     struct dpif_backer *backer;
887     struct dpif_port_dump port_dump;
888     struct dpif_port port;
889     struct shash_node *node;
890     struct list garbage_list;
891     struct odp_garbage *garbage, *next;
892     struct sset names;
893     char *backer_name;
894     const char *name;
895     int error;
896
897     backer = shash_find_data(&all_dpif_backers, type);
898     if (backer) {
899         backer->refcount++;
900         *backerp = backer;
901         return 0;
902     }
903
904     backer_name = xasprintf("ovs-%s", type);
905
906     /* Remove any existing datapaths, since we assume we're the only
907      * userspace controlling the datapath. */
908     sset_init(&names);
909     dp_enumerate_names(type, &names);
910     SSET_FOR_EACH(name, &names) {
911         struct dpif *old_dpif;
912
913         /* Don't remove our backer if it exists. */
914         if (!strcmp(name, backer_name)) {
915             continue;
916         }
917
918         if (dpif_open(name, type, &old_dpif)) {
919             VLOG_WARN("couldn't open old datapath %s to remove it", name);
920         } else {
921             dpif_delete(old_dpif);
922             dpif_close(old_dpif);
923         }
924     }
925     sset_destroy(&names);
926
927     backer = xmalloc(sizeof *backer);
928
929     error = dpif_create_and_open(backer_name, type, &backer->dpif);
930     free(backer_name);
931     if (error) {
932         VLOG_ERR("failed to open datapath of type %s: %s", type,
933                  strerror(error));
934         free(backer);
935         return error;
936     }
937
938     backer->type = xstrdup(type);
939     backer->governor = NULL;
940     backer->refcount = 1;
941     hmap_init(&backer->odp_to_ofport_map);
942     hmap_init(&backer->drop_keys);
943     hmap_init(&backer->subfacets);
944     timer_set_duration(&backer->next_expiration, 1000);
945     backer->need_revalidate = 0;
946     simap_init(&backer->tnl_backers);
947     tag_set_init(&backer->revalidate_set);
948     backer->recv_set_enable = !ofproto_get_flow_restore_wait();
949     *backerp = backer;
950
951     if (backer->recv_set_enable) {
952         dpif_flow_flush(backer->dpif);
953     }
954
955     /* Loop through the ports already on the datapath and remove any
956      * that we don't need anymore. */
957     list_init(&garbage_list);
958     dpif_port_dump_start(&port_dump, backer->dpif);
959     while (dpif_port_dump_next(&port_dump, &port)) {
960         node = shash_find(&init_ofp_ports, port.name);
961         if (!node && strcmp(port.name, dpif_base_name(backer->dpif))) {
962             garbage = xmalloc(sizeof *garbage);
963             garbage->odp_port = port.port_no;
964             list_push_front(&garbage_list, &garbage->list_node);
965         }
966     }
967     dpif_port_dump_done(&port_dump);
968
969     LIST_FOR_EACH_SAFE (garbage, next, list_node, &garbage_list) {
970         dpif_port_del(backer->dpif, garbage->odp_port);
971         list_remove(&garbage->list_node);
972         free(garbage);
973     }
974
975     shash_add(&all_dpif_backers, type, backer);
976
977     error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
978     if (error) {
979         VLOG_ERR("failed to listen on datapath of type %s: %s",
980                  type, strerror(error));
981         close_dpif_backer(backer);
982         return error;
983     }
984
985     backer->max_n_subfacet = 0;
986     backer->created = time_msec();
987     backer->last_minute = backer->created;
988     memset(&backer->hourly, 0, sizeof backer->hourly);
989     memset(&backer->daily, 0, sizeof backer->daily);
990     memset(&backer->lifetime, 0, sizeof backer->lifetime);
991     backer->subfacet_add_count = 0;
992     backer->subfacet_del_count = 0;
993     backer->total_subfacet_add_count = 0;
994     backer->total_subfacet_del_count = 0;
995     backer->avg_n_subfacet = 0;
996     backer->avg_subfacet_life = 0;
997
998     return error;
999 }
1000
1001 static int
1002 construct(struct ofproto *ofproto_)
1003 {
1004     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1005     struct shash_node *node, *next;
1006     int max_ports;
1007     int error;
1008     int i;
1009
1010     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
1011     if (error) {
1012         return error;
1013     }
1014
1015     max_ports = dpif_get_max_ports(ofproto->backer->dpif);
1016     ofproto_init_max_ports(ofproto_, MIN(max_ports, OFPP_MAX));
1017
1018     ofproto->netflow = NULL;
1019     ofproto->sflow = NULL;
1020     ofproto->ipfix = NULL;
1021     ofproto->stp = NULL;
1022     hmap_init(&ofproto->bundles);
1023     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
1024     for (i = 0; i < MAX_MIRRORS; i++) {
1025         ofproto->mirrors[i] = NULL;
1026     }
1027     ofproto->has_bonded_bundles = false;
1028
1029     classifier_init(&ofproto->facets);
1030     ofproto->consistency_rl = LLONG_MIN;
1031
1032     for (i = 0; i < N_TABLES; i++) {
1033         struct table_dpif *table = &ofproto->tables[i];
1034
1035         table->catchall_table = NULL;
1036         table->other_table = NULL;
1037         table->basis = random_uint32();
1038     }
1039
1040     list_init(&ofproto->completions);
1041
1042     ofproto_dpif_unixctl_init();
1043
1044     ofproto->has_mirrors = false;
1045     ofproto->has_bundle_action = false;
1046
1047     hmap_init(&ofproto->vlandev_map);
1048     hmap_init(&ofproto->realdev_vid_map);
1049
1050     sset_init(&ofproto->ports);
1051     sset_init(&ofproto->ghost_ports);
1052     sset_init(&ofproto->port_poll_set);
1053     ofproto->port_poll_errno = 0;
1054
1055     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1056         struct iface_hint *iface_hint = node->data;
1057
1058         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1059             /* Check if the datapath already has this port. */
1060             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1061                 sset_add(&ofproto->ports, node->name);
1062             }
1063
1064             free(iface_hint->br_name);
1065             free(iface_hint->br_type);
1066             free(iface_hint);
1067             shash_delete(&init_ofp_ports, node);
1068         }
1069     }
1070
1071     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1072                 hash_string(ofproto->up.name, 0));
1073     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1074
1075     ofproto_init_tables(ofproto_, N_TABLES);
1076     error = add_internal_flows(ofproto);
1077     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1078
1079     ofproto->n_hit = 0;
1080     ofproto->n_missed = 0;
1081
1082     return error;
1083 }
1084
1085 static int
1086 add_internal_flow(struct ofproto_dpif *ofproto, int id,
1087                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1088 {
1089     struct ofputil_flow_mod fm;
1090     int error;
1091
1092     match_init_catchall(&fm.match);
1093     fm.priority = 0;
1094     match_set_reg(&fm.match, 0, id);
1095     fm.new_cookie = htonll(0);
1096     fm.cookie = htonll(0);
1097     fm.cookie_mask = htonll(0);
1098     fm.table_id = TBL_INTERNAL;
1099     fm.command = OFPFC_ADD;
1100     fm.idle_timeout = 0;
1101     fm.hard_timeout = 0;
1102     fm.buffer_id = 0;
1103     fm.out_port = 0;
1104     fm.flags = 0;
1105     fm.ofpacts = ofpacts->data;
1106     fm.ofpacts_len = ofpacts->size;
1107
1108     error = ofproto_flow_mod(&ofproto->up, &fm);
1109     if (error) {
1110         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
1111                     id, ofperr_to_string(error));
1112         return error;
1113     }
1114
1115     *rulep = rule_dpif_lookup_in_table(ofproto, &fm.match.flow, NULL,
1116                                        TBL_INTERNAL);
1117     ovs_assert(*rulep != NULL);
1118
1119     return 0;
1120 }
1121
1122 static int
1123 add_internal_flows(struct ofproto_dpif *ofproto)
1124 {
1125     struct ofpact_controller *controller;
1126     uint64_t ofpacts_stub[128 / 8];
1127     struct ofpbuf ofpacts;
1128     int error;
1129     int id;
1130
1131     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1132     id = 1;
1133
1134     controller = ofpact_put_CONTROLLER(&ofpacts);
1135     controller->max_len = UINT16_MAX;
1136     controller->controller_id = 0;
1137     controller->reason = OFPR_NO_MATCH;
1138     ofpact_pad(&ofpacts);
1139
1140     error = add_internal_flow(ofproto, id++, &ofpacts, &ofproto->miss_rule);
1141     if (error) {
1142         return error;
1143     }
1144
1145     ofpbuf_clear(&ofpacts);
1146     error = add_internal_flow(ofproto, id++, &ofpacts,
1147                               &ofproto->no_packet_in_rule);
1148     if (error) {
1149         return error;
1150     }
1151
1152     error = add_internal_flow(ofproto, id++, &ofpacts,
1153                               &ofproto->drop_frags_rule);
1154     return error;
1155 }
1156
1157 static void
1158 complete_operations(struct ofproto_dpif *ofproto)
1159 {
1160     struct dpif_completion *c, *next;
1161
1162     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
1163         ofoperation_complete(c->op, 0);
1164         list_remove(&c->list_node);
1165         free(c);
1166     }
1167 }
1168
1169 static void
1170 destruct(struct ofproto *ofproto_)
1171 {
1172     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1173     struct rule_dpif *rule, *next_rule;
1174     struct oftable *table;
1175     int i;
1176
1177     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1178     complete_operations(ofproto);
1179
1180     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1181         struct cls_cursor cursor;
1182
1183         cls_cursor_init(&cursor, &table->cls, NULL);
1184         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1185             ofproto_rule_destroy(&rule->up);
1186         }
1187     }
1188
1189     for (i = 0; i < MAX_MIRRORS; i++) {
1190         mirror_destroy(ofproto->mirrors[i]);
1191     }
1192
1193     netflow_destroy(ofproto->netflow);
1194     dpif_sflow_destroy(ofproto->sflow);
1195     hmap_destroy(&ofproto->bundles);
1196     mac_learning_destroy(ofproto->ml);
1197
1198     classifier_destroy(&ofproto->facets);
1199
1200     hmap_destroy(&ofproto->vlandev_map);
1201     hmap_destroy(&ofproto->realdev_vid_map);
1202
1203     sset_destroy(&ofproto->ports);
1204     sset_destroy(&ofproto->ghost_ports);
1205     sset_destroy(&ofproto->port_poll_set);
1206
1207     close_dpif_backer(ofproto->backer);
1208 }
1209
1210 static int
1211 run_fast(struct ofproto *ofproto_)
1212 {
1213     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1214     struct ofport_dpif *ofport;
1215
1216     /* Do not perform any periodic activity required by 'ofproto' while
1217      * waiting for flow restore to complete. */
1218     if (ofproto_get_flow_restore_wait()) {
1219         return 0;
1220     }
1221
1222     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1223         port_run_fast(ofport);
1224     }
1225
1226     return 0;
1227 }
1228
1229 static int
1230 run(struct ofproto *ofproto_)
1231 {
1232     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1233     struct ofport_dpif *ofport;
1234     struct ofbundle *bundle;
1235     int error;
1236
1237     if (!clogged) {
1238         complete_operations(ofproto);
1239     }
1240
1241     /* Do not perform any periodic activity below required by 'ofproto' while
1242      * waiting for flow restore to complete. */
1243     if (ofproto_get_flow_restore_wait()) {
1244         return 0;
1245     }
1246
1247     error = run_fast(ofproto_);
1248     if (error) {
1249         return error;
1250     }
1251
1252     if (ofproto->netflow) {
1253         if (netflow_run(ofproto->netflow)) {
1254             send_netflow_active_timeouts(ofproto);
1255         }
1256     }
1257     if (ofproto->sflow) {
1258         dpif_sflow_run(ofproto->sflow);
1259     }
1260
1261     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1262         port_run(ofport);
1263     }
1264     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1265         bundle_run(bundle);
1266     }
1267
1268     stp_run(ofproto);
1269     mac_learning_run(ofproto->ml, &ofproto->backer->revalidate_set);
1270
1271     /* Check the consistency of a random facet, to aid debugging. */
1272     if (time_msec() >= ofproto->consistency_rl
1273         && !classifier_is_empty(&ofproto->facets)
1274         && !ofproto->backer->need_revalidate) {
1275         struct cls_table *table;
1276         struct cls_rule *cr;
1277         struct facet *facet;
1278
1279         ofproto->consistency_rl = time_msec() + 250;
1280
1281         table = CONTAINER_OF(hmap_random_node(&ofproto->facets.tables),
1282                              struct cls_table, hmap_node);
1283         cr = CONTAINER_OF(hmap_random_node(&table->rules), struct cls_rule,
1284                           hmap_node);
1285         facet = CONTAINER_OF(cr, struct facet, cr);
1286
1287         if (!tag_set_intersects(&ofproto->backer->revalidate_set,
1288                                 facet->xout.tags)) {
1289             if (!facet_check_consistency(facet)) {
1290                 ofproto->backer->need_revalidate = REV_INCONSISTENCY;
1291             }
1292         }
1293     }
1294
1295     return 0;
1296 }
1297
1298 static void
1299 wait(struct ofproto *ofproto_)
1300 {
1301     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1302     struct ofport_dpif *ofport;
1303     struct ofbundle *bundle;
1304
1305     if (!clogged && !list_is_empty(&ofproto->completions)) {
1306         poll_immediate_wake();
1307     }
1308
1309     if (ofproto_get_flow_restore_wait()) {
1310         return;
1311     }
1312
1313     dpif_wait(ofproto->backer->dpif);
1314     dpif_recv_wait(ofproto->backer->dpif);
1315     if (ofproto->sflow) {
1316         dpif_sflow_wait(ofproto->sflow);
1317     }
1318     if (!tag_set_is_empty(&ofproto->backer->revalidate_set)) {
1319         poll_immediate_wake();
1320     }
1321     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1322         port_wait(ofport);
1323     }
1324     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1325         bundle_wait(bundle);
1326     }
1327     if (ofproto->netflow) {
1328         netflow_wait(ofproto->netflow);
1329     }
1330     mac_learning_wait(ofproto->ml);
1331     stp_wait(ofproto);
1332     if (ofproto->backer->need_revalidate) {
1333         /* Shouldn't happen, but if it does just go around again. */
1334         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1335         poll_immediate_wake();
1336     }
1337 }
1338
1339 static void
1340 get_memory_usage(const struct ofproto *ofproto_, struct simap *usage)
1341 {
1342     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1343     struct cls_cursor cursor;
1344     size_t n_subfacets = 0;
1345     struct facet *facet;
1346
1347     simap_increase(usage, "facets", classifier_count(&ofproto->facets));
1348
1349     cls_cursor_init(&cursor, &ofproto->facets, NULL);
1350     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
1351         n_subfacets += list_size(&facet->subfacets);
1352     }
1353     simap_increase(usage, "subfacets", n_subfacets);
1354 }
1355
1356 static void
1357 flush(struct ofproto *ofproto_)
1358 {
1359     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1360     struct subfacet *subfacet, *next_subfacet;
1361     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
1362     int n_batch;
1363
1364     n_batch = 0;
1365     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
1366                         &ofproto->backer->subfacets) {
1367         if (ofproto_dpif_cast(subfacet->facet->rule->up.ofproto) != ofproto) {
1368             continue;
1369         }
1370
1371         if (subfacet->path != SF_NOT_INSTALLED) {
1372             batch[n_batch++] = subfacet;
1373             if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
1374                 subfacet_destroy_batch(ofproto->backer, batch, n_batch);
1375                 n_batch = 0;
1376             }
1377         } else {
1378             subfacet_destroy(subfacet);
1379         }
1380     }
1381
1382     if (n_batch > 0) {
1383         subfacet_destroy_batch(ofproto->backer, batch, n_batch);
1384     }
1385 }
1386
1387 static void
1388 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1389              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1390 {
1391     *arp_match_ip = true;
1392     *actions = (OFPUTIL_A_OUTPUT |
1393                 OFPUTIL_A_SET_VLAN_VID |
1394                 OFPUTIL_A_SET_VLAN_PCP |
1395                 OFPUTIL_A_STRIP_VLAN |
1396                 OFPUTIL_A_SET_DL_SRC |
1397                 OFPUTIL_A_SET_DL_DST |
1398                 OFPUTIL_A_SET_NW_SRC |
1399                 OFPUTIL_A_SET_NW_DST |
1400                 OFPUTIL_A_SET_NW_TOS |
1401                 OFPUTIL_A_SET_TP_SRC |
1402                 OFPUTIL_A_SET_TP_DST |
1403                 OFPUTIL_A_ENQUEUE);
1404 }
1405
1406 static void
1407 get_tables(struct ofproto *ofproto_, struct ofp12_table_stats *ots)
1408 {
1409     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1410     struct dpif_dp_stats s;
1411     uint64_t n_miss, n_no_pkt_in, n_bytes, n_dropped_frags;
1412     uint64_t n_lookup;
1413
1414     strcpy(ots->name, "classifier");
1415
1416     dpif_get_dp_stats(ofproto->backer->dpif, &s);
1417     rule_get_stats(&ofproto->miss_rule->up, &n_miss, &n_bytes);
1418     rule_get_stats(&ofproto->no_packet_in_rule->up, &n_no_pkt_in, &n_bytes);
1419     rule_get_stats(&ofproto->drop_frags_rule->up, &n_dropped_frags, &n_bytes);
1420
1421     n_lookup = s.n_hit + s.n_missed - n_dropped_frags;
1422     ots->lookup_count = htonll(n_lookup);
1423     ots->matched_count = htonll(n_lookup - n_miss - n_no_pkt_in);
1424 }
1425
1426 static struct ofport *
1427 port_alloc(void)
1428 {
1429     struct ofport_dpif *port = xmalloc(sizeof *port);
1430     return &port->up;
1431 }
1432
1433 static void
1434 port_dealloc(struct ofport *port_)
1435 {
1436     struct ofport_dpif *port = ofport_dpif_cast(port_);
1437     free(port);
1438 }
1439
1440 static int
1441 port_construct(struct ofport *port_)
1442 {
1443     struct ofport_dpif *port = ofport_dpif_cast(port_);
1444     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1445     const struct netdev *netdev = port->up.netdev;
1446     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1447     struct dpif_port dpif_port;
1448     int error;
1449
1450     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1451     port->bundle = NULL;
1452     port->cfm = NULL;
1453     port->bfd = NULL;
1454     port->tag = tag_create_random();
1455     port->may_enable = true;
1456     port->stp_port = NULL;
1457     port->stp_state = STP_DISABLED;
1458     port->tnl_port = NULL;
1459     port->peer = NULL;
1460     hmap_init(&port->priorities);
1461     port->realdev_ofp_port = 0;
1462     port->vlandev_vid = 0;
1463     port->carrier_seq = netdev_get_carrier_resets(netdev);
1464
1465     if (netdev_vport_is_patch(netdev)) {
1466         /* By bailing out here, we don't submit the port to the sFlow module
1467          * to be considered for counter polling export.  This is correct
1468          * because the patch port represents an interface that sFlow considers
1469          * to be "internal" to the switch as a whole, and therefore not an
1470          * candidate for counter polling. */
1471         port->odp_port = OVSP_NONE;
1472         ofport_update_peer(port);
1473         return 0;
1474     }
1475
1476     error = dpif_port_query_by_name(ofproto->backer->dpif,
1477                                     netdev_vport_get_dpif_port(netdev, namebuf,
1478                                                                sizeof namebuf),
1479                                     &dpif_port);
1480     if (error) {
1481         return error;
1482     }
1483
1484     port->odp_port = dpif_port.port_no;
1485
1486     if (netdev_get_tunnel_config(netdev)) {
1487         port->tnl_port = tnl_port_add(&port->up, port->odp_port);
1488     } else {
1489         /* Sanity-check that a mapping doesn't already exist.  This
1490          * shouldn't happen for non-tunnel ports. */
1491         if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1492             VLOG_ERR("port %s already has an OpenFlow port number",
1493                      dpif_port.name);
1494             dpif_port_destroy(&dpif_port);
1495             return EBUSY;
1496         }
1497
1498         hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1499                     hash_int(port->odp_port, 0));
1500     }
1501     dpif_port_destroy(&dpif_port);
1502
1503     if (ofproto->sflow) {
1504         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1505     }
1506
1507     return 0;
1508 }
1509
1510 static void
1511 port_destruct(struct ofport *port_)
1512 {
1513     struct ofport_dpif *port = ofport_dpif_cast(port_);
1514     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1515     const char *devname = netdev_get_name(port->up.netdev);
1516     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1517     const char *dp_port_name;
1518
1519     dp_port_name = netdev_vport_get_dpif_port(port->up.netdev, namebuf,
1520                                               sizeof namebuf);
1521     if (dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
1522         /* The underlying device is still there, so delete it.  This
1523          * happens when the ofproto is being destroyed, since the caller
1524          * assumes that removal of attached ports will happen as part of
1525          * destruction. */
1526         if (!port->tnl_port) {
1527             dpif_port_del(ofproto->backer->dpif, port->odp_port);
1528         }
1529         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1530     }
1531
1532     if (port->peer) {
1533         port->peer->peer = NULL;
1534         port->peer = NULL;
1535     }
1536
1537     if (port->odp_port != OVSP_NONE && !port->tnl_port) {
1538         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1539     }
1540
1541     tnl_port_del(port->tnl_port);
1542     sset_find_and_delete(&ofproto->ports, devname);
1543     sset_find_and_delete(&ofproto->ghost_ports, devname);
1544     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1545     bundle_remove(port_);
1546     set_cfm(port_, NULL);
1547     set_bfd(port_, NULL);
1548     if (ofproto->sflow) {
1549         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1550     }
1551
1552     ofport_clear_priorities(port);
1553     hmap_destroy(&port->priorities);
1554 }
1555
1556 static void
1557 port_modified(struct ofport *port_)
1558 {
1559     struct ofport_dpif *port = ofport_dpif_cast(port_);
1560
1561     if (port->bundle && port->bundle->bond) {
1562         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1563     }
1564
1565     if (port->cfm) {
1566         cfm_set_netdev(port->cfm, port->up.netdev);
1567     }
1568
1569     if (port->tnl_port && tnl_port_reconfigure(&port->up, port->odp_port,
1570                                                &port->tnl_port)) {
1571         ofproto_dpif_cast(port->up.ofproto)->backer->need_revalidate = true;
1572     }
1573
1574     ofport_update_peer(port);
1575 }
1576
1577 static void
1578 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1579 {
1580     struct ofport_dpif *port = ofport_dpif_cast(port_);
1581     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1582     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1583
1584     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1585                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1586                    OFPUTIL_PC_NO_PACKET_IN)) {
1587         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1588
1589         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1590             bundle_update(port->bundle);
1591         }
1592     }
1593 }
1594
1595 static int
1596 set_sflow(struct ofproto *ofproto_,
1597           const struct ofproto_sflow_options *sflow_options)
1598 {
1599     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1600     struct dpif_sflow *ds = ofproto->sflow;
1601
1602     if (sflow_options) {
1603         if (!ds) {
1604             struct ofport_dpif *ofport;
1605
1606             ds = ofproto->sflow = dpif_sflow_create();
1607             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1608                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1609             }
1610             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1611         }
1612         dpif_sflow_set_options(ds, sflow_options);
1613     } else {
1614         if (ds) {
1615             dpif_sflow_destroy(ds);
1616             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1617             ofproto->sflow = NULL;
1618         }
1619     }
1620     return 0;
1621 }
1622
1623 static int
1624 set_ipfix(
1625     struct ofproto *ofproto_,
1626     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
1627     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
1628     size_t n_flow_exporters_options)
1629 {
1630     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1631     struct dpif_ipfix *di = ofproto->ipfix;
1632
1633     if (bridge_exporter_options || flow_exporters_options) {
1634         if (!di) {
1635             di = ofproto->ipfix = dpif_ipfix_create();
1636         }
1637         dpif_ipfix_set_options(
1638             di, bridge_exporter_options, flow_exporters_options,
1639             n_flow_exporters_options);
1640     } else {
1641         if (di) {
1642             dpif_ipfix_destroy(di);
1643             ofproto->ipfix = NULL;
1644         }
1645     }
1646     return 0;
1647 }
1648
1649 static int
1650 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1651 {
1652     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1653     int error;
1654
1655     if (!s) {
1656         error = 0;
1657     } else {
1658         if (!ofport->cfm) {
1659             struct ofproto_dpif *ofproto;
1660
1661             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1662             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1663             ofport->cfm = cfm_create(ofport->up.netdev);
1664         }
1665
1666         if (cfm_configure(ofport->cfm, s)) {
1667             return 0;
1668         }
1669
1670         error = EINVAL;
1671     }
1672     cfm_destroy(ofport->cfm);
1673     ofport->cfm = NULL;
1674     return error;
1675 }
1676
1677 static bool
1678 get_cfm_status(const struct ofport *ofport_,
1679                struct ofproto_cfm_status *status)
1680 {
1681     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1682
1683     if (ofport->cfm) {
1684         status->faults = cfm_get_fault(ofport->cfm);
1685         status->remote_opstate = cfm_get_opup(ofport->cfm);
1686         status->health = cfm_get_health(ofport->cfm);
1687         cfm_get_remote_mpids(ofport->cfm, &status->rmps, &status->n_rmps);
1688         return true;
1689     } else {
1690         return false;
1691     }
1692 }
1693
1694 static int
1695 set_bfd(struct ofport *ofport_, const struct smap *cfg)
1696 {
1697     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
1698     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1699     struct bfd *old;
1700
1701     old = ofport->bfd;
1702     ofport->bfd = bfd_configure(old, netdev_get_name(ofport->up.netdev), cfg);
1703     if (ofport->bfd != old) {
1704         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1705     }
1706
1707     return 0;
1708 }
1709
1710 static int
1711 get_bfd_status(struct ofport *ofport_, struct smap *smap)
1712 {
1713     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1714
1715     if (ofport->bfd) {
1716         bfd_get_status(ofport->bfd, smap);
1717         return 0;
1718     } else {
1719         return ENOENT;
1720     }
1721 }
1722 \f
1723 /* Spanning Tree. */
1724
1725 static void
1726 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1727 {
1728     struct ofproto_dpif *ofproto = ofproto_;
1729     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1730     struct ofport_dpif *ofport;
1731
1732     ofport = stp_port_get_aux(sp);
1733     if (!ofport) {
1734         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1735                      ofproto->up.name, port_num);
1736     } else {
1737         struct eth_header *eth = pkt->l2;
1738
1739         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1740         if (eth_addr_is_zero(eth->eth_src)) {
1741             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1742                          "with unknown MAC", ofproto->up.name, port_num);
1743         } else {
1744             send_packet(ofport, pkt);
1745         }
1746     }
1747     ofpbuf_delete(pkt);
1748 }
1749
1750 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1751 static int
1752 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1753 {
1754     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1755
1756     /* Only revalidate flows if the configuration changed. */
1757     if (!s != !ofproto->stp) {
1758         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1759     }
1760
1761     if (s) {
1762         if (!ofproto->stp) {
1763             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1764                                       send_bpdu_cb, ofproto);
1765             ofproto->stp_last_tick = time_msec();
1766         }
1767
1768         stp_set_bridge_id(ofproto->stp, s->system_id);
1769         stp_set_bridge_priority(ofproto->stp, s->priority);
1770         stp_set_hello_time(ofproto->stp, s->hello_time);
1771         stp_set_max_age(ofproto->stp, s->max_age);
1772         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1773     }  else {
1774         struct ofport *ofport;
1775
1776         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1777             set_stp_port(ofport, NULL);
1778         }
1779
1780         stp_destroy(ofproto->stp);
1781         ofproto->stp = NULL;
1782     }
1783
1784     return 0;
1785 }
1786
1787 static int
1788 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1789 {
1790     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1791
1792     if (ofproto->stp) {
1793         s->enabled = true;
1794         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1795         s->designated_root = stp_get_designated_root(ofproto->stp);
1796         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1797     } else {
1798         s->enabled = false;
1799     }
1800
1801     return 0;
1802 }
1803
1804 static void
1805 update_stp_port_state(struct ofport_dpif *ofport)
1806 {
1807     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1808     enum stp_state state;
1809
1810     /* Figure out new state. */
1811     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1812                              : STP_DISABLED;
1813
1814     /* Update state. */
1815     if (ofport->stp_state != state) {
1816         enum ofputil_port_state of_state;
1817         bool fwd_change;
1818
1819         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1820                     netdev_get_name(ofport->up.netdev),
1821                     stp_state_name(ofport->stp_state),
1822                     stp_state_name(state));
1823         if (stp_learn_in_state(ofport->stp_state)
1824                 != stp_learn_in_state(state)) {
1825             /* xxx Learning action flows should also be flushed. */
1826             mac_learning_flush(ofproto->ml,
1827                                &ofproto->backer->revalidate_set);
1828         }
1829         fwd_change = stp_forward_in_state(ofport->stp_state)
1830                         != stp_forward_in_state(state);
1831
1832         ofproto->backer->need_revalidate = REV_STP;
1833         ofport->stp_state = state;
1834         ofport->stp_state_entered = time_msec();
1835
1836         if (fwd_change && ofport->bundle) {
1837             bundle_update(ofport->bundle);
1838         }
1839
1840         /* Update the STP state bits in the OpenFlow port description. */
1841         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1842         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1843                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1844                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1845                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1846                      : 0);
1847         ofproto_port_set_state(&ofport->up, of_state);
1848     }
1849 }
1850
1851 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1852  * caller is responsible for assigning STP port numbers and ensuring
1853  * there are no duplicates. */
1854 static int
1855 set_stp_port(struct ofport *ofport_,
1856              const struct ofproto_port_stp_settings *s)
1857 {
1858     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1859     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1860     struct stp_port *sp = ofport->stp_port;
1861
1862     if (!s || !s->enable) {
1863         if (sp) {
1864             ofport->stp_port = NULL;
1865             stp_port_disable(sp);
1866             update_stp_port_state(ofport);
1867         }
1868         return 0;
1869     } else if (sp && stp_port_no(sp) != s->port_num
1870             && ofport == stp_port_get_aux(sp)) {
1871         /* The port-id changed, so disable the old one if it's not
1872          * already in use by another port. */
1873         stp_port_disable(sp);
1874     }
1875
1876     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1877     stp_port_enable(sp);
1878
1879     stp_port_set_aux(sp, ofport);
1880     stp_port_set_priority(sp, s->priority);
1881     stp_port_set_path_cost(sp, s->path_cost);
1882
1883     update_stp_port_state(ofport);
1884
1885     return 0;
1886 }
1887
1888 static int
1889 get_stp_port_status(struct ofport *ofport_,
1890                     struct ofproto_port_stp_status *s)
1891 {
1892     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1893     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1894     struct stp_port *sp = ofport->stp_port;
1895
1896     if (!ofproto->stp || !sp) {
1897         s->enabled = false;
1898         return 0;
1899     }
1900
1901     s->enabled = true;
1902     s->port_id = stp_port_get_id(sp);
1903     s->state = stp_port_get_state(sp);
1904     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1905     s->role = stp_port_get_role(sp);
1906     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1907
1908     return 0;
1909 }
1910
1911 static void
1912 stp_run(struct ofproto_dpif *ofproto)
1913 {
1914     if (ofproto->stp) {
1915         long long int now = time_msec();
1916         long long int elapsed = now - ofproto->stp_last_tick;
1917         struct stp_port *sp;
1918
1919         if (elapsed > 0) {
1920             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1921             ofproto->stp_last_tick = now;
1922         }
1923         while (stp_get_changed_port(ofproto->stp, &sp)) {
1924             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1925
1926             if (ofport) {
1927                 update_stp_port_state(ofport);
1928             }
1929         }
1930
1931         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
1932             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
1933         }
1934     }
1935 }
1936
1937 static void
1938 stp_wait(struct ofproto_dpif *ofproto)
1939 {
1940     if (ofproto->stp) {
1941         poll_timer_wait(1000);
1942     }
1943 }
1944
1945 /* Returns true if STP should process 'flow'.  Sets fields in 'wc' that
1946  * were used to make the determination.*/
1947 bool
1948 stp_should_process_flow(const struct flow *flow, struct flow_wildcards *wc)
1949 {
1950     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
1951     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1952 }
1953
1954 void
1955 stp_process_packet(const struct ofport_dpif *ofport,
1956                    const struct ofpbuf *packet)
1957 {
1958     struct ofpbuf payload = *packet;
1959     struct eth_header *eth = payload.data;
1960     struct stp_port *sp = ofport->stp_port;
1961
1962     /* Sink packets on ports that have STP disabled when the bridge has
1963      * STP enabled. */
1964     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1965         return;
1966     }
1967
1968     /* Trim off padding on payload. */
1969     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1970         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1971     }
1972
1973     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1974         stp_received_bpdu(sp, payload.data, payload.size);
1975     }
1976 }
1977 \f
1978 int
1979 ofproto_dpif_queue_to_priority(const struct ofproto_dpif *ofproto,
1980                                uint32_t queue_id, uint32_t *priority)
1981 {
1982     return dpif_queue_to_priority(ofproto->backer->dpif, queue_id, priority);
1983 }
1984
1985 static struct priority_to_dscp *
1986 get_priority(const struct ofport_dpif *ofport, uint32_t priority)
1987 {
1988     struct priority_to_dscp *pdscp;
1989     uint32_t hash;
1990
1991     hash = hash_int(priority, 0);
1992     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &ofport->priorities) {
1993         if (pdscp->priority == priority) {
1994             return pdscp;
1995         }
1996     }
1997     return NULL;
1998 }
1999
2000 bool
2001 ofproto_dpif_dscp_from_priority(const struct ofport_dpif *ofport,
2002                                 uint32_t priority, uint8_t *dscp)
2003 {
2004     struct priority_to_dscp *pdscp = get_priority(ofport, priority);
2005     *dscp = pdscp ? pdscp->dscp : 0;
2006     return pdscp != NULL;
2007 }
2008
2009 static void
2010 ofport_clear_priorities(struct ofport_dpif *ofport)
2011 {
2012     struct priority_to_dscp *pdscp, *next;
2013
2014     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &ofport->priorities) {
2015         hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2016         free(pdscp);
2017     }
2018 }
2019
2020 static int
2021 set_queues(struct ofport *ofport_,
2022            const struct ofproto_port_queue *qdscp_list,
2023            size_t n_qdscp)
2024 {
2025     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2026     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2027     struct hmap new = HMAP_INITIALIZER(&new);
2028     size_t i;
2029
2030     for (i = 0; i < n_qdscp; i++) {
2031         struct priority_to_dscp *pdscp;
2032         uint32_t priority;
2033         uint8_t dscp;
2034
2035         dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
2036         if (dpif_queue_to_priority(ofproto->backer->dpif, qdscp_list[i].queue,
2037                                    &priority)) {
2038             continue;
2039         }
2040
2041         pdscp = get_priority(ofport, priority);
2042         if (pdscp) {
2043             hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2044         } else {
2045             pdscp = xmalloc(sizeof *pdscp);
2046             pdscp->priority = priority;
2047             pdscp->dscp = dscp;
2048             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2049         }
2050
2051         if (pdscp->dscp != dscp) {
2052             pdscp->dscp = dscp;
2053             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2054         }
2055
2056         hmap_insert(&new, &pdscp->hmap_node, hash_int(pdscp->priority, 0));
2057     }
2058
2059     if (!hmap_is_empty(&ofport->priorities)) {
2060         ofport_clear_priorities(ofport);
2061         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2062     }
2063
2064     hmap_swap(&new, &ofport->priorities);
2065     hmap_destroy(&new);
2066
2067     return 0;
2068 }
2069 \f
2070 /* Bundles. */
2071
2072 /* Expires all MAC learning entries associated with 'bundle' and forces its
2073  * ofproto to revalidate every flow.
2074  *
2075  * Normally MAC learning entries are removed only from the ofproto associated
2076  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
2077  * are removed from every ofproto.  When patch ports and SLB bonds are in use
2078  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
2079  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
2080  * with the host from which it migrated. */
2081 static void
2082 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
2083 {
2084     struct ofproto_dpif *ofproto = bundle->ofproto;
2085     struct mac_learning *ml = ofproto->ml;
2086     struct mac_entry *mac, *next_mac;
2087
2088     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2089     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2090         if (mac->port.p == bundle) {
2091             if (all_ofprotos) {
2092                 struct ofproto_dpif *o;
2093
2094                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2095                     if (o != ofproto) {
2096                         struct mac_entry *e;
2097
2098                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan,
2099                                                 NULL);
2100                         if (e) {
2101                             mac_learning_expire(o->ml, e);
2102                         }
2103                     }
2104                 }
2105             }
2106
2107             mac_learning_expire(ml, mac);
2108         }
2109     }
2110 }
2111
2112 static struct ofbundle *
2113 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
2114 {
2115     struct ofbundle *bundle;
2116
2117     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
2118                              &ofproto->bundles) {
2119         if (bundle->aux == aux) {
2120             return bundle;
2121         }
2122     }
2123     return NULL;
2124 }
2125
2126 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
2127  * ones that are found to 'bundles'. */
2128 static void
2129 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
2130                        void **auxes, size_t n_auxes,
2131                        struct hmapx *bundles)
2132 {
2133     size_t i;
2134
2135     hmapx_init(bundles);
2136     for (i = 0; i < n_auxes; i++) {
2137         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
2138         if (bundle) {
2139             hmapx_add(bundles, bundle);
2140         }
2141     }
2142 }
2143
2144 static void
2145 bundle_update(struct ofbundle *bundle)
2146 {
2147     struct ofport_dpif *port;
2148
2149     bundle->floodable = true;
2150     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2151         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2152             || !stp_forward_in_state(port->stp_state)) {
2153             bundle->floodable = false;
2154             break;
2155         }
2156     }
2157 }
2158
2159 static void
2160 bundle_del_port(struct ofport_dpif *port)
2161 {
2162     struct ofbundle *bundle = port->bundle;
2163
2164     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2165
2166     list_remove(&port->bundle_node);
2167     port->bundle = NULL;
2168
2169     if (bundle->lacp) {
2170         lacp_slave_unregister(bundle->lacp, port);
2171     }
2172     if (bundle->bond) {
2173         bond_slave_unregister(bundle->bond, port);
2174     }
2175
2176     bundle_update(bundle);
2177 }
2178
2179 static bool
2180 bundle_add_port(struct ofbundle *bundle, uint16_t ofp_port,
2181                 struct lacp_slave_settings *lacp)
2182 {
2183     struct ofport_dpif *port;
2184
2185     port = get_ofp_port(bundle->ofproto, ofp_port);
2186     if (!port) {
2187         return false;
2188     }
2189
2190     if (port->bundle != bundle) {
2191         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2192         if (port->bundle) {
2193             bundle_del_port(port);
2194         }
2195
2196         port->bundle = bundle;
2197         list_push_back(&bundle->ports, &port->bundle_node);
2198         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2199             || !stp_forward_in_state(port->stp_state)) {
2200             bundle->floodable = false;
2201         }
2202     }
2203     if (lacp) {
2204         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2205         lacp_slave_register(bundle->lacp, port, lacp);
2206     }
2207
2208     return true;
2209 }
2210
2211 static void
2212 bundle_destroy(struct ofbundle *bundle)
2213 {
2214     struct ofproto_dpif *ofproto;
2215     struct ofport_dpif *port, *next_port;
2216     int i;
2217
2218     if (!bundle) {
2219         return;
2220     }
2221
2222     ofproto = bundle->ofproto;
2223     for (i = 0; i < MAX_MIRRORS; i++) {
2224         struct ofmirror *m = ofproto->mirrors[i];
2225         if (m) {
2226             if (m->out == bundle) {
2227                 mirror_destroy(m);
2228             } else if (hmapx_find_and_delete(&m->srcs, bundle)
2229                        || hmapx_find_and_delete(&m->dsts, bundle)) {
2230                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2231             }
2232         }
2233     }
2234
2235     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2236         bundle_del_port(port);
2237     }
2238
2239     bundle_flush_macs(bundle, true);
2240     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2241     free(bundle->name);
2242     free(bundle->trunks);
2243     lacp_destroy(bundle->lacp);
2244     bond_destroy(bundle->bond);
2245     free(bundle);
2246 }
2247
2248 static int
2249 bundle_set(struct ofproto *ofproto_, void *aux,
2250            const struct ofproto_bundle_settings *s)
2251 {
2252     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2253     bool need_flush = false;
2254     struct ofport_dpif *port;
2255     struct ofbundle *bundle;
2256     unsigned long *trunks;
2257     int vlan;
2258     size_t i;
2259     bool ok;
2260
2261     if (!s) {
2262         bundle_destroy(bundle_lookup(ofproto, aux));
2263         return 0;
2264     }
2265
2266     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2267     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2268
2269     bundle = bundle_lookup(ofproto, aux);
2270     if (!bundle) {
2271         bundle = xmalloc(sizeof *bundle);
2272
2273         bundle->ofproto = ofproto;
2274         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2275                     hash_pointer(aux, 0));
2276         bundle->aux = aux;
2277         bundle->name = NULL;
2278
2279         list_init(&bundle->ports);
2280         bundle->vlan_mode = PORT_VLAN_TRUNK;
2281         bundle->vlan = -1;
2282         bundle->trunks = NULL;
2283         bundle->use_priority_tags = s->use_priority_tags;
2284         bundle->lacp = NULL;
2285         bundle->bond = NULL;
2286
2287         bundle->floodable = true;
2288
2289         bundle->src_mirrors = 0;
2290         bundle->dst_mirrors = 0;
2291         bundle->mirror_out = 0;
2292     }
2293
2294     if (!bundle->name || strcmp(s->name, bundle->name)) {
2295         free(bundle->name);
2296         bundle->name = xstrdup(s->name);
2297     }
2298
2299     /* LACP. */
2300     if (s->lacp) {
2301         if (!bundle->lacp) {
2302             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2303             bundle->lacp = lacp_create();
2304         }
2305         lacp_configure(bundle->lacp, s->lacp);
2306     } else {
2307         lacp_destroy(bundle->lacp);
2308         bundle->lacp = NULL;
2309     }
2310
2311     /* Update set of ports. */
2312     ok = true;
2313     for (i = 0; i < s->n_slaves; i++) {
2314         if (!bundle_add_port(bundle, s->slaves[i],
2315                              s->lacp ? &s->lacp_slaves[i] : NULL)) {
2316             ok = false;
2317         }
2318     }
2319     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2320         struct ofport_dpif *next_port;
2321
2322         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2323             for (i = 0; i < s->n_slaves; i++) {
2324                 if (s->slaves[i] == port->up.ofp_port) {
2325                     goto found;
2326                 }
2327             }
2328
2329             bundle_del_port(port);
2330         found: ;
2331         }
2332     }
2333     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2334
2335     if (list_is_empty(&bundle->ports)) {
2336         bundle_destroy(bundle);
2337         return EINVAL;
2338     }
2339
2340     /* Set VLAN tagging mode */
2341     if (s->vlan_mode != bundle->vlan_mode
2342         || s->use_priority_tags != bundle->use_priority_tags) {
2343         bundle->vlan_mode = s->vlan_mode;
2344         bundle->use_priority_tags = s->use_priority_tags;
2345         need_flush = true;
2346     }
2347
2348     /* Set VLAN tag. */
2349     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2350             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2351             : 0);
2352     if (vlan != bundle->vlan) {
2353         bundle->vlan = vlan;
2354         need_flush = true;
2355     }
2356
2357     /* Get trunked VLANs. */
2358     switch (s->vlan_mode) {
2359     case PORT_VLAN_ACCESS:
2360         trunks = NULL;
2361         break;
2362
2363     case PORT_VLAN_TRUNK:
2364         trunks = CONST_CAST(unsigned long *, s->trunks);
2365         break;
2366
2367     case PORT_VLAN_NATIVE_UNTAGGED:
2368     case PORT_VLAN_NATIVE_TAGGED:
2369         if (vlan != 0 && (!s->trunks
2370                           || !bitmap_is_set(s->trunks, vlan)
2371                           || bitmap_is_set(s->trunks, 0))) {
2372             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2373             if (s->trunks) {
2374                 trunks = bitmap_clone(s->trunks, 4096);
2375             } else {
2376                 trunks = bitmap_allocate1(4096);
2377             }
2378             bitmap_set1(trunks, vlan);
2379             bitmap_set0(trunks, 0);
2380         } else {
2381             trunks = CONST_CAST(unsigned long *, s->trunks);
2382         }
2383         break;
2384
2385     default:
2386         NOT_REACHED();
2387     }
2388     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2389         free(bundle->trunks);
2390         if (trunks == s->trunks) {
2391             bundle->trunks = vlan_bitmap_clone(trunks);
2392         } else {
2393             bundle->trunks = trunks;
2394             trunks = NULL;
2395         }
2396         need_flush = true;
2397     }
2398     if (trunks != s->trunks) {
2399         free(trunks);
2400     }
2401
2402     /* Bonding. */
2403     if (!list_is_short(&bundle->ports)) {
2404         bundle->ofproto->has_bonded_bundles = true;
2405         if (bundle->bond) {
2406             if (bond_reconfigure(bundle->bond, s->bond)) {
2407                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2408             }
2409         } else {
2410             bundle->bond = bond_create(s->bond);
2411             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2412         }
2413
2414         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2415             bond_slave_register(bundle->bond, port, port->up.netdev);
2416         }
2417     } else {
2418         bond_destroy(bundle->bond);
2419         bundle->bond = NULL;
2420     }
2421
2422     /* If we changed something that would affect MAC learning, un-learn
2423      * everything on this port and force flow revalidation. */
2424     if (need_flush) {
2425         bundle_flush_macs(bundle, false);
2426     }
2427
2428     return 0;
2429 }
2430
2431 static void
2432 bundle_remove(struct ofport *port_)
2433 {
2434     struct ofport_dpif *port = ofport_dpif_cast(port_);
2435     struct ofbundle *bundle = port->bundle;
2436
2437     if (bundle) {
2438         bundle_del_port(port);
2439         if (list_is_empty(&bundle->ports)) {
2440             bundle_destroy(bundle);
2441         } else if (list_is_short(&bundle->ports)) {
2442             bond_destroy(bundle->bond);
2443             bundle->bond = NULL;
2444         }
2445     }
2446 }
2447
2448 static void
2449 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2450 {
2451     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2452     struct ofport_dpif *port = port_;
2453     uint8_t ea[ETH_ADDR_LEN];
2454     int error;
2455
2456     error = netdev_get_etheraddr(port->up.netdev, ea);
2457     if (!error) {
2458         struct ofpbuf packet;
2459         void *packet_pdu;
2460
2461         ofpbuf_init(&packet, 0);
2462         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2463                                  pdu_size);
2464         memcpy(packet_pdu, pdu, pdu_size);
2465
2466         send_packet(port, &packet);
2467         ofpbuf_uninit(&packet);
2468     } else {
2469         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2470                     "%s (%s)", port->bundle->name,
2471                     netdev_get_name(port->up.netdev), strerror(error));
2472     }
2473 }
2474
2475 static void
2476 bundle_send_learning_packets(struct ofbundle *bundle)
2477 {
2478     struct ofproto_dpif *ofproto = bundle->ofproto;
2479     int error, n_packets, n_errors;
2480     struct mac_entry *e;
2481
2482     error = n_packets = n_errors = 0;
2483     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2484         if (e->port.p != bundle) {
2485             struct ofpbuf *learning_packet;
2486             struct ofport_dpif *port;
2487             void *port_void;
2488             int ret;
2489
2490             /* The assignment to "port" is unnecessary but makes "grep"ing for
2491              * struct ofport_dpif more effective. */
2492             learning_packet = bond_compose_learning_packet(bundle->bond,
2493                                                            e->mac, e->vlan,
2494                                                            &port_void);
2495             port = port_void;
2496             ret = send_packet(port, learning_packet);
2497             ofpbuf_delete(learning_packet);
2498             if (ret) {
2499                 error = ret;
2500                 n_errors++;
2501             }
2502             n_packets++;
2503         }
2504     }
2505
2506     if (n_errors) {
2507         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2508         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2509                      "packets, last error was: %s",
2510                      bundle->name, n_errors, n_packets, strerror(error));
2511     } else {
2512         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2513                  bundle->name, n_packets);
2514     }
2515 }
2516
2517 static void
2518 bundle_run(struct ofbundle *bundle)
2519 {
2520     if (bundle->lacp) {
2521         lacp_run(bundle->lacp, send_pdu_cb);
2522     }
2523     if (bundle->bond) {
2524         struct ofport_dpif *port;
2525
2526         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2527             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2528         }
2529
2530         bond_run(bundle->bond, &bundle->ofproto->backer->revalidate_set,
2531                  lacp_status(bundle->lacp));
2532         if (bond_should_send_learning_packets(bundle->bond)) {
2533             bundle_send_learning_packets(bundle);
2534         }
2535     }
2536 }
2537
2538 static void
2539 bundle_wait(struct ofbundle *bundle)
2540 {
2541     if (bundle->lacp) {
2542         lacp_wait(bundle->lacp);
2543     }
2544     if (bundle->bond) {
2545         bond_wait(bundle->bond);
2546     }
2547 }
2548 \f
2549 /* Mirrors. */
2550
2551 static int
2552 mirror_scan(struct ofproto_dpif *ofproto)
2553 {
2554     int idx;
2555
2556     for (idx = 0; idx < MAX_MIRRORS; idx++) {
2557         if (!ofproto->mirrors[idx]) {
2558             return idx;
2559         }
2560     }
2561     return -1;
2562 }
2563
2564 static struct ofmirror *
2565 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
2566 {
2567     int i;
2568
2569     for (i = 0; i < MAX_MIRRORS; i++) {
2570         struct ofmirror *mirror = ofproto->mirrors[i];
2571         if (mirror && mirror->aux == aux) {
2572             return mirror;
2573         }
2574     }
2575
2576     return NULL;
2577 }
2578
2579 /* Update the 'dup_mirrors' member of each of the ofmirrors in 'ofproto'. */
2580 static void
2581 mirror_update_dups(struct ofproto_dpif *ofproto)
2582 {
2583     int i;
2584
2585     for (i = 0; i < MAX_MIRRORS; i++) {
2586         struct ofmirror *m = ofproto->mirrors[i];
2587
2588         if (m) {
2589             m->dup_mirrors = MIRROR_MASK_C(1) << i;
2590         }
2591     }
2592
2593     for (i = 0; i < MAX_MIRRORS; i++) {
2594         struct ofmirror *m1 = ofproto->mirrors[i];
2595         int j;
2596
2597         if (!m1) {
2598             continue;
2599         }
2600
2601         for (j = i + 1; j < MAX_MIRRORS; j++) {
2602             struct ofmirror *m2 = ofproto->mirrors[j];
2603
2604             if (m2 && m1->out == m2->out && m1->out_vlan == m2->out_vlan) {
2605                 m1->dup_mirrors |= MIRROR_MASK_C(1) << j;
2606                 m2->dup_mirrors |= m1->dup_mirrors;
2607             }
2608         }
2609     }
2610 }
2611
2612 static int
2613 mirror_set(struct ofproto *ofproto_, void *aux,
2614            const struct ofproto_mirror_settings *s)
2615 {
2616     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2617     mirror_mask_t mirror_bit;
2618     struct ofbundle *bundle;
2619     struct ofmirror *mirror;
2620     struct ofbundle *out;
2621     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
2622     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
2623     int out_vlan;
2624
2625     mirror = mirror_lookup(ofproto, aux);
2626     if (!s) {
2627         mirror_destroy(mirror);
2628         return 0;
2629     }
2630     if (!mirror) {
2631         int idx;
2632
2633         idx = mirror_scan(ofproto);
2634         if (idx < 0) {
2635             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
2636                       "cannot create %s",
2637                       ofproto->up.name, MAX_MIRRORS, s->name);
2638             return EFBIG;
2639         }
2640
2641         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
2642         mirror->ofproto = ofproto;
2643         mirror->idx = idx;
2644         mirror->aux = aux;
2645         mirror->out_vlan = -1;
2646         mirror->name = NULL;
2647     }
2648
2649     if (!mirror->name || strcmp(s->name, mirror->name)) {
2650         free(mirror->name);
2651         mirror->name = xstrdup(s->name);
2652     }
2653
2654     /* Get the new configuration. */
2655     if (s->out_bundle) {
2656         out = bundle_lookup(ofproto, s->out_bundle);
2657         if (!out) {
2658             mirror_destroy(mirror);
2659             return EINVAL;
2660         }
2661         out_vlan = -1;
2662     } else {
2663         out = NULL;
2664         out_vlan = s->out_vlan;
2665     }
2666     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
2667     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
2668
2669     /* If the configuration has not changed, do nothing. */
2670     if (hmapx_equals(&srcs, &mirror->srcs)
2671         && hmapx_equals(&dsts, &mirror->dsts)
2672         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
2673         && mirror->out == out
2674         && mirror->out_vlan == out_vlan)
2675     {
2676         hmapx_destroy(&srcs);
2677         hmapx_destroy(&dsts);
2678         return 0;
2679     }
2680
2681     hmapx_swap(&srcs, &mirror->srcs);
2682     hmapx_destroy(&srcs);
2683
2684     hmapx_swap(&dsts, &mirror->dsts);
2685     hmapx_destroy(&dsts);
2686
2687     free(mirror->vlans);
2688     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
2689
2690     mirror->out = out;
2691     mirror->out_vlan = out_vlan;
2692
2693     /* Update bundles. */
2694     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2695     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
2696         if (hmapx_contains(&mirror->srcs, bundle)) {
2697             bundle->src_mirrors |= mirror_bit;
2698         } else {
2699             bundle->src_mirrors &= ~mirror_bit;
2700         }
2701
2702         if (hmapx_contains(&mirror->dsts, bundle)) {
2703             bundle->dst_mirrors |= mirror_bit;
2704         } else {
2705             bundle->dst_mirrors &= ~mirror_bit;
2706         }
2707
2708         if (mirror->out == bundle) {
2709             bundle->mirror_out |= mirror_bit;
2710         } else {
2711             bundle->mirror_out &= ~mirror_bit;
2712         }
2713     }
2714
2715     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2716     ofproto->has_mirrors = true;
2717     mac_learning_flush(ofproto->ml,
2718                        &ofproto->backer->revalidate_set);
2719     mirror_update_dups(ofproto);
2720
2721     return 0;
2722 }
2723
2724 static void
2725 mirror_destroy(struct ofmirror *mirror)
2726 {
2727     struct ofproto_dpif *ofproto;
2728     mirror_mask_t mirror_bit;
2729     struct ofbundle *bundle;
2730     int i;
2731
2732     if (!mirror) {
2733         return;
2734     }
2735
2736     ofproto = mirror->ofproto;
2737     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2738     mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2739
2740     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2741     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2742         bundle->src_mirrors &= ~mirror_bit;
2743         bundle->dst_mirrors &= ~mirror_bit;
2744         bundle->mirror_out &= ~mirror_bit;
2745     }
2746
2747     hmapx_destroy(&mirror->srcs);
2748     hmapx_destroy(&mirror->dsts);
2749     free(mirror->vlans);
2750
2751     ofproto->mirrors[mirror->idx] = NULL;
2752     free(mirror->name);
2753     free(mirror);
2754
2755     mirror_update_dups(ofproto);
2756
2757     ofproto->has_mirrors = false;
2758     for (i = 0; i < MAX_MIRRORS; i++) {
2759         if (ofproto->mirrors[i]) {
2760             ofproto->has_mirrors = true;
2761             break;
2762         }
2763     }
2764 }
2765
2766 static int
2767 mirror_get_stats(struct ofproto *ofproto_, void *aux,
2768                  uint64_t *packets, uint64_t *bytes)
2769 {
2770     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2771     struct ofmirror *mirror = mirror_lookup(ofproto, aux);
2772
2773     if (!mirror) {
2774         *packets = *bytes = UINT64_MAX;
2775         return 0;
2776     }
2777
2778     push_all_stats();
2779
2780     *packets = mirror->packet_count;
2781     *bytes = mirror->byte_count;
2782
2783     return 0;
2784 }
2785
2786 static int
2787 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2788 {
2789     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2790     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2791         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2792     }
2793     return 0;
2794 }
2795
2796 static bool
2797 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2798 {
2799     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2800     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2801     return bundle && bundle->mirror_out != 0;
2802 }
2803
2804 static void
2805 forward_bpdu_changed(struct ofproto *ofproto_)
2806 {
2807     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2808     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2809 }
2810
2811 static void
2812 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
2813                      size_t max_entries)
2814 {
2815     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2816     mac_learning_set_idle_time(ofproto->ml, idle_time);
2817     mac_learning_set_max_entries(ofproto->ml, max_entries);
2818 }
2819 \f
2820 /* Ports. */
2821
2822 struct ofport_dpif *
2823 get_ofp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
2824 {
2825     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2826     return ofport ? ofport_dpif_cast(ofport) : NULL;
2827 }
2828
2829 struct ofport_dpif *
2830 get_odp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
2831 {
2832     struct ofport_dpif *port = odp_port_to_ofport(ofproto->backer, odp_port);
2833     return port && &ofproto->up == port->up.ofproto ? port : NULL;
2834 }
2835
2836 static void
2837 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
2838                             struct ofproto_port *ofproto_port,
2839                             struct dpif_port *dpif_port)
2840 {
2841     ofproto_port->name = dpif_port->name;
2842     ofproto_port->type = dpif_port->type;
2843     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
2844 }
2845
2846 static void
2847 ofport_update_peer(struct ofport_dpif *ofport)
2848 {
2849     const struct ofproto_dpif *ofproto;
2850     struct dpif_backer *backer;
2851     const char *peer_name;
2852
2853     if (!netdev_vport_is_patch(ofport->up.netdev)) {
2854         return;
2855     }
2856
2857     backer = ofproto_dpif_cast(ofport->up.ofproto)->backer;
2858     backer->need_revalidate = true;
2859
2860     if (ofport->peer) {
2861         ofport->peer->peer = NULL;
2862         ofport->peer = NULL;
2863     }
2864
2865     peer_name = netdev_vport_patch_peer(ofport->up.netdev);
2866     if (!peer_name) {
2867         return;
2868     }
2869
2870     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2871         struct ofport *peer_ofport;
2872         struct ofport_dpif *peer;
2873         const char *peer_peer;
2874
2875         if (ofproto->backer != backer) {
2876             continue;
2877         }
2878
2879         peer_ofport = shash_find_data(&ofproto->up.port_by_name, peer_name);
2880         if (!peer_ofport) {
2881             continue;
2882         }
2883
2884         peer = ofport_dpif_cast(peer_ofport);
2885         peer_peer = netdev_vport_patch_peer(peer->up.netdev);
2886         if (peer_peer && !strcmp(netdev_get_name(ofport->up.netdev),
2887                                  peer_peer)) {
2888             ofport->peer = peer;
2889             ofport->peer->peer = ofport;
2890         }
2891
2892         return;
2893     }
2894 }
2895
2896 static void
2897 port_run_fast(struct ofport_dpif *ofport)
2898 {
2899     if (ofport->cfm && cfm_should_send_ccm(ofport->cfm)) {
2900         struct ofpbuf packet;
2901
2902         ofpbuf_init(&packet, 0);
2903         cfm_compose_ccm(ofport->cfm, &packet, ofport->up.pp.hw_addr);
2904         send_packet(ofport, &packet);
2905         ofpbuf_uninit(&packet);
2906     }
2907
2908     if (ofport->bfd && bfd_should_send_packet(ofport->bfd)) {
2909         struct ofpbuf packet;
2910
2911         ofpbuf_init(&packet, 0);
2912         bfd_put_packet(ofport->bfd, &packet, ofport->up.pp.hw_addr);
2913         send_packet(ofport, &packet);
2914         ofpbuf_uninit(&packet);
2915     }
2916 }
2917
2918 static void
2919 port_run(struct ofport_dpif *ofport)
2920 {
2921     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2922     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2923     bool enable = netdev_get_carrier(ofport->up.netdev);
2924
2925     ofport->carrier_seq = carrier_seq;
2926
2927     port_run_fast(ofport);
2928
2929     if (ofport->cfm) {
2930         int cfm_opup = cfm_get_opup(ofport->cfm);
2931
2932         cfm_run(ofport->cfm);
2933         enable = enable && !cfm_get_fault(ofport->cfm);
2934
2935         if (cfm_opup >= 0) {
2936             enable = enable && cfm_opup;
2937         }
2938     }
2939
2940     if (ofport->bfd) {
2941         bfd_run(ofport->bfd);
2942         enable = enable && bfd_forwarding(ofport->bfd);
2943     }
2944
2945     if (ofport->bundle) {
2946         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2947         if (carrier_changed) {
2948             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2949         }
2950     }
2951
2952     if (ofport->may_enable != enable) {
2953         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2954
2955         if (ofproto->has_bundle_action) {
2956             ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
2957         }
2958     }
2959
2960     ofport->may_enable = enable;
2961 }
2962
2963 static void
2964 port_wait(struct ofport_dpif *ofport)
2965 {
2966     if (ofport->cfm) {
2967         cfm_wait(ofport->cfm);
2968     }
2969
2970     if (ofport->bfd) {
2971         bfd_wait(ofport->bfd);
2972     }
2973 }
2974
2975 static int
2976 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2977                    struct ofproto_port *ofproto_port)
2978 {
2979     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2980     struct dpif_port dpif_port;
2981     int error;
2982
2983     if (sset_contains(&ofproto->ghost_ports, devname)) {
2984         const char *type = netdev_get_type_from_name(devname);
2985
2986         /* We may be called before ofproto->up.port_by_name is populated with
2987          * the appropriate ofport.  For this reason, we must get the name and
2988          * type from the netdev layer directly. */
2989         if (type) {
2990             const struct ofport *ofport;
2991
2992             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
2993             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
2994             ofproto_port->name = xstrdup(devname);
2995             ofproto_port->type = xstrdup(type);
2996             return 0;
2997         }
2998         return ENODEV;
2999     }
3000
3001     if (!sset_contains(&ofproto->ports, devname)) {
3002         return ENODEV;
3003     }
3004     error = dpif_port_query_by_name(ofproto->backer->dpif,
3005                                     devname, &dpif_port);
3006     if (!error) {
3007         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
3008     }
3009     return error;
3010 }
3011
3012 static int
3013 port_add(struct ofproto *ofproto_, struct netdev *netdev)
3014 {
3015     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3016     const char *devname = netdev_get_name(netdev);
3017     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
3018     const char *dp_port_name;
3019
3020     if (netdev_vport_is_patch(netdev)) {
3021         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
3022         return 0;
3023     }
3024
3025     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
3026     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
3027         uint32_t port_no = UINT32_MAX;
3028         int error;
3029
3030         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
3031         if (error) {
3032             return error;
3033         }
3034         if (netdev_get_tunnel_config(netdev)) {
3035             simap_put(&ofproto->backer->tnl_backers, dp_port_name, port_no);
3036         }
3037     }
3038
3039     if (netdev_get_tunnel_config(netdev)) {
3040         sset_add(&ofproto->ghost_ports, devname);
3041     } else {
3042         sset_add(&ofproto->ports, devname);
3043     }
3044     return 0;
3045 }
3046
3047 static int
3048 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
3049 {
3050     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3051     struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
3052     int error = 0;
3053
3054     if (!ofport) {
3055         return 0;
3056     }
3057
3058     sset_find_and_delete(&ofproto->ghost_ports,
3059                          netdev_get_name(ofport->up.netdev));
3060     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3061     if (!ofport->tnl_port) {
3062         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
3063         if (!error) {
3064             /* The caller is going to close ofport->up.netdev.  If this is a
3065              * bonded port, then the bond is using that netdev, so remove it
3066              * from the bond.  The client will need to reconfigure everything
3067              * after deleting ports, so then the slave will get re-added. */
3068             bundle_remove(&ofport->up);
3069         }
3070     }
3071     return error;
3072 }
3073
3074 static int
3075 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
3076 {
3077     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3078     int error;
3079
3080     push_all_stats();
3081
3082     error = netdev_get_stats(ofport->up.netdev, stats);
3083
3084     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
3085         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3086
3087         /* ofproto->stats.tx_packets represents packets that we created
3088          * internally and sent to some port (e.g. packets sent with
3089          * send_packet()).  Account for them as if they had come from
3090          * OFPP_LOCAL and got forwarded. */
3091
3092         if (stats->rx_packets != UINT64_MAX) {
3093             stats->rx_packets += ofproto->stats.tx_packets;
3094         }
3095
3096         if (stats->rx_bytes != UINT64_MAX) {
3097             stats->rx_bytes += ofproto->stats.tx_bytes;
3098         }
3099
3100         /* ofproto->stats.rx_packets represents packets that were received on
3101          * some port and we processed internally and dropped (e.g. STP).
3102          * Account for them as if they had been forwarded to OFPP_LOCAL. */
3103
3104         if (stats->tx_packets != UINT64_MAX) {
3105             stats->tx_packets += ofproto->stats.rx_packets;
3106         }
3107
3108         if (stats->tx_bytes != UINT64_MAX) {
3109             stats->tx_bytes += ofproto->stats.rx_bytes;
3110         }
3111     }
3112
3113     return error;
3114 }
3115
3116 struct port_dump_state {
3117     uint32_t bucket;
3118     uint32_t offset;
3119     bool ghost;
3120
3121     struct ofproto_port port;
3122     bool has_port;
3123 };
3124
3125 static int
3126 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
3127 {
3128     *statep = xzalloc(sizeof(struct port_dump_state));
3129     return 0;
3130 }
3131
3132 static int
3133 port_dump_next(const struct ofproto *ofproto_, void *state_,
3134                struct ofproto_port *port)
3135 {
3136     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3137     struct port_dump_state *state = state_;
3138     const struct sset *sset;
3139     struct sset_node *node;
3140
3141     if (state->has_port) {
3142         ofproto_port_destroy(&state->port);
3143         state->has_port = false;
3144     }
3145     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
3146     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
3147         int error;
3148
3149         error = port_query_by_name(ofproto_, node->name, &state->port);
3150         if (!error) {
3151             *port = state->port;
3152             state->has_port = true;
3153             return 0;
3154         } else if (error != ENODEV) {
3155             return error;
3156         }
3157     }
3158
3159     if (!state->ghost) {
3160         state->ghost = true;
3161         state->bucket = 0;
3162         state->offset = 0;
3163         return port_dump_next(ofproto_, state_, port);
3164     }
3165
3166     return EOF;
3167 }
3168
3169 static int
3170 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
3171 {
3172     struct port_dump_state *state = state_;
3173
3174     if (state->has_port) {
3175         ofproto_port_destroy(&state->port);
3176     }
3177     free(state);
3178     return 0;
3179 }
3180
3181 static int
3182 port_poll(const struct ofproto *ofproto_, char **devnamep)
3183 {
3184     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3185
3186     if (ofproto->port_poll_errno) {
3187         int error = ofproto->port_poll_errno;
3188         ofproto->port_poll_errno = 0;
3189         return error;
3190     }
3191
3192     if (sset_is_empty(&ofproto->port_poll_set)) {
3193         return EAGAIN;
3194     }
3195
3196     *devnamep = sset_pop(&ofproto->port_poll_set);
3197     return 0;
3198 }
3199
3200 static void
3201 port_poll_wait(const struct ofproto *ofproto_)
3202 {
3203     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3204     dpif_port_poll_wait(ofproto->backer->dpif);
3205 }
3206
3207 static int
3208 port_is_lacp_current(const struct ofport *ofport_)
3209 {
3210     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3211     return (ofport->bundle && ofport->bundle->lacp
3212             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
3213             : -1);
3214 }
3215 \f
3216 /* Upcall handling. */
3217
3218 /* Flow miss batching.
3219  *
3220  * Some dpifs implement operations faster when you hand them off in a batch.
3221  * To allow batching, "struct flow_miss" queues the dpif-related work needed
3222  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
3223  * more packets, plus possibly installing the flow in the dpif.
3224  *
3225  * So far we only batch the operations that affect flow setup time the most.
3226  * It's possible to batch more than that, but the benefit might be minimal. */
3227 struct flow_miss {
3228     struct hmap_node hmap_node;
3229     struct ofproto_dpif *ofproto;
3230     struct flow flow;
3231     enum odp_key_fitness key_fitness;
3232     const struct nlattr *key;
3233     size_t key_len;
3234     struct list packets;
3235     enum dpif_upcall_type upcall_type;
3236 };
3237
3238 struct flow_miss_op {
3239     struct dpif_op dpif_op;
3240
3241     uint64_t slow_stub[128 / 8]; /* Buffer for compose_slow_path() */
3242     struct xlate_out xout;
3243     bool xout_garbage;           /* 'xout' needs to be uninitialized? */
3244 };
3245
3246 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
3247  * OpenFlow controller as necessary according to their individual
3248  * configurations. */
3249 static void
3250 send_packet_in_miss(struct ofproto_dpif *ofproto, const struct ofpbuf *packet,
3251                     const struct flow *flow)
3252 {
3253     struct ofputil_packet_in pin;
3254
3255     pin.packet = packet->data;
3256     pin.packet_len = packet->size;
3257     pin.reason = OFPR_NO_MATCH;
3258     pin.controller_id = 0;
3259
3260     pin.table_id = 0;
3261     pin.cookie = 0;
3262
3263     pin.send_len = 0;           /* not used for flow table misses */
3264
3265     flow_get_metadata(flow, &pin.fmd);
3266
3267     connmgr_send_packet_in(ofproto->up.connmgr, &pin);
3268 }
3269
3270 static struct flow_miss *
3271 flow_miss_find(struct hmap *todo, const struct ofproto_dpif *ofproto,
3272                const struct flow *flow, uint32_t hash)
3273 {
3274     struct flow_miss *miss;
3275
3276     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
3277         if (miss->ofproto == ofproto && flow_equal(&miss->flow, flow)) {
3278             return miss;
3279         }
3280     }
3281
3282     return NULL;
3283 }
3284
3285 /* Partially Initializes 'op' as an "execute" operation for 'miss' and
3286  * 'packet'.  The caller must initialize op->actions and op->actions_len.  If
3287  * 'miss' is associated with a subfacet the caller must also initialize the
3288  * returned op->subfacet, and if anything needs to be freed after processing
3289  * the op, the caller must initialize op->garbage also. */
3290 static void
3291 init_flow_miss_execute_op(struct flow_miss *miss, struct ofpbuf *packet,
3292                           struct flow_miss_op *op)
3293 {
3294     if (miss->flow.in_port
3295         != vsp_realdev_to_vlandev(miss->ofproto, miss->flow.in_port,
3296                                   miss->flow.vlan_tci)) {
3297         /* This packet was received on a VLAN splinter port.  We
3298          * added a VLAN to the packet to make the packet resemble
3299          * the flow, but the actions were composed assuming that
3300          * the packet contained no VLAN.  So, we must remove the
3301          * VLAN header from the packet before trying to execute the
3302          * actions. */
3303         eth_pop_vlan(packet);
3304     }
3305
3306     op->xout_garbage = false;
3307     op->dpif_op.type = DPIF_OP_EXECUTE;
3308     op->dpif_op.u.execute.key = miss->key;
3309     op->dpif_op.u.execute.key_len = miss->key_len;
3310     op->dpif_op.u.execute.packet = packet;
3311 }
3312
3313 /* Helper for handle_flow_miss_without_facet() and
3314  * handle_flow_miss_with_facet(). */
3315 static void
3316 handle_flow_miss_common(struct rule_dpif *rule,
3317                         struct ofpbuf *packet, const struct flow *flow)
3318 {
3319     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3320
3321     if (rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
3322         /*
3323          * Extra-special case for fail-open mode.
3324          *
3325          * We are in fail-open mode and the packet matched the fail-open
3326          * rule, but we are connected to a controller too.  We should send
3327          * the packet up to the controller in the hope that it will try to
3328          * set up a flow and thereby allow us to exit fail-open.
3329          *
3330          * See the top-level comment in fail-open.c for more information.
3331          */
3332         send_packet_in_miss(ofproto, packet, flow);
3333     }
3334 }
3335
3336 /* Figures out whether a flow that missed in 'ofproto', whose details are in
3337  * 'miss' masked by 'wc', is likely to be worth tracking in detail in userspace
3338  * and (usually) installing a datapath flow.  The answer is usually "yes" (a
3339  * return value of true).  However, for short flows the cost of bookkeeping is
3340  * much higher than the benefits, so when the datapath holds a large number of
3341  * flows we impose some heuristics to decide which flows are likely to be worth
3342  * tracking. */
3343 static bool
3344 flow_miss_should_make_facet(struct flow_miss *miss, struct flow_wildcards *wc)
3345 {
3346     struct dpif_backer *backer = miss->ofproto->backer;
3347     uint32_t hash;
3348
3349     if (!backer->governor) {
3350         size_t n_subfacets;
3351
3352         n_subfacets = hmap_count(&backer->subfacets);
3353         if (n_subfacets * 2 <= flow_eviction_threshold) {
3354             return true;
3355         }
3356
3357         backer->governor = governor_create();
3358     }
3359
3360     hash = flow_hash_in_wildcards(&miss->flow, wc, 0);
3361     return governor_should_install_flow(backer->governor, hash,
3362                                         list_size(&miss->packets));
3363 }
3364
3365 /* Handles 'miss' without creating a facet or subfacet or creating any datapath
3366  * flow.  'miss->flow' must have matched 'rule' and been xlated into 'xout'.
3367  * May add an "execute" operation to 'ops' and increment '*n_ops'. */
3368 static void
3369 handle_flow_miss_without_facet(struct rule_dpif *rule, struct xlate_out *xout,
3370                                struct flow_miss *miss,
3371                                struct flow_miss_op *ops, size_t *n_ops)
3372 {
3373     struct ofpbuf *packet;
3374
3375     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3376
3377         COVERAGE_INC(facet_suppress);
3378
3379         handle_flow_miss_common(rule, packet, &miss->flow);
3380
3381         if (xout->slow) {
3382             struct xlate_in xin;
3383
3384             xlate_in_init(&xin, miss->ofproto, &miss->flow, rule, 0, packet);
3385             xlate_actions_for_side_effects(&xin);
3386         }
3387
3388         if (xout->odp_actions.size) {
3389             struct flow_miss_op *op = &ops[*n_ops];
3390             struct dpif_execute *execute = &op->dpif_op.u.execute;
3391
3392             init_flow_miss_execute_op(miss, packet, op);
3393             xlate_out_copy(&op->xout, xout);
3394             execute->actions = op->xout.odp_actions.data;
3395             execute->actions_len = op->xout.odp_actions.size;
3396             op->xout_garbage = true;
3397
3398             (*n_ops)++;
3399         }
3400     }
3401 }
3402
3403 /* Handles 'miss', which matches 'facet'.  May add any required datapath
3404  * operations to 'ops', incrementing '*n_ops' for each new op.
3405  *
3406  * All of the packets in 'miss' are considered to have arrived at time 'now'.
3407  * This is really important only for new facets: if we just called time_msec()
3408  * here, then the new subfacet or its packets could look (occasionally) as
3409  * though it was used some time after the facet was used.  That can make a
3410  * one-packet flow look like it has a nonzero duration, which looks odd in
3411  * e.g. NetFlow statistics.
3412  *
3413  * If non-null, 'stats' will be folded into 'facet'. */
3414 static void
3415 handle_flow_miss_with_facet(struct flow_miss *miss, struct facet *facet,
3416                             long long int now, struct dpif_flow_stats *stats,
3417                             struct flow_miss_op *ops, size_t *n_ops)
3418 {
3419     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3420     enum subfacet_path want_path;
3421     struct subfacet *subfacet;
3422     struct ofpbuf *packet;
3423
3424     subfacet = subfacet_create(facet, miss, now);
3425     want_path = facet->xout.slow ? SF_SLOW_PATH : SF_FAST_PATH;
3426     if (stats) {
3427         subfacet_update_stats(subfacet, stats);
3428     }
3429
3430     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3431         struct flow_miss_op *op = &ops[*n_ops];
3432
3433         handle_flow_miss_common(facet->rule, packet, &miss->flow);
3434
3435         if (want_path != SF_FAST_PATH) {
3436             struct xlate_in xin;
3437
3438             xlate_in_init(&xin, ofproto, &miss->flow, facet->rule, 0, packet);
3439             xlate_actions_for_side_effects(&xin);
3440         }
3441
3442         if (facet->xout.odp_actions.size) {
3443             struct dpif_execute *execute = &op->dpif_op.u.execute;
3444
3445             init_flow_miss_execute_op(miss, packet, op);
3446             execute->actions = facet->xout.odp_actions.data,
3447             execute->actions_len = facet->xout.odp_actions.size;
3448             (*n_ops)++;
3449         }
3450     }
3451
3452     if (miss->upcall_type == DPIF_UC_MISS || subfacet->path != want_path) {
3453         struct flow_miss_op *op = &ops[(*n_ops)++];
3454         struct dpif_flow_put *put = &op->dpif_op.u.flow_put;
3455
3456         subfacet->path = want_path;
3457
3458         op->xout_garbage = false;
3459         op->dpif_op.type = DPIF_OP_FLOW_PUT;
3460         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3461         put->key = miss->key;
3462         put->key_len = miss->key_len;
3463         if (want_path == SF_FAST_PATH) {
3464             put->actions = facet->xout.odp_actions.data;
3465             put->actions_len = facet->xout.odp_actions.size;
3466         } else {
3467             compose_slow_path(ofproto, &miss->flow, facet->xout.slow,
3468                               op->slow_stub, sizeof op->slow_stub,
3469                               &put->actions, &put->actions_len);
3470         }
3471         put->stats = NULL;
3472     }
3473 }
3474
3475 /* Handles flow miss 'miss'.  May add any required datapath operations
3476  * to 'ops', incrementing '*n_ops' for each new op. */
3477 static void
3478 handle_flow_miss(struct flow_miss *miss, struct flow_miss_op *ops,
3479                  size_t *n_ops)
3480 {
3481     struct ofproto_dpif *ofproto = miss->ofproto;
3482     struct dpif_flow_stats stats__;
3483     struct dpif_flow_stats *stats = &stats__;
3484     struct ofpbuf *packet;
3485     struct facet *facet;
3486     long long int now;
3487
3488     now = time_msec();
3489     memset(stats, 0, sizeof *stats);
3490     stats->used = now;
3491     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3492         stats->tcp_flags |= packet_get_tcp_flags(packet, &miss->flow);
3493         stats->n_bytes += packet->size;
3494         stats->n_packets++;
3495     }
3496
3497     facet = facet_lookup_valid(ofproto, &miss->flow);
3498     if (!facet) {
3499         struct flow_wildcards wc;
3500         struct rule_dpif *rule;
3501         struct xlate_out xout;
3502         struct xlate_in xin;
3503
3504         flow_wildcards_init_catchall(&wc);
3505         rule = rule_dpif_lookup(ofproto, &miss->flow, &wc);
3506         rule_credit_stats(rule, stats);
3507
3508         xlate_in_init(&xin, ofproto, &miss->flow, rule, stats->tcp_flags,
3509                       NULL);
3510         xin.resubmit_stats = stats;
3511         xin.may_learn = true;
3512         xlate_actions(&xin, &xout);
3513         flow_wildcards_or(&xout.wc, &xout.wc, &wc);
3514
3515         /* There does not exist a bijection between 'struct flow' and datapath
3516          * flow keys with fitness ODP_FIT_TO_LITTLE.  This breaks a fundamental
3517          * assumption used throughout the facet and subfacet handling code.
3518          * Since we have to handle these misses in userspace anyway, we simply
3519          * skip facet creation, avoiding the problem altogether. */
3520         if (miss->key_fitness == ODP_FIT_TOO_LITTLE
3521             || !flow_miss_should_make_facet(miss, &xout.wc)) {
3522             handle_flow_miss_without_facet(rule, &xout, miss, ops, n_ops);
3523             return;
3524         }
3525
3526         facet = facet_create(miss, rule, &xout, stats);
3527         stats = NULL;
3528     }
3529     handle_flow_miss_with_facet(miss, facet, now, stats, ops, n_ops);
3530 }
3531
3532 static struct drop_key *
3533 drop_key_lookup(const struct dpif_backer *backer, const struct nlattr *key,
3534                 size_t key_len)
3535 {
3536     struct drop_key *drop_key;
3537
3538     HMAP_FOR_EACH_WITH_HASH (drop_key, hmap_node, hash_bytes(key, key_len, 0),
3539                              &backer->drop_keys) {
3540         if (drop_key->key_len == key_len
3541             && !memcmp(drop_key->key, key, key_len)) {
3542             return drop_key;
3543         }
3544     }
3545     return NULL;
3546 }
3547
3548 static void
3549 drop_key_clear(struct dpif_backer *backer)
3550 {
3551     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
3552     struct drop_key *drop_key, *next;
3553
3554     HMAP_FOR_EACH_SAFE (drop_key, next, hmap_node, &backer->drop_keys) {
3555         int error;
3556
3557         error = dpif_flow_del(backer->dpif, drop_key->key, drop_key->key_len,
3558                               NULL);
3559         if (error && !VLOG_DROP_WARN(&rl)) {
3560             struct ds ds = DS_EMPTY_INITIALIZER;
3561             odp_flow_key_format(drop_key->key, drop_key->key_len, &ds);
3562             VLOG_WARN("Failed to delete drop key (%s) (%s)", strerror(error),
3563                       ds_cstr(&ds));
3564             ds_destroy(&ds);
3565         }
3566
3567         hmap_remove(&backer->drop_keys, &drop_key->hmap_node);
3568         free(drop_key->key);
3569         free(drop_key);
3570     }
3571 }
3572
3573 /* Given a datpath, packet, and flow metadata ('backer', 'packet', and 'key'
3574  * respectively), populates 'flow' with the result of odp_flow_key_to_flow().
3575  * Optionally, if nonnull, populates 'fitnessp' with the fitness of 'flow' as
3576  * returned by odp_flow_key_to_flow().  Also, optionally populates 'ofproto'
3577  * with the ofproto_dpif, and 'odp_in_port' with the datapath in_port, that
3578  * 'packet' ingressed.
3579  *
3580  * If 'ofproto' is nonnull, requires 'flow''s in_port to exist.  Otherwise sets
3581  * 'flow''s in_port to OFPP_NONE.
3582  *
3583  * This function does post-processing on data returned from
3584  * odp_flow_key_to_flow() to help make VLAN splinters transparent to the rest
3585  * of the upcall processing logic.  In particular, if the extracted in_port is
3586  * a VLAN splinter port, it replaces flow->in_port by the "real" port, sets
3587  * flow->vlan_tci correctly for the VLAN of the VLAN splinter port, and pushes
3588  * a VLAN header onto 'packet' (if it is nonnull).
3589  *
3590  * Similarly, this function also includes some logic to help with tunnels.  It
3591  * may modify 'flow' as necessary to make the tunneling implementation
3592  * transparent to the upcall processing logic.
3593  *
3594  * Returns 0 if successful, ENODEV if the parsed flow has no associated ofport,
3595  * or some other positive errno if there are other problems. */
3596 static int
3597 ofproto_receive(const struct dpif_backer *backer, struct ofpbuf *packet,
3598                 const struct nlattr *key, size_t key_len,
3599                 struct flow *flow, enum odp_key_fitness *fitnessp,
3600                 struct ofproto_dpif **ofproto, uint32_t *odp_in_port)
3601 {
3602     const struct ofport_dpif *port;
3603     enum odp_key_fitness fitness;
3604     int error = ENODEV;
3605
3606     fitness = odp_flow_key_to_flow(key, key_len, flow);
3607     if (fitness == ODP_FIT_ERROR) {
3608         error = EINVAL;
3609         goto exit;
3610     }
3611
3612     if (odp_in_port) {
3613         *odp_in_port = flow->in_port;
3614     }
3615
3616     port = (tnl_port_should_receive(flow)
3617             ? ofport_dpif_cast(tnl_port_receive(flow))
3618             : odp_port_to_ofport(backer, flow->in_port));
3619     flow->in_port = port ? port->up.ofp_port : OFPP_NONE;
3620     if (!port) {
3621         goto exit;
3622     }
3623
3624     /* XXX: Since the tunnel module is not scoped per backer, for a tunnel port
3625      * it's theoretically possible that we'll receive an ofport belonging to an
3626      * entirely different datapath.  In practice, this can't happen because no
3627      * platforms has two separate datapaths which each support tunneling. */
3628     ovs_assert(ofproto_dpif_cast(port->up.ofproto)->backer == backer);
3629
3630     if (vsp_adjust_flow(ofproto_dpif_cast(port->up.ofproto), flow)) {
3631         if (packet) {
3632             /* Make the packet resemble the flow, so that it gets sent to
3633              * an OpenFlow controller properly, so that it looks correct
3634              * for sFlow, and so that flow_extract() will get the correct
3635              * vlan_tci if it is called on 'packet'.
3636              *
3637              * The allocated space inside 'packet' probably also contains
3638              * 'key', that is, both 'packet' and 'key' are probably part of
3639              * a struct dpif_upcall (see the large comment on that
3640              * structure definition), so pushing data on 'packet' is in
3641              * general not a good idea since it could overwrite 'key' or
3642              * free it as a side effect.  However, it's OK in this special
3643              * case because we know that 'packet' is inside a Netlink
3644              * attribute: pushing 4 bytes will just overwrite the 4-byte
3645              * "struct nlattr", which is fine since we don't need that
3646              * header anymore. */
3647             eth_push_vlan(packet, flow->vlan_tci);
3648         }
3649         /* We can't reproduce 'key' from 'flow'. */
3650         fitness = fitness == ODP_FIT_PERFECT ? ODP_FIT_TOO_MUCH : fitness;
3651     }
3652     error = 0;
3653
3654     if (ofproto) {
3655         *ofproto = ofproto_dpif_cast(port->up.ofproto);
3656     }
3657
3658 exit:
3659     if (fitnessp) {
3660         *fitnessp = fitness;
3661     }
3662     return error;
3663 }
3664
3665 static void
3666 handle_miss_upcalls(struct dpif_backer *backer, struct dpif_upcall *upcalls,
3667                     size_t n_upcalls)
3668 {
3669     struct dpif_upcall *upcall;
3670     struct flow_miss *miss;
3671     struct flow_miss misses[FLOW_MISS_MAX_BATCH];
3672     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
3673     struct dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
3674     struct hmap todo;
3675     int n_misses;
3676     size_t n_ops;
3677     size_t i;
3678
3679     if (!n_upcalls) {
3680         return;
3681     }
3682
3683     /* Construct the to-do list.
3684      *
3685      * This just amounts to extracting the flow from each packet and sticking
3686      * the packets that have the same flow in the same "flow_miss" structure so
3687      * that we can process them together. */
3688     hmap_init(&todo);
3689     n_misses = 0;
3690     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
3691         struct flow_miss *miss = &misses[n_misses];
3692         struct flow_miss *existing_miss;
3693         struct ofproto_dpif *ofproto;
3694         uint32_t odp_in_port;
3695         struct flow flow;
3696         uint32_t hash;
3697         int error;
3698
3699         error = ofproto_receive(backer, upcall->packet, upcall->key,
3700                                 upcall->key_len, &flow, &miss->key_fitness,
3701                                 &ofproto, &odp_in_port);
3702         if (error == ENODEV) {
3703             struct drop_key *drop_key;
3704
3705             /* Received packet on datapath port for which we couldn't
3706              * associate an ofproto.  This can happen if a port is removed
3707              * while traffic is being received.  Print a rate-limited message
3708              * in case it happens frequently.  Install a drop flow so
3709              * that future packets of the flow are inexpensively dropped
3710              * in the kernel. */
3711             VLOG_INFO_RL(&rl, "received packet on unassociated datapath port "
3712                               "%"PRIu32, odp_in_port);
3713
3714             drop_key = drop_key_lookup(backer, upcall->key, upcall->key_len);
3715             if (!drop_key) {
3716                 drop_key = xmalloc(sizeof *drop_key);
3717                 drop_key->key = xmemdup(upcall->key, upcall->key_len);
3718                 drop_key->key_len = upcall->key_len;
3719
3720                 hmap_insert(&backer->drop_keys, &drop_key->hmap_node,
3721                             hash_bytes(drop_key->key, drop_key->key_len, 0));
3722                 dpif_flow_put(backer->dpif, DPIF_FP_CREATE | DPIF_FP_MODIFY,
3723                               drop_key->key, drop_key->key_len, NULL, 0, NULL);
3724             }
3725             continue;
3726         }
3727         if (error) {
3728             continue;
3729         }
3730
3731         ofproto->n_missed++;
3732         flow_extract(upcall->packet, flow.skb_priority, flow.skb_mark,
3733                      &flow.tunnel, flow.in_port, &miss->flow);
3734
3735         /* Add other packets to a to-do list. */
3736         hash = flow_hash(&miss->flow, 0);
3737         existing_miss = flow_miss_find(&todo, ofproto, &miss->flow, hash);
3738         if (!existing_miss) {
3739             hmap_insert(&todo, &miss->hmap_node, hash);
3740             miss->ofproto = ofproto;
3741             miss->key = upcall->key;
3742             miss->key_len = upcall->key_len;
3743             miss->upcall_type = upcall->type;
3744             list_init(&miss->packets);
3745
3746             n_misses++;
3747         } else {
3748             miss = existing_miss;
3749         }
3750         list_push_back(&miss->packets, &upcall->packet->list_node);
3751     }
3752
3753     /* Process each element in the to-do list, constructing the set of
3754      * operations to batch. */
3755     n_ops = 0;
3756     HMAP_FOR_EACH (miss, hmap_node, &todo) {
3757         handle_flow_miss(miss, flow_miss_ops, &n_ops);
3758     }
3759     ovs_assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
3760
3761     /* Execute batch. */
3762     for (i = 0; i < n_ops; i++) {
3763         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
3764     }
3765     dpif_operate(backer->dpif, dpif_ops, n_ops);
3766
3767     /* Free memory. */
3768     for (i = 0; i < n_ops; i++) {
3769         if (flow_miss_ops[i].xout_garbage) {
3770             xlate_out_uninit(&flow_miss_ops[i].xout);
3771         }
3772     }
3773     hmap_destroy(&todo);
3774 }
3775
3776 static enum { SFLOW_UPCALL, MISS_UPCALL, BAD_UPCALL, FLOW_SAMPLE_UPCALL,
3777               IPFIX_UPCALL }
3778 classify_upcall(const struct dpif_upcall *upcall)
3779 {
3780     size_t userdata_len;
3781     union user_action_cookie cookie;
3782
3783     /* First look at the upcall type. */
3784     switch (upcall->type) {
3785     case DPIF_UC_ACTION:
3786         break;
3787
3788     case DPIF_UC_MISS:
3789         return MISS_UPCALL;
3790
3791     case DPIF_N_UC_TYPES:
3792     default:
3793         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
3794         return BAD_UPCALL;
3795     }
3796
3797     /* "action" upcalls need a closer look. */
3798     if (!upcall->userdata) {
3799         VLOG_WARN_RL(&rl, "action upcall missing cookie");
3800         return BAD_UPCALL;
3801     }
3802     userdata_len = nl_attr_get_size(upcall->userdata);
3803     if (userdata_len < sizeof cookie.type
3804         || userdata_len > sizeof cookie) {
3805         VLOG_WARN_RL(&rl, "action upcall cookie has unexpected size %zu",
3806                      userdata_len);
3807         return BAD_UPCALL;
3808     }
3809     memset(&cookie, 0, sizeof cookie);
3810     memcpy(&cookie, nl_attr_get(upcall->userdata), userdata_len);
3811     if (userdata_len == sizeof cookie.sflow
3812         && cookie.type == USER_ACTION_COOKIE_SFLOW) {
3813         return SFLOW_UPCALL;
3814     } else if (userdata_len == sizeof cookie.slow_path
3815                && cookie.type == USER_ACTION_COOKIE_SLOW_PATH) {
3816         return MISS_UPCALL;
3817     } else if (userdata_len == sizeof cookie.flow_sample
3818                && cookie.type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
3819         return FLOW_SAMPLE_UPCALL;
3820     } else if (userdata_len == sizeof cookie.ipfix
3821                && cookie.type == USER_ACTION_COOKIE_IPFIX) {
3822         return IPFIX_UPCALL;
3823     } else {
3824         VLOG_WARN_RL(&rl, "invalid user cookie of type %"PRIu16
3825                      " and size %zu", cookie.type, userdata_len);
3826         return BAD_UPCALL;
3827     }
3828 }
3829
3830 static void
3831 handle_sflow_upcall(struct dpif_backer *backer,
3832                     const struct dpif_upcall *upcall)
3833 {
3834     struct ofproto_dpif *ofproto;
3835     union user_action_cookie cookie;
3836     struct flow flow;
3837     uint32_t odp_in_port;
3838
3839     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3840                         &flow, NULL, &ofproto, &odp_in_port)
3841         || !ofproto->sflow) {
3842         return;
3843     }
3844
3845     memset(&cookie, 0, sizeof cookie);
3846     memcpy(&cookie, nl_attr_get(upcall->userdata), sizeof cookie.sflow);
3847     dpif_sflow_received(ofproto->sflow, upcall->packet, &flow,
3848                         odp_in_port, &cookie);
3849 }
3850
3851 static void
3852 handle_flow_sample_upcall(struct dpif_backer *backer,
3853                           const struct dpif_upcall *upcall)
3854 {
3855     struct ofproto_dpif *ofproto;
3856     union user_action_cookie cookie;
3857     struct flow flow;
3858
3859     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3860                         &flow, NULL, &ofproto, NULL)
3861         || !ofproto->ipfix) {
3862         return;
3863     }
3864
3865     memset(&cookie, 0, sizeof cookie);
3866     memcpy(&cookie, nl_attr_get(upcall->userdata), sizeof cookie.flow_sample);
3867
3868     /* The flow reflects exactly the contents of the packet.  Sample
3869      * the packet using it. */
3870     dpif_ipfix_flow_sample(ofproto->ipfix, upcall->packet, &flow,
3871                            cookie.flow_sample.collector_set_id,
3872                            cookie.flow_sample.probability,
3873                            cookie.flow_sample.obs_domain_id,
3874                            cookie.flow_sample.obs_point_id);
3875 }
3876
3877 static void
3878 handle_ipfix_upcall(struct dpif_backer *backer,
3879                     const struct dpif_upcall *upcall)
3880 {
3881     struct ofproto_dpif *ofproto;
3882     struct flow flow;
3883
3884     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3885                         &flow, NULL, &ofproto, NULL)
3886         || !ofproto->ipfix) {
3887         return;
3888     }
3889
3890     /* The flow reflects exactly the contents of the packet.  Sample
3891      * the packet using it. */
3892     dpif_ipfix_bridge_sample(ofproto->ipfix, upcall->packet, &flow);
3893 }
3894
3895 static int
3896 handle_upcalls(struct dpif_backer *backer, unsigned int max_batch)
3897 {
3898     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
3899     struct ofpbuf miss_bufs[FLOW_MISS_MAX_BATCH];
3900     uint64_t miss_buf_stubs[FLOW_MISS_MAX_BATCH][4096 / 8];
3901     int n_processed;
3902     int n_misses;
3903     int i;
3904
3905     ovs_assert(max_batch <= FLOW_MISS_MAX_BATCH);
3906
3907     n_misses = 0;
3908     for (n_processed = 0; n_processed < max_batch; n_processed++) {
3909         struct dpif_upcall *upcall = &misses[n_misses];
3910         struct ofpbuf *buf = &miss_bufs[n_misses];
3911         int error;
3912
3913         ofpbuf_use_stub(buf, miss_buf_stubs[n_misses],
3914                         sizeof miss_buf_stubs[n_misses]);
3915         error = dpif_recv(backer->dpif, upcall, buf);
3916         if (error) {
3917             ofpbuf_uninit(buf);
3918             break;
3919         }
3920
3921         switch (classify_upcall(upcall)) {
3922         case MISS_UPCALL:
3923             /* Handle it later. */
3924             n_misses++;
3925             break;
3926
3927         case SFLOW_UPCALL:
3928             handle_sflow_upcall(backer, upcall);
3929             ofpbuf_uninit(buf);
3930             break;
3931
3932         case FLOW_SAMPLE_UPCALL:
3933             handle_flow_sample_upcall(backer, upcall);
3934             ofpbuf_uninit(buf);
3935             break;
3936
3937         case IPFIX_UPCALL:
3938             handle_ipfix_upcall(backer, upcall);
3939             ofpbuf_uninit(buf);
3940             break;
3941
3942         case BAD_UPCALL:
3943             ofpbuf_uninit(buf);
3944             break;
3945         }
3946     }
3947
3948     /* Handle deferred MISS_UPCALL processing. */
3949     handle_miss_upcalls(backer, misses, n_misses);
3950     for (i = 0; i < n_misses; i++) {
3951         ofpbuf_uninit(&miss_bufs[i]);
3952     }
3953
3954     return n_processed;
3955 }
3956 \f
3957 /* Flow expiration. */
3958
3959 static int subfacet_max_idle(const struct dpif_backer *);
3960 static void update_stats(struct dpif_backer *);
3961 static void rule_expire(struct rule_dpif *);
3962 static void expire_subfacets(struct dpif_backer *, int dp_max_idle);
3963
3964 /* This function is called periodically by run().  Its job is to collect
3965  * updates for the flows that have been installed into the datapath, most
3966  * importantly when they last were used, and then use that information to
3967  * expire flows that have not been used recently.
3968  *
3969  * Returns the number of milliseconds after which it should be called again. */
3970 static int
3971 expire(struct dpif_backer *backer)
3972 {
3973     struct ofproto_dpif *ofproto;
3974     size_t n_subfacets;
3975     int max_idle;
3976
3977     /* Periodically clear out the drop keys in an effort to keep them
3978      * relatively few. */
3979     drop_key_clear(backer);
3980
3981     /* Update stats for each flow in the backer. */
3982     update_stats(backer);
3983
3984     n_subfacets = hmap_count(&backer->subfacets);
3985     if (n_subfacets) {
3986         struct subfacet *subfacet;
3987         long long int total, now;
3988
3989         total = 0;
3990         now = time_msec();
3991         HMAP_FOR_EACH (subfacet, hmap_node, &backer->subfacets) {
3992             total += now - subfacet->created;
3993         }
3994         backer->avg_subfacet_life += total / n_subfacets;
3995     }
3996     backer->avg_subfacet_life /= 2;
3997
3998     backer->avg_n_subfacet += n_subfacets;
3999     backer->avg_n_subfacet /= 2;
4000
4001     backer->max_n_subfacet = MAX(backer->max_n_subfacet, n_subfacets);
4002
4003     max_idle = subfacet_max_idle(backer);
4004     expire_subfacets(backer, max_idle);
4005
4006     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4007         struct rule *rule, *next_rule;
4008
4009         if (ofproto->backer != backer) {
4010             continue;
4011         }
4012
4013         /* Expire OpenFlow flows whose idle_timeout or hard_timeout
4014          * has passed. */
4015         LIST_FOR_EACH_SAFE (rule, next_rule, expirable,
4016                             &ofproto->up.expirable) {
4017             rule_expire(rule_dpif_cast(rule));
4018         }
4019
4020         /* All outstanding data in existing flows has been accounted, so it's a
4021          * good time to do bond rebalancing. */
4022         if (ofproto->has_bonded_bundles) {
4023             struct ofbundle *bundle;
4024
4025             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4026                 if (bundle->bond) {
4027                     bond_rebalance(bundle->bond, &backer->revalidate_set);
4028                 }
4029             }
4030         }
4031     }
4032
4033     return MIN(max_idle, 1000);
4034 }
4035
4036 /* Updates flow table statistics given that the datapath just reported 'stats'
4037  * as 'subfacet''s statistics. */
4038 static void
4039 update_subfacet_stats(struct subfacet *subfacet,
4040                       const struct dpif_flow_stats *stats)
4041 {
4042     struct facet *facet = subfacet->facet;
4043     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4044     struct dpif_flow_stats diff;
4045
4046     diff.tcp_flags = stats->tcp_flags;
4047     diff.used = stats->used;
4048
4049     if (stats->n_packets >= subfacet->dp_packet_count) {
4050         diff.n_packets = stats->n_packets - subfacet->dp_packet_count;
4051     } else {
4052         VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
4053         diff.n_packets = 0;
4054     }
4055
4056     if (stats->n_bytes >= subfacet->dp_byte_count) {
4057         diff.n_bytes = stats->n_bytes - subfacet->dp_byte_count;
4058     } else {
4059         VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
4060         diff.n_bytes = 0;
4061     }
4062
4063     ofproto->n_hit += diff.n_packets;
4064     subfacet->dp_packet_count = stats->n_packets;
4065     subfacet->dp_byte_count = stats->n_bytes;
4066     subfacet_update_stats(subfacet, &diff);
4067
4068     if (facet->accounted_bytes < facet->byte_count) {
4069         facet_learn(facet);
4070         facet_account(facet);
4071         facet->accounted_bytes = facet->byte_count;
4072     }
4073 }
4074
4075 /* 'key' with length 'key_len' bytes is a flow in 'dpif' that we know nothing
4076  * about, or a flow that shouldn't be installed but was anyway.  Delete it. */
4077 static void
4078 delete_unexpected_flow(struct dpif_backer *backer,
4079                        const struct nlattr *key, size_t key_len)
4080 {
4081     if (!VLOG_DROP_WARN(&rl)) {
4082         struct ds s;
4083
4084         ds_init(&s);
4085         odp_flow_key_format(key, key_len, &s);
4086         VLOG_WARN("unexpected flow: %s", ds_cstr(&s));
4087         ds_destroy(&s);
4088     }
4089
4090     COVERAGE_INC(facet_unexpected);
4091     dpif_flow_del(backer->dpif, key, key_len, NULL);
4092 }
4093
4094 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
4095  *
4096  * This function also pushes statistics updates to rules which each facet
4097  * resubmits into.  Generally these statistics will be accurate.  However, if a
4098  * facet changes the rule it resubmits into at some time in between
4099  * update_stats() runs, it is possible that statistics accrued to the
4100  * old rule will be incorrectly attributed to the new rule.  This could be
4101  * avoided by calling update_stats() whenever rules are created or
4102  * deleted.  However, the performance impact of making so many calls to the
4103  * datapath do not justify the benefit of having perfectly accurate statistics.
4104  *
4105  * In addition, this function maintains per ofproto flow hit counts. The patch
4106  * port is not treated specially. e.g. A packet ingress from br0 patched into
4107  * br1 will increase the hit count of br0 by 1, however, does not affect
4108  * the hit or miss counts of br1.
4109  */
4110 static void
4111 update_stats(struct dpif_backer *backer)
4112 {
4113     const struct dpif_flow_stats *stats;
4114     struct dpif_flow_dump dump;
4115     const struct nlattr *key;
4116     size_t key_len;
4117
4118     dpif_flow_dump_start(&dump, backer->dpif);
4119     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
4120         struct subfacet *subfacet;
4121         uint32_t key_hash;
4122
4123         key_hash = odp_flow_key_hash(key, key_len);
4124         subfacet = subfacet_find(backer, key, key_len, key_hash);
4125         switch (subfacet ? subfacet->path : SF_NOT_INSTALLED) {
4126         case SF_FAST_PATH:
4127             update_subfacet_stats(subfacet, stats);
4128             break;
4129
4130         case SF_SLOW_PATH:
4131             /* Stats are updated per-packet. */
4132             break;
4133
4134         case SF_NOT_INSTALLED:
4135         default:
4136             delete_unexpected_flow(backer, key, key_len);
4137             break;
4138         }
4139         run_fast_rl();
4140     }
4141     dpif_flow_dump_done(&dump);
4142
4143     update_moving_averages(backer);
4144 }
4145
4146 /* Calculates and returns the number of milliseconds of idle time after which
4147  * subfacets should expire from the datapath.  When a subfacet expires, we fold
4148  * its statistics into its facet, and when a facet's last subfacet expires, we
4149  * fold its statistic into its rule. */
4150 static int
4151 subfacet_max_idle(const struct dpif_backer *backer)
4152 {
4153     /*
4154      * Idle time histogram.
4155      *
4156      * Most of the time a switch has a relatively small number of subfacets.
4157      * When this is the case we might as well keep statistics for all of them
4158      * in userspace and to cache them in the kernel datapath for performance as
4159      * well.
4160      *
4161      * As the number of subfacets increases, the memory required to maintain
4162      * statistics about them in userspace and in the kernel becomes
4163      * significant.  However, with a large number of subfacets it is likely
4164      * that only a few of them are "heavy hitters" that consume a large amount
4165      * of bandwidth.  At this point, only heavy hitters are worth caching in
4166      * the kernel and maintaining in userspaces; other subfacets we can
4167      * discard.
4168      *
4169      * The technique used to compute the idle time is to build a histogram with
4170      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
4171      * that is installed in the kernel gets dropped in the appropriate bucket.
4172      * After the histogram has been built, we compute the cutoff so that only
4173      * the most-recently-used 1% of subfacets (but at least
4174      * flow_eviction_threshold flows) are kept cached.  At least
4175      * the most-recently-used bucket of subfacets is kept, so actually an
4176      * arbitrary number of subfacets can be kept in any given expiration run
4177      * (though the next run will delete most of those unless they receive
4178      * additional data).
4179      *
4180      * This requires a second pass through the subfacets, in addition to the
4181      * pass made by update_stats(), because the former function never looks at
4182      * uninstallable subfacets.
4183      */
4184     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4185     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4186     int buckets[N_BUCKETS] = { 0 };
4187     int total, subtotal, bucket;
4188     struct subfacet *subfacet;
4189     long long int now;
4190     int i;
4191
4192     total = hmap_count(&backer->subfacets);
4193     if (total <= flow_eviction_threshold) {
4194         return N_BUCKETS * BUCKET_WIDTH;
4195     }
4196
4197     /* Build histogram. */
4198     now = time_msec();
4199     HMAP_FOR_EACH (subfacet, hmap_node, &backer->subfacets) {
4200         long long int idle = now - subfacet->used;
4201         int bucket = (idle <= 0 ? 0
4202                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4203                       : (unsigned int) idle / BUCKET_WIDTH);
4204         buckets[bucket]++;
4205     }
4206
4207     /* Find the first bucket whose flows should be expired. */
4208     subtotal = bucket = 0;
4209     do {
4210         subtotal += buckets[bucket++];
4211     } while (bucket < N_BUCKETS &&
4212              subtotal < MAX(flow_eviction_threshold, total / 100));
4213
4214     if (VLOG_IS_DBG_ENABLED()) {
4215         struct ds s;
4216
4217         ds_init(&s);
4218         ds_put_cstr(&s, "keep");
4219         for (i = 0; i < N_BUCKETS; i++) {
4220             if (i == bucket) {
4221                 ds_put_cstr(&s, ", drop");
4222             }
4223             if (buckets[i]) {
4224                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4225             }
4226         }
4227         VLOG_INFO("%s (msec:count)", ds_cstr(&s));
4228         ds_destroy(&s);
4229     }
4230
4231     return bucket * BUCKET_WIDTH;
4232 }
4233
4234 static void
4235 expire_subfacets(struct dpif_backer *backer, int dp_max_idle)
4236 {
4237     /* Cutoff time for most flows. */
4238     long long int normal_cutoff = time_msec() - dp_max_idle;
4239
4240     /* We really want to keep flows for special protocols around, so use a more
4241      * conservative cutoff. */
4242     long long int special_cutoff = time_msec() - 10000;
4243
4244     struct subfacet *subfacet, *next_subfacet;
4245     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
4246     int n_batch;
4247
4248     n_batch = 0;
4249     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
4250                         &backer->subfacets) {
4251         long long int cutoff;
4252
4253         cutoff = (subfacet->facet->xout.slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP
4254                                                 | SLOW_STP)
4255                   ? special_cutoff
4256                   : normal_cutoff);
4257         if (subfacet->used < cutoff) {
4258             if (subfacet->path != SF_NOT_INSTALLED) {
4259                 batch[n_batch++] = subfacet;
4260                 if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
4261                     subfacet_destroy_batch(backer, batch, n_batch);
4262                     n_batch = 0;
4263                 }
4264             } else {
4265                 subfacet_destroy(subfacet);
4266             }
4267         }
4268     }
4269
4270     if (n_batch > 0) {
4271         subfacet_destroy_batch(backer, batch, n_batch);
4272     }
4273 }
4274
4275 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4276  * then delete it entirely. */
4277 static void
4278 rule_expire(struct rule_dpif *rule)
4279 {
4280     struct facet *facet, *next_facet;
4281     long long int now;
4282     uint8_t reason;
4283
4284     if (rule->up.pending) {
4285         /* We'll have to expire it later. */
4286         return;
4287     }
4288
4289     /* Has 'rule' expired? */
4290     now = time_msec();
4291     if (rule->up.hard_timeout
4292         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
4293         reason = OFPRR_HARD_TIMEOUT;
4294     } else if (rule->up.idle_timeout
4295                && now > rule->up.used + rule->up.idle_timeout * 1000) {
4296         reason = OFPRR_IDLE_TIMEOUT;
4297     } else {
4298         return;
4299     }
4300
4301     COVERAGE_INC(ofproto_dpif_expired);
4302
4303     /* Update stats.  (This is a no-op if the rule expired due to an idle
4304      * timeout, because that only happens when the rule has no facets left.) */
4305     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4306         facet_remove(facet);
4307     }
4308
4309     /* Get rid of the rule. */
4310     ofproto_rule_expire(&rule->up, reason);
4311 }
4312 \f
4313 /* Facets. */
4314
4315 /* Creates and returns a new facet based on 'miss'.
4316  *
4317  * The caller must already have determined that no facet with an identical
4318  * 'miss->flow' exists in 'miss->ofproto'.
4319  *
4320  * 'rule' and 'xout' must have been created based on 'miss'.
4321  *
4322  * 'facet'' statistics are initialized based on 'stats'.
4323  *
4324  * The facet will initially have no subfacets.  The caller should create (at
4325  * least) one subfacet with subfacet_create(). */
4326 static struct facet *
4327 facet_create(const struct flow_miss *miss, struct rule_dpif *rule,
4328              struct xlate_out *xout, struct dpif_flow_stats *stats)
4329 {
4330     struct ofproto_dpif *ofproto = miss->ofproto;
4331     struct facet *facet;
4332     struct match match;
4333
4334     facet = xzalloc(sizeof *facet);
4335     facet->packet_count = facet->prev_packet_count = stats->n_packets;
4336     facet->byte_count = facet->prev_byte_count = stats->n_bytes;
4337     facet->tcp_flags = stats->tcp_flags;
4338     facet->used = stats->used;
4339     facet->flow = miss->flow;
4340     facet->learn_rl = time_msec() + 500;
4341     facet->rule = rule;
4342
4343     list_push_back(&facet->rule->facets, &facet->list_node);
4344     list_init(&facet->subfacets);
4345     netflow_flow_init(&facet->nf_flow);
4346     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
4347
4348     xlate_out_copy(&facet->xout, xout);
4349
4350     match_init(&match, &facet->flow, &facet->xout.wc);
4351     cls_rule_init(&facet->cr, &match, OFP_DEFAULT_PRIORITY);
4352     classifier_insert(&ofproto->facets, &facet->cr);
4353
4354     facet->nf_flow.output_iface = facet->xout.nf_output_iface;
4355
4356     return facet;
4357 }
4358
4359 static void
4360 facet_free(struct facet *facet)
4361 {
4362     if (facet) {
4363         xlate_out_uninit(&facet->xout);
4364         free(facet);
4365     }
4366 }
4367
4368 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
4369  * 'packet', which arrived on 'in_port'. */
4370 static bool
4371 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
4372                     const struct nlattr *odp_actions, size_t actions_len,
4373                     struct ofpbuf *packet)
4374 {
4375     struct odputil_keybuf keybuf;
4376     struct ofpbuf key;
4377     int error;
4378
4379     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
4380     odp_flow_key_from_flow(&key, flow,
4381                            ofp_port_to_odp_port(ofproto, flow->in_port));
4382
4383     error = dpif_execute(ofproto->backer->dpif, key.data, key.size,
4384                          odp_actions, actions_len, packet);
4385     return !error;
4386 }
4387
4388 /* Remove 'facet' from its ofproto and free up the associated memory:
4389  *
4390  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
4391  *     rule's statistics, via subfacet_uninstall().
4392  *
4393  *   - Removes 'facet' from its rule and from ofproto->facets.
4394  */
4395 static void
4396 facet_remove(struct facet *facet)
4397 {
4398     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4399     struct subfacet *subfacet, *next_subfacet;
4400
4401     ovs_assert(!list_is_empty(&facet->subfacets));
4402
4403     /* First uninstall all of the subfacets to get final statistics. */
4404     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4405         subfacet_uninstall(subfacet);
4406     }
4407
4408     /* Flush the final stats to the rule.
4409      *
4410      * This might require us to have at least one subfacet around so that we
4411      * can use its actions for accounting in facet_account(), which is why we
4412      * have uninstalled but not yet destroyed the subfacets. */
4413     facet_flush_stats(facet);
4414
4415     /* Now we're really all done so destroy everything. */
4416     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
4417                         &facet->subfacets) {
4418         subfacet_destroy__(subfacet);
4419     }
4420     classifier_remove(&ofproto->facets, &facet->cr);
4421     cls_rule_destroy(&facet->cr);
4422     list_remove(&facet->list_node);
4423     facet_free(facet);
4424 }
4425
4426 /* Feed information from 'facet' back into the learning table to keep it in
4427  * sync with what is actually flowing through the datapath. */
4428 static void
4429 facet_learn(struct facet *facet)
4430 {
4431     long long int now = time_msec();
4432
4433     if (!facet->xout.has_fin_timeout && now < facet->learn_rl) {
4434         return;
4435     }
4436
4437     facet->learn_rl = now + 500;
4438
4439     if (!facet->xout.has_learn
4440         && !facet->xout.has_normal
4441         && (!facet->xout.has_fin_timeout
4442             || !(facet->tcp_flags & (TCP_FIN | TCP_RST)))) {
4443         return;
4444     }
4445
4446     facet_push_stats(facet, true);
4447 }
4448
4449 static void
4450 facet_account(struct facet *facet)
4451 {
4452     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4453     const struct nlattr *a;
4454     unsigned int left;
4455     ovs_be16 vlan_tci;
4456     uint64_t n_bytes;
4457
4458     if (!facet->xout.has_normal || !ofproto->has_bonded_bundles) {
4459         return;
4460     }
4461     n_bytes = facet->byte_count - facet->accounted_bytes;
4462
4463     /* This loop feeds byte counters to bond_account() for rebalancing to use
4464      * as a basis.  We also need to track the actual VLAN on which the packet
4465      * is going to be sent to ensure that it matches the one passed to
4466      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
4467      * hash bucket.)
4468      *
4469      * We use the actions from an arbitrary subfacet because they should all
4470      * be equally valid for our purpose. */
4471     vlan_tci = facet->flow.vlan_tci;
4472     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->xout.odp_actions.data,
4473                              facet->xout.odp_actions.size) {
4474         const struct ovs_action_push_vlan *vlan;
4475         struct ofport_dpif *port;
4476
4477         switch (nl_attr_type(a)) {
4478         case OVS_ACTION_ATTR_OUTPUT:
4479             port = get_odp_port(ofproto, nl_attr_get_u32(a));
4480             if (port && port->bundle && port->bundle->bond) {
4481                 bond_account(port->bundle->bond, &facet->flow,
4482                              vlan_tci_to_vid(vlan_tci), n_bytes);
4483             }
4484             break;
4485
4486         case OVS_ACTION_ATTR_POP_VLAN:
4487             vlan_tci = htons(0);
4488             break;
4489
4490         case OVS_ACTION_ATTR_PUSH_VLAN:
4491             vlan = nl_attr_get(a);
4492             vlan_tci = vlan->vlan_tci;
4493             break;
4494         }
4495     }
4496 }
4497
4498 /* Returns true if the only action for 'facet' is to send to the controller.
4499  * (We don't report NetFlow expiration messages for such facets because they
4500  * are just part of the control logic for the network, not real traffic). */
4501 static bool
4502 facet_is_controller_flow(struct facet *facet)
4503 {
4504     if (facet) {
4505         const struct rule *rule = &facet->rule->up;
4506         const struct ofpact *ofpacts = rule->ofpacts;
4507         size_t ofpacts_len = rule->ofpacts_len;
4508
4509         if (ofpacts_len > 0 &&
4510             ofpacts->type == OFPACT_CONTROLLER &&
4511             ofpact_next(ofpacts) >= ofpact_end(ofpacts, ofpacts_len)) {
4512             return true;
4513         }
4514     }
4515     return false;
4516 }
4517
4518 /* Folds all of 'facet''s statistics into its rule.  Also updates the
4519  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
4520  * 'facet''s statistics in the datapath should have been zeroed and folded into
4521  * its packet and byte counts before this function is called. */
4522 static void
4523 facet_flush_stats(struct facet *facet)
4524 {
4525     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4526     struct subfacet *subfacet;
4527
4528     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4529         ovs_assert(!subfacet->dp_byte_count);
4530         ovs_assert(!subfacet->dp_packet_count);
4531     }
4532
4533     facet_push_stats(facet, false);
4534     if (facet->accounted_bytes < facet->byte_count) {
4535         facet_account(facet);
4536         facet->accounted_bytes = facet->byte_count;
4537     }
4538
4539     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
4540         struct ofexpired expired;
4541         expired.flow = facet->flow;
4542         expired.packet_count = facet->packet_count;
4543         expired.byte_count = facet->byte_count;
4544         expired.used = facet->used;
4545         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4546     }
4547
4548     /* Reset counters to prevent double counting if 'facet' ever gets
4549      * reinstalled. */
4550     facet_reset_counters(facet);
4551
4552     netflow_flow_clear(&facet->nf_flow);
4553     facet->tcp_flags = 0;
4554 }
4555
4556 /* Searches 'ofproto''s table of facets for one which would be responsible for
4557  * 'flow'.  Returns it if found, otherwise a null pointer.
4558  *
4559  * The returned facet might need revalidation; use facet_lookup_valid()
4560  * instead if that is important. */
4561 static struct facet *
4562 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
4563 {
4564     struct cls_rule *cr = classifier_lookup(&ofproto->facets, flow, NULL);
4565     return cr ? CONTAINER_OF(cr, struct facet, cr) : NULL;
4566 }
4567
4568 /* Searches 'ofproto''s table of facets for one capable that covers
4569  * 'flow'.  Returns it if found, otherwise a null pointer.
4570  *
4571  * The returned facet is guaranteed to be valid. */
4572 static struct facet *
4573 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
4574 {
4575     struct facet *facet;
4576
4577     facet = facet_find(ofproto, flow);
4578     if (facet
4579         && (ofproto->backer->need_revalidate
4580             || tag_set_intersects(&ofproto->backer->revalidate_set,
4581                                   facet->xout.tags))
4582         && !facet_revalidate(facet)) {
4583         return NULL;
4584     }
4585
4586     return facet;
4587 }
4588
4589 static bool
4590 facet_check_consistency(struct facet *facet)
4591 {
4592     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
4593
4594     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4595
4596     struct xlate_out xout;
4597     struct xlate_in xin;
4598
4599     struct rule_dpif *rule;
4600     bool ok;
4601
4602     /* Check the rule for consistency. */
4603     rule = rule_dpif_lookup(ofproto, &facet->flow, NULL);
4604     if (rule != facet->rule) {
4605         if (!VLOG_DROP_WARN(&rl)) {
4606             struct ds s = DS_EMPTY_INITIALIZER;
4607
4608             flow_format(&s, &facet->flow);
4609             ds_put_format(&s, ": facet associated with wrong rule (was "
4610                           "table=%"PRIu8",", facet->rule->up.table_id);
4611             cls_rule_format(&facet->rule->up.cr, &s);
4612             ds_put_format(&s, ") (should have been table=%"PRIu8",",
4613                           rule->up.table_id);
4614             cls_rule_format(&rule->up.cr, &s);
4615             ds_put_char(&s, ')');
4616
4617             VLOG_WARN("%s", ds_cstr(&s));
4618             ds_destroy(&s);
4619         }
4620         return false;
4621     }
4622
4623     /* Check the datapath actions for consistency. */
4624     xlate_in_init(&xin, ofproto, &facet->flow, rule, 0, NULL);
4625     xlate_actions(&xin, &xout);
4626
4627     ok = ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)
4628         && facet->xout.slow == xout.slow;
4629     if (!ok && !VLOG_DROP_WARN(&rl)) {
4630         struct ds s = DS_EMPTY_INITIALIZER;
4631
4632         flow_format(&s, &facet->flow);
4633         ds_put_cstr(&s, ": inconsistency in facet");
4634
4635         if (!ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)) {
4636             ds_put_cstr(&s, " (actions were: ");
4637             format_odp_actions(&s, facet->xout.odp_actions.data,
4638                                facet->xout.odp_actions.size);
4639             ds_put_cstr(&s, ") (correct actions: ");
4640             format_odp_actions(&s, xout.odp_actions.data,
4641                                xout.odp_actions.size);
4642             ds_put_char(&s, ')');
4643         }
4644
4645         if (facet->xout.slow != xout.slow) {
4646             ds_put_format(&s, " slow path incorrect. should be %d", xout.slow);
4647         }
4648
4649         VLOG_WARN("%s", ds_cstr(&s));
4650         ds_destroy(&s);
4651     }
4652     xlate_out_uninit(&xout);
4653
4654     return ok;
4655 }
4656
4657 /* Re-searches the classifier for 'facet':
4658  *
4659  *   - If the rule found is different from 'facet''s current rule, moves
4660  *     'facet' to the new rule and recompiles its actions.
4661  *
4662  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
4663  *     where it is and recompiles its actions anyway.
4664  *
4665  *   - If any of 'facet''s subfacets correspond to a new flow according to
4666  *     ofproto_receive(), 'facet' is removed.
4667  *
4668  *   Returns true if 'facet' is still valid.  False if 'facet' was removed. */
4669 static bool
4670 facet_revalidate(struct facet *facet)
4671 {
4672     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4673     struct rule_dpif *new_rule;
4674     struct subfacet *subfacet;
4675     struct flow_wildcards wc;
4676     struct xlate_out xout;
4677     struct xlate_in xin;
4678
4679     COVERAGE_INC(facet_revalidate);
4680
4681     /* Check that child subfacets still correspond to this facet.  Tunnel
4682      * configuration changes could cause a subfacet's OpenFlow in_port to
4683      * change. */
4684     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4685         struct ofproto_dpif *recv_ofproto;
4686         struct flow recv_flow;
4687         int error;
4688
4689         error = ofproto_receive(ofproto->backer, NULL, subfacet->key,
4690                                 subfacet->key_len, &recv_flow, NULL,
4691                                 &recv_ofproto, NULL);
4692         if (error
4693             || recv_ofproto != ofproto
4694             || facet != facet_find(ofproto, &recv_flow)) {
4695             facet_remove(facet);
4696             return false;
4697         }
4698     }
4699
4700     flow_wildcards_init_catchall(&wc);
4701     new_rule = rule_dpif_lookup(ofproto, &facet->flow, &wc);
4702
4703     /* Calculate new datapath actions.
4704      *
4705      * We do not modify any 'facet' state yet, because we might need to, e.g.,
4706      * emit a NetFlow expiration and, if so, we need to have the old state
4707      * around to properly compose it. */
4708     xlate_in_init(&xin, ofproto, &facet->flow, new_rule, 0, NULL);
4709     xlate_actions(&xin, &xout);
4710     flow_wildcards_or(&xout.wc, &xout.wc, &wc);
4711
4712     /* A facet's slow path reason should only change under dramatic
4713      * circumstances.  Rather than try to update everything, it's simpler to
4714      * remove the facet and start over.
4715      *
4716      * More importantly, if a facet's wildcards change, it will be relatively
4717      * difficult to figure out if its subfacets still belong to it, and if not
4718      * which facet they may belong to.  Again, to avoid the complexity, we
4719      * simply give up instead. */
4720     if (facet->xout.slow != xout.slow
4721         || memcmp(&facet->xout.wc, &xout.wc, sizeof xout.wc)) {
4722         facet_remove(facet);
4723         xlate_out_uninit(&xout);
4724         return false;
4725     }
4726
4727     if (!ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)) {
4728         LIST_FOR_EACH(subfacet, list_node, &facet->subfacets) {
4729             if (subfacet->path == SF_FAST_PATH) {
4730                 struct dpif_flow_stats stats;
4731
4732                 subfacet_install(subfacet, &xout.odp_actions, &stats);
4733                 subfacet_update_stats(subfacet, &stats);
4734             }
4735         }
4736
4737         facet_flush_stats(facet);
4738
4739         ofpbuf_clear(&facet->xout.odp_actions);
4740         ofpbuf_put(&facet->xout.odp_actions, xout.odp_actions.data,
4741                    xout.odp_actions.size);
4742     }
4743
4744     /* Update 'facet' now that we've taken care of all the old state. */
4745     facet->xout.tags = xout.tags;
4746     facet->xout.slow = xout.slow;
4747     facet->xout.has_learn = xout.has_learn;
4748     facet->xout.has_normal = xout.has_normal;
4749     facet->xout.has_fin_timeout = xout.has_fin_timeout;
4750     facet->xout.nf_output_iface = xout.nf_output_iface;
4751     facet->xout.mirrors = xout.mirrors;
4752     facet->nf_flow.output_iface = facet->xout.nf_output_iface;
4753
4754     if (facet->rule != new_rule) {
4755         COVERAGE_INC(facet_changed_rule);
4756         list_remove(&facet->list_node);
4757         list_push_back(&new_rule->facets, &facet->list_node);
4758         facet->rule = new_rule;
4759         facet->used = new_rule->up.created;
4760         facet->prev_used = facet->used;
4761     }
4762
4763     xlate_out_uninit(&xout);
4764     return true;
4765 }
4766
4767 static void
4768 facet_reset_counters(struct facet *facet)
4769 {
4770     facet->packet_count = 0;
4771     facet->byte_count = 0;
4772     facet->prev_packet_count = 0;
4773     facet->prev_byte_count = 0;
4774     facet->accounted_bytes = 0;
4775 }
4776
4777 static void
4778 facet_push_stats(struct facet *facet, bool may_learn)
4779 {
4780     struct dpif_flow_stats stats;
4781
4782     ovs_assert(facet->packet_count >= facet->prev_packet_count);
4783     ovs_assert(facet->byte_count >= facet->prev_byte_count);
4784     ovs_assert(facet->used >= facet->prev_used);
4785
4786     stats.n_packets = facet->packet_count - facet->prev_packet_count;
4787     stats.n_bytes = facet->byte_count - facet->prev_byte_count;
4788     stats.used = facet->used;
4789     stats.tcp_flags = facet->tcp_flags;
4790
4791     if (may_learn || stats.n_packets || facet->used > facet->prev_used) {
4792         struct ofproto_dpif *ofproto =
4793             ofproto_dpif_cast(facet->rule->up.ofproto);
4794
4795         struct ofport_dpif *in_port;
4796         struct xlate_in xin;
4797
4798         facet->prev_packet_count = facet->packet_count;
4799         facet->prev_byte_count = facet->byte_count;
4800         facet->prev_used = facet->used;
4801
4802         in_port = get_ofp_port(ofproto, facet->flow.in_port);
4803         if (in_port && in_port->tnl_port) {
4804             netdev_vport_inc_rx(in_port->up.netdev, &stats);
4805         }
4806
4807         rule_credit_stats(facet->rule, &stats);
4808         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow,
4809                                  facet->used);
4810         netflow_flow_update_flags(&facet->nf_flow, facet->tcp_flags);
4811         update_mirror_stats(ofproto, facet->xout.mirrors, stats.n_packets,
4812                             stats.n_bytes);
4813
4814         xlate_in_init(&xin, ofproto, &facet->flow, facet->rule,
4815                       stats.tcp_flags, NULL);
4816         xin.resubmit_stats = &stats;
4817         xin.may_learn = may_learn;
4818         xlate_actions_for_side_effects(&xin);
4819     }
4820 }
4821
4822 static void
4823 push_all_stats__(bool run_fast)
4824 {
4825     static long long int rl = LLONG_MIN;
4826     struct ofproto_dpif *ofproto;
4827
4828     if (time_msec() < rl) {
4829         return;
4830     }
4831
4832     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4833         struct cls_cursor cursor;
4834         struct facet *facet;
4835
4836         cls_cursor_init(&cursor, &ofproto->facets, NULL);
4837         CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
4838             facet_push_stats(facet, false);
4839             if (run_fast) {
4840                 run_fast_rl();
4841             }
4842         }
4843     }
4844
4845     rl = time_msec() + 100;
4846 }
4847
4848 static void
4849 push_all_stats(void)
4850 {
4851     push_all_stats__(true);
4852 }
4853
4854 void
4855 rule_credit_stats(struct rule_dpif *rule, const struct dpif_flow_stats *stats)
4856 {
4857     rule->packet_count += stats->n_packets;
4858     rule->byte_count += stats->n_bytes;
4859     ofproto_rule_update_used(&rule->up, stats->used);
4860 }
4861 \f
4862 /* Subfacets. */
4863
4864 static struct subfacet *
4865 subfacet_find(struct dpif_backer *backer, const struct nlattr *key,
4866               size_t key_len, uint32_t key_hash)
4867 {
4868     struct subfacet *subfacet;
4869
4870     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
4871                              &backer->subfacets) {
4872         if (subfacet->key_len == key_len
4873             && !memcmp(key, subfacet->key, key_len)) {
4874             return subfacet;
4875         }
4876     }
4877
4878     return NULL;
4879 }
4880
4881 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
4882  * 'key_fitness', 'key', and 'key_len' members in 'miss'.  Returns the
4883  * existing subfacet if there is one, otherwise creates and returns a
4884  * new subfacet. */
4885 static struct subfacet *
4886 subfacet_create(struct facet *facet, struct flow_miss *miss,
4887                 long long int now)
4888 {
4889     struct dpif_backer *backer = miss->ofproto->backer;
4890     enum odp_key_fitness key_fitness = miss->key_fitness;
4891     const struct nlattr *key = miss->key;
4892     size_t key_len = miss->key_len;
4893     uint32_t key_hash;
4894     struct subfacet *subfacet;
4895
4896     key_hash = odp_flow_key_hash(key, key_len);
4897
4898     if (list_is_empty(&facet->subfacets)) {
4899         subfacet = &facet->one_subfacet;
4900     } else {
4901         subfacet = subfacet_find(backer, key, key_len, key_hash);
4902         if (subfacet) {
4903             if (subfacet->facet == facet) {
4904                 return subfacet;
4905             }
4906
4907             /* This shouldn't happen. */
4908             VLOG_ERR_RL(&rl, "subfacet with wrong facet");
4909             subfacet_destroy(subfacet);
4910         }
4911
4912         subfacet = xmalloc(sizeof *subfacet);
4913     }
4914
4915     hmap_insert(&backer->subfacets, &subfacet->hmap_node, key_hash);
4916     list_push_back(&facet->subfacets, &subfacet->list_node);
4917     subfacet->facet = facet;
4918     subfacet->key_fitness = key_fitness;
4919     subfacet->key = xmemdup(key, key_len);
4920     subfacet->key_len = key_len;
4921     subfacet->used = now;
4922     subfacet->created = now;
4923     subfacet->dp_packet_count = 0;
4924     subfacet->dp_byte_count = 0;
4925     subfacet->path = SF_NOT_INSTALLED;
4926     subfacet->backer = backer;
4927
4928     backer->subfacet_add_count++;
4929     return subfacet;
4930 }
4931
4932 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
4933  * its facet within 'ofproto', and frees it. */
4934 static void
4935 subfacet_destroy__(struct subfacet *subfacet)
4936 {
4937     struct facet *facet = subfacet->facet;
4938     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4939
4940     /* Update ofproto stats before uninstall the subfacet. */
4941     ofproto->backer->subfacet_del_count++;
4942
4943     subfacet_uninstall(subfacet);
4944     hmap_remove(&subfacet->backer->subfacets, &subfacet->hmap_node);
4945     list_remove(&subfacet->list_node);
4946     free(subfacet->key);
4947     if (subfacet != &facet->one_subfacet) {
4948         free(subfacet);
4949     }
4950 }
4951
4952 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
4953  * last remaining subfacet in its facet destroys the facet too. */
4954 static void
4955 subfacet_destroy(struct subfacet *subfacet)
4956 {
4957     struct facet *facet = subfacet->facet;
4958
4959     if (list_is_singleton(&facet->subfacets)) {
4960         /* facet_remove() needs at least one subfacet (it will remove it). */
4961         facet_remove(facet);
4962     } else {
4963         subfacet_destroy__(subfacet);
4964     }
4965 }
4966
4967 static void
4968 subfacet_destroy_batch(struct dpif_backer *backer,
4969                        struct subfacet **subfacets, int n)
4970 {
4971     struct dpif_op ops[SUBFACET_DESTROY_MAX_BATCH];
4972     struct dpif_op *opsp[SUBFACET_DESTROY_MAX_BATCH];
4973     struct dpif_flow_stats stats[SUBFACET_DESTROY_MAX_BATCH];
4974     int i;
4975
4976     for (i = 0; i < n; i++) {
4977         ops[i].type = DPIF_OP_FLOW_DEL;
4978         ops[i].u.flow_del.key = subfacets[i]->key;
4979         ops[i].u.flow_del.key_len = subfacets[i]->key_len;
4980         ops[i].u.flow_del.stats = &stats[i];
4981         opsp[i] = &ops[i];
4982     }
4983
4984     dpif_operate(backer->dpif, opsp, n);
4985     for (i = 0; i < n; i++) {
4986         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
4987         subfacets[i]->path = SF_NOT_INSTALLED;
4988         subfacet_destroy(subfacets[i]);
4989         run_fast_rl();
4990     }
4991 }
4992
4993 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
4994  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
4995  * in the datapath will be zeroed and 'stats' will be updated with traffic new
4996  * since 'subfacet' was last updated.
4997  *
4998  * Returns 0 if successful, otherwise a positive errno value. */
4999 static int
5000 subfacet_install(struct subfacet *subfacet, const struct ofpbuf *odp_actions,
5001                  struct dpif_flow_stats *stats)
5002 {
5003     struct facet *facet = subfacet->facet;
5004     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5005     enum subfacet_path path = facet->xout.slow ? SF_SLOW_PATH : SF_FAST_PATH;
5006     const struct nlattr *actions = odp_actions->data;
5007     size_t actions_len = odp_actions->size;
5008
5009     uint64_t slow_path_stub[128 / 8];
5010     enum dpif_flow_put_flags flags;
5011     int ret;
5012
5013     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
5014     if (stats) {
5015         flags |= DPIF_FP_ZERO_STATS;
5016     }
5017
5018     if (path == SF_SLOW_PATH) {
5019         compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
5020                           slow_path_stub, sizeof slow_path_stub,
5021                           &actions, &actions_len);
5022     }
5023
5024     ret = dpif_flow_put(subfacet->backer->dpif, flags, subfacet->key,
5025                         subfacet->key_len, actions, actions_len, stats);
5026
5027     if (stats) {
5028         subfacet_reset_dp_stats(subfacet, stats);
5029     }
5030
5031     if (!ret) {
5032         subfacet->path = path;
5033     }
5034     return ret;
5035 }
5036
5037 /* If 'subfacet' is installed in the datapath, uninstalls it. */
5038 static void
5039 subfacet_uninstall(struct subfacet *subfacet)
5040 {
5041     if (subfacet->path != SF_NOT_INSTALLED) {
5042         struct rule_dpif *rule = subfacet->facet->rule;
5043         struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5044         struct dpif_flow_stats stats;
5045         int error;
5046
5047         error = dpif_flow_del(ofproto->backer->dpif, subfacet->key,
5048                               subfacet->key_len, &stats);
5049         subfacet_reset_dp_stats(subfacet, &stats);
5050         if (!error) {
5051             subfacet_update_stats(subfacet, &stats);
5052         }
5053         subfacet->path = SF_NOT_INSTALLED;
5054     } else {
5055         ovs_assert(subfacet->dp_packet_count == 0);
5056         ovs_assert(subfacet->dp_byte_count == 0);
5057     }
5058 }
5059
5060 /* Resets 'subfacet''s datapath statistics counters.  This should be called
5061  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
5062  * non-null, it should contain the statistics returned by dpif when 'subfacet'
5063  * was reset in the datapath.  'stats' will be modified to include only
5064  * statistics new since 'subfacet' was last updated. */
5065 static void
5066 subfacet_reset_dp_stats(struct subfacet *subfacet,
5067                         struct dpif_flow_stats *stats)
5068 {
5069     if (stats
5070         && subfacet->dp_packet_count <= stats->n_packets
5071         && subfacet->dp_byte_count <= stats->n_bytes) {
5072         stats->n_packets -= subfacet->dp_packet_count;
5073         stats->n_bytes -= subfacet->dp_byte_count;
5074     }
5075
5076     subfacet->dp_packet_count = 0;
5077     subfacet->dp_byte_count = 0;
5078 }
5079
5080 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
5081  *
5082  * Because of the meaning of a subfacet's counters, it only makes sense to do
5083  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
5084  * represents a packet that was sent by hand or if it represents statistics
5085  * that have been cleared out of the datapath. */
5086 static void
5087 subfacet_update_stats(struct subfacet *subfacet,
5088                       const struct dpif_flow_stats *stats)
5089 {
5090     if (stats->n_packets || stats->used > subfacet->used) {
5091         struct facet *facet = subfacet->facet;
5092
5093         subfacet->used = MAX(subfacet->used, stats->used);
5094         facet->used = MAX(facet->used, stats->used);
5095         facet->packet_count += stats->n_packets;
5096         facet->byte_count += stats->n_bytes;
5097         facet->tcp_flags |= stats->tcp_flags;
5098     }
5099 }
5100 \f
5101 /* Rules. */
5102
5103 /* Lookup 'flow' in 'ofproto''s classifier.  If 'wc' is non-null, sets
5104  * the fields that were relevant as part of the lookup. */
5105 static struct rule_dpif *
5106 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
5107                  struct flow_wildcards *wc)
5108 {
5109     struct rule_dpif *rule;
5110
5111     rule = rule_dpif_lookup_in_table(ofproto, flow, wc, 0);
5112     if (rule) {
5113         return rule;
5114     }
5115
5116     return rule_dpif_miss_rule(ofproto, flow);
5117 }
5118
5119 struct rule_dpif *
5120 rule_dpif_lookup_in_table(struct ofproto_dpif *ofproto,
5121                           const struct flow *flow, struct flow_wildcards *wc,
5122                           uint8_t table_id)
5123 {
5124     struct cls_rule *cls_rule;
5125     struct classifier *cls;
5126     bool frag;
5127
5128     if (table_id >= N_TABLES) {
5129         return NULL;
5130     }
5131
5132     cls = &ofproto->up.tables[table_id].cls;
5133     frag = (flow->nw_frag & FLOW_NW_FRAG_ANY) != 0;
5134     if (frag && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
5135         /* We must pretend that transport ports are unavailable. */
5136         struct flow ofpc_normal_flow = *flow;
5137         ofpc_normal_flow.tp_src = htons(0);
5138         ofpc_normal_flow.tp_dst = htons(0);
5139         cls_rule = classifier_lookup(cls, &ofpc_normal_flow, wc);
5140     } else if (frag && ofproto->up.frag_handling == OFPC_FRAG_DROP) {
5141         cls_rule = &ofproto->drop_frags_rule->up.cr;
5142         if (wc) {
5143             flow_wildcards_init_exact(wc);
5144         }
5145     } else {
5146         cls_rule = classifier_lookup(cls, flow, wc);
5147     }
5148     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
5149 }
5150
5151 struct rule_dpif *
5152 rule_dpif_miss_rule(struct ofproto_dpif *ofproto, const struct flow *flow)
5153 {
5154     struct ofport_dpif *port;
5155
5156     port = get_ofp_port(ofproto, flow->in_port);
5157     if (!port) {
5158         VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, flow->in_port);
5159         return ofproto->miss_rule;
5160     }
5161
5162     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
5163         return ofproto->no_packet_in_rule;
5164     }
5165     return ofproto->miss_rule;
5166 }
5167
5168 static void
5169 complete_operation(struct rule_dpif *rule)
5170 {
5171     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5172
5173     rule_invalidate(rule);
5174     if (clogged) {
5175         struct dpif_completion *c = xmalloc(sizeof *c);
5176         c->op = rule->up.pending;
5177         list_push_back(&ofproto->completions, &c->list_node);
5178     } else {
5179         ofoperation_complete(rule->up.pending, 0);
5180     }
5181 }
5182
5183 static struct rule *
5184 rule_alloc(void)
5185 {
5186     struct rule_dpif *rule = xmalloc(sizeof *rule);
5187     return &rule->up;
5188 }
5189
5190 static void
5191 rule_dealloc(struct rule *rule_)
5192 {
5193     struct rule_dpif *rule = rule_dpif_cast(rule_);
5194     free(rule);
5195 }
5196
5197 static enum ofperr
5198 rule_construct(struct rule *rule_)
5199 {
5200     struct rule_dpif *rule = rule_dpif_cast(rule_);
5201     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5202     struct rule_dpif *victim;
5203     uint8_t table_id;
5204
5205     rule->packet_count = 0;
5206     rule->byte_count = 0;
5207
5208     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
5209     if (victim && !list_is_empty(&victim->facets)) {
5210         struct facet *facet;
5211
5212         rule->facets = victim->facets;
5213         list_moved(&rule->facets);
5214         LIST_FOR_EACH (facet, list_node, &rule->facets) {
5215             /* XXX: We're only clearing our local counters here.  It's possible
5216              * that quite a few packets are unaccounted for in the datapath
5217              * statistics.  These will be accounted to the new rule instead of
5218              * cleared as required.  This could be fixed by clearing out the
5219              * datapath statistics for this facet, but currently it doesn't
5220              * seem worth it. */
5221             facet_reset_counters(facet);
5222             facet->rule = rule;
5223         }
5224     } else {
5225         /* Must avoid list_moved() in this case. */
5226         list_init(&rule->facets);
5227     }
5228
5229     table_id = rule->up.table_id;
5230     if (victim) {
5231         rule->tag = victim->tag;
5232     } else if (table_id == 0) {
5233         rule->tag = 0;
5234     } else {
5235         struct flow flow;
5236
5237         miniflow_expand(&rule->up.cr.match.flow, &flow);
5238         rule->tag = rule_calculate_tag(&flow, &rule->up.cr.match.mask,
5239                                        ofproto->tables[table_id].basis);
5240     }
5241
5242     complete_operation(rule);
5243     return 0;
5244 }
5245
5246 static void
5247 rule_destruct(struct rule *rule_)
5248 {
5249     struct rule_dpif *rule = rule_dpif_cast(rule_);
5250     struct facet *facet, *next_facet;
5251
5252     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5253         facet_revalidate(facet);
5254     }
5255
5256     complete_operation(rule);
5257 }
5258
5259 static void
5260 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
5261 {
5262     struct rule_dpif *rule = rule_dpif_cast(rule_);
5263
5264     /* push_all_stats() can handle flow misses which, when using the learn
5265      * action, can cause rules to be added and deleted.  This can corrupt our
5266      * caller's datastructures which assume that rule_get_stats() doesn't have
5267      * an impact on the flow table. To be safe, we disable miss handling. */
5268     push_all_stats__(false);
5269
5270     /* Start from historical data for 'rule' itself that are no longer tracked
5271      * in facets.  This counts, for example, facets that have expired. */
5272     *packets = rule->packet_count;
5273     *bytes = rule->byte_count;
5274 }
5275
5276 static void
5277 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
5278                   struct ofpbuf *packet)
5279 {
5280     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5281     struct dpif_flow_stats stats;
5282     struct xlate_out xout;
5283     struct xlate_in xin;
5284
5285     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5286     rule_credit_stats(rule, &stats);
5287
5288     xlate_in_init(&xin, ofproto, flow, rule, stats.tcp_flags, packet);
5289     xin.resubmit_stats = &stats;
5290     xlate_actions(&xin, &xout);
5291
5292     execute_odp_actions(ofproto, flow, xout.odp_actions.data,
5293                         xout.odp_actions.size, packet);
5294
5295     xlate_out_uninit(&xout);
5296 }
5297
5298 static enum ofperr
5299 rule_execute(struct rule *rule, const struct flow *flow,
5300              struct ofpbuf *packet)
5301 {
5302     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
5303     ofpbuf_delete(packet);
5304     return 0;
5305 }
5306
5307 static void
5308 rule_modify_actions(struct rule *rule_)
5309 {
5310     struct rule_dpif *rule = rule_dpif_cast(rule_);
5311
5312     complete_operation(rule);
5313 }
5314 \f
5315 /* Sends 'packet' out 'ofport'.
5316  * May modify 'packet'.
5317  * Returns 0 if successful, otherwise a positive errno value. */
5318 static int
5319 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
5320 {
5321     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5322     uint64_t odp_actions_stub[1024 / 8];
5323     struct ofpbuf key, odp_actions;
5324     struct dpif_flow_stats stats;
5325     struct odputil_keybuf keybuf;
5326     struct ofpact_output output;
5327     struct xlate_out xout;
5328     struct xlate_in xin;
5329     struct flow flow;
5330     int error;
5331
5332     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5333     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5334
5335     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
5336     flow_extract(packet, 0, 0, NULL, OFPP_NONE, &flow);
5337     odp_flow_key_from_flow(&key, &flow, ofp_port_to_odp_port(ofproto,
5338                                                              OFPP_LOCAL));
5339     dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5340
5341     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
5342     output.port = ofport->up.ofp_port;
5343     output.max_len = 0;
5344
5345     xlate_in_init(&xin, ofproto, &flow, NULL, 0, packet);
5346     xin.ofpacts_len = sizeof output;
5347     xin.ofpacts = &output.ofpact;
5348     xin.resubmit_stats = &stats;
5349     xlate_actions(&xin, &xout);
5350
5351     error = dpif_execute(ofproto->backer->dpif,
5352                          key.data, key.size,
5353                          xout.odp_actions.data, xout.odp_actions.size,
5354                          packet);
5355     xlate_out_uninit(&xout);
5356
5357     if (error) {
5358         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %s (%s)",
5359                      ofproto->up.name, netdev_get_name(ofport->up.netdev),
5360                      strerror(error));
5361     }
5362
5363     ofproto->stats.tx_packets++;
5364     ofproto->stats.tx_bytes += packet->size;
5365     return error;
5366 }
5367
5368 /* Composes an ODP action for a "slow path" action for 'flow' within 'ofproto'.
5369  * The action will state 'slow' as the reason that the action is in the slow
5370  * path.  (This is purely informational: it allows a human viewing "ovs-dpctl
5371  * dump-flows" output to see why a flow is in the slow path.)
5372  *
5373  * The 'stub_size' bytes in 'stub' will be used to store the action.
5374  * 'stub_size' must be large enough for the action.
5375  *
5376  * The action and its size will be stored in '*actionsp' and '*actions_lenp',
5377  * respectively. */
5378 static void
5379 compose_slow_path(const struct ofproto_dpif *ofproto, const struct flow *flow,
5380                   enum slow_path_reason slow,
5381                   uint64_t *stub, size_t stub_size,
5382                   const struct nlattr **actionsp, size_t *actions_lenp)
5383 {
5384     union user_action_cookie cookie;
5385     struct ofpbuf buf;
5386
5387     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
5388     cookie.slow_path.unused = 0;
5389     cookie.slow_path.reason = slow;
5390
5391     ofpbuf_use_stack(&buf, stub, stub_size);
5392     if (slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)) {
5393         uint32_t pid = dpif_port_get_pid(ofproto->backer->dpif, UINT32_MAX);
5394         odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, &buf);
5395     } else {
5396         put_userspace_action(ofproto, &buf, flow, &cookie,
5397                              sizeof cookie.slow_path);
5398     }
5399     *actionsp = buf.data;
5400     *actions_lenp = buf.size;
5401 }
5402
5403 size_t
5404 put_userspace_action(const struct ofproto_dpif *ofproto,
5405                      struct ofpbuf *odp_actions,
5406                      const struct flow *flow,
5407                      const union user_action_cookie *cookie,
5408                      const size_t cookie_size)
5409 {
5410     uint32_t pid;
5411
5412     pid = dpif_port_get_pid(ofproto->backer->dpif,
5413                             ofp_port_to_odp_port(ofproto, flow->in_port));
5414
5415     return odp_put_userspace_action(pid, cookie, cookie_size, odp_actions);
5416 }
5417
5418
5419 static void
5420 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
5421                     uint64_t packets, uint64_t bytes)
5422 {
5423     if (!mirrors) {
5424         return;
5425     }
5426
5427     for (; mirrors; mirrors = zero_rightmost_1bit(mirrors)) {
5428         struct ofmirror *m;
5429
5430         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
5431
5432         if (!m) {
5433             /* In normal circumstances 'm' will not be NULL.  However,
5434              * if mirrors are reconfigured, we can temporarily get out
5435              * of sync in facet_revalidate().  We could "correct" the
5436              * mirror list before reaching here, but doing that would
5437              * not properly account the traffic stats we've currently
5438              * accumulated for previous mirror configuration. */
5439             continue;
5440         }
5441
5442         m->packet_count += packets;
5443         m->byte_count += bytes;
5444     }
5445 }
5446
5447 \f
5448 /* Optimized flow revalidation.
5449  *
5450  * It's a difficult problem, in general, to tell which facets need to have
5451  * their actions recalculated whenever the OpenFlow flow table changes.  We
5452  * don't try to solve that general problem: for most kinds of OpenFlow flow
5453  * table changes, we recalculate the actions for every facet.  This is
5454  * relatively expensive, but it's good enough if the OpenFlow flow table
5455  * doesn't change very often.
5456  *
5457  * However, we can expect one particular kind of OpenFlow flow table change to
5458  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
5459  * of CPU on revalidating every facet whenever MAC learning modifies the flow
5460  * table, we add a special case that applies to flow tables in which every rule
5461  * has the same form (that is, the same wildcards), except that the table is
5462  * also allowed to have a single "catch-all" flow that matches all packets.  We
5463  * optimize this case by tagging all of the facets that resubmit into the table
5464  * and invalidating the same tag whenever a flow changes in that table.  The
5465  * end result is that we revalidate just the facets that need it (and sometimes
5466  * a few more, but not all of the facets or even all of the facets that
5467  * resubmit to the table modified by MAC learning). */
5468
5469 /* Calculates the tag to use for 'flow' and mask 'mask' when it is inserted
5470  * into an OpenFlow table with the given 'basis'. */
5471 tag_type
5472 rule_calculate_tag(const struct flow *flow, const struct minimask *mask,
5473                    uint32_t secret)
5474 {
5475     if (minimask_is_catchall(mask)) {
5476         return 0;
5477     } else {
5478         uint32_t hash = flow_hash_in_minimask(flow, mask, secret);
5479         return tag_create_deterministic(hash);
5480     }
5481 }
5482
5483 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
5484  * taggability of that table.
5485  *
5486  * This function must be called after *each* change to a flow table.  If you
5487  * skip calling it on some changes then the pointer comparisons at the end can
5488  * be invalid if you get unlucky.  For example, if a flow removal causes a
5489  * cls_table to be destroyed and then a flow insertion causes a cls_table with
5490  * different wildcards to be created with the same address, then this function
5491  * will incorrectly skip revalidation. */
5492 static void
5493 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
5494 {
5495     struct table_dpif *table = &ofproto->tables[table_id];
5496     const struct oftable *oftable = &ofproto->up.tables[table_id];
5497     struct cls_table *catchall, *other;
5498     struct cls_table *t;
5499
5500     catchall = other = NULL;
5501
5502     switch (hmap_count(&oftable->cls.tables)) {
5503     case 0:
5504         /* We could tag this OpenFlow table but it would make the logic a
5505          * little harder and it's a corner case that doesn't seem worth it
5506          * yet. */
5507         break;
5508
5509     case 1:
5510     case 2:
5511         HMAP_FOR_EACH (t, hmap_node, &oftable->cls.tables) {
5512             if (cls_table_is_catchall(t)) {
5513                 catchall = t;
5514             } else if (!other) {
5515                 other = t;
5516             } else {
5517                 /* Indicate that we can't tag this by setting both tables to
5518                  * NULL.  (We know that 'catchall' is already NULL.) */
5519                 other = NULL;
5520             }
5521         }
5522         break;
5523
5524     default:
5525         /* Can't tag this table. */
5526         break;
5527     }
5528
5529     if (table->catchall_table != catchall || table->other_table != other) {
5530         table->catchall_table = catchall;
5531         table->other_table = other;
5532         ofproto->backer->need_revalidate = REV_FLOW_TABLE;
5533     }
5534 }
5535
5536 /* Given 'rule' that has changed in some way (either it is a rule being
5537  * inserted, a rule being deleted, or a rule whose actions are being
5538  * modified), marks facets for revalidation to ensure that packets will be
5539  * forwarded correctly according to the new state of the flow table.
5540  *
5541  * This function must be called after *each* change to a flow table.  See
5542  * the comment on table_update_taggable() for more information. */
5543 static void
5544 rule_invalidate(const struct rule_dpif *rule)
5545 {
5546     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5547
5548     table_update_taggable(ofproto, rule->up.table_id);
5549
5550     if (!ofproto->backer->need_revalidate) {
5551         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5552
5553         if (table->other_table && rule->tag) {
5554             tag_set_add(&ofproto->backer->revalidate_set, rule->tag);
5555         } else {
5556             ofproto->backer->need_revalidate = REV_FLOW_TABLE;
5557         }
5558     }
5559 }
5560 \f
5561 static bool
5562 set_frag_handling(struct ofproto *ofproto_,
5563                   enum ofp_config_flags frag_handling)
5564 {
5565     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5566     if (frag_handling != OFPC_FRAG_REASM) {
5567         ofproto->backer->need_revalidate = REV_RECONFIGURE;
5568         return true;
5569     } else {
5570         return false;
5571     }
5572 }
5573
5574 static enum ofperr
5575 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5576            const struct flow *flow,
5577            const struct ofpact *ofpacts, size_t ofpacts_len)
5578 {
5579     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5580     struct odputil_keybuf keybuf;
5581     struct dpif_flow_stats stats;
5582     struct xlate_out xout;
5583     struct xlate_in xin;
5584     struct ofpbuf key;
5585
5586
5587     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5588     odp_flow_key_from_flow(&key, flow,
5589                            ofp_port_to_odp_port(ofproto, flow->in_port));
5590
5591     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5592
5593     xlate_in_init(&xin, ofproto, flow, NULL, stats.tcp_flags, packet);
5594     xin.resubmit_stats = &stats;
5595     xin.ofpacts_len = ofpacts_len;
5596     xin.ofpacts = ofpacts;
5597
5598     xlate_actions(&xin, &xout);
5599     dpif_execute(ofproto->backer->dpif, key.data, key.size,
5600                  xout.odp_actions.data, xout.odp_actions.size, packet);
5601     xlate_out_uninit(&xout);
5602
5603     return 0;
5604 }
5605 \f
5606 /* NetFlow. */
5607
5608 static int
5609 set_netflow(struct ofproto *ofproto_,
5610             const struct netflow_options *netflow_options)
5611 {
5612     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5613
5614     if (netflow_options) {
5615         if (!ofproto->netflow) {
5616             ofproto->netflow = netflow_create();
5617         }
5618         return netflow_set_options(ofproto->netflow, netflow_options);
5619     } else {
5620         netflow_destroy(ofproto->netflow);
5621         ofproto->netflow = NULL;
5622         return 0;
5623     }
5624 }
5625
5626 static void
5627 get_netflow_ids(const struct ofproto *ofproto_,
5628                 uint8_t *engine_type, uint8_t *engine_id)
5629 {
5630     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5631
5632     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
5633 }
5634
5635 static void
5636 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
5637 {
5638     if (!facet_is_controller_flow(facet) &&
5639         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5640         struct subfacet *subfacet;
5641         struct ofexpired expired;
5642
5643         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5644             if (subfacet->path == SF_FAST_PATH) {
5645                 struct dpif_flow_stats stats;
5646
5647                 subfacet_install(subfacet, &facet->xout.odp_actions,
5648                                  &stats);
5649                 subfacet_update_stats(subfacet, &stats);
5650             }
5651         }
5652
5653         expired.flow = facet->flow;
5654         expired.packet_count = facet->packet_count;
5655         expired.byte_count = facet->byte_count;
5656         expired.used = facet->used;
5657         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5658     }
5659 }
5660
5661 static void
5662 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
5663 {
5664     struct cls_cursor cursor;
5665     struct facet *facet;
5666
5667     cls_cursor_init(&cursor, &ofproto->facets, NULL);
5668     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
5669         send_active_timeout(ofproto, facet);
5670     }
5671 }
5672 \f
5673 static struct ofproto_dpif *
5674 ofproto_dpif_lookup(const char *name)
5675 {
5676     struct ofproto_dpif *ofproto;
5677
5678     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
5679                              hash_string(name, 0), &all_ofproto_dpifs) {
5680         if (!strcmp(ofproto->up.name, name)) {
5681             return ofproto;
5682         }
5683     }
5684     return NULL;
5685 }
5686
5687 static void
5688 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
5689                           const char *argv[], void *aux OVS_UNUSED)
5690 {
5691     struct ofproto_dpif *ofproto;
5692
5693     if (argc > 1) {
5694         ofproto = ofproto_dpif_lookup(argv[1]);
5695         if (!ofproto) {
5696             unixctl_command_reply_error(conn, "no such bridge");
5697             return;
5698         }
5699         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
5700     } else {
5701         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
5702             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
5703         }
5704     }
5705
5706     unixctl_command_reply(conn, "table successfully flushed");
5707 }
5708
5709 static void
5710 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
5711                          const char *argv[], void *aux OVS_UNUSED)
5712 {
5713     struct ds ds = DS_EMPTY_INITIALIZER;
5714     const struct ofproto_dpif *ofproto;
5715     const struct mac_entry *e;
5716
5717     ofproto = ofproto_dpif_lookup(argv[1]);
5718     if (!ofproto) {
5719         unixctl_command_reply_error(conn, "no such bridge");
5720         return;
5721     }
5722
5723     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5724     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5725         struct ofbundle *bundle = e->port.p;
5726         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5727                       ofbundle_get_a_port(bundle)->odp_port,
5728                       e->vlan, ETH_ADDR_ARGS(e->mac),
5729                       mac_entry_age(ofproto->ml, e));
5730     }
5731     unixctl_command_reply(conn, ds_cstr(&ds));
5732     ds_destroy(&ds);
5733 }
5734
5735 struct trace_ctx {
5736     struct xlate_out xout;
5737     struct xlate_in xin;
5738     struct flow flow;
5739     struct ds *result;
5740 };
5741
5742 static void
5743 trace_format_rule(struct ds *result, int level, const struct rule_dpif *rule)
5744 {
5745     ds_put_char_multiple(result, '\t', level);
5746     if (!rule) {
5747         ds_put_cstr(result, "No match\n");
5748         return;
5749     }
5750
5751     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5752                   rule ? rule->up.table_id : 0, ntohll(rule->up.flow_cookie));
5753     cls_rule_format(&rule->up.cr, result);
5754     ds_put_char(result, '\n');
5755
5756     ds_put_char_multiple(result, '\t', level);
5757     ds_put_cstr(result, "OpenFlow ");
5758     ofpacts_format(rule->up.ofpacts, rule->up.ofpacts_len, result);
5759     ds_put_char(result, '\n');
5760 }
5761
5762 static void
5763 trace_format_flow(struct ds *result, int level, const char *title,
5764                   struct trace_ctx *trace)
5765 {
5766     ds_put_char_multiple(result, '\t', level);
5767     ds_put_format(result, "%s: ", title);
5768     if (flow_equal(&trace->xin.flow, &trace->flow)) {
5769         ds_put_cstr(result, "unchanged");
5770     } else {
5771         flow_format(result, &trace->xin.flow);
5772         trace->flow = trace->xin.flow;
5773     }
5774     ds_put_char(result, '\n');
5775 }
5776
5777 static void
5778 trace_format_regs(struct ds *result, int level, const char *title,
5779                   struct trace_ctx *trace)
5780 {
5781     size_t i;
5782
5783     ds_put_char_multiple(result, '\t', level);
5784     ds_put_format(result, "%s:", title);
5785     for (i = 0; i < FLOW_N_REGS; i++) {
5786         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5787     }
5788     ds_put_char(result, '\n');
5789 }
5790
5791 static void
5792 trace_format_odp(struct ds *result, int level, const char *title,
5793                  struct trace_ctx *trace)
5794 {
5795     struct ofpbuf *odp_actions = &trace->xout.odp_actions;
5796
5797     ds_put_char_multiple(result, '\t', level);
5798     ds_put_format(result, "%s: ", title);
5799     format_odp_actions(result, odp_actions->data, odp_actions->size);
5800     ds_put_char(result, '\n');
5801 }
5802
5803 static void
5804 trace_resubmit(struct xlate_in *xin, struct rule_dpif *rule, int recurse)
5805 {
5806     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
5807     struct ds *result = trace->result;
5808
5809     ds_put_char(result, '\n');
5810     trace_format_flow(result, recurse + 1, "Resubmitted flow", trace);
5811     trace_format_regs(result, recurse + 1, "Resubmitted regs", trace);
5812     trace_format_odp(result,  recurse + 1, "Resubmitted  odp", trace);
5813     trace_format_rule(result, recurse + 1, rule);
5814 }
5815
5816 static void
5817 trace_report(struct xlate_in *xin, const char *s, int recurse)
5818 {
5819     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
5820     struct ds *result = trace->result;
5821
5822     ds_put_char_multiple(result, '\t', recurse);
5823     ds_put_cstr(result, s);
5824     ds_put_char(result, '\n');
5825 }
5826
5827 static void
5828 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
5829                       void *aux OVS_UNUSED)
5830 {
5831     const struct dpif_backer *backer;
5832     struct ofproto_dpif *ofproto;
5833     struct ofpbuf odp_key;
5834     struct ofpbuf *packet;
5835     struct ds result;
5836     struct flow flow;
5837     char *s;
5838
5839     packet = NULL;
5840     backer = NULL;
5841     ds_init(&result);
5842     ofpbuf_init(&odp_key, 0);
5843
5844     /* Handle "-generate" or a hex string as the last argument. */
5845     if (!strcmp(argv[argc - 1], "-generate")) {
5846         packet = ofpbuf_new(0);
5847         argc--;
5848     } else {
5849         const char *error = eth_from_hex(argv[argc - 1], &packet);
5850         if (!error) {
5851             argc--;
5852         } else if (argc == 4) {
5853             /* The 3-argument form must end in "-generate' or a hex string. */
5854             unixctl_command_reply_error(conn, error);
5855             goto exit;
5856         }
5857     }
5858
5859     /* Parse the flow and determine whether a datapath or
5860      * bridge is specified. If function odp_flow_key_from_string()
5861      * returns 0, the flow is a odp_flow. If function
5862      * parse_ofp_exact_flow() returns 0, the flow is a br_flow. */
5863     if (!odp_flow_key_from_string(argv[argc - 1], NULL, &odp_key)) {
5864         /* If the odp_flow is the second argument,
5865          * the datapath name is the first argument. */
5866         if (argc == 3) {
5867             const char *dp_type;
5868             if (!strncmp(argv[1], "ovs-", 4)) {
5869                 dp_type = argv[1] + 4;
5870             } else {
5871                 dp_type = argv[1];
5872             }
5873             backer = shash_find_data(&all_dpif_backers, dp_type);
5874             if (!backer) {
5875                 unixctl_command_reply_error(conn, "Cannot find datapath "
5876                                "of this name");
5877                 goto exit;
5878             }
5879         } else {
5880             /* No datapath name specified, so there should be only one
5881              * datapath. */
5882             struct shash_node *node;
5883             if (shash_count(&all_dpif_backers) != 1) {
5884                 unixctl_command_reply_error(conn, "Must specify datapath "
5885                          "name, there is more than one type of datapath");
5886                 goto exit;
5887             }
5888             node = shash_first(&all_dpif_backers);
5889             backer = node->data;
5890         }
5891
5892         /* Extract the ofproto_dpif object from the ofproto_receive()
5893          * function. */
5894         if (ofproto_receive(backer, NULL, odp_key.data,
5895                             odp_key.size, &flow, NULL, &ofproto, NULL)) {
5896             unixctl_command_reply_error(conn, "Invalid datapath flow");
5897             goto exit;
5898         }
5899         ds_put_format(&result, "Bridge: %s\n", ofproto->up.name);
5900     } else if (!parse_ofp_exact_flow(&flow, argv[argc - 1])) {
5901         if (argc != 3) {
5902             unixctl_command_reply_error(conn, "Must specify bridge name");
5903             goto exit;
5904         }
5905
5906         ofproto = ofproto_dpif_lookup(argv[1]);
5907         if (!ofproto) {
5908             unixctl_command_reply_error(conn, "Unknown bridge name");
5909             goto exit;
5910         }
5911     } else {
5912         unixctl_command_reply_error(conn, "Bad flow syntax");
5913         goto exit;
5914     }
5915
5916     /* Generate a packet, if requested. */
5917     if (packet) {
5918         if (!packet->size) {
5919             flow_compose(packet, &flow);
5920         } else {
5921             ds_put_cstr(&result, "Packet: ");
5922             s = ofp_packet_to_string(packet->data, packet->size);
5923             ds_put_cstr(&result, s);
5924             free(s);
5925
5926             /* Use the metadata from the flow and the packet argument
5927              * to reconstruct the flow. */
5928             flow_extract(packet, flow.skb_priority, flow.skb_mark, NULL,
5929                          flow.in_port, &flow);
5930         }
5931     }
5932
5933     ofproto_trace(ofproto, &flow, packet, &result);
5934     unixctl_command_reply(conn, ds_cstr(&result));
5935
5936 exit:
5937     ds_destroy(&result);
5938     ofpbuf_delete(packet);
5939     ofpbuf_uninit(&odp_key);
5940 }
5941
5942 void
5943 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
5944               const struct ofpbuf *packet, struct ds *ds)
5945 {
5946     struct rule_dpif *rule;
5947
5948     ds_put_cstr(ds, "Flow: ");
5949     flow_format(ds, flow);
5950     ds_put_char(ds, '\n');
5951
5952     rule = rule_dpif_lookup(ofproto, flow, NULL);
5953
5954     trace_format_rule(ds, 0, rule);
5955     if (rule == ofproto->miss_rule) {
5956         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
5957     } else if (rule == ofproto->no_packet_in_rule) {
5958         ds_put_cstr(ds, "\nNo match, packets dropped because "
5959                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
5960     } else if (rule == ofproto->drop_frags_rule) {
5961         ds_put_cstr(ds, "\nPackets dropped because they are IP fragments "
5962                     "and the fragment handling mode is \"drop\".\n");
5963     }
5964
5965     if (rule) {
5966         uint64_t odp_actions_stub[1024 / 8];
5967         struct ofpbuf odp_actions;
5968         struct trace_ctx trace;
5969         struct match match;
5970         uint8_t tcp_flags;
5971
5972         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
5973         trace.result = ds;
5974         trace.flow = *flow;
5975         ofpbuf_use_stub(&odp_actions,
5976                         odp_actions_stub, sizeof odp_actions_stub);
5977         xlate_in_init(&trace.xin, ofproto, flow, rule, tcp_flags, packet);
5978         trace.xin.resubmit_hook = trace_resubmit;
5979         trace.xin.report_hook = trace_report;
5980
5981         xlate_actions(&trace.xin, &trace.xout);
5982
5983         ds_put_char(ds, '\n');
5984         trace_format_flow(ds, 0, "Final flow", &trace);
5985
5986         match_init(&match, flow, &trace.xout.wc);
5987         ds_put_cstr(ds, "Relevant fields: ");
5988         match_format(&match, ds, OFP_DEFAULT_PRIORITY);
5989         ds_put_char(ds, '\n');
5990
5991         ds_put_cstr(ds, "Datapath actions: ");
5992         format_odp_actions(ds, trace.xout.odp_actions.data,
5993                            trace.xout.odp_actions.size);
5994
5995         if (trace.xout.slow) {
5996             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
5997                         "slow path because it:");
5998             switch (trace.xout.slow) {
5999             case SLOW_CFM:
6000                 ds_put_cstr(ds, "\n\t- Consists of CFM packets.");
6001                 break;
6002             case SLOW_LACP:
6003                 ds_put_cstr(ds, "\n\t- Consists of LACP packets.");
6004                 break;
6005             case SLOW_STP:
6006                 ds_put_cstr(ds, "\n\t- Consists of STP packets.");
6007                 break;
6008             case SLOW_BFD:
6009                 ds_put_cstr(ds, "\n\t- Consists of BFD packets.");
6010                 break;
6011             case SLOW_CONTROLLER:
6012                 ds_put_cstr(ds, "\n\t- Sends \"packet-in\" messages "
6013                             "to the OpenFlow controller.");
6014                 break;
6015             case __SLOW_MAX:
6016                 NOT_REACHED();
6017             }
6018         }
6019
6020         xlate_out_uninit(&trace.xout);
6021     }
6022 }
6023
6024 static void
6025 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
6026                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6027 {
6028     clogged = true;
6029     unixctl_command_reply(conn, NULL);
6030 }
6031
6032 static void
6033 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
6034                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6035 {
6036     clogged = false;
6037     unixctl_command_reply(conn, NULL);
6038 }
6039
6040 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
6041  * 'reply' describing the results. */
6042 static void
6043 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
6044 {
6045     struct cls_cursor cursor;
6046     struct facet *facet;
6047     int errors;
6048
6049     errors = 0;
6050     cls_cursor_init(&cursor, &ofproto->facets, NULL);
6051     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
6052         if (!facet_check_consistency(facet)) {
6053             errors++;
6054         }
6055     }
6056     if (errors) {
6057         ofproto->backer->need_revalidate = REV_INCONSISTENCY;
6058     }
6059
6060     if (errors) {
6061         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
6062                       ofproto->up.name, errors);
6063     } else {
6064         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
6065     }
6066 }
6067
6068 static void
6069 ofproto_dpif_self_check(struct unixctl_conn *conn,
6070                         int argc, const char *argv[], void *aux OVS_UNUSED)
6071 {
6072     struct ds reply = DS_EMPTY_INITIALIZER;
6073     struct ofproto_dpif *ofproto;
6074
6075     if (argc > 1) {
6076         ofproto = ofproto_dpif_lookup(argv[1]);
6077         if (!ofproto) {
6078             unixctl_command_reply_error(conn, "Unknown ofproto (use "
6079                                         "ofproto/list for help)");
6080             return;
6081         }
6082         ofproto_dpif_self_check__(ofproto, &reply);
6083     } else {
6084         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6085             ofproto_dpif_self_check__(ofproto, &reply);
6086         }
6087     }
6088
6089     unixctl_command_reply(conn, ds_cstr(&reply));
6090     ds_destroy(&reply);
6091 }
6092
6093 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
6094  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
6095  * to destroy 'ofproto_shash' and free the returned value. */
6096 static const struct shash_node **
6097 get_ofprotos(struct shash *ofproto_shash)
6098 {
6099     const struct ofproto_dpif *ofproto;
6100
6101     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6102         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
6103         shash_add_nocopy(ofproto_shash, name, ofproto);
6104     }
6105
6106     return shash_sort(ofproto_shash);
6107 }
6108
6109 static void
6110 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
6111                               const char *argv[] OVS_UNUSED,
6112                               void *aux OVS_UNUSED)
6113 {
6114     struct ds ds = DS_EMPTY_INITIALIZER;
6115     struct shash ofproto_shash;
6116     const struct shash_node **sorted_ofprotos;
6117     int i;
6118
6119     shash_init(&ofproto_shash);
6120     sorted_ofprotos = get_ofprotos(&ofproto_shash);
6121     for (i = 0; i < shash_count(&ofproto_shash); i++) {
6122         const struct shash_node *node = sorted_ofprotos[i];
6123         ds_put_format(&ds, "%s\n", node->name);
6124     }
6125
6126     shash_destroy(&ofproto_shash);
6127     free(sorted_ofprotos);
6128
6129     unixctl_command_reply(conn, ds_cstr(&ds));
6130     ds_destroy(&ds);
6131 }
6132
6133 static void
6134 show_dp_rates(struct ds *ds, const char *heading,
6135               const struct avg_subfacet_rates *rates)
6136 {
6137     ds_put_format(ds, "%s add rate: %5.3f/min, del rate: %5.3f/min\n",
6138                   heading, rates->add_rate, rates->del_rate);
6139 }
6140
6141 static void
6142 dpif_show_backer(const struct dpif_backer *backer, struct ds *ds)
6143 {
6144     const struct shash_node **ofprotos;
6145     struct ofproto_dpif *ofproto;
6146     struct shash ofproto_shash;
6147     uint64_t n_hit, n_missed;
6148     long long int minutes;
6149     size_t i;
6150
6151     n_hit = n_missed = 0;
6152     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6153         if (ofproto->backer == backer) {
6154             n_missed += ofproto->n_missed;
6155             n_hit += ofproto->n_hit;
6156         }
6157     }
6158
6159     ds_put_format(ds, "%s: hit:%"PRIu64" missed:%"PRIu64"\n",
6160                   dpif_name(backer->dpif), n_hit, n_missed);
6161     ds_put_format(ds, "\tflows: cur: %zu, avg: %u, max: %u,"
6162                   " life span: %lldms\n", hmap_count(&backer->subfacets),
6163                   backer->avg_n_subfacet, backer->max_n_subfacet,
6164                   backer->avg_subfacet_life);
6165
6166     minutes = (time_msec() - backer->created) / (1000 * 60);
6167     if (minutes >= 60) {
6168         show_dp_rates(ds, "\thourly avg:", &backer->hourly);
6169     }
6170     if (minutes >= 60 * 24) {
6171         show_dp_rates(ds, "\tdaily avg:",  &backer->daily);
6172     }
6173     show_dp_rates(ds, "\toverall avg:",  &backer->lifetime);
6174
6175     shash_init(&ofproto_shash);
6176     ofprotos = get_ofprotos(&ofproto_shash);
6177     for (i = 0; i < shash_count(&ofproto_shash); i++) {
6178         struct ofproto_dpif *ofproto = ofprotos[i]->data;
6179         const struct shash_node **ports;
6180         size_t j;
6181
6182         if (ofproto->backer != backer) {
6183             continue;
6184         }
6185
6186         ds_put_format(ds, "\t%s: hit:%"PRIu64" missed:%"PRIu64"\n",
6187                       ofproto->up.name, ofproto->n_hit, ofproto->n_missed);
6188
6189         ports = shash_sort(&ofproto->up.port_by_name);
6190         for (j = 0; j < shash_count(&ofproto->up.port_by_name); j++) {
6191             const struct shash_node *node = ports[j];
6192             struct ofport *ofport = node->data;
6193             struct smap config;
6194             uint32_t odp_port;
6195
6196             ds_put_format(ds, "\t\t%s %u/", netdev_get_name(ofport->netdev),
6197                           ofport->ofp_port);
6198
6199             odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
6200             if (odp_port != OVSP_NONE) {
6201                 ds_put_format(ds, "%"PRIu32":", odp_port);
6202             } else {
6203                 ds_put_cstr(ds, "none:");
6204             }
6205
6206             ds_put_format(ds, " (%s", netdev_get_type(ofport->netdev));
6207
6208             smap_init(&config);
6209             if (!netdev_get_config(ofport->netdev, &config)) {
6210                 const struct smap_node **nodes;
6211                 size_t i;
6212
6213                 nodes = smap_sort(&config);
6214                 for (i = 0; i < smap_count(&config); i++) {
6215                     const struct smap_node *node = nodes[i];
6216                     ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
6217                                   node->key, node->value);
6218                 }
6219                 free(nodes);
6220             }
6221             smap_destroy(&config);
6222
6223             ds_put_char(ds, ')');
6224             ds_put_char(ds, '\n');
6225         }
6226         free(ports);
6227     }
6228     shash_destroy(&ofproto_shash);
6229     free(ofprotos);
6230 }
6231
6232 static void
6233 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
6234                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6235 {
6236     struct ds ds = DS_EMPTY_INITIALIZER;
6237     const struct shash_node **backers;
6238     int i;
6239
6240     backers = shash_sort(&all_dpif_backers);
6241     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
6242         dpif_show_backer(backers[i]->data, &ds);
6243     }
6244     free(backers);
6245
6246     unixctl_command_reply(conn, ds_cstr(&ds));
6247     ds_destroy(&ds);
6248 }
6249
6250 /* Dump the megaflow (facet) cache.  This is useful to check the
6251  * correctness of flow wildcarding, since the same mechanism is used for
6252  * both xlate caching and kernel wildcarding.
6253  *
6254  * It's important to note that in the output the flow description uses
6255  * OpenFlow (OFP) ports, but the actions use datapath (ODP) ports.
6256  *
6257  * This command is only needed for advanced debugging, so it's not
6258  * documented in the man page. */
6259 static void
6260 ofproto_unixctl_dpif_dump_megaflows(struct unixctl_conn *conn,
6261                                     int argc OVS_UNUSED, const char *argv[],
6262                                     void *aux OVS_UNUSED)
6263 {
6264     struct ds ds = DS_EMPTY_INITIALIZER;
6265     const struct ofproto_dpif *ofproto;
6266     long long int now = time_msec();
6267     struct cls_cursor cursor;
6268     struct facet *facet;
6269
6270     ofproto = ofproto_dpif_lookup(argv[1]);
6271     if (!ofproto) {
6272         unixctl_command_reply_error(conn, "no such bridge");
6273         return;
6274     }
6275
6276     cls_cursor_init(&cursor, &ofproto->facets, NULL);
6277     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
6278         cls_rule_format(&facet->cr, &ds);
6279         ds_put_cstr(&ds, ", ");
6280         ds_put_format(&ds, "n_subfacets:%zu, ", list_size(&facet->subfacets));
6281         ds_put_format(&ds, "used:%.3fs, ", (now - facet->used) / 1000.0);
6282         ds_put_cstr(&ds, "Datapath actions: ");
6283         if (facet->xout.slow) {
6284             uint64_t slow_path_stub[128 / 8];
6285             const struct nlattr *actions;
6286             size_t actions_len;
6287
6288             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
6289                               slow_path_stub, sizeof slow_path_stub,
6290                               &actions, &actions_len);
6291             format_odp_actions(&ds, actions, actions_len);
6292         } else {
6293             format_odp_actions(&ds, facet->xout.odp_actions.data,
6294                                facet->xout.odp_actions.size);
6295         }
6296         ds_put_cstr(&ds, "\n");
6297     }
6298
6299     ds_chomp(&ds, '\n');
6300     unixctl_command_reply(conn, ds_cstr(&ds));
6301     ds_destroy(&ds);
6302 }
6303
6304 static void
6305 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
6306                                 int argc OVS_UNUSED, const char *argv[],
6307                                 void *aux OVS_UNUSED)
6308 {
6309     struct ds ds = DS_EMPTY_INITIALIZER;
6310     const struct ofproto_dpif *ofproto;
6311     struct subfacet *subfacet;
6312
6313     ofproto = ofproto_dpif_lookup(argv[1]);
6314     if (!ofproto) {
6315         unixctl_command_reply_error(conn, "no such bridge");
6316         return;
6317     }
6318
6319     update_stats(ofproto->backer);
6320
6321     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->backer->subfacets) {
6322         struct facet *facet = subfacet->facet;
6323
6324         if (ofproto_dpif_cast(facet->rule->up.ofproto) != ofproto) {
6325             continue;
6326         }
6327
6328         odp_flow_key_format(subfacet->key, subfacet->key_len, &ds);
6329
6330         ds_put_format(&ds, ", packets:%"PRIu64", bytes:%"PRIu64", used:",
6331                       subfacet->dp_packet_count, subfacet->dp_byte_count);
6332         if (subfacet->used) {
6333             ds_put_format(&ds, "%.3fs",
6334                           (time_msec() - subfacet->used) / 1000.0);
6335         } else {
6336             ds_put_format(&ds, "never");
6337         }
6338         if (subfacet->facet->tcp_flags) {
6339             ds_put_cstr(&ds, ", flags:");
6340             packet_format_tcp_flags(&ds, subfacet->facet->tcp_flags);
6341         }
6342
6343         ds_put_cstr(&ds, ", actions:");
6344         if (facet->xout.slow) {
6345             uint64_t slow_path_stub[128 / 8];
6346             const struct nlattr *actions;
6347             size_t actions_len;
6348
6349             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
6350                               slow_path_stub, sizeof slow_path_stub,
6351                               &actions, &actions_len);
6352             format_odp_actions(&ds, actions, actions_len);
6353         } else {
6354             format_odp_actions(&ds, facet->xout.odp_actions.data,
6355                                facet->xout.odp_actions.size);
6356         }
6357         ds_put_char(&ds, '\n');
6358     }
6359
6360     unixctl_command_reply(conn, ds_cstr(&ds));
6361     ds_destroy(&ds);
6362 }
6363
6364 static void
6365 ofproto_unixctl_dpif_del_flows(struct unixctl_conn *conn,
6366                                int argc OVS_UNUSED, const char *argv[],
6367                                void *aux OVS_UNUSED)
6368 {
6369     struct ds ds = DS_EMPTY_INITIALIZER;
6370     struct ofproto_dpif *ofproto;
6371
6372     ofproto = ofproto_dpif_lookup(argv[1]);
6373     if (!ofproto) {
6374         unixctl_command_reply_error(conn, "no such bridge");
6375         return;
6376     }
6377
6378     flush(&ofproto->up);
6379
6380     unixctl_command_reply(conn, ds_cstr(&ds));
6381     ds_destroy(&ds);
6382 }
6383
6384 static void
6385 ofproto_dpif_unixctl_init(void)
6386 {
6387     static bool registered;
6388     if (registered) {
6389         return;
6390     }
6391     registered = true;
6392
6393     unixctl_command_register(
6394         "ofproto/trace",
6395         "[dp_name]|bridge odp_flow|br_flow [-generate|packet]",
6396         1, 3, ofproto_unixctl_trace, NULL);
6397     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
6398                              ofproto_unixctl_fdb_flush, NULL);
6399     unixctl_command_register("fdb/show", "bridge", 1, 1,
6400                              ofproto_unixctl_fdb_show, NULL);
6401     unixctl_command_register("ofproto/clog", "", 0, 0,
6402                              ofproto_dpif_clog, NULL);
6403     unixctl_command_register("ofproto/unclog", "", 0, 0,
6404                              ofproto_dpif_unclog, NULL);
6405     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
6406                              ofproto_dpif_self_check, NULL);
6407     unixctl_command_register("dpif/dump-dps", "", 0, 0,
6408                              ofproto_unixctl_dpif_dump_dps, NULL);
6409     unixctl_command_register("dpif/show", "", 0, 0, ofproto_unixctl_dpif_show,
6410                              NULL);
6411     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
6412                              ofproto_unixctl_dpif_dump_flows, NULL);
6413     unixctl_command_register("dpif/del-flows", "bridge", 1, 1,
6414                              ofproto_unixctl_dpif_del_flows, NULL);
6415     unixctl_command_register("dpif/dump-megaflows", "bridge", 1, 1,
6416                              ofproto_unixctl_dpif_dump_megaflows, NULL);
6417 }
6418 \f
6419 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6420  *
6421  * This is deprecated.  It is only for compatibility with broken device drivers
6422  * in old versions of Linux that do not properly support VLANs when VLAN
6423  * devices are not used.  When broken device drivers are no longer in
6424  * widespread use, we will delete these interfaces. */
6425
6426 static int
6427 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
6428 {
6429     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
6430     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
6431
6432     if (realdev_ofp_port == ofport->realdev_ofp_port
6433         && vid == ofport->vlandev_vid) {
6434         return 0;
6435     }
6436
6437     ofproto->backer->need_revalidate = REV_RECONFIGURE;
6438
6439     if (ofport->realdev_ofp_port) {
6440         vsp_remove(ofport);
6441     }
6442     if (realdev_ofp_port && ofport->bundle) {
6443         /* vlandevs are enslaved to their realdevs, so they are not allowed to
6444          * themselves be part of a bundle. */
6445         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
6446     }
6447
6448     ofport->realdev_ofp_port = realdev_ofp_port;
6449     ofport->vlandev_vid = vid;
6450
6451     if (realdev_ofp_port) {
6452         vsp_add(ofport, realdev_ofp_port, vid);
6453     }
6454
6455     return 0;
6456 }
6457
6458 static uint32_t
6459 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
6460 {
6461     return hash_2words(realdev_ofp_port, vid);
6462 }
6463
6464 /* Returns the OFP port number of the Linux VLAN device that corresponds to
6465  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
6466  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
6467  * 'vlan_tci' 9, it would return the port number of eth0.9.
6468  *
6469  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
6470  * function just returns its 'realdev_ofp_port' argument. */
6471 uint16_t
6472 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
6473                        uint16_t realdev_ofp_port, ovs_be16 vlan_tci)
6474 {
6475     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
6476         int vid = vlan_tci_to_vid(vlan_tci);
6477         const struct vlan_splinter *vsp;
6478
6479         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
6480                                  hash_realdev_vid(realdev_ofp_port, vid),
6481                                  &ofproto->realdev_vid_map) {
6482             if (vsp->realdev_ofp_port == realdev_ofp_port
6483                 && vsp->vid == vid) {
6484                 return vsp->vlandev_ofp_port;
6485             }
6486         }
6487     }
6488     return realdev_ofp_port;
6489 }
6490
6491 static struct vlan_splinter *
6492 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
6493 {
6494     struct vlan_splinter *vsp;
6495
6496     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
6497                              &ofproto->vlandev_map) {
6498         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
6499             return vsp;
6500         }
6501     }
6502
6503     return NULL;
6504 }
6505
6506 /* Returns the OpenFlow port number of the "real" device underlying the Linux
6507  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
6508  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
6509  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
6510  * eth0 and store 9 in '*vid'.
6511  *
6512  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
6513  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
6514  * always does.*/
6515 static uint16_t
6516 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
6517                        uint16_t vlandev_ofp_port, int *vid)
6518 {
6519     if (!hmap_is_empty(&ofproto->vlandev_map)) {
6520         const struct vlan_splinter *vsp;
6521
6522         vsp = vlandev_find(ofproto, vlandev_ofp_port);
6523         if (vsp) {
6524             if (vid) {
6525                 *vid = vsp->vid;
6526             }
6527             return vsp->realdev_ofp_port;
6528         }
6529     }
6530     return 0;
6531 }
6532
6533 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
6534  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
6535  * 'flow->in_port' to the "real" device backing the VLAN device, sets
6536  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
6537  * always the case unless VLAN splinters are enabled), returns false without
6538  * making any changes. */
6539 static bool
6540 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
6541 {
6542     uint16_t realdev;
6543     int vid;
6544
6545     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port, &vid);
6546     if (!realdev) {
6547         return false;
6548     }
6549
6550     /* Cause the flow to be processed as if it came in on the real device with
6551      * the VLAN device's VLAN ID. */
6552     flow->in_port = realdev;
6553     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
6554     return true;
6555 }
6556
6557 static void
6558 vsp_remove(struct ofport_dpif *port)
6559 {
6560     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6561     struct vlan_splinter *vsp;
6562
6563     vsp = vlandev_find(ofproto, port->up.ofp_port);
6564     if (vsp) {
6565         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
6566         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
6567         free(vsp);
6568
6569         port->realdev_ofp_port = 0;
6570     } else {
6571         VLOG_ERR("missing vlan device record");
6572     }
6573 }
6574
6575 static void
6576 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
6577 {
6578     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6579
6580     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
6581         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
6582             == realdev_ofp_port)) {
6583         struct vlan_splinter *vsp;
6584
6585         vsp = xmalloc(sizeof *vsp);
6586         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
6587                     hash_int(port->up.ofp_port, 0));
6588         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
6589                     hash_realdev_vid(realdev_ofp_port, vid));
6590         vsp->realdev_ofp_port = realdev_ofp_port;
6591         vsp->vlandev_ofp_port = port->up.ofp_port;
6592         vsp->vid = vid;
6593
6594         port->realdev_ofp_port = realdev_ofp_port;
6595     } else {
6596         VLOG_ERR("duplicate vlan device record");
6597     }
6598 }
6599
6600 uint32_t
6601 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
6602 {
6603     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
6604     return ofport ? ofport->odp_port : OVSP_NONE;
6605 }
6606
6607 static struct ofport_dpif *
6608 odp_port_to_ofport(const struct dpif_backer *backer, uint32_t odp_port)
6609 {
6610     struct ofport_dpif *port;
6611
6612     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node,
6613                              hash_int(odp_port, 0),
6614                              &backer->odp_to_ofport_map) {
6615         if (port->odp_port == odp_port) {
6616             return port;
6617         }
6618     }
6619
6620     return NULL;
6621 }
6622
6623 static uint16_t
6624 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
6625 {
6626     struct ofport_dpif *port;
6627
6628     port = odp_port_to_ofport(ofproto->backer, odp_port);
6629     if (port && &ofproto->up == port->up.ofproto) {
6630         return port->up.ofp_port;
6631     } else {
6632         return OFPP_NONE;
6633     }
6634 }
6635
6636 /* Compute exponentially weighted moving average, adding 'new' as the newest,
6637  * most heavily weighted element.  'base' designates the rate of decay: after
6638  * 'base' further updates, 'new''s weight in the EWMA decays to about 1/e
6639  * (about .37). */
6640 static void
6641 exp_mavg(double *avg, int base, double new)
6642 {
6643     *avg = (*avg * (base - 1) + new) / base;
6644 }
6645
6646 static void
6647 update_moving_averages(struct dpif_backer *backer)
6648 {
6649     const int min_ms = 60 * 1000; /* milliseconds in one minute. */
6650     long long int minutes = (time_msec() - backer->created) / min_ms;
6651
6652     if (minutes > 0) {
6653         backer->lifetime.add_rate = (double) backer->total_subfacet_add_count
6654             / minutes;
6655         backer->lifetime.del_rate = (double) backer->total_subfacet_del_count
6656             / minutes;
6657     } else {
6658         backer->lifetime.add_rate = 0.0;
6659         backer->lifetime.del_rate = 0.0;
6660     }
6661
6662     /* Update hourly averages on the minute boundaries. */
6663     if (time_msec() - backer->last_minute >= min_ms) {
6664         exp_mavg(&backer->hourly.add_rate, 60, backer->subfacet_add_count);
6665         exp_mavg(&backer->hourly.del_rate, 60, backer->subfacet_del_count);
6666
6667         /* Update daily averages on the hour boundaries. */
6668         if ((backer->last_minute - backer->created) / min_ms % 60 == 59) {
6669             exp_mavg(&backer->daily.add_rate, 24, backer->hourly.add_rate);
6670             exp_mavg(&backer->daily.del_rate, 24, backer->hourly.del_rate);
6671         }
6672
6673         backer->total_subfacet_add_count += backer->subfacet_add_count;
6674         backer->total_subfacet_del_count += backer->subfacet_del_count;
6675         backer->subfacet_add_count = 0;
6676         backer->subfacet_del_count = 0;
6677         backer->last_minute += min_ms;
6678     }
6679 }
6680
6681 const struct ofproto_class ofproto_dpif_class = {
6682     init,
6683     enumerate_types,
6684     enumerate_names,
6685     del,
6686     port_open_type,
6687     type_run,
6688     type_run_fast,
6689     type_wait,
6690     alloc,
6691     construct,
6692     destruct,
6693     dealloc,
6694     run,
6695     run_fast,
6696     wait,
6697     get_memory_usage,
6698     flush,
6699     get_features,
6700     get_tables,
6701     port_alloc,
6702     port_construct,
6703     port_destruct,
6704     port_dealloc,
6705     port_modified,
6706     port_reconfigured,
6707     port_query_by_name,
6708     port_add,
6709     port_del,
6710     port_get_stats,
6711     port_dump_start,
6712     port_dump_next,
6713     port_dump_done,
6714     port_poll,
6715     port_poll_wait,
6716     port_is_lacp_current,
6717     NULL,                       /* rule_choose_table */
6718     rule_alloc,
6719     rule_construct,
6720     rule_destruct,
6721     rule_dealloc,
6722     rule_get_stats,
6723     rule_execute,
6724     rule_modify_actions,
6725     set_frag_handling,
6726     packet_out,
6727     set_netflow,
6728     get_netflow_ids,
6729     set_sflow,
6730     set_ipfix,
6731     set_cfm,
6732     get_cfm_status,
6733     set_bfd,
6734     get_bfd_status,
6735     set_stp,
6736     get_stp_status,
6737     set_stp_port,
6738     get_stp_port_status,
6739     set_queues,
6740     bundle_set,
6741     bundle_remove,
6742     mirror_set,
6743     mirror_get_stats,
6744     set_flood_vlans,
6745     is_mirror_output_bundle,
6746     forward_bpdu_changed,
6747     set_mac_table_config,
6748     set_realdev,
6749 };