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