xref: /illumos-gate/usr/src/uts/common/io/sata/adapters/ahci/ahci.c (revision 581cede61ac9c14d8d4ea452562a567189eead78)
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 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * AHCI (Advanced Host Controller Interface) SATA HBA Driver
29  *
30  * Power Management Support
31  * ------------------------
32  *
33  * At the moment, the ahci driver only implements suspend/resume to
34  * support Suspend to RAM on X86 feature. Device power management isn't
35  * implemented, link power management is disabled, and hot plug isn't
36  * allowed during the period from suspend to resume.
37  *
38  * For s/r support, the ahci driver only need to implement DDI_SUSPEND
39  * and DDI_RESUME entries, and don't need to take care of new requests
40  * sent down after suspend because the target driver (sd) has already
41  * handled these conditions, and blocked these requests. For the detailed
42  * information, please check with sdopen, sdclose and sdioctl routines.
43  *
44  */
45 
46 #include <sys/note.h>
47 #include <sys/scsi/scsi.h>
48 #include <sys/pci.h>
49 #include <sys/disp.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/adapters/ahci/ahcireg.h>
52 #include <sys/sata/adapters/ahci/ahcivar.h>
53 
54 /*
55  * This is the string displayed by modinfo, etc.
56  * Make sure you keep the version ID up to date!
57  */
58 static char ahci_ident[] = "ahci driver";
59 
60 /*
61  * Function prototypes for driver entry points
62  */
63 static	int ahci_attach(dev_info_t *, ddi_attach_cmd_t);
64 static	int ahci_detach(dev_info_t *, ddi_detach_cmd_t);
65 static	int ahci_getinfo(dev_info_t *, ddi_info_cmd_t, void *, void **);
66 static	int ahci_quiesce(dev_info_t *);
67 
68 /*
69  * Function prototypes for SATA Framework interfaces
70  */
71 static	int ahci_register_sata_hba_tran(ahci_ctl_t *, uint32_t);
72 static	int ahci_unregister_sata_hba_tran(ahci_ctl_t *);
73 
74 static	int ahci_tran_probe_port(dev_info_t *, sata_device_t *);
75 static	int ahci_tran_start(dev_info_t *, sata_pkt_t *spkt);
76 static	int ahci_tran_abort(dev_info_t *, sata_pkt_t *, int);
77 static	int ahci_tran_reset_dport(dev_info_t *, sata_device_t *);
78 static	int ahci_tran_hotplug_port_activate(dev_info_t *, sata_device_t *);
79 static	int ahci_tran_hotplug_port_deactivate(dev_info_t *, sata_device_t *);
80 #if defined(__lock_lint)
81 static	int ahci_selftest(dev_info_t *, sata_device_t *);
82 #endif
83 
84 /*
85  * Local function prototypes
86  */
87 static	int ahci_alloc_ports_state(ahci_ctl_t *);
88 static	void ahci_dealloc_ports_state(ahci_ctl_t *);
89 static	int ahci_alloc_port_state(ahci_ctl_t *, uint8_t);
90 static	void ahci_dealloc_port_state(ahci_ctl_t *, uint8_t);
91 static	int ahci_alloc_rcvd_fis(ahci_ctl_t *, ahci_port_t *, uint8_t);
92 static	void ahci_dealloc_rcvd_fis(ahci_port_t *);
93 static	int ahci_alloc_cmd_list(ahci_ctl_t *, ahci_port_t *, uint8_t);
94 static	void ahci_dealloc_cmd_list(ahci_ctl_t *, ahci_port_t *);
95 static  int ahci_alloc_cmd_tables(ahci_ctl_t *, ahci_port_t *);
96 static  void ahci_dealloc_cmd_tables(ahci_ctl_t *, ahci_port_t *);
97 static	void ahci_alloc_pmult(ahci_ctl_t *, ahci_port_t *);
98 static	void ahci_dealloc_pmult(ahci_ctl_t *, ahci_port_t *);
99 
100 static	int ahci_initialize_controller(ahci_ctl_t *);
101 static	void ahci_uninitialize_controller(ahci_ctl_t *);
102 static	int ahci_initialize_port(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
103 static	int ahci_config_space_init(ahci_ctl_t *);
104 
105 static	void ahci_drain_ports_taskq(ahci_ctl_t *);
106 static	int ahci_rdwr_pmult(ahci_ctl_t *, ahci_addr_t *, uint8_t, uint32_t *,
107     uint8_t);
108 static	int ahci_read_pmult(ahci_ctl_t *, ahci_addr_t *, uint8_t, uint32_t *);
109 static	int ahci_write_pmult(ahci_ctl_t *, ahci_addr_t *, uint8_t, uint32_t);
110 static	int ahci_update_pmult_pscr(ahci_ctl_t *, ahci_addr_t *,
111     sata_device_t *);
112 static	int ahci_update_pmult_gscr(ahci_ctl_t *, ahci_addr_t *,
113     sata_device_t *);
114 static	int ahci_initialize_pmult(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *,
115     sata_device_t *);
116 static	int ahci_initialize_pmport(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
117 static	int ahci_probe_pmult(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
118 static	int ahci_probe_pmport(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *,
119     sata_device_t *);
120 
121 static	void ahci_disable_interface_pm(ahci_ctl_t *, uint8_t);
122 static	int ahci_start_port(ahci_ctl_t *, ahci_port_t *, uint8_t);
123 static	void ahci_find_dev_signature(ahci_ctl_t *, ahci_port_t *,
124     ahci_addr_t *);
125 static	void ahci_update_sata_registers(ahci_ctl_t *, uint8_t, sata_device_t *);
126 static	int ahci_deliver_satapkt(ahci_ctl_t *, ahci_port_t *,
127     ahci_addr_t *, sata_pkt_t *);
128 static	int ahci_do_sync_start(ahci_ctl_t *, ahci_port_t *,
129     ahci_addr_t *, sata_pkt_t *);
130 static	int ahci_claim_free_slot(ahci_ctl_t *, ahci_port_t *,
131     ahci_addr_t *, int);
132 static  void ahci_copy_err_cnxt(sata_cmd_t *, ahci_fis_d2h_register_t *);
133 static	void ahci_copy_ncq_err_page(sata_cmd_t *,
134     struct sata_ncq_error_recovery_page *);
135 static	void ahci_copy_out_regs(sata_cmd_t *, ahci_fis_d2h_register_t *);
136 
137 static	int ahci_software_reset(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
138 static	int ahci_hba_reset(ahci_ctl_t *);
139 static	int ahci_port_reset(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
140 static	int ahci_pmport_reset(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
141 static	void ahci_reject_all_abort_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
142 static	int ahci_reset_device_reject_pkts(ahci_ctl_t *, ahci_port_t *,
143     ahci_addr_t *);
144 static	int ahci_reset_pmdevice_reject_pkts(ahci_ctl_t *, ahci_port_t *,
145     ahci_addr_t *);
146 static	int ahci_reset_port_reject_pkts(ahci_ctl_t *, ahci_port_t *,
147     ahci_addr_t *);
148 static	int ahci_reset_hba_reject_pkts(ahci_ctl_t *);
149 static	int ahci_put_port_into_notrunning_state(ahci_ctl_t *, ahci_port_t *,
150     uint8_t);
151 static	int ahci_restart_port_wait_till_ready(ahci_ctl_t *, ahci_port_t *,
152     uint8_t, int, int *);
153 static	void ahci_mop_commands(ahci_ctl_t *, ahci_port_t *, uint32_t,
154     uint32_t, uint32_t, uint32_t, uint32_t);
155 static	uint32_t ahci_get_rdlogext_data(ahci_ctl_t *, ahci_port_t *, uint8_t);
156 static void ahci_get_rqsense_data(ahci_ctl_t *, ahci_port_t *,
157     uint8_t, sata_pkt_t *);
158 static	void ahci_fatal_error_recovery_handler(ahci_ctl_t *, ahci_port_t *,
159     ahci_addr_t *, uint32_t);
160 static	void ahci_pmult_error_recovery_handler(ahci_ctl_t *, ahci_port_t *,
161     uint8_t, uint32_t);
162 static	void ahci_timeout_pkts(ahci_ctl_t *, ahci_port_t *,
163     uint8_t, uint32_t);
164 static	void ahci_events_handler(void *);
165 static	void ahci_watchdog_handler(ahci_ctl_t *);
166 
167 static	uint_t ahci_intr(caddr_t, caddr_t);
168 static	void ahci_port_intr(ahci_ctl_t *, ahci_port_t *, uint8_t);
169 static	int ahci_add_intrs(ahci_ctl_t *, int);
170 static	void ahci_rem_intrs(ahci_ctl_t *);
171 static	void ahci_enable_all_intrs(ahci_ctl_t *);
172 static	void ahci_disable_all_intrs(ahci_ctl_t *);
173 static	void ahci_enable_port_intrs(ahci_ctl_t *, uint8_t);
174 static	void ahci_disable_port_intrs(ahci_ctl_t *, uint8_t);
175 
176 static  int ahci_intr_cmd_cmplt(ahci_ctl_t *, ahci_port_t *, uint8_t);
177 static	int ahci_intr_set_device_bits(ahci_ctl_t *, ahci_port_t *, uint8_t);
178 static	int ahci_intr_ncq_events(ahci_ctl_t *, ahci_port_t *, ahci_addr_t *);
179 static	int ahci_intr_pmult_sntf_events(ahci_ctl_t *, ahci_port_t *, uint8_t);
180 static	int ahci_intr_port_connect_change(ahci_ctl_t *, ahci_port_t *, uint8_t);
181 static	int ahci_intr_device_mechanical_presence_status(ahci_ctl_t *,
182     ahci_port_t *, uint8_t);
183 static	int ahci_intr_phyrdy_change(ahci_ctl_t *, ahci_port_t *, uint8_t);
184 static	int ahci_intr_non_fatal_error(ahci_ctl_t *, ahci_port_t *,
185     uint8_t, uint32_t);
186 static  int ahci_intr_fatal_error(ahci_ctl_t *, ahci_port_t *,
187     uint8_t, uint32_t);
188 static	int ahci_intr_cold_port_detect(ahci_ctl_t *, ahci_port_t *, uint8_t);
189 
190 static	void ahci_get_ahci_addr(ahci_ctl_t *, sata_device_t *, ahci_addr_t *);
191 static	int ahci_get_num_implemented_ports(uint32_t);
192 static  void ahci_log_fatal_error_message(ahci_ctl_t *, uint8_t port,
193     uint32_t);
194 static	void ahci_log_serror_message(ahci_ctl_t *, uint8_t, uint32_t, int);
195 #if AHCI_DEBUG
196 static	void ahci_log(ahci_ctl_t *, uint_t, char *, ...);
197 #endif
198 
199 
200 /*
201  * DMA attributes for the data buffer
202  *
203  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
204  * does not support 64-bit addressing
205  */
206 static ddi_dma_attr_t buffer_dma_attr = {
207 	DMA_ATTR_V0,		/* dma_attr_version */
208 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
209 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
210 	0x3fffffull,		/* dma_attr_count_max i.e. for one cookie */
211 	0x2ull,			/* dma_attr_align: word aligned */
212 	1,			/* dma_attr_burstsizes */
213 	1,			/* dma_attr_minxfer */
214 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
215 	0xffffffffull,		/* dma_attr_seg */
216 	AHCI_PRDT_NUMBER,	/* dma_attr_sgllen */
217 	512,			/* dma_attr_granular */
218 	0,			/* dma_attr_flags */
219 };
220 
221 /*
222  * DMA attributes for the rcvd FIS
223  *
224  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
225  * does not support 64-bit addressing
226  */
227 static ddi_dma_attr_t rcvd_fis_dma_attr = {
228 	DMA_ATTR_V0,		/* dma_attr_version */
229 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
230 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
231 	0xffffffffull,		/* dma_attr_count_max i.e. for one cookie */
232 	0x100ull,		/* dma_attr_align: 256-byte aligned */
233 	1,			/* dma_attr_burstsizes */
234 	1,			/* dma_attr_minxfer */
235 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
236 	0xffffffffull,		/* dma_attr_seg */
237 	1,			/* dma_attr_sgllen */
238 	1,			/* dma_attr_granular */
239 	0,			/* dma_attr_flags */
240 };
241 
242 /*
243  * DMA attributes for the command list
244  *
245  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
246  * does not support 64-bit addressing
247  */
248 static ddi_dma_attr_t cmd_list_dma_attr = {
249 	DMA_ATTR_V0,		/* dma_attr_version */
250 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
251 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
252 	0xffffffffull,		/* dma_attr_count_max i.e. for one cookie */
253 	0x400ull,		/* dma_attr_align: 1K-byte aligned */
254 	1,			/* dma_attr_burstsizes */
255 	1,			/* dma_attr_minxfer */
256 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
257 	0xffffffffull,		/* dma_attr_seg */
258 	1,			/* dma_attr_sgllen */
259 	1,			/* dma_attr_granular */
260 	0,			/* dma_attr_flags */
261 };
262 
263 /*
264  * DMA attributes for cmd tables
265  *
266  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
267  * does not support 64-bit addressing
268  */
269 static ddi_dma_attr_t cmd_table_dma_attr = {
270 	DMA_ATTR_V0,		/* dma_attr_version */
271 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
272 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
273 	0xffffffffull,		/* dma_attr_count_max i.e. for one cookie */
274 	0x80ull,		/* dma_attr_align: 128-byte aligned */
275 	1,			/* dma_attr_burstsizes */
276 	1,			/* dma_attr_minxfer */
277 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
278 	0xffffffffull,		/* dma_attr_seg */
279 	1,			/* dma_attr_sgllen */
280 	1,			/* dma_attr_granular */
281 	0,			/* dma_attr_flags */
282 };
283 
284 
285 /* Device access attributes */
286 static ddi_device_acc_attr_t accattr = {
287 	DDI_DEVICE_ATTR_V0,
288 	DDI_STRUCTURE_LE_ACC,
289 	DDI_STRICTORDER_ACC
290 };
291 
292 
293 static struct dev_ops ahcictl_dev_ops = {
294 	DEVO_REV,		/* devo_rev */
295 	0,			/* refcnt  */
296 	ahci_getinfo,		/* info */
297 	nulldev,		/* identify */
298 	nulldev,		/* probe */
299 	ahci_attach,		/* attach */
300 	ahci_detach,		/* detach */
301 	nodev,			/* no reset */
302 	(struct cb_ops *)0,	/* driver operations */
303 	NULL,			/* bus operations */
304 	NULL,			/* power */
305 	ahci_quiesce,		/* quiesce */
306 };
307 
308 static sata_tran_hotplug_ops_t ahci_tran_hotplug_ops = {
309 	SATA_TRAN_HOTPLUG_OPS_REV_1,
310 	ahci_tran_hotplug_port_activate,
311 	ahci_tran_hotplug_port_deactivate
312 };
313 
314 extern struct mod_ops mod_driverops;
315 
316 static  struct modldrv modldrv = {
317 	&mod_driverops,		/* driverops */
318 	ahci_ident,		/* short description */
319 	&ahcictl_dev_ops,	/* driver ops */
320 };
321 
322 static  struct modlinkage modlinkage = {
323 	MODREV_1,
324 	&modldrv,
325 	NULL
326 };
327 
328 /* The following variables are watchdog handler related */
329 static int ahci_watchdog_timeout = 5; /* 5 seconds */
330 static int ahci_watchdog_tick;
331 
332 /*
333  * This static variable indicates the size of command table,
334  * and it's changeable with prdt number, which ahci_dma_prdt_number
335  * indicates.
336  */
337 static size_t ahci_cmd_table_size;
338 
339 /*
340  * The below global variables are tunable via /etc/system
341  *
342  *	ahci_dma_prdt_number
343  *	ahci_msi_enabled
344  *	ahci_buf_64bit_dma
345  *	ahci_commu_64bit_dma
346  */
347 
348 /* The number of Physical Region Descriptor Table(PRDT) in Command Table */
349 int ahci_dma_prdt_number = AHCI_PRDT_NUMBER;
350 
351 /* AHCI MSI is tunable */
352 boolean_t ahci_msi_enabled = B_TRUE;
353 
354 /*
355  * 64-bit dma addressing for data buffer is tunable
356  *
357  * The variable controls only the below value:
358  *	DBAU (upper 32-bits physical address of data block)
359  */
360 boolean_t ahci_buf_64bit_dma = B_TRUE;
361 
362 /*
363  * 64-bit dma addressing for communication system descriptors is tunable
364  *
365  * The variable controls the below three values:
366  *
367  *	PxCLBU (upper 32-bits for the command list base physical address)
368  *	PxFBU (upper 32-bits for the received FIS base physical address)
369  *	CTBAU (upper 32-bits of command table base)
370  */
371 boolean_t ahci_commu_64bit_dma = B_TRUE;
372 
373 /*
374  * End of global tunable variable definition
375  */
376 
377 #if AHCI_DEBUG
378 uint32_t ahci_debug_flags = 0;
379 #else
380 uint32_t ahci_debug_flags = (AHCIDBG_ERRS|AHCIDBG_TIMEOUT);
381 #endif
382 
383 
384 #if AHCI_DEBUG
385 /* The following is needed for ahci_log() */
386 static kmutex_t ahci_log_mutex;
387 static char ahci_log_buf[512];
388 #endif
389 
390 /* Opaque state pointer initialized by ddi_soft_state_init() */
391 static void *ahci_statep = NULL;
392 
393 /*
394  *  ahci module initialization.
395  */
396 int
397 _init(void)
398 {
399 	int	ret;
400 
401 	ret = ddi_soft_state_init(&ahci_statep, sizeof (ahci_ctl_t), 0);
402 	if (ret != 0) {
403 		goto err_out;
404 	}
405 
406 #if AHCI_DEBUG
407 	mutex_init(&ahci_log_mutex, NULL, MUTEX_DRIVER, NULL);
408 #endif
409 
410 	if ((ret = sata_hba_init(&modlinkage)) != 0) {
411 #if AHCI_DEBUG
412 		mutex_destroy(&ahci_log_mutex);
413 #endif
414 		ddi_soft_state_fini(&ahci_statep);
415 		goto err_out;
416 	}
417 
418 	ret = mod_install(&modlinkage);
419 	if (ret != 0) {
420 		sata_hba_fini(&modlinkage);
421 #if AHCI_DEBUG
422 		mutex_destroy(&ahci_log_mutex);
423 #endif
424 		ddi_soft_state_fini(&ahci_statep);
425 		goto err_out;
426 	}
427 
428 	/* watchdog tick */
429 	ahci_watchdog_tick = drv_usectohz(
430 	    (clock_t)ahci_watchdog_timeout * 1000000);
431 	return (ret);
432 
433 err_out:
434 	cmn_err(CE_WARN, "!ahci: Module init failed");
435 	return (ret);
436 }
437 
438 /*
439  * ahci module uninitialize.
440  */
441 int
442 _fini(void)
443 {
444 	int	ret;
445 
446 	ret = mod_remove(&modlinkage);
447 	if (ret != 0) {
448 		return (ret);
449 	}
450 
451 	/* Remove the resources allocated in _init(). */
452 	sata_hba_fini(&modlinkage);
453 #if AHCI_DEBUG
454 	mutex_destroy(&ahci_log_mutex);
455 #endif
456 	ddi_soft_state_fini(&ahci_statep);
457 
458 	return (ret);
459 }
460 
461 /*
462  * _info entry point
463  */
464 int
465 _info(struct modinfo *modinfop)
466 {
467 	return (mod_info(&modlinkage, modinfop));
468 }
469 
470 /*
471  * The attach entry point for dev_ops.
472  */
473 static int
474 ahci_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
475 {
476 	ahci_ctl_t *ahci_ctlp = NULL;
477 	int instance = ddi_get_instance(dip);
478 	int status;
479 	int attach_state;
480 	uint32_t cap_status, ahci_version;
481 	int intr_types;
482 	int i;
483 	pci_regspec_t *regs;
484 	int regs_length;
485 	int rnumber;
486 #if AHCI_DEBUG
487 	int speed;
488 #endif
489 
490 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp, "ahci_attach enter",
491 	    NULL);
492 
493 	switch (cmd) {
494 	case DDI_ATTACH:
495 		break;
496 
497 	case DDI_RESUME:
498 
499 		/*
500 		 * During DDI_RESUME, the hardware state of the device
501 		 * (power may have been removed from the device) must be
502 		 * restored, allow pending requests to continue, and
503 		 * service new requests.
504 		 */
505 		ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
506 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
507 
508 		/* Restart watch thread */
509 		if (ahci_ctlp->ahcictl_timeout_id == 0)
510 			ahci_ctlp->ahcictl_timeout_id = timeout(
511 			    (void (*)(void *))ahci_watchdog_handler,
512 			    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
513 
514 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
515 
516 		/*
517 		 * Re-initialize the controller and enable the interrupts and
518 		 * restart all the ports.
519 		 *
520 		 * Note that so far we don't support hot-plug during
521 		 * suspend/resume.
522 		 */
523 		if (ahci_initialize_controller(ahci_ctlp) != AHCI_SUCCESS) {
524 			AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PM, ahci_ctlp,
525 			    "Failed to initialize the controller "
526 			    "during DDI_RESUME", NULL);
527 			return (DDI_FAILURE);
528 		}
529 
530 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
531 		ahci_ctlp->ahcictl_flags &= ~ AHCI_SUSPEND;
532 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
533 
534 		return (DDI_SUCCESS);
535 
536 	default:
537 		return (DDI_FAILURE);
538 	}
539 
540 	attach_state = AHCI_ATTACH_STATE_NONE;
541 
542 	/* Allocate soft state */
543 	status = ddi_soft_state_zalloc(ahci_statep, instance);
544 	if (status != DDI_SUCCESS) {
545 		cmn_err(CE_WARN, "!ahci%d: Cannot allocate soft state",
546 		    instance);
547 		goto err_out;
548 	}
549 
550 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
551 	ahci_ctlp->ahcictl_flags |= AHCI_ATTACH;
552 	ahci_ctlp->ahcictl_dip = dip;
553 
554 	/* Initialize the cport/port mapping */
555 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
556 		ahci_ctlp->ahcictl_port_to_cport[i] = 0xff;
557 		ahci_ctlp->ahcictl_cport_to_port[i] = 0xff;
558 	}
559 
560 	attach_state |= AHCI_ATTACH_STATE_STATEP_ALLOC;
561 
562 	/*
563 	 * Now map the AHCI base address; which includes global
564 	 * registers and port control registers
565 	 *
566 	 * According to the spec, the AHCI Base Address is BAR5,
567 	 * but BAR0-BAR4 are optional, so we need to check which
568 	 * rnumber is used for BAR5.
569 	 */
570 
571 	/*
572 	 * search through DDI "reg" property for the AHCI register set
573 	 */
574 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dip,
575 	    DDI_PROP_DONTPASS, "reg", (int **)&regs,
576 	    (uint_t *)&regs_length) != DDI_PROP_SUCCESS) {
577 		cmn_err(CE_WARN, "!ahci%d: Cannot lookup reg property",
578 		    instance);
579 		goto err_out;
580 	}
581 
582 	/* AHCI Base Address is located at 0x24 offset */
583 	for (rnumber = 0; rnumber < regs_length; ++rnumber) {
584 		if ((regs[rnumber].pci_phys_hi & PCI_REG_REG_M)
585 		    == AHCI_PCI_RNUM)
586 			break;
587 	}
588 
589 	ddi_prop_free(regs);
590 
591 	if (rnumber == regs_length) {
592 		cmn_err(CE_WARN, "!ahci%d: Cannot find AHCI register set",
593 		    instance);
594 		goto err_out;
595 	}
596 
597 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "rnumber = %d", rnumber);
598 
599 	status = ddi_regs_map_setup(dip,
600 	    rnumber,
601 	    (caddr_t *)&ahci_ctlp->ahcictl_ahci_addr,
602 	    0,
603 	    0,
604 	    &accattr,
605 	    &ahci_ctlp->ahcictl_ahci_acc_handle);
606 	if (status != DDI_SUCCESS) {
607 		cmn_err(CE_WARN, "!ahci%d: Cannot map register space",
608 		    instance);
609 		goto err_out;
610 	}
611 
612 	attach_state |= AHCI_ATTACH_STATE_REG_MAP;
613 
614 	/* Get the AHCI version information */
615 	ahci_version = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
616 	    (uint32_t *)AHCI_GLOBAL_VS(ahci_ctlp));
617 
618 	cmn_err(CE_NOTE, "!ahci%d: hba AHCI version = %x.%x", instance,
619 	    (ahci_version & 0xffff0000) >> 16,
620 	    ((ahci_version & 0x0000ff00) >> 4 |
621 	    (ahci_version & 0x000000ff)));
622 
623 	/* We don't support controllers whose versions are lower than 1.0 */
624 	if (!(ahci_version & 0xffff0000)) {
625 		cmn_err(CE_WARN, "ahci%d: Don't support AHCI HBA with lower "
626 		    "than version 1.0", instance);
627 		goto err_out;
628 	}
629 
630 	/* Get the HBA capabilities information */
631 	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
632 	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
633 
634 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba capabilites = 0x%x",
635 	    cap_status);
636 
637 #if AHCI_DEBUG
638 	/* Get the interface speed supported by the HBA */
639 	speed = (cap_status & AHCI_HBA_CAP_ISS) >> AHCI_HBA_CAP_ISS_SHIFT;
640 	if (speed == 0x01) {
641 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
642 		    "hba interface speed support: Gen 1 (1.5Gbps)", NULL);
643 	} else if (speed == 0x10) {
644 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
645 		    "hba interface speed support: Gen 2 (3 Gbps)", NULL);
646 	} else if (speed == 0x11) {
647 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
648 		    "hba interface speed support: Gen 3 (6 Gbps)", NULL);
649 	}
650 #endif
651 
652 	/* Get the number of command slots supported by the HBA */
653 	ahci_ctlp->ahcictl_num_cmd_slots =
654 	    ((cap_status & AHCI_HBA_CAP_NCS) >>
655 	    AHCI_HBA_CAP_NCS_SHIFT) + 1;
656 
657 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba number of cmd slots: %d",
658 	    ahci_ctlp->ahcictl_num_cmd_slots);
659 
660 	/* Get the bit map which indicates ports implemented by the HBA */
661 	ahci_ctlp->ahcictl_ports_implemented =
662 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
663 	    (uint32_t *)AHCI_GLOBAL_PI(ahci_ctlp));
664 
665 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba implementation of ports: 0x%x",
666 	    ahci_ctlp->ahcictl_ports_implemented);
667 
668 	/*
669 	 * According to the AHCI spec, CAP.NP should indicate the maximum
670 	 * number of ports supported by the HBA silicon, but we found
671 	 * this value of ICH8 chipset only indicates the number of ports
672 	 * implemented (exposed) by it. Therefore, the driver should calculate
673 	 * the potential maximum value by checking PI register, and use
674 	 * the maximum of this value and CAP.NP.
675 	 */
676 	ahci_ctlp->ahcictl_num_ports = max(
677 	    (cap_status & AHCI_HBA_CAP_NP) + 1,
678 	    ddi_fls(ahci_ctlp->ahcictl_ports_implemented));
679 
680 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba number of ports: %d",
681 	    ahci_ctlp->ahcictl_num_ports);
682 
683 	/* Get the number of implemented ports by the HBA */
684 	ahci_ctlp->ahcictl_num_implemented_ports =
685 	    ahci_get_num_implemented_ports(
686 	    ahci_ctlp->ahcictl_ports_implemented);
687 
688 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
689 	    "hba number of implemented ports: %d",
690 	    ahci_ctlp->ahcictl_num_implemented_ports);
691 
692 	/* Check whether HBA supports 64bit DMA addressing */
693 	if (!(cap_status & AHCI_HBA_CAP_S64A)) {
694 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_BUF_32BIT_DMA;
695 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
696 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
697 		    "hba does not support 64-bit addressing", NULL);
698 	}
699 
700 	/* Checking for the support of Port Multiplier */
701 	if (cap_status & AHCI_HBA_CAP_SPM) {
702 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_PMULT_CBSS;
703 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_PMULT, ahci_ctlp,
704 		    "hba supports port multiplier (CBSS)", NULL);
705 
706 		/* Support FIS-based switching ? */
707 		if (cap_status & AHCI_HBA_CAP_FBSS) {
708 			ahci_ctlp->ahcictl_cap |= AHCI_CAP_PMULT_FBSS;
709 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_PMULT, ahci_ctlp,
710 			    "hba supports FIS-based switching (FBSS)", NULL);
711 		}
712 	}
713 
714 	/* Checking for Support Command List Override */
715 	if (cap_status & AHCI_HBA_CAP_SCLO) {
716 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_SCLO;
717 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_PMULT, ahci_ctlp,
718 		    "hba supports command list override.", NULL);
719 	}
720 
721 	/* Checking for Asynchronous Notification */
722 	if (cap_status & AHCI_HBA_CAP_SSNTF) {
723 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_SNTF;
724 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_PMULT, ahci_ctlp,
725 		    "hba supports asynchronous notification.", NULL);
726 	}
727 
728 	if (pci_config_setup(dip, &ahci_ctlp->ahcictl_pci_conf_handle)
729 	    != DDI_SUCCESS) {
730 		cmn_err(CE_WARN, "!ahci%d: Cannot set up pci configure space",
731 		    instance);
732 		goto err_out;
733 	}
734 
735 	attach_state |= AHCI_ATTACH_STATE_PCICFG_SETUP;
736 
737 	/*
738 	 * Check the pci configuration space, and set caps. We also
739 	 * handle the hardware defect in this function.
740 	 *
741 	 * For example, force ATI SB600 to use 32-bit dma addressing
742 	 * since it doesn't support 64-bit dma though its CAP register
743 	 * declares it support.
744 	 */
745 	if (ahci_config_space_init(ahci_ctlp) == AHCI_FAILURE) {
746 		cmn_err(CE_WARN, "!ahci%d: ahci_config_space_init failed",
747 		    instance);
748 		goto err_out;
749 	}
750 
751 	/*
752 	 * Disable the whole controller interrupts before adding
753 	 * interrupt handlers(s).
754 	 */
755 	ahci_disable_all_intrs(ahci_ctlp);
756 
757 	/* Get supported interrupt types */
758 	if (ddi_intr_get_supported_types(dip, &intr_types) != DDI_SUCCESS) {
759 		cmn_err(CE_WARN, "!ahci%d: ddi_intr_get_supported_types failed",
760 		    instance);
761 		goto err_out;
762 	}
763 
764 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
765 	    "ddi_intr_get_supported_types() returned: 0x%x",
766 	    intr_types);
767 
768 	if (ahci_msi_enabled && (intr_types & DDI_INTR_TYPE_MSI)) {
769 		/*
770 		 * Try MSI first, but fall back to FIXED if failed
771 		 */
772 		if (ahci_add_intrs(ahci_ctlp, DDI_INTR_TYPE_MSI) ==
773 		    DDI_SUCCESS) {
774 			ahci_ctlp->ahcictl_intr_type = DDI_INTR_TYPE_MSI;
775 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
776 			    "Using MSI interrupt type", NULL);
777 			goto intr_done;
778 		}
779 
780 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
781 		    "MSI registration failed, "
782 		    "trying FIXED interrupts", NULL);
783 	}
784 
785 	if (intr_types & DDI_INTR_TYPE_FIXED) {
786 		if (ahci_add_intrs(ahci_ctlp, DDI_INTR_TYPE_FIXED) ==
787 		    DDI_SUCCESS) {
788 			ahci_ctlp->ahcictl_intr_type = DDI_INTR_TYPE_FIXED;
789 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
790 			    "Using FIXED interrupt type", NULL);
791 			goto intr_done;
792 		}
793 
794 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
795 		    "FIXED interrupt registration failed", NULL);
796 	}
797 
798 	cmn_err(CE_WARN, "!ahci%d: Interrupt registration failed", instance);
799 
800 	goto err_out;
801 
802 intr_done:
803 
804 	attach_state |= AHCI_ATTACH_STATE_INTR_ADDED;
805 
806 	/* Initialize the controller mutex */
807 	mutex_init(&ahci_ctlp->ahcictl_mutex, NULL, MUTEX_DRIVER,
808 	    (void *)(uintptr_t)ahci_ctlp->ahcictl_intr_pri);
809 
810 	attach_state |= AHCI_ATTACH_STATE_MUTEX_INIT;
811 
812 	if (ahci_dma_prdt_number < AHCI_MIN_PRDT_NUMBER) {
813 		ahci_dma_prdt_number = AHCI_MIN_PRDT_NUMBER;
814 	} else if (ahci_dma_prdt_number > AHCI_MAX_PRDT_NUMBER) {
815 		ahci_dma_prdt_number = AHCI_MAX_PRDT_NUMBER;
816 	}
817 
818 	ahci_cmd_table_size = (sizeof (ahci_cmd_table_t) +
819 	    (ahci_dma_prdt_number - AHCI_PRDT_NUMBER) *
820 	    sizeof (ahci_prdt_item_t));
821 
822 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
823 	    "ahci_attach: ahci_dma_prdt_number set by user is 0x%x,"
824 	    " ahci_cmd_table_size is 0x%x",
825 	    ahci_dma_prdt_number, ahci_cmd_table_size);
826 
827 	if (ahci_dma_prdt_number != AHCI_PRDT_NUMBER)
828 		ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_sgllen =
829 		    ahci_dma_prdt_number;
830 
831 	ahci_ctlp->ahcictl_buffer_dma_attr = buffer_dma_attr;
832 	ahci_ctlp->ahcictl_rcvd_fis_dma_attr = rcvd_fis_dma_attr;
833 	ahci_ctlp->ahcictl_cmd_list_dma_attr = cmd_list_dma_attr;
834 	ahci_ctlp->ahcictl_cmd_table_dma_attr = cmd_table_dma_attr;
835 
836 	if ((ahci_buf_64bit_dma == B_FALSE) ||
837 	    (ahci_ctlp->ahcictl_cap & AHCI_CAP_BUF_32BIT_DMA)) {
838 		ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_addr_hi =
839 		    0xffffffffull;
840 	}
841 
842 	if ((ahci_commu_64bit_dma == B_FALSE) ||
843 	    (ahci_ctlp->ahcictl_cap & AHCI_CAP_COMMU_32BIT_DMA)) {
844 		ahci_ctlp->ahcictl_rcvd_fis_dma_attr.dma_attr_addr_hi =
845 		    0xffffffffull;
846 		ahci_ctlp->ahcictl_cmd_list_dma_attr.dma_attr_addr_hi =
847 		    0xffffffffull;
848 		ahci_ctlp->ahcictl_cmd_table_dma_attr.dma_attr_addr_hi =
849 		    0xffffffffull;
850 	}
851 
852 	/* Allocate the ports structure */
853 	status = ahci_alloc_ports_state(ahci_ctlp);
854 	if (status != AHCI_SUCCESS) {
855 		cmn_err(CE_WARN, "!ahci%d: Cannot allocate ports structure",
856 		    instance);
857 		goto err_out;
858 	}
859 
860 	attach_state |= AHCI_ATTACH_STATE_PORT_ALLOC;
861 
862 	/*
863 	 * Initialize the controller and ports.
864 	 */
865 	status = ahci_initialize_controller(ahci_ctlp);
866 	if (status != AHCI_SUCCESS) {
867 		cmn_err(CE_WARN, "!ahci%d: HBA initialization failed",
868 		    instance);
869 		goto err_out;
870 	}
871 
872 	attach_state |= AHCI_ATTACH_STATE_HW_INIT;
873 
874 	/* Start one thread to check packet timeouts */
875 	ahci_ctlp->ahcictl_timeout_id = timeout(
876 	    (void (*)(void *))ahci_watchdog_handler,
877 	    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
878 
879 	attach_state |= AHCI_ATTACH_STATE_TIMEOUT_ENABLED;
880 
881 	if (ahci_register_sata_hba_tran(ahci_ctlp, cap_status)) {
882 		cmn_err(CE_WARN, "!ahci%d: sata hba tran registration failed",
883 		    instance);
884 		goto err_out;
885 	}
886 
887 	ahci_ctlp->ahcictl_flags &= ~AHCI_ATTACH;
888 
889 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "ahci_attach success!", NULL);
890 
891 	return (DDI_SUCCESS);
892 
893 err_out:
894 	if (attach_state & AHCI_ATTACH_STATE_TIMEOUT_ENABLED) {
895 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
896 		(void) untimeout(ahci_ctlp->ahcictl_timeout_id);
897 		ahci_ctlp->ahcictl_timeout_id = 0;
898 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
899 	}
900 
901 	if (attach_state & AHCI_ATTACH_STATE_HW_INIT) {
902 		ahci_uninitialize_controller(ahci_ctlp);
903 	}
904 
905 	if (attach_state & AHCI_ATTACH_STATE_PORT_ALLOC) {
906 		ahci_dealloc_ports_state(ahci_ctlp);
907 	}
908 
909 	if (attach_state & AHCI_ATTACH_STATE_MUTEX_INIT) {
910 		mutex_destroy(&ahci_ctlp->ahcictl_mutex);
911 	}
912 
913 	if (attach_state & AHCI_ATTACH_STATE_INTR_ADDED) {
914 		ahci_rem_intrs(ahci_ctlp);
915 	}
916 
917 	if (attach_state & AHCI_ATTACH_STATE_PCICFG_SETUP) {
918 		pci_config_teardown(&ahci_ctlp->ahcictl_pci_conf_handle);
919 	}
920 
921 	if (attach_state & AHCI_ATTACH_STATE_REG_MAP) {
922 		ddi_regs_map_free(&ahci_ctlp->ahcictl_ahci_acc_handle);
923 	}
924 
925 	if (attach_state & AHCI_ATTACH_STATE_STATEP_ALLOC) {
926 		ddi_soft_state_free(ahci_statep, instance);
927 	}
928 
929 	return (DDI_FAILURE);
930 }
931 
932 /*
933  * The detach entry point for dev_ops.
934  */
935 static int
936 ahci_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
937 {
938 	ahci_ctl_t *ahci_ctlp;
939 	int instance;
940 	int ret;
941 
942 	instance = ddi_get_instance(dip);
943 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
944 
945 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_detach enter", NULL);
946 
947 	switch (cmd) {
948 	case DDI_DETACH:
949 
950 		/* disable the interrupts for an uninterrupted detach */
951 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
952 		ahci_disable_all_intrs(ahci_ctlp);
953 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
954 
955 		/* unregister from the sata framework. */
956 		ret = ahci_unregister_sata_hba_tran(ahci_ctlp);
957 		if (ret != AHCI_SUCCESS) {
958 			mutex_enter(&ahci_ctlp->ahcictl_mutex);
959 			ahci_enable_all_intrs(ahci_ctlp);
960 			mutex_exit(&ahci_ctlp->ahcictl_mutex);
961 			return (DDI_FAILURE);
962 		}
963 
964 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
965 
966 		/* stop the watchdog handler */
967 		(void) untimeout(ahci_ctlp->ahcictl_timeout_id);
968 		ahci_ctlp->ahcictl_timeout_id = 0;
969 
970 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
971 
972 		/* uninitialize the controller */
973 		ahci_uninitialize_controller(ahci_ctlp);
974 
975 		/* remove the interrupts */
976 		ahci_rem_intrs(ahci_ctlp);
977 
978 		/* deallocate the ports structures */
979 		ahci_dealloc_ports_state(ahci_ctlp);
980 
981 		/* destroy mutex */
982 		mutex_destroy(&ahci_ctlp->ahcictl_mutex);
983 
984 		/* teardown the pci config */
985 		pci_config_teardown(&ahci_ctlp->ahcictl_pci_conf_handle);
986 
987 		/* remove the reg maps. */
988 		ddi_regs_map_free(&ahci_ctlp->ahcictl_ahci_acc_handle);
989 
990 		/* free the soft state. */
991 		ddi_soft_state_free(ahci_statep, instance);
992 
993 		return (DDI_SUCCESS);
994 
995 	case DDI_SUSPEND:
996 
997 		/*
998 		 * The steps associated with suspension must include putting
999 		 * the underlying device into a quiescent state so that it
1000 		 * will not generate interrupts or modify or access memory.
1001 		 */
1002 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
1003 		if (ahci_ctlp->ahcictl_flags & AHCI_SUSPEND) {
1004 			mutex_exit(&ahci_ctlp->ahcictl_mutex);
1005 			return (DDI_SUCCESS);
1006 		}
1007 
1008 		ahci_ctlp->ahcictl_flags |= AHCI_SUSPEND;
1009 
1010 		/* stop the watchdog handler */
1011 		if (ahci_ctlp->ahcictl_timeout_id) {
1012 			(void) untimeout(ahci_ctlp->ahcictl_timeout_id);
1013 			ahci_ctlp->ahcictl_timeout_id = 0;
1014 		}
1015 
1016 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
1017 
1018 		/*
1019 		 * drain the taskq
1020 		 */
1021 		ahci_drain_ports_taskq(ahci_ctlp);
1022 
1023 		/*
1024 		 * Disable the interrupts and stop all the ports.
1025 		 */
1026 		ahci_uninitialize_controller(ahci_ctlp);
1027 
1028 		return (DDI_SUCCESS);
1029 
1030 	default:
1031 		return (DDI_FAILURE);
1032 	}
1033 }
1034 
1035 /*
1036  * The info entry point for dev_ops.
1037  *
1038  */
1039 static int
1040 ahci_getinfo(dev_info_t *dip, ddi_info_cmd_t infocmd,
1041 		    void *arg, void **result)
1042 {
1043 #ifndef __lock_lint
1044 	_NOTE(ARGUNUSED(dip))
1045 #endif /* __lock_lint */
1046 
1047 	ahci_ctl_t *ahci_ctlp;
1048 	int instance;
1049 	dev_t dev;
1050 
1051 	dev = (dev_t)arg;
1052 	instance = getminor(dev);
1053 
1054 	switch (infocmd) {
1055 		case DDI_INFO_DEVT2DEVINFO:
1056 			ahci_ctlp = ddi_get_soft_state(ahci_statep,  instance);
1057 			if (ahci_ctlp != NULL) {
1058 				*result = ahci_ctlp->ahcictl_dip;
1059 				return (DDI_SUCCESS);
1060 			} else {
1061 				*result = NULL;
1062 				return (DDI_FAILURE);
1063 			}
1064 		case DDI_INFO_DEVT2INSTANCE:
1065 			*(int *)result = instance;
1066 			break;
1067 		default:
1068 			break;
1069 	}
1070 
1071 	return (DDI_SUCCESS);
1072 }
1073 
1074 /*
1075  * Registers the ahci with sata framework.
1076  */
1077 static int
1078 ahci_register_sata_hba_tran(ahci_ctl_t *ahci_ctlp, uint32_t cap_status)
1079 {
1080 	struct 	sata_hba_tran	*sata_hba_tran;
1081 
1082 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
1083 	    "ahci_register_sata_hba_tran enter", NULL);
1084 
1085 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
1086 
1087 	/* Allocate memory for the sata_hba_tran  */
1088 	sata_hba_tran = kmem_zalloc(sizeof (sata_hba_tran_t), KM_SLEEP);
1089 
1090 	sata_hba_tran->sata_tran_hba_rev = SATA_TRAN_HBA_REV_3;
1091 	sata_hba_tran->sata_tran_hba_dip = ahci_ctlp->ahcictl_dip;
1092 	sata_hba_tran->sata_tran_hba_dma_attr =
1093 	    &ahci_ctlp->ahcictl_buffer_dma_attr;
1094 
1095 	/* Report the number of implemented ports */
1096 	sata_hba_tran->sata_tran_hba_num_cports =
1097 	    ahci_ctlp->ahcictl_num_implemented_ports;
1098 
1099 	/* Support ATAPI device */
1100 	sata_hba_tran->sata_tran_hba_features_support = SATA_CTLF_ATAPI;
1101 
1102 	/* Get the data transfer capability for PIO command by the HBA */
1103 	if (cap_status & AHCI_HBA_CAP_PMD) {
1104 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_PIO_MDRQ;
1105 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "HBA supports multiple "
1106 		    "DRQ block data transfer for PIO command protocol", NULL);
1107 	}
1108 
1109 	/*
1110 	 * According to the AHCI spec, the ATA/ATAPI-7 queued feature set
1111 	 * is not supported by AHCI (including the READ QUEUED (EXT), WRITE
1112 	 * QUEUED (EXT), and SERVICE commands). Queued operations are
1113 	 * supported in AHCI using the READ FPDMA QUEUED and WRITE FPDMA
1114 	 * QUEUED commands when the HBA and device support native command
1115 	 * queuing(NCQ).
1116 	 *
1117 	 * SATA_CTLF_NCQ will be set to sata_tran_hba_features_support if the
1118 	 * CAP register of the HBA indicates NCQ is supported.
1119 	 *
1120 	 * SATA_CTLF_NCQ cannot be set if AHCI_CAP_NO_MCMDLIST_NONQUEUE is
1121 	 * set because the previous register content of PxCI can be re-written
1122 	 * in the register write.
1123 	 */
1124 	if ((cap_status & AHCI_HBA_CAP_SNCQ) &&
1125 	    !(ahci_ctlp->ahcictl_cap & AHCI_CAP_NO_MCMDLIST_NONQUEUE)) {
1126 		sata_hba_tran->sata_tran_hba_features_support |= SATA_CTLF_NCQ;
1127 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_NCQ;
1128 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "HBA supports Native "
1129 		    "Command Queuing", NULL);
1130 	}
1131 
1132 	/* Support port multiplier? */
1133 	if (cap_status & AHCI_HBA_CAP_SPM) {
1134 		sata_hba_tran->sata_tran_hba_features_support |=
1135 		    SATA_CTLF_PORT_MULTIPLIER;
1136 
1137 		/* Support FIS-based switching for port multiplier? */
1138 		if (cap_status & AHCI_HBA_CAP_FBSS) {
1139 			sata_hba_tran->sata_tran_hba_features_support |=
1140 			    SATA_CTLF_PMULT_FBS;
1141 		}
1142 	}
1143 
1144 	/* Report the number of command slots */
1145 	sata_hba_tran->sata_tran_hba_qdepth = ahci_ctlp->ahcictl_num_cmd_slots;
1146 
1147 	sata_hba_tran->sata_tran_probe_port = ahci_tran_probe_port;
1148 	sata_hba_tran->sata_tran_start = ahci_tran_start;
1149 	sata_hba_tran->sata_tran_abort = ahci_tran_abort;
1150 	sata_hba_tran->sata_tran_reset_dport = ahci_tran_reset_dport;
1151 	sata_hba_tran->sata_tran_hotplug_ops = &ahci_tran_hotplug_ops;
1152 #ifdef __lock_lint
1153 	sata_hba_tran->sata_tran_selftest = ahci_selftest;
1154 #endif
1155 	/*
1156 	 * When SATA framework adds support for pwrmgt the
1157 	 * pwrmgt_ops needs to be updated
1158 	 */
1159 	sata_hba_tran->sata_tran_pwrmgt_ops = NULL;
1160 	sata_hba_tran->sata_tran_ioctl = NULL;
1161 
1162 	ahci_ctlp->ahcictl_sata_hba_tran = sata_hba_tran;
1163 
1164 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
1165 
1166 	/* Attach it to SATA framework */
1167 	if (sata_hba_attach(ahci_ctlp->ahcictl_dip, sata_hba_tran, DDI_ATTACH)
1168 	    != DDI_SUCCESS) {
1169 		kmem_free((void *)sata_hba_tran, sizeof (sata_hba_tran_t));
1170 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
1171 		ahci_ctlp->ahcictl_sata_hba_tran = NULL;
1172 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
1173 		return (AHCI_FAILURE);
1174 	}
1175 
1176 	return (AHCI_SUCCESS);
1177 }
1178 
1179 /*
1180  * Unregisters the ahci with sata framework.
1181  */
1182 static int
1183 ahci_unregister_sata_hba_tran(ahci_ctl_t *ahci_ctlp)
1184 {
1185 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1186 	    "ahci_unregister_sata_hba_tran enter", NULL);
1187 
1188 	/* Detach from the SATA framework. */
1189 	if (sata_hba_detach(ahci_ctlp->ahcictl_dip, DDI_DETACH) !=
1190 	    DDI_SUCCESS) {
1191 		return (AHCI_FAILURE);
1192 	}
1193 
1194 	/* Deallocate sata_hba_tran. */
1195 	kmem_free((void *)ahci_ctlp->ahcictl_sata_hba_tran,
1196 	    sizeof (sata_hba_tran_t));
1197 
1198 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
1199 	ahci_ctlp->ahcictl_sata_hba_tran = NULL;
1200 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
1201 
1202 	return (AHCI_SUCCESS);
1203 }
1204 
1205 #define	SET_PORTSTR(str, addrp)						\
1206 	if (AHCI_ADDR_IS_PORT(addrp))					\
1207 		(void) sprintf((str), "%d", (addrp)->aa_port);		\
1208 	else if (AHCI_ADDR_IS_PMULT(addrp))				\
1209 		(void) sprintf((str), "%d (pmult)", (addrp)->aa_port);	\
1210 	else								\
1211 		(void) sprintf((str), "%d:%d", (addrp)->aa_port,	\
1212 		    (addrp)->aa_pmport);
1213 
1214 /*
1215  * ahci_tran_probe_port is called by SATA framework. It returns port state,
1216  * port status registers and an attached device type via sata_device
1217  * structure.
1218  *
1219  * We return the cached information from a previous hardware probe. The
1220  * actual hardware probing itself was done either from within
1221  * ahci_initialize_controller() during the driver attach or from a phy
1222  * ready change interrupt handler.
1223  */
1224 static int
1225 ahci_tran_probe_port(dev_info_t *dip, sata_device_t *sd)
1226 {
1227 	ahci_ctl_t *ahci_ctlp;
1228 	ahci_port_t *ahci_portp;
1229 	ahci_addr_t addr, pmult_addr;
1230 	uint8_t cport = sd->satadev_addr.cport;
1231 	char portstr[10];
1232 	uint8_t device_type;
1233 	uint32_t port_state;
1234 	uint8_t port;
1235 	int rval = SATA_SUCCESS, rval_init;
1236 
1237 	ahci_ctlp = ddi_get_soft_state(ahci_statep, ddi_get_instance(dip));
1238 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
1239 
1240 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
1241 
1242 	mutex_enter(&ahci_portp->ahciport_mutex);
1243 
1244 	ahci_get_ahci_addr(ahci_ctlp, sd, &addr);
1245 	ASSERT(AHCI_ADDR_IS_VALID(&addr));
1246 	SET_PORTSTR(portstr, &addr);
1247 
1248 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1249 	    "ahci_tran_probe_port enter: port %s", portstr);
1250 
1251 	if ((AHCI_ADDR_IS_PMULT(&addr) || AHCI_ADDR_IS_PMPORT(&addr)) &&
1252 	    (ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT ||
1253 	    ahci_portp->ahciport_pmult_info == NULL)) {
1254 		/* port mutliplier is removed. */
1255 		AHCIDBG(AHCIDBG_PMULT, ahci_ctlp,
1256 		    "ahci_tran_probe_port: "
1257 		    "port-pmult is removed from port %s", portstr);
1258 		mutex_exit(&ahci_portp->ahciport_mutex);
1259 		return (SATA_FAILURE);
1260 	}
1261 
1262 	/*
1263 	 * The sata_device may refer to
1264 	 * 1. A controller port.
1265 	 *    A controller port should be ready here.
1266 	 * 2. A port multiplier.
1267 	 *    If it has not been initialized, initialized it. If it is
1268 	 *    initilaized, we need check the status of all its device ports.
1269 	 * 3. A port multiplier port.
1270 	 *    If it has not been initialized, initialized it.
1271 	 *
1272 	 * A port multiplier or a port multiplier port may require some
1273 	 * initialization because we cannot do these time-consuming jobs in an
1274 	 * interrupt context.
1275 	 */
1276 	if (AHCI_ADDR_IS_PORT(&addr)) {
1277 		if (ahci_portp->ahciport_device_type == SATA_DTYPE_PMULT) {
1278 			AHCI_ADDR_SET_PMULT(&pmult_addr, port);
1279 			port_state = ahci_portp->ahciport_port_state;
1280 			/* SATA Framework's first probe? */
1281 			if (!(port_state & SATA_DSTATE_PMULT_INIT)) {
1282 				/* Initialize registers on a port multiplier */
1283 				rval_init = ahci_initialize_pmult(ahci_ctlp,
1284 				    ahci_portp, &pmult_addr, sd);
1285 				if (rval_init != AHCI_SUCCESS) {
1286 					AHCIDBG(AHCIDBG_PMULT, ahci_ctlp,
1287 					    "ahci_tran_probe_port: "
1288 					    "pmult initialization failed.",
1289 					    NULL);
1290 					mutex_exit(&ahci_portp->ahciport_mutex);
1291 					return (SATA_FAILURE);
1292 				}
1293 			}
1294 		}
1295 	} else if (AHCI_ADDR_IS_PMULT(&addr)) {
1296 		/* Check pmports hotplug events */
1297 		(void) ahci_probe_pmult(ahci_ctlp, ahci_portp, &addr);
1298 	} else if (AHCI_ADDR_IS_PMPORT(&addr)) {
1299 		if (ahci_probe_pmport(ahci_ctlp, ahci_portp,
1300 		    &addr, sd) != AHCI_SUCCESS) {
1301 			rval = SATA_FAILURE;
1302 			goto out;
1303 		}
1304 	}
1305 
1306 	/* Update port state and device type */
1307 	port_state = AHCIPORT_GET_STATE(ahci_portp, &addr);
1308 
1309 	switch (port_state) {
1310 
1311 	case SATA_PSTATE_FAILED:
1312 		sd->satadev_state = SATA_PSTATE_FAILED;
1313 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1314 		    "ahci_tran_probe_port: port %s PORT FAILED", portstr);
1315 		goto out;
1316 
1317 	case SATA_PSTATE_SHUTDOWN:
1318 		sd->satadev_state = SATA_PSTATE_SHUTDOWN;
1319 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1320 		    "ahci_tran_probe_port: port %s PORT SHUTDOWN", portstr);
1321 		goto out;
1322 
1323 	case SATA_PSTATE_PWROFF:
1324 		sd->satadev_state = SATA_PSTATE_PWROFF;
1325 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1326 		    "ahci_tran_probe_port: port %s PORT PWROFF", portstr);
1327 		goto out;
1328 
1329 	case SATA_PSTATE_PWRON:
1330 		sd->satadev_state = SATA_PSTATE_PWRON;
1331 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1332 		    "ahci_tran_probe_port: port %s PORT PWRON", portstr);
1333 		break;
1334 
1335 	default:
1336 		sd->satadev_state = port_state;
1337 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1338 		    "ahci_tran_probe_port: port %s PORT NORMAL %x",
1339 		    portstr, port_state);
1340 		break;
1341 	}
1342 
1343 	device_type = AHCIPORT_GET_DEV_TYPE(ahci_portp, &addr);
1344 
1345 	switch (device_type) {
1346 
1347 	case SATA_DTYPE_ATADISK:
1348 		sd->satadev_type = SATA_DTYPE_ATADISK;
1349 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1350 		    "ahci_tran_probe_port: port %s DISK found", portstr);
1351 		break;
1352 
1353 	case SATA_DTYPE_ATAPI:
1354 		/*
1355 		 * HBA driver only knows it's an ATAPI device, and don't know
1356 		 * it's CD/DVD, tape or ATAPI disk because the ATAPI device
1357 		 * type need to be determined by checking IDENTIFY PACKET
1358 		 * DEVICE data
1359 		 */
1360 		sd->satadev_type = SATA_DTYPE_ATAPI;
1361 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1362 		    "ahci_tran_probe_port: port %s ATAPI found", portstr);
1363 		break;
1364 
1365 	case SATA_DTYPE_PMULT:
1366 		ASSERT(AHCI_ADDR_IS_PORT(&addr)||AHCI_ADDR_IS_PMULT(&addr));
1367 		sd->satadev_type = SATA_DTYPE_PMULT;
1368 
1369 		/* Update the number of pmports. */
1370 		ASSERT(ahci_portp->ahciport_pmult_info != NULL);
1371 		sd->satadev_add_info = ahci_portp->
1372 		    ahciport_pmult_info->ahcipmi_num_dev_ports;
1373 
1374 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1375 		    "ahci_tran_probe_port: port %s Port Multiplier found",
1376 		    portstr);
1377 		break;
1378 
1379 	case SATA_DTYPE_UNKNOWN:
1380 		sd->satadev_type = SATA_DTYPE_UNKNOWN;
1381 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1382 		    "ahci_tran_probe_port: port %s Unknown device found",
1383 		    portstr);
1384 		break;
1385 
1386 	default:
1387 		/* we don't support any other device types */
1388 		sd->satadev_type = SATA_DTYPE_NONE;
1389 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1390 		    "ahci_tran_probe_port: port %s No device found", portstr);
1391 		break;
1392 	}
1393 
1394 out:
1395 	/* Register update only fails while probing a pmult/pmport */
1396 	if (AHCI_ADDR_IS_PORT(&addr)) {
1397 		ahci_update_sata_registers(ahci_ctlp, port, sd);
1398 		if (ahci_portp->ahciport_device_type == SATA_DTYPE_PMULT)
1399 			if (port_state & SATA_STATE_READY)
1400 				if (ahci_update_pmult_gscr(ahci_ctlp,
1401 				    &pmult_addr, sd) != AHCI_SUCCESS)
1402 					rval = SATA_FAILURE;
1403 	} else if (AHCI_ADDR_IS_PMULT(&addr)) {
1404 		ahci_update_sata_registers(ahci_ctlp, port, sd);
1405 		if (port_state & SATA_STATE_READY)
1406 			if (ahci_update_pmult_gscr(ahci_ctlp,
1407 			    &addr, sd) != AHCI_SUCCESS)
1408 				rval = SATA_FAILURE;
1409 	} else if (AHCI_ADDR_IS_PMPORT(&addr)) {
1410 		if (port_state & SATA_STATE_READY)
1411 			if (ahci_update_pmult_pscr(ahci_ctlp,
1412 			    &addr, sd) != AHCI_SUCCESS)
1413 				rval = SATA_FAILURE;
1414 	}
1415 
1416 	mutex_exit(&ahci_portp->ahciport_mutex);
1417 	return (rval);
1418 }
1419 
1420 /*
1421  * There are four operation modes in sata framework:
1422  * SATA_OPMODE_INTERRUPTS
1423  * SATA_OPMODE_POLLING
1424  * SATA_OPMODE_ASYNCH
1425  * SATA_OPMODE_SYNCH
1426  *
1427  * Their combined meanings as following:
1428  *
1429  * SATA_OPMODE_SYNCH
1430  * The command has to be completed before sata_tran_start functions returns.
1431  * Either interrupts or polling could be used - it's up to the driver.
1432  * Mode used currently for internal, sata-module initiated operations.
1433  *
1434  * SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS
1435  * It is the same as the one above.
1436  *
1437  * SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING
1438  * The command has to be completed before sata_tran_start function returns.
1439  * No interrupt used, polling only. This should be the mode used for scsi
1440  * packets with FLAG_NOINTR.
1441  *
1442  * SATA_OPMODE_ASYNCH | SATA_OPMODE_INTERRUPTS
1443  * The command may be queued (callback function specified). Interrupts could
1444  * be used. It's normal operation mode.
1445  */
1446 /*
1447  * Called by sata framework to transport a sata packet down stream.
1448  */
1449 static int
1450 ahci_tran_start(dev_info_t *dip, sata_pkt_t *spkt)
1451 {
1452 	ahci_ctl_t *ahci_ctlp;
1453 	ahci_port_t *ahci_portp;
1454 	ahci_addr_t addr, addr_pmult;
1455 	sata_device_t sdevice;
1456 	uint8_t	cport = spkt->satapkt_device.satadev_addr.cport;
1457 	uint8_t port;
1458 	char portstr[10];
1459 
1460 	ahci_ctlp = ddi_get_soft_state(ahci_statep, ddi_get_instance(dip));
1461 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
1462 
1463 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1464 	    "ahci_tran_start enter: cport %d satapkt 0x%p",
1465 	    cport, (void *)spkt);
1466 
1467 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
1468 
1469 	mutex_enter(&ahci_portp->ahciport_mutex);
1470 	ahci_get_ahci_addr(ahci_ctlp, &spkt->satapkt_device, &addr);
1471 	SET_PORTSTR(portstr, &addr);
1472 
1473 	/* Sanity check */
1474 	if (AHCI_ADDR_IS_PMPORT(&addr)) {
1475 		if (ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT ||
1476 		    ahci_portp->ahciport_pmult_info == NULL) {
1477 
1478 			spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1479 			spkt->satapkt_device.satadev_type = SATA_DTYPE_NONE;
1480 			spkt->satapkt_device.satadev_state = SATA_STATE_UNKNOWN;
1481 			ahci_update_sata_registers(ahci_ctlp, port,
1482 			    &spkt->satapkt_device);
1483 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1484 			    "ahci_tran_start returning PORT_ERROR while "
1485 			    "pmult removed: port: %s", portstr);
1486 			mutex_exit(&ahci_portp->ahciport_mutex);
1487 			return (SATA_TRAN_PORT_ERROR);
1488 		}
1489 
1490 		/* Port multiplier and pmport are correctly initialized? */
1491 		if (!(ahci_portp->ahciport_port_state &
1492 		    SATA_DSTATE_PMULT_INIT)) {
1493 			AHCI_ADDR_SET_PMULT(&addr_pmult, port);
1494 			if (!ddi_in_panic() ||
1495 			    ahci_initialize_pmult(ahci_ctlp, ahci_portp,
1496 			    &addr_pmult, &sdevice) != AHCI_SUCCESS) {
1497 				spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1498 				spkt->satapkt_device.satadev_type =
1499 				    AHCIPORT_GET_DEV_TYPE(ahci_portp, &addr);
1500 				spkt->satapkt_device.satadev_state =
1501 				    AHCIPORT_GET_STATE(ahci_portp, &addr);
1502 				ahci_update_sata_registers(ahci_ctlp, port,
1503 				    &spkt->satapkt_device);
1504 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1505 				    "ahci_tran_start returning PORT_ERROR "
1506 				    "while pmult is not initialized "
1507 				    "at port %d", port);
1508 				mutex_exit(&ahci_portp->ahciport_mutex);
1509 				return (SATA_TRAN_PORT_ERROR);
1510 			}
1511 		}
1512 		if (!(AHCIPORT_GET_STATE(ahci_portp, &addr) &
1513 		    SATA_STATE_READY)) {
1514 			if (!ddi_in_panic() ||
1515 			    ahci_initialize_pmport(ahci_ctlp,
1516 			    ahci_portp, &addr) != AHCI_SUCCESS) {
1517 				spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1518 				spkt->satapkt_device.satadev_type =
1519 				    AHCIPORT_GET_DEV_TYPE(ahci_portp, &addr);
1520 				spkt->satapkt_device.satadev_state =
1521 				    AHCIPORT_GET_STATE(ahci_portp, &addr);
1522 				ahci_update_sata_registers(ahci_ctlp, port,
1523 				    &spkt->satapkt_device);
1524 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1525 				    "ahci_tran_start returning PORT_ERROR "
1526 				    "while sub-link is not initialized "
1527 				    "at port: %s", portstr);
1528 				mutex_exit(&ahci_portp->ahciport_mutex);
1529 				return (SATA_TRAN_PORT_ERROR);
1530 			}
1531 		}
1532 	}
1533 
1534 	if (AHCIPORT_GET_STATE(ahci_portp, &addr) & SATA_PSTATE_FAILED ||
1535 	    AHCIPORT_GET_STATE(ahci_portp, &addr) & SATA_PSTATE_SHUTDOWN||
1536 	    AHCIPORT_GET_STATE(ahci_portp, &addr) & SATA_PSTATE_PWROFF) {
1537 		/*
1538 		 * In case the target driver would send the packet before
1539 		 * sata framework can have the opportunity to process those
1540 		 * event reports.
1541 		 */
1542 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1543 		spkt->satapkt_device.satadev_state =
1544 		    ahci_portp->ahciport_port_state;
1545 		ahci_update_sata_registers(ahci_ctlp, port,
1546 		    &spkt->satapkt_device);
1547 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1548 		    "ahci_tran_start returning PORT_ERROR while "
1549 		    "port in FAILED/SHUTDOWN/PWROFF state: "
1550 		    "port: %s", portstr);
1551 		mutex_exit(&ahci_portp->ahciport_mutex);
1552 		return (SATA_TRAN_PORT_ERROR);
1553 	}
1554 
1555 	if (AHCIPORT_GET_DEV_TYPE(ahci_portp, &addr) == SATA_DTYPE_NONE) {
1556 		/*
1557 		 * ahci_intr_phyrdy_change() may have rendered it to
1558 		 * SATA_DTYPE_NONE.
1559 		 */
1560 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1561 		spkt->satapkt_device.satadev_type = SATA_DTYPE_NONE;
1562 		spkt->satapkt_device.satadev_state =
1563 		    ahci_portp->ahciport_port_state;
1564 		ahci_update_sata_registers(ahci_ctlp, port,
1565 		    &spkt->satapkt_device);
1566 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1567 		    "ahci_tran_start returning PORT_ERROR while "
1568 		    "no device attached: port: %s", portstr);
1569 		mutex_exit(&ahci_portp->ahciport_mutex);
1570 		return (SATA_TRAN_PORT_ERROR);
1571 	}
1572 
1573 	/* R/W PMULT command will occupy the whole HBA port */
1574 	if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
1575 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1576 		    "ahci_tran_start returning BUSY while "
1577 		    "executing READ/WRITE PORT-MULT command: "
1578 		    "port: %s", portstr);
1579 		spkt->satapkt_reason = SATA_PKT_BUSY;
1580 		mutex_exit(&ahci_portp->ahciport_mutex);
1581 		return (SATA_TRAN_BUSY);
1582 	}
1583 
1584 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_HOTPLUG) {
1585 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1586 		    "ahci_tran_start returning BUSY while "
1587 		    "hot-plug in progress: port: %s", portstr);
1588 		spkt->satapkt_reason = SATA_PKT_BUSY;
1589 		mutex_exit(&ahci_portp->ahciport_mutex);
1590 		return (SATA_TRAN_BUSY);
1591 	}
1592 
1593 	/*
1594 	 * SATA HBA driver should remember that a device was reset and it
1595 	 * is supposed to reject any packets which do not specify either
1596 	 * SATA_IGNORE_DEV_RESET_STATE or SATA_CLEAR_DEV_RESET_STATE.
1597 	 *
1598 	 * This is to prevent a race condition when a device was arbitrarily
1599 	 * reset by the HBA driver (and lost it's setting) and a target
1600 	 * driver sending some commands to a device before the sata framework
1601 	 * has a chance to restore the device setting (such as cache enable/
1602 	 * disable or other resettable stuff).
1603 	 */
1604 	/*
1605 	 * It is unnecessary to use specific flags to indicate
1606 	 * reset_in_progress for a pmport. While mopping, all command will be
1607 	 * mopped so that the entire HBA port is being dealt as a single
1608 	 * object.
1609 	 */
1610 	if (spkt->satapkt_cmd.satacmd_flags.sata_clear_dev_reset) {
1611 		ahci_portp->ahciport_reset_in_progress = 0;
1612 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1613 		    "ahci_tran_start [CLEAR] the "
1614 		    "reset_in_progress for port: %d", port);
1615 	}
1616 
1617 	if (ahci_portp->ahciport_reset_in_progress &&
1618 	    ! spkt->satapkt_cmd.satacmd_flags.sata_ignore_dev_reset &&
1619 	    ! ddi_in_panic()) {
1620 		spkt->satapkt_reason = SATA_PKT_BUSY;
1621 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1622 		    "ahci_tran_start returning BUSY while "
1623 		    "reset in progress: port: %d", port);
1624 		mutex_exit(&ahci_portp->ahciport_mutex);
1625 		return (SATA_TRAN_BUSY);
1626 	}
1627 
1628 #ifdef AHCI_DEBUG
1629 	if (spkt->satapkt_cmd.satacmd_flags.sata_ignore_dev_reset) {
1630 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1631 		    "ahci_tran_start: packet 0x%p [PASSTHRU] at port %d",
1632 		    spkt, port);
1633 	}
1634 #endif
1635 
1636 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
1637 		spkt->satapkt_reason = SATA_PKT_BUSY;
1638 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1639 		    "ahci_tran_start returning BUSY while "
1640 		    "mopping in progress: port: %d", port);
1641 		mutex_exit(&ahci_portp->ahciport_mutex);
1642 		return (SATA_TRAN_BUSY);
1643 	}
1644 
1645 	if (spkt->satapkt_op_mode &
1646 	    (SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING)) {
1647 		/*
1648 		 * If a SYNC command to be executed in interrupt context,
1649 		 * bounce it back to sata module.
1650 		 */
1651 		if (!(spkt->satapkt_op_mode & SATA_OPMODE_POLLING) &&
1652 		    servicing_interrupt()) {
1653 			spkt->satapkt_reason = SATA_PKT_BUSY;
1654 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1655 			    "ahci_tran_start returning BUSY while "
1656 			    "sending SYNC mode under interrupt context: "
1657 			    "port : %d", port);
1658 			mutex_exit(&ahci_portp->ahciport_mutex);
1659 			return (SATA_TRAN_BUSY);
1660 		}
1661 
1662 		/* We need to do the sync start now */
1663 		if (ahci_do_sync_start(ahci_ctlp, ahci_portp, &addr,
1664 		    spkt) == AHCI_FAILURE) {
1665 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_tran_start "
1666 			    "return QUEUE_FULL: port %d", port);
1667 			mutex_exit(&ahci_portp->ahciport_mutex);
1668 			return (SATA_TRAN_QUEUE_FULL);
1669 		}
1670 	} else {
1671 		/* Async start, using interrupt */
1672 		if (ahci_deliver_satapkt(ahci_ctlp, ahci_portp, &addr, spkt)
1673 		    == AHCI_FAILURE) {
1674 			spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
1675 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_tran_start "
1676 			    "returning QUEUE_FULL: port %d", port);
1677 			mutex_exit(&ahci_portp->ahciport_mutex);
1678 			return (SATA_TRAN_QUEUE_FULL);
1679 		}
1680 	}
1681 
1682 	AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_tran_start "
1683 	    "sata tran accepted: port %s", portstr);
1684 
1685 	mutex_exit(&ahci_portp->ahciport_mutex);
1686 	return (SATA_TRAN_ACCEPTED);
1687 }
1688 
1689 /*
1690  * SATA_OPMODE_SYNCH flag is set
1691  *
1692  * If SATA_OPMODE_POLLING flag is set, then we must poll the command
1693  * without interrupt, otherwise we can still use the interrupt.
1694  *
1695  * WARNING!!! ahciport_mutex should be acquired before the function
1696  * is called.
1697  */
1698 static int
1699 ahci_do_sync_start(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
1700     ahci_addr_t *addrp, sata_pkt_t *spkt)
1701 {
1702 	int pkt_timeout_ticks;
1703 	uint32_t timeout_tags;
1704 	int rval;
1705 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
1706 	uint8_t port = addrp->aa_port;
1707 
1708 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_do_sync_start enter: "
1709 	    "port %d:%d spkt 0x%p", port, addrp->aa_pmport, spkt);
1710 
1711 	if (spkt->satapkt_op_mode & SATA_OPMODE_POLLING) {
1712 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_POLLING;
1713 		if ((rval = ahci_deliver_satapkt(ahci_ctlp, ahci_portp,
1714 		    addrp, spkt)) == AHCI_FAILURE) {
1715 			ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_POLLING;
1716 			return (rval);
1717 		}
1718 
1719 		pkt_timeout_ticks =
1720 		    drv_usectohz((clock_t)spkt->satapkt_time * 1000000);
1721 
1722 		while (spkt->satapkt_reason == SATA_PKT_BUSY) {
1723 			mutex_exit(&ahci_portp->ahciport_mutex);
1724 
1725 			/* Simulate the interrupt */
1726 			ahci_port_intr(ahci_ctlp, ahci_portp, port);
1727 
1728 			drv_usecwait(AHCI_10MS_USECS);
1729 
1730 			mutex_enter(&ahci_portp->ahciport_mutex);
1731 			pkt_timeout_ticks -= AHCI_10MS_TICKS;
1732 			if (pkt_timeout_ticks < 0) {
1733 				cmn_err(CE_WARN, "!ahci%d: ahci_do_sync_start "
1734 				    "port %d satapkt 0x%p timed out\n",
1735 				    instance, port, (void *)spkt);
1736 				timeout_tags = (0x1 << rval);
1737 				mutex_exit(&ahci_portp->ahciport_mutex);
1738 				ahci_timeout_pkts(ahci_ctlp, ahci_portp,
1739 				    port, timeout_tags);
1740 				mutex_enter(&ahci_portp->ahciport_mutex);
1741 			}
1742 		}
1743 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_POLLING;
1744 		return (AHCI_SUCCESS);
1745 
1746 	} else {
1747 		if ((rval = ahci_deliver_satapkt(ahci_ctlp, ahci_portp,
1748 		    addrp, spkt)) == AHCI_FAILURE)
1749 			return (rval);
1750 
1751 #if AHCI_DEBUG
1752 		/*
1753 		 * Note that the driver always uses the slot 0 to deliver
1754 		 * REQUEST SENSE or READ LOG EXT command
1755 		 */
1756 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
1757 			ASSERT(rval == 0);
1758 #endif
1759 
1760 		while (spkt->satapkt_reason == SATA_PKT_BUSY)
1761 			cv_wait(&ahci_portp->ahciport_cv,
1762 			    &ahci_portp->ahciport_mutex);
1763 
1764 		return (AHCI_SUCCESS);
1765 	}
1766 }
1767 
1768 #define	SENDUP_PACKET(ahci_portp, satapkt, reason)			\
1769 	if (satapkt) {							\
1770 		satapkt->satapkt_reason = reason;			\
1771 		/*							\
1772 		 * We set the satapkt_reason in both sync and		\
1773 		 * non-sync cases.					\
1774 		 */							\
1775 	}								\
1776 	if (satapkt &&							\
1777 	    ! (satapkt->satapkt_op_mode & SATA_OPMODE_SYNCH) &&		\
1778 	    satapkt->satapkt_comp) {					\
1779 		mutex_exit(&ahci_portp->ahciport_mutex);		\
1780 		(*satapkt->satapkt_comp)(satapkt);			\
1781 		mutex_enter(&ahci_portp->ahciport_mutex);		\
1782 	} else {							\
1783 		if (satapkt &&						\
1784 		    (satapkt->satapkt_op_mode & SATA_OPMODE_SYNCH) &&	\
1785 		    ! (satapkt->satapkt_op_mode & SATA_OPMODE_POLLING))	\
1786 			cv_broadcast(&ahci_portp->ahciport_cv);		\
1787 	}
1788 
1789 /*
1790  * Searches for and claims a free command slot.
1791  *
1792  * Returns value:
1793  *
1794  * AHCI_FAILURE returned only if
1795  *	1. No empty slot left
1796  *	2. Non-queued command requested while queued command(s) is outstanding
1797  *	3. Queued command requested while non-queued command(s) is outstanding
1798  *	4. HBA doesn't support multiple-use of command list while already a
1799  *	   non-queued command is oustanding
1800  *	5. Queued command requested while some queued command(s) has been
1801  *	   outstanding on a different port multiplier port. (AHCI spec 1.2,
1802  *	   9.1.2)
1803  *
1804  * claimed slot number returned if succeeded
1805  *
1806  * NOTE: it will always return slot 0 for following commands to simplify the
1807  * algorithm.
1808  * 	1. REQUEST SENSE or READ LOG EXT command during error recovery process
1809  * 	2. READ/WRITE PORTMULT command
1810  *
1811  * WARNING!!! ahciport_mutex should be acquired before the function
1812  * is called.
1813  */
1814 static int
1815 ahci_claim_free_slot(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
1816     ahci_addr_t *addrp, int command_type)
1817 {
1818 	uint32_t port_cmd_issue;
1819 	uint32_t free_slots;
1820 	int slot;
1821 
1822 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_claim_free_slot enter "
1823 	    "ahciport_pending_tags = 0x%x "
1824 	    "ahciport_pending_ncq_tags = 0x%x",
1825 	    ahci_portp->ahciport_pending_tags,
1826 	    ahci_portp->ahciport_pending_ncq_tags);
1827 
1828 	/*
1829 	 * According to the AHCI spec, system software is responsible to
1830 	 * ensure that queued and non-queued commands are not mixed in
1831 	 * the command list.
1832 	 */
1833 	if (command_type == AHCI_NON_NCQ_CMD) {
1834 		/* Non-NCQ command request */
1835 		if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
1836 			AHCIDBG(AHCIDBG_INFO|AHCIDBG_NCQ, ahci_ctlp,
1837 			    "ahci_claim_free_slot: there is still pending "
1838 			    "queued command(s) in the command list, "
1839 			    "so no available slot for the non-queued "
1840 			    "command", NULL);
1841 			return (AHCI_FAILURE);
1842 		}
1843 		if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
1844 			AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
1845 			    "ahci_claim_free_slot: there is still pending "
1846 			    "read/write port-mult command(s) in command list, "
1847 			    "so no available slot for the non-queued command",
1848 			    NULL);
1849 			return (AHCI_FAILURE);
1850 		}
1851 		if ((ahci_ctlp->ahcictl_cap & AHCI_CAP_NO_MCMDLIST_NONQUEUE) &&
1852 		    NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
1853 			AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1854 			    "ahci_claim_free_slot: HBA cannot support multiple-"
1855 			    "use of the command list for non-queued commands",
1856 			    NULL);
1857 			return (AHCI_FAILURE);
1858 		}
1859 		free_slots = (~ahci_portp->ahciport_pending_tags) &
1860 		    AHCI_SLOT_MASK(ahci_ctlp);
1861 	} else if (command_type == AHCI_NCQ_CMD) {
1862 		/* NCQ command request */
1863 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
1864 			AHCIDBG(AHCIDBG_INFO|AHCIDBG_NCQ, ahci_ctlp,
1865 			    "ahci_claim_free_slot: there is still pending "
1866 			    "non-queued command(s) in the command list, "
1867 			    "so no available slot for the queued command",
1868 			    NULL);
1869 			return (AHCI_FAILURE);
1870 		}
1871 
1872 		/*
1873 		 * NCQ commands cannot be sent to different port multiplier
1874 		 * ports in Command-Based Switching mode
1875 		 */
1876 		/*
1877 		 * NOTE: In Command-Based Switching mode, AHCI controller
1878 		 * usually reports a 'Handshake Error' when multiple NCQ
1879 		 * commands are outstanding simultaneously.
1880 		 */
1881 		if (AHCIPORT_DEV_TYPE(ahci_portp, addrp) == SATA_DTYPE_PMULT) {
1882 			ASSERT(ahci_portp->ahciport_pmult_info != NULL);
1883 			if (!(ahci_ctlp->ahcictl_cap & AHCI_CAP_PMULT_FBSS) &&
1884 			    NCQ_CMD_IN_PROGRESS(ahci_portp) &&
1885 			    AHCIPORT_NCQ_PMPORT(ahci_portp) !=
1886 			    addrp->aa_pmport) {
1887 				AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1888 				    "ahci_claim_free_slot: there is still "
1889 				    "pending queued command(s) in the "
1890 				    "command list for another Port Multiplier "
1891 				    "port, so no available slot.", NULL);
1892 				return (AHCI_FAILURE);
1893 			}
1894 		}
1895 
1896 		free_slots = (~ahci_portp->ahciport_pending_ncq_tags) &
1897 		    AHCI_NCQ_SLOT_MASK(ahci_portp);
1898 	} else if (command_type == AHCI_ERR_RETRI_CMD) {
1899 		/* Error retrieval command request */
1900 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1901 		    "ahci_claim_free_slot: slot 0 is allocated for REQUEST "
1902 		    "SENSE or READ LOG EXT command", NULL);
1903 		slot = 0;
1904 		goto out;
1905 	} else if (command_type == AHCI_RDWR_PMULT_CMD) {
1906 		/*
1907 		 * An extra check on PxCI. Sometimes PxCI bits may not be
1908 		 * cleared during hot-plug or error recovery process.
1909 		 */
1910 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
1911 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, addrp->aa_port));
1912 
1913 		if (port_cmd_issue != 0) {
1914 			AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
1915 			    "ahci_claim_free_slot: there is still pending "
1916 			    "command(s) in command list (0x%x/0x%x, PxCI %x),"
1917 			    "so no available slot for R/W PMULT command.",
1918 			    NON_NCQ_CMD_IN_PROGRESS(ahci_portp),
1919 			    NCQ_CMD_IN_PROGRESS(ahci_portp),
1920 			    port_cmd_issue);
1921 			return (AHCI_FAILURE);
1922 		}
1923 
1924 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1925 		    "ahci_claim_free_slot: slot 0 is allocated for "
1926 		    "READ/WRITE PORTMULT command", NULL);
1927 		slot = 0;
1928 		goto out;
1929 	}
1930 
1931 	slot = ddi_ffs(free_slots) - 1;
1932 	if (slot == -1) {
1933 		AHCIDBG(AHCIDBG_VERBOSE, ahci_ctlp,
1934 		    "ahci_claim_free_slot: no empty slots", NULL);
1935 		return (AHCI_FAILURE);
1936 	}
1937 
1938 	/*
1939 	 * According to the AHCI spec, to allow a simple mechanism for the
1940 	 * HBA to map command list slots to queue entries, software must
1941 	 * match the tag number it uses to the slot it is placing the command
1942 	 * in. For example, if a queued command is placed in slot 5, the tag
1943 	 * for that command must be 5.
1944 	 */
1945 	if (command_type == AHCI_NCQ_CMD) {
1946 		ahci_portp->ahciport_pending_ncq_tags |= (0x1 << slot);
1947 		if (AHCI_ADDR_IS_PMPORT(addrp)) {
1948 			ASSERT(ahci_portp->ahciport_pmult_info != NULL);
1949 			AHCIPORT_NCQ_PMPORT(ahci_portp) = addrp->aa_pmport;
1950 		}
1951 	}
1952 
1953 	ahci_portp->ahciport_pending_tags |= (0x1 << slot);
1954 
1955 out:
1956 	AHCIDBG(AHCIDBG_VERBOSE, ahci_ctlp,
1957 	    "ahci_claim_free_slot: found slot: 0x%x", slot);
1958 
1959 	return (slot);
1960 }
1961 
1962 /*
1963  * Builds the Command Table for the sata packet and delivers it to controller.
1964  *
1965  * Returns:
1966  * 	slot number if we can obtain a slot successfully
1967  *	otherwise, return AHCI_FAILURE
1968  *
1969  * WARNING!!! ahciport_mutex should be acquired before the function is called.
1970  */
1971 static int
1972 ahci_deliver_satapkt(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
1973     ahci_addr_t *addrp, sata_pkt_t *spkt)
1974 {
1975 	int cmd_slot;
1976 	sata_cmd_t *scmd;
1977 	ahci_fis_h2d_register_t *h2d_register_fisp;
1978 	ahci_cmd_table_t *cmd_table;
1979 	ahci_cmd_header_t *cmd_header;
1980 	int ncookies;
1981 	int i;
1982 	int command_type = AHCI_NON_NCQ_CMD;
1983 	int ncq_qdepth;
1984 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
1985 	uint8_t port, pmport;
1986 #if AHCI_DEBUG
1987 	uint32_t *ptr;
1988 	uint8_t *ptr2;
1989 #endif
1990 
1991 	port = addrp->aa_port;
1992 	pmport = addrp->aa_pmport;
1993 
1994 	spkt->satapkt_reason = SATA_PKT_BUSY;
1995 
1996 	scmd = &spkt->satapkt_cmd;
1997 
1998 	/* Check if the command is a NCQ command */
1999 	if (scmd->satacmd_cmd_reg == SATAC_READ_FPDMA_QUEUED ||
2000 	    scmd->satacmd_cmd_reg == SATAC_WRITE_FPDMA_QUEUED) {
2001 		command_type = AHCI_NCQ_CMD;
2002 
2003 		/*
2004 		 * When NCQ is support, system software must determine the
2005 		 * maximum tag allowed by the device and the HBA, and it
2006 		 * must use a value not beyond of the lower bound of the two.
2007 		 *
2008 		 * Sata module is going to calculate the qdepth and send
2009 		 * down to HBA driver via sata_cmd.
2010 		 */
2011 		ncq_qdepth = scmd->satacmd_flags.sata_max_queue_depth + 1;
2012 
2013 		/*
2014 		 * At the moment, the driver doesn't support the dynamic
2015 		 * setting of the maximum ncq depth, and the value can be
2016 		 * set either during the attach or after hot-plug insertion.
2017 		 */
2018 		if (ahci_portp->ahciport_max_ncq_tags == 0) {
2019 			ahci_portp->ahciport_max_ncq_tags = ncq_qdepth;
2020 			AHCIDBG(AHCIDBG_NCQ, ahci_ctlp,
2021 			    "ahci_deliver_satapkt: port %d the max tags for "
2022 			    "NCQ command is %d", port, ncq_qdepth);
2023 		} else {
2024 			if (ncq_qdepth != ahci_portp->ahciport_max_ncq_tags) {
2025 				cmn_err(CE_WARN, "!ahci%d: ahci_deliver_satapkt"
2026 				    " port %d the max tag for NCQ command is "
2027 				    "requested to change from %d to %d, at the"
2028 				    " moment the driver doesn't support the "
2029 				    "dynamic change so it's going to "
2030 				    "still use the previous tag value",
2031 				    instance, port,
2032 				    ahci_portp->ahciport_max_ncq_tags,
2033 				    ncq_qdepth);
2034 			}
2035 		}
2036 	}
2037 
2038 	/* Check if the command is an error retrieval command */
2039 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
2040 		command_type = AHCI_ERR_RETRI_CMD;
2041 
2042 	/* Check if the command is an read/write pmult command */
2043 	if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp))
2044 		command_type = AHCI_RDWR_PMULT_CMD;
2045 
2046 	/* Check if there is an empty command slot */
2047 	cmd_slot = ahci_claim_free_slot(ahci_ctlp, ahci_portp,
2048 	    addrp, command_type);
2049 	if (cmd_slot == AHCI_FAILURE) {
2050 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "no free command slot", NULL);
2051 		return (AHCI_FAILURE);
2052 	}
2053 
2054 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INFO, ahci_ctlp,
2055 	    "ahci_deliver_satapkt enter: cmd_reg: 0x%x, cmd_slot: 0x%x, "
2056 	    "port: %d, satapkt: 0x%p", scmd->satacmd_cmd_reg,
2057 	    cmd_slot, port, (void *)spkt);
2058 
2059 	cmd_table = ahci_portp->ahciport_cmd_tables[cmd_slot];
2060 	bzero((void *)cmd_table, ahci_cmd_table_size);
2061 
2062 	/* For data transfer operations, it is the H2D Register FIS */
2063 	h2d_register_fisp =
2064 	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
2065 
2066 	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
2067 
2068 	/*
2069 	 * PMP field only make sense when target is a port multiplier or a
2070 	 * device behind a port multiplier. Otherwise should set it to 0.
2071 	 */
2072 	if (AHCI_ADDR_IS_PMULT(addrp) || AHCI_ADDR_IS_PMPORT(addrp))
2073 		SET_FIS_PMP(h2d_register_fisp, pmport);
2074 
2075 	SET_FIS_CDMDEVCTL(h2d_register_fisp, 1);
2076 	SET_FIS_COMMAND(h2d_register_fisp, scmd->satacmd_cmd_reg);
2077 	SET_FIS_FEATURES(h2d_register_fisp, scmd->satacmd_features_reg);
2078 	SET_FIS_SECTOR_COUNT(h2d_register_fisp, scmd->satacmd_sec_count_lsb);
2079 
2080 	switch (scmd->satacmd_addr_type) {
2081 
2082 	case 0:
2083 		/*
2084 		 * satacmd_addr_type will be 0 for the commands below:
2085 		 * 	ATAPI command
2086 		 * 	SATAC_IDLE_IM
2087 		 * 	SATAC_STANDBY_IM
2088 		 * 	SATAC_DOWNLOAD_MICROCODE
2089 		 * 	SATAC_FLUSH_CACHE
2090 		 * 	SATAC_SET_FEATURES
2091 		 * 	SATAC_SMART
2092 		 * 	SATAC_ID_PACKET_DEVICE
2093 		 * 	SATAC_ID_DEVICE
2094 		 * 	SATAC_READ_PORTMULT
2095 		 * 	SATAC_WRITE_PORTMULT
2096 		 */
2097 		/* FALLTHRU */
2098 
2099 	case ATA_ADDR_LBA:
2100 		/* FALLTHRU */
2101 
2102 	case ATA_ADDR_LBA28:
2103 		/* LBA[7:0] */
2104 		SET_FIS_SECTOR(h2d_register_fisp, scmd->satacmd_lba_low_lsb);
2105 
2106 		/* LBA[15:8] */
2107 		SET_FIS_CYL_LOW(h2d_register_fisp, scmd->satacmd_lba_mid_lsb);
2108 
2109 		/* LBA[23:16] */
2110 		SET_FIS_CYL_HI(h2d_register_fisp, scmd->satacmd_lba_high_lsb);
2111 
2112 		/* LBA [27:24] (also called dev_head) */
2113 		SET_FIS_DEV_HEAD(h2d_register_fisp, scmd->satacmd_device_reg);
2114 
2115 		break;
2116 
2117 	case ATA_ADDR_LBA48:
2118 		/* LBA[7:0] */
2119 		SET_FIS_SECTOR(h2d_register_fisp, scmd->satacmd_lba_low_lsb);
2120 
2121 		/* LBA[15:8] */
2122 		SET_FIS_CYL_LOW(h2d_register_fisp, scmd->satacmd_lba_mid_lsb);
2123 
2124 		/* LBA[23:16] */
2125 		SET_FIS_CYL_HI(h2d_register_fisp, scmd->satacmd_lba_high_lsb);
2126 
2127 		/* LBA [31:24] */
2128 		SET_FIS_SECTOR_EXP(h2d_register_fisp,
2129 		    scmd->satacmd_lba_low_msb);
2130 
2131 		/* LBA [39:32] */
2132 		SET_FIS_CYL_LOW_EXP(h2d_register_fisp,
2133 		    scmd->satacmd_lba_mid_msb);
2134 
2135 		/* LBA [47:40] */
2136 		SET_FIS_CYL_HI_EXP(h2d_register_fisp,
2137 		    scmd->satacmd_lba_high_msb);
2138 
2139 		/* Set dev_head */
2140 		SET_FIS_DEV_HEAD(h2d_register_fisp,
2141 		    scmd->satacmd_device_reg);
2142 
2143 		/* Set the extended sector count and features */
2144 		SET_FIS_SECTOR_COUNT_EXP(h2d_register_fisp,
2145 		    scmd->satacmd_sec_count_msb);
2146 		SET_FIS_FEATURES_EXP(h2d_register_fisp,
2147 		    scmd->satacmd_features_reg_ext);
2148 		break;
2149 	}
2150 
2151 	/*
2152 	 * For NCQ command (READ/WRITE FPDMA QUEUED), sector count 7:0 is
2153 	 * filled into features field, and sector count 8:15 is filled into
2154 	 * features (exp) field. TAG is filled into sector field.
2155 	 */
2156 	if (command_type == AHCI_NCQ_CMD) {
2157 		SET_FIS_FEATURES(h2d_register_fisp,
2158 		    scmd->satacmd_sec_count_lsb);
2159 		SET_FIS_FEATURES_EXP(h2d_register_fisp,
2160 		    scmd->satacmd_sec_count_msb);
2161 
2162 		SET_FIS_SECTOR_COUNT(h2d_register_fisp,
2163 		    (cmd_slot << SATA_TAG_QUEUING_SHIFT));
2164 	}
2165 
2166 	ncookies = scmd->satacmd_num_dma_cookies;
2167 	AHCIDBG(AHCIDBG_PRDT, ahci_ctlp,
2168 	    "ncookies = 0x%x, ahci_dma_prdt_number = 0x%x",
2169 	    ncookies, ahci_dma_prdt_number);
2170 
2171 	ASSERT(ncookies <= ahci_dma_prdt_number);
2172 	ahci_portp->ahciport_prd_bytecounts[cmd_slot] = 0;
2173 
2174 	/* *** now fill the scatter gather list ******* */
2175 	for (i = 0; i < ncookies; i++) {
2176 		cmd_table->ahcict_prdt[i].ahcipi_data_base_addr =
2177 		    scmd->satacmd_dma_cookie_list[i]._dmu._dmac_la[0];
2178 		cmd_table->ahcict_prdt[i].ahcipi_data_base_addr_upper =
2179 		    scmd->satacmd_dma_cookie_list[i]._dmu._dmac_la[1];
2180 		cmd_table->ahcict_prdt[i].ahcipi_descr_info =
2181 		    scmd->satacmd_dma_cookie_list[i].dmac_size - 1;
2182 		ahci_portp->ahciport_prd_bytecounts[cmd_slot] +=
2183 		    scmd->satacmd_dma_cookie_list[i].dmac_size;
2184 	}
2185 
2186 	AHCIDBG(AHCIDBG_PRDT, ahci_ctlp,
2187 	    "ahciport_prd_bytecounts 0x%x for cmd_slot 0x%x",
2188 	    ahci_portp->ahciport_prd_bytecounts[cmd_slot], cmd_slot);
2189 
2190 	/* The ACMD field is filled in for ATAPI command */
2191 	if (scmd->satacmd_cmd_reg == SATAC_PACKET) {
2192 		bcopy(scmd->satacmd_acdb, cmd_table->ahcict_atapi_cmd,
2193 		    SATA_ATAPI_MAX_CDB_LEN);
2194 	}
2195 
2196 	/* Set Command Header in Command List */
2197 	cmd_header = &ahci_portp->ahciport_cmd_list[cmd_slot];
2198 	BZERO_DESCR_INFO(cmd_header);
2199 	BZERO_PRD_BYTE_COUNT(cmd_header);
2200 
2201 	/* Set the number of entries in the PRD table */
2202 	SET_PRD_TABLE_LENGTH(cmd_header, ncookies);
2203 
2204 	/* Set the length of the command in the CFIS area */
2205 	SET_COMMAND_FIS_LENGTH(cmd_header, AHCI_H2D_REGISTER_FIS_LENGTH);
2206 
2207 	/*
2208 	 * PMP field only make sense when target is a port multiplier or a
2209 	 * device behind a port multiplier. Otherwise should set it to 0.
2210 	 */
2211 	if (AHCI_ADDR_IS_PMULT(addrp) || AHCI_ADDR_IS_PMPORT(addrp))
2212 		SET_PORT_MULTI_PORT(cmd_header, pmport);
2213 
2214 	AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "command data direction is "
2215 	    "sata_data_direction = 0x%x",
2216 	    scmd->satacmd_flags.sata_data_direction);
2217 
2218 	/* Set A bit if it is an ATAPI command */
2219 	if (scmd->satacmd_cmd_reg == SATAC_PACKET)
2220 		SET_ATAPI(cmd_header, AHCI_CMDHEAD_ATAPI);
2221 
2222 	/* Set W bit if data is going to the device */
2223 	if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE)
2224 		SET_WRITE(cmd_header, AHCI_CMDHEAD_DATA_WRITE);
2225 
2226 	/*
2227 	 * Set the prefetchable bit - this bit is only valid if the PRDTL
2228 	 * field is non-zero or the ATAPI 'A' bit is set in the command
2229 	 * header. This bit cannot be set when using native command
2230 	 * queuing commands or when using FIS-based switching with a Port
2231 	 * multiplier.
2232 	 */
2233 	if (command_type != AHCI_NCQ_CMD)
2234 		SET_PREFETCHABLE(cmd_header, AHCI_CMDHEAD_PREFETCHABLE);
2235 
2236 	/*
2237 	 * Now remember the sata packet in ahciport_slot_pkts[].
2238 	 * Error retrieval command and r/w port multiplier command will
2239 	 * be stored specifically for each port.
2240 	 */
2241 	if (!ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
2242 	    !RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp))
2243 		ahci_portp->ahciport_slot_pkts[cmd_slot] = spkt;
2244 
2245 	/*
2246 	 * We are overloading satapkt_hba_driver_private with
2247 	 * watched_cycle count.
2248 	 */
2249 	spkt->satapkt_hba_driver_private = (void *)(intptr_t)0;
2250 
2251 #if AHCI_DEBUG
2252 	if (ahci_debug_flags & AHCIDBG_ATACMD &&
2253 	    scmd->satacmd_cmd_reg != SATAC_PACKET ||
2254 	    ahci_debug_flags & AHCIDBG_ATAPICMD &&
2255 	    scmd->satacmd_cmd_reg == SATAC_PACKET) {
2256 
2257 		/* Dump the command header and table */
2258 		ahci_log(ahci_ctlp, CE_WARN, "\n");
2259 		ahci_log(ahci_ctlp, CE_WARN, "Command header&table for spkt "
2260 		    "0x%p cmd_reg 0x%x port %d", spkt,
2261 		    scmd->satacmd_cmd_reg, port);
2262 		ptr = (uint32_t *)cmd_header;
2263 		ahci_log(ahci_ctlp, CE_WARN,
2264 		    "  Command Header:%8x %8x %8x %8x",
2265 		    ptr[0], ptr[1], ptr[2], ptr[3]);
2266 
2267 		/* Dump the H2D register FIS */
2268 		ptr = (uint32_t *)h2d_register_fisp;
2269 		ahci_log(ahci_ctlp, CE_WARN,
2270 		    "  Command FIS:   %8x %8x %8x %8x",
2271 		    ptr[0], ptr[1], ptr[2], ptr[3]);
2272 
2273 		/* Dump the ACMD register FIS */
2274 		ptr2 = (uint8_t *)&(cmd_table->ahcict_atapi_cmd);
2275 		for (i = 0; i < SATA_ATAPI_MAX_CDB_LEN/8; i++)
2276 			if (ahci_debug_flags & AHCIDBG_ATAPICMD)
2277 				ahci_log(ahci_ctlp, CE_WARN,
2278 				    "  ATAPI command: %2x %2x %2x %2x "
2279 				    "%2x %2x %2x %2x",
2280 				    ptr2[8 * i], ptr2[8 * i + 1],
2281 				    ptr2[8 * i + 2], ptr2[8 * i + 3],
2282 				    ptr2[8 * i + 4], ptr2[8 * i + 5],
2283 				    ptr2[8 * i + 6], ptr2[8 * i + 7]);
2284 
2285 		/* Dump the PRDT */
2286 		for (i = 0; i < ncookies; i++) {
2287 			ptr = (uint32_t *)&(cmd_table->ahcict_prdt[i]);
2288 			ahci_log(ahci_ctlp, CE_WARN,
2289 			    "  Cookie %d:      %8x %8x %8x %8x",
2290 			    i, ptr[0], ptr[1], ptr[2], ptr[3]);
2291 		}
2292 	}
2293 #endif
2294 
2295 	(void) ddi_dma_sync(
2296 	    ahci_portp->ahciport_cmd_tables_dma_handle[cmd_slot],
2297 	    0,
2298 	    ahci_cmd_table_size,
2299 	    DDI_DMA_SYNC_FORDEV);
2300 
2301 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
2302 	    cmd_slot * sizeof (ahci_cmd_header_t),
2303 	    sizeof (ahci_cmd_header_t),
2304 	    DDI_DMA_SYNC_FORDEV);
2305 
2306 	/* Set the corresponding bit in the PxSACT.DS for queued command */
2307 	if (command_type == AHCI_NCQ_CMD) {
2308 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
2309 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port),
2310 		    (0x1 << cmd_slot));
2311 	}
2312 
2313 	/* Indicate to the HBA that a command is active. */
2314 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
2315 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
2316 	    (0x1 << cmd_slot));
2317 
2318 	AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_deliver_satapkt "
2319 	    "exit: port %d", port);
2320 
2321 	return (cmd_slot);
2322 }
2323 
2324 /*
2325  * Called by the sata framework to abort the previously sent packet(s).
2326  *
2327  * Reset device to abort commands.
2328  */
2329 static int
2330 ahci_tran_abort(dev_info_t *dip, sata_pkt_t *spkt, int flag)
2331 {
2332 	ahci_ctl_t *ahci_ctlp;
2333 	ahci_port_t *ahci_portp;
2334 	uint32_t slot_status = 0;
2335 	uint32_t aborted_tags = 0;
2336 	uint32_t finished_tags = 0;
2337 	uint8_t cport = spkt->satapkt_device.satadev_addr.cport;
2338 	uint8_t port;
2339 	int tmp_slot;
2340 	int instance = ddi_get_instance(dip);
2341 
2342 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
2343 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
2344 
2345 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2346 	    "ahci_tran_abort enter: port %d", port);
2347 
2348 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
2349 	mutex_enter(&ahci_portp->ahciport_mutex);
2350 
2351 	/*
2352 	 * If AHCI_PORT_FLAG_MOPPING flag is set, it means all the pending
2353 	 * commands are being mopped, therefore there is nothing else to do
2354 	 */
2355 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2356 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
2357 		    "ahci_tran_abort: port %d is in "
2358 		    "mopping process, so just return directly ", port);
2359 		mutex_exit(&ahci_portp->ahciport_mutex);
2360 		return (SATA_SUCCESS);
2361 	}
2362 
2363 	/*
2364 	 * If AHCI_PORT_FLAG_RDWR_PMULT flag is set, it means a R/W PMULT
2365 	 * command is being executed so no other commands is outstanding,
2366 	 * nothing to do.
2367 	 */
2368 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_RDWR_PMULT) {
2369 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
2370 		    "ahci_tran_abort: port %d is reading/writing "
2371 		    "port multiplier, so just return directly ", port);
2372 		mutex_exit(&ahci_portp->ahciport_mutex);
2373 		return (SATA_SUCCESS);
2374 	}
2375 
2376 	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED |
2377 	    ahci_portp->ahciport_port_state & SATA_PSTATE_SHUTDOWN |
2378 	    ahci_portp->ahciport_port_state & SATA_PSTATE_PWROFF) {
2379 		/*
2380 		 * In case the targer driver would send the request before
2381 		 * sata framework can have the opportunity to process those
2382 		 * event reports.
2383 		 */
2384 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
2385 		spkt->satapkt_device.satadev_state =
2386 		    ahci_portp->ahciport_port_state;
2387 		ahci_update_sata_registers(ahci_ctlp, port,
2388 		    &spkt->satapkt_device);
2389 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2390 		    "ahci_tran_abort returning SATA_FAILURE while "
2391 		    "port in FAILED/SHUTDOWN/PWROFF state: "
2392 		    "port: %d", port);
2393 		mutex_exit(&ahci_portp->ahciport_mutex);
2394 		return (SATA_FAILURE);
2395 	}
2396 
2397 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
2398 		/*
2399 		 * ahci_intr_phyrdy_change() may have rendered it to
2400 		 * AHCI_PORT_TYPE_NODEV.
2401 		 */
2402 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
2403 		spkt->satapkt_device.satadev_type = SATA_DTYPE_NONE;
2404 		spkt->satapkt_device.satadev_state =
2405 		    ahci_portp->ahciport_port_state;
2406 		ahci_update_sata_registers(ahci_ctlp, port,
2407 		    &spkt->satapkt_device);
2408 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2409 		    "ahci_tran_abort returning SATA_FAILURE while "
2410 		    "no device attached: port: %d", port);
2411 		mutex_exit(&ahci_portp->ahciport_mutex);
2412 		return (SATA_FAILURE);
2413 	}
2414 
2415 	if (flag == SATA_ABORT_ALL_PACKETS) {
2416 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2417 			aborted_tags = ahci_portp->ahciport_pending_tags;
2418 		else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2419 			aborted_tags = ahci_portp->ahciport_pending_ncq_tags;
2420 
2421 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d abort all packets",
2422 		    instance, port);
2423 	} else {
2424 		aborted_tags = 0xffffffff;
2425 		/*
2426 		 * Aborting one specific packet, first search the
2427 		 * ahciport_slot_pkts[] list for matching spkt.
2428 		 */
2429 		for (tmp_slot = 0;
2430 		    tmp_slot < ahci_ctlp->ahcictl_num_cmd_slots; tmp_slot++) {
2431 			if (ahci_portp->ahciport_slot_pkts[tmp_slot] == spkt) {
2432 				aborted_tags = (0x1 << tmp_slot);
2433 				break;
2434 			}
2435 		}
2436 
2437 		if (aborted_tags == 0xffffffff) {
2438 			/* request packet is not on the pending list */
2439 			AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
2440 			    "Cannot find the aborting pkt 0x%p on the "
2441 			    "pending list", (void *)spkt);
2442 			ahci_update_sata_registers(ahci_ctlp, port,
2443 			    &spkt->satapkt_device);
2444 			mutex_exit(&ahci_portp->ahciport_mutex);
2445 			return (SATA_FAILURE);
2446 		}
2447 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d abort satapkt 0x%p",
2448 		    instance, port, (void *)spkt);
2449 	}
2450 
2451 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2452 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2453 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2454 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2455 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2456 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2457 
2458 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2459 	ahci_portp->ahciport_mop_in_progress++;
2460 
2461 	/*
2462 	 * To abort the packet(s), first we are trying to clear PxCMD.ST
2463 	 * to stop the port, and if the port can be stopped
2464 	 * successfully with PxTFD.STS.BSY and PxTFD.STS.DRQ cleared to '0',
2465 	 * then we just send back the aborted packet(s) with ABORTED flag
2466 	 * and then restart the port by setting PxCMD.ST and PxCMD.FRE.
2467 	 * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then we
2468 	 * perform a COMRESET.
2469 	 */
2470 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp,
2471 	    ahci_portp, port, NULL, NULL);
2472 
2473 	/*
2474 	 * Compute which have finished and which need to be retried.
2475 	 *
2476 	 * The finished tags are ahciport_pending_tags/ahciport_pending_ncq_tags
2477 	 * minus the slot_status. The aborted_tags has to be deducted by
2478 	 * finished_tags since we can't possibly abort a tag which had finished
2479 	 * already.
2480 	 */
2481 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2482 		finished_tags = ahci_portp->ahciport_pending_tags &
2483 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2484 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2485 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2486 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2487 
2488 	aborted_tags &= ~finished_tags;
2489 
2490 	ahci_mop_commands(ahci_ctlp,
2491 	    ahci_portp,
2492 	    slot_status,
2493 	    0, /* failed tags */
2494 	    0, /* timeout tags */
2495 	    aborted_tags,
2496 	    0); /* reset tags */
2497 
2498 	ahci_update_sata_registers(ahci_ctlp, port, &spkt->satapkt_device);
2499 	mutex_exit(&ahci_portp->ahciport_mutex);
2500 
2501 	return (SATA_SUCCESS);
2502 }
2503 
2504 /*
2505  * Used to do device reset and reject all the pending packets on a device
2506  * during the reset operation.
2507  *
2508  * NOTE: ONLY called by ahci_tran_reset_dport
2509  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2510  */
2511 static int
2512 ahci_reset_device_reject_pkts(ahci_ctl_t *ahci_ctlp,
2513     ahci_port_t *ahci_portp, ahci_addr_t *addrp)
2514 {
2515 	uint32_t slot_status = 0;
2516 	uint32_t reset_tags = 0;
2517 	uint32_t finished_tags = 0;
2518 	uint8_t port = addrp->aa_port;
2519 	sata_device_t sdevice;
2520 	int ret;
2521 
2522 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2523 	    "ahci_reset_device_reject_pkts on port: %d", port);
2524 
2525 	/*
2526 	 * If AHCI_PORT_FLAG_MOPPING flag is set, it means all the pending
2527 	 * commands are being mopped, therefore there is nothing else to do
2528 	 */
2529 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2530 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2531 		    "ahci_reset_device_reject_pkts: port %d is in "
2532 		    "mopping process, so return directly ", port);
2533 		return (SATA_SUCCESS);
2534 	}
2535 
2536 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2537 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2538 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2539 		reset_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2540 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2541 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2542 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2543 		reset_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2544 	}
2545 
2546 	if (ahci_software_reset(ahci_ctlp, ahci_portp, addrp)
2547 	    != AHCI_SUCCESS) {
2548 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2549 		    "Try to do a port reset after software "
2550 		    "reset failed", port);
2551 		ret = ahci_port_reset(ahci_ctlp, ahci_portp, addrp);
2552 		if (ret != AHCI_SUCCESS) {
2553 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2554 			    "ahci_reset_device_reject_pkts: port %d "
2555 			    "failed", port);
2556 			return (SATA_FAILURE);
2557 		}
2558 	}
2559 	/* Set the reset in progress flag */
2560 	ahci_portp->ahciport_reset_in_progress = 1;
2561 
2562 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2563 	ahci_portp->ahciport_mop_in_progress++;
2564 
2565 	/* Indicate to the framework that a reset has happened */
2566 	bzero((void *)&sdevice, sizeof (sata_device_t));
2567 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
2568 	sdevice.satadev_addr.pmport = 0;
2569 	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
2570 	sdevice.satadev_state = SATA_DSTATE_RESET |
2571 	    SATA_DSTATE_PWR_ACTIVE;
2572 	mutex_exit(&ahci_portp->ahciport_mutex);
2573 	sata_hba_event_notify(
2574 	    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
2575 	    &sdevice,
2576 	    SATA_EVNT_DEVICE_RESET);
2577 	mutex_enter(&ahci_portp->ahciport_mutex);
2578 
2579 	AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
2580 	    "port %d sending event up: SATA_EVNT_DEVICE_RESET", port);
2581 
2582 	/* Next try to mop the pending commands */
2583 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2584 		finished_tags = ahci_portp->ahciport_pending_tags &
2585 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2586 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2587 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2588 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2589 
2590 	reset_tags &= ~finished_tags;
2591 
2592 	ahci_mop_commands(ahci_ctlp,
2593 	    ahci_portp,
2594 	    slot_status,
2595 	    0, /* failed tags */
2596 	    0, /* timeout tags */
2597 	    0, /* aborted tags */
2598 	    reset_tags); /* reset tags */
2599 
2600 	return (SATA_SUCCESS);
2601 }
2602 
2603 /*
2604  * Used to do device reset and reject all the pending packets on a device
2605  * during the reset operation.
2606  *
2607  * NOTE: ONLY called by ahci_tran_reset_dport
2608  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2609  */
2610 static int
2611 ahci_reset_pmdevice_reject_pkts(ahci_ctl_t *ahci_ctlp,
2612     ahci_port_t *ahci_portp, ahci_addr_t *addrp)
2613 {
2614 	uint32_t finished_tags = 0, reset_tags = 0, slot_status = 0;
2615 	uint8_t port = addrp->aa_port;
2616 	uint8_t pmport = addrp->aa_pmport;
2617 	sata_device_t sdevice;
2618 
2619 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_PMULT, ahci_ctlp,
2620 	    "ahci_reset_pmdevice_reject_pkts at port %d:%d", port, pmport);
2621 
2622 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2623 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2624 		    "ahci_reset_pmdevice_reject_pkts: port %d is in "
2625 		    "mopping process, so return directly ", port);
2626 		return (SATA_SUCCESS);
2627 	}
2628 
2629 	/* Checking for outstanding commands */
2630 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2631 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2632 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2633 		reset_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2634 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2635 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2636 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2637 		reset_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2638 	}
2639 
2640 	/* Issue SOFTWARE reset command. */
2641 	if (ahci_software_reset(ahci_ctlp, ahci_portp, addrp)
2642 	    != AHCI_SUCCESS) {
2643 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2644 		    "Try to do a port reset after software "
2645 		    "reset failed", port);
2646 		return (SATA_FAILURE);
2647 	}
2648 
2649 	/* Set the reset in progress flag */
2650 	ahci_portp->ahciport_reset_in_progress = 1;
2651 
2652 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2653 	ahci_portp->ahciport_mop_in_progress++;
2654 
2655 	/* Indicate to the framework that a reset has happened */
2656 	bzero((void *)&sdevice, sizeof (sata_device_t));
2657 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
2658 	sdevice.satadev_addr.pmport = pmport;
2659 	if (AHCI_ADDR_IS_PMULT(addrp))
2660 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
2661 	else
2662 		sdevice.satadev_addr.qual = SATA_ADDR_DPMPORT;
2663 	sdevice.satadev_state = SATA_DSTATE_RESET |
2664 	    SATA_DSTATE_PWR_ACTIVE;
2665 	mutex_exit(&ahci_portp->ahciport_mutex);
2666 	sata_hba_event_notify(
2667 	    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
2668 	    &sdevice,
2669 	    SATA_EVNT_DEVICE_RESET);
2670 	mutex_enter(&ahci_portp->ahciport_mutex);
2671 
2672 	AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
2673 	    "port %d:%d sending event up: SATA_EVNT_DEVICE_RESET",
2674 	    port, pmport);
2675 
2676 	/* Next try to mop the pending commands */
2677 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2678 		finished_tags = ahci_portp->ahciport_pending_tags &
2679 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2680 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2681 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2682 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2683 	reset_tags &= ~finished_tags;
2684 
2685 	AHCIDBG(AHCIDBG_EVENT|AHCIDBG_PMULT, ahci_ctlp,
2686 	    "reset_tags = %x, finished_tags = %x, slot_status = %x",
2687 	    reset_tags, finished_tags, slot_status);
2688 
2689 	/*
2690 	 * NOTE: Because PxCI be only erased by unset PxCMD.ST bit, so even we
2691 	 * try to reset a single device behind a port multiplier will
2692 	 * terminate all the commands on that HBA port. We need mop these
2693 	 * commands as well.
2694 	 */
2695 	ahci_mop_commands(ahci_ctlp,
2696 	    ahci_portp,
2697 	    slot_status,
2698 	    0, /* failed tags */
2699 	    0, /* timeout tags */
2700 	    0, /* aborted tags */
2701 	    reset_tags); /* reset tags */
2702 
2703 	return (SATA_SUCCESS);
2704 }
2705 
2706 /*
2707  * Used to do port reset and reject all the pending packets on a port during
2708  * the reset operation.
2709  *
2710  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2711  */
2712 static int
2713 ahci_reset_port_reject_pkts(ahci_ctl_t *ahci_ctlp,
2714     ahci_port_t *ahci_portp, ahci_addr_t *addrp)
2715 {
2716 	uint32_t slot_status = 0;
2717 	uint32_t reset_tags = 0;
2718 	uint32_t finished_tags = 0;
2719 	uint8_t port = addrp->aa_port;
2720 
2721 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2722 	    "ahci_reset_port_reject_pkts at port: %d", port);
2723 
2724 	/*
2725 	 * If AHCI_PORT_FLAG_MOPPING flag is set, it means all the pending
2726 	 * commands are being mopped, therefore there is nothing else to do
2727 	 */
2728 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2729 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2730 		    "ahci_reset_port_reject_pkts: port %d is in "
2731 		    "mopping process, so return directly ", port);
2732 		return (SATA_SUCCESS);
2733 	}
2734 
2735 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2736 	ahci_portp->ahciport_mop_in_progress++;
2737 
2738 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2739 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2740 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2741 		reset_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2742 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2743 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2744 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2745 		reset_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2746 	}
2747 
2748 	if (ahci_restart_port_wait_till_ready(ahci_ctlp,
2749 	    ahci_portp, port, AHCI_PORT_RESET|AHCI_RESET_NO_EVENTS_UP,
2750 	    NULL) != AHCI_SUCCESS) {
2751 
2752 		/* Clear mop flag */
2753 		ahci_portp->ahciport_mop_in_progress--;
2754 		if (ahci_portp->ahciport_mop_in_progress == 0)
2755 			ahci_portp->ahciport_flags &=
2756 			    ~AHCI_PORT_FLAG_MOPPING;
2757 		return (SATA_FAILURE);
2758 	}
2759 
2760 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2761 		finished_tags = ahci_portp->ahciport_pending_tags &
2762 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2763 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2764 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2765 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2766 
2767 	reset_tags &= ~finished_tags;
2768 
2769 	ahci_mop_commands(ahci_ctlp,
2770 	    ahci_portp,
2771 	    slot_status,
2772 	    0, /* failed tags */
2773 	    0, /* timeout tags */
2774 	    0, /* aborted tags */
2775 	    reset_tags); /* reset tags */
2776 
2777 	return (SATA_SUCCESS);
2778 }
2779 
2780 /*
2781  * Used to do hba reset and reject all the pending packets on all ports
2782  * during the reset operation.
2783  */
2784 static int
2785 ahci_reset_hba_reject_pkts(ahci_ctl_t *ahci_ctlp)
2786 {
2787 	ahci_port_t *ahci_portp;
2788 	uint32_t slot_status[AHCI_MAX_PORTS];
2789 	uint32_t reset_tags[AHCI_MAX_PORTS];
2790 	uint32_t finished_tags[AHCI_MAX_PORTS];
2791 	int port;
2792 	int ret = SATA_SUCCESS;
2793 
2794 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2795 	    "ahci_reset_hba_reject_pkts enter", NULL);
2796 
2797 	bzero(slot_status, sizeof (slot_status));
2798 	bzero(reset_tags, sizeof (reset_tags));
2799 	bzero(finished_tags, sizeof (finished_tags));
2800 
2801 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2802 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2803 			continue;
2804 		}
2805 
2806 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2807 
2808 		mutex_enter(&ahci_portp->ahciport_mutex);
2809 		ahci_portp->ahciport_reset_in_progress = 1;
2810 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2811 			slot_status[port] = ddi_get32(
2812 			    ahci_ctlp->ahcictl_ahci_acc_handle,
2813 			    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2814 			reset_tags[port] = slot_status[port] &
2815 			    AHCI_SLOT_MASK(ahci_ctlp);
2816 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
2817 			    "port %d: reset_tags = 0x%x pending_tags = 0x%x",
2818 			    port, reset_tags[port],
2819 			    ahci_portp->ahciport_pending_tags);
2820 		} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2821 			slot_status[port] = ddi_get32(
2822 			    ahci_ctlp->ahcictl_ahci_acc_handle,
2823 			    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2824 			reset_tags[port] = slot_status[port] &
2825 			    AHCI_NCQ_SLOT_MASK(ahci_portp);
2826 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
2827 			    "port %d: reset_tags = 0x%x pending_tags = 0x%x",
2828 			    port, reset_tags[port],
2829 			    ahci_portp->ahciport_pending_tags);
2830 		}
2831 		mutex_exit(&ahci_portp->ahciport_mutex);
2832 	}
2833 
2834 	if (ahci_hba_reset(ahci_ctlp) != AHCI_SUCCESS) {
2835 		ret = SATA_FAILURE;
2836 	}
2837 
2838 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2839 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2840 			continue;
2841 		}
2842 
2843 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2844 
2845 		mutex_enter(&ahci_portp->ahciport_mutex);
2846 		/*
2847 		 * To prevent recursive enter to ahci_mop_commands, we need
2848 		 * check AHCI_PORT_FLAG_MOPPING flag.
2849 		 */
2850 		if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2851 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2852 			    "ahci_reset_hba_reject_pkts: port %d is in "
2853 			    "mopping process, so return directly ", port);
2854 			mutex_exit(&ahci_portp->ahciport_mutex);
2855 			continue;
2856 		}
2857 
2858 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2859 		ahci_portp->ahciport_mop_in_progress++;
2860 
2861 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2862 			finished_tags[port]  =
2863 			    ahci_portp->ahciport_pending_tags &
2864 			    ~slot_status[port] & AHCI_SLOT_MASK(ahci_ctlp);
2865 		else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2866 			finished_tags[port] =
2867 			    ahci_portp->ahciport_pending_ncq_tags &
2868 			    ~slot_status[port] & AHCI_NCQ_SLOT_MASK(ahci_portp);
2869 
2870 		reset_tags[port] &= ~finished_tags[port];
2871 
2872 		ahci_mop_commands(ahci_ctlp,
2873 		    ahci_portp,
2874 		    slot_status[port],
2875 		    0, /* failed tags */
2876 		    0, /* timeout tags */
2877 		    0, /* aborted tags */
2878 		    reset_tags[port]); /* reset tags */
2879 		mutex_exit(&ahci_portp->ahciport_mutex);
2880 	}
2881 out:
2882 	return (ret);
2883 }
2884 
2885 /*
2886  * Called by sata framework to reset a port(s) or device.
2887  */
2888 static int
2889 ahci_tran_reset_dport(dev_info_t *dip, sata_device_t *sd)
2890 {
2891 	ahci_ctl_t *ahci_ctlp;
2892 	ahci_port_t *ahci_portp;
2893 	ahci_addr_t addr;
2894 	uint8_t cport = sd->satadev_addr.cport;
2895 	uint8_t pmport = sd->satadev_addr.pmport;
2896 	uint8_t port;
2897 	int ret = SATA_SUCCESS;
2898 	int instance = ddi_get_instance(dip);
2899 
2900 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
2901 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
2902 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
2903 
2904 	ahci_get_ahci_addr(ahci_ctlp, sd, &addr);
2905 
2906 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2907 	    "ahci_tran_reset_dport enter: cport %d", cport);
2908 
2909 	switch (sd->satadev_addr.qual) {
2910 	case SATA_ADDR_PMPORT:
2911 		/*
2912 		 * If we want to issue a COMRESET on a pmport, we need to
2913 		 * reject the outstanding commands on that pmport. According
2914 		 * to AHCI spec, PxCI register could only be cleared by
2915 		 * clearing PxCMD.ST, which will halt the controller port - as
2916 		 * well as other pmports.
2917 		 *
2918 		 * Therefore we directly reset the controller port for
2919 		 * simplicity. ahci_tran_probe_port() will handle reset stuff
2920 		 * like initializing the given pmport.
2921 		 */
2922 		/* FALLTHRU */
2923 	case SATA_ADDR_CPORT:
2924 		/* Port reset */
2925 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2926 		cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport "
2927 		    "port %d reset port", instance, port);
2928 
2929 		mutex_enter(&ahci_portp->ahciport_mutex);
2930 		ret = ahci_reset_port_reject_pkts(ahci_ctlp, ahci_portp, &addr);
2931 		mutex_exit(&ahci_portp->ahciport_mutex);
2932 
2933 		break;
2934 
2935 	case SATA_ADDR_DPMPORT:
2936 		cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport "
2937 		    "port %d:%d reset device", instance, port, pmport);
2938 		/* FALLTHRU */
2939 	case SATA_ADDR_DCPORT:
2940 		/* Device reset */
2941 		if (sd->satadev_addr.qual == SATA_ADDR_DCPORT)
2942 			cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport "
2943 			    "port %d reset device", instance, port);
2944 
2945 		mutex_enter(&ahci_portp->ahciport_mutex);
2946 		/*
2947 		 * software reset request must be sent to SATA_PMULT_HOSTPORT
2948 		 * if target is a port multiplier:
2949 		 */
2950 		if (sd->satadev_addr.qual == SATA_ADDR_DCPORT &&
2951 		    ahci_portp->ahciport_device_type == SATA_DTYPE_PMULT)
2952 			AHCI_ADDR_SET_PMULT(&addr, port);
2953 
2954 		if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED |
2955 		    ahci_portp->ahciport_port_state & SATA_PSTATE_SHUTDOWN |
2956 		    ahci_portp->ahciport_port_state & SATA_PSTATE_PWROFF) {
2957 			/*
2958 			 * In case the targer driver would send the request
2959 			 * before sata framework can have the opportunity to
2960 			 * process those event reports.
2961 			 */
2962 			sd->satadev_state = ahci_portp->ahciport_port_state;
2963 			ahci_update_sata_registers(ahci_ctlp, port, sd);
2964 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2965 			    "ahci_tran_reset_dport returning SATA_FAILURE "
2966 			    "while port in FAILED/SHUTDOWN/PWROFF state: "
2967 			    "port: %d", port);
2968 			mutex_exit(&ahci_portp->ahciport_mutex);
2969 			ret = SATA_FAILURE;
2970 			break;
2971 		}
2972 
2973 		if (AHCIPORT_GET_DEV_TYPE(ahci_portp, &addr) ==
2974 		    SATA_DTYPE_NONE) {
2975 			/*
2976 			 * ahci_intr_phyrdy_change() may have rendered it to
2977 			 * AHCI_PORT_TYPE_NODEV.
2978 			 */
2979 			sd->satadev_type = SATA_DTYPE_NONE;
2980 			sd->satadev_state = AHCIPORT_GET_STATE(ahci_portp,
2981 			    &addr);
2982 			ahci_update_sata_registers(ahci_ctlp, port, sd);
2983 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2984 			    "ahci_tran_reset_dport returning SATA_FAILURE "
2985 			    "while no device attached: port: %d", port);
2986 			mutex_exit(&ahci_portp->ahciport_mutex);
2987 			ret = SATA_FAILURE;
2988 			break;
2989 		}
2990 
2991 		if (AHCI_ADDR_IS_PORT(&addr)) {
2992 			ret = ahci_reset_device_reject_pkts(ahci_ctlp,
2993 			    ahci_portp, &addr);
2994 		} else {
2995 			ret = ahci_reset_pmdevice_reject_pkts(ahci_ctlp,
2996 			    ahci_portp, &addr);
2997 		}
2998 
2999 		mutex_exit(&ahci_portp->ahciport_mutex);
3000 		break;
3001 
3002 	case SATA_ADDR_CNTRL:
3003 		/* Reset the whole controller */
3004 		cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport "
3005 		    "reset the whole hba", instance);
3006 		ret = ahci_reset_hba_reject_pkts(ahci_ctlp);
3007 		break;
3008 
3009 	default:
3010 		ret = SATA_FAILURE;
3011 	}
3012 
3013 	return (ret);
3014 }
3015 
3016 /*
3017  * Called by sata framework to activate a port as part of hotplug.
3018  * (cfgadm -c connect satax/y)
3019  * Support port multiplier.
3020  */
3021 static int
3022 ahci_tran_hotplug_port_activate(dev_info_t *dip, sata_device_t *satadev)
3023 {
3024 	ahci_ctl_t *ahci_ctlp;
3025 	ahci_port_t *ahci_portp;
3026 	ahci_addr_t addr;
3027 	uint8_t	cport = satadev->satadev_addr.cport;
3028 	uint8_t	pmport = satadev->satadev_addr.pmport;
3029 	uint8_t port;
3030 	int instance = ddi_get_instance(dip);
3031 
3032 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
3033 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
3034 
3035 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
3036 	    "ahci_tran_hotplug_port_activate enter: cport %d", cport);
3037 
3038 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
3039 
3040 	mutex_enter(&ahci_portp->ahciport_mutex);
3041 	ahci_get_ahci_addr(ahci_ctlp, satadev, &addr);
3042 	ASSERT(AHCI_ADDR_IS_PORT(&addr) || AHCI_ADDR_IS_PMPORT(&addr));
3043 
3044 	if (AHCI_ADDR_IS_PORT(&addr)) {
3045 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d is activated",
3046 		    instance, port);
3047 
3048 		/* Enable the interrupts on the port */
3049 		ahci_enable_port_intrs(ahci_ctlp, port);
3050 
3051 		/*
3052 		 * Reset the port so that the PHY communication would be
3053 		 * re-established.  But this reset is an internal operation
3054 		 * and the sata module doesn't need to know about it.
3055 		 * Moreover, the port with a device attached will be started
3056 		 * too.
3057 		 */
3058 		(void) ahci_restart_port_wait_till_ready(ahci_ctlp,
3059 		    ahci_portp, port,
3060 		    AHCI_PORT_RESET|AHCI_RESET_NO_EVENTS_UP,
3061 		    NULL);
3062 
3063 		/*
3064 		 * Need to check the link status and device status of the port
3065 		 * and consider raising power if the port was in D3 state
3066 		 */
3067 		ahci_portp->ahciport_port_state |= SATA_PSTATE_PWRON;
3068 		ahci_portp->ahciport_port_state &= ~SATA_PSTATE_PWROFF;
3069 		ahci_portp->ahciport_port_state &= ~SATA_PSTATE_SHUTDOWN;
3070 	} else if (AHCI_ADDR_IS_PMPORT(&addr)) {
3071 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d:%d is activated",
3072 		    instance, port, pmport);
3073 		/* AHCI_ADDR_PMPORT */
3074 		AHCIPORT_PMSTATE(ahci_portp, &addr) |= SATA_PSTATE_PWRON;
3075 		AHCIPORT_PMSTATE(ahci_portp, &addr) &=
3076 		    ~(SATA_PSTATE_PWROFF|SATA_PSTATE_SHUTDOWN);
3077 	}
3078 
3079 	satadev->satadev_state = ahci_portp->ahciport_port_state;
3080 
3081 	ahci_update_sata_registers(ahci_ctlp, port, satadev);
3082 
3083 	mutex_exit(&ahci_portp->ahciport_mutex);
3084 	return (SATA_SUCCESS);
3085 }
3086 
3087 /*
3088  * Called by sata framework to deactivate a port as part of hotplug.
3089  * (cfgadm -c disconnect satax/y)
3090  * Support port multiplier.
3091  */
3092 static int
3093 ahci_tran_hotplug_port_deactivate(dev_info_t *dip, sata_device_t *satadev)
3094 {
3095 	ahci_ctl_t *ahci_ctlp;
3096 	ahci_port_t *ahci_portp;
3097 	ahci_addr_t addr;
3098 	uint8_t	cport = satadev->satadev_addr.cport;
3099 	uint8_t	pmport = satadev->satadev_addr.pmport;
3100 	uint8_t port;
3101 	uint32_t port_scontrol;
3102 	int instance = ddi_get_instance(dip);
3103 
3104 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
3105 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
3106 
3107 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
3108 	    "ahci_tran_hotplug_port_deactivate enter: cport %d", cport);
3109 
3110 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
3111 	mutex_enter(&ahci_portp->ahciport_mutex);
3112 	ahci_get_ahci_addr(ahci_ctlp, satadev, &addr);
3113 	ASSERT(AHCI_ADDR_IS_PORT(&addr) || AHCI_ADDR_IS_PMPORT(&addr));
3114 
3115 	if (AHCI_ADDR_IS_PORT(&addr)) {
3116 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d is deactivated",
3117 		    instance, port);
3118 
3119 		/* Disable the interrupts on the port */
3120 		ahci_disable_port_intrs(ahci_ctlp, port);
3121 
3122 		if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) {
3123 
3124 			/* First to abort all the pending commands */
3125 			ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
3126 
3127 			/* Then stop the port */
3128 			(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
3129 			    ahci_portp, port);
3130 		}
3131 
3132 		/* Next put the PHY offline */
3133 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3134 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3135 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_DISABLE);
3136 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle, (uint32_t *)
3137 		    AHCI_PORT_PxSCTL(ahci_ctlp, port), port_scontrol);
3138 	} else if (AHCI_ADDR_IS_PMPORT(&addr)) {
3139 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d:%d is deactivated",
3140 		    instance, port, pmport);
3141 
3142 		ahci_disable_port_intrs(ahci_ctlp, port);
3143 		if (AHCIPORT_GET_DEV_TYPE(ahci_portp, &addr)
3144 		    != SATA_DTYPE_NONE)
3145 			ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
3146 
3147 		/* Re-enable the interrupts for the other pmports */
3148 		ahci_enable_port_intrs(ahci_ctlp, port);
3149 	}
3150 
3151 	/* Update port state */
3152 	AHCIPORT_SET_STATE(ahci_portp, &addr, SATA_PSTATE_SHUTDOWN);
3153 	satadev->satadev_state = SATA_PSTATE_SHUTDOWN;
3154 
3155 	ahci_update_sata_registers(ahci_ctlp, port, satadev);
3156 
3157 	mutex_exit(&ahci_portp->ahciport_mutex);
3158 	return (SATA_SUCCESS);
3159 }
3160 
3161 /*
3162  * To be used to mark all the outstanding pkts with SATA_PKT_ABORTED
3163  * when a device is unplugged or a port is deactivated.
3164  *
3165  * WARNING!!! ahciport_mutex should be acquired before the function is called.
3166  */
3167 static void
3168 ahci_reject_all_abort_pkts(ahci_ctl_t *ahci_ctlp,
3169     ahci_port_t *ahci_portp, uint8_t port)
3170 {
3171 	uint32_t slot_status = 0;
3172 	uint32_t abort_tags = 0;
3173 
3174 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
3175 	    "ahci_reject_all_abort_pkts at port: %d", port);
3176 
3177 	/* Read/write port multiplier command takes highest priority */
3178 	if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
3179 		slot_status = 0x1;
3180 		abort_tags = 0x1;
3181 		goto out;
3182 	}
3183 
3184 	/*
3185 	 * When AHCI_PORT_FLAG_MOPPING is set, we need to check whether a
3186 	 * REQUEST SENSE command or READ LOG EXT command is delivered to HBA
3187 	 * to get the error data, if yes when the device is removed, the
3188 	 * command needs to be aborted too.
3189 	 */
3190 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
3191 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
3192 			slot_status = 0x1;
3193 			abort_tags = 0x1;
3194 			goto out;
3195 		} else {
3196 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3197 			    "ahci_reject_all_abort_pkts return directly "
3198 			    "port %d no needs to reject any outstanding "
3199 			    "commands", port);
3200 			return;
3201 		}
3202 	}
3203 
3204 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
3205 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3206 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
3207 		abort_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
3208 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
3209 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3210 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
3211 		abort_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
3212 	}
3213 
3214 out:
3215 	/* No need to do mop when there is no outstanding commands */
3216 	if (slot_status != 0) {
3217 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
3218 		ahci_portp->ahciport_mop_in_progress++;
3219 
3220 		ahci_mop_commands(ahci_ctlp,
3221 		    ahci_portp,
3222 		    slot_status,
3223 		    0, /* failed tags */
3224 		    0, /* timeout tags */
3225 		    abort_tags, /* aborting tags */
3226 		    0); /* reset tags */
3227 	}
3228 }
3229 
3230 #if defined(__lock_lint)
3231 static int
3232 ahci_selftest(dev_info_t *dip, sata_device_t *device)
3233 {
3234 	return (SATA_SUCCESS);
3235 }
3236 #endif
3237 
3238 /*
3239  * Allocate the ports structure, only called by ahci_attach
3240  */
3241 static int
3242 ahci_alloc_ports_state(ahci_ctl_t *ahci_ctlp)
3243 {
3244 	int port, cport = 0;
3245 
3246 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3247 	    "ahci_alloc_ports_state enter", NULL);
3248 
3249 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3250 
3251 	/* Allocate structures only for the implemented ports */
3252 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3253 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3254 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3255 			    "hba port %d not implemented", port);
3256 			continue;
3257 		}
3258 
3259 		ahci_ctlp->ahcictl_cport_to_port[cport] = (uint8_t)port;
3260 		ahci_ctlp->ahcictl_port_to_cport[port] =
3261 		    (uint8_t)cport++;
3262 
3263 		if (ahci_alloc_port_state(ahci_ctlp, port) != AHCI_SUCCESS) {
3264 			goto err_out;
3265 		}
3266 	}
3267 
3268 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3269 	return (AHCI_SUCCESS);
3270 
3271 err_out:
3272 	for (port--; port >= 0; port--) {
3273 		if (AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3274 			ahci_dealloc_port_state(ahci_ctlp, port);
3275 		}
3276 	}
3277 
3278 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3279 	return (AHCI_FAILURE);
3280 }
3281 
3282 /*
3283  * Reverse of ahci_alloc_ports_state(), only called by ahci_detach
3284  */
3285 static void
3286 ahci_dealloc_ports_state(ahci_ctl_t *ahci_ctlp)
3287 {
3288 	int port;
3289 
3290 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3291 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3292 		/* if this port is implemented by the HBA */
3293 		if (AHCI_PORT_IMPLEMENTED(ahci_ctlp, port))
3294 			ahci_dealloc_port_state(ahci_ctlp, port);
3295 	}
3296 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3297 }
3298 
3299 /*
3300  * Drain the taskq.
3301  */
3302 static void
3303 ahci_drain_ports_taskq(ahci_ctl_t *ahci_ctlp)
3304 {
3305 	ahci_port_t *ahci_portp;
3306 	int port;
3307 
3308 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3309 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3310 			continue;
3311 		}
3312 
3313 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
3314 
3315 		mutex_enter(&ahci_portp->ahciport_mutex);
3316 		ddi_taskq_wait(ahci_portp->ahciport_event_taskq);
3317 		mutex_exit(&ahci_portp->ahciport_mutex);
3318 	}
3319 }
3320 
3321 /*
3322  * Initialize the controller and all ports. And then try to start the ports
3323  * if there are devices attached.
3324  *
3325  * This routine can be called from three seperate cases: DDI_ATTACH,
3326  * PM_LEVEL_D0 and DDI_RESUME. The DDI_ATTACH case is different from
3327  * other two cases; device signature probing are attempted only during
3328  * DDI_ATTACH case.
3329  *
3330  * WARNING!!! Disable the whole controller's interrupts before calling and
3331  * the interrupts will be enabled upon successfully return.
3332  */
3333 static int
3334 ahci_initialize_controller(ahci_ctl_t *ahci_ctlp)
3335 {
3336 	ahci_port_t *ahci_portp;
3337 	ahci_addr_t addr;
3338 	uint32_t ghc_control;
3339 	int port;
3340 
3341 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3342 	    "ahci_initialize_controller enter", NULL);
3343 
3344 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3345 
3346 	/*
3347 	 * Indicate that system software is AHCI aware by setting
3348 	 * GHC.AE to 1
3349 	 */
3350 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3351 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3352 
3353 	ghc_control |= AHCI_HBA_GHC_AE;
3354 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3355 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp),
3356 	    ghc_control);
3357 
3358 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3359 
3360 	/* Initialize the implemented ports and structures */
3361 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3362 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3363 			continue;
3364 		}
3365 
3366 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
3367 		mutex_enter(&ahci_portp->ahciport_mutex);
3368 
3369 		/*
3370 		 * Ensure that the controller is not in the running state
3371 		 * by checking every implemented port's PxCMD register
3372 		 */
3373 		AHCI_ADDR_SET_PORT(&addr, (uint8_t)port);
3374 
3375 		if (ahci_initialize_port(ahci_ctlp, ahci_portp, &addr)
3376 		    != AHCI_SUCCESS) {
3377 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3378 			    "ahci_initialize_controller: failed to "
3379 			    "initialize port %d", port);
3380 			/*
3381 			 * Set the port state to SATA_PSTATE_FAILED if
3382 			 * failed to initialize it.
3383 			 */
3384 			ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
3385 		}
3386 
3387 		mutex_exit(&ahci_portp->ahciport_mutex);
3388 	}
3389 
3390 	/* Enable the whole controller interrupts */
3391 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3392 	ahci_enable_all_intrs(ahci_ctlp);
3393 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3394 
3395 	return (AHCI_SUCCESS);
3396 }
3397 
3398 /*
3399  * Reverse of ahci_initialize_controller()
3400  *
3401  * We only need to stop the ports and disable the interrupt.
3402  */
3403 static void
3404 ahci_uninitialize_controller(ahci_ctl_t *ahci_ctlp)
3405 {
3406 	ahci_port_t *ahci_portp;
3407 	int port;
3408 
3409 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3410 	    "ahci_uninitialize_controller enter", NULL);
3411 
3412 	/* disable all the interrupts. */
3413 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3414 	ahci_disable_all_intrs(ahci_ctlp);
3415 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3416 
3417 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3418 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3419 			continue;
3420 		}
3421 
3422 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
3423 
3424 		/* Stop the port by clearing PxCMD.ST */
3425 		mutex_enter(&ahci_portp->ahciport_mutex);
3426 
3427 		/*
3428 		 * Here we must disable the port interrupt because
3429 		 * ahci_disable_all_intrs only clear GHC.IE, and IS
3430 		 * register will be still set if PxIE is enabled.
3431 		 * When ahci shares one IRQ with other drivers, the
3432 		 * intr handler may claim the intr mistakenly.
3433 		 */
3434 		ahci_disable_port_intrs(ahci_ctlp, port);
3435 		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
3436 		    ahci_portp, port);
3437 		mutex_exit(&ahci_portp->ahciport_mutex);
3438 	}
3439 }
3440 
3441 /*
3442  * ahci_alloc_pmult()
3443  * 1. Setting HBA port registers which are necessary for a port multiplier.
3444  *    (Set PxCMD.PMA while PxCMD.ST is '0')
3445  * 2. Allocate ahci_pmult_info structure.
3446  *
3447  * NOTE: Must stop port before the function is called.
3448  * WARNING!!! ahciport_mutex should be acquired before the function is
3449  * called.
3450  */
3451 static void
3452 ahci_alloc_pmult(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
3453 {
3454 	uint32_t port_cmd_status;
3455 	uint8_t port = ahci_portp->ahciport_port_num;
3456 
3457 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3458 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3459 
3460 	/* The port must have been stopped before. */
3461 	ASSERT(!(port_cmd_status & AHCI_CMD_STATUS_ST));
3462 
3463 	if (!(port_cmd_status & AHCI_CMD_STATUS_PMA)) {
3464 		/* set PMA bit */
3465 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3466 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3467 		    port_cmd_status|AHCI_CMD_STATUS_PMA);
3468 
3469 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_PMULT, ahci_ctlp,
3470 		    "ahci_alloc_pmult: "
3471 		    "PxCMD.PMA bit set at port %d.", port);
3472 	}
3473 
3474 	/* Allocate port multiplier information structure */
3475 	if (ahci_portp->ahciport_pmult_info == NULL) {
3476 		ahci_portp->ahciport_pmult_info = (ahci_pmult_info_t *)
3477 		    kmem_zalloc(sizeof (ahci_pmult_info_t), KM_SLEEP);
3478 	}
3479 
3480 	ASSERT(ahci_portp->ahciport_pmult_info != NULL);
3481 }
3482 
3483 /*
3484  * ahci_dealloc_pmult()
3485  * 1. Clearing related registers when a port multiplier is detached.
3486  *    (Clear PxCMD.PMA while PxCMD.ST is '0')
3487  * 2. Deallocate ahci_pmult_info structure.
3488  *
3489  * NOTE: Must stop port before the function is called.
3490  * WARNING!!! ahciport_mutex should be acquired before the function is
3491  * called.
3492  */
3493 static void
3494 ahci_dealloc_pmult(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
3495 {
3496 	uint32_t port_cmd_status;
3497 	uint8_t port = ahci_portp->ahciport_port_num;
3498 
3499 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3500 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3501 
3502 	if (port_cmd_status & AHCI_CMD_STATUS_PMA) {
3503 		/* Clear PMA bit */
3504 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3505 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3506 		    (port_cmd_status & (~AHCI_CMD_STATUS_PMA)));
3507 
3508 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_PMULT, ahci_ctlp,
3509 		    "ahci_dealloc_pmult: "
3510 		    "PxCMD.PMA bit cleared at port %d.", port);
3511 	}
3512 
3513 	/* Release port multiplier information structure */
3514 	if (ahci_portp->ahciport_pmult_info != NULL) {
3515 		kmem_free(ahci_portp->ahciport_pmult_info,
3516 		    sizeof (ahci_pmult_info_t));
3517 		ahci_portp->ahciport_pmult_info = NULL;
3518 	}
3519 }
3520 
3521 /*
3522  * The routine is to initialize a port. First put the port in NOTRunning
3523  * state, then enable port interrupt and clear Serror register. And under
3524  * AHCI_ATTACH case, find device signature and then try to start the port.
3525  *
3526  * Called by
3527  *    1. ahci_initialize_controller
3528  *    2. ahci_intr_phyrdy_change (hotplug)
3529  *
3530  * WARNING!!! ahciport_mutex should be acquired before the function is called.
3531  */
3532 static int
3533 ahci_initialize_port(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
3534     ahci_addr_t *addrp)
3535 {
3536 	uint32_t port_sstatus, port_task_file, port_cmd_status;
3537 	uint8_t port = addrp->aa_port;
3538 	boolean_t pm_mode = B_TRUE;	/* Power Management mode */
3539 	int ret;
3540 
3541 	ASSERT(mutex_owned(&ahci_portp->ahciport_mutex));
3542 
3543 	/* AHCI_ADDR_PORT: We've no idea of the attached device here.  */
3544 	ASSERT(AHCI_ADDR_IS_PORT(addrp));
3545 
3546 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3547 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3548 
3549 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3550 	    "ahci_initialize_port: port %d ", port);
3551 
3552 	/*
3553 	 * Check whether the port is in NotRunning state, if not,
3554 	 * put the port in NotRunning state
3555 	 */
3556 	if (port_cmd_status &
3557 	    (AHCI_CMD_STATUS_ST |
3558 	    AHCI_CMD_STATUS_CR |
3559 	    AHCI_CMD_STATUS_FRE |
3560 	    AHCI_CMD_STATUS_FR)) {
3561 		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
3562 		    ahci_portp, port);
3563 	}
3564 
3565 	/* Disable interrupt */
3566 	ahci_disable_port_intrs(ahci_ctlp, port);
3567 
3568 	/* Device is unknown at first */
3569 	AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_UNKNOWN);
3570 
3571 	/* Disable the interface power management */
3572 	ahci_disable_interface_pm(ahci_ctlp, port);
3573 
3574 	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3575 	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
3576 	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3577 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3578 
3579 	/* Check physcial link status */
3580 	if (SSTATUS_GET_IPM(port_sstatus) == SSTATUS_IPM_NODEV_NOPHYCOM ||
3581 	    SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_NOPHYCOM ||
3582 
3583 	    /* Check interface status */
3584 	    port_task_file & AHCI_TFD_STS_BSY ||
3585 	    port_task_file & AHCI_TFD_STS_DRQ ||
3586 
3587 	    /* Check whether port reset must be executed */
3588 	    ahci_ctlp->ahcictl_cap & AHCI_CAP_INIT_PORT_RESET) {
3589 
3590 		/* Something went wrong, we need do some reset things */
3591 		ret = ahci_port_reset(ahci_ctlp, ahci_portp, addrp);
3592 
3593 		/* Does port reset succeed on HBA port? */
3594 		if (ret != AHCI_SUCCESS) {
3595 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
3596 			    "ahci_initialize_port:"
3597 			    "port reset faild at port %d", port);
3598 			return (AHCI_FAILURE);
3599 		}
3600 
3601 		/* Is port failed? */
3602 		if (AHCIPORT_GET_STATE(ahci_portp, addrp) &
3603 		    SATA_PSTATE_FAILED) {
3604 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
3605 			    "ahci_initialize_port: port %d state 0x%x",
3606 			    port, ahci_portp->ahciport_port_state);
3607 			return (AHCI_FAILURE);
3608 		}
3609 	}
3610 	AHCIPORT_SET_STATE(ahci_portp, addrp, SATA_STATE_READY);
3611 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "port %d is ready now.", port);
3612 
3613 	/*
3614 	 * At the time being, only probe ports/devices and get the types of
3615 	 * attached devices during DDI_ATTACH. In fact, the device can be
3616 	 * changed during power state changes, but at the time being, we
3617 	 * don't support the situation.
3618 	 */
3619 	mutex_exit(&ahci_portp->ahciport_mutex);
3620 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3621 	if (ahci_ctlp->ahcictl_flags & AHCI_ATTACH)
3622 		pm_mode = B_FALSE;
3623 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3624 	mutex_enter(&ahci_portp->ahciport_mutex);
3625 
3626 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_HOTPLUG)
3627 		pm_mode = B_FALSE;
3628 
3629 	if (!pm_mode) {
3630 		/*
3631 		 * Try to get the device signature if the port is
3632 		 * not empty.
3633 		 */
3634 		if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE)
3635 			ahci_find_dev_signature(ahci_ctlp, ahci_portp, addrp);
3636 	} else {
3637 
3638 		/*
3639 		 * During the resume, we need to set the PxCLB, PxCLBU, PxFB
3640 		 * and PxFBU registers in case these registers were cleared
3641 		 * during the suspend.
3642 		 */
3643 		AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3644 		    "ahci_initialize_port: port %d "
3645 		    "reset the port during resume", port);
3646 		(void) ahci_port_reset(ahci_ctlp, ahci_portp, addrp);
3647 
3648 		AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3649 		    "ahci_initialize_port: port %d "
3650 		    "set PxCLB, PxCLBU, PxFB and PxFBU "
3651 		    "during resume", port);
3652 
3653 		/* Config Port Received FIS Base Address */
3654 		ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
3655 		    (uint64_t *)AHCI_PORT_PxFB(ahci_ctlp, port),
3656 		    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
3657 
3658 		/* Config Port Command List Base Address */
3659 		ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
3660 		    (uint64_t *)AHCI_PORT_PxCLB(ahci_ctlp, port),
3661 		    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
3662 	}
3663 
3664 	/* Return directly if no device connected */
3665 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
3666 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3667 		    "No device connected to port %d", port);
3668 		goto out;
3669 	}
3670 
3671 	/* If this is a port multiplier, we need do some initialization */
3672 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_PMULT) {
3673 		AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
3674 		    "Port multiplier found at port %d", port);
3675 		ahci_alloc_pmult(ahci_ctlp, ahci_portp);
3676 	}
3677 
3678 	/* Try to start the port */
3679 	if (ahci_start_port(ahci_ctlp, ahci_portp, port)
3680 	    != AHCI_SUCCESS) {
3681 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3682 		    "failed to start port %d", port);
3683 		return (AHCI_FAILURE);
3684 	}
3685 out:
3686 	/* Enable port interrupts */
3687 	ahci_enable_port_intrs(ahci_ctlp, port);
3688 
3689 	return (AHCI_SUCCESS);
3690 }
3691 
3692 /*
3693  *  Handle hardware defect, and check the capabilities. For example,
3694  *  power management capabilty and MSI capability.
3695  */
3696 static int
3697 ahci_config_space_init(ahci_ctl_t *ahci_ctlp)
3698 {
3699 	ushort_t venid, devid;
3700 	ushort_t caps_ptr, cap_count, cap;
3701 #if AHCI_DEBUG
3702 	ushort_t pmcap, pmcsr;
3703 	ushort_t msimc;
3704 #endif
3705 	uint8_t revision;
3706 
3707 	venid = pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3708 	    PCI_CONF_VENID);
3709 
3710 	devid = pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3711 	    PCI_CONF_DEVID);
3712 
3713 	/*
3714 	 * Modify dma_attr_align of ahcictl_buffer_dma_attr. For VT8251, those
3715 	 * controllers with 0x00 revision id work on 4-byte aligned buffer,
3716 	 * which is a bug and was fixed after 0x00 revision id controllers.
3717 	 *
3718 	 * Moreover, VT8251 cannot use multiple command slots in the command
3719 	 * list for non-queued commands because the previous register content
3720 	 * of PxCI can be re-written in the register write, so a flag will be
3721 	 * set to record this defect - AHCI_CAP_NO_MCMDLIST_NONQUEUE.
3722 	 */
3723 	if (venid == VIA_VENID) {
3724 		revision = pci_config_get8(ahci_ctlp->ahcictl_pci_conf_handle,
3725 		    PCI_CONF_REVID);
3726 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3727 		    "revision id = 0x%x", revision);
3728 		if (revision == 0x00) {
3729 			ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_align = 0x4;
3730 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3731 			    "change ddi_attr_align to 0x4", NULL);
3732 		}
3733 
3734 		ahci_ctlp->ahcictl_cap = AHCI_CAP_NO_MCMDLIST_NONQUEUE;
3735 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3736 		    "VT8251 cannot use multiple command lists for "
3737 		    "non-queued commands", NULL);
3738 	}
3739 
3740 	/*
3741 	 * AMD/ATI SB600 (1002,4380) AHCI chipset doesn't support 64-bit DMA
3742 	 * addressing for both data buffer and communication memory descriptors
3743 	 * though S64A bit of CAP register declares the support.
3744 	 *
3745 	 * We found this chipset must do port reset during initialization,
3746 	 * otherwise, when retrieving device signature, software reset will
3747 	 * get time out.
3748 	 */
3749 	if (venid == 0x1002 && devid == 0x4380) {
3750 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3751 		    "ATI SB600 cannot do 64-bit DMA for both data buffer "
3752 		    "and communication memory descriptors though CAP indicates "
3753 		    "support, so force it to use 32-bit DMA", NULL);
3754 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_BUF_32BIT_DMA;
3755 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
3756 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_INIT_PORT_RESET;
3757 	}
3758 
3759 	/*
3760 	 * AMD/ATI SB700/750 (1002,4391) AHCI chipset doesn't support 64-bit
3761 	 * DMA addressing for communication memory descriptors though S64A bit
3762 	 * of CAP register declares the support. However, it does support
3763 	 * 64-bit DMA for data buffer.
3764 	 */
3765 	if (venid == 0x1002 && devid == 0x4391) {
3766 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3767 		    "ATI SB700/750 cannot do 64-bit DMA for communication "
3768 		    "memory descriptors though CAP indicates support, "
3769 		    "so force it to use 32-bit DMA", NULL);
3770 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
3771 	}
3772 
3773 	/*
3774 	 * Check if capabilities list is supported and if so,
3775 	 * get initial capabilities pointer and clear bits 0,1.
3776 	 */
3777 	if (pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3778 	    PCI_CONF_STAT) & PCI_STAT_CAP) {
3779 		caps_ptr = P2ALIGN(pci_config_get8(
3780 		    ahci_ctlp->ahcictl_pci_conf_handle,
3781 		    PCI_CONF_CAP_PTR), 4);
3782 	} else {
3783 		caps_ptr = PCI_CAP_NEXT_PTR_NULL;
3784 	}
3785 
3786 	/*
3787 	 * Walk capabilities if supported.
3788 	 */
3789 	for (cap_count = 0; caps_ptr != PCI_CAP_NEXT_PTR_NULL; ) {
3790 
3791 		/*
3792 		 * Check that we haven't exceeded the maximum number of
3793 		 * capabilities and that the pointer is in a valid range.
3794 		 */
3795 		if (++cap_count > PCI_CAP_MAX_PTR) {
3796 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3797 			    "too many device capabilities", NULL);
3798 			return (AHCI_FAILURE);
3799 		}
3800 		if (caps_ptr < PCI_CAP_PTR_OFF) {
3801 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3802 			    "capabilities pointer 0x%x out of range",
3803 			    caps_ptr);
3804 			return (AHCI_FAILURE);
3805 		}
3806 
3807 		/*
3808 		 * Get next capability and check that it is valid.
3809 		 * For now, we only support power management.
3810 		 */
3811 		cap = pci_config_get8(ahci_ctlp->ahcictl_pci_conf_handle,
3812 		    caps_ptr);
3813 		switch (cap) {
3814 		case PCI_CAP_ID_PM:
3815 
3816 			/* power management supported */
3817 			ahci_ctlp->ahcictl_cap |= AHCI_CAP_PM;
3818 
3819 			/* Save PMCSR offset */
3820 			ahci_ctlp->ahcictl_pmcsr_offset = caps_ptr + PCI_PMCSR;
3821 
3822 #if AHCI_DEBUG
3823 			pmcap = pci_config_get16(
3824 			    ahci_ctlp->ahcictl_pci_conf_handle,
3825 			    caps_ptr + PCI_PMCAP);
3826 			pmcsr = pci_config_get16(
3827 			    ahci_ctlp->ahcictl_pci_conf_handle,
3828 			    ahci_ctlp->ahcictl_pmcsr_offset);
3829 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3830 			    "Power Management capability found PCI_PMCAP "
3831 			    "= 0x%x PCI_PMCSR = 0x%x", pmcap, pmcsr);
3832 			if ((pmcap & 0x3) == 0x3)
3833 				AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3834 				    "PCI Power Management Interface "
3835 				    "spec 1.2 compliant", NULL);
3836 #endif
3837 			break;
3838 
3839 		case PCI_CAP_ID_MSI:
3840 #if AHCI_DEBUG
3841 			msimc = pci_config_get16(
3842 			    ahci_ctlp->ahcictl_pci_conf_handle,
3843 			    caps_ptr + PCI_MSI_CTRL);
3844 			AHCIDBG(AHCIDBG_MSI, ahci_ctlp,
3845 			    "Message Signaled Interrupt capability found "
3846 			    "MSICAP_MC.MMC = 0x%x", (msimc & 0xe) >> 1);
3847 #endif
3848 			AHCIDBG(AHCIDBG_MSI, ahci_ctlp,
3849 			    "MSI capability found", NULL);
3850 			break;
3851 
3852 		case PCI_CAP_ID_PCIX:
3853 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3854 			    "PCI-X capability found", NULL);
3855 			break;
3856 
3857 		case PCI_CAP_ID_PCI_E:
3858 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3859 			    "PCI Express capability found", NULL);
3860 			break;
3861 
3862 		case PCI_CAP_ID_MSI_X:
3863 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3864 			    "MSI-X capability found", NULL);
3865 			break;
3866 
3867 		case PCI_CAP_ID_SATA:
3868 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3869 			    "SATA capability found", NULL);
3870 			break;
3871 
3872 		case PCI_CAP_ID_VS:
3873 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3874 			    "Vendor Specific capability found", NULL);
3875 			break;
3876 
3877 		default:
3878 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3879 			    "unrecognized capability 0x%x", cap);
3880 			break;
3881 		}
3882 
3883 		/*
3884 		 * Get next capabilities pointer and clear bits 0,1.
3885 		 */
3886 		caps_ptr = P2ALIGN(pci_config_get8(
3887 		    ahci_ctlp->ahcictl_pci_conf_handle,
3888 		    (caps_ptr + PCI_CAP_NEXT_PTR)), 4);
3889 	}
3890 
3891 	return (AHCI_SUCCESS);
3892 }
3893 
3894 /*
3895  * Read/Write a register at port multiplier by SATA READ PORTMULT / SATA WRITE
3896  * PORTMULT command. SYNC & POLLING mode is used.
3897  *
3898  * WARNING!!! ahciport_mutex should be acquired before the function
3899  * is called.
3900  */
3901 static int
3902 ahci_rdwr_pmult(ahci_ctl_t *ahci_ctlp, ahci_addr_t *addrp,
3903     uint8_t regn, uint32_t *pregv, uint8_t type)
3904 {
3905 	ahci_port_t *ahci_portp;
3906 	ahci_addr_t pmult_addr;
3907 	sata_pkt_t *spkt;
3908 	sata_cmd_t *scmd;
3909 	sata_device_t sata_device;
3910 	uint8_t port = addrp->aa_port;
3911 	uint8_t pmport = addrp->aa_pmport;
3912 	uint8_t cport;
3913 	uint32_t intr_mask;
3914 	int rval;
3915 	char portstr[10];
3916 
3917 	SET_PORTSTR(portstr, addrp);
3918 	cport = ahci_ctlp->ahcictl_port_to_cport[port];
3919 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
3920 
3921 	ASSERT(AHCI_ADDR_IS_PMPORT(addrp) || AHCI_ADDR_IS_PMULT(addrp));
3922 	ASSERT(mutex_owned(&ahci_portp->ahciport_mutex));
3923 
3924 	/* Check the existence of the port multiplier */
3925 	if (ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT)
3926 		return (AHCI_FAILURE);
3927 
3928 	/* Request a READ/WRITE PORTMULT sata packet. */
3929 	bzero(&sata_device, sizeof (sata_device_t));
3930 	sata_device.satadev_addr.cport = cport;
3931 	sata_device.satadev_addr.pmport = pmport;
3932 	sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
3933 	sata_device.satadev_rev = SATA_DEVICE_REV;
3934 
3935 	/*
3936 	 * Make sure no command is outstanding here. All R/W PMULT requests
3937 	 * come from
3938 	 *
3939 	 * 1. ahci_attach()
3940 	 *    The port should be empty.
3941 	 *
3942 	 * 2. ahci_tran_probe_port()
3943 	 *    Any request from SATA framework (via ahci_tran_start) should be
3944 	 *    rejected if R/W PMULT command is outstanding.
3945 	 *
3946 	 *    If we are doing mopping, do not check those flags because no
3947 	 *    command will be actually outstanding.
3948 	 *
3949 	 *    If the port has been occupied by any other commands, the probe
3950 	 *    function will return a SATA_RETRY. SATA framework will retry
3951 	 *    later.
3952 	 */
3953 	if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
3954 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
3955 		    "R/W PMULT failed: R/W PMULT in progress at port %d.",
3956 		    port, ahci_portp->ahciport_flags);
3957 		return (AHCI_FAILURE);
3958 	}
3959 
3960 	if (!(ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) && (
3961 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) ||
3962 	    NCQ_CMD_IN_PROGRESS(ahci_portp) ||
3963 	    NON_NCQ_CMD_IN_PROGRESS(ahci_portp))) {
3964 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
3965 		    "R/W PMULT failed: port %d is occupied (flags 0x%x).",
3966 		    port, ahci_portp->ahciport_flags);
3967 		return (AHCI_FAILURE);
3968 	}
3969 
3970 	/*
3971 	 * The port multiplier is gone. This may happen when
3972 	 * 1. Cutting off the power of an enclosure. The device lose the power
3973 	 *    before port multiplier.
3974 	 * 2. Disconnecting the port multiplier during hot-plugging a sub-drive.
3975 	 *
3976 	 * The issued command should be aborted and the following command
3977 	 * should not be continued.
3978 	 */
3979 	if (!(ahci_portp->ahciport_port_state & SATA_STATE_READY)) {
3980 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
3981 		    "READ/WRITE PMULT failed: "
3982 		    "port-mult is removed from port %d", port);
3983 		return (AHCI_FAILURE);
3984 	}
3985 
3986 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RDWR_PMULT;
3987 
3988 	spkt = sata_get_rdwr_pmult_pkt(ahci_ctlp->ahcictl_dip,
3989 	    &sata_device, regn, *pregv, type);
3990 
3991 	/*
3992 	 * READ/WRITE PORTMULT command is intended to sent to the control port
3993 	 * of the port multiplier.
3994 	 */
3995 	AHCI_ADDR_SET_PMULT(&pmult_addr, addrp->aa_port);
3996 
3997 	ahci_portp->ahciport_rdwr_pmult_pkt = spkt;
3998 
3999 	/* No interrupt here. Store the interrupt enable mask. */
4000 	intr_mask = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4001 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port));
4002 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4003 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port), 0);
4004 
4005 	rval = ahci_do_sync_start(ahci_ctlp, ahci_portp, &pmult_addr, spkt);
4006 
4007 	if (rval == AHCI_SUCCESS &&
4008 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
4009 		if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
4010 			scmd = &spkt->satapkt_cmd;
4011 			*pregv = scmd->satacmd_lba_high_lsb << 24 |
4012 			    scmd->satacmd_lba_mid_lsb << 16 |
4013 			    scmd->satacmd_lba_low_lsb << 8 |
4014 			    scmd->satacmd_sec_count_lsb;
4015 		}
4016 	} else {
4017 		/* Failed or not completed. */
4018 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
4019 		    "ahci_rdwr_pmult: cannot [%s] %s[%d] at port %s",
4020 		    type == SATA_RDWR_PMULT_PKT_TYPE_READ?"Read":"Write",
4021 		    AHCI_ADDR_IS_PMULT(addrp)?"gscr":"pscr", regn, portstr);
4022 		rval = AHCI_FAILURE;
4023 	}
4024 out:
4025 	/* Restore the interrupt mask */
4026 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4027 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port), intr_mask);
4028 
4029 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_RDWR_PMULT;
4030 	ahci_portp->ahciport_rdwr_pmult_pkt = NULL;
4031 	sata_free_rdwr_pmult_pkt(spkt);
4032 	return (rval);
4033 }
4034 
4035 static int
4036 ahci_read_pmult(ahci_ctl_t *ahci_ctlp, ahci_addr_t *addrp,
4037     uint8_t regn, uint32_t *pregv)
4038 {
4039 	return ahci_rdwr_pmult(ahci_ctlp, addrp, regn, pregv,
4040 	    SATA_RDWR_PMULT_PKT_TYPE_READ);
4041 }
4042 
4043 static int
4044 ahci_write_pmult(ahci_ctl_t *ahci_ctlp, ahci_addr_t *addrp,
4045     uint8_t regn, uint32_t regv)
4046 {
4047 	return ahci_rdwr_pmult(ahci_ctlp, addrp, regn, &regv,
4048 	    SATA_RDWR_PMULT_PKT_TYPE_WRITE);
4049 }
4050 
4051 #define	READ_PMULT(addrp, r, pv, out)					\
4052 	if (ahci_read_pmult(ahci_ctlp, addrp, r, pv) != AHCI_SUCCESS)	\
4053 		goto out;
4054 
4055 #define	WRITE_PMULT(addrp, r, v, out)					\
4056 	if (ahci_write_pmult(ahci_ctlp, addrp, r, v) != AHCI_SUCCESS)	\
4057 		goto out;
4058 
4059 /*
4060  * Update sata registers on port multiplier, including GSCR/PSCR registers.
4061  * ahci_update_pmult_gscr()
4062  * ahci_update_pmult_pscr()
4063  *
4064  * WARNING!!! ahciport_mutex should be acquired before those functions
4065  * get called.
4066  */
4067 static int
4068 ahci_update_pmult_gscr(ahci_ctl_t *ahci_ctlp, ahci_addr_t *addrp,
4069     sata_device_t *sd)
4070 {
4071 	READ_PMULT(addrp, SATA_PMULT_GSCR0, &sd->satadev_gscr.gscr0, err);
4072 	READ_PMULT(addrp, SATA_PMULT_GSCR1, &sd->satadev_gscr.gscr1, err);
4073 	READ_PMULT(addrp, SATA_PMULT_GSCR2, &sd->satadev_gscr.gscr2, err);
4074 	READ_PMULT(addrp, SATA_PMULT_GSCR64, &sd->satadev_gscr.gscr64, err);
4075 
4076 	return (AHCI_SUCCESS);
4077 
4078 err:	/* R/W PMULT error */
4079 	return (AHCI_FAILURE);
4080 }
4081 
4082 static int
4083 ahci_update_pmult_pscr(ahci_ctl_t *ahci_ctlp, ahci_addr_t *addrp,
4084     sata_device_t *sd)
4085 {
4086 	ASSERT(AHCI_ADDR_IS_PMPORT(addrp));
4087 
4088 	READ_PMULT(addrp, SATA_PMULT_REG_SSTS, &sd->satadev_scr.sstatus, err);
4089 	READ_PMULT(addrp, SATA_PMULT_REG_SERR, &sd->satadev_scr.serror, err);
4090 	READ_PMULT(addrp, SATA_PMULT_REG_SCTL, &sd->satadev_scr.scontrol, err);
4091 	READ_PMULT(addrp, SATA_PMULT_REG_SACT, &sd->satadev_scr.sactive, err);
4092 
4093 	return (AHCI_SUCCESS);
4094 
4095 err:	/* R/W PMULT error */
4096 	return (AHCI_FAILURE);
4097 }
4098 
4099 /*
4100  * ahci_initialize_pmult()
4101  *
4102  * Initialize a port multiplier, including
4103  * 1. Enable FEATURES register at port multiplier. (SATA Chp.16)
4104  * 2. Redefine MASK register. (SATA Chap 16.?)
4105  *
4106  * WARNING!!! ahciport_mutex should be acquired before the function
4107  * is called.
4108  */
4109 static int
4110 ahci_initialize_pmult(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4111     ahci_addr_t *addrp, sata_device_t *sd)
4112 {
4113 	uint32_t gscr64;
4114 	uint8_t port = addrp->aa_port;
4115 
4116 	ASSERT(mutex_owned(&ahci_portp->ahciport_mutex));
4117 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
4118 	    "[Initialize] Port-multiplier at port %d.", port);
4119 
4120 	/*
4121 	 * Enable features of port multiplier. Currently only
4122 	 * Asynchronous Notification is enabled.
4123 	 */
4124 	/* Check gscr64 for supported features. */
4125 	READ_PMULT(addrp, SATA_PMULT_GSCR64, &gscr64, err);
4126 
4127 	if (gscr64 & SATA_PMULT_CAP_SNOTIF) {
4128 		AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
4129 		    "port %d: Port Multiplier supports "
4130 		    "Asynchronous Notification.", port);
4131 
4132 		/* Write to gscr96 to enabled features */
4133 		WRITE_PMULT(addrp, SATA_PMULT_GSCR96,
4134 		    SATA_PMULT_CAP_SNOTIF, err);
4135 
4136 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4137 		    (uint32_t *)AHCI_PORT_PxSNTF(ahci_ctlp, port),
4138 		    AHCI_SNOTIF_CLEAR_ALL);
4139 		AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
4140 		    "port %d: PMult PxSNTF cleared.", port);
4141 
4142 	}
4143 
4144 	/*
4145 	 * Now we need to update gscr33 register to enable hot-plug interrupt
4146 	 * for sub devices behind port multiplier.
4147 	 */
4148 	WRITE_PMULT(addrp, SATA_PMULT_GSCR33, (0x1ffff), err);
4149 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
4150 	    "port %d: gscr33 mask set to %x.", port, (0x1ffff));
4151 
4152 	/*
4153 	 * Fetch the number of device ports of the port multiplier
4154 	 */
4155 	if (ahci_update_pmult_gscr(ahci_ctlp, addrp, sd) != AHCI_SUCCESS)
4156 		return (AHCI_FAILURE);
4157 
4158 	/* If it's not in the blacklist, use the value in GSCR2 */
4159 	if (sata_check_pmult_blacklist(sd) == SATA_FAILURE)
4160 		sd->satadev_add_info = sd->satadev_gscr.gscr2 &
4161 		    SATA_PMULT_PORTNUM_MASK;
4162 
4163 	ahci_portp->ahciport_pmult_info->ahcipmi_num_dev_ports =
4164 	    sd->satadev_add_info;
4165 
4166 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
4167 	    "port %d: pmult sub-port number updated to %x.", port,
4168 	    ahci_portp->ahciport_pmult_info->ahcipmi_num_dev_ports);
4169 
4170 	/* Till now port-mult is successfully initialized */
4171 	ahci_portp->ahciport_port_state |= SATA_DSTATE_PMULT_INIT;
4172 	return (AHCI_SUCCESS);
4173 
4174 err:	/* R/W PMULT error */
4175 	return (AHCI_FAILURE);
4176 }
4177 
4178 /*
4179  * Initialize a port multiplier port. According to spec, firstly we need
4180  * issue a COMRESET, then a software reset to get its signature.
4181  *
4182  * NOTE: This function should only be called in ahci_probe_pmport()
4183  * WARNING!!! ahciport_mutex should be acquired before the function.
4184  */
4185 static int
4186 ahci_initialize_pmport(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4187     ahci_addr_t *addrp)
4188 {
4189 	uint32_t finished_tags = 0, reset_tags = 0, slot_status = 0;
4190 	uint8_t port = addrp->aa_port;
4191 	uint8_t pmport = addrp->aa_pmport;
4192 	int ret = AHCI_FAILURE;
4193 
4194 	ASSERT(AHCI_ADDR_IS_PMPORT(addrp));
4195 
4196 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
4197 	    "ahci_initialize_pmport: port %d:%d", port, pmport);
4198 
4199 	/* Check HBA port state */
4200 	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED) {
4201 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
4202 		    "ahci_initialize_pmport:"
4203 		    "port %d:%d Port Multiplier is failed.",
4204 		    port, pmport);
4205 		return (AHCI_FAILURE);
4206 	}
4207 
4208 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_HOTPLUG) {
4209 		return (AHCI_FAILURE);
4210 	}
4211 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_HOTPLUG;
4212 
4213 	/* Checking for outstanding commands */
4214 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
4215 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4216 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4217 		reset_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
4218 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
4219 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4220 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
4221 		reset_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
4222 	}
4223 
4224 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
4225 	ahci_portp->ahciport_mop_in_progress++;
4226 
4227 	/* Clear status */
4228 	AHCIPORT_SET_STATE(ahci_portp, addrp, SATA_STATE_UNKNOWN);
4229 
4230 	/* Firstly assume an unknown device */
4231 	AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_UNKNOWN);
4232 
4233 	ahci_disable_port_intrs(ahci_ctlp, port);
4234 
4235 	/* port reset is necessary for port multiplier port */
4236 	if (ahci_pmport_reset(ahci_ctlp, ahci_portp, addrp) != AHCI_SUCCESS) {
4237 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
4238 		    "ahci_initialize_pmport:"
4239 		    "port reset failed at port %d:%d",
4240 		    port, pmport);
4241 		goto out;
4242 	}
4243 
4244 	/* Is port failed? */
4245 	if (AHCIPORT_GET_STATE(ahci_portp, addrp) &
4246 	    SATA_PSTATE_FAILED) {
4247 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4248 		    "ahci_initialize_pmport: port %d:%d failed. "
4249 		    "state = 0x%x", port, pmport,
4250 		    ahci_portp->ahciport_port_state);
4251 		goto out;
4252 	}
4253 
4254 	/* Is there any device attached? */
4255 	if (AHCIPORT_GET_DEV_TYPE(ahci_portp, addrp)
4256 	    == SATA_DTYPE_NONE) {
4257 		/* Do not waste time on an empty port */
4258 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
4259 		    "ahci_initialize_pmport: No device is found "
4260 		    "at port %d:%d", port, pmport);
4261 		ret = AHCI_SUCCESS;
4262 		goto out;
4263 	}
4264 
4265 	AHCIPORT_SET_STATE(ahci_portp, addrp, SATA_STATE_READY);
4266 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4267 	    "port %d:%d is ready now.", port, pmport);
4268 
4269 	/*
4270 	 * Till now we can assure a device attached to that HBA port and work
4271 	 * correctly. Now try to get the device signature. This is an optional
4272 	 * step. If failed, unknown device is assumed, then SATA module will
4273 	 * continue to use IDENTIFY DEVICE to get the information of the
4274 	 * device.
4275 	 */
4276 	ahci_find_dev_signature(ahci_ctlp, ahci_portp, addrp);
4277 
4278 	ret = AHCI_SUCCESS;
4279 
4280 out:
4281 	/* Next try to mop the pending commands */
4282 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
4283 		finished_tags = ahci_portp->ahciport_pending_tags &
4284 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
4285 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
4286 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
4287 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
4288 	reset_tags &= ~finished_tags;
4289 
4290 	ahci_mop_commands(ahci_ctlp,
4291 	    ahci_portp,
4292 	    slot_status,
4293 	    0, /* failed tags */
4294 	    0, /* timeout tags */
4295 	    0, /* aborted tags */
4296 	    reset_tags); /* reset tags */
4297 
4298 	/* Clear PxSNTF register if supported. */
4299 	if (ahci_ctlp->ahcictl_cap & AHCI_CAP_SNTF) {
4300 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4301 		    (uint32_t *)AHCI_PORT_PxSNTF(ahci_ctlp, port),
4302 		    AHCI_SNOTIF_CLEAR_ALL);
4303 	}
4304 
4305 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_HOTPLUG;
4306 	ahci_enable_port_intrs(ahci_ctlp, port);
4307 	return (ret);
4308 }
4309 
4310 /*
4311  * ahci_probe_pmult()
4312  *
4313  * This function will be called to probe a port multiplier, which will
4314  * handle hotplug events on port multiplier ports.
4315  *
4316  * NOTE: Only called from ahci_tran_probe_port()
4317  * WARNING!!! ahciport_mutex should be acquired before the function is called.
4318  */
4319 static int
4320 ahci_probe_pmult(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4321     ahci_addr_t *addrp)
4322 {
4323 	sata_device_t sdevice;
4324 	ahci_addr_t pmport_addr;
4325 	uint32_t gscr32, port_hotplug_tags;
4326 	uint32_t pmport_sstatus;
4327 	int dev_exists_now = 0, dev_existed_previously = 0;
4328 	uint8_t port = addrp->aa_port;
4329 	int npmport;
4330 
4331 	/* The bits in GSCR32 refers to the pmport that has a hot-plug event. */
4332 	READ_PMULT(addrp, SATA_PMULT_GSCR32, &gscr32, err);
4333 	port_hotplug_tags = gscr32 & AHCI_PMPORT_MASK(ahci_portp);
4334 
4335 	do {
4336 		npmport = ddi_ffs(port_hotplug_tags) - 1;
4337 		if (npmport == -1)
4338 			/* no pending hot plug events. */
4339 			return (AHCI_SUCCESS);
4340 
4341 		AHCIDBG(AHCIDBG_EVENT|AHCIDBG_PMULT, ahci_ctlp,
4342 		    "hot-plug event at port %d:%d", port, npmport);
4343 
4344 		AHCI_ADDR_SET_PMPORT(&pmport_addr, port, (uint8_t)npmport);
4345 
4346 		/* Check previous device at that port */
4347 		if (AHCIPORT_GET_DEV_TYPE(ahci_portp, &pmport_addr)
4348 		    != SATA_DTYPE_NONE)
4349 			dev_existed_previously = 1;
4350 
4351 		/* PxSStatus tells the presence of device. */
4352 		READ_PMULT(&pmport_addr, SATA_PMULT_REG_SSTS,
4353 		    &pmport_sstatus, err);
4354 
4355 		if (SSTATUS_GET_DET(pmport_sstatus) ==
4356 		    SSTATUS_DET_DEVPRE_PHYCOM)
4357 			dev_exists_now = 1;
4358 
4359 		/*
4360 		 * Clear PxSERR is critical. The transition from 0 to 1 will
4361 		 * emit a FIS which generates an asynchronous notification
4362 		 * event at controller. If we fail to clear the PxSERR, the
4363 		 * Async Notif events will no longer be activated on this
4364 		 * pmport.
4365 		 */
4366 		WRITE_PMULT(&pmport_addr, SATA_PMULT_REG_SERR,
4367 		    AHCI_SERROR_CLEAR_ALL, err);
4368 
4369 		bzero((void *)&sdevice, sizeof (sata_device_t));
4370 		sdevice.satadev_addr.cport = ahci_ctlp->
4371 		    ahcictl_port_to_cport[port];
4372 		sdevice.satadev_addr.qual = SATA_ADDR_PMPORT;
4373 		sdevice.satadev_addr.pmport = (uint8_t)npmport;
4374 		sdevice.satadev_state = SATA_PSTATE_PWRON;
4375 
4376 		AHCIDBG(AHCIDBG_EVENT|AHCIDBG_PMULT, ahci_ctlp,
4377 		    "[Existence] %d -> %d", dev_existed_previously,
4378 		    dev_exists_now);
4379 
4380 		if (dev_exists_now) {
4381 			if (dev_existed_previously) {
4382 				/* Link (may) not change: Exist -> Exist * */
4383 				AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
4384 				    "ahci_probe_pmult: port %d:%d "
4385 				    "device link lost/established",
4386 				    port, npmport);
4387 
4388 				mutex_exit(&ahci_portp->ahciport_mutex);
4389 				sata_hba_event_notify(
4390 				    ahci_ctlp->ahcictl_sata_hba_tran->
4391 				    sata_tran_hba_dip,
4392 				    &sdevice,
4393 				    SATA_EVNT_LINK_LOST|
4394 				    SATA_EVNT_LINK_ESTABLISHED);
4395 				mutex_enter(&ahci_portp->ahciport_mutex);
4396 			} else {
4397 				/* Link change: None -> Exist */
4398 				AHCIDBG(AHCIDBG_EVENT|AHCIDBG_PMULT, ahci_ctlp,
4399 				    "ahci_probe_pmult: port %d:%d "
4400 				    "device link established", port, npmport);
4401 
4402 				/* Clear port state */
4403 				AHCIPORT_SET_STATE(ahci_portp, &pmport_addr,
4404 				    SATA_STATE_UNKNOWN);
4405 				AHCIDBG(AHCIDBG_EVENT|AHCIDBG_PMULT, ahci_ctlp,
4406 				    "ahci_probe_pmult: port %d "
4407 				    "ahciport_port_state [Cleared].", port);
4408 
4409 				mutex_exit(&ahci_portp->ahciport_mutex);
4410 				sata_hba_event_notify(
4411 				    ahci_ctlp->ahcictl_sata_hba_tran->
4412 				    sata_tran_hba_dip,
4413 				    &sdevice,
4414 				    SATA_EVNT_LINK_ESTABLISHED);
4415 				mutex_enter(&ahci_portp->ahciport_mutex);
4416 			}
4417 		} else { /* No device exists now */
4418 			if (dev_existed_previously) {
4419 
4420 				/* Link change: Exist -> None */
4421 				AHCIDBG(AHCIDBG_EVENT|AHCIDBG_PMULT, ahci_ctlp,
4422 				    "ahci_probe_pmult: port %d:%d "
4423 				    "device link lost", port, npmport);
4424 
4425 				/* An existing device is lost. */
4426 				AHCIPORT_SET_STATE(ahci_portp, &pmport_addr,
4427 				    SATA_STATE_UNKNOWN);
4428 				AHCIPORT_SET_DEV_TYPE(ahci_portp, &pmport_addr,
4429 				    SATA_DTYPE_NONE);
4430 
4431 				mutex_exit(&ahci_portp->ahciport_mutex);
4432 				sata_hba_event_notify(
4433 				    ahci_ctlp->ahcictl_sata_hba_tran->
4434 				    sata_tran_hba_dip,
4435 				    &sdevice,
4436 				    SATA_EVNT_LINK_LOST);
4437 				mutex_enter(&ahci_portp->ahciport_mutex);
4438 			}
4439 		}
4440 
4441 		CLEAR_BIT(port_hotplug_tags, npmport);
4442 	} while (port_hotplug_tags != 0);
4443 
4444 	return (AHCI_SUCCESS);
4445 
4446 err:	/* R/W PMULT error */
4447 	return (AHCI_FAILURE);
4448 }
4449 
4450 /*
4451  * Probe and initialize a port multiplier port.
4452  * A port multiplier port could only be initilaizer here.
4453  *
4454  * WARNING!!! ahcictl_mutex should be acquired before the function
4455  * is called.
4456  */
4457 static int
4458 ahci_probe_pmport(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4459     ahci_addr_t *addrp, sata_device_t *sd)
4460 {
4461 	uint32_t port_state;
4462 	uint8_t port = addrp->aa_port;
4463 	ahci_addr_t addr_pmult;
4464 
4465 	/*
4466 	 * Check the parent - port multiplier first.
4467 	 */
4468 
4469 	/*
4470 	 * Parent port multiplier might have been removed. This event will be
4471 	 * ignored and failure.
4472 	 */
4473 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE ||
4474 	    ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT) {
4475 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
4476 		    "ahci_tran_probe_port: "
4477 		    "parent device removed, ignore event.", NULL);
4478 
4479 		return (AHCI_FAILURE);
4480 	}
4481 
4482 	/* The port is ready? */
4483 	port_state = ahci_portp->ahciport_port_state;
4484 	if (!(port_state & SATA_STATE_READY)) {
4485 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
4486 		    "ahci_tran_probe_port: "
4487 		    "parent port-mult is NOT ready.", NULL);
4488 
4489 		if (ahci_restart_port_wait_till_ready(ahci_ctlp,
4490 		    ahci_portp, port, AHCI_PORT_RESET, NULL) !=
4491 		    AHCI_SUCCESS) {
4492 			AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
4493 			    "ahci_tran_probe_port: "
4494 			    "restart port-mult failed.", NULL);
4495 			return (AHCI_FAILURE);
4496 		}
4497 	}
4498 
4499 	/*
4500 	 * If port-mult is restarted due to some reason, we need
4501 	 * re-initialized the PMult.
4502 	 */
4503 	if (!(port_state & SATA_DSTATE_PMULT_INIT)) {
4504 		/* Initialize registers on a port multiplier */
4505 		AHCI_ADDR_SET_PMULT(&addr_pmult, addrp->aa_port);
4506 		if (ahci_initialize_pmult(ahci_ctlp, ahci_portp,
4507 		    &addr_pmult, sd) != AHCI_SUCCESS)
4508 			return (AHCI_FAILURE);
4509 	}
4510 
4511 	/*
4512 	 * Then we check the port-mult port
4513 	 */
4514 	/* Is this pmport initialized? */
4515 	port_state = AHCIPORT_GET_STATE(ahci_portp, addrp);
4516 	if (!(port_state & SATA_STATE_READY)) {
4517 
4518 		/* ahci_initialize_pmport() will set READY state */
4519 		if (ahci_initialize_pmport(ahci_ctlp,
4520 		    ahci_portp, addrp) != AHCI_SUCCESS)
4521 			return (AHCI_FAILURE);
4522 	}
4523 
4524 	return (AHCI_SUCCESS);
4525 }
4526 
4527 /*
4528  * AHCI device reset ...; a single device on one of the ports is reset,
4529  * but the HBA and physical communication remain intact. This is the
4530  * least intrusive.
4531  *
4532  * When issuing a software reset sequence, there should not be other
4533  * commands in the command list, so we will first clear and then re-set
4534  * PxCMD.ST to clear PxCI. And before issuing the software reset,
4535  * the port must be idle and PxTFD.STS.BSY and PxTFD.STS.DRQ must be
4536  * cleared unless command list override (PxCMD.CLO) is supported.
4537  *
4538  * WARNING!!! ahciport_mutex should be acquired and PxCMD.FRE should be
4539  * set before the function is called.
4540  */
4541 static int
4542 ahci_software_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4543     ahci_addr_t *addrp)
4544 {
4545 	ahci_fis_h2d_register_t *h2d_register_fisp;
4546 	ahci_cmd_table_t *cmd_table;
4547 	ahci_cmd_header_t *cmd_header;
4548 	uint32_t port_cmd_status, port_cmd_issue, port_task_file;
4549 	int slot, loop_count;
4550 	uint8_t port = addrp->aa_port;
4551 	uint8_t pmport = addrp->aa_pmport;
4552 	int rval = AHCI_FAILURE;
4553 
4554 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
4555 	    "port %d:%d device software resetting (FIS)", port, pmport);
4556 
4557 	/* First clear PxCMD.ST (AHCI v1.2 10.4.1) */
4558 	if (ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp,
4559 	    port) != AHCI_SUCCESS) {
4560 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4561 		    "ahci_software_reset: cannot stop HBA port %d.", port);
4562 		goto out;
4563 	}
4564 
4565 	/* Check PxTFD.STS.BSY and PxTFD.STS.DRQ */
4566 	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4567 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
4568 
4569 	if (port_task_file & AHCI_TFD_STS_BSY ||
4570 	    port_task_file & AHCI_TFD_STS_DRQ) {
4571 		if (!(ahci_ctlp->ahcictl_cap & AHCI_CAP_SCLO)) {
4572 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4573 			    "PxTFD.STS.BSY/DRQ is set (PxTFD=0x%x), "
4574 			    "cannot issue a software reset.", port_task_file);
4575 			goto out;
4576 		}
4577 
4578 		/*
4579 		 * If HBA Support CLO, as Command List Override (CAP.SCLO is
4580 		 * set), PxCMD.CLO bit should be set before set PxCMD.ST, in
4581 		 * order to clear PxTFD.STS.BSY and PxTFD.STS.DRQ.
4582 		 */
4583 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4584 		    "PxTFD.STS.BSY/DRQ is set, try SCLO.", NULL)
4585 
4586 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4587 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4588 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4589 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4590 		    port_cmd_status|AHCI_CMD_STATUS_CLO);
4591 
4592 		/* Waiting till PxCMD.SCLO bit is cleared */
4593 		loop_count = 0;
4594 		do {
4595 			/* Wait for 10 millisec */
4596 			drv_usecwait(AHCI_10MS_USECS);
4597 
4598 			/* We are effectively timing out after 1 sec. */
4599 			if (loop_count++ > 100) {
4600 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4601 				    "SCLO time out. port %d is busy.", port);
4602 				goto out;
4603 			}
4604 
4605 			port_cmd_status =
4606 			    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4607 			    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4608 		} while (port_cmd_status & AHCI_CMD_STATUS_CLO);
4609 
4610 		/* Re-check */
4611 		port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4612 		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
4613 		if (port_task_file & AHCI_TFD_STS_BSY ||
4614 		    port_task_file & AHCI_TFD_STS_DRQ) {
4615 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4616 			    "SCLO cannot clear PxTFD.STS.BSY/DRQ (PxTFD=0x%x)",
4617 			    port_task_file);
4618 			goto out;
4619 		}
4620 	}
4621 
4622 	/* Then start port */
4623 	if (ahci_start_port(ahci_ctlp, ahci_portp, port)
4624 	    != AHCI_SUCCESS) {
4625 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4626 		    "ahci_software_reset: cannot start AHCI port %d.", port);
4627 		goto out;
4628 	}
4629 
4630 	/*
4631 	 * When ahci_port.ahciport_mop_in_progress is set, A non-zero
4632 	 * ahci_port.ahciport_pending_ncq_tags may fail
4633 	 * ahci_claim_free_slot(). Actually according to spec, by clearing
4634 	 * PxCMD.ST there is no command outstanding while executing software
4635 	 * reseting. Hence we directly use slot 0 instead of
4636 	 * ahci_claim_free_slot().
4637 	 */
4638 	slot = 0;
4639 
4640 	/* Now send the first H2D Register FIS with SRST set to 1 */
4641 	cmd_table = ahci_portp->ahciport_cmd_tables[slot];
4642 	bzero((void *)cmd_table, ahci_cmd_table_size);
4643 
4644 	h2d_register_fisp =
4645 	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
4646 
4647 	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
4648 	SET_FIS_PMP(h2d_register_fisp, pmport);
4649 	SET_FIS_DEVCTL(h2d_register_fisp, SATA_DEVCTL_SRST);
4650 
4651 	/* Set Command Header in Command List */
4652 	cmd_header = &ahci_portp->ahciport_cmd_list[slot];
4653 	BZERO_DESCR_INFO(cmd_header);
4654 	BZERO_PRD_BYTE_COUNT(cmd_header);
4655 	SET_COMMAND_FIS_LENGTH(cmd_header, 5);
4656 	SET_PORT_MULTI_PORT(cmd_header, pmport);
4657 
4658 	SET_CLEAR_BUSY_UPON_R_OK(cmd_header, 1);
4659 	SET_RESET(cmd_header, 1);
4660 	SET_WRITE(cmd_header, 1);
4661 
4662 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_tables_dma_handle[slot],
4663 	    0,
4664 	    ahci_cmd_table_size,
4665 	    DDI_DMA_SYNC_FORDEV);
4666 
4667 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
4668 	    slot * sizeof (ahci_cmd_header_t),
4669 	    sizeof (ahci_cmd_header_t),
4670 	    DDI_DMA_SYNC_FORDEV);
4671 
4672 	/* Indicate to the HBA that a command is active. */
4673 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4674 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
4675 	    (0x1 << slot));
4676 
4677 	loop_count = 0;
4678 
4679 	/* Loop till the first command is finished */
4680 	do {
4681 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4682 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4683 
4684 		/* We are effectively timing out after 1 sec. */
4685 		if (loop_count++ > AHCI_POLLRATE_PORT_SOFTRESET) {
4686 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4687 			    "the first SRST FIS is timed out, "
4688 			    "loop_count = %d", loop_count);
4689 			goto out;
4690 		}
4691 		/* Wait for 10 millisec */
4692 		drv_usecwait(AHCI_10MS_USECS);
4693 	} while (port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp) & (0x1 << slot));
4694 
4695 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
4696 	    "ahci_software_reset: 1st loop count: %d, "
4697 	    "port_cmd_issue = 0x%x, slot = 0x%x",
4698 	    loop_count, port_cmd_issue, slot);
4699 
4700 	/* According to ATA spec, we need wait at least 5 microsecs here. */
4701 	drv_usecwait(AHCI_1MS_USECS);
4702 
4703 	/* Now send the second H2D Register FIS with SRST cleard to zero */
4704 	cmd_table = ahci_portp->ahciport_cmd_tables[slot];
4705 	bzero((void *)cmd_table, ahci_cmd_table_size);
4706 
4707 	h2d_register_fisp =
4708 	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
4709 
4710 	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
4711 	SET_FIS_PMP(h2d_register_fisp, pmport);
4712 
4713 	/* Set Command Header in Command List */
4714 	cmd_header = &ahci_portp->ahciport_cmd_list[slot];
4715 	BZERO_DESCR_INFO(cmd_header);
4716 	BZERO_PRD_BYTE_COUNT(cmd_header);
4717 	SET_COMMAND_FIS_LENGTH(cmd_header, 5);
4718 	SET_PORT_MULTI_PORT(cmd_header, pmport);
4719 
4720 	SET_WRITE(cmd_header, 1);
4721 
4722 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_tables_dma_handle[slot],
4723 	    0,
4724 	    ahci_cmd_table_size,
4725 	    DDI_DMA_SYNC_FORDEV);
4726 
4727 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
4728 	    slot * sizeof (ahci_cmd_header_t),
4729 	    sizeof (ahci_cmd_header_t),
4730 	    DDI_DMA_SYNC_FORDEV);
4731 
4732 	/* Indicate to the HBA that a command is active. */
4733 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4734 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
4735 	    (0x1 << slot));
4736 
4737 	loop_count = 0;
4738 
4739 	/* Loop till the second command is finished */
4740 	do {
4741 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4742 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4743 
4744 		/* We are effectively timing out after 1 sec. */
4745 		if (loop_count++ > AHCI_POLLRATE_PORT_SOFTRESET) {
4746 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4747 			    "the second SRST FIS is timed out, "
4748 			    "loop_count = %d", loop_count);
4749 			goto out;
4750 		}
4751 
4752 		/* Wait for 10 millisec */
4753 		drv_usecwait(AHCI_10MS_USECS);
4754 	} while (port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp) & (0x1 << slot));
4755 
4756 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
4757 	    "ahci_software_reset: 2nd loop count: %d, "
4758 	    "port_cmd_issue = 0x%x, slot = 0x%x",
4759 	    loop_count, port_cmd_issue, slot);
4760 
4761 	CLEAR_BIT(ahci_portp->ahciport_pending_tags, slot);
4762 
4763 	rval = AHCI_SUCCESS;
4764 out:
4765 	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4766 	    "ahci_software_reset: %s at port %d:%d",
4767 	    rval == AHCI_SUCCESS ? "succeed" : "failed",
4768 	    port, pmport);
4769 
4770 	return (rval);
4771 }
4772 
4773 /*
4774  * AHCI port reset ...; the physical communication between the HBA and device
4775  * on a port are disabled. This is more intrusive.
4776  *
4777  * When an HBA or port reset occurs, Phy communication is going to
4778  * be re-established with the device through a COMRESET followed by the
4779  * normal out-of-band communication sequence defined in Serial ATA. AT
4780  * the end of reset, the device, if working properly, will send a D2H
4781  * Register FIS, which contains the device signature. When the HBA receives
4782  * this FIS, it updates PxTFD.STS and PxTFD.ERR register fields, and updates
4783  * the PxSIG register with the signature.
4784  *
4785  * Staggered spin-up is an optional feature in SATA II, and it enables an HBA
4786  * to individually spin-up attached devices. Please refer to chapter 10.9 of
4787  * AHCI 1.0 spec.
4788  */
4789 /*
4790  * WARNING!!! ahciport_mutex should be acquired, and PxCMD.ST should be also
4791  * cleared before the function is called.
4792  */
4793 static int
4794 ahci_port_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4795     ahci_addr_t *addrp)
4796 {
4797 	ahci_addr_t pmult_addr;
4798 	uint32_t cap_status, port_cmd_status;
4799 	uint32_t port_scontrol, port_sstatus, port_serror;
4800 	uint32_t port_intr_status, port_task_file;
4801 	uint32_t port_state;
4802 	uint8_t port = addrp->aa_port;
4803 
4804 	int loop_count;
4805 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
4806 
4807 	/* Target is a port multiplier port? */
4808 	if (AHCI_ADDR_IS_PMPORT(addrp))
4809 		return (ahci_pmport_reset(ahci_ctlp, ahci_portp, addrp));
4810 
4811 	/* Otherwise it must be an HBA port. */
4812 	ASSERT(AHCI_ADDR_IS_PORT(addrp));
4813 
4814 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
4815 	    "Port %d port resetting...", port);
4816 	ahci_portp->ahciport_port_state = 0;
4817 
4818 	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4819 	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
4820 
4821 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4822 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4823 
4824 	if (cap_status & AHCI_HBA_CAP_SSS) {
4825 		/*
4826 		 * HBA support staggered spin-up, if the port has
4827 		 * not spin up yet, then force it to do spin-up
4828 		 */
4829 		if (!(port_cmd_status & AHCI_CMD_STATUS_SUD)) {
4830 			if (!(ahci_portp->ahciport_flags
4831 			    & AHCI_PORT_FLAG_SPINUP)) {
4832 				AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4833 				    "Port %d PxCMD.SUD is zero, force "
4834 				    "it to do spin-up", port);
4835 				ahci_portp->ahciport_flags |=
4836 				    AHCI_PORT_FLAG_SPINUP;
4837 			}
4838 		}
4839 	} else {
4840 		/*
4841 		 * HBA doesn't support stagger spin-up, force it
4842 		 * to do normal COMRESET
4843 		 */
4844 		if (ahci_portp->ahciport_flags &
4845 		    AHCI_PORT_FLAG_SPINUP) {
4846 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4847 			    "HBA does not support staggered spin-up "
4848 			    "force it to do normal COMRESET", NULL);
4849 			ahci_portp->ahciport_flags &=
4850 			    ~AHCI_PORT_FLAG_SPINUP;
4851 		}
4852 	}
4853 
4854 	if (!(ahci_portp->ahciport_flags & AHCI_PORT_FLAG_SPINUP)) {
4855 		/* Do normal COMRESET */
4856 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
4857 		    "ahci_port_reset: do normal COMRESET", port);
4858 
4859 		/*
4860 		 * According to the spec, SUD bit should be set here,
4861 		 * but JMicron JMB363 doesn't follow it, so remove
4862 		 * the assertion, and just print a debug message.
4863 		 */
4864 #if AHCI_DEBUG
4865 		if (!(port_cmd_status & AHCI_CMD_STATUS_SUD))
4866 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4867 			    "port %d SUD bit not set", port)
4868 #endif
4869 
4870 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4871 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
4872 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_COMRESET);
4873 
4874 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4875 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
4876 		    port_scontrol);
4877 
4878 		/* Enable PxCMD.FRE to read device */
4879 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4880 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4881 		    port_cmd_status|AHCI_CMD_STATUS_FRE);
4882 
4883 		/*
4884 		 * Give time for COMRESET to percolate, according to the AHCI
4885 		 * spec, software shall wait at least 1 millisecond before
4886 		 * clearing PxSCTL.DET
4887 		 */
4888 		drv_usecwait(AHCI_1MS_USECS*2);
4889 
4890 		/* Fetch the SCONTROL again and rewrite the DET part with 0 */
4891 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4892 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
4893 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_NOACTION);
4894 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4895 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
4896 		    port_scontrol);
4897 	} else {
4898 		/* Do staggered spin-up */
4899 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4900 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
4901 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_NOACTION);
4902 
4903 		/* PxSCTL.DET must be 0 */
4904 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4905 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
4906 		    port_scontrol);
4907 
4908 		port_cmd_status &= ~AHCI_CMD_STATUS_SUD;
4909 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4910 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4911 		    port_cmd_status);
4912 
4913 		/* 0 -> 1 edge */
4914 		drv_usecwait(AHCI_1MS_USECS*2);
4915 
4916 		/* Set PxCMD.SUD to 1 */
4917 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4918 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4919 		port_cmd_status |= AHCI_CMD_STATUS_SUD;
4920 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4921 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4922 		    port_cmd_status);
4923 
4924 		/* Enable PxCMD.FRE to read device */
4925 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4926 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4927 		    port_cmd_status|AHCI_CMD_STATUS_FRE);
4928 	}
4929 
4930 	/*
4931 	 * The port enters P:StartComm state, and HBA tells link layer to
4932 	 * start communication, which involves sending COMRESET to device.
4933 	 * And the HBA resets PxTFD.STS to 7Fh.
4934 	 *
4935 	 * When a COMINIT is received from the device, then the port enters
4936 	 * P:ComInit state. And HBA sets PxTFD.STS to FFh or 80h. HBA sets
4937 	 * PxSSTS.DET to 1h to indicate a device is detected but communication
4938 	 * is not yet established. HBA sets PxSERR.DIAG.X to '1' to indicate
4939 	 * a COMINIT has been received.
4940 	 */
4941 	/*
4942 	 * The DET field is valid only if IPM field indicates
4943 	 * that the interface is in active state.
4944 	 */
4945 	loop_count = 0;
4946 	do {
4947 		port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4948 		    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
4949 
4950 		if (SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) {
4951 			/*
4952 			 * If the interface is not active, the DET field
4953 			 * is considered not accurate. So we want to
4954 			 * continue looping.
4955 			 */
4956 			SSTATUS_SET_DET(port_sstatus, SSTATUS_DET_NODEV);
4957 		}
4958 
4959 		if (loop_count++ > AHCI_POLLRATE_PORT_SSTATUS) {
4960 			/*
4961 			 * We are effectively timing out after 0.1 sec.
4962 			 */
4963 			break;
4964 		}
4965 
4966 		/* Wait for 10 millisec */
4967 		drv_usecwait(AHCI_10MS_USECS);
4968 	} while (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM);
4969 
4970 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
4971 	    "ahci_port_reset: 1st loop count: %d, "
4972 	    "port_sstatus = 0x%x port %d",
4973 	    loop_count, port_sstatus, port);
4974 
4975 	if ((SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) ||
4976 	    (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM)) {
4977 		/*
4978 		 * Either the port is not active or there
4979 		 * is no device present.
4980 		 */
4981 		AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_NONE);
4982 		return (AHCI_SUCCESS);
4983 	}
4984 
4985 	/* Now we can make sure there is a device connected to the port */
4986 	port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4987 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
4988 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4989 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
4990 
4991 	/*
4992 	 * A COMINIT signal is supposed to be received
4993 	 * PxSERR.DIAG.X or PxIS.PCS should be set
4994 	 */
4995 	if (!(port_intr_status & AHCI_INTR_STATUS_PCS) &&
4996 	    !(port_serror & SERROR_EXCHANGED_ERR)) {
4997 		cmn_err(CE_WARN, "!ahci%d: ahci_port_reset port %d "
4998 		    "COMINIT signal from the device not received",
4999 		    instance, port);
5000 		AHCIPORT_SET_STATE(ahci_portp, addrp, SATA_PSTATE_FAILED);
5001 		return (AHCI_FAILURE);
5002 	}
5003 
5004 	/*
5005 	 * According to the spec, when PxSCTL.DET is set to 0h, upon
5006 	 * receiving a COMINIT from the attached device, PxTFD.STS.BSY
5007 	 * shall be set to '1' by the HBA.
5008 	 *
5009 	 * However, we found JMicron JMB363 doesn't follow this, so
5010 	 * remove this check, and just print a debug message.
5011 	 */
5012 #if AHCI_DEBUG
5013 	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5014 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
5015 	if (!(port_task_file & AHCI_TFD_STS_BSY)) {
5016 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_port_reset: "
5017 		    "port %d BSY bit is not set after COMINIT signal "
5018 		    "is received", port);
5019 	}
5020 #endif
5021 
5022 	/*
5023 	 * PxSERR.DIAG.X has to be cleared in order to update PxTFD with
5024 	 * the D2H FIS received by HBA.
5025 	 */
5026 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5027 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5028 	    SERROR_EXCHANGED_ERR);
5029 
5030 	/*
5031 	 * Devices should return a FIS contains its signature to HBA after
5032 	 * COMINIT signal. Check whether a D2H FIS is received by polling
5033 	 * PxTFD.STS.ERR bit.
5034 	 */
5035 	loop_count = 0;
5036 	do {
5037 		/* Wait for 10 millisec */
5038 		drv_usecwait(AHCI_10MS_USECS);
5039 
5040 		if (loop_count++ > AHCI_POLLRATE_PORT_TFD_ERROR) {
5041 			/*
5042 			 * We are effectively timing out after 11 sec.
5043 			 */
5044 			cmn_err(CE_WARN, "!ahci%d: ahci_port_reset port %d "
5045 			    "the device hardware has been initialized and "
5046 			    "the power-up diagnostics failed",
5047 			    instance, port);
5048 
5049 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_port_reset: "
5050 			    "port %d PxTFD.STS.ERR is not set, we need another "
5051 			    "software reset.", port);
5052 
5053 			/* Clear port serror register for the port */
5054 			ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5055 			    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5056 			    AHCI_SERROR_CLEAR_ALL);
5057 
5058 			AHCI_ADDR_SET_PMULT(&pmult_addr, port);
5059 
5060 			/* Try another software reset. */
5061 			if (ahci_software_reset(ahci_ctlp, ahci_portp,
5062 			    &pmult_addr) != AHCI_SUCCESS) {
5063 				AHCIPORT_SET_STATE(ahci_portp, addrp,
5064 				    SATA_PSTATE_FAILED);
5065 				return (AHCI_FAILURE);
5066 			}
5067 			break;
5068 		}
5069 
5070 		/* Wait for 10 millisec */
5071 		drv_usecwait(AHCI_10MS_USECS);
5072 
5073 		/*
5074 		 * The Error bit '1' means COMRESET is finished successfully
5075 		 * The device hardware has been initialized and the power-up
5076 		 * diagnostics successfully completed. The device requests
5077 		 * that the Transport layer transmit a Register - D2H FIS to
5078 		 * the host. (SATA spec 11.5, v2.6)
5079 		 */
5080 		port_task_file =
5081 		    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5082 		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
5083 	} while (((port_task_file & AHCI_TFD_ERR_MASK)
5084 	    >> AHCI_TFD_ERR_SHIFT) != AHCI_TFD_ERR_SGS);
5085 
5086 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
5087 	    "ahci_port_reset: 2nd loop count: %d, "
5088 	    "port_task_file = 0x%x port %d",
5089 	    loop_count, port_task_file, port);
5090 
5091 	/* Clear port serror register for the port */
5092 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5093 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5094 	    AHCI_SERROR_CLEAR_ALL);
5095 
5096 	/* Set port as ready */
5097 	port_state = AHCIPORT_GET_STATE(ahci_portp, addrp);
5098 	AHCIPORT_SET_STATE(ahci_portp, addrp, port_state|SATA_STATE_READY);
5099 
5100 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_ERRS, ahci_ctlp,
5101 	    "ahci_port_reset: succeed at port %d.", port);
5102 	return (AHCI_SUCCESS);
5103 }
5104 
5105 /*
5106  * COMRESET on a port multiplier port.
5107  *
5108  * NOTE: Only called in ahci_port_reset()
5109  */
5110 static int
5111 ahci_pmport_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
5112     ahci_addr_t *addrp)
5113 {
5114 	uint32_t port_scontrol, port_sstatus, port_serror;
5115 	uint32_t port_cmd_status, port_intr_status;
5116 	uint32_t port_state;
5117 	uint8_t port = addrp->aa_port;
5118 	uint8_t pmport = addrp->aa_pmport;
5119 	int loop_count;
5120 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
5121 
5122 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
5123 	    "port %d:%d: pmport resetting", port, pmport);
5124 
5125 	/* Initialize pmport state */
5126 	AHCIPORT_SET_STATE(ahci_portp, addrp, 0);
5127 
5128 	READ_PMULT(addrp, SATA_PMULT_REG_SCTL, &port_scontrol, err);
5129 	SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_COMRESET);
5130 	WRITE_PMULT(addrp, SATA_PMULT_REG_SCTL, port_scontrol, err);
5131 
5132 	/* PxCMD.FRE should be set before. */
5133 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5134 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5135 	ASSERT(port_cmd_status & AHCI_CMD_STATUS_FRE);
5136 	if (!(port_cmd_status & AHCI_CMD_STATUS_FRE))
5137 		return (AHCI_FAILURE);
5138 
5139 	/*
5140 	 * Give time for COMRESET to percolate, according to the AHCI
5141 	 * spec, software shall wait at least 1 millisecond before
5142 	 * clearing PxSCTL.DET
5143 	 */
5144 	drv_usecwait(AHCI_1MS_USECS*2);
5145 
5146 	/*
5147 	 * Fetch the SCONTROL again and rewrite the DET part with 0
5148 	 * This will generate an Asychronous Notification events.
5149 	 */
5150 	READ_PMULT(addrp, SATA_PMULT_REG_SCTL, &port_scontrol, err);
5151 	SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_NOACTION);
5152 	WRITE_PMULT(addrp, SATA_PMULT_REG_SCTL, port_scontrol, err);
5153 
5154 	/*
5155 	 * The port enters P:StartComm state, and HBA tells link layer to
5156 	 * start communication, which involves sending COMRESET to device.
5157 	 * And the HBA resets PxTFD.STS to 7Fh.
5158 	 *
5159 	 * When a COMINIT is received from the device, then the port enters
5160 	 * P:ComInit state. And HBA sets PxTFD.STS to FFh or 80h. HBA sets
5161 	 * PxSSTS.DET to 1h to indicate a device is detected but communication
5162 	 * is not yet established. HBA sets PxSERR.DIAG.X to '1' to indicate
5163 	 * a COMINIT has been received.
5164 	 */
5165 	/*
5166 	 * The DET field is valid only if IPM field indicates
5167 	 * that the interface is in active state.
5168 	 */
5169 	loop_count = 0;
5170 	do {
5171 		READ_PMULT(addrp, SATA_PMULT_REG_SSTS, &port_sstatus, err);
5172 
5173 		if (SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) {
5174 			/*
5175 			 * If the interface is not active, the DET field
5176 			 * is considered not accurate. So we want to
5177 			 * continue looping.
5178 			 */
5179 			SSTATUS_SET_DET(port_sstatus, SSTATUS_DET_NODEV);
5180 		}
5181 
5182 		if (loop_count++ > AHCI_POLLRATE_PORT_SSTATUS) {
5183 			/*
5184 			 * We are effectively timing out after 0.1 sec.
5185 			 */
5186 			break;
5187 		}
5188 
5189 		/* Wait for 10 millisec */
5190 		drv_usecwait(AHCI_10MS_USECS);
5191 
5192 	} while (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM);
5193 
5194 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
5195 	    "ahci_pmport_reset: 1st loop count: %d, "
5196 	    "port_sstatus = 0x%x port %d:%d",
5197 	    loop_count, port_sstatus, port, pmport);
5198 
5199 	if ((SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) ||
5200 	    (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM)) {
5201 		/*
5202 		 * Either the port is not active or there
5203 		 * is no device present.
5204 		 */
5205 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INFO, ahci_ctlp,
5206 		    "ahci_pmport_reset: "
5207 		    "no device attached to port %d:%d",
5208 		    port, pmport);
5209 		AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_NONE);
5210 		return (AHCI_SUCCESS);
5211 	}
5212 
5213 	/* Now we can make sure there is a device connected to the port */
5214 	/* COMINIT signal is supposed to be received (PxSERR.DIAG.X = '1') */
5215 	READ_PMULT(addrp, SATA_PMULT_REG_SERR, &port_serror, err);
5216 
5217 	if (!(port_serror & (1 << 26))) {
5218 		cmn_err(CE_WARN, "!ahci%d: ahci_pmport_reset: "
5219 		    "COMINIT signal from the device not received port %d:%d",
5220 		    instance, port, pmport);
5221 
5222 		AHCIPORT_SET_STATE(ahci_portp, addrp, SATA_PSTATE_FAILED);
5223 		return (AHCI_FAILURE);
5224 	}
5225 
5226 	/*
5227 	 * After clear PxSERR register, we will receive a D2H FIS.
5228 	 * Normally this FIS will cause a IPMS error according to AHCI spec
5229 	 * v1.2 because there is no command outstanding for it. So we need
5230 	 * to ignore this error.
5231 	 */
5232 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_IGNORE_IPMS;
5233 	WRITE_PMULT(addrp, SATA_PMULT_REG_SERR, AHCI_SERROR_CLEAR_ALL, err);
5234 
5235 	/* Now we need to check the D2H FIS by checking IPMS error. */
5236 	loop_count = 0;
5237 	do {
5238 		port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5239 		    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
5240 
5241 		if (loop_count++ > AHCI_POLLRATE_PORT_TFD_ERROR) {
5242 			/*
5243 			 * No D2H FIS received. This is possible according
5244 			 * to SATA 2.6 spec.
5245 			 */
5246 			cmn_err(CE_WARN, "ahci_port_reset: port %d:%d "
5247 			    "PxIS.IPMS is not set, we need another "
5248 			    "software reset.", port, pmport);
5249 
5250 			break;
5251 		}
5252 
5253 		/* Wait for 10 millisec */
5254 		mutex_exit(&ahci_portp->ahciport_mutex);
5255 		delay(AHCI_10MS_TICKS);
5256 		mutex_enter(&ahci_portp->ahciport_mutex);
5257 
5258 	} while (!(port_intr_status & AHCI_INTR_STATUS_IPMS));
5259 
5260 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
5261 	    "ahci_pmport_reset: 2st loop count: %d, "
5262 	    "port_sstatus = 0x%x port %d:%d",
5263 	    loop_count, port_sstatus, port, pmport);
5264 
5265 	/* Clear IPMS */
5266 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5267 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
5268 	    AHCI_INTR_STATUS_IPMS);
5269 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_IGNORE_IPMS;
5270 
5271 	/* This pmport is now ready for ahci_tran_start() */
5272 	port_state = AHCIPORT_GET_STATE(ahci_portp, addrp);
5273 	AHCIPORT_SET_STATE(ahci_portp, addrp, port_state|SATA_STATE_READY);
5274 
5275 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_ERRS, ahci_ctlp,
5276 	    "ahci_pmport_reset: succeed at port %d:%d", port, pmport);
5277 	return (AHCI_SUCCESS);
5278 
5279 err:	/* R/W PMULT error */
5280 	/* IPMS flags might be set before. */
5281 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_IGNORE_IPMS;
5282 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_ERRS, ahci_ctlp,
5283 	    "ahci_pmport_reset: failed at port %d:%d", port, pmport);
5284 
5285 	return (AHCI_FAILURE);
5286 }
5287 
5288 /*
5289  * AHCI HBA reset ...; the entire HBA is reset, and all ports are disabled.
5290  * This is the most intrusive.
5291  *
5292  * When an HBA reset occurs, Phy communication will be re-established with
5293  * the device through a COMRESET followed by the normal out-of-band
5294  * communication sequence defined in Serial ATA. AT the end of reset, the
5295  * device, if working properly, will send a D2H Register FIS, which contains
5296  * the device signature. When the HBA receives this FIS, it updates PxTFD.STS
5297  * and PxTFD.ERR register fields, and updates the PxSIG register with the
5298  * signature.
5299  *
5300  * Remember to set GHC.AE to 1 before calling ahci_hba_reset.
5301  */
5302 static int
5303 ahci_hba_reset(ahci_ctl_t *ahci_ctlp)
5304 {
5305 	ahci_port_t *ahci_portp;
5306 	ahci_addr_t addr;
5307 	uint32_t ghc_control;
5308 	uint8_t port;
5309 	int loop_count;
5310 	int rval = AHCI_SUCCESS;
5311 
5312 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp, "HBA resetting",
5313 	    NULL);
5314 
5315 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
5316 
5317 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5318 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5319 
5320 	/* Setting GHC.HR to 1, remember GHC.AE is already set to 1 before */
5321 	ghc_control |= AHCI_HBA_GHC_HR;
5322 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5323 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
5324 
5325 	/*
5326 	 * Wait until HBA Reset complete or timeout
5327 	 */
5328 	loop_count = 0;
5329 	do {
5330 		ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5331 		    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5332 
5333 		if (loop_count++ > AHCI_POLLRATE_HBA_RESET) {
5334 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5335 			    "ahci hba reset is timing out, "
5336 			    "ghc_control = 0x%x", ghc_control);
5337 			/* We are effectively timing out after 1 sec. */
5338 			break;
5339 		}
5340 
5341 		/* Wait for 10 millisec */
5342 		drv_usecwait(AHCI_10MS_USECS);
5343 	} while (ghc_control & AHCI_HBA_GHC_HR);
5344 
5345 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
5346 	    "ahci_hba_reset: 1st loop count: %d, "
5347 	    "ghc_control = 0x%x", loop_count, ghc_control);
5348 
5349 	if (ghc_control & AHCI_HBA_GHC_HR) {
5350 		/* The hba is not reset for some reasons */
5351 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5352 		    "hba reset failed: HBA in a hung or locked state", NULL);
5353 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
5354 		return (AHCI_FAILURE);
5355 	}
5356 
5357 	/*
5358 	 * HBA reset will clear (AHCI Spec v1.2 10.4.3) GHC.IE / GHC.AE
5359 	 */
5360 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5361 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5362 	ghc_control |= (AHCI_HBA_GHC_AE | AHCI_HBA_GHC_IE);
5363 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5364 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
5365 
5366 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
5367 
5368 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
5369 		/* Only check implemented ports */
5370 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
5371 			continue;
5372 		}
5373 
5374 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
5375 		mutex_enter(&ahci_portp->ahciport_mutex);
5376 
5377 		AHCI_ADDR_SET_PORT(&addr, port);
5378 
5379 		if (ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
5380 		    port, AHCI_PORT_RESET|AHCI_RESET_NO_EVENTS_UP, NULL) !=
5381 		    AHCI_SUCCESS) {
5382 			rval = AHCI_FAILURE;
5383 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5384 			    "ahci_hba_reset: port %d failed", port);
5385 			/*
5386 			 * Set the port state to SATA_PSTATE_FAILED if
5387 			 * failed to initialize it.
5388 			 */
5389 			ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
5390 		}
5391 
5392 		mutex_exit(&ahci_portp->ahciport_mutex);
5393 	}
5394 
5395 	return (rval);
5396 }
5397 
5398 /*
5399  * This routine is only called from AHCI_ATTACH or phyrdy change
5400  * case. It first calls software reset, then stop the port and try to
5401  * read PxSIG register to find the type of device attached to the port.
5402  *
5403  * The caller should make sure a valid device exists on specified port and
5404  * physical communication has been established so that the signature could
5405  * be retrieved by software reset.
5406  *
5407  * WARNING!!! ahciport_mutex should be acquired before the function
5408  * is called. And the port interrupt is disabled.
5409  */
5410 static void
5411 ahci_find_dev_signature(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
5412     ahci_addr_t *addrp)
5413 {
5414 	ahci_addr_t dev_addr;
5415 	uint32_t signature;
5416 	uint8_t port = addrp->aa_port;
5417 	uint8_t pmport = addrp->aa_pmport;
5418 	ASSERT(AHCI_ADDR_IS_VALID(addrp));
5419 
5420 	if (AHCI_ADDR_IS_PORT(addrp)) {
5421 		AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
5422 		    "ahci_find_dev_signature enter: port %d", port);
5423 
5424 		/*
5425 		 * NOTE: when the ahci address is a HBA port, we do not know
5426 		 * it is a device or a port multiplier that attached. we need
5427 		 * try a software reset at port multiplier address (0xf
5428 		 * pmport)
5429 		 */
5430 		AHCI_ADDR_SET_PMULT(&dev_addr, addrp->aa_port);
5431 	} else {
5432 		AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
5433 		    "ahci_find_dev_signature enter: port %d:%d",
5434 		    port, pmport);
5435 		dev_addr = *addrp;
5436 	}
5437 
5438 	/* Assume it is unknown. */
5439 	AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_UNKNOWN);
5440 
5441 	/* Issue a software reset to get the signature */
5442 	if (ahci_software_reset(ahci_ctlp, ahci_portp, &dev_addr)
5443 	    != AHCI_SUCCESS) {
5444 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5445 		    "ahci_find_dev_signature: software reset failed "
5446 		    "at port %d:%d, cannot get signature.", port, pmport);
5447 		AHCIPORT_SET_STATE(ahci_portp, addrp, SATA_PSTATE_FAILED);
5448 		return;
5449 	}
5450 
5451 	/*
5452 	 * ahci_software_reset has started the port, so we need manually stop
5453 	 * the port again.
5454 	 */
5455 	if (AHCI_ADDR_IS_PORT(addrp)) {
5456 		if (ahci_put_port_into_notrunning_state(ahci_ctlp,
5457 		    ahci_portp, port) != AHCI_SUCCESS) {
5458 			AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
5459 			    "ahci_find_dev_signature: cannot stop port %d.",
5460 			    port);
5461 			ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
5462 			return;
5463 		}
5464 	}
5465 
5466 	/* Now we can make sure that a valid signature is received. */
5467 	signature = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5468 	    (uint32_t *)AHCI_PORT_PxSIG(ahci_ctlp, port));
5469 
5470 #ifdef AHCI_DEBUG
5471 	if (AHCI_ADDR_IS_PMPORT(addrp)) {
5472 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
5473 		    "ahci_find_dev_signature: signature = 0x%x at port %d:%d",
5474 		    signature, port, pmport);
5475 	} else {
5476 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INFO, ahci_ctlp,
5477 		    "ahci_find_dev_signature: signature = 0x%x at port %d",
5478 		    signature, port);
5479 	}
5480 #endif
5481 
5482 	/* NOTE: Only support ATAPI device at controller port. */
5483 	if (signature == AHCI_SIGNATURE_ATAPI && !AHCI_ADDR_IS_PORT(addrp))
5484 		signature = SATA_DTYPE_UNKNOWN;
5485 
5486 	switch (signature) {
5487 
5488 	case AHCI_SIGNATURE_DISK:
5489 		AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_ATADISK);
5490 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
5491 		    "Disk is found at port: %d", port);
5492 		break;
5493 
5494 	case AHCI_SIGNATURE_ATAPI:
5495 		AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_ATAPI);
5496 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
5497 		    "ATAPI device is found at port: %d", port);
5498 		break;
5499 
5500 	case AHCI_SIGNATURE_PORT_MULTIPLIER:
5501 		/* Port Multiplier cannot recursively attached. */
5502 		ASSERT(AHCI_ADDR_IS_PORT(addrp));
5503 		AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_PMULT);
5504 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
5505 		    "Port Multiplier is found at port: %d", port);
5506 		break;
5507 
5508 	default:
5509 		AHCIPORT_SET_DEV_TYPE(ahci_portp, addrp, SATA_DTYPE_UNKNOWN);
5510 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
5511 		    "Unknown device is found at port: %d", port);
5512 	}
5513 }
5514 
5515 /*
5516  * According to the spec, to reliably detect hot plug removals, software
5517  * must disable interface power management. Software should perform the
5518  * following initialization on a port after a device is attached:
5519  *   Set PxSCTL.IPM to 3h to disable interface state transitions
5520  *   Set PxCMD.ALPE to '0' to disable aggressive power management
5521  *   Disable device initiated interface power management by SET FEATURE
5522  *
5523  * We can ignore the last item because by default the feature is disabled
5524  */
5525 static void
5526 ahci_disable_interface_pm(ahci_ctl_t *ahci_ctlp, uint8_t port)
5527 {
5528 	uint32_t port_scontrol, port_cmd_status;
5529 
5530 	port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5531 	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
5532 	SCONTROL_SET_IPM(port_scontrol, SCONTROL_IPM_DISABLE_BOTH);
5533 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5534 	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port), port_scontrol);
5535 
5536 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5537 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5538 	port_cmd_status &= ~AHCI_CMD_STATUS_ALPE;
5539 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5540 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port), port_cmd_status);
5541 }
5542 
5543 /*
5544  * Start the port - set PxCMD.ST to 1, if PxCMD.FRE is not set
5545  * to 1, then set it firstly.
5546  *
5547  * Each port contains two major DMA engines. One DMA engine walks through
5548  * the command list, and is controlled by PxCMD.ST. The second DMA engine
5549  * copies received FISes into system memory, and is controlled by PxCMD.FRE.
5550  *
5551  * Software shall not set PxCMD.ST to '1' until it verifies that PxCMD.CR
5552  * is '0' and has set PxCMD.FRE is '1'. And software shall not clear
5553  * PxCMD.FRE while PxCMD.ST or PxCMD.CR is set '1'.
5554  *
5555  * Software shall not set PxCMD.ST to '1' unless a functional device is
5556  * present on the port(as determined by PxTFD.STS.BSY = '0',
5557  * PxTFD.STS.DRQ = '0', and PxSSTS.DET = 3h).
5558  *
5559  * WARNING!!! ahciport_mutex should be acquired before the function
5560  * is called.
5561  */
5562 static int
5563 ahci_start_port(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
5564 {
5565 	uint32_t port_cmd_status;
5566 
5567 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_start_port: %d enter", port);
5568 
5569 	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED) {
5570 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port failed "
5571 		    "the state for port %d is 0x%x",
5572 		    port, ahci_portp->ahciport_port_state);
5573 		return (AHCI_FAILURE);
5574 	}
5575 
5576 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
5577 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port failed "
5578 		    "no device is attached at port %d", port);
5579 		return (AHCI_FAILURE);
5580 	}
5581 
5582 	/* First to set PxCMD.FRE before setting PxCMD.ST. */
5583 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5584 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5585 
5586 	if (!(port_cmd_status & AHCI_CMD_STATUS_FRE)) {
5587 		port_cmd_status |= AHCI_CMD_STATUS_FRE;
5588 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5589 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
5590 		    port_cmd_status);
5591 	}
5592 
5593 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5594 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5595 
5596 	port_cmd_status |= AHCI_CMD_STATUS_ST;
5597 
5598 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5599 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
5600 	    port_cmd_status);
5601 
5602 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_STARTED;
5603 
5604 	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port: "
5605 	    "PxCMD.ST set to '1' at port %d", port);
5606 
5607 	return (AHCI_SUCCESS);
5608 }
5609 
5610 /*
5611  * Allocate the ahci_port_t including Received FIS and Command List.
5612  * The argument - port is the physical port number, and not logical
5613  * port number seen by the SATA framework.
5614  *
5615  * WARNING!!! ahcictl_mutex should be acquired before the function
5616  * is called.
5617  */
5618 static int
5619 ahci_alloc_port_state(ahci_ctl_t *ahci_ctlp, uint8_t port)
5620 {
5621 	dev_info_t *dip = ahci_ctlp->ahcictl_dip;
5622 	ahci_port_t *ahci_portp;
5623 	char taskq_name[64] = "event_handle_taskq";
5624 
5625 	ahci_portp =
5626 	    (ahci_port_t *)kmem_zalloc(sizeof (ahci_port_t), KM_SLEEP);
5627 
5628 	ahci_ctlp->ahcictl_ports[port] = ahci_portp;
5629 	ahci_portp->ahciport_port_num = port;
5630 
5631 	/* Initialize the port condition variable */
5632 	cv_init(&ahci_portp->ahciport_cv, NULL, CV_DRIVER, NULL);
5633 
5634 	/* Initialize the port mutex */
5635 	mutex_init(&ahci_portp->ahciport_mutex, NULL, MUTEX_DRIVER,
5636 	    (void *)(uintptr_t)ahci_ctlp->ahcictl_intr_pri);
5637 
5638 	mutex_enter(&ahci_portp->ahciport_mutex);
5639 
5640 	/*
5641 	 * Allocate memory for received FIS structure and
5642 	 * command list for this port
5643 	 */
5644 	if (ahci_alloc_rcvd_fis(ahci_ctlp, ahci_portp, port) != AHCI_SUCCESS) {
5645 		goto err_case1;
5646 	}
5647 
5648 	if (ahci_alloc_cmd_list(ahci_ctlp, ahci_portp, port) != AHCI_SUCCESS) {
5649 		goto err_case2;
5650 	}
5651 
5652 	(void) snprintf(taskq_name + strlen(taskq_name),
5653 	    sizeof (taskq_name) - strlen(taskq_name),
5654 	    "_port%d", port);
5655 
5656 	/* Create the taskq for the port */
5657 	if ((ahci_portp->ahciport_event_taskq = ddi_taskq_create(dip,
5658 	    taskq_name, 2, TASKQ_DEFAULTPRI, 0)) == NULL) {
5659 		cmn_err(CE_WARN, "!ahci%d: ddi_taskq_create failed for event "
5660 		    "handle", ddi_get_instance(ahci_ctlp->ahcictl_dip));
5661 		goto err_case3;
5662 	}
5663 
5664 	/* Allocate the argument for the taskq */
5665 	ahci_portp->ahciport_event_args =
5666 	    kmem_zalloc(sizeof (ahci_event_arg_t), KM_SLEEP);
5667 
5668 	ahci_portp->ahciport_event_args->ahciea_addrp =
5669 	    kmem_zalloc(sizeof (ahci_addr_t), KM_SLEEP);
5670 
5671 	if (ahci_portp->ahciport_event_args == NULL)
5672 		goto err_case4;
5673 
5674 	mutex_exit(&ahci_portp->ahciport_mutex);
5675 
5676 	return (AHCI_SUCCESS);
5677 
5678 err_case4:
5679 	ddi_taskq_destroy(ahci_portp->ahciport_event_taskq);
5680 
5681 err_case3:
5682 	ahci_dealloc_cmd_list(ahci_ctlp, ahci_portp);
5683 
5684 err_case2:
5685 	ahci_dealloc_rcvd_fis(ahci_portp);
5686 
5687 err_case1:
5688 	mutex_exit(&ahci_portp->ahciport_mutex);
5689 	mutex_destroy(&ahci_portp->ahciport_mutex);
5690 	cv_destroy(&ahci_portp->ahciport_cv);
5691 
5692 	kmem_free(ahci_portp, sizeof (ahci_port_t));
5693 
5694 	return (AHCI_FAILURE);
5695 }
5696 
5697 /*
5698  * Reverse of ahci_dealloc_port_state().
5699  *
5700  * WARNING!!! ahcictl_mutex should be acquired before the function
5701  * is called.
5702  */
5703 static void
5704 ahci_dealloc_port_state(ahci_ctl_t *ahci_ctlp, uint8_t port)
5705 {
5706 	ahci_port_t *ahci_portp = ahci_ctlp->ahcictl_ports[port];
5707 
5708 	ASSERT(ahci_portp != NULL);
5709 
5710 	mutex_enter(&ahci_portp->ahciport_mutex);
5711 	kmem_free(ahci_portp->ahciport_event_args->ahciea_addrp,
5712 	    sizeof (ahci_addr_t));
5713 	ahci_portp->ahciport_event_args->ahciea_addrp = NULL;
5714 	kmem_free(ahci_portp->ahciport_event_args, sizeof (ahci_event_arg_t));
5715 	ahci_portp->ahciport_event_args = NULL;
5716 	ddi_taskq_destroy(ahci_portp->ahciport_event_taskq);
5717 	ahci_dealloc_cmd_list(ahci_ctlp, ahci_portp);
5718 	ahci_dealloc_rcvd_fis(ahci_portp);
5719 	ahci_dealloc_pmult(ahci_ctlp, ahci_portp);
5720 	mutex_exit(&ahci_portp->ahciport_mutex);
5721 
5722 	mutex_destroy(&ahci_portp->ahciport_mutex);
5723 	cv_destroy(&ahci_portp->ahciport_cv);
5724 
5725 	kmem_free(ahci_portp, sizeof (ahci_port_t));
5726 
5727 	ahci_ctlp->ahcictl_ports[port] = NULL;
5728 }
5729 
5730 /*
5731  * Allocates memory for the Received FIS Structure
5732  *
5733  * WARNING!!! ahciport_mutex should be acquired before the function
5734  * is called.
5735  */
5736 static int
5737 ahci_alloc_rcvd_fis(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
5738     uint8_t port)
5739 {
5740 	size_t rcvd_fis_size;
5741 	size_t ret_len;
5742 	uint_t cookie_count;
5743 
5744 	rcvd_fis_size = sizeof (ahci_rcvd_fis_t);
5745 
5746 	/* allocate rcvd FIS dma handle. */
5747 	if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
5748 	    &ahci_ctlp->ahcictl_rcvd_fis_dma_attr,
5749 	    DDI_DMA_SLEEP,
5750 	    NULL,
5751 	    &ahci_portp->ahciport_rcvd_fis_dma_handle) !=
5752 	    DDI_SUCCESS) {
5753 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5754 		    "rcvd FIS dma handle alloc failed", NULL);
5755 
5756 		return (AHCI_FAILURE);
5757 	}
5758 
5759 	if (ddi_dma_mem_alloc(ahci_portp->ahciport_rcvd_fis_dma_handle,
5760 	    rcvd_fis_size,
5761 	    &accattr,
5762 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
5763 	    DDI_DMA_SLEEP,
5764 	    NULL,
5765 	    (caddr_t *)&ahci_portp->ahciport_rcvd_fis,
5766 	    &ret_len,
5767 	    &ahci_portp->ahciport_rcvd_fis_acc_handle) != NULL) {
5768 
5769 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5770 		    "rcvd FIS dma mem alloc fail", NULL);
5771 		/* error.. free the dma handle. */
5772 		ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
5773 		return (AHCI_FAILURE);
5774 	}
5775 
5776 	if (ddi_dma_addr_bind_handle(ahci_portp->ahciport_rcvd_fis_dma_handle,
5777 	    NULL,
5778 	    (caddr_t)ahci_portp->ahciport_rcvd_fis,
5779 	    rcvd_fis_size,
5780 	    DDI_DMA_CONSISTENT,
5781 	    DDI_DMA_SLEEP,
5782 	    NULL,
5783 	    &ahci_portp->ahciport_rcvd_fis_dma_cookie,
5784 	    &cookie_count) !=  DDI_DMA_MAPPED) {
5785 
5786 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5787 		    "rcvd FIS dma handle bind fail", NULL);
5788 		/*  error.. free the dma handle & free the memory. */
5789 		ddi_dma_mem_free(&ahci_portp->ahciport_rcvd_fis_acc_handle);
5790 		ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
5791 		return (AHCI_FAILURE);
5792 	}
5793 
5794 	bzero((void *)ahci_portp->ahciport_rcvd_fis, rcvd_fis_size);
5795 
5796 	/* Config Port Received FIS Base Address */
5797 	ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
5798 	    (uint64_t *)AHCI_PORT_PxFB(ahci_ctlp, port),
5799 	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
5800 
5801 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "64-bit, dma address: 0x%llx",
5802 	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
5803 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "32-bit, dma address: 0x%x",
5804 	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_address);
5805 
5806 	return (AHCI_SUCCESS);
5807 }
5808 
5809 /*
5810  * Deallocates the Received FIS Structure
5811  *
5812  * WARNING!!! ahciport_mutex should be acquired before the function
5813  * is called.
5814  */
5815 static void
5816 ahci_dealloc_rcvd_fis(ahci_port_t *ahci_portp)
5817 {
5818 	/* Unbind the cmd list dma handle first. */
5819 	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_rcvd_fis_dma_handle);
5820 
5821 	/* Then free the underlying memory. */
5822 	ddi_dma_mem_free(&ahci_portp->ahciport_rcvd_fis_acc_handle);
5823 
5824 	/* Now free the handle itself. */
5825 	ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
5826 }
5827 
5828 /*
5829  * Allocates memory for the Command List, which contains up to 32 entries.
5830  * Each entry contains a command header, which is a 32-byte structure that
5831  * includes the pointer to the command table.
5832  *
5833  * WARNING!!! ahciport_mutex should be acquired before the function
5834  * is called.
5835  */
5836 static int
5837 ahci_alloc_cmd_list(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
5838     uint8_t port)
5839 {
5840 	size_t cmd_list_size;
5841 	size_t ret_len;
5842 	uint_t cookie_count;
5843 
5844 	cmd_list_size =
5845 	    ahci_ctlp->ahcictl_num_cmd_slots * sizeof (ahci_cmd_header_t);
5846 
5847 	/* allocate cmd list dma handle. */
5848 	if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
5849 	    &ahci_ctlp->ahcictl_cmd_list_dma_attr,
5850 	    DDI_DMA_SLEEP,
5851 	    NULL,
5852 	    &ahci_portp->ahciport_cmd_list_dma_handle) != DDI_SUCCESS) {
5853 
5854 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5855 		    "cmd list dma handle alloc failed", NULL);
5856 		return (AHCI_FAILURE);
5857 	}
5858 
5859 	if (ddi_dma_mem_alloc(ahci_portp->ahciport_cmd_list_dma_handle,
5860 	    cmd_list_size,
5861 	    &accattr,
5862 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
5863 	    DDI_DMA_SLEEP,
5864 	    NULL,
5865 	    (caddr_t *)&ahci_portp->ahciport_cmd_list,
5866 	    &ret_len,
5867 	    &ahci_portp->ahciport_cmd_list_acc_handle) != NULL) {
5868 
5869 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5870 		    "cmd list dma mem alloc fail", NULL);
5871 		/* error.. free the dma handle. */
5872 		ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
5873 		return (AHCI_FAILURE);
5874 	}
5875 
5876 	if (ddi_dma_addr_bind_handle(ahci_portp->ahciport_cmd_list_dma_handle,
5877 	    NULL,
5878 	    (caddr_t)ahci_portp->ahciport_cmd_list,
5879 	    cmd_list_size,
5880 	    DDI_DMA_CONSISTENT,
5881 	    DDI_DMA_SLEEP,
5882 	    NULL,
5883 	    &ahci_portp->ahciport_cmd_list_dma_cookie,
5884 	    &cookie_count) !=  DDI_DMA_MAPPED) {
5885 
5886 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5887 		    "cmd list dma handle bind fail", NULL);
5888 		/*  error.. free the dma handle & free the memory. */
5889 		ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
5890 		ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
5891 		return (AHCI_FAILURE);
5892 	}
5893 
5894 	bzero((void *)ahci_portp->ahciport_cmd_list, cmd_list_size);
5895 
5896 	/* Config Port Command List Base Address */
5897 	ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
5898 	    (uint64_t *)AHCI_PORT_PxCLB(ahci_ctlp, port),
5899 	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
5900 
5901 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "64-bit, dma address: 0x%llx",
5902 	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
5903 
5904 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "32-bit, dma address: 0x%x",
5905 	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_address);
5906 
5907 	if (ahci_alloc_cmd_tables(ahci_ctlp, ahci_portp) != AHCI_SUCCESS) {
5908 		goto err_out;
5909 	}
5910 
5911 	return (AHCI_SUCCESS);
5912 
5913 err_out:
5914 	/* Unbind the cmd list dma handle first. */
5915 	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_cmd_list_dma_handle);
5916 
5917 	/* Then free the underlying memory. */
5918 	ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
5919 
5920 	/* Now free the handle itself. */
5921 	ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
5922 
5923 	return (AHCI_FAILURE);
5924 }
5925 
5926 /*
5927  * Deallocates the Command List
5928  *
5929  * WARNING!!! ahciport_mutex should be acquired before the function
5930  * is called.
5931  */
5932 static void
5933 ahci_dealloc_cmd_list(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
5934 {
5935 	/* First dealloc command table */
5936 	ahci_dealloc_cmd_tables(ahci_ctlp, ahci_portp);
5937 
5938 	/* Unbind the cmd list dma handle first. */
5939 	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_cmd_list_dma_handle);
5940 
5941 	/* Then free the underlying memory. */
5942 	ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
5943 
5944 	/* Now free the handle itself. */
5945 	ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
5946 }
5947 
5948 /*
5949  * Allocates memory for all Command Tables, which contains Command FIS,
5950  * ATAPI Command and Physical Region Descriptor Table.
5951  *
5952  * WARNING!!! ahciport_mutex should be acquired before the function
5953  * is called.
5954  */
5955 static int
5956 ahci_alloc_cmd_tables(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
5957 {
5958 	size_t ret_len;
5959 	ddi_dma_cookie_t cmd_table_dma_cookie;
5960 	uint_t cookie_count;
5961 	int slot;
5962 
5963 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
5964 	    "ahci_alloc_cmd_tables: port %d enter",
5965 	    ahci_portp->ahciport_port_num);
5966 
5967 	for (slot = 0; slot < ahci_ctlp->ahcictl_num_cmd_slots; slot++) {
5968 		/* Allocate cmd table dma handle. */
5969 		if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
5970 		    &ahci_ctlp->ahcictl_cmd_table_dma_attr,
5971 		    DDI_DMA_SLEEP,
5972 		    NULL,
5973 		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]) !=
5974 		    DDI_SUCCESS) {
5975 
5976 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5977 			    "cmd table dma handle alloc failed", NULL);
5978 
5979 			goto err_out;
5980 		}
5981 
5982 		if (ddi_dma_mem_alloc(
5983 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot],
5984 		    ahci_cmd_table_size,
5985 		    &accattr,
5986 		    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
5987 		    DDI_DMA_SLEEP,
5988 		    NULL,
5989 		    (caddr_t *)&ahci_portp->ahciport_cmd_tables[slot],
5990 		    &ret_len,
5991 		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]) !=
5992 		    NULL) {
5993 
5994 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
5995 			    "cmd table dma mem alloc fail", NULL);
5996 
5997 			/* error.. free the dma handle. */
5998 			ddi_dma_free_handle(
5999 			    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
6000 			goto err_out;
6001 		}
6002 
6003 		if (ddi_dma_addr_bind_handle(
6004 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot],
6005 		    NULL,
6006 		    (caddr_t)ahci_portp->ahciport_cmd_tables[slot],
6007 		    ahci_cmd_table_size,
6008 		    DDI_DMA_CONSISTENT,
6009 		    DDI_DMA_SLEEP,
6010 		    NULL,
6011 		    &cmd_table_dma_cookie,
6012 		    &cookie_count) !=  DDI_DMA_MAPPED) {
6013 
6014 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
6015 			    "cmd table dma handle bind fail", NULL);
6016 			/*  error.. free the dma handle & free the memory. */
6017 			ddi_dma_mem_free(
6018 			    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
6019 			ddi_dma_free_handle(
6020 			    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
6021 			goto err_out;
6022 		}
6023 
6024 		bzero((void *)ahci_portp->ahciport_cmd_tables[slot],
6025 		    ahci_cmd_table_size);
6026 
6027 		/* Config Port Command Table Base Address */
6028 		SET_COMMAND_TABLE_BASE_ADDR(
6029 		    (&ahci_portp->ahciport_cmd_list[slot]),
6030 		    cmd_table_dma_cookie.dmac_laddress & 0xffffffffull);
6031 
6032 #ifndef __lock_lint
6033 		SET_COMMAND_TABLE_BASE_ADDR_UPPER(
6034 		    (&ahci_portp->ahciport_cmd_list[slot]),
6035 		    cmd_table_dma_cookie.dmac_laddress >> 32);
6036 #endif
6037 	}
6038 
6039 	return (AHCI_SUCCESS);
6040 err_out:
6041 
6042 	for (slot--; slot >= 0; slot--) {
6043 		/* Unbind the cmd table dma handle first */
6044 		(void) ddi_dma_unbind_handle(
6045 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
6046 
6047 		/* Then free the underlying memory */
6048 		ddi_dma_mem_free(
6049 		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
6050 
6051 		/* Now free the handle itself */
6052 		ddi_dma_free_handle(
6053 		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
6054 	}
6055 
6056 	return (AHCI_FAILURE);
6057 }
6058 
6059 /*
6060  * Deallocates memory for all Command Tables.
6061  *
6062  * WARNING!!! ahciport_mutex should be acquired before the function
6063  * is called.
6064  */
6065 static void
6066 ahci_dealloc_cmd_tables(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
6067 {
6068 	int slot;
6069 
6070 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6071 	    "ahci_dealloc_cmd_tables: %d enter",
6072 	    ahci_portp->ahciport_port_num);
6073 
6074 	for (slot = 0; slot < ahci_ctlp->ahcictl_num_cmd_slots; slot++) {
6075 		/* Unbind the cmd table dma handle first. */
6076 		(void) ddi_dma_unbind_handle(
6077 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
6078 
6079 		/* Then free the underlying memory. */
6080 		ddi_dma_mem_free(
6081 		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
6082 
6083 		/* Now free the handle itself. */
6084 		ddi_dma_free_handle(
6085 		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
6086 	}
6087 }
6088 
6089 /*
6090  * Update SATA registers at controller ports
6091  *
6092  * WARNING!!! ahciport_mutex should be acquired before those functions
6093  * get called.
6094  */
6095 static void
6096 ahci_update_sata_registers(ahci_ctl_t *ahci_ctlp, uint8_t port,
6097     sata_device_t *sd)
6098 {
6099 	sd->satadev_scr.sstatus =
6100 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6101 	    (uint32_t *)(AHCI_PORT_PxSSTS(ahci_ctlp, port)));
6102 	sd->satadev_scr.serror =
6103 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6104 	    (uint32_t *)(AHCI_PORT_PxSERR(ahci_ctlp, port)));
6105 	sd->satadev_scr.scontrol =
6106 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6107 	    (uint32_t *)(AHCI_PORT_PxSCTL(ahci_ctlp, port)));
6108 	sd->satadev_scr.sactive =
6109 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6110 	    (uint32_t *)(AHCI_PORT_PxSACT(ahci_ctlp, port)));
6111 }
6112 
6113 /*
6114  * For poll mode, ahci_port_intr will be called to emulate the interrupt
6115  */
6116 static void
6117 ahci_port_intr(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
6118 {
6119 	uint32_t port_intr_status;
6120 	uint32_t port_intr_enable;
6121 
6122 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
6123 	    "ahci_port_intr enter: port %d", port);
6124 
6125 	mutex_enter(&ahci_portp->ahciport_mutex);
6126 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_POLLING) {
6127 		/* For SATA_OPMODE_POLLING commands */
6128 		port_intr_enable =
6129 		    (AHCI_INTR_STATUS_DHRS |
6130 		    AHCI_INTR_STATUS_PSS |
6131 		    AHCI_INTR_STATUS_SDBS |
6132 		    AHCI_INTR_STATUS_UFS |
6133 		    AHCI_INTR_STATUS_PCS |
6134 		    AHCI_INTR_STATUS_PRCS |
6135 		    AHCI_INTR_STATUS_OFS |
6136 		    AHCI_INTR_STATUS_INFS |
6137 		    AHCI_INTR_STATUS_IFS |
6138 		    AHCI_INTR_STATUS_HBDS |
6139 		    AHCI_INTR_STATUS_HBFS |
6140 		    AHCI_INTR_STATUS_TFES);
6141 	} else {
6142 		/*
6143 		 * port_intr_enable indicates that the corresponding interrrupt
6144 		 * reporting is enabled.
6145 		 */
6146 		port_intr_enable = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6147 		    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port));
6148 	}
6149 
6150 	/* IPMS error in port reset should be ignored according AHCI spec. */
6151 	if (!(ahci_portp->ahciport_flags & AHCI_PORT_FLAG_IGNORE_IPMS))
6152 		port_intr_enable |= AHCI_INTR_STATUS_IPMS;
6153 	mutex_exit(&ahci_portp->ahciport_mutex);
6154 
6155 	/*
6156 	 * port_intr_stats indicates that the corresponding interrupt
6157 	 * condition is active.
6158 	 */
6159 	port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6160 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
6161 
6162 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6163 	    "ahci_port_intr: port %d, port_intr_status = 0x%x, "
6164 	    "port_intr_enable = 0x%x",
6165 	    port, port_intr_status, port_intr_enable);
6166 
6167 	port_intr_status &= port_intr_enable;
6168 
6169 	/* First clear the port interrupts status */
6170 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6171 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
6172 	    port_intr_status);
6173 
6174 	/* Check the completed non-queued commands */
6175 	if (port_intr_status & (AHCI_INTR_STATUS_DHRS |
6176 	    AHCI_INTR_STATUS_PSS)) {
6177 		(void) ahci_intr_cmd_cmplt(ahci_ctlp,
6178 		    ahci_portp, port);
6179 	}
6180 
6181 	/* Check the completed queued commands */
6182 	if (port_intr_status & AHCI_INTR_STATUS_SDBS) {
6183 		(void) ahci_intr_set_device_bits(ahci_ctlp,
6184 		    ahci_portp, port);
6185 	}
6186 
6187 	/* Check the port connect change status interrupt bit */
6188 	if (port_intr_status & AHCI_INTR_STATUS_PCS) {
6189 		(void) ahci_intr_port_connect_change(ahci_ctlp,
6190 		    ahci_portp, port);
6191 	}
6192 
6193 	/* Check the device mechanical presence status interrupt bit */
6194 	if (port_intr_status & AHCI_INTR_STATUS_DMPS) {
6195 		(void) ahci_intr_device_mechanical_presence_status(
6196 		    ahci_ctlp, ahci_portp, port);
6197 	}
6198 
6199 	/* Check the PhyRdy change status interrupt bit */
6200 	if (port_intr_status & AHCI_INTR_STATUS_PRCS) {
6201 		(void) ahci_intr_phyrdy_change(ahci_ctlp, ahci_portp,
6202 		    port);
6203 	}
6204 
6205 	/*
6206 	 * Check the non-fatal error interrupt bits, there are four
6207 	 * kinds of non-fatal errors at the time being:
6208 	 *
6209 	 *    PxIS.UFS - Unknown FIS Error
6210 	 *    PxIS.OFS - Overflow Error
6211 	 *    PxIS.INFS - Interface Non-Fatal Error
6212 	 *    PxIS.IPMS - Incorrect Port Multiplier Status Error
6213 	 *
6214 	 * For these non-fatal errors, the HBA can continue to operate,
6215 	 * so the driver just log the error messages.
6216 	 */
6217 	if (port_intr_status & (AHCI_INTR_STATUS_UFS |
6218 	    AHCI_INTR_STATUS_OFS |
6219 	    AHCI_INTR_STATUS_IPMS |
6220 	    AHCI_INTR_STATUS_INFS)) {
6221 		(void) ahci_intr_non_fatal_error(ahci_ctlp, ahci_portp,
6222 		    port, port_intr_status);
6223 	}
6224 
6225 	/*
6226 	 * Check the fatal error interrupt bits, there are four kinds
6227 	 * of fatal errors for AHCI controllers:
6228 	 *
6229 	 *    PxIS.HBFS - Host Bus Fatal Error
6230 	 *    PxIS.HBDS - Host Bus Data Error
6231 	 *    PxIS.IFS - Interface Fatal Error
6232 	 *    PxIS.TFES - Task File Error
6233 	 *
6234 	 * The fatal error means the HBA can not recover from it by
6235 	 * itself, and it will try to abort the transfer, and the software
6236 	 * must intervene to restart the port.
6237 	 */
6238 	if (port_intr_status & (AHCI_INTR_STATUS_IFS |
6239 	    AHCI_INTR_STATUS_HBDS |
6240 	    AHCI_INTR_STATUS_HBFS |
6241 	    AHCI_INTR_STATUS_TFES))
6242 		(void) ahci_intr_fatal_error(ahci_ctlp, ahci_portp,
6243 		    port, port_intr_status);
6244 
6245 	/* Check the cold port detect interrupt bit */
6246 	if (port_intr_status & AHCI_INTR_STATUS_CPDS) {
6247 		(void) ahci_intr_cold_port_detect(ahci_ctlp, ahci_portp, port);
6248 	}
6249 
6250 	/* Second clear the corresponding bit in IS.IPS */
6251 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6252 	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp), (0x1 << port));
6253 }
6254 
6255 /*
6256  * Interrupt service handler
6257  */
6258 static uint_t
6259 ahci_intr(caddr_t arg1, caddr_t arg2)
6260 {
6261 #ifndef __lock_lint
6262 	_NOTE(ARGUNUSED(arg2))
6263 #endif
6264 	/* LINTED */
6265 	ahci_ctl_t *ahci_ctlp = (ahci_ctl_t *)arg1;
6266 	ahci_port_t *ahci_portp;
6267 	int32_t global_intr_status;
6268 	uint8_t port;
6269 
6270 	/*
6271 	 * global_intr_status indicates that the corresponding port has
6272 	 * an interrupt pending.
6273 	 */
6274 	global_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6275 	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp));
6276 
6277 	if (!(global_intr_status & ahci_ctlp->ahcictl_ports_implemented)) {
6278 		/* The interrupt is not ours */
6279 		return (DDI_INTR_UNCLAIMED);
6280 	}
6281 
6282 	/* Loop for all the ports */
6283 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
6284 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
6285 			continue;
6286 		}
6287 		if (!((0x1 << port) & global_intr_status)) {
6288 			continue;
6289 		}
6290 
6291 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
6292 
6293 		/* Call ahci_port_intr */
6294 		ahci_port_intr(ahci_ctlp, ahci_portp, port);
6295 	}
6296 
6297 	return (DDI_INTR_CLAIMED);
6298 }
6299 
6300 /*
6301  * For non-queued commands, when the corresponding bit in the PxCI register
6302  * is cleared, it means the command is completed successfully. And according
6303  * to the HBA state machine, there are three conditions which possibly will
6304  * try to clear the PxCI register bit.
6305  *	1. Receive one D2H Register FIS which is with 'I' bit set
6306  *	2. Update PIO Setup FIS
6307  *	3. Transmit a command and receive R_OK if CTBA.C is set (software reset)
6308  *
6309  * Process completed non-queued commands when the interrupt status bit -
6310  * AHCI_INTR_STATUS_DHRS or AHCI_INTR_STATUS_PSS is set.
6311  *
6312  * AHCI_INTR_STATUS_DHRS means a D2H Register FIS has been received
6313  * with the 'I' bit set. And the following commands will send thus
6314  * FIS with 'I' bit set upon the successful completion:
6315  * 	1. Non-data commands
6316  * 	2. DMA data-in command
6317  * 	3. DMA data-out command
6318  * 	4. PIO data-out command
6319  *	5. PACKET non-data commands
6320  *	6. PACKET PIO data-in command
6321  *	7. PACKET PIO data-out command
6322  *	8. PACKET DMA data-in command
6323  *	9. PACKET DMA data-out command
6324  *
6325  * AHCI_INTR_STATUS_PSS means a PIO Setup FIS has been received
6326  * with the 'I' bit set. And the following commands will send this
6327  * FIS upon the successful completion:
6328  * 	1. PIO data-in command
6329  */
6330 static int
6331 ahci_intr_cmd_cmplt(ahci_ctl_t *ahci_ctlp,
6332     ahci_port_t *ahci_portp, uint8_t port)
6333 {
6334 	uint32_t port_cmd_issue = 0;
6335 	uint32_t finished_tags;
6336 	int finished_slot;
6337 	sata_pkt_t *satapkt;
6338 	ahci_fis_d2h_register_t *rcvd_fisp;
6339 #if AHCI_DEBUG
6340 	ahci_cmd_header_t *cmd_header;
6341 	uint32_t cmd_dmacount;
6342 #endif
6343 
6344 	mutex_enter(&ahci_portp->ahciport_mutex);
6345 
6346 	if (!ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
6347 	    !RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp) &&
6348 	    !NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6349 		/*
6350 		 * Spurious interrupt. Nothing to be done.
6351 		 */
6352 		mutex_exit(&ahci_portp->ahciport_mutex);
6353 		return (AHCI_SUCCESS);
6354 	}
6355 
6356 	port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6357 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
6358 
6359 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6360 		/* Slot 0 is always used during error recovery */
6361 		finished_tags = 0x1 & ~port_cmd_issue;
6362 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6363 		    "ahci_intr_cmd_cmplt: port %d the sata pkt for error "
6364 		    "retrieval is finished, and finished_tags = 0x%x",
6365 		    port, finished_tags);
6366 	} else if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
6367 		finished_tags = 0x1 & ~port_cmd_issue;
6368 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
6369 		    "ahci_intr_cmd_cmplt: port %d the sata pkt for r/w "
6370 		    "port multiplier is finished, and finished_tags = 0x%x",
6371 		    port, finished_tags);
6372 
6373 	} else {
6374 
6375 		finished_tags = ahci_portp->ahciport_pending_tags &
6376 		    ~port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp);
6377 	}
6378 
6379 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6380 	    "ahci_intr_cmd_cmplt: pending_tags = 0x%x, "
6381 	    "port_cmd_issue = 0x%x finished_tags = 0x%x",
6382 	    ahci_portp->ahciport_pending_tags, port_cmd_issue,
6383 	    finished_tags);
6384 
6385 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
6386 	    (finished_tags == 0x1)) {
6387 		satapkt = ahci_portp->ahciport_err_retri_pkt;
6388 		ASSERT(satapkt != NULL);
6389 
6390 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6391 		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
6392 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
6393 
6394 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
6395 		goto out;
6396 	}
6397 
6398 	if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp) &&
6399 	    (finished_tags == 0x1)) {
6400 		satapkt = ahci_portp->ahciport_rdwr_pmult_pkt;
6401 		ASSERT(satapkt != NULL);
6402 
6403 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6404 		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
6405 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
6406 
6407 		/* READ PORTMULT need copy out FIS content. */
6408 		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
6409 			rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
6410 			    ahcirf_d2h_register_fis);
6411 			satapkt->satapkt_cmd.satacmd_status_reg =
6412 			    GET_RFIS_STATUS(rcvd_fisp);
6413 			ahci_copy_out_regs(&satapkt->satapkt_cmd, rcvd_fisp);
6414 		}
6415 
6416 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
6417 		goto out;
6418 	}
6419 
6420 	while (finished_tags) {
6421 		finished_slot = ddi_ffs(finished_tags) - 1;
6422 		if (finished_slot == -1) {
6423 			goto out;
6424 		}
6425 
6426 		satapkt = ahci_portp->ahciport_slot_pkts[finished_slot];
6427 		ASSERT(satapkt != NULL);
6428 #if AHCI_DEBUG
6429 		/*
6430 		 * For non-native queued commands, the PRD byte count field
6431 		 * shall contain an accurate count of the number of bytes
6432 		 * transferred for the command before the PxCI bit is cleared
6433 		 * to '0' for the command.
6434 		 *
6435 		 * The purpose of this field is to let software know how many
6436 		 * bytes transferred for a given operation in order to
6437 		 * determine if underflow occurred. When issuing native command
6438 		 * queuing commands, this field should not be used and is not
6439 		 * required to be valid since in this case underflow is always
6440 		 * illegal.
6441 		 *
6442 		 * For data reads, the HBA will update its PRD byte count with
6443 		 * the total number of bytes received from the last FIS, and
6444 		 * may be able to continue normally. For data writes, the
6445 		 * device will detect an error, and HBA most likely will get
6446 		 * a fatal error.
6447 		 *
6448 		 * Therefore, here just put code to debug part. And please
6449 		 * refer to the comment above ahci_intr_fatal_error for the
6450 		 * definition of underflow error.
6451 		 */
6452 		cmd_dmacount =
6453 		    ahci_portp->ahciport_prd_bytecounts[finished_slot];
6454 		if (cmd_dmacount) {
6455 			cmd_header =
6456 			    &ahci_portp->ahciport_cmd_list[finished_slot];
6457 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_PRDT, ahci_ctlp,
6458 			    "ahci_intr_cmd_cmplt: port %d, "
6459 			    "PRD Byte Count = 0x%x, "
6460 			    "ahciport_prd_bytecounts = 0x%x", port,
6461 			    cmd_header->ahcich_prd_byte_count,
6462 			    cmd_dmacount);
6463 
6464 			if (cmd_header->ahcich_prd_byte_count != cmd_dmacount) {
6465 				AHCIDBG(AHCIDBG_UNDERFLOW, ahci_ctlp,
6466 				    "ahci_intr_cmd_cmplt: port %d, "
6467 				    "an underflow occurred", port);
6468 			}
6469 		}
6470 #endif
6471 
6472 		/*
6473 		 * For SATAC_SMART command with SATA_SMART_RETURN_STATUS
6474 		 * feature, sata_special_regs flag will be set, and the
6475 		 * driver should copy the status and the other corresponding
6476 		 * register values in the D2H Register FIS received (It's
6477 		 * working on Non-data protocol) from the device back to
6478 		 * the sata_cmd.
6479 		 *
6480 		 * For every AHCI port, there is only one Received FIS
6481 		 * structure, which contains the FISes received from the
6482 		 * device, So we're trying to copy the content of D2H
6483 		 * Register FIS in the Received FIS structure back to
6484 		 * the sata_cmd.
6485 		 */
6486 		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
6487 			rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
6488 			    ahcirf_d2h_register_fis);
6489 			satapkt->satapkt_cmd.satacmd_status_reg =
6490 			    GET_RFIS_STATUS(rcvd_fisp);
6491 			ahci_copy_out_regs(&satapkt->satapkt_cmd, rcvd_fisp);
6492 		}
6493 
6494 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6495 		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
6496 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
6497 
6498 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, finished_slot);
6499 		CLEAR_BIT(finished_tags, finished_slot);
6500 		ahci_portp->ahciport_slot_pkts[finished_slot] = NULL;
6501 
6502 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
6503 	}
6504 out:
6505 	AHCIDBG(AHCIDBG_PKTCOMP, ahci_ctlp,
6506 	    "ahci_intr_cmd_cmplt: pending_tags = 0x%x",
6507 	    ahci_portp->ahciport_pending_tags);
6508 
6509 	mutex_exit(&ahci_portp->ahciport_mutex);
6510 
6511 	return (AHCI_SUCCESS);
6512 }
6513 
6514 /*
6515  * AHCI_INTR_STATUS_SDBS means a Set Device Bits FIS has been received
6516  * with the 'I' bit set and has been copied into system memory. It will
6517  * be sent under the following situations:
6518  *
6519  * 1. NCQ command is completed
6520  *
6521  * The completion of NCQ commands (READ/WRITE FPDMA QUEUED) is performed
6522  * via the Set Device Bits FIS. When such event is generated, the software
6523  * needs to read PxSACT register and compares the current value to the
6524  * list of commands previously issue by software. ahciport_pending_ncq_tags
6525  * keeps the tags of previously issued commands.
6526  *
6527  * 2. Asynchronous Notification
6528  *
6529  * Asynchronous Notification is a feature in SATA spec 2.6.
6530  *
6531  * 1) ATAPI device will send a signal to the host when media is inserted or
6532  * removed and avoids polling the device for media changes. The signal
6533  * sent to the host is a Set Device Bits FIS with the 'I' and 'N' bits
6534  * set to '1'. At the moment, it's not supported yet.
6535  *
6536  * 2) Port multiplier will send a signal to the host when a hot plug event
6537  * has occured on a port multiplier port. It is used when command based
6538  * switching is employed. This is handled by ahci_intr_pmult_sntf_events()
6539  */
6540 static int
6541 ahci_intr_set_device_bits(ahci_ctl_t *ahci_ctlp,
6542     ahci_port_t *ahci_portp, uint8_t port)
6543 {
6544 	ahci_addr_t addr;
6545 
6546 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
6547 	    "ahci_intr_set_device_bits enter: port %d", port);
6548 
6549 	/* Initialize HBA port address */
6550 	AHCI_ADDR_SET_PORT(&addr, port);
6551 
6552 	/* NCQ plug handler */
6553 	(void) ahci_intr_ncq_events(ahci_ctlp, ahci_portp, &addr);
6554 
6555 	/* Check port multiplier's asynchronous notification events */
6556 	if (ahci_ctlp->ahcictl_cap & AHCI_CAP_SNTF) {
6557 		(void) ahci_intr_pmult_sntf_events(ahci_ctlp,
6558 		    ahci_portp, port);
6559 	}
6560 
6561 	/* ATAPI events is not supported yet */
6562 
6563 	return (AHCI_SUCCESS);
6564 }
6565 /*
6566  * NCQ interrupt handler. Called upon a NCQ command is completed.
6567  * Only be called from ahci_intr_set_device_bits().
6568  *
6569  * WARNING!!! ahciport_mutex should be acquired before the function is
6570  * called.
6571  */
6572 static int
6573 ahci_intr_ncq_events(ahci_ctl_t *ahci_ctlp,
6574     ahci_port_t *ahci_portp, ahci_addr_t *addrp)
6575 {
6576 	uint32_t port_sactive;
6577 	uint32_t port_cmd_issue;
6578 	uint32_t issued_tags;
6579 	int issued_slot;
6580 	uint32_t finished_tags;
6581 	int finished_slot;
6582 	uint8_t port = addrp->aa_port;
6583 	sata_pkt_t *satapkt;
6584 
6585 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
6586 	    "ahci_intr_set_device_bits enter: port %d", port);
6587 
6588 	mutex_enter(&ahci_portp->ahciport_mutex);
6589 	if (!NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6590 		mutex_exit(&ahci_portp->ahciport_mutex);
6591 		return (AHCI_SUCCESS);
6592 	}
6593 
6594 	/*
6595 	 * First the handler got which commands are finished by checking
6596 	 * PxSACT register
6597 	 */
6598 	port_sactive = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6599 	    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
6600 
6601 	finished_tags = ahci_portp->ahciport_pending_ncq_tags &
6602 	    ~port_sactive & AHCI_NCQ_SLOT_MASK(ahci_portp);
6603 
6604 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
6605 	    "ahci_intr_set_device_bits: port %d pending_ncq_tags = 0x%x "
6606 	    "port_sactive = 0x%x", port,
6607 	    ahci_portp->ahciport_pending_ncq_tags, port_sactive);
6608 
6609 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
6610 	    "ahci_intr_set_device_bits: finished_tags = 0x%x", finished_tags);
6611 
6612 	/*
6613 	 * For NCQ commands, the software can determine which command has
6614 	 * already been transmitted to the device by checking PxCI register.
6615 	 */
6616 	port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6617 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
6618 
6619 	issued_tags = ahci_portp->ahciport_pending_tags &
6620 	    ~port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp);
6621 
6622 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
6623 	    "ahci_intr_set_device_bits: port %d pending_tags = 0x%x "
6624 	    "port_cmd_issue = 0x%x", port,
6625 	    ahci_portp->ahciport_pending_tags, port_cmd_issue);
6626 
6627 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
6628 	    "ahci_intr_set_device_bits: issued_tags = 0x%x", issued_tags);
6629 
6630 	/*
6631 	 * Clear ahciport_pending_tags bit when the corresponding command
6632 	 * is already sent down to the device.
6633 	 */
6634 	while (issued_tags) {
6635 		issued_slot = ddi_ffs(issued_tags) - 1;
6636 		if (issued_slot == -1) {
6637 			goto next;
6638 		}
6639 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, issued_slot);
6640 		CLEAR_BIT(issued_tags, issued_slot);
6641 	}
6642 
6643 next:
6644 	while (finished_tags) {
6645 		finished_slot = ddi_ffs(finished_tags) - 1;
6646 		if (finished_slot == -1) {
6647 			goto out;
6648 		}
6649 
6650 		/* The command is certainly transmitted to the device */
6651 		ASSERT(!(ahci_portp->ahciport_pending_tags &
6652 		    (0x1 << finished_slot)));
6653 
6654 		satapkt = ahci_portp->ahciport_slot_pkts[finished_slot];
6655 		ASSERT(satapkt != NULL);
6656 
6657 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
6658 		    "ahci_intr_set_device_bits: sending up pkt 0x%p "
6659 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
6660 
6661 		CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags, finished_slot);
6662 		CLEAR_BIT(finished_tags, finished_slot);
6663 		ahci_portp->ahciport_slot_pkts[finished_slot] = NULL;
6664 
6665 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
6666 	}
6667 out:
6668 	AHCIDBG(AHCIDBG_PKTCOMP|AHCIDBG_NCQ, ahci_ctlp,
6669 	    "ahci_intr_set_device_bits: port %d "
6670 	    "pending_ncq_tags = 0x%x pending_tags = 0x%x",
6671 	    port, ahci_portp->ahciport_pending_ncq_tags,
6672 	    ahci_portp->ahciport_pending_tags);
6673 
6674 	mutex_exit(&ahci_portp->ahciport_mutex);
6675 
6676 	return (AHCI_SUCCESS);
6677 }
6678 
6679 /*
6680  * Port multiplier asynchronous notification event handler. Called upon a
6681  * device is hot plugged/pulled.
6682  *
6683  * The async-notification event will only be recorded by ahcipmi_snotif_tags
6684  * here and will be handled by ahci_probe_pmult().
6685  *
6686  * NOTE: called only from ahci_port_intr().
6687  */
6688 static int
6689 ahci_intr_pmult_sntf_events(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
6690     uint8_t port)
6691 {
6692 	sata_device_t sdevice;
6693 
6694 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
6695 	    "ahci_intr_pmult_sntf_events enter: port %d ", port);
6696 
6697 	/* no hot-plug while attaching process */
6698 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
6699 	if (ahci_ctlp->ahcictl_flags & AHCI_ATTACH) {
6700 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
6701 		return (AHCI_SUCCESS);
6702 	}
6703 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
6704 
6705 	mutex_enter(&ahci_portp->ahciport_mutex);
6706 	if (ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT) {
6707 		mutex_exit(&ahci_portp->ahciport_mutex);
6708 		return (AHCI_SUCCESS);
6709 	}
6710 
6711 	ASSERT(ahci_portp->ahciport_pmult_info != NULL);
6712 
6713 	ahci_portp->ahciport_pmult_info->ahcipmi_snotif_tags =
6714 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6715 	    (uint32_t *)AHCI_PORT_PxSNTF(ahci_ctlp, port));
6716 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6717 	    (uint32_t *)AHCI_PORT_PxSNTF(ahci_ctlp, port),
6718 	    AHCI_SNOTIF_CLEAR_ALL);
6719 
6720 	if (ahci_portp->ahciport_pmult_info->ahcipmi_snotif_tags == 0) {
6721 		mutex_exit(&ahci_portp->ahciport_mutex);
6722 		return (AHCI_SUCCESS);
6723 	}
6724 
6725 	/* Port Multiplier sub-device hot-plug handler */
6726 	if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
6727 		mutex_exit(&ahci_portp->ahciport_mutex);
6728 		return (AHCI_SUCCESS);
6729 	}
6730 
6731 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_PMULT_SNTF) {
6732 		/* Not allowed to re-enter. */
6733 		mutex_exit(&ahci_portp->ahciport_mutex);
6734 		return (AHCI_SUCCESS);
6735 	}
6736 
6737 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_PMULT_SNTF;
6738 
6739 	/*
6740 	 * NOTE:
6741 	 * Even if Asynchronous Notification is supported (and enabled) by
6742 	 * both controller and the port multiplier, the content of PxSNTF
6743 	 * register is always set to 0x8000 by async notification event. We
6744 	 * need to check GSCR[32] on the port multiplier to find out the
6745 	 * owner of this event.
6746 	 * This is not accord with SATA spec 2.6 and needs further
6747 	 * clarification.
6748 	 */
6749 	/* hot-plug will not reported while reseting. */
6750 	if (ahci_portp->ahciport_reset_in_progress == 1) {
6751 		AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
6752 		    "port %d snotif event ignored", port);
6753 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_PMULT_SNTF;
6754 		mutex_exit(&ahci_portp->ahciport_mutex);
6755 		return (AHCI_SUCCESS);
6756 	}
6757 
6758 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_PMULT, ahci_ctlp,
6759 	    "PxSNTF is set to 0x%x by port multiplier",
6760 	    ahci_portp->ahciport_pmult_info->ahcipmi_snotif_tags);
6761 
6762 	/*
6763 	 * Now we need do some necessary operation and inform SATA framework
6764 	 * that link/device events has happened.
6765 	 */
6766 	bzero((void *)&sdevice, sizeof (sata_device_t));
6767 	sdevice.satadev_addr.cport = ahci_ctlp->
6768 	    ahcictl_port_to_cport[port];
6769 	sdevice.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
6770 	sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
6771 	sdevice.satadev_state = SATA_PSTATE_PWRON;
6772 
6773 	/* Just reject packets, do not stop that port. */
6774 	ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
6775 
6776 	mutex_exit(&ahci_portp->ahciport_mutex);
6777 	sata_hba_event_notify(
6778 	    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
6779 	    &sdevice,
6780 	    SATA_EVNT_PMULT_LINK_CHANGED);
6781 	mutex_enter(&ahci_portp->ahciport_mutex);
6782 
6783 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_PMULT_SNTF;
6784 	mutex_exit(&ahci_portp->ahciport_mutex);
6785 
6786 	return (AHCI_SUCCESS);
6787 }
6788 
6789 /*
6790  * 1=Change in Current Connect Status. 0=No change in Current Connect Status.
6791  * This bit reflects the state of PxSERR.DIAG.X. This bit is only cleared
6792  * when PxSERR.DIAG.X is cleared. When PxSERR.DIAG.X is set to one, it
6793  * indicates a COMINIT signal was received.
6794  *
6795  * Hot plug insertion is detected by reception of a COMINIT signal from the
6796  * device. On reception of unsolicited COMINIT, the HBA shall generate a
6797  * COMRESET. If the COMINIT is in responce to a COMRESET, then the HBA shall
6798  * begin the normal communication negotiation sequence as outlined in the
6799  * Serial ATA 1.0a specification. When a COMRESET is sent to the device the
6800  * PxSSTS.DET field shall be cleared to 0h. When a COMINIT is received, the
6801  * PxSSTS.DET field shall be set to 1h. When the communication negotiation
6802  * sequence is complete and PhyRdy is true the PxSSTS.DET field	shall be set
6803  * to 3h. Therefore, at the moment the ahci driver is going to check PhyRdy
6804  * to handle hot plug insertion. In this interrupt handler, just do nothing
6805  * but print some log message and clear the bit.
6806  */
6807 static int
6808 ahci_intr_port_connect_change(ahci_ctl_t *ahci_ctlp,
6809     ahci_port_t *ahci_portp, uint8_t port)
6810 {
6811 #if AHCI_DEBUG
6812 	uint32_t port_serror;
6813 #endif
6814 
6815 	mutex_enter(&ahci_portp->ahciport_mutex);
6816 
6817 #if AHCI_DEBUG
6818 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6819 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
6820 
6821 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
6822 	    "ahci_intr_port_connect_change: port %d, "
6823 	    "port_serror = 0x%x", port, port_serror);
6824 #endif
6825 
6826 	/* Clear PxSERR.DIAG.X to clear the interrupt bit */
6827 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6828 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
6829 	    SERROR_EXCHANGED_ERR);
6830 
6831 	mutex_exit(&ahci_portp->ahciport_mutex);
6832 
6833 	return (AHCI_SUCCESS);
6834 }
6835 
6836 /*
6837  * Hot Plug Operation for platforms that support Mechanical Presence
6838  * Switches.
6839  *
6840  * When set, it indicates that a mechanical presence switch attached to this
6841  * port has been opened or closed, which may lead to a change in the connection
6842  * state of the device. This bit is only valid if both CAP.SMPS and PxCMD.MPSP
6843  * are set to '1'.
6844  *
6845  * At the moment, this interrupt is not needed and disabled and we just log
6846  * the debug message.
6847  */
6848 static int
6849 ahci_intr_device_mechanical_presence_status(ahci_ctl_t *ahci_ctlp,
6850     ahci_port_t *ahci_portp, uint8_t port)
6851 {
6852 	uint32_t cap_status, port_cmd_status;
6853 
6854 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
6855 	    "ahci_intr_device_mechanical_presence_status enter, "
6856 	    "port %d", port);
6857 
6858 	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6859 	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
6860 
6861 	mutex_enter(&ahci_portp->ahciport_mutex);
6862 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6863 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6864 
6865 	if (!(cap_status & AHCI_HBA_CAP_SMPS) ||
6866 	    !(port_cmd_status & AHCI_CMD_STATUS_MPSP)) {
6867 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6868 		    "CAP.SMPS or PxCMD.MPSP is not set, so just ignore "
6869 		    "the interrupt: cap_status = 0x%x, "
6870 		    "port_cmd_status = 0x%x", cap_status, port_cmd_status);
6871 		mutex_exit(&ahci_portp->ahciport_mutex);
6872 
6873 		return (AHCI_SUCCESS);
6874 	}
6875 
6876 #if AHCI_DEBUG
6877 	if (port_cmd_status & AHCI_CMD_STATUS_MPSS) {
6878 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6879 		    "The mechanical presence switch is open: "
6880 		    "port %d, port_cmd_status = 0x%x",
6881 		    port, port_cmd_status);
6882 	} else {
6883 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
6884 		    "The mechanical presence switch is close: "
6885 		    "port %d, port_cmd_status = 0x%x",
6886 		    port, port_cmd_status);
6887 	}
6888 #endif
6889 
6890 	mutex_exit(&ahci_portp->ahciport_mutex);
6891 
6892 	return (AHCI_SUCCESS);
6893 }
6894 
6895 /*
6896  * Native Hot Plug Support.
6897  *
6898  * When set, it indicates that the internal PHYRDY signal changed state.
6899  * This bit reflects the state of PxSERR.DIAG.N.
6900  *
6901  * There are three kinds of conditions to generate this interrupt event:
6902  * 1. a device is inserted
6903  * 2. a device is disconnected
6904  * 3. when the link enters/exits a Partial or Slumber interface power
6905  *    management state
6906  *
6907  * If inteface power management is enabled for a port, the PxSERR.DIAG.N
6908  * bit may be set due to the link entering the Partial or Slumber power
6909  * management state, rather than due to a hot plug insertion or removal
6910  * event. So far, the interface power management is disabled, so the
6911  * driver can reliably get removal detection notification via the
6912  * PxSERR.DIAG.N bit.
6913  */
6914 static int
6915 ahci_intr_phyrdy_change(ahci_ctl_t *ahci_ctlp,
6916     ahci_port_t *ahci_portp, uint8_t port)
6917 {
6918 	uint32_t port_sstatus = 0; /* No dev present & PHY not established. */
6919 	sata_device_t sdevice;
6920 	int dev_exists_now = 0;
6921 	int dev_existed_previously = 0;
6922 	ahci_addr_t port_addr;
6923 
6924 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
6925 	    "ahci_intr_phyrdy_change enter, port %d", port);
6926 
6927 	/* Clear PxSERR.DIAG.N to clear the interrupt bit */
6928 	mutex_enter(&ahci_portp->ahciport_mutex);
6929 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6930 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
6931 	    SERROR_PHY_RDY_CHG);
6932 	mutex_exit(&ahci_portp->ahciport_mutex);
6933 
6934 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
6935 	if ((ahci_ctlp->ahcictl_sata_hba_tran == NULL) ||
6936 	    (ahci_portp == NULL)) {
6937 		/* The whole controller setup is not yet done. */
6938 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
6939 		return (AHCI_SUCCESS);
6940 	}
6941 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
6942 
6943 	mutex_enter(&ahci_portp->ahciport_mutex);
6944 
6945 	/* SStatus tells the presence of device. */
6946 	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6947 	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
6948 
6949 	if (SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_PHYCOM) {
6950 		dev_exists_now = 1;
6951 	}
6952 
6953 	if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) {
6954 		dev_existed_previously = 1;
6955 	}
6956 
6957 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_NODEV) {
6958 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_NODEV;
6959 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6960 		    "ahci_intr_phyrdy_change: port %d "
6961 		    "AHCI_PORT_FLAG_NODEV is cleared", port);
6962 		if (dev_exists_now == 0)
6963 			dev_existed_previously = 1;
6964 	}
6965 
6966 	bzero((void *)&sdevice, sizeof (sata_device_t));
6967 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
6968 	sdevice.satadev_addr.qual = SATA_ADDR_CPORT;
6969 	sdevice.satadev_addr.pmport = 0;
6970 	sdevice.satadev_state = SATA_PSTATE_PWRON;
6971 	ahci_portp->ahciport_port_state = SATA_PSTATE_PWRON;
6972 
6973 	AHCI_ADDR_SET_PORT(&port_addr, port);
6974 
6975 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_HOTPLUG;
6976 	if (dev_exists_now) {
6977 		if (dev_existed_previously) { /* 1 -> 1 */
6978 			/* Things are fine now. The loss was temporary. */
6979 			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
6980 			    "ahci_intr_phyrdy_change  port %d "
6981 			    "device link lost/established", port);
6982 
6983 			mutex_exit(&ahci_portp->ahciport_mutex);
6984 			sata_hba_event_notify(
6985 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
6986 			    &sdevice,
6987 			    SATA_EVNT_LINK_LOST|SATA_EVNT_LINK_ESTABLISHED);
6988 			mutex_enter(&ahci_portp->ahciport_mutex);
6989 
6990 		} else { /* 0 -> 1 */
6991 			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
6992 			    "ahci_intr_phyrdy_change: port %d "
6993 			    "device link established", port);
6994 
6995 			/*
6996 			 * A new device has been detected. The new device
6997 			 * might be a port multiplier instead of a drive, so
6998 			 * we cannot update the signature directly.
6999 			 */
7000 			(void) ahci_initialize_port(ahci_ctlp,
7001 			    ahci_portp, &port_addr);
7002 
7003 			/* Try to start the port */
7004 			if (ahci_start_port(ahci_ctlp, ahci_portp, port)
7005 			    != AHCI_SUCCESS) {
7006 				sdevice.satadev_state |= SATA_PSTATE_FAILED;
7007 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
7008 				    "ahci_intr_phyrdy_change: port %d failed "
7009 				    "at start port", port);
7010 			}
7011 
7012 			/* Clear the max queue depth for inserted device */
7013 			ahci_portp->ahciport_max_ncq_tags = 0;
7014 
7015 			mutex_exit(&ahci_portp->ahciport_mutex);
7016 			sata_hba_event_notify(
7017 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
7018 			    &sdevice,
7019 			    SATA_EVNT_LINK_ESTABLISHED);
7020 			mutex_enter(&ahci_portp->ahciport_mutex);
7021 
7022 		}
7023 	} else { /* No device exists now */
7024 
7025 		if (dev_existed_previously) { /* 1 -> 0 */
7026 			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
7027 			    "ahci_intr_phyrdy_change: port %d "
7028 			    "device link lost", port);
7029 
7030 			ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
7031 			(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
7032 			    ahci_portp, port);
7033 
7034 			if (ahci_portp->ahciport_device_type ==
7035 			    SATA_DTYPE_PMULT) {
7036 				ahci_dealloc_pmult(ahci_ctlp, ahci_portp);
7037 			}
7038 
7039 			/* An existing device is lost. */
7040 			ahci_portp->ahciport_device_type = SATA_DTYPE_NONE;
7041 			ahci_portp->ahciport_port_state = SATA_STATE_UNKNOWN;
7042 
7043 			mutex_exit(&ahci_portp->ahciport_mutex);
7044 			sata_hba_event_notify(
7045 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
7046 			    &sdevice,
7047 			    SATA_EVNT_LINK_LOST);
7048 			mutex_enter(&ahci_portp->ahciport_mutex);
7049 		}
7050 	}
7051 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_HOTPLUG;
7052 
7053 	mutex_exit(&ahci_portp->ahciport_mutex);
7054 
7055 	return (AHCI_SUCCESS);
7056 }
7057 
7058 /*
7059  * PxIS.UFS - Unknown FIS Error
7060  *
7061  * This interrupt event means an unknown FIS was received and has been
7062  * copied into system memory. An unknown FIS is not considered an illegal
7063  * FIS, unless the length received is more than 64 bytes. If an unknown
7064  * FIS arrives with length <= 64 bytes, it is posted and the HBA continues
7065  * normal operation. If the unknown FIS is more than 64 bytes, then it
7066  * won't be posted to memory and PxSERR.ERR.P will be set, which is then
7067  * a fatal error.
7068  *
7069  * PxIS.IPMS - Incorrect Port Multiplier Status
7070  *
7071  * IPMS Indicates that the HBA received a FIS from a device that did not
7072  * have a command outstanding. The IPMS bit may be set during enumeration
7073  * of devices on a Port Multiplier due to the normal Port Multiplier
7074  * enumeration process. It is recommended that IPMS only be used after
7075  * enumeration is complete on the Port Multiplier (copied from spec).
7076  *
7077  * PxIS.OFS - Overflow Error
7078  *
7079  * Command list overflow is defined as software building a command table
7080  * that has fewer total bytes than the transaction given to the device.
7081  * On device writes, the HBA will run out of data, and on reads, there
7082  * will be no room to put the data.
7083  *
7084  * For an overflow on data read, either PIO or DMA, the HBA will set
7085  * PxIS.OFS, and the HBA will do a best effort to continue, and it's a
7086  * non-fatal error when the HBA can continues. Sometimes, it will cause
7087  * a fatal error and need the software to do something.
7088  *
7089  * For an overflow on data write, setting PxIS.OFS is optional for both
7090  * DMA and PIO, and it's a fatal error, and a COMRESET is required by
7091  * software to clean up from this serious error.
7092  *
7093  * PxIS.INFS - Interface Non-Fatal Error
7094  *
7095  * This interrupt event indicates that the HBA encountered an error on
7096  * the Serial ATA interface but was able to continue operation. The kind
7097  * of error usually occurred during a non-Data FIS, and under this condition
7098  * the FIS will be re-transmitted by HBA automatically.
7099  *
7100  * When the FMA is implemented, there should be a stat structure to
7101  * record how many every kind of error happens.
7102  */
7103 static int
7104 ahci_intr_non_fatal_error(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
7105     uint8_t port, uint32_t intr_status)
7106 {
7107 	uint32_t port_serror;
7108 #if AHCI_DEBUG
7109 	uint32_t port_cmd_status;
7110 	uint32_t port_cmd_issue;
7111 	uint32_t port_sactive;
7112 	int current_slot;
7113 	uint32_t current_tags;
7114 	sata_pkt_t *satapkt;
7115 	ahci_cmd_header_t *cmd_header;
7116 	uint32_t cmd_dmacount;
7117 #endif
7118 
7119 	mutex_enter(&ahci_portp->ahciport_mutex);
7120 
7121 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7122 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
7123 
7124 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY|AHCIDBG_ERRS, ahci_ctlp,
7125 	    "ahci_intr_non_fatal_error: port %d, "
7126 	    "PxSERR = 0x%x, PxIS = 0x%x ", port, port_serror, intr_status);
7127 
7128 	ahci_log_serror_message(ahci_ctlp, port, port_serror, 1);
7129 
7130 	if (intr_status & AHCI_INTR_STATUS_UFS) {
7131 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
7132 		    "ahci port %d has unknown FIS error", port);
7133 
7134 		/* Clear the interrupt bit by clearing PxSERR.DIAG.F */
7135 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7136 		    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
7137 		    SERROR_FIS_TYPE);
7138 	}
7139 
7140 #if AHCI_DEBUG
7141 	if (intr_status & AHCI_INTR_STATUS_IPMS) {
7142 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci port %d "
7143 		    "has Incorrect Port Multiplier Status error", port);
7144 	}
7145 
7146 	if (intr_status & AHCI_INTR_STATUS_OFS) {
7147 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7148 		    "ahci port %d has overflow error", port);
7149 	}
7150 
7151 	if (intr_status & AHCI_INTR_STATUS_INFS) {
7152 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7153 		    "ahci port %d has interface non fatal error", port);
7154 	}
7155 
7156 	/*
7157 	 * Record the error occurred command's slot.
7158 	 */
7159 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
7160 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7161 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7162 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7163 
7164 		current_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
7165 		    AHCI_CMD_STATUS_CCS_SHIFT;
7166 
7167 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7168 			satapkt = ahci_portp->ahciport_err_retri_pkt;
7169 			ASSERT(satapkt != NULL);
7170 			ASSERT(current_slot == 0);
7171 		} else {
7172 			satapkt = ahci_portp->ahciport_slot_pkts[current_slot];
7173 		}
7174 
7175 		if (satapkt != NULL) {
7176 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7177 			    "ahci_intr_non_fatal_error: pending_tags = 0x%x "
7178 			    "cmd 0x%x", ahci_portp->ahciport_pending_tags,
7179 			    satapkt->satapkt_cmd.satacmd_cmd_reg);
7180 
7181 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7182 			    "ahci_intr_non_fatal_error: port %d, "
7183 			    "satapkt 0x%p is being processed when error occurs",
7184 			    port, (void *)satapkt);
7185 
7186 			/*
7187 			 * PRD Byte Count field of command header is not
7188 			 * required to reflect the total number of bytes
7189 			 * transferred when an overflow occurs, so here
7190 			 * just log the value.
7191 			 */
7192 			cmd_dmacount =
7193 			    ahci_portp->ahciport_prd_bytecounts[current_slot];
7194 			if (cmd_dmacount) {
7195 				cmd_header = &ahci_portp->
7196 				    ahciport_cmd_list[current_slot];
7197 				AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7198 				    "ahci_intr_non_fatal_error: port %d, "
7199 				    "PRD Byte Count = 0x%x, "
7200 				    "ahciport_prd_bytecounts = 0x%x", port,
7201 				    cmd_header->ahcich_prd_byte_count,
7202 				    cmd_dmacount);
7203 			}
7204 		}
7205 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7206 		/*
7207 		 * For queued command, list those command which have already
7208 		 * been transmitted to the device and still not completed.
7209 		 */
7210 		port_sactive = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7211 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
7212 
7213 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7214 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
7215 
7216 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ|AHCIDBG_ERRS, ahci_ctlp,
7217 		    "ahci_intr_non_fatal_error: pending_ncq_tags = 0x%x "
7218 		    "port_sactive = 0x%x port_cmd_issue = 0x%x",
7219 		    ahci_portp->ahciport_pending_ncq_tags,
7220 		    port_sactive, port_cmd_issue);
7221 
7222 		current_tags = ahci_portp->ahciport_pending_ncq_tags &
7223 		    port_sactive & ~port_cmd_issue &
7224 		    AHCI_NCQ_SLOT_MASK(ahci_portp);
7225 
7226 		while (current_tags) {
7227 			current_slot = ddi_ffs(current_tags) - 1;
7228 			if (current_slot == -1) {
7229 				goto out;
7230 			}
7231 
7232 			satapkt = ahci_portp->ahciport_slot_pkts[current_slot];
7233 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ|AHCIDBG_ERRS,
7234 			    ahci_ctlp, "ahci_intr_non_fatal_error: "
7235 			    "port %d, satapkt 0x%p is outstanding when "
7236 			    "error occurs", port, (void *)satapkt);
7237 
7238 			CLEAR_BIT(current_tags, current_slot);
7239 		}
7240 	}
7241 out:
7242 #endif
7243 	mutex_exit(&ahci_portp->ahciport_mutex);
7244 
7245 	return (AHCI_SUCCESS);
7246 }
7247 
7248 /*
7249  * According to the AHCI spec, the error types include system memory
7250  * errors, interface errors, port multiplier errors, device errors,
7251  * command list overflow, command list underflow, native command
7252  * queuing tag errors and pio data transfer errors.
7253  *
7254  * System memory errors such as target abort, master abort, and parity
7255  * may cause the host to stop, and they are serious errors and needed
7256  * to be recovered with software intervention. When system software
7257  * has given a pointer to the HBA that doesn't exist in physical memory,
7258  * a master/target abort error occurs, and PxIS.HBFS will be set. A
7259  * data error such as CRC or parity occurs, the HBA aborts the transfer
7260  * (if necessary) and PxIS.HBDS will be set.
7261  *
7262  * Interface errors are errors that occur due to electrical issues on
7263  * the interface, or protocol miscommunication between the device and
7264  * HBA, and the respective PxSERR register bit will be set. And PxIS.IFS
7265  * (fatal) or PxIS.INFS (non-fatal) will be set. The conditions that
7266  * causes PxIS.IFS/PxIS.INFS to be set are
7267  * 	1. in PxSERR.ERR, P bit is set to '1'
7268  *	2. in PxSERR.DIAG, C or H bit is set to '1'
7269  *	3. PhyRdy drop unexpectly, N bit is set to '1'
7270  * If the error occurred during a non-data FIS, the FIS must be
7271  * retransmitted, and the error is non-fatal and PxIS.INFS is set. If
7272  * the error occurred during a data FIS, the transfer will stop, so
7273  * the error is fatal and PxIS.IFS is set.
7274  *
7275  * When a FIS arrives that updates the taskfile, the HBA checks to see
7276  * if PxTFD.STS.ERR is set. If yes, PxIS.TFES will be set and the HBA
7277  * stops processing any more commands.
7278  *
7279  * Command list overflow is defined as software building a command table
7280  * that has fewer total bytes than the transaction given to the device.
7281  * On device writes, the HBA will run out of data, and on reads, there
7282  * will be no room to put the data. For an overflow on data read, either
7283  * PIO or DMA, the HBA will set PxIS.OFS, and it's a non-fatal error.
7284  * For an overflow on data write, setting PxIS.OFS is optional for both
7285  * DMA and PIO, and a COMRESET is required by software to clean up from
7286  * this serious error.
7287  *
7288  * Command list underflow is defined as software building a command
7289  * table that has more total bytes than the transaction given to the
7290  * device. For data writes, both PIO and DMA, the device will detect
7291  * an error and end the transfer. And these errors are most likely going
7292  * to be fatal errors that will cause the port to be restarted. For
7293  * data reads, the HBA updates its PRD byte count, and may be
7294  * able to continue normally, but is not required to. And The HBA is
7295  * not required to detect underflow conditions for native command
7296  * queuing command.
7297  *
7298  * The HBA does not actively check incoming DMA Setup FISes to ensure
7299  * that the PxSACT register bit for that slot is set. Existing error
7300  * mechanisms, such as host bus failure, or bad protocol, are used to
7301  * recover from this case.
7302  *
7303  * In accordance with Serial ATA 1.0a, DATA FISes prior to the final
7304  * DATA FIS must be an integral number of Dwords. If the HBA receives
7305  * a request which is not an integral number of Dwords, the HBA
7306  * set PxSERR.ERR.P to '1', set PxIS.IFS to '1' and stop running until
7307  * software restarts the port. And the HBA ensures that the size
7308  * of the DATA FIS received during a PIO command matches the size in
7309  * the Transfer Cound field of the preceding PIO Setup FIS, if not, the
7310  * HBA sets PxSERR.ERR.P to '1', set PxIS.IFS to '1', and then
7311  * stop running until software restarts the port.
7312  */
7313 /*
7314  * the fatal errors include PxIS.IFS, PxIS.HBDS, PxIS.HBFS and PxIS.TFES.
7315  *
7316  * PxIS.IFS indicates that the hba encountered an error on the serial ata
7317  * interface which caused the transfer to stop.
7318  *
7319  * PxIS.HBDS indicates that the hba encountered a data error
7320  * (uncorrectable ecc/parity) when reading from or writing to system memory.
7321  *
7322  * PxIS.HBFS indicates that the hba encountered a host bus error that it
7323  * cannot recover from, such as a bad software pointer.
7324  *
7325  * PxIS.TFES is set whenever the status register is updated by the device
7326  * and the error bit (bit 0) is set.
7327  */
7328 static int
7329 ahci_intr_fatal_error(ahci_ctl_t *ahci_ctlp,
7330     ahci_port_t *ahci_portp, uint8_t port, uint32_t intr_status)
7331 {
7332 	uint32_t port_cmd_status;
7333 	uint32_t port_serror;
7334 	uint32_t task_file_status;
7335 	int failed_slot;
7336 	sata_pkt_t *spkt = NULL;
7337 	uint8_t err_byte;
7338 	ahci_event_arg_t *args;
7339 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
7340 
7341 	mutex_enter(&ahci_portp->ahciport_mutex);
7342 
7343 	/*
7344 	 * ahci_intr_phyrdy_change() may have rendered it to
7345 	 * SATA_DTYPE_NONE.
7346 	 */
7347 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
7348 		AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
7349 		    "ahci_intr_fatal_error: port %d no device attached, "
7350 		    "and just return without doing anything", port);
7351 		goto out0;
7352 	}
7353 
7354 	if (intr_status & AHCI_INTR_STATUS_TFES) {
7355 		task_file_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7356 		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
7357 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7358 		    "ahci_intr_fatal_error: port %d "
7359 		    "task_file_status = 0x%x", port, task_file_status);
7360 	}
7361 
7362 	/*
7363 	 * Here we just log the fatal error info in interrupt context.
7364 	 * Misc recovery processing will be handled in task queue.
7365 	 */
7366 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7367 		/*
7368 		 * Read PxCMD.CCS to determine the slot that the HBA
7369 		 * was processing when the error occurred.
7370 		 */
7371 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7372 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7373 		failed_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
7374 		    AHCI_CMD_STATUS_CCS_SHIFT;
7375 
7376 		spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
7377 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7378 		    "ahci_intr_fatal_error: spkt 0x%p is being processed when "
7379 		    "fatal error occurred for port %d", spkt, port);
7380 
7381 		/* A Task File Data error. */
7382 		if (intr_status & AHCI_INTR_STATUS_TFES) {
7383 			err_byte = (task_file_status & AHCI_TFD_ERR_MASK)
7384 			    >> AHCI_TFD_ERR_SHIFT;
7385 
7386 			/*
7387 			 * Won't emit the error message if it is an IDENTIFY
7388 			 * DEVICE command sent to an ATAPI device.
7389 			 */
7390 			if ((spkt != NULL) &&
7391 			    (spkt->satapkt_cmd.satacmd_cmd_reg ==
7392 			    SATAC_ID_DEVICE) &&
7393 			    (err_byte == SATA_ERROR_ABORT))
7394 				goto out1;
7395 
7396 			/*
7397 			 * Won't emit the error message if it is an ATAPI PACKET
7398 			 * command
7399 			 */
7400 			if ((spkt != NULL) &&
7401 			    (spkt->satapkt_cmd.satacmd_cmd_reg == SATAC_PACKET))
7402 				goto out1;
7403 		}
7404 	}
7405 
7406 	/* print the fatal error type */
7407 	ahci_log_fatal_error_message(ahci_ctlp, port, intr_status);
7408 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7409 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
7410 
7411 	/* print PxSERR related error message */
7412 	ahci_log_serror_message(ahci_ctlp, port, port_serror, 0);
7413 
7414 	/* print task file register value */
7415 	if (intr_status & AHCI_INTR_STATUS_TFES) {
7416 		cmn_err(CE_WARN, "!ahci%d: ahci port %d task_file_status "
7417 		    "= 0x%x", instance, port, task_file_status);
7418 	}
7419 
7420 out1:
7421 	/* Prepare the argument for the taskq */
7422 	args = ahci_portp->ahciport_event_args;
7423 	args->ahciea_ctlp = (void *)ahci_ctlp;
7424 	args->ahciea_portp = (void *)ahci_portp;
7425 	args->ahciea_event = intr_status;
7426 	AHCI_ADDR_SET_PORT((ahci_addr_t *)args->ahciea_addrp, port);
7427 
7428 	/* Start the taskq to handle error recovery */
7429 	if ((ddi_taskq_dispatch(ahci_portp->ahciport_event_taskq,
7430 	    ahci_events_handler,
7431 	    (void *)args, DDI_NOSLEEP)) != DDI_SUCCESS) {
7432 		cmn_err(CE_WARN, "!ahci%d: ahci start taskq for event handler "
7433 		    "failed", instance);
7434 	}
7435 out0:
7436 	mutex_exit(&ahci_portp->ahciport_mutex);
7437 
7438 	return (AHCI_SUCCESS);
7439 }
7440 
7441 /*
7442  * Hot Plug Operation for platforms that support Cold Presence Detect.
7443  *
7444  * When set, a device status has changed as detected by the cold presence
7445  * detect logic. This bit can either be set due to a non-connected port
7446  * receiving a device, or a connected port having its device removed.
7447  * This bit is only valid if the port supports cold presence detect as
7448  * indicated by PxCMD.CPD set to '1'.
7449  *
7450  * At the moment, this interrupt is not needed and disabled and we just
7451  * log the debug message.
7452  */
7453 static int
7454 ahci_intr_cold_port_detect(ahci_ctl_t *ahci_ctlp,
7455     ahci_port_t *ahci_portp, uint8_t port)
7456 {
7457 	uint32_t port_cmd_status;
7458 	sata_device_t sdevice;
7459 
7460 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
7461 	    "ahci_intr_cold_port_detect enter, port %d", port);
7462 
7463 	mutex_enter(&ahci_portp->ahciport_mutex);
7464 
7465 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7466 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7467 	if (!(port_cmd_status & AHCI_CMD_STATUS_CPD)) {
7468 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
7469 		    "port %d does not support cold presence detect, so "
7470 		    "we just ignore this interrupt", port);
7471 		mutex_exit(&ahci_portp->ahciport_mutex);
7472 		return (AHCI_SUCCESS);
7473 	}
7474 
7475 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
7476 	    "port %d device status has changed", port);
7477 
7478 	bzero((void *)&sdevice, sizeof (sata_device_t));
7479 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
7480 	sdevice.satadev_addr.qual = SATA_ADDR_CPORT;
7481 	sdevice.satadev_addr.pmport = 0;
7482 	sdevice.satadev_state = SATA_PSTATE_PWRON;
7483 
7484 	if (port_cmd_status & AHCI_CMD_STATUS_CPS) {
7485 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
7486 		    "port %d: a device is hot plugged", port);
7487 		mutex_exit(&ahci_portp->ahciport_mutex);
7488 		sata_hba_event_notify(
7489 		    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
7490 		    &sdevice,
7491 		    SATA_EVNT_DEVICE_ATTACHED);
7492 		mutex_enter(&ahci_portp->ahciport_mutex);
7493 
7494 	} else {
7495 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
7496 		    "port %d: a device is hot unplugged", port);
7497 		mutex_exit(&ahci_portp->ahciport_mutex);
7498 		sata_hba_event_notify(
7499 		    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
7500 		    &sdevice,
7501 		    SATA_EVNT_DEVICE_DETACHED);
7502 		mutex_enter(&ahci_portp->ahciport_mutex);
7503 	}
7504 
7505 	mutex_exit(&ahci_portp->ahciport_mutex);
7506 
7507 	return (AHCI_SUCCESS);
7508 }
7509 
7510 /*
7511  * Enable the interrupts for a particular port.
7512  *
7513  * WARNING!!! ahciport_mutex should be acquired before the function
7514  * is called.
7515  */
7516 static void
7517 ahci_enable_port_intrs(ahci_ctl_t *ahci_ctlp, uint8_t port)
7518 {
7519 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
7520 	    "ahci_enable_port_intrs enter, port %d", port);
7521 
7522 	/*
7523 	 * Clear port interrupt status before enabling interrupt
7524 	 */
7525 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7526 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
7527 	    AHCI_PORT_INTR_MASK);
7528 
7529 	/*
7530 	 * Clear the pending bit from IS.IPS
7531 	 */
7532 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7533 	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp), (1 << port));
7534 
7535 	/*
7536 	 * Enable the following interrupts:
7537 	 *	Device to Host Register FIS Interrupt (DHRS)
7538 	 *	PIO Setup FIS Interrupt (PSS)
7539 	 *	Set Device Bits Interrupt (SDBS)
7540 	 *	Unknown FIS Interrupt (UFS)
7541 	 *	Port Connect Change Status (PCS)
7542 	 *	PhyRdy Change Status (PRCS)
7543 	 *	Overflow Status (OFS)
7544 	 *	Interface Non-fatal Error Status (INFS)
7545 	 *	Interface Fatal Error Status (IFS)
7546 	 *	Host Bus Data Error Status (HBDS)
7547 	 *	Host Bus Fatal Error Status (HBFS)
7548 	 *	Task File Error Status (TFES)
7549 	 */
7550 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7551 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port),
7552 	    (AHCI_INTR_STATUS_DHRS |
7553 	    AHCI_INTR_STATUS_PSS |
7554 	    AHCI_INTR_STATUS_SDBS |
7555 	    AHCI_INTR_STATUS_UFS |
7556 	    AHCI_INTR_STATUS_DPS |
7557 	    AHCI_INTR_STATUS_PCS |
7558 	    AHCI_INTR_STATUS_PRCS |
7559 	    AHCI_INTR_STATUS_OFS |
7560 	    AHCI_INTR_STATUS_INFS |
7561 	    AHCI_INTR_STATUS_IFS |
7562 	    AHCI_INTR_STATUS_HBDS |
7563 	    AHCI_INTR_STATUS_HBFS |
7564 	    AHCI_INTR_STATUS_TFES));
7565 }
7566 
7567 /*
7568  * Enable interrupts for all the ports.
7569  *
7570  * WARNING!!! ahcictl_mutex should be acquired before the function
7571  * is called.
7572  */
7573 static void
7574 ahci_enable_all_intrs(ahci_ctl_t *ahci_ctlp)
7575 {
7576 	uint32_t ghc_control;
7577 
7578 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_enable_all_intrs enter", NULL);
7579 
7580 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7581 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
7582 
7583 	ghc_control |= AHCI_HBA_GHC_IE;
7584 
7585 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7586 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
7587 }
7588 
7589 /*
7590  * Disable interrupts for a particular port.
7591  *
7592  * WARNING!!! ahciport_mutex should be acquired before the function
7593  * is called.
7594  */
7595 static void
7596 ahci_disable_port_intrs(ahci_ctl_t *ahci_ctlp, uint8_t port)
7597 {
7598 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
7599 	    "ahci_disable_port_intrs enter, port %d", port);
7600 
7601 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7602 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port), 0);
7603 }
7604 
7605 /*
7606  * Disable interrupts for the whole HBA.
7607  *
7608  * The global bit is cleared, then all interrupt sources from all
7609  * ports are disabled.
7610  *
7611  * WARNING!!! ahcictl_mutex should be acquired before the function
7612  * is called.
7613  */
7614 static void
7615 ahci_disable_all_intrs(ahci_ctl_t *ahci_ctlp)
7616 {
7617 	uint32_t ghc_control;
7618 
7619 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_disable_all_intrs enter",
7620 	    NULL);
7621 
7622 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7623 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
7624 
7625 	ghc_control &= ~ AHCI_HBA_GHC_IE;
7626 
7627 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7628 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
7629 }
7630 
7631 /*
7632  * Handle FIXED or MSI interrupts.
7633  */
7634 /*
7635  * According to AHCI spec, the HBA may support several interrupt modes:
7636  *	* pin based interrupts (FIXED)
7637  *	* single MSI message interrupts
7638  *	* multiple MSI based message interrupts
7639  *
7640  * For pin based interrupts, the software interrupt handler need to check IS
7641  * register to find out which port has pending interrupts. And then check
7642  * PxIS register to find out which interrupt events happened on that port.
7643  *
7644  * For single MSI message interrupts, MSICAP.MC.MSIE is set with '1', and
7645  * MSICAP.MC.MME is set with '0'. This mode is similar to pin based interrupts
7646  * in that software interrupt handler need to check IS register to determine
7647  * which port triggered the interrupts since it uses a single message for all
7648  * port interrupts.
7649  *
7650  * HBA may optionally support multiple MSI message for better performance. In
7651  * this mode, each port may have its own interrupt message, and thus generation
7652  * of interrupts is no longer controlled through the IS register. MSICAP.MC.MMC
7653  * represents a power-of-2 wrapper on the number of implemented ports, and
7654  * the mapping of ports to interrupts is done in a 1-1 relationship, up to the
7655  * maximum number of assigned interrupts. When the number of MSI messages
7656  * allocated is less than the number requested, then hardware may have two
7657  * implementation behaviors:
7658  *	* assign each ports its own interrupt and then force all additional
7659  *	  ports to share the last interrupt message, and this condition is
7660  *	  indicated by clearing GHC.MRSM to '0'
7661  *	* revert to single MSI mode, indicated by setting GHC.MRSM to '1'
7662  * When multiple-message MSI is enabled, hardware will still set IS register
7663  * as single message case. And this IS register may be used by software when
7664  * fewer than the requested number of messages is granted in order to determine
7665  * which port had the interrupt.
7666  *
7667  * Note: The current ahci driver only supports the first two interrupt modes:
7668  * pin based interrupts and single MSI message interrupts, and the reason
7669  * is indicated in below code.
7670  */
7671 static int
7672 ahci_add_intrs(ahci_ctl_t *ahci_ctlp, int intr_type)
7673 {
7674 	dev_info_t *dip = ahci_ctlp->ahcictl_dip;
7675 	int		count, avail, actual;
7676 	int		i, rc;
7677 
7678 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
7679 	    "ahci_add_intrs enter interrupt type 0x%x", intr_type);
7680 
7681 	/* get number of interrupts. */
7682 	rc = ddi_intr_get_nintrs(dip, intr_type, &count);
7683 	if ((rc != DDI_SUCCESS) || (count == 0)) {
7684 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7685 		    "ddi_intr_get_nintrs() failed, "
7686 		    "rc %d count %d\n", rc, count);
7687 		return (DDI_FAILURE);
7688 	}
7689 
7690 	/* get number of available interrupts. */
7691 	rc = ddi_intr_get_navail(dip, intr_type, &avail);
7692 	if ((rc != DDI_SUCCESS) || (avail == 0)) {
7693 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7694 		    "ddi_intr_get_navail() failed, "
7695 		    "rc %d avail %d\n", rc, avail);
7696 		return (DDI_FAILURE);
7697 	}
7698 
7699 #if AHCI_DEBUG
7700 	if (avail < count) {
7701 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7702 		    "ddi_intr_get_nintrs returned %d, navail() returned %d",
7703 		    count, avail);
7704 	}
7705 #endif
7706 
7707 	/*
7708 	 * Note: So far Solaris restricts the maximum number of messages for
7709 	 * x86 to 2, that is avail is 2, so here we set the count with 1 to
7710 	 * force the driver to use single MSI message interrupt. In future if
7711 	 * Solaris remove the restriction, then we need to delete the below
7712 	 * code and try to use multiple interrupt routine to gain better
7713 	 * performance.
7714 	 */
7715 	if ((intr_type == DDI_INTR_TYPE_MSI) && (count > 1)) {
7716 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
7717 		    "force to use one interrupt routine though the "
7718 		    "HBA supports %d interrupt", count);
7719 		count = 1;
7720 	}
7721 
7722 	/* Allocate an array of interrupt handles. */
7723 	ahci_ctlp->ahcictl_intr_size = count * sizeof (ddi_intr_handle_t);
7724 	ahci_ctlp->ahcictl_intr_htable =
7725 	    kmem_alloc(ahci_ctlp->ahcictl_intr_size, KM_SLEEP);
7726 
7727 	/* call ddi_intr_alloc(). */
7728 	rc = ddi_intr_alloc(dip, ahci_ctlp->ahcictl_intr_htable,
7729 	    intr_type, 0, count, &actual, DDI_INTR_ALLOC_NORMAL);
7730 
7731 	if ((rc != DDI_SUCCESS) || (actual == 0)) {
7732 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7733 		    "ddi_intr_alloc() failed, rc %d count %d actual %d "
7734 		    "avail %d\n", rc, count, actual, avail);
7735 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
7736 		    ahci_ctlp->ahcictl_intr_size);
7737 		return (DDI_FAILURE);
7738 	}
7739 
7740 	/* use interrupt count returned */
7741 #if AHCI_DEBUG
7742 	if (actual < count) {
7743 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7744 		    "Requested: %d, Received: %d", count, actual);
7745 	}
7746 #endif
7747 
7748 	ahci_ctlp->ahcictl_intr_cnt = actual;
7749 
7750 	/*
7751 	 * Get priority for first, assume remaining are all the same.
7752 	 */
7753 	if (ddi_intr_get_pri(ahci_ctlp->ahcictl_intr_htable[0],
7754 	    &ahci_ctlp->ahcictl_intr_pri) != DDI_SUCCESS) {
7755 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7756 		    "ddi_intr_get_pri() failed", NULL);
7757 
7758 		/* Free already allocated intr. */
7759 		for (i = 0; i < actual; i++) {
7760 			(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[i]);
7761 		}
7762 
7763 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
7764 		    ahci_ctlp->ahcictl_intr_size);
7765 		return (DDI_FAILURE);
7766 	}
7767 
7768 	/* Test for high level interrupt. */
7769 	if (ahci_ctlp->ahcictl_intr_pri >= ddi_intr_get_hilevel_pri()) {
7770 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7771 		    "ahci_add_intrs: Hi level intr not supported", NULL);
7772 
7773 		/* Free already allocated intr. */
7774 		for (i = 0; i < actual; i++) {
7775 			(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[i]);
7776 		}
7777 
7778 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
7779 		    sizeof (ddi_intr_handle_t));
7780 
7781 		return (DDI_FAILURE);
7782 	}
7783 
7784 	/* Call ddi_intr_add_handler(). */
7785 	for (i = 0; i < actual; i++) {
7786 		if (ddi_intr_add_handler(ahci_ctlp->ahcictl_intr_htable[i],
7787 		    ahci_intr, (caddr_t)ahci_ctlp, NULL) != DDI_SUCCESS) {
7788 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7789 			    "ddi_intr_add_handler() failed", NULL);
7790 
7791 			/* Free already allocated intr. */
7792 			for (i = 0; i < actual; i++) {
7793 				(void) ddi_intr_free(
7794 				    ahci_ctlp->ahcictl_intr_htable[i]);
7795 			}
7796 
7797 			kmem_free(ahci_ctlp->ahcictl_intr_htable,
7798 			    ahci_ctlp->ahcictl_intr_size);
7799 			return (DDI_FAILURE);
7800 		}
7801 	}
7802 
7803 	if (ddi_intr_get_cap(ahci_ctlp->ahcictl_intr_htable[0],
7804 	    &ahci_ctlp->ahcictl_intr_cap) != DDI_SUCCESS) {
7805 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
7806 		    "ddi_intr_get_cap() failed", NULL);
7807 
7808 		/* Free already allocated intr. */
7809 		for (i = 0; i < actual; i++) {
7810 			(void) ddi_intr_free(
7811 			    ahci_ctlp->ahcictl_intr_htable[i]);
7812 		}
7813 
7814 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
7815 		    ahci_ctlp->ahcictl_intr_size);
7816 		return (DDI_FAILURE);
7817 	}
7818 
7819 	if (ahci_ctlp->ahcictl_intr_cap & DDI_INTR_FLAG_BLOCK) {
7820 		/* Call ddi_intr_block_enable() for MSI. */
7821 		(void) ddi_intr_block_enable(ahci_ctlp->ahcictl_intr_htable,
7822 		    ahci_ctlp->ahcictl_intr_cnt);
7823 	} else {
7824 		/* Call ddi_intr_enable() for FIXED or MSI non block enable. */
7825 		for (i = 0; i < ahci_ctlp->ahcictl_intr_cnt; i++) {
7826 			(void) ddi_intr_enable(
7827 			    ahci_ctlp->ahcictl_intr_htable[i]);
7828 		}
7829 	}
7830 
7831 	return (DDI_SUCCESS);
7832 }
7833 
7834 /*
7835  * Removes the registered interrupts irrespective of whether they
7836  * were legacy or MSI.
7837  *
7838  * WARNING!!! The controller interrupts must be disabled before calling
7839  * this routine.
7840  */
7841 static void
7842 ahci_rem_intrs(ahci_ctl_t *ahci_ctlp)
7843 {
7844 	int x;
7845 
7846 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_rem_intrs entered", NULL);
7847 
7848 	/* Disable all interrupts. */
7849 	if ((ahci_ctlp->ahcictl_intr_type == DDI_INTR_TYPE_MSI) &&
7850 	    (ahci_ctlp->ahcictl_intr_cap & DDI_INTR_FLAG_BLOCK)) {
7851 		/* Call ddi_intr_block_disable(). */
7852 		(void) ddi_intr_block_disable(ahci_ctlp->ahcictl_intr_htable,
7853 		    ahci_ctlp->ahcictl_intr_cnt);
7854 	} else {
7855 		for (x = 0; x < ahci_ctlp->ahcictl_intr_cnt; x++) {
7856 			(void) ddi_intr_disable(
7857 			    ahci_ctlp->ahcictl_intr_htable[x]);
7858 		}
7859 	}
7860 
7861 	/* Call ddi_intr_remove_handler(). */
7862 	for (x = 0; x < ahci_ctlp->ahcictl_intr_cnt; x++) {
7863 		(void) ddi_intr_remove_handler(
7864 		    ahci_ctlp->ahcictl_intr_htable[x]);
7865 		(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[x]);
7866 	}
7867 
7868 	kmem_free(ahci_ctlp->ahcictl_intr_htable, ahci_ctlp->ahcictl_intr_size);
7869 }
7870 
7871 /*
7872  * This routine tries to put port into P:NotRunning state by clearing
7873  * PxCMD.ST. HBA will clear PxCI to 0h, PxSACT to 0h, PxCMD.CCS to 0h
7874  * and PxCMD.CR to '0'.
7875  *
7876  * WARNING!!! ahciport_mutex should be acquired before the function
7877  * is called.
7878  */
7879 static int
7880 ahci_put_port_into_notrunning_state(ahci_ctl_t *ahci_ctlp,
7881     ahci_port_t *ahci_portp, uint8_t port)
7882 {
7883 	uint32_t port_cmd_status;
7884 	int loop_count;
7885 
7886 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
7887 	    "ahci_put_port_into_notrunning_state enter: port %d", port);
7888 
7889 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7890 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7891 
7892 	port_cmd_status &= ~AHCI_CMD_STATUS_ST;
7893 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
7894 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port), port_cmd_status);
7895 
7896 	/* Wait until PxCMD.CR is cleared */
7897 	loop_count = 0;
7898 	do {
7899 		port_cmd_status =
7900 		    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7901 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7902 
7903 		if (loop_count++ > AHCI_POLLRATE_PORT_IDLE) {
7904 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
7905 			    "clearing port %d CMD.CR timeout, "
7906 			    "port_cmd_status = 0x%x", port,
7907 			    port_cmd_status);
7908 			/*
7909 			 * We are effectively timing out after 0.5 sec.
7910 			 * This value is specified in AHCI spec.
7911 			 */
7912 			break;
7913 		}
7914 
7915 		/* Wait for 10 millisec */
7916 		drv_usecwait(AHCI_10MS_USECS);
7917 	} while (port_cmd_status & AHCI_CMD_STATUS_CR);
7918 
7919 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_STARTED;
7920 
7921 	if (port_cmd_status & AHCI_CMD_STATUS_CR) {
7922 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
7923 		    "ahci_put_port_into_notrunning_state: failed to clear "
7924 		    "PxCMD.CR to '0' after loop count: %d, and "
7925 		    "port_cmd_status = 0x%x", loop_count, port_cmd_status);
7926 		return (AHCI_FAILURE);
7927 	} else {
7928 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
7929 		    "ahci_put_port_into_notrunning_state: succeeded to clear "
7930 		    "PxCMD.CR to '0' after loop count: %d, and "
7931 		    "port_cmd_status = 0x%x", loop_count, port_cmd_status);
7932 		return (AHCI_SUCCESS);
7933 	}
7934 }
7935 
7936 /*
7937  * First clear PxCMD.ST, and then check PxTFD. If both PxTFD.STS.BSY
7938  * and PxTFD.STS.DRQ cleared to '0', it means the device is in a
7939  * stable state, then set PxCMD.ST to '1' to start the port directly.
7940  * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then issue a
7941  * COMRESET to the device to put it in an idle state.
7942  *
7943  * The fifth argument returns whether the port reset is involved during
7944  * the process.
7945  *
7946  * The routine will be called under following scenarios:
7947  * 	+ To reset the HBA
7948  *	+ To abort the packet(s)
7949  *	+ To reset the port
7950  *	+ To activate the port
7951  *	+ Fatal error recovery
7952  *	+ To abort the timeout packet(s)
7953  *
7954  * WARNING!!! ahciport_mutex should be acquired before the function
7955  * is called. And ahciport_mutex will be released before the reset
7956  * event is reported to sata module by calling sata_hba_event_notify,
7957  * and then be acquired again later.
7958  *
7959  * NOTES!!! During this procedure, PxSERR register will be cleared, and
7960  * according to the spec, the clearance of three bits will also clear
7961  * three interrupt status bits.
7962  *	1. PxSERR.DIAG.F will clear PxIS.UFS
7963  *	2. PxSERR.DIAG.X will clear PxIS.PCS
7964  *	3. PxSERR.DIAG.N will clear PxIS.PRCS
7965  *
7966  * Among these three interrupt events, the driver needs to take care of
7967  * PxIS.PRCS, which is the hot plug event. When the driver found out
7968  * a device was unplugged, it will call the interrupt handler.
7969  */
7970 static int
7971 ahci_restart_port_wait_till_ready(ahci_ctl_t *ahci_ctlp,
7972     ahci_port_t *ahci_portp, uint8_t port, int flag, int *reset_flag)
7973 {
7974 	uint32_t port_sstatus;
7975 	uint32_t task_file_status;
7976 	sata_device_t sdevice;
7977 	int rval;
7978 	ahci_addr_t addr_port;
7979 	ahci_pmult_info_t *pminfo = NULL;
7980 	int dev_exists_begin = 0;
7981 	int dev_exists_end = 0;
7982 	uint32_t previous_dev_type = ahci_portp->ahciport_device_type;
7983 	int npmport = 0;
7984 	uint8_t cport = ahci_ctlp->ahcictl_port_to_cport[port];
7985 
7986 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
7987 	    "ahci_restart_port_wait_till_ready: port %d enter", port);
7988 
7989 	AHCI_ADDR_SET_PORT(&addr_port, port);
7990 
7991 	if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE)
7992 		dev_exists_begin = 1;
7993 
7994 	/* First clear PxCMD.ST */
7995 	rval = ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp,
7996 	    port);
7997 	if (rval != AHCI_SUCCESS)
7998 		/*
7999 		 * If PxCMD.CR does not clear within a reasonable time, it
8000 		 * may assume the interface is in a hung condition and may
8001 		 * continue with issuing the port reset.
8002 		 */
8003 		goto reset;
8004 
8005 	/* Then clear PxSERR */
8006 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
8007 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
8008 	    AHCI_SERROR_CLEAR_ALL);
8009 
8010 	/* Then get PxTFD */
8011 	task_file_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
8012 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
8013 
8014 	/*
8015 	 * Check whether the device is in a stable status, if yes,
8016 	 * then start the port directly. However for ahci_tran_reset_dport,
8017 	 * we may have to perform a port reset.
8018 	 */
8019 	if (!(task_file_status & (AHCI_TFD_STS_BSY | AHCI_TFD_STS_DRQ)) &&
8020 	    !(flag & AHCI_PORT_RESET))
8021 		goto out;
8022 
8023 reset:
8024 	/*
8025 	 * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then issue
8026 	 * a COMRESET to the device
8027 	 */
8028 	ahci_disable_port_intrs(ahci_ctlp, port);
8029 	rval = ahci_port_reset(ahci_ctlp, ahci_portp, &addr_port);
8030 	ahci_enable_port_intrs(ahci_ctlp, port);
8031 
8032 #ifdef AHCI_DEBUG
8033 	if (rval != AHCI_SUCCESS)
8034 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8035 		    "ahci_restart_port_wait_till_ready: port %d failed",
8036 		    port);
8037 #endif
8038 
8039 	if (reset_flag != NULL)
8040 		*reset_flag = 1;
8041 
8042 	/* Indicate to the framework that a reset has happened. */
8043 	if ((ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) &&
8044 	    (ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT) &&
8045 	    !(flag & AHCI_RESET_NO_EVENTS_UP)) {
8046 		/* Set the reset in progress flag */
8047 		ahci_portp->ahciport_reset_in_progress = 1;
8048 
8049 		bzero((void *)&sdevice, sizeof (sata_device_t));
8050 		sdevice.satadev_addr.cport =
8051 		    ahci_ctlp->ahcictl_port_to_cport[port];
8052 		sdevice.satadev_addr.pmport = 0;
8053 		sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
8054 
8055 		sdevice.satadev_state = SATA_DSTATE_RESET |
8056 		    SATA_DSTATE_PWR_ACTIVE;
8057 		if (ahci_ctlp->ahcictl_sata_hba_tran) {
8058 			mutex_exit(&ahci_portp->ahciport_mutex);
8059 			sata_hba_event_notify(
8060 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
8061 			    &sdevice,
8062 			    SATA_EVNT_DEVICE_RESET);
8063 			mutex_enter(&ahci_portp->ahciport_mutex);
8064 		}
8065 
8066 		AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
8067 		    "port %d sending event up: SATA_EVNT_DEVICE_RESET", port);
8068 	} else {
8069 		ahci_portp->ahciport_reset_in_progress = 0;
8070 	}
8071 
8072 out:
8073 	(void) ahci_start_port(ahci_ctlp, ahci_portp, port);
8074 
8075 	/* SStatus tells the presence of device. */
8076 	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
8077 	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
8078 
8079 	if (SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_PHYCOM) {
8080 		dev_exists_end = 1;
8081 	}
8082 
8083 	if (dev_exists_begin == 0 && dev_exists_end == 0) /* 0 -> 0 */
8084 		return (rval);
8085 
8086 	/* Check whether a hot plug event happened */
8087 	if (dev_exists_begin == 1 && dev_exists_end == 0) { /* 1 -> 0 */
8088 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8089 		    "ahci_restart_port_wait_till_ready: port %d "
8090 		    "device is removed", port);
8091 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_NODEV;
8092 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8093 		    "ahci_restart_port_wait_till_ready: port %d "
8094 		    "AHCI_PORT_FLAG_NODEV flag is set", port);
8095 		mutex_exit(&ahci_portp->ahciport_mutex);
8096 		(void) ahci_intr_phyrdy_change(ahci_ctlp, ahci_portp, port);
8097 		mutex_enter(&ahci_portp->ahciport_mutex);
8098 
8099 		return (rval);
8100 	}
8101 
8102 
8103 	/* 0/1 -> 1 : device may change */
8104 	/*
8105 	 * May be called by ahci_fatal_error_recovery_handler, so
8106 	 * don't issue software if the previous device is ATAPI.
8107 	 */
8108 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_ATAPI)
8109 		return (rval);
8110 
8111 	/*
8112 	 * The COMRESET will make port multiplier enter legacy mode.
8113 	 * Issue a software reset to make it work again.
8114 	 */
8115 	ahci_find_dev_signature(ahci_ctlp, ahci_portp, &addr_port);
8116 
8117 	/*
8118 	 * Following codes are specific for the port multiplier
8119 	 */
8120 	if (previous_dev_type != SATA_DTYPE_PMULT &&
8121 	    ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT) {
8122 		/* in case previous_dev_type is corrupt */
8123 		ahci_dealloc_pmult(ahci_ctlp, ahci_portp);
8124 		(void) ahci_start_port(ahci_ctlp, ahci_portp, port);
8125 		return (rval);
8126 	}
8127 
8128 	/* Device change: PMult -> Non-PMult */
8129 	if (previous_dev_type == SATA_DTYPE_PMULT &&
8130 	    ahci_portp->ahciport_device_type != SATA_DTYPE_PMULT) {
8131 		/*
8132 		 * This might happen because
8133 		 * 1. Software reset failed. Port multiplier is not correctly
8134 		 *    enumerated.
8135 		 * 2. Another non-port-multiplier device is attached. Perhaps
8136 		 *    the port multiplier was replaced by another device by
8137 		 *    whatever reason, but AHCI driver missed hot-plug event.
8138 		 *
8139 		 * Now that the port has been initialized, we just need to
8140 		 * update the port structure according new device, then report
8141 		 * and wait SATA framework to probe new device.
8142 		 */
8143 
8144 		/* Force to release pmult resource */
8145 		ahci_dealloc_pmult(ahci_ctlp, ahci_portp);
8146 		(void) ahci_start_port(ahci_ctlp, ahci_portp, port);
8147 
8148 		bzero((void *)&sdevice, sizeof (sata_device_t));
8149 		sdevice.satadev_addr.cport =
8150 		    ahci_ctlp->ahcictl_port_to_cport[port];
8151 		sdevice.satadev_addr.pmport = 0;
8152 		sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
8153 
8154 		sdevice.satadev_state = SATA_DSTATE_RESET |
8155 		    SATA_DSTATE_PWR_ACTIVE;
8156 
8157 		mutex_exit(&ahci_portp->ahciport_mutex);
8158 		sata_hba_event_notify(
8159 		    ahci_ctlp->ahcictl_dip,
8160 		    &sdevice,
8161 		    SATA_EVNT_DEVICE_RESET);
8162 		mutex_enter(&ahci_portp->ahciport_mutex);
8163 
8164 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8165 		    "Port multiplier is [Gone] at port %d ", port);
8166 		AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
8167 		    "port %d sending event up: SATA_EVNT_DEVICE_RESET", port);
8168 
8169 		return (AHCI_SUCCESS);
8170 	}
8171 
8172 	/* Device change: Non-PMult -> PMult */
8173 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_PMULT) {
8174 
8175 		/* NOTE: The PxCMD.PMA may be cleared by HBA reset. */
8176 		ahci_alloc_pmult(ahci_ctlp, ahci_portp);
8177 
8178 		(void) ahci_start_port(ahci_ctlp, ahci_portp, port);
8179 	}
8180 	pminfo = ahci_portp->ahciport_pmult_info;
8181 	ASSERT(pminfo != NULL);
8182 
8183 	/* Device (may) change: PMult -> PMult */
8184 	/*
8185 	 * First initialize port multiplier. Set state to READY and wait for
8186 	 * probe entry point to initialize it
8187 	 */
8188 	ahci_portp->ahciport_port_state = SATA_STATE_READY;
8189 
8190 	/*
8191 	 * It's a little complicated while target is a port multiplier. we
8192 	 * need to COMRESET all pmports behind that PMult otherwise those
8193 	 * sub-links between the PMult and the sub-devices will be in an
8194 	 * inactive state (indicated by PSCR0/PxSSTS) and the following access
8195 	 * to those sub-devices will be rejected by Link-Fatal-Error.
8196 	 */
8197 	/*
8198 	 * The PxSNTF will be set soon after the pmult is plugged. While the
8199 	 * pmult itself is attaching, sata_hba_event_notfiy will fail. so we
8200 	 * simply mark every sub-port as 'unknown', then ahci_probe_pmport
8201 	 * will initialized it.
8202 	 */
8203 	for (npmport = 0; npmport < pminfo->ahcipmi_num_dev_ports; npmport++)
8204 		pminfo->ahcipmi_port_state[npmport] = SATA_STATE_UNKNOWN;
8205 
8206 	/* Report reset event. */
8207 	ahci_portp->ahciport_reset_in_progress = 1;
8208 
8209 	bzero((void *)&sdevice, sizeof (sata_device_t));
8210 	sdevice.satadev_addr.cport = cport;
8211 	sdevice.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
8212 	sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
8213 	sdevice.satadev_state = SATA_DSTATE_RESET | SATA_DSTATE_PWR_ACTIVE;
8214 	sata_hba_event_notify(ahci_ctlp->ahcictl_dip, &sdevice,
8215 	    SATA_EVNT_DEVICE_RESET);
8216 
8217 	return (rval);
8218 }
8219 
8220 /*
8221  * This routine may be called under four scenarios:
8222  *	a) do the recovery from fatal error
8223  *	b) or we need to timeout some commands
8224  *	c) or we need to abort some commands
8225  *	d) or we need reset device/port/controller
8226  *
8227  * In all these scenarios, we need to send any pending unfinished
8228  * commands up to sata framework.
8229  *
8230  * WARNING!!! ahciport_mutex should be acquired before the function is called.
8231  */
8232 static void
8233 ahci_mop_commands(ahci_ctl_t *ahci_ctlp,
8234     ahci_port_t *ahci_portp,
8235     uint32_t slot_status,
8236     uint32_t failed_tags,
8237     uint32_t timeout_tags,
8238     uint32_t aborted_tags,
8239     uint32_t reset_tags)
8240 {
8241 	uint32_t finished_tags = 0;
8242 	uint32_t unfinished_tags = 0;
8243 	int tmp_slot;
8244 	sata_pkt_t *satapkt;
8245 	int ncq_cmd_in_progress = 0;
8246 	int err_retri_cmd_in_progress = 0;
8247 	int rdwr_pmult_cmd_in_progress = 0;
8248 
8249 	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
8250 	    "ahci_mop_commands entered: port: %d slot_status: 0x%x",
8251 	    ahci_portp->ahciport_port_num, slot_status);
8252 
8253 	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
8254 	    "ahci_mop_commands: failed_tags: 0x%x, "
8255 	    "timeout_tags: 0x%x aborted_tags: 0x%x, "
8256 	    "reset_tags: 0x%x", failed_tags,
8257 	    timeout_tags, aborted_tags, reset_tags);
8258 
8259 #ifdef AHCI_DEBUG
8260 	if (ahci_debug_flags & AHCIDBG_ERRS) {
8261 		int i;
8262 		char msg_buf[200] = {0, };
8263 		for (i = 0x1f; i >= 0; i--) {
8264 			if (ahci_portp->ahciport_slot_pkts[i] != NULL)
8265 				msg_buf[i] = 'X';
8266 			else
8267 				msg_buf[i] = '.';
8268 		}
8269 		msg_buf[0x20] = '\0';
8270 		cmn_err(CE_NOTE, "port[%d] slots: %s",
8271 		    ahci_portp->ahciport_port_num, msg_buf);
8272 		cmn_err(CE_NOTE, "[ERR-RT] %p [RW-PM] %p ",
8273 		    (void *)ahci_portp->ahciport_err_retri_pkt,
8274 		    (void *)ahci_portp->ahciport_rdwr_pmult_pkt);
8275 	}
8276 #endif
8277 
8278 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
8279 		finished_tags = ahci_portp->ahciport_pending_tags &
8280 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
8281 
8282 		unfinished_tags = slot_status &
8283 		    AHCI_SLOT_MASK(ahci_ctlp) &
8284 		    ~failed_tags &
8285 		    ~aborted_tags &
8286 		    ~reset_tags &
8287 		    ~timeout_tags;
8288 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
8289 		ncq_cmd_in_progress = 1;
8290 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
8291 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
8292 
8293 		unfinished_tags = slot_status &
8294 		    AHCI_NCQ_SLOT_MASK(ahci_portp) &
8295 		    ~failed_tags &
8296 		    ~aborted_tags &
8297 		    ~reset_tags &
8298 		    ~timeout_tags;
8299 	} else if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
8300 
8301 		/*
8302 		 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT is
8303 		 * set, it means REQUEST SENSE or READ LOG EXT command doesn't
8304 		 * complete successfully due to one of the following three
8305 		 * conditions:
8306 		 *
8307 		 *	1. Fatal error - failed_tags includes its slot
8308 		 *	2. Timed out - timeout_tags includes its slot
8309 		 *	3. Aborted when hot unplug - aborted_tags includes its
8310 		 *	   slot
8311 		 *
8312 		 * Please note that the command is always sent down in Slot 0
8313 		 */
8314 		err_retri_cmd_in_progress = 1;
8315 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_NCQ, ahci_ctlp,
8316 		    "ahci_mop_commands is called for port %d while "
8317 		    "REQUEST SENSE or READ LOG EXT for error retrieval "
8318 		    "is being executed slot_status = 0x%x",
8319 		    ahci_portp->ahciport_port_num, slot_status);
8320 		ASSERT(ahci_portp->ahciport_mop_in_progress > 1);
8321 		ASSERT(slot_status == 0x1);
8322 	} else if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
8323 		rdwr_pmult_cmd_in_progress = 1;
8324 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PMULT, ahci_ctlp,
8325 		    "ahci_mop_commands is called for port %d while "
8326 		    "READ/WRITE PORTMULT command is being executed",
8327 		    ahci_portp->ahciport_port_num);
8328 
8329 		ASSERT(slot_status == 0x1);
8330 	}
8331 
8332 #ifdef AHCI_DEBUG
8333 	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
8334 	    "ahci_mop_commands: finished_tags: 0x%x, "
8335 	    "unfinished_tags 0x%x", finished_tags, unfinished_tags);
8336 #endif
8337 
8338 	/* Send up finished packets with SATA_PKT_COMPLETED */
8339 	while (finished_tags) {
8340 		tmp_slot = ddi_ffs(finished_tags) - 1;
8341 		if (tmp_slot == -1) {
8342 			break;
8343 		}
8344 
8345 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
8346 		ASSERT(satapkt != NULL);
8347 
8348 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_mop_commands: "
8349 		    "sending up pkt 0x%p with SATA_PKT_COMPLETED",
8350 		    (void *)satapkt);
8351 
8352 		/*
8353 		 * Cannot fetch the return register content since the port
8354 		 * was restarted, so the corresponding tag will be set to
8355 		 * aborted tags.
8356 		 */
8357 		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
8358 			CLEAR_BIT(finished_tags, tmp_slot);
8359 			aborted_tags |= tmp_slot;
8360 			continue;
8361 		}
8362 
8363 		if (ncq_cmd_in_progress)
8364 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
8365 			    tmp_slot);
8366 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
8367 		CLEAR_BIT(finished_tags, tmp_slot);
8368 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
8369 
8370 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
8371 	}
8372 
8373 	/* Send up failed packets with SATA_PKT_DEV_ERROR. */
8374 	while (failed_tags) {
8375 		if (err_retri_cmd_in_progress) {
8376 			satapkt = ahci_portp->ahciport_err_retri_pkt;
8377 			ASSERT(satapkt != NULL);
8378 			ASSERT(failed_tags == 0x1);
8379 
8380 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8381 			    "sending up pkt 0x%p with SATA_PKT_DEV_ERROR",
8382 			    (void *)satapkt);
8383 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
8384 			break;
8385 		}
8386 		if (rdwr_pmult_cmd_in_progress) {
8387 			satapkt = ahci_portp->ahciport_rdwr_pmult_pkt;
8388 			ASSERT(satapkt != NULL);
8389 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8390 			    "ahci_mop_commands: sending up "
8391 			    "rdwr pmult pkt 0x%p with SATA_PKT_DEV_ERROR",
8392 			    (void *)satapkt);
8393 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
8394 			break;
8395 		}
8396 
8397 		tmp_slot = ddi_ffs(failed_tags) - 1;
8398 		if (tmp_slot == -1) {
8399 			break;
8400 		}
8401 
8402 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
8403 		ASSERT(satapkt != NULL);
8404 
8405 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8406 		    "sending up pkt 0x%p with SATA_PKT_DEV_ERROR",
8407 		    (void *)satapkt);
8408 
8409 		if (ncq_cmd_in_progress)
8410 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
8411 			    tmp_slot);
8412 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
8413 		CLEAR_BIT(failed_tags, tmp_slot);
8414 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
8415 
8416 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
8417 	}
8418 
8419 	/* Send up timeout packets with SATA_PKT_TIMEOUT. */
8420 	while (timeout_tags) {
8421 		if (err_retri_cmd_in_progress) {
8422 			satapkt = ahci_portp->ahciport_err_retri_pkt;
8423 			ASSERT(satapkt != NULL);
8424 			ASSERT(timeout_tags == 0x1);
8425 
8426 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8427 			    "sending up pkt 0x%p with SATA_PKT_TIMEOUT",
8428 			    (void *)satapkt);
8429 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
8430 			break;
8431 		}
8432 		if (rdwr_pmult_cmd_in_progress) {
8433 			satapkt = ahci_portp->ahciport_rdwr_pmult_pkt;
8434 			ASSERT(satapkt != NULL);
8435 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8436 			    "ahci_mop_commands: sending up "
8437 			    "rdwr pmult pkt 0x%p with SATA_PKT_TIMEOUT",
8438 			    (void *)satapkt);
8439 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
8440 			break;
8441 		}
8442 
8443 		tmp_slot = ddi_ffs(timeout_tags) - 1;
8444 		if (tmp_slot == -1) {
8445 			break;
8446 		}
8447 
8448 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
8449 		ASSERT(satapkt != NULL);
8450 
8451 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8452 		    "sending up pkt 0x%p with SATA_PKT_TIMEOUT",
8453 		    (void *)satapkt);
8454 
8455 		if (ncq_cmd_in_progress)
8456 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
8457 			    tmp_slot);
8458 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
8459 		CLEAR_BIT(timeout_tags, tmp_slot);
8460 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
8461 
8462 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
8463 	}
8464 
8465 	/* Send up aborted packets with SATA_PKT_ABORTED */
8466 	while (aborted_tags) {
8467 		if (err_retri_cmd_in_progress) {
8468 			satapkt = ahci_portp->ahciport_err_retri_pkt;
8469 			ASSERT(satapkt != NULL);
8470 			ASSERT(aborted_tags == 0x1);
8471 
8472 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8473 			    "sending up pkt 0x%p with SATA_PKT_ABORTED",
8474 			    (void *)satapkt);
8475 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
8476 			break;
8477 		}
8478 		if (rdwr_pmult_cmd_in_progress) {
8479 			satapkt = ahci_portp->ahciport_rdwr_pmult_pkt;
8480 			ASSERT(satapkt != NULL);
8481 			ASSERT(aborted_tags == 0x1);
8482 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8483 			    "ahci_mop_commands: sending up "
8484 			    "rdwr pmult pkt 0x%p with SATA_PKT_ABORTED",
8485 			    (void *)satapkt);
8486 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
8487 			break;
8488 		}
8489 
8490 		tmp_slot = ddi_ffs(aborted_tags) - 1;
8491 		if (tmp_slot == -1) {
8492 			break;
8493 		}
8494 
8495 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
8496 		ASSERT(satapkt != NULL);
8497 
8498 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8499 		    "sending up pkt 0x%p with SATA_PKT_ABORTED",
8500 		    (void *)satapkt);
8501 
8502 		if (ncq_cmd_in_progress)
8503 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
8504 			    tmp_slot);
8505 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
8506 		CLEAR_BIT(aborted_tags, tmp_slot);
8507 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
8508 
8509 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
8510 	}
8511 
8512 	/* Send up reset packets with SATA_PKT_RESET. */
8513 	while (reset_tags) {
8514 		if (rdwr_pmult_cmd_in_progress) {
8515 			satapkt = ahci_portp->ahciport_rdwr_pmult_pkt;
8516 			ASSERT(satapkt != NULL);
8517 			ASSERT(aborted_tags == 0x1);
8518 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8519 			    "ahci_mop_commands: sending up "
8520 			    "rdwr pmult pkt 0x%p with SATA_PKT_RESET",
8521 			    (void *)satapkt);
8522 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
8523 			break;
8524 		}
8525 
8526 		tmp_slot = ddi_ffs(reset_tags) - 1;
8527 		if (tmp_slot == -1) {
8528 			break;
8529 		}
8530 
8531 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
8532 		ASSERT(satapkt != NULL);
8533 
8534 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8535 		    "sending up pkt 0x%p with SATA_PKT_RESET",
8536 		    (void *)satapkt);
8537 
8538 		if (ncq_cmd_in_progress)
8539 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
8540 			    tmp_slot);
8541 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
8542 		CLEAR_BIT(reset_tags, tmp_slot);
8543 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
8544 
8545 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
8546 	}
8547 
8548 	/* Send up unfinished packets with SATA_PKT_RESET */
8549 	while (unfinished_tags) {
8550 		tmp_slot = ddi_ffs(unfinished_tags) - 1;
8551 		if (tmp_slot == -1) {
8552 			break;
8553 		}
8554 
8555 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
8556 		ASSERT(satapkt != NULL);
8557 
8558 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
8559 		    "sending up pkt 0x%p with SATA_PKT_RESET",
8560 		    (void *)satapkt);
8561 
8562 		if (ncq_cmd_in_progress)
8563 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
8564 			    tmp_slot);
8565 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
8566 		CLEAR_BIT(unfinished_tags, tmp_slot);
8567 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
8568 
8569 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
8570 	}
8571 
8572 	ahci_portp->ahciport_mop_in_progress--;
8573 	ASSERT(ahci_portp->ahciport_mop_in_progress >= 0);
8574 
8575 	if (ahci_portp->ahciport_mop_in_progress == 0)
8576 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_MOPPING;
8577 }
8578 
8579 /*
8580  * This routine is going to first request a READ LOG EXT sata pkt from sata
8581  * module, and then deliver it to the HBA to get the ncq failure context.
8582  * The return value is the exactly failed tags.
8583  */
8584 static uint32_t
8585 ahci_get_rdlogext_data(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
8586     uint8_t port)
8587 {
8588 	sata_device_t	sdevice;
8589 	sata_pkt_t	*rdlog_spkt, *spkt;
8590 	ddi_dma_handle_t buf_dma_handle;
8591 	ahci_addr_t	addr;
8592 	int		loop_count;
8593 	int		rval;
8594 	int		failed_slot;
8595 	uint32_t	failed_tags = 0;
8596 	struct sata_ncq_error_recovery_page *ncq_err_page;
8597 
8598 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_NCQ, ahci_ctlp,
8599 	    "ahci_get_rdlogext_data enter: port %d", port);
8600 
8601 	/* Prepare the sdevice data */
8602 	bzero((void *)&sdevice, sizeof (sata_device_t));
8603 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
8604 
8605 	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
8606 	sdevice.satadev_addr.pmport = 0;
8607 
8608 	/* Translate sata_device.satadev_addr -> ahci_addr */
8609 	ahci_get_ahci_addr(ahci_ctlp, &sdevice, &addr);
8610 
8611 	/*
8612 	 * Call the sata hba interface to get a rdlog spkt
8613 	 */
8614 	loop_count = 0;
8615 loop:
8616 	rdlog_spkt = sata_get_error_retrieval_pkt(ahci_ctlp->ahcictl_dip,
8617 	    &sdevice, SATA_ERR_RETR_PKT_TYPE_NCQ);
8618 	if (rdlog_spkt == NULL) {
8619 		if (loop_count++ < AHCI_POLLRATE_GET_SPKT) {
8620 			/* Sleep for a while */
8621 			drv_usecwait(AHCI_10MS_USECS);
8622 			goto loop;
8623 		}
8624 		/* Timed out after 1s */
8625 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8626 		    "failed to get rdlog spkt for port %d", port);
8627 		return (failed_tags);
8628 	}
8629 
8630 	ASSERT(rdlog_spkt->satapkt_op_mode & SATA_OPMODE_SYNCH);
8631 
8632 	/*
8633 	 * This flag is used to handle the specific error recovery when the
8634 	 * READ LOG EXT command gets a failure (fatal error or time-out).
8635 	 */
8636 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RDLOGEXT;
8637 
8638 	/*
8639 	 * This start is not supposed to fail because after port is restarted,
8640 	 * the whole command list is empty.
8641 	 */
8642 	ahci_portp->ahciport_err_retri_pkt = rdlog_spkt;
8643 	(void) ahci_do_sync_start(ahci_ctlp, ahci_portp, &addr, rdlog_spkt);
8644 	ahci_portp->ahciport_err_retri_pkt = NULL;
8645 
8646 	/* Remove the flag after READ LOG EXT command is completed */
8647 	ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_RDLOGEXT;
8648 
8649 	if (rdlog_spkt->satapkt_reason == SATA_PKT_COMPLETED) {
8650 		/* Update the request log data */
8651 		buf_dma_handle = *(ddi_dma_handle_t *)
8652 		    (rdlog_spkt->satapkt_cmd.satacmd_err_ret_buf_handle);
8653 		rval = ddi_dma_sync(buf_dma_handle, 0, 0,
8654 		    DDI_DMA_SYNC_FORKERNEL);
8655 		if (rval == DDI_SUCCESS) {
8656 			ncq_err_page =
8657 			    (struct sata_ncq_error_recovery_page *)rdlog_spkt->
8658 			    satapkt_cmd.satacmd_bp->b_un.b_addr;
8659 
8660 			/* Get the failed tag */
8661 			failed_slot = ncq_err_page->ncq_tag;
8662 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8663 			    "ahci_get_rdlogext_data: port %d "
8664 			    "failed slot %d", port, failed_slot);
8665 			if (failed_slot & NQ) {
8666 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8667 				    "the failed slot is not a valid tag", NULL);
8668 				goto out;
8669 			}
8670 
8671 			failed_slot &= NCQ_TAG_MASK;
8672 			spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
8673 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8674 			    "ahci_get_rdlogext_data: failed spkt 0x%p",
8675 			    (void *)spkt);
8676 			if (spkt == NULL) {
8677 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8678 				    "the failed slot spkt is NULL", NULL);
8679 				goto out;
8680 			}
8681 
8682 			failed_tags = 0x1 << failed_slot;
8683 
8684 			/* Fill out the error context */
8685 			ahci_copy_ncq_err_page(&spkt->satapkt_cmd,
8686 			    ncq_err_page);
8687 			ahci_update_sata_registers(ahci_ctlp, port,
8688 			    &spkt->satapkt_device);
8689 		}
8690 	}
8691 out:
8692 	sata_free_error_retrieval_pkt(rdlog_spkt);
8693 
8694 	return (failed_tags);
8695 }
8696 
8697 /*
8698  * This routine is going to first request a REQUEST SENSE sata pkt from sata
8699  * module, and then deliver it to the HBA to get the sense data and copy
8700  * the sense data back to the orignal failed sata pkt, and free the REQUEST
8701  * SENSE sata pkt later.
8702  */
8703 static void
8704 ahci_get_rqsense_data(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
8705     uint8_t port, sata_pkt_t *spkt)
8706 {
8707 	sata_device_t	sdevice;
8708 	sata_pkt_t	*rs_spkt;
8709 	sata_cmd_t	*sata_cmd;
8710 	ddi_dma_handle_t buf_dma_handle;
8711 	ahci_addr_t	addr;
8712 	int		loop_count;
8713 #if AHCI_DEBUG
8714 	struct scsi_extended_sense *rqsense;
8715 #endif
8716 
8717 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
8718 	    "ahci_get_rqsense_data enter: port %d", port);
8719 
8720 	/* Prepare the sdevice data */
8721 	bzero((void *)&sdevice, sizeof (sata_device_t));
8722 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
8723 
8724 	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
8725 	sdevice.satadev_addr.pmport = 0;
8726 
8727 	/* Translate sata_device.satadev_addr -> ahci_addr */
8728 	ahci_get_ahci_addr(ahci_ctlp, &sdevice, &addr);
8729 
8730 	sata_cmd = &spkt->satapkt_cmd;
8731 
8732 	/*
8733 	 * Call the sata hba interface to get a rs spkt
8734 	 */
8735 	loop_count = 0;
8736 loop:
8737 	rs_spkt = sata_get_error_retrieval_pkt(ahci_ctlp->ahcictl_dip,
8738 	    &sdevice, SATA_ERR_RETR_PKT_TYPE_ATAPI);
8739 	if (rs_spkt == NULL) {
8740 		if (loop_count++ < AHCI_POLLRATE_GET_SPKT) {
8741 			/* Sleep for a while */
8742 			drv_usecwait(AHCI_10MS_USECS);
8743 			goto loop;
8744 
8745 		}
8746 		/* Timed out after 1s */
8747 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8748 		    "failed to get rs spkt for port %d", port);
8749 		return;
8750 	}
8751 
8752 	ASSERT(rs_spkt->satapkt_op_mode & SATA_OPMODE_SYNCH);
8753 
8754 	/*
8755 	 * This flag is used to handle the specific error recovery when the
8756 	 * REQUEST SENSE command gets a faiure (fatal error or time-out).
8757 	 */
8758 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RQSENSE;
8759 
8760 	/*
8761 	 * This start is not supposed to fail because after port is restarted,
8762 	 * the whole command list is empty.
8763 	 */
8764 	ahci_portp->ahciport_err_retri_pkt = rs_spkt;
8765 	(void) ahci_do_sync_start(ahci_ctlp, ahci_portp, &addr, rs_spkt);
8766 	ahci_portp->ahciport_err_retri_pkt = NULL;
8767 
8768 	/* Remove the flag after REQUEST SENSE command is completed */
8769 	ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_RQSENSE;
8770 
8771 	if (rs_spkt->satapkt_reason == SATA_PKT_COMPLETED) {
8772 		/* Update the request sense data */
8773 		buf_dma_handle = *(ddi_dma_handle_t *)
8774 		    (rs_spkt->satapkt_cmd.satacmd_err_ret_buf_handle);
8775 		(void) ddi_dma_sync(buf_dma_handle, 0, 0,
8776 		    DDI_DMA_SYNC_FORKERNEL);
8777 		/* Copy the request sense data */
8778 		bcopy(rs_spkt->
8779 		    satapkt_cmd.satacmd_bp->b_un.b_addr,
8780 		    &sata_cmd->satacmd_rqsense,
8781 		    SATA_ATAPI_MIN_RQSENSE_LEN);
8782 #if AHCI_DEBUG
8783 		rqsense = (struct scsi_extended_sense *)
8784 		    sata_cmd->satacmd_rqsense;
8785 
8786 		/* Dump the sense data */
8787 		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp, "\n", NULL);
8788 		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp,
8789 		    "Sense data for satapkt %p ATAPI cmd 0x%x",
8790 		    spkt, sata_cmd->satacmd_acdb[0]);
8791 		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp,
8792 		    "  es_code 0x%x es_class 0x%x "
8793 		    "es_key 0x%x es_add_code 0x%x "
8794 		    "es_qual_code 0x%x",
8795 		    rqsense->es_code, rqsense->es_class,
8796 		    rqsense->es_key, rqsense->es_add_code,
8797 		    rqsense->es_qual_code);
8798 #endif
8799 	}
8800 
8801 	sata_free_error_retrieval_pkt(rs_spkt);
8802 }
8803 
8804 /*
8805  * Fatal errors will cause the HBA to enter the ERR: Fatal state. To recover,
8806  * the port must be restarted. When the HBA detects thus error, it may try
8807  * to abort a transfer. And if the transfer was aborted, the device is
8808  * expected to send a D2H Register FIS with PxTFD.STS.ERR set to '1' and both
8809  * PxTFD.STS.BSY and PxTFD.STS.DRQ cleared to '0'. Then system software knows
8810  * that the device is in a stable status and transfers may be restarted without
8811  * issuing a COMRESET to the device. If PxTFD.STS.BSY or PxTFD.STS.DRQ is set,
8812  * then the software will send the COMRESET to do the port reset.
8813  *
8814  * Software should perform the appropriate error recovery actions based on
8815  * whether non-queued commands were being issued or natived command queuing
8816  * commands were being issued.
8817  *
8818  * And software will complete the command that had the error with error mark
8819  * to higher level software.
8820  *
8821  * Fatal errors include the following:
8822  *	PxIS.IFS - Interface Fatal Error Status
8823  *	PxIS.HBDS - Host Bus Data Error Status
8824  *	PxIS.HBFS - Host Bus Fatal Error Status
8825  *	PxIS.TFES - Task File Error Status
8826  *
8827  * WARNING!!! ahciport_mutex should be acquired before the function is called.
8828  */
8829 static void
8830 ahci_fatal_error_recovery_handler(ahci_ctl_t *ahci_ctlp,
8831     ahci_port_t *ahci_portp, ahci_addr_t *addrp, uint32_t intr_status)
8832 {
8833 	uint32_t	port_cmd_status;
8834 	uint32_t	slot_status = 0;
8835 	uint32_t	failed_tags = 0;
8836 	int		failed_slot;
8837 	int		reset_flag = 0, flag = 0;
8838 	ahci_fis_d2h_register_t	*ahci_rcvd_fisp;
8839 	sata_cmd_t	*sata_cmd = NULL;
8840 	sata_pkt_t	*spkt = NULL;
8841 #if AHCI_DEBUG
8842 	ahci_cmd_header_t *cmd_header;
8843 #endif
8844 	uint8_t 	port = addrp->aa_port;
8845 
8846 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
8847 	    "ahci_fatal_error_recovery_handler enter: port %d", port);
8848 
8849 	/* Port multiplier error */
8850 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_PMULT) {
8851 		/* FBS code is neither completed nor tested. */
8852 		ahci_pmult_error_recovery_handler(ahci_ctlp, ahci_portp,
8853 		    port, intr_status);
8854 
8855 		/* Force a port reset */
8856 		flag = AHCI_PORT_RESET;
8857 	}
8858 
8859 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
8860 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
8861 
8862 		/* Read PxCI to see which commands are still outstanding */
8863 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
8864 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
8865 
8866 		/*
8867 		 * Read PxCMD.CCS to determine the slot that the HBA
8868 		 * was processing when the error occurred.
8869 		 */
8870 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
8871 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
8872 		failed_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
8873 		    AHCI_CMD_STATUS_CCS_SHIFT;
8874 
8875 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
8876 			spkt = ahci_portp->ahciport_err_retri_pkt;
8877 			ASSERT(spkt != NULL);
8878 		} else {
8879 			spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
8880 			if (spkt == NULL) {
8881 				/* May happen when interface errors occur? */
8882 				goto next;
8883 			}
8884 		}
8885 
8886 #if AHCI_DEBUG
8887 		/*
8888 		 * Debugging purpose...
8889 		 */
8890 		if (ahci_portp->ahciport_prd_bytecounts[failed_slot]) {
8891 			cmd_header =
8892 			    &ahci_portp->ahciport_cmd_list[failed_slot];
8893 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
8894 			    "ahci_fatal_error_recovery_handler: port %d, "
8895 			    "PRD Byte Count = 0x%x, "
8896 			    "ahciport_prd_bytecounts = 0x%x", port,
8897 			    cmd_header->ahcich_prd_byte_count,
8898 			    ahci_portp->ahciport_prd_bytecounts[failed_slot]);
8899 		}
8900 #endif
8901 
8902 		sata_cmd = &spkt->satapkt_cmd;
8903 
8904 		/* Fill out the status and error registers for PxIS.TFES */
8905 		if (intr_status & AHCI_INTR_STATUS_TFES) {
8906 			ahci_rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
8907 			    ahcirf_d2h_register_fis);
8908 
8909 			/* Copy the error context back to the sata_cmd */
8910 			ahci_copy_err_cnxt(sata_cmd, ahci_rcvd_fisp);
8911 		}
8912 
8913 		/* The failed command must be one of the outstanding commands */
8914 		failed_tags = 0x1 << failed_slot;
8915 		ASSERT(failed_tags & slot_status);
8916 
8917 		/* Update the sata registers, especially PxSERR register */
8918 		ahci_update_sata_registers(ahci_ctlp, port,
8919 		    &spkt->satapkt_device);
8920 
8921 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
8922 		/* Read PxSACT to see which commands are still outstanding */
8923 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
8924 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
8925 	}
8926 next:
8927 
8928 #if AHCI_DEBUG
8929 	/*
8930 	 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT flag is
8931 	 * set, it means a fatal error happened after REQUEST SENSE command
8932 	 * or READ LOG EXT command is delivered to the HBA during the error
8933 	 * recovery process. At this time, the only outstanding command is
8934 	 * supposed to be REQUEST SENSE command or READ LOG EXT command.
8935 	 */
8936 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
8937 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8938 		    "ahci_fatal_error_recovery_handler: port %d REQUEST SENSE "
8939 		    "command or READ LOG EXT command for error data retrieval "
8940 		    "failed", port);
8941 		ASSERT(slot_status == 0x1);
8942 		ASSERT(failed_slot == 0);
8943 		ASSERT(spkt->satapkt_cmd.satacmd_acdb[0] ==
8944 		    SCMD_REQUEST_SENSE ||
8945 		    spkt->satapkt_cmd.satacmd_cmd_reg ==
8946 		    SATAC_READ_LOG_EXT);
8947 	}
8948 #endif
8949 
8950 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
8951 	ahci_portp->ahciport_mop_in_progress++;
8952 
8953 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
8954 	    port, flag, &reset_flag);
8955 
8956 	/*
8957 	 * Won't retrieve error information:
8958 	 * 1. Port reset was involved to recover
8959 	 * 2. Device is gone
8960 	 * 3. IDENTIFY DEVICE command sent to ATAPI device
8961 	 * 4. REQUEST SENSE or READ LOG EXT command during error recovery
8962 	 */
8963 	if (reset_flag ||
8964 	    ahci_portp->ahciport_device_type == SATA_DTYPE_NONE ||
8965 	    spkt && spkt->satapkt_cmd.satacmd_cmd_reg == SATAC_ID_DEVICE ||
8966 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
8967 		goto out;
8968 
8969 	/*
8970 	 * Deliver READ LOG EXT to gather information about the error when
8971 	 * a COMRESET has not been performed as part of the error recovery
8972 	 * during NCQ command processing.
8973 	 */
8974 	if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
8975 		failed_tags = ahci_get_rdlogext_data(ahci_ctlp,
8976 		    ahci_portp, port);
8977 		goto out;
8978 	}
8979 
8980 	/*
8981 	 * Deliver REQUEST SENSE for ATAPI command to gather information about
8982 	 * the error when a COMRESET has not been performed as part of the
8983 	 * error recovery.
8984 	 */
8985 	if (spkt && ahci_portp->ahciport_device_type == SATA_DTYPE_ATAPI)
8986 		ahci_get_rqsense_data(ahci_ctlp, ahci_portp, port, spkt);
8987 out:
8988 	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
8989 	    "ahci_fatal_error_recovery_handler: port %d fatal error "
8990 	    "occurred slot_status = 0x%x, pending_tags = 0x%x, "
8991 	    "pending_ncq_tags = 0x%x failed_tags = 0x%x",
8992 	    port, slot_status, ahci_portp->ahciport_pending_tags,
8993 	    ahci_portp->ahciport_pending_ncq_tags, failed_tags);
8994 
8995 	ahci_mop_commands(ahci_ctlp,
8996 	    ahci_portp,
8997 	    slot_status,
8998 	    failed_tags, /* failed tags */
8999 	    0, /* timeout tags */
9000 	    0, /* aborted tags */
9001 	    0); /* reset tags */
9002 }
9003 
9004 /*
9005  * Used to recovery a PMULT pmport fatal error under FIS-based switching.
9006  * 	1. device specific.PxFBS.SDE=1
9007  * 	2. Non-Deivce specific.
9008  * Nothing will be done when Command-based switching is employed.
9009  *
9010  * Currently code is neither completed nor tested.
9011  *
9012  * WARNING!!! ahciport_mutex should be acquired before the function
9013  * is called.
9014  */
9015 static void
9016 ahci_pmult_error_recovery_handler(ahci_ctl_t *ahci_ctlp,
9017     ahci_port_t *ahci_portp, uint8_t port, uint32_t intr_status)
9018 {
9019 #ifndef __lock_lint
9020 	_NOTE(ARGUNUSED(intr_status))
9021 #endif
9022 	uint32_t	port_fbs_ctrl;
9023 	int loop_count = 0;
9024 	ahci_addr_t	addr;
9025 
9026 	/* Nothing will be done under Command-based switching. */
9027 	if (!(ahci_ctlp->ahcictl_cap & AHCI_CAP_PMULT_FBSS))
9028 		return;
9029 
9030 	port_fbs_ctrl = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
9031 	    (uint32_t *)AHCI_PORT_PxFBS(ahci_ctlp, port));
9032 
9033 	if (!(port_fbs_ctrl & AHCI_FBS_EN))
9034 		/* FBS is not enabled. */
9035 		return;
9036 
9037 	/* Problem's getting complicated now. */
9038 	/*
9039 	 * If FIS-based switching is used, we need to check
9040 	 * the PxFBS to see the error type.
9041 	 */
9042 	port_fbs_ctrl = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
9043 	    (uint32_t *)AHCI_PORT_PxFBS(ahci_ctlp, port));
9044 
9045 	/* Refer to spec(v1.2) 9.3.6.1 */
9046 	if (port_fbs_ctrl & AHCI_FBS_SDE) {
9047 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
9048 		    "A Device Sepcific Error: port %d", port);
9049 		/*
9050 		 * Controller has paused commands for all other
9051 		 * sub-devices until PxFBS.DEC is set.
9052 		 */
9053 		ahci_reject_all_abort_pkts(ahci_ctlp,
9054 		    ahci_portp, 0);
9055 
9056 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
9057 		    (uint32_t *)AHCI_PORT_PxFBS(ahci_ctlp, port),
9058 		    port_fbs_ctrl | AHCI_FBS_DEC);
9059 
9060 		/*
9061 		 * Wait controller clear PxFBS.DEC,
9062 		 * then we can continue.
9063 		 */
9064 		loop_count = 0;
9065 		do {
9066 			port_fbs_ctrl = ddi_get32(ahci_ctlp->
9067 			    ahcictl_ahci_acc_handle, (uint32_t *)
9068 			    AHCI_PORT_PxFBS(ahci_ctlp, port));
9069 
9070 			if (loop_count++ > 1000)
9071 				/*
9072 				 * Esclate the error. Follow
9073 				 * non-device specific error
9074 				 * procedure.
9075 				 */
9076 				return;
9077 
9078 			drv_usecwait(AHCI_100US_USECS);
9079 		} while (port_fbs_ctrl & AHCI_FBS_DEC);
9080 
9081 		/*
9082 		 * Issue a software reset to ensure drive is in
9083 		 * a known state.
9084 		 */
9085 		(void) ahci_software_reset(ahci_ctlp,
9086 		    ahci_portp, &addr);
9087 
9088 	} else {
9089 
9090 		/* Process Non-Device Specific Error. */
9091 		/* This will be handled later on. */
9092 		cmn_err(CE_NOTE, "!FBS is not supported now.");
9093 	}
9094 }
9095 /*
9096  * Handle events - fatal error recovery
9097  */
9098 static void
9099 ahci_events_handler(void *args)
9100 {
9101 	ahci_event_arg_t *ahci_event_arg;
9102 	ahci_ctl_t *ahci_ctlp;
9103 	ahci_port_t *ahci_portp;
9104 	ahci_addr_t *addrp;
9105 	uint32_t event;
9106 
9107 	ahci_event_arg = (ahci_event_arg_t *)args;
9108 
9109 	ahci_ctlp = ahci_event_arg->ahciea_ctlp;
9110 	ahci_portp = ahci_event_arg->ahciea_portp;
9111 	addrp = ahci_event_arg->ahciea_addrp;
9112 	event = ahci_event_arg->ahciea_event;
9113 
9114 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
9115 	    "ahci_events_handler enter: port %d intr_status = 0x%x",
9116 	    ahci_portp->ahciport_port_num, event);
9117 
9118 	mutex_enter(&ahci_portp->ahciport_mutex);
9119 
9120 	/*
9121 	 * ahci_intr_phyrdy_change() may have rendered it to
9122 	 * SATA_DTYPE_NONE.
9123 	 */
9124 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
9125 		AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
9126 		    "ahci_events_handler: port %d no device attached, "
9127 		    "and just return without doing anything",
9128 		    ahci_portp->ahciport_port_num);
9129 		goto out;
9130 	}
9131 
9132 	if (event & (AHCI_INTR_STATUS_IFS |
9133 	    AHCI_INTR_STATUS_HBDS |
9134 	    AHCI_INTR_STATUS_HBFS |
9135 	    AHCI_INTR_STATUS_TFES))
9136 		ahci_fatal_error_recovery_handler(ahci_ctlp, ahci_portp,
9137 		    addrp, event);
9138 
9139 out:
9140 	mutex_exit(&ahci_portp->ahciport_mutex);
9141 }
9142 
9143 /*
9144  * ahci_watchdog_handler() and ahci_do_sync_start will call us if they
9145  * detect there are some commands which are timed out.
9146  */
9147 static void
9148 ahci_timeout_pkts(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
9149     uint8_t port, uint32_t tmp_timeout_tags)
9150 {
9151 	uint32_t slot_status = 0;
9152 	uint32_t finished_tags = 0;
9153 	uint32_t timeout_tags = 0;
9154 
9155 	AHCIDBG(AHCIDBG_TIMEOUT|AHCIDBG_ENTRY, ahci_ctlp,
9156 	    "ahci_timeout_pkts enter: port %d", port);
9157 
9158 	mutex_enter(&ahci_portp->ahciport_mutex);
9159 
9160 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
9161 	    RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp) ||
9162 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
9163 		/* Read PxCI to see which commands are still outstanding */
9164 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
9165 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
9166 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
9167 		/* Read PxSACT to see which commands are still outstanding */
9168 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
9169 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
9170 	}
9171 
9172 #if AHCI_DEBUG
9173 	/*
9174 	 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT flag is
9175 	 * set, it means a fatal error happened after REQUEST SENSE command
9176 	 * or READ LOG EXT command is delivered to the HBA during the error
9177 	 * recovery process. At this time, the only outstanding command is
9178 	 * supposed to be REQUEST SENSE command or READ LOG EXT command.
9179 	 */
9180 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
9181 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT, ahci_ctlp,
9182 		    "ahci_timeout_pkts called while REQUEST SENSE "
9183 		    "command or READ LOG EXT command for error recovery "
9184 		    "timed out timeout_tags = 0x%x, slot_status = 0x%x, "
9185 		    "pending_tags = 0x%x, pending_ncq_tags = 0x%x",
9186 		    tmp_timeout_tags, slot_status,
9187 		    ahci_portp->ahciport_pending_tags,
9188 		    ahci_portp->ahciport_pending_ncq_tags);
9189 		ASSERT(slot_status == 0x1);
9190 	} else if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
9191 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT, ahci_ctlp,
9192 		    "ahci_timeout_pkts called while executing R/W PMULT "
9193 		    "command timeout_tags = 0x%x, slot_status = 0x%x",
9194 		    tmp_timeout_tags, slot_status);
9195 		ASSERT(slot_status == 0x1);
9196 	}
9197 #endif
9198 
9199 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
9200 	ahci_portp->ahciport_mop_in_progress++;
9201 
9202 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
9203 	    port, AHCI_PORT_RESET, NULL);
9204 
9205 	/*
9206 	 * Re-identify timeout tags because some previously checked commands
9207 	 * could already complete.
9208 	 */
9209 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
9210 		finished_tags = ahci_portp->ahciport_pending_tags &
9211 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
9212 		timeout_tags = tmp_timeout_tags & ~finished_tags;
9213 
9214 		AHCIDBG(AHCIDBG_TIMEOUT, ahci_ctlp,
9215 		    "ahci_timeout_pkts: port %d, finished_tags = 0x%x, "
9216 		    "timeout_tags = 0x%x, port_cmd_issue = 0x%x, "
9217 		    "pending_tags = 0x%x ",
9218 		    port, finished_tags, timeout_tags,
9219 		    slot_status, ahci_portp->ahciport_pending_tags);
9220 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
9221 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
9222 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
9223 		timeout_tags = tmp_timeout_tags & ~finished_tags;
9224 
9225 		AHCIDBG(AHCIDBG_TIMEOUT|AHCIDBG_NCQ, ahci_ctlp,
9226 		    "ahci_timeout_pkts: port %d, finished_tags = 0x%x, "
9227 		    "timeout_tags = 0x%x, port_sactive = 0x%x, "
9228 		    "pending_ncq_tags = 0x%x ",
9229 		    port, finished_tags, timeout_tags,
9230 		    slot_status, ahci_portp->ahciport_pending_ncq_tags);
9231 	} else if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) ||
9232 	    RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
9233 		timeout_tags = tmp_timeout_tags;
9234 	}
9235 
9236 	ahci_mop_commands(ahci_ctlp,
9237 	    ahci_portp,
9238 	    slot_status,
9239 	    0,			/* failed tags */
9240 	    timeout_tags,	/* timeout tags */
9241 	    0,			/* aborted tags */
9242 	    0);			/* reset tags */
9243 
9244 	mutex_exit(&ahci_portp->ahciport_mutex);
9245 }
9246 
9247 /*
9248  * Watchdog handler kicks in every 5 seconds to timeout any commands pending
9249  * for long time.
9250  */
9251 static void
9252 ahci_watchdog_handler(ahci_ctl_t *ahci_ctlp)
9253 {
9254 	ahci_port_t *ahci_portp;
9255 	sata_pkt_t *spkt;
9256 	uint32_t pending_tags;
9257 	uint32_t timeout_tags;
9258 	uint32_t port_cmd_status;
9259 	uint32_t port_sactive;
9260 	uint8_t port;
9261 	int tmp_slot;
9262 	int current_slot;
9263 	uint32_t current_tags;
9264 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
9265 	/* max number of cycles this packet should survive */
9266 	int max_life_cycles;
9267 
9268 	/* how many cycles this packet survived so far */
9269 	int watched_cycles;
9270 
9271 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
9272 
9273 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
9274 	    "ahci_watchdog_handler entered", NULL);
9275 
9276 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
9277 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
9278 			continue;
9279 		}
9280 
9281 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
9282 
9283 		mutex_enter(&ahci_portp->ahciport_mutex);
9284 		if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
9285 			mutex_exit(&ahci_portp->ahciport_mutex);
9286 			continue;
9287 		}
9288 
9289 		/* Skip the check for those ports in error recovery */
9290 		if ((ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) &&
9291 		    !(ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))) {
9292 			mutex_exit(&ahci_portp->ahciport_mutex);
9293 			continue;
9294 		}
9295 
9296 		pending_tags = 0;
9297 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
9298 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
9299 
9300 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) ||
9301 		    RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp)) {
9302 			current_slot = 0;
9303 			pending_tags = 0x1;
9304 		} else if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
9305 			current_slot =
9306 			    (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
9307 			    AHCI_CMD_STATUS_CCS_SHIFT;
9308 			pending_tags = ahci_portp->ahciport_pending_tags;
9309 		} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
9310 			port_sactive = ddi_get32(
9311 			    ahci_ctlp->ahcictl_ahci_acc_handle,
9312 			    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
9313 			current_tags = port_sactive &
9314 			    ~port_cmd_status &
9315 			    AHCI_NCQ_SLOT_MASK(ahci_portp);
9316 			pending_tags = ahci_portp->ahciport_pending_ncq_tags;
9317 		}
9318 
9319 		timeout_tags = 0;
9320 		while (pending_tags) {
9321 			tmp_slot = ddi_ffs(pending_tags) - 1;
9322 			if (tmp_slot == -1) {
9323 				break;
9324 			}
9325 
9326 			if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
9327 				spkt = ahci_portp->ahciport_err_retri_pkt;
9328 			else if (RDWR_PMULT_CMD_IN_PROGRESS(ahci_portp))
9329 				spkt = ahci_portp->ahciport_rdwr_pmult_pkt;
9330 			else
9331 				spkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
9332 
9333 			if ((spkt != NULL) && spkt->satapkt_time &&
9334 			    !(spkt->satapkt_op_mode & SATA_OPMODE_POLLING)) {
9335 				/*
9336 				 * We are overloading satapkt_hba_driver_private
9337 				 * with watched_cycle count.
9338 				 *
9339 				 * If a packet has survived for more than it's
9340 				 * max life cycles, it is a candidate for time
9341 				 * out.
9342 				 */
9343 				watched_cycles = (int)(intptr_t)
9344 				    spkt->satapkt_hba_driver_private;
9345 				watched_cycles++;
9346 				max_life_cycles = (spkt->satapkt_time +
9347 				    ahci_watchdog_timeout - 1) /
9348 				    ahci_watchdog_timeout;
9349 
9350 				spkt->satapkt_hba_driver_private =
9351 				    (void *)(intptr_t)watched_cycles;
9352 
9353 				if (watched_cycles <= max_life_cycles)
9354 					goto next;
9355 
9356 #if AHCI_DEBUG
9357 				if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
9358 					AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT,
9359 					    ahci_ctlp, "watchdog: the current "
9360 					    "tags is 0x%x", current_tags);
9361 				} else {
9362 					AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT,
9363 					    ahci_ctlp, "watchdog: the current "
9364 					    "slot is %d", current_slot);
9365 				}
9366 #endif
9367 
9368 				/*
9369 				 * We need to check whether the HBA has
9370 				 * begun to execute the command, if not,
9371 				 * then re-set the timer of the command.
9372 				 */
9373 				if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) &&
9374 				    (tmp_slot != current_slot) ||
9375 				    NCQ_CMD_IN_PROGRESS(ahci_portp) &&
9376 				    ((0x1 << tmp_slot) & current_tags)) {
9377 					spkt->satapkt_hba_driver_private =
9378 					    (void *)(intptr_t)0;
9379 				} else {
9380 					timeout_tags |= (0x1 << tmp_slot);
9381 					cmn_err(CE_WARN, "!ahci%d: watchdog "
9382 					    "port %d satapkt 0x%p timed out\n",
9383 					    instance, port, (void *)spkt);
9384 				}
9385 			}
9386 next:
9387 			CLEAR_BIT(pending_tags, tmp_slot);
9388 		}
9389 
9390 		if (timeout_tags) {
9391 			mutex_exit(&ahci_portp->ahciport_mutex);
9392 			mutex_exit(&ahci_ctlp->ahcictl_mutex);
9393 			ahci_timeout_pkts(ahci_ctlp, ahci_portp,
9394 			    port, timeout_tags);
9395 			mutex_enter(&ahci_ctlp->ahcictl_mutex);
9396 			mutex_enter(&ahci_portp->ahciport_mutex);
9397 		}
9398 
9399 		mutex_exit(&ahci_portp->ahciport_mutex);
9400 	}
9401 
9402 	/* Re-install the watchdog timeout handler */
9403 	if (ahci_ctlp->ahcictl_timeout_id != 0) {
9404 		ahci_ctlp->ahcictl_timeout_id =
9405 		    timeout((void (*)(void *))ahci_watchdog_handler,
9406 		    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
9407 	}
9408 
9409 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
9410 }
9411 
9412 /*
9413  * Fill the error context into sata_cmd for non-queued command error.
9414  */
9415 static void
9416 ahci_copy_err_cnxt(sata_cmd_t *scmd, ahci_fis_d2h_register_t *rfisp)
9417 {
9418 	scmd->satacmd_status_reg = GET_RFIS_STATUS(rfisp);
9419 	scmd->satacmd_error_reg = GET_RFIS_ERROR(rfisp);
9420 	scmd->satacmd_sec_count_lsb = GET_RFIS_SECTOR_COUNT(rfisp);
9421 	scmd->satacmd_lba_low_lsb = GET_RFIS_CYL_LOW(rfisp);
9422 	scmd->satacmd_lba_mid_lsb = GET_RFIS_CYL_MID(rfisp);
9423 	scmd->satacmd_lba_high_lsb = GET_RFIS_CYL_HI(rfisp);
9424 	scmd->satacmd_device_reg = GET_RFIS_DEV_HEAD(rfisp);
9425 
9426 	if (scmd->satacmd_addr_type == ATA_ADDR_LBA48) {
9427 		scmd->satacmd_sec_count_msb = GET_RFIS_SECTOR_COUNT_EXP(rfisp);
9428 		scmd->satacmd_lba_low_msb = GET_RFIS_CYL_LOW_EXP(rfisp);
9429 		scmd->satacmd_lba_mid_msb = GET_RFIS_CYL_MID_EXP(rfisp);
9430 		scmd->satacmd_lba_high_msb = GET_RFIS_CYL_HI_EXP(rfisp);
9431 	}
9432 }
9433 
9434 /*
9435  * Fill the ncq error page into sata_cmd for queued command error.
9436  */
9437 static void
9438 ahci_copy_ncq_err_page(sata_cmd_t *scmd,
9439     struct sata_ncq_error_recovery_page *ncq_err_page)
9440 {
9441 	scmd->satacmd_sec_count_msb = ncq_err_page->ncq_sector_count_ext;
9442 	scmd->satacmd_sec_count_lsb = ncq_err_page->ncq_sector_count;
9443 	scmd->satacmd_lba_low_msb = ncq_err_page->ncq_sector_number_ext;
9444 	scmd->satacmd_lba_low_lsb = ncq_err_page->ncq_sector_number;
9445 	scmd->satacmd_lba_mid_msb = ncq_err_page->ncq_cyl_low_ext;
9446 	scmd->satacmd_lba_mid_lsb = ncq_err_page->ncq_cyl_low;
9447 	scmd->satacmd_lba_high_msb = ncq_err_page->ncq_cyl_high_ext;
9448 	scmd->satacmd_lba_high_lsb = ncq_err_page->ncq_cyl_high;
9449 	scmd->satacmd_device_reg = ncq_err_page->ncq_dev_head;
9450 	scmd->satacmd_status_reg = ncq_err_page->ncq_status;
9451 	scmd->satacmd_error_reg = ncq_err_page->ncq_error;
9452 }
9453 
9454 /*
9455  * Put the respective register value to sata_cmd_t for satacmd_flags.
9456  */
9457 static void
9458 ahci_copy_out_regs(sata_cmd_t *scmd, ahci_fis_d2h_register_t *rfisp)
9459 {
9460 	if (scmd->satacmd_flags.sata_copy_out_sec_count_msb)
9461 		scmd->satacmd_sec_count_msb = GET_RFIS_SECTOR_COUNT_EXP(rfisp);
9462 	if (scmd->satacmd_flags.sata_copy_out_lba_low_msb)
9463 		scmd->satacmd_lba_low_msb = GET_RFIS_CYL_LOW_EXP(rfisp);
9464 	if (scmd->satacmd_flags.sata_copy_out_lba_mid_msb)
9465 		scmd->satacmd_lba_mid_msb = GET_RFIS_CYL_MID_EXP(rfisp);
9466 	if (scmd->satacmd_flags.sata_copy_out_lba_high_msb)
9467 		scmd->satacmd_lba_high_msb = GET_RFIS_CYL_HI_EXP(rfisp);
9468 	if (scmd->satacmd_flags.sata_copy_out_sec_count_lsb)
9469 		scmd->satacmd_sec_count_lsb = GET_RFIS_SECTOR_COUNT(rfisp);
9470 	if (scmd->satacmd_flags.sata_copy_out_lba_low_lsb)
9471 		scmd->satacmd_lba_low_lsb = GET_RFIS_CYL_LOW(rfisp);
9472 	if (scmd->satacmd_flags.sata_copy_out_lba_mid_lsb)
9473 		scmd->satacmd_lba_mid_lsb = GET_RFIS_CYL_MID(rfisp);
9474 	if (scmd->satacmd_flags.sata_copy_out_lba_high_lsb)
9475 		scmd->satacmd_lba_high_lsb = GET_RFIS_CYL_HI(rfisp);
9476 	if (scmd->satacmd_flags.sata_copy_out_device_reg)
9477 		scmd->satacmd_device_reg = GET_RFIS_DEV_HEAD(rfisp);
9478 	if (scmd->satacmd_flags.sata_copy_out_error_reg)
9479 		scmd->satacmd_error_reg = GET_RFIS_ERROR(rfisp);
9480 }
9481 
9482 static void
9483 ahci_log_fatal_error_message(ahci_ctl_t *ahci_ctlp, uint8_t port,
9484     uint32_t intr_status)
9485 {
9486 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
9487 
9488 	if (intr_status & AHCI_INTR_STATUS_IFS)
9489 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has interface fatal "
9490 		    "error", instance, port);
9491 
9492 	if (intr_status & AHCI_INTR_STATUS_HBDS)
9493 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has bus data error",
9494 		    instance, port);
9495 
9496 	if (intr_status & AHCI_INTR_STATUS_HBFS)
9497 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has bus fatal error",
9498 		    instance, port);
9499 
9500 	if (intr_status & AHCI_INTR_STATUS_TFES)
9501 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has task file error",
9502 		    instance, port);
9503 
9504 	cmn_err(CE_WARN, "!ahci%d: ahci port %d is trying to do error "
9505 	    "recovery", instance, port);
9506 }
9507 
9508 /*
9509  * Dump the serror message to the log.
9510  */
9511 static void
9512 ahci_log_serror_message(ahci_ctl_t *ahci_ctlp, uint8_t port,
9513     uint32_t port_serror, int debug_only)
9514 {
9515 	static char err_buf[512];
9516 	static char err_msg_header[16];
9517 	char *err_msg = err_buf;
9518 
9519 	*err_buf = '\0';
9520 	*err_msg_header = '\0';
9521 
9522 	if (port_serror & SERROR_DATA_ERR_FIXED) {
9523 		err_msg = strcat(err_msg,
9524 		    "\tRecovered Data Integrity Error (I)\n");
9525 	}
9526 
9527 	if (port_serror & SERROR_COMM_ERR_FIXED) {
9528 		err_msg = strcat(err_msg,
9529 		    "\tRecovered Communication Error (M)\n");
9530 	}
9531 
9532 	if (port_serror & SERROR_DATA_ERR) {
9533 		err_msg = strcat(err_msg,
9534 		    "\tTransient Data Integrity Error (T)\n");
9535 	}
9536 
9537 	if (port_serror & SERROR_PERSISTENT_ERR) {
9538 		err_msg = strcat(err_msg,
9539 		    "\tPersistent Communication or Data Integrity Error (C)\n");
9540 	}
9541 
9542 	if (port_serror & SERROR_PROTOCOL_ERR) {
9543 		err_msg = strcat(err_msg, "\tProtocol Error (P)\n");
9544 	}
9545 
9546 	if (port_serror & SERROR_INT_ERR) {
9547 		err_msg = strcat(err_msg, "\tInternal Error (E)\n");
9548 	}
9549 
9550 	if (port_serror & SERROR_PHY_RDY_CHG) {
9551 		err_msg = strcat(err_msg, "\tPhyRdy Change (N)\n");
9552 	}
9553 
9554 	if (port_serror & SERROR_PHY_INT_ERR) {
9555 		err_msg = strcat(err_msg, "\tPhy Internal Error (I)\n");
9556 	}
9557 
9558 	if (port_serror & SERROR_COMM_WAKE) {
9559 		err_msg = strcat(err_msg, "\tComm Wake (W)\n");
9560 	}
9561 
9562 	if (port_serror & SERROR_10B_TO_8B_ERR) {
9563 		err_msg = strcat(err_msg, "\t10B to 8B Decode Error (B)\n");
9564 	}
9565 
9566 	if (port_serror & SERROR_DISPARITY_ERR) {
9567 		err_msg = strcat(err_msg, "\tDisparity Error (D)\n");
9568 	}
9569 
9570 	if (port_serror & SERROR_CRC_ERR) {
9571 		err_msg = strcat(err_msg, "\tCRC Error (C)\n");
9572 	}
9573 
9574 	if (port_serror & SERROR_HANDSHAKE_ERR) {
9575 		err_msg = strcat(err_msg, "\tHandshake Error (H)\n");
9576 	}
9577 
9578 	if (port_serror & SERROR_LINK_SEQ_ERR) {
9579 		err_msg = strcat(err_msg, "\tLink Sequence Error (S)\n");
9580 	}
9581 
9582 	if (port_serror & SERROR_TRANS_ERR) {
9583 		err_msg = strcat(err_msg,
9584 		    "\tTransport state transition error (T)\n");
9585 	}
9586 
9587 	if (port_serror & SERROR_FIS_TYPE) {
9588 		err_msg = strcat(err_msg, "\tUnknown FIS Type (F)\n");
9589 	}
9590 
9591 	if (port_serror & SERROR_EXCHANGED_ERR) {
9592 		err_msg = strcat(err_msg, "\tExchanged (X)\n");
9593 	}
9594 
9595 	if (err_msg == NULL)
9596 		return;
9597 
9598 	if (debug_only) {
9599 		(void) sprintf(err_msg_header, "port %d", port);
9600 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, err_msg_header, NULL);
9601 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, err_msg, NULL);
9602 	} else if (ahci_ctlp) {
9603 		cmn_err(CE_WARN, "!ahci%d: %s %s",
9604 		    ddi_get_instance(ahci_ctlp->ahcictl_dip),
9605 		    err_msg_header, err_msg);
9606 
9607 		/* sata trace debug */
9608 		sata_trace_debug(ahci_ctlp->ahcictl_dip,
9609 		    "ahci%d: %s %s", ddi_get_instance(ahci_ctlp->ahcictl_dip),
9610 		    err_msg_header, err_msg);
9611 	} else {
9612 		cmn_err(CE_WARN, "!ahci: %s %s", err_msg_header, err_msg);
9613 
9614 		/* sata trace debug */
9615 		sata_trace_debug(NULL, "ahci: %s %s", err_msg_header, err_msg);
9616 	}
9617 }
9618 
9619 /*
9620  * Translate the sata_address_t type into the ahci_addr_t type.
9621  * sata_device.satadev_addr structure is used as source.
9622  */
9623 static void
9624 ahci_get_ahci_addr(ahci_ctl_t *ahci_ctlp, sata_device_t *sd,
9625     ahci_addr_t *ahci_addrp)
9626 {
9627 	sata_address_t *sata_addrp = &sd->satadev_addr;
9628 	ahci_addrp->aa_port =
9629 	    ahci_ctlp->ahcictl_cport_to_port[sata_addrp->cport];
9630 	ahci_addrp->aa_pmport = sata_addrp->pmport;
9631 
9632 	switch (sata_addrp->qual) {
9633 	case SATA_ADDR_DCPORT:
9634 	case SATA_ADDR_CPORT:
9635 		ahci_addrp->aa_qual = AHCI_ADDR_PORT;
9636 		break;
9637 	case SATA_ADDR_PMULT:
9638 		ahci_addrp->aa_qual = AHCI_ADDR_PMULT;
9639 		break;
9640 	case SATA_ADDR_DPMPORT:
9641 	case SATA_ADDR_PMPORT:
9642 		ahci_addrp->aa_qual = AHCI_ADDR_PMPORT;
9643 		break;
9644 	case SATA_ADDR_NULL:
9645 	default:
9646 		/* something went wrong */
9647 		ahci_addrp->aa_qual = AHCI_ADDR_NULL;
9648 		break;
9649 	}
9650 }
9651 
9652 /*
9653  * This routine is to calculate the total number of ports implemented
9654  * by the HBA.
9655  */
9656 static int
9657 ahci_get_num_implemented_ports(uint32_t ports_implemented)
9658 {
9659 	uint8_t i;
9660 	int num = 0;
9661 
9662 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
9663 		if (((uint32_t)0x1 << i) & ports_implemented)
9664 			num++;
9665 	}
9666 
9667 	return (num);
9668 }
9669 
9670 #if AHCI_DEBUG
9671 static void
9672 ahci_log(ahci_ctl_t *ahci_ctlp, uint_t level, char *fmt, ...)
9673 {
9674 	static char name[16];
9675 	va_list ap;
9676 
9677 	mutex_enter(&ahci_log_mutex);
9678 
9679 	va_start(ap, fmt);
9680 	if (ahci_ctlp) {
9681 		(void) sprintf(name, "ahci%d: ",
9682 		    ddi_get_instance(ahci_ctlp->ahcictl_dip));
9683 	} else {
9684 		(void) sprintf(name, "ahci: ");
9685 	}
9686 
9687 	(void) vsprintf(ahci_log_buf, fmt, ap);
9688 	va_end(ap);
9689 
9690 	cmn_err(level, "%s%s", name, ahci_log_buf);
9691 
9692 	mutex_exit(&ahci_log_mutex);
9693 }
9694 #endif
9695 
9696 /*
9697  * quiesce(9E) entry point.
9698  *
9699  * This function is called when the system is single-threaded at high
9700  * PIL with preemption disabled. Therefore, this function must not be
9701  * blocked.
9702  *
9703  * This function returns DDI_SUCCESS on success, or DDI_FAILURE on failure.
9704  * DDI_FAILURE indicates an error condition and should almost never happen.
9705  */
9706 static int
9707 ahci_quiesce(dev_info_t *dip)
9708 {
9709 	ahci_ctl_t *ahci_ctlp;
9710 	ahci_port_t *ahci_portp;
9711 	int instance, port;
9712 
9713 	instance = ddi_get_instance(dip);
9714 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
9715 
9716 	if (ahci_ctlp == NULL)
9717 		return (DDI_FAILURE);
9718 
9719 #if AHCI_DEBUG
9720 	ahci_debug_flags = 0;
9721 #endif
9722 
9723 	/* disable all the interrupts. */
9724 	ahci_disable_all_intrs(ahci_ctlp);
9725 
9726 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
9727 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
9728 			continue;
9729 		}
9730 
9731 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
9732 
9733 		/*
9734 		 * Stop the port by clearing PxCMD.ST
9735 		 *
9736 		 * Here we must disable the port interrupt because
9737 		 * ahci_disable_all_intrs only clear GHC.IE, and IS
9738 		 * register will be still set if PxIE is enabled.
9739 		 * When ahci shares one IRQ with other drivers, the
9740 		 * intr handler may claim the intr mistakenly.
9741 		 */
9742 		ahci_disable_port_intrs(ahci_ctlp, port);
9743 		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
9744 		    ahci_portp, port);
9745 	}
9746 
9747 	return (DDI_SUCCESS);
9748 }
9749