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