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