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