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