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