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