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