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