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