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