]> git.proxmox.com Git - mirror_ovs.git/blob - ofproto/ofproto-dpif-upcall.c
ofproto-dpif-upcall: Only call ovsrcu_postpone() on active actions
[mirror_ovs.git] / ofproto / ofproto-dpif-upcall.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 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 "openvswitch/dynamic-string.h"
27 #include "fail-open.h"
28 #include "guarded-list.h"
29 #include "latch.h"
30 #include "openvswitch/list.h"
31 #include "netlink.h"
32 #include "openvswitch/ofpbuf.h"
33 #include "ofproto-dpif-ipfix.h"
34 #include "ofproto-dpif-sflow.h"
35 #include "ofproto-dpif-xlate.h"
36 #include "ofproto-dpif-xlate-cache.h"
37 #include "ofproto-dpif-trace.h"
38 #include "ovs-rcu.h"
39 #include "packets.h"
40 #include "openvswitch/poll-loop.h"
41 #include "seq.h"
42 #include "tunnel.h"
43 #include "unixctl.h"
44 #include "openvswitch/vlog.h"
45
46 #define MAX_QUEUE_LENGTH 512
47 #define UPCALL_MAX_BATCH 64
48 #define REVALIDATE_MAX_BATCH 50
49
50 VLOG_DEFINE_THIS_MODULE(ofproto_dpif_upcall);
51
52 COVERAGE_DEFINE(dumped_duplicate_flow);
53 COVERAGE_DEFINE(dumped_new_flow);
54 COVERAGE_DEFINE(handler_duplicate_upcall);
55 COVERAGE_DEFINE(upcall_ukey_contention);
56 COVERAGE_DEFINE(upcall_ukey_replace);
57 COVERAGE_DEFINE(revalidate_missed_dp_flow);
58
59 /* A thread that reads upcalls from dpif, forwards each upcall's packet,
60 * and possibly sets up a kernel flow as a cache. */
61 struct handler {
62 struct udpif *udpif; /* Parent udpif. */
63 pthread_t thread; /* Thread ID. */
64 uint32_t handler_id; /* Handler id. */
65 };
66
67 /* In the absence of a multiple-writer multiple-reader datastructure for
68 * storing udpif_keys ("ukeys"), we use a large number of cmaps, each with its
69 * own lock for writing. */
70 #define N_UMAPS 512 /* per udpif. */
71 struct umap {
72 struct ovs_mutex mutex; /* Take for writing to the following. */
73 struct cmap cmap; /* Datapath flow keys. */
74 };
75
76 /* A thread that processes datapath flows, updates OpenFlow statistics, and
77 * updates or removes them if necessary.
78 *
79 * Revalidator threads operate in two phases: "dump" and "sweep". In between
80 * each phase, all revalidators sync up so that all revalidator threads are
81 * either in one phase or the other, but not a combination.
82 *
83 * During the dump phase, revalidators fetch flows from the datapath and
84 * attribute the statistics to OpenFlow rules. Each datapath flow has a
85 * corresponding ukey which caches the most recently seen statistics. If
86 * a flow needs to be deleted (for example, because it is unused over a
87 * period of time), revalidator threads may delete the flow during the
88 * dump phase. The datapath is not guaranteed to reliably dump all flows
89 * from the datapath, and there is no mapping between datapath flows to
90 * revalidators, so a particular flow may be handled by zero or more
91 * revalidators during a single dump phase. To avoid duplicate attribution
92 * of statistics, ukeys are never deleted during this phase.
93 *
94 * During the sweep phase, each revalidator takes ownership of a different
95 * slice of umaps and sweeps through all ukeys in those umaps to figure out
96 * whether they need to be deleted. During this phase, revalidators may
97 * fetch individual flows which were not dumped during the dump phase to
98 * validate them and attribute statistics.
99 */
100 struct revalidator {
101 struct udpif *udpif; /* Parent udpif. */
102 pthread_t thread; /* Thread ID. */
103 unsigned int id; /* ovsthread_id_self(). */
104 };
105
106 /* An upcall handler for ofproto_dpif.
107 *
108 * udpif keeps records of two kind of logically separate units:
109 *
110 * upcall handling
111 * ---------------
112 *
113 * - An array of 'struct handler's for upcall handling and flow
114 * installation.
115 *
116 * flow revalidation
117 * -----------------
118 *
119 * - Revalidation threads which read the datapath flow table and maintains
120 * them.
121 */
122 struct udpif {
123 struct ovs_list list_node; /* In all_udpifs list. */
124
125 struct dpif *dpif; /* Datapath handle. */
126 struct dpif_backer *backer; /* Opaque dpif_backer pointer. */
127
128 struct handler *handlers; /* Upcall handlers. */
129 size_t n_handlers;
130
131 struct revalidator *revalidators; /* Flow revalidators. */
132 size_t n_revalidators;
133
134 struct latch exit_latch; /* Tells child threads to exit. */
135
136 /* Revalidation. */
137 struct seq *reval_seq; /* Incremented to force revalidation. */
138 bool reval_exit; /* Set by leader on 'exit_latch. */
139 struct ovs_barrier reval_barrier; /* Barrier used by revalidators. */
140 struct dpif_flow_dump *dump; /* DPIF flow dump state. */
141 long long int dump_duration; /* Duration of the last flow dump. */
142 struct seq *dump_seq; /* Increments each dump iteration. */
143 atomic_bool enable_ufid; /* If true, skip dumping flow attrs. */
144
145 /* These variables provide a mechanism for the main thread to pause
146 * all revalidation without having to completely shut the threads down.
147 * 'pause_latch' is shared between the main thread and the lead
148 * revalidator thread, so when it is desirable to halt revalidation, the
149 * main thread will set the latch. 'pause' and 'pause_barrier' are shared
150 * by revalidator threads. The lead revalidator will set 'pause' when it
151 * observes the latch has been set, and this will cause all revalidator
152 * threads to wait on 'pause_barrier' at the beginning of the next
153 * revalidation round. */
154 bool pause; /* Set by leader on 'pause_latch. */
155 struct latch pause_latch; /* Set to force revalidators pause. */
156 struct ovs_barrier pause_barrier; /* Barrier used to pause all */
157 /* revalidators by main thread. */
158
159 /* There are 'N_UMAPS' maps containing 'struct udpif_key' elements.
160 *
161 * During the flow dump phase, revalidators insert into these with a random
162 * distribution. During the garbage collection phase, each revalidator
163 * takes care of garbage collecting a slice of these maps. */
164 struct umap *ukeys;
165
166 /* Datapath flow statistics. */
167 unsigned int max_n_flows;
168 unsigned int avg_n_flows;
169
170 /* Following fields are accessed and modified by different threads. */
171 atomic_uint flow_limit; /* Datapath flow hard limit. */
172
173 /* n_flows_mutex prevents multiple threads updating these concurrently. */
174 atomic_uint n_flows; /* Number of flows in the datapath. */
175 atomic_llong n_flows_timestamp; /* Last time n_flows was updated. */
176 struct ovs_mutex n_flows_mutex;
177
178 /* Following fields are accessed and modified only from the main thread. */
179 struct unixctl_conn **conns; /* Connections waiting on dump_seq. */
180 uint64_t conn_seq; /* Corresponds to 'dump_seq' when
181 conns[n_conns-1] was stored. */
182 size_t n_conns; /* Number of connections waiting. */
183 };
184
185 enum upcall_type {
186 BAD_UPCALL, /* Some kind of bug somewhere. */
187 MISS_UPCALL, /* A flow miss. */
188 SLOW_PATH_UPCALL, /* Slow path upcall. */
189 SFLOW_UPCALL, /* sFlow sample. */
190 FLOW_SAMPLE_UPCALL, /* Per-flow sampling. */
191 IPFIX_UPCALL, /* Per-bridge sampling. */
192 CONTROLLER_UPCALL /* Destined for the controller. */
193 };
194
195 enum reval_result {
196 UKEY_KEEP,
197 UKEY_DELETE,
198 UKEY_MODIFY
199 };
200
201 struct upcall {
202 struct ofproto_dpif *ofproto; /* Parent ofproto. */
203 const struct recirc_id_node *recirc; /* Recirculation context. */
204 bool have_recirc_ref; /* Reference held on recirc ctx? */
205
206 /* The flow and packet are only required to be constant when using
207 * dpif-netdev. If a modification is absolutely necessary, a const cast
208 * may be used with other datapaths. */
209 const struct flow *flow; /* Parsed representation of the packet. */
210 enum odp_key_fitness fitness; /* Fitness of 'flow' relative to ODP key. */
211 const ovs_u128 *ufid; /* Unique identifier for 'flow'. */
212 unsigned pmd_id; /* Datapath poll mode driver id. */
213 const struct dp_packet *packet; /* Packet associated with this upcall. */
214 ofp_port_t ofp_in_port; /* OpenFlow in port, or OFPP_NONE. */
215 uint16_t mru; /* If !0, Maximum receive unit of
216 fragmented IP packet */
217
218 enum upcall_type type; /* Type of the upcall. */
219 const struct nlattr *actions; /* Flow actions in DPIF_UC_ACTION Upcalls. */
220
221 bool xout_initialized; /* True if 'xout' must be uninitialized. */
222 struct xlate_out xout; /* Result of xlate_actions(). */
223 struct ofpbuf odp_actions; /* Datapath actions from xlate_actions(). */
224 struct flow_wildcards wc; /* Dependencies that megaflow must match. */
225 struct ofpbuf put_actions; /* Actions 'put' in the fastpath. */
226
227 struct dpif_ipfix *ipfix; /* IPFIX pointer or NULL. */
228 struct dpif_sflow *sflow; /* SFlow pointer or NULL. */
229
230 struct udpif_key *ukey; /* Revalidator flow cache. */
231 bool ukey_persists; /* Set true to keep 'ukey' beyond the
232 lifetime of this upcall. */
233
234 uint64_t reval_seq; /* udpif->reval_seq at translation time. */
235
236 /* Not used by the upcall callback interface. */
237 const struct nlattr *key; /* Datapath flow key. */
238 size_t key_len; /* Datapath flow key length. */
239 const struct nlattr *out_tun_key; /* Datapath output tunnel key. */
240
241 struct user_action_cookie cookie;
242
243 uint64_t odp_actions_stub[1024 / 8]; /* Stub for odp_actions. */
244 };
245
246 /* Ukeys must transition through these states using transition_ukey(). */
247 enum ukey_state {
248 UKEY_CREATED = 0,
249 UKEY_VISIBLE, /* Ukey is in umap, datapath flow install is queued. */
250 UKEY_OPERATIONAL, /* Ukey is in umap, datapath flow is installed. */
251 UKEY_EVICTING, /* Ukey is in umap, datapath flow delete is queued. */
252 UKEY_EVICTED, /* Ukey is in umap, datapath flow is deleted. */
253 UKEY_DELETED, /* Ukey removed from umap, ukey free is deferred. */
254 };
255 #define N_UKEY_STATES (UKEY_DELETED + 1)
256
257 /* 'udpif_key's are responsible for tracking the little bit of state udpif
258 * needs to do flow expiration which can't be pulled directly from the
259 * datapath. They may be created by any handler or revalidator thread at any
260 * time, and read by any revalidator during the dump phase. They are however
261 * each owned by a single revalidator which takes care of destroying them
262 * during the garbage-collection phase.
263 *
264 * The mutex within the ukey protects some members of the ukey. The ukey
265 * itself is protected by RCU and is held within a umap in the parent udpif.
266 * Adding or removing a ukey from a umap is only safe when holding the
267 * corresponding umap lock. */
268 struct udpif_key {
269 struct cmap_node cmap_node; /* In parent revalidator 'ukeys' map. */
270
271 /* These elements are read only once created, and therefore aren't
272 * protected by a mutex. */
273 const struct nlattr *key; /* Datapath flow key. */
274 size_t key_len; /* Length of 'key'. */
275 const struct nlattr *mask; /* Datapath flow mask. */
276 size_t mask_len; /* Length of 'mask'. */
277 ovs_u128 ufid; /* Unique flow identifier. */
278 bool ufid_present; /* True if 'ufid' is in datapath. */
279 uint32_t hash; /* Pre-computed hash for 'key'. */
280 unsigned pmd_id; /* Datapath poll mode driver id. */
281
282 struct ovs_mutex mutex; /* Guards the following. */
283 struct dpif_flow_stats stats OVS_GUARDED; /* Last known stats.*/
284 long long int created OVS_GUARDED; /* Estimate of creation time. */
285 uint64_t dump_seq OVS_GUARDED; /* Tracks udpif->dump_seq. */
286 uint64_t reval_seq OVS_GUARDED; /* Tracks udpif->reval_seq. */
287 enum ukey_state state OVS_GUARDED; /* Tracks ukey lifetime. */
288
289 /* 'state' debug information. */
290 unsigned int state_thread OVS_GUARDED; /* Thread that transitions. */
291 const char *state_where OVS_GUARDED; /* transition_ukey() locator. */
292
293 /* Datapath flow actions as nlattrs. Protected by RCU. Read with
294 * ukey_get_actions(), and write with ukey_set_actions(). */
295 OVSRCU_TYPE(struct ofpbuf *) actions;
296
297 struct xlate_cache *xcache OVS_GUARDED; /* Cache for xlate entries that
298 * are affected by this ukey.
299 * Used for stats and learning.*/
300 union {
301 struct odputil_keybuf buf;
302 struct nlattr nla;
303 } keybuf, maskbuf;
304
305 uint32_t key_recirc_id; /* Non-zero if reference is held by the ukey. */
306 struct recirc_refs recircs; /* Action recirc IDs with references held. */
307 };
308
309 /* Datapath operation with optional ukey attached. */
310 struct ukey_op {
311 struct udpif_key *ukey;
312 struct dpif_flow_stats stats; /* Stats for 'op'. */
313 struct dpif_op dop; /* Flow operation. */
314 };
315
316 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
317 static struct ovs_list all_udpifs = OVS_LIST_INITIALIZER(&all_udpifs);
318
319 static size_t recv_upcalls(struct handler *);
320 static int process_upcall(struct udpif *, struct upcall *,
321 struct ofpbuf *odp_actions, struct flow_wildcards *);
322 static void handle_upcalls(struct udpif *, struct upcall *, size_t n_upcalls);
323 static void udpif_stop_threads(struct udpif *);
324 static void udpif_start_threads(struct udpif *, size_t n_handlers,
325 size_t n_revalidators);
326 static void udpif_pause_revalidators(struct udpif *);
327 static void udpif_resume_revalidators(struct udpif *);
328 static void *udpif_upcall_handler(void *);
329 static void *udpif_revalidator(void *);
330 static unsigned long udpif_get_n_flows(struct udpif *);
331 static void revalidate(struct revalidator *);
332 static void revalidator_pause(struct revalidator *);
333 static void revalidator_sweep(struct revalidator *);
334 static void revalidator_purge(struct revalidator *);
335 static void upcall_unixctl_show(struct unixctl_conn *conn, int argc,
336 const char *argv[], void *aux);
337 static void upcall_unixctl_disable_megaflows(struct unixctl_conn *, int argc,
338 const char *argv[], void *aux);
339 static void upcall_unixctl_enable_megaflows(struct unixctl_conn *, int argc,
340 const char *argv[], void *aux);
341 static void upcall_unixctl_disable_ufid(struct unixctl_conn *, int argc,
342 const char *argv[], void *aux);
343 static void upcall_unixctl_enable_ufid(struct unixctl_conn *, int argc,
344 const char *argv[], void *aux);
345 static void upcall_unixctl_set_flow_limit(struct unixctl_conn *conn, int argc,
346 const char *argv[], void *aux);
347 static void upcall_unixctl_dump_wait(struct unixctl_conn *conn, int argc,
348 const char *argv[], void *aux);
349 static void upcall_unixctl_purge(struct unixctl_conn *conn, int argc,
350 const char *argv[], void *aux);
351
352 static struct udpif_key *ukey_create_from_upcall(struct upcall *,
353 struct flow_wildcards *);
354 static int ukey_create_from_dpif_flow(const struct udpif *,
355 const struct dpif_flow *,
356 struct udpif_key **);
357 static void ukey_get_actions(struct udpif_key *, const struct nlattr **actions,
358 size_t *size);
359 static bool ukey_install__(struct udpif *, struct udpif_key *ukey)
360 OVS_TRY_LOCK(true, ukey->mutex);
361 static bool ukey_install(struct udpif *udpif, struct udpif_key *ukey);
362 static void transition_ukey_at(struct udpif_key *ukey, enum ukey_state dst,
363 const char *where)
364 OVS_REQUIRES(ukey->mutex);
365 #define transition_ukey(UKEY, DST) \
366 transition_ukey_at(UKEY, DST, OVS_SOURCE_LOCATOR)
367 static struct udpif_key *ukey_lookup(struct udpif *udpif,
368 const ovs_u128 *ufid,
369 const unsigned pmd_id);
370 static int ukey_acquire(struct udpif *, const struct dpif_flow *,
371 struct udpif_key **result, int *error);
372 static void ukey_delete__(struct udpif_key *);
373 static void ukey_delete(struct umap *, struct udpif_key *);
374 static enum upcall_type classify_upcall(enum dpif_upcall_type type,
375 const struct nlattr *userdata,
376 struct user_action_cookie *cookie);
377
378 static void put_op_init(struct ukey_op *op, struct udpif_key *ukey,
379 enum dpif_flow_put_flags flags);
380 static void delete_op_init(struct udpif *udpif, struct ukey_op *op,
381 struct udpif_key *ukey);
382
383 static int upcall_receive(struct upcall *, const struct dpif_backer *,
384 const struct dp_packet *packet, enum dpif_upcall_type,
385 const struct nlattr *userdata, const struct flow *,
386 const unsigned int mru,
387 const ovs_u128 *ufid, const unsigned pmd_id);
388 static void upcall_uninit(struct upcall *);
389
390 static upcall_callback upcall_cb;
391 static dp_purge_callback dp_purge_cb;
392
393 static atomic_bool enable_megaflows = ATOMIC_VAR_INIT(true);
394 static atomic_bool enable_ufid = ATOMIC_VAR_INIT(true);
395
396 void
397 udpif_init(void)
398 {
399 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
400 if (ovsthread_once_start(&once)) {
401 unixctl_command_register("upcall/show", "", 0, 0, upcall_unixctl_show,
402 NULL);
403 unixctl_command_register("upcall/disable-megaflows", "", 0, 0,
404 upcall_unixctl_disable_megaflows, NULL);
405 unixctl_command_register("upcall/enable-megaflows", "", 0, 0,
406 upcall_unixctl_enable_megaflows, NULL);
407 unixctl_command_register("upcall/disable-ufid", "", 0, 0,
408 upcall_unixctl_disable_ufid, NULL);
409 unixctl_command_register("upcall/enable-ufid", "", 0, 0,
410 upcall_unixctl_enable_ufid, NULL);
411 unixctl_command_register("upcall/set-flow-limit", "flow-limit-number",
412 1, 1, upcall_unixctl_set_flow_limit, NULL);
413 unixctl_command_register("revalidator/wait", "", 0, 0,
414 upcall_unixctl_dump_wait, NULL);
415 unixctl_command_register("revalidator/purge", "", 0, 0,
416 upcall_unixctl_purge, NULL);
417 ovsthread_once_done(&once);
418 }
419 }
420
421 struct udpif *
422 udpif_create(struct dpif_backer *backer, struct dpif *dpif)
423 {
424 struct udpif *udpif = xzalloc(sizeof *udpif);
425
426 udpif->dpif = dpif;
427 udpif->backer = backer;
428 atomic_init(&udpif->flow_limit, MIN(ofproto_flow_limit, 10000));
429 udpif->reval_seq = seq_create();
430 udpif->dump_seq = seq_create();
431 latch_init(&udpif->exit_latch);
432 latch_init(&udpif->pause_latch);
433 ovs_list_push_back(&all_udpifs, &udpif->list_node);
434 atomic_init(&udpif->enable_ufid, false);
435 atomic_init(&udpif->n_flows, 0);
436 atomic_init(&udpif->n_flows_timestamp, LLONG_MIN);
437 ovs_mutex_init(&udpif->n_flows_mutex);
438 udpif->ukeys = xmalloc(N_UMAPS * sizeof *udpif->ukeys);
439 for (int i = 0; i < N_UMAPS; i++) {
440 cmap_init(&udpif->ukeys[i].cmap);
441 ovs_mutex_init(&udpif->ukeys[i].mutex);
442 }
443
444 dpif_register_upcall_cb(dpif, upcall_cb, udpif);
445 dpif_register_dp_purge_cb(dpif, dp_purge_cb, udpif);
446
447 return udpif;
448 }
449
450 void
451 udpif_run(struct udpif *udpif)
452 {
453 if (udpif->conns && udpif->conn_seq != seq_read(udpif->dump_seq)) {
454 int i;
455
456 for (i = 0; i < udpif->n_conns; i++) {
457 unixctl_command_reply(udpif->conns[i], NULL);
458 }
459 free(udpif->conns);
460 udpif->conns = NULL;
461 udpif->n_conns = 0;
462 }
463 }
464
465 void
466 udpif_destroy(struct udpif *udpif)
467 {
468 udpif_stop_threads(udpif);
469
470 dpif_register_dp_purge_cb(udpif->dpif, NULL, udpif);
471 dpif_register_upcall_cb(udpif->dpif, NULL, udpif);
472
473 for (int i = 0; i < N_UMAPS; i++) {
474 cmap_destroy(&udpif->ukeys[i].cmap);
475 ovs_mutex_destroy(&udpif->ukeys[i].mutex);
476 }
477 free(udpif->ukeys);
478 udpif->ukeys = NULL;
479
480 ovs_list_remove(&udpif->list_node);
481 latch_destroy(&udpif->exit_latch);
482 latch_destroy(&udpif->pause_latch);
483 seq_destroy(udpif->reval_seq);
484 seq_destroy(udpif->dump_seq);
485 ovs_mutex_destroy(&udpif->n_flows_mutex);
486 free(udpif);
487 }
488
489 /* Stops the handler and revalidator threads, must be enclosed in
490 * ovsrcu quiescent state unless when destroying udpif. */
491 static void
492 udpif_stop_threads(struct udpif *udpif)
493 {
494 if (udpif && (udpif->n_handlers != 0 || udpif->n_revalidators != 0)) {
495 size_t i;
496
497 latch_set(&udpif->exit_latch);
498
499 for (i = 0; i < udpif->n_handlers; i++) {
500 struct handler *handler = &udpif->handlers[i];
501
502 xpthread_join(handler->thread, NULL);
503 }
504
505 for (i = 0; i < udpif->n_revalidators; i++) {
506 xpthread_join(udpif->revalidators[i].thread, NULL);
507 }
508
509 dpif_disable_upcall(udpif->dpif);
510
511 for (i = 0; i < udpif->n_revalidators; i++) {
512 struct revalidator *revalidator = &udpif->revalidators[i];
513
514 /* Delete ukeys, and delete all flows from the datapath to prevent
515 * double-counting stats. */
516 revalidator_purge(revalidator);
517 }
518
519 latch_poll(&udpif->exit_latch);
520
521 ovs_barrier_destroy(&udpif->reval_barrier);
522 ovs_barrier_destroy(&udpif->pause_barrier);
523
524 free(udpif->revalidators);
525 udpif->revalidators = NULL;
526 udpif->n_revalidators = 0;
527
528 free(udpif->handlers);
529 udpif->handlers = NULL;
530 udpif->n_handlers = 0;
531 }
532 }
533
534 /* Starts the handler and revalidator threads, must be enclosed in
535 * ovsrcu quiescent state. */
536 static void
537 udpif_start_threads(struct udpif *udpif, size_t n_handlers_,
538 size_t n_revalidators_)
539 {
540 if (udpif && n_handlers_ && n_revalidators_) {
541 udpif->n_handlers = n_handlers_;
542 udpif->n_revalidators = n_revalidators_;
543
544 udpif->handlers = xzalloc(udpif->n_handlers * sizeof *udpif->handlers);
545 for (size_t i = 0; i < udpif->n_handlers; i++) {
546 struct handler *handler = &udpif->handlers[i];
547
548 handler->udpif = udpif;
549 handler->handler_id = i;
550 handler->thread = ovs_thread_create(
551 "handler", udpif_upcall_handler, handler);
552 }
553
554 atomic_init(&udpif->enable_ufid, udpif->backer->rt_support.ufid);
555 dpif_enable_upcall(udpif->dpif);
556
557 ovs_barrier_init(&udpif->reval_barrier, udpif->n_revalidators);
558 ovs_barrier_init(&udpif->pause_barrier, udpif->n_revalidators + 1);
559 udpif->reval_exit = false;
560 udpif->pause = false;
561 udpif->revalidators = xzalloc(udpif->n_revalidators
562 * sizeof *udpif->revalidators);
563 for (size_t i = 0; i < udpif->n_revalidators; i++) {
564 struct revalidator *revalidator = &udpif->revalidators[i];
565
566 revalidator->udpif = udpif;
567 revalidator->thread = ovs_thread_create(
568 "revalidator", udpif_revalidator, revalidator);
569 }
570 }
571 }
572
573 /* Pauses all revalidators. Should only be called by the main thread.
574 * When function returns, all revalidators are paused and will proceed
575 * only after udpif_resume_revalidators() is called. */
576 static void
577 udpif_pause_revalidators(struct udpif *udpif)
578 {
579 if (udpif->backer->recv_set_enable) {
580 latch_set(&udpif->pause_latch);
581 ovs_barrier_block(&udpif->pause_barrier);
582 }
583 }
584
585 /* Resumes the pausing of revalidators. Should only be called by the
586 * main thread. */
587 static void
588 udpif_resume_revalidators(struct udpif *udpif)
589 {
590 if (udpif->backer->recv_set_enable) {
591 latch_poll(&udpif->pause_latch);
592 ovs_barrier_block(&udpif->pause_barrier);
593 }
594 }
595
596 /* Tells 'udpif' how many threads it should use to handle upcalls.
597 * 'n_handlers_' and 'n_revalidators_' can never be zero. 'udpif''s
598 * datapath handle must have packet reception enabled before starting
599 * threads. */
600 void
601 udpif_set_threads(struct udpif *udpif, size_t n_handlers_,
602 size_t n_revalidators_)
603 {
604 ovs_assert(udpif);
605 ovs_assert(n_handlers_ && n_revalidators_);
606
607 ovsrcu_quiesce_start();
608 if (udpif->n_handlers != n_handlers_
609 || udpif->n_revalidators != n_revalidators_) {
610 udpif_stop_threads(udpif);
611 }
612
613 if (!udpif->handlers && !udpif->revalidators) {
614 int error;
615
616 error = dpif_handlers_set(udpif->dpif, n_handlers_);
617 if (error) {
618 VLOG_ERR("failed to configure handlers in dpif %s: %s",
619 dpif_name(udpif->dpif), ovs_strerror(error));
620 return;
621 }
622
623 udpif_start_threads(udpif, n_handlers_, n_revalidators_);
624 }
625 ovsrcu_quiesce_end();
626 }
627
628 /* Waits for all ongoing upcall translations to complete. This ensures that
629 * there are no transient references to any removed ofprotos (or other
630 * objects). In particular, this should be called after an ofproto is removed
631 * (e.g. via xlate_remove_ofproto()) but before it is destroyed. */
632 void
633 udpif_synchronize(struct udpif *udpif)
634 {
635 /* This is stronger than necessary. It would be sufficient to ensure
636 * (somehow) that each handler and revalidator thread had passed through
637 * its main loop once. */
638 size_t n_handlers_ = udpif->n_handlers;
639 size_t n_revalidators_ = udpif->n_revalidators;
640
641 ovsrcu_quiesce_start();
642 udpif_stop_threads(udpif);
643 udpif_start_threads(udpif, n_handlers_, n_revalidators_);
644 ovsrcu_quiesce_end();
645 }
646
647 /* Notifies 'udpif' that something changed which may render previous
648 * xlate_actions() results invalid. */
649 void
650 udpif_revalidate(struct udpif *udpif)
651 {
652 seq_change(udpif->reval_seq);
653 }
654
655 /* Returns a seq which increments every time 'udpif' pulls stats from the
656 * datapath. Callers can use this to get a sense of when might be a good time
657 * to do periodic work which relies on relatively up to date statistics. */
658 struct seq *
659 udpif_dump_seq(struct udpif *udpif)
660 {
661 return udpif->dump_seq;
662 }
663
664 void
665 udpif_get_memory_usage(struct udpif *udpif, struct simap *usage)
666 {
667 size_t i;
668
669 simap_increase(usage, "handlers", udpif->n_handlers);
670
671 simap_increase(usage, "revalidators", udpif->n_revalidators);
672 for (i = 0; i < N_UMAPS; i++) {
673 simap_increase(usage, "udpif keys", cmap_count(&udpif->ukeys[i].cmap));
674 }
675 }
676
677 /* Remove flows from a single datapath. */
678 void
679 udpif_flush(struct udpif *udpif)
680 {
681 size_t n_handlers_ = udpif->n_handlers;
682 size_t n_revalidators_ = udpif->n_revalidators;
683
684 ovsrcu_quiesce_start();
685
686 udpif_stop_threads(udpif);
687 dpif_flow_flush(udpif->dpif);
688 udpif_start_threads(udpif, n_handlers_, n_revalidators_);
689
690 ovsrcu_quiesce_end();
691 }
692
693 /* Removes all flows from all datapaths. */
694 static void
695 udpif_flush_all_datapaths(void)
696 {
697 struct udpif *udpif;
698
699 LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
700 udpif_flush(udpif);
701 }
702 }
703
704 static bool
705 udpif_use_ufid(struct udpif *udpif)
706 {
707 bool enable;
708
709 atomic_read_relaxed(&enable_ufid, &enable);
710 return enable && udpif->backer->rt_support.ufid;
711 }
712
713 \f
714 static unsigned long
715 udpif_get_n_flows(struct udpif *udpif)
716 {
717 long long int time, now;
718 unsigned long flow_count;
719
720 now = time_msec();
721 atomic_read_relaxed(&udpif->n_flows_timestamp, &time);
722 if (time < now - 100 && !ovs_mutex_trylock(&udpif->n_flows_mutex)) {
723 struct dpif_dp_stats stats;
724
725 atomic_store_relaxed(&udpif->n_flows_timestamp, now);
726 dpif_get_dp_stats(udpif->dpif, &stats);
727 flow_count = stats.n_flows;
728 atomic_store_relaxed(&udpif->n_flows, flow_count);
729 ovs_mutex_unlock(&udpif->n_flows_mutex);
730 } else {
731 atomic_read_relaxed(&udpif->n_flows, &flow_count);
732 }
733 return flow_count;
734 }
735
736 /* The upcall handler thread tries to read a batch of UPCALL_MAX_BATCH
737 * upcalls from dpif, processes the batch and installs corresponding flows
738 * in dpif. */
739 static void *
740 udpif_upcall_handler(void *arg)
741 {
742 struct handler *handler = arg;
743 struct udpif *udpif = handler->udpif;
744
745 while (!latch_is_set(&handler->udpif->exit_latch)) {
746 if (recv_upcalls(handler)) {
747 poll_immediate_wake();
748 } else {
749 dpif_recv_wait(udpif->dpif, handler->handler_id);
750 latch_wait(&udpif->exit_latch);
751 }
752 poll_block();
753 }
754
755 return NULL;
756 }
757
758 static size_t
759 recv_upcalls(struct handler *handler)
760 {
761 struct udpif *udpif = handler->udpif;
762 uint64_t recv_stubs[UPCALL_MAX_BATCH][512 / 8];
763 struct ofpbuf recv_bufs[UPCALL_MAX_BATCH];
764 struct dpif_upcall dupcalls[UPCALL_MAX_BATCH];
765 struct upcall upcalls[UPCALL_MAX_BATCH];
766 struct flow flows[UPCALL_MAX_BATCH];
767 size_t n_upcalls, i;
768
769 n_upcalls = 0;
770 while (n_upcalls < UPCALL_MAX_BATCH) {
771 struct ofpbuf *recv_buf = &recv_bufs[n_upcalls];
772 struct dpif_upcall *dupcall = &dupcalls[n_upcalls];
773 struct upcall *upcall = &upcalls[n_upcalls];
774 struct flow *flow = &flows[n_upcalls];
775 unsigned int mru;
776 int error;
777
778 ofpbuf_use_stub(recv_buf, recv_stubs[n_upcalls],
779 sizeof recv_stubs[n_upcalls]);
780 if (dpif_recv(udpif->dpif, handler->handler_id, dupcall, recv_buf)) {
781 ofpbuf_uninit(recv_buf);
782 break;
783 }
784
785 upcall->fitness = odp_flow_key_to_flow(dupcall->key, dupcall->key_len,
786 flow);
787 if (upcall->fitness == ODP_FIT_ERROR) {
788 goto free_dupcall;
789 }
790
791 if (dupcall->mru) {
792 mru = nl_attr_get_u16(dupcall->mru);
793 } else {
794 mru = 0;
795 }
796
797 error = upcall_receive(upcall, udpif->backer, &dupcall->packet,
798 dupcall->type, dupcall->userdata, flow, mru,
799 &dupcall->ufid, PMD_ID_NULL);
800 if (error) {
801 if (error == ENODEV) {
802 /* Received packet on datapath port for which we couldn't
803 * associate an ofproto. This can happen if a port is removed
804 * while traffic is being received. Print a rate-limited
805 * message in case it happens frequently. */
806 dpif_flow_put(udpif->dpif, DPIF_FP_CREATE, dupcall->key,
807 dupcall->key_len, NULL, 0, NULL, 0,
808 &dupcall->ufid, PMD_ID_NULL, NULL);
809 VLOG_INFO_RL(&rl, "received packet on unassociated datapath "
810 "port %"PRIu32, flow->in_port.odp_port);
811 }
812 goto free_dupcall;
813 }
814
815 upcall->key = dupcall->key;
816 upcall->key_len = dupcall->key_len;
817 upcall->ufid = &dupcall->ufid;
818
819 upcall->out_tun_key = dupcall->out_tun_key;
820 upcall->actions = dupcall->actions;
821
822 pkt_metadata_from_flow(&dupcall->packet.md, flow);
823 flow_extract(&dupcall->packet, flow);
824
825 error = process_upcall(udpif, upcall,
826 &upcall->odp_actions, &upcall->wc);
827 if (error) {
828 goto cleanup;
829 }
830
831 n_upcalls++;
832 continue;
833
834 cleanup:
835 upcall_uninit(upcall);
836 free_dupcall:
837 dp_packet_uninit(&dupcall->packet);
838 ofpbuf_uninit(recv_buf);
839 }
840
841 if (n_upcalls) {
842 handle_upcalls(handler->udpif, upcalls, n_upcalls);
843 for (i = 0; i < n_upcalls; i++) {
844 dp_packet_uninit(&dupcalls[i].packet);
845 ofpbuf_uninit(&recv_bufs[i]);
846 upcall_uninit(&upcalls[i]);
847 }
848 }
849
850 return n_upcalls;
851 }
852
853 static void *
854 udpif_revalidator(void *arg)
855 {
856 /* Used by all revalidators. */
857 struct revalidator *revalidator = arg;
858 struct udpif *udpif = revalidator->udpif;
859 bool leader = revalidator == &udpif->revalidators[0];
860
861 /* Used only by the leader. */
862 long long int start_time = 0;
863 uint64_t last_reval_seq = 0;
864 size_t n_flows = 0;
865
866 revalidator->id = ovsthread_id_self();
867 for (;;) {
868 if (leader) {
869 uint64_t reval_seq;
870
871 recirc_run(); /* Recirculation cleanup. */
872
873 reval_seq = seq_read(udpif->reval_seq);
874 last_reval_seq = reval_seq;
875
876 n_flows = udpif_get_n_flows(udpif);
877 udpif->max_n_flows = MAX(n_flows, udpif->max_n_flows);
878 udpif->avg_n_flows = (udpif->avg_n_flows + n_flows) / 2;
879
880 /* Only the leader checks the pause latch to prevent a race where
881 * some threads think it's false and proceed to block on
882 * reval_barrier and others think it's true and block indefinitely
883 * on the pause_barrier */
884 udpif->pause = latch_is_set(&udpif->pause_latch);
885
886 /* Only the leader checks the exit latch to prevent a race where
887 * some threads think it's true and exit and others think it's
888 * false and block indefinitely on the reval_barrier */
889 udpif->reval_exit = latch_is_set(&udpif->exit_latch);
890
891 start_time = time_msec();
892 if (!udpif->reval_exit) {
893 bool terse_dump;
894
895 terse_dump = udpif_use_ufid(udpif);
896 udpif->dump = dpif_flow_dump_create(udpif->dpif, terse_dump,
897 NULL);
898 }
899 }
900
901 /* Wait for the leader to start the flow dump. */
902 ovs_barrier_block(&udpif->reval_barrier);
903 if (udpif->pause) {
904 revalidator_pause(revalidator);
905 }
906
907 if (udpif->reval_exit) {
908 break;
909 }
910 revalidate(revalidator);
911
912 /* Wait for all flows to have been dumped before we garbage collect. */
913 ovs_barrier_block(&udpif->reval_barrier);
914 revalidator_sweep(revalidator);
915
916 /* Wait for all revalidators to finish garbage collection. */
917 ovs_barrier_block(&udpif->reval_barrier);
918
919 if (leader) {
920 unsigned int flow_limit;
921 long long int duration;
922
923 atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
924
925 dpif_flow_dump_destroy(udpif->dump);
926 seq_change(udpif->dump_seq);
927
928 duration = MAX(time_msec() - start_time, 1);
929 udpif->dump_duration = duration;
930 if (duration > 2000) {
931 flow_limit /= duration / 1000;
932 } else if (duration > 1300) {
933 flow_limit = flow_limit * 3 / 4;
934 } else if (duration < 1000 && n_flows > 2000
935 && flow_limit < n_flows * 1000 / duration) {
936 flow_limit += 1000;
937 }
938 flow_limit = MIN(ofproto_flow_limit, MAX(flow_limit, 1000));
939 atomic_store_relaxed(&udpif->flow_limit, flow_limit);
940
941 if (duration > 2000) {
942 VLOG_INFO("Spent an unreasonably long %lldms dumping flows",
943 duration);
944 }
945
946 poll_timer_wait_until(start_time + MIN(ofproto_max_idle, 500));
947 seq_wait(udpif->reval_seq, last_reval_seq);
948 latch_wait(&udpif->exit_latch);
949 latch_wait(&udpif->pause_latch);
950 poll_block();
951
952 if (!latch_is_set(&udpif->pause_latch) &&
953 !latch_is_set(&udpif->exit_latch)) {
954 long long int now = time_msec();
955 /* Block again if we are woken up within 5ms of the last start
956 * time. */
957 start_time += 5;
958
959 if (now < start_time) {
960 poll_timer_wait_until(start_time);
961 latch_wait(&udpif->exit_latch);
962 latch_wait(&udpif->pause_latch);
963 poll_block();
964 }
965 }
966 }
967 }
968
969 return NULL;
970 }
971 \f
972 static enum upcall_type
973 classify_upcall(enum dpif_upcall_type type, const struct nlattr *userdata,
974 struct user_action_cookie *cookie)
975 {
976 /* First look at the upcall type. */
977 switch (type) {
978 case DPIF_UC_ACTION:
979 break;
980
981 case DPIF_UC_MISS:
982 return MISS_UPCALL;
983
984 case DPIF_N_UC_TYPES:
985 default:
986 VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, type);
987 return BAD_UPCALL;
988 }
989
990 /* "action" upcalls need a closer look. */
991 if (!userdata) {
992 VLOG_WARN_RL(&rl, "action upcall missing cookie");
993 return BAD_UPCALL;
994 }
995
996 size_t userdata_len = nl_attr_get_size(userdata);
997 if (userdata_len != sizeof *cookie) {
998 VLOG_WARN_RL(&rl, "action upcall cookie has unexpected size %"PRIuSIZE,
999 userdata_len);
1000 return BAD_UPCALL;
1001 }
1002 memcpy(cookie, nl_attr_get(userdata), sizeof *cookie);
1003 if (cookie->type == USER_ACTION_COOKIE_SFLOW) {
1004 return SFLOW_UPCALL;
1005 } else if (cookie->type == USER_ACTION_COOKIE_SLOW_PATH) {
1006 return SLOW_PATH_UPCALL;
1007 } else if (cookie->type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
1008 return FLOW_SAMPLE_UPCALL;
1009 } else if (cookie->type == USER_ACTION_COOKIE_IPFIX) {
1010 return IPFIX_UPCALL;
1011 } else if (cookie->type == USER_ACTION_COOKIE_CONTROLLER) {
1012 return CONTROLLER_UPCALL;
1013 } else {
1014 VLOG_WARN_RL(&rl, "invalid user cookie of type %"PRIu16
1015 " and size %"PRIuSIZE, cookie->type, userdata_len);
1016 return BAD_UPCALL;
1017 }
1018 }
1019
1020 /* Calculates slow path actions for 'xout'. 'buf' must statically be
1021 * initialized with at least 128 bytes of space. */
1022 static void
1023 compose_slow_path(struct udpif *udpif, struct xlate_out *xout,
1024 const struct flow *flow,
1025 odp_port_t odp_in_port, ofp_port_t ofp_in_port,
1026 struct ofpbuf *buf, uint32_t meter_id,
1027 struct uuid *ofproto_uuid)
1028 {
1029 struct user_action_cookie cookie;
1030 odp_port_t port;
1031 uint32_t pid;
1032
1033 cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
1034 cookie.ofp_in_port = ofp_in_port;
1035 cookie.ofproto_uuid = *ofproto_uuid;
1036 cookie.slow_path.reason = xout->slow;
1037
1038 port = xout->slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)
1039 ? ODPP_NONE
1040 : odp_in_port;
1041 pid = dpif_port_get_pid(udpif->dpif, port, flow_hash_5tuple(flow, 0));
1042
1043 size_t offset;
1044 size_t ac_offset;
1045 if (meter_id != UINT32_MAX) {
1046 /* If slowpath meter is configured, generate clone(meter, userspace)
1047 * action. */
1048 offset = nl_msg_start_nested(buf, OVS_ACTION_ATTR_SAMPLE);
1049 nl_msg_put_u32(buf, OVS_SAMPLE_ATTR_PROBABILITY, UINT32_MAX);
1050 ac_offset = nl_msg_start_nested(buf, OVS_SAMPLE_ATTR_ACTIONS);
1051 nl_msg_put_u32(buf, OVS_ACTION_ATTR_METER, meter_id);
1052 }
1053
1054 odp_put_userspace_action(pid, &cookie, sizeof cookie,
1055 ODPP_NONE, false, buf);
1056
1057 if (meter_id != UINT32_MAX) {
1058 nl_msg_end_nested(buf, ac_offset);
1059 nl_msg_end_nested(buf, offset);
1060 }
1061 }
1062
1063 /* If there is no error, the upcall must be destroyed with upcall_uninit()
1064 * before quiescing, as the referred objects are guaranteed to exist only
1065 * until the calling thread quiesces. Otherwise, do not call upcall_uninit()
1066 * since the 'upcall->put_actions' remains uninitialized. */
1067 static int
1068 upcall_receive(struct upcall *upcall, const struct dpif_backer *backer,
1069 const struct dp_packet *packet, enum dpif_upcall_type type,
1070 const struct nlattr *userdata, const struct flow *flow,
1071 const unsigned int mru,
1072 const ovs_u128 *ufid, const unsigned pmd_id)
1073 {
1074 int error;
1075
1076 upcall->type = classify_upcall(type, userdata, &upcall->cookie);
1077 if (upcall->type == BAD_UPCALL) {
1078 return EAGAIN;
1079 } else if (upcall->type == MISS_UPCALL) {
1080 error = xlate_lookup(backer, flow, &upcall->ofproto, &upcall->ipfix,
1081 &upcall->sflow, NULL, &upcall->ofp_in_port);
1082 if (error) {
1083 return error;
1084 }
1085 } else {
1086 struct ofproto_dpif *ofproto
1087 = ofproto_dpif_lookup_by_uuid(&upcall->cookie.ofproto_uuid);
1088 if (!ofproto) {
1089 VLOG_INFO_RL(&rl, "upcall could not find ofproto");
1090 return ENODEV;
1091 }
1092 upcall->ofproto = ofproto;
1093 upcall->ipfix = ofproto->ipfix;
1094 upcall->sflow = ofproto->sflow;
1095 upcall->ofp_in_port = upcall->cookie.ofp_in_port;
1096 }
1097
1098 upcall->recirc = NULL;
1099 upcall->have_recirc_ref = false;
1100 upcall->flow = flow;
1101 upcall->packet = packet;
1102 upcall->ufid = ufid;
1103 upcall->pmd_id = pmd_id;
1104 ofpbuf_use_stub(&upcall->odp_actions, upcall->odp_actions_stub,
1105 sizeof upcall->odp_actions_stub);
1106 ofpbuf_init(&upcall->put_actions, 0);
1107
1108 upcall->xout_initialized = false;
1109 upcall->ukey_persists = false;
1110
1111 upcall->ukey = NULL;
1112 upcall->key = NULL;
1113 upcall->key_len = 0;
1114 upcall->mru = mru;
1115
1116 upcall->out_tun_key = NULL;
1117 upcall->actions = NULL;
1118
1119 return 0;
1120 }
1121
1122 static void
1123 upcall_xlate(struct udpif *udpif, struct upcall *upcall,
1124 struct ofpbuf *odp_actions, struct flow_wildcards *wc)
1125 {
1126 struct dpif_flow_stats stats;
1127 enum xlate_error xerr;
1128 struct xlate_in xin;
1129 struct ds output;
1130
1131 stats.n_packets = 1;
1132 stats.n_bytes = dp_packet_size(upcall->packet);
1133 stats.used = time_msec();
1134 stats.tcp_flags = ntohs(upcall->flow->tcp_flags);
1135
1136 xlate_in_init(&xin, upcall->ofproto,
1137 ofproto_dpif_get_tables_version(upcall->ofproto),
1138 upcall->flow, upcall->ofp_in_port, NULL,
1139 stats.tcp_flags, upcall->packet, wc, odp_actions);
1140
1141 if (upcall->type == MISS_UPCALL) {
1142 xin.resubmit_stats = &stats;
1143
1144 if (xin.frozen_state) {
1145 /* We may install a datapath flow only if we get a reference to the
1146 * recirculation context (otherwise we could have recirculation
1147 * upcalls using recirculation ID for which no context can be
1148 * found). We may still execute the flow's actions even if we
1149 * don't install the flow. */
1150 upcall->recirc = recirc_id_node_from_state(xin.frozen_state);
1151 upcall->have_recirc_ref = recirc_id_node_try_ref_rcu(upcall->recirc);
1152 }
1153 } else {
1154 /* For non-miss upcalls, we are either executing actions (one of which
1155 * is an userspace action) for an upcall, in which case the stats have
1156 * already been taken care of, or there's a flow in the datapath which
1157 * this packet was accounted to. Presumably the revalidators will deal
1158 * with pushing its stats eventually. */
1159 }
1160
1161 upcall->reval_seq = seq_read(udpif->reval_seq);
1162
1163 xerr = xlate_actions(&xin, &upcall->xout);
1164
1165 /* Translate again and log the ofproto trace for
1166 * these two error types. */
1167 if (xerr == XLATE_RECURSION_TOO_DEEP ||
1168 xerr == XLATE_TOO_MANY_RESUBMITS) {
1169 static struct vlog_rate_limit rll = VLOG_RATE_LIMIT_INIT(1, 1);
1170
1171 /* This is a huge log, so be conservative. */
1172 if (!VLOG_DROP_WARN(&rll)) {
1173 ds_init(&output);
1174 ofproto_trace(upcall->ofproto, upcall->flow,
1175 upcall->packet, NULL, 0, NULL, &output);
1176 VLOG_WARN("%s", ds_cstr(&output));
1177 ds_destroy(&output);
1178 }
1179 }
1180
1181 if (wc) {
1182 /* Convert the input port wildcard from OFP to ODP format. There's no
1183 * real way to do this for arbitrary bitmasks since the numbering spaces
1184 * aren't the same. However, flow translation always exact matches the
1185 * whole thing, so we can do the same here. */
1186 WC_MASK_FIELD(wc, in_port.odp_port);
1187 }
1188
1189 upcall->xout_initialized = true;
1190
1191 if (upcall->fitness == ODP_FIT_TOO_LITTLE) {
1192 upcall->xout.slow |= SLOW_MATCH;
1193 }
1194 if (!upcall->xout.slow) {
1195 ofpbuf_use_const(&upcall->put_actions,
1196 odp_actions->data, odp_actions->size);
1197 } else {
1198 /* upcall->put_actions already initialized by upcall_receive(). */
1199 compose_slow_path(udpif, &upcall->xout, upcall->flow,
1200 upcall->flow->in_port.odp_port, upcall->ofp_in_port,
1201 &upcall->put_actions,
1202 upcall->ofproto->up.slowpath_meter_id,
1203 &upcall->ofproto->uuid);
1204 }
1205
1206 /* This function is also called for slow-pathed flows. As we are only
1207 * going to create new datapath flows for actual datapath misses, there is
1208 * no point in creating a ukey otherwise. */
1209 if (upcall->type == MISS_UPCALL) {
1210 upcall->ukey = ukey_create_from_upcall(upcall, wc);
1211 }
1212 }
1213
1214 static void
1215 upcall_uninit(struct upcall *upcall)
1216 {
1217 if (upcall) {
1218 if (upcall->xout_initialized) {
1219 xlate_out_uninit(&upcall->xout);
1220 }
1221 ofpbuf_uninit(&upcall->odp_actions);
1222 ofpbuf_uninit(&upcall->put_actions);
1223 if (upcall->ukey) {
1224 if (!upcall->ukey_persists) {
1225 ukey_delete__(upcall->ukey);
1226 }
1227 } else if (upcall->have_recirc_ref) {
1228 /* The reference was transferred to the ukey if one was created. */
1229 recirc_id_node_unref(upcall->recirc);
1230 }
1231 }
1232 }
1233
1234 /* If there are less flows than the limit, and this is a miss upcall which
1235 *
1236 * - Has no recirc_id, OR
1237 * - Has a recirc_id and we can get a reference on the recirc ctx,
1238 *
1239 * Then we should install the flow (true). Otherwise, return false. */
1240 static bool
1241 should_install_flow(struct udpif *udpif, struct upcall *upcall)
1242 {
1243 unsigned int flow_limit;
1244
1245 if (upcall->type != MISS_UPCALL) {
1246 return false;
1247 } else if (upcall->recirc && !upcall->have_recirc_ref) {
1248 VLOG_DBG_RL(&rl, "upcall: no reference for recirc flow");
1249 return false;
1250 }
1251
1252 atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
1253 if (udpif_get_n_flows(udpif) >= flow_limit) {
1254 VLOG_WARN_RL(&rl, "upcall: datapath flow limit reached");
1255 return false;
1256 }
1257
1258 return true;
1259 }
1260
1261 static int
1262 upcall_cb(const struct dp_packet *packet, const struct flow *flow, ovs_u128 *ufid,
1263 unsigned pmd_id, enum dpif_upcall_type type,
1264 const struct nlattr *userdata, struct ofpbuf *actions,
1265 struct flow_wildcards *wc, struct ofpbuf *put_actions, void *aux)
1266 {
1267 struct udpif *udpif = aux;
1268 struct upcall upcall;
1269 bool megaflow;
1270 int error;
1271
1272 atomic_read_relaxed(&enable_megaflows, &megaflow);
1273
1274 error = upcall_receive(&upcall, udpif->backer, packet, type, userdata,
1275 flow, 0, ufid, pmd_id);
1276 if (error) {
1277 return error;
1278 }
1279
1280 upcall.fitness = ODP_FIT_PERFECT;
1281 error = process_upcall(udpif, &upcall, actions, wc);
1282 if (error) {
1283 goto out;
1284 }
1285
1286 if (upcall.xout.slow && put_actions) {
1287 ofpbuf_put(put_actions, upcall.put_actions.data,
1288 upcall.put_actions.size);
1289 }
1290
1291 if (OVS_UNLIKELY(!megaflow && wc)) {
1292 flow_wildcards_init_for_packet(wc, flow);
1293 }
1294
1295 if (!should_install_flow(udpif, &upcall)) {
1296 error = ENOSPC;
1297 goto out;
1298 }
1299
1300 if (upcall.ukey && !ukey_install(udpif, upcall.ukey)) {
1301 static struct vlog_rate_limit rll = VLOG_RATE_LIMIT_INIT(1, 1);
1302 VLOG_WARN_RL(&rll, "upcall_cb failure: ukey installation fails");
1303 error = ENOSPC;
1304 }
1305 out:
1306 if (!error) {
1307 upcall.ukey_persists = true;
1308 }
1309 upcall_uninit(&upcall);
1310 return error;
1311 }
1312
1313 static size_t
1314 dpif_get_actions(struct udpif *udpif, struct upcall *upcall,
1315 const struct nlattr **actions)
1316 {
1317 size_t actions_len = 0;
1318
1319 if (upcall->actions) {
1320 /* Actions were passed up from datapath. */
1321 *actions = nl_attr_get(upcall->actions);
1322 actions_len = nl_attr_get_size(upcall->actions);
1323 }
1324
1325 if (actions_len == 0) {
1326 /* Lookup actions in userspace cache. */
1327 struct udpif_key *ukey = ukey_lookup(udpif, upcall->ufid,
1328 upcall->pmd_id);
1329 if (ukey) {
1330 ukey_get_actions(ukey, actions, &actions_len);
1331 }
1332 }
1333
1334 return actions_len;
1335 }
1336
1337 static size_t
1338 dpif_read_actions(struct udpif *udpif, struct upcall *upcall,
1339 const struct flow *flow, enum upcall_type type,
1340 void *upcall_data)
1341 {
1342 const struct nlattr *actions = NULL;
1343 size_t actions_len = dpif_get_actions(udpif, upcall, &actions);
1344
1345 if (!actions || !actions_len) {
1346 return 0;
1347 }
1348
1349 switch (type) {
1350 case SFLOW_UPCALL:
1351 dpif_sflow_read_actions(flow, actions, actions_len, upcall_data, true);
1352 break;
1353 case FLOW_SAMPLE_UPCALL:
1354 case IPFIX_UPCALL:
1355 dpif_ipfix_read_actions(flow, actions, actions_len, upcall_data);
1356 break;
1357 case BAD_UPCALL:
1358 case MISS_UPCALL:
1359 case SLOW_PATH_UPCALL:
1360 case CONTROLLER_UPCALL:
1361 default:
1362 break;
1363 }
1364
1365 return actions_len;
1366 }
1367
1368 static int
1369 process_upcall(struct udpif *udpif, struct upcall *upcall,
1370 struct ofpbuf *odp_actions, struct flow_wildcards *wc)
1371 {
1372 const struct dp_packet *packet = upcall->packet;
1373 const struct flow *flow = upcall->flow;
1374 size_t actions_len = 0;
1375
1376 switch (upcall->type) {
1377 case MISS_UPCALL:
1378 case SLOW_PATH_UPCALL:
1379 upcall_xlate(udpif, upcall, odp_actions, wc);
1380 return 0;
1381
1382 case SFLOW_UPCALL:
1383 if (upcall->sflow) {
1384 struct dpif_sflow_actions sflow_actions;
1385
1386 memset(&sflow_actions, 0, sizeof sflow_actions);
1387
1388 actions_len = dpif_read_actions(udpif, upcall, flow,
1389 upcall->type, &sflow_actions);
1390 dpif_sflow_received(upcall->sflow, packet, flow,
1391 flow->in_port.odp_port, &upcall->cookie,
1392 actions_len > 0 ? &sflow_actions : NULL);
1393 }
1394 break;
1395
1396 case IPFIX_UPCALL:
1397 case FLOW_SAMPLE_UPCALL:
1398 if (upcall->ipfix) {
1399 struct flow_tnl output_tunnel_key;
1400 struct dpif_ipfix_actions ipfix_actions;
1401
1402 memset(&ipfix_actions, 0, sizeof ipfix_actions);
1403
1404 if (upcall->out_tun_key) {
1405 odp_tun_key_from_attr(upcall->out_tun_key, &output_tunnel_key);
1406 }
1407
1408 actions_len = dpif_read_actions(udpif, upcall, flow,
1409 upcall->type, &ipfix_actions);
1410 if (upcall->type == IPFIX_UPCALL) {
1411 dpif_ipfix_bridge_sample(upcall->ipfix, packet, flow,
1412 flow->in_port.odp_port,
1413 upcall->cookie.ipfix.output_odp_port,
1414 upcall->out_tun_key ?
1415 &output_tunnel_key : NULL,
1416 actions_len > 0 ?
1417 &ipfix_actions: NULL);
1418 } else {
1419 /* The flow reflects exactly the contents of the packet.
1420 * Sample the packet using it. */
1421 dpif_ipfix_flow_sample(upcall->ipfix, packet, flow,
1422 &upcall->cookie, flow->in_port.odp_port,
1423 upcall->out_tun_key ?
1424 &output_tunnel_key : NULL,
1425 actions_len > 0 ? &ipfix_actions: NULL);
1426 }
1427 }
1428 break;
1429
1430 case CONTROLLER_UPCALL:
1431 {
1432 struct user_action_cookie *cookie = &upcall->cookie;
1433
1434 if (cookie->controller.dont_send) {
1435 return 0;
1436 }
1437
1438 uint32_t recirc_id = cookie->controller.recirc_id;
1439 if (!recirc_id) {
1440 break;
1441 }
1442
1443 const struct recirc_id_node *recirc_node
1444 = recirc_id_node_find(recirc_id);
1445 if (!recirc_node) {
1446 break;
1447 }
1448
1449 const struct frozen_state *state = &recirc_node->state;
1450
1451 struct ofproto_async_msg *am = xmalloc(sizeof *am);
1452 *am = (struct ofproto_async_msg) {
1453 .controller_id = cookie->controller.controller_id,
1454 .oam = OAM_PACKET_IN,
1455 .pin = {
1456 .up = {
1457 .base = {
1458 .packet = xmemdup(dp_packet_data(packet),
1459 dp_packet_size(packet)),
1460 .packet_len = dp_packet_size(packet),
1461 .reason = cookie->controller.reason,
1462 .table_id = state->table_id,
1463 .cookie = get_32aligned_be64(
1464 &cookie->controller.rule_cookie),
1465 .userdata = (recirc_node->state.userdata_len
1466 ? xmemdup(recirc_node->state.userdata,
1467 recirc_node->state.userdata_len)
1468 : NULL),
1469 .userdata_len = recirc_node->state.userdata_len,
1470 },
1471 },
1472 .max_len = cookie->controller.max_len,
1473 },
1474 };
1475
1476 if (cookie->controller.continuation) {
1477 am->pin.up.stack = (state->stack_size
1478 ? xmemdup(state->stack, state->stack_size)
1479 : NULL),
1480 am->pin.up.stack_size = state->stack_size,
1481 am->pin.up.mirrors = state->mirrors,
1482 am->pin.up.conntracked = state->conntracked,
1483 am->pin.up.actions = (state->ofpacts_len
1484 ? xmemdup(state->ofpacts,
1485 state->ofpacts_len) : NULL),
1486 am->pin.up.actions_len = state->ofpacts_len,
1487 am->pin.up.action_set = (state->action_set_len
1488 ? xmemdup(state->action_set,
1489 state->action_set_len)
1490 : NULL),
1491 am->pin.up.action_set_len = state->action_set_len,
1492 am->pin.up.bridge = upcall->ofproto->uuid;
1493 }
1494
1495 /* We don't want to use the upcall 'flow', since it may be
1496 * more specific than the point at which the "controller"
1497 * action was specified. */
1498 struct flow frozen_flow;
1499
1500 frozen_flow = *flow;
1501 if (!state->conntracked) {
1502 flow_clear_conntrack(&frozen_flow);
1503 }
1504
1505 frozen_metadata_to_flow(&state->metadata, &frozen_flow);
1506 flow_get_metadata(&frozen_flow, &am->pin.up.base.flow_metadata);
1507
1508 ofproto_dpif_send_async_msg(upcall->ofproto, am);
1509 }
1510 break;
1511
1512 case BAD_UPCALL:
1513 break;
1514 }
1515
1516 return EAGAIN;
1517 }
1518
1519 static void
1520 handle_upcalls(struct udpif *udpif, struct upcall *upcalls,
1521 size_t n_upcalls)
1522 {
1523 struct dpif_op *opsp[UPCALL_MAX_BATCH * 2];
1524 struct ukey_op ops[UPCALL_MAX_BATCH * 2];
1525 size_t n_ops, n_opsp, i;
1526
1527 /* Handle the packets individually in order of arrival.
1528 *
1529 * - For SLOW_CFM, SLOW_LACP, SLOW_STP, SLOW_BFD, and SLOW_LLDP,
1530 * translation is what processes received packets for these
1531 * protocols.
1532 *
1533 * - For SLOW_ACTION, translation executes the actions directly.
1534 *
1535 * The loop fills 'ops' with an array of operations to execute in the
1536 * datapath. */
1537 n_ops = 0;
1538 for (i = 0; i < n_upcalls; i++) {
1539 struct upcall *upcall = &upcalls[i];
1540 const struct dp_packet *packet = upcall->packet;
1541 struct ukey_op *op;
1542
1543 if (should_install_flow(udpif, upcall)) {
1544 struct udpif_key *ukey = upcall->ukey;
1545
1546 if (ukey_install(udpif, ukey)) {
1547 upcall->ukey_persists = true;
1548 put_op_init(&ops[n_ops++], ukey, DPIF_FP_CREATE);
1549 }
1550 }
1551
1552 if (upcall->odp_actions.size) {
1553 op = &ops[n_ops++];
1554 op->ukey = NULL;
1555 op->dop.type = DPIF_OP_EXECUTE;
1556 op->dop.u.execute.packet = CONST_CAST(struct dp_packet *, packet);
1557 op->dop.u.execute.flow = upcall->flow;
1558 odp_key_to_dp_packet(upcall->key, upcall->key_len,
1559 op->dop.u.execute.packet);
1560 op->dop.u.execute.actions = upcall->odp_actions.data;
1561 op->dop.u.execute.actions_len = upcall->odp_actions.size;
1562 op->dop.u.execute.needs_help = (upcall->xout.slow & SLOW_ACTION) != 0;
1563 op->dop.u.execute.probe = false;
1564 op->dop.u.execute.mtu = upcall->mru;
1565 }
1566 }
1567
1568 /* Execute batch. */
1569 n_opsp = 0;
1570 for (i = 0; i < n_ops; i++) {
1571 opsp[n_opsp++] = &ops[i].dop;
1572 }
1573 dpif_operate(udpif->dpif, opsp, n_opsp);
1574 for (i = 0; i < n_ops; i++) {
1575 struct udpif_key *ukey = ops[i].ukey;
1576
1577 if (ukey) {
1578 ovs_mutex_lock(&ukey->mutex);
1579 if (ops[i].dop.error) {
1580 transition_ukey(ukey, UKEY_EVICTED);
1581 } else if (ukey->state < UKEY_OPERATIONAL) {
1582 transition_ukey(ukey, UKEY_OPERATIONAL);
1583 }
1584 ovs_mutex_unlock(&ukey->mutex);
1585 }
1586 }
1587 }
1588
1589 static uint32_t
1590 get_ukey_hash(const ovs_u128 *ufid, const unsigned pmd_id)
1591 {
1592 return hash_2words(ufid->u32[0], pmd_id);
1593 }
1594
1595 static struct udpif_key *
1596 ukey_lookup(struct udpif *udpif, const ovs_u128 *ufid, const unsigned pmd_id)
1597 {
1598 struct udpif_key *ukey;
1599 int idx = get_ukey_hash(ufid, pmd_id) % N_UMAPS;
1600 struct cmap *cmap = &udpif->ukeys[idx].cmap;
1601
1602 CMAP_FOR_EACH_WITH_HASH (ukey, cmap_node,
1603 get_ukey_hash(ufid, pmd_id), cmap) {
1604 if (ovs_u128_equals(ukey->ufid, *ufid)) {
1605 return ukey;
1606 }
1607 }
1608 return NULL;
1609 }
1610
1611 /* Provides safe lockless access of RCU protected 'ukey->actions'. Callers may
1612 * alternatively access the field directly if they take 'ukey->mutex'. */
1613 static void
1614 ukey_get_actions(struct udpif_key *ukey, const struct nlattr **actions, size_t *size)
1615 {
1616 const struct ofpbuf *buf = ovsrcu_get(struct ofpbuf *, &ukey->actions);
1617 *actions = buf->data;
1618 *size = buf->size;
1619 }
1620
1621 static void
1622 ukey_set_actions(struct udpif_key *ukey, const struct ofpbuf *actions)
1623 {
1624 struct ofpbuf *old_actions = ovsrcu_get_protected(struct ofpbuf *,
1625 &ukey->actions);
1626
1627 if (old_actions) {
1628 ovsrcu_postpone(ofpbuf_delete, old_actions);
1629 }
1630
1631 ovsrcu_set(&ukey->actions, ofpbuf_clone(actions));
1632 }
1633
1634 static struct udpif_key *
1635 ukey_create__(const struct nlattr *key, size_t key_len,
1636 const struct nlattr *mask, size_t mask_len,
1637 bool ufid_present, const ovs_u128 *ufid,
1638 const unsigned pmd_id, const struct ofpbuf *actions,
1639 uint64_t reval_seq, long long int used,
1640 uint32_t key_recirc_id, struct xlate_out *xout)
1641 OVS_NO_THREAD_SAFETY_ANALYSIS
1642 {
1643 struct udpif_key *ukey = xmalloc(sizeof *ukey);
1644
1645 memcpy(&ukey->keybuf, key, key_len);
1646 ukey->key = &ukey->keybuf.nla;
1647 ukey->key_len = key_len;
1648 memcpy(&ukey->maskbuf, mask, mask_len);
1649 ukey->mask = &ukey->maskbuf.nla;
1650 ukey->mask_len = mask_len;
1651 ukey->ufid_present = ufid_present;
1652 ukey->ufid = *ufid;
1653 ukey->pmd_id = pmd_id;
1654 ukey->hash = get_ukey_hash(&ukey->ufid, pmd_id);
1655
1656 ovsrcu_init(&ukey->actions, NULL);
1657 ukey_set_actions(ukey, actions);
1658
1659 ovs_mutex_init(&ukey->mutex);
1660 ukey->dump_seq = 0; /* Not yet dumped */
1661 ukey->reval_seq = reval_seq;
1662 ukey->state = UKEY_CREATED;
1663 ukey->state_thread = ovsthread_id_self();
1664 ukey->state_where = OVS_SOURCE_LOCATOR;
1665 ukey->created = time_msec();
1666 memset(&ukey->stats, 0, sizeof ukey->stats);
1667 ukey->stats.used = used;
1668 ukey->xcache = NULL;
1669
1670 ukey->key_recirc_id = key_recirc_id;
1671 recirc_refs_init(&ukey->recircs);
1672 if (xout) {
1673 /* Take ownership of the action recirc id references. */
1674 recirc_refs_swap(&ukey->recircs, &xout->recircs);
1675 }
1676
1677 return ukey;
1678 }
1679
1680 static struct udpif_key *
1681 ukey_create_from_upcall(struct upcall *upcall, struct flow_wildcards *wc)
1682 {
1683 struct odputil_keybuf keystub, maskstub;
1684 struct ofpbuf keybuf, maskbuf;
1685 bool megaflow;
1686 struct odp_flow_key_parms odp_parms = {
1687 .flow = upcall->flow,
1688 .mask = wc ? &wc->masks : NULL,
1689 };
1690
1691 odp_parms.support = upcall->ofproto->backer->rt_support.odp;
1692 if (upcall->key_len) {
1693 ofpbuf_use_const(&keybuf, upcall->key, upcall->key_len);
1694 } else {
1695 /* dpif-netdev doesn't provide a netlink-formatted flow key in the
1696 * upcall, so convert the upcall's flow here. */
1697 ofpbuf_use_stack(&keybuf, &keystub, sizeof keystub);
1698 odp_flow_key_from_flow(&odp_parms, &keybuf);
1699 }
1700
1701 atomic_read_relaxed(&enable_megaflows, &megaflow);
1702 ofpbuf_use_stack(&maskbuf, &maskstub, sizeof maskstub);
1703 if (megaflow && wc) {
1704 odp_parms.key_buf = &keybuf;
1705 odp_flow_key_from_mask(&odp_parms, &maskbuf);
1706 }
1707
1708 return ukey_create__(keybuf.data, keybuf.size, maskbuf.data, maskbuf.size,
1709 true, upcall->ufid, upcall->pmd_id,
1710 &upcall->put_actions, upcall->reval_seq, 0,
1711 upcall->have_recirc_ref ? upcall->recirc->id : 0,
1712 &upcall->xout);
1713 }
1714
1715 static int
1716 ukey_create_from_dpif_flow(const struct udpif *udpif,
1717 const struct dpif_flow *flow,
1718 struct udpif_key **ukey)
1719 {
1720 struct dpif_flow full_flow;
1721 struct ofpbuf actions;
1722 uint64_t reval_seq;
1723 uint64_t stub[DPIF_FLOW_BUFSIZE / 8];
1724 const struct nlattr *a;
1725 unsigned int left;
1726
1727 if (!flow->key_len || !flow->actions_len) {
1728 struct ofpbuf buf;
1729 int err;
1730
1731 /* If the key or actions were not provided by the datapath, fetch the
1732 * full flow. */
1733 ofpbuf_use_stack(&buf, &stub, sizeof stub);
1734 err = dpif_flow_get(udpif->dpif, flow->key, flow->key_len,
1735 flow->ufid_present ? &flow->ufid : NULL,
1736 flow->pmd_id, &buf, &full_flow);
1737 if (err) {
1738 return err;
1739 }
1740 flow = &full_flow;
1741 }
1742
1743 /* Check the flow actions for recirculation action. As recirculation
1744 * relies on OVS userspace internal state, we need to delete all old
1745 * datapath flows with either a non-zero recirc_id in the key, or any
1746 * recirculation actions upon OVS restart. */
1747 NL_ATTR_FOR_EACH (a, left, flow->key, flow->key_len) {
1748 if (nl_attr_type(a) == OVS_KEY_ATTR_RECIRC_ID
1749 && nl_attr_get_u32(a) != 0) {
1750 return EINVAL;
1751 }
1752 }
1753 NL_ATTR_FOR_EACH (a, left, flow->actions, flow->actions_len) {
1754 if (nl_attr_type(a) == OVS_ACTION_ATTR_RECIRC) {
1755 return EINVAL;
1756 }
1757 }
1758
1759 reval_seq = seq_read(udpif->reval_seq) - 1; /* Ensure revalidation. */
1760 ofpbuf_use_const(&actions, &flow->actions, flow->actions_len);
1761 *ukey = ukey_create__(flow->key, flow->key_len,
1762 flow->mask, flow->mask_len, flow->ufid_present,
1763 &flow->ufid, flow->pmd_id, &actions,
1764 reval_seq, flow->stats.used, 0, NULL);
1765
1766 return 0;
1767 }
1768
1769 static bool
1770 try_ukey_replace(struct umap *umap, struct udpif_key *old_ukey,
1771 struct udpif_key *new_ukey)
1772 OVS_REQUIRES(umap->mutex)
1773 OVS_TRY_LOCK(true, new_ukey->mutex)
1774 {
1775 bool replaced = false;
1776
1777 if (!ovs_mutex_trylock(&old_ukey->mutex)) {
1778 if (old_ukey->state == UKEY_EVICTED) {
1779 /* The flow was deleted during the current revalidator dump,
1780 * but its ukey won't be fully cleaned up until the sweep phase.
1781 * In the mean time, we are receiving upcalls for this traffic.
1782 * Expedite the (new) flow install by replacing the ukey. */
1783 ovs_mutex_lock(&new_ukey->mutex);
1784 cmap_replace(&umap->cmap, &old_ukey->cmap_node,
1785 &new_ukey->cmap_node, new_ukey->hash);
1786 ovsrcu_postpone(ukey_delete__, old_ukey);
1787 transition_ukey(old_ukey, UKEY_DELETED);
1788 transition_ukey(new_ukey, UKEY_VISIBLE);
1789 replaced = true;
1790 }
1791 ovs_mutex_unlock(&old_ukey->mutex);
1792 }
1793
1794 if (replaced) {
1795 COVERAGE_INC(upcall_ukey_replace);
1796 } else {
1797 COVERAGE_INC(handler_duplicate_upcall);
1798 }
1799 return replaced;
1800 }
1801
1802 /* Attempts to insert a ukey into the shared ukey maps.
1803 *
1804 * On success, returns true, installs the ukey and returns it in a locked
1805 * state. Otherwise, returns false. */
1806 static bool
1807 ukey_install__(struct udpif *udpif, struct udpif_key *new_ukey)
1808 OVS_TRY_LOCK(true, new_ukey->mutex)
1809 {
1810 struct umap *umap;
1811 struct udpif_key *old_ukey;
1812 uint32_t idx;
1813 bool locked = false;
1814
1815 idx = new_ukey->hash % N_UMAPS;
1816 umap = &udpif->ukeys[idx];
1817 ovs_mutex_lock(&umap->mutex);
1818 old_ukey = ukey_lookup(udpif, &new_ukey->ufid, new_ukey->pmd_id);
1819 if (old_ukey) {
1820 /* Uncommon case: A ukey is already installed with the same UFID. */
1821 if (old_ukey->key_len == new_ukey->key_len
1822 && !memcmp(old_ukey->key, new_ukey->key, new_ukey->key_len)) {
1823 locked = try_ukey_replace(umap, old_ukey, new_ukey);
1824 } else {
1825 struct ds ds = DS_EMPTY_INITIALIZER;
1826
1827 odp_format_ufid(&old_ukey->ufid, &ds);
1828 ds_put_cstr(&ds, " ");
1829 odp_flow_key_format(old_ukey->key, old_ukey->key_len, &ds);
1830 ds_put_cstr(&ds, "\n");
1831 odp_format_ufid(&new_ukey->ufid, &ds);
1832 ds_put_cstr(&ds, " ");
1833 odp_flow_key_format(new_ukey->key, new_ukey->key_len, &ds);
1834
1835 VLOG_WARN_RL(&rl, "Conflicting ukey for flows:\n%s", ds_cstr(&ds));
1836 ds_destroy(&ds);
1837 }
1838 } else {
1839 ovs_mutex_lock(&new_ukey->mutex);
1840 cmap_insert(&umap->cmap, &new_ukey->cmap_node, new_ukey->hash);
1841 transition_ukey(new_ukey, UKEY_VISIBLE);
1842 locked = true;
1843 }
1844 ovs_mutex_unlock(&umap->mutex);
1845
1846 return locked;
1847 }
1848
1849 static void
1850 transition_ukey_at(struct udpif_key *ukey, enum ukey_state dst,
1851 const char *where)
1852 OVS_REQUIRES(ukey->mutex)
1853 {
1854 if (dst < ukey->state) {
1855 VLOG_ABORT("Invalid ukey transition %d->%d (last transitioned from "
1856 "thread %u at %s)", ukey->state, dst, ukey->state_thread,
1857 ukey->state_where);
1858 }
1859 if (ukey->state == dst && dst == UKEY_OPERATIONAL) {
1860 return;
1861 }
1862
1863 /* Valid state transitions:
1864 * UKEY_CREATED -> UKEY_VISIBLE
1865 * Ukey is now visible in the umap.
1866 * UKEY_VISIBLE -> UKEY_OPERATIONAL
1867 * A handler has installed the flow, and the flow is in the datapath.
1868 * UKEY_VISIBLE -> UKEY_EVICTING
1869 * A handler installs the flow, then revalidator sweeps the ukey before
1870 * the flow is dumped. Most likely the flow was installed; start trying
1871 * to delete it.
1872 * UKEY_VISIBLE -> UKEY_EVICTED
1873 * A handler attempts to install the flow, but the datapath rejects it.
1874 * Consider that the datapath has already destroyed it.
1875 * UKEY_OPERATIONAL -> UKEY_EVICTING
1876 * A revalidator decides to evict the datapath flow.
1877 * UKEY_EVICTING -> UKEY_EVICTED
1878 * A revalidator has evicted the datapath flow.
1879 * UKEY_EVICTED -> UKEY_DELETED
1880 * A revalidator has removed the ukey from the umap and is deleting it.
1881 */
1882 if (ukey->state == dst - 1 || (ukey->state == UKEY_VISIBLE &&
1883 dst < UKEY_DELETED)) {
1884 ukey->state = dst;
1885 } else {
1886 struct ds ds = DS_EMPTY_INITIALIZER;
1887
1888 odp_format_ufid(&ukey->ufid, &ds);
1889 VLOG_WARN_RL(&rl, "Invalid state transition for ukey %s: %d -> %d",
1890 ds_cstr(&ds), ukey->state, dst);
1891 ds_destroy(&ds);
1892 }
1893 ukey->state_thread = ovsthread_id_self();
1894 ukey->state_where = where;
1895 }
1896
1897 static bool
1898 ukey_install(struct udpif *udpif, struct udpif_key *ukey)
1899 {
1900 bool installed;
1901
1902 installed = ukey_install__(udpif, ukey);
1903 if (installed) {
1904 ovs_mutex_unlock(&ukey->mutex);
1905 }
1906
1907 return installed;
1908 }
1909
1910 /* Searches for a ukey in 'udpif->ukeys' that matches 'flow' and attempts to
1911 * lock the ukey. If the ukey does not exist, create it.
1912 *
1913 * Returns 0 on success, setting *result to the matching ukey and returning it
1914 * in a locked state. Otherwise, returns an errno and clears *result. EBUSY
1915 * indicates that another thread is handling this flow. Other errors indicate
1916 * an unexpected condition creating a new ukey.
1917 *
1918 * *error is an output parameter provided to appease the threadsafety analyser,
1919 * and its value matches the return value. */
1920 static int
1921 ukey_acquire(struct udpif *udpif, const struct dpif_flow *flow,
1922 struct udpif_key **result, int *error)
1923 OVS_TRY_LOCK(0, (*result)->mutex)
1924 {
1925 struct udpif_key *ukey;
1926 int retval;
1927
1928 ukey = ukey_lookup(udpif, &flow->ufid, flow->pmd_id);
1929 if (ukey) {
1930 retval = ovs_mutex_trylock(&ukey->mutex);
1931 } else {
1932 /* Usually we try to avoid installing flows from revalidator threads,
1933 * because locking on a umap may cause handler threads to block.
1934 * However there are certain cases, like when ovs-vswitchd is
1935 * restarted, where it is desirable to handle flows that exist in the
1936 * datapath gracefully (ie, don't just clear the datapath). */
1937 bool install;
1938
1939 retval = ukey_create_from_dpif_flow(udpif, flow, &ukey);
1940 if (retval) {
1941 goto done;
1942 }
1943 install = ukey_install__(udpif, ukey);
1944 if (install) {
1945 retval = 0;
1946 } else {
1947 ukey_delete__(ukey);
1948 retval = EBUSY;
1949 }
1950 }
1951
1952 done:
1953 *error = retval;
1954 if (retval) {
1955 *result = NULL;
1956 } else {
1957 *result = ukey;
1958 }
1959 return retval;
1960 }
1961
1962 static void
1963 ukey_delete__(struct udpif_key *ukey)
1964 OVS_NO_THREAD_SAFETY_ANALYSIS
1965 {
1966 if (ukey) {
1967 if (ukey->key_recirc_id) {
1968 recirc_free_id(ukey->key_recirc_id);
1969 }
1970 recirc_refs_unref(&ukey->recircs);
1971 xlate_cache_delete(ukey->xcache);
1972 ofpbuf_delete(ovsrcu_get(struct ofpbuf *, &ukey->actions));
1973 ovs_mutex_destroy(&ukey->mutex);
1974 free(ukey);
1975 }
1976 }
1977
1978 static void
1979 ukey_delete(struct umap *umap, struct udpif_key *ukey)
1980 OVS_REQUIRES(umap->mutex)
1981 {
1982 ovs_mutex_lock(&ukey->mutex);
1983 if (ukey->state < UKEY_DELETED) {
1984 cmap_remove(&umap->cmap, &ukey->cmap_node, ukey->hash);
1985 ovsrcu_postpone(ukey_delete__, ukey);
1986 transition_ukey(ukey, UKEY_DELETED);
1987 }
1988 ovs_mutex_unlock(&ukey->mutex);
1989 }
1990
1991 static bool
1992 should_revalidate(const struct udpif *udpif, uint64_t packets,
1993 long long int used)
1994 {
1995 long long int metric, now, duration;
1996
1997 if (!used) {
1998 /* Always revalidate the first time a flow is dumped. */
1999 return true;
2000 }
2001
2002 if (udpif->dump_duration < 200) {
2003 /* We are likely to handle full revalidation for the flows. */
2004 return true;
2005 }
2006
2007 /* Calculate the mean time between seeing these packets. If this
2008 * exceeds the threshold, then delete the flow rather than performing
2009 * costly revalidation for flows that aren't being hit frequently.
2010 *
2011 * This is targeted at situations where the dump_duration is high (~1s),
2012 * and revalidation is triggered by a call to udpif_revalidate(). In
2013 * these situations, revalidation of all flows causes fluctuations in the
2014 * flow_limit due to the interaction with the dump_duration and max_idle.
2015 * This tends to result in deletion of low-throughput flows anyway, so
2016 * skip the revalidation and just delete those flows. */
2017 packets = MAX(packets, 1);
2018 now = MAX(used, time_msec());
2019 duration = now - used;
2020 metric = duration / packets;
2021
2022 if (metric < 200) {
2023 /* The flow is receiving more than ~5pps, so keep it. */
2024 return true;
2025 }
2026 return false;
2027 }
2028
2029 struct reval_context {
2030 /* Optional output parameters */
2031 struct flow_wildcards *wc;
2032 struct ofpbuf *odp_actions;
2033 struct netflow **netflow;
2034 struct xlate_cache *xcache;
2035
2036 /* Required output parameters */
2037 struct xlate_out xout;
2038 struct flow flow;
2039 };
2040
2041 /* Translates 'key' into a flow, populating 'ctx' as it goes along.
2042 *
2043 * Returns 0 on success, otherwise a positive errno value.
2044 *
2045 * The caller is responsible for uninitializing ctx->xout on success.
2046 */
2047 static int
2048 xlate_key(struct udpif *udpif, const struct nlattr *key, unsigned int len,
2049 const struct dpif_flow_stats *push, struct reval_context *ctx)
2050 {
2051 struct ofproto_dpif *ofproto;
2052 ofp_port_t ofp_in_port;
2053 enum odp_key_fitness fitness;
2054 struct xlate_in xin;
2055 int error;
2056
2057 fitness = odp_flow_key_to_flow(key, len, &ctx->flow);
2058 if (fitness == ODP_FIT_ERROR) {
2059 return EINVAL;
2060 }
2061
2062 error = xlate_lookup(udpif->backer, &ctx->flow, &ofproto, NULL, NULL,
2063 ctx->netflow, &ofp_in_port);
2064 if (error) {
2065 return error;
2066 }
2067
2068 xlate_in_init(&xin, ofproto, ofproto_dpif_get_tables_version(ofproto),
2069 &ctx->flow, ofp_in_port, NULL, push->tcp_flags,
2070 NULL, ctx->wc, ctx->odp_actions);
2071 if (push->n_packets) {
2072 xin.resubmit_stats = push;
2073 xin.allow_side_effects = true;
2074 }
2075 xin.xcache = ctx->xcache;
2076 xlate_actions(&xin, &ctx->xout);
2077 if (fitness == ODP_FIT_TOO_LITTLE) {
2078 ctx->xout.slow |= SLOW_MATCH;
2079 }
2080
2081 return 0;
2082 }
2083
2084 static int
2085 xlate_ukey(struct udpif *udpif, const struct udpif_key *ukey,
2086 uint16_t tcp_flags, struct reval_context *ctx)
2087 {
2088 struct dpif_flow_stats push = {
2089 .tcp_flags = tcp_flags,
2090 };
2091 return xlate_key(udpif, ukey->key, ukey->key_len, &push, ctx);
2092 }
2093
2094 static int
2095 populate_xcache(struct udpif *udpif, struct udpif_key *ukey,
2096 uint16_t tcp_flags)
2097 OVS_REQUIRES(ukey->mutex)
2098 {
2099 struct reval_context ctx = {
2100 .odp_actions = NULL,
2101 .netflow = NULL,
2102 .wc = NULL,
2103 };
2104 int error;
2105
2106 ovs_assert(!ukey->xcache);
2107 ukey->xcache = ctx.xcache = xlate_cache_new();
2108 error = xlate_ukey(udpif, ukey, tcp_flags, &ctx);
2109 if (error) {
2110 return error;
2111 }
2112 xlate_out_uninit(&ctx.xout);
2113
2114 return 0;
2115 }
2116
2117 static enum reval_result
2118 revalidate_ukey__(struct udpif *udpif, const struct udpif_key *ukey,
2119 uint16_t tcp_flags, struct ofpbuf *odp_actions,
2120 struct recirc_refs *recircs, struct xlate_cache *xcache)
2121 {
2122 struct xlate_out *xoutp;
2123 struct netflow *netflow;
2124 struct flow_wildcards dp_mask, wc;
2125 enum reval_result result;
2126 struct reval_context ctx = {
2127 .odp_actions = odp_actions,
2128 .netflow = &netflow,
2129 .xcache = xcache,
2130 .wc = &wc,
2131 };
2132
2133 result = UKEY_DELETE;
2134 xoutp = NULL;
2135 netflow = NULL;
2136
2137 if (xlate_ukey(udpif, ukey, tcp_flags, &ctx)) {
2138 goto exit;
2139 }
2140 xoutp = &ctx.xout;
2141
2142 if (xoutp->avoid_caching) {
2143 goto exit;
2144 }
2145
2146 if (xoutp->slow) {
2147 struct ofproto_dpif *ofproto;
2148 ofp_port_t ofp_in_port;
2149
2150 ofproto = xlate_lookup_ofproto(udpif->backer, &ctx.flow, &ofp_in_port);
2151
2152 ofpbuf_clear(odp_actions);
2153
2154 if (!ofproto) {
2155 goto exit;
2156 }
2157
2158 compose_slow_path(udpif, xoutp, &ctx.flow, ctx.flow.in_port.odp_port,
2159 ofp_in_port, odp_actions,
2160 ofproto->up.slowpath_meter_id, &ofproto->uuid);
2161 }
2162
2163 if (odp_flow_key_to_mask(ukey->mask, ukey->mask_len, &dp_mask, &ctx.flow)
2164 == ODP_FIT_ERROR) {
2165 goto exit;
2166 }
2167
2168 /* Do not modify if any bit is wildcarded by the installed datapath flow,
2169 * but not the newly revalidated wildcard mask (wc), i.e., if revalidation
2170 * tells that the datapath flow is now too generic and must be narrowed
2171 * down. Note that we do not know if the datapath has ignored any of the
2172 * wildcarded bits, so we may be overly conservative here. */
2173 if (flow_wildcards_has_extra(&dp_mask, ctx.wc)) {
2174 goto exit;
2175 }
2176
2177 if (!ofpbuf_equal(odp_actions,
2178 ovsrcu_get(struct ofpbuf *, &ukey->actions))) {
2179 /* The datapath mask was OK, but the actions seem to have changed.
2180 * Let's modify it in place. */
2181 result = UKEY_MODIFY;
2182 /* Transfer recirc action ID references to the caller. */
2183 recirc_refs_swap(recircs, &xoutp->recircs);
2184 goto exit;
2185 }
2186
2187 result = UKEY_KEEP;
2188
2189 exit:
2190 if (netflow && result == UKEY_DELETE) {
2191 netflow_flow_clear(netflow, &ctx.flow);
2192 }
2193 xlate_out_uninit(xoutp);
2194 return result;
2195 }
2196
2197 /* Verifies that the datapath actions of 'ukey' are still correct, and pushes
2198 * 'stats' for it.
2199 *
2200 * Returns a recommended action for 'ukey', options include:
2201 * UKEY_DELETE The ukey should be deleted.
2202 * UKEY_KEEP The ukey is fine as is.
2203 * UKEY_MODIFY The ukey's actions should be changed but is otherwise
2204 * fine. Callers should change the actions to those found
2205 * in the caller supplied 'odp_actions' buffer. The
2206 * recirculation references can be found in 'recircs' and
2207 * must be handled by the caller.
2208 *
2209 * If the result is UKEY_MODIFY, then references to all recirc_ids used by the
2210 * new flow will be held within 'recircs' (which may be none).
2211 *
2212 * The caller is responsible for both initializing 'recircs' prior this call,
2213 * and ensuring any references are eventually freed.
2214 */
2215 static enum reval_result
2216 revalidate_ukey(struct udpif *udpif, struct udpif_key *ukey,
2217 const struct dpif_flow_stats *stats,
2218 struct ofpbuf *odp_actions, uint64_t reval_seq,
2219 struct recirc_refs *recircs)
2220 OVS_REQUIRES(ukey->mutex)
2221 {
2222 bool need_revalidate = ukey->reval_seq != reval_seq;
2223 enum reval_result result = UKEY_DELETE;
2224 struct dpif_flow_stats push;
2225
2226 ofpbuf_clear(odp_actions);
2227
2228 push.used = stats->used;
2229 push.tcp_flags = stats->tcp_flags;
2230 push.n_packets = (stats->n_packets > ukey->stats.n_packets
2231 ? stats->n_packets - ukey->stats.n_packets
2232 : 0);
2233 push.n_bytes = (stats->n_bytes > ukey->stats.n_bytes
2234 ? stats->n_bytes - ukey->stats.n_bytes
2235 : 0);
2236
2237 if (need_revalidate) {
2238 if (should_revalidate(udpif, push.n_packets, ukey->stats.used)) {
2239 if (!ukey->xcache) {
2240 ukey->xcache = xlate_cache_new();
2241 } else {
2242 xlate_cache_clear(ukey->xcache);
2243 }
2244 result = revalidate_ukey__(udpif, ukey, push.tcp_flags,
2245 odp_actions, recircs, ukey->xcache);
2246 } /* else delete; too expensive to revalidate */
2247 } else if (!push.n_packets || ukey->xcache
2248 || !populate_xcache(udpif, ukey, push.tcp_flags)) {
2249 result = UKEY_KEEP;
2250 }
2251
2252 /* Stats for deleted flows will be attributed upon flow deletion. Skip. */
2253 if (result != UKEY_DELETE) {
2254 xlate_push_stats(ukey->xcache, &push);
2255 ukey->stats = *stats;
2256 ukey->reval_seq = reval_seq;
2257 }
2258
2259 return result;
2260 }
2261
2262 static void
2263 delete_op_init__(struct udpif *udpif, struct ukey_op *op,
2264 const struct dpif_flow *flow)
2265 {
2266 op->ukey = NULL;
2267 op->dop.type = DPIF_OP_FLOW_DEL;
2268 op->dop.u.flow_del.key = flow->key;
2269 op->dop.u.flow_del.key_len = flow->key_len;
2270 op->dop.u.flow_del.ufid = flow->ufid_present ? &flow->ufid : NULL;
2271 op->dop.u.flow_del.pmd_id = flow->pmd_id;
2272 op->dop.u.flow_del.stats = &op->stats;
2273 op->dop.u.flow_del.terse = udpif_use_ufid(udpif);
2274 }
2275
2276 static void
2277 delete_op_init(struct udpif *udpif, struct ukey_op *op, struct udpif_key *ukey)
2278 {
2279 op->ukey = ukey;
2280 op->dop.type = DPIF_OP_FLOW_DEL;
2281 op->dop.u.flow_del.key = ukey->key;
2282 op->dop.u.flow_del.key_len = ukey->key_len;
2283 op->dop.u.flow_del.ufid = ukey->ufid_present ? &ukey->ufid : NULL;
2284 op->dop.u.flow_del.pmd_id = ukey->pmd_id;
2285 op->dop.u.flow_del.stats = &op->stats;
2286 op->dop.u.flow_del.terse = udpif_use_ufid(udpif);
2287 }
2288
2289 static void
2290 put_op_init(struct ukey_op *op, struct udpif_key *ukey,
2291 enum dpif_flow_put_flags flags)
2292 {
2293 op->ukey = ukey;
2294 op->dop.type = DPIF_OP_FLOW_PUT;
2295 op->dop.u.flow_put.flags = flags;
2296 op->dop.u.flow_put.key = ukey->key;
2297 op->dop.u.flow_put.key_len = ukey->key_len;
2298 op->dop.u.flow_put.mask = ukey->mask;
2299 op->dop.u.flow_put.mask_len = ukey->mask_len;
2300 op->dop.u.flow_put.ufid = ukey->ufid_present ? &ukey->ufid : NULL;
2301 op->dop.u.flow_put.pmd_id = ukey->pmd_id;
2302 op->dop.u.flow_put.stats = NULL;
2303 ukey_get_actions(ukey, &op->dop.u.flow_put.actions,
2304 &op->dop.u.flow_put.actions_len);
2305 }
2306
2307 /* Executes datapath operations 'ops' and attributes stats retrieved from the
2308 * datapath as part of those operations. */
2309 static void
2310 push_dp_ops(struct udpif *udpif, struct ukey_op *ops, size_t n_ops)
2311 {
2312 struct dpif_op *opsp[REVALIDATE_MAX_BATCH];
2313 size_t i;
2314
2315 ovs_assert(n_ops <= REVALIDATE_MAX_BATCH);
2316 for (i = 0; i < n_ops; i++) {
2317 opsp[i] = &ops[i].dop;
2318 }
2319 dpif_operate(udpif->dpif, opsp, n_ops);
2320
2321 for (i = 0; i < n_ops; i++) {
2322 struct ukey_op *op = &ops[i];
2323 struct dpif_flow_stats *push, *stats, push_buf;
2324
2325 stats = op->dop.u.flow_del.stats;
2326 push = &push_buf;
2327
2328 if (op->dop.type != DPIF_OP_FLOW_DEL) {
2329 /* Only deleted flows need their stats pushed. */
2330 continue;
2331 }
2332
2333 if (op->dop.error) {
2334 /* flow_del error, 'stats' is unusable. */
2335 if (op->ukey) {
2336 ovs_mutex_lock(&op->ukey->mutex);
2337 transition_ukey(op->ukey, UKEY_EVICTED);
2338 ovs_mutex_unlock(&op->ukey->mutex);
2339 }
2340 continue;
2341 }
2342
2343 if (op->ukey) {
2344 ovs_mutex_lock(&op->ukey->mutex);
2345 transition_ukey(op->ukey, UKEY_EVICTED);
2346 push->used = MAX(stats->used, op->ukey->stats.used);
2347 push->tcp_flags = stats->tcp_flags | op->ukey->stats.tcp_flags;
2348 push->n_packets = stats->n_packets - op->ukey->stats.n_packets;
2349 push->n_bytes = stats->n_bytes - op->ukey->stats.n_bytes;
2350 ovs_mutex_unlock(&op->ukey->mutex);
2351 } else {
2352 push = stats;
2353 }
2354
2355 if (push->n_packets || netflow_exists()) {
2356 const struct nlattr *key = op->dop.u.flow_del.key;
2357 size_t key_len = op->dop.u.flow_del.key_len;
2358 struct netflow *netflow;
2359 struct reval_context ctx = {
2360 .netflow = &netflow,
2361 };
2362 int error;
2363
2364 if (op->ukey) {
2365 ovs_mutex_lock(&op->ukey->mutex);
2366 if (op->ukey->xcache) {
2367 xlate_push_stats(op->ukey->xcache, push);
2368 ovs_mutex_unlock(&op->ukey->mutex);
2369 continue;
2370 }
2371 ovs_mutex_unlock(&op->ukey->mutex);
2372 key = op->ukey->key;
2373 key_len = op->ukey->key_len;
2374 }
2375
2376 error = xlate_key(udpif, key, key_len, push, &ctx);
2377 if (error) {
2378 static struct vlog_rate_limit rll = VLOG_RATE_LIMIT_INIT(1, 5);
2379 VLOG_WARN_RL(&rll, "xlate_key failed (%s)!",
2380 ovs_strerror(error));
2381 } else {
2382 xlate_out_uninit(&ctx.xout);
2383 if (netflow) {
2384 netflow_flow_clear(netflow, &ctx.flow);
2385 }
2386 }
2387 }
2388 }
2389 }
2390
2391 /* Executes datapath operations 'ops', attributes stats retrieved from the
2392 * datapath, and deletes ukeys corresponding to deleted flows. */
2393 static void
2394 push_ukey_ops(struct udpif *udpif, struct umap *umap,
2395 struct ukey_op *ops, size_t n_ops)
2396 {
2397 int i;
2398
2399 push_dp_ops(udpif, ops, n_ops);
2400 ovs_mutex_lock(&umap->mutex);
2401 for (i = 0; i < n_ops; i++) {
2402 if (ops[i].dop.type == DPIF_OP_FLOW_DEL) {
2403 ukey_delete(umap, ops[i].ukey);
2404 }
2405 }
2406 ovs_mutex_unlock(&umap->mutex);
2407 }
2408
2409 static void
2410 log_unexpected_flow(const struct dpif_flow *flow, int error)
2411 {
2412 struct ds ds = DS_EMPTY_INITIALIZER;
2413
2414 ds_put_format(&ds, "Failed to acquire udpif_key corresponding to "
2415 "unexpected flow (%s): ", ovs_strerror(error));
2416 odp_format_ufid(&flow->ufid, &ds);
2417
2418 static struct vlog_rate_limit rll = VLOG_RATE_LIMIT_INIT(10, 60);
2419 VLOG_WARN_RL(&rll, "%s", ds_cstr(&ds));
2420
2421 ds_destroy(&ds);
2422 }
2423
2424 static void
2425 reval_op_init(struct ukey_op *op, enum reval_result result,
2426 struct udpif *udpif, struct udpif_key *ukey,
2427 struct recirc_refs *recircs, struct ofpbuf *odp_actions)
2428 OVS_REQUIRES(ukey->mutex)
2429 {
2430 if (result == UKEY_DELETE) {
2431 delete_op_init(udpif, op, ukey);
2432 transition_ukey(ukey, UKEY_EVICTING);
2433 } else if (result == UKEY_MODIFY) {
2434 /* Store the new recircs. */
2435 recirc_refs_swap(&ukey->recircs, recircs);
2436 /* Release old recircs. */
2437 recirc_refs_unref(recircs);
2438 /* ukey->key_recirc_id remains, as the key is the same as before. */
2439
2440 ukey_set_actions(ukey, odp_actions);
2441 put_op_init(op, ukey, DPIF_FP_MODIFY);
2442 }
2443 }
2444
2445 static void
2446 revalidate(struct revalidator *revalidator)
2447 {
2448 uint64_t odp_actions_stub[1024 / 8];
2449 struct ofpbuf odp_actions = OFPBUF_STUB_INITIALIZER(odp_actions_stub);
2450
2451 struct udpif *udpif = revalidator->udpif;
2452 struct dpif_flow_dump_thread *dump_thread;
2453 uint64_t dump_seq, reval_seq;
2454 unsigned int flow_limit;
2455
2456 dump_seq = seq_read(udpif->dump_seq);
2457 reval_seq = seq_read(udpif->reval_seq);
2458 atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
2459 dump_thread = dpif_flow_dump_thread_create(udpif->dump);
2460 for (;;) {
2461 struct ukey_op ops[REVALIDATE_MAX_BATCH];
2462 int n_ops = 0;
2463
2464 struct dpif_flow flows[REVALIDATE_MAX_BATCH];
2465 const struct dpif_flow *f;
2466 int n_dumped;
2467
2468 long long int max_idle;
2469 long long int now;
2470 size_t n_dp_flows;
2471 bool kill_them_all;
2472
2473 n_dumped = dpif_flow_dump_next(dump_thread, flows, ARRAY_SIZE(flows));
2474 if (!n_dumped) {
2475 break;
2476 }
2477
2478 now = time_msec();
2479
2480 /* In normal operation we want to keep flows around until they have
2481 * been idle for 'ofproto_max_idle' milliseconds. However:
2482 *
2483 * - If the number of datapath flows climbs above 'flow_limit',
2484 * drop that down to 100 ms to try to bring the flows down to
2485 * the limit.
2486 *
2487 * - If the number of datapath flows climbs above twice
2488 * 'flow_limit', delete all the datapath flows as an emergency
2489 * measure. (We reassess this condition for the next batch of
2490 * datapath flows, so we will recover before all the flows are
2491 * gone.) */
2492 n_dp_flows = udpif_get_n_flows(udpif);
2493 kill_them_all = n_dp_flows > flow_limit * 2;
2494 max_idle = n_dp_flows > flow_limit ? 100 : ofproto_max_idle;
2495
2496 for (f = flows; f < &flows[n_dumped]; f++) {
2497 long long int used = f->stats.used;
2498 struct recirc_refs recircs = RECIRC_REFS_EMPTY_INITIALIZER;
2499 enum reval_result result;
2500 struct udpif_key *ukey;
2501 bool already_dumped;
2502 int error;
2503
2504 if (ukey_acquire(udpif, f, &ukey, &error)) {
2505 if (error == EBUSY) {
2506 /* Another thread is processing this flow, so don't bother
2507 * processing it.*/
2508 COVERAGE_INC(upcall_ukey_contention);
2509 } else {
2510 log_unexpected_flow(f, error);
2511 if (error != ENOENT) {
2512 delete_op_init__(udpif, &ops[n_ops++], f);
2513 }
2514 }
2515 continue;
2516 }
2517
2518 already_dumped = ukey->dump_seq == dump_seq;
2519 if (already_dumped) {
2520 /* The flow has already been handled during this flow dump
2521 * operation. Skip it. */
2522 if (ukey->xcache) {
2523 COVERAGE_INC(dumped_duplicate_flow);
2524 } else {
2525 COVERAGE_INC(dumped_new_flow);
2526 }
2527 ovs_mutex_unlock(&ukey->mutex);
2528 continue;
2529 }
2530
2531 if (ukey->state <= UKEY_OPERATIONAL) {
2532 /* The flow is now confirmed to be in the datapath. */
2533 transition_ukey(ukey, UKEY_OPERATIONAL);
2534 } else {
2535 VLOG_INFO("Unexpected ukey transition from state %d "
2536 "(last transitioned from thread %u at %s)",
2537 ukey->state, ukey->state_thread, ukey->state_where);
2538 ovs_mutex_unlock(&ukey->mutex);
2539 continue;
2540 }
2541
2542 if (!used) {
2543 used = ukey->created;
2544 }
2545 if (kill_them_all || (used && used < now - max_idle)) {
2546 result = UKEY_DELETE;
2547 } else {
2548 result = revalidate_ukey(udpif, ukey, &f->stats, &odp_actions,
2549 reval_seq, &recircs);
2550 }
2551 ukey->dump_seq = dump_seq;
2552
2553 if (result != UKEY_KEEP) {
2554 /* Takes ownership of 'recircs'. */
2555 reval_op_init(&ops[n_ops++], result, udpif, ukey, &recircs,
2556 &odp_actions);
2557 }
2558 ovs_mutex_unlock(&ukey->mutex);
2559 }
2560
2561 if (n_ops) {
2562 /* Push datapath ops but defer ukey deletion to 'sweep' phase. */
2563 push_dp_ops(udpif, ops, n_ops);
2564 }
2565 ovsrcu_quiesce();
2566 }
2567 dpif_flow_dump_thread_destroy(dump_thread);
2568 ofpbuf_uninit(&odp_actions);
2569 }
2570
2571 /* Pauses the 'revalidator', can only proceed after main thread
2572 * calls udpif_resume_revalidators(). */
2573 static void
2574 revalidator_pause(struct revalidator *revalidator)
2575 {
2576 /* The first block is for sync'ing the pause with main thread. */
2577 ovs_barrier_block(&revalidator->udpif->pause_barrier);
2578 /* The second block is for pausing until main thread resumes. */
2579 ovs_barrier_block(&revalidator->udpif->pause_barrier);
2580 }
2581
2582 static void
2583 revalidator_sweep__(struct revalidator *revalidator, bool purge)
2584 {
2585 struct udpif *udpif;
2586 uint64_t dump_seq, reval_seq;
2587 int slice;
2588
2589 udpif = revalidator->udpif;
2590 dump_seq = seq_read(udpif->dump_seq);
2591 reval_seq = seq_read(udpif->reval_seq);
2592 slice = revalidator - udpif->revalidators;
2593 ovs_assert(slice < udpif->n_revalidators);
2594
2595 for (int i = slice; i < N_UMAPS; i += udpif->n_revalidators) {
2596 uint64_t odp_actions_stub[1024 / 8];
2597 struct ofpbuf odp_actions = OFPBUF_STUB_INITIALIZER(odp_actions_stub);
2598
2599 struct ukey_op ops[REVALIDATE_MAX_BATCH];
2600 struct udpif_key *ukey;
2601 struct umap *umap = &udpif->ukeys[i];
2602 size_t n_ops = 0;
2603
2604 CMAP_FOR_EACH(ukey, cmap_node, &umap->cmap) {
2605 enum ukey_state ukey_state;
2606
2607 /* Handler threads could be holding a ukey lock while it installs a
2608 * new flow, so don't hang around waiting for access to it. */
2609 if (ovs_mutex_trylock(&ukey->mutex)) {
2610 continue;
2611 }
2612 ukey_state = ukey->state;
2613 if (ukey_state == UKEY_OPERATIONAL
2614 || (ukey_state == UKEY_VISIBLE && purge)) {
2615 struct recirc_refs recircs = RECIRC_REFS_EMPTY_INITIALIZER;
2616 bool seq_mismatch = (ukey->dump_seq != dump_seq
2617 && ukey->reval_seq != reval_seq);
2618 enum reval_result result;
2619
2620 if (purge) {
2621 result = UKEY_DELETE;
2622 } else if (!seq_mismatch) {
2623 result = UKEY_KEEP;
2624 } else {
2625 struct dpif_flow_stats stats;
2626 COVERAGE_INC(revalidate_missed_dp_flow);
2627 memset(&stats, 0, sizeof stats);
2628 result = revalidate_ukey(udpif, ukey, &stats, &odp_actions,
2629 reval_seq, &recircs);
2630 }
2631 if (result != UKEY_KEEP) {
2632 /* Clears 'recircs' if filled by revalidate_ukey(). */
2633 reval_op_init(&ops[n_ops++], result, udpif, ukey, &recircs,
2634 &odp_actions);
2635 }
2636 }
2637 ovs_mutex_unlock(&ukey->mutex);
2638
2639 if (ukey_state == UKEY_EVICTED) {
2640 /* The common flow deletion case involves deletion of the flow
2641 * during the dump phase and ukey deletion here. */
2642 ovs_mutex_lock(&umap->mutex);
2643 ukey_delete(umap, ukey);
2644 ovs_mutex_unlock(&umap->mutex);
2645 }
2646
2647 if (n_ops == REVALIDATE_MAX_BATCH) {
2648 /* Update/delete missed flows and clean up corresponding ukeys
2649 * if necessary. */
2650 push_ukey_ops(udpif, umap, ops, n_ops);
2651 n_ops = 0;
2652 }
2653 }
2654
2655 if (n_ops) {
2656 push_ukey_ops(udpif, umap, ops, n_ops);
2657 }
2658
2659 ofpbuf_uninit(&odp_actions);
2660 ovsrcu_quiesce();
2661 }
2662 }
2663
2664 static void
2665 revalidator_sweep(struct revalidator *revalidator)
2666 {
2667 revalidator_sweep__(revalidator, false);
2668 }
2669
2670 static void
2671 revalidator_purge(struct revalidator *revalidator)
2672 {
2673 revalidator_sweep__(revalidator, true);
2674 }
2675
2676 /* In reaction to dpif purge, purges all 'ukey's with same 'pmd_id'. */
2677 static void
2678 dp_purge_cb(void *aux, unsigned pmd_id)
2679 OVS_NO_THREAD_SAFETY_ANALYSIS
2680 {
2681 struct udpif *udpif = aux;
2682 size_t i;
2683
2684 udpif_pause_revalidators(udpif);
2685 for (i = 0; i < N_UMAPS; i++) {
2686 struct ukey_op ops[REVALIDATE_MAX_BATCH];
2687 struct udpif_key *ukey;
2688 struct umap *umap = &udpif->ukeys[i];
2689 size_t n_ops = 0;
2690
2691 CMAP_FOR_EACH(ukey, cmap_node, &umap->cmap) {
2692 if (ukey->pmd_id == pmd_id) {
2693 delete_op_init(udpif, &ops[n_ops++], ukey);
2694 transition_ukey(ukey, UKEY_EVICTING);
2695
2696 if (n_ops == REVALIDATE_MAX_BATCH) {
2697 push_ukey_ops(udpif, umap, ops, n_ops);
2698 n_ops = 0;
2699 }
2700 }
2701 }
2702
2703 if (n_ops) {
2704 push_ukey_ops(udpif, umap, ops, n_ops);
2705 }
2706
2707 ovsrcu_quiesce();
2708 }
2709 udpif_resume_revalidators(udpif);
2710 }
2711 \f
2712 static void
2713 upcall_unixctl_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
2714 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2715 {
2716 struct ds ds = DS_EMPTY_INITIALIZER;
2717 struct udpif *udpif;
2718
2719 LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2720 unsigned int flow_limit;
2721 bool ufid_enabled;
2722 size_t i;
2723
2724 atomic_read_relaxed(&udpif->flow_limit, &flow_limit);
2725 ufid_enabled = udpif_use_ufid(udpif);
2726
2727 ds_put_format(&ds, "%s:\n", dpif_name(udpif->dpif));
2728 ds_put_format(&ds, "\tflows : (current %lu)"
2729 " (avg %u) (max %u) (limit %u)\n", udpif_get_n_flows(udpif),
2730 udpif->avg_n_flows, udpif->max_n_flows, flow_limit);
2731 ds_put_format(&ds, "\tdump duration : %lldms\n", udpif->dump_duration);
2732 ds_put_format(&ds, "\tufid enabled : ");
2733 if (ufid_enabled) {
2734 ds_put_format(&ds, "true\n");
2735 } else {
2736 ds_put_format(&ds, "false\n");
2737 }
2738 ds_put_char(&ds, '\n');
2739
2740 for (i = 0; i < n_revalidators; i++) {
2741 struct revalidator *revalidator = &udpif->revalidators[i];
2742 int j, elements = 0;
2743
2744 for (j = i; j < N_UMAPS; j += n_revalidators) {
2745 elements += cmap_count(&udpif->ukeys[j].cmap);
2746 }
2747 ds_put_format(&ds, "\t%u: (keys %d)\n", revalidator->id, elements);
2748 }
2749 }
2750
2751 unixctl_command_reply(conn, ds_cstr(&ds));
2752 ds_destroy(&ds);
2753 }
2754
2755 /* Disable using the megaflows.
2756 *
2757 * This command is only needed for advanced debugging, so it's not
2758 * documented in the man page. */
2759 static void
2760 upcall_unixctl_disable_megaflows(struct unixctl_conn *conn,
2761 int argc OVS_UNUSED,
2762 const char *argv[] OVS_UNUSED,
2763 void *aux OVS_UNUSED)
2764 {
2765 atomic_store_relaxed(&enable_megaflows, false);
2766 udpif_flush_all_datapaths();
2767 unixctl_command_reply(conn, "megaflows disabled");
2768 }
2769
2770 /* Re-enable using megaflows.
2771 *
2772 * This command is only needed for advanced debugging, so it's not
2773 * documented in the man page. */
2774 static void
2775 upcall_unixctl_enable_megaflows(struct unixctl_conn *conn,
2776 int argc OVS_UNUSED,
2777 const char *argv[] OVS_UNUSED,
2778 void *aux OVS_UNUSED)
2779 {
2780 atomic_store_relaxed(&enable_megaflows, true);
2781 udpif_flush_all_datapaths();
2782 unixctl_command_reply(conn, "megaflows enabled");
2783 }
2784
2785 /* Disable skipping flow attributes during flow dump.
2786 *
2787 * This command is only needed for advanced debugging, so it's not
2788 * documented in the man page. */
2789 static void
2790 upcall_unixctl_disable_ufid(struct unixctl_conn *conn, int argc OVS_UNUSED,
2791 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2792 {
2793 atomic_store_relaxed(&enable_ufid, false);
2794 unixctl_command_reply(conn, "Datapath dumping tersely using UFID disabled");
2795 }
2796
2797 /* Re-enable skipping flow attributes during flow dump.
2798 *
2799 * This command is only needed for advanced debugging, so it's not documented
2800 * in the man page. */
2801 static void
2802 upcall_unixctl_enable_ufid(struct unixctl_conn *conn, int argc OVS_UNUSED,
2803 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2804 {
2805 atomic_store_relaxed(&enable_ufid, true);
2806 unixctl_command_reply(conn, "Datapath dumping tersely using UFID enabled "
2807 "for supported datapaths");
2808 }
2809
2810 /* Set the flow limit.
2811 *
2812 * This command is only needed for advanced debugging, so it's not
2813 * documented in the man page. */
2814 static void
2815 upcall_unixctl_set_flow_limit(struct unixctl_conn *conn,
2816 int argc OVS_UNUSED,
2817 const char *argv[],
2818 void *aux OVS_UNUSED)
2819 {
2820 struct ds ds = DS_EMPTY_INITIALIZER;
2821 struct udpif *udpif;
2822 unsigned int flow_limit = atoi(argv[1]);
2823
2824 LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2825 atomic_store_relaxed(&udpif->flow_limit, flow_limit);
2826 }
2827 ds_put_format(&ds, "set flow_limit to %u\n", flow_limit);
2828 unixctl_command_reply(conn, ds_cstr(&ds));
2829 ds_destroy(&ds);
2830 }
2831
2832 static void
2833 upcall_unixctl_dump_wait(struct unixctl_conn *conn,
2834 int argc OVS_UNUSED,
2835 const char *argv[] OVS_UNUSED,
2836 void *aux OVS_UNUSED)
2837 {
2838 if (ovs_list_is_singleton(&all_udpifs)) {
2839 struct udpif *udpif = NULL;
2840 size_t len;
2841
2842 udpif = OBJECT_CONTAINING(ovs_list_front(&all_udpifs), udpif, list_node);
2843 len = (udpif->n_conns + 1) * sizeof *udpif->conns;
2844 udpif->conn_seq = seq_read(udpif->dump_seq);
2845 udpif->conns = xrealloc(udpif->conns, len);
2846 udpif->conns[udpif->n_conns++] = conn;
2847 } else {
2848 unixctl_command_reply_error(conn, "can't wait on multiple udpifs.");
2849 }
2850 }
2851
2852 static void
2853 upcall_unixctl_purge(struct unixctl_conn *conn, int argc OVS_UNUSED,
2854 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
2855 {
2856 struct udpif *udpif;
2857
2858 LIST_FOR_EACH (udpif, list_node, &all_udpifs) {
2859 int n;
2860
2861 for (n = 0; n < udpif->n_revalidators; n++) {
2862 revalidator_purge(&udpif->revalidators[n]);
2863 }
2864 }
2865 unixctl_command_reply(conn, "");
2866 }