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