xref: /spdk/lib/nvmf/rdma.c (revision 712a3f69d32632bf6c862f00200f7f437d3f7529)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation. All rights reserved.
5  *   Copyright (c) 2019, 2020 Mellanox Technologies LTD. All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include <infiniband/verbs.h>
37 #include <rdma/rdma_cma.h>
38 #include <rdma/rdma_verbs.h>
39 
40 #include "spdk/config.h"
41 #include "spdk/thread.h"
42 #include "spdk/likely.h"
43 #include "spdk/nvmf_transport.h"
44 #include "spdk/string.h"
45 #include "spdk/trace.h"
46 #include "spdk/util.h"
47 
48 #include "spdk_internal/assert.h"
49 #include "spdk_internal/log.h"
50 
51 struct spdk_nvme_rdma_hooks g_nvmf_hooks = {};
52 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_rdma;
53 
54 /*
55  RDMA Connection Resource Defaults
56  */
57 #define NVMF_DEFAULT_TX_SGE		SPDK_NVMF_MAX_SGL_ENTRIES
58 #define NVMF_DEFAULT_RSP_SGE		1
59 #define NVMF_DEFAULT_RX_SGE		2
60 
61 /* The RDMA completion queue size */
62 #define DEFAULT_NVMF_RDMA_CQ_SIZE	4096
63 #define MAX_WR_PER_QP(queue_depth)	(queue_depth * 3 + 2)
64 
65 /* Timeout for destroying defunct rqpairs */
66 #define NVMF_RDMA_QPAIR_DESTROY_TIMEOUT_US	4000000
67 
68 static int g_spdk_nvmf_ibv_query_mask =
69 	IBV_QP_STATE |
70 	IBV_QP_PKEY_INDEX |
71 	IBV_QP_PORT |
72 	IBV_QP_ACCESS_FLAGS |
73 	IBV_QP_AV |
74 	IBV_QP_PATH_MTU |
75 	IBV_QP_DEST_QPN |
76 	IBV_QP_RQ_PSN |
77 	IBV_QP_MAX_DEST_RD_ATOMIC |
78 	IBV_QP_MIN_RNR_TIMER |
79 	IBV_QP_SQ_PSN |
80 	IBV_QP_TIMEOUT |
81 	IBV_QP_RETRY_CNT |
82 	IBV_QP_RNR_RETRY |
83 	IBV_QP_MAX_QP_RD_ATOMIC;
84 
85 enum spdk_nvmf_rdma_request_state {
86 	/* The request is not currently in use */
87 	RDMA_REQUEST_STATE_FREE = 0,
88 
89 	/* Initial state when request first received */
90 	RDMA_REQUEST_STATE_NEW,
91 
92 	/* The request is queued until a data buffer is available. */
93 	RDMA_REQUEST_STATE_NEED_BUFFER,
94 
95 	/* The request is waiting on RDMA queue depth availability
96 	 * to transfer data from the host to the controller.
97 	 */
98 	RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING,
99 
100 	/* The request is currently transferring data from the host to the controller. */
101 	RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER,
102 
103 	/* The request is ready to execute at the block device */
104 	RDMA_REQUEST_STATE_READY_TO_EXECUTE,
105 
106 	/* The request is currently executing at the block device */
107 	RDMA_REQUEST_STATE_EXECUTING,
108 
109 	/* The request finished executing at the block device */
110 	RDMA_REQUEST_STATE_EXECUTED,
111 
112 	/* The request is waiting on RDMA queue depth availability
113 	 * to transfer data from the controller to the host.
114 	 */
115 	RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING,
116 
117 	/* The request is ready to send a completion */
118 	RDMA_REQUEST_STATE_READY_TO_COMPLETE,
119 
120 	/* The request is currently transferring data from the controller to the host. */
121 	RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST,
122 
123 	/* The request currently has an outstanding completion without an
124 	 * associated data transfer.
125 	 */
126 	RDMA_REQUEST_STATE_COMPLETING,
127 
128 	/* The request completed and can be marked free. */
129 	RDMA_REQUEST_STATE_COMPLETED,
130 
131 	/* Terminator */
132 	RDMA_REQUEST_NUM_STATES,
133 };
134 
135 #define OBJECT_NVMF_RDMA_IO				0x40
136 
137 #define TRACE_GROUP_NVMF_RDMA				0x4
138 #define TRACE_RDMA_REQUEST_STATE_NEW					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x0)
139 #define TRACE_RDMA_REQUEST_STATE_NEED_BUFFER				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x1)
140 #define TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING	SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x2)
141 #define TRACE_RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER	SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x3)
142 #define TRACE_RDMA_REQUEST_STATE_READY_TO_EXECUTE			SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x4)
143 #define TRACE_RDMA_REQUEST_STATE_EXECUTING				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x5)
144 #define TRACE_RDMA_REQUEST_STATE_EXECUTED				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x6)
145 #define TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING		SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x7)
146 #define TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE			SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x8)
147 #define TRACE_RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST	SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x9)
148 #define TRACE_RDMA_REQUEST_STATE_COMPLETING				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0xA)
149 #define TRACE_RDMA_REQUEST_STATE_COMPLETED				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0xB)
150 #define TRACE_RDMA_QP_CREATE						SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0xC)
151 #define TRACE_RDMA_IBV_ASYNC_EVENT					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0xD)
152 #define TRACE_RDMA_CM_ASYNC_EVENT					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0xE)
153 #define TRACE_RDMA_QP_STATE_CHANGE					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0xF)
154 #define TRACE_RDMA_QP_DISCONNECT					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x10)
155 #define TRACE_RDMA_QP_DESTROY						SPDK_TPOINT_ID(TRACE_GROUP_NVMF_RDMA, 0x11)
156 
157 SPDK_TRACE_REGISTER_FN(nvmf_trace, "nvmf_rdma", TRACE_GROUP_NVMF_RDMA)
158 {
159 	spdk_trace_register_object(OBJECT_NVMF_RDMA_IO, 'r');
160 	spdk_trace_register_description("RDMA_REQ_NEW", TRACE_RDMA_REQUEST_STATE_NEW,
161 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 1, 1, "cmid:   ");
162 	spdk_trace_register_description("RDMA_REQ_NEED_BUFFER", TRACE_RDMA_REQUEST_STATE_NEED_BUFFER,
163 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
164 	spdk_trace_register_description("RDMA_REQ_TX_PENDING_C2H",
165 					TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING,
166 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
167 	spdk_trace_register_description("RDMA_REQ_TX_PENDING_H2C",
168 					TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING,
169 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
170 	spdk_trace_register_description("RDMA_REQ_TX_H2C",
171 					TRACE_RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER,
172 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
173 	spdk_trace_register_description("RDMA_REQ_RDY_TO_EXECUTE",
174 					TRACE_RDMA_REQUEST_STATE_READY_TO_EXECUTE,
175 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
176 	spdk_trace_register_description("RDMA_REQ_EXECUTING",
177 					TRACE_RDMA_REQUEST_STATE_EXECUTING,
178 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
179 	spdk_trace_register_description("RDMA_REQ_EXECUTED",
180 					TRACE_RDMA_REQUEST_STATE_EXECUTED,
181 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
182 	spdk_trace_register_description("RDMA_REQ_RDY_TO_COMPL",
183 					TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE,
184 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
185 	spdk_trace_register_description("RDMA_REQ_COMPLETING_C2H",
186 					TRACE_RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST,
187 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
188 	spdk_trace_register_description("RDMA_REQ_COMPLETING",
189 					TRACE_RDMA_REQUEST_STATE_COMPLETING,
190 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
191 	spdk_trace_register_description("RDMA_REQ_COMPLETED",
192 					TRACE_RDMA_REQUEST_STATE_COMPLETED,
193 					OWNER_NONE, OBJECT_NVMF_RDMA_IO, 0, 1, "cmid:   ");
194 
195 	spdk_trace_register_description("RDMA_QP_CREATE", TRACE_RDMA_QP_CREATE,
196 					OWNER_NONE, OBJECT_NONE, 0, 0, "");
197 	spdk_trace_register_description("RDMA_IBV_ASYNC_EVENT", TRACE_RDMA_IBV_ASYNC_EVENT,
198 					OWNER_NONE, OBJECT_NONE, 0, 0, "type:   ");
199 	spdk_trace_register_description("RDMA_CM_ASYNC_EVENT", TRACE_RDMA_CM_ASYNC_EVENT,
200 					OWNER_NONE, OBJECT_NONE, 0, 0, "type:   ");
201 	spdk_trace_register_description("RDMA_QP_STATE_CHANGE", TRACE_RDMA_QP_STATE_CHANGE,
202 					OWNER_NONE, OBJECT_NONE, 0, 1, "state:  ");
203 	spdk_trace_register_description("RDMA_QP_DISCONNECT", TRACE_RDMA_QP_DISCONNECT,
204 					OWNER_NONE, OBJECT_NONE, 0, 0, "");
205 	spdk_trace_register_description("RDMA_QP_DESTROY", TRACE_RDMA_QP_DESTROY,
206 					OWNER_NONE, OBJECT_NONE, 0, 0, "");
207 }
208 
209 enum spdk_nvmf_rdma_wr_type {
210 	RDMA_WR_TYPE_RECV,
211 	RDMA_WR_TYPE_SEND,
212 	RDMA_WR_TYPE_DATA,
213 };
214 
215 struct spdk_nvmf_rdma_wr {
216 	enum spdk_nvmf_rdma_wr_type	type;
217 };
218 
219 /* This structure holds commands as they are received off the wire.
220  * It must be dynamically paired with a full request object
221  * (spdk_nvmf_rdma_request) to service a request. It is separate
222  * from the request because RDMA does not appear to order
223  * completions, so occasionally we'll get a new incoming
224  * command when there aren't any free request objects.
225  */
226 struct spdk_nvmf_rdma_recv {
227 	struct ibv_recv_wr			wr;
228 	struct ibv_sge				sgl[NVMF_DEFAULT_RX_SGE];
229 
230 	struct spdk_nvmf_rdma_qpair		*qpair;
231 
232 	/* In-capsule data buffer */
233 	uint8_t					*buf;
234 
235 	struct spdk_nvmf_rdma_wr		rdma_wr;
236 	uint64_t				receive_tsc;
237 
238 	STAILQ_ENTRY(spdk_nvmf_rdma_recv)	link;
239 };
240 
241 struct spdk_nvmf_rdma_request_data {
242 	struct spdk_nvmf_rdma_wr	rdma_wr;
243 	struct ibv_send_wr		wr;
244 	struct ibv_sge			sgl[SPDK_NVMF_MAX_SGL_ENTRIES];
245 };
246 
247 struct spdk_nvmf_rdma_request {
248 	struct spdk_nvmf_request		req;
249 
250 	enum spdk_nvmf_rdma_request_state	state;
251 
252 	struct spdk_nvmf_rdma_recv		*recv;
253 
254 	struct {
255 		struct spdk_nvmf_rdma_wr	rdma_wr;
256 		struct	ibv_send_wr		wr;
257 		struct	ibv_sge			sgl[NVMF_DEFAULT_RSP_SGE];
258 	} rsp;
259 
260 	struct spdk_nvmf_rdma_request_data	data;
261 
262 	uint32_t				iovpos;
263 
264 	uint32_t				num_outstanding_data_wr;
265 	uint64_t				receive_tsc;
266 
267 	STAILQ_ENTRY(spdk_nvmf_rdma_request)	state_link;
268 };
269 
270 enum spdk_nvmf_rdma_qpair_disconnect_flags {
271 	RDMA_QP_DISCONNECTING		= 1,
272 	RDMA_QP_RECV_DRAINED		= 1 << 1,
273 	RDMA_QP_SEND_DRAINED		= 1 << 2
274 };
275 
276 struct spdk_nvmf_rdma_resource_opts {
277 	struct spdk_nvmf_rdma_qpair	*qpair;
278 	/* qp points either to an ibv_qp object or an ibv_srq object depending on the value of shared. */
279 	void				*qp;
280 	struct ibv_pd			*pd;
281 	uint32_t			max_queue_depth;
282 	uint32_t			in_capsule_data_size;
283 	bool				shared;
284 };
285 
286 struct spdk_nvmf_send_wr_list {
287 	struct ibv_send_wr	*first;
288 	struct ibv_send_wr	*last;
289 };
290 
291 struct spdk_nvmf_recv_wr_list {
292 	struct ibv_recv_wr	*first;
293 	struct ibv_recv_wr	*last;
294 };
295 
296 struct spdk_nvmf_rdma_resources {
297 	/* Array of size "max_queue_depth" containing RDMA requests. */
298 	struct spdk_nvmf_rdma_request		*reqs;
299 
300 	/* Array of size "max_queue_depth" containing RDMA recvs. */
301 	struct spdk_nvmf_rdma_recv		*recvs;
302 
303 	/* Array of size "max_queue_depth" containing 64 byte capsules
304 	 * used for receive.
305 	 */
306 	union nvmf_h2c_msg			*cmds;
307 	struct ibv_mr				*cmds_mr;
308 
309 	/* Array of size "max_queue_depth" containing 16 byte completions
310 	 * to be sent back to the user.
311 	 */
312 	union nvmf_c2h_msg			*cpls;
313 	struct ibv_mr				*cpls_mr;
314 
315 	/* Array of size "max_queue_depth * InCapsuleDataSize" containing
316 	 * buffers to be used for in capsule data.
317 	 */
318 	void					*bufs;
319 	struct ibv_mr				*bufs_mr;
320 
321 	/* The list of pending recvs to transfer */
322 	struct spdk_nvmf_recv_wr_list		recvs_to_post;
323 
324 	/* Receives that are waiting for a request object */
325 	STAILQ_HEAD(, spdk_nvmf_rdma_recv)	incoming_queue;
326 
327 	/* Queue to track free requests */
328 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	free_queue;
329 };
330 
331 typedef void (*spdk_nvmf_rdma_qpair_ibv_event)(struct spdk_nvmf_rdma_qpair *rqpair);
332 
333 struct spdk_nvmf_rdma_ibv_event_ctx {
334 	struct spdk_nvmf_rdma_qpair			*rqpair;
335 	spdk_nvmf_rdma_qpair_ibv_event			cb_fn;
336 	/* Link to other ibv events associated with this qpair */
337 	STAILQ_ENTRY(spdk_nvmf_rdma_ibv_event_ctx)	link;
338 };
339 
340 struct spdk_nvmf_rdma_qpair {
341 	struct spdk_nvmf_qpair			qpair;
342 
343 	struct spdk_nvmf_rdma_device		*device;
344 	struct spdk_nvmf_rdma_poller		*poller;
345 
346 	struct rdma_cm_id			*cm_id;
347 	struct ibv_srq				*srq;
348 	struct rdma_cm_id			*listen_id;
349 
350 	/* The maximum number of I/O outstanding on this connection at one time */
351 	uint16_t				max_queue_depth;
352 
353 	/* The maximum number of active RDMA READ and ATOMIC operations at one time */
354 	uint16_t				max_read_depth;
355 
356 	/* The maximum number of RDMA SEND operations at one time */
357 	uint32_t				max_send_depth;
358 
359 	/* The current number of outstanding WRs from this qpair's
360 	 * recv queue. Should not exceed device->attr.max_queue_depth.
361 	 */
362 	uint16_t				current_recv_depth;
363 
364 	/* The current number of active RDMA READ operations */
365 	uint16_t				current_read_depth;
366 
367 	/* The current number of posted WRs from this qpair's
368 	 * send queue. Should not exceed max_send_depth.
369 	 */
370 	uint32_t				current_send_depth;
371 
372 	/* The maximum number of SGEs per WR on the send queue */
373 	uint32_t				max_send_sge;
374 
375 	/* The maximum number of SGEs per WR on the recv queue */
376 	uint32_t				max_recv_sge;
377 
378 	/* The list of pending send requests for a transfer */
379 	struct spdk_nvmf_send_wr_list		sends_to_post;
380 
381 	struct spdk_nvmf_rdma_resources		*resources;
382 
383 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	pending_rdma_read_queue;
384 
385 	STAILQ_HEAD(, spdk_nvmf_rdma_request)	pending_rdma_write_queue;
386 
387 	/* Number of requests not in the free state */
388 	uint32_t				qd;
389 
390 	TAILQ_ENTRY(spdk_nvmf_rdma_qpair)	link;
391 
392 	STAILQ_ENTRY(spdk_nvmf_rdma_qpair)	recv_link;
393 
394 	STAILQ_ENTRY(spdk_nvmf_rdma_qpair)	send_link;
395 
396 	/* IBV queue pair attributes: they are used to manage
397 	 * qp state and recover from errors.
398 	 */
399 	enum ibv_qp_state			ibv_state;
400 
401 	uint32_t				disconnect_flags;
402 
403 	/* Poller registered in case the qpair doesn't properly
404 	 * complete the qpair destruct process and becomes defunct.
405 	 */
406 
407 	struct spdk_poller			*destruct_poller;
408 
409 	/* List of ibv async events */
410 	STAILQ_HEAD(, spdk_nvmf_rdma_ibv_event_ctx)	ibv_events;
411 
412 	/* There are several ways a disconnect can start on a qpair
413 	 * and they are not all mutually exclusive. It is important
414 	 * that we only initialize one of these paths.
415 	 */
416 	bool					disconnect_started;
417 	/* Lets us know that we have received the last_wqe event. */
418 	bool					last_wqe_reached;
419 };
420 
421 struct spdk_nvmf_rdma_poller_stat {
422 	uint64_t				completions;
423 	uint64_t				polls;
424 	uint64_t				requests;
425 	uint64_t				request_latency;
426 	uint64_t				pending_free_request;
427 	uint64_t				pending_rdma_read;
428 	uint64_t				pending_rdma_write;
429 };
430 
431 struct spdk_nvmf_rdma_poller {
432 	struct spdk_nvmf_rdma_device		*device;
433 	struct spdk_nvmf_rdma_poll_group	*group;
434 
435 	int					num_cqe;
436 	int					required_num_wr;
437 	struct ibv_cq				*cq;
438 
439 	/* The maximum number of I/O outstanding on the shared receive queue at one time */
440 	uint16_t				max_srq_depth;
441 
442 	/* Shared receive queue */
443 	struct ibv_srq				*srq;
444 
445 	struct spdk_nvmf_rdma_resources		*resources;
446 	struct spdk_nvmf_rdma_poller_stat	stat;
447 
448 	TAILQ_HEAD(, spdk_nvmf_rdma_qpair)	qpairs;
449 
450 	STAILQ_HEAD(, spdk_nvmf_rdma_qpair)	qpairs_pending_recv;
451 
452 	STAILQ_HEAD(, spdk_nvmf_rdma_qpair)	qpairs_pending_send;
453 
454 	TAILQ_ENTRY(spdk_nvmf_rdma_poller)	link;
455 };
456 
457 struct spdk_nvmf_rdma_poll_group_stat {
458 	uint64_t				pending_data_buffer;
459 };
460 
461 struct spdk_nvmf_rdma_poll_group {
462 	struct spdk_nvmf_transport_poll_group		group;
463 	struct spdk_nvmf_rdma_poll_group_stat		stat;
464 	TAILQ_HEAD(, spdk_nvmf_rdma_poller)		pollers;
465 	TAILQ_ENTRY(spdk_nvmf_rdma_poll_group)		link;
466 	/*
467 	 * buffers which are split across multiple RDMA
468 	 * memory regions cannot be used by this transport.
469 	 */
470 	STAILQ_HEAD(, spdk_nvmf_transport_pg_cache_buf)	retired_bufs;
471 };
472 
473 struct spdk_nvmf_rdma_conn_sched {
474 	struct spdk_nvmf_rdma_poll_group *next_admin_pg;
475 	struct spdk_nvmf_rdma_poll_group *next_io_pg;
476 };
477 
478 /* Assuming rdma_cm uses just one protection domain per ibv_context. */
479 struct spdk_nvmf_rdma_device {
480 	struct ibv_device_attr			attr;
481 	struct ibv_context			*context;
482 
483 	struct spdk_mem_map			*map;
484 	struct ibv_pd				*pd;
485 
486 	int					num_srq;
487 
488 	TAILQ_ENTRY(spdk_nvmf_rdma_device)	link;
489 };
490 
491 struct spdk_nvmf_rdma_port {
492 	const struct spdk_nvme_transport_id	*trid;
493 	struct rdma_cm_id			*id;
494 	struct spdk_nvmf_rdma_device		*device;
495 	TAILQ_ENTRY(spdk_nvmf_rdma_port)	link;
496 };
497 
498 struct spdk_nvmf_rdma_transport {
499 	struct spdk_nvmf_transport	transport;
500 
501 	struct spdk_nvmf_rdma_conn_sched conn_sched;
502 
503 	struct rdma_event_channel	*event_channel;
504 
505 	struct spdk_mempool		*data_wr_pool;
506 
507 	pthread_mutex_t			lock;
508 
509 	/* fields used to poll RDMA/IB events */
510 	nfds_t			npoll_fds;
511 	struct pollfd		*poll_fds;
512 
513 	TAILQ_HEAD(, spdk_nvmf_rdma_device)	devices;
514 	TAILQ_HEAD(, spdk_nvmf_rdma_port)	ports;
515 	TAILQ_HEAD(, spdk_nvmf_rdma_poll_group)	poll_groups;
516 };
517 
518 static inline void
519 spdk_nvmf_rdma_start_disconnect(struct spdk_nvmf_rdma_qpair *rqpair);
520 
521 static bool
522 spdk_nvmf_rdma_request_process(struct spdk_nvmf_rdma_transport *rtransport,
523 			       struct spdk_nvmf_rdma_request *rdma_req);
524 
525 static inline int
526 spdk_nvmf_rdma_check_ibv_state(enum ibv_qp_state state)
527 {
528 	switch (state) {
529 	case IBV_QPS_RESET:
530 	case IBV_QPS_INIT:
531 	case IBV_QPS_RTR:
532 	case IBV_QPS_RTS:
533 	case IBV_QPS_SQD:
534 	case IBV_QPS_SQE:
535 	case IBV_QPS_ERR:
536 		return 0;
537 	default:
538 		return -1;
539 	}
540 }
541 
542 static inline enum spdk_nvme_media_error_status_code
543 spdk_nvmf_rdma_dif_error_to_compl_status(uint8_t err_type) {
544 	enum spdk_nvme_media_error_status_code result;
545 	switch (err_type)
546 	{
547 	case SPDK_DIF_REFTAG_ERROR:
548 		result = SPDK_NVME_SC_REFERENCE_TAG_CHECK_ERROR;
549 		break;
550 	case SPDK_DIF_APPTAG_ERROR:
551 		result = SPDK_NVME_SC_APPLICATION_TAG_CHECK_ERROR;
552 		break;
553 	case SPDK_DIF_GUARD_ERROR:
554 		result = SPDK_NVME_SC_GUARD_CHECK_ERROR;
555 		break;
556 	default:
557 		SPDK_UNREACHABLE();
558 	}
559 
560 	return result;
561 }
562 
563 static enum ibv_qp_state
564 spdk_nvmf_rdma_update_ibv_state(struct spdk_nvmf_rdma_qpair *rqpair) {
565 	enum ibv_qp_state old_state, new_state;
566 	struct ibv_qp_attr qp_attr;
567 	struct ibv_qp_init_attr init_attr;
568 	int rc;
569 
570 	old_state = rqpair->ibv_state;
571 	rc = ibv_query_qp(rqpair->cm_id->qp, &qp_attr,
572 			  g_spdk_nvmf_ibv_query_mask, &init_attr);
573 
574 	if (rc)
575 	{
576 		SPDK_ERRLOG("Failed to get updated RDMA queue pair state!\n");
577 		return IBV_QPS_ERR + 1;
578 	}
579 
580 	new_state = qp_attr.qp_state;
581 	rqpair->ibv_state = new_state;
582 	qp_attr.ah_attr.port_num = qp_attr.port_num;
583 
584 	rc = spdk_nvmf_rdma_check_ibv_state(new_state);
585 	if (rc)
586 	{
587 		SPDK_ERRLOG("QP#%d: bad state updated: %u, maybe hardware issue\n", rqpair->qpair.qid, new_state);
588 		/*
589 		 * IBV_QPS_UNKNOWN undefined if lib version smaller than libibverbs-1.1.8
590 		 * IBV_QPS_UNKNOWN is the enum element after IBV_QPS_ERR
591 		 */
592 		return IBV_QPS_ERR + 1;
593 	}
594 
595 	if (old_state != new_state)
596 	{
597 		spdk_trace_record(TRACE_RDMA_QP_STATE_CHANGE, 0, 0,
598 				  (uintptr_t)rqpair->cm_id, new_state);
599 	}
600 	return new_state;
601 }
602 
603 static const char *str_ibv_qp_state[] = {
604 	"IBV_QPS_RESET",
605 	"IBV_QPS_INIT",
606 	"IBV_QPS_RTR",
607 	"IBV_QPS_RTS",
608 	"IBV_QPS_SQD",
609 	"IBV_QPS_SQE",
610 	"IBV_QPS_ERR",
611 	"IBV_QPS_UNKNOWN"
612 };
613 
614 static int
615 spdk_nvmf_rdma_set_ibv_state(struct spdk_nvmf_rdma_qpair *rqpair,
616 			     enum ibv_qp_state new_state)
617 {
618 	struct ibv_qp_attr qp_attr;
619 	struct ibv_qp_init_attr init_attr;
620 	int rc;
621 	enum ibv_qp_state state;
622 	static int attr_mask_rc[] = {
623 		[IBV_QPS_RESET] = IBV_QP_STATE,
624 		[IBV_QPS_INIT] = (IBV_QP_STATE |
625 				  IBV_QP_PKEY_INDEX |
626 				  IBV_QP_PORT |
627 				  IBV_QP_ACCESS_FLAGS),
628 		[IBV_QPS_RTR] = (IBV_QP_STATE |
629 				 IBV_QP_AV |
630 				 IBV_QP_PATH_MTU |
631 				 IBV_QP_DEST_QPN |
632 				 IBV_QP_RQ_PSN |
633 				 IBV_QP_MAX_DEST_RD_ATOMIC |
634 				 IBV_QP_MIN_RNR_TIMER),
635 		[IBV_QPS_RTS] = (IBV_QP_STATE |
636 				 IBV_QP_SQ_PSN |
637 				 IBV_QP_TIMEOUT |
638 				 IBV_QP_RETRY_CNT |
639 				 IBV_QP_RNR_RETRY |
640 				 IBV_QP_MAX_QP_RD_ATOMIC),
641 		[IBV_QPS_SQD] = IBV_QP_STATE,
642 		[IBV_QPS_SQE] = IBV_QP_STATE,
643 		[IBV_QPS_ERR] = IBV_QP_STATE,
644 	};
645 
646 	rc = spdk_nvmf_rdma_check_ibv_state(new_state);
647 	if (rc) {
648 		SPDK_ERRLOG("QP#%d: bad state requested: %u\n",
649 			    rqpair->qpair.qid, new_state);
650 		return rc;
651 	}
652 
653 	rc = ibv_query_qp(rqpair->cm_id->qp, &qp_attr,
654 			  g_spdk_nvmf_ibv_query_mask, &init_attr);
655 
656 	if (rc) {
657 		SPDK_ERRLOG("Failed to get updated RDMA queue pair state!\n");
658 	}
659 
660 	qp_attr.cur_qp_state = rqpair->ibv_state;
661 	qp_attr.qp_state = new_state;
662 
663 	rc = ibv_modify_qp(rqpair->cm_id->qp, &qp_attr,
664 			   attr_mask_rc[new_state]);
665 
666 	if (rc) {
667 		SPDK_ERRLOG("QP#%d: failed to set state to: %s, %d (%s)\n",
668 			    rqpair->qpair.qid, str_ibv_qp_state[new_state], errno, strerror(errno));
669 		return rc;
670 	}
671 
672 	state = spdk_nvmf_rdma_update_ibv_state(rqpair);
673 
674 	if (state != new_state) {
675 		SPDK_ERRLOG("QP#%d: expected state: %s, actual state: %s\n",
676 			    rqpair->qpair.qid, str_ibv_qp_state[new_state],
677 			    str_ibv_qp_state[state]);
678 		return -1;
679 	}
680 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "IBV QP#%u changed to: %s\n", rqpair->qpair.qid,
681 		      str_ibv_qp_state[state]);
682 	return 0;
683 }
684 
685 static void
686 nvmf_rdma_request_free_data(struct spdk_nvmf_rdma_request *rdma_req,
687 			    struct spdk_nvmf_rdma_transport *rtransport)
688 {
689 	struct spdk_nvmf_rdma_request_data	*data_wr;
690 	struct ibv_send_wr			*next_send_wr;
691 	uint64_t				req_wrid;
692 
693 	rdma_req->num_outstanding_data_wr = 0;
694 	data_wr = &rdma_req->data;
695 	req_wrid = data_wr->wr.wr_id;
696 	while (data_wr && data_wr->wr.wr_id == req_wrid) {
697 		memset(data_wr->sgl, 0, sizeof(data_wr->wr.sg_list[0]) * data_wr->wr.num_sge);
698 		data_wr->wr.num_sge = 0;
699 		next_send_wr = data_wr->wr.next;
700 		if (data_wr != &rdma_req->data) {
701 			spdk_mempool_put(rtransport->data_wr_pool, data_wr);
702 		}
703 		data_wr = (!next_send_wr || next_send_wr == &rdma_req->rsp.wr) ? NULL :
704 			  SPDK_CONTAINEROF(next_send_wr, struct spdk_nvmf_rdma_request_data, wr);
705 	}
706 }
707 
708 static void
709 nvmf_rdma_dump_request(struct spdk_nvmf_rdma_request *req)
710 {
711 	SPDK_ERRLOG("\t\tRequest Data From Pool: %d\n", req->req.data_from_pool);
712 	if (req->req.cmd) {
713 		SPDK_ERRLOG("\t\tRequest opcode: %d\n", req->req.cmd->nvmf_cmd.opcode);
714 	}
715 	if (req->recv) {
716 		SPDK_ERRLOG("\t\tRequest recv wr_id%lu\n", req->recv->wr.wr_id);
717 	}
718 }
719 
720 static void
721 nvmf_rdma_dump_qpair_contents(struct spdk_nvmf_rdma_qpair *rqpair)
722 {
723 	int i;
724 
725 	SPDK_ERRLOG("Dumping contents of queue pair (QID %d)\n", rqpair->qpair.qid);
726 	for (i = 0; i < rqpair->max_queue_depth; i++) {
727 		if (rqpair->resources->reqs[i].state != RDMA_REQUEST_STATE_FREE) {
728 			nvmf_rdma_dump_request(&rqpair->resources->reqs[i]);
729 		}
730 	}
731 }
732 
733 static void
734 nvmf_rdma_resources_destroy(struct spdk_nvmf_rdma_resources *resources)
735 {
736 	if (resources->cmds_mr) {
737 		ibv_dereg_mr(resources->cmds_mr);
738 	}
739 
740 	if (resources->cpls_mr) {
741 		ibv_dereg_mr(resources->cpls_mr);
742 	}
743 
744 	if (resources->bufs_mr) {
745 		ibv_dereg_mr(resources->bufs_mr);
746 	}
747 
748 	spdk_free(resources->cmds);
749 	spdk_free(resources->cpls);
750 	spdk_free(resources->bufs);
751 	free(resources->reqs);
752 	free(resources->recvs);
753 	free(resources);
754 }
755 
756 
757 static struct spdk_nvmf_rdma_resources *
758 nvmf_rdma_resources_create(struct spdk_nvmf_rdma_resource_opts *opts)
759 {
760 	struct spdk_nvmf_rdma_resources	*resources;
761 	struct spdk_nvmf_rdma_request	*rdma_req;
762 	struct spdk_nvmf_rdma_recv	*rdma_recv;
763 	struct ibv_qp			*qp;
764 	struct ibv_srq			*srq;
765 	uint32_t			i;
766 	int				rc;
767 
768 	resources = calloc(1, sizeof(struct spdk_nvmf_rdma_resources));
769 	if (!resources) {
770 		SPDK_ERRLOG("Unable to allocate resources for receive queue.\n");
771 		return NULL;
772 	}
773 
774 	resources->reqs = calloc(opts->max_queue_depth, sizeof(*resources->reqs));
775 	resources->recvs = calloc(opts->max_queue_depth, sizeof(*resources->recvs));
776 	resources->cmds = spdk_zmalloc(opts->max_queue_depth * sizeof(*resources->cmds),
777 				       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
778 	resources->cpls = spdk_zmalloc(opts->max_queue_depth * sizeof(*resources->cpls),
779 				       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
780 
781 	if (opts->in_capsule_data_size > 0) {
782 		resources->bufs = spdk_zmalloc(opts->max_queue_depth * opts->in_capsule_data_size,
783 					       0x1000, NULL, SPDK_ENV_LCORE_ID_ANY,
784 					       SPDK_MALLOC_DMA);
785 	}
786 
787 	if (!resources->reqs || !resources->recvs || !resources->cmds ||
788 	    !resources->cpls || (opts->in_capsule_data_size && !resources->bufs)) {
789 		SPDK_ERRLOG("Unable to allocate sufficient memory for RDMA queue.\n");
790 		goto cleanup;
791 	}
792 
793 	resources->cmds_mr = ibv_reg_mr(opts->pd, resources->cmds,
794 					opts->max_queue_depth * sizeof(*resources->cmds),
795 					IBV_ACCESS_LOCAL_WRITE);
796 	resources->cpls_mr = ibv_reg_mr(opts->pd, resources->cpls,
797 					opts->max_queue_depth * sizeof(*resources->cpls),
798 					0);
799 
800 	if (opts->in_capsule_data_size) {
801 		resources->bufs_mr = ibv_reg_mr(opts->pd, resources->bufs,
802 						opts->max_queue_depth *
803 						opts->in_capsule_data_size,
804 						IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
805 	}
806 
807 	if (!resources->cmds_mr || !resources->cpls_mr ||
808 	    (opts->in_capsule_data_size &&
809 	     !resources->bufs_mr)) {
810 		goto cleanup;
811 	}
812 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Command Array: %p Length: %lx LKey: %x\n",
813 		      resources->cmds, opts->max_queue_depth * sizeof(*resources->cmds),
814 		      resources->cmds_mr->lkey);
815 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Completion Array: %p Length: %lx LKey: %x\n",
816 		      resources->cpls, opts->max_queue_depth * sizeof(*resources->cpls),
817 		      resources->cpls_mr->lkey);
818 	if (resources->bufs && resources->bufs_mr) {
819 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "In Capsule Data Array: %p Length: %x LKey: %x\n",
820 			      resources->bufs, opts->max_queue_depth *
821 			      opts->in_capsule_data_size, resources->bufs_mr->lkey);
822 	}
823 
824 	/* Initialize queues */
825 	STAILQ_INIT(&resources->incoming_queue);
826 	STAILQ_INIT(&resources->free_queue);
827 
828 	for (i = 0; i < opts->max_queue_depth; i++) {
829 		struct ibv_recv_wr *bad_wr = NULL;
830 
831 		rdma_recv = &resources->recvs[i];
832 		rdma_recv->qpair = opts->qpair;
833 
834 		/* Set up memory to receive commands */
835 		if (resources->bufs) {
836 			rdma_recv->buf = (void *)((uintptr_t)resources->bufs + (i *
837 						  opts->in_capsule_data_size));
838 		}
839 
840 		rdma_recv->rdma_wr.type = RDMA_WR_TYPE_RECV;
841 
842 		rdma_recv->sgl[0].addr = (uintptr_t)&resources->cmds[i];
843 		rdma_recv->sgl[0].length = sizeof(resources->cmds[i]);
844 		rdma_recv->sgl[0].lkey = resources->cmds_mr->lkey;
845 		rdma_recv->wr.num_sge = 1;
846 
847 		if (rdma_recv->buf && resources->bufs_mr) {
848 			rdma_recv->sgl[1].addr = (uintptr_t)rdma_recv->buf;
849 			rdma_recv->sgl[1].length = opts->in_capsule_data_size;
850 			rdma_recv->sgl[1].lkey = resources->bufs_mr->lkey;
851 			rdma_recv->wr.num_sge++;
852 		}
853 
854 		rdma_recv->wr.wr_id = (uintptr_t)&rdma_recv->rdma_wr;
855 		rdma_recv->wr.sg_list = rdma_recv->sgl;
856 		if (opts->shared) {
857 			srq = (struct ibv_srq *)opts->qp;
858 			rc = ibv_post_srq_recv(srq, &rdma_recv->wr, &bad_wr);
859 		} else {
860 			qp = (struct ibv_qp *)opts->qp;
861 			rc = ibv_post_recv(qp, &rdma_recv->wr, &bad_wr);
862 		}
863 		if (rc) {
864 			goto cleanup;
865 		}
866 	}
867 
868 	for (i = 0; i < opts->max_queue_depth; i++) {
869 		rdma_req = &resources->reqs[i];
870 
871 		if (opts->qpair != NULL) {
872 			rdma_req->req.qpair = &opts->qpair->qpair;
873 		} else {
874 			rdma_req->req.qpair = NULL;
875 		}
876 		rdma_req->req.cmd = NULL;
877 
878 		/* Set up memory to send responses */
879 		rdma_req->req.rsp = &resources->cpls[i];
880 
881 		rdma_req->rsp.sgl[0].addr = (uintptr_t)&resources->cpls[i];
882 		rdma_req->rsp.sgl[0].length = sizeof(resources->cpls[i]);
883 		rdma_req->rsp.sgl[0].lkey = resources->cpls_mr->lkey;
884 
885 		rdma_req->rsp.rdma_wr.type = RDMA_WR_TYPE_SEND;
886 		rdma_req->rsp.wr.wr_id = (uintptr_t)&rdma_req->rsp.rdma_wr;
887 		rdma_req->rsp.wr.next = NULL;
888 		rdma_req->rsp.wr.opcode = IBV_WR_SEND;
889 		rdma_req->rsp.wr.send_flags = IBV_SEND_SIGNALED;
890 		rdma_req->rsp.wr.sg_list = rdma_req->rsp.sgl;
891 		rdma_req->rsp.wr.num_sge = SPDK_COUNTOF(rdma_req->rsp.sgl);
892 
893 		/* Set up memory for data buffers */
894 		rdma_req->data.rdma_wr.type = RDMA_WR_TYPE_DATA;
895 		rdma_req->data.wr.wr_id = (uintptr_t)&rdma_req->data.rdma_wr;
896 		rdma_req->data.wr.next = NULL;
897 		rdma_req->data.wr.send_flags = IBV_SEND_SIGNALED;
898 		rdma_req->data.wr.sg_list = rdma_req->data.sgl;
899 		rdma_req->data.wr.num_sge = SPDK_COUNTOF(rdma_req->data.sgl);
900 
901 		/* Initialize request state to FREE */
902 		rdma_req->state = RDMA_REQUEST_STATE_FREE;
903 		STAILQ_INSERT_TAIL(&resources->free_queue, rdma_req, state_link);
904 	}
905 
906 	return resources;
907 
908 cleanup:
909 	nvmf_rdma_resources_destroy(resources);
910 	return NULL;
911 }
912 
913 static void
914 spdk_nvmf_rdma_qpair_clean_ibv_events(struct spdk_nvmf_rdma_qpair *rqpair)
915 {
916 	struct spdk_nvmf_rdma_ibv_event_ctx *ctx, *tctx;
917 	STAILQ_FOREACH_SAFE(ctx, &rqpair->ibv_events, link, tctx) {
918 		ctx->rqpair = NULL;
919 		/* Memory allocated for ctx is freed in spdk_nvmf_rdma_qpair_process_ibv_event */
920 		STAILQ_REMOVE(&rqpair->ibv_events, ctx, spdk_nvmf_rdma_ibv_event_ctx, link);
921 	}
922 }
923 
924 static void
925 spdk_nvmf_rdma_qpair_destroy(struct spdk_nvmf_rdma_qpair *rqpair)
926 {
927 	struct spdk_nvmf_rdma_recv	*rdma_recv, *recv_tmp;
928 	struct ibv_recv_wr		*bad_recv_wr = NULL;
929 	int				rc;
930 
931 	spdk_trace_record(TRACE_RDMA_QP_DESTROY, 0, 0, (uintptr_t)rqpair->cm_id, 0);
932 
933 	spdk_poller_unregister(&rqpair->destruct_poller);
934 
935 	if (rqpair->qd != 0) {
936 		struct spdk_nvmf_qpair *qpair = &rqpair->qpair;
937 		struct spdk_nvmf_rdma_transport	*rtransport = SPDK_CONTAINEROF(qpair->transport,
938 				struct spdk_nvmf_rdma_transport, transport);
939 		struct spdk_nvmf_rdma_request *req;
940 		uint32_t i, max_req_count = 0;
941 
942 		SPDK_WARNLOG("Destroying qpair when queue depth is %d\n", rqpair->qd);
943 
944 		if (rqpair->srq == NULL) {
945 			nvmf_rdma_dump_qpair_contents(rqpair);
946 			max_req_count = rqpair->max_queue_depth;
947 		} else if (rqpair->poller && rqpair->resources) {
948 			max_req_count = rqpair->poller->max_srq_depth;
949 		}
950 
951 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Release incomplete requests\n");
952 		for (i = 0; i < max_req_count; i++) {
953 			req = &rqpair->resources->reqs[i];
954 			if (req->req.qpair == qpair && req->state != RDMA_REQUEST_STATE_FREE) {
955 				/* spdk_nvmf_rdma_request_process checks qpair ibv and internal state
956 				 * and completes a request */
957 				spdk_nvmf_rdma_request_process(rtransport, req);
958 			}
959 		}
960 		assert(rqpair->qd == 0);
961 	}
962 
963 	if (rqpair->poller) {
964 		TAILQ_REMOVE(&rqpair->poller->qpairs, rqpair, link);
965 
966 		if (rqpair->srq != NULL && rqpair->resources != NULL) {
967 			/* Drop all received but unprocessed commands for this queue and return them to SRQ */
968 			STAILQ_FOREACH_SAFE(rdma_recv, &rqpair->resources->incoming_queue, link, recv_tmp) {
969 				if (rqpair == rdma_recv->qpair) {
970 					STAILQ_REMOVE(&rqpair->resources->incoming_queue, rdma_recv, spdk_nvmf_rdma_recv, link);
971 					rc = ibv_post_srq_recv(rqpair->srq, &rdma_recv->wr, &bad_recv_wr);
972 					if (rc) {
973 						SPDK_ERRLOG("Unable to re-post rx descriptor\n");
974 					}
975 				}
976 			}
977 		}
978 	}
979 
980 	if (rqpair->cm_id) {
981 		if (rqpair->cm_id->qp != NULL) {
982 			rdma_destroy_qp(rqpair->cm_id);
983 		}
984 		rdma_destroy_id(rqpair->cm_id);
985 
986 		if (rqpair->poller != NULL && rqpair->srq == NULL) {
987 			rqpair->poller->required_num_wr -= MAX_WR_PER_QP(rqpair->max_queue_depth);
988 		}
989 	}
990 
991 	if (rqpair->srq == NULL && rqpair->resources != NULL) {
992 		nvmf_rdma_resources_destroy(rqpair->resources);
993 	}
994 
995 	spdk_nvmf_rdma_qpair_clean_ibv_events(rqpair);
996 
997 	free(rqpair);
998 }
999 
1000 static int
1001 nvmf_rdma_resize_cq(struct spdk_nvmf_rdma_qpair *rqpair, struct spdk_nvmf_rdma_device *device)
1002 {
1003 	struct spdk_nvmf_rdma_poller	*rpoller;
1004 	int				rc, num_cqe, required_num_wr;
1005 
1006 	/* Enlarge CQ size dynamically */
1007 	rpoller = rqpair->poller;
1008 	required_num_wr = rpoller->required_num_wr + MAX_WR_PER_QP(rqpair->max_queue_depth);
1009 	num_cqe = rpoller->num_cqe;
1010 	if (num_cqe < required_num_wr) {
1011 		num_cqe = spdk_max(num_cqe * 2, required_num_wr);
1012 		num_cqe = spdk_min(num_cqe, device->attr.max_cqe);
1013 	}
1014 
1015 	if (rpoller->num_cqe != num_cqe) {
1016 		if (required_num_wr > device->attr.max_cqe) {
1017 			SPDK_ERRLOG("RDMA CQE requirement (%d) exceeds device max_cqe limitation (%d)\n",
1018 				    required_num_wr, device->attr.max_cqe);
1019 			return -1;
1020 		}
1021 
1022 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Resize RDMA CQ from %d to %d\n", rpoller->num_cqe, num_cqe);
1023 		rc = ibv_resize_cq(rpoller->cq, num_cqe);
1024 		if (rc) {
1025 			SPDK_ERRLOG("RDMA CQ resize failed: errno %d: %s\n", errno, spdk_strerror(errno));
1026 			return -1;
1027 		}
1028 
1029 		rpoller->num_cqe = num_cqe;
1030 	}
1031 
1032 	rpoller->required_num_wr = required_num_wr;
1033 	return 0;
1034 }
1035 
1036 static int
1037 spdk_nvmf_rdma_qpair_initialize(struct spdk_nvmf_qpair *qpair)
1038 {
1039 	struct spdk_nvmf_rdma_qpair		*rqpair;
1040 	int					rc;
1041 	struct spdk_nvmf_rdma_transport		*rtransport;
1042 	struct spdk_nvmf_transport		*transport;
1043 	struct spdk_nvmf_rdma_resource_opts	opts;
1044 	struct spdk_nvmf_rdma_device		*device;
1045 	struct ibv_qp_init_attr			ibv_init_attr;
1046 
1047 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
1048 	device = rqpair->device;
1049 
1050 	memset(&ibv_init_attr, 0, sizeof(struct ibv_qp_init_attr));
1051 	ibv_init_attr.qp_context	= rqpair;
1052 	ibv_init_attr.qp_type		= IBV_QPT_RC;
1053 	ibv_init_attr.send_cq		= rqpair->poller->cq;
1054 	ibv_init_attr.recv_cq		= rqpair->poller->cq;
1055 
1056 	if (rqpair->srq) {
1057 		ibv_init_attr.srq		= rqpair->srq;
1058 	} else {
1059 		ibv_init_attr.cap.max_recv_wr	= rqpair->max_queue_depth +
1060 						  1; /* RECV operations + dummy drain WR */
1061 	}
1062 
1063 	ibv_init_attr.cap.max_send_wr	= rqpair->max_queue_depth *
1064 					  2 + 1; /* SEND, READ, and WRITE operations + dummy drain WR */
1065 	ibv_init_attr.cap.max_send_sge	= spdk_min(device->attr.max_sge, NVMF_DEFAULT_TX_SGE);
1066 	ibv_init_attr.cap.max_recv_sge	= spdk_min(device->attr.max_sge, NVMF_DEFAULT_RX_SGE);
1067 
1068 	if (rqpair->srq == NULL && nvmf_rdma_resize_cq(rqpair, device) < 0) {
1069 		SPDK_ERRLOG("Failed to resize the completion queue. Cannot initialize qpair.\n");
1070 		goto error;
1071 	}
1072 
1073 	rc = rdma_create_qp(rqpair->cm_id, device->pd, &ibv_init_attr);
1074 	if (rc) {
1075 		SPDK_ERRLOG("rdma_create_qp failed: errno %d: %s\n", errno, spdk_strerror(errno));
1076 		goto error;
1077 	}
1078 
1079 	rqpair->max_send_depth = spdk_min((uint32_t)(rqpair->max_queue_depth * 2 + 1),
1080 					  ibv_init_attr.cap.max_send_wr);
1081 	rqpair->max_send_sge = spdk_min(NVMF_DEFAULT_TX_SGE, ibv_init_attr.cap.max_send_sge);
1082 	rqpair->max_recv_sge = spdk_min(NVMF_DEFAULT_RX_SGE, ibv_init_attr.cap.max_recv_sge);
1083 	spdk_trace_record(TRACE_RDMA_QP_CREATE, 0, 0, (uintptr_t)rqpair->cm_id, 0);
1084 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "New RDMA Connection: %p\n", qpair);
1085 
1086 	rqpair->sends_to_post.first = NULL;
1087 	rqpair->sends_to_post.last = NULL;
1088 
1089 	if (rqpair->poller->srq == NULL) {
1090 		rtransport = SPDK_CONTAINEROF(qpair->transport, struct spdk_nvmf_rdma_transport, transport);
1091 		transport = &rtransport->transport;
1092 
1093 		opts.qp = rqpair->cm_id->qp;
1094 		opts.pd = rqpair->cm_id->pd;
1095 		opts.qpair = rqpair;
1096 		opts.shared = false;
1097 		opts.max_queue_depth = rqpair->max_queue_depth;
1098 		opts.in_capsule_data_size = transport->opts.in_capsule_data_size;
1099 
1100 		rqpair->resources = nvmf_rdma_resources_create(&opts);
1101 
1102 		if (!rqpair->resources) {
1103 			SPDK_ERRLOG("Unable to allocate resources for receive queue.\n");
1104 			rdma_destroy_qp(rqpair->cm_id);
1105 			goto error;
1106 		}
1107 	} else {
1108 		rqpair->resources = rqpair->poller->resources;
1109 	}
1110 
1111 	rqpair->current_recv_depth = 0;
1112 	STAILQ_INIT(&rqpair->pending_rdma_read_queue);
1113 	STAILQ_INIT(&rqpair->pending_rdma_write_queue);
1114 
1115 	return 0;
1116 
1117 error:
1118 	rdma_destroy_id(rqpair->cm_id);
1119 	rqpair->cm_id = NULL;
1120 	return -1;
1121 }
1122 
1123 /* Append the given recv wr structure to the resource structs outstanding recvs list. */
1124 /* This function accepts either a single wr or the first wr in a linked list. */
1125 static void
1126 nvmf_rdma_qpair_queue_recv_wrs(struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_recv_wr *first)
1127 {
1128 	struct ibv_recv_wr *last;
1129 
1130 	last = first;
1131 	while (last->next != NULL) {
1132 		last = last->next;
1133 	}
1134 
1135 	if (rqpair->resources->recvs_to_post.first == NULL) {
1136 		rqpair->resources->recvs_to_post.first = first;
1137 		rqpair->resources->recvs_to_post.last = last;
1138 		if (rqpair->srq == NULL) {
1139 			STAILQ_INSERT_TAIL(&rqpair->poller->qpairs_pending_recv, rqpair, recv_link);
1140 		}
1141 	} else {
1142 		rqpair->resources->recvs_to_post.last->next = first;
1143 		rqpair->resources->recvs_to_post.last = last;
1144 	}
1145 }
1146 
1147 /* Append the given send wr structure to the qpair's outstanding sends list. */
1148 /* This function accepts either a single wr or the first wr in a linked list. */
1149 static void
1150 nvmf_rdma_qpair_queue_send_wrs(struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_send_wr *first)
1151 {
1152 	struct ibv_send_wr *last;
1153 
1154 	last = first;
1155 	while (last->next != NULL) {
1156 		last = last->next;
1157 	}
1158 
1159 	if (rqpair->sends_to_post.first == NULL) {
1160 		rqpair->sends_to_post.first = first;
1161 		rqpair->sends_to_post.last = last;
1162 		STAILQ_INSERT_TAIL(&rqpair->poller->qpairs_pending_send, rqpair, send_link);
1163 	} else {
1164 		rqpair->sends_to_post.last->next = first;
1165 		rqpair->sends_to_post.last = last;
1166 	}
1167 }
1168 
1169 static int
1170 request_transfer_in(struct spdk_nvmf_request *req)
1171 {
1172 	struct spdk_nvmf_rdma_request	*rdma_req;
1173 	struct spdk_nvmf_qpair		*qpair;
1174 	struct spdk_nvmf_rdma_qpair	*rqpair;
1175 
1176 	qpair = req->qpair;
1177 	rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
1178 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
1179 
1180 	assert(req->xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER);
1181 	assert(rdma_req != NULL);
1182 
1183 	nvmf_rdma_qpair_queue_send_wrs(rqpair, &rdma_req->data.wr);
1184 	rqpair->current_read_depth += rdma_req->num_outstanding_data_wr;
1185 	rqpair->current_send_depth += rdma_req->num_outstanding_data_wr;
1186 	return 0;
1187 }
1188 
1189 static int
1190 request_transfer_out(struct spdk_nvmf_request *req, int *data_posted)
1191 {
1192 	int				num_outstanding_data_wr = 0;
1193 	struct spdk_nvmf_rdma_request	*rdma_req;
1194 	struct spdk_nvmf_qpair		*qpair;
1195 	struct spdk_nvmf_rdma_qpair	*rqpair;
1196 	struct spdk_nvme_cpl		*rsp;
1197 	struct ibv_send_wr		*first = NULL;
1198 
1199 	*data_posted = 0;
1200 	qpair = req->qpair;
1201 	rsp = &req->rsp->nvme_cpl;
1202 	rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
1203 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
1204 
1205 	/* Advance our sq_head pointer */
1206 	if (qpair->sq_head == qpair->sq_head_max) {
1207 		qpair->sq_head = 0;
1208 	} else {
1209 		qpair->sq_head++;
1210 	}
1211 	rsp->sqhd = qpair->sq_head;
1212 
1213 	/* queue the capsule for the recv buffer */
1214 	assert(rdma_req->recv != NULL);
1215 
1216 	nvmf_rdma_qpair_queue_recv_wrs(rqpair, &rdma_req->recv->wr);
1217 
1218 	rdma_req->recv = NULL;
1219 	assert(rqpair->current_recv_depth > 0);
1220 	rqpair->current_recv_depth--;
1221 
1222 	/* Build the response which consists of optional
1223 	 * RDMA WRITEs to transfer data, plus an RDMA SEND
1224 	 * containing the response.
1225 	 */
1226 	first = &rdma_req->rsp.wr;
1227 
1228 	if (rsp->status.sc == SPDK_NVME_SC_SUCCESS &&
1229 	    req->xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
1230 		first = &rdma_req->data.wr;
1231 		*data_posted = 1;
1232 		num_outstanding_data_wr = rdma_req->num_outstanding_data_wr;
1233 	}
1234 	nvmf_rdma_qpair_queue_send_wrs(rqpair, first);
1235 	/* +1 for the rsp wr */
1236 	rqpair->current_send_depth += num_outstanding_data_wr + 1;
1237 
1238 	return 0;
1239 }
1240 
1241 static int
1242 spdk_nvmf_rdma_event_accept(struct rdma_cm_id *id, struct spdk_nvmf_rdma_qpair *rqpair)
1243 {
1244 	struct spdk_nvmf_rdma_accept_private_data	accept_data;
1245 	struct rdma_conn_param				ctrlr_event_data = {};
1246 	int						rc;
1247 
1248 	accept_data.recfmt = 0;
1249 	accept_data.crqsize = rqpair->max_queue_depth;
1250 
1251 	ctrlr_event_data.private_data = &accept_data;
1252 	ctrlr_event_data.private_data_len = sizeof(accept_data);
1253 	if (id->ps == RDMA_PS_TCP) {
1254 		ctrlr_event_data.responder_resources = 0; /* We accept 0 reads from the host */
1255 		ctrlr_event_data.initiator_depth = rqpair->max_read_depth;
1256 	}
1257 
1258 	/* Configure infinite retries for the initiator side qpair.
1259 	 * When using a shared receive queue on the target side,
1260 	 * we need to pass this value to the initiator to prevent the
1261 	 * initiator side NIC from completing SEND requests back to the
1262 	 * initiator with status rnr_retry_count_exceeded. */
1263 	if (rqpair->srq != NULL) {
1264 		ctrlr_event_data.rnr_retry_count = 0x7;
1265 	}
1266 
1267 	rc = rdma_accept(id, &ctrlr_event_data);
1268 	if (rc) {
1269 		SPDK_ERRLOG("Error %d on rdma_accept\n", errno);
1270 	} else {
1271 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Sent back the accept\n");
1272 	}
1273 
1274 	return rc;
1275 }
1276 
1277 static void
1278 spdk_nvmf_rdma_event_reject(struct rdma_cm_id *id, enum spdk_nvmf_rdma_transport_error error)
1279 {
1280 	struct spdk_nvmf_rdma_reject_private_data	rej_data;
1281 
1282 	rej_data.recfmt = 0;
1283 	rej_data.sts = error;
1284 
1285 	rdma_reject(id, &rej_data, sizeof(rej_data));
1286 }
1287 
1288 static int
1289 nvmf_rdma_connect(struct spdk_nvmf_transport *transport, struct rdma_cm_event *event,
1290 		  new_qpair_fn cb_fn, void *cb_arg)
1291 {
1292 	struct spdk_nvmf_rdma_transport *rtransport;
1293 	struct spdk_nvmf_rdma_qpair	*rqpair = NULL;
1294 	struct spdk_nvmf_rdma_port	*port;
1295 	struct rdma_conn_param		*rdma_param = NULL;
1296 	const struct spdk_nvmf_rdma_request_private_data *private_data = NULL;
1297 	uint16_t			max_queue_depth;
1298 	uint16_t			max_read_depth;
1299 
1300 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
1301 
1302 	assert(event->id != NULL); /* Impossible. Can't even reject the connection. */
1303 	assert(event->id->verbs != NULL); /* Impossible. No way to handle this. */
1304 
1305 	rdma_param = &event->param.conn;
1306 	if (rdma_param->private_data == NULL ||
1307 	    rdma_param->private_data_len < sizeof(struct spdk_nvmf_rdma_request_private_data)) {
1308 		SPDK_ERRLOG("connect request: no private data provided\n");
1309 		spdk_nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_INVALID_PRIVATE_DATA_LENGTH);
1310 		return -1;
1311 	}
1312 
1313 	private_data = rdma_param->private_data;
1314 	if (private_data->recfmt != 0) {
1315 		SPDK_ERRLOG("Received RDMA private data with RECFMT != 0\n");
1316 		spdk_nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_INVALID_RECFMT);
1317 		return -1;
1318 	}
1319 
1320 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Connect Recv on fabric intf name %s, dev_name %s\n",
1321 		      event->id->verbs->device->name, event->id->verbs->device->dev_name);
1322 
1323 	port = event->listen_id->context;
1324 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Listen Id was %p with verbs %p. ListenAddr: %p\n",
1325 		      event->listen_id, event->listen_id->verbs, port);
1326 
1327 	/* Figure out the supported queue depth. This is a multi-step process
1328 	 * that takes into account hardware maximums, host provided values,
1329 	 * and our target's internal memory limits */
1330 
1331 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Calculating Queue Depth\n");
1332 
1333 	/* Start with the maximum queue depth allowed by the target */
1334 	max_queue_depth = rtransport->transport.opts.max_queue_depth;
1335 	max_read_depth = rtransport->transport.opts.max_queue_depth;
1336 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Target Max Queue Depth: %d\n",
1337 		      rtransport->transport.opts.max_queue_depth);
1338 
1339 	/* Next check the local NIC's hardware limitations */
1340 	SPDK_DEBUGLOG(SPDK_LOG_RDMA,
1341 		      "Local NIC Max Send/Recv Queue Depth: %d Max Read/Write Queue Depth: %d\n",
1342 		      port->device->attr.max_qp_wr, port->device->attr.max_qp_rd_atom);
1343 	max_queue_depth = spdk_min(max_queue_depth, port->device->attr.max_qp_wr);
1344 	max_read_depth = spdk_min(max_read_depth, port->device->attr.max_qp_init_rd_atom);
1345 
1346 	/* Next check the remote NIC's hardware limitations */
1347 	SPDK_DEBUGLOG(SPDK_LOG_RDMA,
1348 		      "Host (Initiator) NIC Max Incoming RDMA R/W operations: %d Max Outgoing RDMA R/W operations: %d\n",
1349 		      rdma_param->initiator_depth, rdma_param->responder_resources);
1350 	if (rdma_param->initiator_depth > 0) {
1351 		max_read_depth = spdk_min(max_read_depth, rdma_param->initiator_depth);
1352 	}
1353 
1354 	/* Finally check for the host software requested values, which are
1355 	 * optional. */
1356 	if (rdma_param->private_data != NULL &&
1357 	    rdma_param->private_data_len >= sizeof(struct spdk_nvmf_rdma_request_private_data)) {
1358 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Host Receive Queue Size: %d\n", private_data->hrqsize);
1359 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Host Send Queue Size: %d\n", private_data->hsqsize);
1360 		max_queue_depth = spdk_min(max_queue_depth, private_data->hrqsize);
1361 		max_queue_depth = spdk_min(max_queue_depth, private_data->hsqsize + 1);
1362 	}
1363 
1364 	SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Final Negotiated Queue Depth: %d R/W Depth: %d\n",
1365 		      max_queue_depth, max_read_depth);
1366 
1367 	rqpair = calloc(1, sizeof(struct spdk_nvmf_rdma_qpair));
1368 	if (rqpair == NULL) {
1369 		SPDK_ERRLOG("Could not allocate new connection.\n");
1370 		spdk_nvmf_rdma_event_reject(event->id, SPDK_NVMF_RDMA_ERROR_NO_RESOURCES);
1371 		return -1;
1372 	}
1373 
1374 	rqpair->device = port->device;
1375 	rqpair->max_queue_depth = max_queue_depth;
1376 	rqpair->max_read_depth = max_read_depth;
1377 	rqpair->cm_id = event->id;
1378 	rqpair->listen_id = event->listen_id;
1379 	rqpair->qpair.transport = transport;
1380 	STAILQ_INIT(&rqpair->ibv_events);
1381 	/* use qid from the private data to determine the qpair type
1382 	   qid will be set to the appropriate value when the controller is created */
1383 	rqpair->qpair.qid = private_data->qid;
1384 
1385 	event->id->context = &rqpair->qpair;
1386 
1387 	cb_fn(&rqpair->qpair, cb_arg);
1388 
1389 	return 0;
1390 }
1391 
1392 static int
1393 spdk_nvmf_rdma_mem_notify(void *cb_ctx, struct spdk_mem_map *map,
1394 			  enum spdk_mem_map_notify_action action,
1395 			  void *vaddr, size_t size)
1396 {
1397 	struct ibv_pd *pd = cb_ctx;
1398 	struct ibv_mr *mr;
1399 	int rc;
1400 
1401 	switch (action) {
1402 	case SPDK_MEM_MAP_NOTIFY_REGISTER:
1403 		if (!g_nvmf_hooks.get_rkey) {
1404 			mr = ibv_reg_mr(pd, vaddr, size,
1405 					IBV_ACCESS_LOCAL_WRITE |
1406 					IBV_ACCESS_REMOTE_READ |
1407 					IBV_ACCESS_REMOTE_WRITE);
1408 			if (mr == NULL) {
1409 				SPDK_ERRLOG("ibv_reg_mr() failed\n");
1410 				return -1;
1411 			} else {
1412 				rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, size, (uint64_t)mr);
1413 			}
1414 		} else {
1415 			rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, size,
1416 							  g_nvmf_hooks.get_rkey(pd, vaddr, size));
1417 		}
1418 		break;
1419 	case SPDK_MEM_MAP_NOTIFY_UNREGISTER:
1420 		if (!g_nvmf_hooks.get_rkey) {
1421 			mr = (struct ibv_mr *)spdk_mem_map_translate(map, (uint64_t)vaddr, NULL);
1422 			if (mr) {
1423 				ibv_dereg_mr(mr);
1424 			}
1425 		}
1426 		rc = spdk_mem_map_clear_translation(map, (uint64_t)vaddr, size);
1427 		break;
1428 	default:
1429 		SPDK_UNREACHABLE();
1430 	}
1431 
1432 	return rc;
1433 }
1434 
1435 static int
1436 spdk_nvmf_rdma_check_contiguous_entries(uint64_t addr_1, uint64_t addr_2)
1437 {
1438 	/* Two contiguous mappings will point to the same address which is the start of the RDMA MR. */
1439 	return addr_1 == addr_2;
1440 }
1441 
1442 static inline void
1443 nvmf_rdma_setup_wr(struct ibv_send_wr *wr, struct ibv_send_wr *next,
1444 		   enum spdk_nvme_data_transfer xfer)
1445 {
1446 	if (xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
1447 		wr->opcode = IBV_WR_RDMA_WRITE;
1448 		wr->send_flags = 0;
1449 		wr->next = next;
1450 	} else if (xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER) {
1451 		wr->opcode = IBV_WR_RDMA_READ;
1452 		wr->send_flags = IBV_SEND_SIGNALED;
1453 		wr->next = NULL;
1454 	} else {
1455 		assert(0);
1456 	}
1457 }
1458 
1459 static int
1460 nvmf_request_alloc_wrs(struct spdk_nvmf_rdma_transport *rtransport,
1461 		       struct spdk_nvmf_rdma_request *rdma_req,
1462 		       uint32_t num_sgl_descriptors)
1463 {
1464 	struct spdk_nvmf_rdma_request_data	*work_requests[SPDK_NVMF_MAX_SGL_ENTRIES];
1465 	struct spdk_nvmf_rdma_request_data	*current_data_wr;
1466 	uint32_t				i;
1467 
1468 	if (num_sgl_descriptors > SPDK_NVMF_MAX_SGL_ENTRIES) {
1469 		SPDK_ERRLOG("Requested too much entries (%u), the limit is %u\n",
1470 			    num_sgl_descriptors, SPDK_NVMF_MAX_SGL_ENTRIES);
1471 		return -EINVAL;
1472 	}
1473 
1474 	if (spdk_mempool_get_bulk(rtransport->data_wr_pool, (void **)work_requests, num_sgl_descriptors)) {
1475 		return -ENOMEM;
1476 	}
1477 
1478 	current_data_wr = &rdma_req->data;
1479 
1480 	for (i = 0; i < num_sgl_descriptors; i++) {
1481 		nvmf_rdma_setup_wr(&current_data_wr->wr, &work_requests[i]->wr, rdma_req->req.xfer);
1482 		current_data_wr->wr.next = &work_requests[i]->wr;
1483 		current_data_wr = work_requests[i];
1484 		current_data_wr->wr.sg_list = current_data_wr->sgl;
1485 		current_data_wr->wr.wr_id = rdma_req->data.wr.wr_id;
1486 	}
1487 
1488 	nvmf_rdma_setup_wr(&current_data_wr->wr, &rdma_req->rsp.wr, rdma_req->req.xfer);
1489 
1490 	return 0;
1491 }
1492 
1493 static inline void
1494 nvmf_rdma_setup_request(struct spdk_nvmf_rdma_request *rdma_req)
1495 {
1496 	struct ibv_send_wr		*wr = &rdma_req->data.wr;
1497 	struct spdk_nvme_sgl_descriptor	*sgl = &rdma_req->req.cmd->nvme_cmd.dptr.sgl1;
1498 
1499 	wr->wr.rdma.rkey = sgl->keyed.key;
1500 	wr->wr.rdma.remote_addr = sgl->address;
1501 	nvmf_rdma_setup_wr(wr, &rdma_req->rsp.wr, rdma_req->req.xfer);
1502 }
1503 
1504 static inline void
1505 nvmf_rdma_update_remote_addr(struct spdk_nvmf_rdma_request *rdma_req, uint32_t num_wrs)
1506 {
1507 	struct ibv_send_wr		*wr = &rdma_req->data.wr;
1508 	struct spdk_nvme_sgl_descriptor	*sgl = &rdma_req->req.cmd->nvme_cmd.dptr.sgl1;
1509 	uint32_t			i;
1510 	int				j;
1511 	uint64_t			remote_addr_offset = 0;
1512 
1513 	for (i = 0; i < num_wrs; ++i) {
1514 		wr->wr.rdma.rkey = sgl->keyed.key;
1515 		wr->wr.rdma.remote_addr = sgl->address + remote_addr_offset;
1516 		for (j = 0; j < wr->num_sge; ++j) {
1517 			remote_addr_offset += wr->sg_list[j].length;
1518 		}
1519 		wr = wr->next;
1520 	}
1521 }
1522 
1523 /* This function is used in the rare case that we have a buffer split over multiple memory regions. */
1524 static int
1525 nvmf_rdma_replace_buffer(struct spdk_nvmf_rdma_poll_group *rgroup, void **buf)
1526 {
1527 	struct spdk_nvmf_transport_poll_group	*group = &rgroup->group;
1528 	struct spdk_nvmf_transport		*transport = group->transport;
1529 	struct spdk_nvmf_transport_pg_cache_buf	*old_buf;
1530 	void					*new_buf;
1531 
1532 	if (!(STAILQ_EMPTY(&group->buf_cache))) {
1533 		group->buf_cache_count--;
1534 		new_buf = STAILQ_FIRST(&group->buf_cache);
1535 		STAILQ_REMOVE_HEAD(&group->buf_cache, link);
1536 		assert(*buf != NULL);
1537 	} else {
1538 		new_buf = spdk_mempool_get(transport->data_buf_pool);
1539 	}
1540 
1541 	if (*buf == NULL) {
1542 		return -ENOMEM;
1543 	}
1544 
1545 	old_buf = *buf;
1546 	STAILQ_INSERT_HEAD(&rgroup->retired_bufs, old_buf, link);
1547 	*buf = new_buf;
1548 	return 0;
1549 }
1550 
1551 static bool
1552 nvmf_rdma_get_lkey(struct spdk_nvmf_rdma_device *device, struct iovec *iov,
1553 		   uint32_t *_lkey)
1554 {
1555 	uint64_t	translation_len;
1556 	uint32_t	lkey;
1557 
1558 	translation_len = iov->iov_len;
1559 
1560 	if (!g_nvmf_hooks.get_rkey) {
1561 		lkey = ((struct ibv_mr *)spdk_mem_map_translate(device->map,
1562 				(uint64_t)iov->iov_base, &translation_len))->lkey;
1563 	} else {
1564 		lkey = spdk_mem_map_translate(device->map,
1565 					      (uint64_t)iov->iov_base, &translation_len);
1566 	}
1567 
1568 	if (spdk_unlikely(translation_len < iov->iov_len)) {
1569 		return false;
1570 	}
1571 
1572 	*_lkey = lkey;
1573 	return true;
1574 }
1575 
1576 static bool
1577 nvmf_rdma_fill_wr_sge(struct spdk_nvmf_rdma_device *device,
1578 		      struct iovec *iov, struct ibv_send_wr **_wr,
1579 		      uint32_t *_remaining_data_block, uint32_t *_offset,
1580 		      uint32_t *_num_extra_wrs,
1581 		      const struct spdk_dif_ctx *dif_ctx)
1582 {
1583 	struct ibv_send_wr *wr = *_wr;
1584 	struct ibv_sge	*sg_ele = &wr->sg_list[wr->num_sge];
1585 	uint32_t	lkey = 0;
1586 	uint32_t	remaining, data_block_size, md_size, sge_len;
1587 
1588 	if (spdk_unlikely(!nvmf_rdma_get_lkey(device, iov, &lkey))) {
1589 		/* This is a very rare case that can occur when using DPDK version < 19.05 */
1590 		SPDK_ERRLOG("Data buffer split over multiple RDMA Memory Regions. Removing it from circulation.\n");
1591 		return false;
1592 	}
1593 
1594 	if (spdk_likely(!dif_ctx)) {
1595 		sg_ele->lkey = lkey;
1596 		sg_ele->addr = (uintptr_t)(iov->iov_base);
1597 		sg_ele->length = iov->iov_len;
1598 		wr->num_sge++;
1599 	} else {
1600 		remaining = iov->iov_len - *_offset;
1601 		data_block_size = dif_ctx->block_size - dif_ctx->md_size;
1602 		md_size = dif_ctx->md_size;
1603 
1604 		while (remaining) {
1605 			if (wr->num_sge >= SPDK_NVMF_MAX_SGL_ENTRIES) {
1606 				if (*_num_extra_wrs > 0 && wr->next) {
1607 					*_wr = wr->next;
1608 					wr = *_wr;
1609 					wr->num_sge = 0;
1610 					sg_ele = &wr->sg_list[wr->num_sge];
1611 					(*_num_extra_wrs)--;
1612 				} else {
1613 					break;
1614 				}
1615 			}
1616 			sg_ele->lkey = lkey;
1617 			sg_ele->addr = (uintptr_t)((char *)iov->iov_base + *_offset);
1618 			sge_len = spdk_min(remaining, *_remaining_data_block);
1619 			sg_ele->length = sge_len;
1620 			remaining -= sge_len;
1621 			*_remaining_data_block -= sge_len;
1622 			*_offset += sge_len;
1623 
1624 			sg_ele++;
1625 			wr->num_sge++;
1626 
1627 			if (*_remaining_data_block == 0) {
1628 				/* skip metadata */
1629 				*_offset += md_size;
1630 				/* Metadata that do not fit this IO buffer will be included in the next IO buffer */
1631 				remaining -= spdk_min(remaining, md_size);
1632 				*_remaining_data_block = data_block_size;
1633 			}
1634 
1635 			if (remaining == 0) {
1636 				/* By subtracting the size of the last IOV from the offset, we ensure that we skip
1637 				   the remaining metadata bits at the beginning of the next buffer */
1638 				*_offset -= iov->iov_len;
1639 			}
1640 		}
1641 	}
1642 
1643 	return true;
1644 }
1645 
1646 static int
1647 nvmf_rdma_fill_wr_sgl(struct spdk_nvmf_rdma_poll_group *rgroup,
1648 		      struct spdk_nvmf_rdma_device *device,
1649 		      struct spdk_nvmf_rdma_request *rdma_req,
1650 		      struct ibv_send_wr *wr,
1651 		      uint32_t length,
1652 		      uint32_t num_extra_wrs)
1653 {
1654 	struct spdk_nvmf_request *req = &rdma_req->req;
1655 	struct spdk_dif_ctx *dif_ctx = NULL;
1656 	uint32_t remaining_data_block = 0;
1657 	uint32_t offset = 0;
1658 
1659 	if (spdk_unlikely(rdma_req->req.dif.dif_insert_or_strip)) {
1660 		dif_ctx = &rdma_req->req.dif.dif_ctx;
1661 		remaining_data_block = dif_ctx->block_size - dif_ctx->md_size;
1662 	}
1663 
1664 	wr->num_sge = 0;
1665 
1666 	while (length && (num_extra_wrs || wr->num_sge < SPDK_NVMF_MAX_SGL_ENTRIES)) {
1667 		while (spdk_unlikely(!nvmf_rdma_fill_wr_sge(device, &req->iov[rdma_req->iovpos], &wr,
1668 				     &remaining_data_block, &offset, &num_extra_wrs, dif_ctx))) {
1669 			if (nvmf_rdma_replace_buffer(rgroup, &req->buffers[rdma_req->iovpos]) == -ENOMEM) {
1670 				return -ENOMEM;
1671 			}
1672 			req->iov[rdma_req->iovpos].iov_base = (void *)((uintptr_t)(req->buffers[rdma_req->iovpos] +
1673 							      NVMF_DATA_BUFFER_MASK) &
1674 							      ~NVMF_DATA_BUFFER_MASK);
1675 		}
1676 
1677 		length -= req->iov[rdma_req->iovpos].iov_len;
1678 		rdma_req->iovpos++;
1679 	}
1680 
1681 	if (length) {
1682 		SPDK_ERRLOG("Not enough SG entries to hold data buffer\n");
1683 		return -EINVAL;
1684 	}
1685 
1686 	return 0;
1687 }
1688 
1689 static inline uint32_t
1690 nvmf_rdma_calc_num_wrs(uint32_t length, uint32_t io_unit_size, uint32_t block_size)
1691 {
1692 	/* estimate the number of SG entries and WRs needed to process the request */
1693 	uint32_t num_sge = 0;
1694 	uint32_t i;
1695 	uint32_t num_buffers = SPDK_CEIL_DIV(length, io_unit_size);
1696 
1697 	for (i = 0; i < num_buffers && length > 0; i++) {
1698 		uint32_t buffer_len = spdk_min(length, io_unit_size);
1699 		uint32_t num_sge_in_block = SPDK_CEIL_DIV(buffer_len, block_size);
1700 
1701 		if (num_sge_in_block * block_size > buffer_len) {
1702 			++num_sge_in_block;
1703 		}
1704 		num_sge += num_sge_in_block;
1705 		length -= buffer_len;
1706 	}
1707 	return SPDK_CEIL_DIV(num_sge, SPDK_NVMF_MAX_SGL_ENTRIES);
1708 }
1709 
1710 static int
1711 spdk_nvmf_rdma_request_fill_iovs(struct spdk_nvmf_rdma_transport *rtransport,
1712 				 struct spdk_nvmf_rdma_device *device,
1713 				 struct spdk_nvmf_rdma_request *rdma_req,
1714 				 uint32_t length)
1715 {
1716 	struct spdk_nvmf_rdma_qpair		*rqpair;
1717 	struct spdk_nvmf_rdma_poll_group	*rgroup;
1718 	struct spdk_nvmf_request		*req = &rdma_req->req;
1719 	struct ibv_send_wr			*wr = &rdma_req->data.wr;
1720 	int					rc;
1721 	uint32_t				num_wrs = 1;
1722 
1723 	rqpair = SPDK_CONTAINEROF(req->qpair, struct spdk_nvmf_rdma_qpair, qpair);
1724 	rgroup = rqpair->poller->group;
1725 
1726 	/* rdma wr specifics */
1727 	nvmf_rdma_setup_request(rdma_req);
1728 
1729 	rc = spdk_nvmf_request_get_buffers(req, &rgroup->group, &rtransport->transport,
1730 					   length);
1731 	if (rc != 0) {
1732 		return rc;
1733 	}
1734 
1735 	assert(req->iovcnt <= rqpair->max_send_sge);
1736 
1737 	rdma_req->iovpos = 0;
1738 
1739 	if (spdk_unlikely(req->dif.dif_insert_or_strip)) {
1740 		num_wrs = nvmf_rdma_calc_num_wrs(length, rtransport->transport.opts.io_unit_size,
1741 						 req->dif.dif_ctx.block_size);
1742 		if (num_wrs > 1) {
1743 			rc = nvmf_request_alloc_wrs(rtransport, rdma_req, num_wrs - 1);
1744 			if (rc != 0) {
1745 				goto err_exit;
1746 			}
1747 		}
1748 	}
1749 
1750 	rc = nvmf_rdma_fill_wr_sgl(rgroup, device, rdma_req, wr, length, num_wrs - 1);
1751 	if (spdk_unlikely(rc != 0)) {
1752 		goto err_exit;
1753 	}
1754 
1755 	if (spdk_unlikely(num_wrs > 1)) {
1756 		nvmf_rdma_update_remote_addr(rdma_req, num_wrs);
1757 	}
1758 
1759 	/* set the number of outstanding data WRs for this request. */
1760 	rdma_req->num_outstanding_data_wr = num_wrs;
1761 
1762 	return rc;
1763 
1764 err_exit:
1765 	spdk_nvmf_request_free_buffers(req, &rgroup->group, &rtransport->transport);
1766 	nvmf_rdma_request_free_data(rdma_req, rtransport);
1767 	req->iovcnt = 0;
1768 	return rc;
1769 }
1770 
1771 static int
1772 nvmf_rdma_request_fill_iovs_multi_sgl(struct spdk_nvmf_rdma_transport *rtransport,
1773 				      struct spdk_nvmf_rdma_device *device,
1774 				      struct spdk_nvmf_rdma_request *rdma_req)
1775 {
1776 	struct spdk_nvmf_rdma_qpair		*rqpair;
1777 	struct spdk_nvmf_rdma_poll_group	*rgroup;
1778 	struct ibv_send_wr			*current_wr;
1779 	struct spdk_nvmf_request		*req = &rdma_req->req;
1780 	struct spdk_nvme_sgl_descriptor		*inline_segment, *desc;
1781 	uint32_t				num_sgl_descriptors;
1782 	uint32_t				lengths[SPDK_NVMF_MAX_SGL_ENTRIES];
1783 	uint32_t				i;
1784 	int					rc;
1785 
1786 	rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
1787 	rgroup = rqpair->poller->group;
1788 
1789 	inline_segment = &req->cmd->nvme_cmd.dptr.sgl1;
1790 	assert(inline_segment->generic.type == SPDK_NVME_SGL_TYPE_LAST_SEGMENT);
1791 	assert(inline_segment->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET);
1792 
1793 	num_sgl_descriptors = inline_segment->unkeyed.length / sizeof(struct spdk_nvme_sgl_descriptor);
1794 	assert(num_sgl_descriptors <= SPDK_NVMF_MAX_SGL_ENTRIES);
1795 
1796 	if (nvmf_request_alloc_wrs(rtransport, rdma_req, num_sgl_descriptors - 1) != 0) {
1797 		return -ENOMEM;
1798 	}
1799 
1800 	desc = (struct spdk_nvme_sgl_descriptor *)rdma_req->recv->buf + inline_segment->address;
1801 	for (i = 0; i < num_sgl_descriptors; i++) {
1802 		if (spdk_likely(!req->dif.dif_insert_or_strip)) {
1803 			lengths[i] = desc->keyed.length;
1804 		} else {
1805 			req->dif.orig_length += desc->keyed.length;
1806 			lengths[i] = spdk_dif_get_length_with_md(desc->keyed.length, &req->dif.dif_ctx);
1807 			req->dif.elba_length += lengths[i];
1808 		}
1809 		desc++;
1810 	}
1811 
1812 	rc = spdk_nvmf_request_get_buffers_multi(req, &rgroup->group, &rtransport->transport,
1813 			lengths, num_sgl_descriptors);
1814 	if (rc != 0) {
1815 		nvmf_rdma_request_free_data(rdma_req, rtransport);
1816 		return rc;
1817 	}
1818 
1819 	/* The first WR must always be the embedded data WR. This is how we unwind them later. */
1820 	current_wr = &rdma_req->data.wr;
1821 	assert(current_wr != NULL);
1822 
1823 	req->length = 0;
1824 	rdma_req->iovpos = 0;
1825 	desc = (struct spdk_nvme_sgl_descriptor *)rdma_req->recv->buf + inline_segment->address;
1826 	for (i = 0; i < num_sgl_descriptors; i++) {
1827 		/* The descriptors must be keyed data block descriptors with an address, not an offset. */
1828 		if (spdk_unlikely(desc->generic.type != SPDK_NVME_SGL_TYPE_KEYED_DATA_BLOCK ||
1829 				  desc->keyed.subtype != SPDK_NVME_SGL_SUBTYPE_ADDRESS)) {
1830 			rc = -EINVAL;
1831 			goto err_exit;
1832 		}
1833 
1834 		current_wr->num_sge = 0;
1835 
1836 		rc = nvmf_rdma_fill_wr_sgl(rgroup, device, rdma_req, current_wr, lengths[i], 0);
1837 		if (rc != 0) {
1838 			rc = -ENOMEM;
1839 			goto err_exit;
1840 		}
1841 
1842 		req->length += desc->keyed.length;
1843 		current_wr->wr.rdma.rkey = desc->keyed.key;
1844 		current_wr->wr.rdma.remote_addr = desc->address;
1845 		current_wr = current_wr->next;
1846 		desc++;
1847 	}
1848 
1849 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
1850 	/* Go back to the last descriptor in the list. */
1851 	desc--;
1852 	if ((device->attr.device_cap_flags & IBV_DEVICE_MEM_MGT_EXTENSIONS) != 0) {
1853 		if (desc->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_INVALIDATE_KEY) {
1854 			rdma_req->rsp.wr.opcode = IBV_WR_SEND_WITH_INV;
1855 			rdma_req->rsp.wr.imm_data = desc->keyed.key;
1856 		}
1857 	}
1858 #endif
1859 
1860 	rdma_req->num_outstanding_data_wr = num_sgl_descriptors;
1861 
1862 	return 0;
1863 
1864 err_exit:
1865 	spdk_nvmf_request_free_buffers(req, &rgroup->group, &rtransport->transport);
1866 	nvmf_rdma_request_free_data(rdma_req, rtransport);
1867 	return rc;
1868 }
1869 
1870 static int
1871 spdk_nvmf_rdma_request_parse_sgl(struct spdk_nvmf_rdma_transport *rtransport,
1872 				 struct spdk_nvmf_rdma_device *device,
1873 				 struct spdk_nvmf_rdma_request *rdma_req)
1874 {
1875 	struct spdk_nvmf_request		*req = &rdma_req->req;
1876 	struct spdk_nvme_cpl			*rsp;
1877 	struct spdk_nvme_sgl_descriptor		*sgl;
1878 	int					rc;
1879 	uint32_t				length;
1880 
1881 	rsp = &req->rsp->nvme_cpl;
1882 	sgl = &req->cmd->nvme_cmd.dptr.sgl1;
1883 
1884 	if (sgl->generic.type == SPDK_NVME_SGL_TYPE_KEYED_DATA_BLOCK &&
1885 	    (sgl->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_ADDRESS ||
1886 	     sgl->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_INVALIDATE_KEY)) {
1887 
1888 		length = sgl->keyed.length;
1889 		if (length > rtransport->transport.opts.max_io_size) {
1890 			SPDK_ERRLOG("SGL length 0x%x exceeds max io size 0x%x\n",
1891 				    length, rtransport->transport.opts.max_io_size);
1892 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1893 			return -1;
1894 		}
1895 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
1896 		if ((device->attr.device_cap_flags & IBV_DEVICE_MEM_MGT_EXTENSIONS) != 0) {
1897 			if (sgl->keyed.subtype == SPDK_NVME_SGL_SUBTYPE_INVALIDATE_KEY) {
1898 				rdma_req->rsp.wr.opcode = IBV_WR_SEND_WITH_INV;
1899 				rdma_req->rsp.wr.imm_data = sgl->keyed.key;
1900 			}
1901 		}
1902 #endif
1903 
1904 		/* fill request length and populate iovs */
1905 		req->length = length;
1906 
1907 		if (spdk_unlikely(req->dif.dif_insert_or_strip)) {
1908 			req->dif.orig_length = length;
1909 			length = spdk_dif_get_length_with_md(length, &req->dif.dif_ctx);
1910 			req->dif.elba_length = length;
1911 		}
1912 
1913 		rc = spdk_nvmf_rdma_request_fill_iovs(rtransport, device, rdma_req, length);
1914 		if (spdk_unlikely(rc < 0)) {
1915 			if (rc == -EINVAL) {
1916 				SPDK_ERRLOG("SGL length exceeds the max I/O size\n");
1917 				rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1918 				return -1;
1919 			}
1920 			/* No available buffers. Queue this request up. */
1921 			SPDK_DEBUGLOG(SPDK_LOG_RDMA, "No available large data buffers. Queueing request %p\n", rdma_req);
1922 			return 0;
1923 		}
1924 
1925 		/* backward compatible */
1926 		req->data = req->iov[0].iov_base;
1927 
1928 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Request %p took %d buffer/s from central pool\n", rdma_req,
1929 			      req->iovcnt);
1930 
1931 		return 0;
1932 	} else if (sgl->generic.type == SPDK_NVME_SGL_TYPE_DATA_BLOCK &&
1933 		   sgl->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET) {
1934 		uint64_t offset = sgl->address;
1935 		uint32_t max_len = rtransport->transport.opts.in_capsule_data_size;
1936 
1937 		SPDK_DEBUGLOG(SPDK_LOG_NVMF, "In-capsule data: offset 0x%" PRIx64 ", length 0x%x\n",
1938 			      offset, sgl->unkeyed.length);
1939 
1940 		if (offset > max_len) {
1941 			SPDK_ERRLOG("In-capsule offset 0x%" PRIx64 " exceeds capsule length 0x%x\n",
1942 				    offset, max_len);
1943 			rsp->status.sc = SPDK_NVME_SC_INVALID_SGL_OFFSET;
1944 			return -1;
1945 		}
1946 		max_len -= (uint32_t)offset;
1947 
1948 		if (sgl->unkeyed.length > max_len) {
1949 			SPDK_ERRLOG("In-capsule data length 0x%x exceeds capsule length 0x%x\n",
1950 				    sgl->unkeyed.length, max_len);
1951 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1952 			return -1;
1953 		}
1954 
1955 		rdma_req->num_outstanding_data_wr = 0;
1956 		req->data = rdma_req->recv->buf + offset;
1957 		req->data_from_pool = false;
1958 		req->length = sgl->unkeyed.length;
1959 
1960 		req->iov[0].iov_base = req->data;
1961 		req->iov[0].iov_len = req->length;
1962 		req->iovcnt = 1;
1963 
1964 		return 0;
1965 	} else if (sgl->generic.type == SPDK_NVME_SGL_TYPE_LAST_SEGMENT &&
1966 		   sgl->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET) {
1967 
1968 		rc = nvmf_rdma_request_fill_iovs_multi_sgl(rtransport, device, rdma_req);
1969 		if (rc == -ENOMEM) {
1970 			SPDK_DEBUGLOG(SPDK_LOG_RDMA, "No available large data buffers. Queueing request %p\n", rdma_req);
1971 			return 0;
1972 		} else if (rc == -EINVAL) {
1973 			SPDK_ERRLOG("Multi SGL element request length exceeds the max I/O size\n");
1974 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
1975 			return -1;
1976 		}
1977 
1978 		/* backward compatible */
1979 		req->data = req->iov[0].iov_base;
1980 
1981 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Request %p took %d buffer/s from central pool\n", rdma_req,
1982 			      req->iovcnt);
1983 
1984 		return 0;
1985 	}
1986 
1987 	SPDK_ERRLOG("Invalid NVMf I/O Command SGL:  Type 0x%x, Subtype 0x%x\n",
1988 		    sgl->generic.type, sgl->generic.subtype);
1989 	rsp->status.sc = SPDK_NVME_SC_SGL_DESCRIPTOR_TYPE_INVALID;
1990 	return -1;
1991 }
1992 
1993 static void
1994 nvmf_rdma_request_free(struct spdk_nvmf_rdma_request *rdma_req,
1995 		       struct spdk_nvmf_rdma_transport	*rtransport)
1996 {
1997 	struct spdk_nvmf_rdma_qpair		*rqpair;
1998 	struct spdk_nvmf_rdma_poll_group	*rgroup;
1999 
2000 	rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
2001 	if (rdma_req->req.data_from_pool) {
2002 		rgroup = rqpair->poller->group;
2003 
2004 		spdk_nvmf_request_free_buffers(&rdma_req->req, &rgroup->group, &rtransport->transport);
2005 	}
2006 	nvmf_rdma_request_free_data(rdma_req, rtransport);
2007 	rdma_req->req.length = 0;
2008 	rdma_req->req.iovcnt = 0;
2009 	rdma_req->req.data = NULL;
2010 	rdma_req->rsp.wr.next = NULL;
2011 	rdma_req->data.wr.next = NULL;
2012 	memset(&rdma_req->req.dif, 0, sizeof(rdma_req->req.dif));
2013 	rqpair->qd--;
2014 
2015 	STAILQ_INSERT_HEAD(&rqpair->resources->free_queue, rdma_req, state_link);
2016 	rdma_req->state = RDMA_REQUEST_STATE_FREE;
2017 }
2018 
2019 bool
2020 spdk_nvmf_rdma_request_process(struct spdk_nvmf_rdma_transport *rtransport,
2021 			       struct spdk_nvmf_rdma_request *rdma_req)
2022 {
2023 	struct spdk_nvmf_rdma_qpair	*rqpair;
2024 	struct spdk_nvmf_rdma_device	*device;
2025 	struct spdk_nvmf_rdma_poll_group *rgroup;
2026 	struct spdk_nvme_cpl		*rsp = &rdma_req->req.rsp->nvme_cpl;
2027 	int				rc;
2028 	struct spdk_nvmf_rdma_recv	*rdma_recv;
2029 	enum spdk_nvmf_rdma_request_state prev_state;
2030 	bool				progress = false;
2031 	int				data_posted;
2032 	uint32_t			num_blocks;
2033 
2034 	rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
2035 	device = rqpair->device;
2036 	rgroup = rqpair->poller->group;
2037 
2038 	assert(rdma_req->state != RDMA_REQUEST_STATE_FREE);
2039 
2040 	/* If the queue pair is in an error state, force the request to the completed state
2041 	 * to release resources. */
2042 	if (rqpair->ibv_state == IBV_QPS_ERR || rqpair->qpair.state != SPDK_NVMF_QPAIR_ACTIVE) {
2043 		if (rdma_req->state == RDMA_REQUEST_STATE_NEED_BUFFER) {
2044 			STAILQ_REMOVE(&rgroup->group.pending_buf_queue, &rdma_req->req, spdk_nvmf_request, buf_link);
2045 		} else if (rdma_req->state == RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING) {
2046 			STAILQ_REMOVE(&rqpair->pending_rdma_read_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2047 		} else if (rdma_req->state == RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING) {
2048 			STAILQ_REMOVE(&rqpair->pending_rdma_write_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2049 		}
2050 		rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2051 	}
2052 
2053 	/* The loop here is to allow for several back-to-back state changes. */
2054 	do {
2055 		prev_state = rdma_req->state;
2056 
2057 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Request %p entering state %d\n", rdma_req, prev_state);
2058 
2059 		switch (rdma_req->state) {
2060 		case RDMA_REQUEST_STATE_FREE:
2061 			/* Some external code must kick a request into RDMA_REQUEST_STATE_NEW
2062 			 * to escape this state. */
2063 			break;
2064 		case RDMA_REQUEST_STATE_NEW:
2065 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_NEW, 0, 0,
2066 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2067 			rdma_recv = rdma_req->recv;
2068 
2069 			/* The first element of the SGL is the NVMe command */
2070 			rdma_req->req.cmd = (union nvmf_h2c_msg *)rdma_recv->sgl[0].addr;
2071 			memset(rdma_req->req.rsp, 0, sizeof(*rdma_req->req.rsp));
2072 
2073 			if (rqpair->ibv_state == IBV_QPS_ERR  || rqpair->qpair.state != SPDK_NVMF_QPAIR_ACTIVE) {
2074 				rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2075 				break;
2076 			}
2077 
2078 			if (spdk_unlikely(spdk_nvmf_request_get_dif_ctx(&rdma_req->req, &rdma_req->req.dif.dif_ctx))) {
2079 				rdma_req->req.dif.dif_insert_or_strip = true;
2080 			}
2081 
2082 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
2083 			rdma_req->rsp.wr.opcode = IBV_WR_SEND;
2084 			rdma_req->rsp.wr.imm_data = 0;
2085 #endif
2086 
2087 			/* The next state transition depends on the data transfer needs of this request. */
2088 			rdma_req->req.xfer = spdk_nvmf_req_get_xfer(&rdma_req->req);
2089 
2090 			/* If no data to transfer, ready to execute. */
2091 			if (rdma_req->req.xfer == SPDK_NVME_DATA_NONE) {
2092 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_EXECUTE;
2093 				break;
2094 			}
2095 
2096 			rdma_req->state = RDMA_REQUEST_STATE_NEED_BUFFER;
2097 			STAILQ_INSERT_TAIL(&rgroup->group.pending_buf_queue, &rdma_req->req, buf_link);
2098 			break;
2099 		case RDMA_REQUEST_STATE_NEED_BUFFER:
2100 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_NEED_BUFFER, 0, 0,
2101 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2102 
2103 			assert(rdma_req->req.xfer != SPDK_NVME_DATA_NONE);
2104 
2105 			if (&rdma_req->req != STAILQ_FIRST(&rgroup->group.pending_buf_queue)) {
2106 				/* This request needs to wait in line to obtain a buffer */
2107 				break;
2108 			}
2109 
2110 			/* Try to get a data buffer */
2111 			rc = spdk_nvmf_rdma_request_parse_sgl(rtransport, device, rdma_req);
2112 			if (rc < 0) {
2113 				STAILQ_REMOVE_HEAD(&rgroup->group.pending_buf_queue, buf_link);
2114 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2115 				break;
2116 			}
2117 
2118 			if (!rdma_req->req.data) {
2119 				/* No buffers available. */
2120 				rgroup->stat.pending_data_buffer++;
2121 				break;
2122 			}
2123 
2124 			STAILQ_REMOVE_HEAD(&rgroup->group.pending_buf_queue, buf_link);
2125 
2126 			/* If data is transferring from host to controller and the data didn't
2127 			 * arrive using in capsule data, we need to do a transfer from the host.
2128 			 */
2129 			if (rdma_req->req.xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER &&
2130 			    rdma_req->req.data_from_pool) {
2131 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_read_queue, rdma_req, state_link);
2132 				rdma_req->state = RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING;
2133 				break;
2134 			}
2135 
2136 			rdma_req->state = RDMA_REQUEST_STATE_READY_TO_EXECUTE;
2137 			break;
2138 		case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING:
2139 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_CONTROLLER_PENDING, 0, 0,
2140 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2141 
2142 			if (rdma_req != STAILQ_FIRST(&rqpair->pending_rdma_read_queue)) {
2143 				/* This request needs to wait in line to perform RDMA */
2144 				break;
2145 			}
2146 			if (rqpair->current_send_depth + rdma_req->num_outstanding_data_wr > rqpair->max_send_depth
2147 			    || rqpair->current_read_depth + rdma_req->num_outstanding_data_wr > rqpair->max_read_depth) {
2148 				/* We can only have so many WRs outstanding. we have to wait until some finish. */
2149 				rqpair->poller->stat.pending_rdma_read++;
2150 				break;
2151 			}
2152 
2153 			/* We have already verified that this request is the head of the queue. */
2154 			STAILQ_REMOVE_HEAD(&rqpair->pending_rdma_read_queue, state_link);
2155 
2156 			rc = request_transfer_in(&rdma_req->req);
2157 			if (!rc) {
2158 				rdma_req->state = RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER;
2159 			} else {
2160 				rsp->status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
2161 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2162 			}
2163 			break;
2164 		case RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER:
2165 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER, 0, 0,
2166 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2167 			/* Some external code must kick a request into RDMA_REQUEST_STATE_READY_TO_EXECUTE
2168 			 * to escape this state. */
2169 			break;
2170 		case RDMA_REQUEST_STATE_READY_TO_EXECUTE:
2171 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_READY_TO_EXECUTE, 0, 0,
2172 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2173 
2174 			if (spdk_unlikely(rdma_req->req.dif.dif_insert_or_strip)) {
2175 				if (rdma_req->req.xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER) {
2176 					/* generate DIF for write operation */
2177 					num_blocks = SPDK_CEIL_DIV(rdma_req->req.dif.elba_length, rdma_req->req.dif.dif_ctx.block_size);
2178 					assert(num_blocks > 0);
2179 
2180 					rc = spdk_dif_generate(rdma_req->req.iov, rdma_req->req.iovcnt,
2181 							       num_blocks, &rdma_req->req.dif.dif_ctx);
2182 					if (rc != 0) {
2183 						SPDK_ERRLOG("DIF generation failed\n");
2184 						rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2185 						spdk_nvmf_rdma_start_disconnect(rqpair);
2186 						break;
2187 					}
2188 				}
2189 
2190 				assert(rdma_req->req.dif.elba_length >= rdma_req->req.length);
2191 				/* set extended length before IO operation */
2192 				rdma_req->req.length = rdma_req->req.dif.elba_length;
2193 			}
2194 
2195 			rdma_req->state = RDMA_REQUEST_STATE_EXECUTING;
2196 			spdk_nvmf_request_exec(&rdma_req->req);
2197 			break;
2198 		case RDMA_REQUEST_STATE_EXECUTING:
2199 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_EXECUTING, 0, 0,
2200 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2201 			/* Some external code must kick a request into RDMA_REQUEST_STATE_EXECUTED
2202 			 * to escape this state. */
2203 			break;
2204 		case RDMA_REQUEST_STATE_EXECUTED:
2205 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_EXECUTED, 0, 0,
2206 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2207 			if (rdma_req->req.xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
2208 				STAILQ_INSERT_TAIL(&rqpair->pending_rdma_write_queue, rdma_req, state_link);
2209 				rdma_req->state = RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING;
2210 			} else {
2211 				rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2212 			}
2213 			if (spdk_unlikely(rdma_req->req.dif.dif_insert_or_strip)) {
2214 				/* restore the original length */
2215 				rdma_req->req.length = rdma_req->req.dif.orig_length;
2216 
2217 				if (rdma_req->req.xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
2218 					struct spdk_dif_error error_blk;
2219 
2220 					num_blocks = SPDK_CEIL_DIV(rdma_req->req.dif.elba_length, rdma_req->req.dif.dif_ctx.block_size);
2221 
2222 					rc = spdk_dif_verify(rdma_req->req.iov, rdma_req->req.iovcnt, num_blocks,
2223 							     &rdma_req->req.dif.dif_ctx, &error_blk);
2224 					if (rc) {
2225 						struct spdk_nvme_cpl *rsp = &rdma_req->req.rsp->nvme_cpl;
2226 
2227 						SPDK_ERRLOG("DIF error detected. type=%d, offset=%" PRIu32 "\n", error_blk.err_type,
2228 							    error_blk.err_offset);
2229 						rsp->status.sct = SPDK_NVME_SCT_MEDIA_ERROR;
2230 						rsp->status.sc = spdk_nvmf_rdma_dif_error_to_compl_status(error_blk.err_type);
2231 						rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2232 						STAILQ_REMOVE(&rqpair->pending_rdma_write_queue, rdma_req, spdk_nvmf_rdma_request, state_link);
2233 					}
2234 				}
2235 			}
2236 			break;
2237 		case RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING:
2238 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_DATA_TRANSFER_TO_HOST_PENDING, 0, 0,
2239 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2240 
2241 			if (rdma_req != STAILQ_FIRST(&rqpair->pending_rdma_write_queue)) {
2242 				/* This request needs to wait in line to perform RDMA */
2243 				break;
2244 			}
2245 			if ((rqpair->current_send_depth + rdma_req->num_outstanding_data_wr + 1) >
2246 			    rqpair->max_send_depth) {
2247 				/* We can only have so many WRs outstanding. we have to wait until some finish.
2248 				 * +1 since each request has an additional wr in the resp. */
2249 				rqpair->poller->stat.pending_rdma_write++;
2250 				break;
2251 			}
2252 
2253 			/* We have already verified that this request is the head of the queue. */
2254 			STAILQ_REMOVE_HEAD(&rqpair->pending_rdma_write_queue, state_link);
2255 
2256 			/* The data transfer will be kicked off from
2257 			 * RDMA_REQUEST_STATE_READY_TO_COMPLETE state.
2258 			 */
2259 			rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
2260 			break;
2261 		case RDMA_REQUEST_STATE_READY_TO_COMPLETE:
2262 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_READY_TO_COMPLETE, 0, 0,
2263 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2264 			rc = request_transfer_out(&rdma_req->req, &data_posted);
2265 			assert(rc == 0); /* No good way to handle this currently */
2266 			if (rc) {
2267 				rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
2268 			} else {
2269 				rdma_req->state = data_posted ? RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST :
2270 						  RDMA_REQUEST_STATE_COMPLETING;
2271 			}
2272 			break;
2273 		case RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST:
2274 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST, 0, 0,
2275 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2276 			/* Some external code must kick a request into RDMA_REQUEST_STATE_COMPLETED
2277 			 * to escape this state. */
2278 			break;
2279 		case RDMA_REQUEST_STATE_COMPLETING:
2280 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_COMPLETING, 0, 0,
2281 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2282 			/* Some external code must kick a request into RDMA_REQUEST_STATE_COMPLETED
2283 			 * to escape this state. */
2284 			break;
2285 		case RDMA_REQUEST_STATE_COMPLETED:
2286 			spdk_trace_record(TRACE_RDMA_REQUEST_STATE_COMPLETED, 0, 0,
2287 					  (uintptr_t)rdma_req, (uintptr_t)rqpair->cm_id);
2288 
2289 			rqpair->poller->stat.request_latency += spdk_get_ticks() - rdma_req->receive_tsc;
2290 			nvmf_rdma_request_free(rdma_req, rtransport);
2291 			break;
2292 		case RDMA_REQUEST_NUM_STATES:
2293 		default:
2294 			assert(0);
2295 			break;
2296 		}
2297 
2298 		if (rdma_req->state != prev_state) {
2299 			progress = true;
2300 		}
2301 	} while (rdma_req->state != prev_state);
2302 
2303 	return progress;
2304 }
2305 
2306 /* Public API callbacks begin here */
2307 
2308 #define SPDK_NVMF_RDMA_DEFAULT_MAX_QUEUE_DEPTH 128
2309 #define SPDK_NVMF_RDMA_DEFAULT_AQ_DEPTH 128
2310 #define SPDK_NVMF_RDMA_DEFAULT_SRQ_DEPTH 4096
2311 #define SPDK_NVMF_RDMA_DEFAULT_MAX_QPAIRS_PER_CTRLR 128
2312 #define SPDK_NVMF_RDMA_DEFAULT_IN_CAPSULE_DATA_SIZE 4096
2313 #define SPDK_NVMF_RDMA_DEFAULT_MAX_IO_SIZE 131072
2314 #define SPDK_NVMF_RDMA_MIN_IO_BUFFER_SIZE (SPDK_NVMF_RDMA_DEFAULT_MAX_IO_SIZE / SPDK_NVMF_MAX_SGL_ENTRIES)
2315 #define SPDK_NVMF_RDMA_DEFAULT_NUM_SHARED_BUFFERS 4095
2316 #define SPDK_NVMF_RDMA_DEFAULT_BUFFER_CACHE_SIZE 32
2317 #define SPDK_NVMF_RDMA_DEFAULT_NO_SRQ false
2318 #define SPDK_NVMF_RDMA_DIF_INSERT_OR_STRIP false
2319 
2320 static void
2321 spdk_nvmf_rdma_opts_init(struct spdk_nvmf_transport_opts *opts)
2322 {
2323 	opts->max_queue_depth =		SPDK_NVMF_RDMA_DEFAULT_MAX_QUEUE_DEPTH;
2324 	opts->max_qpairs_per_ctrlr =	SPDK_NVMF_RDMA_DEFAULT_MAX_QPAIRS_PER_CTRLR;
2325 	opts->in_capsule_data_size =	SPDK_NVMF_RDMA_DEFAULT_IN_CAPSULE_DATA_SIZE;
2326 	opts->max_io_size =		SPDK_NVMF_RDMA_DEFAULT_MAX_IO_SIZE;
2327 	opts->io_unit_size =		SPDK_NVMF_RDMA_MIN_IO_BUFFER_SIZE;
2328 	opts->max_aq_depth =		SPDK_NVMF_RDMA_DEFAULT_AQ_DEPTH;
2329 	opts->num_shared_buffers =	SPDK_NVMF_RDMA_DEFAULT_NUM_SHARED_BUFFERS;
2330 	opts->buf_cache_size =		SPDK_NVMF_RDMA_DEFAULT_BUFFER_CACHE_SIZE;
2331 	opts->max_srq_depth =		SPDK_NVMF_RDMA_DEFAULT_SRQ_DEPTH;
2332 	opts->no_srq =			SPDK_NVMF_RDMA_DEFAULT_NO_SRQ;
2333 	opts->dif_insert_or_strip =	SPDK_NVMF_RDMA_DIF_INSERT_OR_STRIP;
2334 }
2335 
2336 const struct spdk_mem_map_ops g_nvmf_rdma_map_ops = {
2337 	.notify_cb = spdk_nvmf_rdma_mem_notify,
2338 	.are_contiguous = spdk_nvmf_rdma_check_contiguous_entries
2339 };
2340 
2341 static int spdk_nvmf_rdma_destroy(struct spdk_nvmf_transport *transport);
2342 
2343 static struct spdk_nvmf_transport *
2344 spdk_nvmf_rdma_create(struct spdk_nvmf_transport_opts *opts)
2345 {
2346 	int rc;
2347 	struct spdk_nvmf_rdma_transport *rtransport;
2348 	struct spdk_nvmf_rdma_device	*device, *tmp;
2349 	struct ibv_context		**contexts;
2350 	uint32_t			i;
2351 	int				flag;
2352 	uint32_t			sge_count;
2353 	uint32_t			min_shared_buffers;
2354 	int				max_device_sge = SPDK_NVMF_MAX_SGL_ENTRIES;
2355 	pthread_mutexattr_t		attr;
2356 
2357 	rtransport = calloc(1, sizeof(*rtransport));
2358 	if (!rtransport) {
2359 		return NULL;
2360 	}
2361 
2362 	if (pthread_mutexattr_init(&attr)) {
2363 		SPDK_ERRLOG("pthread_mutexattr_init() failed\n");
2364 		free(rtransport);
2365 		return NULL;
2366 	}
2367 
2368 	if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) {
2369 		SPDK_ERRLOG("pthread_mutexattr_settype() failed\n");
2370 		pthread_mutexattr_destroy(&attr);
2371 		free(rtransport);
2372 		return NULL;
2373 	}
2374 
2375 	if (pthread_mutex_init(&rtransport->lock, &attr)) {
2376 		SPDK_ERRLOG("pthread_mutex_init() failed\n");
2377 		pthread_mutexattr_destroy(&attr);
2378 		free(rtransport);
2379 		return NULL;
2380 	}
2381 
2382 	pthread_mutexattr_destroy(&attr);
2383 
2384 	TAILQ_INIT(&rtransport->devices);
2385 	TAILQ_INIT(&rtransport->ports);
2386 	TAILQ_INIT(&rtransport->poll_groups);
2387 
2388 	rtransport->transport.ops = &spdk_nvmf_transport_rdma;
2389 
2390 	SPDK_INFOLOG(SPDK_LOG_RDMA, "*** RDMA Transport Init ***\n"
2391 		     "  Transport opts:  max_ioq_depth=%d, max_io_size=%d,\n"
2392 		     "  max_qpairs_per_ctrlr=%d, io_unit_size=%d,\n"
2393 		     "  in_capsule_data_size=%d, max_aq_depth=%d,\n"
2394 		     "  num_shared_buffers=%d, max_srq_depth=%d, no_srq=%d\n",
2395 		     opts->max_queue_depth,
2396 		     opts->max_io_size,
2397 		     opts->max_qpairs_per_ctrlr,
2398 		     opts->io_unit_size,
2399 		     opts->in_capsule_data_size,
2400 		     opts->max_aq_depth,
2401 		     opts->num_shared_buffers,
2402 		     opts->max_srq_depth,
2403 		     opts->no_srq);
2404 
2405 	/* I/O unit size cannot be larger than max I/O size */
2406 	if (opts->io_unit_size > opts->max_io_size) {
2407 		opts->io_unit_size = opts->max_io_size;
2408 	}
2409 
2410 	if (opts->num_shared_buffers < (SPDK_NVMF_MAX_SGL_ENTRIES * 2)) {
2411 		SPDK_ERRLOG("The number of shared data buffers (%d) is less than"
2412 			    "the minimum number required to guarantee that forward progress can be made (%d)\n",
2413 			    opts->num_shared_buffers, (SPDK_NVMF_MAX_SGL_ENTRIES * 2));
2414 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2415 		return NULL;
2416 	}
2417 
2418 	min_shared_buffers = spdk_thread_get_count() * opts->buf_cache_size;
2419 	if (min_shared_buffers > opts->num_shared_buffers) {
2420 		SPDK_ERRLOG("There are not enough buffers to satisfy"
2421 			    "per-poll group caches for each thread. (%" PRIu32 ")"
2422 			    "supplied. (%" PRIu32 ") required\n", opts->num_shared_buffers, min_shared_buffers);
2423 		SPDK_ERRLOG("Please specify a larger number of shared buffers\n");
2424 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2425 		return NULL;
2426 	}
2427 
2428 	sge_count = opts->max_io_size / opts->io_unit_size;
2429 	if (sge_count > NVMF_DEFAULT_TX_SGE) {
2430 		SPDK_ERRLOG("Unsupported IO Unit size specified, %d bytes\n", opts->io_unit_size);
2431 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2432 		return NULL;
2433 	}
2434 
2435 	rtransport->event_channel = rdma_create_event_channel();
2436 	if (rtransport->event_channel == NULL) {
2437 		SPDK_ERRLOG("rdma_create_event_channel() failed, %s\n", spdk_strerror(errno));
2438 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2439 		return NULL;
2440 	}
2441 
2442 	flag = fcntl(rtransport->event_channel->fd, F_GETFL);
2443 	if (fcntl(rtransport->event_channel->fd, F_SETFL, flag | O_NONBLOCK) < 0) {
2444 		SPDK_ERRLOG("fcntl can't set nonblocking mode for socket, fd: %d (%s)\n",
2445 			    rtransport->event_channel->fd, spdk_strerror(errno));
2446 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2447 		return NULL;
2448 	}
2449 
2450 	rtransport->data_wr_pool = spdk_mempool_create("spdk_nvmf_rdma_wr_data",
2451 				   opts->max_queue_depth * SPDK_NVMF_MAX_SGL_ENTRIES,
2452 				   sizeof(struct spdk_nvmf_rdma_request_data),
2453 				   SPDK_MEMPOOL_DEFAULT_CACHE_SIZE,
2454 				   SPDK_ENV_SOCKET_ID_ANY);
2455 	if (!rtransport->data_wr_pool) {
2456 		SPDK_ERRLOG("Unable to allocate work request pool for poll group\n");
2457 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2458 		return NULL;
2459 	}
2460 
2461 	contexts = rdma_get_devices(NULL);
2462 	if (contexts == NULL) {
2463 		SPDK_ERRLOG("rdma_get_devices() failed: %s (%d)\n", spdk_strerror(errno), errno);
2464 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2465 		return NULL;
2466 	}
2467 
2468 	i = 0;
2469 	rc = 0;
2470 	while (contexts[i] != NULL) {
2471 		device = calloc(1, sizeof(*device));
2472 		if (!device) {
2473 			SPDK_ERRLOG("Unable to allocate memory for RDMA devices.\n");
2474 			rc = -ENOMEM;
2475 			break;
2476 		}
2477 		device->context = contexts[i];
2478 		rc = ibv_query_device(device->context, &device->attr);
2479 		if (rc < 0) {
2480 			SPDK_ERRLOG("Failed to query RDMA device attributes.\n");
2481 			free(device);
2482 			break;
2483 
2484 		}
2485 
2486 		max_device_sge = spdk_min(max_device_sge, device->attr.max_sge);
2487 
2488 #ifdef SPDK_CONFIG_RDMA_SEND_WITH_INVAL
2489 		if ((device->attr.device_cap_flags & IBV_DEVICE_MEM_MGT_EXTENSIONS) == 0) {
2490 			SPDK_WARNLOG("The libibverbs on this system supports SEND_WITH_INVALIDATE,");
2491 			SPDK_WARNLOG("but the device with vendor ID %u does not.\n", device->attr.vendor_id);
2492 		}
2493 
2494 		/**
2495 		 * The vendor ID is assigned by the IEEE and an ID of 0 implies Soft-RoCE.
2496 		 * The Soft-RoCE RXE driver does not currently support send with invalidate,
2497 		 * but incorrectly reports that it does. There are changes making their way
2498 		 * through the kernel now that will enable this feature. When they are merged,
2499 		 * we can conditionally enable this feature.
2500 		 *
2501 		 * TODO: enable this for versions of the kernel rxe driver that support it.
2502 		 */
2503 		if (device->attr.vendor_id == 0) {
2504 			device->attr.device_cap_flags &= ~(IBV_DEVICE_MEM_MGT_EXTENSIONS);
2505 		}
2506 #endif
2507 
2508 		/* set up device context async ev fd as NON_BLOCKING */
2509 		flag = fcntl(device->context->async_fd, F_GETFL);
2510 		rc = fcntl(device->context->async_fd, F_SETFL, flag | O_NONBLOCK);
2511 		if (rc < 0) {
2512 			SPDK_ERRLOG("Failed to set context async fd to NONBLOCK.\n");
2513 			free(device);
2514 			break;
2515 		}
2516 
2517 		TAILQ_INSERT_TAIL(&rtransport->devices, device, link);
2518 		i++;
2519 
2520 		if (g_nvmf_hooks.get_ibv_pd) {
2521 			device->pd = g_nvmf_hooks.get_ibv_pd(NULL, device->context);
2522 		} else {
2523 			device->pd = ibv_alloc_pd(device->context);
2524 		}
2525 
2526 		if (!device->pd) {
2527 			SPDK_ERRLOG("Unable to allocate protection domain.\n");
2528 			rc = -ENOMEM;
2529 			break;
2530 		}
2531 
2532 		assert(device->map == NULL);
2533 
2534 		device->map = spdk_mem_map_alloc(0, &g_nvmf_rdma_map_ops, device->pd);
2535 		if (!device->map) {
2536 			SPDK_ERRLOG("Unable to allocate memory map for listen address\n");
2537 			rc = -ENOMEM;
2538 			break;
2539 		}
2540 
2541 		assert(device->map != NULL);
2542 		assert(device->pd != NULL);
2543 	}
2544 	rdma_free_devices(contexts);
2545 
2546 	if (opts->io_unit_size * max_device_sge < opts->max_io_size) {
2547 		/* divide and round up. */
2548 		opts->io_unit_size = (opts->max_io_size + max_device_sge - 1) / max_device_sge;
2549 
2550 		/* round up to the nearest 4k. */
2551 		opts->io_unit_size = (opts->io_unit_size + NVMF_DATA_BUFFER_ALIGNMENT - 1) & ~NVMF_DATA_BUFFER_MASK;
2552 
2553 		opts->io_unit_size = spdk_max(opts->io_unit_size, SPDK_NVMF_RDMA_MIN_IO_BUFFER_SIZE);
2554 		SPDK_NOTICELOG("Adjusting the io unit size to fit the device's maximum I/O size. New I/O unit size %u\n",
2555 			       opts->io_unit_size);
2556 	}
2557 
2558 	if (rc < 0) {
2559 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2560 		return NULL;
2561 	}
2562 
2563 	/* Set up poll descriptor array to monitor events from RDMA and IB
2564 	 * in a single poll syscall
2565 	 */
2566 	rtransport->npoll_fds = i + 1;
2567 	i = 0;
2568 	rtransport->poll_fds = calloc(rtransport->npoll_fds, sizeof(struct pollfd));
2569 	if (rtransport->poll_fds == NULL) {
2570 		SPDK_ERRLOG("poll_fds allocation failed\n");
2571 		spdk_nvmf_rdma_destroy(&rtransport->transport);
2572 		return NULL;
2573 	}
2574 
2575 	rtransport->poll_fds[i].fd = rtransport->event_channel->fd;
2576 	rtransport->poll_fds[i++].events = POLLIN;
2577 
2578 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, tmp) {
2579 		rtransport->poll_fds[i].fd = device->context->async_fd;
2580 		rtransport->poll_fds[i++].events = POLLIN;
2581 	}
2582 
2583 	return &rtransport->transport;
2584 }
2585 
2586 static int
2587 spdk_nvmf_rdma_destroy(struct spdk_nvmf_transport *transport)
2588 {
2589 	struct spdk_nvmf_rdma_transport	*rtransport;
2590 	struct spdk_nvmf_rdma_port	*port, *port_tmp;
2591 	struct spdk_nvmf_rdma_device	*device, *device_tmp;
2592 
2593 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2594 
2595 	TAILQ_FOREACH_SAFE(port, &rtransport->ports, link, port_tmp) {
2596 		TAILQ_REMOVE(&rtransport->ports, port, link);
2597 		rdma_destroy_id(port->id);
2598 		free(port);
2599 	}
2600 
2601 	if (rtransport->poll_fds != NULL) {
2602 		free(rtransport->poll_fds);
2603 	}
2604 
2605 	if (rtransport->event_channel != NULL) {
2606 		rdma_destroy_event_channel(rtransport->event_channel);
2607 	}
2608 
2609 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, device_tmp) {
2610 		TAILQ_REMOVE(&rtransport->devices, device, link);
2611 		if (device->map) {
2612 			spdk_mem_map_free(&device->map);
2613 		}
2614 		if (device->pd) {
2615 			if (!g_nvmf_hooks.get_ibv_pd) {
2616 				ibv_dealloc_pd(device->pd);
2617 			}
2618 		}
2619 		free(device);
2620 	}
2621 
2622 	if (rtransport->data_wr_pool != NULL) {
2623 		if (spdk_mempool_count(rtransport->data_wr_pool) !=
2624 		    (transport->opts.max_queue_depth * SPDK_NVMF_MAX_SGL_ENTRIES)) {
2625 			SPDK_ERRLOG("transport wr pool count is %zu but should be %u\n",
2626 				    spdk_mempool_count(rtransport->data_wr_pool),
2627 				    transport->opts.max_queue_depth * SPDK_NVMF_MAX_SGL_ENTRIES);
2628 		}
2629 	}
2630 
2631 	spdk_mempool_free(rtransport->data_wr_pool);
2632 
2633 	pthread_mutex_destroy(&rtransport->lock);
2634 	free(rtransport);
2635 
2636 	return 0;
2637 }
2638 
2639 static int
2640 spdk_nvmf_rdma_trid_from_cm_id(struct rdma_cm_id *id,
2641 			       struct spdk_nvme_transport_id *trid,
2642 			       bool peer);
2643 
2644 static int
2645 spdk_nvmf_rdma_listen(struct spdk_nvmf_transport *transport,
2646 		      const struct spdk_nvme_transport_id *trid,
2647 		      spdk_nvmf_tgt_listen_done_fn cb_fn,
2648 		      void *cb_arg)
2649 {
2650 	struct spdk_nvmf_rdma_transport	*rtransport;
2651 	struct spdk_nvmf_rdma_device	*device;
2652 	struct spdk_nvmf_rdma_port	*port;
2653 	struct addrinfo			*res;
2654 	struct addrinfo			hints;
2655 	int				family;
2656 	int				rc;
2657 
2658 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2659 	assert(rtransport->event_channel != NULL);
2660 
2661 	pthread_mutex_lock(&rtransport->lock);
2662 	port = calloc(1, sizeof(*port));
2663 	if (!port) {
2664 		SPDK_ERRLOG("Port allocation failed\n");
2665 		pthread_mutex_unlock(&rtransport->lock);
2666 		return -ENOMEM;
2667 	}
2668 
2669 	port->trid = trid;
2670 
2671 	switch (trid->adrfam) {
2672 	case SPDK_NVMF_ADRFAM_IPV4:
2673 		family = AF_INET;
2674 		break;
2675 	case SPDK_NVMF_ADRFAM_IPV6:
2676 		family = AF_INET6;
2677 		break;
2678 	default:
2679 		SPDK_ERRLOG("Unhandled ADRFAM %d\n", trid->adrfam);
2680 		free(port);
2681 		pthread_mutex_unlock(&rtransport->lock);
2682 		return -EINVAL;
2683 	}
2684 
2685 	memset(&hints, 0, sizeof(hints));
2686 	hints.ai_family = family;
2687 	hints.ai_flags = AI_NUMERICSERV;
2688 	hints.ai_socktype = SOCK_STREAM;
2689 	hints.ai_protocol = 0;
2690 
2691 	rc = getaddrinfo(trid->traddr, trid->trsvcid, &hints, &res);
2692 	if (rc) {
2693 		SPDK_ERRLOG("getaddrinfo failed: %s (%d)\n", gai_strerror(rc), rc);
2694 		free(port);
2695 		pthread_mutex_unlock(&rtransport->lock);
2696 		return -EINVAL;
2697 	}
2698 
2699 	rc = rdma_create_id(rtransport->event_channel, &port->id, port, RDMA_PS_TCP);
2700 	if (rc < 0) {
2701 		SPDK_ERRLOG("rdma_create_id() failed\n");
2702 		freeaddrinfo(res);
2703 		free(port);
2704 		pthread_mutex_unlock(&rtransport->lock);
2705 		return rc;
2706 	}
2707 
2708 	rc = rdma_bind_addr(port->id, res->ai_addr);
2709 	freeaddrinfo(res);
2710 
2711 	if (rc < 0) {
2712 		SPDK_ERRLOG("rdma_bind_addr() failed\n");
2713 		rdma_destroy_id(port->id);
2714 		free(port);
2715 		pthread_mutex_unlock(&rtransport->lock);
2716 		return rc;
2717 	}
2718 
2719 	if (!port->id->verbs) {
2720 		SPDK_ERRLOG("ibv_context is null\n");
2721 		rdma_destroy_id(port->id);
2722 		free(port);
2723 		pthread_mutex_unlock(&rtransport->lock);
2724 		return -1;
2725 	}
2726 
2727 	rc = rdma_listen(port->id, 10); /* 10 = backlog */
2728 	if (rc < 0) {
2729 		SPDK_ERRLOG("rdma_listen() failed\n");
2730 		rdma_destroy_id(port->id);
2731 		free(port);
2732 		pthread_mutex_unlock(&rtransport->lock);
2733 		return rc;
2734 	}
2735 
2736 	TAILQ_FOREACH(device, &rtransport->devices, link) {
2737 		if (device->context == port->id->verbs) {
2738 			port->device = device;
2739 			break;
2740 		}
2741 	}
2742 	if (!port->device) {
2743 		SPDK_ERRLOG("Accepted a connection with verbs %p, but unable to find a corresponding device.\n",
2744 			    port->id->verbs);
2745 		rdma_destroy_id(port->id);
2746 		free(port);
2747 		pthread_mutex_unlock(&rtransport->lock);
2748 		return -EINVAL;
2749 	}
2750 
2751 	SPDK_NOTICELOG("*** NVMe/RDMA Target Listening on %s port %s ***\n",
2752 		       trid->traddr, trid->trsvcid);
2753 
2754 	TAILQ_INSERT_TAIL(&rtransport->ports, port, link);
2755 	pthread_mutex_unlock(&rtransport->lock);
2756 
2757 	if (cb_fn != NULL) {
2758 		cb_fn(cb_arg, 0);
2759 	}
2760 
2761 	return 0;
2762 }
2763 
2764 static void
2765 spdk_nvmf_rdma_stop_listen(struct spdk_nvmf_transport *transport,
2766 			   const struct spdk_nvme_transport_id *trid)
2767 {
2768 	struct spdk_nvmf_rdma_transport *rtransport;
2769 	struct spdk_nvmf_rdma_port *port, *tmp;
2770 
2771 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2772 
2773 	pthread_mutex_lock(&rtransport->lock);
2774 	TAILQ_FOREACH_SAFE(port, &rtransport->ports, link, tmp) {
2775 		if (spdk_nvme_transport_id_compare(port->trid, trid) == 0) {
2776 			TAILQ_REMOVE(&rtransport->ports, port, link);
2777 			rdma_destroy_id(port->id);
2778 			free(port);
2779 			break;
2780 		}
2781 	}
2782 
2783 	pthread_mutex_unlock(&rtransport->lock);
2784 }
2785 
2786 static void
2787 spdk_nvmf_rdma_qpair_process_pending(struct spdk_nvmf_rdma_transport *rtransport,
2788 				     struct spdk_nvmf_rdma_qpair *rqpair, bool drain)
2789 {
2790 	struct spdk_nvmf_request *req, *tmp;
2791 	struct spdk_nvmf_rdma_request	*rdma_req, *req_tmp;
2792 	struct spdk_nvmf_rdma_resources *resources;
2793 
2794 	/* We process I/O in the data transfer pending queue at the highest priority. RDMA reads first */
2795 	STAILQ_FOREACH_SAFE(rdma_req, &rqpair->pending_rdma_read_queue, state_link, req_tmp) {
2796 		if (spdk_nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
2797 			break;
2798 		}
2799 	}
2800 
2801 	/* Then RDMA writes since reads have stronger restrictions than writes */
2802 	STAILQ_FOREACH_SAFE(rdma_req, &rqpair->pending_rdma_write_queue, state_link, req_tmp) {
2803 		if (spdk_nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
2804 			break;
2805 		}
2806 	}
2807 
2808 	/* The second highest priority is I/O waiting on memory buffers. */
2809 	STAILQ_FOREACH_SAFE(req, &rqpair->poller->group->group.pending_buf_queue, buf_link, tmp) {
2810 		rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
2811 		if (spdk_nvmf_rdma_request_process(rtransport, rdma_req) == false && drain == false) {
2812 			break;
2813 		}
2814 	}
2815 
2816 	resources = rqpair->resources;
2817 	while (!STAILQ_EMPTY(&resources->free_queue) && !STAILQ_EMPTY(&resources->incoming_queue)) {
2818 		rdma_req = STAILQ_FIRST(&resources->free_queue);
2819 		STAILQ_REMOVE_HEAD(&resources->free_queue, state_link);
2820 		rdma_req->recv = STAILQ_FIRST(&resources->incoming_queue);
2821 		STAILQ_REMOVE_HEAD(&resources->incoming_queue, link);
2822 
2823 		if (rqpair->srq != NULL) {
2824 			rdma_req->req.qpair = &rdma_req->recv->qpair->qpair;
2825 			rdma_req->recv->qpair->qd++;
2826 		} else {
2827 			rqpair->qd++;
2828 		}
2829 
2830 		rdma_req->receive_tsc = rdma_req->recv->receive_tsc;
2831 		rdma_req->state = RDMA_REQUEST_STATE_NEW;
2832 		if (spdk_nvmf_rdma_request_process(rtransport, rdma_req) == false) {
2833 			break;
2834 		}
2835 	}
2836 	if (!STAILQ_EMPTY(&resources->incoming_queue) && STAILQ_EMPTY(&resources->free_queue)) {
2837 		rqpair->poller->stat.pending_free_request++;
2838 	}
2839 }
2840 
2841 static void
2842 _nvmf_rdma_qpair_disconnect(void *ctx)
2843 {
2844 	struct spdk_nvmf_qpair *qpair = ctx;
2845 
2846 	spdk_nvmf_qpair_disconnect(qpair, NULL, NULL);
2847 }
2848 
2849 static void
2850 _nvmf_rdma_try_disconnect(void *ctx)
2851 {
2852 	struct spdk_nvmf_qpair *qpair = ctx;
2853 	struct spdk_nvmf_poll_group *group;
2854 
2855 	/* Read the group out of the qpair. This is normally set and accessed only from
2856 	 * the thread that created the group. Here, we're not on that thread necessarily.
2857 	 * The data member qpair->group begins it's life as NULL and then is assigned to
2858 	 * a pointer and never changes. So fortunately reading this and checking for
2859 	 * non-NULL is thread safe in the x86_64 memory model. */
2860 	group = qpair->group;
2861 
2862 	if (group == NULL) {
2863 		/* The qpair hasn't been assigned to a group yet, so we can't
2864 		 * process a disconnect. Send a message to ourself and try again. */
2865 		spdk_thread_send_msg(spdk_get_thread(), _nvmf_rdma_try_disconnect, qpair);
2866 		return;
2867 	}
2868 
2869 	spdk_thread_send_msg(group->thread, _nvmf_rdma_qpair_disconnect, qpair);
2870 }
2871 
2872 static inline void
2873 spdk_nvmf_rdma_start_disconnect(struct spdk_nvmf_rdma_qpair *rqpair)
2874 {
2875 	if (!__atomic_test_and_set(&rqpair->disconnect_started, __ATOMIC_RELAXED)) {
2876 		_nvmf_rdma_try_disconnect(&rqpair->qpair);
2877 	}
2878 }
2879 
2880 static void nvmf_rdma_destroy_drained_qpair(void *ctx)
2881 {
2882 	struct spdk_nvmf_rdma_qpair *rqpair = ctx;
2883 	struct spdk_nvmf_rdma_transport *rtransport = SPDK_CONTAINEROF(rqpair->qpair.transport,
2884 			struct spdk_nvmf_rdma_transport, transport);
2885 
2886 	/* In non SRQ path, we will reach rqpair->max_queue_depth. In SRQ path, we will get the last_wqe event. */
2887 	if (rqpair->current_send_depth != 0) {
2888 		return;
2889 	}
2890 
2891 	if (rqpair->srq == NULL && rqpair->current_recv_depth != rqpair->max_queue_depth) {
2892 		return;
2893 	}
2894 
2895 	if (rqpair->srq != NULL && rqpair->last_wqe_reached == false) {
2896 		return;
2897 	}
2898 
2899 	spdk_nvmf_rdma_qpair_process_pending(rtransport, rqpair, true);
2900 
2901 	/* Qpair will be destroyed after nvmf layer closes this qpair */
2902 	if (rqpair->qpair.state != SPDK_NVMF_QPAIR_ERROR) {
2903 		return;
2904 	}
2905 
2906 	spdk_nvmf_rdma_qpair_destroy(rqpair);
2907 }
2908 
2909 
2910 static int
2911 nvmf_rdma_disconnect(struct rdma_cm_event *evt)
2912 {
2913 	struct spdk_nvmf_qpair		*qpair;
2914 	struct spdk_nvmf_rdma_qpair	*rqpair;
2915 
2916 	if (evt->id == NULL) {
2917 		SPDK_ERRLOG("disconnect request: missing cm_id\n");
2918 		return -1;
2919 	}
2920 
2921 	qpair = evt->id->context;
2922 	if (qpair == NULL) {
2923 		SPDK_ERRLOG("disconnect request: no active connection\n");
2924 		return -1;
2925 	}
2926 
2927 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
2928 
2929 	spdk_trace_record(TRACE_RDMA_QP_DISCONNECT, 0, 0, (uintptr_t)rqpair->cm_id, 0);
2930 
2931 	spdk_nvmf_rdma_start_disconnect(rqpair);
2932 
2933 	return 0;
2934 }
2935 
2936 #ifdef DEBUG
2937 static const char *CM_EVENT_STR[] = {
2938 	"RDMA_CM_EVENT_ADDR_RESOLVED",
2939 	"RDMA_CM_EVENT_ADDR_ERROR",
2940 	"RDMA_CM_EVENT_ROUTE_RESOLVED",
2941 	"RDMA_CM_EVENT_ROUTE_ERROR",
2942 	"RDMA_CM_EVENT_CONNECT_REQUEST",
2943 	"RDMA_CM_EVENT_CONNECT_RESPONSE",
2944 	"RDMA_CM_EVENT_CONNECT_ERROR",
2945 	"RDMA_CM_EVENT_UNREACHABLE",
2946 	"RDMA_CM_EVENT_REJECTED",
2947 	"RDMA_CM_EVENT_ESTABLISHED",
2948 	"RDMA_CM_EVENT_DISCONNECTED",
2949 	"RDMA_CM_EVENT_DEVICE_REMOVAL",
2950 	"RDMA_CM_EVENT_MULTICAST_JOIN",
2951 	"RDMA_CM_EVENT_MULTICAST_ERROR",
2952 	"RDMA_CM_EVENT_ADDR_CHANGE",
2953 	"RDMA_CM_EVENT_TIMEWAIT_EXIT"
2954 };
2955 #endif /* DEBUG */
2956 
2957 static void
2958 nvmf_rdma_disconnect_qpairs_on_port(struct spdk_nvmf_rdma_transport *rtransport,
2959 				    struct spdk_nvmf_rdma_port *port)
2960 {
2961 	struct spdk_nvmf_rdma_poll_group	*rgroup;
2962 	struct spdk_nvmf_rdma_poller		*rpoller;
2963 	struct spdk_nvmf_rdma_qpair		*rqpair;
2964 
2965 	TAILQ_FOREACH(rgroup, &rtransport->poll_groups, link) {
2966 		TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
2967 			TAILQ_FOREACH(rqpair, &rpoller->qpairs, link) {
2968 				if (rqpair->listen_id == port->id) {
2969 					spdk_nvmf_rdma_start_disconnect(rqpair);
2970 				}
2971 			}
2972 		}
2973 	}
2974 }
2975 
2976 static bool
2977 nvmf_rdma_handle_cm_event_addr_change(struct spdk_nvmf_transport *transport,
2978 				      struct rdma_cm_event *event)
2979 {
2980 	const struct spdk_nvme_transport_id	*trid;
2981 	struct spdk_nvmf_rdma_port		*port;
2982 	struct spdk_nvmf_rdma_transport		*rtransport;
2983 	bool					event_acked = false;
2984 
2985 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
2986 	TAILQ_FOREACH(port, &rtransport->ports, link) {
2987 		if (port->id == event->id) {
2988 			SPDK_ERRLOG("ADDR_CHANGE: IP %s:%s migrated\n", port->trid->traddr, port->trid->trsvcid);
2989 			rdma_ack_cm_event(event);
2990 			event_acked = true;
2991 			trid = port->trid;
2992 			break;
2993 		}
2994 	}
2995 
2996 	if (event_acked) {
2997 		nvmf_rdma_disconnect_qpairs_on_port(rtransport, port);
2998 
2999 		spdk_nvmf_rdma_stop_listen(transport, trid);
3000 		spdk_nvmf_rdma_listen(transport, trid, NULL, NULL);
3001 	}
3002 
3003 	return event_acked;
3004 }
3005 
3006 static void
3007 nvmf_rdma_handle_cm_event_port_removal(struct spdk_nvmf_transport *transport,
3008 				       struct rdma_cm_event *event)
3009 {
3010 	struct spdk_nvmf_rdma_port		*port;
3011 	struct spdk_nvmf_rdma_transport		*rtransport;
3012 
3013 	port = event->id->context;
3014 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3015 
3016 	SPDK_NOTICELOG("Port %s:%s is being removed\n", port->trid->traddr, port->trid->trsvcid);
3017 
3018 	nvmf_rdma_disconnect_qpairs_on_port(rtransport, port);
3019 
3020 	rdma_ack_cm_event(event);
3021 
3022 	while (spdk_nvmf_transport_stop_listen(transport, port->trid) == 0) {
3023 		;
3024 	}
3025 }
3026 
3027 static void
3028 spdk_nvmf_process_cm_event(struct spdk_nvmf_transport *transport, new_qpair_fn cb_fn, void *cb_arg)
3029 {
3030 	struct spdk_nvmf_rdma_transport *rtransport;
3031 	struct rdma_cm_event		*event;
3032 	int				rc;
3033 	bool				event_acked;
3034 
3035 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3036 
3037 	if (rtransport->event_channel == NULL) {
3038 		return;
3039 	}
3040 
3041 	while (1) {
3042 		event_acked = false;
3043 		rc = rdma_get_cm_event(rtransport->event_channel, &event);
3044 		if (rc) {
3045 			if (errno != EAGAIN && errno != EWOULDBLOCK) {
3046 				SPDK_ERRLOG("Acceptor Event Error: %s\n", spdk_strerror(errno));
3047 			}
3048 			break;
3049 		}
3050 
3051 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Acceptor Event: %s\n", CM_EVENT_STR[event->event]);
3052 
3053 		spdk_trace_record(TRACE_RDMA_CM_ASYNC_EVENT, 0, 0, 0, event->event);
3054 
3055 		switch (event->event) {
3056 		case RDMA_CM_EVENT_ADDR_RESOLVED:
3057 		case RDMA_CM_EVENT_ADDR_ERROR:
3058 		case RDMA_CM_EVENT_ROUTE_RESOLVED:
3059 		case RDMA_CM_EVENT_ROUTE_ERROR:
3060 			/* No action required. The target never attempts to resolve routes. */
3061 			break;
3062 		case RDMA_CM_EVENT_CONNECT_REQUEST:
3063 			rc = nvmf_rdma_connect(transport, event, cb_fn, cb_arg);
3064 			if (rc < 0) {
3065 				SPDK_ERRLOG("Unable to process connect event. rc: %d\n", rc);
3066 				break;
3067 			}
3068 			break;
3069 		case RDMA_CM_EVENT_CONNECT_RESPONSE:
3070 			/* The target never initiates a new connection. So this will not occur. */
3071 			break;
3072 		case RDMA_CM_EVENT_CONNECT_ERROR:
3073 			/* Can this happen? The docs say it can, but not sure what causes it. */
3074 			break;
3075 		case RDMA_CM_EVENT_UNREACHABLE:
3076 		case RDMA_CM_EVENT_REJECTED:
3077 			/* These only occur on the client side. */
3078 			break;
3079 		case RDMA_CM_EVENT_ESTABLISHED:
3080 			/* TODO: Should we be waiting for this event anywhere? */
3081 			break;
3082 		case RDMA_CM_EVENT_DISCONNECTED:
3083 			rc = nvmf_rdma_disconnect(event);
3084 			if (rc < 0) {
3085 				SPDK_ERRLOG("Unable to process disconnect event. rc: %d\n", rc);
3086 				break;
3087 			}
3088 			break;
3089 		case RDMA_CM_EVENT_DEVICE_REMOVAL:
3090 			/* In case of device removal, kernel IB part triggers IBV_EVENT_DEVICE_FATAL
3091 			 * which triggers RDMA_CM_EVENT_DEVICE_REMOVAL on all cma_id’s.
3092 			 * Once these events are sent to SPDK, we should release all IB resources and
3093 			 * don't make attempts to call any ibv_query/modify/create functions. We can only call
3094 			 * ibv_destory* functions to release user space memory allocated by IB. All kernel
3095 			 * resources are already cleaned. */
3096 			if (event->id->qp) {
3097 				/* If rdma_cm event has a valid `qp` pointer then the event refers to the
3098 				 * corresponding qpair. Otherwise the event refers to a listening device */
3099 				rc = nvmf_rdma_disconnect(event);
3100 				if (rc < 0) {
3101 					SPDK_ERRLOG("Unable to process disconnect event. rc: %d\n", rc);
3102 					break;
3103 				}
3104 			} else {
3105 				nvmf_rdma_handle_cm_event_port_removal(transport, event);
3106 				event_acked = true;
3107 			}
3108 			break;
3109 		case RDMA_CM_EVENT_MULTICAST_JOIN:
3110 		case RDMA_CM_EVENT_MULTICAST_ERROR:
3111 			/* Multicast is not used */
3112 			break;
3113 		case RDMA_CM_EVENT_ADDR_CHANGE:
3114 			event_acked = nvmf_rdma_handle_cm_event_addr_change(transport, event);
3115 			break;
3116 		case RDMA_CM_EVENT_TIMEWAIT_EXIT:
3117 			/* For now, do nothing. The target never re-uses queue pairs. */
3118 			break;
3119 		default:
3120 			SPDK_ERRLOG("Unexpected Acceptor Event [%d]\n", event->event);
3121 			break;
3122 		}
3123 		if (!event_acked) {
3124 			rdma_ack_cm_event(event);
3125 		}
3126 	}
3127 }
3128 
3129 static void
3130 nvmf_rdma_handle_qp_fatal(struct spdk_nvmf_rdma_qpair *rqpair)
3131 {
3132 	spdk_nvmf_rdma_update_ibv_state(rqpair);
3133 	spdk_nvmf_rdma_start_disconnect(rqpair);
3134 }
3135 
3136 static void
3137 nvmf_rdma_handle_last_wqe_reached(struct spdk_nvmf_rdma_qpair *rqpair)
3138 {
3139 	rqpair->last_wqe_reached = true;
3140 	nvmf_rdma_destroy_drained_qpair(rqpair);
3141 }
3142 
3143 static void
3144 nvmf_rdma_handle_sq_drained(struct spdk_nvmf_rdma_qpair *rqpair)
3145 {
3146 	spdk_nvmf_rdma_start_disconnect(rqpair);
3147 }
3148 
3149 static void
3150 spdk_nvmf_rdma_qpair_process_ibv_event(void *ctx)
3151 {
3152 	struct spdk_nvmf_rdma_ibv_event_ctx *event_ctx = ctx;
3153 
3154 	if (event_ctx->rqpair) {
3155 		STAILQ_REMOVE(&event_ctx->rqpair->ibv_events, event_ctx, spdk_nvmf_rdma_ibv_event_ctx, link);
3156 		if (event_ctx->cb_fn) {
3157 			event_ctx->cb_fn(event_ctx->rqpair);
3158 		}
3159 	}
3160 	free(event_ctx);
3161 }
3162 
3163 static int
3164 spdk_nvmf_rdma_send_qpair_async_event(struct spdk_nvmf_rdma_qpair *rqpair,
3165 				      spdk_nvmf_rdma_qpair_ibv_event fn)
3166 {
3167 	struct spdk_nvmf_rdma_ibv_event_ctx *ctx;
3168 
3169 	if (!rqpair->qpair.group) {
3170 		return EINVAL;
3171 	}
3172 
3173 	ctx = calloc(1, sizeof(*ctx));
3174 	if (!ctx) {
3175 		return ENOMEM;
3176 	}
3177 
3178 	ctx->rqpair = rqpair;
3179 	ctx->cb_fn = fn;
3180 	STAILQ_INSERT_TAIL(&rqpair->ibv_events, ctx, link);
3181 
3182 	return spdk_thread_send_msg(rqpair->qpair.group->thread, spdk_nvmf_rdma_qpair_process_ibv_event,
3183 				    ctx);
3184 }
3185 
3186 static void
3187 spdk_nvmf_process_ib_event(struct spdk_nvmf_rdma_device *device)
3188 {
3189 	int				rc;
3190 	struct spdk_nvmf_rdma_qpair	*rqpair = NULL;
3191 	struct ibv_async_event		event;
3192 
3193 	rc = ibv_get_async_event(device->context, &event);
3194 
3195 	if (rc) {
3196 		SPDK_ERRLOG("Failed to get async_event (%d): %s\n",
3197 			    errno, spdk_strerror(errno));
3198 		return;
3199 	}
3200 
3201 	switch (event.event_type) {
3202 	case IBV_EVENT_QP_FATAL:
3203 		rqpair = event.element.qp->qp_context;
3204 		SPDK_ERRLOG("Fatal event received for rqpair %p\n", rqpair);
3205 		spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0,
3206 				  (uintptr_t)rqpair->cm_id, event.event_type);
3207 		if (spdk_nvmf_rdma_send_qpair_async_event(rqpair, nvmf_rdma_handle_qp_fatal)) {
3208 			SPDK_ERRLOG("Failed to send QP_FATAL event for rqpair %p\n", rqpair);
3209 			nvmf_rdma_handle_qp_fatal(rqpair);
3210 		}
3211 		break;
3212 	case IBV_EVENT_QP_LAST_WQE_REACHED:
3213 		/* This event only occurs for shared receive queues. */
3214 		rqpair = event.element.qp->qp_context;
3215 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Last WQE reached event received for rqpair %p\n", rqpair);
3216 		if (spdk_nvmf_rdma_send_qpair_async_event(rqpair, nvmf_rdma_handle_last_wqe_reached)) {
3217 			SPDK_ERRLOG("Failed to send LAST_WQE_REACHED event for rqpair %p\n", rqpair);
3218 			rqpair->last_wqe_reached = true;
3219 		}
3220 		break;
3221 	case IBV_EVENT_SQ_DRAINED:
3222 		/* This event occurs frequently in both error and non-error states.
3223 		 * Check if the qpair is in an error state before sending a message. */
3224 		rqpair = event.element.qp->qp_context;
3225 		SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Last sq drained event received for rqpair %p\n", rqpair);
3226 		spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0,
3227 				  (uintptr_t)rqpair->cm_id, event.event_type);
3228 		if (spdk_nvmf_rdma_update_ibv_state(rqpair) == IBV_QPS_ERR) {
3229 			if (spdk_nvmf_rdma_send_qpair_async_event(rqpair, nvmf_rdma_handle_sq_drained)) {
3230 				SPDK_ERRLOG("Failed to send SQ_DRAINED event for rqpair %p\n", rqpair);
3231 				nvmf_rdma_handle_sq_drained(rqpair);
3232 			}
3233 		}
3234 		break;
3235 	case IBV_EVENT_QP_REQ_ERR:
3236 	case IBV_EVENT_QP_ACCESS_ERR:
3237 	case IBV_EVENT_COMM_EST:
3238 	case IBV_EVENT_PATH_MIG:
3239 	case IBV_EVENT_PATH_MIG_ERR:
3240 		SPDK_NOTICELOG("Async event: %s\n",
3241 			       ibv_event_type_str(event.event_type));
3242 		rqpair = event.element.qp->qp_context;
3243 		spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0,
3244 				  (uintptr_t)rqpair->cm_id, event.event_type);
3245 		spdk_nvmf_rdma_update_ibv_state(rqpair);
3246 		break;
3247 	case IBV_EVENT_CQ_ERR:
3248 	case IBV_EVENT_DEVICE_FATAL:
3249 	case IBV_EVENT_PORT_ACTIVE:
3250 	case IBV_EVENT_PORT_ERR:
3251 	case IBV_EVENT_LID_CHANGE:
3252 	case IBV_EVENT_PKEY_CHANGE:
3253 	case IBV_EVENT_SM_CHANGE:
3254 	case IBV_EVENT_SRQ_ERR:
3255 	case IBV_EVENT_SRQ_LIMIT_REACHED:
3256 	case IBV_EVENT_CLIENT_REREGISTER:
3257 	case IBV_EVENT_GID_CHANGE:
3258 	default:
3259 		SPDK_NOTICELOG("Async event: %s\n",
3260 			       ibv_event_type_str(event.event_type));
3261 		spdk_trace_record(TRACE_RDMA_IBV_ASYNC_EVENT, 0, 0, 0, event.event_type);
3262 		break;
3263 	}
3264 	ibv_ack_async_event(&event);
3265 }
3266 
3267 static void
3268 spdk_nvmf_rdma_accept(struct spdk_nvmf_transport *transport, new_qpair_fn cb_fn, void *cb_arg)
3269 {
3270 	int	nfds, i = 0;
3271 	struct spdk_nvmf_rdma_transport *rtransport;
3272 	struct spdk_nvmf_rdma_device *device, *tmp;
3273 
3274 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3275 	nfds = poll(rtransport->poll_fds, rtransport->npoll_fds, 0);
3276 
3277 	if (nfds <= 0) {
3278 		return;
3279 	}
3280 
3281 	/* The first poll descriptor is RDMA CM event */
3282 	if (rtransport->poll_fds[i++].revents & POLLIN) {
3283 		spdk_nvmf_process_cm_event(transport, cb_fn, cb_arg);
3284 		nfds--;
3285 	}
3286 
3287 	if (nfds == 0) {
3288 		return;
3289 	}
3290 
3291 	/* Second and subsequent poll descriptors are IB async events */
3292 	TAILQ_FOREACH_SAFE(device, &rtransport->devices, link, tmp) {
3293 		if (rtransport->poll_fds[i++].revents & POLLIN) {
3294 			spdk_nvmf_process_ib_event(device);
3295 			nfds--;
3296 		}
3297 	}
3298 	/* check all flagged fd's have been served */
3299 	assert(nfds == 0);
3300 }
3301 
3302 static void
3303 spdk_nvmf_rdma_discover(struct spdk_nvmf_transport *transport,
3304 			struct spdk_nvme_transport_id *trid,
3305 			struct spdk_nvmf_discovery_log_page_entry *entry)
3306 {
3307 	entry->trtype = SPDK_NVMF_TRTYPE_RDMA;
3308 	entry->adrfam = trid->adrfam;
3309 	entry->treq.secure_channel = SPDK_NVMF_TREQ_SECURE_CHANNEL_NOT_REQUIRED;
3310 
3311 	spdk_strcpy_pad(entry->trsvcid, trid->trsvcid, sizeof(entry->trsvcid), ' ');
3312 	spdk_strcpy_pad(entry->traddr, trid->traddr, sizeof(entry->traddr), ' ');
3313 
3314 	entry->tsas.rdma.rdma_qptype = SPDK_NVMF_RDMA_QPTYPE_RELIABLE_CONNECTED;
3315 	entry->tsas.rdma.rdma_prtype = SPDK_NVMF_RDMA_PRTYPE_NONE;
3316 	entry->tsas.rdma.rdma_cms = SPDK_NVMF_RDMA_CMS_RDMA_CM;
3317 }
3318 
3319 static void
3320 spdk_nvmf_rdma_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group);
3321 
3322 static struct spdk_nvmf_transport_poll_group *
3323 spdk_nvmf_rdma_poll_group_create(struct spdk_nvmf_transport *transport)
3324 {
3325 	struct spdk_nvmf_rdma_transport		*rtransport;
3326 	struct spdk_nvmf_rdma_poll_group	*rgroup;
3327 	struct spdk_nvmf_rdma_poller		*poller;
3328 	struct spdk_nvmf_rdma_device		*device;
3329 	struct ibv_srq_init_attr		srq_init_attr;
3330 	struct spdk_nvmf_rdma_resource_opts	opts;
3331 	int					num_cqe;
3332 
3333 	rtransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_rdma_transport, transport);
3334 
3335 	rgroup = calloc(1, sizeof(*rgroup));
3336 	if (!rgroup) {
3337 		return NULL;
3338 	}
3339 
3340 	TAILQ_INIT(&rgroup->pollers);
3341 	STAILQ_INIT(&rgroup->retired_bufs);
3342 
3343 	pthread_mutex_lock(&rtransport->lock);
3344 	TAILQ_FOREACH(device, &rtransport->devices, link) {
3345 		poller = calloc(1, sizeof(*poller));
3346 		if (!poller) {
3347 			SPDK_ERRLOG("Unable to allocate memory for new RDMA poller\n");
3348 			spdk_nvmf_rdma_poll_group_destroy(&rgroup->group);
3349 			pthread_mutex_unlock(&rtransport->lock);
3350 			return NULL;
3351 		}
3352 
3353 		poller->device = device;
3354 		poller->group = rgroup;
3355 
3356 		TAILQ_INIT(&poller->qpairs);
3357 		STAILQ_INIT(&poller->qpairs_pending_send);
3358 		STAILQ_INIT(&poller->qpairs_pending_recv);
3359 
3360 		TAILQ_INSERT_TAIL(&rgroup->pollers, poller, link);
3361 		if (transport->opts.no_srq == false && device->num_srq < device->attr.max_srq) {
3362 			poller->max_srq_depth = transport->opts.max_srq_depth;
3363 
3364 			device->num_srq++;
3365 			memset(&srq_init_attr, 0, sizeof(struct ibv_srq_init_attr));
3366 			srq_init_attr.attr.max_wr = poller->max_srq_depth;
3367 			srq_init_attr.attr.max_sge = spdk_min(device->attr.max_sge, NVMF_DEFAULT_RX_SGE);
3368 			poller->srq = ibv_create_srq(device->pd, &srq_init_attr);
3369 			if (!poller->srq) {
3370 				SPDK_ERRLOG("Unable to create shared receive queue, errno %d\n", errno);
3371 				spdk_nvmf_rdma_poll_group_destroy(&rgroup->group);
3372 				pthread_mutex_unlock(&rtransport->lock);
3373 				return NULL;
3374 			}
3375 
3376 			opts.qp = poller->srq;
3377 			opts.pd = device->pd;
3378 			opts.qpair = NULL;
3379 			opts.shared = true;
3380 			opts.max_queue_depth = poller->max_srq_depth;
3381 			opts.in_capsule_data_size = transport->opts.in_capsule_data_size;
3382 
3383 			poller->resources = nvmf_rdma_resources_create(&opts);
3384 			if (!poller->resources) {
3385 				SPDK_ERRLOG("Unable to allocate resources for shared receive queue.\n");
3386 				spdk_nvmf_rdma_poll_group_destroy(&rgroup->group);
3387 				pthread_mutex_unlock(&rtransport->lock);
3388 				return NULL;
3389 			}
3390 		}
3391 
3392 		/*
3393 		 * When using an srq, we can limit the completion queue at startup.
3394 		 * The following formula represents the calculation:
3395 		 * num_cqe = num_recv + num_data_wr + num_send_wr.
3396 		 * where num_recv=num_data_wr=and num_send_wr=poller->max_srq_depth
3397 		 */
3398 		if (poller->srq) {
3399 			num_cqe = poller->max_srq_depth * 3;
3400 		} else {
3401 			num_cqe = DEFAULT_NVMF_RDMA_CQ_SIZE;
3402 		}
3403 
3404 		poller->cq = ibv_create_cq(device->context, num_cqe, poller, NULL, 0);
3405 		if (!poller->cq) {
3406 			SPDK_ERRLOG("Unable to create completion queue\n");
3407 			spdk_nvmf_rdma_poll_group_destroy(&rgroup->group);
3408 			pthread_mutex_unlock(&rtransport->lock);
3409 			return NULL;
3410 		}
3411 		poller->num_cqe = num_cqe;
3412 	}
3413 
3414 	TAILQ_INSERT_TAIL(&rtransport->poll_groups, rgroup, link);
3415 	if (rtransport->conn_sched.next_admin_pg == NULL) {
3416 		rtransport->conn_sched.next_admin_pg = rgroup;
3417 		rtransport->conn_sched.next_io_pg = rgroup;
3418 	}
3419 
3420 	pthread_mutex_unlock(&rtransport->lock);
3421 	return &rgroup->group;
3422 }
3423 
3424 static struct spdk_nvmf_transport_poll_group *
3425 spdk_nvmf_rdma_get_optimal_poll_group(struct spdk_nvmf_qpair *qpair)
3426 {
3427 	struct spdk_nvmf_rdma_transport *rtransport;
3428 	struct spdk_nvmf_rdma_poll_group **pg;
3429 	struct spdk_nvmf_transport_poll_group *result;
3430 
3431 	rtransport = SPDK_CONTAINEROF(qpair->transport, struct spdk_nvmf_rdma_transport, transport);
3432 
3433 	pthread_mutex_lock(&rtransport->lock);
3434 
3435 	if (TAILQ_EMPTY(&rtransport->poll_groups)) {
3436 		pthread_mutex_unlock(&rtransport->lock);
3437 		return NULL;
3438 	}
3439 
3440 	if (qpair->qid == 0) {
3441 		pg = &rtransport->conn_sched.next_admin_pg;
3442 	} else {
3443 		pg = &rtransport->conn_sched.next_io_pg;
3444 	}
3445 
3446 	assert(*pg != NULL);
3447 
3448 	result = &(*pg)->group;
3449 
3450 	*pg = TAILQ_NEXT(*pg, link);
3451 	if (*pg == NULL) {
3452 		*pg = TAILQ_FIRST(&rtransport->poll_groups);
3453 	}
3454 
3455 	pthread_mutex_unlock(&rtransport->lock);
3456 
3457 	return result;
3458 }
3459 
3460 static void
3461 spdk_nvmf_rdma_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group)
3462 {
3463 	struct spdk_nvmf_rdma_poll_group	*rgroup, *next_rgroup;
3464 	struct spdk_nvmf_rdma_poller		*poller, *tmp;
3465 	struct spdk_nvmf_rdma_qpair		*qpair, *tmp_qpair;
3466 	struct spdk_nvmf_transport_pg_cache_buf	*buf, *tmp_buf;
3467 	struct spdk_nvmf_rdma_transport		*rtransport;
3468 
3469 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
3470 	if (!rgroup) {
3471 		return;
3472 	}
3473 
3474 	/* free all retired buffers back to the transport so we don't short the mempool. */
3475 	STAILQ_FOREACH_SAFE(buf, &rgroup->retired_bufs, link, tmp_buf) {
3476 		STAILQ_REMOVE(&rgroup->retired_bufs, buf, spdk_nvmf_transport_pg_cache_buf, link);
3477 		assert(group->transport != NULL);
3478 		spdk_mempool_put(group->transport->data_buf_pool, buf);
3479 	}
3480 
3481 	TAILQ_FOREACH_SAFE(poller, &rgroup->pollers, link, tmp) {
3482 		TAILQ_REMOVE(&rgroup->pollers, poller, link);
3483 
3484 		TAILQ_FOREACH_SAFE(qpair, &poller->qpairs, link, tmp_qpair) {
3485 			spdk_nvmf_rdma_qpair_destroy(qpair);
3486 		}
3487 
3488 		if (poller->srq) {
3489 			nvmf_rdma_resources_destroy(poller->resources);
3490 			ibv_destroy_srq(poller->srq);
3491 			SPDK_DEBUGLOG(SPDK_LOG_RDMA, "Destroyed RDMA shared queue %p\n", poller->srq);
3492 		}
3493 
3494 		if (poller->cq) {
3495 			ibv_destroy_cq(poller->cq);
3496 		}
3497 
3498 		free(poller);
3499 	}
3500 
3501 	if (rgroup->group.transport == NULL) {
3502 		/* Transport can be NULL when spdk_nvmf_rdma_poll_group_create()
3503 		 * calls this function directly in a failure path. */
3504 		free(rgroup);
3505 		return;
3506 	}
3507 
3508 	rtransport = SPDK_CONTAINEROF(rgroup->group.transport, struct spdk_nvmf_rdma_transport, transport);
3509 
3510 	pthread_mutex_lock(&rtransport->lock);
3511 	next_rgroup = TAILQ_NEXT(rgroup, link);
3512 	TAILQ_REMOVE(&rtransport->poll_groups, rgroup, link);
3513 	if (next_rgroup == NULL) {
3514 		next_rgroup = TAILQ_FIRST(&rtransport->poll_groups);
3515 	}
3516 	if (rtransport->conn_sched.next_admin_pg == rgroup) {
3517 		rtransport->conn_sched.next_admin_pg = next_rgroup;
3518 	}
3519 	if (rtransport->conn_sched.next_io_pg == rgroup) {
3520 		rtransport->conn_sched.next_io_pg = next_rgroup;
3521 	}
3522 	pthread_mutex_unlock(&rtransport->lock);
3523 
3524 	free(rgroup);
3525 }
3526 
3527 static void
3528 spdk_nvmf_rdma_qpair_reject_connection(struct spdk_nvmf_rdma_qpair *rqpair)
3529 {
3530 	if (rqpair->cm_id != NULL) {
3531 		spdk_nvmf_rdma_event_reject(rqpair->cm_id, SPDK_NVMF_RDMA_ERROR_NO_RESOURCES);
3532 	}
3533 	spdk_nvmf_rdma_qpair_destroy(rqpair);
3534 }
3535 
3536 static int
3537 spdk_nvmf_rdma_poll_group_add(struct spdk_nvmf_transport_poll_group *group,
3538 			      struct spdk_nvmf_qpair *qpair)
3539 {
3540 	struct spdk_nvmf_rdma_poll_group	*rgroup;
3541 	struct spdk_nvmf_rdma_qpair		*rqpair;
3542 	struct spdk_nvmf_rdma_device		*device;
3543 	struct spdk_nvmf_rdma_poller		*poller;
3544 	int					rc;
3545 
3546 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
3547 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
3548 
3549 	device = rqpair->device;
3550 
3551 	TAILQ_FOREACH(poller, &rgroup->pollers, link) {
3552 		if (poller->device == device) {
3553 			break;
3554 		}
3555 	}
3556 
3557 	if (!poller) {
3558 		SPDK_ERRLOG("No poller found for device.\n");
3559 		return -1;
3560 	}
3561 
3562 	TAILQ_INSERT_TAIL(&poller->qpairs, rqpair, link);
3563 	rqpair->poller = poller;
3564 	rqpair->srq = rqpair->poller->srq;
3565 
3566 	rc = spdk_nvmf_rdma_qpair_initialize(qpair);
3567 	if (rc < 0) {
3568 		SPDK_ERRLOG("Failed to initialize nvmf_rdma_qpair with qpair=%p\n", qpair);
3569 		return -1;
3570 	}
3571 
3572 	rc = spdk_nvmf_rdma_event_accept(rqpair->cm_id, rqpair);
3573 	if (rc) {
3574 		/* Try to reject, but we probably can't */
3575 		spdk_nvmf_rdma_qpair_reject_connection(rqpair);
3576 		return -1;
3577 	}
3578 
3579 	spdk_nvmf_rdma_update_ibv_state(rqpair);
3580 
3581 	return 0;
3582 }
3583 
3584 static int
3585 spdk_nvmf_rdma_request_free(struct spdk_nvmf_request *req)
3586 {
3587 	struct spdk_nvmf_rdma_request	*rdma_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_rdma_request, req);
3588 	struct spdk_nvmf_rdma_transport	*rtransport = SPDK_CONTAINEROF(req->qpair->transport,
3589 			struct spdk_nvmf_rdma_transport, transport);
3590 
3591 	nvmf_rdma_request_free(rdma_req, rtransport);
3592 	return 0;
3593 }
3594 
3595 static int
3596 spdk_nvmf_rdma_request_complete(struct spdk_nvmf_request *req)
3597 {
3598 	struct spdk_nvmf_rdma_transport	*rtransport = SPDK_CONTAINEROF(req->qpair->transport,
3599 			struct spdk_nvmf_rdma_transport, transport);
3600 	struct spdk_nvmf_rdma_request	*rdma_req = SPDK_CONTAINEROF(req,
3601 			struct spdk_nvmf_rdma_request, req);
3602 	struct spdk_nvmf_rdma_qpair     *rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair,
3603 			struct spdk_nvmf_rdma_qpair, qpair);
3604 
3605 	if (rqpair->ibv_state != IBV_QPS_ERR) {
3606 		/* The connection is alive, so process the request as normal */
3607 		rdma_req->state = RDMA_REQUEST_STATE_EXECUTED;
3608 	} else {
3609 		/* The connection is dead. Move the request directly to the completed state. */
3610 		rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
3611 	}
3612 
3613 	spdk_nvmf_rdma_request_process(rtransport, rdma_req);
3614 
3615 	return 0;
3616 }
3617 
3618 static int
3619 spdk_nvmf_rdma_destroy_defunct_qpair(void *ctx)
3620 {
3621 	struct spdk_nvmf_rdma_qpair	*rqpair = ctx;
3622 	struct spdk_nvmf_rdma_transport *rtransport = SPDK_CONTAINEROF(rqpair->qpair.transport,
3623 			struct spdk_nvmf_rdma_transport, transport);
3624 
3625 	SPDK_INFOLOG(SPDK_LOG_RDMA, "QP#%d hasn't been drained as expected, manually destroy it\n",
3626 		     rqpair->qpair.qid);
3627 
3628 	spdk_nvmf_rdma_qpair_process_pending(rtransport, rqpair, true);
3629 	spdk_nvmf_rdma_qpair_destroy(rqpair);
3630 
3631 	return 0;
3632 }
3633 
3634 static void
3635 spdk_nvmf_rdma_close_qpair(struct spdk_nvmf_qpair *qpair)
3636 {
3637 	struct spdk_nvmf_rdma_qpair *rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
3638 
3639 	if (rqpair->disconnect_flags & RDMA_QP_DISCONNECTING) {
3640 		return;
3641 	}
3642 
3643 	rqpair->disconnect_flags |= RDMA_QP_DISCONNECTING;
3644 
3645 	/* This happens only when the qpair is disconnected before
3646 	 * it is added to the poll group. Since there is no poll group,
3647 	 * the RDMA qp has not been initialized yet and the RDMA CM
3648 	 * event has not yet been acknowledged, so we need to reject it.
3649 	 */
3650 	if (rqpair->qpair.state == SPDK_NVMF_QPAIR_UNINITIALIZED) {
3651 		spdk_nvmf_rdma_qpair_reject_connection(rqpair);
3652 		return;
3653 	}
3654 
3655 	if (rqpair->ibv_state != IBV_QPS_ERR) {
3656 		spdk_nvmf_rdma_set_ibv_state(rqpair, IBV_QPS_ERR);
3657 	}
3658 
3659 	rqpair->destruct_poller = spdk_poller_register(spdk_nvmf_rdma_destroy_defunct_qpair, (void *)rqpair,
3660 				  NVMF_RDMA_QPAIR_DESTROY_TIMEOUT_US);
3661 }
3662 
3663 static struct spdk_nvmf_rdma_qpair *
3664 get_rdma_qpair_from_wc(struct spdk_nvmf_rdma_poller *rpoller, struct ibv_wc *wc)
3665 {
3666 	struct spdk_nvmf_rdma_qpair *rqpair;
3667 	/* @todo: improve QP search */
3668 	TAILQ_FOREACH(rqpair, &rpoller->qpairs, link) {
3669 		if (wc->qp_num == rqpair->cm_id->qp->qp_num) {
3670 			return rqpair;
3671 		}
3672 	}
3673 	SPDK_ERRLOG("Didn't find QP with qp_num %u\n", wc->qp_num);
3674 	return NULL;
3675 }
3676 
3677 #ifdef DEBUG
3678 static int
3679 spdk_nvmf_rdma_req_is_completing(struct spdk_nvmf_rdma_request *rdma_req)
3680 {
3681 	return rdma_req->state == RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST ||
3682 	       rdma_req->state == RDMA_REQUEST_STATE_COMPLETING;
3683 }
3684 #endif
3685 
3686 static void
3687 _poller_reset_failed_recvs(struct spdk_nvmf_rdma_poller *rpoller, struct ibv_recv_wr *bad_recv_wr,
3688 			   int rc)
3689 {
3690 	struct spdk_nvmf_rdma_recv	*rdma_recv;
3691 	struct spdk_nvmf_rdma_wr	*bad_rdma_wr;
3692 
3693 	SPDK_ERRLOG("Failed to post a recv for the poller %p with errno %d\n", rpoller, -rc);
3694 	while (bad_recv_wr != NULL) {
3695 		bad_rdma_wr = (struct spdk_nvmf_rdma_wr *)bad_recv_wr->wr_id;
3696 		rdma_recv = SPDK_CONTAINEROF(bad_rdma_wr, struct spdk_nvmf_rdma_recv, rdma_wr);
3697 
3698 		rdma_recv->qpair->current_recv_depth++;
3699 		bad_recv_wr = bad_recv_wr->next;
3700 		SPDK_ERRLOG("Failed to post a recv for the qpair %p with errno %d\n", rdma_recv->qpair, -rc);
3701 		spdk_nvmf_rdma_start_disconnect(rdma_recv->qpair);
3702 	}
3703 }
3704 
3705 static void
3706 _qp_reset_failed_recvs(struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_recv_wr *bad_recv_wr, int rc)
3707 {
3708 	SPDK_ERRLOG("Failed to post a recv for the qpair %p with errno %d\n", rqpair, -rc);
3709 	while (bad_recv_wr != NULL) {
3710 		bad_recv_wr = bad_recv_wr->next;
3711 		rqpair->current_recv_depth++;
3712 	}
3713 	spdk_nvmf_rdma_start_disconnect(rqpair);
3714 }
3715 
3716 static void
3717 _poller_submit_recvs(struct spdk_nvmf_rdma_transport *rtransport,
3718 		     struct spdk_nvmf_rdma_poller *rpoller)
3719 {
3720 	struct spdk_nvmf_rdma_qpair	*rqpair;
3721 	struct ibv_recv_wr		*bad_recv_wr;
3722 	int				rc;
3723 
3724 	if (rpoller->srq) {
3725 		if (rpoller->resources->recvs_to_post.first != NULL) {
3726 			rc = ibv_post_srq_recv(rpoller->srq, rpoller->resources->recvs_to_post.first, &bad_recv_wr);
3727 			if (rc) {
3728 				_poller_reset_failed_recvs(rpoller, bad_recv_wr, rc);
3729 			}
3730 			rpoller->resources->recvs_to_post.first = NULL;
3731 			rpoller->resources->recvs_to_post.last = NULL;
3732 		}
3733 	} else {
3734 		while (!STAILQ_EMPTY(&rpoller->qpairs_pending_recv)) {
3735 			rqpair = STAILQ_FIRST(&rpoller->qpairs_pending_recv);
3736 			assert(rqpair->resources->recvs_to_post.first != NULL);
3737 			rc = ibv_post_recv(rqpair->cm_id->qp, rqpair->resources->recvs_to_post.first, &bad_recv_wr);
3738 			if (rc) {
3739 				_qp_reset_failed_recvs(rqpair, bad_recv_wr, rc);
3740 			}
3741 			rqpair->resources->recvs_to_post.first = NULL;
3742 			rqpair->resources->recvs_to_post.last = NULL;
3743 			STAILQ_REMOVE_HEAD(&rpoller->qpairs_pending_recv, recv_link);
3744 		}
3745 	}
3746 }
3747 
3748 static void
3749 _qp_reset_failed_sends(struct spdk_nvmf_rdma_transport *rtransport,
3750 		       struct spdk_nvmf_rdma_qpair *rqpair, struct ibv_send_wr *bad_wr, int rc)
3751 {
3752 	struct spdk_nvmf_rdma_wr	*bad_rdma_wr;
3753 	struct spdk_nvmf_rdma_request	*prev_rdma_req = NULL, *cur_rdma_req = NULL;
3754 
3755 	SPDK_ERRLOG("Failed to post a send for the qpair %p with errno %d\n", rqpair, -rc);
3756 	for (; bad_wr != NULL; bad_wr = bad_wr->next) {
3757 		bad_rdma_wr = (struct spdk_nvmf_rdma_wr *)bad_wr->wr_id;
3758 		assert(rqpair->current_send_depth > 0);
3759 		rqpair->current_send_depth--;
3760 		switch (bad_rdma_wr->type) {
3761 		case RDMA_WR_TYPE_DATA:
3762 			cur_rdma_req = SPDK_CONTAINEROF(bad_rdma_wr, struct spdk_nvmf_rdma_request, data.rdma_wr);
3763 			if (bad_wr->opcode == IBV_WR_RDMA_READ) {
3764 				assert(rqpair->current_read_depth > 0);
3765 				rqpair->current_read_depth--;
3766 			}
3767 			break;
3768 		case RDMA_WR_TYPE_SEND:
3769 			cur_rdma_req = SPDK_CONTAINEROF(bad_rdma_wr, struct spdk_nvmf_rdma_request, rsp.rdma_wr);
3770 			break;
3771 		default:
3772 			SPDK_ERRLOG("Found a RECV in the list of pending SEND requests for qpair %p\n", rqpair);
3773 			prev_rdma_req = cur_rdma_req;
3774 			continue;
3775 		}
3776 
3777 		if (prev_rdma_req == cur_rdma_req) {
3778 			/* this request was handled by an earlier wr. i.e. we were performing an nvme read. */
3779 			/* We only have to check against prev_wr since each requests wrs are contiguous in this list. */
3780 			continue;
3781 		}
3782 
3783 		switch (cur_rdma_req->state) {
3784 		case RDMA_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER:
3785 			cur_rdma_req->req.rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3786 			cur_rdma_req->state = RDMA_REQUEST_STATE_READY_TO_COMPLETE;
3787 			break;
3788 		case RDMA_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST:
3789 		case RDMA_REQUEST_STATE_COMPLETING:
3790 			cur_rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
3791 			break;
3792 		default:
3793 			SPDK_ERRLOG("Found a request in a bad state %d when draining pending SEND requests for qpair %p\n",
3794 				    cur_rdma_req->state, rqpair);
3795 			continue;
3796 		}
3797 
3798 		spdk_nvmf_rdma_request_process(rtransport, cur_rdma_req);
3799 		prev_rdma_req = cur_rdma_req;
3800 	}
3801 
3802 	if (rqpair->qpair.state == SPDK_NVMF_QPAIR_ACTIVE) {
3803 		/* Disconnect the connection. */
3804 		spdk_nvmf_rdma_start_disconnect(rqpair);
3805 	}
3806 
3807 }
3808 
3809 static void
3810 _poller_submit_sends(struct spdk_nvmf_rdma_transport *rtransport,
3811 		     struct spdk_nvmf_rdma_poller *rpoller)
3812 {
3813 	struct spdk_nvmf_rdma_qpair	*rqpair;
3814 	struct ibv_send_wr		*bad_wr = NULL;
3815 	int				rc;
3816 
3817 	while (!STAILQ_EMPTY(&rpoller->qpairs_pending_send)) {
3818 		rqpair = STAILQ_FIRST(&rpoller->qpairs_pending_send);
3819 		assert(rqpair->sends_to_post.first != NULL);
3820 		rc = ibv_post_send(rqpair->cm_id->qp, rqpair->sends_to_post.first, &bad_wr);
3821 
3822 		/* bad wr always points to the first wr that failed. */
3823 		if (rc) {
3824 			_qp_reset_failed_sends(rtransport, rqpair, bad_wr, rc);
3825 		}
3826 		rqpair->sends_to_post.first = NULL;
3827 		rqpair->sends_to_post.last = NULL;
3828 		STAILQ_REMOVE_HEAD(&rpoller->qpairs_pending_send, send_link);
3829 	}
3830 }
3831 
3832 static int
3833 spdk_nvmf_rdma_poller_poll(struct spdk_nvmf_rdma_transport *rtransport,
3834 			   struct spdk_nvmf_rdma_poller *rpoller)
3835 {
3836 	struct ibv_wc wc[32];
3837 	struct spdk_nvmf_rdma_wr	*rdma_wr;
3838 	struct spdk_nvmf_rdma_request	*rdma_req;
3839 	struct spdk_nvmf_rdma_recv	*rdma_recv;
3840 	struct spdk_nvmf_rdma_qpair	*rqpair;
3841 	int reaped, i;
3842 	int count = 0;
3843 	bool error = false;
3844 	uint64_t poll_tsc = spdk_get_ticks();
3845 
3846 	/* Poll for completing operations. */
3847 	reaped = ibv_poll_cq(rpoller->cq, 32, wc);
3848 	if (reaped < 0) {
3849 		SPDK_ERRLOG("Error polling CQ! (%d): %s\n",
3850 			    errno, spdk_strerror(errno));
3851 		return -1;
3852 	}
3853 
3854 	rpoller->stat.polls++;
3855 	rpoller->stat.completions += reaped;
3856 
3857 	for (i = 0; i < reaped; i++) {
3858 
3859 		rdma_wr = (struct spdk_nvmf_rdma_wr *)wc[i].wr_id;
3860 
3861 		switch (rdma_wr->type) {
3862 		case RDMA_WR_TYPE_SEND:
3863 			rdma_req = SPDK_CONTAINEROF(rdma_wr, struct spdk_nvmf_rdma_request, rsp.rdma_wr);
3864 			rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
3865 
3866 			if (!wc[i].status) {
3867 				count++;
3868 				assert(wc[i].opcode == IBV_WC_SEND);
3869 				assert(spdk_nvmf_rdma_req_is_completing(rdma_req));
3870 			} else {
3871 				SPDK_ERRLOG("data=%p length=%u\n", rdma_req->req.data, rdma_req->req.length);
3872 			}
3873 
3874 			rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
3875 			/* +1 for the response wr */
3876 			rqpair->current_send_depth -= rdma_req->num_outstanding_data_wr + 1;
3877 			rdma_req->num_outstanding_data_wr = 0;
3878 
3879 			spdk_nvmf_rdma_request_process(rtransport, rdma_req);
3880 			break;
3881 		case RDMA_WR_TYPE_RECV:
3882 			/* rdma_recv->qpair will be invalid if using an SRQ.  In that case we have to get the qpair from the wc. */
3883 			rdma_recv = SPDK_CONTAINEROF(rdma_wr, struct spdk_nvmf_rdma_recv, rdma_wr);
3884 			if (rpoller->srq != NULL) {
3885 				rdma_recv->qpair = get_rdma_qpair_from_wc(rpoller, &wc[i]);
3886 				/* It is possible that there are still some completions for destroyed QP
3887 				 * associated with SRQ. We just ignore these late completions and re-post
3888 				 * receive WRs back to SRQ.
3889 				 */
3890 				if (spdk_unlikely(NULL == rdma_recv->qpair)) {
3891 					struct ibv_recv_wr *bad_wr;
3892 					int rc;
3893 
3894 					rdma_recv->wr.next = NULL;
3895 					rc = ibv_post_srq_recv(rpoller->srq,
3896 							       &rdma_recv->wr,
3897 							       &bad_wr);
3898 					if (rc) {
3899 						SPDK_ERRLOG("Failed to re-post recv WR to SRQ, err %d\n", rc);
3900 					}
3901 					continue;
3902 				}
3903 			}
3904 			rqpair = rdma_recv->qpair;
3905 
3906 			assert(rqpair != NULL);
3907 			if (!wc[i].status) {
3908 				assert(wc[i].opcode == IBV_WC_RECV);
3909 				if (rqpair->current_recv_depth >= rqpair->max_queue_depth) {
3910 					spdk_nvmf_rdma_start_disconnect(rqpair);
3911 					break;
3912 				}
3913 			}
3914 
3915 			rdma_recv->wr.next = NULL;
3916 			rqpair->current_recv_depth++;
3917 			rdma_recv->receive_tsc = poll_tsc;
3918 			rpoller->stat.requests++;
3919 			STAILQ_INSERT_TAIL(&rqpair->resources->incoming_queue, rdma_recv, link);
3920 			break;
3921 		case RDMA_WR_TYPE_DATA:
3922 			rdma_req = SPDK_CONTAINEROF(rdma_wr, struct spdk_nvmf_rdma_request, data.rdma_wr);
3923 			rqpair = SPDK_CONTAINEROF(rdma_req->req.qpair, struct spdk_nvmf_rdma_qpair, qpair);
3924 
3925 			assert(rdma_req->num_outstanding_data_wr > 0);
3926 
3927 			rqpair->current_send_depth--;
3928 			rdma_req->num_outstanding_data_wr--;
3929 			if (!wc[i].status) {
3930 				assert(wc[i].opcode == IBV_WC_RDMA_READ);
3931 				rqpair->current_read_depth--;
3932 				/* wait for all outstanding reads associated with the same rdma_req to complete before proceeding. */
3933 				if (rdma_req->num_outstanding_data_wr == 0) {
3934 					rdma_req->state = RDMA_REQUEST_STATE_READY_TO_EXECUTE;
3935 					spdk_nvmf_rdma_request_process(rtransport, rdma_req);
3936 				}
3937 			} else {
3938 				/* If the data transfer fails still force the queue into the error state,
3939 				 * if we were performing an RDMA_READ, we need to force the request into a
3940 				 * completed state since it wasn't linked to a send. However, in the RDMA_WRITE
3941 				 * case, we should wait for the SEND to complete. */
3942 				SPDK_ERRLOG("data=%p length=%u\n", rdma_req->req.data, rdma_req->req.length);
3943 				if (rdma_req->data.wr.opcode == IBV_WR_RDMA_READ) {
3944 					rqpair->current_read_depth--;
3945 					if (rdma_req->num_outstanding_data_wr == 0) {
3946 						rdma_req->state = RDMA_REQUEST_STATE_COMPLETED;
3947 					}
3948 				}
3949 			}
3950 			break;
3951 		default:
3952 			SPDK_ERRLOG("Received an unknown opcode on the CQ: %d\n", wc[i].opcode);
3953 			continue;
3954 		}
3955 
3956 		/* Handle error conditions */
3957 		if (wc[i].status) {
3958 			SPDK_DEBUGLOG(SPDK_LOG_RDMA, "CQ error on CQ %p, Request 0x%lu (%d): %s\n",
3959 				      rpoller->cq, wc[i].wr_id, wc[i].status, ibv_wc_status_str(wc[i].status));
3960 
3961 			error = true;
3962 
3963 			if (rqpair->qpair.state == SPDK_NVMF_QPAIR_ACTIVE) {
3964 				/* Disconnect the connection. */
3965 				spdk_nvmf_rdma_start_disconnect(rqpair);
3966 			} else {
3967 				nvmf_rdma_destroy_drained_qpair(rqpair);
3968 			}
3969 			continue;
3970 		}
3971 
3972 		spdk_nvmf_rdma_qpair_process_pending(rtransport, rqpair, false);
3973 
3974 		if (rqpair->qpair.state != SPDK_NVMF_QPAIR_ACTIVE) {
3975 			nvmf_rdma_destroy_drained_qpair(rqpair);
3976 		}
3977 	}
3978 
3979 	if (error == true) {
3980 		return -1;
3981 	}
3982 
3983 	/* submit outstanding work requests. */
3984 	_poller_submit_recvs(rtransport, rpoller);
3985 	_poller_submit_sends(rtransport, rpoller);
3986 
3987 	return count;
3988 }
3989 
3990 static int
3991 spdk_nvmf_rdma_poll_group_poll(struct spdk_nvmf_transport_poll_group *group)
3992 {
3993 	struct spdk_nvmf_rdma_transport *rtransport;
3994 	struct spdk_nvmf_rdma_poll_group *rgroup;
3995 	struct spdk_nvmf_rdma_poller	*rpoller;
3996 	int				count, rc;
3997 
3998 	rtransport = SPDK_CONTAINEROF(group->transport, struct spdk_nvmf_rdma_transport, transport);
3999 	rgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_rdma_poll_group, group);
4000 
4001 	count = 0;
4002 	TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
4003 		rc = spdk_nvmf_rdma_poller_poll(rtransport, rpoller);
4004 		if (rc < 0) {
4005 			return rc;
4006 		}
4007 		count += rc;
4008 	}
4009 
4010 	return count;
4011 }
4012 
4013 static int
4014 spdk_nvmf_rdma_trid_from_cm_id(struct rdma_cm_id *id,
4015 			       struct spdk_nvme_transport_id *trid,
4016 			       bool peer)
4017 {
4018 	struct sockaddr *saddr;
4019 	uint16_t port;
4020 
4021 	spdk_nvme_trid_populate_transport(trid, SPDK_NVME_TRANSPORT_RDMA);
4022 
4023 	if (peer) {
4024 		saddr = rdma_get_peer_addr(id);
4025 	} else {
4026 		saddr = rdma_get_local_addr(id);
4027 	}
4028 	switch (saddr->sa_family) {
4029 	case AF_INET: {
4030 		struct sockaddr_in *saddr_in = (struct sockaddr_in *)saddr;
4031 
4032 		trid->adrfam = SPDK_NVMF_ADRFAM_IPV4;
4033 		inet_ntop(AF_INET, &saddr_in->sin_addr,
4034 			  trid->traddr, sizeof(trid->traddr));
4035 		if (peer) {
4036 			port = ntohs(rdma_get_dst_port(id));
4037 		} else {
4038 			port = ntohs(rdma_get_src_port(id));
4039 		}
4040 		snprintf(trid->trsvcid, sizeof(trid->trsvcid), "%u", port);
4041 		break;
4042 	}
4043 	case AF_INET6: {
4044 		struct sockaddr_in6 *saddr_in = (struct sockaddr_in6 *)saddr;
4045 		trid->adrfam = SPDK_NVMF_ADRFAM_IPV6;
4046 		inet_ntop(AF_INET6, &saddr_in->sin6_addr,
4047 			  trid->traddr, sizeof(trid->traddr));
4048 		if (peer) {
4049 			port = ntohs(rdma_get_dst_port(id));
4050 		} else {
4051 			port = ntohs(rdma_get_src_port(id));
4052 		}
4053 		snprintf(trid->trsvcid, sizeof(trid->trsvcid), "%u", port);
4054 		break;
4055 	}
4056 	default:
4057 		return -1;
4058 
4059 	}
4060 
4061 	return 0;
4062 }
4063 
4064 static int
4065 spdk_nvmf_rdma_qpair_get_peer_trid(struct spdk_nvmf_qpair *qpair,
4066 				   struct spdk_nvme_transport_id *trid)
4067 {
4068 	struct spdk_nvmf_rdma_qpair	*rqpair;
4069 
4070 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4071 
4072 	return spdk_nvmf_rdma_trid_from_cm_id(rqpair->cm_id, trid, true);
4073 }
4074 
4075 static int
4076 spdk_nvmf_rdma_qpair_get_local_trid(struct spdk_nvmf_qpair *qpair,
4077 				    struct spdk_nvme_transport_id *trid)
4078 {
4079 	struct spdk_nvmf_rdma_qpair	*rqpair;
4080 
4081 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4082 
4083 	return spdk_nvmf_rdma_trid_from_cm_id(rqpair->cm_id, trid, false);
4084 }
4085 
4086 static int
4087 spdk_nvmf_rdma_qpair_get_listen_trid(struct spdk_nvmf_qpair *qpair,
4088 				     struct spdk_nvme_transport_id *trid)
4089 {
4090 	struct spdk_nvmf_rdma_qpair	*rqpair;
4091 
4092 	rqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_rdma_qpair, qpair);
4093 
4094 	return spdk_nvmf_rdma_trid_from_cm_id(rqpair->listen_id, trid, false);
4095 }
4096 
4097 void
4098 spdk_nvmf_rdma_init_hooks(struct spdk_nvme_rdma_hooks *hooks)
4099 {
4100 	g_nvmf_hooks = *hooks;
4101 }
4102 
4103 static int
4104 spdk_nvmf_rdma_poll_group_get_stat(struct spdk_nvmf_tgt *tgt,
4105 				   struct spdk_nvmf_transport_poll_group_stat **stat)
4106 {
4107 	struct spdk_io_channel *ch;
4108 	struct spdk_nvmf_poll_group *group;
4109 	struct spdk_nvmf_transport_poll_group *tgroup;
4110 	struct spdk_nvmf_rdma_poll_group *rgroup;
4111 	struct spdk_nvmf_rdma_poller *rpoller;
4112 	struct spdk_nvmf_rdma_device_stat *device_stat;
4113 	uint64_t num_devices = 0;
4114 
4115 	if (tgt == NULL || stat == NULL) {
4116 		return -EINVAL;
4117 	}
4118 
4119 	ch = spdk_get_io_channel(tgt);
4120 	group = spdk_io_channel_get_ctx(ch);;
4121 	spdk_put_io_channel(ch);
4122 	TAILQ_FOREACH(tgroup, &group->tgroups, link) {
4123 		if (SPDK_NVME_TRANSPORT_RDMA == tgroup->transport->ops->type) {
4124 			*stat = calloc(1, sizeof(struct spdk_nvmf_transport_poll_group_stat));
4125 			if (!*stat) {
4126 				SPDK_ERRLOG("Failed to allocate memory for NVMf RDMA statistics\n");
4127 				return -ENOMEM;
4128 			}
4129 			(*stat)->trtype = SPDK_NVME_TRANSPORT_RDMA;
4130 
4131 			rgroup = SPDK_CONTAINEROF(tgroup, struct spdk_nvmf_rdma_poll_group, group);
4132 			/* Count devices to allocate enough memory */
4133 			TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
4134 				++num_devices;
4135 			}
4136 			(*stat)->rdma.devices = calloc(num_devices, sizeof(struct spdk_nvmf_rdma_device_stat));
4137 			if (!(*stat)->rdma.devices) {
4138 				SPDK_ERRLOG("Failed to allocate NVMf RDMA devices statistics\n");
4139 				free(*stat);
4140 				return -ENOMEM;
4141 			}
4142 
4143 			(*stat)->rdma.pending_data_buffer = rgroup->stat.pending_data_buffer;
4144 			(*stat)->rdma.num_devices = num_devices;
4145 			num_devices = 0;
4146 			TAILQ_FOREACH(rpoller, &rgroup->pollers, link) {
4147 				device_stat = &(*stat)->rdma.devices[num_devices++];
4148 				device_stat->name = ibv_get_device_name(rpoller->device->context->device);
4149 				device_stat->polls = rpoller->stat.polls;
4150 				device_stat->completions = rpoller->stat.completions;
4151 				device_stat->requests = rpoller->stat.requests;
4152 				device_stat->request_latency = rpoller->stat.request_latency;
4153 				device_stat->pending_free_request = rpoller->stat.pending_free_request;
4154 				device_stat->pending_rdma_read = rpoller->stat.pending_rdma_read;
4155 				device_stat->pending_rdma_write = rpoller->stat.pending_rdma_write;
4156 			}
4157 			return 0;
4158 		}
4159 	}
4160 	return -ENOENT;
4161 }
4162 
4163 static void
4164 spdk_nvmf_rdma_poll_group_free_stat(struct spdk_nvmf_transport_poll_group_stat *stat)
4165 {
4166 	if (stat) {
4167 		free(stat->rdma.devices);
4168 	}
4169 	free(stat);
4170 }
4171 
4172 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_rdma = {
4173 	.name = "RDMA",
4174 	.type = SPDK_NVME_TRANSPORT_RDMA,
4175 	.opts_init = spdk_nvmf_rdma_opts_init,
4176 	.create = spdk_nvmf_rdma_create,
4177 	.destroy = spdk_nvmf_rdma_destroy,
4178 
4179 	.listen = spdk_nvmf_rdma_listen,
4180 	.stop_listen = spdk_nvmf_rdma_stop_listen,
4181 	.accept = spdk_nvmf_rdma_accept,
4182 
4183 	.listener_discover = spdk_nvmf_rdma_discover,
4184 
4185 	.poll_group_create = spdk_nvmf_rdma_poll_group_create,
4186 	.get_optimal_poll_group = spdk_nvmf_rdma_get_optimal_poll_group,
4187 	.poll_group_destroy = spdk_nvmf_rdma_poll_group_destroy,
4188 	.poll_group_add = spdk_nvmf_rdma_poll_group_add,
4189 	.poll_group_poll = spdk_nvmf_rdma_poll_group_poll,
4190 
4191 	.req_free = spdk_nvmf_rdma_request_free,
4192 	.req_complete = spdk_nvmf_rdma_request_complete,
4193 
4194 	.qpair_fini = spdk_nvmf_rdma_close_qpair,
4195 	.qpair_get_peer_trid = spdk_nvmf_rdma_qpair_get_peer_trid,
4196 	.qpair_get_local_trid = spdk_nvmf_rdma_qpair_get_local_trid,
4197 	.qpair_get_listen_trid = spdk_nvmf_rdma_qpair_get_listen_trid,
4198 
4199 	.poll_group_get_stat = spdk_nvmf_rdma_poll_group_get_stat,
4200 	.poll_group_free_stat = spdk_nvmf_rdma_poll_group_free_stat,
4201 };
4202 
4203 SPDK_NVMF_TRANSPORT_REGISTER(rdma, &spdk_nvmf_transport_rdma);
4204 SPDK_LOG_REGISTER_COMPONENT("rdma", SPDK_LOG_RDMA)
4205