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