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