xref: /linux/drivers/nvme/host/rdma.c (revision 90e0d94d369d342e735a75174439482119b6c393)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVMe over Fabrics RDMA host code.
4  * Copyright (c) 2015-2016 HGST, a Western Digital Company.
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 #include <linux/module.h>
8 #include <linux/init.h>
9 #include <linux/slab.h>
10 #include <rdma/mr_pool.h>
11 #include <linux/err.h>
12 #include <linux/string.h>
13 #include <linux/atomic.h>
14 #include <linux/blk-mq.h>
15 #include <linux/blk-mq-rdma.h>
16 #include <linux/blk-integrity.h>
17 #include <linux/types.h>
18 #include <linux/list.h>
19 #include <linux/mutex.h>
20 #include <linux/scatterlist.h>
21 #include <linux/nvme.h>
22 #include <asm/unaligned.h>
23 
24 #include <rdma/ib_verbs.h>
25 #include <rdma/rdma_cm.h>
26 #include <linux/nvme-rdma.h>
27 
28 #include "nvme.h"
29 #include "fabrics.h"
30 
31 
32 #define NVME_RDMA_CM_TIMEOUT_MS		3000		/* 3 second */
33 
34 #define NVME_RDMA_MAX_SEGMENTS		256
35 
36 #define NVME_RDMA_MAX_INLINE_SEGMENTS	4
37 
38 #define NVME_RDMA_DATA_SGL_SIZE \
39 	(sizeof(struct scatterlist) * NVME_INLINE_SG_CNT)
40 #define NVME_RDMA_METADATA_SGL_SIZE \
41 	(sizeof(struct scatterlist) * NVME_INLINE_METADATA_SG_CNT)
42 
43 struct nvme_rdma_device {
44 	struct ib_device	*dev;
45 	struct ib_pd		*pd;
46 	struct kref		ref;
47 	struct list_head	entry;
48 	unsigned int		num_inline_segments;
49 };
50 
51 struct nvme_rdma_qe {
52 	struct ib_cqe		cqe;
53 	void			*data;
54 	u64			dma;
55 };
56 
57 struct nvme_rdma_sgl {
58 	int			nents;
59 	struct sg_table		sg_table;
60 };
61 
62 struct nvme_rdma_queue;
63 struct nvme_rdma_request {
64 	struct nvme_request	req;
65 	struct ib_mr		*mr;
66 	struct nvme_rdma_qe	sqe;
67 	union nvme_result	result;
68 	__le16			status;
69 	refcount_t		ref;
70 	struct ib_sge		sge[1 + NVME_RDMA_MAX_INLINE_SEGMENTS];
71 	u32			num_sge;
72 	struct ib_reg_wr	reg_wr;
73 	struct ib_cqe		reg_cqe;
74 	struct nvme_rdma_queue  *queue;
75 	struct nvme_rdma_sgl	data_sgl;
76 	struct nvme_rdma_sgl	*metadata_sgl;
77 	bool			use_sig_mr;
78 };
79 
80 enum nvme_rdma_queue_flags {
81 	NVME_RDMA_Q_ALLOCATED		= 0,
82 	NVME_RDMA_Q_LIVE		= 1,
83 	NVME_RDMA_Q_TR_READY		= 2,
84 };
85 
86 struct nvme_rdma_queue {
87 	struct nvme_rdma_qe	*rsp_ring;
88 	int			queue_size;
89 	size_t			cmnd_capsule_len;
90 	struct nvme_rdma_ctrl	*ctrl;
91 	struct nvme_rdma_device	*device;
92 	struct ib_cq		*ib_cq;
93 	struct ib_qp		*qp;
94 
95 	unsigned long		flags;
96 	struct rdma_cm_id	*cm_id;
97 	int			cm_error;
98 	struct completion	cm_done;
99 	bool			pi_support;
100 	int			cq_size;
101 	struct mutex		queue_lock;
102 };
103 
104 struct nvme_rdma_ctrl {
105 	/* read only in the hot path */
106 	struct nvme_rdma_queue	*queues;
107 
108 	/* other member variables */
109 	struct blk_mq_tag_set	tag_set;
110 	struct work_struct	err_work;
111 
112 	struct nvme_rdma_qe	async_event_sqe;
113 
114 	struct delayed_work	reconnect_work;
115 
116 	struct list_head	list;
117 
118 	struct blk_mq_tag_set	admin_tag_set;
119 	struct nvme_rdma_device	*device;
120 
121 	u32			max_fr_pages;
122 
123 	struct sockaddr_storage addr;
124 	struct sockaddr_storage src_addr;
125 
126 	struct nvme_ctrl	ctrl;
127 	bool			use_inline_data;
128 	u32			io_queues[HCTX_MAX_TYPES];
129 };
130 
131 static inline struct nvme_rdma_ctrl *to_rdma_ctrl(struct nvme_ctrl *ctrl)
132 {
133 	return container_of(ctrl, struct nvme_rdma_ctrl, ctrl);
134 }
135 
136 static LIST_HEAD(device_list);
137 static DEFINE_MUTEX(device_list_mutex);
138 
139 static LIST_HEAD(nvme_rdma_ctrl_list);
140 static DEFINE_MUTEX(nvme_rdma_ctrl_mutex);
141 
142 /*
143  * Disabling this option makes small I/O goes faster, but is fundamentally
144  * unsafe.  With it turned off we will have to register a global rkey that
145  * allows read and write access to all physical memory.
146  */
147 static bool register_always = true;
148 module_param(register_always, bool, 0444);
149 MODULE_PARM_DESC(register_always,
150 	 "Use memory registration even for contiguous memory regions");
151 
152 static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id,
153 		struct rdma_cm_event *event);
154 static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc);
155 static void nvme_rdma_complete_rq(struct request *rq);
156 
157 static const struct blk_mq_ops nvme_rdma_mq_ops;
158 static const struct blk_mq_ops nvme_rdma_admin_mq_ops;
159 
160 static inline int nvme_rdma_queue_idx(struct nvme_rdma_queue *queue)
161 {
162 	return queue - queue->ctrl->queues;
163 }
164 
165 static bool nvme_rdma_poll_queue(struct nvme_rdma_queue *queue)
166 {
167 	return nvme_rdma_queue_idx(queue) >
168 		queue->ctrl->io_queues[HCTX_TYPE_DEFAULT] +
169 		queue->ctrl->io_queues[HCTX_TYPE_READ];
170 }
171 
172 static inline size_t nvme_rdma_inline_data_size(struct nvme_rdma_queue *queue)
173 {
174 	return queue->cmnd_capsule_len - sizeof(struct nvme_command);
175 }
176 
177 static void nvme_rdma_free_qe(struct ib_device *ibdev, struct nvme_rdma_qe *qe,
178 		size_t capsule_size, enum dma_data_direction dir)
179 {
180 	ib_dma_unmap_single(ibdev, qe->dma, capsule_size, dir);
181 	kfree(qe->data);
182 }
183 
184 static int nvme_rdma_alloc_qe(struct ib_device *ibdev, struct nvme_rdma_qe *qe,
185 		size_t capsule_size, enum dma_data_direction dir)
186 {
187 	qe->data = kzalloc(capsule_size, GFP_KERNEL);
188 	if (!qe->data)
189 		return -ENOMEM;
190 
191 	qe->dma = ib_dma_map_single(ibdev, qe->data, capsule_size, dir);
192 	if (ib_dma_mapping_error(ibdev, qe->dma)) {
193 		kfree(qe->data);
194 		qe->data = NULL;
195 		return -ENOMEM;
196 	}
197 
198 	return 0;
199 }
200 
201 static void nvme_rdma_free_ring(struct ib_device *ibdev,
202 		struct nvme_rdma_qe *ring, size_t ib_queue_size,
203 		size_t capsule_size, enum dma_data_direction dir)
204 {
205 	int i;
206 
207 	for (i = 0; i < ib_queue_size; i++)
208 		nvme_rdma_free_qe(ibdev, &ring[i], capsule_size, dir);
209 	kfree(ring);
210 }
211 
212 static struct nvme_rdma_qe *nvme_rdma_alloc_ring(struct ib_device *ibdev,
213 		size_t ib_queue_size, size_t capsule_size,
214 		enum dma_data_direction dir)
215 {
216 	struct nvme_rdma_qe *ring;
217 	int i;
218 
219 	ring = kcalloc(ib_queue_size, sizeof(struct nvme_rdma_qe), GFP_KERNEL);
220 	if (!ring)
221 		return NULL;
222 
223 	/*
224 	 * Bind the CQEs (post recv buffers) DMA mapping to the RDMA queue
225 	 * lifetime. It's safe, since any chage in the underlying RDMA device
226 	 * will issue error recovery and queue re-creation.
227 	 */
228 	for (i = 0; i < ib_queue_size; i++) {
229 		if (nvme_rdma_alloc_qe(ibdev, &ring[i], capsule_size, dir))
230 			goto out_free_ring;
231 	}
232 
233 	return ring;
234 
235 out_free_ring:
236 	nvme_rdma_free_ring(ibdev, ring, i, capsule_size, dir);
237 	return NULL;
238 }
239 
240 static void nvme_rdma_qp_event(struct ib_event *event, void *context)
241 {
242 	pr_debug("QP event %s (%d)\n",
243 		 ib_event_msg(event->event), event->event);
244 
245 }
246 
247 static int nvme_rdma_wait_for_cm(struct nvme_rdma_queue *queue)
248 {
249 	int ret;
250 
251 	ret = wait_for_completion_interruptible(&queue->cm_done);
252 	if (ret)
253 		return ret;
254 	WARN_ON_ONCE(queue->cm_error > 0);
255 	return queue->cm_error;
256 }
257 
258 static int nvme_rdma_create_qp(struct nvme_rdma_queue *queue, const int factor)
259 {
260 	struct nvme_rdma_device *dev = queue->device;
261 	struct ib_qp_init_attr init_attr;
262 	int ret;
263 
264 	memset(&init_attr, 0, sizeof(init_attr));
265 	init_attr.event_handler = nvme_rdma_qp_event;
266 	/* +1 for drain */
267 	init_attr.cap.max_send_wr = factor * queue->queue_size + 1;
268 	/* +1 for drain */
269 	init_attr.cap.max_recv_wr = queue->queue_size + 1;
270 	init_attr.cap.max_recv_sge = 1;
271 	init_attr.cap.max_send_sge = 1 + dev->num_inline_segments;
272 	init_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
273 	init_attr.qp_type = IB_QPT_RC;
274 	init_attr.send_cq = queue->ib_cq;
275 	init_attr.recv_cq = queue->ib_cq;
276 	if (queue->pi_support)
277 		init_attr.create_flags |= IB_QP_CREATE_INTEGRITY_EN;
278 	init_attr.qp_context = queue;
279 
280 	ret = rdma_create_qp(queue->cm_id, dev->pd, &init_attr);
281 
282 	queue->qp = queue->cm_id->qp;
283 	return ret;
284 }
285 
286 static void nvme_rdma_exit_request(struct blk_mq_tag_set *set,
287 		struct request *rq, unsigned int hctx_idx)
288 {
289 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
290 
291 	kfree(req->sqe.data);
292 }
293 
294 static int nvme_rdma_init_request(struct blk_mq_tag_set *set,
295 		struct request *rq, unsigned int hctx_idx,
296 		unsigned int numa_node)
297 {
298 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(set->driver_data);
299 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
300 	int queue_idx = (set == &ctrl->tag_set) ? hctx_idx + 1 : 0;
301 	struct nvme_rdma_queue *queue = &ctrl->queues[queue_idx];
302 
303 	nvme_req(rq)->ctrl = &ctrl->ctrl;
304 	req->sqe.data = kzalloc(sizeof(struct nvme_command), GFP_KERNEL);
305 	if (!req->sqe.data)
306 		return -ENOMEM;
307 
308 	/* metadata nvme_rdma_sgl struct is located after command's data SGL */
309 	if (queue->pi_support)
310 		req->metadata_sgl = (void *)nvme_req(rq) +
311 			sizeof(struct nvme_rdma_request) +
312 			NVME_RDMA_DATA_SGL_SIZE;
313 
314 	req->queue = queue;
315 	nvme_req(rq)->cmd = req->sqe.data;
316 
317 	return 0;
318 }
319 
320 static int nvme_rdma_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
321 		unsigned int hctx_idx)
322 {
323 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(data);
324 	struct nvme_rdma_queue *queue = &ctrl->queues[hctx_idx + 1];
325 
326 	BUG_ON(hctx_idx >= ctrl->ctrl.queue_count);
327 
328 	hctx->driver_data = queue;
329 	return 0;
330 }
331 
332 static int nvme_rdma_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
333 		unsigned int hctx_idx)
334 {
335 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(data);
336 	struct nvme_rdma_queue *queue = &ctrl->queues[0];
337 
338 	BUG_ON(hctx_idx != 0);
339 
340 	hctx->driver_data = queue;
341 	return 0;
342 }
343 
344 static void nvme_rdma_free_dev(struct kref *ref)
345 {
346 	struct nvme_rdma_device *ndev =
347 		container_of(ref, struct nvme_rdma_device, ref);
348 
349 	mutex_lock(&device_list_mutex);
350 	list_del(&ndev->entry);
351 	mutex_unlock(&device_list_mutex);
352 
353 	ib_dealloc_pd(ndev->pd);
354 	kfree(ndev);
355 }
356 
357 static void nvme_rdma_dev_put(struct nvme_rdma_device *dev)
358 {
359 	kref_put(&dev->ref, nvme_rdma_free_dev);
360 }
361 
362 static int nvme_rdma_dev_get(struct nvme_rdma_device *dev)
363 {
364 	return kref_get_unless_zero(&dev->ref);
365 }
366 
367 static struct nvme_rdma_device *
368 nvme_rdma_find_get_device(struct rdma_cm_id *cm_id)
369 {
370 	struct nvme_rdma_device *ndev;
371 
372 	mutex_lock(&device_list_mutex);
373 	list_for_each_entry(ndev, &device_list, entry) {
374 		if (ndev->dev->node_guid == cm_id->device->node_guid &&
375 		    nvme_rdma_dev_get(ndev))
376 			goto out_unlock;
377 	}
378 
379 	ndev = kzalloc(sizeof(*ndev), GFP_KERNEL);
380 	if (!ndev)
381 		goto out_err;
382 
383 	ndev->dev = cm_id->device;
384 	kref_init(&ndev->ref);
385 
386 	ndev->pd = ib_alloc_pd(ndev->dev,
387 		register_always ? 0 : IB_PD_UNSAFE_GLOBAL_RKEY);
388 	if (IS_ERR(ndev->pd))
389 		goto out_free_dev;
390 
391 	if (!(ndev->dev->attrs.device_cap_flags &
392 	      IB_DEVICE_MEM_MGT_EXTENSIONS)) {
393 		dev_err(&ndev->dev->dev,
394 			"Memory registrations not supported.\n");
395 		goto out_free_pd;
396 	}
397 
398 	ndev->num_inline_segments = min(NVME_RDMA_MAX_INLINE_SEGMENTS,
399 					ndev->dev->attrs.max_send_sge - 1);
400 	list_add(&ndev->entry, &device_list);
401 out_unlock:
402 	mutex_unlock(&device_list_mutex);
403 	return ndev;
404 
405 out_free_pd:
406 	ib_dealloc_pd(ndev->pd);
407 out_free_dev:
408 	kfree(ndev);
409 out_err:
410 	mutex_unlock(&device_list_mutex);
411 	return NULL;
412 }
413 
414 static void nvme_rdma_free_cq(struct nvme_rdma_queue *queue)
415 {
416 	if (nvme_rdma_poll_queue(queue))
417 		ib_free_cq(queue->ib_cq);
418 	else
419 		ib_cq_pool_put(queue->ib_cq, queue->cq_size);
420 }
421 
422 static void nvme_rdma_destroy_queue_ib(struct nvme_rdma_queue *queue)
423 {
424 	struct nvme_rdma_device *dev;
425 	struct ib_device *ibdev;
426 
427 	if (!test_and_clear_bit(NVME_RDMA_Q_TR_READY, &queue->flags))
428 		return;
429 
430 	dev = queue->device;
431 	ibdev = dev->dev;
432 
433 	if (queue->pi_support)
434 		ib_mr_pool_destroy(queue->qp, &queue->qp->sig_mrs);
435 	ib_mr_pool_destroy(queue->qp, &queue->qp->rdma_mrs);
436 
437 	/*
438 	 * The cm_id object might have been destroyed during RDMA connection
439 	 * establishment error flow to avoid getting other cma events, thus
440 	 * the destruction of the QP shouldn't use rdma_cm API.
441 	 */
442 	ib_destroy_qp(queue->qp);
443 	nvme_rdma_free_cq(queue);
444 
445 	nvme_rdma_free_ring(ibdev, queue->rsp_ring, queue->queue_size,
446 			sizeof(struct nvme_completion), DMA_FROM_DEVICE);
447 
448 	nvme_rdma_dev_put(dev);
449 }
450 
451 static int nvme_rdma_get_max_fr_pages(struct ib_device *ibdev, bool pi_support)
452 {
453 	u32 max_page_list_len;
454 
455 	if (pi_support)
456 		max_page_list_len = ibdev->attrs.max_pi_fast_reg_page_list_len;
457 	else
458 		max_page_list_len = ibdev->attrs.max_fast_reg_page_list_len;
459 
460 	return min_t(u32, NVME_RDMA_MAX_SEGMENTS, max_page_list_len - 1);
461 }
462 
463 static int nvme_rdma_create_cq(struct ib_device *ibdev,
464 		struct nvme_rdma_queue *queue)
465 {
466 	int ret, comp_vector, idx = nvme_rdma_queue_idx(queue);
467 	enum ib_poll_context poll_ctx;
468 
469 	/*
470 	 * Spread I/O queues completion vectors according their queue index.
471 	 * Admin queues can always go on completion vector 0.
472 	 */
473 	comp_vector = (idx == 0 ? idx : idx - 1) % ibdev->num_comp_vectors;
474 
475 	/* Polling queues need direct cq polling context */
476 	if (nvme_rdma_poll_queue(queue)) {
477 		poll_ctx = IB_POLL_DIRECT;
478 		queue->ib_cq = ib_alloc_cq(ibdev, queue, queue->cq_size,
479 					   comp_vector, poll_ctx);
480 	} else {
481 		poll_ctx = IB_POLL_SOFTIRQ;
482 		queue->ib_cq = ib_cq_pool_get(ibdev, queue->cq_size,
483 					      comp_vector, poll_ctx);
484 	}
485 
486 	if (IS_ERR(queue->ib_cq)) {
487 		ret = PTR_ERR(queue->ib_cq);
488 		return ret;
489 	}
490 
491 	return 0;
492 }
493 
494 static int nvme_rdma_create_queue_ib(struct nvme_rdma_queue *queue)
495 {
496 	struct ib_device *ibdev;
497 	const int send_wr_factor = 3;			/* MR, SEND, INV */
498 	const int cq_factor = send_wr_factor + 1;	/* + RECV */
499 	int ret, pages_per_mr;
500 
501 	queue->device = nvme_rdma_find_get_device(queue->cm_id);
502 	if (!queue->device) {
503 		dev_err(queue->cm_id->device->dev.parent,
504 			"no client data found!\n");
505 		return -ECONNREFUSED;
506 	}
507 	ibdev = queue->device->dev;
508 
509 	/* +1 for ib_stop_cq */
510 	queue->cq_size = cq_factor * queue->queue_size + 1;
511 
512 	ret = nvme_rdma_create_cq(ibdev, queue);
513 	if (ret)
514 		goto out_put_dev;
515 
516 	ret = nvme_rdma_create_qp(queue, send_wr_factor);
517 	if (ret)
518 		goto out_destroy_ib_cq;
519 
520 	queue->rsp_ring = nvme_rdma_alloc_ring(ibdev, queue->queue_size,
521 			sizeof(struct nvme_completion), DMA_FROM_DEVICE);
522 	if (!queue->rsp_ring) {
523 		ret = -ENOMEM;
524 		goto out_destroy_qp;
525 	}
526 
527 	/*
528 	 * Currently we don't use SG_GAPS MR's so if the first entry is
529 	 * misaligned we'll end up using two entries for a single data page,
530 	 * so one additional entry is required.
531 	 */
532 	pages_per_mr = nvme_rdma_get_max_fr_pages(ibdev, queue->pi_support) + 1;
533 	ret = ib_mr_pool_init(queue->qp, &queue->qp->rdma_mrs,
534 			      queue->queue_size,
535 			      IB_MR_TYPE_MEM_REG,
536 			      pages_per_mr, 0);
537 	if (ret) {
538 		dev_err(queue->ctrl->ctrl.device,
539 			"failed to initialize MR pool sized %d for QID %d\n",
540 			queue->queue_size, nvme_rdma_queue_idx(queue));
541 		goto out_destroy_ring;
542 	}
543 
544 	if (queue->pi_support) {
545 		ret = ib_mr_pool_init(queue->qp, &queue->qp->sig_mrs,
546 				      queue->queue_size, IB_MR_TYPE_INTEGRITY,
547 				      pages_per_mr, pages_per_mr);
548 		if (ret) {
549 			dev_err(queue->ctrl->ctrl.device,
550 				"failed to initialize PI MR pool sized %d for QID %d\n",
551 				queue->queue_size, nvme_rdma_queue_idx(queue));
552 			goto out_destroy_mr_pool;
553 		}
554 	}
555 
556 	set_bit(NVME_RDMA_Q_TR_READY, &queue->flags);
557 
558 	return 0;
559 
560 out_destroy_mr_pool:
561 	ib_mr_pool_destroy(queue->qp, &queue->qp->rdma_mrs);
562 out_destroy_ring:
563 	nvme_rdma_free_ring(ibdev, queue->rsp_ring, queue->queue_size,
564 			    sizeof(struct nvme_completion), DMA_FROM_DEVICE);
565 out_destroy_qp:
566 	rdma_destroy_qp(queue->cm_id);
567 out_destroy_ib_cq:
568 	nvme_rdma_free_cq(queue);
569 out_put_dev:
570 	nvme_rdma_dev_put(queue->device);
571 	return ret;
572 }
573 
574 static int nvme_rdma_alloc_queue(struct nvme_rdma_ctrl *ctrl,
575 		int idx, size_t queue_size)
576 {
577 	struct nvme_rdma_queue *queue;
578 	struct sockaddr *src_addr = NULL;
579 	int ret;
580 
581 	queue = &ctrl->queues[idx];
582 	mutex_init(&queue->queue_lock);
583 	queue->ctrl = ctrl;
584 	if (idx && ctrl->ctrl.max_integrity_segments)
585 		queue->pi_support = true;
586 	else
587 		queue->pi_support = false;
588 	init_completion(&queue->cm_done);
589 
590 	if (idx > 0)
591 		queue->cmnd_capsule_len = ctrl->ctrl.ioccsz * 16;
592 	else
593 		queue->cmnd_capsule_len = sizeof(struct nvme_command);
594 
595 	queue->queue_size = queue_size;
596 
597 	queue->cm_id = rdma_create_id(&init_net, nvme_rdma_cm_handler, queue,
598 			RDMA_PS_TCP, IB_QPT_RC);
599 	if (IS_ERR(queue->cm_id)) {
600 		dev_info(ctrl->ctrl.device,
601 			"failed to create CM ID: %ld\n", PTR_ERR(queue->cm_id));
602 		ret = PTR_ERR(queue->cm_id);
603 		goto out_destroy_mutex;
604 	}
605 
606 	if (ctrl->ctrl.opts->mask & NVMF_OPT_HOST_TRADDR)
607 		src_addr = (struct sockaddr *)&ctrl->src_addr;
608 
609 	queue->cm_error = -ETIMEDOUT;
610 	ret = rdma_resolve_addr(queue->cm_id, src_addr,
611 			(struct sockaddr *)&ctrl->addr,
612 			NVME_RDMA_CM_TIMEOUT_MS);
613 	if (ret) {
614 		dev_info(ctrl->ctrl.device,
615 			"rdma_resolve_addr failed (%d).\n", ret);
616 		goto out_destroy_cm_id;
617 	}
618 
619 	ret = nvme_rdma_wait_for_cm(queue);
620 	if (ret) {
621 		dev_info(ctrl->ctrl.device,
622 			"rdma connection establishment failed (%d)\n", ret);
623 		goto out_destroy_cm_id;
624 	}
625 
626 	set_bit(NVME_RDMA_Q_ALLOCATED, &queue->flags);
627 
628 	return 0;
629 
630 out_destroy_cm_id:
631 	rdma_destroy_id(queue->cm_id);
632 	nvme_rdma_destroy_queue_ib(queue);
633 out_destroy_mutex:
634 	mutex_destroy(&queue->queue_lock);
635 	return ret;
636 }
637 
638 static void __nvme_rdma_stop_queue(struct nvme_rdma_queue *queue)
639 {
640 	rdma_disconnect(queue->cm_id);
641 	ib_drain_qp(queue->qp);
642 }
643 
644 static void nvme_rdma_stop_queue(struct nvme_rdma_queue *queue)
645 {
646 	mutex_lock(&queue->queue_lock);
647 	if (test_and_clear_bit(NVME_RDMA_Q_LIVE, &queue->flags))
648 		__nvme_rdma_stop_queue(queue);
649 	mutex_unlock(&queue->queue_lock);
650 }
651 
652 static void nvme_rdma_free_queue(struct nvme_rdma_queue *queue)
653 {
654 	if (!test_and_clear_bit(NVME_RDMA_Q_ALLOCATED, &queue->flags))
655 		return;
656 
657 	rdma_destroy_id(queue->cm_id);
658 	nvme_rdma_destroy_queue_ib(queue);
659 	mutex_destroy(&queue->queue_lock);
660 }
661 
662 static void nvme_rdma_free_io_queues(struct nvme_rdma_ctrl *ctrl)
663 {
664 	int i;
665 
666 	for (i = 1; i < ctrl->ctrl.queue_count; i++)
667 		nvme_rdma_free_queue(&ctrl->queues[i]);
668 }
669 
670 static void nvme_rdma_stop_io_queues(struct nvme_rdma_ctrl *ctrl)
671 {
672 	int i;
673 
674 	for (i = 1; i < ctrl->ctrl.queue_count; i++)
675 		nvme_rdma_stop_queue(&ctrl->queues[i]);
676 }
677 
678 static int nvme_rdma_start_queue(struct nvme_rdma_ctrl *ctrl, int idx)
679 {
680 	struct nvme_rdma_queue *queue = &ctrl->queues[idx];
681 	int ret;
682 
683 	if (idx)
684 		ret = nvmf_connect_io_queue(&ctrl->ctrl, idx);
685 	else
686 		ret = nvmf_connect_admin_queue(&ctrl->ctrl);
687 
688 	if (!ret) {
689 		set_bit(NVME_RDMA_Q_LIVE, &queue->flags);
690 	} else {
691 		if (test_bit(NVME_RDMA_Q_ALLOCATED, &queue->flags))
692 			__nvme_rdma_stop_queue(queue);
693 		dev_info(ctrl->ctrl.device,
694 			"failed to connect queue: %d ret=%d\n", idx, ret);
695 	}
696 	return ret;
697 }
698 
699 static int nvme_rdma_start_io_queues(struct nvme_rdma_ctrl *ctrl,
700 				     int first, int last)
701 {
702 	int i, ret = 0;
703 
704 	for (i = first; i < last; i++) {
705 		ret = nvme_rdma_start_queue(ctrl, i);
706 		if (ret)
707 			goto out_stop_queues;
708 	}
709 
710 	return 0;
711 
712 out_stop_queues:
713 	for (i--; i >= first; i--)
714 		nvme_rdma_stop_queue(&ctrl->queues[i]);
715 	return ret;
716 }
717 
718 static int nvme_rdma_alloc_io_queues(struct nvme_rdma_ctrl *ctrl)
719 {
720 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
721 	struct ib_device *ibdev = ctrl->device->dev;
722 	unsigned int nr_io_queues, nr_default_queues;
723 	unsigned int nr_read_queues, nr_poll_queues;
724 	int i, ret;
725 
726 	nr_read_queues = min_t(unsigned int, ibdev->num_comp_vectors,
727 				min(opts->nr_io_queues, num_online_cpus()));
728 	nr_default_queues =  min_t(unsigned int, ibdev->num_comp_vectors,
729 				min(opts->nr_write_queues, num_online_cpus()));
730 	nr_poll_queues = min(opts->nr_poll_queues, num_online_cpus());
731 	nr_io_queues = nr_read_queues + nr_default_queues + nr_poll_queues;
732 
733 	ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
734 	if (ret)
735 		return ret;
736 
737 	if (nr_io_queues == 0) {
738 		dev_err(ctrl->ctrl.device,
739 			"unable to set any I/O queues\n");
740 		return -ENOMEM;
741 	}
742 
743 	ctrl->ctrl.queue_count = nr_io_queues + 1;
744 	dev_info(ctrl->ctrl.device,
745 		"creating %d I/O queues.\n", nr_io_queues);
746 
747 	if (opts->nr_write_queues && nr_read_queues < nr_io_queues) {
748 		/*
749 		 * separate read/write queues
750 		 * hand out dedicated default queues only after we have
751 		 * sufficient read queues.
752 		 */
753 		ctrl->io_queues[HCTX_TYPE_READ] = nr_read_queues;
754 		nr_io_queues -= ctrl->io_queues[HCTX_TYPE_READ];
755 		ctrl->io_queues[HCTX_TYPE_DEFAULT] =
756 			min(nr_default_queues, nr_io_queues);
757 		nr_io_queues -= ctrl->io_queues[HCTX_TYPE_DEFAULT];
758 	} else {
759 		/*
760 		 * shared read/write queues
761 		 * either no write queues were requested, or we don't have
762 		 * sufficient queue count to have dedicated default queues.
763 		 */
764 		ctrl->io_queues[HCTX_TYPE_DEFAULT] =
765 			min(nr_read_queues, nr_io_queues);
766 		nr_io_queues -= ctrl->io_queues[HCTX_TYPE_DEFAULT];
767 	}
768 
769 	if (opts->nr_poll_queues && nr_io_queues) {
770 		/* map dedicated poll queues only if we have queues left */
771 		ctrl->io_queues[HCTX_TYPE_POLL] =
772 			min(nr_poll_queues, nr_io_queues);
773 	}
774 
775 	for (i = 1; i < ctrl->ctrl.queue_count; i++) {
776 		ret = nvme_rdma_alloc_queue(ctrl, i,
777 				ctrl->ctrl.sqsize + 1);
778 		if (ret)
779 			goto out_free_queues;
780 	}
781 
782 	return 0;
783 
784 out_free_queues:
785 	for (i--; i >= 1; i--)
786 		nvme_rdma_free_queue(&ctrl->queues[i]);
787 
788 	return ret;
789 }
790 
791 static int nvme_rdma_alloc_tag_set(struct nvme_ctrl *ctrl)
792 {
793 	unsigned int cmd_size = sizeof(struct nvme_rdma_request) +
794 				NVME_RDMA_DATA_SGL_SIZE;
795 
796 	if (ctrl->max_integrity_segments)
797 		cmd_size += sizeof(struct nvme_rdma_sgl) +
798 			    NVME_RDMA_METADATA_SGL_SIZE;
799 
800 	return nvme_alloc_io_tag_set(ctrl, &to_rdma_ctrl(ctrl)->tag_set,
801 			&nvme_rdma_mq_ops, BLK_MQ_F_SHOULD_MERGE, cmd_size);
802 }
803 
804 static void nvme_rdma_destroy_admin_queue(struct nvme_rdma_ctrl *ctrl)
805 {
806 	if (ctrl->async_event_sqe.data) {
807 		cancel_work_sync(&ctrl->ctrl.async_event_work);
808 		nvme_rdma_free_qe(ctrl->device->dev, &ctrl->async_event_sqe,
809 				sizeof(struct nvme_command), DMA_TO_DEVICE);
810 		ctrl->async_event_sqe.data = NULL;
811 	}
812 	nvme_rdma_free_queue(&ctrl->queues[0]);
813 }
814 
815 static int nvme_rdma_configure_admin_queue(struct nvme_rdma_ctrl *ctrl,
816 		bool new)
817 {
818 	bool pi_capable = false;
819 	int error;
820 
821 	error = nvme_rdma_alloc_queue(ctrl, 0, NVME_AQ_DEPTH);
822 	if (error)
823 		return error;
824 
825 	ctrl->device = ctrl->queues[0].device;
826 	ctrl->ctrl.numa_node = ibdev_to_node(ctrl->device->dev);
827 
828 	/* T10-PI support */
829 	if (ctrl->device->dev->attrs.kernel_cap_flags &
830 	    IBK_INTEGRITY_HANDOVER)
831 		pi_capable = true;
832 
833 	ctrl->max_fr_pages = nvme_rdma_get_max_fr_pages(ctrl->device->dev,
834 							pi_capable);
835 
836 	/*
837 	 * Bind the async event SQE DMA mapping to the admin queue lifetime.
838 	 * It's safe, since any chage in the underlying RDMA device will issue
839 	 * error recovery and queue re-creation.
840 	 */
841 	error = nvme_rdma_alloc_qe(ctrl->device->dev, &ctrl->async_event_sqe,
842 			sizeof(struct nvme_command), DMA_TO_DEVICE);
843 	if (error)
844 		goto out_free_queue;
845 
846 	if (new) {
847 		error = nvme_alloc_admin_tag_set(&ctrl->ctrl,
848 				&ctrl->admin_tag_set, &nvme_rdma_admin_mq_ops,
849 				BLK_MQ_F_NO_SCHED,
850 				sizeof(struct nvme_rdma_request) +
851 				NVME_RDMA_DATA_SGL_SIZE);
852 		if (error)
853 			goto out_free_async_qe;
854 
855 	}
856 
857 	error = nvme_rdma_start_queue(ctrl, 0);
858 	if (error)
859 		goto out_remove_admin_tag_set;
860 
861 	error = nvme_enable_ctrl(&ctrl->ctrl);
862 	if (error)
863 		goto out_stop_queue;
864 
865 	ctrl->ctrl.max_segments = ctrl->max_fr_pages;
866 	ctrl->ctrl.max_hw_sectors = ctrl->max_fr_pages << (ilog2(SZ_4K) - 9);
867 	if (pi_capable)
868 		ctrl->ctrl.max_integrity_segments = ctrl->max_fr_pages;
869 	else
870 		ctrl->ctrl.max_integrity_segments = 0;
871 
872 	nvme_start_admin_queue(&ctrl->ctrl);
873 
874 	error = nvme_init_ctrl_finish(&ctrl->ctrl);
875 	if (error)
876 		goto out_quiesce_queue;
877 
878 	return 0;
879 
880 out_quiesce_queue:
881 	nvme_stop_admin_queue(&ctrl->ctrl);
882 	blk_sync_queue(ctrl->ctrl.admin_q);
883 out_stop_queue:
884 	nvme_rdma_stop_queue(&ctrl->queues[0]);
885 	nvme_cancel_admin_tagset(&ctrl->ctrl);
886 out_remove_admin_tag_set:
887 	if (new)
888 		nvme_remove_admin_tag_set(&ctrl->ctrl);
889 out_free_async_qe:
890 	if (ctrl->async_event_sqe.data) {
891 		nvme_rdma_free_qe(ctrl->device->dev, &ctrl->async_event_sqe,
892 			sizeof(struct nvme_command), DMA_TO_DEVICE);
893 		ctrl->async_event_sqe.data = NULL;
894 	}
895 out_free_queue:
896 	nvme_rdma_free_queue(&ctrl->queues[0]);
897 	return error;
898 }
899 
900 static int nvme_rdma_configure_io_queues(struct nvme_rdma_ctrl *ctrl, bool new)
901 {
902 	int ret, nr_queues;
903 
904 	ret = nvme_rdma_alloc_io_queues(ctrl);
905 	if (ret)
906 		return ret;
907 
908 	if (new) {
909 		ret = nvme_rdma_alloc_tag_set(&ctrl->ctrl);
910 		if (ret)
911 			goto out_free_io_queues;
912 	}
913 
914 	/*
915 	 * Only start IO queues for which we have allocated the tagset
916 	 * and limitted it to the available queues. On reconnects, the
917 	 * queue number might have changed.
918 	 */
919 	nr_queues = min(ctrl->tag_set.nr_hw_queues + 1, ctrl->ctrl.queue_count);
920 	ret = nvme_rdma_start_io_queues(ctrl, 1, nr_queues);
921 	if (ret)
922 		goto out_cleanup_tagset;
923 
924 	if (!new) {
925 		nvme_start_queues(&ctrl->ctrl);
926 		if (!nvme_wait_freeze_timeout(&ctrl->ctrl, NVME_IO_TIMEOUT)) {
927 			/*
928 			 * If we timed out waiting for freeze we are likely to
929 			 * be stuck.  Fail the controller initialization just
930 			 * to be safe.
931 			 */
932 			ret = -ENODEV;
933 			goto out_wait_freeze_timed_out;
934 		}
935 		blk_mq_update_nr_hw_queues(ctrl->ctrl.tagset,
936 			ctrl->ctrl.queue_count - 1);
937 		nvme_unfreeze(&ctrl->ctrl);
938 	}
939 
940 	/*
941 	 * If the number of queues has increased (reconnect case)
942 	 * start all new queues now.
943 	 */
944 	ret = nvme_rdma_start_io_queues(ctrl, nr_queues,
945 					ctrl->tag_set.nr_hw_queues + 1);
946 	if (ret)
947 		goto out_wait_freeze_timed_out;
948 
949 	return 0;
950 
951 out_wait_freeze_timed_out:
952 	nvme_stop_queues(&ctrl->ctrl);
953 	nvme_sync_io_queues(&ctrl->ctrl);
954 	nvme_rdma_stop_io_queues(ctrl);
955 out_cleanup_tagset:
956 	nvme_cancel_tagset(&ctrl->ctrl);
957 	if (new)
958 		nvme_remove_io_tag_set(&ctrl->ctrl);
959 out_free_io_queues:
960 	nvme_rdma_free_io_queues(ctrl);
961 	return ret;
962 }
963 
964 static void nvme_rdma_teardown_admin_queue(struct nvme_rdma_ctrl *ctrl,
965 		bool remove)
966 {
967 	nvme_stop_admin_queue(&ctrl->ctrl);
968 	blk_sync_queue(ctrl->ctrl.admin_q);
969 	nvme_rdma_stop_queue(&ctrl->queues[0]);
970 	nvme_cancel_admin_tagset(&ctrl->ctrl);
971 	if (remove) {
972 		nvme_start_admin_queue(&ctrl->ctrl);
973 		nvme_remove_admin_tag_set(&ctrl->ctrl);
974 	}
975 	nvme_rdma_destroy_admin_queue(ctrl);
976 }
977 
978 static void nvme_rdma_teardown_io_queues(struct nvme_rdma_ctrl *ctrl,
979 		bool remove)
980 {
981 	if (ctrl->ctrl.queue_count > 1) {
982 		nvme_start_freeze(&ctrl->ctrl);
983 		nvme_stop_queues(&ctrl->ctrl);
984 		nvme_sync_io_queues(&ctrl->ctrl);
985 		nvme_rdma_stop_io_queues(ctrl);
986 		nvme_cancel_tagset(&ctrl->ctrl);
987 		if (remove) {
988 			nvme_start_queues(&ctrl->ctrl);
989 			nvme_remove_io_tag_set(&ctrl->ctrl);
990 		}
991 		nvme_rdma_free_io_queues(ctrl);
992 	}
993 }
994 
995 static void nvme_rdma_stop_ctrl(struct nvme_ctrl *nctrl)
996 {
997 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
998 
999 	cancel_work_sync(&ctrl->err_work);
1000 	cancel_delayed_work_sync(&ctrl->reconnect_work);
1001 }
1002 
1003 static void nvme_rdma_free_ctrl(struct nvme_ctrl *nctrl)
1004 {
1005 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
1006 
1007 	if (list_empty(&ctrl->list))
1008 		goto free_ctrl;
1009 
1010 	mutex_lock(&nvme_rdma_ctrl_mutex);
1011 	list_del(&ctrl->list);
1012 	mutex_unlock(&nvme_rdma_ctrl_mutex);
1013 
1014 	nvmf_free_options(nctrl->opts);
1015 free_ctrl:
1016 	kfree(ctrl->queues);
1017 	kfree(ctrl);
1018 }
1019 
1020 static void nvme_rdma_reconnect_or_remove(struct nvme_rdma_ctrl *ctrl)
1021 {
1022 	/* If we are resetting/deleting then do nothing */
1023 	if (ctrl->ctrl.state != NVME_CTRL_CONNECTING) {
1024 		WARN_ON_ONCE(ctrl->ctrl.state == NVME_CTRL_NEW ||
1025 			ctrl->ctrl.state == NVME_CTRL_LIVE);
1026 		return;
1027 	}
1028 
1029 	if (nvmf_should_reconnect(&ctrl->ctrl)) {
1030 		dev_info(ctrl->ctrl.device, "Reconnecting in %d seconds...\n",
1031 			ctrl->ctrl.opts->reconnect_delay);
1032 		queue_delayed_work(nvme_wq, &ctrl->reconnect_work,
1033 				ctrl->ctrl.opts->reconnect_delay * HZ);
1034 	} else {
1035 		nvme_delete_ctrl(&ctrl->ctrl);
1036 	}
1037 }
1038 
1039 static int nvme_rdma_setup_ctrl(struct nvme_rdma_ctrl *ctrl, bool new)
1040 {
1041 	int ret;
1042 	bool changed;
1043 
1044 	ret = nvme_rdma_configure_admin_queue(ctrl, new);
1045 	if (ret)
1046 		return ret;
1047 
1048 	if (ctrl->ctrl.icdoff) {
1049 		ret = -EOPNOTSUPP;
1050 		dev_err(ctrl->ctrl.device, "icdoff is not supported!\n");
1051 		goto destroy_admin;
1052 	}
1053 
1054 	if (!(ctrl->ctrl.sgls & (1 << 2))) {
1055 		ret = -EOPNOTSUPP;
1056 		dev_err(ctrl->ctrl.device,
1057 			"Mandatory keyed sgls are not supported!\n");
1058 		goto destroy_admin;
1059 	}
1060 
1061 	if (ctrl->ctrl.opts->queue_size > ctrl->ctrl.sqsize + 1) {
1062 		dev_warn(ctrl->ctrl.device,
1063 			"queue_size %zu > ctrl sqsize %u, clamping down\n",
1064 			ctrl->ctrl.opts->queue_size, ctrl->ctrl.sqsize + 1);
1065 	}
1066 
1067 	if (ctrl->ctrl.sqsize + 1 > NVME_RDMA_MAX_QUEUE_SIZE) {
1068 		dev_warn(ctrl->ctrl.device,
1069 			"ctrl sqsize %u > max queue size %u, clamping down\n",
1070 			ctrl->ctrl.sqsize + 1, NVME_RDMA_MAX_QUEUE_SIZE);
1071 		ctrl->ctrl.sqsize = NVME_RDMA_MAX_QUEUE_SIZE - 1;
1072 	}
1073 
1074 	if (ctrl->ctrl.sqsize + 1 > ctrl->ctrl.maxcmd) {
1075 		dev_warn(ctrl->ctrl.device,
1076 			"sqsize %u > ctrl maxcmd %u, clamping down\n",
1077 			ctrl->ctrl.sqsize + 1, ctrl->ctrl.maxcmd);
1078 		ctrl->ctrl.sqsize = ctrl->ctrl.maxcmd - 1;
1079 	}
1080 
1081 	if (ctrl->ctrl.sgls & (1 << 20))
1082 		ctrl->use_inline_data = true;
1083 
1084 	if (ctrl->ctrl.queue_count > 1) {
1085 		ret = nvme_rdma_configure_io_queues(ctrl, new);
1086 		if (ret)
1087 			goto destroy_admin;
1088 	}
1089 
1090 	changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE);
1091 	if (!changed) {
1092 		/*
1093 		 * state change failure is ok if we started ctrl delete,
1094 		 * unless we're during creation of a new controller to
1095 		 * avoid races with teardown flow.
1096 		 */
1097 		WARN_ON_ONCE(ctrl->ctrl.state != NVME_CTRL_DELETING &&
1098 			     ctrl->ctrl.state != NVME_CTRL_DELETING_NOIO);
1099 		WARN_ON_ONCE(new);
1100 		ret = -EINVAL;
1101 		goto destroy_io;
1102 	}
1103 
1104 	nvme_start_ctrl(&ctrl->ctrl);
1105 	return 0;
1106 
1107 destroy_io:
1108 	if (ctrl->ctrl.queue_count > 1) {
1109 		nvme_stop_queues(&ctrl->ctrl);
1110 		nvme_sync_io_queues(&ctrl->ctrl);
1111 		nvme_rdma_stop_io_queues(ctrl);
1112 		nvme_cancel_tagset(&ctrl->ctrl);
1113 		if (new)
1114 			nvme_remove_io_tag_set(&ctrl->ctrl);
1115 		nvme_rdma_free_io_queues(ctrl);
1116 	}
1117 destroy_admin:
1118 	nvme_stop_admin_queue(&ctrl->ctrl);
1119 	blk_sync_queue(ctrl->ctrl.admin_q);
1120 	nvme_rdma_stop_queue(&ctrl->queues[0]);
1121 	nvme_cancel_admin_tagset(&ctrl->ctrl);
1122 	if (new)
1123 		nvme_remove_admin_tag_set(&ctrl->ctrl);
1124 	nvme_rdma_destroy_admin_queue(ctrl);
1125 	return ret;
1126 }
1127 
1128 static void nvme_rdma_reconnect_ctrl_work(struct work_struct *work)
1129 {
1130 	struct nvme_rdma_ctrl *ctrl = container_of(to_delayed_work(work),
1131 			struct nvme_rdma_ctrl, reconnect_work);
1132 
1133 	++ctrl->ctrl.nr_reconnects;
1134 
1135 	if (nvme_rdma_setup_ctrl(ctrl, false))
1136 		goto requeue;
1137 
1138 	dev_info(ctrl->ctrl.device, "Successfully reconnected (%d attempts)\n",
1139 			ctrl->ctrl.nr_reconnects);
1140 
1141 	ctrl->ctrl.nr_reconnects = 0;
1142 
1143 	return;
1144 
1145 requeue:
1146 	dev_info(ctrl->ctrl.device, "Failed reconnect attempt %d\n",
1147 			ctrl->ctrl.nr_reconnects);
1148 	nvme_rdma_reconnect_or_remove(ctrl);
1149 }
1150 
1151 static void nvme_rdma_error_recovery_work(struct work_struct *work)
1152 {
1153 	struct nvme_rdma_ctrl *ctrl = container_of(work,
1154 			struct nvme_rdma_ctrl, err_work);
1155 
1156 	nvme_auth_stop(&ctrl->ctrl);
1157 	nvme_stop_keep_alive(&ctrl->ctrl);
1158 	flush_work(&ctrl->ctrl.async_event_work);
1159 	nvme_rdma_teardown_io_queues(ctrl, false);
1160 	nvme_start_queues(&ctrl->ctrl);
1161 	nvme_rdma_teardown_admin_queue(ctrl, false);
1162 	nvme_start_admin_queue(&ctrl->ctrl);
1163 
1164 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
1165 		/* state change failure is ok if we started ctrl delete */
1166 		WARN_ON_ONCE(ctrl->ctrl.state != NVME_CTRL_DELETING &&
1167 			     ctrl->ctrl.state != NVME_CTRL_DELETING_NOIO);
1168 		return;
1169 	}
1170 
1171 	nvme_rdma_reconnect_or_remove(ctrl);
1172 }
1173 
1174 static void nvme_rdma_error_recovery(struct nvme_rdma_ctrl *ctrl)
1175 {
1176 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RESETTING))
1177 		return;
1178 
1179 	dev_warn(ctrl->ctrl.device, "starting error recovery\n");
1180 	queue_work(nvme_reset_wq, &ctrl->err_work);
1181 }
1182 
1183 static void nvme_rdma_end_request(struct nvme_rdma_request *req)
1184 {
1185 	struct request *rq = blk_mq_rq_from_pdu(req);
1186 
1187 	if (!refcount_dec_and_test(&req->ref))
1188 		return;
1189 	if (!nvme_try_complete_req(rq, req->status, req->result))
1190 		nvme_rdma_complete_rq(rq);
1191 }
1192 
1193 static void nvme_rdma_wr_error(struct ib_cq *cq, struct ib_wc *wc,
1194 		const char *op)
1195 {
1196 	struct nvme_rdma_queue *queue = wc->qp->qp_context;
1197 	struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1198 
1199 	if (ctrl->ctrl.state == NVME_CTRL_LIVE)
1200 		dev_info(ctrl->ctrl.device,
1201 			     "%s for CQE 0x%p failed with status %s (%d)\n",
1202 			     op, wc->wr_cqe,
1203 			     ib_wc_status_msg(wc->status), wc->status);
1204 	nvme_rdma_error_recovery(ctrl);
1205 }
1206 
1207 static void nvme_rdma_memreg_done(struct ib_cq *cq, struct ib_wc *wc)
1208 {
1209 	if (unlikely(wc->status != IB_WC_SUCCESS))
1210 		nvme_rdma_wr_error(cq, wc, "MEMREG");
1211 }
1212 
1213 static void nvme_rdma_inv_rkey_done(struct ib_cq *cq, struct ib_wc *wc)
1214 {
1215 	struct nvme_rdma_request *req =
1216 		container_of(wc->wr_cqe, struct nvme_rdma_request, reg_cqe);
1217 
1218 	if (unlikely(wc->status != IB_WC_SUCCESS))
1219 		nvme_rdma_wr_error(cq, wc, "LOCAL_INV");
1220 	else
1221 		nvme_rdma_end_request(req);
1222 }
1223 
1224 static int nvme_rdma_inv_rkey(struct nvme_rdma_queue *queue,
1225 		struct nvme_rdma_request *req)
1226 {
1227 	struct ib_send_wr wr = {
1228 		.opcode		    = IB_WR_LOCAL_INV,
1229 		.next		    = NULL,
1230 		.num_sge	    = 0,
1231 		.send_flags	    = IB_SEND_SIGNALED,
1232 		.ex.invalidate_rkey = req->mr->rkey,
1233 	};
1234 
1235 	req->reg_cqe.done = nvme_rdma_inv_rkey_done;
1236 	wr.wr_cqe = &req->reg_cqe;
1237 
1238 	return ib_post_send(queue->qp, &wr, NULL);
1239 }
1240 
1241 static void nvme_rdma_dma_unmap_req(struct ib_device *ibdev, struct request *rq)
1242 {
1243 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1244 
1245 	if (blk_integrity_rq(rq)) {
1246 		ib_dma_unmap_sg(ibdev, req->metadata_sgl->sg_table.sgl,
1247 				req->metadata_sgl->nents, rq_dma_dir(rq));
1248 		sg_free_table_chained(&req->metadata_sgl->sg_table,
1249 				      NVME_INLINE_METADATA_SG_CNT);
1250 	}
1251 
1252 	ib_dma_unmap_sg(ibdev, req->data_sgl.sg_table.sgl, req->data_sgl.nents,
1253 			rq_dma_dir(rq));
1254 	sg_free_table_chained(&req->data_sgl.sg_table, NVME_INLINE_SG_CNT);
1255 }
1256 
1257 static void nvme_rdma_unmap_data(struct nvme_rdma_queue *queue,
1258 		struct request *rq)
1259 {
1260 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1261 	struct nvme_rdma_device *dev = queue->device;
1262 	struct ib_device *ibdev = dev->dev;
1263 	struct list_head *pool = &queue->qp->rdma_mrs;
1264 
1265 	if (!blk_rq_nr_phys_segments(rq))
1266 		return;
1267 
1268 	if (req->use_sig_mr)
1269 		pool = &queue->qp->sig_mrs;
1270 
1271 	if (req->mr) {
1272 		ib_mr_pool_put(queue->qp, pool, req->mr);
1273 		req->mr = NULL;
1274 	}
1275 
1276 	nvme_rdma_dma_unmap_req(ibdev, rq);
1277 }
1278 
1279 static int nvme_rdma_set_sg_null(struct nvme_command *c)
1280 {
1281 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1282 
1283 	sg->addr = 0;
1284 	put_unaligned_le24(0, sg->length);
1285 	put_unaligned_le32(0, sg->key);
1286 	sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1287 	return 0;
1288 }
1289 
1290 static int nvme_rdma_map_sg_inline(struct nvme_rdma_queue *queue,
1291 		struct nvme_rdma_request *req, struct nvme_command *c,
1292 		int count)
1293 {
1294 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
1295 	struct ib_sge *sge = &req->sge[1];
1296 	struct scatterlist *sgl;
1297 	u32 len = 0;
1298 	int i;
1299 
1300 	for_each_sg(req->data_sgl.sg_table.sgl, sgl, count, i) {
1301 		sge->addr = sg_dma_address(sgl);
1302 		sge->length = sg_dma_len(sgl);
1303 		sge->lkey = queue->device->pd->local_dma_lkey;
1304 		len += sge->length;
1305 		sge++;
1306 	}
1307 
1308 	sg->addr = cpu_to_le64(queue->ctrl->ctrl.icdoff);
1309 	sg->length = cpu_to_le32(len);
1310 	sg->type = (NVME_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_OFFSET;
1311 
1312 	req->num_sge += count;
1313 	return 0;
1314 }
1315 
1316 static int nvme_rdma_map_sg_single(struct nvme_rdma_queue *queue,
1317 		struct nvme_rdma_request *req, struct nvme_command *c)
1318 {
1319 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1320 
1321 	sg->addr = cpu_to_le64(sg_dma_address(req->data_sgl.sg_table.sgl));
1322 	put_unaligned_le24(sg_dma_len(req->data_sgl.sg_table.sgl), sg->length);
1323 	put_unaligned_le32(queue->device->pd->unsafe_global_rkey, sg->key);
1324 	sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1325 	return 0;
1326 }
1327 
1328 static int nvme_rdma_map_sg_fr(struct nvme_rdma_queue *queue,
1329 		struct nvme_rdma_request *req, struct nvme_command *c,
1330 		int count)
1331 {
1332 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1333 	int nr;
1334 
1335 	req->mr = ib_mr_pool_get(queue->qp, &queue->qp->rdma_mrs);
1336 	if (WARN_ON_ONCE(!req->mr))
1337 		return -EAGAIN;
1338 
1339 	/*
1340 	 * Align the MR to a 4K page size to match the ctrl page size and
1341 	 * the block virtual boundary.
1342 	 */
1343 	nr = ib_map_mr_sg(req->mr, req->data_sgl.sg_table.sgl, count, NULL,
1344 			  SZ_4K);
1345 	if (unlikely(nr < count)) {
1346 		ib_mr_pool_put(queue->qp, &queue->qp->rdma_mrs, req->mr);
1347 		req->mr = NULL;
1348 		if (nr < 0)
1349 			return nr;
1350 		return -EINVAL;
1351 	}
1352 
1353 	ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1354 
1355 	req->reg_cqe.done = nvme_rdma_memreg_done;
1356 	memset(&req->reg_wr, 0, sizeof(req->reg_wr));
1357 	req->reg_wr.wr.opcode = IB_WR_REG_MR;
1358 	req->reg_wr.wr.wr_cqe = &req->reg_cqe;
1359 	req->reg_wr.wr.num_sge = 0;
1360 	req->reg_wr.mr = req->mr;
1361 	req->reg_wr.key = req->mr->rkey;
1362 	req->reg_wr.access = IB_ACCESS_LOCAL_WRITE |
1363 			     IB_ACCESS_REMOTE_READ |
1364 			     IB_ACCESS_REMOTE_WRITE;
1365 
1366 	sg->addr = cpu_to_le64(req->mr->iova);
1367 	put_unaligned_le24(req->mr->length, sg->length);
1368 	put_unaligned_le32(req->mr->rkey, sg->key);
1369 	sg->type = (NVME_KEY_SGL_FMT_DATA_DESC << 4) |
1370 			NVME_SGL_FMT_INVALIDATE;
1371 
1372 	return 0;
1373 }
1374 
1375 static void nvme_rdma_set_sig_domain(struct blk_integrity *bi,
1376 		struct nvme_command *cmd, struct ib_sig_domain *domain,
1377 		u16 control, u8 pi_type)
1378 {
1379 	domain->sig_type = IB_SIG_TYPE_T10_DIF;
1380 	domain->sig.dif.bg_type = IB_T10DIF_CRC;
1381 	domain->sig.dif.pi_interval = 1 << bi->interval_exp;
1382 	domain->sig.dif.ref_tag = le32_to_cpu(cmd->rw.reftag);
1383 	if (control & NVME_RW_PRINFO_PRCHK_REF)
1384 		domain->sig.dif.ref_remap = true;
1385 
1386 	domain->sig.dif.app_tag = le16_to_cpu(cmd->rw.apptag);
1387 	domain->sig.dif.apptag_check_mask = le16_to_cpu(cmd->rw.appmask);
1388 	domain->sig.dif.app_escape = true;
1389 	if (pi_type == NVME_NS_DPS_PI_TYPE3)
1390 		domain->sig.dif.ref_escape = true;
1391 }
1392 
1393 static void nvme_rdma_set_sig_attrs(struct blk_integrity *bi,
1394 		struct nvme_command *cmd, struct ib_sig_attrs *sig_attrs,
1395 		u8 pi_type)
1396 {
1397 	u16 control = le16_to_cpu(cmd->rw.control);
1398 
1399 	memset(sig_attrs, 0, sizeof(*sig_attrs));
1400 	if (control & NVME_RW_PRINFO_PRACT) {
1401 		/* for WRITE_INSERT/READ_STRIP no memory domain */
1402 		sig_attrs->mem.sig_type = IB_SIG_TYPE_NONE;
1403 		nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->wire, control,
1404 					 pi_type);
1405 		/* Clear the PRACT bit since HCA will generate/verify the PI */
1406 		control &= ~NVME_RW_PRINFO_PRACT;
1407 		cmd->rw.control = cpu_to_le16(control);
1408 	} else {
1409 		/* for WRITE_PASS/READ_PASS both wire/memory domains exist */
1410 		nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->wire, control,
1411 					 pi_type);
1412 		nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->mem, control,
1413 					 pi_type);
1414 	}
1415 }
1416 
1417 static void nvme_rdma_set_prot_checks(struct nvme_command *cmd, u8 *mask)
1418 {
1419 	*mask = 0;
1420 	if (le16_to_cpu(cmd->rw.control) & NVME_RW_PRINFO_PRCHK_REF)
1421 		*mask |= IB_SIG_CHECK_REFTAG;
1422 	if (le16_to_cpu(cmd->rw.control) & NVME_RW_PRINFO_PRCHK_GUARD)
1423 		*mask |= IB_SIG_CHECK_GUARD;
1424 }
1425 
1426 static void nvme_rdma_sig_done(struct ib_cq *cq, struct ib_wc *wc)
1427 {
1428 	if (unlikely(wc->status != IB_WC_SUCCESS))
1429 		nvme_rdma_wr_error(cq, wc, "SIG");
1430 }
1431 
1432 static int nvme_rdma_map_sg_pi(struct nvme_rdma_queue *queue,
1433 		struct nvme_rdma_request *req, struct nvme_command *c,
1434 		int count, int pi_count)
1435 {
1436 	struct nvme_rdma_sgl *sgl = &req->data_sgl;
1437 	struct ib_reg_wr *wr = &req->reg_wr;
1438 	struct request *rq = blk_mq_rq_from_pdu(req);
1439 	struct nvme_ns *ns = rq->q->queuedata;
1440 	struct bio *bio = rq->bio;
1441 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1442 	int nr;
1443 
1444 	req->mr = ib_mr_pool_get(queue->qp, &queue->qp->sig_mrs);
1445 	if (WARN_ON_ONCE(!req->mr))
1446 		return -EAGAIN;
1447 
1448 	nr = ib_map_mr_sg_pi(req->mr, sgl->sg_table.sgl, count, NULL,
1449 			     req->metadata_sgl->sg_table.sgl, pi_count, NULL,
1450 			     SZ_4K);
1451 	if (unlikely(nr))
1452 		goto mr_put;
1453 
1454 	nvme_rdma_set_sig_attrs(blk_get_integrity(bio->bi_bdev->bd_disk), c,
1455 				req->mr->sig_attrs, ns->pi_type);
1456 	nvme_rdma_set_prot_checks(c, &req->mr->sig_attrs->check_mask);
1457 
1458 	ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1459 
1460 	req->reg_cqe.done = nvme_rdma_sig_done;
1461 	memset(wr, 0, sizeof(*wr));
1462 	wr->wr.opcode = IB_WR_REG_MR_INTEGRITY;
1463 	wr->wr.wr_cqe = &req->reg_cqe;
1464 	wr->wr.num_sge = 0;
1465 	wr->wr.send_flags = 0;
1466 	wr->mr = req->mr;
1467 	wr->key = req->mr->rkey;
1468 	wr->access = IB_ACCESS_LOCAL_WRITE |
1469 		     IB_ACCESS_REMOTE_READ |
1470 		     IB_ACCESS_REMOTE_WRITE;
1471 
1472 	sg->addr = cpu_to_le64(req->mr->iova);
1473 	put_unaligned_le24(req->mr->length, sg->length);
1474 	put_unaligned_le32(req->mr->rkey, sg->key);
1475 	sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1476 
1477 	return 0;
1478 
1479 mr_put:
1480 	ib_mr_pool_put(queue->qp, &queue->qp->sig_mrs, req->mr);
1481 	req->mr = NULL;
1482 	if (nr < 0)
1483 		return nr;
1484 	return -EINVAL;
1485 }
1486 
1487 static int nvme_rdma_dma_map_req(struct ib_device *ibdev, struct request *rq,
1488 		int *count, int *pi_count)
1489 {
1490 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1491 	int ret;
1492 
1493 	req->data_sgl.sg_table.sgl = (struct scatterlist *)(req + 1);
1494 	ret = sg_alloc_table_chained(&req->data_sgl.sg_table,
1495 			blk_rq_nr_phys_segments(rq), req->data_sgl.sg_table.sgl,
1496 			NVME_INLINE_SG_CNT);
1497 	if (ret)
1498 		return -ENOMEM;
1499 
1500 	req->data_sgl.nents = blk_rq_map_sg(rq->q, rq,
1501 					    req->data_sgl.sg_table.sgl);
1502 
1503 	*count = ib_dma_map_sg(ibdev, req->data_sgl.sg_table.sgl,
1504 			       req->data_sgl.nents, rq_dma_dir(rq));
1505 	if (unlikely(*count <= 0)) {
1506 		ret = -EIO;
1507 		goto out_free_table;
1508 	}
1509 
1510 	if (blk_integrity_rq(rq)) {
1511 		req->metadata_sgl->sg_table.sgl =
1512 			(struct scatterlist *)(req->metadata_sgl + 1);
1513 		ret = sg_alloc_table_chained(&req->metadata_sgl->sg_table,
1514 				blk_rq_count_integrity_sg(rq->q, rq->bio),
1515 				req->metadata_sgl->sg_table.sgl,
1516 				NVME_INLINE_METADATA_SG_CNT);
1517 		if (unlikely(ret)) {
1518 			ret = -ENOMEM;
1519 			goto out_unmap_sg;
1520 		}
1521 
1522 		req->metadata_sgl->nents = blk_rq_map_integrity_sg(rq->q,
1523 				rq->bio, req->metadata_sgl->sg_table.sgl);
1524 		*pi_count = ib_dma_map_sg(ibdev,
1525 					  req->metadata_sgl->sg_table.sgl,
1526 					  req->metadata_sgl->nents,
1527 					  rq_dma_dir(rq));
1528 		if (unlikely(*pi_count <= 0)) {
1529 			ret = -EIO;
1530 			goto out_free_pi_table;
1531 		}
1532 	}
1533 
1534 	return 0;
1535 
1536 out_free_pi_table:
1537 	sg_free_table_chained(&req->metadata_sgl->sg_table,
1538 			      NVME_INLINE_METADATA_SG_CNT);
1539 out_unmap_sg:
1540 	ib_dma_unmap_sg(ibdev, req->data_sgl.sg_table.sgl, req->data_sgl.nents,
1541 			rq_dma_dir(rq));
1542 out_free_table:
1543 	sg_free_table_chained(&req->data_sgl.sg_table, NVME_INLINE_SG_CNT);
1544 	return ret;
1545 }
1546 
1547 static int nvme_rdma_map_data(struct nvme_rdma_queue *queue,
1548 		struct request *rq, struct nvme_command *c)
1549 {
1550 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1551 	struct nvme_rdma_device *dev = queue->device;
1552 	struct ib_device *ibdev = dev->dev;
1553 	int pi_count = 0;
1554 	int count, ret;
1555 
1556 	req->num_sge = 1;
1557 	refcount_set(&req->ref, 2); /* send and recv completions */
1558 
1559 	c->common.flags |= NVME_CMD_SGL_METABUF;
1560 
1561 	if (!blk_rq_nr_phys_segments(rq))
1562 		return nvme_rdma_set_sg_null(c);
1563 
1564 	ret = nvme_rdma_dma_map_req(ibdev, rq, &count, &pi_count);
1565 	if (unlikely(ret))
1566 		return ret;
1567 
1568 	if (req->use_sig_mr) {
1569 		ret = nvme_rdma_map_sg_pi(queue, req, c, count, pi_count);
1570 		goto out;
1571 	}
1572 
1573 	if (count <= dev->num_inline_segments) {
1574 		if (rq_data_dir(rq) == WRITE && nvme_rdma_queue_idx(queue) &&
1575 		    queue->ctrl->use_inline_data &&
1576 		    blk_rq_payload_bytes(rq) <=
1577 				nvme_rdma_inline_data_size(queue)) {
1578 			ret = nvme_rdma_map_sg_inline(queue, req, c, count);
1579 			goto out;
1580 		}
1581 
1582 		if (count == 1 && dev->pd->flags & IB_PD_UNSAFE_GLOBAL_RKEY) {
1583 			ret = nvme_rdma_map_sg_single(queue, req, c);
1584 			goto out;
1585 		}
1586 	}
1587 
1588 	ret = nvme_rdma_map_sg_fr(queue, req, c, count);
1589 out:
1590 	if (unlikely(ret))
1591 		goto out_dma_unmap_req;
1592 
1593 	return 0;
1594 
1595 out_dma_unmap_req:
1596 	nvme_rdma_dma_unmap_req(ibdev, rq);
1597 	return ret;
1598 }
1599 
1600 static void nvme_rdma_send_done(struct ib_cq *cq, struct ib_wc *wc)
1601 {
1602 	struct nvme_rdma_qe *qe =
1603 		container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe);
1604 	struct nvme_rdma_request *req =
1605 		container_of(qe, struct nvme_rdma_request, sqe);
1606 
1607 	if (unlikely(wc->status != IB_WC_SUCCESS))
1608 		nvme_rdma_wr_error(cq, wc, "SEND");
1609 	else
1610 		nvme_rdma_end_request(req);
1611 }
1612 
1613 static int nvme_rdma_post_send(struct nvme_rdma_queue *queue,
1614 		struct nvme_rdma_qe *qe, struct ib_sge *sge, u32 num_sge,
1615 		struct ib_send_wr *first)
1616 {
1617 	struct ib_send_wr wr;
1618 	int ret;
1619 
1620 	sge->addr   = qe->dma;
1621 	sge->length = sizeof(struct nvme_command);
1622 	sge->lkey   = queue->device->pd->local_dma_lkey;
1623 
1624 	wr.next       = NULL;
1625 	wr.wr_cqe     = &qe->cqe;
1626 	wr.sg_list    = sge;
1627 	wr.num_sge    = num_sge;
1628 	wr.opcode     = IB_WR_SEND;
1629 	wr.send_flags = IB_SEND_SIGNALED;
1630 
1631 	if (first)
1632 		first->next = &wr;
1633 	else
1634 		first = &wr;
1635 
1636 	ret = ib_post_send(queue->qp, first, NULL);
1637 	if (unlikely(ret)) {
1638 		dev_err(queue->ctrl->ctrl.device,
1639 			     "%s failed with error code %d\n", __func__, ret);
1640 	}
1641 	return ret;
1642 }
1643 
1644 static int nvme_rdma_post_recv(struct nvme_rdma_queue *queue,
1645 		struct nvme_rdma_qe *qe)
1646 {
1647 	struct ib_recv_wr wr;
1648 	struct ib_sge list;
1649 	int ret;
1650 
1651 	list.addr   = qe->dma;
1652 	list.length = sizeof(struct nvme_completion);
1653 	list.lkey   = queue->device->pd->local_dma_lkey;
1654 
1655 	qe->cqe.done = nvme_rdma_recv_done;
1656 
1657 	wr.next     = NULL;
1658 	wr.wr_cqe   = &qe->cqe;
1659 	wr.sg_list  = &list;
1660 	wr.num_sge  = 1;
1661 
1662 	ret = ib_post_recv(queue->qp, &wr, NULL);
1663 	if (unlikely(ret)) {
1664 		dev_err(queue->ctrl->ctrl.device,
1665 			"%s failed with error code %d\n", __func__, ret);
1666 	}
1667 	return ret;
1668 }
1669 
1670 static struct blk_mq_tags *nvme_rdma_tagset(struct nvme_rdma_queue *queue)
1671 {
1672 	u32 queue_idx = nvme_rdma_queue_idx(queue);
1673 
1674 	if (queue_idx == 0)
1675 		return queue->ctrl->admin_tag_set.tags[queue_idx];
1676 	return queue->ctrl->tag_set.tags[queue_idx - 1];
1677 }
1678 
1679 static void nvme_rdma_async_done(struct ib_cq *cq, struct ib_wc *wc)
1680 {
1681 	if (unlikely(wc->status != IB_WC_SUCCESS))
1682 		nvme_rdma_wr_error(cq, wc, "ASYNC");
1683 }
1684 
1685 static void nvme_rdma_submit_async_event(struct nvme_ctrl *arg)
1686 {
1687 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(arg);
1688 	struct nvme_rdma_queue *queue = &ctrl->queues[0];
1689 	struct ib_device *dev = queue->device->dev;
1690 	struct nvme_rdma_qe *sqe = &ctrl->async_event_sqe;
1691 	struct nvme_command *cmd = sqe->data;
1692 	struct ib_sge sge;
1693 	int ret;
1694 
1695 	ib_dma_sync_single_for_cpu(dev, sqe->dma, sizeof(*cmd), DMA_TO_DEVICE);
1696 
1697 	memset(cmd, 0, sizeof(*cmd));
1698 	cmd->common.opcode = nvme_admin_async_event;
1699 	cmd->common.command_id = NVME_AQ_BLK_MQ_DEPTH;
1700 	cmd->common.flags |= NVME_CMD_SGL_METABUF;
1701 	nvme_rdma_set_sg_null(cmd);
1702 
1703 	sqe->cqe.done = nvme_rdma_async_done;
1704 
1705 	ib_dma_sync_single_for_device(dev, sqe->dma, sizeof(*cmd),
1706 			DMA_TO_DEVICE);
1707 
1708 	ret = nvme_rdma_post_send(queue, sqe, &sge, 1, NULL);
1709 	WARN_ON_ONCE(ret);
1710 }
1711 
1712 static void nvme_rdma_process_nvme_rsp(struct nvme_rdma_queue *queue,
1713 		struct nvme_completion *cqe, struct ib_wc *wc)
1714 {
1715 	struct request *rq;
1716 	struct nvme_rdma_request *req;
1717 
1718 	rq = nvme_find_rq(nvme_rdma_tagset(queue), cqe->command_id);
1719 	if (!rq) {
1720 		dev_err(queue->ctrl->ctrl.device,
1721 			"got bad command_id %#x on QP %#x\n",
1722 			cqe->command_id, queue->qp->qp_num);
1723 		nvme_rdma_error_recovery(queue->ctrl);
1724 		return;
1725 	}
1726 	req = blk_mq_rq_to_pdu(rq);
1727 
1728 	req->status = cqe->status;
1729 	req->result = cqe->result;
1730 
1731 	if (wc->wc_flags & IB_WC_WITH_INVALIDATE) {
1732 		if (unlikely(!req->mr ||
1733 			     wc->ex.invalidate_rkey != req->mr->rkey)) {
1734 			dev_err(queue->ctrl->ctrl.device,
1735 				"Bogus remote invalidation for rkey %#x\n",
1736 				req->mr ? req->mr->rkey : 0);
1737 			nvme_rdma_error_recovery(queue->ctrl);
1738 		}
1739 	} else if (req->mr) {
1740 		int ret;
1741 
1742 		ret = nvme_rdma_inv_rkey(queue, req);
1743 		if (unlikely(ret < 0)) {
1744 			dev_err(queue->ctrl->ctrl.device,
1745 				"Queueing INV WR for rkey %#x failed (%d)\n",
1746 				req->mr->rkey, ret);
1747 			nvme_rdma_error_recovery(queue->ctrl);
1748 		}
1749 		/* the local invalidation completion will end the request */
1750 		return;
1751 	}
1752 
1753 	nvme_rdma_end_request(req);
1754 }
1755 
1756 static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc)
1757 {
1758 	struct nvme_rdma_qe *qe =
1759 		container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe);
1760 	struct nvme_rdma_queue *queue = wc->qp->qp_context;
1761 	struct ib_device *ibdev = queue->device->dev;
1762 	struct nvme_completion *cqe = qe->data;
1763 	const size_t len = sizeof(struct nvme_completion);
1764 
1765 	if (unlikely(wc->status != IB_WC_SUCCESS)) {
1766 		nvme_rdma_wr_error(cq, wc, "RECV");
1767 		return;
1768 	}
1769 
1770 	/* sanity checking for received data length */
1771 	if (unlikely(wc->byte_len < len)) {
1772 		dev_err(queue->ctrl->ctrl.device,
1773 			"Unexpected nvme completion length(%d)\n", wc->byte_len);
1774 		nvme_rdma_error_recovery(queue->ctrl);
1775 		return;
1776 	}
1777 
1778 	ib_dma_sync_single_for_cpu(ibdev, qe->dma, len, DMA_FROM_DEVICE);
1779 	/*
1780 	 * AEN requests are special as they don't time out and can
1781 	 * survive any kind of queue freeze and often don't respond to
1782 	 * aborts.  We don't even bother to allocate a struct request
1783 	 * for them but rather special case them here.
1784 	 */
1785 	if (unlikely(nvme_is_aen_req(nvme_rdma_queue_idx(queue),
1786 				     cqe->command_id)))
1787 		nvme_complete_async_event(&queue->ctrl->ctrl, cqe->status,
1788 				&cqe->result);
1789 	else
1790 		nvme_rdma_process_nvme_rsp(queue, cqe, wc);
1791 	ib_dma_sync_single_for_device(ibdev, qe->dma, len, DMA_FROM_DEVICE);
1792 
1793 	nvme_rdma_post_recv(queue, qe);
1794 }
1795 
1796 static int nvme_rdma_conn_established(struct nvme_rdma_queue *queue)
1797 {
1798 	int ret, i;
1799 
1800 	for (i = 0; i < queue->queue_size; i++) {
1801 		ret = nvme_rdma_post_recv(queue, &queue->rsp_ring[i]);
1802 		if (ret)
1803 			return ret;
1804 	}
1805 
1806 	return 0;
1807 }
1808 
1809 static int nvme_rdma_conn_rejected(struct nvme_rdma_queue *queue,
1810 		struct rdma_cm_event *ev)
1811 {
1812 	struct rdma_cm_id *cm_id = queue->cm_id;
1813 	int status = ev->status;
1814 	const char *rej_msg;
1815 	const struct nvme_rdma_cm_rej *rej_data;
1816 	u8 rej_data_len;
1817 
1818 	rej_msg = rdma_reject_msg(cm_id, status);
1819 	rej_data = rdma_consumer_reject_data(cm_id, ev, &rej_data_len);
1820 
1821 	if (rej_data && rej_data_len >= sizeof(u16)) {
1822 		u16 sts = le16_to_cpu(rej_data->sts);
1823 
1824 		dev_err(queue->ctrl->ctrl.device,
1825 		      "Connect rejected: status %d (%s) nvme status %d (%s).\n",
1826 		      status, rej_msg, sts, nvme_rdma_cm_msg(sts));
1827 	} else {
1828 		dev_err(queue->ctrl->ctrl.device,
1829 			"Connect rejected: status %d (%s).\n", status, rej_msg);
1830 	}
1831 
1832 	return -ECONNRESET;
1833 }
1834 
1835 static int nvme_rdma_addr_resolved(struct nvme_rdma_queue *queue)
1836 {
1837 	struct nvme_ctrl *ctrl = &queue->ctrl->ctrl;
1838 	int ret;
1839 
1840 	ret = nvme_rdma_create_queue_ib(queue);
1841 	if (ret)
1842 		return ret;
1843 
1844 	if (ctrl->opts->tos >= 0)
1845 		rdma_set_service_type(queue->cm_id, ctrl->opts->tos);
1846 	ret = rdma_resolve_route(queue->cm_id, NVME_RDMA_CM_TIMEOUT_MS);
1847 	if (ret) {
1848 		dev_err(ctrl->device, "rdma_resolve_route failed (%d).\n",
1849 			queue->cm_error);
1850 		goto out_destroy_queue;
1851 	}
1852 
1853 	return 0;
1854 
1855 out_destroy_queue:
1856 	nvme_rdma_destroy_queue_ib(queue);
1857 	return ret;
1858 }
1859 
1860 static int nvme_rdma_route_resolved(struct nvme_rdma_queue *queue)
1861 {
1862 	struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1863 	struct rdma_conn_param param = { };
1864 	struct nvme_rdma_cm_req priv = { };
1865 	int ret;
1866 
1867 	param.qp_num = queue->qp->qp_num;
1868 	param.flow_control = 1;
1869 
1870 	param.responder_resources = queue->device->dev->attrs.max_qp_rd_atom;
1871 	/* maximum retry count */
1872 	param.retry_count = 7;
1873 	param.rnr_retry_count = 7;
1874 	param.private_data = &priv;
1875 	param.private_data_len = sizeof(priv);
1876 
1877 	priv.recfmt = cpu_to_le16(NVME_RDMA_CM_FMT_1_0);
1878 	priv.qid = cpu_to_le16(nvme_rdma_queue_idx(queue));
1879 	/*
1880 	 * set the admin queue depth to the minimum size
1881 	 * specified by the Fabrics standard.
1882 	 */
1883 	if (priv.qid == 0) {
1884 		priv.hrqsize = cpu_to_le16(NVME_AQ_DEPTH);
1885 		priv.hsqsize = cpu_to_le16(NVME_AQ_DEPTH - 1);
1886 	} else {
1887 		/*
1888 		 * current interpretation of the fabrics spec
1889 		 * is at minimum you make hrqsize sqsize+1, or a
1890 		 * 1's based representation of sqsize.
1891 		 */
1892 		priv.hrqsize = cpu_to_le16(queue->queue_size);
1893 		priv.hsqsize = cpu_to_le16(queue->ctrl->ctrl.sqsize);
1894 	}
1895 
1896 	ret = rdma_connect_locked(queue->cm_id, &param);
1897 	if (ret) {
1898 		dev_err(ctrl->ctrl.device,
1899 			"rdma_connect_locked failed (%d).\n", ret);
1900 		return ret;
1901 	}
1902 
1903 	return 0;
1904 }
1905 
1906 static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id,
1907 		struct rdma_cm_event *ev)
1908 {
1909 	struct nvme_rdma_queue *queue = cm_id->context;
1910 	int cm_error = 0;
1911 
1912 	dev_dbg(queue->ctrl->ctrl.device, "%s (%d): status %d id %p\n",
1913 		rdma_event_msg(ev->event), ev->event,
1914 		ev->status, cm_id);
1915 
1916 	switch (ev->event) {
1917 	case RDMA_CM_EVENT_ADDR_RESOLVED:
1918 		cm_error = nvme_rdma_addr_resolved(queue);
1919 		break;
1920 	case RDMA_CM_EVENT_ROUTE_RESOLVED:
1921 		cm_error = nvme_rdma_route_resolved(queue);
1922 		break;
1923 	case RDMA_CM_EVENT_ESTABLISHED:
1924 		queue->cm_error = nvme_rdma_conn_established(queue);
1925 		/* complete cm_done regardless of success/failure */
1926 		complete(&queue->cm_done);
1927 		return 0;
1928 	case RDMA_CM_EVENT_REJECTED:
1929 		cm_error = nvme_rdma_conn_rejected(queue, ev);
1930 		break;
1931 	case RDMA_CM_EVENT_ROUTE_ERROR:
1932 	case RDMA_CM_EVENT_CONNECT_ERROR:
1933 	case RDMA_CM_EVENT_UNREACHABLE:
1934 	case RDMA_CM_EVENT_ADDR_ERROR:
1935 		dev_dbg(queue->ctrl->ctrl.device,
1936 			"CM error event %d\n", ev->event);
1937 		cm_error = -ECONNRESET;
1938 		break;
1939 	case RDMA_CM_EVENT_DISCONNECTED:
1940 	case RDMA_CM_EVENT_ADDR_CHANGE:
1941 	case RDMA_CM_EVENT_TIMEWAIT_EXIT:
1942 		dev_dbg(queue->ctrl->ctrl.device,
1943 			"disconnect received - connection closed\n");
1944 		nvme_rdma_error_recovery(queue->ctrl);
1945 		break;
1946 	case RDMA_CM_EVENT_DEVICE_REMOVAL:
1947 		/* device removal is handled via the ib_client API */
1948 		break;
1949 	default:
1950 		dev_err(queue->ctrl->ctrl.device,
1951 			"Unexpected RDMA CM event (%d)\n", ev->event);
1952 		nvme_rdma_error_recovery(queue->ctrl);
1953 		break;
1954 	}
1955 
1956 	if (cm_error) {
1957 		queue->cm_error = cm_error;
1958 		complete(&queue->cm_done);
1959 	}
1960 
1961 	return 0;
1962 }
1963 
1964 static void nvme_rdma_complete_timed_out(struct request *rq)
1965 {
1966 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1967 	struct nvme_rdma_queue *queue = req->queue;
1968 
1969 	nvme_rdma_stop_queue(queue);
1970 	nvmf_complete_timed_out_request(rq);
1971 }
1972 
1973 static enum blk_eh_timer_return nvme_rdma_timeout(struct request *rq)
1974 {
1975 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1976 	struct nvme_rdma_queue *queue = req->queue;
1977 	struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1978 
1979 	dev_warn(ctrl->ctrl.device, "I/O %d QID %d timeout\n",
1980 		 rq->tag, nvme_rdma_queue_idx(queue));
1981 
1982 	if (ctrl->ctrl.state != NVME_CTRL_LIVE) {
1983 		/*
1984 		 * If we are resetting, connecting or deleting we should
1985 		 * complete immediately because we may block controller
1986 		 * teardown or setup sequence
1987 		 * - ctrl disable/shutdown fabrics requests
1988 		 * - connect requests
1989 		 * - initialization admin requests
1990 		 * - I/O requests that entered after unquiescing and
1991 		 *   the controller stopped responding
1992 		 *
1993 		 * All other requests should be cancelled by the error
1994 		 * recovery work, so it's fine that we fail it here.
1995 		 */
1996 		nvme_rdma_complete_timed_out(rq);
1997 		return BLK_EH_DONE;
1998 	}
1999 
2000 	/*
2001 	 * LIVE state should trigger the normal error recovery which will
2002 	 * handle completing this request.
2003 	 */
2004 	nvme_rdma_error_recovery(ctrl);
2005 	return BLK_EH_RESET_TIMER;
2006 }
2007 
2008 static blk_status_t nvme_rdma_queue_rq(struct blk_mq_hw_ctx *hctx,
2009 		const struct blk_mq_queue_data *bd)
2010 {
2011 	struct nvme_ns *ns = hctx->queue->queuedata;
2012 	struct nvme_rdma_queue *queue = hctx->driver_data;
2013 	struct request *rq = bd->rq;
2014 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2015 	struct nvme_rdma_qe *sqe = &req->sqe;
2016 	struct nvme_command *c = nvme_req(rq)->cmd;
2017 	struct ib_device *dev;
2018 	bool queue_ready = test_bit(NVME_RDMA_Q_LIVE, &queue->flags);
2019 	blk_status_t ret;
2020 	int err;
2021 
2022 	WARN_ON_ONCE(rq->tag < 0);
2023 
2024 	if (!nvme_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
2025 		return nvme_fail_nonready_command(&queue->ctrl->ctrl, rq);
2026 
2027 	dev = queue->device->dev;
2028 
2029 	req->sqe.dma = ib_dma_map_single(dev, req->sqe.data,
2030 					 sizeof(struct nvme_command),
2031 					 DMA_TO_DEVICE);
2032 	err = ib_dma_mapping_error(dev, req->sqe.dma);
2033 	if (unlikely(err))
2034 		return BLK_STS_RESOURCE;
2035 
2036 	ib_dma_sync_single_for_cpu(dev, sqe->dma,
2037 			sizeof(struct nvme_command), DMA_TO_DEVICE);
2038 
2039 	ret = nvme_setup_cmd(ns, rq);
2040 	if (ret)
2041 		goto unmap_qe;
2042 
2043 	blk_mq_start_request(rq);
2044 
2045 	if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
2046 	    queue->pi_support &&
2047 	    (c->common.opcode == nvme_cmd_write ||
2048 	     c->common.opcode == nvme_cmd_read) &&
2049 	    nvme_ns_has_pi(ns))
2050 		req->use_sig_mr = true;
2051 	else
2052 		req->use_sig_mr = false;
2053 
2054 	err = nvme_rdma_map_data(queue, rq, c);
2055 	if (unlikely(err < 0)) {
2056 		dev_err(queue->ctrl->ctrl.device,
2057 			     "Failed to map data (%d)\n", err);
2058 		goto err;
2059 	}
2060 
2061 	sqe->cqe.done = nvme_rdma_send_done;
2062 
2063 	ib_dma_sync_single_for_device(dev, sqe->dma,
2064 			sizeof(struct nvme_command), DMA_TO_DEVICE);
2065 
2066 	err = nvme_rdma_post_send(queue, sqe, req->sge, req->num_sge,
2067 			req->mr ? &req->reg_wr.wr : NULL);
2068 	if (unlikely(err))
2069 		goto err_unmap;
2070 
2071 	return BLK_STS_OK;
2072 
2073 err_unmap:
2074 	nvme_rdma_unmap_data(queue, rq);
2075 err:
2076 	if (err == -EIO)
2077 		ret = nvme_host_path_error(rq);
2078 	else if (err == -ENOMEM || err == -EAGAIN)
2079 		ret = BLK_STS_RESOURCE;
2080 	else
2081 		ret = BLK_STS_IOERR;
2082 	nvme_cleanup_cmd(rq);
2083 unmap_qe:
2084 	ib_dma_unmap_single(dev, req->sqe.dma, sizeof(struct nvme_command),
2085 			    DMA_TO_DEVICE);
2086 	return ret;
2087 }
2088 
2089 static int nvme_rdma_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
2090 {
2091 	struct nvme_rdma_queue *queue = hctx->driver_data;
2092 
2093 	return ib_process_cq_direct(queue->ib_cq, -1);
2094 }
2095 
2096 static void nvme_rdma_check_pi_status(struct nvme_rdma_request *req)
2097 {
2098 	struct request *rq = blk_mq_rq_from_pdu(req);
2099 	struct ib_mr_status mr_status;
2100 	int ret;
2101 
2102 	ret = ib_check_mr_status(req->mr, IB_MR_CHECK_SIG_STATUS, &mr_status);
2103 	if (ret) {
2104 		pr_err("ib_check_mr_status failed, ret %d\n", ret);
2105 		nvme_req(rq)->status = NVME_SC_INVALID_PI;
2106 		return;
2107 	}
2108 
2109 	if (mr_status.fail_status & IB_MR_CHECK_SIG_STATUS) {
2110 		switch (mr_status.sig_err.err_type) {
2111 		case IB_SIG_BAD_GUARD:
2112 			nvme_req(rq)->status = NVME_SC_GUARD_CHECK;
2113 			break;
2114 		case IB_SIG_BAD_REFTAG:
2115 			nvme_req(rq)->status = NVME_SC_REFTAG_CHECK;
2116 			break;
2117 		case IB_SIG_BAD_APPTAG:
2118 			nvme_req(rq)->status = NVME_SC_APPTAG_CHECK;
2119 			break;
2120 		}
2121 		pr_err("PI error found type %d expected 0x%x vs actual 0x%x\n",
2122 		       mr_status.sig_err.err_type, mr_status.sig_err.expected,
2123 		       mr_status.sig_err.actual);
2124 	}
2125 }
2126 
2127 static void nvme_rdma_complete_rq(struct request *rq)
2128 {
2129 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2130 	struct nvme_rdma_queue *queue = req->queue;
2131 	struct ib_device *ibdev = queue->device->dev;
2132 
2133 	if (req->use_sig_mr)
2134 		nvme_rdma_check_pi_status(req);
2135 
2136 	nvme_rdma_unmap_data(queue, rq);
2137 	ib_dma_unmap_single(ibdev, req->sqe.dma, sizeof(struct nvme_command),
2138 			    DMA_TO_DEVICE);
2139 	nvme_complete_rq(rq);
2140 }
2141 
2142 static void nvme_rdma_map_queues(struct blk_mq_tag_set *set)
2143 {
2144 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(set->driver_data);
2145 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2146 
2147 	if (opts->nr_write_queues && ctrl->io_queues[HCTX_TYPE_READ]) {
2148 		/* separate read/write queues */
2149 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
2150 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2151 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2152 		set->map[HCTX_TYPE_READ].nr_queues =
2153 			ctrl->io_queues[HCTX_TYPE_READ];
2154 		set->map[HCTX_TYPE_READ].queue_offset =
2155 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2156 	} else {
2157 		/* shared read/write queues */
2158 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
2159 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2160 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2161 		set->map[HCTX_TYPE_READ].nr_queues =
2162 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2163 		set->map[HCTX_TYPE_READ].queue_offset = 0;
2164 	}
2165 	blk_mq_rdma_map_queues(&set->map[HCTX_TYPE_DEFAULT],
2166 			ctrl->device->dev, 0);
2167 	blk_mq_rdma_map_queues(&set->map[HCTX_TYPE_READ],
2168 			ctrl->device->dev, 0);
2169 
2170 	if (opts->nr_poll_queues && ctrl->io_queues[HCTX_TYPE_POLL]) {
2171 		/* map dedicated poll queues only if we have queues left */
2172 		set->map[HCTX_TYPE_POLL].nr_queues =
2173 				ctrl->io_queues[HCTX_TYPE_POLL];
2174 		set->map[HCTX_TYPE_POLL].queue_offset =
2175 			ctrl->io_queues[HCTX_TYPE_DEFAULT] +
2176 			ctrl->io_queues[HCTX_TYPE_READ];
2177 		blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]);
2178 	}
2179 
2180 	dev_info(ctrl->ctrl.device,
2181 		"mapped %d/%d/%d default/read/poll queues.\n",
2182 		ctrl->io_queues[HCTX_TYPE_DEFAULT],
2183 		ctrl->io_queues[HCTX_TYPE_READ],
2184 		ctrl->io_queues[HCTX_TYPE_POLL]);
2185 }
2186 
2187 static const struct blk_mq_ops nvme_rdma_mq_ops = {
2188 	.queue_rq	= nvme_rdma_queue_rq,
2189 	.complete	= nvme_rdma_complete_rq,
2190 	.init_request	= nvme_rdma_init_request,
2191 	.exit_request	= nvme_rdma_exit_request,
2192 	.init_hctx	= nvme_rdma_init_hctx,
2193 	.timeout	= nvme_rdma_timeout,
2194 	.map_queues	= nvme_rdma_map_queues,
2195 	.poll		= nvme_rdma_poll,
2196 };
2197 
2198 static const struct blk_mq_ops nvme_rdma_admin_mq_ops = {
2199 	.queue_rq	= nvme_rdma_queue_rq,
2200 	.complete	= nvme_rdma_complete_rq,
2201 	.init_request	= nvme_rdma_init_request,
2202 	.exit_request	= nvme_rdma_exit_request,
2203 	.init_hctx	= nvme_rdma_init_admin_hctx,
2204 	.timeout	= nvme_rdma_timeout,
2205 };
2206 
2207 static void nvme_rdma_shutdown_ctrl(struct nvme_rdma_ctrl *ctrl, bool shutdown)
2208 {
2209 	nvme_rdma_teardown_io_queues(ctrl, shutdown);
2210 	nvme_stop_admin_queue(&ctrl->ctrl);
2211 	if (shutdown)
2212 		nvme_shutdown_ctrl(&ctrl->ctrl);
2213 	else
2214 		nvme_disable_ctrl(&ctrl->ctrl);
2215 	nvme_rdma_teardown_admin_queue(ctrl, shutdown);
2216 }
2217 
2218 static void nvme_rdma_delete_ctrl(struct nvme_ctrl *ctrl)
2219 {
2220 	nvme_rdma_shutdown_ctrl(to_rdma_ctrl(ctrl), true);
2221 }
2222 
2223 static void nvme_rdma_reset_ctrl_work(struct work_struct *work)
2224 {
2225 	struct nvme_rdma_ctrl *ctrl =
2226 		container_of(work, struct nvme_rdma_ctrl, ctrl.reset_work);
2227 
2228 	nvme_stop_ctrl(&ctrl->ctrl);
2229 	nvme_rdma_shutdown_ctrl(ctrl, false);
2230 
2231 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
2232 		/* state change failure should never happen */
2233 		WARN_ON_ONCE(1);
2234 		return;
2235 	}
2236 
2237 	if (nvme_rdma_setup_ctrl(ctrl, false))
2238 		goto out_fail;
2239 
2240 	return;
2241 
2242 out_fail:
2243 	++ctrl->ctrl.nr_reconnects;
2244 	nvme_rdma_reconnect_or_remove(ctrl);
2245 }
2246 
2247 static const struct nvme_ctrl_ops nvme_rdma_ctrl_ops = {
2248 	.name			= "rdma",
2249 	.module			= THIS_MODULE,
2250 	.flags			= NVME_F_FABRICS | NVME_F_METADATA_SUPPORTED,
2251 	.reg_read32		= nvmf_reg_read32,
2252 	.reg_read64		= nvmf_reg_read64,
2253 	.reg_write32		= nvmf_reg_write32,
2254 	.free_ctrl		= nvme_rdma_free_ctrl,
2255 	.submit_async_event	= nvme_rdma_submit_async_event,
2256 	.delete_ctrl		= nvme_rdma_delete_ctrl,
2257 	.get_address		= nvmf_get_address,
2258 	.stop_ctrl		= nvme_rdma_stop_ctrl,
2259 };
2260 
2261 /*
2262  * Fails a connection request if it matches an existing controller
2263  * (association) with the same tuple:
2264  * <Host NQN, Host ID, local address, remote address, remote port, SUBSYS NQN>
2265  *
2266  * if local address is not specified in the request, it will match an
2267  * existing controller with all the other parameters the same and no
2268  * local port address specified as well.
2269  *
2270  * The ports don't need to be compared as they are intrinsically
2271  * already matched by the port pointers supplied.
2272  */
2273 static bool
2274 nvme_rdma_existing_controller(struct nvmf_ctrl_options *opts)
2275 {
2276 	struct nvme_rdma_ctrl *ctrl;
2277 	bool found = false;
2278 
2279 	mutex_lock(&nvme_rdma_ctrl_mutex);
2280 	list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) {
2281 		found = nvmf_ip_options_match(&ctrl->ctrl, opts);
2282 		if (found)
2283 			break;
2284 	}
2285 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2286 
2287 	return found;
2288 }
2289 
2290 static struct nvme_ctrl *nvme_rdma_create_ctrl(struct device *dev,
2291 		struct nvmf_ctrl_options *opts)
2292 {
2293 	struct nvme_rdma_ctrl *ctrl;
2294 	int ret;
2295 	bool changed;
2296 
2297 	ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
2298 	if (!ctrl)
2299 		return ERR_PTR(-ENOMEM);
2300 	ctrl->ctrl.opts = opts;
2301 	INIT_LIST_HEAD(&ctrl->list);
2302 
2303 	if (!(opts->mask & NVMF_OPT_TRSVCID)) {
2304 		opts->trsvcid =
2305 			kstrdup(__stringify(NVME_RDMA_IP_PORT), GFP_KERNEL);
2306 		if (!opts->trsvcid) {
2307 			ret = -ENOMEM;
2308 			goto out_free_ctrl;
2309 		}
2310 		opts->mask |= NVMF_OPT_TRSVCID;
2311 	}
2312 
2313 	ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2314 			opts->traddr, opts->trsvcid, &ctrl->addr);
2315 	if (ret) {
2316 		pr_err("malformed address passed: %s:%s\n",
2317 			opts->traddr, opts->trsvcid);
2318 		goto out_free_ctrl;
2319 	}
2320 
2321 	if (opts->mask & NVMF_OPT_HOST_TRADDR) {
2322 		ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2323 			opts->host_traddr, NULL, &ctrl->src_addr);
2324 		if (ret) {
2325 			pr_err("malformed src address passed: %s\n",
2326 			       opts->host_traddr);
2327 			goto out_free_ctrl;
2328 		}
2329 	}
2330 
2331 	if (!opts->duplicate_connect && nvme_rdma_existing_controller(opts)) {
2332 		ret = -EALREADY;
2333 		goto out_free_ctrl;
2334 	}
2335 
2336 	INIT_DELAYED_WORK(&ctrl->reconnect_work,
2337 			nvme_rdma_reconnect_ctrl_work);
2338 	INIT_WORK(&ctrl->err_work, nvme_rdma_error_recovery_work);
2339 	INIT_WORK(&ctrl->ctrl.reset_work, nvme_rdma_reset_ctrl_work);
2340 
2341 	ctrl->ctrl.queue_count = opts->nr_io_queues + opts->nr_write_queues +
2342 				opts->nr_poll_queues + 1;
2343 	ctrl->ctrl.sqsize = opts->queue_size - 1;
2344 	ctrl->ctrl.kato = opts->kato;
2345 
2346 	ret = -ENOMEM;
2347 	ctrl->queues = kcalloc(ctrl->ctrl.queue_count, sizeof(*ctrl->queues),
2348 				GFP_KERNEL);
2349 	if (!ctrl->queues)
2350 		goto out_free_ctrl;
2351 
2352 	ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_rdma_ctrl_ops,
2353 				0 /* no quirks, we're perfect! */);
2354 	if (ret)
2355 		goto out_kfree_queues;
2356 
2357 	changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING);
2358 	WARN_ON_ONCE(!changed);
2359 
2360 	ret = nvme_rdma_setup_ctrl(ctrl, true);
2361 	if (ret)
2362 		goto out_uninit_ctrl;
2363 
2364 	dev_info(ctrl->ctrl.device, "new ctrl: NQN \"%s\", addr %pISpcs\n",
2365 		nvmf_ctrl_subsysnqn(&ctrl->ctrl), &ctrl->addr);
2366 
2367 	mutex_lock(&nvme_rdma_ctrl_mutex);
2368 	list_add_tail(&ctrl->list, &nvme_rdma_ctrl_list);
2369 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2370 
2371 	return &ctrl->ctrl;
2372 
2373 out_uninit_ctrl:
2374 	nvme_uninit_ctrl(&ctrl->ctrl);
2375 	nvme_put_ctrl(&ctrl->ctrl);
2376 	if (ret > 0)
2377 		ret = -EIO;
2378 	return ERR_PTR(ret);
2379 out_kfree_queues:
2380 	kfree(ctrl->queues);
2381 out_free_ctrl:
2382 	kfree(ctrl);
2383 	return ERR_PTR(ret);
2384 }
2385 
2386 static struct nvmf_transport_ops nvme_rdma_transport = {
2387 	.name		= "rdma",
2388 	.module		= THIS_MODULE,
2389 	.required_opts	= NVMF_OPT_TRADDR,
2390 	.allowed_opts	= NVMF_OPT_TRSVCID | NVMF_OPT_RECONNECT_DELAY |
2391 			  NVMF_OPT_HOST_TRADDR | NVMF_OPT_CTRL_LOSS_TMO |
2392 			  NVMF_OPT_NR_WRITE_QUEUES | NVMF_OPT_NR_POLL_QUEUES |
2393 			  NVMF_OPT_TOS,
2394 	.create_ctrl	= nvme_rdma_create_ctrl,
2395 };
2396 
2397 static void nvme_rdma_remove_one(struct ib_device *ib_device, void *client_data)
2398 {
2399 	struct nvme_rdma_ctrl *ctrl;
2400 	struct nvme_rdma_device *ndev;
2401 	bool found = false;
2402 
2403 	mutex_lock(&device_list_mutex);
2404 	list_for_each_entry(ndev, &device_list, entry) {
2405 		if (ndev->dev == ib_device) {
2406 			found = true;
2407 			break;
2408 		}
2409 	}
2410 	mutex_unlock(&device_list_mutex);
2411 
2412 	if (!found)
2413 		return;
2414 
2415 	/* Delete all controllers using this device */
2416 	mutex_lock(&nvme_rdma_ctrl_mutex);
2417 	list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) {
2418 		if (ctrl->device->dev != ib_device)
2419 			continue;
2420 		nvme_delete_ctrl(&ctrl->ctrl);
2421 	}
2422 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2423 
2424 	flush_workqueue(nvme_delete_wq);
2425 }
2426 
2427 static struct ib_client nvme_rdma_ib_client = {
2428 	.name   = "nvme_rdma",
2429 	.remove = nvme_rdma_remove_one
2430 };
2431 
2432 static int __init nvme_rdma_init_module(void)
2433 {
2434 	int ret;
2435 
2436 	ret = ib_register_client(&nvme_rdma_ib_client);
2437 	if (ret)
2438 		return ret;
2439 
2440 	ret = nvmf_register_transport(&nvme_rdma_transport);
2441 	if (ret)
2442 		goto err_unreg_client;
2443 
2444 	return 0;
2445 
2446 err_unreg_client:
2447 	ib_unregister_client(&nvme_rdma_ib_client);
2448 	return ret;
2449 }
2450 
2451 static void __exit nvme_rdma_cleanup_module(void)
2452 {
2453 	struct nvme_rdma_ctrl *ctrl;
2454 
2455 	nvmf_unregister_transport(&nvme_rdma_transport);
2456 	ib_unregister_client(&nvme_rdma_ib_client);
2457 
2458 	mutex_lock(&nvme_rdma_ctrl_mutex);
2459 	list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list)
2460 		nvme_delete_ctrl(&ctrl->ctrl);
2461 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2462 	flush_workqueue(nvme_delete_wq);
2463 }
2464 
2465 module_init(nvme_rdma_init_module);
2466 module_exit(nvme_rdma_cleanup_module);
2467 
2468 MODULE_LICENSE("GPL v2");
2469