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