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