xref: /spdk/lib/nvmf/rdma.c (revision 29f0200847c15e8f331d9b70114ebacff5ceed8c)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2016 Intel Corporation. All rights reserved.
3  *   Copyright (c) 2019-2021 Mellanox Technologies LTD. All rights reserved.
4  *   Copyright (c) 2021-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "spdk/config.h"
10 #include "spdk/thread.h"
11 #include "spdk/likely.h"
12 #include "spdk/nvmf_transport.h"
13 #include "spdk/string.h"
14 #include "spdk/trace.h"
15 #include "spdk/tree.h"
16 #include "spdk/util.h"
17 
18 #include "spdk_internal/assert.h"
19 #include "spdk/log.h"
20 #include "spdk_internal/rdma_provider.h"
21 #include "spdk_internal/rdma_utils.h"
22 
23 #include "nvmf_internal.h"
24 #include "transport.h"
25 
26 #include "spdk_internal/trace_defs.h"
27 
28 struct spdk_nvme_rdma_hooks g_nvmf_hooks = {};
29 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_rdma;
30 
31 /*
32  RDMA Connection Resource Defaults
33  */
34 #define NVMF_DEFAULT_MSDBD		16
35 #define NVMF_DEFAULT_TX_SGE		SPDK_NVMF_MAX_SGL_ENTRIES
36 #define NVMF_DEFAULT_RSP_SGE		1
37 #define NVMF_DEFAULT_RX_SGE		2
38 
39 #define NVMF_RDMA_MAX_EVENTS_PER_POLL	32
40 
41 SPDK_STATIC_ASSERT(NVMF_DEFAULT_MSDBD <= SPDK_NVMF_MAX_SGL_ENTRIES,
42 		   "MSDBD must not exceed SPDK_NVMF_MAX_SGL_ENTRIES");
43 
44 /* The RDMA completion queue size */
45 #define DEFAULT_NVMF_RDMA_CQ_SIZE	4096
46 #define MAX_WR_PER_QP(queue_depth)	(queue_depth * 3 + 2)
47 
48 enum spdk_nvmf_rdma_request_state {
49 	/* The request is not currently in use */
50 	RDMA_REQUEST_STATE_FREE = 0,
51 
52 	/* Initial state when request first received */
53 	RDMA_REQUEST_STATE_NEW,
54 
55 	/* The request is queued until a data buffer is available. */
56 	RDMA_REQUEST_STATE_NEED_BUFFER,
57 
58 	/* The request is waiting on RDMA queue depth availability
59 	 * to transfer data from the host to the controller.
60 	 */
61 	RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING,
62 
63 	/* The request is currently transferring data from the host to the controller. */
64 	RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER,
65 
66 	/* The request is ready to execute at the block device */
67 	RDMA_REQUEST_STATE_READY_TO_EXECUTE,
68 
69 	/* The request is currently executing at the block device */
70 	RDMA_REQUEST_STATE_EXECUTING,
71 
72 	/* The request finished executing at the block device */
73 	RDMA_REQUEST_STATE_EXECUTED,
74 
75 	/* The request is waiting on RDMA queue depth availability
76 	 * to transfer data from the controller to the host.
77 	 */
78 	RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING,
79 
80 	/* The request is waiting on RDMA queue depth availability
81 	 * to send response to the host.
82 	 */
83 	RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING,
84 
85 	/* The request is ready to send a completion */
86 	RDMA_REQUEST_STATE_READY_TO_COMPLETE,
87 
88 	/* The request is currently transferring data from the controller to the host. */
89 	RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST,
90 
91 	/* The request currently has an outstanding completion without an
92 	 * associated data transfer.
93 	 */
94 	RDMA_REQUEST_STATE_COMPLETING,
95 
96 	/* The request completed and can be marked free. */
97 	RDMA_REQUEST_STATE_COMPLETED,
98 
99 	/* Terminator */
100 	RDMA_REQUEST_NUM_STATES,
101 };
102 
103 SPDK_TRACE_REGISTER_FN(nvmf_trace, "nvmf_rdma", TRACE_GROUP_NVMF_RDMA)
104 {
105 	spdk_trace_register_object(OBJECT_NVMF_RDMA_IO, 'r');
106 
107 	struct spdk_trace_tpoint_opts opts[] = {
108 		{
109 			"RDMA_REQ_NEW", TRACE_RDMA_REQUEST_STATE_NEW,
110 			OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 1,
111 			{
112 				{ "qpair", SPDK_TRACE_ARG_TYPE_PTR, 8 },
113 				{ "qd", SPDK_TRACE_ARG_TYPE_INT, 4 }
114 			}
115 		},
116 		{
117 			"RDMA_REQ_COMPLETED", TRACE_RDMA_REQUEST_STATE_COMPLETED,
118 			OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
119 			{
120 				{ "qpair", SPDK_TRACE_ARG_TYPE_PTR, 8 },
121 				{ "qd", SPDK_TRACE_ARG_TYPE_INT, 4 }
122 			}
123 		},
124 	};
125 
126 	spdk_trace_register_description_ext(opts, SPDK_COUNTOF(opts));
127 	spdk_trace_register_description("RDMA_REQ_NEED_BUFFER", TRACE_RDMA_REQUEST_STATE_NEED_BUFFER,
128 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
129 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
130 	spdk_trace_register_description("RDMA_REQ_TX_PENDING_C2H",
131 					TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING,
132 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
133 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
134 	spdk_trace_register_description("RDMA_REQ_TX_PENDING_H2C",
135 					TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING,
136 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
137 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
138 	spdk_trace_register_description("RDMA_REQ_TX_H2C",
139 					TRACE_RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER,
140 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
141 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
142 	spdk_trace_register_description("RDMA_REQ_RDY_TO_EXECUTE",
143 					TRACE_RDMA_REQUEST_STATE_READY_TO_EXECUTE,
144 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
145 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
146 	spdk_trace_register_description("RDMA_REQ_EXECUTING",
147 					TRACE_RDMA_REQUEST_STATE_EXECUTING,
148 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
149 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
150 	spdk_trace_register_description("RDMA_REQ_EXECUTED",
151 					TRACE_RDMA_REQUEST_STATE_EXECUTED,
152 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
153 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
154 	spdk_trace_register_description("RDMA_REQ_RDY2COMPL_PEND",
155 					TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING,
156 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
157 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
158 	spdk_trace_register_description("RDMA_REQ_RDY_TO_COMPL",
159 					TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE,
160 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
161 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
162 	spdk_trace_register_description("RDMA_REQ_COMPLETING_C2H",
163 					TRACE_RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST,
164 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
165 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
166 	spdk_trace_register_description("RDMA_REQ_COMPLETING",
167 					TRACE_RDMA_REQUEST_STATE_COMPLETING,
168 					OWNER_TYPE_NONE, OBJECT_NVMF_RDMA_IO, 0,
169 					SPDK_TRACE_ARG_TYPE_PTR, "qpair");
170 
171 	spdk_trace_register_description("RDMA_QP_CREATE", TRACE_RDMA_QP_CREATE,
172 					OWNER_TYPE_NONE, OBJECT_NONE, 0,
173 					SPDK_TRACE_ARG_TYPE_INT, "");
174 	spdk_trace_register_description("RDMA_IBV_ASYNC_EVENT", TRACE_RDMA_IBV_ASYNC_EVENT,
175 					OWNER_TYPE_NONE, OBJECT_NONE, 0,
176 					SPDK_TRACE_ARG_TYPE_INT, "type");
177 	spdk_trace_register_description("RDMA_CM_ASYNC_EVENT", TRACE_RDMA_CM_ASYNC_EVENT,
178 					OWNER_TYPE_NONE, OBJECT_NONE, 0,
179 					SPDK_TRACE_ARG_TYPE_INT, "type");
180 	spdk_trace_register_description("RDMA_QP_DISCONNECT", TRACE_RDMA_QP_DISCONNECT,
181 					OWNER_TYPE_NONE, OBJECT_NONE, 0,
182 					SPDK_TRACE_ARG_TYPE_INT, "");
183 	spdk_trace_register_description("RDMA_QP_DESTROY", TRACE_RDMA_QP_DESTROY,
184 					OWNER_TYPE_NONE, OBJECT_NONE, 0,
185 					SPDK_TRACE_ARG_TYPE_INT, "");
186 }
187 
188 enum spdk_nvmf_rdma_wr_type {
189 	RDMA_WR_TYPE_RECV,
190 	RDMA_WR_TYPE_SEND,
191 	RDMA_WR_TYPE_DATA,
192 };
193 
194 struct spdk_nvmf_rdma_wr {
195 	/* Uses enum spdk_nvmf_rdma_wr_type */
196 	uint8_t type;
197 };
198 
199 /* This structure holds commands as they are received off the wire.
200  * It must be dynamically paired with a full request object
201  * (spdk_nvmf_rdma_request) to service a request. It is separate
202  * from the request because RDMA does not appear to order
203  * completions, so occasionally we'll get a new incoming
204  * command when there aren't any free request objects.
205  */
206 struct spdk_nvmf_rdma_recv {
207 	struct ibv_recv_wr			wr;
208 	struct ibv_sge				sgl[NVMF_DEFAULT_RX_SGE];
209 
210 	struct spdk_nvmf_rdma_qpair		*qpair;
211 
212 	/* In-capsule data buffer */
213 	uint8_t					*buf;
214 
215 	struct spdk_nvmf_rdma_wr		rdma_wr;
216 	uint64_t				receive_tsc;
217 
218 	STAILQ_ENTRY(spdk_nvmf_rdma_recv)	link;
219 };
220 
221 struct spdk_nvmf_rdma_request_data {
222 	struct ibv_send_wr		wr;
223 	struct ibv_sge			sgl[SPDK_NVMF_MAX_SGL_ENTRIES];
224 };
225 
226 struct spdk_nvmf_rdma_request {
227 	struct spdk_nvmf_request		req;
228 
229 	bool					fused_failed;
230 
231 	struct spdk_nvmf_rdma_wr		data_wr;
232 	struct spdk_nvmf_rdma_wr		rsp_wr;
233 
234 	/* Uses enum spdk_nvmf_rdma_request_state */
235 	uint8_t					state;
236 
237 	/* Data offset in req.iov */
238 	uint32_t				offset;
239 
240 	struct spdk_nvmf_rdma_recv		*recv;
241 
242 	struct {
243 		struct	ibv_send_wr		wr;
244 		struct	ibv_sge			sgl[NVMF_DEFAULT_RSP_SGE];
245 	} rsp;
246 
247 	uint16_t				iovpos;
248 	uint16_t				num_outstanding_data_wr;
249 	/* Used to split Write IO with multi SGL payload */
250 	uint16_t				num_remaining_data_wr;
251 	uint64_t				receive_tsc;
252 	struct spdk_nvmf_rdma_request		*fused_pair;
253 	STAILQ_ENTRY(spdk_nvmf_rdma_request)	state_link;
254 	struct ibv_send_wr			*remaining_tranfer_in_wrs;
255 	struct ibv_send_wr			*transfer_wr;
256 	struct spdk_nvmf_rdma_request_data	data;
257 };
258 
259 struct spdk_nvmf_rdma_resource_opts {
260 	struct spdk_nvmf_rdma_qpair	*qpair;
261 	/* qp points either to an ibv_qp object or an ibv_srq object depending on the value of shared. */
262 	void				*qp;
263 	struct spdk_rdma_utils_mem_map	*map;
264 	uint32_t			max_queue_depth;
265 	uint32_t			in_capsule_data_size;
266 	bool				shared;
267 };
268 
269 struct spdk_nvmf_rdma_resources {
270 	/* Array of size "max_queue_depth" containing RDMA requests. */
271 	struct spdk_nvmf_rdma_request		*reqs;
272 
273 	/* Array of size "max_queue_depth" containing RDMA recvs. */
274 	struct spdk_nvmf_rdma_recv		*recvs;
275 
276 	/* Array of size "max_queue_depth" containing 64 byte capsules
277 	 * used for receive.
278 	 */
279 	union nvmf_h2c_msg			*cmds;
280 
281 	/* Array of size "max_queue_depth" containing 16 byte completions
282 	 * to be sent back to the user.
283 	 */
284 	union nvmf_c2h_msg			*cpls;
285 
286 	/* Array of size "max_queue_depth * InCapsuleDataSize" containing
287 	 * buffers to be used for in capsule data.
288 	 */
289 	void					*bufs;
290 
291 	/* Receives that are waiting for a request object */
292 	STAILQ_HEAD(, spdk_nvmf_rdma_recv)	incoming_queue;
293 
294 	/* Queue to track free requests */
295 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	free_queue;
296 };
297 
298 typedef void (*spdk_nvmf_rdma_qpair_ibv_event)(struct spdk_nvmf_rdma_qpair *rqpair);
299 
300 typedef void (*spdk_poller_destroy_cb)(void *ctx);
301 
302 struct spdk_nvmf_rdma_ibv_event_ctx {
303 	struct spdk_nvmf_rdma_qpair			*rqpair;
304 	spdk_nvmf_rdma_qpair_ibv_event			cb_fn;
305 	/* Link to other ibv events associated with this qpair */
306 	STAILQ_ENTRY(spdk_nvmf_rdma_ibv_event_ctx)	link;
307 };
308 
309 struct spdk_nvmf_rdma_qpair {
310 	struct spdk_nvmf_qpair			qpair;
311 
312 	struct spdk_nvmf_rdma_device		*device;
313 	struct spdk_nvmf_rdma_poller		*poller;
314 
315 	struct spdk_rdma_provider_qp		*rdma_qp;
316 	struct rdma_cm_id			*cm_id;
317 	struct spdk_rdma_provider_srq		*srq;
318 	struct rdma_cm_id			*listen_id;
319 
320 	/* Cache the QP number to improve QP search by RB tree. */
321 	uint32_t				qp_num;
322 
323 	/* The maximum number of I/O outstanding on this connection at one time */
324 	uint16_t				max_queue_depth;
325 
326 	/* The maximum number of active RDMA READ and ATOMIC operations at one time */
327 	uint16_t				max_read_depth;
328 
329 	/* The maximum number of RDMA SEND operations at one time */
330 	uint32_t				max_send_depth;
331 
332 	/* The current number of outstanding WRs from this qpair's
333 	 * recv queue. Should not exceed device->attr.max_queue_depth.
334 	 */
335 	uint16_t				current_recv_depth;
336 
337 	/* The current number of active RDMA READ operations */
338 	uint16_t				current_read_depth;
339 
340 	/* The current number of posted WRs from this qpair's
341 	 * send queue. Should not exceed max_send_depth.
342 	 */
343 	uint32_t				current_send_depth;
344 
345 	/* The maximum number of SGEs per WR on the send queue */
346 	uint32_t				max_send_sge;
347 
348 	/* The maximum number of SGEs per WR on the recv queue */
349 	uint32_t				max_recv_sge;
350 
351 	struct spdk_nvmf_rdma_resources		*resources;
352 
353 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	pending_rdma_read_queue;
354 
355 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	pending_rdma_write_queue;
356 
357 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	pending_rdma_send_queue;
358 
359 	/* Number of requests not in the free state */
360 	uint32_t				qd;
361 
362 	bool					ibv_in_error_state;
363 
364 	RB_ENTRY(spdk_nvmf_rdma_qpair)		node;
365 
366 	STAILQ_ENTRY(spdk_nvmf_rdma_qpair)	recv_link;
367 
368 	STAILQ_ENTRY(spdk_nvmf_rdma_qpair)	send_link;
369 
370 	/* Points to the a request that has fuse bits set to
371 	 * SPDK_NVME_CMD_FUSE_FIRST, when the qpair is waiting
372 	 * for the request that has SPDK_NVME_CMD_FUSE_SECOND.
373 	 */
374 	struct spdk_nvmf_rdma_request		*fused_first;
375 
376 	/*
377 	 * io_channel which is used to destroy qpair when it is removed from poll group
378 	 */
379 	struct spdk_io_channel		*destruct_channel;
380 
381 	/* List of ibv async events */
382 	STAILQ_HEAD(, spdk_nvmf_rdma_ibv_event_ctx)	ibv_events;
383 
384 	/* Lets us know that we have received the last_wqe event. */
385 	bool					last_wqe_reached;
386 
387 	/* Indicate that nvmf_rdma_close_qpair is called */
388 	bool					to_close;
389 };
390 
391 struct spdk_nvmf_rdma_poller_stat {
392 	uint64_t				completions;
393 	uint64_t				polls;
394 	uint64_t				idle_polls;
395 	uint64_t				requests;
396 	uint64_t				request_latency;
397 	uint64_t				pending_free_request;
398 	uint64_t				pending_rdma_read;
399 	uint64_t				pending_rdma_write;
400 	uint64_t				pending_rdma_send;
401 	struct spdk_rdma_provider_qp_stats	qp_stats;
402 };
403 
404 struct spdk_nvmf_rdma_poller {
405 	struct spdk_nvmf_rdma_device		*device;
406 	struct spdk_nvmf_rdma_poll_group	*group;
407 
408 	int					num_cqe;
409 	int					required_num_wr;
410 	struct ibv_cq				*cq;
411 
412 	/* The maximum number of I/O outstanding on the shared receive queue at one time */
413 	uint16_t				max_srq_depth;
414 	bool					need_destroy;
415 
416 	/* Shared receive queue */
417 	struct spdk_rdma_provider_srq		*srq;
418 
419 	struct spdk_nvmf_rdma_resources		*resources;
420 	struct spdk_nvmf_rdma_poller_stat	stat;
421 
422 	spdk_poller_destroy_cb			destroy_cb;
423 	void					*destroy_cb_ctx;
424 
425 	RB_HEAD(qpairs_tree, spdk_nvmf_rdma_qpair) qpairs;
426 
427 	STAILQ_HEAD(, spdk_nvmf_rdma_qpair)	qpairs_pending_recv;
428 
429 	STAILQ_HEAD(, spdk_nvmf_rdma_qpair)	qpairs_pending_send;
430 
431 	TAILQ_ENTRY(spdk_nvmf_rdma_poller)	link;
432 };
433 
434 struct spdk_nvmf_rdma_poll_group_stat {
435 	uint64_t				pending_data_buffer;
436 };
437 
438 struct spdk_nvmf_rdma_poll_group {
439 	struct spdk_nvmf_transport_poll_group		group;
440 	struct spdk_nvmf_rdma_poll_group_stat		stat;
441 	TAILQ_HEAD(, spdk_nvmf_rdma_poller)		pollers;
442 	TAILQ_ENTRY(spdk_nvmf_rdma_poll_group)		link;
443 };
444 
445 struct spdk_nvmf_rdma_conn_sched {
446 	struct spdk_nvmf_rdma_poll_group *next_admin_pg;
447 	struct spdk_nvmf_rdma_poll_group *next_io_pg;
448 };
449 
450 /* Assuming rdma_cm uses just one protection domain per ibv_context. */
451 struct spdk_nvmf_rdma_device {
452 	struct ibv_device_attr			attr;
453 	struct ibv_context			*context;
454 
455 	struct spdk_rdma_utils_mem_map		*map;
456 	struct ibv_pd				*pd;
457 
458 	int					num_srq;
459 	bool					need_destroy;
460 	bool					ready_to_destroy;
461 	bool					is_ready;
462 
463 	TAILQ_ENTRY(spdk_nvmf_rdma_device)	link;
464 };
465 
466 struct spdk_nvmf_rdma_port {
467 	const struct spdk_nvme_transport_id	*trid;
468 	struct rdma_cm_id			*id;
469 	struct spdk_nvmf_rdma_device		*device;
470 	TAILQ_ENTRY(spdk_nvmf_rdma_port)	link;
471 };
472 
473 struct rdma_transport_opts {
474 	int		num_cqe;
475 	uint32_t	max_srq_depth;
476 	bool		no_srq;
477 	bool		no_wr_batching;
478 	int		acceptor_backlog;
479 };
480 
481 struct spdk_nvmf_rdma_transport {
482 	struct spdk_nvmf_transport	transport;
483 	struct rdma_transport_opts	rdma_opts;
484 
485 	struct spdk_nvmf_rdma_conn_sched conn_sched;
486 
487 	struct rdma_event_channel	*event_channel;
488 
489 	struct spdk_mempool		*data_wr_pool;
490 
491 	struct spdk_poller		*accept_poller;
492 
493 	/* fields used to poll RDMA/IB events */
494 	nfds_t			npoll_fds;
495 	struct pollfd		*poll_fds;
496 
497 	TAILQ_HEAD(, spdk_nvmf_rdma_device)	devices;
498 	TAILQ_HEAD(, spdk_nvmf_rdma_port)	ports;
499 	TAILQ_HEAD(, spdk_nvmf_rdma_poll_group)	poll_groups;
500 
501 	/* ports that are removed unexpectedly and need retry listen */
502 	TAILQ_HEAD(, spdk_nvmf_rdma_port)		retry_ports;
503 };
504 
505 struct poller_manage_ctx {
506 	struct spdk_nvmf_rdma_transport		*rtransport;
507 	struct spdk_nvmf_rdma_poll_group	*rgroup;
508 	struct spdk_nvmf_rdma_poller		*rpoller;
509 	struct spdk_nvmf_rdma_device		*device;
510 
511 	struct spdk_thread			*thread;
512 	volatile int				*inflight_op_counter;
513 };
514 
515 static const struct spdk_json_object_decoder rdma_transport_opts_decoder[] = {
516 	{
517 		"num_cqe", offsetof(struct rdma_transport_opts, num_cqe),
518 		spdk_json_decode_int32, true
519 	},
520 	{
521 		"max_srq_depth", offsetof(struct rdma_transport_opts, max_srq_depth),
522 		spdk_json_decode_uint32, true
523 	},
524 	{
525 		"no_srq", offsetof(struct rdma_transport_opts, no_srq),
526 		spdk_json_decode_bool, true
527 	},
528 	{
529 		"no_wr_batching", offsetof(struct rdma_transport_opts, no_wr_batching),
530 		spdk_json_decode_bool, true
531 	},
532 	{
533 		"acceptor_backlog", offsetof(struct rdma_transport_opts, acceptor_backlog),
534 		spdk_json_decode_int32, true
535 	},
536 };
537 
538 static int
539 nvmf_rdma_qpair_compare(struct spdk_nvmf_rdma_qpair *rqpair1, struct spdk_nvmf_rdma_qpair *rqpair2)
540 {
541 	return rqpair1->qp_num < rqpair2->qp_num ? -1 : rqpair1->qp_num > rqpair2->qp_num;
542 }
543 
544 RB_GENERATE_STATIC(qpairs_tree, spdk_nvmf_rdma_qpair, node, nvmf_rdma_qpair_compare);
545 
546 static bool nvmf_rdma_request_process(struct spdk_nvmf_rdma_transport *rtransport,
547 				      struct spdk_nvmf_rdma_request *rdma_req);
548 
549 static void _poller_submit_sends(struct spdk_nvmf_rdma_transport *rtransport,
550 				 struct spdk_nvmf_rdma_poller *rpoller);
551 
552 static void _poller_submit_recvs(struct spdk_nvmf_rdma_transport *rtransport,
553 				 struct spdk_nvmf_rdma_poller *rpoller);
554 
555 static void _nvmf_rdma_remove_destroyed_device(void *c);
556 
557 static inline enum spdk_nvme_media_error_status_code
558 nvmf_rdma_dif_error_to_compl_status(uint8_t err_type) {
559 	enum spdk_nvme_media_error_status_code result;
560 	switch (err_type)
561 	{
562 	case SPDK_DIF_REFTAG_ERROR:
563 		result = SPDK_NVME_SC_REFERENCE_TAG_CHECK_ERROR;
564 		break;
565 	case SPDK_DIF_APPTAG_ERROR:
566 		result = SPDK_NVME_SC_APPLICATION_TAG_CHECK_ERROR;
567 		break;
568 	case SPDK_DIF_GUARD_ERROR:
569 		result = SPDK_NVME_SC_GUARD_CHECK_ERROR;
570 		break;
571 	default:
572 		SPDK_UNREACHABLE();
573 	}
574 
575 	return result;
576 }
577 
578 /*
579  * Return data_wrs to pool starting from \b data_wr
580  * Request's own response and data WR are excluded
581  */
582 static void
583 _nvmf_rdma_request_free_data(struct spdk_nvmf_rdma_request *rdma_req,
584 			     struct ibv_send_wr *data_wr,
585 			     struct spdk_mempool *pool)
586 {
587 	struct spdk_nvmf_rdma_request_data	*work_requests[SPDK_NVMF_MAX_SGL_ENTRIES];
588 	struct spdk_nvmf_rdma_request_data	*nvmf_data;
589 	struct ibv_send_wr			*next_send_wr;
590 	uint64_t				req_wrid = (uint64_t)&rdma_req->data_wr;
591 	uint32_t				num_wrs = 0;
592 
593 	while (data_wr && data_wr->wr_id == req_wrid) {
594 		nvmf_data = SPDK_CONTAINEROF(data_wr, struct spdk_nvmf_rdma_request_data, wr);
595 		memset(nvmf_data->sgl, 0, sizeof(data_wr->sg_list[0]) * data_wr->num_sge);
596 		data_wr->num_sge = 0;
597 		next_send_wr = data_wr->next;
598 		if (data_wr != &rdma_req->data.wr) {
599 			data_wr->next = NULL;
600 			assert(num_wrs < SPDK_NVMF_MAX_SGL_ENTRIES);
601 			work_requests[num_wrs] = nvmf_data;
602 			num_wrs++;
603 		}
604 		data_wr = (!next_send_wr || next_send_wr == &rdma_req->rsp.wr) ? NULL : next_send_wr;
605 	}
606 
607 	if (num_wrs) {
608 		spdk_mempool_put_bulk(pool, (void **) work_requests, num_wrs);
609 	}
610 }
611 
612 static void
613 nvmf_rdma_request_free_data(struct spdk_nvmf_rdma_request *rdma_req,
614 			    struct spdk_nvmf_rdma_transport *rtransport)
615 {
616 	rdma_req->num_outstanding_data_wr = 0;
617 
618 	_nvmf_rdma_request_free_data(rdma_req, rdma_req->transfer_wr, rtransport->data_wr_pool);
619 
620 	if (rdma_req->remaining_tranfer_in_wrs) {
621 		_nvmf_rdma_request_free_data(rdma_req, rdma_req->remaining_tranfer_in_wrs,
622 					     rtransport->data_wr_pool);
623 		rdma_req->remaining_tranfer_in_wrs = NULL;
624 	}
625 
626 	rdma_req->data.wr.next = NULL;
627 	rdma_req->rsp.wr.next = NULL;
628 }
629 
630 static void
631 nvmf_rdma_dump_request(struct spdk_nvmf_rdma_request *req)
632 {
633 	SPDK_ERRLOG("\t\tRequest Data From Pool: %d\n", req->req.data_from_pool);
634 	if (req->req.cmd) {
635 		SPDK_ERRLOG("\t\tRequest opcode: %d\n", req->req.cmd->nvmf_cmd.opcode);
636 	}
637 	if (req->recv) {
638 		SPDK_ERRLOG("\t\tRequest recv wr_id%lu\n", req->recv->wr.wr_id);
639 	}
640 }
641 
642 static void
643 nvmf_rdma_dump_qpair_contents(struct spdk_nvmf_rdma_qpair *rqpair)
644 {
645 	int i;
646 
647 	SPDK_ERRLOG("Dumping contents of queue pair (QID %d)\n", rqpair->qpair.qid);
648 	for (i = 0; i < rqpair->max_queue_depth; i++) {
649 		if (rqpair->resources->reqs[i].state != RDMA_REQUEST_STATE_FREE) {
650 			nvmf_rdma_dump_request(&rqpair->resources->reqs[i]);
651 		}
652 	}
653 }
654 
655 static void
656 nvmf_rdma_resources_destroy(struct spdk_nvmf_rdma_resources *resources)
657 {
658 	spdk_free(resources->cmds);
659 	spdk_free(resources->cpls);
660 	spdk_free(resources->bufs);
661 	spdk_free(resources->reqs);
662 	spdk_free(resources->recvs);
663 	free(resources);
664 }
665 
666 
667 static struct spdk_nvmf_rdma_resources *
668 nvmf_rdma_resources_create(struct spdk_nvmf_rdma_resource_opts *opts)
669 {
670 	struct spdk_nvmf_rdma_resources		*resources;
671 	struct spdk_nvmf_rdma_request		*rdma_req;
672 	struct spdk_nvmf_rdma_recv		*rdma_recv;
673 	struct spdk_rdma_provider_qp		*qp = NULL;
674 	struct spdk_rdma_provider_srq		*srq = NULL;
675 	struct ibv_recv_wr			*bad_wr = NULL;
676 	struct spdk_rdma_utils_memory_translation translation;
677 	uint32_t				i;
678 	int					rc = 0;
679 
680 	resources = calloc(1, sizeof(struct spdk_nvmf_rdma_resources));
681 	if (!resources) {
682 		SPDK_ERRLOG("Unable to allocate resources for receive queue.\n");
683 		return NULL;
684 	}
685 
686 	resources->reqs = spdk_zmalloc(opts->max_queue_depth * sizeof(*resources->reqs),
687 				       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
688 	resources->recvs = spdk_zmalloc(opts->max_queue_depth * sizeof(*resources->recvs),
689 					0x1000, NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
690 	resources->cmds = spdk_zmalloc(opts->max_queue_depth * sizeof(*resources->cmds),
691 				       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
692 	resources->cpls = spdk_zmalloc(opts->max_queue_depth * sizeof(*resources->cpls),
693 				       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
694 
695 	if (opts->in_capsule_data_size > 0) {
696 		resources->bufs = spdk_zmalloc(opts->max_queue_depth * opts->in_capsule_data_size,
697 					       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY,
698 					       SPDK_MALLOC_DMA);
699 	}
700 
701 	if (!resources->reqs || !resources->recvs || !resources->cmds ||
702 	    !resources->cpls || (opts->in_capsule_data_size && !resources->bufs)) {
703 		SPDK_ERRLOG("Unable to allocate sufficient memory for RDMA queue.\n");
704 		goto cleanup;
705 	}
706 
707 	SPDK_DEBUGLOG(rdma, "Command Array: %p Length: %lx\n",
708 		      resources->cmds, opts->max_queue_depth * sizeof(*resources->cmds));
709 	SPDK_DEBUGLOG(rdma, "Completion Array: %p Length: %lx\n",
710 		      resources->cpls, opts->max_queue_depth * sizeof(*resources->cpls));
711 	if (resources->bufs) {
712 		SPDK_DEBUGLOG(rdma, "In Capsule Data Array: %p Length: %x\n",
713 			      resources->bufs, opts->max_queue_depth *
714 			      opts->in_capsule_data_size);
715 	}
716 
717 	/* Initialize queues */
718 	STAILQ_INIT(&resources->incoming_queue);
719 	STAILQ_INIT(&resources->free_queue);
720 
721 	if (opts->shared) {
722 		srq = (struct spdk_rdma_provider_srq *)opts->qp;
723 	} else {
724 		qp = (struct spdk_rdma_provider_qp *)opts->qp;
725 	}
726 
727 	for (i = 0; i < opts->max_queue_depth; i++) {
728 		rdma_recv = &resources->recvs[i];
729 		rdma_recv->qpair = opts->qpair;
730 
731 		/* Set up memory to receive commands */
732 		if (resources->bufs) {
733 			rdma_recv->buf = (void *)((uintptr_t)resources->bufs + (i *
734 						  opts->in_capsule_data_size));
735 		}
736 
737 		rdma_recv->rdma_wr.type = RDMA_WR_TYPE_RECV;
738 
739 		rdma_recv->sgl[0].addr = (uintptr_t)&resources->cmds[i];
740 		rdma_recv->sgl[0].length = sizeof(resources->cmds[i]);
741 		rc = spdk_rdma_utils_get_translation(opts->map, &resources->cmds[i], sizeof(resources->cmds[i]),
742 						     &translation);
743 		if (rc) {
744 			goto cleanup;
745 		}
746 		rdma_recv->sgl[0].lkey = spdk_rdma_utils_memory_translation_get_lkey(&translation);
747 		rdma_recv->wr.num_sge = 1;
748 
749 		if (rdma_recv->buf) {
750 			rdma_recv->sgl[1].addr = (uintptr_t)rdma_recv->buf;
751 			rdma_recv->sgl[1].length = opts->in_capsule_data_size;
752 			rc = spdk_rdma_utils_get_translation(opts->map, rdma_recv->buf, opts->in_capsule_data_size,
753 							     &translation);
754 			if (rc) {
755 				goto cleanup;
756 			}
757 			rdma_recv->sgl[1].lkey = spdk_rdma_utils_memory_translation_get_lkey(&translation);
758 			rdma_recv->wr.num_sge++;
759 		}
760 
761 		rdma_recv->wr.wr_id = (uintptr_t)&rdma_recv->rdma_wr;
762 		rdma_recv->wr.sg_list = rdma_recv->sgl;
763 		if (srq) {
764 			spdk_rdma_provider_srq_queue_recv_wrs(srq, &rdma_recv->wr);
765 		} else {
766 			spdk_rdma_provider_qp_queue_recv_wrs(qp, &rdma_recv->wr);
767 		}
768 	}
769 
770 	for (i = 0; i < opts->max_queue_depth; i++) {
771 		rdma_req = &resources->reqs[i];
772 
773 		if (opts->qpair != NULL) {
774 			rdma_req->req.qpair = &opts->qpair->qpair;
775 		} else {
776 			rdma_req->req.qpair = NULL;
777 		}
778 		rdma_req->req.cmd = NULL;
779 		rdma_req->req.iovcnt = 0;
780 		rdma_req->req.stripped_data = NULL;
781 
782 		/* Set up memory to send responses */
783 		rdma_req->req.rsp = &resources->cpls[i];
784 
785 		rdma_req->rsp.sgl[0].addr = (uintptr_t)&resources->cpls[i];
786 		rdma_req->rsp.sgl[0].length = sizeof(resources->cpls[i]);
787 		rc = spdk_rdma_utils_get_translation(opts->map, &resources->cpls[i], sizeof(resources->cpls[i]),
788 						     &translation);
789 		if (rc) {
790 			goto cleanup;
791 		}
792 		rdma_req->rsp.sgl[0].lkey = spdk_rdma_utils_memory_translation_get_lkey(&translation);
793 
794 		rdma_req->rsp_wr.type = RDMA_WR_TYPE_SEND;
795 		rdma_req->rsp.wr.wr_id = (uintptr_t)&rdma_req->rsp_wr;
796 		rdma_req->rsp.wr.next = NULL;
797 		rdma_req->rsp.wr.opcode = IBV_WR_SEND;
798 		rdma_req->rsp.wr.send_flags = IBV_SEND_SIGNALED;
799 		rdma_req->rsp.wr.sg_list = rdma_req->rsp.sgl;
800 		rdma_req->rsp.wr.num_sge = SPDK_COUNTOF(rdma_req->rsp.sgl);
801 
802 		/* Set up memory for data buffers */
803 		rdma_req->data_wr.type = RDMA_WR_TYPE_DATA;
804 		rdma_req->data.wr.wr_id = (uintptr_t)&rdma_req->data_wr;
805 		rdma_req->data.wr.next = NULL;
806 		rdma_req->data.wr.send_flags = IBV_SEND_SIGNALED;
807 		rdma_req->data.wr.sg_list = rdma_req->data.sgl;
808 		rdma_req->data.wr.num_sge = SPDK_COUNTOF(rdma_req->data.sgl);
809 
810 		/* Initialize request state to FREE */
811 		rdma_req->state = RDMA_REQUEST_STATE_FREE;
812 		STAILQ_INSERT_TAIL(&resources->free_queue, rdma_req, state_link);
813 	}
814 
815 	if (srq) {
816 		rc = spdk_rdma_provider_srq_flush_recv_wrs(srq, &bad_wr);
817 	} else {
818 		rc = spdk_rdma_provider_qp_flush_recv_wrs(qp, &bad_wr);
819 	}
820 
821 	if (rc) {
822 		goto cleanup;
823 	}
824 
825 	return resources;
826 
827 cleanup:
828 	nvmf_rdma_resources_destroy(resources);
829 	return NULL;
830 }
831 
832 static void
833 nvmf_rdma_qpair_clean_ibv_events(struct spdk_nvmf_rdma_qpair *rqpair)
834 {
835 	struct spdk_nvmf_rdma_ibv_event_ctx *ctx, *tctx;
836 	STAILQ_FOREACH_SAFE(ctx, &rqpair->ibv_events, link, tctx) {
837 		ctx->rqpair = NULL;
838 		/* Memory allocated for ctx is freed in nvmf_rdma_qpair_process_ibv_event */
839 		STAILQ_REMOVE(&rqpair->ibv_events, ctx, spdk_nvmf_rdma_ibv_event_ctx, link);
840 	}
841 }
842 
843 static void nvmf_rdma_poller_destroy(struct spdk_nvmf_rdma_poller *poller);
844 
845 static void
846 nvmf_rdma_qpair_destroy(struct spdk_nvmf_rdma_qpair *rqpair)
847 {
848 	struct spdk_nvmf_rdma_recv	*rdma_recv, *recv_tmp;
849 	struct ibv_recv_wr		*bad_recv_wr = NULL;
850 	int				rc;
851 
852 	spdk_trace_record(TRACE_RDMA_QP_DESTROY, 0, 0, (uintptr_t)rqpair);
853 
854 	if (rqpair->qd != 0) {
855 		struct spdk_nvmf_qpair *qpair = &rqpair->qpair;
856 		struct spdk_nvmf_rdma_transport	*rtransport = SPDK_CONTAINEROF(qpair->transport,
857 				struct spdk_nvmf_rdma_transport, transport);
858 		struct spdk_nvmf_rdma_request *req;
859 		uint32_t i, max_req_count = 0;
860 
861 		SPDK_WARNLOG("Destroying qpair when queue depth is %d\n", rqpair->qd);
862 
863 		if (rqpair->srq == NULL) {
864 			nvmf_rdma_dump_qpair_contents(rqpair);
865 			max_req_count = rqpair->max_queue_depth;
866 		} else if (rqpair->poller && rqpair->resources) {
867 			max_req_count = rqpair->poller->max_srq_depth;
868 		}
869 
870 		SPDK_DEBUGLOG(rdma, "Release incomplete requests\n");
871 		for (i = 0; i < max_req_count; i++) {
872 			req = &rqpair->resources->reqs[i];
873 			if (req->req.qpair == qpair && req->state != RDMA_REQUEST_STATE_FREE) {
874 				/* nvmf_rdma_request_process checks qpair ibv and internal state
875 				 * and completes a request */
876 				nvmf_rdma_request_process(rtransport, req);
877 			}
878 		}
879 		assert(rqpair->qd == 0);
880 	}
881 
882 	if (rqpair->poller) {
883 		RB_REMOVE(qpairs_tree, &rqpair->poller->qpairs, rqpair);
884 
885 		if (rqpair->srq != NULL && rqpair->resources != NULL) {
886 			/* Drop all received but unprocessed commands for this queue and return them to SRQ */
887 			STAILQ_FOREACH_SAFE(rdma_recv, &rqpair->resources->incoming_queue, link, recv_tmp) {
888 				if (rqpair == rdma_recv->qpair) {
889 					STAILQ_REMOVE(&rqpair->resources->incoming_queue, rdma_recv, spdk_nvmf_rdma_recv, link);
890 					spdk_rdma_provider_srq_queue_recv_wrs(rqpair->srq, &rdma_recv->wr);
891 					rc = spdk_rdma_provider_srq_flush_recv_wrs(rqpair->srq, &bad_recv_wr);
892 					if (rc) {
893 						SPDK_ERRLOG("Unable to re-post rx descriptor\n");
894 					}
895 				}
896 			}
897 		}
898 	}
899 
900 	if (rqpair->cm_id) {
901 		if (rqpair->rdma_qp != NULL) {
902 			spdk_rdma_provider_qp_destroy(rqpair->rdma_qp);
903 			rqpair->rdma_qp = NULL;
904 		}
905 
906 		if (rqpair->poller != NULL && rqpair->srq == NULL) {
907 			rqpair->poller->required_num_wr -= MAX_WR_PER_QP(rqpair->max_queue_depth);
908 		}
909 	}
910 
911 	if (rqpair->srq == NULL && rqpair->resources != NULL) {
912 		nvmf_rdma_resources_destroy(rqpair->resources);
913 	}
914 
915 	nvmf_rdma_qpair_clean_ibv_events(rqpair);
916 
917 	if (rqpair->destruct_channel) {
918 		spdk_put_io_channel(rqpair->destruct_channel);
919 		rqpair->destruct_channel = NULL;
920 	}
921 
922 	if (rqpair->poller && rqpair->poller->need_destroy && RB_EMPTY(&rqpair->poller->qpairs)) {
923 		nvmf_rdma_poller_destroy(rqpair->poller);
924 	}
925 
926 	/* destroy cm_id last so cma device will not be freed before we destroy the cq. */
927 	if (rqpair->cm_id) {
928 		rdma_destroy_id(rqpair->cm_id);
929 	}
930 
931 	free(rqpair);
932 }
933 
934 static int
935 nvmf_rdma_resize_cq(struct spdk_nvmf_rdma_qpair *rqpair, struct spdk_nvmf_rdma_device *device)
936 {
937 	struct spdk_nvmf_rdma_poller	*rpoller;
938 	int				rc, num_cqe, required_num_wr;
939 
940 	/* Enlarge CQ size dynamically */
941 	rpoller = rqpair->poller;
942 	required_num_wr = rpoller->required_num_wr + MAX_WR_PER_QP(rqpair->max_queue_depth);
943 	num_cqe = rpoller->num_cqe;
944 	if (num_cqe < required_num_wr) {
945 		num_cqe = spdk_max(num_cqe * 2, required_num_wr);
946 		num_cqe = spdk_min(num_cqe, device->attr.max_cqe);
947 	}
948 
949 	if (rpoller->num_cqe != num_cqe) {
950 		if (device->context->device->transport_type == IBV_TRANSPORT_IWARP) {
951 			SPDK_ERRLOG("iWARP doesn't support CQ resize. Current capacity %u, required %u\n"
952 				    "Using CQ of insufficient size may lead to CQ overrun\n", rpoller->num_cqe, num_cqe);
953 			return -1;
954 		}
955 		if (required_num_wr > device->attr.max_cqe) {
956 			SPDK_ERRLOG("RDMA CQE requirement (%d) exceeds device max_cqe limitation (%d)\n",
957 				    required_num_wr, device->attr.max_cqe);
958 			return -1;
959 		}
960 
961 		SPDK_DEBUGLOG(rdma, "Resize RDMA CQ from %d to %d\n", rpoller->num_cqe, num_cqe);
962 		rc = ibv_resize_cq(rpoller->cq, num_cqe);
963 		if (rc) {
964 			SPDK_ERRLOG("RDMA CQ resize failed: errno %d: %s\n", errno, spdk_strerror(errno));
965 			return -1;
966 		}
967 
968 		rpoller->num_cqe = num_cqe;
969 	}
970 
971 	rpoller->required_num_wr = required_num_wr;
972 	return 0;
973 }
974 
975 static int
976 nvmf_rdma_qpair_initialize(struct spdk_nvmf_qpair *qpair)
977 {
978 	struct spdk_nvmf_rdma_qpair		*rqpair;
979 	struct spdk_nvmf_rdma_transport		*rtransport;
980 	struct spdk_nvmf_transport		*transport;
981 	struct spdk_nvmf_rdma_resource_opts	opts;
982 	struct spdk_nvmf_rdma_device		*device;
983 	struct spdk_rdma_provider_qp_init_attr	qp_init_attr = {};
984 
985 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
986 	device = rqpair->device;
987 
988 	qp_init_attr.qp_context	= rqpair;
989 	qp_init_attr.pd		= device->pd;
990 	qp_init_attr.send_cq	= rqpair->poller->cq;
991 	qp_init_attr.recv_cq	= rqpair->poller->cq;
992 
993 	if (rqpair->srq) {
994 		qp_init_attr.srq		= rqpair->srq->srq;
995 	} else {
996 		qp_init_attr.cap.max_recv_wr	= rqpair->max_queue_depth;
997 	}
998 
999 	/* SEND, READ, and WRITE operations */
1000 	qp_init_attr.cap.max_send_wr	= (uint32_t)rqpair->max_queue_depth * 2;
1001 	qp_init_attr.cap.max_send_sge	= spdk_min((uint32_t)device->attr.max_sge, NVMF_DEFAULT_TX_SGE);
1002 	qp_init_attr.cap.max_recv_sge	= spdk_min((uint32_t)device->attr.max_sge, NVMF_DEFAULT_RX_SGE);
1003 	qp_init_attr.stats		= &rqpair->poller->stat.qp_stats;
1004 
1005 	if (rqpair->srq == NULL && nvmf_rdma_resize_cq(rqpair, device) < 0) {
1006 		SPDK_ERRLOG("Failed to resize the completion queue. Cannot initialize qpair.\n");
1007 		goto error;
1008 	}
1009 
1010 	rqpair->rdma_qp = spdk_rdma_provider_qp_create(rqpair->cm_id, &qp_init_attr);
1011 	if (!rqpair->rdma_qp) {
1012 		goto error;
1013 	}
1014 
1015 	rqpair->qp_num = rqpair->rdma_qp->qp->qp_num;
1016 
1017 	rqpair->max_send_depth = spdk_min((uint32_t)(rqpair->max_queue_depth * 2),
1018 					  qp_init_attr.cap.max_send_wr);
1019 	rqpair->max_send_sge = spdk_min(NVMF_DEFAULT_TX_SGE, qp_init_attr.cap.max_send_sge);
1020 	rqpair->max_recv_sge = spdk_min(NVMF_DEFAULT_RX_SGE, qp_init_attr.cap.max_recv_sge);
1021 	spdk_trace_record(TRACE_RDMA_QP_CREATE, 0, 0, (uintptr_t)rqpair);
1022 	SPDK_DEBUGLOG(rdma, "New RDMA Connection: %p\n", qpair);
1023 
1024 	if (rqpair->poller->srq == NULL) {
1025 		rtransport = SPDK_CONTAINEROF(qpair->transport, struct spdk_nvmf_rdma_transport, transport);
1026 		transport = &rtransport->transport;
1027 
1028 		opts.qp = rqpair->rdma_qp;
1029 		opts.map = device->map;
1030 		opts.qpair = rqpair;
1031 		opts.shared = false;
1032 		opts.max_queue_depth = rqpair->max_queue_depth;
1033 		opts.in_capsule_data_size = transport->opts.in_capsule_data_size;
1034 
1035 		rqpair->resources = nvmf_rdma_resources_create(&opts);
1036 
1037 		if (!rqpair->resources) {
1038 			SPDK_ERRLOG("Unable to allocate resources for receive queue.\n");
1039 			rdma_destroy_qp(rqpair->cm_id);
1040 			goto error;
1041 		}
1042 	} else {
1043 		rqpair->resources = rqpair->poller->resources;
1044 	}
1045 
1046 	rqpair->current_recv_depth = 0;
1047 	STAILQ_INIT(&rqpair->pending_rdma_read_queue);
1048 	STAILQ_INIT(&rqpair->pending_rdma_write_queue);
1049 	STAILQ_INIT(&rqpair->pending_rdma_send_queue);
1050 	rqpair->qpair.queue_depth = 0;
1051 
1052 	return 0;
1053 
1054 error:
1055 	rdma_destroy_id(rqpair->cm_id);
1056 	rqpair->cm_id = NULL;
1057 	return -1;
1058 }
1059 
1060 /* Append the given recv wr structure to the resource structs outstanding recvs list. */
1061 /* This function accepts either a single wr or the first wr in a linked list. */
1062 static void
1063 nvmf_rdma_qpair_queue_recv_wrs(struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_recv_wr *first)
1064 {
1065 	struct spdk_nvmf_rdma_transport *rtransport = SPDK_CONTAINEROF(rqpair->qpair.transport,
1066 			struct spdk_nvmf_rdma_transport, transport);
1067 
1068 	if (rqpair->srq != NULL) {
1069 		spdk_rdma_provider_srq_queue_recv_wrs(rqpair->srq, first);
1070 	} else {
1071 		if (spdk_rdma_provider_qp_queue_recv_wrs(rqpair->rdma_qp, first)) {
1072 			STAILQ_INSERT_TAIL(&rqpair->poller->qpairs_pending_recv, rqpair, recv_link);
1073 		}
1074 	}
1075 
1076 	if (rtransport->rdma_opts.no_wr_batching) {
1077 		_poller_submit_recvs(rtransport, rqpair->poller);
1078 	}
1079 }
1080 
1081 static int
1082 request_transfer_in(struct spdk_nvmf_request *req)
1083 {
1084 	struct spdk_nvmf_rdma_request	*rdma_req;
1085 	struct spdk_nvmf_qpair		*qpair;
1086 	struct spdk_nvmf_rdma_qpair	*rqpair;
1087 	struct spdk_nvmf_rdma_transport *rtransport;
1088 
1089 	qpair = req->qpair;
1090 	rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
1091 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
1092 	rtransport = SPDK_CONTAINEROF(rqpair->qpair.transport,
1093 				      struct spdk_nvmf_rdma_transport, transport);
1094 
1095 	assert(req->xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER);
1096 	assert(rdma_req != NULL);
1097 
1098 	if (spdk_rdma_provider_qp_queue_send_wrs(rqpair->rdma_qp, rdma_req->transfer_wr)) {
1099 		STAILQ_INSERT_TAIL(&rqpair->poller->qpairs_pending_send, rqpair, send_link);
1100 	}
1101 	if (rtransport->rdma_opts.no_wr_batching) {
1102 		_poller_submit_sends(rtransport, rqpair->poller);
1103 	}
1104 
1105 	assert(rqpair->current_read_depth + rdma_req->num_outstanding_data_wr <= rqpair->max_read_depth);
1106 	rqpair->current_read_depth += rdma_req->num_outstanding_data_wr;
1107 	assert(rqpair->current_send_depth + rdma_req->num_outstanding_data_wr <= rqpair->max_send_depth);
1108 	rqpair->current_send_depth += rdma_req->num_outstanding_data_wr;
1109 	return 0;
1110 }
1111 
1112 static inline void
1113 nvmf_rdma_request_reset_transfer_in(struct spdk_nvmf_rdma_request *rdma_req,
1114 				    struct spdk_nvmf_rdma_transport *rtransport)
1115 {
1116 	/* Put completed WRs back to pool and move transfer_wr pointer */
1117 	_nvmf_rdma_request_free_data(rdma_req, rdma_req->transfer_wr, rtransport->data_wr_pool);
1118 	rdma_req->transfer_wr = rdma_req->remaining_tranfer_in_wrs;
1119 	rdma_req->remaining_tranfer_in_wrs = NULL;
1120 	rdma_req->num_outstanding_data_wr = rdma_req->num_remaining_data_wr;
1121 	rdma_req->num_remaining_data_wr = 0;
1122 }
1123 
1124 static inline int
1125 request_prepare_transfer_in_part(struct spdk_nvmf_request *req, uint32_t num_reads_available)
1126 {
1127 	struct spdk_nvmf_rdma_request	*rdma_req;
1128 	struct ibv_send_wr		*wr;
1129 	uint32_t i;
1130 
1131 	rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
1132 
1133 	assert(req->xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER);
1134 	assert(rdma_req != NULL);
1135 	assert(num_reads_available > 0);
1136 	assert(rdma_req->num_outstanding_data_wr > num_reads_available);
1137 	wr = rdma_req->transfer_wr;
1138 
1139 	for (i = 0; i < num_reads_available - 1; i++) {
1140 		wr = wr->next;
1141 	}
1142 
1143 	rdma_req->remaining_tranfer_in_wrs = wr->next;
1144 	rdma_req->num_remaining_data_wr = rdma_req->num_outstanding_data_wr - num_reads_available;
1145 	rdma_req->num_outstanding_data_wr = num_reads_available;
1146 	/* Break chain of WRs to send only part. Once this portion completes, we continue sending RDMA_READs */
1147 	wr->next = NULL;
1148 
1149 	return 0;
1150 }
1151 
1152 static int
1153 request_transfer_out(struct spdk_nvmf_request *req, int *data_posted)
1154 {
1155 	int				num_outstanding_data_wr = 0;
1156 	struct spdk_nvmf_rdma_request	*rdma_req;
1157 	struct spdk_nvmf_qpair		*qpair;
1158 	struct spdk_nvmf_rdma_qpair	*rqpair;
1159 	struct spdk_nvme_cpl		*rsp;
1160 	struct ibv_send_wr		*first = NULL;
1161 	struct spdk_nvmf_rdma_transport *rtransport;
1162 
1163 	*data_posted = 0;
1164 	qpair = req->qpair;
1165 	rsp = &req->rsp->nvme_cpl;
1166 	rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
1167 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
1168 	rtransport = SPDK_CONTAINEROF(rqpair->qpair.transport,
1169 				      struct spdk_nvmf_rdma_transport, transport);
1170 
1171 	/* Advance our sq_head pointer */
1172 	if (qpair->sq_head == qpair->sq_head_max) {
1173 		qpair->sq_head = 0;
1174 	} else {
1175 		qpair->sq_head++;
1176 	}
1177 	rsp->sqhd = qpair->sq_head;
1178 
1179 	/* queue the capsule for the recv buffer */
1180 	assert(rdma_req->recv != NULL);
1181 
1182 	nvmf_rdma_qpair_queue_recv_wrs(rqpair, &rdma_req->recv->wr);
1183 
1184 	rdma_req->recv = NULL;
1185 	assert(rqpair->current_recv_depth > 0);
1186 	rqpair->current_recv_depth--;
1187 
1188 	/* Build the response which consists of optional
1189 	 * RDMA WRITEs to transfer data, plus an RDMA SEND
1190 	 * containing the response.
1191 	 */
1192 	first = &rdma_req->rsp.wr;
1193 
1194 	if (spdk_unlikely(rsp->status.sc != SPDK_NVME_SC_SUCCESS)) {
1195 		/* On failure, data was not read from the controller. So clear the
1196 		 * number of outstanding data WRs to zero.
1197 		 */
1198 		rdma_req->num_outstanding_data_wr = 0;
1199 	} else if (req->xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
1200 		first = rdma_req->transfer_wr;
1201 		*data_posted = 1;
1202 		num_outstanding_data_wr = rdma_req->num_outstanding_data_wr;
1203 	}
1204 	if (spdk_rdma_provider_qp_queue_send_wrs(rqpair->rdma_qp, first)) {
1205 		STAILQ_INSERT_TAIL(&rqpair->poller->qpairs_pending_send, rqpair, send_link);
1206 	}
1207 	if (rtransport->rdma_opts.no_wr_batching) {
1208 		_poller_submit_sends(rtransport, rqpair->poller);
1209 	}
1210 
1211 	/* +1 for the rsp wr */
1212 	assert(rqpair->current_send_depth + num_outstanding_data_wr + 1 <= rqpair->max_send_depth);
1213 	rqpair->current_send_depth += num_outstanding_data_wr + 1;
1214 
1215 	return 0;
1216 }
1217 
1218 static int
1219 nvmf_rdma_event_accept(struct rdma_cm_id *id, struct spdk_nvmf_rdma_qpair *rqpair)
1220 {
1221 	struct spdk_nvmf_rdma_accept_private_data	accept_data;
1222 	struct rdma_conn_param				ctrlr_event_data = {};
1223 	int						rc;
1224 
1225 	accept_data.recfmt = 0;
1226 	accept_data.crqsize = rqpair->max_queue_depth;
1227 
1228 	ctrlr_event_data.private_data = &accept_data;
1229 	ctrlr_event_data.private_data_len = sizeof(accept_data);
1230 	if (id->ps == RDMA_PS_TCP) {
1231 		ctrlr_event_data.responder_resources = 0; /* We accept 0 reads from the host */
1232 		ctrlr_event_data.initiator_depth = rqpair->max_read_depth;
1233 	}
1234 
1235 	/* Configure infinite retries for the initiator side qpair.
1236 	 * We need to pass this value to the initiator to prevent the
1237 	 * initiator side NIC from completing SEND requests back to the
1238 	 * initiator with status rnr_retry_count_exceeded. */
1239 	ctrlr_event_data.rnr_retry_count = 0x7;
1240 
1241 	/* When qpair is created without use of rdma cm API, an additional
1242 	 * information must be provided to initiator in the connection response:
1243 	 * whether qpair is using SRQ and its qp_num
1244 	 * Fields below are ignored by rdma cm if qpair has been
1245 	 * created using rdma cm API. */
1246 	ctrlr_event_data.srq = rqpair->srq ? 1 : 0;
1247 	ctrlr_event_data.qp_num = rqpair->qp_num;
1248 
1249 	rc = spdk_rdma_provider_qp_accept(rqpair->rdma_qp, &ctrlr_event_data);
1250 	if (rc) {
1251 		SPDK_ERRLOG("Error %d on spdk_rdma_provider_qp_accept\n", errno);
1252 	} else {
1253 		SPDK_DEBUGLOG(rdma, "Sent back the accept\n");
1254 	}
1255 
1256 	return rc;
1257 }
1258 
1259 static void
1260 nvmf_rdma_event_reject(struct rdma_cm_id *id, enum spdk_nvmf_rdma_transport_error error)
1261 {
1262 	struct spdk_nvmf_rdma_reject_private_data	rej_data;
1263 
1264 	rej_data.recfmt = 0;
1265 	rej_data.sts = error;
1266 
1267 	rdma_reject(id, &rej_data, sizeof(rej_data));
1268 }
1269 
1270 static int
1271 nvmf_rdma_connect(struct spdk_nvmf_transport *transport, struct rdma_cm_event *event)
1272 {
1273 	struct spdk_nvmf_rdma_transport *rtransport;
1274 	struct spdk_nvmf_rdma_qpair	*rqpair = NULL;
1275 	struct spdk_nvmf_rdma_port	*port;
1276 	struct rdma_conn_param		*rdma_param = NULL;
1277 	const struct spdk_nvmf_rdma_request_private_data *private_data = NULL;
1278 	uint16_t			max_queue_depth;
1279 	uint16_t			max_read_depth;
1280 
1281 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
1282 
1283 	assert(event->id != NULL); /* Impossible. Can't even reject the connection. */
1284 	assert(event->id->verbs != NULL); /* Impossible. No way to handle this. */
1285 
1286 	rdma_param = &event->param.conn;
1287 	if (rdma_param->private_data == NULL ||
1288 	    rdma_param->private_data_len < sizeof(struct spdk_nvmf_rdma_request_private_data)) {
1289 		SPDK_ERRLOG("connect request: no private data provided\n");
1290 		nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_INVALID_PRIVATE_DATA_LENGTH);
1291 		return -1;
1292 	}
1293 
1294 	private_data = rdma_param->private_data;
1295 	if (private_data->recfmt != 0) {
1296 		SPDK_ERRLOG("Received RDMA private data with RECFMT != 0\n");
1297 		nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_INVALID_RECFMT);
1298 		return -1;
1299 	}
1300 
1301 	SPDK_DEBUGLOG(rdma, "Connect Recv on fabric intf name %s, dev_name %s\n",
1302 		      event->id->verbs->device->name, event->id->verbs->device->dev_name);
1303 
1304 	port = event->listen_id->context;
1305 	SPDK_DEBUGLOG(rdma, "Listen Id was %p with verbs %p. ListenAddr: %p\n",
1306 		      event->listen_id, event->listen_id->verbs, port);
1307 
1308 	/* Figure out the supported queue depth. This is a multi-step process
1309 	 * that takes into account hardware maximums, host provided values,
1310 	 * and our target's internal memory limits */
1311 
1312 	SPDK_DEBUGLOG(rdma, "Calculating Queue Depth\n");
1313 
1314 	/* Start with the maximum queue depth allowed by the target */
1315 	max_queue_depth = rtransport->transport.opts.max_queue_depth;
1316 	max_read_depth = rtransport->transport.opts.max_queue_depth;
1317 	SPDK_DEBUGLOG(rdma, "Target Max Queue Depth: %d\n",
1318 		      rtransport->transport.opts.max_queue_depth);
1319 
1320 	/* Next check the local NIC's hardware limitations */
1321 	SPDK_DEBUGLOG(rdma,
1322 		      "Local NIC Max Send/Recv Queue Depth: %d Max Read/Write Queue Depth: %d\n",
1323 		      port->device->attr.max_qp_wr, port->device->attr.max_qp_rd_atom);
1324 	max_queue_depth = spdk_min(max_queue_depth, port->device->attr.max_qp_wr);
1325 	max_read_depth = spdk_min(max_read_depth, port->device->attr.max_qp_init_rd_atom);
1326 
1327 	/* Next check the remote NIC's hardware limitations */
1328 	SPDK_DEBUGLOG(rdma,
1329 		      "Host (Initiator) NIC Max Incoming RDMA R/W operations: %d Max Outgoing RDMA R/W operations: %d\n",
1330 		      rdma_param->initiator_depth, rdma_param->responder_resources);
1331 	/* from man3 rdma_get_cm_event
1332 	 * responder_resources - Specifies the number of responder resources that is requested by the recipient.
1333 	 * The responder_resources field must match the initiator depth specified by the remote node when running
1334 	 * the rdma_connect and rdma_accept functions. */
1335 	if (rdma_param->responder_resources != 0) {
1336 		if (private_data->qid) {
1337 			SPDK_DEBUGLOG(rdma, "Host (Initiator) is not allowed to use RDMA operations,"
1338 				      " responder_resources must be 0 but set to %u\n",
1339 				      rdma_param->responder_resources);
1340 		} else {
1341 			SPDK_WARNLOG("Host (Initiator) is not allowed to use RDMA operations,"
1342 				     " responder_resources must be 0 but set to %u\n",
1343 				     rdma_param->responder_resources);
1344 		}
1345 	}
1346 	/* from man3 rdma_get_cm_event
1347 	 * initiator_depth - Specifies the maximum number of outstanding RDMA read operations that the recipient holds.
1348 	 * The initiator_depth field must match the responder resources specified by the remote node when running
1349 	 * the rdma_connect and rdma_accept functions. */
1350 	if (rdma_param->initiator_depth == 0) {
1351 		SPDK_ERRLOG("Host (Initiator) doesn't support RDMA_READ or atomic operations\n");
1352 		nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_INVALID_IRD);
1353 		return -1;
1354 	}
1355 	max_read_depth = spdk_min(max_read_depth, rdma_param->initiator_depth);
1356 
1357 	SPDK_DEBUGLOG(rdma, "Host Receive Queue Size: %d\n", private_data->hrqsize);
1358 	SPDK_DEBUGLOG(rdma, "Host Send Queue Size: %d\n", private_data->hsqsize);
1359 	max_queue_depth = spdk_min(max_queue_depth, private_data->hrqsize);
1360 	max_queue_depth = spdk_min(max_queue_depth, private_data->hsqsize + 1);
1361 
1362 	SPDK_DEBUGLOG(rdma, "Final Negotiated Queue Depth: %d R/W Depth: %d\n",
1363 		      max_queue_depth, max_read_depth);
1364 
1365 	rqpair = calloc(1, sizeof(struct spdk_nvmf_rdma_qpair));
1366 	if (rqpair == NULL) {
1367 		SPDK_ERRLOG("Could not allocate new connection.\n");
1368 		nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_NO_RESOURCES);
1369 		return -1;
1370 	}
1371 
1372 	rqpair->device = port->device;
1373 	rqpair->max_queue_depth = max_queue_depth;
1374 	rqpair->max_read_depth = max_read_depth;
1375 	rqpair->cm_id = event->id;
1376 	rqpair->listen_id = event->listen_id;
1377 	rqpair->qpair.transport = transport;
1378 	STAILQ_INIT(&rqpair->ibv_events);
1379 	/* use qid from the private data to determine the qpair type
1380 	   qid will be set to the appropriate value when the controller is created */
1381 	rqpair->qpair.qid = private_data->qid;
1382 
1383 	event->id->context = &rqpair->qpair;
1384 
1385 	spdk_nvmf_tgt_new_qpair(transport->tgt, &rqpair->qpair);
1386 
1387 	return 0;
1388 }
1389 
1390 static inline void
1391 nvmf_rdma_setup_wr(struct ibv_send_wr *wr, struct ibv_send_wr *next,
1392 		   enum spdk_nvme_data_transfer xfer)
1393 {
1394 	if (xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
1395 		wr->opcode = IBV_WR_RDMA_WRITE;
1396 		wr->send_flags = 0;
1397 		wr->next = next;
1398 	} else if (xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER) {
1399 		wr->opcode = IBV_WR_RDMA_READ;
1400 		wr->send_flags = IBV_SEND_SIGNALED;
1401 		wr->next = NULL;
1402 	} else {
1403 		assert(0);
1404 	}
1405 }
1406 
1407 static int
1408 nvmf_request_alloc_wrs(struct spdk_nvmf_rdma_transport *rtransport,
1409 		       struct spdk_nvmf_rdma_request *rdma_req,
1410 		       uint32_t num_sgl_descriptors)
1411 {
1412 	struct spdk_nvmf_rdma_request_data	*work_requests[SPDK_NVMF_MAX_SGL_ENTRIES];
1413 	struct spdk_nvmf_rdma_request_data	*current_data_wr;
1414 	uint32_t				i;
1415 
1416 	if (spdk_unlikely(num_sgl_descriptors > SPDK_NVMF_MAX_SGL_ENTRIES)) {
1417 		SPDK_ERRLOG("Requested too much entries (%u), the limit is %u\n",
1418 			    num_sgl_descriptors, SPDK_NVMF_MAX_SGL_ENTRIES);
1419 		return -EINVAL;
1420 	}
1421 
1422 	if (spdk_unlikely(spdk_mempool_get_bulk(rtransport->data_wr_pool, (void **)work_requests,
1423 						num_sgl_descriptors))) {
1424 		return -ENOMEM;
1425 	}
1426 
1427 	current_data_wr = &rdma_req->data;
1428 
1429 	for (i = 0; i < num_sgl_descriptors; i++) {
1430 		nvmf_rdma_setup_wr(&current_data_wr->wr, &work_requests[i]->wr, rdma_req->req.xfer);
1431 		current_data_wr->wr.next = &work_requests[i]->wr;
1432 		current_data_wr = work_requests[i];
1433 		current_data_wr->wr.sg_list = current_data_wr->sgl;
1434 		current_data_wr->wr.wr_id = rdma_req->data.wr.wr_id;
1435 	}
1436 
1437 	nvmf_rdma_setup_wr(&current_data_wr->wr, &rdma_req->rsp.wr, rdma_req->req.xfer);
1438 
1439 	return 0;
1440 }
1441 
1442 static inline void
1443 nvmf_rdma_setup_request(struct spdk_nvmf_rdma_request *rdma_req)
1444 {
1445 	struct ibv_send_wr		*wr = &rdma_req->data.wr;
1446 	struct spdk_nvme_sgl_descriptor	*sgl = &rdma_req->req.cmd->nvme_cmd.dptr.sgl1;
1447 
1448 	wr->wr.rdma.rkey = sgl->keyed.key;
1449 	wr->wr.rdma.remote_addr = sgl->address;
1450 	nvmf_rdma_setup_wr(wr, &rdma_req->rsp.wr, rdma_req->req.xfer);
1451 }
1452 
1453 static inline void
1454 nvmf_rdma_update_remote_addr(struct spdk_nvmf_rdma_request *rdma_req, uint32_t num_wrs)
1455 {
1456 	struct ibv_send_wr		*wr = &rdma_req->data.wr;
1457 	struct spdk_nvme_sgl_descriptor	*sgl = &rdma_req->req.cmd->nvme_cmd.dptr.sgl1;
1458 	uint32_t			i;
1459 	int				j;
1460 	uint64_t			remote_addr_offset = 0;
1461 
1462 	for (i = 0; i < num_wrs; ++i) {
1463 		wr->wr.rdma.rkey = sgl->keyed.key;
1464 		wr->wr.rdma.remote_addr = sgl->address + remote_addr_offset;
1465 		for (j = 0; j < wr->num_sge; ++j) {
1466 			remote_addr_offset += wr->sg_list[j].length;
1467 		}
1468 		wr = wr->next;
1469 	}
1470 }
1471 
1472 static int
1473 nvmf_rdma_fill_wr_sgl(struct spdk_nvmf_rdma_device *device,
1474 		      struct spdk_nvmf_rdma_request *rdma_req,
1475 		      struct ibv_send_wr *wr,
1476 		      uint32_t total_length)
1477 {
1478 	struct spdk_rdma_utils_memory_translation mem_translation;
1479 	struct ibv_sge	*sg_ele;
1480 	struct iovec *iov;
1481 	uint32_t lkey, remaining;
1482 	int rc;
1483 
1484 	wr->num_sge = 0;
1485 
1486 	while (total_length && wr->num_sge < SPDK_NVMF_MAX_SGL_ENTRIES) {
1487 		iov = &rdma_req->req.iov[rdma_req->iovpos];
1488 		rc = spdk_rdma_utils_get_translation(device->map, iov->iov_base, iov->iov_len, &mem_translation);
1489 		if (spdk_unlikely(rc)) {
1490 			return rc;
1491 		}
1492 
1493 		lkey = spdk_rdma_utils_memory_translation_get_lkey(&mem_translation);
1494 		sg_ele = &wr->sg_list[wr->num_sge];
1495 		remaining = spdk_min((uint32_t)iov->iov_len - rdma_req->offset, total_length);
1496 
1497 		sg_ele->lkey = lkey;
1498 		sg_ele->addr = (uintptr_t)iov->iov_base + rdma_req->offset;
1499 		sg_ele->length = remaining;
1500 		SPDK_DEBUGLOG(rdma, "sge[%d] %p addr 0x%"PRIx64", len %u\n", wr->num_sge, sg_ele, sg_ele->addr,
1501 			      sg_ele->length);
1502 		rdma_req->offset += sg_ele->length;
1503 		total_length -= sg_ele->length;
1504 		wr->num_sge++;
1505 
1506 		if (rdma_req->offset == iov->iov_len) {
1507 			rdma_req->offset = 0;
1508 			rdma_req->iovpos++;
1509 		}
1510 	}
1511 
1512 	if (spdk_unlikely(total_length)) {
1513 		SPDK_ERRLOG("Not enough SG entries to hold data buffer\n");
1514 		return -EINVAL;
1515 	}
1516 
1517 	return 0;
1518 }
1519 
1520 static int
1521 nvmf_rdma_fill_wr_sgl_with_dif(struct spdk_nvmf_rdma_device *device,
1522 			       struct spdk_nvmf_rdma_request *rdma_req,
1523 			       struct ibv_send_wr *wr,
1524 			       uint32_t total_length,
1525 			       uint32_t num_extra_wrs)
1526 {
1527 	struct spdk_rdma_utils_memory_translation mem_translation;
1528 	struct spdk_dif_ctx *dif_ctx = &rdma_req->req.dif.dif_ctx;
1529 	struct ibv_sge *sg_ele;
1530 	struct iovec *iov;
1531 	struct iovec *rdma_iov;
1532 	uint32_t lkey, remaining;
1533 	uint32_t remaining_data_block, data_block_size, md_size;
1534 	uint32_t sge_len;
1535 	int rc;
1536 
1537 	data_block_size = dif_ctx->block_size - dif_ctx->md_size;
1538 
1539 	if (spdk_likely(!rdma_req->req.stripped_data)) {
1540 		rdma_iov = rdma_req->req.iov;
1541 		remaining_data_block = data_block_size;
1542 		md_size = dif_ctx->md_size;
1543 	} else {
1544 		rdma_iov = rdma_req->req.stripped_data->iov;
1545 		total_length = total_length / dif_ctx->block_size * data_block_size;
1546 		remaining_data_block = total_length;
1547 		md_size = 0;
1548 	}
1549 
1550 	wr->num_sge = 0;
1551 
1552 	while (total_length && (num_extra_wrs || wr->num_sge < SPDK_NVMF_MAX_SGL_ENTRIES)) {
1553 		iov = rdma_iov + rdma_req->iovpos;
1554 		rc = spdk_rdma_utils_get_translation(device->map, iov->iov_base, iov->iov_len, &mem_translation);
1555 		if (spdk_unlikely(rc)) {
1556 			return rc;
1557 		}
1558 
1559 		lkey = spdk_rdma_utils_memory_translation_get_lkey(&mem_translation);
1560 		sg_ele = &wr->sg_list[wr->num_sge];
1561 		remaining = spdk_min((uint32_t)iov->iov_len - rdma_req->offset, total_length);
1562 
1563 		while (remaining) {
1564 			if (wr->num_sge >= SPDK_NVMF_MAX_SGL_ENTRIES) {
1565 				if (num_extra_wrs > 0 && wr->next) {
1566 					wr = wr->next;
1567 					wr->num_sge = 0;
1568 					sg_ele = &wr->sg_list[wr->num_sge];
1569 					num_extra_wrs--;
1570 				} else {
1571 					break;
1572 				}
1573 			}
1574 			sg_ele->lkey = lkey;
1575 			sg_ele->addr = (uintptr_t)((char *)iov->iov_base + rdma_req->offset);
1576 			sge_len = spdk_min(remaining, remaining_data_block);
1577 			sg_ele->length = sge_len;
1578 			SPDK_DEBUGLOG(rdma, "sge[%d] %p addr 0x%"PRIx64", len %u\n", wr->num_sge, sg_ele,
1579 				      sg_ele->addr, sg_ele->length);
1580 			remaining -= sge_len;
1581 			remaining_data_block -= sge_len;
1582 			rdma_req->offset += sge_len;
1583 			total_length -= sge_len;
1584 
1585 			sg_ele++;
1586 			wr->num_sge++;
1587 
1588 			if (remaining_data_block == 0) {
1589 				/* skip metadata */
1590 				rdma_req->offset += md_size;
1591 				total_length -= md_size;
1592 				/* Metadata that do not fit this IO buffer will be included in the next IO buffer */
1593 				remaining -= spdk_min(remaining, md_size);
1594 				remaining_data_block = data_block_size;
1595 			}
1596 
1597 			if (remaining == 0) {
1598 				/* By subtracting the size of the last IOV from the offset, we ensure that we skip
1599 				   the remaining metadata bits at the beginning of the next buffer */
1600 				rdma_req->offset -= spdk_min(iov->iov_len, rdma_req->offset);
1601 				rdma_req->iovpos++;
1602 			}
1603 		}
1604 	}
1605 
1606 	if (spdk_unlikely(total_length)) {
1607 		SPDK_ERRLOG("Not enough SG entries to hold data buffer\n");
1608 		return -EINVAL;
1609 	}
1610 
1611 	return 0;
1612 }
1613 
1614 static inline uint32_t
1615 nvmf_rdma_calc_num_wrs(uint32_t length, uint32_t io_unit_size, uint32_t block_size)
1616 {
1617 	/* estimate the number of SG entries and WRs needed to process the request */
1618 	uint32_t num_sge = 0;
1619 	uint32_t i;
1620 	uint32_t num_buffers = SPDK_CEIL_DIV(length, io_unit_size);
1621 
1622 	for (i = 0; i < num_buffers && length > 0; i++) {
1623 		uint32_t buffer_len = spdk_min(length, io_unit_size);
1624 		uint32_t num_sge_in_block = SPDK_CEIL_DIV(buffer_len, block_size);
1625 
1626 		if (num_sge_in_block * block_size > buffer_len) {
1627 			++num_sge_in_block;
1628 		}
1629 		num_sge += num_sge_in_block;
1630 		length -= buffer_len;
1631 	}
1632 	return SPDK_CEIL_DIV(num_sge, SPDK_NVMF_MAX_SGL_ENTRIES);
1633 }
1634 
1635 static int
1636 nvmf_rdma_request_fill_iovs(struct spdk_nvmf_rdma_transport *rtransport,
1637 			    struct spdk_nvmf_rdma_device *device,
1638 			    struct spdk_nvmf_rdma_request *rdma_req)
1639 {
1640 	struct spdk_nvmf_rdma_qpair		*rqpair;
1641 	struct spdk_nvmf_rdma_poll_group	*rgroup;
1642 	struct spdk_nvmf_request		*req = &rdma_req->req;
1643 	struct ibv_send_wr			*wr = &rdma_req->data.wr;
1644 	int					rc;
1645 	uint32_t				num_wrs = 1;
1646 	uint32_t				length;
1647 
1648 	rqpair = SPDK_CONTAINEROF(req->qpair, struct spdk_nvmf_rdma_qpair, qpair);
1649 	rgroup = rqpair->poller->group;
1650 
1651 	/* rdma wr specifics */
1652 	nvmf_rdma_setup_request(rdma_req);
1653 
1654 	length = req->length;
1655 	if (spdk_unlikely(req->dif_enabled)) {
1656 		req->dif.orig_length = length;
1657 		length = spdk_dif_get_length_with_md(length, &req->dif.dif_ctx);
1658 		req->dif.elba_length = length;
1659 	}
1660 
1661 	rc = spdk_nvmf_request_get_buffers(req, &rgroup->group, &rtransport->transport,
1662 					   length);
1663 	if (spdk_unlikely(rc != 0)) {
1664 		return rc;
1665 	}
1666 
1667 	assert(req->iovcnt <= rqpair->max_send_sge);
1668 
1669 	/* When dif_insert_or_strip is true and the I/O data length is greater than one block,
1670 	 * the stripped_buffers are got for DIF stripping. */
1671 	if (spdk_unlikely(req->dif_enabled && (req->xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST)
1672 			  && (req->dif.elba_length > req->dif.dif_ctx.block_size))) {
1673 		rc = nvmf_request_get_stripped_buffers(req, &rgroup->group,
1674 						       &rtransport->transport, req->dif.orig_length);
1675 		if (rc != 0) {
1676 			SPDK_INFOLOG(rdma, "Get stripped buffers fail %d, fallback to req.iov.\n", rc);
1677 		}
1678 	}
1679 
1680 	rdma_req->iovpos = 0;
1681 
1682 	if (spdk_unlikely(req->dif_enabled)) {
1683 		num_wrs = nvmf_rdma_calc_num_wrs(length, rtransport->transport.opts.io_unit_size,
1684 						 req->dif.dif_ctx.block_size);
1685 		if (num_wrs > 1) {
1686 			rc = nvmf_request_alloc_wrs(rtransport, rdma_req, num_wrs - 1);
1687 			if (spdk_unlikely(rc != 0)) {
1688 				goto err_exit;
1689 			}
1690 		}
1691 
1692 		rc = nvmf_rdma_fill_wr_sgl_with_dif(device, rdma_req, wr, length, num_wrs - 1);
1693 		if (spdk_unlikely(rc != 0)) {
1694 			goto err_exit;
1695 		}
1696 
1697 		if (num_wrs > 1) {
1698 			nvmf_rdma_update_remote_addr(rdma_req, num_wrs);
1699 		}
1700 	} else {
1701 		rc = nvmf_rdma_fill_wr_sgl(device, rdma_req, wr, length);
1702 		if (spdk_unlikely(rc != 0)) {
1703 			goto err_exit;
1704 		}
1705 	}
1706 
1707 	/* set the number of outstanding data WRs for this request. */
1708 	rdma_req->num_outstanding_data_wr = num_wrs;
1709 
1710 	return rc;
1711 
1712 err_exit:
1713 	spdk_nvmf_request_free_buffers(req, &rgroup->group, &rtransport->transport);
1714 	nvmf_rdma_request_free_data(rdma_req, rtransport);
1715 	req->iovcnt = 0;
1716 	return rc;
1717 }
1718 
1719 static int
1720 nvmf_rdma_request_fill_iovs_multi_sgl(struct spdk_nvmf_rdma_transport *rtransport,
1721 				      struct spdk_nvmf_rdma_device *device,
1722 				      struct spdk_nvmf_rdma_request *rdma_req)
1723 {
1724 	struct spdk_nvmf_rdma_qpair		*rqpair;
1725 	struct spdk_nvmf_rdma_poll_group	*rgroup;
1726 	struct ibv_send_wr			*current_wr;
1727 	struct spdk_nvmf_request		*req = &rdma_req->req;
1728 	struct spdk_nvme_sgl_descriptor		*inline_segment, *desc;
1729 	uint32_t				num_sgl_descriptors;
1730 	uint32_t				lengths[SPDK_NVMF_MAX_SGL_ENTRIES], total_length = 0;
1731 	uint32_t				i;
1732 	int					rc;
1733 
1734 	rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
1735 	rgroup = rqpair->poller->group;
1736 
1737 	inline_segment = &req->cmd->nvme_cmd.dptr.sgl1;
1738 	assert(inline_segment->generic.type == SPDK_NVME_SGL_TYPE_LAST_SEGMENT);
1739 	assert(inline_segment->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET);
1740 
1741 	num_sgl_descriptors = inline_segment->unkeyed.length / sizeof(struct spdk_nvme_sgl_descriptor);
1742 	assert(num_sgl_descriptors <= SPDK_NVMF_MAX_SGL_ENTRIES);
1743 
1744 	desc = (struct spdk_nvme_sgl_descriptor *)rdma_req->recv->buf + inline_segment->address;
1745 	for (i = 0; i < num_sgl_descriptors; i++) {
1746 		if (spdk_likely(!req->dif_enabled)) {
1747 			lengths[i] = desc->keyed.length;
1748 		} else {
1749 			req->dif.orig_length += desc->keyed.length;
1750 			lengths[i] = spdk_dif_get_length_with_md(desc->keyed.length, &req->dif.dif_ctx);
1751 			req->dif.elba_length += lengths[i];
1752 		}
1753 		total_length += lengths[i];
1754 		desc++;
1755 	}
1756 
1757 	if (spdk_unlikely(total_length > rtransport->transport.opts.max_io_size)) {
1758 		SPDK_ERRLOG("Multi SGL length 0x%x exceeds max io size 0x%x\n",
1759 			    total_length, rtransport->transport.opts.max_io_size);
1760 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1761 		return -EINVAL;
1762 	}
1763 
1764 	rc = nvmf_request_alloc_wrs(rtransport, rdma_req, num_sgl_descriptors - 1);
1765 	if (spdk_unlikely(rc != 0)) {
1766 		return -ENOMEM;
1767 	}
1768 
1769 	rc = spdk_nvmf_request_get_buffers(req, &rgroup->group, &rtransport->transport, total_length);
1770 	if (spdk_unlikely(rc != 0)) {
1771 		nvmf_rdma_request_free_data(rdma_req, rtransport);
1772 		return rc;
1773 	}
1774 
1775 	/* When dif_insert_or_strip is true and the I/O data length is greater than one block,
1776 	 * the stripped_buffers are got for DIF stripping. */
1777 	if (spdk_unlikely(req->dif_enabled && (req->xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST)
1778 			  && (req->dif.elba_length > req->dif.dif_ctx.block_size))) {
1779 		rc = nvmf_request_get_stripped_buffers(req, &rgroup->group,
1780 						       &rtransport->transport, req->dif.orig_length);
1781 		if (spdk_unlikely(rc != 0)) {
1782 			SPDK_INFOLOG(rdma, "Get stripped buffers fail %d, fallback to req.iov.\n", rc);
1783 		}
1784 	}
1785 
1786 	/* The first WR must always be the embedded data WR. This is how we unwind them later. */
1787 	current_wr = &rdma_req->data.wr;
1788 	assert(current_wr != NULL);
1789 
1790 	req->length = 0;
1791 	rdma_req->iovpos = 0;
1792 	desc = (struct spdk_nvme_sgl_descriptor *)rdma_req->recv->buf + inline_segment->address;
1793 	for (i = 0; i < num_sgl_descriptors; i++) {
1794 		/* The descriptors must be keyed data block descriptors with an address, not an offset. */
1795 		if (spdk_unlikely(desc->generic.type != SPDK_NVME_SGL_TYPE_KEYED_DATA_BLOCK ||
1796 				  desc->keyed.subtype != SPDK_NVME_SGL_SUBTYPE_ADDRESS)) {
1797 			rc = -EINVAL;
1798 			goto err_exit;
1799 		}
1800 
1801 		if (spdk_likely(!req->dif_enabled)) {
1802 			rc = nvmf_rdma_fill_wr_sgl(device, rdma_req, current_wr, lengths[i]);
1803 		} else {
1804 			rc = nvmf_rdma_fill_wr_sgl_with_dif(device, rdma_req, current_wr,
1805 							    lengths[i], 0);
1806 		}
1807 		if (spdk_unlikely(rc != 0)) {
1808 			rc = -ENOMEM;
1809 			goto err_exit;
1810 		}
1811 
1812 		req->length += desc->keyed.length;
1813 		current_wr->wr.rdma.rkey = desc->keyed.key;
1814 		current_wr->wr.rdma.remote_addr = desc->address;
1815 		current_wr = current_wr->next;
1816 		desc++;
1817 	}
1818 
1819 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
1820 	/* Go back to the last descriptor in the list. */
1821 	desc--;
1822 	if ((device->attr.device_cap_flags & IBV_DEVICE_MEM_MGT_EXTENSIONS) != 0) {
1823 		if (desc->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_INVALIDATE_KEY) {
1824 			rdma_req->rsp.wr.opcode = IBV_WR_SEND_WITH_INV;
1825 			rdma_req->rsp.wr.imm_data = desc->keyed.key;
1826 		}
1827 	}
1828 #endif
1829 
1830 	rdma_req->num_outstanding_data_wr = num_sgl_descriptors;
1831 
1832 	return 0;
1833 
1834 err_exit:
1835 	spdk_nvmf_request_free_buffers(req, &rgroup->group, &rtransport->transport);
1836 	nvmf_rdma_request_free_data(rdma_req, rtransport);
1837 	return rc;
1838 }
1839 
1840 static int
1841 nvmf_rdma_request_parse_sgl(struct spdk_nvmf_rdma_transport *rtransport,
1842 			    struct spdk_nvmf_rdma_device *device,
1843 			    struct spdk_nvmf_rdma_request *rdma_req)
1844 {
1845 	struct spdk_nvmf_request		*req = &rdma_req->req;
1846 	struct spdk_nvme_cpl			*rsp;
1847 	struct spdk_nvme_sgl_descriptor		*sgl;
1848 	int					rc;
1849 	uint32_t				length;
1850 
1851 	rsp = &req->rsp->nvme_cpl;
1852 	sgl = &req->cmd->nvme_cmd.dptr.sgl1;
1853 
1854 	if (sgl->generic.type == SPDK_NVME_SGL_TYPE_KEYED_DATA_BLOCK &&
1855 	    (sgl->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_ADDRESS ||
1856 	     sgl->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_INVALIDATE_KEY)) {
1857 
1858 		length = sgl->keyed.length;
1859 		if (spdk_unlikely(length > rtransport->transport.opts.max_io_size)) {
1860 			SPDK_ERRLOG("SGL length 0x%x exceeds max io size 0x%x\n",
1861 				    length, rtransport->transport.opts.max_io_size);
1862 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1863 			return -1;
1864 		}
1865 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
1866 		if ((device->attr.device_cap_flags & IBV_DEVICE_MEM_MGT_EXTENSIONS) != 0) {
1867 			if (sgl->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_INVALIDATE_KEY) {
1868 				rdma_req->rsp.wr.opcode = IBV_WR_SEND_WITH_INV;
1869 				rdma_req->rsp.wr.imm_data = sgl->keyed.key;
1870 			}
1871 		}
1872 #endif
1873 
1874 		/* fill request length and populate iovs */
1875 		req->length = length;
1876 
1877 		rc = nvmf_rdma_request_fill_iovs(rtransport, device, rdma_req);
1878 		if (spdk_unlikely(rc < 0)) {
1879 			if (rc == -EINVAL) {
1880 				SPDK_ERRLOG("SGL length exceeds the max I/O size\n");
1881 				rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1882 				return -1;
1883 			}
1884 			/* No available buffers. Queue this request up. */
1885 			SPDK_DEBUGLOG(rdma, "No available large data buffers. Queueing request %p\n", rdma_req);
1886 			return 0;
1887 		}
1888 
1889 		SPDK_DEBUGLOG(rdma, "Request %p took %d buffer/s from central pool\n", rdma_req,
1890 			      req->iovcnt);
1891 
1892 		return 0;
1893 	} else if (sgl->generic.type == SPDK_NVME_SGL_TYPE_DATA_BLOCK &&
1894 		   sgl->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET) {
1895 		uint64_t offset = sgl->address;
1896 		uint32_t max_len = rtransport->transport.opts.in_capsule_data_size;
1897 
1898 		SPDK_DEBUGLOG(nvmf, "In-capsule data: offset 0x%" PRIx64 ", length 0x%x\n",
1899 			      offset, sgl->unkeyed.length);
1900 
1901 		if (spdk_unlikely(offset > max_len)) {
1902 			SPDK_ERRLOG("In-capsule offset 0x%" PRIx64 " exceeds capsule length 0x%x\n",
1903 				    offset, max_len);
1904 			rsp->status.sc = SPDK_NVME_SC_INVALID_SGL_OFFSET;
1905 			return -1;
1906 		}
1907 		max_len -= (uint32_t)offset;
1908 
1909 		if (spdk_unlikely(sgl->unkeyed.length > max_len)) {
1910 			SPDK_ERRLOG("In-capsule data length 0x%x exceeds capsule length 0x%x\n",
1911 				    sgl->unkeyed.length, max_len);
1912 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1913 			return -1;
1914 		}
1915 
1916 		rdma_req->num_outstanding_data_wr = 0;
1917 		req->data_from_pool = false;
1918 		req->length = sgl->unkeyed.length;
1919 
1920 		req->iov[0].iov_base = rdma_req->recv->buf + offset;
1921 		req->iov[0].iov_len = req->length;
1922 		req->iovcnt = 1;
1923 
1924 		return 0;
1925 	} else if (sgl->generic.type == SPDK_NVME_SGL_TYPE_LAST_SEGMENT &&
1926 		   sgl->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET) {
1927 
1928 		rc = nvmf_rdma_request_fill_iovs_multi_sgl(rtransport, device, rdma_req);
1929 		if (spdk_unlikely(rc == -ENOMEM)) {
1930 			SPDK_DEBUGLOG(rdma, "No available large data buffers. Queueing request %p\n", rdma_req);
1931 			return 0;
1932 		} else if (spdk_unlikely(rc == -EINVAL)) {
1933 			SPDK_ERRLOG("Multi SGL element request length exceeds the max I/O size\n");
1934 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1935 			return -1;
1936 		}
1937 
1938 		SPDK_DEBUGLOG(rdma, "Request %p took %d buffer/s from central pool\n", rdma_req,
1939 			      req->iovcnt);
1940 
1941 		return 0;
1942 	}
1943 
1944 	SPDK_ERRLOG("Invalid NVMf I/O Command SGL:  Type 0x%x, Subtype 0x%x\n",
1945 		    sgl->generic.type, sgl->generic.subtype);
1946 	rsp->status.sc = SPDK_NVME_SC_SGL_DESCRIPTOR_TYPE_INVALID;
1947 	return -1;
1948 }
1949 
1950 static void
1951 _nvmf_rdma_request_free(struct spdk_nvmf_rdma_request *rdma_req,
1952 			struct spdk_nvmf_rdma_transport	*rtransport)
1953 {
1954 	struct spdk_nvmf_rdma_qpair		*rqpair;
1955 	struct spdk_nvmf_rdma_poll_group	*rgroup;
1956 
1957 	rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
1958 	if (rdma_req->req.data_from_pool) {
1959 		rgroup = rqpair->poller->group;
1960 
1961 		spdk_nvmf_request_free_buffers(&rdma_req->req, &rgroup->group, &rtransport->transport);
1962 	}
1963 	if (rdma_req->req.stripped_data) {
1964 		nvmf_request_free_stripped_buffers(&rdma_req->req,
1965 						   &rqpair->poller->group->group,
1966 						   &rtransport->transport);
1967 	}
1968 	nvmf_rdma_request_free_data(rdma_req, rtransport);
1969 	rdma_req->req.length = 0;
1970 	rdma_req->req.iovcnt = 0;
1971 	rdma_req->offset = 0;
1972 	rdma_req->req.dif_enabled = false;
1973 	rdma_req->fused_failed = false;
1974 	rdma_req->transfer_wr = NULL;
1975 	if (rdma_req->fused_pair) {
1976 		/* This req was part of a valid fused pair, but failed before it got to
1977 		 * READ_TO_EXECUTE state.  This means we need to fail the other request
1978 		 * in the pair, because it is no longer part of a valid pair.  If the pair
1979 		 * already reached READY_TO_EXECUTE state, we need to kick it.
1980 		 */
1981 		rdma_req->fused_pair->fused_failed = true;
1982 		if (rdma_req->fused_pair->state == RDMA_REQUEST_STATE_READY_TO_EXECUTE) {
1983 			nvmf_rdma_request_process(rtransport, rdma_req->fused_pair);
1984 		}
1985 		rdma_req->fused_pair = NULL;
1986 	}
1987 	memset(&rdma_req->req.dif, 0, sizeof(rdma_req->req.dif));
1988 	rqpair->qd--;
1989 
1990 	STAILQ_INSERT_HEAD(&rqpair->resources->free_queue, rdma_req, state_link);
1991 	rqpair->qpair.queue_depth--;
1992 	rdma_req->state = RDMA_REQUEST_STATE_FREE;
1993 }
1994 
1995 static void
1996 nvmf_rdma_check_fused_ordering(struct spdk_nvmf_rdma_transport *rtransport,
1997 			       struct spdk_nvmf_rdma_qpair *rqpair,
1998 			       struct spdk_nvmf_rdma_request *rdma_req)
1999 {
2000 	enum spdk_nvme_cmd_fuse last, next;
2001 
2002 	last = rqpair->fused_first ? rqpair->fused_first->req.cmd->nvme_cmd.fuse : SPDK_NVME_CMD_FUSE_NONE;
2003 	next = rdma_req->req.cmd->nvme_cmd.fuse;
2004 
2005 	assert(last != SPDK_NVME_CMD_FUSE_SECOND);
2006 
2007 	if (spdk_likely(last == SPDK_NVME_CMD_FUSE_NONE && next == SPDK_NVME_CMD_FUSE_NONE)) {
2008 		return;
2009 	}
2010 
2011 	if (last == SPDK_NVME_CMD_FUSE_FIRST) {
2012 		if (next == SPDK_NVME_CMD_FUSE_SECOND) {
2013 			/* This is a valid pair of fused commands.  Point them at each other
2014 			 * so they can be submitted consecutively once ready to be executed.
2015 			 */
2016 			rqpair->fused_first->fused_pair = rdma_req;
2017 			rdma_req->fused_pair = rqpair->fused_first;
2018 			rqpair->fused_first = NULL;
2019 			return;
2020 		} else {
2021 			/* Mark the last req as failed since it wasn't followed by a SECOND. */
2022 			rqpair->fused_first->fused_failed = true;
2023 
2024 			/* If the last req is in READY_TO_EXECUTE state, then call
2025 			 * nvmf_rdma_request_process(), otherwise nothing else will kick it.
2026 			 */
2027 			if (rqpair->fused_first->state == RDMA_REQUEST_STATE_READY_TO_EXECUTE) {
2028 				nvmf_rdma_request_process(rtransport, rqpair->fused_first);
2029 			}
2030 
2031 			rqpair->fused_first = NULL;
2032 		}
2033 	}
2034 
2035 	if (next == SPDK_NVME_CMD_FUSE_FIRST) {
2036 		/* Set rqpair->fused_first here so that we know to check that the next request
2037 		 * is a SECOND (and to fail this one if it isn't).
2038 		 */
2039 		rqpair->fused_first = rdma_req;
2040 	} else if (next == SPDK_NVME_CMD_FUSE_SECOND) {
2041 		/* Mark this req failed since it ia SECOND and the last one was not a FIRST. */
2042 		rdma_req->fused_failed = true;
2043 	}
2044 }
2045 
2046 bool
2047 nvmf_rdma_request_process(struct spdk_nvmf_rdma_transport *rtransport,
2048 			  struct spdk_nvmf_rdma_request *rdma_req)
2049 {
2050 	struct spdk_nvmf_rdma_qpair	*rqpair;
2051 	struct spdk_nvmf_rdma_device	*device;
2052 	struct spdk_nvmf_rdma_poll_group *rgroup;
2053 	struct spdk_nvme_cpl		*rsp = &rdma_req->req.rsp->nvme_cpl;
2054 	int				rc;
2055 	struct spdk_nvmf_rdma_recv	*rdma_recv;
2056 	enum spdk_nvmf_rdma_request_state prev_state;
2057 	bool				progress = false;
2058 	int				data_posted;
2059 	uint32_t			num_blocks, num_rdma_reads_available, qdepth;
2060 
2061 	rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
2062 	device = rqpair->device;
2063 	rgroup = rqpair->poller->group;
2064 
2065 	assert(rdma_req->state != RDMA_REQUEST_STATE_FREE);
2066 
2067 	/* If the queue pair is in an error state, force the request to the completed state
2068 	 * to release resources. */
2069 	if (spdk_unlikely(rqpair->ibv_in_error_state || !spdk_nvmf_qpair_is_active(&rqpair->qpair))) {
2070 		switch (rdma_req->state) {
2071 		case RDMA_REQUEST_STATE_NEED_BUFFER:
2072 			STAILQ_REMOVE(&rgroup->group.pending_buf_queue, &rdma_req->req, spdk_nvmf_request, buf_link);
2073 			break;
2074 		case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING:
2075 			STAILQ_REMOVE(&rqpair->pending_rdma_read_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2076 			break;
2077 		case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING:
2078 			STAILQ_REMOVE(&rqpair->pending_rdma_write_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2079 			break;
2080 		case RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING:
2081 			STAILQ_REMOVE(&rqpair->pending_rdma_send_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2082 			break;
2083 		default:
2084 			break;
2085 		}
2086 		rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2087 	}
2088 
2089 	/* The loop here is to allow for several back-to-back state changes. */
2090 	do {
2091 		prev_state = rdma_req->state;
2092 
2093 		SPDK_DEBUGLOG(rdma, "Request %p entering state %d\n", rdma_req, prev_state);
2094 
2095 		switch (rdma_req->state) {
2096 		case RDMA_REQUEST_STATE_FREE:
2097 			/* Some external code must kick a request into RDMA_REQUEST_STATE_NEW
2098 			 * to escape this state. */
2099 			break;
2100 		case RDMA_REQUEST_STATE_NEW:
2101 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_NEW, 0, 0,
2102 					  (uintptr_t)rdma_req, (uintptr_t)rqpair, rqpair->qpair.queue_depth);
2103 			rdma_recv = rdma_req->recv;
2104 
2105 			/* The first element of the SGL is the NVMe command */
2106 			rdma_req->req.cmd = (union nvmf_h2c_msg *)rdma_recv->sgl[0].addr;
2107 			memset(rdma_req->req.rsp, 0, sizeof(*rdma_req->req.rsp));
2108 			rdma_req->transfer_wr = &rdma_req->data.wr;
2109 
2110 			if (spdk_unlikely(rqpair->ibv_in_error_state || !spdk_nvmf_qpair_is_active(&rqpair->qpair))) {
2111 				rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2112 				break;
2113 			}
2114 
2115 			if (spdk_unlikely(spdk_nvmf_request_get_dif_ctx(&rdma_req->req, &rdma_req->req.dif.dif_ctx))) {
2116 				rdma_req->req.dif_enabled = true;
2117 			}
2118 
2119 			nvmf_rdma_check_fused_ordering(rtransport, rqpair, rdma_req);
2120 
2121 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
2122 			rdma_req->rsp.wr.opcode = IBV_WR_SEND;
2123 			rdma_req->rsp.wr.imm_data = 0;
2124 #endif
2125 
2126 			/* The next state transition depends on the data transfer needs of this request. */
2127 			rdma_req->req.xfer = spdk_nvmf_req_get_xfer(&rdma_req->req);
2128 
2129 			if (spdk_unlikely(rdma_req->req.xfer == SPDK_NVME_DATA_BIDIRECTIONAL)) {
2130 				rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2131 				rsp->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
2132 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req, state_link);
2133 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
2134 				SPDK_DEBUGLOG(rdma, "Request %p: invalid xfer type (BIDIRECTIONAL)\n", rdma_req);
2135 				break;
2136 			}
2137 
2138 			/* If no data to transfer, ready to execute. */
2139 			if (rdma_req->req.xfer == SPDK_NVME_DATA_NONE) {
2140 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_EXECUTE;
2141 				break;
2142 			}
2143 
2144 			rdma_req->state = RDMA_REQUEST_STATE_NEED_BUFFER;
2145 			STAILQ_INSERT_TAIL(&rgroup->group.pending_buf_queue, &rdma_req->req, buf_link);
2146 			break;
2147 		case RDMA_REQUEST_STATE_NEED_BUFFER:
2148 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_NEED_BUFFER, 0, 0,
2149 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2150 
2151 			assert(rdma_req->req.xfer != SPDK_NVME_DATA_NONE);
2152 
2153 			if (&rdma_req->req != STAILQ_FIRST(&rgroup->group.pending_buf_queue)) {
2154 				/* This request needs to wait in line to obtain a buffer */
2155 				break;
2156 			}
2157 
2158 			/* Try to get a data buffer */
2159 			rc = nvmf_rdma_request_parse_sgl(rtransport, device, rdma_req);
2160 			if (spdk_unlikely(rc < 0)) {
2161 				STAILQ_REMOVE_HEAD(&rgroup->group.pending_buf_queue, buf_link);
2162 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req, state_link);
2163 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
2164 				break;
2165 			}
2166 
2167 			if (rdma_req->req.iovcnt == 0) {
2168 				/* No buffers available. */
2169 				rgroup->stat.pending_data_buffer++;
2170 				break;
2171 			}
2172 
2173 			STAILQ_REMOVE_HEAD(&rgroup->group.pending_buf_queue, buf_link);
2174 
2175 			/* If data is transferring from host to controller and the data didn't
2176 			 * arrive using in capsule data, we need to do a transfer from the host.
2177 			 */
2178 			if (rdma_req->req.xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER &&
2179 			    rdma_req->req.data_from_pool) {
2180 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_read_queue, rdma_req, state_link);
2181 				rdma_req->state = RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING;
2182 				break;
2183 			}
2184 
2185 			rdma_req->state = RDMA_REQUEST_STATE_READY_TO_EXECUTE;
2186 			break;
2187 		case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING:
2188 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING, 0, 0,
2189 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2190 
2191 			if (rdma_req != STAILQ_FIRST(&rqpair->pending_rdma_read_queue)) {
2192 				/* This request needs to wait in line to perform RDMA */
2193 				break;
2194 			}
2195 			assert(rqpair->max_send_depth >= rqpair->current_send_depth);
2196 			qdepth = rqpair->max_send_depth - rqpair->current_send_depth;
2197 			assert(rqpair->max_read_depth >= rqpair->current_read_depth);
2198 			num_rdma_reads_available = rqpair->max_read_depth - rqpair->current_read_depth;
2199 			if (rdma_req->num_outstanding_data_wr > qdepth ||
2200 			    rdma_req->num_outstanding_data_wr > num_rdma_reads_available) {
2201 				if (num_rdma_reads_available && qdepth) {
2202 					/* Send as much as we can */
2203 					request_prepare_transfer_in_part(&rdma_req->req, spdk_min(num_rdma_reads_available, qdepth));
2204 				} else {
2205 					/* We can only have so many WRs outstanding. we have to wait until some finish. */
2206 					rqpair->poller->stat.pending_rdma_read++;
2207 					break;
2208 				}
2209 			}
2210 
2211 			/* We have already verified that this request is the head of the queue. */
2212 			if (rdma_req->num_remaining_data_wr == 0) {
2213 				STAILQ_REMOVE_HEAD(&rqpair->pending_rdma_read_queue, state_link);
2214 			}
2215 
2216 			rc = request_transfer_in(&rdma_req->req);
2217 			if (spdk_likely(rc == 0)) {
2218 				rdma_req->state = RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER;
2219 			} else {
2220 				rsp->status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
2221 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req, state_link);
2222 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
2223 			}
2224 			break;
2225 		case RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER:
2226 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER, 0, 0,
2227 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2228 			/* Some external code must kick a request into RDMA_REQUEST_STATE_READY_TO_EXECUTE
2229 			 * to escape this state. */
2230 			break;
2231 		case RDMA_REQUEST_STATE_READY_TO_EXECUTE:
2232 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_READY_TO_EXECUTE, 0, 0,
2233 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2234 
2235 			if (spdk_unlikely(rdma_req->req.dif_enabled)) {
2236 				if (rdma_req->req.xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER) {
2237 					/* generate DIF for write operation */
2238 					num_blocks = SPDK_CEIL_DIV(rdma_req->req.dif.elba_length, rdma_req->req.dif.dif_ctx.block_size);
2239 					assert(num_blocks > 0);
2240 
2241 					rc = spdk_dif_generate(rdma_req->req.iov, rdma_req->req.iovcnt,
2242 							       num_blocks, &rdma_req->req.dif.dif_ctx);
2243 					if (rc != 0) {
2244 						SPDK_ERRLOG("DIF generation failed\n");
2245 						rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2246 						spdk_nvmf_qpair_disconnect(&rqpair->qpair);
2247 						break;
2248 					}
2249 				}
2250 
2251 				assert(rdma_req->req.dif.elba_length >= rdma_req->req.length);
2252 				/* set extended length before IO operation */
2253 				rdma_req->req.length = rdma_req->req.dif.elba_length;
2254 			}
2255 
2256 			if (rdma_req->req.cmd->nvme_cmd.fuse != SPDK_NVME_CMD_FUSE_NONE) {
2257 				if (rdma_req->fused_failed) {
2258 					/* This request failed FUSED semantics.  Fail it immediately, without
2259 					 * even sending it to the target layer.
2260 					 */
2261 					rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2262 					rsp->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
2263 					STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req, state_link);
2264 					rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
2265 					break;
2266 				}
2267 
2268 				if (rdma_req->fused_pair == NULL ||
2269 				    rdma_req->fused_pair->state != RDMA_REQUEST_STATE_READY_TO_EXECUTE) {
2270 					/* This request is ready to execute, but either we don't know yet if it's
2271 					 * valid - i.e. this is a FIRST but we haven't received the next
2272 					 * request yet or the other request of this fused pair isn't ready to
2273 					 * execute.  So break here and this request will get processed later either
2274 					 * when the other request is ready or we find that this request isn't valid.
2275 					 */
2276 					break;
2277 				}
2278 			}
2279 
2280 			/* If we get to this point, and this request is a fused command, we know that
2281 			 * it is part of valid sequence (FIRST followed by a SECOND) and that both
2282 			 * requests are READY_TO_EXECUTE. So call spdk_nvmf_request_exec() both on this
2283 			 * request, and the other request of the fused pair, in the correct order.
2284 			 * Also clear the ->fused_pair pointers on both requests, since after this point
2285 			 * we no longer need to maintain the relationship between these two requests.
2286 			 */
2287 			if (rdma_req->req.cmd->nvme_cmd.fuse == SPDK_NVME_CMD_FUSE_SECOND) {
2288 				assert(rdma_req->fused_pair != NULL);
2289 				assert(rdma_req->fused_pair->fused_pair != NULL);
2290 				rdma_req->fused_pair->state = RDMA_REQUEST_STATE_EXECUTING;
2291 				spdk_nvmf_request_exec(&rdma_req->fused_pair->req);
2292 				rdma_req->fused_pair->fused_pair = NULL;
2293 				rdma_req->fused_pair = NULL;
2294 			}
2295 			rdma_req->state = RDMA_REQUEST_STATE_EXECUTING;
2296 			spdk_nvmf_request_exec(&rdma_req->req);
2297 			if (rdma_req->req.cmd->nvme_cmd.fuse == SPDK_NVME_CMD_FUSE_FIRST) {
2298 				assert(rdma_req->fused_pair != NULL);
2299 				assert(rdma_req->fused_pair->fused_pair != NULL);
2300 				rdma_req->fused_pair->state = RDMA_REQUEST_STATE_EXECUTING;
2301 				spdk_nvmf_request_exec(&rdma_req->fused_pair->req);
2302 				rdma_req->fused_pair->fused_pair = NULL;
2303 				rdma_req->fused_pair = NULL;
2304 			}
2305 			break;
2306 		case RDMA_REQUEST_STATE_EXECUTING:
2307 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_EXECUTING, 0, 0,
2308 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2309 			/* Some external code must kick a request into RDMA_REQUEST_STATE_EXECUTED
2310 			 * to escape this state. */
2311 			break;
2312 		case RDMA_REQUEST_STATE_EXECUTED:
2313 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_EXECUTED, 0, 0,
2314 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2315 			if (rsp->status.sc == SPDK_NVME_SC_SUCCESS &&
2316 			    rdma_req->req.xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
2317 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_write_queue, rdma_req, state_link);
2318 				rdma_req->state = RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING;
2319 			} else {
2320 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req, state_link);
2321 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
2322 			}
2323 			if (spdk_unlikely(rdma_req->req.dif_enabled)) {
2324 				/* restore the original length */
2325 				rdma_req->req.length = rdma_req->req.dif.orig_length;
2326 
2327 				if (rdma_req->req.xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
2328 					struct spdk_dif_error error_blk;
2329 
2330 					num_blocks = SPDK_CEIL_DIV(rdma_req->req.dif.elba_length, rdma_req->req.dif.dif_ctx.block_size);
2331 					if (!rdma_req->req.stripped_data) {
2332 						rc = spdk_dif_verify(rdma_req->req.iov, rdma_req->req.iovcnt, num_blocks,
2333 								     &rdma_req->req.dif.dif_ctx, &error_blk);
2334 					} else {
2335 						rc = spdk_dif_verify_copy(rdma_req->req.stripped_data->iov,
2336 									  rdma_req->req.stripped_data->iovcnt,
2337 									  rdma_req->req.iov, rdma_req->req.iovcnt, num_blocks,
2338 									  &rdma_req->req.dif.dif_ctx, &error_blk);
2339 					}
2340 					if (rc) {
2341 						struct spdk_nvme_cpl *rsp = &rdma_req->req.rsp->nvme_cpl;
2342 
2343 						SPDK_ERRLOG("DIF error detected. type=%d, offset=%" PRIu32 "\n", error_blk.err_type,
2344 							    error_blk.err_offset);
2345 						rsp->status.sct = SPDK_NVME_SCT_MEDIA_ERROR;
2346 						rsp->status.sc = nvmf_rdma_dif_error_to_compl_status(error_blk.err_type);
2347 						STAILQ_REMOVE(&rqpair->pending_rdma_write_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2348 						STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req, state_link);
2349 						rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
2350 					}
2351 				}
2352 			}
2353 			break;
2354 		case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING:
2355 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING, 0, 0,
2356 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2357 
2358 			if (rdma_req != STAILQ_FIRST(&rqpair->pending_rdma_write_queue)) {
2359 				/* This request needs to wait in line to perform RDMA */
2360 				break;
2361 			}
2362 			if ((rqpair->current_send_depth + rdma_req->num_outstanding_data_wr + 1) >
2363 			    rqpair->max_send_depth) {
2364 				/* We can only have so many WRs outstanding. we have to wait until some finish.
2365 				 * +1 since each request has an additional wr in the resp. */
2366 				rqpair->poller->stat.pending_rdma_write++;
2367 				break;
2368 			}
2369 
2370 			/* We have already verified that this request is the head of the queue. */
2371 			STAILQ_REMOVE_HEAD(&rqpair->pending_rdma_write_queue, state_link);
2372 
2373 			/* The data transfer will be kicked off from
2374 			 * RDMA_REQUEST_STATE_READY_TO_COMPLETE state.
2375 			 * We verified that data + response fit into send queue, so we can go to the next state directly
2376 			 */
2377 			rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2378 			break;
2379 		case RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING:
2380 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING, 0, 0,
2381 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2382 
2383 			if (rdma_req != STAILQ_FIRST(&rqpair->pending_rdma_send_queue)) {
2384 				/* This request needs to wait in line to send the completion */
2385 				break;
2386 			}
2387 
2388 			assert(rqpair->current_send_depth <= rqpair->max_send_depth);
2389 			if (rqpair->current_send_depth == rqpair->max_send_depth) {
2390 				/* We can only have so many WRs outstanding. we have to wait until some finish */
2391 				rqpair->poller->stat.pending_rdma_send++;
2392 				break;
2393 			}
2394 
2395 			/* We have already verified that this request is the head of the queue. */
2396 			STAILQ_REMOVE_HEAD(&rqpair->pending_rdma_send_queue, state_link);
2397 
2398 			/* The response sending will be kicked off from
2399 			 * RDMA_REQUEST_STATE_READY_TO_COMPLETE state.
2400 			 */
2401 			rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2402 			break;
2403 		case RDMA_REQUEST_STATE_READY_TO_COMPLETE:
2404 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE, 0, 0,
2405 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2406 			rc = request_transfer_out(&rdma_req->req, &data_posted);
2407 			assert(rc == 0); /* No good way to handle this currently */
2408 			if (spdk_unlikely(rc)) {
2409 				rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2410 			} else {
2411 				rdma_req->state = data_posted ? RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST :
2412 						  RDMA_REQUEST_STATE_COMPLETING;
2413 			}
2414 			break;
2415 		case RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST:
2416 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST, 0, 0,
2417 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2418 			/* Some external code must kick a request into RDMA_REQUEST_STATE_COMPLETED
2419 			 * to escape this state. */
2420 			break;
2421 		case RDMA_REQUEST_STATE_COMPLETING:
2422 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_COMPLETING, 0, 0,
2423 					  (uintptr_t)rdma_req, (uintptr_t)rqpair);
2424 			/* Some external code must kick a request into RDMA_REQUEST_STATE_COMPLETED
2425 			 * to escape this state. */
2426 			break;
2427 		case RDMA_REQUEST_STATE_COMPLETED:
2428 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_COMPLETED, 0, 0,
2429 					  (uintptr_t)rdma_req, (uintptr_t)rqpair, rqpair->qpair.queue_depth);
2430 
2431 			rqpair->poller->stat.request_latency += spdk_get_ticks() - rdma_req->receive_tsc;
2432 			_nvmf_rdma_request_free(rdma_req, rtransport);
2433 			break;
2434 		case RDMA_REQUEST_NUM_STATES:
2435 		default:
2436 			assert(0);
2437 			break;
2438 		}
2439 
2440 		if (rdma_req->state != prev_state) {
2441 			progress = true;
2442 		}
2443 	} while (rdma_req->state != prev_state);
2444 
2445 	return progress;
2446 }
2447 
2448 /* Public API callbacks begin here */
2449 
2450 #define SPDK_NVMF_RDMA_DEFAULT_MAX_QUEUE_DEPTH 128
2451 #define SPDK_NVMF_RDMA_DEFAULT_AQ_DEPTH 128
2452 #define SPDK_NVMF_RDMA_DEFAULT_SRQ_DEPTH 4096
2453 #define SPDK_NVMF_RDMA_DEFAULT_MAX_QPAIRS_PER_CTRLR 128
2454 #define SPDK_NVMF_RDMA_DEFAULT_IN_CAPSULE_DATA_SIZE 4096
2455 #define SPDK_NVMF_RDMA_DEFAULT_MAX_IO_SIZE 131072
2456 #define SPDK_NVMF_RDMA_MIN_IO_BUFFER_SIZE (SPDK_NVMF_RDMA_DEFAULT_MAX_IO_SIZE / SPDK_NVMF_MAX_SGL_ENTRIES)
2457 #define SPDK_NVMF_RDMA_DEFAULT_NUM_SHARED_BUFFERS 4095
2458 #define SPDK_NVMF_RDMA_DEFAULT_BUFFER_CACHE_SIZE UINT32_MAX
2459 #define SPDK_NVMF_RDMA_DEFAULT_NO_SRQ false
2460 #define SPDK_NVMF_RDMA_DIF_INSERT_OR_STRIP false
2461 #define SPDK_NVMF_RDMA_ACCEPTOR_BACKLOG 100
2462 #define SPDK_NVMF_RDMA_DEFAULT_ABORT_TIMEOUT_SEC 1
2463 #define SPDK_NVMF_RDMA_DEFAULT_NO_WR_BATCHING false
2464 #define SPDK_NVMF_RDMA_DEFAULT_DATA_WR_POOL_SIZE 4095
2465 
2466 static void
2467 nvmf_rdma_opts_init(struct spdk_nvmf_transport_opts *opts)
2468 {
2469 	opts->max_queue_depth =		SPDK_NVMF_RDMA_DEFAULT_MAX_QUEUE_DEPTH;
2470 	opts->max_qpairs_per_ctrlr =	SPDK_NVMF_RDMA_DEFAULT_MAX_QPAIRS_PER_CTRLR;
2471 	opts->in_capsule_data_size =	SPDK_NVMF_RDMA_DEFAULT_IN_CAPSULE_DATA_SIZE;
2472 	opts->max_io_size =		SPDK_NVMF_RDMA_DEFAULT_MAX_IO_SIZE;
2473 	opts->io_unit_size =		SPDK_NVMF_RDMA_MIN_IO_BUFFER_SIZE;
2474 	opts->max_aq_depth =		SPDK_NVMF_RDMA_DEFAULT_AQ_DEPTH;
2475 	opts->num_shared_buffers =	SPDK_NVMF_RDMA_DEFAULT_NUM_SHARED_BUFFERS;
2476 	opts->buf_cache_size =		SPDK_NVMF_RDMA_DEFAULT_BUFFER_CACHE_SIZE;
2477 	opts->dif_insert_or_strip =	SPDK_NVMF_RDMA_DIF_INSERT_OR_STRIP;
2478 	opts->abort_timeout_sec =	SPDK_NVMF_RDMA_DEFAULT_ABORT_TIMEOUT_SEC;
2479 	opts->transport_specific =      NULL;
2480 	opts->data_wr_pool_size	=	SPDK_NVMF_RDMA_DEFAULT_DATA_WR_POOL_SIZE;
2481 }
2482 
2483 static int nvmf_rdma_destroy(struct spdk_nvmf_transport *transport,
2484 			     spdk_nvmf_transport_destroy_done_cb cb_fn, void *cb_arg);
2485 
2486 static inline bool
2487 nvmf_rdma_is_rxe_device(struct spdk_nvmf_rdma_device *device)
2488 {
2489 	return device->attr.vendor_id == SPDK_RDMA_RXE_VENDOR_ID_OLD ||
2490 	       device->attr.vendor_id == SPDK_RDMA_RXE_VENDOR_ID_NEW;
2491 }
2492 
2493 static int nvmf_rdma_accept(void *ctx);
2494 static bool nvmf_rdma_retry_listen_port(struct spdk_nvmf_rdma_transport *rtransport);
2495 static void destroy_ib_device(struct spdk_nvmf_rdma_transport *rtransport,
2496 			      struct spdk_nvmf_rdma_device *device);
2497 
2498 static int
2499 create_ib_device(struct spdk_nvmf_rdma_transport *rtransport, struct ibv_context *context,
2500 		 struct spdk_nvmf_rdma_device **new_device)
2501 {
2502 	struct spdk_nvmf_rdma_device	*device;
2503 	int				flag = 0;
2504 	int				rc = 0;
2505 
2506 	device = calloc(1, sizeof(*device));
2507 	if (!device) {
2508 		SPDK_ERRLOG("Unable to allocate memory for RDMA devices.\n");
2509 		return -ENOMEM;
2510 	}
2511 	device->context = context;
2512 	rc = ibv_query_device(device->context, &device->attr);
2513 	if (rc < 0) {
2514 		SPDK_ERRLOG("Failed to query RDMA device attributes.\n");
2515 		free(device);
2516 		return rc;
2517 	}
2518 
2519 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
2520 	if ((device->attr.device_cap_flags & IBV_DEVICE_MEM_MGT_EXTENSIONS) == 0) {
2521 		SPDK_WARNLOG("The libibverbs on this system supports SEND_WITH_INVALIDATE,");
2522 		SPDK_WARNLOG("but the device with vendor ID %u does not.\n", device->attr.vendor_id);
2523 	}
2524 
2525 	/**
2526 	 * The vendor ID is assigned by the IEEE and an ID of 0 implies Soft-RoCE.
2527 	 * The Soft-RoCE RXE driver does not currently support send with invalidate,
2528 	 * but incorrectly reports that it does. There are changes making their way
2529 	 * through the kernel now that will enable this feature. When they are merged,
2530 	 * we can conditionally enable this feature.
2531 	 *
2532 	 * TODO: enable this for versions of the kernel rxe driver that support it.
2533 	 */
2534 	if (nvmf_rdma_is_rxe_device(device)) {
2535 		device->attr.device_cap_flags &= ~(IBV_DEVICE_MEM_MGT_EXTENSIONS);
2536 	}
2537 #endif
2538 
2539 	/* set up device context async ev fd as NON_BLOCKING */
2540 	flag = fcntl(device->context->async_fd, F_GETFL);
2541 	rc = fcntl(device->context->async_fd, F_SETFL, flag | O_NONBLOCK);
2542 	if (rc < 0) {
2543 		SPDK_ERRLOG("Failed to set context async fd to NONBLOCK.\n");
2544 		free(device);
2545 		return rc;
2546 	}
2547 
2548 	TAILQ_INSERT_TAIL(&rtransport->devices, device, link);
2549 	SPDK_DEBUGLOG(rdma, "New device %p is added to RDMA trasport\n", device);
2550 
2551 	if (g_nvmf_hooks.get_ibv_pd) {
2552 		device->pd = g_nvmf_hooks.get_ibv_pd(NULL, device->context);
2553 	} else {
2554 		device->pd = ibv_alloc_pd(device->context);
2555 	}
2556 
2557 	if (!device->pd) {
2558 		SPDK_ERRLOG("Unable to allocate protection domain.\n");
2559 		destroy_ib_device(rtransport, device);
2560 		return -ENOMEM;
2561 	}
2562 
2563 	assert(device->map == NULL);
2564 
2565 	device->map = spdk_rdma_utils_create_mem_map(device->pd, &g_nvmf_hooks, IBV_ACCESS_LOCAL_WRITE);
2566 	if (!device->map) {
2567 		SPDK_ERRLOG("Unable to allocate memory map for listen address\n");
2568 		destroy_ib_device(rtransport, device);
2569 		return -ENOMEM;
2570 	}
2571 
2572 	assert(device->map != NULL);
2573 	assert(device->pd != NULL);
2574 
2575 	if (new_device) {
2576 		*new_device = device;
2577 	}
2578 	SPDK_NOTICELOG("Create IB device %s(%p/%p) succeed.\n", ibv_get_device_name(context->device),
2579 		       device, context);
2580 
2581 	return 0;
2582 }
2583 
2584 static void
2585 free_poll_fds(struct spdk_nvmf_rdma_transport *rtransport)
2586 {
2587 	if (rtransport->poll_fds) {
2588 		free(rtransport->poll_fds);
2589 		rtransport->poll_fds = NULL;
2590 	}
2591 	rtransport->npoll_fds = 0;
2592 }
2593 
2594 static int
2595 generate_poll_fds(struct spdk_nvmf_rdma_transport *rtransport)
2596 {
2597 	/* Set up poll descriptor array to monitor events from RDMA and IB
2598 	 * in a single poll syscall
2599 	 */
2600 	int device_count = 0;
2601 	int i = 0;
2602 	struct spdk_nvmf_rdma_device *device, *tmp;
2603 
2604 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, tmp) {
2605 		device_count++;
2606 	}
2607 
2608 	rtransport->npoll_fds = device_count + 1;
2609 
2610 	rtransport->poll_fds = calloc(rtransport->npoll_fds, sizeof(struct pollfd));
2611 	if (rtransport->poll_fds == NULL) {
2612 		SPDK_ERRLOG("poll_fds allocation failed\n");
2613 		return -ENOMEM;
2614 	}
2615 
2616 	rtransport->poll_fds[i].fd = rtransport->event_channel->fd;
2617 	rtransport->poll_fds[i++].events = POLLIN;
2618 
2619 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, tmp) {
2620 		rtransport->poll_fds[i].fd = device->context->async_fd;
2621 		rtransport->poll_fds[i++].events = POLLIN;
2622 	}
2623 
2624 	return 0;
2625 }
2626 
2627 static struct spdk_nvmf_transport *
2628 nvmf_rdma_create(struct spdk_nvmf_transport_opts *opts)
2629 {
2630 	int rc;
2631 	struct spdk_nvmf_rdma_transport *rtransport;
2632 	struct spdk_nvmf_rdma_device	*device;
2633 	struct ibv_context		**contexts;
2634 	size_t				data_wr_pool_size;
2635 	uint32_t			i;
2636 	int				flag;
2637 	uint32_t			sge_count;
2638 	uint32_t			min_shared_buffers;
2639 	uint32_t			min_in_capsule_data_size;
2640 	int				max_device_sge = SPDK_NVMF_MAX_SGL_ENTRIES;
2641 
2642 	rtransport = calloc(1, sizeof(*rtransport));
2643 	if (!rtransport) {
2644 		return NULL;
2645 	}
2646 
2647 	TAILQ_INIT(&rtransport->devices);
2648 	TAILQ_INIT(&rtransport->ports);
2649 	TAILQ_INIT(&rtransport->poll_groups);
2650 	TAILQ_INIT(&rtransport->retry_ports);
2651 
2652 	rtransport->transport.ops = &spdk_nvmf_transport_rdma;
2653 	rtransport->rdma_opts.num_cqe = DEFAULT_NVMF_RDMA_CQ_SIZE;
2654 	rtransport->rdma_opts.max_srq_depth = SPDK_NVMF_RDMA_DEFAULT_SRQ_DEPTH;
2655 	rtransport->rdma_opts.no_srq = SPDK_NVMF_RDMA_DEFAULT_NO_SRQ;
2656 	rtransport->rdma_opts.acceptor_backlog = SPDK_NVMF_RDMA_ACCEPTOR_BACKLOG;
2657 	rtransport->rdma_opts.no_wr_batching = SPDK_NVMF_RDMA_DEFAULT_NO_WR_BATCHING;
2658 	if (opts->transport_specific != NULL &&
2659 	    spdk_json_decode_object_relaxed(opts->transport_specific, rdma_transport_opts_decoder,
2660 					    SPDK_COUNTOF(rdma_transport_opts_decoder),
2661 					    &rtransport->rdma_opts)) {
2662 		SPDK_ERRLOG("spdk_json_decode_object_relaxed failed\n");
2663 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2664 		return NULL;
2665 	}
2666 
2667 	SPDK_INFOLOG(rdma, "*** RDMA Transport Init ***\n"
2668 		     "  Transport opts:  max_ioq_depth=%d, max_io_size=%d,\n"
2669 		     "  max_io_qpairs_per_ctrlr=%d, io_unit_size=%d,\n"
2670 		     "  in_capsule_data_size=%d, max_aq_depth=%d,\n"
2671 		     "  num_shared_buffers=%d, num_cqe=%d, max_srq_depth=%d, no_srq=%d,"
2672 		     "  acceptor_backlog=%d, no_wr_batching=%d abort_timeout_sec=%d\n",
2673 		     opts->max_queue_depth,
2674 		     opts->max_io_size,
2675 		     opts->max_qpairs_per_ctrlr - 1,
2676 		     opts->io_unit_size,
2677 		     opts->in_capsule_data_size,
2678 		     opts->max_aq_depth,
2679 		     opts->num_shared_buffers,
2680 		     rtransport->rdma_opts.num_cqe,
2681 		     rtransport->rdma_opts.max_srq_depth,
2682 		     rtransport->rdma_opts.no_srq,
2683 		     rtransport->rdma_opts.acceptor_backlog,
2684 		     rtransport->rdma_opts.no_wr_batching,
2685 		     opts->abort_timeout_sec);
2686 
2687 	/* I/O unit size cannot be larger than max I/O size */
2688 	if (opts->io_unit_size > opts->max_io_size) {
2689 		opts->io_unit_size = opts->max_io_size;
2690 	}
2691 
2692 	if (rtransport->rdma_opts.acceptor_backlog <= 0) {
2693 		SPDK_ERRLOG("The acceptor backlog cannot be less than 1, setting to the default value of (%d).\n",
2694 			    SPDK_NVMF_RDMA_ACCEPTOR_BACKLOG);
2695 		rtransport->rdma_opts.acceptor_backlog = SPDK_NVMF_RDMA_ACCEPTOR_BACKLOG;
2696 	}
2697 
2698 	if (opts->num_shared_buffers < (SPDK_NVMF_MAX_SGL_ENTRIES * 2)) {
2699 		SPDK_ERRLOG("The number of shared data buffers (%d) is less than"
2700 			    "the minimum number required to guarantee that forward progress can be made (%d)\n",
2701 			    opts->num_shared_buffers, (SPDK_NVMF_MAX_SGL_ENTRIES * 2));
2702 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2703 		return NULL;
2704 	}
2705 
2706 	/* If buf_cache_size == UINT32_MAX, we will dynamically pick a cache size later that we know will fit. */
2707 	if (opts->buf_cache_size < UINT32_MAX) {
2708 		min_shared_buffers = spdk_env_get_core_count() * opts->buf_cache_size;
2709 		if (min_shared_buffers > opts->num_shared_buffers) {
2710 			SPDK_ERRLOG("There are not enough buffers to satisfy"
2711 				    "per-poll group caches for each thread. (%" PRIu32 ")"
2712 				    "supplied. (%" PRIu32 ") required\n", opts->num_shared_buffers, min_shared_buffers);
2713 			SPDK_ERRLOG("Please specify a larger number of shared buffers\n");
2714 			nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2715 			return NULL;
2716 		}
2717 	}
2718 
2719 	sge_count = opts->max_io_size / opts->io_unit_size;
2720 	if (sge_count > NVMF_DEFAULT_TX_SGE) {
2721 		SPDK_ERRLOG("Unsupported IO Unit size specified, %d bytes\n", opts->io_unit_size);
2722 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2723 		return NULL;
2724 	}
2725 
2726 	min_in_capsule_data_size = sizeof(struct spdk_nvme_sgl_descriptor) * SPDK_NVMF_MAX_SGL_ENTRIES;
2727 	if (opts->in_capsule_data_size < min_in_capsule_data_size) {
2728 		SPDK_WARNLOG("In capsule data size is set to %u, this is minimum size required to support msdbd=16\n",
2729 			     min_in_capsule_data_size);
2730 		opts->in_capsule_data_size = min_in_capsule_data_size;
2731 	}
2732 
2733 	rtransport->event_channel = rdma_create_event_channel();
2734 	if (rtransport->event_channel == NULL) {
2735 		SPDK_ERRLOG("rdma_create_event_channel() failed, %s\n", spdk_strerror(errno));
2736 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2737 		return NULL;
2738 	}
2739 
2740 	flag = fcntl(rtransport->event_channel->fd, F_GETFL);
2741 	if (fcntl(rtransport->event_channel->fd, F_SETFL, flag | O_NONBLOCK) < 0) {
2742 		SPDK_ERRLOG("fcntl can't set nonblocking mode for socket, fd: %d (%s)\n",
2743 			    rtransport->event_channel->fd, spdk_strerror(errno));
2744 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2745 		return NULL;
2746 	}
2747 
2748 	data_wr_pool_size = opts->data_wr_pool_size;
2749 	if (data_wr_pool_size < SPDK_NVMF_MAX_SGL_ENTRIES * 2 * spdk_env_get_core_count()) {
2750 		data_wr_pool_size = SPDK_NVMF_MAX_SGL_ENTRIES * 2 * spdk_env_get_core_count();
2751 		SPDK_NOTICELOG("data_wr_pool_size is changed to %zu to guarantee enough cache for handling "
2752 			       "at least one IO in each core\n", data_wr_pool_size);
2753 	}
2754 	rtransport->data_wr_pool = spdk_mempool_create("spdk_nvmf_rdma_wr_data", data_wr_pool_size,
2755 				   sizeof(struct spdk_nvmf_rdma_request_data), SPDK_MEMPOOL_DEFAULT_CACHE_SIZE,
2756 				   SPDK_ENV_SOCKET_ID_ANY);
2757 	if (!rtransport->data_wr_pool) {
2758 		if (spdk_mempool_lookup("spdk_nvmf_rdma_wr_data") != NULL) {
2759 			SPDK_ERRLOG("Unable to allocate work request pool for poll group: already exists\n");
2760 			SPDK_ERRLOG("Probably running in multiprocess environment, which is "
2761 				    "unsupported by the nvmf library\n");
2762 		} else {
2763 			SPDK_ERRLOG("Unable to allocate work request pool for poll group\n");
2764 		}
2765 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2766 		return NULL;
2767 	}
2768 
2769 	contexts = rdma_get_devices(NULL);
2770 	if (contexts == NULL) {
2771 		SPDK_ERRLOG("rdma_get_devices() failed: %s (%d)\n", spdk_strerror(errno), errno);
2772 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2773 		return NULL;
2774 	}
2775 
2776 	i = 0;
2777 	rc = 0;
2778 	while (contexts[i] != NULL) {
2779 		rc = create_ib_device(rtransport, contexts[i], &device);
2780 		if (rc < 0) {
2781 			break;
2782 		}
2783 		i++;
2784 		max_device_sge = spdk_min(max_device_sge, device->attr.max_sge);
2785 		device->is_ready = true;
2786 	}
2787 	rdma_free_devices(contexts);
2788 
2789 	if (opts->io_unit_size * max_device_sge < opts->max_io_size) {
2790 		/* divide and round up. */
2791 		opts->io_unit_size = (opts->max_io_size + max_device_sge - 1) / max_device_sge;
2792 
2793 		/* round up to the nearest 4k. */
2794 		opts->io_unit_size = (opts->io_unit_size + NVMF_DATA_BUFFER_ALIGNMENT - 1) & ~NVMF_DATA_BUFFER_MASK;
2795 
2796 		opts->io_unit_size = spdk_max(opts->io_unit_size, SPDK_NVMF_RDMA_MIN_IO_BUFFER_SIZE);
2797 		SPDK_NOTICELOG("Adjusting the io unit size to fit the device's maximum I/O size. New I/O unit size %u\n",
2798 			       opts->io_unit_size);
2799 	}
2800 
2801 	if (rc < 0) {
2802 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2803 		return NULL;
2804 	}
2805 
2806 	rc = generate_poll_fds(rtransport);
2807 	if (rc < 0) {
2808 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2809 		return NULL;
2810 	}
2811 
2812 	rtransport->accept_poller = SPDK_POLLER_REGISTER(nvmf_rdma_accept, &rtransport->transport,
2813 				    opts->acceptor_poll_rate);
2814 	if (!rtransport->accept_poller) {
2815 		nvmf_rdma_destroy(&rtransport->transport, NULL, NULL);
2816 		return NULL;
2817 	}
2818 
2819 	return &rtransport->transport;
2820 }
2821 
2822 static void
2823 destroy_ib_device(struct spdk_nvmf_rdma_transport *rtransport,
2824 		  struct spdk_nvmf_rdma_device *device)
2825 {
2826 	TAILQ_REMOVE(&rtransport->devices, device, link);
2827 	spdk_rdma_utils_free_mem_map(&device->map);
2828 	if (device->pd) {
2829 		if (!g_nvmf_hooks.get_ibv_pd) {
2830 			ibv_dealloc_pd(device->pd);
2831 		}
2832 	}
2833 	SPDK_DEBUGLOG(rdma, "IB device [%p] is destroyed.\n", device);
2834 	free(device);
2835 }
2836 
2837 static void
2838 nvmf_rdma_dump_opts(struct spdk_nvmf_transport *transport, struct spdk_json_write_ctx *w)
2839 {
2840 	struct spdk_nvmf_rdma_transport	*rtransport;
2841 	assert(w != NULL);
2842 
2843 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2844 	spdk_json_write_named_uint32(w, "max_srq_depth", rtransport->rdma_opts.max_srq_depth);
2845 	spdk_json_write_named_bool(w, "no_srq", rtransport->rdma_opts.no_srq);
2846 	if (rtransport->rdma_opts.no_srq == true) {
2847 		spdk_json_write_named_int32(w, "num_cqe", rtransport->rdma_opts.num_cqe);
2848 	}
2849 	spdk_json_write_named_int32(w, "acceptor_backlog", rtransport->rdma_opts.acceptor_backlog);
2850 	spdk_json_write_named_bool(w, "no_wr_batching", rtransport->rdma_opts.no_wr_batching);
2851 }
2852 
2853 static int
2854 nvmf_rdma_destroy(struct spdk_nvmf_transport *transport,
2855 		  spdk_nvmf_transport_destroy_done_cb cb_fn, void *cb_arg)
2856 {
2857 	struct spdk_nvmf_rdma_transport	*rtransport;
2858 	struct spdk_nvmf_rdma_port	*port, *port_tmp;
2859 	struct spdk_nvmf_rdma_device	*device, *device_tmp;
2860 
2861 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2862 
2863 	TAILQ_FOREACH_SAFE(port, &rtransport->retry_ports, link, port_tmp) {
2864 		TAILQ_REMOVE(&rtransport->retry_ports, port, link);
2865 		free(port);
2866 	}
2867 
2868 	TAILQ_FOREACH_SAFE(port, &rtransport->ports, link, port_tmp) {
2869 		TAILQ_REMOVE(&rtransport->ports, port, link);
2870 		rdma_destroy_id(port->id);
2871 		free(port);
2872 	}
2873 
2874 	free_poll_fds(rtransport);
2875 
2876 	if (rtransport->event_channel != NULL) {
2877 		rdma_destroy_event_channel(rtransport->event_channel);
2878 	}
2879 
2880 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, device_tmp) {
2881 		destroy_ib_device(rtransport, device);
2882 	}
2883 
2884 	if (rtransport->data_wr_pool != NULL) {
2885 		if (spdk_mempool_count(rtransport->data_wr_pool) != transport->opts.data_wr_pool_size) {
2886 			SPDK_ERRLOG("transport wr pool count is %zu but should be %u\n",
2887 				    spdk_mempool_count(rtransport->data_wr_pool),
2888 				    transport->opts.max_queue_depth * SPDK_NVMF_MAX_SGL_ENTRIES);
2889 		}
2890 	}
2891 
2892 	spdk_mempool_free(rtransport->data_wr_pool);
2893 
2894 	spdk_poller_unregister(&rtransport->accept_poller);
2895 	free(rtransport);
2896 
2897 	if (cb_fn) {
2898 		cb_fn(cb_arg);
2899 	}
2900 	return 0;
2901 }
2902 
2903 static int nvmf_rdma_trid_from_cm_id(struct rdma_cm_id *id,
2904 				     struct spdk_nvme_transport_id *trid,
2905 				     bool peer);
2906 
2907 static bool nvmf_rdma_rescan_devices(struct spdk_nvmf_rdma_transport *rtransport);
2908 
2909 static int
2910 nvmf_rdma_listen(struct spdk_nvmf_transport *transport, const struct spdk_nvme_transport_id *trid,
2911 		 struct spdk_nvmf_listen_opts *listen_opts)
2912 {
2913 	struct spdk_nvmf_rdma_transport	*rtransport;
2914 	struct spdk_nvmf_rdma_device	*device;
2915 	struct spdk_nvmf_rdma_port	*port, *tmp_port;
2916 	struct addrinfo			*res;
2917 	struct addrinfo			hints;
2918 	int				family;
2919 	int				rc;
2920 	long int			port_val;
2921 	bool				is_retry = false;
2922 
2923 	if (!strlen(trid->trsvcid)) {
2924 		SPDK_ERRLOG("Service id is required\n");
2925 		return -EINVAL;
2926 	}
2927 
2928 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2929 	assert(rtransport->event_channel != NULL);
2930 
2931 	port = calloc(1, sizeof(*port));
2932 	if (!port) {
2933 		SPDK_ERRLOG("Port allocation failed\n");
2934 		return -ENOMEM;
2935 	}
2936 
2937 	port->trid = trid;
2938 
2939 	switch (trid->adrfam) {
2940 	case SPDK_NVMF_ADRFAM_IPV4:
2941 		family = AF_INET;
2942 		break;
2943 	case SPDK_NVMF_ADRFAM_IPV6:
2944 		family = AF_INET6;
2945 		break;
2946 	default:
2947 		SPDK_ERRLOG("Unhandled ADRFAM %d\n", trid->adrfam);
2948 		free(port);
2949 		return -EINVAL;
2950 	}
2951 
2952 	memset(&hints, 0, sizeof(hints));
2953 	hints.ai_family = family;
2954 	hints.ai_flags = AI_NUMERICSERV;
2955 	hints.ai_socktype = SOCK_STREAM;
2956 	hints.ai_protocol = 0;
2957 
2958 	/* Range check the trsvcid. Fail in 3 cases:
2959 	 * < 0: means that spdk_strtol hit an error
2960 	 * 0: this results in ephemeral port which we don't want
2961 	 * > 65535: port too high
2962 	 */
2963 	port_val = spdk_strtol(trid->trsvcid, 10);
2964 	if (port_val <= 0 || port_val > 65535) {
2965 		SPDK_ERRLOG("invalid trsvcid %s\n", trid->trsvcid);
2966 		free(port);
2967 		return -EINVAL;
2968 	}
2969 
2970 	rc = getaddrinfo(trid->traddr, trid->trsvcid, &hints, &res);
2971 	if (rc) {
2972 		SPDK_ERRLOG("getaddrinfo failed: %s (%d)\n", gai_strerror(rc), rc);
2973 		free(port);
2974 		return -(abs(rc));
2975 	}
2976 
2977 	rc = rdma_create_id(rtransport->event_channel, &port->id, port, RDMA_PS_TCP);
2978 	if (rc < 0) {
2979 		SPDK_ERRLOG("rdma_create_id() failed\n");
2980 		freeaddrinfo(res);
2981 		free(port);
2982 		return rc;
2983 	}
2984 
2985 	rc = rdma_bind_addr(port->id, res->ai_addr);
2986 	freeaddrinfo(res);
2987 
2988 	if (rc < 0) {
2989 		TAILQ_FOREACH(tmp_port, &rtransport->retry_ports, link) {
2990 			if (spdk_nvme_transport_id_compare(tmp_port->trid, trid) == 0) {
2991 				is_retry = true;
2992 				break;
2993 			}
2994 		}
2995 		if (!is_retry) {
2996 			SPDK_ERRLOG("rdma_bind_addr() failed\n");
2997 		}
2998 		rdma_destroy_id(port->id);
2999 		free(port);
3000 		return rc;
3001 	}
3002 
3003 	if (!port->id->verbs) {
3004 		SPDK_ERRLOG("ibv_context is null\n");
3005 		rdma_destroy_id(port->id);
3006 		free(port);
3007 		return -1;
3008 	}
3009 
3010 	rc = rdma_listen(port->id, rtransport->rdma_opts.acceptor_backlog);
3011 	if (rc < 0) {
3012 		SPDK_ERRLOG("rdma_listen() failed\n");
3013 		rdma_destroy_id(port->id);
3014 		free(port);
3015 		return rc;
3016 	}
3017 
3018 	TAILQ_FOREACH(device, &rtransport->devices, link) {
3019 		if (device->context == port->id->verbs && device->is_ready) {
3020 			port->device = device;
3021 			break;
3022 		}
3023 	}
3024 	if (!port->device) {
3025 		SPDK_ERRLOG("Accepted a connection with verbs %p, but unable to find a corresponding device.\n",
3026 			    port->id->verbs);
3027 		rdma_destroy_id(port->id);
3028 		free(port);
3029 		nvmf_rdma_rescan_devices(rtransport);
3030 		return -EINVAL;
3031 	}
3032 
3033 	SPDK_NOTICELOG("*** NVMe/RDMA Target Listening on %s port %s ***\n",
3034 		       trid->traddr, trid->trsvcid);
3035 
3036 	TAILQ_INSERT_TAIL(&rtransport->ports, port, link);
3037 	return 0;
3038 }
3039 
3040 static void
3041 nvmf_rdma_stop_listen_ex(struct spdk_nvmf_transport *transport,
3042 			 const struct spdk_nvme_transport_id *trid, bool need_retry)
3043 {
3044 	struct spdk_nvmf_rdma_transport	*rtransport;
3045 	struct spdk_nvmf_rdma_port	*port, *tmp;
3046 
3047 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3048 
3049 	if (!need_retry) {
3050 		TAILQ_FOREACH_SAFE(port, &rtransport->retry_ports, link, tmp) {
3051 			if (spdk_nvme_transport_id_compare(port->trid, trid) == 0) {
3052 				TAILQ_REMOVE(&rtransport->retry_ports, port, link);
3053 				free(port);
3054 			}
3055 		}
3056 	}
3057 
3058 	TAILQ_FOREACH_SAFE(port, &rtransport->ports, link, tmp) {
3059 		if (spdk_nvme_transport_id_compare(port->trid, trid) == 0) {
3060 			SPDK_DEBUGLOG(rdma, "Port %s:%s removed. need retry: %d\n",
3061 				      port->trid->traddr, port->trid->trsvcid, need_retry);
3062 			TAILQ_REMOVE(&rtransport->ports, port, link);
3063 			rdma_destroy_id(port->id);
3064 			port->id = NULL;
3065 			port->device = NULL;
3066 			if (need_retry) {
3067 				TAILQ_INSERT_TAIL(&rtransport->retry_ports, port, link);
3068 			} else {
3069 				free(port);
3070 			}
3071 			break;
3072 		}
3073 	}
3074 }
3075 
3076 static void
3077 nvmf_rdma_stop_listen(struct spdk_nvmf_transport *transport,
3078 		      const struct spdk_nvme_transport_id *trid)
3079 {
3080 	nvmf_rdma_stop_listen_ex(transport, trid, false);
3081 }
3082 
3083 static void _nvmf_rdma_register_poller_in_group(void *c);
3084 static void _nvmf_rdma_remove_poller_in_group(void *c);
3085 
3086 static bool
3087 nvmf_rdma_all_pollers_management_done(void *c)
3088 {
3089 	struct poller_manage_ctx	*ctx = c;
3090 	int				counter;
3091 
3092 	counter = __atomic_sub_fetch(ctx->inflight_op_counter, 1, __ATOMIC_SEQ_CST);
3093 	SPDK_DEBUGLOG(rdma, "nvmf_rdma_all_pollers_management_done called. counter: %d, poller: %p\n",
3094 		      counter, ctx->rpoller);
3095 
3096 	if (counter == 0) {
3097 		free((void *)ctx->inflight_op_counter);
3098 	}
3099 	free(ctx);
3100 
3101 	return counter == 0;
3102 }
3103 
3104 static int
3105 nvmf_rdma_manage_poller(struct spdk_nvmf_rdma_transport *rtransport,
3106 			struct spdk_nvmf_rdma_device *device, bool *has_inflight, bool is_add)
3107 {
3108 	struct spdk_nvmf_rdma_poll_group	*rgroup;
3109 	struct spdk_nvmf_rdma_poller		*rpoller;
3110 	struct spdk_nvmf_poll_group		*poll_group;
3111 	struct poller_manage_ctx		*ctx;
3112 	bool					found;
3113 	int					*inflight_counter;
3114 	spdk_msg_fn				do_fn;
3115 
3116 	*has_inflight = false;
3117 	do_fn = is_add ? _nvmf_rdma_register_poller_in_group : _nvmf_rdma_remove_poller_in_group;
3118 	inflight_counter = calloc(1, sizeof(int));
3119 	if (!inflight_counter) {
3120 		SPDK_ERRLOG("Failed to allocate inflight counter when removing pollers\n");
3121 		return -ENOMEM;
3122 	}
3123 
3124 	TAILQ_FOREACH(rgroup, &rtransport->poll_groups, link) {
3125 		(*inflight_counter)++;
3126 	}
3127 
3128 	TAILQ_FOREACH(rgroup, &rtransport->poll_groups, link) {
3129 		found = false;
3130 		TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
3131 			if (rpoller->device == device) {
3132 				found = true;
3133 				break;
3134 			}
3135 		}
3136 		if (found == is_add) {
3137 			__atomic_fetch_sub(inflight_counter, 1, __ATOMIC_SEQ_CST);
3138 			continue;
3139 		}
3140 
3141 		ctx = calloc(1, sizeof(struct poller_manage_ctx));
3142 		if (!ctx) {
3143 			SPDK_ERRLOG("Failed to allocate poller_manage_ctx when removing pollers\n");
3144 			if (!*has_inflight) {
3145 				free(inflight_counter);
3146 			}
3147 			return -ENOMEM;
3148 		}
3149 
3150 		ctx->rtransport = rtransport;
3151 		ctx->rgroup = rgroup;
3152 		ctx->rpoller = rpoller;
3153 		ctx->device = device;
3154 		ctx->thread = spdk_get_thread();
3155 		ctx->inflight_op_counter = inflight_counter;
3156 		*has_inflight = true;
3157 
3158 		poll_group = rgroup->group.group;
3159 		if (poll_group->thread != spdk_get_thread()) {
3160 			spdk_thread_send_msg(poll_group->thread, do_fn, ctx);
3161 		} else {
3162 			do_fn(ctx);
3163 		}
3164 	}
3165 
3166 	if (!*has_inflight) {
3167 		free(inflight_counter);
3168 	}
3169 
3170 	return 0;
3171 }
3172 
3173 static void nvmf_rdma_handle_device_removal(struct spdk_nvmf_rdma_transport *rtransport,
3174 		struct spdk_nvmf_rdma_device *device);
3175 
3176 static struct spdk_nvmf_rdma_device *
3177 nvmf_rdma_find_ib_device(struct spdk_nvmf_rdma_transport *rtransport,
3178 			 struct ibv_context *context)
3179 {
3180 	struct spdk_nvmf_rdma_device	*device, *tmp_device;
3181 
3182 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, tmp_device) {
3183 		if (device->need_destroy) {
3184 			continue;
3185 		}
3186 
3187 		if (strcmp(device->context->device->dev_name, context->device->dev_name) == 0) {
3188 			return device;
3189 		}
3190 	}
3191 
3192 	return NULL;
3193 }
3194 
3195 static bool
3196 nvmf_rdma_check_devices_context(struct spdk_nvmf_rdma_transport *rtransport,
3197 				struct ibv_context *context)
3198 {
3199 	struct spdk_nvmf_rdma_device	*old_device, *new_device;
3200 	int				rc = 0;
3201 	bool				has_inflight;
3202 
3203 	old_device = nvmf_rdma_find_ib_device(rtransport, context);
3204 
3205 	if (old_device) {
3206 		if (old_device->context != context && !old_device->need_destroy && old_device->is_ready) {
3207 			/* context may not have time to be cleaned when rescan. exactly one context
3208 			 * is valid for a device so this context must be invalid and just remove it. */
3209 			SPDK_WARNLOG("Device %p has a invalid context %p\n", old_device, old_device->context);
3210 			old_device->need_destroy = true;
3211 			nvmf_rdma_handle_device_removal(rtransport, old_device);
3212 		}
3213 		return false;
3214 	}
3215 
3216 	rc = create_ib_device(rtransport, context, &new_device);
3217 	/* TODO: update transport opts. */
3218 	if (rc < 0) {
3219 		SPDK_ERRLOG("Failed to create ib device for context: %s(%p)\n",
3220 			    ibv_get_device_name(context->device), context);
3221 		return false;
3222 	}
3223 
3224 	rc = nvmf_rdma_manage_poller(rtransport, new_device, &has_inflight, true);
3225 	if (rc < 0) {
3226 		SPDK_ERRLOG("Failed to add poller for device context: %s(%p)\n",
3227 			    ibv_get_device_name(context->device), context);
3228 		return false;
3229 	}
3230 
3231 	if (has_inflight) {
3232 		new_device->is_ready = true;
3233 	}
3234 
3235 	return true;
3236 }
3237 
3238 static bool
3239 nvmf_rdma_rescan_devices(struct spdk_nvmf_rdma_transport *rtransport)
3240 {
3241 	struct spdk_nvmf_rdma_device	*device;
3242 	struct ibv_device		**ibv_device_list = NULL;
3243 	struct ibv_context		**contexts = NULL;
3244 	int				i = 0;
3245 	int				num_dev = 0;
3246 	bool				new_create = false, has_new_device = false;
3247 	struct ibv_context		*tmp_verbs = NULL;
3248 
3249 	/* do not rescan when any device is destroying, or context may be freed when
3250 	 * regenerating the poll fds.
3251 	 */
3252 	TAILQ_FOREACH(device, &rtransport->devices, link) {
3253 		if (device->need_destroy) {
3254 			return false;
3255 		}
3256 	}
3257 
3258 	ibv_device_list = ibv_get_device_list(&num_dev);
3259 
3260 	/* There is a bug in librdmacm. If verbs init failed in rdma_get_devices, it'll be
3261 	 * marked as dead verbs and never be init again. So we need to make sure the
3262 	 * verbs is available before we call rdma_get_devices. */
3263 	if (num_dev >= 0) {
3264 		for (i = 0; i < num_dev; i++) {
3265 			tmp_verbs = ibv_open_device(ibv_device_list[i]);
3266 			if (!tmp_verbs) {
3267 				SPDK_WARNLOG("Failed to init ibv device %p, err %d. Skip rescan.\n", ibv_device_list[i], errno);
3268 				break;
3269 			}
3270 			if (nvmf_rdma_find_ib_device(rtransport, tmp_verbs) == NULL) {
3271 				SPDK_DEBUGLOG(rdma, "Find new verbs init ibv device %p(%s).\n", ibv_device_list[i],
3272 					      tmp_verbs->device->dev_name);
3273 				has_new_device = true;
3274 			}
3275 			ibv_close_device(tmp_verbs);
3276 		}
3277 		ibv_free_device_list(ibv_device_list);
3278 		if (!tmp_verbs || !has_new_device) {
3279 			return false;
3280 		}
3281 	}
3282 
3283 	contexts = rdma_get_devices(NULL);
3284 
3285 	for (i = 0; contexts && contexts[i] != NULL; i++) {
3286 		new_create |= nvmf_rdma_check_devices_context(rtransport, contexts[i]);
3287 	}
3288 
3289 	if (new_create) {
3290 		free_poll_fds(rtransport);
3291 		generate_poll_fds(rtransport);
3292 	}
3293 
3294 	if (contexts) {
3295 		rdma_free_devices(contexts);
3296 	}
3297 
3298 	return new_create;
3299 }
3300 
3301 static bool
3302 nvmf_rdma_retry_listen_port(struct spdk_nvmf_rdma_transport *rtransport)
3303 {
3304 	struct spdk_nvmf_rdma_port	*port, *tmp_port;
3305 	int				rc = 0;
3306 	bool				new_create = false;
3307 
3308 	if (TAILQ_EMPTY(&rtransport->retry_ports)) {
3309 		return false;
3310 	}
3311 
3312 	new_create = nvmf_rdma_rescan_devices(rtransport);
3313 
3314 	TAILQ_FOREACH_SAFE(port, &rtransport->retry_ports, link, tmp_port) {
3315 		rc = nvmf_rdma_listen(&rtransport->transport, port->trid, NULL);
3316 
3317 		TAILQ_REMOVE(&rtransport->retry_ports, port, link);
3318 		if (rc) {
3319 			if (new_create) {
3320 				SPDK_ERRLOG("Found new IB device but port %s:%s is still failed(%d) to listen.\n",
3321 					    port->trid->traddr, port->trid->trsvcid, rc);
3322 			}
3323 			TAILQ_INSERT_TAIL(&rtransport->retry_ports, port, link);
3324 			break;
3325 		} else {
3326 			SPDK_NOTICELOG("Port %s:%s come back\n", port->trid->traddr, port->trid->trsvcid);
3327 			free(port);
3328 		}
3329 	}
3330 
3331 	return true;
3332 }
3333 
3334 static void
3335 nvmf_rdma_qpair_process_pending(struct spdk_nvmf_rdma_transport *rtransport,
3336 				struct spdk_nvmf_rdma_qpair *rqpair, bool drain)
3337 {
3338 	struct spdk_nvmf_request *req, *tmp;
3339 	struct spdk_nvmf_rdma_request	*rdma_req, *req_tmp;
3340 	struct spdk_nvmf_rdma_resources *resources;
3341 
3342 	/* First process requests which are waiting for response to be sent */
3343 	STAILQ_FOREACH_SAFE(rdma_req, &rqpair->pending_rdma_send_queue, state_link, req_tmp) {
3344 		if (nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
3345 			break;
3346 		}
3347 	}
3348 
3349 	/* We process I/O in the data transfer pending queue at the highest priority. */
3350 	STAILQ_FOREACH_SAFE(rdma_req, &rqpair->pending_rdma_read_queue, state_link, req_tmp) {
3351 		if (nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
3352 			break;
3353 		}
3354 	}
3355 
3356 	/* Then RDMA writes since reads have stronger restrictions than writes */
3357 	STAILQ_FOREACH_SAFE(rdma_req, &rqpair->pending_rdma_write_queue, state_link, req_tmp) {
3358 		if (nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
3359 			break;
3360 		}
3361 	}
3362 
3363 	/* Then we handle request waiting on memory buffers. */
3364 	STAILQ_FOREACH_SAFE(req, &rqpair->poller->group->group.pending_buf_queue, buf_link, tmp) {
3365 		rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
3366 		if (nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
3367 			break;
3368 		}
3369 	}
3370 
3371 	resources = rqpair->resources;
3372 	while (!STAILQ_EMPTY(&resources->free_queue) && !STAILQ_EMPTY(&resources->incoming_queue)) {
3373 		rdma_req = STAILQ_FIRST(&resources->free_queue);
3374 		STAILQ_REMOVE_HEAD(&resources->free_queue, state_link);
3375 		rdma_req->recv = STAILQ_FIRST(&resources->incoming_queue);
3376 		STAILQ_REMOVE_HEAD(&resources->incoming_queue, link);
3377 
3378 		if (rqpair->srq != NULL) {
3379 			rdma_req->req.qpair = &rdma_req->recv->qpair->qpair;
3380 			rdma_req->recv->qpair->qd++;
3381 		} else {
3382 			rqpair->qd++;
3383 		}
3384 
3385 		rdma_req->receive_tsc = rdma_req->recv->receive_tsc;
3386 		rdma_req->state = RDMA_REQUEST_STATE_NEW;
3387 		if (nvmf_rdma_request_process(rtransport, rdma_req) == false) {
3388 			break;
3389 		}
3390 	}
3391 	if (!STAILQ_EMPTY(&resources->incoming_queue) && STAILQ_EMPTY(&resources->free_queue)) {
3392 		rqpair->poller->stat.pending_free_request++;
3393 	}
3394 }
3395 
3396 static void
3397 nvmf_rdma_poller_process_pending_buf_queue(struct spdk_nvmf_rdma_transport *rtransport,
3398 		struct spdk_nvmf_rdma_poller *rpoller)
3399 {
3400 	struct spdk_nvmf_request *req, *tmp;
3401 	struct spdk_nvmf_rdma_request *rdma_req;
3402 
3403 	STAILQ_FOREACH_SAFE(req, &rpoller->group->group.pending_buf_queue, buf_link, tmp) {
3404 		rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
3405 		if (nvmf_rdma_request_process(rtransport, rdma_req) == false) {
3406 			break;
3407 		}
3408 	}
3409 }
3410 
3411 static inline bool
3412 nvmf_rdma_can_ignore_last_wqe_reached(struct spdk_nvmf_rdma_device *device)
3413 {
3414 	/* iWARP transport and SoftRoCE driver don't support LAST_WQE_REACHED ibv async event */
3415 	return nvmf_rdma_is_rxe_device(device) ||
3416 	       device->context->device->transport_type == IBV_TRANSPORT_IWARP;
3417 }
3418 
3419 static void
3420 nvmf_rdma_destroy_drained_qpair(struct spdk_nvmf_rdma_qpair *rqpair)
3421 {
3422 	struct spdk_nvmf_rdma_transport *rtransport = SPDK_CONTAINEROF(rqpair->qpair.transport,
3423 			struct spdk_nvmf_rdma_transport, transport);
3424 
3425 	nvmf_rdma_qpair_process_pending(rtransport, rqpair, true);
3426 
3427 	/* nvmf_rdma_close_qpair is not called */
3428 	if (!rqpair->to_close) {
3429 		return;
3430 	}
3431 
3432 	/* device is already destroyed and we should force destroy this qpair. */
3433 	if (rqpair->poller && rqpair->poller->need_destroy) {
3434 		nvmf_rdma_qpair_destroy(rqpair);
3435 		return;
3436 	}
3437 
3438 	/* In non SRQ path, we will reach rqpair->max_queue_depth. In SRQ path, we will get the last_wqe event. */
3439 	if (rqpair->current_send_depth != 0) {
3440 		return;
3441 	}
3442 
3443 	if (rqpair->srq == NULL && rqpair->current_recv_depth != rqpair->max_queue_depth) {
3444 		return;
3445 	}
3446 
3447 	if (rqpair->srq != NULL && rqpair->last_wqe_reached == false &&
3448 	    !nvmf_rdma_can_ignore_last_wqe_reached(rqpair->device)) {
3449 		return;
3450 	}
3451 
3452 	assert(rqpair->qpair.state == SPDK_NVMF_QPAIR_ERROR);
3453 
3454 	nvmf_rdma_qpair_destroy(rqpair);
3455 }
3456 
3457 static int
3458 nvmf_rdma_disconnect(struct rdma_cm_event *evt, bool *event_acked)
3459 {
3460 	struct spdk_nvmf_qpair		*qpair;
3461 	struct spdk_nvmf_rdma_qpair	*rqpair;
3462 
3463 	if (evt->id == NULL) {
3464 		SPDK_ERRLOG("disconnect request: missing cm_id\n");
3465 		return -1;
3466 	}
3467 
3468 	qpair = evt->id->context;
3469 	if (qpair == NULL) {
3470 		SPDK_ERRLOG("disconnect request: no active connection\n");
3471 		return -1;
3472 	}
3473 
3474 	rdma_ack_cm_event(evt);
3475 	*event_acked = true;
3476 
3477 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
3478 
3479 	spdk_trace_record(TRACE_RDMA_QP_DISCONNECT, 0, 0, (uintptr_t)rqpair);
3480 
3481 	spdk_nvmf_qpair_disconnect(&rqpair->qpair);
3482 
3483 	return 0;
3484 }
3485 
3486 #ifdef DEBUG
3487 static const char *CM_EVENT_STR[] = {
3488 	"RDMA_CM_EVENT_ADDR_RESOLVED",
3489 	"RDMA_CM_EVENT_ADDR_ERROR",
3490 	"RDMA_CM_EVENT_ROUTE_RESOLVED",
3491 	"RDMA_CM_EVENT_ROUTE_ERROR",
3492 	"RDMA_CM_EVENT_CONNECT_REQUEST",
3493 	"RDMA_CM_EVENT_CONNECT_RESPONSE",
3494 	"RDMA_CM_EVENT_CONNECT_ERROR",
3495 	"RDMA_CM_EVENT_UNREACHABLE",
3496 	"RDMA_CM_EVENT_REJECTED",
3497 	"RDMA_CM_EVENT_ESTABLISHED",
3498 	"RDMA_CM_EVENT_DISCONNECTED",
3499 	"RDMA_CM_EVENT_DEVICE_REMOVAL",
3500 	"RDMA_CM_EVENT_MULTICAST_JOIN",
3501 	"RDMA_CM_EVENT_MULTICAST_ERROR",
3502 	"RDMA_CM_EVENT_ADDR_CHANGE",
3503 	"RDMA_CM_EVENT_TIMEWAIT_EXIT"
3504 };
3505 #endif /* DEBUG */
3506 
3507 static void
3508 nvmf_rdma_disconnect_qpairs_on_port(struct spdk_nvmf_rdma_transport *rtransport,
3509 				    struct spdk_nvmf_rdma_port *port)
3510 {
3511 	struct spdk_nvmf_rdma_poll_group	*rgroup;
3512 	struct spdk_nvmf_rdma_poller		*rpoller;
3513 	struct spdk_nvmf_rdma_qpair		*rqpair;
3514 
3515 	TAILQ_FOREACH(rgroup, &rtransport->poll_groups, link) {
3516 		TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
3517 			RB_FOREACH(rqpair, qpairs_tree, &rpoller->qpairs) {
3518 				if (rqpair->listen_id == port->id) {
3519 					spdk_nvmf_qpair_disconnect(&rqpair->qpair);
3520 				}
3521 			}
3522 		}
3523 	}
3524 }
3525 
3526 static bool
3527 nvmf_rdma_handle_cm_event_addr_change(struct spdk_nvmf_transport *transport,
3528 				      struct rdma_cm_event *event)
3529 {
3530 	const struct spdk_nvme_transport_id	*trid;
3531 	struct spdk_nvmf_rdma_port		*port;
3532 	struct spdk_nvmf_rdma_transport		*rtransport;
3533 	bool					event_acked = false;
3534 
3535 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3536 	TAILQ_FOREACH(port, &rtransport->ports, link) {
3537 		if (port->id == event->id) {
3538 			SPDK_ERRLOG("ADDR_CHANGE: IP %s:%s migrated\n", port->trid->traddr, port->trid->trsvcid);
3539 			rdma_ack_cm_event(event);
3540 			event_acked = true;
3541 			trid = port->trid;
3542 			break;
3543 		}
3544 	}
3545 
3546 	if (event_acked) {
3547 		nvmf_rdma_disconnect_qpairs_on_port(rtransport, port);
3548 
3549 		nvmf_rdma_stop_listen(transport, trid);
3550 		nvmf_rdma_listen(transport, trid, NULL);
3551 	}
3552 
3553 	return event_acked;
3554 }
3555 
3556 static void
3557 nvmf_rdma_handle_device_removal(struct spdk_nvmf_rdma_transport *rtransport,
3558 				struct spdk_nvmf_rdma_device *device)
3559 {
3560 	struct spdk_nvmf_rdma_port	*port, *port_tmp;
3561 	int				rc;
3562 	bool				has_inflight;
3563 
3564 	rc = nvmf_rdma_manage_poller(rtransport, device, &has_inflight, false);
3565 	if (rc) {
3566 		SPDK_ERRLOG("Failed to handle device removal, rc %d\n", rc);
3567 		return;
3568 	}
3569 
3570 	if (!has_inflight) {
3571 		/* no pollers, destroy the device */
3572 		device->ready_to_destroy = true;
3573 		spdk_thread_send_msg(spdk_get_thread(), _nvmf_rdma_remove_destroyed_device, rtransport);
3574 	}
3575 
3576 	TAILQ_FOREACH_SAFE(port, &rtransport->ports, link, port_tmp) {
3577 		if (port->device == device) {
3578 			SPDK_NOTICELOG("Port %s:%s on device %s is being removed.\n",
3579 				       port->trid->traddr,
3580 				       port->trid->trsvcid,
3581 				       ibv_get_device_name(port->device->context->device));
3582 
3583 			/* keep NVMF listener and only destroy structures of the
3584 			 * RDMA transport. when the device comes back we can retry listening
3585 			 * and the application's workflow will not be interrupted.
3586 			 */
3587 			nvmf_rdma_stop_listen_ex(&rtransport->transport, port->trid, true);
3588 		}
3589 	}
3590 }
3591 
3592 static void
3593 nvmf_rdma_handle_cm_event_port_removal(struct spdk_nvmf_transport *transport,
3594 				       struct rdma_cm_event *event)
3595 {
3596 	struct spdk_nvmf_rdma_port		*port, *tmp_port;
3597 	struct spdk_nvmf_rdma_transport		*rtransport;
3598 
3599 	port = event->id->context;
3600 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3601 
3602 	rdma_ack_cm_event(event);
3603 
3604 	/* if device removal happens during ctrl qpair disconnecting, it's possible that we receive
3605 	 * an DEVICE_REMOVAL event on qpair but the id->qp is just NULL. So we should make sure that
3606 	 * we are handling a port event here.
3607 	 */
3608 	TAILQ_FOREACH(tmp_port, &rtransport->ports, link) {
3609 		if (port == tmp_port && port->device && !port->device->need_destroy) {
3610 			port->device->need_destroy = true;
3611 			nvmf_rdma_handle_device_removal(rtransport, port->device);
3612 		}
3613 	}
3614 }
3615 
3616 static void
3617 nvmf_process_cm_events(struct spdk_nvmf_transport *transport, uint32_t max_events)
3618 {
3619 	struct spdk_nvmf_rdma_transport *rtransport;
3620 	struct rdma_cm_event		*event;
3621 	uint32_t			i;
3622 	int				rc;
3623 	bool				event_acked;
3624 
3625 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3626 
3627 	if (rtransport->event_channel == NULL) {
3628 		return;
3629 	}
3630 
3631 	for (i = 0; i < max_events; i++) {
3632 		event_acked = false;
3633 		rc = rdma_get_cm_event(rtransport->event_channel, &event);
3634 		if (rc) {
3635 			if (errno != EAGAIN && errno != EWOULDBLOCK) {
3636 				SPDK_ERRLOG("Acceptor Event Error: %s\n", spdk_strerror(errno));
3637 			}
3638 			break;
3639 		}
3640 
3641 		SPDK_DEBUGLOG(rdma, "Acceptor Event: %s\n", CM_EVENT_STR[event->event]);
3642 
3643 		spdk_trace_record(TRACE_RDMA_CM_ASYNC_EVENT, 0, 0, 0, event->event);
3644 
3645 		switch (event->event) {
3646 		case RDMA_CM_EVENT_ADDR_RESOLVED:
3647 		case RDMA_CM_EVENT_ADDR_ERROR:
3648 		case RDMA_CM_EVENT_ROUTE_RESOLVED:
3649 		case RDMA_CM_EVENT_ROUTE_ERROR:
3650 			/* No action required. The target never attempts to resolve routes. */
3651 			break;
3652 		case RDMA_CM_EVENT_CONNECT_REQUEST:
3653 			rc = nvmf_rdma_connect(transport, event);
3654 			if (rc < 0) {
3655 				SPDK_ERRLOG("Unable to process connect event. rc: %d\n", rc);
3656 				break;
3657 			}
3658 			break;
3659 		case RDMA_CM_EVENT_CONNECT_RESPONSE:
3660 			/* The target never initiates a new connection. So this will not occur. */
3661 			break;
3662 		case RDMA_CM_EVENT_CONNECT_ERROR:
3663 			/* Can this happen? The docs say it can, but not sure what causes it. */
3664 			break;
3665 		case RDMA_CM_EVENT_UNREACHABLE:
3666 		case RDMA_CM_EVENT_REJECTED:
3667 			/* These only occur on the client side. */
3668 			break;
3669 		case RDMA_CM_EVENT_ESTABLISHED:
3670 			/* TODO: Should we be waiting for this event anywhere? */
3671 			break;
3672 		case RDMA_CM_EVENT_DISCONNECTED:
3673 			rc = nvmf_rdma_disconnect(event, &event_acked);
3674 			if (rc < 0) {
3675 				SPDK_ERRLOG("Unable to process disconnect event. rc: %d\n", rc);
3676 				break;
3677 			}
3678 			break;
3679 		case RDMA_CM_EVENT_DEVICE_REMOVAL:
3680 			/* In case of device removal, kernel IB part triggers IBV_EVENT_DEVICE_FATAL
3681 			 * which triggers RDMA_CM_EVENT_DEVICE_REMOVAL on all cma_id’s.
3682 			 * Once these events are sent to SPDK, we should release all IB resources and
3683 			 * don't make attempts to call any ibv_query/modify/create functions. We can only call
3684 			 * ibv_destroy* functions to release user space memory allocated by IB. All kernel
3685 			 * resources are already cleaned. */
3686 			if (event->id->qp) {
3687 				/* If rdma_cm event has a valid `qp` pointer then the event refers to the
3688 				 * corresponding qpair. Otherwise the event refers to a listening device. */
3689 				rc = nvmf_rdma_disconnect(event, &event_acked);
3690 				if (rc < 0) {
3691 					SPDK_ERRLOG("Unable to process disconnect event. rc: %d\n", rc);
3692 					break;
3693 				}
3694 			} else {
3695 				nvmf_rdma_handle_cm_event_port_removal(transport, event);
3696 				event_acked = true;
3697 			}
3698 			break;
3699 		case RDMA_CM_EVENT_MULTICAST_JOIN:
3700 		case RDMA_CM_EVENT_MULTICAST_ERROR:
3701 			/* Multicast is not used */
3702 			break;
3703 		case RDMA_CM_EVENT_ADDR_CHANGE:
3704 			event_acked = nvmf_rdma_handle_cm_event_addr_change(transport, event);
3705 			break;
3706 		case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3707 			/* For now, do nothing. The target never re-uses queue pairs. */
3708 			break;
3709 		default:
3710 			SPDK_ERRLOG("Unexpected Acceptor Event [%d]\n", event->event);
3711 			break;
3712 		}
3713 		if (!event_acked) {
3714 			rdma_ack_cm_event(event);
3715 		}
3716 	}
3717 }
3718 
3719 static void
3720 nvmf_rdma_handle_last_wqe_reached(struct spdk_nvmf_rdma_qpair *rqpair)
3721 {
3722 	rqpair->last_wqe_reached = true;
3723 	nvmf_rdma_destroy_drained_qpair(rqpair);
3724 }
3725 
3726 static void
3727 nvmf_rdma_qpair_process_ibv_event(void *ctx)
3728 {
3729 	struct spdk_nvmf_rdma_ibv_event_ctx *event_ctx = ctx;
3730 
3731 	if (event_ctx->rqpair) {
3732 		STAILQ_REMOVE(&event_ctx->rqpair->ibv_events, event_ctx, spdk_nvmf_rdma_ibv_event_ctx, link);
3733 		if (event_ctx->cb_fn) {
3734 			event_ctx->cb_fn(event_ctx->rqpair);
3735 		}
3736 	}
3737 	free(event_ctx);
3738 }
3739 
3740 static int
3741 nvmf_rdma_send_qpair_async_event(struct spdk_nvmf_rdma_qpair *rqpair,
3742 				 spdk_nvmf_rdma_qpair_ibv_event fn)
3743 {
3744 	struct spdk_nvmf_rdma_ibv_event_ctx *ctx;
3745 	struct spdk_thread *thr = NULL;
3746 	int rc;
3747 
3748 	if (rqpair->qpair.group) {
3749 		thr = rqpair->qpair.group->thread;
3750 	} else if (rqpair->destruct_channel) {
3751 		thr = spdk_io_channel_get_thread(rqpair->destruct_channel);
3752 	}
3753 
3754 	if (!thr) {
3755 		SPDK_DEBUGLOG(rdma, "rqpair %p has no thread\n", rqpair);
3756 		return -EINVAL;
3757 	}
3758 
3759 	ctx = calloc(1, sizeof(*ctx));
3760 	if (!ctx) {
3761 		return -ENOMEM;
3762 	}
3763 
3764 	ctx->rqpair = rqpair;
3765 	ctx->cb_fn = fn;
3766 	STAILQ_INSERT_TAIL(&rqpair->ibv_events, ctx, link);
3767 
3768 	rc = spdk_thread_send_msg(thr, nvmf_rdma_qpair_process_ibv_event, ctx);
3769 	if (rc) {
3770 		STAILQ_REMOVE(&rqpair->ibv_events, ctx, spdk_nvmf_rdma_ibv_event_ctx, link);
3771 		free(ctx);
3772 	}
3773 
3774 	return rc;
3775 }
3776 
3777 static int
3778 nvmf_process_ib_event(struct spdk_nvmf_rdma_device *device)
3779 {
3780 	int				rc;
3781 	struct spdk_nvmf_rdma_qpair	*rqpair = NULL;
3782 	struct ibv_async_event		event;
3783 
3784 	rc = ibv_get_async_event(device->context, &event);
3785 
3786 	if (rc) {
3787 		/* In non-blocking mode -1 means there are no events available */
3788 		return rc;
3789 	}
3790 
3791 	switch (event.event_type) {
3792 	case IBV_EVENT_QP_FATAL:
3793 	case IBV_EVENT_QP_LAST_WQE_REACHED:
3794 	case IBV_EVENT_QP_REQ_ERR:
3795 	case IBV_EVENT_QP_ACCESS_ERR:
3796 	case IBV_EVENT_COMM_EST:
3797 	case IBV_EVENT_PATH_MIG:
3798 	case IBV_EVENT_PATH_MIG_ERR:
3799 		rqpair = event.element.qp->qp_context;
3800 		if (!rqpair) {
3801 			/* Any QP event for NVMe-RDMA initiator may be returned. */
3802 			SPDK_NOTICELOG("Async QP event for unknown QP: %s\n",
3803 				       ibv_event_type_str(event.event_type));
3804 			break;
3805 		}
3806 
3807 		switch (event.event_type) {
3808 		case IBV_EVENT_QP_FATAL:
3809 			SPDK_ERRLOG("Fatal event received for rqpair %p\n", rqpair);
3810 			spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0,
3811 					  (uintptr_t)rqpair, event.event_type);
3812 			rqpair->ibv_in_error_state = true;
3813 			spdk_nvmf_qpair_disconnect(&rqpair->qpair);
3814 			break;
3815 		case IBV_EVENT_QP_LAST_WQE_REACHED:
3816 			/* This event only occurs for shared receive queues. */
3817 			SPDK_DEBUGLOG(rdma, "Last WQE reached event received for rqpair %p\n", rqpair);
3818 			rc = nvmf_rdma_send_qpair_async_event(rqpair, nvmf_rdma_handle_last_wqe_reached);
3819 			if (rc) {
3820 				SPDK_WARNLOG("Failed to send LAST_WQE_REACHED event. rqpair %p, err %d\n", rqpair, rc);
3821 				rqpair->last_wqe_reached = true;
3822 			}
3823 			break;
3824 		case IBV_EVENT_QP_REQ_ERR:
3825 		case IBV_EVENT_QP_ACCESS_ERR:
3826 		case IBV_EVENT_COMM_EST:
3827 		case IBV_EVENT_PATH_MIG:
3828 		case IBV_EVENT_PATH_MIG_ERR:
3829 			SPDK_NOTICELOG("Async QP event: %s\n",
3830 				       ibv_event_type_str(event.event_type));
3831 			spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0,
3832 					  (uintptr_t)rqpair, event.event_type);
3833 			rqpair->ibv_in_error_state = true;
3834 			break;
3835 		default:
3836 			break;
3837 		}
3838 		break;
3839 	case IBV_EVENT_DEVICE_FATAL:
3840 		SPDK_ERRLOG("Device Fatal event[%s] received on %s. device: %p\n",
3841 			    ibv_event_type_str(event.event_type), ibv_get_device_name(device->context->device), device);
3842 		device->need_destroy = true;
3843 		break;
3844 	case IBV_EVENT_CQ_ERR:
3845 	case IBV_EVENT_PORT_ACTIVE:
3846 	case IBV_EVENT_PORT_ERR:
3847 	case IBV_EVENT_LID_CHANGE:
3848 	case IBV_EVENT_PKEY_CHANGE:
3849 	case IBV_EVENT_SM_CHANGE:
3850 	case IBV_EVENT_SRQ_ERR:
3851 	case IBV_EVENT_SRQ_LIMIT_REACHED:
3852 	case IBV_EVENT_CLIENT_REREGISTER:
3853 	case IBV_EVENT_GID_CHANGE:
3854 	case IBV_EVENT_SQ_DRAINED:
3855 	default:
3856 		SPDK_NOTICELOG("Async event: %s\n",
3857 			       ibv_event_type_str(event.event_type));
3858 		spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0, 0, event.event_type);
3859 		break;
3860 	}
3861 	ibv_ack_async_event(&event);
3862 
3863 	return 0;
3864 }
3865 
3866 static void
3867 nvmf_process_ib_events(struct spdk_nvmf_rdma_device *device, uint32_t max_events)
3868 {
3869 	int rc = 0;
3870 	uint32_t i = 0;
3871 
3872 	for (i = 0; i < max_events; i++) {
3873 		rc = nvmf_process_ib_event(device);
3874 		if (rc) {
3875 			break;
3876 		}
3877 	}
3878 
3879 	SPDK_DEBUGLOG(rdma, "Device %s: %u events processed\n", device->context->device->name, i);
3880 }
3881 
3882 static int
3883 nvmf_rdma_accept(void *ctx)
3884 {
3885 	int	nfds, i = 0;
3886 	struct spdk_nvmf_transport *transport = ctx;
3887 	struct spdk_nvmf_rdma_transport *rtransport;
3888 	struct spdk_nvmf_rdma_device *device, *tmp;
3889 	uint32_t count;
3890 	short revents;
3891 	bool do_retry;
3892 
3893 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3894 	do_retry = nvmf_rdma_retry_listen_port(rtransport);
3895 
3896 	count = nfds = poll(rtransport->poll_fds, rtransport->npoll_fds, 0);
3897 
3898 	if (nfds <= 0) {
3899 		return do_retry ? SPDK_POLLER_BUSY : SPDK_POLLER_IDLE;
3900 	}
3901 
3902 	/* The first poll descriptor is RDMA CM event */
3903 	if (rtransport->poll_fds[i++].revents & POLLIN) {
3904 		nvmf_process_cm_events(transport, NVMF_RDMA_MAX_EVENTS_PER_POLL);
3905 		nfds--;
3906 	}
3907 
3908 	if (nfds == 0) {
3909 		return SPDK_POLLER_BUSY;
3910 	}
3911 
3912 	/* Second and subsequent poll descriptors are IB async events */
3913 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, tmp) {
3914 		revents = rtransport->poll_fds[i++].revents;
3915 		if (revents & POLLIN) {
3916 			if (spdk_likely(!device->need_destroy)) {
3917 				nvmf_process_ib_events(device, NVMF_RDMA_MAX_EVENTS_PER_POLL);
3918 				if (spdk_unlikely(device->need_destroy)) {
3919 					nvmf_rdma_handle_device_removal(rtransport, device);
3920 				}
3921 			}
3922 			nfds--;
3923 		} else if (revents & POLLNVAL || revents & POLLHUP) {
3924 			SPDK_ERRLOG("Receive unknown revent %x on device %p\n", (int)revents, device);
3925 			nfds--;
3926 		}
3927 	}
3928 	/* check all flagged fd's have been served */
3929 	assert(nfds == 0);
3930 
3931 	return count > 0 ? SPDK_POLLER_BUSY : SPDK_POLLER_IDLE;
3932 }
3933 
3934 static void
3935 nvmf_rdma_cdata_init(struct spdk_nvmf_transport *transport, struct spdk_nvmf_subsystem *subsystem,
3936 		     struct spdk_nvmf_ctrlr_data *cdata)
3937 {
3938 	cdata->nvmf_specific.msdbd = NVMF_DEFAULT_MSDBD;
3939 
3940 	/* Disable in-capsule data transfer for RDMA controller when dif_insert_or_strip is enabled
3941 	since in-capsule data only works with NVME drives that support SGL memory layout */
3942 	if (transport->opts.dif_insert_or_strip) {
3943 		cdata->nvmf_specific.ioccsz = sizeof(struct spdk_nvme_cmd) / 16;
3944 	}
3945 
3946 	if (cdata->nvmf_specific.ioccsz > ((sizeof(struct spdk_nvme_cmd) + 0x1000) / 16)) {
3947 		SPDK_WARNLOG("RDMA is configured to support up to 16 SGL entries while in capsule"
3948 			     " data is greater than 4KiB.\n");
3949 		SPDK_WARNLOG("When used in conjunction with the NVMe-oF initiator from the Linux "
3950 			     "kernel between versions 5.4 and 5.12 data corruption may occur for "
3951 			     "writes that are not a multiple of 4KiB in size.\n");
3952 	}
3953 }
3954 
3955 static void
3956 nvmf_rdma_discover(struct spdk_nvmf_transport *transport,
3957 		   struct spdk_nvme_transport_id *trid,
3958 		   struct spdk_nvmf_discovery_log_page_entry *entry)
3959 {
3960 	entry->trtype = SPDK_NVMF_TRTYPE_RDMA;
3961 	entry->adrfam = trid->adrfam;
3962 	entry->treq.secure_channel = SPDK_NVMF_TREQ_SECURE_CHANNEL_NOT_REQUIRED;
3963 
3964 	spdk_strcpy_pad(entry->trsvcid, trid->trsvcid, sizeof(entry->trsvcid), ' ');
3965 	spdk_strcpy_pad(entry->traddr, trid->traddr, sizeof(entry->traddr), ' ');
3966 
3967 	entry->tsas.rdma.rdma_qptype = SPDK_NVMF_RDMA_QPTYPE_RELIABLE_CONNECTED;
3968 	entry->tsas.rdma.rdma_prtype = SPDK_NVMF_RDMA_PRTYPE_NONE;
3969 	entry->tsas.rdma.rdma_cms = SPDK_NVMF_RDMA_CMS_RDMA_CM;
3970 }
3971 
3972 static int
3973 nvmf_rdma_poller_create(struct spdk_nvmf_rdma_transport *rtransport,
3974 			struct spdk_nvmf_rdma_poll_group *rgroup, struct spdk_nvmf_rdma_device *device,
3975 			struct spdk_nvmf_rdma_poller **out_poller)
3976 {
3977 	struct spdk_nvmf_rdma_poller		*poller;
3978 	struct spdk_rdma_provider_srq_init_attr	srq_init_attr;
3979 	struct spdk_nvmf_rdma_resource_opts	opts;
3980 	int					num_cqe;
3981 
3982 	poller = calloc(1, sizeof(*poller));
3983 	if (!poller) {
3984 		SPDK_ERRLOG("Unable to allocate memory for new RDMA poller\n");
3985 		return -1;
3986 	}
3987 
3988 	poller->device = device;
3989 	poller->group = rgroup;
3990 	*out_poller = poller;
3991 
3992 	RB_INIT(&poller->qpairs);
3993 	STAILQ_INIT(&poller->qpairs_pending_send);
3994 	STAILQ_INIT(&poller->qpairs_pending_recv);
3995 
3996 	TAILQ_INSERT_TAIL(&rgroup->pollers, poller, link);
3997 	SPDK_DEBUGLOG(rdma, "Create poller %p on device %p in poll group %p.\n", poller, device, rgroup);
3998 	if (rtransport->rdma_opts.no_srq == false && device->num_srq < device->attr.max_srq) {
3999 		if ((int)rtransport->rdma_opts.max_srq_depth > device->attr.max_srq_wr) {
4000 			SPDK_WARNLOG("Requested SRQ depth %u, max supported by dev %s is %d\n",
4001 				     rtransport->rdma_opts.max_srq_depth, device->context->device->name, device->attr.max_srq_wr);
4002 		}
4003 		poller->max_srq_depth = spdk_min((int)rtransport->rdma_opts.max_srq_depth, device->attr.max_srq_wr);
4004 
4005 		device->num_srq++;
4006 		memset(&srq_init_attr, 0, sizeof(srq_init_attr));
4007 		srq_init_attr.pd = device->pd;
4008 		srq_init_attr.stats = &poller->stat.qp_stats.recv;
4009 		srq_init_attr.srq_init_attr.attr.max_wr = poller->max_srq_depth;
4010 		srq_init_attr.srq_init_attr.attr.max_sge = spdk_min(device->attr.max_sge, NVMF_DEFAULT_RX_SGE);
4011 		poller->srq = spdk_rdma_provider_srq_create(&srq_init_attr);
4012 		if (!poller->srq) {
4013 			SPDK_ERRLOG("Unable to create shared receive queue, errno %d\n", errno);
4014 			return -1;
4015 		}
4016 
4017 		opts.qp = poller->srq;
4018 		opts.map = device->map;
4019 		opts.qpair = NULL;
4020 		opts.shared = true;
4021 		opts.max_queue_depth = poller->max_srq_depth;
4022 		opts.in_capsule_data_size = rtransport->transport.opts.in_capsule_data_size;
4023 
4024 		poller->resources = nvmf_rdma_resources_create(&opts);
4025 		if (!poller->resources) {
4026 			SPDK_ERRLOG("Unable to allocate resources for shared receive queue.\n");
4027 			return -1;
4028 		}
4029 	}
4030 
4031 	/*
4032 	 * When using an srq, we can limit the completion queue at startup.
4033 	 * The following formula represents the calculation:
4034 	 * num_cqe = num_recv + num_data_wr + num_send_wr.
4035 	 * where num_recv=num_data_wr=and num_send_wr=poller->max_srq_depth
4036 	 */
4037 	if (poller->srq) {
4038 		num_cqe = poller->max_srq_depth * 3;
4039 	} else {
4040 		num_cqe = rtransport->rdma_opts.num_cqe;
4041 	}
4042 
4043 	poller->cq = ibv_create_cq(device->context, num_cqe, poller, NULL, 0);
4044 	if (!poller->cq) {
4045 		SPDK_ERRLOG("Unable to create completion queue\n");
4046 		return -1;
4047 	}
4048 	poller->num_cqe = num_cqe;
4049 	return 0;
4050 }
4051 
4052 static void
4053 _nvmf_rdma_register_poller_in_group(void *c)
4054 {
4055 	struct spdk_nvmf_rdma_poller	*poller;
4056 	struct poller_manage_ctx	*ctx = c;
4057 	struct spdk_nvmf_rdma_device	*device;
4058 	int				rc;
4059 
4060 	rc = nvmf_rdma_poller_create(ctx->rtransport, ctx->rgroup, ctx->device, &poller);
4061 	if (rc < 0 && poller) {
4062 		nvmf_rdma_poller_destroy(poller);
4063 	}
4064 
4065 	device = ctx->device;
4066 	if (nvmf_rdma_all_pollers_management_done(ctx)) {
4067 		device->is_ready = true;
4068 	}
4069 }
4070 
4071 static void nvmf_rdma_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group);
4072 
4073 static struct spdk_nvmf_transport_poll_group *
4074 nvmf_rdma_poll_group_create(struct spdk_nvmf_transport *transport,
4075 			    struct spdk_nvmf_poll_group *group)
4076 {
4077 	struct spdk_nvmf_rdma_transport		*rtransport;
4078 	struct spdk_nvmf_rdma_poll_group	*rgroup;
4079 	struct spdk_nvmf_rdma_poller		*poller;
4080 	struct spdk_nvmf_rdma_device		*device;
4081 	int					rc;
4082 
4083 	if (spdk_interrupt_mode_is_enabled()) {
4084 		SPDK_ERRLOG("RDMA transport does not support interrupt mode\n");
4085 		return NULL;
4086 	}
4087 
4088 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
4089 
4090 	rgroup = calloc(1, sizeof(*rgroup));
4091 	if (!rgroup) {
4092 		return NULL;
4093 	}
4094 
4095 	TAILQ_INIT(&rgroup->pollers);
4096 
4097 	TAILQ_FOREACH(device, &rtransport->devices, link) {
4098 		rc = nvmf_rdma_poller_create(rtransport, rgroup, device, &poller);
4099 		if (rc < 0) {
4100 			nvmf_rdma_poll_group_destroy(&rgroup->group);
4101 			return NULL;
4102 		}
4103 	}
4104 
4105 	TAILQ_INSERT_TAIL(&rtransport->poll_groups, rgroup, link);
4106 	if (rtransport->conn_sched.next_admin_pg == NULL) {
4107 		rtransport->conn_sched.next_admin_pg = rgroup;
4108 		rtransport->conn_sched.next_io_pg = rgroup;
4109 	}
4110 
4111 	return &rgroup->group;
4112 }
4113 
4114 static uint32_t
4115 nvmf_poll_group_get_io_qpair_count(struct spdk_nvmf_poll_group *pg)
4116 {
4117 	uint32_t count;
4118 
4119 	/* Just assume that unassociated qpairs will eventually be io
4120 	 * qpairs.  This is close enough for the use cases for this
4121 	 * function.
4122 	 */
4123 	pthread_mutex_lock(&pg->mutex);
4124 	count = pg->stat.current_io_qpairs + pg->current_unassociated_qpairs;
4125 	pthread_mutex_unlock(&pg->mutex);
4126 
4127 	return count;
4128 }
4129 
4130 static struct spdk_nvmf_transport_poll_group *
4131 nvmf_rdma_get_optimal_poll_group(struct spdk_nvmf_qpair *qpair)
4132 {
4133 	struct spdk_nvmf_rdma_transport *rtransport;
4134 	struct spdk_nvmf_rdma_poll_group **pg;
4135 	struct spdk_nvmf_transport_poll_group *result;
4136 	uint32_t count;
4137 
4138 	rtransport = SPDK_CONTAINEROF(qpair->transport, struct spdk_nvmf_rdma_transport, transport);
4139 
4140 	if (TAILQ_EMPTY(&rtransport->poll_groups)) {
4141 		return NULL;
4142 	}
4143 
4144 	if (qpair->qid == 0) {
4145 		pg = &rtransport->conn_sched.next_admin_pg;
4146 	} else {
4147 		struct spdk_nvmf_rdma_poll_group *pg_min, *pg_start, *pg_current;
4148 		uint32_t min_value;
4149 
4150 		pg = &rtransport->conn_sched.next_io_pg;
4151 		pg_min = *pg;
4152 		pg_start = *pg;
4153 		pg_current = *pg;
4154 		min_value = nvmf_poll_group_get_io_qpair_count(pg_current->group.group);
4155 
4156 		while (1) {
4157 			count = nvmf_poll_group_get_io_qpair_count(pg_current->group.group);
4158 
4159 			if (count < min_value) {
4160 				min_value = count;
4161 				pg_min = pg_current;
4162 			}
4163 
4164 			pg_current = TAILQ_NEXT(pg_current, link);
4165 			if (pg_current == NULL) {
4166 				pg_current = TAILQ_FIRST(&rtransport->poll_groups);
4167 			}
4168 
4169 			if (pg_current == pg_start || min_value == 0) {
4170 				break;
4171 			}
4172 		}
4173 		*pg = pg_min;
4174 	}
4175 
4176 	assert(*pg != NULL);
4177 
4178 	result = &(*pg)->group;
4179 
4180 	*pg = TAILQ_NEXT(*pg, link);
4181 	if (*pg == NULL) {
4182 		*pg = TAILQ_FIRST(&rtransport->poll_groups);
4183 	}
4184 
4185 	return result;
4186 }
4187 
4188 static void
4189 nvmf_rdma_poller_destroy(struct spdk_nvmf_rdma_poller *poller)
4190 {
4191 	struct spdk_nvmf_rdma_qpair	*qpair, *tmp_qpair;
4192 	int				rc;
4193 
4194 	TAILQ_REMOVE(&poller->group->pollers, poller, link);
4195 	RB_FOREACH_SAFE(qpair, qpairs_tree, &poller->qpairs, tmp_qpair) {
4196 		nvmf_rdma_qpair_destroy(qpair);
4197 	}
4198 
4199 	if (poller->srq) {
4200 		if (poller->resources) {
4201 			nvmf_rdma_resources_destroy(poller->resources);
4202 		}
4203 		spdk_rdma_provider_srq_destroy(poller->srq);
4204 		SPDK_DEBUGLOG(rdma, "Destroyed RDMA shared queue %p\n", poller->srq);
4205 	}
4206 
4207 	if (poller->cq) {
4208 		rc = ibv_destroy_cq(poller->cq);
4209 		if (rc != 0) {
4210 			SPDK_ERRLOG("Destroy cq return %d, error: %s\n", rc, strerror(errno));
4211 		}
4212 	}
4213 
4214 	if (poller->destroy_cb) {
4215 		poller->destroy_cb(poller->destroy_cb_ctx);
4216 		poller->destroy_cb = NULL;
4217 	}
4218 
4219 	free(poller);
4220 }
4221 
4222 static void
4223 nvmf_rdma_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group)
4224 {
4225 	struct spdk_nvmf_rdma_poll_group	*rgroup, *next_rgroup;
4226 	struct spdk_nvmf_rdma_poller		*poller, *tmp;
4227 	struct spdk_nvmf_rdma_transport		*rtransport;
4228 
4229 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
4230 	if (!rgroup) {
4231 		return;
4232 	}
4233 
4234 	TAILQ_FOREACH_SAFE(poller, &rgroup->pollers, link, tmp) {
4235 		nvmf_rdma_poller_destroy(poller);
4236 	}
4237 
4238 	if (rgroup->group.transport == NULL) {
4239 		/* Transport can be NULL when nvmf_rdma_poll_group_create()
4240 		 * calls this function directly in a failure path. */
4241 		free(rgroup);
4242 		return;
4243 	}
4244 
4245 	rtransport = SPDK_CONTAINEROF(rgroup->group.transport, struct spdk_nvmf_rdma_transport, transport);
4246 
4247 	next_rgroup = TAILQ_NEXT(rgroup, link);
4248 	TAILQ_REMOVE(&rtransport->poll_groups, rgroup, link);
4249 	if (next_rgroup == NULL) {
4250 		next_rgroup = TAILQ_FIRST(&rtransport->poll_groups);
4251 	}
4252 	if (rtransport->conn_sched.next_admin_pg == rgroup) {
4253 		rtransport->conn_sched.next_admin_pg = next_rgroup;
4254 	}
4255 	if (rtransport->conn_sched.next_io_pg == rgroup) {
4256 		rtransport->conn_sched.next_io_pg = next_rgroup;
4257 	}
4258 
4259 	free(rgroup);
4260 }
4261 
4262 static void
4263 nvmf_rdma_qpair_reject_connection(struct spdk_nvmf_rdma_qpair *rqpair)
4264 {
4265 	if (rqpair->cm_id != NULL) {
4266 		nvmf_rdma_event_reject(rqpair->cm_id, SPDK_NVMF_RDMA_ERROR_NO_RESOURCES);
4267 	}
4268 }
4269 
4270 static int
4271 nvmf_rdma_poll_group_add(struct spdk_nvmf_transport_poll_group *group,
4272 			 struct spdk_nvmf_qpair *qpair)
4273 {
4274 	struct spdk_nvmf_rdma_poll_group	*rgroup;
4275 	struct spdk_nvmf_rdma_qpair		*rqpair;
4276 	struct spdk_nvmf_rdma_device		*device;
4277 	struct spdk_nvmf_rdma_poller		*poller;
4278 	int					rc;
4279 
4280 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
4281 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4282 
4283 	device = rqpair->device;
4284 
4285 	TAILQ_FOREACH(poller, &rgroup->pollers, link) {
4286 		if (poller->device == device) {
4287 			break;
4288 		}
4289 	}
4290 
4291 	if (!poller) {
4292 		SPDK_ERRLOG("No poller found for device.\n");
4293 		return -1;
4294 	}
4295 
4296 	if (poller->need_destroy) {
4297 		SPDK_ERRLOG("Poller is destroying.\n");
4298 		return -1;
4299 	}
4300 
4301 	rqpair->poller = poller;
4302 	rqpair->srq = rqpair->poller->srq;
4303 
4304 	rc = nvmf_rdma_qpair_initialize(qpair);
4305 	if (rc < 0) {
4306 		SPDK_ERRLOG("Failed to initialize nvmf_rdma_qpair with qpair=%p\n", qpair);
4307 		rqpair->poller = NULL;
4308 		rqpair->srq = NULL;
4309 		return -1;
4310 	}
4311 
4312 	RB_INSERT(qpairs_tree, &poller->qpairs, rqpair);
4313 
4314 	rc = nvmf_rdma_event_accept(rqpair->cm_id, rqpair);
4315 	if (rc) {
4316 		/* Try to reject, but we probably can't */
4317 		nvmf_rdma_qpair_reject_connection(rqpair);
4318 		return -1;
4319 	}
4320 
4321 	return 0;
4322 }
4323 
4324 static int
4325 nvmf_rdma_poll_group_remove(struct spdk_nvmf_transport_poll_group *group,
4326 			    struct spdk_nvmf_qpair *qpair)
4327 {
4328 	struct spdk_nvmf_rdma_qpair		*rqpair;
4329 
4330 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4331 	assert(group->transport->tgt != NULL);
4332 
4333 	rqpair->destruct_channel = spdk_get_io_channel(group->transport->tgt);
4334 
4335 	if (!rqpair->destruct_channel) {
4336 		SPDK_WARNLOG("failed to get io_channel, qpair %p\n", qpair);
4337 		return 0;
4338 	}
4339 
4340 	/* Sanity check that we get io_channel on the correct thread */
4341 	if (qpair->group) {
4342 		assert(qpair->group->thread == spdk_io_channel_get_thread(rqpair->destruct_channel));
4343 	}
4344 
4345 	return 0;
4346 }
4347 
4348 static int
4349 nvmf_rdma_request_free(struct spdk_nvmf_request *req)
4350 {
4351 	struct spdk_nvmf_rdma_request	*rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
4352 	struct spdk_nvmf_rdma_transport	*rtransport = SPDK_CONTAINEROF(req->qpair->transport,
4353 			struct spdk_nvmf_rdma_transport, transport);
4354 	struct spdk_nvmf_rdma_qpair *rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair,
4355 					      struct spdk_nvmf_rdma_qpair, qpair);
4356 
4357 	/*
4358 	 * AER requests are freed when a qpair is destroyed. The recv corresponding to that request
4359 	 * needs to be returned to the shared receive queue or the poll group will eventually be
4360 	 * starved of RECV structures.
4361 	 */
4362 	if (rqpair->srq && rdma_req->recv) {
4363 		int rc;
4364 		struct ibv_recv_wr *bad_recv_wr;
4365 
4366 		spdk_rdma_provider_srq_queue_recv_wrs(rqpair->srq, &rdma_req->recv->wr);
4367 		rc = spdk_rdma_provider_srq_flush_recv_wrs(rqpair->srq, &bad_recv_wr);
4368 		if (rc) {
4369 			SPDK_ERRLOG("Unable to re-post rx descriptor\n");
4370 		}
4371 	}
4372 
4373 	_nvmf_rdma_request_free(rdma_req, rtransport);
4374 	return 0;
4375 }
4376 
4377 static int
4378 nvmf_rdma_request_complete(struct spdk_nvmf_request *req)
4379 {
4380 	struct spdk_nvmf_rdma_transport	*rtransport = SPDK_CONTAINEROF(req->qpair->transport,
4381 			struct spdk_nvmf_rdma_transport, transport);
4382 	struct spdk_nvmf_rdma_request	*rdma_req = SPDK_CONTAINEROF(req,
4383 			struct spdk_nvmf_rdma_request, req);
4384 	struct spdk_nvmf_rdma_qpair     *rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair,
4385 			struct spdk_nvmf_rdma_qpair, qpair);
4386 
4387 	if (spdk_unlikely(rqpair->ibv_in_error_state)) {
4388 		/* The connection is dead. Move the request directly to the completed state. */
4389 		rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
4390 	} else {
4391 		/* The connection is alive, so process the request as normal */
4392 		rdma_req->state = RDMA_REQUEST_STATE_EXECUTED;
4393 	}
4394 
4395 	nvmf_rdma_request_process(rtransport, rdma_req);
4396 
4397 	return 0;
4398 }
4399 
4400 static void
4401 nvmf_rdma_close_qpair(struct spdk_nvmf_qpair *qpair,
4402 		      spdk_nvmf_transport_qpair_fini_cb cb_fn, void *cb_arg)
4403 {
4404 	struct spdk_nvmf_rdma_qpair *rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4405 
4406 	rqpair->to_close = true;
4407 
4408 	/* This happens only when the qpair is disconnected before
4409 	 * it is added to the poll group. Since there is no poll group,
4410 	 * the RDMA qp has not been initialized yet and the RDMA CM
4411 	 * event has not yet been acknowledged, so we need to reject it.
4412 	 */
4413 	if (rqpair->qpair.state == SPDK_NVMF_QPAIR_UNINITIALIZED) {
4414 		nvmf_rdma_qpair_reject_connection(rqpair);
4415 		nvmf_rdma_qpair_destroy(rqpair);
4416 		return;
4417 	}
4418 
4419 	if (rqpair->rdma_qp) {
4420 		spdk_rdma_provider_qp_disconnect(rqpair->rdma_qp);
4421 	}
4422 
4423 	nvmf_rdma_destroy_drained_qpair(rqpair);
4424 
4425 	if (cb_fn) {
4426 		cb_fn(cb_arg);
4427 	}
4428 }
4429 
4430 static struct spdk_nvmf_rdma_qpair *
4431 get_rdma_qpair_from_wc(struct spdk_nvmf_rdma_poller *rpoller, struct ibv_wc *wc)
4432 {
4433 	struct spdk_nvmf_rdma_qpair find;
4434 
4435 	find.qp_num = wc->qp_num;
4436 
4437 	return RB_FIND(qpairs_tree, &rpoller->qpairs, &find);
4438 }
4439 
4440 #ifdef DEBUG
4441 static int
4442 nvmf_rdma_req_is_completing(struct spdk_nvmf_rdma_request *rdma_req)
4443 {
4444 	return rdma_req->state == RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST ||
4445 	       rdma_req->state == RDMA_REQUEST_STATE_COMPLETING;
4446 }
4447 #endif
4448 
4449 static void
4450 _poller_reset_failed_recvs(struct spdk_nvmf_rdma_poller *rpoller, struct ibv_recv_wr *bad_recv_wr,
4451 			   int rc)
4452 {
4453 	struct spdk_nvmf_rdma_recv	*rdma_recv;
4454 	struct spdk_nvmf_rdma_wr	*bad_rdma_wr;
4455 
4456 	SPDK_ERRLOG("Failed to post a recv for the poller %p with errno %d\n", rpoller, -rc);
4457 	while (bad_recv_wr != NULL) {
4458 		bad_rdma_wr = (struct spdk_nvmf_rdma_wr *)bad_recv_wr->wr_id;
4459 		rdma_recv = SPDK_CONTAINEROF(bad_rdma_wr, struct spdk_nvmf_rdma_recv, rdma_wr);
4460 
4461 		rdma_recv->qpair->current_recv_depth++;
4462 		bad_recv_wr = bad_recv_wr->next;
4463 		SPDK_ERRLOG("Failed to post a recv for the qpair %p with errno %d\n", rdma_recv->qpair, -rc);
4464 		spdk_nvmf_qpair_disconnect(&rdma_recv->qpair->qpair);
4465 	}
4466 }
4467 
4468 static void
4469 _qp_reset_failed_recvs(struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_recv_wr *bad_recv_wr, int rc)
4470 {
4471 	SPDK_ERRLOG("Failed to post a recv for the qpair %p with errno %d\n", rqpair, -rc);
4472 	while (bad_recv_wr != NULL) {
4473 		bad_recv_wr = bad_recv_wr->next;
4474 		rqpair->current_recv_depth++;
4475 	}
4476 	spdk_nvmf_qpair_disconnect(&rqpair->qpair);
4477 }
4478 
4479 static void
4480 _poller_submit_recvs(struct spdk_nvmf_rdma_transport *rtransport,
4481 		     struct spdk_nvmf_rdma_poller *rpoller)
4482 {
4483 	struct spdk_nvmf_rdma_qpair	*rqpair;
4484 	struct ibv_recv_wr		*bad_recv_wr;
4485 	int				rc;
4486 
4487 	if (rpoller->srq) {
4488 		rc = spdk_rdma_provider_srq_flush_recv_wrs(rpoller->srq, &bad_recv_wr);
4489 		if (spdk_unlikely(rc)) {
4490 			_poller_reset_failed_recvs(rpoller, bad_recv_wr, rc);
4491 		}
4492 	} else {
4493 		while (!STAILQ_EMPTY(&rpoller->qpairs_pending_recv)) {
4494 			rqpair = STAILQ_FIRST(&rpoller->qpairs_pending_recv);
4495 			rc = spdk_rdma_provider_qp_flush_recv_wrs(rqpair->rdma_qp, &bad_recv_wr);
4496 			if (spdk_unlikely(rc)) {
4497 				_qp_reset_failed_recvs(rqpair, bad_recv_wr, rc);
4498 			}
4499 			STAILQ_REMOVE_HEAD(&rpoller->qpairs_pending_recv, recv_link);
4500 		}
4501 	}
4502 }
4503 
4504 static void
4505 _qp_reset_failed_sends(struct spdk_nvmf_rdma_transport *rtransport,
4506 		       struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_send_wr *bad_wr, int rc)
4507 {
4508 	struct spdk_nvmf_rdma_wr	*bad_rdma_wr;
4509 	struct spdk_nvmf_rdma_request	*prev_rdma_req = NULL, *cur_rdma_req = NULL;
4510 
4511 	SPDK_ERRLOG("Failed to post a send for the qpair %p with errno %d\n", rqpair, -rc);
4512 	for (; bad_wr != NULL; bad_wr = bad_wr->next) {
4513 		bad_rdma_wr = (struct spdk_nvmf_rdma_wr *)bad_wr->wr_id;
4514 		assert(rqpair->current_send_depth > 0);
4515 		rqpair->current_send_depth--;
4516 		switch (bad_rdma_wr->type) {
4517 		case RDMA_WR_TYPE_DATA:
4518 			cur_rdma_req = SPDK_CONTAINEROF(bad_rdma_wr, struct spdk_nvmf_rdma_request, data_wr);
4519 			if (bad_wr->opcode == IBV_WR_RDMA_READ) {
4520 				assert(rqpair->current_read_depth > 0);
4521 				rqpair->current_read_depth--;
4522 			}
4523 			break;
4524 		case RDMA_WR_TYPE_SEND:
4525 			cur_rdma_req = SPDK_CONTAINEROF(bad_rdma_wr, struct spdk_nvmf_rdma_request, rsp_wr);
4526 			break;
4527 		default:
4528 			SPDK_ERRLOG("Found a RECV in the list of pending SEND requests for qpair %p\n", rqpair);
4529 			prev_rdma_req = cur_rdma_req;
4530 			continue;
4531 		}
4532 
4533 		if (prev_rdma_req == cur_rdma_req) {
4534 			/* this request was handled by an earlier wr. i.e. we were performing an nvme read. */
4535 			/* We only have to check against prev_wr since each requests wrs are contiguous in this list. */
4536 			continue;
4537 		}
4538 
4539 		switch (cur_rdma_req->state) {
4540 		case RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER:
4541 			cur_rdma_req->req.rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
4542 			STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, cur_rdma_req, state_link);
4543 			cur_rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
4544 			break;
4545 		case RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST:
4546 		case RDMA_REQUEST_STATE_COMPLETING:
4547 			cur_rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
4548 			break;
4549 		default:
4550 			SPDK_ERRLOG("Found a request in a bad state %d when draining pending SEND requests for qpair %p\n",
4551 				    cur_rdma_req->state, rqpair);
4552 			continue;
4553 		}
4554 
4555 		nvmf_rdma_request_process(rtransport, cur_rdma_req);
4556 		prev_rdma_req = cur_rdma_req;
4557 	}
4558 
4559 	if (spdk_nvmf_qpair_is_active(&rqpair->qpair)) {
4560 		/* Disconnect the connection. */
4561 		spdk_nvmf_qpair_disconnect(&rqpair->qpair);
4562 	}
4563 
4564 }
4565 
4566 static void
4567 _poller_submit_sends(struct spdk_nvmf_rdma_transport *rtransport,
4568 		     struct spdk_nvmf_rdma_poller *rpoller)
4569 {
4570 	struct spdk_nvmf_rdma_qpair	*rqpair;
4571 	struct ibv_send_wr		*bad_wr = NULL;
4572 	int				rc;
4573 
4574 	while (!STAILQ_EMPTY(&rpoller->qpairs_pending_send)) {
4575 		rqpair = STAILQ_FIRST(&rpoller->qpairs_pending_send);
4576 		rc = spdk_rdma_provider_qp_flush_send_wrs(rqpair->rdma_qp, &bad_wr);
4577 
4578 		/* bad wr always points to the first wr that failed. */
4579 		if (spdk_unlikely(rc)) {
4580 			_qp_reset_failed_sends(rtransport, rqpair, bad_wr, rc);
4581 		}
4582 		STAILQ_REMOVE_HEAD(&rpoller->qpairs_pending_send, send_link);
4583 	}
4584 }
4585 
4586 static const char *
4587 nvmf_rdma_wr_type_str(enum spdk_nvmf_rdma_wr_type wr_type)
4588 {
4589 	switch (wr_type) {
4590 	case RDMA_WR_TYPE_RECV:
4591 		return "RECV";
4592 	case RDMA_WR_TYPE_SEND:
4593 		return "SEND";
4594 	case RDMA_WR_TYPE_DATA:
4595 		return "DATA";
4596 	default:
4597 		SPDK_ERRLOG("Unknown WR type %d\n", wr_type);
4598 		SPDK_UNREACHABLE();
4599 	}
4600 }
4601 
4602 static inline void
4603 nvmf_rdma_log_wc_status(struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_wc *wc)
4604 {
4605 	enum spdk_nvmf_rdma_wr_type wr_type = ((struct spdk_nvmf_rdma_wr *)wc->wr_id)->type;
4606 
4607 	if (wc->status == IBV_WC_WR_FLUSH_ERR) {
4608 		/* If qpair is in ERR state, we will receive completions for all posted and not completed
4609 		 * Work Requests with IBV_WC_WR_FLUSH_ERR status. Don't log an error in that case */
4610 		SPDK_DEBUGLOG(rdma,
4611 			      "Error on CQ %p, (qp state %d, in_error %d) request 0x%lu, type %s, status: (%d): %s\n",
4612 			      rqpair->poller->cq, rqpair->qpair.state, rqpair->ibv_in_error_state, wc->wr_id,
4613 			      nvmf_rdma_wr_type_str(wr_type), wc->status, ibv_wc_status_str(wc->status));
4614 	} else {
4615 		SPDK_ERRLOG("Error on CQ %p, (qp state %d, in_error %d) request 0x%lu, type %s, status: (%d): %s\n",
4616 			    rqpair->poller->cq, rqpair->qpair.state, rqpair->ibv_in_error_state, wc->wr_id,
4617 			    nvmf_rdma_wr_type_str(wr_type), wc->status, ibv_wc_status_str(wc->status));
4618 	}
4619 }
4620 
4621 static int
4622 nvmf_rdma_poller_poll(struct spdk_nvmf_rdma_transport *rtransport,
4623 		      struct spdk_nvmf_rdma_poller *rpoller)
4624 {
4625 	struct ibv_wc wc[32];
4626 	struct spdk_nvmf_rdma_wr	*rdma_wr;
4627 	struct spdk_nvmf_rdma_request	*rdma_req;
4628 	struct spdk_nvmf_rdma_recv	*rdma_recv;
4629 	struct spdk_nvmf_rdma_qpair	*rqpair, *tmp_rqpair;
4630 	int reaped, i;
4631 	int count = 0;
4632 	int rc;
4633 	bool error = false;
4634 	uint64_t poll_tsc = spdk_get_ticks();
4635 
4636 	if (spdk_unlikely(rpoller->need_destroy)) {
4637 		/* If qpair is closed before poller destroy, nvmf_rdma_destroy_drained_qpair may not
4638 		 * be called because we cannot poll anything from cq. So we call that here to force
4639 		 * destroy the qpair after to_close turning true.
4640 		 */
4641 		RB_FOREACH_SAFE(rqpair, qpairs_tree, &rpoller->qpairs, tmp_rqpair) {
4642 			nvmf_rdma_destroy_drained_qpair(rqpair);
4643 		}
4644 		return 0;
4645 	}
4646 
4647 	/* Poll for completing operations. */
4648 	reaped = ibv_poll_cq(rpoller->cq, 32, wc);
4649 	if (spdk_unlikely(reaped < 0)) {
4650 		SPDK_ERRLOG("Error polling CQ! (%d): %s\n",
4651 			    errno, spdk_strerror(errno));
4652 		return -1;
4653 	} else if (reaped == 0) {
4654 		rpoller->stat.idle_polls++;
4655 	}
4656 
4657 	rpoller->stat.polls++;
4658 	rpoller->stat.completions += reaped;
4659 
4660 	for (i = 0; i < reaped; i++) {
4661 
4662 		rdma_wr = (struct spdk_nvmf_rdma_wr *)wc[i].wr_id;
4663 
4664 		switch (rdma_wr->type) {
4665 		case RDMA_WR_TYPE_SEND:
4666 			rdma_req = SPDK_CONTAINEROF(rdma_wr, struct spdk_nvmf_rdma_request, rsp_wr);
4667 			rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
4668 
4669 			if (spdk_likely(!wc[i].status)) {
4670 				count++;
4671 				assert(wc[i].opcode == IBV_WC_SEND);
4672 				assert(nvmf_rdma_req_is_completing(rdma_req));
4673 			}
4674 
4675 			rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
4676 			/* RDMA_WRITE operation completed. +1 since it was chained with rsp WR */
4677 			assert(rqpair->current_send_depth >= (uint32_t)rdma_req->num_outstanding_data_wr + 1);
4678 			rqpair->current_send_depth -= rdma_req->num_outstanding_data_wr + 1;
4679 			rdma_req->num_outstanding_data_wr = 0;
4680 
4681 			nvmf_rdma_request_process(rtransport, rdma_req);
4682 			break;
4683 		case RDMA_WR_TYPE_RECV:
4684 			/* rdma_recv->qpair will be invalid if using an SRQ.  In that case we have to get the qpair from the wc. */
4685 			rdma_recv = SPDK_CONTAINEROF(rdma_wr, struct spdk_nvmf_rdma_recv, rdma_wr);
4686 			if (rpoller->srq != NULL) {
4687 				rdma_recv->qpair = get_rdma_qpair_from_wc(rpoller, &wc[i]);
4688 				/* It is possible that there are still some completions for destroyed QP
4689 				 * associated with SRQ. We just ignore these late completions and re-post
4690 				 * receive WRs back to SRQ.
4691 				 */
4692 				if (spdk_unlikely(NULL == rdma_recv->qpair)) {
4693 					struct ibv_recv_wr *bad_wr;
4694 
4695 					rdma_recv->wr.next = NULL;
4696 					spdk_rdma_provider_srq_queue_recv_wrs(rpoller->srq, &rdma_recv->wr);
4697 					rc = spdk_rdma_provider_srq_flush_recv_wrs(rpoller->srq, &bad_wr);
4698 					if (rc) {
4699 						SPDK_ERRLOG("Failed to re-post recv WR to SRQ, err %d\n", rc);
4700 					}
4701 					continue;
4702 				}
4703 			}
4704 			rqpair = rdma_recv->qpair;
4705 
4706 			assert(rqpair != NULL);
4707 			if (spdk_likely(!wc[i].status)) {
4708 				assert(wc[i].opcode == IBV_WC_RECV);
4709 				if (rqpair->current_recv_depth >= rqpair->max_queue_depth) {
4710 					spdk_nvmf_qpair_disconnect(&rqpair->qpair);
4711 					break;
4712 				}
4713 			}
4714 
4715 			rdma_recv->wr.next = NULL;
4716 			rqpair->current_recv_depth++;
4717 			rdma_recv->receive_tsc = poll_tsc;
4718 			rpoller->stat.requests++;
4719 			STAILQ_INSERT_HEAD(&rqpair->resources->incoming_queue, rdma_recv, link);
4720 			rqpair->qpair.queue_depth++;
4721 			break;
4722 		case RDMA_WR_TYPE_DATA:
4723 			rdma_req = SPDK_CONTAINEROF(rdma_wr, struct spdk_nvmf_rdma_request, data_wr);
4724 			rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
4725 
4726 			assert(rdma_req->num_outstanding_data_wr > 0);
4727 
4728 			rqpair->current_send_depth--;
4729 			rdma_req->num_outstanding_data_wr--;
4730 			if (spdk_likely(!wc[i].status)) {
4731 				assert(wc[i].opcode == IBV_WC_RDMA_READ);
4732 				rqpair->current_read_depth--;
4733 				/* wait for all outstanding reads associated with the same rdma_req to complete before proceeding. */
4734 				if (rdma_req->num_outstanding_data_wr == 0) {
4735 					if (rdma_req->num_remaining_data_wr) {
4736 						/* Only part of RDMA_READ operations was submitted, process the rest */
4737 						nvmf_rdma_request_reset_transfer_in(rdma_req, rtransport);
4738 						rdma_req->state = RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING;
4739 						nvmf_rdma_request_process(rtransport, rdma_req);
4740 						break;
4741 					}
4742 					rdma_req->state = RDMA_REQUEST_STATE_READY_TO_EXECUTE;
4743 					nvmf_rdma_request_process(rtransport, rdma_req);
4744 				}
4745 			} else {
4746 				/* If the data transfer fails still force the queue into the error state,
4747 				 * if we were performing an RDMA_READ, we need to force the request into a
4748 				 * completed state since it wasn't linked to a send. However, in the RDMA_WRITE
4749 				 * case, we should wait for the SEND to complete. */
4750 				if (rdma_req->data.wr.opcode == IBV_WR_RDMA_READ) {
4751 					rqpair->current_read_depth--;
4752 					if (rdma_req->num_outstanding_data_wr == 0) {
4753 						rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
4754 					}
4755 				}
4756 			}
4757 			break;
4758 		default:
4759 			SPDK_ERRLOG("Received an unknown opcode on the CQ: %d\n", wc[i].opcode);
4760 			continue;
4761 		}
4762 
4763 		/* Handle error conditions */
4764 		if (spdk_unlikely(wc[i].status)) {
4765 			rqpair->ibv_in_error_state = true;
4766 			nvmf_rdma_log_wc_status(rqpair, &wc[i]);
4767 
4768 			error = true;
4769 
4770 			if (spdk_nvmf_qpair_is_active(&rqpair->qpair)) {
4771 				/* Disconnect the connection. */
4772 				spdk_nvmf_qpair_disconnect(&rqpair->qpair);
4773 			} else {
4774 				nvmf_rdma_destroy_drained_qpair(rqpair);
4775 			}
4776 			continue;
4777 		}
4778 
4779 		nvmf_rdma_qpair_process_pending(rtransport, rqpair, false);
4780 
4781 		if (spdk_unlikely(!spdk_nvmf_qpair_is_active(&rqpair->qpair))) {
4782 			nvmf_rdma_destroy_drained_qpair(rqpair);
4783 		}
4784 	}
4785 
4786 	if (spdk_unlikely(error == true)) {
4787 		return -1;
4788 	}
4789 
4790 	if (reaped == 0) {
4791 		/* In some cases we may not receive any CQE but we still may have pending IO requests waiting for
4792 		 * a resource (e.g. a WR from the data_wr_pool).
4793 		 * We need to start processing of such requests if no CQE reaped */
4794 		nvmf_rdma_poller_process_pending_buf_queue(rtransport, rpoller);
4795 	}
4796 
4797 	/* submit outstanding work requests. */
4798 	_poller_submit_recvs(rtransport, rpoller);
4799 	_poller_submit_sends(rtransport, rpoller);
4800 
4801 	return count;
4802 }
4803 
4804 static void
4805 _nvmf_rdma_remove_destroyed_device(void *c)
4806 {
4807 	struct spdk_nvmf_rdma_transport	*rtransport = c;
4808 	struct spdk_nvmf_rdma_device	*device, *device_tmp;
4809 	int				rc;
4810 
4811 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, device_tmp) {
4812 		if (device->ready_to_destroy) {
4813 			destroy_ib_device(rtransport, device);
4814 		}
4815 	}
4816 
4817 	free_poll_fds(rtransport);
4818 	rc = generate_poll_fds(rtransport);
4819 	/* cannot handle fd allocation error here */
4820 	if (rc != 0) {
4821 		SPDK_ERRLOG("Failed to generate poll fds after remove ib device.\n");
4822 	}
4823 }
4824 
4825 static void
4826 _nvmf_rdma_remove_poller_in_group_cb(void *c)
4827 {
4828 	struct poller_manage_ctx	*ctx = c;
4829 	struct spdk_nvmf_rdma_transport	*rtransport = ctx->rtransport;
4830 	struct spdk_nvmf_rdma_device	*device = ctx->device;
4831 	struct spdk_thread		*thread = ctx->thread;
4832 
4833 	if (nvmf_rdma_all_pollers_management_done(c)) {
4834 		/* destroy device when last poller is destroyed */
4835 		device->ready_to_destroy = true;
4836 		spdk_thread_send_msg(thread, _nvmf_rdma_remove_destroyed_device, rtransport);
4837 	}
4838 }
4839 
4840 static void
4841 _nvmf_rdma_remove_poller_in_group(void *c)
4842 {
4843 	struct poller_manage_ctx		*ctx = c;
4844 
4845 	ctx->rpoller->need_destroy = true;
4846 	ctx->rpoller->destroy_cb_ctx = ctx;
4847 	ctx->rpoller->destroy_cb = _nvmf_rdma_remove_poller_in_group_cb;
4848 
4849 	/* qp will be disconnected after receiving a RDMA_CM_EVENT_DEVICE_REMOVAL event. */
4850 	if (RB_EMPTY(&ctx->rpoller->qpairs)) {
4851 		nvmf_rdma_poller_destroy(ctx->rpoller);
4852 	}
4853 }
4854 
4855 static int
4856 nvmf_rdma_poll_group_poll(struct spdk_nvmf_transport_poll_group *group)
4857 {
4858 	struct spdk_nvmf_rdma_transport *rtransport;
4859 	struct spdk_nvmf_rdma_poll_group *rgroup;
4860 	struct spdk_nvmf_rdma_poller	*rpoller, *tmp;
4861 	int				count = 0, rc, rc2 = 0;
4862 
4863 	rtransport = SPDK_CONTAINEROF(group->transport, struct spdk_nvmf_rdma_transport, transport);
4864 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
4865 
4866 	TAILQ_FOREACH_SAFE(rpoller, &rgroup->pollers, link, tmp) {
4867 		rc = nvmf_rdma_poller_poll(rtransport, rpoller);
4868 		if (spdk_unlikely(rc < 0)) {
4869 			if (rc2 == 0) {
4870 				rc2 = rc;
4871 			}
4872 			continue;
4873 		}
4874 		count += rc;
4875 	}
4876 
4877 	return rc2 ? rc2 : count;
4878 }
4879 
4880 static int
4881 nvmf_rdma_trid_from_cm_id(struct rdma_cm_id *id,
4882 			  struct spdk_nvme_transport_id *trid,
4883 			  bool peer)
4884 {
4885 	struct sockaddr *saddr;
4886 	uint16_t port;
4887 
4888 	spdk_nvme_trid_populate_transport(trid, SPDK_NVME_TRANSPORT_RDMA);
4889 
4890 	if (peer) {
4891 		saddr = rdma_get_peer_addr(id);
4892 	} else {
4893 		saddr = rdma_get_local_addr(id);
4894 	}
4895 	switch (saddr->sa_family) {
4896 	case AF_INET: {
4897 		struct sockaddr_in *saddr_in = (struct sockaddr_in *)saddr;
4898 
4899 		trid->adrfam = SPDK_NVMF_ADRFAM_IPV4;
4900 		inet_ntop(AF_INET, &saddr_in->sin_addr,
4901 			  trid->traddr, sizeof(trid->traddr));
4902 		if (peer) {
4903 			port = ntohs(rdma_get_dst_port(id));
4904 		} else {
4905 			port = ntohs(rdma_get_src_port(id));
4906 		}
4907 		snprintf(trid->trsvcid, sizeof(trid->trsvcid), "%u", port);
4908 		break;
4909 	}
4910 	case AF_INET6: {
4911 		struct sockaddr_in6 *saddr_in = (struct sockaddr_in6 *)saddr;
4912 		trid->adrfam = SPDK_NVMF_ADRFAM_IPV6;
4913 		inet_ntop(AF_INET6, &saddr_in->sin6_addr,
4914 			  trid->traddr, sizeof(trid->traddr));
4915 		if (peer) {
4916 			port = ntohs(rdma_get_dst_port(id));
4917 		} else {
4918 			port = ntohs(rdma_get_src_port(id));
4919 		}
4920 		snprintf(trid->trsvcid, sizeof(trid->trsvcid), "%u", port);
4921 		break;
4922 	}
4923 	default:
4924 		return -1;
4925 
4926 	}
4927 
4928 	return 0;
4929 }
4930 
4931 static int
4932 nvmf_rdma_qpair_get_peer_trid(struct spdk_nvmf_qpair *qpair,
4933 			      struct spdk_nvme_transport_id *trid)
4934 {
4935 	struct spdk_nvmf_rdma_qpair	*rqpair;
4936 
4937 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4938 
4939 	return nvmf_rdma_trid_from_cm_id(rqpair->cm_id, trid, true);
4940 }
4941 
4942 static int
4943 nvmf_rdma_qpair_get_local_trid(struct spdk_nvmf_qpair *qpair,
4944 			       struct spdk_nvme_transport_id *trid)
4945 {
4946 	struct spdk_nvmf_rdma_qpair	*rqpair;
4947 
4948 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4949 
4950 	return nvmf_rdma_trid_from_cm_id(rqpair->cm_id, trid, false);
4951 }
4952 
4953 static int
4954 nvmf_rdma_qpair_get_listen_trid(struct spdk_nvmf_qpair *qpair,
4955 				struct spdk_nvme_transport_id *trid)
4956 {
4957 	struct spdk_nvmf_rdma_qpair	*rqpair;
4958 
4959 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4960 
4961 	return nvmf_rdma_trid_from_cm_id(rqpair->listen_id, trid, false);
4962 }
4963 
4964 void
4965 spdk_nvmf_rdma_init_hooks(struct spdk_nvme_rdma_hooks *hooks)
4966 {
4967 	g_nvmf_hooks = *hooks;
4968 }
4969 
4970 static void
4971 nvmf_rdma_request_set_abort_status(struct spdk_nvmf_request *req,
4972 				   struct spdk_nvmf_rdma_request *rdma_req_to_abort,
4973 				   struct spdk_nvmf_rdma_qpair *rqpair)
4974 {
4975 	rdma_req_to_abort->req.rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4976 	rdma_req_to_abort->req.rsp->nvme_cpl.status.sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
4977 
4978 	STAILQ_INSERT_TAIL(&rqpair->pending_rdma_send_queue, rdma_req_to_abort, state_link);
4979 	rdma_req_to_abort->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING;
4980 
4981 	req->rsp->nvme_cpl.cdw0 &= ~1U;	/* Command was successfully aborted. */
4982 }
4983 
4984 static int
4985 _nvmf_rdma_qpair_abort_request(void *ctx)
4986 {
4987 	struct spdk_nvmf_request *req = ctx;
4988 	struct spdk_nvmf_rdma_request *rdma_req_to_abort = SPDK_CONTAINEROF(
4989 				req->req_to_abort, struct spdk_nvmf_rdma_request, req);
4990 	struct spdk_nvmf_rdma_qpair *rqpair = SPDK_CONTAINEROF(req->req_to_abort->qpair,
4991 					      struct spdk_nvmf_rdma_qpair, qpair);
4992 	int rc;
4993 
4994 	spdk_poller_unregister(&req->poller);
4995 
4996 	switch (rdma_req_to_abort->state) {
4997 	case RDMA_REQUEST_STATE_EXECUTING:
4998 		rc = nvmf_ctrlr_abort_request(req);
4999 		if (rc == SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS) {
5000 			return SPDK_POLLER_BUSY;
5001 		}
5002 		break;
5003 
5004 	case RDMA_REQUEST_STATE_NEED_BUFFER:
5005 		STAILQ_REMOVE(&rqpair->poller->group->group.pending_buf_queue,
5006 			      &rdma_req_to_abort->req, spdk_nvmf_request, buf_link);
5007 
5008 		nvmf_rdma_request_set_abort_status(req, rdma_req_to_abort, rqpair);
5009 		break;
5010 
5011 	case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING:
5012 		STAILQ_REMOVE(&rqpair->pending_rdma_read_queue, rdma_req_to_abort,
5013 			      spdk_nvmf_rdma_request, state_link);
5014 
5015 		nvmf_rdma_request_set_abort_status(req, rdma_req_to_abort, rqpair);
5016 		break;
5017 
5018 	case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING:
5019 		STAILQ_REMOVE(&rqpair->pending_rdma_write_queue, rdma_req_to_abort,
5020 			      spdk_nvmf_rdma_request, state_link);
5021 
5022 		nvmf_rdma_request_set_abort_status(req, rdma_req_to_abort, rqpair);
5023 		break;
5024 
5025 	case RDMA_REQUEST_STATE_READY_TO_COMPLETE_PENDING:
5026 		/* Remove req from the list here to re-use common function */
5027 		STAILQ_REMOVE(&rqpair->pending_rdma_send_queue, rdma_req_to_abort,
5028 			      spdk_nvmf_rdma_request, state_link);
5029 
5030 		nvmf_rdma_request_set_abort_status(req, rdma_req_to_abort, rqpair);
5031 		break;
5032 
5033 	case RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER:
5034 		if (spdk_get_ticks() < req->timeout_tsc) {
5035 			req->poller = SPDK_POLLER_REGISTER(_nvmf_rdma_qpair_abort_request, req, 0);
5036 			return SPDK_POLLER_BUSY;
5037 		}
5038 		break;
5039 
5040 	default:
5041 		break;
5042 	}
5043 
5044 	spdk_nvmf_request_complete(req);
5045 	return SPDK_POLLER_BUSY;
5046 }
5047 
5048 static void
5049 nvmf_rdma_qpair_abort_request(struct spdk_nvmf_qpair *qpair,
5050 			      struct spdk_nvmf_request *req)
5051 {
5052 	struct spdk_nvmf_rdma_qpair *rqpair;
5053 	struct spdk_nvmf_rdma_transport *rtransport;
5054 	struct spdk_nvmf_transport *transport;
5055 	uint16_t cid;
5056 	uint32_t i, max_req_count;
5057 	struct spdk_nvmf_rdma_request *rdma_req_to_abort = NULL, *rdma_req;
5058 
5059 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
5060 	rtransport = SPDK_CONTAINEROF(qpair->transport, struct spdk_nvmf_rdma_transport, transport);
5061 	transport = &rtransport->transport;
5062 
5063 	cid = req->cmd->nvme_cmd.cdw10_bits.abort.cid;
5064 	max_req_count = rqpair->srq == NULL ? rqpair->max_queue_depth : rqpair->poller->max_srq_depth;
5065 
5066 	for (i = 0; i < max_req_count; i++) {
5067 		rdma_req = &rqpair->resources->reqs[i];
5068 		/* When SRQ == NULL, rqpair has its own requests and req.qpair pointer always points to the qpair
5069 		 * When SRQ != NULL all rqpairs share common requests and qpair pointer is assigned when we start to
5070 		 * process a request. So in both cases all requests which are not in FREE state have valid qpair ptr */
5071 		if (rdma_req->state != RDMA_REQUEST_STATE_FREE && rdma_req->req.cmd->nvme_cmd.cid == cid &&
5072 		    rdma_req->req.qpair == qpair) {
5073 			rdma_req_to_abort = rdma_req;
5074 			break;
5075 		}
5076 	}
5077 
5078 	if (rdma_req_to_abort == NULL) {
5079 		spdk_nvmf_request_complete(req);
5080 		return;
5081 	}
5082 
5083 	req->req_to_abort = &rdma_req_to_abort->req;
5084 	req->timeout_tsc = spdk_get_ticks() +
5085 			   transport->opts.abort_timeout_sec * spdk_get_ticks_hz();
5086 	req->poller = NULL;
5087 
5088 	_nvmf_rdma_qpair_abort_request(req);
5089 }
5090 
5091 static void
5092 nvmf_rdma_poll_group_dump_stat(struct spdk_nvmf_transport_poll_group *group,
5093 			       struct spdk_json_write_ctx *w)
5094 {
5095 	struct spdk_nvmf_rdma_poll_group *rgroup;
5096 	struct spdk_nvmf_rdma_poller *rpoller;
5097 
5098 	assert(w != NULL);
5099 
5100 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
5101 
5102 	spdk_json_write_named_uint64(w, "pending_data_buffer", rgroup->stat.pending_data_buffer);
5103 
5104 	spdk_json_write_named_array_begin(w, "devices");
5105 
5106 	TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
5107 		spdk_json_write_object_begin(w);
5108 		spdk_json_write_named_string(w, "name",
5109 					     ibv_get_device_name(rpoller->device->context->device));
5110 		spdk_json_write_named_uint64(w, "polls",
5111 					     rpoller->stat.polls);
5112 		spdk_json_write_named_uint64(w, "idle_polls",
5113 					     rpoller->stat.idle_polls);
5114 		spdk_json_write_named_uint64(w, "completions",
5115 					     rpoller->stat.completions);
5116 		spdk_json_write_named_uint64(w, "requests",
5117 					     rpoller->stat.requests);
5118 		spdk_json_write_named_uint64(w, "request_latency",
5119 					     rpoller->stat.request_latency);
5120 		spdk_json_write_named_uint64(w, "pending_free_request",
5121 					     rpoller->stat.pending_free_request);
5122 		spdk_json_write_named_uint64(w, "pending_rdma_read",
5123 					     rpoller->stat.pending_rdma_read);
5124 		spdk_json_write_named_uint64(w, "pending_rdma_write",
5125 					     rpoller->stat.pending_rdma_write);
5126 		spdk_json_write_named_uint64(w, "pending_rdma_send",
5127 					     rpoller->stat.pending_rdma_send);
5128 		spdk_json_write_named_uint64(w, "total_send_wrs",
5129 					     rpoller->stat.qp_stats.send.num_submitted_wrs);
5130 		spdk_json_write_named_uint64(w, "send_doorbell_updates",
5131 					     rpoller->stat.qp_stats.send.doorbell_updates);
5132 		spdk_json_write_named_uint64(w, "total_recv_wrs",
5133 					     rpoller->stat.qp_stats.recv.num_submitted_wrs);
5134 		spdk_json_write_named_uint64(w, "recv_doorbell_updates",
5135 					     rpoller->stat.qp_stats.recv.doorbell_updates);
5136 		spdk_json_write_object_end(w);
5137 	}
5138 
5139 	spdk_json_write_array_end(w);
5140 }
5141 
5142 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_rdma = {
5143 	.name = "RDMA",
5144 	.type = SPDK_NVME_TRANSPORT_RDMA,
5145 	.opts_init = nvmf_rdma_opts_init,
5146 	.create = nvmf_rdma_create,
5147 	.dump_opts = nvmf_rdma_dump_opts,
5148 	.destroy = nvmf_rdma_destroy,
5149 
5150 	.listen = nvmf_rdma_listen,
5151 	.stop_listen = nvmf_rdma_stop_listen,
5152 	.cdata_init = nvmf_rdma_cdata_init,
5153 
5154 	.listener_discover = nvmf_rdma_discover,
5155 
5156 	.poll_group_create = nvmf_rdma_poll_group_create,
5157 	.get_optimal_poll_group = nvmf_rdma_get_optimal_poll_group,
5158 	.poll_group_destroy = nvmf_rdma_poll_group_destroy,
5159 	.poll_group_add = nvmf_rdma_poll_group_add,
5160 	.poll_group_remove = nvmf_rdma_poll_group_remove,
5161 	.poll_group_poll = nvmf_rdma_poll_group_poll,
5162 
5163 	.req_free = nvmf_rdma_request_free,
5164 	.req_complete = nvmf_rdma_request_complete,
5165 
5166 	.qpair_fini = nvmf_rdma_close_qpair,
5167 	.qpair_get_peer_trid = nvmf_rdma_qpair_get_peer_trid,
5168 	.qpair_get_local_trid = nvmf_rdma_qpair_get_local_trid,
5169 	.qpair_get_listen_trid = nvmf_rdma_qpair_get_listen_trid,
5170 	.qpair_abort_request = nvmf_rdma_qpair_abort_request,
5171 
5172 	.poll_group_dump_stat = nvmf_rdma_poll_group_dump_stat,
5173 };
5174 
5175 SPDK_NVMF_TRANSPORT_REGISTER(rdma, &spdk_nvmf_transport_rdma);
5176 SPDK_LOG_REGISTER_COMPONENT(rdma)
5177