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