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