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