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