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