ovs-thread: Make caller provide thread name when creating a thread.
[sliver-openvswitch.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 "dpif.h"
25 #include "dynamic-string.h"
26 #include "fail-open.h"
27 #include "guarded-list.h"
28 #include "latch.h"
29 #include "list.h"
30 #include "netlink.h"
31 #include "ofpbuf.h"
32 #include "ofproto-dpif-ipfix.h"
33 #include "ofproto-dpif-sflow.h"
34 #include "ofproto-dpif-xlate.h"
35 #include "ovs-rcu.h"
36 #include "packets.h"
37 #include "poll-loop.h"
38 #include "seq.h"
39 #include "unixctl.h"
40 #include "vlog.h"
41
42 #define MAX_QUEUE_LENGTH 512
43 #define FLOW_MISS_MAX_BATCH 50
44 #define REVALIDATE_MAX_BATCH 50
45
46 VLOG_DEFINE_THIS_MODULE(ofproto_dpif_upcall);
47
48 COVERAGE_DEFINE(upcall_duplicate_flow);
49
50 /* A thread that reads upcalls from dpif, forwards each upcall's packet,
51  * and possibly sets up a kernel flow as a cache. */
52 struct handler {
53     struct udpif *udpif;               /* Parent udpif. */
54     pthread_t thread;                  /* Thread ID. */
55     uint32_t handler_id;               /* Handler id. */
56 };
57
58 /* A thread that processes datapath flows, updates OpenFlow statistics, and
59  * updates or removes them if necessary. */
60 struct revalidator {
61     struct udpif *udpif;               /* Parent udpif. */
62     pthread_t thread;                  /* Thread ID. */
63     unsigned int id;                   /* ovsthread_id_self(). */
64     struct hmap *ukeys;                /* Points into udpif->ukeys for this
65                                           revalidator. Used for GC phase. */
66 };
67
68 /* An upcall handler for ofproto_dpif.
69  *
70  * udpif keeps records of two kind of logically separate units:
71  *
72  * upcall handling
73  * ---------------
74  *
75  *    - An array of 'struct handler's for upcall handling and flow
76  *      installation.
77  *
78  * flow revalidation
79  * -----------------
80  *
81  *    - Revalidation threads which read the datapath flow table and maintains
82  *      them.
83  */
84 struct udpif {
85     struct list list_node;             /* In all_udpifs list. */
86
87     struct dpif *dpif;                 /* Datapath handle. */
88     struct dpif_backer *backer;        /* Opaque dpif_backer pointer. */
89
90     uint32_t secret;                   /* Random seed for upcall hash. */
91
92     struct handler *handlers;          /* Upcall handlers. */
93     size_t n_handlers;
94
95     struct revalidator *revalidators;  /* Flow revalidators. */
96     size_t n_revalidators;
97
98     struct latch exit_latch;           /* Tells child threads to exit. */
99
100     /* Revalidation. */
101     struct seq *reval_seq;             /* Incremented to force revalidation. */
102     bool need_revalidate;              /* As indicated by 'reval_seq'. */
103     bool reval_exit;                   /* Set by leader on 'exit_latch. */
104     pthread_barrier_t reval_barrier;   /* Barrier used by revalidators. */
105     struct dpif_flow_dump dump;        /* DPIF flow dump state. */
106     long long int dump_duration;       /* Duration of the last flow dump. */
107     struct seq *dump_seq;              /* Increments each dump iteration. */
108
109     /* There are 'n_revalidators' ukey hmaps. Each revalidator retains a
110      * reference to one of these for garbage collection.
111      *
112      * During the flow dump phase, revalidators insert into these with a random
113      * distribution. During the garbage collection phase, each revalidator
114      * takes care of garbage collecting one of these hmaps. */
115     struct {
116         struct ovs_mutex mutex;        /* Guards the following. */
117         struct hmap hmap OVS_GUARDED;  /* Datapath flow keys. */
118     } *ukeys;
119
120     /* Datapath flow statistics. */
121     unsigned int max_n_flows;
122     unsigned int avg_n_flows;
123
124     /* Following fields are accessed and modified by different threads. */
125     atomic_uint flow_limit;            /* Datapath flow hard limit. */
126
127     /* n_flows_mutex prevents multiple threads updating these concurrently. */
128     atomic_uint64_t n_flows;           /* Number of flows in the datapath. */
129     atomic_llong n_flows_timestamp;    /* Last time n_flows was updated. */
130     struct ovs_mutex n_flows_mutex;
131 };
132
133 enum upcall_type {
134     BAD_UPCALL,                 /* Some kind of bug somewhere. */
135     MISS_UPCALL,                /* A flow miss.  */
136     SFLOW_UPCALL,               /* sFlow sample. */
137     FLOW_SAMPLE_UPCALL,         /* Per-flow sampling. */
138     IPFIX_UPCALL                /* Per-bridge sampling. */
139 };
140
141 struct upcall {
142     struct flow_miss *flow_miss;    /* This upcall's flow_miss. */
143
144     /* Raw upcall plus data for keeping track of the memory backing it. */
145     struct dpif_upcall dpif_upcall; /* As returned by dpif_recv() */
146     struct ofpbuf upcall_buf;       /* Owns some data in 'dpif_upcall'. */
147     uint64_t upcall_stub[512 / 8];  /* Buffer to reduce need for malloc(). */
148 };
149
150 /* 'udpif_key's are responsible for tracking the little bit of state udpif
151  * needs to do flow expiration which can't be pulled directly from the
152  * datapath.  They may be created or maintained by any revalidator during
153  * the dump phase, but are owned by a single revalidator, and are destroyed
154  * by that revalidator during the garbage-collection phase.
155  *
156  * While some elements of a udpif_key are protected by a mutex, the ukey itself
157  * is not.  Therefore it is not safe to destroy a udpif_key except when all
158  * revalidators are in garbage collection phase, or they aren't running. */
159 struct udpif_key {
160     struct hmap_node hmap_node;     /* In parent revalidator 'ukeys' map. */
161
162     /* These elements are read only once created, and therefore aren't
163      * protected by a mutex. */
164     const struct nlattr *key;      /* Datapath flow key. */
165     size_t key_len;                /* Length of 'key'. */
166
167     struct ovs_mutex mutex;                   /* Guards the following. */
168     struct dpif_flow_stats stats OVS_GUARDED; /* Last known stats.*/
169     long long int created OVS_GUARDED;        /* Estimate of creation time. */
170     bool mark OVS_GUARDED;                    /* For mark and sweep garbage
171                                                  collection. */
172     bool flow_exists OVS_GUARDED;             /* Ensures flows are only deleted
173                                                  once. */
174
175     struct xlate_cache *xcache OVS_GUARDED;   /* Cache for xlate entries that
176                                                * are affected by this ukey.
177                                                * Used for stats and learning.*/
178     struct odputil_keybuf key_buf;            /* Memory for 'key'. */
179 };
180
181 /* Flow miss batching.
182  *
183  * Some dpifs implement operations faster when you hand them off in a batch.
184  * To allow batching, "struct flow_miss" queues the dpif-related work needed
185  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
186  * more packets, plus possibly installing the flow in the dpif. */
187 struct flow_miss {
188     struct hmap_node hmap_node;
189     struct ofproto_dpif *ofproto;
190
191     struct flow flow;
192     const struct nlattr *key;
193     size_t key_len;
194     enum dpif_upcall_type upcall_type;
195     struct dpif_flow_stats stats;
196     odp_port_t odp_in_port;
197
198     uint64_t slow_path_buf[128 / 8];
199     struct odputil_keybuf mask_buf;
200
201     struct xlate_out xout;
202
203     bool put;
204 };
205
206 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
207 static struct list all_udpifs = LIST_INITIALIZER(&all_udpifs);
208
209 static size_t read_upcalls(struct handler *,
210                            struct upcall upcalls[FLOW_MISS_MAX_BATCH],
211                            struct flow_miss miss_buf[FLOW_MISS_MAX_BATCH],
212                            struct hmap *);
213 static void handle_upcalls(struct handler *, struct hmap *, struct upcall *,
214                            size_t n_upcalls);
215 static void udpif_stop_threads(struct udpif *);
216 static void udpif_start_threads(struct udpif *, size_t n_handlers,
217                                 size_t n_revalidators);
218 static void *udpif_upcall_handler(void *);
219 static void *udpif_revalidator(void *);
220 static uint64_t udpif_get_n_flows(struct udpif *);
221 static void revalidate(struct revalidator *);
222 static void revalidator_sweep(struct revalidator *);
223 static void revalidator_purge(struct revalidator *);
224 static void upcall_unixctl_show(struct unixctl_conn *conn, int argc,
225                                 const char *argv[], void *aux);
226 static void upcall_unixctl_disable_megaflows(struct unixctl_conn *, int argc,
227                                              const char *argv[], void *aux);
228 static void upcall_unixctl_enable_megaflows(struct unixctl_conn *, int argc,
229                                             const char *argv[], void *aux);
230 static void upcall_unixctl_set_flow_limit(struct unixctl_conn *conn, int argc,
231                                             const char *argv[], void *aux);
232
233 static struct udpif_key *ukey_create(const struct nlattr *key, size_t key_len,
234                                      long long int used);
235 static void ukey_delete(struct revalidator *, struct udpif_key *);
236
237 static atomic_bool enable_megaflows = ATOMIC_VAR_INIT(true);
238
239 struct udpif *
240 udpif_create(struct dpif_backer *backer, struct dpif *dpif)
241 {
242     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
243     struct udpif *udpif = xzalloc(sizeof *udpif);
244
245     if (ovsthread_once_start(&once)) {
246         unixctl_command_register("upcall/show", "", 0, 0, upcall_unixctl_show,
247                                  NULL);
248         unixctl_command_register("upcall/disable-megaflows", "", 0, 0,
249                                  upcall_unixctl_disable_megaflows, NULL);
250         unixctl_command_register("upcall/enable-megaflows", "", 0, 0,
251                                  upcall_unixctl_enable_megaflows, NULL);
252         unixctl_command_register("upcall/set-flow-limit", "", 1, 1,
253                                  upcall_unixctl_set_flow_limit, NULL);
254         ovsthread_once_done(&once);
255     }
256
257     udpif->dpif = dpif;
258     udpif->backer = backer;
259     atomic_init(&udpif->flow_limit, MIN(ofproto_flow_limit, 10000));
260     udpif->secret = random_uint32();
261     udpif->reval_seq = seq_create();
262     udpif->dump_seq = seq_create();
263     latch_init(&udpif->exit_latch);
264     list_push_back(&all_udpifs, &udpif->list_node);
265     atomic_init(&udpif->n_flows, 0);
266     atomic_init(&udpif->n_flows_timestamp, LLONG_MIN);
267     ovs_mutex_init(&udpif->n_flows_mutex);
268
269     return udpif;
270 }
271
272 void
273 udpif_destroy(struct udpif *udpif)
274 {
275     udpif_stop_threads(udpif);
276
277     list_remove(&udpif->list_node);
278     latch_destroy(&udpif->exit_latch);
279     seq_destroy(udpif->reval_seq);
280     seq_destroy(udpif->dump_seq);
281     ovs_mutex_destroy(&udpif->n_flows_mutex);
282     free(udpif);
283 }
284
285 /* Stops the handler and revalidator threads, must be enclosed in
286  * ovsrcu quiescent state unless when destroying udpif. */
287 static void
288 udpif_stop_threads(struct udpif *udpif)
289 {
290     if (udpif && (udpif->n_handlers != 0 || udpif->n_revalidators != 0)) {
291         size_t i;
292
293         latch_set(&udpif->exit_latch);
294
295         for (i = 0; i < udpif->n_handlers; i++) {
296             struct handler *handler = &udpif->handlers[i];
297
298             xpthread_join(handler->thread, NULL);
299         }
300
301         for (i = 0; i < udpif->n_revalidators; i++) {
302             xpthread_join(udpif->revalidators[i].thread, NULL);
303         }
304
305         for (i = 0; i < udpif->n_revalidators; i++) {
306             struct revalidator *revalidator = &udpif->revalidators[i];
307
308             /* Delete ukeys, and delete all flows from the datapath to prevent
309              * double-counting stats. */
310             revalidator_purge(revalidator);
311
312             hmap_destroy(&udpif->ukeys[i].hmap);
313             ovs_mutex_destroy(&udpif->ukeys[i].mutex);
314         }
315
316         latch_poll(&udpif->exit_latch);
317
318         xpthread_barrier_destroy(&udpif->reval_barrier);
319
320         free(udpif->revalidators);
321         udpif->revalidators = NULL;
322         udpif->n_revalidators = 0;
323
324         free(udpif->handlers);
325         udpif->handlers = NULL;
326         udpif->n_handlers = 0;
327
328         free(udpif->ukeys);
329         udpif->ukeys = NULL;
330     }
331 }
332
333 /* Starts the handler and revalidator threads, must be enclosed in
334  * ovsrcu quiescent state. */
335 static void
336 udpif_start_threads(struct udpif *udpif, size_t n_handlers,
337                     size_t n_revalidators)
338 {
339     if (udpif && n_handlers && n_revalidators) {
340         size_t i;
341
342         udpif->n_handlers = n_handlers;
343         udpif->n_revalidators = n_revalidators;
344
345         udpif->handlers = xzalloc(udpif->n_handlers * sizeof *udpif->handlers);
346         for (i = 0; i < udpif->n_handlers; i++) {
347             struct handler *handler = &udpif->handlers[i];
348
349             handler->udpif = udpif;
350             handler->handler_id = i;
351             handler->thread = ovs_thread_create(
352                 "handler", udpif_upcall_handler, handler);
353         }
354
355         xpthread_barrier_init(&udpif->reval_barrier, NULL,
356                               udpif->n_revalidators);
357         udpif->reval_exit = false;
358         udpif->revalidators = xzalloc(udpif->n_revalidators
359                                       * sizeof *udpif->revalidators);
360         udpif->ukeys = xmalloc(sizeof *udpif->ukeys * n_revalidators);
361         for (i = 0; i < udpif->n_revalidators; i++) {
362             struct revalidator *revalidator = &udpif->revalidators[i];
363
364             revalidator->udpif = udpif;
365             hmap_init(&udpif->ukeys[i].hmap);
366             ovs_mutex_init(&udpif->ukeys[i].mutex);
367             revalidator->ukeys = &udpif->ukeys[i].hmap;
368             revalidator->thread = ovs_thread_create(
369                 "revalidator", udpif_revalidator, revalidator);
370         }
371     }
372 }
373
374 /* Tells 'udpif' how many threads it should use to handle upcalls.
375  * 'n_handlers' and 'n_revalidators' can never be zero.  'udpif''s
376  * datapath handle must have packet reception enabled before starting
377  * threads. */
378 void
379 udpif_set_threads(struct udpif *udpif, size_t n_handlers,
380                   size_t n_revalidators)
381 {
382     int error;
383
384     ovs_assert(udpif);
385     ovs_assert(n_handlers && n_revalidators);
386
387     ovsrcu_quiesce_start();
388     if (udpif->n_handlers != n_handlers
389         || udpif->n_revalidators != n_revalidators) {
390         udpif_stop_threads(udpif);
391     }
392
393     error = dpif_handlers_set(udpif->dpif, n_handlers);
394     if (error) {
395         VLOG_ERR("failed to configure handlers in dpif %s: %s",
396                  dpif_name(udpif->dpif), ovs_strerror(error));
397         return;
398     }
399
400     if (!udpif->handlers && !udpif->revalidators) {
401         udpif_start_threads(udpif, n_handlers, n_revalidators);
402     }
403     ovsrcu_quiesce_end();
404 }
405
406 /* Waits for all ongoing upcall translations to complete.  This ensures that
407  * there are no transient references to any removed ofprotos (or other
408  * objects).  In particular, this should be called after an ofproto is removed
409  * (e.g. via xlate_remove_ofproto()) but before it is destroyed. */
410 void
411 udpif_synchronize(struct udpif *udpif)
412 {
413     /* This is stronger than necessary.  It would be sufficient to ensure
414      * (somehow) that each handler and revalidator thread had passed through
415      * its main loop once. */
416     size_t n_handlers = udpif->n_handlers;
417     size_t n_revalidators = udpif->n_revalidators;
418
419     ovsrcu_quiesce_start();
420     udpif_stop_threads(udpif);
421     udpif_start_threads(udpif, n_handlers, n_revalidators);
422     ovsrcu_quiesce_end();
423 }
424
425 /* Notifies 'udpif' that something changed which may render previous
426  * xlate_actions() results invalid. */
427 void
428 udpif_revalidate(struct udpif *udpif)
429 {
430     seq_change(udpif->reval_seq);
431 }
432
433 /* Returns a seq which increments every time 'udpif' pulls stats from the
434  * datapath.  Callers can use this to get a sense of when might be a good time
435  * to do periodic work which relies on relatively up to date statistics. */
436 struct seq *
437 udpif_dump_seq(struct udpif *udpif)
438 {
439     return udpif->dump_seq;
440 }
441
442 void
443 udpif_get_memory_usage(struct udpif *udpif, struct simap *usage)
444 {
445     size_t i;
446
447     simap_increase(usage, "handlers", udpif->n_handlers);
448
449     simap_increase(usage, "revalidators", udpif->n_revalidators);
450     for (i = 0; i < udpif->n_revalidators; i++) {
451         ovs_mutex_lock(&udpif->ukeys[i].mutex);
452         simap_increase(usage, "udpif keys", hmap_count(&udpif->ukeys[i].hmap));
453         ovs_mutex_unlock(&udpif->ukeys[i].mutex);
454     }
455 }
456
457 /* Remove flows from a single datapath. */
458 void
459 udpif_flush(struct udpif *udpif)
460 {
461     size_t n_handlers, n_revalidators;
462
463     n_handlers = udpif->n_handlers;
464     n_revalidators = udpif->n_revalidators;
465
466     ovsrcu_quiesce_start();
467
468     udpif_stop_threads(udpif);
469     dpif_flow_flush(udpif->dpif);
470     udpif_start_threads(udpif, n_handlers, n_revalidators);
471
472     ovsrcu_quiesce_end();
473 }
474
475 /* Removes all flows from all datapaths. */
476 static void
477 udpif_flush_all_datapaths(void)
478 {
479     struct udpif *udpif;
480
481     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
482         udpif_flush(udpif);
483     }
484 }
485
486 \f
487 static uint64_t
488 udpif_get_n_flows(struct udpif *udpif)
489 {
490     long long int time, now;
491     uint64_t flow_count;
492
493     now = time_msec();
494     atomic_read(&udpif->n_flows_timestamp, &time);
495     if (time < now - 100 && !ovs_mutex_trylock(&udpif->n_flows_mutex)) {
496         struct dpif_dp_stats stats;
497
498         atomic_store(&udpif->n_flows_timestamp, now);
499         dpif_get_dp_stats(udpif->dpif, &stats);
500         flow_count = stats.n_flows;
501         atomic_store(&udpif->n_flows, flow_count);
502         ovs_mutex_unlock(&udpif->n_flows_mutex);
503     } else {
504         atomic_read(&udpif->n_flows, &flow_count);
505     }
506     return flow_count;
507 }
508
509 /* The upcall handler thread tries to read a batch of FLOW_MISS_MAX_BATCH
510  * upcalls from dpif, processes the batch and installs corresponding flows
511  * in dpif. */
512 static void *
513 udpif_upcall_handler(void *arg)
514 {
515     struct handler *handler = arg;
516     struct udpif *udpif = handler->udpif;
517     struct hmap misses = HMAP_INITIALIZER(&misses);
518
519     while (!latch_is_set(&handler->udpif->exit_latch)) {
520         struct upcall upcalls[FLOW_MISS_MAX_BATCH];
521         struct flow_miss miss_buf[FLOW_MISS_MAX_BATCH];
522         struct flow_miss *miss;
523         size_t n_upcalls, i;
524
525         n_upcalls = read_upcalls(handler, upcalls, miss_buf, &misses);
526         if (!n_upcalls) {
527             dpif_recv_wait(udpif->dpif, handler->handler_id);
528             latch_wait(&udpif->exit_latch);
529             poll_block();
530         } else {
531             handle_upcalls(handler, &misses, upcalls, n_upcalls);
532
533             HMAP_FOR_EACH (miss, hmap_node, &misses) {
534                 xlate_out_uninit(&miss->xout);
535             }
536             hmap_clear(&misses);
537             for (i = 0; i < n_upcalls; i++) {
538                 ofpbuf_uninit(&upcalls[i].dpif_upcall.packet);
539                 ofpbuf_uninit(&upcalls[i].upcall_buf);
540             }
541         }
542         coverage_clear();
543     }
544     hmap_destroy(&misses);
545
546     return NULL;
547 }
548
549 static void *
550 udpif_revalidator(void *arg)
551 {
552     /* Used by all revalidators. */
553     struct revalidator *revalidator = arg;
554     struct udpif *udpif = revalidator->udpif;
555     bool leader = revalidator == &udpif->revalidators[0];
556
557     /* Used only by the leader. */
558     long long int start_time = 0;
559     uint64_t last_reval_seq = 0;
560     unsigned int flow_limit = 0;
561     size_t n_flows = 0;
562
563     revalidator->id = ovsthread_id_self();
564     for (;;) {
565         if (leader) {
566             uint64_t reval_seq;
567
568             reval_seq = seq_read(udpif->reval_seq);
569             udpif->need_revalidate = last_reval_seq != reval_seq;
570             last_reval_seq = reval_seq;
571
572             n_flows = udpif_get_n_flows(udpif);
573             udpif->max_n_flows = MAX(n_flows, udpif->max_n_flows);
574             udpif->avg_n_flows = (udpif->avg_n_flows + n_flows) / 2;
575
576             /* Only the leader checks the exit latch to prevent a race where
577              * some threads think it's true and exit and others think it's
578              * false and block indefinitely on the reval_barrier */
579             udpif->reval_exit = latch_is_set(&udpif->exit_latch);
580
581             start_time = time_msec();
582             if (!udpif->reval_exit) {
583                 dpif_flow_dump_start(&udpif->dump, udpif->dpif);
584             }
585         }
586
587         /* Wait for the leader to start the flow dump. */
588         xpthread_barrier_wait(&udpif->reval_barrier);
589         if (udpif->reval_exit) {
590             break;
591         }
592         revalidate(revalidator);
593
594         /* Wait for all flows to have been dumped before we garbage collect. */
595         xpthread_barrier_wait(&udpif->reval_barrier);
596         revalidator_sweep(revalidator);
597
598         /* Wait for all revalidators to finish garbage collection. */
599         xpthread_barrier_wait(&udpif->reval_barrier);
600
601         if (leader) {
602             long long int duration;
603
604             dpif_flow_dump_done(&udpif->dump);
605             seq_change(udpif->dump_seq);
606
607             duration = MAX(time_msec() - start_time, 1);
608             atomic_read(&udpif->flow_limit, &flow_limit);
609             udpif->dump_duration = duration;
610             if (duration > 2000) {
611                 flow_limit /= duration / 1000;
612             } else if (duration > 1300) {
613                 flow_limit = flow_limit * 3 / 4;
614             } else if (duration < 1000 && n_flows > 2000
615                        && flow_limit < n_flows * 1000 / duration) {
616                 flow_limit += 1000;
617             }
618             flow_limit = MIN(ofproto_flow_limit, MAX(flow_limit, 1000));
619             atomic_store(&udpif->flow_limit, flow_limit);
620
621             if (duration > 2000) {
622                 VLOG_INFO("Spent an unreasonably long %lldms dumping flows",
623                           duration);
624             }
625
626             poll_timer_wait_until(start_time + MIN(ofproto_max_idle, 500));
627             seq_wait(udpif->reval_seq, last_reval_seq);
628             latch_wait(&udpif->exit_latch);
629             poll_block();
630         }
631     }
632
633     return NULL;
634 }
635 \f
636 static enum upcall_type
637 classify_upcall(const struct upcall *upcall)
638 {
639     const struct dpif_upcall *dpif_upcall = &upcall->dpif_upcall;
640     union user_action_cookie cookie;
641     size_t userdata_len;
642
643     /* First look at the upcall type. */
644     switch (dpif_upcall->type) {
645     case DPIF_UC_ACTION:
646         break;
647
648     case DPIF_UC_MISS:
649         return MISS_UPCALL;
650
651     case DPIF_N_UC_TYPES:
652     default:
653         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32,
654                      dpif_upcall->type);
655         return BAD_UPCALL;
656     }
657
658     /* "action" upcalls need a closer look. */
659     if (!dpif_upcall->userdata) {
660         VLOG_WARN_RL(&rl, "action upcall missing cookie");
661         return BAD_UPCALL;
662     }
663     userdata_len = nl_attr_get_size(dpif_upcall->userdata);
664     if (userdata_len < sizeof cookie.type
665         || userdata_len > sizeof cookie) {
666         VLOG_WARN_RL(&rl, "action upcall cookie has unexpected size %"PRIuSIZE,
667                      userdata_len);
668         return BAD_UPCALL;
669     }
670     memset(&cookie, 0, sizeof cookie);
671     memcpy(&cookie, nl_attr_get(dpif_upcall->userdata), userdata_len);
672     if (userdata_len == MAX(8, sizeof cookie.sflow)
673         && cookie.type == USER_ACTION_COOKIE_SFLOW) {
674         return SFLOW_UPCALL;
675     } else if (userdata_len == MAX(8, sizeof cookie.slow_path)
676                && cookie.type == USER_ACTION_COOKIE_SLOW_PATH) {
677         return MISS_UPCALL;
678     } else if (userdata_len == MAX(8, sizeof cookie.flow_sample)
679                && cookie.type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
680         return FLOW_SAMPLE_UPCALL;
681     } else if (userdata_len == MAX(8, sizeof cookie.ipfix)
682                && cookie.type == USER_ACTION_COOKIE_IPFIX) {
683         return IPFIX_UPCALL;
684     } else {
685         VLOG_WARN_RL(&rl, "invalid user cookie of type %"PRIu16
686                      " and size %"PRIuSIZE, cookie.type, userdata_len);
687         return BAD_UPCALL;
688     }
689 }
690
691 /* Calculates slow path actions for 'xout'.  'buf' must statically be
692  * initialized with at least 128 bytes of space. */
693 static void
694 compose_slow_path(struct udpif *udpif, struct xlate_out *xout,
695                   struct flow *flow, odp_port_t odp_in_port,
696                   struct ofpbuf *buf)
697 {
698     union user_action_cookie cookie;
699     odp_port_t port;
700     uint32_t pid;
701
702     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
703     cookie.slow_path.unused = 0;
704     cookie.slow_path.reason = xout->slow;
705
706     port = xout->slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)
707         ? ODPP_NONE
708         : odp_in_port;
709     pid = dpif_port_get_pid(udpif->dpif, port, flow_hash_5tuple(flow, 0));
710     odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, buf);
711 }
712
713 static struct flow_miss *
714 flow_miss_find(struct hmap *todo, const struct ofproto_dpif *ofproto,
715                const struct flow *flow, uint32_t hash)
716 {
717     struct flow_miss *miss;
718
719     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
720         if (miss->ofproto == ofproto && flow_equal(&miss->flow, flow)) {
721             return miss;
722         }
723     }
724
725     return NULL;
726 }
727
728 /* Reads and classifies upcalls.  Returns the number of upcalls successfully
729  * read. */
730 static size_t
731 read_upcalls(struct handler *handler,
732              struct upcall upcalls[FLOW_MISS_MAX_BATCH],
733              struct flow_miss miss_buf[FLOW_MISS_MAX_BATCH],
734              struct hmap *misses)
735 {
736     struct udpif *udpif = handler->udpif;
737     size_t i;
738     size_t n_misses = 0;
739     size_t n_upcalls = 0;
740
741     /*
742      * Try reading FLOW_MISS_MAX_BATCH upcalls from dpif.
743      *
744      * Extract the flow from each upcall.  Construct in 'misses' a hash table
745      * that maps each unique flow to a 'struct flow_miss'.
746      *
747      * Most commonly there is a single packet per flow_miss, but there are
748      * several reasons why there might be more than one, e.g.:
749      *
750      *   - The dpif packet interface does not support TSO (or UFO, etc.), so a
751      *     large packet sent to userspace is split into a sequence of smaller
752      *     ones.
753      *
754      *   - A stream of quickly arriving packets in an established "slow-pathed"
755      *     flow.
756      *
757      *   - Rarely, a stream of quickly arriving packets in a flow not yet
758      *     established.  (This is rare because most protocols do not send
759      *     multiple back-to-back packets before receiving a reply from the
760      *     other end of the connection, which gives OVS a chance to set up a
761      *     datapath flow.)
762      */
763     for (i = 0; i < FLOW_MISS_MAX_BATCH; i++) {
764         struct upcall *upcall = &upcalls[n_upcalls];
765         struct flow_miss *miss = &miss_buf[n_misses];
766         struct dpif_upcall *dupcall;
767         struct ofpbuf *packet;
768         struct flow_miss *existing_miss;
769         struct ofproto_dpif *ofproto;
770         struct dpif_sflow *sflow;
771         struct dpif_ipfix *ipfix;
772         struct flow flow;
773         enum upcall_type type;
774         odp_port_t odp_in_port;
775         int error;
776
777         ofpbuf_use_stub(&upcall->upcall_buf, upcall->upcall_stub,
778                         sizeof upcall->upcall_stub);
779         error = dpif_recv(udpif->dpif, handler->handler_id,
780                           &upcall->dpif_upcall, &upcall->upcall_buf);
781         if (error) {
782             ofpbuf_uninit(&upcall->upcall_buf);
783             break;
784         }
785
786         dupcall = &upcall->dpif_upcall;
787         packet = &dupcall->packet;
788         error = xlate_receive(udpif->backer, packet, dupcall->key,
789                               dupcall->key_len, &flow,
790                               &ofproto, &ipfix, &sflow, NULL, &odp_in_port);
791         if (error) {
792             if (error == ENODEV) {
793                 /* Received packet on datapath port for which we couldn't
794                  * associate an ofproto.  This can happen if a port is removed
795                  * while traffic is being received.  Print a rate-limited
796                  * message in case it happens frequently.  Install a drop flow
797                  * so that future packets of the flow are inexpensively dropped
798                  * in the kernel. */
799                 VLOG_INFO_RL(&rl, "received packet on unassociated datapath "
800                              "port %"PRIu32, odp_in_port);
801                 dpif_flow_put(udpif->dpif, DPIF_FP_CREATE | DPIF_FP_MODIFY,
802                               dupcall->key, dupcall->key_len, NULL, 0, NULL, 0,
803                               NULL);
804             }
805             goto destroy_upcall;
806         }
807
808         type = classify_upcall(upcall);
809         if (type == MISS_UPCALL) {
810             uint32_t hash;
811             struct pkt_metadata md = pkt_metadata_from_flow(&flow);
812
813             flow_extract(packet, &md, &miss->flow);
814             hash = flow_hash(&miss->flow, 0);
815             existing_miss = flow_miss_find(misses, ofproto, &miss->flow,
816                                            hash);
817             if (!existing_miss) {
818                 hmap_insert(misses, &miss->hmap_node, hash);
819                 miss->ofproto = ofproto;
820                 miss->key = dupcall->key;
821                 miss->key_len = dupcall->key_len;
822                 miss->upcall_type = dupcall->type;
823                 miss->stats.n_packets = 0;
824                 miss->stats.n_bytes = 0;
825                 miss->stats.used = time_msec();
826                 miss->stats.tcp_flags = 0;
827                 miss->odp_in_port = odp_in_port;
828                 miss->put = false;
829                 n_misses++;
830             } else {
831                 miss = existing_miss;
832             }
833             miss->stats.tcp_flags |= ntohs(miss->flow.tcp_flags);
834             miss->stats.n_bytes += ofpbuf_size(packet);
835             miss->stats.n_packets++;
836
837             upcall->flow_miss = miss;
838             n_upcalls++;
839             continue;
840         }
841
842         switch (type) {
843         case SFLOW_UPCALL:
844             if (sflow) {
845                 union user_action_cookie cookie;
846
847                 memset(&cookie, 0, sizeof cookie);
848                 memcpy(&cookie, nl_attr_get(dupcall->userdata),
849                        sizeof cookie.sflow);
850                 dpif_sflow_received(sflow, packet, &flow, odp_in_port,
851                                     &cookie);
852             }
853             break;
854         case IPFIX_UPCALL:
855             if (ipfix) {
856                 dpif_ipfix_bridge_sample(ipfix, packet, &flow);
857             }
858             break;
859         case FLOW_SAMPLE_UPCALL:
860             if (ipfix) {
861                 union user_action_cookie cookie;
862
863                 memset(&cookie, 0, sizeof cookie);
864                 memcpy(&cookie, nl_attr_get(dupcall->userdata),
865                        sizeof cookie.flow_sample);
866
867                 /* The flow reflects exactly the contents of the packet.
868                  * Sample the packet using it. */
869                 dpif_ipfix_flow_sample(ipfix, packet, &flow,
870                                        cookie.flow_sample.collector_set_id,
871                                        cookie.flow_sample.probability,
872                                        cookie.flow_sample.obs_domain_id,
873                                        cookie.flow_sample.obs_point_id);
874             }
875             break;
876         case BAD_UPCALL:
877             break;
878         case MISS_UPCALL:
879             OVS_NOT_REACHED();
880         }
881
882         dpif_ipfix_unref(ipfix);
883         dpif_sflow_unref(sflow);
884
885 destroy_upcall:
886         ofpbuf_uninit(&upcall->dpif_upcall.packet);
887         ofpbuf_uninit(&upcall->upcall_buf);
888     }
889
890     return n_upcalls;
891 }
892
893 static void
894 handle_upcalls(struct handler *handler, struct hmap *misses,
895                struct upcall *upcalls, size_t n_upcalls)
896 {
897     struct udpif *udpif = handler->udpif;
898     struct dpif_op *opsp[FLOW_MISS_MAX_BATCH * 2];
899     struct dpif_op ops[FLOW_MISS_MAX_BATCH * 2];
900     struct flow_miss *miss;
901     size_t n_ops, i;
902     unsigned int flow_limit;
903     bool fail_open, may_put;
904
905     atomic_read(&udpif->flow_limit, &flow_limit);
906     may_put = udpif_get_n_flows(udpif) < flow_limit;
907
908     /* Initialize each 'struct flow_miss's ->xout.
909      *
910      * We do this per-flow_miss rather than per-packet because, most commonly,
911      * all the packets in a flow can use the same translation.
912      *
913      * We can't do this in the previous loop because we need the TCP flags for
914      * all the packets in each miss. */
915     fail_open = false;
916     HMAP_FOR_EACH (miss, hmap_node, misses) {
917         struct xlate_in xin;
918
919         xlate_in_init(&xin, miss->ofproto, &miss->flow, NULL,
920                       miss->stats.tcp_flags, NULL);
921         xin.may_learn = true;
922
923         if (miss->upcall_type == DPIF_UC_MISS) {
924             xin.resubmit_stats = &miss->stats;
925         } else {
926             /* For non-miss upcalls, there's a flow in the datapath which this
927              * packet was accounted to.  Presumably the revalidators will deal
928              * with pushing its stats eventually. */
929         }
930
931         xlate_actions(&xin, &miss->xout);
932         fail_open = fail_open || miss->xout.fail_open;
933     }
934
935     /* Now handle the packets individually in order of arrival.  In the common
936      * case each packet of a miss can share the same actions, but slow-pathed
937      * packets need to be translated individually:
938      *
939      *   - For SLOW_CFM, SLOW_LACP, SLOW_STP, and SLOW_BFD, translation is what
940      *     processes received packets for these protocols.
941      *
942      *   - For SLOW_CONTROLLER, translation sends the packet to the OpenFlow
943      *     controller.
944      *
945      * The loop fills 'ops' with an array of operations to execute in the
946      * datapath. */
947     n_ops = 0;
948     for (i = 0; i < n_upcalls; i++) {
949         struct upcall *upcall = &upcalls[i];
950         struct flow_miss *miss = upcall->flow_miss;
951         struct ofpbuf *packet = &upcall->dpif_upcall.packet;
952         struct dpif_op *op;
953         ovs_be16 flow_vlan_tci;
954
955         /* Save a copy of flow.vlan_tci in case it is changed to
956          * generate proper mega flow masks for VLAN splinter flows. */
957         flow_vlan_tci = miss->flow.vlan_tci;
958
959         if (miss->xout.slow) {
960             struct xlate_in xin;
961
962             xlate_in_init(&xin, miss->ofproto, &miss->flow, NULL, 0, packet);
963             xlate_actions_for_side_effects(&xin);
964         }
965
966         if (miss->flow.in_port.ofp_port
967             != vsp_realdev_to_vlandev(miss->ofproto,
968                                       miss->flow.in_port.ofp_port,
969                                       miss->flow.vlan_tci)) {
970             /* This packet was received on a VLAN splinter port.  We
971              * added a VLAN to the packet to make the packet resemble
972              * the flow, but the actions were composed assuming that
973              * the packet contained no VLAN.  So, we must remove the
974              * VLAN header from the packet before trying to execute the
975              * actions. */
976             if (ofpbuf_size(&miss->xout.odp_actions)) {
977                 eth_pop_vlan(packet);
978             }
979
980             /* Remove the flow vlan tags inserted by vlan splinter logic
981              * to ensure megaflow masks generated match the data path flow. */
982             miss->flow.vlan_tci = 0;
983         }
984
985         /* Do not install a flow into the datapath if:
986          *
987          *    - The datapath already has too many flows.
988          *
989          *    - An earlier iteration of this loop already put the same flow.
990          *
991          *    - We received this packet via some flow installed in the kernel
992          *      already. */
993         if (may_put
994             && !miss->put
995             && upcall->dpif_upcall.type == DPIF_UC_MISS) {
996             struct ofpbuf mask;
997             bool megaflow;
998
999             miss->put = true;
1000
1001             atomic_read(&enable_megaflows, &megaflow);
1002             ofpbuf_use_stack(&mask, &miss->mask_buf, sizeof miss->mask_buf);
1003             if (megaflow) {
1004                 size_t max_mpls;
1005
1006                 max_mpls = ofproto_dpif_get_max_mpls_depth(miss->ofproto);
1007                 odp_flow_key_from_mask(&mask, &miss->xout.wc.masks,
1008                                        &miss->flow, UINT32_MAX, max_mpls);
1009             }
1010
1011             op = &ops[n_ops++];
1012             op->type = DPIF_OP_FLOW_PUT;
1013             op->u.flow_put.flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
1014             op->u.flow_put.key = miss->key;
1015             op->u.flow_put.key_len = miss->key_len;
1016             op->u.flow_put.mask = ofpbuf_data(&mask);
1017             op->u.flow_put.mask_len = ofpbuf_size(&mask);
1018             op->u.flow_put.stats = NULL;
1019
1020             if (!miss->xout.slow) {
1021                 op->u.flow_put.actions = ofpbuf_data(&miss->xout.odp_actions);
1022                 op->u.flow_put.actions_len = ofpbuf_size(&miss->xout.odp_actions);
1023             } else {
1024                 struct ofpbuf buf;
1025
1026                 ofpbuf_use_stack(&buf, miss->slow_path_buf,
1027                                  sizeof miss->slow_path_buf);
1028                 compose_slow_path(udpif, &miss->xout, &miss->flow,
1029                                   miss->odp_in_port, &buf);
1030                 op->u.flow_put.actions = ofpbuf_data(&buf);
1031                 op->u.flow_put.actions_len = ofpbuf_size(&buf);
1032             }
1033         }
1034
1035         /*
1036          * The 'miss' may be shared by multiple upcalls. Restore
1037          * the saved flow vlan_tci field before processing the next
1038          * upcall. */
1039         miss->flow.vlan_tci = flow_vlan_tci;
1040
1041         if (ofpbuf_size(&miss->xout.odp_actions)) {
1042
1043             op = &ops[n_ops++];
1044             op->type = DPIF_OP_EXECUTE;
1045             op->u.execute.packet = packet;
1046             odp_key_to_pkt_metadata(miss->key, miss->key_len,
1047                                     &op->u.execute.md);
1048             op->u.execute.actions = ofpbuf_data(&miss->xout.odp_actions);
1049             op->u.execute.actions_len = ofpbuf_size(&miss->xout.odp_actions);
1050             op->u.execute.needs_help = (miss->xout.slow & SLOW_ACTION) != 0;
1051         }
1052     }
1053
1054     /* Special case for fail-open mode.
1055      *
1056      * If we are in fail-open mode, but we are connected to a controller too,
1057      * then we should send the packet up to the controller in the hope that it
1058      * will try to set up a flow and thereby allow us to exit fail-open.
1059      *
1060      * See the top-level comment in fail-open.c for more information.
1061      *
1062      * Copy packets before they are modified by execution. */
1063     if (fail_open) {
1064         for (i = 0; i < n_upcalls; i++) {
1065             struct upcall *upcall = &upcalls[i];
1066             struct flow_miss *miss = upcall->flow_miss;
1067             struct ofpbuf *packet = &upcall->dpif_upcall.packet;
1068             struct ofproto_packet_in *pin;
1069
1070             pin = xmalloc(sizeof *pin);
1071             pin->up.packet = xmemdup(ofpbuf_data(packet), ofpbuf_size(packet));
1072             pin->up.packet_len = ofpbuf_size(packet);
1073             pin->up.reason = OFPR_NO_MATCH;
1074             pin->up.table_id = 0;
1075             pin->up.cookie = OVS_BE64_MAX;
1076             flow_get_metadata(&miss->flow, &pin->up.fmd);
1077             pin->send_len = 0; /* Not used for flow table misses. */
1078             pin->miss_type = OFPROTO_PACKET_IN_NO_MISS;
1079             ofproto_dpif_send_packet_in(miss->ofproto, pin);
1080         }
1081     }
1082
1083     /* Execute batch. */
1084     for (i = 0; i < n_ops; i++) {
1085         opsp[i] = &ops[i];
1086     }
1087     dpif_operate(udpif->dpif, opsp, n_ops);
1088 }
1089
1090 /* Must be called with udpif->ukeys[hash % udpif->n_revalidators].mutex. */
1091 static struct udpif_key *
1092 ukey_lookup__(struct udpif *udpif, const struct nlattr *key, size_t key_len,
1093               uint32_t hash)
1094 {
1095     struct udpif_key *ukey;
1096     struct hmap *hmap = &udpif->ukeys[hash % udpif->n_revalidators].hmap;
1097
1098     HMAP_FOR_EACH_WITH_HASH (ukey, hmap_node, hash, hmap) {
1099         if (ukey->key_len == key_len && !memcmp(ukey->key, key, key_len)) {
1100             return ukey;
1101         }
1102     }
1103     return NULL;
1104 }
1105
1106 static struct udpif_key *
1107 ukey_lookup(struct udpif *udpif, const struct nlattr *key, size_t key_len,
1108             uint32_t hash)
1109 {
1110     struct udpif_key *ukey;
1111     uint32_t idx = hash % udpif->n_revalidators;
1112
1113     ovs_mutex_lock(&udpif->ukeys[idx].mutex);
1114     ukey = ukey_lookup__(udpif, key, key_len, hash);
1115     ovs_mutex_unlock(&udpif->ukeys[idx].mutex);
1116
1117     return ukey;
1118 }
1119
1120 static struct udpif_key *
1121 ukey_create(const struct nlattr *key, size_t key_len, long long int used)
1122 {
1123     struct udpif_key *ukey = xmalloc(sizeof *ukey);
1124     ovs_mutex_init(&ukey->mutex);
1125
1126     ukey->key = (struct nlattr *) &ukey->key_buf;
1127     memcpy(&ukey->key_buf, key, key_len);
1128     ukey->key_len = key_len;
1129
1130     ovs_mutex_lock(&ukey->mutex);
1131     ukey->mark = false;
1132     ukey->flow_exists = true;
1133     ukey->created = used ? used : time_msec();
1134     memset(&ukey->stats, 0, sizeof ukey->stats);
1135     ukey->xcache = NULL;
1136     ovs_mutex_unlock(&ukey->mutex);
1137
1138     return ukey;
1139 }
1140
1141 /* Checks for a ukey in 'udpif->ukeys' with the same 'ukey->key' and 'hash',
1142  * and inserts 'ukey' if it does not exist.
1143  *
1144  * Returns true if 'ukey' was inserted into 'udpif->ukeys', false otherwise. */
1145 static bool
1146 udpif_insert_ukey(struct udpif *udpif, struct udpif_key *ukey, uint32_t hash)
1147 {
1148     struct udpif_key *duplicate;
1149     uint32_t idx = hash % udpif->n_revalidators;
1150     bool ok;
1151
1152     ovs_mutex_lock(&udpif->ukeys[idx].mutex);
1153     duplicate = ukey_lookup__(udpif, ukey->key, ukey->key_len, hash);
1154     if (duplicate) {
1155         ok = false;
1156     } else {
1157         hmap_insert(&udpif->ukeys[idx].hmap, &ukey->hmap_node, hash);
1158         ok = true;
1159     }
1160     ovs_mutex_unlock(&udpif->ukeys[idx].mutex);
1161
1162     return ok;
1163 }
1164
1165 static void
1166 ukey_delete(struct revalidator *revalidator, struct udpif_key *ukey)
1167     OVS_NO_THREAD_SAFETY_ANALYSIS
1168 {
1169     if (revalidator) {
1170         hmap_remove(revalidator->ukeys, &ukey->hmap_node);
1171     }
1172     xlate_cache_delete(ukey->xcache);
1173     ovs_mutex_destroy(&ukey->mutex);
1174     free(ukey);
1175 }
1176
1177 static bool
1178 should_revalidate(uint64_t packets, long long int used)
1179 {
1180     long long int metric, now, duration;
1181
1182     /* Calculate the mean time between seeing these packets. If this
1183      * exceeds the threshold, then delete the flow rather than performing
1184      * costly revalidation for flows that aren't being hit frequently.
1185      *
1186      * This is targeted at situations where the dump_duration is high (~1s),
1187      * and revalidation is triggered by a call to udpif_revalidate(). In
1188      * these situations, revalidation of all flows causes fluctuations in the
1189      * flow_limit due to the interaction with the dump_duration and max_idle.
1190      * This tends to result in deletion of low-throughput flows anyway, so
1191      * skip the revalidation and just delete those flows. */
1192     packets = MAX(packets, 1);
1193     now = MAX(used, time_msec());
1194     duration = now - used;
1195     metric = duration / packets;
1196
1197     if (metric > 200) {
1198         return false;
1199     }
1200     return true;
1201 }
1202
1203 static bool
1204 revalidate_ukey(struct udpif *udpif, struct udpif_key *ukey,
1205                 const struct nlattr *mask, size_t mask_len,
1206                 const struct nlattr *actions, size_t actions_len,
1207                 const struct dpif_flow_stats *stats)
1208 {
1209     uint64_t slow_path_buf[128 / 8];
1210     struct xlate_out xout, *xoutp;
1211     struct netflow *netflow;
1212     struct ofproto_dpif *ofproto;
1213     struct dpif_flow_stats push;
1214     struct ofpbuf xout_actions;
1215     struct flow flow, dp_mask;
1216     uint32_t *dp32, *xout32;
1217     odp_port_t odp_in_port;
1218     struct xlate_in xin;
1219     long long int last_used;
1220     int error;
1221     size_t i;
1222     bool may_learn, ok;
1223
1224     ok = false;
1225     xoutp = NULL;
1226     netflow = NULL;
1227
1228     ovs_mutex_lock(&ukey->mutex);
1229     last_used = ukey->stats.used;
1230     push.used = stats->used;
1231     push.tcp_flags = stats->tcp_flags;
1232     push.n_packets = stats->n_packets > ukey->stats.n_packets
1233         ? stats->n_packets - ukey->stats.n_packets
1234         : 0;
1235     push.n_bytes = stats->n_bytes > ukey->stats.n_bytes
1236         ? stats->n_bytes - ukey->stats.n_bytes
1237         : 0;
1238
1239     if (!ukey->flow_exists) {
1240         /* Don't bother revalidating if the flow was already deleted. */
1241         goto exit;
1242     }
1243
1244     if (udpif->need_revalidate && last_used
1245         && !should_revalidate(push.n_packets, last_used)) {
1246         ok = false;
1247         goto exit;
1248     }
1249
1250     /* We will push the stats, so update the ukey stats cache. */
1251     ukey->stats = *stats;
1252     if (!push.n_packets && !udpif->need_revalidate) {
1253         ok = true;
1254         goto exit;
1255     }
1256
1257     may_learn = push.n_packets > 0;
1258     if (ukey->xcache && !udpif->need_revalidate) {
1259         xlate_push_stats(ukey->xcache, may_learn, &push);
1260         ok = true;
1261         goto exit;
1262     }
1263
1264     error = xlate_receive(udpif->backer, NULL, ukey->key, ukey->key_len, &flow,
1265                           &ofproto, NULL, NULL, &netflow, &odp_in_port);
1266     if (error) {
1267         goto exit;
1268     }
1269
1270     if (udpif->need_revalidate) {
1271         xlate_cache_clear(ukey->xcache);
1272     }
1273     if (!ukey->xcache) {
1274         ukey->xcache = xlate_cache_new();
1275     }
1276
1277     xlate_in_init(&xin, ofproto, &flow, NULL, push.tcp_flags, NULL);
1278     xin.resubmit_stats = push.n_packets ? &push : NULL;
1279     xin.xcache = ukey->xcache;
1280     xin.may_learn = may_learn;
1281     xin.skip_wildcards = !udpif->need_revalidate;
1282     xlate_actions(&xin, &xout);
1283     xoutp = &xout;
1284
1285     if (!udpif->need_revalidate) {
1286         ok = true;
1287         goto exit;
1288     }
1289
1290     if (!xout.slow) {
1291         ofpbuf_use_const(&xout_actions, ofpbuf_data(&xout.odp_actions),
1292                          ofpbuf_size(&xout.odp_actions));
1293     } else {
1294         ofpbuf_use_stack(&xout_actions, slow_path_buf, sizeof slow_path_buf);
1295         compose_slow_path(udpif, &xout, &flow, odp_in_port, &xout_actions);
1296     }
1297
1298     if (actions_len != ofpbuf_size(&xout_actions)
1299         || memcmp(ofpbuf_data(&xout_actions), actions, actions_len)) {
1300         goto exit;
1301     }
1302
1303     if (odp_flow_key_to_mask(mask, mask_len, &dp_mask, &flow)
1304         == ODP_FIT_ERROR) {
1305         goto exit;
1306     }
1307
1308     /* Since the kernel is free to ignore wildcarded bits in the mask, we can't
1309      * directly check that the masks are the same.  Instead we check that the
1310      * mask in the kernel is more specific i.e. less wildcarded, than what
1311      * we've calculated here.  This guarantees we don't catch any packets we
1312      * shouldn't with the megaflow. */
1313     dp32 = (uint32_t *) &dp_mask;
1314     xout32 = (uint32_t *) &xout.wc.masks;
1315     for (i = 0; i < FLOW_U32S; i++) {
1316         if ((dp32[i] | xout32[i]) != dp32[i]) {
1317             goto exit;
1318         }
1319     }
1320     ok = true;
1321
1322 exit:
1323     ovs_mutex_unlock(&ukey->mutex);
1324     if (netflow) {
1325         if (!ok) {
1326             netflow_expire(netflow, &flow);
1327             netflow_flow_clear(netflow, &flow);
1328         }
1329         netflow_unref(netflow);
1330     }
1331     xlate_out_uninit(xoutp);
1332     return ok;
1333 }
1334
1335 struct dump_op {
1336     struct udpif_key *ukey;
1337     struct dpif_flow_stats stats; /* Stats for 'op'. */
1338     struct dpif_op op;            /* Flow del operation. */
1339 };
1340
1341 static void
1342 dump_op_init(struct dump_op *op, const struct nlattr *key, size_t key_len,
1343              struct udpif_key *ukey)
1344 {
1345     op->ukey = ukey;
1346     op->op.type = DPIF_OP_FLOW_DEL;
1347     op->op.u.flow_del.key = key;
1348     op->op.u.flow_del.key_len = key_len;
1349     op->op.u.flow_del.stats = &op->stats;
1350 }
1351
1352 static void
1353 push_dump_ops__(struct udpif *udpif, struct dump_op *ops, size_t n_ops)
1354 {
1355     struct dpif_op *opsp[REVALIDATE_MAX_BATCH];
1356     size_t i;
1357
1358     ovs_assert(n_ops <= REVALIDATE_MAX_BATCH);
1359     for (i = 0; i < n_ops; i++) {
1360         opsp[i] = &ops[i].op;
1361     }
1362     dpif_operate(udpif->dpif, opsp, n_ops);
1363
1364     for (i = 0; i < n_ops; i++) {
1365         struct dump_op *op = &ops[i];
1366         struct dpif_flow_stats *push, *stats, push_buf;
1367
1368         stats = op->op.u.flow_del.stats;
1369         if (op->ukey) {
1370             push = &push_buf;
1371             ovs_mutex_lock(&op->ukey->mutex);
1372             push->used = MAX(stats->used, op->ukey->stats.used);
1373             push->tcp_flags = stats->tcp_flags | op->ukey->stats.tcp_flags;
1374             push->n_packets = stats->n_packets - op->ukey->stats.n_packets;
1375             push->n_bytes = stats->n_bytes - op->ukey->stats.n_bytes;
1376             ovs_mutex_unlock(&op->ukey->mutex);
1377         } else {
1378             push = stats;
1379         }
1380
1381         if (push->n_packets || netflow_exists()) {
1382             struct ofproto_dpif *ofproto;
1383             struct netflow *netflow;
1384             struct flow flow;
1385             bool may_learn;
1386
1387             may_learn = push->n_packets > 0;
1388             if (op->ukey) {
1389                 ovs_mutex_lock(&op->ukey->mutex);
1390                 if (op->ukey->xcache) {
1391                     xlate_push_stats(op->ukey->xcache, may_learn, push);
1392                     ovs_mutex_unlock(&op->ukey->mutex);
1393                     continue;
1394                 }
1395                 ovs_mutex_unlock(&op->ukey->mutex);
1396             }
1397
1398             if (!xlate_receive(udpif->backer, NULL, op->op.u.flow_del.key,
1399                                op->op.u.flow_del.key_len, &flow, &ofproto,
1400                                NULL, NULL, &netflow, NULL)) {
1401                 struct xlate_in xin;
1402
1403                 xlate_in_init(&xin, ofproto, &flow, NULL, push->tcp_flags,
1404                               NULL);
1405                 xin.resubmit_stats = push->n_packets ? push : NULL;
1406                 xin.may_learn = may_learn;
1407                 xin.skip_wildcards = true;
1408                 xlate_actions_for_side_effects(&xin);
1409
1410                 if (netflow) {
1411                     netflow_expire(netflow, &flow);
1412                     netflow_flow_clear(netflow, &flow);
1413                     netflow_unref(netflow);
1414                 }
1415             }
1416         }
1417     }
1418 }
1419
1420 static void
1421 push_dump_ops(struct revalidator *revalidator,
1422               struct dump_op *ops, size_t n_ops)
1423 {
1424     int i;
1425
1426     push_dump_ops__(revalidator->udpif, ops, n_ops);
1427     for (i = 0; i < n_ops; i++) {
1428         ukey_delete(revalidator, ops[i].ukey);
1429     }
1430 }
1431
1432 static void
1433 revalidate(struct revalidator *revalidator)
1434 {
1435     struct udpif *udpif = revalidator->udpif;
1436
1437     struct dump_op ops[REVALIDATE_MAX_BATCH];
1438     const struct nlattr *key, *mask, *actions;
1439     size_t key_len, mask_len, actions_len;
1440     const struct dpif_flow_stats *stats;
1441     long long int now;
1442     unsigned int flow_limit;
1443     size_t n_ops;
1444     void *state;
1445
1446     n_ops = 0;
1447     now = time_msec();
1448     atomic_read(&udpif->flow_limit, &flow_limit);
1449
1450     dpif_flow_dump_state_init(udpif->dpif, &state);
1451     while (dpif_flow_dump_next(&udpif->dump, state, &key, &key_len, &mask,
1452                                &mask_len, &actions, &actions_len, &stats)) {
1453         struct udpif_key *ukey;
1454         bool mark, may_destroy;
1455         long long int used, max_idle;
1456         uint32_t hash;
1457         size_t n_flows;
1458
1459         hash = hash_bytes(key, key_len, udpif->secret);
1460         ukey = ukey_lookup(udpif, key, key_len, hash);
1461
1462         used = stats->used;
1463         if (!used && ukey) {
1464             ovs_mutex_lock(&ukey->mutex);
1465
1466             if (ukey->mark || !ukey->flow_exists) {
1467                 /* The flow has already been dumped. This can occasionally
1468                  * occur if the datapath is changed in the middle of a flow
1469                  * dump. Rather than perform the same work twice, skip the
1470                  * flow this time. */
1471                 ovs_mutex_unlock(&ukey->mutex);
1472                 COVERAGE_INC(upcall_duplicate_flow);
1473                 continue;
1474             }
1475
1476             used = ukey->created;
1477             ovs_mutex_unlock(&ukey->mutex);
1478         }
1479
1480         n_flows = udpif_get_n_flows(udpif);
1481         max_idle = ofproto_max_idle;
1482         if (n_flows > flow_limit) {
1483             max_idle = 100;
1484         }
1485
1486         if ((used && used < now - max_idle) || n_flows > flow_limit * 2) {
1487             mark = false;
1488         } else {
1489             if (!ukey) {
1490                 ukey = ukey_create(key, key_len, used);
1491                 if (!udpif_insert_ukey(udpif, ukey, hash)) {
1492                     /* The same ukey has already been created. This means that
1493                      * another revalidator is processing this flow
1494                      * concurrently, so don't bother processing it. */
1495                     ukey_delete(NULL, ukey);
1496                     continue;
1497                 }
1498             }
1499
1500             mark = revalidate_ukey(udpif, ukey, mask, mask_len, actions,
1501                                    actions_len, stats);
1502         }
1503
1504         if (ukey) {
1505             ovs_mutex_lock(&ukey->mutex);
1506             ukey->mark = ukey->flow_exists = mark;
1507             ovs_mutex_unlock(&ukey->mutex);
1508         }
1509
1510         if (!mark) {
1511             dump_op_init(&ops[n_ops++], key, key_len, ukey);
1512         }
1513
1514         may_destroy = dpif_flow_dump_next_may_destroy_keys(&udpif->dump,
1515                                                            state);
1516
1517         /* Only update 'now' immediately before 'buffer' will be updated.
1518          * This gives us the current time relative to the time the datapath
1519          * will write into 'stats'. */
1520         if (may_destroy) {
1521             now = time_msec();
1522         }
1523
1524         /* Only do a dpif_operate when we've hit our maximum batch, or when our
1525          * memory is about to be clobbered by the next call to
1526          * dpif_flow_dump_next(). */
1527         if (n_ops == REVALIDATE_MAX_BATCH || (n_ops && may_destroy)) {
1528             push_dump_ops__(udpif, ops, n_ops);
1529             n_ops = 0;
1530         }
1531     }
1532
1533     if (n_ops) {
1534         push_dump_ops__(udpif, ops, n_ops);
1535     }
1536
1537     dpif_flow_dump_state_uninit(udpif->dpif, state);
1538 }
1539
1540 static void
1541 revalidator_sweep__(struct revalidator *revalidator, bool purge)
1542     OVS_NO_THREAD_SAFETY_ANALYSIS
1543 {
1544     struct dump_op ops[REVALIDATE_MAX_BATCH];
1545     struct udpif_key *ukey, *next;
1546     size_t n_ops;
1547
1548     n_ops = 0;
1549
1550     /* During garbage collection, this revalidator completely owns its ukeys
1551      * map, and therefore doesn't need to do any locking. */
1552     HMAP_FOR_EACH_SAFE (ukey, next, hmap_node, revalidator->ukeys) {
1553         if (!purge && ukey->mark) {
1554             ukey->mark = false;
1555         } else if (!ukey->flow_exists) {
1556             ukey_delete(revalidator, ukey);
1557         } else {
1558             struct dump_op *op = &ops[n_ops++];
1559
1560             /* If we have previously seen a flow in the datapath, but didn't
1561              * see it during the most recent dump, delete it. This allows us
1562              * to clean up the ukey and keep the statistics consistent. */
1563             dump_op_init(op, ukey->key, ukey->key_len, ukey);
1564             if (n_ops == REVALIDATE_MAX_BATCH) {
1565                 push_dump_ops(revalidator, ops, n_ops);
1566                 n_ops = 0;
1567             }
1568         }
1569     }
1570
1571     if (n_ops) {
1572         push_dump_ops(revalidator, ops, n_ops);
1573     }
1574 }
1575
1576 static void
1577 revalidator_sweep(struct revalidator *revalidator)
1578 {
1579     revalidator_sweep__(revalidator, false);
1580 }
1581
1582 static void
1583 revalidator_purge(struct revalidator *revalidator)
1584 {
1585     revalidator_sweep__(revalidator, true);
1586 }
1587 \f
1588 static void
1589 upcall_unixctl_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
1590                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
1591 {
1592     struct ds ds = DS_EMPTY_INITIALIZER;
1593     struct udpif *udpif;
1594
1595     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
1596         unsigned int flow_limit;
1597         size_t i;
1598
1599         atomic_read(&udpif->flow_limit, &flow_limit);
1600
1601         ds_put_format(&ds, "%s:\n", dpif_name(udpif->dpif));
1602         ds_put_format(&ds, "\tflows         : (current %"PRIu64")"
1603             " (avg %u) (max %u) (limit %u)\n", udpif_get_n_flows(udpif),
1604             udpif->avg_n_flows, udpif->max_n_flows, flow_limit);
1605         ds_put_format(&ds, "\tdump duration : %lldms\n", udpif->dump_duration);
1606
1607         ds_put_char(&ds, '\n');
1608         for (i = 0; i < n_revalidators; i++) {
1609             struct revalidator *revalidator = &udpif->revalidators[i];
1610
1611             ovs_mutex_lock(&udpif->ukeys[i].mutex);
1612             ds_put_format(&ds, "\t%u: (keys %"PRIuSIZE")\n",
1613                           revalidator->id, hmap_count(&udpif->ukeys[i].hmap));
1614             ovs_mutex_unlock(&udpif->ukeys[i].mutex);
1615         }
1616     }
1617
1618     unixctl_command_reply(conn, ds_cstr(&ds));
1619     ds_destroy(&ds);
1620 }
1621
1622 /* Disable using the megaflows.
1623  *
1624  * This command is only needed for advanced debugging, so it's not
1625  * documented in the man page. */
1626 static void
1627 upcall_unixctl_disable_megaflows(struct unixctl_conn *conn,
1628                                  int argc OVS_UNUSED,
1629                                  const char *argv[] OVS_UNUSED,
1630                                  void *aux OVS_UNUSED)
1631 {
1632     atomic_store(&enable_megaflows, false);
1633     udpif_flush_all_datapaths();
1634     unixctl_command_reply(conn, "megaflows disabled");
1635 }
1636
1637 /* Re-enable using megaflows.
1638  *
1639  * This command is only needed for advanced debugging, so it's not
1640  * documented in the man page. */
1641 static void
1642 upcall_unixctl_enable_megaflows(struct unixctl_conn *conn,
1643                                 int argc OVS_UNUSED,
1644                                 const char *argv[] OVS_UNUSED,
1645                                 void *aux OVS_UNUSED)
1646 {
1647     atomic_store(&enable_megaflows, true);
1648     udpif_flush_all_datapaths();
1649     unixctl_command_reply(conn, "megaflows enabled");
1650 }
1651
1652 /* Set the flow limit.
1653  *
1654  * This command is only needed for advanced debugging, so it's not
1655  * documented in the man page. */
1656 static void
1657 upcall_unixctl_set_flow_limit(struct unixctl_conn *conn,
1658                               int argc OVS_UNUSED,
1659                               const char *argv[] OVS_UNUSED,
1660                               void *aux OVS_UNUSED)
1661 {
1662     struct ds ds = DS_EMPTY_INITIALIZER;
1663     struct udpif *udpif;
1664     unsigned int flow_limit = atoi(argv[1]);
1665
1666     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
1667         atomic_store(&udpif->flow_limit, flow_limit);
1668     }
1669     ds_put_format(&ds, "set flow_limit to %u\n", flow_limit);
1670     unixctl_command_reply(conn, ds_cstr(&ds));
1671     ds_destroy(&ds);
1672 }