ofproto-dpif-upcall: Document revalidator cycle.
[cascardo/ovs.git] / ofproto / ofproto-dpif-upcall.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.  */
14
15 #include <config.h>
16 #include "ofproto-dpif-upcall.h"
17
18 #include <errno.h>
19 #include <stdbool.h>
20 #include <inttypes.h>
21
22 #include "connmgr.h"
23 #include "coverage.h"
24 #include "cmap.h"
25 #include "dpif.h"
26 #include "dynamic-string.h"
27 #include "fail-open.h"
28 #include "guarded-list.h"
29 #include "latch.h"
30 #include "list.h"
31 #include "netlink.h"
32 #include "ofpbuf.h"
33 #include "ofproto-dpif-ipfix.h"
34 #include "ofproto-dpif-sflow.h"
35 #include "ofproto-dpif-xlate.h"
36 #include "ovs-rcu.h"
37 #include "packets.h"
38 #include "poll-loop.h"
39 #include "seq.h"
40 #include "unixctl.h"
41 #include "openvswitch/vlog.h"
42
43 #define MAX_QUEUE_LENGTH 512
44 #define UPCALL_MAX_BATCH 64
45 #define REVALIDATE_MAX_BATCH 50
46
47 VLOG_DEFINE_THIS_MODULE(ofproto_dpif_upcall);
48
49 COVERAGE_DEFINE(dumped_duplicate_flow);
50 COVERAGE_DEFINE(dumped_new_flow);
51 COVERAGE_DEFINE(handler_duplicate_upcall);
52 COVERAGE_DEFINE(upcall_ukey_contention);
53 COVERAGE_DEFINE(revalidate_missed_dp_flow);
54
55 /* A thread that reads upcalls from dpif, forwards each upcall's packet,
56  * and possibly sets up a kernel flow as a cache. */
57 struct handler {
58     struct udpif *udpif;               /* Parent udpif. */
59     pthread_t thread;                  /* Thread ID. */
60     uint32_t handler_id;               /* Handler id. */
61 };
62
63 /* In the absence of a multiple-writer multiple-reader datastructure for
64  * storing udpif_keys ("ukeys"), we use a large number of cmaps, each with its
65  * own lock for writing. */
66 #define N_UMAPS 512 /* per udpif. */
67 struct umap {
68     struct ovs_mutex mutex;            /* Take for writing to the following. */
69     struct cmap cmap;                  /* Datapath flow keys. */
70 };
71
72 /* A thread that processes datapath flows, updates OpenFlow statistics, and
73  * updates or removes them if necessary.
74  *
75  * Revalidator threads operate in two phases: "dump" and "sweep". In between
76  * each phase, all revalidators sync up so that all revalidator threads are
77  * either in one phase or the other, but not a combination.
78  *
79  *     During the dump phase, revalidators fetch flows from the datapath and
80  *     attribute the statistics to OpenFlow rules. Each datapath flow has a
81  *     corresponding ukey which caches the most recently seen statistics. If
82  *     a flow needs to be deleted (for example, because it is unused over a
83  *     period of time), revalidator threads may delete the flow during the
84  *     dump phase. The datapath is not guaranteed to reliably dump all flows
85  *     from the datapath, and there is no mapping between datapath flows to
86  *     revalidators, so a particular flow may be handled by zero or more
87  *     revalidators during a single dump phase. To avoid duplicate attribution
88  *     of statistics, ukeys are never deleted during this phase.
89  *
90  *     During the sweep phase, each revalidator takes ownership of a different
91  *     slice of umaps and sweeps through all ukeys in those umaps to figure out
92  *     whether they need to be deleted. During this phase, revalidators may
93  *     fetch individual flows which were not dumped during the dump phase to
94  *     validate them and attribute statistics.
95  */
96 struct revalidator {
97     struct udpif *udpif;               /* Parent udpif. */
98     pthread_t thread;                  /* Thread ID. */
99     unsigned int id;                   /* ovsthread_id_self(). */
100 };
101
102 /* An upcall handler for ofproto_dpif.
103  *
104  * udpif keeps records of two kind of logically separate units:
105  *
106  * upcall handling
107  * ---------------
108  *
109  *    - An array of 'struct handler's for upcall handling and flow
110  *      installation.
111  *
112  * flow revalidation
113  * -----------------
114  *
115  *    - Revalidation threads which read the datapath flow table and maintains
116  *      them.
117  */
118 struct udpif {
119     struct ovs_list list_node;         /* In all_udpifs list. */
120
121     struct dpif *dpif;                 /* Datapath handle. */
122     struct dpif_backer *backer;        /* Opaque dpif_backer pointer. */
123
124     struct handler *handlers;          /* Upcall handlers. */
125     size_t n_handlers;
126
127     struct revalidator *revalidators;  /* Flow revalidators. */
128     size_t n_revalidators;
129
130     struct latch exit_latch;           /* Tells child threads to exit. */
131
132     /* Revalidation. */
133     struct seq *reval_seq;             /* Incremented to force revalidation. */
134     bool reval_exit;                   /* Set by leader on 'exit_latch. */
135     struct ovs_barrier reval_barrier;  /* Barrier used by revalidators. */
136     struct dpif_flow_dump *dump;       /* DPIF flow dump state. */
137     long long int dump_duration;       /* Duration of the last flow dump. */
138     struct seq *dump_seq;              /* Increments each dump iteration. */
139     atomic_bool enable_ufid;           /* If true, skip dumping flow attrs. */
140
141     /* These variables provide a mechanism for the main thread to pause
142      * all revalidation without having to completely shut the threads down.
143      * 'pause_latch' is shared between the main thread and the lead
144      * revalidator thread, so when it is desirable to halt revalidation, the
145      * main thread will set the latch. 'pause' and 'pause_barrier' are shared
146      * by revalidator threads. The lead revalidator will set 'pause' when it
147      * observes the latch has been set, and this will cause all revalidator
148      * threads to wait on 'pause_barrier' at the beginning of the next
149      * revalidation round. */
150     bool pause;                        /* Set by leader on 'pause_latch. */
151     struct latch pause_latch;          /* Set to force revalidators pause. */
152     struct ovs_barrier pause_barrier;  /* Barrier used to pause all */
153                                        /* revalidators by main thread. */
154
155     /* There are 'N_UMAPS' maps containing 'struct udpif_key' elements.
156      *
157      * During the flow dump phase, revalidators insert into these with a random
158      * distribution. During the garbage collection phase, each revalidator
159      * takes care of garbage collecting a slice of these maps. */
160     struct umap *ukeys;
161
162     /* Datapath flow statistics. */
163     unsigned int max_n_flows;
164     unsigned int avg_n_flows;
165
166     /* Following fields are accessed and modified by different threads. */
167     atomic_uint flow_limit;            /* Datapath flow hard limit. */
168
169     /* n_flows_mutex prevents multiple threads updating these concurrently. */
170     atomic_uint n_flows;               /* Number of flows in the datapath. */
171     atomic_llong n_flows_timestamp;    /* Last time n_flows was updated. */
172     struct ovs_mutex n_flows_mutex;
173
174     /* Following fields are accessed and modified only from the main thread. */
175     struct unixctl_conn **conns;       /* Connections waiting on dump_seq. */
176     uint64_t conn_seq;                 /* Corresponds to 'dump_seq' when
177                                           conns[n_conns-1] was stored. */
178     size_t n_conns;                    /* Number of connections waiting. */
179 };
180
181 enum upcall_type {
182     BAD_UPCALL,                 /* Some kind of bug somewhere. */
183     MISS_UPCALL,                /* A flow miss.  */
184     SFLOW_UPCALL,               /* sFlow sample. */
185     FLOW_SAMPLE_UPCALL,         /* Per-flow sampling. */
186     IPFIX_UPCALL                /* Per-bridge sampling. */
187 };
188
189 enum reval_result {
190     UKEY_KEEP,
191     UKEY_DELETE,
192     UKEY_MODIFY
193 };
194
195 struct upcall {
196     struct ofproto_dpif *ofproto;  /* Parent ofproto. */
197     const struct recirc_id_node *recirc; /* Recirculation context. */
198     bool have_recirc_ref;                /* Reference held on recirc ctx? */
199
200     /* The flow and packet are only required to be constant when using
201      * dpif-netdev.  If a modification is absolutely necessary, a const cast
202      * may be used with other datapaths. */
203     const struct flow *flow;       /* Parsed representation of the packet. */
204     const ovs_u128 *ufid;          /* Unique identifier for 'flow'. */
205     unsigned pmd_id;               /* Datapath poll mode driver id. */
206     const struct dp_packet *packet;   /* Packet associated with this upcall. */
207     ofp_port_t in_port;            /* OpenFlow in port, or OFPP_NONE. */
208     uint16_t mru;                  /* If !0, Maximum receive unit of
209                                       fragmented IP packet */
210
211     enum dpif_upcall_type type;    /* Datapath type of the upcall. */
212     const struct nlattr *userdata; /* Userdata for DPIF_UC_ACTION Upcalls. */
213     const struct nlattr *actions;  /* Flow actions in DPIF_UC_ACTION Upcalls. */
214
215     bool xout_initialized;         /* True if 'xout' must be uninitialized. */
216     struct xlate_out xout;         /* Result of xlate_actions(). */
217     struct ofpbuf odp_actions;     /* Datapath actions from xlate_actions(). */
218     struct flow_wildcards wc;      /* Dependencies that megaflow must match. */
219     struct ofpbuf put_actions;     /* Actions 'put' in the fastpath. */
220
221     struct dpif_ipfix *ipfix;      /* IPFIX pointer or NULL. */
222     struct dpif_sflow *sflow;      /* SFlow pointer or NULL. */
223
224     bool vsp_adjusted;             /* 'packet' and 'flow' were adjusted for
225                                       VLAN splinters if true. */
226
227     struct udpif_key *ukey;        /* Revalidator flow cache. */
228     bool ukey_persists;            /* Set true to keep 'ukey' beyond the
229                                       lifetime of this upcall. */
230
231     uint64_t dump_seq;             /* udpif->dump_seq at translation time. */
232     uint64_t reval_seq;            /* udpif->reval_seq at translation time. */
233
234     /* Not used by the upcall callback interface. */
235     const struct nlattr *key;      /* Datapath flow key. */
236     size_t key_len;                /* Datapath flow key length. */
237     const struct nlattr *out_tun_key;  /* Datapath output tunnel key. */
238
239     uint64_t odp_actions_stub[1024 / 8]; /* Stub for odp_actions. */
240 };
241
242 /* 'udpif_key's are responsible for tracking the little bit of state udpif
243  * needs to do flow expiration which can't be pulled directly from the
244  * datapath.  They may be created by any handler or revalidator thread at any
245  * time, and read by any revalidator during the dump phase. They are however
246  * each owned by a single revalidator which takes care of destroying them
247  * during the garbage-collection phase.
248  *
249  * The mutex within the ukey protects some members of the ukey. The ukey
250  * itself is protected by RCU and is held within a umap in the parent udpif.
251  * Adding or removing a ukey from a umap is only safe when holding the
252  * corresponding umap lock. */
253 struct udpif_key {
254     struct cmap_node cmap_node;     /* In parent revalidator 'ukeys' map. */
255
256     /* These elements are read only once created, and therefore aren't
257      * protected by a mutex. */
258     const struct nlattr *key;      /* Datapath flow key. */
259     size_t key_len;                /* Length of 'key'. */
260     const struct nlattr *mask;     /* Datapath flow mask. */
261     size_t mask_len;               /* Length of 'mask'. */
262     ovs_u128 ufid;                 /* Unique flow identifier. */
263     bool ufid_present;             /* True if 'ufid' is in datapath. */
264     uint32_t hash;                 /* Pre-computed hash for 'key'. */
265     unsigned pmd_id;               /* Datapath poll mode driver id. */
266
267     struct ovs_mutex mutex;                   /* Guards the following. */
268     struct dpif_flow_stats stats OVS_GUARDED; /* Last known stats.*/
269     long long int created OVS_GUARDED;        /* Estimate of creation time. */
270     uint64_t dump_seq OVS_GUARDED;            /* Tracks udpif->dump_seq. */
271     uint64_t reval_seq OVS_GUARDED;           /* Tracks udpif->reval_seq. */
272     bool flow_exists OVS_GUARDED;             /* Ensures flows are only deleted
273                                                  once. */
274     /* Datapath flow actions as nlattrs.  Protected by RCU.  Read with
275      * ukey_get_actions(), and write with ukey_set_actions(). */
276     OVSRCU_TYPE(struct ofpbuf *) actions;
277
278     struct xlate_cache *xcache OVS_GUARDED;   /* Cache for xlate entries that
279                                                * are affected by this ukey.
280                                                * Used for stats and learning.*/
281     union {
282         struct odputil_keybuf buf;
283         struct nlattr nla;
284     } keybuf, maskbuf;
285
286     uint32_t key_recirc_id;   /* Non-zero if reference is held by the ukey. */
287     struct recirc_refs recircs;  /* Action recirc IDs with references held. */
288 };
289
290 /* Datapath operation with optional ukey attached. */
291 struct ukey_op {
292     struct udpif_key *ukey;
293     struct dpif_flow_stats stats; /* Stats for 'op'. */
294     struct dpif_op dop;           /* Flow operation. */
295 };
296
297 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
298 static struct ovs_list all_udpifs = OVS_LIST_INITIALIZER(&all_udpifs);
299
300 static size_t recv_upcalls(struct handler *);
301 static int process_upcall(struct udpif *, struct upcall *,
302                           struct ofpbuf *odp_actions, struct flow_wildcards *);
303 static void handle_upcalls(struct udpif *, struct upcall *, size_t n_upcalls);
304 static void udpif_stop_threads(struct udpif *);
305 static void udpif_start_threads(struct udpif *, size_t n_handlers,
306                                 size_t n_revalidators);
307 static void udpif_pause_revalidators(struct udpif *);
308 static void udpif_resume_revalidators(struct udpif *);
309 static void *udpif_upcall_handler(void *);
310 static void *udpif_revalidator(void *);
311 static unsigned long udpif_get_n_flows(struct udpif *);
312 static void revalidate(struct revalidator *);
313 static void revalidator_pause(struct revalidator *);
314 static void revalidator_sweep(struct revalidator *);
315 static void revalidator_purge(struct revalidator *);
316 static void upcall_unixctl_show(struct unixctl_conn *conn, int argc,
317                                 const char *argv[], void *aux);
318 static void upcall_unixctl_disable_megaflows(struct unixctl_conn *, int argc,
319                                              const char *argv[], void *aux);
320 static void upcall_unixctl_enable_megaflows(struct unixctl_conn *, int argc,
321                                             const char *argv[], void *aux);
322 static void upcall_unixctl_disable_ufid(struct unixctl_conn *, int argc,
323                                               const char *argv[], void *aux);
324 static void upcall_unixctl_enable_ufid(struct unixctl_conn *, int argc,
325                                              const char *argv[], void *aux);
326 static void upcall_unixctl_set_flow_limit(struct unixctl_conn *conn, int argc,
327                                             const char *argv[], void *aux);
328 static void upcall_unixctl_dump_wait(struct unixctl_conn *conn, int argc,
329                                      const char *argv[], void *aux);
330 static void upcall_unixctl_purge(struct unixctl_conn *conn, int argc,
331                                  const char *argv[], void *aux);
332
333 static struct udpif_key *ukey_create_from_upcall(struct upcall *,
334                                                  struct flow_wildcards *);
335 static int ukey_create_from_dpif_flow(const struct udpif *,
336                                       const struct dpif_flow *,
337                                       struct udpif_key **);
338 static void ukey_get_actions(struct udpif_key *, const struct nlattr **actions,
339                              size_t *size);
340 static bool ukey_install_start(struct udpif *, struct udpif_key *ukey);
341 static bool ukey_install_finish(struct udpif_key *ukey, int error);
342 static bool ukey_install(struct udpif *udpif, struct udpif_key *ukey);
343 static struct udpif_key *ukey_lookup(struct udpif *udpif,
344                                      const ovs_u128 *ufid);
345 static int ukey_acquire(struct udpif *, const struct dpif_flow *,
346                         struct udpif_key **result, int *error);
347 static void ukey_delete__(struct udpif_key *);
348 static void ukey_delete(struct umap *, struct udpif_key *);
349 static enum upcall_type classify_upcall(enum dpif_upcall_type type,
350                                         const struct nlattr *userdata);
351
352 static int upcall_receive(struct upcall *, const struct dpif_backer *,
353                           const struct dp_packet *packet, enum dpif_upcall_type,
354                           const struct nlattr *userdata, const struct flow *,
355                           const unsigned int mru,
356                           const ovs_u128 *ufid, const unsigned pmd_id);
357 static void upcall_uninit(struct upcall *);
358
359 static upcall_callback upcall_cb;
360 static dp_purge_callback dp_purge_cb;
361
362 static atomic_bool enable_megaflows = ATOMIC_VAR_INIT(true);
363 static atomic_bool enable_ufid = ATOMIC_VAR_INIT(true);
364
365 void
366 udpif_init(void)
367 {
368     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
369     if (ovsthread_once_start(&once)) {
370         unixctl_command_register("upcall/show", "", 0, 0, upcall_unixctl_show,
371                                  NULL);
372         unixctl_command_register("upcall/disable-megaflows", "", 0, 0,
373                                  upcall_unixctl_disable_megaflows, NULL);
374         unixctl_command_register("upcall/enable-megaflows", "", 0, 0,
375                                  upcall_unixctl_enable_megaflows, NULL);
376         unixctl_command_register("upcall/disable-ufid", "", 0, 0,
377                                  upcall_unixctl_disable_ufid, NULL);
378         unixctl_command_register("upcall/enable-ufid", "", 0, 0,
379                                  upcall_unixctl_enable_ufid, NULL);
380         unixctl_command_register("upcall/set-flow-limit", "", 1, 1,
381                                  upcall_unixctl_set_flow_limit, NULL);
382         unixctl_command_register("revalidator/wait", "", 0, 0,
383                                  upcall_unixctl_dump_wait, NULL);
384         unixctl_command_register("revalidator/purge", "", 0, 0,
385                                  upcall_unixctl_purge, NULL);
386         ovsthread_once_done(&once);
387     }
388 }
389
390 struct udpif *
391 udpif_create(struct dpif_backer *backer, struct dpif *dpif)
392 {
393     struct udpif *udpif = xzalloc(sizeof *udpif);
394
395     udpif->dpif = dpif;
396     udpif->backer = backer;
397     atomic_init(&udpif->flow_limit, MIN(ofproto_flow_limit, 10000));
398     udpif->reval_seq = seq_create();
399     udpif->dump_seq = seq_create();
400     latch_init(&udpif->exit_latch);
401     latch_init(&udpif->pause_latch);
402     list_push_back(&all_udpifs, &udpif->list_node);
403     atomic_init(&udpif->enable_ufid, false);
404     atomic_init(&udpif->n_flows, 0);
405     atomic_init(&udpif->n_flows_timestamp, LLONG_MIN);
406     ovs_mutex_init(&udpif->n_flows_mutex);
407     udpif->ukeys = xmalloc(N_UMAPS * sizeof *udpif->ukeys);
408     for (int i = 0; i < N_UMAPS; i++) {
409         cmap_init(&udpif->ukeys[i].cmap);
410         ovs_mutex_init(&udpif->ukeys[i].mutex);
411     }
412
413     dpif_register_upcall_cb(dpif, upcall_cb, udpif);
414     dpif_register_dp_purge_cb(dpif, dp_purge_cb, udpif);
415
416     return udpif;
417 }
418
419 void
420 udpif_run(struct udpif *udpif)
421 {
422     if (udpif->conns && udpif->conn_seq != seq_read(udpif->dump_seq)) {
423         int i;
424
425         for (i = 0; i < udpif->n_conns; i++) {
426             unixctl_command_reply(udpif->conns[i], NULL);
427         }
428         free(udpif->conns);
429         udpif->conns = NULL;
430         udpif->n_conns = 0;
431     }
432 }
433
434 void
435 udpif_destroy(struct udpif *udpif)
436 {
437     udpif_stop_threads(udpif);
438
439     for (int i = 0; i < N_UMAPS; i++) {
440         cmap_destroy(&udpif->ukeys[i].cmap);
441         ovs_mutex_destroy(&udpif->ukeys[i].mutex);
442     }
443     free(udpif->ukeys);
444     udpif->ukeys = NULL;
445
446     list_remove(&udpif->list_node);
447     latch_destroy(&udpif->exit_latch);
448     latch_destroy(&udpif->pause_latch);
449     seq_destroy(udpif->reval_seq);
450     seq_destroy(udpif->dump_seq);
451     ovs_mutex_destroy(&udpif->n_flows_mutex);
452     free(udpif);
453 }
454
455 /* Stops the handler and revalidator threads, must be enclosed in
456  * ovsrcu quiescent state unless when destroying udpif. */
457 static void
458 udpif_stop_threads(struct udpif *udpif)
459 {
460     if (udpif && (udpif->n_handlers != 0 || udpif->n_revalidators != 0)) {
461         size_t i;
462
463         latch_set(&udpif->exit_latch);
464
465         for (i = 0; i < udpif->n_handlers; i++) {
466             struct handler *handler = &udpif->handlers[i];
467
468             xpthread_join(handler->thread, NULL);
469         }
470
471         for (i = 0; i < udpif->n_revalidators; i++) {
472             xpthread_join(udpif->revalidators[i].thread, NULL);
473         }
474
475         dpif_disable_upcall(udpif->dpif);
476
477         for (i = 0; i < udpif->n_revalidators; i++) {
478             struct revalidator *revalidator = &udpif->revalidators[i];
479
480             /* Delete ukeys, and delete all flows from the datapath to prevent
481              * double-counting stats. */
482             revalidator_purge(revalidator);
483         }
484
485         latch_poll(&udpif->exit_latch);
486
487         ovs_barrier_destroy(&udpif->reval_barrier);
488         ovs_barrier_destroy(&udpif->pause_barrier);
489
490         free(udpif->revalidators);
491         udpif->revalidators = NULL;
492         udpif->n_revalidators = 0;
493
494         free(udpif->handlers);
495         udpif->handlers = NULL;
496         udpif->n_handlers = 0;
497     }
498 }
499
500 /* Starts the handler and revalidator threads, must be enclosed in
501  * ovsrcu quiescent state. */
502 static void
503 udpif_start_threads(struct udpif *udpif, size_t n_handlers,
504                     size_t n_revalidators)
505 {
506     if (udpif && n_handlers && n_revalidators) {
507         size_t i;
508         bool enable_ufid;
509
510         udpif->n_handlers = n_handlers;
511         udpif->n_revalidators = n_revalidators;
512
513         udpif->handlers = xzalloc(udpif->n_handlers * sizeof *udpif->handlers);
514         for (i = 0; i < udpif->n_handlers; i++) {
515             struct handler *handler = &udpif->handlers[i];
516
517             handler->udpif = udpif;
518             handler->handler_id = i;
519             handler->thread = ovs_thread_create(
520                 "handler", udpif_upcall_handler, handler);
521         }
522
523         enable_ufid = ofproto_dpif_get_enable_ufid(udpif->backer);
524         atomic_init(&udpif->enable_ufid, enable_ufid);
525         dpif_enable_upcall(udpif->dpif);
526
527         ovs_barrier_init(&udpif->reval_barrier, udpif->n_revalidators);
528         ovs_barrier_init(&udpif->pause_barrier, udpif->n_revalidators + 1);
529         udpif->reval_exit = false;
530         udpif->pause = false;
531         udpif->revalidators = xzalloc(udpif->n_revalidators
532                                       * sizeof *udpif->revalidators);
533         for (i = 0; i < udpif->n_revalidators; i++) {
534             struct revalidator *revalidator = &udpif->revalidators[i];
535
536             revalidator->udpif = udpif;
537             revalidator->thread = ovs_thread_create(
538                 "revalidator", udpif_revalidator, revalidator);
539         }
540     }
541 }
542
543 /* Pauses all revalidators.  Should only be called by the main thread.
544  * When function returns, all revalidators are paused and will proceed
545  * only after udpif_resume_revalidators() is called. */
546 static void
547 udpif_pause_revalidators(struct udpif *udpif)
548 {
549     if (ofproto_dpif_backer_enabled(udpif->backer)) {
550         latch_set(&udpif->pause_latch);
551         ovs_barrier_block(&udpif->pause_barrier);
552     }
553 }
554
555 /* Resumes the pausing of revalidators.  Should only be called by the
556  * main thread. */
557 static void
558 udpif_resume_revalidators(struct udpif *udpif)
559 {
560     if (ofproto_dpif_backer_enabled(udpif->backer)) {
561         latch_poll(&udpif->pause_latch);
562         ovs_barrier_block(&udpif->pause_barrier);
563     }
564 }
565
566 /* Tells 'udpif' how many threads it should use to handle upcalls.
567  * 'n_handlers' and 'n_revalidators' can never be zero.  'udpif''s
568  * datapath handle must have packet reception enabled before starting
569  * threads. */
570 void
571 udpif_set_threads(struct udpif *udpif, size_t n_handlers,
572                   size_t n_revalidators)
573 {
574     ovs_assert(udpif);
575     ovs_assert(n_handlers && n_revalidators);
576
577     ovsrcu_quiesce_start();
578     if (udpif->n_handlers != n_handlers
579         || udpif->n_revalidators != n_revalidators) {
580         udpif_stop_threads(udpif);
581     }
582
583     if (!udpif->handlers && !udpif->revalidators) {
584         int error;
585
586         error = dpif_handlers_set(udpif->dpif, n_handlers);
587         if (error) {
588             VLOG_ERR("failed to configure handlers in dpif %s: %s",
589                      dpif_name(udpif->dpif), ovs_strerror(error));
590             return;
591         }
592
593         udpif_start_threads(udpif, n_handlers, n_revalidators);
594     }
595     ovsrcu_quiesce_end();
596 }
597
598 /* Waits for all ongoing upcall translations to complete.  This ensures that
599  * there are no transient references to any removed ofprotos (or other
600  * objects).  In particular, this should be called after an ofproto is removed
601  * (e.g. via xlate_remove_ofproto()) but before it is destroyed. */
602 void
603 udpif_synchronize(struct udpif *udpif)
604 {
605     /* This is stronger than necessary.  It would be sufficient to ensure
606      * (somehow) that each handler and revalidator thread had passed through
607      * its main loop once. */
608     size_t n_handlers = udpif->n_handlers;
609     size_t n_revalidators = udpif->n_revalidators;
610
611     ovsrcu_quiesce_start();
612     udpif_stop_threads(udpif);
613     udpif_start_threads(udpif, n_handlers, n_revalidators);
614     ovsrcu_quiesce_end();
615 }
616
617 /* Notifies 'udpif' that something changed which may render previous
618  * xlate_actions() results invalid. */
619 void
620 udpif_revalidate(struct udpif *udpif)
621 {
622     seq_change(udpif->reval_seq);
623 }
624
625 /* Returns a seq which increments every time 'udpif' pulls stats from the
626  * datapath.  Callers can use this to get a sense of when might be a good time
627  * to do periodic work which relies on relatively up to date statistics. */
628 struct seq *
629 udpif_dump_seq(struct udpif *udpif)
630 {
631     return udpif->dump_seq;
632 }
633
634 void
635 udpif_get_memory_usage(struct udpif *udpif, struct simap *usage)
636 {
637     size_t i;
638
639     simap_increase(usage, "handlers", udpif->n_handlers);
640
641     simap_increase(usage, "revalidators", udpif->n_revalidators);
642     for (i = 0; i < N_UMAPS; i++) {
643         simap_increase(usage, "udpif keys", cmap_count(&udpif->ukeys[i].cmap));
644     }
645 }
646
647 /* Remove flows from a single datapath. */
648 void
649 udpif_flush(struct udpif *udpif)
650 {
651     size_t n_handlers, n_revalidators;
652
653     n_handlers = udpif->n_handlers;
654     n_revalidators = udpif->n_revalidators;
655
656     ovsrcu_quiesce_start();
657
658     udpif_stop_threads(udpif);
659     dpif_flow_flush(udpif->dpif);
660     udpif_start_threads(udpif, n_handlers, n_revalidators);
661
662     ovsrcu_quiesce_end();
663 }
664
665 /* Removes all flows from all datapaths. */
666 static void
667 udpif_flush_all_datapaths(void)
668 {
669     struct udpif *udpif;
670
671     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
672         udpif_flush(udpif);
673     }
674 }
675
676 static bool
677 udpif_use_ufid(struct udpif *udpif)
678 {
679     bool enable;
680
681     atomic_read_relaxed(&enable_ufid, &enable);
682     return enable && ofproto_dpif_get_enable_ufid(udpif->backer);
683 }
684
685 \f
686 static unsigned long
687 udpif_get_n_flows(struct udpif *udpif)
688 {
689     long long int time, now;
690     unsigned long flow_count;
691
692     now = time_msec();
693     atomic_read_relaxed(&udpif->n_flows_timestamp, &time);
694     if (time < now - 100 && !ovs_mutex_trylock(&udpif->n_flows_mutex)) {
695         struct dpif_dp_stats stats;
696
697         atomic_store_relaxed(&udpif->n_flows_timestamp, now);
698         dpif_get_dp_stats(udpif->dpif, &stats);
699         flow_count = stats.n_flows;
700         atomic_store_relaxed(&udpif->n_flows, flow_count);
701         ovs_mutex_unlock(&udpif->n_flows_mutex);
702     } else {
703         atomic_read_relaxed(&udpif->n_flows, &flow_count);
704     }
705     return flow_count;
706 }
707
708 /* The upcall handler thread tries to read a batch of UPCALL_MAX_BATCH
709  * upcalls from dpif, processes the batch and installs corresponding flows
710  * in dpif. */
711 static void *
712 udpif_upcall_handler(void *arg)
713 {
714     struct handler *handler = arg;
715     struct udpif *udpif = handler->udpif;
716
717     while (!latch_is_set(&handler->udpif->exit_latch)) {
718         if (recv_upcalls(handler)) {
719             poll_immediate_wake();
720         } else {
721             dpif_recv_wait(udpif->dpif, handler->handler_id);
722             latch_wait(&udpif->exit_latch);
723         }
724         poll_block();
725     }
726
727     return NULL;
728 }
729
730 static size_t
731 recv_upcalls(struct handler *handler)
732 {
733     struct udpif *udpif = handler->udpif;
734     uint64_t recv_stubs[UPCALL_MAX_BATCH][512 / 8];
735     struct ofpbuf recv_bufs[UPCALL_MAX_BATCH];
736     struct dpif_upcall dupcalls[UPCALL_MAX_BATCH];
737     struct upcall upcalls[UPCALL_MAX_BATCH];
738     struct flow flows[UPCALL_MAX_BATCH];
739     size_t n_upcalls, i;
740
741     n_upcalls = 0;
742     while (n_upcalls < UPCALL_MAX_BATCH) {
743         struct ofpbuf *recv_buf = &recv_bufs[n_upcalls];
744         struct dpif_upcall *dupcall = &dupcalls[n_upcalls];
745         struct upcall *upcall = &upcalls[n_upcalls];
746         struct flow *flow = &flows[n_upcalls];
747         unsigned int mru;
748         int error;
749
750         ofpbuf_use_stub(recv_buf, recv_stubs[n_upcalls],
751                         sizeof recv_stubs[n_upcalls]);
752         if (dpif_recv(udpif->dpif, handler->handler_id, dupcall, recv_buf)) {
753             ofpbuf_uninit(recv_buf);
754             break;
755         }
756
757         if (odp_flow_key_to_flow(dupcall->key, dupcall->key_len, flow)
758             == ODP_FIT_ERROR) {
759             goto free_dupcall;
760         }
761
762         if (dupcall->mru) {
763             mru = nl_attr_get_u16(dupcall->mru);
764         } else {
765             mru = 0;
766         }
767
768         error = upcall_receive(upcall, udpif->backer, &dupcall->packet,
769                                dupcall->type, dupcall->userdata, flow, mru,
770                                &dupcall->ufid, PMD_ID_NULL);
771         if (error) {
772             if (error == ENODEV) {
773                 /* Received packet on datapath port for which we couldn't
774                  * associate an ofproto.  This can happen if a port is removed
775                  * while traffic is being received.  Print a rate-limited
776                  * message in case it happens frequently. */
777                 dpif_flow_put(udpif->dpif, DPIF_FP_CREATE, dupcall->key,
778                               dupcall->key_len, NULL, 0, NULL, 0,
779                               &dupcall->ufid, PMD_ID_NULL, NULL);
780                 VLOG_INFO_RL(&rl, "received packet on unassociated datapath "
781                              "port %"PRIu32, flow->in_port.odp_port);
782             }
783             goto free_dupcall;
784         }
785
786         upcall->key = dupcall->key;
787         upcall->key_len = dupcall->key_len;
788         upcall->ufid = &dupcall->ufid;
789
790         upcall->out_tun_key = dupcall->out_tun_key;
791         upcall->actions = dupcall->actions;
792
793         if (vsp_adjust_flow(upcall->ofproto, flow, &dupcall->packet)) {
794             upcall->vsp_adjusted = true;
795         }
796
797         pkt_metadata_from_flow(&dupcall->packet.md, flow);
798         flow_extract(&dupcall->packet, flow);
799
800         error = process_upcall(udpif, upcall,
801                                &upcall->odp_actions, &upcall->wc);
802         if (error) {
803             goto cleanup;
804         }
805
806         n_upcalls++;
807         continue;
808
809 cleanup:
810         upcall_uninit(upcall);
811 free_dupcall:
812         dp_packet_uninit(&dupcall->packet);
813         ofpbuf_uninit(recv_buf);
814     }
815
816     if (n_upcalls) {
817         handle_upcalls(handler->udpif, upcalls, n_upcalls);
818         for (i = 0; i < n_upcalls; i++) {
819             dp_packet_uninit(&dupcalls[i].packet);
820             ofpbuf_uninit(&recv_bufs[i]);
821             upcall_uninit(&upcalls[i]);
822         }
823     }
824
825     return n_upcalls;
826 }
827
828 static void *
829 udpif_revalidator(void *arg)
830 {
831     /* Used by all revalidators. */
832     struct revalidator *revalidator = arg;
833     struct udpif *udpif = revalidator->udpif;
834     bool leader = revalidator == &udpif->revalidators[0];
835
836     /* Used only by the leader. */
837     long long int start_time = 0;
838     uint64_t last_reval_seq = 0;
839     size_t n_flows = 0;
840
841     revalidator->id = ovsthread_id_self();
842     for (;;) {
843         if (leader) {
844             uint64_t reval_seq;
845
846             recirc_run(); /* Recirculation cleanup. */
847
848             reval_seq = seq_read(udpif->reval_seq);
849             last_reval_seq = reval_seq;
850
851             n_flows = udpif_get_n_flows(udpif);
852             udpif->max_n_flows = MAX(n_flows, udpif->max_n_flows);
853             udpif->avg_n_flows = (udpif->avg_n_flows + n_flows) / 2;
854
855             /* Only the leader checks the pause latch to prevent a race where
856              * some threads think it's false and proceed to block on
857              * reval_barrier and others think it's true and block indefinitely
858              * on the pause_barrier */
859             udpif->pause = latch_is_set(&udpif->pause_latch);
860
861             /* Only the leader checks the exit latch to prevent a race where
862              * some threads think it's true and exit and others think it's
863              * false and block indefinitely on the reval_barrier */
864             udpif->reval_exit = latch_is_set(&udpif->exit_latch);
865
866             start_time = time_msec();
867             if (!udpif->reval_exit) {
868                 bool terse_dump;
869
870                 terse_dump = udpif_use_ufid(udpif);
871                 udpif->dump = dpif_flow_dump_create(udpif->dpif, terse_dump);
872             }
873         }
874
875         /* Wait for the leader to start the flow dump. */
876         ovs_barrier_block(&udpif->reval_barrier);
877         if (udpif->pause) {
878             revalidator_pause(revalidator);
879         }
880
881         if (udpif->reval_exit) {
882             break;
883         }
884         revalidate(revalidator);
885
886         /* Wait for all flows to have been dumped before we garbage collect. */
887         ovs_barrier_block(&udpif->reval_barrier);
888         revalidator_sweep(revalidator);
889
890         /* Wait for all revalidators to finish garbage collection. */
891         ovs_barrier_block(&udpif->reval_barrier);
892
893         if (leader) {
894             unsigned int flow_limit;
895             long long int duration;
896
897             atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
898
899             dpif_flow_dump_destroy(udpif->dump);
900             seq_change(udpif->dump_seq);
901
902             duration = MAX(time_msec() - start_time, 1);
903             udpif->dump_duration = duration;
904             if (duration > 2000) {
905                 flow_limit /= duration / 1000;
906             } else if (duration > 1300) {
907                 flow_limit = flow_limit * 3 / 4;
908             } else if (duration < 1000 && n_flows > 2000
909                        && flow_limit < n_flows * 1000 / duration) {
910                 flow_limit += 1000;
911             }
912             flow_limit = MIN(ofproto_flow_limit, MAX(flow_limit, 1000));
913             atomic_store_relaxed(&udpif->flow_limit, flow_limit);
914
915             if (duration > 2000) {
916                 VLOG_INFO("Spent an unreasonably long %lldms dumping flows",
917                           duration);
918             }
919
920             poll_timer_wait_until(start_time + MIN(ofproto_max_idle, 500));
921             seq_wait(udpif->reval_seq, last_reval_seq);
922             latch_wait(&udpif->exit_latch);
923             latch_wait(&udpif->pause_latch);
924             poll_block();
925         }
926     }
927
928     return NULL;
929 }
930 \f
931 static enum upcall_type
932 classify_upcall(enum dpif_upcall_type type, const struct nlattr *userdata)
933 {
934     union user_action_cookie cookie;
935     size_t userdata_len;
936
937     /* First look at the upcall type. */
938     switch (type) {
939     case DPIF_UC_ACTION:
940         break;
941
942     case DPIF_UC_MISS:
943         return MISS_UPCALL;
944
945     case DPIF_N_UC_TYPES:
946     default:
947         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, type);
948         return BAD_UPCALL;
949     }
950
951     /* "action" upcalls need a closer look. */
952     if (!userdata) {
953         VLOG_WARN_RL(&rl, "action upcall missing cookie");
954         return BAD_UPCALL;
955     }
956     userdata_len = nl_attr_get_size(userdata);
957     if (userdata_len < sizeof cookie.type
958         || userdata_len > sizeof cookie) {
959         VLOG_WARN_RL(&rl, "action upcall cookie has unexpected size %"PRIuSIZE,
960                      userdata_len);
961         return BAD_UPCALL;
962     }
963     memset(&cookie, 0, sizeof cookie);
964     memcpy(&cookie, nl_attr_get(userdata), userdata_len);
965     if (userdata_len == MAX(8, sizeof cookie.sflow)
966         && cookie.type == USER_ACTION_COOKIE_SFLOW) {
967         return SFLOW_UPCALL;
968     } else if (userdata_len == MAX(8, sizeof cookie.slow_path)
969                && cookie.type == USER_ACTION_COOKIE_SLOW_PATH) {
970         return MISS_UPCALL;
971     } else if (userdata_len == MAX(8, sizeof cookie.flow_sample)
972                && cookie.type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
973         return FLOW_SAMPLE_UPCALL;
974     } else if (userdata_len == MAX(8, sizeof cookie.ipfix)
975                && cookie.type == USER_ACTION_COOKIE_IPFIX) {
976         return IPFIX_UPCALL;
977     } else {
978         VLOG_WARN_RL(&rl, "invalid user cookie of type %"PRIu16
979                      " and size %"PRIuSIZE, cookie.type, userdata_len);
980         return BAD_UPCALL;
981     }
982 }
983
984 /* Calculates slow path actions for 'xout'.  'buf' must statically be
985  * initialized with at least 128 bytes of space. */
986 static void
987 compose_slow_path(struct udpif *udpif, struct xlate_out *xout,
988                   const struct flow *flow, odp_port_t odp_in_port,
989                   struct ofpbuf *buf)
990 {
991     union user_action_cookie cookie;
992     odp_port_t port;
993     uint32_t pid;
994
995     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
996     cookie.slow_path.unused = 0;
997     cookie.slow_path.reason = xout->slow;
998
999     port = xout->slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)
1000         ? ODPP_NONE
1001         : odp_in_port;
1002     pid = dpif_port_get_pid(udpif->dpif, port, flow_hash_5tuple(flow, 0));
1003     odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path,
1004                              ODPP_NONE, false, buf);
1005 }
1006
1007 /* If there is no error, the upcall must be destroyed with upcall_uninit()
1008  * before quiescing, as the referred objects are guaranteed to exist only
1009  * until the calling thread quiesces.  Otherwise, do not call upcall_uninit()
1010  * since the 'upcall->put_actions' remains uninitialized. */
1011 static int
1012 upcall_receive(struct upcall *upcall, const struct dpif_backer *backer,
1013                const struct dp_packet *packet, enum dpif_upcall_type type,
1014                const struct nlattr *userdata, const struct flow *flow,
1015                const unsigned int mru,
1016                const ovs_u128 *ufid, const unsigned pmd_id)
1017 {
1018     int error;
1019
1020     error = xlate_lookup(backer, flow, &upcall->ofproto, &upcall->ipfix,
1021                          &upcall->sflow, NULL, &upcall->in_port);
1022     if (error) {
1023         return error;
1024     }
1025
1026     upcall->recirc = NULL;
1027     upcall->have_recirc_ref = false;
1028     upcall->flow = flow;
1029     upcall->packet = packet;
1030     upcall->ufid = ufid;
1031     upcall->pmd_id = pmd_id;
1032     upcall->type = type;
1033     upcall->userdata = userdata;
1034     ofpbuf_use_stub(&upcall->odp_actions, upcall->odp_actions_stub,
1035                     sizeof upcall->odp_actions_stub);
1036     ofpbuf_init(&upcall->put_actions, 0);
1037
1038     upcall->xout_initialized = false;
1039     upcall->vsp_adjusted = false;
1040     upcall->ukey_persists = false;
1041
1042     upcall->ukey = NULL;
1043     upcall->key = NULL;
1044     upcall->key_len = 0;
1045     upcall->mru = mru;
1046
1047     upcall->out_tun_key = NULL;
1048     upcall->actions = NULL;
1049
1050     return 0;
1051 }
1052
1053 static void
1054 upcall_xlate(struct udpif *udpif, struct upcall *upcall,
1055              struct ofpbuf *odp_actions, struct flow_wildcards *wc)
1056 {
1057     struct dpif_flow_stats stats;
1058     struct xlate_in xin;
1059
1060     stats.n_packets = 1;
1061     stats.n_bytes = dp_packet_size(upcall->packet);
1062     stats.used = time_msec();
1063     stats.tcp_flags = ntohs(upcall->flow->tcp_flags);
1064
1065     xlate_in_init(&xin, upcall->ofproto, upcall->flow, upcall->in_port, NULL,
1066                   stats.tcp_flags, upcall->packet, wc, odp_actions);
1067
1068     if (upcall->type == DPIF_UC_MISS) {
1069         xin.resubmit_stats = &stats;
1070
1071         if (xin.recirc) {
1072             /* We may install a datapath flow only if we get a reference to the
1073              * recirculation context (otherwise we could have recirculation
1074              * upcalls using recirculation ID for which no context can be
1075              * found).  We may still execute the flow's actions even if we
1076              * don't install the flow. */
1077             upcall->recirc = xin.recirc;
1078             upcall->have_recirc_ref = recirc_id_node_try_ref_rcu(xin.recirc);
1079         }
1080     } else {
1081         /* For non-miss upcalls, we are either executing actions (one of which
1082          * is an userspace action) for an upcall, in which case the stats have
1083          * already been taken care of, or there's a flow in the datapath which
1084          * this packet was accounted to.  Presumably the revalidators will deal
1085          * with pushing its stats eventually. */
1086     }
1087
1088     upcall->dump_seq = seq_read(udpif->dump_seq);
1089     upcall->reval_seq = seq_read(udpif->reval_seq);
1090     xlate_actions(&xin, &upcall->xout);
1091     upcall->xout_initialized = true;
1092
1093     /* Special case for fail-open mode.
1094      *
1095      * If we are in fail-open mode, but we are connected to a controller too,
1096      * then we should send the packet up to the controller in the hope that it
1097      * will try to set up a flow and thereby allow us to exit fail-open.
1098      *
1099      * See the top-level comment in fail-open.c for more information.
1100      *
1101      * Copy packets before they are modified by execution. */
1102     if (upcall->xout.fail_open) {
1103         const struct dp_packet *packet = upcall->packet;
1104         struct ofproto_packet_in *pin;
1105
1106         pin = xmalloc(sizeof *pin);
1107         pin->up.packet = xmemdup(dp_packet_data(packet), dp_packet_size(packet));
1108         pin->up.packet_len = dp_packet_size(packet);
1109         pin->up.reason = OFPR_NO_MATCH;
1110         pin->up.table_id = 0;
1111         pin->up.cookie = OVS_BE64_MAX;
1112         flow_get_metadata(upcall->flow, &pin->up.flow_metadata);
1113         pin->send_len = 0; /* Not used for flow table misses. */
1114         pin->miss_type = OFPROTO_PACKET_IN_NO_MISS;
1115         ofproto_dpif_send_packet_in(upcall->ofproto, pin);
1116     }
1117
1118     if (!upcall->xout.slow) {
1119         ofpbuf_use_const(&upcall->put_actions,
1120                          odp_actions->data, odp_actions->size);
1121     } else {
1122         /* upcall->put_actions already initialized by upcall_receive(). */
1123         compose_slow_path(udpif, &upcall->xout, upcall->flow,
1124                           upcall->flow->in_port.odp_port,
1125                           &upcall->put_actions);
1126     }
1127
1128     /* This function is also called for slow-pathed flows.  As we are only
1129      * going to create new datapath flows for actual datapath misses, there is
1130      * no point in creating a ukey otherwise. */
1131     if (upcall->type == DPIF_UC_MISS) {
1132         upcall->ukey = ukey_create_from_upcall(upcall, wc);
1133     }
1134 }
1135
1136 static void
1137 upcall_uninit(struct upcall *upcall)
1138 {
1139     if (upcall) {
1140         if (upcall->xout_initialized) {
1141             xlate_out_uninit(&upcall->xout);
1142         }
1143         ofpbuf_uninit(&upcall->odp_actions);
1144         ofpbuf_uninit(&upcall->put_actions);
1145         if (upcall->ukey) {
1146             if (!upcall->ukey_persists) {
1147                 ukey_delete__(upcall->ukey);
1148             }
1149         } else if (upcall->have_recirc_ref) {
1150             /* The reference was transferred to the ukey if one was created. */
1151             recirc_id_node_unref(upcall->recirc);
1152         }
1153     }
1154 }
1155
1156 static int
1157 upcall_cb(const struct dp_packet *packet, const struct flow *flow, ovs_u128 *ufid,
1158           unsigned pmd_id, enum dpif_upcall_type type,
1159           const struct nlattr *userdata, struct ofpbuf *actions,
1160           struct flow_wildcards *wc, struct ofpbuf *put_actions, void *aux)
1161 {
1162     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1163     struct udpif *udpif = aux;
1164     unsigned int flow_limit;
1165     struct upcall upcall;
1166     bool megaflow;
1167     int error;
1168
1169     atomic_read_relaxed(&enable_megaflows, &megaflow);
1170     atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
1171
1172     error = upcall_receive(&upcall, udpif->backer, packet, type, userdata,
1173                            flow, 0, ufid, pmd_id);
1174     if (error) {
1175         return error;
1176     }
1177
1178     error = process_upcall(udpif, &upcall, actions, wc);
1179     if (error) {
1180         goto out;
1181     }
1182
1183     if (upcall.xout.slow && put_actions) {
1184         ofpbuf_put(put_actions, upcall.put_actions.data,
1185                    upcall.put_actions.size);
1186     }
1187
1188     if (OVS_UNLIKELY(!megaflow)) {
1189         flow_wildcards_init_for_packet(wc, flow);
1190     }
1191
1192     if (udpif_get_n_flows(udpif) >= flow_limit) {
1193         VLOG_WARN_RL(&rl, "upcall_cb failure: datapath flow limit reached");
1194         error = ENOSPC;
1195         goto out;
1196     }
1197
1198     /* Prevent miss flow installation if the key has recirculation ID but we
1199      * were not able to get a reference on it. */
1200     if (type == DPIF_UC_MISS && upcall.recirc && !upcall.have_recirc_ref) {
1201         VLOG_WARN_RL(&rl, "upcall_cb failure: no reference for recirc flow");
1202         error = ENOSPC;
1203         goto out;
1204     }
1205
1206     if (upcall.ukey && !ukey_install(udpif, upcall.ukey)) {
1207         VLOG_WARN_RL(&rl, "upcall_cb failure: ukey installation fails");
1208         error = ENOSPC;
1209     }
1210 out:
1211     if (!error) {
1212         upcall.ukey_persists = true;
1213     }
1214     upcall_uninit(&upcall);
1215     return error;
1216 }
1217
1218 static int
1219 process_upcall(struct udpif *udpif, struct upcall *upcall,
1220                struct ofpbuf *odp_actions, struct flow_wildcards *wc)
1221 {
1222     const struct nlattr *userdata = upcall->userdata;
1223     const struct dp_packet *packet = upcall->packet;
1224     const struct flow *flow = upcall->flow;
1225
1226     switch (classify_upcall(upcall->type, userdata)) {
1227     case MISS_UPCALL:
1228         upcall_xlate(udpif, upcall, odp_actions, wc);
1229         return 0;
1230
1231     case SFLOW_UPCALL:
1232         if (upcall->sflow) {
1233             union user_action_cookie cookie;
1234             const struct nlattr *actions;
1235             size_t actions_len = 0;
1236             struct dpif_sflow_actions sflow_actions;
1237             memset(&sflow_actions, 0, sizeof sflow_actions);
1238             memset(&cookie, 0, sizeof cookie);
1239             memcpy(&cookie, nl_attr_get(userdata), sizeof cookie.sflow);
1240             if (upcall->actions) {
1241                 /* Actions were passed up from datapath. */
1242                 actions = nl_attr_get(upcall->actions);
1243                 actions_len = nl_attr_get_size(upcall->actions);
1244                 if (actions && actions_len) {
1245                     dpif_sflow_read_actions(flow, actions, actions_len,
1246                                             &sflow_actions);
1247                 }
1248             }
1249             if (actions_len == 0) {
1250                 /* Lookup actions in userspace cache. */
1251                 struct udpif_key *ukey = ukey_lookup(udpif, upcall->ufid);
1252                 if (ukey) {
1253                     ukey_get_actions(ukey, &actions, &actions_len);
1254                     dpif_sflow_read_actions(flow, actions, actions_len,
1255                                             &sflow_actions);
1256                 }
1257             }
1258             dpif_sflow_received(upcall->sflow, packet, flow,
1259                                 flow->in_port.odp_port, &cookie,
1260                                 actions_len > 0 ? &sflow_actions : NULL);
1261         }
1262         break;
1263
1264     case IPFIX_UPCALL:
1265         if (upcall->ipfix) {
1266             union user_action_cookie cookie;
1267             struct flow_tnl output_tunnel_key;
1268
1269             memset(&cookie, 0, sizeof cookie);
1270             memcpy(&cookie, nl_attr_get(userdata), sizeof cookie.ipfix);
1271
1272             if (upcall->out_tun_key) {
1273                 odp_tun_key_from_attr(upcall->out_tun_key, false,
1274                                       &output_tunnel_key);
1275             }
1276             dpif_ipfix_bridge_sample(upcall->ipfix, packet, flow,
1277                                      flow->in_port.odp_port,
1278                                      cookie.ipfix.output_odp_port,
1279                                      upcall->out_tun_key ?
1280                                          &output_tunnel_key : NULL);
1281         }
1282         break;
1283
1284     case FLOW_SAMPLE_UPCALL:
1285         if (upcall->ipfix) {
1286             union user_action_cookie cookie;
1287
1288             memset(&cookie, 0, sizeof cookie);
1289             memcpy(&cookie, nl_attr_get(userdata), sizeof cookie.flow_sample);
1290
1291             /* The flow reflects exactly the contents of the packet.
1292              * Sample the packet using it. */
1293             dpif_ipfix_flow_sample(upcall->ipfix, packet, flow,
1294                                    cookie.flow_sample.collector_set_id,
1295                                    cookie.flow_sample.probability,
1296                                    cookie.flow_sample.obs_domain_id,
1297                                    cookie.flow_sample.obs_point_id);
1298         }
1299         break;
1300
1301     case BAD_UPCALL:
1302         break;
1303     }
1304
1305     return EAGAIN;
1306 }
1307
1308 static void
1309 handle_upcalls(struct udpif *udpif, struct upcall *upcalls,
1310                size_t n_upcalls)
1311 {
1312     struct dpif_op *opsp[UPCALL_MAX_BATCH * 2];
1313     struct ukey_op ops[UPCALL_MAX_BATCH * 2];
1314     unsigned int flow_limit;
1315     size_t n_ops, n_opsp, i;
1316     bool may_put;
1317
1318     atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
1319
1320     may_put = udpif_get_n_flows(udpif) < flow_limit;
1321
1322     /* Handle the packets individually in order of arrival.
1323      *
1324      *   - For SLOW_CFM, SLOW_LACP, SLOW_STP, and SLOW_BFD, translation is what
1325      *     processes received packets for these protocols.
1326      *
1327      *   - For SLOW_CONTROLLER, translation sends the packet to the OpenFlow
1328      *     controller.
1329      *
1330      * The loop fills 'ops' with an array of operations to execute in the
1331      * datapath. */
1332     n_ops = 0;
1333     for (i = 0; i < n_upcalls; i++) {
1334         struct upcall *upcall = &upcalls[i];
1335         const struct dp_packet *packet = upcall->packet;
1336         struct ukey_op *op;
1337
1338         if (upcall->vsp_adjusted) {
1339             /* This packet was received on a VLAN splinter port.  We added a
1340              * VLAN to the packet to make the packet resemble the flow, but the
1341              * actions were composed assuming that the packet contained no
1342              * VLAN.  So, we must remove the VLAN header from the packet before
1343              * trying to execute the actions. */
1344             if (upcall->odp_actions.size) {
1345                 eth_pop_vlan(CONST_CAST(struct dp_packet *, upcall->packet));
1346             }
1347
1348             /* Remove the flow vlan tags inserted by vlan splinter logic
1349              * to ensure megaflow masks generated match the data path flow. */
1350             CONST_CAST(struct flow *, upcall->flow)->vlan_tci = 0;
1351         }
1352
1353         /* Do not install a flow into the datapath if:
1354          *
1355          *    - The datapath already has too many flows.
1356          *
1357          *    - We received this packet via some flow installed in the kernel
1358          *      already.
1359          *
1360          *    - Upcall was a recirculation but we do not have a reference to
1361          *      to the recirculation ID. */
1362         if (may_put && upcall->type == DPIF_UC_MISS &&
1363             (!upcall->recirc || upcall->have_recirc_ref)) {
1364             struct udpif_key *ukey = upcall->ukey;
1365
1366             upcall->ukey_persists = true;
1367             op = &ops[n_ops++];
1368
1369             op->ukey = ukey;
1370             op->dop.type = DPIF_OP_FLOW_PUT;
1371             op->dop.u.flow_put.flags = DPIF_FP_CREATE;
1372             op->dop.u.flow_put.key = ukey->key;
1373             op->dop.u.flow_put.key_len = ukey->key_len;
1374             op->dop.u.flow_put.mask = ukey->mask;
1375             op->dop.u.flow_put.mask_len = ukey->mask_len;
1376             op->dop.u.flow_put.ufid = upcall->ufid;
1377             op->dop.u.flow_put.stats = NULL;
1378             ukey_get_actions(ukey, &op->dop.u.flow_put.actions,
1379                              &op->dop.u.flow_put.actions_len);
1380         }
1381
1382         if (upcall->odp_actions.size) {
1383             op = &ops[n_ops++];
1384             op->ukey = NULL;
1385             op->dop.type = DPIF_OP_EXECUTE;
1386             op->dop.u.execute.packet = CONST_CAST(struct dp_packet *, packet);
1387             odp_key_to_pkt_metadata(upcall->key, upcall->key_len,
1388                                     &op->dop.u.execute.packet->md);
1389             op->dop.u.execute.actions = upcall->odp_actions.data;
1390             op->dop.u.execute.actions_len = upcall->odp_actions.size;
1391             op->dop.u.execute.needs_help = (upcall->xout.slow & SLOW_ACTION) != 0;
1392             op->dop.u.execute.probe = false;
1393             op->dop.u.execute.mtu = upcall->mru;
1394         }
1395     }
1396
1397     /* Execute batch.
1398      *
1399      * We install ukeys before installing the flows, locking them for exclusive
1400      * access by this thread for the period of installation. This ensures that
1401      * other threads won't attempt to delete the flows as we are creating them.
1402      */
1403     n_opsp = 0;
1404     for (i = 0; i < n_ops; i++) {
1405         struct udpif_key *ukey = ops[i].ukey;
1406
1407         if (ukey) {
1408             /* If we can't install the ukey, don't install the flow. */
1409             if (!ukey_install_start(udpif, ukey)) {
1410                 ukey_delete__(ukey);
1411                 ops[i].ukey = NULL;
1412                 continue;
1413             }
1414         }
1415         opsp[n_opsp++] = &ops[i].dop;
1416     }
1417     dpif_operate(udpif->dpif, opsp, n_opsp);
1418     for (i = 0; i < n_ops; i++) {
1419         if (ops[i].ukey) {
1420             ukey_install_finish(ops[i].ukey, ops[i].dop.error);
1421         }
1422     }
1423 }
1424
1425 static uint32_t
1426 get_ufid_hash(const ovs_u128 *ufid)
1427 {
1428     return ufid->u32[0];
1429 }
1430
1431 static struct udpif_key *
1432 ukey_lookup(struct udpif *udpif, const ovs_u128 *ufid)
1433 {
1434     struct udpif_key *ukey;
1435     int idx = get_ufid_hash(ufid) % N_UMAPS;
1436     struct cmap *cmap = &udpif->ukeys[idx].cmap;
1437
1438     CMAP_FOR_EACH_WITH_HASH (ukey, cmap_node, get_ufid_hash(ufid), cmap) {
1439         if (ovs_u128_equals(&ukey->ufid, ufid)) {
1440             return ukey;
1441         }
1442     }
1443     return NULL;
1444 }
1445
1446 /* Provides safe lockless access of RCU protected 'ukey->actions'.  Callers may
1447  * alternatively access the field directly if they take 'ukey->mutex'. */
1448 static void
1449 ukey_get_actions(struct udpif_key *ukey, const struct nlattr **actions, size_t *size)
1450 {
1451     const struct ofpbuf *buf = ovsrcu_get(struct ofpbuf *, &ukey->actions);
1452     *actions = buf->data;
1453     *size = buf->size;
1454 }
1455
1456 static void
1457 ukey_set_actions(struct udpif_key *ukey, const struct ofpbuf *actions)
1458 {
1459     ovsrcu_postpone(ofpbuf_delete,
1460                     ovsrcu_get_protected(struct ofpbuf *, &ukey->actions));
1461     ovsrcu_set(&ukey->actions, ofpbuf_clone(actions));
1462 }
1463
1464 static struct udpif_key *
1465 ukey_create__(const struct nlattr *key, size_t key_len,
1466               const struct nlattr *mask, size_t mask_len,
1467               bool ufid_present, const ovs_u128 *ufid,
1468               const unsigned pmd_id, const struct ofpbuf *actions,
1469               uint64_t dump_seq, uint64_t reval_seq, long long int used,
1470               uint32_t key_recirc_id, struct xlate_out *xout)
1471     OVS_NO_THREAD_SAFETY_ANALYSIS
1472 {
1473     struct udpif_key *ukey = xmalloc(sizeof *ukey);
1474
1475     memcpy(&ukey->keybuf, key, key_len);
1476     ukey->key = &ukey->keybuf.nla;
1477     ukey->key_len = key_len;
1478     memcpy(&ukey->maskbuf, mask, mask_len);
1479     ukey->mask = &ukey->maskbuf.nla;
1480     ukey->mask_len = mask_len;
1481     ukey->ufid_present = ufid_present;
1482     ukey->ufid = *ufid;
1483     ukey->pmd_id = pmd_id;
1484     ukey->hash = get_ufid_hash(&ukey->ufid);
1485
1486     ovsrcu_init(&ukey->actions, NULL);
1487     ukey_set_actions(ukey, actions);
1488
1489     ovs_mutex_init(&ukey->mutex);
1490     ukey->dump_seq = dump_seq;
1491     ukey->reval_seq = reval_seq;
1492     ukey->flow_exists = false;
1493     ukey->created = time_msec();
1494     memset(&ukey->stats, 0, sizeof ukey->stats);
1495     ukey->stats.used = used;
1496     ukey->xcache = NULL;
1497
1498     ukey->key_recirc_id = key_recirc_id;
1499     recirc_refs_init(&ukey->recircs);
1500     if (xout) {
1501         /* Take ownership of the action recirc id references. */
1502         recirc_refs_swap(&ukey->recircs, &xout->recircs);
1503     }
1504
1505     return ukey;
1506 }
1507
1508 static struct udpif_key *
1509 ukey_create_from_upcall(struct upcall *upcall, struct flow_wildcards *wc)
1510 {
1511     struct odputil_keybuf keystub, maskstub;
1512     struct ofpbuf keybuf, maskbuf;
1513     bool megaflow;
1514     struct odp_flow_key_parms odp_parms = {
1515         .flow = upcall->flow,
1516         .mask = &wc->masks,
1517     };
1518
1519     odp_parms.support = ofproto_dpif_get_support(upcall->ofproto)->odp;
1520     if (upcall->key_len) {
1521         ofpbuf_use_const(&keybuf, upcall->key, upcall->key_len);
1522     } else {
1523         /* dpif-netdev doesn't provide a netlink-formatted flow key in the
1524          * upcall, so convert the upcall's flow here. */
1525         ofpbuf_use_stack(&keybuf, &keystub, sizeof keystub);
1526         odp_parms.odp_in_port = upcall->flow->in_port.odp_port;
1527         odp_flow_key_from_flow(&odp_parms, &keybuf);
1528     }
1529
1530     atomic_read_relaxed(&enable_megaflows, &megaflow);
1531     ofpbuf_use_stack(&maskbuf, &maskstub, sizeof maskstub);
1532     if (megaflow) {
1533         odp_parms.odp_in_port = ODPP_NONE;
1534         odp_parms.key_buf = &keybuf;
1535
1536         odp_flow_key_from_mask(&odp_parms, &maskbuf);
1537     }
1538
1539     return ukey_create__(keybuf.data, keybuf.size, maskbuf.data, maskbuf.size,
1540                          true, upcall->ufid, upcall->pmd_id,
1541                          &upcall->put_actions, upcall->dump_seq,
1542                          upcall->reval_seq, 0,
1543                          upcall->have_recirc_ref ? upcall->recirc->id : 0,
1544                          &upcall->xout);
1545 }
1546
1547 static int
1548 ukey_create_from_dpif_flow(const struct udpif *udpif,
1549                            const struct dpif_flow *flow,
1550                            struct udpif_key **ukey)
1551 {
1552     struct dpif_flow full_flow;
1553     struct ofpbuf actions;
1554     uint64_t dump_seq, reval_seq;
1555     uint64_t stub[DPIF_FLOW_BUFSIZE / 8];
1556     const struct nlattr *a;
1557     unsigned int left;
1558
1559     if (!flow->key_len || !flow->actions_len) {
1560         struct ofpbuf buf;
1561         int err;
1562
1563         /* If the key or actions were not provided by the datapath, fetch the
1564          * full flow. */
1565         ofpbuf_use_stack(&buf, &stub, sizeof stub);
1566         err = dpif_flow_get(udpif->dpif, NULL, 0, &flow->ufid,
1567                             flow->pmd_id, &buf, &full_flow);
1568         if (err) {
1569             return err;
1570         }
1571         flow = &full_flow;
1572     }
1573
1574     /* Check the flow actions for recirculation action.  As recirculation
1575      * relies on OVS userspace internal state, we need to delete all old
1576      * datapath flows with either a non-zero recirc_id in the key, or any
1577      * recirculation actions upon OVS restart. */
1578     NL_ATTR_FOR_EACH_UNSAFE (a, left, flow->key, flow->key_len) {
1579         if (nl_attr_type(a) == OVS_KEY_ATTR_RECIRC_ID
1580             && nl_attr_get_u32(a) != 0) {
1581             return EINVAL;
1582         }
1583     }
1584     NL_ATTR_FOR_EACH_UNSAFE (a, left, flow->actions, flow->actions_len) {
1585         if (nl_attr_type(a) == OVS_ACTION_ATTR_RECIRC) {
1586             return EINVAL;
1587         }
1588     }
1589
1590     dump_seq = seq_read(udpif->dump_seq);
1591     reval_seq = seq_read(udpif->reval_seq);
1592     ofpbuf_use_const(&actions, &flow->actions, flow->actions_len);
1593     *ukey = ukey_create__(flow->key, flow->key_len,
1594                           flow->mask, flow->mask_len, flow->ufid_present,
1595                           &flow->ufid, flow->pmd_id, &actions, dump_seq,
1596                           reval_seq, flow->stats.used, 0, NULL);
1597
1598     return 0;
1599 }
1600
1601 /* Attempts to insert a ukey into the shared ukey maps.
1602  *
1603  * On success, returns true, installs the ukey and returns it in a locked
1604  * state. Otherwise, returns false. */
1605 static bool
1606 ukey_install_start(struct udpif *udpif, struct udpif_key *new_ukey)
1607     OVS_TRY_LOCK(true, new_ukey->mutex)
1608 {
1609     struct umap *umap;
1610     struct udpif_key *old_ukey;
1611     uint32_t idx;
1612     bool locked = false;
1613
1614     idx = new_ukey->hash % N_UMAPS;
1615     umap = &udpif->ukeys[idx];
1616     ovs_mutex_lock(&umap->mutex);
1617     old_ukey = ukey_lookup(udpif, &new_ukey->ufid);
1618     if (old_ukey) {
1619         /* Uncommon case: A ukey is already installed with the same UFID. */
1620         if (old_ukey->key_len == new_ukey->key_len
1621             && !memcmp(old_ukey->key, new_ukey->key, new_ukey->key_len)) {
1622             COVERAGE_INC(handler_duplicate_upcall);
1623         } else {
1624             struct ds ds = DS_EMPTY_INITIALIZER;
1625
1626             odp_format_ufid(&old_ukey->ufid, &ds);
1627             ds_put_cstr(&ds, " ");
1628             odp_flow_key_format(old_ukey->key, old_ukey->key_len, &ds);
1629             ds_put_cstr(&ds, "\n");
1630             odp_format_ufid(&new_ukey->ufid, &ds);
1631             ds_put_cstr(&ds, " ");
1632             odp_flow_key_format(new_ukey->key, new_ukey->key_len, &ds);
1633
1634             VLOG_WARN_RL(&rl, "Conflicting ukey for flows:\n%s", ds_cstr(&ds));
1635             ds_destroy(&ds);
1636         }
1637     } else {
1638         ovs_mutex_lock(&new_ukey->mutex);
1639         cmap_insert(&umap->cmap, &new_ukey->cmap_node, new_ukey->hash);
1640         locked = true;
1641     }
1642     ovs_mutex_unlock(&umap->mutex);
1643
1644     return locked;
1645 }
1646
1647 static void
1648 ukey_install_finish__(struct udpif_key *ukey) OVS_REQUIRES(ukey->mutex)
1649 {
1650     ukey->flow_exists = true;
1651 }
1652
1653 static bool
1654 ukey_install_finish(struct udpif_key *ukey, int error)
1655     OVS_RELEASES(ukey->mutex)
1656 {
1657     if (!error) {
1658         ukey_install_finish__(ukey);
1659     }
1660     ovs_mutex_unlock(&ukey->mutex);
1661
1662     return !error;
1663 }
1664
1665 static bool
1666 ukey_install(struct udpif *udpif, struct udpif_key *ukey)
1667 {
1668     /* The usual way to keep 'ukey->flow_exists' in sync with the datapath is
1669      * to call ukey_install_start(), install the corresponding datapath flow,
1670      * then call ukey_install_finish(). The netdev interface using upcall_cb()
1671      * doesn't provide a function to separately finish the flow installation,
1672      * so we perform the operations together here.
1673      *
1674      * This is fine currently, as revalidator threads will only delete this
1675      * ukey during revalidator_sweep() and only if the dump_seq is mismatched.
1676      * It is unlikely for a revalidator thread to advance dump_seq and reach
1677      * the next GC phase between ukey creation and flow installation. */
1678     return ukey_install_start(udpif, ukey) && ukey_install_finish(ukey, 0);
1679 }
1680
1681 /* Searches for a ukey in 'udpif->ukeys' that matches 'flow' and attempts to
1682  * lock the ukey. If the ukey does not exist, create it.
1683  *
1684  * Returns 0 on success, setting *result to the matching ukey and returning it
1685  * in a locked state. Otherwise, returns an errno and clears *result. EBUSY
1686  * indicates that another thread is handling this flow. Other errors indicate
1687  * an unexpected condition creating a new ukey.
1688  *
1689  * *error is an output parameter provided to appease the threadsafety analyser,
1690  * and its value matches the return value. */
1691 static int
1692 ukey_acquire(struct udpif *udpif, const struct dpif_flow *flow,
1693              struct udpif_key **result, int *error)
1694     OVS_TRY_LOCK(0, (*result)->mutex)
1695 {
1696     struct udpif_key *ukey;
1697     int retval;
1698
1699     ukey = ukey_lookup(udpif, &flow->ufid);
1700     if (ukey) {
1701         retval = ovs_mutex_trylock(&ukey->mutex);
1702     } else {
1703         /* Usually we try to avoid installing flows from revalidator threads,
1704          * because locking on a umap may cause handler threads to block.
1705          * However there are certain cases, like when ovs-vswitchd is
1706          * restarted, where it is desirable to handle flows that exist in the
1707          * datapath gracefully (ie, don't just clear the datapath). */
1708         bool install;
1709
1710         retval = ukey_create_from_dpif_flow(udpif, flow, &ukey);
1711         if (retval) {
1712             goto done;
1713         }
1714         install = ukey_install_start(udpif, ukey);
1715         if (install) {
1716             ukey_install_finish__(ukey);
1717             retval = 0;
1718         } else {
1719             ukey_delete__(ukey);
1720             retval = EBUSY;
1721         }
1722     }
1723
1724 done:
1725     *error = retval;
1726     if (retval) {
1727         *result = NULL;
1728     } else {
1729         *result = ukey;
1730     }
1731     return retval;
1732 }
1733
1734 static void
1735 ukey_delete__(struct udpif_key *ukey)
1736     OVS_NO_THREAD_SAFETY_ANALYSIS
1737 {
1738     if (ukey) {
1739         if (ukey->key_recirc_id) {
1740             recirc_free_id(ukey->key_recirc_id);
1741         }
1742         recirc_refs_unref(&ukey->recircs);
1743         xlate_cache_delete(ukey->xcache);
1744         ofpbuf_delete(ovsrcu_get(struct ofpbuf *, &ukey->actions));
1745         ovs_mutex_destroy(&ukey->mutex);
1746         free(ukey);
1747     }
1748 }
1749
1750 static void
1751 ukey_delete(struct umap *umap, struct udpif_key *ukey)
1752     OVS_REQUIRES(umap->mutex)
1753 {
1754     cmap_remove(&umap->cmap, &ukey->cmap_node, ukey->hash);
1755     ovsrcu_postpone(ukey_delete__, ukey);
1756 }
1757
1758 static bool
1759 should_revalidate(const struct udpif *udpif, uint64_t packets,
1760                   long long int used)
1761 {
1762     long long int metric, now, duration;
1763
1764     if (udpif->dump_duration < 200) {
1765         /* We are likely to handle full revalidation for the flows. */
1766         return true;
1767     }
1768
1769     /* Calculate the mean time between seeing these packets. If this
1770      * exceeds the threshold, then delete the flow rather than performing
1771      * costly revalidation for flows that aren't being hit frequently.
1772      *
1773      * This is targeted at situations where the dump_duration is high (~1s),
1774      * and revalidation is triggered by a call to udpif_revalidate(). In
1775      * these situations, revalidation of all flows causes fluctuations in the
1776      * flow_limit due to the interaction with the dump_duration and max_idle.
1777      * This tends to result in deletion of low-throughput flows anyway, so
1778      * skip the revalidation and just delete those flows. */
1779     packets = MAX(packets, 1);
1780     now = MAX(used, time_msec());
1781     duration = now - used;
1782     metric = duration / packets;
1783
1784     if (metric < 200) {
1785         /* The flow is receiving more than ~5pps, so keep it. */
1786         return true;
1787     }
1788     return false;
1789 }
1790
1791 /* Verifies that the datapath actions of 'ukey' are still correct, and pushes
1792  * 'stats' for it.
1793  *
1794  * Returns a recommended action for 'ukey', options include:
1795  *      UKEY_DELETE The ukey should be deleted.
1796  *      UKEY_KEEP   The ukey is fine as is.
1797  *      UKEY_MODIFY The ukey's actions should be changed but is otherwise
1798  *                  fine.  Callers should change the actions to those found
1799  *                  in the caller supplied 'odp_actions' buffer.  The
1800  *                  recirculation references can be found in 'recircs' and
1801  *                  must be handled by the caller.
1802  *
1803  * If the result is UKEY_MODIFY, then references to all recirc_ids used by the
1804  * new flow will be held within 'recircs' (which may be none).
1805  *
1806  * The caller is responsible for both initializing 'recircs' prior this call,
1807  * and ensuring any references are eventually freed.
1808  */
1809 static enum reval_result
1810 revalidate_ukey(struct udpif *udpif, struct udpif_key *ukey,
1811                 const struct dpif_flow_stats *stats,
1812                 struct ofpbuf *odp_actions, uint64_t reval_seq,
1813                 struct recirc_refs *recircs)
1814     OVS_REQUIRES(ukey->mutex)
1815 {
1816     struct xlate_out xout, *xoutp;
1817     struct netflow *netflow;
1818     struct ofproto_dpif *ofproto;
1819     struct dpif_flow_stats push;
1820     struct flow flow;
1821     struct flow_wildcards dp_mask, wc;
1822     enum reval_result result;
1823     ofp_port_t ofp_in_port;
1824     struct xlate_in xin;
1825     long long int last_used;
1826     int error;
1827     bool need_revalidate;
1828
1829     result = UKEY_DELETE;
1830     xoutp = NULL;
1831     netflow = NULL;
1832
1833     ofpbuf_clear(odp_actions);
1834     need_revalidate = (ukey->reval_seq != reval_seq);
1835     last_used = ukey->stats.used;
1836     push.used = stats->used;
1837     push.tcp_flags = stats->tcp_flags;
1838     push.n_packets = (stats->n_packets > ukey->stats.n_packets
1839                       ? stats->n_packets - ukey->stats.n_packets
1840                       : 0);
1841     push.n_bytes = (stats->n_bytes > ukey->stats.n_bytes
1842                     ? stats->n_bytes - ukey->stats.n_bytes
1843                     : 0);
1844
1845     if (need_revalidate && last_used
1846         && !should_revalidate(udpif, push.n_packets, last_used)) {
1847         goto exit;
1848     }
1849
1850     /* We will push the stats, so update the ukey stats cache. */
1851     ukey->stats = *stats;
1852     if (!push.n_packets && !need_revalidate) {
1853         result = UKEY_KEEP;
1854         goto exit;
1855     }
1856
1857     if (ukey->xcache && !need_revalidate) {
1858         xlate_push_stats(ukey->xcache, &push);
1859         result = UKEY_KEEP;
1860         goto exit;
1861     }
1862
1863     if (odp_flow_key_to_flow(ukey->key, ukey->key_len, &flow)
1864         == ODP_FIT_ERROR) {
1865         goto exit;
1866     }
1867
1868     error = xlate_lookup(udpif->backer, &flow, &ofproto, NULL, NULL, &netflow,
1869                          &ofp_in_port);
1870     if (error) {
1871         goto exit;
1872     }
1873
1874     if (need_revalidate) {
1875         xlate_cache_clear(ukey->xcache);
1876     }
1877     if (!ukey->xcache) {
1878         ukey->xcache = xlate_cache_new();
1879     }
1880
1881     xlate_in_init(&xin, ofproto, &flow, ofp_in_port, NULL, push.tcp_flags,
1882                   NULL, need_revalidate ? &wc : NULL, odp_actions);
1883     if (push.n_packets) {
1884         xin.resubmit_stats = &push;
1885         xin.may_learn = true;
1886     }
1887     xin.xcache = ukey->xcache;
1888     xlate_actions(&xin, &xout);
1889     xoutp = &xout;
1890
1891     if (!need_revalidate) {
1892         result = UKEY_KEEP;
1893         goto exit;
1894     }
1895
1896     if (xout.slow) {
1897         ofpbuf_clear(odp_actions);
1898         compose_slow_path(udpif, &xout, &flow, flow.in_port.odp_port,
1899                           odp_actions);
1900     }
1901
1902     if (odp_flow_key_to_mask(ukey->mask, ukey->mask_len, ukey->key,
1903                              ukey->key_len, &dp_mask, &flow)
1904         == ODP_FIT_ERROR) {
1905         goto exit;
1906     }
1907
1908     /* Do not modify if any bit is wildcarded by the installed datapath flow,
1909      * but not the newly revalidated wildcard mask (wc), i.e., if revalidation
1910      * tells that the datapath flow is now too generic and must be narrowed
1911      * down.  Note that we do not know if the datapath has ignored any of the
1912      * wildcarded bits, so we may be overtly conservative here. */
1913     if (flow_wildcards_has_extra(&dp_mask, &wc)) {
1914         goto exit;
1915     }
1916
1917     if (!ofpbuf_equal(odp_actions,
1918                       ovsrcu_get(struct ofpbuf *, &ukey->actions))) {
1919         /* The datapath mask was OK, but the actions seem to have changed.
1920          * Let's modify it in place. */
1921         result = UKEY_MODIFY;
1922         /* Transfer recirc action ID references to the caller. */
1923         recirc_refs_swap(recircs, &xoutp->recircs);
1924         goto exit;
1925     }
1926
1927     result = UKEY_KEEP;
1928
1929 exit:
1930     if (result != UKEY_DELETE) {
1931         ukey->reval_seq = reval_seq;
1932     }
1933     if (netflow && result == UKEY_DELETE) {
1934         netflow_flow_clear(netflow, &flow);
1935     }
1936     xlate_out_uninit(xoutp);
1937     return result;
1938 }
1939
1940 static void
1941 delete_op_init__(struct udpif *udpif, struct ukey_op *op,
1942                  const struct dpif_flow *flow)
1943 {
1944     op->ukey = NULL;
1945     op->dop.type = DPIF_OP_FLOW_DEL;
1946     op->dop.u.flow_del.key = flow->key;
1947     op->dop.u.flow_del.key_len = flow->key_len;
1948     op->dop.u.flow_del.ufid = flow->ufid_present ? &flow->ufid : NULL;
1949     op->dop.u.flow_del.pmd_id = flow->pmd_id;
1950     op->dop.u.flow_del.stats = &op->stats;
1951     op->dop.u.flow_del.terse = udpif_use_ufid(udpif);
1952 }
1953
1954 static void
1955 delete_op_init(struct udpif *udpif, struct ukey_op *op, struct udpif_key *ukey)
1956 {
1957     op->ukey = ukey;
1958     op->dop.type = DPIF_OP_FLOW_DEL;
1959     op->dop.u.flow_del.key = ukey->key;
1960     op->dop.u.flow_del.key_len = ukey->key_len;
1961     op->dop.u.flow_del.ufid = ukey->ufid_present ? &ukey->ufid : NULL;
1962     op->dop.u.flow_del.pmd_id = ukey->pmd_id;
1963     op->dop.u.flow_del.stats = &op->stats;
1964     op->dop.u.flow_del.terse = udpif_use_ufid(udpif);
1965 }
1966
1967 static void
1968 modify_op_init(struct ukey_op *op, struct udpif_key *ukey)
1969 {
1970     op->ukey = ukey;
1971     op->dop.type = DPIF_OP_FLOW_PUT;
1972     op->dop.u.flow_put.flags = DPIF_FP_MODIFY;
1973     op->dop.u.flow_put.key = ukey->key;
1974     op->dop.u.flow_put.key_len = ukey->key_len;
1975     op->dop.u.flow_put.mask = ukey->mask;
1976     op->dop.u.flow_put.mask_len = ukey->mask_len;
1977     op->dop.u.flow_put.ufid = &ukey->ufid;
1978     op->dop.u.flow_put.pmd_id = ukey->pmd_id;
1979     op->dop.u.flow_put.stats = NULL;
1980     ukey_get_actions(ukey, &op->dop.u.flow_put.actions,
1981                      &op->dop.u.flow_put.actions_len);
1982 }
1983
1984 /* Executes datapath operations 'ops' and attributes stats retrieved from the
1985  * datapath as part of those operations. */
1986 static void
1987 push_dp_ops(struct udpif *udpif, struct ukey_op *ops, size_t n_ops)
1988 {
1989     struct dpif_op *opsp[REVALIDATE_MAX_BATCH];
1990     size_t i;
1991
1992     ovs_assert(n_ops <= REVALIDATE_MAX_BATCH);
1993     for (i = 0; i < n_ops; i++) {
1994         opsp[i] = &ops[i].dop;
1995     }
1996     dpif_operate(udpif->dpif, opsp, n_ops);
1997
1998     for (i = 0; i < n_ops; i++) {
1999         struct ukey_op *op = &ops[i];
2000         struct dpif_flow_stats *push, *stats, push_buf;
2001
2002         stats = op->dop.u.flow_del.stats;
2003         push = &push_buf;
2004
2005         if (op->dop.type != DPIF_OP_FLOW_DEL) {
2006             /* Only deleted flows need their stats pushed. */
2007             continue;
2008         }
2009
2010         if (op->dop.error) {
2011             /* flow_del error, 'stats' is unusable. */
2012             continue;
2013         }
2014
2015         if (op->ukey) {
2016             ovs_mutex_lock(&op->ukey->mutex);
2017             push->used = MAX(stats->used, op->ukey->stats.used);
2018             push->tcp_flags = stats->tcp_flags | op->ukey->stats.tcp_flags;
2019             push->n_packets = stats->n_packets - op->ukey->stats.n_packets;
2020             push->n_bytes = stats->n_bytes - op->ukey->stats.n_bytes;
2021             ovs_mutex_unlock(&op->ukey->mutex);
2022         } else {
2023             push = stats;
2024         }
2025
2026         if (push->n_packets || netflow_exists()) {
2027             const struct nlattr *key = op->dop.u.flow_del.key;
2028             size_t key_len = op->dop.u.flow_del.key_len;
2029             struct ofproto_dpif *ofproto;
2030             struct netflow *netflow;
2031             ofp_port_t ofp_in_port;
2032             struct flow flow;
2033             int error;
2034
2035             if (op->ukey) {
2036                 ovs_mutex_lock(&op->ukey->mutex);
2037                 if (op->ukey->xcache) {
2038                     xlate_push_stats(op->ukey->xcache, push);
2039                     ovs_mutex_unlock(&op->ukey->mutex);
2040                     continue;
2041                 }
2042                 ovs_mutex_unlock(&op->ukey->mutex);
2043                 key = op->ukey->key;
2044                 key_len = op->ukey->key_len;
2045             }
2046
2047             if (odp_flow_key_to_flow(key, key_len, &flow)
2048                 == ODP_FIT_ERROR) {
2049                 continue;
2050             }
2051
2052             error = xlate_lookup(udpif->backer, &flow, &ofproto, NULL, NULL,
2053                                  &netflow, &ofp_in_port);
2054             if (!error) {
2055                 struct xlate_in xin;
2056
2057                 xlate_in_init(&xin, ofproto, &flow, ofp_in_port, NULL,
2058                               push->tcp_flags, NULL, NULL, NULL);
2059                 xin.resubmit_stats = push->n_packets ? push : NULL;
2060                 xin.may_learn = push->n_packets > 0;
2061                 xlate_actions_for_side_effects(&xin);
2062
2063                 if (netflow) {
2064                     netflow_flow_clear(netflow, &flow);
2065                 }
2066             }
2067         }
2068     }
2069 }
2070
2071 /* Executes datapath operations 'ops', attributes stats retrieved from the
2072  * datapath, and deletes ukeys corresponding to deleted flows. */
2073 static void
2074 push_ukey_ops(struct udpif *udpif, struct umap *umap,
2075               struct ukey_op *ops, size_t n_ops)
2076 {
2077     int i;
2078
2079     push_dp_ops(udpif, ops, n_ops);
2080     ovs_mutex_lock(&umap->mutex);
2081     for (i = 0; i < n_ops; i++) {
2082         if (ops[i].dop.type == DPIF_OP_FLOW_DEL) {
2083             ukey_delete(umap, ops[i].ukey);
2084         }
2085     }
2086     ovs_mutex_unlock(&umap->mutex);
2087 }
2088
2089 static void
2090 log_unexpected_flow(const struct dpif_flow *flow, int error)
2091 {
2092     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 60);
2093     struct ds ds = DS_EMPTY_INITIALIZER;
2094
2095     ds_put_format(&ds, "Failed to acquire udpif_key corresponding to "
2096                   "unexpected flow (%s): ", ovs_strerror(error));
2097     odp_format_ufid(&flow->ufid, &ds);
2098     VLOG_WARN_RL(&rl, "%s", ds_cstr(&ds));
2099 }
2100
2101 static void
2102 reval_op_init(struct ukey_op *op, enum reval_result result,
2103               struct udpif *udpif, struct udpif_key *ukey,
2104               struct recirc_refs *recircs, struct ofpbuf *odp_actions)
2105 {
2106     if (result == UKEY_DELETE) {
2107         delete_op_init(udpif, op, ukey);
2108     } else if (result == UKEY_MODIFY) {
2109         /* Store the new recircs. */
2110         recirc_refs_swap(&ukey->recircs, recircs);
2111         /* Release old recircs. */
2112         recirc_refs_unref(recircs);
2113         /* ukey->key_recirc_id remains, as the key is the same as before. */
2114
2115         ukey_set_actions(ukey, odp_actions);
2116         modify_op_init(op, ukey);
2117     }
2118 }
2119
2120 static void
2121 revalidate(struct revalidator *revalidator)
2122 {
2123     uint64_t odp_actions_stub[1024 / 8];
2124     struct ofpbuf odp_actions = OFPBUF_STUB_INITIALIZER(odp_actions_stub);
2125
2126     struct udpif *udpif = revalidator->udpif;
2127     struct dpif_flow_dump_thread *dump_thread;
2128     uint64_t dump_seq, reval_seq;
2129     unsigned int flow_limit;
2130
2131     dump_seq = seq_read(udpif->dump_seq);
2132     reval_seq = seq_read(udpif->reval_seq);
2133     atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
2134     dump_thread = dpif_flow_dump_thread_create(udpif->dump);
2135     for (;;) {
2136         struct ukey_op ops[REVALIDATE_MAX_BATCH];
2137         int n_ops = 0;
2138
2139         struct dpif_flow flows[REVALIDATE_MAX_BATCH];
2140         const struct dpif_flow *f;
2141         int n_dumped;
2142
2143         long long int max_idle;
2144         long long int now;
2145         size_t n_dp_flows;
2146         bool kill_them_all;
2147
2148         n_dumped = dpif_flow_dump_next(dump_thread, flows, ARRAY_SIZE(flows));
2149         if (!n_dumped) {
2150             break;
2151         }
2152
2153         now = time_msec();
2154
2155         /* In normal operation we want to keep flows around until they have
2156          * been idle for 'ofproto_max_idle' milliseconds.  However:
2157          *
2158          *     - If the number of datapath flows climbs above 'flow_limit',
2159          *       drop that down to 100 ms to try to bring the flows down to
2160          *       the limit.
2161          *
2162          *     - If the number of datapath flows climbs above twice
2163          *       'flow_limit', delete all the datapath flows as an emergency
2164          *       measure.  (We reassess this condition for the next batch of
2165          *       datapath flows, so we will recover before all the flows are
2166          *       gone.) */
2167         n_dp_flows = udpif_get_n_flows(udpif);
2168         kill_them_all = n_dp_flows > flow_limit * 2;
2169         max_idle = n_dp_flows > flow_limit ? 100 : ofproto_max_idle;
2170
2171         for (f = flows; f < &flows[n_dumped]; f++) {
2172             long long int used = f->stats.used;
2173             struct recirc_refs recircs = RECIRC_REFS_EMPTY_INITIALIZER;
2174             enum reval_result result;
2175             struct udpif_key *ukey;
2176             bool already_dumped;
2177             int error;
2178
2179             if (ukey_acquire(udpif, f, &ukey, &error)) {
2180                 if (error == EBUSY) {
2181                     /* Another thread is processing this flow, so don't bother
2182                      * processing it.*/
2183                     COVERAGE_INC(upcall_ukey_contention);
2184                 } else {
2185                     log_unexpected_flow(f, error);
2186                     if (error != ENOENT) {
2187                         delete_op_init__(udpif, &ops[n_ops++], f);
2188                     }
2189                 }
2190                 continue;
2191             }
2192
2193             already_dumped = ukey->dump_seq == dump_seq;
2194             if (already_dumped) {
2195                 /* The flow has already been handled during this flow dump
2196                  * operation. Skip it. */
2197                 if (ukey->xcache) {
2198                     COVERAGE_INC(dumped_duplicate_flow);
2199                 } else {
2200                     COVERAGE_INC(dumped_new_flow);
2201                 }
2202                 ovs_mutex_unlock(&ukey->mutex);
2203                 continue;
2204             }
2205
2206             if (!used) {
2207                 used = ukey->created;
2208             }
2209             if (kill_them_all || (used && used < now - max_idle)) {
2210                 result = UKEY_DELETE;
2211             } else {
2212                 result = revalidate_ukey(udpif, ukey, &f->stats, &odp_actions,
2213                                          reval_seq, &recircs);
2214             }
2215             ukey->dump_seq = dump_seq;
2216             ukey->flow_exists = result != UKEY_DELETE;
2217
2218             if (result != UKEY_KEEP) {
2219                 /* Takes ownership of 'recircs'. */
2220                 reval_op_init(&ops[n_ops++], result, udpif, ukey, &recircs,
2221                               &odp_actions);
2222             }
2223             ovs_mutex_unlock(&ukey->mutex);
2224         }
2225
2226         if (n_ops) {
2227             /* Push datapath ops but defer ukey deletion to 'sweep' phase. */
2228             push_dp_ops(udpif, ops, n_ops);
2229         }
2230         ovsrcu_quiesce();
2231     }
2232     dpif_flow_dump_thread_destroy(dump_thread);
2233     ofpbuf_uninit(&odp_actions);
2234 }
2235
2236 /* Pauses the 'revalidator', can only proceed after main thread
2237  * calls udpif_resume_revalidators(). */
2238 static void
2239 revalidator_pause(struct revalidator *revalidator)
2240 {
2241     /* The first block is for sync'ing the pause with main thread. */
2242     ovs_barrier_block(&revalidator->udpif->pause_barrier);
2243     /* The second block is for pausing until main thread resumes. */
2244     ovs_barrier_block(&revalidator->udpif->pause_barrier);
2245 }
2246
2247 static void
2248 revalidator_sweep__(struct revalidator *revalidator, bool purge)
2249 {
2250     struct udpif *udpif;
2251     uint64_t dump_seq, reval_seq;
2252     int slice;
2253
2254     udpif = revalidator->udpif;
2255     dump_seq = seq_read(udpif->dump_seq);
2256     reval_seq = seq_read(udpif->reval_seq);
2257     slice = revalidator - udpif->revalidators;
2258     ovs_assert(slice < udpif->n_revalidators);
2259
2260     for (int i = slice; i < N_UMAPS; i += udpif->n_revalidators) {
2261         uint64_t odp_actions_stub[1024 / 8];
2262         struct ofpbuf odp_actions = OFPBUF_STUB_INITIALIZER(odp_actions_stub);
2263
2264         struct ukey_op ops[REVALIDATE_MAX_BATCH];
2265         struct udpif_key *ukey;
2266         struct umap *umap = &udpif->ukeys[i];
2267         size_t n_ops = 0;
2268
2269         CMAP_FOR_EACH(ukey, cmap_node, &umap->cmap) {
2270             bool flow_exists;
2271
2272             /* Handler threads could be holding a ukey lock while it installs a
2273              * new flow, so don't hang around waiting for access to it. */
2274             if (ovs_mutex_trylock(&ukey->mutex)) {
2275                 continue;
2276             }
2277             flow_exists = ukey->flow_exists;
2278             if (flow_exists) {
2279                 struct recirc_refs recircs = RECIRC_REFS_EMPTY_INITIALIZER;
2280                 bool seq_mismatch = (ukey->dump_seq != dump_seq
2281                                      && ukey->reval_seq != reval_seq);
2282                 enum reval_result result;
2283
2284                 if (purge) {
2285                     result = UKEY_DELETE;
2286                 } else if (!seq_mismatch) {
2287                     result = UKEY_KEEP;
2288                 } else {
2289                     struct dpif_flow_stats stats;
2290                     COVERAGE_INC(revalidate_missed_dp_flow);
2291                     memset(&stats, 0, sizeof stats);
2292                     result = revalidate_ukey(udpif, ukey, &stats, &odp_actions,
2293                                              reval_seq, &recircs);
2294                 }
2295                 if (result != UKEY_KEEP) {
2296                     /* Clears 'recircs' if filled by revalidate_ukey(). */
2297                     reval_op_init(&ops[n_ops++], result, udpif, ukey, &recircs,
2298                                   &odp_actions);
2299                 }
2300             }
2301             ovs_mutex_unlock(&ukey->mutex);
2302
2303             if (!flow_exists) {
2304                 /* The common flow deletion case involves deletion of the flow
2305                  * during the dump phase and ukey deletion here. */
2306                 ovs_mutex_lock(&umap->mutex);
2307                 ukey_delete(umap, ukey);
2308                 ovs_mutex_unlock(&umap->mutex);
2309             }
2310
2311             if (n_ops == REVALIDATE_MAX_BATCH) {
2312                 /* Update/delete missed flows and clean up corresponding ukeys
2313                  * if necessary. */
2314                 push_ukey_ops(udpif, umap, ops, n_ops);
2315                 n_ops = 0;
2316             }
2317         }
2318
2319         if (n_ops) {
2320             push_ukey_ops(udpif, umap, ops, n_ops);
2321         }
2322
2323         ofpbuf_uninit(&odp_actions);
2324         ovsrcu_quiesce();
2325     }
2326 }
2327
2328 static void
2329 revalidator_sweep(struct revalidator *revalidator)
2330 {
2331     revalidator_sweep__(revalidator, false);
2332 }
2333
2334 static void
2335 revalidator_purge(struct revalidator *revalidator)
2336 {
2337     revalidator_sweep__(revalidator, true);
2338 }
2339
2340 /* In reaction to dpif purge, purges all 'ukey's with same 'pmd_id'. */
2341 static void
2342 dp_purge_cb(void *aux, unsigned pmd_id)
2343 {
2344     struct udpif *udpif = aux;
2345     size_t i;
2346
2347     udpif_pause_revalidators(udpif);
2348     for (i = 0; i < N_UMAPS; i++) {
2349         struct ukey_op ops[REVALIDATE_MAX_BATCH];
2350         struct udpif_key *ukey;
2351         struct umap *umap = &udpif->ukeys[i];
2352         size_t n_ops = 0;
2353
2354         CMAP_FOR_EACH(ukey, cmap_node, &umap->cmap) {
2355              if (ukey->pmd_id == pmd_id) {
2356                 delete_op_init(udpif, &ops[n_ops++], ukey);
2357                 if (n_ops == REVALIDATE_MAX_BATCH) {
2358                     push_ukey_ops(udpif, umap, ops, n_ops);
2359                     n_ops = 0;
2360                 }
2361             }
2362         }
2363
2364         if (n_ops) {
2365             push_ukey_ops(udpif, umap, ops, n_ops);
2366         }
2367
2368         ovsrcu_quiesce();
2369     }
2370     udpif_resume_revalidators(udpif);
2371 }
2372 \f
2373 static void
2374 upcall_unixctl_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
2375                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2376 {
2377     struct ds ds = DS_EMPTY_INITIALIZER;
2378     struct udpif *udpif;
2379
2380     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2381         unsigned int flow_limit;
2382         bool ufid_enabled;
2383         size_t i;
2384
2385         atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
2386         ufid_enabled = udpif_use_ufid(udpif);
2387
2388         ds_put_format(&ds, "%s:\n", dpif_name(udpif->dpif));
2389         ds_put_format(&ds, "\tflows         : (current %lu)"
2390             " (avg %u) (max %u) (limit %u)\n", udpif_get_n_flows(udpif),
2391             udpif->avg_n_flows, udpif->max_n_flows, flow_limit);
2392         ds_put_format(&ds, "\tdump duration : %lldms\n", udpif->dump_duration);
2393         ds_put_format(&ds, "\tufid enabled : ");
2394         if (ufid_enabled) {
2395             ds_put_format(&ds, "true\n");
2396         } else {
2397             ds_put_format(&ds, "false\n");
2398         }
2399         ds_put_char(&ds, '\n');
2400
2401         for (i = 0; i < n_revalidators; i++) {
2402             struct revalidator *revalidator = &udpif->revalidators[i];
2403             int j, elements = 0;
2404
2405             for (j = i; j < N_UMAPS; j += n_revalidators) {
2406                 elements += cmap_count(&udpif->ukeys[j].cmap);
2407             }
2408             ds_put_format(&ds, "\t%u: (keys %d)\n", revalidator->id, elements);
2409         }
2410     }
2411
2412     unixctl_command_reply(conn, ds_cstr(&ds));
2413     ds_destroy(&ds);
2414 }
2415
2416 /* Disable using the megaflows.
2417  *
2418  * This command is only needed for advanced debugging, so it's not
2419  * documented in the man page. */
2420 static void
2421 upcall_unixctl_disable_megaflows(struct unixctl_conn *conn,
2422                                  int argc OVS_UNUSED,
2423                                  const char *argv[] OVS_UNUSED,
2424                                  void *aux OVS_UNUSED)
2425 {
2426     atomic_store_relaxed(&enable_megaflows, false);
2427     udpif_flush_all_datapaths();
2428     unixctl_command_reply(conn, "megaflows disabled");
2429 }
2430
2431 /* Re-enable using megaflows.
2432  *
2433  * This command is only needed for advanced debugging, so it's not
2434  * documented in the man page. */
2435 static void
2436 upcall_unixctl_enable_megaflows(struct unixctl_conn *conn,
2437                                 int argc OVS_UNUSED,
2438                                 const char *argv[] OVS_UNUSED,
2439                                 void *aux OVS_UNUSED)
2440 {
2441     atomic_store_relaxed(&enable_megaflows, true);
2442     udpif_flush_all_datapaths();
2443     unixctl_command_reply(conn, "megaflows enabled");
2444 }
2445
2446 /* Disable skipping flow attributes during flow dump.
2447  *
2448  * This command is only needed for advanced debugging, so it's not
2449  * documented in the man page. */
2450 static void
2451 upcall_unixctl_disable_ufid(struct unixctl_conn *conn, int argc OVS_UNUSED,
2452                            const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2453 {
2454     atomic_store_relaxed(&enable_ufid, false);
2455     unixctl_command_reply(conn, "Datapath dumping tersely using UFID disabled");
2456 }
2457
2458 /* Re-enable skipping flow attributes during flow dump.
2459  *
2460  * This command is only needed for advanced debugging, so it's not documented
2461  * in the man page. */
2462 static void
2463 upcall_unixctl_enable_ufid(struct unixctl_conn *conn, int argc OVS_UNUSED,
2464                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2465 {
2466     atomic_store_relaxed(&enable_ufid, true);
2467     unixctl_command_reply(conn, "Datapath dumping tersely using UFID enabled "
2468                                 "for supported datapaths");
2469 }
2470
2471 /* Set the flow limit.
2472  *
2473  * This command is only needed for advanced debugging, so it's not
2474  * documented in the man page. */
2475 static void
2476 upcall_unixctl_set_flow_limit(struct unixctl_conn *conn,
2477                               int argc OVS_UNUSED,
2478                               const char *argv[] OVS_UNUSED,
2479                               void *aux OVS_UNUSED)
2480 {
2481     struct ds ds = DS_EMPTY_INITIALIZER;
2482     struct udpif *udpif;
2483     unsigned int flow_limit = atoi(argv[1]);
2484
2485     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2486         atomic_store_relaxed(&udpif->flow_limit, flow_limit);
2487     }
2488     ds_put_format(&ds, "set flow_limit to %u\n", flow_limit);
2489     unixctl_command_reply(conn, ds_cstr(&ds));
2490     ds_destroy(&ds);
2491 }
2492
2493 static void
2494 upcall_unixctl_dump_wait(struct unixctl_conn *conn,
2495                          int argc OVS_UNUSED,
2496                          const char *argv[] OVS_UNUSED,
2497                          void *aux OVS_UNUSED)
2498 {
2499     if (list_is_singleton(&all_udpifs)) {
2500         struct udpif *udpif = NULL;
2501         size_t len;
2502
2503         udpif = OBJECT_CONTAINING(list_front(&all_udpifs), udpif, list_node);
2504         len = (udpif->n_conns + 1) * sizeof *udpif->conns;
2505         udpif->conn_seq = seq_read(udpif->dump_seq);
2506         udpif->conns = xrealloc(udpif->conns, len);
2507         udpif->conns[udpif->n_conns++] = conn;
2508     } else {
2509         unixctl_command_reply_error(conn, "can't wait on multiple udpifs.");
2510     }
2511 }
2512
2513 static void
2514 upcall_unixctl_purge(struct unixctl_conn *conn, int argc OVS_UNUSED,
2515                      const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2516 {
2517     struct udpif *udpif;
2518
2519     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2520         int n;
2521
2522         for (n = 0; n < udpif->n_revalidators; n++) {
2523             revalidator_purge(&udpif->revalidators[n]);
2524         }
2525     }
2526     unixctl_command_reply(conn, "");
2527 }