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