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