GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / nvme / target / rdma.c
1 /*
2  * NVMe over Fabrics RDMA target.
3  * Copyright (c) 2015-2016 HGST, a Western Digital Company.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15 #include <linux/atomic.h>
16 #include <linux/ctype.h>
17 #include <linux/delay.h>
18 #include <linux/err.h>
19 #include <linux/init.h>
20 #include <linux/module.h>
21 #include <linux/nvme.h>
22 #include <linux/slab.h>
23 #include <linux/string.h>
24 #include <linux/wait.h>
25 #include <linux/inet.h>
26 #include <asm/unaligned.h>
27
28 #include <rdma/ib_verbs.h>
29 #include <rdma/rdma_cm.h>
30 #include <rdma/rw.h>
31
32 #include <linux/nvme-rdma.h>
33 #include "nvmet.h"
34
35 /*
36  * We allow at least 1 page, up to 4 SGEs, and up to 16KB of inline data
37  */
38 #define NVMET_RDMA_DEFAULT_INLINE_DATA_SIZE     PAGE_SIZE
39 #define NVMET_RDMA_MAX_INLINE_SGE               4
40 #define NVMET_RDMA_MAX_INLINE_DATA_SIZE         max_t(int, SZ_16K, PAGE_SIZE)
41
42 struct nvmet_rdma_cmd {
43         struct ib_sge           sge[NVMET_RDMA_MAX_INLINE_SGE + 1];
44         struct ib_cqe           cqe;
45         struct ib_recv_wr       wr;
46         struct scatterlist      inline_sg[NVMET_RDMA_MAX_INLINE_SGE];
47         struct nvme_command     *nvme_cmd;
48         struct nvmet_rdma_queue *queue;
49 };
50
51 enum {
52         NVMET_RDMA_REQ_INLINE_DATA      = (1 << 0),
53         NVMET_RDMA_REQ_INVALIDATE_RKEY  = (1 << 1),
54 };
55
56 struct nvmet_rdma_rsp {
57         struct ib_sge           send_sge;
58         struct ib_cqe           send_cqe;
59         struct ib_send_wr       send_wr;
60
61         struct nvmet_rdma_cmd   *cmd;
62         struct nvmet_rdma_queue *queue;
63
64         struct ib_cqe           read_cqe;
65         struct rdma_rw_ctx      rw;
66
67         struct nvmet_req        req;
68
69         bool                    allocated;
70         u8                      n_rdma;
71         u32                     flags;
72         u32                     invalidate_rkey;
73
74         struct list_head        wait_list;
75         struct list_head        free_list;
76 };
77
78 enum nvmet_rdma_queue_state {
79         NVMET_RDMA_Q_CONNECTING,
80         NVMET_RDMA_Q_LIVE,
81         NVMET_RDMA_Q_DISCONNECTING,
82 };
83
84 struct nvmet_rdma_queue {
85         struct rdma_cm_id       *cm_id;
86         struct ib_qp            *qp;
87         struct nvmet_port       *port;
88         struct ib_cq            *cq;
89         atomic_t                sq_wr_avail;
90         struct nvmet_rdma_device *dev;
91         spinlock_t              state_lock;
92         enum nvmet_rdma_queue_state state;
93         struct nvmet_cq         nvme_cq;
94         struct nvmet_sq         nvme_sq;
95
96         struct nvmet_rdma_rsp   *rsps;
97         struct list_head        free_rsps;
98         spinlock_t              rsps_lock;
99         struct nvmet_rdma_cmd   *cmds;
100
101         struct work_struct      release_work;
102         struct list_head        rsp_wait_list;
103         struct list_head        rsp_wr_wait_list;
104         spinlock_t              rsp_wr_wait_lock;
105
106         int                     idx;
107         int                     host_qid;
108         int                     recv_queue_size;
109         int                     send_queue_size;
110
111         struct list_head        queue_list;
112 };
113
114 struct nvmet_rdma_device {
115         struct ib_device        *device;
116         struct ib_pd            *pd;
117         struct ib_srq           *srq;
118         struct nvmet_rdma_cmd   *srq_cmds;
119         size_t                  srq_size;
120         struct kref             ref;
121         struct list_head        entry;
122         int                     inline_data_size;
123         int                     inline_page_count;
124 };
125
126 static bool nvmet_rdma_use_srq;
127 module_param_named(use_srq, nvmet_rdma_use_srq, bool, 0444);
128 MODULE_PARM_DESC(use_srq, "Use shared receive queue.");
129
130 static DEFINE_IDA(nvmet_rdma_queue_ida);
131 static LIST_HEAD(nvmet_rdma_queue_list);
132 static DEFINE_MUTEX(nvmet_rdma_queue_mutex);
133
134 static LIST_HEAD(device_list);
135 static DEFINE_MUTEX(device_list_mutex);
136
137 static bool nvmet_rdma_execute_command(struct nvmet_rdma_rsp *rsp);
138 static void nvmet_rdma_send_done(struct ib_cq *cq, struct ib_wc *wc);
139 static void nvmet_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc);
140 static void nvmet_rdma_read_data_done(struct ib_cq *cq, struct ib_wc *wc);
141 static void nvmet_rdma_qp_event(struct ib_event *event, void *priv);
142 static void nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue);
143 static void nvmet_rdma_free_rsp(struct nvmet_rdma_device *ndev,
144                                 struct nvmet_rdma_rsp *r);
145 static int nvmet_rdma_alloc_rsp(struct nvmet_rdma_device *ndev,
146                                 struct nvmet_rdma_rsp *r);
147
148 static const struct nvmet_fabrics_ops nvmet_rdma_ops;
149
150 static int num_pages(int len)
151 {
152         return 1 + (((len - 1) & PAGE_MASK) >> PAGE_SHIFT);
153 }
154
155 /* XXX: really should move to a generic header sooner or later.. */
156 static inline u32 get_unaligned_le24(const u8 *p)
157 {
158         return (u32)p[0] | (u32)p[1] << 8 | (u32)p[2] << 16;
159 }
160
161 static inline bool nvmet_rdma_need_data_in(struct nvmet_rdma_rsp *rsp)
162 {
163         return nvme_is_write(rsp->req.cmd) &&
164                 rsp->req.transfer_len &&
165                 !(rsp->flags & NVMET_RDMA_REQ_INLINE_DATA);
166 }
167
168 static inline bool nvmet_rdma_need_data_out(struct nvmet_rdma_rsp *rsp)
169 {
170         return !nvme_is_write(rsp->req.cmd) &&
171                 rsp->req.transfer_len &&
172                 !rsp->req.rsp->status &&
173                 !(rsp->flags & NVMET_RDMA_REQ_INLINE_DATA);
174 }
175
176 static inline struct nvmet_rdma_rsp *
177 nvmet_rdma_get_rsp(struct nvmet_rdma_queue *queue)
178 {
179         struct nvmet_rdma_rsp *rsp;
180         unsigned long flags;
181
182         spin_lock_irqsave(&queue->rsps_lock, flags);
183         rsp = list_first_entry_or_null(&queue->free_rsps,
184                                 struct nvmet_rdma_rsp, free_list);
185         if (likely(rsp))
186                 list_del(&rsp->free_list);
187         spin_unlock_irqrestore(&queue->rsps_lock, flags);
188
189         if (unlikely(!rsp)) {
190                 int ret;
191
192                 rsp = kzalloc(sizeof(*rsp), GFP_KERNEL);
193                 if (unlikely(!rsp))
194                         return NULL;
195                 ret = nvmet_rdma_alloc_rsp(queue->dev, rsp);
196                 if (unlikely(ret)) {
197                         kfree(rsp);
198                         return NULL;
199                 }
200
201                 rsp->allocated = true;
202         }
203
204         return rsp;
205 }
206
207 static inline void
208 nvmet_rdma_put_rsp(struct nvmet_rdma_rsp *rsp)
209 {
210         unsigned long flags;
211
212         if (unlikely(rsp->allocated)) {
213                 nvmet_rdma_free_rsp(rsp->queue->dev, rsp);
214                 kfree(rsp);
215                 return;
216         }
217
218         spin_lock_irqsave(&rsp->queue->rsps_lock, flags);
219         list_add_tail(&rsp->free_list, &rsp->queue->free_rsps);
220         spin_unlock_irqrestore(&rsp->queue->rsps_lock, flags);
221 }
222
223 static void nvmet_rdma_free_inline_pages(struct nvmet_rdma_device *ndev,
224                                 struct nvmet_rdma_cmd *c)
225 {
226         struct scatterlist *sg;
227         struct ib_sge *sge;
228         int i;
229
230         if (!ndev->inline_data_size)
231                 return;
232
233         sg = c->inline_sg;
234         sge = &c->sge[1];
235
236         for (i = 0; i < ndev->inline_page_count; i++, sg++, sge++) {
237                 if (sge->length)
238                         ib_dma_unmap_page(ndev->device, sge->addr,
239                                         sge->length, DMA_FROM_DEVICE);
240                 if (sg_page(sg))
241                         __free_page(sg_page(sg));
242         }
243 }
244
245 static int nvmet_rdma_alloc_inline_pages(struct nvmet_rdma_device *ndev,
246                                 struct nvmet_rdma_cmd *c)
247 {
248         struct scatterlist *sg;
249         struct ib_sge *sge;
250         struct page *pg;
251         int len;
252         int i;
253
254         if (!ndev->inline_data_size)
255                 return 0;
256
257         sg = c->inline_sg;
258         sg_init_table(sg, ndev->inline_page_count);
259         sge = &c->sge[1];
260         len = ndev->inline_data_size;
261
262         for (i = 0; i < ndev->inline_page_count; i++, sg++, sge++) {
263                 pg = alloc_page(GFP_KERNEL);
264                 if (!pg)
265                         goto out_err;
266                 sg_assign_page(sg, pg);
267                 sge->addr = ib_dma_map_page(ndev->device,
268                         pg, 0, PAGE_SIZE, DMA_FROM_DEVICE);
269                 if (ib_dma_mapping_error(ndev->device, sge->addr))
270                         goto out_err;
271                 sge->length = min_t(int, len, PAGE_SIZE);
272                 sge->lkey = ndev->pd->local_dma_lkey;
273                 len -= sge->length;
274         }
275
276         return 0;
277 out_err:
278         for (; i >= 0; i--, sg--, sge--) {
279                 if (sge->length)
280                         ib_dma_unmap_page(ndev->device, sge->addr,
281                                         sge->length, DMA_FROM_DEVICE);
282                 if (sg_page(sg))
283                         __free_page(sg_page(sg));
284         }
285         return -ENOMEM;
286 }
287
288 static int nvmet_rdma_alloc_cmd(struct nvmet_rdma_device *ndev,
289                         struct nvmet_rdma_cmd *c, bool admin)
290 {
291         /* NVMe command / RDMA RECV */
292         c->nvme_cmd = kmalloc(sizeof(*c->nvme_cmd), GFP_KERNEL);
293         if (!c->nvme_cmd)
294                 goto out;
295
296         c->sge[0].addr = ib_dma_map_single(ndev->device, c->nvme_cmd,
297                         sizeof(*c->nvme_cmd), DMA_FROM_DEVICE);
298         if (ib_dma_mapping_error(ndev->device, c->sge[0].addr))
299                 goto out_free_cmd;
300
301         c->sge[0].length = sizeof(*c->nvme_cmd);
302         c->sge[0].lkey = ndev->pd->local_dma_lkey;
303
304         if (!admin && nvmet_rdma_alloc_inline_pages(ndev, c))
305                 goto out_unmap_cmd;
306
307         c->cqe.done = nvmet_rdma_recv_done;
308
309         c->wr.wr_cqe = &c->cqe;
310         c->wr.sg_list = c->sge;
311         c->wr.num_sge = admin ? 1 : ndev->inline_page_count + 1;
312
313         return 0;
314
315 out_unmap_cmd:
316         ib_dma_unmap_single(ndev->device, c->sge[0].addr,
317                         sizeof(*c->nvme_cmd), DMA_FROM_DEVICE);
318 out_free_cmd:
319         kfree(c->nvme_cmd);
320
321 out:
322         return -ENOMEM;
323 }
324
325 static void nvmet_rdma_free_cmd(struct nvmet_rdma_device *ndev,
326                 struct nvmet_rdma_cmd *c, bool admin)
327 {
328         if (!admin)
329                 nvmet_rdma_free_inline_pages(ndev, c);
330         ib_dma_unmap_single(ndev->device, c->sge[0].addr,
331                                 sizeof(*c->nvme_cmd), DMA_FROM_DEVICE);
332         kfree(c->nvme_cmd);
333 }
334
335 static struct nvmet_rdma_cmd *
336 nvmet_rdma_alloc_cmds(struct nvmet_rdma_device *ndev,
337                 int nr_cmds, bool admin)
338 {
339         struct nvmet_rdma_cmd *cmds;
340         int ret = -EINVAL, i;
341
342         cmds = kcalloc(nr_cmds, sizeof(struct nvmet_rdma_cmd), GFP_KERNEL);
343         if (!cmds)
344                 goto out;
345
346         for (i = 0; i < nr_cmds; i++) {
347                 ret = nvmet_rdma_alloc_cmd(ndev, cmds + i, admin);
348                 if (ret)
349                         goto out_free;
350         }
351
352         return cmds;
353
354 out_free:
355         while (--i >= 0)
356                 nvmet_rdma_free_cmd(ndev, cmds + i, admin);
357         kfree(cmds);
358 out:
359         return ERR_PTR(ret);
360 }
361
362 static void nvmet_rdma_free_cmds(struct nvmet_rdma_device *ndev,
363                 struct nvmet_rdma_cmd *cmds, int nr_cmds, bool admin)
364 {
365         int i;
366
367         for (i = 0; i < nr_cmds; i++)
368                 nvmet_rdma_free_cmd(ndev, cmds + i, admin);
369         kfree(cmds);
370 }
371
372 static int nvmet_rdma_alloc_rsp(struct nvmet_rdma_device *ndev,
373                 struct nvmet_rdma_rsp *r)
374 {
375         /* NVMe CQE / RDMA SEND */
376         r->req.rsp = kmalloc(sizeof(*r->req.rsp), GFP_KERNEL);
377         if (!r->req.rsp)
378                 goto out;
379
380         r->send_sge.addr = ib_dma_map_single(ndev->device, r->req.rsp,
381                         sizeof(*r->req.rsp), DMA_TO_DEVICE);
382         if (ib_dma_mapping_error(ndev->device, r->send_sge.addr))
383                 goto out_free_rsp;
384
385         r->send_sge.length = sizeof(*r->req.rsp);
386         r->send_sge.lkey = ndev->pd->local_dma_lkey;
387
388         r->send_cqe.done = nvmet_rdma_send_done;
389
390         r->send_wr.wr_cqe = &r->send_cqe;
391         r->send_wr.sg_list = &r->send_sge;
392         r->send_wr.num_sge = 1;
393         r->send_wr.send_flags = IB_SEND_SIGNALED;
394
395         /* Data In / RDMA READ */
396         r->read_cqe.done = nvmet_rdma_read_data_done;
397         return 0;
398
399 out_free_rsp:
400         kfree(r->req.rsp);
401 out:
402         return -ENOMEM;
403 }
404
405 static void nvmet_rdma_free_rsp(struct nvmet_rdma_device *ndev,
406                 struct nvmet_rdma_rsp *r)
407 {
408         ib_dma_unmap_single(ndev->device, r->send_sge.addr,
409                                 sizeof(*r->req.rsp), DMA_TO_DEVICE);
410         kfree(r->req.rsp);
411 }
412
413 static int
414 nvmet_rdma_alloc_rsps(struct nvmet_rdma_queue *queue)
415 {
416         struct nvmet_rdma_device *ndev = queue->dev;
417         int nr_rsps = queue->recv_queue_size * 2;
418         int ret = -EINVAL, i;
419
420         queue->rsps = kcalloc(nr_rsps, sizeof(struct nvmet_rdma_rsp),
421                         GFP_KERNEL);
422         if (!queue->rsps)
423                 goto out;
424
425         for (i = 0; i < nr_rsps; i++) {
426                 struct nvmet_rdma_rsp *rsp = &queue->rsps[i];
427
428                 ret = nvmet_rdma_alloc_rsp(ndev, rsp);
429                 if (ret)
430                         goto out_free;
431
432                 list_add_tail(&rsp->free_list, &queue->free_rsps);
433         }
434
435         return 0;
436
437 out_free:
438         while (--i >= 0) {
439                 struct nvmet_rdma_rsp *rsp = &queue->rsps[i];
440
441                 list_del(&rsp->free_list);
442                 nvmet_rdma_free_rsp(ndev, rsp);
443         }
444         kfree(queue->rsps);
445 out:
446         return ret;
447 }
448
449 static void nvmet_rdma_free_rsps(struct nvmet_rdma_queue *queue)
450 {
451         struct nvmet_rdma_device *ndev = queue->dev;
452         int i, nr_rsps = queue->recv_queue_size * 2;
453
454         for (i = 0; i < nr_rsps; i++) {
455                 struct nvmet_rdma_rsp *rsp = &queue->rsps[i];
456
457                 list_del(&rsp->free_list);
458                 nvmet_rdma_free_rsp(ndev, rsp);
459         }
460         kfree(queue->rsps);
461 }
462
463 static int nvmet_rdma_post_recv(struct nvmet_rdma_device *ndev,
464                 struct nvmet_rdma_cmd *cmd)
465 {
466         int ret;
467
468         ib_dma_sync_single_for_device(ndev->device,
469                 cmd->sge[0].addr, cmd->sge[0].length,
470                 DMA_FROM_DEVICE);
471
472         if (ndev->srq)
473                 ret = ib_post_srq_recv(ndev->srq, &cmd->wr, NULL);
474         else
475                 ret = ib_post_recv(cmd->queue->qp, &cmd->wr, NULL);
476
477         if (unlikely(ret))
478                 pr_err("post_recv cmd failed\n");
479
480         return ret;
481 }
482
483 static void nvmet_rdma_process_wr_wait_list(struct nvmet_rdma_queue *queue)
484 {
485         spin_lock(&queue->rsp_wr_wait_lock);
486         while (!list_empty(&queue->rsp_wr_wait_list)) {
487                 struct nvmet_rdma_rsp *rsp;
488                 bool ret;
489
490                 rsp = list_entry(queue->rsp_wr_wait_list.next,
491                                 struct nvmet_rdma_rsp, wait_list);
492                 list_del(&rsp->wait_list);
493
494                 spin_unlock(&queue->rsp_wr_wait_lock);
495                 ret = nvmet_rdma_execute_command(rsp);
496                 spin_lock(&queue->rsp_wr_wait_lock);
497
498                 if (!ret) {
499                         list_add(&rsp->wait_list, &queue->rsp_wr_wait_list);
500                         break;
501                 }
502         }
503         spin_unlock(&queue->rsp_wr_wait_lock);
504 }
505
506
507 static void nvmet_rdma_release_rsp(struct nvmet_rdma_rsp *rsp)
508 {
509         struct nvmet_rdma_queue *queue = rsp->queue;
510
511         atomic_add(1 + rsp->n_rdma, &queue->sq_wr_avail);
512
513         if (rsp->n_rdma) {
514                 rdma_rw_ctx_destroy(&rsp->rw, queue->qp,
515                                 queue->cm_id->port_num, rsp->req.sg,
516                                 rsp->req.sg_cnt, nvmet_data_dir(&rsp->req));
517         }
518
519         if (rsp->req.sg != rsp->cmd->inline_sg)
520                 sgl_free(rsp->req.sg);
521
522         if (unlikely(!list_empty_careful(&queue->rsp_wr_wait_list)))
523                 nvmet_rdma_process_wr_wait_list(queue);
524
525         nvmet_rdma_put_rsp(rsp);
526 }
527
528 static void nvmet_rdma_error_comp(struct nvmet_rdma_queue *queue)
529 {
530         if (queue->nvme_sq.ctrl) {
531                 nvmet_ctrl_fatal_error(queue->nvme_sq.ctrl);
532         } else {
533                 /*
534                  * we didn't setup the controller yet in case
535                  * of admin connect error, just disconnect and
536                  * cleanup the queue
537                  */
538                 nvmet_rdma_queue_disconnect(queue);
539         }
540 }
541
542 static void nvmet_rdma_send_done(struct ib_cq *cq, struct ib_wc *wc)
543 {
544         struct nvmet_rdma_rsp *rsp =
545                 container_of(wc->wr_cqe, struct nvmet_rdma_rsp, send_cqe);
546         struct nvmet_rdma_queue *queue = cq->cq_context;
547
548         nvmet_rdma_release_rsp(rsp);
549
550         if (unlikely(wc->status != IB_WC_SUCCESS &&
551                      wc->status != IB_WC_WR_FLUSH_ERR)) {
552                 pr_err("SEND for CQE 0x%p failed with status %s (%d).\n",
553                         wc->wr_cqe, ib_wc_status_msg(wc->status), wc->status);
554                 nvmet_rdma_error_comp(queue);
555         }
556 }
557
558 static void nvmet_rdma_queue_response(struct nvmet_req *req)
559 {
560         struct nvmet_rdma_rsp *rsp =
561                 container_of(req, struct nvmet_rdma_rsp, req);
562         struct rdma_cm_id *cm_id = rsp->queue->cm_id;
563         struct ib_send_wr *first_wr;
564
565         if (rsp->flags & NVMET_RDMA_REQ_INVALIDATE_RKEY) {
566                 rsp->send_wr.opcode = IB_WR_SEND_WITH_INV;
567                 rsp->send_wr.ex.invalidate_rkey = rsp->invalidate_rkey;
568         } else {
569                 rsp->send_wr.opcode = IB_WR_SEND;
570         }
571
572         if (nvmet_rdma_need_data_out(rsp))
573                 first_wr = rdma_rw_ctx_wrs(&rsp->rw, cm_id->qp,
574                                 cm_id->port_num, NULL, &rsp->send_wr);
575         else
576                 first_wr = &rsp->send_wr;
577
578         nvmet_rdma_post_recv(rsp->queue->dev, rsp->cmd);
579
580         ib_dma_sync_single_for_device(rsp->queue->dev->device,
581                 rsp->send_sge.addr, rsp->send_sge.length,
582                 DMA_TO_DEVICE);
583
584         if (unlikely(ib_post_send(cm_id->qp, first_wr, NULL))) {
585                 pr_err("sending cmd response failed\n");
586                 nvmet_rdma_release_rsp(rsp);
587         }
588 }
589
590 static void nvmet_rdma_read_data_done(struct ib_cq *cq, struct ib_wc *wc)
591 {
592         struct nvmet_rdma_rsp *rsp =
593                 container_of(wc->wr_cqe, struct nvmet_rdma_rsp, read_cqe);
594         struct nvmet_rdma_queue *queue = cq->cq_context;
595
596         WARN_ON(rsp->n_rdma <= 0);
597         atomic_add(rsp->n_rdma, &queue->sq_wr_avail);
598         rdma_rw_ctx_destroy(&rsp->rw, queue->qp,
599                         queue->cm_id->port_num, rsp->req.sg,
600                         rsp->req.sg_cnt, nvmet_data_dir(&rsp->req));
601         rsp->n_rdma = 0;
602
603         if (unlikely(wc->status != IB_WC_SUCCESS)) {
604                 nvmet_req_uninit(&rsp->req);
605                 nvmet_rdma_release_rsp(rsp);
606                 if (wc->status != IB_WC_WR_FLUSH_ERR) {
607                         pr_info("RDMA READ for CQE 0x%p failed with status %s (%d).\n",
608                                 wc->wr_cqe, ib_wc_status_msg(wc->status), wc->status);
609                         nvmet_rdma_error_comp(queue);
610                 }
611                 return;
612         }
613
614         nvmet_req_execute(&rsp->req);
615 }
616
617 static void nvmet_rdma_use_inline_sg(struct nvmet_rdma_rsp *rsp, u32 len,
618                 u64 off)
619 {
620         int sg_count = num_pages(len);
621         struct scatterlist *sg;
622         int i;
623
624         sg = rsp->cmd->inline_sg;
625         for (i = 0; i < sg_count; i++, sg++) {
626                 if (i < sg_count - 1)
627                         sg_unmark_end(sg);
628                 else
629                         sg_mark_end(sg);
630                 sg->offset = off;
631                 sg->length = min_t(int, len, PAGE_SIZE - off);
632                 len -= sg->length;
633                 if (!i)
634                         off = 0;
635         }
636
637         rsp->req.sg = rsp->cmd->inline_sg;
638         rsp->req.sg_cnt = sg_count;
639 }
640
641 static u16 nvmet_rdma_map_sgl_inline(struct nvmet_rdma_rsp *rsp)
642 {
643         struct nvme_sgl_desc *sgl = &rsp->req.cmd->common.dptr.sgl;
644         u64 off = le64_to_cpu(sgl->addr);
645         u32 len = le32_to_cpu(sgl->length);
646
647         if (!nvme_is_write(rsp->req.cmd))
648                 return NVME_SC_INVALID_FIELD | NVME_SC_DNR;
649
650         if (off + len > rsp->queue->dev->inline_data_size) {
651                 pr_err("invalid inline data offset!\n");
652                 return NVME_SC_SGL_INVALID_OFFSET | NVME_SC_DNR;
653         }
654
655         /* no data command? */
656         if (!len)
657                 return 0;
658
659         nvmet_rdma_use_inline_sg(rsp, len, off);
660         rsp->flags |= NVMET_RDMA_REQ_INLINE_DATA;
661         rsp->req.transfer_len += len;
662         return 0;
663 }
664
665 static u16 nvmet_rdma_map_sgl_keyed(struct nvmet_rdma_rsp *rsp,
666                 struct nvme_keyed_sgl_desc *sgl, bool invalidate)
667 {
668         struct rdma_cm_id *cm_id = rsp->queue->cm_id;
669         u64 addr = le64_to_cpu(sgl->addr);
670         u32 len = get_unaligned_le24(sgl->length);
671         u32 key = get_unaligned_le32(sgl->key);
672         int ret;
673
674         /* no data command? */
675         if (!len)
676                 return 0;
677
678         rsp->req.sg = sgl_alloc(len, GFP_KERNEL, &rsp->req.sg_cnt);
679         if (!rsp->req.sg)
680                 return NVME_SC_INTERNAL;
681
682         ret = rdma_rw_ctx_init(&rsp->rw, cm_id->qp, cm_id->port_num,
683                         rsp->req.sg, rsp->req.sg_cnt, 0, addr, key,
684                         nvmet_data_dir(&rsp->req));
685         if (ret < 0)
686                 return NVME_SC_INTERNAL;
687         rsp->req.transfer_len += len;
688         rsp->n_rdma += ret;
689
690         if (invalidate) {
691                 rsp->invalidate_rkey = key;
692                 rsp->flags |= NVMET_RDMA_REQ_INVALIDATE_RKEY;
693         }
694
695         return 0;
696 }
697
698 static u16 nvmet_rdma_map_sgl(struct nvmet_rdma_rsp *rsp)
699 {
700         struct nvme_keyed_sgl_desc *sgl = &rsp->req.cmd->common.dptr.ksgl;
701
702         switch (sgl->type >> 4) {
703         case NVME_SGL_FMT_DATA_DESC:
704                 switch (sgl->type & 0xf) {
705                 case NVME_SGL_FMT_OFFSET:
706                         return nvmet_rdma_map_sgl_inline(rsp);
707                 default:
708                         pr_err("invalid SGL subtype: %#x\n", sgl->type);
709                         return NVME_SC_INVALID_FIELD | NVME_SC_DNR;
710                 }
711         case NVME_KEY_SGL_FMT_DATA_DESC:
712                 switch (sgl->type & 0xf) {
713                 case NVME_SGL_FMT_ADDRESS | NVME_SGL_FMT_INVALIDATE:
714                         return nvmet_rdma_map_sgl_keyed(rsp, sgl, true);
715                 case NVME_SGL_FMT_ADDRESS:
716                         return nvmet_rdma_map_sgl_keyed(rsp, sgl, false);
717                 default:
718                         pr_err("invalid SGL subtype: %#x\n", sgl->type);
719                         return NVME_SC_INVALID_FIELD | NVME_SC_DNR;
720                 }
721         default:
722                 pr_err("invalid SGL type: %#x\n", sgl->type);
723                 return NVME_SC_SGL_INVALID_TYPE | NVME_SC_DNR;
724         }
725 }
726
727 static bool nvmet_rdma_execute_command(struct nvmet_rdma_rsp *rsp)
728 {
729         struct nvmet_rdma_queue *queue = rsp->queue;
730
731         if (unlikely(atomic_sub_return(1 + rsp->n_rdma,
732                         &queue->sq_wr_avail) < 0)) {
733                 pr_debug("IB send queue full (needed %d): queue %u cntlid %u\n",
734                                 1 + rsp->n_rdma, queue->idx,
735                                 queue->nvme_sq.ctrl->cntlid);
736                 atomic_add(1 + rsp->n_rdma, &queue->sq_wr_avail);
737                 return false;
738         }
739
740         if (nvmet_rdma_need_data_in(rsp)) {
741                 if (rdma_rw_ctx_post(&rsp->rw, queue->qp,
742                                 queue->cm_id->port_num, &rsp->read_cqe, NULL))
743                         nvmet_req_complete(&rsp->req, NVME_SC_DATA_XFER_ERROR);
744         } else {
745                 nvmet_req_execute(&rsp->req);
746         }
747
748         return true;
749 }
750
751 static void nvmet_rdma_handle_command(struct nvmet_rdma_queue *queue,
752                 struct nvmet_rdma_rsp *cmd)
753 {
754         u16 status;
755
756         ib_dma_sync_single_for_cpu(queue->dev->device,
757                 cmd->cmd->sge[0].addr, cmd->cmd->sge[0].length,
758                 DMA_FROM_DEVICE);
759         ib_dma_sync_single_for_cpu(queue->dev->device,
760                 cmd->send_sge.addr, cmd->send_sge.length,
761                 DMA_TO_DEVICE);
762
763         if (!nvmet_req_init(&cmd->req, &queue->nvme_cq,
764                         &queue->nvme_sq, &nvmet_rdma_ops))
765                 return;
766
767         status = nvmet_rdma_map_sgl(cmd);
768         if (status)
769                 goto out_err;
770
771         if (unlikely(!nvmet_rdma_execute_command(cmd))) {
772                 spin_lock(&queue->rsp_wr_wait_lock);
773                 list_add_tail(&cmd->wait_list, &queue->rsp_wr_wait_list);
774                 spin_unlock(&queue->rsp_wr_wait_lock);
775         }
776
777         return;
778
779 out_err:
780         nvmet_req_complete(&cmd->req, status);
781 }
782
783 static void nvmet_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc)
784 {
785         struct nvmet_rdma_cmd *cmd =
786                 container_of(wc->wr_cqe, struct nvmet_rdma_cmd, cqe);
787         struct nvmet_rdma_queue *queue = cq->cq_context;
788         struct nvmet_rdma_rsp *rsp;
789
790         if (unlikely(wc->status != IB_WC_SUCCESS)) {
791                 if (wc->status != IB_WC_WR_FLUSH_ERR) {
792                         pr_err("RECV for CQE 0x%p failed with status %s (%d)\n",
793                                 wc->wr_cqe, ib_wc_status_msg(wc->status),
794                                 wc->status);
795                         nvmet_rdma_error_comp(queue);
796                 }
797                 return;
798         }
799
800         if (unlikely(wc->byte_len < sizeof(struct nvme_command))) {
801                 pr_err("Ctrl Fatal Error: capsule size less than 64 bytes\n");
802                 nvmet_rdma_error_comp(queue);
803                 return;
804         }
805
806         cmd->queue = queue;
807         rsp = nvmet_rdma_get_rsp(queue);
808         if (unlikely(!rsp)) {
809                 /*
810                  * we get here only under memory pressure,
811                  * silently drop and have the host retry
812                  * as we can't even fail it.
813                  */
814                 nvmet_rdma_post_recv(queue->dev, cmd);
815                 return;
816         }
817         rsp->queue = queue;
818         rsp->cmd = cmd;
819         rsp->flags = 0;
820         rsp->req.cmd = cmd->nvme_cmd;
821         rsp->req.port = queue->port;
822         rsp->n_rdma = 0;
823
824         if (unlikely(queue->state != NVMET_RDMA_Q_LIVE)) {
825                 unsigned long flags;
826
827                 spin_lock_irqsave(&queue->state_lock, flags);
828                 if (queue->state == NVMET_RDMA_Q_CONNECTING)
829                         list_add_tail(&rsp->wait_list, &queue->rsp_wait_list);
830                 else
831                         nvmet_rdma_put_rsp(rsp);
832                 spin_unlock_irqrestore(&queue->state_lock, flags);
833                 return;
834         }
835
836         nvmet_rdma_handle_command(queue, rsp);
837 }
838
839 static void nvmet_rdma_destroy_srq(struct nvmet_rdma_device *ndev)
840 {
841         if (!ndev->srq)
842                 return;
843
844         nvmet_rdma_free_cmds(ndev, ndev->srq_cmds, ndev->srq_size, false);
845         ib_destroy_srq(ndev->srq);
846 }
847
848 static int nvmet_rdma_init_srq(struct nvmet_rdma_device *ndev)
849 {
850         struct ib_srq_init_attr srq_attr = { NULL, };
851         struct ib_srq *srq;
852         size_t srq_size;
853         int ret, i;
854
855         srq_size = 4095;        /* XXX: tune */
856
857         srq_attr.attr.max_wr = srq_size;
858         srq_attr.attr.max_sge = 1 + ndev->inline_page_count;
859         srq_attr.attr.srq_limit = 0;
860         srq_attr.srq_type = IB_SRQT_BASIC;
861         srq = ib_create_srq(ndev->pd, &srq_attr);
862         if (IS_ERR(srq)) {
863                 /*
864                  * If SRQs aren't supported we just go ahead and use normal
865                  * non-shared receive queues.
866                  */
867                 pr_info("SRQ requested but not supported.\n");
868                 return 0;
869         }
870
871         ndev->srq_cmds = nvmet_rdma_alloc_cmds(ndev, srq_size, false);
872         if (IS_ERR(ndev->srq_cmds)) {
873                 ret = PTR_ERR(ndev->srq_cmds);
874                 goto out_destroy_srq;
875         }
876
877         ndev->srq = srq;
878         ndev->srq_size = srq_size;
879
880         for (i = 0; i < srq_size; i++) {
881                 ret = nvmet_rdma_post_recv(ndev, &ndev->srq_cmds[i]);
882                 if (ret)
883                         goto out_free_cmds;
884         }
885
886         return 0;
887
888 out_free_cmds:
889         nvmet_rdma_free_cmds(ndev, ndev->srq_cmds, ndev->srq_size, false);
890 out_destroy_srq:
891         ib_destroy_srq(srq);
892         return ret;
893 }
894
895 static void nvmet_rdma_free_dev(struct kref *ref)
896 {
897         struct nvmet_rdma_device *ndev =
898                 container_of(ref, struct nvmet_rdma_device, ref);
899
900         mutex_lock(&device_list_mutex);
901         list_del(&ndev->entry);
902         mutex_unlock(&device_list_mutex);
903
904         nvmet_rdma_destroy_srq(ndev);
905         ib_dealloc_pd(ndev->pd);
906
907         kfree(ndev);
908 }
909
910 static struct nvmet_rdma_device *
911 nvmet_rdma_find_get_device(struct rdma_cm_id *cm_id)
912 {
913         struct nvmet_port *port = cm_id->context;
914         struct nvmet_rdma_device *ndev;
915         int inline_page_count;
916         int inline_sge_count;
917         int ret;
918
919         mutex_lock(&device_list_mutex);
920         list_for_each_entry(ndev, &device_list, entry) {
921                 if (ndev->device->node_guid == cm_id->device->node_guid &&
922                     kref_get_unless_zero(&ndev->ref))
923                         goto out_unlock;
924         }
925
926         ndev = kzalloc(sizeof(*ndev), GFP_KERNEL);
927         if (!ndev)
928                 goto out_err;
929
930         inline_page_count = num_pages(port->inline_data_size);
931         inline_sge_count = max(cm_id->device->attrs.max_sge_rd,
932                                 cm_id->device->attrs.max_recv_sge) - 1;
933         if (inline_page_count > inline_sge_count) {
934                 pr_warn("inline_data_size %d cannot be supported by device %s. Reducing to %lu.\n",
935                         port->inline_data_size, cm_id->device->name,
936                         inline_sge_count * PAGE_SIZE);
937                 port->inline_data_size = inline_sge_count * PAGE_SIZE;
938                 inline_page_count = inline_sge_count;
939         }
940         ndev->inline_data_size = port->inline_data_size;
941         ndev->inline_page_count = inline_page_count;
942         ndev->device = cm_id->device;
943         kref_init(&ndev->ref);
944
945         ndev->pd = ib_alloc_pd(ndev->device, 0);
946         if (IS_ERR(ndev->pd))
947                 goto out_free_dev;
948
949         if (nvmet_rdma_use_srq) {
950                 ret = nvmet_rdma_init_srq(ndev);
951                 if (ret)
952                         goto out_free_pd;
953         }
954
955         list_add(&ndev->entry, &device_list);
956 out_unlock:
957         mutex_unlock(&device_list_mutex);
958         pr_debug("added %s.\n", ndev->device->name);
959         return ndev;
960
961 out_free_pd:
962         ib_dealloc_pd(ndev->pd);
963 out_free_dev:
964         kfree(ndev);
965 out_err:
966         mutex_unlock(&device_list_mutex);
967         return NULL;
968 }
969
970 static int nvmet_rdma_create_queue_ib(struct nvmet_rdma_queue *queue)
971 {
972         struct ib_qp_init_attr qp_attr;
973         struct nvmet_rdma_device *ndev = queue->dev;
974         int comp_vector, nr_cqe, ret, i;
975
976         /*
977          * Spread the io queues across completion vectors,
978          * but still keep all admin queues on vector 0.
979          */
980         comp_vector = !queue->host_qid ? 0 :
981                 queue->idx % ndev->device->num_comp_vectors;
982
983         /*
984          * Reserve CQ slots for RECV + RDMA_READ/RDMA_WRITE + RDMA_SEND.
985          */
986         nr_cqe = queue->recv_queue_size + 2 * queue->send_queue_size;
987
988         queue->cq = ib_alloc_cq(ndev->device, queue,
989                         nr_cqe + 1, comp_vector,
990                         IB_POLL_WORKQUEUE);
991         if (IS_ERR(queue->cq)) {
992                 ret = PTR_ERR(queue->cq);
993                 pr_err("failed to create CQ cqe= %d ret= %d\n",
994                        nr_cqe + 1, ret);
995                 goto out;
996         }
997
998         memset(&qp_attr, 0, sizeof(qp_attr));
999         qp_attr.qp_context = queue;
1000         qp_attr.event_handler = nvmet_rdma_qp_event;
1001         qp_attr.send_cq = queue->cq;
1002         qp_attr.recv_cq = queue->cq;
1003         qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
1004         qp_attr.qp_type = IB_QPT_RC;
1005         /* +1 for drain */
1006         qp_attr.cap.max_send_wr = queue->send_queue_size + 1;
1007         qp_attr.cap.max_rdma_ctxs = queue->send_queue_size;
1008         qp_attr.cap.max_send_sge = max(ndev->device->attrs.max_sge_rd,
1009                                         ndev->device->attrs.max_send_sge);
1010
1011         if (ndev->srq) {
1012                 qp_attr.srq = ndev->srq;
1013         } else {
1014                 /* +1 for drain */
1015                 qp_attr.cap.max_recv_wr = 1 + queue->recv_queue_size;
1016                 qp_attr.cap.max_recv_sge = 1 + ndev->inline_page_count;
1017         }
1018
1019         ret = rdma_create_qp(queue->cm_id, ndev->pd, &qp_attr);
1020         if (ret) {
1021                 pr_err("failed to create_qp ret= %d\n", ret);
1022                 goto err_destroy_cq;
1023         }
1024         queue->qp = queue->cm_id->qp;
1025
1026         atomic_set(&queue->sq_wr_avail, qp_attr.cap.max_send_wr);
1027
1028         pr_debug("%s: max_cqe= %d max_sge= %d sq_size = %d cm_id= %p\n",
1029                  __func__, queue->cq->cqe, qp_attr.cap.max_send_sge,
1030                  qp_attr.cap.max_send_wr, queue->cm_id);
1031
1032         if (!ndev->srq) {
1033                 for (i = 0; i < queue->recv_queue_size; i++) {
1034                         queue->cmds[i].queue = queue;
1035                         ret = nvmet_rdma_post_recv(ndev, &queue->cmds[i]);
1036                         if (ret)
1037                                 goto err_destroy_qp;
1038                 }
1039         }
1040
1041 out:
1042         return ret;
1043
1044 err_destroy_qp:
1045         rdma_destroy_qp(queue->cm_id);
1046 err_destroy_cq:
1047         ib_free_cq(queue->cq);
1048         goto out;
1049 }
1050
1051 static void nvmet_rdma_destroy_queue_ib(struct nvmet_rdma_queue *queue)
1052 {
1053         ib_drain_qp(queue->qp);
1054         if (queue->cm_id)
1055                 rdma_destroy_id(queue->cm_id);
1056         ib_destroy_qp(queue->qp);
1057         ib_free_cq(queue->cq);
1058 }
1059
1060 static void nvmet_rdma_free_queue(struct nvmet_rdma_queue *queue)
1061 {
1062         pr_debug("freeing queue %d\n", queue->idx);
1063
1064         nvmet_sq_destroy(&queue->nvme_sq);
1065
1066         nvmet_rdma_destroy_queue_ib(queue);
1067         if (!queue->dev->srq) {
1068                 nvmet_rdma_free_cmds(queue->dev, queue->cmds,
1069                                 queue->recv_queue_size,
1070                                 !queue->host_qid);
1071         }
1072         nvmet_rdma_free_rsps(queue);
1073         ida_simple_remove(&nvmet_rdma_queue_ida, queue->idx);
1074         kfree(queue);
1075 }
1076
1077 static void nvmet_rdma_release_queue_work(struct work_struct *w)
1078 {
1079         struct nvmet_rdma_queue *queue =
1080                 container_of(w, struct nvmet_rdma_queue, release_work);
1081         struct nvmet_rdma_device *dev = queue->dev;
1082
1083         nvmet_rdma_free_queue(queue);
1084
1085         kref_put(&dev->ref, nvmet_rdma_free_dev);
1086 }
1087
1088 static int
1089 nvmet_rdma_parse_cm_connect_req(struct rdma_conn_param *conn,
1090                                 struct nvmet_rdma_queue *queue)
1091 {
1092         struct nvme_rdma_cm_req *req;
1093
1094         req = (struct nvme_rdma_cm_req *)conn->private_data;
1095         if (!req || conn->private_data_len == 0)
1096                 return NVME_RDMA_CM_INVALID_LEN;
1097
1098         if (le16_to_cpu(req->recfmt) != NVME_RDMA_CM_FMT_1_0)
1099                 return NVME_RDMA_CM_INVALID_RECFMT;
1100
1101         queue->host_qid = le16_to_cpu(req->qid);
1102
1103         /*
1104          * req->hsqsize corresponds to our recv queue size plus 1
1105          * req->hrqsize corresponds to our send queue size
1106          */
1107         queue->recv_queue_size = le16_to_cpu(req->hsqsize) + 1;
1108         queue->send_queue_size = le16_to_cpu(req->hrqsize);
1109
1110         if (!queue->host_qid && queue->recv_queue_size > NVME_AQ_DEPTH)
1111                 return NVME_RDMA_CM_INVALID_HSQSIZE;
1112
1113         /* XXX: Should we enforce some kind of max for IO queues? */
1114
1115         return 0;
1116 }
1117
1118 static int nvmet_rdma_cm_reject(struct rdma_cm_id *cm_id,
1119                                 enum nvme_rdma_cm_status status)
1120 {
1121         struct nvme_rdma_cm_rej rej;
1122
1123         pr_debug("rejecting connect request: status %d (%s)\n",
1124                  status, nvme_rdma_cm_msg(status));
1125
1126         rej.recfmt = cpu_to_le16(NVME_RDMA_CM_FMT_1_0);
1127         rej.sts = cpu_to_le16(status);
1128
1129         return rdma_reject(cm_id, (void *)&rej, sizeof(rej));
1130 }
1131
1132 static struct nvmet_rdma_queue *
1133 nvmet_rdma_alloc_queue(struct nvmet_rdma_device *ndev,
1134                 struct rdma_cm_id *cm_id,
1135                 struct rdma_cm_event *event)
1136 {
1137         struct nvmet_rdma_queue *queue;
1138         int ret;
1139
1140         queue = kzalloc(sizeof(*queue), GFP_KERNEL);
1141         if (!queue) {
1142                 ret = NVME_RDMA_CM_NO_RSC;
1143                 goto out_reject;
1144         }
1145
1146         ret = nvmet_sq_init(&queue->nvme_sq);
1147         if (ret) {
1148                 ret = NVME_RDMA_CM_NO_RSC;
1149                 goto out_free_queue;
1150         }
1151
1152         ret = nvmet_rdma_parse_cm_connect_req(&event->param.conn, queue);
1153         if (ret)
1154                 goto out_destroy_sq;
1155
1156         /*
1157          * Schedules the actual release because calling rdma_destroy_id from
1158          * inside a CM callback would trigger a deadlock. (great API design..)
1159          */
1160         INIT_WORK(&queue->release_work, nvmet_rdma_release_queue_work);
1161         queue->dev = ndev;
1162         queue->cm_id = cm_id;
1163
1164         spin_lock_init(&queue->state_lock);
1165         queue->state = NVMET_RDMA_Q_CONNECTING;
1166         INIT_LIST_HEAD(&queue->rsp_wait_list);
1167         INIT_LIST_HEAD(&queue->rsp_wr_wait_list);
1168         spin_lock_init(&queue->rsp_wr_wait_lock);
1169         INIT_LIST_HEAD(&queue->free_rsps);
1170         spin_lock_init(&queue->rsps_lock);
1171         INIT_LIST_HEAD(&queue->queue_list);
1172
1173         queue->idx = ida_simple_get(&nvmet_rdma_queue_ida, 0, 0, GFP_KERNEL);
1174         if (queue->idx < 0) {
1175                 ret = NVME_RDMA_CM_NO_RSC;
1176                 goto out_destroy_sq;
1177         }
1178
1179         ret = nvmet_rdma_alloc_rsps(queue);
1180         if (ret) {
1181                 ret = NVME_RDMA_CM_NO_RSC;
1182                 goto out_ida_remove;
1183         }
1184
1185         if (!ndev->srq) {
1186                 queue->cmds = nvmet_rdma_alloc_cmds(ndev,
1187                                 queue->recv_queue_size,
1188                                 !queue->host_qid);
1189                 if (IS_ERR(queue->cmds)) {
1190                         ret = NVME_RDMA_CM_NO_RSC;
1191                         goto out_free_responses;
1192                 }
1193         }
1194
1195         ret = nvmet_rdma_create_queue_ib(queue);
1196         if (ret) {
1197                 pr_err("%s: creating RDMA queue failed (%d).\n",
1198                         __func__, ret);
1199                 ret = NVME_RDMA_CM_NO_RSC;
1200                 goto out_free_cmds;
1201         }
1202
1203         return queue;
1204
1205 out_free_cmds:
1206         if (!ndev->srq) {
1207                 nvmet_rdma_free_cmds(queue->dev, queue->cmds,
1208                                 queue->recv_queue_size,
1209                                 !queue->host_qid);
1210         }
1211 out_free_responses:
1212         nvmet_rdma_free_rsps(queue);
1213 out_ida_remove:
1214         ida_simple_remove(&nvmet_rdma_queue_ida, queue->idx);
1215 out_destroy_sq:
1216         nvmet_sq_destroy(&queue->nvme_sq);
1217 out_free_queue:
1218         kfree(queue);
1219 out_reject:
1220         nvmet_rdma_cm_reject(cm_id, ret);
1221         return NULL;
1222 }
1223
1224 static void nvmet_rdma_qp_event(struct ib_event *event, void *priv)
1225 {
1226         struct nvmet_rdma_queue *queue = priv;
1227
1228         switch (event->event) {
1229         case IB_EVENT_COMM_EST:
1230                 rdma_notify(queue->cm_id, event->event);
1231                 break;
1232         default:
1233                 pr_err("received IB QP event: %s (%d)\n",
1234                        ib_event_msg(event->event), event->event);
1235                 break;
1236         }
1237 }
1238
1239 static int nvmet_rdma_cm_accept(struct rdma_cm_id *cm_id,
1240                 struct nvmet_rdma_queue *queue,
1241                 struct rdma_conn_param *p)
1242 {
1243         struct rdma_conn_param  param = { };
1244         struct nvme_rdma_cm_rep priv = { };
1245         int ret = -ENOMEM;
1246
1247         param.rnr_retry_count = 7;
1248         param.flow_control = 1;
1249         param.initiator_depth = min_t(u8, p->initiator_depth,
1250                 queue->dev->device->attrs.max_qp_init_rd_atom);
1251         param.private_data = &priv;
1252         param.private_data_len = sizeof(priv);
1253         priv.recfmt = cpu_to_le16(NVME_RDMA_CM_FMT_1_0);
1254         priv.crqsize = cpu_to_le16(queue->recv_queue_size);
1255
1256         ret = rdma_accept(cm_id, &param);
1257         if (ret)
1258                 pr_err("rdma_accept failed (error code = %d)\n", ret);
1259
1260         return ret;
1261 }
1262
1263 static int nvmet_rdma_queue_connect(struct rdma_cm_id *cm_id,
1264                 struct rdma_cm_event *event)
1265 {
1266         struct nvmet_rdma_device *ndev;
1267         struct nvmet_rdma_queue *queue;
1268         int ret = -EINVAL;
1269
1270         ndev = nvmet_rdma_find_get_device(cm_id);
1271         if (!ndev) {
1272                 nvmet_rdma_cm_reject(cm_id, NVME_RDMA_CM_NO_RSC);
1273                 return -ECONNREFUSED;
1274         }
1275
1276         queue = nvmet_rdma_alloc_queue(ndev, cm_id, event);
1277         if (!queue) {
1278                 ret = -ENOMEM;
1279                 goto put_device;
1280         }
1281         queue->port = cm_id->context;
1282
1283         if (queue->host_qid == 0) {
1284                 /* Let inflight controller teardown complete */
1285                 flush_scheduled_work();
1286         }
1287
1288         ret = nvmet_rdma_cm_accept(cm_id, queue, &event->param.conn);
1289         if (ret) {
1290                 /*
1291                  * Don't destroy the cm_id in free path, as we implicitly
1292                  * destroy the cm_id here with non-zero ret code.
1293                  */
1294                 queue->cm_id = NULL;
1295                 goto free_queue;
1296         }
1297
1298         mutex_lock(&nvmet_rdma_queue_mutex);
1299         list_add_tail(&queue->queue_list, &nvmet_rdma_queue_list);
1300         mutex_unlock(&nvmet_rdma_queue_mutex);
1301
1302         return 0;
1303
1304 free_queue:
1305         nvmet_rdma_free_queue(queue);
1306 put_device:
1307         kref_put(&ndev->ref, nvmet_rdma_free_dev);
1308
1309         return ret;
1310 }
1311
1312 static void nvmet_rdma_queue_established(struct nvmet_rdma_queue *queue)
1313 {
1314         unsigned long flags;
1315
1316         spin_lock_irqsave(&queue->state_lock, flags);
1317         if (queue->state != NVMET_RDMA_Q_CONNECTING) {
1318                 pr_warn("trying to establish a connected queue\n");
1319                 goto out_unlock;
1320         }
1321         queue->state = NVMET_RDMA_Q_LIVE;
1322
1323         while (!list_empty(&queue->rsp_wait_list)) {
1324                 struct nvmet_rdma_rsp *cmd;
1325
1326                 cmd = list_first_entry(&queue->rsp_wait_list,
1327                                         struct nvmet_rdma_rsp, wait_list);
1328                 list_del(&cmd->wait_list);
1329
1330                 spin_unlock_irqrestore(&queue->state_lock, flags);
1331                 nvmet_rdma_handle_command(queue, cmd);
1332                 spin_lock_irqsave(&queue->state_lock, flags);
1333         }
1334
1335 out_unlock:
1336         spin_unlock_irqrestore(&queue->state_lock, flags);
1337 }
1338
1339 static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
1340 {
1341         bool disconnect = false;
1342         unsigned long flags;
1343
1344         pr_debug("cm_id= %p queue->state= %d\n", queue->cm_id, queue->state);
1345
1346         spin_lock_irqsave(&queue->state_lock, flags);
1347         switch (queue->state) {
1348         case NVMET_RDMA_Q_CONNECTING:
1349         case NVMET_RDMA_Q_LIVE:
1350                 queue->state = NVMET_RDMA_Q_DISCONNECTING;
1351                 disconnect = true;
1352                 break;
1353         case NVMET_RDMA_Q_DISCONNECTING:
1354                 break;
1355         }
1356         spin_unlock_irqrestore(&queue->state_lock, flags);
1357
1358         if (disconnect) {
1359                 rdma_disconnect(queue->cm_id);
1360                 schedule_work(&queue->release_work);
1361         }
1362 }
1363
1364 static void nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
1365 {
1366         bool disconnect = false;
1367
1368         mutex_lock(&nvmet_rdma_queue_mutex);
1369         if (!list_empty(&queue->queue_list)) {
1370                 list_del_init(&queue->queue_list);
1371                 disconnect = true;
1372         }
1373         mutex_unlock(&nvmet_rdma_queue_mutex);
1374
1375         if (disconnect)
1376                 __nvmet_rdma_queue_disconnect(queue);
1377 }
1378
1379 static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id,
1380                 struct nvmet_rdma_queue *queue)
1381 {
1382         WARN_ON_ONCE(queue->state != NVMET_RDMA_Q_CONNECTING);
1383
1384         mutex_lock(&nvmet_rdma_queue_mutex);
1385         if (!list_empty(&queue->queue_list))
1386                 list_del_init(&queue->queue_list);
1387         mutex_unlock(&nvmet_rdma_queue_mutex);
1388
1389         pr_err("failed to connect queue %d\n", queue->idx);
1390         schedule_work(&queue->release_work);
1391 }
1392
1393 /**
1394  * nvme_rdma_device_removal() - Handle RDMA device removal
1395  * @cm_id:      rdma_cm id, used for nvmet port
1396  * @queue:      nvmet rdma queue (cm id qp_context)
1397  *
1398  * DEVICE_REMOVAL event notifies us that the RDMA device is about
1399  * to unplug. Note that this event can be generated on a normal
1400  * queue cm_id and/or a device bound listener cm_id (where in this
1401  * case queue will be null).
1402  *
1403  * We registered an ib_client to handle device removal for queues,
1404  * so we only need to handle the listening port cm_ids. In this case
1405  * we nullify the priv to prevent double cm_id destruction and destroying
1406  * the cm_id implicitely by returning a non-zero rc to the callout.
1407  */
1408 static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id,
1409                 struct nvmet_rdma_queue *queue)
1410 {
1411         struct nvmet_port *port;
1412
1413         if (queue) {
1414                 /*
1415                  * This is a queue cm_id. we have registered
1416                  * an ib_client to handle queues removal
1417                  * so don't interfear and just return.
1418                  */
1419                 return 0;
1420         }
1421
1422         port = cm_id->context;
1423
1424         /*
1425          * This is a listener cm_id. Make sure that
1426          * future remove_port won't invoke a double
1427          * cm_id destroy. use atomic xchg to make sure
1428          * we don't compete with remove_port.
1429          */
1430         if (xchg(&port->priv, NULL) != cm_id)
1431                 return 0;
1432
1433         /*
1434          * We need to return 1 so that the core will destroy
1435          * it's own ID.  What a great API design..
1436          */
1437         return 1;
1438 }
1439
1440 static int nvmet_rdma_cm_handler(struct rdma_cm_id *cm_id,
1441                 struct rdma_cm_event *event)
1442 {
1443         struct nvmet_rdma_queue *queue = NULL;
1444         int ret = 0;
1445
1446         if (cm_id->qp)
1447                 queue = cm_id->qp->qp_context;
1448
1449         pr_debug("%s (%d): status %d id %p\n",
1450                 rdma_event_msg(event->event), event->event,
1451                 event->status, cm_id);
1452
1453         switch (event->event) {
1454         case RDMA_CM_EVENT_CONNECT_REQUEST:
1455                 ret = nvmet_rdma_queue_connect(cm_id, event);
1456                 break;
1457         case RDMA_CM_EVENT_ESTABLISHED:
1458                 nvmet_rdma_queue_established(queue);
1459                 break;
1460         case RDMA_CM_EVENT_ADDR_CHANGE:
1461         case RDMA_CM_EVENT_DISCONNECTED:
1462         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
1463                 nvmet_rdma_queue_disconnect(queue);
1464                 break;
1465         case RDMA_CM_EVENT_DEVICE_REMOVAL:
1466                 ret = nvmet_rdma_device_removal(cm_id, queue);
1467                 break;
1468         case RDMA_CM_EVENT_REJECTED:
1469                 pr_debug("Connection rejected: %s\n",
1470                          rdma_reject_msg(cm_id, event->status));
1471                 /* FALLTHROUGH */
1472         case RDMA_CM_EVENT_UNREACHABLE:
1473         case RDMA_CM_EVENT_CONNECT_ERROR:
1474                 nvmet_rdma_queue_connect_fail(cm_id, queue);
1475                 break;
1476         default:
1477                 pr_err("received unrecognized RDMA CM event %d\n",
1478                         event->event);
1479                 break;
1480         }
1481
1482         return ret;
1483 }
1484
1485 static void nvmet_rdma_delete_ctrl(struct nvmet_ctrl *ctrl)
1486 {
1487         struct nvmet_rdma_queue *queue;
1488
1489 restart:
1490         mutex_lock(&nvmet_rdma_queue_mutex);
1491         list_for_each_entry(queue, &nvmet_rdma_queue_list, queue_list) {
1492                 if (queue->nvme_sq.ctrl == ctrl) {
1493                         list_del_init(&queue->queue_list);
1494                         mutex_unlock(&nvmet_rdma_queue_mutex);
1495
1496                         __nvmet_rdma_queue_disconnect(queue);
1497                         goto restart;
1498                 }
1499         }
1500         mutex_unlock(&nvmet_rdma_queue_mutex);
1501 }
1502
1503 static int nvmet_rdma_add_port(struct nvmet_port *port)
1504 {
1505         struct rdma_cm_id *cm_id;
1506         struct sockaddr_storage addr = { };
1507         __kernel_sa_family_t af;
1508         int ret;
1509
1510         switch (port->disc_addr.adrfam) {
1511         case NVMF_ADDR_FAMILY_IP4:
1512                 af = AF_INET;
1513                 break;
1514         case NVMF_ADDR_FAMILY_IP6:
1515                 af = AF_INET6;
1516                 break;
1517         default:
1518                 pr_err("address family %d not supported\n",
1519                                 port->disc_addr.adrfam);
1520                 return -EINVAL;
1521         }
1522
1523         if (port->inline_data_size < 0) {
1524                 port->inline_data_size = NVMET_RDMA_DEFAULT_INLINE_DATA_SIZE;
1525         } else if (port->inline_data_size > NVMET_RDMA_MAX_INLINE_DATA_SIZE) {
1526                 pr_warn("inline_data_size %u is too large, reducing to %u\n",
1527                         port->inline_data_size,
1528                         NVMET_RDMA_MAX_INLINE_DATA_SIZE);
1529                 port->inline_data_size = NVMET_RDMA_MAX_INLINE_DATA_SIZE;
1530         }
1531
1532         ret = inet_pton_with_scope(&init_net, af, port->disc_addr.traddr,
1533                         port->disc_addr.trsvcid, &addr);
1534         if (ret) {
1535                 pr_err("malformed ip/port passed: %s:%s\n",
1536                         port->disc_addr.traddr, port->disc_addr.trsvcid);
1537                 return ret;
1538         }
1539
1540         cm_id = rdma_create_id(&init_net, nvmet_rdma_cm_handler, port,
1541                         RDMA_PS_TCP, IB_QPT_RC);
1542         if (IS_ERR(cm_id)) {
1543                 pr_err("CM ID creation failed\n");
1544                 return PTR_ERR(cm_id);
1545         }
1546
1547         /*
1548          * Allow both IPv4 and IPv6 sockets to bind a single port
1549          * at the same time.
1550          */
1551         ret = rdma_set_afonly(cm_id, 1);
1552         if (ret) {
1553                 pr_err("rdma_set_afonly failed (%d)\n", ret);
1554                 goto out_destroy_id;
1555         }
1556
1557         ret = rdma_bind_addr(cm_id, (struct sockaddr *)&addr);
1558         if (ret) {
1559                 pr_err("binding CM ID to %pISpcs failed (%d)\n",
1560                         (struct sockaddr *)&addr, ret);
1561                 goto out_destroy_id;
1562         }
1563
1564         ret = rdma_listen(cm_id, 128);
1565         if (ret) {
1566                 pr_err("listening to %pISpcs failed (%d)\n",
1567                         (struct sockaddr *)&addr, ret);
1568                 goto out_destroy_id;
1569         }
1570
1571         pr_info("enabling port %d (%pISpcs)\n",
1572                 le16_to_cpu(port->disc_addr.portid), (struct sockaddr *)&addr);
1573         port->priv = cm_id;
1574         return 0;
1575
1576 out_destroy_id:
1577         rdma_destroy_id(cm_id);
1578         return ret;
1579 }
1580
1581 static void nvmet_rdma_remove_port(struct nvmet_port *port)
1582 {
1583         struct rdma_cm_id *cm_id = xchg(&port->priv, NULL);
1584
1585         if (cm_id)
1586                 rdma_destroy_id(cm_id);
1587 }
1588
1589 static void nvmet_rdma_disc_port_addr(struct nvmet_req *req,
1590                 struct nvmet_port *port, char *traddr)
1591 {
1592         struct rdma_cm_id *cm_id = port->priv;
1593
1594         if (inet_addr_is_any((struct sockaddr *)&cm_id->route.addr.src_addr)) {
1595                 struct nvmet_rdma_rsp *rsp =
1596                         container_of(req, struct nvmet_rdma_rsp, req);
1597                 struct rdma_cm_id *req_cm_id = rsp->queue->cm_id;
1598                 struct sockaddr *addr = (void *)&req_cm_id->route.addr.src_addr;
1599
1600                 sprintf(traddr, "%pISc", addr);
1601         } else {
1602                 memcpy(traddr, port->disc_addr.traddr, NVMF_TRADDR_SIZE);
1603         }
1604 }
1605
1606 static const struct nvmet_fabrics_ops nvmet_rdma_ops = {
1607         .owner                  = THIS_MODULE,
1608         .type                   = NVMF_TRTYPE_RDMA,
1609         .msdbd                  = 1,
1610         .has_keyed_sgls         = 1,
1611         .add_port               = nvmet_rdma_add_port,
1612         .remove_port            = nvmet_rdma_remove_port,
1613         .queue_response         = nvmet_rdma_queue_response,
1614         .delete_ctrl            = nvmet_rdma_delete_ctrl,
1615         .disc_traddr            = nvmet_rdma_disc_port_addr,
1616 };
1617
1618 static void nvmet_rdma_remove_one(struct ib_device *ib_device, void *client_data)
1619 {
1620         struct nvmet_rdma_queue *queue, *tmp;
1621         struct nvmet_rdma_device *ndev;
1622         bool found = false;
1623
1624         mutex_lock(&device_list_mutex);
1625         list_for_each_entry(ndev, &device_list, entry) {
1626                 if (ndev->device == ib_device) {
1627                         found = true;
1628                         break;
1629                 }
1630         }
1631         mutex_unlock(&device_list_mutex);
1632
1633         if (!found)
1634                 return;
1635
1636         /*
1637          * IB Device that is used by nvmet controllers is being removed,
1638          * delete all queues using this device.
1639          */
1640         mutex_lock(&nvmet_rdma_queue_mutex);
1641         list_for_each_entry_safe(queue, tmp, &nvmet_rdma_queue_list,
1642                                  queue_list) {
1643                 if (queue->dev->device != ib_device)
1644                         continue;
1645
1646                 pr_info("Removing queue %d\n", queue->idx);
1647                 list_del_init(&queue->queue_list);
1648                 __nvmet_rdma_queue_disconnect(queue);
1649         }
1650         mutex_unlock(&nvmet_rdma_queue_mutex);
1651
1652         flush_scheduled_work();
1653 }
1654
1655 static struct ib_client nvmet_rdma_ib_client = {
1656         .name   = "nvmet_rdma",
1657         .remove = nvmet_rdma_remove_one
1658 };
1659
1660 static int __init nvmet_rdma_init(void)
1661 {
1662         int ret;
1663
1664         ret = ib_register_client(&nvmet_rdma_ib_client);
1665         if (ret)
1666                 return ret;
1667
1668         ret = nvmet_register_transport(&nvmet_rdma_ops);
1669         if (ret)
1670                 goto err_ib_client;
1671
1672         return 0;
1673
1674 err_ib_client:
1675         ib_unregister_client(&nvmet_rdma_ib_client);
1676         return ret;
1677 }
1678
1679 static void __exit nvmet_rdma_exit(void)
1680 {
1681         nvmet_unregister_transport(&nvmet_rdma_ops);
1682         ib_unregister_client(&nvmet_rdma_ib_client);
1683         WARN_ON_ONCE(!list_empty(&nvmet_rdma_queue_list));
1684         ida_destroy(&nvmet_rdma_queue_ida);
1685 }
1686
1687 module_init(nvmet_rdma_init);
1688 module_exit(nvmet_rdma_exit);
1689
1690 MODULE_LICENSE("GPL v2");
1691 MODULE_ALIAS("nvmet-transport-1"); /* 1 == NVMF_TRTYPE_RDMA */