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