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