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