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