108130f140d022fe727a8d6bc760e7b2f79e7583
[linux-2.6-microblaze.git] / drivers / nvme / host / fc.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2016 Avago Technologies.  All rights reserved.
4  */
5 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
6 #include <linux/module.h>
7 #include <linux/parser.h>
8 #include <uapi/scsi/fc/fc_fs.h>
9 #include <uapi/scsi/fc/fc_els.h>
10 #include <linux/delay.h>
11 #include <linux/overflow.h>
12
13 #include "nvme.h"
14 #include "fabrics.h"
15 #include <linux/nvme-fc-driver.h>
16 #include <linux/nvme-fc.h>
17 #include "fc.h"
18 #include <scsi/scsi_transport_fc.h>
19
20 /* *************************** Data Structures/Defines ****************** */
21
22
23 enum nvme_fc_queue_flags {
24         NVME_FC_Q_CONNECTED = 0,
25         NVME_FC_Q_LIVE,
26 };
27
28 #define NVME_FC_DEFAULT_DEV_LOSS_TMO    60      /* seconds */
29
30 struct nvme_fc_queue {
31         struct nvme_fc_ctrl     *ctrl;
32         struct device           *dev;
33         struct blk_mq_hw_ctx    *hctx;
34         void                    *lldd_handle;
35         size_t                  cmnd_capsule_len;
36         u32                     qnum;
37         u32                     rqcnt;
38         u32                     seqno;
39
40         u64                     connection_id;
41         atomic_t                csn;
42
43         unsigned long           flags;
44 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
45
46 enum nvme_fcop_flags {
47         FCOP_FLAGS_TERMIO       = (1 << 0),
48         FCOP_FLAGS_AEN          = (1 << 1),
49 };
50
51 struct nvmefc_ls_req_op {
52         struct nvmefc_ls_req    ls_req;
53
54         struct nvme_fc_rport    *rport;
55         struct nvme_fc_queue    *queue;
56         struct request          *rq;
57         u32                     flags;
58
59         int                     ls_error;
60         struct completion       ls_done;
61         struct list_head        lsreq_list;     /* rport->ls_req_list */
62         bool                    req_queued;
63 };
64
65 struct nvmefc_ls_rcv_op {
66         struct nvme_fc_rport            *rport;
67         struct nvmefc_ls_rsp            *lsrsp;
68         union nvmefc_ls_requests        *rqstbuf;
69         union nvmefc_ls_responses       *rspbuf;
70         u16                             rqstdatalen;
71         bool                            handled;
72         dma_addr_t                      rspdma;
73         struct list_head                lsrcv_list;     /* rport->ls_rcv_list */
74 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
75
76 enum nvme_fcpop_state {
77         FCPOP_STATE_UNINIT      = 0,
78         FCPOP_STATE_IDLE        = 1,
79         FCPOP_STATE_ACTIVE      = 2,
80         FCPOP_STATE_ABORTED     = 3,
81         FCPOP_STATE_COMPLETE    = 4,
82 };
83
84 struct nvme_fc_fcp_op {
85         struct nvme_request     nreq;           /*
86                                                  * nvme/host/core.c
87                                                  * requires this to be
88                                                  * the 1st element in the
89                                                  * private structure
90                                                  * associated with the
91                                                  * request.
92                                                  */
93         struct nvmefc_fcp_req   fcp_req;
94
95         struct nvme_fc_ctrl     *ctrl;
96         struct nvme_fc_queue    *queue;
97         struct request          *rq;
98
99         atomic_t                state;
100         u32                     flags;
101         u32                     rqno;
102         u32                     nents;
103
104         struct nvme_fc_cmd_iu   cmd_iu;
105         struct nvme_fc_ersp_iu  rsp_iu;
106 };
107
108 struct nvme_fcp_op_w_sgl {
109         struct nvme_fc_fcp_op   op;
110         struct scatterlist      sgl[NVME_INLINE_SG_CNT];
111         uint8_t                 priv[];
112 };
113
114 struct nvme_fc_lport {
115         struct nvme_fc_local_port       localport;
116
117         struct ida                      endp_cnt;
118         struct list_head                port_list;      /* nvme_fc_port_list */
119         struct list_head                endp_list;
120         struct device                   *dev;   /* physical device for dma */
121         struct nvme_fc_port_template    *ops;
122         struct kref                     ref;
123         atomic_t                        act_rport_cnt;
124 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
125
126 struct nvme_fc_rport {
127         struct nvme_fc_remote_port      remoteport;
128
129         struct list_head                endp_list; /* for lport->endp_list */
130         struct list_head                ctrl_list;
131         struct list_head                ls_req_list;
132         struct list_head                ls_rcv_list;
133         struct list_head                disc_list;
134         struct device                   *dev;   /* physical device for dma */
135         struct nvme_fc_lport            *lport;
136         spinlock_t                      lock;
137         struct kref                     ref;
138         atomic_t                        act_ctrl_cnt;
139         unsigned long                   dev_loss_end;
140         struct work_struct              lsrcv_work;
141 } __aligned(sizeof(u64));       /* alignment for other things alloc'd with */
142
143 /* fc_ctrl flags values - specified as bit positions */
144 #define ASSOC_ACTIVE            0
145 #define FCCTRL_TERMIO           1
146
147 struct nvme_fc_ctrl {
148         spinlock_t              lock;
149         struct nvme_fc_queue    *queues;
150         struct device           *dev;
151         struct nvme_fc_lport    *lport;
152         struct nvme_fc_rport    *rport;
153         u32                     cnum;
154
155         bool                    ioq_live;
156         atomic_t                err_work_active;
157         u64                     association_id;
158         struct nvmefc_ls_rcv_op *rcv_disconn;
159
160         struct list_head        ctrl_list;      /* rport->ctrl_list */
161
162         struct blk_mq_tag_set   admin_tag_set;
163         struct blk_mq_tag_set   tag_set;
164
165         struct delayed_work     connect_work;
166         struct work_struct      err_work;
167
168         struct kref             ref;
169         unsigned long           flags;
170         u32                     iocnt;
171         wait_queue_head_t       ioabort_wait;
172
173         struct nvme_fc_fcp_op   aen_ops[NVME_NR_AEN_COMMANDS];
174
175         struct nvme_ctrl        ctrl;
176 };
177
178 static inline struct nvme_fc_ctrl *
179 to_fc_ctrl(struct nvme_ctrl *ctrl)
180 {
181         return container_of(ctrl, struct nvme_fc_ctrl, ctrl);
182 }
183
184 static inline struct nvme_fc_lport *
185 localport_to_lport(struct nvme_fc_local_port *portptr)
186 {
187         return container_of(portptr, struct nvme_fc_lport, localport);
188 }
189
190 static inline struct nvme_fc_rport *
191 remoteport_to_rport(struct nvme_fc_remote_port *portptr)
192 {
193         return container_of(portptr, struct nvme_fc_rport, remoteport);
194 }
195
196 static inline struct nvmefc_ls_req_op *
197 ls_req_to_lsop(struct nvmefc_ls_req *lsreq)
198 {
199         return container_of(lsreq, struct nvmefc_ls_req_op, ls_req);
200 }
201
202 static inline struct nvme_fc_fcp_op *
203 fcp_req_to_fcp_op(struct nvmefc_fcp_req *fcpreq)
204 {
205         return container_of(fcpreq, struct nvme_fc_fcp_op, fcp_req);
206 }
207
208
209
210 /* *************************** Globals **************************** */
211
212
213 static DEFINE_SPINLOCK(nvme_fc_lock);
214
215 static LIST_HEAD(nvme_fc_lport_list);
216 static DEFINE_IDA(nvme_fc_local_port_cnt);
217 static DEFINE_IDA(nvme_fc_ctrl_cnt);
218
219 static struct workqueue_struct *nvme_fc_wq;
220
221 static bool nvme_fc_waiting_to_unload;
222 static DECLARE_COMPLETION(nvme_fc_unload_proceed);
223
224 /*
225  * These items are short-term. They will eventually be moved into
226  * a generic FC class. See comments in module init.
227  */
228 static struct device *fc_udev_device;
229
230 static void nvme_fc_complete_rq(struct request *rq);
231
232 /* *********************** FC-NVME Port Management ************************ */
233
234 static void __nvme_fc_delete_hw_queue(struct nvme_fc_ctrl *,
235                         struct nvme_fc_queue *, unsigned int);
236
237 static void nvme_fc_handle_ls_rqst_work(struct work_struct *work);
238
239
240 static void
241 nvme_fc_free_lport(struct kref *ref)
242 {
243         struct nvme_fc_lport *lport =
244                 container_of(ref, struct nvme_fc_lport, ref);
245         unsigned long flags;
246
247         WARN_ON(lport->localport.port_state != FC_OBJSTATE_DELETED);
248         WARN_ON(!list_empty(&lport->endp_list));
249
250         /* remove from transport list */
251         spin_lock_irqsave(&nvme_fc_lock, flags);
252         list_del(&lport->port_list);
253         if (nvme_fc_waiting_to_unload && list_empty(&nvme_fc_lport_list))
254                 complete(&nvme_fc_unload_proceed);
255         spin_unlock_irqrestore(&nvme_fc_lock, flags);
256
257         ida_simple_remove(&nvme_fc_local_port_cnt, lport->localport.port_num);
258         ida_destroy(&lport->endp_cnt);
259
260         put_device(lport->dev);
261
262         kfree(lport);
263 }
264
265 static void
266 nvme_fc_lport_put(struct nvme_fc_lport *lport)
267 {
268         kref_put(&lport->ref, nvme_fc_free_lport);
269 }
270
271 static int
272 nvme_fc_lport_get(struct nvme_fc_lport *lport)
273 {
274         return kref_get_unless_zero(&lport->ref);
275 }
276
277
278 static struct nvme_fc_lport *
279 nvme_fc_attach_to_unreg_lport(struct nvme_fc_port_info *pinfo,
280                         struct nvme_fc_port_template *ops,
281                         struct device *dev)
282 {
283         struct nvme_fc_lport *lport;
284         unsigned long flags;
285
286         spin_lock_irqsave(&nvme_fc_lock, flags);
287
288         list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
289                 if (lport->localport.node_name != pinfo->node_name ||
290                     lport->localport.port_name != pinfo->port_name)
291                         continue;
292
293                 if (lport->dev != dev) {
294                         lport = ERR_PTR(-EXDEV);
295                         goto out_done;
296                 }
297
298                 if (lport->localport.port_state != FC_OBJSTATE_DELETED) {
299                         lport = ERR_PTR(-EEXIST);
300                         goto out_done;
301                 }
302
303                 if (!nvme_fc_lport_get(lport)) {
304                         /*
305                          * fails if ref cnt already 0. If so,
306                          * act as if lport already deleted
307                          */
308                         lport = NULL;
309                         goto out_done;
310                 }
311
312                 /* resume the lport */
313
314                 lport->ops = ops;
315                 lport->localport.port_role = pinfo->port_role;
316                 lport->localport.port_id = pinfo->port_id;
317                 lport->localport.port_state = FC_OBJSTATE_ONLINE;
318
319                 spin_unlock_irqrestore(&nvme_fc_lock, flags);
320
321                 return lport;
322         }
323
324         lport = NULL;
325
326 out_done:
327         spin_unlock_irqrestore(&nvme_fc_lock, flags);
328
329         return lport;
330 }
331
332 /**
333  * nvme_fc_register_localport - transport entry point called by an
334  *                              LLDD to register the existence of a NVME
335  *                              host FC port.
336  * @pinfo:     pointer to information about the port to be registered
337  * @template:  LLDD entrypoints and operational parameters for the port
338  * @dev:       physical hardware device node port corresponds to. Will be
339  *             used for DMA mappings
340  * @portptr:   pointer to a local port pointer. Upon success, the routine
341  *             will allocate a nvme_fc_local_port structure and place its
342  *             address in the local port pointer. Upon failure, local port
343  *             pointer will be set to 0.
344  *
345  * Returns:
346  * a completion status. Must be 0 upon success; a negative errno
347  * (ex: -ENXIO) upon failure.
348  */
349 int
350 nvme_fc_register_localport(struct nvme_fc_port_info *pinfo,
351                         struct nvme_fc_port_template *template,
352                         struct device *dev,
353                         struct nvme_fc_local_port **portptr)
354 {
355         struct nvme_fc_lport *newrec;
356         unsigned long flags;
357         int ret, idx;
358
359         if (!template->localport_delete || !template->remoteport_delete ||
360             !template->ls_req || !template->fcp_io ||
361             !template->ls_abort || !template->fcp_abort ||
362             !template->max_hw_queues || !template->max_sgl_segments ||
363             !template->max_dif_sgl_segments || !template->dma_boundary) {
364                 ret = -EINVAL;
365                 goto out_reghost_failed;
366         }
367
368         /*
369          * look to see if there is already a localport that had been
370          * deregistered and in the process of waiting for all the
371          * references to fully be removed.  If the references haven't
372          * expired, we can simply re-enable the localport. Remoteports
373          * and controller reconnections should resume naturally.
374          */
375         newrec = nvme_fc_attach_to_unreg_lport(pinfo, template, dev);
376
377         /* found an lport, but something about its state is bad */
378         if (IS_ERR(newrec)) {
379                 ret = PTR_ERR(newrec);
380                 goto out_reghost_failed;
381
382         /* found existing lport, which was resumed */
383         } else if (newrec) {
384                 *portptr = &newrec->localport;
385                 return 0;
386         }
387
388         /* nothing found - allocate a new localport struct */
389
390         newrec = kmalloc((sizeof(*newrec) + template->local_priv_sz),
391                          GFP_KERNEL);
392         if (!newrec) {
393                 ret = -ENOMEM;
394                 goto out_reghost_failed;
395         }
396
397         idx = ida_simple_get(&nvme_fc_local_port_cnt, 0, 0, GFP_KERNEL);
398         if (idx < 0) {
399                 ret = -ENOSPC;
400                 goto out_fail_kfree;
401         }
402
403         if (!get_device(dev) && dev) {
404                 ret = -ENODEV;
405                 goto out_ida_put;
406         }
407
408         INIT_LIST_HEAD(&newrec->port_list);
409         INIT_LIST_HEAD(&newrec->endp_list);
410         kref_init(&newrec->ref);
411         atomic_set(&newrec->act_rport_cnt, 0);
412         newrec->ops = template;
413         newrec->dev = dev;
414         ida_init(&newrec->endp_cnt);
415         if (template->local_priv_sz)
416                 newrec->localport.private = &newrec[1];
417         else
418                 newrec->localport.private = NULL;
419         newrec->localport.node_name = pinfo->node_name;
420         newrec->localport.port_name = pinfo->port_name;
421         newrec->localport.port_role = pinfo->port_role;
422         newrec->localport.port_id = pinfo->port_id;
423         newrec->localport.port_state = FC_OBJSTATE_ONLINE;
424         newrec->localport.port_num = idx;
425
426         spin_lock_irqsave(&nvme_fc_lock, flags);
427         list_add_tail(&newrec->port_list, &nvme_fc_lport_list);
428         spin_unlock_irqrestore(&nvme_fc_lock, flags);
429
430         if (dev)
431                 dma_set_seg_boundary(dev, template->dma_boundary);
432
433         *portptr = &newrec->localport;
434         return 0;
435
436 out_ida_put:
437         ida_simple_remove(&nvme_fc_local_port_cnt, idx);
438 out_fail_kfree:
439         kfree(newrec);
440 out_reghost_failed:
441         *portptr = NULL;
442
443         return ret;
444 }
445 EXPORT_SYMBOL_GPL(nvme_fc_register_localport);
446
447 /**
448  * nvme_fc_unregister_localport - transport entry point called by an
449  *                              LLDD to deregister/remove a previously
450  *                              registered a NVME host FC port.
451  * @portptr: pointer to the (registered) local port that is to be deregistered.
452  *
453  * Returns:
454  * a completion status. Must be 0 upon success; a negative errno
455  * (ex: -ENXIO) upon failure.
456  */
457 int
458 nvme_fc_unregister_localport(struct nvme_fc_local_port *portptr)
459 {
460         struct nvme_fc_lport *lport = localport_to_lport(portptr);
461         unsigned long flags;
462
463         if (!portptr)
464                 return -EINVAL;
465
466         spin_lock_irqsave(&nvme_fc_lock, flags);
467
468         if (portptr->port_state != FC_OBJSTATE_ONLINE) {
469                 spin_unlock_irqrestore(&nvme_fc_lock, flags);
470                 return -EINVAL;
471         }
472         portptr->port_state = FC_OBJSTATE_DELETED;
473
474         spin_unlock_irqrestore(&nvme_fc_lock, flags);
475
476         if (atomic_read(&lport->act_rport_cnt) == 0)
477                 lport->ops->localport_delete(&lport->localport);
478
479         nvme_fc_lport_put(lport);
480
481         return 0;
482 }
483 EXPORT_SYMBOL_GPL(nvme_fc_unregister_localport);
484
485 /*
486  * TRADDR strings, per FC-NVME are fixed format:
487  *   "nn-0x<16hexdigits>:pn-0x<16hexdigits>" - 43 characters
488  * udev event will only differ by prefix of what field is
489  * being specified:
490  *    "NVMEFC_HOST_TRADDR=" or "NVMEFC_TRADDR=" - 19 max characters
491  *  19 + 43 + null_fudge = 64 characters
492  */
493 #define FCNVME_TRADDR_LENGTH            64
494
495 static void
496 nvme_fc_signal_discovery_scan(struct nvme_fc_lport *lport,
497                 struct nvme_fc_rport *rport)
498 {
499         char hostaddr[FCNVME_TRADDR_LENGTH];    /* NVMEFC_HOST_TRADDR=...*/
500         char tgtaddr[FCNVME_TRADDR_LENGTH];     /* NVMEFC_TRADDR=...*/
501         char *envp[4] = { "FC_EVENT=nvmediscovery", hostaddr, tgtaddr, NULL };
502
503         if (!(rport->remoteport.port_role & FC_PORT_ROLE_NVME_DISCOVERY))
504                 return;
505
506         snprintf(hostaddr, sizeof(hostaddr),
507                 "NVMEFC_HOST_TRADDR=nn-0x%016llx:pn-0x%016llx",
508                 lport->localport.node_name, lport->localport.port_name);
509         snprintf(tgtaddr, sizeof(tgtaddr),
510                 "NVMEFC_TRADDR=nn-0x%016llx:pn-0x%016llx",
511                 rport->remoteport.node_name, rport->remoteport.port_name);
512         kobject_uevent_env(&fc_udev_device->kobj, KOBJ_CHANGE, envp);
513 }
514
515 static void
516 nvme_fc_free_rport(struct kref *ref)
517 {
518         struct nvme_fc_rport *rport =
519                 container_of(ref, struct nvme_fc_rport, ref);
520         struct nvme_fc_lport *lport =
521                         localport_to_lport(rport->remoteport.localport);
522         unsigned long flags;
523
524         WARN_ON(rport->remoteport.port_state != FC_OBJSTATE_DELETED);
525         WARN_ON(!list_empty(&rport->ctrl_list));
526
527         /* remove from lport list */
528         spin_lock_irqsave(&nvme_fc_lock, flags);
529         list_del(&rport->endp_list);
530         spin_unlock_irqrestore(&nvme_fc_lock, flags);
531
532         WARN_ON(!list_empty(&rport->disc_list));
533         ida_simple_remove(&lport->endp_cnt, rport->remoteport.port_num);
534
535         kfree(rport);
536
537         nvme_fc_lport_put(lport);
538 }
539
540 static void
541 nvme_fc_rport_put(struct nvme_fc_rport *rport)
542 {
543         kref_put(&rport->ref, nvme_fc_free_rport);
544 }
545
546 static int
547 nvme_fc_rport_get(struct nvme_fc_rport *rport)
548 {
549         return kref_get_unless_zero(&rport->ref);
550 }
551
552 static void
553 nvme_fc_resume_controller(struct nvme_fc_ctrl *ctrl)
554 {
555         switch (ctrl->ctrl.state) {
556         case NVME_CTRL_NEW:
557         case NVME_CTRL_CONNECTING:
558                 /*
559                  * As all reconnects were suppressed, schedule a
560                  * connect.
561                  */
562                 dev_info(ctrl->ctrl.device,
563                         "NVME-FC{%d}: connectivity re-established. "
564                         "Attempting reconnect\n", ctrl->cnum);
565
566                 queue_delayed_work(nvme_wq, &ctrl->connect_work, 0);
567                 break;
568
569         case NVME_CTRL_RESETTING:
570                 /*
571                  * Controller is already in the process of terminating the
572                  * association. No need to do anything further. The reconnect
573                  * step will naturally occur after the reset completes.
574                  */
575                 break;
576
577         default:
578                 /* no action to take - let it delete */
579                 break;
580         }
581 }
582
583 static struct nvme_fc_rport *
584 nvme_fc_attach_to_suspended_rport(struct nvme_fc_lport *lport,
585                                 struct nvme_fc_port_info *pinfo)
586 {
587         struct nvme_fc_rport *rport;
588         struct nvme_fc_ctrl *ctrl;
589         unsigned long flags;
590
591         spin_lock_irqsave(&nvme_fc_lock, flags);
592
593         list_for_each_entry(rport, &lport->endp_list, endp_list) {
594                 if (rport->remoteport.node_name != pinfo->node_name ||
595                     rport->remoteport.port_name != pinfo->port_name)
596                         continue;
597
598                 if (!nvme_fc_rport_get(rport)) {
599                         rport = ERR_PTR(-ENOLCK);
600                         goto out_done;
601                 }
602
603                 spin_unlock_irqrestore(&nvme_fc_lock, flags);
604
605                 spin_lock_irqsave(&rport->lock, flags);
606
607                 /* has it been unregistered */
608                 if (rport->remoteport.port_state != FC_OBJSTATE_DELETED) {
609                         /* means lldd called us twice */
610                         spin_unlock_irqrestore(&rport->lock, flags);
611                         nvme_fc_rport_put(rport);
612                         return ERR_PTR(-ESTALE);
613                 }
614
615                 rport->remoteport.port_role = pinfo->port_role;
616                 rport->remoteport.port_id = pinfo->port_id;
617                 rport->remoteport.port_state = FC_OBJSTATE_ONLINE;
618                 rport->dev_loss_end = 0;
619
620                 /*
621                  * kick off a reconnect attempt on all associations to the
622                  * remote port. A successful reconnects will resume i/o.
623                  */
624                 list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list)
625                         nvme_fc_resume_controller(ctrl);
626
627                 spin_unlock_irqrestore(&rport->lock, flags);
628
629                 return rport;
630         }
631
632         rport = NULL;
633
634 out_done:
635         spin_unlock_irqrestore(&nvme_fc_lock, flags);
636
637         return rport;
638 }
639
640 static inline void
641 __nvme_fc_set_dev_loss_tmo(struct nvme_fc_rport *rport,
642                         struct nvme_fc_port_info *pinfo)
643 {
644         if (pinfo->dev_loss_tmo)
645                 rport->remoteport.dev_loss_tmo = pinfo->dev_loss_tmo;
646         else
647                 rport->remoteport.dev_loss_tmo = NVME_FC_DEFAULT_DEV_LOSS_TMO;
648 }
649
650 /**
651  * nvme_fc_register_remoteport - transport entry point called by an
652  *                              LLDD to register the existence of a NVME
653  *                              subsystem FC port on its fabric.
654  * @localport: pointer to the (registered) local port that the remote
655  *             subsystem port is connected to.
656  * @pinfo:     pointer to information about the port to be registered
657  * @portptr:   pointer to a remote port pointer. Upon success, the routine
658  *             will allocate a nvme_fc_remote_port structure and place its
659  *             address in the remote port pointer. Upon failure, remote port
660  *             pointer will be set to 0.
661  *
662  * Returns:
663  * a completion status. Must be 0 upon success; a negative errno
664  * (ex: -ENXIO) upon failure.
665  */
666 int
667 nvme_fc_register_remoteport(struct nvme_fc_local_port *localport,
668                                 struct nvme_fc_port_info *pinfo,
669                                 struct nvme_fc_remote_port **portptr)
670 {
671         struct nvme_fc_lport *lport = localport_to_lport(localport);
672         struct nvme_fc_rport *newrec;
673         unsigned long flags;
674         int ret, idx;
675
676         if (!nvme_fc_lport_get(lport)) {
677                 ret = -ESHUTDOWN;
678                 goto out_reghost_failed;
679         }
680
681         /*
682          * look to see if there is already a remoteport that is waiting
683          * for a reconnect (within dev_loss_tmo) with the same WWN's.
684          * If so, transition to it and reconnect.
685          */
686         newrec = nvme_fc_attach_to_suspended_rport(lport, pinfo);
687
688         /* found an rport, but something about its state is bad */
689         if (IS_ERR(newrec)) {
690                 ret = PTR_ERR(newrec);
691                 goto out_lport_put;
692
693         /* found existing rport, which was resumed */
694         } else if (newrec) {
695                 nvme_fc_lport_put(lport);
696                 __nvme_fc_set_dev_loss_tmo(newrec, pinfo);
697                 nvme_fc_signal_discovery_scan(lport, newrec);
698                 *portptr = &newrec->remoteport;
699                 return 0;
700         }
701
702         /* nothing found - allocate a new remoteport struct */
703
704         newrec = kmalloc((sizeof(*newrec) + lport->ops->remote_priv_sz),
705                          GFP_KERNEL);
706         if (!newrec) {
707                 ret = -ENOMEM;
708                 goto out_lport_put;
709         }
710
711         idx = ida_simple_get(&lport->endp_cnt, 0, 0, GFP_KERNEL);
712         if (idx < 0) {
713                 ret = -ENOSPC;
714                 goto out_kfree_rport;
715         }
716
717         INIT_LIST_HEAD(&newrec->endp_list);
718         INIT_LIST_HEAD(&newrec->ctrl_list);
719         INIT_LIST_HEAD(&newrec->ls_req_list);
720         INIT_LIST_HEAD(&newrec->disc_list);
721         kref_init(&newrec->ref);
722         atomic_set(&newrec->act_ctrl_cnt, 0);
723         spin_lock_init(&newrec->lock);
724         newrec->remoteport.localport = &lport->localport;
725         INIT_LIST_HEAD(&newrec->ls_rcv_list);
726         newrec->dev = lport->dev;
727         newrec->lport = lport;
728         if (lport->ops->remote_priv_sz)
729                 newrec->remoteport.private = &newrec[1];
730         else
731                 newrec->remoteport.private = NULL;
732         newrec->remoteport.port_role = pinfo->port_role;
733         newrec->remoteport.node_name = pinfo->node_name;
734         newrec->remoteport.port_name = pinfo->port_name;
735         newrec->remoteport.port_id = pinfo->port_id;
736         newrec->remoteport.port_state = FC_OBJSTATE_ONLINE;
737         newrec->remoteport.port_num = idx;
738         __nvme_fc_set_dev_loss_tmo(newrec, pinfo);
739         INIT_WORK(&newrec->lsrcv_work, nvme_fc_handle_ls_rqst_work);
740
741         spin_lock_irqsave(&nvme_fc_lock, flags);
742         list_add_tail(&newrec->endp_list, &lport->endp_list);
743         spin_unlock_irqrestore(&nvme_fc_lock, flags);
744
745         nvme_fc_signal_discovery_scan(lport, newrec);
746
747         *portptr = &newrec->remoteport;
748         return 0;
749
750 out_kfree_rport:
751         kfree(newrec);
752 out_lport_put:
753         nvme_fc_lport_put(lport);
754 out_reghost_failed:
755         *portptr = NULL;
756         return ret;
757 }
758 EXPORT_SYMBOL_GPL(nvme_fc_register_remoteport);
759
760 static int
761 nvme_fc_abort_lsops(struct nvme_fc_rport *rport)
762 {
763         struct nvmefc_ls_req_op *lsop;
764         unsigned long flags;
765
766 restart:
767         spin_lock_irqsave(&rport->lock, flags);
768
769         list_for_each_entry(lsop, &rport->ls_req_list, lsreq_list) {
770                 if (!(lsop->flags & FCOP_FLAGS_TERMIO)) {
771                         lsop->flags |= FCOP_FLAGS_TERMIO;
772                         spin_unlock_irqrestore(&rport->lock, flags);
773                         rport->lport->ops->ls_abort(&rport->lport->localport,
774                                                 &rport->remoteport,
775                                                 &lsop->ls_req);
776                         goto restart;
777                 }
778         }
779         spin_unlock_irqrestore(&rport->lock, flags);
780
781         return 0;
782 }
783
784 static void
785 nvme_fc_ctrl_connectivity_loss(struct nvme_fc_ctrl *ctrl)
786 {
787         dev_info(ctrl->ctrl.device,
788                 "NVME-FC{%d}: controller connectivity lost. Awaiting "
789                 "Reconnect", ctrl->cnum);
790
791         switch (ctrl->ctrl.state) {
792         case NVME_CTRL_NEW:
793         case NVME_CTRL_LIVE:
794                 /*
795                  * Schedule a controller reset. The reset will terminate the
796                  * association and schedule the reconnect timer.  Reconnects
797                  * will be attempted until either the ctlr_loss_tmo
798                  * (max_retries * connect_delay) expires or the remoteport's
799                  * dev_loss_tmo expires.
800                  */
801                 if (nvme_reset_ctrl(&ctrl->ctrl)) {
802                         dev_warn(ctrl->ctrl.device,
803                                 "NVME-FC{%d}: Couldn't schedule reset.\n",
804                                 ctrl->cnum);
805                         nvme_delete_ctrl(&ctrl->ctrl);
806                 }
807                 break;
808
809         case NVME_CTRL_CONNECTING:
810                 /*
811                  * The association has already been terminated and the
812                  * controller is attempting reconnects.  No need to do anything
813                  * futher.  Reconnects will be attempted until either the
814                  * ctlr_loss_tmo (max_retries * connect_delay) expires or the
815                  * remoteport's dev_loss_tmo expires.
816                  */
817                 break;
818
819         case NVME_CTRL_RESETTING:
820                 /*
821                  * Controller is already in the process of terminating the
822                  * association.  No need to do anything further. The reconnect
823                  * step will kick in naturally after the association is
824                  * terminated.
825                  */
826                 break;
827
828         case NVME_CTRL_DELETING:
829         case NVME_CTRL_DELETING_NOIO:
830         default:
831                 /* no action to take - let it delete */
832                 break;
833         }
834 }
835
836 /**
837  * nvme_fc_unregister_remoteport - transport entry point called by an
838  *                              LLDD to deregister/remove a previously
839  *                              registered a NVME subsystem FC port.
840  * @portptr: pointer to the (registered) remote port that is to be
841  *           deregistered.
842  *
843  * Returns:
844  * a completion status. Must be 0 upon success; a negative errno
845  * (ex: -ENXIO) upon failure.
846  */
847 int
848 nvme_fc_unregister_remoteport(struct nvme_fc_remote_port *portptr)
849 {
850         struct nvme_fc_rport *rport = remoteport_to_rport(portptr);
851         struct nvme_fc_ctrl *ctrl;
852         unsigned long flags;
853
854         if (!portptr)
855                 return -EINVAL;
856
857         spin_lock_irqsave(&rport->lock, flags);
858
859         if (portptr->port_state != FC_OBJSTATE_ONLINE) {
860                 spin_unlock_irqrestore(&rport->lock, flags);
861                 return -EINVAL;
862         }
863         portptr->port_state = FC_OBJSTATE_DELETED;
864
865         rport->dev_loss_end = jiffies + (portptr->dev_loss_tmo * HZ);
866
867         list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list) {
868                 /* if dev_loss_tmo==0, dev loss is immediate */
869                 if (!portptr->dev_loss_tmo) {
870                         dev_warn(ctrl->ctrl.device,
871                                 "NVME-FC{%d}: controller connectivity lost.\n",
872                                 ctrl->cnum);
873                         nvme_delete_ctrl(&ctrl->ctrl);
874                 } else
875                         nvme_fc_ctrl_connectivity_loss(ctrl);
876         }
877
878         spin_unlock_irqrestore(&rport->lock, flags);
879
880         nvme_fc_abort_lsops(rport);
881
882         if (atomic_read(&rport->act_ctrl_cnt) == 0)
883                 rport->lport->ops->remoteport_delete(portptr);
884
885         /*
886          * release the reference, which will allow, if all controllers
887          * go away, which should only occur after dev_loss_tmo occurs,
888          * for the rport to be torn down.
889          */
890         nvme_fc_rport_put(rport);
891
892         return 0;
893 }
894 EXPORT_SYMBOL_GPL(nvme_fc_unregister_remoteport);
895
896 /**
897  * nvme_fc_rescan_remoteport - transport entry point called by an
898  *                              LLDD to request a nvme device rescan.
899  * @remoteport: pointer to the (registered) remote port that is to be
900  *              rescanned.
901  *
902  * Returns: N/A
903  */
904 void
905 nvme_fc_rescan_remoteport(struct nvme_fc_remote_port *remoteport)
906 {
907         struct nvme_fc_rport *rport = remoteport_to_rport(remoteport);
908
909         nvme_fc_signal_discovery_scan(rport->lport, rport);
910 }
911 EXPORT_SYMBOL_GPL(nvme_fc_rescan_remoteport);
912
913 int
914 nvme_fc_set_remoteport_devloss(struct nvme_fc_remote_port *portptr,
915                         u32 dev_loss_tmo)
916 {
917         struct nvme_fc_rport *rport = remoteport_to_rport(portptr);
918         unsigned long flags;
919
920         spin_lock_irqsave(&rport->lock, flags);
921
922         if (portptr->port_state != FC_OBJSTATE_ONLINE) {
923                 spin_unlock_irqrestore(&rport->lock, flags);
924                 return -EINVAL;
925         }
926
927         /* a dev_loss_tmo of 0 (immediate) is allowed to be set */
928         rport->remoteport.dev_loss_tmo = dev_loss_tmo;
929
930         spin_unlock_irqrestore(&rport->lock, flags);
931
932         return 0;
933 }
934 EXPORT_SYMBOL_GPL(nvme_fc_set_remoteport_devloss);
935
936
937 /* *********************** FC-NVME DMA Handling **************************** */
938
939 /*
940  * The fcloop device passes in a NULL device pointer. Real LLD's will
941  * pass in a valid device pointer. If NULL is passed to the dma mapping
942  * routines, depending on the platform, it may or may not succeed, and
943  * may crash.
944  *
945  * As such:
946  * Wrapper all the dma routines and check the dev pointer.
947  *
948  * If simple mappings (return just a dma address, we'll noop them,
949  * returning a dma address of 0.
950  *
951  * On more complex mappings (dma_map_sg), a pseudo routine fills
952  * in the scatter list, setting all dma addresses to 0.
953  */
954
955 static inline dma_addr_t
956 fc_dma_map_single(struct device *dev, void *ptr, size_t size,
957                 enum dma_data_direction dir)
958 {
959         return dev ? dma_map_single(dev, ptr, size, dir) : (dma_addr_t)0L;
960 }
961
962 static inline int
963 fc_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
964 {
965         return dev ? dma_mapping_error(dev, dma_addr) : 0;
966 }
967
968 static inline void
969 fc_dma_unmap_single(struct device *dev, dma_addr_t addr, size_t size,
970         enum dma_data_direction dir)
971 {
972         if (dev)
973                 dma_unmap_single(dev, addr, size, dir);
974 }
975
976 static inline void
977 fc_dma_sync_single_for_cpu(struct device *dev, dma_addr_t addr, size_t size,
978                 enum dma_data_direction dir)
979 {
980         if (dev)
981                 dma_sync_single_for_cpu(dev, addr, size, dir);
982 }
983
984 static inline void
985 fc_dma_sync_single_for_device(struct device *dev, dma_addr_t addr, size_t size,
986                 enum dma_data_direction dir)
987 {
988         if (dev)
989                 dma_sync_single_for_device(dev, addr, size, dir);
990 }
991
992 /* pseudo dma_map_sg call */
993 static int
994 fc_map_sg(struct scatterlist *sg, int nents)
995 {
996         struct scatterlist *s;
997         int i;
998
999         WARN_ON(nents == 0 || sg[0].length == 0);
1000
1001         for_each_sg(sg, s, nents, i) {
1002                 s->dma_address = 0L;
1003 #ifdef CONFIG_NEED_SG_DMA_LENGTH
1004                 s->dma_length = s->length;
1005 #endif
1006         }
1007         return nents;
1008 }
1009
1010 static inline int
1011 fc_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
1012                 enum dma_data_direction dir)
1013 {
1014         return dev ? dma_map_sg(dev, sg, nents, dir) : fc_map_sg(sg, nents);
1015 }
1016
1017 static inline void
1018 fc_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
1019                 enum dma_data_direction dir)
1020 {
1021         if (dev)
1022                 dma_unmap_sg(dev, sg, nents, dir);
1023 }
1024
1025 /* *********************** FC-NVME LS Handling **************************** */
1026
1027 static void nvme_fc_ctrl_put(struct nvme_fc_ctrl *);
1028 static int nvme_fc_ctrl_get(struct nvme_fc_ctrl *);
1029
1030 static void nvme_fc_error_recovery(struct nvme_fc_ctrl *ctrl, char *errmsg);
1031
1032 static void
1033 __nvme_fc_finish_ls_req(struct nvmefc_ls_req_op *lsop)
1034 {
1035         struct nvme_fc_rport *rport = lsop->rport;
1036         struct nvmefc_ls_req *lsreq = &lsop->ls_req;
1037         unsigned long flags;
1038
1039         spin_lock_irqsave(&rport->lock, flags);
1040
1041         if (!lsop->req_queued) {
1042                 spin_unlock_irqrestore(&rport->lock, flags);
1043                 return;
1044         }
1045
1046         list_del(&lsop->lsreq_list);
1047
1048         lsop->req_queued = false;
1049
1050         spin_unlock_irqrestore(&rport->lock, flags);
1051
1052         fc_dma_unmap_single(rport->dev, lsreq->rqstdma,
1053                                   (lsreq->rqstlen + lsreq->rsplen),
1054                                   DMA_BIDIRECTIONAL);
1055
1056         nvme_fc_rport_put(rport);
1057 }
1058
1059 static int
1060 __nvme_fc_send_ls_req(struct nvme_fc_rport *rport,
1061                 struct nvmefc_ls_req_op *lsop,
1062                 void (*done)(struct nvmefc_ls_req *req, int status))
1063 {
1064         struct nvmefc_ls_req *lsreq = &lsop->ls_req;
1065         unsigned long flags;
1066         int ret = 0;
1067
1068         if (rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
1069                 return -ECONNREFUSED;
1070
1071         if (!nvme_fc_rport_get(rport))
1072                 return -ESHUTDOWN;
1073
1074         lsreq->done = done;
1075         lsop->rport = rport;
1076         lsop->req_queued = false;
1077         INIT_LIST_HEAD(&lsop->lsreq_list);
1078         init_completion(&lsop->ls_done);
1079
1080         lsreq->rqstdma = fc_dma_map_single(rport->dev, lsreq->rqstaddr,
1081                                   lsreq->rqstlen + lsreq->rsplen,
1082                                   DMA_BIDIRECTIONAL);
1083         if (fc_dma_mapping_error(rport->dev, lsreq->rqstdma)) {
1084                 ret = -EFAULT;
1085                 goto out_putrport;
1086         }
1087         lsreq->rspdma = lsreq->rqstdma + lsreq->rqstlen;
1088
1089         spin_lock_irqsave(&rport->lock, flags);
1090
1091         list_add_tail(&lsop->lsreq_list, &rport->ls_req_list);
1092
1093         lsop->req_queued = true;
1094
1095         spin_unlock_irqrestore(&rport->lock, flags);
1096
1097         ret = rport->lport->ops->ls_req(&rport->lport->localport,
1098                                         &rport->remoteport, lsreq);
1099         if (ret)
1100                 goto out_unlink;
1101
1102         return 0;
1103
1104 out_unlink:
1105         lsop->ls_error = ret;
1106         spin_lock_irqsave(&rport->lock, flags);
1107         lsop->req_queued = false;
1108         list_del(&lsop->lsreq_list);
1109         spin_unlock_irqrestore(&rport->lock, flags);
1110         fc_dma_unmap_single(rport->dev, lsreq->rqstdma,
1111                                   (lsreq->rqstlen + lsreq->rsplen),
1112                                   DMA_BIDIRECTIONAL);
1113 out_putrport:
1114         nvme_fc_rport_put(rport);
1115
1116         return ret;
1117 }
1118
1119 static void
1120 nvme_fc_send_ls_req_done(struct nvmefc_ls_req *lsreq, int status)
1121 {
1122         struct nvmefc_ls_req_op *lsop = ls_req_to_lsop(lsreq);
1123
1124         lsop->ls_error = status;
1125         complete(&lsop->ls_done);
1126 }
1127
1128 static int
1129 nvme_fc_send_ls_req(struct nvme_fc_rport *rport, struct nvmefc_ls_req_op *lsop)
1130 {
1131         struct nvmefc_ls_req *lsreq = &lsop->ls_req;
1132         struct fcnvme_ls_rjt *rjt = lsreq->rspaddr;
1133         int ret;
1134
1135         ret = __nvme_fc_send_ls_req(rport, lsop, nvme_fc_send_ls_req_done);
1136
1137         if (!ret) {
1138                 /*
1139                  * No timeout/not interruptible as we need the struct
1140                  * to exist until the lldd calls us back. Thus mandate
1141                  * wait until driver calls back. lldd responsible for
1142                  * the timeout action
1143                  */
1144                 wait_for_completion(&lsop->ls_done);
1145
1146                 __nvme_fc_finish_ls_req(lsop);
1147
1148                 ret = lsop->ls_error;
1149         }
1150
1151         if (ret)
1152                 return ret;
1153
1154         /* ACC or RJT payload ? */
1155         if (rjt->w0.ls_cmd == FCNVME_LS_RJT)
1156                 return -ENXIO;
1157
1158         return 0;
1159 }
1160
1161 static int
1162 nvme_fc_send_ls_req_async(struct nvme_fc_rport *rport,
1163                 struct nvmefc_ls_req_op *lsop,
1164                 void (*done)(struct nvmefc_ls_req *req, int status))
1165 {
1166         /* don't wait for completion */
1167
1168         return __nvme_fc_send_ls_req(rport, lsop, done);
1169 }
1170
1171 static int
1172 nvme_fc_connect_admin_queue(struct nvme_fc_ctrl *ctrl,
1173         struct nvme_fc_queue *queue, u16 qsize, u16 ersp_ratio)
1174 {
1175         struct nvmefc_ls_req_op *lsop;
1176         struct nvmefc_ls_req *lsreq;
1177         struct fcnvme_ls_cr_assoc_rqst *assoc_rqst;
1178         struct fcnvme_ls_cr_assoc_acc *assoc_acc;
1179         unsigned long flags;
1180         int ret, fcret = 0;
1181
1182         lsop = kzalloc((sizeof(*lsop) +
1183                          sizeof(*assoc_rqst) + sizeof(*assoc_acc) +
1184                          ctrl->lport->ops->lsrqst_priv_sz), GFP_KERNEL);
1185         if (!lsop) {
1186                 dev_info(ctrl->ctrl.device,
1187                         "NVME-FC{%d}: send Create Association failed: ENOMEM\n",
1188                         ctrl->cnum);
1189                 ret = -ENOMEM;
1190                 goto out_no_memory;
1191         }
1192
1193         assoc_rqst = (struct fcnvme_ls_cr_assoc_rqst *)&lsop[1];
1194         assoc_acc = (struct fcnvme_ls_cr_assoc_acc *)&assoc_rqst[1];
1195         lsreq = &lsop->ls_req;
1196         if (ctrl->lport->ops->lsrqst_priv_sz)
1197                 lsreq->private = &assoc_acc[1];
1198         else
1199                 lsreq->private = NULL;
1200
1201         assoc_rqst->w0.ls_cmd = FCNVME_LS_CREATE_ASSOCIATION;
1202         assoc_rqst->desc_list_len =
1203                         cpu_to_be32(sizeof(struct fcnvme_lsdesc_cr_assoc_cmd));
1204
1205         assoc_rqst->assoc_cmd.desc_tag =
1206                         cpu_to_be32(FCNVME_LSDESC_CREATE_ASSOC_CMD);
1207         assoc_rqst->assoc_cmd.desc_len =
1208                         fcnvme_lsdesc_len(
1209                                 sizeof(struct fcnvme_lsdesc_cr_assoc_cmd));
1210
1211         assoc_rqst->assoc_cmd.ersp_ratio = cpu_to_be16(ersp_ratio);
1212         assoc_rqst->assoc_cmd.sqsize = cpu_to_be16(qsize - 1);
1213         /* Linux supports only Dynamic controllers */
1214         assoc_rqst->assoc_cmd.cntlid = cpu_to_be16(0xffff);
1215         uuid_copy(&assoc_rqst->assoc_cmd.hostid, &ctrl->ctrl.opts->host->id);
1216         strncpy(assoc_rqst->assoc_cmd.hostnqn, ctrl->ctrl.opts->host->nqn,
1217                 min(FCNVME_ASSOC_HOSTNQN_LEN, NVMF_NQN_SIZE));
1218         strncpy(assoc_rqst->assoc_cmd.subnqn, ctrl->ctrl.opts->subsysnqn,
1219                 min(FCNVME_ASSOC_SUBNQN_LEN, NVMF_NQN_SIZE));
1220
1221         lsop->queue = queue;
1222         lsreq->rqstaddr = assoc_rqst;
1223         lsreq->rqstlen = sizeof(*assoc_rqst);
1224         lsreq->rspaddr = assoc_acc;
1225         lsreq->rsplen = sizeof(*assoc_acc);
1226         lsreq->timeout = NVME_FC_LS_TIMEOUT_SEC;
1227
1228         ret = nvme_fc_send_ls_req(ctrl->rport, lsop);
1229         if (ret)
1230                 goto out_free_buffer;
1231
1232         /* process connect LS completion */
1233
1234         /* validate the ACC response */
1235         if (assoc_acc->hdr.w0.ls_cmd != FCNVME_LS_ACC)
1236                 fcret = VERR_LSACC;
1237         else if (assoc_acc->hdr.desc_list_len !=
1238                         fcnvme_lsdesc_len(
1239                                 sizeof(struct fcnvme_ls_cr_assoc_acc)))
1240                 fcret = VERR_CR_ASSOC_ACC_LEN;
1241         else if (assoc_acc->hdr.rqst.desc_tag !=
1242                         cpu_to_be32(FCNVME_LSDESC_RQST))
1243                 fcret = VERR_LSDESC_RQST;
1244         else if (assoc_acc->hdr.rqst.desc_len !=
1245                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_rqst)))
1246                 fcret = VERR_LSDESC_RQST_LEN;
1247         else if (assoc_acc->hdr.rqst.w0.ls_cmd != FCNVME_LS_CREATE_ASSOCIATION)
1248                 fcret = VERR_CR_ASSOC;
1249         else if (assoc_acc->associd.desc_tag !=
1250                         cpu_to_be32(FCNVME_LSDESC_ASSOC_ID))
1251                 fcret = VERR_ASSOC_ID;
1252         else if (assoc_acc->associd.desc_len !=
1253                         fcnvme_lsdesc_len(
1254                                 sizeof(struct fcnvme_lsdesc_assoc_id)))
1255                 fcret = VERR_ASSOC_ID_LEN;
1256         else if (assoc_acc->connectid.desc_tag !=
1257                         cpu_to_be32(FCNVME_LSDESC_CONN_ID))
1258                 fcret = VERR_CONN_ID;
1259         else if (assoc_acc->connectid.desc_len !=
1260                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_conn_id)))
1261                 fcret = VERR_CONN_ID_LEN;
1262
1263         if (fcret) {
1264                 ret = -EBADF;
1265                 dev_err(ctrl->dev,
1266                         "q %d Create Association LS failed: %s\n",
1267                         queue->qnum, validation_errors[fcret]);
1268         } else {
1269                 spin_lock_irqsave(&ctrl->lock, flags);
1270                 ctrl->association_id =
1271                         be64_to_cpu(assoc_acc->associd.association_id);
1272                 queue->connection_id =
1273                         be64_to_cpu(assoc_acc->connectid.connection_id);
1274                 set_bit(NVME_FC_Q_CONNECTED, &queue->flags);
1275                 spin_unlock_irqrestore(&ctrl->lock, flags);
1276         }
1277
1278 out_free_buffer:
1279         kfree(lsop);
1280 out_no_memory:
1281         if (ret)
1282                 dev_err(ctrl->dev,
1283                         "queue %d connect admin queue failed (%d).\n",
1284                         queue->qnum, ret);
1285         return ret;
1286 }
1287
1288 static int
1289 nvme_fc_connect_queue(struct nvme_fc_ctrl *ctrl, struct nvme_fc_queue *queue,
1290                         u16 qsize, u16 ersp_ratio)
1291 {
1292         struct nvmefc_ls_req_op *lsop;
1293         struct nvmefc_ls_req *lsreq;
1294         struct fcnvme_ls_cr_conn_rqst *conn_rqst;
1295         struct fcnvme_ls_cr_conn_acc *conn_acc;
1296         int ret, fcret = 0;
1297
1298         lsop = kzalloc((sizeof(*lsop) +
1299                          sizeof(*conn_rqst) + sizeof(*conn_acc) +
1300                          ctrl->lport->ops->lsrqst_priv_sz), GFP_KERNEL);
1301         if (!lsop) {
1302                 dev_info(ctrl->ctrl.device,
1303                         "NVME-FC{%d}: send Create Connection failed: ENOMEM\n",
1304                         ctrl->cnum);
1305                 ret = -ENOMEM;
1306                 goto out_no_memory;
1307         }
1308
1309         conn_rqst = (struct fcnvme_ls_cr_conn_rqst *)&lsop[1];
1310         conn_acc = (struct fcnvme_ls_cr_conn_acc *)&conn_rqst[1];
1311         lsreq = &lsop->ls_req;
1312         if (ctrl->lport->ops->lsrqst_priv_sz)
1313                 lsreq->private = (void *)&conn_acc[1];
1314         else
1315                 lsreq->private = NULL;
1316
1317         conn_rqst->w0.ls_cmd = FCNVME_LS_CREATE_CONNECTION;
1318         conn_rqst->desc_list_len = cpu_to_be32(
1319                                 sizeof(struct fcnvme_lsdesc_assoc_id) +
1320                                 sizeof(struct fcnvme_lsdesc_cr_conn_cmd));
1321
1322         conn_rqst->associd.desc_tag = cpu_to_be32(FCNVME_LSDESC_ASSOC_ID);
1323         conn_rqst->associd.desc_len =
1324                         fcnvme_lsdesc_len(
1325                                 sizeof(struct fcnvme_lsdesc_assoc_id));
1326         conn_rqst->associd.association_id = cpu_to_be64(ctrl->association_id);
1327         conn_rqst->connect_cmd.desc_tag =
1328                         cpu_to_be32(FCNVME_LSDESC_CREATE_CONN_CMD);
1329         conn_rqst->connect_cmd.desc_len =
1330                         fcnvme_lsdesc_len(
1331                                 sizeof(struct fcnvme_lsdesc_cr_conn_cmd));
1332         conn_rqst->connect_cmd.ersp_ratio = cpu_to_be16(ersp_ratio);
1333         conn_rqst->connect_cmd.qid  = cpu_to_be16(queue->qnum);
1334         conn_rqst->connect_cmd.sqsize = cpu_to_be16(qsize - 1);
1335
1336         lsop->queue = queue;
1337         lsreq->rqstaddr = conn_rqst;
1338         lsreq->rqstlen = sizeof(*conn_rqst);
1339         lsreq->rspaddr = conn_acc;
1340         lsreq->rsplen = sizeof(*conn_acc);
1341         lsreq->timeout = NVME_FC_LS_TIMEOUT_SEC;
1342
1343         ret = nvme_fc_send_ls_req(ctrl->rport, lsop);
1344         if (ret)
1345                 goto out_free_buffer;
1346
1347         /* process connect LS completion */
1348
1349         /* validate the ACC response */
1350         if (conn_acc->hdr.w0.ls_cmd != FCNVME_LS_ACC)
1351                 fcret = VERR_LSACC;
1352         else if (conn_acc->hdr.desc_list_len !=
1353                         fcnvme_lsdesc_len(sizeof(struct fcnvme_ls_cr_conn_acc)))
1354                 fcret = VERR_CR_CONN_ACC_LEN;
1355         else if (conn_acc->hdr.rqst.desc_tag != cpu_to_be32(FCNVME_LSDESC_RQST))
1356                 fcret = VERR_LSDESC_RQST;
1357         else if (conn_acc->hdr.rqst.desc_len !=
1358                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_rqst)))
1359                 fcret = VERR_LSDESC_RQST_LEN;
1360         else if (conn_acc->hdr.rqst.w0.ls_cmd != FCNVME_LS_CREATE_CONNECTION)
1361                 fcret = VERR_CR_CONN;
1362         else if (conn_acc->connectid.desc_tag !=
1363                         cpu_to_be32(FCNVME_LSDESC_CONN_ID))
1364                 fcret = VERR_CONN_ID;
1365         else if (conn_acc->connectid.desc_len !=
1366                         fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_conn_id)))
1367                 fcret = VERR_CONN_ID_LEN;
1368
1369         if (fcret) {
1370                 ret = -EBADF;
1371                 dev_err(ctrl->dev,
1372                         "q %d Create I/O Connection LS failed: %s\n",
1373                         queue->qnum, validation_errors[fcret]);
1374         } else {
1375                 queue->connection_id =
1376                         be64_to_cpu(conn_acc->connectid.connection_id);
1377                 set_bit(NVME_FC_Q_CONNECTED, &queue->flags);
1378         }
1379
1380 out_free_buffer:
1381         kfree(lsop);
1382 out_no_memory:
1383         if (ret)
1384                 dev_err(ctrl->dev,
1385                         "queue %d connect I/O queue failed (%d).\n",
1386                         queue->qnum, ret);
1387         return ret;
1388 }
1389
1390 static void
1391 nvme_fc_disconnect_assoc_done(struct nvmefc_ls_req *lsreq, int status)
1392 {
1393         struct nvmefc_ls_req_op *lsop = ls_req_to_lsop(lsreq);
1394
1395         __nvme_fc_finish_ls_req(lsop);
1396
1397         /* fc-nvme initiator doesn't care about success or failure of cmd */
1398
1399         kfree(lsop);
1400 }
1401
1402 /*
1403  * This routine sends a FC-NVME LS to disconnect (aka terminate)
1404  * the FC-NVME Association.  Terminating the association also
1405  * terminates the FC-NVME connections (per queue, both admin and io
1406  * queues) that are part of the association. E.g. things are torn
1407  * down, and the related FC-NVME Association ID and Connection IDs
1408  * become invalid.
1409  *
1410  * The behavior of the fc-nvme initiator is such that it's
1411  * understanding of the association and connections will implicitly
1412  * be torn down. The action is implicit as it may be due to a loss of
1413  * connectivity with the fc-nvme target, so you may never get a
1414  * response even if you tried.  As such, the action of this routine
1415  * is to asynchronously send the LS, ignore any results of the LS, and
1416  * continue on with terminating the association. If the fc-nvme target
1417  * is present and receives the LS, it too can tear down.
1418  */
1419 static void
1420 nvme_fc_xmt_disconnect_assoc(struct nvme_fc_ctrl *ctrl)
1421 {
1422         struct fcnvme_ls_disconnect_assoc_rqst *discon_rqst;
1423         struct fcnvme_ls_disconnect_assoc_acc *discon_acc;
1424         struct nvmefc_ls_req_op *lsop;
1425         struct nvmefc_ls_req *lsreq;
1426         int ret;
1427
1428         lsop = kzalloc((sizeof(*lsop) +
1429                         sizeof(*discon_rqst) + sizeof(*discon_acc) +
1430                         ctrl->lport->ops->lsrqst_priv_sz), GFP_KERNEL);
1431         if (!lsop) {
1432                 dev_info(ctrl->ctrl.device,
1433                         "NVME-FC{%d}: send Disconnect Association "
1434                         "failed: ENOMEM\n",
1435                         ctrl->cnum);
1436                 return;
1437         }
1438
1439         discon_rqst = (struct fcnvme_ls_disconnect_assoc_rqst *)&lsop[1];
1440         discon_acc = (struct fcnvme_ls_disconnect_assoc_acc *)&discon_rqst[1];
1441         lsreq = &lsop->ls_req;
1442         if (ctrl->lport->ops->lsrqst_priv_sz)
1443                 lsreq->private = (void *)&discon_acc[1];
1444         else
1445                 lsreq->private = NULL;
1446
1447         nvmefc_fmt_lsreq_discon_assoc(lsreq, discon_rqst, discon_acc,
1448                                 ctrl->association_id);
1449
1450         ret = nvme_fc_send_ls_req_async(ctrl->rport, lsop,
1451                                 nvme_fc_disconnect_assoc_done);
1452         if (ret)
1453                 kfree(lsop);
1454 }
1455
1456 static void
1457 nvme_fc_xmt_ls_rsp_done(struct nvmefc_ls_rsp *lsrsp)
1458 {
1459         struct nvmefc_ls_rcv_op *lsop = lsrsp->nvme_fc_private;
1460         struct nvme_fc_rport *rport = lsop->rport;
1461         struct nvme_fc_lport *lport = rport->lport;
1462         unsigned long flags;
1463
1464         spin_lock_irqsave(&rport->lock, flags);
1465         list_del(&lsop->lsrcv_list);
1466         spin_unlock_irqrestore(&rport->lock, flags);
1467
1468         fc_dma_sync_single_for_cpu(lport->dev, lsop->rspdma,
1469                                 sizeof(*lsop->rspbuf), DMA_TO_DEVICE);
1470         fc_dma_unmap_single(lport->dev, lsop->rspdma,
1471                         sizeof(*lsop->rspbuf), DMA_TO_DEVICE);
1472
1473         kfree(lsop);
1474
1475         nvme_fc_rport_put(rport);
1476 }
1477
1478 static void
1479 nvme_fc_xmt_ls_rsp(struct nvmefc_ls_rcv_op *lsop)
1480 {
1481         struct nvme_fc_rport *rport = lsop->rport;
1482         struct nvme_fc_lport *lport = rport->lport;
1483         struct fcnvme_ls_rqst_w0 *w0 = &lsop->rqstbuf->w0;
1484         int ret;
1485
1486         fc_dma_sync_single_for_device(lport->dev, lsop->rspdma,
1487                                   sizeof(*lsop->rspbuf), DMA_TO_DEVICE);
1488
1489         ret = lport->ops->xmt_ls_rsp(&lport->localport, &rport->remoteport,
1490                                      lsop->lsrsp);
1491         if (ret) {
1492                 dev_warn(lport->dev,
1493                         "LLDD rejected LS RSP xmt: LS %d status %d\n",
1494                         w0->ls_cmd, ret);
1495                 nvme_fc_xmt_ls_rsp_done(lsop->lsrsp);
1496                 return;
1497         }
1498 }
1499
1500 static struct nvme_fc_ctrl *
1501 nvme_fc_match_disconn_ls(struct nvme_fc_rport *rport,
1502                       struct nvmefc_ls_rcv_op *lsop)
1503 {
1504         struct fcnvme_ls_disconnect_assoc_rqst *rqst =
1505                                         &lsop->rqstbuf->rq_dis_assoc;
1506         struct nvme_fc_ctrl *ctrl, *ret = NULL;
1507         struct nvmefc_ls_rcv_op *oldls = NULL;
1508         u64 association_id = be64_to_cpu(rqst->associd.association_id);
1509         unsigned long flags;
1510
1511         spin_lock_irqsave(&rport->lock, flags);
1512
1513         list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list) {
1514                 if (!nvme_fc_ctrl_get(ctrl))
1515                         continue;
1516                 spin_lock(&ctrl->lock);
1517                 if (association_id == ctrl->association_id) {
1518                         oldls = ctrl->rcv_disconn;
1519                         ctrl->rcv_disconn = lsop;
1520                         ret = ctrl;
1521                 }
1522                 spin_unlock(&ctrl->lock);
1523                 if (ret)
1524                         /* leave the ctrl get reference */
1525                         break;
1526                 nvme_fc_ctrl_put(ctrl);
1527         }
1528
1529         spin_unlock_irqrestore(&rport->lock, flags);
1530
1531         /* transmit a response for anything that was pending */
1532         if (oldls) {
1533                 dev_info(rport->lport->dev,
1534                         "NVME-FC{%d}: Multiple Disconnect Association "
1535                         "LS's received\n", ctrl->cnum);
1536                 /* overwrite good response with bogus failure */
1537                 oldls->lsrsp->rsplen = nvme_fc_format_rjt(oldls->rspbuf,
1538                                                 sizeof(*oldls->rspbuf),
1539                                                 rqst->w0.ls_cmd,
1540                                                 FCNVME_RJT_RC_UNAB,
1541                                                 FCNVME_RJT_EXP_NONE, 0);
1542                 nvme_fc_xmt_ls_rsp(oldls);
1543         }
1544
1545         return ret;
1546 }
1547
1548 /*
1549  * returns true to mean LS handled and ls_rsp can be sent
1550  * returns false to defer ls_rsp xmt (will be done as part of
1551  *     association termination)
1552  */
1553 static bool
1554 nvme_fc_ls_disconnect_assoc(struct nvmefc_ls_rcv_op *lsop)
1555 {
1556         struct nvme_fc_rport *rport = lsop->rport;
1557         struct fcnvme_ls_disconnect_assoc_rqst *rqst =
1558                                         &lsop->rqstbuf->rq_dis_assoc;
1559         struct fcnvme_ls_disconnect_assoc_acc *acc =
1560                                         &lsop->rspbuf->rsp_dis_assoc;
1561         struct nvme_fc_ctrl *ctrl = NULL;
1562         int ret = 0;
1563
1564         memset(acc, 0, sizeof(*acc));
1565
1566         ret = nvmefc_vldt_lsreq_discon_assoc(lsop->rqstdatalen, rqst);
1567         if (!ret) {
1568                 /* match an active association */
1569                 ctrl = nvme_fc_match_disconn_ls(rport, lsop);
1570                 if (!ctrl)
1571                         ret = VERR_NO_ASSOC;
1572         }
1573
1574         if (ret) {
1575                 dev_info(rport->lport->dev,
1576                         "Disconnect LS failed: %s\n",
1577                         validation_errors[ret]);
1578                 lsop->lsrsp->rsplen = nvme_fc_format_rjt(acc,
1579                                         sizeof(*acc), rqst->w0.ls_cmd,
1580                                         (ret == VERR_NO_ASSOC) ?
1581                                                 FCNVME_RJT_RC_INV_ASSOC :
1582                                                 FCNVME_RJT_RC_LOGIC,
1583                                         FCNVME_RJT_EXP_NONE, 0);
1584                 return true;
1585         }
1586
1587         /* format an ACCept response */
1588
1589         lsop->lsrsp->rsplen = sizeof(*acc);
1590
1591         nvme_fc_format_rsp_hdr(acc, FCNVME_LS_ACC,
1592                         fcnvme_lsdesc_len(
1593                                 sizeof(struct fcnvme_ls_disconnect_assoc_acc)),
1594                         FCNVME_LS_DISCONNECT_ASSOC);
1595
1596         /*
1597          * the transmit of the response will occur after the exchanges
1598          * for the association have been ABTS'd by
1599          * nvme_fc_delete_association().
1600          */
1601
1602         /* fail the association */
1603         nvme_fc_error_recovery(ctrl, "Disconnect Association LS received");
1604
1605         /* release the reference taken by nvme_fc_match_disconn_ls() */
1606         nvme_fc_ctrl_put(ctrl);
1607
1608         return false;
1609 }
1610
1611 /*
1612  * Actual Processing routine for received FC-NVME LS Requests from the LLD
1613  * returns true if a response should be sent afterward, false if rsp will
1614  * be sent asynchronously.
1615  */
1616 static bool
1617 nvme_fc_handle_ls_rqst(struct nvmefc_ls_rcv_op *lsop)
1618 {
1619         struct fcnvme_ls_rqst_w0 *w0 = &lsop->rqstbuf->w0;
1620         bool ret = true;
1621
1622         lsop->lsrsp->nvme_fc_private = lsop;
1623         lsop->lsrsp->rspbuf = lsop->rspbuf;
1624         lsop->lsrsp->rspdma = lsop->rspdma;
1625         lsop->lsrsp->done = nvme_fc_xmt_ls_rsp_done;
1626         /* Be preventative. handlers will later set to valid length */
1627         lsop->lsrsp->rsplen = 0;
1628
1629         /*
1630          * handlers:
1631          *   parse request input, execute the request, and format the
1632          *   LS response
1633          */
1634         switch (w0->ls_cmd) {
1635         case FCNVME_LS_DISCONNECT_ASSOC:
1636                 ret = nvme_fc_ls_disconnect_assoc(lsop);
1637                 break;
1638         case FCNVME_LS_DISCONNECT_CONN:
1639                 lsop->lsrsp->rsplen = nvme_fc_format_rjt(lsop->rspbuf,
1640                                 sizeof(*lsop->rspbuf), w0->ls_cmd,
1641                                 FCNVME_RJT_RC_UNSUP, FCNVME_RJT_EXP_NONE, 0);
1642                 break;
1643         case FCNVME_LS_CREATE_ASSOCIATION:
1644         case FCNVME_LS_CREATE_CONNECTION:
1645                 lsop->lsrsp->rsplen = nvme_fc_format_rjt(lsop->rspbuf,
1646                                 sizeof(*lsop->rspbuf), w0->ls_cmd,
1647                                 FCNVME_RJT_RC_LOGIC, FCNVME_RJT_EXP_NONE, 0);
1648                 break;
1649         default:
1650                 lsop->lsrsp->rsplen = nvme_fc_format_rjt(lsop->rspbuf,
1651                                 sizeof(*lsop->rspbuf), w0->ls_cmd,
1652                                 FCNVME_RJT_RC_INVAL, FCNVME_RJT_EXP_NONE, 0);
1653                 break;
1654         }
1655
1656         return(ret);
1657 }
1658
1659 static void
1660 nvme_fc_handle_ls_rqst_work(struct work_struct *work)
1661 {
1662         struct nvme_fc_rport *rport =
1663                 container_of(work, struct nvme_fc_rport, lsrcv_work);
1664         struct fcnvme_ls_rqst_w0 *w0;
1665         struct nvmefc_ls_rcv_op *lsop;
1666         unsigned long flags;
1667         bool sendrsp;
1668
1669 restart:
1670         sendrsp = true;
1671         spin_lock_irqsave(&rport->lock, flags);
1672         list_for_each_entry(lsop, &rport->ls_rcv_list, lsrcv_list) {
1673                 if (lsop->handled)
1674                         continue;
1675
1676                 lsop->handled = true;
1677                 if (rport->remoteport.port_state == FC_OBJSTATE_ONLINE) {
1678                         spin_unlock_irqrestore(&rport->lock, flags);
1679                         sendrsp = nvme_fc_handle_ls_rqst(lsop);
1680                 } else {
1681                         spin_unlock_irqrestore(&rport->lock, flags);
1682                         w0 = &lsop->rqstbuf->w0;
1683                         lsop->lsrsp->rsplen = nvme_fc_format_rjt(
1684                                                 lsop->rspbuf,
1685                                                 sizeof(*lsop->rspbuf),
1686                                                 w0->ls_cmd,
1687                                                 FCNVME_RJT_RC_UNAB,
1688                                                 FCNVME_RJT_EXP_NONE, 0);
1689                 }
1690                 if (sendrsp)
1691                         nvme_fc_xmt_ls_rsp(lsop);
1692                 goto restart;
1693         }
1694         spin_unlock_irqrestore(&rport->lock, flags);
1695 }
1696
1697 /**
1698  * nvme_fc_rcv_ls_req - transport entry point called by an LLDD
1699  *                       upon the reception of a NVME LS request.
1700  *
1701  * The nvme-fc layer will copy payload to an internal structure for
1702  * processing.  As such, upon completion of the routine, the LLDD may
1703  * immediately free/reuse the LS request buffer passed in the call.
1704  *
1705  * If this routine returns error, the LLDD should abort the exchange.
1706  *
1707  * @remoteport: pointer to the (registered) remote port that the LS
1708  *              was received from. The remoteport is associated with
1709  *              a specific localport.
1710  * @lsrsp:      pointer to a nvmefc_ls_rsp response structure to be
1711  *              used to reference the exchange corresponding to the LS
1712  *              when issuing an ls response.
1713  * @lsreqbuf:   pointer to the buffer containing the LS Request
1714  * @lsreqbuf_len: length, in bytes, of the received LS request
1715  */
1716 int
1717 nvme_fc_rcv_ls_req(struct nvme_fc_remote_port *portptr,
1718                         struct nvmefc_ls_rsp *lsrsp,
1719                         void *lsreqbuf, u32 lsreqbuf_len)
1720 {
1721         struct nvme_fc_rport *rport = remoteport_to_rport(portptr);
1722         struct nvme_fc_lport *lport = rport->lport;
1723         struct fcnvme_ls_rqst_w0 *w0 = (struct fcnvme_ls_rqst_w0 *)lsreqbuf;
1724         struct nvmefc_ls_rcv_op *lsop;
1725         unsigned long flags;
1726         int ret;
1727
1728         nvme_fc_rport_get(rport);
1729
1730         /* validate there's a routine to transmit a response */
1731         if (!lport->ops->xmt_ls_rsp) {
1732                 dev_info(lport->dev,
1733                         "RCV %s LS failed: no LLDD xmt_ls_rsp\n",
1734                         (w0->ls_cmd <= NVME_FC_LAST_LS_CMD_VALUE) ?
1735                                 nvmefc_ls_names[w0->ls_cmd] : "");
1736                 ret = -EINVAL;
1737                 goto out_put;
1738         }
1739
1740         if (lsreqbuf_len > sizeof(union nvmefc_ls_requests)) {
1741                 dev_info(lport->dev,
1742                         "RCV %s LS failed: payload too large\n",
1743                         (w0->ls_cmd <= NVME_FC_LAST_LS_CMD_VALUE) ?
1744                                 nvmefc_ls_names[w0->ls_cmd] : "");
1745                 ret = -E2BIG;
1746                 goto out_put;
1747         }
1748
1749         lsop = kzalloc(sizeof(*lsop) +
1750                         sizeof(union nvmefc_ls_requests) +
1751                         sizeof(union nvmefc_ls_responses),
1752                         GFP_KERNEL);
1753         if (!lsop) {
1754                 dev_info(lport->dev,
1755                         "RCV %s LS failed: No memory\n",
1756                         (w0->ls_cmd <= NVME_FC_LAST_LS_CMD_VALUE) ?
1757                                 nvmefc_ls_names[w0->ls_cmd] : "");
1758                 ret = -ENOMEM;
1759                 goto out_put;
1760         }
1761         lsop->rqstbuf = (union nvmefc_ls_requests *)&lsop[1];
1762         lsop->rspbuf = (union nvmefc_ls_responses *)&lsop->rqstbuf[1];
1763
1764         lsop->rspdma = fc_dma_map_single(lport->dev, lsop->rspbuf,
1765                                         sizeof(*lsop->rspbuf),
1766                                         DMA_TO_DEVICE);
1767         if (fc_dma_mapping_error(lport->dev, lsop->rspdma)) {
1768                 dev_info(lport->dev,
1769                         "RCV %s LS failed: DMA mapping failure\n",
1770                         (w0->ls_cmd <= NVME_FC_LAST_LS_CMD_VALUE) ?
1771                                 nvmefc_ls_names[w0->ls_cmd] : "");
1772                 ret = -EFAULT;
1773                 goto out_free;
1774         }
1775
1776         lsop->rport = rport;
1777         lsop->lsrsp = lsrsp;
1778
1779         memcpy(lsop->rqstbuf, lsreqbuf, lsreqbuf_len);
1780         lsop->rqstdatalen = lsreqbuf_len;
1781
1782         spin_lock_irqsave(&rport->lock, flags);
1783         if (rport->remoteport.port_state != FC_OBJSTATE_ONLINE) {
1784                 spin_unlock_irqrestore(&rport->lock, flags);
1785                 ret = -ENOTCONN;
1786                 goto out_unmap;
1787         }
1788         list_add_tail(&lsop->lsrcv_list, &rport->ls_rcv_list);
1789         spin_unlock_irqrestore(&rport->lock, flags);
1790
1791         schedule_work(&rport->lsrcv_work);
1792
1793         return 0;
1794
1795 out_unmap:
1796         fc_dma_unmap_single(lport->dev, lsop->rspdma,
1797                         sizeof(*lsop->rspbuf), DMA_TO_DEVICE);
1798 out_free:
1799         kfree(lsop);
1800 out_put:
1801         nvme_fc_rport_put(rport);
1802         return ret;
1803 }
1804 EXPORT_SYMBOL_GPL(nvme_fc_rcv_ls_req);
1805
1806
1807 /* *********************** NVME Ctrl Routines **************************** */
1808
1809 static void
1810 __nvme_fc_exit_request(struct nvme_fc_ctrl *ctrl,
1811                 struct nvme_fc_fcp_op *op)
1812 {
1813         fc_dma_unmap_single(ctrl->lport->dev, op->fcp_req.rspdma,
1814                                 sizeof(op->rsp_iu), DMA_FROM_DEVICE);
1815         fc_dma_unmap_single(ctrl->lport->dev, op->fcp_req.cmddma,
1816                                 sizeof(op->cmd_iu), DMA_TO_DEVICE);
1817
1818         atomic_set(&op->state, FCPOP_STATE_UNINIT);
1819 }
1820
1821 static void
1822 nvme_fc_exit_request(struct blk_mq_tag_set *set, struct request *rq,
1823                 unsigned int hctx_idx)
1824 {
1825         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
1826
1827         return __nvme_fc_exit_request(set->driver_data, op);
1828 }
1829
1830 static int
1831 __nvme_fc_abort_op(struct nvme_fc_ctrl *ctrl, struct nvme_fc_fcp_op *op)
1832 {
1833         unsigned long flags;
1834         int opstate;
1835
1836         spin_lock_irqsave(&ctrl->lock, flags);
1837         opstate = atomic_xchg(&op->state, FCPOP_STATE_ABORTED);
1838         if (opstate != FCPOP_STATE_ACTIVE)
1839                 atomic_set(&op->state, opstate);
1840         else if (test_bit(FCCTRL_TERMIO, &ctrl->flags)) {
1841                 op->flags |= FCOP_FLAGS_TERMIO;
1842                 ctrl->iocnt++;
1843         }
1844         spin_unlock_irqrestore(&ctrl->lock, flags);
1845
1846         if (opstate != FCPOP_STATE_ACTIVE)
1847                 return -ECANCELED;
1848
1849         ctrl->lport->ops->fcp_abort(&ctrl->lport->localport,
1850                                         &ctrl->rport->remoteport,
1851                                         op->queue->lldd_handle,
1852                                         &op->fcp_req);
1853
1854         return 0;
1855 }
1856
1857 static void
1858 nvme_fc_abort_aen_ops(struct nvme_fc_ctrl *ctrl)
1859 {
1860         struct nvme_fc_fcp_op *aen_op = ctrl->aen_ops;
1861         int i;
1862
1863         /* ensure we've initialized the ops once */
1864         if (!(aen_op->flags & FCOP_FLAGS_AEN))
1865                 return;
1866
1867         for (i = 0; i < NVME_NR_AEN_COMMANDS; i++, aen_op++)
1868                 __nvme_fc_abort_op(ctrl, aen_op);
1869 }
1870
1871 static inline void
1872 __nvme_fc_fcpop_chk_teardowns(struct nvme_fc_ctrl *ctrl,
1873                 struct nvme_fc_fcp_op *op, int opstate)
1874 {
1875         unsigned long flags;
1876
1877         if (opstate == FCPOP_STATE_ABORTED) {
1878                 spin_lock_irqsave(&ctrl->lock, flags);
1879                 if (test_bit(FCCTRL_TERMIO, &ctrl->flags) &&
1880                     op->flags & FCOP_FLAGS_TERMIO) {
1881                         if (!--ctrl->iocnt)
1882                                 wake_up(&ctrl->ioabort_wait);
1883                 }
1884                 spin_unlock_irqrestore(&ctrl->lock, flags);
1885         }
1886 }
1887
1888 static void
1889 nvme_fc_fcpio_done(struct nvmefc_fcp_req *req)
1890 {
1891         struct nvme_fc_fcp_op *op = fcp_req_to_fcp_op(req);
1892         struct request *rq = op->rq;
1893         struct nvmefc_fcp_req *freq = &op->fcp_req;
1894         struct nvme_fc_ctrl *ctrl = op->ctrl;
1895         struct nvme_fc_queue *queue = op->queue;
1896         struct nvme_completion *cqe = &op->rsp_iu.cqe;
1897         struct nvme_command *sqe = &op->cmd_iu.sqe;
1898         __le16 status = cpu_to_le16(NVME_SC_SUCCESS << 1);
1899         union nvme_result result;
1900         bool terminate_assoc = true;
1901         int opstate;
1902
1903         /*
1904          * WARNING:
1905          * The current linux implementation of a nvme controller
1906          * allocates a single tag set for all io queues and sizes
1907          * the io queues to fully hold all possible tags. Thus, the
1908          * implementation does not reference or care about the sqhd
1909          * value as it never needs to use the sqhd/sqtail pointers
1910          * for submission pacing.
1911          *
1912          * This affects the FC-NVME implementation in two ways:
1913          * 1) As the value doesn't matter, we don't need to waste
1914          *    cycles extracting it from ERSPs and stamping it in the
1915          *    cases where the transport fabricates CQEs on successful
1916          *    completions.
1917          * 2) The FC-NVME implementation requires that delivery of
1918          *    ERSP completions are to go back to the nvme layer in order
1919          *    relative to the rsn, such that the sqhd value will always
1920          *    be "in order" for the nvme layer. As the nvme layer in
1921          *    linux doesn't care about sqhd, there's no need to return
1922          *    them in order.
1923          *
1924          * Additionally:
1925          * As the core nvme layer in linux currently does not look at
1926          * every field in the cqe - in cases where the FC transport must
1927          * fabricate a CQE, the following fields will not be set as they
1928          * are not referenced:
1929          *      cqe.sqid,  cqe.sqhd,  cqe.command_id
1930          *
1931          * Failure or error of an individual i/o, in a transport
1932          * detected fashion unrelated to the nvme completion status,
1933          * potentially cause the initiator and target sides to get out
1934          * of sync on SQ head/tail (aka outstanding io count allowed).
1935          * Per FC-NVME spec, failure of an individual command requires
1936          * the connection to be terminated, which in turn requires the
1937          * association to be terminated.
1938          */
1939
1940         opstate = atomic_xchg(&op->state, FCPOP_STATE_COMPLETE);
1941
1942         fc_dma_sync_single_for_cpu(ctrl->lport->dev, op->fcp_req.rspdma,
1943                                 sizeof(op->rsp_iu), DMA_FROM_DEVICE);
1944
1945         if (opstate == FCPOP_STATE_ABORTED)
1946                 status = cpu_to_le16(NVME_SC_HOST_PATH_ERROR << 1);
1947         else if (freq->status) {
1948                 status = cpu_to_le16(NVME_SC_HOST_PATH_ERROR << 1);
1949                 dev_info(ctrl->ctrl.device,
1950                         "NVME-FC{%d}: io failed due to lldd error %d\n",
1951                         ctrl->cnum, freq->status);
1952         }
1953
1954         /*
1955          * For the linux implementation, if we have an unsuccesful
1956          * status, they blk-mq layer can typically be called with the
1957          * non-zero status and the content of the cqe isn't important.
1958          */
1959         if (status)
1960                 goto done;
1961
1962         /*
1963          * command completed successfully relative to the wire
1964          * protocol. However, validate anything received and
1965          * extract the status and result from the cqe (create it
1966          * where necessary).
1967          */
1968
1969         switch (freq->rcv_rsplen) {
1970
1971         case 0:
1972         case NVME_FC_SIZEOF_ZEROS_RSP:
1973                 /*
1974                  * No response payload or 12 bytes of payload (which
1975                  * should all be zeros) are considered successful and
1976                  * no payload in the CQE by the transport.
1977                  */
1978                 if (freq->transferred_length !=
1979                     be32_to_cpu(op->cmd_iu.data_len)) {
1980                         status = cpu_to_le16(NVME_SC_HOST_PATH_ERROR << 1);
1981                         dev_info(ctrl->ctrl.device,
1982                                 "NVME-FC{%d}: io failed due to bad transfer "
1983                                 "length: %d vs expected %d\n",
1984                                 ctrl->cnum, freq->transferred_length,
1985                                 be32_to_cpu(op->cmd_iu.data_len));
1986                         goto done;
1987                 }
1988                 result.u64 = 0;
1989                 break;
1990
1991         case sizeof(struct nvme_fc_ersp_iu):
1992                 /*
1993                  * The ERSP IU contains a full completion with CQE.
1994                  * Validate ERSP IU and look at cqe.
1995                  */
1996                 if (unlikely(be16_to_cpu(op->rsp_iu.iu_len) !=
1997                                         (freq->rcv_rsplen / 4) ||
1998                              be32_to_cpu(op->rsp_iu.xfrd_len) !=
1999                                         freq->transferred_length ||
2000                              op->rsp_iu.ersp_result ||
2001                              sqe->common.command_id != cqe->command_id)) {
2002                         status = cpu_to_le16(NVME_SC_HOST_PATH_ERROR << 1);
2003                         dev_info(ctrl->ctrl.device,
2004                                 "NVME-FC{%d}: io failed due to bad NVMe_ERSP: "
2005                                 "iu len %d, xfr len %d vs %d, status code "
2006                                 "%d, cmdid %d vs %d\n",
2007                                 ctrl->cnum, be16_to_cpu(op->rsp_iu.iu_len),
2008                                 be32_to_cpu(op->rsp_iu.xfrd_len),
2009                                 freq->transferred_length,
2010                                 op->rsp_iu.ersp_result,
2011                                 sqe->common.command_id,
2012                                 cqe->command_id);
2013                         goto done;
2014                 }
2015                 result = cqe->result;
2016                 status = cqe->status;
2017                 break;
2018
2019         default:
2020                 status = cpu_to_le16(NVME_SC_HOST_PATH_ERROR << 1);
2021                 dev_info(ctrl->ctrl.device,
2022                         "NVME-FC{%d}: io failed due to odd NVMe_xRSP iu "
2023                         "len %d\n",
2024                         ctrl->cnum, freq->rcv_rsplen);
2025                 goto done;
2026         }
2027
2028         terminate_assoc = false;
2029
2030 done:
2031         if (op->flags & FCOP_FLAGS_AEN) {
2032                 nvme_complete_async_event(&queue->ctrl->ctrl, status, &result);
2033                 __nvme_fc_fcpop_chk_teardowns(ctrl, op, opstate);
2034                 atomic_set(&op->state, FCPOP_STATE_IDLE);
2035                 op->flags = FCOP_FLAGS_AEN;     /* clear other flags */
2036                 nvme_fc_ctrl_put(ctrl);
2037                 goto check_error;
2038         }
2039
2040         __nvme_fc_fcpop_chk_teardowns(ctrl, op, opstate);
2041         if (!nvme_try_complete_req(rq, status, result))
2042                 nvme_fc_complete_rq(rq);
2043
2044 check_error:
2045         if (terminate_assoc)
2046                 nvme_fc_error_recovery(ctrl, "transport detected io error");
2047 }
2048
2049 static int
2050 __nvme_fc_init_request(struct nvme_fc_ctrl *ctrl,
2051                 struct nvme_fc_queue *queue, struct nvme_fc_fcp_op *op,
2052                 struct request *rq, u32 rqno)
2053 {
2054         struct nvme_fcp_op_w_sgl *op_w_sgl =
2055                 container_of(op, typeof(*op_w_sgl), op);
2056         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2057         int ret = 0;
2058
2059         memset(op, 0, sizeof(*op));
2060         op->fcp_req.cmdaddr = &op->cmd_iu;
2061         op->fcp_req.cmdlen = sizeof(op->cmd_iu);
2062         op->fcp_req.rspaddr = &op->rsp_iu;
2063         op->fcp_req.rsplen = sizeof(op->rsp_iu);
2064         op->fcp_req.done = nvme_fc_fcpio_done;
2065         op->ctrl = ctrl;
2066         op->queue = queue;
2067         op->rq = rq;
2068         op->rqno = rqno;
2069
2070         cmdiu->format_id = NVME_CMD_FORMAT_ID;
2071         cmdiu->fc_id = NVME_CMD_FC_ID;
2072         cmdiu->iu_len = cpu_to_be16(sizeof(*cmdiu) / sizeof(u32));
2073         if (queue->qnum)
2074                 cmdiu->rsv_cat = fccmnd_set_cat_css(0,
2075                                         (NVME_CC_CSS_NVM >> NVME_CC_CSS_SHIFT));
2076         else
2077                 cmdiu->rsv_cat = fccmnd_set_cat_admin(0);
2078
2079         op->fcp_req.cmddma = fc_dma_map_single(ctrl->lport->dev,
2080                                 &op->cmd_iu, sizeof(op->cmd_iu), DMA_TO_DEVICE);
2081         if (fc_dma_mapping_error(ctrl->lport->dev, op->fcp_req.cmddma)) {
2082                 dev_err(ctrl->dev,
2083                         "FCP Op failed - cmdiu dma mapping failed.\n");
2084                 ret = -EFAULT;
2085                 goto out_on_error;
2086         }
2087
2088         op->fcp_req.rspdma = fc_dma_map_single(ctrl->lport->dev,
2089                                 &op->rsp_iu, sizeof(op->rsp_iu),
2090                                 DMA_FROM_DEVICE);
2091         if (fc_dma_mapping_error(ctrl->lport->dev, op->fcp_req.rspdma)) {
2092                 dev_err(ctrl->dev,
2093                         "FCP Op failed - rspiu dma mapping failed.\n");
2094                 ret = -EFAULT;
2095         }
2096
2097         atomic_set(&op->state, FCPOP_STATE_IDLE);
2098 out_on_error:
2099         return ret;
2100 }
2101
2102 static int
2103 nvme_fc_init_request(struct blk_mq_tag_set *set, struct request *rq,
2104                 unsigned int hctx_idx, unsigned int numa_node)
2105 {
2106         struct nvme_fc_ctrl *ctrl = set->driver_data;
2107         struct nvme_fcp_op_w_sgl *op = blk_mq_rq_to_pdu(rq);
2108         int queue_idx = (set == &ctrl->tag_set) ? hctx_idx + 1 : 0;
2109         struct nvme_fc_queue *queue = &ctrl->queues[queue_idx];
2110         int res;
2111
2112         res = __nvme_fc_init_request(ctrl, queue, &op->op, rq, queue->rqcnt++);
2113         if (res)
2114                 return res;
2115         op->op.fcp_req.first_sgl = op->sgl;
2116         op->op.fcp_req.private = &op->priv[0];
2117         nvme_req(rq)->ctrl = &ctrl->ctrl;
2118         return res;
2119 }
2120
2121 static int
2122 nvme_fc_init_aen_ops(struct nvme_fc_ctrl *ctrl)
2123 {
2124         struct nvme_fc_fcp_op *aen_op;
2125         struct nvme_fc_cmd_iu *cmdiu;
2126         struct nvme_command *sqe;
2127         void *private = NULL;
2128         int i, ret;
2129
2130         aen_op = ctrl->aen_ops;
2131         for (i = 0; i < NVME_NR_AEN_COMMANDS; i++, aen_op++) {
2132                 if (ctrl->lport->ops->fcprqst_priv_sz) {
2133                         private = kzalloc(ctrl->lport->ops->fcprqst_priv_sz,
2134                                                 GFP_KERNEL);
2135                         if (!private)
2136                                 return -ENOMEM;
2137                 }
2138
2139                 cmdiu = &aen_op->cmd_iu;
2140                 sqe = &cmdiu->sqe;
2141                 ret = __nvme_fc_init_request(ctrl, &ctrl->queues[0],
2142                                 aen_op, (struct request *)NULL,
2143                                 (NVME_AQ_BLK_MQ_DEPTH + i));
2144                 if (ret) {
2145                         kfree(private);
2146                         return ret;
2147                 }
2148
2149                 aen_op->flags = FCOP_FLAGS_AEN;
2150                 aen_op->fcp_req.private = private;
2151
2152                 memset(sqe, 0, sizeof(*sqe));
2153                 sqe->common.opcode = nvme_admin_async_event;
2154                 /* Note: core layer may overwrite the sqe.command_id value */
2155                 sqe->common.command_id = NVME_AQ_BLK_MQ_DEPTH + i;
2156         }
2157         return 0;
2158 }
2159
2160 static void
2161 nvme_fc_term_aen_ops(struct nvme_fc_ctrl *ctrl)
2162 {
2163         struct nvme_fc_fcp_op *aen_op;
2164         int i;
2165
2166         cancel_work_sync(&ctrl->ctrl.async_event_work);
2167         aen_op = ctrl->aen_ops;
2168         for (i = 0; i < NVME_NR_AEN_COMMANDS; i++, aen_op++) {
2169                 __nvme_fc_exit_request(ctrl, aen_op);
2170
2171                 kfree(aen_op->fcp_req.private);
2172                 aen_op->fcp_req.private = NULL;
2173         }
2174 }
2175
2176 static inline void
2177 __nvme_fc_init_hctx(struct blk_mq_hw_ctx *hctx, struct nvme_fc_ctrl *ctrl,
2178                 unsigned int qidx)
2179 {
2180         struct nvme_fc_queue *queue = &ctrl->queues[qidx];
2181
2182         hctx->driver_data = queue;
2183         queue->hctx = hctx;
2184 }
2185
2186 static int
2187 nvme_fc_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
2188                 unsigned int hctx_idx)
2189 {
2190         struct nvme_fc_ctrl *ctrl = data;
2191
2192         __nvme_fc_init_hctx(hctx, ctrl, hctx_idx + 1);
2193
2194         return 0;
2195 }
2196
2197 static int
2198 nvme_fc_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
2199                 unsigned int hctx_idx)
2200 {
2201         struct nvme_fc_ctrl *ctrl = data;
2202
2203         __nvme_fc_init_hctx(hctx, ctrl, hctx_idx);
2204
2205         return 0;
2206 }
2207
2208 static void
2209 nvme_fc_init_queue(struct nvme_fc_ctrl *ctrl, int idx)
2210 {
2211         struct nvme_fc_queue *queue;
2212
2213         queue = &ctrl->queues[idx];
2214         memset(queue, 0, sizeof(*queue));
2215         queue->ctrl = ctrl;
2216         queue->qnum = idx;
2217         atomic_set(&queue->csn, 0);
2218         queue->dev = ctrl->dev;
2219
2220         if (idx > 0)
2221                 queue->cmnd_capsule_len = ctrl->ctrl.ioccsz * 16;
2222         else
2223                 queue->cmnd_capsule_len = sizeof(struct nvme_command);
2224
2225         /*
2226          * Considered whether we should allocate buffers for all SQEs
2227          * and CQEs and dma map them - mapping their respective entries
2228          * into the request structures (kernel vm addr and dma address)
2229          * thus the driver could use the buffers/mappings directly.
2230          * It only makes sense if the LLDD would use them for its
2231          * messaging api. It's very unlikely most adapter api's would use
2232          * a native NVME sqe/cqe. More reasonable if FC-NVME IU payload
2233          * structures were used instead.
2234          */
2235 }
2236
2237 /*
2238  * This routine terminates a queue at the transport level.
2239  * The transport has already ensured that all outstanding ios on
2240  * the queue have been terminated.
2241  * The transport will send a Disconnect LS request to terminate
2242  * the queue's connection. Termination of the admin queue will also
2243  * terminate the association at the target.
2244  */
2245 static void
2246 nvme_fc_free_queue(struct nvme_fc_queue *queue)
2247 {
2248         if (!test_and_clear_bit(NVME_FC_Q_CONNECTED, &queue->flags))
2249                 return;
2250
2251         clear_bit(NVME_FC_Q_LIVE, &queue->flags);
2252         /*
2253          * Current implementation never disconnects a single queue.
2254          * It always terminates a whole association. So there is never
2255          * a disconnect(queue) LS sent to the target.
2256          */
2257
2258         queue->connection_id = 0;
2259         atomic_set(&queue->csn, 0);
2260 }
2261
2262 static void
2263 __nvme_fc_delete_hw_queue(struct nvme_fc_ctrl *ctrl,
2264         struct nvme_fc_queue *queue, unsigned int qidx)
2265 {
2266         if (ctrl->lport->ops->delete_queue)
2267                 ctrl->lport->ops->delete_queue(&ctrl->lport->localport, qidx,
2268                                 queue->lldd_handle);
2269         queue->lldd_handle = NULL;
2270 }
2271
2272 static void
2273 nvme_fc_free_io_queues(struct nvme_fc_ctrl *ctrl)
2274 {
2275         int i;
2276
2277         for (i = 1; i < ctrl->ctrl.queue_count; i++)
2278                 nvme_fc_free_queue(&ctrl->queues[i]);
2279 }
2280
2281 static int
2282 __nvme_fc_create_hw_queue(struct nvme_fc_ctrl *ctrl,
2283         struct nvme_fc_queue *queue, unsigned int qidx, u16 qsize)
2284 {
2285         int ret = 0;
2286
2287         queue->lldd_handle = NULL;
2288         if (ctrl->lport->ops->create_queue)
2289                 ret = ctrl->lport->ops->create_queue(&ctrl->lport->localport,
2290                                 qidx, qsize, &queue->lldd_handle);
2291
2292         return ret;
2293 }
2294
2295 static void
2296 nvme_fc_delete_hw_io_queues(struct nvme_fc_ctrl *ctrl)
2297 {
2298         struct nvme_fc_queue *queue = &ctrl->queues[ctrl->ctrl.queue_count - 1];
2299         int i;
2300
2301         for (i = ctrl->ctrl.queue_count - 1; i >= 1; i--, queue--)
2302                 __nvme_fc_delete_hw_queue(ctrl, queue, i);
2303 }
2304
2305 static int
2306 nvme_fc_create_hw_io_queues(struct nvme_fc_ctrl *ctrl, u16 qsize)
2307 {
2308         struct nvme_fc_queue *queue = &ctrl->queues[1];
2309         int i, ret;
2310
2311         for (i = 1; i < ctrl->ctrl.queue_count; i++, queue++) {
2312                 ret = __nvme_fc_create_hw_queue(ctrl, queue, i, qsize);
2313                 if (ret)
2314                         goto delete_queues;
2315         }
2316
2317         return 0;
2318
2319 delete_queues:
2320         for (; i > 0; i--)
2321                 __nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[i], i);
2322         return ret;
2323 }
2324
2325 static int
2326 nvme_fc_connect_io_queues(struct nvme_fc_ctrl *ctrl, u16 qsize)
2327 {
2328         int i, ret = 0;
2329
2330         for (i = 1; i < ctrl->ctrl.queue_count; i++) {
2331                 ret = nvme_fc_connect_queue(ctrl, &ctrl->queues[i], qsize,
2332                                         (qsize / 5));
2333                 if (ret)
2334                         break;
2335                 ret = nvmf_connect_io_queue(&ctrl->ctrl, i, false);
2336                 if (ret)
2337                         break;
2338
2339                 set_bit(NVME_FC_Q_LIVE, &ctrl->queues[i].flags);
2340         }
2341
2342         return ret;
2343 }
2344
2345 static void
2346 nvme_fc_init_io_queues(struct nvme_fc_ctrl *ctrl)
2347 {
2348         int i;
2349
2350         for (i = 1; i < ctrl->ctrl.queue_count; i++)
2351                 nvme_fc_init_queue(ctrl, i);
2352 }
2353
2354 static void
2355 nvme_fc_ctrl_free(struct kref *ref)
2356 {
2357         struct nvme_fc_ctrl *ctrl =
2358                 container_of(ref, struct nvme_fc_ctrl, ref);
2359         unsigned long flags;
2360
2361         if (ctrl->ctrl.tagset) {
2362                 blk_cleanup_queue(ctrl->ctrl.connect_q);
2363                 blk_mq_free_tag_set(&ctrl->tag_set);
2364         }
2365
2366         /* remove from rport list */
2367         spin_lock_irqsave(&ctrl->rport->lock, flags);
2368         list_del(&ctrl->ctrl_list);
2369         spin_unlock_irqrestore(&ctrl->rport->lock, flags);
2370
2371         blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
2372         blk_cleanup_queue(ctrl->ctrl.admin_q);
2373         blk_cleanup_queue(ctrl->ctrl.fabrics_q);
2374         blk_mq_free_tag_set(&ctrl->admin_tag_set);
2375
2376         kfree(ctrl->queues);
2377
2378         put_device(ctrl->dev);
2379         nvme_fc_rport_put(ctrl->rport);
2380
2381         ida_simple_remove(&nvme_fc_ctrl_cnt, ctrl->cnum);
2382         if (ctrl->ctrl.opts)
2383                 nvmf_free_options(ctrl->ctrl.opts);
2384         kfree(ctrl);
2385 }
2386
2387 static void
2388 nvme_fc_ctrl_put(struct nvme_fc_ctrl *ctrl)
2389 {
2390         kref_put(&ctrl->ref, nvme_fc_ctrl_free);
2391 }
2392
2393 static int
2394 nvme_fc_ctrl_get(struct nvme_fc_ctrl *ctrl)
2395 {
2396         return kref_get_unless_zero(&ctrl->ref);
2397 }
2398
2399 /*
2400  * All accesses from nvme core layer done - can now free the
2401  * controller. Called after last nvme_put_ctrl() call
2402  */
2403 static void
2404 nvme_fc_nvme_ctrl_freed(struct nvme_ctrl *nctrl)
2405 {
2406         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
2407
2408         WARN_ON(nctrl != &ctrl->ctrl);
2409
2410         nvme_fc_ctrl_put(ctrl);
2411 }
2412
2413 static void
2414 nvme_fc_error_recovery(struct nvme_fc_ctrl *ctrl, char *errmsg)
2415 {
2416         int active;
2417
2418         /*
2419          * if an error (io timeout, etc) while (re)connecting,
2420          * it's an error on creating the new association.
2421          * Start the error recovery thread if it hasn't already
2422          * been started. It is expected there could be multiple
2423          * ios hitting this path before things are cleaned up.
2424          */
2425         if (ctrl->ctrl.state == NVME_CTRL_CONNECTING) {
2426                 active = atomic_xchg(&ctrl->err_work_active, 1);
2427                 if (!active && !queue_work(nvme_fc_wq, &ctrl->err_work)) {
2428                         atomic_set(&ctrl->err_work_active, 0);
2429                         WARN_ON(1);
2430                 }
2431                 return;
2432         }
2433
2434         /* Otherwise, only proceed if in LIVE state - e.g. on first error */
2435         if (ctrl->ctrl.state != NVME_CTRL_LIVE)
2436                 return;
2437
2438         dev_warn(ctrl->ctrl.device,
2439                 "NVME-FC{%d}: transport association event: %s\n",
2440                 ctrl->cnum, errmsg);
2441         dev_warn(ctrl->ctrl.device,
2442                 "NVME-FC{%d}: resetting controller\n", ctrl->cnum);
2443
2444         nvme_reset_ctrl(&ctrl->ctrl);
2445 }
2446
2447 static enum blk_eh_timer_return
2448 nvme_fc_timeout(struct request *rq, bool reserved)
2449 {
2450         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2451         struct nvme_fc_ctrl *ctrl = op->ctrl;
2452         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2453         struct nvme_command *sqe = &cmdiu->sqe;
2454
2455         /*
2456          * Attempt to abort the offending command. Command completion
2457          * will detect the aborted io and will fail the connection.
2458          */
2459         dev_info(ctrl->ctrl.device,
2460                 "NVME-FC{%d.%d}: io timeout: opcode %d fctype %d w10/11: "
2461                 "x%08x/x%08x\n",
2462                 ctrl->cnum, op->queue->qnum, sqe->common.opcode,
2463                 sqe->connect.fctype, sqe->common.cdw10, sqe->common.cdw11);
2464         if (__nvme_fc_abort_op(ctrl, op))
2465                 nvme_fc_error_recovery(ctrl, "io timeout abort failed");
2466
2467         /*
2468          * the io abort has been initiated. Have the reset timer
2469          * restarted and the abort completion will complete the io
2470          * shortly. Avoids a synchronous wait while the abort finishes.
2471          */
2472         return BLK_EH_RESET_TIMER;
2473 }
2474
2475 static int
2476 nvme_fc_map_data(struct nvme_fc_ctrl *ctrl, struct request *rq,
2477                 struct nvme_fc_fcp_op *op)
2478 {
2479         struct nvmefc_fcp_req *freq = &op->fcp_req;
2480         int ret;
2481
2482         freq->sg_cnt = 0;
2483
2484         if (!blk_rq_nr_phys_segments(rq))
2485                 return 0;
2486
2487         freq->sg_table.sgl = freq->first_sgl;
2488         ret = sg_alloc_table_chained(&freq->sg_table,
2489                         blk_rq_nr_phys_segments(rq), freq->sg_table.sgl,
2490                         NVME_INLINE_SG_CNT);
2491         if (ret)
2492                 return -ENOMEM;
2493
2494         op->nents = blk_rq_map_sg(rq->q, rq, freq->sg_table.sgl);
2495         WARN_ON(op->nents > blk_rq_nr_phys_segments(rq));
2496         freq->sg_cnt = fc_dma_map_sg(ctrl->lport->dev, freq->sg_table.sgl,
2497                                 op->nents, rq_dma_dir(rq));
2498         if (unlikely(freq->sg_cnt <= 0)) {
2499                 sg_free_table_chained(&freq->sg_table, NVME_INLINE_SG_CNT);
2500                 freq->sg_cnt = 0;
2501                 return -EFAULT;
2502         }
2503
2504         /*
2505          * TODO: blk_integrity_rq(rq)  for DIF
2506          */
2507         return 0;
2508 }
2509
2510 static void
2511 nvme_fc_unmap_data(struct nvme_fc_ctrl *ctrl, struct request *rq,
2512                 struct nvme_fc_fcp_op *op)
2513 {
2514         struct nvmefc_fcp_req *freq = &op->fcp_req;
2515
2516         if (!freq->sg_cnt)
2517                 return;
2518
2519         fc_dma_unmap_sg(ctrl->lport->dev, freq->sg_table.sgl, op->nents,
2520                         rq_dma_dir(rq));
2521
2522         sg_free_table_chained(&freq->sg_table, NVME_INLINE_SG_CNT);
2523
2524         freq->sg_cnt = 0;
2525 }
2526
2527 /*
2528  * In FC, the queue is a logical thing. At transport connect, the target
2529  * creates its "queue" and returns a handle that is to be given to the
2530  * target whenever it posts something to the corresponding SQ.  When an
2531  * SQE is sent on a SQ, FC effectively considers the SQE, or rather the
2532  * command contained within the SQE, an io, and assigns a FC exchange
2533  * to it. The SQE and the associated SQ handle are sent in the initial
2534  * CMD IU sents on the exchange. All transfers relative to the io occur
2535  * as part of the exchange.  The CQE is the last thing for the io,
2536  * which is transferred (explicitly or implicitly) with the RSP IU
2537  * sent on the exchange. After the CQE is received, the FC exchange is
2538  * terminaed and the Exchange may be used on a different io.
2539  *
2540  * The transport to LLDD api has the transport making a request for a
2541  * new fcp io request to the LLDD. The LLDD then allocates a FC exchange
2542  * resource and transfers the command. The LLDD will then process all
2543  * steps to complete the io. Upon completion, the transport done routine
2544  * is called.
2545  *
2546  * So - while the operation is outstanding to the LLDD, there is a link
2547  * level FC exchange resource that is also outstanding. This must be
2548  * considered in all cleanup operations.
2549  */
2550 static blk_status_t
2551 nvme_fc_start_fcp_op(struct nvme_fc_ctrl *ctrl, struct nvme_fc_queue *queue,
2552         struct nvme_fc_fcp_op *op, u32 data_len,
2553         enum nvmefc_fcp_datadir io_dir)
2554 {
2555         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2556         struct nvme_command *sqe = &cmdiu->sqe;
2557         int ret, opstate;
2558
2559         /*
2560          * before attempting to send the io, check to see if we believe
2561          * the target device is present
2562          */
2563         if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
2564                 return BLK_STS_RESOURCE;
2565
2566         if (!nvme_fc_ctrl_get(ctrl))
2567                 return BLK_STS_IOERR;
2568
2569         /* format the FC-NVME CMD IU and fcp_req */
2570         cmdiu->connection_id = cpu_to_be64(queue->connection_id);
2571         cmdiu->data_len = cpu_to_be32(data_len);
2572         switch (io_dir) {
2573         case NVMEFC_FCP_WRITE:
2574                 cmdiu->flags = FCNVME_CMD_FLAGS_WRITE;
2575                 break;
2576         case NVMEFC_FCP_READ:
2577                 cmdiu->flags = FCNVME_CMD_FLAGS_READ;
2578                 break;
2579         case NVMEFC_FCP_NODATA:
2580                 cmdiu->flags = 0;
2581                 break;
2582         }
2583         op->fcp_req.payload_length = data_len;
2584         op->fcp_req.io_dir = io_dir;
2585         op->fcp_req.transferred_length = 0;
2586         op->fcp_req.rcv_rsplen = 0;
2587         op->fcp_req.status = NVME_SC_SUCCESS;
2588         op->fcp_req.sqid = cpu_to_le16(queue->qnum);
2589
2590         /*
2591          * validate per fabric rules, set fields mandated by fabric spec
2592          * as well as those by FC-NVME spec.
2593          */
2594         WARN_ON_ONCE(sqe->common.metadata);
2595         sqe->common.flags |= NVME_CMD_SGL_METABUF;
2596
2597         /*
2598          * format SQE DPTR field per FC-NVME rules:
2599          *    type=0x5     Transport SGL Data Block Descriptor
2600          *    subtype=0xA  Transport-specific value
2601          *    address=0
2602          *    length=length of the data series
2603          */
2604         sqe->rw.dptr.sgl.type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2605                                         NVME_SGL_FMT_TRANSPORT_A;
2606         sqe->rw.dptr.sgl.length = cpu_to_le32(data_len);
2607         sqe->rw.dptr.sgl.addr = 0;
2608
2609         if (!(op->flags & FCOP_FLAGS_AEN)) {
2610                 ret = nvme_fc_map_data(ctrl, op->rq, op);
2611                 if (ret < 0) {
2612                         nvme_cleanup_cmd(op->rq);
2613                         nvme_fc_ctrl_put(ctrl);
2614                         if (ret == -ENOMEM || ret == -EAGAIN)
2615                                 return BLK_STS_RESOURCE;
2616                         return BLK_STS_IOERR;
2617                 }
2618         }
2619
2620         fc_dma_sync_single_for_device(ctrl->lport->dev, op->fcp_req.cmddma,
2621                                   sizeof(op->cmd_iu), DMA_TO_DEVICE);
2622
2623         atomic_set(&op->state, FCPOP_STATE_ACTIVE);
2624
2625         if (!(op->flags & FCOP_FLAGS_AEN))
2626                 blk_mq_start_request(op->rq);
2627
2628         cmdiu->csn = cpu_to_be32(atomic_inc_return(&queue->csn));
2629         ret = ctrl->lport->ops->fcp_io(&ctrl->lport->localport,
2630                                         &ctrl->rport->remoteport,
2631                                         queue->lldd_handle, &op->fcp_req);
2632
2633         if (ret) {
2634                 /*
2635                  * If the lld fails to send the command is there an issue with
2636                  * the csn value?  If the command that fails is the Connect,
2637                  * no - as the connection won't be live.  If it is a command
2638                  * post-connect, it's possible a gap in csn may be created.
2639                  * Does this matter?  As Linux initiators don't send fused
2640                  * commands, no.  The gap would exist, but as there's nothing
2641                  * that depends on csn order to be delivered on the target
2642                  * side, it shouldn't hurt.  It would be difficult for a
2643                  * target to even detect the csn gap as it has no idea when the
2644                  * cmd with the csn was supposed to arrive.
2645                  */
2646                 opstate = atomic_xchg(&op->state, FCPOP_STATE_COMPLETE);
2647                 __nvme_fc_fcpop_chk_teardowns(ctrl, op, opstate);
2648
2649                 if (!(op->flags & FCOP_FLAGS_AEN)) {
2650                         nvme_fc_unmap_data(ctrl, op->rq, op);
2651                         nvme_cleanup_cmd(op->rq);
2652                 }
2653
2654                 nvme_fc_ctrl_put(ctrl);
2655
2656                 if (ctrl->rport->remoteport.port_state == FC_OBJSTATE_ONLINE &&
2657                                 ret != -EBUSY)
2658                         return BLK_STS_IOERR;
2659
2660                 return BLK_STS_RESOURCE;
2661         }
2662
2663         return BLK_STS_OK;
2664 }
2665
2666 static blk_status_t
2667 nvme_fc_queue_rq(struct blk_mq_hw_ctx *hctx,
2668                         const struct blk_mq_queue_data *bd)
2669 {
2670         struct nvme_ns *ns = hctx->queue->queuedata;
2671         struct nvme_fc_queue *queue = hctx->driver_data;
2672         struct nvme_fc_ctrl *ctrl = queue->ctrl;
2673         struct request *rq = bd->rq;
2674         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2675         struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2676         struct nvme_command *sqe = &cmdiu->sqe;
2677         enum nvmefc_fcp_datadir io_dir;
2678         bool queue_ready = test_bit(NVME_FC_Q_LIVE, &queue->flags);
2679         u32 data_len;
2680         blk_status_t ret;
2681
2682         if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE ||
2683             !nvmf_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
2684                 return nvmf_fail_nonready_command(&queue->ctrl->ctrl, rq);
2685
2686         ret = nvme_setup_cmd(ns, rq, sqe);
2687         if (ret)
2688                 return ret;
2689
2690         /*
2691          * nvme core doesn't quite treat the rq opaquely. Commands such
2692          * as WRITE ZEROES will return a non-zero rq payload_bytes yet
2693          * there is no actual payload to be transferred.
2694          * To get it right, key data transmission on there being 1 or
2695          * more physical segments in the sg list. If there is no
2696          * physical segments, there is no payload.
2697          */
2698         if (blk_rq_nr_phys_segments(rq)) {
2699                 data_len = blk_rq_payload_bytes(rq);
2700                 io_dir = ((rq_data_dir(rq) == WRITE) ?
2701                                         NVMEFC_FCP_WRITE : NVMEFC_FCP_READ);
2702         } else {
2703                 data_len = 0;
2704                 io_dir = NVMEFC_FCP_NODATA;
2705         }
2706
2707
2708         return nvme_fc_start_fcp_op(ctrl, queue, op, data_len, io_dir);
2709 }
2710
2711 static void
2712 nvme_fc_submit_async_event(struct nvme_ctrl *arg)
2713 {
2714         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(arg);
2715         struct nvme_fc_fcp_op *aen_op;
2716         blk_status_t ret;
2717
2718         if (test_bit(FCCTRL_TERMIO, &ctrl->flags))
2719                 return;
2720
2721         aen_op = &ctrl->aen_ops[0];
2722
2723         ret = nvme_fc_start_fcp_op(ctrl, aen_op->queue, aen_op, 0,
2724                                         NVMEFC_FCP_NODATA);
2725         if (ret)
2726                 dev_err(ctrl->ctrl.device,
2727                         "failed async event work\n");
2728 }
2729
2730 static void
2731 nvme_fc_complete_rq(struct request *rq)
2732 {
2733         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2734         struct nvme_fc_ctrl *ctrl = op->ctrl;
2735
2736         atomic_set(&op->state, FCPOP_STATE_IDLE);
2737         op->flags &= ~FCOP_FLAGS_TERMIO;
2738
2739         nvme_fc_unmap_data(ctrl, rq, op);
2740         nvme_complete_rq(rq);
2741         nvme_fc_ctrl_put(ctrl);
2742 }
2743
2744 /*
2745  * This routine is used by the transport when it needs to find active
2746  * io on a queue that is to be terminated. The transport uses
2747  * blk_mq_tagset_busy_itr() to find the busy requests, which then invoke
2748  * this routine to kill them on a 1 by 1 basis.
2749  *
2750  * As FC allocates FC exchange for each io, the transport must contact
2751  * the LLDD to terminate the exchange, thus releasing the FC exchange.
2752  * After terminating the exchange the LLDD will call the transport's
2753  * normal io done path for the request, but it will have an aborted
2754  * status. The done path will return the io request back to the block
2755  * layer with an error status.
2756  */
2757 static bool
2758 nvme_fc_terminate_exchange(struct request *req, void *data, bool reserved)
2759 {
2760         struct nvme_ctrl *nctrl = data;
2761         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
2762         struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(req);
2763
2764         __nvme_fc_abort_op(ctrl, op);
2765         return true;
2766 }
2767
2768
2769 static const struct blk_mq_ops nvme_fc_mq_ops = {
2770         .queue_rq       = nvme_fc_queue_rq,
2771         .complete       = nvme_fc_complete_rq,
2772         .init_request   = nvme_fc_init_request,
2773         .exit_request   = nvme_fc_exit_request,
2774         .init_hctx      = nvme_fc_init_hctx,
2775         .timeout        = nvme_fc_timeout,
2776 };
2777
2778 static int
2779 nvme_fc_create_io_queues(struct nvme_fc_ctrl *ctrl)
2780 {
2781         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2782         unsigned int nr_io_queues;
2783         int ret;
2784
2785         nr_io_queues = min(min(opts->nr_io_queues, num_online_cpus()),
2786                                 ctrl->lport->ops->max_hw_queues);
2787         ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
2788         if (ret) {
2789                 dev_info(ctrl->ctrl.device,
2790                         "set_queue_count failed: %d\n", ret);
2791                 return ret;
2792         }
2793
2794         ctrl->ctrl.queue_count = nr_io_queues + 1;
2795         if (!nr_io_queues)
2796                 return 0;
2797
2798         nvme_fc_init_io_queues(ctrl);
2799
2800         memset(&ctrl->tag_set, 0, sizeof(ctrl->tag_set));
2801         ctrl->tag_set.ops = &nvme_fc_mq_ops;
2802         ctrl->tag_set.queue_depth = ctrl->ctrl.opts->queue_size;
2803         ctrl->tag_set.reserved_tags = 1; /* fabric connect */
2804         ctrl->tag_set.numa_node = ctrl->ctrl.numa_node;
2805         ctrl->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2806         ctrl->tag_set.cmd_size =
2807                 struct_size((struct nvme_fcp_op_w_sgl *)NULL, priv,
2808                             ctrl->lport->ops->fcprqst_priv_sz);
2809         ctrl->tag_set.driver_data = ctrl;
2810         ctrl->tag_set.nr_hw_queues = ctrl->ctrl.queue_count - 1;
2811         ctrl->tag_set.timeout = NVME_IO_TIMEOUT;
2812
2813         ret = blk_mq_alloc_tag_set(&ctrl->tag_set);
2814         if (ret)
2815                 return ret;
2816
2817         ctrl->ctrl.tagset = &ctrl->tag_set;
2818
2819         ctrl->ctrl.connect_q = blk_mq_init_queue(&ctrl->tag_set);
2820         if (IS_ERR(ctrl->ctrl.connect_q)) {
2821                 ret = PTR_ERR(ctrl->ctrl.connect_q);
2822                 goto out_free_tag_set;
2823         }
2824
2825         ret = nvme_fc_create_hw_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2826         if (ret)
2827                 goto out_cleanup_blk_queue;
2828
2829         ret = nvme_fc_connect_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2830         if (ret)
2831                 goto out_delete_hw_queues;
2832
2833         ctrl->ioq_live = true;
2834
2835         return 0;
2836
2837 out_delete_hw_queues:
2838         nvme_fc_delete_hw_io_queues(ctrl);
2839 out_cleanup_blk_queue:
2840         blk_cleanup_queue(ctrl->ctrl.connect_q);
2841 out_free_tag_set:
2842         blk_mq_free_tag_set(&ctrl->tag_set);
2843         nvme_fc_free_io_queues(ctrl);
2844
2845         /* force put free routine to ignore io queues */
2846         ctrl->ctrl.tagset = NULL;
2847
2848         return ret;
2849 }
2850
2851 static int
2852 nvme_fc_recreate_io_queues(struct nvme_fc_ctrl *ctrl)
2853 {
2854         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2855         u32 prior_ioq_cnt = ctrl->ctrl.queue_count - 1;
2856         unsigned int nr_io_queues;
2857         int ret;
2858
2859         nr_io_queues = min(min(opts->nr_io_queues, num_online_cpus()),
2860                                 ctrl->lport->ops->max_hw_queues);
2861         ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
2862         if (ret) {
2863                 dev_info(ctrl->ctrl.device,
2864                         "set_queue_count failed: %d\n", ret);
2865                 return ret;
2866         }
2867
2868         if (!nr_io_queues && prior_ioq_cnt) {
2869                 dev_info(ctrl->ctrl.device,
2870                         "Fail Reconnect: At least 1 io queue "
2871                         "required (was %d)\n", prior_ioq_cnt);
2872                 return -ENOSPC;
2873         }
2874
2875         ctrl->ctrl.queue_count = nr_io_queues + 1;
2876         /* check for io queues existing */
2877         if (ctrl->ctrl.queue_count == 1)
2878                 return 0;
2879
2880         ret = nvme_fc_create_hw_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2881         if (ret)
2882                 goto out_free_io_queues;
2883
2884         ret = nvme_fc_connect_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2885         if (ret)
2886                 goto out_delete_hw_queues;
2887
2888         if (prior_ioq_cnt != nr_io_queues)
2889                 dev_info(ctrl->ctrl.device,
2890                         "reconnect: revising io queue count from %d to %d\n",
2891                         prior_ioq_cnt, nr_io_queues);
2892         blk_mq_update_nr_hw_queues(&ctrl->tag_set, nr_io_queues);
2893
2894         return 0;
2895
2896 out_delete_hw_queues:
2897         nvme_fc_delete_hw_io_queues(ctrl);
2898 out_free_io_queues:
2899         nvme_fc_free_io_queues(ctrl);
2900         return ret;
2901 }
2902
2903 static void
2904 nvme_fc_rport_active_on_lport(struct nvme_fc_rport *rport)
2905 {
2906         struct nvme_fc_lport *lport = rport->lport;
2907
2908         atomic_inc(&lport->act_rport_cnt);
2909 }
2910
2911 static void
2912 nvme_fc_rport_inactive_on_lport(struct nvme_fc_rport *rport)
2913 {
2914         struct nvme_fc_lport *lport = rport->lport;
2915         u32 cnt;
2916
2917         cnt = atomic_dec_return(&lport->act_rport_cnt);
2918         if (cnt == 0 && lport->localport.port_state == FC_OBJSTATE_DELETED)
2919                 lport->ops->localport_delete(&lport->localport);
2920 }
2921
2922 static int
2923 nvme_fc_ctlr_active_on_rport(struct nvme_fc_ctrl *ctrl)
2924 {
2925         struct nvme_fc_rport *rport = ctrl->rport;
2926         u32 cnt;
2927
2928         if (test_and_set_bit(ASSOC_ACTIVE, &ctrl->flags))
2929                 return 1;
2930
2931         cnt = atomic_inc_return(&rport->act_ctrl_cnt);
2932         if (cnt == 1)
2933                 nvme_fc_rport_active_on_lport(rport);
2934
2935         return 0;
2936 }
2937
2938 static int
2939 nvme_fc_ctlr_inactive_on_rport(struct nvme_fc_ctrl *ctrl)
2940 {
2941         struct nvme_fc_rport *rport = ctrl->rport;
2942         struct nvme_fc_lport *lport = rport->lport;
2943         u32 cnt;
2944
2945         /* clearing of ctrl->flags ASSOC_ACTIVE bit is in association delete */
2946
2947         cnt = atomic_dec_return(&rport->act_ctrl_cnt);
2948         if (cnt == 0) {
2949                 if (rport->remoteport.port_state == FC_OBJSTATE_DELETED)
2950                         lport->ops->remoteport_delete(&rport->remoteport);
2951                 nvme_fc_rport_inactive_on_lport(rport);
2952         }
2953
2954         return 0;
2955 }
2956
2957 /*
2958  * This routine restarts the controller on the host side, and
2959  * on the link side, recreates the controller association.
2960  */
2961 static int
2962 nvme_fc_create_association(struct nvme_fc_ctrl *ctrl)
2963 {
2964         struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2965         struct nvmefc_ls_rcv_op *disls = NULL;
2966         unsigned long flags;
2967         int ret;
2968         bool changed;
2969
2970         ++ctrl->ctrl.nr_reconnects;
2971
2972         if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
2973                 return -ENODEV;
2974
2975         if (nvme_fc_ctlr_active_on_rport(ctrl))
2976                 return -ENOTUNIQ;
2977
2978         dev_info(ctrl->ctrl.device,
2979                 "NVME-FC{%d}: create association : host wwpn 0x%016llx "
2980                 " rport wwpn 0x%016llx: NQN \"%s\"\n",
2981                 ctrl->cnum, ctrl->lport->localport.port_name,
2982                 ctrl->rport->remoteport.port_name, ctrl->ctrl.opts->subsysnqn);
2983
2984         /*
2985          * Create the admin queue
2986          */
2987
2988         ret = __nvme_fc_create_hw_queue(ctrl, &ctrl->queues[0], 0,
2989                                 NVME_AQ_DEPTH);
2990         if (ret)
2991                 goto out_free_queue;
2992
2993         ret = nvme_fc_connect_admin_queue(ctrl, &ctrl->queues[0],
2994                                 NVME_AQ_DEPTH, (NVME_AQ_DEPTH / 4));
2995         if (ret)
2996                 goto out_delete_hw_queue;
2997
2998         ret = nvmf_connect_admin_queue(&ctrl->ctrl);
2999         if (ret)
3000                 goto out_disconnect_admin_queue;
3001
3002         set_bit(NVME_FC_Q_LIVE, &ctrl->queues[0].flags);
3003
3004         /*
3005          * Check controller capabilities
3006          *
3007          * todo:- add code to check if ctrl attributes changed from
3008          * prior connection values
3009          */
3010
3011         ret = nvme_enable_ctrl(&ctrl->ctrl);
3012         if (ret)
3013                 goto out_disconnect_admin_queue;
3014
3015         ctrl->ctrl.max_segments = ctrl->lport->ops->max_sgl_segments;
3016         ctrl->ctrl.max_hw_sectors = ctrl->ctrl.max_segments <<
3017                                                 (ilog2(SZ_4K) - 9);
3018
3019         blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
3020
3021         ret = nvme_init_identify(&ctrl->ctrl);
3022         if (ret)
3023                 goto out_disconnect_admin_queue;
3024
3025         /* sanity checks */
3026
3027         /* FC-NVME does not have other data in the capsule */
3028         if (ctrl->ctrl.icdoff) {
3029                 dev_err(ctrl->ctrl.device, "icdoff %d is not supported!\n",
3030                                 ctrl->ctrl.icdoff);
3031                 goto out_disconnect_admin_queue;
3032         }
3033
3034         /* FC-NVME supports normal SGL Data Block Descriptors */
3035
3036         if (opts->queue_size > ctrl->ctrl.maxcmd) {
3037                 /* warn if maxcmd is lower than queue_size */
3038                 dev_warn(ctrl->ctrl.device,
3039                         "queue_size %zu > ctrl maxcmd %u, reducing "
3040                         "to maxcmd\n",
3041                         opts->queue_size, ctrl->ctrl.maxcmd);
3042                 opts->queue_size = ctrl->ctrl.maxcmd;
3043         }
3044
3045         if (opts->queue_size > ctrl->ctrl.sqsize + 1) {
3046                 /* warn if sqsize is lower than queue_size */
3047                 dev_warn(ctrl->ctrl.device,
3048                         "queue_size %zu > ctrl sqsize %u, reducing "
3049                         "to sqsize\n",
3050                         opts->queue_size, ctrl->ctrl.sqsize + 1);
3051                 opts->queue_size = ctrl->ctrl.sqsize + 1;
3052         }
3053
3054         ret = nvme_fc_init_aen_ops(ctrl);
3055         if (ret)
3056                 goto out_term_aen_ops;
3057
3058         /*
3059          * Create the io queues
3060          */
3061
3062         if (ctrl->ctrl.queue_count > 1) {
3063                 if (!ctrl->ioq_live)
3064                         ret = nvme_fc_create_io_queues(ctrl);
3065                 else
3066                         ret = nvme_fc_recreate_io_queues(ctrl);
3067                 if (ret)
3068                         goto out_term_aen_ops;
3069         }
3070
3071         changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE);
3072
3073         ctrl->ctrl.nr_reconnects = 0;
3074
3075         if (changed)
3076                 nvme_start_ctrl(&ctrl->ctrl);
3077
3078         return 0;       /* Success */
3079
3080 out_term_aen_ops:
3081         nvme_fc_term_aen_ops(ctrl);
3082 out_disconnect_admin_queue:
3083         /* send a Disconnect(association) LS to fc-nvme target */
3084         nvme_fc_xmt_disconnect_assoc(ctrl);
3085         spin_lock_irqsave(&ctrl->lock, flags);
3086         ctrl->association_id = 0;
3087         disls = ctrl->rcv_disconn;
3088         ctrl->rcv_disconn = NULL;
3089         spin_unlock_irqrestore(&ctrl->lock, flags);
3090         if (disls)
3091                 nvme_fc_xmt_ls_rsp(disls);
3092 out_delete_hw_queue:
3093         __nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[0], 0);
3094 out_free_queue:
3095         nvme_fc_free_queue(&ctrl->queues[0]);
3096         clear_bit(ASSOC_ACTIVE, &ctrl->flags);
3097         nvme_fc_ctlr_inactive_on_rport(ctrl);
3098
3099         return ret;
3100 }
3101
3102
3103 /*
3104  * This routine runs through all outstanding commands on the association
3105  * and aborts them.  This routine is typically be called by the
3106  * delete_association routine. It is also called due to an error during
3107  * reconnect. In that scenario, it is most likely a command that initializes
3108  * the controller, including fabric Connect commands on io queues, that
3109  * may have timed out or failed thus the io must be killed for the connect
3110  * thread to see the error.
3111  */
3112 static void
3113 __nvme_fc_abort_outstanding_ios(struct nvme_fc_ctrl *ctrl, bool start_queues)
3114 {
3115         /*
3116          * If io queues are present, stop them and terminate all outstanding
3117          * ios on them. As FC allocates FC exchange for each io, the
3118          * transport must contact the LLDD to terminate the exchange,
3119          * thus releasing the FC exchange. We use blk_mq_tagset_busy_itr()
3120          * to tell us what io's are busy and invoke a transport routine
3121          * to kill them with the LLDD.  After terminating the exchange
3122          * the LLDD will call the transport's normal io done path, but it
3123          * will have an aborted status. The done path will return the
3124          * io requests back to the block layer as part of normal completions
3125          * (but with error status).
3126          */
3127         if (ctrl->ctrl.queue_count > 1) {
3128                 nvme_stop_queues(&ctrl->ctrl);
3129                 blk_mq_tagset_busy_iter(&ctrl->tag_set,
3130                                 nvme_fc_terminate_exchange, &ctrl->ctrl);
3131                 blk_mq_tagset_wait_completed_request(&ctrl->tag_set);
3132                 if (start_queues)
3133                         nvme_start_queues(&ctrl->ctrl);
3134         }
3135
3136         /*
3137          * Other transports, which don't have link-level contexts bound
3138          * to sqe's, would try to gracefully shutdown the controller by
3139          * writing the registers for shutdown and polling (call
3140          * nvme_shutdown_ctrl()). Given a bunch of i/o was potentially
3141          * just aborted and we will wait on those contexts, and given
3142          * there was no indication of how live the controlelr is on the
3143          * link, don't send more io to create more contexts for the
3144          * shutdown. Let the controller fail via keepalive failure if
3145          * its still present.
3146          */
3147
3148         /*
3149          * clean up the admin queue. Same thing as above.
3150          */
3151         blk_mq_quiesce_queue(ctrl->ctrl.admin_q);
3152         blk_mq_tagset_busy_iter(&ctrl->admin_tag_set,
3153                                 nvme_fc_terminate_exchange, &ctrl->ctrl);
3154         blk_mq_tagset_wait_completed_request(&ctrl->admin_tag_set);
3155 }
3156
3157 /*
3158  * This routine stops operation of the controller on the host side.
3159  * On the host os stack side: Admin and IO queues are stopped,
3160  *   outstanding ios on them terminated via FC ABTS.
3161  * On the link side: the association is terminated.
3162  */
3163 static void
3164 nvme_fc_delete_association(struct nvme_fc_ctrl *ctrl)
3165 {
3166         struct nvmefc_ls_rcv_op *disls = NULL;
3167         unsigned long flags;
3168
3169         if (!test_and_clear_bit(ASSOC_ACTIVE, &ctrl->flags))
3170                 return;
3171
3172         spin_lock_irqsave(&ctrl->lock, flags);
3173         set_bit(FCCTRL_TERMIO, &ctrl->flags);
3174         ctrl->iocnt = 0;
3175         spin_unlock_irqrestore(&ctrl->lock, flags);
3176
3177         __nvme_fc_abort_outstanding_ios(ctrl, false);
3178
3179         /* kill the aens as they are a separate path */
3180         nvme_fc_abort_aen_ops(ctrl);
3181
3182         /* wait for all io that had to be aborted */
3183         spin_lock_irq(&ctrl->lock);
3184         wait_event_lock_irq(ctrl->ioabort_wait, ctrl->iocnt == 0, ctrl->lock);
3185         clear_bit(FCCTRL_TERMIO, &ctrl->flags);
3186         spin_unlock_irq(&ctrl->lock);
3187
3188         nvme_fc_term_aen_ops(ctrl);
3189
3190         /*
3191          * send a Disconnect(association) LS to fc-nvme target
3192          * Note: could have been sent at top of process, but
3193          * cleaner on link traffic if after the aborts complete.
3194          * Note: if association doesn't exist, association_id will be 0
3195          */
3196         if (ctrl->association_id)
3197                 nvme_fc_xmt_disconnect_assoc(ctrl);
3198
3199         spin_lock_irqsave(&ctrl->lock, flags);
3200         ctrl->association_id = 0;
3201         disls = ctrl->rcv_disconn;
3202         ctrl->rcv_disconn = NULL;
3203         spin_unlock_irqrestore(&ctrl->lock, flags);
3204         if (disls)
3205                 /*
3206                  * if a Disconnect Request was waiting for a response, send
3207                  * now that all ABTS's have been issued (and are complete).
3208                  */
3209                 nvme_fc_xmt_ls_rsp(disls);
3210
3211         if (ctrl->ctrl.tagset) {
3212                 nvme_fc_delete_hw_io_queues(ctrl);
3213                 nvme_fc_free_io_queues(ctrl);
3214         }
3215
3216         __nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[0], 0);
3217         nvme_fc_free_queue(&ctrl->queues[0]);
3218
3219         /* re-enable the admin_q so anything new can fast fail */
3220         blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
3221
3222         /* resume the io queues so that things will fast fail */
3223         nvme_start_queues(&ctrl->ctrl);
3224
3225         nvme_fc_ctlr_inactive_on_rport(ctrl);
3226 }
3227
3228 static void
3229 nvme_fc_delete_ctrl(struct nvme_ctrl *nctrl)
3230 {
3231         struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
3232
3233         cancel_work_sync(&ctrl->err_work);
3234         cancel_delayed_work_sync(&ctrl->connect_work);
3235         /*
3236          * kill the association on the link side.  this will block
3237          * waiting for io to terminate
3238          */
3239         nvme_fc_delete_association(ctrl);
3240 }
3241
3242 static void
3243 nvme_fc_reconnect_or_delete(struct nvme_fc_ctrl *ctrl, int status)
3244 {
3245         struct nvme_fc_rport *rport = ctrl->rport;
3246         struct nvme_fc_remote_port *portptr = &rport->remoteport;
3247         unsigned long recon_delay = ctrl->ctrl.opts->reconnect_delay * HZ;
3248         bool recon = true;
3249
3250         if (ctrl->ctrl.state != NVME_CTRL_CONNECTING)
3251                 return;
3252
3253         if (portptr->port_state == FC_OBJSTATE_ONLINE)
3254                 dev_info(ctrl->ctrl.device,
3255                         "NVME-FC{%d}: reset: Reconnect attempt failed (%d)\n",
3256                         ctrl->cnum, status);
3257         else if (time_after_eq(jiffies, rport->dev_loss_end))
3258                 recon = false;
3259
3260         if (recon && nvmf_should_reconnect(&ctrl->ctrl)) {
3261                 if (portptr->port_state == FC_OBJSTATE_ONLINE)
3262                         dev_info(ctrl->ctrl.device,
3263                                 "NVME-FC{%d}: Reconnect attempt in %ld "
3264                                 "seconds\n",
3265                                 ctrl->cnum, recon_delay / HZ);
3266                 else if (time_after(jiffies + recon_delay, rport->dev_loss_end))
3267                         recon_delay = rport->dev_loss_end - jiffies;
3268
3269                 queue_delayed_work(nvme_wq, &ctrl->connect_work, recon_delay);
3270         } else {
3271                 if (portptr->port_state == FC_OBJSTATE_ONLINE)
3272                         dev_warn(ctrl->ctrl.device,
3273                                 "NVME-FC{%d}: Max reconnect attempts (%d) "
3274                                 "reached.\n",
3275                                 ctrl->cnum, ctrl->ctrl.nr_reconnects);
3276                 else
3277                         dev_warn(ctrl->ctrl.device,
3278                                 "NVME-FC{%d}: dev_loss_tmo (%d) expired "
3279                                 "while waiting for remoteport connectivity.\n",
3280                                 ctrl->cnum, min_t(int, portptr->dev_loss_tmo,
3281                                         (ctrl->ctrl.opts->max_reconnects *
3282                                          ctrl->ctrl.opts->reconnect_delay)));
3283                 WARN_ON(nvme_delete_ctrl(&ctrl->ctrl));
3284         }
3285 }
3286
3287 static void
3288 __nvme_fc_terminate_io(struct nvme_fc_ctrl *ctrl)
3289 {
3290         /*
3291          * if state is CONNECTING - the error occurred as part of a
3292          * reconnect attempt. Abort any ios on the association and
3293          * let the create_association error paths resolve things.
3294          */
3295         if (ctrl->ctrl.state == NVME_CTRL_CONNECTING) {
3296                 __nvme_fc_abort_outstanding_ios(ctrl, true);
3297                 return;
3298         }
3299
3300         /*
3301          * For any other state, kill the association. As this routine
3302          * is a common io abort routine for resetting and such, after
3303          * the association is terminated, ensure that the state is set
3304          * to CONNECTING.
3305          */
3306
3307         nvme_stop_keep_alive(&ctrl->ctrl);
3308
3309         /* will block will waiting for io to terminate */
3310         nvme_fc_delete_association(ctrl);
3311
3312         if (ctrl->ctrl.state != NVME_CTRL_CONNECTING &&
3313             !nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING))
3314                 dev_err(ctrl->ctrl.device,
3315                         "NVME-FC{%d}: error_recovery: Couldn't change state "
3316                         "to CONNECTING\n", ctrl->cnum);
3317 }
3318
3319 static void
3320 nvme_fc_reset_ctrl_work(struct work_struct *work)
3321 {
3322         struct nvme_fc_ctrl *ctrl =
3323                 container_of(work, struct nvme_fc_ctrl, ctrl.reset_work);
3324         int ret;
3325
3326         __nvme_fc_terminate_io(ctrl);
3327
3328         nvme_stop_ctrl(&ctrl->ctrl);
3329
3330         if (ctrl->rport->remoteport.port_state == FC_OBJSTATE_ONLINE)
3331                 ret = nvme_fc_create_association(ctrl);
3332         else
3333                 ret = -ENOTCONN;
3334
3335         if (ret)
3336                 nvme_fc_reconnect_or_delete(ctrl, ret);
3337         else
3338                 dev_info(ctrl->ctrl.device,
3339                         "NVME-FC{%d}: controller reset complete\n",
3340                         ctrl->cnum);
3341 }
3342
3343 static void
3344 nvme_fc_connect_err_work(struct work_struct *work)
3345 {
3346         struct nvme_fc_ctrl *ctrl =
3347                         container_of(work, struct nvme_fc_ctrl, err_work);
3348
3349         __nvme_fc_terminate_io(ctrl);
3350
3351         atomic_set(&ctrl->err_work_active, 0);
3352
3353         /*
3354          * Rescheduling the connection after recovering
3355          * from the io error is left to the reconnect work
3356          * item, which is what should have stalled waiting on
3357          * the io that had the error that scheduled this work.
3358          */
3359 }
3360
3361 static const struct nvme_ctrl_ops nvme_fc_ctrl_ops = {
3362         .name                   = "fc",
3363         .module                 = THIS_MODULE,
3364         .flags                  = NVME_F_FABRICS,
3365         .reg_read32             = nvmf_reg_read32,
3366         .reg_read64             = nvmf_reg_read64,
3367         .reg_write32            = nvmf_reg_write32,
3368         .free_ctrl              = nvme_fc_nvme_ctrl_freed,
3369         .submit_async_event     = nvme_fc_submit_async_event,
3370         .delete_ctrl            = nvme_fc_delete_ctrl,
3371         .get_address            = nvmf_get_address,
3372 };
3373
3374 static void
3375 nvme_fc_connect_ctrl_work(struct work_struct *work)
3376 {
3377         int ret;
3378
3379         struct nvme_fc_ctrl *ctrl =
3380                         container_of(to_delayed_work(work),
3381                                 struct nvme_fc_ctrl, connect_work);
3382
3383         ret = nvme_fc_create_association(ctrl);
3384         if (ret)
3385                 nvme_fc_reconnect_or_delete(ctrl, ret);
3386         else
3387                 dev_info(ctrl->ctrl.device,
3388                         "NVME-FC{%d}: controller connect complete\n",
3389                         ctrl->cnum);
3390 }
3391
3392
3393 static const struct blk_mq_ops nvme_fc_admin_mq_ops = {
3394         .queue_rq       = nvme_fc_queue_rq,
3395         .complete       = nvme_fc_complete_rq,
3396         .init_request   = nvme_fc_init_request,
3397         .exit_request   = nvme_fc_exit_request,
3398         .init_hctx      = nvme_fc_init_admin_hctx,
3399         .timeout        = nvme_fc_timeout,
3400 };
3401
3402
3403 /*
3404  * Fails a controller request if it matches an existing controller
3405  * (association) with the same tuple:
3406  * <Host NQN, Host ID, local FC port, remote FC port, SUBSYS NQN>
3407  *
3408  * The ports don't need to be compared as they are intrinsically
3409  * already matched by the port pointers supplied.
3410  */
3411 static bool
3412 nvme_fc_existing_controller(struct nvme_fc_rport *rport,
3413                 struct nvmf_ctrl_options *opts)
3414 {
3415         struct nvme_fc_ctrl *ctrl;
3416         unsigned long flags;
3417         bool found = false;
3418
3419         spin_lock_irqsave(&rport->lock, flags);
3420         list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list) {
3421                 found = nvmf_ctlr_matches_baseopts(&ctrl->ctrl, opts);
3422                 if (found)
3423                         break;
3424         }
3425         spin_unlock_irqrestore(&rport->lock, flags);
3426
3427         return found;
3428 }
3429
3430 static struct nvme_ctrl *
3431 nvme_fc_init_ctrl(struct device *dev, struct nvmf_ctrl_options *opts,
3432         struct nvme_fc_lport *lport, struct nvme_fc_rport *rport)
3433 {
3434         struct nvme_fc_ctrl *ctrl;
3435         unsigned long flags;
3436         int ret, idx;
3437
3438         if (!(rport->remoteport.port_role &
3439             (FC_PORT_ROLE_NVME_DISCOVERY | FC_PORT_ROLE_NVME_TARGET))) {
3440                 ret = -EBADR;
3441                 goto out_fail;
3442         }
3443
3444         if (!opts->duplicate_connect &&
3445             nvme_fc_existing_controller(rport, opts)) {
3446                 ret = -EALREADY;
3447                 goto out_fail;
3448         }
3449
3450         ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
3451         if (!ctrl) {
3452                 ret = -ENOMEM;
3453                 goto out_fail;
3454         }
3455
3456         idx = ida_simple_get(&nvme_fc_ctrl_cnt, 0, 0, GFP_KERNEL);
3457         if (idx < 0) {
3458                 ret = -ENOSPC;
3459                 goto out_free_ctrl;
3460         }
3461
3462         ctrl->ctrl.opts = opts;
3463         ctrl->ctrl.nr_reconnects = 0;
3464         if (lport->dev)
3465                 ctrl->ctrl.numa_node = dev_to_node(lport->dev);
3466         else
3467                 ctrl->ctrl.numa_node = NUMA_NO_NODE;
3468         INIT_LIST_HEAD(&ctrl->ctrl_list);
3469         ctrl->lport = lport;
3470         ctrl->rport = rport;
3471         ctrl->dev = lport->dev;
3472         ctrl->cnum = idx;
3473         ctrl->ioq_live = false;
3474         atomic_set(&ctrl->err_work_active, 0);
3475         init_waitqueue_head(&ctrl->ioabort_wait);
3476
3477         get_device(ctrl->dev);
3478         kref_init(&ctrl->ref);
3479
3480         INIT_WORK(&ctrl->ctrl.reset_work, nvme_fc_reset_ctrl_work);
3481         INIT_DELAYED_WORK(&ctrl->connect_work, nvme_fc_connect_ctrl_work);
3482         INIT_WORK(&ctrl->err_work, nvme_fc_connect_err_work);
3483         spin_lock_init(&ctrl->lock);
3484
3485         /* io queue count */
3486         ctrl->ctrl.queue_count = min_t(unsigned int,
3487                                 opts->nr_io_queues,
3488                                 lport->ops->max_hw_queues);
3489         ctrl->ctrl.queue_count++;       /* +1 for admin queue */
3490
3491         ctrl->ctrl.sqsize = opts->queue_size - 1;
3492         ctrl->ctrl.kato = opts->kato;
3493         ctrl->ctrl.cntlid = 0xffff;
3494
3495         ret = -ENOMEM;
3496         ctrl->queues = kcalloc(ctrl->ctrl.queue_count,
3497                                 sizeof(struct nvme_fc_queue), GFP_KERNEL);
3498         if (!ctrl->queues)
3499                 goto out_free_ida;
3500
3501         nvme_fc_init_queue(ctrl, 0);
3502
3503         memset(&ctrl->admin_tag_set, 0, sizeof(ctrl->admin_tag_set));
3504         ctrl->admin_tag_set.ops = &nvme_fc_admin_mq_ops;
3505         ctrl->admin_tag_set.queue_depth = NVME_AQ_MQ_TAG_DEPTH;
3506         ctrl->admin_tag_set.reserved_tags = 2; /* fabric connect + Keep-Alive */
3507         ctrl->admin_tag_set.numa_node = ctrl->ctrl.numa_node;
3508         ctrl->admin_tag_set.cmd_size =
3509                 struct_size((struct nvme_fcp_op_w_sgl *)NULL, priv,
3510                             ctrl->lport->ops->fcprqst_priv_sz);
3511         ctrl->admin_tag_set.driver_data = ctrl;
3512         ctrl->admin_tag_set.nr_hw_queues = 1;
3513         ctrl->admin_tag_set.timeout = ADMIN_TIMEOUT;
3514         ctrl->admin_tag_set.flags = BLK_MQ_F_NO_SCHED;
3515
3516         ret = blk_mq_alloc_tag_set(&ctrl->admin_tag_set);
3517         if (ret)
3518                 goto out_free_queues;
3519         ctrl->ctrl.admin_tagset = &ctrl->admin_tag_set;
3520
3521         ctrl->ctrl.fabrics_q = blk_mq_init_queue(&ctrl->admin_tag_set);
3522         if (IS_ERR(ctrl->ctrl.fabrics_q)) {
3523                 ret = PTR_ERR(ctrl->ctrl.fabrics_q);
3524                 goto out_free_admin_tag_set;
3525         }
3526
3527         ctrl->ctrl.admin_q = blk_mq_init_queue(&ctrl->admin_tag_set);
3528         if (IS_ERR(ctrl->ctrl.admin_q)) {
3529                 ret = PTR_ERR(ctrl->ctrl.admin_q);
3530                 goto out_cleanup_fabrics_q;
3531         }
3532
3533         /*
3534          * Would have been nice to init io queues tag set as well.
3535          * However, we require interaction from the controller
3536          * for max io queue count before we can do so.
3537          * Defer this to the connect path.
3538          */
3539
3540         ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_fc_ctrl_ops, 0);
3541         if (ret)
3542                 goto out_cleanup_admin_q;
3543
3544         /* at this point, teardown path changes to ref counting on nvme ctrl */
3545
3546         spin_lock_irqsave(&rport->lock, flags);
3547         list_add_tail(&ctrl->ctrl_list, &rport->ctrl_list);
3548         spin_unlock_irqrestore(&rport->lock, flags);
3549
3550         if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RESETTING) ||
3551             !nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
3552                 dev_err(ctrl->ctrl.device,
3553                         "NVME-FC{%d}: failed to init ctrl state\n", ctrl->cnum);
3554                 goto fail_ctrl;
3555         }
3556
3557         if (!queue_delayed_work(nvme_wq, &ctrl->connect_work, 0)) {
3558                 dev_err(ctrl->ctrl.device,
3559                         "NVME-FC{%d}: failed to schedule initial connect\n",
3560                         ctrl->cnum);
3561                 goto fail_ctrl;
3562         }
3563
3564         flush_delayed_work(&ctrl->connect_work);
3565
3566         dev_info(ctrl->ctrl.device,
3567                 "NVME-FC{%d}: new ctrl: NQN \"%s\"\n",
3568                 ctrl->cnum, ctrl->ctrl.opts->subsysnqn);
3569
3570         return &ctrl->ctrl;
3571
3572 fail_ctrl:
3573         nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_DELETING);
3574         cancel_work_sync(&ctrl->ctrl.reset_work);
3575         cancel_work_sync(&ctrl->err_work);
3576         cancel_delayed_work_sync(&ctrl->connect_work);
3577
3578         ctrl->ctrl.opts = NULL;
3579
3580         /* initiate nvme ctrl ref counting teardown */
3581         nvme_uninit_ctrl(&ctrl->ctrl);
3582
3583         /* Remove core ctrl ref. */
3584         nvme_put_ctrl(&ctrl->ctrl);
3585
3586         /* as we're past the point where we transition to the ref
3587          * counting teardown path, if we return a bad pointer here,
3588          * the calling routine, thinking it's prior to the
3589          * transition, will do an rport put. Since the teardown
3590          * path also does a rport put, we do an extra get here to
3591          * so proper order/teardown happens.
3592          */
3593         nvme_fc_rport_get(rport);
3594
3595         return ERR_PTR(-EIO);
3596
3597 out_cleanup_admin_q:
3598         blk_cleanup_queue(ctrl->ctrl.admin_q);
3599 out_cleanup_fabrics_q:
3600         blk_cleanup_queue(ctrl->ctrl.fabrics_q);
3601 out_free_admin_tag_set:
3602         blk_mq_free_tag_set(&ctrl->admin_tag_set);
3603 out_free_queues:
3604         kfree(ctrl->queues);
3605 out_free_ida:
3606         put_device(ctrl->dev);
3607         ida_simple_remove(&nvme_fc_ctrl_cnt, ctrl->cnum);
3608 out_free_ctrl:
3609         kfree(ctrl);
3610 out_fail:
3611         /* exit via here doesn't follow ctlr ref points */
3612         return ERR_PTR(ret);
3613 }
3614
3615
3616 struct nvmet_fc_traddr {
3617         u64     nn;
3618         u64     pn;
3619 };
3620
3621 static int
3622 __nvme_fc_parse_u64(substring_t *sstr, u64 *val)
3623 {
3624         u64 token64;
3625
3626         if (match_u64(sstr, &token64))
3627                 return -EINVAL;
3628         *val = token64;
3629
3630         return 0;
3631 }
3632
3633 /*
3634  * This routine validates and extracts the WWN's from the TRADDR string.
3635  * As kernel parsers need the 0x to determine number base, universally
3636  * build string to parse with 0x prefix before parsing name strings.
3637  */
3638 static int
3639 nvme_fc_parse_traddr(struct nvmet_fc_traddr *traddr, char *buf, size_t blen)
3640 {
3641         char name[2 + NVME_FC_TRADDR_HEXNAMELEN + 1];
3642         substring_t wwn = { name, &name[sizeof(name)-1] };
3643         int nnoffset, pnoffset;
3644
3645         /* validate if string is one of the 2 allowed formats */
3646         if (strnlen(buf, blen) == NVME_FC_TRADDR_MAXLENGTH &&
3647                         !strncmp(buf, "nn-0x", NVME_FC_TRADDR_OXNNLEN) &&
3648                         !strncmp(&buf[NVME_FC_TRADDR_MAX_PN_OFFSET],
3649                                 "pn-0x", NVME_FC_TRADDR_OXNNLEN)) {
3650                 nnoffset = NVME_FC_TRADDR_OXNNLEN;
3651                 pnoffset = NVME_FC_TRADDR_MAX_PN_OFFSET +
3652                                                 NVME_FC_TRADDR_OXNNLEN;
3653         } else if ((strnlen(buf, blen) == NVME_FC_TRADDR_MINLENGTH &&
3654                         !strncmp(buf, "nn-", NVME_FC_TRADDR_NNLEN) &&
3655                         !strncmp(&buf[NVME_FC_TRADDR_MIN_PN_OFFSET],
3656                                 "pn-", NVME_FC_TRADDR_NNLEN))) {
3657                 nnoffset = NVME_FC_TRADDR_NNLEN;
3658                 pnoffset = NVME_FC_TRADDR_MIN_PN_OFFSET + NVME_FC_TRADDR_NNLEN;
3659         } else
3660                 goto out_einval;
3661
3662         name[0] = '0';
3663         name[1] = 'x';
3664         name[2 + NVME_FC_TRADDR_HEXNAMELEN] = 0;
3665
3666         memcpy(&name[2], &buf[nnoffset], NVME_FC_TRADDR_HEXNAMELEN);
3667         if (__nvme_fc_parse_u64(&wwn, &traddr->nn))
3668                 goto out_einval;
3669
3670         memcpy(&name[2], &buf[pnoffset], NVME_FC_TRADDR_HEXNAMELEN);
3671         if (__nvme_fc_parse_u64(&wwn, &traddr->pn))
3672                 goto out_einval;
3673
3674         return 0;
3675
3676 out_einval:
3677         pr_warn("%s: bad traddr string\n", __func__);
3678         return -EINVAL;
3679 }
3680
3681 static struct nvme_ctrl *
3682 nvme_fc_create_ctrl(struct device *dev, struct nvmf_ctrl_options *opts)
3683 {
3684         struct nvme_fc_lport *lport;
3685         struct nvme_fc_rport *rport;
3686         struct nvme_ctrl *ctrl;
3687         struct nvmet_fc_traddr laddr = { 0L, 0L };
3688         struct nvmet_fc_traddr raddr = { 0L, 0L };
3689         unsigned long flags;
3690         int ret;
3691
3692         ret = nvme_fc_parse_traddr(&raddr, opts->traddr, NVMF_TRADDR_SIZE);
3693         if (ret || !raddr.nn || !raddr.pn)
3694                 return ERR_PTR(-EINVAL);
3695
3696         ret = nvme_fc_parse_traddr(&laddr, opts->host_traddr, NVMF_TRADDR_SIZE);
3697         if (ret || !laddr.nn || !laddr.pn)
3698                 return ERR_PTR(-EINVAL);
3699
3700         /* find the host and remote ports to connect together */
3701         spin_lock_irqsave(&nvme_fc_lock, flags);
3702         list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3703                 if (lport->localport.node_name != laddr.nn ||
3704                     lport->localport.port_name != laddr.pn ||
3705                     lport->localport.port_state != FC_OBJSTATE_ONLINE)
3706                         continue;
3707
3708                 list_for_each_entry(rport, &lport->endp_list, endp_list) {
3709                         if (rport->remoteport.node_name != raddr.nn ||
3710                             rport->remoteport.port_name != raddr.pn ||
3711                             rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
3712                                 continue;
3713
3714                         /* if fail to get reference fall through. Will error */
3715                         if (!nvme_fc_rport_get(rport))
3716                                 break;
3717
3718                         spin_unlock_irqrestore(&nvme_fc_lock, flags);
3719
3720                         ctrl = nvme_fc_init_ctrl(dev, opts, lport, rport);
3721                         if (IS_ERR(ctrl))
3722                                 nvme_fc_rport_put(rport);
3723                         return ctrl;
3724                 }
3725         }
3726         spin_unlock_irqrestore(&nvme_fc_lock, flags);
3727
3728         pr_warn("%s: %s - %s combination not found\n",
3729                 __func__, opts->traddr, opts->host_traddr);
3730         return ERR_PTR(-ENOENT);
3731 }
3732
3733
3734 static struct nvmf_transport_ops nvme_fc_transport = {
3735         .name           = "fc",
3736         .module         = THIS_MODULE,
3737         .required_opts  = NVMF_OPT_TRADDR | NVMF_OPT_HOST_TRADDR,
3738         .allowed_opts   = NVMF_OPT_RECONNECT_DELAY | NVMF_OPT_CTRL_LOSS_TMO,
3739         .create_ctrl    = nvme_fc_create_ctrl,
3740 };
3741
3742 /* Arbitrary successive failures max. With lots of subsystems could be high */
3743 #define DISCOVERY_MAX_FAIL      20
3744
3745 static ssize_t nvme_fc_nvme_discovery_store(struct device *dev,
3746                 struct device_attribute *attr, const char *buf, size_t count)
3747 {
3748         unsigned long flags;
3749         LIST_HEAD(local_disc_list);
3750         struct nvme_fc_lport *lport;
3751         struct nvme_fc_rport *rport;
3752         int failcnt = 0;
3753
3754         spin_lock_irqsave(&nvme_fc_lock, flags);
3755 restart:
3756         list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3757                 list_for_each_entry(rport, &lport->endp_list, endp_list) {
3758                         if (!nvme_fc_lport_get(lport))
3759                                 continue;
3760                         if (!nvme_fc_rport_get(rport)) {
3761                                 /*
3762                                  * This is a temporary condition. Upon restart
3763                                  * this rport will be gone from the list.
3764                                  *
3765                                  * Revert the lport put and retry.  Anything
3766                                  * added to the list already will be skipped (as
3767                                  * they are no longer list_empty).  Loops should
3768                                  * resume at rports that were not yet seen.
3769                                  */
3770                                 nvme_fc_lport_put(lport);
3771
3772                                 if (failcnt++ < DISCOVERY_MAX_FAIL)
3773                                         goto restart;
3774
3775                                 pr_err("nvme_discovery: too many reference "
3776                                        "failures\n");
3777                                 goto process_local_list;
3778                         }
3779                         if (list_empty(&rport->disc_list))
3780                                 list_add_tail(&rport->disc_list,
3781                                               &local_disc_list);
3782                 }
3783         }
3784
3785 process_local_list:
3786         while (!list_empty(&local_disc_list)) {
3787                 rport = list_first_entry(&local_disc_list,
3788                                          struct nvme_fc_rport, disc_list);
3789                 list_del_init(&rport->disc_list);
3790                 spin_unlock_irqrestore(&nvme_fc_lock, flags);
3791
3792                 lport = rport->lport;
3793                 /* signal discovery. Won't hurt if it repeats */
3794                 nvme_fc_signal_discovery_scan(lport, rport);
3795                 nvme_fc_rport_put(rport);
3796                 nvme_fc_lport_put(lport);
3797
3798                 spin_lock_irqsave(&nvme_fc_lock, flags);
3799         }
3800         spin_unlock_irqrestore(&nvme_fc_lock, flags);
3801
3802         return count;
3803 }
3804 static DEVICE_ATTR(nvme_discovery, 0200, NULL, nvme_fc_nvme_discovery_store);
3805
3806 static struct attribute *nvme_fc_attrs[] = {
3807         &dev_attr_nvme_discovery.attr,
3808         NULL
3809 };
3810
3811 static struct attribute_group nvme_fc_attr_group = {
3812         .attrs = nvme_fc_attrs,
3813 };
3814
3815 static const struct attribute_group *nvme_fc_attr_groups[] = {
3816         &nvme_fc_attr_group,
3817         NULL
3818 };
3819
3820 static struct class fc_class = {
3821         .name = "fc",
3822         .dev_groups = nvme_fc_attr_groups,
3823         .owner = THIS_MODULE,
3824 };
3825
3826 static int __init nvme_fc_init_module(void)
3827 {
3828         int ret;
3829
3830         nvme_fc_wq = alloc_workqueue("nvme_fc_wq", WQ_MEM_RECLAIM, 0);
3831         if (!nvme_fc_wq)
3832                 return -ENOMEM;
3833
3834         /*
3835          * NOTE:
3836          * It is expected that in the future the kernel will combine
3837          * the FC-isms that are currently under scsi and now being
3838          * added to by NVME into a new standalone FC class. The SCSI
3839          * and NVME protocols and their devices would be under this
3840          * new FC class.
3841          *
3842          * As we need something to post FC-specific udev events to,
3843          * specifically for nvme probe events, start by creating the
3844          * new device class.  When the new standalone FC class is
3845          * put in place, this code will move to a more generic
3846          * location for the class.
3847          */
3848         ret = class_register(&fc_class);
3849         if (ret) {
3850                 pr_err("couldn't register class fc\n");
3851                 goto out_destroy_wq;
3852         }
3853
3854         /*
3855          * Create a device for the FC-centric udev events
3856          */
3857         fc_udev_device = device_create(&fc_class, NULL, MKDEV(0, 0), NULL,
3858                                 "fc_udev_device");
3859         if (IS_ERR(fc_udev_device)) {
3860                 pr_err("couldn't create fc_udev device!\n");
3861                 ret = PTR_ERR(fc_udev_device);
3862                 goto out_destroy_class;
3863         }
3864
3865         ret = nvmf_register_transport(&nvme_fc_transport);
3866         if (ret)
3867                 goto out_destroy_device;
3868
3869         return 0;
3870
3871 out_destroy_device:
3872         device_destroy(&fc_class, MKDEV(0, 0));
3873 out_destroy_class:
3874         class_unregister(&fc_class);
3875 out_destroy_wq:
3876         destroy_workqueue(nvme_fc_wq);
3877
3878         return ret;
3879 }
3880
3881 static void
3882 nvme_fc_delete_controllers(struct nvme_fc_rport *rport)
3883 {
3884         struct nvme_fc_ctrl *ctrl;
3885
3886         spin_lock(&rport->lock);
3887         list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list) {
3888                 dev_warn(ctrl->ctrl.device,
3889                         "NVME-FC{%d}: transport unloading: deleting ctrl\n",
3890                         ctrl->cnum);
3891                 nvme_delete_ctrl(&ctrl->ctrl);
3892         }
3893         spin_unlock(&rport->lock);
3894 }
3895
3896 static void
3897 nvme_fc_cleanup_for_unload(void)
3898 {
3899         struct nvme_fc_lport *lport;
3900         struct nvme_fc_rport *rport;
3901
3902         list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3903                 list_for_each_entry(rport, &lport->endp_list, endp_list) {
3904                         nvme_fc_delete_controllers(rport);
3905                 }
3906         }
3907 }
3908
3909 static void __exit nvme_fc_exit_module(void)
3910 {
3911         unsigned long flags;
3912         bool need_cleanup = false;
3913
3914         spin_lock_irqsave(&nvme_fc_lock, flags);
3915         nvme_fc_waiting_to_unload = true;
3916         if (!list_empty(&nvme_fc_lport_list)) {
3917                 need_cleanup = true;
3918                 nvme_fc_cleanup_for_unload();
3919         }
3920         spin_unlock_irqrestore(&nvme_fc_lock, flags);
3921         if (need_cleanup) {
3922                 pr_info("%s: waiting for ctlr deletes\n", __func__);
3923                 wait_for_completion(&nvme_fc_unload_proceed);
3924                 pr_info("%s: ctrl deletes complete\n", __func__);
3925         }
3926
3927         nvmf_unregister_transport(&nvme_fc_transport);
3928
3929         ida_destroy(&nvme_fc_local_port_cnt);
3930         ida_destroy(&nvme_fc_ctrl_cnt);
3931
3932         device_destroy(&fc_class, MKDEV(0, 0));
3933         class_unregister(&fc_class);
3934         destroy_workqueue(nvme_fc_wq);
3935 }
3936
3937 module_init(nvme_fc_init_module);
3938 module_exit(nvme_fc_exit_module);
3939
3940 MODULE_LICENSE("GPL v2");