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