xref: /illumos-gate/usr/src/uts/common/io/scsi/adapters/pmcs/pmcs_subr.c (revision 188eaed9d5f14c73dfba1cd0dabaa430bdfd4a9a)
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 	mutex_exit(&p->lock);
4806 
4807 	if (mutex_tryenter(&pwp->wfree_lock) == 0) {
4808 		mutex_enter(&pwp->pfree_lock);
4809 		STAILQ_INSERT_TAIL(&pwp->pf, p, next);
4810 		mutex_exit(&pwp->pfree_lock);
4811 	} else {
4812 		STAILQ_INSERT_TAIL(&pwp->wf, p, next);
4813 		mutex_exit(&pwp->wfree_lock);
4814 	}
4815 }
4816 
4817 /*
4818  * Find a work structure based upon a tag and make sure that the tag
4819  * serial number matches the work structure we've found.
4820  * If a structure is found, its lock is held upon return.
4821  * If lock_phy is B_TRUE, then lock the phy also when returning the work struct
4822  */
4823 pmcwork_t *
4824 pmcs_tag2wp(pmcs_hw_t *pwp, uint32_t htag, boolean_t lock_phy)
4825 {
4826 	pmcwork_t *p;
4827 	pmcs_phy_t *phyp;
4828 	uint32_t idx = PMCS_TAG_INDEX(htag);
4829 
4830 	p = &pwp->work[idx];
4831 
4832 	mutex_enter(&p->lock);
4833 	if (p->htag == htag) {
4834 		if (lock_phy) {
4835 			phyp = p->phy;
4836 			if (phyp != NULL) {
4837 				/* phy lock should be held before work lock */
4838 				mutex_exit(&p->lock);
4839 				mutex_enter(&phyp->phy_lock);
4840 				mutex_enter(&p->lock);
4841 			}
4842 			/*
4843 			 * Check htag again, in case the work got completed
4844 			 * while we dropped the work lock and got the phy lock
4845 			 */
4846 			if (p->htag != htag) {
4847 				if (phyp != NULL) {
4848 					mutex_exit(&p->lock);
4849 					mutex_exit(&phyp->phy_lock);
4850 				}
4851 				pmcs_prt(pwp, PMCS_PRT_DEBUG, phyp, NULL, "%s: "
4852 				    "HTAG (0x%x) found, but work (0x%p) "
4853 				    "is already complete", __func__, htag,
4854 				    (void *)p);
4855 				return (NULL);
4856 			}
4857 		}
4858 		return (p);
4859 	}
4860 	mutex_exit(&p->lock);
4861 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
4862 	    "INDEX 0x%x HTAG 0x%x got p->htag 0x%x", idx, htag, p->htag);
4863 	return (NULL);
4864 }
4865 
4866 /*
4867  * Issue an abort for a command or for all commands.
4868  *
4869  * Since this can be called from interrupt context,
4870  * we don't wait for completion if wait is not set.
4871  *
4872  * Called with PHY lock held.
4873  */
4874 int
4875 pmcs_abort(pmcs_hw_t *pwp, pmcs_phy_t *pptr, uint32_t tag, int all_cmds,
4876     int wait)
4877 {
4878 	pmcwork_t *pwrk;
4879 	pmcs_xscsi_t *tgt;
4880 	uint32_t msg[PMCS_MSG_SIZE], *ptr;
4881 	int result, abt_type;
4882 	uint32_t abt_htag, status;
4883 
4884 	if (pptr->abort_all_start) {
4885 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, "%s: ABORT_ALL for "
4886 		    "(%s) already in progress.", __func__, pptr->path);
4887 		return (EBUSY);
4888 	}
4889 
4890 	switch (pptr->dtype) {
4891 	case SAS:
4892 		abt_type = PMCIN_SSP_ABORT;
4893 		break;
4894 	case SATA:
4895 		abt_type = PMCIN_SATA_ABORT;
4896 		break;
4897 	case EXPANDER:
4898 		abt_type = PMCIN_SMP_ABORT;
4899 		break;
4900 	default:
4901 		return (0);
4902 	}
4903 
4904 	pwrk = pmcs_gwork(pwp, wait ? PMCS_TAG_TYPE_WAIT : PMCS_TAG_TYPE_NONE,
4905 	    pptr);
4906 
4907 	if (pwrk == NULL) {
4908 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nowrk, __func__);
4909 		return (ENOMEM);
4910 	}
4911 
4912 	pwrk->dtype = pptr->dtype;
4913 	pwrk->xp = pptr->target;
4914 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
4915 	if (wait) {
4916 		pwrk->arg = msg;
4917 	}
4918 	if (pptr->valid_device_id == 0) {
4919 		pmcs_pwork(pwp, pwrk);
4920 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4921 		    "%s: Invalid DeviceID", __func__);
4922 		return (ENODEV);
4923 	}
4924 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL, abt_type));
4925 	msg[1] = LE_32(pwrk->htag);
4926 	msg[2] = LE_32(pptr->device_id);
4927 	if (all_cmds) {
4928 		msg[3] = 0;
4929 		msg[4] = LE_32(1);
4930 		pwrk->ptr = NULL;
4931 		pwrk->abt_htag = PMCS_ABT_HTAG_ALL;
4932 		pptr->abort_all_start = gethrtime();
4933 	} else {
4934 		msg[3] = LE_32(tag);
4935 		msg[4] = 0;
4936 		pwrk->abt_htag = tag;
4937 	}
4938 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4939 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4940 	if (ptr == NULL) {
4941 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
4942 		pmcs_pwork(pwp, pwrk);
4943 		pptr->abort_all_start = 0;
4944 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nomsg, __func__);
4945 		return (ENOMEM);
4946 	}
4947 
4948 	COPY_MESSAGE(ptr, msg, 5);
4949 	if (all_cmds) {
4950 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4951 		    "%s: aborting all commands for %s device %s. (htag=0x%x)",
4952 		    __func__, pmcs_get_typename(pptr->dtype), pptr->path,
4953 		    msg[1]);
4954 	} else {
4955 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
4956 		    "%s: aborting tag 0x%x for %s device %s. (htag=0x%x)",
4957 		    __func__, tag, pmcs_get_typename(pptr->dtype), pptr->path,
4958 		    msg[1]);
4959 	}
4960 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
4961 
4962 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
4963 	if (!wait) {
4964 		mutex_exit(&pwrk->lock);
4965 		return (0);
4966 	}
4967 
4968 	abt_htag = pwrk->htag;
4969 	pmcs_unlock_phy(pptr);
4970 	WAIT_FOR(pwrk, 1000, result);
4971 	pmcs_pwork(pwp, pwrk);
4972 	pmcs_lock_phy(pptr);
4973 	tgt = pptr->target;
4974 
4975 	if (all_cmds) {
4976 		pptr->abort_all_start = 0;
4977 		cv_signal(&pptr->abort_all_cv);
4978 	}
4979 
4980 	if (result) {
4981 		if (all_cmds) {
4982 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
4983 			    "%s: Abort all request timed out", __func__);
4984 		} else {
4985 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
4986 			    "%s: Abort (htag 0x%08x) request timed out",
4987 			    __func__, abt_htag);
4988 		}
4989 		if (tgt != NULL) {
4990 			mutex_enter(&tgt->statlock);
4991 			if ((tgt->dev_state != PMCS_DEVICE_STATE_IN_RECOVERY) &&
4992 			    (tgt->dev_state !=
4993 			    PMCS_DEVICE_STATE_NON_OPERATIONAL)) {
4994 				pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
4995 				    "%s: Trying DS error recovery for tgt 0x%p",
4996 				    __func__, (void *)tgt);
4997 				(void) pmcs_send_err_recovery_cmd(pwp,
4998 				    PMCS_DEVICE_STATE_IN_RECOVERY, pptr, tgt);
4999 			}
5000 			mutex_exit(&tgt->statlock);
5001 		}
5002 		return (ETIMEDOUT);
5003 	}
5004 
5005 	status = LE_32(msg[2]);
5006 	if (status != PMCOUT_STATUS_OK) {
5007 		/*
5008 		 * The only non-success status are IO_NOT_VALID &
5009 		 * IO_ABORT_IN_PROGRESS.
5010 		 * In case of IO_ABORT_IN_PROGRESS, the other ABORT cmd's
5011 		 * status is of concern and this duplicate cmd status can
5012 		 * be ignored.
5013 		 * If IO_NOT_VALID, that's not an error per-se.
5014 		 * For abort of single I/O complete the command anyway.
5015 		 * If, however, we were aborting all, that is a problem
5016 		 * as IO_NOT_VALID really means that the IO or device is
5017 		 * not there. So, discovery process will take of the cleanup.
5018 		 */
5019 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5020 		    "%s: abort result 0x%x", __func__, LE_32(msg[2]));
5021 		if (all_cmds) {
5022 			PHY_CHANGED(pwp, pptr);
5023 			RESTART_DISCOVERY(pwp);
5024 		} else {
5025 			return (EINVAL);
5026 		}
5027 
5028 		return (0);
5029 	}
5030 
5031 	if (tgt != NULL) {
5032 		mutex_enter(&tgt->statlock);
5033 		if (tgt->dev_state == PMCS_DEVICE_STATE_IN_RECOVERY) {
5034 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5035 			    "%s: Restoring OPERATIONAL dev_state for tgt 0x%p",
5036 			    __func__, (void *)tgt);
5037 			(void) pmcs_send_err_recovery_cmd(pwp,
5038 			    PMCS_DEVICE_STATE_OPERATIONAL, pptr, tgt);
5039 		}
5040 		mutex_exit(&tgt->statlock);
5041 	}
5042 
5043 	return (0);
5044 }
5045 
5046 /*
5047  * Issue a task management function to an SSP device.
5048  *
5049  * Called with PHY lock held.
5050  * statlock CANNOT be held upon entry.
5051  */
5052 int
5053 pmcs_ssp_tmf(pmcs_hw_t *pwp, pmcs_phy_t *pptr, uint8_t tmf, uint32_t tag,
5054     uint64_t lun, uint32_t *response)
5055 {
5056 	int result, ds;
5057 	uint8_t local[PMCS_QENTRY_SIZE << 1], *xd;
5058 	sas_ssp_rsp_iu_t *rptr = (void *)local;
5059 	static const uint8_t ssp_rsp_evec[] = {
5060 		0x58, 0x61, 0x56, 0x72, 0x00
5061 	};
5062 	uint32_t msg[PMCS_MSG_SIZE], *ptr, status;
5063 	struct pmcwork *pwrk;
5064 	pmcs_xscsi_t *xp;
5065 
5066 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
5067 	if (pwrk == NULL) {
5068 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nowrk, __func__);
5069 		return (ENOMEM);
5070 	}
5071 	/*
5072 	 * NB: We use the PMCS_OQ_GENERAL outbound queue
5073 	 * NB: so as to not get entangled in normal I/O
5074 	 * NB: processing.
5075 	 */
5076 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
5077 	msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
5078 	    PMCIN_SSP_INI_TM_START));
5079 	msg[1] = LE_32(pwrk->htag);
5080 	msg[2] = LE_32(pptr->device_id);
5081 	if (tmf == SAS_ABORT_TASK || tmf == SAS_QUERY_TASK) {
5082 		msg[3] = LE_32(tag);
5083 	} else {
5084 		msg[3] = 0;
5085 	}
5086 	msg[4] = LE_32(tmf);
5087 	msg[5] = BE_32((uint32_t)lun);
5088 	msg[6] = BE_32((uint32_t)(lun >> 32));
5089 	msg[7] = LE_32(PMCIN_MESSAGE_REPORT);
5090 
5091 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5092 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5093 	if (ptr == NULL) {
5094 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5095 		pmcs_pwork(pwp, pwrk);
5096 		pmcs_prt(pwp, PMCS_PRT_ERR, pptr, NULL, pmcs_nomsg, __func__);
5097 		return (ENOMEM);
5098 	}
5099 	COPY_MESSAGE(ptr, msg, 7);
5100 	pwrk->arg = msg;
5101 	pwrk->dtype = pptr->dtype;
5102 	xp = pptr->target;
5103 	pwrk->xp = xp;
5104 
5105 	if (xp != NULL) {
5106 		mutex_enter(&xp->statlock);
5107 		if (xp->dev_state == PMCS_DEVICE_STATE_NON_OPERATIONAL) {
5108 			mutex_exit(&xp->statlock);
5109 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5110 			pmcs_pwork(pwp, pwrk);
5111 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp, "%s: Not "
5112 			    "sending '%s' because DS is '%s'", __func__,
5113 			    pmcs_tmf2str(tmf), pmcs_status_str
5114 			    (PMCOUT_STATUS_IO_DS_NON_OPERATIONAL));
5115 			return (EIO);
5116 		}
5117 		mutex_exit(&xp->statlock);
5118 	}
5119 
5120 	pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5121 	    "%s: sending '%s' to %s (lun %llu) tag 0x%x", __func__,
5122 	    pmcs_tmf2str(tmf), pptr->path, (unsigned long long) lun, tag);
5123 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
5124 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5125 
5126 	pmcs_unlock_phy(pptr);
5127 	/*
5128 	 * This is a command sent to the target device, so it can take
5129 	 * significant amount of time to complete when path & device is busy.
5130 	 * Set a timeout to 20 seconds
5131 	 */
5132 	WAIT_FOR(pwrk, 20000, result);
5133 	pmcs_pwork(pwp, pwrk);
5134 	pmcs_lock_phy(pptr);
5135 	xp = pptr->target;
5136 
5137 	if (result) {
5138 		if (xp == NULL) {
5139 			return (ETIMEDOUT);
5140 		}
5141 
5142 		mutex_enter(&xp->statlock);
5143 		pmcs_start_dev_state_recovery(xp, pptr);
5144 		mutex_exit(&xp->statlock);
5145 		return (ETIMEDOUT);
5146 	}
5147 
5148 	status = LE_32(msg[2]);
5149 	if (status != PMCOUT_STATUS_OK) {
5150 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5151 		    "%s: status %s for TMF %s action to %s, lun %llu",
5152 		    __func__, pmcs_status_str(status),  pmcs_tmf2str(tmf),
5153 		    pptr->path, (unsigned long long) lun);
5154 		if ((status == PMCOUT_STATUS_IO_DS_NON_OPERATIONAL) ||
5155 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK) ||
5156 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_IT_NEXUS_LOSS)) {
5157 			ds = PMCS_DEVICE_STATE_NON_OPERATIONAL;
5158 		} else if (status == PMCOUT_STATUS_IO_DS_IN_RECOVERY) {
5159 			/*
5160 			 * If the status is IN_RECOVERY, it's an indication
5161 			 * that it's now time for us to request to have the
5162 			 * device state set to OPERATIONAL since we're the ones
5163 			 * that requested recovery to begin with.
5164 			 */
5165 			ds = PMCS_DEVICE_STATE_OPERATIONAL;
5166 		} else {
5167 			ds = PMCS_DEVICE_STATE_IN_RECOVERY;
5168 		}
5169 		if (xp != NULL) {
5170 			mutex_enter(&xp->statlock);
5171 			if (xp->dev_state != ds) {
5172 				pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5173 				    "%s: Sending err recovery cmd"
5174 				    " for tgt 0x%p (status = %s)",
5175 				    __func__, (void *)xp,
5176 				    pmcs_status_str(status));
5177 				(void) pmcs_send_err_recovery_cmd(pwp, ds,
5178 				    pptr, xp);
5179 			}
5180 			mutex_exit(&xp->statlock);
5181 		}
5182 		return (EIO);
5183 	} else {
5184 		ds = PMCS_DEVICE_STATE_OPERATIONAL;
5185 		if (xp != NULL) {
5186 			mutex_enter(&xp->statlock);
5187 			if (xp->dev_state != ds) {
5188 				pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5189 				    "%s: Sending err recovery cmd"
5190 				    " for tgt 0x%p (status = %s)",
5191 				    __func__, (void *)xp,
5192 				    pmcs_status_str(status));
5193 				(void) pmcs_send_err_recovery_cmd(pwp, ds,
5194 				    pptr, xp);
5195 			}
5196 			mutex_exit(&xp->statlock);
5197 		}
5198 	}
5199 	if (LE_32(msg[3]) == 0) {
5200 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5201 		    "TMF completed with no response");
5202 		return (EIO);
5203 	}
5204 	pmcs_endian_transform(pwp, local, &msg[5], ssp_rsp_evec);
5205 	xd = (uint8_t *)(&msg[5]);
5206 	xd += SAS_RSP_HDR_SIZE;
5207 	if (rptr->datapres != SAS_RSP_DATAPRES_RESPONSE_DATA) {
5208 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5209 		    "%s: TMF response not RESPONSE DATA (0x%x)",
5210 		    __func__, rptr->datapres);
5211 		return (EIO);
5212 	}
5213 	if (rptr->response_data_length != 4) {
5214 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG,
5215 		    "Bad SAS RESPONSE DATA LENGTH", msg);
5216 		return (EIO);
5217 	}
5218 	(void) memcpy(&status, xd, sizeof (uint32_t));
5219 	status = BE_32(status);
5220 	if (response != NULL)
5221 		*response = status;
5222 	/*
5223 	 * The status is actually in the low-order byte.  The upper three
5224 	 * bytes contain additional information for the TMFs that support them.
5225 	 * However, at this time we do not issue any of those.  In the other
5226 	 * cases, the upper three bytes are supposed to be 0, but it appears
5227 	 * they aren't always.  Just mask them off.
5228 	 */
5229 	switch (status & 0xff) {
5230 	case SAS_RSP_TMF_COMPLETE:
5231 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5232 		    "%s: TMF complete", __func__);
5233 		result = 0;
5234 		break;
5235 	case SAS_RSP_TMF_SUCCEEDED:
5236 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5237 		    "%s: TMF succeeded", __func__);
5238 		result = 0;
5239 		break;
5240 	case SAS_RSP_INVALID_FRAME:
5241 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5242 		    "%s: TMF returned INVALID FRAME", __func__);
5243 		result = EIO;
5244 		break;
5245 	case SAS_RSP_TMF_NOT_SUPPORTED:
5246 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5247 		    "%s: TMF returned TMF NOT SUPPORTED", __func__);
5248 		result = EIO;
5249 		break;
5250 	case SAS_RSP_TMF_FAILED:
5251 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5252 		    "%s: TMF returned TMF FAILED", __func__);
5253 		result = EIO;
5254 		break;
5255 	case SAS_RSP_TMF_INCORRECT_LUN:
5256 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5257 		    "%s: TMF returned INCORRECT LUN", __func__);
5258 		result = EIO;
5259 		break;
5260 	case SAS_RSP_OVERLAPPED_OIPTTA:
5261 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5262 		    "%s: TMF returned OVERLAPPED INITIATOR PORT TRANSFER TAG "
5263 		    "ATTEMPTED", __func__);
5264 		result = EIO;
5265 		break;
5266 	default:
5267 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, xp,
5268 		    "%s: TMF returned unknown code 0x%x", __func__, status);
5269 		result = EIO;
5270 		break;
5271 	}
5272 	return (result);
5273 }
5274 
5275 /*
5276  * Called with PHY lock held and scratch acquired
5277  */
5278 int
5279 pmcs_sata_abort_ncq(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
5280 {
5281 	const char *utag_fail_fmt = "%s: untagged NCQ command failure";
5282 	const char *tag_fail_fmt = "%s: NCQ command failure (tag 0x%x)";
5283 	uint32_t msg[PMCS_QENTRY_SIZE], *ptr, result, status;
5284 	uint8_t *fp = pwp->scratch, ds;
5285 	fis_t fis;
5286 	pmcwork_t *pwrk;
5287 	pmcs_xscsi_t *tgt;
5288 
5289 	pwrk = pmcs_gwork(pwp, PMCS_TAG_TYPE_WAIT, pptr);
5290 	if (pwrk == NULL) {
5291 		return (ENOMEM);
5292 	}
5293 	pwrk->htag |= PMCS_TAG_NONIO_CMD;
5294 	msg[0] = LE_32(PMCS_IOMB_IN_SAS(PMCS_OQ_IODONE,
5295 	    PMCIN_SATA_HOST_IO_START));
5296 	msg[1] = LE_32(pwrk->htag);
5297 	msg[2] = LE_32(pptr->device_id);
5298 	msg[3] = LE_32(512);
5299 	msg[4] = LE_32(SATA_PROTOCOL_PIO | PMCIN_DATADIR_2_INI);
5300 	msg[5] = LE_32((READ_LOG_EXT << 16) | (C_BIT << 8) | FIS_REG_H2DEV);
5301 	msg[6] = LE_32(0x10);
5302 	msg[8] = LE_32(1);
5303 	msg[9] = 0;
5304 	msg[10] = 0;
5305 	msg[11] = 0;
5306 	msg[12] = LE_32(DWORD0(pwp->scratch_dma));
5307 	msg[13] = LE_32(DWORD1(pwp->scratch_dma));
5308 	msg[14] = LE_32(512);
5309 	msg[15] = 0;
5310 
5311 	pwrk->arg = msg;
5312 	pwrk->dtype = pptr->dtype;
5313 	pwrk->xp = pptr->target;
5314 
5315 	mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5316 	ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5317 	if (ptr == NULL) {
5318 		mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5319 		pmcs_pwork(pwp, pwrk);
5320 		return (ENOMEM);
5321 	}
5322 	COPY_MESSAGE(ptr, msg, PMCS_QENTRY_SIZE);
5323 	pwrk->state = PMCS_WORK_STATE_ONCHIP;
5324 	INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5325 
5326 	pmcs_unlock_phy(pptr);
5327 	WAIT_FOR(pwrk, 250, result);
5328 	pmcs_pwork(pwp, pwrk);
5329 	pmcs_lock_phy(pptr);
5330 
5331 	tgt = pptr->target;
5332 	if (result) {
5333 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt, pmcs_timeo, __func__);
5334 		return (EIO);
5335 	}
5336 	status = LE_32(msg[2]);
5337 	if (status != PMCOUT_STATUS_OK || LE_32(msg[3])) {
5338 		if (tgt == NULL) {
5339 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5340 			    "%s: cannot find target for phy 0x%p for "
5341 			    "dev state recovery", __func__, (void *)pptr);
5342 			return (EIO);
5343 		}
5344 
5345 		mutex_enter(&tgt->statlock);
5346 
5347 		pmcs_print_entry(pwp, PMCS_PRT_DEBUG, "READ LOG EXT", msg);
5348 		if ((status == PMCOUT_STATUS_IO_DS_NON_OPERATIONAL) ||
5349 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK) ||
5350 		    (status == PMCOUT_STATUS_OPEN_CNX_ERROR_IT_NEXUS_LOSS)) {
5351 			ds = PMCS_DEVICE_STATE_NON_OPERATIONAL;
5352 		} else {
5353 			ds = PMCS_DEVICE_STATE_IN_RECOVERY;
5354 		}
5355 		if (tgt->dev_state != ds) {
5356 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt, "%s: Trying "
5357 			    "SATA DS Recovery for tgt(0x%p) for status(%s)",
5358 			    __func__, (void *)tgt, pmcs_status_str(status));
5359 			(void) pmcs_send_err_recovery_cmd(pwp, ds, pptr, tgt);
5360 		}
5361 
5362 		mutex_exit(&tgt->statlock);
5363 		return (EIO);
5364 	}
5365 	fis[0] = (fp[4] << 24) | (fp[3] << 16) | (fp[2] << 8) | FIS_REG_D2H;
5366 	fis[1] = (fp[8] << 24) | (fp[7] << 16) | (fp[6] << 8) | fp[5];
5367 	fis[2] = (fp[12] << 24) | (fp[11] << 16) | (fp[10] << 8) | fp[9];
5368 	fis[3] = (fp[16] << 24) | (fp[15] << 16) | (fp[14] << 8) | fp[13];
5369 	fis[4] = 0;
5370 	if (fp[0] & 0x80) {
5371 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5372 		    utag_fail_fmt, __func__);
5373 	} else {
5374 		pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, tgt,
5375 		    tag_fail_fmt, __func__, fp[0] & 0x1f);
5376 	}
5377 	pmcs_fis_dump(pwp, fis);
5378 	pptr->need_rl_ext = 0;
5379 	return (0);
5380 }
5381 
5382 /*
5383  * Transform a structure from CPU to Device endian format, or
5384  * vice versa, based upon a transformation vector.
5385  *
5386  * A transformation vector is an array of bytes, each byte
5387  * of which is defined thusly:
5388  *
5389  *  bit 7: from CPU to desired endian, otherwise from desired endian
5390  *	   to CPU format
5391  *  bit 6: Big Endian, else Little Endian
5392  *  bits 5-4:
5393  *       00 Undefined
5394  *       01 One Byte quantities
5395  *       02 Two Byte quantities
5396  *       03 Four Byte quantities
5397  *
5398  *  bits 3-0:
5399  *       00 Undefined
5400  *       Number of quantities to transform
5401  *
5402  * The vector is terminated by a 0 value.
5403  */
5404 
5405 void
5406 pmcs_endian_transform(pmcs_hw_t *pwp, void *orig_out, void *orig_in,
5407     const uint8_t *xfvec)
5408 {
5409 	uint8_t c, *out = orig_out, *in = orig_in;
5410 
5411 	if (xfvec == NULL) {
5412 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5413 		    "%s: null xfvec", __func__);
5414 		return;
5415 	}
5416 	if (out == NULL) {
5417 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5418 		    "%s: null out", __func__);
5419 		return;
5420 	}
5421 	if (in == NULL) {
5422 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5423 		    "%s: null in", __func__);
5424 		return;
5425 	}
5426 	while ((c = *xfvec++) != 0) {
5427 		int nbyt = (c & 0xf);
5428 		int size = (c >> 4) & 0x3;
5429 		int bige = (c >> 4) & 0x4;
5430 
5431 		switch (size) {
5432 		case 1:
5433 		{
5434 			while (nbyt-- > 0) {
5435 				*out++ = *in++;
5436 			}
5437 			break;
5438 		}
5439 		case 2:
5440 		{
5441 			uint16_t tmp;
5442 			while (nbyt-- > 0) {
5443 				(void) memcpy(&tmp, in, sizeof (uint16_t));
5444 				if (bige) {
5445 					tmp = BE_16(tmp);
5446 				} else {
5447 					tmp = LE_16(tmp);
5448 				}
5449 				(void) memcpy(out, &tmp, sizeof (uint16_t));
5450 				out += sizeof (uint16_t);
5451 				in += sizeof (uint16_t);
5452 			}
5453 			break;
5454 		}
5455 		case 3:
5456 		{
5457 			uint32_t tmp;
5458 			while (nbyt-- > 0) {
5459 				(void) memcpy(&tmp, in, sizeof (uint32_t));
5460 				if (bige) {
5461 					tmp = BE_32(tmp);
5462 				} else {
5463 					tmp = LE_32(tmp);
5464 				}
5465 				(void) memcpy(out, &tmp, sizeof (uint32_t));
5466 				out += sizeof (uint32_t);
5467 				in += sizeof (uint32_t);
5468 			}
5469 			break;
5470 		}
5471 		default:
5472 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
5473 			    "%s: bad size", __func__);
5474 			return;
5475 		}
5476 	}
5477 }
5478 
5479 const char *
5480 pmcs_get_rate(unsigned int linkrt)
5481 {
5482 	const char *rate;
5483 	switch (linkrt) {
5484 	case SAS_LINK_RATE_1_5GBIT:
5485 		rate = "1.5";
5486 		break;
5487 	case SAS_LINK_RATE_3GBIT:
5488 		rate = "3.0";
5489 		break;
5490 	case SAS_LINK_RATE_6GBIT:
5491 		rate = "6.0";
5492 		break;
5493 	default:
5494 		rate = "???";
5495 		break;
5496 	}
5497 	return (rate);
5498 }
5499 
5500 const char *
5501 pmcs_get_typename(pmcs_dtype_t type)
5502 {
5503 	switch (type) {
5504 	case NOTHING:
5505 		return ("NIL");
5506 	case SATA:
5507 		return ("SATA");
5508 	case SAS:
5509 		return ("SSP");
5510 	case EXPANDER:
5511 		return ("EXPANDER");
5512 	}
5513 	return ("????");
5514 }
5515 
5516 const char *
5517 pmcs_tmf2str(int tmf)
5518 {
5519 	switch (tmf) {
5520 	case SAS_ABORT_TASK:
5521 		return ("Abort Task");
5522 	case SAS_ABORT_TASK_SET:
5523 		return ("Abort Task Set");
5524 	case SAS_CLEAR_TASK_SET:
5525 		return ("Clear Task Set");
5526 	case SAS_LOGICAL_UNIT_RESET:
5527 		return ("Logical Unit Reset");
5528 	case SAS_I_T_NEXUS_RESET:
5529 		return ("I_T Nexus Reset");
5530 	case SAS_CLEAR_ACA:
5531 		return ("Clear ACA");
5532 	case SAS_QUERY_TASK:
5533 		return ("Query Task");
5534 	case SAS_QUERY_TASK_SET:
5535 		return ("Query Task Set");
5536 	case SAS_QUERY_UNIT_ATTENTION:
5537 		return ("Query Unit Attention");
5538 	default:
5539 		return ("Unknown");
5540 	}
5541 }
5542 
5543 const char *
5544 pmcs_status_str(uint32_t status)
5545 {
5546 	switch (status) {
5547 	case PMCOUT_STATUS_OK:
5548 		return ("OK");
5549 	case PMCOUT_STATUS_ABORTED:
5550 		return ("ABORTED");
5551 	case PMCOUT_STATUS_OVERFLOW:
5552 		return ("OVERFLOW");
5553 	case PMCOUT_STATUS_UNDERFLOW:
5554 		return ("UNDERFLOW");
5555 	case PMCOUT_STATUS_FAILED:
5556 		return ("FAILED");
5557 	case PMCOUT_STATUS_ABORT_RESET:
5558 		return ("ABORT_RESET");
5559 	case PMCOUT_STATUS_IO_NOT_VALID:
5560 		return ("IO_NOT_VALID");
5561 	case PMCOUT_STATUS_NO_DEVICE:
5562 		return ("NO_DEVICE");
5563 	case PMCOUT_STATUS_ILLEGAL_PARAMETER:
5564 		return ("ILLEGAL_PARAMETER");
5565 	case PMCOUT_STATUS_LINK_FAILURE:
5566 		return ("LINK_FAILURE");
5567 	case PMCOUT_STATUS_PROG_ERROR:
5568 		return ("PROG_ERROR");
5569 	case PMCOUT_STATUS_EDC_IN_ERROR:
5570 		return ("EDC_IN_ERROR");
5571 	case PMCOUT_STATUS_EDC_OUT_ERROR:
5572 		return ("EDC_OUT_ERROR");
5573 	case PMCOUT_STATUS_ERROR_HW_TIMEOUT:
5574 		return ("ERROR_HW_TIMEOUT");
5575 	case PMCOUT_STATUS_XFER_ERR_BREAK:
5576 		return ("XFER_ERR_BREAK");
5577 	case PMCOUT_STATUS_XFER_ERR_PHY_NOT_READY:
5578 		return ("XFER_ERR_PHY_NOT_READY");
5579 	case PMCOUT_STATUS_OPEN_CNX_PROTOCOL_NOT_SUPPORTED:
5580 		return ("OPEN_CNX_PROTOCOL_NOT_SUPPORTED");
5581 	case PMCOUT_STATUS_OPEN_CNX_ERROR_ZONE_VIOLATION:
5582 		return ("OPEN_CNX_ERROR_ZONE_VIOLATION");
5583 	case PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK:
5584 		return ("OPEN_CNX_ERROR_BREAK");
5585 	case PMCOUT_STATUS_OPEN_CNX_ERROR_IT_NEXUS_LOSS:
5586 		return ("OPEN_CNX_ERROR_IT_NEXUS_LOSS");
5587 	case PMCOUT_STATUS_OPENCNX_ERROR_BAD_DESTINATION:
5588 		return ("OPENCNX_ERROR_BAD_DESTINATION");
5589 	case PMCOUT_STATUS_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
5590 		return ("OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED");
5591 	case PMCOUT_STATUS_OPEN_CNX_ERROR_STP_RESOURCES_BUSY:
5592 		return ("OPEN_CNX_ERROR_STP_RESOURCES_BUSY");
5593 	case PMCOUT_STATUS_OPEN_CNX_ERROR_WRONG_DESTINATION:
5594 		return ("OPEN_CNX_ERROR_WRONG_DESTINATION");
5595 	case PMCOUT_STATUS_OPEN_CNX_ERROR_UNKNOWN_ERROR:
5596 		return ("OPEN_CNX_ERROR_UNKNOWN_ERROR");
5597 	case PMCOUT_STATUS_IO_XFER_ERROR_NAK_RECEIVED:
5598 		return ("IO_XFER_ERROR_NAK_RECEIVED");
5599 	case PMCOUT_STATUS_XFER_ERROR_ACK_NAK_TIMEOUT:
5600 		return ("XFER_ERROR_ACK_NAK_TIMEOUT");
5601 	case PMCOUT_STATUS_XFER_ERROR_PEER_ABORTED:
5602 		return ("XFER_ERROR_PEER_ABORTED");
5603 	case PMCOUT_STATUS_XFER_ERROR_RX_FRAME:
5604 		return ("XFER_ERROR_RX_FRAME");
5605 	case PMCOUT_STATUS_IO_XFER_ERROR_DMA:
5606 		return ("IO_XFER_ERROR_DMA");
5607 	case PMCOUT_STATUS_XFER_ERROR_CREDIT_TIMEOUT:
5608 		return ("XFER_ERROR_CREDIT_TIMEOUT");
5609 	case PMCOUT_STATUS_XFER_ERROR_SATA_LINK_TIMEOUT:
5610 		return ("XFER_ERROR_SATA_LINK_TIMEOUT");
5611 	case PMCOUT_STATUS_XFER_ERROR_SATA:
5612 		return ("XFER_ERROR_SATA");
5613 	case PMCOUT_STATUS_XFER_ERROR_REJECTED_NCQ_MODE:
5614 		return ("XFER_ERROR_REJECTED_NCQ_MODE");
5615 	case PMCOUT_STATUS_XFER_ERROR_ABORTED_DUE_TO_SRST:
5616 		return ("XFER_ERROR_ABORTED_DUE_TO_SRST");
5617 	case PMCOUT_STATUS_XFER_ERROR_ABORTED_NCQ_MODE:
5618 		return ("XFER_ERROR_ABORTED_NCQ_MODE");
5619 	case PMCOUT_STATUS_IO_XFER_OPEN_RETRY_TIMEOUT:
5620 		return ("IO_XFER_OPEN_RETRY_TIMEOUT");
5621 	case PMCOUT_STATUS_SMP_RESP_CONNECTION_ERROR:
5622 		return ("SMP_RESP_CONNECTION_ERROR");
5623 	case PMCOUT_STATUS_XFER_ERROR_UNEXPECTED_PHASE:
5624 		return ("XFER_ERROR_UNEXPECTED_PHASE");
5625 	case PMCOUT_STATUS_XFER_ERROR_RDY_OVERRUN:
5626 		return ("XFER_ERROR_RDY_OVERRUN");
5627 	case PMCOUT_STATUS_XFER_ERROR_RDY_NOT_EXPECTED:
5628 		return ("XFER_ERROR_RDY_NOT_EXPECTED");
5629 	case PMCOUT_STATUS_XFER_ERROR_CMD_ISSUE_ACK_NAK_TIMEOUT:
5630 		return ("XFER_ERROR_CMD_ISSUE_ACK_NAK_TIMEOUT");
5631 	case PMCOUT_STATUS_XFER_ERROR_CMD_ISSUE_BREAK_BEFORE_ACK_NACK:
5632 		return ("XFER_ERROR_CMD_ISSUE_BREAK_BEFORE_ACK_NACK");
5633 	case PMCOUT_STATUS_XFER_ERROR_CMD_ISSUE_PHY_DOWN_BEFORE_ACK_NAK:
5634 		return ("XFER_ERROR_CMD_ISSUE_PHY_DOWN_BEFORE_ACK_NAK");
5635 	case PMCOUT_STATUS_XFER_ERROR_OFFSET_MISMATCH:
5636 		return ("XFER_ERROR_OFFSET_MISMATCH");
5637 	case PMCOUT_STATUS_XFER_ERROR_ZERO_DATA_LEN:
5638 		return ("XFER_ERROR_ZERO_DATA_LEN");
5639 	case PMCOUT_STATUS_XFER_CMD_FRAME_ISSUED:
5640 		return ("XFER_CMD_FRAME_ISSUED");
5641 	case PMCOUT_STATUS_ERROR_INTERNAL_SMP_RESOURCE:
5642 		return ("ERROR_INTERNAL_SMP_RESOURCE");
5643 	case PMCOUT_STATUS_IO_PORT_IN_RESET:
5644 		return ("IO_PORT_IN_RESET");
5645 	case PMCOUT_STATUS_IO_DS_NON_OPERATIONAL:
5646 		return ("DEVICE STATE NON-OPERATIONAL");
5647 	case PMCOUT_STATUS_IO_DS_IN_RECOVERY:
5648 		return ("DEVICE STATE IN RECOVERY");
5649 	case PMCOUT_STATUS_IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
5650 		return ("OPEN CNX ERR HW RESOURCE BUSY");
5651 	default:
5652 		return (NULL);
5653 	}
5654 }
5655 
5656 uint64_t
5657 pmcs_barray2wwn(uint8_t ba[8])
5658 {
5659 	uint64_t result = 0;
5660 	int i;
5661 
5662 	for (i = 0; i < 8; i++) {
5663 		result <<= 8;
5664 		result |= ba[i];
5665 	}
5666 	return (result);
5667 }
5668 
5669 void
5670 pmcs_wwn2barray(uint64_t wwn, uint8_t ba[8])
5671 {
5672 	int i;
5673 	for (i = 0; i < 8; i++) {
5674 		ba[7 - i] = wwn & 0xff;
5675 		wwn >>= 8;
5676 	}
5677 }
5678 
5679 void
5680 pmcs_report_fwversion(pmcs_hw_t *pwp)
5681 {
5682 	const char *fwsupport;
5683 	switch (PMCS_FW_TYPE(pwp)) {
5684 	case PMCS_FW_TYPE_RELEASED:
5685 		fwsupport = "Released";
5686 		break;
5687 	case PMCS_FW_TYPE_DEVELOPMENT:
5688 		fwsupport = "Development";
5689 		break;
5690 	case PMCS_FW_TYPE_ALPHA:
5691 		fwsupport = "Alpha";
5692 		break;
5693 	case PMCS_FW_TYPE_BETA:
5694 		fwsupport = "Beta";
5695 		break;
5696 	default:
5697 		fwsupport = "Special";
5698 		break;
5699 	}
5700 	pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5701 	    "Chip Revision: %c; F/W Revision %x.%x.%x %s (ILA rev %08x)",
5702 	    'A' + pwp->chiprev, PMCS_FW_MAJOR(pwp), PMCS_FW_MINOR(pwp),
5703 	    PMCS_FW_MICRO(pwp), fwsupport, pwp->ila_ver);
5704 }
5705 
5706 void
5707 pmcs_phy_name(pmcs_hw_t *pwp, pmcs_phy_t *pptr, char *obuf, size_t olen)
5708 {
5709 	if (pptr->parent) {
5710 		pmcs_phy_name(pwp, pptr->parent, obuf, olen);
5711 		(void) snprintf(obuf, olen, "%s.%02x", obuf, pptr->phynum);
5712 	} else {
5713 		(void) snprintf(obuf, olen, "pp%02x", pptr->phynum);
5714 	}
5715 }
5716 
5717 /*
5718  * This function is called as a sanity check to ensure that a newly registered
5719  * PHY doesn't have a device_id that exists with another registered PHY.
5720  */
5721 static boolean_t
5722 pmcs_validate_devid(pmcs_phy_t *parent, pmcs_phy_t *phyp, uint32_t device_id)
5723 {
5724 	pmcs_phy_t *pptr, *pchild;
5725 	boolean_t rval;
5726 
5727 	pptr = parent;
5728 
5729 	while (pptr) {
5730 		if (pptr->valid_device_id && (pptr != phyp) &&
5731 		    (pptr->device_id == device_id)) {
5732 			/*
5733 			 * This can still be OK if both of these PHYs actually
5734 			 * represent the same device (e.g. expander).  It could
5735 			 * be a case of a new "primary" PHY.  If the SAS address
5736 			 * is the same and they have the same parent, we'll
5737 			 * accept this if the PHY to be registered is the
5738 			 * primary.
5739 			 */
5740 			if ((phyp->parent == pptr->parent) &&
5741 			    (memcmp(phyp->sas_address,
5742 			    pptr->sas_address, 8) == 0) && (phyp->width > 1)) {
5743 				/*
5744 				 * Move children over to the new primary and
5745 				 * update both PHYs
5746 				 */
5747 				pmcs_lock_phy(pptr);
5748 				phyp->children = pptr->children;
5749 				pchild = phyp->children;
5750 				while (pchild) {
5751 					pchild->parent = phyp;
5752 					pchild = pchild->sibling;
5753 				}
5754 				phyp->subsidiary = 0;
5755 				phyp->ncphy = pptr->ncphy;
5756 				/*
5757 				 * device_id, valid_device_id, and configured
5758 				 * will be set by the caller
5759 				 */
5760 				pptr->children = NULL;
5761 				pptr->subsidiary = 1;
5762 				pptr->ncphy = 0;
5763 				pmcs_unlock_phy(pptr);
5764 				pmcs_prt(pptr->pwp, PMCS_PRT_DEBUG, pptr, NULL,
5765 				    "%s: Moving device_id %d from PHY %s to %s",
5766 				    __func__, device_id, pptr->path,
5767 				    phyp->path);
5768 				return (B_TRUE);
5769 			}
5770 			pmcs_prt(pptr->pwp, PMCS_PRT_DEBUG, pptr, NULL,
5771 			    "%s: phy %s already exists as %s with "
5772 			    "device id 0x%x", __func__, phyp->path,
5773 			    pptr->path, device_id);
5774 			return (B_FALSE);
5775 		}
5776 
5777 		if (pptr->children) {
5778 			rval = pmcs_validate_devid(pptr->children, phyp,
5779 			    device_id);
5780 			if (rval == B_FALSE) {
5781 				return (rval);
5782 			}
5783 		}
5784 
5785 		pptr = pptr->sibling;
5786 	}
5787 
5788 	/* This PHY and device_id are valid */
5789 	return (B_TRUE);
5790 }
5791 
5792 /*
5793  * If the PHY is found, it is returned locked
5794  */
5795 static pmcs_phy_t *
5796 pmcs_find_phy_by_wwn_impl(pmcs_phy_t *phyp, uint8_t *wwn)
5797 {
5798 	pmcs_phy_t *matched_phy, *cphyp, *nphyp;
5799 
5800 	ASSERT(!mutex_owned(&phyp->phy_lock));
5801 
5802 	while (phyp) {
5803 		pmcs_lock_phy(phyp);
5804 
5805 		if (phyp->valid_device_id) {
5806 			if (memcmp(phyp->sas_address, wwn, 8) == 0) {
5807 				return (phyp);
5808 			}
5809 		}
5810 
5811 		if (phyp->children) {
5812 			cphyp = phyp->children;
5813 			pmcs_unlock_phy(phyp);
5814 			matched_phy = pmcs_find_phy_by_wwn_impl(cphyp, wwn);
5815 			if (matched_phy) {
5816 				ASSERT(mutex_owned(&matched_phy->phy_lock));
5817 				return (matched_phy);
5818 			}
5819 			pmcs_lock_phy(phyp);
5820 		}
5821 
5822 		/*
5823 		 * Only iterate through non-root PHYs
5824 		 */
5825 		if (IS_ROOT_PHY(phyp)) {
5826 			pmcs_unlock_phy(phyp);
5827 			phyp = NULL;
5828 		} else {
5829 			nphyp = phyp->sibling;
5830 			pmcs_unlock_phy(phyp);
5831 			phyp = nphyp;
5832 		}
5833 	}
5834 
5835 	return (NULL);
5836 }
5837 
5838 pmcs_phy_t *
5839 pmcs_find_phy_by_wwn(pmcs_hw_t *pwp, uint64_t wwn)
5840 {
5841 	uint8_t ebstr[8];
5842 	pmcs_phy_t *pptr, *matched_phy;
5843 
5844 	pmcs_wwn2barray(wwn, ebstr);
5845 
5846 	pptr = pwp->root_phys;
5847 	while (pptr) {
5848 		matched_phy = pmcs_find_phy_by_wwn_impl(pptr, ebstr);
5849 		if (matched_phy) {
5850 			ASSERT(mutex_owned(&matched_phy->phy_lock));
5851 			return (matched_phy);
5852 		}
5853 
5854 		pptr = pptr->sibling;
5855 	}
5856 
5857 	return (NULL);
5858 }
5859 
5860 
5861 /*
5862  * pmcs_find_phy_by_sas_address
5863  *
5864  * Find a PHY that both matches "sas_addr" and is on "iport".
5865  * If a matching PHY is found, it is returned locked.
5866  */
5867 pmcs_phy_t *
5868 pmcs_find_phy_by_sas_address(pmcs_hw_t *pwp, pmcs_iport_t *iport,
5869     pmcs_phy_t *root, char *sas_addr)
5870 {
5871 	int ua_form = 1;
5872 	uint64_t wwn;
5873 	char addr[PMCS_MAX_UA_SIZE];
5874 	pmcs_phy_t *pptr, *pnext, *pchild;
5875 
5876 	if (root == NULL) {
5877 		pptr = pwp->root_phys;
5878 	} else {
5879 		pptr = root;
5880 	}
5881 
5882 	while (pptr) {
5883 		pmcs_lock_phy(pptr);
5884 		/*
5885 		 * If the PHY is dead or does not have a valid device ID,
5886 		 * skip it.
5887 		 */
5888 		if ((pptr->dead) || (!pptr->valid_device_id)) {
5889 			goto next_phy;
5890 		}
5891 
5892 		if (pptr->iport != iport) {
5893 			goto next_phy;
5894 		}
5895 
5896 		wwn = pmcs_barray2wwn(pptr->sas_address);
5897 		(void *) scsi_wwn_to_wwnstr(wwn, ua_form, addr);
5898 		if (strncmp(addr, sas_addr, strlen(addr)) == 0) {
5899 			return (pptr);
5900 		}
5901 
5902 		if (pptr->children) {
5903 			pchild = pptr->children;
5904 			pmcs_unlock_phy(pptr);
5905 			pnext = pmcs_find_phy_by_sas_address(pwp, iport, pchild,
5906 			    sas_addr);
5907 			if (pnext) {
5908 				return (pnext);
5909 			}
5910 			pmcs_lock_phy(pptr);
5911 		}
5912 
5913 next_phy:
5914 		pnext = pptr->sibling;
5915 		pmcs_unlock_phy(pptr);
5916 		pptr = pnext;
5917 	}
5918 
5919 	return (NULL);
5920 }
5921 
5922 void
5923 pmcs_fis_dump(pmcs_hw_t *pwp, fis_t fis)
5924 {
5925 	switch (fis[0] & 0xff) {
5926 	case FIS_REG_H2DEV:
5927 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5928 		    "FIS REGISTER HOST TO DEVICE: "
5929 		    "OP=0x%02x Feature=0x%04x Count=0x%04x Device=0x%02x "
5930 		    "LBA=%llu", BYTE2(fis[0]), BYTE3(fis[2]) << 8 |
5931 		    BYTE3(fis[0]), WORD0(fis[3]), BYTE3(fis[1]),
5932 		    (unsigned long long)
5933 		    (((uint64_t)fis[2] & 0x00ffffff) << 24 |
5934 		    ((uint64_t)fis[1] & 0x00ffffff)));
5935 		break;
5936 	case FIS_REG_D2H:
5937 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5938 		    "FIS REGISTER DEVICE TO HOST: Status=0x%02x "
5939 		    "Error=0x%02x Dev=0x%02x Count=0x%04x LBA=%llu",
5940 		    BYTE2(fis[0]), BYTE3(fis[0]), BYTE3(fis[1]), WORD0(fis[3]),
5941 		    (unsigned long long)(((uint64_t)fis[2] & 0x00ffffff) << 24 |
5942 		    ((uint64_t)fis[1] & 0x00ffffff)));
5943 		break;
5944 	default:
5945 		pmcs_prt(pwp, PMCS_PRT_INFO, NULL, NULL,
5946 		    "FIS: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x",
5947 		    fis[0], fis[1], fis[2], fis[3], fis[4]);
5948 		break;
5949 	}
5950 }
5951 
5952 void
5953 pmcs_print_entry(pmcs_hw_t *pwp, int level, char *msg, void *arg)
5954 {
5955 	uint32_t *mb = arg;
5956 	size_t i;
5957 
5958 	pmcs_prt(pwp, level, NULL, NULL, msg);
5959 	for (i = 0; i < (PMCS_QENTRY_SIZE / sizeof (uint32_t)); i += 4) {
5960 		pmcs_prt(pwp, level, NULL, NULL,
5961 		    "Offset %2lu: 0x%08x 0x%08x 0x%08x 0x%08x",
5962 		    i * sizeof (uint32_t), LE_32(mb[i]),
5963 		    LE_32(mb[i+1]), LE_32(mb[i+2]), LE_32(mb[i+3]));
5964 	}
5965 }
5966 
5967 /*
5968  * If phyp == NULL we're being called from the worker thread, in which
5969  * case we need to check all the PHYs.  In this case, the softstate lock
5970  * will be held.
5971  * If phyp is non-NULL, just issue the spinup release for the specified PHY
5972  * (which will already be locked).
5973  */
5974 void
5975 pmcs_spinup_release(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
5976 {
5977 	uint32_t *msg;
5978 	struct pmcwork *pwrk;
5979 	pmcs_phy_t *tphyp;
5980 
5981 	if (phyp != NULL) {
5982 		ASSERT(mutex_owned(&phyp->phy_lock));
5983 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, phyp, NULL,
5984 		    "%s: Issuing spinup release only for PHY %s", __func__,
5985 		    phyp->path);
5986 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5987 		msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
5988 		if (msg == NULL || (pwrk =
5989 		    pmcs_gwork(pwp, PMCS_TAG_TYPE_NONE, NULL)) == NULL) {
5990 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
5991 			SCHEDULE_WORK(pwp, PMCS_WORK_SPINUP_RELEASE);
5992 			return;
5993 		}
5994 
5995 		phyp->spinup_hold = 0;
5996 		bzero(msg, PMCS_QENTRY_SIZE);
5997 		pwrk->htag |= PMCS_TAG_NONIO_CMD;
5998 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
5999 		    PMCIN_LOCAL_PHY_CONTROL));
6000 		msg[1] = LE_32(pwrk->htag);
6001 		msg[2] = LE_32((0x10 << 8) | phyp->phynum);
6002 
6003 		pwrk->dtype = phyp->dtype;
6004 		pwrk->state = PMCS_WORK_STATE_ONCHIP;
6005 		pwrk->xp = phyp->target;
6006 		mutex_exit(&pwrk->lock);
6007 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6008 		return;
6009 	}
6010 
6011 	ASSERT(mutex_owned(&pwp->lock));
6012 
6013 	tphyp = pwp->root_phys;
6014 	while (tphyp) {
6015 		pmcs_lock_phy(tphyp);
6016 		if (tphyp->spinup_hold == 0) {
6017 			pmcs_unlock_phy(tphyp);
6018 			tphyp = tphyp->sibling;
6019 			continue;
6020 		}
6021 
6022 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, tphyp, NULL,
6023 		    "%s: Issuing spinup release for PHY %s", __func__,
6024 		    tphyp->path);
6025 
6026 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6027 		msg = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6028 		if (msg == NULL || (pwrk =
6029 		    pmcs_gwork(pwp, PMCS_TAG_TYPE_NONE, NULL)) == NULL) {
6030 			pmcs_unlock_phy(tphyp);
6031 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6032 			SCHEDULE_WORK(pwp, PMCS_WORK_SPINUP_RELEASE);
6033 			break;
6034 		}
6035 
6036 		tphyp->spinup_hold = 0;
6037 		bzero(msg, PMCS_QENTRY_SIZE);
6038 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
6039 		    PMCIN_LOCAL_PHY_CONTROL));
6040 		msg[1] = LE_32(pwrk->htag);
6041 		msg[2] = LE_32((0x10 << 8) | tphyp->phynum);
6042 
6043 		pwrk->dtype = tphyp->dtype;
6044 		pwrk->state = PMCS_WORK_STATE_ONCHIP;
6045 		pwrk->xp = tphyp->target;
6046 		mutex_exit(&pwrk->lock);
6047 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6048 		pmcs_unlock_phy(tphyp);
6049 
6050 		tphyp = tphyp->sibling;
6051 	}
6052 }
6053 
6054 /*
6055  * Abort commands on dead PHYs and deregister them as well as removing
6056  * the associated targets.
6057  */
6058 static int
6059 pmcs_kill_devices(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
6060 {
6061 	pmcs_phy_t *pnext, *pchild;
6062 	boolean_t remove_device;
6063 	int rval = 0;
6064 
6065 	while (phyp) {
6066 		pmcs_lock_phy(phyp);
6067 		pchild = phyp->children;
6068 		pnext = phyp->sibling;
6069 		pmcs_unlock_phy(phyp);
6070 
6071 		if (pchild) {
6072 			rval = pmcs_kill_devices(pwp, pchild);
6073 			if (rval) {
6074 				return (rval);
6075 			}
6076 		}
6077 
6078 		mutex_enter(&pwp->lock);
6079 		pmcs_lock_phy(phyp);
6080 		if (phyp->dead && phyp->valid_device_id) {
6081 			remove_device = B_TRUE;
6082 		} else {
6083 			remove_device = B_FALSE;
6084 		}
6085 
6086 		if (remove_device) {
6087 			pmcs_remove_device(pwp, phyp);
6088 			mutex_exit(&pwp->lock);
6089 
6090 			rval = pmcs_kill_device(pwp, phyp);
6091 			if (rval) {
6092 				pmcs_unlock_phy(phyp);
6093 				return (rval);
6094 			}
6095 		} else {
6096 			mutex_exit(&pwp->lock);
6097 		}
6098 
6099 		pmcs_unlock_phy(phyp);
6100 		phyp = pnext;
6101 	}
6102 
6103 	return (rval);
6104 }
6105 
6106 /*
6107  * Called with PHY locked
6108  */
6109 int
6110 pmcs_kill_device(pmcs_hw_t *pwp, pmcs_phy_t *pptr)
6111 {
6112 	int rval;
6113 
6114 	pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL, "kill %s device @ %s",
6115 	    pmcs_get_typename(pptr->dtype), pptr->path);
6116 
6117 	/*
6118 	 * There may be an outstanding ABORT_ALL running, which we wouldn't
6119 	 * know just by checking abort_pending.  We can, however, check
6120 	 * abort_all_start.  If it's non-zero, there is one, and we'll just
6121 	 * sit here and wait for it to complete.  If we don't, we'll remove
6122 	 * the device while there are still commands pending.
6123 	 */
6124 	if (pptr->abort_all_start) {
6125 		while (pptr->abort_all_start) {
6126 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
6127 			    "%s: Waiting for outstanding ABORT_ALL on PHY 0x%p",
6128 			    __func__, (void *)pptr);
6129 			cv_wait(&pptr->abort_all_cv, &pptr->phy_lock);
6130 		}
6131 	} else if (pptr->abort_pending) {
6132 		rval = pmcs_abort(pwp, pptr, pptr->device_id, 1, 1);
6133 		if (rval) {
6134 			pmcs_prt(pwp, PMCS_PRT_DEBUG, pptr, NULL,
6135 			    "%s: ABORT_ALL returned non-zero status (%d) for "
6136 			    "PHY 0x%p", __func__, rval, (void *)pptr);
6137 			return (rval);
6138 		}
6139 		pptr->abort_pending = 0;
6140 	}
6141 
6142 	if (pptr->valid_device_id) {
6143 		pmcs_deregister_device(pwp, pptr);
6144 	}
6145 
6146 	PHY_CHANGED(pwp, pptr);
6147 	RESTART_DISCOVERY(pwp);
6148 	pptr->valid_device_id = 0;
6149 	return (0);
6150 }
6151 
6152 /*
6153  * Acknowledge the SAS h/w events that need acknowledgement.
6154  * This is only needed for first level PHYs.
6155  */
6156 void
6157 pmcs_ack_events(pmcs_hw_t *pwp)
6158 {
6159 	uint32_t msg[PMCS_MSG_SIZE], *ptr;
6160 	struct pmcwork *pwrk;
6161 	pmcs_phy_t *pptr;
6162 
6163 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
6164 		pmcs_lock_phy(pptr);
6165 		if (pptr->hw_event_ack == 0) {
6166 			pmcs_unlock_phy(pptr);
6167 			continue;
6168 		}
6169 		mutex_enter(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6170 		ptr = GET_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6171 
6172 		if ((ptr == NULL) || (pwrk =
6173 		    pmcs_gwork(pwp, PMCS_TAG_TYPE_NONE, NULL)) == NULL) {
6174 			mutex_exit(&pwp->iqp_lock[PMCS_IQ_OTHER]);
6175 			pmcs_unlock_phy(pptr);
6176 			SCHEDULE_WORK(pwp, PMCS_WORK_SAS_HW_ACK);
6177 			break;
6178 		}
6179 
6180 		msg[0] = LE_32(PMCS_HIPRI(pwp, PMCS_OQ_GENERAL,
6181 		    PMCIN_SAS_HW_EVENT_ACK));
6182 		msg[1] = LE_32(pwrk->htag);
6183 		msg[2] = LE_32(pptr->hw_event_ack);
6184 
6185 		mutex_exit(&pwrk->lock);
6186 		pwrk->dtype = pptr->dtype;
6187 		pptr->hw_event_ack = 0;
6188 		COPY_MESSAGE(ptr, msg, 3);
6189 		INC_IQ_ENTRY(pwp, PMCS_IQ_OTHER);
6190 		pmcs_unlock_phy(pptr);
6191 	}
6192 }
6193 
6194 /*
6195  * Load DMA
6196  */
6197 int
6198 pmcs_dma_load(pmcs_hw_t *pwp, pmcs_cmd_t *sp, uint32_t *msg)
6199 {
6200 	ddi_dma_cookie_t *sg;
6201 	pmcs_dmachunk_t *tc;
6202 	pmcs_dmasgl_t *sgl, *prior;
6203 	int seg, tsc;
6204 	uint64_t sgl_addr;
6205 
6206 	/*
6207 	 * If we have no data segments, we're done.
6208 	 */
6209 	if (CMD2PKT(sp)->pkt_numcookies == 0) {
6210 		return (0);
6211 	}
6212 
6213 	/*
6214 	 * Get the S/G list pointer.
6215 	 */
6216 	sg = CMD2PKT(sp)->pkt_cookies;
6217 
6218 	/*
6219 	 * If we only have one dma segment, we can directly address that
6220 	 * data within the Inbound message itself.
6221 	 */
6222 	if (CMD2PKT(sp)->pkt_numcookies == 1) {
6223 		msg[12] = LE_32(DWORD0(sg->dmac_laddress));
6224 		msg[13] = LE_32(DWORD1(sg->dmac_laddress));
6225 		msg[14] = LE_32(sg->dmac_size);
6226 		msg[15] = 0;
6227 		return (0);
6228 	}
6229 
6230 	/*
6231 	 * Otherwise, we'll need one or more external S/G list chunks.
6232 	 * Get the first one and its dma address into the Inbound message.
6233 	 */
6234 	mutex_enter(&pwp->dma_lock);
6235 	tc = pwp->dma_freelist;
6236 	if (tc == NULL) {
6237 		SCHEDULE_WORK(pwp, PMCS_WORK_ADD_DMA_CHUNKS);
6238 		mutex_exit(&pwp->dma_lock);
6239 		pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
6240 		    "%s: out of SG lists", __func__);
6241 		return (-1);
6242 	}
6243 	pwp->dma_freelist = tc->nxt;
6244 	mutex_exit(&pwp->dma_lock);
6245 
6246 	tc->nxt = NULL;
6247 	sp->cmd_clist = tc;
6248 	sgl = tc->chunks;
6249 	(void) memset(tc->chunks, 0, PMCS_SGL_CHUNKSZ);
6250 	sgl_addr = tc->addr;
6251 	msg[12] = LE_32(DWORD0(sgl_addr));
6252 	msg[13] = LE_32(DWORD1(sgl_addr));
6253 	msg[14] = 0;
6254 	msg[15] = LE_32(PMCS_DMASGL_EXTENSION);
6255 
6256 	prior = sgl;
6257 	tsc = 0;
6258 
6259 	for (seg = 0; seg < CMD2PKT(sp)->pkt_numcookies; seg++) {
6260 		/*
6261 		 * If the current segment count for this chunk is one less than
6262 		 * the number s/g lists per chunk and we have more than one seg
6263 		 * to go, we need another chunk. Get it, and make sure that the
6264 		 * tail end of the the previous chunk points the new chunk
6265 		 * (if remembering an offset can be called 'pointing to').
6266 		 *
6267 		 * Note that we can store the offset into our command area that
6268 		 * represents the new chunk in the length field of the part
6269 		 * that points the PMC chip at the next chunk- the PMC chip
6270 		 * ignores this field when the EXTENSION bit is set.
6271 		 *
6272 		 * This is required for dma unloads later.
6273 		 */
6274 		if (tsc == (PMCS_SGL_NCHUNKS - 1) &&
6275 		    seg < (CMD2PKT(sp)->pkt_numcookies - 1)) {
6276 			mutex_enter(&pwp->dma_lock);
6277 			tc = pwp->dma_freelist;
6278 			if (tc == NULL) {
6279 				SCHEDULE_WORK(pwp, PMCS_WORK_ADD_DMA_CHUNKS);
6280 				mutex_exit(&pwp->dma_lock);
6281 				pmcs_dma_unload(pwp, sp);
6282 				pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
6283 				    "%s: out of SG lists", __func__);
6284 				return (-1);
6285 			}
6286 			pwp->dma_freelist = tc->nxt;
6287 			tc->nxt = sp->cmd_clist;
6288 			mutex_exit(&pwp->dma_lock);
6289 
6290 			sp->cmd_clist = tc;
6291 			(void) memset(tc->chunks, 0, PMCS_SGL_CHUNKSZ);
6292 			sgl = tc->chunks;
6293 			sgl_addr = tc->addr;
6294 			prior[PMCS_SGL_NCHUNKS-1].sglal =
6295 			    LE_32(DWORD0(sgl_addr));
6296 			prior[PMCS_SGL_NCHUNKS-1].sglah =
6297 			    LE_32(DWORD1(sgl_addr));
6298 			prior[PMCS_SGL_NCHUNKS-1].sglen = 0;
6299 			prior[PMCS_SGL_NCHUNKS-1].flags =
6300 			    LE_32(PMCS_DMASGL_EXTENSION);
6301 			prior = sgl;
6302 			tsc = 0;
6303 		}
6304 		sgl[tsc].sglal = LE_32(DWORD0(sg->dmac_laddress));
6305 		sgl[tsc].sglah = LE_32(DWORD1(sg->dmac_laddress));
6306 		sgl[tsc].sglen = LE_32(sg->dmac_size);
6307 		sgl[tsc++].flags = 0;
6308 		sg++;
6309 	}
6310 	return (0);
6311 }
6312 
6313 /*
6314  * Unload DMA
6315  */
6316 void
6317 pmcs_dma_unload(pmcs_hw_t *pwp, pmcs_cmd_t *sp)
6318 {
6319 	pmcs_dmachunk_t *cp;
6320 
6321 	mutex_enter(&pwp->dma_lock);
6322 	while ((cp = sp->cmd_clist) != NULL) {
6323 		sp->cmd_clist = cp->nxt;
6324 		cp->nxt = pwp->dma_freelist;
6325 		pwp->dma_freelist = cp;
6326 	}
6327 	mutex_exit(&pwp->dma_lock);
6328 }
6329 
6330 /*
6331  * Take a chunk of consistent memory that has just been allocated and inserted
6332  * into the cip indices and prepare it for DMA chunk usage and add it to the
6333  * freelist.
6334  *
6335  * Called with dma_lock locked (except during attach when it's unnecessary)
6336  */
6337 void
6338 pmcs_idma_chunks(pmcs_hw_t *pwp, pmcs_dmachunk_t *dcp,
6339     pmcs_chunk_t *pchunk, unsigned long lim)
6340 {
6341 	unsigned long off, n;
6342 	pmcs_dmachunk_t *np = dcp;
6343 	pmcs_chunk_t *tmp_chunk;
6344 
6345 	if (pwp->dma_chunklist == NULL) {
6346 		pwp->dma_chunklist = pchunk;
6347 	} else {
6348 		tmp_chunk = pwp->dma_chunklist;
6349 		while (tmp_chunk->next) {
6350 			tmp_chunk = tmp_chunk->next;
6351 		}
6352 		tmp_chunk->next = pchunk;
6353 	}
6354 
6355 	/*
6356 	 * Install offsets into chunk lists.
6357 	 */
6358 	for (n = 0, off = 0; off < lim; off += PMCS_SGL_CHUNKSZ, n++) {
6359 		np->chunks = (void *)&pchunk->addrp[off];
6360 		np->addr = pchunk->dma_addr + off;
6361 		np->acc_handle = pchunk->acc_handle;
6362 		np->dma_handle = pchunk->dma_handle;
6363 		if ((off + PMCS_SGL_CHUNKSZ) < lim) {
6364 			np = np->nxt;
6365 		}
6366 	}
6367 	np->nxt = pwp->dma_freelist;
6368 	pwp->dma_freelist = dcp;
6369 	pmcs_prt(pwp, PMCS_PRT_DEBUG2, NULL, NULL,
6370 	    "added %lu DMA chunks ", n);
6371 }
6372 
6373 /*
6374  * Change the value of the interrupt coalescing timer.  This is done currently
6375  * only for I/O completions.  If we're using the "auto clear" feature, it can
6376  * be turned back on when interrupt coalescing is turned off and must be
6377  * turned off when the coalescing timer is on.
6378  * NOTE: PMCS_MSIX_GENERAL and PMCS_OQ_IODONE are the same value.  As long
6379  * as that's true, we don't need to distinguish between them.
6380  */
6381 
6382 void
6383 pmcs_set_intr_coal_timer(pmcs_hw_t *pwp, pmcs_coal_timer_adj_t adj)
6384 {
6385 	if (adj == DECREASE_TIMER) {
6386 		/* If the timer is already off, nothing to do. */
6387 		if (pwp->io_intr_coal.timer_on == B_FALSE) {
6388 			return;
6389 		}
6390 
6391 		pwp->io_intr_coal.intr_coal_timer -= PMCS_COAL_TIMER_GRAN;
6392 
6393 		if (pwp->io_intr_coal.intr_coal_timer == 0) {
6394 			/* Disable the timer */
6395 			pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_CONTROL, 0);
6396 
6397 			if (pwp->odb_auto_clear & (1 << PMCS_MSIX_IODONE)) {
6398 				pmcs_wr_topunit(pwp, PMCS_OBDB_AUTO_CLR,
6399 				    pwp->odb_auto_clear);
6400 			}
6401 
6402 			pwp->io_intr_coal.timer_on = B_FALSE;
6403 			pwp->io_intr_coal.max_io_completions = B_FALSE;
6404 			pwp->io_intr_coal.num_intrs = 0;
6405 			pwp->io_intr_coal.int_cleared = B_FALSE;
6406 			pwp->io_intr_coal.num_io_completions = 0;
6407 
6408 			DTRACE_PROBE1(pmcs__intr__coalesce__timer__off,
6409 			    pmcs_io_intr_coal_t *, &pwp->io_intr_coal);
6410 		} else {
6411 			pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_TIMER,
6412 			    pwp->io_intr_coal.intr_coal_timer);
6413 		}
6414 	} else {
6415 		/*
6416 		 * If the timer isn't on yet, do the setup for it now.
6417 		 */
6418 		if (pwp->io_intr_coal.timer_on == B_FALSE) {
6419 			/* If auto clear is being used, turn it off. */
6420 			if (pwp->odb_auto_clear & (1 << PMCS_MSIX_IODONE)) {
6421 				pmcs_wr_topunit(pwp, PMCS_OBDB_AUTO_CLR,
6422 				    (pwp->odb_auto_clear &
6423 				    ~(1 << PMCS_MSIX_IODONE)));
6424 			}
6425 
6426 			pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_CONTROL,
6427 			    (1 << PMCS_MSIX_IODONE));
6428 			pwp->io_intr_coal.timer_on = B_TRUE;
6429 			pwp->io_intr_coal.intr_coal_timer =
6430 			    PMCS_COAL_TIMER_GRAN;
6431 
6432 			DTRACE_PROBE1(pmcs__intr__coalesce__timer__on,
6433 			    pmcs_io_intr_coal_t *, &pwp->io_intr_coal);
6434 		} else {
6435 			pwp->io_intr_coal.intr_coal_timer +=
6436 			    PMCS_COAL_TIMER_GRAN;
6437 		}
6438 
6439 		if (pwp->io_intr_coal.intr_coal_timer > PMCS_MAX_COAL_TIMER) {
6440 			pwp->io_intr_coal.intr_coal_timer = PMCS_MAX_COAL_TIMER;
6441 		}
6442 
6443 		pmcs_wr_topunit(pwp, PMCS_INT_COALESCING_TIMER,
6444 		    pwp->io_intr_coal.intr_coal_timer);
6445 	}
6446 
6447 	/*
6448 	 * Adjust the interrupt threshold based on the current timer value
6449 	 */
6450 	pwp->io_intr_coal.intr_threshold =
6451 	    PMCS_INTR_THRESHOLD(PMCS_QUANTUM_TIME_USECS * 1000 /
6452 	    (pwp->io_intr_coal.intr_latency +
6453 	    (pwp->io_intr_coal.intr_coal_timer * 1000)));
6454 }
6455 
6456 /*
6457  * Register Access functions
6458  */
6459 uint32_t
6460 pmcs_rd_iqci(pmcs_hw_t *pwp, uint32_t qnum)
6461 {
6462 	uint32_t iqci;
6463 
6464 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORKERNEL) !=
6465 	    DDI_SUCCESS) {
6466 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6467 		    "%s: ddi_dma_sync failed?", __func__);
6468 	}
6469 
6470 	iqci = LE_32(
6471 	    ((uint32_t *)((void *)pwp->cip))[IQ_OFFSET(qnum) >> 2]);
6472 
6473 	return (iqci);
6474 }
6475 
6476 uint32_t
6477 pmcs_rd_oqpi(pmcs_hw_t *pwp, uint32_t qnum)
6478 {
6479 	uint32_t oqpi;
6480 
6481 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORKERNEL) !=
6482 	    DDI_SUCCESS) {
6483 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6484 		    "%s: ddi_dma_sync failed?", __func__);
6485 	}
6486 
6487 	oqpi = LE_32(
6488 	    ((uint32_t *)((void *)pwp->cip))[OQ_OFFSET(qnum) >> 2]);
6489 
6490 	return (oqpi);
6491 }
6492 
6493 uint32_t
6494 pmcs_rd_gsm_reg(pmcs_hw_t *pwp, uint8_t hi, uint32_t off)
6495 {
6496 	uint32_t rv, newaxil, oldaxil, oldaxih;
6497 
6498 	newaxil = off & ~GSM_BASE_MASK;
6499 	off &= GSM_BASE_MASK;
6500 	mutex_enter(&pwp->axil_lock);
6501 	oldaxil = ddi_get32(pwp->top_acc_handle,
6502 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]);
6503 	ddi_put32(pwp->top_acc_handle,
6504 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], newaxil);
6505 	drv_usecwait(10);
6506 	if (ddi_get32(pwp->top_acc_handle,
6507 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != newaxil) {
6508 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6509 		    "AXIL register update failed");
6510 	}
6511 	if (hi) {
6512 		oldaxih = ddi_get32(pwp->top_acc_handle,
6513 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2]);
6514 		ddi_put32(pwp->top_acc_handle,
6515 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2], hi);
6516 		drv_usecwait(10);
6517 		if (ddi_get32(pwp->top_acc_handle,
6518 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2]) != hi) {
6519 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6520 			    "AXIH register update failed");
6521 		}
6522 	}
6523 	rv = ddi_get32(pwp->gsm_acc_handle, &pwp->gsm_regs[off >> 2]);
6524 	if (hi) {
6525 		ddi_put32(pwp->top_acc_handle,
6526 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2], oldaxih);
6527 		drv_usecwait(10);
6528 		if (ddi_get32(pwp->top_acc_handle,
6529 		    &pwp->top_regs[PMCS_AXI_TRANS_UPPER >> 2]) != oldaxih) {
6530 			pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6531 			    "AXIH register restore failed");
6532 		}
6533 	}
6534 	ddi_put32(pwp->top_acc_handle,
6535 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], oldaxil);
6536 	drv_usecwait(10);
6537 	if (ddi_get32(pwp->top_acc_handle,
6538 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != oldaxil) {
6539 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6540 		    "AXIL register restore failed");
6541 	}
6542 	mutex_exit(&pwp->axil_lock);
6543 	return (rv);
6544 }
6545 
6546 void
6547 pmcs_wr_gsm_reg(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6548 {
6549 	uint32_t newaxil, oldaxil;
6550 
6551 	newaxil = off & ~GSM_BASE_MASK;
6552 	off &= GSM_BASE_MASK;
6553 	mutex_enter(&pwp->axil_lock);
6554 	oldaxil = ddi_get32(pwp->top_acc_handle,
6555 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]);
6556 	ddi_put32(pwp->top_acc_handle,
6557 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], newaxil);
6558 	drv_usecwait(10);
6559 	if (ddi_get32(pwp->top_acc_handle,
6560 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != newaxil) {
6561 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6562 		    "AXIL register update failed");
6563 	}
6564 	ddi_put32(pwp->gsm_acc_handle, &pwp->gsm_regs[off >> 2], val);
6565 	ddi_put32(pwp->top_acc_handle,
6566 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2], oldaxil);
6567 	drv_usecwait(10);
6568 	if (ddi_get32(pwp->top_acc_handle,
6569 	    &pwp->top_regs[PMCS_AXI_TRANS >> 2]) != oldaxil) {
6570 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6571 		    "AXIL register restore failed");
6572 	}
6573 	mutex_exit(&pwp->axil_lock);
6574 }
6575 
6576 uint32_t
6577 pmcs_rd_topunit(pmcs_hw_t *pwp, uint32_t off)
6578 {
6579 	switch (off) {
6580 	case PMCS_SPC_RESET:
6581 	case PMCS_SPC_BOOT_STRAP:
6582 	case PMCS_SPC_DEVICE_ID:
6583 	case PMCS_DEVICE_REVISION:
6584 		off = pmcs_rd_gsm_reg(pwp, 0, off);
6585 		break;
6586 	default:
6587 		off = ddi_get32(pwp->top_acc_handle,
6588 		    &pwp->top_regs[off >> 2]);
6589 		break;
6590 	}
6591 	return (off);
6592 }
6593 
6594 void
6595 pmcs_wr_topunit(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6596 {
6597 	switch (off) {
6598 	case PMCS_SPC_RESET:
6599 	case PMCS_DEVICE_REVISION:
6600 		pmcs_wr_gsm_reg(pwp, off, val);
6601 		break;
6602 	default:
6603 		ddi_put32(pwp->top_acc_handle, &pwp->top_regs[off >> 2], val);
6604 		break;
6605 	}
6606 }
6607 
6608 uint32_t
6609 pmcs_rd_msgunit(pmcs_hw_t *pwp, uint32_t off)
6610 {
6611 	return (ddi_get32(pwp->msg_acc_handle, &pwp->msg_regs[off >> 2]));
6612 }
6613 
6614 uint32_t
6615 pmcs_rd_mpi_tbl(pmcs_hw_t *pwp, uint32_t off)
6616 {
6617 	return (ddi_get32(pwp->mpi_acc_handle,
6618 	    &pwp->mpi_regs[(pwp->mpi_offset + off) >> 2]));
6619 }
6620 
6621 uint32_t
6622 pmcs_rd_gst_tbl(pmcs_hw_t *pwp, uint32_t off)
6623 {
6624 	return (ddi_get32(pwp->mpi_acc_handle,
6625 	    &pwp->mpi_regs[(pwp->mpi_gst_offset + off) >> 2]));
6626 }
6627 
6628 uint32_t
6629 pmcs_rd_iqc_tbl(pmcs_hw_t *pwp, uint32_t off)
6630 {
6631 	return (ddi_get32(pwp->mpi_acc_handle,
6632 	    &pwp->mpi_regs[(pwp->mpi_iqc_offset + off) >> 2]));
6633 }
6634 
6635 uint32_t
6636 pmcs_rd_oqc_tbl(pmcs_hw_t *pwp, uint32_t off)
6637 {
6638 	return (ddi_get32(pwp->mpi_acc_handle,
6639 	    &pwp->mpi_regs[(pwp->mpi_oqc_offset + off) >> 2]));
6640 }
6641 
6642 uint32_t
6643 pmcs_rd_iqpi(pmcs_hw_t *pwp, uint32_t qnum)
6644 {
6645 	return (ddi_get32(pwp->mpi_acc_handle,
6646 	    &pwp->mpi_regs[pwp->iqpi_offset[qnum] >> 2]));
6647 }
6648 
6649 uint32_t
6650 pmcs_rd_oqci(pmcs_hw_t *pwp, uint32_t qnum)
6651 {
6652 	return (ddi_get32(pwp->mpi_acc_handle,
6653 	    &pwp->mpi_regs[pwp->oqci_offset[qnum] >> 2]));
6654 }
6655 
6656 void
6657 pmcs_wr_msgunit(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6658 {
6659 	ddi_put32(pwp->msg_acc_handle, &pwp->msg_regs[off >> 2], val);
6660 }
6661 
6662 void
6663 pmcs_wr_mpi_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6664 {
6665 	ddi_put32(pwp->mpi_acc_handle,
6666 	    &pwp->mpi_regs[(pwp->mpi_offset + off) >> 2], (val));
6667 }
6668 
6669 void
6670 pmcs_wr_gst_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6671 {
6672 	ddi_put32(pwp->mpi_acc_handle,
6673 	    &pwp->mpi_regs[(pwp->mpi_gst_offset + off) >> 2], val);
6674 }
6675 
6676 void
6677 pmcs_wr_iqc_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6678 {
6679 	ddi_put32(pwp->mpi_acc_handle,
6680 	    &pwp->mpi_regs[(pwp->mpi_iqc_offset + off) >> 2], val);
6681 }
6682 
6683 void
6684 pmcs_wr_oqc_tbl(pmcs_hw_t *pwp, uint32_t off, uint32_t val)
6685 {
6686 	ddi_put32(pwp->mpi_acc_handle,
6687 	    &pwp->mpi_regs[(pwp->mpi_oqc_offset + off) >> 2], val);
6688 }
6689 
6690 void
6691 pmcs_wr_iqci(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6692 {
6693 	((uint32_t *)((void *)pwp->cip))[IQ_OFFSET(qnum) >> 2] = val;
6694 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORDEV) !=
6695 	    DDI_SUCCESS) {
6696 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6697 		    "%s: ddi_dma_sync failed?", __func__);
6698 	}
6699 }
6700 
6701 void
6702 pmcs_wr_iqpi(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6703 {
6704 	ddi_put32(pwp->mpi_acc_handle,
6705 	    &pwp->mpi_regs[pwp->iqpi_offset[qnum] >> 2], val);
6706 }
6707 
6708 void
6709 pmcs_wr_oqci(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6710 {
6711 	ddi_put32(pwp->mpi_acc_handle,
6712 	    &pwp->mpi_regs[pwp->oqci_offset[qnum] >> 2], val);
6713 }
6714 
6715 void
6716 pmcs_wr_oqpi(pmcs_hw_t *pwp, uint32_t qnum, uint32_t val)
6717 {
6718 	((uint32_t *)((void *)pwp->cip))[OQ_OFFSET(qnum) >> 2] = val;
6719 	if (ddi_dma_sync(pwp->cip_handles, 0, 0, DDI_DMA_SYNC_FORDEV) !=
6720 	    DDI_SUCCESS) {
6721 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
6722 		    "%s: ddi_dma_sync failed?", __func__);
6723 	}
6724 }
6725 
6726 /*
6727  * Check the status value of an outbound IOMB and report anything bad
6728  */
6729 
6730 void
6731 pmcs_check_iomb_status(pmcs_hw_t *pwp, uint32_t *iomb)
6732 {
6733 	uint16_t 	opcode;
6734 	int		offset;
6735 
6736 	if (iomb == NULL) {
6737 		return;
6738 	}
6739 
6740 	opcode = LE_32(iomb[0]) & 0xfff;
6741 
6742 	switch (opcode) {
6743 		/*
6744 		 * The following have no status field, so ignore them
6745 		 */
6746 	case PMCOUT_ECHO:
6747 	case PMCOUT_SAS_HW_EVENT:
6748 	case PMCOUT_GET_DEVICE_HANDLE:
6749 	case PMCOUT_SATA_EVENT:
6750 	case PMCOUT_SSP_EVENT:
6751 	case PMCOUT_DEVICE_HANDLE_ARRIVED:
6752 	case PMCOUT_SMP_REQUEST_RECEIVED:
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 	mutex_init(&local->phy_lock, NULL, MUTEX_DRIVER,
7590 	    DDI_INTR_PRI(orig_phy->pwp->intr_pri));
7591 
7592 	return (local);
7593 }
7594 
7595 int
7596 pmcs_check_acc_handle(ddi_acc_handle_t handle)
7597 {
7598 	ddi_fm_error_t de;
7599 
7600 	if (handle == NULL) {
7601 		return (DDI_FAILURE);
7602 	}
7603 	ddi_fm_acc_err_get(handle, &de, DDI_FME_VER0);
7604 	return (de.fme_status);
7605 }
7606 
7607 int
7608 pmcs_check_dma_handle(ddi_dma_handle_t handle)
7609 {
7610 	ddi_fm_error_t de;
7611 
7612 	if (handle == NULL) {
7613 		return (DDI_FAILURE);
7614 	}
7615 	ddi_fm_dma_err_get(handle, &de, DDI_FME_VER0);
7616 	return (de.fme_status);
7617 }
7618 
7619 
7620 void
7621 pmcs_fm_ereport(pmcs_hw_t *pwp, char *detail)
7622 {
7623 	uint64_t ena;
7624 	char buf[FM_MAX_CLASS];
7625 
7626 	(void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
7627 	ena = fm_ena_generate(0, FM_ENA_FMT1);
7628 	if (DDI_FM_EREPORT_CAP(pwp->fm_capabilities)) {
7629 		ddi_fm_ereport_post(pwp->dip, buf, ena, DDI_NOSLEEP,
7630 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0, NULL);
7631 	}
7632 }
7633 
7634 int
7635 pmcs_check_acc_dma_handle(pmcs_hw_t *pwp)
7636 {
7637 	pmcs_chunk_t *pchunk;
7638 	int i;
7639 
7640 	/* check all acc & dma handles allocated in attach */
7641 	if ((pmcs_check_acc_handle(pwp->pci_acc_handle) != DDI_SUCCESS) ||
7642 	    (pmcs_check_acc_handle(pwp->msg_acc_handle) != DDI_SUCCESS) ||
7643 	    (pmcs_check_acc_handle(pwp->top_acc_handle) != DDI_SUCCESS) ||
7644 	    (pmcs_check_acc_handle(pwp->mpi_acc_handle) != DDI_SUCCESS) ||
7645 	    (pmcs_check_acc_handle(pwp->gsm_acc_handle) != DDI_SUCCESS)) {
7646 		goto check_failed;
7647 	}
7648 
7649 	for (i = 0; i < PMCS_NIQ; i++) {
7650 		if ((pmcs_check_dma_handle(
7651 		    pwp->iqp_handles[i]) != DDI_SUCCESS) ||
7652 		    (pmcs_check_acc_handle(
7653 		    pwp->iqp_acchdls[i]) != DDI_SUCCESS)) {
7654 			goto check_failed;
7655 		}
7656 	}
7657 
7658 	for (i = 0; i < PMCS_NOQ; i++) {
7659 		if ((pmcs_check_dma_handle(
7660 		    pwp->oqp_handles[i]) != DDI_SUCCESS) ||
7661 		    (pmcs_check_acc_handle(
7662 		    pwp->oqp_acchdls[i]) != DDI_SUCCESS)) {
7663 			goto check_failed;
7664 		}
7665 	}
7666 
7667 	if ((pmcs_check_dma_handle(pwp->cip_handles) != DDI_SUCCESS) ||
7668 	    (pmcs_check_acc_handle(pwp->cip_acchdls) != DDI_SUCCESS)) {
7669 		goto check_failed;
7670 	}
7671 
7672 	if (pwp->fwlog &&
7673 	    ((pmcs_check_dma_handle(pwp->fwlog_hndl) != DDI_SUCCESS) ||
7674 	    (pmcs_check_acc_handle(pwp->fwlog_acchdl) != DDI_SUCCESS))) {
7675 		goto check_failed;
7676 	}
7677 
7678 	if (pwp->regdump_hndl && pwp->regdump_acchdl &&
7679 	    ((pmcs_check_dma_handle(pwp->regdump_hndl) != DDI_SUCCESS) ||
7680 	    (pmcs_check_acc_handle(pwp->regdump_acchdl)
7681 	    != DDI_SUCCESS))) {
7682 		goto check_failed;
7683 	}
7684 
7685 
7686 	pchunk = pwp->dma_chunklist;
7687 	while (pchunk) {
7688 		if ((pmcs_check_acc_handle(pchunk->acc_handle)
7689 		    != DDI_SUCCESS) ||
7690 		    (pmcs_check_dma_handle(pchunk->dma_handle)
7691 		    != DDI_SUCCESS)) {
7692 			goto check_failed;
7693 		}
7694 		pchunk = pchunk->next;
7695 	}
7696 
7697 	return (0);
7698 
7699 check_failed:
7700 
7701 	return (1);
7702 }
7703 
7704 /*
7705  * pmcs_handle_dead_phys
7706  *
7707  * If the PHY has no outstanding work associated with it, remove it from
7708  * the dead PHY list and free it.
7709  *
7710  * If pwp->ds_err_recovering or pwp->configuring is set, don't run.
7711  * This keeps routines that need to submit work to the chip from having to
7712  * hold PHY locks to ensure that PHYs don't disappear while they do their work.
7713  */
7714 void
7715 pmcs_handle_dead_phys(pmcs_hw_t *pwp)
7716 {
7717 	pmcs_phy_t *phyp, *nphyp, *pphyp;
7718 
7719 	mutex_enter(&pwp->lock);
7720 	mutex_enter(&pwp->config_lock);
7721 
7722 	if (pwp->configuring | pwp->ds_err_recovering) {
7723 		mutex_exit(&pwp->config_lock);
7724 		mutex_exit(&pwp->lock);
7725 		return;
7726 	}
7727 
7728 	/*
7729 	 * Check every PHY in the dead PHY list
7730 	 */
7731 	mutex_enter(&pwp->dead_phylist_lock);
7732 	phyp = pwp->dead_phys;
7733 	pphyp = NULL;	/* Set previous PHY to NULL */
7734 
7735 	while (phyp != NULL) {
7736 		pmcs_lock_phy(phyp);
7737 		ASSERT(phyp->dead);
7738 
7739 		nphyp = phyp->dead_next;
7740 
7741 		/*
7742 		 * Check for outstanding work
7743 		 */
7744 		if (phyp->ref_count > 0) {
7745 			pmcs_unlock_phy(phyp);
7746 			pphyp = phyp;	/* This PHY becomes "previous" */
7747 		} else if (phyp->target) {
7748 			pmcs_unlock_phy(phyp);
7749 			pmcs_prt(pwp, PMCS_PRT_DEBUG1, phyp, phyp->target,
7750 			    "%s: Not freeing PHY 0x%p: target 0x%p is not free",
7751 			    __func__, (void *)phyp, (void *)phyp->target);
7752 			pphyp = phyp;
7753 		} else {
7754 			/*
7755 			 * No outstanding work or target references. Remove it
7756 			 * from the list and free it
7757 			 */
7758 			pmcs_prt(pwp, PMCS_PRT_DEBUG, phyp, phyp->target,
7759 			    "%s: Freeing inactive dead PHY 0x%p @ %s "
7760 			    "target = 0x%p", __func__, (void *)phyp,
7761 			    phyp->path, (void *)phyp->target);
7762 			/*
7763 			 * If pphyp is NULL, then phyp was the head of the list,
7764 			 * so just reset the head to nphyp. Otherwise, the
7765 			 * previous PHY will now point to nphyp (the next PHY)
7766 			 */
7767 			if (pphyp == NULL) {
7768 				pwp->dead_phys = nphyp;
7769 			} else {
7770 				pphyp->dead_next = nphyp;
7771 			}
7772 			/*
7773 			 * If the target still points to this PHY, remove
7774 			 * that linkage now.
7775 			 */
7776 			if (phyp->target) {
7777 				mutex_enter(&phyp->target->statlock);
7778 				if (phyp->target->phy == phyp) {
7779 					phyp->target->phy = NULL;
7780 				}
7781 				mutex_exit(&phyp->target->statlock);
7782 			}
7783 			pmcs_unlock_phy(phyp);
7784 			phyp->target_addr = NULL;
7785 			kmem_cache_free(pwp->phy_cache, phyp);
7786 		}
7787 
7788 		phyp = nphyp;
7789 	}
7790 
7791 	mutex_exit(&pwp->dead_phylist_lock);
7792 	mutex_exit(&pwp->config_lock);
7793 	mutex_exit(&pwp->lock);
7794 }
7795 
7796 void
7797 pmcs_inc_phy_ref_count(pmcs_phy_t *phyp)
7798 {
7799 	atomic_inc_32(&phyp->ref_count);
7800 }
7801 
7802 void
7803 pmcs_dec_phy_ref_count(pmcs_phy_t *phyp)
7804 {
7805 	ASSERT(phyp->ref_count != 0);
7806 	atomic_dec_32(&phyp->ref_count);
7807 }
7808 
7809 /*
7810  * pmcs_reap_dead_phy
7811  *
7812  * This function is called from pmcs_new_tport when we have a PHY
7813  * without a target pointer.  It's possible in that case that this PHY
7814  * may have a "brother" on the dead_phys list.  That is, it may be the same as
7815  * this one but with a different root PHY number (e.g. pp05 vs. pp04).  If
7816  * that's the case, update the dead PHY and this new PHY.  If that's not the
7817  * case, we should get a tran_tgt_init on this after it's reported to SCSA.
7818  *
7819  * Called with PHY locked.
7820  */
7821 static void
7822 pmcs_reap_dead_phy(pmcs_phy_t *phyp)
7823 {
7824 	pmcs_hw_t *pwp = phyp->pwp;
7825 	pmcs_phy_t *ctmp;
7826 	pmcs_iport_t *iport_cmp;
7827 
7828 	ASSERT(mutex_owned(&phyp->phy_lock));
7829 
7830 	/*
7831 	 * Check the dead PHYs list
7832 	 */
7833 	mutex_enter(&pwp->dead_phylist_lock);
7834 	ctmp = pwp->dead_phys;
7835 	while (ctmp) {
7836 		/*
7837 		 * If the iport is NULL, compare against last_iport.
7838 		 */
7839 		if (ctmp->iport) {
7840 			iport_cmp = ctmp->iport;
7841 		} else {
7842 			iport_cmp = ctmp->last_iport;
7843 		}
7844 
7845 		if ((iport_cmp != phyp->iport) ||
7846 		    (memcmp((void *)&ctmp->sas_address[0],
7847 		    (void *)&phyp->sas_address[0], 8))) {
7848 			ctmp = ctmp->dead_next;
7849 			continue;
7850 		}
7851 
7852 		/*
7853 		 * Same SAS address on same iport.  Now check to see if
7854 		 * the PHY path is the same with the possible exception
7855 		 * of the root PHY number.
7856 		 * The "5" is the string length of "pp00."
7857 		 */
7858 		if ((strnlen(phyp->path, 5) >= 5) &&
7859 		    (strnlen(ctmp->path, 5) >= 5)) {
7860 			if (memcmp((void *)&phyp->path[5],
7861 			    (void *)&ctmp->path[5],
7862 			    strnlen(phyp->path, 32) - 5) == 0) {
7863 				break;
7864 			}
7865 		}
7866 
7867 		ctmp = ctmp->dead_next;
7868 	}
7869 	mutex_exit(&pwp->dead_phylist_lock);
7870 
7871 	/*
7872 	 * Found a match.  Remove the target linkage and drop the
7873 	 * ref count on the old PHY.  Then, increment the ref count
7874 	 * on the new PHY to compensate.
7875 	 */
7876 	if (ctmp) {
7877 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, ctmp, NULL,
7878 		    "%s: Found match in dead PHY list (0x%p) for new PHY %s",
7879 		    __func__, (void *)ctmp, phyp->path);
7880 		/*
7881 		 * If there is a pointer to the target in the dead PHY, move
7882 		 * all reference counts to the new PHY.
7883 		 */
7884 		if (ctmp->target) {
7885 			mutex_enter(&ctmp->target->statlock);
7886 			phyp->target = ctmp->target;
7887 
7888 			while (ctmp->ref_count != 0) {
7889 				pmcs_inc_phy_ref_count(phyp);
7890 				pmcs_dec_phy_ref_count(ctmp);
7891 			}
7892 			/*
7893 			 * Update the target's linkage as well
7894 			 */
7895 			phyp->target->phy = phyp;
7896 			phyp->target->dtype = phyp->dtype;
7897 			ctmp->target = NULL;
7898 			mutex_exit(&phyp->target->statlock);
7899 		}
7900 	}
7901 }
7902 
7903 /*
7904  * Called with iport lock held
7905  */
7906 void
7907 pmcs_add_phy_to_iport(pmcs_iport_t *iport, pmcs_phy_t *phyp)
7908 {
7909 	ASSERT(mutex_owned(&iport->lock));
7910 	ASSERT(phyp);
7911 	ASSERT(!list_link_active(&phyp->list_node));
7912 
7913 	iport->nphy++;
7914 	list_insert_tail(&iport->phys, phyp);
7915 	pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32, PMCS_NUM_PHYS,
7916 	    &iport->nphy);
7917 	mutex_enter(&phyp->phy_lock);
7918 	pmcs_create_one_phy_stats(iport, phyp);
7919 	mutex_exit(&phyp->phy_lock);
7920 	pmcs_hold_iport(iport);
7921 }
7922 
7923 /*
7924  * Called with the iport lock held
7925  */
7926 void
7927 pmcs_remove_phy_from_iport(pmcs_iport_t *iport, pmcs_phy_t *phyp)
7928 {
7929 	pmcs_phy_t *pptr, *next_pptr;
7930 
7931 	ASSERT(mutex_owned(&iport->lock));
7932 
7933 	/*
7934 	 * If phyp is NULL, remove all PHYs from the iport
7935 	 */
7936 	if (phyp == NULL) {
7937 		for (pptr = list_head(&iport->phys); pptr != NULL;
7938 		    pptr = next_pptr) {
7939 			next_pptr = list_next(&iport->phys, pptr);
7940 			mutex_enter(&pptr->phy_lock);
7941 			if (pptr->phy_stats != NULL) {
7942 				kstat_delete(pptr->phy_stats);
7943 				pptr->phy_stats = NULL;
7944 			}
7945 			pptr->iport = NULL;
7946 			pmcs_update_phy_pm_props(pptr, pptr->att_port_pm_tmp,
7947 			    pptr->tgt_port_pm_tmp, B_FALSE);
7948 			mutex_exit(&pptr->phy_lock);
7949 			pmcs_rele_iport(iport);
7950 			list_remove(&iport->phys, pptr);
7951 			pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32,
7952 			    PMCS_NUM_PHYS, &iport->nphy);
7953 		}
7954 		iport->nphy = 0;
7955 		return;
7956 	}
7957 
7958 	ASSERT(phyp);
7959 	ASSERT(iport->nphy > 0);
7960 	ASSERT(list_link_active(&phyp->list_node));
7961 	iport->nphy--;
7962 	list_remove(&iport->phys, phyp);
7963 	pmcs_update_phy_pm_props(phyp, phyp->att_port_pm_tmp,
7964 	    phyp->tgt_port_pm_tmp, B_FALSE);
7965 	pmcs_smhba_add_iport_prop(iport, DATA_TYPE_INT32, PMCS_NUM_PHYS,
7966 	    &iport->nphy);
7967 	pmcs_rele_iport(iport);
7968 }
7969 
7970 /*
7971  * This function checks to see if the target pointed to by phyp is still
7972  * correct.  This is done by comparing the target's unit address with the
7973  * SAS address in phyp.
7974  *
7975  * Called with PHY locked and target statlock held
7976  */
7977 static boolean_t
7978 pmcs_phy_target_match(pmcs_phy_t *phyp)
7979 {
7980 	uint64_t wwn;
7981 	char unit_address[PMCS_MAX_UA_SIZE];
7982 	boolean_t rval = B_FALSE;
7983 
7984 	ASSERT(phyp);
7985 	ASSERT(phyp->target);
7986 	ASSERT(mutex_owned(&phyp->phy_lock));
7987 	ASSERT(mutex_owned(&phyp->target->statlock));
7988 
7989 	wwn = pmcs_barray2wwn(phyp->sas_address);
7990 	(void) scsi_wwn_to_wwnstr(wwn, 1, unit_address);
7991 
7992 	if (memcmp((void *)unit_address, (void *)phyp->target->unit_address,
7993 	    strnlen(phyp->target->unit_address, PMCS_MAX_UA_SIZE)) == 0) {
7994 		rval = B_TRUE;
7995 	}
7996 
7997 	return (rval);
7998 }
7999 /*
8000  * Commands used to serialize SMP requests.
8001  *
8002  * The SPC only allows 2 SMP commands per SMP target: 1 cmd pending and 1 cmd
8003  * queued for the same SMP target. If a third SMP cmd is sent to the SPC for an
8004  * SMP target that already has a SMP cmd pending and one queued, then the
8005  * SPC responds with the ERROR_INTERNAL_SMP_RESOURCE response.
8006  *
8007  * Additionally, the SPC has an 8 entry deep cmd queue and the number of SMP
8008  * cmds that can be queued is controlled by the PORT_CONTROL IOMB. The
8009  * SPC default is 1 SMP command/port (iport).  These 2 queued SMP cmds would
8010  * have to be for different SMP targets.  The INTERNAL_SMP_RESOURCE error will
8011  * also be returned if a 2nd SMP cmd is sent to the controller when there is
8012  * already 1 SMP cmd queued for that port or if a 3rd SMP cmd is sent to the
8013  * queue if there are already 2 queued SMP cmds.
8014  */
8015 void
8016 pmcs_smp_acquire(pmcs_iport_t *iport)
8017 {
8018 	if (iport == NULL) {
8019 		return;
8020 	}
8021 
8022 	mutex_enter(&iport->smp_lock);
8023 	while (iport->smp_active) {
8024 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_IPORT, NULL, NULL,
8025 		    "%s: SMP is active on thread 0x%p, waiting", __func__,
8026 		    (void *)iport->smp_active_thread);
8027 		cv_wait(&iport->smp_cv, &iport->smp_lock);
8028 	}
8029 	iport->smp_active = B_TRUE;
8030 	iport->smp_active_thread = curthread;
8031 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG3, NULL, NULL,
8032 	    "%s: SMP acquired by thread 0x%p", __func__,
8033 	    (void *)iport->smp_active_thread);
8034 	mutex_exit(&iport->smp_lock);
8035 }
8036 
8037 void
8038 pmcs_smp_release(pmcs_iport_t *iport)
8039 {
8040 	if (iport == NULL) {
8041 		return;
8042 	}
8043 
8044 	mutex_enter(&iport->smp_lock);
8045 	pmcs_prt(iport->pwp, PMCS_PRT_DEBUG3, NULL, NULL,
8046 	    "%s: SMP released by thread 0x%p", __func__, (void *)curthread);
8047 	iport->smp_active = B_FALSE;
8048 	iport->smp_active_thread = NULL;
8049 	cv_signal(&iport->smp_cv);
8050 	mutex_exit(&iport->smp_lock);
8051 }
8052 
8053 /*
8054  * Update a PHY's attached-port-pm and target-port-pm properties
8055  *
8056  * phyp: PHY whose properties are to be updated
8057  *
8058  * att_bv: Bit value of the attached-port-pm property to be updated in the
8059  * 64-bit holding area for the PHY.
8060  *
8061  * tgt_bv: Bit value of the target-port-pm property to update in the 64-bit
8062  * holding area for the PHY.
8063  *
8064  * prop_add_val: If TRUE, we're adding bits into the property value.
8065  * Otherwise, we're taking them out.  Either way, the properties for this
8066  * PHY will be updated.
8067  */
8068 void
8069 pmcs_update_phy_pm_props(pmcs_phy_t *phyp, uint64_t att_bv, uint64_t tgt_bv,
8070     boolean_t prop_add_val)
8071 {
8072 	pmcs_xscsi_t	*tgt;
8073 
8074 	if (prop_add_val) {
8075 		/*
8076 		 * If the values are currently 0, then we're setting the
8077 		 * phymask for just this PHY as well.
8078 		 */
8079 		if (phyp->att_port_pm_tmp == 0) {
8080 			phyp->att_port_pm = att_bv;
8081 			phyp->tgt_port_pm = tgt_bv;
8082 		}
8083 		phyp->att_port_pm_tmp |= att_bv;
8084 		phyp->tgt_port_pm_tmp |= tgt_bv;
8085 		(void) snprintf(phyp->att_port_pm_str, PMCS_PM_MAX_NAMELEN,
8086 		    "%"PRIx64, phyp->att_port_pm_tmp);
8087 		(void) snprintf(phyp->tgt_port_pm_str, PMCS_PM_MAX_NAMELEN,
8088 		    "%"PRIx64, phyp->tgt_port_pm_tmp);
8089 	} else {
8090 		phyp->att_port_pm_tmp &= ~att_bv;
8091 		phyp->tgt_port_pm_tmp &= ~tgt_bv;
8092 		if (phyp->att_port_pm_tmp) {
8093 			(void) snprintf(phyp->att_port_pm_str,
8094 			    PMCS_PM_MAX_NAMELEN, "%"PRIx64,
8095 			    phyp->att_port_pm_tmp);
8096 		} else {
8097 			phyp->att_port_pm_str[0] = '\0';
8098 			phyp->att_port_pm = 0;
8099 		}
8100 		if (phyp->tgt_port_pm_tmp) {
8101 			(void) snprintf(phyp->tgt_port_pm_str,
8102 			    PMCS_PM_MAX_NAMELEN, "%"PRIx64,
8103 			    phyp->tgt_port_pm_tmp);
8104 		} else {
8105 			phyp->tgt_port_pm_str[0] = '\0';
8106 			phyp->tgt_port_pm = 0;
8107 		}
8108 	}
8109 
8110 	if ((phyp->target_addr) && (*phyp->target_addr != NULL)) {
8111 		tgt = *phyp->target_addr;
8112 	} else if (phyp->target != NULL) {
8113 		tgt = phyp->target;
8114 	} else {
8115 		return;
8116 	}
8117 
8118 	mutex_enter(&tgt->statlock);
8119 	if (!list_is_empty(&tgt->lun_list)) {
8120 		pmcs_lun_t *lunp;
8121 
8122 		lunp = list_head(&tgt->lun_list);
8123 		while (lunp) {
8124 			(void) scsi_device_prop_update_string(lunp->sd,
8125 			    SCSI_DEVICE_PROP_PATH,
8126 			    SCSI_ADDR_PROP_ATTACHED_PORT_PM,
8127 			    phyp->att_port_pm_str);
8128 			(void) scsi_device_prop_update_string(lunp->sd,
8129 			    SCSI_DEVICE_PROP_PATH,
8130 			    SCSI_ADDR_PROP_TARGET_PORT_PM,
8131 			    phyp->tgt_port_pm_str);
8132 			lunp = list_next(&tgt->lun_list, lunp);
8133 		}
8134 	} else if (tgt->smpd) {
8135 		(void) smp_device_prop_update_string(tgt->smpd,
8136 		    SCSI_ADDR_PROP_ATTACHED_PORT_PM,
8137 		    phyp->att_port_pm_str);
8138 		(void) smp_device_prop_update_string(tgt->smpd,
8139 		    SCSI_ADDR_PROP_TARGET_PORT_PM,
8140 		    phyp->tgt_port_pm_str);
8141 	}
8142 	mutex_exit(&tgt->statlock);
8143 }
8144 
8145 /* ARGSUSED */
8146 void
8147 pmcs_deregister_device_work(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
8148 {
8149 	pmcs_phy_t	*pptr;
8150 
8151 	for (pptr = pwp->root_phys; pptr; pptr = pptr->sibling) {
8152 		pmcs_lock_phy(pptr);
8153 		if (pptr->deregister_wait) {
8154 			pmcs_deregister_device(pwp, pptr);
8155 		}
8156 		pmcs_unlock_phy(pptr);
8157 	}
8158 }
8159 
8160 /*
8161  * pmcs_iport_active
8162  *
8163  * Mark this iport as active.  Called with the iport lock held.
8164  */
8165 static void
8166 pmcs_iport_active(pmcs_iport_t *iport)
8167 {
8168 	ASSERT(mutex_owned(&iport->lock));
8169 
8170 	iport->ua_state = UA_ACTIVE;
8171 	iport->smp_active = B_FALSE;
8172 	iport->smp_active_thread = NULL;
8173 }
8174 
8175 /* ARGSUSED */
8176 static void
8177 pmcs_tgtmap_activate_cb(void *tgtmap_priv, char *tgt_addr,
8178     scsi_tgtmap_tgt_type_t tgt_type, void **tgt_privp)
8179 {
8180 	pmcs_iport_t *iport = (pmcs_iport_t *)tgtmap_priv;
8181 	pmcs_hw_t *pwp = iport->pwp;
8182 	pmcs_xscsi_t *target;
8183 
8184 	/*
8185 	 * Look up the target.  If there is one, and it doesn't have a PHY
8186 	 * pointer, re-establish that linkage here.
8187 	 */
8188 	mutex_enter(&pwp->lock);
8189 	target = pmcs_get_target(iport, tgt_addr, B_FALSE);
8190 	mutex_exit(&pwp->lock);
8191 
8192 	/*
8193 	 * If we got a target, it will now have a PHY pointer and the PHY
8194 	 * will point to the target.  The PHY will be locked, so we'll need
8195 	 * to unlock it.
8196 	 */
8197 	if (target != NULL) {
8198 		pmcs_unlock_phy(target->phy);
8199 	}
8200 
8201 	/*
8202 	 * Update config_restart_time so we don't try to restart discovery
8203 	 * while enumeration is still in progress.
8204 	 */
8205 	mutex_enter(&pwp->config_lock);
8206 	pwp->config_restart_time = ddi_get_lbolt() +
8207 	    drv_usectohz(PMCS_REDISCOVERY_DELAY);
8208 	mutex_exit(&pwp->config_lock);
8209 }
8210 
8211 /* ARGSUSED */
8212 static boolean_t
8213 pmcs_tgtmap_deactivate_cb(void *tgtmap_priv, char *tgt_addr,
8214     scsi_tgtmap_tgt_type_t tgt_type, void *tgt_priv,
8215     scsi_tgtmap_deact_rsn_t tgt_deact_rsn)
8216 {
8217 	pmcs_iport_t *iport = (pmcs_iport_t *)tgtmap_priv;
8218 	pmcs_phy_t *phyp;
8219 	boolean_t rediscover = B_FALSE;
8220 
8221 	ASSERT(iport);
8222 
8223 	phyp = pmcs_find_phy_by_sas_address(iport->pwp, iport, NULL, tgt_addr);
8224 	if (phyp == NULL) {
8225 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_IPORT, NULL, NULL,
8226 		    "%s: Couldn't find PHY at %s", __func__, tgt_addr);
8227 		return (rediscover);
8228 	}
8229 	/* phyp is locked */
8230 
8231 	if (!phyp->reenumerate && phyp->configured) {
8232 		pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_CONFIG, phyp, phyp->target,
8233 		    "%s: PHY @ %s is configured... re-enumerate", __func__,
8234 		    tgt_addr);
8235 		phyp->reenumerate = 1;
8236 	}
8237 
8238 	/*
8239 	 * Check to see if reenumerate is set, and if so, if we've reached our
8240 	 * maximum number of retries.
8241 	 */
8242 	if (phyp->reenumerate) {
8243 		if (phyp->enum_attempts == PMCS_MAX_REENUMERATE) {
8244 			pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_CONFIG, phyp,
8245 			    phyp->target,
8246 			    "%s: No more enumeration attempts for %s", __func__,
8247 			    tgt_addr);
8248 		} else {
8249 			pmcs_prt(iport->pwp, PMCS_PRT_DEBUG_CONFIG, phyp,
8250 			    phyp->target, "%s: Re-attempt enumeration for %s",
8251 			    __func__, tgt_addr);
8252 			++phyp->enum_attempts;
8253 			rediscover = B_TRUE;
8254 		}
8255 
8256 		phyp->reenumerate = 0;
8257 	}
8258 
8259 	pmcs_unlock_phy(phyp);
8260 
8261 	mutex_enter(&iport->pwp->config_lock);
8262 	iport->pwp->config_restart_time = ddi_get_lbolt() +
8263 	    drv_usectohz(PMCS_REDISCOVERY_DELAY);
8264 	if (rediscover) {
8265 		iport->pwp->config_restart = B_TRUE;
8266 	} else if (iport->pwp->config_restart == B_TRUE) {
8267 		/*
8268 		 * If we aren't asking for rediscovery because of this PHY,
8269 		 * check to see if we're already asking for it on behalf of
8270 		 * some other PHY.  If so, we'll want to return TRUE, so reset
8271 		 * "rediscover" here.
8272 		 */
8273 		rediscover = B_TRUE;
8274 	}
8275 
8276 	mutex_exit(&iport->pwp->config_lock);
8277 
8278 	return (rediscover);
8279 }
8280 
8281 void
8282 pmcs_status_disposition(pmcs_phy_t *phyp, uint32_t status)
8283 {
8284 	ASSERT(phyp);
8285 	ASSERT(!mutex_owned(&phyp->phy_lock));
8286 
8287 	if (phyp == NULL) {
8288 		return;
8289 	}
8290 
8291 	pmcs_lock_phy(phyp);
8292 
8293 	/*
8294 	 * XXX: Do we need to call this function from an SSP_EVENT?
8295 	 */
8296 
8297 	switch (status) {
8298 	case PMCOUT_STATUS_NO_DEVICE:
8299 	case PMCOUT_STATUS_ERROR_HW_TIMEOUT:
8300 	case PMCOUT_STATUS_XFER_ERR_BREAK:
8301 	case PMCOUT_STATUS_XFER_ERR_PHY_NOT_READY:
8302 	case PMCOUT_STATUS_OPEN_CNX_PROTOCOL_NOT_SUPPORTED:
8303 	case PMCOUT_STATUS_OPEN_CNX_ERROR_ZONE_VIOLATION:
8304 	case PMCOUT_STATUS_OPEN_CNX_ERROR_BREAK:
8305 	case PMCOUT_STATUS_OPENCNX_ERROR_BAD_DESTINATION:
8306 	case PMCOUT_STATUS_OPEN_CNX_ERROR_CONNECTION_RATE_NOT_SUPPORTED:
8307 	case PMCOUT_STATUS_OPEN_CNX_ERROR_STP_RESOURCES_BUSY:
8308 	case PMCOUT_STATUS_OPEN_CNX_ERROR_WRONG_DESTINATION:
8309 	case PMCOUT_STATUS_OPEN_CNX_ERROR_UNKNOWN_ERROR:
8310 	case PMCOUT_STATUS_IO_XFER_ERROR_NAK_RECEIVED:
8311 	case PMCOUT_STATUS_XFER_ERROR_RX_FRAME:
8312 	case PMCOUT_STATUS_IO_XFER_OPEN_RETRY_TIMEOUT:
8313 	case PMCOUT_STATUS_ERROR_INTERNAL_SMP_RESOURCE:
8314 	case PMCOUT_STATUS_IO_PORT_IN_RESET:
8315 	case PMCOUT_STATUS_IO_DS_NON_OPERATIONAL:
8316 	case PMCOUT_STATUS_IO_DS_IN_RECOVERY:
8317 	case PMCOUT_STATUS_IO_OPEN_CNX_ERROR_HW_RESOURCE_BUSY:
8318 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG, phyp, phyp->target,
8319 		    "%s: status = 0x%x for " SAS_ADDR_FMT ", reenumerate",
8320 		    __func__, status, SAS_ADDR_PRT(phyp->sas_address));
8321 		phyp->reenumerate = 1;
8322 		break;
8323 
8324 	default:
8325 		pmcs_prt(phyp->pwp, PMCS_PRT_DEBUG, phyp, phyp->target,
8326 		    "%s: status = 0x%x for " SAS_ADDR_FMT ", no reenumeration",
8327 		    __func__, status, SAS_ADDR_PRT(phyp->sas_address));
8328 		break;
8329 	}
8330 
8331 	pmcs_unlock_phy(phyp);
8332 }
8333 
8334 /*
8335  * Add the list of PHYs pointed to by phyp to the dead_phys_list
8336  *
8337  * Called with all PHYs in the list locked
8338  */
8339 static void
8340 pmcs_add_dead_phys(pmcs_hw_t *pwp, pmcs_phy_t *phyp)
8341 {
8342 	mutex_enter(&pwp->dead_phylist_lock);
8343 	while (phyp) {
8344 		pmcs_phy_t *nxt = phyp->sibling;
8345 		ASSERT(phyp->dead);
8346 		pmcs_prt(pwp, PMCS_PRT_DEBUG_CONFIG, phyp, NULL,
8347 		    "%s: dead PHY 0x%p (%s) (ref_count %d)", __func__,
8348 		    (void *)phyp, phyp->path, phyp->ref_count);
8349 		/*
8350 		 * Put this PHY on the dead PHY list for the watchdog to
8351 		 * clean up after any outstanding work has completed.
8352 		 */
8353 		phyp->dead_next = pwp->dead_phys;
8354 		pwp->dead_phys = phyp;
8355 		pmcs_unlock_phy(phyp);
8356 		phyp = nxt;
8357 	}
8358 	mutex_exit(&pwp->dead_phylist_lock);
8359 }
8360 
8361 static void
8362 pmcs_get_fw_version(pmcs_hw_t *pwp)
8363 {
8364 	uint32_t ila_len, ver_hi, ver_lo;
8365 	uint8_t ila_ver_string[9], img_flag;
8366 	char uc, *ucp = &uc;
8367 	unsigned long ila_ver;
8368 	uint64_t ver_hilo;
8369 
8370 	/* Firmware version is easy. */
8371 	pwp->fw = pmcs_rd_mpi_tbl(pwp, PMCS_MPI_FW);
8372 
8373 	/*
8374 	 * Get the image size (2nd to last dword)
8375 	 * NOTE: The GSM registers are mapped little-endian, but the data
8376 	 * on the flash is actually big-endian, so we need to swap these values
8377 	 * regardless of which platform we're on.
8378 	 */
8379 	ila_len = BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8380 	    GSM_FLASH_BASE + GSM_SM_BLKSZ - (2 << 2)));
8381 	if (ila_len > 65535) {
8382 		pmcs_prt(pwp, PMCS_PRT_DEBUG, NULL, NULL,
8383 		    "%s: Invalid ILA image size (0x%x)?", __func__, ila_len);
8384 		return;
8385 	}
8386 
8387 	/*
8388 	 * The numeric version is at ila_len - PMCS_ILA_VER_OFFSET
8389 	 */
8390 	ver_hi = BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8391 	    GSM_FLASH_BASE + ila_len - PMCS_ILA_VER_OFFSET));
8392 	ver_lo = BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8393 	    GSM_FLASH_BASE + ila_len - PMCS_ILA_VER_OFFSET + 4));
8394 	ver_hilo = BE_64(((uint64_t)ver_hi << 32) | ver_lo);
8395 	bcopy((const void *)&ver_hilo, &ila_ver_string[0], 8);
8396 	ila_ver_string[8] = '\0';
8397 
8398 	(void) ddi_strtoul((const char *)ila_ver_string, &ucp, 16, &ila_ver);
8399 	pwp->ila_ver = (int)(ila_ver & 0xffffffff);
8400 
8401 	img_flag = (BSWAP_32(pmcs_rd_gsm_reg(pwp, GSM_FLASH_BASE_UPPER,
8402 	    GSM_FLASH_IMG_FLAGS)) & 0xff000000) >> 24;
8403 	if (img_flag & PMCS_IMG_FLAG_A) {
8404 		pwp->fw_active_img = 1;
8405 	} else {
8406 		pwp->fw_active_img = 0;
8407 	}
8408 }
8409