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