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