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