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