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