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