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