xref: /openbmc/linux/drivers/nvme/host/fc.c (revision 29c37341)
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_end_request(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 	aen_op = ctrl->aen_ops;
2164 	for (i = 0; i < NVME_NR_AEN_COMMANDS; i++, aen_op++) {
2165 		__nvme_fc_exit_request(ctrl, aen_op);
2166 
2167 		kfree(aen_op->fcp_req.private);
2168 		aen_op->fcp_req.private = NULL;
2169 	}
2170 }
2171 
2172 static inline void
2173 __nvme_fc_init_hctx(struct blk_mq_hw_ctx *hctx, struct nvme_fc_ctrl *ctrl,
2174 		unsigned int qidx)
2175 {
2176 	struct nvme_fc_queue *queue = &ctrl->queues[qidx];
2177 
2178 	hctx->driver_data = queue;
2179 	queue->hctx = hctx;
2180 }
2181 
2182 static int
2183 nvme_fc_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
2184 		unsigned int hctx_idx)
2185 {
2186 	struct nvme_fc_ctrl *ctrl = data;
2187 
2188 	__nvme_fc_init_hctx(hctx, ctrl, hctx_idx + 1);
2189 
2190 	return 0;
2191 }
2192 
2193 static int
2194 nvme_fc_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
2195 		unsigned int hctx_idx)
2196 {
2197 	struct nvme_fc_ctrl *ctrl = data;
2198 
2199 	__nvme_fc_init_hctx(hctx, ctrl, hctx_idx);
2200 
2201 	return 0;
2202 }
2203 
2204 static void
2205 nvme_fc_init_queue(struct nvme_fc_ctrl *ctrl, int idx)
2206 {
2207 	struct nvme_fc_queue *queue;
2208 
2209 	queue = &ctrl->queues[idx];
2210 	memset(queue, 0, sizeof(*queue));
2211 	queue->ctrl = ctrl;
2212 	queue->qnum = idx;
2213 	atomic_set(&queue->csn, 0);
2214 	queue->dev = ctrl->dev;
2215 
2216 	if (idx > 0)
2217 		queue->cmnd_capsule_len = ctrl->ctrl.ioccsz * 16;
2218 	else
2219 		queue->cmnd_capsule_len = sizeof(struct nvme_command);
2220 
2221 	/*
2222 	 * Considered whether we should allocate buffers for all SQEs
2223 	 * and CQEs and dma map them - mapping their respective entries
2224 	 * into the request structures (kernel vm addr and dma address)
2225 	 * thus the driver could use the buffers/mappings directly.
2226 	 * It only makes sense if the LLDD would use them for its
2227 	 * messaging api. It's very unlikely most adapter api's would use
2228 	 * a native NVME sqe/cqe. More reasonable if FC-NVME IU payload
2229 	 * structures were used instead.
2230 	 */
2231 }
2232 
2233 /*
2234  * This routine terminates a queue at the transport level.
2235  * The transport has already ensured that all outstanding ios on
2236  * the queue have been terminated.
2237  * The transport will send a Disconnect LS request to terminate
2238  * the queue's connection. Termination of the admin queue will also
2239  * terminate the association at the target.
2240  */
2241 static void
2242 nvme_fc_free_queue(struct nvme_fc_queue *queue)
2243 {
2244 	if (!test_and_clear_bit(NVME_FC_Q_CONNECTED, &queue->flags))
2245 		return;
2246 
2247 	clear_bit(NVME_FC_Q_LIVE, &queue->flags);
2248 	/*
2249 	 * Current implementation never disconnects a single queue.
2250 	 * It always terminates a whole association. So there is never
2251 	 * a disconnect(queue) LS sent to the target.
2252 	 */
2253 
2254 	queue->connection_id = 0;
2255 	atomic_set(&queue->csn, 0);
2256 }
2257 
2258 static void
2259 __nvme_fc_delete_hw_queue(struct nvme_fc_ctrl *ctrl,
2260 	struct nvme_fc_queue *queue, unsigned int qidx)
2261 {
2262 	if (ctrl->lport->ops->delete_queue)
2263 		ctrl->lport->ops->delete_queue(&ctrl->lport->localport, qidx,
2264 				queue->lldd_handle);
2265 	queue->lldd_handle = NULL;
2266 }
2267 
2268 static void
2269 nvme_fc_free_io_queues(struct nvme_fc_ctrl *ctrl)
2270 {
2271 	int i;
2272 
2273 	for (i = 1; i < ctrl->ctrl.queue_count; i++)
2274 		nvme_fc_free_queue(&ctrl->queues[i]);
2275 }
2276 
2277 static int
2278 __nvme_fc_create_hw_queue(struct nvme_fc_ctrl *ctrl,
2279 	struct nvme_fc_queue *queue, unsigned int qidx, u16 qsize)
2280 {
2281 	int ret = 0;
2282 
2283 	queue->lldd_handle = NULL;
2284 	if (ctrl->lport->ops->create_queue)
2285 		ret = ctrl->lport->ops->create_queue(&ctrl->lport->localport,
2286 				qidx, qsize, &queue->lldd_handle);
2287 
2288 	return ret;
2289 }
2290 
2291 static void
2292 nvme_fc_delete_hw_io_queues(struct nvme_fc_ctrl *ctrl)
2293 {
2294 	struct nvme_fc_queue *queue = &ctrl->queues[ctrl->ctrl.queue_count - 1];
2295 	int i;
2296 
2297 	for (i = ctrl->ctrl.queue_count - 1; i >= 1; i--, queue--)
2298 		__nvme_fc_delete_hw_queue(ctrl, queue, i);
2299 }
2300 
2301 static int
2302 nvme_fc_create_hw_io_queues(struct nvme_fc_ctrl *ctrl, u16 qsize)
2303 {
2304 	struct nvme_fc_queue *queue = &ctrl->queues[1];
2305 	int i, ret;
2306 
2307 	for (i = 1; i < ctrl->ctrl.queue_count; i++, queue++) {
2308 		ret = __nvme_fc_create_hw_queue(ctrl, queue, i, qsize);
2309 		if (ret)
2310 			goto delete_queues;
2311 	}
2312 
2313 	return 0;
2314 
2315 delete_queues:
2316 	for (; i >= 0; i--)
2317 		__nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[i], i);
2318 	return ret;
2319 }
2320 
2321 static int
2322 nvme_fc_connect_io_queues(struct nvme_fc_ctrl *ctrl, u16 qsize)
2323 {
2324 	int i, ret = 0;
2325 
2326 	for (i = 1; i < ctrl->ctrl.queue_count; i++) {
2327 		ret = nvme_fc_connect_queue(ctrl, &ctrl->queues[i], qsize,
2328 					(qsize / 5));
2329 		if (ret)
2330 			break;
2331 		ret = nvmf_connect_io_queue(&ctrl->ctrl, i, false);
2332 		if (ret)
2333 			break;
2334 
2335 		set_bit(NVME_FC_Q_LIVE, &ctrl->queues[i].flags);
2336 	}
2337 
2338 	return ret;
2339 }
2340 
2341 static void
2342 nvme_fc_init_io_queues(struct nvme_fc_ctrl *ctrl)
2343 {
2344 	int i;
2345 
2346 	for (i = 1; i < ctrl->ctrl.queue_count; i++)
2347 		nvme_fc_init_queue(ctrl, i);
2348 }
2349 
2350 static void
2351 nvme_fc_ctrl_free(struct kref *ref)
2352 {
2353 	struct nvme_fc_ctrl *ctrl =
2354 		container_of(ref, struct nvme_fc_ctrl, ref);
2355 	unsigned long flags;
2356 
2357 	if (ctrl->ctrl.tagset) {
2358 		blk_cleanup_queue(ctrl->ctrl.connect_q);
2359 		blk_mq_free_tag_set(&ctrl->tag_set);
2360 	}
2361 
2362 	/* remove from rport list */
2363 	spin_lock_irqsave(&ctrl->rport->lock, flags);
2364 	list_del(&ctrl->ctrl_list);
2365 	spin_unlock_irqrestore(&ctrl->rport->lock, flags);
2366 
2367 	blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
2368 	blk_cleanup_queue(ctrl->ctrl.admin_q);
2369 	blk_cleanup_queue(ctrl->ctrl.fabrics_q);
2370 	blk_mq_free_tag_set(&ctrl->admin_tag_set);
2371 
2372 	kfree(ctrl->queues);
2373 
2374 	put_device(ctrl->dev);
2375 	nvme_fc_rport_put(ctrl->rport);
2376 
2377 	ida_simple_remove(&nvme_fc_ctrl_cnt, ctrl->cnum);
2378 	if (ctrl->ctrl.opts)
2379 		nvmf_free_options(ctrl->ctrl.opts);
2380 	kfree(ctrl);
2381 }
2382 
2383 static void
2384 nvme_fc_ctrl_put(struct nvme_fc_ctrl *ctrl)
2385 {
2386 	kref_put(&ctrl->ref, nvme_fc_ctrl_free);
2387 }
2388 
2389 static int
2390 nvme_fc_ctrl_get(struct nvme_fc_ctrl *ctrl)
2391 {
2392 	return kref_get_unless_zero(&ctrl->ref);
2393 }
2394 
2395 /*
2396  * All accesses from nvme core layer done - can now free the
2397  * controller. Called after last nvme_put_ctrl() call
2398  */
2399 static void
2400 nvme_fc_nvme_ctrl_freed(struct nvme_ctrl *nctrl)
2401 {
2402 	struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
2403 
2404 	WARN_ON(nctrl != &ctrl->ctrl);
2405 
2406 	nvme_fc_ctrl_put(ctrl);
2407 }
2408 
2409 static void
2410 nvme_fc_error_recovery(struct nvme_fc_ctrl *ctrl, char *errmsg)
2411 {
2412 	int active;
2413 
2414 	/*
2415 	 * if an error (io timeout, etc) while (re)connecting,
2416 	 * it's an error on creating the new association.
2417 	 * Start the error recovery thread if it hasn't already
2418 	 * been started. It is expected there could be multiple
2419 	 * ios hitting this path before things are cleaned up.
2420 	 */
2421 	if (ctrl->ctrl.state == NVME_CTRL_CONNECTING) {
2422 		active = atomic_xchg(&ctrl->err_work_active, 1);
2423 		if (!active && !queue_work(nvme_fc_wq, &ctrl->err_work)) {
2424 			atomic_set(&ctrl->err_work_active, 0);
2425 			WARN_ON(1);
2426 		}
2427 		return;
2428 	}
2429 
2430 	/* Otherwise, only proceed if in LIVE state - e.g. on first error */
2431 	if (ctrl->ctrl.state != NVME_CTRL_LIVE)
2432 		return;
2433 
2434 	dev_warn(ctrl->ctrl.device,
2435 		"NVME-FC{%d}: transport association error detected: %s\n",
2436 		ctrl->cnum, errmsg);
2437 	dev_warn(ctrl->ctrl.device,
2438 		"NVME-FC{%d}: resetting controller\n", ctrl->cnum);
2439 
2440 	nvme_reset_ctrl(&ctrl->ctrl);
2441 }
2442 
2443 static enum blk_eh_timer_return
2444 nvme_fc_timeout(struct request *rq, bool reserved)
2445 {
2446 	struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2447 	struct nvme_fc_ctrl *ctrl = op->ctrl;
2448 
2449 	/*
2450 	 * we can't individually ABTS an io without affecting the queue,
2451 	 * thus killing the queue, and thus the association.
2452 	 * So resolve by performing a controller reset, which will stop
2453 	 * the host/io stack, terminate the association on the link,
2454 	 * and recreate an association on the link.
2455 	 */
2456 	nvme_fc_error_recovery(ctrl, "io timeout error");
2457 
2458 	/*
2459 	 * the io abort has been initiated. Have the reset timer
2460 	 * restarted and the abort completion will complete the io
2461 	 * shortly. Avoids a synchronous wait while the abort finishes.
2462 	 */
2463 	return BLK_EH_RESET_TIMER;
2464 }
2465 
2466 static int
2467 nvme_fc_map_data(struct nvme_fc_ctrl *ctrl, struct request *rq,
2468 		struct nvme_fc_fcp_op *op)
2469 {
2470 	struct nvmefc_fcp_req *freq = &op->fcp_req;
2471 	int ret;
2472 
2473 	freq->sg_cnt = 0;
2474 
2475 	if (!blk_rq_nr_phys_segments(rq))
2476 		return 0;
2477 
2478 	freq->sg_table.sgl = freq->first_sgl;
2479 	ret = sg_alloc_table_chained(&freq->sg_table,
2480 			blk_rq_nr_phys_segments(rq), freq->sg_table.sgl,
2481 			NVME_INLINE_SG_CNT);
2482 	if (ret)
2483 		return -ENOMEM;
2484 
2485 	op->nents = blk_rq_map_sg(rq->q, rq, freq->sg_table.sgl);
2486 	WARN_ON(op->nents > blk_rq_nr_phys_segments(rq));
2487 	freq->sg_cnt = fc_dma_map_sg(ctrl->lport->dev, freq->sg_table.sgl,
2488 				op->nents, rq_dma_dir(rq));
2489 	if (unlikely(freq->sg_cnt <= 0)) {
2490 		sg_free_table_chained(&freq->sg_table, NVME_INLINE_SG_CNT);
2491 		freq->sg_cnt = 0;
2492 		return -EFAULT;
2493 	}
2494 
2495 	/*
2496 	 * TODO: blk_integrity_rq(rq)  for DIF
2497 	 */
2498 	return 0;
2499 }
2500 
2501 static void
2502 nvme_fc_unmap_data(struct nvme_fc_ctrl *ctrl, struct request *rq,
2503 		struct nvme_fc_fcp_op *op)
2504 {
2505 	struct nvmefc_fcp_req *freq = &op->fcp_req;
2506 
2507 	if (!freq->sg_cnt)
2508 		return;
2509 
2510 	fc_dma_unmap_sg(ctrl->lport->dev, freq->sg_table.sgl, op->nents,
2511 			rq_dma_dir(rq));
2512 
2513 	sg_free_table_chained(&freq->sg_table, NVME_INLINE_SG_CNT);
2514 
2515 	freq->sg_cnt = 0;
2516 }
2517 
2518 /*
2519  * In FC, the queue is a logical thing. At transport connect, the target
2520  * creates its "queue" and returns a handle that is to be given to the
2521  * target whenever it posts something to the corresponding SQ.  When an
2522  * SQE is sent on a SQ, FC effectively considers the SQE, or rather the
2523  * command contained within the SQE, an io, and assigns a FC exchange
2524  * to it. The SQE and the associated SQ handle are sent in the initial
2525  * CMD IU sents on the exchange. All transfers relative to the io occur
2526  * as part of the exchange.  The CQE is the last thing for the io,
2527  * which is transferred (explicitly or implicitly) with the RSP IU
2528  * sent on the exchange. After the CQE is received, the FC exchange is
2529  * terminaed and the Exchange may be used on a different io.
2530  *
2531  * The transport to LLDD api has the transport making a request for a
2532  * new fcp io request to the LLDD. The LLDD then allocates a FC exchange
2533  * resource and transfers the command. The LLDD will then process all
2534  * steps to complete the io. Upon completion, the transport done routine
2535  * is called.
2536  *
2537  * So - while the operation is outstanding to the LLDD, there is a link
2538  * level FC exchange resource that is also outstanding. This must be
2539  * considered in all cleanup operations.
2540  */
2541 static blk_status_t
2542 nvme_fc_start_fcp_op(struct nvme_fc_ctrl *ctrl, struct nvme_fc_queue *queue,
2543 	struct nvme_fc_fcp_op *op, u32 data_len,
2544 	enum nvmefc_fcp_datadir	io_dir)
2545 {
2546 	struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2547 	struct nvme_command *sqe = &cmdiu->sqe;
2548 	int ret, opstate;
2549 
2550 	/*
2551 	 * before attempting to send the io, check to see if we believe
2552 	 * the target device is present
2553 	 */
2554 	if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
2555 		return BLK_STS_RESOURCE;
2556 
2557 	if (!nvme_fc_ctrl_get(ctrl))
2558 		return BLK_STS_IOERR;
2559 
2560 	/* format the FC-NVME CMD IU and fcp_req */
2561 	cmdiu->connection_id = cpu_to_be64(queue->connection_id);
2562 	cmdiu->data_len = cpu_to_be32(data_len);
2563 	switch (io_dir) {
2564 	case NVMEFC_FCP_WRITE:
2565 		cmdiu->flags = FCNVME_CMD_FLAGS_WRITE;
2566 		break;
2567 	case NVMEFC_FCP_READ:
2568 		cmdiu->flags = FCNVME_CMD_FLAGS_READ;
2569 		break;
2570 	case NVMEFC_FCP_NODATA:
2571 		cmdiu->flags = 0;
2572 		break;
2573 	}
2574 	op->fcp_req.payload_length = data_len;
2575 	op->fcp_req.io_dir = io_dir;
2576 	op->fcp_req.transferred_length = 0;
2577 	op->fcp_req.rcv_rsplen = 0;
2578 	op->fcp_req.status = NVME_SC_SUCCESS;
2579 	op->fcp_req.sqid = cpu_to_le16(queue->qnum);
2580 
2581 	/*
2582 	 * validate per fabric rules, set fields mandated by fabric spec
2583 	 * as well as those by FC-NVME spec.
2584 	 */
2585 	WARN_ON_ONCE(sqe->common.metadata);
2586 	sqe->common.flags |= NVME_CMD_SGL_METABUF;
2587 
2588 	/*
2589 	 * format SQE DPTR field per FC-NVME rules:
2590 	 *    type=0x5     Transport SGL Data Block Descriptor
2591 	 *    subtype=0xA  Transport-specific value
2592 	 *    address=0
2593 	 *    length=length of the data series
2594 	 */
2595 	sqe->rw.dptr.sgl.type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2596 					NVME_SGL_FMT_TRANSPORT_A;
2597 	sqe->rw.dptr.sgl.length = cpu_to_le32(data_len);
2598 	sqe->rw.dptr.sgl.addr = 0;
2599 
2600 	if (!(op->flags & FCOP_FLAGS_AEN)) {
2601 		ret = nvme_fc_map_data(ctrl, op->rq, op);
2602 		if (ret < 0) {
2603 			nvme_cleanup_cmd(op->rq);
2604 			nvme_fc_ctrl_put(ctrl);
2605 			if (ret == -ENOMEM || ret == -EAGAIN)
2606 				return BLK_STS_RESOURCE;
2607 			return BLK_STS_IOERR;
2608 		}
2609 	}
2610 
2611 	fc_dma_sync_single_for_device(ctrl->lport->dev, op->fcp_req.cmddma,
2612 				  sizeof(op->cmd_iu), DMA_TO_DEVICE);
2613 
2614 	atomic_set(&op->state, FCPOP_STATE_ACTIVE);
2615 
2616 	if (!(op->flags & FCOP_FLAGS_AEN))
2617 		blk_mq_start_request(op->rq);
2618 
2619 	cmdiu->csn = cpu_to_be32(atomic_inc_return(&queue->csn));
2620 	ret = ctrl->lport->ops->fcp_io(&ctrl->lport->localport,
2621 					&ctrl->rport->remoteport,
2622 					queue->lldd_handle, &op->fcp_req);
2623 
2624 	if (ret) {
2625 		/*
2626 		 * If the lld fails to send the command is there an issue with
2627 		 * the csn value?  If the command that fails is the Connect,
2628 		 * no - as the connection won't be live.  If it is a command
2629 		 * post-connect, it's possible a gap in csn may be created.
2630 		 * Does this matter?  As Linux initiators don't send fused
2631 		 * commands, no.  The gap would exist, but as there's nothing
2632 		 * that depends on csn order to be delivered on the target
2633 		 * side, it shouldn't hurt.  It would be difficult for a
2634 		 * target to even detect the csn gap as it has no idea when the
2635 		 * cmd with the csn was supposed to arrive.
2636 		 */
2637 		opstate = atomic_xchg(&op->state, FCPOP_STATE_COMPLETE);
2638 		__nvme_fc_fcpop_chk_teardowns(ctrl, op, opstate);
2639 
2640 		if (!(op->flags & FCOP_FLAGS_AEN)) {
2641 			nvme_fc_unmap_data(ctrl, op->rq, op);
2642 			nvme_cleanup_cmd(op->rq);
2643 		}
2644 
2645 		nvme_fc_ctrl_put(ctrl);
2646 
2647 		if (ctrl->rport->remoteport.port_state == FC_OBJSTATE_ONLINE &&
2648 				ret != -EBUSY)
2649 			return BLK_STS_IOERR;
2650 
2651 		return BLK_STS_RESOURCE;
2652 	}
2653 
2654 	return BLK_STS_OK;
2655 }
2656 
2657 static blk_status_t
2658 nvme_fc_queue_rq(struct blk_mq_hw_ctx *hctx,
2659 			const struct blk_mq_queue_data *bd)
2660 {
2661 	struct nvme_ns *ns = hctx->queue->queuedata;
2662 	struct nvme_fc_queue *queue = hctx->driver_data;
2663 	struct nvme_fc_ctrl *ctrl = queue->ctrl;
2664 	struct request *rq = bd->rq;
2665 	struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2666 	struct nvme_fc_cmd_iu *cmdiu = &op->cmd_iu;
2667 	struct nvme_command *sqe = &cmdiu->sqe;
2668 	enum nvmefc_fcp_datadir	io_dir;
2669 	bool queue_ready = test_bit(NVME_FC_Q_LIVE, &queue->flags);
2670 	u32 data_len;
2671 	blk_status_t ret;
2672 
2673 	if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE ||
2674 	    !nvmf_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
2675 		return nvmf_fail_nonready_command(&queue->ctrl->ctrl, rq);
2676 
2677 	ret = nvme_setup_cmd(ns, rq, sqe);
2678 	if (ret)
2679 		return ret;
2680 
2681 	/*
2682 	 * nvme core doesn't quite treat the rq opaquely. Commands such
2683 	 * as WRITE ZEROES will return a non-zero rq payload_bytes yet
2684 	 * there is no actual payload to be transferred.
2685 	 * To get it right, key data transmission on there being 1 or
2686 	 * more physical segments in the sg list. If there is no
2687 	 * physical segments, there is no payload.
2688 	 */
2689 	if (blk_rq_nr_phys_segments(rq)) {
2690 		data_len = blk_rq_payload_bytes(rq);
2691 		io_dir = ((rq_data_dir(rq) == WRITE) ?
2692 					NVMEFC_FCP_WRITE : NVMEFC_FCP_READ);
2693 	} else {
2694 		data_len = 0;
2695 		io_dir = NVMEFC_FCP_NODATA;
2696 	}
2697 
2698 
2699 	return nvme_fc_start_fcp_op(ctrl, queue, op, data_len, io_dir);
2700 }
2701 
2702 static void
2703 nvme_fc_submit_async_event(struct nvme_ctrl *arg)
2704 {
2705 	struct nvme_fc_ctrl *ctrl = to_fc_ctrl(arg);
2706 	struct nvme_fc_fcp_op *aen_op;
2707 	blk_status_t ret;
2708 
2709 	if (test_bit(FCCTRL_TERMIO, &ctrl->flags))
2710 		return;
2711 
2712 	aen_op = &ctrl->aen_ops[0];
2713 
2714 	ret = nvme_fc_start_fcp_op(ctrl, aen_op->queue, aen_op, 0,
2715 					NVMEFC_FCP_NODATA);
2716 	if (ret)
2717 		dev_err(ctrl->ctrl.device,
2718 			"failed async event work\n");
2719 }
2720 
2721 static void
2722 nvme_fc_complete_rq(struct request *rq)
2723 {
2724 	struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(rq);
2725 	struct nvme_fc_ctrl *ctrl = op->ctrl;
2726 
2727 	atomic_set(&op->state, FCPOP_STATE_IDLE);
2728 
2729 	nvme_fc_unmap_data(ctrl, rq, op);
2730 	nvme_complete_rq(rq);
2731 	nvme_fc_ctrl_put(ctrl);
2732 }
2733 
2734 /*
2735  * This routine is used by the transport when it needs to find active
2736  * io on a queue that is to be terminated. The transport uses
2737  * blk_mq_tagset_busy_itr() to find the busy requests, which then invoke
2738  * this routine to kill them on a 1 by 1 basis.
2739  *
2740  * As FC allocates FC exchange for each io, the transport must contact
2741  * the LLDD to terminate the exchange, thus releasing the FC exchange.
2742  * After terminating the exchange the LLDD will call the transport's
2743  * normal io done path for the request, but it will have an aborted
2744  * status. The done path will return the io request back to the block
2745  * layer with an error status.
2746  */
2747 static bool
2748 nvme_fc_terminate_exchange(struct request *req, void *data, bool reserved)
2749 {
2750 	struct nvme_ctrl *nctrl = data;
2751 	struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
2752 	struct nvme_fc_fcp_op *op = blk_mq_rq_to_pdu(req);
2753 
2754 	__nvme_fc_abort_op(ctrl, op);
2755 	return true;
2756 }
2757 
2758 
2759 static const struct blk_mq_ops nvme_fc_mq_ops = {
2760 	.queue_rq	= nvme_fc_queue_rq,
2761 	.complete	= nvme_fc_complete_rq,
2762 	.init_request	= nvme_fc_init_request,
2763 	.exit_request	= nvme_fc_exit_request,
2764 	.init_hctx	= nvme_fc_init_hctx,
2765 	.timeout	= nvme_fc_timeout,
2766 };
2767 
2768 static int
2769 nvme_fc_create_io_queues(struct nvme_fc_ctrl *ctrl)
2770 {
2771 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2772 	unsigned int nr_io_queues;
2773 	int ret;
2774 
2775 	nr_io_queues = min(min(opts->nr_io_queues, num_online_cpus()),
2776 				ctrl->lport->ops->max_hw_queues);
2777 	ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
2778 	if (ret) {
2779 		dev_info(ctrl->ctrl.device,
2780 			"set_queue_count failed: %d\n", ret);
2781 		return ret;
2782 	}
2783 
2784 	ctrl->ctrl.queue_count = nr_io_queues + 1;
2785 	if (!nr_io_queues)
2786 		return 0;
2787 
2788 	nvme_fc_init_io_queues(ctrl);
2789 
2790 	memset(&ctrl->tag_set, 0, sizeof(ctrl->tag_set));
2791 	ctrl->tag_set.ops = &nvme_fc_mq_ops;
2792 	ctrl->tag_set.queue_depth = ctrl->ctrl.opts->queue_size;
2793 	ctrl->tag_set.reserved_tags = 1; /* fabric connect */
2794 	ctrl->tag_set.numa_node = ctrl->ctrl.numa_node;
2795 	ctrl->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2796 	ctrl->tag_set.cmd_size =
2797 		struct_size((struct nvme_fcp_op_w_sgl *)NULL, priv,
2798 			    ctrl->lport->ops->fcprqst_priv_sz);
2799 	ctrl->tag_set.driver_data = ctrl;
2800 	ctrl->tag_set.nr_hw_queues = ctrl->ctrl.queue_count - 1;
2801 	ctrl->tag_set.timeout = NVME_IO_TIMEOUT;
2802 
2803 	ret = blk_mq_alloc_tag_set(&ctrl->tag_set);
2804 	if (ret)
2805 		return ret;
2806 
2807 	ctrl->ctrl.tagset = &ctrl->tag_set;
2808 
2809 	ctrl->ctrl.connect_q = blk_mq_init_queue(&ctrl->tag_set);
2810 	if (IS_ERR(ctrl->ctrl.connect_q)) {
2811 		ret = PTR_ERR(ctrl->ctrl.connect_q);
2812 		goto out_free_tag_set;
2813 	}
2814 
2815 	ret = nvme_fc_create_hw_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2816 	if (ret)
2817 		goto out_cleanup_blk_queue;
2818 
2819 	ret = nvme_fc_connect_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2820 	if (ret)
2821 		goto out_delete_hw_queues;
2822 
2823 	ctrl->ioq_live = true;
2824 
2825 	return 0;
2826 
2827 out_delete_hw_queues:
2828 	nvme_fc_delete_hw_io_queues(ctrl);
2829 out_cleanup_blk_queue:
2830 	blk_cleanup_queue(ctrl->ctrl.connect_q);
2831 out_free_tag_set:
2832 	blk_mq_free_tag_set(&ctrl->tag_set);
2833 	nvme_fc_free_io_queues(ctrl);
2834 
2835 	/* force put free routine to ignore io queues */
2836 	ctrl->ctrl.tagset = NULL;
2837 
2838 	return ret;
2839 }
2840 
2841 static int
2842 nvme_fc_recreate_io_queues(struct nvme_fc_ctrl *ctrl)
2843 {
2844 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2845 	u32 prior_ioq_cnt = ctrl->ctrl.queue_count - 1;
2846 	unsigned int nr_io_queues;
2847 	int ret;
2848 
2849 	nr_io_queues = min(min(opts->nr_io_queues, num_online_cpus()),
2850 				ctrl->lport->ops->max_hw_queues);
2851 	ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues);
2852 	if (ret) {
2853 		dev_info(ctrl->ctrl.device,
2854 			"set_queue_count failed: %d\n", ret);
2855 		return ret;
2856 	}
2857 
2858 	if (!nr_io_queues && prior_ioq_cnt) {
2859 		dev_info(ctrl->ctrl.device,
2860 			"Fail Reconnect: At least 1 io queue "
2861 			"required (was %d)\n", prior_ioq_cnt);
2862 		return -ENOSPC;
2863 	}
2864 
2865 	ctrl->ctrl.queue_count = nr_io_queues + 1;
2866 	/* check for io queues existing */
2867 	if (ctrl->ctrl.queue_count == 1)
2868 		return 0;
2869 
2870 	ret = nvme_fc_create_hw_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2871 	if (ret)
2872 		goto out_free_io_queues;
2873 
2874 	ret = nvme_fc_connect_io_queues(ctrl, ctrl->ctrl.sqsize + 1);
2875 	if (ret)
2876 		goto out_delete_hw_queues;
2877 
2878 	if (prior_ioq_cnt != nr_io_queues)
2879 		dev_info(ctrl->ctrl.device,
2880 			"reconnect: revising io queue count from %d to %d\n",
2881 			prior_ioq_cnt, nr_io_queues);
2882 	blk_mq_update_nr_hw_queues(&ctrl->tag_set, nr_io_queues);
2883 
2884 	return 0;
2885 
2886 out_delete_hw_queues:
2887 	nvme_fc_delete_hw_io_queues(ctrl);
2888 out_free_io_queues:
2889 	nvme_fc_free_io_queues(ctrl);
2890 	return ret;
2891 }
2892 
2893 static void
2894 nvme_fc_rport_active_on_lport(struct nvme_fc_rport *rport)
2895 {
2896 	struct nvme_fc_lport *lport = rport->lport;
2897 
2898 	atomic_inc(&lport->act_rport_cnt);
2899 }
2900 
2901 static void
2902 nvme_fc_rport_inactive_on_lport(struct nvme_fc_rport *rport)
2903 {
2904 	struct nvme_fc_lport *lport = rport->lport;
2905 	u32 cnt;
2906 
2907 	cnt = atomic_dec_return(&lport->act_rport_cnt);
2908 	if (cnt == 0 && lport->localport.port_state == FC_OBJSTATE_DELETED)
2909 		lport->ops->localport_delete(&lport->localport);
2910 }
2911 
2912 static int
2913 nvme_fc_ctlr_active_on_rport(struct nvme_fc_ctrl *ctrl)
2914 {
2915 	struct nvme_fc_rport *rport = ctrl->rport;
2916 	u32 cnt;
2917 
2918 	if (test_and_set_bit(ASSOC_ACTIVE, &ctrl->flags))
2919 		return 1;
2920 
2921 	cnt = atomic_inc_return(&rport->act_ctrl_cnt);
2922 	if (cnt == 1)
2923 		nvme_fc_rport_active_on_lport(rport);
2924 
2925 	return 0;
2926 }
2927 
2928 static int
2929 nvme_fc_ctlr_inactive_on_rport(struct nvme_fc_ctrl *ctrl)
2930 {
2931 	struct nvme_fc_rport *rport = ctrl->rport;
2932 	struct nvme_fc_lport *lport = rport->lport;
2933 	u32 cnt;
2934 
2935 	/* clearing of ctrl->flags ASSOC_ACTIVE bit is in association delete */
2936 
2937 	cnt = atomic_dec_return(&rport->act_ctrl_cnt);
2938 	if (cnt == 0) {
2939 		if (rport->remoteport.port_state == FC_OBJSTATE_DELETED)
2940 			lport->ops->remoteport_delete(&rport->remoteport);
2941 		nvme_fc_rport_inactive_on_lport(rport);
2942 	}
2943 
2944 	return 0;
2945 }
2946 
2947 /*
2948  * This routine restarts the controller on the host side, and
2949  * on the link side, recreates the controller association.
2950  */
2951 static int
2952 nvme_fc_create_association(struct nvme_fc_ctrl *ctrl)
2953 {
2954 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2955 	struct nvmefc_ls_rcv_op *disls = NULL;
2956 	unsigned long flags;
2957 	int ret;
2958 	bool changed;
2959 
2960 	++ctrl->ctrl.nr_reconnects;
2961 
2962 	if (ctrl->rport->remoteport.port_state != FC_OBJSTATE_ONLINE)
2963 		return -ENODEV;
2964 
2965 	if (nvme_fc_ctlr_active_on_rport(ctrl))
2966 		return -ENOTUNIQ;
2967 
2968 	dev_info(ctrl->ctrl.device,
2969 		"NVME-FC{%d}: create association : host wwpn 0x%016llx "
2970 		" rport wwpn 0x%016llx: NQN \"%s\"\n",
2971 		ctrl->cnum, ctrl->lport->localport.port_name,
2972 		ctrl->rport->remoteport.port_name, ctrl->ctrl.opts->subsysnqn);
2973 
2974 	/*
2975 	 * Create the admin queue
2976 	 */
2977 
2978 	ret = __nvme_fc_create_hw_queue(ctrl, &ctrl->queues[0], 0,
2979 				NVME_AQ_DEPTH);
2980 	if (ret)
2981 		goto out_free_queue;
2982 
2983 	ret = nvme_fc_connect_admin_queue(ctrl, &ctrl->queues[0],
2984 				NVME_AQ_DEPTH, (NVME_AQ_DEPTH / 4));
2985 	if (ret)
2986 		goto out_delete_hw_queue;
2987 
2988 	ret = nvmf_connect_admin_queue(&ctrl->ctrl);
2989 	if (ret)
2990 		goto out_disconnect_admin_queue;
2991 
2992 	set_bit(NVME_FC_Q_LIVE, &ctrl->queues[0].flags);
2993 
2994 	/*
2995 	 * Check controller capabilities
2996 	 *
2997 	 * todo:- add code to check if ctrl attributes changed from
2998 	 * prior connection values
2999 	 */
3000 
3001 	ret = nvme_enable_ctrl(&ctrl->ctrl);
3002 	if (ret)
3003 		goto out_disconnect_admin_queue;
3004 
3005 	ctrl->ctrl.max_segments = ctrl->lport->ops->max_sgl_segments;
3006 	ctrl->ctrl.max_hw_sectors = ctrl->ctrl.max_segments <<
3007 						(ilog2(SZ_4K) - 9);
3008 
3009 	blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
3010 
3011 	ret = nvme_init_identify(&ctrl->ctrl);
3012 	if (ret)
3013 		goto out_disconnect_admin_queue;
3014 
3015 	/* sanity checks */
3016 
3017 	/* FC-NVME does not have other data in the capsule */
3018 	if (ctrl->ctrl.icdoff) {
3019 		dev_err(ctrl->ctrl.device, "icdoff %d is not supported!\n",
3020 				ctrl->ctrl.icdoff);
3021 		goto out_disconnect_admin_queue;
3022 	}
3023 
3024 	/* FC-NVME supports normal SGL Data Block Descriptors */
3025 
3026 	if (opts->queue_size > ctrl->ctrl.maxcmd) {
3027 		/* warn if maxcmd is lower than queue_size */
3028 		dev_warn(ctrl->ctrl.device,
3029 			"queue_size %zu > ctrl maxcmd %u, reducing "
3030 			"to maxcmd\n",
3031 			opts->queue_size, ctrl->ctrl.maxcmd);
3032 		opts->queue_size = ctrl->ctrl.maxcmd;
3033 	}
3034 
3035 	if (opts->queue_size > ctrl->ctrl.sqsize + 1) {
3036 		/* warn if sqsize is lower than queue_size */
3037 		dev_warn(ctrl->ctrl.device,
3038 			"queue_size %zu > ctrl sqsize %u, reducing "
3039 			"to sqsize\n",
3040 			opts->queue_size, ctrl->ctrl.sqsize + 1);
3041 		opts->queue_size = ctrl->ctrl.sqsize + 1;
3042 	}
3043 
3044 	ret = nvme_fc_init_aen_ops(ctrl);
3045 	if (ret)
3046 		goto out_term_aen_ops;
3047 
3048 	/*
3049 	 * Create the io queues
3050 	 */
3051 
3052 	if (ctrl->ctrl.queue_count > 1) {
3053 		if (!ctrl->ioq_live)
3054 			ret = nvme_fc_create_io_queues(ctrl);
3055 		else
3056 			ret = nvme_fc_recreate_io_queues(ctrl);
3057 		if (ret)
3058 			goto out_term_aen_ops;
3059 	}
3060 
3061 	changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE);
3062 
3063 	ctrl->ctrl.nr_reconnects = 0;
3064 
3065 	if (changed)
3066 		nvme_start_ctrl(&ctrl->ctrl);
3067 
3068 	return 0;	/* Success */
3069 
3070 out_term_aen_ops:
3071 	nvme_fc_term_aen_ops(ctrl);
3072 out_disconnect_admin_queue:
3073 	/* send a Disconnect(association) LS to fc-nvme target */
3074 	nvme_fc_xmt_disconnect_assoc(ctrl);
3075 	spin_lock_irqsave(&ctrl->lock, flags);
3076 	ctrl->association_id = 0;
3077 	disls = ctrl->rcv_disconn;
3078 	ctrl->rcv_disconn = NULL;
3079 	spin_unlock_irqrestore(&ctrl->lock, flags);
3080 	if (disls)
3081 		nvme_fc_xmt_ls_rsp(disls);
3082 out_delete_hw_queue:
3083 	__nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[0], 0);
3084 out_free_queue:
3085 	nvme_fc_free_queue(&ctrl->queues[0]);
3086 	clear_bit(ASSOC_ACTIVE, &ctrl->flags);
3087 	nvme_fc_ctlr_inactive_on_rport(ctrl);
3088 
3089 	return ret;
3090 }
3091 
3092 /*
3093  * This routine stops operation of the controller on the host side.
3094  * On the host os stack side: Admin and IO queues are stopped,
3095  *   outstanding ios on them terminated via FC ABTS.
3096  * On the link side: the association is terminated.
3097  */
3098 static void
3099 nvme_fc_delete_association(struct nvme_fc_ctrl *ctrl)
3100 {
3101 	struct nvmefc_ls_rcv_op *disls = NULL;
3102 	unsigned long flags;
3103 
3104 	if (!test_and_clear_bit(ASSOC_ACTIVE, &ctrl->flags))
3105 		return;
3106 
3107 	spin_lock_irqsave(&ctrl->lock, flags);
3108 	set_bit(FCCTRL_TERMIO, &ctrl->flags);
3109 	ctrl->iocnt = 0;
3110 	spin_unlock_irqrestore(&ctrl->lock, flags);
3111 
3112 	/*
3113 	 * If io queues are present, stop them and terminate all outstanding
3114 	 * ios on them. As FC allocates FC exchange for each io, the
3115 	 * transport must contact the LLDD to terminate the exchange,
3116 	 * thus releasing the FC exchange. We use blk_mq_tagset_busy_itr()
3117 	 * to tell us what io's are busy and invoke a transport routine
3118 	 * to kill them with the LLDD.  After terminating the exchange
3119 	 * the LLDD will call the transport's normal io done path, but it
3120 	 * will have an aborted status. The done path will return the
3121 	 * io requests back to the block layer as part of normal completions
3122 	 * (but with error status).
3123 	 */
3124 	if (ctrl->ctrl.queue_count > 1) {
3125 		nvme_stop_queues(&ctrl->ctrl);
3126 		blk_mq_tagset_busy_iter(&ctrl->tag_set,
3127 				nvme_fc_terminate_exchange, &ctrl->ctrl);
3128 		blk_mq_tagset_wait_completed_request(&ctrl->tag_set);
3129 	}
3130 
3131 	/*
3132 	 * Other transports, which don't have link-level contexts bound
3133 	 * to sqe's, would try to gracefully shutdown the controller by
3134 	 * writing the registers for shutdown and polling (call
3135 	 * nvme_shutdown_ctrl()). Given a bunch of i/o was potentially
3136 	 * just aborted and we will wait on those contexts, and given
3137 	 * there was no indication of how live the controlelr is on the
3138 	 * link, don't send more io to create more contexts for the
3139 	 * shutdown. Let the controller fail via keepalive failure if
3140 	 * its still present.
3141 	 */
3142 
3143 	/*
3144 	 * clean up the admin queue. Same thing as above.
3145 	 * use blk_mq_tagset_busy_itr() and the transport routine to
3146 	 * terminate the exchanges.
3147 	 */
3148 	blk_mq_quiesce_queue(ctrl->ctrl.admin_q);
3149 	blk_mq_tagset_busy_iter(&ctrl->admin_tag_set,
3150 				nvme_fc_terminate_exchange, &ctrl->ctrl);
3151 	blk_mq_tagset_wait_completed_request(&ctrl->admin_tag_set);
3152 
3153 	/* kill the aens as they are a separate path */
3154 	nvme_fc_abort_aen_ops(ctrl);
3155 
3156 	/* wait for all io that had to be aborted */
3157 	spin_lock_irq(&ctrl->lock);
3158 	wait_event_lock_irq(ctrl->ioabort_wait, ctrl->iocnt == 0, ctrl->lock);
3159 	clear_bit(FCCTRL_TERMIO, &ctrl->flags);
3160 	spin_unlock_irq(&ctrl->lock);
3161 
3162 	nvme_fc_term_aen_ops(ctrl);
3163 
3164 	/*
3165 	 * send a Disconnect(association) LS to fc-nvme target
3166 	 * Note: could have been sent at top of process, but
3167 	 * cleaner on link traffic if after the aborts complete.
3168 	 * Note: if association doesn't exist, association_id will be 0
3169 	 */
3170 	if (ctrl->association_id)
3171 		nvme_fc_xmt_disconnect_assoc(ctrl);
3172 
3173 	spin_lock_irqsave(&ctrl->lock, flags);
3174 	ctrl->association_id = 0;
3175 	disls = ctrl->rcv_disconn;
3176 	ctrl->rcv_disconn = NULL;
3177 	spin_unlock_irqrestore(&ctrl->lock, flags);
3178 	if (disls)
3179 		/*
3180 		 * if a Disconnect Request was waiting for a response, send
3181 		 * now that all ABTS's have been issued (and are complete).
3182 		 */
3183 		nvme_fc_xmt_ls_rsp(disls);
3184 
3185 	if (ctrl->ctrl.tagset) {
3186 		nvme_fc_delete_hw_io_queues(ctrl);
3187 		nvme_fc_free_io_queues(ctrl);
3188 	}
3189 
3190 	__nvme_fc_delete_hw_queue(ctrl, &ctrl->queues[0], 0);
3191 	nvme_fc_free_queue(&ctrl->queues[0]);
3192 
3193 	/* re-enable the admin_q so anything new can fast fail */
3194 	blk_mq_unquiesce_queue(ctrl->ctrl.admin_q);
3195 
3196 	/* resume the io queues so that things will fast fail */
3197 	nvme_start_queues(&ctrl->ctrl);
3198 
3199 	nvme_fc_ctlr_inactive_on_rport(ctrl);
3200 }
3201 
3202 static void
3203 nvme_fc_delete_ctrl(struct nvme_ctrl *nctrl)
3204 {
3205 	struct nvme_fc_ctrl *ctrl = to_fc_ctrl(nctrl);
3206 
3207 	cancel_work_sync(&ctrl->err_work);
3208 	cancel_delayed_work_sync(&ctrl->connect_work);
3209 	/*
3210 	 * kill the association on the link side.  this will block
3211 	 * waiting for io to terminate
3212 	 */
3213 	nvme_fc_delete_association(ctrl);
3214 }
3215 
3216 static void
3217 nvme_fc_reconnect_or_delete(struct nvme_fc_ctrl *ctrl, int status)
3218 {
3219 	struct nvme_fc_rport *rport = ctrl->rport;
3220 	struct nvme_fc_remote_port *portptr = &rport->remoteport;
3221 	unsigned long recon_delay = ctrl->ctrl.opts->reconnect_delay * HZ;
3222 	bool recon = true;
3223 
3224 	if (ctrl->ctrl.state != NVME_CTRL_CONNECTING)
3225 		return;
3226 
3227 	if (portptr->port_state == FC_OBJSTATE_ONLINE)
3228 		dev_info(ctrl->ctrl.device,
3229 			"NVME-FC{%d}: reset: Reconnect attempt failed (%d)\n",
3230 			ctrl->cnum, status);
3231 	else if (time_after_eq(jiffies, rport->dev_loss_end))
3232 		recon = false;
3233 
3234 	if (recon && nvmf_should_reconnect(&ctrl->ctrl)) {
3235 		if (portptr->port_state == FC_OBJSTATE_ONLINE)
3236 			dev_info(ctrl->ctrl.device,
3237 				"NVME-FC{%d}: Reconnect attempt in %ld "
3238 				"seconds\n",
3239 				ctrl->cnum, recon_delay / HZ);
3240 		else if (time_after(jiffies + recon_delay, rport->dev_loss_end))
3241 			recon_delay = rport->dev_loss_end - jiffies;
3242 
3243 		queue_delayed_work(nvme_wq, &ctrl->connect_work, recon_delay);
3244 	} else {
3245 		if (portptr->port_state == FC_OBJSTATE_ONLINE)
3246 			dev_warn(ctrl->ctrl.device,
3247 				"NVME-FC{%d}: Max reconnect attempts (%d) "
3248 				"reached.\n",
3249 				ctrl->cnum, ctrl->ctrl.nr_reconnects);
3250 		else
3251 			dev_warn(ctrl->ctrl.device,
3252 				"NVME-FC{%d}: dev_loss_tmo (%d) expired "
3253 				"while waiting for remoteport connectivity.\n",
3254 				ctrl->cnum, min_t(int, portptr->dev_loss_tmo,
3255 					(ctrl->ctrl.opts->max_reconnects *
3256 					 ctrl->ctrl.opts->reconnect_delay)));
3257 		WARN_ON(nvme_delete_ctrl(&ctrl->ctrl));
3258 	}
3259 }
3260 
3261 static void
3262 __nvme_fc_terminate_io(struct nvme_fc_ctrl *ctrl)
3263 {
3264 	/*
3265 	 * if state is connecting - the error occurred as part of a
3266 	 * reconnect attempt. The create_association error paths will
3267 	 * clean up any outstanding io.
3268 	 *
3269 	 * if it's a different state - ensure all pending io is
3270 	 * terminated. Given this can delay while waiting for the
3271 	 * aborted io to return, we recheck adapter state below
3272 	 * before changing state.
3273 	 */
3274 	if (ctrl->ctrl.state != NVME_CTRL_CONNECTING) {
3275 		nvme_stop_keep_alive(&ctrl->ctrl);
3276 
3277 		/* will block will waiting for io to terminate */
3278 		nvme_fc_delete_association(ctrl);
3279 	}
3280 
3281 	if (ctrl->ctrl.state != NVME_CTRL_CONNECTING &&
3282 	    !nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING))
3283 		dev_err(ctrl->ctrl.device,
3284 			"NVME-FC{%d}: error_recovery: Couldn't change state "
3285 			"to CONNECTING\n", ctrl->cnum);
3286 }
3287 
3288 static void
3289 nvme_fc_reset_ctrl_work(struct work_struct *work)
3290 {
3291 	struct nvme_fc_ctrl *ctrl =
3292 		container_of(work, struct nvme_fc_ctrl, ctrl.reset_work);
3293 	int ret;
3294 
3295 	__nvme_fc_terminate_io(ctrl);
3296 
3297 	nvme_stop_ctrl(&ctrl->ctrl);
3298 
3299 	if (ctrl->rport->remoteport.port_state == FC_OBJSTATE_ONLINE)
3300 		ret = nvme_fc_create_association(ctrl);
3301 	else
3302 		ret = -ENOTCONN;
3303 
3304 	if (ret)
3305 		nvme_fc_reconnect_or_delete(ctrl, ret);
3306 	else
3307 		dev_info(ctrl->ctrl.device,
3308 			"NVME-FC{%d}: controller reset complete\n",
3309 			ctrl->cnum);
3310 }
3311 
3312 static void
3313 nvme_fc_connect_err_work(struct work_struct *work)
3314 {
3315 	struct nvme_fc_ctrl *ctrl =
3316 			container_of(work, struct nvme_fc_ctrl, err_work);
3317 
3318 	__nvme_fc_terminate_io(ctrl);
3319 
3320 	atomic_set(&ctrl->err_work_active, 0);
3321 
3322 	/*
3323 	 * Rescheduling the connection after recovering
3324 	 * from the io error is left to the reconnect work
3325 	 * item, which is what should have stalled waiting on
3326 	 * the io that had the error that scheduled this work.
3327 	 */
3328 }
3329 
3330 static const struct nvme_ctrl_ops nvme_fc_ctrl_ops = {
3331 	.name			= "fc",
3332 	.module			= THIS_MODULE,
3333 	.flags			= NVME_F_FABRICS,
3334 	.reg_read32		= nvmf_reg_read32,
3335 	.reg_read64		= nvmf_reg_read64,
3336 	.reg_write32		= nvmf_reg_write32,
3337 	.free_ctrl		= nvme_fc_nvme_ctrl_freed,
3338 	.submit_async_event	= nvme_fc_submit_async_event,
3339 	.delete_ctrl		= nvme_fc_delete_ctrl,
3340 	.get_address		= nvmf_get_address,
3341 };
3342 
3343 static void
3344 nvme_fc_connect_ctrl_work(struct work_struct *work)
3345 {
3346 	int ret;
3347 
3348 	struct nvme_fc_ctrl *ctrl =
3349 			container_of(to_delayed_work(work),
3350 				struct nvme_fc_ctrl, connect_work);
3351 
3352 	ret = nvme_fc_create_association(ctrl);
3353 	if (ret)
3354 		nvme_fc_reconnect_or_delete(ctrl, ret);
3355 	else
3356 		dev_info(ctrl->ctrl.device,
3357 			"NVME-FC{%d}: controller connect complete\n",
3358 			ctrl->cnum);
3359 }
3360 
3361 
3362 static const struct blk_mq_ops nvme_fc_admin_mq_ops = {
3363 	.queue_rq	= nvme_fc_queue_rq,
3364 	.complete	= nvme_fc_complete_rq,
3365 	.init_request	= nvme_fc_init_request,
3366 	.exit_request	= nvme_fc_exit_request,
3367 	.init_hctx	= nvme_fc_init_admin_hctx,
3368 	.timeout	= nvme_fc_timeout,
3369 };
3370 
3371 
3372 /*
3373  * Fails a controller request if it matches an existing controller
3374  * (association) with the same tuple:
3375  * <Host NQN, Host ID, local FC port, remote FC port, SUBSYS NQN>
3376  *
3377  * The ports don't need to be compared as they are intrinsically
3378  * already matched by the port pointers supplied.
3379  */
3380 static bool
3381 nvme_fc_existing_controller(struct nvme_fc_rport *rport,
3382 		struct nvmf_ctrl_options *opts)
3383 {
3384 	struct nvme_fc_ctrl *ctrl;
3385 	unsigned long flags;
3386 	bool found = false;
3387 
3388 	spin_lock_irqsave(&rport->lock, flags);
3389 	list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list) {
3390 		found = nvmf_ctlr_matches_baseopts(&ctrl->ctrl, opts);
3391 		if (found)
3392 			break;
3393 	}
3394 	spin_unlock_irqrestore(&rport->lock, flags);
3395 
3396 	return found;
3397 }
3398 
3399 static struct nvme_ctrl *
3400 nvme_fc_init_ctrl(struct device *dev, struct nvmf_ctrl_options *opts,
3401 	struct nvme_fc_lport *lport, struct nvme_fc_rport *rport)
3402 {
3403 	struct nvme_fc_ctrl *ctrl;
3404 	unsigned long flags;
3405 	int ret, idx;
3406 
3407 	if (!(rport->remoteport.port_role &
3408 	    (FC_PORT_ROLE_NVME_DISCOVERY | FC_PORT_ROLE_NVME_TARGET))) {
3409 		ret = -EBADR;
3410 		goto out_fail;
3411 	}
3412 
3413 	if (!opts->duplicate_connect &&
3414 	    nvme_fc_existing_controller(rport, opts)) {
3415 		ret = -EALREADY;
3416 		goto out_fail;
3417 	}
3418 
3419 	ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
3420 	if (!ctrl) {
3421 		ret = -ENOMEM;
3422 		goto out_fail;
3423 	}
3424 
3425 	idx = ida_simple_get(&nvme_fc_ctrl_cnt, 0, 0, GFP_KERNEL);
3426 	if (idx < 0) {
3427 		ret = -ENOSPC;
3428 		goto out_free_ctrl;
3429 	}
3430 
3431 	ctrl->ctrl.opts = opts;
3432 	ctrl->ctrl.nr_reconnects = 0;
3433 	if (lport->dev)
3434 		ctrl->ctrl.numa_node = dev_to_node(lport->dev);
3435 	else
3436 		ctrl->ctrl.numa_node = NUMA_NO_NODE;
3437 	INIT_LIST_HEAD(&ctrl->ctrl_list);
3438 	ctrl->lport = lport;
3439 	ctrl->rport = rport;
3440 	ctrl->dev = lport->dev;
3441 	ctrl->cnum = idx;
3442 	ctrl->ioq_live = false;
3443 	atomic_set(&ctrl->err_work_active, 0);
3444 	init_waitqueue_head(&ctrl->ioabort_wait);
3445 
3446 	get_device(ctrl->dev);
3447 	kref_init(&ctrl->ref);
3448 
3449 	INIT_WORK(&ctrl->ctrl.reset_work, nvme_fc_reset_ctrl_work);
3450 	INIT_DELAYED_WORK(&ctrl->connect_work, nvme_fc_connect_ctrl_work);
3451 	INIT_WORK(&ctrl->err_work, nvme_fc_connect_err_work);
3452 	spin_lock_init(&ctrl->lock);
3453 
3454 	/* io queue count */
3455 	ctrl->ctrl.queue_count = min_t(unsigned int,
3456 				opts->nr_io_queues,
3457 				lport->ops->max_hw_queues);
3458 	ctrl->ctrl.queue_count++;	/* +1 for admin queue */
3459 
3460 	ctrl->ctrl.sqsize = opts->queue_size - 1;
3461 	ctrl->ctrl.kato = opts->kato;
3462 	ctrl->ctrl.cntlid = 0xffff;
3463 
3464 	ret = -ENOMEM;
3465 	ctrl->queues = kcalloc(ctrl->ctrl.queue_count,
3466 				sizeof(struct nvme_fc_queue), GFP_KERNEL);
3467 	if (!ctrl->queues)
3468 		goto out_free_ida;
3469 
3470 	nvme_fc_init_queue(ctrl, 0);
3471 
3472 	memset(&ctrl->admin_tag_set, 0, sizeof(ctrl->admin_tag_set));
3473 	ctrl->admin_tag_set.ops = &nvme_fc_admin_mq_ops;
3474 	ctrl->admin_tag_set.queue_depth = NVME_AQ_MQ_TAG_DEPTH;
3475 	ctrl->admin_tag_set.reserved_tags = 2; /* fabric connect + Keep-Alive */
3476 	ctrl->admin_tag_set.numa_node = ctrl->ctrl.numa_node;
3477 	ctrl->admin_tag_set.cmd_size =
3478 		struct_size((struct nvme_fcp_op_w_sgl *)NULL, priv,
3479 			    ctrl->lport->ops->fcprqst_priv_sz);
3480 	ctrl->admin_tag_set.driver_data = ctrl;
3481 	ctrl->admin_tag_set.nr_hw_queues = 1;
3482 	ctrl->admin_tag_set.timeout = ADMIN_TIMEOUT;
3483 	ctrl->admin_tag_set.flags = BLK_MQ_F_NO_SCHED;
3484 
3485 	ret = blk_mq_alloc_tag_set(&ctrl->admin_tag_set);
3486 	if (ret)
3487 		goto out_free_queues;
3488 	ctrl->ctrl.admin_tagset = &ctrl->admin_tag_set;
3489 
3490 	ctrl->ctrl.fabrics_q = blk_mq_init_queue(&ctrl->admin_tag_set);
3491 	if (IS_ERR(ctrl->ctrl.fabrics_q)) {
3492 		ret = PTR_ERR(ctrl->ctrl.fabrics_q);
3493 		goto out_free_admin_tag_set;
3494 	}
3495 
3496 	ctrl->ctrl.admin_q = blk_mq_init_queue(&ctrl->admin_tag_set);
3497 	if (IS_ERR(ctrl->ctrl.admin_q)) {
3498 		ret = PTR_ERR(ctrl->ctrl.admin_q);
3499 		goto out_cleanup_fabrics_q;
3500 	}
3501 
3502 	/*
3503 	 * Would have been nice to init io queues tag set as well.
3504 	 * However, we require interaction from the controller
3505 	 * for max io queue count before we can do so.
3506 	 * Defer this to the connect path.
3507 	 */
3508 
3509 	ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_fc_ctrl_ops, 0);
3510 	if (ret)
3511 		goto out_cleanup_admin_q;
3512 
3513 	/* at this point, teardown path changes to ref counting on nvme ctrl */
3514 
3515 	spin_lock_irqsave(&rport->lock, flags);
3516 	list_add_tail(&ctrl->ctrl_list, &rport->ctrl_list);
3517 	spin_unlock_irqrestore(&rport->lock, flags);
3518 
3519 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RESETTING) ||
3520 	    !nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
3521 		dev_err(ctrl->ctrl.device,
3522 			"NVME-FC{%d}: failed to init ctrl state\n", ctrl->cnum);
3523 		goto fail_ctrl;
3524 	}
3525 
3526 	if (!queue_delayed_work(nvme_wq, &ctrl->connect_work, 0)) {
3527 		dev_err(ctrl->ctrl.device,
3528 			"NVME-FC{%d}: failed to schedule initial connect\n",
3529 			ctrl->cnum);
3530 		goto fail_ctrl;
3531 	}
3532 
3533 	flush_delayed_work(&ctrl->connect_work);
3534 
3535 	dev_info(ctrl->ctrl.device,
3536 		"NVME-FC{%d}: new ctrl: NQN \"%s\"\n",
3537 		ctrl->cnum, ctrl->ctrl.opts->subsysnqn);
3538 
3539 	return &ctrl->ctrl;
3540 
3541 fail_ctrl:
3542 	nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_DELETING);
3543 	cancel_work_sync(&ctrl->ctrl.reset_work);
3544 	cancel_work_sync(&ctrl->err_work);
3545 	cancel_delayed_work_sync(&ctrl->connect_work);
3546 
3547 	ctrl->ctrl.opts = NULL;
3548 
3549 	/* initiate nvme ctrl ref counting teardown */
3550 	nvme_uninit_ctrl(&ctrl->ctrl);
3551 
3552 	/* Remove core ctrl ref. */
3553 	nvme_put_ctrl(&ctrl->ctrl);
3554 
3555 	/* as we're past the point where we transition to the ref
3556 	 * counting teardown path, if we return a bad pointer here,
3557 	 * the calling routine, thinking it's prior to the
3558 	 * transition, will do an rport put. Since the teardown
3559 	 * path also does a rport put, we do an extra get here to
3560 	 * so proper order/teardown happens.
3561 	 */
3562 	nvme_fc_rport_get(rport);
3563 
3564 	return ERR_PTR(-EIO);
3565 
3566 out_cleanup_admin_q:
3567 	blk_cleanup_queue(ctrl->ctrl.admin_q);
3568 out_cleanup_fabrics_q:
3569 	blk_cleanup_queue(ctrl->ctrl.fabrics_q);
3570 out_free_admin_tag_set:
3571 	blk_mq_free_tag_set(&ctrl->admin_tag_set);
3572 out_free_queues:
3573 	kfree(ctrl->queues);
3574 out_free_ida:
3575 	put_device(ctrl->dev);
3576 	ida_simple_remove(&nvme_fc_ctrl_cnt, ctrl->cnum);
3577 out_free_ctrl:
3578 	kfree(ctrl);
3579 out_fail:
3580 	/* exit via here doesn't follow ctlr ref points */
3581 	return ERR_PTR(ret);
3582 }
3583 
3584 
3585 struct nvmet_fc_traddr {
3586 	u64	nn;
3587 	u64	pn;
3588 };
3589 
3590 static int
3591 __nvme_fc_parse_u64(substring_t *sstr, u64 *val)
3592 {
3593 	u64 token64;
3594 
3595 	if (match_u64(sstr, &token64))
3596 		return -EINVAL;
3597 	*val = token64;
3598 
3599 	return 0;
3600 }
3601 
3602 /*
3603  * This routine validates and extracts the WWN's from the TRADDR string.
3604  * As kernel parsers need the 0x to determine number base, universally
3605  * build string to parse with 0x prefix before parsing name strings.
3606  */
3607 static int
3608 nvme_fc_parse_traddr(struct nvmet_fc_traddr *traddr, char *buf, size_t blen)
3609 {
3610 	char name[2 + NVME_FC_TRADDR_HEXNAMELEN + 1];
3611 	substring_t wwn = { name, &name[sizeof(name)-1] };
3612 	int nnoffset, pnoffset;
3613 
3614 	/* validate if string is one of the 2 allowed formats */
3615 	if (strnlen(buf, blen) == NVME_FC_TRADDR_MAXLENGTH &&
3616 			!strncmp(buf, "nn-0x", NVME_FC_TRADDR_OXNNLEN) &&
3617 			!strncmp(&buf[NVME_FC_TRADDR_MAX_PN_OFFSET],
3618 				"pn-0x", NVME_FC_TRADDR_OXNNLEN)) {
3619 		nnoffset = NVME_FC_TRADDR_OXNNLEN;
3620 		pnoffset = NVME_FC_TRADDR_MAX_PN_OFFSET +
3621 						NVME_FC_TRADDR_OXNNLEN;
3622 	} else if ((strnlen(buf, blen) == NVME_FC_TRADDR_MINLENGTH &&
3623 			!strncmp(buf, "nn-", NVME_FC_TRADDR_NNLEN) &&
3624 			!strncmp(&buf[NVME_FC_TRADDR_MIN_PN_OFFSET],
3625 				"pn-", NVME_FC_TRADDR_NNLEN))) {
3626 		nnoffset = NVME_FC_TRADDR_NNLEN;
3627 		pnoffset = NVME_FC_TRADDR_MIN_PN_OFFSET + NVME_FC_TRADDR_NNLEN;
3628 	} else
3629 		goto out_einval;
3630 
3631 	name[0] = '0';
3632 	name[1] = 'x';
3633 	name[2 + NVME_FC_TRADDR_HEXNAMELEN] = 0;
3634 
3635 	memcpy(&name[2], &buf[nnoffset], NVME_FC_TRADDR_HEXNAMELEN);
3636 	if (__nvme_fc_parse_u64(&wwn, &traddr->nn))
3637 		goto out_einval;
3638 
3639 	memcpy(&name[2], &buf[pnoffset], NVME_FC_TRADDR_HEXNAMELEN);
3640 	if (__nvme_fc_parse_u64(&wwn, &traddr->pn))
3641 		goto out_einval;
3642 
3643 	return 0;
3644 
3645 out_einval:
3646 	pr_warn("%s: bad traddr string\n", __func__);
3647 	return -EINVAL;
3648 }
3649 
3650 static struct nvme_ctrl *
3651 nvme_fc_create_ctrl(struct device *dev, struct nvmf_ctrl_options *opts)
3652 {
3653 	struct nvme_fc_lport *lport;
3654 	struct nvme_fc_rport *rport;
3655 	struct nvme_ctrl *ctrl;
3656 	struct nvmet_fc_traddr laddr = { 0L, 0L };
3657 	struct nvmet_fc_traddr raddr = { 0L, 0L };
3658 	unsigned long flags;
3659 	int ret;
3660 
3661 	ret = nvme_fc_parse_traddr(&raddr, opts->traddr, NVMF_TRADDR_SIZE);
3662 	if (ret || !raddr.nn || !raddr.pn)
3663 		return ERR_PTR(-EINVAL);
3664 
3665 	ret = nvme_fc_parse_traddr(&laddr, opts->host_traddr, NVMF_TRADDR_SIZE);
3666 	if (ret || !laddr.nn || !laddr.pn)
3667 		return ERR_PTR(-EINVAL);
3668 
3669 	/* find the host and remote ports to connect together */
3670 	spin_lock_irqsave(&nvme_fc_lock, flags);
3671 	list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3672 		if (lport->localport.node_name != laddr.nn ||
3673 		    lport->localport.port_name != laddr.pn)
3674 			continue;
3675 
3676 		list_for_each_entry(rport, &lport->endp_list, endp_list) {
3677 			if (rport->remoteport.node_name != raddr.nn ||
3678 			    rport->remoteport.port_name != raddr.pn)
3679 				continue;
3680 
3681 			/* if fail to get reference fall through. Will error */
3682 			if (!nvme_fc_rport_get(rport))
3683 				break;
3684 
3685 			spin_unlock_irqrestore(&nvme_fc_lock, flags);
3686 
3687 			ctrl = nvme_fc_init_ctrl(dev, opts, lport, rport);
3688 			if (IS_ERR(ctrl))
3689 				nvme_fc_rport_put(rport);
3690 			return ctrl;
3691 		}
3692 	}
3693 	spin_unlock_irqrestore(&nvme_fc_lock, flags);
3694 
3695 	pr_warn("%s: %s - %s combination not found\n",
3696 		__func__, opts->traddr, opts->host_traddr);
3697 	return ERR_PTR(-ENOENT);
3698 }
3699 
3700 
3701 static struct nvmf_transport_ops nvme_fc_transport = {
3702 	.name		= "fc",
3703 	.module		= THIS_MODULE,
3704 	.required_opts	= NVMF_OPT_TRADDR | NVMF_OPT_HOST_TRADDR,
3705 	.allowed_opts	= NVMF_OPT_RECONNECT_DELAY | NVMF_OPT_CTRL_LOSS_TMO,
3706 	.create_ctrl	= nvme_fc_create_ctrl,
3707 };
3708 
3709 /* Arbitrary successive failures max. With lots of subsystems could be high */
3710 #define DISCOVERY_MAX_FAIL	20
3711 
3712 static ssize_t nvme_fc_nvme_discovery_store(struct device *dev,
3713 		struct device_attribute *attr, const char *buf, size_t count)
3714 {
3715 	unsigned long flags;
3716 	LIST_HEAD(local_disc_list);
3717 	struct nvme_fc_lport *lport;
3718 	struct nvme_fc_rport *rport;
3719 	int failcnt = 0;
3720 
3721 	spin_lock_irqsave(&nvme_fc_lock, flags);
3722 restart:
3723 	list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3724 		list_for_each_entry(rport, &lport->endp_list, endp_list) {
3725 			if (!nvme_fc_lport_get(lport))
3726 				continue;
3727 			if (!nvme_fc_rport_get(rport)) {
3728 				/*
3729 				 * This is a temporary condition. Upon restart
3730 				 * this rport will be gone from the list.
3731 				 *
3732 				 * Revert the lport put and retry.  Anything
3733 				 * added to the list already will be skipped (as
3734 				 * they are no longer list_empty).  Loops should
3735 				 * resume at rports that were not yet seen.
3736 				 */
3737 				nvme_fc_lport_put(lport);
3738 
3739 				if (failcnt++ < DISCOVERY_MAX_FAIL)
3740 					goto restart;
3741 
3742 				pr_err("nvme_discovery: too many reference "
3743 				       "failures\n");
3744 				goto process_local_list;
3745 			}
3746 			if (list_empty(&rport->disc_list))
3747 				list_add_tail(&rport->disc_list,
3748 					      &local_disc_list);
3749 		}
3750 	}
3751 
3752 process_local_list:
3753 	while (!list_empty(&local_disc_list)) {
3754 		rport = list_first_entry(&local_disc_list,
3755 					 struct nvme_fc_rport, disc_list);
3756 		list_del_init(&rport->disc_list);
3757 		spin_unlock_irqrestore(&nvme_fc_lock, flags);
3758 
3759 		lport = rport->lport;
3760 		/* signal discovery. Won't hurt if it repeats */
3761 		nvme_fc_signal_discovery_scan(lport, rport);
3762 		nvme_fc_rport_put(rport);
3763 		nvme_fc_lport_put(lport);
3764 
3765 		spin_lock_irqsave(&nvme_fc_lock, flags);
3766 	}
3767 	spin_unlock_irqrestore(&nvme_fc_lock, flags);
3768 
3769 	return count;
3770 }
3771 static DEVICE_ATTR(nvme_discovery, 0200, NULL, nvme_fc_nvme_discovery_store);
3772 
3773 static struct attribute *nvme_fc_attrs[] = {
3774 	&dev_attr_nvme_discovery.attr,
3775 	NULL
3776 };
3777 
3778 static struct attribute_group nvme_fc_attr_group = {
3779 	.attrs = nvme_fc_attrs,
3780 };
3781 
3782 static const struct attribute_group *nvme_fc_attr_groups[] = {
3783 	&nvme_fc_attr_group,
3784 	NULL
3785 };
3786 
3787 static struct class fc_class = {
3788 	.name = "fc",
3789 	.dev_groups = nvme_fc_attr_groups,
3790 	.owner = THIS_MODULE,
3791 };
3792 
3793 static int __init nvme_fc_init_module(void)
3794 {
3795 	int ret;
3796 
3797 	nvme_fc_wq = alloc_workqueue("nvme_fc_wq", WQ_MEM_RECLAIM, 0);
3798 	if (!nvme_fc_wq)
3799 		return -ENOMEM;
3800 
3801 	/*
3802 	 * NOTE:
3803 	 * It is expected that in the future the kernel will combine
3804 	 * the FC-isms that are currently under scsi and now being
3805 	 * added to by NVME into a new standalone FC class. The SCSI
3806 	 * and NVME protocols and their devices would be under this
3807 	 * new FC class.
3808 	 *
3809 	 * As we need something to post FC-specific udev events to,
3810 	 * specifically for nvme probe events, start by creating the
3811 	 * new device class.  When the new standalone FC class is
3812 	 * put in place, this code will move to a more generic
3813 	 * location for the class.
3814 	 */
3815 	ret = class_register(&fc_class);
3816 	if (ret) {
3817 		pr_err("couldn't register class fc\n");
3818 		goto out_destroy_wq;
3819 	}
3820 
3821 	/*
3822 	 * Create a device for the FC-centric udev events
3823 	 */
3824 	fc_udev_device = device_create(&fc_class, NULL, MKDEV(0, 0), NULL,
3825 				"fc_udev_device");
3826 	if (IS_ERR(fc_udev_device)) {
3827 		pr_err("couldn't create fc_udev device!\n");
3828 		ret = PTR_ERR(fc_udev_device);
3829 		goto out_destroy_class;
3830 	}
3831 
3832 	ret = nvmf_register_transport(&nvme_fc_transport);
3833 	if (ret)
3834 		goto out_destroy_device;
3835 
3836 	return 0;
3837 
3838 out_destroy_device:
3839 	device_destroy(&fc_class, MKDEV(0, 0));
3840 out_destroy_class:
3841 	class_unregister(&fc_class);
3842 out_destroy_wq:
3843 	destroy_workqueue(nvme_fc_wq);
3844 
3845 	return ret;
3846 }
3847 
3848 static void
3849 nvme_fc_delete_controllers(struct nvme_fc_rport *rport)
3850 {
3851 	struct nvme_fc_ctrl *ctrl;
3852 
3853 	spin_lock(&rport->lock);
3854 	list_for_each_entry(ctrl, &rport->ctrl_list, ctrl_list) {
3855 		dev_warn(ctrl->ctrl.device,
3856 			"NVME-FC{%d}: transport unloading: deleting ctrl\n",
3857 			ctrl->cnum);
3858 		nvme_delete_ctrl(&ctrl->ctrl);
3859 	}
3860 	spin_unlock(&rport->lock);
3861 }
3862 
3863 static void
3864 nvme_fc_cleanup_for_unload(void)
3865 {
3866 	struct nvme_fc_lport *lport;
3867 	struct nvme_fc_rport *rport;
3868 
3869 	list_for_each_entry(lport, &nvme_fc_lport_list, port_list) {
3870 		list_for_each_entry(rport, &lport->endp_list, endp_list) {
3871 			nvme_fc_delete_controllers(rport);
3872 		}
3873 	}
3874 }
3875 
3876 static void __exit nvme_fc_exit_module(void)
3877 {
3878 	unsigned long flags;
3879 	bool need_cleanup = false;
3880 
3881 	spin_lock_irqsave(&nvme_fc_lock, flags);
3882 	nvme_fc_waiting_to_unload = true;
3883 	if (!list_empty(&nvme_fc_lport_list)) {
3884 		need_cleanup = true;
3885 		nvme_fc_cleanup_for_unload();
3886 	}
3887 	spin_unlock_irqrestore(&nvme_fc_lock, flags);
3888 	if (need_cleanup) {
3889 		pr_info("%s: waiting for ctlr deletes\n", __func__);
3890 		wait_for_completion(&nvme_fc_unload_proceed);
3891 		pr_info("%s: ctrl deletes complete\n", __func__);
3892 	}
3893 
3894 	nvmf_unregister_transport(&nvme_fc_transport);
3895 
3896 	ida_destroy(&nvme_fc_local_port_cnt);
3897 	ida_destroy(&nvme_fc_ctrl_cnt);
3898 
3899 	device_destroy(&fc_class, MKDEV(0, 0));
3900 	class_unregister(&fc_class);
3901 	destroy_workqueue(nvme_fc_wq);
3902 }
3903 
3904 module_init(nvme_fc_init_module);
3905 module_exit(nvme_fc_exit_module);
3906 
3907 MODULE_LICENSE("GPL v2");
3908