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