1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/conf.h>
27 #include <sys/file.h>
28 #include <sys/ddi.h>
29 #include <sys/sunddi.h>
30 #include <sys/modctl.h>
31 #include <sys/scsi/scsi.h>
32 #include <sys/scsi/impl/scsi_reset_notify.h>
33 #include <sys/disp.h>
34 #include <sys/byteorder.h>
35 #include <sys/varargs.h>
36 #include <sys/atomic.h>
37 #include <sys/sdt.h>
38 
39 #include <stmf.h>
40 #include <stmf_ioctl.h>
41 #include <portif.h>
42 #include <fct.h>
43 #include <fctio.h>
44 #include <fct_impl.h>
45 #include <discovery.h>
46 
47 static int fct_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
48 static int fct_detach(dev_info_t *dip, ddi_detach_cmd_t cmd);
49 static int fct_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg,
50     void **result);
51 static int fct_open(dev_t *devp, int flag, int otype, cred_t *credp);
52 static int fct_close(dev_t dev, int flag, int otype, cred_t *credp);
53 static int fct_ioctl(dev_t dev, int cmd, intptr_t data, int mode,
54     cred_t *credp, int *rval);
55 static int fct_fctiocmd(intptr_t data, int mode);
56 void fct_init_kstats(fct_i_local_port_t *iport);
57 
58 static dev_info_t *fct_dip;
59 static struct cb_ops fct_cb_ops = {
60 	fct_open,			/* open */
61 	fct_close,			/* close */
62 	nodev,				/* strategy */
63 	nodev,				/* print */
64 	nodev,				/* dump */
65 	nodev,				/* read */
66 	nodev,				/* write */
67 	fct_ioctl,			/* ioctl */
68 	nodev,				/* devmap */
69 	nodev,				/* mmap */
70 	nodev,				/* segmap */
71 	nochpoll,			/* chpoll */
72 	ddi_prop_op,			/* cb_prop_op */
73 	0,				/* streamtab */
74 	D_NEW | D_MP,			/* cb_flag */
75 	CB_REV,				/* rev */
76 	nodev,				/* aread */
77 	nodev				/* awrite */
78 };
79 
80 static struct dev_ops fct_ops = {
81 	DEVO_REV,
82 	0,
83 	fct_getinfo,
84 	nulldev,		/* identify */
85 	nulldev,		/* probe */
86 	fct_attach,
87 	fct_detach,
88 	nodev,			/* reset */
89 	&fct_cb_ops,
90 	NULL,			/* bus_ops */
91 	NULL			/* power */
92 };
93 
94 #define	FCT_NAME	"COMSTAR FCT"
95 #define	FCT_MODULE_NAME	"fct"
96 
97 extern struct mod_ops mod_driverops;
98 static struct modldrv modldrv = {
99 	&mod_driverops,
100 	FCT_NAME,
101 	&fct_ops
102 };
103 
104 static struct modlinkage modlinkage = {
105 	MODREV_1,
106 	&modldrv,
107 	NULL
108 };
109 
110 static uint32_t	rportid_table_size = FCT_HASH_TABLE_SIZE;
111 static int max_cached_ncmds = FCT_MAX_CACHED_CMDS;
112 static fct_i_local_port_t *fct_iport_list = NULL;
113 static kmutex_t fct_global_mutex;
114 uint32_t fct_rscn_options = RSCN_OPTION_VERIFY;
115 
116 int
117 _init(void)
118 {
119 	int ret;
120 
121 	ret = mod_install(&modlinkage);
122 	if (ret)
123 		return (ret);
124 	/* XXX */
125 	mutex_init(&fct_global_mutex, NULL, MUTEX_DRIVER, NULL);
126 	return (ret);
127 }
128 
129 int
130 _fini(void)
131 {
132 	int ret;
133 
134 	ret = mod_remove(&modlinkage);
135 	if (ret)
136 		return (ret);
137 	/* XXX */
138 	mutex_destroy(&fct_global_mutex);
139 	return (ret);
140 }
141 
142 int
143 _info(struct modinfo *modinfop)
144 {
145 	return (mod_info(&modlinkage, modinfop));
146 }
147 
148 /* ARGSUSED */
149 static int
150 fct_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **result)
151 {
152 	switch (cmd) {
153 	case DDI_INFO_DEVT2DEVINFO:
154 		*result = fct_dip;
155 		break;
156 	case DDI_INFO_DEVT2INSTANCE:
157 		*result = (void *)(uintptr_t)ddi_get_instance(fct_dip);
158 		break;
159 	default:
160 		return (DDI_FAILURE);
161 	}
162 
163 	return (DDI_SUCCESS);
164 }
165 
166 static int
167 fct_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
168 {
169 	switch (cmd) {
170 	case DDI_ATTACH:
171 		fct_dip = dip;
172 
173 		if (ddi_create_minor_node(dip, "admin", S_IFCHR, 0,
174 		    DDI_NT_STMF_PP, 0) != DDI_SUCCESS) {
175 			break;
176 		}
177 		ddi_report_dev(dip);
178 		return (DDI_SUCCESS);
179 	}
180 
181 	return (DDI_FAILURE);
182 }
183 
184 static int
185 fct_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
186 {
187 	switch (cmd) {
188 	case DDI_DETACH:
189 		ddi_remove_minor_node(dip, 0);
190 		return (DDI_SUCCESS);
191 	}
192 
193 	return (DDI_FAILURE);
194 }
195 
196 /* ARGSUSED */
197 static int
198 fct_open(dev_t *devp, int flag, int otype, cred_t *credp)
199 {
200 	if (otype != OTYP_CHR)
201 		return (EINVAL);
202 	return (0);
203 }
204 
205 /* ARGSUSED */
206 static int
207 fct_close(dev_t dev, int flag, int otype, cred_t *credp)
208 {
209 	return (0);
210 }
211 
212 /* ARGSUSED */
213 static int
214 fct_ioctl(dev_t dev, int cmd, intptr_t data, int mode,
215     cred_t *credp, int *rval)
216 {
217 	int		ret = 0;
218 
219 	if ((cmd & 0xff000000) != FCT_IOCTL) {
220 		return (ENOTTY);
221 	}
222 
223 	if (drv_priv(credp) != 0) {
224 		return (EPERM);
225 	}
226 
227 	switch (cmd) {
228 	case FCTIO_CMD:
229 		ret = fct_fctiocmd(data, mode);
230 		break;
231 	default:
232 		ret = ENOTTY;
233 		break;
234 	}
235 
236 	return (ret);
237 }
238 
239 int
240 fct_copyin_iocdata(intptr_t data, int mode, fctio_t **fctio,
241     void **ibuf, void **abuf, void **obuf)
242 {
243 	int ret = 0;
244 
245 	*ibuf = NULL;
246 	*abuf = NULL;
247 	*obuf = NULL;
248 	*fctio = kmem_zalloc(sizeof (fctio_t), KM_SLEEP);
249 	if (ddi_copyin((void *)data, *fctio, sizeof (fctio_t), mode)) {
250 		ret = EFAULT;
251 		goto copyin_iocdata_done;
252 	}
253 
254 	if ((*fctio)->fctio_ilen) {
255 		*ibuf = kmem_zalloc((*fctio)->fctio_ilen, KM_SLEEP);
256 		if (ddi_copyin((void *)(unsigned long)(*fctio)->fctio_ibuf,
257 		    *ibuf, (*fctio)->fctio_ilen, mode)) {
258 			ret = EFAULT;
259 			goto copyin_iocdata_done;
260 		}
261 	}
262 	if ((*fctio)->fctio_alen) {
263 		*abuf = kmem_zalloc((*fctio)->fctio_alen, KM_SLEEP);
264 		if (ddi_copyin((void *)(unsigned long)(*fctio)->fctio_abuf,
265 		    *abuf, (*fctio)->fctio_alen, mode)) {
266 			ret = EFAULT;
267 			goto copyin_iocdata_done;
268 		}
269 	}
270 	if ((*fctio)->fctio_olen)
271 		*obuf = kmem_zalloc((*fctio)->fctio_olen, KM_SLEEP);
272 	if (ret == 0)
273 		return (0);
274 	ret = EFAULT;
275 copyin_iocdata_done:
276 	if (*obuf) {
277 		kmem_free(*obuf, (*fctio)->fctio_olen);
278 		*obuf = NULL;
279 	}
280 	if (*abuf) {
281 		kmem_free(*abuf, (*fctio)->fctio_alen);
282 		*abuf = NULL;
283 	}
284 	if (*ibuf) {
285 		kmem_free(*ibuf, (*fctio)->fctio_ilen);
286 		*ibuf = NULL;
287 	}
288 	kmem_free(*fctio, sizeof (fctio_t));
289 	return (ret);
290 }
291 
292 int
293 fct_copyout_iocdata(intptr_t data, int mode, fctio_t *fctio, void *obuf)
294 {
295 	int ret = 0;
296 
297 	if (fctio->fctio_olen) {
298 		ret = ddi_copyout(obuf,
299 		    (void *)(unsigned long)fctio->fctio_obuf, fctio->fctio_olen,
300 		    mode);
301 		if (ret) {
302 			return (EFAULT);
303 		}
304 	}
305 	ret = ddi_copyout(fctio, (void *)data, sizeof (fctio_t), mode);
306 	if (ret) {
307 		return (EFAULT);
308 	}
309 	return (0);
310 }
311 
312 int
313 fct_get_port_list(char *pathList, int count)
314 {
315 	fct_i_local_port_t *iport;
316 	int	i = 0, maxPorts = 0;
317 
318 	ASSERT(pathList != NULL);
319 
320 	mutex_enter(&fct_global_mutex);
321 	for (iport = fct_iport_list; iport; iport = iport->iport_next) {
322 		if (i < count)
323 			bcopy(iport->iport_port->port_pwwn,
324 			    pathList + 8 * i, 8);
325 		maxPorts ++;
326 		i++;
327 	}
328 	mutex_exit(&fct_global_mutex);
329 	return (maxPorts);
330 }
331 
332 /* invoked with fct_global_mutex locked */
333 fct_i_local_port_t *
334 fct_get_iport_per_wwn(uint8_t *pwwn)
335 {
336 	fct_i_local_port_t *iport;
337 
338 	ASSERT(mutex_owned(&fct_global_mutex));
339 	for (iport = fct_iport_list; iport; iport = iport->iport_next) {
340 		if (bcmp(iport->iport_port->port_pwwn, pwwn, 8) == 0)
341 			return (iport);
342 	}
343 	return (NULL);
344 }
345 
346 int
347 fct_get_adapter_attr(uint8_t *pwwn, fc_tgt_hba_adapter_attributes_t *hba_attr,
348     uint32_t *err_detail)
349 {
350 	fct_i_local_port_t *iport;
351 	fct_port_attrs_t *attr;
352 
353 	hba_attr->version = FCT_HBA_ADAPTER_ATTRIBUTES_VERSION;
354 	iport = fct_get_iport_per_wwn(pwwn);
355 	if (!iport) {
356 		*err_detail = FCTIO_BADWWN;
357 		return (ENXIO);
358 	}
359 
360 	attr = (fct_port_attrs_t *)kmem_zalloc(sizeof (fct_port_attrs_t),
361 	    KM_SLEEP);
362 	mutex_exit(&fct_global_mutex);
363 	iport->iport_port->port_populate_hba_details(iport->iport_port, attr);
364 	mutex_enter(&fct_global_mutex);
365 
366 	bcopy(attr->manufacturer, hba_attr->Manufacturer,
367 	    sizeof (hba_attr->Manufacturer));
368 	bcopy(attr->serial_number, hba_attr->SerialNumber,
369 	    sizeof (hba_attr->SerialNumber));
370 	bcopy(attr->model, hba_attr->Model, sizeof (hba_attr->Model));
371 	bcopy(attr->model_description, hba_attr->ModelDescription,
372 	    sizeof (hba_attr->ModelDescription));
373 	if (iport->iport_port->port_sym_node_name)
374 		bcopy(iport->iport_port->port_sym_node_name,
375 		    hba_attr->NodeSymbolicName,
376 		    strlen(iport->iport_port->port_sym_node_name));
377 	else
378 		bcopy(utsname.nodename, hba_attr->NodeSymbolicName,
379 		    strlen(utsname.nodename));
380 	bcopy(attr->hardware_version, hba_attr->HardwareVersion,
381 	    sizeof (hba_attr->HardwareVersion));
382 	bcopy(attr->option_rom_version, hba_attr->OptionROMVersion,
383 	    sizeof (hba_attr->OptionROMVersion));
384 	bcopy(attr->firmware_version, hba_attr->FirmwareVersion,
385 	    sizeof (hba_attr->FirmwareVersion));
386 	hba_attr->VendorSpecificID = attr->vendor_specific_id;
387 	bcopy(iport->iport_port->port_nwwn, hba_attr->NodeWWN,
388 	    sizeof (hba_attr->NodeWWN));
389 
390 	bcopy(attr->driver_name, hba_attr->DriverName,
391 	    sizeof (hba_attr->DriverName));
392 	bcopy(attr->driver_version, hba_attr->DriverVersion,
393 	    sizeof (hba_attr->DriverVersion));
394 
395 
396 	/* hba_attr->NumberOfPorts = fct_count_fru_ports(iport); */
397 	hba_attr->NumberOfPorts = 1;
398 
399 	kmem_free(attr, sizeof (fct_port_attrs_t));
400 	return (0);
401 }
402 
403 int
404 fct_get_adapter_port_attr(fct_i_local_port_t *ilport, uint8_t *pwwn,
405     fc_tgt_hba_port_attributes_t *port_attr, uint32_t *err_detail)
406 {
407 	fct_i_local_port_t *iport = ilport;
408 	fct_i_remote_port_t *irp = NULL;
409 	fct_port_attrs_t *attr;
410 	int i = 0;
411 
412 	port_attr->version = FCT_HBA_PORT_ATTRIBUTES_VERSION;
413 
414 	if (!ilport) {
415 		iport = fct_get_iport_per_wwn(pwwn);
416 		if (!iport) {
417 			*err_detail = FCTIO_BADWWN;
418 			return (ENXIO);
419 		}
420 	}
421 
422 	attr = (fct_port_attrs_t *)kmem_zalloc(sizeof (fct_port_attrs_t),
423 	    KM_SLEEP);
424 	mutex_exit(&fct_global_mutex);
425 	iport->iport_port->port_populate_hba_details(iport->iport_port, attr);
426 	mutex_enter(&fct_global_mutex);
427 
428 	port_attr->lastChange = iport->iport_last_change;
429 	bcopy(iport->iport_port->port_nwwn, port_attr->NodeWWN,
430 	    sizeof (port_attr->NodeWWN));
431 	bcopy(iport->iport_port->port_pwwn, port_attr->PortWWN,
432 	    sizeof (port_attr->PortWWN));
433 	bzero(port_attr->FabricName, sizeof (port_attr->FabricName));
434 	port_attr->PortFcId = iport->iport_link_info.portid;
435 	if ((iport->iport_link_state & S_LINK_ONLINE) ||
436 	    (iport->iport_link_state & S_RCVD_LINK_UP)) {
437 		port_attr->PortState = FC_HBA_PORTSTATE_ONLINE;
438 	} else {
439 		port_attr->PortState = FC_HBA_PORTSTATE_OFFLINE;
440 	}
441 	switch (iport->iport_link_info.port_topology) {
442 		case PORT_TOPOLOGY_PT_TO_PT:
443 			port_attr->PortType = FC_HBA_PORTTYPE_PTP;
444 			break;
445 		case PORT_TOPOLOGY_PRIVATE_LOOP:
446 			port_attr->PortType = FC_HBA_PORTTYPE_LPORT;
447 			break;
448 		case PORT_TOPOLOGY_PUBLIC_LOOP:
449 			port_attr->PortType = FC_HBA_PORTTYPE_NLPORT;
450 			break;
451 		case PORT_TOPOLOGY_FABRIC_PT_TO_PT:
452 			port_attr->PortType = FC_HBA_PORTTYPE_FPORT;
453 			break;
454 		default:
455 			port_attr->PortType = FC_HBA_PORTTYPE_UNKNOWN;
456 			break;
457 	}
458 	port_attr->PortSupportedClassofService = attr->supported_cos;
459 	port_attr->PortSupportedFc4Types[0] = 0;
460 	port_attr->PortActiveFc4Types[2] = 1;
461 	if (iport->iport_port->port_sym_port_name)
462 		bcopy(iport->iport_port->port_sym_port_name,
463 		    port_attr->PortSymbolicName,
464 		    strlen(iport->iport_port->port_sym_port_name));
465 	else if (iport->iport_port->port_default_alias)
466 		bcopy(iport->iport_port->port_default_alias,
467 		    port_attr->PortSymbolicName,
468 		    strlen(iport->iport_port->port_default_alias));
469 	else
470 		port_attr->PortSymbolicName[0] = 0;
471 	/* the definition is different so need to translate */
472 	if (attr->supported_speed & PORT_SPEED_1G)
473 		port_attr->PortSupportedSpeed |= FC_HBA_PORTSPEED_1GBIT;
474 	if (attr->supported_speed & PORT_SPEED_2G)
475 		port_attr->PortSupportedSpeed |= FC_HBA_PORTSPEED_2GBIT;
476 	if (attr->supported_speed & PORT_SPEED_4G)
477 		port_attr->PortSupportedSpeed |= FC_HBA_PORTSPEED_4GBIT;
478 	if (attr->supported_speed & PORT_SPEED_8G)
479 		port_attr->PortSupportedSpeed |= FC_HBA_PORTSPEED_8GBIT;
480 	if (attr->supported_speed & PORT_SPEED_10G)
481 		port_attr->PortSupportedSpeed |= FC_HBA_PORTSPEED_10GBIT;
482 	switch (iport->iport_link_info.port_speed) {
483 		case PORT_SPEED_1G:
484 			port_attr->PortSpeed = FC_HBA_PORTSPEED_1GBIT;
485 			break;
486 		case PORT_SPEED_2G:
487 			port_attr->PortSpeed = FC_HBA_PORTSPEED_2GBIT;
488 			break;
489 		case PORT_SPEED_4G:
490 			port_attr->PortSpeed = FC_HBA_PORTSPEED_4GBIT;
491 			break;
492 		case PORT_SPEED_8G:
493 			port_attr->PortSpeed = FC_HBA_PORTSPEED_8GBIT;
494 			break;
495 		case PORT_SPEED_10G:
496 			port_attr->PortSpeed = FC_HBA_PORTSPEED_10GBIT;
497 			break;
498 		default:
499 			port_attr->PortSpeed = FC_HBA_PORTSPEED_UNKNOWN;
500 			break;
501 	}
502 	port_attr->PortMaxFrameSize = attr->max_frame_size;
503 	rw_enter(&iport->iport_lock, RW_READER);
504 	port_attr->NumberofDiscoveredPorts = iport->iport_nrps_login;
505 	for (; i < iport->iport_port->port_max_logins; i++) {
506 		irp = iport->iport_rp_slots[i];
507 		if (irp && irp->irp_flags & IRP_PLOGI_DONE) {
508 			if (FC_WELL_KNOWN_ADDR(irp->irp_portid))
509 				port_attr->NumberofDiscoveredPorts --;
510 		}
511 	}
512 	rw_exit(&iport->iport_lock);
513 
514 	kmem_free(attr, sizeof (fct_port_attrs_t));
515 
516 	return (0);
517 }
518 
519 int
520 fct_get_discovered_port_attr(fct_i_remote_port_t *remote_port,
521     uint8_t *port_wwn, uint32_t index, fc_tgt_hba_port_attributes_t *port_attr,
522     uint32_t *error_detail)
523 {
524 	fct_i_local_port_t *iport;
525 	fct_i_remote_port_t *irp = remote_port;
526 	int	count = 0, i = 0;
527 
528 	port_attr->version = FCT_HBA_PORT_ATTRIBUTES_VERSION;
529 	if (!remote_port) {
530 		iport = fct_get_iport_per_wwn(port_wwn);
531 		if (!iport) {
532 			*error_detail = FCTIO_BADWWN;
533 			return (ENXIO);
534 		}
535 
536 		rw_enter(&iport->iport_lock, RW_READER);
537 
538 		if (index >= iport->iport_nrps_login) {
539 			rw_exit(&iport->iport_lock);
540 			*error_detail = FCTIO_OUTOFBOUNDS;
541 			return (EINVAL);
542 		}
543 		for (; i < iport->iport_port->port_max_logins; i++) {
544 			irp = iport->iport_rp_slots[i];
545 			if (irp && irp->irp_flags & IRP_PLOGI_DONE &&
546 			    !FC_WELL_KNOWN_ADDR(irp->irp_portid)) {
547 				count ++;
548 				if ((index + 1) <= count)
549 					break;
550 			}
551 		}
552 		if (i >= iport->iport_port->port_max_logins) {
553 			rw_exit(&iport->iport_lock);
554 			*error_detail = FCTIO_OUTOFBOUNDS;
555 			return (EINVAL);
556 		}
557 		ASSERT(irp);
558 	} else {
559 		iport = (fct_i_local_port_t *)
560 		    irp->irp_rp->rp_port->port_fct_private;
561 	}
562 	port_attr->lastChange = iport->iport_last_change;
563 	rw_enter(&irp->irp_lock, RW_READER);
564 	bcopy(irp->irp_rp->rp_pwwn, port_attr->PortWWN,
565 	    sizeof (port_attr->PortWWN));
566 	bcopy(irp->irp_rp->rp_nwwn, port_attr->NodeWWN,
567 	    sizeof (port_attr->NodeWWN));
568 	port_attr->PortFcId = irp->irp_portid;
569 	if (irp->irp_spn)
570 		(void) strncpy(port_attr->PortSymbolicName, irp->irp_spn,
571 		    strlen(irp->irp_spn));
572 	else
573 		port_attr->PortSymbolicName[0] = '\0';
574 	port_attr->PortSupportedClassofService = irp->irp_cos;
575 	bcopy((caddr_t)irp->irp_fc4types, port_attr->PortActiveFc4Types,
576 	    sizeof (irp->irp_fc4types));
577 	bcopy((caddr_t)irp->irp_fc4types, port_attr->PortSupportedFc4Types,
578 	    sizeof (irp->irp_fc4types));
579 	if (irp->irp_flags & IRP_PLOGI_DONE)
580 		port_attr->PortState = FC_HBA_PORTSTATE_ONLINE;
581 	else
582 		port_attr->PortState = FC_HBA_PORTSTATE_UNKNOWN;
583 
584 	port_attr->PortType = FC_HBA_PORTTYPE_UNKNOWN;
585 	port_attr->PortSupportedSpeed = FC_HBA_PORTSPEED_UNKNOWN;
586 	port_attr->PortSpeed = FC_HBA_PORTSPEED_UNKNOWN;
587 	port_attr->PortMaxFrameSize = 0;
588 	port_attr->NumberofDiscoveredPorts = 0;
589 	rw_exit(&irp->irp_lock);
590 	if (!remote_port) {
591 		rw_exit(&iport->iport_lock);
592 	}
593 	return (0);
594 }
595 
596 int
597 fct_get_port_attr(uint8_t *port_wwn,
598     fc_tgt_hba_port_attributes_t *port_attr, uint32_t *error_detail)
599 {
600 	fct_i_local_port_t *iport;
601 	fct_i_remote_port_t *irp;
602 	int i, ret;
603 
604 	iport = fct_get_iport_per_wwn(port_wwn);
605 	if (iport) {
606 		return (fct_get_adapter_port_attr(iport, port_wwn,
607 		    port_attr, error_detail));
608 	}
609 	/* else */
610 	for (iport = fct_iport_list; iport; iport = iport->iport_next) {
611 		rw_enter(&iport->iport_lock, RW_READER);
612 		for (i = 0; i < rportid_table_size; i++) {
613 			irp = iport->iport_rp_tb[i];
614 			while (irp) {
615 				if (bcmp(irp->irp_rp->rp_pwwn,
616 				    port_wwn, 8) == 0 &&
617 				    irp->irp_flags & IRP_PLOGI_DONE) {
618 					ret = fct_get_discovered_port_attr(
619 					    irp, NULL, 0, port_attr,
620 					    error_detail);
621 					rw_exit(&iport->iport_lock);
622 					return (ret);
623 				}
624 				irp = irp->irp_next;
625 			}
626 		}
627 		rw_exit(&iport->iport_lock);
628 	}
629 	*error_detail = FCTIO_BADWWN;
630 	return (ENXIO);
631 }
632 
633 /* ARGSUSED */
634 int
635 fct_get_port_stats(uint8_t *port_wwn,
636     fc_tgt_hba_adapter_port_stats_t *port_stats, uint32_t *error_detail)
637 {
638 	int ret;
639 	fct_i_local_port_t *iport = fct_get_iport_per_wwn(port_wwn);
640 	fct_port_link_status_t	stat;
641 	uint32_t buf_size = sizeof (fc_tgt_hba_adapter_port_stats_t);
642 
643 	if (!iport)
644 		return (ENXIO);
645 	port_stats->version = FCT_HBA_ADAPTER_PORT_STATS_VERSION;
646 
647 	if (iport->iport_port->port_info == NULL) {
648 		*error_detail = FCTIO_FAILURE;
649 		return (EIO);
650 	}
651 	ret = iport->iport_port->port_info(FC_TGT_PORT_RLS,
652 	    iport->iport_port, NULL, (uint8_t *)&stat, &buf_size);
653 	if (ret != STMF_SUCCESS) {
654 		*error_detail = FCTIO_FAILURE;
655 		return (EIO);
656 	}
657 
658 	port_stats->SecondsSinceLastReset = 0;
659 	port_stats->TxFrames = 0;
660 	port_stats->TxWords = 0;
661 	port_stats->RxFrames = 0;
662 	port_stats->RxWords = 0;
663 	port_stats->LIPCount = 0;
664 	port_stats->NOSCount = 0;
665 	port_stats->ErrorFrames = 0;
666 	port_stats->DumpedFrames = 0;
667 	port_stats->LinkFailureCount = stat.LinkFailureCount;
668 	port_stats->LossOfSyncCount = stat.LossOfSyncCount;
669 	port_stats->LossOfSignalCount = stat.LossOfSignalsCount;
670 	port_stats->PrimitiveSeqProtocolErrCount =
671 	    stat.PrimitiveSeqProtocolErrorCount;
672 	port_stats->InvalidTxWordCount =
673 	    stat.InvalidTransmissionWordCount;
674 	port_stats->InvalidCRCCount = stat.InvalidCRCCount;
675 
676 	return (ret);
677 }
678 
679 int
680 fct_get_link_status(uint8_t *port_wwn, uint64_t *dest_id,
681     fct_port_link_status_t *link_status, uint32_t *error_detail)
682 {
683 	fct_i_local_port_t *iport = fct_get_iport_per_wwn(port_wwn);
684 	fct_i_remote_port_t *irp = NULL;
685 	uint32_t buf_size = sizeof (fct_port_link_status_t);
686 	stmf_status_t ret = 0;
687 	int i;
688 	fct_cmd_t *cmd = NULL;
689 
690 	if (!iport) {
691 		*error_detail = FCTIO_BADWWN;
692 		return (ENXIO);
693 	}
694 
695 	/*
696 	 * If what we are requesting is zero or same as local port,
697 	 * then we use port_info()
698 	 */
699 	if (dest_id == NULL || *dest_id == iport->iport_link_info.portid) {
700 		if (iport->iport_port->port_info == NULL) {
701 			*error_detail = FCTIO_FAILURE;
702 			return (EIO);
703 		}
704 		ret = iport->iport_port->port_info(FC_TGT_PORT_RLS,
705 		    iport->iport_port, NULL,
706 		    (uint8_t *)link_status, &buf_size);
707 		if (ret == STMF_SUCCESS) {
708 			return (0);
709 		} else {
710 			*error_detail = FCTIO_FAILURE;
711 			return (EIO);
712 		}
713 	}
714 
715 	/*
716 	 * For remote port, we will send RLS
717 	 */
718 	for (i = 0; i < rportid_table_size; i++) {
719 		irp = iport->iport_rp_tb[i];
720 		while (irp) {
721 			if (irp->irp_rp->rp_id == *dest_id &&
722 			    irp->irp_flags & IRP_PLOGI_DONE) {
723 				goto SEND_RLS_ELS;
724 			}
725 			irp = irp->irp_next;
726 		}
727 	}
728 	return (ENXIO);
729 
730 SEND_RLS_ELS:
731 	cmd = fct_create_solels(iport->iport_port,
732 	    irp->irp_rp, 0, ELS_OP_RLS,
733 	    0, fct_rls_cb);
734 	if (!cmd)
735 		return (ENOMEM);
736 	iport->iport_rls_cb_data.fct_link_status = link_status;
737 	CMD_TO_ICMD(cmd)->icmd_cb_private = &iport->iport_rls_cb_data;
738 	fct_post_to_solcmd_queue(iport->iport_port, cmd);
739 	sema_p(&iport->iport_rls_sema);
740 	if (iport->iport_rls_cb_data.fct_els_res != FCT_SUCCESS)
741 		ret = EIO;
742 	return (ret);
743 }
744 
745 static int
746 fct_forcelip(uint8_t *port_wwn, uint32_t *fctio_errno)
747 {
748 	fct_status_t		 rval;
749 	fct_i_local_port_t	*iport;
750 
751 	mutex_enter(&fct_global_mutex);
752 	iport = fct_get_iport_per_wwn(port_wwn);
753 	mutex_exit(&fct_global_mutex);
754 	if (iport == NULL) {
755 		return (-1);
756 	}
757 
758 	iport->iport_port->port_ctl(iport->iport_port,
759 	    FCT_CMD_FORCE_LIP, &rval);
760 	if (rval != FCT_SUCCESS) {
761 		*fctio_errno = FCTIO_FAILURE;
762 	} else {
763 		*fctio_errno = 0;
764 	}
765 
766 	return (0);
767 }
768 
769 static int
770 fct_fctiocmd(intptr_t data, int mode)
771 {
772 	int ret	 = 0;
773 	void		*ibuf = NULL;
774 	void		*obuf = NULL;
775 	void		*abuf = NULL;
776 	fctio_t		*fctio;
777 	uint32_t	attr_length;
778 
779 	ret = fct_copyin_iocdata(data, mode, &fctio, &ibuf, &abuf, &obuf);
780 	if (ret) {
781 		return (ret);
782 	}
783 
784 	switch (fctio->fctio_cmd) {
785 	case FCTIO_ADAPTER_LIST: {
786 		fc_tgt_hba_list_t *list = (fc_tgt_hba_list_t *)obuf;
787 		int		count;
788 
789 		if (fctio->fctio_olen < sizeof (fc_tgt_hba_list_t)) {
790 			ret = EINVAL;
791 			break;
792 		}
793 		list->numPorts = (fctio->fctio_olen -
794 		    sizeof (fc_tgt_hba_list_t))/8 + 1;
795 
796 		list->version = FCT_HBA_LIST_VERSION;
797 		count = fct_get_port_list((char *)list->port_wwn,
798 		    list->numPorts);
799 		if (count < 0) {
800 			ret = ENXIO;
801 			break;
802 		}
803 		if (count > list->numPorts) {
804 			fctio->fctio_errno = FCTIO_MOREDATA;
805 			ret = ENOSPC;
806 		}
807 		list->numPorts = count;
808 		break;
809 		}
810 	case FCTIO_GET_ADAPTER_ATTRIBUTES: {
811 		fc_tgt_hba_adapter_attributes_t *hba_attr;
812 		uint8_t	*port_wwn = (uint8_t *)ibuf;
813 
814 		attr_length = sizeof (fc_tgt_hba_adapter_attributes_t);
815 		if (fctio->fctio_olen < attr_length ||
816 		    fctio->fctio_xfer != FCTIO_XFER_READ) {
817 			ret = EINVAL;
818 			break;
819 		}
820 		hba_attr = (fc_tgt_hba_adapter_attributes_t *)obuf;
821 
822 		mutex_enter(&fct_global_mutex);
823 		ret = fct_get_adapter_attr(port_wwn, hba_attr,
824 		    &fctio->fctio_errno);
825 		mutex_exit(&fct_global_mutex);
826 
827 		break;
828 		}
829 	case FCTIO_GET_ADAPTER_PORT_ATTRIBUTES: {
830 		fc_tgt_hba_port_attributes_t *port_attr;
831 
832 		uint8_t *port_wwn = (uint8_t *)ibuf;
833 
834 		attr_length = sizeof (fc_tgt_hba_port_attributes_t);
835 		if (fctio->fctio_olen < attr_length ||
836 		    fctio->fctio_xfer != FCTIO_XFER_READ) {
837 			ret = EINVAL;
838 			break;
839 		}
840 		port_attr = (fc_tgt_hba_port_attributes_t *)obuf;
841 
842 		mutex_enter(&fct_global_mutex);
843 		ret = fct_get_adapter_port_attr(NULL, port_wwn, port_attr,
844 		    &fctio->fctio_errno);
845 		mutex_exit(&fct_global_mutex);
846 
847 		break;
848 		}
849 	case FCTIO_GET_DISCOVERED_PORT_ATTRIBUTES: {
850 		uint8_t *port_wwn = (uint8_t *)ibuf;
851 		uint32_t *port_index = (uint32_t *)abuf;
852 		fc_tgt_hba_port_attributes_t *port_attr;
853 
854 		attr_length = sizeof (fc_tgt_hba_port_attributes_t);
855 		if (fctio->fctio_olen < attr_length ||
856 		    fctio->fctio_xfer != FCTIO_XFER_READ) {
857 			ret = EINVAL;
858 			break;
859 		}
860 		port_attr = (fc_tgt_hba_port_attributes_t *)obuf;
861 
862 		mutex_enter(&fct_global_mutex);
863 		ret = fct_get_discovered_port_attr(NULL, port_wwn,
864 		    *port_index, port_attr, &fctio->fctio_errno);
865 		mutex_exit(&fct_global_mutex);
866 
867 		break;
868 		}
869 	case FCTIO_GET_PORT_ATTRIBUTES: {
870 		uint8_t *port_wwn = (uint8_t *)ibuf;
871 		fc_tgt_hba_port_attributes_t *port_attr;
872 
873 		attr_length = sizeof (fc_tgt_hba_port_attributes_t);
874 		if (fctio->fctio_olen < attr_length ||
875 		    fctio->fctio_xfer != FCTIO_XFER_READ) {
876 			ret = EINVAL;
877 			break;
878 		}
879 
880 		port_attr = (fc_tgt_hba_port_attributes_t *)obuf;
881 
882 		mutex_enter(&fct_global_mutex);
883 		ret = fct_get_port_attr(port_wwn, port_attr,
884 		    &fctio->fctio_errno);
885 		mutex_exit(&fct_global_mutex);
886 
887 		break;
888 		}
889 	case FCTIO_GET_ADAPTER_PORT_STATS: {
890 		uint8_t *port_wwn = (uint8_t *)ibuf;
891 		fc_tgt_hba_adapter_port_stats_t *port_stats =
892 		    (fc_tgt_hba_adapter_port_stats_t *)obuf;
893 		mutex_enter(&fct_global_mutex);
894 		ret = fct_get_port_stats(port_wwn, port_stats,
895 		    &fctio->fctio_errno);
896 		mutex_exit(&fct_global_mutex);
897 		break;
898 		}
899 	case FCTIO_GET_LINK_STATUS: {
900 		uint8_t *port_wwn = (uint8_t *)ibuf;
901 		fct_port_link_status_t *link_status =
902 		    (fct_port_link_status_t *)obuf;
903 		uint64_t *dest_id = abuf;
904 
905 		mutex_enter(&fct_global_mutex);
906 		ret = fct_get_link_status(port_wwn, dest_id, link_status,
907 		    &fctio->fctio_errno);
908 		mutex_exit(&fct_global_mutex);
909 		break;
910 		}
911 
912 	case FCTIO_FORCE_LIP:
913 		ret = fct_forcelip((uint8_t *)ibuf, &fctio->fctio_errno);
914 		break;
915 
916 	default:
917 		break;
918 	}
919 	if (ret == 0) {
920 		ret = fct_copyout_iocdata(data, mode, fctio, obuf);
921 	} else if (fctio->fctio_errno) {
922 		(void) fct_copyout_iocdata(data, mode, fctio, obuf);
923 	}
924 
925 	if (obuf) {
926 		kmem_free(obuf, fctio->fctio_olen);
927 		obuf = NULL;
928 	}
929 	if (abuf) {
930 		kmem_free(abuf, fctio->fctio_alen);
931 		abuf = NULL;
932 	}
933 
934 	if (ibuf) {
935 		kmem_free(ibuf, fctio->fctio_ilen);
936 		ibuf = NULL;
937 	}
938 	kmem_free(fctio, sizeof (fctio_t));
939 	return (ret);
940 }
941 
942 typedef struct {
943 	void	*bp;	/* back pointer from internal struct to main struct */
944 	int	alloc_size;
945 	fct_struct_id_t struct_id;
946 } __ifct_t;
947 
948 typedef struct {
949 	__ifct_t	*fp;	/* Framework private */
950 	void		*cp;	/* Caller private */
951 	void		*ss;	/* struct specific */
952 } __fct_t;
953 
954 static struct {
955 	int shared;
956 	int fw_private;
957 	int struct_specific;
958 } fct_sizes[] = { { 0, 0, 0 },
959 	{ GET_STRUCT_SIZE(fct_local_port_t),
960 		GET_STRUCT_SIZE(fct_i_local_port_t), 0 },
961 	{ GET_STRUCT_SIZE(fct_remote_port_t),
962 		GET_STRUCT_SIZE(fct_i_remote_port_t), 0 },
963 	{ GET_STRUCT_SIZE(fct_cmd_t),
964 		GET_STRUCT_SIZE(fct_i_cmd_t), GET_STRUCT_SIZE(fct_els_t) },
965 	{ GET_STRUCT_SIZE(fct_cmd_t),
966 		GET_STRUCT_SIZE(fct_i_cmd_t), GET_STRUCT_SIZE(fct_els_t) },
967 	{ GET_STRUCT_SIZE(fct_cmd_t),
968 		GET_STRUCT_SIZE(fct_i_cmd_t), GET_STRUCT_SIZE(fct_sol_ct_t) },
969 	{ GET_STRUCT_SIZE(fct_cmd_t), GET_STRUCT_SIZE(fct_i_cmd_t),
970 		GET_STRUCT_SIZE(fct_rcvd_abts_t) },
971 	{ GET_STRUCT_SIZE(fct_cmd_t),	/* FCT_STRUCT_CMD_FCP_XCHG */
972 		GET_STRUCT_SIZE(fct_i_cmd_t), 0 },
973 	{ GET_STRUCT_SIZE(fct_dbuf_store_t),
974 		GET_STRUCT_SIZE(__ifct_t), 0 }
975 };
976 
977 void *
978 fct_alloc(fct_struct_id_t struct_id, int additional_size, int flags)
979 {
980 	int fct_size;
981 	int kmem_flag;
982 	__fct_t *sh;
983 
984 	if ((struct_id == 0) || (struct_id >= FCT_MAX_STRUCT_IDS))
985 		return (NULL);
986 
987 	if ((curthread->t_flag & T_INTR_THREAD) || (flags & AF_FORCE_NOSLEEP)) {
988 		kmem_flag = KM_NOSLEEP;
989 	} else {
990 		kmem_flag = KM_SLEEP;
991 	}
992 
993 	additional_size = (additional_size + 7) & (~7);
994 	fct_size = fct_sizes[struct_id].shared +
995 	    fct_sizes[struct_id].fw_private +
996 	    fct_sizes[struct_id].struct_specific + additional_size;
997 
998 	if (struct_id == FCT_STRUCT_LOCAL_PORT) {
999 		stmf_local_port_t *lport;
1000 
1001 		lport = (stmf_local_port_t *)stmf_alloc(
1002 		    STMF_STRUCT_STMF_LOCAL_PORT, fct_size, flags);
1003 		if (lport) {
1004 			sh = (__fct_t *)lport->lport_port_private;
1005 			sh->ss = lport;
1006 		} else {
1007 			return (NULL);
1008 		}
1009 	} else if (struct_id == FCT_STRUCT_DBUF_STORE) {
1010 		stmf_dbuf_store_t *ds;
1011 
1012 		ds = (stmf_dbuf_store_t *)stmf_alloc(STMF_STRUCT_DBUF_STORE,
1013 		    fct_size, flags);
1014 		if (ds) {
1015 			sh = (__fct_t *)ds->ds_port_private;
1016 			sh->ss = ds;
1017 		} else {
1018 			return (NULL);
1019 		}
1020 	} else {
1021 		sh = (__fct_t *)kmem_zalloc(fct_size, kmem_flag);
1022 	}
1023 
1024 	if (sh == NULL)
1025 		return (NULL);
1026 
1027 	sh->fp = (__ifct_t *)GET_BYTE_OFFSET(sh, fct_sizes[struct_id].shared);
1028 	sh->cp = GET_BYTE_OFFSET(sh->fp, fct_sizes[struct_id].fw_private);
1029 	if (fct_sizes[struct_id].struct_specific)
1030 		sh->ss = GET_BYTE_OFFSET(sh->cp, additional_size);
1031 
1032 	sh->fp->bp = sh;
1033 	sh->fp->alloc_size = fct_size;
1034 	sh->fp->struct_id = struct_id;
1035 
1036 	if (struct_id == FCT_STRUCT_CMD_FCP_XCHG) {
1037 		((fct_cmd_t *)sh)->cmd_type = FCT_CMD_FCP_XCHG;
1038 	} else if (struct_id == FCT_STRUCT_CMD_RCVD_ELS) {
1039 		((fct_cmd_t *)sh)->cmd_type = FCT_CMD_RCVD_ELS;
1040 	} else if (struct_id == FCT_STRUCT_CMD_SOL_ELS) {
1041 		((fct_cmd_t *)sh)->cmd_type = FCT_CMD_SOL_ELS;
1042 	} else if (struct_id == FCT_STRUCT_CMD_RCVD_ABTS) {
1043 		((fct_cmd_t *)sh)->cmd_type = FCT_CMD_RCVD_ABTS;
1044 	} else if (struct_id == FCT_STRUCT_CMD_SOL_CT) {
1045 		((fct_cmd_t *)sh)->cmd_type = FCT_CMD_SOL_CT;
1046 	}
1047 
1048 	return (sh);
1049 }
1050 
1051 void
1052 fct_free(void *ptr)
1053 {
1054 	__fct_t *sh = (__fct_t *)ptr;
1055 	fct_struct_id_t struct_id = sh->fp->struct_id;
1056 
1057 	if (struct_id == FCT_STRUCT_CMD_SOL_CT) {
1058 		fct_sol_ct_t *ct = (fct_sol_ct_t *)
1059 		    ((fct_cmd_t *)ptr)->cmd_specific;
1060 
1061 		if (ct->ct_req_alloc_size) {
1062 			kmem_free(ct->ct_req_payload, ct->ct_req_alloc_size);
1063 		}
1064 		if (ct->ct_resp_alloc_size) {
1065 			kmem_free(ct->ct_resp_payload, ct->ct_resp_alloc_size);
1066 		}
1067 	} else if ((struct_id == FCT_STRUCT_CMD_RCVD_ELS) ||
1068 	    (struct_id == FCT_STRUCT_CMD_SOL_ELS)) {
1069 		fct_els_t *els = (fct_els_t *)
1070 			((fct_cmd_t *)ptr)->cmd_specific;
1071 		if (els->els_req_alloc_size)
1072 			kmem_free(els->els_req_payload,
1073 				els->els_req_alloc_size);
1074 		if (els->els_resp_alloc_size)
1075 			kmem_free(els->els_resp_payload,
1076 				els->els_resp_alloc_size);
1077 	}
1078 
1079 	if (struct_id == FCT_STRUCT_LOCAL_PORT) {
1080 		stmf_free(((fct_local_port_t *)ptr)->port_lport);
1081 	} else if (struct_id == FCT_STRUCT_DBUF_STORE) {
1082 		stmf_free(((fct_dbuf_store_t *)ptr)->fds_ds);
1083 	} else {
1084 		kmem_free(ptr, sh->fp->alloc_size);
1085 	}
1086 }
1087 
1088 stmf_data_buf_t *
1089 fct_alloc_dbuf(scsi_task_t *task, uint32_t size, uint32_t *pminsize,
1090     uint32_t flags)
1091 {
1092 	fct_local_port_t *port = (fct_local_port_t *)
1093 	    task->task_lport->lport_port_private;
1094 
1095 	return (port->port_fds->fds_alloc_data_buf(port, size,
1096 	    pminsize, flags));
1097 }
1098 
1099 void
1100 fct_free_dbuf(stmf_dbuf_store_t *ds, stmf_data_buf_t *dbuf)
1101 {
1102 	fct_dbuf_store_t *fds;
1103 
1104 	fds = (fct_dbuf_store_t *)ds->ds_port_private;
1105 
1106 	fds->fds_free_data_buf(fds, dbuf);
1107 }
1108 
1109 static uint32_t taskq_cntr = 0;
1110 
1111 fct_status_t
1112 fct_register_local_port(fct_local_port_t *port)
1113 {
1114 	fct_i_local_port_t	*iport;
1115 	stmf_local_port_t	*lport;
1116 	fct_cmd_slot_t		*slot;
1117 	int			i;
1118 	char			taskq_name[24];
1119 
1120 	iport = (fct_i_local_port_t *)port->port_fct_private;
1121 	if (port->port_fca_version != FCT_FCA_MODREV_1) {
1122 		cmn_err(CE_WARN,
1123 		    "fct: %s driver version mismatch",
1124 		    port->port_default_alias);
1125 		return (FCT_FAILURE);
1126 	}
1127 	if (port->port_default_alias) {
1128 		int l = strlen(port->port_default_alias);
1129 
1130 		if (l < 16) {
1131 			iport->iport_alias = iport->iport_alias_mem;
1132 		} else {
1133 			iport->iport_alias =
1134 			    (char *)kmem_zalloc(l+1, KM_SLEEP);
1135 		}
1136 		(void) strcpy(iport->iport_alias, port->port_default_alias);
1137 	} else {
1138 		iport->iport_alias = NULL;
1139 	}
1140 	stmf_wwn_to_devid_desc((scsi_devid_desc_t *)iport->iport_id,
1141 	    port->port_pwwn, PROTOCOL_FIBRE_CHANNEL);
1142 	(void) snprintf(taskq_name, 24, "stmf_fct_taskq_%d",
1143 	    atomic_add_32_nv(&taskq_cntr, 1));
1144 	taskq_name[23] = 0;
1145 	if ((iport->iport_worker_taskq = ddi_taskq_create(NULL,
1146 	    taskq_name, 1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1147 		return (FCT_FAILURE);
1148 	}
1149 	mutex_init(&iport->iport_worker_lock, NULL, MUTEX_DRIVER, NULL);
1150 	cv_init(&iport->iport_worker_cv, NULL, CV_DRIVER, NULL);
1151 	rw_init(&iport->iport_lock, NULL, RW_DRIVER, NULL);
1152 	sema_init(&iport->iport_rls_sema, 0, NULL, SEMA_DRIVER, NULL);
1153 
1154 	/* Remote port mgmt */
1155 	iport->iport_rp_slots = (fct_i_remote_port_t **)kmem_zalloc(
1156 	    port->port_max_logins * sizeof (fct_i_remote_port_t *), KM_SLEEP);
1157 	iport->iport_rp_tb = kmem_zalloc(rportid_table_size *
1158 	    sizeof (fct_i_remote_port_t *), KM_SLEEP);
1159 
1160 	/* fct_cmds for SCSI traffic */
1161 	iport->iport_total_alloced_ncmds = 0;
1162 	iport->iport_cached_ncmds = 0;
1163 	port->port_fca_fcp_cmd_size =
1164 	    (port->port_fca_fcp_cmd_size + 7) & ~7;
1165 	iport->iport_cached_cmdlist = NULL;
1166 	mutex_init(&iport->iport_cached_cmd_lock, NULL, MUTEX_DRIVER, NULL);
1167 
1168 	/* Initialize cmd slots */
1169 	iport->iport_cmd_slots = (fct_cmd_slot_t *)kmem_zalloc(
1170 	    port->port_max_xchges * sizeof (fct_cmd_slot_t), KM_SLEEP);
1171 	iport->iport_next_free_slot = 0;
1172 	for (i = 0; i < port->port_max_xchges; ) {
1173 		slot = &iport->iport_cmd_slots[i];
1174 		slot->slot_no = (uint16_t)i;
1175 		slot->slot_next = (uint16_t)(++i);
1176 	}
1177 	slot->slot_next = FCT_SLOT_EOL;
1178 	iport->iport_nslots_free = port->port_max_xchges;
1179 
1180 	iport->iport_task_green_limit =
1181 	    (port->port_max_xchges * FCT_TASK_GREEN_LIMIT) / 100;
1182 	iport->iport_task_yellow_limit =
1183 	    (port->port_max_xchges * FCT_TASK_YELLOW_LIMIT) / 100;
1184 	iport->iport_task_red_limit =
1185 	    (port->port_max_xchges * FCT_TASK_RED_LIMIT) / 100;
1186 
1187 	/* Start worker thread */
1188 	atomic_and_32(&iport->iport_flags, ~IPORT_TERMINATE_WORKER);
1189 	(void) ddi_taskq_dispatch(iport->iport_worker_taskq,
1190 	    fct_port_worker, port, DDI_SLEEP);
1191 	/* Wait for taskq to start */
1192 	while ((iport->iport_flags & IPORT_WORKER_RUNNING) == 0) {
1193 		delay(1);
1194 	}
1195 
1196 	lport = port->port_lport;
1197 	lport->lport_id = (scsi_devid_desc_t *)iport->iport_id;
1198 	lport->lport_alias = iport->iport_alias;
1199 	lport->lport_pp = port->port_pp;
1200 	port->port_fds->fds_ds->ds_alloc_data_buf = fct_alloc_dbuf;
1201 	port->port_fds->fds_ds->ds_free_data_buf = fct_free_dbuf;
1202 	lport->lport_ds = port->port_fds->fds_ds;
1203 	lport->lport_xfer_data = fct_xfer_scsi_data;
1204 	lport->lport_send_status = fct_send_scsi_status;
1205 	lport->lport_task_free = fct_scsi_task_free;
1206 	lport->lport_abort = fct_scsi_abort;
1207 	lport->lport_ctl = fct_ctl;
1208 	lport->lport_info = fct_info;
1209 	lport->lport_event_handler = fct_event_handler;
1210 	/* set up as alua participating port */
1211 	stmf_set_port_alua(lport);
1212 	if (stmf_register_local_port(port->port_lport) != FCT_SUCCESS) {
1213 		goto fct_regport_fail1;
1214 	}
1215 	(void) stmf_lport_add_event(lport, LPORT_EVENT_INITIAL_LUN_MAPPED);
1216 
1217 	mutex_enter(&fct_global_mutex);
1218 	iport->iport_next = fct_iport_list;
1219 	iport->iport_prev = NULL;
1220 	if (iport->iport_next)
1221 		iport->iport_next->iport_prev = iport;
1222 	fct_iport_list = iport;
1223 	mutex_exit(&fct_global_mutex);
1224 
1225 	fct_init_kstats(iport);
1226 
1227 	fct_log_local_port_event(port, ESC_SUNFC_PORT_ATTACH);
1228 
1229 	return (FCT_SUCCESS);
1230 
1231 fct_regport_fail1:;
1232 	/* Stop the taskq 1st */
1233 	if (iport->iport_flags & IPORT_WORKER_RUNNING) {
1234 		atomic_or_32(&iport->iport_flags, IPORT_TERMINATE_WORKER);
1235 		cv_broadcast(&iport->iport_worker_cv);
1236 		while (iport->iport_flags & IPORT_WORKER_RUNNING) {
1237 			delay(1);
1238 		}
1239 	}
1240 	ddi_taskq_destroy(iport->iport_worker_taskq);
1241 	if (iport->iport_rp_tb) {
1242 		kmem_free(iport->iport_rp_tb, rportid_table_size *
1243 		    sizeof (fct_i_remote_port_t *));
1244 	}
1245 	return (FCT_FAILURE);
1246 }
1247 
1248 fct_status_t
1249 fct_deregister_local_port(fct_local_port_t *port)
1250 {
1251 	fct_i_local_port_t	*iport;
1252 	fct_i_cmd_t		*icmd, *next_icmd;
1253 	int			ndx;
1254 
1255 	iport = (fct_i_local_port_t *)port->port_fct_private;
1256 
1257 	if ((iport->iport_state != FCT_STATE_OFFLINE) ||
1258 	    iport->iport_state_not_acked) {
1259 		return (FCT_FAILURE);
1260 	}
1261 
1262 	/* Stop the taskq 1st */
1263 	if (iport->iport_flags & IPORT_WORKER_RUNNING) {
1264 		atomic_or_32(&iport->iport_flags, IPORT_TERMINATE_WORKER);
1265 		cv_broadcast(&iport->iport_worker_cv);
1266 		for (ndx = 0; ndx < 100; ndx++) {
1267 			if ((iport->iport_flags & IPORT_WORKER_RUNNING)
1268 			    == 0) {
1269 				break;
1270 			}
1271 			delay(drv_usectohz(10000));
1272 		}
1273 		if (ndx == 100) {
1274 			atomic_and_32(&iport->iport_flags,
1275 			    ~IPORT_TERMINATE_WORKER);
1276 			return (FCT_WORKER_STUCK);
1277 		}
1278 	}
1279 
1280 	if (stmf_deregister_local_port(port->port_lport) != FCT_SUCCESS) {
1281 		goto fct_deregport_fail1;
1282 	}
1283 
1284 	mutex_enter(&fct_global_mutex);
1285 	if (iport->iport_next)
1286 		iport->iport_next->iport_prev = iport->iport_prev;
1287 	if (iport->iport_prev)
1288 		iport->iport_prev->iport_next = iport->iport_next;
1289 	else
1290 		fct_iport_list = iport->iport_next;
1291 	mutex_exit(&fct_global_mutex);
1292 	/*
1293 	 * At this time, there should be no outstanding and pending
1294 	 * I/Os, so we can just release resources.
1295 	 */
1296 	ASSERT(iport->iport_total_alloced_ncmds == iport->iport_cached_ncmds);
1297 	for (icmd = iport->iport_cached_cmdlist; icmd; icmd = next_icmd) {
1298 		next_icmd = icmd->icmd_next;
1299 		fct_free(icmd->icmd_cmd);
1300 	}
1301 	mutex_destroy(&iport->iport_cached_cmd_lock);
1302 	kmem_free(iport->iport_cmd_slots, port->port_max_xchges *
1303 	    sizeof (fct_cmd_slot_t));
1304 	kmem_free(iport->iport_rp_slots, port->port_max_logins *
1305 	    sizeof (fct_i_remote_port_t *));
1306 	rw_destroy(&iport->iport_lock);
1307 	cv_destroy(&iport->iport_worker_cv);
1308 	sema_destroy(&iport->iport_rls_sema);
1309 	mutex_destroy(&iport->iport_worker_lock);
1310 	ddi_taskq_destroy(iport->iport_worker_taskq);
1311 	if (iport->iport_rp_tb) {
1312 		kmem_free(iport->iport_rp_tb, rportid_table_size *
1313 		    sizeof (fct_i_remote_port_t *));
1314 	}
1315 
1316 	if (iport->iport_kstat_portstat) {
1317 		kstat_delete(iport->iport_kstat_portstat);
1318 	}
1319 
1320 	fct_log_local_port_event(port, ESC_SUNFC_PORT_DETACH);
1321 	return (FCT_SUCCESS);
1322 
1323 fct_deregport_fail1:;
1324 	/* Restart the worker */
1325 	atomic_and_32(&iport->iport_flags, ~IPORT_TERMINATE_WORKER);
1326 	(void) ddi_taskq_dispatch(iport->iport_worker_taskq,
1327 	    fct_port_worker, port, DDI_SLEEP);
1328 	/* Wait for taskq to start */
1329 	while ((iport->iport_flags & IPORT_WORKER_RUNNING) == 0) {
1330 		delay(1);
1331 	}
1332 	return (FCT_FAILURE);
1333 }
1334 
1335 /* ARGSUSED */
1336 void
1337 fct_handle_event(fct_local_port_t *port, int event_id, uint32_t event_flags,
1338 		caddr_t arg)
1339 {
1340 	char			info[80];
1341 	fct_i_event_t		*e;
1342 	fct_i_local_port_t	*iport = (fct_i_local_port_t *)
1343 	    port->port_fct_private;
1344 
1345 	e = kmem_zalloc(sizeof (fct_i_event_t), KM_NOSLEEP);
1346 
1347 	if (e == NULL) {
1348 		/*
1349 		 * XXX Throw HBA fatal error event
1350 		 */
1351 		(void) snprintf(info, 80,
1352 		    "fct_handle_event: iport-%p, allocation "
1353 		    "of fct_i_event failed", (void *)iport);
1354 		info[79] = 0;
1355 		(void) fct_port_shutdown(iport->iport_port,
1356 		    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
1357 		return;
1358 	}
1359 	/* Just queue the event */
1360 	e->event_type = event_id;
1361 	mutex_enter(&iport->iport_worker_lock);
1362 	if (iport->iport_event_head == NULL) {
1363 		iport->iport_event_head = iport->iport_event_tail = e;
1364 	} else {
1365 		iport->iport_event_tail->event_next = e;
1366 		iport->iport_event_tail = e;
1367 	}
1368 	if (IS_WORKER_SLEEPING(iport))
1369 		cv_signal(&iport->iport_worker_cv);
1370 	mutex_exit(&iport->iport_worker_lock);
1371 }
1372 
1373 /*
1374  * Called with iport_lock held as reader.
1375  */
1376 fct_i_remote_port_t *
1377 fct_portid_to_portptr(fct_i_local_port_t *iport, uint32_t portid)
1378 {
1379 	fct_i_remote_port_t	*irp;
1380 
1381 	irp = iport->iport_rp_tb[FCT_PORTID_HASH_FUNC(portid)];
1382 	for (; irp != NULL; irp = irp->irp_next) {
1383 		if (irp->irp_portid == portid)
1384 			return (irp);
1385 	}
1386 
1387 	return (NULL);
1388 
1389 }
1390 
1391 /*
1392  * Called with irp_lock held as writer.
1393  */
1394 void
1395 fct_queue_rp(fct_i_local_port_t *iport, fct_i_remote_port_t *irp)
1396 {
1397 	int hash_key =
1398 	    FCT_PORTID_HASH_FUNC(irp->irp_portid);
1399 
1400 	irp->irp_next = iport->iport_rp_tb[hash_key];
1401 	iport->iport_rp_tb[hash_key] = irp;
1402 	iport->iport_nrps++;
1403 }
1404 
1405 /*
1406  * Called with irp_lock and iport_lock held as writer.
1407  */
1408 void
1409 fct_deque_rp(fct_i_local_port_t *iport, fct_i_remote_port_t *irp)
1410 {
1411 	fct_i_remote_port_t	*irp_next = NULL;
1412 	fct_i_remote_port_t	*irp_last = NULL;
1413 	int hash_key			  =
1414 	    FCT_PORTID_HASH_FUNC(irp->irp_portid);
1415 
1416 	irp_next = iport->iport_rp_tb[hash_key];
1417 	irp_last = NULL;
1418 	while (irp_next != NULL) {
1419 		if (irp == irp_next) {
1420 			break;
1421 		}
1422 		irp_last = irp_next;
1423 		irp_next = irp_next->irp_next;
1424 	}
1425 
1426 	if (irp_next) {
1427 		if (irp_last == NULL) {
1428 			iport->iport_rp_tb[hash_key] =
1429 			    irp->irp_next;
1430 		} else {
1431 			irp_last->irp_next = irp->irp_next;
1432 		}
1433 		irp->irp_next = NULL;
1434 		iport->iport_nrps--;
1435 	}
1436 }
1437 
1438 int
1439 fct_is_irp_logging_out(fct_i_remote_port_t *irp, int force_implicit)
1440 {
1441 	int logging_out = 0;
1442 
1443 	rw_enter(&irp->irp_lock, RW_WRITER);
1444 	if ((irp->irp_flags & IRP_IN_DISCOVERY_QUEUE) == 0) {
1445 		logging_out = 0;
1446 		goto ilo_done;
1447 	}
1448 	if ((irp->irp_els_list == NULL) && (irp->irp_deregister_timer)) {
1449 		if (force_implicit && irp->irp_nonfcp_xchg_count) {
1450 			logging_out = 0;
1451 		} else {
1452 			logging_out = 1;
1453 		}
1454 		goto ilo_done;
1455 	}
1456 	if (irp->irp_els_list) {
1457 		fct_i_cmd_t *icmd;
1458 		/* Last session affecting ELS should be a LOGO */
1459 		for (icmd = irp->irp_els_list; icmd; icmd = icmd->icmd_next) {
1460 			uint8_t op = (ICMD_TO_ELS(icmd))->els_req_payload[0];
1461 			if (op == ELS_OP_LOGO) {
1462 				if (force_implicit) {
1463 					if (icmd->icmd_flags & ICMD_IMPLICIT)
1464 						logging_out = 1;
1465 					else
1466 						logging_out = 0;
1467 				} else {
1468 					logging_out = 1;
1469 				}
1470 			} else if ((op == ELS_OP_PLOGI) ||
1471 			    (op == ELS_OP_PRLI) ||
1472 			    (op == ELS_OP_PRLO) || (op == ELS_OP_TPRLO)) {
1473 				logging_out = 0;
1474 			}
1475 		}
1476 	}
1477 ilo_done:;
1478 	rw_exit(&irp->irp_lock);
1479 
1480 	return (logging_out);
1481 }
1482 
1483 /*
1484  * The force_implicit flag enforces the implicit semantics which may be
1485  * needed if a received logout got stuck e.g. a response to a received
1486  * LOGO never came back from the FCA.
1487  */
1488 int
1489 fct_implicitly_logo_all(fct_i_local_port_t *iport, int force_implicit)
1490 {
1491 	fct_i_remote_port_t	*irp = NULL;
1492 	fct_cmd_t		*cmd = NULL;
1493 	int			 i   = 0;
1494 	int			nports = 0;
1495 
1496 	if (!iport->iport_nrps) {
1497 		return (nports);
1498 	}
1499 
1500 	rw_enter(&iport->iport_lock, RW_WRITER);
1501 	for (i = 0; i < rportid_table_size; i++) {
1502 		irp = iport->iport_rp_tb[i];
1503 		while (irp) {
1504 			if ((!(irp->irp_flags & IRP_PLOGI_DONE)) &&
1505 			    (fct_is_irp_logging_out(irp, force_implicit))) {
1506 				irp = irp->irp_next;
1507 				continue;
1508 			}
1509 
1510 			cmd = fct_create_solels(iport->iport_port, irp->irp_rp,
1511 			    1, ELS_OP_LOGO, 0, fct_logo_cb);
1512 			if (cmd == NULL) {
1513 				stmf_trace(iport->iport_alias,
1514 				    "fct_implictly_logo_all: cmd null");
1515 				rw_exit(&iport->iport_lock);
1516 
1517 				return (nports);
1518 			}
1519 
1520 			fct_post_implicit_logo(cmd);
1521 			nports++;
1522 			irp = irp->irp_next;
1523 		}
1524 	}
1525 	rw_exit(&iport->iport_lock);
1526 
1527 	return (nports);
1528 }
1529 
1530 void
1531 fct_rehash(fct_i_local_port_t *iport)
1532 {
1533 	fct_i_remote_port_t **iport_rp_tb_tmp;
1534 	fct_i_remote_port_t **iport_rp_tb_new;
1535 	fct_i_remote_port_t *irp;
1536 	fct_i_remote_port_t *irp_next;
1537 	int i;
1538 
1539 	iport_rp_tb_new = kmem_zalloc(rportid_table_size *
1540 	    sizeof (fct_i_remote_port_t *), KM_SLEEP);
1541 	rw_enter(&iport->iport_lock, RW_WRITER);
1542 	/* reconstruct the hash table */
1543 	iport_rp_tb_tmp = iport->iport_rp_tb;
1544 	iport->iport_rp_tb = iport_rp_tb_new;
1545 	iport->iport_nrps = 0;
1546 	for (i = 0; i < rportid_table_size; i++) {
1547 		irp = iport_rp_tb_tmp[i];
1548 		while (irp) {
1549 			irp_next = irp->irp_next;
1550 			fct_queue_rp(iport, irp);
1551 			irp = irp_next;
1552 		}
1553 	}
1554 	rw_exit(&iport->iport_lock);
1555 	kmem_free(iport_rp_tb_tmp, rportid_table_size *
1556 	    sizeof (fct_i_remote_port_t *));
1557 
1558 }
1559 
1560 uint8_t
1561 fct_local_port_cleanup_done(fct_i_local_port_t *iport)
1562 {
1563 	fct_i_remote_port_t *irp;
1564 	int i;
1565 
1566 	if (iport->iport_nrps_login)
1567 		return (0);
1568 	/* loop all rps to check if the cmd have already been drained */
1569 	for (i = 0; i < rportid_table_size; i++) {
1570 		irp = iport->iport_rp_tb[i];
1571 		while (irp) {
1572 			if (irp->irp_fcp_xchg_count ||
1573 			    irp->irp_nonfcp_xchg_count)
1574 				return (0);
1575 			irp = irp->irp_next;
1576 		}
1577 	}
1578 	return (1);
1579 }
1580 
1581 fct_cmd_t *
1582 fct_scsi_task_alloc(fct_local_port_t *port, uint16_t rp_handle,
1583 		uint32_t rportid, uint8_t *lun, uint16_t cdb_length,
1584 		uint16_t task_ext)
1585 {
1586 	fct_cmd_t *cmd;
1587 	fct_i_cmd_t *icmd;
1588 	fct_i_local_port_t *iport =
1589 	    (fct_i_local_port_t *)port->port_fct_private;
1590 	fct_i_remote_port_t *irp;
1591 	scsi_task_t *task;
1592 	fct_remote_port_t *rp;
1593 	uint16_t cmd_slot;
1594 
1595 	rw_enter(&iport->iport_lock, RW_READER);
1596 	if ((iport->iport_link_state & S_LINK_ONLINE) == 0) {
1597 		rw_exit(&iport->iport_lock);
1598 		stmf_trace(iport->iport_alias, "cmd alloc called while the port"
1599 		    " was offline");
1600 		return (NULL);
1601 	}
1602 
1603 	if (rp_handle == FCT_HANDLE_NONE) {
1604 		irp = fct_portid_to_portptr(iport, rportid);
1605 		if (irp == NULL) {
1606 			rw_exit(&iport->iport_lock);
1607 			stmf_trace(iport->iport_alias, "cmd received from "
1608 			    "non existent port %x", rportid);
1609 			return (NULL);
1610 		}
1611 	} else {
1612 		if ((rp_handle >= port->port_max_logins) ||
1613 		    ((irp = iport->iport_rp_slots[rp_handle]) == NULL)) {
1614 			rw_exit(&iport->iport_lock);
1615 			stmf_trace(iport->iport_alias, "cmd received from "
1616 			    "invalid port handle %x", rp_handle);
1617 			return (NULL);
1618 		}
1619 	}
1620 	rp = irp->irp_rp;
1621 
1622 	rw_enter(&irp->irp_lock, RW_READER);
1623 	if ((irp->irp_flags & IRP_PRLI_DONE) == 0) {
1624 		rw_exit(&irp->irp_lock);
1625 		rw_exit(&iport->iport_lock);
1626 		stmf_trace(iport->iport_alias, "cmd alloc called while fcp "
1627 		    "login was not done. portid=%x, rp=%p", rp->rp_id, rp);
1628 		return (NULL);
1629 	}
1630 
1631 	mutex_enter(&iport->iport_cached_cmd_lock);
1632 	if ((icmd = iport->iport_cached_cmdlist) != NULL) {
1633 		iport->iport_cached_cmdlist = icmd->icmd_next;
1634 		iport->iport_cached_ncmds--;
1635 		cmd = icmd->icmd_cmd;
1636 	} else {
1637 		icmd = NULL;
1638 	}
1639 	mutex_exit(&iport->iport_cached_cmd_lock);
1640 	if (icmd == NULL) {
1641 		cmd = (fct_cmd_t *)fct_alloc(FCT_STRUCT_CMD_FCP_XCHG,
1642 		    port->port_fca_fcp_cmd_size, 0);
1643 		if (cmd == NULL) {
1644 			rw_exit(&irp->irp_lock);
1645 			rw_exit(&iport->iport_lock);
1646 			stmf_trace(iport->iport_alias, "Ran out of "
1647 			    "memory, port=%p", port);
1648 			return (NULL);
1649 		}
1650 
1651 		icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1652 		icmd->icmd_next = NULL;
1653 		cmd->cmd_port = port;
1654 		atomic_add_32(&iport->iport_total_alloced_ncmds, 1);
1655 	}
1656 
1657 	/*
1658 	 * The accuracy of iport_max_active_ncmds is not important
1659 	 */
1660 	if ((iport->iport_total_alloced_ncmds - iport->iport_cached_ncmds) >
1661 	    iport->iport_max_active_ncmds) {
1662 		iport->iport_max_active_ncmds =
1663 		    iport->iport_total_alloced_ncmds -
1664 		    iport->iport_cached_ncmds;
1665 	}
1666 
1667 	/* Lets get a slot */
1668 	cmd_slot = fct_alloc_cmd_slot(iport, cmd);
1669 	if (cmd_slot == FCT_SLOT_EOL) {
1670 		rw_exit(&irp->irp_lock);
1671 		rw_exit(&iport->iport_lock);
1672 		stmf_trace(iport->iport_alias, "Ran out of xchg resources");
1673 		cmd->cmd_handle = 0;
1674 		fct_cmd_free(cmd);
1675 		return (NULL);
1676 	}
1677 	atomic_add_16(&irp->irp_fcp_xchg_count, 1);
1678 	cmd->cmd_rp = rp;
1679 	icmd->icmd_flags |= ICMD_IN_TRANSITION | ICMD_KNOWN_TO_FCA;
1680 	rw_exit(&irp->irp_lock);
1681 	rw_exit(&iport->iport_lock);
1682 
1683 	icmd->icmd_start_time = ddi_get_lbolt();
1684 
1685 	cmd->cmd_specific = stmf_task_alloc(port->port_lport, irp->irp_session,
1686 	    lun, cdb_length, task_ext);
1687 	if ((task = (scsi_task_t *)cmd->cmd_specific) != NULL) {
1688 		task->task_port_private = cmd;
1689 		return (cmd);
1690 	}
1691 
1692 	fct_cmd_free(cmd);
1693 
1694 	return (NULL);
1695 }
1696 
1697 void
1698 fct_scsi_task_free(scsi_task_t *task)
1699 {
1700 	fct_cmd_t *cmd = (fct_cmd_t *)task->task_port_private;
1701 
1702 	cmd->cmd_comp_status = task->task_completion_status;
1703 	fct_cmd_free(cmd);
1704 }
1705 
1706 void
1707 fct_post_rcvd_cmd(fct_cmd_t *cmd, stmf_data_buf_t *dbuf)
1708 {
1709 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
1710 		fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1711 		fct_i_local_port_t *iport =
1712 		    (fct_i_local_port_t *)cmd->cmd_port->port_fct_private;
1713 		fct_i_remote_port_t *irp =
1714 		    (fct_i_remote_port_t *)cmd->cmd_rp->rp_fct_private;
1715 		scsi_task_t *task = (scsi_task_t *)cmd->cmd_specific;
1716 
1717 		uint16_t irp_task = irp->irp_fcp_xchg_count;
1718 		uint32_t load = iport->iport_total_alloced_ncmds -
1719 		    iport->iport_cached_ncmds;
1720 
1721 		DTRACE_FC_4(scsi__command,
1722 		    fct_cmd_t, cmd,
1723 		    fct_i_local_port_t, iport,
1724 		    scsi_task_t, task,
1725 		    fct_i_remote_port_t, irp);
1726 
1727 		if (load >= iport->iport_task_green_limit) {
1728 			if ((load < iport->iport_task_yellow_limit &&
1729 			    irp_task >= 4) ||
1730 			    (load >= iport->iport_task_yellow_limit &&
1731 			    load < iport->iport_task_red_limit &&
1732 			    irp_task >= 1) ||
1733 			    (load >= iport->iport_task_red_limit))
1734 				task->task_additional_flags |=
1735 				    TASK_AF_PORT_LOAD_HIGH;
1736 		}
1737 		stmf_post_task((scsi_task_t *)cmd->cmd_specific, dbuf);
1738 		atomic_and_32(&icmd->icmd_flags, ~ICMD_IN_TRANSITION);
1739 		return;
1740 	}
1741 	/* We dont need dbuf for other cmds */
1742 	if (dbuf) {
1743 		cmd->cmd_port->port_fds->fds_free_data_buf(
1744 		    cmd->cmd_port->port_fds, dbuf);
1745 		dbuf = NULL;
1746 	}
1747 	if (cmd->cmd_type == FCT_CMD_RCVD_ELS) {
1748 		fct_handle_els(cmd);
1749 		return;
1750 	}
1751 	if (cmd->cmd_type == FCT_CMD_RCVD_ABTS) {
1752 		fct_handle_rcvd_abts(cmd);
1753 		return;
1754 	}
1755 
1756 	ASSERT(0);
1757 }
1758 
1759 /*
1760  * This function bypasses fct_handle_els()
1761  */
1762 void
1763 fct_post_implicit_logo(fct_cmd_t *cmd)
1764 {
1765 	fct_local_port_t *port = cmd->cmd_port;
1766 	fct_i_local_port_t *iport =
1767 	    (fct_i_local_port_t *)port->port_fct_private;
1768 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1769 	fct_remote_port_t *rp = cmd->cmd_rp;
1770 	fct_i_remote_port_t *irp = (fct_i_remote_port_t *)rp->rp_fct_private;
1771 
1772 	icmd->icmd_start_time = ddi_get_lbolt();
1773 
1774 	rw_enter(&irp->irp_lock, RW_WRITER);
1775 	atomic_or_32(&icmd->icmd_flags, ICMD_IMPLICIT_CMD_HAS_RESOURCE);
1776 	atomic_add_16(&irp->irp_nonfcp_xchg_count, 1);
1777 	atomic_add_16(&irp->irp_sa_elses_count, 1);
1778 	/*
1779 	 * An implicit LOGO can also be posted to a irp where a PLOGI might
1780 	 * be in process. That PLOGI will reset this flag and decrement the
1781 	 * iport_nrps_login counter.
1782 	 */
1783 	if (irp->irp_flags & IRP_PLOGI_DONE) {
1784 		atomic_add_32(&iport->iport_nrps_login, -1);
1785 	}
1786 	atomic_and_32(&irp->irp_flags, ~(IRP_PLOGI_DONE | IRP_PRLI_DONE));
1787 	atomic_or_32(&icmd->icmd_flags, ICMD_SESSION_AFFECTING);
1788 	fct_post_to_discovery_queue(iport, irp, icmd);
1789 	rw_exit(&irp->irp_lock);
1790 }
1791 
1792 /*
1793  * called with iport_lock held, return the slot number
1794  */
1795 uint16_t
1796 fct_alloc_cmd_slot(fct_i_local_port_t *iport, fct_cmd_t *cmd)
1797 {
1798 	uint16_t cmd_slot;
1799 	uint32_t old, new;
1800 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1801 
1802 	do {
1803 		old = iport->iport_next_free_slot;
1804 		cmd_slot = old & 0xFFFF;
1805 		if (cmd_slot == FCT_SLOT_EOL)
1806 			return (cmd_slot);
1807 		/*
1808 		 * We use high order 16 bits as a counter which keeps on
1809 		 * incrementing to avoid ABA issues with atomic lists.
1810 		 */
1811 		new = ((old + (0x10000)) & 0xFFFF0000);
1812 		new |= iport->iport_cmd_slots[cmd_slot].slot_next;
1813 	} while (atomic_cas_32(&iport->iport_next_free_slot, old, new) != old);
1814 
1815 	atomic_add_16(&iport->iport_nslots_free, -1);
1816 	iport->iport_cmd_slots[cmd_slot].slot_cmd = icmd;
1817 	cmd->cmd_handle = (uint32_t)cmd_slot | 0x80000000 |
1818 	    (((uint32_t)(iport->iport_cmd_slots[cmd_slot].slot_uniq_cntr))
1819 	    << 24);
1820 	return (cmd_slot);
1821 }
1822 
1823 /*
1824  * If icmd is not NULL, irp_lock must be held
1825  */
1826 void
1827 fct_post_to_discovery_queue(fct_i_local_port_t *iport,
1828     fct_i_remote_port_t *irp, fct_i_cmd_t *icmd)
1829 {
1830 	fct_i_cmd_t	**p;
1831 
1832 	ASSERT(!MUTEX_HELD(&iport->iport_worker_lock));
1833 	if (icmd) {
1834 		icmd->icmd_next = NULL;
1835 		for (p = &irp->irp_els_list; *p != NULL;
1836 		    p = &((*p)->icmd_next))
1837 			;
1838 
1839 		*p = icmd;
1840 		atomic_or_32(&icmd->icmd_flags, ICMD_IN_IRP_QUEUE);
1841 	}
1842 
1843 	mutex_enter(&iport->iport_worker_lock);
1844 	if ((irp->irp_flags & IRP_IN_DISCOVERY_QUEUE) == 0) {
1845 
1846 		/*
1847 		 * CAUTION: do not grab local_port/remote_port locks after
1848 		 * grabbing the worker lock.
1849 		 */
1850 		irp->irp_discovery_next = NULL;
1851 		if (iport->iport_rpwe_tail) {
1852 			iport->iport_rpwe_tail->irp_discovery_next = irp;
1853 			iport->iport_rpwe_tail = irp;
1854 		} else {
1855 			iport->iport_rpwe_head = iport->iport_rpwe_tail = irp;
1856 		}
1857 
1858 		atomic_or_32(&irp->irp_flags, IRP_IN_DISCOVERY_QUEUE);
1859 	}
1860 
1861 	/*
1862 	 * We need always signal the port worker irrespective of the fact that
1863 	 * irp is already in discovery queue or not.
1864 	 */
1865 	if (IS_WORKER_SLEEPING(iport)) {
1866 		cv_signal(&iport->iport_worker_cv);
1867 	}
1868 	mutex_exit(&iport->iport_worker_lock);
1869 }
1870 
1871 stmf_status_t
1872 fct_xfer_scsi_data(scsi_task_t *task, stmf_data_buf_t *dbuf, uint32_t ioflags)
1873 {
1874 	fct_cmd_t *cmd = (fct_cmd_t *)task->task_port_private;
1875 
1876 	DTRACE_FC_5(xfer__start,
1877 	    fct_cmd_t, cmd,
1878 	    fct_i_local_port_t, cmd->cmd_port->port_fct_private,
1879 	    scsi_task_t, task,
1880 	    fct_i_remote_port_t, cmd->cmd_rp->rp_fct_private,
1881 	    stmf_data_buf_t, dbuf);
1882 
1883 	return (cmd->cmd_port->port_xfer_scsi_data(cmd, dbuf, ioflags));
1884 }
1885 
1886 void
1887 fct_scsi_data_xfer_done(fct_cmd_t *cmd, stmf_data_buf_t *dbuf, uint32_t ioflags)
1888 {
1889 	fct_i_cmd_t	*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1890 	uint32_t	old, new;
1891 	uint32_t	iof = 0;
1892 
1893 	DTRACE_FC_5(xfer__done,
1894 	    fct_cmd_t, cmd,
1895 	    fct_i_local_port_t, cmd->cmd_port->port_fct_private,
1896 	    scsi_task_t, ((scsi_task_t *)cmd->cmd_specific),
1897 	    fct_i_remote_port_t, cmd->cmd_rp->rp_fct_private,
1898 	    stmf_data_buf_t, dbuf);
1899 
1900 	if (ioflags & FCT_IOF_FCA_DONE) {
1901 		do {
1902 			old = new = icmd->icmd_flags;
1903 			if (old & ICMD_BEING_ABORTED) {
1904 				return;
1905 			}
1906 			new &= ~ICMD_KNOWN_TO_FCA;
1907 		} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
1908 		iof = STMF_IOF_LPORT_DONE;
1909 		cmd->cmd_comp_status = dbuf->db_xfer_status;
1910 	}
1911 
1912 	if (icmd->icmd_flags & ICMD_BEING_ABORTED)
1913 		return;
1914 	stmf_data_xfer_done((scsi_task_t *)cmd->cmd_specific, dbuf, iof);
1915 }
1916 
1917 stmf_status_t
1918 fct_send_scsi_status(scsi_task_t *task, uint32_t ioflags)
1919 {
1920 	fct_cmd_t *cmd = (fct_cmd_t *)task->task_port_private;
1921 
1922 	DTRACE_FC_4(scsi__response,
1923 	    fct_cmd_t, cmd,
1924 	    fct_i_local_port_t,
1925 	    (fct_i_local_port_t *)cmd->cmd_port->port_fct_private,
1926 	    scsi_task_t, task,
1927 	    fct_i_remote_port_t,
1928 	    (fct_i_remote_port_t *)cmd->cmd_rp->rp_fct_private);
1929 
1930 	return (cmd->cmd_port->port_send_cmd_response(cmd, ioflags));
1931 }
1932 
1933 void
1934 fct_send_response_done(fct_cmd_t *cmd, fct_status_t s, uint32_t ioflags)
1935 {
1936 	fct_i_cmd_t	*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1937 	fct_local_port_t *port = cmd->cmd_port;
1938 	fct_i_local_port_t *iport = (fct_i_local_port_t *)
1939 	    port->port_fct_private;
1940 	uint32_t old, new;
1941 
1942 	if ((ioflags & FCT_IOF_FCA_DONE) == 0) {
1943 		/* Until we support confirmed completions, this is an error */
1944 		fct_queue_cmd_for_termination(cmd, s);
1945 		return;
1946 	}
1947 	do {
1948 		old = new = icmd->icmd_flags;
1949 		if (old & ICMD_BEING_ABORTED) {
1950 			return;
1951 		}
1952 		new &= ~ICMD_KNOWN_TO_FCA;
1953 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
1954 
1955 	cmd->cmd_comp_status = s;
1956 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
1957 		stmf_send_status_done((scsi_task_t *)cmd->cmd_specific, s,
1958 		    STMF_IOF_LPORT_DONE);
1959 		return;
1960 	}
1961 
1962 	if (cmd->cmd_type == FCT_CMD_RCVD_ELS) {
1963 		fct_cmd_free(cmd);
1964 		return;
1965 	} else if (cmd->cmd_type == FCT_CMD_SOL_ELS) {
1966 		fct_handle_sol_els_completion(iport, icmd);
1967 	} else if (cmd->cmd_type == FCT_CMD_SOL_CT) {
1968 		/* Tell the caller that we are done */
1969 		atomic_or_32(&icmd->icmd_flags, ICMD_CMD_COMPLETE);
1970 	} else {
1971 		ASSERT(0);
1972 	}
1973 }
1974 
1975 void
1976 fct_cmd_free(fct_cmd_t *cmd)
1977 {
1978 	char			info[80];
1979 	fct_i_cmd_t		*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1980 	fct_local_port_t	*port = cmd->cmd_port;
1981 	fct_i_local_port_t	*iport = (fct_i_local_port_t *)
1982 	    port->port_fct_private;
1983 	fct_i_remote_port_t	*irp = NULL;
1984 	int			do_abts_acc = 0;
1985 	uint32_t		old, new;
1986 
1987 	ASSERT(!mutex_owned(&iport->iport_worker_lock));
1988 	/* Give the slot back */
1989 	if (CMD_HANDLE_VALID(cmd->cmd_handle)) {
1990 		uint16_t n = CMD_HANDLE_SLOT_INDEX(cmd->cmd_handle);
1991 		fct_cmd_slot_t *slot;
1992 
1993 		/*
1994 		 * If anything went wrong, grab the lock as writer. This is
1995 		 * probably unnecessary.
1996 		 */
1997 		if ((cmd->cmd_comp_status != FCT_SUCCESS) ||
1998 		    (icmd->icmd_flags & ICMD_ABTS_RECEIVED)) {
1999 			rw_enter(&iport->iport_lock, RW_WRITER);
2000 		} else {
2001 			rw_enter(&iport->iport_lock, RW_READER);
2002 		}
2003 
2004 		if ((icmd->icmd_flags & ICMD_ABTS_RECEIVED) &&
2005 		    (cmd->cmd_link != NULL)) {
2006 			do_abts_acc = 1;
2007 		}
2008 
2009 		/* XXX Validate slot before freeing */
2010 
2011 		slot = &iport->iport_cmd_slots[n];
2012 		slot->slot_uniq_cntr++;
2013 		slot->slot_cmd = NULL;
2014 		do {
2015 			old = iport->iport_next_free_slot;
2016 			slot->slot_next = old & 0xFFFF;
2017 			new = (old + 0x10000) & 0xFFFF0000;
2018 			new |= slot->slot_no;
2019 		} while (atomic_cas_32(&iport->iport_next_free_slot,
2020 		    old, new) != old);
2021 		cmd->cmd_handle = 0;
2022 		atomic_add_16(&iport->iport_nslots_free, 1);
2023 		if (cmd->cmd_rp) {
2024 			irp = (fct_i_remote_port_t *)
2025 			    cmd->cmd_rp->rp_fct_private;
2026 			if (cmd->cmd_type == FCT_CMD_FCP_XCHG)
2027 				atomic_add_16(&irp->irp_fcp_xchg_count, -1);
2028 			else
2029 				atomic_add_16(&irp->irp_nonfcp_xchg_count, -1);
2030 		}
2031 		rw_exit(&iport->iport_lock);
2032 	} else if ((icmd->icmd_flags & ICMD_IMPLICIT) &&
2033 	    (icmd->icmd_flags & ICMD_IMPLICIT_CMD_HAS_RESOURCE)) {
2034 		/* for implicit cmd, no cmd slot is used */
2035 		if (cmd->cmd_rp) {
2036 			irp = (fct_i_remote_port_t *)
2037 			    cmd->cmd_rp->rp_fct_private;
2038 			if (cmd->cmd_type == FCT_CMD_FCP_XCHG)
2039 				atomic_add_16(&irp->irp_fcp_xchg_count, -1);
2040 			else
2041 				atomic_add_16(&irp->irp_nonfcp_xchg_count, -1);
2042 		}
2043 	}
2044 
2045 	if (do_abts_acc) {
2046 		fct_cmd_t *lcmd = cmd->cmd_link;
2047 		fct_fill_abts_acc(lcmd);
2048 		if (port->port_send_cmd_response(lcmd,
2049 		    FCT_IOF_FORCE_FCA_DONE) != FCT_SUCCESS) {
2050 			/*
2051 			 * XXX Throw HBA fatal error event
2052 			 * Later shutdown svc will terminate the ABTS in the end
2053 			 */
2054 			(void) snprintf(info, 80,
2055 			    "fct_cmd_free: iport-%p, ABTS_ACC"
2056 			    " port_send_cmd_response failed", (void *)iport);
2057 			info[79] = 0;
2058 			(void) fct_port_shutdown(iport->iport_port,
2059 			    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
2060 			return;
2061 		} else {
2062 			fct_cmd_free(lcmd);
2063 			cmd->cmd_link = NULL;
2064 		}
2065 	}
2066 
2067 	/* Free the cmd */
2068 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
2069 		if (iport->iport_cached_ncmds < max_cached_ncmds) {
2070 			icmd->icmd_flags = 0;
2071 			mutex_enter(&iport->iport_cached_cmd_lock);
2072 			icmd->icmd_next = iport->iport_cached_cmdlist;
2073 			iport->iport_cached_cmdlist = icmd;
2074 			iport->iport_cached_ncmds++;
2075 			mutex_exit(&iport->iport_cached_cmd_lock);
2076 		} else {
2077 			atomic_add_32(&iport->iport_total_alloced_ncmds, -1);
2078 			fct_free(cmd);
2079 		}
2080 	} else {
2081 		fct_free(cmd);
2082 	}
2083 }
2084 
2085 /* ARGSUSED */
2086 stmf_status_t
2087 fct_scsi_abort(stmf_local_port_t *lport, int abort_cmd, void *arg,
2088 							uint32_t flags)
2089 {
2090 	stmf_status_t ret = STMF_SUCCESS;
2091 	scsi_task_t *task;
2092 	fct_cmd_t *cmd;
2093 	fct_i_cmd_t *icmd;
2094 	fct_local_port_t *port;
2095 	uint32_t old, new;
2096 
2097 	ASSERT(abort_cmd == STMF_LPORT_ABORT_TASK);
2098 
2099 	task = (scsi_task_t *)arg;
2100 	cmd = (fct_cmd_t *)task->task_port_private;
2101 	icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2102 	port = (fct_local_port_t *)lport->lport_port_private;
2103 
2104 	do {
2105 		old = new = icmd->icmd_flags;
2106 		if ((old & ICMD_KNOWN_TO_FCA) == 0)
2107 			return (STMF_NOT_FOUND);
2108 		ASSERT((old & ICMD_FCA_ABORT_CALLED) == 0);
2109 		new |= ICMD_BEING_ABORTED | ICMD_FCA_ABORT_CALLED;
2110 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
2111 	ret = port->port_abort_cmd(port, cmd, 0);
2112 	if ((ret == FCT_NOT_FOUND) || (ret == FCT_ABORT_SUCCESS)) {
2113 		atomic_and_32(&icmd->icmd_flags, ~ICMD_KNOWN_TO_FCA);
2114 	} else if (ret == FCT_BUSY) {
2115 		atomic_and_32(&icmd->icmd_flags, ~ICMD_FCA_ABORT_CALLED);
2116 	}
2117 
2118 	return (ret);
2119 }
2120 
2121 void
2122 fct_ctl(struct stmf_local_port *lport, int cmd, void *arg)
2123 {
2124 	fct_local_port_t *port;
2125 	fct_i_local_port_t *iport;
2126 	stmf_change_status_t st;
2127 	stmf_change_status_t *pst;
2128 
2129 	ASSERT((cmd == STMF_CMD_LPORT_ONLINE) ||
2130 	    (cmd == STMF_ACK_LPORT_ONLINE_COMPLETE) ||
2131 	    (cmd == STMF_CMD_LPORT_OFFLINE) ||
2132 	    (cmd == STMF_ACK_LPORT_OFFLINE_COMPLETE) ||
2133 	    (cmd == FCT_CMD_PORT_ONLINE_COMPLETE) ||
2134 	    (cmd == FCT_CMD_PORT_OFFLINE_COMPLETE));
2135 
2136 	port = (fct_local_port_t *)lport->lport_port_private;
2137 	pst = (stmf_change_status_t *)arg;
2138 	st.st_completion_status = STMF_SUCCESS;
2139 	st.st_additional_info = NULL;
2140 
2141 	iport = (fct_i_local_port_t *)port->port_fct_private;
2142 	/*
2143 	 * We are mostly a passthrough, except during offline.
2144 	 */
2145 	switch (cmd) {
2146 	case STMF_CMD_LPORT_ONLINE:
2147 		if (iport->iport_state == FCT_STATE_ONLINE)
2148 			st.st_completion_status = STMF_ALREADY;
2149 		else if (iport->iport_state != FCT_STATE_OFFLINE)
2150 			st.st_completion_status = STMF_INVALID_ARG;
2151 		if (st.st_completion_status != STMF_SUCCESS) {
2152 			(void) stmf_ctl(STMF_CMD_LPORT_ONLINE_COMPLETE, lport,
2153 			    &st);
2154 			break;
2155 		}
2156 		iport->iport_state_not_acked = 1;
2157 		iport->iport_state = FCT_STATE_ONLINING;
2158 		port->port_ctl(port, FCT_CMD_PORT_ONLINE, arg);
2159 		break;
2160 	case FCT_CMD_PORT_ONLINE_COMPLETE:
2161 		ASSERT(iport->iport_state == FCT_STATE_ONLINING);
2162 		if (pst->st_completion_status != FCT_SUCCESS) {
2163 			iport->iport_state = FCT_STATE_OFFLINE;
2164 			iport->iport_state_not_acked = 0;
2165 		} else {
2166 			iport->iport_state = FCT_STATE_ONLINE;
2167 		}
2168 		(void) stmf_ctl(STMF_CMD_LPORT_ONLINE_COMPLETE, lport, arg);
2169 		break;
2170 	case STMF_ACK_LPORT_ONLINE_COMPLETE:
2171 		ASSERT(iport->iport_state == FCT_STATE_ONLINE);
2172 		iport->iport_state_not_acked = 0;
2173 		port->port_ctl(port, FCT_ACK_PORT_ONLINE_COMPLETE, arg);
2174 		break;
2175 
2176 	case STMF_CMD_LPORT_OFFLINE:
2177 		if (iport->iport_state == FCT_STATE_OFFLINE)
2178 			st.st_completion_status = STMF_ALREADY;
2179 		else if (iport->iport_state != FCT_STATE_ONLINE)
2180 			st.st_completion_status = STMF_INVALID_ARG;
2181 		if (st.st_completion_status != STMF_SUCCESS) {
2182 			(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE_COMPLETE, lport,
2183 			    &st);
2184 			break;
2185 		}
2186 		iport->iport_state_not_acked = 1;
2187 		iport->iport_state = FCT_STATE_OFFLINING;
2188 		port->port_ctl(port, FCT_CMD_PORT_OFFLINE, arg);
2189 		break;
2190 	case FCT_CMD_PORT_OFFLINE_COMPLETE:
2191 		ASSERT(iport->iport_state == FCT_STATE_OFFLINING);
2192 		if (pst->st_completion_status != FCT_SUCCESS) {
2193 			iport->iport_state = FCT_STATE_ONLINE;
2194 			iport->iport_state_not_acked = 0;
2195 			(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE_COMPLETE, lport,
2196 			    pst);
2197 			break;
2198 		}
2199 
2200 		/*
2201 		 * If FCA's offline was successful, we dont tell stmf yet.
2202 		 * Becasue now we have to do the cleanup before we go upto
2203 		 * stmf. That cleanup is done by the worker thread.
2204 		 */
2205 
2206 		/* FCA is offline, post a link down, its harmless anyway */
2207 		fct_handle_event(port, FCT_EVENT_LINK_DOWN, 0, 0);
2208 
2209 		/* Trigger port offline processing by the worker */
2210 		iport->iport_offline_prstate = FCT_OPR_START;
2211 		break;
2212 	case STMF_ACK_LPORT_OFFLINE_COMPLETE:
2213 		ASSERT(iport->iport_state == FCT_STATE_OFFLINE);
2214 		iport->iport_state_not_acked = 0;
2215 		port->port_ctl(port, FCT_ACK_PORT_OFFLINE_COMPLETE, arg);
2216 		break;
2217 	}
2218 }
2219 
2220 /* ARGSUSED */
2221 stmf_status_t
2222 fct_info(uint32_t cmd, stmf_local_port_t *lport, void *arg, uint8_t *buf,
2223 						uint32_t *bufsizep)
2224 {
2225 	return (STMF_NOT_SUPPORTED);
2226 }
2227 
2228 /*
2229  * implicit: if it's true, it means it will only be used in fct module, or else
2230  * it will be sent to the link.
2231  */
2232 fct_cmd_t *
2233 fct_create_solels(fct_local_port_t *port, fct_remote_port_t *rp, int implicit,
2234     uchar_t elsop, uint32_t wkdid, fct_icmd_cb_t icmdcb)
2235 {
2236 	fct_cmd_t		*cmd	= NULL;
2237 	fct_i_cmd_t		*icmd	= NULL;
2238 	fct_els_t		*els	= NULL;
2239 	fct_i_remote_port_t	*irp	= NULL;
2240 	uint8_t			*p	= NULL;
2241 	uint32_t		 ptid	= 0;
2242 
2243 	cmd = (fct_cmd_t *)fct_alloc(FCT_STRUCT_CMD_SOL_ELS,
2244 	    port->port_fca_sol_els_private_size, 0);
2245 	if (!cmd) {
2246 		return (NULL);
2247 	}
2248 
2249 	if (rp) {
2250 		irp = RP_TO_IRP(rp);
2251 	} else if (((irp = fct_portid_to_portptr(PORT_TO_IPORT(port),
2252 	    wkdid)) == NULL) && (elsop != ELS_OP_PLOGI)) {
2253 		stmf_trace(PORT_TO_IPORT(port)->iport_alias,
2254 		    "fct_create_solels: Must PLOGI to %x first", wkdid);
2255 		fct_free(cmd);
2256 		return (NULL);
2257 	}
2258 
2259 	cmd->cmd_port	= port;
2260 	cmd->cmd_oxid	= PTR2INT(cmd, uint16_t);
2261 	cmd->cmd_rxid	= 0xFFFF;
2262 	cmd->cmd_handle = 0;
2263 	icmd		= CMD_TO_ICMD(cmd);
2264 	els		= ICMD_TO_ELS(icmd);
2265 	icmd->icmd_cb	= icmdcb;
2266 	if (irp) {
2267 		cmd->cmd_rp	   = irp->irp_rp;
2268 		cmd->cmd_rp_handle = irp->irp_rp->rp_handle;
2269 		cmd->cmd_rportid   = irp->irp_rp->rp_id;
2270 	} else {
2271 		cmd->cmd_rp_handle = FCT_HANDLE_NONE;
2272 		cmd->cmd_rportid   = wkdid;
2273 	}
2274 	cmd->cmd_lportid = (PORT_TO_IPORT(port))->iport_link_info.portid;
2275 
2276 	if (implicit) {
2277 		/*
2278 		 * Since we will not send it to FCA, so we only allocate space
2279 		 */
2280 		ASSERT(elsop & (ELS_OP_LOGO | ELS_OP_PLOGI));
2281 		icmd->icmd_flags |= ICMD_IMPLICIT;
2282 		if (elsop == ELS_OP_LOGO) {
2283 			/*
2284 			 * Handling implicit LOGO should dependent on as less
2285 			 * as resources. So a trick here.
2286 			 */
2287 			els->els_req_size = 1;
2288 			els->els_req_payload = cmd->cmd_fca_private;
2289 		} else {
2290 			els->els_req_alloc_size = els->els_req_size = 116;
2291 			els->els_resp_alloc_size = els->els_resp_size = 116;
2292 			els->els_req_payload = (uint8_t *)
2293 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2294 			els->els_resp_payload = (uint8_t *)
2295 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2296 		}
2297 	} else {
2298 		/*
2299 		 * Allocate space for its request and response
2300 		 * Fill the request payload according to spec.
2301 		 */
2302 		switch (elsop) {
2303 		case ELS_OP_LOGO:
2304 			els->els_resp_alloc_size = els->els_resp_size = 4;
2305 			els->els_resp_payload = (uint8_t *)kmem_zalloc(
2306 			    els->els_resp_size, KM_SLEEP);
2307 			els->els_req_alloc_size = els->els_req_size = 16;
2308 			els->els_req_payload = (uint8_t *)kmem_zalloc(
2309 			    els->els_req_size, KM_SLEEP);
2310 			ptid = PORT_TO_IPORT(port)->iport_link_info.portid;
2311 			fct_value_to_netbuf(ptid, els->els_req_payload + 5, 3);
2312 			bcopy(port->port_pwwn, els->els_req_payload + 8, 8);
2313 			break;
2314 
2315 		case ELS_OP_RSCN:
2316 			els->els_resp_alloc_size = els->els_resp_size = 4;
2317 			els->els_resp_payload = (uint8_t *)kmem_zalloc(
2318 			    els->els_resp_size, KM_SLEEP);
2319 			els->els_req_size = els->els_req_alloc_size = 8;
2320 			els->els_req_payload = (uint8_t *)kmem_zalloc(
2321 			    els->els_req_size, KM_SLEEP);
2322 			els->els_req_payload[1] = 0x04;
2323 			els->els_req_payload[3] = 0x08;
2324 			els->els_req_payload[4] |= 0x80;
2325 			ptid = PORT_TO_IPORT(port)->iport_link_info.portid;
2326 			fct_value_to_netbuf(ptid, els->els_req_payload + 5, 3);
2327 			break;
2328 
2329 		case ELS_OP_PLOGI:
2330 			els->els_resp_alloc_size = els->els_resp_size = 116;
2331 			els->els_resp_payload = (uint8_t *)
2332 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2333 			els->els_req_alloc_size = els->els_req_size = 116;
2334 			p = els->els_req_payload = (uint8_t *)
2335 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2336 			bcopy(port->port_pwwn, p + 20, 8);
2337 			bcopy(port->port_nwwn, p + 28, 8);
2338 
2339 			/*
2340 			 * Common service parameters
2341 			 */
2342 			p[0x04] = 0x09;		/* high version */
2343 			p[0x05] = 0x08;		/* low version */
2344 			p[0x06] = 0x00;		/* BB credit: 0x0065 */
2345 			p[0x07] = 0x65;
2346 
2347 			/* CI0: Continuously Increasing Offset - 1 */
2348 			/* RRO: Randomly Relative Offset - 0 */
2349 			/* VVV: Vendor Version Level - 0 */
2350 			/* N-F: N or F Port Payload Sender - 0 (N) */
2351 			/* BBM: BB Credit Management - 0 (Normal) */
2352 			p[0x08] = 0x80;
2353 			p[0x09] = 0x00;
2354 
2355 			/* Max RX size */
2356 			p[0x0A] = 0x08;
2357 			p[0x0B] = 0x00;
2358 
2359 			/* NPTCS: N Port Total Concurrent Sequences - 0x0000 */
2360 			p[0x0C] = 0x00;
2361 			p[0x0D] = 0x00;
2362 
2363 			/* ROIC: Relative Offset By Info - 0xFFFF */
2364 			p[0x0E] = 0xFF;
2365 			p[0x0F] = 0xFF;
2366 
2367 			/* EDTOV: Error Detect Timeout - 0x000007D0 */
2368 			p[0x10] = 0x00;
2369 			p[0x11] = 0x00;
2370 			p[0x12] = 0x07;
2371 			p[0x13] = 0xD0;
2372 
2373 			/*
2374 			 * Class-3 Parameters
2375 			 */
2376 			/* C3-VAL: Class 3 Value - 1 */
2377 			/* C3-XID: X_ID Reassignment - 0 */
2378 			/* C3-IPA: Initial Process Assignment */
2379 			/* C3-AI-DCC: Data compression capable */
2380 			/* C3-AI-DC-HB: Data compression history buffer size */
2381 			/* C3-AI-DCE: Data encrytion capable */
2382 			/* C3-AI-CSC: Clock synchronization capable */
2383 			/* C3-ErrPol: Error pliciy */
2384 			/* C3-CatSeq: Information Cat. Per Sequence */
2385 			/* C3-AR-DCC: */
2386 			/* C3-AR-DC-HB: */
2387 			/* C3-AR-DCE: */
2388 			/* C3-AR-CSC */
2389 			p[0x44] = 0x80;
2390 			p[0x45] = 0x00;
2391 			p[0x46] = 0x00;
2392 			p[0x47] = 0x00;
2393 			p[0x48] = 0x00;
2394 			p[0x49] = 0x00;
2395 
2396 			/* C3-RxSize: Class 3 receive data size */
2397 			p[0x4A] = 0x08;
2398 			p[0x4B] = 0x00;
2399 
2400 			/* C3-ConSeq: Class 3 Concourrent sequences */
2401 			p[0x4C] = 0x00;
2402 			p[0x4D] = 0xFF;
2403 
2404 			/* C3-OSPE: Class 3 open sequence per exchange */
2405 			p[0x50] = 0x00;
2406 			p[0x51] = 0x01;
2407 
2408 			break;
2409 
2410 		case ELS_OP_SCR:
2411 			els->els_resp_alloc_size = els->els_resp_size = 4;
2412 			els->els_resp_payload = (uint8_t *)
2413 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2414 			els->els_req_alloc_size = els->els_req_size = 8;
2415 			p = els->els_req_payload = (uint8_t *)
2416 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2417 			p[7] = FC_SCR_FULL_REGISTRATION;
2418 			break;
2419 		case ELS_OP_RLS:
2420 			els->els_resp_alloc_size = els->els_resp_size = 28;
2421 			els->els_resp_payload = (uint8_t *)
2422 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2423 			els->els_req_alloc_size = els->els_req_size = 8;
2424 			p = els->els_req_payload = (uint8_t *)
2425 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2426 			ptid = PORT_TO_IPORT(port)->iport_link_info.portid;
2427 			fct_value_to_netbuf(ptid, els->els_req_payload + 5, 3);
2428 			break;
2429 
2430 		default:
2431 			ASSERT(0);
2432 		}
2433 	}
2434 
2435 	els->els_req_payload[0] = elsop;
2436 	return (cmd);
2437 }
2438 
2439 fct_cmd_t *
2440 fct_create_solct(fct_local_port_t *port, fct_remote_port_t *query_rp,
2441     uint16_t ctop, fct_icmd_cb_t icmdcb)
2442 {
2443 	fct_cmd_t		*cmd	 = NULL;
2444 	fct_i_cmd_t		*icmd	 = NULL;
2445 	fct_sol_ct_t		*ct	 = NULL;
2446 	uint8_t			*p	 = NULL;
2447 	fct_i_remote_port_t	*irp	 = NULL;
2448 	fct_i_local_port_t	*iport	 = NULL;
2449 	char			*nname	 = NULL;
2450 	int			 namelen = 0;
2451 
2452 	/*
2453 	 * Allocate space
2454 	 */
2455 	cmd = fct_alloc(FCT_STRUCT_CMD_SOL_CT,
2456 	    port->port_fca_sol_ct_private_size, 0);
2457 	if (!cmd) {
2458 		return (NULL);
2459 	}
2460 
2461 	/*
2462 	 * We should have PLOGIed to the name server (0xFFFFFC)
2463 	 * Caution: this irp is not query_rp->rp_fct_private.
2464 	 */
2465 	irp = fct_portid_to_portptr((fct_i_local_port_t *)
2466 	    port->port_fct_private, FS_NAME_SERVER);
2467 	if (irp == NULL) {
2468 		stmf_trace(PORT_TO_IPORT(port)->iport_alias,
2469 		    "fct_create_solct: Must PLOGI name server first");
2470 		fct_free(cmd);
2471 		return (NULL);
2472 	}
2473 
2474 	cmd->cmd_port	   = port;
2475 	cmd->cmd_rp	   = irp->irp_rp;
2476 	cmd->cmd_rp_handle = irp->irp_rp->rp_handle;
2477 	cmd->cmd_rportid   = irp->irp_rp->rp_id;
2478 	cmd->cmd_lportid   = (PORT_TO_IPORT(port))->iport_link_info.portid;
2479 	cmd->cmd_oxid	   = PTR2INT(cmd, uint16_t);
2480 	cmd->cmd_rxid	   = 0xFFFF;
2481 	cmd->cmd_handle	   = 0;
2482 	icmd		   = CMD_TO_ICMD(cmd);
2483 	ct		   = ICMD_TO_CT(icmd);
2484 	icmd->icmd_cb	   = icmdcb;
2485 	iport		   = ICMD_TO_IPORT(icmd);
2486 
2487 	switch (ctop) {
2488 	case NS_GSNN_NN:
2489 		/*
2490 		 * Allocate max space for its sybolic name
2491 		 */
2492 		ct->ct_resp_alloc_size = ct->ct_resp_size = 272;
2493 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2494 		    KM_SLEEP);
2495 
2496 		ct->ct_req_size = ct->ct_req_alloc_size = 24;
2497 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2498 		    KM_SLEEP);
2499 
2500 		bcopy(query_rp->rp_nwwn, p + 16, 8);
2501 		break;
2502 
2503 	case NS_RNN_ID:
2504 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2505 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2506 		    KM_SLEEP);
2507 		ct->ct_req_size = ct->ct_req_alloc_size = 28;
2508 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2509 		    KM_SLEEP);
2510 
2511 		/*
2512 		 * Port Identifier
2513 		 */
2514 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2515 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2516 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2517 
2518 		/*
2519 		 * Node Name
2520 		 */
2521 		bcopy(port->port_nwwn, p + 20, 8);
2522 		break;
2523 
2524 	case NS_RCS_ID:
2525 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2526 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2527 		    KM_SLEEP);
2528 		ct->ct_req_size = ct->ct_req_alloc_size = 24;
2529 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2530 		    KM_SLEEP);
2531 
2532 		/*
2533 		 * Port Identifier
2534 		 */
2535 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2536 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2537 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2538 
2539 		/*
2540 		 * Class of Service
2541 		 */
2542 		*(p + 23) = FC_NS_CLASS3;
2543 		break;
2544 
2545 	case NS_RFT_ID:
2546 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2547 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2548 		    KM_SLEEP);
2549 		ct->ct_req_size = ct->ct_req_alloc_size = 52;
2550 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2551 		    KM_SLEEP);
2552 
2553 		/*
2554 		 * Port Identifier
2555 		 */
2556 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2557 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2558 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2559 
2560 		/*
2561 		 * FC-4 Protocol Types
2562 		 */
2563 		*(p + 22) = 0x1;	/* 0x100 */
2564 		break;
2565 
2566 	case NS_RSPN_ID:
2567 		/*
2568 		 * If we get here, port->port_sym_port_name is always not NULL.
2569 		 */
2570 		ASSERT(port->port_sym_port_name);
2571 		namelen = strlen(port->port_sym_port_name);
2572 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2573 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2574 		    KM_SLEEP);
2575 		ct->ct_req_size = ct->ct_req_alloc_size =
2576 		    (21 + namelen + 3) & ~3;
2577 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2578 		    KM_SLEEP);
2579 
2580 		/*
2581 		 * Port Identifier
2582 		 */
2583 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2584 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2585 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2586 
2587 		/*
2588 		 * String length
2589 		 */
2590 		p[20] = namelen;
2591 
2592 		/*
2593 		 * Symbolic port name
2594 		 */
2595 		bcopy(port->port_sym_port_name, p + 21, ct->ct_req_size - 21);
2596 		break;
2597 
2598 	case NS_RSNN_NN:
2599 		namelen = port->port_sym_node_name == NULL ?
2600 		    strlen(utsname.nodename) :
2601 		    strlen(port->port_sym_node_name);
2602 		nname = port->port_sym_node_name == NULL ?
2603 		    utsname.nodename : port->port_sym_node_name;
2604 
2605 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2606 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2607 		    KM_SLEEP);
2608 		ct->ct_req_size = ct->ct_req_alloc_size =
2609 		    (25 + namelen + 3) & ~3;
2610 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2611 		    KM_SLEEP);
2612 
2613 		/*
2614 		 * Node name
2615 		 */
2616 		bcopy(port->port_nwwn, p + 16, 8);
2617 
2618 		/*
2619 		 * String length
2620 		 */
2621 		p[24] = namelen;
2622 
2623 		/*
2624 		 * Symbolic node name
2625 		 */
2626 		bcopy(nname, p + 25, ct->ct_req_size - 25);
2627 		break;
2628 
2629 	case NS_GSPN_ID:
2630 		ct->ct_resp_alloc_size = ct->ct_resp_size = 272;
2631 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2632 		    KM_SLEEP);
2633 		ct->ct_req_size = ct->ct_req_alloc_size = 20;
2634 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2635 		    KM_SLEEP);
2636 		/*
2637 		 * Port Identifier
2638 		 */
2639 		p[17] = (query_rp->rp_id >> 16) & 0xFF;
2640 		p[18] = (query_rp->rp_id >>  8) & 0xFF;
2641 		p[19] = (query_rp->rp_id >>  0) & 0xFF;
2642 		break;
2643 
2644 	case NS_GCS_ID:
2645 		ct->ct_resp_alloc_size = ct->ct_resp_size = 20;
2646 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2647 		    KM_SLEEP);
2648 		ct->ct_req_size = ct->ct_req_alloc_size = 20;
2649 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2650 		    KM_SLEEP);
2651 		/*
2652 		 * Port Identifier
2653 		 */
2654 		p[17] = (query_rp->rp_id >> 16) & 0xFF;
2655 		p[18] = (query_rp->rp_id >>  8) & 0xFF;
2656 		p[19] = (query_rp->rp_id >>  0) & 0xFF;
2657 		break;
2658 
2659 	case NS_GFT_ID:
2660 		ct->ct_resp_alloc_size = ct->ct_resp_size = 48;
2661 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2662 		    KM_SLEEP);
2663 		ct->ct_req_size = ct->ct_req_alloc_size = 20;
2664 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2665 		    KM_SLEEP);
2666 		/*
2667 		 * Port Identifier
2668 		 */
2669 		p[17] = (query_rp->rp_id >> 16) & 0xFF;
2670 		p[18] = (query_rp->rp_id >>  8) & 0xFF;
2671 		p[19] = (query_rp->rp_id >>  0) & 0xFF;
2672 		break;
2673 
2674 	case NS_GID_PN:
2675 		ct->ct_resp_alloc_size = ct->ct_resp_size = 20;
2676 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2677 		    KM_SLEEP);
2678 
2679 		ct->ct_req_size = ct->ct_req_alloc_size = 24;
2680 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2681 		    KM_SLEEP);
2682 
2683 		bcopy(query_rp->rp_pwwn, p + 16, 8);
2684 		break;
2685 
2686 	default:
2687 		/* CONSTCOND */
2688 		ASSERT(0);
2689 	}
2690 
2691 	FCT_FILL_CTIU_PREAMPLE(p, ctop);
2692 	return (cmd);
2693 }
2694 
2695 /*
2696  * Cmd can only be solicited CT/ELS. They will be dispatched to the discovery
2697  * queue eventually too.
2698  * We queue solicited cmds here to track solicited cmds and to take full use
2699  * of single thread mechanism.
2700  * But in current implmentation, we don't use  this mechanism on SOL_CT, PLOGI.
2701  * To avoid to interrupt current flow, ICMD_IN_SOLCMD_QUEUE is used here.
2702  */
2703 void
2704 fct_post_to_solcmd_queue(fct_local_port_t *port, fct_cmd_t *cmd)
2705 {
2706 	fct_i_local_port_t	*iport	= (fct_i_local_port_t *)
2707 	    port->port_fct_private;
2708 	fct_i_cmd_t *icmd		= (fct_i_cmd_t *)cmd->cmd_fct_private;
2709 
2710 	mutex_enter(&iport->iport_worker_lock);
2711 	icmd->icmd_solcmd_next = iport->iport_solcmd_queue;
2712 	iport->iport_solcmd_queue = icmd;
2713 	atomic_or_32(&icmd->icmd_flags, ICMD_IN_SOLCMD_QUEUE | ICMD_SOLCMD_NEW);
2714 	if (IS_WORKER_SLEEPING(iport)) {
2715 		cv_signal(&iport->iport_worker_cv);
2716 	}
2717 	mutex_exit(&iport->iport_worker_lock);
2718 }
2719 
2720 /* ARGSUSED */
2721 void
2722 fct_event_handler(stmf_local_port_t *lport, int eventid, void *arg,
2723     uint32_t flags)
2724 {
2725 	fct_local_port_t	*port  = (fct_local_port_t *)
2726 	    lport->lport_port_private;
2727 	fct_i_local_port_t	*iport = (fct_i_local_port_t *)
2728 	    port->port_fct_private;
2729 	stmf_scsi_session_t	*ss;
2730 	fct_i_remote_port_t	*irp;
2731 
2732 	switch (eventid) {
2733 	case LPORT_EVENT_INITIAL_LUN_MAPPED:
2734 		ss = (stmf_scsi_session_t *)arg;
2735 		irp = (fct_i_remote_port_t *)ss->ss_port_private;
2736 		stmf_trace(iport->iport_alias,
2737 		    "Initial LUN mapped to session ss-%p, irp-%p", ss, irp);
2738 		break;
2739 
2740 	default:
2741 		stmf_trace(iport->iport_alias,
2742 		    "Unknown event received, %d", eventid);
2743 	}
2744 }
2745 
2746 void
2747 fct_send_cmd_done(fct_cmd_t *cmd, fct_status_t s, uint32_t ioflags)
2748 {
2749 	/* XXX For now just call send_resp_done() */
2750 	fct_send_response_done(cmd, s, ioflags);
2751 }
2752 
2753 void
2754 fct_cmd_fca_aborted(fct_cmd_t *cmd, fct_status_t s, uint32_t ioflags)
2755 {
2756 	fct_i_cmd_t		*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2757 	char			info[160];
2758 	unsigned long long	st;
2759 
2760 	st = s;	/* To make gcc happy */
2761 	ASSERT(icmd->icmd_flags & ICMD_BEING_ABORTED);
2762 	if ((((s != FCT_ABORT_SUCCESS) && (s != FCT_NOT_FOUND))) ||
2763 	    ((ioflags & FCT_IOF_FCA_DONE) == 0)) {
2764 		(void) snprintf(info, 160, "fct_cmd_fca_aborted: cmd-%p, "
2765 		    "s-%llx, iofalgs-%x", (void *)cmd, st, ioflags);
2766 		info[159] = 0;
2767 		(void) fct_port_shutdown(cmd->cmd_port,
2768 		    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
2769 		return;
2770 	}
2771 
2772 	atomic_and_32(&icmd->icmd_flags, ~ICMD_KNOWN_TO_FCA);
2773 	/* For non FCP Rest of the work is done by the terminator */
2774 	/* For FCP stuff just call stmf */
2775 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
2776 		stmf_task_lport_aborted((scsi_task_t *)cmd->cmd_specific,
2777 		    s, STMF_IOF_LPORT_DONE);
2778 	}
2779 }
2780 
2781 /*
2782  * FCA drivers will use it, when they want to abort some FC transactions
2783  * due to lack of resource.
2784  */
2785 uint16_t
2786 fct_get_rp_handle(fct_local_port_t *port, uint32_t rportid)
2787 {
2788 	fct_i_remote_port_t	*irp;
2789 
2790 	irp = fct_portid_to_portptr(
2791 	    (fct_i_local_port_t *)(port->port_fct_private), rportid);
2792 	if (irp == NULL) {
2793 		return (0xFFFF);
2794 	} else {
2795 		return (irp->irp_rp->rp_handle);
2796 	}
2797 }
2798 
2799 fct_cmd_t *
2800 fct_handle_to_cmd(fct_local_port_t *port, uint32_t fct_handle)
2801 {
2802 	fct_cmd_slot_t *slot;
2803 	uint16_t ndx;
2804 
2805 	if (!CMD_HANDLE_VALID(fct_handle))
2806 		return (NULL);
2807 	if ((ndx = CMD_HANDLE_SLOT_INDEX(fct_handle)) >= port->port_max_xchges)
2808 		return (NULL);
2809 
2810 	slot = &((fct_i_local_port_t *)port->port_fct_private)->iport_cmd_slots[
2811 	    ndx];
2812 
2813 	if ((slot->slot_uniq_cntr | 0x80) != (fct_handle >> 24))
2814 		return (NULL);
2815 	return (slot->slot_cmd->icmd_cmd);
2816 }
2817 
2818 void
2819 fct_queue_scsi_task_for_termination(fct_cmd_t *cmd, fct_status_t s)
2820 {
2821 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2822 
2823 	uint32_t old, new;
2824 
2825 	do {
2826 		old = icmd->icmd_flags;
2827 		if ((old & (ICMD_BEING_ABORTED | ICMD_KNOWN_TO_FCA)) !=
2828 		    ICMD_KNOWN_TO_FCA)
2829 			return;
2830 		new = old | ICMD_BEING_ABORTED;
2831 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
2832 	stmf_abort(STMF_QUEUE_TASK_ABORT, (scsi_task_t *)cmd->cmd_specific,
2833 	    s, NULL);
2834 }
2835 
2836 void
2837 fct_fill_abts_acc(fct_cmd_t *cmd)
2838 {
2839 	fct_rcvd_abts_t *abts = (fct_rcvd_abts_t *)cmd->cmd_specific;
2840 	uint8_t *p;
2841 
2842 	abts->abts_resp_rctl = BLS_OP_BA_ACC;
2843 	p = abts->abts_resp_payload;
2844 	bzero(p, 12);
2845 	*((uint16_t *)(p+4)) = BE_16(cmd->cmd_oxid);
2846 	*((uint16_t *)(p+6)) = BE_16(cmd->cmd_rxid);
2847 	p[10] = p[11] = 0xff;
2848 }
2849 
2850 void
2851 fct_handle_rcvd_abts(fct_cmd_t *cmd)
2852 {
2853 	char			info[80];
2854 	fct_local_port_t	*port = cmd->cmd_port;
2855 	fct_i_local_port_t	*iport =
2856 	    (fct_i_local_port_t *)port->port_fct_private;
2857 	fct_i_cmd_t		*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2858 	fct_i_remote_port_t	*irp;
2859 	fct_cmd_t		*c = NULL;
2860 	fct_i_cmd_t		*ic = NULL;
2861 	int			found = 0;
2862 	int			i;
2863 
2864 	icmd->icmd_start_time = ddi_get_lbolt();
2865 	icmd->icmd_flags |= ICMD_KNOWN_TO_FCA;
2866 
2867 	rw_enter(&iport->iport_lock, RW_WRITER);
2868 	/* Make sure local port is sane */
2869 	if ((iport->iport_link_state & S_LINK_ONLINE) == 0) {
2870 		rw_exit(&iport->iport_lock);
2871 		stmf_trace(iport->iport_alias, "ABTS not posted becasue"
2872 		    "port state was %x", iport->iport_link_state);
2873 		fct_queue_cmd_for_termination(cmd, FCT_LOCAL_PORT_OFFLINE);
2874 		return;
2875 	}
2876 
2877 	if (cmd->cmd_rp_handle == FCT_HANDLE_NONE)
2878 		irp = fct_portid_to_portptr(iport, cmd->cmd_rportid);
2879 	else if (cmd->cmd_rp_handle < port->port_max_logins)
2880 		irp = iport->iport_rp_slots[cmd->cmd_rp_handle];
2881 	else
2882 		irp = NULL;
2883 	if (irp == NULL) {
2884 		/* XXX Throw a logout to the initiator */
2885 		rw_exit(&iport->iport_lock);
2886 		stmf_trace(iport->iport_alias, "ABTS received from"
2887 		    " %x without a session", cmd->cmd_rportid);
2888 		fct_queue_cmd_for_termination(cmd, FCT_NOT_LOGGED_IN);
2889 		return;
2890 	}
2891 
2892 	DTRACE_FC_3(abts__receive,
2893 	    fct_cmd_t, cmd,
2894 	    fct_local_port_t, port,
2895 	    fct_i_remote_port_t, irp);
2896 
2897 	cmd->cmd_rp = irp->irp_rp;
2898 
2899 	/*
2900 	 * No need to allocate an xchg resource. ABTSes use the same
2901 	 * xchg resource as the cmd they are aborting.
2902 	 */
2903 	rw_enter(&irp->irp_lock, RW_WRITER);
2904 	mutex_enter(&iport->iport_worker_lock);
2905 	/* Lets find the command first */
2906 	for (i = 0; i < port->port_max_xchges; i++) {
2907 		if ((ic = iport->iport_cmd_slots[i].slot_cmd) == NULL)
2908 			continue;
2909 		if ((ic->icmd_flags & ICMD_KNOWN_TO_FCA) == 0)
2910 			continue;
2911 		c = ic->icmd_cmd;
2912 		if (!CMD_HANDLE_VALID(c->cmd_handle))
2913 			continue;
2914 		if ((c->cmd_rportid != cmd->cmd_rportid) ||
2915 		    (c->cmd_oxid != cmd->cmd_oxid))
2916 			continue;
2917 		/* Found the command */
2918 		found = 1;
2919 		break;
2920 	}
2921 	if (!found) {
2922 		mutex_exit(&iport->iport_worker_lock);
2923 		rw_exit(&irp->irp_lock);
2924 		rw_exit(&iport->iport_lock);
2925 		/* Dont even bother queueing it. Just respond */
2926 		fct_fill_abts_acc(cmd);
2927 		if (port->port_send_cmd_response(cmd,
2928 		    FCT_IOF_FORCE_FCA_DONE) != FCT_SUCCESS) {
2929 			/*
2930 			 * XXX Throw HBA fatal error event
2931 			 * Later shutdown svc will terminate the ABTS in the end
2932 			 */
2933 			(void) snprintf(info, 80,
2934 			    "fct_handle_rcvd_abts: iport-%p, "
2935 			    "ABTS_ACC port_send_cmd_response failed",
2936 			    (void *)iport);
2937 			info[79] = 0;
2938 			(void) fct_port_shutdown(iport->iport_port,
2939 			    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
2940 		} else {
2941 			fct_cmd_free(cmd);
2942 		}
2943 		return;
2944 	}
2945 
2946 	/* Check if this an abts retry */
2947 	if (c->cmd_link && (ic->icmd_flags & ICMD_ABTS_RECEIVED)) {
2948 		/* Kill this abts. */
2949 		fct_q_for_termination_lock_held(iport, icmd, FCT_ABORTED);
2950 		if (IS_WORKER_SLEEPING(iport))
2951 			cv_signal(&iport->iport_worker_cv);
2952 		mutex_exit(&iport->iport_worker_lock);
2953 		rw_exit(&irp->irp_lock);
2954 		rw_exit(&iport->iport_lock);
2955 		return;
2956 	}
2957 	c->cmd_link = cmd;
2958 	atomic_or_32(&ic->icmd_flags, ICMD_ABTS_RECEIVED);
2959 	cmd->cmd_link = c;
2960 	mutex_exit(&iport->iport_worker_lock);
2961 	rw_exit(&irp->irp_lock);
2962 	fct_queue_cmd_for_termination(c, FCT_ABTS_RECEIVED);
2963 	rw_exit(&iport->iport_lock);
2964 }
2965 
2966 void
2967 fct_queue_cmd_for_termination(fct_cmd_t *cmd, fct_status_t s)
2968 {
2969 	fct_local_port_t *port = cmd->cmd_port;
2970 	fct_i_local_port_t *iport = (fct_i_local_port_t *)
2971 	    port->port_fct_private;
2972 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2973 
2974 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
2975 		fct_queue_scsi_task_for_termination(cmd, s);
2976 		return;
2977 	}
2978 	mutex_enter(&iport->iport_worker_lock);
2979 	fct_q_for_termination_lock_held(iport, icmd, s);
2980 	if (IS_WORKER_SLEEPING(iport))
2981 		cv_signal(&iport->iport_worker_cv);
2982 	mutex_exit(&iport->iport_worker_lock);
2983 }
2984 
2985 /*
2986  * This function will not be called for SCSI CMDS
2987  */
2988 void
2989 fct_q_for_termination_lock_held(fct_i_local_port_t *iport, fct_i_cmd_t *icmd,
2990 		fct_status_t s)
2991 {
2992 	uint32_t old, new;
2993 	fct_i_cmd_t **ppicmd;
2994 
2995 	do {
2996 		old = icmd->icmd_flags;
2997 		if (old & ICMD_BEING_ABORTED)
2998 			return;
2999 		new = old | ICMD_BEING_ABORTED;
3000 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
3001 
3002 	icmd->icmd_start_time = ddi_get_lbolt();
3003 	icmd->icmd_cmd->cmd_comp_status = s;
3004 
3005 	icmd->icmd_next = NULL;
3006 	for (ppicmd = &(iport->iport_abort_queue); *ppicmd != NULL;
3007 	    ppicmd = &((*ppicmd)->icmd_next))
3008 		;
3009 
3010 	*ppicmd = icmd;
3011 }
3012 
3013 /*
3014  * For those cmds, for which we called fca_abort but it has not yet completed,
3015  * reset the FCA_ABORT_CALLED flag, so that abort can be called again.
3016  * This is done after a FCA offline. The reason is that after offline, the
3017  * firmware is not running so abort will never complete. But if we call it
3018  * again, the FCA will detect that it is not offline and it will
3019  * not call the firmware at all. Most likely it will abort in a synchronous
3020  * manner i.e. return FCT_ABORT_SUCCESS or FCT_NOT_FOUND.
3021  */
3022 void
3023 fct_reset_flag_abort_called(fct_i_local_port_t *iport)
3024 {
3025 	fct_i_cmd_t *icmd;
3026 	uint32_t old, new;
3027 	int i, do_clear;
3028 
3029 	ASSERT(mutex_owned(&iport->iport_worker_lock));
3030 	mutex_exit(&iport->iport_worker_lock);
3031 	rw_enter(&iport->iport_lock, RW_WRITER);
3032 	mutex_enter(&iport->iport_worker_lock);
3033 
3034 	for (i = 0; i < iport->iport_port->port_max_xchges; i++) {
3035 		if (iport->iport_cmd_slots[i].slot_cmd == NULL)
3036 			continue;
3037 
3038 		icmd = iport->iport_cmd_slots[i].slot_cmd;
3039 
3040 		do {
3041 			old = new = icmd->icmd_flags;
3042 			if ((old & (ICMD_KNOWN_TO_FCA |
3043 			    ICMD_FCA_ABORT_CALLED)) == (ICMD_KNOWN_TO_FCA |
3044 			    ICMD_FCA_ABORT_CALLED)) {
3045 				new &= ~ICMD_FCA_ABORT_CALLED;
3046 				do_clear = 1;
3047 			} else {
3048 				do_clear = 0;
3049 				break;
3050 			}
3051 		} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
3052 		if (do_clear &&
3053 		    (icmd->icmd_cmd->cmd_type == FCT_CMD_FCP_XCHG)) {
3054 			stmf_abort(STMF_REQUEUE_TASK_ABORT_LPORT,
3055 			    icmd->icmd_cmd->cmd_specific, 0, NULL);
3056 		}
3057 	}
3058 
3059 	rw_exit(&iport->iport_lock);
3060 }
3061 
3062 /*
3063  * Modify the irp_deregister_timer such that the ports start deregistering
3064  * quickly.
3065  */
3066 void
3067 fct_irp_deregister_speedup(fct_i_local_port_t *iport)
3068 {
3069 	fct_i_remote_port_t *irp;
3070 	int i;
3071 
3072 	if (!iport->iport_nrps)
3073 		return;
3074 
3075 	for (i = 0; i < rportid_table_size; i++) {
3076 		irp = iport->iport_rp_tb[i];
3077 		while (irp) {
3078 			irp->irp_deregister_timer = ddi_get_lbolt() - 1;
3079 			irp = irp->irp_next;
3080 		}
3081 	}
3082 }
3083 
3084 disc_action_t
3085 fct_handle_port_offline(fct_i_local_port_t *iport)
3086 {
3087 	if (iport->iport_offline_prstate == FCT_OPR_START) {
3088 		fct_reset_flag_abort_called(iport);
3089 		iport->iport_offline_prstate = FCT_OPR_CMD_CLEANUP_WAIT;
3090 		/* fct_ctl has already submitted a link offline event */
3091 		return (DISC_ACTION_DELAY_RESCAN);
3092 	}
3093 	if (iport->iport_offline_prstate == FCT_OPR_CMD_CLEANUP_WAIT) {
3094 		if (iport->iport_link_state != PORT_STATE_LINK_DOWN)
3095 			return (DISC_ACTION_DELAY_RESCAN);
3096 		/*
3097 		 * All I/Os have been killed at this time. Lets speedup
3098 		 * the port deregister process.
3099 		 */
3100 		mutex_exit(&iport->iport_worker_lock);
3101 		rw_enter(&iport->iport_lock, RW_WRITER);
3102 		fct_irp_deregister_speedup(iport);
3103 		rw_exit(&iport->iport_lock);
3104 		mutex_enter(&iport->iport_worker_lock);
3105 		iport->iport_offline_prstate = FCT_OPR_INT_CLEANUP_WAIT;
3106 		return (DISC_ACTION_RESCAN);
3107 	}
3108 	if (iport->iport_offline_prstate == FCT_OPR_INT_CLEANUP_WAIT) {
3109 		stmf_change_status_t st;
3110 
3111 		if (iport->iport_solcmd_queue) {
3112 			return (DISC_ACTION_DELAY_RESCAN);
3113 		}
3114 
3115 		if (iport->iport_nrps) {
3116 			/*
3117 			 * A port logout may have gone when implicit logo all
3118 			 * was retried. So do the port speedup again here.
3119 			 */
3120 			mutex_exit(&iport->iport_worker_lock);
3121 			rw_enter(&iport->iport_lock, RW_WRITER);
3122 			fct_irp_deregister_speedup(iport);
3123 			rw_exit(&iport->iport_lock);
3124 			mutex_enter(&iport->iport_worker_lock);
3125 			return (DISC_ACTION_DELAY_RESCAN);
3126 		}
3127 
3128 		if (iport->iport_event_head != NULL) {
3129 			return (DISC_ACTION_DELAY_RESCAN);
3130 		}
3131 
3132 		st.st_completion_status = STMF_SUCCESS;
3133 		st.st_additional_info = NULL;
3134 		iport->iport_offline_prstate = FCT_OPR_DONE;
3135 		iport->iport_state = FCT_STATE_OFFLINE;
3136 		mutex_exit(&iport->iport_worker_lock);
3137 		(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE_COMPLETE,
3138 		    iport->iport_port->port_lport, &st);
3139 		mutex_enter(&iport->iport_worker_lock);
3140 		return (DISC_ACTION_DELAY_RESCAN);
3141 	}
3142 
3143 	/* NOTREACHED */
3144 	return (0);
3145 }
3146 
3147 /*
3148  * See stmf.h for information on rflags. Additional info is just a text
3149  * description of the reason for this call. Additional_info can be NULL.
3150  * Also the caller can declare additional info on the stack. stmf_ctl
3151  * makes a copy of it before returning.
3152  */
3153 fct_status_t
3154 fct_port_initialize(fct_local_port_t *port, uint32_t rflags,
3155 				char *additional_info)
3156 {
3157 	stmf_state_change_info_t st;
3158 
3159 	st.st_rflags = rflags;
3160 	st.st_additional_info = additional_info;
3161 	stmf_trace(NULL, "fct_port_initialize: port-%p, %s", port,
3162 	    additional_info? additional_info : "no more information");
3163 	return (stmf_ctl(STMF_CMD_LPORT_ONLINE, port->port_lport, &st));
3164 }
3165 
3166 fct_status_t
3167 fct_port_shutdown(fct_local_port_t *port, uint32_t rflags,
3168 				char *additional_info)
3169 {
3170 	stmf_state_change_info_t st;
3171 
3172 	st.st_rflags = rflags;
3173 	st.st_additional_info = additional_info;
3174 	stmf_trace(NULL, "fct_port_shutdown: port-%p, %s", port,
3175 	    additional_info? additional_info : "no more information");
3176 	return (stmf_ctl(STMF_CMD_LPORT_OFFLINE, port->port_lport, &st));
3177 }
3178 
3179 /*
3180  * Called by worker thread. The aim is to terminate the command
3181  * using whatever means it takes.
3182  * Called with worker lock held.
3183  */
3184 disc_action_t
3185 fct_cmd_terminator(fct_i_local_port_t *iport)
3186 {
3187 	char			info[80];
3188 	clock_t			endtime;
3189 	fct_i_cmd_t		**ppicmd;
3190 	fct_i_cmd_t		*icmd;
3191 	fct_cmd_t		*cmd;
3192 	fct_local_port_t	*port = iport->iport_port;
3193 	disc_action_t		ret = DISC_ACTION_NO_WORK;
3194 	fct_status_t		abort_ret;
3195 	int			fca_done, fct_done, cmd_implicit = 0;
3196 	int			flags;
3197 	unsigned long long	st;
3198 
3199 	/* Lets Limit each run to 20ms max. */
3200 	endtime = ddi_get_lbolt() + drv_usectohz(20000);
3201 
3202 	/* Start from where we left off last time */
3203 	if (iport->iport_ppicmd_term) {
3204 		ppicmd = iport->iport_ppicmd_term;
3205 		iport->iport_ppicmd_term = NULL;
3206 	} else {
3207 		ppicmd = &iport->iport_abort_queue;
3208 	}
3209 
3210 	/*
3211 	 * Once a command gets on discovery queue, this is the only thread
3212 	 * which can access it. So no need for the lock here.
3213 	 */
3214 	mutex_exit(&iport->iport_worker_lock);
3215 
3216 	while ((icmd = *ppicmd) != NULL) {
3217 		cmd = icmd->icmd_cmd;
3218 
3219 		/* Always remember that cmd->cmd_rp can be NULL */
3220 		if ((icmd->icmd_flags & (ICMD_KNOWN_TO_FCA |
3221 		    ICMD_FCA_ABORT_CALLED)) == ICMD_KNOWN_TO_FCA) {
3222 			atomic_or_32(&icmd->icmd_flags, ICMD_FCA_ABORT_CALLED);
3223 			if (CMD_HANDLE_VALID(cmd->cmd_handle))
3224 				flags = 0;
3225 			else
3226 				flags = FCT_IOF_FORCE_FCA_DONE;
3227 			abort_ret = port->port_abort_cmd(port, cmd, flags);
3228 			if ((abort_ret != FCT_SUCCESS) &&
3229 			    (abort_ret != FCT_ABORT_SUCCESS) &&
3230 			    (abort_ret != FCT_NOT_FOUND)) {
3231 				if (flags & FCT_IOF_FORCE_FCA_DONE) {
3232 					/*
3233 					 * XXX trigger port fatal,
3234 					 * Abort the termination, and shutdown
3235 					 * svc will trigger fct_cmd_termination
3236 					 * again.
3237 					 */
3238 					(void) snprintf(info, 80,
3239 					    "fct_cmd_terminator:"
3240 					    " iport-%p, port_abort_cmd with "
3241 					    "FORCE_FCA_DONE failed",
3242 					    (void *)iport);
3243 					info[79] = 0;
3244 					(void) fct_port_shutdown(
3245 					    iport->iport_port,
3246 					    STMF_RFLAG_FATAL_ERROR |
3247 					    STMF_RFLAG_RESET, info);
3248 
3249 					mutex_enter(&iport->iport_worker_lock);
3250 					iport->iport_ppicmd_term = ppicmd;
3251 					return (DISC_ACTION_DELAY_RESCAN);
3252 				}
3253 				atomic_and_32(&icmd->icmd_flags,
3254 				    ~ICMD_FCA_ABORT_CALLED);
3255 			} else if ((flags & FCT_IOF_FORCE_FCA_DONE) ||
3256 			    (abort_ret == FCT_ABORT_SUCCESS) ||
3257 			    (abort_ret == FCT_NOT_FOUND)) {
3258 				atomic_and_32(&icmd->icmd_flags,
3259 				    ~ICMD_KNOWN_TO_FCA);
3260 			}
3261 			ret |= DISC_ACTION_DELAY_RESCAN;
3262 		} else if (icmd->icmd_flags & ICMD_IMPLICIT) {
3263 			if (cmd->cmd_type == FCT_CMD_SOL_ELS)
3264 				cmd->cmd_comp_status = FCT_ABORTED;
3265 			atomic_or_32(&icmd->icmd_flags, ICMD_FCA_ABORT_CALLED);
3266 			cmd_implicit = 1;
3267 		}
3268 		if ((icmd->icmd_flags & ICMD_KNOWN_TO_FCA) == 0)
3269 			fca_done = 1;
3270 		else
3271 			fca_done = 0;
3272 		if ((icmd->icmd_flags & ICMD_IN_IRP_QUEUE) == 0)
3273 			fct_done = 1;
3274 		else
3275 			fct_done = 0;
3276 		if ((fca_done || cmd_implicit) && fct_done) {
3277 			mutex_enter(&iport->iport_worker_lock);
3278 			ASSERT(*ppicmd == icmd);
3279 			*ppicmd = (*ppicmd)->icmd_next;
3280 			mutex_exit(&iport->iport_worker_lock);
3281 			if ((cmd->cmd_type == FCT_CMD_RCVD_ELS) ||
3282 			    (cmd->cmd_type == FCT_CMD_RCVD_ABTS)) {
3283 				/* Free the cmd */
3284 				fct_cmd_free(cmd);
3285 			} else if (cmd->cmd_type == FCT_CMD_SOL_ELS) {
3286 				fct_handle_sol_els_completion(iport, icmd);
3287 				if (icmd->icmd_flags & ICMD_IMPLICIT) {
3288 					if (IS_LOGO_ELS(icmd)) {
3289 						/* IMPLICIT LOGO is special */
3290 						fct_cmd_free(cmd);
3291 					}
3292 				}
3293 			} else if (cmd->cmd_type == FCT_CMD_SOL_CT) {
3294 				fct_sol_ct_t *ct = ICMD_TO_CT(icmd);
3295 
3296 				/* Tell the caller that we are done */
3297 				atomic_or_32(&icmd->icmd_flags,
3298 				    ICMD_CMD_COMPLETE);
3299 				if (fct_netbuf_to_value(
3300 				    ct->ct_req_payload + 8, 2) == NS_GID_PN) {
3301 					fct_i_remote_port_t *irp;
3302 
3303 					rw_enter(&iport->iport_lock, RW_READER);
3304 					irp = fct_lookup_irp_by_portwwn(iport,
3305 					    ct->ct_req_payload + 16);
3306 
3307 					if (irp) {
3308 						atomic_and_32(&irp->irp_flags,
3309 						    ~IRP_RSCN_QUEUED);
3310 					}
3311 					rw_exit(&iport->iport_lock);
3312 				}
3313 			} else {
3314 				ASSERT(0);
3315 			}
3316 		} else {
3317 			clock_t	timeout_ticks;
3318 			if (port->port_fca_abort_timeout)
3319 				timeout_ticks = drv_usectohz(
3320 				    port->port_fca_abort_timeout*1000);
3321 			else
3322 				/* 10 seconds by default */
3323 				timeout_ticks = drv_usectohz(10 * 1000000);
3324 			if ((ddi_get_lbolt() >
3325 			    (icmd->icmd_start_time+timeout_ticks)) &&
3326 			    iport->iport_state == FCT_STATE_ONLINE) {
3327 				/* timeout, reset the port */
3328 				char cmd_type[10];
3329 				if (cmd->cmd_type == FCT_CMD_RCVD_ELS ||
3330 				    cmd->cmd_type == FCT_CMD_SOL_ELS) {
3331 					fct_els_t *els = cmd->cmd_specific;
3332 					(void) snprintf(cmd_type,
3333 					    sizeof (cmd_type), "%x.%x",
3334 					    cmd->cmd_type,
3335 					    els->els_req_payload[0]);
3336 				} else if (cmd->cmd_type == FCT_CMD_SOL_CT) {
3337 					fct_sol_ct_t *ct = cmd->cmd_specific;
3338 					(void) snprintf(cmd_type,
3339 					    sizeof (cmd_type), "%x.%02x%02x",
3340 					    cmd->cmd_type,
3341 					    ct->ct_req_payload[8],
3342 					    ct->ct_req_payload[9]);
3343 				} else {
3344 					cmd_type[0] = 0;
3345 				}
3346 				st = cmd->cmd_comp_status;	/* gcc fix */
3347 				(void) snprintf(info, 80, "fct_cmd_terminator:"
3348 				    " iport-%p, cmd_type(0x%s),"
3349 				    " reason(%llx)", (void *)iport, cmd_type,
3350 				    st);
3351 				info[79] = 0;
3352 				(void) fct_port_shutdown(port,
3353 				    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET,
3354 				    info);
3355 			}
3356 			ppicmd = &((*ppicmd)->icmd_next);
3357 		}
3358 
3359 		if (ddi_get_lbolt() > endtime) {
3360 			mutex_enter(&iport->iport_worker_lock);
3361 			iport->iport_ppicmd_term = ppicmd;
3362 			return (DISC_ACTION_DELAY_RESCAN);
3363 		}
3364 	}
3365 	mutex_enter(&iport->iport_worker_lock);
3366 	if (iport->iport_abort_queue)
3367 		return (DISC_ACTION_DELAY_RESCAN);
3368 	if (ret == DISC_ACTION_NO_WORK)
3369 		return (DISC_ACTION_RESCAN);
3370 	return (ret);
3371 }
3372 
3373 /*
3374  * Send a syslog event for adapter port level events.
3375  */
3376 void
3377 fct_log_local_port_event(fct_local_port_t *port, char *subclass)
3378 {
3379 	nvlist_t *attr_list;
3380 	int port_instance;
3381 
3382 	if (!fct_dip)
3383 		return;
3384 	port_instance = ddi_get_instance(fct_dip);
3385 
3386 	if (nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE,
3387 	    KM_SLEEP) != DDI_SUCCESS) {
3388 		goto alloc_failed;
3389 	}
3390 
3391 	if (nvlist_add_uint32(attr_list, "instance", port_instance)
3392 	    != DDI_SUCCESS) {
3393 		goto error;
3394 	}
3395 
3396 	if (nvlist_add_byte_array(attr_list, "port-wwn",
3397 	    port->port_pwwn, 8) != DDI_SUCCESS) {
3398 		goto error;
3399 	}
3400 
3401 	(void) ddi_log_sysevent(fct_dip, DDI_VENDOR_SUNW, EC_SUNFC,
3402 	    subclass, attr_list, NULL, DDI_SLEEP);
3403 
3404 	nvlist_free(attr_list);
3405 	return;
3406 
3407 error:
3408 	nvlist_free(attr_list);
3409 alloc_failed:
3410 	stmf_trace(((fct_i_local_port_t *)port->port_fct_private)->iport_alias,
3411 	    "Unable to send %s event", subclass);
3412 }
3413 
3414 void
3415 fct_log_remote_port_event(fct_local_port_t *port, char *subclass,
3416     uint8_t *rp_pwwn, uint32_t rp_id)
3417 {
3418 	nvlist_t *attr_list;
3419 	int port_instance;
3420 
3421 	if (!fct_dip)
3422 		return;
3423 	port_instance = ddi_get_instance(fct_dip);
3424 
3425 	if (nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE,
3426 	    KM_SLEEP) != DDI_SUCCESS) {
3427 		goto alloc_failed;
3428 	}
3429 
3430 	if (nvlist_add_uint32(attr_list, "instance", port_instance)
3431 	    != DDI_SUCCESS) {
3432 		goto error;
3433 	}
3434 
3435 	if (nvlist_add_byte_array(attr_list, "port-wwn",
3436 	    port->port_pwwn, 8) != DDI_SUCCESS) {
3437 		goto error;
3438 	}
3439 
3440 	if (nvlist_add_byte_array(attr_list, "target-port-wwn",
3441 	    rp_pwwn, 8) != DDI_SUCCESS) {
3442 		goto error;
3443 	}
3444 
3445 	if (nvlist_add_uint32(attr_list, "target-port-id",
3446 	    rp_id) != DDI_SUCCESS) {
3447 		goto error;
3448 	}
3449 
3450 	(void) ddi_log_sysevent(fct_dip, DDI_VENDOR_SUNW, EC_SUNFC,
3451 	    subclass, attr_list, NULL, DDI_SLEEP);
3452 
3453 	nvlist_free(attr_list);
3454 	return;
3455 
3456 error:
3457 	nvlist_free(attr_list);
3458 alloc_failed:
3459 	stmf_trace(((fct_i_local_port_t *)port->port_fct_private)->iport_alias,
3460 	    "Unable to send %s event", subclass);
3461 }
3462 
3463 uint64_t
3464 fct_netbuf_to_value(uint8_t *buf, uint8_t nbytes)
3465 {
3466 	uint64_t	ret = 0;
3467 	uint8_t		idx = 0;
3468 
3469 	do {
3470 		ret |= (buf[idx] << (8 * (nbytes -idx - 1)));
3471 	} while (++idx < nbytes);
3472 
3473 	return (ret);
3474 }
3475 
3476 void
3477 fct_value_to_netbuf(uint64_t value, uint8_t *buf, uint8_t nbytes)
3478 {
3479 	uint8_t		idx = 0;
3480 
3481 	for (idx = 0; idx < nbytes; idx++) {
3482 		buf[idx] = 0xFF & (value >> (8 * (nbytes - idx - 1)));
3483 	}
3484 }
3485 
3486 /*
3487  * from_ptr: ptr to uchar_t array of size WWN_SIZE
3488  * to_ptr: char ptr to string of size WWN_SIZE*2+1
3489  */
3490 void
3491 fct_wwn_to_str(char *to_ptr, const uint8_t *from_ptr)
3492 {
3493 	ASSERT(to_ptr != NULL && from_ptr != NULL);
3494 
3495 	(void) sprintf(to_ptr, "%02x%02x%02x%02x%02x%02x%02x%02x",
3496 	    from_ptr[0], from_ptr[1], from_ptr[2], from_ptr[3],
3497 	    from_ptr[4], from_ptr[5], from_ptr[6], from_ptr[7]);
3498 }
3499 
3500 static int
3501 fct_update_stats(kstat_t *ks, int rw)
3502 {
3503 	fct_i_local_port_t *iport;
3504 	fct_port_stat_t *port_kstat;
3505 	fct_port_link_status_t stat;
3506 	uint32_t	buf_size = sizeof (stat);
3507 	int		ret;
3508 
3509 	if (rw == KSTAT_WRITE)
3510 		return (EACCES);
3511 
3512 	iport = (fct_i_local_port_t *)ks->ks_private;
3513 	port_kstat = (fct_port_stat_t *)ks->ks_data;
3514 
3515 	if (iport->iport_port->port_info == NULL) {
3516 		return (EIO);
3517 	}
3518 	ret = iport->iport_port->port_info(FC_TGT_PORT_RLS,
3519 	    iport->iport_port, NULL, (uint8_t *)&stat, &buf_size);
3520 	if (ret != STMF_SUCCESS) {
3521 		return (EIO);
3522 	}
3523 
3524 	port_kstat->link_failure_cnt.value.ui32 =
3525 	    stat.LinkFailureCount;
3526 	port_kstat->loss_of_sync_cnt.value.ui32 =
3527 	    stat.LossOfSyncCount;
3528 	port_kstat->loss_of_signals_cnt.value.ui32 =
3529 	    stat.LossOfSignalsCount;
3530 	port_kstat->prim_seq_protocol_err_cnt.value.ui32 =
3531 	    stat.PrimitiveSeqProtocolErrorCount;
3532 	port_kstat->invalid_tx_word_cnt.value.ui32 =
3533 	    stat.InvalidTransmissionWordCount;
3534 	port_kstat->invalid_crc_cnt.value.ui32 =
3535 	    stat.InvalidCRCCount;
3536 
3537 	return (0);
3538 }
3539 
3540 void
3541 fct_init_kstats(fct_i_local_port_t *iport)
3542 {
3543 	kstat_t *ks;
3544 	fct_port_stat_t *port_kstat;
3545 	char	name[256];
3546 
3547 	if (iport->iport_alias)
3548 		(void) sprintf(name, "iport_%s", iport->iport_alias);
3549 	else
3550 		(void) sprintf(name, "iport_%"PRIxPTR"", (uintptr_t)iport);
3551 	ks = kstat_create(FCT_MODULE_NAME, 0, name, "rawdata",
3552 	    KSTAT_TYPE_NAMED, sizeof (fct_port_stat_t) / sizeof (kstat_named_t),
3553 	    0);
3554 
3555 	if (ks == NULL) {
3556 		return;
3557 	}
3558 	port_kstat = (fct_port_stat_t *)ks->ks_data;
3559 
3560 	iport->iport_kstat_portstat = ks;
3561 	kstat_named_init(&port_kstat->link_failure_cnt,
3562 	    "Link_failure_cnt", KSTAT_DATA_UINT32);
3563 	kstat_named_init(&port_kstat->loss_of_sync_cnt,
3564 	    "Loss_of_sync_cnt", KSTAT_DATA_UINT32);
3565 	kstat_named_init(&port_kstat->loss_of_signals_cnt,
3566 	    "Loss_of_signals_cnt", KSTAT_DATA_UINT32);
3567 	kstat_named_init(&port_kstat->prim_seq_protocol_err_cnt,
3568 	    "Prim_seq_protocol_err_cnt", KSTAT_DATA_UINT32);
3569 	kstat_named_init(&port_kstat->invalid_tx_word_cnt,
3570 	    "Invalid_tx_word_cnt", KSTAT_DATA_UINT32);
3571 	kstat_named_init(&port_kstat->invalid_crc_cnt,
3572 	    "Invalid_crc_cnt", KSTAT_DATA_UINT32);
3573 	ks->ks_update = fct_update_stats;
3574 	ks->ks_private = (void *)iport;
3575 	kstat_install(ks);
3576 
3577 }
3578