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