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