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