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