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