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