nvme: introduce nvme_reinit_tagset
[linux-2.6-microblaze.git] / drivers / nvme / host / fc.c
1 /*
2  * Copyright (c) 2016 Avago Technologies.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of version 2 of the GNU General Public License as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful.
9  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
10  * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
11  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO
12  * THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
13  * See the GNU General Public License for more details, a copy of which
14  * can be found in the file COPYING included with this package
15  *
16  */
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 #include <linux/module.h>
19 #include <linux/parser.h>
20 #include <uapi/scsi/fc/fc_fs.h>
21 #include <uapi/scsi/fc/fc_els.h>
22 #include <linux/delay.h>
23
24 #include "nvme.h"
25 #include "fabrics.h"
26 #include <linux/nvme-fc-driver.h>
27 #include <linux/nvme-fc.h>
28
29
30 /* *************************** Data Structures/Defines ****************** */
31
32
33 /*
34  * We handle AEN commands ourselves and don't even let the
35  * block layer know about them.
36  */
37 #define NVME_FC_NR_AEN_COMMANDS 1
38 #define NVME_FC_AQ_BLKMQ_DEPTH  \
39         (NVME_AQ_DEPTH - NVME_FC_NR_AEN_COMMANDS)
40 #define AEN_CMDID_BASE          (NVME_FC_AQ_BLKMQ_DEPTH + 1)
41
42 enum nvme_fc_queue_flags {
43         NVME_FC_Q_CONNECTED = (1 << 0),
44 };
45
46 #define NVMEFC_QUEUE_DELAY      3               /* ms units */
47
48 struct nvme_fc_queue {
49         struct nvme_fc_ctrl     *ctrl;
50         struct device           *dev;
51         struct blk_mq_hw_ctx    *hctx;
52         void                    *lldd_handle;
53         int                     queue_size;
54         size_t                  cmnd_capsule_len;
55         u32                     qnum;
56         u32                     rqcnt;
57         u32                     seqno;
58
59         u64                     connection_id;
60         atomic_t                csn;
61
62         unsigned long           flags;
63 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
64
65 enum nvme_fcop_flags {
66         FCOP_FLAGS_TERMIO       = (1 << 0),
67         FCOP_FLAGS_RELEASED     = (1 << 1),
68         FCOP_FLAGS_COMPLETE     = (1 << 2),
69         FCOP_FLAGS_AEN          = (1 << 3),
70 };
71
72 struct nvmefc_ls_req_op {
73         struct nvmefc_ls_req    ls_req;
74
75         struct nvme_fc_rport    *rport;
76         struct nvme_fc_queue    *queue;
77         struct request          *rq;
78         u32                     flags;
79
80         int                     ls_error;
81         struct completion       ls_done;
82         struct list_head        lsreq_list;     /* rport->ls_req_list */
83         bool                    req_queued;
84 };
85
86 enum nvme_fcpop_state {
87         FCPOP_STATE_UNINIT      = 0,
88         FCPOP_STATE_IDLE        = 1,
89         FCPOP_STATE_ACTIVE      = 2,
90         FCPOP_STATE_ABORTED     = 3,
91         FCPOP_STATE_COMPLETE    = 4,
92 };
93
94 struct nvme_fc_fcp_op {
95         struct nvme_request     nreq;           /*
96                                                  * nvme/host/core.c
97                                                  * requires this to be
98                                                  * the 1st element in the
99                                                  * private structure
100                                                  * associated with the
101                                                  * request.
102                                                  */
103         struct nvmefc_fcp_req   fcp_req;
104
105         struct nvme_fc_ctrl     *ctrl;
106         struct nvme_fc_queue    *queue;
107         struct request          *rq;
108
109         atomic_t                state;
110         u32                     flags;
111         u32                     rqno;
112         u32                     nents;
113
114         struct nvme_fc_cmd_iu   cmd_iu;
115         struct nvme_fc_ersp_iu  rsp_iu;
116 };
117
118 struct nvme_fc_lport {
119         struct nvme_fc_local_port       localport;
120
121         struct ida                      endp_cnt;
122         struct list_head                port_list;      /* nvme_fc_port_list */
123         struct list_head                endp_list;
124         struct device                   *dev;   /* physical device for dma */
125         struct nvme_fc_port_template    *ops;
126         struct kref                     ref;
127 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
128
129 struct nvme_fc_rport {
130         struct nvme_fc_remote_port      remoteport;
131
132         struct list_head                endp_list; /* for lport->endp_list */
133         struct list_head                ctrl_list;
134         struct list_head                ls_req_list;
135         struct device                   *dev;   /* physical device for dma */
136         struct nvme_fc_lport            *lport;
137         spinlock_t                      lock;
138         struct kref                     ref;
139 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
140
141 enum nvme_fcctrl_flags {
142         FCCTRL_TERMIO           = (1 << 0),
143 };
144
145 struct nvme_fc_ctrl {
146         spinlock_t              lock;
147         struct nvme_fc_queue    *queues;
148         struct device           *dev;
149         struct nvme_fc_lport    *lport;
150         struct nvme_fc_rport    *rport;
151         u32                     cnum;
152
153         u64                     association_id;
154
155         struct list_head        ctrl_list;      /* rport->ctrl_list */
156
157         struct blk_mq_tag_set   admin_tag_set;
158         struct blk_mq_tag_set   tag_set;
159
160         struct work_struct      delete_work;
161         struct delayed_work     connect_work;
162
163         struct kref             ref;
164         u32                     flags;
165         u32                     iocnt;
166         wait_queue_head_t       ioabort_wait;
167
168         struct nvme_fc_fcp_op   aen_ops[NVME_FC_NR_AEN_COMMANDS];
169
170         struct nvme_ctrl        ctrl;
171 };
172
173 static inline struct nvme_fc_ctrl *
174 to_fc_ctrl(struct nvme_ctrl *ctrl)
175 {
176         return container_of(ctrl, struct nvme_fc_ctrl, ctrl);
177 }
178
179 static inline struct nvme_fc_lport *
180 localport_to_lport(struct nvme_fc_local_port *portptr)
181 {
182         return container_of(portptr, struct nvme_fc_lport, localport);
183 }
184
185 static inline struct nvme_fc_rport *
186 remoteport_to_rport(struct nvme_fc_remote_port *portptr)
187 {
188         return container_of(portptr, struct nvme_fc_rport, remoteport);
189 }
190
191 static inline struct nvmefc_ls_req_op *
192 ls_req_to_lsop(struct nvmefc_ls_req *lsreq)
193 {
194         return container_of(lsreq, struct nvmefc_ls_req_op, ls_req);
195 }
196
197 static inline struct nvme_fc_fcp_op *
198 fcp_req_to_fcp_op(struct nvmefc_fcp_req *fcpreq)
199 {
200         return container_of(fcpreq, struct nvme_fc_fcp_op, fcp_req);
201 }
202
203
204
205 /* *************************** Globals **************************** */
206
207
208 static DEFINE_SPINLOCK(nvme_fc_lock);
209
210 static LIST_HEAD(nvme_fc_lport_list);
211 static DEFINE_IDA(nvme_fc_local_port_cnt);
212 static DEFINE_IDA(nvme_fc_ctrl_cnt);
213
214
215
216 /*
217  * These items are short-term. They will eventually be moved into
218  * a generic FC class. See comments in module init.
219  */
220 static struct class *fc_class;
221 static struct device *fc_udev_device;
222
223
224 /* *********************** FC-NVME Port Management ************************ */
225
226 static int __nvme_fc_del_ctrl(struct nvme_fc_ctrl *);
227 static void __nvme_fc_delete_hw_queue(struct nvme_fc_ctrl *,
228                         struct nvme_fc_queue *, unsigned int);
229
230 static void
231 nvme_fc_free_lport(struct kref *ref)
232 {
233         struct nvme_fc_lport *lport =
234                 container_of(ref, struct nvme_fc_lport, ref);
235         unsigned long flags;
236
237         WARN_ON(lport->localport.port_state != FC_OBJSTATE_DELETED);
238         WARN_ON(!list_empty(&lport->endp_list));
239
240         /* remove from transport list */
241         spin_lock_irqsave(&nvme_fc_lock, flags);
242         list_del(&lport->port_list);
243         spin_unlock_irqrestore(&nvme_fc_lock, flags);
244
245         /* let the LLDD know we've finished tearing it down */
246         lport->ops->localport_delete(&lport->localport);
247
248         ida_simple_remove(&nvme_fc_local_port_cnt, lport->localport.port_num);
249         ida_destroy(&lport->endp_cnt);
250
251         put_device(lport->dev);
252
253         kfree(lport);
254 }
255
256 static void
257 nvme_fc_lport_put(struct nvme_fc_lport *lport)
258 {
259         kref_put(&lport->ref, nvme_fc_free_lport);
260 }
261
262 static int
263 nvme_fc_lport_get(struct nvme_fc_lport *lport)
264 {
265         return kref_get_unless_zero(&lport->ref);
266 }
267
268
269 static struct nvme_fc_lport *
270 nvme_fc_attach_to_unreg_lport(struct nvme_fc_port_info *pinfo)
271 {
272         struct nvme_fc_lport *lport;
273         unsigned long flags;
274
275         spin_lock_irqsave(&nvme_fc_lock, flags);
276
277         list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
278                 if (lport->localport.node_name != pinfo->node_name ||
279                     lport->localport.port_name != pinfo->port_name)
280                         continue;
281
282                 if (lport->localport.port_state != FC_OBJSTATE_DELETED) {
283                         lport = ERR_PTR(-EEXIST);
284                         goto out_done;
285                 }
286
287                 if (!nvme_fc_lport_get(lport)) {
288                         /*
289                          * fails if ref cnt already 0. If so,
290                          * act as if lport already deleted
291                          */
292                         lport = NULL;
293                         goto out_done;
294                 }
295
296                 /* resume the lport */
297
298                 lport->localport.port_role = pinfo->port_role;
299                 lport->localport.port_id = pinfo->port_id;
300                 lport->localport.port_state = FC_OBJSTATE_ONLINE;
301
302                 spin_unlock_irqrestore(&nvme_fc_lock, flags);
303
304                 return lport;
305         }
306
307         lport = NULL;
308
309 out_done:
310         spin_unlock_irqrestore(&nvme_fc_lock, flags);
311
312         return lport;
313 }
314
315 /**
316  * nvme_fc_register_localport - transport entry point called by an
317  *                              LLDD to register the existence of a NVME
318  *                              host FC port.
319  * @pinfo:     pointer to information about the port to be registered
320  * @template:  LLDD entrypoints and operational parameters for the port
321  * @dev:       physical hardware device node port corresponds to. Will be
322  *             used for DMA mappings
323  * @lport_p:   pointer to a local port pointer. Upon success, the routine
324  *             will allocate a nvme_fc_local_port structure and place its
325  *             address in the local port pointer. Upon failure, local port
326  *             pointer will be set to 0.
327  *
328  * Returns:
329  * a completion status. Must be 0 upon success; a negative errno
330  * (ex: -ENXIO) upon failure.
331  */
332 int
333 nvme_fc_register_localport(struct nvme_fc_port_info *pinfo,
334                         struct nvme_fc_port_template *template,
335                         struct device *dev,
336                         struct nvme_fc_local_port **portptr)
337 {
338         struct nvme_fc_lport *newrec;
339         unsigned long flags;
340         int ret, idx;
341
342         if (!template->localport_delete || !template->remoteport_delete ||
343             !template->ls_req || !template->fcp_io ||
344             !template->ls_abort || !template->fcp_abort ||
345             !template->max_hw_queues || !template->max_sgl_segments ||
346             !template->max_dif_sgl_segments || !template->dma_boundary) {
347                 ret = -EINVAL;
348                 goto out_reghost_failed;
349         }
350
351         /*
352          * look to see if there is already a localport that had been
353          * deregistered and in the process of waiting for all the
354          * references to fully be removed.  If the references haven't
355          * expired, we can simply re-enable the localport. Remoteports
356          * and controller reconnections should resume naturally.
357          */
358         newrec = nvme_fc_attach_to_unreg_lport(pinfo);
359
360         /* found an lport, but something about its state is bad */
361         if (IS_ERR(newrec)) {
362                 ret = PTR_ERR(newrec);
363                 goto out_reghost_failed;
364
365         /* found existing lport, which was resumed */
366         } else if (newrec) {
367                 *portptr = &newrec->localport;
368                 return 0;
369         }
370
371         /* nothing found - allocate a new localport struct */
372
373         newrec = kmalloc((sizeof(*newrec) + template->local_priv_sz),
374                          GFP_KERNEL);
375         if (!newrec) {
376                 ret = -ENOMEM;
377                 goto out_reghost_failed;
378         }
379
380         idx = ida_simple_get(&nvme_fc_local_port_cnt, 0, 0, GFP_KERNEL);
381         if (idx < 0) {
382                 ret = -ENOSPC;
383                 goto out_fail_kfree;
384         }
385
386         if (!get_device(dev) && dev) {
387                 ret = -ENODEV;
388                 goto out_ida_put;
389         }
390
391         INIT_LIST_HEAD(&newrec->port_list);
392         INIT_LIST_HEAD(&newrec->endp_list);
393         kref_init(&newrec->ref);
394         newrec->ops = template;
395         newrec->dev = dev;
396         ida_init(&newrec->endp_cnt);
397         newrec->localport.private = &newrec[1];
398         newrec->localport.node_name = pinfo->node_name;
399         newrec->localport.port_name = pinfo->port_name;
400         newrec->localport.port_role = pinfo->port_role;
401         newrec->localport.port_id = pinfo->port_id;
402         newrec->localport.port_state = FC_OBJSTATE_ONLINE;
403         newrec->localport.port_num = idx;
404
405         spin_lock_irqsave(&nvme_fc_lock, flags);
406         list_add_tail(&newrec->port_list, &nvme_fc_lport_list);
407         spin_unlock_irqrestore(&nvme_fc_lock, flags);
408
409         if (dev)
410                 dma_set_seg_boundary(dev, template->dma_boundary);
411
412         *portptr = &newrec->localport;
413         return 0;
414
415 out_ida_put:
416         ida_simple_remove(&nvme_fc_local_port_cnt, idx);
417 out_fail_kfree:
418         kfree(newrec);
419 out_reghost_failed:
420         *portptr = NULL;
421
422         return ret;
423 }
424 EXPORT_SYMBOL_GPL(nvme_fc_register_localport);
425
426 /**
427  * nvme_fc_unregister_localport - transport entry point called by an
428  *                              LLDD to deregister/remove a previously
429  *                              registered a NVME host FC port.
430  * @localport: pointer to the (registered) local port that is to be
431  *             deregistered.
432  *
433  * Returns:
434  * a completion status. Must be 0 upon success; a negative errno
435  * (ex: -ENXIO) upon failure.
436  */
437 int
438 nvme_fc_unregister_localport(struct nvme_fc_local_port *portptr)
439 {
440         struct nvme_fc_lport *lport = localport_to_lport(portptr);
441         unsigned long flags;
442
443         if (!portptr)
444                 return -EINVAL;
445
446         spin_lock_irqsave(&nvme_fc_lock, flags);
447
448         if (portptr->port_state != FC_OBJSTATE_ONLINE) {
449                 spin_unlock_irqrestore(&nvme_fc_lock, flags);
450                 return -EINVAL;
451         }
452         portptr->port_state = FC_OBJSTATE_DELETED;
453
454         spin_unlock_irqrestore(&nvme_fc_lock, flags);
455
456         nvme_fc_lport_put(lport);
457
458         return 0;
459 }
460 EXPORT_SYMBOL_GPL(nvme_fc_unregister_localport);
461
462 /*
463  * TRADDR strings, per FC-NVME are fixed format:
464  *   "nn-0x<16hexdigits>:pn-0x<16hexdigits>" - 43 characters
465  * udev event will only differ by prefix of what field is
466  * being specified:
467  *    "NVMEFC_HOST_TRADDR=" or "NVMEFC_TRADDR=" - 19 max characters
468  *  19 + 43 + null_fudge = 64 characters
469  */
470 #define FCNVME_TRADDR_LENGTH            64
471
472 static void
473 nvme_fc_signal_discovery_scan(struct nvme_fc_lport *lport,
474                 struct nvme_fc_rport *rport)
475 {
476         char hostaddr[FCNVME_TRADDR_LENGTH];    /* NVMEFC_HOST_TRADDR=...*/
477         char tgtaddr[FCNVME_TRADDR_LENGTH];     /* NVMEFC_TRADDR=...*/
478         char *envp[4] = { "FC_EVENT=nvmediscovery", hostaddr, tgtaddr, NULL };
479
480         if (!(rport->remoteport.port_role & FC_PORT_ROLE_NVME_DISCOVERY))
481                 return;
482
483         snprintf(hostaddr, sizeof(hostaddr),
484                 "NVMEFC_HOST_TRADDR=nn-0x%016llx:pn-0x%016llx",
485                 lport->localport.node_name, lport->localport.port_name);
486         snprintf(tgtaddr, sizeof(tgtaddr),
487                 "NVMEFC_TRADDR=nn-0x%016llx:pn-0x%016llx",
488                 rport->remoteport.node_name, rport->remoteport.port_name);
489         kobject_uevent_env(&fc_udev_device->kobj, KOBJ_CHANGE, envp);
490 }
491
492 static void
493 nvme_fc_free_rport(struct kref *ref)
494 {
495         struct nvme_fc_rport *rport =
496                 container_of(ref, struct nvme_fc_rport, ref);
497         struct nvme_fc_lport *lport =
498                         localport_to_lport(rport->remoteport.localport);
499         unsigned long flags;
500
501         WARN_ON(rport->remoteport.port_state != FC_OBJSTATE_DELETED);
502         WARN_ON(!list_empty(&rport->ctrl_list));
503
504         /* remove from lport list */
505         spin_lock_irqsave(&nvme_fc_lock, flags);
506         list_del(&rport->endp_list);
507         spin_unlock_irqrestore(&nvme_fc_lock, flags);
508
509         /* let the LLDD know we've finished tearing it down */
510         lport->ops->remoteport_delete(&rport->remoteport);
511
512         ida_simple_remove(&lport->endp_cnt, rport->remoteport.port_num);
513
514         kfree(rport);
515
516         nvme_fc_lport_put(lport);
517 }
518
519 static void
520 nvme_fc_rport_put(struct nvme_fc_rport *rport)
521 {
522         kref_put(&rport->ref, nvme_fc_free_rport);
523 }
524
525 static int
526 nvme_fc_rport_get(struct nvme_fc_rport *rport)
527 {
528         return kref_get_unless_zero(&rport->ref);
529 }
530
531 /**
532  * nvme_fc_register_remoteport - transport entry point called by an
533  *                              LLDD to register the existence of a NVME
534  *                              subsystem FC port on its fabric.
535  * @localport: pointer to the (registered) local port that the remote
536  *             subsystem port is connected to.
537  * @pinfo:     pointer to information about the port to be registered
538  * @rport_p:   pointer to a remote port pointer. Upon success, the routine
539  *             will allocate a nvme_fc_remote_port structure and place its
540  *             address in the remote port pointer. Upon failure, remote port
541  *             pointer will be set to 0.
542  *
543  * Returns:
544  * a completion status. Must be 0 upon success; a negative errno
545  * (ex: -ENXIO) upon failure.
546  */
547 int
548 nvme_fc_register_remoteport(struct nvme_fc_local_port *localport,
549                                 struct nvme_fc_port_info *pinfo,
550                                 struct nvme_fc_remote_port **portptr)
551 {
552         struct nvme_fc_lport *lport = localport_to_lport(localport);
553         struct nvme_fc_rport *newrec;
554         unsigned long flags;
555         int ret, idx;
556
557         newrec = kmalloc((sizeof(*newrec) + lport->ops->remote_priv_sz),
558                          GFP_KERNEL);
559         if (!newrec) {
560                 ret = -ENOMEM;
561                 goto out_reghost_failed;
562         }
563
564         if (!nvme_fc_lport_get(lport)) {
565                 ret = -ESHUTDOWN;
566                 goto out_kfree_rport;
567         }
568
569         idx = ida_simple_get(&lport->endp_cnt, 0, 0, GFP_KERNEL);
570         if (idx < 0) {
571                 ret = -ENOSPC;
572                 goto out_lport_put;
573         }
574
575         INIT_LIST_HEAD(&newrec->endp_list);
576         INIT_LIST_HEAD(&newrec->ctrl_list);
577         INIT_LIST_HEAD(&newrec->ls_req_list);
578         kref_init(&newrec->ref);
579         spin_lock_init(&newrec->lock);
580         newrec->remoteport.localport = &lport->localport;
581         newrec->dev = lport->dev;
582         newrec->lport = lport;
583         newrec->remoteport.private = &newrec[1];
584         newrec->remoteport.port_role = pinfo->port_role;
585         newrec->remoteport.node_name = pinfo->node_name;
586         newrec->remoteport.port_name = pinfo->port_name;
587         newrec->remoteport.port_id = pinfo->port_id;
588         newrec->remoteport.port_state = FC_OBJSTATE_ONLINE;
589         newrec->remoteport.port_num = idx;
590
591         spin_lock_irqsave(&nvme_fc_lock, flags);
592         list_add_tail(&newrec->endp_list, &lport->endp_list);
593         spin_unlock_irqrestore(&nvme_fc_lock, flags);
594
595         nvme_fc_signal_discovery_scan(lport, newrec);
596
597         *portptr = &newrec->remoteport;
598         return 0;
599
600 out_lport_put:
601         nvme_fc_lport_put(lport);
602 out_kfree_rport:
603         kfree(newrec);
604 out_reghost_failed:
605         *portptr = NULL;
606         return ret;
607 }
608 EXPORT_SYMBOL_GPL(nvme_fc_register_remoteport);
609
610 static int
611 nvme_fc_abort_lsops(struct nvme_fc_rport *rport)
612 {
613         struct nvmefc_ls_req_op *lsop;
614         unsigned long flags;
615
616 restart:
617         spin_lock_irqsave(&rport->lock, flags);
618
619         list_for_each_entry(lsop, &rport->ls_req_list, lsreq_list) {
620                 if (!(lsop->flags & FCOP_FLAGS_TERMIO)) {
621                         lsop->flags |= FCOP_FLAGS_TERMIO;
622                         spin_unlock_irqrestore(&rport->lock, flags);
623                         rport->lport->ops->ls_abort(&rport->lport->localport,
624                                                 &rport->remoteport,
625                                                 &lsop->ls_req);
626                         goto restart;
627                 }
628         }
629         spin_unlock_irqrestore(&rport->lock, flags);
630
631         return 0;
632 }
633
634 /**
635  * nvme_fc_unregister_remoteport - transport entry point called by an
636  *                              LLDD to deregister/remove a previously
637  *                              registered a NVME subsystem FC port.
638  * @remoteport: pointer to the (registered) remote port that is to be
639  *              deregistered.
640  *
641  * Returns:
642  * a completion status. Must be 0 upon success; a negative errno
643  * (ex: -ENXIO) upon failure.
644  */
645 int
646 nvme_fc_unregister_remoteport(struct nvme_fc_remote_port *portptr)
647 {
648         struct nvme_fc_rport *rport = remoteport_to_rport(portptr);
649         struct nvme_fc_ctrl *ctrl;
650         unsigned long flags;
651
652         if (!portptr)
653                 return -EINVAL;
654
655         spin_lock_irqsave(&rport->lock, flags);
656
657         if (portptr->port_state != FC_OBJSTATE_ONLINE) {
658                 spin_unlock_irqrestore(&rport->lock, flags);
659                 return -EINVAL;
660         }
661         portptr->port_state = FC_OBJSTATE_DELETED;
662
663         /* tear down all associations to the remote port */
664         list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list)
665                 __nvme_fc_del_ctrl(ctrl);
666
667         spin_unlock_irqrestore(&rport->lock, flags);
668
669         nvme_fc_abort_lsops(rport);
670
671         nvme_fc_rport_put(rport);
672         return 0;
673 }
674 EXPORT_SYMBOL_GPL(nvme_fc_unregister_remoteport);
675
676 /**
677  * nvme_fc_rescan_remoteport - transport entry point called by an
678  *                              LLDD to request a nvme device rescan.
679  * @remoteport: pointer to the (registered) remote port that is to be
680  *              rescanned.
681  *
682  * Returns: N/A
683  */
684 void
685 nvme_fc_rescan_remoteport(struct nvme_fc_remote_port *remoteport)
686 {
687         struct nvme_fc_rport *rport = remoteport_to_rport(remoteport);
688
689         nvme_fc_signal_discovery_scan(rport->lport, rport);
690 }
691 EXPORT_SYMBOL_GPL(nvme_fc_rescan_remoteport);
692
693
694 /* *********************** FC-NVME DMA Handling **************************** */
695
696 /*
697  * The fcloop device passes in a NULL device pointer. Real LLD's will
698  * pass in a valid device pointer. If NULL is passed to the dma mapping
699  * routines, depending on the platform, it may or may not succeed, and
700  * may crash.
701  *
702  * As such:
703  * Wrapper all the dma routines and check the dev pointer.
704  *
705  * If simple mappings (return just a dma address, we'll noop them,
706  * returning a dma address of 0.
707  *
708  * On more complex mappings (dma_map_sg), a pseudo routine fills
709  * in the scatter list, setting all dma addresses to 0.
710  */
711
712 static inline dma_addr_t
713 fc_dma_map_single(struct device *dev, void *ptr, size_t size,
714                 enum dma_data_direction dir)
715 {
716         return dev ? dma_map_single(dev, ptr, size, dir) : (dma_addr_t)0L;
717 }
718
719 static inline int
720 fc_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
721 {
722         return dev ? dma_mapping_error(dev, dma_addr) : 0;
723 }
724
725 static inline void
726 fc_dma_unmap_single(struct device *dev, dma_addr_t addr, size_t size,
727         enum dma_data_direction dir)
728 {
729         if (dev)
730                 dma_unmap_single(dev, addr, size, dir);
731 }
732
733 static inline void
734 fc_dma_sync_single_for_cpu(struct device *dev, dma_addr_t addr, size_t size,
735                 enum dma_data_direction dir)
736 {
737         if (dev)
738                 dma_sync_single_for_cpu(dev, addr, size, dir);
739 }
740
741 static inline void
742 fc_dma_sync_single_for_device(struct device *dev, dma_addr_t addr, size_t size,
743                 enum dma_data_direction dir)
744 {
745         if (dev)
746                 dma_sync_single_for_device(dev, addr, size, dir);
747 }
748
749 /* pseudo dma_map_sg call */
750 static int
751 fc_map_sg(struct scatterlist *sg, int nents)
752 {
753         struct scatterlist *s;
754         int i;
755
756         WARN_ON(nents == 0 || sg[0].length == 0);
757
758         for_each_sg(sg, s, nents, i) {
759                 s->dma_address = 0L;
760 #ifdef CONFIG_NEED_SG_DMA_LENGTH
761                 s->dma_length = s->length;
762 #endif
763         }
764         return nents;
765 }
766
767 static inline int
768 fc_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
769                 enum dma_data_direction dir)
770 {
771         return dev ? dma_map_sg(dev, sg, nents, dir) : fc_map_sg(sg, nents);
772 }
773
774 static inline void
775 fc_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
776                 enum dma_data_direction dir)
777 {
778         if (dev)
779                 dma_unmap_sg(dev, sg, nents, dir);
780 }
781
782
783 /* *********************** FC-NVME LS Handling **************************** */
784
785 static void nvme_fc_ctrl_put(struct nvme_fc_ctrl *);
786 static int nvme_fc_ctrl_get(struct nvme_fc_ctrl *);
787
788
789 static void
790 __nvme_fc_finish_ls_req(struct nvmefc_ls_req_op *lsop)
791 {
792         struct nvme_fc_rport *rport = lsop->rport;
793         struct nvmefc_ls_req *lsreq = &lsop->ls_req;
794         unsigned long flags;
795
796         spin_lock_irqsave(&rport->lock, flags);
797
798         if (!lsop->req_queued) {
799                 spin_unlock_irqrestore(&rport->lock, flags);
800                 return;
801         }
802
803         list_del(&lsop->lsreq_list);
804
805         lsop->req_queued = false;
806
807         spin_unlock_irqrestore(&rport->lock, flags);
808
809         fc_dma_unmap_single(rport->dev, lsreq->rqstdma,
810                                   (lsreq->rqstlen + lsreq->rsplen),
811                                   DMA_BIDIRECTIONAL);
812
813         nvme_fc_rport_put(rport);
814 }
815
816 static int
817 __nvme_fc_send_ls_req(struct nvme_fc_rport *rport,
818                 struct nvmefc_ls_req_op *lsop,
819                 void (*done)(struct nvmefc_ls_req *req, int status))
820 {
821         struct nvmefc_ls_req *lsreq = &lsop->ls_req;
822         unsigned long flags;
823         int ret = 0;
824
825         if (rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
826                 return -ECONNREFUSED;
827
828         if (!nvme_fc_rport_get(rport))
829                 return -ESHUTDOWN;
830
831         lsreq->done = done;
832         lsop->rport = rport;
833         lsop->req_queued = false;
834         INIT_LIST_HEAD(&lsop->lsreq_list);
835         init_completion(&lsop->ls_done);
836
837         lsreq->rqstdma = fc_dma_map_single(rport->dev, lsreq->rqstaddr,
838                                   lsreq->rqstlen + lsreq->rsplen,
839                                   DMA_BIDIRECTIONAL);
840         if (fc_dma_mapping_error(rport->dev, lsreq->rqstdma)) {
841                 ret = -EFAULT;
842                 goto out_putrport;
843         }
844         lsreq->rspdma = lsreq->rqstdma + lsreq->rqstlen;
845
846         spin_lock_irqsave(&rport->lock, flags);
847
848         list_add_tail(&lsop->lsreq_list, &rport->ls_req_list);
849
850         lsop->req_queued = true;
851
852         spin_unlock_irqrestore(&rport->lock, flags);
853
854         ret = rport->lport->ops->ls_req(&rport->lport->localport,
855                                         &rport->remoteport, lsreq);
856         if (ret)
857                 goto out_unlink;
858
859         return 0;
860
861 out_unlink:
862         lsop->ls_error = ret;
863         spin_lock_irqsave(&rport->lock, flags);
864         lsop->req_queued = false;
865         list_del(&lsop->lsreq_list);
866         spin_unlock_irqrestore(&rport->lock, flags);
867         fc_dma_unmap_single(rport->dev, lsreq->rqstdma,
868                                   (lsreq->rqstlen + lsreq->rsplen),
869                                   DMA_BIDIRECTIONAL);
870 out_putrport:
871         nvme_fc_rport_put(rport);
872
873         return ret;
874 }
875
876 static void
877 nvme_fc_send_ls_req_done(struct nvmefc_ls_req *lsreq, int status)
878 {
879         struct nvmefc_ls_req_op *lsop = ls_req_to_lsop(lsreq);
880
881         lsop->ls_error = status;
882         complete(&lsop->ls_done);
883 }
884
885 static int
886 nvme_fc_send_ls_req(struct nvme_fc_rport *rport, struct nvmefc_ls_req_op *lsop)
887 {
888         struct nvmefc_ls_req *lsreq = &lsop->ls_req;
889         struct fcnvme_ls_rjt *rjt = lsreq->rspaddr;
890         int ret;
891
892         ret = __nvme_fc_send_ls_req(rport, lsop, nvme_fc_send_ls_req_done);
893
894         if (!ret) {
895                 /*
896                  * No timeout/not interruptible as we need the struct
897                  * to exist until the lldd calls us back. Thus mandate
898                  * wait until driver calls back. lldd responsible for
899                  * the timeout action
900                  */
901                 wait_for_completion(&lsop->ls_done);
902
903                 __nvme_fc_finish_ls_req(lsop);
904
905                 ret = lsop->ls_error;
906         }
907
908         if (ret)
909                 return ret;
910
911         /* ACC or RJT payload ? */
912         if (rjt->w0.ls_cmd == FCNVME_LS_RJT)
913                 return -ENXIO;
914
915         return 0;
916 }
917
918 static int
919 nvme_fc_send_ls_req_async(struct nvme_fc_rport *rport,
920                 struct nvmefc_ls_req_op *lsop,
921                 void (*done)(struct nvmefc_ls_req *req, int status))
922 {
923         /* don't wait for completion */
924
925         return __nvme_fc_send_ls_req(rport, lsop, done);
926 }
927
928 /* Validation Error indexes into the string table below */
929 enum {
930         VERR_NO_ERROR           = 0,
931         VERR_LSACC              = 1,
932         VERR_LSDESC_RQST        = 2,
933         VERR_LSDESC_RQST_LEN    = 3,
934         VERR_ASSOC_ID           = 4,
935         VERR_ASSOC_ID_LEN       = 5,
936         VERR_CONN_ID            = 6,
937         VERR_CONN_ID_LEN        = 7,
938         VERR_CR_ASSOC           = 8,
939         VERR_CR_ASSOC_ACC_LEN   = 9,
940         VERR_CR_CONN            = 10,
941         VERR_CR_CONN_ACC_LEN    = 11,
942         VERR_DISCONN            = 12,
943         VERR_DISCONN_ACC_LEN    = 13,
944 };
945
946 static char *validation_errors[] = {
947         "OK",
948         "Not LS_ACC",
949         "Not LSDESC_RQST",
950         "Bad LSDESC_RQST Length",
951         "Not Association ID",
952         "Bad Association ID Length",
953         "Not Connection ID",
954         "Bad Connection ID Length",
955         "Not CR_ASSOC Rqst",
956         "Bad CR_ASSOC ACC Length",
957         "Not CR_CONN Rqst",
958         "Bad CR_CONN ACC Length",
959         "Not Disconnect Rqst",
960         "Bad Disconnect ACC Length",
961 };
962
963 static int
964 nvme_fc_connect_admin_queue(struct nvme_fc_ctrl *ctrl,
965         struct nvme_fc_queue *queue, u16 qsize, u16 ersp_ratio)
966 {
967         struct nvmefc_ls_req_op *lsop;
968         struct nvmefc_ls_req *lsreq;
969         struct fcnvme_ls_cr_assoc_rqst *assoc_rqst;
970         struct fcnvme_ls_cr_assoc_acc *assoc_acc;
971         int ret, fcret = 0;
972
973         lsop = kzalloc((sizeof(*lsop) +
974                          ctrl->lport->ops->lsrqst_priv_sz +
975                          sizeof(*assoc_rqst) + sizeof(*assoc_acc)), GFP_KERNEL);
976         if (!lsop) {
977                 ret = -ENOMEM;
978                 goto out_no_memory;
979         }
980         lsreq = &lsop->ls_req;
981
982         lsreq->private = (void *)&lsop[1];
983         assoc_rqst = (struct fcnvme_ls_cr_assoc_rqst *)
984                         (lsreq->private + ctrl->lport->ops->lsrqst_priv_sz);
985         assoc_acc = (struct fcnvme_ls_cr_assoc_acc *)&assoc_rqst[1];
986
987         assoc_rqst->w0.ls_cmd = FCNVME_LS_CREATE_ASSOCIATION;
988         assoc_rqst->desc_list_len =
989                         cpu_to_be32(sizeof(struct fcnvme_lsdesc_cr_assoc_cmd));
990
991         assoc_rqst->assoc_cmd.desc_tag =
992                         cpu_to_be32(FCNVME_LSDESC_CREATE_ASSOC_CMD);
993         assoc_rqst->assoc_cmd.desc_len =
994                         fcnvme_lsdesc_len(
995                                 sizeof(struct fcnvme_lsdesc_cr_assoc_cmd));
996
997         assoc_rqst->assoc_cmd.ersp_ratio = cpu_to_be16(ersp_ratio);
998         assoc_rqst->assoc_cmd.sqsize = cpu_to_be16(qsize);
999         /* Linux supports only Dynamic controllers */
1000         assoc_rqst->assoc_cmd.cntlid = cpu_to_be16(0xffff);
1001         uuid_copy(&assoc_rqst->assoc_cmd.hostid, &ctrl->ctrl.opts->host->id);
1002         strncpy(assoc_rqst->assoc_cmd.hostnqn, ctrl->ctrl.opts->host->nqn,
1003                 min(FCNVME_ASSOC_HOSTNQN_LEN, NVMF_NQN_SIZE));
1004         strncpy(assoc_rqst->assoc_cmd.subnqn, ctrl->ctrl.opts->subsysnqn,
1005                 min(FCNVME_ASSOC_SUBNQN_LEN, NVMF_NQN_SIZE));
1006
1007         lsop->queue = queue;
1008         lsreq->rqstaddr = assoc_rqst;
1009         lsreq->rqstlen = sizeof(*assoc_rqst);
1010         lsreq->rspaddr = assoc_acc;
1011         lsreq->rsplen = sizeof(*assoc_acc);
1012         lsreq->timeout = NVME_FC_CONNECT_TIMEOUT_SEC;
1013
1014         ret = nvme_fc_send_ls_req(ctrl->rport, lsop);
1015         if (ret)
1016                 goto out_free_buffer;
1017
1018         /* process connect LS completion */
1019
1020         /* validate the ACC response */
1021         if (assoc_acc->hdr.w0.ls_cmd != FCNVME_LS_ACC)
1022                 fcret = VERR_LSACC;
1023         else if (assoc_acc->hdr.desc_list_len !=
1024                         fcnvme_lsdesc_len(
1025                                 sizeof(struct fcnvme_ls_cr_assoc_acc)))
1026                 fcret = VERR_CR_ASSOC_ACC_LEN;
1027         else if (assoc_acc->hdr.rqst.desc_tag !=
1028                         cpu_to_be32(FCNVME_LSDESC_RQST))
1029                 fcret = VERR_LSDESC_RQST;
1030         else if (assoc_acc->hdr.rqst.desc_len !=
1031                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_rqst)))
1032                 fcret = VERR_LSDESC_RQST_LEN;
1033         else if (assoc_acc->hdr.rqst.w0.ls_cmd != FCNVME_LS_CREATE_ASSOCIATION)
1034                 fcret = VERR_CR_ASSOC;
1035         else if (assoc_acc->associd.desc_tag !=
1036                         cpu_to_be32(FCNVME_LSDESC_ASSOC_ID))
1037                 fcret = VERR_ASSOC_ID;
1038         else if (assoc_acc->associd.desc_len !=
1039                         fcnvme_lsdesc_len(
1040                                 sizeof(struct fcnvme_lsdesc_assoc_id)))
1041                 fcret = VERR_ASSOC_ID_LEN;
1042         else if (assoc_acc->connectid.desc_tag !=
1043                         cpu_to_be32(FCNVME_LSDESC_CONN_ID))
1044                 fcret = VERR_CONN_ID;
1045         else if (assoc_acc->connectid.desc_len !=
1046                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_conn_id)))
1047                 fcret = VERR_CONN_ID_LEN;
1048
1049         if (fcret) {
1050                 ret = -EBADF;
1051                 dev_err(ctrl->dev,
1052                         "q %d connect failed: %s\n",
1053                         queue->qnum, validation_errors[fcret]);
1054         } else {
1055                 ctrl->association_id =
1056                         be64_to_cpu(assoc_acc->associd.association_id);
1057                 queue->connection_id =
1058                         be64_to_cpu(assoc_acc->connectid.connection_id);
1059                 set_bit(NVME_FC_Q_CONNECTED, &queue->flags);
1060         }
1061
1062 out_free_buffer:
1063         kfree(lsop);
1064 out_no_memory:
1065         if (ret)
1066                 dev_err(ctrl->dev,
1067                         "queue %d connect admin queue failed (%d).\n",
1068                         queue->qnum, ret);
1069         return ret;
1070 }
1071
1072 static int
1073 nvme_fc_connect_queue(struct nvme_fc_ctrl *ctrl, struct nvme_fc_queue *queue,
1074                         u16 qsize, u16 ersp_ratio)
1075 {
1076         struct nvmefc_ls_req_op *lsop;
1077         struct nvmefc_ls_req *lsreq;
1078         struct fcnvme_ls_cr_conn_rqst *conn_rqst;
1079         struct fcnvme_ls_cr_conn_acc *conn_acc;
1080         int ret, fcret = 0;
1081
1082         lsop = kzalloc((sizeof(*lsop) +
1083                          ctrl->lport->ops->lsrqst_priv_sz +
1084                          sizeof(*conn_rqst) + sizeof(*conn_acc)), GFP_KERNEL);
1085         if (!lsop) {
1086                 ret = -ENOMEM;
1087                 goto out_no_memory;
1088         }
1089         lsreq = &lsop->ls_req;
1090
1091         lsreq->private = (void *)&lsop[1];
1092         conn_rqst = (struct fcnvme_ls_cr_conn_rqst *)
1093                         (lsreq->private + ctrl->lport->ops->lsrqst_priv_sz);
1094         conn_acc = (struct fcnvme_ls_cr_conn_acc *)&conn_rqst[1];
1095
1096         conn_rqst->w0.ls_cmd = FCNVME_LS_CREATE_CONNECTION;
1097         conn_rqst->desc_list_len = cpu_to_be32(
1098                                 sizeof(struct fcnvme_lsdesc_assoc_id) +
1099                                 sizeof(struct fcnvme_lsdesc_cr_conn_cmd));
1100
1101         conn_rqst->associd.desc_tag = cpu_to_be32(FCNVME_LSDESC_ASSOC_ID);
1102         conn_rqst->associd.desc_len =
1103                         fcnvme_lsdesc_len(
1104                                 sizeof(struct fcnvme_lsdesc_assoc_id));
1105         conn_rqst->associd.association_id = cpu_to_be64(ctrl->association_id);
1106         conn_rqst->connect_cmd.desc_tag =
1107                         cpu_to_be32(FCNVME_LSDESC_CREATE_CONN_CMD);
1108         conn_rqst->connect_cmd.desc_len =
1109                         fcnvme_lsdesc_len(
1110                                 sizeof(struct fcnvme_lsdesc_cr_conn_cmd));
1111         conn_rqst->connect_cmd.ersp_ratio = cpu_to_be16(ersp_ratio);
1112         conn_rqst->connect_cmd.qid  = cpu_to_be16(queue->qnum);
1113         conn_rqst->connect_cmd.sqsize = cpu_to_be16(qsize);
1114
1115         lsop->queue = queue;
1116         lsreq->rqstaddr = conn_rqst;
1117         lsreq->rqstlen = sizeof(*conn_rqst);
1118         lsreq->rspaddr = conn_acc;
1119         lsreq->rsplen = sizeof(*conn_acc);
1120         lsreq->timeout = NVME_FC_CONNECT_TIMEOUT_SEC;
1121
1122         ret = nvme_fc_send_ls_req(ctrl->rport, lsop);
1123         if (ret)
1124                 goto out_free_buffer;
1125
1126         /* process connect LS completion */
1127
1128         /* validate the ACC response */
1129         if (conn_acc->hdr.w0.ls_cmd != FCNVME_LS_ACC)
1130                 fcret = VERR_LSACC;
1131         else if (conn_acc->hdr.desc_list_len !=
1132                         fcnvme_lsdesc_len(sizeof(struct fcnvme_ls_cr_conn_acc)))
1133                 fcret = VERR_CR_CONN_ACC_LEN;
1134         else if (conn_acc->hdr.rqst.desc_tag != cpu_to_be32(FCNVME_LSDESC_RQST))
1135                 fcret = VERR_LSDESC_RQST;
1136         else if (conn_acc->hdr.rqst.desc_len !=
1137                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_rqst)))
1138                 fcret = VERR_LSDESC_RQST_LEN;
1139         else if (conn_acc->hdr.rqst.w0.ls_cmd != FCNVME_LS_CREATE_CONNECTION)
1140                 fcret = VERR_CR_CONN;
1141         else if (conn_acc->connectid.desc_tag !=
1142                         cpu_to_be32(FCNVME_LSDESC_CONN_ID))
1143                 fcret = VERR_CONN_ID;
1144         else if (conn_acc->connectid.desc_len !=
1145                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_conn_id)))
1146                 fcret = VERR_CONN_ID_LEN;
1147
1148         if (fcret) {
1149                 ret = -EBADF;
1150                 dev_err(ctrl->dev,
1151                         "q %d connect failed: %s\n",
1152                         queue->qnum, validation_errors[fcret]);
1153         } else {
1154                 queue->connection_id =
1155                         be64_to_cpu(conn_acc->connectid.connection_id);
1156                 set_bit(NVME_FC_Q_CONNECTED, &queue->flags);
1157         }
1158
1159 out_free_buffer:
1160         kfree(lsop);
1161 out_no_memory:
1162         if (ret)
1163                 dev_err(ctrl->dev,
1164                         "queue %d connect command failed (%d).\n",
1165                         queue->qnum, ret);
1166         return ret;
1167 }
1168
1169 static void
1170 nvme_fc_disconnect_assoc_done(struct nvmefc_ls_req *lsreq, int status)
1171 {
1172         struct nvmefc_ls_req_op *lsop = ls_req_to_lsop(lsreq);
1173
1174         __nvme_fc_finish_ls_req(lsop);
1175
1176         /* fc-nvme iniator doesn't care about success or failure of cmd */
1177
1178         kfree(lsop);
1179 }
1180
1181 /*
1182  * This routine sends a FC-NVME LS to disconnect (aka terminate)
1183  * the FC-NVME Association.  Terminating the association also
1184  * terminates the FC-NVME connections (per queue, both admin and io
1185  * queues) that are part of the association. E.g. things are torn
1186  * down, and the related FC-NVME Association ID and Connection IDs
1187  * become invalid.
1188  *
1189  * The behavior of the fc-nvme initiator is such that it's
1190  * understanding of the association and connections will implicitly
1191  * be torn down. The action is implicit as it may be due to a loss of
1192  * connectivity with the fc-nvme target, so you may never get a
1193  * response even if you tried.  As such, the action of this routine
1194  * is to asynchronously send the LS, ignore any results of the LS, and
1195  * continue on with terminating the association. If the fc-nvme target
1196  * is present and receives the LS, it too can tear down.
1197  */
1198 static void
1199 nvme_fc_xmt_disconnect_assoc(struct nvme_fc_ctrl *ctrl)
1200 {
1201         struct fcnvme_ls_disconnect_rqst *discon_rqst;
1202         struct fcnvme_ls_disconnect_acc *discon_acc;
1203         struct nvmefc_ls_req_op *lsop;
1204         struct nvmefc_ls_req *lsreq;
1205         int ret;
1206
1207         lsop = kzalloc((sizeof(*lsop) +
1208                          ctrl->lport->ops->lsrqst_priv_sz +
1209                          sizeof(*discon_rqst) + sizeof(*discon_acc)),
1210                         GFP_KERNEL);
1211         if (!lsop)
1212                 /* couldn't sent it... too bad */
1213                 return;
1214
1215         lsreq = &lsop->ls_req;
1216
1217         lsreq->private = (void *)&lsop[1];
1218         discon_rqst = (struct fcnvme_ls_disconnect_rqst *)
1219                         (lsreq->private + ctrl->lport->ops->lsrqst_priv_sz);
1220         discon_acc = (struct fcnvme_ls_disconnect_acc *)&discon_rqst[1];
1221
1222         discon_rqst->w0.ls_cmd = FCNVME_LS_DISCONNECT;
1223         discon_rqst->desc_list_len = cpu_to_be32(
1224                                 sizeof(struct fcnvme_lsdesc_assoc_id) +
1225                                 sizeof(struct fcnvme_lsdesc_disconn_cmd));
1226
1227         discon_rqst->associd.desc_tag = cpu_to_be32(FCNVME_LSDESC_ASSOC_ID);
1228         discon_rqst->associd.desc_len =
1229                         fcnvme_lsdesc_len(
1230                                 sizeof(struct fcnvme_lsdesc_assoc_id));
1231
1232         discon_rqst->associd.association_id = cpu_to_be64(ctrl->association_id);
1233
1234         discon_rqst->discon_cmd.desc_tag = cpu_to_be32(
1235                                                 FCNVME_LSDESC_DISCONN_CMD);
1236         discon_rqst->discon_cmd.desc_len =
1237                         fcnvme_lsdesc_len(
1238                                 sizeof(struct fcnvme_lsdesc_disconn_cmd));
1239         discon_rqst->discon_cmd.scope = FCNVME_DISCONN_ASSOCIATION;
1240         discon_rqst->discon_cmd.id = cpu_to_be64(ctrl->association_id);
1241
1242         lsreq->rqstaddr = discon_rqst;
1243         lsreq->rqstlen = sizeof(*discon_rqst);
1244         lsreq->rspaddr = discon_acc;
1245         lsreq->rsplen = sizeof(*discon_acc);
1246         lsreq->timeout = NVME_FC_CONNECT_TIMEOUT_SEC;
1247
1248         ret = nvme_fc_send_ls_req_async(ctrl->rport, lsop,
1249                                 nvme_fc_disconnect_assoc_done);
1250         if (ret)
1251                 kfree(lsop);
1252
1253         /* only meaningful part to terminating the association */
1254         ctrl->association_id = 0;
1255 }
1256
1257
1258 /* *********************** NVME Ctrl Routines **************************** */
1259
1260 static void __nvme_fc_final_op_cleanup(struct request *rq);
1261 static void nvme_fc_error_recovery(struct nvme_fc_ctrl *ctrl, char *errmsg);
1262
1263 static int
1264 nvme_fc_reinit_request(void *data, struct request *rq)
1265 {
1266         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
1267         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
1268
1269         memset(cmdiu, 0, sizeof(*cmdiu));
1270         cmdiu->scsi_id = NVME_CMD_SCSI_ID;
1271         cmdiu->fc_id = NVME_CMD_FC_ID;
1272         cmdiu->iu_len = cpu_to_be16(sizeof(*cmdiu) / sizeof(u32));
1273         memset(&op->rsp_iu, 0, sizeof(op->rsp_iu));
1274
1275         return 0;
1276 }
1277
1278 static void
1279 __nvme_fc_exit_request(struct nvme_fc_ctrl *ctrl,
1280                 struct nvme_fc_fcp_op *op)
1281 {
1282         fc_dma_unmap_single(ctrl->lport->dev, op->fcp_req.rspdma,
1283                                 sizeof(op->rsp_iu), DMA_FROM_DEVICE);
1284         fc_dma_unmap_single(ctrl->lport->dev, op->fcp_req.cmddma,
1285                                 sizeof(op->cmd_iu), DMA_TO_DEVICE);
1286
1287         atomic_set(&op->state, FCPOP_STATE_UNINIT);
1288 }
1289
1290 static void
1291 nvme_fc_exit_request(struct blk_mq_tag_set *set, struct request *rq,
1292                 unsigned int hctx_idx)
1293 {
1294         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
1295
1296         return __nvme_fc_exit_request(set->driver_data, op);
1297 }
1298
1299 static int
1300 __nvme_fc_abort_op(struct nvme_fc_ctrl *ctrl, struct nvme_fc_fcp_op *op)
1301 {
1302         int state;
1303
1304         state = atomic_xchg(&op->state, FCPOP_STATE_ABORTED);
1305         if (state != FCPOP_STATE_ACTIVE) {
1306                 atomic_set(&op->state, state);
1307                 return -ECANCELED;
1308         }
1309
1310         ctrl->lport->ops->fcp_abort(&ctrl->lport->localport,
1311                                         &ctrl->rport->remoteport,
1312                                         op->queue->lldd_handle,
1313                                         &op->fcp_req);
1314
1315         return 0;
1316 }
1317
1318 static void
1319 nvme_fc_abort_aen_ops(struct nvme_fc_ctrl *ctrl)
1320 {
1321         struct nvme_fc_fcp_op *aen_op = ctrl->aen_ops;
1322         unsigned long flags;
1323         int i, ret;
1324
1325         for (i = 0; i < NVME_FC_NR_AEN_COMMANDS; i++, aen_op++) {
1326                 if (atomic_read(&aen_op->state) != FCPOP_STATE_ACTIVE)
1327                         continue;
1328
1329                 spin_lock_irqsave(&ctrl->lock, flags);
1330                 if (ctrl->flags & FCCTRL_TERMIO) {
1331                         ctrl->iocnt++;
1332                         aen_op->flags |= FCOP_FLAGS_TERMIO;
1333                 }
1334                 spin_unlock_irqrestore(&ctrl->lock, flags);
1335
1336                 ret = __nvme_fc_abort_op(ctrl, aen_op);
1337                 if (ret) {
1338                         /*
1339                          * if __nvme_fc_abort_op failed the io wasn't
1340                          * active. Thus this call path is running in
1341                          * parallel to the io complete. Treat as non-error.
1342                          */
1343
1344                         /* back out the flags/counters */
1345                         spin_lock_irqsave(&ctrl->lock, flags);
1346                         if (ctrl->flags & FCCTRL_TERMIO)
1347                                 ctrl->iocnt--;
1348                         aen_op->flags &= ~FCOP_FLAGS_TERMIO;
1349                         spin_unlock_irqrestore(&ctrl->lock, flags);
1350                         return;
1351                 }
1352         }
1353 }
1354
1355 static inline int
1356 __nvme_fc_fcpop_chk_teardowns(struct nvme_fc_ctrl *ctrl,
1357                 struct nvme_fc_fcp_op *op)
1358 {
1359         unsigned long flags;
1360         bool complete_rq = false;
1361
1362         spin_lock_irqsave(&ctrl->lock, flags);
1363         if (unlikely(op->flags & FCOP_FLAGS_TERMIO)) {
1364                 if (ctrl->flags & FCCTRL_TERMIO) {
1365                         if (!--ctrl->iocnt)
1366                                 wake_up(&ctrl->ioabort_wait);
1367                 }
1368         }
1369         if (op->flags & FCOP_FLAGS_RELEASED)
1370                 complete_rq = true;
1371         else
1372                 op->flags |= FCOP_FLAGS_COMPLETE;
1373         spin_unlock_irqrestore(&ctrl->lock, flags);
1374
1375         return complete_rq;
1376 }
1377
1378 static void
1379 nvme_fc_fcpio_done(struct nvmefc_fcp_req *req)
1380 {
1381         struct nvme_fc_fcp_op *op = fcp_req_to_fcp_op(req);
1382         struct request *rq = op->rq;
1383         struct nvmefc_fcp_req *freq = &op->fcp_req;
1384         struct nvme_fc_ctrl *ctrl = op->ctrl;
1385         struct nvme_fc_queue *queue = op->queue;
1386         struct nvme_completion *cqe = &op->rsp_iu.cqe;
1387         struct nvme_command *sqe = &op->cmd_iu.sqe;
1388         __le16 status = cpu_to_le16(NVME_SC_SUCCESS << 1);
1389         union nvme_result result;
1390         bool complete_rq, terminate_assoc = true;
1391
1392         /*
1393          * WARNING:
1394          * The current linux implementation of a nvme controller
1395          * allocates a single tag set for all io queues and sizes
1396          * the io queues to fully hold all possible tags. Thus, the
1397          * implementation does not reference or care about the sqhd
1398          * value as it never needs to use the sqhd/sqtail pointers
1399          * for submission pacing.
1400          *
1401          * This affects the FC-NVME implementation in two ways:
1402          * 1) As the value doesn't matter, we don't need to waste
1403          *    cycles extracting it from ERSPs and stamping it in the
1404          *    cases where the transport fabricates CQEs on successful
1405          *    completions.
1406          * 2) The FC-NVME implementation requires that delivery of
1407          *    ERSP completions are to go back to the nvme layer in order
1408          *    relative to the rsn, such that the sqhd value will always
1409          *    be "in order" for the nvme layer. As the nvme layer in
1410          *    linux doesn't care about sqhd, there's no need to return
1411          *    them in order.
1412          *
1413          * Additionally:
1414          * As the core nvme layer in linux currently does not look at
1415          * every field in the cqe - in cases where the FC transport must
1416          * fabricate a CQE, the following fields will not be set as they
1417          * are not referenced:
1418          *      cqe.sqid,  cqe.sqhd,  cqe.command_id
1419          *
1420          * Failure or error of an individual i/o, in a transport
1421          * detected fashion unrelated to the nvme completion status,
1422          * potentially cause the initiator and target sides to get out
1423          * of sync on SQ head/tail (aka outstanding io count allowed).
1424          * Per FC-NVME spec, failure of an individual command requires
1425          * the connection to be terminated, which in turn requires the
1426          * association to be terminated.
1427          */
1428
1429         fc_dma_sync_single_for_cpu(ctrl->lport->dev, op->fcp_req.rspdma,
1430                                 sizeof(op->rsp_iu), DMA_FROM_DEVICE);
1431
1432         if (atomic_read(&op->state) == FCPOP_STATE_ABORTED)
1433                 status = cpu_to_le16((NVME_SC_ABORT_REQ | NVME_SC_DNR) << 1);
1434         else if (freq->status)
1435                 status = cpu_to_le16(NVME_SC_INTERNAL << 1);
1436
1437         /*
1438          * For the linux implementation, if we have an unsuccesful
1439          * status, they blk-mq layer can typically be called with the
1440          * non-zero status and the content of the cqe isn't important.
1441          */
1442         if (status)
1443                 goto done;
1444
1445         /*
1446          * command completed successfully relative to the wire
1447          * protocol. However, validate anything received and
1448          * extract the status and result from the cqe (create it
1449          * where necessary).
1450          */
1451
1452         switch (freq->rcv_rsplen) {
1453
1454         case 0:
1455         case NVME_FC_SIZEOF_ZEROS_RSP:
1456                 /*
1457                  * No response payload or 12 bytes of payload (which
1458                  * should all be zeros) are considered successful and
1459                  * no payload in the CQE by the transport.
1460                  */
1461                 if (freq->transferred_length !=
1462                         be32_to_cpu(op->cmd_iu.data_len)) {
1463                         status = cpu_to_le16(NVME_SC_INTERNAL << 1);
1464                         goto done;
1465                 }
1466                 result.u64 = 0;
1467                 break;
1468
1469         case sizeof(struct nvme_fc_ersp_iu):
1470                 /*
1471                  * The ERSP IU contains a full completion with CQE.
1472                  * Validate ERSP IU and look at cqe.
1473                  */
1474                 if (unlikely(be16_to_cpu(op->rsp_iu.iu_len) !=
1475                                         (freq->rcv_rsplen / 4) ||
1476                              be32_to_cpu(op->rsp_iu.xfrd_len) !=
1477                                         freq->transferred_length ||
1478                              op->rsp_iu.status_code ||
1479                              sqe->common.command_id != cqe->command_id)) {
1480                         status = cpu_to_le16(NVME_SC_INTERNAL << 1);
1481                         goto done;
1482                 }
1483                 result = cqe->result;
1484                 status = cqe->status;
1485                 break;
1486
1487         default:
1488                 status = cpu_to_le16(NVME_SC_INTERNAL << 1);
1489                 goto done;
1490         }
1491
1492         terminate_assoc = false;
1493
1494 done:
1495         if (op->flags & FCOP_FLAGS_AEN) {
1496                 nvme_complete_async_event(&queue->ctrl->ctrl, status, &result);
1497                 complete_rq = __nvme_fc_fcpop_chk_teardowns(ctrl, op);
1498                 atomic_set(&op->state, FCPOP_STATE_IDLE);
1499                 op->flags = FCOP_FLAGS_AEN;     /* clear other flags */
1500                 nvme_fc_ctrl_put(ctrl);
1501                 goto check_error;
1502         }
1503
1504         complete_rq = __nvme_fc_fcpop_chk_teardowns(ctrl, op);
1505         if (!complete_rq) {
1506                 if (unlikely(op->flags & FCOP_FLAGS_TERMIO)) {
1507                         status = cpu_to_le16(NVME_SC_ABORT_REQ << 1);
1508                         if (blk_queue_dying(rq->q))
1509                                 status |= cpu_to_le16(NVME_SC_DNR << 1);
1510                 }
1511                 nvme_end_request(rq, status, result);
1512         } else
1513                 __nvme_fc_final_op_cleanup(rq);
1514
1515 check_error:
1516         if (terminate_assoc)
1517                 nvme_fc_error_recovery(ctrl, "transport detected io error");
1518 }
1519
1520 static int
1521 __nvme_fc_init_request(struct nvme_fc_ctrl *ctrl,
1522                 struct nvme_fc_queue *queue, struct nvme_fc_fcp_op *op,
1523                 struct request *rq, u32 rqno)
1524 {
1525         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
1526         int ret = 0;
1527
1528         memset(op, 0, sizeof(*op));
1529         op->fcp_req.cmdaddr = &op->cmd_iu;
1530         op->fcp_req.cmdlen = sizeof(op->cmd_iu);
1531         op->fcp_req.rspaddr = &op->rsp_iu;
1532         op->fcp_req.rsplen = sizeof(op->rsp_iu);
1533         op->fcp_req.done = nvme_fc_fcpio_done;
1534         op->fcp_req.first_sgl = (struct scatterlist *)&op[1];
1535         op->fcp_req.private = &op->fcp_req.first_sgl[SG_CHUNK_SIZE];
1536         op->ctrl = ctrl;
1537         op->queue = queue;
1538         op->rq = rq;
1539         op->rqno = rqno;
1540
1541         cmdiu->scsi_id = NVME_CMD_SCSI_ID;
1542         cmdiu->fc_id = NVME_CMD_FC_ID;
1543         cmdiu->iu_len = cpu_to_be16(sizeof(*cmdiu) / sizeof(u32));
1544
1545         op->fcp_req.cmddma = fc_dma_map_single(ctrl->lport->dev,
1546                                 &op->cmd_iu, sizeof(op->cmd_iu), DMA_TO_DEVICE);
1547         if (fc_dma_mapping_error(ctrl->lport->dev, op->fcp_req.cmddma)) {
1548                 dev_err(ctrl->dev,
1549                         "FCP Op failed - cmdiu dma mapping failed.\n");
1550                 ret = EFAULT;
1551                 goto out_on_error;
1552         }
1553
1554         op->fcp_req.rspdma = fc_dma_map_single(ctrl->lport->dev,
1555                                 &op->rsp_iu, sizeof(op->rsp_iu),
1556                                 DMA_FROM_DEVICE);
1557         if (fc_dma_mapping_error(ctrl->lport->dev, op->fcp_req.rspdma)) {
1558                 dev_err(ctrl->dev,
1559                         "FCP Op failed - rspiu dma mapping failed.\n");
1560                 ret = EFAULT;
1561         }
1562
1563         atomic_set(&op->state, FCPOP_STATE_IDLE);
1564 out_on_error:
1565         return ret;
1566 }
1567
1568 static int
1569 nvme_fc_init_request(struct blk_mq_tag_set *set, struct request *rq,
1570                 unsigned int hctx_idx, unsigned int numa_node)
1571 {
1572         struct nvme_fc_ctrl *ctrl = set->driver_data;
1573         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
1574         int queue_idx = (set == &ctrl->tag_set) ? hctx_idx + 1 : 0;
1575         struct nvme_fc_queue *queue = &ctrl->queues[queue_idx];
1576
1577         return __nvme_fc_init_request(ctrl, queue, op, rq, queue->rqcnt++);
1578 }
1579
1580 static int
1581 nvme_fc_init_aen_ops(struct nvme_fc_ctrl *ctrl)
1582 {
1583         struct nvme_fc_fcp_op *aen_op;
1584         struct nvme_fc_cmd_iu *cmdiu;
1585         struct nvme_command *sqe;
1586         void *private;
1587         int i, ret;
1588
1589         aen_op = ctrl->aen_ops;
1590         for (i = 0; i < NVME_FC_NR_AEN_COMMANDS; i++, aen_op++) {
1591                 private = kzalloc(ctrl->lport->ops->fcprqst_priv_sz,
1592                                                 GFP_KERNEL);
1593                 if (!private)
1594                         return -ENOMEM;
1595
1596                 cmdiu = &aen_op->cmd_iu;
1597                 sqe = &cmdiu->sqe;
1598                 ret = __nvme_fc_init_request(ctrl, &ctrl->queues[0],
1599                                 aen_op, (struct request *)NULL,
1600                                 (AEN_CMDID_BASE + i));
1601                 if (ret) {
1602                         kfree(private);
1603                         return ret;
1604                 }
1605
1606                 aen_op->flags = FCOP_FLAGS_AEN;
1607                 aen_op->fcp_req.first_sgl = NULL; /* no sg list */
1608                 aen_op->fcp_req.private = private;
1609
1610                 memset(sqe, 0, sizeof(*sqe));
1611                 sqe->common.opcode = nvme_admin_async_event;
1612                 /* Note: core layer may overwrite the sqe.command_id value */
1613                 sqe->common.command_id = AEN_CMDID_BASE + i;
1614         }
1615         return 0;
1616 }
1617
1618 static void
1619 nvme_fc_term_aen_ops(struct nvme_fc_ctrl *ctrl)
1620 {
1621         struct nvme_fc_fcp_op *aen_op;
1622         int i;
1623
1624         aen_op = ctrl->aen_ops;
1625         for (i = 0; i < NVME_FC_NR_AEN_COMMANDS; i++, aen_op++) {
1626                 if (!aen_op->fcp_req.private)
1627                         continue;
1628
1629                 __nvme_fc_exit_request(ctrl, aen_op);
1630
1631                 kfree(aen_op->fcp_req.private);
1632                 aen_op->fcp_req.private = NULL;
1633         }
1634 }
1635
1636 static inline void
1637 __nvme_fc_init_hctx(struct blk_mq_hw_ctx *hctx, struct nvme_fc_ctrl *ctrl,
1638                 unsigned int qidx)
1639 {
1640         struct nvme_fc_queue *queue = &ctrl->queues[qidx];
1641
1642         hctx->driver_data = queue;
1643         queue->hctx = hctx;
1644 }
1645
1646 static int
1647 nvme_fc_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
1648                 unsigned int hctx_idx)
1649 {
1650         struct nvme_fc_ctrl *ctrl = data;
1651
1652         __nvme_fc_init_hctx(hctx, ctrl, hctx_idx + 1);
1653
1654         return 0;
1655 }
1656
1657 static int
1658 nvme_fc_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
1659                 unsigned int hctx_idx)
1660 {
1661         struct nvme_fc_ctrl *ctrl = data;
1662
1663         __nvme_fc_init_hctx(hctx, ctrl, hctx_idx);
1664
1665         return 0;
1666 }
1667
1668 static void
1669 nvme_fc_init_queue(struct nvme_fc_ctrl *ctrl, int idx, size_t queue_size)
1670 {
1671         struct nvme_fc_queue *queue;
1672
1673         queue = &ctrl->queues[idx];
1674         memset(queue, 0, sizeof(*queue));
1675         queue->ctrl = ctrl;
1676         queue->qnum = idx;
1677         atomic_set(&queue->csn, 1);
1678         queue->dev = ctrl->dev;
1679
1680         if (idx > 0)
1681                 queue->cmnd_capsule_len = ctrl->ctrl.ioccsz * 16;
1682         else
1683                 queue->cmnd_capsule_len = sizeof(struct nvme_command);
1684
1685         queue->queue_size = queue_size;
1686
1687         /*
1688          * Considered whether we should allocate buffers for all SQEs
1689          * and CQEs and dma map them - mapping their respective entries
1690          * into the request structures (kernel vm addr and dma address)
1691          * thus the driver could use the buffers/mappings directly.
1692          * It only makes sense if the LLDD would use them for its
1693          * messaging api. It's very unlikely most adapter api's would use
1694          * a native NVME sqe/cqe. More reasonable if FC-NVME IU payload
1695          * structures were used instead.
1696          */
1697 }
1698
1699 /*
1700  * This routine terminates a queue at the transport level.
1701  * The transport has already ensured that all outstanding ios on
1702  * the queue have been terminated.
1703  * The transport will send a Disconnect LS request to terminate
1704  * the queue's connection. Termination of the admin queue will also
1705  * terminate the association at the target.
1706  */
1707 static void
1708 nvme_fc_free_queue(struct nvme_fc_queue *queue)
1709 {
1710         if (!test_and_clear_bit(NVME_FC_Q_CONNECTED, &queue->flags))
1711                 return;
1712
1713         /*
1714          * Current implementation never disconnects a single queue.
1715          * It always terminates a whole association. So there is never
1716          * a disconnect(queue) LS sent to the target.
1717          */
1718
1719         queue->connection_id = 0;
1720         clear_bit(NVME_FC_Q_CONNECTED, &queue->flags);
1721 }
1722
1723 static void
1724 __nvme_fc_delete_hw_queue(struct nvme_fc_ctrl *ctrl,
1725         struct nvme_fc_queue *queue, unsigned int qidx)
1726 {
1727         if (ctrl->lport->ops->delete_queue)
1728                 ctrl->lport->ops->delete_queue(&ctrl->lport->localport, qidx,
1729                                 queue->lldd_handle);
1730         queue->lldd_handle = NULL;
1731 }
1732
1733 static void
1734 nvme_fc_free_io_queues(struct nvme_fc_ctrl *ctrl)
1735 {
1736         int i;
1737
1738         for (i = 1; i < ctrl->ctrl.queue_count; i++)
1739                 nvme_fc_free_queue(&ctrl->queues[i]);
1740 }
1741
1742 static int
1743 __nvme_fc_create_hw_queue(struct nvme_fc_ctrl *ctrl,
1744         struct nvme_fc_queue *queue, unsigned int qidx, u16 qsize)
1745 {
1746         int ret = 0;
1747
1748         queue->lldd_handle = NULL;
1749         if (ctrl->lport->ops->create_queue)
1750                 ret = ctrl->lport->ops->create_queue(&ctrl->lport->localport,
1751                                 qidx, qsize, &queue->lldd_handle);
1752
1753         return ret;
1754 }
1755
1756 static void
1757 nvme_fc_delete_hw_io_queues(struct nvme_fc_ctrl *ctrl)
1758 {
1759         struct nvme_fc_queue *queue = &ctrl->queues[ctrl->ctrl.queue_count - 1];
1760         int i;
1761
1762         for (i = ctrl->ctrl.queue_count - 1; i >= 1; i--, queue--)
1763                 __nvme_fc_delete_hw_queue(ctrl, queue, i);
1764 }
1765
1766 static int
1767 nvme_fc_create_hw_io_queues(struct nvme_fc_ctrl *ctrl, u16 qsize)
1768 {
1769         struct nvme_fc_queue *queue = &ctrl->queues[1];
1770         int i, ret;
1771
1772         for (i = 1; i < ctrl->ctrl.queue_count; i++, queue++) {
1773                 ret = __nvme_fc_create_hw_queue(ctrl, queue, i, qsize);
1774                 if (ret)
1775                         goto delete_queues;
1776         }
1777
1778         return 0;
1779
1780 delete_queues:
1781         for (; i >= 0; i--)
1782                 __nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[i], i);
1783         return ret;
1784 }
1785
1786 static int
1787 nvme_fc_connect_io_queues(struct nvme_fc_ctrl *ctrl, u16 qsize)
1788 {
1789         int i, ret = 0;
1790
1791         for (i = 1; i < ctrl->ctrl.queue_count; i++) {
1792                 ret = nvme_fc_connect_queue(ctrl, &ctrl->queues[i], qsize,
1793                                         (qsize / 5));
1794                 if (ret)
1795                         break;
1796                 ret = nvmf_connect_io_queue(&ctrl->ctrl, i);
1797                 if (ret)
1798                         break;
1799         }
1800
1801         return ret;
1802 }
1803
1804 static void
1805 nvme_fc_init_io_queues(struct nvme_fc_ctrl *ctrl)
1806 {
1807         int i;
1808
1809         for (i = 1; i < ctrl->ctrl.queue_count; i++)
1810                 nvme_fc_init_queue(ctrl, i, ctrl->ctrl.sqsize);
1811 }
1812
1813 static void
1814 nvme_fc_ctrl_free(struct kref *ref)
1815 {
1816         struct nvme_fc_ctrl *ctrl =
1817                 container_of(ref, struct nvme_fc_ctrl, ref);
1818         unsigned long flags;
1819
1820         if (ctrl->ctrl.tagset) {
1821                 blk_cleanup_queue(ctrl->ctrl.connect_q);
1822                 blk_mq_free_tag_set(&ctrl->tag_set);
1823         }
1824
1825         /* remove from rport list */
1826         spin_lock_irqsave(&ctrl->rport->lock, flags);
1827         list_del(&ctrl->ctrl_list);
1828         spin_unlock_irqrestore(&ctrl->rport->lock, flags);
1829
1830         blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
1831         blk_cleanup_queue(ctrl->ctrl.admin_q);
1832         blk_mq_free_tag_set(&ctrl->admin_tag_set);
1833
1834         kfree(ctrl->queues);
1835
1836         put_device(ctrl->dev);
1837         nvme_fc_rport_put(ctrl->rport);
1838
1839         ida_simple_remove(&nvme_fc_ctrl_cnt, ctrl->cnum);
1840         if (ctrl->ctrl.opts)
1841                 nvmf_free_options(ctrl->ctrl.opts);
1842         kfree(ctrl);
1843 }
1844
1845 static void
1846 nvme_fc_ctrl_put(struct nvme_fc_ctrl *ctrl)
1847 {
1848         kref_put(&ctrl->ref, nvme_fc_ctrl_free);
1849 }
1850
1851 static int
1852 nvme_fc_ctrl_get(struct nvme_fc_ctrl *ctrl)
1853 {
1854         return kref_get_unless_zero(&ctrl->ref);
1855 }
1856
1857 /*
1858  * All accesses from nvme core layer done - can now free the
1859  * controller. Called after last nvme_put_ctrl() call
1860  */
1861 static void
1862 nvme_fc_nvme_ctrl_freed(struct nvme_ctrl *nctrl)
1863 {
1864         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
1865
1866         WARN_ON(nctrl != &ctrl->ctrl);
1867
1868         nvme_fc_ctrl_put(ctrl);
1869 }
1870
1871 static void
1872 nvme_fc_error_recovery(struct nvme_fc_ctrl *ctrl, char *errmsg)
1873 {
1874         /* only proceed if in LIVE state - e.g. on first error */
1875         if (ctrl->ctrl.state != NVME_CTRL_LIVE)
1876                 return;
1877
1878         dev_warn(ctrl->ctrl.device,
1879                 "NVME-FC{%d}: transport association error detected: %s\n",
1880                 ctrl->cnum, errmsg);
1881         dev_warn(ctrl->ctrl.device,
1882                 "NVME-FC{%d}: resetting controller\n", ctrl->cnum);
1883
1884         if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RECONNECTING)) {
1885                 dev_err(ctrl->ctrl.device,
1886                         "NVME-FC{%d}: error_recovery: Couldn't change state "
1887                         "to RECONNECTING\n", ctrl->cnum);
1888                 return;
1889         }
1890
1891         nvme_reset_ctrl(&ctrl->ctrl);
1892 }
1893
1894 static enum blk_eh_timer_return
1895 nvme_fc_timeout(struct request *rq, bool reserved)
1896 {
1897         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
1898         struct nvme_fc_ctrl *ctrl = op->ctrl;
1899         int ret;
1900
1901         if (reserved)
1902                 return BLK_EH_RESET_TIMER;
1903
1904         ret = __nvme_fc_abort_op(ctrl, op);
1905         if (ret)
1906                 /* io wasn't active to abort consider it done */
1907                 return BLK_EH_HANDLED;
1908
1909         /*
1910          * we can't individually ABTS an io without affecting the queue,
1911          * thus killing the queue, adn thus the association.
1912          * So resolve by performing a controller reset, which will stop
1913          * the host/io stack, terminate the association on the link,
1914          * and recreate an association on the link.
1915          */
1916         nvme_fc_error_recovery(ctrl, "io timeout error");
1917
1918         return BLK_EH_HANDLED;
1919 }
1920
1921 static int
1922 nvme_fc_map_data(struct nvme_fc_ctrl *ctrl, struct request *rq,
1923                 struct nvme_fc_fcp_op *op)
1924 {
1925         struct nvmefc_fcp_req *freq = &op->fcp_req;
1926         enum dma_data_direction dir;
1927         int ret;
1928
1929         freq->sg_cnt = 0;
1930
1931         if (!blk_rq_payload_bytes(rq))
1932                 return 0;
1933
1934         freq->sg_table.sgl = freq->first_sgl;
1935         ret = sg_alloc_table_chained(&freq->sg_table,
1936                         blk_rq_nr_phys_segments(rq), freq->sg_table.sgl);
1937         if (ret)
1938                 return -ENOMEM;
1939
1940         op->nents = blk_rq_map_sg(rq->q, rq, freq->sg_table.sgl);
1941         WARN_ON(op->nents > blk_rq_nr_phys_segments(rq));
1942         dir = (rq_data_dir(rq) == WRITE) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1943         freq->sg_cnt = fc_dma_map_sg(ctrl->lport->dev, freq->sg_table.sgl,
1944                                 op->nents, dir);
1945         if (unlikely(freq->sg_cnt <= 0)) {
1946                 sg_free_table_chained(&freq->sg_table, true);
1947                 freq->sg_cnt = 0;
1948                 return -EFAULT;
1949         }
1950
1951         /*
1952          * TODO: blk_integrity_rq(rq)  for DIF
1953          */
1954         return 0;
1955 }
1956
1957 static void
1958 nvme_fc_unmap_data(struct nvme_fc_ctrl *ctrl, struct request *rq,
1959                 struct nvme_fc_fcp_op *op)
1960 {
1961         struct nvmefc_fcp_req *freq = &op->fcp_req;
1962
1963         if (!freq->sg_cnt)
1964                 return;
1965
1966         fc_dma_unmap_sg(ctrl->lport->dev, freq->sg_table.sgl, op->nents,
1967                                 ((rq_data_dir(rq) == WRITE) ?
1968                                         DMA_TO_DEVICE : DMA_FROM_DEVICE));
1969
1970         nvme_cleanup_cmd(rq);
1971
1972         sg_free_table_chained(&freq->sg_table, true);
1973
1974         freq->sg_cnt = 0;
1975 }
1976
1977 /*
1978  * In FC, the queue is a logical thing. At transport connect, the target
1979  * creates its "queue" and returns a handle that is to be given to the
1980  * target whenever it posts something to the corresponding SQ.  When an
1981  * SQE is sent on a SQ, FC effectively considers the SQE, or rather the
1982  * command contained within the SQE, an io, and assigns a FC exchange
1983  * to it. The SQE and the associated SQ handle are sent in the initial
1984  * CMD IU sents on the exchange. All transfers relative to the io occur
1985  * as part of the exchange.  The CQE is the last thing for the io,
1986  * which is transferred (explicitly or implicitly) with the RSP IU
1987  * sent on the exchange. After the CQE is received, the FC exchange is
1988  * terminaed and the Exchange may be used on a different io.
1989  *
1990  * The transport to LLDD api has the transport making a request for a
1991  * new fcp io request to the LLDD. The LLDD then allocates a FC exchange
1992  * resource and transfers the command. The LLDD will then process all
1993  * steps to complete the io. Upon completion, the transport done routine
1994  * is called.
1995  *
1996  * So - while the operation is outstanding to the LLDD, there is a link
1997  * level FC exchange resource that is also outstanding. This must be
1998  * considered in all cleanup operations.
1999  */
2000 static blk_status_t
2001 nvme_fc_start_fcp_op(struct nvme_fc_ctrl *ctrl, struct nvme_fc_queue *queue,
2002         struct nvme_fc_fcp_op *op, u32 data_len,
2003         enum nvmefc_fcp_datadir io_dir)
2004 {
2005         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2006         struct nvme_command *sqe = &cmdiu->sqe;
2007         u32 csn;
2008         int ret;
2009
2010         /*
2011          * before attempting to send the io, check to see if we believe
2012          * the target device is present
2013          */
2014         if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
2015                 goto busy;
2016
2017         if (!nvme_fc_ctrl_get(ctrl))
2018                 return BLK_STS_IOERR;
2019
2020         /* format the FC-NVME CMD IU and fcp_req */
2021         cmdiu->connection_id = cpu_to_be64(queue->connection_id);
2022         csn = atomic_inc_return(&queue->csn);
2023         cmdiu->csn = cpu_to_be32(csn);
2024         cmdiu->data_len = cpu_to_be32(data_len);
2025         switch (io_dir) {
2026         case NVMEFC_FCP_WRITE:
2027                 cmdiu->flags = FCNVME_CMD_FLAGS_WRITE;
2028                 break;
2029         case NVMEFC_FCP_READ:
2030                 cmdiu->flags = FCNVME_CMD_FLAGS_READ;
2031                 break;
2032         case NVMEFC_FCP_NODATA:
2033                 cmdiu->flags = 0;
2034                 break;
2035         }
2036         op->fcp_req.payload_length = data_len;
2037         op->fcp_req.io_dir = io_dir;
2038         op->fcp_req.transferred_length = 0;
2039         op->fcp_req.rcv_rsplen = 0;
2040         op->fcp_req.status = NVME_SC_SUCCESS;
2041         op->fcp_req.sqid = cpu_to_le16(queue->qnum);
2042
2043         /*
2044          * validate per fabric rules, set fields mandated by fabric spec
2045          * as well as those by FC-NVME spec.
2046          */
2047         WARN_ON_ONCE(sqe->common.metadata);
2048         sqe->common.flags |= NVME_CMD_SGL_METABUF;
2049
2050         /*
2051          * format SQE DPTR field per FC-NVME rules:
2052          *    type=0x5     Transport SGL Data Block Descriptor
2053          *    subtype=0xA  Transport-specific value
2054          *    address=0
2055          *    length=length of the data series
2056          */
2057         sqe->rw.dptr.sgl.type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2058                                         NVME_SGL_FMT_TRANSPORT_A;
2059         sqe->rw.dptr.sgl.length = cpu_to_le32(data_len);
2060         sqe->rw.dptr.sgl.addr = 0;
2061
2062         if (!(op->flags & FCOP_FLAGS_AEN)) {
2063                 ret = nvme_fc_map_data(ctrl, op->rq, op);
2064                 if (ret < 0) {
2065                         nvme_cleanup_cmd(op->rq);
2066                         nvme_fc_ctrl_put(ctrl);
2067                         if (ret == -ENOMEM || ret == -EAGAIN)
2068                                 return BLK_STS_RESOURCE;
2069                         return BLK_STS_IOERR;
2070                 }
2071         }
2072
2073         fc_dma_sync_single_for_device(ctrl->lport->dev, op->fcp_req.cmddma,
2074                                   sizeof(op->cmd_iu), DMA_TO_DEVICE);
2075
2076         atomic_set(&op->state, FCPOP_STATE_ACTIVE);
2077
2078         if (!(op->flags & FCOP_FLAGS_AEN))
2079                 blk_mq_start_request(op->rq);
2080
2081         ret = ctrl->lport->ops->fcp_io(&ctrl->lport->localport,
2082                                         &ctrl->rport->remoteport,
2083                                         queue->lldd_handle, &op->fcp_req);
2084
2085         if (ret) {
2086                 if (!(op->flags & FCOP_FLAGS_AEN))
2087                         nvme_fc_unmap_data(ctrl, op->rq, op);
2088
2089                 nvme_fc_ctrl_put(ctrl);
2090
2091                 if (ctrl->rport->remoteport.port_state == FC_OBJSTATE_ONLINE &&
2092                                 ret != -EBUSY)
2093                         return BLK_STS_IOERR;
2094
2095                 goto busy;
2096         }
2097
2098         return BLK_STS_OK;
2099
2100 busy:
2101         if (!(op->flags & FCOP_FLAGS_AEN) && queue->hctx)
2102                 blk_mq_delay_run_hw_queue(queue->hctx, NVMEFC_QUEUE_DELAY);
2103
2104         return BLK_STS_RESOURCE;
2105 }
2106
2107 static blk_status_t
2108 nvme_fc_queue_rq(struct blk_mq_hw_ctx *hctx,
2109                         const struct blk_mq_queue_data *bd)
2110 {
2111         struct nvme_ns *ns = hctx->queue->queuedata;
2112         struct nvme_fc_queue *queue = hctx->driver_data;
2113         struct nvme_fc_ctrl *ctrl = queue->ctrl;
2114         struct request *rq = bd->rq;
2115         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2116         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2117         struct nvme_command *sqe = &cmdiu->sqe;
2118         enum nvmefc_fcp_datadir io_dir;
2119         u32 data_len;
2120         blk_status_t ret;
2121
2122         ret = nvme_setup_cmd(ns, rq, sqe);
2123         if (ret)
2124                 return ret;
2125
2126         data_len = blk_rq_payload_bytes(rq);
2127         if (data_len)
2128                 io_dir = ((rq_data_dir(rq) == WRITE) ?
2129                                         NVMEFC_FCP_WRITE : NVMEFC_FCP_READ);
2130         else
2131                 io_dir = NVMEFC_FCP_NODATA;
2132
2133         return nvme_fc_start_fcp_op(ctrl, queue, op, data_len, io_dir);
2134 }
2135
2136 static struct blk_mq_tags *
2137 nvme_fc_tagset(struct nvme_fc_queue *queue)
2138 {
2139         if (queue->qnum == 0)
2140                 return queue->ctrl->admin_tag_set.tags[queue->qnum];
2141
2142         return queue->ctrl->tag_set.tags[queue->qnum - 1];
2143 }
2144
2145 static int
2146 nvme_fc_poll(struct blk_mq_hw_ctx *hctx, unsigned int tag)
2147
2148 {
2149         struct nvme_fc_queue *queue = hctx->driver_data;
2150         struct nvme_fc_ctrl *ctrl = queue->ctrl;
2151         struct request *req;
2152         struct nvme_fc_fcp_op *op;
2153
2154         req = blk_mq_tag_to_rq(nvme_fc_tagset(queue), tag);
2155         if (!req)
2156                 return 0;
2157
2158         op = blk_mq_rq_to_pdu(req);
2159
2160         if ((atomic_read(&op->state) == FCPOP_STATE_ACTIVE) &&
2161                  (ctrl->lport->ops->poll_queue))
2162                 ctrl->lport->ops->poll_queue(&ctrl->lport->localport,
2163                                                  queue->lldd_handle);
2164
2165         return ((atomic_read(&op->state) != FCPOP_STATE_ACTIVE));
2166 }
2167
2168 static void
2169 nvme_fc_submit_async_event(struct nvme_ctrl *arg, int aer_idx)
2170 {
2171         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(arg);
2172         struct nvme_fc_fcp_op *aen_op;
2173         unsigned long flags;
2174         bool terminating = false;
2175         blk_status_t ret;
2176
2177         if (aer_idx > NVME_FC_NR_AEN_COMMANDS)
2178                 return;
2179
2180         spin_lock_irqsave(&ctrl->lock, flags);
2181         if (ctrl->flags & FCCTRL_TERMIO)
2182                 terminating = true;
2183         spin_unlock_irqrestore(&ctrl->lock, flags);
2184
2185         if (terminating)
2186                 return;
2187
2188         aen_op = &ctrl->aen_ops[aer_idx];
2189
2190         ret = nvme_fc_start_fcp_op(ctrl, aen_op->queue, aen_op, 0,
2191                                         NVMEFC_FCP_NODATA);
2192         if (ret)
2193                 dev_err(ctrl->ctrl.device,
2194                         "failed async event work [%d]\n", aer_idx);
2195 }
2196
2197 static void
2198 __nvme_fc_final_op_cleanup(struct request *rq)
2199 {
2200         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2201         struct nvme_fc_ctrl *ctrl = op->ctrl;
2202
2203         atomic_set(&op->state, FCPOP_STATE_IDLE);
2204         op->flags &= ~(FCOP_FLAGS_TERMIO | FCOP_FLAGS_RELEASED |
2205                         FCOP_FLAGS_COMPLETE);
2206
2207         nvme_fc_unmap_data(ctrl, rq, op);
2208         nvme_complete_rq(rq);
2209         nvme_fc_ctrl_put(ctrl);
2210
2211 }
2212
2213 static void
2214 nvme_fc_complete_rq(struct request *rq)
2215 {
2216         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2217         struct nvme_fc_ctrl *ctrl = op->ctrl;
2218         unsigned long flags;
2219         bool completed = false;
2220
2221         /*
2222          * the core layer, on controller resets after calling
2223          * nvme_shutdown_ctrl(), calls complete_rq without our
2224          * calling blk_mq_complete_request(), thus there may still
2225          * be live i/o outstanding with the LLDD. Means transport has
2226          * to track complete calls vs fcpio_done calls to know what
2227          * path to take on completes and dones.
2228          */
2229         spin_lock_irqsave(&ctrl->lock, flags);
2230         if (op->flags & FCOP_FLAGS_COMPLETE)
2231                 completed = true;
2232         else
2233                 op->flags |= FCOP_FLAGS_RELEASED;
2234         spin_unlock_irqrestore(&ctrl->lock, flags);
2235
2236         if (completed)
2237                 __nvme_fc_final_op_cleanup(rq);
2238 }
2239
2240 /*
2241  * This routine is used by the transport when it needs to find active
2242  * io on a queue that is to be terminated. The transport uses
2243  * blk_mq_tagset_busy_itr() to find the busy requests, which then invoke
2244  * this routine to kill them on a 1 by 1 basis.
2245  *
2246  * As FC allocates FC exchange for each io, the transport must contact
2247  * the LLDD to terminate the exchange, thus releasing the FC exchange.
2248  * After terminating the exchange the LLDD will call the transport's
2249  * normal io done path for the request, but it will have an aborted
2250  * status. The done path will return the io request back to the block
2251  * layer with an error status.
2252  */
2253 static void
2254 nvme_fc_terminate_exchange(struct request *req, void *data, bool reserved)
2255 {
2256         struct nvme_ctrl *nctrl = data;
2257         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
2258         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(req);
2259         unsigned long flags;
2260         int status;
2261
2262         if (!blk_mq_request_started(req))
2263                 return;
2264
2265         spin_lock_irqsave(&ctrl->lock, flags);
2266         if (ctrl->flags & FCCTRL_TERMIO) {
2267                 ctrl->iocnt++;
2268                 op->flags |= FCOP_FLAGS_TERMIO;
2269         }
2270         spin_unlock_irqrestore(&ctrl->lock, flags);
2271
2272         status = __nvme_fc_abort_op(ctrl, op);
2273         if (status) {
2274                 /*
2275                  * if __nvme_fc_abort_op failed the io wasn't
2276                  * active. Thus this call path is running in
2277                  * parallel to the io complete. Treat as non-error.
2278                  */
2279
2280                 /* back out the flags/counters */
2281                 spin_lock_irqsave(&ctrl->lock, flags);
2282                 if (ctrl->flags & FCCTRL_TERMIO)
2283                         ctrl->iocnt--;
2284                 op->flags &= ~FCOP_FLAGS_TERMIO;
2285                 spin_unlock_irqrestore(&ctrl->lock, flags);
2286                 return;
2287         }
2288 }
2289
2290
2291 static const struct blk_mq_ops nvme_fc_mq_ops = {
2292         .queue_rq       = nvme_fc_queue_rq,
2293         .complete       = nvme_fc_complete_rq,
2294         .init_request   = nvme_fc_init_request,
2295         .exit_request   = nvme_fc_exit_request,
2296         .init_hctx      = nvme_fc_init_hctx,
2297         .poll           = nvme_fc_poll,
2298         .timeout        = nvme_fc_timeout,
2299 };
2300
2301 static int
2302 nvme_fc_create_io_queues(struct nvme_fc_ctrl *ctrl)
2303 {
2304         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2305         unsigned int nr_io_queues;
2306         int ret;
2307
2308         nr_io_queues = min(min(opts->nr_io_queues, num_online_cpus()),
2309                                 ctrl->lport->ops->max_hw_queues);
2310         ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
2311         if (ret) {
2312                 dev_info(ctrl->ctrl.device,
2313                         "set_queue_count failed: %d\n", ret);
2314                 return ret;
2315         }
2316
2317         ctrl->ctrl.queue_count = nr_io_queues + 1;
2318         if (!nr_io_queues)
2319                 return 0;
2320
2321         nvme_fc_init_io_queues(ctrl);
2322
2323         memset(&ctrl->tag_set, 0, sizeof(ctrl->tag_set));
2324         ctrl->tag_set.ops = &nvme_fc_mq_ops;
2325         ctrl->tag_set.queue_depth = ctrl->ctrl.opts->queue_size;
2326         ctrl->tag_set.reserved_tags = 1; /* fabric connect */
2327         ctrl->tag_set.numa_node = NUMA_NO_NODE;
2328         ctrl->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2329         ctrl->tag_set.cmd_size = sizeof(struct nvme_fc_fcp_op) +
2330                                         (SG_CHUNK_SIZE *
2331                                                 sizeof(struct scatterlist)) +
2332                                         ctrl->lport->ops->fcprqst_priv_sz;
2333         ctrl->tag_set.driver_data = ctrl;
2334         ctrl->tag_set.nr_hw_queues = ctrl->ctrl.queue_count - 1;
2335         ctrl->tag_set.timeout = NVME_IO_TIMEOUT;
2336
2337         ret = blk_mq_alloc_tag_set(&ctrl->tag_set);
2338         if (ret)
2339                 return ret;
2340
2341         ctrl->ctrl.tagset = &ctrl->tag_set;
2342
2343         ctrl->ctrl.connect_q = blk_mq_init_queue(&ctrl->tag_set);
2344         if (IS_ERR(ctrl->ctrl.connect_q)) {
2345                 ret = PTR_ERR(ctrl->ctrl.connect_q);
2346                 goto out_free_tag_set;
2347         }
2348
2349         ret = nvme_fc_create_hw_io_queues(ctrl, ctrl->ctrl.opts->queue_size);
2350         if (ret)
2351                 goto out_cleanup_blk_queue;
2352
2353         ret = nvme_fc_connect_io_queues(ctrl, ctrl->ctrl.opts->queue_size);
2354         if (ret)
2355                 goto out_delete_hw_queues;
2356
2357         return 0;
2358
2359 out_delete_hw_queues:
2360         nvme_fc_delete_hw_io_queues(ctrl);
2361 out_cleanup_blk_queue:
2362         blk_cleanup_queue(ctrl->ctrl.connect_q);
2363 out_free_tag_set:
2364         blk_mq_free_tag_set(&ctrl->tag_set);
2365         nvme_fc_free_io_queues(ctrl);
2366
2367         /* force put free routine to ignore io queues */
2368         ctrl->ctrl.tagset = NULL;
2369
2370         return ret;
2371 }
2372
2373 static int
2374 nvme_fc_reinit_io_queues(struct nvme_fc_ctrl *ctrl)
2375 {
2376         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2377         unsigned int nr_io_queues;
2378         int ret;
2379
2380         nr_io_queues = min(min(opts->nr_io_queues, num_online_cpus()),
2381                                 ctrl->lport->ops->max_hw_queues);
2382         ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
2383         if (ret) {
2384                 dev_info(ctrl->ctrl.device,
2385                         "set_queue_count failed: %d\n", ret);
2386                 return ret;
2387         }
2388
2389         ctrl->ctrl.queue_count = nr_io_queues + 1;
2390         /* check for io queues existing */
2391         if (ctrl->ctrl.queue_count == 1)
2392                 return 0;
2393
2394         nvme_fc_init_io_queues(ctrl);
2395
2396         ret = nvme_reinit_tagset(&ctrl->ctrl, ctrl->ctrl.tagset);
2397         if (ret)
2398                 goto out_free_io_queues;
2399
2400         ret = nvme_fc_create_hw_io_queues(ctrl, ctrl->ctrl.opts->queue_size);
2401         if (ret)
2402                 goto out_free_io_queues;
2403
2404         ret = nvme_fc_connect_io_queues(ctrl, ctrl->ctrl.opts->queue_size);
2405         if (ret)
2406                 goto out_delete_hw_queues;
2407
2408         blk_mq_update_nr_hw_queues(&ctrl->tag_set, nr_io_queues);
2409
2410         return 0;
2411
2412 out_delete_hw_queues:
2413         nvme_fc_delete_hw_io_queues(ctrl);
2414 out_free_io_queues:
2415         nvme_fc_free_io_queues(ctrl);
2416         return ret;
2417 }
2418
2419 /*
2420  * This routine restarts the controller on the host side, and
2421  * on the link side, recreates the controller association.
2422  */
2423 static int
2424 nvme_fc_create_association(struct nvme_fc_ctrl *ctrl)
2425 {
2426         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2427         u32 segs;
2428         int ret;
2429         bool changed;
2430
2431         ++ctrl->ctrl.nr_reconnects;
2432
2433         /*
2434          * Create the admin queue
2435          */
2436
2437         nvme_fc_init_queue(ctrl, 0, NVME_FC_AQ_BLKMQ_DEPTH);
2438
2439         ret = __nvme_fc_create_hw_queue(ctrl, &ctrl->queues[0], 0,
2440                                 NVME_FC_AQ_BLKMQ_DEPTH);
2441         if (ret)
2442                 goto out_free_queue;
2443
2444         ret = nvme_fc_connect_admin_queue(ctrl, &ctrl->queues[0],
2445                                 NVME_FC_AQ_BLKMQ_DEPTH,
2446                                 (NVME_FC_AQ_BLKMQ_DEPTH / 4));
2447         if (ret)
2448                 goto out_delete_hw_queue;
2449
2450         if (ctrl->ctrl.state != NVME_CTRL_NEW)
2451                 blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
2452
2453         ret = nvmf_connect_admin_queue(&ctrl->ctrl);
2454         if (ret)
2455                 goto out_disconnect_admin_queue;
2456
2457         /*
2458          * Check controller capabilities
2459          *
2460          * todo:- add code to check if ctrl attributes changed from
2461          * prior connection values
2462          */
2463
2464         ret = nvmf_reg_read64(&ctrl->ctrl, NVME_REG_CAP, &ctrl->ctrl.cap);
2465         if (ret) {
2466                 dev_err(ctrl->ctrl.device,
2467                         "prop_get NVME_REG_CAP failed\n");
2468                 goto out_disconnect_admin_queue;
2469         }
2470
2471         ctrl->ctrl.sqsize =
2472                 min_t(int, NVME_CAP_MQES(ctrl->ctrl.cap) + 1, ctrl->ctrl.sqsize);
2473
2474         ret = nvme_enable_ctrl(&ctrl->ctrl, ctrl->ctrl.cap);
2475         if (ret)
2476                 goto out_disconnect_admin_queue;
2477
2478         segs = min_t(u32, NVME_FC_MAX_SEGMENTS,
2479                         ctrl->lport->ops->max_sgl_segments);
2480         ctrl->ctrl.max_hw_sectors = (segs - 1) << (PAGE_SHIFT - 9);
2481
2482         ret = nvme_init_identify(&ctrl->ctrl);
2483         if (ret)
2484                 goto out_disconnect_admin_queue;
2485
2486         /* sanity checks */
2487
2488         /* FC-NVME does not have other data in the capsule */
2489         if (ctrl->ctrl.icdoff) {
2490                 dev_err(ctrl->ctrl.device, "icdoff %d is not supported!\n",
2491                                 ctrl->ctrl.icdoff);
2492                 goto out_disconnect_admin_queue;
2493         }
2494
2495         /* FC-NVME supports normal SGL Data Block Descriptors */
2496
2497         if (opts->queue_size > ctrl->ctrl.maxcmd) {
2498                 /* warn if maxcmd is lower than queue_size */
2499                 dev_warn(ctrl->ctrl.device,
2500                         "queue_size %zu > ctrl maxcmd %u, reducing "
2501                         "to queue_size\n",
2502                         opts->queue_size, ctrl->ctrl.maxcmd);
2503                 opts->queue_size = ctrl->ctrl.maxcmd;
2504         }
2505
2506         ret = nvme_fc_init_aen_ops(ctrl);
2507         if (ret)
2508                 goto out_term_aen_ops;
2509
2510         /*
2511          * Create the io queues
2512          */
2513
2514         if (ctrl->ctrl.queue_count > 1) {
2515                 if (ctrl->ctrl.state == NVME_CTRL_NEW)
2516                         ret = nvme_fc_create_io_queues(ctrl);
2517                 else
2518                         ret = nvme_fc_reinit_io_queues(ctrl);
2519                 if (ret)
2520                         goto out_term_aen_ops;
2521         }
2522
2523         changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE);
2524         WARN_ON_ONCE(!changed);
2525
2526         ctrl->ctrl.nr_reconnects = 0;
2527
2528         nvme_start_ctrl(&ctrl->ctrl);
2529
2530         return 0;       /* Success */
2531
2532 out_term_aen_ops:
2533         nvme_fc_term_aen_ops(ctrl);
2534 out_disconnect_admin_queue:
2535         /* send a Disconnect(association) LS to fc-nvme target */
2536         nvme_fc_xmt_disconnect_assoc(ctrl);
2537 out_delete_hw_queue:
2538         __nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[0], 0);
2539 out_free_queue:
2540         nvme_fc_free_queue(&ctrl->queues[0]);
2541
2542         return ret;
2543 }
2544
2545 /*
2546  * This routine stops operation of the controller on the host side.
2547  * On the host os stack side: Admin and IO queues are stopped,
2548  *   outstanding ios on them terminated via FC ABTS.
2549  * On the link side: the association is terminated.
2550  */
2551 static void
2552 nvme_fc_delete_association(struct nvme_fc_ctrl *ctrl)
2553 {
2554         unsigned long flags;
2555
2556         spin_lock_irqsave(&ctrl->lock, flags);
2557         ctrl->flags |= FCCTRL_TERMIO;
2558         ctrl->iocnt = 0;
2559         spin_unlock_irqrestore(&ctrl->lock, flags);
2560
2561         /*
2562          * If io queues are present, stop them and terminate all outstanding
2563          * ios on them. As FC allocates FC exchange for each io, the
2564          * transport must contact the LLDD to terminate the exchange,
2565          * thus releasing the FC exchange. We use blk_mq_tagset_busy_itr()
2566          * to tell us what io's are busy and invoke a transport routine
2567          * to kill them with the LLDD.  After terminating the exchange
2568          * the LLDD will call the transport's normal io done path, but it
2569          * will have an aborted status. The done path will return the
2570          * io requests back to the block layer as part of normal completions
2571          * (but with error status).
2572          */
2573         if (ctrl->ctrl.queue_count > 1) {
2574                 nvme_stop_queues(&ctrl->ctrl);
2575                 blk_mq_tagset_busy_iter(&ctrl->tag_set,
2576                                 nvme_fc_terminate_exchange, &ctrl->ctrl);
2577         }
2578
2579         /*
2580          * Other transports, which don't have link-level contexts bound
2581          * to sqe's, would try to gracefully shutdown the controller by
2582          * writing the registers for shutdown and polling (call
2583          * nvme_shutdown_ctrl()). Given a bunch of i/o was potentially
2584          * just aborted and we will wait on those contexts, and given
2585          * there was no indication of how live the controlelr is on the
2586          * link, don't send more io to create more contexts for the
2587          * shutdown. Let the controller fail via keepalive failure if
2588          * its still present.
2589          */
2590
2591         /*
2592          * clean up the admin queue. Same thing as above.
2593          * use blk_mq_tagset_busy_itr() and the transport routine to
2594          * terminate the exchanges.
2595          */
2596         blk_mq_quiesce_queue(ctrl->ctrl.admin_q);
2597         blk_mq_tagset_busy_iter(&ctrl->admin_tag_set,
2598                                 nvme_fc_terminate_exchange, &ctrl->ctrl);
2599
2600         /* kill the aens as they are a separate path */
2601         nvme_fc_abort_aen_ops(ctrl);
2602
2603         /* wait for all io that had to be aborted */
2604         spin_lock_irqsave(&ctrl->lock, flags);
2605         wait_event_lock_irq(ctrl->ioabort_wait, ctrl->iocnt == 0, ctrl->lock);
2606         ctrl->flags &= ~FCCTRL_TERMIO;
2607         spin_unlock_irqrestore(&ctrl->lock, flags);
2608
2609         nvme_fc_term_aen_ops(ctrl);
2610
2611         /*
2612          * send a Disconnect(association) LS to fc-nvme target
2613          * Note: could have been sent at top of process, but
2614          * cleaner on link traffic if after the aborts complete.
2615          * Note: if association doesn't exist, association_id will be 0
2616          */
2617         if (ctrl->association_id)
2618                 nvme_fc_xmt_disconnect_assoc(ctrl);
2619
2620         if (ctrl->ctrl.tagset) {
2621                 nvme_fc_delete_hw_io_queues(ctrl);
2622                 nvme_fc_free_io_queues(ctrl);
2623         }
2624
2625         __nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[0], 0);
2626         nvme_fc_free_queue(&ctrl->queues[0]);
2627 }
2628
2629 static void
2630 nvme_fc_delete_ctrl_work(struct work_struct *work)
2631 {
2632         struct nvme_fc_ctrl *ctrl =
2633                 container_of(work, struct nvme_fc_ctrl, delete_work);
2634
2635         cancel_work_sync(&ctrl->ctrl.reset_work);
2636         cancel_delayed_work_sync(&ctrl->connect_work);
2637         nvme_stop_ctrl(&ctrl->ctrl);
2638         nvme_remove_namespaces(&ctrl->ctrl);
2639         /*
2640          * kill the association on the link side.  this will block
2641          * waiting for io to terminate
2642          */
2643         nvme_fc_delete_association(ctrl);
2644
2645         /*
2646          * tear down the controller
2647          * After the last reference on the nvme ctrl is removed,
2648          * the transport nvme_fc_nvme_ctrl_freed() callback will be
2649          * invoked. From there, the transport will tear down it's
2650          * logical queues and association.
2651          */
2652         nvme_uninit_ctrl(&ctrl->ctrl);
2653
2654         nvme_put_ctrl(&ctrl->ctrl);
2655 }
2656
2657 static bool
2658 __nvme_fc_schedule_delete_work(struct nvme_fc_ctrl *ctrl)
2659 {
2660         if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_DELETING))
2661                 return true;
2662
2663         if (!queue_work(nvme_wq, &ctrl->delete_work))
2664                 return true;
2665
2666         return false;
2667 }
2668
2669 static int
2670 __nvme_fc_del_ctrl(struct nvme_fc_ctrl *ctrl)
2671 {
2672         return __nvme_fc_schedule_delete_work(ctrl) ? -EBUSY : 0;
2673 }
2674
2675 /*
2676  * Request from nvme core layer to delete the controller
2677  */
2678 static int
2679 nvme_fc_del_nvme_ctrl(struct nvme_ctrl *nctrl)
2680 {
2681         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
2682         int ret;
2683
2684         if (!kref_get_unless_zero(&ctrl->ctrl.kref))
2685                 return -EBUSY;
2686
2687         ret = __nvme_fc_del_ctrl(ctrl);
2688
2689         if (!ret)
2690                 flush_workqueue(nvme_wq);
2691
2692         nvme_put_ctrl(&ctrl->ctrl);
2693
2694         return ret;
2695 }
2696
2697 static void
2698 nvme_fc_reconnect_or_delete(struct nvme_fc_ctrl *ctrl, int status)
2699 {
2700         /* If we are resetting/deleting then do nothing */
2701         if (ctrl->ctrl.state != NVME_CTRL_RECONNECTING) {
2702                 WARN_ON_ONCE(ctrl->ctrl.state == NVME_CTRL_NEW ||
2703                         ctrl->ctrl.state == NVME_CTRL_LIVE);
2704                 return;
2705         }
2706
2707         dev_info(ctrl->ctrl.device,
2708                 "NVME-FC{%d}: reset: Reconnect attempt failed (%d)\n",
2709                 ctrl->cnum, status);
2710
2711         if (nvmf_should_reconnect(&ctrl->ctrl)) {
2712                 dev_info(ctrl->ctrl.device,
2713                         "NVME-FC{%d}: Reconnect attempt in %d seconds.\n",
2714                         ctrl->cnum, ctrl->ctrl.opts->reconnect_delay);
2715                 queue_delayed_work(nvme_wq, &ctrl->connect_work,
2716                                 ctrl->ctrl.opts->reconnect_delay * HZ);
2717         } else {
2718                 dev_warn(ctrl->ctrl.device,
2719                                 "NVME-FC{%d}: Max reconnect attempts (%d) "
2720                                 "reached. Removing controller\n",
2721                                 ctrl->cnum, ctrl->ctrl.nr_reconnects);
2722                 WARN_ON(__nvme_fc_schedule_delete_work(ctrl));
2723         }
2724 }
2725
2726 static void
2727 nvme_fc_reset_ctrl_work(struct work_struct *work)
2728 {
2729         struct nvme_fc_ctrl *ctrl =
2730                 container_of(work, struct nvme_fc_ctrl, ctrl.reset_work);
2731         int ret;
2732
2733         nvme_stop_ctrl(&ctrl->ctrl);
2734         /* will block will waiting for io to terminate */
2735         nvme_fc_delete_association(ctrl);
2736
2737         ret = nvme_fc_create_association(ctrl);
2738         if (ret)
2739                 nvme_fc_reconnect_or_delete(ctrl, ret);
2740         else
2741                 dev_info(ctrl->ctrl.device,
2742                         "NVME-FC{%d}: controller reset complete\n", ctrl->cnum);
2743 }
2744
2745 static const struct nvme_ctrl_ops nvme_fc_ctrl_ops = {
2746         .name                   = "fc",
2747         .module                 = THIS_MODULE,
2748         .flags                  = NVME_F_FABRICS,
2749         .reg_read32             = nvmf_reg_read32,
2750         .reg_read64             = nvmf_reg_read64,
2751         .reg_write32            = nvmf_reg_write32,
2752         .free_ctrl              = nvme_fc_nvme_ctrl_freed,
2753         .submit_async_event     = nvme_fc_submit_async_event,
2754         .delete_ctrl            = nvme_fc_del_nvme_ctrl,
2755         .get_address            = nvmf_get_address,
2756         .reinit_request         = nvme_fc_reinit_request,
2757 };
2758
2759 static void
2760 nvme_fc_connect_ctrl_work(struct work_struct *work)
2761 {
2762         int ret;
2763
2764         struct nvme_fc_ctrl *ctrl =
2765                         container_of(to_delayed_work(work),
2766                                 struct nvme_fc_ctrl, connect_work);
2767
2768         ret = nvme_fc_create_association(ctrl);
2769         if (ret)
2770                 nvme_fc_reconnect_or_delete(ctrl, ret);
2771         else
2772                 dev_info(ctrl->ctrl.device,
2773                         "NVME-FC{%d}: controller reconnect complete\n",
2774                         ctrl->cnum);
2775 }
2776
2777
2778 static const struct blk_mq_ops nvme_fc_admin_mq_ops = {
2779         .queue_rq       = nvme_fc_queue_rq,
2780         .complete       = nvme_fc_complete_rq,
2781         .init_request   = nvme_fc_init_request,
2782         .exit_request   = nvme_fc_exit_request,
2783         .init_hctx      = nvme_fc_init_admin_hctx,
2784         .timeout        = nvme_fc_timeout,
2785 };
2786
2787
2788 static struct nvme_ctrl *
2789 nvme_fc_init_ctrl(struct device *dev, struct nvmf_ctrl_options *opts,
2790         struct nvme_fc_lport *lport, struct nvme_fc_rport *rport)
2791 {
2792         struct nvme_fc_ctrl *ctrl;
2793         unsigned long flags;
2794         int ret, idx;
2795
2796         if (!(rport->remoteport.port_role &
2797             (FC_PORT_ROLE_NVME_DISCOVERY | FC_PORT_ROLE_NVME_TARGET))) {
2798                 ret = -EBADR;
2799                 goto out_fail;
2800         }
2801
2802         ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
2803         if (!ctrl) {
2804                 ret = -ENOMEM;
2805                 goto out_fail;
2806         }
2807
2808         idx = ida_simple_get(&nvme_fc_ctrl_cnt, 0, 0, GFP_KERNEL);
2809         if (idx < 0) {
2810                 ret = -ENOSPC;
2811                 goto out_free_ctrl;
2812         }
2813
2814         ctrl->ctrl.opts = opts;
2815         INIT_LIST_HEAD(&ctrl->ctrl_list);
2816         ctrl->lport = lport;
2817         ctrl->rport = rport;
2818         ctrl->dev = lport->dev;
2819         ctrl->cnum = idx;
2820
2821         get_device(ctrl->dev);
2822         kref_init(&ctrl->ref);
2823
2824         INIT_WORK(&ctrl->delete_work, nvme_fc_delete_ctrl_work);
2825         INIT_WORK(&ctrl->ctrl.reset_work, nvme_fc_reset_ctrl_work);
2826         INIT_DELAYED_WORK(&ctrl->connect_work, nvme_fc_connect_ctrl_work);
2827         spin_lock_init(&ctrl->lock);
2828
2829         /* io queue count */
2830         ctrl->ctrl.queue_count = min_t(unsigned int,
2831                                 opts->nr_io_queues,
2832                                 lport->ops->max_hw_queues);
2833         ctrl->ctrl.queue_count++;       /* +1 for admin queue */
2834
2835         ctrl->ctrl.sqsize = opts->queue_size - 1;
2836         ctrl->ctrl.kato = opts->kato;
2837
2838         ret = -ENOMEM;
2839         ctrl->queues = kcalloc(ctrl->ctrl.queue_count,
2840                                 sizeof(struct nvme_fc_queue), GFP_KERNEL);
2841         if (!ctrl->queues)
2842                 goto out_free_ida;
2843
2844         memset(&ctrl->admin_tag_set, 0, sizeof(ctrl->admin_tag_set));
2845         ctrl->admin_tag_set.ops = &nvme_fc_admin_mq_ops;
2846         ctrl->admin_tag_set.queue_depth = NVME_FC_AQ_BLKMQ_DEPTH;
2847         ctrl->admin_tag_set.reserved_tags = 2; /* fabric connect + Keep-Alive */
2848         ctrl->admin_tag_set.numa_node = NUMA_NO_NODE;
2849         ctrl->admin_tag_set.cmd_size = sizeof(struct nvme_fc_fcp_op) +
2850                                         (SG_CHUNK_SIZE *
2851                                                 sizeof(struct scatterlist)) +
2852                                         ctrl->lport->ops->fcprqst_priv_sz;
2853         ctrl->admin_tag_set.driver_data = ctrl;
2854         ctrl->admin_tag_set.nr_hw_queues = 1;
2855         ctrl->admin_tag_set.timeout = ADMIN_TIMEOUT;
2856
2857         ret = blk_mq_alloc_tag_set(&ctrl->admin_tag_set);
2858         if (ret)
2859                 goto out_free_queues;
2860         ctrl->ctrl.admin_tagset = &ctrl->admin_tag_set;
2861
2862         ctrl->ctrl.admin_q = blk_mq_init_queue(&ctrl->admin_tag_set);
2863         if (IS_ERR(ctrl->ctrl.admin_q)) {
2864                 ret = PTR_ERR(ctrl->ctrl.admin_q);
2865                 goto out_free_admin_tag_set;
2866         }
2867
2868         /*
2869          * Would have been nice to init io queues tag set as well.
2870          * However, we require interaction from the controller
2871          * for max io queue count before we can do so.
2872          * Defer this to the connect path.
2873          */
2874
2875         ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_fc_ctrl_ops, 0);
2876         if (ret)
2877                 goto out_cleanup_admin_q;
2878
2879         /* at this point, teardown path changes to ref counting on nvme ctrl */
2880
2881         spin_lock_irqsave(&rport->lock, flags);
2882         list_add_tail(&ctrl->ctrl_list, &rport->ctrl_list);
2883         spin_unlock_irqrestore(&rport->lock, flags);
2884
2885         ret = nvme_fc_create_association(ctrl);
2886         if (ret) {
2887                 ctrl->ctrl.opts = NULL;
2888                 /* initiate nvme ctrl ref counting teardown */
2889                 nvme_uninit_ctrl(&ctrl->ctrl);
2890                 nvme_put_ctrl(&ctrl->ctrl);
2891
2892                 /* Remove core ctrl ref. */
2893                 nvme_put_ctrl(&ctrl->ctrl);
2894
2895                 /* as we're past the point where we transition to the ref
2896                  * counting teardown path, if we return a bad pointer here,
2897                  * the calling routine, thinking it's prior to the
2898                  * transition, will do an rport put. Since the teardown
2899                  * path also does a rport put, we do an extra get here to
2900                  * so proper order/teardown happens.
2901                  */
2902                 nvme_fc_rport_get(rport);
2903
2904                 if (ret > 0)
2905                         ret = -EIO;
2906                 return ERR_PTR(ret);
2907         }
2908
2909         kref_get(&ctrl->ctrl.kref);
2910
2911         dev_info(ctrl->ctrl.device,
2912                 "NVME-FC{%d}: new ctrl: NQN \"%s\"\n",
2913                 ctrl->cnum, ctrl->ctrl.opts->subsysnqn);
2914
2915         return &ctrl->ctrl;
2916
2917 out_cleanup_admin_q:
2918         blk_cleanup_queue(ctrl->ctrl.admin_q);
2919 out_free_admin_tag_set:
2920         blk_mq_free_tag_set(&ctrl->admin_tag_set);
2921 out_free_queues:
2922         kfree(ctrl->queues);
2923 out_free_ida:
2924         put_device(ctrl->dev);
2925         ida_simple_remove(&nvme_fc_ctrl_cnt, ctrl->cnum);
2926 out_free_ctrl:
2927         kfree(ctrl);
2928 out_fail:
2929         /* exit via here doesn't follow ctlr ref points */
2930         return ERR_PTR(ret);
2931 }
2932
2933
2934 struct nvmet_fc_traddr {
2935         u64     nn;
2936         u64     pn;
2937 };
2938
2939 static int
2940 __nvme_fc_parse_u64(substring_t *sstr, u64 *val)
2941 {
2942         u64 token64;
2943
2944         if (match_u64(sstr, &token64))
2945                 return -EINVAL;
2946         *val = token64;
2947
2948         return 0;
2949 }
2950
2951 /*
2952  * This routine validates and extracts the WWN's from the TRADDR string.
2953  * As kernel parsers need the 0x to determine number base, universally
2954  * build string to parse with 0x prefix before parsing name strings.
2955  */
2956 static int
2957 nvme_fc_parse_traddr(struct nvmet_fc_traddr *traddr, char *buf, size_t blen)
2958 {
2959         char name[2 + NVME_FC_TRADDR_HEXNAMELEN + 1];
2960         substring_t wwn = { name, &name[sizeof(name)-1] };
2961         int nnoffset, pnoffset;
2962
2963         /* validate it string one of the 2 allowed formats */
2964         if (strnlen(buf, blen) == NVME_FC_TRADDR_MAXLENGTH &&
2965                         !strncmp(buf, "nn-0x", NVME_FC_TRADDR_OXNNLEN) &&
2966                         !strncmp(&buf[NVME_FC_TRADDR_MAX_PN_OFFSET],
2967                                 "pn-0x", NVME_FC_TRADDR_OXNNLEN)) {
2968                 nnoffset = NVME_FC_TRADDR_OXNNLEN;
2969                 pnoffset = NVME_FC_TRADDR_MAX_PN_OFFSET +
2970                                                 NVME_FC_TRADDR_OXNNLEN;
2971         } else if ((strnlen(buf, blen) == NVME_FC_TRADDR_MINLENGTH &&
2972                         !strncmp(buf, "nn-", NVME_FC_TRADDR_NNLEN) &&
2973                         !strncmp(&buf[NVME_FC_TRADDR_MIN_PN_OFFSET],
2974                                 "pn-", NVME_FC_TRADDR_NNLEN))) {
2975                 nnoffset = NVME_FC_TRADDR_NNLEN;
2976                 pnoffset = NVME_FC_TRADDR_MIN_PN_OFFSET + NVME_FC_TRADDR_NNLEN;
2977         } else
2978                 goto out_einval;
2979
2980         name[0] = '0';
2981         name[1] = 'x';
2982         name[2 + NVME_FC_TRADDR_HEXNAMELEN] = 0;
2983
2984         memcpy(&name[2], &buf[nnoffset], NVME_FC_TRADDR_HEXNAMELEN);
2985         if (__nvme_fc_parse_u64(&wwn, &traddr->nn))
2986                 goto out_einval;
2987
2988         memcpy(&name[2], &buf[pnoffset], NVME_FC_TRADDR_HEXNAMELEN);
2989         if (__nvme_fc_parse_u64(&wwn, &traddr->pn))
2990                 goto out_einval;
2991
2992         return 0;
2993
2994 out_einval:
2995         pr_warn("%s: bad traddr string\n", __func__);
2996         return -EINVAL;
2997 }
2998
2999 static struct nvme_ctrl *
3000 nvme_fc_create_ctrl(struct device *dev, struct nvmf_ctrl_options *opts)
3001 {
3002         struct nvme_fc_lport *lport;
3003         struct nvme_fc_rport *rport;
3004         struct nvme_ctrl *ctrl;
3005         struct nvmet_fc_traddr laddr = { 0L, 0L };
3006         struct nvmet_fc_traddr raddr = { 0L, 0L };
3007         unsigned long flags;
3008         int ret;
3009
3010         ret = nvme_fc_parse_traddr(&raddr, opts->traddr, NVMF_TRADDR_SIZE);
3011         if (ret || !raddr.nn || !raddr.pn)
3012                 return ERR_PTR(-EINVAL);
3013
3014         ret = nvme_fc_parse_traddr(&laddr, opts->host_traddr, NVMF_TRADDR_SIZE);
3015         if (ret || !laddr.nn || !laddr.pn)
3016                 return ERR_PTR(-EINVAL);
3017
3018         /* find the host and remote ports to connect together */
3019         spin_lock_irqsave(&nvme_fc_lock, flags);
3020         list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3021                 if (lport->localport.node_name != laddr.nn ||
3022                     lport->localport.port_name != laddr.pn)
3023                         continue;
3024
3025                 list_for_each_entry(rport, &lport->endp_list, endp_list) {
3026                         if (rport->remoteport.node_name != raddr.nn ||
3027                             rport->remoteport.port_name != raddr.pn)
3028                                 continue;
3029
3030                         /* if fail to get reference fall through. Will error */
3031                         if (!nvme_fc_rport_get(rport))
3032                                 break;
3033
3034                         spin_unlock_irqrestore(&nvme_fc_lock, flags);
3035
3036                         ctrl = nvme_fc_init_ctrl(dev, opts, lport, rport);
3037                         if (IS_ERR(ctrl))
3038                                 nvme_fc_rport_put(rport);
3039                         return ctrl;
3040                 }
3041         }
3042         spin_unlock_irqrestore(&nvme_fc_lock, flags);
3043
3044         return ERR_PTR(-ENOENT);
3045 }
3046
3047
3048 static struct nvmf_transport_ops nvme_fc_transport = {
3049         .name           = "fc",
3050         .required_opts  = NVMF_OPT_TRADDR | NVMF_OPT_HOST_TRADDR,
3051         .allowed_opts   = NVMF_OPT_RECONNECT_DELAY | NVMF_OPT_CTRL_LOSS_TMO,
3052         .create_ctrl    = nvme_fc_create_ctrl,
3053 };
3054
3055 static int __init nvme_fc_init_module(void)
3056 {
3057         int ret;
3058
3059         /*
3060          * NOTE:
3061          * It is expected that in the future the kernel will combine
3062          * the FC-isms that are currently under scsi and now being
3063          * added to by NVME into a new standalone FC class. The SCSI
3064          * and NVME protocols and their devices would be under this
3065          * new FC class.
3066          *
3067          * As we need something to post FC-specific udev events to,
3068          * specifically for nvme probe events, start by creating the
3069          * new device class.  When the new standalone FC class is
3070          * put in place, this code will move to a more generic
3071          * location for the class.
3072          */
3073         fc_class = class_create(THIS_MODULE, "fc");
3074         if (IS_ERR(fc_class)) {
3075                 pr_err("couldn't register class fc\n");
3076                 return PTR_ERR(fc_class);
3077         }
3078
3079         /*
3080          * Create a device for the FC-centric udev events
3081          */
3082         fc_udev_device = device_create(fc_class, NULL, MKDEV(0, 0), NULL,
3083                                 "fc_udev_device");
3084         if (IS_ERR(fc_udev_device)) {
3085                 pr_err("couldn't create fc_udev device!\n");
3086                 ret = PTR_ERR(fc_udev_device);
3087                 goto out_destroy_class;
3088         }
3089
3090         ret = nvmf_register_transport(&nvme_fc_transport);
3091         if (ret)
3092                 goto out_destroy_device;
3093
3094         return 0;
3095
3096 out_destroy_device:
3097         device_destroy(fc_class, MKDEV(0, 0));
3098 out_destroy_class:
3099         class_destroy(fc_class);
3100         return ret;
3101 }
3102
3103 static void __exit nvme_fc_exit_module(void)
3104 {
3105         /* sanity check - all lports should be removed */
3106         if (!list_empty(&nvme_fc_lport_list))
3107                 pr_warn("%s: localport list not empty\n", __func__);
3108
3109         nvmf_unregister_transport(&nvme_fc_transport);
3110
3111         ida_destroy(&nvme_fc_local_port_cnt);
3112         ida_destroy(&nvme_fc_ctrl_cnt);
3113
3114         device_destroy(fc_class, MKDEV(0, 0));
3115         class_destroy(fc_class);
3116 }
3117
3118 module_init(nvme_fc_init_module);
3119 module_exit(nvme_fc_exit_module);
3120
3121 MODULE_LICENSE("GPL v2");