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