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 	if (stmf_register_local_port(port->port_lport) != FCT_SUCCESS) {
1211 		goto fct_regport_fail1;
1212 	}
1213 	(void) stmf_lport_add_event(lport, LPORT_EVENT_INITIAL_LUN_MAPPED);
1214 
1215 	mutex_enter(&fct_global_mutex);
1216 	iport->iport_next = fct_iport_list;
1217 	iport->iport_prev = NULL;
1218 	if (iport->iport_next)
1219 		iport->iport_next->iport_prev = iport;
1220 	fct_iport_list = iport;
1221 	mutex_exit(&fct_global_mutex);
1222 
1223 	fct_init_kstats(iport);
1224 
1225 	fct_log_local_port_event(port, ESC_SUNFC_PORT_ATTACH);
1226 
1227 	return (FCT_SUCCESS);
1228 
1229 fct_regport_fail1:;
1230 	/* Stop the taskq 1st */
1231 	if (iport->iport_flags & IPORT_WORKER_RUNNING) {
1232 		atomic_or_32(&iport->iport_flags, IPORT_TERMINATE_WORKER);
1233 		cv_broadcast(&iport->iport_worker_cv);
1234 		while (iport->iport_flags & IPORT_WORKER_RUNNING) {
1235 			delay(1);
1236 		}
1237 	}
1238 	ddi_taskq_destroy(iport->iport_worker_taskq);
1239 	if (iport->iport_rp_tb) {
1240 		kmem_free(iport->iport_rp_tb, rportid_table_size *
1241 		    sizeof (fct_i_remote_port_t *));
1242 	}
1243 	return (FCT_FAILURE);
1244 }
1245 
1246 fct_status_t
1247 fct_deregister_local_port(fct_local_port_t *port)
1248 {
1249 	fct_i_local_port_t	*iport;
1250 	fct_i_cmd_t		*icmd, *next_icmd;
1251 	int			ndx;
1252 
1253 	iport = (fct_i_local_port_t *)port->port_fct_private;
1254 
1255 	if ((iport->iport_state != FCT_STATE_OFFLINE) ||
1256 	    iport->iport_state_not_acked) {
1257 		return (FCT_FAILURE);
1258 	}
1259 
1260 	/* Stop the taskq 1st */
1261 	if (iport->iport_flags & IPORT_WORKER_RUNNING) {
1262 		atomic_or_32(&iport->iport_flags, IPORT_TERMINATE_WORKER);
1263 		cv_broadcast(&iport->iport_worker_cv);
1264 		for (ndx = 0; ndx < 100; ndx++) {
1265 			if ((iport->iport_flags & IPORT_WORKER_RUNNING)
1266 			    == 0) {
1267 				break;
1268 			}
1269 			delay(drv_usectohz(10000));
1270 		}
1271 		if (ndx == 100) {
1272 			atomic_and_32(&iport->iport_flags,
1273 			    ~IPORT_TERMINATE_WORKER);
1274 			return (FCT_WORKER_STUCK);
1275 		}
1276 	}
1277 
1278 	if (stmf_deregister_local_port(port->port_lport) != FCT_SUCCESS) {
1279 		goto fct_deregport_fail1;
1280 	}
1281 
1282 	mutex_enter(&fct_global_mutex);
1283 	if (iport->iport_next)
1284 		iport->iport_next->iport_prev = iport->iport_prev;
1285 	if (iport->iport_prev)
1286 		iport->iport_prev->iport_next = iport->iport_next;
1287 	else
1288 		fct_iport_list = iport->iport_next;
1289 	mutex_exit(&fct_global_mutex);
1290 	/*
1291 	 * At this time, there should be no outstanding and pending
1292 	 * I/Os, so we can just release resources.
1293 	 */
1294 	ASSERT(iport->iport_total_alloced_ncmds == iport->iport_cached_ncmds);
1295 	for (icmd = iport->iport_cached_cmdlist; icmd; icmd = next_icmd) {
1296 		next_icmd = icmd->icmd_next;
1297 		fct_free(icmd->icmd_cmd);
1298 	}
1299 	mutex_destroy(&iport->iport_cached_cmd_lock);
1300 	kmem_free(iport->iport_cmd_slots, port->port_max_xchges *
1301 	    sizeof (fct_cmd_slot_t));
1302 	kmem_free(iport->iport_rp_slots, port->port_max_logins *
1303 	    sizeof (fct_i_remote_port_t *));
1304 	rw_destroy(&iport->iport_lock);
1305 	cv_destroy(&iport->iport_worker_cv);
1306 	sema_destroy(&iport->iport_rls_sema);
1307 	mutex_destroy(&iport->iport_worker_lock);
1308 	ddi_taskq_destroy(iport->iport_worker_taskq);
1309 	if (iport->iport_rp_tb) {
1310 		kmem_free(iport->iport_rp_tb, rportid_table_size *
1311 		    sizeof (fct_i_remote_port_t *));
1312 	}
1313 
1314 	if (iport->iport_kstat_portstat) {
1315 		kstat_delete(iport->iport_kstat_portstat);
1316 	}
1317 
1318 	fct_log_local_port_event(port, ESC_SUNFC_PORT_DETACH);
1319 	return (FCT_SUCCESS);
1320 
1321 fct_deregport_fail1:;
1322 	/* Restart the worker */
1323 	atomic_and_32(&iport->iport_flags, ~IPORT_TERMINATE_WORKER);
1324 	(void) ddi_taskq_dispatch(iport->iport_worker_taskq,
1325 	    fct_port_worker, port, DDI_SLEEP);
1326 	/* Wait for taskq to start */
1327 	while ((iport->iport_flags & IPORT_WORKER_RUNNING) == 0) {
1328 		delay(1);
1329 	}
1330 	return (FCT_FAILURE);
1331 }
1332 
1333 /* ARGSUSED */
1334 void
1335 fct_handle_event(fct_local_port_t *port, int event_id, uint32_t event_flags,
1336 		caddr_t arg)
1337 {
1338 	char			info[80];
1339 	fct_i_event_t		*e;
1340 	fct_i_local_port_t	*iport = (fct_i_local_port_t *)
1341 	    port->port_fct_private;
1342 
1343 	e = kmem_zalloc(sizeof (fct_i_event_t), KM_NOSLEEP);
1344 
1345 	if (e == NULL) {
1346 		/*
1347 		 * XXX Throw HBA fatal error event
1348 		 */
1349 		(void) snprintf(info, 80,
1350 		    "fct_handle_event: iport-%p, allocation "
1351 		    "of fct_i_event failed", (void *)iport);
1352 		info[79] = 0;
1353 		(void) fct_port_shutdown(iport->iport_port,
1354 		    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
1355 		return;
1356 	}
1357 	/* Just queue the event */
1358 	e->event_type = event_id;
1359 	mutex_enter(&iport->iport_worker_lock);
1360 	if (iport->iport_event_head == NULL) {
1361 		iport->iport_event_head = iport->iport_event_tail = e;
1362 	} else {
1363 		iport->iport_event_tail->event_next = e;
1364 		iport->iport_event_tail = e;
1365 	}
1366 	if (IS_WORKER_SLEEPING(iport))
1367 		cv_signal(&iport->iport_worker_cv);
1368 	mutex_exit(&iport->iport_worker_lock);
1369 }
1370 
1371 /*
1372  * Called with iport_lock held as reader.
1373  */
1374 fct_i_remote_port_t *
1375 fct_portid_to_portptr(fct_i_local_port_t *iport, uint32_t portid)
1376 {
1377 	fct_i_remote_port_t	*irp;
1378 
1379 	irp = iport->iport_rp_tb[FCT_PORTID_HASH_FUNC(portid)];
1380 	for (; irp != NULL; irp = irp->irp_next) {
1381 		if (irp->irp_portid == portid)
1382 			return (irp);
1383 	}
1384 
1385 	return (NULL);
1386 
1387 }
1388 
1389 /*
1390  * Called with irp_lock held as writer.
1391  */
1392 void
1393 fct_queue_rp(fct_i_local_port_t *iport, fct_i_remote_port_t *irp)
1394 {
1395 	int hash_key =
1396 	    FCT_PORTID_HASH_FUNC(irp->irp_portid);
1397 
1398 	irp->irp_next = iport->iport_rp_tb[hash_key];
1399 	iport->iport_rp_tb[hash_key] = irp;
1400 	iport->iport_nrps++;
1401 }
1402 
1403 /*
1404  * Called with irp_lock and iport_lock held as writer.
1405  */
1406 void
1407 fct_deque_rp(fct_i_local_port_t *iport, fct_i_remote_port_t *irp)
1408 {
1409 	fct_i_remote_port_t	*irp_next = NULL;
1410 	fct_i_remote_port_t	*irp_last = NULL;
1411 	int hash_key			  =
1412 	    FCT_PORTID_HASH_FUNC(irp->irp_portid);
1413 
1414 	irp_next = iport->iport_rp_tb[hash_key];
1415 	irp_last = NULL;
1416 	while (irp_next != NULL) {
1417 		if (irp == irp_next) {
1418 			break;
1419 		}
1420 		irp_last = irp_next;
1421 		irp_next = irp_next->irp_next;
1422 	}
1423 
1424 	if (irp_next) {
1425 		if (irp_last == NULL) {
1426 			iport->iport_rp_tb[hash_key] =
1427 			    irp->irp_next;
1428 		} else {
1429 			irp_last->irp_next = irp->irp_next;
1430 		}
1431 		irp->irp_next = NULL;
1432 		iport->iport_nrps--;
1433 	}
1434 }
1435 
1436 int
1437 fct_is_irp_logging_out(fct_i_remote_port_t *irp, int force_implicit)
1438 {
1439 	int logging_out = 0;
1440 
1441 	rw_enter(&irp->irp_lock, RW_WRITER);
1442 	if ((irp->irp_flags & IRP_IN_DISCOVERY_QUEUE) == 0) {
1443 		logging_out = 0;
1444 		goto ilo_done;
1445 	}
1446 	if ((irp->irp_els_list == NULL) && (irp->irp_deregister_timer)) {
1447 		if (force_implicit && irp->irp_nonfcp_xchg_count) {
1448 			logging_out = 0;
1449 		} else {
1450 			logging_out = 1;
1451 		}
1452 		goto ilo_done;
1453 	}
1454 	if (irp->irp_els_list) {
1455 		fct_i_cmd_t *icmd;
1456 		/* Last session affecting ELS should be a LOGO */
1457 		for (icmd = irp->irp_els_list; icmd; icmd = icmd->icmd_next) {
1458 			uint8_t op = (ICMD_TO_ELS(icmd))->els_req_payload[0];
1459 			if (op == ELS_OP_LOGO) {
1460 				if (force_implicit) {
1461 					if (icmd->icmd_flags & ICMD_IMPLICIT)
1462 						logging_out = 1;
1463 					else
1464 						logging_out = 0;
1465 				} else {
1466 					logging_out = 1;
1467 				}
1468 			} else if ((op == ELS_OP_PLOGI) ||
1469 			    (op == ELS_OP_PRLI) ||
1470 			    (op == ELS_OP_PRLO) || (op == ELS_OP_TPRLO)) {
1471 				logging_out = 0;
1472 			}
1473 		}
1474 	}
1475 ilo_done:;
1476 	rw_exit(&irp->irp_lock);
1477 
1478 	return (logging_out);
1479 }
1480 
1481 /*
1482  * The force_implicit flag enforces the implicit semantics which may be
1483  * needed if a received logout got stuck e.g. a response to a received
1484  * LOGO never came back from the FCA.
1485  */
1486 int
1487 fct_implicitly_logo_all(fct_i_local_port_t *iport, int force_implicit)
1488 {
1489 	fct_i_remote_port_t	*irp = NULL;
1490 	fct_cmd_t		*cmd = NULL;
1491 	int			 i   = 0;
1492 	int			nports = 0;
1493 
1494 	if (!iport->iport_nrps) {
1495 		return (nports);
1496 	}
1497 
1498 	rw_enter(&iport->iport_lock, RW_WRITER);
1499 	for (i = 0; i < rportid_table_size; i++) {
1500 		irp = iport->iport_rp_tb[i];
1501 		while (irp) {
1502 			if ((!(irp->irp_flags & IRP_PLOGI_DONE)) &&
1503 			    (fct_is_irp_logging_out(irp, force_implicit))) {
1504 				irp = irp->irp_next;
1505 				continue;
1506 			}
1507 
1508 			cmd = fct_create_solels(iport->iport_port, irp->irp_rp,
1509 			    1, ELS_OP_LOGO, 0, fct_logo_cb);
1510 			if (cmd == NULL) {
1511 				stmf_trace(iport->iport_alias,
1512 				    "fct_implictly_logo_all: cmd null");
1513 				rw_exit(&iport->iport_lock);
1514 
1515 				return (nports);
1516 			}
1517 
1518 			fct_post_implicit_logo(cmd);
1519 			nports++;
1520 			irp = irp->irp_next;
1521 		}
1522 	}
1523 	rw_exit(&iport->iport_lock);
1524 
1525 	return (nports);
1526 }
1527 
1528 void
1529 fct_rehash(fct_i_local_port_t *iport)
1530 {
1531 	fct_i_remote_port_t **iport_rp_tb_tmp;
1532 	fct_i_remote_port_t **iport_rp_tb_new;
1533 	fct_i_remote_port_t *irp;
1534 	fct_i_remote_port_t *irp_next;
1535 	int i;
1536 
1537 	iport_rp_tb_new = kmem_zalloc(rportid_table_size *
1538 	    sizeof (fct_i_remote_port_t *), KM_SLEEP);
1539 	rw_enter(&iport->iport_lock, RW_WRITER);
1540 	/* reconstruct the hash table */
1541 	iport_rp_tb_tmp = iport->iport_rp_tb;
1542 	iport->iport_rp_tb = iport_rp_tb_new;
1543 	iport->iport_nrps = 0;
1544 	for (i = 0; i < rportid_table_size; i++) {
1545 		irp = iport_rp_tb_tmp[i];
1546 		while (irp) {
1547 			irp_next = irp->irp_next;
1548 			fct_queue_rp(iport, irp);
1549 			irp = irp_next;
1550 		}
1551 	}
1552 	rw_exit(&iport->iport_lock);
1553 	kmem_free(iport_rp_tb_tmp, rportid_table_size *
1554 	    sizeof (fct_i_remote_port_t *));
1555 
1556 }
1557 
1558 uint8_t
1559 fct_local_port_cleanup_done(fct_i_local_port_t *iport)
1560 {
1561 	fct_i_remote_port_t *irp;
1562 	int i;
1563 
1564 	if (iport->iport_nrps_login)
1565 		return (0);
1566 	/* loop all rps to check if the cmd have already been drained */
1567 	for (i = 0; i < rportid_table_size; i++) {
1568 		irp = iport->iport_rp_tb[i];
1569 		while (irp) {
1570 			if (irp->irp_fcp_xchg_count ||
1571 			    irp->irp_nonfcp_xchg_count)
1572 				return (0);
1573 			irp = irp->irp_next;
1574 		}
1575 	}
1576 	return (1);
1577 }
1578 
1579 fct_cmd_t *
1580 fct_scsi_task_alloc(fct_local_port_t *port, uint16_t rp_handle,
1581 		uint32_t rportid, uint8_t *lun, uint16_t cdb_length,
1582 		uint16_t task_ext)
1583 {
1584 	fct_cmd_t *cmd;
1585 	fct_i_cmd_t *icmd;
1586 	fct_i_local_port_t *iport =
1587 	    (fct_i_local_port_t *)port->port_fct_private;
1588 	fct_i_remote_port_t *irp;
1589 	scsi_task_t *task;
1590 	fct_remote_port_t *rp;
1591 	uint16_t cmd_slot;
1592 
1593 	rw_enter(&iport->iport_lock, RW_READER);
1594 	if ((iport->iport_link_state & S_LINK_ONLINE) == 0) {
1595 		rw_exit(&iport->iport_lock);
1596 		stmf_trace(iport->iport_alias, "cmd alloc called while the port"
1597 		    " was offline");
1598 		return (NULL);
1599 	}
1600 
1601 	if (rp_handle == FCT_HANDLE_NONE) {
1602 		irp = fct_portid_to_portptr(iport, rportid);
1603 		if (irp == NULL) {
1604 			rw_exit(&iport->iport_lock);
1605 			stmf_trace(iport->iport_alias, "cmd received from "
1606 			    "non existent port %x", rportid);
1607 			return (NULL);
1608 		}
1609 	} else {
1610 		if ((rp_handle >= port->port_max_logins) ||
1611 		    ((irp = iport->iport_rp_slots[rp_handle]) == NULL)) {
1612 			rw_exit(&iport->iport_lock);
1613 			stmf_trace(iport->iport_alias, "cmd received from "
1614 			    "invalid port handle %x", rp_handle);
1615 			return (NULL);
1616 		}
1617 	}
1618 	rp = irp->irp_rp;
1619 
1620 	rw_enter(&irp->irp_lock, RW_READER);
1621 	if ((irp->irp_flags & IRP_PRLI_DONE) == 0) {
1622 		rw_exit(&irp->irp_lock);
1623 		rw_exit(&iport->iport_lock);
1624 		stmf_trace(iport->iport_alias, "cmd alloc called while fcp "
1625 		    "login was not done. portid=%x, rp=%p", rp->rp_id, rp);
1626 		return (NULL);
1627 	}
1628 
1629 	mutex_enter(&iport->iport_cached_cmd_lock);
1630 	if ((icmd = iport->iport_cached_cmdlist) != NULL) {
1631 		iport->iport_cached_cmdlist = icmd->icmd_next;
1632 		iport->iport_cached_ncmds--;
1633 		cmd = icmd->icmd_cmd;
1634 	} else {
1635 		icmd = NULL;
1636 	}
1637 	mutex_exit(&iport->iport_cached_cmd_lock);
1638 	if (icmd == NULL) {
1639 		cmd = (fct_cmd_t *)fct_alloc(FCT_STRUCT_CMD_FCP_XCHG,
1640 		    port->port_fca_fcp_cmd_size, 0);
1641 		if (cmd == NULL) {
1642 			rw_exit(&irp->irp_lock);
1643 			rw_exit(&iport->iport_lock);
1644 			stmf_trace(iport->iport_alias, "Ran out of "
1645 			    "memory, port=%p", port);
1646 			return (NULL);
1647 		}
1648 
1649 		icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1650 		icmd->icmd_next = NULL;
1651 		cmd->cmd_port = port;
1652 		atomic_add_32(&iport->iport_total_alloced_ncmds, 1);
1653 	}
1654 
1655 	/*
1656 	 * The accuracy of iport_max_active_ncmds is not important
1657 	 */
1658 	if ((iport->iport_total_alloced_ncmds - iport->iport_cached_ncmds) >
1659 	    iport->iport_max_active_ncmds) {
1660 		iport->iport_max_active_ncmds =
1661 		    iport->iport_total_alloced_ncmds -
1662 		    iport->iport_cached_ncmds;
1663 	}
1664 
1665 	/* Lets get a slot */
1666 	cmd_slot = fct_alloc_cmd_slot(iport, cmd);
1667 	if (cmd_slot == FCT_SLOT_EOL) {
1668 		rw_exit(&irp->irp_lock);
1669 		rw_exit(&iport->iport_lock);
1670 		stmf_trace(iport->iport_alias, "Ran out of xchg resources");
1671 		cmd->cmd_handle = 0;
1672 		fct_cmd_free(cmd);
1673 		return (NULL);
1674 	}
1675 	atomic_add_16(&irp->irp_fcp_xchg_count, 1);
1676 	cmd->cmd_rp = rp;
1677 	icmd->icmd_flags |= ICMD_IN_TRANSITION | ICMD_KNOWN_TO_FCA;
1678 	rw_exit(&irp->irp_lock);
1679 	rw_exit(&iport->iport_lock);
1680 
1681 	icmd->icmd_start_time = ddi_get_lbolt();
1682 
1683 	cmd->cmd_specific = stmf_task_alloc(port->port_lport, irp->irp_session,
1684 	    lun, cdb_length, task_ext);
1685 	if ((task = (scsi_task_t *)cmd->cmd_specific) != NULL) {
1686 		task->task_port_private = cmd;
1687 		return (cmd);
1688 	}
1689 
1690 	fct_cmd_free(cmd);
1691 
1692 	return (NULL);
1693 }
1694 
1695 void
1696 fct_scsi_task_free(scsi_task_t *task)
1697 {
1698 	fct_cmd_t *cmd = (fct_cmd_t *)task->task_port_private;
1699 
1700 	cmd->cmd_comp_status = task->task_completion_status;
1701 	fct_cmd_free(cmd);
1702 }
1703 
1704 void
1705 fct_post_rcvd_cmd(fct_cmd_t *cmd, stmf_data_buf_t *dbuf)
1706 {
1707 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
1708 		fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1709 		fct_i_local_port_t *iport =
1710 		    (fct_i_local_port_t *)cmd->cmd_port->port_fct_private;
1711 		fct_i_remote_port_t *irp =
1712 		    (fct_i_remote_port_t *)cmd->cmd_rp->rp_fct_private;
1713 		scsi_task_t *task = (scsi_task_t *)cmd->cmd_specific;
1714 
1715 		uint16_t irp_task = irp->irp_fcp_xchg_count;
1716 		uint32_t load = iport->iport_total_alloced_ncmds -
1717 		    iport->iport_cached_ncmds;
1718 
1719 		DTRACE_FC_4(scsi__command,
1720 		    fct_cmd_t, cmd,
1721 		    fct_i_local_port_t, iport,
1722 		    scsi_task_t, task,
1723 		    fct_i_remote_port_t, irp);
1724 
1725 		if (load >= iport->iport_task_green_limit) {
1726 			if ((load < iport->iport_task_yellow_limit &&
1727 			    irp_task >= 4) ||
1728 			    (load >= iport->iport_task_yellow_limit &&
1729 			    load < iport->iport_task_red_limit &&
1730 			    irp_task >= 1) ||
1731 			    (load >= iport->iport_task_red_limit))
1732 				task->task_additional_flags |=
1733 				    TASK_AF_PORT_LOAD_HIGH;
1734 		}
1735 		stmf_post_task((scsi_task_t *)cmd->cmd_specific, dbuf);
1736 		atomic_and_32(&icmd->icmd_flags, ~ICMD_IN_TRANSITION);
1737 		return;
1738 	}
1739 	/* We dont need dbuf for other cmds */
1740 	if (dbuf) {
1741 		cmd->cmd_port->port_fds->fds_free_data_buf(
1742 		    cmd->cmd_port->port_fds, dbuf);
1743 		dbuf = NULL;
1744 	}
1745 	if (cmd->cmd_type == FCT_CMD_RCVD_ELS) {
1746 		fct_handle_els(cmd);
1747 		return;
1748 	}
1749 	if (cmd->cmd_type == FCT_CMD_RCVD_ABTS) {
1750 		fct_handle_rcvd_abts(cmd);
1751 		return;
1752 	}
1753 
1754 	ASSERT(0);
1755 }
1756 
1757 /*
1758  * This function bypasses fct_handle_els()
1759  */
1760 void
1761 fct_post_implicit_logo(fct_cmd_t *cmd)
1762 {
1763 	fct_local_port_t *port = cmd->cmd_port;
1764 	fct_i_local_port_t *iport =
1765 	    (fct_i_local_port_t *)port->port_fct_private;
1766 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1767 	fct_remote_port_t *rp = cmd->cmd_rp;
1768 	fct_i_remote_port_t *irp = (fct_i_remote_port_t *)rp->rp_fct_private;
1769 
1770 	icmd->icmd_start_time = ddi_get_lbolt();
1771 
1772 	rw_enter(&irp->irp_lock, RW_WRITER);
1773 	atomic_or_32(&icmd->icmd_flags, ICMD_IMPLICIT_CMD_HAS_RESOURCE);
1774 	atomic_add_16(&irp->irp_nonfcp_xchg_count, 1);
1775 	atomic_add_16(&irp->irp_sa_elses_count, 1);
1776 	/*
1777 	 * An implicit LOGO can also be posted to a irp where a PLOGI might
1778 	 * be in process. That PLOGI will reset this flag and decrement the
1779 	 * iport_nrps_login counter.
1780 	 */
1781 	if (irp->irp_flags & IRP_PLOGI_DONE) {
1782 		atomic_add_32(&iport->iport_nrps_login, -1);
1783 	}
1784 	atomic_and_32(&irp->irp_flags, ~(IRP_PLOGI_DONE | IRP_PRLI_DONE));
1785 	atomic_or_32(&icmd->icmd_flags, ICMD_SESSION_AFFECTING);
1786 	fct_post_to_discovery_queue(iport, irp, icmd);
1787 	rw_exit(&irp->irp_lock);
1788 }
1789 
1790 /*
1791  * called with iport_lock held, return the slot number
1792  */
1793 uint16_t
1794 fct_alloc_cmd_slot(fct_i_local_port_t *iport, fct_cmd_t *cmd)
1795 {
1796 	uint16_t cmd_slot;
1797 	uint32_t old, new;
1798 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1799 
1800 	do {
1801 		old = iport->iport_next_free_slot;
1802 		cmd_slot = old & 0xFFFF;
1803 		if (cmd_slot == FCT_SLOT_EOL)
1804 			return (cmd_slot);
1805 		/*
1806 		 * We use high order 16 bits as a counter which keeps on
1807 		 * incrementing to avoid ABA issues with atomic lists.
1808 		 */
1809 		new = ((old + (0x10000)) & 0xFFFF0000);
1810 		new |= iport->iport_cmd_slots[cmd_slot].slot_next;
1811 	} while (atomic_cas_32(&iport->iport_next_free_slot, old, new) != old);
1812 
1813 	atomic_add_16(&iport->iport_nslots_free, -1);
1814 	iport->iport_cmd_slots[cmd_slot].slot_cmd = icmd;
1815 	cmd->cmd_handle = (uint32_t)cmd_slot | 0x80000000 |
1816 	    (((uint32_t)(iport->iport_cmd_slots[cmd_slot].slot_uniq_cntr))
1817 	    << 24);
1818 	return (cmd_slot);
1819 }
1820 
1821 /*
1822  * If icmd is not NULL, irp_lock must be held
1823  */
1824 void
1825 fct_post_to_discovery_queue(fct_i_local_port_t *iport,
1826     fct_i_remote_port_t *irp, fct_i_cmd_t *icmd)
1827 {
1828 	fct_i_cmd_t	**p;
1829 
1830 	ASSERT(!MUTEX_HELD(&iport->iport_worker_lock));
1831 	if (icmd) {
1832 		icmd->icmd_next = NULL;
1833 		for (p = &irp->irp_els_list; *p != NULL;
1834 		    p = &((*p)->icmd_next))
1835 			;
1836 
1837 		*p = icmd;
1838 		atomic_or_32(&icmd->icmd_flags, ICMD_IN_IRP_QUEUE);
1839 	}
1840 
1841 	mutex_enter(&iport->iport_worker_lock);
1842 	if ((irp->irp_flags & IRP_IN_DISCOVERY_QUEUE) == 0) {
1843 
1844 		/*
1845 		 * CAUTION: do not grab local_port/remote_port locks after
1846 		 * grabbing the worker lock.
1847 		 */
1848 		irp->irp_discovery_next = NULL;
1849 		if (iport->iport_rpwe_tail) {
1850 			iport->iport_rpwe_tail->irp_discovery_next = irp;
1851 			iport->iport_rpwe_tail = irp;
1852 		} else {
1853 			iport->iport_rpwe_head = iport->iport_rpwe_tail = irp;
1854 		}
1855 
1856 		atomic_or_32(&irp->irp_flags, IRP_IN_DISCOVERY_QUEUE);
1857 	}
1858 
1859 	/*
1860 	 * We need always signal the port worker irrespective of the fact that
1861 	 * irp is already in discovery queue or not.
1862 	 */
1863 	if (IS_WORKER_SLEEPING(iport)) {
1864 		cv_signal(&iport->iport_worker_cv);
1865 	}
1866 	mutex_exit(&iport->iport_worker_lock);
1867 }
1868 
1869 stmf_status_t
1870 fct_xfer_scsi_data(scsi_task_t *task, stmf_data_buf_t *dbuf, uint32_t ioflags)
1871 {
1872 	fct_cmd_t *cmd = (fct_cmd_t *)task->task_port_private;
1873 
1874 	DTRACE_FC_5(xfer__start,
1875 	    fct_cmd_t, cmd,
1876 	    fct_i_local_port_t, cmd->cmd_port->port_fct_private,
1877 	    scsi_task_t, task,
1878 	    fct_i_remote_port_t, cmd->cmd_rp->rp_fct_private,
1879 	    stmf_data_buf_t, dbuf);
1880 
1881 	return (cmd->cmd_port->port_xfer_scsi_data(cmd, dbuf, ioflags));
1882 }
1883 
1884 void
1885 fct_scsi_data_xfer_done(fct_cmd_t *cmd, stmf_data_buf_t *dbuf, uint32_t ioflags)
1886 {
1887 	fct_i_cmd_t	*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1888 	uint32_t	old, new;
1889 	uint32_t	iof = 0;
1890 
1891 	DTRACE_FC_5(xfer__done,
1892 	    fct_cmd_t, cmd,
1893 	    fct_i_local_port_t, cmd->cmd_port->port_fct_private,
1894 	    scsi_task_t, ((scsi_task_t *)cmd->cmd_specific),
1895 	    fct_i_remote_port_t, cmd->cmd_rp->rp_fct_private,
1896 	    stmf_data_buf_t, dbuf);
1897 
1898 	if (ioflags & FCT_IOF_FCA_DONE) {
1899 		do {
1900 			old = new = icmd->icmd_flags;
1901 			if (old & ICMD_BEING_ABORTED) {
1902 				return;
1903 			}
1904 			new &= ~ICMD_KNOWN_TO_FCA;
1905 		} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
1906 		iof = STMF_IOF_LPORT_DONE;
1907 		cmd->cmd_comp_status = dbuf->db_xfer_status;
1908 	}
1909 
1910 	if (icmd->icmd_flags & ICMD_BEING_ABORTED)
1911 		return;
1912 	stmf_data_xfer_done((scsi_task_t *)cmd->cmd_specific, dbuf, iof);
1913 }
1914 
1915 stmf_status_t
1916 fct_send_scsi_status(scsi_task_t *task, uint32_t ioflags)
1917 {
1918 	fct_cmd_t *cmd = (fct_cmd_t *)task->task_port_private;
1919 
1920 	DTRACE_FC_4(scsi__response,
1921 	    fct_cmd_t, cmd,
1922 	    fct_i_local_port_t,
1923 	    (fct_i_local_port_t *)cmd->cmd_port->port_fct_private,
1924 	    scsi_task_t, task,
1925 	    fct_i_remote_port_t,
1926 	    (fct_i_remote_port_t *)cmd->cmd_rp->rp_fct_private);
1927 
1928 	return (cmd->cmd_port->port_send_cmd_response(cmd, ioflags));
1929 }
1930 
1931 void
1932 fct_send_response_done(fct_cmd_t *cmd, fct_status_t s, uint32_t ioflags)
1933 {
1934 	fct_i_cmd_t	*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1935 	fct_local_port_t *port = cmd->cmd_port;
1936 	fct_i_local_port_t *iport = (fct_i_local_port_t *)
1937 	    port->port_fct_private;
1938 	uint32_t old, new;
1939 
1940 	if ((ioflags & FCT_IOF_FCA_DONE) == 0) {
1941 		/* Until we support confirmed completions, this is an error */
1942 		fct_queue_cmd_for_termination(cmd, s);
1943 		return;
1944 	}
1945 	do {
1946 		old = new = icmd->icmd_flags;
1947 		if (old & ICMD_BEING_ABORTED) {
1948 			return;
1949 		}
1950 		new &= ~ICMD_KNOWN_TO_FCA;
1951 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
1952 
1953 	cmd->cmd_comp_status = s;
1954 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
1955 		stmf_send_status_done((scsi_task_t *)cmd->cmd_specific, s,
1956 		    STMF_IOF_LPORT_DONE);
1957 		return;
1958 	}
1959 
1960 	if (cmd->cmd_type == FCT_CMD_RCVD_ELS) {
1961 		fct_cmd_free(cmd);
1962 		return;
1963 	} else if (cmd->cmd_type == FCT_CMD_SOL_ELS) {
1964 		fct_handle_sol_els_completion(iport, icmd);
1965 	} else if (cmd->cmd_type == FCT_CMD_SOL_CT) {
1966 		/* Tell the caller that we are done */
1967 		atomic_or_32(&icmd->icmd_flags, ICMD_CMD_COMPLETE);
1968 	} else {
1969 		ASSERT(0);
1970 	}
1971 }
1972 
1973 void
1974 fct_cmd_free(fct_cmd_t *cmd)
1975 {
1976 	char			info[80];
1977 	fct_i_cmd_t		*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
1978 	fct_local_port_t	*port = cmd->cmd_port;
1979 	fct_i_local_port_t	*iport = (fct_i_local_port_t *)
1980 	    port->port_fct_private;
1981 	fct_i_remote_port_t	*irp = NULL;
1982 	int			do_abts_acc = 0;
1983 	uint32_t		old, new;
1984 
1985 	ASSERT(!mutex_owned(&iport->iport_worker_lock));
1986 	/* Give the slot back */
1987 	if (CMD_HANDLE_VALID(cmd->cmd_handle)) {
1988 		uint16_t n = CMD_HANDLE_SLOT_INDEX(cmd->cmd_handle);
1989 		fct_cmd_slot_t *slot;
1990 
1991 		/*
1992 		 * If anything went wrong, grab the lock as writer. This is
1993 		 * probably unnecessary.
1994 		 */
1995 		if ((cmd->cmd_comp_status != FCT_SUCCESS) ||
1996 		    (icmd->icmd_flags & ICMD_ABTS_RECEIVED)) {
1997 			rw_enter(&iport->iport_lock, RW_WRITER);
1998 		} else {
1999 			rw_enter(&iport->iport_lock, RW_READER);
2000 		}
2001 
2002 		if ((icmd->icmd_flags & ICMD_ABTS_RECEIVED) &&
2003 		    (cmd->cmd_link != NULL)) {
2004 			do_abts_acc = 1;
2005 		}
2006 
2007 		/* XXX Validate slot before freeing */
2008 
2009 		slot = &iport->iport_cmd_slots[n];
2010 		slot->slot_uniq_cntr++;
2011 		slot->slot_cmd = NULL;
2012 		do {
2013 			old = iport->iport_next_free_slot;
2014 			slot->slot_next = old & 0xFFFF;
2015 			new = (old + 0x10000) & 0xFFFF0000;
2016 			new |= slot->slot_no;
2017 		} while (atomic_cas_32(&iport->iport_next_free_slot,
2018 		    old, new) != old);
2019 		cmd->cmd_handle = 0;
2020 		atomic_add_16(&iport->iport_nslots_free, 1);
2021 		if (cmd->cmd_rp) {
2022 			irp = (fct_i_remote_port_t *)
2023 			    cmd->cmd_rp->rp_fct_private;
2024 			if (cmd->cmd_type == FCT_CMD_FCP_XCHG)
2025 				atomic_add_16(&irp->irp_fcp_xchg_count, -1);
2026 			else
2027 				atomic_add_16(&irp->irp_nonfcp_xchg_count, -1);
2028 		}
2029 		rw_exit(&iport->iport_lock);
2030 	} else if ((icmd->icmd_flags & ICMD_IMPLICIT) &&
2031 	    (icmd->icmd_flags & ICMD_IMPLICIT_CMD_HAS_RESOURCE)) {
2032 		/* for implicit cmd, no cmd slot is used */
2033 		if (cmd->cmd_rp) {
2034 			irp = (fct_i_remote_port_t *)
2035 			    cmd->cmd_rp->rp_fct_private;
2036 			if (cmd->cmd_type == FCT_CMD_FCP_XCHG)
2037 				atomic_add_16(&irp->irp_fcp_xchg_count, -1);
2038 			else
2039 				atomic_add_16(&irp->irp_nonfcp_xchg_count, -1);
2040 		}
2041 	}
2042 
2043 	if (do_abts_acc) {
2044 		fct_cmd_t *lcmd = cmd->cmd_link;
2045 		fct_fill_abts_acc(lcmd);
2046 		if (port->port_send_cmd_response(lcmd,
2047 		    FCT_IOF_FORCE_FCA_DONE) != FCT_SUCCESS) {
2048 			/*
2049 			 * XXX Throw HBA fatal error event
2050 			 * Later shutdown svc will terminate the ABTS in the end
2051 			 */
2052 			(void) snprintf(info, 80,
2053 			    "fct_cmd_free: iport-%p, ABTS_ACC"
2054 			    " port_send_cmd_response failed", (void *)iport);
2055 			info[79] = 0;
2056 			(void) fct_port_shutdown(iport->iport_port,
2057 			    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
2058 			return;
2059 		} else {
2060 			fct_cmd_free(lcmd);
2061 			cmd->cmd_link = NULL;
2062 		}
2063 	}
2064 
2065 	/* Free the cmd */
2066 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
2067 		if (iport->iport_cached_ncmds < max_cached_ncmds) {
2068 			icmd->icmd_flags = 0;
2069 			mutex_enter(&iport->iport_cached_cmd_lock);
2070 			icmd->icmd_next = iport->iport_cached_cmdlist;
2071 			iport->iport_cached_cmdlist = icmd;
2072 			iport->iport_cached_ncmds++;
2073 			mutex_exit(&iport->iport_cached_cmd_lock);
2074 		} else {
2075 			atomic_add_32(&iport->iport_total_alloced_ncmds, -1);
2076 			fct_free(cmd);
2077 		}
2078 	} else {
2079 		fct_free(cmd);
2080 	}
2081 }
2082 
2083 /* ARGSUSED */
2084 stmf_status_t
2085 fct_scsi_abort(stmf_local_port_t *lport, int abort_cmd, void *arg,
2086 							uint32_t flags)
2087 {
2088 	stmf_status_t ret = STMF_SUCCESS;
2089 	scsi_task_t *task;
2090 	fct_cmd_t *cmd;
2091 	fct_i_cmd_t *icmd;
2092 	fct_local_port_t *port;
2093 	uint32_t old, new;
2094 
2095 	ASSERT(abort_cmd == STMF_LPORT_ABORT_TASK);
2096 
2097 	task = (scsi_task_t *)arg;
2098 	cmd = (fct_cmd_t *)task->task_port_private;
2099 	icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2100 	port = (fct_local_port_t *)lport->lport_port_private;
2101 
2102 	do {
2103 		old = new = icmd->icmd_flags;
2104 		if ((old & ICMD_KNOWN_TO_FCA) == 0)
2105 			return (STMF_NOT_FOUND);
2106 		ASSERT((old & ICMD_FCA_ABORT_CALLED) == 0);
2107 		new |= ICMD_BEING_ABORTED | ICMD_FCA_ABORT_CALLED;
2108 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
2109 	ret = port->port_abort_cmd(port, cmd, 0);
2110 	if ((ret == FCT_NOT_FOUND) || (ret == FCT_ABORT_SUCCESS)) {
2111 		atomic_and_32(&icmd->icmd_flags, ~ICMD_KNOWN_TO_FCA);
2112 	} else if (ret == FCT_BUSY) {
2113 		atomic_and_32(&icmd->icmd_flags, ~ICMD_FCA_ABORT_CALLED);
2114 	}
2115 
2116 	return (ret);
2117 }
2118 
2119 void
2120 fct_ctl(struct stmf_local_port *lport, int cmd, void *arg)
2121 {
2122 	fct_local_port_t *port;
2123 	fct_i_local_port_t *iport;
2124 	stmf_change_status_t st;
2125 	stmf_change_status_t *pst;
2126 
2127 	ASSERT((cmd == STMF_CMD_LPORT_ONLINE) ||
2128 	    (cmd == STMF_ACK_LPORT_ONLINE_COMPLETE) ||
2129 	    (cmd == STMF_CMD_LPORT_OFFLINE) ||
2130 	    (cmd == STMF_ACK_LPORT_OFFLINE_COMPLETE) ||
2131 	    (cmd == FCT_CMD_PORT_ONLINE_COMPLETE) ||
2132 	    (cmd == FCT_CMD_PORT_OFFLINE_COMPLETE));
2133 
2134 	port = (fct_local_port_t *)lport->lport_port_private;
2135 	pst = (stmf_change_status_t *)arg;
2136 	st.st_completion_status = STMF_SUCCESS;
2137 	st.st_additional_info = NULL;
2138 
2139 	iport = (fct_i_local_port_t *)port->port_fct_private;
2140 	/*
2141 	 * We are mostly a passthrough, except during offline.
2142 	 */
2143 	switch (cmd) {
2144 	case STMF_CMD_LPORT_ONLINE:
2145 		if (iport->iport_state == FCT_STATE_ONLINE)
2146 			st.st_completion_status = STMF_ALREADY;
2147 		else if (iport->iport_state != FCT_STATE_OFFLINE)
2148 			st.st_completion_status = STMF_INVALID_ARG;
2149 		if (st.st_completion_status != STMF_SUCCESS) {
2150 			(void) stmf_ctl(STMF_CMD_LPORT_ONLINE_COMPLETE, lport,
2151 			    &st);
2152 			break;
2153 		}
2154 		iport->iport_state_not_acked = 1;
2155 		iport->iport_state = FCT_STATE_ONLINING;
2156 		port->port_ctl(port, FCT_CMD_PORT_ONLINE, arg);
2157 		break;
2158 	case FCT_CMD_PORT_ONLINE_COMPLETE:
2159 		ASSERT(iport->iport_state == FCT_STATE_ONLINING);
2160 		if (pst->st_completion_status != FCT_SUCCESS) {
2161 			iport->iport_state = FCT_STATE_OFFLINE;
2162 			iport->iport_state_not_acked = 0;
2163 		} else {
2164 			iport->iport_state = FCT_STATE_ONLINE;
2165 		}
2166 		(void) stmf_ctl(STMF_CMD_LPORT_ONLINE_COMPLETE, lport, arg);
2167 		break;
2168 	case STMF_ACK_LPORT_ONLINE_COMPLETE:
2169 		ASSERT(iport->iport_state == FCT_STATE_ONLINE);
2170 		iport->iport_state_not_acked = 0;
2171 		port->port_ctl(port, FCT_ACK_PORT_ONLINE_COMPLETE, arg);
2172 		break;
2173 
2174 	case STMF_CMD_LPORT_OFFLINE:
2175 		if (iport->iport_state == FCT_STATE_OFFLINE)
2176 			st.st_completion_status = STMF_ALREADY;
2177 		else if (iport->iport_state != FCT_STATE_ONLINE)
2178 			st.st_completion_status = STMF_INVALID_ARG;
2179 		if (st.st_completion_status != STMF_SUCCESS) {
2180 			(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE_COMPLETE, lport,
2181 			    &st);
2182 			break;
2183 		}
2184 		iport->iport_state_not_acked = 1;
2185 		iport->iport_state = FCT_STATE_OFFLINING;
2186 		port->port_ctl(port, FCT_CMD_PORT_OFFLINE, arg);
2187 		break;
2188 	case FCT_CMD_PORT_OFFLINE_COMPLETE:
2189 		ASSERT(iport->iport_state == FCT_STATE_OFFLINING);
2190 		if (pst->st_completion_status != FCT_SUCCESS) {
2191 			iport->iport_state = FCT_STATE_ONLINE;
2192 			iport->iport_state_not_acked = 0;
2193 			(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE_COMPLETE, lport,
2194 			    pst);
2195 			break;
2196 		}
2197 
2198 		/*
2199 		 * If FCA's offline was successful, we dont tell stmf yet.
2200 		 * Becasue now we have to do the cleanup before we go upto
2201 		 * stmf. That cleanup is done by the worker thread.
2202 		 */
2203 
2204 		/* FCA is offline, post a link down, its harmless anyway */
2205 		fct_handle_event(port, FCT_EVENT_LINK_DOWN, 0, 0);
2206 
2207 		/* Trigger port offline processing by the worker */
2208 		iport->iport_offline_prstate = FCT_OPR_START;
2209 		break;
2210 	case STMF_ACK_LPORT_OFFLINE_COMPLETE:
2211 		ASSERT(iport->iport_state == FCT_STATE_OFFLINE);
2212 		iport->iport_state_not_acked = 0;
2213 		port->port_ctl(port, FCT_ACK_PORT_OFFLINE_COMPLETE, arg);
2214 		break;
2215 	}
2216 }
2217 
2218 /* ARGSUSED */
2219 stmf_status_t
2220 fct_info(uint32_t cmd, stmf_local_port_t *lport, void *arg, uint8_t *buf,
2221 						uint32_t *bufsizep)
2222 {
2223 	return (STMF_NOT_SUPPORTED);
2224 }
2225 
2226 /*
2227  * implicit: if it's true, it means it will only be used in fct module, or else
2228  * it will be sent to the link.
2229  */
2230 fct_cmd_t *
2231 fct_create_solels(fct_local_port_t *port, fct_remote_port_t *rp, int implicit,
2232     uchar_t elsop, uint32_t wkdid, fct_icmd_cb_t icmdcb)
2233 {
2234 	fct_cmd_t		*cmd	= NULL;
2235 	fct_i_cmd_t		*icmd	= NULL;
2236 	fct_els_t		*els	= NULL;
2237 	fct_i_remote_port_t	*irp	= NULL;
2238 	uint8_t			*p	= NULL;
2239 	uint32_t		 ptid	= 0;
2240 
2241 	cmd = (fct_cmd_t *)fct_alloc(FCT_STRUCT_CMD_SOL_ELS,
2242 	    port->port_fca_sol_els_private_size, 0);
2243 	if (!cmd) {
2244 		return (NULL);
2245 	}
2246 
2247 	if (rp) {
2248 		irp = RP_TO_IRP(rp);
2249 	} else if (((irp = fct_portid_to_portptr(PORT_TO_IPORT(port),
2250 	    wkdid)) == NULL) && (elsop != ELS_OP_PLOGI)) {
2251 		stmf_trace(PORT_TO_IPORT(port)->iport_alias,
2252 		    "fct_create_solels: Must PLOGI to %x first", wkdid);
2253 		fct_free(cmd);
2254 		return (NULL);
2255 	}
2256 
2257 	cmd->cmd_port	= port;
2258 	cmd->cmd_oxid	= PTR2INT(cmd, uint16_t);
2259 	cmd->cmd_rxid	= 0xFFFF;
2260 	cmd->cmd_handle = 0;
2261 	icmd		= CMD_TO_ICMD(cmd);
2262 	els		= ICMD_TO_ELS(icmd);
2263 	icmd->icmd_cb	= icmdcb;
2264 	if (irp) {
2265 		cmd->cmd_rp	   = irp->irp_rp;
2266 		cmd->cmd_rp_handle = irp->irp_rp->rp_handle;
2267 		cmd->cmd_rportid   = irp->irp_rp->rp_id;
2268 	} else {
2269 		cmd->cmd_rp_handle = FCT_HANDLE_NONE;
2270 		cmd->cmd_rportid   = wkdid;
2271 	}
2272 	cmd->cmd_lportid = (PORT_TO_IPORT(port))->iport_link_info.portid;
2273 
2274 	if (implicit) {
2275 		/*
2276 		 * Since we will not send it to FCA, so we only allocate space
2277 		 */
2278 		ASSERT(elsop & (ELS_OP_LOGO | ELS_OP_PLOGI));
2279 		icmd->icmd_flags |= ICMD_IMPLICIT;
2280 		if (elsop == ELS_OP_LOGO) {
2281 			/*
2282 			 * Handling implicit LOGO should dependent on as less
2283 			 * as resources. So a trick here.
2284 			 */
2285 			els->els_req_size = 1;
2286 			els->els_req_payload = cmd->cmd_fca_private;
2287 		} else {
2288 			els->els_req_alloc_size = els->els_req_size = 116;
2289 			els->els_resp_alloc_size = els->els_resp_size = 116;
2290 			els->els_req_payload = (uint8_t *)
2291 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2292 			els->els_resp_payload = (uint8_t *)
2293 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2294 		}
2295 	} else {
2296 		/*
2297 		 * Allocate space for its request and response
2298 		 * Fill the request payload according to spec.
2299 		 */
2300 		switch (elsop) {
2301 		case ELS_OP_LOGO:
2302 			els->els_resp_alloc_size = els->els_resp_size = 4;
2303 			els->els_resp_payload = (uint8_t *)kmem_zalloc(
2304 			    els->els_resp_size, KM_SLEEP);
2305 			els->els_req_alloc_size = els->els_req_size = 16;
2306 			els->els_req_payload = (uint8_t *)kmem_zalloc(
2307 			    els->els_req_size, KM_SLEEP);
2308 			ptid = PORT_TO_IPORT(port)->iport_link_info.portid;
2309 			fct_value_to_netbuf(ptid, els->els_req_payload + 5, 3);
2310 			bcopy(port->port_pwwn, els->els_req_payload + 8, 8);
2311 			break;
2312 
2313 		case ELS_OP_RSCN:
2314 			els->els_resp_alloc_size = els->els_resp_size = 4;
2315 			els->els_resp_payload = (uint8_t *)kmem_zalloc(
2316 			    els->els_resp_size, KM_SLEEP);
2317 			els->els_req_size = els->els_req_alloc_size = 8;
2318 			els->els_req_payload = (uint8_t *)kmem_zalloc(
2319 			    els->els_req_size, KM_SLEEP);
2320 			els->els_req_payload[1] = 0x04;
2321 			els->els_req_payload[3] = 0x08;
2322 			els->els_req_payload[4] |= 0x80;
2323 			ptid = PORT_TO_IPORT(port)->iport_link_info.portid;
2324 			fct_value_to_netbuf(ptid, els->els_req_payload + 5, 3);
2325 			break;
2326 
2327 		case ELS_OP_PLOGI:
2328 			els->els_resp_alloc_size = els->els_resp_size = 116;
2329 			els->els_resp_payload = (uint8_t *)
2330 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2331 			els->els_req_alloc_size = els->els_req_size = 116;
2332 			p = els->els_req_payload = (uint8_t *)
2333 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2334 			bcopy(port->port_pwwn, p + 20, 8);
2335 			bcopy(port->port_nwwn, p + 28, 8);
2336 
2337 			/*
2338 			 * Common service parameters
2339 			 */
2340 			p[0x04] = 0x09;		/* high version */
2341 			p[0x05] = 0x08;		/* low version */
2342 			p[0x06] = 0x00;		/* BB credit: 0x0065 */
2343 			p[0x07] = 0x65;
2344 
2345 			/* CI0: Continuously Increasing Offset - 1 */
2346 			/* RRO: Randomly Relative Offset - 0 */
2347 			/* VVV: Vendor Version Level - 0 */
2348 			/* N-F: N or F Port Payload Sender - 0 (N) */
2349 			/* BBM: BB Credit Management - 0 (Normal) */
2350 			p[0x08] = 0x80;
2351 			p[0x09] = 0x00;
2352 
2353 			/* Max RX size */
2354 			p[0x0A] = 0x08;
2355 			p[0x0B] = 0x00;
2356 
2357 			/* NPTCS: N Port Total Concurrent Sequences - 0x0000 */
2358 			p[0x0C] = 0x00;
2359 			p[0x0D] = 0x00;
2360 
2361 			/* ROIC: Relative Offset By Info - 0xFFFF */
2362 			p[0x0E] = 0xFF;
2363 			p[0x0F] = 0xFF;
2364 
2365 			/* EDTOV: Error Detect Timeout - 0x000007D0 */
2366 			p[0x10] = 0x00;
2367 			p[0x11] = 0x00;
2368 			p[0x12] = 0x07;
2369 			p[0x13] = 0xD0;
2370 
2371 			/*
2372 			 * Class-3 Parameters
2373 			 */
2374 			/* C3-VAL: Class 3 Value - 1 */
2375 			/* C3-XID: X_ID Reassignment - 0 */
2376 			/* C3-IPA: Initial Process Assignment */
2377 			/* C3-AI-DCC: Data compression capable */
2378 			/* C3-AI-DC-HB: Data compression history buffer size */
2379 			/* C3-AI-DCE: Data encrytion capable */
2380 			/* C3-AI-CSC: Clock synchronization capable */
2381 			/* C3-ErrPol: Error pliciy */
2382 			/* C3-CatSeq: Information Cat. Per Sequence */
2383 			/* C3-AR-DCC: */
2384 			/* C3-AR-DC-HB: */
2385 			/* C3-AR-DCE: */
2386 			/* C3-AR-CSC */
2387 			p[0x44] = 0x80;
2388 			p[0x45] = 0x00;
2389 			p[0x46] = 0x00;
2390 			p[0x47] = 0x00;
2391 			p[0x48] = 0x00;
2392 			p[0x49] = 0x00;
2393 
2394 			/* C3-RxSize: Class 3 receive data size */
2395 			p[0x4A] = 0x08;
2396 			p[0x4B] = 0x00;
2397 
2398 			/* C3-ConSeq: Class 3 Concourrent sequences */
2399 			p[0x4C] = 0x00;
2400 			p[0x4D] = 0xFF;
2401 
2402 			/* C3-OSPE: Class 3 open sequence per exchange */
2403 			p[0x50] = 0x00;
2404 			p[0x51] = 0x01;
2405 
2406 			break;
2407 
2408 		case ELS_OP_SCR:
2409 			els->els_resp_alloc_size = els->els_resp_size = 4;
2410 			els->els_resp_payload = (uint8_t *)
2411 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2412 			els->els_req_alloc_size = els->els_req_size = 8;
2413 			p = els->els_req_payload = (uint8_t *)
2414 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2415 			p[7] = FC_SCR_FULL_REGISTRATION;
2416 			break;
2417 		case ELS_OP_RLS:
2418 			els->els_resp_alloc_size = els->els_resp_size = 28;
2419 			els->els_resp_payload = (uint8_t *)
2420 			    kmem_zalloc(els->els_resp_size, KM_SLEEP);
2421 			els->els_req_alloc_size = els->els_req_size = 8;
2422 			p = els->els_req_payload = (uint8_t *)
2423 			    kmem_zalloc(els->els_req_size, KM_SLEEP);
2424 			ptid = PORT_TO_IPORT(port)->iport_link_info.portid;
2425 			fct_value_to_netbuf(ptid, els->els_req_payload + 5, 3);
2426 			break;
2427 
2428 		default:
2429 			ASSERT(0);
2430 		}
2431 	}
2432 
2433 	els->els_req_payload[0] = elsop;
2434 	return (cmd);
2435 }
2436 
2437 fct_cmd_t *
2438 fct_create_solct(fct_local_port_t *port, fct_remote_port_t *query_rp,
2439     uint16_t ctop, fct_icmd_cb_t icmdcb)
2440 {
2441 	fct_cmd_t		*cmd	 = NULL;
2442 	fct_i_cmd_t		*icmd	 = NULL;
2443 	fct_sol_ct_t		*ct	 = NULL;
2444 	uint8_t			*p	 = NULL;
2445 	fct_i_remote_port_t	*irp	 = NULL;
2446 	fct_i_local_port_t	*iport	 = NULL;
2447 	char			*nname	 = NULL;
2448 	int			 namelen = 0;
2449 
2450 	/*
2451 	 * Allocate space
2452 	 */
2453 	cmd = fct_alloc(FCT_STRUCT_CMD_SOL_CT,
2454 	    port->port_fca_sol_ct_private_size, 0);
2455 	if (!cmd) {
2456 		return (NULL);
2457 	}
2458 
2459 	/*
2460 	 * We should have PLOGIed to the name server (0xFFFFFC)
2461 	 * Caution: this irp is not query_rp->rp_fct_private.
2462 	 */
2463 	irp = fct_portid_to_portptr((fct_i_local_port_t *)
2464 	    port->port_fct_private, FS_NAME_SERVER);
2465 	if (irp == NULL) {
2466 		stmf_trace(PORT_TO_IPORT(port)->iport_alias,
2467 		    "fct_create_solct: Must PLOGI name server first");
2468 		fct_free(cmd);
2469 		return (NULL);
2470 	}
2471 
2472 	cmd->cmd_port	   = port;
2473 	cmd->cmd_rp	   = irp->irp_rp;
2474 	cmd->cmd_rp_handle = irp->irp_rp->rp_handle;
2475 	cmd->cmd_rportid   = irp->irp_rp->rp_id;
2476 	cmd->cmd_lportid   = (PORT_TO_IPORT(port))->iport_link_info.portid;
2477 	cmd->cmd_oxid	   = PTR2INT(cmd, uint16_t);
2478 	cmd->cmd_rxid	   = 0xFFFF;
2479 	cmd->cmd_handle	   = 0;
2480 	icmd		   = CMD_TO_ICMD(cmd);
2481 	ct		   = ICMD_TO_CT(icmd);
2482 	icmd->icmd_cb	   = icmdcb;
2483 	iport		   = ICMD_TO_IPORT(icmd);
2484 
2485 	switch (ctop) {
2486 	case NS_GSNN_NN:
2487 		/*
2488 		 * Allocate max space for its sybolic name
2489 		 */
2490 		ct->ct_resp_alloc_size = ct->ct_resp_size = 272;
2491 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2492 		    KM_SLEEP);
2493 
2494 		ct->ct_req_size = ct->ct_req_alloc_size = 24;
2495 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2496 		    KM_SLEEP);
2497 
2498 		bcopy(query_rp->rp_nwwn, p + 16, 8);
2499 		break;
2500 
2501 	case NS_RNN_ID:
2502 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2503 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2504 		    KM_SLEEP);
2505 		ct->ct_req_size = ct->ct_req_alloc_size = 28;
2506 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2507 		    KM_SLEEP);
2508 
2509 		/*
2510 		 * Port Identifier
2511 		 */
2512 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2513 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2514 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2515 
2516 		/*
2517 		 * Node Name
2518 		 */
2519 		bcopy(port->port_nwwn, p + 20, 8);
2520 		break;
2521 
2522 	case NS_RCS_ID:
2523 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2524 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2525 		    KM_SLEEP);
2526 		ct->ct_req_size = ct->ct_req_alloc_size = 24;
2527 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2528 		    KM_SLEEP);
2529 
2530 		/*
2531 		 * Port Identifier
2532 		 */
2533 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2534 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2535 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2536 
2537 		/*
2538 		 * Class of Service
2539 		 */
2540 		*(p + 23) = FC_NS_CLASS3;
2541 		break;
2542 
2543 	case NS_RFT_ID:
2544 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2545 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2546 		    KM_SLEEP);
2547 		ct->ct_req_size = ct->ct_req_alloc_size = 52;
2548 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2549 		    KM_SLEEP);
2550 
2551 		/*
2552 		 * Port Identifier
2553 		 */
2554 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2555 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2556 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2557 
2558 		/*
2559 		 * FC-4 Protocol Types
2560 		 */
2561 		*(p + 22) = 0x1;	/* 0x100 */
2562 		break;
2563 
2564 	case NS_RSPN_ID:
2565 		/*
2566 		 * If we get here, port->port_sym_port_name is always not NULL.
2567 		 */
2568 		ASSERT(port->port_sym_port_name);
2569 		namelen = strlen(port->port_sym_port_name);
2570 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2571 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2572 		    KM_SLEEP);
2573 		ct->ct_req_size = ct->ct_req_alloc_size =
2574 		    (21 + namelen + 3) & ~3;
2575 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2576 		    KM_SLEEP);
2577 
2578 		/*
2579 		 * Port Identifier
2580 		 */
2581 		p[17] = (iport->iport_link_info.portid >> 16) & 0xFF;
2582 		p[18] = (iport->iport_link_info.portid >>  8) & 0xFF;
2583 		p[19] = (iport->iport_link_info.portid >>  0) & 0xFF;
2584 
2585 		/*
2586 		 * String length
2587 		 */
2588 		p[20] = namelen;
2589 
2590 		/*
2591 		 * Symbolic port name
2592 		 */
2593 		bcopy(port->port_sym_port_name, p + 21, ct->ct_req_size - 21);
2594 		break;
2595 
2596 	case NS_RSNN_NN:
2597 		namelen = port->port_sym_node_name == NULL ?
2598 		    strlen(utsname.nodename) :
2599 		    strlen(port->port_sym_node_name);
2600 		nname = port->port_sym_node_name == NULL ?
2601 		    utsname.nodename : port->port_sym_node_name;
2602 
2603 		ct->ct_resp_alloc_size = ct->ct_resp_size = 16;
2604 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2605 		    KM_SLEEP);
2606 		ct->ct_req_size = ct->ct_req_alloc_size =
2607 		    (25 + namelen + 3) & ~3;
2608 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2609 		    KM_SLEEP);
2610 
2611 		/*
2612 		 * Node name
2613 		 */
2614 		bcopy(port->port_nwwn, p + 16, 8);
2615 
2616 		/*
2617 		 * String length
2618 		 */
2619 		p[24] = namelen;
2620 
2621 		/*
2622 		 * Symbolic node name
2623 		 */
2624 		bcopy(nname, p + 25, ct->ct_req_size - 25);
2625 		break;
2626 
2627 	case NS_GSPN_ID:
2628 		ct->ct_resp_alloc_size = ct->ct_resp_size = 272;
2629 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2630 		    KM_SLEEP);
2631 		ct->ct_req_size = ct->ct_req_alloc_size = 20;
2632 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2633 		    KM_SLEEP);
2634 		/*
2635 		 * Port Identifier
2636 		 */
2637 		p[17] = (query_rp->rp_id >> 16) & 0xFF;
2638 		p[18] = (query_rp->rp_id >>  8) & 0xFF;
2639 		p[19] = (query_rp->rp_id >>  0) & 0xFF;
2640 		break;
2641 
2642 	case NS_GCS_ID:
2643 		ct->ct_resp_alloc_size = ct->ct_resp_size = 20;
2644 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2645 		    KM_SLEEP);
2646 		ct->ct_req_size = ct->ct_req_alloc_size = 20;
2647 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2648 		    KM_SLEEP);
2649 		/*
2650 		 * Port Identifier
2651 		 */
2652 		p[17] = (query_rp->rp_id >> 16) & 0xFF;
2653 		p[18] = (query_rp->rp_id >>  8) & 0xFF;
2654 		p[19] = (query_rp->rp_id >>  0) & 0xFF;
2655 		break;
2656 
2657 	case NS_GFT_ID:
2658 		ct->ct_resp_alloc_size = ct->ct_resp_size = 48;
2659 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2660 		    KM_SLEEP);
2661 		ct->ct_req_size = ct->ct_req_alloc_size = 20;
2662 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2663 		    KM_SLEEP);
2664 		/*
2665 		 * Port Identifier
2666 		 */
2667 		p[17] = (query_rp->rp_id >> 16) & 0xFF;
2668 		p[18] = (query_rp->rp_id >>  8) & 0xFF;
2669 		p[19] = (query_rp->rp_id >>  0) & 0xFF;
2670 		break;
2671 
2672 	case NS_GID_PN:
2673 		ct->ct_resp_alloc_size = ct->ct_resp_size = 20;
2674 		ct->ct_resp_payload = (uint8_t *)kmem_zalloc(ct->ct_resp_size,
2675 		    KM_SLEEP);
2676 
2677 		ct->ct_req_size = ct->ct_req_alloc_size = 24;
2678 		p = ct->ct_req_payload = (uint8_t *)kmem_zalloc(ct->ct_req_size,
2679 		    KM_SLEEP);
2680 
2681 		bcopy(query_rp->rp_pwwn, p + 16, 8);
2682 		break;
2683 
2684 	default:
2685 		/* CONSTCOND */
2686 		ASSERT(0);
2687 	}
2688 
2689 	FCT_FILL_CTIU_PREAMPLE(p, ctop);
2690 	return (cmd);
2691 }
2692 
2693 /*
2694  * Cmd can only be solicited CT/ELS. They will be dispatched to the discovery
2695  * queue eventually too.
2696  * We queue solicited cmds here to track solicited cmds and to take full use
2697  * of single thread mechanism.
2698  * But in current implmentation, we don't use  this mechanism on SOL_CT, PLOGI.
2699  * To avoid to interrupt current flow, ICMD_IN_SOLCMD_QUEUE is used here.
2700  */
2701 void
2702 fct_post_to_solcmd_queue(fct_local_port_t *port, fct_cmd_t *cmd)
2703 {
2704 	fct_i_local_port_t	*iport	= (fct_i_local_port_t *)
2705 	    port->port_fct_private;
2706 	fct_i_cmd_t *icmd		= (fct_i_cmd_t *)cmd->cmd_fct_private;
2707 
2708 	mutex_enter(&iport->iport_worker_lock);
2709 	icmd->icmd_solcmd_next = iport->iport_solcmd_queue;
2710 	iport->iport_solcmd_queue = icmd;
2711 	atomic_or_32(&icmd->icmd_flags, ICMD_IN_SOLCMD_QUEUE | ICMD_SOLCMD_NEW);
2712 	if (IS_WORKER_SLEEPING(iport)) {
2713 		cv_signal(&iport->iport_worker_cv);
2714 	}
2715 	mutex_exit(&iport->iport_worker_lock);
2716 }
2717 
2718 /* ARGSUSED */
2719 void
2720 fct_event_handler(stmf_local_port_t *lport, int eventid, void *arg,
2721     uint32_t flags)
2722 {
2723 	fct_local_port_t	*port  = (fct_local_port_t *)
2724 	    lport->lport_port_private;
2725 	fct_i_local_port_t	*iport = (fct_i_local_port_t *)
2726 	    port->port_fct_private;
2727 	stmf_scsi_session_t	*ss;
2728 	fct_i_remote_port_t	*irp;
2729 
2730 	switch (eventid) {
2731 	case LPORT_EVENT_INITIAL_LUN_MAPPED:
2732 		ss = (stmf_scsi_session_t *)arg;
2733 		irp = (fct_i_remote_port_t *)ss->ss_port_private;
2734 		stmf_trace(iport->iport_alias,
2735 		    "Initial LUN mapped to session ss-%p, irp-%p", ss, irp);
2736 		break;
2737 
2738 	default:
2739 		stmf_trace(iport->iport_alias,
2740 		    "Unknown event received, %d", eventid);
2741 	}
2742 }
2743 
2744 void
2745 fct_send_cmd_done(fct_cmd_t *cmd, fct_status_t s, uint32_t ioflags)
2746 {
2747 	/* XXX For now just call send_resp_done() */
2748 	fct_send_response_done(cmd, s, ioflags);
2749 }
2750 
2751 void
2752 fct_cmd_fca_aborted(fct_cmd_t *cmd, fct_status_t s, uint32_t ioflags)
2753 {
2754 	fct_i_cmd_t		*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2755 	char			info[160];
2756 	unsigned long long	st;
2757 
2758 	st = s;	/* To make gcc happy */
2759 	ASSERT(icmd->icmd_flags & ICMD_BEING_ABORTED);
2760 	if ((((s != FCT_ABORT_SUCCESS) && (s != FCT_NOT_FOUND))) ||
2761 	    ((ioflags & FCT_IOF_FCA_DONE) == 0)) {
2762 		(void) snprintf(info, 160, "fct_cmd_fca_aborted: cmd-%p, "
2763 		    "s-%llx, iofalgs-%x", (void *)cmd, st, ioflags);
2764 		info[159] = 0;
2765 		(void) fct_port_shutdown(cmd->cmd_port,
2766 		    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
2767 		return;
2768 	}
2769 
2770 	atomic_and_32(&icmd->icmd_flags, ~ICMD_KNOWN_TO_FCA);
2771 	/* For non FCP Rest of the work is done by the terminator */
2772 	/* For FCP stuff just call stmf */
2773 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
2774 		stmf_task_lport_aborted((scsi_task_t *)cmd->cmd_specific,
2775 		    s, STMF_IOF_LPORT_DONE);
2776 	}
2777 }
2778 
2779 /*
2780  * FCA drivers will use it, when they want to abort some FC transactions
2781  * due to lack of resource.
2782  */
2783 uint16_t
2784 fct_get_rp_handle(fct_local_port_t *port, uint32_t rportid)
2785 {
2786 	fct_i_remote_port_t	*irp;
2787 
2788 	irp = fct_portid_to_portptr(
2789 	    (fct_i_local_port_t *)(port->port_fct_private), rportid);
2790 	if (irp == NULL) {
2791 		return (0xFFFF);
2792 	} else {
2793 		return (irp->irp_rp->rp_handle);
2794 	}
2795 }
2796 
2797 fct_cmd_t *
2798 fct_handle_to_cmd(fct_local_port_t *port, uint32_t fct_handle)
2799 {
2800 	fct_cmd_slot_t *slot;
2801 	uint16_t ndx;
2802 
2803 	if (!CMD_HANDLE_VALID(fct_handle))
2804 		return (NULL);
2805 	if ((ndx = CMD_HANDLE_SLOT_INDEX(fct_handle)) >= port->port_max_xchges)
2806 		return (NULL);
2807 
2808 	slot = &((fct_i_local_port_t *)port->port_fct_private)->iport_cmd_slots[
2809 	    ndx];
2810 
2811 	if ((slot->slot_uniq_cntr | 0x80) != (fct_handle >> 24))
2812 		return (NULL);
2813 	return (slot->slot_cmd->icmd_cmd);
2814 }
2815 
2816 void
2817 fct_queue_scsi_task_for_termination(fct_cmd_t *cmd, fct_status_t s)
2818 {
2819 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2820 
2821 	uint32_t old, new;
2822 
2823 	do {
2824 		old = icmd->icmd_flags;
2825 		if ((old & (ICMD_BEING_ABORTED | ICMD_KNOWN_TO_FCA)) !=
2826 		    ICMD_KNOWN_TO_FCA)
2827 			return;
2828 		new = old | ICMD_BEING_ABORTED;
2829 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
2830 	stmf_abort(STMF_QUEUE_TASK_ABORT, (scsi_task_t *)cmd->cmd_specific,
2831 	    s, NULL);
2832 }
2833 
2834 void
2835 fct_fill_abts_acc(fct_cmd_t *cmd)
2836 {
2837 	fct_rcvd_abts_t *abts = (fct_rcvd_abts_t *)cmd->cmd_specific;
2838 	uint8_t *p;
2839 
2840 	abts->abts_resp_rctl = BLS_OP_BA_ACC;
2841 	p = abts->abts_resp_payload;
2842 	bzero(p, 12);
2843 	*((uint16_t *)(p+4)) = BE_16(cmd->cmd_oxid);
2844 	*((uint16_t *)(p+6)) = BE_16(cmd->cmd_rxid);
2845 	p[10] = p[11] = 0xff;
2846 }
2847 
2848 void
2849 fct_handle_rcvd_abts(fct_cmd_t *cmd)
2850 {
2851 	char			info[80];
2852 	fct_local_port_t	*port = cmd->cmd_port;
2853 	fct_i_local_port_t	*iport =
2854 	    (fct_i_local_port_t *)port->port_fct_private;
2855 	fct_i_cmd_t		*icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2856 	fct_i_remote_port_t	*irp;
2857 	fct_cmd_t		*c = NULL;
2858 	fct_i_cmd_t		*ic = NULL;
2859 	int			found = 0;
2860 	int			i;
2861 
2862 	icmd->icmd_start_time = ddi_get_lbolt();
2863 	icmd->icmd_flags |= ICMD_KNOWN_TO_FCA;
2864 
2865 	rw_enter(&iport->iport_lock, RW_WRITER);
2866 	/* Make sure local port is sane */
2867 	if ((iport->iport_link_state & S_LINK_ONLINE) == 0) {
2868 		rw_exit(&iport->iport_lock);
2869 		stmf_trace(iport->iport_alias, "ABTS not posted becasue"
2870 		    "port state was %x", iport->iport_link_state);
2871 		fct_queue_cmd_for_termination(cmd, FCT_LOCAL_PORT_OFFLINE);
2872 		return;
2873 	}
2874 
2875 	if (cmd->cmd_rp_handle == FCT_HANDLE_NONE)
2876 		irp = fct_portid_to_portptr(iport, cmd->cmd_rportid);
2877 	else if (cmd->cmd_rp_handle < port->port_max_logins)
2878 		irp = iport->iport_rp_slots[cmd->cmd_rp_handle];
2879 	else
2880 		irp = NULL;
2881 	if (irp == NULL) {
2882 		/* XXX Throw a logout to the initiator */
2883 		rw_exit(&iport->iport_lock);
2884 		stmf_trace(iport->iport_alias, "ABTS received from"
2885 		    " %x without a session", cmd->cmd_rportid);
2886 		fct_queue_cmd_for_termination(cmd, FCT_NOT_LOGGED_IN);
2887 		return;
2888 	}
2889 
2890 	DTRACE_FC_3(abts__receive,
2891 	    fct_cmd_t, cmd,
2892 	    fct_local_port_t, port,
2893 	    fct_i_remote_port_t, irp);
2894 
2895 	cmd->cmd_rp = irp->irp_rp;
2896 
2897 	/*
2898 	 * No need to allocate an xchg resource. ABTSes use the same
2899 	 * xchg resource as the cmd they are aborting.
2900 	 */
2901 	rw_enter(&irp->irp_lock, RW_WRITER);
2902 	mutex_enter(&iport->iport_worker_lock);
2903 	/* Lets find the command first */
2904 	for (i = 0; i < port->port_max_xchges; i++) {
2905 		if ((ic = iport->iport_cmd_slots[i].slot_cmd) == NULL)
2906 			continue;
2907 		if ((ic->icmd_flags & ICMD_KNOWN_TO_FCA) == 0)
2908 			continue;
2909 		c = ic->icmd_cmd;
2910 		if (!CMD_HANDLE_VALID(c->cmd_handle))
2911 			continue;
2912 		if ((c->cmd_rportid != cmd->cmd_rportid) ||
2913 		    (c->cmd_oxid != cmd->cmd_oxid))
2914 			continue;
2915 		/* Found the command */
2916 		found = 1;
2917 		break;
2918 	}
2919 	if (!found) {
2920 		mutex_exit(&iport->iport_worker_lock);
2921 		rw_exit(&irp->irp_lock);
2922 		rw_exit(&iport->iport_lock);
2923 		/* Dont even bother queueing it. Just respond */
2924 		fct_fill_abts_acc(cmd);
2925 		if (port->port_send_cmd_response(cmd,
2926 		    FCT_IOF_FORCE_FCA_DONE) != FCT_SUCCESS) {
2927 			/*
2928 			 * XXX Throw HBA fatal error event
2929 			 * Later shutdown svc will terminate the ABTS in the end
2930 			 */
2931 			(void) snprintf(info, 80,
2932 			    "fct_handle_rcvd_abts: iport-%p, "
2933 			    "ABTS_ACC port_send_cmd_response failed",
2934 			    (void *)iport);
2935 			info[79] = 0;
2936 			(void) fct_port_shutdown(iport->iport_port,
2937 			    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET, info);
2938 		} else {
2939 			fct_cmd_free(cmd);
2940 		}
2941 		return;
2942 	}
2943 
2944 	/* Check if this an abts retry */
2945 	if (c->cmd_link && (ic->icmd_flags & ICMD_ABTS_RECEIVED)) {
2946 		/* Kill this abts. */
2947 		fct_q_for_termination_lock_held(iport, icmd, FCT_ABORTED);
2948 		if (IS_WORKER_SLEEPING(iport))
2949 			cv_signal(&iport->iport_worker_cv);
2950 		mutex_exit(&iport->iport_worker_lock);
2951 		rw_exit(&irp->irp_lock);
2952 		rw_exit(&iport->iport_lock);
2953 		return;
2954 	}
2955 	c->cmd_link = cmd;
2956 	atomic_or_32(&ic->icmd_flags, ICMD_ABTS_RECEIVED);
2957 	cmd->cmd_link = c;
2958 	mutex_exit(&iport->iport_worker_lock);
2959 	rw_exit(&irp->irp_lock);
2960 	fct_queue_cmd_for_termination(c, FCT_ABTS_RECEIVED);
2961 	rw_exit(&iport->iport_lock);
2962 }
2963 
2964 void
2965 fct_queue_cmd_for_termination(fct_cmd_t *cmd, fct_status_t s)
2966 {
2967 	fct_local_port_t *port = cmd->cmd_port;
2968 	fct_i_local_port_t *iport = (fct_i_local_port_t *)
2969 	    port->port_fct_private;
2970 	fct_i_cmd_t *icmd = (fct_i_cmd_t *)cmd->cmd_fct_private;
2971 
2972 	if (cmd->cmd_type == FCT_CMD_FCP_XCHG) {
2973 		fct_queue_scsi_task_for_termination(cmd, s);
2974 		return;
2975 	}
2976 	mutex_enter(&iport->iport_worker_lock);
2977 	fct_q_for_termination_lock_held(iport, icmd, s);
2978 	if (IS_WORKER_SLEEPING(iport))
2979 		cv_signal(&iport->iport_worker_cv);
2980 	mutex_exit(&iport->iport_worker_lock);
2981 }
2982 
2983 /*
2984  * This function will not be called for SCSI CMDS
2985  */
2986 void
2987 fct_q_for_termination_lock_held(fct_i_local_port_t *iport, fct_i_cmd_t *icmd,
2988 		fct_status_t s)
2989 {
2990 	uint32_t old, new;
2991 	fct_i_cmd_t **ppicmd;
2992 
2993 	do {
2994 		old = icmd->icmd_flags;
2995 		if (old & ICMD_BEING_ABORTED)
2996 			return;
2997 		new = old | ICMD_BEING_ABORTED;
2998 	} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
2999 
3000 	icmd->icmd_start_time = ddi_get_lbolt();
3001 	icmd->icmd_cmd->cmd_comp_status = s;
3002 
3003 	icmd->icmd_next = NULL;
3004 	for (ppicmd = &(iport->iport_abort_queue); *ppicmd != NULL;
3005 	    ppicmd = &((*ppicmd)->icmd_next))
3006 		;
3007 
3008 	*ppicmd = icmd;
3009 }
3010 
3011 /*
3012  * For those cmds, for which we called fca_abort but it has not yet completed,
3013  * reset the FCA_ABORT_CALLED flag, so that abort can be called again.
3014  * This is done after a FCA offline. The reason is that after offline, the
3015  * firmware is not running so abort will never complete. But if we call it
3016  * again, the FCA will detect that it is not offline and it will
3017  * not call the firmware at all. Most likely it will abort in a synchronous
3018  * manner i.e. return FCT_ABORT_SUCCESS or FCT_NOT_FOUND.
3019  */
3020 void
3021 fct_reset_flag_abort_called(fct_i_local_port_t *iport)
3022 {
3023 	fct_i_cmd_t *icmd;
3024 	uint32_t old, new;
3025 	int i, do_clear;
3026 
3027 	ASSERT(mutex_owned(&iport->iport_worker_lock));
3028 	mutex_exit(&iport->iport_worker_lock);
3029 	rw_enter(&iport->iport_lock, RW_WRITER);
3030 	mutex_enter(&iport->iport_worker_lock);
3031 
3032 	for (i = 0; i < iport->iport_port->port_max_xchges; i++) {
3033 		if (iport->iport_cmd_slots[i].slot_cmd == NULL)
3034 			continue;
3035 
3036 		icmd = iport->iport_cmd_slots[i].slot_cmd;
3037 
3038 		do {
3039 			old = new = icmd->icmd_flags;
3040 			if ((old & (ICMD_KNOWN_TO_FCA |
3041 			    ICMD_FCA_ABORT_CALLED)) == (ICMD_KNOWN_TO_FCA |
3042 			    ICMD_FCA_ABORT_CALLED)) {
3043 				new &= ~ICMD_FCA_ABORT_CALLED;
3044 				do_clear = 1;
3045 			} else {
3046 				do_clear = 0;
3047 				break;
3048 			}
3049 		} while (atomic_cas_32(&icmd->icmd_flags, old, new) != old);
3050 		if (do_clear &&
3051 		    (icmd->icmd_cmd->cmd_type == FCT_CMD_FCP_XCHG)) {
3052 			stmf_abort(STMF_REQUEUE_TASK_ABORT_LPORT,
3053 			    icmd->icmd_cmd->cmd_specific, 0, NULL);
3054 		}
3055 	}
3056 
3057 	rw_exit(&iport->iport_lock);
3058 }
3059 
3060 /*
3061  * Modify the irp_deregister_timer such that the ports start deregistering
3062  * quickly.
3063  */
3064 void
3065 fct_irp_deregister_speedup(fct_i_local_port_t *iport)
3066 {
3067 	fct_i_remote_port_t *irp;
3068 	int i;
3069 
3070 	if (!iport->iport_nrps)
3071 		return;
3072 
3073 	for (i = 0; i < rportid_table_size; i++) {
3074 		irp = iport->iport_rp_tb[i];
3075 		while (irp) {
3076 			irp->irp_deregister_timer = ddi_get_lbolt() - 1;
3077 			irp = irp->irp_next;
3078 		}
3079 	}
3080 }
3081 
3082 disc_action_t
3083 fct_handle_port_offline(fct_i_local_port_t *iport)
3084 {
3085 	if (iport->iport_offline_prstate == FCT_OPR_START) {
3086 		fct_reset_flag_abort_called(iport);
3087 		iport->iport_offline_prstate = FCT_OPR_CMD_CLEANUP_WAIT;
3088 		/* fct_ctl has already submitted a link offline event */
3089 		return (DISC_ACTION_DELAY_RESCAN);
3090 	}
3091 	if (iport->iport_offline_prstate == FCT_OPR_CMD_CLEANUP_WAIT) {
3092 		if (iport->iport_link_state != PORT_STATE_LINK_DOWN)
3093 			return (DISC_ACTION_DELAY_RESCAN);
3094 		/*
3095 		 * All I/Os have been killed at this time. Lets speedup
3096 		 * the port deregister process.
3097 		 */
3098 		mutex_exit(&iport->iport_worker_lock);
3099 		rw_enter(&iport->iport_lock, RW_WRITER);
3100 		fct_irp_deregister_speedup(iport);
3101 		rw_exit(&iport->iport_lock);
3102 		mutex_enter(&iport->iport_worker_lock);
3103 		iport->iport_offline_prstate = FCT_OPR_INT_CLEANUP_WAIT;
3104 		return (DISC_ACTION_RESCAN);
3105 	}
3106 	if (iport->iport_offline_prstate == FCT_OPR_INT_CLEANUP_WAIT) {
3107 		stmf_change_status_t st;
3108 
3109 		if (iport->iport_solcmd_queue) {
3110 			return (DISC_ACTION_DELAY_RESCAN);
3111 		}
3112 
3113 		if (iport->iport_nrps) {
3114 			/*
3115 			 * A port logout may have gone when implicit logo all
3116 			 * was retried. So do the port speedup again here.
3117 			 */
3118 			mutex_exit(&iport->iport_worker_lock);
3119 			rw_enter(&iport->iport_lock, RW_WRITER);
3120 			fct_irp_deregister_speedup(iport);
3121 			rw_exit(&iport->iport_lock);
3122 			mutex_enter(&iport->iport_worker_lock);
3123 			return (DISC_ACTION_DELAY_RESCAN);
3124 		}
3125 
3126 		if (iport->iport_event_head != NULL) {
3127 			return (DISC_ACTION_DELAY_RESCAN);
3128 		}
3129 
3130 		st.st_completion_status = STMF_SUCCESS;
3131 		st.st_additional_info = NULL;
3132 		iport->iport_offline_prstate = FCT_OPR_DONE;
3133 		iport->iport_state = FCT_STATE_OFFLINE;
3134 		mutex_exit(&iport->iport_worker_lock);
3135 		(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE_COMPLETE,
3136 		    iport->iport_port->port_lport, &st);
3137 		mutex_enter(&iport->iport_worker_lock);
3138 		return (DISC_ACTION_DELAY_RESCAN);
3139 	}
3140 
3141 	/* NOTREACHED */
3142 	return (0);
3143 }
3144 
3145 /*
3146  * See stmf.h for information on rflags. Additional info is just a text
3147  * description of the reason for this call. Additional_info can be NULL.
3148  * Also the caller can declare additional info on the stack. stmf_ctl
3149  * makes a copy of it before returning.
3150  */
3151 fct_status_t
3152 fct_port_initialize(fct_local_port_t *port, uint32_t rflags,
3153 				char *additional_info)
3154 {
3155 	stmf_state_change_info_t st;
3156 
3157 	st.st_rflags = rflags;
3158 	st.st_additional_info = additional_info;
3159 	stmf_trace(NULL, "fct_port_initialize: port-%p, %s", port,
3160 	    additional_info? additional_info : "no more information");
3161 	return (stmf_ctl(STMF_CMD_LPORT_ONLINE, port->port_lport, &st));
3162 }
3163 
3164 fct_status_t
3165 fct_port_shutdown(fct_local_port_t *port, uint32_t rflags,
3166 				char *additional_info)
3167 {
3168 	stmf_state_change_info_t st;
3169 
3170 	st.st_rflags = rflags;
3171 	st.st_additional_info = additional_info;
3172 	stmf_trace(NULL, "fct_port_shutdown: port-%p, %s", port,
3173 	    additional_info? additional_info : "no more information");
3174 	return (stmf_ctl(STMF_CMD_LPORT_OFFLINE, port->port_lport, &st));
3175 }
3176 
3177 /*
3178  * Called by worker thread. The aim is to terminate the command
3179  * using whatever means it takes.
3180  * Called with worker lock held.
3181  */
3182 disc_action_t
3183 fct_cmd_terminator(fct_i_local_port_t *iport)
3184 {
3185 	char			info[80];
3186 	clock_t			endtime;
3187 	fct_i_cmd_t		**ppicmd;
3188 	fct_i_cmd_t		*icmd;
3189 	fct_cmd_t		*cmd;
3190 	fct_local_port_t	*port = iport->iport_port;
3191 	disc_action_t		ret = DISC_ACTION_NO_WORK;
3192 	fct_status_t		abort_ret;
3193 	int			fca_done, fct_done, cmd_implicit = 0;
3194 	int			flags;
3195 	unsigned long long	st;
3196 
3197 	/* Lets Limit each run to 20ms max. */
3198 	endtime = ddi_get_lbolt() + drv_usectohz(20000);
3199 
3200 	/* Start from where we left off last time */
3201 	if (iport->iport_ppicmd_term) {
3202 		ppicmd = iport->iport_ppicmd_term;
3203 		iport->iport_ppicmd_term = NULL;
3204 	} else {
3205 		ppicmd = &iport->iport_abort_queue;
3206 	}
3207 
3208 	/*
3209 	 * Once a command gets on discovery queue, this is the only thread
3210 	 * which can access it. So no need for the lock here.
3211 	 */
3212 	mutex_exit(&iport->iport_worker_lock);
3213 
3214 	while ((icmd = *ppicmd) != NULL) {
3215 		cmd = icmd->icmd_cmd;
3216 
3217 		/* Always remember that cmd->cmd_rp can be NULL */
3218 		if ((icmd->icmd_flags & (ICMD_KNOWN_TO_FCA |
3219 		    ICMD_FCA_ABORT_CALLED)) == ICMD_KNOWN_TO_FCA) {
3220 			atomic_or_32(&icmd->icmd_flags, ICMD_FCA_ABORT_CALLED);
3221 			if (CMD_HANDLE_VALID(cmd->cmd_handle))
3222 				flags = 0;
3223 			else
3224 				flags = FCT_IOF_FORCE_FCA_DONE;
3225 			abort_ret = port->port_abort_cmd(port, cmd, flags);
3226 			if ((abort_ret != FCT_SUCCESS) &&
3227 			    (abort_ret != FCT_ABORT_SUCCESS) &&
3228 			    (abort_ret != FCT_NOT_FOUND)) {
3229 				if (flags & FCT_IOF_FORCE_FCA_DONE) {
3230 					/*
3231 					 * XXX trigger port fatal,
3232 					 * Abort the termination, and shutdown
3233 					 * svc will trigger fct_cmd_termination
3234 					 * again.
3235 					 */
3236 					(void) snprintf(info, 80,
3237 					    "fct_cmd_terminator:"
3238 					    " iport-%p, port_abort_cmd with "
3239 					    "FORCE_FCA_DONE failed",
3240 					    (void *)iport);
3241 					info[79] = 0;
3242 					(void) fct_port_shutdown(
3243 					    iport->iport_port,
3244 					    STMF_RFLAG_FATAL_ERROR |
3245 					    STMF_RFLAG_RESET, info);
3246 
3247 					mutex_enter(&iport->iport_worker_lock);
3248 					iport->iport_ppicmd_term = ppicmd;
3249 					return (DISC_ACTION_DELAY_RESCAN);
3250 				}
3251 				atomic_and_32(&icmd->icmd_flags,
3252 				    ~ICMD_FCA_ABORT_CALLED);
3253 			} else if ((flags & FCT_IOF_FORCE_FCA_DONE) ||
3254 			    (abort_ret == FCT_ABORT_SUCCESS) ||
3255 			    (abort_ret == FCT_NOT_FOUND)) {
3256 				atomic_and_32(&icmd->icmd_flags,
3257 				    ~ICMD_KNOWN_TO_FCA);
3258 			}
3259 			ret |= DISC_ACTION_DELAY_RESCAN;
3260 		} else if (icmd->icmd_flags & ICMD_IMPLICIT) {
3261 			if (cmd->cmd_type == FCT_CMD_SOL_ELS)
3262 				cmd->cmd_comp_status = FCT_ABORTED;
3263 			atomic_or_32(&icmd->icmd_flags, ICMD_FCA_ABORT_CALLED);
3264 			cmd_implicit = 1;
3265 		}
3266 		if ((icmd->icmd_flags & ICMD_KNOWN_TO_FCA) == 0)
3267 			fca_done = 1;
3268 		else
3269 			fca_done = 0;
3270 		if ((icmd->icmd_flags & ICMD_IN_IRP_QUEUE) == 0)
3271 			fct_done = 1;
3272 		else
3273 			fct_done = 0;
3274 		if ((fca_done || cmd_implicit) && fct_done) {
3275 			mutex_enter(&iport->iport_worker_lock);
3276 			ASSERT(*ppicmd == icmd);
3277 			*ppicmd = (*ppicmd)->icmd_next;
3278 			mutex_exit(&iport->iport_worker_lock);
3279 			if ((cmd->cmd_type == FCT_CMD_RCVD_ELS) ||
3280 			    (cmd->cmd_type == FCT_CMD_RCVD_ABTS)) {
3281 				/* Free the cmd */
3282 				fct_cmd_free(cmd);
3283 			} else if (cmd->cmd_type == FCT_CMD_SOL_ELS) {
3284 				fct_handle_sol_els_completion(iport, icmd);
3285 				if (icmd->icmd_flags & ICMD_IMPLICIT) {
3286 					if (IS_LOGO_ELS(icmd)) {
3287 						/* IMPLICIT LOGO is special */
3288 						fct_cmd_free(cmd);
3289 					}
3290 				}
3291 			} else if (cmd->cmd_type == FCT_CMD_SOL_CT) {
3292 				fct_sol_ct_t *ct = ICMD_TO_CT(icmd);
3293 
3294 				/* Tell the caller that we are done */
3295 				atomic_or_32(&icmd->icmd_flags,
3296 				    ICMD_CMD_COMPLETE);
3297 				if (fct_netbuf_to_value(
3298 				    ct->ct_req_payload + 8, 2) == NS_GID_PN) {
3299 					fct_i_remote_port_t *irp;
3300 
3301 					rw_enter(&iport->iport_lock, RW_READER);
3302 					irp = fct_lookup_irp_by_portwwn(iport,
3303 					    ct->ct_req_payload + 16);
3304 
3305 					if (irp) {
3306 						atomic_and_32(&irp->irp_flags,
3307 						    ~IRP_RSCN_QUEUED);
3308 					}
3309 					rw_exit(&iport->iport_lock);
3310 				}
3311 			} else {
3312 				ASSERT(0);
3313 			}
3314 		} else {
3315 			clock_t	timeout_ticks;
3316 			if (port->port_fca_abort_timeout)
3317 				timeout_ticks = drv_usectohz(
3318 				    port->port_fca_abort_timeout*1000);
3319 			else
3320 				/* 10 seconds by default */
3321 				timeout_ticks = drv_usectohz(10 * 1000000);
3322 			if ((ddi_get_lbolt() >
3323 			    (icmd->icmd_start_time+timeout_ticks)) &&
3324 			    iport->iport_state == FCT_STATE_ONLINE) {
3325 				/* timeout, reset the port */
3326 				char cmd_type[10];
3327 				if (cmd->cmd_type == FCT_CMD_RCVD_ELS ||
3328 				    cmd->cmd_type == FCT_CMD_SOL_ELS) {
3329 					fct_els_t *els = cmd->cmd_specific;
3330 					(void) snprintf(cmd_type,
3331 					    sizeof (cmd_type), "%x.%x",
3332 					    cmd->cmd_type,
3333 					    els->els_req_payload[0]);
3334 				} else if (cmd->cmd_type == FCT_CMD_SOL_CT) {
3335 					fct_sol_ct_t *ct = cmd->cmd_specific;
3336 					(void) snprintf(cmd_type,
3337 					    sizeof (cmd_type), "%x.%02x%02x",
3338 					    cmd->cmd_type,
3339 					    ct->ct_req_payload[8],
3340 					    ct->ct_req_payload[9]);
3341 				} else {
3342 					cmd_type[0] = 0;
3343 				}
3344 				st = cmd->cmd_comp_status;	/* gcc fix */
3345 				(void) snprintf(info, 80, "fct_cmd_terminator:"
3346 				    " iport-%p, cmd_type(0x%s),"
3347 				    " reason(%llx)", (void *)iport, cmd_type,
3348 				    st);
3349 				info[79] = 0;
3350 				(void) fct_port_shutdown(port,
3351 				    STMF_RFLAG_FATAL_ERROR | STMF_RFLAG_RESET,
3352 				    info);
3353 			}
3354 			ppicmd = &((*ppicmd)->icmd_next);
3355 		}
3356 
3357 		if (ddi_get_lbolt() > endtime) {
3358 			mutex_enter(&iport->iport_worker_lock);
3359 			iport->iport_ppicmd_term = ppicmd;
3360 			return (DISC_ACTION_DELAY_RESCAN);
3361 		}
3362 	}
3363 	mutex_enter(&iport->iport_worker_lock);
3364 	if (iport->iport_abort_queue)
3365 		return (DISC_ACTION_DELAY_RESCAN);
3366 	if (ret == DISC_ACTION_NO_WORK)
3367 		return (DISC_ACTION_RESCAN);
3368 	return (ret);
3369 }
3370 
3371 /*
3372  * Send a syslog event for adapter port level events.
3373  */
3374 void
3375 fct_log_local_port_event(fct_local_port_t *port, char *subclass)
3376 {
3377 	nvlist_t *attr_list;
3378 	int port_instance;
3379 
3380 	if (!fct_dip)
3381 		return;
3382 	port_instance = ddi_get_instance(fct_dip);
3383 
3384 	if (nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE,
3385 	    KM_SLEEP) != DDI_SUCCESS) {
3386 		goto alloc_failed;
3387 	}
3388 
3389 	if (nvlist_add_uint32(attr_list, "instance", port_instance)
3390 	    != DDI_SUCCESS) {
3391 		goto error;
3392 	}
3393 
3394 	if (nvlist_add_byte_array(attr_list, "port-wwn",
3395 	    port->port_pwwn, 8) != DDI_SUCCESS) {
3396 		goto error;
3397 	}
3398 
3399 	(void) ddi_log_sysevent(fct_dip, DDI_VENDOR_SUNW, EC_SUNFC,
3400 	    subclass, attr_list, NULL, DDI_SLEEP);
3401 
3402 	nvlist_free(attr_list);
3403 	return;
3404 
3405 error:
3406 	nvlist_free(attr_list);
3407 alloc_failed:
3408 	stmf_trace(((fct_i_local_port_t *)port->port_fct_private)->iport_alias,
3409 	    "Unable to send %s event", subclass);
3410 }
3411 
3412 void
3413 fct_log_remote_port_event(fct_local_port_t *port, char *subclass,
3414     uint8_t *rp_pwwn, uint32_t rp_id)
3415 {
3416 	nvlist_t *attr_list;
3417 	int port_instance;
3418 
3419 	if (!fct_dip)
3420 		return;
3421 	port_instance = ddi_get_instance(fct_dip);
3422 
3423 	if (nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE,
3424 	    KM_SLEEP) != DDI_SUCCESS) {
3425 		goto alloc_failed;
3426 	}
3427 
3428 	if (nvlist_add_uint32(attr_list, "instance", port_instance)
3429 	    != DDI_SUCCESS) {
3430 		goto error;
3431 	}
3432 
3433 	if (nvlist_add_byte_array(attr_list, "port-wwn",
3434 	    port->port_pwwn, 8) != DDI_SUCCESS) {
3435 		goto error;
3436 	}
3437 
3438 	if (nvlist_add_byte_array(attr_list, "target-port-wwn",
3439 	    rp_pwwn, 8) != DDI_SUCCESS) {
3440 		goto error;
3441 	}
3442 
3443 	if (nvlist_add_uint32(attr_list, "target-port-id",
3444 	    rp_id) != DDI_SUCCESS) {
3445 		goto error;
3446 	}
3447 
3448 	(void) ddi_log_sysevent(fct_dip, DDI_VENDOR_SUNW, EC_SUNFC,
3449 	    subclass, attr_list, NULL, DDI_SLEEP);
3450 
3451 	nvlist_free(attr_list);
3452 	return;
3453 
3454 error:
3455 	nvlist_free(attr_list);
3456 alloc_failed:
3457 	stmf_trace(((fct_i_local_port_t *)port->port_fct_private)->iport_alias,
3458 	    "Unable to send %s event", subclass);
3459 }
3460 
3461 uint64_t
3462 fct_netbuf_to_value(uint8_t *buf, uint8_t nbytes)
3463 {
3464 	uint64_t	ret = 0;
3465 	uint8_t		idx = 0;
3466 
3467 	do {
3468 		ret |= (buf[idx] << (8 * (nbytes -idx - 1)));
3469 	} while (++idx < nbytes);
3470 
3471 	return (ret);
3472 }
3473 
3474 void
3475 fct_value_to_netbuf(uint64_t value, uint8_t *buf, uint8_t nbytes)
3476 {
3477 	uint8_t		idx = 0;
3478 
3479 	for (idx = 0; idx < nbytes; idx++) {
3480 		buf[idx] = 0xFF & (value >> (8 * (nbytes - idx - 1)));
3481 	}
3482 }
3483 
3484 /*
3485  * from_ptr: ptr to uchar_t array of size WWN_SIZE
3486  * to_ptr: char ptr to string of size WWN_SIZE*2+1
3487  */
3488 void
3489 fct_wwn_to_str(char *to_ptr, const uint8_t *from_ptr)
3490 {
3491 	ASSERT(to_ptr != NULL && from_ptr != NULL);
3492 
3493 	(void) sprintf(to_ptr, "%02x%02x%02x%02x%02x%02x%02x%02x",
3494 	    from_ptr[0], from_ptr[1], from_ptr[2], from_ptr[3],
3495 	    from_ptr[4], from_ptr[5], from_ptr[6], from_ptr[7]);
3496 }
3497 
3498 static int
3499 fct_update_stats(kstat_t *ks, int rw)
3500 {
3501 	fct_i_local_port_t *iport;
3502 	fct_port_stat_t *port_kstat;
3503 	fct_port_link_status_t stat;
3504 	uint32_t	buf_size = sizeof (stat);
3505 	int		ret;
3506 
3507 	if (rw == KSTAT_WRITE)
3508 		return (EACCES);
3509 
3510 	iport = (fct_i_local_port_t *)ks->ks_private;
3511 	port_kstat = (fct_port_stat_t *)ks->ks_data;
3512 
3513 	if (iport->iport_port->port_info == NULL) {
3514 		return (EIO);
3515 	}
3516 	ret = iport->iport_port->port_info(FC_TGT_PORT_RLS,
3517 	    iport->iport_port, NULL, (uint8_t *)&stat, &buf_size);
3518 	if (ret != STMF_SUCCESS) {
3519 		return (EIO);
3520 	}
3521 
3522 	port_kstat->link_failure_cnt.value.ui32 =
3523 	    stat.LinkFailureCount;
3524 	port_kstat->loss_of_sync_cnt.value.ui32 =
3525 	    stat.LossOfSyncCount;
3526 	port_kstat->loss_of_signals_cnt.value.ui32 =
3527 	    stat.LossOfSignalsCount;
3528 	port_kstat->prim_seq_protocol_err_cnt.value.ui32 =
3529 	    stat.PrimitiveSeqProtocolErrorCount;
3530 	port_kstat->invalid_tx_word_cnt.value.ui32 =
3531 	    stat.InvalidTransmissionWordCount;
3532 	port_kstat->invalid_crc_cnt.value.ui32 =
3533 	    stat.InvalidCRCCount;
3534 
3535 	return (0);
3536 }
3537 
3538 void
3539 fct_init_kstats(fct_i_local_port_t *iport)
3540 {
3541 	kstat_t *ks;
3542 	fct_port_stat_t *port_kstat;
3543 	char	name[256];
3544 
3545 	if (iport->iport_alias)
3546 		(void) sprintf(name, "iport_%s", iport->iport_alias);
3547 	else
3548 		(void) sprintf(name, "iport_%"PRIxPTR"", (uintptr_t)iport);
3549 	ks = kstat_create(FCT_MODULE_NAME, 0, name, "rawdata",
3550 	    KSTAT_TYPE_NAMED, sizeof (fct_port_stat_t) / sizeof (kstat_named_t),
3551 	    0);
3552 
3553 	if (ks == NULL) {
3554 		return;
3555 	}
3556 	port_kstat = (fct_port_stat_t *)ks->ks_data;
3557 
3558 	iport->iport_kstat_portstat = ks;
3559 	kstat_named_init(&port_kstat->link_failure_cnt,
3560 	    "Link_failure_cnt", KSTAT_DATA_UINT32);
3561 	kstat_named_init(&port_kstat->loss_of_sync_cnt,
3562 	    "Loss_of_sync_cnt", KSTAT_DATA_UINT32);
3563 	kstat_named_init(&port_kstat->loss_of_signals_cnt,
3564 	    "Loss_of_signals_cnt", KSTAT_DATA_UINT32);
3565 	kstat_named_init(&port_kstat->prim_seq_protocol_err_cnt,
3566 	    "Prim_seq_protocol_err_cnt", KSTAT_DATA_UINT32);
3567 	kstat_named_init(&port_kstat->invalid_tx_word_cnt,
3568 	    "Invalid_tx_word_cnt", KSTAT_DATA_UINT32);
3569 	kstat_named_init(&port_kstat->invalid_crc_cnt,
3570 	    "Invalid_crc_cnt", KSTAT_DATA_UINT32);
3571 	ks->ks_update = fct_update_stats;
3572 	ks->ks_private = (void *)iport;
3573 	kstat_install(ks);
3574 
3575 }
3576