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