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