xref: /illumos-gate/usr/src/uts/common/io/scsi/adapters/pmcs/pmcs_subr.c (revision 37b6b6d4d240f6c7150638ee7c705b2a91f61183)
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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 /*
26  * This file contains various support routines.
27  */
28 
29 #include <sys/scsi/adapters/pmcs/pmcs.h>
30 
31 /*
32  * Local static data
33  */
34 static int tgtmap_stable_usec = MICROSEC;	/* 1 second */
35 static int tgtmap_csync_usec = 10 * MICROSEC;	/* 10 seconds */
36 
37 /*
38  * SAS Topology Configuration
39  */
40 static void pmcs_new_tport(pmcs_hw_t *, pmcs_phy_t *);
41 static void pmcs_configure_expander(pmcs_hw_t *, pmcs_phy_t *, pmcs_iport_t *);
42 
43 static void pmcs_check_expanders(pmcs_hw_t *, pmcs_phy_t *);
44 static void pmcs_check_expander(pmcs_hw_t *, pmcs_phy_t *);
45 static void pmcs_clear_expander(pmcs_hw_t *, pmcs_phy_t *, int);
46 
47 static int pmcs_expander_get_nphy(pmcs_hw_t *, pmcs_phy_t *);
48 static int pmcs_expander_content_discover(pmcs_hw_t *, pmcs_phy_t *,
49     pmcs_phy_t *);
50 
51 static int pmcs_smp_function_result(pmcs_hw_t *, smp_response_frame_t *);
52 static void pmcs_flush_nonio_cmds(pmcs_hw_t *pwp, pmcs_xscsi_t *tgt);
53 static boolean_t pmcs_validate_devid(pmcs_phy_t *, pmcs_phy_t *, uint32_t);
54 static void pmcs_clear_phys(pmcs_hw_t *, pmcs_phy_t *);
55 static int pmcs_configure_new_devices(pmcs_hw_t *, pmcs_phy_t *);
56 static void pmcs_begin_observations(pmcs_hw_t *);
57 static void pmcs_flush_observations(pmcs_hw_t *);
58 static boolean_t pmcs_report_observations(pmcs_hw_t *);
59 static boolean_t pmcs_report_iport_observations(pmcs_hw_t *, pmcs_iport_t *,
60     pmcs_phy_t *);
61 static pmcs_phy_t *pmcs_find_phy_needing_work(pmcs_hw_t *, pmcs_phy_t *);
62 static int pmcs_kill_devices(pmcs_hw_t *, pmcs_phy_t *);
63 static void pmcs_lock_phy_impl(pmcs_phy_t *, int);
64 static void pmcs_unlock_phy_impl(pmcs_phy_t *, int);
65 static pmcs_phy_t *pmcs_clone_phy(pmcs_phy_t *);
66 static boolean_t pmcs_configure_phy(pmcs_hw_t *, pmcs_phy_t *);
67 static void pmcs_reap_dead_phy(pmcs_phy_t *);
68 static pmcs_iport_t *pmcs_get_iport_by_ua(pmcs_hw_t *, char *);
69 static boolean_t pmcs_phy_target_match(pmcs_phy_t *);
70 static void pmcs_iport_active(pmcs_iport_t *);
71 static void pmcs_tgtmap_activate_cb(void *, char *, scsi_tgtmap_tgt_type_t,
72     void **);
73 static boolean_t pmcs_tgtmap_deactivate_cb(void *, char *,
74     scsi_tgtmap_tgt_type_t, void *, scsi_tgtmap_deact_rsn_t);
75 static void pmcs_add_dead_phys(pmcs_hw_t *, pmcs_phy_t *);
76 static void pmcs_get_fw_version(pmcs_hw_t *);
77 static int pmcs_get_time_stamp(pmcs_hw_t *, uint64_t *, hrtime_t *);
78 
79 /*
80  * Often used strings
81  */
82 const char pmcs_nowrk[] = "%s: unable to get work structure";
83 const char pmcs_nomsg[] = "%s: unable to get Inbound Message entry";
84 const char pmcs_timeo[] = "%s: command timed out";
85 
86 extern const ddi_dma_attr_t pmcs_dattr;
87 extern kmutex_t pmcs_trace_lock;
88 
89 /*
90  * Some Initial setup steps.
91  */
92 
93 int
94 pmcs_setup(pmcs_hw_t *pwp)
95 {
96 	uint32_t barval = pwp->mpibar;
97 	uint32_t i, scratch, regbar, regoff, barbar, baroff;
98 	uint32_t new_ioq_depth, ferr = 0;
99 
100 	/*
101 	 * Check current state. If we're not at READY state,
102 	 * we can't go further.
103 	 */
104 	scratch = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1);
105 	if ((scratch & PMCS_MSGU_AAP_STATE_MASK) == PMCS_MSGU_AAP_STATE_ERROR) {
106 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
107 		    "%s: AAP Error State (0x%x)",
108 		    __func__, pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1) &
109 		    PMCS_MSGU_AAP_ERROR_MASK);
110 		pmcs_fm_ereport(pwp, DDI_FM_DEVICE_INVAL_STATE);
111 		ddi_fm_service_impact(pwp->dip, DDI_SERVICE_LOST);
112 		return (-1);
113 	}
114 	if ((scratch & PMCS_MSGU_AAP_STATE_MASK) != PMCS_MSGU_AAP_STATE_READY) {
115 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
116 		    "%s: AAP unit not ready (state 0x%x)",
117 		    __func__, scratch & PMCS_MSGU_AAP_STATE_MASK);
118 		pmcs_fm_ereport(pwp, DDI_FM_DEVICE_INVAL_STATE);
119 		ddi_fm_service_impact(pwp->dip, DDI_SERVICE_LOST);
120 		return (-1);
121 	}
122 
123 	/*
124 	 * Read the offset from the Message Unit scratchpad 0 register.
125 	 * This allows us to read the MPI Configuration table.
126 	 *
127 	 * Check its signature for validity.
128 	 */
129 	baroff = barval;
130 	barbar = barval >> PMCS_MSGU_MPI_BAR_SHIFT;
131 	baroff &= PMCS_MSGU_MPI_OFFSET_MASK;
132 
133 	regoff = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH0);
134 	regbar = regoff >> PMCS_MSGU_MPI_BAR_SHIFT;
135 	regoff &= PMCS_MSGU_MPI_OFFSET_MASK;
136 
137 	if (regoff > baroff) {
138 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
139 		    "%s: bad MPI Table Length (register offset=0x%08x, "
140 		    "passed offset=0x%08x)", __func__, regoff, baroff);
141 		return (-1);
142 	}
143 	if (regbar != barbar) {
144 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
145 		    "%s: bad MPI BAR (register BAROFF=0x%08x, "
146 		    "passed BAROFF=0x%08x)", __func__, regbar, barbar);
147 		return (-1);
148 	}
149 	pwp->mpi_offset = regoff;
150 	if (pmcs_rd_mpi_tbl(pwp, PMCS_MPI_AS) != PMCS_SIGNATURE) {
151 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
152 		    "%s: Bad MPI Configuration Table Signature 0x%x", __func__,
153 		    pmcs_rd_mpi_tbl(pwp, PMCS_MPI_AS));
154 		return (-1);
155 	}
156 
157 	if (pmcs_rd_mpi_tbl(pwp, PMCS_MPI_IR) != PMCS_MPI_REVISION1) {
158 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
159 		    "%s: Bad MPI Configuration Revision 0x%x", __func__,
160 		    pmcs_rd_mpi_tbl(pwp, PMCS_MPI_IR));
161 		return (-1);
162 	}
163 
164 	/*
165 	 * Generate offsets for the General System, Inbound Queue Configuration
166 	 * and Outbound Queue configuration tables. This way the macros to
167 	 * access those tables will work correctly.
168 	 */
169 	pwp->mpi_gst_offset =
170 	    pwp->mpi_offset + pmcs_rd_mpi_tbl(pwp, PMCS_MPI_GSTO);
171 	pwp->mpi_iqc_offset =
172 	    pwp->mpi_offset + pmcs_rd_mpi_tbl(pwp, PMCS_MPI_IQCTO);
173 	pwp->mpi_oqc_offset =
174 	    pwp->mpi_offset + pmcs_rd_mpi_tbl(pwp, PMCS_MPI_OQCTO);
175 
176 	pmcs_get_fw_version(pwp);
177 
178 	pwp->max_cmd = pmcs_rd_mpi_tbl(pwp, PMCS_MPI_MOIO);
179 	pwp->max_dev = pmcs_rd_mpi_tbl(pwp, PMCS_MPI_INFO0) >> 16;
180 
181 	pwp->max_iq = PMCS_MNIQ(pmcs_rd_mpi_tbl(pwp, PMCS_MPI_INFO1));
182 	pwp->max_oq = PMCS_MNOQ(pmcs_rd_mpi_tbl(pwp, PMCS_MPI_INFO1));
183 	pwp->nphy = PMCS_NPHY(pmcs_rd_mpi_tbl(pwp, PMCS_MPI_INFO1));
184 	if (pwp->max_iq <= PMCS_NIQ) {
185 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
186 		    "%s: not enough Inbound Queues supported "
187 		    "(need %d, max_oq=%d)", __func__, pwp->max_iq, PMCS_NIQ);
188 		return (-1);
189 	}
190 	if (pwp->max_oq <= PMCS_NOQ) {
191 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
192 		    "%s: not enough Outbound Queues supported "
193 		    "(need %d, max_oq=%d)", __func__, pwp->max_oq, PMCS_NOQ);
194 		return (-1);
195 	}
196 	if (pwp->nphy == 0) {
197 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
198 		    "%s: zero phys reported", __func__);
199 		return (-1);
200 	}
201 	if (PMCS_HPIQ(pmcs_rd_mpi_tbl(pwp, PMCS_MPI_INFO1))) {
202 		pwp->hipri_queue = (1 << PMCS_IQ_OTHER);
203 	}
204 
205 
206 	for (i = 0; i < pwp->nphy; i++) {
207 		PMCS_MPI_EVQSET(pwp, PMCS_OQ_EVENTS, i);
208 		PMCS_MPI_NCQSET(pwp, PMCS_OQ_EVENTS, i);
209 	}
210 
211 	pmcs_wr_mpi_tbl(pwp, PMCS_MPI_INFO2,
212 	    (PMCS_OQ_EVENTS << GENERAL_EVENT_OQ_SHIFT) |
213 	    (PMCS_OQ_EVENTS << DEVICE_HANDLE_REMOVED_SHIFT));
214 
215 	/*
216 	 * Verify that ioq_depth is valid (> 0 and not so high that it
217 	 * would cause us to overrun the chip with commands).
218 	 */
219 	if (pwp->ioq_depth == 0) {
220 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
221 		    "%s: I/O queue depth set to 0. Setting to %d",
222 		    __func__, PMCS_NQENTRY);
223 		pwp->ioq_depth = PMCS_NQENTRY;
224 	}
225 
226 	if (pwp->ioq_depth < PMCS_MIN_NQENTRY) {
227 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
228 		    "%s: I/O queue depth set too low (%d). Setting to %d",
229 		    __func__, pwp->ioq_depth, PMCS_MIN_NQENTRY);
230 		pwp->ioq_depth = PMCS_MIN_NQENTRY;
231 	}
232 
233 	if (pwp->ioq_depth > (pwp->max_cmd / (PMCS_IO_IQ_MASK + 1))) {
234 		new_ioq_depth = pwp->max_cmd / (PMCS_IO_IQ_MASK + 1);
235 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
236 		    "%s: I/O queue depth set too high (%d). Setting to %d",
237 		    __func__, pwp->ioq_depth, new_ioq_depth);
238 		pwp->ioq_depth = new_ioq_depth;
239 	}
240 
241 	/*
242 	 * Allocate consistent memory for OQs and IQs.
243 	 */
244 	pwp->iqp_dma_attr = pwp->oqp_dma_attr = pmcs_dattr;
245 	pwp->iqp_dma_attr.dma_attr_align =
246 	    pwp->oqp_dma_attr.dma_attr_align = PMCS_QENTRY_SIZE;
247 
248 	/*
249 	 * The Rev C chip has the ability to do PIO to or from consistent
250 	 * memory anywhere in a 64 bit address space, but the firmware is
251 	 * not presently set up to do so.
252 	 */
253 	pwp->iqp_dma_attr.dma_attr_addr_hi =
254 	    pwp->oqp_dma_attr.dma_attr_addr_hi = 0x000000FFFFFFFFFFull;
255 
256 	for (i = 0; i < PMCS_NIQ; i++) {
257 		if (pmcs_dma_setup(pwp, &pwp->iqp_dma_attr,
258 		    &pwp->iqp_acchdls[i],
259 		    &pwp->iqp_handles[i], PMCS_QENTRY_SIZE * pwp->ioq_depth,
260 		    (caddr_t *)&pwp->iqp[i], &pwp->iqaddr[i]) == B_FALSE) {
261 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
262 			    "Failed to setup DMA for iqp[%d]", i);
263 			return (-1);
264 		}
265 		bzero(pwp->iqp[i], PMCS_QENTRY_SIZE * pwp->ioq_depth);
266 	}
267 
268 	for (i = 0; i < PMCS_NOQ; i++) {
269 		if (pmcs_dma_setup(pwp, &pwp->oqp_dma_attr,
270 		    &pwp->oqp_acchdls[i],
271 		    &pwp->oqp_handles[i], PMCS_QENTRY_SIZE * pwp->ioq_depth,
272 		    (caddr_t *)&pwp->oqp[i], &pwp->oqaddr[i]) == B_FALSE) {
273 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
274 			    "Failed to setup DMA for oqp[%d]", i);
275 			return (-1);
276 		}
277 		bzero(pwp->oqp[i], PMCS_QENTRY_SIZE * pwp->ioq_depth);
278 	}
279 
280 	/*
281 	 * Install the IQ and OQ addresses (and null out the rest).
282 	 */
283 	for (i = 0; i < pwp->max_iq; i++) {
284 		pwp->iqpi_offset[i] = pmcs_rd_iqc_tbl(pwp, PMCS_IQPIOFFX(i));
285 		if (i < PMCS_NIQ) {
286 			if (i != PMCS_IQ_OTHER) {
287 				pmcs_wr_iqc_tbl(pwp, PMCS_IQC_PARMX(i),
288 				    pwp->ioq_depth | (PMCS_QENTRY_SIZE << 16));
289 			} else {
290 				pmcs_wr_iqc_tbl(pwp, PMCS_IQC_PARMX(i),
291 				    (1 << 30) | pwp->ioq_depth |
292 				    (PMCS_QENTRY_SIZE << 16));
293 			}
294 			pmcs_wr_iqc_tbl(pwp, PMCS_IQBAHX(i),
295 			    DWORD1(pwp->iqaddr[i]));
296 			pmcs_wr_iqc_tbl(pwp, PMCS_IQBALX(i),
297 			    DWORD0(pwp->iqaddr[i]));
298 			pmcs_wr_iqc_tbl(pwp, PMCS_IQCIBAHX(i),
299 			    DWORD1(pwp->ciaddr+IQ_OFFSET(i)));
300 			pmcs_wr_iqc_tbl(pwp, PMCS_IQCIBALX(i),
301 			    DWORD0(pwp->ciaddr+IQ_OFFSET(i)));
302 		} else {
303 			pmcs_wr_iqc_tbl(pwp, PMCS_IQC_PARMX(i), 0);
304 			pmcs_wr_iqc_tbl(pwp, PMCS_IQBAHX(i), 0);
305 			pmcs_wr_iqc_tbl(pwp, PMCS_IQBALX(i), 0);
306 			pmcs_wr_iqc_tbl(pwp, PMCS_IQCIBAHX(i), 0);
307 			pmcs_wr_iqc_tbl(pwp, PMCS_IQCIBALX(i), 0);
308 		}
309 	}
310 
311 	for (i = 0; i < pwp->max_oq; i++) {
312 		pwp->oqci_offset[i] = pmcs_rd_oqc_tbl(pwp, PMCS_OQCIOFFX(i));
313 		if (i < PMCS_NOQ) {
314 			pmcs_wr_oqc_tbl(pwp, PMCS_OQC_PARMX(i), pwp->ioq_depth |
315 			    (PMCS_QENTRY_SIZE << 16) | OQIEX);
316 			pmcs_wr_oqc_tbl(pwp, PMCS_OQBAHX(i),
317 			    DWORD1(pwp->oqaddr[i]));
318 			pmcs_wr_oqc_tbl(pwp, PMCS_OQBALX(i),
319 			    DWORD0(pwp->oqaddr[i]));
320 			pmcs_wr_oqc_tbl(pwp, PMCS_OQPIBAHX(i),
321 			    DWORD1(pwp->ciaddr+OQ_OFFSET(i)));
322 			pmcs_wr_oqc_tbl(pwp, PMCS_OQPIBALX(i),
323 			    DWORD0(pwp->ciaddr+OQ_OFFSET(i)));
324 			pmcs_wr_oqc_tbl(pwp, PMCS_OQIPARM(i),
325 			    pwp->oqvec[i] << 24);
326 			pmcs_wr_oqc_tbl(pwp, PMCS_OQDICX(i), 0);
327 		} else {
328 			pmcs_wr_oqc_tbl(pwp, PMCS_OQC_PARMX(i), 0);
329 			pmcs_wr_oqc_tbl(pwp, PMCS_OQBAHX(i), 0);
330 			pmcs_wr_oqc_tbl(pwp, PMCS_OQBALX(i), 0);
331 			pmcs_wr_oqc_tbl(pwp, PMCS_OQPIBAHX(i), 0);
332 			pmcs_wr_oqc_tbl(pwp, PMCS_OQPIBALX(i), 0);
333 			pmcs_wr_oqc_tbl(pwp, PMCS_OQIPARM(i), 0);
334 			pmcs_wr_oqc_tbl(pwp, PMCS_OQDICX(i), 0);
335 		}
336 	}
337 
338 	/*
339 	 * Set up logging, if defined.
340 	 */
341 	if (pwp->fwlog) {
342 		uint64_t logdma = pwp->fwaddr;
343 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_MELBAH, DWORD1(logdma));
344 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_MELBAL, DWORD0(logdma));
345 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_MELBS, PMCS_FWLOG_SIZE >> 1);
346 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_MELSEV, pwp->fwlog);
347 		logdma += (PMCS_FWLOG_SIZE >> 1);
348 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_IELBAH, DWORD1(logdma));
349 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_IELBAL, DWORD0(logdma));
350 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_IELBS, PMCS_FWLOG_SIZE >> 1);
351 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_IELSEV, pwp->fwlog);
352 	}
353 
354 	/*
355 	 * Interrupt vectors, outbound queues, and odb_auto_clear
356 	 *
357 	 * MSI/MSI-X:
358 	 * If we got 4 interrupt vectors, we'll assign one to each outbound
359 	 * queue as well as the fatal interrupt, and auto clear can be set
360 	 * for each.
361 	 *
362 	 * If we only got 2 vectors, one will be used for I/O completions
363 	 * and the other for the other two vectors.  In this case, auto_
364 	 * clear can only be set for I/Os, which is fine.  The fatal
365 	 * interrupt will be mapped to the PMCS_FATAL_INTERRUPT bit, which
366 	 * is not an interrupt vector.
367 	 *
368 	 * MSI/MSI-X/INT-X:
369 	 * If we only got 1 interrupt vector, auto_clear must be set to 0,
370 	 * and again the fatal interrupt will be mapped to the
371 	 * PMCS_FATAL_INTERRUPT bit (again, not an interrupt vector).
372 	 */
373 
374 	switch (pwp->int_type) {
375 	case PMCS_INT_MSIX:
376 	case PMCS_INT_MSI:
377 		switch (pwp->intr_cnt) {
378 		case 1:
379 			pmcs_wr_mpi_tbl(pwp, PMCS_MPI_FERR, PMCS_FERRIE |
380 			    (PMCS_FATAL_INTERRUPT << PMCS_FERIV_SHIFT));
381 			pwp->odb_auto_clear = 0;
382 			break;
383 		case 2:
384 			pmcs_wr_mpi_tbl(pwp, PMCS_MPI_FERR, PMCS_FERRIE |
385 			    (PMCS_FATAL_INTERRUPT << PMCS_FERIV_SHIFT));
386 			pwp->odb_auto_clear = (1 << PMCS_FATAL_INTERRUPT) |
387 			    (1 << PMCS_MSIX_IODONE);
388 			break;
389 		case 4:
390 			pmcs_wr_mpi_tbl(pwp, PMCS_MPI_FERR, PMCS_FERRIE |
391 			    (PMCS_MSIX_FATAL << PMCS_FERIV_SHIFT));
392 			pwp->odb_auto_clear = (1 << PMCS_MSIX_FATAL) |
393 			    (1 << PMCS_MSIX_GENERAL) | (1 << PMCS_MSIX_IODONE) |
394 			    (1 << PMCS_MSIX_EVENTS);
395 			break;
396 		}
397 		break;
398 
399 	case PMCS_INT_FIXED:
400 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_FERR,
401 		    PMCS_FERRIE | (PMCS_FATAL_INTERRUPT << PMCS_FERIV_SHIFT));
402 		pwp->odb_auto_clear = 0;
403 		break;
404 	}
405 
406 	/*
407 	 * If the open retry interval is non-zero, set it.
408 	 */
409 	if (pwp->open_retry_interval != 0) {
410 		int phynum;
411 
412 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
413 		    "%s: Setting open retry interval to %d usecs", __func__,
414 		    pwp->open_retry_interval);
415 		for (phynum = 0; phynum < pwp->nphy; phynum ++) {
416 			pmcs_wr_gsm_reg(pwp, OPEN_RETRY_INTERVAL(phynum),
417 			    pwp->open_retry_interval);
418 		}
419 	}
420 
421 	/*
422 	 * Enable Interrupt Reassertion
423 	 * Default Delay 1000us
424 	 */
425 	ferr = pmcs_rd_mpi_tbl(pwp, PMCS_MPI_FERR);
426 	if ((ferr & PMCS_MPI_IRAE) == 0) {
427 		ferr &= ~(PMCS_MPI_IRAU | PMCS_MPI_IRAD_MASK);
428 		pmcs_wr_mpi_tbl(pwp, PMCS_MPI_FERR, ferr | PMCS_MPI_IRAE);
429 	}
430 
431 	pmcs_wr_topunit(pwp, PMCS_OBDB_AUTO_CLR, pwp->odb_auto_clear);
432 	pwp->mpi_table_setup = 1;
433 	return (0);
434 }
435 
436 /*
437  * Start the Message Passing protocol with the PMC chip.
438  */
439 int
440 pmcs_start_mpi(pmcs_hw_t *pwp)
441 {
442 	int i;
443 
444 	pmcs_wr_msgunit(pwp, PMCS_MSGU_IBDB, PMCS_MSGU_IBDB_MPIINI);
445 	for (i = 0; i < 1000; i++) {
446 		if ((pmcs_rd_msgunit(pwp, PMCS_MSGU_IBDB) &
447 		    PMCS_MSGU_IBDB_MPIINI) == 0) {
448 			break;
449 		}
450 		drv_usecwait(1000);
451 	}
452 	if (pmcs_rd_msgunit(pwp, PMCS_MSGU_IBDB) & PMCS_MSGU_IBDB_MPIINI) {
453 		return (-1);
454 	}
455 	drv_usecwait(500000);
456 
457 	/*
458 	 * Check to make sure we got to INIT state.
459 	 */
460 	if (PMCS_MPI_S(pmcs_rd_gst_tbl(pwp, PMCS_GST_BASE)) !=
461 	    PMCS_MPI_STATE_INIT) {
462 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
463 		    "%s: MPI launch failed (GST 0x%x DBCLR 0x%x)", __func__,
464 		    pmcs_rd_gst_tbl(pwp, PMCS_GST_BASE),
465 		    pmcs_rd_msgunit(pwp, PMCS_MSGU_IBDB_CLEAR));
466 		return (-1);
467 	}
468 	return (0);
469 }
470 
471 /*
472  * Stop the Message Passing protocol with the PMC chip.
473  */
474 int
475 pmcs_stop_mpi(pmcs_hw_t *pwp)
476 {
477 	int i;
478 
479 	for (i = 0; i < pwp->max_iq; i++) {
480 		pmcs_wr_iqc_tbl(pwp, PMCS_IQC_PARMX(i), 0);
481 		pmcs_wr_iqc_tbl(pwp, PMCS_IQBAHX(i), 0);
482 		pmcs_wr_iqc_tbl(pwp, PMCS_IQBALX(i), 0);
483 		pmcs_wr_iqc_tbl(pwp, PMCS_IQCIBAHX(i), 0);
484 		pmcs_wr_iqc_tbl(pwp, PMCS_IQCIBALX(i), 0);
485 	}
486 	for (i = 0; i < pwp->max_oq; i++) {
487 		pmcs_wr_oqc_tbl(pwp, PMCS_OQC_PARMX(i), 0);
488 		pmcs_wr_oqc_tbl(pwp, PMCS_OQBAHX(i), 0);
489 		pmcs_wr_oqc_tbl(pwp, PMCS_OQBALX(i), 0);
490 		pmcs_wr_oqc_tbl(pwp, PMCS_OQPIBAHX(i), 0);
491 		pmcs_wr_oqc_tbl(pwp, PMCS_OQPIBALX(i), 0);
492 		pmcs_wr_oqc_tbl(pwp, PMCS_OQIPARM(i), 0);
493 		pmcs_wr_oqc_tbl(pwp, PMCS_OQDICX(i), 0);
494 	}
495 	pmcs_wr_mpi_tbl(pwp, PMCS_MPI_FERR, 0);
496 	pmcs_wr_msgunit(pwp, PMCS_MSGU_IBDB, PMCS_MSGU_IBDB_MPICTU);
497 	for (i = 0; i < 2000; i++) {
498 		if ((pmcs_rd_msgunit(pwp, PMCS_MSGU_IBDB) &
499 		    PMCS_MSGU_IBDB_MPICTU) == 0) {
500 			break;
501 		}
502 		drv_usecwait(1000);
503 	}
504 	if (pmcs_rd_msgunit(pwp, PMCS_MSGU_IBDB) & PMCS_MSGU_IBDB_MPICTU) {
505 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
506 		    "%s: MPI stop failed", __func__);
507 		return (-1);
508 	}
509 	return (0);
510 }
511 
512 /*
513  * Do a sequence of ECHO messages to test for MPI functionality,
514  * all inbound and outbound queue functionality and interrupts.
515  */
516 int
517 pmcs_echo_test(pmcs_hw_t *pwp)
518 {
519 	echo_test_t fred;
520 	struct pmcwork *pwrk;
521 	uint32_t *msg, count;
522 	int iqe = 0, iqo = 0, result, rval = 0;
523 	int iterations;
524 	hrtime_t echo_start, echo_end, echo_total;
525 
526 	ASSERT(pwp->max_cmd > 0);
527 
528 	/*
529 	 * We want iterations to be max_cmd * 3 to ensure that we run the
530 	 * echo test enough times to iterate through every inbound queue
531 	 * at least twice.
532 	 */
533 	iterations = pwp->max_cmd * 3;
534 
535 	echo_total = 0;
536 	count = 0;
537 
538 	while (count < iterations) {
539 		pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, NULL);
540 		if (pwrk == NULL) {
541 			pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL,
542 			    pmcs_nowrk, __func__);
543 			rval = -1;
544 			break;
545 		}
546 
547 		mutex_enter(&pwp->iqp_lock[iqe]);
548 		msg = GET_IQ_ENTRY(pwp, iqe);
549 		if (msg == NULL) {
550 			mutex_exit(&pwp->iqp_lock[iqe]);
551 			pmcs_pwork(pwp, pwrk);
552 			pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL,
553 			    pmcs_nomsg, __func__);
554 			rval = -1;
555 			break;
556 		}
557 
558 		bzero(msg, PMCS_QENTRY_SIZE);
559 
560 		if (iqe == PMCS_IQ_OTHER) {
561 			/* This is on the high priority queue */
562 			msg[0] = LE_32(PMCS_HIPRI(pwp, iqo, PMCIN_ECHO));
563 		} else {
564 			msg[0] = LE_32(PMCS_IOMB_IN_SAS(iqo, PMCIN_ECHO));
565 		}
566 		msg[1] = LE_32(pwrk->htag);
567 		fred.signature = 0xdeadbeef;
568 		fred.count = count;
569 		fred.ptr = &count;
570 		(void) memcpy(&msg[2], &fred, sizeof (fred));
571 		pwrk->state = PMCS_WORK_STATE_ONCHIP;
572 
573 		INC_IQ_ENTRY(pwp, iqe);
574 
575 		echo_start = gethrtime();
576 		DTRACE_PROBE2(pmcs__echo__test__wait__start,
577 		    hrtime_t, echo_start, uint32_t, pwrk->htag);
578 
579 		if (++iqe == PMCS_NIQ) {
580 			iqe = 0;
581 		}
582 		if (++iqo == PMCS_NOQ) {
583 			iqo = 0;
584 		}
585 
586 		WAIT_FOR(pwrk, 250, result);
587 		pmcs_pwork(pwp, pwrk);
588 
589 		echo_end = gethrtime();
590 		DTRACE_PROBE2(pmcs__echo__test__wait__end,
591 		    hrtime_t, echo_end, int, result);
592 		echo_total += (echo_end - echo_start);
593 
594 		if (result) {
595 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
596 			    "%s: command timed out on echo test #%d",
597 			    __func__, count);
598 			rval = -1;
599 			break;
600 		}
601 	}
602 
603 	/*
604 	 * The intr_threshold is adjusted by PMCS_INTR_THRESHOLD in order to
605 	 * remove the overhead of things like the delay in getting signaled
606 	 * for completion.
607 	 */
608 	if (echo_total != 0) {
609 		pwp->io_intr_coal.intr_latency =
610 		    (echo_total / iterations) / 2;
611 		pwp->io_intr_coal.intr_threshold =
612 		    PMCS_INTR_THRESHOLD(PMCS_QUANTUM_TIME_USECS * 1000 /
613 		    pwp->io_intr_coal.intr_latency);
614 	}
615 
616 	return (rval);
617 }
618 
619 /*
620  * Start the (real) phys
621  */
622 int
623 pmcs_start_phy(pmcs_hw_t *pwp, int phynum, int linkmode, int speed)
624 {
625 	int result;
626 	uint32_t *msg;
627 	struct pmcwork *pwrk;
628 	pmcs_phy_t *pptr;
629 	sas_identify_af_t sap;
630 
631 	mutex_enter(&pwp->lock);
632 	pptr = pwp->root_phys + phynum;
633 	if (pptr == NULL) {
634 		mutex_exit(&pwp->lock);
635 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
636 		    "%s: cannot find port %d", __func__, phynum);
637 		return (0);
638 	}
639 
640 	pmcs_lock_phy(pptr);
641 	mutex_exit(&pwp->lock);
642 
643 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
644 	if (pwrk == NULL) {
645 		pmcs_unlock_phy(pptr);
646 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nowrk, __func__);
647 		return (-1);
648 	}
649 
650 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
651 	msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
652 
653 	if (msg == NULL) {
654 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
655 		pmcs_unlock_phy(pptr);
656 		pmcs_pwork(pwp, pwrk);
657 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nomsg, __func__);
658 		return (-1);
659 	}
660 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_EVENTS, PMCIN_PHY_START));
661 	msg[1] = LE_32(pwrk->htag);
662 	msg[2] = LE_32(linkmode | speed | phynum);
663 	bzero(&sap, sizeof (sap));
664 	sap.device_type = SAS_IF_DTYPE_ENDPOINT;
665 	sap.ssp_ini_port = 1;
666 
667 	if (pwp->separate_ports) {
668 		pmcs_wwn2barray(pwp->sas_wwns[phynum], sap.sas_address);
669 	} else {
670 		pmcs_wwn2barray(pwp->sas_wwns[0], sap.sas_address);
671 	}
672 
673 	ASSERT(phynum < SAS2_PHYNUM_MAX);
674 	sap.phy_identifier = phynum & SAS2_PHYNUM_MASK;
675 	(void) memcpy(&msg[3], &sap, sizeof (sas_identify_af_t));
676 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
677 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
678 
679 	pptr->state.prog_min_rate = (lowbit((ulong_t)speed) - 1);
680 	pptr->state.prog_max_rate = (highbit((ulong_t)speed) - 1);
681 	pptr->state.hw_min_rate = PMCS_HW_MIN_LINK_RATE;
682 	pptr->state.hw_max_rate = PMCS_HW_MAX_LINK_RATE;
683 
684 	pmcs_unlock_phy(pptr);
685 	WAIT_FOR(pwrk, 1000, result);
686 	pmcs_pwork(pwp, pwrk);
687 
688 	if (result) {
689 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, pmcs_timeo, __func__);
690 	} else {
691 		mutex_enter(&pwp->lock);
692 		pwp->phys_started |= (1 << phynum);
693 		mutex_exit(&pwp->lock);
694 	}
695 
696 	return (0);
697 }
698 
699 int
700 pmcs_start_phys(pmcs_hw_t *pwp)
701 {
702 	int i, rval;
703 
704 	for (i = 0; i < pwp->nphy; i++) {
705 		if ((pwp->phyid_block_mask & (1 << i)) == 0) {
706 			if (pmcs_start_phy(pwp, i,
707 			    (pwp->phymode << PHY_MODE_SHIFT),
708 			    pwp->physpeed << PHY_LINK_SHIFT)) {
709 				return (-1);
710 			}
711 			if (pmcs_clear_diag_counters(pwp, i)) {
712 				pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
713 				    "%s: failed to reset counters on PHY (%d)",
714 				    __func__, i);
715 			}
716 		}
717 	}
718 
719 	rval = pmcs_get_time_stamp(pwp, &pwp->fw_timestamp, &pwp->hrtimestamp);
720 	if (rval) {
721 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
722 		    "%s: Failed to obtain firmware timestamp", __func__);
723 	} else {
724 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
725 		    "Firmware timestamp: 0x%" PRIx64, pwp->fw_timestamp);
726 	}
727 
728 	return (0);
729 }
730 
731 /*
732  * Called with PHY locked
733  */
734 int
735 pmcs_reset_phy(pmcs_hw_t *pwp, pmcs_phy_t *pptr, uint8_t type)
736 {
737 	uint32_t *msg;
738 	uint32_t iomb[(PMCS_QENTRY_SIZE << 1) >> 2];
739 	const char *mbar;
740 	uint32_t amt;
741 	uint32_t pdevid;
742 	uint32_t stsoff;
743 	uint32_t status;
744 	int result, level, phynum;
745 	struct pmcwork *pwrk;
746 	pmcs_iport_t *iport;
747 	uint32_t htag;
748 
749 	ASSERT(mutex_owned(&pptr->phy_lock));
750 
751 	bzero(iomb, PMCS_QENTRY_SIZE);
752 	phynum = pptr->phynum;
753 	level = pptr->level;
754 	if (level > 0) {
755 		pdevid = pptr->parent->device_id;
756 	} else if ((level == 0) && (pptr->dtype == EXPANDER)) {
757 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, pptr->target,
758 		    "%s: Not resetting HBA PHY @ %s", __func__, pptr->path);
759 		return (0);
760 	}
761 
762 	if (!pptr->iport || !pptr->valid_device_id) {
763 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, pptr->target,
764 		    "%s: Can't reach PHY %s", __func__, pptr->path);
765 		return (0);
766 	}
767 
768 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
769 
770 	if (pwrk == NULL) {
771 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nowrk, __func__);
772 		return (ENOMEM);
773 	}
774 
775 	pwrk->arg = iomb;
776 
777 	/*
778 	 * If level > 0, we need to issue an SMP_REQUEST with a PHY_CONTROL
779 	 * function to do either a link reset or hard reset.  If level == 0,
780 	 * then we do a LOCAL_PHY_CONTROL IOMB to do link/hard reset to the
781 	 * root (local) PHY
782 	 */
783 	if (level) {
784 		stsoff = 2;
785 		iomb[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
786 		    PMCIN_SMP_REQUEST));
787 		iomb[1] = LE_32(pwrk->htag);
788 		iomb[2] = LE_32(pdevid);
789 		iomb[3] = LE_32(40 << SMP_REQUEST_LENGTH_SHIFT);
790 		/*
791 		 * Send SMP PHY CONTROL/HARD or LINK RESET
792 		 */
793 		iomb[4] = BE_32(0x40910000);
794 		iomb[5] = 0;
795 
796 		if (type == PMCS_PHYOP_HARD_RESET) {
797 			mbar = "SMP PHY CONTROL/HARD RESET";
798 			iomb[6] = BE_32((phynum << 16) |
799 			    (PMCS_PHYOP_HARD_RESET << 8));
800 		} else {
801 			mbar = "SMP PHY CONTROL/LINK RESET";
802 			iomb[6] = BE_32((phynum << 16) |
803 			    (PMCS_PHYOP_LINK_RESET << 8));
804 		}
805 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
806 		    "%s: sending %s to %s for phy 0x%x",
807 		    __func__, mbar, pptr->parent->path, pptr->phynum);
808 		amt = 7;
809 	} else {
810 		/*
811 		 * Unlike most other Outbound messages, status for
812 		 * a local phy operation is in DWORD 3.
813 		 */
814 		stsoff = 3;
815 		iomb[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
816 		    PMCIN_LOCAL_PHY_CONTROL));
817 		iomb[1] = LE_32(pwrk->htag);
818 		if (type == PMCS_PHYOP_LINK_RESET) {
819 			mbar = "LOCAL PHY LINK RESET";
820 			iomb[2] = LE_32((PMCS_PHYOP_LINK_RESET << 8) | phynum);
821 		} else {
822 			mbar = "LOCAL PHY HARD RESET";
823 			iomb[2] = LE_32((PMCS_PHYOP_HARD_RESET << 8) | phynum);
824 		}
825 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
826 		    "%s: sending %s to %s", __func__, mbar, pptr->path);
827 		amt = 3;
828 	}
829 
830 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
831 	msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
832 	if (msg == NULL) {
833 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
834 		pmcs_pwork(pwp, pwrk);
835 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nomsg, __func__);
836 		return (ENOMEM);
837 	}
838 	COPY_MESSAGE(msg, iomb, amt);
839 	htag = pwrk->htag;
840 
841 	pmcs_hold_iport(pptr->iport);
842 	iport = pptr->iport;
843 	pmcs_smp_acquire(iport);
844 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
845 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
846 	pmcs_unlock_phy(pptr);
847 	WAIT_FOR(pwrk, 1000, result);
848 	pmcs_pwork(pwp, pwrk);
849 	pmcs_smp_release(iport);
850 	pmcs_rele_iport(iport);
851 	pmcs_lock_phy(pptr);
852 
853 	if (result) {
854 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, pmcs_timeo, __func__);
855 
856 		if (pmcs_abort(pwp, pptr, htag, 0, 0)) {
857 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
858 			    "%s: Unable to issue SMP abort for htag 0x%08x",
859 			    __func__, htag);
860 		} else {
861 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
862 			    "%s: Issuing SMP ABORT for htag 0x%08x",
863 			    __func__, htag);
864 		}
865 		return (EIO);
866 	}
867 	status = LE_32(iomb[stsoff]);
868 
869 	if (status != PMCOUT_STATUS_OK) {
870 		char buf[32];
871 		const char *es =  pmcs_status_str(status);
872 		if (es == NULL) {
873 			(void) snprintf(buf, sizeof (buf), "Status 0x%x",
874 			    status);
875 			es = buf;
876 		}
877 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
878 		    "%s: %s action returned %s for %s", __func__, mbar, es,
879 		    pptr->path);
880 		return (status);
881 	}
882 
883 	return (0);
884 }
885 
886 /*
887  * Stop the (real) phys.  No PHY or softstate locks are required as this only
888  * happens during detach.
889  */
890 void
891 pmcs_stop_phy(pmcs_hw_t *pwp, int phynum)
892 {
893 	int result;
894 	pmcs_phy_t *pptr;
895 	uint32_t *msg;
896 	struct pmcwork *pwrk;
897 
898 	pptr =  pwp->root_phys + phynum;
899 	if (pptr == NULL) {
900 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
901 		    "%s: unable to find port %d", __func__, phynum);
902 		return;
903 	}
904 
905 	if (pwp->phys_started & (1 << phynum)) {
906 		pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
907 
908 		if (pwrk == NULL) {
909 			pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL,
910 			    pmcs_nowrk, __func__);
911 			return;
912 		}
913 
914 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
915 		msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
916 
917 		if (msg == NULL) {
918 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
919 			pmcs_pwork(pwp, pwrk);
920 			pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL,
921 			    pmcs_nomsg, __func__);
922 			return;
923 		}
924 
925 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_EVENTS, PMCIN_PHY_STOP));
926 		msg[1] = LE_32(pwrk->htag);
927 		msg[2] = LE_32(phynum);
928 		pwrk->state = PMCS_WORK_STATE_ONCHIP;
929 		/*
930 		 * Make this unconfigured now.
931 		 */
932 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
933 		WAIT_FOR(pwrk, 1000, result);
934 		pmcs_pwork(pwp, pwrk);
935 		if (result) {
936 			pmcs_prt(pwp, PMCS_PRT_DEBUG,
937 			    pptr, NULL, pmcs_timeo, __func__);
938 		}
939 
940 		pwp->phys_started &= ~(1 << phynum);
941 	}
942 
943 	pptr->configured = 0;
944 }
945 
946 /*
947  * No locks should be required as this is only called during detach
948  */
949 void
950 pmcs_stop_phys(pmcs_hw_t *pwp)
951 {
952 	int i;
953 	for (i = 0; i < pwp->nphy; i++) {
954 		if ((pwp->phyid_block_mask & (1 << i)) == 0) {
955 			pmcs_stop_phy(pwp, i);
956 		}
957 	}
958 }
959 
960 /*
961  * Run SAS_DIAG_EXECUTE with cmd and cmd_desc passed.
962  * 	ERR_CNT_RESET: return status of cmd
963  *	DIAG_REPORT_GET: return value of the counter
964  */
965 int
966 pmcs_sas_diag_execute(pmcs_hw_t *pwp, uint32_t cmd, uint32_t cmd_desc,
967     uint8_t phynum)
968 {
969 	uint32_t htag, *ptr, status, msg[PMCS_MSG_SIZE << 1];
970 	int result;
971 	struct pmcwork *pwrk;
972 
973 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, NULL);
974 	if (pwrk == NULL) {
975 		pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL, pmcs_nowrk, __func__);
976 		return (DDI_FAILURE);
977 	}
978 	pwrk->arg = msg;
979 	htag = pwrk->htag;
980 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_EVENTS, PMCIN_SAS_DIAG_EXECUTE));
981 	msg[1] = LE_32(htag);
982 	msg[2] = LE_32((cmd << PMCS_DIAG_CMD_SHIFT) |
983 	    (cmd_desc << PMCS_DIAG_CMD_DESC_SHIFT) | phynum);
984 
985 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
986 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
987 	if (ptr == NULL) {
988 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
989 		pmcs_pwork(pwp, pwrk);
990 		pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL, pmcs_nomsg, __func__);
991 		return (DDI_FAILURE);
992 	}
993 	COPY_MESSAGE(ptr, msg, 3);
994 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
995 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
996 
997 	WAIT_FOR(pwrk, 1000, result);
998 	pmcs_pwork(pwp, pwrk);
999 	if (result) {
1000 		pmcs_timed_out(pwp, htag, __func__);
1001 		return (DDI_FAILURE);
1002 	}
1003 
1004 	status = LE_32(msg[3]);
1005 
1006 	/* Return for counter reset */
1007 	if (cmd == PMCS_ERR_CNT_RESET)
1008 		return (status);
1009 
1010 	/* Return for counter value */
1011 	if (status) {
1012 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
1013 		    "%s: failed, status (0x%x)", __func__, status);
1014 		return (DDI_FAILURE);
1015 	}
1016 	return (LE_32(msg[4]));
1017 }
1018 
1019 /* Get the current value of the counter for desc on phynum and return it. */
1020 int
1021 pmcs_get_diag_report(pmcs_hw_t *pwp, uint32_t desc, uint8_t phynum)
1022 {
1023 	return (pmcs_sas_diag_execute(pwp, PMCS_DIAG_REPORT_GET, desc, phynum));
1024 }
1025 
1026 /* Clear all of the counters for phynum. Returns the status of the command. */
1027 int
1028 pmcs_clear_diag_counters(pmcs_hw_t *pwp, uint8_t phynum)
1029 {
1030 	uint32_t	cmd = PMCS_ERR_CNT_RESET;
1031 	uint32_t	cmd_desc;
1032 
1033 	cmd_desc = PMCS_INVALID_DWORD_CNT;
1034 	if (pmcs_sas_diag_execute(pwp, cmd, cmd_desc, phynum))
1035 		return (DDI_FAILURE);
1036 
1037 	cmd_desc = PMCS_DISPARITY_ERR_CNT;
1038 	if (pmcs_sas_diag_execute(pwp, cmd, cmd_desc, phynum))
1039 		return (DDI_FAILURE);
1040 
1041 	cmd_desc = PMCS_LOST_DWORD_SYNC_CNT;
1042 	if (pmcs_sas_diag_execute(pwp, cmd, cmd_desc, phynum))
1043 		return (DDI_FAILURE);
1044 
1045 	cmd_desc = PMCS_RESET_FAILED_CNT;
1046 	if (pmcs_sas_diag_execute(pwp, cmd, cmd_desc, phynum))
1047 		return (DDI_FAILURE);
1048 
1049 	return (DDI_SUCCESS);
1050 }
1051 
1052 /*
1053  * Get firmware timestamp
1054  */
1055 static int
1056 pmcs_get_time_stamp(pmcs_hw_t *pwp, uint64_t *fw_ts, hrtime_t *sys_hr_ts)
1057 {
1058 	uint32_t htag, *ptr, msg[PMCS_MSG_SIZE << 1];
1059 	int result;
1060 	struct pmcwork *pwrk;
1061 
1062 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, NULL);
1063 	if (pwrk == NULL) {
1064 		pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL, pmcs_nowrk, __func__);
1065 		return (-1);
1066 	}
1067 	pwrk->arg = msg;
1068 	htag = pwrk->htag;
1069 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_EVENTS, PMCIN_GET_TIME_STAMP));
1070 	msg[1] = LE_32(pwrk->htag);
1071 
1072 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
1073 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
1074 	if (ptr == NULL) {
1075 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
1076 		pmcs_pwork(pwp, pwrk);
1077 		pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL, pmcs_nomsg, __func__);
1078 		return (-1);
1079 	}
1080 	COPY_MESSAGE(ptr, msg, 2);
1081 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
1082 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
1083 
1084 	WAIT_FOR(pwrk, 1000, result);
1085 	pmcs_pwork(pwp, pwrk);
1086 	if (result) {
1087 		pmcs_timed_out(pwp, htag, __func__);
1088 		return (-1);
1089 	}
1090 
1091 	mutex_enter(&pmcs_trace_lock);
1092 	*sys_hr_ts = gethrtime();
1093 	gethrestime(&pwp->sys_timestamp);
1094 	*fw_ts = LE_32(msg[2]) | (((uint64_t)LE_32(msg[3])) << 32);
1095 	mutex_exit(&pmcs_trace_lock);
1096 	return (0);
1097 }
1098 
1099 /*
1100  * Dump all pertinent registers
1101  */
1102 
1103 void
1104 pmcs_register_dump(pmcs_hw_t *pwp)
1105 {
1106 	int i;
1107 	uint32_t val;
1108 
1109 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "pmcs%d: Register dump start",
1110 	    ddi_get_instance(pwp->dip));
1111 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
1112 	    "OBDB (intr): 0x%08x (mask): 0x%08x (clear): 0x%08x",
1113 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_OBDB),
1114 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_OBDB_MASK),
1115 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_OBDB_CLEAR));
1116 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "SCRATCH0: 0x%08x",
1117 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH0));
1118 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "SCRATCH1: 0x%08x",
1119 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1));
1120 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "SCRATCH2: 0x%08x",
1121 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH2));
1122 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "SCRATCH3: 0x%08x",
1123 	    pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH3));
1124 	for (i = 0; i < PMCS_NIQ; i++) {
1125 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "IQ %d: CI %u PI %u",
1126 		    i, pmcs_rd_iqci(pwp, i), pmcs_rd_iqpi(pwp, i));
1127 	}
1128 	for (i = 0; i < PMCS_NOQ; i++) {
1129 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "OQ %d: CI %u PI %u",
1130 		    i, pmcs_rd_oqci(pwp, i), pmcs_rd_oqpi(pwp, i));
1131 	}
1132 	val = pmcs_rd_gst_tbl(pwp, PMCS_GST_BASE);
1133 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
1134 	    "GST TABLE BASE: 0x%08x (STATE=0x%x QF=%d GSTLEN=%d HMI_ERR=0x%x)",
1135 	    val, PMCS_MPI_S(val), PMCS_QF(val), PMCS_GSTLEN(val) * 4,
1136 	    PMCS_HMI_ERR(val));
1137 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "GST TABLE IQFRZ0: 0x%08x",
1138 	    pmcs_rd_gst_tbl(pwp, PMCS_GST_IQFRZ0));
1139 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "GST TABLE IQFRZ1: 0x%08x",
1140 	    pmcs_rd_gst_tbl(pwp, PMCS_GST_IQFRZ1));
1141 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "GST TABLE MSGU TICK: 0x%08x",
1142 	    pmcs_rd_gst_tbl(pwp, PMCS_GST_MSGU_TICK));
1143 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "GST TABLE IOP TICK: 0x%08x",
1144 	    pmcs_rd_gst_tbl(pwp, PMCS_GST_IOP_TICK));
1145 	for (i = 0; i < pwp->nphy; i++) {
1146 		uint32_t rerrf, pinfo, started = 0, link = 0;
1147 		pinfo = pmcs_rd_gst_tbl(pwp, PMCS_GST_PHY_INFO(i));
1148 		if (pinfo & 1) {
1149 			started = 1;
1150 			link = pinfo & 2;
1151 		}
1152 		rerrf = pmcs_rd_gst_tbl(pwp, PMCS_GST_RERR_INFO(i));
1153 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
1154 		    "GST TABLE PHY%d STARTED=%d LINK=%d RERR=0x%08x",
1155 		    i, started, link, rerrf);
1156 	}
1157 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "pmcs%d: Register dump end",
1158 	    ddi_get_instance(pwp->dip));
1159 }
1160 
1161 /*
1162  * Handle SATA Abort and other error processing
1163  */
1164 int
1165 pmcs_abort_handler(pmcs_hw_t *pwp)
1166 {
1167 	pmcs_phy_t *pptr, *pnext, *pnext_uplevel[PMCS_MAX_XPND];
1168 	pmcs_xscsi_t *tgt;
1169 	int r, level = 0;
1170 
1171 	pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL, "%s", __func__);
1172 
1173 	mutex_enter(&pwp->lock);
1174 	pptr = pwp->root_phys;
1175 	mutex_exit(&pwp->lock);
1176 
1177 	while (pptr) {
1178 		/*
1179 		 * XXX: Need to make sure this doesn't happen
1180 		 * XXX: when non-NCQ commands are running.
1181 		 */
1182 		pmcs_lock_phy(pptr);
1183 		if (pptr->need_rl_ext) {
1184 			ASSERT(pptr->dtype == SATA);
1185 			if (pmcs_acquire_scratch(pwp, B_FALSE)) {
1186 				goto next_phy;
1187 			}
1188 			r = pmcs_sata_abort_ncq(pwp, pptr);
1189 			pmcs_release_scratch(pwp);
1190 			if (r == ENOMEM) {
1191 				goto next_phy;
1192 			}
1193 			if (r) {
1194 				r = pmcs_reset_phy(pwp, pptr,
1195 				    PMCS_PHYOP_LINK_RESET);
1196 				if (r == ENOMEM) {
1197 					goto next_phy;
1198 				}
1199 				/* what if other failures happened? */
1200 				pptr->abort_pending = 1;
1201 				pptr->abort_sent = 0;
1202 			}
1203 		}
1204 		if (pptr->abort_pending == 0 || pptr->abort_sent) {
1205 			goto next_phy;
1206 		}
1207 		pptr->abort_pending = 0;
1208 		if (pmcs_abort(pwp, pptr, pptr->device_id, 1, 1) == ENOMEM) {
1209 			pptr->abort_pending = 1;
1210 			goto next_phy;
1211 		}
1212 		pptr->abort_sent = 1;
1213 
1214 		/*
1215 		 * If the iport is no longer active, flush the queues
1216 		 */
1217 		if ((pptr->iport == NULL) ||
1218 		    (pptr->iport->ua_state != UA_ACTIVE)) {
1219 			tgt = pptr->target;
1220 			if (tgt != NULL) {
1221 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, tgt,
1222 				    "%s: Clearing target 0x%p, inactive iport",
1223 				    __func__, (void *) tgt);
1224 				mutex_enter(&tgt->statlock);
1225 				pmcs_clear_xp(pwp, tgt);
1226 				mutex_exit(&tgt->statlock);
1227 			}
1228 		}
1229 
1230 next_phy:
1231 		if (pptr->children) {
1232 			pnext = pptr->children;
1233 			pnext_uplevel[level++] = pptr->sibling;
1234 		} else {
1235 			pnext = pptr->sibling;
1236 			while ((pnext == NULL) && (level > 0)) {
1237 				pnext = pnext_uplevel[--level];
1238 			}
1239 		}
1240 
1241 		pmcs_unlock_phy(pptr);
1242 		pptr = pnext;
1243 	}
1244 
1245 	return (0);
1246 }
1247 
1248 /*
1249  * Register a device (get a device handle for it).
1250  * Called with PHY lock held.
1251  */
1252 int
1253 pmcs_register_device(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
1254 {
1255 	struct pmcwork *pwrk;
1256 	int result = 0;
1257 	uint32_t *msg;
1258 	uint32_t tmp, status;
1259 	uint32_t iomb[(PMCS_QENTRY_SIZE << 1) >> 2];
1260 
1261 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
1262 	msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
1263 
1264 	if (msg == NULL ||
1265 	    (pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr)) == NULL) {
1266 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
1267 		result = ENOMEM;
1268 		goto out;
1269 	}
1270 
1271 	pwrk->arg = iomb;
1272 	pwrk->dtype = pptr->dtype;
1273 
1274 	msg[1] = LE_32(pwrk->htag);
1275 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL, PMCIN_REGISTER_DEVICE));
1276 	tmp = PMCS_DEVREG_TLR |
1277 	    (pptr->link_rate << PMCS_DEVREG_LINK_RATE_SHIFT);
1278 	if (IS_ROOT_PHY(pptr)) {
1279 		msg[2] = LE_32(pptr->portid |
1280 		    (pptr->phynum << PMCS_PHYID_SHIFT));
1281 	} else {
1282 		msg[2] = LE_32(pptr->portid);
1283 	}
1284 	if (pptr->dtype == SATA) {
1285 		if (IS_ROOT_PHY(pptr)) {
1286 			tmp |= PMCS_DEVREG_TYPE_SATA_DIRECT;
1287 		} else {
1288 			tmp |= PMCS_DEVREG_TYPE_SATA;
1289 		}
1290 	} else {
1291 		tmp |= PMCS_DEVREG_TYPE_SAS;
1292 	}
1293 	msg[3] = LE_32(tmp);
1294 	msg[4] = LE_32(PMCS_DEVREG_IT_NEXUS_TIMEOUT);
1295 	(void) memcpy(&msg[5], pptr->sas_address, 8);
1296 
1297 	CLEAN_MESSAGE(msg, 7);
1298 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
1299 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
1300 
1301 	pmcs_unlock_phy(pptr);
1302 	WAIT_FOR(pwrk, 250, result);
1303 	pmcs_pwork(pwp, pwrk);
1304 	pmcs_lock_phy(pptr);
1305 
1306 	if (result) {
1307 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, pmcs_timeo, __func__);
1308 		result = ETIMEDOUT;
1309 		goto out;
1310 	}
1311 	status = LE_32(iomb[2]);
1312 	tmp = LE_32(iomb[3]);
1313 	switch (status) {
1314 	case PMCS_DEVREG_OK:
1315 	case PMCS_DEVREG_DEVICE_ALREADY_REGISTERED:
1316 	case PMCS_DEVREG_PHY_ALREADY_REGISTERED:
1317 		if (pmcs_validate_devid(pwp->root_phys, pptr, tmp) == B_FALSE) {
1318 			result = EEXIST;
1319 			goto out;
1320 		} else if (status != PMCS_DEVREG_OK) {
1321 			if (tmp == 0xffffffff) {	/* F/W bug */
1322 				pmcs_prt(pwp, PMCS_PRT_INFO, pptr, NULL,
1323 				    "%s: phy %s already has bogus devid 0x%x",
1324 				    __func__, pptr->path, tmp);
1325 				result = EIO;
1326 				goto out;
1327 			} else {
1328 				pmcs_prt(pwp, PMCS_PRT_INFO, pptr, NULL,
1329 				    "%s: phy %s already has a device id 0x%x",
1330 				    __func__, pptr->path, tmp);
1331 			}
1332 		}
1333 		break;
1334 	default:
1335 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
1336 		    "%s: status 0x%x when trying to register device %s",
1337 		    __func__, status, pptr->path);
1338 		result = EIO;
1339 		goto out;
1340 	}
1341 	pptr->device_id = tmp;
1342 	pptr->valid_device_id = 1;
1343 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL, "Phy %s/" SAS_ADDR_FMT
1344 	    " registered with device_id 0x%x (portid %d)", pptr->path,
1345 	    SAS_ADDR_PRT(pptr->sas_address), tmp, pptr->portid);
1346 out:
1347 	return (result);
1348 }
1349 
1350 /*
1351  * Deregister a device (remove a device handle).
1352  * Called with PHY locked.
1353  */
1354 void
1355 pmcs_deregister_device(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
1356 {
1357 	struct pmcwork *pwrk;
1358 	uint32_t msg[PMCS_MSG_SIZE], *ptr, status;
1359 	uint32_t iomb[(PMCS_QENTRY_SIZE << 1) >> 2];
1360 	int result;
1361 
1362 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
1363 	if (pwrk == NULL) {
1364 		return;
1365 	}
1366 
1367 	pwrk->arg = iomb;
1368 	pwrk->dtype = pptr->dtype;
1369 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
1370 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
1371 	if (ptr == NULL) {
1372 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
1373 		pmcs_pwork(pwp, pwrk);
1374 		return;
1375 	}
1376 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
1377 	    PMCIN_DEREGISTER_DEVICE_HANDLE));
1378 	msg[1] = LE_32(pwrk->htag);
1379 	msg[2] = LE_32(pptr->device_id);
1380 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
1381 	COPY_MESSAGE(ptr, msg, 3);
1382 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
1383 
1384 	pmcs_unlock_phy(pptr);
1385 	WAIT_FOR(pwrk, 250, result);
1386 	pmcs_pwork(pwp, pwrk);
1387 	pmcs_lock_phy(pptr);
1388 
1389 	if (result) {
1390 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, pmcs_timeo, __func__);
1391 		return;
1392 	}
1393 	status = LE_32(iomb[2]);
1394 	if (status != PMCOUT_STATUS_OK) {
1395 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
1396 		    "%s: status 0x%x when trying to deregister device %s",
1397 		    __func__, status, pptr->path);
1398 	} else {
1399 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
1400 		    "%s: device %s deregistered", __func__, pptr->path);
1401 	}
1402 
1403 	pptr->device_id = PMCS_INVALID_DEVICE_ID;
1404 	pptr->configured = 0;
1405 	pptr->deregister_wait = 0;
1406 	pptr->valid_device_id = 0;
1407 }
1408 
1409 /*
1410  * Deregister all registered devices.
1411  */
1412 void
1413 pmcs_deregister_devices(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
1414 {
1415 	/*
1416 	 * Start at the maximum level and walk back to level 0.  This only
1417 	 * gets done during detach after all threads and timers have been
1418 	 * destroyed.
1419 	 */
1420 	while (phyp) {
1421 		if (phyp->children) {
1422 			pmcs_deregister_devices(pwp, phyp->children);
1423 		}
1424 		pmcs_lock_phy(phyp);
1425 		if (phyp->valid_device_id) {
1426 			pmcs_deregister_device(pwp, phyp);
1427 		}
1428 		pmcs_unlock_phy(phyp);
1429 		phyp = phyp->sibling;
1430 	}
1431 }
1432 
1433 /*
1434  * Perform a 'soft' reset on the PMC chip
1435  */
1436 int
1437 pmcs_soft_reset(pmcs_hw_t *pwp, boolean_t no_restart)
1438 {
1439 	uint32_t s2, sfrbits, gsm, rapchk, wapchk, wdpchk, spc, tsmode;
1440 	pmcs_phy_t *pptr;
1441 	char *msg = NULL;
1442 	int i;
1443 
1444 	/*
1445 	 * Disable interrupts
1446 	 */
1447 	pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_MASK, 0xffffffff);
1448 	pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_CLEAR, 0xffffffff);
1449 
1450 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL, "%s", __func__);
1451 
1452 	if (pwp->locks_initted) {
1453 		mutex_enter(&pwp->lock);
1454 	}
1455 	pwp->blocked = 1;
1456 
1457 	/*
1458 	 * Clear our softstate copies of the MSGU and IOP heartbeats.
1459 	 */
1460 	pwp->last_msgu_tick = pwp->last_iop_tick = 0;
1461 
1462 	/*
1463 	 * Step 1
1464 	 */
1465 	s2 = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH2);
1466 	if ((s2 & PMCS_MSGU_HOST_SOFT_RESET_READY) == 0) {
1467 		pmcs_wr_gsm_reg(pwp, RB6_ACCESS, RB6_NMI_SIGNATURE);
1468 		pmcs_wr_gsm_reg(pwp, RB6_ACCESS, RB6_NMI_SIGNATURE);
1469 		for (i = 0; i < 100; i++) {
1470 			s2 = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH2) &
1471 			    PMCS_MSGU_HOST_SOFT_RESET_READY;
1472 			if (s2) {
1473 				break;
1474 			}
1475 			drv_usecwait(10000);
1476 		}
1477 		s2 = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH2) &
1478 		    PMCS_MSGU_HOST_SOFT_RESET_READY;
1479 		if (s2 == 0) {
1480 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
1481 			    "%s: PMCS_MSGU_HOST_SOFT_RESET_READY never came "
1482 			    "ready", __func__);
1483 			pmcs_register_dump(pwp);
1484 			if ((pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1) &
1485 			    PMCS_MSGU_CPU_SOFT_RESET_READY) == 0 ||
1486 			    (pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH2) &
1487 			    PMCS_MSGU_CPU_SOFT_RESET_READY) == 0) {
1488 				pwp->state = STATE_DEAD;
1489 				pwp->blocked = 0;
1490 				if (pwp->locks_initted) {
1491 					mutex_exit(&pwp->lock);
1492 				}
1493 				return (-1);
1494 			}
1495 		}
1496 	}
1497 
1498 	/*
1499 	 * Step 2
1500 	 */
1501 	pmcs_wr_gsm_reg(pwp, NMI_EN_VPE0_IOP, 0);
1502 	drv_usecwait(10);
1503 	pmcs_wr_gsm_reg(pwp, NMI_EN_VPE0_AAP1, 0);
1504 	drv_usecwait(10);
1505 	pmcs_wr_topunit(pwp, PMCS_EVENT_INT_ENABLE, 0);
1506 	drv_usecwait(10);
1507 	pmcs_wr_topunit(pwp, PMCS_EVENT_INT_STAT,
1508 	    pmcs_rd_topunit(pwp, PMCS_EVENT_INT_STAT));
1509 	drv_usecwait(10);
1510 	pmcs_wr_topunit(pwp, PMCS_ERROR_INT_ENABLE, 0);
1511 	drv_usecwait(10);
1512 	pmcs_wr_topunit(pwp, PMCS_ERROR_INT_STAT,
1513 	    pmcs_rd_topunit(pwp, PMCS_ERROR_INT_STAT));
1514 	drv_usecwait(10);
1515 
1516 	sfrbits = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1) &
1517 	    PMCS_MSGU_AAP_SFR_PROGRESS;
1518 	sfrbits ^= PMCS_MSGU_AAP_SFR_PROGRESS;
1519 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "PMCS_MSGU_HOST_SCRATCH0 "
1520 	    "%08x -> %08x", pmcs_rd_msgunit(pwp, PMCS_MSGU_HOST_SCRATCH0),
1521 	    HST_SFT_RESET_SIG);
1522 	pmcs_wr_msgunit(pwp, PMCS_MSGU_HOST_SCRATCH0, HST_SFT_RESET_SIG);
1523 
1524 	/*
1525 	 * Step 3
1526 	 */
1527 	gsm = pmcs_rd_gsm_reg(pwp, 0, GSM_CFG_AND_RESET);
1528 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "GSM %08x -> %08x", gsm,
1529 	    gsm & ~PMCS_SOFT_RESET_BITS);
1530 	pmcs_wr_gsm_reg(pwp, GSM_CFG_AND_RESET, gsm & ~PMCS_SOFT_RESET_BITS);
1531 
1532 	/*
1533 	 * Step 4
1534 	 */
1535 	rapchk = pmcs_rd_gsm_reg(pwp, 0, READ_ADR_PARITY_CHK_EN);
1536 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "READ_ADR_PARITY_CHK_EN "
1537 	    "%08x -> %08x", rapchk, 0);
1538 	pmcs_wr_gsm_reg(pwp, READ_ADR_PARITY_CHK_EN, 0);
1539 	wapchk = pmcs_rd_gsm_reg(pwp, 0, WRITE_ADR_PARITY_CHK_EN);
1540 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "WRITE_ADR_PARITY_CHK_EN "
1541 	    "%08x -> %08x", wapchk, 0);
1542 	pmcs_wr_gsm_reg(pwp, WRITE_ADR_PARITY_CHK_EN, 0);
1543 	wdpchk = pmcs_rd_gsm_reg(pwp, 0, WRITE_DATA_PARITY_CHK_EN);
1544 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "WRITE_DATA_PARITY_CHK_EN "
1545 	    "%08x -> %08x", wdpchk, 0);
1546 	pmcs_wr_gsm_reg(pwp, WRITE_DATA_PARITY_CHK_EN, 0);
1547 
1548 	/*
1549 	 * Step 5
1550 	 */
1551 	drv_usecwait(100);
1552 
1553 	/*
1554 	 * Step 5.5 (Temporary workaround for 1.07.xx Beta)
1555 	 */
1556 	tsmode = pmcs_rd_gsm_reg(pwp, 0, PMCS_GPIO_TRISTATE_MODE_ADDR);
1557 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "GPIO TSMODE %08x -> %08x",
1558 	    tsmode, tsmode & ~(PMCS_GPIO_TSMODE_BIT0|PMCS_GPIO_TSMODE_BIT1));
1559 	pmcs_wr_gsm_reg(pwp, PMCS_GPIO_TRISTATE_MODE_ADDR,
1560 	    tsmode & ~(PMCS_GPIO_TSMODE_BIT0|PMCS_GPIO_TSMODE_BIT1));
1561 	drv_usecwait(10);
1562 
1563 	/*
1564 	 * Step 6
1565 	 */
1566 	spc = pmcs_rd_topunit(pwp, PMCS_SPC_RESET);
1567 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "SPC_RESET %08x -> %08x",
1568 	    spc, spc & ~(PCS_IOP_SS_RSTB|PCS_AAP1_SS_RSTB));
1569 	pmcs_wr_topunit(pwp, PMCS_SPC_RESET,
1570 	    spc & ~(PCS_IOP_SS_RSTB|PCS_AAP1_SS_RSTB));
1571 	drv_usecwait(10);
1572 
1573 	/*
1574 	 * Step 7
1575 	 */
1576 	spc = pmcs_rd_topunit(pwp, PMCS_SPC_RESET);
1577 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "SPC_RESET %08x -> %08x",
1578 	    spc, spc & ~(BDMA_CORE_RSTB|OSSP_RSTB));
1579 	pmcs_wr_topunit(pwp, PMCS_SPC_RESET, spc & ~(BDMA_CORE_RSTB|OSSP_RSTB));
1580 
1581 	/*
1582 	 * Step 8
1583 	 */
1584 	drv_usecwait(100);
1585 
1586 	/*
1587 	 * Step 9
1588 	 */
1589 	spc = pmcs_rd_topunit(pwp, PMCS_SPC_RESET);
1590 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "SPC_RESET %08x -> %08x",
1591 	    spc, spc | (BDMA_CORE_RSTB|OSSP_RSTB));
1592 	pmcs_wr_topunit(pwp, PMCS_SPC_RESET, spc | (BDMA_CORE_RSTB|OSSP_RSTB));
1593 
1594 	/*
1595 	 * Step 10
1596 	 */
1597 	drv_usecwait(100);
1598 
1599 	/*
1600 	 * Step 11
1601 	 */
1602 	gsm = pmcs_rd_gsm_reg(pwp, 0, GSM_CFG_AND_RESET);
1603 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "GSM %08x -> %08x", gsm,
1604 	    gsm | PMCS_SOFT_RESET_BITS);
1605 	pmcs_wr_gsm_reg(pwp, GSM_CFG_AND_RESET, gsm | PMCS_SOFT_RESET_BITS);
1606 	drv_usecwait(10);
1607 
1608 	/*
1609 	 * Step 12
1610 	 */
1611 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "READ_ADR_PARITY_CHK_EN "
1612 	    "%08x -> %08x", pmcs_rd_gsm_reg(pwp, 0, READ_ADR_PARITY_CHK_EN),
1613 	    rapchk);
1614 	pmcs_wr_gsm_reg(pwp, READ_ADR_PARITY_CHK_EN, rapchk);
1615 	drv_usecwait(10);
1616 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "WRITE_ADR_PARITY_CHK_EN "
1617 	    "%08x -> %08x", pmcs_rd_gsm_reg(pwp, 0, WRITE_ADR_PARITY_CHK_EN),
1618 	    wapchk);
1619 	pmcs_wr_gsm_reg(pwp, WRITE_ADR_PARITY_CHK_EN, wapchk);
1620 	drv_usecwait(10);
1621 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "WRITE_DATA_PARITY_CHK_EN "
1622 	    "%08x -> %08x", pmcs_rd_gsm_reg(pwp, 0, WRITE_DATA_PARITY_CHK_EN),
1623 	    wapchk);
1624 	pmcs_wr_gsm_reg(pwp, WRITE_DATA_PARITY_CHK_EN, wdpchk);
1625 	drv_usecwait(10);
1626 
1627 	/*
1628 	 * Step 13
1629 	 */
1630 	spc = pmcs_rd_topunit(pwp, PMCS_SPC_RESET);
1631 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL, "SPC_RESET %08x -> %08x",
1632 	    spc, spc | (PCS_IOP_SS_RSTB|PCS_AAP1_SS_RSTB));
1633 	pmcs_wr_topunit(pwp, PMCS_SPC_RESET,
1634 	    spc | (PCS_IOP_SS_RSTB|PCS_AAP1_SS_RSTB));
1635 
1636 	/*
1637 	 * Step 14
1638 	 */
1639 	drv_usecwait(100);
1640 
1641 	/*
1642 	 * Step 15
1643 	 */
1644 	for (spc = 0, i = 0; i < 1000; i++) {
1645 		drv_usecwait(1000);
1646 		spc = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1);
1647 		if ((spc & PMCS_MSGU_AAP_SFR_PROGRESS) == sfrbits) {
1648 			break;
1649 		}
1650 	}
1651 
1652 	if ((spc & PMCS_MSGU_AAP_SFR_PROGRESS) != sfrbits) {
1653 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
1654 		    "SFR didn't toggle (sfr 0x%x)", spc);
1655 		pwp->state = STATE_DEAD;
1656 		pwp->blocked = 0;
1657 		if (pwp->locks_initted) {
1658 			mutex_exit(&pwp->lock);
1659 		}
1660 		return (-1);
1661 	}
1662 
1663 	/*
1664 	 * Step 16
1665 	 */
1666 	pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_MASK, 0xffffffff);
1667 	pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_CLEAR, 0xffffffff);
1668 
1669 	/*
1670 	 * Wait for up to 5 seconds for AAP state to come either ready or error.
1671 	 */
1672 	for (i = 0; i < 50; i++) {
1673 		spc = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1) &
1674 		    PMCS_MSGU_AAP_STATE_MASK;
1675 		if (spc == PMCS_MSGU_AAP_STATE_ERROR ||
1676 		    spc == PMCS_MSGU_AAP_STATE_READY) {
1677 			break;
1678 		}
1679 		drv_usecwait(100000);
1680 	}
1681 	spc = pmcs_rd_msgunit(pwp, PMCS_MSGU_SCRATCH1);
1682 	if ((spc & PMCS_MSGU_AAP_STATE_MASK) != PMCS_MSGU_AAP_STATE_READY) {
1683 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
1684 		    "soft reset failed (state 0x%x)", spc);
1685 		pwp->state = STATE_DEAD;
1686 		pwp->blocked = 0;
1687 		if (pwp->locks_initted) {
1688 			mutex_exit(&pwp->lock);
1689 		}
1690 		return (-1);
1691 	}
1692 
1693 	/* Clear the firmware log */
1694 	if (pwp->fwlogp) {
1695 		bzero(pwp->fwlogp, PMCS_FWLOG_SIZE);
1696 	}
1697 
1698 	/* Reset our queue indices and entries */
1699 	bzero(pwp->shadow_iqpi, sizeof (pwp->shadow_iqpi));
1700 	bzero(pwp->last_iqci, sizeof (pwp->last_iqci));
1701 	bzero(pwp->last_htag, sizeof (pwp->last_htag));
1702 	for (i = 0; i < PMCS_NIQ; i++) {
1703 		if (pwp->iqp[i]) {
1704 			bzero(pwp->iqp[i], PMCS_QENTRY_SIZE * pwp->ioq_depth);
1705 			pmcs_wr_iqpi(pwp, i, 0);
1706 			pmcs_wr_iqci(pwp, i, 0);
1707 		}
1708 	}
1709 	for (i = 0; i < PMCS_NOQ; i++) {
1710 		if (pwp->oqp[i]) {
1711 			bzero(pwp->oqp[i], PMCS_QENTRY_SIZE * pwp->ioq_depth);
1712 			pmcs_wr_oqpi(pwp, i, 0);
1713 			pmcs_wr_oqci(pwp, i, 0);
1714 		}
1715 
1716 	}
1717 
1718 	if (pwp->state == STATE_DEAD || pwp->state == STATE_UNPROBING ||
1719 	    pwp->state == STATE_PROBING || pwp->locks_initted == 0) {
1720 		pwp->blocked = 0;
1721 		if (pwp->locks_initted) {
1722 			mutex_exit(&pwp->lock);
1723 		}
1724 		return (0);
1725 	}
1726 
1727 	/*
1728 	 * Return at this point if we dont need to startup.
1729 	 */
1730 	if (no_restart) {
1731 		return (0);
1732 	}
1733 
1734 	ASSERT(pwp->locks_initted != 0);
1735 
1736 	/*
1737 	 * Flush the target queues and clear each target's PHY
1738 	 */
1739 	if (pwp->targets) {
1740 		for (i = 0; i < pwp->max_dev; i++) {
1741 			pmcs_xscsi_t *xp = pwp->targets[i];
1742 
1743 			if (xp == NULL) {
1744 				continue;
1745 			}
1746 
1747 			mutex_enter(&xp->statlock);
1748 			pmcs_flush_target_queues(pwp, xp, PMCS_TGT_ALL_QUEUES);
1749 			xp->phy = NULL;
1750 			mutex_exit(&xp->statlock);
1751 		}
1752 	}
1753 
1754 	/*
1755 	 * Zero out the ports list, free non root phys, clear root phys
1756 	 */
1757 	bzero(pwp->ports, sizeof (pwp->ports));
1758 	pmcs_free_all_phys(pwp, pwp->root_phys);
1759 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
1760 		pmcs_lock_phy(pptr);
1761 		pmcs_clear_phy(pwp, pptr);
1762 		pptr->target = NULL;
1763 		pmcs_unlock_phy(pptr);
1764 	}
1765 
1766 	/*
1767 	 * Restore Interrupt Mask
1768 	 */
1769 	pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_MASK, pwp->intr_mask);
1770 	pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_CLEAR, 0xffffffff);
1771 
1772 	pwp->mpi_table_setup = 0;
1773 	mutex_exit(&pwp->lock);
1774 
1775 	/*
1776 	 * Set up MPI again.
1777 	 */
1778 	if (pmcs_setup(pwp)) {
1779 		msg = "unable to setup MPI tables again";
1780 		goto fail_restart;
1781 	}
1782 	pmcs_report_fwversion(pwp);
1783 
1784 	/*
1785 	 * Restart MPI
1786 	 */
1787 	if (pmcs_start_mpi(pwp)) {
1788 		msg = "unable to restart MPI again";
1789 		goto fail_restart;
1790 	}
1791 
1792 	mutex_enter(&pwp->lock);
1793 	SCHEDULE_WORK(pwp, PMCS_WORK_RUN_QUEUES);
1794 	mutex_exit(&pwp->lock);
1795 
1796 	/*
1797 	 * Run any completions
1798 	 */
1799 	PMCS_CQ_RUN(pwp);
1800 
1801 	/*
1802 	 * Delay
1803 	 */
1804 	drv_usecwait(1000000);
1805 	return (0);
1806 
1807 fail_restart:
1808 	mutex_enter(&pwp->lock);
1809 	pwp->state = STATE_DEAD;
1810 	mutex_exit(&pwp->lock);
1811 	pmcs_prt(pwp, PMCS_PRT_ERR, NULL, NULL,
1812 	    "%s: Failed: %s", __func__, msg);
1813 	return (-1);
1814 }
1815 
1816 
1817 /*
1818  * Perform a 'hot' reset, which will soft reset the chip and
1819  * restore the state back to pre-reset context. Called with pwp
1820  * lock held.
1821  */
1822 int
1823 pmcs_hot_reset(pmcs_hw_t *pwp)
1824 {
1825 	pmcs_iport_t	*iport;
1826 
1827 	ASSERT(mutex_owned(&pwp->lock));
1828 	pwp->state = STATE_IN_RESET;
1829 
1830 	/*
1831 	 * For any iports on this HBA, report empty target sets and
1832 	 * then tear them down.
1833 	 */
1834 	rw_enter(&pwp->iports_lock, RW_READER);
1835 	for (iport = list_head(&pwp->iports); iport != NULL;
1836 	    iport = list_next(&pwp->iports, iport)) {
1837 		mutex_enter(&iport->lock);
1838 		(void) scsi_hba_tgtmap_set_begin(iport->iss_tgtmap);
1839 		(void) scsi_hba_tgtmap_set_end(iport->iss_tgtmap, 0);
1840 		pmcs_iport_teardown_phys(iport);
1841 		mutex_exit(&iport->lock);
1842 	}
1843 	rw_exit(&pwp->iports_lock);
1844 
1845 	/* Grab a register dump, in the event that reset fails */
1846 	pmcs_register_dump_int(pwp);
1847 	mutex_exit(&pwp->lock);
1848 
1849 	/* Ensure discovery is not running before we proceed */
1850 	mutex_enter(&pwp->config_lock);
1851 	while (pwp->configuring) {
1852 		cv_wait(&pwp->config_cv, &pwp->config_lock);
1853 	}
1854 	mutex_exit(&pwp->config_lock);
1855 
1856 	/* Issue soft reset and clean up related softstate */
1857 	if (pmcs_soft_reset(pwp, B_FALSE)) {
1858 		/*
1859 		 * Disable interrupts, in case we got far enough along to
1860 		 * enable them, then fire off ereport and service impact.
1861 		 */
1862 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
1863 		    "%s: failed soft reset", __func__);
1864 		pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_MASK, 0xffffffff);
1865 		pmcs_wr_msgunit(pwp, PMCS_MSGU_OBDB_CLEAR, 0xffffffff);
1866 		pmcs_fm_ereport(pwp, DDI_FM_DEVICE_NO_RESPONSE);
1867 		ddi_fm_service_impact(pwp->dip, DDI_SERVICE_LOST);
1868 		mutex_enter(&pwp->lock);
1869 		pwp->state = STATE_DEAD;
1870 		return (DDI_FAILURE);
1871 	}
1872 
1873 	mutex_enter(&pwp->lock);
1874 	pwp->state = STATE_RUNNING;
1875 	mutex_exit(&pwp->lock);
1876 
1877 	/*
1878 	 * Finally, restart the phys, which will bring the iports back
1879 	 * up and eventually result in discovery running.
1880 	 */
1881 	if (pmcs_start_phys(pwp)) {
1882 		/* We should be up and running now, so retry */
1883 		if (pmcs_start_phys(pwp)) {
1884 			/* Apparently unable to restart PHYs, fail */
1885 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
1886 			    "%s: failed to restart PHYs after soft reset",
1887 			    __func__);
1888 			mutex_enter(&pwp->lock);
1889 			return (DDI_FAILURE);
1890 		}
1891 	}
1892 
1893 	mutex_enter(&pwp->lock);
1894 	return (DDI_SUCCESS);
1895 }
1896 
1897 /*
1898  * Reset a device or a logical unit.
1899  */
1900 int
1901 pmcs_reset_dev(pmcs_hw_t *pwp, pmcs_phy_t *pptr, uint64_t lun)
1902 {
1903 	int rval = 0;
1904 
1905 	if (pptr == NULL) {
1906 		return (ENXIO);
1907 	}
1908 
1909 	pmcs_lock_phy(pptr);
1910 	if (pptr->dtype == SAS) {
1911 		/*
1912 		 * Some devices do not support SAS_I_T_NEXUS_RESET as
1913 		 * it is not a mandatory (in SAM4) task management
1914 		 * function, while LOGIC_UNIT_RESET is mandatory.
1915 		 *
1916 		 * The problem here is that we need to iterate over
1917 		 * all known LUNs to emulate the semantics of
1918 		 * "RESET_TARGET".
1919 		 *
1920 		 * XXX: FIX ME
1921 		 */
1922 		if (lun == (uint64_t)-1) {
1923 			lun = 0;
1924 		}
1925 		rval = pmcs_ssp_tmf(pwp, pptr, SAS_LOGICAL_UNIT_RESET, 0, lun,
1926 		    NULL);
1927 	} else if (pptr->dtype == SATA) {
1928 		if (lun != 0ull) {
1929 			pmcs_unlock_phy(pptr);
1930 			return (EINVAL);
1931 		}
1932 		rval = pmcs_reset_phy(pwp, pptr, PMCS_PHYOP_LINK_RESET);
1933 	} else {
1934 		pmcs_unlock_phy(pptr);
1935 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
1936 		    "%s: cannot reset a SMP device yet (%s)",
1937 		    __func__, pptr->path);
1938 		return (EINVAL);
1939 	}
1940 
1941 	/*
1942 	 * Now harvest any commands killed by this action
1943 	 * by issuing an ABORT for all commands on this device.
1944 	 *
1945 	 * We do this even if the the tmf or reset fails (in case there
1946 	 * are any dead commands around to be harvested *anyway*).
1947 	 * We don't have to await for the abort to complete.
1948 	 */
1949 	if (pmcs_abort(pwp, pptr, 0, 1, 0)) {
1950 		pptr->abort_pending = 1;
1951 		SCHEDULE_WORK(pwp, PMCS_WORK_ABORT_HANDLE);
1952 	}
1953 
1954 	pmcs_unlock_phy(pptr);
1955 	return (rval);
1956 }
1957 
1958 /*
1959  * Called with PHY locked.
1960  */
1961 static int
1962 pmcs_get_device_handle(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
1963 {
1964 	if (pptr->valid_device_id == 0) {
1965 		int result = pmcs_register_device(pwp, pptr);
1966 
1967 		/*
1968 		 * If we changed while registering, punt
1969 		 */
1970 		if (pptr->changed) {
1971 			RESTART_DISCOVERY(pwp);
1972 			return (-1);
1973 		}
1974 
1975 		/*
1976 		 * If we had a failure to register, check against errors.
1977 		 * An ENOMEM error means we just retry (temp resource shortage).
1978 		 */
1979 		if (result == ENOMEM) {
1980 			PHY_CHANGED(pwp, pptr);
1981 			RESTART_DISCOVERY(pwp);
1982 			return (-1);
1983 		}
1984 
1985 		/*
1986 		 * An ETIMEDOUT error means we retry (if our counter isn't
1987 		 * exhausted)
1988 		 */
1989 		if (result == ETIMEDOUT) {
1990 			if (ddi_get_lbolt() < pptr->config_stop) {
1991 				PHY_CHANGED(pwp, pptr);
1992 				RESTART_DISCOVERY(pwp);
1993 			} else {
1994 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
1995 				    "%s: Retries exhausted for %s, killing",
1996 				    __func__, pptr->path);
1997 				pptr->config_stop = 0;
1998 				pmcs_kill_changed(pwp, pptr, 0);
1999 			}
2000 			return (-1);
2001 		}
2002 		/*
2003 		 * Other errors or no valid device id is fatal, but don't
2004 		 * preclude a future action.
2005 		 */
2006 		if (result || pptr->valid_device_id == 0) {
2007 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
2008 			    "%s: %s could not be registered", __func__,
2009 			    pptr->path);
2010 			return (-1);
2011 		}
2012 	}
2013 	return (0);
2014 }
2015 
2016 int
2017 pmcs_iport_tgtmap_create(pmcs_iport_t *iport)
2018 {
2019 	ASSERT(iport);
2020 	if (iport == NULL)
2021 		return (B_FALSE);
2022 
2023 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL, "%s", __func__);
2024 
2025 	/* create target map */
2026 	if (scsi_hba_tgtmap_create(iport->dip, SCSI_TM_FULLSET,
2027 	    tgtmap_csync_usec, tgtmap_stable_usec, (void *)iport,
2028 	    pmcs_tgtmap_activate_cb, pmcs_tgtmap_deactivate_cb,
2029 	    &iport->iss_tgtmap) != DDI_SUCCESS) {
2030 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG, NULL, NULL,
2031 		    "%s: failed to create tgtmap", __func__);
2032 		return (B_FALSE);
2033 	}
2034 	return (B_TRUE);
2035 }
2036 
2037 int
2038 pmcs_iport_tgtmap_destroy(pmcs_iport_t *iport)
2039 {
2040 	ASSERT(iport && iport->iss_tgtmap);
2041 	if ((iport == NULL) || (iport->iss_tgtmap == NULL))
2042 		return (B_FALSE);
2043 
2044 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL, "%s", __func__);
2045 
2046 	/* destroy target map */
2047 	scsi_hba_tgtmap_destroy(iport->iss_tgtmap);
2048 	return (B_TRUE);
2049 }
2050 
2051 /*
2052  * Remove all phys from an iport's phymap and empty it's phylist.
2053  * Called when a port has been reset by the host (see pmcs_intr.c)
2054  * or prior to issuing a soft reset if we detect a stall on the chip
2055  * (see pmcs_attach.c).
2056  */
2057 void
2058 pmcs_iport_teardown_phys(pmcs_iport_t *iport)
2059 {
2060 	pmcs_hw_t		*pwp;
2061 	sas_phymap_phys_t	*phys;
2062 	int			phynum;
2063 
2064 	ASSERT(iport);
2065 	ASSERT(mutex_owned(&iport->lock));
2066 	pwp = iport->pwp;
2067 	ASSERT(pwp);
2068 
2069 	/*
2070 	 * Remove all phys from the iport handle's phy list, unset its
2071 	 * primary phy and update its state.
2072 	 */
2073 	pmcs_remove_phy_from_iport(iport, NULL);
2074 	iport->pptr = NULL;
2075 	iport->ua_state = UA_PEND_DEACTIVATE;
2076 
2077 	/* Remove all phys from the phymap */
2078 	phys = sas_phymap_ua2phys(pwp->hss_phymap, iport->ua);
2079 	if (phys) {
2080 		while ((phynum = sas_phymap_phys_next(phys)) != -1) {
2081 			(void) sas_phymap_phy_rem(pwp->hss_phymap, phynum);
2082 		}
2083 		sas_phymap_phys_free(phys);
2084 	}
2085 }
2086 
2087 /*
2088  * Query the phymap and populate the iport handle passed in.
2089  * Called with iport lock held.
2090  */
2091 int
2092 pmcs_iport_configure_phys(pmcs_iport_t *iport)
2093 {
2094 	pmcs_hw_t		*pwp;
2095 	pmcs_phy_t		*pptr;
2096 	sas_phymap_phys_t	*phys;
2097 	int			phynum;
2098 	int			inst;
2099 
2100 	ASSERT(iport);
2101 	ASSERT(mutex_owned(&iport->lock));
2102 	pwp = iport->pwp;
2103 	ASSERT(pwp);
2104 	inst = ddi_get_instance(iport->dip);
2105 
2106 	mutex_enter(&pwp->lock);
2107 	ASSERT(pwp->root_phys != NULL);
2108 
2109 	/*
2110 	 * Query the phymap regarding the phys in this iport and populate
2111 	 * the iport's phys list. Hereafter this list is maintained via
2112 	 * port up and down events in pmcs_intr.c
2113 	 */
2114 	ASSERT(list_is_empty(&iport->phys));
2115 	phys = sas_phymap_ua2phys(pwp->hss_phymap, iport->ua);
2116 	ASSERT(phys != NULL);
2117 	while ((phynum = sas_phymap_phys_next(phys)) != -1) {
2118 		/* Grab the phy pointer from root_phys */
2119 		pptr = pwp->root_phys + phynum;
2120 		ASSERT(pptr);
2121 		pmcs_lock_phy(pptr);
2122 		ASSERT(pptr->phynum == phynum);
2123 
2124 		/*
2125 		 * Set a back pointer in the phy to this iport.
2126 		 */
2127 		pptr->iport = iport;
2128 
2129 		/*
2130 		 * If this phy is the primary, set a pointer to it on our
2131 		 * iport handle, and set our portid from it.
2132 		 */
2133 		if (!pptr->subsidiary) {
2134 			iport->pptr = pptr;
2135 			iport->portid = pptr->portid;
2136 		}
2137 
2138 		/*
2139 		 * Finally, insert the phy into our list
2140 		 */
2141 		pmcs_unlock_phy(pptr);
2142 		pmcs_add_phy_to_iport(iport, pptr);
2143 
2144 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL, "%s: found "
2145 		    "phy %d [0x%p] on iport%d, refcnt(%d)", __func__, phynum,
2146 		    (void *)pptr, inst, iport->refcnt);
2147 	}
2148 	mutex_exit(&pwp->lock);
2149 	sas_phymap_phys_free(phys);
2150 	RESTART_DISCOVERY(pwp);
2151 	return (DDI_SUCCESS);
2152 }
2153 
2154 /*
2155  * Return the iport that ua is associated with, or NULL.  If an iport is
2156  * returned, it will be held and the caller must release the hold.
2157  */
2158 static pmcs_iport_t *
2159 pmcs_get_iport_by_ua(pmcs_hw_t *pwp, char *ua)
2160 {
2161 	pmcs_iport_t	*iport = NULL;
2162 
2163 	rw_enter(&pwp->iports_lock, RW_READER);
2164 	for (iport = list_head(&pwp->iports);
2165 	    iport != NULL;
2166 	    iport = list_next(&pwp->iports, iport)) {
2167 		mutex_enter(&iport->lock);
2168 		if (strcmp(iport->ua, ua) == 0) {
2169 			mutex_exit(&iport->lock);
2170 			pmcs_hold_iport(iport);
2171 			break;
2172 		}
2173 		mutex_exit(&iport->lock);
2174 	}
2175 	rw_exit(&pwp->iports_lock);
2176 
2177 	return (iport);
2178 }
2179 
2180 /*
2181  * Return the iport that pptr is associated with, or NULL.
2182  * If an iport is returned, there is a hold that the caller must release.
2183  */
2184 pmcs_iport_t *
2185 pmcs_get_iport_by_wwn(pmcs_hw_t *pwp, uint64_t wwn)
2186 {
2187 	pmcs_iport_t	*iport = NULL;
2188 	char		*ua;
2189 
2190 	ua = sas_phymap_lookup_ua(pwp->hss_phymap, pwp->sas_wwns[0], wwn);
2191 	if (ua) {
2192 		iport = pmcs_get_iport_by_ua(pwp, ua);
2193 		if (iport) {
2194 			mutex_enter(&iport->lock);
2195 			pmcs_iport_active(iport);
2196 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL, "%s: "
2197 			    "found iport [0x%p] on ua (%s), refcnt (%d)",
2198 			    __func__, (void *)iport, ua, iport->refcnt);
2199 			mutex_exit(&iport->lock);
2200 		}
2201 	}
2202 
2203 	return (iport);
2204 }
2205 
2206 /*
2207  * Promote the next phy on this port to primary, and return it.
2208  * Called when the primary PHY on a port is going down, but the port
2209  * remains up (see pmcs_intr.c).
2210  */
2211 pmcs_phy_t *
2212 pmcs_promote_next_phy(pmcs_phy_t *prev_primary)
2213 {
2214 	pmcs_hw_t	*pwp;
2215 	pmcs_iport_t	*iport;
2216 	pmcs_phy_t	*pptr, *child;
2217 	int		portid;
2218 
2219 	pmcs_lock_phy(prev_primary);
2220 	portid = prev_primary->portid;
2221 	iport  = prev_primary->iport;
2222 	pwp    = prev_primary->pwp;
2223 
2224 	/* Use the first available phy in this port */
2225 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
2226 		if ((pptr->portid == portid) && (pptr != prev_primary)) {
2227 			mutex_enter(&pptr->phy_lock);
2228 			break;
2229 		}
2230 	}
2231 
2232 	if (pptr == NULL) {
2233 		pmcs_unlock_phy(prev_primary);
2234 		return (NULL);
2235 	}
2236 
2237 	if (iport) {
2238 		mutex_enter(&iport->lock);
2239 		iport->pptr = pptr;
2240 		mutex_exit(&iport->lock);
2241 	}
2242 
2243 	/* Update the phy handle with the data from the previous primary */
2244 	pptr->children		= prev_primary->children;
2245 	child = pptr->children;
2246 	while (child) {
2247 		child->parent = pptr;
2248 		child = child->sibling;
2249 	}
2250 	pptr->ncphy		= prev_primary->ncphy;
2251 	pptr->width		= prev_primary->width;
2252 	pptr->dtype		= prev_primary->dtype;
2253 	pptr->pend_dtype	= prev_primary->pend_dtype;
2254 	pptr->tolerates_sas2	= prev_primary->tolerates_sas2;
2255 	pptr->atdt		= prev_primary->atdt;
2256 	pptr->portid		= prev_primary->portid;
2257 	pptr->link_rate		= prev_primary->link_rate;
2258 	pptr->configured	= prev_primary->configured;
2259 	pptr->iport		= prev_primary->iport;
2260 	pptr->target		= prev_primary->target;
2261 	if (pptr->target) {
2262 		pptr->target->phy = pptr;
2263 	}
2264 
2265 	/* Update the phy mask properties for the affected PHYs */
2266 	/* Clear the current values... */
2267 	pmcs_update_phy_pm_props(pptr, pptr->att_port_pm_tmp,
2268 	    pptr->tgt_port_pm_tmp, B_FALSE);
2269 	/* ...replace with the values from prev_primary... */
2270 	pmcs_update_phy_pm_props(pptr, prev_primary->att_port_pm_tmp,
2271 	    prev_primary->tgt_port_pm_tmp, B_TRUE);
2272 	/* ...then clear prev_primary's PHY values from the new primary */
2273 	pmcs_update_phy_pm_props(pptr, prev_primary->att_port_pm,
2274 	    prev_primary->tgt_port_pm, B_FALSE);
2275 	/* Clear the prev_primary's values */
2276 	pmcs_update_phy_pm_props(prev_primary, prev_primary->att_port_pm_tmp,
2277 	    prev_primary->tgt_port_pm_tmp, B_FALSE);
2278 
2279 	pptr->subsidiary = 0;
2280 
2281 	prev_primary->subsidiary = 1;
2282 	prev_primary->children = NULL;
2283 	prev_primary->target = NULL;
2284 	pptr->device_id = prev_primary->device_id;
2285 	pptr->valid_device_id = prev_primary->valid_device_id;
2286 	pmcs_unlock_phy(prev_primary);
2287 
2288 	/*
2289 	 * We call pmcs_unlock_phy() on pptr because it now contains the
2290 	 * list of children.
2291 	 */
2292 	pmcs_unlock_phy(pptr);
2293 
2294 	return (pptr);
2295 }
2296 
2297 void
2298 pmcs_hold_iport(pmcs_iport_t *iport)
2299 {
2300 	/*
2301 	 * Grab a reference to this iport.
2302 	 */
2303 	ASSERT(iport);
2304 	mutex_enter(&iport->refcnt_lock);
2305 	iport->refcnt++;
2306 	mutex_exit(&iport->refcnt_lock);
2307 
2308 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG2, NULL, NULL, "%s: iport "
2309 	    "[0x%p] refcnt (%d)", __func__, (void *)iport, iport->refcnt);
2310 }
2311 
2312 void
2313 pmcs_rele_iport(pmcs_iport_t *iport)
2314 {
2315 	/*
2316 	 * Release a refcnt on this iport. If this is the last reference,
2317 	 * signal the potential waiter in pmcs_iport_unattach().
2318 	 */
2319 	ASSERT(iport->refcnt > 0);
2320 	mutex_enter(&iport->refcnt_lock);
2321 	iport->refcnt--;
2322 	mutex_exit(&iport->refcnt_lock);
2323 	if (iport->refcnt == 0) {
2324 		cv_signal(&iport->refcnt_cv);
2325 	}
2326 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG2, NULL, NULL, "%s: iport "
2327 	    "[0x%p] refcnt (%d)", __func__, (void *)iport, iport->refcnt);
2328 }
2329 
2330 void
2331 pmcs_phymap_activate(void *arg, char *ua, void **privp)
2332 {
2333 	_NOTE(ARGUNUSED(privp));
2334 	pmcs_hw_t	*pwp = arg;
2335 	pmcs_iport_t	*iport = NULL;
2336 
2337 	mutex_enter(&pwp->lock);
2338 	if ((pwp->state == STATE_UNPROBING) || (pwp->state == STATE_DEAD) ||
2339 	    (pwp->state == STATE_IN_RESET)) {
2340 		mutex_exit(&pwp->lock);
2341 		return;
2342 	}
2343 	pwp->phymap_active++;
2344 	mutex_exit(&pwp->lock);
2345 
2346 	if (scsi_hba_iportmap_iport_add(pwp->hss_iportmap, ua, NULL) !=
2347 	    DDI_SUCCESS) {
2348 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL, "%s: failed to "
2349 		    "add iport handle on unit address [%s]", __func__, ua);
2350 	} else {
2351 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL, "%s: "
2352 		    "phymap_active count (%d), added iport handle on unit "
2353 		    "address [%s]", __func__, pwp->phymap_active, ua);
2354 	}
2355 
2356 	/* Set the HBA softstate as our private data for this unit address */
2357 	*privp = (void *)pwp;
2358 
2359 	/*
2360 	 * We are waiting on attach for this iport node, unless it is still
2361 	 * attached. This can happen if a consumer has an outstanding open
2362 	 * on our iport node, but the port is down.  If this is the case, we
2363 	 * need to configure our iport here for reuse.
2364 	 */
2365 	iport = pmcs_get_iport_by_ua(pwp, ua);
2366 	if (iport) {
2367 		mutex_enter(&iport->lock);
2368 		if (pmcs_iport_configure_phys(iport) != DDI_SUCCESS) {
2369 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL, "%s: "
2370 			    "failed to configure phys on iport [0x%p] at "
2371 			    "unit address (%s)", __func__, (void *)iport, ua);
2372 		}
2373 		pmcs_iport_active(iport);
2374 		pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32, PMCS_NUM_PHYS,
2375 		    &iport->nphy);
2376 		mutex_exit(&iport->lock);
2377 		pmcs_rele_iport(iport);
2378 	}
2379 
2380 }
2381 
2382 void
2383 pmcs_phymap_deactivate(void *arg, char *ua, void *privp)
2384 {
2385 	_NOTE(ARGUNUSED(privp));
2386 	pmcs_hw_t	*pwp = arg;
2387 	pmcs_iport_t	*iport;
2388 
2389 	mutex_enter(&pwp->lock);
2390 	pwp->phymap_active--;
2391 	mutex_exit(&pwp->lock);
2392 
2393 	if (scsi_hba_iportmap_iport_remove(pwp->hss_iportmap, ua) !=
2394 	    DDI_SUCCESS) {
2395 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL, "%s: failed to "
2396 		    "remove iport handle on unit address [%s]", __func__, ua);
2397 	} else {
2398 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL, "%s: "
2399 		    "phymap_active count (%d), removed iport handle on unit "
2400 		    "address [%s]", __func__, pwp->phymap_active, ua);
2401 	}
2402 
2403 	iport = pmcs_get_iport_by_ua(pwp, ua);
2404 
2405 	if (iport == NULL) {
2406 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL, "%s: failed "
2407 		    "lookup of iport handle on unit addr (%s)", __func__, ua);
2408 		return;
2409 	}
2410 
2411 	mutex_enter(&iport->lock);
2412 	iport->ua_state = UA_INACTIVE;
2413 	iport->portid = PMCS_IPORT_INVALID_PORT_ID;
2414 	pmcs_remove_phy_from_iport(iport, NULL);
2415 	mutex_exit(&iport->lock);
2416 	pmcs_rele_iport(iport);
2417 }
2418 
2419 /*
2420  * Top-level discovery function
2421  */
2422 void
2423 pmcs_discover(pmcs_hw_t *pwp)
2424 {
2425 	pmcs_phy_t		*pptr;
2426 	pmcs_phy_t		*root_phy;
2427 
2428 	DTRACE_PROBE2(pmcs__discover__entry, ulong_t, pwp->work_flags,
2429 	    boolean_t, pwp->config_changed);
2430 
2431 	mutex_enter(&pwp->lock);
2432 
2433 	if (pwp->state != STATE_RUNNING) {
2434 		mutex_exit(&pwp->lock);
2435 		return;
2436 	}
2437 
2438 	/* Ensure we have at least one phymap active */
2439 	if (pwp->phymap_active == 0) {
2440 		mutex_exit(&pwp->lock);
2441 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2442 		    "%s: phymap inactive, exiting", __func__);
2443 		return;
2444 	}
2445 
2446 	mutex_exit(&pwp->lock);
2447 
2448 	/*
2449 	 * If no iports have attached, but we have PHYs that are up, we
2450 	 * are waiting for iport attach to complete.  Restart discovery.
2451 	 */
2452 	rw_enter(&pwp->iports_lock, RW_READER);
2453 	if (!pwp->iports_attached) {
2454 		rw_exit(&pwp->iports_lock);
2455 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2456 		    "%s: no iports attached, retry discovery", __func__);
2457 		SCHEDULE_WORK(pwp, PMCS_WORK_DISCOVER);
2458 		return;
2459 	}
2460 	rw_exit(&pwp->iports_lock);
2461 
2462 	mutex_enter(&pwp->config_lock);
2463 	if (pwp->configuring) {
2464 		mutex_exit(&pwp->config_lock);
2465 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2466 		    "%s: configuration already in progress", __func__);
2467 		return;
2468 	}
2469 
2470 	if (pmcs_acquire_scratch(pwp, B_FALSE)) {
2471 		mutex_exit(&pwp->config_lock);
2472 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2473 		    "%s: cannot allocate scratch", __func__);
2474 		SCHEDULE_WORK(pwp, PMCS_WORK_DISCOVER);
2475 		return;
2476 	}
2477 
2478 	pwp->configuring = 1;
2479 	pwp->config_changed = B_FALSE;
2480 	mutex_exit(&pwp->config_lock);
2481 
2482 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL, "Discovery begin");
2483 
2484 	/*
2485 	 * First, tell SCSA that we're beginning set operations.
2486 	 */
2487 	pmcs_begin_observations(pwp);
2488 
2489 	/*
2490 	 * The order of the following traversals is important.
2491 	 *
2492 	 * The first one checks for changed expanders.
2493 	 *
2494 	 * The second one aborts commands for dead devices and deregisters them.
2495 	 *
2496 	 * The third one clears the contents of dead expanders from the tree
2497 	 *
2498 	 * The fourth one clears now dead devices in expanders that remain.
2499 	 */
2500 
2501 	/*
2502 	 * 1. Check expanders marked changed (but not dead) to see if they still
2503 	 * have the same number of phys and the same SAS address. Mark them,
2504 	 * their subsidiary phys (if wide) and their descendents dead if
2505 	 * anything has changed. Check the devices they contain to see if
2506 	 * *they* have changed. If they've changed from type NOTHING we leave
2507 	 * them marked changed to be configured later (picking up a new SAS
2508 	 * address and link rate if possible). Otherwise, any change in type,
2509 	 * SAS address or removal of target role will cause us to mark them
2510 	 * (and their descendents) as dead (and cause any pending commands
2511 	 * and associated devices to be removed).
2512 	 *
2513 	 * NOTE: We don't want to bail on discovery if the config has
2514 	 * changed until *after* we run pmcs_kill_devices.
2515 	 */
2516 	root_phy = pwp->root_phys;
2517 	pmcs_check_expanders(pwp, root_phy);
2518 
2519 	/*
2520 	 * 2. Descend the tree looking for dead devices and kill them
2521 	 * by aborting all active commands and then deregistering them.
2522 	 */
2523 	if (pmcs_kill_devices(pwp, root_phy)) {
2524 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2525 		    "%s: pmcs_kill_devices failed!", __func__);
2526 	}
2527 
2528 	/*
2529 	 * 3. Check for dead expanders and remove their children from the tree.
2530 	 * By the time we get here, the devices and commands for them have
2531 	 * already been terminated and removed.
2532 	 *
2533 	 * We do this independent of the configuration count changing so we can
2534 	 * free any dead device PHYs that were discovered while checking
2535 	 * expanders. We ignore any subsidiary phys as pmcs_clear_expander
2536 	 * will take care of those.
2537 	 *
2538 	 * NOTE: pmcs_clear_expander requires softstate lock
2539 	 */
2540 	mutex_enter(&pwp->lock);
2541 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
2542 		/*
2543 		 * Call pmcs_clear_expander for every root PHY.  It will
2544 		 * recurse and determine which (if any) expanders actually
2545 		 * need to be cleared.
2546 		 */
2547 		pmcs_lock_phy(pptr);
2548 		pmcs_clear_expander(pwp, pptr, 0);
2549 		pmcs_unlock_phy(pptr);
2550 	}
2551 	mutex_exit(&pwp->lock);
2552 
2553 	/*
2554 	 * 4. Check for dead devices and nullify them. By the time we get here,
2555 	 * the devices and commands for them have already been terminated
2556 	 * and removed. This is different from step 2 in that this just nulls
2557 	 * phys that are part of expanders that are still here but used to
2558 	 * be something but are no longer something (e.g., after a pulled
2559 	 * disk drive). Note that dead expanders had their contained phys
2560 	 * removed from the tree- here, the expanders themselves are
2561 	 * nullified (unless they were removed by being contained in another
2562 	 * expander phy).
2563 	 */
2564 	pmcs_clear_phys(pwp, root_phy);
2565 
2566 	/*
2567 	 * 5. Now check for and configure new devices.
2568 	 */
2569 	if (pmcs_configure_new_devices(pwp, root_phy)) {
2570 		goto restart;
2571 	}
2572 
2573 out:
2574 	DTRACE_PROBE2(pmcs__discover__exit, ulong_t, pwp->work_flags,
2575 	    boolean_t, pwp->config_changed);
2576 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL, "Discovery end");
2577 
2578 	mutex_enter(&pwp->config_lock);
2579 
2580 	if (pwp->config_changed == B_FALSE) {
2581 		/*
2582 		 * Observation is stable, report what we currently see to
2583 		 * the tgtmaps for delta processing. Start by setting
2584 		 * BEGIN on all tgtmaps.
2585 		 */
2586 		mutex_exit(&pwp->config_lock);
2587 		if (pmcs_report_observations(pwp) == B_FALSE) {
2588 			goto restart;
2589 		}
2590 		mutex_enter(&pwp->config_lock);
2591 	} else {
2592 		/*
2593 		 * If config_changed is TRUE, we need to reschedule
2594 		 * discovery now.
2595 		 */
2596 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2597 		    "%s: Config has changed, will re-run discovery", __func__);
2598 		SCHEDULE_WORK(pwp, PMCS_WORK_DISCOVER);
2599 	}
2600 
2601 	pmcs_release_scratch(pwp);
2602 	if (!pwp->quiesced) {
2603 		pwp->blocked = 0;
2604 	}
2605 	pwp->configuring = 0;
2606 	cv_signal(&pwp->config_cv);
2607 	mutex_exit(&pwp->config_lock);
2608 
2609 #ifdef DEBUG
2610 	pptr = pmcs_find_phy_needing_work(pwp, pwp->root_phys);
2611 	if (pptr != NULL) {
2612 		if (!WORK_IS_SCHEDULED(pwp, PMCS_WORK_DISCOVER)) {
2613 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
2614 			    "PHY %s dead=%d changed=%d configured=%d "
2615 			    "but no work scheduled", pptr->path, pptr->dead,
2616 			    pptr->changed, pptr->configured);
2617 		}
2618 		pmcs_unlock_phy(pptr);
2619 	}
2620 #endif
2621 
2622 	return;
2623 
2624 restart:
2625 	/* Clean up and restart discovery */
2626 	pmcs_release_scratch(pwp);
2627 	pmcs_flush_observations(pwp);
2628 	mutex_enter(&pwp->config_lock);
2629 	pwp->configuring = 0;
2630 	cv_signal(&pwp->config_cv);
2631 	RESTART_DISCOVERY_LOCKED(pwp);
2632 	mutex_exit(&pwp->config_lock);
2633 }
2634 
2635 /*
2636  * Return any PHY that needs to have scheduled work done.  The PHY is returned
2637  * locked.
2638  */
2639 static pmcs_phy_t *
2640 pmcs_find_phy_needing_work(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
2641 {
2642 	pmcs_phy_t *cphyp, *pnext;
2643 
2644 	while (pptr) {
2645 		pmcs_lock_phy(pptr);
2646 
2647 		if (pptr->changed || (pptr->dead && pptr->valid_device_id)) {
2648 			return (pptr);
2649 		}
2650 
2651 		pnext = pptr->sibling;
2652 
2653 		if (pptr->children) {
2654 			cphyp = pptr->children;
2655 			pmcs_unlock_phy(pptr);
2656 			cphyp = pmcs_find_phy_needing_work(pwp, cphyp);
2657 			if (cphyp) {
2658 				return (cphyp);
2659 			}
2660 		} else {
2661 			pmcs_unlock_phy(pptr);
2662 		}
2663 
2664 		pptr = pnext;
2665 	}
2666 
2667 	return (NULL);
2668 }
2669 
2670 /*
2671  * We may (or may not) report observations to SCSA.  This is prefaced by
2672  * issuing a set_begin for each iport target map.
2673  */
2674 static void
2675 pmcs_begin_observations(pmcs_hw_t *pwp)
2676 {
2677 	pmcs_iport_t		*iport;
2678 	scsi_hba_tgtmap_t	*tgtmap;
2679 
2680 	rw_enter(&pwp->iports_lock, RW_READER);
2681 	for (iport = list_head(&pwp->iports); iport != NULL;
2682 	    iport = list_next(&pwp->iports, iport)) {
2683 		/*
2684 		 * Unless we have at least one phy up, skip this iport.
2685 		 * Note we don't need to lock the iport for report_skip
2686 		 * since it is only used here.  We are doing the skip so that
2687 		 * the phymap and iportmap stabilization times are honored -
2688 		 * giving us the ability to recover port operation within the
2689 		 * stabilization time without unconfiguring targets using the
2690 		 * port.
2691 		 */
2692 		if (!sas_phymap_uahasphys(pwp->hss_phymap, iport->ua)) {
2693 			iport->report_skip = 1;
2694 			continue;		/* skip set_begin */
2695 		}
2696 		iport->report_skip = 0;
2697 
2698 		tgtmap = iport->iss_tgtmap;
2699 		ASSERT(tgtmap);
2700 		if (scsi_hba_tgtmap_set_begin(tgtmap) != DDI_SUCCESS) {
2701 			pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL,
2702 			    "%s: cannot set_begin tgtmap ", __func__);
2703 			rw_exit(&pwp->iports_lock);
2704 			return;
2705 		}
2706 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL,
2707 		    "%s: set begin on tgtmap [0x%p]", __func__, (void *)tgtmap);
2708 	}
2709 	rw_exit(&pwp->iports_lock);
2710 }
2711 
2712 /*
2713  * Tell SCSA to flush the observations we've already sent (if any), as they
2714  * are no longer valid.
2715  */
2716 static void
2717 pmcs_flush_observations(pmcs_hw_t *pwp)
2718 {
2719 	pmcs_iport_t		*iport;
2720 	scsi_hba_tgtmap_t	*tgtmap;
2721 
2722 	rw_enter(&pwp->iports_lock, RW_READER);
2723 	for (iport = list_head(&pwp->iports); iport != NULL;
2724 	    iport = list_next(&pwp->iports, iport)) {
2725 		/*
2726 		 * Skip this iport if it has no PHYs up.
2727 		 */
2728 		if (!sas_phymap_uahasphys(pwp->hss_phymap, iport->ua)) {
2729 			continue;
2730 		}
2731 
2732 		tgtmap = iport->iss_tgtmap;
2733 		ASSERT(tgtmap);
2734 		if (scsi_hba_tgtmap_set_flush(tgtmap) != DDI_SUCCESS) {
2735 			pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL,
2736 			    "%s: Failed set_flush on tgtmap 0x%p", __func__,
2737 			    (void *)tgtmap);
2738 		} else {
2739 			pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL,
2740 			    "%s: set flush on tgtmap 0x%p", __func__,
2741 			    (void *)tgtmap);
2742 		}
2743 	}
2744 	rw_exit(&pwp->iports_lock);
2745 }
2746 
2747 /*
2748  * Report current observations to SCSA.
2749  */
2750 static boolean_t
2751 pmcs_report_observations(pmcs_hw_t *pwp)
2752 {
2753 	pmcs_iport_t		*iport;
2754 	scsi_hba_tgtmap_t	*tgtmap;
2755 	char			*ap;
2756 	pmcs_phy_t		*pptr;
2757 	uint64_t		wwn;
2758 
2759 	/*
2760 	 * Observation is stable, report what we currently see to the tgtmaps
2761 	 * for delta processing.
2762 	 */
2763 	pptr = pwp->root_phys;
2764 
2765 	while (pptr) {
2766 		pmcs_lock_phy(pptr);
2767 
2768 		/*
2769 		 * Skip PHYs that have nothing attached or are dead.
2770 		 */
2771 		if ((pptr->dtype == NOTHING) || pptr->dead) {
2772 			pmcs_unlock_phy(pptr);
2773 			pptr = pptr->sibling;
2774 			continue;
2775 		}
2776 
2777 		if (pptr->changed) {
2778 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
2779 			    "%s: oops, PHY %s changed; restart discovery",
2780 			    __func__, pptr->path);
2781 			pmcs_unlock_phy(pptr);
2782 			return (B_FALSE);
2783 		}
2784 
2785 		/*
2786 		 * Get the iport for this root PHY, then call the helper
2787 		 * to report observations for this iport's targets
2788 		 */
2789 		wwn = pmcs_barray2wwn(pptr->sas_address);
2790 		pmcs_unlock_phy(pptr);
2791 		iport = pmcs_get_iport_by_wwn(pwp, wwn);
2792 		if (iport == NULL) {
2793 			/* No iport for this tgt */
2794 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
2795 			    "%s: no iport for this target", __func__);
2796 			pptr = pptr->sibling;
2797 			continue;
2798 		}
2799 
2800 		pmcs_lock_phy(pptr);
2801 		if (!iport->report_skip) {
2802 			if (pmcs_report_iport_observations(
2803 			    pwp, iport, pptr) == B_FALSE) {
2804 				pmcs_rele_iport(iport);
2805 				pmcs_unlock_phy(pptr);
2806 				return (B_FALSE);
2807 			}
2808 		}
2809 		pmcs_rele_iport(iport);
2810 		pmcs_unlock_phy(pptr);
2811 		pptr = pptr->sibling;
2812 	}
2813 
2814 	/*
2815 	 * The observation is complete, end sets. Note we will skip any
2816 	 * iports that are active, but have no PHYs in them (i.e. awaiting
2817 	 * unconfigure). Set to restart discovery if we find this.
2818 	 */
2819 	rw_enter(&pwp->iports_lock, RW_READER);
2820 	for (iport = list_head(&pwp->iports);
2821 	    iport != NULL;
2822 	    iport = list_next(&pwp->iports, iport)) {
2823 
2824 		if (iport->report_skip)
2825 			continue;		/* skip set_end */
2826 
2827 		tgtmap = iport->iss_tgtmap;
2828 		ASSERT(tgtmap);
2829 		if (scsi_hba_tgtmap_set_end(tgtmap, 0) != DDI_SUCCESS) {
2830 			pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL,
2831 			    "%s: cannot set_end tgtmap ", __func__);
2832 			rw_exit(&pwp->iports_lock);
2833 			return (B_FALSE);
2834 		}
2835 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, NULL, NULL,
2836 		    "%s: set end on tgtmap [0x%p]", __func__, (void *)tgtmap);
2837 	}
2838 
2839 	/*
2840 	 * Now that discovery is complete, set up the necessary
2841 	 * DDI properties on each iport node.
2842 	 */
2843 	for (iport = list_head(&pwp->iports); iport != NULL;
2844 	    iport = list_next(&pwp->iports, iport)) {
2845 		/* Set up the 'attached-port' property on the iport */
2846 		ap = kmem_zalloc(PMCS_MAX_UA_SIZE, KM_SLEEP);
2847 		mutex_enter(&iport->lock);
2848 		pptr = iport->pptr;
2849 		mutex_exit(&iport->lock);
2850 		if (pptr == NULL) {
2851 			/*
2852 			 * This iport is down, but has not been
2853 			 * removed from our list (unconfigured).
2854 			 * Set our value to '0'.
2855 			 */
2856 			(void) snprintf(ap, 1, "%s", "0");
2857 		} else {
2858 			/* Otherwise, set it to remote phy's wwn */
2859 			pmcs_lock_phy(pptr);
2860 			wwn = pmcs_barray2wwn(pptr->sas_address);
2861 			(void) scsi_wwn_to_wwnstr(wwn, 1, ap);
2862 			pmcs_unlock_phy(pptr);
2863 		}
2864 		if (ndi_prop_update_string(DDI_DEV_T_NONE, iport->dip,
2865 		    SCSI_ADDR_PROP_ATTACHED_PORT, ap) != DDI_SUCCESS) {
2866 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL, "%s: Failed "
2867 			    "to set prop ("SCSI_ADDR_PROP_ATTACHED_PORT")",
2868 			    __func__);
2869 		}
2870 		kmem_free(ap, PMCS_MAX_UA_SIZE);
2871 	}
2872 	rw_exit(&pwp->iports_lock);
2873 
2874 	return (B_TRUE);
2875 }
2876 
2877 /*
2878  * Report observations into a particular iport's target map
2879  *
2880  * Called with phyp (and all descendents) locked
2881  */
2882 static boolean_t
2883 pmcs_report_iport_observations(pmcs_hw_t *pwp, pmcs_iport_t *iport,
2884     pmcs_phy_t *phyp)
2885 {
2886 	pmcs_phy_t		*lphyp;
2887 	scsi_hba_tgtmap_t	*tgtmap;
2888 	scsi_tgtmap_tgt_type_t	tgt_type;
2889 	char			*ua;
2890 	uint64_t		wwn;
2891 
2892 	tgtmap = iport->iss_tgtmap;
2893 	ASSERT(tgtmap);
2894 
2895 	lphyp = phyp;
2896 	while (lphyp) {
2897 		switch (lphyp->dtype) {
2898 		default:		/* Skip unknown PHYs. */
2899 			/* for non-root phys, skip to sibling */
2900 			goto next_phy;
2901 
2902 		case SATA:
2903 		case SAS:
2904 			tgt_type = SCSI_TGT_SCSI_DEVICE;
2905 			break;
2906 
2907 		case EXPANDER:
2908 			tgt_type = SCSI_TGT_SMP_DEVICE;
2909 			break;
2910 		}
2911 
2912 		if (lphyp->dead || !lphyp->configured) {
2913 			goto next_phy;
2914 		}
2915 
2916 		/*
2917 		 * Validate the PHY's SAS address
2918 		 */
2919 		if (((lphyp->sas_address[0] & 0xf0) >> 4) != NAA_IEEE_REG) {
2920 			pmcs_prt(pwp, PMCS_PRT_ERR, lphyp, NULL,
2921 			    "PHY 0x%p (%s) has invalid SAS address; "
2922 			    "will not enumerate", (void *)lphyp, lphyp->path);
2923 			goto next_phy;
2924 		}
2925 
2926 		wwn = pmcs_barray2wwn(lphyp->sas_address);
2927 		ua = scsi_wwn_to_wwnstr(wwn, 1, NULL);
2928 
2929 		pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP, lphyp, NULL,
2930 		    "iport_observation: adding %s on tgtmap [0x%p] phy [0x%p]",
2931 		    ua, (void *)tgtmap, (void*)lphyp);
2932 
2933 		if (scsi_hba_tgtmap_set_add(tgtmap, tgt_type, ua, NULL) !=
2934 		    DDI_SUCCESS) {
2935 			pmcs_prt(pwp, PMCS_PRT_DEBUG_MAP,  NULL, NULL,
2936 			    "%s: failed to add address %s", __func__, ua);
2937 			scsi_free_wwnstr(ua);
2938 			return (B_FALSE);
2939 		}
2940 		scsi_free_wwnstr(ua);
2941 
2942 		if (lphyp->children) {
2943 			if (pmcs_report_iport_observations(pwp, iport,
2944 			    lphyp->children) == B_FALSE) {
2945 				return (B_FALSE);
2946 			}
2947 		}
2948 
2949 		/* for non-root phys, report siblings too */
2950 next_phy:
2951 		if (IS_ROOT_PHY(lphyp)) {
2952 			lphyp = NULL;
2953 		} else {
2954 			lphyp = lphyp->sibling;
2955 		}
2956 	}
2957 
2958 	return (B_TRUE);
2959 }
2960 
2961 /*
2962  * Check for and configure new devices.
2963  *
2964  * If the changed device is a SATA device, add a SATA device.
2965  *
2966  * If the changed device is a SAS device, add a SAS device.
2967  *
2968  * If the changed device is an EXPANDER device, do a REPORT
2969  * GENERAL SMP command to find out the number of contained phys.
2970  *
2971  * For each number of contained phys, allocate a phy, do a
2972  * DISCOVERY SMP command to find out what kind of device it
2973  * is and add it to the linked list of phys on the *next* level.
2974  *
2975  * NOTE: pptr passed in by the caller will be a root PHY
2976  */
2977 static int
2978 pmcs_configure_new_devices(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
2979 {
2980 	int rval = 0;
2981 	pmcs_iport_t *iport;
2982 	pmcs_phy_t *pnext, *orig_pptr = pptr, *root_phy, *pchild;
2983 	uint64_t wwn;
2984 
2985 	/*
2986 	 * First, walk through each PHY at this level
2987 	 */
2988 	while (pptr) {
2989 		pmcs_lock_phy(pptr);
2990 		pnext = pptr->sibling;
2991 
2992 		/*
2993 		 * Set the new dtype if it has changed
2994 		 */
2995 		if ((pptr->pend_dtype != NEW) &&
2996 		    (pptr->pend_dtype != pptr->dtype)) {
2997 			pptr->dtype = pptr->pend_dtype;
2998 		}
2999 
3000 		if (pptr->changed == 0 || pptr->dead || pptr->configured) {
3001 			goto next_phy;
3002 		}
3003 
3004 		/* Confirm that this iport is configured */
3005 		root_phy = pmcs_get_root_phy(pptr);
3006 		wwn = pmcs_barray2wwn(root_phy->sas_address);
3007 		pmcs_unlock_phy(pptr);
3008 		iport = pmcs_get_iport_by_wwn(pwp, wwn);
3009 		if (iport == NULL) {
3010 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, NULL,
3011 			    "%s: iport not yet configured, "
3012 			    "retry discovery", __func__);
3013 			pnext = NULL;
3014 			rval = -1;
3015 			pmcs_lock_phy(pptr);
3016 			goto next_phy;
3017 		}
3018 
3019 		pmcs_lock_phy(pptr);
3020 		switch (pptr->dtype) {
3021 		case NOTHING:
3022 			pptr->changed = 0;
3023 			break;
3024 		case SATA:
3025 		case SAS:
3026 			pptr->iport = iport;
3027 			pmcs_new_tport(pwp, pptr);
3028 			break;
3029 		case EXPANDER:
3030 			pmcs_configure_expander(pwp, pptr, iport);
3031 			break;
3032 		}
3033 		pmcs_rele_iport(iport);
3034 
3035 		mutex_enter(&pwp->config_lock);
3036 		if (pwp->config_changed) {
3037 			mutex_exit(&pwp->config_lock);
3038 			pnext = NULL;
3039 			goto next_phy;
3040 		}
3041 		mutex_exit(&pwp->config_lock);
3042 
3043 next_phy:
3044 		pmcs_unlock_phy(pptr);
3045 		pptr = pnext;
3046 	}
3047 
3048 	if (rval != 0) {
3049 		return (rval);
3050 	}
3051 
3052 	/*
3053 	 * Now walk through each PHY again, recalling ourselves if they
3054 	 * have children
3055 	 */
3056 	pptr = orig_pptr;
3057 	while (pptr) {
3058 		pmcs_lock_phy(pptr);
3059 		pnext = pptr->sibling;
3060 		pchild = pptr->children;
3061 		pmcs_unlock_phy(pptr);
3062 
3063 		if (pchild) {
3064 			rval = pmcs_configure_new_devices(pwp, pchild);
3065 			if (rval != 0) {
3066 				break;
3067 			}
3068 		}
3069 
3070 		pptr = pnext;
3071 	}
3072 
3073 	return (rval);
3074 }
3075 
3076 /*
3077  * Set all phys and descendent phys as changed if changed == B_TRUE, otherwise
3078  * mark them all as not changed.
3079  *
3080  * Called with parent PHY locked.
3081  */
3082 void
3083 pmcs_set_changed(pmcs_hw_t *pwp, pmcs_phy_t *parent, boolean_t changed,
3084     int level)
3085 {
3086 	pmcs_phy_t *pptr;
3087 
3088 	if (level == 0) {
3089 		if (changed) {
3090 			PHY_CHANGED(pwp, parent);
3091 		} else {
3092 			parent->changed = 0;
3093 		}
3094 		if (parent->dtype == EXPANDER && parent->level) {
3095 			parent->width = 1;
3096 		}
3097 		if (parent->children) {
3098 			pmcs_set_changed(pwp, parent->children, changed,
3099 			    level + 1);
3100 		}
3101 	} else {
3102 		pptr = parent;
3103 		while (pptr) {
3104 			if (changed) {
3105 				PHY_CHANGED(pwp, pptr);
3106 			} else {
3107 				pptr->changed = 0;
3108 			}
3109 			if (pptr->dtype == EXPANDER && pptr->level) {
3110 				pptr->width = 1;
3111 			}
3112 			if (pptr->children) {
3113 				pmcs_set_changed(pwp, pptr->children, changed,
3114 				    level + 1);
3115 			}
3116 			pptr = pptr->sibling;
3117 		}
3118 	}
3119 }
3120 
3121 /*
3122  * Take the passed phy mark it and its descendants as dead.
3123  * Fire up reconfiguration to abort commands and bury it.
3124  *
3125  * Called with the parent PHY locked.
3126  */
3127 void
3128 pmcs_kill_changed(pmcs_hw_t *pwp, pmcs_phy_t *parent, int level)
3129 {
3130 	pmcs_phy_t *pptr = parent;
3131 
3132 	while (pptr) {
3133 		pptr->link_rate = 0;
3134 		pptr->abort_sent = 0;
3135 		pptr->abort_pending = 1;
3136 		SCHEDULE_WORK(pwp, PMCS_WORK_ABORT_HANDLE);
3137 		pptr->need_rl_ext = 0;
3138 
3139 		if (pptr->dead == 0) {
3140 			PHY_CHANGED(pwp, pptr);
3141 			RESTART_DISCOVERY(pwp);
3142 		}
3143 
3144 		pptr->dead = 1;
3145 
3146 		if (pptr->children) {
3147 			pmcs_kill_changed(pwp, pptr->children, level + 1);
3148 		}
3149 
3150 		/*
3151 		 * Only kill siblings at level > 0
3152 		 */
3153 		if (level == 0) {
3154 			return;
3155 		}
3156 
3157 		pptr = pptr->sibling;
3158 	}
3159 }
3160 
3161 /*
3162  * Go through every PHY and clear any that are dead (unless they're expanders)
3163  */
3164 static void
3165 pmcs_clear_phys(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
3166 {
3167 	pmcs_phy_t *pnext, *phyp;
3168 
3169 	phyp = pptr;
3170 	while (phyp) {
3171 		if (IS_ROOT_PHY(phyp)) {
3172 			pmcs_lock_phy(phyp);
3173 		}
3174 
3175 		if ((phyp->dtype != EXPANDER) && phyp->dead) {
3176 			pmcs_clear_phy(pwp, phyp);
3177 		}
3178 
3179 		if (phyp->children) {
3180 			pmcs_clear_phys(pwp, phyp->children);
3181 		}
3182 
3183 		pnext = phyp->sibling;
3184 
3185 		if (IS_ROOT_PHY(phyp)) {
3186 			pmcs_unlock_phy(phyp);
3187 		}
3188 
3189 		phyp = pnext;
3190 	}
3191 }
3192 
3193 /*
3194  * Clear volatile parts of a phy.  Called with PHY locked.
3195  */
3196 void
3197 pmcs_clear_phy(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
3198 {
3199 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL, "%s: %s",
3200 	    __func__, pptr->path);
3201 	ASSERT(mutex_owned(&pptr->phy_lock));
3202 	/* keep sibling */
3203 	/* keep children */
3204 	/* keep parent */
3205 	pptr->device_id = PMCS_INVALID_DEVICE_ID;
3206 	/* keep hw_event_ack */
3207 	pptr->ncphy = 0;
3208 	/* keep phynum */
3209 	pptr->width = 0;
3210 	pptr->ds_recovery_retries = 0;
3211 	pptr->ds_prev_good_recoveries = 0;
3212 	pptr->last_good_recovery = 0;
3213 	pptr->prev_recovery = 0;
3214 
3215 	/* keep dtype */
3216 	pptr->config_stop = 0;
3217 	pptr->spinup_hold = 0;
3218 	pptr->atdt = 0;
3219 	/* keep portid */
3220 	pptr->link_rate = 0;
3221 	pptr->valid_device_id = 0;
3222 	pptr->abort_sent = 0;
3223 	pptr->abort_pending = 0;
3224 	pptr->need_rl_ext = 0;
3225 	pptr->subsidiary = 0;
3226 	pptr->configured = 0;
3227 	pptr->deregister_wait = 0;
3228 	pptr->reenumerate = 0;
3229 	/* Only mark dead if it's not a root PHY and its dtype isn't NOTHING */
3230 	/* XXX: What about directly attached disks? */
3231 	if (!IS_ROOT_PHY(pptr) && (pptr->dtype != NOTHING))
3232 		pptr->dead = 1;
3233 	pptr->changed = 0;
3234 	/* keep SAS address */
3235 	/* keep path */
3236 	/* keep ref_count */
3237 	/* Don't clear iport on root PHYs - they are handled in pmcs_intr.c */
3238 	if (!IS_ROOT_PHY(pptr)) {
3239 		pptr->last_iport = pptr->iport;
3240 		pptr->iport = NULL;
3241 	}
3242 	/* keep target */
3243 }
3244 
3245 /*
3246  * Allocate softstate for this target if there isn't already one.  If there
3247  * is, just redo our internal configuration.  If it is actually "new", we'll
3248  * soon get a tran_tgt_init for it.
3249  *
3250  * Called with PHY locked.
3251  */
3252 static void
3253 pmcs_new_tport(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
3254 {
3255 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL, "%s: phy 0x%p @ %s",
3256 	    __func__, (void *)pptr, pptr->path);
3257 
3258 	if (pmcs_configure_phy(pwp, pptr) == B_FALSE) {
3259 		/*
3260 		 * If the config failed, mark the PHY as changed.
3261 		 */
3262 		PHY_CHANGED(pwp, pptr);
3263 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3264 		    "%s: pmcs_configure_phy failed for phy 0x%p", __func__,
3265 		    (void *)pptr);
3266 		return;
3267 	}
3268 
3269 	/* Mark PHY as no longer changed */
3270 	pptr->changed = 0;
3271 
3272 	/*
3273 	 * If the PHY has no target pointer:
3274 	 *
3275 	 * If it's a root PHY, see if another PHY in the iport holds the
3276 	 * target pointer (primary PHY changed).  If so, move it over.
3277 	 *
3278 	 * If it's not a root PHY, see if there's a PHY on the dead_phys
3279 	 * list that matches.
3280 	 */
3281 	if (pptr->target == NULL) {
3282 		if (IS_ROOT_PHY(pptr)) {
3283 			pmcs_phy_t *rphy = pwp->root_phys;
3284 
3285 			while (rphy) {
3286 				if (rphy == pptr) {
3287 					rphy = rphy->sibling;
3288 					continue;
3289 				}
3290 
3291 				mutex_enter(&rphy->phy_lock);
3292 				if ((rphy->iport == pptr->iport) &&
3293 				    (rphy->target != NULL)) {
3294 					mutex_enter(&rphy->target->statlock);
3295 					pptr->target = rphy->target;
3296 					rphy->target = NULL;
3297 					pptr->target->phy = pptr;
3298 					/* The target is now on pptr */
3299 					mutex_exit(&pptr->target->statlock);
3300 					mutex_exit(&rphy->phy_lock);
3301 					pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG,
3302 					    pptr, pptr->target,
3303 					    "%s: Moved target from %s to %s",
3304 					    __func__, rphy->path, pptr->path);
3305 					break;
3306 				}
3307 				mutex_exit(&rphy->phy_lock);
3308 
3309 				rphy = rphy->sibling;
3310 			}
3311 		} else {
3312 			pmcs_reap_dead_phy(pptr);
3313 		}
3314 	}
3315 
3316 	/*
3317 	 * Only assign the device if there is a target for this PHY with a
3318 	 * matching SAS address.  If an iport is disconnected from one piece
3319 	 * of storage and connected to another within the iport stabilization
3320 	 * time, we can get the PHY/target mismatch situation.
3321 	 *
3322 	 * Otherwise, it'll get done in tran_tgt_init.
3323 	 */
3324 	if (pptr->target) {
3325 		mutex_enter(&pptr->target->statlock);
3326 		if (pmcs_phy_target_match(pptr) == B_FALSE) {
3327 			mutex_exit(&pptr->target->statlock);
3328 			if (!IS_ROOT_PHY(pptr)) {
3329 				pmcs_dec_phy_ref_count(pptr);
3330 			}
3331 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
3332 			    "%s: Not assigning existing tgt %p for PHY %p "
3333 			    "(WWN mismatch)", __func__, (void *)pptr->target,
3334 			    (void *)pptr);
3335 			pptr->target = NULL;
3336 			return;
3337 		}
3338 
3339 		if (!pmcs_assign_device(pwp, pptr->target)) {
3340 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, pptr->target,
3341 			    "%s: pmcs_assign_device failed for target 0x%p",
3342 			    __func__, (void *)pptr->target);
3343 		}
3344 		mutex_exit(&pptr->target->statlock);
3345 	}
3346 }
3347 
3348 /*
3349  * Called with PHY lock held.
3350  */
3351 static boolean_t
3352 pmcs_configure_phy(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
3353 {
3354 	char *dtype;
3355 
3356 	ASSERT(mutex_owned(&pptr->phy_lock));
3357 
3358 	/*
3359 	 * Mark this device as no longer changed.
3360 	 */
3361 	pptr->changed = 0;
3362 
3363 	/*
3364 	 * If we don't have a device handle, get one.
3365 	 */
3366 	if (pmcs_get_device_handle(pwp, pptr)) {
3367 		return (B_FALSE);
3368 	}
3369 
3370 	pptr->configured = 1;
3371 
3372 	switch (pptr->dtype) {
3373 	case SAS:
3374 		dtype = "SAS";
3375 		break;
3376 	case SATA:
3377 		dtype = "SATA";
3378 		break;
3379 	case EXPANDER:
3380 		dtype = "SMP";
3381 		break;
3382 	default:
3383 		dtype = "???";
3384 	}
3385 
3386 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL, "config_dev: %s "
3387 	    "dev %s " SAS_ADDR_FMT " dev id 0x%x lr 0x%x", dtype, pptr->path,
3388 	    SAS_ADDR_PRT(pptr->sas_address), pptr->device_id, pptr->link_rate);
3389 
3390 	return (B_TRUE);
3391 }
3392 
3393 /*
3394  * Called with PHY locked
3395  */
3396 static void
3397 pmcs_configure_expander(pmcs_hw_t *pwp, pmcs_phy_t *pptr, pmcs_iport_t *iport)
3398 {
3399 	pmcs_phy_t *ctmp, *clist = NULL, *cnext;
3400 	int result, i, nphy = 0;
3401 	boolean_t root_phy = B_FALSE;
3402 
3403 	ASSERT(iport);
3404 
3405 	/*
3406 	 * Step 1- clear our "changed" bit. If we need to retry/restart due
3407 	 * to resource shortages, we'll set it again. While we're doing
3408 	 * configuration, other events may set it again as well.  If the PHY
3409 	 * is a root PHY and is currently marked as having changed, reset the
3410 	 * config_stop timer as well.
3411 	 */
3412 	if (IS_ROOT_PHY(pptr) && pptr->changed) {
3413 		pptr->config_stop = ddi_get_lbolt() +
3414 		    drv_usectohz(PMCS_MAX_CONFIG_TIME);
3415 	}
3416 	pptr->changed = 0;
3417 
3418 	/*
3419 	 * Step 2- make sure we don't overflow
3420 	 */
3421 	if (pptr->level == PMCS_MAX_XPND-1) {
3422 		pmcs_prt(pwp, PMCS_PRT_WARN, pptr, NULL,
3423 		    "%s: SAS expansion tree too deep", __func__);
3424 		return;
3425 	}
3426 
3427 	/*
3428 	 * Step 3- Check if this expander is part of a wide phy that has
3429 	 * already been configured.
3430 	 *
3431 	 * This is known by checking this level for another EXPANDER device
3432 	 * with the same SAS address and isn't already marked as a subsidiary
3433 	 * phy and a parent whose SAS address is the same as our SAS address
3434 	 * (if there are parents).
3435 	 */
3436 	if (!IS_ROOT_PHY(pptr)) {
3437 		/*
3438 		 * No need to lock the parent here because we're in discovery
3439 		 * and the only time a PHY's children pointer can change is
3440 		 * in discovery; either in pmcs_clear_expander (which has
3441 		 * already been called) or here, down below.  Plus, trying to
3442 		 * grab the parent's lock here can cause deadlock.
3443 		 */
3444 		ctmp = pptr->parent->children;
3445 	} else {
3446 		ctmp = pwp->root_phys;
3447 		root_phy = B_TRUE;
3448 	}
3449 
3450 	while (ctmp) {
3451 		/*
3452 		 * If we've checked all PHYs up to pptr, we stop. Otherwise,
3453 		 * we'll be checking for a primary PHY with a higher PHY
3454 		 * number than pptr, which will never happen.  The primary
3455 		 * PHY on non-root expanders will ALWAYS be the lowest
3456 		 * numbered PHY.
3457 		 */
3458 		if (ctmp == pptr) {
3459 			break;
3460 		}
3461 
3462 		/*
3463 		 * If pptr and ctmp are root PHYs, just grab the mutex on
3464 		 * ctmp.  No need to lock the entire tree.  If they are not
3465 		 * root PHYs, there is no need to lock since a non-root PHY's
3466 		 * SAS address and other characteristics can only change in
3467 		 * discovery anyway.
3468 		 */
3469 		if (root_phy) {
3470 			mutex_enter(&ctmp->phy_lock);
3471 		}
3472 
3473 		if (ctmp->dtype == EXPANDER && ctmp->width &&
3474 		    memcmp(ctmp->sas_address, pptr->sas_address, 8) == 0) {
3475 			int widephy = 0;
3476 			/*
3477 			 * If these phys are not root PHYs, compare their SAS
3478 			 * addresses too.
3479 			 */
3480 			if (!root_phy) {
3481 				if (memcmp(ctmp->parent->sas_address,
3482 				    pptr->parent->sas_address, 8) == 0) {
3483 					widephy = 1;
3484 				}
3485 			} else {
3486 				widephy = 1;
3487 			}
3488 			if (widephy) {
3489 				ctmp->width++;
3490 				pptr->subsidiary = 1;
3491 
3492 				/*
3493 				 * Update the primary PHY's attached-port-pm
3494 				 * and target-port-pm information with the info
3495 				 * from this subsidiary
3496 				 */
3497 				pmcs_update_phy_pm_props(ctmp,
3498 				    pptr->att_port_pm_tmp,
3499 				    pptr->tgt_port_pm_tmp, B_TRUE);
3500 
3501 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3502 				    "%s: PHY %s part of wide PHY %s "
3503 				    "(now %d wide)", __func__, pptr->path,
3504 				    ctmp->path, ctmp->width);
3505 				if (root_phy) {
3506 					mutex_exit(&ctmp->phy_lock);
3507 				}
3508 				return;
3509 			}
3510 		}
3511 
3512 		cnext = ctmp->sibling;
3513 		if (root_phy) {
3514 			mutex_exit(&ctmp->phy_lock);
3515 		}
3516 		ctmp = cnext;
3517 	}
3518 
3519 	/*
3520 	 * Step 4- If we don't have a device handle, get one.  Since this
3521 	 * is the primary PHY, make sure subsidiary is cleared.
3522 	 */
3523 	pptr->subsidiary = 0;
3524 	pptr->iport = iport;
3525 	if (pmcs_get_device_handle(pwp, pptr)) {
3526 		goto out;
3527 	}
3528 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL, "Config expander %s "
3529 	    SAS_ADDR_FMT " dev id 0x%x lr 0x%x", pptr->path,
3530 	    SAS_ADDR_PRT(pptr->sas_address), pptr->device_id, pptr->link_rate);
3531 
3532 	/*
3533 	 * Step 5- figure out how many phys are in this expander.
3534 	 */
3535 	nphy = pmcs_expander_get_nphy(pwp, pptr);
3536 	if (nphy <= 0) {
3537 		if (nphy == 0 && ddi_get_lbolt() < pptr->config_stop) {
3538 			PHY_CHANGED(pwp, pptr);
3539 			RESTART_DISCOVERY(pwp);
3540 		} else {
3541 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3542 			    "%s: Retries exhausted for %s, killing", __func__,
3543 			    pptr->path);
3544 			pptr->config_stop = 0;
3545 			pmcs_kill_changed(pwp, pptr, 0);
3546 		}
3547 		goto out;
3548 	}
3549 
3550 	/*
3551 	 * Step 6- Allocate a list of phys for this expander and figure out
3552 	 * what each one is.
3553 	 */
3554 	for (i = 0; i < nphy; i++) {
3555 		ctmp = kmem_cache_alloc(pwp->phy_cache, KM_SLEEP);
3556 		bzero(ctmp, sizeof (pmcs_phy_t));
3557 		ctmp->device_id = PMCS_INVALID_DEVICE_ID;
3558 		ctmp->sibling = clist;
3559 		ctmp->pend_dtype = NEW;	/* Init pending dtype */
3560 		ctmp->config_stop = ddi_get_lbolt() +
3561 		    drv_usectohz(PMCS_MAX_CONFIG_TIME);
3562 		clist = ctmp;
3563 	}
3564 
3565 	mutex_enter(&pwp->config_lock);
3566 	if (pwp->config_changed) {
3567 		RESTART_DISCOVERY_LOCKED(pwp);
3568 		mutex_exit(&pwp->config_lock);
3569 		/*
3570 		 * Clean up the newly allocated PHYs and return
3571 		 */
3572 		while (clist) {
3573 			ctmp = clist->sibling;
3574 			clist->target_addr = NULL;
3575 			kmem_cache_free(pwp->phy_cache, clist);
3576 			clist = ctmp;
3577 		}
3578 		return;
3579 	}
3580 	mutex_exit(&pwp->config_lock);
3581 
3582 	/*
3583 	 * Step 7- Now fill in the rest of the static portions of the phy.
3584 	 */
3585 	for (i = 0, ctmp = clist; ctmp; ctmp = ctmp->sibling, i++) {
3586 		ctmp->parent = pptr;
3587 		ctmp->pwp = pwp;
3588 		ctmp->level = pptr->level+1;
3589 		ctmp->portid = pptr->portid;
3590 		if (ctmp->tolerates_sas2) {
3591 			ASSERT(i < SAS2_PHYNUM_MAX);
3592 			ctmp->phynum = i & SAS2_PHYNUM_MASK;
3593 		} else {
3594 			ASSERT(i < SAS_PHYNUM_MAX);
3595 			ctmp->phynum = i & SAS_PHYNUM_MASK;
3596 		}
3597 		pmcs_phy_name(pwp, ctmp, ctmp->path, sizeof (ctmp->path));
3598 		pmcs_lock_phy(ctmp);
3599 	}
3600 
3601 	/*
3602 	 * Step 8- Discover things about each phy in the expander.
3603 	 */
3604 	for (i = 0, ctmp = clist; ctmp; ctmp = ctmp->sibling, i++) {
3605 		result = pmcs_expander_content_discover(pwp, pptr, ctmp);
3606 		if (result <= 0) {
3607 			if (ddi_get_lbolt() < pptr->config_stop) {
3608 				PHY_CHANGED(pwp, pptr);
3609 				RESTART_DISCOVERY(pwp);
3610 			} else {
3611 				pptr->config_stop = 0;
3612 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3613 				    "%s: Retries exhausted for %s, killing",
3614 				    __func__, pptr->path);
3615 				pmcs_kill_changed(pwp, pptr, 0);
3616 			}
3617 			goto out;
3618 		}
3619 
3620 		/* Set pend_dtype to dtype for 1st time initialization */
3621 		ctmp->pend_dtype = ctmp->dtype;
3622 	}
3623 
3624 	/*
3625 	 * Step 9: Install the new list on the next level. There should
3626 	 * typically be no children pointer on this PHY.  There is one known
3627 	 * case where this can happen, though.  If a root PHY goes down and
3628 	 * comes back up before discovery can run, we will fail to remove the
3629 	 * children from that PHY since it will no longer be marked dead.
3630 	 * However, in this case, all children should also be marked dead.  If
3631 	 * we see that, take those children and put them on the dead_phys list.
3632 	 */
3633 	if (pptr->children != NULL) {
3634 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
3635 		    "%s: Expander @ %s still has children: Clean up",
3636 		    __func__, pptr->path);
3637 		pmcs_add_dead_phys(pwp, pptr->children);
3638 	}
3639 
3640 	/*
3641 	 * Set the new children pointer for this expander
3642 	 */
3643 	pptr->children = clist;
3644 	clist = NULL;
3645 	pptr->ncphy = nphy;
3646 	pptr->configured = 1;
3647 
3648 	/*
3649 	 * We only set width if we're greater than level 0.
3650 	 */
3651 	if (pptr->level) {
3652 		pptr->width = 1;
3653 	}
3654 
3655 	/*
3656 	 * Now tell the rest of the world about us, as an SMP node.
3657 	 */
3658 	pptr->iport = iport;
3659 	pmcs_new_tport(pwp, pptr);
3660 
3661 out:
3662 	while (clist) {
3663 		ctmp = clist->sibling;
3664 		pmcs_unlock_phy(clist);
3665 		clist->target_addr = NULL;
3666 		kmem_cache_free(pwp->phy_cache, clist);
3667 		clist = ctmp;
3668 	}
3669 }
3670 
3671 /*
3672  * 2. Check expanders marked changed (but not dead) to see if they still have
3673  * the same number of phys and the same SAS address. Mark them, their subsidiary
3674  * phys (if wide) and their descendents dead if anything has changed. Check the
3675  * the devices they contain to see if *they* have changed. If they've changed
3676  * from type NOTHING we leave them marked changed to be configured later
3677  * (picking up a new SAS address and link rate if possible). Otherwise, any
3678  * change in type, SAS address or removal of target role will cause us to
3679  * mark them (and their descendents) as dead and cause any pending commands
3680  * and associated devices to be removed.
3681  *
3682  * Called with PHY (pptr) locked.
3683  */
3684 
3685 static void
3686 pmcs_check_expander(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
3687 {
3688 	int nphy, result;
3689 	pmcs_phy_t *ctmp, *local, *local_list = NULL, *local_tail = NULL;
3690 	boolean_t kill_changed, changed;
3691 
3692 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3693 	    "%s: check %s", __func__, pptr->path);
3694 
3695 	/*
3696 	 * Step 1: Mark phy as not changed. We will mark it changed if we need
3697 	 * to retry.
3698 	 */
3699 	pptr->changed = 0;
3700 
3701 	/*
3702 	 * Reset the config_stop time. Although we're not actually configuring
3703 	 * anything here, we do want some indication of when to give up trying
3704 	 * if we can't communicate with the expander.
3705 	 */
3706 	pptr->config_stop = ddi_get_lbolt() +
3707 	    drv_usectohz(PMCS_MAX_CONFIG_TIME);
3708 
3709 	/*
3710 	 * Step 2: Figure out how many phys are in this expander. If
3711 	 * pmcs_expander_get_nphy returns 0 we ran out of resources,
3712 	 * so reschedule and try later. If it returns another error,
3713 	 * just return.
3714 	 */
3715 	nphy = pmcs_expander_get_nphy(pwp, pptr);
3716 	if (nphy <= 0) {
3717 		if ((nphy == 0) && (ddi_get_lbolt() < pptr->config_stop)) {
3718 			PHY_CHANGED(pwp, pptr);
3719 			RESTART_DISCOVERY(pwp);
3720 		} else {
3721 			pptr->config_stop = 0;
3722 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3723 			    "%s: Retries exhausted for %s, killing", __func__,
3724 			    pptr->path);
3725 			pmcs_kill_changed(pwp, pptr, 0);
3726 		}
3727 		return;
3728 	}
3729 
3730 	/*
3731 	 * Step 3: If the number of phys don't agree, kill the old sub-tree.
3732 	 */
3733 	if (nphy != pptr->ncphy) {
3734 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3735 		    "%s: number of contained phys for %s changed from %d to %d",
3736 		    __func__, pptr->path, pptr->ncphy, nphy);
3737 		/*
3738 		 * Force a rescan of this expander after dead contents
3739 		 * are cleared and removed.
3740 		 */
3741 		pmcs_kill_changed(pwp, pptr, 0);
3742 		return;
3743 	}
3744 
3745 	/*
3746 	 * Step 4: if we're at the bottom of the stack, we're done
3747 	 * (we can't have any levels below us)
3748 	 */
3749 	if (pptr->level == PMCS_MAX_XPND-1) {
3750 		return;
3751 	}
3752 
3753 	/*
3754 	 * Step 5: Discover things about each phy in this expander.  We do
3755 	 * this by walking the current list of contained phys and doing a
3756 	 * content discovery for it to a local phy.
3757 	 */
3758 	ctmp = pptr->children;
3759 	ASSERT(ctmp);
3760 	if (ctmp == NULL) {
3761 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3762 		    "%s: No children attached to expander @ %s?", __func__,
3763 		    pptr->path);
3764 		return;
3765 	}
3766 
3767 	while (ctmp) {
3768 		/*
3769 		 * Allocate a local PHY to contain the proposed new contents
3770 		 * and link it to the rest of the local PHYs so that they
3771 		 * can all be freed later.
3772 		 */
3773 		local = pmcs_clone_phy(ctmp);
3774 
3775 		if (local_list == NULL) {
3776 			local_list = local;
3777 			local_tail = local;
3778 		} else {
3779 			local_tail->sibling = local;
3780 			local_tail = local;
3781 		}
3782 
3783 		/*
3784 		 * Need to lock the local PHY since pmcs_expander_content_
3785 		 * discovery may call pmcs_clear_phy on it, which expects
3786 		 * the PHY to be locked.
3787 		 */
3788 		pmcs_lock_phy(local);
3789 		result = pmcs_expander_content_discover(pwp, pptr, local);
3790 		pmcs_unlock_phy(local);
3791 		if (result <= 0) {
3792 			if (ddi_get_lbolt() < pptr->config_stop) {
3793 				PHY_CHANGED(pwp, pptr);
3794 				RESTART_DISCOVERY(pwp);
3795 			} else {
3796 				pptr->config_stop = 0;
3797 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
3798 				    "%s: Retries exhausted for %s, killing",
3799 				    __func__, pptr->path);
3800 				pmcs_kill_changed(pwp, pptr, 0);
3801 			}
3802 
3803 			/*
3804 			 * Release all the local PHYs that we allocated.
3805 			 */
3806 			pmcs_free_phys(pwp, local_list);
3807 			return;
3808 		}
3809 
3810 		ctmp = ctmp->sibling;
3811 	}
3812 
3813 	/*
3814 	 * Step 6: Compare the local PHY's contents to our current PHY.  If
3815 	 * there are changes, take the appropriate action.
3816 	 * This is done in two steps (step 5 above, and 6 here) so that if we
3817 	 * have to bail during this process (e.g. pmcs_expander_content_discover
3818 	 * fails), we haven't actually changed the state of any of the real
3819 	 * PHYs.  Next time we come through here, we'll be starting over from
3820 	 * scratch.  This keeps us from marking a changed PHY as no longer
3821 	 * changed, but then having to bail only to come back next time and
3822 	 * think that the PHY hadn't changed.  If this were to happen, we
3823 	 * would fail to properly configure the device behind this PHY.
3824 	 */
3825 	local = local_list;
3826 	ctmp = pptr->children;
3827 
3828 	while (ctmp) {
3829 		changed = B_FALSE;
3830 		kill_changed = B_FALSE;
3831 
3832 		/*
3833 		 * We set local to local_list prior to this loop so that we
3834 		 * can simply walk the local_list while we walk this list.  The
3835 		 * two lists should be completely in sync.
3836 		 *
3837 		 * Clear the changed flag here.
3838 		 */
3839 		ctmp->changed = 0;
3840 
3841 		if (ctmp->dtype != local->dtype) {
3842 			if (ctmp->dtype != NOTHING) {
3843 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
3844 				    "%s: %s type changed from %s to %s "
3845 				    "(killing)", __func__, ctmp->path,
3846 				    PHY_TYPE(ctmp), PHY_TYPE(local));
3847 				/*
3848 				 * Force a rescan of this expander after dead
3849 				 * contents are cleared and removed.
3850 				 */
3851 				changed = B_TRUE;
3852 				kill_changed = B_TRUE;
3853 			} else {
3854 				changed = B_TRUE;
3855 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
3856 				    "%s: %s type changed from NOTHING to %s",
3857 				    __func__, ctmp->path, PHY_TYPE(local));
3858 				/*
3859 				 * Since this PHY was nothing and is now
3860 				 * something, reset the config_stop timer.
3861 				 */
3862 				ctmp->config_stop = ddi_get_lbolt() +
3863 				    drv_usectohz(PMCS_MAX_CONFIG_TIME);
3864 			}
3865 
3866 		} else if (ctmp->atdt != local->atdt) {
3867 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL, "%s: "
3868 			    "%s attached device type changed from %d to %d "
3869 			    "(killing)", __func__, ctmp->path, ctmp->atdt,
3870 			    local->atdt);
3871 			/*
3872 			 * Force a rescan of this expander after dead
3873 			 * contents are cleared and removed.
3874 			 */
3875 			changed = B_TRUE;
3876 
3877 			if (local->atdt == 0) {
3878 				kill_changed = B_TRUE;
3879 			}
3880 		} else if (ctmp->link_rate != local->link_rate) {
3881 			pmcs_prt(pwp, PMCS_PRT_INFO, ctmp, NULL, "%s: %s "
3882 			    "changed speed from %s to %s", __func__, ctmp->path,
3883 			    pmcs_get_rate(ctmp->link_rate),
3884 			    pmcs_get_rate(local->link_rate));
3885 			/* If the speed changed from invalid, force rescan */
3886 			if (!PMCS_VALID_LINK_RATE(ctmp->link_rate)) {
3887 				changed = B_TRUE;
3888 				RESTART_DISCOVERY(pwp);
3889 			} else {
3890 				/* Just update to the new link rate */
3891 				ctmp->link_rate = local->link_rate;
3892 			}
3893 
3894 			if (!PMCS_VALID_LINK_RATE(local->link_rate)) {
3895 				kill_changed = B_TRUE;
3896 			}
3897 		} else if (memcmp(ctmp->sas_address, local->sas_address,
3898 		    sizeof (ctmp->sas_address)) != 0) {
3899 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
3900 			    "%s: SAS Addr for %s changed from " SAS_ADDR_FMT
3901 			    "to " SAS_ADDR_FMT " (kill old tree)", __func__,
3902 			    ctmp->path, SAS_ADDR_PRT(ctmp->sas_address),
3903 			    SAS_ADDR_PRT(local->sas_address));
3904 			/*
3905 			 * Force a rescan of this expander after dead
3906 			 * contents are cleared and removed.
3907 			 */
3908 			changed = B_TRUE;
3909 		} else {
3910 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
3911 			    "%s: %s looks the same (type %s)",
3912 			    __func__, ctmp->path, PHY_TYPE(ctmp));
3913 			/*
3914 			 * If EXPANDER, still mark it changed so we
3915 			 * re-evaluate its contents.  If it's not an expander,
3916 			 * but it hasn't been configured, also mark it as
3917 			 * changed so that it will undergo configuration.
3918 			 */
3919 			if (ctmp->dtype == EXPANDER) {
3920 				changed = B_TRUE;
3921 			} else if ((ctmp->dtype != NOTHING) &&
3922 			    !ctmp->configured) {
3923 				ctmp->changed = 1;
3924 			} else {
3925 				/* It simply hasn't changed */
3926 				ctmp->changed = 0;
3927 			}
3928 		}
3929 
3930 		/*
3931 		 * If the PHY changed, call pmcs_kill_changed if indicated,
3932 		 * update its contents to reflect its current state and mark it
3933 		 * as changed.
3934 		 */
3935 		if (changed) {
3936 			/*
3937 			 * pmcs_kill_changed will mark the PHY as changed, so
3938 			 * only do PHY_CHANGED if we did not do kill_changed.
3939 			 */
3940 			if (kill_changed) {
3941 				pmcs_kill_changed(pwp, ctmp, 0);
3942 			} else {
3943 				/*
3944 				 * If we're not killing the device, it's not
3945 				 * dead.  Mark the PHY as changed.
3946 				 */
3947 				PHY_CHANGED(pwp, ctmp);
3948 
3949 				if (ctmp->dead) {
3950 					pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG,
3951 					    ctmp, NULL, "%s: Unmarking PHY %s "
3952 					    "dead, restarting discovery",
3953 					    __func__, ctmp->path);
3954 					ctmp->dead = 0;
3955 					RESTART_DISCOVERY(pwp);
3956 				}
3957 			}
3958 
3959 			/*
3960 			 * If the dtype of this PHY is now NOTHING, mark it as
3961 			 * unconfigured.  Set pend_dtype to what the new dtype
3962 			 * is.  It'll get updated at the end of the discovery
3963 			 * process.
3964 			 */
3965 			if (local->dtype == NOTHING) {
3966 				bzero(ctmp->sas_address,
3967 				    sizeof (local->sas_address));
3968 				ctmp->atdt = 0;
3969 				ctmp->link_rate = 0;
3970 				ctmp->pend_dtype = NOTHING;
3971 				ctmp->configured = 0;
3972 			} else {
3973 				(void) memcpy(ctmp->sas_address,
3974 				    local->sas_address,
3975 				    sizeof (local->sas_address));
3976 				ctmp->atdt = local->atdt;
3977 				ctmp->link_rate = local->link_rate;
3978 				ctmp->pend_dtype = local->dtype;
3979 			}
3980 		}
3981 
3982 		local = local->sibling;
3983 		ctmp = ctmp->sibling;
3984 	}
3985 
3986 	/*
3987 	 * If we got to here, that means we were able to see all the PHYs
3988 	 * and we can now update all of the real PHYs with the information
3989 	 * we got on the local PHYs.  Once that's done, free all the local
3990 	 * PHYs.
3991 	 */
3992 
3993 	pmcs_free_phys(pwp, local_list);
3994 }
3995 
3996 /*
3997  * Top level routine to check expanders.  We call pmcs_check_expander for
3998  * each expander.  Since we're not doing any configuration right now, it
3999  * doesn't matter if this is breadth-first.
4000  */
4001 static void
4002 pmcs_check_expanders(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
4003 {
4004 	pmcs_phy_t *phyp, *pnext, *pchild;
4005 
4006 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4007 	    "%s: %s", __func__, pptr->path);
4008 
4009 	/*
4010 	 * Check each expander at this level
4011 	 */
4012 	phyp = pptr;
4013 	while (phyp) {
4014 		pmcs_lock_phy(phyp);
4015 
4016 		if ((phyp->dtype == EXPANDER) && phyp->changed &&
4017 		    !phyp->dead && !phyp->subsidiary &&
4018 		    phyp->configured) {
4019 			pmcs_check_expander(pwp, phyp);
4020 		}
4021 
4022 		pnext = phyp->sibling;
4023 		pmcs_unlock_phy(phyp);
4024 		phyp = pnext;
4025 	}
4026 
4027 	/*
4028 	 * Now check the children
4029 	 */
4030 	phyp = pptr;
4031 	while (phyp) {
4032 		pmcs_lock_phy(phyp);
4033 		pnext = phyp->sibling;
4034 		pchild = phyp->children;
4035 		pmcs_unlock_phy(phyp);
4036 
4037 		if (pchild) {
4038 			pmcs_check_expanders(pwp, pchild);
4039 		}
4040 
4041 		phyp = pnext;
4042 	}
4043 }
4044 
4045 /*
4046  * Called with softstate and PHY locked
4047  */
4048 static void
4049 pmcs_clear_expander(pmcs_hw_t *pwp, pmcs_phy_t *pptr, int level)
4050 {
4051 	pmcs_phy_t *ctmp;
4052 
4053 	ASSERT(mutex_owned(&pwp->lock));
4054 	ASSERT(mutex_owned(&pptr->phy_lock));
4055 	ASSERT(pptr->level < PMCS_MAX_XPND - 1);
4056 
4057 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4058 	    "%s: checking %s", __func__, pptr->path);
4059 
4060 	ctmp = pptr->children;
4061 	while (ctmp) {
4062 		/*
4063 		 * If the expander is dead, mark its children dead
4064 		 */
4065 		if (pptr->dead) {
4066 			ctmp->dead = 1;
4067 		}
4068 		if (ctmp->dtype == EXPANDER) {
4069 			pmcs_clear_expander(pwp, ctmp, level + 1);
4070 		}
4071 		ctmp = ctmp->sibling;
4072 	}
4073 
4074 	/*
4075 	 * If this expander is not dead, we're done here.
4076 	 */
4077 	if (!pptr->dead) {
4078 		return;
4079 	}
4080 
4081 	/*
4082 	 * Now snip out the list of children below us and release them
4083 	 */
4084 	if (pptr->children) {
4085 		pmcs_add_dead_phys(pwp, pptr->children);
4086 	}
4087 
4088 	pptr->children = NULL;
4089 
4090 	/*
4091 	 * Clear subsidiary phys as well.  Getting the parent's PHY lock
4092 	 * is only necessary if level == 0 since otherwise the parent is
4093 	 * already locked.
4094 	 */
4095 	if (!IS_ROOT_PHY(pptr)) {
4096 		if (level == 0) {
4097 			mutex_enter(&pptr->parent->phy_lock);
4098 		}
4099 		ctmp = pptr->parent->children;
4100 		if (level == 0) {
4101 			mutex_exit(&pptr->parent->phy_lock);
4102 		}
4103 	} else {
4104 		ctmp = pwp->root_phys;
4105 	}
4106 
4107 	while (ctmp) {
4108 		if (ctmp == pptr) {
4109 			ctmp = ctmp->sibling;
4110 			continue;
4111 		}
4112 		/*
4113 		 * We only need to lock subsidiary PHYs on the level 0
4114 		 * expander.  Any children of that expander, subsidiaries or
4115 		 * not, will already be locked.
4116 		 */
4117 		if (level == 0) {
4118 			pmcs_lock_phy(ctmp);
4119 		}
4120 		if (ctmp->dtype != EXPANDER || ctmp->subsidiary == 0 ||
4121 		    memcmp(ctmp->sas_address, pptr->sas_address,
4122 		    sizeof (ctmp->sas_address)) != 0) {
4123 			if (level == 0) {
4124 				pmcs_unlock_phy(ctmp);
4125 			}
4126 			ctmp = ctmp->sibling;
4127 			continue;
4128 		}
4129 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
4130 		    "%s: subsidiary %s", __func__, ctmp->path);
4131 		pmcs_clear_phy(pwp, ctmp);
4132 		if (level == 0) {
4133 			pmcs_unlock_phy(ctmp);
4134 		}
4135 		ctmp = ctmp->sibling;
4136 	}
4137 
4138 	pmcs_clear_phy(pwp, pptr);
4139 }
4140 
4141 /*
4142  * Called with PHY locked and with scratch acquired. We return 0 if
4143  * we fail to allocate resources or notice that the configuration
4144  * count changed while we were running the command. We return
4145  * less than zero if we had an I/O error or received an unsupported
4146  * configuration. Otherwise we return the number of phys in the
4147  * expander.
4148  */
4149 #define	DFM(m, y) if (m == NULL) m = y
4150 static int
4151 pmcs_expander_get_nphy(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
4152 {
4153 	struct pmcwork *pwrk;
4154 	pmcs_iport_t *iport;
4155 	char buf[64];
4156 	const uint_t rdoff = 0x100;	/* returned data offset */
4157 	smp_response_frame_t *srf;
4158 	smp_report_general_resp_t *srgr;
4159 	uint32_t msg[PMCS_MSG_SIZE], *ptr, htag, status, ival;
4160 	int result = 0;
4161 
4162 	ival = 0x40001100;
4163 
4164 again:
4165 	if (!pptr->iport || !pptr->valid_device_id) {
4166 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, pptr->target,
4167 		    "%s: Can't reach PHY %s", __func__, pptr->path);
4168 		goto out;
4169 	}
4170 
4171 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
4172 	if (pwrk == NULL) {
4173 		goto out;
4174 	}
4175 	(void) memset(pwp->scratch, 0x77, PMCS_SCRATCH_SIZE);
4176 	pwrk->arg = pwp->scratch;
4177 	pwrk->dtype = pptr->dtype;
4178 	pwrk->xp = pptr->target;
4179 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
4180 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4181 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4182 	if (ptr == NULL) {
4183 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4184 		pmcs_prt(pwp, PMCS_PRT_DEBUG2, pptr, NULL,
4185 		    "%s: GET_IQ_ENTRY failed", __func__);
4186 		pmcs_pwork(pwp, pwrk);
4187 		goto out;
4188 	}
4189 
4190 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL, PMCIN_SMP_REQUEST));
4191 	msg[1] = LE_32(pwrk->htag);
4192 	msg[2] = LE_32(pptr->device_id);
4193 	msg[3] = LE_32((4 << SMP_REQUEST_LENGTH_SHIFT) | SMP_INDIRECT_RESPONSE);
4194 	/*
4195 	 * Send SMP REPORT GENERAL (of either SAS1.1 or SAS2 flavors).
4196 	 */
4197 	msg[4] = BE_32(ival);
4198 	msg[5] = 0;
4199 	msg[6] = 0;
4200 	msg[7] = 0;
4201 	msg[8] = 0;
4202 	msg[9] = 0;
4203 	msg[10] = 0;
4204 	msg[11] = 0;
4205 	msg[12] = LE_32(DWORD0(pwp->scratch_dma+rdoff));
4206 	msg[13] = LE_32(DWORD1(pwp->scratch_dma+rdoff));
4207 	msg[14] = LE_32(PMCS_SCRATCH_SIZE - rdoff);
4208 	msg[15] = 0;
4209 
4210 	COPY_MESSAGE(ptr, msg, PMCS_MSG_SIZE);
4211 
4212 	pmcs_hold_iport(pptr->iport);
4213 	iport = pptr->iport;
4214 	pmcs_smp_acquire(iport);
4215 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
4216 	htag = pwrk->htag;
4217 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4218 	pmcs_unlock_phy(pptr);
4219 	WAIT_FOR(pwrk, 1000, result);
4220 	pmcs_pwork(pwp, pwrk);
4221 	pmcs_smp_release(iport);
4222 	pmcs_rele_iport(iport);
4223 	pmcs_lock_phy(pptr);
4224 
4225 
4226 	mutex_enter(&pwp->config_lock);
4227 	if (pwp->config_changed) {
4228 		RESTART_DISCOVERY_LOCKED(pwp);
4229 		mutex_exit(&pwp->config_lock);
4230 		result = 0;
4231 		goto out;
4232 	}
4233 	mutex_exit(&pwp->config_lock);
4234 
4235 	if (result) {
4236 		pmcs_timed_out(pwp, htag, __func__);
4237 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4238 		    "%s: Issuing SMP ABORT for htag 0x%08x", __func__, htag);
4239 		if (pmcs_abort(pwp, pptr, htag, 0, 0)) {
4240 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4241 			    "%s: Unable to issue SMP ABORT for htag 0x%08x",
4242 			    __func__, htag);
4243 		} else {
4244 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4245 			    "%s: Issuing SMP ABORT for htag 0x%08x",
4246 			    __func__, htag);
4247 		}
4248 		result = 0;
4249 		goto out;
4250 	}
4251 	ptr = (void *)pwp->scratch;
4252 	status = LE_32(ptr[2]);
4253 	if (status == PMCOUT_STATUS_UNDERFLOW ||
4254 	    status == PMCOUT_STATUS_OVERFLOW) {
4255 		pmcs_prt(pwp, PMCS_PRT_DEBUG_UNDERFLOW, pptr, NULL,
4256 		    "%s: over/underflow", __func__);
4257 		status = PMCOUT_STATUS_OK;
4258 	}
4259 	srf = (smp_response_frame_t *)&((uint32_t *)pwp->scratch)[rdoff >> 2];
4260 	srgr = (smp_report_general_resp_t *)
4261 	    &((uint32_t *)pwp->scratch)[(rdoff >> 2)+1];
4262 
4263 	if (status != PMCOUT_STATUS_OK) {
4264 		char *nag = NULL;
4265 		(void) snprintf(buf, sizeof (buf),
4266 		    "%s: SMP op failed (0x%x)", __func__, status);
4267 		switch (status) {
4268 		case PMCOUT_STATUS_IO_PORT_IN_RESET:
4269 			DFM(nag, "I/O Port In Reset");
4270 			/* FALLTHROUGH */
4271 		case PMCOUT_STATUS_ERROR_HW_TIMEOUT:
4272 			DFM(nag, "Hardware Timeout");
4273 			/* FALLTHROUGH */
4274 		case PMCOUT_STATUS_ERROR_INTERNAL_SMP_RESOURCE:
4275 			DFM(nag, "Internal SMP Resource Failure");
4276 			/* FALLTHROUGH */
4277 		case PMCOUT_STATUS_XFER_ERR_PHY_NOT_READY:
4278 			DFM(nag, "PHY Not Ready");
4279 			/* FALLTHROUGH */
4280 		case PMCOUT_STATUS_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
4281 			DFM(nag, "Connection Rate Not Supported");
4282 			/* FALLTHROUGH */
4283 		case PMCOUT_STATUS_IO_XFER_OPEN_RETRY_TIMEOUT:
4284 			DFM(nag, "Open Retry Timeout");
4285 			/* FALLTHROUGH */
4286 		case PMCOUT_STATUS_IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
4287 			DFM(nag, "HW Resource Busy");
4288 			/* FALLTHROUGH */
4289 		case PMCOUT_STATUS_SMP_RESP_CONNECTION_ERROR:
4290 			DFM(nag, "Response Connection Error");
4291 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4292 			    "%s: expander %s SMP operation failed (%s)",
4293 			    __func__, pptr->path, nag);
4294 			break;
4295 
4296 		/*
4297 		 * For the IO_DS_NON_OPERATIONAL case, we need to kick off
4298 		 * device state recovery and return 0 so that the caller
4299 		 * doesn't assume this expander is dead for good.
4300 		 */
4301 		case PMCOUT_STATUS_IO_DS_NON_OPERATIONAL: {
4302 			pmcs_xscsi_t *xp = pptr->target;
4303 
4304 			pmcs_prt(pwp, PMCS_PRT_DEBUG_DEV_STATE, pptr, xp,
4305 			    "%s: expander %s device state non-operational",
4306 			    __func__, pptr->path);
4307 
4308 			if (xp == NULL) {
4309 				/*
4310 				 * Kick off recovery right now.
4311 				 */
4312 				SCHEDULE_WORK(pwp, PMCS_WORK_DS_ERR_RECOVERY);
4313 				(void) ddi_taskq_dispatch(pwp->tq, pmcs_worker,
4314 				    pwp, DDI_NOSLEEP);
4315 			} else {
4316 				mutex_enter(&xp->statlock);
4317 				pmcs_start_dev_state_recovery(xp, pptr);
4318 				mutex_exit(&xp->statlock);
4319 			}
4320 
4321 			break;
4322 		}
4323 
4324 		default:
4325 			pmcs_print_entry(pwp, PMCS_PRT_DEBUG, buf, ptr);
4326 			result = -EIO;
4327 			break;
4328 		}
4329 	} else if (srf->srf_frame_type != SMP_FRAME_TYPE_RESPONSE) {
4330 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4331 		    "%s: bad response frame type 0x%x",
4332 		    __func__, srf->srf_frame_type);
4333 		result = -EINVAL;
4334 	} else if (srf->srf_function != SMP_FUNC_REPORT_GENERAL) {
4335 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4336 		    "%s: bad response function 0x%x",
4337 		    __func__, srf->srf_function);
4338 		result = -EINVAL;
4339 	} else if (srf->srf_result != 0) {
4340 		/*
4341 		 * Check to see if we have a value of 3 for failure and
4342 		 * whether we were using a SAS2.0 allocation length value
4343 		 * and retry without it.
4344 		 */
4345 		if (srf->srf_result == 3 && (ival & 0xff00)) {
4346 			ival &= ~0xff00;
4347 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4348 			    "%s: err 0x%x with SAS2 request- retry with SAS1",
4349 			    __func__, srf->srf_result);
4350 			goto again;
4351 		}
4352 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4353 		    "%s: bad response 0x%x", __func__, srf->srf_result);
4354 		result = -EINVAL;
4355 	} else if (srgr->srgr_configuring) {
4356 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4357 		    "%s: expander at phy %s is still configuring",
4358 		    __func__, pptr->path);
4359 		result = 0;
4360 	} else {
4361 		result = srgr->srgr_number_of_phys;
4362 		if (ival & 0xff00) {
4363 			pptr->tolerates_sas2 = 1;
4364 		}
4365 		/*
4366 		 * Save off the REPORT_GENERAL response
4367 		 */
4368 		bcopy(srgr, &pptr->rg_resp, sizeof (smp_report_general_resp_t));
4369 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4370 		    "%s has %d phys and %s SAS2", pptr->path, result,
4371 		    pptr->tolerates_sas2? "tolerates" : "does not tolerate");
4372 	}
4373 out:
4374 	return (result);
4375 }
4376 
4377 /*
4378  * Called with expander locked (and thus, pptr) as well as all PHYs up to
4379  * the root, and scratch acquired. Return 0 if we fail to allocate resources
4380  * or notice that the configuration changed while we were running the command.
4381  *
4382  * We return less than zero if we had an I/O error or received an
4383  * unsupported configuration.
4384  */
4385 static int
4386 pmcs_expander_content_discover(pmcs_hw_t *pwp, pmcs_phy_t *expander,
4387     pmcs_phy_t *pptr)
4388 {
4389 	struct pmcwork *pwrk;
4390 	pmcs_iport_t *iport;
4391 	char buf[64];
4392 	uint8_t sas_address[8];
4393 	uint8_t att_sas_address[8];
4394 	smp_response_frame_t *srf;
4395 	smp_discover_resp_t *sdr;
4396 	const uint_t rdoff = 0x100;	/* returned data offset */
4397 	uint8_t *roff;
4398 	uint32_t status, *ptr, msg[PMCS_MSG_SIZE], htag;
4399 	int result = 0;
4400 	uint8_t	ini_support;
4401 	uint8_t	tgt_support;
4402 
4403 	if (!expander->iport || !expander->valid_device_id) {
4404 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, expander, expander->target,
4405 		    "%s: Can't reach PHY %s", __func__, expander->path);
4406 		goto out;
4407 	}
4408 
4409 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, expander);
4410 	if (pwrk == NULL) {
4411 		goto out;
4412 	}
4413 	(void) memset(pwp->scratch, 0x77, PMCS_SCRATCH_SIZE);
4414 	pwrk->arg = pwp->scratch;
4415 	pwrk->dtype = expander->dtype;
4416 	pwrk->xp = expander->target;
4417 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
4418 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL, PMCIN_SMP_REQUEST));
4419 	msg[1] = LE_32(pwrk->htag);
4420 	msg[2] = LE_32(expander->device_id);
4421 	msg[3] = LE_32((12 << SMP_REQUEST_LENGTH_SHIFT) |
4422 	    SMP_INDIRECT_RESPONSE);
4423 	/*
4424 	 * Send SMP DISCOVER (of either SAS1.1 or SAS2 flavors).
4425 	 */
4426 	if (expander->tolerates_sas2) {
4427 		msg[4] = BE_32(0x40101B00);
4428 	} else {
4429 		msg[4] = BE_32(0x40100000);
4430 	}
4431 	msg[5] = 0;
4432 	msg[6] = BE_32((pptr->phynum << 16));
4433 	msg[7] = 0;
4434 	msg[8] = 0;
4435 	msg[9] = 0;
4436 	msg[10] = 0;
4437 	msg[11] = 0;
4438 	msg[12] = LE_32(DWORD0(pwp->scratch_dma+rdoff));
4439 	msg[13] = LE_32(DWORD1(pwp->scratch_dma+rdoff));
4440 	msg[14] = LE_32(PMCS_SCRATCH_SIZE - rdoff);
4441 	msg[15] = 0;
4442 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4443 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4444 	if (ptr == NULL) {
4445 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4446 		goto out;
4447 	}
4448 
4449 	COPY_MESSAGE(ptr, msg, PMCS_MSG_SIZE);
4450 
4451 	pmcs_hold_iport(expander->iport);
4452 	iport = expander->iport;
4453 	pmcs_smp_acquire(iport);
4454 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
4455 	htag = pwrk->htag;
4456 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4457 	pmcs_unlock_phy(expander);
4458 	WAIT_FOR(pwrk, 1000, result);
4459 	pmcs_pwork(pwp, pwrk);
4460 	pmcs_smp_release(iport);
4461 	pmcs_rele_iport(iport);
4462 	pmcs_lock_phy(expander);
4463 
4464 	mutex_enter(&pwp->config_lock);
4465 	if (pwp->config_changed) {
4466 		RESTART_DISCOVERY_LOCKED(pwp);
4467 		mutex_exit(&pwp->config_lock);
4468 		result = 0;
4469 		goto out;
4470 	}
4471 	mutex_exit(&pwp->config_lock);
4472 
4473 	if (result) {
4474 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, pmcs_timeo, __func__);
4475 		if (pmcs_abort(pwp, expander, htag, 0, 0)) {
4476 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4477 			    "%s: Unable to issue SMP ABORT for htag 0x%08x",
4478 			    __func__, htag);
4479 		} else {
4480 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4481 			    "%s: Issuing SMP ABORT for htag 0x%08x",
4482 			    __func__, htag);
4483 		}
4484 		result = -ETIMEDOUT;
4485 		goto out;
4486 	}
4487 	ptr = (void *)pwp->scratch;
4488 	/*
4489 	 * Point roff to the DMA offset for returned data
4490 	 */
4491 	roff = pwp->scratch;
4492 	roff += rdoff;
4493 	srf = (smp_response_frame_t *)roff;
4494 	sdr = (smp_discover_resp_t *)(roff+4);
4495 	status = LE_32(ptr[2]);
4496 	if (status == PMCOUT_STATUS_UNDERFLOW ||
4497 	    status == PMCOUT_STATUS_OVERFLOW) {
4498 		pmcs_prt(pwp, PMCS_PRT_DEBUG_UNDERFLOW, pptr, NULL,
4499 		    "%s: over/underflow", __func__);
4500 		status = PMCOUT_STATUS_OK;
4501 	}
4502 	if (status != PMCOUT_STATUS_OK) {
4503 		char *nag = NULL;
4504 		(void) snprintf(buf, sizeof (buf),
4505 		    "%s: SMP op failed (0x%x)", __func__, status);
4506 		switch (status) {
4507 		case PMCOUT_STATUS_ERROR_HW_TIMEOUT:
4508 			DFM(nag, "Hardware Timeout");
4509 			/* FALLTHROUGH */
4510 		case PMCOUT_STATUS_ERROR_INTERNAL_SMP_RESOURCE:
4511 			DFM(nag, "Internal SMP Resource Failure");
4512 			/* FALLTHROUGH */
4513 		case PMCOUT_STATUS_XFER_ERR_PHY_NOT_READY:
4514 			DFM(nag, "PHY Not Ready");
4515 			/* FALLTHROUGH */
4516 		case PMCOUT_STATUS_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
4517 			DFM(nag, "Connection Rate Not Supported");
4518 			/* FALLTHROUGH */
4519 		case PMCOUT_STATUS_IO_XFER_OPEN_RETRY_TIMEOUT:
4520 			DFM(nag, "Open Retry Timeout");
4521 			/* FALLTHROUGH */
4522 		case PMCOUT_STATUS_IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
4523 			DFM(nag, "HW Resource Busy");
4524 			/* FALLTHROUGH */
4525 		case PMCOUT_STATUS_SMP_RESP_CONNECTION_ERROR:
4526 			DFM(nag, "Response Connection Error");
4527 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4528 			    "%s: expander %s SMP operation failed (%s)",
4529 			    __func__, pptr->path, nag);
4530 			break;
4531 		default:
4532 			pmcs_print_entry(pwp, PMCS_PRT_DEBUG, buf, ptr);
4533 			result = -EIO;
4534 			break;
4535 		}
4536 		goto out;
4537 	} else if (srf->srf_frame_type != SMP_FRAME_TYPE_RESPONSE) {
4538 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4539 		    "%s: bad response frame type 0x%x",
4540 		    __func__, srf->srf_frame_type);
4541 		result = -EINVAL;
4542 		goto out;
4543 	} else if (srf->srf_function != SMP_FUNC_DISCOVER) {
4544 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4545 		    "%s: bad response function 0x%x",
4546 		    __func__, srf->srf_function);
4547 		result = -EINVAL;
4548 		goto out;
4549 	} else if (srf->srf_result != SMP_RES_FUNCTION_ACCEPTED) {
4550 		result = pmcs_smp_function_result(pwp, srf);
4551 		/* Need not fail if PHY is Vacant */
4552 		if (result != SMP_RES_PHY_VACANT) {
4553 			result = -EINVAL;
4554 			goto out;
4555 		}
4556 	}
4557 
4558 	/*
4559 	 * Save off the DISCOVER response
4560 	 */
4561 	bcopy(sdr, &pptr->disc_resp, sizeof (smp_discover_resp_t));
4562 
4563 	ini_support = (sdr->sdr_attached_sata_host |
4564 	    (sdr->sdr_attached_smp_initiator << 1) |
4565 	    (sdr->sdr_attached_stp_initiator << 2) |
4566 	    (sdr->sdr_attached_ssp_initiator << 3));
4567 
4568 	tgt_support = (sdr->sdr_attached_sata_device |
4569 	    (sdr->sdr_attached_smp_target << 1) |
4570 	    (sdr->sdr_attached_stp_target << 2) |
4571 	    (sdr->sdr_attached_ssp_target << 3));
4572 
4573 	pmcs_wwn2barray(BE_64(sdr->sdr_sas_addr), sas_address);
4574 	pmcs_wwn2barray(BE_64(sdr->sdr_attached_sas_addr), att_sas_address);
4575 
4576 	pptr->virtual = sdr->sdr_virtual_phy;
4577 
4578 	/*
4579 	 * Set the routing attribute regardless of the PHY type.
4580 	 */
4581 	pptr->routing_attr = sdr->sdr_routing_attr;
4582 
4583 	switch (sdr->sdr_attached_device_type) {
4584 	case SAS_IF_DTYPE_ENDPOINT:
4585 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4586 		    "exp_content: %s atdt=0x%x lr=%x is=%x ts=%x SAS="
4587 		    SAS_ADDR_FMT " attSAS=" SAS_ADDR_FMT " atPHY=%x",
4588 		    pptr->path,
4589 		    sdr->sdr_attached_device_type,
4590 		    sdr->sdr_negotiated_logical_link_rate,
4591 		    ini_support,
4592 		    tgt_support,
4593 		    SAS_ADDR_PRT(sas_address),
4594 		    SAS_ADDR_PRT(att_sas_address),
4595 		    sdr->sdr_attached_phy_identifier);
4596 
4597 		if (sdr->sdr_attached_sata_device ||
4598 		    sdr->sdr_attached_stp_target) {
4599 			pptr->dtype = SATA;
4600 		} else if (sdr->sdr_attached_ssp_target) {
4601 			pptr->dtype = SAS;
4602 		} else if (tgt_support || ini_support) {
4603 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4604 			    "%s: %s has tgt support=%x init support=(%x)",
4605 			    __func__, pptr->path, tgt_support, ini_support);
4606 		}
4607 
4608 		switch (pptr->routing_attr) {
4609 		case SMP_ROUTING_SUBTRACTIVE:
4610 		case SMP_ROUTING_TABLE:
4611 		case SMP_ROUTING_DIRECT:
4612 			pptr->routing_method = SMP_ROUTING_DIRECT;
4613 			break;
4614 		default:
4615 			pptr->routing_method = 0xff;	/* Invalid method */
4616 			break;
4617 		}
4618 		pmcs_update_phy_pm_props(pptr, (1ULL << pptr->phynum),
4619 		    (1ULL << sdr->sdr_attached_phy_identifier), B_TRUE);
4620 		break;
4621 	case SAS_IF_DTYPE_EDGE:
4622 	case SAS_IF_DTYPE_FANOUT:
4623 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4624 		    "exp_content: %s atdt=0x%x lr=%x is=%x ts=%x SAS="
4625 		    SAS_ADDR_FMT " attSAS=" SAS_ADDR_FMT " atPHY=%x",
4626 		    pptr->path,
4627 		    sdr->sdr_attached_device_type,
4628 		    sdr->sdr_negotiated_logical_link_rate,
4629 		    ini_support,
4630 		    tgt_support,
4631 		    SAS_ADDR_PRT(sas_address),
4632 		    SAS_ADDR_PRT(att_sas_address),
4633 		    sdr->sdr_attached_phy_identifier);
4634 		if (sdr->sdr_attached_smp_target) {
4635 			/*
4636 			 * Avoid configuring phys that just point back
4637 			 * at a parent phy
4638 			 */
4639 			if (expander->parent &&
4640 			    memcmp(expander->parent->sas_address,
4641 			    att_sas_address,
4642 			    sizeof (expander->parent->sas_address)) == 0) {
4643 				pmcs_prt(pwp, PMCS_PRT_DEBUG3, pptr, NULL,
4644 				    "%s: skipping port back to parent "
4645 				    "expander (%s)", __func__, pptr->path);
4646 				pptr->dtype = NOTHING;
4647 				break;
4648 			}
4649 			pptr->dtype = EXPANDER;
4650 
4651 		} else if (tgt_support || ini_support) {
4652 			pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4653 			    "%s has tgt support=%x init support=(%x)",
4654 			    pptr->path, tgt_support, ini_support);
4655 			pptr->dtype = EXPANDER;
4656 		}
4657 		if (pptr->routing_attr == SMP_ROUTING_DIRECT) {
4658 			pptr->routing_method = 0xff;	/* Invalid method */
4659 		} else {
4660 			pptr->routing_method = pptr->routing_attr;
4661 		}
4662 		pmcs_update_phy_pm_props(pptr, (1ULL << pptr->phynum),
4663 		    (1ULL << sdr->sdr_attached_phy_identifier), B_TRUE);
4664 		break;
4665 	default:
4666 		pptr->dtype = NOTHING;
4667 		break;
4668 	}
4669 	if (pptr->dtype != NOTHING) {
4670 		pmcs_phy_t *ctmp;
4671 
4672 		/*
4673 		 * If the attached device is a SATA device and the expander
4674 		 * is (possibly) a SAS2 compliant expander, check for whether
4675 		 * there is a NAA=5 WWN field starting at this offset and
4676 		 * use that for the SAS Address for this device.
4677 		 */
4678 		if (expander->tolerates_sas2 && pptr->dtype == SATA &&
4679 		    (roff[SAS_ATTACHED_NAME_OFFSET] >> 8) == NAA_IEEE_REG) {
4680 			(void) memcpy(pptr->sas_address,
4681 			    &roff[SAS_ATTACHED_NAME_OFFSET], 8);
4682 		} else {
4683 			(void) memcpy(pptr->sas_address, att_sas_address, 8);
4684 		}
4685 		pptr->atdt = (sdr->sdr_attached_device_type);
4686 		/*
4687 		 * Now run up from the expander's parent up to the top to
4688 		 * make sure we only use the least common link_rate.
4689 		 */
4690 		for (ctmp = expander->parent; ctmp; ctmp = ctmp->parent) {
4691 			if (ctmp->link_rate <
4692 			    sdr->sdr_negotiated_logical_link_rate) {
4693 				pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, pptr, NULL,
4694 				    "%s: derating link rate from %x to %x due "
4695 				    "to %s being slower", pptr->path,
4696 				    sdr->sdr_negotiated_logical_link_rate,
4697 				    ctmp->link_rate,
4698 				    ctmp->path);
4699 				sdr->sdr_negotiated_logical_link_rate =
4700 				    ctmp->link_rate;
4701 			}
4702 		}
4703 		pptr->link_rate = sdr->sdr_negotiated_logical_link_rate;
4704 		pptr->state.prog_min_rate = sdr->sdr_prog_min_phys_link_rate;
4705 		pptr->state.hw_min_rate = sdr->sdr_hw_min_phys_link_rate;
4706 		pptr->state.prog_max_rate = sdr->sdr_prog_max_phys_link_rate;
4707 		pptr->state.hw_max_rate = sdr->sdr_hw_max_phys_link_rate;
4708 		PHY_CHANGED(pwp, pptr);
4709 	} else {
4710 		pmcs_clear_phy(pwp, pptr);
4711 	}
4712 	result = 1;
4713 out:
4714 	return (result);
4715 }
4716 
4717 /*
4718  * Get a work structure and assign it a tag with type and serial number
4719  * If a structure is returned, it is returned locked.
4720  */
4721 pmcwork_t *
4722 pmcs_gwork(pmcs_hw_t *pwp, uint32_t tag_type, pmcs_phy_t *phyp)
4723 {
4724 	pmcwork_t *p;
4725 	uint16_t snum;
4726 	uint32_t off;
4727 
4728 	mutex_enter(&pwp->wfree_lock);
4729 	p = STAILQ_FIRST(&pwp->wf);
4730 	if (p == NULL) {
4731 		/*
4732 		 * If we couldn't get a work structure, it's time to bite
4733 		 * the bullet, grab the pfree_lock and copy over all the
4734 		 * work structures from the pending free list to the actual
4735 		 * free list (assuming it's not also empty).
4736 		 */
4737 		mutex_enter(&pwp->pfree_lock);
4738 		if (STAILQ_FIRST(&pwp->pf) == NULL) {
4739 			mutex_exit(&pwp->pfree_lock);
4740 			mutex_exit(&pwp->wfree_lock);
4741 			return (NULL);
4742 		}
4743 		pwp->wf.stqh_first = pwp->pf.stqh_first;
4744 		pwp->wf.stqh_last = pwp->pf.stqh_last;
4745 		STAILQ_INIT(&pwp->pf);
4746 		mutex_exit(&pwp->pfree_lock);
4747 
4748 		p = STAILQ_FIRST(&pwp->wf);
4749 		ASSERT(p != NULL);
4750 	}
4751 	STAILQ_REMOVE(&pwp->wf, p, pmcwork, next);
4752 	snum = pwp->wserno++;
4753 	mutex_exit(&pwp->wfree_lock);
4754 
4755 	off = p - pwp->work;
4756 
4757 	mutex_enter(&p->lock);
4758 	ASSERT(p->state == PMCS_WORK_STATE_NIL);
4759 	ASSERT(p->htag == PMCS_TAG_FREE);
4760 	p->htag = (tag_type << PMCS_TAG_TYPE_SHIFT) & PMCS_TAG_TYPE_MASK;
4761 	p->htag |= ((snum << PMCS_TAG_SERNO_SHIFT) & PMCS_TAG_SERNO_MASK);
4762 	p->htag |= ((off << PMCS_TAG_INDEX_SHIFT) & PMCS_TAG_INDEX_MASK);
4763 	p->start = gethrtime();
4764 	p->state = PMCS_WORK_STATE_READY;
4765 	p->ssp_event = 0;
4766 	p->dead = 0;
4767 
4768 	if (phyp) {
4769 		p->phy = phyp;
4770 		pmcs_inc_phy_ref_count(phyp);
4771 	}
4772 
4773 	return (p);
4774 }
4775 
4776 /*
4777  * Called with pwrk lock held.  Returned with lock released.
4778  */
4779 void
4780 pmcs_pwork(pmcs_hw_t *pwp, pmcwork_t *p)
4781 {
4782 	ASSERT(p != NULL);
4783 	ASSERT(mutex_owned(&p->lock));
4784 
4785 	p->last_ptr = p->ptr;
4786 	p->last_arg = p->arg;
4787 	p->last_phy = p->phy;
4788 	p->last_xp = p->xp;
4789 	p->last_htag = p->htag;
4790 	p->last_state = p->state;
4791 	p->finish = gethrtime();
4792 
4793 	if (p->phy) {
4794 		pmcs_dec_phy_ref_count(p->phy);
4795 	}
4796 
4797 	p->state = PMCS_WORK_STATE_NIL;
4798 	p->htag = PMCS_TAG_FREE;
4799 	p->xp = NULL;
4800 	p->ptr = NULL;
4801 	p->arg = NULL;
4802 	p->phy = NULL;
4803 	p->abt_htag = 0;
4804 	p->timer = 0;
4805 	p->onwire = 0;
4806 	mutex_exit(&p->lock);
4807 
4808 	if (mutex_tryenter(&pwp->wfree_lock) == 0) {
4809 		mutex_enter(&pwp->pfree_lock);
4810 		STAILQ_INSERT_TAIL(&pwp->pf, p, next);
4811 		mutex_exit(&pwp->pfree_lock);
4812 	} else {
4813 		STAILQ_INSERT_TAIL(&pwp->wf, p, next);
4814 		mutex_exit(&pwp->wfree_lock);
4815 	}
4816 }
4817 
4818 /*
4819  * Find a work structure based upon a tag and make sure that the tag
4820  * serial number matches the work structure we've found.
4821  * If a structure is found, its lock is held upon return.
4822  * If lock_phy is B_TRUE, then lock the phy also when returning the work struct
4823  */
4824 pmcwork_t *
4825 pmcs_tag2wp(pmcs_hw_t *pwp, uint32_t htag, boolean_t lock_phy)
4826 {
4827 	pmcwork_t *p;
4828 	pmcs_phy_t *phyp;
4829 	uint32_t idx = PMCS_TAG_INDEX(htag);
4830 
4831 	p = &pwp->work[idx];
4832 
4833 	mutex_enter(&p->lock);
4834 	if (p->htag == htag) {
4835 		if (lock_phy) {
4836 			phyp = p->phy;
4837 			if (phyp != NULL) {
4838 				/* phy lock should be held before work lock */
4839 				mutex_exit(&p->lock);
4840 				mutex_enter(&phyp->phy_lock);
4841 				mutex_enter(&p->lock);
4842 			}
4843 			/*
4844 			 * Check htag again, in case the work got completed
4845 			 * while we dropped the work lock and got the phy lock
4846 			 */
4847 			if (p->htag != htag) {
4848 				if (phyp != NULL) {
4849 					mutex_exit(&p->lock);
4850 					mutex_exit(&phyp->phy_lock);
4851 				}
4852 				pmcs_prt(pwp, PMCS_PRT_DEBUG, phyp, NULL, "%s: "
4853 				    "HTAG (0x%x) found, but work (0x%p) "
4854 				    "is already complete", __func__, htag,
4855 				    (void *)p);
4856 				return (NULL);
4857 			}
4858 		}
4859 		return (p);
4860 	}
4861 	mutex_exit(&p->lock);
4862 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
4863 	    "INDEX 0x%x HTAG 0x%x got p->htag 0x%x", idx, htag, p->htag);
4864 	return (NULL);
4865 }
4866 
4867 /*
4868  * Issue an abort for a command or for all commands.
4869  *
4870  * Since this can be called from interrupt context,
4871  * we don't wait for completion if wait is not set.
4872  *
4873  * Called with PHY lock held.
4874  */
4875 int
4876 pmcs_abort(pmcs_hw_t *pwp, pmcs_phy_t *pptr, uint32_t tag, int all_cmds,
4877     int wait)
4878 {
4879 	pmcwork_t *pwrk;
4880 	pmcs_xscsi_t *tgt;
4881 	uint32_t msg[PMCS_MSG_SIZE], *ptr;
4882 	int result, abt_type;
4883 	uint32_t abt_htag, status;
4884 
4885 	if (pptr->abort_all_start) {
4886 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, "%s: ABORT_ALL for "
4887 		    "(%s) already in progress.", __func__, pptr->path);
4888 		return (EBUSY);
4889 	}
4890 
4891 	switch (pptr->dtype) {
4892 	case SAS:
4893 		abt_type = PMCIN_SSP_ABORT;
4894 		break;
4895 	case SATA:
4896 		abt_type = PMCIN_SATA_ABORT;
4897 		break;
4898 	case EXPANDER:
4899 		abt_type = PMCIN_SMP_ABORT;
4900 		break;
4901 	default:
4902 		return (0);
4903 	}
4904 
4905 	pwrk = pmcs_gwork(pwp, wait ? PMCS_TAG_TYPE_WAIT : PMCS_TAG_TYPE_NONE,
4906 	    pptr);
4907 
4908 	if (pwrk == NULL) {
4909 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nowrk, __func__);
4910 		return (ENOMEM);
4911 	}
4912 
4913 	pwrk->dtype = pptr->dtype;
4914 	pwrk->xp = pptr->target;
4915 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
4916 	if (wait) {
4917 		pwrk->arg = msg;
4918 	}
4919 	if (pptr->valid_device_id == 0) {
4920 		pmcs_pwork(pwp, pwrk);
4921 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4922 		    "%s: Invalid DeviceID", __func__);
4923 		return (ENODEV);
4924 	}
4925 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL, abt_type));
4926 	msg[1] = LE_32(pwrk->htag);
4927 	msg[2] = LE_32(pptr->device_id);
4928 	if (all_cmds) {
4929 		msg[3] = 0;
4930 		msg[4] = LE_32(1);
4931 		pwrk->ptr = NULL;
4932 		pwrk->abt_htag = PMCS_ABT_HTAG_ALL;
4933 		pptr->abort_all_start = gethrtime();
4934 	} else {
4935 		msg[3] = LE_32(tag);
4936 		msg[4] = 0;
4937 		pwrk->abt_htag = tag;
4938 	}
4939 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4940 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4941 	if (ptr == NULL) {
4942 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4943 		pmcs_pwork(pwp, pwrk);
4944 		pptr->abort_all_start = 0;
4945 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nomsg, __func__);
4946 		return (ENOMEM);
4947 	}
4948 
4949 	COPY_MESSAGE(ptr, msg, 5);
4950 	if (all_cmds) {
4951 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4952 		    "%s: aborting all commands for %s device %s. (htag=0x%x)",
4953 		    __func__, pmcs_get_typename(pptr->dtype), pptr->path,
4954 		    msg[1]);
4955 	} else {
4956 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4957 		    "%s: aborting tag 0x%x for %s device %s. (htag=0x%x)",
4958 		    __func__, tag, pmcs_get_typename(pptr->dtype), pptr->path,
4959 		    msg[1]);
4960 	}
4961 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
4962 
4963 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4964 	if (!wait) {
4965 		mutex_exit(&pwrk->lock);
4966 		return (0);
4967 	}
4968 
4969 	abt_htag = pwrk->htag;
4970 	pmcs_unlock_phy(pptr);
4971 	WAIT_FOR(pwrk, 1000, result);
4972 	pmcs_pwork(pwp, pwrk);
4973 	pmcs_lock_phy(pptr);
4974 	tgt = pptr->target;
4975 
4976 	if (all_cmds) {
4977 		pptr->abort_all_start = 0;
4978 		cv_signal(&pptr->abort_all_cv);
4979 	}
4980 
4981 	if (result) {
4982 		if (all_cmds) {
4983 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
4984 			    "%s: Abort all request timed out", __func__);
4985 		} else {
4986 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
4987 			    "%s: Abort (htag 0x%08x) request timed out",
4988 			    __func__, abt_htag);
4989 		}
4990 		if (tgt != NULL) {
4991 			mutex_enter(&tgt->statlock);
4992 			if ((tgt->dev_state != PMCS_DEVICE_STATE_IN_RECOVERY) &&
4993 			    (tgt->dev_state !=
4994 			    PMCS_DEVICE_STATE_NON_OPERATIONAL)) {
4995 				pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
4996 				    "%s: Trying DS error recovery for tgt 0x%p",
4997 				    __func__, (void *)tgt);
4998 				(void) pmcs_send_err_recovery_cmd(pwp,
4999 				    PMCS_DEVICE_STATE_IN_RECOVERY, pptr, tgt);
5000 			}
5001 			mutex_exit(&tgt->statlock);
5002 		}
5003 		return (ETIMEDOUT);
5004 	}
5005 
5006 	status = LE_32(msg[2]);
5007 	if (status != PMCOUT_STATUS_OK) {
5008 		/*
5009 		 * The only non-success status are IO_NOT_VALID &
5010 		 * IO_ABORT_IN_PROGRESS.
5011 		 * In case of IO_ABORT_IN_PROGRESS, the other ABORT cmd's
5012 		 * status is of concern and this duplicate cmd status can
5013 		 * be ignored.
5014 		 * If IO_NOT_VALID, that's not an error per-se.
5015 		 * For abort of single I/O complete the command anyway.
5016 		 * If, however, we were aborting all, that is a problem
5017 		 * as IO_NOT_VALID really means that the IO or device is
5018 		 * not there. So, discovery process will take of the cleanup.
5019 		 */
5020 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5021 		    "%s: abort result 0x%x", __func__, LE_32(msg[2]));
5022 		if (all_cmds) {
5023 			PHY_CHANGED(pwp, pptr);
5024 			RESTART_DISCOVERY(pwp);
5025 		} else {
5026 			return (EINVAL);
5027 		}
5028 
5029 		return (0);
5030 	}
5031 
5032 	if (tgt != NULL) {
5033 		mutex_enter(&tgt->statlock);
5034 		if (tgt->dev_state == PMCS_DEVICE_STATE_IN_RECOVERY) {
5035 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5036 			    "%s: Restoring OPERATIONAL dev_state for tgt 0x%p",
5037 			    __func__, (void *)tgt);
5038 			(void) pmcs_send_err_recovery_cmd(pwp,
5039 			    PMCS_DEVICE_STATE_OPERATIONAL, pptr, tgt);
5040 		}
5041 		mutex_exit(&tgt->statlock);
5042 	}
5043 
5044 	return (0);
5045 }
5046 
5047 /*
5048  * Issue a task management function to an SSP device.
5049  *
5050  * Called with PHY lock held.
5051  * statlock CANNOT be held upon entry.
5052  */
5053 int
5054 pmcs_ssp_tmf(pmcs_hw_t *pwp, pmcs_phy_t *pptr, uint8_t tmf, uint32_t tag,
5055     uint64_t lun, uint32_t *response)
5056 {
5057 	int result, ds;
5058 	uint8_t local[PMCS_QENTRY_SIZE << 1], *xd;
5059 	sas_ssp_rsp_iu_t *rptr = (void *)local;
5060 	static const uint8_t ssp_rsp_evec[] = {
5061 		0x58, 0x61, 0x56, 0x72, 0x00
5062 	};
5063 	uint32_t msg[PMCS_MSG_SIZE], *ptr, status;
5064 	struct pmcwork *pwrk;
5065 	pmcs_xscsi_t *xp;
5066 
5067 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
5068 	if (pwrk == NULL) {
5069 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nowrk, __func__);
5070 		return (ENOMEM);
5071 	}
5072 	/*
5073 	 * NB: We use the PMCS_OQ_GENERAL outbound queue
5074 	 * NB: so as to not get entangled in normal I/O
5075 	 * NB: processing.
5076 	 */
5077 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
5078 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
5079 	    PMCIN_SSP_INI_TM_START));
5080 	msg[1] = LE_32(pwrk->htag);
5081 	msg[2] = LE_32(pptr->device_id);
5082 	if (tmf == SAS_ABORT_TASK || tmf == SAS_QUERY_TASK) {
5083 		msg[3] = LE_32(tag);
5084 	} else {
5085 		msg[3] = 0;
5086 	}
5087 	msg[4] = LE_32(tmf);
5088 	msg[5] = BE_32((uint32_t)lun);
5089 	msg[6] = BE_32((uint32_t)(lun >> 32));
5090 	msg[7] = LE_32(PMCIN_MESSAGE_REPORT);
5091 
5092 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5093 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5094 	if (ptr == NULL) {
5095 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5096 		pmcs_pwork(pwp, pwrk);
5097 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nomsg, __func__);
5098 		return (ENOMEM);
5099 	}
5100 	COPY_MESSAGE(ptr, msg, 7);
5101 	pwrk->arg = msg;
5102 	pwrk->dtype = pptr->dtype;
5103 	xp = pptr->target;
5104 	pwrk->xp = xp;
5105 
5106 	if (xp != NULL) {
5107 		mutex_enter(&xp->statlock);
5108 		if (xp->dev_state == PMCS_DEVICE_STATE_NON_OPERATIONAL) {
5109 			mutex_exit(&xp->statlock);
5110 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5111 			pmcs_pwork(pwp, pwrk);
5112 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp, "%s: Not "
5113 			    "sending '%s' because DS is '%s'", __func__,
5114 			    pmcs_tmf2str(tmf), pmcs_status_str
5115 			    (PMCOUT_STATUS_IO_DS_NON_OPERATIONAL));
5116 			return (EIO);
5117 		}
5118 		mutex_exit(&xp->statlock);
5119 	}
5120 
5121 	pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5122 	    "%s: sending '%s' to %s (lun %llu) tag 0x%x", __func__,
5123 	    pmcs_tmf2str(tmf), pptr->path, (unsigned long long) lun, tag);
5124 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
5125 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5126 
5127 	pmcs_unlock_phy(pptr);
5128 	/*
5129 	 * This is a command sent to the target device, so it can take
5130 	 * significant amount of time to complete when path & device is busy.
5131 	 * Set a timeout to 20 seconds
5132 	 */
5133 	WAIT_FOR(pwrk, 20000, result);
5134 	pmcs_pwork(pwp, pwrk);
5135 	pmcs_lock_phy(pptr);
5136 	xp = pptr->target;
5137 
5138 	if (result) {
5139 		if (xp == NULL) {
5140 			return (ETIMEDOUT);
5141 		}
5142 
5143 		mutex_enter(&xp->statlock);
5144 		pmcs_start_dev_state_recovery(xp, pptr);
5145 		mutex_exit(&xp->statlock);
5146 		return (ETIMEDOUT);
5147 	}
5148 
5149 	status = LE_32(msg[2]);
5150 	if (status != PMCOUT_STATUS_OK) {
5151 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5152 		    "%s: status %s for TMF %s action to %s, lun %llu",
5153 		    __func__, pmcs_status_str(status),  pmcs_tmf2str(tmf),
5154 		    pptr->path, (unsigned long long) lun);
5155 		if ((status == PMCOUT_STATUS_IO_DS_NON_OPERATIONAL) ||
5156 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK) ||
5157 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_IT_NEXUS_LOSS)) {
5158 			ds = PMCS_DEVICE_STATE_NON_OPERATIONAL;
5159 		} else if (status == PMCOUT_STATUS_IO_DS_IN_RECOVERY) {
5160 			/*
5161 			 * If the status is IN_RECOVERY, it's an indication
5162 			 * that it's now time for us to request to have the
5163 			 * device state set to OPERATIONAL since we're the ones
5164 			 * that requested recovery to begin with.
5165 			 */
5166 			ds = PMCS_DEVICE_STATE_OPERATIONAL;
5167 		} else {
5168 			ds = PMCS_DEVICE_STATE_IN_RECOVERY;
5169 		}
5170 		if (xp != NULL) {
5171 			mutex_enter(&xp->statlock);
5172 			if (xp->dev_state != ds) {
5173 				pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5174 				    "%s: Sending err recovery cmd"
5175 				    " for tgt 0x%p (status = %s)",
5176 				    __func__, (void *)xp,
5177 				    pmcs_status_str(status));
5178 				(void) pmcs_send_err_recovery_cmd(pwp, ds,
5179 				    pptr, xp);
5180 			}
5181 			mutex_exit(&xp->statlock);
5182 		}
5183 		return (EIO);
5184 	} else {
5185 		ds = PMCS_DEVICE_STATE_OPERATIONAL;
5186 		if (xp != NULL) {
5187 			mutex_enter(&xp->statlock);
5188 			if (xp->dev_state != ds) {
5189 				pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5190 				    "%s: Sending err recovery cmd"
5191 				    " for tgt 0x%p (status = %s)",
5192 				    __func__, (void *)xp,
5193 				    pmcs_status_str(status));
5194 				(void) pmcs_send_err_recovery_cmd(pwp, ds,
5195 				    pptr, xp);
5196 			}
5197 			mutex_exit(&xp->statlock);
5198 		}
5199 	}
5200 	if (LE_32(msg[3]) == 0) {
5201 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5202 		    "TMF completed with no response");
5203 		return (EIO);
5204 	}
5205 	pmcs_endian_transform(pwp, local, &msg[5], ssp_rsp_evec);
5206 	xd = (uint8_t *)(&msg[5]);
5207 	xd += SAS_RSP_HDR_SIZE;
5208 	if (rptr->datapres != SAS_RSP_DATAPRES_RESPONSE_DATA) {
5209 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5210 		    "%s: TMF response not RESPONSE DATA (0x%x)",
5211 		    __func__, rptr->datapres);
5212 		return (EIO);
5213 	}
5214 	if (rptr->response_data_length != 4) {
5215 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG,
5216 		    "Bad SAS RESPONSE DATA LENGTH", msg);
5217 		return (EIO);
5218 	}
5219 	(void) memcpy(&status, xd, sizeof (uint32_t));
5220 	status = BE_32(status);
5221 	if (response != NULL)
5222 		*response = status;
5223 	/*
5224 	 * The status is actually in the low-order byte.  The upper three
5225 	 * bytes contain additional information for the TMFs that support them.
5226 	 * However, at this time we do not issue any of those.  In the other
5227 	 * cases, the upper three bytes are supposed to be 0, but it appears
5228 	 * they aren't always.  Just mask them off.
5229 	 */
5230 	switch (status & 0xff) {
5231 	case SAS_RSP_TMF_COMPLETE:
5232 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5233 		    "%s: TMF complete", __func__);
5234 		result = 0;
5235 		break;
5236 	case SAS_RSP_TMF_SUCCEEDED:
5237 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5238 		    "%s: TMF succeeded", __func__);
5239 		result = 0;
5240 		break;
5241 	case SAS_RSP_INVALID_FRAME:
5242 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5243 		    "%s: TMF returned INVALID FRAME", __func__);
5244 		result = EIO;
5245 		break;
5246 	case SAS_RSP_TMF_NOT_SUPPORTED:
5247 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5248 		    "%s: TMF returned TMF NOT SUPPORTED", __func__);
5249 		result = EIO;
5250 		break;
5251 	case SAS_RSP_TMF_FAILED:
5252 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5253 		    "%s: TMF returned TMF FAILED", __func__);
5254 		result = EIO;
5255 		break;
5256 	case SAS_RSP_TMF_INCORRECT_LUN:
5257 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5258 		    "%s: TMF returned INCORRECT LUN", __func__);
5259 		result = EIO;
5260 		break;
5261 	case SAS_RSP_OVERLAPPED_OIPTTA:
5262 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5263 		    "%s: TMF returned OVERLAPPED INITIATOR PORT TRANSFER TAG "
5264 		    "ATTEMPTED", __func__);
5265 		result = EIO;
5266 		break;
5267 	default:
5268 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5269 		    "%s: TMF returned unknown code 0x%x", __func__, status);
5270 		result = EIO;
5271 		break;
5272 	}
5273 	return (result);
5274 }
5275 
5276 /*
5277  * Called with PHY lock held and scratch acquired
5278  */
5279 int
5280 pmcs_sata_abort_ncq(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
5281 {
5282 	const char *utag_fail_fmt = "%s: untagged NCQ command failure";
5283 	const char *tag_fail_fmt = "%s: NCQ command failure (tag 0x%x)";
5284 	uint32_t msg[PMCS_QENTRY_SIZE], *ptr, result, status;
5285 	uint8_t *fp = pwp->scratch, ds;
5286 	fis_t fis;
5287 	pmcwork_t *pwrk;
5288 	pmcs_xscsi_t *tgt;
5289 
5290 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
5291 	if (pwrk == NULL) {
5292 		return (ENOMEM);
5293 	}
5294 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
5295 	msg[0] = LE_32(PMCS_IOMB_IN_SAS(PMCS_OQ_IODONE,
5296 	    PMCIN_SATA_HOST_IO_START));
5297 	msg[1] = LE_32(pwrk->htag);
5298 	msg[2] = LE_32(pptr->device_id);
5299 	msg[3] = LE_32(512);
5300 	msg[4] = LE_32(SATA_PROTOCOL_PIO | PMCIN_DATADIR_2_INI);
5301 	msg[5] = LE_32((READ_LOG_EXT << 16) | (C_BIT << 8) | FIS_REG_H2DEV);
5302 	msg[6] = LE_32(0x10);
5303 	msg[8] = LE_32(1);
5304 	msg[9] = 0;
5305 	msg[10] = 0;
5306 	msg[11] = 0;
5307 	msg[12] = LE_32(DWORD0(pwp->scratch_dma));
5308 	msg[13] = LE_32(DWORD1(pwp->scratch_dma));
5309 	msg[14] = LE_32(512);
5310 	msg[15] = 0;
5311 
5312 	pwrk->arg = msg;
5313 	pwrk->dtype = pptr->dtype;
5314 	pwrk->xp = pptr->target;
5315 
5316 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5317 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5318 	if (ptr == NULL) {
5319 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5320 		pmcs_pwork(pwp, pwrk);
5321 		return (ENOMEM);
5322 	}
5323 	COPY_MESSAGE(ptr, msg, PMCS_QENTRY_SIZE);
5324 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
5325 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5326 
5327 	pmcs_unlock_phy(pptr);
5328 	WAIT_FOR(pwrk, 250, result);
5329 	pmcs_pwork(pwp, pwrk);
5330 	pmcs_lock_phy(pptr);
5331 
5332 	tgt = pptr->target;
5333 	if (result) {
5334 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt, pmcs_timeo, __func__);
5335 		return (EIO);
5336 	}
5337 	status = LE_32(msg[2]);
5338 	if (status != PMCOUT_STATUS_OK || LE_32(msg[3])) {
5339 		if (tgt == NULL) {
5340 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5341 			    "%s: cannot find target for phy 0x%p for "
5342 			    "dev state recovery", __func__, (void *)pptr);
5343 			return (EIO);
5344 		}
5345 
5346 		mutex_enter(&tgt->statlock);
5347 
5348 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG, "READ LOG EXT", msg);
5349 		if ((status == PMCOUT_STATUS_IO_DS_NON_OPERATIONAL) ||
5350 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK) ||
5351 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_IT_NEXUS_LOSS)) {
5352 			ds = PMCS_DEVICE_STATE_NON_OPERATIONAL;
5353 		} else {
5354 			ds = PMCS_DEVICE_STATE_IN_RECOVERY;
5355 		}
5356 		if (tgt->dev_state != ds) {
5357 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt, "%s: Trying "
5358 			    "SATA DS Recovery for tgt(0x%p) for status(%s)",
5359 			    __func__, (void *)tgt, pmcs_status_str(status));
5360 			(void) pmcs_send_err_recovery_cmd(pwp, ds, pptr, tgt);
5361 		}
5362 
5363 		mutex_exit(&tgt->statlock);
5364 		return (EIO);
5365 	}
5366 	fis[0] = (fp[4] << 24) | (fp[3] << 16) | (fp[2] << 8) | FIS_REG_D2H;
5367 	fis[1] = (fp[8] << 24) | (fp[7] << 16) | (fp[6] << 8) | fp[5];
5368 	fis[2] = (fp[12] << 24) | (fp[11] << 16) | (fp[10] << 8) | fp[9];
5369 	fis[3] = (fp[16] << 24) | (fp[15] << 16) | (fp[14] << 8) | fp[13];
5370 	fis[4] = 0;
5371 	if (fp[0] & 0x80) {
5372 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5373 		    utag_fail_fmt, __func__);
5374 	} else {
5375 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5376 		    tag_fail_fmt, __func__, fp[0] & 0x1f);
5377 	}
5378 	pmcs_fis_dump(pwp, fis);
5379 	pptr->need_rl_ext = 0;
5380 	return (0);
5381 }
5382 
5383 /*
5384  * Transform a structure from CPU to Device endian format, or
5385  * vice versa, based upon a transformation vector.
5386  *
5387  * A transformation vector is an array of bytes, each byte
5388  * of which is defined thusly:
5389  *
5390  *  bit 7: from CPU to desired endian, otherwise from desired endian
5391  *	   to CPU format
5392  *  bit 6: Big Endian, else Little Endian
5393  *  bits 5-4:
5394  *       00 Undefined
5395  *       01 One Byte quantities
5396  *       02 Two Byte quantities
5397  *       03 Four Byte quantities
5398  *
5399  *  bits 3-0:
5400  *       00 Undefined
5401  *       Number of quantities to transform
5402  *
5403  * The vector is terminated by a 0 value.
5404  */
5405 
5406 void
5407 pmcs_endian_transform(pmcs_hw_t *pwp, void *orig_out, void *orig_in,
5408     const uint8_t *xfvec)
5409 {
5410 	uint8_t c, *out = orig_out, *in = orig_in;
5411 
5412 	if (xfvec == NULL) {
5413 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5414 		    "%s: null xfvec", __func__);
5415 		return;
5416 	}
5417 	if (out == NULL) {
5418 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5419 		    "%s: null out", __func__);
5420 		return;
5421 	}
5422 	if (in == NULL) {
5423 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5424 		    "%s: null in", __func__);
5425 		return;
5426 	}
5427 	while ((c = *xfvec++) != 0) {
5428 		int nbyt = (c & 0xf);
5429 		int size = (c >> 4) & 0x3;
5430 		int bige = (c >> 4) & 0x4;
5431 
5432 		switch (size) {
5433 		case 1:
5434 		{
5435 			while (nbyt-- > 0) {
5436 				*out++ = *in++;
5437 			}
5438 			break;
5439 		}
5440 		case 2:
5441 		{
5442 			uint16_t tmp;
5443 			while (nbyt-- > 0) {
5444 				(void) memcpy(&tmp, in, sizeof (uint16_t));
5445 				if (bige) {
5446 					tmp = BE_16(tmp);
5447 				} else {
5448 					tmp = LE_16(tmp);
5449 				}
5450 				(void) memcpy(out, &tmp, sizeof (uint16_t));
5451 				out += sizeof (uint16_t);
5452 				in += sizeof (uint16_t);
5453 			}
5454 			break;
5455 		}
5456 		case 3:
5457 		{
5458 			uint32_t tmp;
5459 			while (nbyt-- > 0) {
5460 				(void) memcpy(&tmp, in, sizeof (uint32_t));
5461 				if (bige) {
5462 					tmp = BE_32(tmp);
5463 				} else {
5464 					tmp = LE_32(tmp);
5465 				}
5466 				(void) memcpy(out, &tmp, sizeof (uint32_t));
5467 				out += sizeof (uint32_t);
5468 				in += sizeof (uint32_t);
5469 			}
5470 			break;
5471 		}
5472 		default:
5473 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5474 			    "%s: bad size", __func__);
5475 			return;
5476 		}
5477 	}
5478 }
5479 
5480 const char *
5481 pmcs_get_rate(unsigned int linkrt)
5482 {
5483 	const char *rate;
5484 	switch (linkrt) {
5485 	case SAS_LINK_RATE_1_5GBIT:
5486 		rate = "1.5";
5487 		break;
5488 	case SAS_LINK_RATE_3GBIT:
5489 		rate = "3.0";
5490 		break;
5491 	case SAS_LINK_RATE_6GBIT:
5492 		rate = "6.0";
5493 		break;
5494 	default:
5495 		rate = "???";
5496 		break;
5497 	}
5498 	return (rate);
5499 }
5500 
5501 const char *
5502 pmcs_get_typename(pmcs_dtype_t type)
5503 {
5504 	switch (type) {
5505 	case NOTHING:
5506 		return ("NIL");
5507 	case SATA:
5508 		return ("SATA");
5509 	case SAS:
5510 		return ("SSP");
5511 	case EXPANDER:
5512 		return ("EXPANDER");
5513 	}
5514 	return ("????");
5515 }
5516 
5517 const char *
5518 pmcs_tmf2str(int tmf)
5519 {
5520 	switch (tmf) {
5521 	case SAS_ABORT_TASK:
5522 		return ("Abort Task");
5523 	case SAS_ABORT_TASK_SET:
5524 		return ("Abort Task Set");
5525 	case SAS_CLEAR_TASK_SET:
5526 		return ("Clear Task Set");
5527 	case SAS_LOGICAL_UNIT_RESET:
5528 		return ("Logical Unit Reset");
5529 	case SAS_I_T_NEXUS_RESET:
5530 		return ("I_T Nexus Reset");
5531 	case SAS_CLEAR_ACA:
5532 		return ("Clear ACA");
5533 	case SAS_QUERY_TASK:
5534 		return ("Query Task");
5535 	case SAS_QUERY_TASK_SET:
5536 		return ("Query Task Set");
5537 	case SAS_QUERY_UNIT_ATTENTION:
5538 		return ("Query Unit Attention");
5539 	default:
5540 		return ("Unknown");
5541 	}
5542 }
5543 
5544 const char *
5545 pmcs_status_str(uint32_t status)
5546 {
5547 	switch (status) {
5548 	case PMCOUT_STATUS_OK:
5549 		return ("OK");
5550 	case PMCOUT_STATUS_ABORTED:
5551 		return ("ABORTED");
5552 	case PMCOUT_STATUS_OVERFLOW:
5553 		return ("OVERFLOW");
5554 	case PMCOUT_STATUS_UNDERFLOW:
5555 		return ("UNDERFLOW");
5556 	case PMCOUT_STATUS_FAILED:
5557 		return ("FAILED");
5558 	case PMCOUT_STATUS_ABORT_RESET:
5559 		return ("ABORT_RESET");
5560 	case PMCOUT_STATUS_IO_NOT_VALID:
5561 		return ("IO_NOT_VALID");
5562 	case PMCOUT_STATUS_NO_DEVICE:
5563 		return ("NO_DEVICE");
5564 	case PMCOUT_STATUS_ILLEGAL_PARAMETER:
5565 		return ("ILLEGAL_PARAMETER");
5566 	case PMCOUT_STATUS_LINK_FAILURE:
5567 		return ("LINK_FAILURE");
5568 	case PMCOUT_STATUS_PROG_ERROR:
5569 		return ("PROG_ERROR");
5570 	case PMCOUT_STATUS_EDC_IN_ERROR:
5571 		return ("EDC_IN_ERROR");
5572 	case PMCOUT_STATUS_EDC_OUT_ERROR:
5573 		return ("EDC_OUT_ERROR");
5574 	case PMCOUT_STATUS_ERROR_HW_TIMEOUT:
5575 		return ("ERROR_HW_TIMEOUT");
5576 	case PMCOUT_STATUS_XFER_ERR_BREAK:
5577 		return ("XFER_ERR_BREAK");
5578 	case PMCOUT_STATUS_XFER_ERR_PHY_NOT_READY:
5579 		return ("XFER_ERR_PHY_NOT_READY");
5580 	case PMCOUT_STATUS_OPEN_CNX_PROTOCOL_NOT_SUPPORTED:
5581 		return ("OPEN_CNX_PROTOCOL_NOT_SUPPORTED");
5582 	case PMCOUT_STATUS_OPEN_CNX_ERROR_ZONE_VIOLATION:
5583 		return ("OPEN_CNX_ERROR_ZONE_VIOLATION");
5584 	case PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK:
5585 		return ("OPEN_CNX_ERROR_BREAK");
5586 	case PMCOUT_STATUS_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
5587 		return ("OPEN_CNX_ERROR_IT_NEXUS_LOSS");
5588 	case PMCOUT_STATUS_OPENCNX_ERROR_BAD_DESTINATION:
5589 		return ("OPENCNX_ERROR_BAD_DESTINATION");
5590 	case PMCOUT_STATUS_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
5591 		return ("OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED");
5592 	case PMCOUT_STATUS_OPEN_CNX_ERROR_STP_RESOURCES_BUSY:
5593 		return ("OPEN_CNX_ERROR_STP_RESOURCES_BUSY");
5594 	case PMCOUT_STATUS_OPEN_CNX_ERROR_WRONG_DESTINATION:
5595 		return ("OPEN_CNX_ERROR_WRONG_DESTINATION");
5596 	case PMCOUT_STATUS_OPEN_CNX_ERROR_UNKNOWN_ERROR:
5597 		return ("OPEN_CNX_ERROR_UNKNOWN_ERROR");
5598 	case PMCOUT_STATUS_IO_XFER_ERROR_NAK_RECEIVED:
5599 		return ("IO_XFER_ERROR_NAK_RECEIVED");
5600 	case PMCOUT_STATUS_XFER_ERROR_ACK_NAK_TIMEOUT:
5601 		return ("XFER_ERROR_ACK_NAK_TIMEOUT");
5602 	case PMCOUT_STATUS_XFER_ERROR_PEER_ABORTED:
5603 		return ("XFER_ERROR_PEER_ABORTED");
5604 	case PMCOUT_STATUS_XFER_ERROR_RX_FRAME:
5605 		return ("XFER_ERROR_RX_FRAME");
5606 	case PMCOUT_STATUS_IO_XFER_ERROR_DMA:
5607 		return ("IO_XFER_ERROR_DMA");
5608 	case PMCOUT_STATUS_XFER_ERROR_CREDIT_TIMEOUT:
5609 		return ("XFER_ERROR_CREDIT_TIMEOUT");
5610 	case PMCOUT_STATUS_XFER_ERROR_SATA_LINK_TIMEOUT:
5611 		return ("XFER_ERROR_SATA_LINK_TIMEOUT");
5612 	case PMCOUT_STATUS_XFER_ERROR_SATA:
5613 		return ("XFER_ERROR_SATA");
5614 	case PMCOUT_STATUS_XFER_ERROR_REJECTED_NCQ_MODE:
5615 		return ("XFER_ERROR_REJECTED_NCQ_MODE");
5616 	case PMCOUT_STATUS_XFER_ERROR_ABORTED_DUE_TO_SRST:
5617 		return ("XFER_ERROR_ABORTED_DUE_TO_SRST");
5618 	case PMCOUT_STATUS_XFER_ERROR_ABORTED_NCQ_MODE:
5619 		return ("XFER_ERROR_ABORTED_NCQ_MODE");
5620 	case PMCOUT_STATUS_IO_XFER_OPEN_RETRY_TIMEOUT:
5621 		return ("IO_XFER_OPEN_RETRY_TIMEOUT");
5622 	case PMCOUT_STATUS_SMP_RESP_CONNECTION_ERROR:
5623 		return ("SMP_RESP_CONNECTION_ERROR");
5624 	case PMCOUT_STATUS_XFER_ERROR_UNEXPECTED_PHASE:
5625 		return ("XFER_ERROR_UNEXPECTED_PHASE");
5626 	case PMCOUT_STATUS_XFER_ERROR_RDY_OVERRUN:
5627 		return ("XFER_ERROR_RDY_OVERRUN");
5628 	case PMCOUT_STATUS_XFER_ERROR_RDY_NOT_EXPECTED:
5629 		return ("XFER_ERROR_RDY_NOT_EXPECTED");
5630 	case PMCOUT_STATUS_XFER_ERROR_CMD_ISSUE_ACK_NAK_TIMEOUT:
5631 		return ("XFER_ERROR_CMD_ISSUE_ACK_NAK_TIMEOUT");
5632 	case PMCOUT_STATUS_XFER_ERROR_CMD_ISSUE_BREAK_BEFORE_ACK_NACK:
5633 		return ("XFER_ERROR_CMD_ISSUE_BREAK_BEFORE_ACK_NACK");
5634 	case PMCOUT_STATUS_XFER_ERROR_CMD_ISSUE_PHY_DOWN_BEFORE_ACK_NAK:
5635 		return ("XFER_ERROR_CMD_ISSUE_PHY_DOWN_BEFORE_ACK_NAK");
5636 	case PMCOUT_STATUS_XFER_ERROR_OFFSET_MISMATCH:
5637 		return ("XFER_ERROR_OFFSET_MISMATCH");
5638 	case PMCOUT_STATUS_XFER_ERROR_ZERO_DATA_LEN:
5639 		return ("XFER_ERROR_ZERO_DATA_LEN");
5640 	case PMCOUT_STATUS_XFER_CMD_FRAME_ISSUED:
5641 		return ("XFER_CMD_FRAME_ISSUED");
5642 	case PMCOUT_STATUS_ERROR_INTERNAL_SMP_RESOURCE:
5643 		return ("ERROR_INTERNAL_SMP_RESOURCE");
5644 	case PMCOUT_STATUS_IO_PORT_IN_RESET:
5645 		return ("IO_PORT_IN_RESET");
5646 	case PMCOUT_STATUS_IO_DS_NON_OPERATIONAL:
5647 		return ("DEVICE STATE NON-OPERATIONAL");
5648 	case PMCOUT_STATUS_IO_DS_IN_RECOVERY:
5649 		return ("DEVICE STATE IN RECOVERY");
5650 	case PMCOUT_STATUS_IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
5651 		return ("OPEN CNX ERR HW RESOURCE BUSY");
5652 	default:
5653 		return (NULL);
5654 	}
5655 }
5656 
5657 uint64_t
5658 pmcs_barray2wwn(uint8_t ba[8])
5659 {
5660 	uint64_t result = 0;
5661 	int i;
5662 
5663 	for (i = 0; i < 8; i++) {
5664 		result <<= 8;
5665 		result |= ba[i];
5666 	}
5667 	return (result);
5668 }
5669 
5670 void
5671 pmcs_wwn2barray(uint64_t wwn, uint8_t ba[8])
5672 {
5673 	int i;
5674 	for (i = 0; i < 8; i++) {
5675 		ba[7 - i] = wwn & 0xff;
5676 		wwn >>= 8;
5677 	}
5678 }
5679 
5680 void
5681 pmcs_report_fwversion(pmcs_hw_t *pwp)
5682 {
5683 	const char *fwsupport;
5684 	switch (PMCS_FW_TYPE(pwp)) {
5685 	case PMCS_FW_TYPE_RELEASED:
5686 		fwsupport = "Released";
5687 		break;
5688 	case PMCS_FW_TYPE_DEVELOPMENT:
5689 		fwsupport = "Development";
5690 		break;
5691 	case PMCS_FW_TYPE_ALPHA:
5692 		fwsupport = "Alpha";
5693 		break;
5694 	case PMCS_FW_TYPE_BETA:
5695 		fwsupport = "Beta";
5696 		break;
5697 	default:
5698 		fwsupport = "Special";
5699 		break;
5700 	}
5701 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5702 	    "Chip Revision: %c; F/W Revision %x.%x.%x %s (ILA rev %08x)",
5703 	    'A' + pwp->chiprev, PMCS_FW_MAJOR(pwp), PMCS_FW_MINOR(pwp),
5704 	    PMCS_FW_MICRO(pwp), fwsupport, pwp->ila_ver);
5705 }
5706 
5707 void
5708 pmcs_phy_name(pmcs_hw_t *pwp, pmcs_phy_t *pptr, char *obuf, size_t olen)
5709 {
5710 	if (pptr->parent) {
5711 		pmcs_phy_name(pwp, pptr->parent, obuf, olen);
5712 		(void) snprintf(obuf, olen, "%s.%02x", obuf, pptr->phynum);
5713 	} else {
5714 		(void) snprintf(obuf, olen, "pp%02x", pptr->phynum);
5715 	}
5716 }
5717 
5718 /*
5719  * This function is called as a sanity check to ensure that a newly registered
5720  * PHY doesn't have a device_id that exists with another registered PHY.
5721  */
5722 static boolean_t
5723 pmcs_validate_devid(pmcs_phy_t *parent, pmcs_phy_t *phyp, uint32_t device_id)
5724 {
5725 	pmcs_phy_t *pptr, *pchild;
5726 	boolean_t rval;
5727 
5728 	pptr = parent;
5729 
5730 	while (pptr) {
5731 		if (pptr->valid_device_id && (pptr != phyp) &&
5732 		    (pptr->device_id == device_id)) {
5733 			/*
5734 			 * This can still be OK if both of these PHYs actually
5735 			 * represent the same device (e.g. expander).  It could
5736 			 * be a case of a new "primary" PHY.  If the SAS address
5737 			 * is the same and they have the same parent, we'll
5738 			 * accept this if the PHY to be registered is the
5739 			 * primary.
5740 			 */
5741 			if ((phyp->parent == pptr->parent) &&
5742 			    (memcmp(phyp->sas_address,
5743 			    pptr->sas_address, 8) == 0) && (phyp->width > 1)) {
5744 				/*
5745 				 * Move children over to the new primary and
5746 				 * update both PHYs
5747 				 */
5748 				pmcs_lock_phy(pptr);
5749 				phyp->children = pptr->children;
5750 				pchild = phyp->children;
5751 				while (pchild) {
5752 					pchild->parent = phyp;
5753 					pchild = pchild->sibling;
5754 				}
5755 				phyp->subsidiary = 0;
5756 				phyp->ncphy = pptr->ncphy;
5757 				/*
5758 				 * device_id, valid_device_id, and configured
5759 				 * will be set by the caller
5760 				 */
5761 				pptr->children = NULL;
5762 				pptr->subsidiary = 1;
5763 				pptr->ncphy = 0;
5764 				pmcs_unlock_phy(pptr);
5765 				pmcs_prt(pptr->pwp, PMCS_PRT_DEBUG, pptr, NULL,
5766 				    "%s: Moving device_id %d from PHY %s to %s",
5767 				    __func__, device_id, pptr->path,
5768 				    phyp->path);
5769 				return (B_TRUE);
5770 			}
5771 			pmcs_prt(pptr->pwp, PMCS_PRT_DEBUG, pptr, NULL,
5772 			    "%s: phy %s already exists as %s with "
5773 			    "device id 0x%x", __func__, phyp->path,
5774 			    pptr->path, device_id);
5775 			return (B_FALSE);
5776 		}
5777 
5778 		if (pptr->children) {
5779 			rval = pmcs_validate_devid(pptr->children, phyp,
5780 			    device_id);
5781 			if (rval == B_FALSE) {
5782 				return (rval);
5783 			}
5784 		}
5785 
5786 		pptr = pptr->sibling;
5787 	}
5788 
5789 	/* This PHY and device_id are valid */
5790 	return (B_TRUE);
5791 }
5792 
5793 /*
5794  * If the PHY is found, it is returned locked
5795  */
5796 static pmcs_phy_t *
5797 pmcs_find_phy_by_wwn_impl(pmcs_phy_t *phyp, uint8_t *wwn)
5798 {
5799 	pmcs_phy_t *matched_phy, *cphyp, *nphyp;
5800 
5801 	ASSERT(!mutex_owned(&phyp->phy_lock));
5802 
5803 	while (phyp) {
5804 		pmcs_lock_phy(phyp);
5805 
5806 		if (phyp->valid_device_id) {
5807 			if (memcmp(phyp->sas_address, wwn, 8) == 0) {
5808 				return (phyp);
5809 			}
5810 		}
5811 
5812 		if (phyp->children) {
5813 			cphyp = phyp->children;
5814 			pmcs_unlock_phy(phyp);
5815 			matched_phy = pmcs_find_phy_by_wwn_impl(cphyp, wwn);
5816 			if (matched_phy) {
5817 				ASSERT(mutex_owned(&matched_phy->phy_lock));
5818 				return (matched_phy);
5819 			}
5820 			pmcs_lock_phy(phyp);
5821 		}
5822 
5823 		/*
5824 		 * Only iterate through non-root PHYs
5825 		 */
5826 		if (IS_ROOT_PHY(phyp)) {
5827 			pmcs_unlock_phy(phyp);
5828 			phyp = NULL;
5829 		} else {
5830 			nphyp = phyp->sibling;
5831 			pmcs_unlock_phy(phyp);
5832 			phyp = nphyp;
5833 		}
5834 	}
5835 
5836 	return (NULL);
5837 }
5838 
5839 pmcs_phy_t *
5840 pmcs_find_phy_by_wwn(pmcs_hw_t *pwp, uint64_t wwn)
5841 {
5842 	uint8_t ebstr[8];
5843 	pmcs_phy_t *pptr, *matched_phy;
5844 
5845 	pmcs_wwn2barray(wwn, ebstr);
5846 
5847 	pptr = pwp->root_phys;
5848 	while (pptr) {
5849 		matched_phy = pmcs_find_phy_by_wwn_impl(pptr, ebstr);
5850 		if (matched_phy) {
5851 			ASSERT(mutex_owned(&matched_phy->phy_lock));
5852 			return (matched_phy);
5853 		}
5854 
5855 		pptr = pptr->sibling;
5856 	}
5857 
5858 	return (NULL);
5859 }
5860 
5861 
5862 /*
5863  * pmcs_find_phy_by_sas_address
5864  *
5865  * Find a PHY that both matches "sas_addr" and is on "iport".
5866  * If a matching PHY is found, it is returned locked.
5867  */
5868 pmcs_phy_t *
5869 pmcs_find_phy_by_sas_address(pmcs_hw_t *pwp, pmcs_iport_t *iport,
5870     pmcs_phy_t *root, char *sas_addr)
5871 {
5872 	int ua_form = 1;
5873 	uint64_t wwn;
5874 	char addr[PMCS_MAX_UA_SIZE];
5875 	pmcs_phy_t *pptr, *pnext, *pchild;
5876 
5877 	if (root == NULL) {
5878 		pptr = pwp->root_phys;
5879 	} else {
5880 		pptr = root;
5881 	}
5882 
5883 	while (pptr) {
5884 		pmcs_lock_phy(pptr);
5885 		/*
5886 		 * If the PHY is dead or does not have a valid device ID,
5887 		 * skip it.
5888 		 */
5889 		if ((pptr->dead) || (!pptr->valid_device_id)) {
5890 			goto next_phy;
5891 		}
5892 
5893 		if (pptr->iport != iport) {
5894 			goto next_phy;
5895 		}
5896 
5897 		wwn = pmcs_barray2wwn(pptr->sas_address);
5898 		(void *) scsi_wwn_to_wwnstr(wwn, ua_form, addr);
5899 		if (strncmp(addr, sas_addr, strlen(addr)) == 0) {
5900 			return (pptr);
5901 		}
5902 
5903 		if (pptr->children) {
5904 			pchild = pptr->children;
5905 			pmcs_unlock_phy(pptr);
5906 			pnext = pmcs_find_phy_by_sas_address(pwp, iport, pchild,
5907 			    sas_addr);
5908 			if (pnext) {
5909 				return (pnext);
5910 			}
5911 			pmcs_lock_phy(pptr);
5912 		}
5913 
5914 next_phy:
5915 		pnext = pptr->sibling;
5916 		pmcs_unlock_phy(pptr);
5917 		pptr = pnext;
5918 	}
5919 
5920 	return (NULL);
5921 }
5922 
5923 void
5924 pmcs_fis_dump(pmcs_hw_t *pwp, fis_t fis)
5925 {
5926 	switch (fis[0] & 0xff) {
5927 	case FIS_REG_H2DEV:
5928 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5929 		    "FIS REGISTER HOST TO DEVICE: "
5930 		    "OP=0x%02x Feature=0x%04x Count=0x%04x Device=0x%02x "
5931 		    "LBA=%llu", BYTE2(fis[0]), BYTE3(fis[2]) << 8 |
5932 		    BYTE3(fis[0]), WORD0(fis[3]), BYTE3(fis[1]),
5933 		    (unsigned long long)
5934 		    (((uint64_t)fis[2] & 0x00ffffff) << 24 |
5935 		    ((uint64_t)fis[1] & 0x00ffffff)));
5936 		break;
5937 	case FIS_REG_D2H:
5938 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5939 		    "FIS REGISTER DEVICE TO HOST: Status=0x%02x "
5940 		    "Error=0x%02x Dev=0x%02x Count=0x%04x LBA=%llu",
5941 		    BYTE2(fis[0]), BYTE3(fis[0]), BYTE3(fis[1]), WORD0(fis[3]),
5942 		    (unsigned long long)(((uint64_t)fis[2] & 0x00ffffff) << 24 |
5943 		    ((uint64_t)fis[1] & 0x00ffffff)));
5944 		break;
5945 	default:
5946 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5947 		    "FIS: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x",
5948 		    fis[0], fis[1], fis[2], fis[3], fis[4]);
5949 		break;
5950 	}
5951 }
5952 
5953 void
5954 pmcs_print_entry(pmcs_hw_t *pwp, int level, char *msg, void *arg)
5955 {
5956 	uint32_t *mb = arg;
5957 	size_t i;
5958 
5959 	pmcs_prt(pwp, level, NULL, NULL, msg);
5960 	for (i = 0; i < (PMCS_QENTRY_SIZE / sizeof (uint32_t)); i += 4) {
5961 		pmcs_prt(pwp, level, NULL, NULL,
5962 		    "Offset %2lu: 0x%08x 0x%08x 0x%08x 0x%08x",
5963 		    i * sizeof (uint32_t), LE_32(mb[i]),
5964 		    LE_32(mb[i+1]), LE_32(mb[i+2]), LE_32(mb[i+3]));
5965 	}
5966 }
5967 
5968 /*
5969  * If phyp == NULL we're being called from the worker thread, in which
5970  * case we need to check all the PHYs.  In this case, the softstate lock
5971  * will be held.
5972  * If phyp is non-NULL, just issue the spinup release for the specified PHY
5973  * (which will already be locked).
5974  */
5975 void
5976 pmcs_spinup_release(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
5977 {
5978 	uint32_t *msg;
5979 	struct pmcwork *pwrk;
5980 	pmcs_phy_t *tphyp;
5981 
5982 	if (phyp != NULL) {
5983 		ASSERT(mutex_owned(&phyp->phy_lock));
5984 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, phyp, NULL,
5985 		    "%s: Issuing spinup release only for PHY %s", __func__,
5986 		    phyp->path);
5987 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5988 		msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5989 		if (msg == NULL || (pwrk =
5990 		    pmcs_gwork(pwp, PMCS_TAG_TYPE_NONE, NULL)) == NULL) {
5991 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5992 			SCHEDULE_WORK(pwp, PMCS_WORK_SPINUP_RELEASE);
5993 			return;
5994 		}
5995 
5996 		phyp->spinup_hold = 0;
5997 		bzero(msg, PMCS_QENTRY_SIZE);
5998 		pwrk->htag |= PMCS_TAG_NONIO_CMD;
5999 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
6000 		    PMCIN_LOCAL_PHY_CONTROL));
6001 		msg[1] = LE_32(pwrk->htag);
6002 		msg[2] = LE_32((0x10 << 8) | phyp->phynum);
6003 
6004 		pwrk->dtype = phyp->dtype;
6005 		pwrk->state = PMCS_WORK_STATE_ONCHIP;
6006 		pwrk->xp = phyp->target;
6007 		mutex_exit(&pwrk->lock);
6008 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6009 		return;
6010 	}
6011 
6012 	ASSERT(mutex_owned(&pwp->lock));
6013 
6014 	tphyp = pwp->root_phys;
6015 	while (tphyp) {
6016 		pmcs_lock_phy(tphyp);
6017 		if (tphyp->spinup_hold == 0) {
6018 			pmcs_unlock_phy(tphyp);
6019 			tphyp = tphyp->sibling;
6020 			continue;
6021 		}
6022 
6023 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, tphyp, NULL,
6024 		    "%s: Issuing spinup release for PHY %s", __func__,
6025 		    tphyp->path);
6026 
6027 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6028 		msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6029 		if (msg == NULL || (pwrk =
6030 		    pmcs_gwork(pwp, PMCS_TAG_TYPE_NONE, NULL)) == NULL) {
6031 			pmcs_unlock_phy(tphyp);
6032 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6033 			SCHEDULE_WORK(pwp, PMCS_WORK_SPINUP_RELEASE);
6034 			break;
6035 		}
6036 
6037 		tphyp->spinup_hold = 0;
6038 		bzero(msg, PMCS_QENTRY_SIZE);
6039 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
6040 		    PMCIN_LOCAL_PHY_CONTROL));
6041 		msg[1] = LE_32(pwrk->htag);
6042 		msg[2] = LE_32((0x10 << 8) | tphyp->phynum);
6043 
6044 		pwrk->dtype = tphyp->dtype;
6045 		pwrk->state = PMCS_WORK_STATE_ONCHIP;
6046 		pwrk->xp = tphyp->target;
6047 		mutex_exit(&pwrk->lock);
6048 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6049 		pmcs_unlock_phy(tphyp);
6050 
6051 		tphyp = tphyp->sibling;
6052 	}
6053 }
6054 
6055 /*
6056  * Abort commands on dead PHYs and deregister them as well as removing
6057  * the associated targets.
6058  */
6059 static int
6060 pmcs_kill_devices(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
6061 {
6062 	pmcs_phy_t *pnext, *pchild;
6063 	boolean_t remove_device;
6064 	int rval = 0;
6065 
6066 	while (phyp) {
6067 		pmcs_lock_phy(phyp);
6068 		pchild = phyp->children;
6069 		pnext = phyp->sibling;
6070 		pmcs_unlock_phy(phyp);
6071 
6072 		if (pchild) {
6073 			rval = pmcs_kill_devices(pwp, pchild);
6074 			if (rval) {
6075 				return (rval);
6076 			}
6077 		}
6078 
6079 		mutex_enter(&pwp->lock);
6080 		pmcs_lock_phy(phyp);
6081 		if (phyp->dead && phyp->valid_device_id) {
6082 			remove_device = B_TRUE;
6083 		} else {
6084 			remove_device = B_FALSE;
6085 		}
6086 
6087 		if (remove_device) {
6088 			pmcs_remove_device(pwp, phyp);
6089 			mutex_exit(&pwp->lock);
6090 
6091 			rval = pmcs_kill_device(pwp, phyp);
6092 			if (rval) {
6093 				pmcs_unlock_phy(phyp);
6094 				return (rval);
6095 			}
6096 		} else {
6097 			mutex_exit(&pwp->lock);
6098 		}
6099 
6100 		pmcs_unlock_phy(phyp);
6101 		phyp = pnext;
6102 	}
6103 
6104 	return (rval);
6105 }
6106 
6107 /*
6108  * Called with PHY locked
6109  */
6110 int
6111 pmcs_kill_device(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
6112 {
6113 	int rval;
6114 
6115 	pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, "kill %s device @ %s",
6116 	    pmcs_get_typename(pptr->dtype), pptr->path);
6117 
6118 	/*
6119 	 * There may be an outstanding ABORT_ALL running, which we wouldn't
6120 	 * know just by checking abort_pending.  We can, however, check
6121 	 * abort_all_start.  If it's non-zero, there is one, and we'll just
6122 	 * sit here and wait for it to complete.  If we don't, we'll remove
6123 	 * the device while there are still commands pending.
6124 	 */
6125 	if (pptr->abort_all_start) {
6126 		while (pptr->abort_all_start) {
6127 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
6128 			    "%s: Waiting for outstanding ABORT_ALL on PHY 0x%p",
6129 			    __func__, (void *)pptr);
6130 			cv_wait(&pptr->abort_all_cv, &pptr->phy_lock);
6131 		}
6132 	} else if (pptr->abort_pending) {
6133 		rval = pmcs_abort(pwp, pptr, pptr->device_id, 1, 1);
6134 		if (rval) {
6135 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
6136 			    "%s: ABORT_ALL returned non-zero status (%d) for "
6137 			    "PHY 0x%p", __func__, rval, (void *)pptr);
6138 			return (rval);
6139 		}
6140 		pptr->abort_pending = 0;
6141 	}
6142 
6143 	if (pptr->valid_device_id) {
6144 		pmcs_deregister_device(pwp, pptr);
6145 	}
6146 
6147 	PHY_CHANGED(pwp, pptr);
6148 	RESTART_DISCOVERY(pwp);
6149 	pptr->valid_device_id = 0;
6150 	return (0);
6151 }
6152 
6153 /*
6154  * Acknowledge the SAS h/w events that need acknowledgement.
6155  * This is only needed for first level PHYs.
6156  */
6157 void
6158 pmcs_ack_events(pmcs_hw_t *pwp)
6159 {
6160 	uint32_t msg[PMCS_MSG_SIZE], *ptr;
6161 	struct pmcwork *pwrk;
6162 	pmcs_phy_t *pptr;
6163 
6164 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
6165 		pmcs_lock_phy(pptr);
6166 		if (pptr->hw_event_ack == 0) {
6167 			pmcs_unlock_phy(pptr);
6168 			continue;
6169 		}
6170 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6171 		ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6172 
6173 		if ((ptr == NULL) || (pwrk =
6174 		    pmcs_gwork(pwp, PMCS_TAG_TYPE_NONE, NULL)) == NULL) {
6175 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6176 			pmcs_unlock_phy(pptr);
6177 			SCHEDULE_WORK(pwp, PMCS_WORK_SAS_HW_ACK);
6178 			break;
6179 		}
6180 
6181 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
6182 		    PMCIN_SAS_HW_EVENT_ACK));
6183 		msg[1] = LE_32(pwrk->htag);
6184 		msg[2] = LE_32(pptr->hw_event_ack);
6185 
6186 		mutex_exit(&pwrk->lock);
6187 		pwrk->dtype = pptr->dtype;
6188 		pptr->hw_event_ack = 0;
6189 		COPY_MESSAGE(ptr, msg, 3);
6190 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6191 		pmcs_unlock_phy(pptr);
6192 	}
6193 }
6194 
6195 /*
6196  * Load DMA
6197  */
6198 int
6199 pmcs_dma_load(pmcs_hw_t *pwp, pmcs_cmd_t *sp, uint32_t *msg)
6200 {
6201 	ddi_dma_cookie_t *sg;
6202 	pmcs_dmachunk_t *tc;
6203 	pmcs_dmasgl_t *sgl, *prior;
6204 	int seg, tsc;
6205 	uint64_t sgl_addr;
6206 
6207 	/*
6208 	 * If we have no data segments, we're done.
6209 	 */
6210 	if (CMD2PKT(sp)->pkt_numcookies == 0) {
6211 		return (0);
6212 	}
6213 
6214 	/*
6215 	 * Get the S/G list pointer.
6216 	 */
6217 	sg = CMD2PKT(sp)->pkt_cookies;
6218 
6219 	/*
6220 	 * If we only have one dma segment, we can directly address that
6221 	 * data within the Inbound message itself.
6222 	 */
6223 	if (CMD2PKT(sp)->pkt_numcookies == 1) {
6224 		msg[12] = LE_32(DWORD0(sg->dmac_laddress));
6225 		msg[13] = LE_32(DWORD1(sg->dmac_laddress));
6226 		msg[14] = LE_32(sg->dmac_size);
6227 		msg[15] = 0;
6228 		return (0);
6229 	}
6230 
6231 	/*
6232 	 * Otherwise, we'll need one or more external S/G list chunks.
6233 	 * Get the first one and its dma address into the Inbound message.
6234 	 */
6235 	mutex_enter(&pwp->dma_lock);
6236 	tc = pwp->dma_freelist;
6237 	if (tc == NULL) {
6238 		SCHEDULE_WORK(pwp, PMCS_WORK_ADD_DMA_CHUNKS);
6239 		mutex_exit(&pwp->dma_lock);
6240 		pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
6241 		    "%s: out of SG lists", __func__);
6242 		return (-1);
6243 	}
6244 	pwp->dma_freelist = tc->nxt;
6245 	mutex_exit(&pwp->dma_lock);
6246 
6247 	tc->nxt = NULL;
6248 	sp->cmd_clist = tc;
6249 	sgl = tc->chunks;
6250 	(void) memset(tc->chunks, 0, PMCS_SGL_CHUNKSZ);
6251 	sgl_addr = tc->addr;
6252 	msg[12] = LE_32(DWORD0(sgl_addr));
6253 	msg[13] = LE_32(DWORD1(sgl_addr));
6254 	msg[14] = 0;
6255 	msg[15] = LE_32(PMCS_DMASGL_EXTENSION);
6256 
6257 	prior = sgl;
6258 	tsc = 0;
6259 
6260 	for (seg = 0; seg < CMD2PKT(sp)->pkt_numcookies; seg++) {
6261 		/*
6262 		 * If the current segment count for this chunk is one less than
6263 		 * the number s/g lists per chunk and we have more than one seg
6264 		 * to go, we need another chunk. Get it, and make sure that the
6265 		 * tail end of the the previous chunk points the new chunk
6266 		 * (if remembering an offset can be called 'pointing to').
6267 		 *
6268 		 * Note that we can store the offset into our command area that
6269 		 * represents the new chunk in the length field of the part
6270 		 * that points the PMC chip at the next chunk- the PMC chip
6271 		 * ignores this field when the EXTENSION bit is set.
6272 		 *
6273 		 * This is required for dma unloads later.
6274 		 */
6275 		if (tsc == (PMCS_SGL_NCHUNKS - 1) &&
6276 		    seg < (CMD2PKT(sp)->pkt_numcookies - 1)) {
6277 			mutex_enter(&pwp->dma_lock);
6278 			tc = pwp->dma_freelist;
6279 			if (tc == NULL) {
6280 				SCHEDULE_WORK(pwp, PMCS_WORK_ADD_DMA_CHUNKS);
6281 				mutex_exit(&pwp->dma_lock);
6282 				pmcs_dma_unload(pwp, sp);
6283 				pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
6284 				    "%s: out of SG lists", __func__);
6285 				return (-1);
6286 			}
6287 			pwp->dma_freelist = tc->nxt;
6288 			tc->nxt = sp->cmd_clist;
6289 			mutex_exit(&pwp->dma_lock);
6290 
6291 			sp->cmd_clist = tc;
6292 			(void) memset(tc->chunks, 0, PMCS_SGL_CHUNKSZ);
6293 			sgl = tc->chunks;
6294 			sgl_addr = tc->addr;
6295 			prior[PMCS_SGL_NCHUNKS-1].sglal =
6296 			    LE_32(DWORD0(sgl_addr));
6297 			prior[PMCS_SGL_NCHUNKS-1].sglah =
6298 			    LE_32(DWORD1(sgl_addr));
6299 			prior[PMCS_SGL_NCHUNKS-1].sglen = 0;
6300 			prior[PMCS_SGL_NCHUNKS-1].flags =
6301 			    LE_32(PMCS_DMASGL_EXTENSION);
6302 			prior = sgl;
6303 			tsc = 0;
6304 		}
6305 		sgl[tsc].sglal = LE_32(DWORD0(sg->dmac_laddress));
6306 		sgl[tsc].sglah = LE_32(DWORD1(sg->dmac_laddress));
6307 		sgl[tsc].sglen = LE_32(sg->dmac_size);
6308 		sgl[tsc++].flags = 0;
6309 		sg++;
6310 	}
6311 	return (0);
6312 }
6313 
6314 /*
6315  * Unload DMA
6316  */
6317 void
6318 pmcs_dma_unload(pmcs_hw_t *pwp, pmcs_cmd_t *sp)
6319 {
6320 	pmcs_dmachunk_t *cp;
6321 
6322 	mutex_enter(&pwp->dma_lock);
6323 	while ((cp = sp->cmd_clist) != NULL) {
6324 		sp->cmd_clist = cp->nxt;
6325 		cp->nxt = pwp->dma_freelist;
6326 		pwp->dma_freelist = cp;
6327 	}
6328 	mutex_exit(&pwp->dma_lock);
6329 }
6330 
6331 /*
6332  * Take a chunk of consistent memory that has just been allocated and inserted
6333  * into the cip indices and prepare it for DMA chunk usage and add it to the
6334  * freelist.
6335  *
6336  * Called with dma_lock locked (except during attach when it's unnecessary)
6337  */
6338 void
6339 pmcs_idma_chunks(pmcs_hw_t *pwp, pmcs_dmachunk_t *dcp,
6340     pmcs_chunk_t *pchunk, unsigned long lim)
6341 {
6342 	unsigned long off, n;
6343 	pmcs_dmachunk_t *np = dcp;
6344 	pmcs_chunk_t *tmp_chunk;
6345 
6346 	if (pwp->dma_chunklist == NULL) {
6347 		pwp->dma_chunklist = pchunk;
6348 	} else {
6349 		tmp_chunk = pwp->dma_chunklist;
6350 		while (tmp_chunk->next) {
6351 			tmp_chunk = tmp_chunk->next;
6352 		}
6353 		tmp_chunk->next = pchunk;
6354 	}
6355 
6356 	/*
6357 	 * Install offsets into chunk lists.
6358 	 */
6359 	for (n = 0, off = 0; off < lim; off += PMCS_SGL_CHUNKSZ, n++) {
6360 		np->chunks = (void *)&pchunk->addrp[off];
6361 		np->addr = pchunk->dma_addr + off;
6362 		np->acc_handle = pchunk->acc_handle;
6363 		np->dma_handle = pchunk->dma_handle;
6364 		if ((off + PMCS_SGL_CHUNKSZ) < lim) {
6365 			np = np->nxt;
6366 		}
6367 	}
6368 	np->nxt = pwp->dma_freelist;
6369 	pwp->dma_freelist = dcp;
6370 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
6371 	    "added %lu DMA chunks ", n);
6372 }
6373 
6374 /*
6375  * Change the value of the interrupt coalescing timer.  This is done currently
6376  * only for I/O completions.  If we're using the "auto clear" feature, it can
6377  * be turned back on when interrupt coalescing is turned off and must be
6378  * turned off when the coalescing timer is on.
6379  * NOTE: PMCS_MSIX_GENERAL and PMCS_OQ_IODONE are the same value.  As long
6380  * as that's true, we don't need to distinguish between them.
6381  */
6382 
6383 void
6384 pmcs_set_intr_coal_timer(pmcs_hw_t *pwp, pmcs_coal_timer_adj_t adj)
6385 {
6386 	if (adj == DECREASE_TIMER) {
6387 		/* If the timer is already off, nothing to do. */
6388 		if (pwp->io_intr_coal.timer_on == B_FALSE) {
6389 			return;
6390 		}
6391 
6392 		pwp->io_intr_coal.intr_coal_timer -= PMCS_COAL_TIMER_GRAN;
6393 
6394 		if (pwp->io_intr_coal.intr_coal_timer == 0) {
6395 			/* Disable the timer */
6396 			pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_CONTROL, 0);
6397 
6398 			if (pwp->odb_auto_clear & (1 << PMCS_MSIX_IODONE)) {
6399 				pmcs_wr_topunit(pwp, PMCS_OBDB_AUTO_CLR,
6400 				    pwp->odb_auto_clear);
6401 			}
6402 
6403 			pwp->io_intr_coal.timer_on = B_FALSE;
6404 			pwp->io_intr_coal.max_io_completions = B_FALSE;
6405 			pwp->io_intr_coal.num_intrs = 0;
6406 			pwp->io_intr_coal.int_cleared = B_FALSE;
6407 			pwp->io_intr_coal.num_io_completions = 0;
6408 
6409 			DTRACE_PROBE1(pmcs__intr__coalesce__timer__off,
6410 			    pmcs_io_intr_coal_t *, &pwp->io_intr_coal);
6411 		} else {
6412 			pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_TIMER,
6413 			    pwp->io_intr_coal.intr_coal_timer);
6414 		}
6415 	} else {
6416 		/*
6417 		 * If the timer isn't on yet, do the setup for it now.
6418 		 */
6419 		if (pwp->io_intr_coal.timer_on == B_FALSE) {
6420 			/* If auto clear is being used, turn it off. */
6421 			if (pwp->odb_auto_clear & (1 << PMCS_MSIX_IODONE)) {
6422 				pmcs_wr_topunit(pwp, PMCS_OBDB_AUTO_CLR,
6423 				    (pwp->odb_auto_clear &
6424 				    ~(1 << PMCS_MSIX_IODONE)));
6425 			}
6426 
6427 			pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_CONTROL,
6428 			    (1 << PMCS_MSIX_IODONE));
6429 			pwp->io_intr_coal.timer_on = B_TRUE;
6430 			pwp->io_intr_coal.intr_coal_timer =
6431 			    PMCS_COAL_TIMER_GRAN;
6432 
6433 			DTRACE_PROBE1(pmcs__intr__coalesce__timer__on,
6434 			    pmcs_io_intr_coal_t *, &pwp->io_intr_coal);
6435 		} else {
6436 			pwp->io_intr_coal.intr_coal_timer +=
6437 			    PMCS_COAL_TIMER_GRAN;
6438 		}
6439 
6440 		if (pwp->io_intr_coal.intr_coal_timer > PMCS_MAX_COAL_TIMER) {
6441 			pwp->io_intr_coal.intr_coal_timer = PMCS_MAX_COAL_TIMER;
6442 		}
6443 
6444 		pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_TIMER,
6445 		    pwp->io_intr_coal.intr_coal_timer);
6446 	}
6447 
6448 	/*
6449 	 * Adjust the interrupt threshold based on the current timer value
6450 	 */
6451 	pwp->io_intr_coal.intr_threshold =
6452 	    PMCS_INTR_THRESHOLD(PMCS_QUANTUM_TIME_USECS * 1000 /
6453 	    (pwp->io_intr_coal.intr_latency +
6454 	    (pwp->io_intr_coal.intr_coal_timer * 1000)));
6455 }
6456 
6457 /*
6458  * Register Access functions
6459  */
6460 uint32_t
6461 pmcs_rd_iqci(pmcs_hw_t *pwp, uint32_t qnum)
6462 {
6463 	uint32_t iqci;
6464 
6465 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORKERNEL) !=
6466 	    DDI_SUCCESS) {
6467 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6468 		    "%s: ddi_dma_sync failed?", __func__);
6469 	}
6470 
6471 	iqci = LE_32(
6472 	    ((uint32_t *)((void *)pwp->cip))[IQ_OFFSET(qnum) >> 2]);
6473 
6474 	return (iqci);
6475 }
6476 
6477 uint32_t
6478 pmcs_rd_oqpi(pmcs_hw_t *pwp, uint32_t qnum)
6479 {
6480 	uint32_t oqpi;
6481 
6482 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORKERNEL) !=
6483 	    DDI_SUCCESS) {
6484 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6485 		    "%s: ddi_dma_sync failed?", __func__);
6486 	}
6487 
6488 	oqpi = LE_32(
6489 	    ((uint32_t *)((void *)pwp->cip))[OQ_OFFSET(qnum) >> 2]);
6490 
6491 	return (oqpi);
6492 }
6493 
6494 uint32_t
6495 pmcs_rd_gsm_reg(pmcs_hw_t *pwp, uint8_t hi, uint32_t off)
6496 {
6497 	uint32_t rv, newaxil, oldaxil, oldaxih;
6498 
6499 	newaxil = off & ~GSM_BASE_MASK;
6500 	off &= GSM_BASE_MASK;
6501 	mutex_enter(&pwp->axil_lock);
6502 	oldaxil = ddi_get32(pwp->top_acc_handle,
6503 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]);
6504 	ddi_put32(pwp->top_acc_handle,
6505 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], newaxil);
6506 	drv_usecwait(10);
6507 	if (ddi_get32(pwp->top_acc_handle,
6508 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != newaxil) {
6509 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6510 		    "AXIL register update failed");
6511 	}
6512 	if (hi) {
6513 		oldaxih = ddi_get32(pwp->top_acc_handle,
6514 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2]);
6515 		ddi_put32(pwp->top_acc_handle,
6516 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2], hi);
6517 		drv_usecwait(10);
6518 		if (ddi_get32(pwp->top_acc_handle,
6519 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2]) != hi) {
6520 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6521 			    "AXIH register update failed");
6522 		}
6523 	}
6524 	rv = ddi_get32(pwp->gsm_acc_handle, &pwp->gsm_regs[off >> 2]);
6525 	if (hi) {
6526 		ddi_put32(pwp->top_acc_handle,
6527 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2], oldaxih);
6528 		drv_usecwait(10);
6529 		if (ddi_get32(pwp->top_acc_handle,
6530 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2]) != oldaxih) {
6531 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6532 			    "AXIH register restore failed");
6533 		}
6534 	}
6535 	ddi_put32(pwp->top_acc_handle,
6536 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], oldaxil);
6537 	drv_usecwait(10);
6538 	if (ddi_get32(pwp->top_acc_handle,
6539 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != oldaxil) {
6540 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6541 		    "AXIL register restore failed");
6542 	}
6543 	mutex_exit(&pwp->axil_lock);
6544 	return (rv);
6545 }
6546 
6547 void
6548 pmcs_wr_gsm_reg(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6549 {
6550 	uint32_t newaxil, oldaxil;
6551 
6552 	newaxil = off & ~GSM_BASE_MASK;
6553 	off &= GSM_BASE_MASK;
6554 	mutex_enter(&pwp->axil_lock);
6555 	oldaxil = ddi_get32(pwp->top_acc_handle,
6556 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]);
6557 	ddi_put32(pwp->top_acc_handle,
6558 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], newaxil);
6559 	drv_usecwait(10);
6560 	if (ddi_get32(pwp->top_acc_handle,
6561 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != newaxil) {
6562 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6563 		    "AXIL register update failed");
6564 	}
6565 	ddi_put32(pwp->gsm_acc_handle, &pwp->gsm_regs[off >> 2], val);
6566 	ddi_put32(pwp->top_acc_handle,
6567 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], oldaxil);
6568 	drv_usecwait(10);
6569 	if (ddi_get32(pwp->top_acc_handle,
6570 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != oldaxil) {
6571 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6572 		    "AXIL register restore failed");
6573 	}
6574 	mutex_exit(&pwp->axil_lock);
6575 }
6576 
6577 uint32_t
6578 pmcs_rd_topunit(pmcs_hw_t *pwp, uint32_t off)
6579 {
6580 	switch (off) {
6581 	case PMCS_SPC_RESET:
6582 	case PMCS_SPC_BOOT_STRAP:
6583 	case PMCS_SPC_DEVICE_ID:
6584 	case PMCS_DEVICE_REVISION:
6585 		off = pmcs_rd_gsm_reg(pwp, 0, off);
6586 		break;
6587 	default:
6588 		off = ddi_get32(pwp->top_acc_handle,
6589 		    &pwp->top_regs[off >> 2]);
6590 		break;
6591 	}
6592 	return (off);
6593 }
6594 
6595 void
6596 pmcs_wr_topunit(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6597 {
6598 	switch (off) {
6599 	case PMCS_SPC_RESET:
6600 	case PMCS_DEVICE_REVISION:
6601 		pmcs_wr_gsm_reg(pwp, off, val);
6602 		break;
6603 	default:
6604 		ddi_put32(pwp->top_acc_handle, &pwp->top_regs[off >> 2], val);
6605 		break;
6606 	}
6607 }
6608 
6609 uint32_t
6610 pmcs_rd_msgunit(pmcs_hw_t *pwp, uint32_t off)
6611 {
6612 	return (ddi_get32(pwp->msg_acc_handle, &pwp->msg_regs[off >> 2]));
6613 }
6614 
6615 uint32_t
6616 pmcs_rd_mpi_tbl(pmcs_hw_t *pwp, uint32_t off)
6617 {
6618 	return (ddi_get32(pwp->mpi_acc_handle,
6619 	    &pwp->mpi_regs[(pwp->mpi_offset + off) >> 2]));
6620 }
6621 
6622 uint32_t
6623 pmcs_rd_gst_tbl(pmcs_hw_t *pwp, uint32_t off)
6624 {
6625 	return (ddi_get32(pwp->mpi_acc_handle,
6626 	    &pwp->mpi_regs[(pwp->mpi_gst_offset + off) >> 2]));
6627 }
6628 
6629 uint32_t
6630 pmcs_rd_iqc_tbl(pmcs_hw_t *pwp, uint32_t off)
6631 {
6632 	return (ddi_get32(pwp->mpi_acc_handle,
6633 	    &pwp->mpi_regs[(pwp->mpi_iqc_offset + off) >> 2]));
6634 }
6635 
6636 uint32_t
6637 pmcs_rd_oqc_tbl(pmcs_hw_t *pwp, uint32_t off)
6638 {
6639 	return (ddi_get32(pwp->mpi_acc_handle,
6640 	    &pwp->mpi_regs[(pwp->mpi_oqc_offset + off) >> 2]));
6641 }
6642 
6643 uint32_t
6644 pmcs_rd_iqpi(pmcs_hw_t *pwp, uint32_t qnum)
6645 {
6646 	return (ddi_get32(pwp->mpi_acc_handle,
6647 	    &pwp->mpi_regs[pwp->iqpi_offset[qnum] >> 2]));
6648 }
6649 
6650 uint32_t
6651 pmcs_rd_oqci(pmcs_hw_t *pwp, uint32_t qnum)
6652 {
6653 	return (ddi_get32(pwp->mpi_acc_handle,
6654 	    &pwp->mpi_regs[pwp->oqci_offset[qnum] >> 2]));
6655 }
6656 
6657 void
6658 pmcs_wr_msgunit(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6659 {
6660 	ddi_put32(pwp->msg_acc_handle, &pwp->msg_regs[off >> 2], val);
6661 }
6662 
6663 void
6664 pmcs_wr_mpi_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6665 {
6666 	ddi_put32(pwp->mpi_acc_handle,
6667 	    &pwp->mpi_regs[(pwp->mpi_offset + off) >> 2], (val));
6668 }
6669 
6670 void
6671 pmcs_wr_gst_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6672 {
6673 	ddi_put32(pwp->mpi_acc_handle,
6674 	    &pwp->mpi_regs[(pwp->mpi_gst_offset + off) >> 2], val);
6675 }
6676 
6677 void
6678 pmcs_wr_iqc_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6679 {
6680 	ddi_put32(pwp->mpi_acc_handle,
6681 	    &pwp->mpi_regs[(pwp->mpi_iqc_offset + off) >> 2], val);
6682 }
6683 
6684 void
6685 pmcs_wr_oqc_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6686 {
6687 	ddi_put32(pwp->mpi_acc_handle,
6688 	    &pwp->mpi_regs[(pwp->mpi_oqc_offset + off) >> 2], val);
6689 }
6690 
6691 void
6692 pmcs_wr_iqci(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6693 {
6694 	((uint32_t *)((void *)pwp->cip))[IQ_OFFSET(qnum) >> 2] = val;
6695 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORDEV) !=
6696 	    DDI_SUCCESS) {
6697 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6698 		    "%s: ddi_dma_sync failed?", __func__);
6699 	}
6700 }
6701 
6702 void
6703 pmcs_wr_iqpi(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6704 {
6705 	ddi_put32(pwp->mpi_acc_handle,
6706 	    &pwp->mpi_regs[pwp->iqpi_offset[qnum] >> 2], val);
6707 }
6708 
6709 void
6710 pmcs_wr_oqci(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6711 {
6712 	ddi_put32(pwp->mpi_acc_handle,
6713 	    &pwp->mpi_regs[pwp->oqci_offset[qnum] >> 2], val);
6714 }
6715 
6716 void
6717 pmcs_wr_oqpi(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6718 {
6719 	((uint32_t *)((void *)pwp->cip))[OQ_OFFSET(qnum) >> 2] = val;
6720 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORDEV) !=
6721 	    DDI_SUCCESS) {
6722 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6723 		    "%s: ddi_dma_sync failed?", __func__);
6724 	}
6725 }
6726 
6727 /*
6728  * Check the status value of an outbound IOMB and report anything bad
6729  */
6730 
6731 void
6732 pmcs_check_iomb_status(pmcs_hw_t *pwp, uint32_t *iomb)
6733 {
6734 	uint16_t 	opcode;
6735 	int		offset;
6736 
6737 	if (iomb == NULL) {
6738 		return;
6739 	}
6740 
6741 	opcode = LE_32(iomb[0]) & 0xfff;
6742 
6743 	switch (opcode) {
6744 		/*
6745 		 * The following have no status field, so ignore them
6746 		 */
6747 	case PMCOUT_ECHO:
6748 	case PMCOUT_SAS_HW_EVENT:
6749 	case PMCOUT_GET_DEVICE_HANDLE:
6750 	case PMCOUT_SATA_EVENT:
6751 	case PMCOUT_SSP_EVENT:
6752 	case PMCOUT_DEVICE_HANDLE_ARRIVED:
6753 	case PMCOUT_GPIO:
6754 	case PMCOUT_GPIO_EVENT:
6755 	case PMCOUT_GET_TIME_STAMP:
6756 	case PMCOUT_SKIP_ENTRIES:
6757 	case PMCOUT_GET_NVMD_DATA:	/* Actually lower 16 bits of word 3 */
6758 	case PMCOUT_SET_NVMD_DATA:	/* but ignore - we don't use these */
6759 	case PMCOUT_DEVICE_HANDLE_REMOVED:
6760 	case PMCOUT_SSP_REQUEST_RECEIVED:
6761 		return;
6762 
6763 	case PMCOUT_GENERAL_EVENT:
6764 		offset = 1;
6765 		break;
6766 
6767 	case PMCOUT_SSP_COMPLETION:
6768 	case PMCOUT_SMP_COMPLETION:
6769 	case PMCOUT_DEVICE_REGISTRATION:
6770 	case PMCOUT_DEREGISTER_DEVICE_HANDLE:
6771 	case PMCOUT_SATA_COMPLETION:
6772 	case PMCOUT_DEVICE_INFO:
6773 	case PMCOUT_FW_FLASH_UPDATE:
6774 	case PMCOUT_SSP_ABORT:
6775 	case PMCOUT_SATA_ABORT:
6776 	case PMCOUT_SAS_DIAG_MODE_START_END:
6777 	case PMCOUT_SAS_HW_EVENT_ACK_ACK:
6778 	case PMCOUT_SMP_ABORT:
6779 	case PMCOUT_SET_DEVICE_STATE:
6780 	case PMCOUT_GET_DEVICE_STATE:
6781 	case PMCOUT_SET_DEVICE_INFO:
6782 		offset = 2;
6783 		break;
6784 
6785 	case PMCOUT_LOCAL_PHY_CONTROL:
6786 	case PMCOUT_SAS_DIAG_EXECUTE:
6787 	case PMCOUT_PORT_CONTROL:
6788 		offset = 3;
6789 		break;
6790 
6791 	case PMCOUT_GET_INFO:
6792 	case PMCOUT_GET_VPD:
6793 	case PMCOUT_SAS_ASSISTED_DISCOVERY_EVENT:
6794 	case PMCOUT_SATA_ASSISTED_DISCOVERY_EVENT:
6795 	case PMCOUT_SET_VPD:
6796 	case PMCOUT_TWI:
6797 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG,
6798 		    "Got response for deprecated opcode", iomb);
6799 		return;
6800 
6801 	default:
6802 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG,
6803 		    "Got response for unknown opcode", iomb);
6804 		return;
6805 	}
6806 
6807 	if (LE_32(iomb[offset]) != PMCOUT_STATUS_OK) {
6808 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG,
6809 		    "bad status on TAG_TYPE_NONE command", iomb);
6810 	}
6811 }
6812 
6813 /*
6814  * Called with statlock held
6815  */
6816 void
6817 pmcs_clear_xp(pmcs_hw_t *pwp, pmcs_xscsi_t *xp)
6818 {
6819 	_NOTE(ARGUNUSED(pwp));
6820 
6821 	ASSERT(mutex_owned(&xp->statlock));
6822 
6823 	pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, xp, "%s: Device 0x%p is gone.",
6824 	    __func__, (void *)xp);
6825 
6826 	/*
6827 	 * Clear the dip now.  This keeps pmcs_remove_device from attempting
6828 	 * to call us on the same device while we're still flushing queues.
6829 	 * The only side effect is we can no longer update SM-HBA properties,
6830 	 * but this device is going away anyway, so no matter.
6831 	 */
6832 	xp->dip = NULL;
6833 	xp->smpd = NULL;
6834 	xp->special_running = 0;
6835 	xp->recovering = 0;
6836 	xp->recover_wait = 0;
6837 	xp->draining = 0;
6838 	xp->new = 0;
6839 	xp->assigned = 0;
6840 	xp->dev_state = 0;
6841 	xp->tagmap = 0;
6842 	xp->dev_gone = 1;
6843 	xp->event_recovery = 0;
6844 	xp->dtype = NOTHING;
6845 	xp->wq_recovery_tail = NULL;
6846 	/* Don't clear xp->phy */
6847 	/* Don't clear xp->actv_cnt */
6848 	/* Don't clear xp->actv_pkts */
6849 
6850 	/*
6851 	 * Flush all target queues
6852 	 */
6853 	pmcs_flush_target_queues(pwp, xp, PMCS_TGT_ALL_QUEUES);
6854 }
6855 
6856 static int
6857 pmcs_smp_function_result(pmcs_hw_t *pwp, smp_response_frame_t *srf)
6858 {
6859 	int result = srf->srf_result;
6860 
6861 	switch (result) {
6862 	case SMP_RES_UNKNOWN_FUNCTION:
6863 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6864 		    "%s: SMP DISCOVER Response "
6865 		    "Function Result: Unknown SMP Function(0x%x)",
6866 		    __func__, result);
6867 		break;
6868 	case SMP_RES_FUNCTION_FAILED:
6869 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6870 		    "%s: SMP DISCOVER Response "
6871 		    "Function Result: SMP Function Failed(0x%x)",
6872 		    __func__, result);
6873 		break;
6874 	case SMP_RES_INVALID_REQUEST_FRAME_LENGTH:
6875 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6876 		    "%s: SMP DISCOVER Response "
6877 		    "Function Result: Invalid Request Frame Length(0x%x)",
6878 		    __func__, result);
6879 		break;
6880 	case SMP_RES_INCOMPLETE_DESCRIPTOR_LIST:
6881 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6882 		    "%s: SMP DISCOVER Response "
6883 		    "Function Result: Incomplete Descriptor List(0x%x)",
6884 		    __func__, result);
6885 		break;
6886 	case SMP_RES_PHY_DOES_NOT_EXIST:
6887 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6888 		    "%s: SMP DISCOVER Response "
6889 		    "Function Result: PHY does not exist(0x%x)",
6890 		    __func__, result);
6891 		break;
6892 	case SMP_RES_PHY_VACANT:
6893 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6894 		    "%s: SMP DISCOVER Response "
6895 		    "Function Result: PHY Vacant(0x%x)",
6896 		    __func__, result);
6897 		break;
6898 	default:
6899 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6900 		    "%s: SMP DISCOVER Response "
6901 		    "Function Result: (0x%x)",
6902 		    __func__, result);
6903 		break;
6904 	}
6905 
6906 	return (result);
6907 }
6908 
6909 /*
6910  * Do all the repetitive stuff necessary to setup for DMA
6911  *
6912  * pwp: Used for dip
6913  * dma_attr: ddi_dma_attr_t to use for the mapping
6914  * acch: ddi_acc_handle_t to use for the mapping
6915  * dmah: ddi_dma_handle_t to use
6916  * length: Amount of memory for mapping
6917  * kvap: Pointer filled in with kernel virtual address on successful return
6918  * dma_addr: Pointer filled in with DMA address on successful return
6919  */
6920 boolean_t
6921 pmcs_dma_setup(pmcs_hw_t *pwp, ddi_dma_attr_t *dma_attr, ddi_acc_handle_t *acch,
6922     ddi_dma_handle_t *dmah, size_t length, caddr_t *kvap, uint64_t *dma_addr)
6923 {
6924 	dev_info_t		*dip = pwp->dip;
6925 	ddi_dma_cookie_t	cookie;
6926 	size_t			real_length;
6927 	uint_t			ddma_flag = DDI_DMA_CONSISTENT;
6928 	uint_t			ddabh_flag = DDI_DMA_CONSISTENT | DDI_DMA_RDWR;
6929 	uint_t			cookie_cnt;
6930 	ddi_device_acc_attr_t	mattr = {
6931 		DDI_DEVICE_ATTR_V0,
6932 		DDI_NEVERSWAP_ACC,
6933 		DDI_STRICTORDER_ACC,
6934 		DDI_DEFAULT_ACC
6935 	};
6936 
6937 	*acch = NULL;
6938 	*dmah = NULL;
6939 
6940 	if (ddi_dma_alloc_handle(dip, dma_attr, DDI_DMA_SLEEP, NULL, dmah) !=
6941 	    DDI_SUCCESS) {
6942 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6943 		    "Failed to allocate DMA handle");
6944 		return (B_FALSE);
6945 	}
6946 
6947 	if (ddi_dma_mem_alloc(*dmah, length, &mattr, ddma_flag, DDI_DMA_SLEEP,
6948 	    NULL, kvap, &real_length, acch) != DDI_SUCCESS) {
6949 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6950 		    "Failed to allocate DMA mem");
6951 		ddi_dma_free_handle(dmah);
6952 		*dmah = NULL;
6953 		return (B_FALSE);
6954 	}
6955 
6956 	if (ddi_dma_addr_bind_handle(*dmah, NULL, *kvap, real_length,
6957 	    ddabh_flag, DDI_DMA_SLEEP, NULL, &cookie, &cookie_cnt)
6958 	    != DDI_DMA_MAPPED) {
6959 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL, "Failed to bind DMA");
6960 		ddi_dma_free_handle(dmah);
6961 		ddi_dma_mem_free(acch);
6962 		*dmah = NULL;
6963 		*acch = NULL;
6964 		return (B_FALSE);
6965 	}
6966 
6967 	if (cookie_cnt != 1) {
6968 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL, "Multiple cookies");
6969 		if (ddi_dma_unbind_handle(*dmah) != DDI_SUCCESS) {
6970 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL, "Condition "
6971 			    "failed at %s():%d", __func__, __LINE__);
6972 		}
6973 		ddi_dma_free_handle(dmah);
6974 		ddi_dma_mem_free(acch);
6975 		*dmah = NULL;
6976 		*acch = NULL;
6977 		return (B_FALSE);
6978 	}
6979 
6980 	*dma_addr = cookie.dmac_laddress;
6981 
6982 	return (B_TRUE);
6983 }
6984 
6985 /*
6986  * Flush requested queues for a particular target.  Called with statlock held
6987  */
6988 void
6989 pmcs_flush_target_queues(pmcs_hw_t *pwp, pmcs_xscsi_t *tgt, uint8_t queues)
6990 {
6991 	pmcs_cmd_t	*sp, *sp_next;
6992 	pmcwork_t	*pwrk;
6993 
6994 	ASSERT(pwp != NULL);
6995 	ASSERT(tgt != NULL);
6996 
6997 	pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, tgt,
6998 	    "%s: Flushing queues (%d) for target 0x%p", __func__,
6999 	    queues, (void *)tgt);
7000 
7001 	/*
7002 	 * Commands on the wait queue (or the special queue below) don't have
7003 	 * work structures associated with them.
7004 	 */
7005 	if (queues & PMCS_TGT_WAIT_QUEUE) {
7006 		mutex_enter(&tgt->wqlock);
7007 		while ((sp = STAILQ_FIRST(&tgt->wq)) != NULL) {
7008 			STAILQ_REMOVE(&tgt->wq, sp, pmcs_cmd, cmd_next);
7009 			pmcs_prt(pwp, PMCS_PRT_DEBUG1, NULL, tgt,
7010 			    "%s: Removing cmd 0x%p from wq for target 0x%p",
7011 			    __func__, (void *)sp, (void *)tgt);
7012 			CMD2PKT(sp)->pkt_reason = CMD_DEV_GONE;
7013 			CMD2PKT(sp)->pkt_state = STATE_GOT_BUS;
7014 			mutex_exit(&tgt->wqlock);
7015 			pmcs_dma_unload(pwp, sp);
7016 			mutex_enter(&pwp->cq_lock);
7017 			STAILQ_INSERT_TAIL(&pwp->cq, sp, cmd_next);
7018 			PMCS_CQ_RUN_LOCKED(pwp);
7019 			mutex_exit(&pwp->cq_lock);
7020 			mutex_enter(&tgt->wqlock);
7021 		}
7022 		mutex_exit(&tgt->wqlock);
7023 	}
7024 
7025 	/*
7026 	 * Commands on the active queue will have work structures associated
7027 	 * with them.
7028 	 */
7029 	if (queues & PMCS_TGT_ACTIVE_QUEUE) {
7030 		mutex_exit(&tgt->statlock);
7031 		mutex_enter(&tgt->aqlock);
7032 		sp = STAILQ_FIRST(&tgt->aq);
7033 		while (sp) {
7034 			sp_next = STAILQ_NEXT(sp, cmd_next);
7035 			pwrk = pmcs_tag2wp(pwp, sp->cmd_tag, B_FALSE);
7036 
7037 			/*
7038 			 * If we don't find a work structure, it's because
7039 			 * the command is already complete.  If so, move on
7040 			 * to the next one.
7041 			 */
7042 			if (pwrk == NULL) {
7043 				pmcs_prt(pwp, PMCS_PRT_DEBUG1, tgt->phy, tgt,
7044 				    "%s: Not removing cmd 0x%p (htag 0x%x) "
7045 				    "from aq", __func__, (void *)sp,
7046 				    sp->cmd_tag);
7047 				sp = sp_next;
7048 				continue;
7049 			}
7050 
7051 			STAILQ_REMOVE(&tgt->aq, sp, pmcs_cmd, cmd_next);
7052 			pmcs_prt(pwp, PMCS_PRT_DEBUG1, tgt->phy, tgt,
7053 			    "%s: Removing cmd 0x%p (htag 0x%x) from aq for "
7054 			    "target 0x%p", __func__, (void *)sp, sp->cmd_tag,
7055 			    (void *)tgt);
7056 			mutex_exit(&tgt->aqlock);
7057 
7058 			/*
7059 			 * Mark the work structure as dead and complete it
7060 			 */
7061 			pwrk->dead = 1;
7062 			CMD2PKT(sp)->pkt_reason = CMD_DEV_GONE;
7063 			CMD2PKT(sp)->pkt_state = STATE_GOT_BUS;
7064 			pmcs_complete_work_impl(pwp, pwrk, NULL, 0);
7065 			pmcs_dma_unload(pwp, sp);
7066 			mutex_enter(&pwp->cq_lock);
7067 			STAILQ_INSERT_TAIL(&pwp->cq, sp, cmd_next);
7068 			mutex_exit(&pwp->cq_lock);
7069 			mutex_enter(&tgt->aqlock);
7070 			sp = sp_next;
7071 		}
7072 		mutex_exit(&tgt->aqlock);
7073 		mutex_enter(&tgt->statlock);
7074 	}
7075 
7076 	if (queues & PMCS_TGT_SPECIAL_QUEUE) {
7077 		while ((sp = STAILQ_FIRST(&tgt->sq)) != NULL) {
7078 			STAILQ_REMOVE(&tgt->sq, sp, pmcs_cmd, cmd_next);
7079 			pmcs_prt(pwp, PMCS_PRT_DEBUG1, tgt->phy, tgt,
7080 			    "%s: Removing cmd 0x%p from sq for target 0x%p",
7081 			    __func__, (void *)sp, (void *)tgt);
7082 			CMD2PKT(sp)->pkt_reason = CMD_DEV_GONE;
7083 			CMD2PKT(sp)->pkt_state = STATE_GOT_BUS;
7084 			pmcs_dma_unload(pwp, sp);
7085 			mutex_enter(&pwp->cq_lock);
7086 			STAILQ_INSERT_TAIL(&pwp->cq, sp, cmd_next);
7087 			mutex_exit(&pwp->cq_lock);
7088 		}
7089 	}
7090 
7091 	if (queues == PMCS_TGT_ALL_QUEUES) {
7092 		mutex_exit(&tgt->statlock);
7093 		pmcs_flush_nonio_cmds(pwp, tgt);
7094 		mutex_enter(&tgt->statlock);
7095 	}
7096 }
7097 
7098 /*
7099  * Flush non-IO commands for this target. This cleans up the off-queue
7100  * work with no pmcs_cmd_t associated.
7101  */
7102 static void
7103 pmcs_flush_nonio_cmds(pmcs_hw_t *pwp, pmcs_xscsi_t *tgt)
7104 {
7105 	int i;
7106 	pmcwork_t *p;
7107 
7108 	for (i = 0; i < pwp->max_cmd; i++) {
7109 		p = &pwp->work[i];
7110 		mutex_enter(&p->lock);
7111 		if (p->xp != tgt) {
7112 			mutex_exit(&p->lock);
7113 			continue;
7114 		}
7115 		if (p->htag & PMCS_TAG_NONIO_CMD) {
7116 			if (!PMCS_COMMAND_ACTIVE(p) || PMCS_COMMAND_DONE(p)) {
7117 				mutex_exit(&p->lock);
7118 				continue;
7119 			}
7120 			pmcs_prt(pwp, PMCS_PRT_DEBUG, p->phy, p->xp,
7121 			    "%s: Completing non-io cmd with HTAG 0x%x",
7122 			    __func__, p->htag);
7123 			pmcs_complete_work_impl(pwp, p, NULL, 0);
7124 		} else {
7125 			mutex_exit(&p->lock);
7126 		}
7127 	}
7128 }
7129 
7130 void
7131 pmcs_complete_work_impl(pmcs_hw_t *pwp, pmcwork_t *pwrk, uint32_t *iomb,
7132     size_t amt)
7133 {
7134 	pmcs_phy_t	*pptr = NULL;
7135 
7136 	switch (PMCS_TAG_TYPE(pwrk->htag)) {
7137 	case PMCS_TAG_TYPE_CBACK:
7138 	{
7139 		pmcs_cb_t callback = (pmcs_cb_t)pwrk->ptr;
7140 		(*callback)(pwp, pwrk, iomb);
7141 		break;
7142 	}
7143 	case PMCS_TAG_TYPE_WAIT:
7144 		if (pwrk->arg && iomb && amt) {
7145 			(void) memcpy(pwrk->arg, iomb, amt);
7146 		}
7147 		cv_signal(&pwrk->sleep_cv);
7148 		mutex_exit(&pwrk->lock);
7149 		break;
7150 	case PMCS_TAG_TYPE_NONE:
7151 #ifdef DEBUG
7152 		pmcs_check_iomb_status(pwp, iomb);
7153 #endif
7154 		pptr = pwrk->phy;
7155 		pmcs_pwork(pwp, pwrk);
7156 
7157 		/* If this was an abort all, clean up if needed */
7158 		if ((pwrk->abt_htag == PMCS_ABT_HTAG_ALL) && (pptr != NULL)) {
7159 			mutex_enter(&pptr->phy_lock);
7160 			if (pptr->abort_all_start) {
7161 				pptr->abort_all_start = 0;
7162 				cv_signal(&pptr->abort_all_cv);
7163 			}
7164 			mutex_exit(&pptr->phy_lock);
7165 		}
7166 		break;
7167 	default:
7168 		/*
7169 		 * We will leak a structure here if we don't know
7170 		 * what happened
7171 		 */
7172 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
7173 		    "%s: Unknown PMCS_TAG_TYPE (%x)",
7174 		    __func__, PMCS_TAG_TYPE(pwrk->htag));
7175 		break;
7176 	}
7177 }
7178 
7179 /*
7180  * Determine if iport still has targets. During detach(9E), if SCSA is
7181  * successfull in its guarantee of tran_tgt_free(9E) before detach(9E),
7182  * this should always return B_FALSE.
7183  */
7184 boolean_t
7185 pmcs_iport_has_targets(pmcs_hw_t *pwp, pmcs_iport_t *iport)
7186 {
7187 	pmcs_xscsi_t *xp;
7188 	int i;
7189 
7190 	mutex_enter(&pwp->lock);
7191 
7192 	if (!pwp->targets || !pwp->max_dev) {
7193 		mutex_exit(&pwp->lock);
7194 		return (B_FALSE);
7195 	}
7196 
7197 	for (i = 0; i < pwp->max_dev; i++) {
7198 		xp = pwp->targets[i];
7199 		if ((xp == NULL) || (xp->phy == NULL) ||
7200 		    (xp->phy->iport != iport)) {
7201 			continue;
7202 		}
7203 
7204 		mutex_exit(&pwp->lock);
7205 		return (B_TRUE);
7206 	}
7207 
7208 	mutex_exit(&pwp->lock);
7209 	return (B_FALSE);
7210 }
7211 
7212 /*
7213  * Called with softstate lock held
7214  */
7215 void
7216 pmcs_destroy_target(pmcs_xscsi_t *target)
7217 {
7218 	pmcs_hw_t *pwp = target->pwp;
7219 	pmcs_iport_t *iport;
7220 
7221 	ASSERT(pwp);
7222 	ASSERT(mutex_owned(&pwp->lock));
7223 
7224 	if (!target->ua) {
7225 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, target,
7226 		    "%s: target %p iport address is null",
7227 		    __func__, (void *)target);
7228 	}
7229 
7230 	iport = pmcs_get_iport_by_ua(pwp, target->ua);
7231 	if (iport == NULL) {
7232 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, target,
7233 		    "%s: no iport associated with tgt(0x%p)",
7234 		    __func__, (void *)target);
7235 		return;
7236 	}
7237 
7238 	pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, NULL, target,
7239 	    "%s: free target %p", __func__, (void *)target);
7240 	if (target->ua) {
7241 		strfree(target->ua);
7242 	}
7243 
7244 	mutex_destroy(&target->wqlock);
7245 	mutex_destroy(&target->aqlock);
7246 	mutex_destroy(&target->statlock);
7247 	cv_destroy(&target->reset_cv);
7248 	cv_destroy(&target->abort_cv);
7249 	ddi_soft_state_bystr_fini(&target->lun_sstate);
7250 	ddi_soft_state_bystr_free(iport->tgt_sstate, target->unit_address);
7251 	pmcs_rele_iport(iport);
7252 }
7253 
7254 /*
7255  * pmcs_lock_phy_impl
7256  *
7257  * This function is what does the actual work for pmcs_lock_phy.  It will
7258  * lock all PHYs from phyp down in a top-down fashion.
7259  *
7260  * Locking notes:
7261  * 1. level starts from 0 for the PHY ("parent") that's passed in.  It is
7262  * not a reflection of the actual level of the PHY in the SAS topology.
7263  * 2. If parent is an expander, then parent is locked along with all its
7264  * descendents.
7265  * 3. Expander subsidiary PHYs at level 0 are not locked.  It is the
7266  * responsibility of the caller to individually lock expander subsidiary PHYs
7267  * at level 0 if necessary.
7268  * 4. Siblings at level 0 are not traversed due to the possibility that we're
7269  * locking a PHY on the dead list.  The siblings could be pointing to invalid
7270  * PHYs.  We don't lock siblings at level 0 anyway.
7271  */
7272 static void
7273 pmcs_lock_phy_impl(pmcs_phy_t *phyp, int level)
7274 {
7275 	pmcs_phy_t *tphyp;
7276 
7277 	ASSERT((phyp->dtype == SAS) || (phyp->dtype == SATA) ||
7278 	    (phyp->dtype == EXPANDER) || (phyp->dtype == NOTHING));
7279 
7280 	/*
7281 	 * Start walking the PHYs.
7282 	 */
7283 	tphyp = phyp;
7284 	while (tphyp) {
7285 		/*
7286 		 * If we're at the top level, only lock ourselves.  For anything
7287 		 * at level > 0, traverse children while locking everything.
7288 		 */
7289 		if ((level > 0) || (tphyp == phyp)) {
7290 			pmcs_prt(tphyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, tphyp,
7291 			    NULL, "%s: PHY 0x%p parent 0x%p path %s lvl %d",
7292 			    __func__, (void *)tphyp, (void *)tphyp->parent,
7293 			    tphyp->path, level);
7294 			mutex_enter(&tphyp->phy_lock);
7295 
7296 			if (tphyp->children) {
7297 				pmcs_lock_phy_impl(tphyp->children, level + 1);
7298 			}
7299 		}
7300 
7301 		if (level == 0) {
7302 			return;
7303 		}
7304 
7305 		tphyp = tphyp->sibling;
7306 	}
7307 }
7308 
7309 /*
7310  * pmcs_lock_phy
7311  *
7312  * This function is responsible for locking a PHY and all its descendents
7313  */
7314 void
7315 pmcs_lock_phy(pmcs_phy_t *phyp)
7316 {
7317 #ifdef DEBUG
7318 	char *callername = NULL;
7319 	ulong_t off;
7320 
7321 	ASSERT(phyp != NULL);
7322 
7323 	callername = modgetsymname((uintptr_t)caller(), &off);
7324 
7325 	if (callername == NULL) {
7326 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, phyp, NULL,
7327 		    "%s: PHY 0x%p path %s caller: unknown", __func__,
7328 		    (void *)phyp, phyp->path);
7329 	} else {
7330 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, phyp, NULL,
7331 		    "%s: PHY 0x%p path %s caller: %s+%lx", __func__,
7332 		    (void *)phyp, phyp->path, callername, off);
7333 	}
7334 #else
7335 	pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, phyp, NULL,
7336 	    "%s: PHY 0x%p path %s", __func__, (void *)phyp, phyp->path);
7337 #endif
7338 	pmcs_lock_phy_impl(phyp, 0);
7339 }
7340 
7341 /*
7342  * pmcs_unlock_phy_impl
7343  *
7344  * Unlock all PHYs from phyp down in a bottom-up fashion.
7345  */
7346 static void
7347 pmcs_unlock_phy_impl(pmcs_phy_t *phyp, int level)
7348 {
7349 	pmcs_phy_t *phy_next;
7350 
7351 	ASSERT((phyp->dtype == SAS) || (phyp->dtype == SATA) ||
7352 	    (phyp->dtype == EXPANDER) || (phyp->dtype == NOTHING));
7353 
7354 	/*
7355 	 * Recurse down to the bottom PHYs
7356 	 */
7357 	if (level == 0) {
7358 		if (phyp->children) {
7359 			pmcs_unlock_phy_impl(phyp->children, level + 1);
7360 		}
7361 	} else {
7362 		phy_next = phyp;
7363 		while (phy_next) {
7364 			if (phy_next->children) {
7365 				pmcs_unlock_phy_impl(phy_next->children,
7366 				    level + 1);
7367 			}
7368 			phy_next = phy_next->sibling;
7369 		}
7370 	}
7371 
7372 	/*
7373 	 * Iterate through PHYs unlocking all at level > 0 as well the top PHY
7374 	 */
7375 	phy_next = phyp;
7376 	while (phy_next) {
7377 		if ((level > 0) || (phy_next == phyp)) {
7378 			pmcs_prt(phy_next->pwp, PMCS_PRT_DEBUG_PHY_LOCKING,
7379 			    phy_next, NULL,
7380 			    "%s: PHY 0x%p parent 0x%p path %s lvl %d",
7381 			    __func__, (void *)phy_next,
7382 			    (void *)phy_next->parent, phy_next->path, level);
7383 			mutex_exit(&phy_next->phy_lock);
7384 		}
7385 
7386 		if (level == 0) {
7387 			return;
7388 		}
7389 
7390 		phy_next = phy_next->sibling;
7391 	}
7392 }
7393 
7394 /*
7395  * pmcs_unlock_phy
7396  *
7397  * Unlock a PHY and all its descendents
7398  */
7399 void
7400 pmcs_unlock_phy(pmcs_phy_t *phyp)
7401 {
7402 #ifdef DEBUG
7403 	char *callername = NULL;
7404 	ulong_t off;
7405 
7406 	ASSERT(phyp != NULL);
7407 
7408 	callername = modgetsymname((uintptr_t)caller(), &off);
7409 
7410 	if (callername == NULL) {
7411 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, phyp, NULL,
7412 		    "%s: PHY 0x%p path %s caller: unknown", __func__,
7413 		    (void *)phyp, phyp->path);
7414 	} else {
7415 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, phyp, NULL,
7416 		    "%s: PHY 0x%p path %s caller: %s+%lx", __func__,
7417 		    (void *)phyp, phyp->path, callername, off);
7418 	}
7419 #else
7420 	pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG_PHY_LOCKING, phyp, NULL,
7421 	    "%s: PHY 0x%p path %s", __func__, (void *)phyp, phyp->path);
7422 #endif
7423 	pmcs_unlock_phy_impl(phyp, 0);
7424 }
7425 
7426 /*
7427  * pmcs_get_root_phy
7428  *
7429  * For a given phy pointer return its root phy.
7430  * This function must only be called during discovery in order to ensure that
7431  * the chain of PHYs from phyp up to the root PHY doesn't change.
7432  */
7433 pmcs_phy_t *
7434 pmcs_get_root_phy(pmcs_phy_t *phyp)
7435 {
7436 	ASSERT(phyp);
7437 
7438 	while (phyp) {
7439 		if (IS_ROOT_PHY(phyp)) {
7440 			break;
7441 		}
7442 		phyp = phyp->parent;
7443 	}
7444 
7445 	return (phyp);
7446 }
7447 
7448 /*
7449  * pmcs_free_dma_chunklist
7450  *
7451  * Free DMA S/G chunk list
7452  */
7453 void
7454 pmcs_free_dma_chunklist(pmcs_hw_t *pwp)
7455 {
7456 	pmcs_chunk_t	*pchunk;
7457 
7458 	while (pwp->dma_chunklist) {
7459 		pchunk = pwp->dma_chunklist;
7460 		pwp->dma_chunklist = pwp->dma_chunklist->next;
7461 		if (pchunk->dma_handle) {
7462 			if (ddi_dma_unbind_handle(pchunk->dma_handle) !=
7463 			    DDI_SUCCESS) {
7464 				pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
7465 				    "Condition failed at %s():%d",
7466 				    __func__, __LINE__);
7467 			}
7468 			ddi_dma_free_handle(&pchunk->dma_handle);
7469 			ddi_dma_mem_free(&pchunk->acc_handle);
7470 		}
7471 		kmem_free(pchunk, sizeof (pmcs_chunk_t));
7472 	}
7473 }
7474 
7475 /*ARGSUSED2*/
7476 int
7477 pmcs_phy_constructor(void *buf, void *arg, int kmflags)
7478 {
7479 	pmcs_hw_t *pwp = (pmcs_hw_t *)arg;
7480 	pmcs_phy_t *phyp = (pmcs_phy_t *)buf;
7481 
7482 	mutex_init(&phyp->phy_lock, NULL, MUTEX_DRIVER,
7483 	    DDI_INTR_PRI(pwp->intr_pri));
7484 	cv_init(&phyp->abort_all_cv, NULL, CV_DRIVER, NULL);
7485 	return (0);
7486 }
7487 
7488 /*ARGSUSED1*/
7489 void
7490 pmcs_phy_destructor(void *buf, void *arg)
7491 {
7492 	pmcs_phy_t *phyp = (pmcs_phy_t *)buf;
7493 
7494 	cv_destroy(&phyp->abort_all_cv);
7495 	mutex_destroy(&phyp->phy_lock);
7496 }
7497 
7498 /*
7499  * Free all PHYs from the kmem_cache starting at phyp as well as everything
7500  * on the dead_phys list.
7501  *
7502  * NOTE: This function does not free root PHYs as they are not allocated
7503  * from the kmem_cache.
7504  *
7505  * No PHY locks are acquired as this should only be called during DDI_DETACH
7506  * or soft reset (while pmcs interrupts are disabled).
7507  */
7508 void
7509 pmcs_free_all_phys(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
7510 {
7511 	pmcs_phy_t *tphyp, *nphyp, *cphyp;
7512 
7513 	if (phyp == NULL) {
7514 		return;
7515 	}
7516 
7517 	for (tphyp = phyp; tphyp; tphyp = nphyp) {
7518 		nphyp = tphyp->sibling;
7519 		cphyp = tphyp->children;
7520 
7521 		if (cphyp) {
7522 			tphyp->children = NULL;
7523 			pmcs_free_all_phys(pwp, cphyp);
7524 		}
7525 
7526 		if (!IS_ROOT_PHY(tphyp)) {
7527 			tphyp->target_addr = NULL;
7528 			kmem_cache_free(pwp->phy_cache, tphyp);
7529 		}
7530 	}
7531 
7532 	mutex_enter(&pwp->dead_phylist_lock);
7533 	for (tphyp = pwp->dead_phys; tphyp; tphyp = nphyp) {
7534 		nphyp = tphyp->dead_next;
7535 		tphyp->target_addr = NULL;
7536 		kmem_cache_free(pwp->phy_cache, tphyp);
7537 	}
7538 	pwp->dead_phys = NULL;
7539 	mutex_exit(&pwp->dead_phylist_lock);
7540 }
7541 
7542 /*
7543  * Free a list of PHYs linked together by the sibling pointer back to the
7544  * kmem cache from whence they came.  This function does not recurse, so the
7545  * caller must ensure there are no children.
7546  */
7547 void
7548 pmcs_free_phys(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
7549 {
7550 	pmcs_phy_t *next_phy;
7551 
7552 	while (phyp) {
7553 		next_phy = phyp->sibling;
7554 		ASSERT(!mutex_owned(&phyp->phy_lock));
7555 		phyp->target_addr = NULL;
7556 		kmem_cache_free(pwp->phy_cache, phyp);
7557 		phyp = next_phy;
7558 	}
7559 }
7560 
7561 /*
7562  * Make a copy of an existing PHY structure.  This is used primarily in
7563  * discovery to compare the contents of an existing PHY with what gets
7564  * reported back by an expander.
7565  *
7566  * This function must not be called from any context where sleeping is
7567  * not possible.
7568  *
7569  * The new PHY is returned unlocked.
7570  */
7571 static pmcs_phy_t *
7572 pmcs_clone_phy(pmcs_phy_t *orig_phy)
7573 {
7574 	pmcs_phy_t *local;
7575 
7576 	local = kmem_cache_alloc(orig_phy->pwp->phy_cache, KM_SLEEP);
7577 
7578 	/*
7579 	 * Go ahead and just copy everything...
7580 	 */
7581 	*local = *orig_phy;
7582 	local->target_addr = &orig_phy->target;
7583 
7584 	/*
7585 	 * But the following must be set appropriately for this copy
7586 	 */
7587 	local->sibling = NULL;
7588 	local->children = NULL;
7589 	local->target = NULL;
7590 	mutex_init(&local->phy_lock, NULL, MUTEX_DRIVER,
7591 	    DDI_INTR_PRI(orig_phy->pwp->intr_pri));
7592 
7593 	return (local);
7594 }
7595 
7596 int
7597 pmcs_check_acc_handle(ddi_acc_handle_t handle)
7598 {
7599 	ddi_fm_error_t de;
7600 
7601 	if (handle == NULL) {
7602 		return (DDI_FAILURE);
7603 	}
7604 	ddi_fm_acc_err_get(handle, &de, DDI_FME_VER0);
7605 	return (de.fme_status);
7606 }
7607 
7608 int
7609 pmcs_check_dma_handle(ddi_dma_handle_t handle)
7610 {
7611 	ddi_fm_error_t de;
7612 
7613 	if (handle == NULL) {
7614 		return (DDI_FAILURE);
7615 	}
7616 	ddi_fm_dma_err_get(handle, &de, DDI_FME_VER0);
7617 	return (de.fme_status);
7618 }
7619 
7620 
7621 void
7622 pmcs_fm_ereport(pmcs_hw_t *pwp, char *detail)
7623 {
7624 	uint64_t ena;
7625 	char buf[FM_MAX_CLASS];
7626 
7627 	(void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
7628 	ena = fm_ena_generate(0, FM_ENA_FMT1);
7629 	if (DDI_FM_EREPORT_CAP(pwp->fm_capabilities)) {
7630 		ddi_fm_ereport_post(pwp->dip, buf, ena, DDI_NOSLEEP,
7631 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0, NULL);
7632 	}
7633 }
7634 
7635 int
7636 pmcs_check_acc_dma_handle(pmcs_hw_t *pwp)
7637 {
7638 	pmcs_chunk_t *pchunk;
7639 	int i;
7640 
7641 	/* check all acc & dma handles allocated in attach */
7642 	if ((pmcs_check_acc_handle(pwp->pci_acc_handle) != DDI_SUCCESS) ||
7643 	    (pmcs_check_acc_handle(pwp->msg_acc_handle) != DDI_SUCCESS) ||
7644 	    (pmcs_check_acc_handle(pwp->top_acc_handle) != DDI_SUCCESS) ||
7645 	    (pmcs_check_acc_handle(pwp->mpi_acc_handle) != DDI_SUCCESS) ||
7646 	    (pmcs_check_acc_handle(pwp->gsm_acc_handle) != DDI_SUCCESS)) {
7647 		goto check_failed;
7648 	}
7649 
7650 	for (i = 0; i < PMCS_NIQ; i++) {
7651 		if ((pmcs_check_dma_handle(
7652 		    pwp->iqp_handles[i]) != DDI_SUCCESS) ||
7653 		    (pmcs_check_acc_handle(
7654 		    pwp->iqp_acchdls[i]) != DDI_SUCCESS)) {
7655 			goto check_failed;
7656 		}
7657 	}
7658 
7659 	for (i = 0; i < PMCS_NOQ; i++) {
7660 		if ((pmcs_check_dma_handle(
7661 		    pwp->oqp_handles[i]) != DDI_SUCCESS) ||
7662 		    (pmcs_check_acc_handle(
7663 		    pwp->oqp_acchdls[i]) != DDI_SUCCESS)) {
7664 			goto check_failed;
7665 		}
7666 	}
7667 
7668 	if ((pmcs_check_dma_handle(pwp->cip_handles) != DDI_SUCCESS) ||
7669 	    (pmcs_check_acc_handle(pwp->cip_acchdls) != DDI_SUCCESS)) {
7670 		goto check_failed;
7671 	}
7672 
7673 	if (pwp->fwlog &&
7674 	    ((pmcs_check_dma_handle(pwp->fwlog_hndl) != DDI_SUCCESS) ||
7675 	    (pmcs_check_acc_handle(pwp->fwlog_acchdl) != DDI_SUCCESS))) {
7676 		goto check_failed;
7677 	}
7678 
7679 	if (pwp->regdump_hndl && pwp->regdump_acchdl &&
7680 	    ((pmcs_check_dma_handle(pwp->regdump_hndl) != DDI_SUCCESS) ||
7681 	    (pmcs_check_acc_handle(pwp->regdump_acchdl)
7682 	    != DDI_SUCCESS))) {
7683 		goto check_failed;
7684 	}
7685 
7686 
7687 	pchunk = pwp->dma_chunklist;
7688 	while (pchunk) {
7689 		if ((pmcs_check_acc_handle(pchunk->acc_handle)
7690 		    != DDI_SUCCESS) ||
7691 		    (pmcs_check_dma_handle(pchunk->dma_handle)
7692 		    != DDI_SUCCESS)) {
7693 			goto check_failed;
7694 		}
7695 		pchunk = pchunk->next;
7696 	}
7697 
7698 	return (0);
7699 
7700 check_failed:
7701 
7702 	return (1);
7703 }
7704 
7705 /*
7706  * pmcs_handle_dead_phys
7707  *
7708  * If the PHY has no outstanding work associated with it, remove it from
7709  * the dead PHY list and free it.
7710  *
7711  * If pwp->ds_err_recovering or pwp->configuring is set, don't run.
7712  * This keeps routines that need to submit work to the chip from having to
7713  * hold PHY locks to ensure that PHYs don't disappear while they do their work.
7714  */
7715 void
7716 pmcs_handle_dead_phys(pmcs_hw_t *pwp)
7717 {
7718 	pmcs_phy_t *phyp, *nphyp, *pphyp;
7719 
7720 	mutex_enter(&pwp->lock);
7721 	mutex_enter(&pwp->config_lock);
7722 
7723 	if (pwp->configuring | pwp->ds_err_recovering) {
7724 		mutex_exit(&pwp->config_lock);
7725 		mutex_exit(&pwp->lock);
7726 		return;
7727 	}
7728 
7729 	/*
7730 	 * Check every PHY in the dead PHY list
7731 	 */
7732 	mutex_enter(&pwp->dead_phylist_lock);
7733 	phyp = pwp->dead_phys;
7734 	pphyp = NULL;	/* Set previous PHY to NULL */
7735 
7736 	while (phyp != NULL) {
7737 		pmcs_lock_phy(phyp);
7738 		ASSERT(phyp->dead);
7739 
7740 		nphyp = phyp->dead_next;
7741 
7742 		/*
7743 		 * Check for outstanding work
7744 		 */
7745 		if (phyp->ref_count > 0) {
7746 			pmcs_unlock_phy(phyp);
7747 			pphyp = phyp;	/* This PHY becomes "previous" */
7748 		} else if (phyp->target) {
7749 			pmcs_unlock_phy(phyp);
7750 			pmcs_prt(pwp, PMCS_PRT_DEBUG1, phyp, phyp->target,
7751 			    "%s: Not freeing PHY 0x%p: target 0x%p is not free",
7752 			    __func__, (void *)phyp, (void *)phyp->target);
7753 			pphyp = phyp;
7754 		} else {
7755 			/*
7756 			 * No outstanding work or target references. Remove it
7757 			 * from the list and free it
7758 			 */
7759 			pmcs_prt(pwp, PMCS_PRT_DEBUG, phyp, phyp->target,
7760 			    "%s: Freeing inactive dead PHY 0x%p @ %s "
7761 			    "target = 0x%p", __func__, (void *)phyp,
7762 			    phyp->path, (void *)phyp->target);
7763 			/*
7764 			 * If pphyp is NULL, then phyp was the head of the list,
7765 			 * so just reset the head to nphyp. Otherwise, the
7766 			 * previous PHY will now point to nphyp (the next PHY)
7767 			 */
7768 			if (pphyp == NULL) {
7769 				pwp->dead_phys = nphyp;
7770 			} else {
7771 				pphyp->dead_next = nphyp;
7772 			}
7773 			/*
7774 			 * If the target still points to this PHY, remove
7775 			 * that linkage now.
7776 			 */
7777 			if (phyp->target) {
7778 				mutex_enter(&phyp->target->statlock);
7779 				if (phyp->target->phy == phyp) {
7780 					phyp->target->phy = NULL;
7781 				}
7782 				mutex_exit(&phyp->target->statlock);
7783 			}
7784 			pmcs_unlock_phy(phyp);
7785 			phyp->target_addr = NULL;
7786 			kmem_cache_free(pwp->phy_cache, phyp);
7787 		}
7788 
7789 		phyp = nphyp;
7790 	}
7791 
7792 	mutex_exit(&pwp->dead_phylist_lock);
7793 	mutex_exit(&pwp->config_lock);
7794 	mutex_exit(&pwp->lock);
7795 }
7796 
7797 void
7798 pmcs_inc_phy_ref_count(pmcs_phy_t *phyp)
7799 {
7800 	atomic_inc_32(&phyp->ref_count);
7801 }
7802 
7803 void
7804 pmcs_dec_phy_ref_count(pmcs_phy_t *phyp)
7805 {
7806 	ASSERT(phyp->ref_count != 0);
7807 	atomic_dec_32(&phyp->ref_count);
7808 }
7809 
7810 /*
7811  * pmcs_reap_dead_phy
7812  *
7813  * This function is called from pmcs_new_tport when we have a PHY
7814  * without a target pointer.  It's possible in that case that this PHY
7815  * may have a "brother" on the dead_phys list.  That is, it may be the same as
7816  * this one but with a different root PHY number (e.g. pp05 vs. pp04).  If
7817  * that's the case, update the dead PHY and this new PHY.  If that's not the
7818  * case, we should get a tran_tgt_init on this after it's reported to SCSA.
7819  *
7820  * Called with PHY locked.
7821  */
7822 static void
7823 pmcs_reap_dead_phy(pmcs_phy_t *phyp)
7824 {
7825 	pmcs_hw_t *pwp = phyp->pwp;
7826 	pmcs_phy_t *ctmp;
7827 	pmcs_iport_t *iport_cmp;
7828 
7829 	ASSERT(mutex_owned(&phyp->phy_lock));
7830 
7831 	/*
7832 	 * Check the dead PHYs list
7833 	 */
7834 	mutex_enter(&pwp->dead_phylist_lock);
7835 	ctmp = pwp->dead_phys;
7836 	while (ctmp) {
7837 		/*
7838 		 * If the iport is NULL, compare against last_iport.
7839 		 */
7840 		if (ctmp->iport) {
7841 			iport_cmp = ctmp->iport;
7842 		} else {
7843 			iport_cmp = ctmp->last_iport;
7844 		}
7845 
7846 		if ((iport_cmp != phyp->iport) ||
7847 		    (memcmp((void *)&ctmp->sas_address[0],
7848 		    (void *)&phyp->sas_address[0], 8))) {
7849 			ctmp = ctmp->dead_next;
7850 			continue;
7851 		}
7852 
7853 		/*
7854 		 * Same SAS address on same iport.  Now check to see if
7855 		 * the PHY path is the same with the possible exception
7856 		 * of the root PHY number.
7857 		 * The "5" is the string length of "pp00."
7858 		 */
7859 		if ((strnlen(phyp->path, 5) >= 5) &&
7860 		    (strnlen(ctmp->path, 5) >= 5)) {
7861 			if (memcmp((void *)&phyp->path[5],
7862 			    (void *)&ctmp->path[5],
7863 			    strnlen(phyp->path, 32) - 5) == 0) {
7864 				break;
7865 			}
7866 		}
7867 
7868 		ctmp = ctmp->dead_next;
7869 	}
7870 	mutex_exit(&pwp->dead_phylist_lock);
7871 
7872 	/*
7873 	 * Found a match.  Remove the target linkage and drop the
7874 	 * ref count on the old PHY.  Then, increment the ref count
7875 	 * on the new PHY to compensate.
7876 	 */
7877 	if (ctmp) {
7878 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
7879 		    "%s: Found match in dead PHY list (0x%p) for new PHY %s",
7880 		    __func__, (void *)ctmp, phyp->path);
7881 		/*
7882 		 * If there is a pointer to the target in the dead PHY, move
7883 		 * all reference counts to the new PHY.
7884 		 */
7885 		if (ctmp->target) {
7886 			mutex_enter(&ctmp->target->statlock);
7887 			phyp->target = ctmp->target;
7888 
7889 			while (ctmp->ref_count != 0) {
7890 				pmcs_inc_phy_ref_count(phyp);
7891 				pmcs_dec_phy_ref_count(ctmp);
7892 			}
7893 			/*
7894 			 * Update the target's linkage as well
7895 			 */
7896 			phyp->target->phy = phyp;
7897 			phyp->target->dtype = phyp->dtype;
7898 			ctmp->target = NULL;
7899 			mutex_exit(&phyp->target->statlock);
7900 		}
7901 	}
7902 }
7903 
7904 /*
7905  * Called with iport lock held
7906  */
7907 void
7908 pmcs_add_phy_to_iport(pmcs_iport_t *iport, pmcs_phy_t *phyp)
7909 {
7910 	ASSERT(mutex_owned(&iport->lock));
7911 	ASSERT(phyp);
7912 	ASSERT(!list_link_active(&phyp->list_node));
7913 
7914 	iport->nphy++;
7915 	list_insert_tail(&iport->phys, phyp);
7916 	pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32, PMCS_NUM_PHYS,
7917 	    &iport->nphy);
7918 	mutex_enter(&phyp->phy_lock);
7919 	pmcs_create_one_phy_stats(iport, phyp);
7920 	mutex_exit(&phyp->phy_lock);
7921 	pmcs_hold_iport(iport);
7922 }
7923 
7924 /*
7925  * Called with the iport lock held
7926  */
7927 void
7928 pmcs_remove_phy_from_iport(pmcs_iport_t *iport, pmcs_phy_t *phyp)
7929 {
7930 	pmcs_phy_t *pptr, *next_pptr;
7931 
7932 	ASSERT(mutex_owned(&iport->lock));
7933 
7934 	/*
7935 	 * If phyp is NULL, remove all PHYs from the iport
7936 	 */
7937 	if (phyp == NULL) {
7938 		for (pptr = list_head(&iport->phys); pptr != NULL;
7939 		    pptr = next_pptr) {
7940 			next_pptr = list_next(&iport->phys, pptr);
7941 			mutex_enter(&pptr->phy_lock);
7942 			if (pptr->phy_stats != NULL) {
7943 				kstat_delete(pptr->phy_stats);
7944 				pptr->phy_stats = NULL;
7945 			}
7946 			pptr->iport = NULL;
7947 			pmcs_update_phy_pm_props(pptr, pptr->att_port_pm_tmp,
7948 			    pptr->tgt_port_pm_tmp, B_FALSE);
7949 			mutex_exit(&pptr->phy_lock);
7950 			pmcs_rele_iport(iport);
7951 			list_remove(&iport->phys, pptr);
7952 			pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32,
7953 			    PMCS_NUM_PHYS, &iport->nphy);
7954 		}
7955 		iport->nphy = 0;
7956 		return;
7957 	}
7958 
7959 	ASSERT(phyp);
7960 	ASSERT(iport->nphy > 0);
7961 	ASSERT(list_link_active(&phyp->list_node));
7962 	iport->nphy--;
7963 	list_remove(&iport->phys, phyp);
7964 	pmcs_update_phy_pm_props(phyp, phyp->att_port_pm_tmp,
7965 	    phyp->tgt_port_pm_tmp, B_FALSE);
7966 	pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32, PMCS_NUM_PHYS,
7967 	    &iport->nphy);
7968 	pmcs_rele_iport(iport);
7969 }
7970 
7971 /*
7972  * This function checks to see if the target pointed to by phyp is still
7973  * correct.  This is done by comparing the target's unit address with the
7974  * SAS address in phyp.
7975  *
7976  * Called with PHY locked and target statlock held
7977  */
7978 static boolean_t
7979 pmcs_phy_target_match(pmcs_phy_t *phyp)
7980 {
7981 	uint64_t wwn;
7982 	char unit_address[PMCS_MAX_UA_SIZE];
7983 	boolean_t rval = B_FALSE;
7984 
7985 	ASSERT(phyp);
7986 	ASSERT(phyp->target);
7987 	ASSERT(mutex_owned(&phyp->phy_lock));
7988 	ASSERT(mutex_owned(&phyp->target->statlock));
7989 
7990 	wwn = pmcs_barray2wwn(phyp->sas_address);
7991 	(void) scsi_wwn_to_wwnstr(wwn, 1, unit_address);
7992 
7993 	if (memcmp((void *)unit_address, (void *)phyp->target->unit_address,
7994 	    strnlen(phyp->target->unit_address, PMCS_MAX_UA_SIZE)) == 0) {
7995 		rval = B_TRUE;
7996 	}
7997 
7998 	return (rval);
7999 }
8000 /*
8001  * Commands used to serialize SMP requests.
8002  *
8003  * The SPC only allows 2 SMP commands per SMP target: 1 cmd pending and 1 cmd
8004  * queued for the same SMP target. If a third SMP cmd is sent to the SPC for an
8005  * SMP target that already has a SMP cmd pending and one queued, then the
8006  * SPC responds with the ERROR_INTERNAL_SMP_RESOURCE response.
8007  *
8008  * Additionally, the SPC has an 8 entry deep cmd queue and the number of SMP
8009  * cmds that can be queued is controlled by the PORT_CONTROL IOMB. The
8010  * SPC default is 1 SMP command/port (iport).  These 2 queued SMP cmds would
8011  * have to be for different SMP targets.  The INTERNAL_SMP_RESOURCE error will
8012  * also be returned if a 2nd SMP cmd is sent to the controller when there is
8013  * already 1 SMP cmd queued for that port or if a 3rd SMP cmd is sent to the
8014  * queue if there are already 2 queued SMP cmds.
8015  */
8016 void
8017 pmcs_smp_acquire(pmcs_iport_t *iport)
8018 {
8019 	if (iport == NULL) {
8020 		return;
8021 	}
8022 
8023 	mutex_enter(&iport->smp_lock);
8024 	while (iport->smp_active) {
8025 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_IPORT, NULL, NULL,
8026 		    "%s: SMP is active on thread 0x%p, waiting", __func__,
8027 		    (void *)iport->smp_active_thread);
8028 		cv_wait(&iport->smp_cv, &iport->smp_lock);
8029 	}
8030 	iport->smp_active = B_TRUE;
8031 	iport->smp_active_thread = curthread;
8032 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG3, NULL, NULL,
8033 	    "%s: SMP acquired by thread 0x%p", __func__,
8034 	    (void *)iport->smp_active_thread);
8035 	mutex_exit(&iport->smp_lock);
8036 }
8037 
8038 void
8039 pmcs_smp_release(pmcs_iport_t *iport)
8040 {
8041 	if (iport == NULL) {
8042 		return;
8043 	}
8044 
8045 	mutex_enter(&iport->smp_lock);
8046 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG3, NULL, NULL,
8047 	    "%s: SMP released by thread 0x%p", __func__, (void *)curthread);
8048 	iport->smp_active = B_FALSE;
8049 	iport->smp_active_thread = NULL;
8050 	cv_signal(&iport->smp_cv);
8051 	mutex_exit(&iport->smp_lock);
8052 }
8053 
8054 /*
8055  * Update a PHY's attached-port-pm and target-port-pm properties
8056  *
8057  * phyp: PHY whose properties are to be updated
8058  *
8059  * att_bv: Bit value of the attached-port-pm property to be updated in the
8060  * 64-bit holding area for the PHY.
8061  *
8062  * tgt_bv: Bit value of the target-port-pm property to update in the 64-bit
8063  * holding area for the PHY.
8064  *
8065  * prop_add_val: If TRUE, we're adding bits into the property value.
8066  * Otherwise, we're taking them out.  Either way, the properties for this
8067  * PHY will be updated.
8068  */
8069 void
8070 pmcs_update_phy_pm_props(pmcs_phy_t *phyp, uint64_t att_bv, uint64_t tgt_bv,
8071     boolean_t prop_add_val)
8072 {
8073 	pmcs_xscsi_t	*tgt;
8074 
8075 	if (prop_add_val) {
8076 		/*
8077 		 * If the values are currently 0, then we're setting the
8078 		 * phymask for just this PHY as well.
8079 		 */
8080 		if (phyp->att_port_pm_tmp == 0) {
8081 			phyp->att_port_pm = att_bv;
8082 			phyp->tgt_port_pm = tgt_bv;
8083 		}
8084 		phyp->att_port_pm_tmp |= att_bv;
8085 		phyp->tgt_port_pm_tmp |= tgt_bv;
8086 		(void) snprintf(phyp->att_port_pm_str, PMCS_PM_MAX_NAMELEN,
8087 		    "%"PRIx64, phyp->att_port_pm_tmp);
8088 		(void) snprintf(phyp->tgt_port_pm_str, PMCS_PM_MAX_NAMELEN,
8089 		    "%"PRIx64, phyp->tgt_port_pm_tmp);
8090 	} else {
8091 		phyp->att_port_pm_tmp &= ~att_bv;
8092 		phyp->tgt_port_pm_tmp &= ~tgt_bv;
8093 		if (phyp->att_port_pm_tmp) {
8094 			(void) snprintf(phyp->att_port_pm_str,
8095 			    PMCS_PM_MAX_NAMELEN, "%"PRIx64,
8096 			    phyp->att_port_pm_tmp);
8097 		} else {
8098 			phyp->att_port_pm_str[0] = '\0';
8099 			phyp->att_port_pm = 0;
8100 		}
8101 		if (phyp->tgt_port_pm_tmp) {
8102 			(void) snprintf(phyp->tgt_port_pm_str,
8103 			    PMCS_PM_MAX_NAMELEN, "%"PRIx64,
8104 			    phyp->tgt_port_pm_tmp);
8105 		} else {
8106 			phyp->tgt_port_pm_str[0] = '\0';
8107 			phyp->tgt_port_pm = 0;
8108 		}
8109 	}
8110 
8111 	if ((phyp->target_addr) && (*phyp->target_addr != NULL)) {
8112 		tgt = *phyp->target_addr;
8113 	} else if (phyp->target != NULL) {
8114 		tgt = phyp->target;
8115 	} else {
8116 		return;
8117 	}
8118 
8119 	mutex_enter(&tgt->statlock);
8120 	if (!list_is_empty(&tgt->lun_list)) {
8121 		pmcs_lun_t *lunp;
8122 
8123 		lunp = list_head(&tgt->lun_list);
8124 		while (lunp) {
8125 			(void) scsi_device_prop_update_string(lunp->sd,
8126 			    SCSI_DEVICE_PROP_PATH,
8127 			    SCSI_ADDR_PROP_ATTACHED_PORT_PM,
8128 			    phyp->att_port_pm_str);
8129 			(void) scsi_device_prop_update_string(lunp->sd,
8130 			    SCSI_DEVICE_PROP_PATH,
8131 			    SCSI_ADDR_PROP_TARGET_PORT_PM,
8132 			    phyp->tgt_port_pm_str);
8133 			lunp = list_next(&tgt->lun_list, lunp);
8134 		}
8135 	} else if (tgt->smpd) {
8136 		(void) smp_device_prop_update_string(tgt->smpd,
8137 		    SCSI_ADDR_PROP_ATTACHED_PORT_PM,
8138 		    phyp->att_port_pm_str);
8139 		(void) smp_device_prop_update_string(tgt->smpd,
8140 		    SCSI_ADDR_PROP_TARGET_PORT_PM,
8141 		    phyp->tgt_port_pm_str);
8142 	}
8143 	mutex_exit(&tgt->statlock);
8144 }
8145 
8146 /* ARGSUSED */
8147 void
8148 pmcs_deregister_device_work(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
8149 {
8150 	pmcs_phy_t	*pptr;
8151 
8152 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
8153 		pmcs_lock_phy(pptr);
8154 		if (pptr->deregister_wait) {
8155 			pmcs_deregister_device(pwp, pptr);
8156 		}
8157 		pmcs_unlock_phy(pptr);
8158 	}
8159 }
8160 
8161 /*
8162  * pmcs_iport_active
8163  *
8164  * Mark this iport as active.  Called with the iport lock held.
8165  */
8166 static void
8167 pmcs_iport_active(pmcs_iport_t *iport)
8168 {
8169 	ASSERT(mutex_owned(&iport->lock));
8170 
8171 	iport->ua_state = UA_ACTIVE;
8172 	iport->smp_active = B_FALSE;
8173 	iport->smp_active_thread = NULL;
8174 }
8175 
8176 /* ARGSUSED */
8177 static void
8178 pmcs_tgtmap_activate_cb(void *tgtmap_priv, char *tgt_addr,
8179     scsi_tgtmap_tgt_type_t tgt_type, void **tgt_privp)
8180 {
8181 	pmcs_iport_t *iport = (pmcs_iport_t *)tgtmap_priv;
8182 	pmcs_hw_t *pwp = iport->pwp;
8183 	pmcs_xscsi_t *target;
8184 
8185 	/*
8186 	 * Look up the target.  If there is one, and it doesn't have a PHY
8187 	 * pointer, re-establish that linkage here.
8188 	 */
8189 	mutex_enter(&pwp->lock);
8190 	target = pmcs_get_target(iport, tgt_addr, B_FALSE);
8191 	mutex_exit(&pwp->lock);
8192 
8193 	/*
8194 	 * If we got a target, it will now have a PHY pointer and the PHY
8195 	 * will point to the target.  The PHY will be locked, so we'll need
8196 	 * to unlock it.
8197 	 */
8198 	if (target != NULL) {
8199 		pmcs_unlock_phy(target->phy);
8200 	}
8201 
8202 	/*
8203 	 * Update config_restart_time so we don't try to restart discovery
8204 	 * while enumeration is still in progress.
8205 	 */
8206 	mutex_enter(&pwp->config_lock);
8207 	pwp->config_restart_time = ddi_get_lbolt() +
8208 	    drv_usectohz(PMCS_REDISCOVERY_DELAY);
8209 	mutex_exit(&pwp->config_lock);
8210 }
8211 
8212 /* ARGSUSED */
8213 static boolean_t
8214 pmcs_tgtmap_deactivate_cb(void *tgtmap_priv, char *tgt_addr,
8215     scsi_tgtmap_tgt_type_t tgt_type, void *tgt_priv,
8216     scsi_tgtmap_deact_rsn_t tgt_deact_rsn)
8217 {
8218 	pmcs_iport_t *iport = (pmcs_iport_t *)tgtmap_priv;
8219 	pmcs_phy_t *phyp;
8220 	boolean_t rediscover = B_FALSE;
8221 
8222 	ASSERT(iport);
8223 
8224 	phyp = pmcs_find_phy_by_sas_address(iport->pwp, iport, NULL, tgt_addr);
8225 	if (phyp == NULL) {
8226 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_IPORT, NULL, NULL,
8227 		    "%s: Couldn't find PHY at %s", __func__, tgt_addr);
8228 		return (rediscover);
8229 	}
8230 	/* phyp is locked */
8231 
8232 	if (!phyp->reenumerate && phyp->configured) {
8233 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_CONFIG, phyp, phyp->target,
8234 		    "%s: PHY @ %s is configured... re-enumerate", __func__,
8235 		    tgt_addr);
8236 		phyp->reenumerate = 1;
8237 	}
8238 
8239 	/*
8240 	 * Check to see if reenumerate is set, and if so, if we've reached our
8241 	 * maximum number of retries.
8242 	 */
8243 	if (phyp->reenumerate) {
8244 		if (phyp->enum_attempts == PMCS_MAX_REENUMERATE) {
8245 			pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_CONFIG, phyp,
8246 			    phyp->target,
8247 			    "%s: No more enumeration attempts for %s", __func__,
8248 			    tgt_addr);
8249 		} else {
8250 			pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_CONFIG, phyp,
8251 			    phyp->target, "%s: Re-attempt enumeration for %s",
8252 			    __func__, tgt_addr);
8253 			++phyp->enum_attempts;
8254 			rediscover = B_TRUE;
8255 		}
8256 
8257 		phyp->reenumerate = 0;
8258 	}
8259 
8260 	pmcs_unlock_phy(phyp);
8261 
8262 	mutex_enter(&iport->pwp->config_lock);
8263 	iport->pwp->config_restart_time = ddi_get_lbolt() +
8264 	    drv_usectohz(PMCS_REDISCOVERY_DELAY);
8265 	if (rediscover) {
8266 		iport->pwp->config_restart = B_TRUE;
8267 	} else if (iport->pwp->config_restart == B_TRUE) {
8268 		/*
8269 		 * If we aren't asking for rediscovery because of this PHY,
8270 		 * check to see if we're already asking for it on behalf of
8271 		 * some other PHY.  If so, we'll want to return TRUE, so reset
8272 		 * "rediscover" here.
8273 		 */
8274 		rediscover = B_TRUE;
8275 	}
8276 
8277 	mutex_exit(&iport->pwp->config_lock);
8278 
8279 	return (rediscover);
8280 }
8281 
8282 void
8283 pmcs_status_disposition(pmcs_phy_t *phyp, uint32_t status)
8284 {
8285 	ASSERT(phyp);
8286 	ASSERT(!mutex_owned(&phyp->phy_lock));
8287 
8288 	if (phyp == NULL) {
8289 		return;
8290 	}
8291 
8292 	pmcs_lock_phy(phyp);
8293 
8294 	/*
8295 	 * XXX: Do we need to call this function from an SSP_EVENT?
8296 	 */
8297 
8298 	switch (status) {
8299 	case PMCOUT_STATUS_NO_DEVICE:
8300 	case PMCOUT_STATUS_ERROR_HW_TIMEOUT:
8301 	case PMCOUT_STATUS_XFER_ERR_BREAK:
8302 	case PMCOUT_STATUS_XFER_ERR_PHY_NOT_READY:
8303 	case PMCOUT_STATUS_OPEN_CNX_PROTOCOL_NOT_SUPPORTED:
8304 	case PMCOUT_STATUS_OPEN_CNX_ERROR_ZONE_VIOLATION:
8305 	case PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK:
8306 	case PMCOUT_STATUS_OPENCNX_ERROR_BAD_DESTINATION:
8307 	case PMCOUT_STATUS_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
8308 	case PMCOUT_STATUS_OPEN_CNX_ERROR_STP_RESOURCES_BUSY:
8309 	case PMCOUT_STATUS_OPEN_CNX_ERROR_WRONG_DESTINATION:
8310 	case PMCOUT_STATUS_OPEN_CNX_ERROR_UNKNOWN_ERROR:
8311 	case PMCOUT_STATUS_IO_XFER_ERROR_NAK_RECEIVED:
8312 	case PMCOUT_STATUS_XFER_ERROR_RX_FRAME:
8313 	case PMCOUT_STATUS_IO_XFER_OPEN_RETRY_TIMEOUT:
8314 	case PMCOUT_STATUS_ERROR_INTERNAL_SMP_RESOURCE:
8315 	case PMCOUT_STATUS_IO_PORT_IN_RESET:
8316 	case PMCOUT_STATUS_IO_DS_NON_OPERATIONAL:
8317 	case PMCOUT_STATUS_IO_DS_IN_RECOVERY:
8318 	case PMCOUT_STATUS_IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
8319 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG, phyp, phyp->target,
8320 		    "%s: status = 0x%x for " SAS_ADDR_FMT ", reenumerate",
8321 		    __func__, status, SAS_ADDR_PRT(phyp->sas_address));
8322 		phyp->reenumerate = 1;
8323 		break;
8324 
8325 	default:
8326 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG, phyp, phyp->target,
8327 		    "%s: status = 0x%x for " SAS_ADDR_FMT ", no reenumeration",
8328 		    __func__, status, SAS_ADDR_PRT(phyp->sas_address));
8329 		break;
8330 	}
8331 
8332 	pmcs_unlock_phy(phyp);
8333 }
8334 
8335 /*
8336  * Add the list of PHYs pointed to by phyp to the dead_phys_list
8337  *
8338  * Called with all PHYs in the list locked
8339  */
8340 static void
8341 pmcs_add_dead_phys(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
8342 {
8343 	mutex_enter(&pwp->dead_phylist_lock);
8344 	while (phyp) {
8345 		pmcs_phy_t *nxt = phyp->sibling;
8346 		ASSERT(phyp->dead);
8347 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, phyp, NULL,
8348 		    "%s: dead PHY 0x%p (%s) (ref_count %d)", __func__,
8349 		    (void *)phyp, phyp->path, phyp->ref_count);
8350 		/*
8351 		 * Put this PHY on the dead PHY list for the watchdog to
8352 		 * clean up after any outstanding work has completed.
8353 		 */
8354 		phyp->dead_next = pwp->dead_phys;
8355 		pwp->dead_phys = phyp;
8356 		pmcs_unlock_phy(phyp);
8357 		phyp = nxt;
8358 	}
8359 	mutex_exit(&pwp->dead_phylist_lock);
8360 }
8361 
8362 static void
8363 pmcs_get_fw_version(pmcs_hw_t *pwp)
8364 {
8365 	uint32_t ila_len, ver_hi, ver_lo;
8366 	uint8_t ila_ver_string[9], img_flag;
8367 	char uc, *ucp = &uc;
8368 	unsigned long ila_ver;
8369 	uint64_t ver_hilo;
8370 
8371 	/* Firmware version is easy. */
8372 	pwp->fw = pmcs_rd_mpi_tbl(pwp, PMCS_MPI_FW);
8373 
8374 	/*
8375 	 * Get the image size (2nd to last dword)
8376 	 * NOTE: The GSM registers are mapped little-endian, but the data
8377 	 * on the flash is actually big-endian, so we need to swap these values
8378 	 * regardless of which platform we're on.
8379 	 */
8380 	ila_len = BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8381 	    GSM_FLASH_BASE + GSM_SM_BLKSZ - (2 << 2)));
8382 	if (ila_len > 65535) {
8383 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
8384 		    "%s: Invalid ILA image size (0x%x)?", __func__, ila_len);
8385 		return;
8386 	}
8387 
8388 	/*
8389 	 * The numeric version is at ila_len - PMCS_ILA_VER_OFFSET
8390 	 */
8391 	ver_hi = BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8392 	    GSM_FLASH_BASE + ila_len - PMCS_ILA_VER_OFFSET));
8393 	ver_lo = BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8394 	    GSM_FLASH_BASE + ila_len - PMCS_ILA_VER_OFFSET + 4));
8395 	ver_hilo = BE_64(((uint64_t)ver_hi << 32) | ver_lo);
8396 	bcopy((const void *)&ver_hilo, &ila_ver_string[0], 8);
8397 	ila_ver_string[8] = '\0';
8398 
8399 	(void) ddi_strtoul((const char *)ila_ver_string, &ucp, 16, &ila_ver);
8400 	pwp->ila_ver = (int)(ila_ver & 0xffffffff);
8401 
8402 	img_flag = (BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8403 	    GSM_FLASH_IMG_FLAGS)) & 0xff000000) >> 24;
8404 	if (img_flag & PMCS_IMG_FLAG_A) {
8405 		pwp->fw_active_img = 1;
8406 	} else {
8407 		pwp->fw_active_img = 0;
8408 	}
8409 }
8410