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