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