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