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