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