nvme-rdma: split nvme_rdma_alloc_tagset
[linux-2.6-microblaze.git] / drivers / nvme / host / rdma.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVMe over Fabrics RDMA host code.
4  * Copyright (c) 2015-2016 HGST, a Western Digital Company.
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 #include <linux/module.h>
8 #include <linux/init.h>
9 #include <linux/slab.h>
10 #include <rdma/mr_pool.h>
11 #include <linux/err.h>
12 #include <linux/string.h>
13 #include <linux/atomic.h>
14 #include <linux/blk-mq.h>
15 #include <linux/blk-mq-rdma.h>
16 #include <linux/blk-integrity.h>
17 #include <linux/types.h>
18 #include <linux/list.h>
19 #include <linux/mutex.h>
20 #include <linux/scatterlist.h>
21 #include <linux/nvme.h>
22 #include <asm/unaligned.h>
23
24 #include <rdma/ib_verbs.h>
25 #include <rdma/rdma_cm.h>
26 #include <linux/nvme-rdma.h>
27
28 #include "nvme.h"
29 #include "fabrics.h"
30
31
32 #define NVME_RDMA_CM_TIMEOUT_MS         3000            /* 3 second */
33
34 #define NVME_RDMA_MAX_SEGMENTS          256
35
36 #define NVME_RDMA_MAX_INLINE_SEGMENTS   4
37
38 #define NVME_RDMA_DATA_SGL_SIZE \
39         (sizeof(struct scatterlist) * NVME_INLINE_SG_CNT)
40 #define NVME_RDMA_METADATA_SGL_SIZE \
41         (sizeof(struct scatterlist) * NVME_INLINE_METADATA_SG_CNT)
42
43 struct nvme_rdma_device {
44         struct ib_device        *dev;
45         struct ib_pd            *pd;
46         struct kref             ref;
47         struct list_head        entry;
48         unsigned int            num_inline_segments;
49 };
50
51 struct nvme_rdma_qe {
52         struct ib_cqe           cqe;
53         void                    *data;
54         u64                     dma;
55 };
56
57 struct nvme_rdma_sgl {
58         int                     nents;
59         struct sg_table         sg_table;
60 };
61
62 struct nvme_rdma_queue;
63 struct nvme_rdma_request {
64         struct nvme_request     req;
65         struct ib_mr            *mr;
66         struct nvme_rdma_qe     sqe;
67         union nvme_result       result;
68         __le16                  status;
69         refcount_t              ref;
70         struct ib_sge           sge[1 + NVME_RDMA_MAX_INLINE_SEGMENTS];
71         u32                     num_sge;
72         struct ib_reg_wr        reg_wr;
73         struct ib_cqe           reg_cqe;
74         struct nvme_rdma_queue  *queue;
75         struct nvme_rdma_sgl    data_sgl;
76         struct nvme_rdma_sgl    *metadata_sgl;
77         bool                    use_sig_mr;
78 };
79
80 enum nvme_rdma_queue_flags {
81         NVME_RDMA_Q_ALLOCATED           = 0,
82         NVME_RDMA_Q_LIVE                = 1,
83         NVME_RDMA_Q_TR_READY            = 2,
84 };
85
86 struct nvme_rdma_queue {
87         struct nvme_rdma_qe     *rsp_ring;
88         int                     queue_size;
89         size_t                  cmnd_capsule_len;
90         struct nvme_rdma_ctrl   *ctrl;
91         struct nvme_rdma_device *device;
92         struct ib_cq            *ib_cq;
93         struct ib_qp            *qp;
94
95         unsigned long           flags;
96         struct rdma_cm_id       *cm_id;
97         int                     cm_error;
98         struct completion       cm_done;
99         bool                    pi_support;
100         int                     cq_size;
101         struct mutex            queue_lock;
102 };
103
104 struct nvme_rdma_ctrl {
105         /* read only in the hot path */
106         struct nvme_rdma_queue  *queues;
107
108         /* other member variables */
109         struct blk_mq_tag_set   tag_set;
110         struct work_struct      err_work;
111
112         struct nvme_rdma_qe     async_event_sqe;
113
114         struct delayed_work     reconnect_work;
115
116         struct list_head        list;
117
118         struct blk_mq_tag_set   admin_tag_set;
119         struct nvme_rdma_device *device;
120
121         u32                     max_fr_pages;
122
123         struct sockaddr_storage addr;
124         struct sockaddr_storage src_addr;
125
126         struct nvme_ctrl        ctrl;
127         bool                    use_inline_data;
128         u32                     io_queues[HCTX_MAX_TYPES];
129 };
130
131 static inline struct nvme_rdma_ctrl *to_rdma_ctrl(struct nvme_ctrl *ctrl)
132 {
133         return container_of(ctrl, struct nvme_rdma_ctrl, ctrl);
134 }
135
136 static LIST_HEAD(device_list);
137 static DEFINE_MUTEX(device_list_mutex);
138
139 static LIST_HEAD(nvme_rdma_ctrl_list);
140 static DEFINE_MUTEX(nvme_rdma_ctrl_mutex);
141
142 /*
143  * Disabling this option makes small I/O goes faster, but is fundamentally
144  * unsafe.  With it turned off we will have to register a global rkey that
145  * allows read and write access to all physical memory.
146  */
147 static bool register_always = true;
148 module_param(register_always, bool, 0444);
149 MODULE_PARM_DESC(register_always,
150          "Use memory registration even for contiguous memory regions");
151
152 static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id,
153                 struct rdma_cm_event *event);
154 static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc);
155 static void nvme_rdma_complete_rq(struct request *rq);
156
157 static const struct blk_mq_ops nvme_rdma_mq_ops;
158 static const struct blk_mq_ops nvme_rdma_admin_mq_ops;
159
160 static inline int nvme_rdma_queue_idx(struct nvme_rdma_queue *queue)
161 {
162         return queue - queue->ctrl->queues;
163 }
164
165 static bool nvme_rdma_poll_queue(struct nvme_rdma_queue *queue)
166 {
167         return nvme_rdma_queue_idx(queue) >
168                 queue->ctrl->io_queues[HCTX_TYPE_DEFAULT] +
169                 queue->ctrl->io_queues[HCTX_TYPE_READ];
170 }
171
172 static inline size_t nvme_rdma_inline_data_size(struct nvme_rdma_queue *queue)
173 {
174         return queue->cmnd_capsule_len - sizeof(struct nvme_command);
175 }
176
177 static void nvme_rdma_free_qe(struct ib_device *ibdev, struct nvme_rdma_qe *qe,
178                 size_t capsule_size, enum dma_data_direction dir)
179 {
180         ib_dma_unmap_single(ibdev, qe->dma, capsule_size, dir);
181         kfree(qe->data);
182 }
183
184 static int nvme_rdma_alloc_qe(struct ib_device *ibdev, struct nvme_rdma_qe *qe,
185                 size_t capsule_size, enum dma_data_direction dir)
186 {
187         qe->data = kzalloc(capsule_size, GFP_KERNEL);
188         if (!qe->data)
189                 return -ENOMEM;
190
191         qe->dma = ib_dma_map_single(ibdev, qe->data, capsule_size, dir);
192         if (ib_dma_mapping_error(ibdev, qe->dma)) {
193                 kfree(qe->data);
194                 qe->data = NULL;
195                 return -ENOMEM;
196         }
197
198         return 0;
199 }
200
201 static void nvme_rdma_free_ring(struct ib_device *ibdev,
202                 struct nvme_rdma_qe *ring, size_t ib_queue_size,
203                 size_t capsule_size, enum dma_data_direction dir)
204 {
205         int i;
206
207         for (i = 0; i < ib_queue_size; i++)
208                 nvme_rdma_free_qe(ibdev, &ring[i], capsule_size, dir);
209         kfree(ring);
210 }
211
212 static struct nvme_rdma_qe *nvme_rdma_alloc_ring(struct ib_device *ibdev,
213                 size_t ib_queue_size, size_t capsule_size,
214                 enum dma_data_direction dir)
215 {
216         struct nvme_rdma_qe *ring;
217         int i;
218
219         ring = kcalloc(ib_queue_size, sizeof(struct nvme_rdma_qe), GFP_KERNEL);
220         if (!ring)
221                 return NULL;
222
223         /*
224          * Bind the CQEs (post recv buffers) DMA mapping to the RDMA queue
225          * lifetime. It's safe, since any chage in the underlying RDMA device
226          * will issue error recovery and queue re-creation.
227          */
228         for (i = 0; i < ib_queue_size; i++) {
229                 if (nvme_rdma_alloc_qe(ibdev, &ring[i], capsule_size, dir))
230                         goto out_free_ring;
231         }
232
233         return ring;
234
235 out_free_ring:
236         nvme_rdma_free_ring(ibdev, ring, i, capsule_size, dir);
237         return NULL;
238 }
239
240 static void nvme_rdma_qp_event(struct ib_event *event, void *context)
241 {
242         pr_debug("QP event %s (%d)\n",
243                  ib_event_msg(event->event), event->event);
244
245 }
246
247 static int nvme_rdma_wait_for_cm(struct nvme_rdma_queue *queue)
248 {
249         int ret;
250
251         ret = wait_for_completion_interruptible(&queue->cm_done);
252         if (ret)
253                 return ret;
254         WARN_ON_ONCE(queue->cm_error > 0);
255         return queue->cm_error;
256 }
257
258 static int nvme_rdma_create_qp(struct nvme_rdma_queue *queue, const int factor)
259 {
260         struct nvme_rdma_device *dev = queue->device;
261         struct ib_qp_init_attr init_attr;
262         int ret;
263
264         memset(&init_attr, 0, sizeof(init_attr));
265         init_attr.event_handler = nvme_rdma_qp_event;
266         /* +1 for drain */
267         init_attr.cap.max_send_wr = factor * queue->queue_size + 1;
268         /* +1 for drain */
269         init_attr.cap.max_recv_wr = queue->queue_size + 1;
270         init_attr.cap.max_recv_sge = 1;
271         init_attr.cap.max_send_sge = 1 + dev->num_inline_segments;
272         init_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
273         init_attr.qp_type = IB_QPT_RC;
274         init_attr.send_cq = queue->ib_cq;
275         init_attr.recv_cq = queue->ib_cq;
276         if (queue->pi_support)
277                 init_attr.create_flags |= IB_QP_CREATE_INTEGRITY_EN;
278         init_attr.qp_context = queue;
279
280         ret = rdma_create_qp(queue->cm_id, dev->pd, &init_attr);
281
282         queue->qp = queue->cm_id->qp;
283         return ret;
284 }
285
286 static void nvme_rdma_exit_request(struct blk_mq_tag_set *set,
287                 struct request *rq, unsigned int hctx_idx)
288 {
289         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
290
291         kfree(req->sqe.data);
292 }
293
294 static int nvme_rdma_init_request(struct blk_mq_tag_set *set,
295                 struct request *rq, unsigned int hctx_idx,
296                 unsigned int numa_node)
297 {
298         struct nvme_rdma_ctrl *ctrl = set->driver_data;
299         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
300         int queue_idx = (set == &ctrl->tag_set) ? hctx_idx + 1 : 0;
301         struct nvme_rdma_queue *queue = &ctrl->queues[queue_idx];
302
303         nvme_req(rq)->ctrl = &ctrl->ctrl;
304         req->sqe.data = kzalloc(sizeof(struct nvme_command), GFP_KERNEL);
305         if (!req->sqe.data)
306                 return -ENOMEM;
307
308         /* metadata nvme_rdma_sgl struct is located after command's data SGL */
309         if (queue->pi_support)
310                 req->metadata_sgl = (void *)nvme_req(rq) +
311                         sizeof(struct nvme_rdma_request) +
312                         NVME_RDMA_DATA_SGL_SIZE;
313
314         req->queue = queue;
315         nvme_req(rq)->cmd = req->sqe.data;
316
317         return 0;
318 }
319
320 static int nvme_rdma_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
321                 unsigned int hctx_idx)
322 {
323         struct nvme_rdma_ctrl *ctrl = data;
324         struct nvme_rdma_queue *queue = &ctrl->queues[hctx_idx + 1];
325
326         BUG_ON(hctx_idx >= ctrl->ctrl.queue_count);
327
328         hctx->driver_data = queue;
329         return 0;
330 }
331
332 static int nvme_rdma_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
333                 unsigned int hctx_idx)
334 {
335         struct nvme_rdma_ctrl *ctrl = data;
336         struct nvme_rdma_queue *queue = &ctrl->queues[0];
337
338         BUG_ON(hctx_idx != 0);
339
340         hctx->driver_data = queue;
341         return 0;
342 }
343
344 static void nvme_rdma_free_dev(struct kref *ref)
345 {
346         struct nvme_rdma_device *ndev =
347                 container_of(ref, struct nvme_rdma_device, ref);
348
349         mutex_lock(&device_list_mutex);
350         list_del(&ndev->entry);
351         mutex_unlock(&device_list_mutex);
352
353         ib_dealloc_pd(ndev->pd);
354         kfree(ndev);
355 }
356
357 static void nvme_rdma_dev_put(struct nvme_rdma_device *dev)
358 {
359         kref_put(&dev->ref, nvme_rdma_free_dev);
360 }
361
362 static int nvme_rdma_dev_get(struct nvme_rdma_device *dev)
363 {
364         return kref_get_unless_zero(&dev->ref);
365 }
366
367 static struct nvme_rdma_device *
368 nvme_rdma_find_get_device(struct rdma_cm_id *cm_id)
369 {
370         struct nvme_rdma_device *ndev;
371
372         mutex_lock(&device_list_mutex);
373         list_for_each_entry(ndev, &device_list, entry) {
374                 if (ndev->dev->node_guid == cm_id->device->node_guid &&
375                     nvme_rdma_dev_get(ndev))
376                         goto out_unlock;
377         }
378
379         ndev = kzalloc(sizeof(*ndev), GFP_KERNEL);
380         if (!ndev)
381                 goto out_err;
382
383         ndev->dev = cm_id->device;
384         kref_init(&ndev->ref);
385
386         ndev->pd = ib_alloc_pd(ndev->dev,
387                 register_always ? 0 : IB_PD_UNSAFE_GLOBAL_RKEY);
388         if (IS_ERR(ndev->pd))
389                 goto out_free_dev;
390
391         if (!(ndev->dev->attrs.device_cap_flags &
392               IB_DEVICE_MEM_MGT_EXTENSIONS)) {
393                 dev_err(&ndev->dev->dev,
394                         "Memory registrations not supported.\n");
395                 goto out_free_pd;
396         }
397
398         ndev->num_inline_segments = min(NVME_RDMA_MAX_INLINE_SEGMENTS,
399                                         ndev->dev->attrs.max_send_sge - 1);
400         list_add(&ndev->entry, &device_list);
401 out_unlock:
402         mutex_unlock(&device_list_mutex);
403         return ndev;
404
405 out_free_pd:
406         ib_dealloc_pd(ndev->pd);
407 out_free_dev:
408         kfree(ndev);
409 out_err:
410         mutex_unlock(&device_list_mutex);
411         return NULL;
412 }
413
414 static void nvme_rdma_free_cq(struct nvme_rdma_queue *queue)
415 {
416         if (nvme_rdma_poll_queue(queue))
417                 ib_free_cq(queue->ib_cq);
418         else
419                 ib_cq_pool_put(queue->ib_cq, queue->cq_size);
420 }
421
422 static void nvme_rdma_destroy_queue_ib(struct nvme_rdma_queue *queue)
423 {
424         struct nvme_rdma_device *dev;
425         struct ib_device *ibdev;
426
427         if (!test_and_clear_bit(NVME_RDMA_Q_TR_READY, &queue->flags))
428                 return;
429
430         dev = queue->device;
431         ibdev = dev->dev;
432
433         if (queue->pi_support)
434                 ib_mr_pool_destroy(queue->qp, &queue->qp->sig_mrs);
435         ib_mr_pool_destroy(queue->qp, &queue->qp->rdma_mrs);
436
437         /*
438          * The cm_id object might have been destroyed during RDMA connection
439          * establishment error flow to avoid getting other cma events, thus
440          * the destruction of the QP shouldn't use rdma_cm API.
441          */
442         ib_destroy_qp(queue->qp);
443         nvme_rdma_free_cq(queue);
444
445         nvme_rdma_free_ring(ibdev, queue->rsp_ring, queue->queue_size,
446                         sizeof(struct nvme_completion), DMA_FROM_DEVICE);
447
448         nvme_rdma_dev_put(dev);
449 }
450
451 static int nvme_rdma_get_max_fr_pages(struct ib_device *ibdev, bool pi_support)
452 {
453         u32 max_page_list_len;
454
455         if (pi_support)
456                 max_page_list_len = ibdev->attrs.max_pi_fast_reg_page_list_len;
457         else
458                 max_page_list_len = ibdev->attrs.max_fast_reg_page_list_len;
459
460         return min_t(u32, NVME_RDMA_MAX_SEGMENTS, max_page_list_len - 1);
461 }
462
463 static int nvme_rdma_create_cq(struct ib_device *ibdev,
464                 struct nvme_rdma_queue *queue)
465 {
466         int ret, comp_vector, idx = nvme_rdma_queue_idx(queue);
467         enum ib_poll_context poll_ctx;
468
469         /*
470          * Spread I/O queues completion vectors according their queue index.
471          * Admin queues can always go on completion vector 0.
472          */
473         comp_vector = (idx == 0 ? idx : idx - 1) % ibdev->num_comp_vectors;
474
475         /* Polling queues need direct cq polling context */
476         if (nvme_rdma_poll_queue(queue)) {
477                 poll_ctx = IB_POLL_DIRECT;
478                 queue->ib_cq = ib_alloc_cq(ibdev, queue, queue->cq_size,
479                                            comp_vector, poll_ctx);
480         } else {
481                 poll_ctx = IB_POLL_SOFTIRQ;
482                 queue->ib_cq = ib_cq_pool_get(ibdev, queue->cq_size,
483                                               comp_vector, poll_ctx);
484         }
485
486         if (IS_ERR(queue->ib_cq)) {
487                 ret = PTR_ERR(queue->ib_cq);
488                 return ret;
489         }
490
491         return 0;
492 }
493
494 static int nvme_rdma_create_queue_ib(struct nvme_rdma_queue *queue)
495 {
496         struct ib_device *ibdev;
497         const int send_wr_factor = 3;                   /* MR, SEND, INV */
498         const int cq_factor = send_wr_factor + 1;       /* + RECV */
499         int ret, pages_per_mr;
500
501         queue->device = nvme_rdma_find_get_device(queue->cm_id);
502         if (!queue->device) {
503                 dev_err(queue->cm_id->device->dev.parent,
504                         "no client data found!\n");
505                 return -ECONNREFUSED;
506         }
507         ibdev = queue->device->dev;
508
509         /* +1 for ib_stop_cq */
510         queue->cq_size = cq_factor * queue->queue_size + 1;
511
512         ret = nvme_rdma_create_cq(ibdev, queue);
513         if (ret)
514                 goto out_put_dev;
515
516         ret = nvme_rdma_create_qp(queue, send_wr_factor);
517         if (ret)
518                 goto out_destroy_ib_cq;
519
520         queue->rsp_ring = nvme_rdma_alloc_ring(ibdev, queue->queue_size,
521                         sizeof(struct nvme_completion), DMA_FROM_DEVICE);
522         if (!queue->rsp_ring) {
523                 ret = -ENOMEM;
524                 goto out_destroy_qp;
525         }
526
527         /*
528          * Currently we don't use SG_GAPS MR's so if the first entry is
529          * misaligned we'll end up using two entries for a single data page,
530          * so one additional entry is required.
531          */
532         pages_per_mr = nvme_rdma_get_max_fr_pages(ibdev, queue->pi_support) + 1;
533         ret = ib_mr_pool_init(queue->qp, &queue->qp->rdma_mrs,
534                               queue->queue_size,
535                               IB_MR_TYPE_MEM_REG,
536                               pages_per_mr, 0);
537         if (ret) {
538                 dev_err(queue->ctrl->ctrl.device,
539                         "failed to initialize MR pool sized %d for QID %d\n",
540                         queue->queue_size, nvme_rdma_queue_idx(queue));
541                 goto out_destroy_ring;
542         }
543
544         if (queue->pi_support) {
545                 ret = ib_mr_pool_init(queue->qp, &queue->qp->sig_mrs,
546                                       queue->queue_size, IB_MR_TYPE_INTEGRITY,
547                                       pages_per_mr, pages_per_mr);
548                 if (ret) {
549                         dev_err(queue->ctrl->ctrl.device,
550                                 "failed to initialize PI MR pool sized %d for QID %d\n",
551                                 queue->queue_size, nvme_rdma_queue_idx(queue));
552                         goto out_destroy_mr_pool;
553                 }
554         }
555
556         set_bit(NVME_RDMA_Q_TR_READY, &queue->flags);
557
558         return 0;
559
560 out_destroy_mr_pool:
561         ib_mr_pool_destroy(queue->qp, &queue->qp->rdma_mrs);
562 out_destroy_ring:
563         nvme_rdma_free_ring(ibdev, queue->rsp_ring, queue->queue_size,
564                             sizeof(struct nvme_completion), DMA_FROM_DEVICE);
565 out_destroy_qp:
566         rdma_destroy_qp(queue->cm_id);
567 out_destroy_ib_cq:
568         nvme_rdma_free_cq(queue);
569 out_put_dev:
570         nvme_rdma_dev_put(queue->device);
571         return ret;
572 }
573
574 static int nvme_rdma_alloc_queue(struct nvme_rdma_ctrl *ctrl,
575                 int idx, size_t queue_size)
576 {
577         struct nvme_rdma_queue *queue;
578         struct sockaddr *src_addr = NULL;
579         int ret;
580
581         queue = &ctrl->queues[idx];
582         mutex_init(&queue->queue_lock);
583         queue->ctrl = ctrl;
584         if (idx && ctrl->ctrl.max_integrity_segments)
585                 queue->pi_support = true;
586         else
587                 queue->pi_support = false;
588         init_completion(&queue->cm_done);
589
590         if (idx > 0)
591                 queue->cmnd_capsule_len = ctrl->ctrl.ioccsz * 16;
592         else
593                 queue->cmnd_capsule_len = sizeof(struct nvme_command);
594
595         queue->queue_size = queue_size;
596
597         queue->cm_id = rdma_create_id(&init_net, nvme_rdma_cm_handler, queue,
598                         RDMA_PS_TCP, IB_QPT_RC);
599         if (IS_ERR(queue->cm_id)) {
600                 dev_info(ctrl->ctrl.device,
601                         "failed to create CM ID: %ld\n", PTR_ERR(queue->cm_id));
602                 ret = PTR_ERR(queue->cm_id);
603                 goto out_destroy_mutex;
604         }
605
606         if (ctrl->ctrl.opts->mask & NVMF_OPT_HOST_TRADDR)
607                 src_addr = (struct sockaddr *)&ctrl->src_addr;
608
609         queue->cm_error = -ETIMEDOUT;
610         ret = rdma_resolve_addr(queue->cm_id, src_addr,
611                         (struct sockaddr *)&ctrl->addr,
612                         NVME_RDMA_CM_TIMEOUT_MS);
613         if (ret) {
614                 dev_info(ctrl->ctrl.device,
615                         "rdma_resolve_addr failed (%d).\n", ret);
616                 goto out_destroy_cm_id;
617         }
618
619         ret = nvme_rdma_wait_for_cm(queue);
620         if (ret) {
621                 dev_info(ctrl->ctrl.device,
622                         "rdma connection establishment failed (%d)\n", ret);
623                 goto out_destroy_cm_id;
624         }
625
626         set_bit(NVME_RDMA_Q_ALLOCATED, &queue->flags);
627
628         return 0;
629
630 out_destroy_cm_id:
631         rdma_destroy_id(queue->cm_id);
632         nvme_rdma_destroy_queue_ib(queue);
633 out_destroy_mutex:
634         mutex_destroy(&queue->queue_lock);
635         return ret;
636 }
637
638 static void __nvme_rdma_stop_queue(struct nvme_rdma_queue *queue)
639 {
640         rdma_disconnect(queue->cm_id);
641         ib_drain_qp(queue->qp);
642 }
643
644 static void nvme_rdma_stop_queue(struct nvme_rdma_queue *queue)
645 {
646         mutex_lock(&queue->queue_lock);
647         if (test_and_clear_bit(NVME_RDMA_Q_LIVE, &queue->flags))
648                 __nvme_rdma_stop_queue(queue);
649         mutex_unlock(&queue->queue_lock);
650 }
651
652 static void nvme_rdma_free_queue(struct nvme_rdma_queue *queue)
653 {
654         if (!test_and_clear_bit(NVME_RDMA_Q_ALLOCATED, &queue->flags))
655                 return;
656
657         rdma_destroy_id(queue->cm_id);
658         nvme_rdma_destroy_queue_ib(queue);
659         mutex_destroy(&queue->queue_lock);
660 }
661
662 static void nvme_rdma_free_io_queues(struct nvme_rdma_ctrl *ctrl)
663 {
664         int i;
665
666         for (i = 1; i < ctrl->ctrl.queue_count; i++)
667                 nvme_rdma_free_queue(&ctrl->queues[i]);
668 }
669
670 static void nvme_rdma_stop_io_queues(struct nvme_rdma_ctrl *ctrl)
671 {
672         int i;
673
674         for (i = 1; i < ctrl->ctrl.queue_count; i++)
675                 nvme_rdma_stop_queue(&ctrl->queues[i]);
676 }
677
678 static int nvme_rdma_start_queue(struct nvme_rdma_ctrl *ctrl, int idx)
679 {
680         struct nvme_rdma_queue *queue = &ctrl->queues[idx];
681         int ret;
682
683         if (idx)
684                 ret = nvmf_connect_io_queue(&ctrl->ctrl, idx);
685         else
686                 ret = nvmf_connect_admin_queue(&ctrl->ctrl);
687
688         if (!ret) {
689                 set_bit(NVME_RDMA_Q_LIVE, &queue->flags);
690         } else {
691                 if (test_bit(NVME_RDMA_Q_ALLOCATED, &queue->flags))
692                         __nvme_rdma_stop_queue(queue);
693                 dev_info(ctrl->ctrl.device,
694                         "failed to connect queue: %d ret=%d\n", idx, ret);
695         }
696         return ret;
697 }
698
699 static int nvme_rdma_start_io_queues(struct nvme_rdma_ctrl *ctrl)
700 {
701         int i, ret = 0;
702
703         for (i = 1; i < ctrl->ctrl.queue_count; i++) {
704                 ret = nvme_rdma_start_queue(ctrl, i);
705                 if (ret)
706                         goto out_stop_queues;
707         }
708
709         return 0;
710
711 out_stop_queues:
712         for (i--; i >= 1; i--)
713                 nvme_rdma_stop_queue(&ctrl->queues[i]);
714         return ret;
715 }
716
717 static int nvme_rdma_alloc_io_queues(struct nvme_rdma_ctrl *ctrl)
718 {
719         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
720         struct ib_device *ibdev = ctrl->device->dev;
721         unsigned int nr_io_queues, nr_default_queues;
722         unsigned int nr_read_queues, nr_poll_queues;
723         int i, ret;
724
725         nr_read_queues = min_t(unsigned int, ibdev->num_comp_vectors,
726                                 min(opts->nr_io_queues, num_online_cpus()));
727         nr_default_queues =  min_t(unsigned int, ibdev->num_comp_vectors,
728                                 min(opts->nr_write_queues, num_online_cpus()));
729         nr_poll_queues = min(opts->nr_poll_queues, num_online_cpus());
730         nr_io_queues = nr_read_queues + nr_default_queues + nr_poll_queues;
731
732         ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
733         if (ret)
734                 return ret;
735
736         if (nr_io_queues == 0) {
737                 dev_err(ctrl->ctrl.device,
738                         "unable to set any I/O queues\n");
739                 return -ENOMEM;
740         }
741
742         ctrl->ctrl.queue_count = nr_io_queues + 1;
743         dev_info(ctrl->ctrl.device,
744                 "creating %d I/O queues.\n", nr_io_queues);
745
746         if (opts->nr_write_queues && nr_read_queues < nr_io_queues) {
747                 /*
748                  * separate read/write queues
749                  * hand out dedicated default queues only after we have
750                  * sufficient read queues.
751                  */
752                 ctrl->io_queues[HCTX_TYPE_READ] = nr_read_queues;
753                 nr_io_queues -= ctrl->io_queues[HCTX_TYPE_READ];
754                 ctrl->io_queues[HCTX_TYPE_DEFAULT] =
755                         min(nr_default_queues, nr_io_queues);
756                 nr_io_queues -= ctrl->io_queues[HCTX_TYPE_DEFAULT];
757         } else {
758                 /*
759                  * shared read/write queues
760                  * either no write queues were requested, or we don't have
761                  * sufficient queue count to have dedicated default queues.
762                  */
763                 ctrl->io_queues[HCTX_TYPE_DEFAULT] =
764                         min(nr_read_queues, nr_io_queues);
765                 nr_io_queues -= ctrl->io_queues[HCTX_TYPE_DEFAULT];
766         }
767
768         if (opts->nr_poll_queues && nr_io_queues) {
769                 /* map dedicated poll queues only if we have queues left */
770                 ctrl->io_queues[HCTX_TYPE_POLL] =
771                         min(nr_poll_queues, nr_io_queues);
772         }
773
774         for (i = 1; i < ctrl->ctrl.queue_count; i++) {
775                 ret = nvme_rdma_alloc_queue(ctrl, i,
776                                 ctrl->ctrl.sqsize + 1);
777                 if (ret)
778                         goto out_free_queues;
779         }
780
781         return 0;
782
783 out_free_queues:
784         for (i--; i >= 1; i--)
785                 nvme_rdma_free_queue(&ctrl->queues[i]);
786
787         return ret;
788 }
789
790 static int nvme_rdma_alloc_admin_tag_set(struct nvme_ctrl *nctrl)
791 {
792         struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
793         struct blk_mq_tag_set *set = &ctrl->admin_tag_set;
794         int ret;
795
796         memset(set, 0, sizeof(*set));
797         set->ops = &nvme_rdma_admin_mq_ops;
798         set->queue_depth = NVME_AQ_MQ_TAG_DEPTH;
799         set->reserved_tags = NVMF_RESERVED_TAGS;
800         set->numa_node = nctrl->numa_node;
801         set->cmd_size = sizeof(struct nvme_rdma_request) +
802                         NVME_RDMA_DATA_SGL_SIZE;
803         set->driver_data = ctrl;
804         set->nr_hw_queues = 1;
805         set->timeout = NVME_ADMIN_TIMEOUT;
806         set->flags = BLK_MQ_F_NO_SCHED;
807         ret = blk_mq_alloc_tag_set(set);
808         if (!ret)
809                 ctrl->ctrl.admin_tagset = set;
810         return ret;
811 }
812
813 static int nvme_rdma_alloc_tag_set(struct nvme_ctrl *nctrl)
814 {
815         struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
816         struct blk_mq_tag_set *set = &ctrl->tag_set;
817         int ret;
818
819         memset(set, 0, sizeof(*set));
820         set->ops = &nvme_rdma_mq_ops;
821         set->queue_depth = nctrl->sqsize + 1;
822         set->reserved_tags = NVMF_RESERVED_TAGS;
823         set->numa_node = nctrl->numa_node;
824         set->flags = BLK_MQ_F_SHOULD_MERGE;
825         set->cmd_size = sizeof(struct nvme_rdma_request) +
826                         NVME_RDMA_DATA_SGL_SIZE;
827         if (nctrl->max_integrity_segments)
828                 set->cmd_size += sizeof(struct nvme_rdma_sgl) +
829                                  NVME_RDMA_METADATA_SGL_SIZE;
830         set->driver_data = ctrl;
831         set->nr_hw_queues = nctrl->queue_count - 1;
832         set->timeout = NVME_IO_TIMEOUT;
833         set->nr_maps = nctrl->opts->nr_poll_queues ? HCTX_MAX_TYPES : 2;
834         ret = blk_mq_alloc_tag_set(set);
835         if (!ret)
836                 ctrl->ctrl.tagset = set;
837         return ret;
838 }
839
840 static void nvme_rdma_destroy_admin_queue(struct nvme_rdma_ctrl *ctrl,
841                 bool remove)
842 {
843         if (remove) {
844                 blk_mq_destroy_queue(ctrl->ctrl.admin_q);
845                 blk_mq_destroy_queue(ctrl->ctrl.fabrics_q);
846                 blk_mq_free_tag_set(ctrl->ctrl.admin_tagset);
847         }
848         if (ctrl->async_event_sqe.data) {
849                 cancel_work_sync(&ctrl->ctrl.async_event_work);
850                 nvme_rdma_free_qe(ctrl->device->dev, &ctrl->async_event_sqe,
851                                 sizeof(struct nvme_command), DMA_TO_DEVICE);
852                 ctrl->async_event_sqe.data = NULL;
853         }
854         nvme_rdma_free_queue(&ctrl->queues[0]);
855 }
856
857 static int nvme_rdma_configure_admin_queue(struct nvme_rdma_ctrl *ctrl,
858                 bool new)
859 {
860         bool pi_capable = false;
861         int error;
862
863         error = nvme_rdma_alloc_queue(ctrl, 0, NVME_AQ_DEPTH);
864         if (error)
865                 return error;
866
867         ctrl->device = ctrl->queues[0].device;
868         ctrl->ctrl.numa_node = ibdev_to_node(ctrl->device->dev);
869
870         /* T10-PI support */
871         if (ctrl->device->dev->attrs.kernel_cap_flags &
872             IBK_INTEGRITY_HANDOVER)
873                 pi_capable = true;
874
875         ctrl->max_fr_pages = nvme_rdma_get_max_fr_pages(ctrl->device->dev,
876                                                         pi_capable);
877
878         /*
879          * Bind the async event SQE DMA mapping to the admin queue lifetime.
880          * It's safe, since any chage in the underlying RDMA device will issue
881          * error recovery and queue re-creation.
882          */
883         error = nvme_rdma_alloc_qe(ctrl->device->dev, &ctrl->async_event_sqe,
884                         sizeof(struct nvme_command), DMA_TO_DEVICE);
885         if (error)
886                 goto out_free_queue;
887
888         if (new) {
889                 error = nvme_rdma_alloc_admin_tag_set(&ctrl->ctrl);
890                 if (error)
891                         goto out_free_async_qe;
892
893                 ctrl->ctrl.fabrics_q = blk_mq_init_queue(&ctrl->admin_tag_set);
894                 if (IS_ERR(ctrl->ctrl.fabrics_q)) {
895                         error = PTR_ERR(ctrl->ctrl.fabrics_q);
896                         goto out_free_tagset;
897                 }
898
899                 ctrl->ctrl.admin_q = blk_mq_init_queue(&ctrl->admin_tag_set);
900                 if (IS_ERR(ctrl->ctrl.admin_q)) {
901                         error = PTR_ERR(ctrl->ctrl.admin_q);
902                         goto out_cleanup_fabrics_q;
903                 }
904         }
905
906         error = nvme_rdma_start_queue(ctrl, 0);
907         if (error)
908                 goto out_cleanup_queue;
909
910         error = nvme_enable_ctrl(&ctrl->ctrl);
911         if (error)
912                 goto out_stop_queue;
913
914         ctrl->ctrl.max_segments = ctrl->max_fr_pages;
915         ctrl->ctrl.max_hw_sectors = ctrl->max_fr_pages << (ilog2(SZ_4K) - 9);
916         if (pi_capable)
917                 ctrl->ctrl.max_integrity_segments = ctrl->max_fr_pages;
918         else
919                 ctrl->ctrl.max_integrity_segments = 0;
920
921         nvme_start_admin_queue(&ctrl->ctrl);
922
923         error = nvme_init_ctrl_finish(&ctrl->ctrl);
924         if (error)
925                 goto out_quiesce_queue;
926
927         return 0;
928
929 out_quiesce_queue:
930         nvme_stop_admin_queue(&ctrl->ctrl);
931         blk_sync_queue(ctrl->ctrl.admin_q);
932 out_stop_queue:
933         nvme_rdma_stop_queue(&ctrl->queues[0]);
934         nvme_cancel_admin_tagset(&ctrl->ctrl);
935 out_cleanup_queue:
936         if (new)
937                 blk_mq_destroy_queue(ctrl->ctrl.admin_q);
938 out_cleanup_fabrics_q:
939         if (new)
940                 blk_mq_destroy_queue(ctrl->ctrl.fabrics_q);
941 out_free_tagset:
942         if (new)
943                 blk_mq_free_tag_set(ctrl->ctrl.admin_tagset);
944 out_free_async_qe:
945         if (ctrl->async_event_sqe.data) {
946                 nvme_rdma_free_qe(ctrl->device->dev, &ctrl->async_event_sqe,
947                         sizeof(struct nvme_command), DMA_TO_DEVICE);
948                 ctrl->async_event_sqe.data = NULL;
949         }
950 out_free_queue:
951         nvme_rdma_free_queue(&ctrl->queues[0]);
952         return error;
953 }
954
955 static void nvme_rdma_destroy_io_queues(struct nvme_rdma_ctrl *ctrl,
956                 bool remove)
957 {
958         if (remove) {
959                 blk_mq_destroy_queue(ctrl->ctrl.connect_q);
960                 blk_mq_free_tag_set(ctrl->ctrl.tagset);
961         }
962         nvme_rdma_free_io_queues(ctrl);
963 }
964
965 static int nvme_rdma_configure_io_queues(struct nvme_rdma_ctrl *ctrl, bool new)
966 {
967         int ret;
968
969         ret = nvme_rdma_alloc_io_queues(ctrl);
970         if (ret)
971                 return ret;
972
973         if (new) {
974                 ret = nvme_rdma_alloc_tag_set(&ctrl->ctrl);
975                 if (ret)
976                         goto out_free_io_queues;
977
978                 ret = nvme_ctrl_init_connect_q(&(ctrl->ctrl));
979                 if (ret)
980                         goto out_free_tag_set;
981         }
982
983         ret = nvme_rdma_start_io_queues(ctrl);
984         if (ret)
985                 goto out_cleanup_connect_q;
986
987         if (!new) {
988                 nvme_start_queues(&ctrl->ctrl);
989                 if (!nvme_wait_freeze_timeout(&ctrl->ctrl, NVME_IO_TIMEOUT)) {
990                         /*
991                          * If we timed out waiting for freeze we are likely to
992                          * be stuck.  Fail the controller initialization just
993                          * to be safe.
994                          */
995                         ret = -ENODEV;
996                         goto out_wait_freeze_timed_out;
997                 }
998                 blk_mq_update_nr_hw_queues(ctrl->ctrl.tagset,
999                         ctrl->ctrl.queue_count - 1);
1000                 nvme_unfreeze(&ctrl->ctrl);
1001         }
1002
1003         return 0;
1004
1005 out_wait_freeze_timed_out:
1006         nvme_stop_queues(&ctrl->ctrl);
1007         nvme_sync_io_queues(&ctrl->ctrl);
1008         nvme_rdma_stop_io_queues(ctrl);
1009 out_cleanup_connect_q:
1010         nvme_cancel_tagset(&ctrl->ctrl);
1011         if (new)
1012                 blk_mq_destroy_queue(ctrl->ctrl.connect_q);
1013 out_free_tag_set:
1014         if (new)
1015                 blk_mq_free_tag_set(ctrl->ctrl.tagset);
1016 out_free_io_queues:
1017         nvme_rdma_free_io_queues(ctrl);
1018         return ret;
1019 }
1020
1021 static void nvme_rdma_teardown_admin_queue(struct nvme_rdma_ctrl *ctrl,
1022                 bool remove)
1023 {
1024         nvme_stop_admin_queue(&ctrl->ctrl);
1025         blk_sync_queue(ctrl->ctrl.admin_q);
1026         nvme_rdma_stop_queue(&ctrl->queues[0]);
1027         nvme_cancel_admin_tagset(&ctrl->ctrl);
1028         if (remove)
1029                 nvme_start_admin_queue(&ctrl->ctrl);
1030         nvme_rdma_destroy_admin_queue(ctrl, remove);
1031 }
1032
1033 static void nvme_rdma_teardown_io_queues(struct nvme_rdma_ctrl *ctrl,
1034                 bool remove)
1035 {
1036         if (ctrl->ctrl.queue_count > 1) {
1037                 nvme_start_freeze(&ctrl->ctrl);
1038                 nvme_stop_queues(&ctrl->ctrl);
1039                 nvme_sync_io_queues(&ctrl->ctrl);
1040                 nvme_rdma_stop_io_queues(ctrl);
1041                 nvme_cancel_tagset(&ctrl->ctrl);
1042                 if (remove)
1043                         nvme_start_queues(&ctrl->ctrl);
1044                 nvme_rdma_destroy_io_queues(ctrl, remove);
1045         }
1046 }
1047
1048 static void nvme_rdma_stop_ctrl(struct nvme_ctrl *nctrl)
1049 {
1050         struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
1051
1052         cancel_work_sync(&ctrl->err_work);
1053         cancel_delayed_work_sync(&ctrl->reconnect_work);
1054 }
1055
1056 static void nvme_rdma_free_ctrl(struct nvme_ctrl *nctrl)
1057 {
1058         struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl);
1059
1060         if (list_empty(&ctrl->list))
1061                 goto free_ctrl;
1062
1063         mutex_lock(&nvme_rdma_ctrl_mutex);
1064         list_del(&ctrl->list);
1065         mutex_unlock(&nvme_rdma_ctrl_mutex);
1066
1067         nvmf_free_options(nctrl->opts);
1068 free_ctrl:
1069         kfree(ctrl->queues);
1070         kfree(ctrl);
1071 }
1072
1073 static void nvme_rdma_reconnect_or_remove(struct nvme_rdma_ctrl *ctrl)
1074 {
1075         /* If we are resetting/deleting then do nothing */
1076         if (ctrl->ctrl.state != NVME_CTRL_CONNECTING) {
1077                 WARN_ON_ONCE(ctrl->ctrl.state == NVME_CTRL_NEW ||
1078                         ctrl->ctrl.state == NVME_CTRL_LIVE);
1079                 return;
1080         }
1081
1082         if (nvmf_should_reconnect(&ctrl->ctrl)) {
1083                 dev_info(ctrl->ctrl.device, "Reconnecting in %d seconds...\n",
1084                         ctrl->ctrl.opts->reconnect_delay);
1085                 queue_delayed_work(nvme_wq, &ctrl->reconnect_work,
1086                                 ctrl->ctrl.opts->reconnect_delay * HZ);
1087         } else {
1088                 nvme_delete_ctrl(&ctrl->ctrl);
1089         }
1090 }
1091
1092 static int nvme_rdma_setup_ctrl(struct nvme_rdma_ctrl *ctrl, bool new)
1093 {
1094         int ret;
1095         bool changed;
1096
1097         ret = nvme_rdma_configure_admin_queue(ctrl, new);
1098         if (ret)
1099                 return ret;
1100
1101         if (ctrl->ctrl.icdoff) {
1102                 ret = -EOPNOTSUPP;
1103                 dev_err(ctrl->ctrl.device, "icdoff is not supported!\n");
1104                 goto destroy_admin;
1105         }
1106
1107         if (!(ctrl->ctrl.sgls & (1 << 2))) {
1108                 ret = -EOPNOTSUPP;
1109                 dev_err(ctrl->ctrl.device,
1110                         "Mandatory keyed sgls are not supported!\n");
1111                 goto destroy_admin;
1112         }
1113
1114         if (ctrl->ctrl.opts->queue_size > ctrl->ctrl.sqsize + 1) {
1115                 dev_warn(ctrl->ctrl.device,
1116                         "queue_size %zu > ctrl sqsize %u, clamping down\n",
1117                         ctrl->ctrl.opts->queue_size, ctrl->ctrl.sqsize + 1);
1118         }
1119
1120         if (ctrl->ctrl.sqsize + 1 > NVME_RDMA_MAX_QUEUE_SIZE) {
1121                 dev_warn(ctrl->ctrl.device,
1122                         "ctrl sqsize %u > max queue size %u, clamping down\n",
1123                         ctrl->ctrl.sqsize + 1, NVME_RDMA_MAX_QUEUE_SIZE);
1124                 ctrl->ctrl.sqsize = NVME_RDMA_MAX_QUEUE_SIZE - 1;
1125         }
1126
1127         if (ctrl->ctrl.sqsize + 1 > ctrl->ctrl.maxcmd) {
1128                 dev_warn(ctrl->ctrl.device,
1129                         "sqsize %u > ctrl maxcmd %u, clamping down\n",
1130                         ctrl->ctrl.sqsize + 1, ctrl->ctrl.maxcmd);
1131                 ctrl->ctrl.sqsize = ctrl->ctrl.maxcmd - 1;
1132         }
1133
1134         if (ctrl->ctrl.sgls & (1 << 20))
1135                 ctrl->use_inline_data = true;
1136
1137         if (ctrl->ctrl.queue_count > 1) {
1138                 ret = nvme_rdma_configure_io_queues(ctrl, new);
1139                 if (ret)
1140                         goto destroy_admin;
1141         }
1142
1143         changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE);
1144         if (!changed) {
1145                 /*
1146                  * state change failure is ok if we started ctrl delete,
1147                  * unless we're during creation of a new controller to
1148                  * avoid races with teardown flow.
1149                  */
1150                 WARN_ON_ONCE(ctrl->ctrl.state != NVME_CTRL_DELETING &&
1151                              ctrl->ctrl.state != NVME_CTRL_DELETING_NOIO);
1152                 WARN_ON_ONCE(new);
1153                 ret = -EINVAL;
1154                 goto destroy_io;
1155         }
1156
1157         nvme_start_ctrl(&ctrl->ctrl);
1158         return 0;
1159
1160 destroy_io:
1161         if (ctrl->ctrl.queue_count > 1) {
1162                 nvme_stop_queues(&ctrl->ctrl);
1163                 nvme_sync_io_queues(&ctrl->ctrl);
1164                 nvme_rdma_stop_io_queues(ctrl);
1165                 nvme_cancel_tagset(&ctrl->ctrl);
1166                 nvme_rdma_destroy_io_queues(ctrl, new);
1167         }
1168 destroy_admin:
1169         nvme_stop_admin_queue(&ctrl->ctrl);
1170         blk_sync_queue(ctrl->ctrl.admin_q);
1171         nvme_rdma_stop_queue(&ctrl->queues[0]);
1172         nvme_cancel_admin_tagset(&ctrl->ctrl);
1173         nvme_rdma_destroy_admin_queue(ctrl, new);
1174         return ret;
1175 }
1176
1177 static void nvme_rdma_reconnect_ctrl_work(struct work_struct *work)
1178 {
1179         struct nvme_rdma_ctrl *ctrl = container_of(to_delayed_work(work),
1180                         struct nvme_rdma_ctrl, reconnect_work);
1181
1182         ++ctrl->ctrl.nr_reconnects;
1183
1184         if (nvme_rdma_setup_ctrl(ctrl, false))
1185                 goto requeue;
1186
1187         dev_info(ctrl->ctrl.device, "Successfully reconnected (%d attempts)\n",
1188                         ctrl->ctrl.nr_reconnects);
1189
1190         ctrl->ctrl.nr_reconnects = 0;
1191
1192         return;
1193
1194 requeue:
1195         dev_info(ctrl->ctrl.device, "Failed reconnect attempt %d\n",
1196                         ctrl->ctrl.nr_reconnects);
1197         nvme_rdma_reconnect_or_remove(ctrl);
1198 }
1199
1200 static void nvme_rdma_error_recovery_work(struct work_struct *work)
1201 {
1202         struct nvme_rdma_ctrl *ctrl = container_of(work,
1203                         struct nvme_rdma_ctrl, err_work);
1204
1205         nvme_auth_stop(&ctrl->ctrl);
1206         nvme_stop_keep_alive(&ctrl->ctrl);
1207         flush_work(&ctrl->ctrl.async_event_work);
1208         nvme_rdma_teardown_io_queues(ctrl, false);
1209         nvme_start_queues(&ctrl->ctrl);
1210         nvme_rdma_teardown_admin_queue(ctrl, false);
1211         nvme_start_admin_queue(&ctrl->ctrl);
1212
1213         if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
1214                 /* state change failure is ok if we started ctrl delete */
1215                 WARN_ON_ONCE(ctrl->ctrl.state != NVME_CTRL_DELETING &&
1216                              ctrl->ctrl.state != NVME_CTRL_DELETING_NOIO);
1217                 return;
1218         }
1219
1220         nvme_rdma_reconnect_or_remove(ctrl);
1221 }
1222
1223 static void nvme_rdma_error_recovery(struct nvme_rdma_ctrl *ctrl)
1224 {
1225         if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RESETTING))
1226                 return;
1227
1228         dev_warn(ctrl->ctrl.device, "starting error recovery\n");
1229         queue_work(nvme_reset_wq, &ctrl->err_work);
1230 }
1231
1232 static void nvme_rdma_end_request(struct nvme_rdma_request *req)
1233 {
1234         struct request *rq = blk_mq_rq_from_pdu(req);
1235
1236         if (!refcount_dec_and_test(&req->ref))
1237                 return;
1238         if (!nvme_try_complete_req(rq, req->status, req->result))
1239                 nvme_rdma_complete_rq(rq);
1240 }
1241
1242 static void nvme_rdma_wr_error(struct ib_cq *cq, struct ib_wc *wc,
1243                 const char *op)
1244 {
1245         struct nvme_rdma_queue *queue = wc->qp->qp_context;
1246         struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1247
1248         if (ctrl->ctrl.state == NVME_CTRL_LIVE)
1249                 dev_info(ctrl->ctrl.device,
1250                              "%s for CQE 0x%p failed with status %s (%d)\n",
1251                              op, wc->wr_cqe,
1252                              ib_wc_status_msg(wc->status), wc->status);
1253         nvme_rdma_error_recovery(ctrl);
1254 }
1255
1256 static void nvme_rdma_memreg_done(struct ib_cq *cq, struct ib_wc *wc)
1257 {
1258         if (unlikely(wc->status != IB_WC_SUCCESS))
1259                 nvme_rdma_wr_error(cq, wc, "MEMREG");
1260 }
1261
1262 static void nvme_rdma_inv_rkey_done(struct ib_cq *cq, struct ib_wc *wc)
1263 {
1264         struct nvme_rdma_request *req =
1265                 container_of(wc->wr_cqe, struct nvme_rdma_request, reg_cqe);
1266
1267         if (unlikely(wc->status != IB_WC_SUCCESS))
1268                 nvme_rdma_wr_error(cq, wc, "LOCAL_INV");
1269         else
1270                 nvme_rdma_end_request(req);
1271 }
1272
1273 static int nvme_rdma_inv_rkey(struct nvme_rdma_queue *queue,
1274                 struct nvme_rdma_request *req)
1275 {
1276         struct ib_send_wr wr = {
1277                 .opcode             = IB_WR_LOCAL_INV,
1278                 .next               = NULL,
1279                 .num_sge            = 0,
1280                 .send_flags         = IB_SEND_SIGNALED,
1281                 .ex.invalidate_rkey = req->mr->rkey,
1282         };
1283
1284         req->reg_cqe.done = nvme_rdma_inv_rkey_done;
1285         wr.wr_cqe = &req->reg_cqe;
1286
1287         return ib_post_send(queue->qp, &wr, NULL);
1288 }
1289
1290 static void nvme_rdma_dma_unmap_req(struct ib_device *ibdev, struct request *rq)
1291 {
1292         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1293
1294         if (blk_integrity_rq(rq)) {
1295                 ib_dma_unmap_sg(ibdev, req->metadata_sgl->sg_table.sgl,
1296                                 req->metadata_sgl->nents, rq_dma_dir(rq));
1297                 sg_free_table_chained(&req->metadata_sgl->sg_table,
1298                                       NVME_INLINE_METADATA_SG_CNT);
1299         }
1300
1301         ib_dma_unmap_sg(ibdev, req->data_sgl.sg_table.sgl, req->data_sgl.nents,
1302                         rq_dma_dir(rq));
1303         sg_free_table_chained(&req->data_sgl.sg_table, NVME_INLINE_SG_CNT);
1304 }
1305
1306 static void nvme_rdma_unmap_data(struct nvme_rdma_queue *queue,
1307                 struct request *rq)
1308 {
1309         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1310         struct nvme_rdma_device *dev = queue->device;
1311         struct ib_device *ibdev = dev->dev;
1312         struct list_head *pool = &queue->qp->rdma_mrs;
1313
1314         if (!blk_rq_nr_phys_segments(rq))
1315                 return;
1316
1317         if (req->use_sig_mr)
1318                 pool = &queue->qp->sig_mrs;
1319
1320         if (req->mr) {
1321                 ib_mr_pool_put(queue->qp, pool, req->mr);
1322                 req->mr = NULL;
1323         }
1324
1325         nvme_rdma_dma_unmap_req(ibdev, rq);
1326 }
1327
1328 static int nvme_rdma_set_sg_null(struct nvme_command *c)
1329 {
1330         struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1331
1332         sg->addr = 0;
1333         put_unaligned_le24(0, sg->length);
1334         put_unaligned_le32(0, sg->key);
1335         sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1336         return 0;
1337 }
1338
1339 static int nvme_rdma_map_sg_inline(struct nvme_rdma_queue *queue,
1340                 struct nvme_rdma_request *req, struct nvme_command *c,
1341                 int count)
1342 {
1343         struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
1344         struct ib_sge *sge = &req->sge[1];
1345         struct scatterlist *sgl;
1346         u32 len = 0;
1347         int i;
1348
1349         for_each_sg(req->data_sgl.sg_table.sgl, sgl, count, i) {
1350                 sge->addr = sg_dma_address(sgl);
1351                 sge->length = sg_dma_len(sgl);
1352                 sge->lkey = queue->device->pd->local_dma_lkey;
1353                 len += sge->length;
1354                 sge++;
1355         }
1356
1357         sg->addr = cpu_to_le64(queue->ctrl->ctrl.icdoff);
1358         sg->length = cpu_to_le32(len);
1359         sg->type = (NVME_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_OFFSET;
1360
1361         req->num_sge += count;
1362         return 0;
1363 }
1364
1365 static int nvme_rdma_map_sg_single(struct nvme_rdma_queue *queue,
1366                 struct nvme_rdma_request *req, struct nvme_command *c)
1367 {
1368         struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1369
1370         sg->addr = cpu_to_le64(sg_dma_address(req->data_sgl.sg_table.sgl));
1371         put_unaligned_le24(sg_dma_len(req->data_sgl.sg_table.sgl), sg->length);
1372         put_unaligned_le32(queue->device->pd->unsafe_global_rkey, sg->key);
1373         sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1374         return 0;
1375 }
1376
1377 static int nvme_rdma_map_sg_fr(struct nvme_rdma_queue *queue,
1378                 struct nvme_rdma_request *req, struct nvme_command *c,
1379                 int count)
1380 {
1381         struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1382         int nr;
1383
1384         req->mr = ib_mr_pool_get(queue->qp, &queue->qp->rdma_mrs);
1385         if (WARN_ON_ONCE(!req->mr))
1386                 return -EAGAIN;
1387
1388         /*
1389          * Align the MR to a 4K page size to match the ctrl page size and
1390          * the block virtual boundary.
1391          */
1392         nr = ib_map_mr_sg(req->mr, req->data_sgl.sg_table.sgl, count, NULL,
1393                           SZ_4K);
1394         if (unlikely(nr < count)) {
1395                 ib_mr_pool_put(queue->qp, &queue->qp->rdma_mrs, req->mr);
1396                 req->mr = NULL;
1397                 if (nr < 0)
1398                         return nr;
1399                 return -EINVAL;
1400         }
1401
1402         ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1403
1404         req->reg_cqe.done = nvme_rdma_memreg_done;
1405         memset(&req->reg_wr, 0, sizeof(req->reg_wr));
1406         req->reg_wr.wr.opcode = IB_WR_REG_MR;
1407         req->reg_wr.wr.wr_cqe = &req->reg_cqe;
1408         req->reg_wr.wr.num_sge = 0;
1409         req->reg_wr.mr = req->mr;
1410         req->reg_wr.key = req->mr->rkey;
1411         req->reg_wr.access = IB_ACCESS_LOCAL_WRITE |
1412                              IB_ACCESS_REMOTE_READ |
1413                              IB_ACCESS_REMOTE_WRITE;
1414
1415         sg->addr = cpu_to_le64(req->mr->iova);
1416         put_unaligned_le24(req->mr->length, sg->length);
1417         put_unaligned_le32(req->mr->rkey, sg->key);
1418         sg->type = (NVME_KEY_SGL_FMT_DATA_DESC << 4) |
1419                         NVME_SGL_FMT_INVALIDATE;
1420
1421         return 0;
1422 }
1423
1424 static void nvme_rdma_set_sig_domain(struct blk_integrity *bi,
1425                 struct nvme_command *cmd, struct ib_sig_domain *domain,
1426                 u16 control, u8 pi_type)
1427 {
1428         domain->sig_type = IB_SIG_TYPE_T10_DIF;
1429         domain->sig.dif.bg_type = IB_T10DIF_CRC;
1430         domain->sig.dif.pi_interval = 1 << bi->interval_exp;
1431         domain->sig.dif.ref_tag = le32_to_cpu(cmd->rw.reftag);
1432         if (control & NVME_RW_PRINFO_PRCHK_REF)
1433                 domain->sig.dif.ref_remap = true;
1434
1435         domain->sig.dif.app_tag = le16_to_cpu(cmd->rw.apptag);
1436         domain->sig.dif.apptag_check_mask = le16_to_cpu(cmd->rw.appmask);
1437         domain->sig.dif.app_escape = true;
1438         if (pi_type == NVME_NS_DPS_PI_TYPE3)
1439                 domain->sig.dif.ref_escape = true;
1440 }
1441
1442 static void nvme_rdma_set_sig_attrs(struct blk_integrity *bi,
1443                 struct nvme_command *cmd, struct ib_sig_attrs *sig_attrs,
1444                 u8 pi_type)
1445 {
1446         u16 control = le16_to_cpu(cmd->rw.control);
1447
1448         memset(sig_attrs, 0, sizeof(*sig_attrs));
1449         if (control & NVME_RW_PRINFO_PRACT) {
1450                 /* for WRITE_INSERT/READ_STRIP no memory domain */
1451                 sig_attrs->mem.sig_type = IB_SIG_TYPE_NONE;
1452                 nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->wire, control,
1453                                          pi_type);
1454                 /* Clear the PRACT bit since HCA will generate/verify the PI */
1455                 control &= ~NVME_RW_PRINFO_PRACT;
1456                 cmd->rw.control = cpu_to_le16(control);
1457         } else {
1458                 /* for WRITE_PASS/READ_PASS both wire/memory domains exist */
1459                 nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->wire, control,
1460                                          pi_type);
1461                 nvme_rdma_set_sig_domain(bi, cmd, &sig_attrs->mem, control,
1462                                          pi_type);
1463         }
1464 }
1465
1466 static void nvme_rdma_set_prot_checks(struct nvme_command *cmd, u8 *mask)
1467 {
1468         *mask = 0;
1469         if (le16_to_cpu(cmd->rw.control) & NVME_RW_PRINFO_PRCHK_REF)
1470                 *mask |= IB_SIG_CHECK_REFTAG;
1471         if (le16_to_cpu(cmd->rw.control) & NVME_RW_PRINFO_PRCHK_GUARD)
1472                 *mask |= IB_SIG_CHECK_GUARD;
1473 }
1474
1475 static void nvme_rdma_sig_done(struct ib_cq *cq, struct ib_wc *wc)
1476 {
1477         if (unlikely(wc->status != IB_WC_SUCCESS))
1478                 nvme_rdma_wr_error(cq, wc, "SIG");
1479 }
1480
1481 static int nvme_rdma_map_sg_pi(struct nvme_rdma_queue *queue,
1482                 struct nvme_rdma_request *req, struct nvme_command *c,
1483                 int count, int pi_count)
1484 {
1485         struct nvme_rdma_sgl *sgl = &req->data_sgl;
1486         struct ib_reg_wr *wr = &req->reg_wr;
1487         struct request *rq = blk_mq_rq_from_pdu(req);
1488         struct nvme_ns *ns = rq->q->queuedata;
1489         struct bio *bio = rq->bio;
1490         struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl;
1491         int nr;
1492
1493         req->mr = ib_mr_pool_get(queue->qp, &queue->qp->sig_mrs);
1494         if (WARN_ON_ONCE(!req->mr))
1495                 return -EAGAIN;
1496
1497         nr = ib_map_mr_sg_pi(req->mr, sgl->sg_table.sgl, count, NULL,
1498                              req->metadata_sgl->sg_table.sgl, pi_count, NULL,
1499                              SZ_4K);
1500         if (unlikely(nr))
1501                 goto mr_put;
1502
1503         nvme_rdma_set_sig_attrs(blk_get_integrity(bio->bi_bdev->bd_disk), c,
1504                                 req->mr->sig_attrs, ns->pi_type);
1505         nvme_rdma_set_prot_checks(c, &req->mr->sig_attrs->check_mask);
1506
1507         ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1508
1509         req->reg_cqe.done = nvme_rdma_sig_done;
1510         memset(wr, 0, sizeof(*wr));
1511         wr->wr.opcode = IB_WR_REG_MR_INTEGRITY;
1512         wr->wr.wr_cqe = &req->reg_cqe;
1513         wr->wr.num_sge = 0;
1514         wr->wr.send_flags = 0;
1515         wr->mr = req->mr;
1516         wr->key = req->mr->rkey;
1517         wr->access = IB_ACCESS_LOCAL_WRITE |
1518                      IB_ACCESS_REMOTE_READ |
1519                      IB_ACCESS_REMOTE_WRITE;
1520
1521         sg->addr = cpu_to_le64(req->mr->iova);
1522         put_unaligned_le24(req->mr->length, sg->length);
1523         put_unaligned_le32(req->mr->rkey, sg->key);
1524         sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4;
1525
1526         return 0;
1527
1528 mr_put:
1529         ib_mr_pool_put(queue->qp, &queue->qp->sig_mrs, req->mr);
1530         req->mr = NULL;
1531         if (nr < 0)
1532                 return nr;
1533         return -EINVAL;
1534 }
1535
1536 static int nvme_rdma_dma_map_req(struct ib_device *ibdev, struct request *rq,
1537                 int *count, int *pi_count)
1538 {
1539         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1540         int ret;
1541
1542         req->data_sgl.sg_table.sgl = (struct scatterlist *)(req + 1);
1543         ret = sg_alloc_table_chained(&req->data_sgl.sg_table,
1544                         blk_rq_nr_phys_segments(rq), req->data_sgl.sg_table.sgl,
1545                         NVME_INLINE_SG_CNT);
1546         if (ret)
1547                 return -ENOMEM;
1548
1549         req->data_sgl.nents = blk_rq_map_sg(rq->q, rq,
1550                                             req->data_sgl.sg_table.sgl);
1551
1552         *count = ib_dma_map_sg(ibdev, req->data_sgl.sg_table.sgl,
1553                                req->data_sgl.nents, rq_dma_dir(rq));
1554         if (unlikely(*count <= 0)) {
1555                 ret = -EIO;
1556                 goto out_free_table;
1557         }
1558
1559         if (blk_integrity_rq(rq)) {
1560                 req->metadata_sgl->sg_table.sgl =
1561                         (struct scatterlist *)(req->metadata_sgl + 1);
1562                 ret = sg_alloc_table_chained(&req->metadata_sgl->sg_table,
1563                                 blk_rq_count_integrity_sg(rq->q, rq->bio),
1564                                 req->metadata_sgl->sg_table.sgl,
1565                                 NVME_INLINE_METADATA_SG_CNT);
1566                 if (unlikely(ret)) {
1567                         ret = -ENOMEM;
1568                         goto out_unmap_sg;
1569                 }
1570
1571                 req->metadata_sgl->nents = blk_rq_map_integrity_sg(rq->q,
1572                                 rq->bio, req->metadata_sgl->sg_table.sgl);
1573                 *pi_count = ib_dma_map_sg(ibdev,
1574                                           req->metadata_sgl->sg_table.sgl,
1575                                           req->metadata_sgl->nents,
1576                                           rq_dma_dir(rq));
1577                 if (unlikely(*pi_count <= 0)) {
1578                         ret = -EIO;
1579                         goto out_free_pi_table;
1580                 }
1581         }
1582
1583         return 0;
1584
1585 out_free_pi_table:
1586         sg_free_table_chained(&req->metadata_sgl->sg_table,
1587                               NVME_INLINE_METADATA_SG_CNT);
1588 out_unmap_sg:
1589         ib_dma_unmap_sg(ibdev, req->data_sgl.sg_table.sgl, req->data_sgl.nents,
1590                         rq_dma_dir(rq));
1591 out_free_table:
1592         sg_free_table_chained(&req->data_sgl.sg_table, NVME_INLINE_SG_CNT);
1593         return ret;
1594 }
1595
1596 static int nvme_rdma_map_data(struct nvme_rdma_queue *queue,
1597                 struct request *rq, struct nvme_command *c)
1598 {
1599         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
1600         struct nvme_rdma_device *dev = queue->device;
1601         struct ib_device *ibdev = dev->dev;
1602         int pi_count = 0;
1603         int count, ret;
1604
1605         req->num_sge = 1;
1606         refcount_set(&req->ref, 2); /* send and recv completions */
1607
1608         c->common.flags |= NVME_CMD_SGL_METABUF;
1609
1610         if (!blk_rq_nr_phys_segments(rq))
1611                 return nvme_rdma_set_sg_null(c);
1612
1613         ret = nvme_rdma_dma_map_req(ibdev, rq, &count, &pi_count);
1614         if (unlikely(ret))
1615                 return ret;
1616
1617         if (req->use_sig_mr) {
1618                 ret = nvme_rdma_map_sg_pi(queue, req, c, count, pi_count);
1619                 goto out;
1620         }
1621
1622         if (count <= dev->num_inline_segments) {
1623                 if (rq_data_dir(rq) == WRITE && nvme_rdma_queue_idx(queue) &&
1624                     queue->ctrl->use_inline_data &&
1625                     blk_rq_payload_bytes(rq) <=
1626                                 nvme_rdma_inline_data_size(queue)) {
1627                         ret = nvme_rdma_map_sg_inline(queue, req, c, count);
1628                         goto out;
1629                 }
1630
1631                 if (count == 1 && dev->pd->flags & IB_PD_UNSAFE_GLOBAL_RKEY) {
1632                         ret = nvme_rdma_map_sg_single(queue, req, c);
1633                         goto out;
1634                 }
1635         }
1636
1637         ret = nvme_rdma_map_sg_fr(queue, req, c, count);
1638 out:
1639         if (unlikely(ret))
1640                 goto out_dma_unmap_req;
1641
1642         return 0;
1643
1644 out_dma_unmap_req:
1645         nvme_rdma_dma_unmap_req(ibdev, rq);
1646         return ret;
1647 }
1648
1649 static void nvme_rdma_send_done(struct ib_cq *cq, struct ib_wc *wc)
1650 {
1651         struct nvme_rdma_qe *qe =
1652                 container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe);
1653         struct nvme_rdma_request *req =
1654                 container_of(qe, struct nvme_rdma_request, sqe);
1655
1656         if (unlikely(wc->status != IB_WC_SUCCESS))
1657                 nvme_rdma_wr_error(cq, wc, "SEND");
1658         else
1659                 nvme_rdma_end_request(req);
1660 }
1661
1662 static int nvme_rdma_post_send(struct nvme_rdma_queue *queue,
1663                 struct nvme_rdma_qe *qe, struct ib_sge *sge, u32 num_sge,
1664                 struct ib_send_wr *first)
1665 {
1666         struct ib_send_wr wr;
1667         int ret;
1668
1669         sge->addr   = qe->dma;
1670         sge->length = sizeof(struct nvme_command);
1671         sge->lkey   = queue->device->pd->local_dma_lkey;
1672
1673         wr.next       = NULL;
1674         wr.wr_cqe     = &qe->cqe;
1675         wr.sg_list    = sge;
1676         wr.num_sge    = num_sge;
1677         wr.opcode     = IB_WR_SEND;
1678         wr.send_flags = IB_SEND_SIGNALED;
1679
1680         if (first)
1681                 first->next = &wr;
1682         else
1683                 first = &wr;
1684
1685         ret = ib_post_send(queue->qp, first, NULL);
1686         if (unlikely(ret)) {
1687                 dev_err(queue->ctrl->ctrl.device,
1688                              "%s failed with error code %d\n", __func__, ret);
1689         }
1690         return ret;
1691 }
1692
1693 static int nvme_rdma_post_recv(struct nvme_rdma_queue *queue,
1694                 struct nvme_rdma_qe *qe)
1695 {
1696         struct ib_recv_wr wr;
1697         struct ib_sge list;
1698         int ret;
1699
1700         list.addr   = qe->dma;
1701         list.length = sizeof(struct nvme_completion);
1702         list.lkey   = queue->device->pd->local_dma_lkey;
1703
1704         qe->cqe.done = nvme_rdma_recv_done;
1705
1706         wr.next     = NULL;
1707         wr.wr_cqe   = &qe->cqe;
1708         wr.sg_list  = &list;
1709         wr.num_sge  = 1;
1710
1711         ret = ib_post_recv(queue->qp, &wr, NULL);
1712         if (unlikely(ret)) {
1713                 dev_err(queue->ctrl->ctrl.device,
1714                         "%s failed with error code %d\n", __func__, ret);
1715         }
1716         return ret;
1717 }
1718
1719 static struct blk_mq_tags *nvme_rdma_tagset(struct nvme_rdma_queue *queue)
1720 {
1721         u32 queue_idx = nvme_rdma_queue_idx(queue);
1722
1723         if (queue_idx == 0)
1724                 return queue->ctrl->admin_tag_set.tags[queue_idx];
1725         return queue->ctrl->tag_set.tags[queue_idx - 1];
1726 }
1727
1728 static void nvme_rdma_async_done(struct ib_cq *cq, struct ib_wc *wc)
1729 {
1730         if (unlikely(wc->status != IB_WC_SUCCESS))
1731                 nvme_rdma_wr_error(cq, wc, "ASYNC");
1732 }
1733
1734 static void nvme_rdma_submit_async_event(struct nvme_ctrl *arg)
1735 {
1736         struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(arg);
1737         struct nvme_rdma_queue *queue = &ctrl->queues[0];
1738         struct ib_device *dev = queue->device->dev;
1739         struct nvme_rdma_qe *sqe = &ctrl->async_event_sqe;
1740         struct nvme_command *cmd = sqe->data;
1741         struct ib_sge sge;
1742         int ret;
1743
1744         ib_dma_sync_single_for_cpu(dev, sqe->dma, sizeof(*cmd), DMA_TO_DEVICE);
1745
1746         memset(cmd, 0, sizeof(*cmd));
1747         cmd->common.opcode = nvme_admin_async_event;
1748         cmd->common.command_id = NVME_AQ_BLK_MQ_DEPTH;
1749         cmd->common.flags |= NVME_CMD_SGL_METABUF;
1750         nvme_rdma_set_sg_null(cmd);
1751
1752         sqe->cqe.done = nvme_rdma_async_done;
1753
1754         ib_dma_sync_single_for_device(dev, sqe->dma, sizeof(*cmd),
1755                         DMA_TO_DEVICE);
1756
1757         ret = nvme_rdma_post_send(queue, sqe, &sge, 1, NULL);
1758         WARN_ON_ONCE(ret);
1759 }
1760
1761 static void nvme_rdma_process_nvme_rsp(struct nvme_rdma_queue *queue,
1762                 struct nvme_completion *cqe, struct ib_wc *wc)
1763 {
1764         struct request *rq;
1765         struct nvme_rdma_request *req;
1766
1767         rq = nvme_find_rq(nvme_rdma_tagset(queue), cqe->command_id);
1768         if (!rq) {
1769                 dev_err(queue->ctrl->ctrl.device,
1770                         "got bad command_id %#x on QP %#x\n",
1771                         cqe->command_id, queue->qp->qp_num);
1772                 nvme_rdma_error_recovery(queue->ctrl);
1773                 return;
1774         }
1775         req = blk_mq_rq_to_pdu(rq);
1776
1777         req->status = cqe->status;
1778         req->result = cqe->result;
1779
1780         if (wc->wc_flags & IB_WC_WITH_INVALIDATE) {
1781                 if (unlikely(!req->mr ||
1782                              wc->ex.invalidate_rkey != req->mr->rkey)) {
1783                         dev_err(queue->ctrl->ctrl.device,
1784                                 "Bogus remote invalidation for rkey %#x\n",
1785                                 req->mr ? req->mr->rkey : 0);
1786                         nvme_rdma_error_recovery(queue->ctrl);
1787                 }
1788         } else if (req->mr) {
1789                 int ret;
1790
1791                 ret = nvme_rdma_inv_rkey(queue, req);
1792                 if (unlikely(ret < 0)) {
1793                         dev_err(queue->ctrl->ctrl.device,
1794                                 "Queueing INV WR for rkey %#x failed (%d)\n",
1795                                 req->mr->rkey, ret);
1796                         nvme_rdma_error_recovery(queue->ctrl);
1797                 }
1798                 /* the local invalidation completion will end the request */
1799                 return;
1800         }
1801
1802         nvme_rdma_end_request(req);
1803 }
1804
1805 static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc)
1806 {
1807         struct nvme_rdma_qe *qe =
1808                 container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe);
1809         struct nvme_rdma_queue *queue = wc->qp->qp_context;
1810         struct ib_device *ibdev = queue->device->dev;
1811         struct nvme_completion *cqe = qe->data;
1812         const size_t len = sizeof(struct nvme_completion);
1813
1814         if (unlikely(wc->status != IB_WC_SUCCESS)) {
1815                 nvme_rdma_wr_error(cq, wc, "RECV");
1816                 return;
1817         }
1818
1819         /* sanity checking for received data length */
1820         if (unlikely(wc->byte_len < len)) {
1821                 dev_err(queue->ctrl->ctrl.device,
1822                         "Unexpected nvme completion length(%d)\n", wc->byte_len);
1823                 nvme_rdma_error_recovery(queue->ctrl);
1824                 return;
1825         }
1826
1827         ib_dma_sync_single_for_cpu(ibdev, qe->dma, len, DMA_FROM_DEVICE);
1828         /*
1829          * AEN requests are special as they don't time out and can
1830          * survive any kind of queue freeze and often don't respond to
1831          * aborts.  We don't even bother to allocate a struct request
1832          * for them but rather special case them here.
1833          */
1834         if (unlikely(nvme_is_aen_req(nvme_rdma_queue_idx(queue),
1835                                      cqe->command_id)))
1836                 nvme_complete_async_event(&queue->ctrl->ctrl, cqe->status,
1837                                 &cqe->result);
1838         else
1839                 nvme_rdma_process_nvme_rsp(queue, cqe, wc);
1840         ib_dma_sync_single_for_device(ibdev, qe->dma, len, DMA_FROM_DEVICE);
1841
1842         nvme_rdma_post_recv(queue, qe);
1843 }
1844
1845 static int nvme_rdma_conn_established(struct nvme_rdma_queue *queue)
1846 {
1847         int ret, i;
1848
1849         for (i = 0; i < queue->queue_size; i++) {
1850                 ret = nvme_rdma_post_recv(queue, &queue->rsp_ring[i]);
1851                 if (ret)
1852                         return ret;
1853         }
1854
1855         return 0;
1856 }
1857
1858 static int nvme_rdma_conn_rejected(struct nvme_rdma_queue *queue,
1859                 struct rdma_cm_event *ev)
1860 {
1861         struct rdma_cm_id *cm_id = queue->cm_id;
1862         int status = ev->status;
1863         const char *rej_msg;
1864         const struct nvme_rdma_cm_rej *rej_data;
1865         u8 rej_data_len;
1866
1867         rej_msg = rdma_reject_msg(cm_id, status);
1868         rej_data = rdma_consumer_reject_data(cm_id, ev, &rej_data_len);
1869
1870         if (rej_data && rej_data_len >= sizeof(u16)) {
1871                 u16 sts = le16_to_cpu(rej_data->sts);
1872
1873                 dev_err(queue->ctrl->ctrl.device,
1874                       "Connect rejected: status %d (%s) nvme status %d (%s).\n",
1875                       status, rej_msg, sts, nvme_rdma_cm_msg(sts));
1876         } else {
1877                 dev_err(queue->ctrl->ctrl.device,
1878                         "Connect rejected: status %d (%s).\n", status, rej_msg);
1879         }
1880
1881         return -ECONNRESET;
1882 }
1883
1884 static int nvme_rdma_addr_resolved(struct nvme_rdma_queue *queue)
1885 {
1886         struct nvme_ctrl *ctrl = &queue->ctrl->ctrl;
1887         int ret;
1888
1889         ret = nvme_rdma_create_queue_ib(queue);
1890         if (ret)
1891                 return ret;
1892
1893         if (ctrl->opts->tos >= 0)
1894                 rdma_set_service_type(queue->cm_id, ctrl->opts->tos);
1895         ret = rdma_resolve_route(queue->cm_id, NVME_RDMA_CM_TIMEOUT_MS);
1896         if (ret) {
1897                 dev_err(ctrl->device, "rdma_resolve_route failed (%d).\n",
1898                         queue->cm_error);
1899                 goto out_destroy_queue;
1900         }
1901
1902         return 0;
1903
1904 out_destroy_queue:
1905         nvme_rdma_destroy_queue_ib(queue);
1906         return ret;
1907 }
1908
1909 static int nvme_rdma_route_resolved(struct nvme_rdma_queue *queue)
1910 {
1911         struct nvme_rdma_ctrl *ctrl = queue->ctrl;
1912         struct rdma_conn_param param = { };
1913         struct nvme_rdma_cm_req priv = { };
1914         int ret;
1915
1916         param.qp_num = queue->qp->qp_num;
1917         param.flow_control = 1;
1918
1919         param.responder_resources = queue->device->dev->attrs.max_qp_rd_atom;
1920         /* maximum retry count */
1921         param.retry_count = 7;
1922         param.rnr_retry_count = 7;
1923         param.private_data = &priv;
1924         param.private_data_len = sizeof(priv);
1925
1926         priv.recfmt = cpu_to_le16(NVME_RDMA_CM_FMT_1_0);
1927         priv.qid = cpu_to_le16(nvme_rdma_queue_idx(queue));
1928         /*
1929          * set the admin queue depth to the minimum size
1930          * specified by the Fabrics standard.
1931          */
1932         if (priv.qid == 0) {
1933                 priv.hrqsize = cpu_to_le16(NVME_AQ_DEPTH);
1934                 priv.hsqsize = cpu_to_le16(NVME_AQ_DEPTH - 1);
1935         } else {
1936                 /*
1937                  * current interpretation of the fabrics spec
1938                  * is at minimum you make hrqsize sqsize+1, or a
1939                  * 1's based representation of sqsize.
1940                  */
1941                 priv.hrqsize = cpu_to_le16(queue->queue_size);
1942                 priv.hsqsize = cpu_to_le16(queue->ctrl->ctrl.sqsize);
1943         }
1944
1945         ret = rdma_connect_locked(queue->cm_id, &param);
1946         if (ret) {
1947                 dev_err(ctrl->ctrl.device,
1948                         "rdma_connect_locked failed (%d).\n", ret);
1949                 return ret;
1950         }
1951
1952         return 0;
1953 }
1954
1955 static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id,
1956                 struct rdma_cm_event *ev)
1957 {
1958         struct nvme_rdma_queue *queue = cm_id->context;
1959         int cm_error = 0;
1960
1961         dev_dbg(queue->ctrl->ctrl.device, "%s (%d): status %d id %p\n",
1962                 rdma_event_msg(ev->event), ev->event,
1963                 ev->status, cm_id);
1964
1965         switch (ev->event) {
1966         case RDMA_CM_EVENT_ADDR_RESOLVED:
1967                 cm_error = nvme_rdma_addr_resolved(queue);
1968                 break;
1969         case RDMA_CM_EVENT_ROUTE_RESOLVED:
1970                 cm_error = nvme_rdma_route_resolved(queue);
1971                 break;
1972         case RDMA_CM_EVENT_ESTABLISHED:
1973                 queue->cm_error = nvme_rdma_conn_established(queue);
1974                 /* complete cm_done regardless of success/failure */
1975                 complete(&queue->cm_done);
1976                 return 0;
1977         case RDMA_CM_EVENT_REJECTED:
1978                 cm_error = nvme_rdma_conn_rejected(queue, ev);
1979                 break;
1980         case RDMA_CM_EVENT_ROUTE_ERROR:
1981         case RDMA_CM_EVENT_CONNECT_ERROR:
1982         case RDMA_CM_EVENT_UNREACHABLE:
1983         case RDMA_CM_EVENT_ADDR_ERROR:
1984                 dev_dbg(queue->ctrl->ctrl.device,
1985                         "CM error event %d\n", ev->event);
1986                 cm_error = -ECONNRESET;
1987                 break;
1988         case RDMA_CM_EVENT_DISCONNECTED:
1989         case RDMA_CM_EVENT_ADDR_CHANGE:
1990         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
1991                 dev_dbg(queue->ctrl->ctrl.device,
1992                         "disconnect received - connection closed\n");
1993                 nvme_rdma_error_recovery(queue->ctrl);
1994                 break;
1995         case RDMA_CM_EVENT_DEVICE_REMOVAL:
1996                 /* device removal is handled via the ib_client API */
1997                 break;
1998         default:
1999                 dev_err(queue->ctrl->ctrl.device,
2000                         "Unexpected RDMA CM event (%d)\n", ev->event);
2001                 nvme_rdma_error_recovery(queue->ctrl);
2002                 break;
2003         }
2004
2005         if (cm_error) {
2006                 queue->cm_error = cm_error;
2007                 complete(&queue->cm_done);
2008         }
2009
2010         return 0;
2011 }
2012
2013 static void nvme_rdma_complete_timed_out(struct request *rq)
2014 {
2015         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2016         struct nvme_rdma_queue *queue = req->queue;
2017
2018         nvme_rdma_stop_queue(queue);
2019         nvmf_complete_timed_out_request(rq);
2020 }
2021
2022 static enum blk_eh_timer_return nvme_rdma_timeout(struct request *rq)
2023 {
2024         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2025         struct nvme_rdma_queue *queue = req->queue;
2026         struct nvme_rdma_ctrl *ctrl = queue->ctrl;
2027
2028         dev_warn(ctrl->ctrl.device, "I/O %d QID %d timeout\n",
2029                  rq->tag, nvme_rdma_queue_idx(queue));
2030
2031         if (ctrl->ctrl.state != NVME_CTRL_LIVE) {
2032                 /*
2033                  * If we are resetting, connecting or deleting we should
2034                  * complete immediately because we may block controller
2035                  * teardown or setup sequence
2036                  * - ctrl disable/shutdown fabrics requests
2037                  * - connect requests
2038                  * - initialization admin requests
2039                  * - I/O requests that entered after unquiescing and
2040                  *   the controller stopped responding
2041                  *
2042                  * All other requests should be cancelled by the error
2043                  * recovery work, so it's fine that we fail it here.
2044                  */
2045                 nvme_rdma_complete_timed_out(rq);
2046                 return BLK_EH_DONE;
2047         }
2048
2049         /*
2050          * LIVE state should trigger the normal error recovery which will
2051          * handle completing this request.
2052          */
2053         nvme_rdma_error_recovery(ctrl);
2054         return BLK_EH_RESET_TIMER;
2055 }
2056
2057 static blk_status_t nvme_rdma_queue_rq(struct blk_mq_hw_ctx *hctx,
2058                 const struct blk_mq_queue_data *bd)
2059 {
2060         struct nvme_ns *ns = hctx->queue->queuedata;
2061         struct nvme_rdma_queue *queue = hctx->driver_data;
2062         struct request *rq = bd->rq;
2063         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2064         struct nvme_rdma_qe *sqe = &req->sqe;
2065         struct nvme_command *c = nvme_req(rq)->cmd;
2066         struct ib_device *dev;
2067         bool queue_ready = test_bit(NVME_RDMA_Q_LIVE, &queue->flags);
2068         blk_status_t ret;
2069         int err;
2070
2071         WARN_ON_ONCE(rq->tag < 0);
2072
2073         if (!nvme_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
2074                 return nvme_fail_nonready_command(&queue->ctrl->ctrl, rq);
2075
2076         dev = queue->device->dev;
2077
2078         req->sqe.dma = ib_dma_map_single(dev, req->sqe.data,
2079                                          sizeof(struct nvme_command),
2080                                          DMA_TO_DEVICE);
2081         err = ib_dma_mapping_error(dev, req->sqe.dma);
2082         if (unlikely(err))
2083                 return BLK_STS_RESOURCE;
2084
2085         ib_dma_sync_single_for_cpu(dev, sqe->dma,
2086                         sizeof(struct nvme_command), DMA_TO_DEVICE);
2087
2088         ret = nvme_setup_cmd(ns, rq);
2089         if (ret)
2090                 goto unmap_qe;
2091
2092         blk_mq_start_request(rq);
2093
2094         if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
2095             queue->pi_support &&
2096             (c->common.opcode == nvme_cmd_write ||
2097              c->common.opcode == nvme_cmd_read) &&
2098             nvme_ns_has_pi(ns))
2099                 req->use_sig_mr = true;
2100         else
2101                 req->use_sig_mr = false;
2102
2103         err = nvme_rdma_map_data(queue, rq, c);
2104         if (unlikely(err < 0)) {
2105                 dev_err(queue->ctrl->ctrl.device,
2106                              "Failed to map data (%d)\n", err);
2107                 goto err;
2108         }
2109
2110         sqe->cqe.done = nvme_rdma_send_done;
2111
2112         ib_dma_sync_single_for_device(dev, sqe->dma,
2113                         sizeof(struct nvme_command), DMA_TO_DEVICE);
2114
2115         err = nvme_rdma_post_send(queue, sqe, req->sge, req->num_sge,
2116                         req->mr ? &req->reg_wr.wr : NULL);
2117         if (unlikely(err))
2118                 goto err_unmap;
2119
2120         return BLK_STS_OK;
2121
2122 err_unmap:
2123         nvme_rdma_unmap_data(queue, rq);
2124 err:
2125         if (err == -EIO)
2126                 ret = nvme_host_path_error(rq);
2127         else if (err == -ENOMEM || err == -EAGAIN)
2128                 ret = BLK_STS_RESOURCE;
2129         else
2130                 ret = BLK_STS_IOERR;
2131         nvme_cleanup_cmd(rq);
2132 unmap_qe:
2133         ib_dma_unmap_single(dev, req->sqe.dma, sizeof(struct nvme_command),
2134                             DMA_TO_DEVICE);
2135         return ret;
2136 }
2137
2138 static int nvme_rdma_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
2139 {
2140         struct nvme_rdma_queue *queue = hctx->driver_data;
2141
2142         return ib_process_cq_direct(queue->ib_cq, -1);
2143 }
2144
2145 static void nvme_rdma_check_pi_status(struct nvme_rdma_request *req)
2146 {
2147         struct request *rq = blk_mq_rq_from_pdu(req);
2148         struct ib_mr_status mr_status;
2149         int ret;
2150
2151         ret = ib_check_mr_status(req->mr, IB_MR_CHECK_SIG_STATUS, &mr_status);
2152         if (ret) {
2153                 pr_err("ib_check_mr_status failed, ret %d\n", ret);
2154                 nvme_req(rq)->status = NVME_SC_INVALID_PI;
2155                 return;
2156         }
2157
2158         if (mr_status.fail_status & IB_MR_CHECK_SIG_STATUS) {
2159                 switch (mr_status.sig_err.err_type) {
2160                 case IB_SIG_BAD_GUARD:
2161                         nvme_req(rq)->status = NVME_SC_GUARD_CHECK;
2162                         break;
2163                 case IB_SIG_BAD_REFTAG:
2164                         nvme_req(rq)->status = NVME_SC_REFTAG_CHECK;
2165                         break;
2166                 case IB_SIG_BAD_APPTAG:
2167                         nvme_req(rq)->status = NVME_SC_APPTAG_CHECK;
2168                         break;
2169                 }
2170                 pr_err("PI error found type %d expected 0x%x vs actual 0x%x\n",
2171                        mr_status.sig_err.err_type, mr_status.sig_err.expected,
2172                        mr_status.sig_err.actual);
2173         }
2174 }
2175
2176 static void nvme_rdma_complete_rq(struct request *rq)
2177 {
2178         struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq);
2179         struct nvme_rdma_queue *queue = req->queue;
2180         struct ib_device *ibdev = queue->device->dev;
2181
2182         if (req->use_sig_mr)
2183                 nvme_rdma_check_pi_status(req);
2184
2185         nvme_rdma_unmap_data(queue, rq);
2186         ib_dma_unmap_single(ibdev, req->sqe.dma, sizeof(struct nvme_command),
2187                             DMA_TO_DEVICE);
2188         nvme_complete_rq(rq);
2189 }
2190
2191 static int nvme_rdma_map_queues(struct blk_mq_tag_set *set)
2192 {
2193         struct nvme_rdma_ctrl *ctrl = set->driver_data;
2194         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2195
2196         if (opts->nr_write_queues && ctrl->io_queues[HCTX_TYPE_READ]) {
2197                 /* separate read/write queues */
2198                 set->map[HCTX_TYPE_DEFAULT].nr_queues =
2199                         ctrl->io_queues[HCTX_TYPE_DEFAULT];
2200                 set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2201                 set->map[HCTX_TYPE_READ].nr_queues =
2202                         ctrl->io_queues[HCTX_TYPE_READ];
2203                 set->map[HCTX_TYPE_READ].queue_offset =
2204                         ctrl->io_queues[HCTX_TYPE_DEFAULT];
2205         } else {
2206                 /* shared read/write queues */
2207                 set->map[HCTX_TYPE_DEFAULT].nr_queues =
2208                         ctrl->io_queues[HCTX_TYPE_DEFAULT];
2209                 set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2210                 set->map[HCTX_TYPE_READ].nr_queues =
2211                         ctrl->io_queues[HCTX_TYPE_DEFAULT];
2212                 set->map[HCTX_TYPE_READ].queue_offset = 0;
2213         }
2214         blk_mq_rdma_map_queues(&set->map[HCTX_TYPE_DEFAULT],
2215                         ctrl->device->dev, 0);
2216         blk_mq_rdma_map_queues(&set->map[HCTX_TYPE_READ],
2217                         ctrl->device->dev, 0);
2218
2219         if (opts->nr_poll_queues && ctrl->io_queues[HCTX_TYPE_POLL]) {
2220                 /* map dedicated poll queues only if we have queues left */
2221                 set->map[HCTX_TYPE_POLL].nr_queues =
2222                                 ctrl->io_queues[HCTX_TYPE_POLL];
2223                 set->map[HCTX_TYPE_POLL].queue_offset =
2224                         ctrl->io_queues[HCTX_TYPE_DEFAULT] +
2225                         ctrl->io_queues[HCTX_TYPE_READ];
2226                 blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]);
2227         }
2228
2229         dev_info(ctrl->ctrl.device,
2230                 "mapped %d/%d/%d default/read/poll queues.\n",
2231                 ctrl->io_queues[HCTX_TYPE_DEFAULT],
2232                 ctrl->io_queues[HCTX_TYPE_READ],
2233                 ctrl->io_queues[HCTX_TYPE_POLL]);
2234
2235         return 0;
2236 }
2237
2238 static const struct blk_mq_ops nvme_rdma_mq_ops = {
2239         .queue_rq       = nvme_rdma_queue_rq,
2240         .complete       = nvme_rdma_complete_rq,
2241         .init_request   = nvme_rdma_init_request,
2242         .exit_request   = nvme_rdma_exit_request,
2243         .init_hctx      = nvme_rdma_init_hctx,
2244         .timeout        = nvme_rdma_timeout,
2245         .map_queues     = nvme_rdma_map_queues,
2246         .poll           = nvme_rdma_poll,
2247 };
2248
2249 static const struct blk_mq_ops nvme_rdma_admin_mq_ops = {
2250         .queue_rq       = nvme_rdma_queue_rq,
2251         .complete       = nvme_rdma_complete_rq,
2252         .init_request   = nvme_rdma_init_request,
2253         .exit_request   = nvme_rdma_exit_request,
2254         .init_hctx      = nvme_rdma_init_admin_hctx,
2255         .timeout        = nvme_rdma_timeout,
2256 };
2257
2258 static void nvme_rdma_shutdown_ctrl(struct nvme_rdma_ctrl *ctrl, bool shutdown)
2259 {
2260         nvme_rdma_teardown_io_queues(ctrl, shutdown);
2261         nvme_stop_admin_queue(&ctrl->ctrl);
2262         if (shutdown)
2263                 nvme_shutdown_ctrl(&ctrl->ctrl);
2264         else
2265                 nvme_disable_ctrl(&ctrl->ctrl);
2266         nvme_rdma_teardown_admin_queue(ctrl, shutdown);
2267 }
2268
2269 static void nvme_rdma_delete_ctrl(struct nvme_ctrl *ctrl)
2270 {
2271         nvme_rdma_shutdown_ctrl(to_rdma_ctrl(ctrl), true);
2272 }
2273
2274 static void nvme_rdma_reset_ctrl_work(struct work_struct *work)
2275 {
2276         struct nvme_rdma_ctrl *ctrl =
2277                 container_of(work, struct nvme_rdma_ctrl, ctrl.reset_work);
2278
2279         nvme_stop_ctrl(&ctrl->ctrl);
2280         nvme_rdma_shutdown_ctrl(ctrl, false);
2281
2282         if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
2283                 /* state change failure should never happen */
2284                 WARN_ON_ONCE(1);
2285                 return;
2286         }
2287
2288         if (nvme_rdma_setup_ctrl(ctrl, false))
2289                 goto out_fail;
2290
2291         return;
2292
2293 out_fail:
2294         ++ctrl->ctrl.nr_reconnects;
2295         nvme_rdma_reconnect_or_remove(ctrl);
2296 }
2297
2298 static const struct nvme_ctrl_ops nvme_rdma_ctrl_ops = {
2299         .name                   = "rdma",
2300         .module                 = THIS_MODULE,
2301         .flags                  = NVME_F_FABRICS | NVME_F_METADATA_SUPPORTED,
2302         .reg_read32             = nvmf_reg_read32,
2303         .reg_read64             = nvmf_reg_read64,
2304         .reg_write32            = nvmf_reg_write32,
2305         .free_ctrl              = nvme_rdma_free_ctrl,
2306         .submit_async_event     = nvme_rdma_submit_async_event,
2307         .delete_ctrl            = nvme_rdma_delete_ctrl,
2308         .get_address            = nvmf_get_address,
2309         .stop_ctrl              = nvme_rdma_stop_ctrl,
2310 };
2311
2312 /*
2313  * Fails a connection request if it matches an existing controller
2314  * (association) with the same tuple:
2315  * <Host NQN, Host ID, local address, remote address, remote port, SUBSYS NQN>
2316  *
2317  * if local address is not specified in the request, it will match an
2318  * existing controller with all the other parameters the same and no
2319  * local port address specified as well.
2320  *
2321  * The ports don't need to be compared as they are intrinsically
2322  * already matched by the port pointers supplied.
2323  */
2324 static bool
2325 nvme_rdma_existing_controller(struct nvmf_ctrl_options *opts)
2326 {
2327         struct nvme_rdma_ctrl *ctrl;
2328         bool found = false;
2329
2330         mutex_lock(&nvme_rdma_ctrl_mutex);
2331         list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) {
2332                 found = nvmf_ip_options_match(&ctrl->ctrl, opts);
2333                 if (found)
2334                         break;
2335         }
2336         mutex_unlock(&nvme_rdma_ctrl_mutex);
2337
2338         return found;
2339 }
2340
2341 static struct nvme_ctrl *nvme_rdma_create_ctrl(struct device *dev,
2342                 struct nvmf_ctrl_options *opts)
2343 {
2344         struct nvme_rdma_ctrl *ctrl;
2345         int ret;
2346         bool changed;
2347
2348         ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
2349         if (!ctrl)
2350                 return ERR_PTR(-ENOMEM);
2351         ctrl->ctrl.opts = opts;
2352         INIT_LIST_HEAD(&ctrl->list);
2353
2354         if (!(opts->mask & NVMF_OPT_TRSVCID)) {
2355                 opts->trsvcid =
2356                         kstrdup(__stringify(NVME_RDMA_IP_PORT), GFP_KERNEL);
2357                 if (!opts->trsvcid) {
2358                         ret = -ENOMEM;
2359                         goto out_free_ctrl;
2360                 }
2361                 opts->mask |= NVMF_OPT_TRSVCID;
2362         }
2363
2364         ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2365                         opts->traddr, opts->trsvcid, &ctrl->addr);
2366         if (ret) {
2367                 pr_err("malformed address passed: %s:%s\n",
2368                         opts->traddr, opts->trsvcid);
2369                 goto out_free_ctrl;
2370         }
2371
2372         if (opts->mask & NVMF_OPT_HOST_TRADDR) {
2373                 ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2374                         opts->host_traddr, NULL, &ctrl->src_addr);
2375                 if (ret) {
2376                         pr_err("malformed src address passed: %s\n",
2377                                opts->host_traddr);
2378                         goto out_free_ctrl;
2379                 }
2380         }
2381
2382         if (!opts->duplicate_connect && nvme_rdma_existing_controller(opts)) {
2383                 ret = -EALREADY;
2384                 goto out_free_ctrl;
2385         }
2386
2387         INIT_DELAYED_WORK(&ctrl->reconnect_work,
2388                         nvme_rdma_reconnect_ctrl_work);
2389         INIT_WORK(&ctrl->err_work, nvme_rdma_error_recovery_work);
2390         INIT_WORK(&ctrl->ctrl.reset_work, nvme_rdma_reset_ctrl_work);
2391
2392         ctrl->ctrl.queue_count = opts->nr_io_queues + opts->nr_write_queues +
2393                                 opts->nr_poll_queues + 1;
2394         ctrl->ctrl.sqsize = opts->queue_size - 1;
2395         ctrl->ctrl.kato = opts->kato;
2396
2397         ret = -ENOMEM;
2398         ctrl->queues = kcalloc(ctrl->ctrl.queue_count, sizeof(*ctrl->queues),
2399                                 GFP_KERNEL);
2400         if (!ctrl->queues)
2401                 goto out_free_ctrl;
2402
2403         ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_rdma_ctrl_ops,
2404                                 0 /* no quirks, we're perfect! */);
2405         if (ret)
2406                 goto out_kfree_queues;
2407
2408         changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING);
2409         WARN_ON_ONCE(!changed);
2410
2411         ret = nvme_rdma_setup_ctrl(ctrl, true);
2412         if (ret)
2413                 goto out_uninit_ctrl;
2414
2415         dev_info(ctrl->ctrl.device, "new ctrl: NQN \"%s\", addr %pISpcs\n",
2416                 nvmf_ctrl_subsysnqn(&ctrl->ctrl), &ctrl->addr);
2417
2418         mutex_lock(&nvme_rdma_ctrl_mutex);
2419         list_add_tail(&ctrl->list, &nvme_rdma_ctrl_list);
2420         mutex_unlock(&nvme_rdma_ctrl_mutex);
2421
2422         return &ctrl->ctrl;
2423
2424 out_uninit_ctrl:
2425         nvme_uninit_ctrl(&ctrl->ctrl);
2426         nvme_put_ctrl(&ctrl->ctrl);
2427         if (ret > 0)
2428                 ret = -EIO;
2429         return ERR_PTR(ret);
2430 out_kfree_queues:
2431         kfree(ctrl->queues);
2432 out_free_ctrl:
2433         kfree(ctrl);
2434         return ERR_PTR(ret);
2435 }
2436
2437 static struct nvmf_transport_ops nvme_rdma_transport = {
2438         .name           = "rdma",
2439         .module         = THIS_MODULE,
2440         .required_opts  = NVMF_OPT_TRADDR,
2441         .allowed_opts   = NVMF_OPT_TRSVCID | NVMF_OPT_RECONNECT_DELAY |
2442                           NVMF_OPT_HOST_TRADDR | NVMF_OPT_CTRL_LOSS_TMO |
2443                           NVMF_OPT_NR_WRITE_QUEUES | NVMF_OPT_NR_POLL_QUEUES |
2444                           NVMF_OPT_TOS,
2445         .create_ctrl    = nvme_rdma_create_ctrl,
2446 };
2447
2448 static void nvme_rdma_remove_one(struct ib_device *ib_device, void *client_data)
2449 {
2450         struct nvme_rdma_ctrl *ctrl;
2451         struct nvme_rdma_device *ndev;
2452         bool found = false;
2453
2454         mutex_lock(&device_list_mutex);
2455         list_for_each_entry(ndev, &device_list, entry) {
2456                 if (ndev->dev == ib_device) {
2457                         found = true;
2458                         break;
2459                 }
2460         }
2461         mutex_unlock(&device_list_mutex);
2462
2463         if (!found)
2464                 return;
2465
2466         /* Delete all controllers using this device */
2467         mutex_lock(&nvme_rdma_ctrl_mutex);
2468         list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) {
2469                 if (ctrl->device->dev != ib_device)
2470                         continue;
2471                 nvme_delete_ctrl(&ctrl->ctrl);
2472         }
2473         mutex_unlock(&nvme_rdma_ctrl_mutex);
2474
2475         flush_workqueue(nvme_delete_wq);
2476 }
2477
2478 static struct ib_client nvme_rdma_ib_client = {
2479         .name   = "nvme_rdma",
2480         .remove = nvme_rdma_remove_one
2481 };
2482
2483 static int __init nvme_rdma_init_module(void)
2484 {
2485         int ret;
2486
2487         ret = ib_register_client(&nvme_rdma_ib_client);
2488         if (ret)
2489                 return ret;
2490
2491         ret = nvmf_register_transport(&nvme_rdma_transport);
2492         if (ret)
2493                 goto err_unreg_client;
2494
2495         return 0;
2496
2497 err_unreg_client:
2498         ib_unregister_client(&nvme_rdma_ib_client);
2499         return ret;
2500 }
2501
2502 static void __exit nvme_rdma_cleanup_module(void)
2503 {
2504         struct nvme_rdma_ctrl *ctrl;
2505
2506         nvmf_unregister_transport(&nvme_rdma_transport);
2507         ib_unregister_client(&nvme_rdma_ib_client);
2508
2509         mutex_lock(&nvme_rdma_ctrl_mutex);
2510         list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list)
2511                 nvme_delete_ctrl(&ctrl->ctrl);
2512         mutex_unlock(&nvme_rdma_ctrl_mutex);
2513         flush_workqueue(nvme_delete_wq);
2514 }
2515
2516 module_init(nvme_rdma_init_module);
2517 module_exit(nvme_rdma_cleanup_module);
2518
2519 MODULE_LICENSE("GPL v2");