tunnels: Don't initialize unnecessary packet metadata.
[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 "cmap.h"
25 #include "dpif.h"
26 #include "dynamic-string.h"
27 #include "fail-open.h"
28 #include "guarded-list.h"
29 #include "latch.h"
30 #include "list.h"
31 #include "netlink.h"
32 #include "ofpbuf.h"
33 #include "ofproto-dpif-ipfix.h"
34 #include "ofproto-dpif-sflow.h"
35 #include "ofproto-dpif-xlate.h"
36 #include "ovs-rcu.h"
37 #include "packets.h"
38 #include "poll-loop.h"
39 #include "seq.h"
40 #include "unixctl.h"
41 #include "openvswitch/vlog.h"
42
43 #define MAX_QUEUE_LENGTH 512
44 #define UPCALL_MAX_BATCH 64
45 #define REVALIDATE_MAX_BATCH 50
46
47 VLOG_DEFINE_THIS_MODULE(ofproto_dpif_upcall);
48
49 COVERAGE_DEFINE(dumped_duplicate_flow);
50 COVERAGE_DEFINE(dumped_new_flow);
51 COVERAGE_DEFINE(handler_duplicate_upcall);
52 COVERAGE_DEFINE(upcall_ukey_contention);
53 COVERAGE_DEFINE(revalidate_missed_dp_flow);
54
55 /* A thread that reads upcalls from dpif, forwards each upcall's packet,
56  * and possibly sets up a kernel flow as a cache. */
57 struct handler {
58     struct udpif *udpif;               /* Parent udpif. */
59     pthread_t thread;                  /* Thread ID. */
60     uint32_t handler_id;               /* Handler id. */
61 };
62
63 /* In the absence of a multiple-writer multiple-reader datastructure for
64  * storing ukeys, we use a large number of cmaps, each with its own lock for
65  * writing. */
66 #define N_UMAPS 512 /* per udpif. */
67 struct umap {
68     struct ovs_mutex mutex;            /* Take for writing to the following. */
69     struct cmap cmap;                  /* Datapath flow keys. */
70 };
71
72 /* A thread that processes datapath flows, updates OpenFlow statistics, and
73  * updates or removes them if necessary. */
74 struct revalidator {
75     struct udpif *udpif;               /* Parent udpif. */
76     pthread_t thread;                  /* Thread ID. */
77     unsigned int id;                   /* ovsthread_id_self(). */
78 };
79
80 /* An upcall handler for ofproto_dpif.
81  *
82  * udpif keeps records of two kind of logically separate units:
83  *
84  * upcall handling
85  * ---------------
86  *
87  *    - An array of 'struct handler's for upcall handling and flow
88  *      installation.
89  *
90  * flow revalidation
91  * -----------------
92  *
93  *    - Revalidation threads which read the datapath flow table and maintains
94  *      them.
95  */
96 struct udpif {
97     struct ovs_list list_node;         /* In all_udpifs list. */
98
99     struct dpif *dpif;                 /* Datapath handle. */
100     struct dpif_backer *backer;        /* Opaque dpif_backer pointer. */
101
102     struct handler *handlers;          /* Upcall handlers. */
103     size_t n_handlers;
104
105     struct revalidator *revalidators;  /* Flow revalidators. */
106     size_t n_revalidators;
107
108     struct latch exit_latch;           /* Tells child threads to exit. */
109
110     /* Revalidation. */
111     struct seq *reval_seq;             /* Incremented to force revalidation. */
112     bool reval_exit;                   /* Set by leader on 'exit_latch. */
113     struct ovs_barrier reval_barrier;  /* Barrier used by revalidators. */
114     struct dpif_flow_dump *dump;       /* DPIF flow dump state. */
115     long long int dump_duration;       /* Duration of the last flow dump. */
116     struct seq *dump_seq;              /* Increments each dump iteration. */
117     atomic_bool enable_ufid;           /* If true, skip dumping flow attrs. */
118
119     /* There are 'N_UMAPS' maps containing 'struct udpif_key' elements.
120      *
121      * During the flow dump phase, revalidators insert into these with a random
122      * distribution. During the garbage collection phase, each revalidator
123      * takes care of garbage collecting a slice of these maps. */
124     struct umap *ukeys;
125
126     /* Datapath flow statistics. */
127     unsigned int max_n_flows;
128     unsigned int avg_n_flows;
129
130     /* Following fields are accessed and modified by different threads. */
131     atomic_uint flow_limit;            /* Datapath flow hard limit. */
132
133     /* n_flows_mutex prevents multiple threads updating these concurrently. */
134     atomic_uint n_flows;               /* Number of flows in the datapath. */
135     atomic_llong n_flows_timestamp;    /* Last time n_flows was updated. */
136     struct ovs_mutex n_flows_mutex;
137
138     /* Following fields are accessed and modified only from the main thread. */
139     struct unixctl_conn **conns;       /* Connections waiting on dump_seq. */
140     uint64_t conn_seq;                 /* Corresponds to 'dump_seq' when
141                                           conns[n_conns-1] was stored. */
142     size_t n_conns;                    /* Number of connections waiting. */
143 };
144
145 enum upcall_type {
146     BAD_UPCALL,                 /* Some kind of bug somewhere. */
147     MISS_UPCALL,                /* A flow miss.  */
148     SFLOW_UPCALL,               /* sFlow sample. */
149     FLOW_SAMPLE_UPCALL,         /* Per-flow sampling. */
150     IPFIX_UPCALL                /* Per-bridge sampling. */
151 };
152
153 struct upcall {
154     struct ofproto_dpif *ofproto;  /* Parent ofproto. */
155     const struct recirc_id_node *recirc; /* Recirculation context. */
156     bool have_recirc_ref;                /* Reference held on recirc ctx? */
157
158     /* The flow and packet are only required to be constant when using
159      * dpif-netdev.  If a modification is absolutely necessary, a const cast
160      * may be used with other datapaths. */
161     const struct flow *flow;       /* Parsed representation of the packet. */
162     const ovs_u128 *ufid;          /* Unique identifier for 'flow'. */
163     unsigned pmd_id;               /* Datapath poll mode driver id. */
164     const struct dp_packet *packet;   /* Packet associated with this upcall. */
165     ofp_port_t in_port;            /* OpenFlow in port, or OFPP_NONE. */
166
167     enum dpif_upcall_type type;    /* Datapath type of the upcall. */
168     const struct nlattr *userdata; /* Userdata for DPIF_UC_ACTION Upcalls. */
169
170     bool xout_initialized;         /* True if 'xout' must be uninitialized. */
171     struct xlate_out xout;         /* Result of xlate_actions(). */
172     struct ofpbuf put_actions;     /* Actions 'put' in the fastapath. */
173
174     struct dpif_ipfix *ipfix;      /* IPFIX pointer or NULL. */
175     struct dpif_sflow *sflow;      /* SFlow pointer or NULL. */
176
177     bool vsp_adjusted;             /* 'packet' and 'flow' were adjusted for
178                                       VLAN splinters if true. */
179
180     struct udpif_key *ukey;        /* Revalidator flow cache. */
181     bool ukey_persists;            /* Set true to keep 'ukey' beyond the
182                                       lifetime of this upcall. */
183
184     uint64_t dump_seq;             /* udpif->dump_seq at translation time. */
185     uint64_t reval_seq;            /* udpif->reval_seq at translation time. */
186
187     /* Not used by the upcall callback interface. */
188     const struct nlattr *key;      /* Datapath flow key. */
189     size_t key_len;                /* Datapath flow key length. */
190     const struct nlattr *out_tun_key;  /* Datapath output tunnel key. */
191 };
192
193 /* 'udpif_key's are responsible for tracking the little bit of state udpif
194  * needs to do flow expiration which can't be pulled directly from the
195  * datapath.  They may be created by any handler or revalidator thread at any
196  * time, and read by any revalidator during the dump phase. They are however
197  * each owned by a single revalidator which takes care of destroying them
198  * during the garbage-collection phase.
199  *
200  * The mutex within the ukey protects some members of the ukey. The ukey
201  * itself is protected by RCU and is held within a umap in the parent udpif.
202  * Adding or removing a ukey from a umap is only safe when holding the
203  * corresponding umap lock. */
204 struct udpif_key {
205     struct cmap_node cmap_node;     /* In parent revalidator 'ukeys' map. */
206
207     /* These elements are read only once created, and therefore aren't
208      * protected by a mutex. */
209     const struct nlattr *key;      /* Datapath flow key. */
210     size_t key_len;                /* Length of 'key'. */
211     const struct nlattr *mask;     /* Datapath flow mask. */
212     size_t mask_len;               /* Length of 'mask'. */
213     struct ofpbuf *actions;        /* Datapath flow actions as nlattrs. */
214     ovs_u128 ufid;                 /* Unique flow identifier. */
215     bool ufid_present;             /* True if 'ufid' is in datapath. */
216     uint32_t hash;                 /* Pre-computed hash for 'key'. */
217     unsigned pmd_id;               /* Datapath poll mode driver id. */
218
219     struct ovs_mutex mutex;                   /* Guards the following. */
220     struct dpif_flow_stats stats OVS_GUARDED; /* Last known stats.*/
221     long long int created OVS_GUARDED;        /* Estimate of creation time. */
222     uint64_t dump_seq OVS_GUARDED;            /* Tracks udpif->dump_seq. */
223     uint64_t reval_seq OVS_GUARDED;           /* Tracks udpif->reval_seq. */
224     bool flow_exists OVS_GUARDED;             /* Ensures flows are only deleted
225                                                  once. */
226
227     struct xlate_cache *xcache OVS_GUARDED;   /* Cache for xlate entries that
228                                                * are affected by this ukey.
229                                                * Used for stats and learning.*/
230     union {
231         struct odputil_keybuf buf;
232         struct nlattr nla;
233     } keybuf, maskbuf;
234
235     /* Recirculation IDs with references held by the ukey. */
236     unsigned n_recircs;
237     uint32_t recircs[];   /* 'n_recircs' id's for which references are held. */
238 };
239
240 /* Datapath operation with optional ukey attached. */
241 struct ukey_op {
242     struct udpif_key *ukey;
243     struct dpif_flow_stats stats; /* Stats for 'op'. */
244     struct dpif_op dop;           /* Flow operation. */
245 };
246
247 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
248 static struct ovs_list all_udpifs = OVS_LIST_INITIALIZER(&all_udpifs);
249
250 static size_t recv_upcalls(struct handler *);
251 static int process_upcall(struct udpif *, struct upcall *,
252                           struct ofpbuf *odp_actions);
253 static void handle_upcalls(struct udpif *, struct upcall *, size_t n_upcalls);
254 static void udpif_stop_threads(struct udpif *);
255 static void udpif_start_threads(struct udpif *, size_t n_handlers,
256                                 size_t n_revalidators);
257 static void *udpif_upcall_handler(void *);
258 static void *udpif_revalidator(void *);
259 static unsigned long udpif_get_n_flows(struct udpif *);
260 static void revalidate(struct revalidator *);
261 static void revalidator_sweep(struct revalidator *);
262 static void revalidator_purge(struct revalidator *);
263 static void upcall_unixctl_show(struct unixctl_conn *conn, int argc,
264                                 const char *argv[], void *aux);
265 static void upcall_unixctl_disable_megaflows(struct unixctl_conn *, int argc,
266                                              const char *argv[], void *aux);
267 static void upcall_unixctl_enable_megaflows(struct unixctl_conn *, int argc,
268                                             const char *argv[], void *aux);
269 static void upcall_unixctl_disable_ufid(struct unixctl_conn *, int argc,
270                                               const char *argv[], void *aux);
271 static void upcall_unixctl_enable_ufid(struct unixctl_conn *, int argc,
272                                              const char *argv[], void *aux);
273 static void upcall_unixctl_set_flow_limit(struct unixctl_conn *conn, int argc,
274                                             const char *argv[], void *aux);
275 static void upcall_unixctl_dump_wait(struct unixctl_conn *conn, int argc,
276                                      const char *argv[], void *aux);
277 static void upcall_unixctl_purge(struct unixctl_conn *conn, int argc,
278                                  const char *argv[], void *aux);
279
280 static struct udpif_key *ukey_create_from_upcall(struct upcall *);
281 static int ukey_create_from_dpif_flow(const struct udpif *,
282                                       const struct dpif_flow *,
283                                       struct udpif_key **);
284 static bool ukey_install_start(struct udpif *, struct udpif_key *ukey);
285 static bool ukey_install_finish(struct udpif_key *ukey, int error);
286 static bool ukey_install(struct udpif *udpif, struct udpif_key *ukey);
287 static struct udpif_key *ukey_lookup(struct udpif *udpif,
288                                      const ovs_u128 *ufid);
289 static int ukey_acquire(struct udpif *, const struct dpif_flow *,
290                         struct udpif_key **result, int *error);
291 static void ukey_delete__(struct udpif_key *);
292 static void ukey_delete(struct umap *, struct udpif_key *);
293 static enum upcall_type classify_upcall(enum dpif_upcall_type type,
294                                         const struct nlattr *userdata);
295
296 static int upcall_receive(struct upcall *, const struct dpif_backer *,
297                           const struct dp_packet *packet, enum dpif_upcall_type,
298                           const struct nlattr *userdata, const struct flow *,
299                           const ovs_u128 *ufid, const unsigned pmd_id);
300 static void upcall_uninit(struct upcall *);
301
302 static upcall_callback upcall_cb;
303
304 static atomic_bool enable_megaflows = ATOMIC_VAR_INIT(true);
305 static atomic_bool enable_ufid = ATOMIC_VAR_INIT(true);
306
307 struct udpif *
308 udpif_create(struct dpif_backer *backer, struct dpif *dpif)
309 {
310     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
311     struct udpif *udpif = xzalloc(sizeof *udpif);
312
313     if (ovsthread_once_start(&once)) {
314         unixctl_command_register("upcall/show", "", 0, 0, upcall_unixctl_show,
315                                  NULL);
316         unixctl_command_register("upcall/disable-megaflows", "", 0, 0,
317                                  upcall_unixctl_disable_megaflows, NULL);
318         unixctl_command_register("upcall/enable-megaflows", "", 0, 0,
319                                  upcall_unixctl_enable_megaflows, NULL);
320         unixctl_command_register("upcall/disable-ufid", "", 0, 0,
321                                  upcall_unixctl_disable_ufid, NULL);
322         unixctl_command_register("upcall/enable-ufid", "", 0, 0,
323                                  upcall_unixctl_enable_ufid, NULL);
324         unixctl_command_register("upcall/set-flow-limit", "", 1, 1,
325                                  upcall_unixctl_set_flow_limit, NULL);
326         unixctl_command_register("revalidator/wait", "", 0, 0,
327                                  upcall_unixctl_dump_wait, NULL);
328         unixctl_command_register("revalidator/purge", "", 0, 0,
329                                  upcall_unixctl_purge, NULL);
330         ovsthread_once_done(&once);
331     }
332
333     udpif->dpif = dpif;
334     udpif->backer = backer;
335     atomic_init(&udpif->flow_limit, MIN(ofproto_flow_limit, 10000));
336     udpif->reval_seq = seq_create();
337     udpif->dump_seq = seq_create();
338     latch_init(&udpif->exit_latch);
339     list_push_back(&all_udpifs, &udpif->list_node);
340     atomic_init(&udpif->enable_ufid, false);
341     atomic_init(&udpif->n_flows, 0);
342     atomic_init(&udpif->n_flows_timestamp, LLONG_MIN);
343     ovs_mutex_init(&udpif->n_flows_mutex);
344     udpif->ukeys = xmalloc(N_UMAPS * sizeof *udpif->ukeys);
345     for (int i = 0; i < N_UMAPS; i++) {
346         cmap_init(&udpif->ukeys[i].cmap);
347         ovs_mutex_init(&udpif->ukeys[i].mutex);
348     }
349
350     dpif_register_upcall_cb(dpif, upcall_cb, udpif);
351
352     return udpif;
353 }
354
355 void
356 udpif_run(struct udpif *udpif)
357 {
358     if (udpif->conns && udpif->conn_seq != seq_read(udpif->dump_seq)) {
359         int i;
360
361         for (i = 0; i < udpif->n_conns; i++) {
362             unixctl_command_reply(udpif->conns[i], NULL);
363         }
364         free(udpif->conns);
365         udpif->conns = NULL;
366         udpif->n_conns = 0;
367     }
368 }
369
370 void
371 udpif_destroy(struct udpif *udpif)
372 {
373     udpif_stop_threads(udpif);
374
375     for (int i = 0; i < N_UMAPS; i++) {
376         cmap_destroy(&udpif->ukeys[i].cmap);
377         ovs_mutex_destroy(&udpif->ukeys[i].mutex);
378     }
379     free(udpif->ukeys);
380     udpif->ukeys = NULL;
381
382     list_remove(&udpif->list_node);
383     latch_destroy(&udpif->exit_latch);
384     seq_destroy(udpif->reval_seq);
385     seq_destroy(udpif->dump_seq);
386     ovs_mutex_destroy(&udpif->n_flows_mutex);
387     free(udpif);
388 }
389
390 /* Stops the handler and revalidator threads, must be enclosed in
391  * ovsrcu quiescent state unless when destroying udpif. */
392 static void
393 udpif_stop_threads(struct udpif *udpif)
394 {
395     if (udpif && (udpif->n_handlers != 0 || udpif->n_revalidators != 0)) {
396         size_t i;
397
398         latch_set(&udpif->exit_latch);
399
400         for (i = 0; i < udpif->n_handlers; i++) {
401             struct handler *handler = &udpif->handlers[i];
402
403             xpthread_join(handler->thread, NULL);
404         }
405
406         for (i = 0; i < udpif->n_revalidators; i++) {
407             xpthread_join(udpif->revalidators[i].thread, NULL);
408         }
409
410         dpif_disable_upcall(udpif->dpif);
411
412         for (i = 0; i < udpif->n_revalidators; i++) {
413             struct revalidator *revalidator = &udpif->revalidators[i];
414
415             /* Delete ukeys, and delete all flows from the datapath to prevent
416              * double-counting stats. */
417             revalidator_purge(revalidator);
418         }
419
420         latch_poll(&udpif->exit_latch);
421
422         ovs_barrier_destroy(&udpif->reval_barrier);
423
424         free(udpif->revalidators);
425         udpif->revalidators = NULL;
426         udpif->n_revalidators = 0;
427
428         free(udpif->handlers);
429         udpif->handlers = NULL;
430         udpif->n_handlers = 0;
431     }
432 }
433
434 /* Starts the handler and revalidator threads, must be enclosed in
435  * ovsrcu quiescent state. */
436 static void
437 udpif_start_threads(struct udpif *udpif, size_t n_handlers,
438                     size_t n_revalidators)
439 {
440     if (udpif && n_handlers && n_revalidators) {
441         size_t i;
442         bool enable_ufid;
443
444         udpif->n_handlers = n_handlers;
445         udpif->n_revalidators = n_revalidators;
446
447         udpif->handlers = xzalloc(udpif->n_handlers * sizeof *udpif->handlers);
448         for (i = 0; i < udpif->n_handlers; i++) {
449             struct handler *handler = &udpif->handlers[i];
450
451             handler->udpif = udpif;
452             handler->handler_id = i;
453             handler->thread = ovs_thread_create(
454                 "handler", udpif_upcall_handler, handler);
455         }
456
457         enable_ufid = ofproto_dpif_get_enable_ufid(udpif->backer);
458         atomic_init(&udpif->enable_ufid, enable_ufid);
459         dpif_enable_upcall(udpif->dpif);
460
461         ovs_barrier_init(&udpif->reval_barrier, udpif->n_revalidators);
462         udpif->reval_exit = false;
463         udpif->revalidators = xzalloc(udpif->n_revalidators
464                                       * sizeof *udpif->revalidators);
465         for (i = 0; i < udpif->n_revalidators; i++) {
466             struct revalidator *revalidator = &udpif->revalidators[i];
467
468             revalidator->udpif = udpif;
469             revalidator->thread = ovs_thread_create(
470                 "revalidator", udpif_revalidator, revalidator);
471         }
472     }
473 }
474
475 /* Tells 'udpif' how many threads it should use to handle upcalls.
476  * 'n_handlers' and 'n_revalidators' can never be zero.  'udpif''s
477  * datapath handle must have packet reception enabled before starting
478  * threads. */
479 void
480 udpif_set_threads(struct udpif *udpif, size_t n_handlers,
481                   size_t n_revalidators)
482 {
483     ovs_assert(udpif);
484     ovs_assert(n_handlers && n_revalidators);
485
486     ovsrcu_quiesce_start();
487     if (udpif->n_handlers != n_handlers
488         || udpif->n_revalidators != n_revalidators) {
489         udpif_stop_threads(udpif);
490     }
491
492     if (!udpif->handlers && !udpif->revalidators) {
493         int error;
494
495         error = dpif_handlers_set(udpif->dpif, n_handlers);
496         if (error) {
497             VLOG_ERR("failed to configure handlers in dpif %s: %s",
498                      dpif_name(udpif->dpif), ovs_strerror(error));
499             return;
500         }
501
502         udpif_start_threads(udpif, n_handlers, n_revalidators);
503     }
504     ovsrcu_quiesce_end();
505 }
506
507 /* Waits for all ongoing upcall translations to complete.  This ensures that
508  * there are no transient references to any removed ofprotos (or other
509  * objects).  In particular, this should be called after an ofproto is removed
510  * (e.g. via xlate_remove_ofproto()) but before it is destroyed. */
511 void
512 udpif_synchronize(struct udpif *udpif)
513 {
514     /* This is stronger than necessary.  It would be sufficient to ensure
515      * (somehow) that each handler and revalidator thread had passed through
516      * its main loop once. */
517     size_t n_handlers = udpif->n_handlers;
518     size_t n_revalidators = udpif->n_revalidators;
519
520     ovsrcu_quiesce_start();
521     udpif_stop_threads(udpif);
522     udpif_start_threads(udpif, n_handlers, n_revalidators);
523     ovsrcu_quiesce_end();
524 }
525
526 /* Notifies 'udpif' that something changed which may render previous
527  * xlate_actions() results invalid. */
528 void
529 udpif_revalidate(struct udpif *udpif)
530 {
531     seq_change(udpif->reval_seq);
532 }
533
534 /* Returns a seq which increments every time 'udpif' pulls stats from the
535  * datapath.  Callers can use this to get a sense of when might be a good time
536  * to do periodic work which relies on relatively up to date statistics. */
537 struct seq *
538 udpif_dump_seq(struct udpif *udpif)
539 {
540     return udpif->dump_seq;
541 }
542
543 void
544 udpif_get_memory_usage(struct udpif *udpif, struct simap *usage)
545 {
546     size_t i;
547
548     simap_increase(usage, "handlers", udpif->n_handlers);
549
550     simap_increase(usage, "revalidators", udpif->n_revalidators);
551     for (i = 0; i < N_UMAPS; i++) {
552         simap_increase(usage, "udpif keys", cmap_count(&udpif->ukeys[i].cmap));
553     }
554 }
555
556 /* Remove flows from a single datapath. */
557 void
558 udpif_flush(struct udpif *udpif)
559 {
560     size_t n_handlers, n_revalidators;
561
562     n_handlers = udpif->n_handlers;
563     n_revalidators = udpif->n_revalidators;
564
565     ovsrcu_quiesce_start();
566
567     udpif_stop_threads(udpif);
568     dpif_flow_flush(udpif->dpif);
569     udpif_start_threads(udpif, n_handlers, n_revalidators);
570
571     ovsrcu_quiesce_end();
572 }
573
574 /* Removes all flows from all datapaths. */
575 static void
576 udpif_flush_all_datapaths(void)
577 {
578     struct udpif *udpif;
579
580     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
581         udpif_flush(udpif);
582     }
583 }
584
585 static bool
586 udpif_use_ufid(struct udpif *udpif)
587 {
588     bool enable;
589
590     atomic_read_relaxed(&enable_ufid, &enable);
591     return enable && ofproto_dpif_get_enable_ufid(udpif->backer);
592 }
593
594 \f
595 static unsigned long
596 udpif_get_n_flows(struct udpif *udpif)
597 {
598     long long int time, now;
599     unsigned long flow_count;
600
601     now = time_msec();
602     atomic_read_relaxed(&udpif->n_flows_timestamp, &time);
603     if (time < now - 100 && !ovs_mutex_trylock(&udpif->n_flows_mutex)) {
604         struct dpif_dp_stats stats;
605
606         atomic_store_relaxed(&udpif->n_flows_timestamp, now);
607         dpif_get_dp_stats(udpif->dpif, &stats);
608         flow_count = stats.n_flows;
609         atomic_store_relaxed(&udpif->n_flows, flow_count);
610         ovs_mutex_unlock(&udpif->n_flows_mutex);
611     } else {
612         atomic_read_relaxed(&udpif->n_flows, &flow_count);
613     }
614     return flow_count;
615 }
616
617 /* The upcall handler thread tries to read a batch of UPCALL_MAX_BATCH
618  * upcalls from dpif, processes the batch and installs corresponding flows
619  * in dpif. */
620 static void *
621 udpif_upcall_handler(void *arg)
622 {
623     struct handler *handler = arg;
624     struct udpif *udpif = handler->udpif;
625
626     while (!latch_is_set(&handler->udpif->exit_latch)) {
627         if (recv_upcalls(handler)) {
628             poll_immediate_wake();
629         } else {
630             dpif_recv_wait(udpif->dpif, handler->handler_id);
631             latch_wait(&udpif->exit_latch);
632         }
633         poll_block();
634     }
635
636     return NULL;
637 }
638
639 static size_t
640 recv_upcalls(struct handler *handler)
641 {
642     struct udpif *udpif = handler->udpif;
643     uint64_t recv_stubs[UPCALL_MAX_BATCH][512 / 8];
644     struct ofpbuf recv_bufs[UPCALL_MAX_BATCH];
645     struct dpif_upcall dupcalls[UPCALL_MAX_BATCH];
646     struct upcall upcalls[UPCALL_MAX_BATCH];
647     struct flow flows[UPCALL_MAX_BATCH];
648     size_t n_upcalls, i;
649
650     n_upcalls = 0;
651     while (n_upcalls < UPCALL_MAX_BATCH) {
652         struct ofpbuf *recv_buf = &recv_bufs[n_upcalls];
653         struct dpif_upcall *dupcall = &dupcalls[n_upcalls];
654         struct upcall *upcall = &upcalls[n_upcalls];
655         struct flow *flow = &flows[n_upcalls];
656         int error;
657
658         ofpbuf_use_stub(recv_buf, recv_stubs[n_upcalls],
659                         sizeof recv_stubs[n_upcalls]);
660         if (dpif_recv(udpif->dpif, handler->handler_id, dupcall, recv_buf)) {
661             ofpbuf_uninit(recv_buf);
662             break;
663         }
664
665         if (odp_flow_key_to_flow(dupcall->key, dupcall->key_len, flow)
666             == ODP_FIT_ERROR) {
667             goto free_dupcall;
668         }
669
670         error = upcall_receive(upcall, udpif->backer, &dupcall->packet,
671                                dupcall->type, dupcall->userdata, flow,
672                                &dupcall->ufid, PMD_ID_NULL);
673         if (error) {
674             if (error == ENODEV) {
675                 /* Received packet on datapath port for which we couldn't
676                  * associate an ofproto.  This can happen if a port is removed
677                  * while traffic is being received.  Print a rate-limited
678                  * message in case it happens frequently. */
679                 dpif_flow_put(udpif->dpif, DPIF_FP_CREATE, dupcall->key,
680                               dupcall->key_len, NULL, 0, NULL, 0,
681                               &dupcall->ufid, PMD_ID_NULL, NULL);
682                 VLOG_INFO_RL(&rl, "received packet on unassociated datapath "
683                              "port %"PRIu32, flow->in_port.odp_port);
684             }
685             goto free_dupcall;
686         }
687
688         upcall->key = dupcall->key;
689         upcall->key_len = dupcall->key_len;
690         upcall->ufid = &dupcall->ufid;
691
692         upcall->out_tun_key = dupcall->out_tun_key;
693
694         if (vsp_adjust_flow(upcall->ofproto, flow, &dupcall->packet)) {
695             upcall->vsp_adjusted = true;
696         }
697
698         pkt_metadata_from_flow(&dupcall->packet.md, flow);
699         flow_extract(&dupcall->packet, flow);
700
701         error = process_upcall(udpif, upcall, NULL);
702         if (error) {
703             goto cleanup;
704         }
705
706         n_upcalls++;
707         continue;
708
709 cleanup:
710         upcall_uninit(upcall);
711 free_dupcall:
712         dp_packet_uninit(&dupcall->packet);
713         ofpbuf_uninit(recv_buf);
714     }
715
716     if (n_upcalls) {
717         handle_upcalls(handler->udpif, upcalls, n_upcalls);
718         for (i = 0; i < n_upcalls; i++) {
719             dp_packet_uninit(&dupcalls[i].packet);
720             ofpbuf_uninit(&recv_bufs[i]);
721             upcall_uninit(&upcalls[i]);
722         }
723     }
724
725     return n_upcalls;
726 }
727
728 static void *
729 udpif_revalidator(void *arg)
730 {
731     /* Used by all revalidators. */
732     struct revalidator *revalidator = arg;
733     struct udpif *udpif = revalidator->udpif;
734     bool leader = revalidator == &udpif->revalidators[0];
735
736     /* Used only by the leader. */
737     long long int start_time = 0;
738     uint64_t last_reval_seq = 0;
739     size_t n_flows = 0;
740
741     revalidator->id = ovsthread_id_self();
742     for (;;) {
743         if (leader) {
744             uint64_t reval_seq;
745
746             recirc_run(); /* Recirculation cleanup. */
747
748             reval_seq = seq_read(udpif->reval_seq);
749             last_reval_seq = reval_seq;
750
751             n_flows = udpif_get_n_flows(udpif);
752             udpif->max_n_flows = MAX(n_flows, udpif->max_n_flows);
753             udpif->avg_n_flows = (udpif->avg_n_flows + n_flows) / 2;
754
755             /* Only the leader checks the exit latch to prevent a race where
756              * some threads think it's true and exit and others think it's
757              * false and block indefinitely on the reval_barrier */
758             udpif->reval_exit = latch_is_set(&udpif->exit_latch);
759
760             start_time = time_msec();
761             if (!udpif->reval_exit) {
762                 bool terse_dump;
763
764                 terse_dump = udpif_use_ufid(udpif);
765                 udpif->dump = dpif_flow_dump_create(udpif->dpif, terse_dump);
766             }
767         }
768
769         /* Wait for the leader to start the flow dump. */
770         ovs_barrier_block(&udpif->reval_barrier);
771         if (udpif->reval_exit) {
772             break;
773         }
774         revalidate(revalidator);
775
776         /* Wait for all flows to have been dumped before we garbage collect. */
777         ovs_barrier_block(&udpif->reval_barrier);
778         revalidator_sweep(revalidator);
779
780         /* Wait for all revalidators to finish garbage collection. */
781         ovs_barrier_block(&udpif->reval_barrier);
782
783         if (leader) {
784             unsigned int flow_limit;
785             long long int duration;
786
787             atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
788
789             dpif_flow_dump_destroy(udpif->dump);
790             seq_change(udpif->dump_seq);
791
792             duration = MAX(time_msec() - start_time, 1);
793             udpif->dump_duration = duration;
794             if (duration > 2000) {
795                 flow_limit /= duration / 1000;
796             } else if (duration > 1300) {
797                 flow_limit = flow_limit * 3 / 4;
798             } else if (duration < 1000 && n_flows > 2000
799                        && flow_limit < n_flows * 1000 / duration) {
800                 flow_limit += 1000;
801             }
802             flow_limit = MIN(ofproto_flow_limit, MAX(flow_limit, 1000));
803             atomic_store_relaxed(&udpif->flow_limit, flow_limit);
804
805             if (duration > 2000) {
806                 VLOG_INFO("Spent an unreasonably long %lldms dumping flows",
807                           duration);
808             }
809
810             poll_timer_wait_until(start_time + MIN(ofproto_max_idle, 500));
811             seq_wait(udpif->reval_seq, last_reval_seq);
812             latch_wait(&udpif->exit_latch);
813             poll_block();
814         }
815     }
816
817     return NULL;
818 }
819 \f
820 static enum upcall_type
821 classify_upcall(enum dpif_upcall_type type, const struct nlattr *userdata)
822 {
823     union user_action_cookie cookie;
824     size_t userdata_len;
825
826     /* First look at the upcall type. */
827     switch (type) {
828     case DPIF_UC_ACTION:
829         break;
830
831     case DPIF_UC_MISS:
832         return MISS_UPCALL;
833
834     case DPIF_N_UC_TYPES:
835     default:
836         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, type);
837         return BAD_UPCALL;
838     }
839
840     /* "action" upcalls need a closer look. */
841     if (!userdata) {
842         VLOG_WARN_RL(&rl, "action upcall missing cookie");
843         return BAD_UPCALL;
844     }
845     userdata_len = nl_attr_get_size(userdata);
846     if (userdata_len < sizeof cookie.type
847         || userdata_len > sizeof cookie) {
848         VLOG_WARN_RL(&rl, "action upcall cookie has unexpected size %"PRIuSIZE,
849                      userdata_len);
850         return BAD_UPCALL;
851     }
852     memset(&cookie, 0, sizeof cookie);
853     memcpy(&cookie, nl_attr_get(userdata), userdata_len);
854     if (userdata_len == MAX(8, sizeof cookie.sflow)
855         && cookie.type == USER_ACTION_COOKIE_SFLOW) {
856         return SFLOW_UPCALL;
857     } else if (userdata_len == MAX(8, sizeof cookie.slow_path)
858                && cookie.type == USER_ACTION_COOKIE_SLOW_PATH) {
859         return MISS_UPCALL;
860     } else if (userdata_len == MAX(8, sizeof cookie.flow_sample)
861                && cookie.type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
862         return FLOW_SAMPLE_UPCALL;
863     } else if (userdata_len == MAX(8, sizeof cookie.ipfix)
864                && cookie.type == USER_ACTION_COOKIE_IPFIX) {
865         return IPFIX_UPCALL;
866     } else {
867         VLOG_WARN_RL(&rl, "invalid user cookie of type %"PRIu16
868                      " and size %"PRIuSIZE, cookie.type, userdata_len);
869         return BAD_UPCALL;
870     }
871 }
872
873 /* Calculates slow path actions for 'xout'.  'buf' must statically be
874  * initialized with at least 128 bytes of space. */
875 static void
876 compose_slow_path(struct udpif *udpif, struct xlate_out *xout,
877                   const struct flow *flow, odp_port_t odp_in_port,
878                   struct ofpbuf *buf)
879 {
880     union user_action_cookie cookie;
881     odp_port_t port;
882     uint32_t pid;
883
884     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
885     cookie.slow_path.unused = 0;
886     cookie.slow_path.reason = xout->slow;
887
888     port = xout->slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)
889         ? ODPP_NONE
890         : odp_in_port;
891     pid = dpif_port_get_pid(udpif->dpif, port, flow_hash_5tuple(flow, 0));
892     odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, ODPP_NONE,
893                              buf);
894 }
895
896 /* If there is no error, the upcall must be destroyed with upcall_uninit()
897  * before quiescing, as the referred objects are guaranteed to exist only
898  * until the calling thread quiesces.  Otherwise, do not call upcall_uninit()
899  * since the 'upcall->put_actions' remains uninitialized. */
900 static int
901 upcall_receive(struct upcall *upcall, const struct dpif_backer *backer,
902                const struct dp_packet *packet, enum dpif_upcall_type type,
903                const struct nlattr *userdata, const struct flow *flow,
904                const ovs_u128 *ufid, const unsigned pmd_id)
905 {
906     int error;
907
908     error = xlate_lookup(backer, flow, &upcall->ofproto, &upcall->ipfix,
909                          &upcall->sflow, NULL, &upcall->in_port);
910     if (error) {
911         return error;
912     }
913
914     upcall->recirc = NULL;
915     upcall->have_recirc_ref = false;
916     upcall->flow = flow;
917     upcall->packet = packet;
918     upcall->ufid = ufid;
919     upcall->pmd_id = pmd_id;
920     upcall->type = type;
921     upcall->userdata = userdata;
922     ofpbuf_init(&upcall->put_actions, 0);
923
924     upcall->xout_initialized = false;
925     upcall->vsp_adjusted = false;
926     upcall->ukey_persists = false;
927
928     upcall->ukey = NULL;
929     upcall->key = NULL;
930     upcall->key_len = 0;
931
932     upcall->out_tun_key = NULL;
933
934     return 0;
935 }
936
937 static void
938 upcall_xlate(struct udpif *udpif, struct upcall *upcall,
939              struct ofpbuf *odp_actions)
940 {
941     struct dpif_flow_stats stats;
942     struct xlate_in xin;
943
944     stats.n_packets = 1;
945     stats.n_bytes = dp_packet_size(upcall->packet);
946     stats.used = time_msec();
947     stats.tcp_flags = ntohs(upcall->flow->tcp_flags);
948
949     xlate_in_init(&xin, upcall->ofproto, upcall->flow, upcall->in_port, NULL,
950                   stats.tcp_flags, upcall->packet);
951     xin.odp_actions = odp_actions;
952
953     if (upcall->type == DPIF_UC_MISS) {
954         xin.resubmit_stats = &stats;
955
956         if (xin.recirc) {
957             /* We may install a datapath flow only if we get a reference to the
958              * recirculation context (otherwise we could have recirculation
959              * upcalls using recirculation ID for which no context can be
960              * found).  We may still execute the flow's actions even if we
961              * don't install the flow. */
962             upcall->recirc = xin.recirc;
963             upcall->have_recirc_ref = recirc_id_node_try_ref_rcu(xin.recirc);
964         }
965     } else {
966         /* For non-miss upcalls, we are either executing actions (one of which
967          * is an userspace action) for an upcall, in which case the stats have
968          * already been taken care of, or there's a flow in the datapath which
969          * this packet was accounted to.  Presumably the revalidators will deal
970          * with pushing its stats eventually. */
971     }
972
973     upcall->dump_seq = seq_read(udpif->dump_seq);
974     upcall->reval_seq = seq_read(udpif->reval_seq);
975     xlate_actions(&xin, &upcall->xout);
976     upcall->xout_initialized = true;
977
978     /* Special case for fail-open mode.
979      *
980      * If we are in fail-open mode, but we are connected to a controller too,
981      * then we should send the packet up to the controller in the hope that it
982      * will try to set up a flow and thereby allow us to exit fail-open.
983      *
984      * See the top-level comment in fail-open.c for more information.
985      *
986      * Copy packets before they are modified by execution. */
987     if (upcall->xout.fail_open) {
988         const struct dp_packet *packet = upcall->packet;
989         struct ofproto_packet_in *pin;
990
991         pin = xmalloc(sizeof *pin);
992         pin->up.packet = xmemdup(dp_packet_data(packet), dp_packet_size(packet));
993         pin->up.packet_len = dp_packet_size(packet);
994         pin->up.reason = OFPR_NO_MATCH;
995         pin->up.table_id = 0;
996         pin->up.cookie = OVS_BE64_MAX;
997         flow_get_metadata(upcall->flow, &pin->up.flow_metadata);
998         pin->send_len = 0; /* Not used for flow table misses. */
999         pin->miss_type = OFPROTO_PACKET_IN_NO_MISS;
1000         ofproto_dpif_send_packet_in(upcall->ofproto, pin);
1001     }
1002
1003     if (!upcall->xout.slow) {
1004         ofpbuf_use_const(&upcall->put_actions,
1005                          upcall->xout.odp_actions->data,
1006                          upcall->xout.odp_actions->size);
1007     } else {
1008         ofpbuf_init(&upcall->put_actions, 0);
1009         compose_slow_path(udpif, &upcall->xout, upcall->flow,
1010                           upcall->flow->in_port.odp_port,
1011                           &upcall->put_actions);
1012     }
1013
1014     /* This function is also called for slow-pathed flows.  As we are only
1015      * going to create new datapath flows for actual datapath misses, there is
1016      * no point in creating a ukey otherwise. */
1017     if (upcall->type == DPIF_UC_MISS) {
1018         upcall->ukey = ukey_create_from_upcall(upcall);
1019     }
1020 }
1021
1022 static void
1023 upcall_uninit(struct upcall *upcall)
1024 {
1025     if (upcall) {
1026         if (upcall->xout_initialized) {
1027             xlate_out_uninit(&upcall->xout);
1028         }
1029         ofpbuf_uninit(&upcall->put_actions);
1030         if (upcall->ukey) {
1031             if (!upcall->ukey_persists) {
1032                 ukey_delete__(upcall->ukey);
1033             }
1034         } else if (upcall->have_recirc_ref) {
1035             /* The reference was transferred to the ukey if one was created. */
1036             recirc_id_node_unref(upcall->recirc);
1037         }
1038     }
1039 }
1040
1041 static int
1042 upcall_cb(const struct dp_packet *packet, const struct flow *flow, ovs_u128 *ufid,
1043           unsigned pmd_id, enum dpif_upcall_type type,
1044           const struct nlattr *userdata, struct ofpbuf *actions,
1045           struct flow_wildcards *wc, struct ofpbuf *put_actions, void *aux)
1046 {
1047     struct udpif *udpif = aux;
1048     unsigned int flow_limit;
1049     struct upcall upcall;
1050     bool megaflow;
1051     int error;
1052
1053     atomic_read_relaxed(&enable_megaflows, &megaflow);
1054     atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
1055
1056     error = upcall_receive(&upcall, udpif->backer, packet, type, userdata,
1057                            flow, ufid, pmd_id);
1058     if (error) {
1059         return error;
1060     }
1061
1062     error = process_upcall(udpif, &upcall, actions);
1063     if (error) {
1064         goto out;
1065     }
1066
1067     if (upcall.xout.slow && put_actions) {
1068         ofpbuf_put(put_actions, upcall.put_actions.data,
1069                    upcall.put_actions.size);
1070     }
1071
1072     if (OVS_LIKELY(wc)) {
1073         if (megaflow) {
1074             /* XXX: This could be avoided with sufficient API changes. */
1075             *wc = upcall.xout.wc;
1076         } else {
1077             flow_wildcards_init_for_packet(wc, flow);
1078         }
1079     }
1080
1081     if (udpif_get_n_flows(udpif) >= flow_limit) {
1082         error = ENOSPC;
1083         goto out;
1084     }
1085
1086     /* Prevent miss flow installation if the key has recirculation ID but we
1087      * were not able to get a reference on it. */
1088     if (type == DPIF_UC_MISS && upcall.recirc && !upcall.have_recirc_ref) {
1089         error = ENOSPC;
1090         goto out;
1091     }
1092
1093     if (upcall.ukey && !ukey_install(udpif, upcall.ukey)) {
1094         error = ENOSPC;
1095     }
1096 out:
1097     if (!error) {
1098         upcall.ukey_persists = true;
1099     }
1100     upcall_uninit(&upcall);
1101     return error;
1102 }
1103
1104 static int
1105 process_upcall(struct udpif *udpif, struct upcall *upcall,
1106                struct ofpbuf *odp_actions)
1107 {
1108     const struct nlattr *userdata = upcall->userdata;
1109     const struct dp_packet *packet = upcall->packet;
1110     const struct flow *flow = upcall->flow;
1111
1112     switch (classify_upcall(upcall->type, userdata)) {
1113     case MISS_UPCALL:
1114         upcall_xlate(udpif, upcall, odp_actions);
1115         return 0;
1116
1117     case SFLOW_UPCALL:
1118         if (upcall->sflow) {
1119             union user_action_cookie cookie;
1120
1121             memset(&cookie, 0, sizeof cookie);
1122             memcpy(&cookie, nl_attr_get(userdata), sizeof cookie.sflow);
1123             dpif_sflow_received(upcall->sflow, packet, flow,
1124                                 flow->in_port.odp_port, &cookie);
1125         }
1126         break;
1127
1128     case IPFIX_UPCALL:
1129         if (upcall->ipfix) {
1130             union user_action_cookie cookie;
1131             struct flow_tnl output_tunnel_key;
1132
1133             memset(&cookie, 0, sizeof cookie);
1134             memcpy(&cookie, nl_attr_get(userdata), sizeof cookie.ipfix);
1135
1136             if (upcall->out_tun_key) {
1137                 odp_tun_key_from_attr(upcall->out_tun_key,
1138                                       &output_tunnel_key);
1139             }
1140             dpif_ipfix_bridge_sample(upcall->ipfix, packet, flow,
1141                                      flow->in_port.odp_port,
1142                                      cookie.ipfix.output_odp_port,
1143                                      upcall->out_tun_key ?
1144                                          &output_tunnel_key : NULL);
1145         }
1146         break;
1147
1148     case FLOW_SAMPLE_UPCALL:
1149         if (upcall->ipfix) {
1150             union user_action_cookie cookie;
1151
1152             memset(&cookie, 0, sizeof cookie);
1153             memcpy(&cookie, nl_attr_get(userdata), sizeof cookie.flow_sample);
1154
1155             /* The flow reflects exactly the contents of the packet.
1156              * Sample the packet using it. */
1157             dpif_ipfix_flow_sample(upcall->ipfix, packet, flow,
1158                                    cookie.flow_sample.collector_set_id,
1159                                    cookie.flow_sample.probability,
1160                                    cookie.flow_sample.obs_domain_id,
1161                                    cookie.flow_sample.obs_point_id);
1162         }
1163         break;
1164
1165     case BAD_UPCALL:
1166         break;
1167     }
1168
1169     return EAGAIN;
1170 }
1171
1172 static void
1173 handle_upcalls(struct udpif *udpif, struct upcall *upcalls,
1174                size_t n_upcalls)
1175 {
1176     struct dpif_op *opsp[UPCALL_MAX_BATCH * 2];
1177     struct ukey_op ops[UPCALL_MAX_BATCH * 2];
1178     unsigned int flow_limit;
1179     size_t n_ops, n_opsp, i;
1180     bool may_put;
1181     bool megaflow;
1182
1183     atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
1184     atomic_read_relaxed(&enable_megaflows, &megaflow);
1185
1186     may_put = udpif_get_n_flows(udpif) < flow_limit;
1187
1188     /* Handle the packets individually in order of arrival.
1189      *
1190      *   - For SLOW_CFM, SLOW_LACP, SLOW_STP, and SLOW_BFD, translation is what
1191      *     processes received packets for these protocols.
1192      *
1193      *   - For SLOW_CONTROLLER, translation sends the packet to the OpenFlow
1194      *     controller.
1195      *
1196      * The loop fills 'ops' with an array of operations to execute in the
1197      * datapath. */
1198     n_ops = 0;
1199     for (i = 0; i < n_upcalls; i++) {
1200         struct upcall *upcall = &upcalls[i];
1201         const struct dp_packet *packet = upcall->packet;
1202         struct ukey_op *op;
1203
1204         if (upcall->vsp_adjusted) {
1205             /* This packet was received on a VLAN splinter port.  We added a
1206              * VLAN to the packet to make the packet resemble the flow, but the
1207              * actions were composed assuming that the packet contained no
1208              * VLAN.  So, we must remove the VLAN header from the packet before
1209              * trying to execute the actions. */
1210             if (upcall->xout.odp_actions->size) {
1211                 eth_pop_vlan(CONST_CAST(struct dp_packet *, upcall->packet));
1212             }
1213
1214             /* Remove the flow vlan tags inserted by vlan splinter logic
1215              * to ensure megaflow masks generated match the data path flow. */
1216             CONST_CAST(struct flow *, upcall->flow)->vlan_tci = 0;
1217         }
1218
1219         /* Do not install a flow into the datapath if:
1220          *
1221          *    - The datapath already has too many flows.
1222          *
1223          *    - We received this packet via some flow installed in the kernel
1224          *      already.
1225          *
1226          *    - Upcall was a recirculation but we do not have a reference to
1227          *      to the recirculation ID. */
1228         if (may_put && upcall->type == DPIF_UC_MISS &&
1229             (!upcall->recirc || upcall->have_recirc_ref)) {
1230             struct udpif_key *ukey = upcall->ukey;
1231
1232             upcall->ukey_persists = true;
1233             op = &ops[n_ops++];
1234
1235             op->ukey = ukey;
1236             op->dop.type = DPIF_OP_FLOW_PUT;
1237             op->dop.u.flow_put.flags = DPIF_FP_CREATE;
1238             op->dop.u.flow_put.key = ukey->key;
1239             op->dop.u.flow_put.key_len = ukey->key_len;
1240             op->dop.u.flow_put.mask = ukey->mask;
1241             op->dop.u.flow_put.mask_len = ukey->mask_len;
1242             op->dop.u.flow_put.ufid = upcall->ufid;
1243             op->dop.u.flow_put.stats = NULL;
1244             op->dop.u.flow_put.actions = ukey->actions->data;
1245             op->dop.u.flow_put.actions_len = ukey->actions->size;
1246         }
1247
1248         if (upcall->xout.odp_actions->size) {
1249             op = &ops[n_ops++];
1250             op->ukey = NULL;
1251             op->dop.type = DPIF_OP_EXECUTE;
1252             op->dop.u.execute.packet = CONST_CAST(struct dp_packet *, packet);
1253             odp_key_to_pkt_metadata(upcall->key, upcall->key_len,
1254                                     &op->dop.u.execute.packet->md);
1255             op->dop.u.execute.actions = upcall->xout.odp_actions->data;
1256             op->dop.u.execute.actions_len = upcall->xout.odp_actions->size;
1257             op->dop.u.execute.needs_help = (upcall->xout.slow & SLOW_ACTION) != 0;
1258             op->dop.u.execute.probe = false;
1259         }
1260     }
1261
1262     /* Execute batch.
1263      *
1264      * We install ukeys before installing the flows, locking them for exclusive
1265      * access by this thread for the period of installation. This ensures that
1266      * other threads won't attempt to delete the flows as we are creating them.
1267      */
1268     n_opsp = 0;
1269     for (i = 0; i < n_ops; i++) {
1270         struct udpif_key *ukey = ops[i].ukey;
1271
1272         if (ukey) {
1273             /* If we can't install the ukey, don't install the flow. */
1274             if (!ukey_install_start(udpif, ukey)) {
1275                 ukey_delete__(ukey);
1276                 ops[i].ukey = NULL;
1277                 continue;
1278             }
1279         }
1280         opsp[n_opsp++] = &ops[i].dop;
1281     }
1282     dpif_operate(udpif->dpif, opsp, n_opsp);
1283     for (i = 0; i < n_ops; i++) {
1284         if (ops[i].ukey) {
1285             ukey_install_finish(ops[i].ukey, ops[i].dop.error);
1286         }
1287     }
1288 }
1289
1290 static uint32_t
1291 get_ufid_hash(const ovs_u128 *ufid)
1292 {
1293     return ufid->u32[0];
1294 }
1295
1296 static struct udpif_key *
1297 ukey_lookup(struct udpif *udpif, const ovs_u128 *ufid)
1298 {
1299     struct udpif_key *ukey;
1300     int idx = get_ufid_hash(ufid) % N_UMAPS;
1301     struct cmap *cmap = &udpif->ukeys[idx].cmap;
1302
1303     CMAP_FOR_EACH_WITH_HASH (ukey, cmap_node, get_ufid_hash(ufid), cmap) {
1304         if (ovs_u128_equals(&ukey->ufid, ufid)) {
1305             return ukey;
1306         }
1307     }
1308     return NULL;
1309 }
1310
1311 static struct udpif_key *
1312 ukey_create__(const struct nlattr *key, size_t key_len,
1313               const struct nlattr *mask, size_t mask_len,
1314               bool ufid_present, const ovs_u128 *ufid,
1315               const unsigned pmd_id, const struct ofpbuf *actions,
1316               uint64_t dump_seq, uint64_t reval_seq, long long int used,
1317               const struct recirc_id_node *key_recirc, struct xlate_out *xout)
1318     OVS_NO_THREAD_SAFETY_ANALYSIS
1319 {
1320     unsigned n_recircs = (key_recirc ? 1 : 0) + (xout ? xout->n_recircs : 0);
1321     struct udpif_key *ukey = xmalloc(sizeof *ukey +
1322                                      n_recircs * sizeof *ukey->recircs);
1323
1324     memcpy(&ukey->keybuf, key, key_len);
1325     ukey->key = &ukey->keybuf.nla;
1326     ukey->key_len = key_len;
1327     memcpy(&ukey->maskbuf, mask, mask_len);
1328     ukey->mask = &ukey->maskbuf.nla;
1329     ukey->mask_len = mask_len;
1330     ukey->ufid_present = ufid_present;
1331     ukey->ufid = *ufid;
1332     ukey->pmd_id = pmd_id;
1333     ukey->hash = get_ufid_hash(&ukey->ufid);
1334     ukey->actions = ofpbuf_clone(actions);
1335
1336     ovs_mutex_init(&ukey->mutex);
1337     ukey->dump_seq = dump_seq;
1338     ukey->reval_seq = reval_seq;
1339     ukey->flow_exists = false;
1340     ukey->created = time_msec();
1341     memset(&ukey->stats, 0, sizeof ukey->stats);
1342     ukey->stats.used = used;
1343     ukey->xcache = NULL;
1344
1345     ukey->n_recircs = n_recircs;
1346     if (key_recirc) {
1347         ukey->recircs[0] = key_recirc->id;
1348     }
1349     if (xout && xout->n_recircs) {
1350         const uint32_t *act_recircs = xlate_out_get_recircs(xout);
1351
1352         memcpy(ukey->recircs + (key_recirc ? 1 : 0), act_recircs,
1353                xout->n_recircs * sizeof *ukey->recircs);
1354         xlate_out_take_recircs(xout);
1355     }
1356     return ukey;
1357 }
1358
1359 static struct udpif_key *
1360 ukey_create_from_upcall(struct upcall *upcall)
1361 {
1362     struct odputil_keybuf keystub, maskstub;
1363     struct ofpbuf keybuf, maskbuf;
1364     bool recirc, megaflow;
1365     struct odp_flow_key_parms odp_parms = {
1366         .flow = upcall->flow,
1367         .mask = &upcall->xout.wc.masks,
1368     };
1369
1370     if (upcall->key_len) {
1371         ofpbuf_use_const(&keybuf, upcall->key, upcall->key_len);
1372     } else {
1373         /* dpif-netdev doesn't provide a netlink-formatted flow key in the
1374          * upcall, so convert the upcall's flow here. */
1375         ofpbuf_use_stack(&keybuf, &keystub, sizeof keystub);
1376         odp_parms.odp_in_port = upcall->flow->in_port.odp_port;
1377         odp_parms.recirc = true;
1378         odp_flow_key_from_flow(&odp_parms, &keybuf);
1379     }
1380
1381     atomic_read_relaxed(&enable_megaflows, &megaflow);
1382     recirc = ofproto_dpif_get_enable_recirc(upcall->ofproto);
1383     ofpbuf_use_stack(&maskbuf, &maskstub, sizeof maskstub);
1384     if (megaflow) {
1385         odp_parms.odp_in_port = ODPP_NONE;
1386         odp_parms.max_mpls_depth = ofproto_dpif_get_max_mpls_depth(upcall->ofproto);
1387         odp_parms.recirc = recirc;
1388         odp_parms.key_buf = &keybuf;
1389
1390         odp_flow_key_from_mask(&odp_parms, &maskbuf);
1391     }
1392
1393     return ukey_create__(keybuf.data, keybuf.size, maskbuf.data, maskbuf.size,
1394                          true, upcall->ufid, upcall->pmd_id,
1395                          &upcall->put_actions, upcall->dump_seq,
1396                          upcall->reval_seq, 0,
1397                          upcall->have_recirc_ref ? upcall->recirc : NULL,
1398                          &upcall->xout);
1399 }
1400
1401 static int
1402 ukey_create_from_dpif_flow(const struct udpif *udpif,
1403                            const struct dpif_flow *flow,
1404                            struct udpif_key **ukey)
1405 {
1406     struct dpif_flow full_flow;
1407     struct ofpbuf actions;
1408     uint64_t dump_seq, reval_seq;
1409     uint64_t stub[DPIF_FLOW_BUFSIZE / 8];
1410     const struct nlattr *a;
1411     unsigned int left;
1412
1413     if (!flow->key_len || !flow->actions_len) {
1414         struct ofpbuf buf;
1415         int err;
1416
1417         /* If the key or actions were not provided by the datapath, fetch the
1418          * full flow. */
1419         ofpbuf_use_stack(&buf, &stub, sizeof stub);
1420         err = dpif_flow_get(udpif->dpif, NULL, 0, &flow->ufid,
1421                             flow->pmd_id, &buf, &full_flow);
1422         if (err) {
1423             return err;
1424         }
1425         flow = &full_flow;
1426     }
1427
1428     /* Check the flow actions for recirculation action.  As recirculation
1429      * relies on OVS userspace internal state, we need to delete all old
1430      * datapath flows with recirculation upon OVS restart. */
1431     NL_ATTR_FOR_EACH_UNSAFE (a, left, flow->actions, flow->actions_len) {
1432         if (nl_attr_type(a) == OVS_ACTION_ATTR_RECIRC) {
1433             return EINVAL;
1434         }
1435     }
1436
1437     dump_seq = seq_read(udpif->dump_seq);
1438     reval_seq = seq_read(udpif->reval_seq);
1439     ofpbuf_use_const(&actions, &flow->actions, flow->actions_len);
1440     *ukey = ukey_create__(flow->key, flow->key_len,
1441                           flow->mask, flow->mask_len, flow->ufid_present,
1442                           &flow->ufid, flow->pmd_id, &actions, dump_seq,
1443                           reval_seq, flow->stats.used, NULL, NULL);
1444
1445     return 0;
1446 }
1447
1448 /* Attempts to insert a ukey into the shared ukey maps.
1449  *
1450  * On success, returns true, installs the ukey and returns it in a locked
1451  * state. Otherwise, returns false. */
1452 static bool
1453 ukey_install_start(struct udpif *udpif, struct udpif_key *new_ukey)
1454     OVS_TRY_LOCK(true, new_ukey->mutex)
1455 {
1456     struct umap *umap;
1457     struct udpif_key *old_ukey;
1458     uint32_t idx;
1459     bool locked = false;
1460
1461     idx = new_ukey->hash % N_UMAPS;
1462     umap = &udpif->ukeys[idx];
1463     ovs_mutex_lock(&umap->mutex);
1464     old_ukey = ukey_lookup(udpif, &new_ukey->ufid);
1465     if (old_ukey) {
1466         /* Uncommon case: A ukey is already installed with the same UFID. */
1467         if (old_ukey->key_len == new_ukey->key_len
1468             && !memcmp(old_ukey->key, new_ukey->key, new_ukey->key_len)) {
1469             COVERAGE_INC(handler_duplicate_upcall);
1470         } else {
1471             struct ds ds = DS_EMPTY_INITIALIZER;
1472
1473             odp_format_ufid(&old_ukey->ufid, &ds);
1474             ds_put_cstr(&ds, " ");
1475             odp_flow_key_format(old_ukey->key, old_ukey->key_len, &ds);
1476             ds_put_cstr(&ds, "\n");
1477             odp_format_ufid(&new_ukey->ufid, &ds);
1478             ds_put_cstr(&ds, " ");
1479             odp_flow_key_format(new_ukey->key, new_ukey->key_len, &ds);
1480
1481             VLOG_WARN_RL(&rl, "Conflicting ukey for flows:\n%s", ds_cstr(&ds));
1482             ds_destroy(&ds);
1483         }
1484     } else {
1485         ovs_mutex_lock(&new_ukey->mutex);
1486         cmap_insert(&umap->cmap, &new_ukey->cmap_node, new_ukey->hash);
1487         locked = true;
1488     }
1489     ovs_mutex_unlock(&umap->mutex);
1490
1491     return locked;
1492 }
1493
1494 static void
1495 ukey_install_finish__(struct udpif_key *ukey) OVS_REQUIRES(ukey->mutex)
1496 {
1497     ukey->flow_exists = true;
1498 }
1499
1500 static bool
1501 ukey_install_finish(struct udpif_key *ukey, int error)
1502     OVS_RELEASES(ukey->mutex)
1503 {
1504     if (!error) {
1505         ukey_install_finish__(ukey);
1506     }
1507     ovs_mutex_unlock(&ukey->mutex);
1508
1509     return !error;
1510 }
1511
1512 static bool
1513 ukey_install(struct udpif *udpif, struct udpif_key *ukey)
1514 {
1515     /* The usual way to keep 'ukey->flow_exists' in sync with the datapath is
1516      * to call ukey_install_start(), install the corresponding datapath flow,
1517      * then call ukey_install_finish(). The netdev interface using upcall_cb()
1518      * doesn't provide a function to separately finish the flow installation,
1519      * so we perform the operations together here.
1520      *
1521      * This is fine currently, as revalidator threads will only delete this
1522      * ukey during revalidator_sweep() and only if the dump_seq is mismatched.
1523      * It is unlikely for a revalidator thread to advance dump_seq and reach
1524      * the next GC phase between ukey creation and flow installation. */
1525     return ukey_install_start(udpif, ukey) && ukey_install_finish(ukey, 0);
1526 }
1527
1528 /* Searches for a ukey in 'udpif->ukeys' that matches 'flow' and attempts to
1529  * lock the ukey. If the ukey does not exist, create it.
1530  *
1531  * Returns 0 on success, setting *result to the matching ukey and returning it
1532  * in a locked state. Otherwise, returns an errno and clears *result. EBUSY
1533  * indicates that another thread is handling this flow. Other errors indicate
1534  * an unexpected condition creating a new ukey.
1535  *
1536  * *error is an output parameter provided to appease the threadsafety analyser,
1537  * and its value matches the return value. */
1538 static int
1539 ukey_acquire(struct udpif *udpif, const struct dpif_flow *flow,
1540              struct udpif_key **result, int *error)
1541     OVS_TRY_LOCK(0, (*result)->mutex)
1542 {
1543     struct udpif_key *ukey;
1544     int retval;
1545
1546     ukey = ukey_lookup(udpif, &flow->ufid);
1547     if (ukey) {
1548         retval = ovs_mutex_trylock(&ukey->mutex);
1549     } else {
1550         /* Usually we try to avoid installing flows from revalidator threads,
1551          * because locking on a umap may cause handler threads to block.
1552          * However there are certain cases, like when ovs-vswitchd is
1553          * restarted, where it is desirable to handle flows that exist in the
1554          * datapath gracefully (ie, don't just clear the datapath). */
1555         bool install;
1556
1557         retval = ukey_create_from_dpif_flow(udpif, flow, &ukey);
1558         if (retval) {
1559             goto done;
1560         }
1561         install = ukey_install_start(udpif, ukey);
1562         if (install) {
1563             ukey_install_finish__(ukey);
1564             retval = 0;
1565         } else {
1566             ukey_delete__(ukey);
1567             retval = EBUSY;
1568         }
1569     }
1570
1571 done:
1572     *error = retval;
1573     if (retval) {
1574         *result = NULL;
1575     } else {
1576         *result = ukey;
1577     }
1578     return retval;
1579 }
1580
1581 static void
1582 ukey_delete__(struct udpif_key *ukey)
1583     OVS_NO_THREAD_SAFETY_ANALYSIS
1584 {
1585     if (ukey) {
1586         for (int i = 0; i < ukey->n_recircs; i++) {
1587             recirc_free_id(ukey->recircs[i]);
1588         }
1589         xlate_cache_delete(ukey->xcache);
1590         ofpbuf_delete(ukey->actions);
1591         ovs_mutex_destroy(&ukey->mutex);
1592         free(ukey);
1593     }
1594 }
1595
1596 static void
1597 ukey_delete(struct umap *umap, struct udpif_key *ukey)
1598     OVS_REQUIRES(umap->mutex)
1599 {
1600     cmap_remove(&umap->cmap, &ukey->cmap_node, ukey->hash);
1601     ovsrcu_postpone(ukey_delete__, ukey);
1602 }
1603
1604 static bool
1605 should_revalidate(const struct udpif *udpif, uint64_t packets,
1606                   long long int used)
1607 {
1608     long long int metric, now, duration;
1609
1610     if (udpif->dump_duration < 200) {
1611         /* We are likely to handle full revalidation for the flows. */
1612         return true;
1613     }
1614
1615     /* Calculate the mean time between seeing these packets. If this
1616      * exceeds the threshold, then delete the flow rather than performing
1617      * costly revalidation for flows that aren't being hit frequently.
1618      *
1619      * This is targeted at situations where the dump_duration is high (~1s),
1620      * and revalidation is triggered by a call to udpif_revalidate(). In
1621      * these situations, revalidation of all flows causes fluctuations in the
1622      * flow_limit due to the interaction with the dump_duration and max_idle.
1623      * This tends to result in deletion of low-throughput flows anyway, so
1624      * skip the revalidation and just delete those flows. */
1625     packets = MAX(packets, 1);
1626     now = MAX(used, time_msec());
1627     duration = now - used;
1628     metric = duration / packets;
1629
1630     if (metric < 200) {
1631         /* The flow is receiving more than ~5pps, so keep it. */
1632         return true;
1633     }
1634     return false;
1635 }
1636
1637 static bool
1638 revalidate_ukey(struct udpif *udpif, struct udpif_key *ukey,
1639                 const struct dpif_flow_stats *stats, uint64_t reval_seq)
1640     OVS_REQUIRES(ukey->mutex)
1641 {
1642     uint64_t slow_path_buf[128 / 8];
1643     struct xlate_out xout, *xoutp;
1644     struct netflow *netflow;
1645     struct ofproto_dpif *ofproto;
1646     struct dpif_flow_stats push;
1647     struct ofpbuf xout_actions;
1648     struct flow flow, dp_mask;
1649     uint64_t *dp64, *xout64;
1650     ofp_port_t ofp_in_port;
1651     struct xlate_in xin;
1652     long long int last_used;
1653     int error;
1654     size_t i;
1655     bool ok;
1656     bool need_revalidate;
1657
1658     ok = false;
1659     xoutp = NULL;
1660     netflow = NULL;
1661
1662     need_revalidate = (ukey->reval_seq != reval_seq);
1663     last_used = ukey->stats.used;
1664     push.used = stats->used;
1665     push.tcp_flags = stats->tcp_flags;
1666     push.n_packets = (stats->n_packets > ukey->stats.n_packets
1667                       ? stats->n_packets - ukey->stats.n_packets
1668                       : 0);
1669     push.n_bytes = (stats->n_bytes > ukey->stats.n_bytes
1670                     ? stats->n_bytes - ukey->stats.n_bytes
1671                     : 0);
1672
1673     if (need_revalidate && last_used
1674         && !should_revalidate(udpif, push.n_packets, last_used)) {
1675         ok = false;
1676         goto exit;
1677     }
1678
1679     /* We will push the stats, so update the ukey stats cache. */
1680     ukey->stats = *stats;
1681     if (!push.n_packets && !need_revalidate) {
1682         ok = true;
1683         goto exit;
1684     }
1685
1686     if (ukey->xcache && !need_revalidate) {
1687         xlate_push_stats(ukey->xcache, &push);
1688         ok = true;
1689         goto exit;
1690     }
1691
1692     if (odp_flow_key_to_flow(ukey->key, ukey->key_len, &flow)
1693         == ODP_FIT_ERROR) {
1694         goto exit;
1695     }
1696
1697     error = xlate_lookup(udpif->backer, &flow, &ofproto, NULL, NULL, &netflow,
1698                          &ofp_in_port);
1699     if (error) {
1700         goto exit;
1701     }
1702
1703     if (need_revalidate) {
1704         xlate_cache_clear(ukey->xcache);
1705     }
1706     if (!ukey->xcache) {
1707         ukey->xcache = xlate_cache_new();
1708     }
1709
1710     xlate_in_init(&xin, ofproto, &flow, ofp_in_port, NULL, push.tcp_flags,
1711                   NULL);
1712     if (push.n_packets) {
1713         xin.resubmit_stats = &push;
1714         xin.may_learn = true;
1715     }
1716     xin.xcache = ukey->xcache;
1717     xin.skip_wildcards = !need_revalidate;
1718     xlate_actions(&xin, &xout);
1719     xoutp = &xout;
1720
1721     if (!need_revalidate) {
1722         ok = true;
1723         goto exit;
1724     }
1725
1726     if (!xout.slow) {
1727         ofpbuf_use_const(&xout_actions, xout.odp_actions->data,
1728                          xout.odp_actions->size);
1729     } else {
1730         ofpbuf_use_stack(&xout_actions, slow_path_buf, sizeof slow_path_buf);
1731         compose_slow_path(udpif, &xout, &flow, flow.in_port.odp_port,
1732                           &xout_actions);
1733     }
1734
1735     if (!ofpbuf_equal(&xout_actions, ukey->actions)) {
1736         goto exit;
1737     }
1738
1739     if (odp_flow_key_to_mask(ukey->mask, ukey->mask_len, ukey->key,
1740                              ukey->key_len, &dp_mask, &flow) == ODP_FIT_ERROR) {
1741         goto exit;
1742     }
1743
1744     /* Since the kernel is free to ignore wildcarded bits in the mask, we can't
1745      * directly check that the masks are the same.  Instead we check that the
1746      * mask in the kernel is more specific i.e. less wildcarded, than what
1747      * we've calculated here.  This guarantees we don't catch any packets we
1748      * shouldn't with the megaflow. */
1749     dp64 = (uint64_t *) &dp_mask;
1750     xout64 = (uint64_t *) &xout.wc.masks;
1751     for (i = 0; i < FLOW_U64S; i++) {
1752         if ((dp64[i] | xout64[i]) != dp64[i]) {
1753             goto exit;
1754         }
1755     }
1756
1757     ok = true;
1758
1759 exit:
1760     if (ok) {
1761         ukey->reval_seq = reval_seq;
1762     }
1763     if (netflow && !ok) {
1764         netflow_flow_clear(netflow, &flow);
1765     }
1766     xlate_out_uninit(xoutp);
1767     return ok;
1768 }
1769
1770 static void
1771 delete_op_init__(struct udpif *udpif, struct ukey_op *op,
1772                  const struct dpif_flow *flow)
1773 {
1774     op->ukey = NULL;
1775     op->dop.type = DPIF_OP_FLOW_DEL;
1776     op->dop.u.flow_del.key = flow->key;
1777     op->dop.u.flow_del.key_len = flow->key_len;
1778     op->dop.u.flow_del.ufid = flow->ufid_present ? &flow->ufid : NULL;
1779     op->dop.u.flow_del.pmd_id = flow->pmd_id;
1780     op->dop.u.flow_del.stats = &op->stats;
1781     op->dop.u.flow_del.terse = udpif_use_ufid(udpif);
1782 }
1783
1784 static void
1785 delete_op_init(struct udpif *udpif, struct ukey_op *op, struct udpif_key *ukey)
1786 {
1787     op->ukey = ukey;
1788     op->dop.type = DPIF_OP_FLOW_DEL;
1789     op->dop.u.flow_del.key = ukey->key;
1790     op->dop.u.flow_del.key_len = ukey->key_len;
1791     op->dop.u.flow_del.ufid = ukey->ufid_present ? &ukey->ufid : NULL;
1792     op->dop.u.flow_del.pmd_id = ukey->pmd_id;
1793     op->dop.u.flow_del.stats = &op->stats;
1794     op->dop.u.flow_del.terse = udpif_use_ufid(udpif);
1795 }
1796
1797 static void
1798 push_ukey_ops__(struct udpif *udpif, struct ukey_op *ops, size_t n_ops)
1799 {
1800     struct dpif_op *opsp[REVALIDATE_MAX_BATCH];
1801     size_t i;
1802
1803     ovs_assert(n_ops <= REVALIDATE_MAX_BATCH);
1804     for (i = 0; i < n_ops; i++) {
1805         opsp[i] = &ops[i].dop;
1806     }
1807     dpif_operate(udpif->dpif, opsp, n_ops);
1808
1809     for (i = 0; i < n_ops; i++) {
1810         struct ukey_op *op = &ops[i];
1811         struct dpif_flow_stats *push, *stats, push_buf;
1812
1813         stats = op->dop.u.flow_del.stats;
1814         push = &push_buf;
1815
1816         if (op->ukey) {
1817             ovs_mutex_lock(&op->ukey->mutex);
1818             push->used = MAX(stats->used, op->ukey->stats.used);
1819             push->tcp_flags = stats->tcp_flags | op->ukey->stats.tcp_flags;
1820             push->n_packets = stats->n_packets - op->ukey->stats.n_packets;
1821             push->n_bytes = stats->n_bytes - op->ukey->stats.n_bytes;
1822             ovs_mutex_unlock(&op->ukey->mutex);
1823         } else {
1824             push = stats;
1825         }
1826
1827         if (push->n_packets || netflow_exists()) {
1828             const struct nlattr *key = op->dop.u.flow_del.key;
1829             size_t key_len = op->dop.u.flow_del.key_len;
1830             struct ofproto_dpif *ofproto;
1831             struct netflow *netflow;
1832             ofp_port_t ofp_in_port;
1833             struct flow flow;
1834             int error;
1835
1836             if (op->ukey) {
1837                 ovs_mutex_lock(&op->ukey->mutex);
1838                 if (op->ukey->xcache) {
1839                     xlate_push_stats(op->ukey->xcache, push);
1840                     ovs_mutex_unlock(&op->ukey->mutex);
1841                     continue;
1842                 }
1843                 ovs_mutex_unlock(&op->ukey->mutex);
1844                 key = op->ukey->key;
1845                 key_len = op->ukey->key_len;
1846             }
1847
1848             if (odp_flow_key_to_flow(key, key_len, &flow)
1849                 == ODP_FIT_ERROR) {
1850                 continue;
1851             }
1852
1853             error = xlate_lookup(udpif->backer, &flow, &ofproto, NULL, NULL,
1854                                  &netflow, &ofp_in_port);
1855             if (!error) {
1856                 struct xlate_in xin;
1857
1858                 xlate_in_init(&xin, ofproto, &flow, ofp_in_port, NULL,
1859                               push->tcp_flags, NULL);
1860                 xin.resubmit_stats = push->n_packets ? push : NULL;
1861                 xin.may_learn = push->n_packets > 0;
1862                 xin.skip_wildcards = true;
1863                 xlate_actions_for_side_effects(&xin);
1864
1865                 if (netflow) {
1866                     netflow_flow_clear(netflow, &flow);
1867                 }
1868             }
1869         }
1870     }
1871 }
1872
1873 static void
1874 push_ukey_ops(struct udpif *udpif, struct umap *umap,
1875               struct ukey_op *ops, size_t n_ops)
1876 {
1877     int i;
1878
1879     push_ukey_ops__(udpif, ops, n_ops);
1880     ovs_mutex_lock(&umap->mutex);
1881     for (i = 0; i < n_ops; i++) {
1882         ukey_delete(umap, ops[i].ukey);
1883     }
1884     ovs_mutex_unlock(&umap->mutex);
1885 }
1886
1887 static void
1888 log_unexpected_flow(const struct dpif_flow *flow, int error)
1889 {
1890     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 60);
1891     struct ds ds = DS_EMPTY_INITIALIZER;
1892
1893     ds_put_format(&ds, "Failed to acquire udpif_key corresponding to "
1894                   "unexpected flow (%s): ", ovs_strerror(error));
1895     odp_format_ufid(&flow->ufid, &ds);
1896     VLOG_WARN_RL(&rl, "%s", ds_cstr(&ds));
1897 }
1898
1899 static void
1900 revalidate(struct revalidator *revalidator)
1901 {
1902     struct udpif *udpif = revalidator->udpif;
1903     struct dpif_flow_dump_thread *dump_thread;
1904     uint64_t dump_seq, reval_seq;
1905     unsigned int flow_limit;
1906
1907     dump_seq = seq_read(udpif->dump_seq);
1908     reval_seq = seq_read(udpif->reval_seq);
1909     atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
1910     dump_thread = dpif_flow_dump_thread_create(udpif->dump);
1911     for (;;) {
1912         struct ukey_op ops[REVALIDATE_MAX_BATCH];
1913         int n_ops = 0;
1914
1915         struct dpif_flow flows[REVALIDATE_MAX_BATCH];
1916         const struct dpif_flow *f;
1917         int n_dumped;
1918
1919         long long int max_idle;
1920         long long int now;
1921         size_t n_dp_flows;
1922         bool kill_them_all;
1923
1924         n_dumped = dpif_flow_dump_next(dump_thread, flows, ARRAY_SIZE(flows));
1925         if (!n_dumped) {
1926             break;
1927         }
1928
1929         now = time_msec();
1930
1931         /* In normal operation we want to keep flows around until they have
1932          * been idle for 'ofproto_max_idle' milliseconds.  However:
1933          *
1934          *     - If the number of datapath flows climbs above 'flow_limit',
1935          *       drop that down to 100 ms to try to bring the flows down to
1936          *       the limit.
1937          *
1938          *     - If the number of datapath flows climbs above twice
1939          *       'flow_limit', delete all the datapath flows as an emergency
1940          *       measure.  (We reassess this condition for the next batch of
1941          *       datapath flows, so we will recover before all the flows are
1942          *       gone.) */
1943         n_dp_flows = udpif_get_n_flows(udpif);
1944         kill_them_all = n_dp_flows > flow_limit * 2;
1945         max_idle = n_dp_flows > flow_limit ? 100 : ofproto_max_idle;
1946
1947         for (f = flows; f < &flows[n_dumped]; f++) {
1948             long long int used = f->stats.used;
1949             struct udpif_key *ukey;
1950             bool already_dumped, keep;
1951             int error;
1952
1953             if (ukey_acquire(udpif, f, &ukey, &error)) {
1954                 if (error == EBUSY) {
1955                     /* Another thread is processing this flow, so don't bother
1956                      * processing it.*/
1957                     COVERAGE_INC(upcall_ukey_contention);
1958                 } else {
1959                     log_unexpected_flow(f, error);
1960                     if (error != ENOENT) {
1961                         delete_op_init__(udpif, &ops[n_ops++], f);
1962                     }
1963                 }
1964                 continue;
1965             }
1966
1967             already_dumped = ukey->dump_seq == dump_seq;
1968             if (already_dumped) {
1969                 /* The flow has already been handled during this flow dump
1970                  * operation. Skip it. */
1971                 if (ukey->xcache) {
1972                     COVERAGE_INC(dumped_duplicate_flow);
1973                 } else {
1974                     COVERAGE_INC(dumped_new_flow);
1975                 }
1976                 ovs_mutex_unlock(&ukey->mutex);
1977                 continue;
1978             }
1979
1980             if (!used) {
1981                 used = ukey->created;
1982             }
1983             if (kill_them_all || (used && used < now - max_idle)) {
1984                 keep = false;
1985             } else {
1986                 keep = revalidate_ukey(udpif, ukey, &f->stats, reval_seq);
1987             }
1988             ukey->dump_seq = dump_seq;
1989             ukey->flow_exists = keep;
1990
1991             if (!keep) {
1992                 delete_op_init(udpif, &ops[n_ops++], ukey);
1993             }
1994             ovs_mutex_unlock(&ukey->mutex);
1995         }
1996
1997         if (n_ops) {
1998             push_ukey_ops__(udpif, ops, n_ops);
1999         }
2000         ovsrcu_quiesce();
2001     }
2002     dpif_flow_dump_thread_destroy(dump_thread);
2003 }
2004
2005 static bool
2006 handle_missed_revalidation(struct udpif *udpif, uint64_t reval_seq,
2007                            struct udpif_key *ukey)
2008 {
2009     struct dpif_flow_stats stats;
2010     bool keep;
2011
2012     COVERAGE_INC(revalidate_missed_dp_flow);
2013
2014     memset(&stats, 0, sizeof stats);
2015     ovs_mutex_lock(&ukey->mutex);
2016     keep = revalidate_ukey(udpif, ukey, &stats, reval_seq);
2017     ovs_mutex_unlock(&ukey->mutex);
2018
2019     return keep;
2020 }
2021
2022 static void
2023 revalidator_sweep__(struct revalidator *revalidator, bool purge)
2024 {
2025     struct udpif *udpif;
2026     uint64_t dump_seq, reval_seq;
2027     int slice;
2028
2029     udpif = revalidator->udpif;
2030     dump_seq = seq_read(udpif->dump_seq);
2031     reval_seq = seq_read(udpif->reval_seq);
2032     slice = revalidator - udpif->revalidators;
2033     ovs_assert(slice < udpif->n_revalidators);
2034
2035     for (int i = slice; i < N_UMAPS; i += udpif->n_revalidators) {
2036         struct ukey_op ops[REVALIDATE_MAX_BATCH];
2037         struct udpif_key *ukey;
2038         struct umap *umap = &udpif->ukeys[i];
2039         size_t n_ops = 0;
2040
2041         CMAP_FOR_EACH(ukey, cmap_node, &umap->cmap) {
2042             bool flow_exists, seq_mismatch;
2043
2044             /* Handler threads could be holding a ukey lock while it installs a
2045              * new flow, so don't hang around waiting for access to it. */
2046             if (ovs_mutex_trylock(&ukey->mutex)) {
2047                 continue;
2048             }
2049             flow_exists = ukey->flow_exists;
2050             seq_mismatch = (ukey->dump_seq != dump_seq
2051                             && ukey->reval_seq != reval_seq);
2052             ovs_mutex_unlock(&ukey->mutex);
2053
2054             if (flow_exists
2055                 && (purge
2056                     || (seq_mismatch
2057                         && !handle_missed_revalidation(udpif, reval_seq,
2058                                                        ukey)))) {
2059                 struct ukey_op *op = &ops[n_ops++];
2060
2061                 delete_op_init(udpif, op, ukey);
2062                 if (n_ops == REVALIDATE_MAX_BATCH) {
2063                     push_ukey_ops(udpif, umap, ops, n_ops);
2064                     n_ops = 0;
2065                 }
2066             } else if (!flow_exists) {
2067                 ovs_mutex_lock(&umap->mutex);
2068                 ukey_delete(umap, ukey);
2069                 ovs_mutex_unlock(&umap->mutex);
2070             }
2071         }
2072
2073         if (n_ops) {
2074             push_ukey_ops(udpif, umap, ops, n_ops);
2075         }
2076         ovsrcu_quiesce();
2077     }
2078 }
2079
2080 static void
2081 revalidator_sweep(struct revalidator *revalidator)
2082 {
2083     revalidator_sweep__(revalidator, false);
2084 }
2085
2086 static void
2087 revalidator_purge(struct revalidator *revalidator)
2088 {
2089     revalidator_sweep__(revalidator, true);
2090 }
2091 \f
2092 static void
2093 upcall_unixctl_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
2094                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2095 {
2096     struct ds ds = DS_EMPTY_INITIALIZER;
2097     struct udpif *udpif;
2098
2099     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2100         unsigned int flow_limit;
2101         bool ufid_enabled;
2102         size_t i;
2103
2104         atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
2105         ufid_enabled = udpif_use_ufid(udpif);
2106
2107         ds_put_format(&ds, "%s:\n", dpif_name(udpif->dpif));
2108         ds_put_format(&ds, "\tflows         : (current %lu)"
2109             " (avg %u) (max %u) (limit %u)\n", udpif_get_n_flows(udpif),
2110             udpif->avg_n_flows, udpif->max_n_flows, flow_limit);
2111         ds_put_format(&ds, "\tdump duration : %lldms\n", udpif->dump_duration);
2112         ds_put_format(&ds, "\tufid enabled : ");
2113         if (ufid_enabled) {
2114             ds_put_format(&ds, "true\n");
2115         } else {
2116             ds_put_format(&ds, "false\n");
2117         }
2118         ds_put_char(&ds, '\n');
2119
2120         for (i = 0; i < n_revalidators; i++) {
2121             struct revalidator *revalidator = &udpif->revalidators[i];
2122             int j, elements = 0;
2123
2124             for (j = i; j < N_UMAPS; j += n_revalidators) {
2125                 elements += cmap_count(&udpif->ukeys[j].cmap);
2126             }
2127             ds_put_format(&ds, "\t%u: (keys %d)\n", revalidator->id, elements);
2128         }
2129     }
2130
2131     unixctl_command_reply(conn, ds_cstr(&ds));
2132     ds_destroy(&ds);
2133 }
2134
2135 /* Disable using the megaflows.
2136  *
2137  * This command is only needed for advanced debugging, so it's not
2138  * documented in the man page. */
2139 static void
2140 upcall_unixctl_disable_megaflows(struct unixctl_conn *conn,
2141                                  int argc OVS_UNUSED,
2142                                  const char *argv[] OVS_UNUSED,
2143                                  void *aux OVS_UNUSED)
2144 {
2145     atomic_store_relaxed(&enable_megaflows, false);
2146     udpif_flush_all_datapaths();
2147     unixctl_command_reply(conn, "megaflows disabled");
2148 }
2149
2150 /* Re-enable using megaflows.
2151  *
2152  * This command is only needed for advanced debugging, so it's not
2153  * documented in the man page. */
2154 static void
2155 upcall_unixctl_enable_megaflows(struct unixctl_conn *conn,
2156                                 int argc OVS_UNUSED,
2157                                 const char *argv[] OVS_UNUSED,
2158                                 void *aux OVS_UNUSED)
2159 {
2160     atomic_store_relaxed(&enable_megaflows, true);
2161     udpif_flush_all_datapaths();
2162     unixctl_command_reply(conn, "megaflows enabled");
2163 }
2164
2165 /* Disable skipping flow attributes during flow dump.
2166  *
2167  * This command is only needed for advanced debugging, so it's not
2168  * documented in the man page. */
2169 static void
2170 upcall_unixctl_disable_ufid(struct unixctl_conn *conn, int argc OVS_UNUSED,
2171                            const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2172 {
2173     atomic_store_relaxed(&enable_ufid, false);
2174     unixctl_command_reply(conn, "Datapath dumping tersely using UFID disabled");
2175 }
2176
2177 /* Re-enable skipping flow attributes during flow dump.
2178  *
2179  * This command is only needed for advanced debugging, so it's not documented
2180  * in the man page. */
2181 static void
2182 upcall_unixctl_enable_ufid(struct unixctl_conn *conn, int argc OVS_UNUSED,
2183                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2184 {
2185     atomic_store_relaxed(&enable_ufid, true);
2186     unixctl_command_reply(conn, "Datapath dumping tersely using UFID enabled "
2187                                 "for supported datapaths");
2188 }
2189
2190 /* Set the flow limit.
2191  *
2192  * This command is only needed for advanced debugging, so it's not
2193  * documented in the man page. */
2194 static void
2195 upcall_unixctl_set_flow_limit(struct unixctl_conn *conn,
2196                               int argc OVS_UNUSED,
2197                               const char *argv[] OVS_UNUSED,
2198                               void *aux OVS_UNUSED)
2199 {
2200     struct ds ds = DS_EMPTY_INITIALIZER;
2201     struct udpif *udpif;
2202     unsigned int flow_limit = atoi(argv[1]);
2203
2204     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2205         atomic_store_relaxed(&udpif->flow_limit, flow_limit);
2206     }
2207     ds_put_format(&ds, "set flow_limit to %u\n", flow_limit);
2208     unixctl_command_reply(conn, ds_cstr(&ds));
2209     ds_destroy(&ds);
2210 }
2211
2212 static void
2213 upcall_unixctl_dump_wait(struct unixctl_conn *conn,
2214                          int argc OVS_UNUSED,
2215                          const char *argv[] OVS_UNUSED,
2216                          void *aux OVS_UNUSED)
2217 {
2218     if (list_is_singleton(&all_udpifs)) {
2219         struct udpif *udpif = NULL;
2220         size_t len;
2221
2222         udpif = OBJECT_CONTAINING(list_front(&all_udpifs), udpif, list_node);
2223         len = (udpif->n_conns + 1) * sizeof *udpif->conns;
2224         udpif->conn_seq = seq_read(udpif->dump_seq);
2225         udpif->conns = xrealloc(udpif->conns, len);
2226         udpif->conns[udpif->n_conns++] = conn;
2227     } else {
2228         unixctl_command_reply_error(conn, "can't wait on multiple udpifs.");
2229     }
2230 }
2231
2232 static void
2233 upcall_unixctl_purge(struct unixctl_conn *conn, int argc OVS_UNUSED,
2234                      const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2235 {
2236     struct udpif *udpif;
2237
2238     LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2239         int n;
2240
2241         for (n = 0; n < udpif->n_revalidators; n++) {
2242             revalidator_purge(&udpif->revalidators[n]);
2243         }
2244     }
2245     unixctl_command_reply(conn, "");
2246 }