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