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