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