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