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