xref: /openbmc/linux/drivers/nvme/host/rdma.c (revision ef4290e6)
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,
802 			ctrl->opts->nr_poll_queues ? HCTX_MAX_TYPES : 2,
803 			cmd_size);
804 }
805 
806 static void nvme_rdma_destroy_admin_queue(struct nvme_rdma_ctrl *ctrl)
807 {
808 	if (ctrl->async_event_sqe.data) {
809 		cancel_work_sync(&ctrl->ctrl.async_event_work);
810 		nvme_rdma_free_qe(ctrl->device->dev, &ctrl->async_event_sqe,
811 				sizeof(struct nvme_command), DMA_TO_DEVICE);
812 		ctrl->async_event_sqe.data = NULL;
813 	}
814 	nvme_rdma_free_queue(&ctrl->queues[0]);
815 }
816 
817 static int nvme_rdma_configure_admin_queue(struct nvme_rdma_ctrl *ctrl,
818 		bool new)
819 {
820 	bool pi_capable = false;
821 	int error;
822 
823 	error = nvme_rdma_alloc_queue(ctrl, 0, NVME_AQ_DEPTH);
824 	if (error)
825 		return error;
826 
827 	ctrl->device = ctrl->queues[0].device;
828 	ctrl->ctrl.numa_node = ibdev_to_node(ctrl->device->dev);
829 
830 	/* T10-PI support */
831 	if (ctrl->device->dev->attrs.kernel_cap_flags &
832 	    IBK_INTEGRITY_HANDOVER)
833 		pi_capable = true;
834 
835 	ctrl->max_fr_pages = nvme_rdma_get_max_fr_pages(ctrl->device->dev,
836 							pi_capable);
837 
838 	/*
839 	 * Bind the async event SQE DMA mapping to the admin queue lifetime.
840 	 * It's safe, since any chage in the underlying RDMA device will issue
841 	 * error recovery and queue re-creation.
842 	 */
843 	error = nvme_rdma_alloc_qe(ctrl->device->dev, &ctrl->async_event_sqe,
844 			sizeof(struct nvme_command), DMA_TO_DEVICE);
845 	if (error)
846 		goto out_free_queue;
847 
848 	if (new) {
849 		error = nvme_alloc_admin_tag_set(&ctrl->ctrl,
850 				&ctrl->admin_tag_set, &nvme_rdma_admin_mq_ops,
851 				sizeof(struct nvme_rdma_request) +
852 				NVME_RDMA_DATA_SGL_SIZE);
853 		if (error)
854 			goto out_free_async_qe;
855 
856 	}
857 
858 	error = nvme_rdma_start_queue(ctrl, 0);
859 	if (error)
860 		goto out_remove_admin_tag_set;
861 
862 	error = nvme_enable_ctrl(&ctrl->ctrl);
863 	if (error)
864 		goto out_stop_queue;
865 
866 	ctrl->ctrl.max_segments = ctrl->max_fr_pages;
867 	ctrl->ctrl.max_hw_sectors = ctrl->max_fr_pages << (ilog2(SZ_4K) - 9);
868 	if (pi_capable)
869 		ctrl->ctrl.max_integrity_segments = ctrl->max_fr_pages;
870 	else
871 		ctrl->ctrl.max_integrity_segments = 0;
872 
873 	nvme_unquiesce_admin_queue(&ctrl->ctrl);
874 
875 	error = nvme_init_ctrl_finish(&ctrl->ctrl, false);
876 	if (error)
877 		goto out_quiesce_queue;
878 
879 	return 0;
880 
881 out_quiesce_queue:
882 	nvme_quiesce_admin_queue(&ctrl->ctrl);
883 	blk_sync_queue(ctrl->ctrl.admin_q);
884 out_stop_queue:
885 	nvme_rdma_stop_queue(&ctrl->queues[0]);
886 	nvme_cancel_admin_tagset(&ctrl->ctrl);
887 out_remove_admin_tag_set:
888 	if (new)
889 		nvme_remove_admin_tag_set(&ctrl->ctrl);
890 out_free_async_qe:
891 	if (ctrl->async_event_sqe.data) {
892 		nvme_rdma_free_qe(ctrl->device->dev, &ctrl->async_event_sqe,
893 			sizeof(struct nvme_command), DMA_TO_DEVICE);
894 		ctrl->async_event_sqe.data = NULL;
895 	}
896 out_free_queue:
897 	nvme_rdma_free_queue(&ctrl->queues[0]);
898 	return error;
899 }
900 
901 static int nvme_rdma_configure_io_queues(struct nvme_rdma_ctrl *ctrl, bool new)
902 {
903 	int ret, nr_queues;
904 
905 	ret = nvme_rdma_alloc_io_queues(ctrl);
906 	if (ret)
907 		return ret;
908 
909 	if (new) {
910 		ret = nvme_rdma_alloc_tag_set(&ctrl->ctrl);
911 		if (ret)
912 			goto out_free_io_queues;
913 	}
914 
915 	/*
916 	 * Only start IO queues for which we have allocated the tagset
917 	 * and limitted it to the available queues. On reconnects, the
918 	 * queue number might have changed.
919 	 */
920 	nr_queues = min(ctrl->tag_set.nr_hw_queues + 1, ctrl->ctrl.queue_count);
921 	ret = nvme_rdma_start_io_queues(ctrl, 1, nr_queues);
922 	if (ret)
923 		goto out_cleanup_tagset;
924 
925 	if (!new) {
926 		nvme_unquiesce_io_queues(&ctrl->ctrl);
927 		if (!nvme_wait_freeze_timeout(&ctrl->ctrl, NVME_IO_TIMEOUT)) {
928 			/*
929 			 * If we timed out waiting for freeze we are likely to
930 			 * be stuck.  Fail the controller initialization just
931 			 * to be safe.
932 			 */
933 			ret = -ENODEV;
934 			goto out_wait_freeze_timed_out;
935 		}
936 		blk_mq_update_nr_hw_queues(ctrl->ctrl.tagset,
937 			ctrl->ctrl.queue_count - 1);
938 		nvme_unfreeze(&ctrl->ctrl);
939 	}
940 
941 	/*
942 	 * If the number of queues has increased (reconnect case)
943 	 * start all new queues now.
944 	 */
945 	ret = nvme_rdma_start_io_queues(ctrl, nr_queues,
946 					ctrl->tag_set.nr_hw_queues + 1);
947 	if (ret)
948 		goto out_wait_freeze_timed_out;
949 
950 	return 0;
951 
952 out_wait_freeze_timed_out:
953 	nvme_quiesce_io_queues(&ctrl->ctrl);
954 	nvme_sync_io_queues(&ctrl->ctrl);
955 	nvme_rdma_stop_io_queues(ctrl);
956 out_cleanup_tagset:
957 	nvme_cancel_tagset(&ctrl->ctrl);
958 	if (new)
959 		nvme_remove_io_tag_set(&ctrl->ctrl);
960 out_free_io_queues:
961 	nvme_rdma_free_io_queues(ctrl);
962 	return ret;
963 }
964 
965 static void nvme_rdma_teardown_admin_queue(struct nvme_rdma_ctrl *ctrl,
966 		bool remove)
967 {
968 	nvme_quiesce_admin_queue(&ctrl->ctrl);
969 	blk_sync_queue(ctrl->ctrl.admin_q);
970 	nvme_rdma_stop_queue(&ctrl->queues[0]);
971 	nvme_cancel_admin_tagset(&ctrl->ctrl);
972 	if (remove) {
973 		nvme_unquiesce_admin_queue(&ctrl->ctrl);
974 		nvme_remove_admin_tag_set(&ctrl->ctrl);
975 	}
976 	nvme_rdma_destroy_admin_queue(ctrl);
977 }
978 
979 static void nvme_rdma_teardown_io_queues(struct nvme_rdma_ctrl *ctrl,
980 		bool remove)
981 {
982 	if (ctrl->ctrl.queue_count > 1) {
983 		nvme_start_freeze(&ctrl->ctrl);
984 		nvme_quiesce_io_queues(&ctrl->ctrl);
985 		nvme_sync_io_queues(&ctrl->ctrl);
986 		nvme_rdma_stop_io_queues(ctrl);
987 		nvme_cancel_tagset(&ctrl->ctrl);
988 		if (remove) {
989 			nvme_unquiesce_io_queues(&ctrl->ctrl);
990 			nvme_remove_io_tag_set(&ctrl->ctrl);
991 		}
992 		nvme_rdma_free_io_queues(ctrl);
993 	}
994 }
995 
996 static void nvme_rdma_stop_ctrl(struct nvme_ctrl *nctrl)
997 {
998 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
999 
1000 	flush_work(&ctrl->err_work);
1001 	cancel_delayed_work_sync(&ctrl->reconnect_work);
1002 }
1003 
1004 static void nvme_rdma_free_ctrl(struct nvme_ctrl *nctrl)
1005 {
1006 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
1007 
1008 	if (list_empty(&ctrl->list))
1009 		goto free_ctrl;
1010 
1011 	mutex_lock(&nvme_rdma_ctrl_mutex);
1012 	list_del(&ctrl->list);
1013 	mutex_unlock(&nvme_rdma_ctrl_mutex);
1014 
1015 	nvmf_free_options(nctrl->opts);
1016 free_ctrl:
1017 	kfree(ctrl->queues);
1018 	kfree(ctrl);
1019 }
1020 
1021 static void nvme_rdma_reconnect_or_remove(struct nvme_rdma_ctrl *ctrl)
1022 {
1023 	/* If we are resetting/deleting then do nothing */
1024 	if (ctrl->ctrl.state != NVME_CTRL_CONNECTING) {
1025 		WARN_ON_ONCE(ctrl->ctrl.state == NVME_CTRL_NEW ||
1026 			ctrl->ctrl.state == NVME_CTRL_LIVE);
1027 		return;
1028 	}
1029 
1030 	if (nvmf_should_reconnect(&ctrl->ctrl)) {
1031 		dev_info(ctrl->ctrl.device, "Reconnecting in %d seconds...\n",
1032 			ctrl->ctrl.opts->reconnect_delay);
1033 		queue_delayed_work(nvme_wq, &ctrl->reconnect_work,
1034 				ctrl->ctrl.opts->reconnect_delay * HZ);
1035 	} else {
1036 		nvme_delete_ctrl(&ctrl->ctrl);
1037 	}
1038 }
1039 
1040 static int nvme_rdma_setup_ctrl(struct nvme_rdma_ctrl *ctrl, bool new)
1041 {
1042 	int ret;
1043 	bool changed;
1044 
1045 	ret = nvme_rdma_configure_admin_queue(ctrl, new);
1046 	if (ret)
1047 		return ret;
1048 
1049 	if (ctrl->ctrl.icdoff) {
1050 		ret = -EOPNOTSUPP;
1051 		dev_err(ctrl->ctrl.device, "icdoff is not supported!\n");
1052 		goto destroy_admin;
1053 	}
1054 
1055 	if (!(ctrl->ctrl.sgls & (1 << 2))) {
1056 		ret = -EOPNOTSUPP;
1057 		dev_err(ctrl->ctrl.device,
1058 			"Mandatory keyed sgls are not supported!\n");
1059 		goto destroy_admin;
1060 	}
1061 
1062 	if (ctrl->ctrl.opts->queue_size > ctrl->ctrl.sqsize + 1) {
1063 		dev_warn(ctrl->ctrl.device,
1064 			"queue_size %zu > ctrl sqsize %u, clamping down\n",
1065 			ctrl->ctrl.opts->queue_size, ctrl->ctrl.sqsize + 1);
1066 	}
1067 
1068 	if (ctrl->ctrl.sqsize + 1 > NVME_RDMA_MAX_QUEUE_SIZE) {
1069 		dev_warn(ctrl->ctrl.device,
1070 			"ctrl sqsize %u > max queue size %u, clamping down\n",
1071 			ctrl->ctrl.sqsize + 1, NVME_RDMA_MAX_QUEUE_SIZE);
1072 		ctrl->ctrl.sqsize = NVME_RDMA_MAX_QUEUE_SIZE - 1;
1073 	}
1074 
1075 	if (ctrl->ctrl.sqsize + 1 > ctrl->ctrl.maxcmd) {
1076 		dev_warn(ctrl->ctrl.device,
1077 			"sqsize %u > ctrl maxcmd %u, clamping down\n",
1078 			ctrl->ctrl.sqsize + 1, ctrl->ctrl.maxcmd);
1079 		ctrl->ctrl.sqsize = ctrl->ctrl.maxcmd - 1;
1080 	}
1081 
1082 	if (ctrl->ctrl.sgls & (1 << 20))
1083 		ctrl->use_inline_data = true;
1084 
1085 	if (ctrl->ctrl.queue_count > 1) {
1086 		ret = nvme_rdma_configure_io_queues(ctrl, new);
1087 		if (ret)
1088 			goto destroy_admin;
1089 	}
1090 
1091 	changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE);
1092 	if (!changed) {
1093 		/*
1094 		 * state change failure is ok if we started ctrl delete,
1095 		 * unless we're during creation of a new controller to
1096 		 * avoid races with teardown flow.
1097 		 */
1098 		WARN_ON_ONCE(ctrl->ctrl.state != NVME_CTRL_DELETING &&
1099 			     ctrl->ctrl.state != NVME_CTRL_DELETING_NOIO);
1100 		WARN_ON_ONCE(new);
1101 		ret = -EINVAL;
1102 		goto destroy_io;
1103 	}
1104 
1105 	nvme_start_ctrl(&ctrl->ctrl);
1106 	return 0;
1107 
1108 destroy_io:
1109 	if (ctrl->ctrl.queue_count > 1) {
1110 		nvme_quiesce_io_queues(&ctrl->ctrl);
1111 		nvme_sync_io_queues(&ctrl->ctrl);
1112 		nvme_rdma_stop_io_queues(ctrl);
1113 		nvme_cancel_tagset(&ctrl->ctrl);
1114 		if (new)
1115 			nvme_remove_io_tag_set(&ctrl->ctrl);
1116 		nvme_rdma_free_io_queues(ctrl);
1117 	}
1118 destroy_admin:
1119 	nvme_quiesce_admin_queue(&ctrl->ctrl);
1120 	blk_sync_queue(ctrl->ctrl.admin_q);
1121 	nvme_rdma_stop_queue(&ctrl->queues[0]);
1122 	nvme_cancel_admin_tagset(&ctrl->ctrl);
1123 	if (new)
1124 		nvme_remove_admin_tag_set(&ctrl->ctrl);
1125 	nvme_rdma_destroy_admin_queue(ctrl);
1126 	return ret;
1127 }
1128 
1129 static void nvme_rdma_reconnect_ctrl_work(struct work_struct *work)
1130 {
1131 	struct nvme_rdma_ctrl *ctrl = container_of(to_delayed_work(work),
1132 			struct nvme_rdma_ctrl, reconnect_work);
1133 
1134 	++ctrl->ctrl.nr_reconnects;
1135 
1136 	if (nvme_rdma_setup_ctrl(ctrl, false))
1137 		goto requeue;
1138 
1139 	dev_info(ctrl->ctrl.device, "Successfully reconnected (%d attempts)\n",
1140 			ctrl->ctrl.nr_reconnects);
1141 
1142 	ctrl->ctrl.nr_reconnects = 0;
1143 
1144 	return;
1145 
1146 requeue:
1147 	dev_info(ctrl->ctrl.device, "Failed reconnect attempt %d\n",
1148 			ctrl->ctrl.nr_reconnects);
1149 	nvme_rdma_reconnect_or_remove(ctrl);
1150 }
1151 
1152 static void nvme_rdma_error_recovery_work(struct work_struct *work)
1153 {
1154 	struct nvme_rdma_ctrl *ctrl = container_of(work,
1155 			struct nvme_rdma_ctrl, err_work);
1156 
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_unquiesce_io_queues(&ctrl->ctrl);
1161 	nvme_rdma_teardown_admin_queue(ctrl, false);
1162 	nvme_unquiesce_admin_queue(&ctrl->ctrl);
1163 	nvme_auth_stop(&ctrl->ctrl);
1164 
1165 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
1166 		/* state change failure is ok if we started ctrl delete */
1167 		WARN_ON_ONCE(ctrl->ctrl.state != NVME_CTRL_DELETING &&
1168 			     ctrl->ctrl.state != NVME_CTRL_DELETING_NOIO);
1169 		return;
1170 	}
1171 
1172 	nvme_rdma_reconnect_or_remove(ctrl);
1173 }
1174 
1175 static void nvme_rdma_error_recovery(struct nvme_rdma_ctrl *ctrl)
1176 {
1177 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RESETTING))
1178 		return;
1179 
1180 	dev_warn(ctrl->ctrl.device, "starting error recovery\n");
1181 	queue_work(nvme_reset_wq, &ctrl->err_work);
1182 }
1183 
1184 static void nvme_rdma_end_request(struct nvme_rdma_request *req)
1185 {
1186 	struct request *rq = blk_mq_rq_from_pdu(req);
1187 
1188 	if (!refcount_dec_and_test(&req->ref))
1189 		return;
1190 	if (!nvme_try_complete_req(rq, req->status, req->result))
1191 		nvme_rdma_complete_rq(rq);
1192 }
1193 
1194 static void nvme_rdma_wr_error(struct ib_cq *cq, struct ib_wc *wc,
1195 		const char *op)
1196 {
1197 	struct nvme_rdma_queue *queue = wc->qp->qp_context;
1198 	struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1199 
1200 	if (ctrl->ctrl.state == NVME_CTRL_LIVE)
1201 		dev_info(ctrl->ctrl.device,
1202 			     "%s for CQE 0x%p failed with status %s (%d)\n",
1203 			     op, wc->wr_cqe,
1204 			     ib_wc_status_msg(wc->status), wc->status);
1205 	nvme_rdma_error_recovery(ctrl);
1206 }
1207 
1208 static void nvme_rdma_memreg_done(struct ib_cq *cq, struct ib_wc *wc)
1209 {
1210 	if (unlikely(wc->status != IB_WC_SUCCESS))
1211 		nvme_rdma_wr_error(cq, wc, "MEMREG");
1212 }
1213 
1214 static void nvme_rdma_inv_rkey_done(struct ib_cq *cq, struct ib_wc *wc)
1215 {
1216 	struct nvme_rdma_request *req =
1217 		container_of(wc->wr_cqe, struct nvme_rdma_request, reg_cqe);
1218 
1219 	if (unlikely(wc->status != IB_WC_SUCCESS))
1220 		nvme_rdma_wr_error(cq, wc, "LOCAL_INV");
1221 	else
1222 		nvme_rdma_end_request(req);
1223 }
1224 
1225 static int nvme_rdma_inv_rkey(struct nvme_rdma_queue *queue,
1226 		struct nvme_rdma_request *req)
1227 {
1228 	struct ib_send_wr wr = {
1229 		.opcode		    = IB_WR_LOCAL_INV,
1230 		.next		    = NULL,
1231 		.num_sge	    = 0,
1232 		.send_flags	    = IB_SEND_SIGNALED,
1233 		.ex.invalidate_rkey = req->mr->rkey,
1234 	};
1235 
1236 	req->reg_cqe.done = nvme_rdma_inv_rkey_done;
1237 	wr.wr_cqe = &req->reg_cqe;
1238 
1239 	return ib_post_send(queue->qp, &wr, NULL);
1240 }
1241 
1242 static void nvme_rdma_dma_unmap_req(struct ib_device *ibdev, struct request *rq)
1243 {
1244 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1245 
1246 	if (blk_integrity_rq(rq)) {
1247 		ib_dma_unmap_sg(ibdev, req->metadata_sgl->sg_table.sgl,
1248 				req->metadata_sgl->nents, rq_dma_dir(rq));
1249 		sg_free_table_chained(&req->metadata_sgl->sg_table,
1250 				      NVME_INLINE_METADATA_SG_CNT);
1251 	}
1252 
1253 	ib_dma_unmap_sg(ibdev, req->data_sgl.sg_table.sgl, req->data_sgl.nents,
1254 			rq_dma_dir(rq));
1255 	sg_free_table_chained(&req->data_sgl.sg_table, NVME_INLINE_SG_CNT);
1256 }
1257 
1258 static void nvme_rdma_unmap_data(struct nvme_rdma_queue *queue,
1259 		struct request *rq)
1260 {
1261 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1262 	struct nvme_rdma_device *dev = queue->device;
1263 	struct ib_device *ibdev = dev->dev;
1264 	struct list_head *pool = &queue->qp->rdma_mrs;
1265 
1266 	if (!blk_rq_nr_phys_segments(rq))
1267 		return;
1268 
1269 	if (req->use_sig_mr)
1270 		pool = &queue->qp->sig_mrs;
1271 
1272 	if (req->mr) {
1273 		ib_mr_pool_put(queue->qp, pool, req->mr);
1274 		req->mr = NULL;
1275 	}
1276 
1277 	nvme_rdma_dma_unmap_req(ibdev, rq);
1278 }
1279 
1280 static int nvme_rdma_set_sg_null(struct nvme_command *c)
1281 {
1282 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1283 
1284 	sg->addr = 0;
1285 	put_unaligned_le24(0, sg->length);
1286 	put_unaligned_le32(0, sg->key);
1287 	sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1288 	return 0;
1289 }
1290 
1291 static int nvme_rdma_map_sg_inline(struct nvme_rdma_queue *queue,
1292 		struct nvme_rdma_request *req, struct nvme_command *c,
1293 		int count)
1294 {
1295 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
1296 	struct ib_sge *sge = &req->sge[1];
1297 	struct scatterlist *sgl;
1298 	u32 len = 0;
1299 	int i;
1300 
1301 	for_each_sg(req->data_sgl.sg_table.sgl, sgl, count, i) {
1302 		sge->addr = sg_dma_address(sgl);
1303 		sge->length = sg_dma_len(sgl);
1304 		sge->lkey = queue->device->pd->local_dma_lkey;
1305 		len += sge->length;
1306 		sge++;
1307 	}
1308 
1309 	sg->addr = cpu_to_le64(queue->ctrl->ctrl.icdoff);
1310 	sg->length = cpu_to_le32(len);
1311 	sg->type = (NVME_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_OFFSET;
1312 
1313 	req->num_sge += count;
1314 	return 0;
1315 }
1316 
1317 static int nvme_rdma_map_sg_single(struct nvme_rdma_queue *queue,
1318 		struct nvme_rdma_request *req, struct nvme_command *c)
1319 {
1320 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1321 
1322 	sg->addr = cpu_to_le64(sg_dma_address(req->data_sgl.sg_table.sgl));
1323 	put_unaligned_le24(sg_dma_len(req->data_sgl.sg_table.sgl), sg->length);
1324 	put_unaligned_le32(queue->device->pd->unsafe_global_rkey, sg->key);
1325 	sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1326 	return 0;
1327 }
1328 
1329 static int nvme_rdma_map_sg_fr(struct nvme_rdma_queue *queue,
1330 		struct nvme_rdma_request *req, struct nvme_command *c,
1331 		int count)
1332 {
1333 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1334 	int nr;
1335 
1336 	req->mr = ib_mr_pool_get(queue->qp, &queue->qp->rdma_mrs);
1337 	if (WARN_ON_ONCE(!req->mr))
1338 		return -EAGAIN;
1339 
1340 	/*
1341 	 * Align the MR to a 4K page size to match the ctrl page size and
1342 	 * the block virtual boundary.
1343 	 */
1344 	nr = ib_map_mr_sg(req->mr, req->data_sgl.sg_table.sgl, count, NULL,
1345 			  SZ_4K);
1346 	if (unlikely(nr < count)) {
1347 		ib_mr_pool_put(queue->qp, &queue->qp->rdma_mrs, req->mr);
1348 		req->mr = NULL;
1349 		if (nr < 0)
1350 			return nr;
1351 		return -EINVAL;
1352 	}
1353 
1354 	ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1355 
1356 	req->reg_cqe.done = nvme_rdma_memreg_done;
1357 	memset(&req->reg_wr, 0, sizeof(req->reg_wr));
1358 	req->reg_wr.wr.opcode = IB_WR_REG_MR;
1359 	req->reg_wr.wr.wr_cqe = &req->reg_cqe;
1360 	req->reg_wr.wr.num_sge = 0;
1361 	req->reg_wr.mr = req->mr;
1362 	req->reg_wr.key = req->mr->rkey;
1363 	req->reg_wr.access = IB_ACCESS_LOCAL_WRITE |
1364 			     IB_ACCESS_REMOTE_READ |
1365 			     IB_ACCESS_REMOTE_WRITE;
1366 
1367 	sg->addr = cpu_to_le64(req->mr->iova);
1368 	put_unaligned_le24(req->mr->length, sg->length);
1369 	put_unaligned_le32(req->mr->rkey, sg->key);
1370 	sg->type = (NVME_KEY_SGL_FMT_DATA_DESC << 4) |
1371 			NVME_SGL_FMT_INVALIDATE;
1372 
1373 	return 0;
1374 }
1375 
1376 static void nvme_rdma_set_sig_domain(struct blk_integrity *bi,
1377 		struct nvme_command *cmd, struct ib_sig_domain *domain,
1378 		u16 control, u8 pi_type)
1379 {
1380 	domain->sig_type = IB_SIG_TYPE_T10_DIF;
1381 	domain->sig.dif.bg_type = IB_T10DIF_CRC;
1382 	domain->sig.dif.pi_interval = 1 << bi->interval_exp;
1383 	domain->sig.dif.ref_tag = le32_to_cpu(cmd->rw.reftag);
1384 	if (control & NVME_RW_PRINFO_PRCHK_REF)
1385 		domain->sig.dif.ref_remap = true;
1386 
1387 	domain->sig.dif.app_tag = le16_to_cpu(cmd->rw.apptag);
1388 	domain->sig.dif.apptag_check_mask = le16_to_cpu(cmd->rw.appmask);
1389 	domain->sig.dif.app_escape = true;
1390 	if (pi_type == NVME_NS_DPS_PI_TYPE3)
1391 		domain->sig.dif.ref_escape = true;
1392 }
1393 
1394 static void nvme_rdma_set_sig_attrs(struct blk_integrity *bi,
1395 		struct nvme_command *cmd, struct ib_sig_attrs *sig_attrs,
1396 		u8 pi_type)
1397 {
1398 	u16 control = le16_to_cpu(cmd->rw.control);
1399 
1400 	memset(sig_attrs, 0, sizeof(*sig_attrs));
1401 	if (control & NVME_RW_PRINFO_PRACT) {
1402 		/* for WRITE_INSERT/READ_STRIP no memory domain */
1403 		sig_attrs->mem.sig_type = IB_SIG_TYPE_NONE;
1404 		nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->wire, control,
1405 					 pi_type);
1406 		/* Clear the PRACT bit since HCA will generate/verify the PI */
1407 		control &= ~NVME_RW_PRINFO_PRACT;
1408 		cmd->rw.control = cpu_to_le16(control);
1409 	} else {
1410 		/* for WRITE_PASS/READ_PASS both wire/memory domains exist */
1411 		nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->wire, control,
1412 					 pi_type);
1413 		nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->mem, control,
1414 					 pi_type);
1415 	}
1416 }
1417 
1418 static void nvme_rdma_set_prot_checks(struct nvme_command *cmd, u8 *mask)
1419 {
1420 	*mask = 0;
1421 	if (le16_to_cpu(cmd->rw.control) & NVME_RW_PRINFO_PRCHK_REF)
1422 		*mask |= IB_SIG_CHECK_REFTAG;
1423 	if (le16_to_cpu(cmd->rw.control) & NVME_RW_PRINFO_PRCHK_GUARD)
1424 		*mask |= IB_SIG_CHECK_GUARD;
1425 }
1426 
1427 static void nvme_rdma_sig_done(struct ib_cq *cq, struct ib_wc *wc)
1428 {
1429 	if (unlikely(wc->status != IB_WC_SUCCESS))
1430 		nvme_rdma_wr_error(cq, wc, "SIG");
1431 }
1432 
1433 static int nvme_rdma_map_sg_pi(struct nvme_rdma_queue *queue,
1434 		struct nvme_rdma_request *req, struct nvme_command *c,
1435 		int count, int pi_count)
1436 {
1437 	struct nvme_rdma_sgl *sgl = &req->data_sgl;
1438 	struct ib_reg_wr *wr = &req->reg_wr;
1439 	struct request *rq = blk_mq_rq_from_pdu(req);
1440 	struct nvme_ns *ns = rq->q->queuedata;
1441 	struct bio *bio = rq->bio;
1442 	struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1443 	int nr;
1444 
1445 	req->mr = ib_mr_pool_get(queue->qp, &queue->qp->sig_mrs);
1446 	if (WARN_ON_ONCE(!req->mr))
1447 		return -EAGAIN;
1448 
1449 	nr = ib_map_mr_sg_pi(req->mr, sgl->sg_table.sgl, count, NULL,
1450 			     req->metadata_sgl->sg_table.sgl, pi_count, NULL,
1451 			     SZ_4K);
1452 	if (unlikely(nr))
1453 		goto mr_put;
1454 
1455 	nvme_rdma_set_sig_attrs(blk_get_integrity(bio->bi_bdev->bd_disk), c,
1456 				req->mr->sig_attrs, ns->pi_type);
1457 	nvme_rdma_set_prot_checks(c, &req->mr->sig_attrs->check_mask);
1458 
1459 	ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1460 
1461 	req->reg_cqe.done = nvme_rdma_sig_done;
1462 	memset(wr, 0, sizeof(*wr));
1463 	wr->wr.opcode = IB_WR_REG_MR_INTEGRITY;
1464 	wr->wr.wr_cqe = &req->reg_cqe;
1465 	wr->wr.num_sge = 0;
1466 	wr->wr.send_flags = 0;
1467 	wr->mr = req->mr;
1468 	wr->key = req->mr->rkey;
1469 	wr->access = IB_ACCESS_LOCAL_WRITE |
1470 		     IB_ACCESS_REMOTE_READ |
1471 		     IB_ACCESS_REMOTE_WRITE;
1472 
1473 	sg->addr = cpu_to_le64(req->mr->iova);
1474 	put_unaligned_le24(req->mr->length, sg->length);
1475 	put_unaligned_le32(req->mr->rkey, sg->key);
1476 	sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1477 
1478 	return 0;
1479 
1480 mr_put:
1481 	ib_mr_pool_put(queue->qp, &queue->qp->sig_mrs, req->mr);
1482 	req->mr = NULL;
1483 	if (nr < 0)
1484 		return nr;
1485 	return -EINVAL;
1486 }
1487 
1488 static int nvme_rdma_dma_map_req(struct ib_device *ibdev, struct request *rq,
1489 		int *count, int *pi_count)
1490 {
1491 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1492 	int ret;
1493 
1494 	req->data_sgl.sg_table.sgl = (struct scatterlist *)(req + 1);
1495 	ret = sg_alloc_table_chained(&req->data_sgl.sg_table,
1496 			blk_rq_nr_phys_segments(rq), req->data_sgl.sg_table.sgl,
1497 			NVME_INLINE_SG_CNT);
1498 	if (ret)
1499 		return -ENOMEM;
1500 
1501 	req->data_sgl.nents = blk_rq_map_sg(rq->q, rq,
1502 					    req->data_sgl.sg_table.sgl);
1503 
1504 	*count = ib_dma_map_sg(ibdev, req->data_sgl.sg_table.sgl,
1505 			       req->data_sgl.nents, rq_dma_dir(rq));
1506 	if (unlikely(*count <= 0)) {
1507 		ret = -EIO;
1508 		goto out_free_table;
1509 	}
1510 
1511 	if (blk_integrity_rq(rq)) {
1512 		req->metadata_sgl->sg_table.sgl =
1513 			(struct scatterlist *)(req->metadata_sgl + 1);
1514 		ret = sg_alloc_table_chained(&req->metadata_sgl->sg_table,
1515 				blk_rq_count_integrity_sg(rq->q, rq->bio),
1516 				req->metadata_sgl->sg_table.sgl,
1517 				NVME_INLINE_METADATA_SG_CNT);
1518 		if (unlikely(ret)) {
1519 			ret = -ENOMEM;
1520 			goto out_unmap_sg;
1521 		}
1522 
1523 		req->metadata_sgl->nents = blk_rq_map_integrity_sg(rq->q,
1524 				rq->bio, req->metadata_sgl->sg_table.sgl);
1525 		*pi_count = ib_dma_map_sg(ibdev,
1526 					  req->metadata_sgl->sg_table.sgl,
1527 					  req->metadata_sgl->nents,
1528 					  rq_dma_dir(rq));
1529 		if (unlikely(*pi_count <= 0)) {
1530 			ret = -EIO;
1531 			goto out_free_pi_table;
1532 		}
1533 	}
1534 
1535 	return 0;
1536 
1537 out_free_pi_table:
1538 	sg_free_table_chained(&req->metadata_sgl->sg_table,
1539 			      NVME_INLINE_METADATA_SG_CNT);
1540 out_unmap_sg:
1541 	ib_dma_unmap_sg(ibdev, req->data_sgl.sg_table.sgl, req->data_sgl.nents,
1542 			rq_dma_dir(rq));
1543 out_free_table:
1544 	sg_free_table_chained(&req->data_sgl.sg_table, NVME_INLINE_SG_CNT);
1545 	return ret;
1546 }
1547 
1548 static int nvme_rdma_map_data(struct nvme_rdma_queue *queue,
1549 		struct request *rq, struct nvme_command *c)
1550 {
1551 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1552 	struct nvme_rdma_device *dev = queue->device;
1553 	struct ib_device *ibdev = dev->dev;
1554 	int pi_count = 0;
1555 	int count, ret;
1556 
1557 	req->num_sge = 1;
1558 	refcount_set(&req->ref, 2); /* send and recv completions */
1559 
1560 	c->common.flags |= NVME_CMD_SGL_METABUF;
1561 
1562 	if (!blk_rq_nr_phys_segments(rq))
1563 		return nvme_rdma_set_sg_null(c);
1564 
1565 	ret = nvme_rdma_dma_map_req(ibdev, rq, &count, &pi_count);
1566 	if (unlikely(ret))
1567 		return ret;
1568 
1569 	if (req->use_sig_mr) {
1570 		ret = nvme_rdma_map_sg_pi(queue, req, c, count, pi_count);
1571 		goto out;
1572 	}
1573 
1574 	if (count <= dev->num_inline_segments) {
1575 		if (rq_data_dir(rq) == WRITE && nvme_rdma_queue_idx(queue) &&
1576 		    queue->ctrl->use_inline_data &&
1577 		    blk_rq_payload_bytes(rq) <=
1578 				nvme_rdma_inline_data_size(queue)) {
1579 			ret = nvme_rdma_map_sg_inline(queue, req, c, count);
1580 			goto out;
1581 		}
1582 
1583 		if (count == 1 && dev->pd->flags & IB_PD_UNSAFE_GLOBAL_RKEY) {
1584 			ret = nvme_rdma_map_sg_single(queue, req, c);
1585 			goto out;
1586 		}
1587 	}
1588 
1589 	ret = nvme_rdma_map_sg_fr(queue, req, c, count);
1590 out:
1591 	if (unlikely(ret))
1592 		goto out_dma_unmap_req;
1593 
1594 	return 0;
1595 
1596 out_dma_unmap_req:
1597 	nvme_rdma_dma_unmap_req(ibdev, rq);
1598 	return ret;
1599 }
1600 
1601 static void nvme_rdma_send_done(struct ib_cq *cq, struct ib_wc *wc)
1602 {
1603 	struct nvme_rdma_qe *qe =
1604 		container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe);
1605 	struct nvme_rdma_request *req =
1606 		container_of(qe, struct nvme_rdma_request, sqe);
1607 
1608 	if (unlikely(wc->status != IB_WC_SUCCESS))
1609 		nvme_rdma_wr_error(cq, wc, "SEND");
1610 	else
1611 		nvme_rdma_end_request(req);
1612 }
1613 
1614 static int nvme_rdma_post_send(struct nvme_rdma_queue *queue,
1615 		struct nvme_rdma_qe *qe, struct ib_sge *sge, u32 num_sge,
1616 		struct ib_send_wr *first)
1617 {
1618 	struct ib_send_wr wr;
1619 	int ret;
1620 
1621 	sge->addr   = qe->dma;
1622 	sge->length = sizeof(struct nvme_command);
1623 	sge->lkey   = queue->device->pd->local_dma_lkey;
1624 
1625 	wr.next       = NULL;
1626 	wr.wr_cqe     = &qe->cqe;
1627 	wr.sg_list    = sge;
1628 	wr.num_sge    = num_sge;
1629 	wr.opcode     = IB_WR_SEND;
1630 	wr.send_flags = IB_SEND_SIGNALED;
1631 
1632 	if (first)
1633 		first->next = &wr;
1634 	else
1635 		first = &wr;
1636 
1637 	ret = ib_post_send(queue->qp, first, NULL);
1638 	if (unlikely(ret)) {
1639 		dev_err(queue->ctrl->ctrl.device,
1640 			     "%s failed with error code %d\n", __func__, ret);
1641 	}
1642 	return ret;
1643 }
1644 
1645 static int nvme_rdma_post_recv(struct nvme_rdma_queue *queue,
1646 		struct nvme_rdma_qe *qe)
1647 {
1648 	struct ib_recv_wr wr;
1649 	struct ib_sge list;
1650 	int ret;
1651 
1652 	list.addr   = qe->dma;
1653 	list.length = sizeof(struct nvme_completion);
1654 	list.lkey   = queue->device->pd->local_dma_lkey;
1655 
1656 	qe->cqe.done = nvme_rdma_recv_done;
1657 
1658 	wr.next     = NULL;
1659 	wr.wr_cqe   = &qe->cqe;
1660 	wr.sg_list  = &list;
1661 	wr.num_sge  = 1;
1662 
1663 	ret = ib_post_recv(queue->qp, &wr, NULL);
1664 	if (unlikely(ret)) {
1665 		dev_err(queue->ctrl->ctrl.device,
1666 			"%s failed with error code %d\n", __func__, ret);
1667 	}
1668 	return ret;
1669 }
1670 
1671 static struct blk_mq_tags *nvme_rdma_tagset(struct nvme_rdma_queue *queue)
1672 {
1673 	u32 queue_idx = nvme_rdma_queue_idx(queue);
1674 
1675 	if (queue_idx == 0)
1676 		return queue->ctrl->admin_tag_set.tags[queue_idx];
1677 	return queue->ctrl->tag_set.tags[queue_idx - 1];
1678 }
1679 
1680 static void nvme_rdma_async_done(struct ib_cq *cq, struct ib_wc *wc)
1681 {
1682 	if (unlikely(wc->status != IB_WC_SUCCESS))
1683 		nvme_rdma_wr_error(cq, wc, "ASYNC");
1684 }
1685 
1686 static void nvme_rdma_submit_async_event(struct nvme_ctrl *arg)
1687 {
1688 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(arg);
1689 	struct nvme_rdma_queue *queue = &ctrl->queues[0];
1690 	struct ib_device *dev = queue->device->dev;
1691 	struct nvme_rdma_qe *sqe = &ctrl->async_event_sqe;
1692 	struct nvme_command *cmd = sqe->data;
1693 	struct ib_sge sge;
1694 	int ret;
1695 
1696 	ib_dma_sync_single_for_cpu(dev, sqe->dma, sizeof(*cmd), DMA_TO_DEVICE);
1697 
1698 	memset(cmd, 0, sizeof(*cmd));
1699 	cmd->common.opcode = nvme_admin_async_event;
1700 	cmd->common.command_id = NVME_AQ_BLK_MQ_DEPTH;
1701 	cmd->common.flags |= NVME_CMD_SGL_METABUF;
1702 	nvme_rdma_set_sg_null(cmd);
1703 
1704 	sqe->cqe.done = nvme_rdma_async_done;
1705 
1706 	ib_dma_sync_single_for_device(dev, sqe->dma, sizeof(*cmd),
1707 			DMA_TO_DEVICE);
1708 
1709 	ret = nvme_rdma_post_send(queue, sqe, &sge, 1, NULL);
1710 	WARN_ON_ONCE(ret);
1711 }
1712 
1713 static void nvme_rdma_process_nvme_rsp(struct nvme_rdma_queue *queue,
1714 		struct nvme_completion *cqe, struct ib_wc *wc)
1715 {
1716 	struct request *rq;
1717 	struct nvme_rdma_request *req;
1718 
1719 	rq = nvme_find_rq(nvme_rdma_tagset(queue), cqe->command_id);
1720 	if (!rq) {
1721 		dev_err(queue->ctrl->ctrl.device,
1722 			"got bad command_id %#x on QP %#x\n",
1723 			cqe->command_id, queue->qp->qp_num);
1724 		nvme_rdma_error_recovery(queue->ctrl);
1725 		return;
1726 	}
1727 	req = blk_mq_rq_to_pdu(rq);
1728 
1729 	req->status = cqe->status;
1730 	req->result = cqe->result;
1731 
1732 	if (wc->wc_flags & IB_WC_WITH_INVALIDATE) {
1733 		if (unlikely(!req->mr ||
1734 			     wc->ex.invalidate_rkey != req->mr->rkey)) {
1735 			dev_err(queue->ctrl->ctrl.device,
1736 				"Bogus remote invalidation for rkey %#x\n",
1737 				req->mr ? req->mr->rkey : 0);
1738 			nvme_rdma_error_recovery(queue->ctrl);
1739 		}
1740 	} else if (req->mr) {
1741 		int ret;
1742 
1743 		ret = nvme_rdma_inv_rkey(queue, req);
1744 		if (unlikely(ret < 0)) {
1745 			dev_err(queue->ctrl->ctrl.device,
1746 				"Queueing INV WR for rkey %#x failed (%d)\n",
1747 				req->mr->rkey, ret);
1748 			nvme_rdma_error_recovery(queue->ctrl);
1749 		}
1750 		/* the local invalidation completion will end the request */
1751 		return;
1752 	}
1753 
1754 	nvme_rdma_end_request(req);
1755 }
1756 
1757 static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc)
1758 {
1759 	struct nvme_rdma_qe *qe =
1760 		container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe);
1761 	struct nvme_rdma_queue *queue = wc->qp->qp_context;
1762 	struct ib_device *ibdev = queue->device->dev;
1763 	struct nvme_completion *cqe = qe->data;
1764 	const size_t len = sizeof(struct nvme_completion);
1765 
1766 	if (unlikely(wc->status != IB_WC_SUCCESS)) {
1767 		nvme_rdma_wr_error(cq, wc, "RECV");
1768 		return;
1769 	}
1770 
1771 	/* sanity checking for received data length */
1772 	if (unlikely(wc->byte_len < len)) {
1773 		dev_err(queue->ctrl->ctrl.device,
1774 			"Unexpected nvme completion length(%d)\n", wc->byte_len);
1775 		nvme_rdma_error_recovery(queue->ctrl);
1776 		return;
1777 	}
1778 
1779 	ib_dma_sync_single_for_cpu(ibdev, qe->dma, len, DMA_FROM_DEVICE);
1780 	/*
1781 	 * AEN requests are special as they don't time out and can
1782 	 * survive any kind of queue freeze and often don't respond to
1783 	 * aborts.  We don't even bother to allocate a struct request
1784 	 * for them but rather special case them here.
1785 	 */
1786 	if (unlikely(nvme_is_aen_req(nvme_rdma_queue_idx(queue),
1787 				     cqe->command_id)))
1788 		nvme_complete_async_event(&queue->ctrl->ctrl, cqe->status,
1789 				&cqe->result);
1790 	else
1791 		nvme_rdma_process_nvme_rsp(queue, cqe, wc);
1792 	ib_dma_sync_single_for_device(ibdev, qe->dma, len, DMA_FROM_DEVICE);
1793 
1794 	nvme_rdma_post_recv(queue, qe);
1795 }
1796 
1797 static int nvme_rdma_conn_established(struct nvme_rdma_queue *queue)
1798 {
1799 	int ret, i;
1800 
1801 	for (i = 0; i < queue->queue_size; i++) {
1802 		ret = nvme_rdma_post_recv(queue, &queue->rsp_ring[i]);
1803 		if (ret)
1804 			return ret;
1805 	}
1806 
1807 	return 0;
1808 }
1809 
1810 static int nvme_rdma_conn_rejected(struct nvme_rdma_queue *queue,
1811 		struct rdma_cm_event *ev)
1812 {
1813 	struct rdma_cm_id *cm_id = queue->cm_id;
1814 	int status = ev->status;
1815 	const char *rej_msg;
1816 	const struct nvme_rdma_cm_rej *rej_data;
1817 	u8 rej_data_len;
1818 
1819 	rej_msg = rdma_reject_msg(cm_id, status);
1820 	rej_data = rdma_consumer_reject_data(cm_id, ev, &rej_data_len);
1821 
1822 	if (rej_data && rej_data_len >= sizeof(u16)) {
1823 		u16 sts = le16_to_cpu(rej_data->sts);
1824 
1825 		dev_err(queue->ctrl->ctrl.device,
1826 		      "Connect rejected: status %d (%s) nvme status %d (%s).\n",
1827 		      status, rej_msg, sts, nvme_rdma_cm_msg(sts));
1828 	} else {
1829 		dev_err(queue->ctrl->ctrl.device,
1830 			"Connect rejected: status %d (%s).\n", status, rej_msg);
1831 	}
1832 
1833 	return -ECONNRESET;
1834 }
1835 
1836 static int nvme_rdma_addr_resolved(struct nvme_rdma_queue *queue)
1837 {
1838 	struct nvme_ctrl *ctrl = &queue->ctrl->ctrl;
1839 	int ret;
1840 
1841 	ret = nvme_rdma_create_queue_ib(queue);
1842 	if (ret)
1843 		return ret;
1844 
1845 	if (ctrl->opts->tos >= 0)
1846 		rdma_set_service_type(queue->cm_id, ctrl->opts->tos);
1847 	ret = rdma_resolve_route(queue->cm_id, NVME_RDMA_CM_TIMEOUT_MS);
1848 	if (ret) {
1849 		dev_err(ctrl->device, "rdma_resolve_route failed (%d).\n",
1850 			queue->cm_error);
1851 		goto out_destroy_queue;
1852 	}
1853 
1854 	return 0;
1855 
1856 out_destroy_queue:
1857 	nvme_rdma_destroy_queue_ib(queue);
1858 	return ret;
1859 }
1860 
1861 static int nvme_rdma_route_resolved(struct nvme_rdma_queue *queue)
1862 {
1863 	struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1864 	struct rdma_conn_param param = { };
1865 	struct nvme_rdma_cm_req priv = { };
1866 	int ret;
1867 
1868 	param.qp_num = queue->qp->qp_num;
1869 	param.flow_control = 1;
1870 
1871 	param.responder_resources = queue->device->dev->attrs.max_qp_rd_atom;
1872 	/* maximum retry count */
1873 	param.retry_count = 7;
1874 	param.rnr_retry_count = 7;
1875 	param.private_data = &priv;
1876 	param.private_data_len = sizeof(priv);
1877 
1878 	priv.recfmt = cpu_to_le16(NVME_RDMA_CM_FMT_1_0);
1879 	priv.qid = cpu_to_le16(nvme_rdma_queue_idx(queue));
1880 	/*
1881 	 * set the admin queue depth to the minimum size
1882 	 * specified by the Fabrics standard.
1883 	 */
1884 	if (priv.qid == 0) {
1885 		priv.hrqsize = cpu_to_le16(NVME_AQ_DEPTH);
1886 		priv.hsqsize = cpu_to_le16(NVME_AQ_DEPTH - 1);
1887 	} else {
1888 		/*
1889 		 * current interpretation of the fabrics spec
1890 		 * is at minimum you make hrqsize sqsize+1, or a
1891 		 * 1's based representation of sqsize.
1892 		 */
1893 		priv.hrqsize = cpu_to_le16(queue->queue_size);
1894 		priv.hsqsize = cpu_to_le16(queue->ctrl->ctrl.sqsize);
1895 	}
1896 
1897 	ret = rdma_connect_locked(queue->cm_id, &param);
1898 	if (ret) {
1899 		dev_err(ctrl->ctrl.device,
1900 			"rdma_connect_locked failed (%d).\n", ret);
1901 		return ret;
1902 	}
1903 
1904 	return 0;
1905 }
1906 
1907 static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id,
1908 		struct rdma_cm_event *ev)
1909 {
1910 	struct nvme_rdma_queue *queue = cm_id->context;
1911 	int cm_error = 0;
1912 
1913 	dev_dbg(queue->ctrl->ctrl.device, "%s (%d): status %d id %p\n",
1914 		rdma_event_msg(ev->event), ev->event,
1915 		ev->status, cm_id);
1916 
1917 	switch (ev->event) {
1918 	case RDMA_CM_EVENT_ADDR_RESOLVED:
1919 		cm_error = nvme_rdma_addr_resolved(queue);
1920 		break;
1921 	case RDMA_CM_EVENT_ROUTE_RESOLVED:
1922 		cm_error = nvme_rdma_route_resolved(queue);
1923 		break;
1924 	case RDMA_CM_EVENT_ESTABLISHED:
1925 		queue->cm_error = nvme_rdma_conn_established(queue);
1926 		/* complete cm_done regardless of success/failure */
1927 		complete(&queue->cm_done);
1928 		return 0;
1929 	case RDMA_CM_EVENT_REJECTED:
1930 		cm_error = nvme_rdma_conn_rejected(queue, ev);
1931 		break;
1932 	case RDMA_CM_EVENT_ROUTE_ERROR:
1933 	case RDMA_CM_EVENT_CONNECT_ERROR:
1934 	case RDMA_CM_EVENT_UNREACHABLE:
1935 	case RDMA_CM_EVENT_ADDR_ERROR:
1936 		dev_dbg(queue->ctrl->ctrl.device,
1937 			"CM error event %d\n", ev->event);
1938 		cm_error = -ECONNRESET;
1939 		break;
1940 	case RDMA_CM_EVENT_DISCONNECTED:
1941 	case RDMA_CM_EVENT_ADDR_CHANGE:
1942 	case RDMA_CM_EVENT_TIMEWAIT_EXIT:
1943 		dev_dbg(queue->ctrl->ctrl.device,
1944 			"disconnect received - connection closed\n");
1945 		nvme_rdma_error_recovery(queue->ctrl);
1946 		break;
1947 	case RDMA_CM_EVENT_DEVICE_REMOVAL:
1948 		/* device removal is handled via the ib_client API */
1949 		break;
1950 	default:
1951 		dev_err(queue->ctrl->ctrl.device,
1952 			"Unexpected RDMA CM event (%d)\n", ev->event);
1953 		nvme_rdma_error_recovery(queue->ctrl);
1954 		break;
1955 	}
1956 
1957 	if (cm_error) {
1958 		queue->cm_error = cm_error;
1959 		complete(&queue->cm_done);
1960 	}
1961 
1962 	return 0;
1963 }
1964 
1965 static void nvme_rdma_complete_timed_out(struct request *rq)
1966 {
1967 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1968 	struct nvme_rdma_queue *queue = req->queue;
1969 
1970 	nvme_rdma_stop_queue(queue);
1971 	nvmf_complete_timed_out_request(rq);
1972 }
1973 
1974 static enum blk_eh_timer_return nvme_rdma_timeout(struct request *rq)
1975 {
1976 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1977 	struct nvme_rdma_queue *queue = req->queue;
1978 	struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1979 
1980 	dev_warn(ctrl->ctrl.device, "I/O %d QID %d timeout\n",
1981 		 rq->tag, nvme_rdma_queue_idx(queue));
1982 
1983 	if (ctrl->ctrl.state != NVME_CTRL_LIVE) {
1984 		/*
1985 		 * If we are resetting, connecting or deleting we should
1986 		 * complete immediately because we may block controller
1987 		 * teardown or setup sequence
1988 		 * - ctrl disable/shutdown fabrics requests
1989 		 * - connect requests
1990 		 * - initialization admin requests
1991 		 * - I/O requests that entered after unquiescing and
1992 		 *   the controller stopped responding
1993 		 *
1994 		 * All other requests should be cancelled by the error
1995 		 * recovery work, so it's fine that we fail it here.
1996 		 */
1997 		nvme_rdma_complete_timed_out(rq);
1998 		return BLK_EH_DONE;
1999 	}
2000 
2001 	/*
2002 	 * LIVE state should trigger the normal error recovery which will
2003 	 * handle completing this request.
2004 	 */
2005 	nvme_rdma_error_recovery(ctrl);
2006 	return BLK_EH_RESET_TIMER;
2007 }
2008 
2009 static blk_status_t nvme_rdma_queue_rq(struct blk_mq_hw_ctx *hctx,
2010 		const struct blk_mq_queue_data *bd)
2011 {
2012 	struct nvme_ns *ns = hctx->queue->queuedata;
2013 	struct nvme_rdma_queue *queue = hctx->driver_data;
2014 	struct request *rq = bd->rq;
2015 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2016 	struct nvme_rdma_qe *sqe = &req->sqe;
2017 	struct nvme_command *c = nvme_req(rq)->cmd;
2018 	struct ib_device *dev;
2019 	bool queue_ready = test_bit(NVME_RDMA_Q_LIVE, &queue->flags);
2020 	blk_status_t ret;
2021 	int err;
2022 
2023 	WARN_ON_ONCE(rq->tag < 0);
2024 
2025 	if (!nvme_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
2026 		return nvme_fail_nonready_command(&queue->ctrl->ctrl, rq);
2027 
2028 	dev = queue->device->dev;
2029 
2030 	req->sqe.dma = ib_dma_map_single(dev, req->sqe.data,
2031 					 sizeof(struct nvme_command),
2032 					 DMA_TO_DEVICE);
2033 	err = ib_dma_mapping_error(dev, req->sqe.dma);
2034 	if (unlikely(err))
2035 		return BLK_STS_RESOURCE;
2036 
2037 	ib_dma_sync_single_for_cpu(dev, sqe->dma,
2038 			sizeof(struct nvme_command), DMA_TO_DEVICE);
2039 
2040 	ret = nvme_setup_cmd(ns, rq);
2041 	if (ret)
2042 		goto unmap_qe;
2043 
2044 	nvme_start_request(rq);
2045 
2046 	if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
2047 	    queue->pi_support &&
2048 	    (c->common.opcode == nvme_cmd_write ||
2049 	     c->common.opcode == nvme_cmd_read) &&
2050 	    nvme_ns_has_pi(ns))
2051 		req->use_sig_mr = true;
2052 	else
2053 		req->use_sig_mr = false;
2054 
2055 	err = nvme_rdma_map_data(queue, rq, c);
2056 	if (unlikely(err < 0)) {
2057 		dev_err(queue->ctrl->ctrl.device,
2058 			     "Failed to map data (%d)\n", err);
2059 		goto err;
2060 	}
2061 
2062 	sqe->cqe.done = nvme_rdma_send_done;
2063 
2064 	ib_dma_sync_single_for_device(dev, sqe->dma,
2065 			sizeof(struct nvme_command), DMA_TO_DEVICE);
2066 
2067 	err = nvme_rdma_post_send(queue, sqe, req->sge, req->num_sge,
2068 			req->mr ? &req->reg_wr.wr : NULL);
2069 	if (unlikely(err))
2070 		goto err_unmap;
2071 
2072 	return BLK_STS_OK;
2073 
2074 err_unmap:
2075 	nvme_rdma_unmap_data(queue, rq);
2076 err:
2077 	if (err == -EIO)
2078 		ret = nvme_host_path_error(rq);
2079 	else if (err == -ENOMEM || err == -EAGAIN)
2080 		ret = BLK_STS_RESOURCE;
2081 	else
2082 		ret = BLK_STS_IOERR;
2083 	nvme_cleanup_cmd(rq);
2084 unmap_qe:
2085 	ib_dma_unmap_single(dev, req->sqe.dma, sizeof(struct nvme_command),
2086 			    DMA_TO_DEVICE);
2087 	return ret;
2088 }
2089 
2090 static int nvme_rdma_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
2091 {
2092 	struct nvme_rdma_queue *queue = hctx->driver_data;
2093 
2094 	return ib_process_cq_direct(queue->ib_cq, -1);
2095 }
2096 
2097 static void nvme_rdma_check_pi_status(struct nvme_rdma_request *req)
2098 {
2099 	struct request *rq = blk_mq_rq_from_pdu(req);
2100 	struct ib_mr_status mr_status;
2101 	int ret;
2102 
2103 	ret = ib_check_mr_status(req->mr, IB_MR_CHECK_SIG_STATUS, &mr_status);
2104 	if (ret) {
2105 		pr_err("ib_check_mr_status failed, ret %d\n", ret);
2106 		nvme_req(rq)->status = NVME_SC_INVALID_PI;
2107 		return;
2108 	}
2109 
2110 	if (mr_status.fail_status & IB_MR_CHECK_SIG_STATUS) {
2111 		switch (mr_status.sig_err.err_type) {
2112 		case IB_SIG_BAD_GUARD:
2113 			nvme_req(rq)->status = NVME_SC_GUARD_CHECK;
2114 			break;
2115 		case IB_SIG_BAD_REFTAG:
2116 			nvme_req(rq)->status = NVME_SC_REFTAG_CHECK;
2117 			break;
2118 		case IB_SIG_BAD_APPTAG:
2119 			nvme_req(rq)->status = NVME_SC_APPTAG_CHECK;
2120 			break;
2121 		}
2122 		pr_err("PI error found type %d expected 0x%x vs actual 0x%x\n",
2123 		       mr_status.sig_err.err_type, mr_status.sig_err.expected,
2124 		       mr_status.sig_err.actual);
2125 	}
2126 }
2127 
2128 static void nvme_rdma_complete_rq(struct request *rq)
2129 {
2130 	struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2131 	struct nvme_rdma_queue *queue = req->queue;
2132 	struct ib_device *ibdev = queue->device->dev;
2133 
2134 	if (req->use_sig_mr)
2135 		nvme_rdma_check_pi_status(req);
2136 
2137 	nvme_rdma_unmap_data(queue, rq);
2138 	ib_dma_unmap_single(ibdev, req->sqe.dma, sizeof(struct nvme_command),
2139 			    DMA_TO_DEVICE);
2140 	nvme_complete_rq(rq);
2141 }
2142 
2143 static void nvme_rdma_map_queues(struct blk_mq_tag_set *set)
2144 {
2145 	struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(set->driver_data);
2146 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2147 
2148 	if (opts->nr_write_queues && ctrl->io_queues[HCTX_TYPE_READ]) {
2149 		/* separate read/write queues */
2150 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
2151 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2152 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2153 		set->map[HCTX_TYPE_READ].nr_queues =
2154 			ctrl->io_queues[HCTX_TYPE_READ];
2155 		set->map[HCTX_TYPE_READ].queue_offset =
2156 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2157 	} else {
2158 		/* shared read/write queues */
2159 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
2160 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2161 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2162 		set->map[HCTX_TYPE_READ].nr_queues =
2163 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2164 		set->map[HCTX_TYPE_READ].queue_offset = 0;
2165 	}
2166 	blk_mq_rdma_map_queues(&set->map[HCTX_TYPE_DEFAULT],
2167 			ctrl->device->dev, 0);
2168 	blk_mq_rdma_map_queues(&set->map[HCTX_TYPE_READ],
2169 			ctrl->device->dev, 0);
2170 
2171 	if (opts->nr_poll_queues && ctrl->io_queues[HCTX_TYPE_POLL]) {
2172 		/* map dedicated poll queues only if we have queues left */
2173 		set->map[HCTX_TYPE_POLL].nr_queues =
2174 				ctrl->io_queues[HCTX_TYPE_POLL];
2175 		set->map[HCTX_TYPE_POLL].queue_offset =
2176 			ctrl->io_queues[HCTX_TYPE_DEFAULT] +
2177 			ctrl->io_queues[HCTX_TYPE_READ];
2178 		blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]);
2179 	}
2180 
2181 	dev_info(ctrl->ctrl.device,
2182 		"mapped %d/%d/%d default/read/poll queues.\n",
2183 		ctrl->io_queues[HCTX_TYPE_DEFAULT],
2184 		ctrl->io_queues[HCTX_TYPE_READ],
2185 		ctrl->io_queues[HCTX_TYPE_POLL]);
2186 }
2187 
2188 static const struct blk_mq_ops nvme_rdma_mq_ops = {
2189 	.queue_rq	= nvme_rdma_queue_rq,
2190 	.complete	= nvme_rdma_complete_rq,
2191 	.init_request	= nvme_rdma_init_request,
2192 	.exit_request	= nvme_rdma_exit_request,
2193 	.init_hctx	= nvme_rdma_init_hctx,
2194 	.timeout	= nvme_rdma_timeout,
2195 	.map_queues	= nvme_rdma_map_queues,
2196 	.poll		= nvme_rdma_poll,
2197 };
2198 
2199 static const struct blk_mq_ops nvme_rdma_admin_mq_ops = {
2200 	.queue_rq	= nvme_rdma_queue_rq,
2201 	.complete	= nvme_rdma_complete_rq,
2202 	.init_request	= nvme_rdma_init_request,
2203 	.exit_request	= nvme_rdma_exit_request,
2204 	.init_hctx	= nvme_rdma_init_admin_hctx,
2205 	.timeout	= nvme_rdma_timeout,
2206 };
2207 
2208 static void nvme_rdma_shutdown_ctrl(struct nvme_rdma_ctrl *ctrl, bool shutdown)
2209 {
2210 	nvme_rdma_teardown_io_queues(ctrl, shutdown);
2211 	nvme_quiesce_admin_queue(&ctrl->ctrl);
2212 	nvme_disable_ctrl(&ctrl->ctrl, shutdown);
2213 	nvme_rdma_teardown_admin_queue(ctrl, shutdown);
2214 }
2215 
2216 static void nvme_rdma_delete_ctrl(struct nvme_ctrl *ctrl)
2217 {
2218 	nvme_rdma_shutdown_ctrl(to_rdma_ctrl(ctrl), true);
2219 }
2220 
2221 static void nvme_rdma_reset_ctrl_work(struct work_struct *work)
2222 {
2223 	struct nvme_rdma_ctrl *ctrl =
2224 		container_of(work, struct nvme_rdma_ctrl, ctrl.reset_work);
2225 
2226 	nvme_stop_ctrl(&ctrl->ctrl);
2227 	nvme_rdma_shutdown_ctrl(ctrl, false);
2228 
2229 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
2230 		/* state change failure should never happen */
2231 		WARN_ON_ONCE(1);
2232 		return;
2233 	}
2234 
2235 	if (nvme_rdma_setup_ctrl(ctrl, false))
2236 		goto out_fail;
2237 
2238 	return;
2239 
2240 out_fail:
2241 	++ctrl->ctrl.nr_reconnects;
2242 	nvme_rdma_reconnect_or_remove(ctrl);
2243 }
2244 
2245 static const struct nvme_ctrl_ops nvme_rdma_ctrl_ops = {
2246 	.name			= "rdma",
2247 	.module			= THIS_MODULE,
2248 	.flags			= NVME_F_FABRICS | NVME_F_METADATA_SUPPORTED,
2249 	.reg_read32		= nvmf_reg_read32,
2250 	.reg_read64		= nvmf_reg_read64,
2251 	.reg_write32		= nvmf_reg_write32,
2252 	.free_ctrl		= nvme_rdma_free_ctrl,
2253 	.submit_async_event	= nvme_rdma_submit_async_event,
2254 	.delete_ctrl		= nvme_rdma_delete_ctrl,
2255 	.get_address		= nvmf_get_address,
2256 	.stop_ctrl		= nvme_rdma_stop_ctrl,
2257 };
2258 
2259 /*
2260  * Fails a connection request if it matches an existing controller
2261  * (association) with the same tuple:
2262  * <Host NQN, Host ID, local address, remote address, remote port, SUBSYS NQN>
2263  *
2264  * if local address is not specified in the request, it will match an
2265  * existing controller with all the other parameters the same and no
2266  * local port address specified as well.
2267  *
2268  * The ports don't need to be compared as they are intrinsically
2269  * already matched by the port pointers supplied.
2270  */
2271 static bool
2272 nvme_rdma_existing_controller(struct nvmf_ctrl_options *opts)
2273 {
2274 	struct nvme_rdma_ctrl *ctrl;
2275 	bool found = false;
2276 
2277 	mutex_lock(&nvme_rdma_ctrl_mutex);
2278 	list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) {
2279 		found = nvmf_ip_options_match(&ctrl->ctrl, opts);
2280 		if (found)
2281 			break;
2282 	}
2283 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2284 
2285 	return found;
2286 }
2287 
2288 static struct nvme_ctrl *nvme_rdma_create_ctrl(struct device *dev,
2289 		struct nvmf_ctrl_options *opts)
2290 {
2291 	struct nvme_rdma_ctrl *ctrl;
2292 	int ret;
2293 	bool changed;
2294 
2295 	ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
2296 	if (!ctrl)
2297 		return ERR_PTR(-ENOMEM);
2298 	ctrl->ctrl.opts = opts;
2299 	INIT_LIST_HEAD(&ctrl->list);
2300 
2301 	if (!(opts->mask & NVMF_OPT_TRSVCID)) {
2302 		opts->trsvcid =
2303 			kstrdup(__stringify(NVME_RDMA_IP_PORT), GFP_KERNEL);
2304 		if (!opts->trsvcid) {
2305 			ret = -ENOMEM;
2306 			goto out_free_ctrl;
2307 		}
2308 		opts->mask |= NVMF_OPT_TRSVCID;
2309 	}
2310 
2311 	ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2312 			opts->traddr, opts->trsvcid, &ctrl->addr);
2313 	if (ret) {
2314 		pr_err("malformed address passed: %s:%s\n",
2315 			opts->traddr, opts->trsvcid);
2316 		goto out_free_ctrl;
2317 	}
2318 
2319 	if (opts->mask & NVMF_OPT_HOST_TRADDR) {
2320 		ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2321 			opts->host_traddr, NULL, &ctrl->src_addr);
2322 		if (ret) {
2323 			pr_err("malformed src address passed: %s\n",
2324 			       opts->host_traddr);
2325 			goto out_free_ctrl;
2326 		}
2327 	}
2328 
2329 	if (!opts->duplicate_connect && nvme_rdma_existing_controller(opts)) {
2330 		ret = -EALREADY;
2331 		goto out_free_ctrl;
2332 	}
2333 
2334 	INIT_DELAYED_WORK(&ctrl->reconnect_work,
2335 			nvme_rdma_reconnect_ctrl_work);
2336 	INIT_WORK(&ctrl->err_work, nvme_rdma_error_recovery_work);
2337 	INIT_WORK(&ctrl->ctrl.reset_work, nvme_rdma_reset_ctrl_work);
2338 
2339 	ctrl->ctrl.queue_count = opts->nr_io_queues + opts->nr_write_queues +
2340 				opts->nr_poll_queues + 1;
2341 	ctrl->ctrl.sqsize = opts->queue_size - 1;
2342 	ctrl->ctrl.kato = opts->kato;
2343 
2344 	ret = -ENOMEM;
2345 	ctrl->queues = kcalloc(ctrl->ctrl.queue_count, sizeof(*ctrl->queues),
2346 				GFP_KERNEL);
2347 	if (!ctrl->queues)
2348 		goto out_free_ctrl;
2349 
2350 	ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_rdma_ctrl_ops,
2351 				0 /* no quirks, we're perfect! */);
2352 	if (ret)
2353 		goto out_kfree_queues;
2354 
2355 	changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING);
2356 	WARN_ON_ONCE(!changed);
2357 
2358 	ret = nvme_rdma_setup_ctrl(ctrl, true);
2359 	if (ret)
2360 		goto out_uninit_ctrl;
2361 
2362 	dev_info(ctrl->ctrl.device, "new ctrl: NQN \"%s\", addr %pISpcs\n",
2363 		nvmf_ctrl_subsysnqn(&ctrl->ctrl), &ctrl->addr);
2364 
2365 	mutex_lock(&nvme_rdma_ctrl_mutex);
2366 	list_add_tail(&ctrl->list, &nvme_rdma_ctrl_list);
2367 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2368 
2369 	return &ctrl->ctrl;
2370 
2371 out_uninit_ctrl:
2372 	nvme_uninit_ctrl(&ctrl->ctrl);
2373 	nvme_put_ctrl(&ctrl->ctrl);
2374 	if (ret > 0)
2375 		ret = -EIO;
2376 	return ERR_PTR(ret);
2377 out_kfree_queues:
2378 	kfree(ctrl->queues);
2379 out_free_ctrl:
2380 	kfree(ctrl);
2381 	return ERR_PTR(ret);
2382 }
2383 
2384 static struct nvmf_transport_ops nvme_rdma_transport = {
2385 	.name		= "rdma",
2386 	.module		= THIS_MODULE,
2387 	.required_opts	= NVMF_OPT_TRADDR,
2388 	.allowed_opts	= NVMF_OPT_TRSVCID | NVMF_OPT_RECONNECT_DELAY |
2389 			  NVMF_OPT_HOST_TRADDR | NVMF_OPT_CTRL_LOSS_TMO |
2390 			  NVMF_OPT_NR_WRITE_QUEUES | NVMF_OPT_NR_POLL_QUEUES |
2391 			  NVMF_OPT_TOS,
2392 	.create_ctrl	= nvme_rdma_create_ctrl,
2393 };
2394 
2395 static void nvme_rdma_remove_one(struct ib_device *ib_device, void *client_data)
2396 {
2397 	struct nvme_rdma_ctrl *ctrl;
2398 	struct nvme_rdma_device *ndev;
2399 	bool found = false;
2400 
2401 	mutex_lock(&device_list_mutex);
2402 	list_for_each_entry(ndev, &device_list, entry) {
2403 		if (ndev->dev == ib_device) {
2404 			found = true;
2405 			break;
2406 		}
2407 	}
2408 	mutex_unlock(&device_list_mutex);
2409 
2410 	if (!found)
2411 		return;
2412 
2413 	/* Delete all controllers using this device */
2414 	mutex_lock(&nvme_rdma_ctrl_mutex);
2415 	list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) {
2416 		if (ctrl->device->dev != ib_device)
2417 			continue;
2418 		nvme_delete_ctrl(&ctrl->ctrl);
2419 	}
2420 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2421 
2422 	flush_workqueue(nvme_delete_wq);
2423 }
2424 
2425 static struct ib_client nvme_rdma_ib_client = {
2426 	.name   = "nvme_rdma",
2427 	.remove = nvme_rdma_remove_one
2428 };
2429 
2430 static int __init nvme_rdma_init_module(void)
2431 {
2432 	int ret;
2433 
2434 	ret = ib_register_client(&nvme_rdma_ib_client);
2435 	if (ret)
2436 		return ret;
2437 
2438 	ret = nvmf_register_transport(&nvme_rdma_transport);
2439 	if (ret)
2440 		goto err_unreg_client;
2441 
2442 	return 0;
2443 
2444 err_unreg_client:
2445 	ib_unregister_client(&nvme_rdma_ib_client);
2446 	return ret;
2447 }
2448 
2449 static void __exit nvme_rdma_cleanup_module(void)
2450 {
2451 	struct nvme_rdma_ctrl *ctrl;
2452 
2453 	nvmf_unregister_transport(&nvme_rdma_transport);
2454 	ib_unregister_client(&nvme_rdma_ib_client);
2455 
2456 	mutex_lock(&nvme_rdma_ctrl_mutex);
2457 	list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list)
2458 		nvme_delete_ctrl(&ctrl->ctrl);
2459 	mutex_unlock(&nvme_rdma_ctrl_mutex);
2460 	flush_workqueue(nvme_delete_wq);
2461 }
2462 
2463 module_init(nvme_rdma_init_module);
2464 module_exit(nvme_rdma_cleanup_module);
2465 
2466 MODULE_LICENSE("GPL v2");
2467