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