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