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