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