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