xref: /illumos-gate/usr/src/uts/common/io/sata/adapters/ahci/ahci.c (revision bbe6aa77dcdd1ff0ed28cd41788ea266c5fba962)
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 
98 static	int ahci_initialize_controller(ahci_ctl_t *);
99 static	void ahci_uninitialize_controller(ahci_ctl_t *);
100 static	int ahci_initialize_port(ahci_ctl_t *, ahci_port_t *, uint8_t);
101 static	int ahci_config_space_init(ahci_ctl_t *);
102 
103 static	void ahci_drain_ports_taskq(ahci_ctl_t *);
104 static	void ahci_disable_interface_pm(ahci_ctl_t *, uint8_t);
105 static	int ahci_start_port(ahci_ctl_t *, ahci_port_t *, uint8_t);
106 static	void ahci_find_dev_signature(ahci_ctl_t *, ahci_port_t *, uint8_t);
107 static	void ahci_update_sata_registers(ahci_ctl_t *, uint8_t, sata_device_t *);
108 static	int ahci_deliver_satapkt(ahci_ctl_t *, ahci_port_t *,
109     uint8_t, sata_pkt_t *);
110 static	int ahci_do_sync_start(ahci_ctl_t *, ahci_port_t *,
111     uint8_t, sata_pkt_t *);
112 static	int ahci_claim_free_slot(ahci_ctl_t *, ahci_port_t *, int);
113 static  void ahci_copy_err_cnxt(sata_cmd_t *, ahci_fis_d2h_register_t *);
114 static	void ahci_copy_ncq_err_page(sata_cmd_t *,
115     struct sata_ncq_error_recovery_page *);
116 static	void ahci_copy_out_regs(sata_cmd_t *, ahci_fis_d2h_register_t *);
117 
118 static	int ahci_software_reset(ahci_ctl_t *, ahci_port_t *, uint8_t);
119 static	int ahci_hba_reset(ahci_ctl_t *);
120 static	int ahci_port_reset(ahci_ctl_t *, ahci_port_t *, uint8_t);
121 static	void ahci_reject_all_abort_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
122 static	int ahci_reset_device_reject_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
123 static	int ahci_reset_port_reject_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
124 static	int ahci_reset_hba_reject_pkts(ahci_ctl_t *);
125 static	int ahci_put_port_into_notrunning_state(ahci_ctl_t *, ahci_port_t *,
126     uint8_t);
127 static	int ahci_restart_port_wait_till_ready(ahci_ctl_t *, ahci_port_t *,
128     uint8_t, int, int *);
129 static	void ahci_mop_commands(ahci_ctl_t *, ahci_port_t *, uint32_t,
130     uint32_t, uint32_t, uint32_t, uint32_t);
131 static	uint32_t ahci_get_rdlogext_data(ahci_ctl_t *, ahci_port_t *, uint8_t);
132 static void ahci_get_rqsense_data(ahci_ctl_t *, ahci_port_t *,
133     uint8_t, sata_pkt_t *);
134 static	void ahci_fatal_error_recovery_handler(ahci_ctl_t *, ahci_port_t *,
135     uint8_t, uint32_t);
136 static	void ahci_timeout_pkts(ahci_ctl_t *, ahci_port_t *,
137     uint8_t, uint32_t);
138 static	void ahci_events_handler(void *);
139 static	void ahci_watchdog_handler(ahci_ctl_t *);
140 
141 static	uint_t ahci_intr(caddr_t, caddr_t);
142 static	void ahci_port_intr(ahci_ctl_t *, ahci_port_t *, uint8_t);
143 static	int ahci_add_intrs(ahci_ctl_t *, int);
144 static	void ahci_rem_intrs(ahci_ctl_t *);
145 static	void ahci_enable_all_intrs(ahci_ctl_t *);
146 static	void ahci_disable_all_intrs(ahci_ctl_t *);
147 static	void ahci_enable_port_intrs(ahci_ctl_t *, uint8_t);
148 static	void ahci_disable_port_intrs(ahci_ctl_t *, uint8_t);
149 
150 static  int ahci_intr_cmd_cmplt(ahci_ctl_t *, ahci_port_t *, uint8_t);
151 static	int ahci_intr_set_device_bits(ahci_ctl_t *, ahci_port_t *, uint8_t);
152 static	int ahci_intr_port_connect_change(ahci_ctl_t *, ahci_port_t *, uint8_t);
153 static	int ahci_intr_device_mechanical_presence_status(ahci_ctl_t *,
154     ahci_port_t *, uint8_t);
155 static	int ahci_intr_phyrdy_change(ahci_ctl_t *, ahci_port_t *, uint8_t);
156 static	int ahci_intr_non_fatal_error(ahci_ctl_t *, ahci_port_t *,
157     uint8_t, uint32_t);
158 static  int ahci_intr_fatal_error(ahci_ctl_t *, ahci_port_t *,
159     uint8_t, uint32_t);
160 static	int ahci_intr_cold_port_detect(ahci_ctl_t *, ahci_port_t *, uint8_t);
161 
162 static	int ahci_get_num_implemented_ports(uint32_t);
163 static  void ahci_log_fatal_error_message(ahci_ctl_t *, uint8_t port,
164     uint32_t);
165 static	void ahci_log_serror_message(ahci_ctl_t *, uint8_t, uint32_t, int);
166 #if AHCI_DEBUG
167 static	void ahci_log(ahci_ctl_t *, uint_t, char *, ...);
168 #endif
169 
170 
171 /*
172  * DMA attributes for the data buffer
173  *
174  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
175  * does not support 64-bit addressing
176  */
177 static ddi_dma_attr_t buffer_dma_attr = {
178 	DMA_ATTR_V0,		/* dma_attr_version */
179 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
180 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
181 	0x3fffffull,		/* dma_attr_count_max i.e. for one cookie */
182 	0x2ull,			/* dma_attr_align: word aligned */
183 	1,			/* dma_attr_burstsizes */
184 	1,			/* dma_attr_minxfer */
185 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
186 	0xffffffffull,		/* dma_attr_seg */
187 	AHCI_PRDT_NUMBER,	/* dma_attr_sgllen */
188 	512,			/* dma_attr_granular */
189 	0,			/* dma_attr_flags */
190 };
191 
192 /*
193  * DMA attributes for the rcvd FIS
194  *
195  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
196  * does not support 64-bit addressing
197  */
198 static ddi_dma_attr_t rcvd_fis_dma_attr = {
199 	DMA_ATTR_V0,		/* dma_attr_version */
200 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
201 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
202 	0xffffffffull,		/* dma_attr_count_max i.e. for one cookie */
203 	0x100ull,		/* dma_attr_align: 256-byte aligned */
204 	1,			/* dma_attr_burstsizes */
205 	1,			/* dma_attr_minxfer */
206 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
207 	0xffffffffull,		/* dma_attr_seg */
208 	1,			/* dma_attr_sgllen */
209 	1,			/* dma_attr_granular */
210 	0,			/* dma_attr_flags */
211 };
212 
213 /*
214  * DMA attributes for the command list
215  *
216  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
217  * does not support 64-bit addressing
218  */
219 static ddi_dma_attr_t cmd_list_dma_attr = {
220 	DMA_ATTR_V0,		/* dma_attr_version */
221 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
222 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
223 	0xffffffffull,		/* dma_attr_count_max i.e. for one cookie */
224 	0x400ull,		/* dma_attr_align: 1K-byte aligned */
225 	1,			/* dma_attr_burstsizes */
226 	1,			/* dma_attr_minxfer */
227 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
228 	0xffffffffull,		/* dma_attr_seg */
229 	1,			/* dma_attr_sgllen */
230 	1,			/* dma_attr_granular */
231 	0,			/* dma_attr_flags */
232 };
233 
234 /*
235  * DMA attributes for cmd tables
236  *
237  * dma_attr_addr_hi will be changed to 0xffffffffull if the HBA
238  * does not support 64-bit addressing
239  */
240 static ddi_dma_attr_t cmd_table_dma_attr = {
241 	DMA_ATTR_V0,		/* dma_attr_version */
242 	0x0ull,			/* dma_attr_addr_lo: lowest bus address */
243 	0xffffffffffffffffull,	/* dma_attr_addr_hi: highest bus address */
244 	0xffffffffull,		/* dma_attr_count_max i.e. for one cookie */
245 	0x80ull,		/* dma_attr_align: 128-byte aligned */
246 	1,			/* dma_attr_burstsizes */
247 	1,			/* dma_attr_minxfer */
248 	0xffffffffull,		/* dma_attr_maxxfer i.e. includes all cookies */
249 	0xffffffffull,		/* dma_attr_seg */
250 	1,			/* dma_attr_sgllen */
251 	1,			/* dma_attr_granular */
252 	0,			/* dma_attr_flags */
253 };
254 
255 
256 /* Device access attributes */
257 static ddi_device_acc_attr_t accattr = {
258 	DDI_DEVICE_ATTR_V0,
259 	DDI_STRUCTURE_LE_ACC,
260 	DDI_STRICTORDER_ACC
261 };
262 
263 
264 static struct dev_ops ahcictl_dev_ops = {
265 	DEVO_REV,		/* devo_rev */
266 	0,			/* refcnt  */
267 	ahci_getinfo,		/* info */
268 	nulldev,		/* identify */
269 	nulldev,		/* probe */
270 	ahci_attach,		/* attach */
271 	ahci_detach,		/* detach */
272 	nodev,			/* no reset */
273 	(struct cb_ops *)0,	/* driver operations */
274 	NULL,			/* bus operations */
275 	NULL,			/* power */
276 	ahci_quiesce,		/* quiesce */
277 };
278 
279 static sata_tran_hotplug_ops_t ahci_tran_hotplug_ops = {
280 	SATA_TRAN_HOTPLUG_OPS_REV_1,
281 	ahci_tran_hotplug_port_activate,
282 	ahci_tran_hotplug_port_deactivate
283 };
284 
285 extern struct mod_ops mod_driverops;
286 
287 static  struct modldrv modldrv = {
288 	&mod_driverops,		/* driverops */
289 	ahci_ident,		/* short description */
290 	&ahcictl_dev_ops,	/* driver ops */
291 };
292 
293 static  struct modlinkage modlinkage = {
294 	MODREV_1,
295 	&modldrv,
296 	NULL
297 };
298 
299 /* The following variables are watchdog handler related */
300 static int ahci_watchdog_timeout = 5; /* 5 seconds */
301 static int ahci_watchdog_tick;
302 
303 /*
304  * This static variable indicates the size of command table,
305  * and it's changeable with prdt number, which ahci_dma_prdt_number
306  * indicates.
307  */
308 static size_t ahci_cmd_table_size;
309 
310 /*
311  * The below global variables are tunable via /etc/system
312  *
313  *	ahci_dma_prdt_number
314  *	ahci_msi_enabled
315  *	ahci_buf_64bit_dma
316  *	ahci_commu_64bit_dma
317  */
318 
319 /* The number of Physical Region Descriptor Table(PRDT) in Command Table */
320 int ahci_dma_prdt_number = AHCI_PRDT_NUMBER;
321 
322 /* AHCI MSI is tunable */
323 boolean_t ahci_msi_enabled = B_TRUE;
324 
325 /*
326  * 64-bit dma addressing for data buffer is tunable
327  *
328  * The variable controls only the below value:
329  *	DBAU (upper 32-bits physical address of data block)
330  */
331 boolean_t ahci_buf_64bit_dma = B_TRUE;
332 
333 /*
334  * 64-bit dma addressing for communication system descriptors is tunable
335  *
336  * The variable controls the below three values:
337  *
338  *	PxCLBU (upper 32-bits for the command list base physical address)
339  *	PxFBU (upper 32-bits for the received FIS base physical address)
340  *	CTBAU (upper 32-bits of command table base)
341  */
342 boolean_t ahci_commu_64bit_dma = B_TRUE;
343 
344 /*
345  * End of global tunable variable definition
346  */
347 
348 #if AHCI_DEBUG
349 uint32_t ahci_debug_flags = 0;
350 #else
351 uint32_t ahci_debug_flags = (AHCIDBG_ERRS|AHCIDBG_TIMEOUT);
352 #endif
353 
354 
355 #if AHCI_DEBUG
356 /* The following is needed for ahci_log() */
357 static kmutex_t ahci_log_mutex;
358 static char ahci_log_buf[512];
359 #endif
360 
361 /* Opaque state pointer initialized by ddi_soft_state_init() */
362 static void *ahci_statep = NULL;
363 
364 /*
365  *  ahci module initialization.
366  */
367 int
368 _init(void)
369 {
370 	int	ret;
371 
372 	ret = ddi_soft_state_init(&ahci_statep, sizeof (ahci_ctl_t), 0);
373 	if (ret != 0) {
374 		goto err_out;
375 	}
376 
377 #if AHCI_DEBUG
378 	mutex_init(&ahci_log_mutex, NULL, MUTEX_DRIVER, NULL);
379 #endif
380 
381 	if ((ret = sata_hba_init(&modlinkage)) != 0) {
382 #if AHCI_DEBUG
383 		mutex_destroy(&ahci_log_mutex);
384 #endif
385 		ddi_soft_state_fini(&ahci_statep);
386 		goto err_out;
387 	}
388 
389 	ret = mod_install(&modlinkage);
390 	if (ret != 0) {
391 		sata_hba_fini(&modlinkage);
392 #if AHCI_DEBUG
393 		mutex_destroy(&ahci_log_mutex);
394 #endif
395 		ddi_soft_state_fini(&ahci_statep);
396 		goto err_out;
397 	}
398 
399 	/* watchdog tick */
400 	ahci_watchdog_tick = drv_usectohz(
401 	    (clock_t)ahci_watchdog_timeout * 1000000);
402 	return (ret);
403 
404 err_out:
405 	cmn_err(CE_WARN, "!ahci: Module init failed");
406 	return (ret);
407 }
408 
409 /*
410  * ahci module uninitialize.
411  */
412 int
413 _fini(void)
414 {
415 	int	ret;
416 
417 	ret = mod_remove(&modlinkage);
418 	if (ret != 0) {
419 		return (ret);
420 	}
421 
422 	/* Remove the resources allocated in _init(). */
423 	sata_hba_fini(&modlinkage);
424 #if AHCI_DEBUG
425 	mutex_destroy(&ahci_log_mutex);
426 #endif
427 	ddi_soft_state_fini(&ahci_statep);
428 
429 	return (ret);
430 }
431 
432 /*
433  * _info entry point
434  */
435 int
436 _info(struct modinfo *modinfop)
437 {
438 	return (mod_info(&modlinkage, modinfop));
439 }
440 
441 /*
442  * The attach entry point for dev_ops.
443  */
444 static int
445 ahci_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
446 {
447 	ahci_ctl_t *ahci_ctlp = NULL;
448 	int instance = ddi_get_instance(dip);
449 	int status;
450 	int attach_state;
451 	uint32_t cap_status, ahci_version;
452 	int intr_types;
453 	int i;
454 	pci_regspec_t *regs;
455 	int regs_length;
456 	int rnumber;
457 #if AHCI_DEBUG
458 	int speed;
459 #endif
460 
461 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp, "ahci_attach enter",
462 	    NULL);
463 
464 	switch (cmd) {
465 	case DDI_ATTACH:
466 		break;
467 
468 	case DDI_RESUME:
469 
470 		/*
471 		 * During DDI_RESUME, the hardware state of the device
472 		 * (power may have been removed from the device) must be
473 		 * restored, allow pending requests to continue, and
474 		 * service new requests.
475 		 */
476 		ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
477 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
478 
479 		/* Restart watch thread */
480 		if (ahci_ctlp->ahcictl_timeout_id == 0)
481 			ahci_ctlp->ahcictl_timeout_id = timeout(
482 			    (void (*)(void *))ahci_watchdog_handler,
483 			    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
484 
485 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
486 
487 		/*
488 		 * Re-initialize the controller and enable the interrupts and
489 		 * restart all the ports.
490 		 *
491 		 * Note that so far we don't support hot-plug during
492 		 * suspend/resume.
493 		 */
494 		if (ahci_initialize_controller(ahci_ctlp) != AHCI_SUCCESS) {
495 			AHCIDBG(AHCIDBG_ERRS|AHCIDBG_PM, ahci_ctlp,
496 			    "Failed to initialize the controller "
497 			    "during DDI_RESUME", NULL);
498 			return (DDI_FAILURE);
499 		}
500 
501 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
502 		ahci_ctlp->ahcictl_flags &= ~ AHCI_SUSPEND;
503 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
504 
505 		return (DDI_SUCCESS);
506 
507 	default:
508 		return (DDI_FAILURE);
509 	}
510 
511 	attach_state = AHCI_ATTACH_STATE_NONE;
512 
513 	/* Allocate soft state */
514 	status = ddi_soft_state_zalloc(ahci_statep, instance);
515 	if (status != DDI_SUCCESS) {
516 		cmn_err(CE_WARN, "!ahci%d: Cannot allocate soft state",
517 		    instance);
518 		goto err_out;
519 	}
520 
521 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
522 	ahci_ctlp->ahcictl_flags |= AHCI_ATTACH;
523 	ahci_ctlp->ahcictl_dip = dip;
524 
525 	/* Initialize the cport/port mapping */
526 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
527 		ahci_ctlp->ahcictl_port_to_cport[i] = 0xff;
528 		ahci_ctlp->ahcictl_cport_to_port[i] = 0xff;
529 	}
530 
531 	attach_state |= AHCI_ATTACH_STATE_STATEP_ALLOC;
532 
533 	/*
534 	 * Now map the AHCI base address; which includes global
535 	 * registers and port control registers
536 	 *
537 	 * According to the spec, the AHCI Base Address is BAR5,
538 	 * but BAR0-BAR4 are optional, so we need to check which
539 	 * rnumber is used for BAR5.
540 	 */
541 
542 	/*
543 	 * search through DDI "reg" property for the AHCI register set
544 	 */
545 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dip,
546 	    DDI_PROP_DONTPASS, "reg", (int **)&regs,
547 	    (uint_t *)&regs_length) != DDI_PROP_SUCCESS) {
548 		cmn_err(CE_WARN, "!ahci%d: Cannot lookup reg property",
549 		    instance);
550 		goto err_out;
551 	}
552 
553 	/* AHCI Base Address is located at 0x24 offset */
554 	for (rnumber = 0; rnumber < regs_length; ++rnumber) {
555 		if ((regs[rnumber].pci_phys_hi & PCI_REG_REG_M)
556 		    == AHCI_PCI_RNUM)
557 			break;
558 	}
559 
560 	ddi_prop_free(regs);
561 
562 	if (rnumber == regs_length) {
563 		cmn_err(CE_WARN, "!ahci%d: Cannot find AHCI register set",
564 		    instance);
565 		goto err_out;
566 	}
567 
568 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "rnumber = %d", rnumber);
569 
570 	status = ddi_regs_map_setup(dip,
571 	    rnumber,
572 	    (caddr_t *)&ahci_ctlp->ahcictl_ahci_addr,
573 	    0,
574 	    0,
575 	    &accattr,
576 	    &ahci_ctlp->ahcictl_ahci_acc_handle);
577 	if (status != DDI_SUCCESS) {
578 		cmn_err(CE_WARN, "!ahci%d: Cannot map register space",
579 		    instance);
580 		goto err_out;
581 	}
582 
583 	attach_state |= AHCI_ATTACH_STATE_REG_MAP;
584 
585 	/* Get the AHCI version information */
586 	ahci_version = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
587 	    (uint32_t *)AHCI_GLOBAL_VS(ahci_ctlp));
588 
589 	cmn_err(CE_NOTE, "!ahci%d: hba AHCI version = %x.%x", instance,
590 	    (ahci_version & 0xffff0000) >> 16,
591 	    ((ahci_version & 0x0000ff00) >> 4 |
592 	    (ahci_version & 0x000000ff)));
593 
594 	/* We don't support controllers whose versions are lower than 1.0 */
595 	if (!(ahci_version & 0xffff0000)) {
596 		cmn_err(CE_WARN, "ahci%d: Don't support AHCI HBA with lower "
597 		    "than version 1.0", instance);
598 		goto err_out;
599 	}
600 
601 	/* Get the HBA capabilities information */
602 	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
603 	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
604 
605 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba capabilites = 0x%x",
606 	    cap_status);
607 
608 #if AHCI_DEBUG
609 	/* Get the interface speed supported by the HBA */
610 	speed = (cap_status & AHCI_HBA_CAP_ISS) >> AHCI_HBA_CAP_ISS_SHIFT;
611 	if (speed == 0x01) {
612 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
613 		    "hba interface speed support: Gen 1 (1.5Gbps)", NULL);
614 	} else if (speed == 0x10) {
615 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
616 		    "hba interface speed support: Gen 2 (3 Gbps)", NULL);
617 	} else if (speed == 0x11) {
618 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
619 		    "hba interface speed support: Gen 3 (6 Gbps)", NULL);
620 	}
621 #endif
622 
623 	/* Get the number of command slots supported by the HBA */
624 	ahci_ctlp->ahcictl_num_cmd_slots =
625 	    ((cap_status & AHCI_HBA_CAP_NCS) >>
626 	    AHCI_HBA_CAP_NCS_SHIFT) + 1;
627 
628 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba number of cmd slots: %d",
629 	    ahci_ctlp->ahcictl_num_cmd_slots);
630 
631 	/* Get the bit map which indicates ports implemented by the HBA */
632 	ahci_ctlp->ahcictl_ports_implemented =
633 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
634 	    (uint32_t *)AHCI_GLOBAL_PI(ahci_ctlp));
635 
636 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba implementation of ports: 0x%x",
637 	    ahci_ctlp->ahcictl_ports_implemented);
638 
639 	/*
640 	 * According to the AHCI spec, CAP.NP should indicate the maximum
641 	 * number of ports supported by the HBA silicon, but we found
642 	 * this value of ICH8 chipset only indicates the number of ports
643 	 * implemented (exposed) by it. Therefore, the driver should calculate
644 	 * the potential maximum value by checking PI register, and use
645 	 * the maximum of this value and CAP.NP.
646 	 */
647 	ahci_ctlp->ahcictl_num_ports = max(
648 	    (cap_status & AHCI_HBA_CAP_NP) + 1,
649 	    ddi_fls(ahci_ctlp->ahcictl_ports_implemented));
650 
651 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "hba number of ports: %d",
652 	    ahci_ctlp->ahcictl_num_ports);
653 
654 	/* Get the number of implemented ports by the HBA */
655 	ahci_ctlp->ahcictl_num_implemented_ports =
656 	    ahci_get_num_implemented_ports(
657 	    ahci_ctlp->ahcictl_ports_implemented);
658 
659 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
660 	    "hba number of implemented ports: %d",
661 	    ahci_ctlp->ahcictl_num_implemented_ports);
662 
663 	/* Check whether HBA supports 64bit DMA addressing */
664 	if (!(cap_status & AHCI_HBA_CAP_S64A)) {
665 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_BUF_32BIT_DMA;
666 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
667 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
668 		    "hba does not support 64-bit addressing", NULL);
669 	}
670 
671 	/* Checking for Support Command List Override */
672 	if (cap_status & AHCI_HBA_CAP_SCLO) {
673 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_SCLO;
674 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
675 		    "hba supports command list override.", NULL);
676 	}
677 
678 	if (pci_config_setup(dip, &ahci_ctlp->ahcictl_pci_conf_handle)
679 	    != DDI_SUCCESS) {
680 		cmn_err(CE_WARN, "!ahci%d: Cannot set up pci configure space",
681 		    instance);
682 		goto err_out;
683 	}
684 
685 	attach_state |= AHCI_ATTACH_STATE_PCICFG_SETUP;
686 
687 	/*
688 	 * Check the pci configuration space, and set caps. We also
689 	 * handle the hardware defect in this function.
690 	 *
691 	 * For example, force ATI SB600 to use 32-bit dma addressing
692 	 * since it doesn't support 64-bit dma though its CAP register
693 	 * declares it support.
694 	 */
695 	if (ahci_config_space_init(ahci_ctlp) == AHCI_FAILURE) {
696 		cmn_err(CE_WARN, "!ahci%d: ahci_config_space_init failed",
697 		    instance);
698 		goto err_out;
699 	}
700 
701 	/*
702 	 * Disable the whole controller interrupts before adding
703 	 * interrupt handlers(s).
704 	 */
705 	ahci_disable_all_intrs(ahci_ctlp);
706 
707 	/* Get supported interrupt types */
708 	if (ddi_intr_get_supported_types(dip, &intr_types) != DDI_SUCCESS) {
709 		cmn_err(CE_WARN, "!ahci%d: ddi_intr_get_supported_types failed",
710 		    instance);
711 		goto err_out;
712 	}
713 
714 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
715 	    "ddi_intr_get_supported_types() returned: 0x%x",
716 	    intr_types);
717 
718 	if (ahci_msi_enabled && (intr_types & DDI_INTR_TYPE_MSI)) {
719 		/*
720 		 * Try MSI first, but fall back to FIXED if failed
721 		 */
722 		if (ahci_add_intrs(ahci_ctlp, DDI_INTR_TYPE_MSI) ==
723 		    DDI_SUCCESS) {
724 			ahci_ctlp->ahcictl_intr_type = DDI_INTR_TYPE_MSI;
725 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
726 			    "Using MSI interrupt type", NULL);
727 			goto intr_done;
728 		}
729 
730 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
731 		    "MSI registration failed, "
732 		    "trying FIXED interrupts", NULL);
733 	}
734 
735 	if (intr_types & DDI_INTR_TYPE_FIXED) {
736 		if (ahci_add_intrs(ahci_ctlp, DDI_INTR_TYPE_FIXED) ==
737 		    DDI_SUCCESS) {
738 			ahci_ctlp->ahcictl_intr_type = DDI_INTR_TYPE_FIXED;
739 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
740 			    "Using FIXED interrupt type", NULL);
741 			goto intr_done;
742 		}
743 
744 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
745 		    "FIXED interrupt registration failed", NULL);
746 	}
747 
748 	cmn_err(CE_WARN, "!ahci%d: Interrupt registration failed", instance);
749 
750 	goto err_out;
751 
752 intr_done:
753 
754 	attach_state |= AHCI_ATTACH_STATE_INTR_ADDED;
755 
756 	/* Initialize the controller mutex */
757 	mutex_init(&ahci_ctlp->ahcictl_mutex, NULL, MUTEX_DRIVER,
758 	    (void *)(uintptr_t)ahci_ctlp->ahcictl_intr_pri);
759 
760 	attach_state |= AHCI_ATTACH_STATE_MUTEX_INIT;
761 
762 	if (ahci_dma_prdt_number < AHCI_MIN_PRDT_NUMBER) {
763 		ahci_dma_prdt_number = AHCI_MIN_PRDT_NUMBER;
764 	} else if (ahci_dma_prdt_number > AHCI_MAX_PRDT_NUMBER) {
765 		ahci_dma_prdt_number = AHCI_MAX_PRDT_NUMBER;
766 	}
767 
768 	ahci_cmd_table_size = (sizeof (ahci_cmd_table_t) +
769 	    (ahci_dma_prdt_number - AHCI_PRDT_NUMBER) *
770 	    sizeof (ahci_prdt_item_t));
771 
772 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
773 	    "ahci_attach: ahci_dma_prdt_number set by user is 0x%x,"
774 	    " ahci_cmd_table_size is 0x%x",
775 	    ahci_dma_prdt_number, ahci_cmd_table_size);
776 
777 	if (ahci_dma_prdt_number != AHCI_PRDT_NUMBER)
778 		ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_sgllen =
779 		    ahci_dma_prdt_number;
780 
781 	ahci_ctlp->ahcictl_buffer_dma_attr = buffer_dma_attr;
782 	ahci_ctlp->ahcictl_rcvd_fis_dma_attr = rcvd_fis_dma_attr;
783 	ahci_ctlp->ahcictl_cmd_list_dma_attr = cmd_list_dma_attr;
784 	ahci_ctlp->ahcictl_cmd_table_dma_attr = cmd_table_dma_attr;
785 
786 	if ((ahci_buf_64bit_dma == B_FALSE) ||
787 	    (ahci_ctlp->ahcictl_cap & AHCI_CAP_BUF_32BIT_DMA)) {
788 		ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_addr_hi =
789 		    0xffffffffull;
790 	}
791 
792 	if ((ahci_commu_64bit_dma == B_FALSE) ||
793 	    (ahci_ctlp->ahcictl_cap & AHCI_CAP_COMMU_32BIT_DMA)) {
794 		ahci_ctlp->ahcictl_rcvd_fis_dma_attr.dma_attr_addr_hi =
795 		    0xffffffffull;
796 		ahci_ctlp->ahcictl_cmd_list_dma_attr.dma_attr_addr_hi =
797 		    0xffffffffull;
798 		ahci_ctlp->ahcictl_cmd_table_dma_attr.dma_attr_addr_hi =
799 		    0xffffffffull;
800 	}
801 
802 	/* Allocate the ports structure */
803 	status = ahci_alloc_ports_state(ahci_ctlp);
804 	if (status != AHCI_SUCCESS) {
805 		cmn_err(CE_WARN, "!ahci%d: Cannot allocate ports structure",
806 		    instance);
807 		goto err_out;
808 	}
809 
810 	attach_state |= AHCI_ATTACH_STATE_PORT_ALLOC;
811 
812 	/*
813 	 * Initialize the controller and ports.
814 	 */
815 	status = ahci_initialize_controller(ahci_ctlp);
816 	if (status != AHCI_SUCCESS) {
817 		cmn_err(CE_WARN, "!ahci%d: HBA initialization failed",
818 		    instance);
819 		goto err_out;
820 	}
821 
822 	attach_state |= AHCI_ATTACH_STATE_HW_INIT;
823 
824 	/* Start one thread to check packet timeouts */
825 	ahci_ctlp->ahcictl_timeout_id = timeout(
826 	    (void (*)(void *))ahci_watchdog_handler,
827 	    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
828 
829 	attach_state |= AHCI_ATTACH_STATE_TIMEOUT_ENABLED;
830 
831 	if (ahci_register_sata_hba_tran(ahci_ctlp, cap_status)) {
832 		cmn_err(CE_WARN, "!ahci%d: sata hba tran registration failed",
833 		    instance);
834 		goto err_out;
835 	}
836 
837 	ahci_ctlp->ahcictl_flags &= ~AHCI_ATTACH;
838 
839 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "ahci_attach success!", NULL);
840 
841 	return (DDI_SUCCESS);
842 
843 err_out:
844 	if (attach_state & AHCI_ATTACH_STATE_TIMEOUT_ENABLED) {
845 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
846 		(void) untimeout(ahci_ctlp->ahcictl_timeout_id);
847 		ahci_ctlp->ahcictl_timeout_id = 0;
848 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
849 	}
850 
851 	if (attach_state & AHCI_ATTACH_STATE_HW_INIT) {
852 		ahci_uninitialize_controller(ahci_ctlp);
853 	}
854 
855 	if (attach_state & AHCI_ATTACH_STATE_PORT_ALLOC) {
856 		ahci_dealloc_ports_state(ahci_ctlp);
857 	}
858 
859 	if (attach_state & AHCI_ATTACH_STATE_MUTEX_INIT) {
860 		mutex_destroy(&ahci_ctlp->ahcictl_mutex);
861 	}
862 
863 	if (attach_state & AHCI_ATTACH_STATE_INTR_ADDED) {
864 		ahci_rem_intrs(ahci_ctlp);
865 	}
866 
867 	if (attach_state & AHCI_ATTACH_STATE_PCICFG_SETUP) {
868 		pci_config_teardown(&ahci_ctlp->ahcictl_pci_conf_handle);
869 	}
870 
871 	if (attach_state & AHCI_ATTACH_STATE_REG_MAP) {
872 		ddi_regs_map_free(&ahci_ctlp->ahcictl_ahci_acc_handle);
873 	}
874 
875 	if (attach_state & AHCI_ATTACH_STATE_STATEP_ALLOC) {
876 		ddi_soft_state_free(ahci_statep, instance);
877 	}
878 
879 	return (DDI_FAILURE);
880 }
881 
882 /*
883  * The detach entry point for dev_ops.
884  */
885 static int
886 ahci_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
887 {
888 	ahci_ctl_t *ahci_ctlp;
889 	int instance;
890 	int ret;
891 
892 	instance = ddi_get_instance(dip);
893 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
894 
895 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_detach enter", NULL);
896 
897 	switch (cmd) {
898 	case DDI_DETACH:
899 
900 		/* disable the interrupts for an uninterrupted detach */
901 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
902 		ahci_disable_all_intrs(ahci_ctlp);
903 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
904 
905 		/* unregister from the sata framework. */
906 		ret = ahci_unregister_sata_hba_tran(ahci_ctlp);
907 		if (ret != AHCI_SUCCESS) {
908 			mutex_enter(&ahci_ctlp->ahcictl_mutex);
909 			ahci_enable_all_intrs(ahci_ctlp);
910 			mutex_exit(&ahci_ctlp->ahcictl_mutex);
911 			return (DDI_FAILURE);
912 		}
913 
914 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
915 
916 		/* stop the watchdog handler */
917 		(void) untimeout(ahci_ctlp->ahcictl_timeout_id);
918 		ahci_ctlp->ahcictl_timeout_id = 0;
919 
920 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
921 
922 		/* uninitialize the controller */
923 		ahci_uninitialize_controller(ahci_ctlp);
924 
925 		/* remove the interrupts */
926 		ahci_rem_intrs(ahci_ctlp);
927 
928 		/* deallocate the ports structures */
929 		ahci_dealloc_ports_state(ahci_ctlp);
930 
931 		/* destroy mutex */
932 		mutex_destroy(&ahci_ctlp->ahcictl_mutex);
933 
934 		/* teardown the pci config */
935 		pci_config_teardown(&ahci_ctlp->ahcictl_pci_conf_handle);
936 
937 		/* remove the reg maps. */
938 		ddi_regs_map_free(&ahci_ctlp->ahcictl_ahci_acc_handle);
939 
940 		/* free the soft state. */
941 		ddi_soft_state_free(ahci_statep, instance);
942 
943 		return (DDI_SUCCESS);
944 
945 	case DDI_SUSPEND:
946 
947 		/*
948 		 * The steps associated with suspension must include putting
949 		 * the underlying device into a quiescent state so that it
950 		 * will not generate interrupts or modify or access memory.
951 		 */
952 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
953 		if (ahci_ctlp->ahcictl_flags & AHCI_SUSPEND) {
954 			mutex_exit(&ahci_ctlp->ahcictl_mutex);
955 			return (DDI_SUCCESS);
956 		}
957 
958 		ahci_ctlp->ahcictl_flags |= AHCI_SUSPEND;
959 
960 		/* stop the watchdog handler */
961 		if (ahci_ctlp->ahcictl_timeout_id) {
962 			(void) untimeout(ahci_ctlp->ahcictl_timeout_id);
963 			ahci_ctlp->ahcictl_timeout_id = 0;
964 		}
965 
966 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
967 
968 		/*
969 		 * drain the taskq
970 		 */
971 		ahci_drain_ports_taskq(ahci_ctlp);
972 
973 		/*
974 		 * Disable the interrupts and stop all the ports.
975 		 */
976 		ahci_uninitialize_controller(ahci_ctlp);
977 
978 		return (DDI_SUCCESS);
979 
980 	default:
981 		return (DDI_FAILURE);
982 	}
983 }
984 
985 /*
986  * The info entry point for dev_ops.
987  *
988  */
989 static int
990 ahci_getinfo(dev_info_t *dip, ddi_info_cmd_t infocmd,
991 		    void *arg, void **result)
992 {
993 #ifndef __lock_lint
994 	_NOTE(ARGUNUSED(dip))
995 #endif /* __lock_lint */
996 
997 	ahci_ctl_t *ahci_ctlp;
998 	int instance;
999 	dev_t dev;
1000 
1001 	dev = (dev_t)arg;
1002 	instance = getminor(dev);
1003 
1004 	switch (infocmd) {
1005 		case DDI_INFO_DEVT2DEVINFO:
1006 			ahci_ctlp = ddi_get_soft_state(ahci_statep,  instance);
1007 			if (ahci_ctlp != NULL) {
1008 				*result = ahci_ctlp->ahcictl_dip;
1009 				return (DDI_SUCCESS);
1010 			} else {
1011 				*result = NULL;
1012 				return (DDI_FAILURE);
1013 			}
1014 		case DDI_INFO_DEVT2INSTANCE:
1015 			*(int *)result = instance;
1016 			break;
1017 		default:
1018 			break;
1019 	}
1020 
1021 	return (DDI_SUCCESS);
1022 }
1023 
1024 /*
1025  * Registers the ahci with sata framework.
1026  */
1027 static int
1028 ahci_register_sata_hba_tran(ahci_ctl_t *ahci_ctlp, uint32_t cap_status)
1029 {
1030 	struct 	sata_hba_tran	*sata_hba_tran;
1031 
1032 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
1033 	    "ahci_register_sata_hba_tran enter", NULL);
1034 
1035 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
1036 
1037 	/* Allocate memory for the sata_hba_tran  */
1038 	sata_hba_tran = kmem_zalloc(sizeof (sata_hba_tran_t), KM_SLEEP);
1039 
1040 	sata_hba_tran->sata_tran_hba_rev = SATA_TRAN_HBA_REV_2;
1041 	sata_hba_tran->sata_tran_hba_dip = ahci_ctlp->ahcictl_dip;
1042 	sata_hba_tran->sata_tran_hba_dma_attr =
1043 	    &ahci_ctlp->ahcictl_buffer_dma_attr;
1044 
1045 	/* Report the number of implemented ports */
1046 	sata_hba_tran->sata_tran_hba_num_cports =
1047 	    ahci_ctlp->ahcictl_num_implemented_ports;
1048 
1049 	/* Support ATAPI device */
1050 	sata_hba_tran->sata_tran_hba_features_support = SATA_CTLF_ATAPI;
1051 
1052 	/* Get the data transfer capability for PIO command by the HBA */
1053 	if (cap_status & AHCI_HBA_CAP_PMD) {
1054 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_PIO_MDRQ;
1055 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "HBA supports multiple "
1056 		    "DRQ block data transfer for PIO command protocol", NULL);
1057 	}
1058 
1059 	/*
1060 	 * According to the AHCI spec, the ATA/ATAPI-7 queued feature set
1061 	 * is not supported by AHCI (including the READ QUEUED (EXT), WRITE
1062 	 * QUEUED (EXT), and SERVICE commands). Queued operations are
1063 	 * supported in AHCI using the READ FPDMA QUEUED and WRITE FPDMA
1064 	 * QUEUED commands when the HBA and device support native command
1065 	 * queuing(NCQ).
1066 	 *
1067 	 * SATA_CTLF_NCQ will be set to sata_tran_hba_features_support if the
1068 	 * CAP register of the HBA indicates NCQ is supported.
1069 	 *
1070 	 * SATA_CTLF_NCQ cannot be set if AHCI_CAP_NO_MCMDLIST_NONQUEUE is
1071 	 * set because the previous register content of PxCI can be re-written
1072 	 * in the register write.
1073 	 */
1074 	if ((cap_status & AHCI_HBA_CAP_SNCQ) &&
1075 	    !(ahci_ctlp->ahcictl_cap & AHCI_CAP_NO_MCMDLIST_NONQUEUE)) {
1076 		sata_hba_tran->sata_tran_hba_features_support |= SATA_CTLF_NCQ;
1077 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_NCQ;
1078 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "HBA supports Native "
1079 		    "Command Queuing", NULL);
1080 	}
1081 
1082 	/* Report the number of command slots */
1083 	sata_hba_tran->sata_tran_hba_qdepth = ahci_ctlp->ahcictl_num_cmd_slots;
1084 
1085 	sata_hba_tran->sata_tran_probe_port = ahci_tran_probe_port;
1086 	sata_hba_tran->sata_tran_start = ahci_tran_start;
1087 	sata_hba_tran->sata_tran_abort = ahci_tran_abort;
1088 	sata_hba_tran->sata_tran_reset_dport = ahci_tran_reset_dport;
1089 	sata_hba_tran->sata_tran_hotplug_ops = &ahci_tran_hotplug_ops;
1090 #ifdef __lock_lint
1091 	sata_hba_tran->sata_tran_selftest = ahci_selftest;
1092 #endif
1093 	/*
1094 	 * When SATA framework adds support for pwrmgt the
1095 	 * pwrmgt_ops needs to be updated
1096 	 */
1097 	sata_hba_tran->sata_tran_pwrmgt_ops = NULL;
1098 	sata_hba_tran->sata_tran_ioctl = NULL;
1099 
1100 	ahci_ctlp->ahcictl_sata_hba_tran = sata_hba_tran;
1101 
1102 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
1103 
1104 	/* Attach it to SATA framework */
1105 	if (sata_hba_attach(ahci_ctlp->ahcictl_dip, sata_hba_tran, DDI_ATTACH)
1106 	    != DDI_SUCCESS) {
1107 		kmem_free((void *)sata_hba_tran, sizeof (sata_hba_tran_t));
1108 		mutex_enter(&ahci_ctlp->ahcictl_mutex);
1109 		ahci_ctlp->ahcictl_sata_hba_tran = NULL;
1110 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
1111 		return (AHCI_FAILURE);
1112 	}
1113 
1114 	return (AHCI_SUCCESS);
1115 }
1116 
1117 /*
1118  * Unregisters the ahci with sata framework.
1119  */
1120 static int
1121 ahci_unregister_sata_hba_tran(ahci_ctl_t *ahci_ctlp)
1122 {
1123 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1124 	    "ahci_unregister_sata_hba_tran enter", NULL);
1125 
1126 	/* Detach from the SATA framework. */
1127 	if (sata_hba_detach(ahci_ctlp->ahcictl_dip, DDI_DETACH) !=
1128 	    DDI_SUCCESS) {
1129 		return (AHCI_FAILURE);
1130 	}
1131 
1132 	/* Deallocate sata_hba_tran. */
1133 	kmem_free((void *)ahci_ctlp->ahcictl_sata_hba_tran,
1134 	    sizeof (sata_hba_tran_t));
1135 
1136 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
1137 	ahci_ctlp->ahcictl_sata_hba_tran = NULL;
1138 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
1139 
1140 	return (AHCI_SUCCESS);
1141 }
1142 
1143 /*
1144  * ahci_tran_probe_port is called by SATA framework. It returns port state,
1145  * port status registers and an attached device type via sata_device
1146  * structure.
1147  *
1148  * We return the cached information from a previous hardware probe. The
1149  * actual hardware probing itself was done either from within
1150  * ahci_initialize_controller() during the driver attach or from a phy
1151  * ready change interrupt handler.
1152  */
1153 static int
1154 ahci_tran_probe_port(dev_info_t *dip, sata_device_t *sd)
1155 {
1156 	ahci_ctl_t *ahci_ctlp;
1157 	ahci_port_t *ahci_portp;
1158 	uint8_t	cport = sd->satadev_addr.cport;
1159 	uint8_t pmport = sd->satadev_addr.pmport;
1160 	uint8_t qual = sd->satadev_addr.qual;
1161 	uint8_t	device_type;
1162 	uint32_t port_state;
1163 	uint8_t port;
1164 
1165 	ahci_ctlp = ddi_get_soft_state(ahci_statep, ddi_get_instance(dip));
1166 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
1167 
1168 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1169 	    "ahci_tran_probe_port enter: cport: %d, "
1170 	    "pmport: %d, qual: %d", cport, pmport, qual);
1171 
1172 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
1173 
1174 	mutex_enter(&ahci_portp->ahciport_mutex);
1175 
1176 	port_state = ahci_portp->ahciport_port_state;
1177 	switch (port_state) {
1178 
1179 	case SATA_PSTATE_FAILED:
1180 		sd->satadev_state = SATA_PSTATE_FAILED;
1181 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1182 		    "ahci_tran_probe_port: port %d PORT FAILED", port);
1183 		goto out;
1184 
1185 	case SATA_PSTATE_SHUTDOWN:
1186 		sd->satadev_state = SATA_PSTATE_SHUTDOWN;
1187 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1188 		    "ahci_tran_probe_port: port %d PORT SHUTDOWN", port);
1189 		goto out;
1190 
1191 	case SATA_PSTATE_PWROFF:
1192 		sd->satadev_state = SATA_PSTATE_PWROFF;
1193 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1194 		    "ahci_tran_probe_port: port %d PORT PWROFF", port);
1195 		goto out;
1196 
1197 	case SATA_PSTATE_PWRON:
1198 		sd->satadev_state = SATA_PSTATE_PWRON;
1199 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1200 		    "ahci_tran_probe_port: port %d PORT PWRON", port);
1201 		break;
1202 
1203 	default:
1204 		sd->satadev_state = port_state;
1205 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1206 		    "ahci_tran_probe_port: port %d PORT NORMAL %x",
1207 		    port, port_state);
1208 		break;
1209 	}
1210 
1211 	device_type = ahci_portp->ahciport_device_type;
1212 
1213 	switch (device_type) {
1214 
1215 	case SATA_DTYPE_ATADISK:
1216 		sd->satadev_type = SATA_DTYPE_ATADISK;
1217 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1218 		    "ahci_tran_probe_port: port %d DISK found", port);
1219 		break;
1220 
1221 	case SATA_DTYPE_ATAPI:
1222 		/*
1223 		 * HBA driver only knows it's an ATAPI device, and don't know
1224 		 * it's CD/DVD, tape or ATAPI disk because the ATAPI device
1225 		 * type need to be determined by checking IDENTIFY PACKET
1226 		 * DEVICE data
1227 		 */
1228 		sd->satadev_type = SATA_DTYPE_ATAPI;
1229 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1230 		    "ahci_tran_probe_port: port %d ATAPI found", port);
1231 		break;
1232 
1233 	case SATA_DTYPE_PMULT:
1234 		sd->satadev_type = SATA_DTYPE_PMULT;
1235 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1236 		    "ahci_tran_probe_port: port %d Port Multiplier found",
1237 		    port);
1238 		break;
1239 
1240 	case SATA_DTYPE_UNKNOWN:
1241 		sd->satadev_type = SATA_DTYPE_UNKNOWN;
1242 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1243 		    "ahci_tran_probe_port: port %d Unknown device found", port);
1244 		break;
1245 
1246 	default:
1247 		/* we don't support any other device types */
1248 		sd->satadev_type = SATA_DTYPE_NONE;
1249 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1250 		    "ahci_tran_probe_port: port %d No device found", port);
1251 		break;
1252 	}
1253 
1254 out:
1255 	ahci_update_sata_registers(ahci_ctlp, port, sd);
1256 	mutex_exit(&ahci_portp->ahciport_mutex);
1257 
1258 	return (SATA_SUCCESS);
1259 }
1260 
1261 /*
1262  * There are four operation modes in sata framework:
1263  * SATA_OPMODE_INTERRUPTS
1264  * SATA_OPMODE_POLLING
1265  * SATA_OPMODE_ASYNCH
1266  * SATA_OPMODE_SYNCH
1267  *
1268  * Their combined meanings as following:
1269  *
1270  * SATA_OPMODE_SYNCH
1271  * The command has to be completed before sata_tran_start functions returns.
1272  * Either interrupts or polling could be used - it's up to the driver.
1273  * Mode used currently for internal, sata-module initiated operations.
1274  *
1275  * SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS
1276  * It is the same as the one above.
1277  *
1278  * SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING
1279  * The command has to be completed before sata_tran_start function returns.
1280  * No interrupt used, polling only. This should be the mode used for scsi
1281  * packets with FLAG_NOINTR.
1282  *
1283  * SATA_OPMODE_ASYNCH | SATA_OPMODE_INTERRUPTS
1284  * The command may be queued (callback function specified). Interrupts could
1285  * be used. It's normal operation mode.
1286  */
1287 /*
1288  * Called by sata framework to transport a sata packet down stream.
1289  */
1290 static int
1291 ahci_tran_start(dev_info_t *dip, sata_pkt_t *spkt)
1292 {
1293 	ahci_ctl_t *ahci_ctlp;
1294 	ahci_port_t *ahci_portp;
1295 	uint8_t	cport = spkt->satapkt_device.satadev_addr.cport;
1296 	uint8_t port;
1297 
1298 	ahci_ctlp = ddi_get_soft_state(ahci_statep, ddi_get_instance(dip));
1299 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
1300 
1301 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1302 	    "ahci_tran_start enter: cport %d satapkt 0x%p",
1303 	    cport, (void *)spkt);
1304 
1305 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
1306 
1307 	mutex_enter(&ahci_portp->ahciport_mutex);
1308 
1309 	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED |
1310 	    ahci_portp->ahciport_port_state & SATA_PSTATE_SHUTDOWN |
1311 	    ahci_portp->ahciport_port_state & SATA_PSTATE_PWROFF) {
1312 		/*
1313 		 * In case the targer driver would send the packet before
1314 		 * sata framework can have the opportunity to process those
1315 		 * event reports.
1316 		 */
1317 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1318 		spkt->satapkt_device.satadev_state =
1319 		    ahci_portp->ahciport_port_state;
1320 		ahci_update_sata_registers(ahci_ctlp, port,
1321 		    &spkt->satapkt_device);
1322 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1323 		    "ahci_tran_start returning PORT_ERROR while "
1324 		    "port in FAILED/SHUTDOWN/PWROFF state: "
1325 		    "port: %d", port);
1326 		mutex_exit(&ahci_portp->ahciport_mutex);
1327 		return (SATA_TRAN_PORT_ERROR);
1328 	}
1329 
1330 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
1331 		/*
1332 		 * ahci_intr_phyrdy_change() may have rendered it to
1333 		 * SATA_DTYPE_NONE.
1334 		 */
1335 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
1336 		spkt->satapkt_device.satadev_type = SATA_DTYPE_NONE;
1337 		spkt->satapkt_device.satadev_state =
1338 		    ahci_portp->ahciport_port_state;
1339 		ahci_update_sata_registers(ahci_ctlp, port,
1340 		    &spkt->satapkt_device);
1341 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1342 		    "ahci_tran_start returning PORT_ERROR while "
1343 		    "no device attached: port: %d", port);
1344 		mutex_exit(&ahci_portp->ahciport_mutex);
1345 		return (SATA_TRAN_PORT_ERROR);
1346 	}
1347 
1348 	/*
1349 	 * SATA HBA driver should remember that a device was reset and it
1350 	 * is supposed to reject any packets which do not specify either
1351 	 * SATA_IGNORE_DEV_RESET_STATE or SATA_CLEAR_DEV_RESET_STATE.
1352 	 *
1353 	 * This is to prevent a race condition when a device was arbitrarily
1354 	 * reset by the HBA driver (and lost it's setting) and a target
1355 	 * driver sending some commands to a device before the sata framework
1356 	 * has a chance to restore the device setting (such as cache enable/
1357 	 * disable or other resettable stuff).
1358 	 */
1359 	if (spkt->satapkt_cmd.satacmd_flags.sata_clear_dev_reset) {
1360 		ahci_portp->ahciport_reset_in_progress = 0;
1361 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1362 		    "ahci_tran_start clearing the "
1363 		    "reset_in_progress for port: %d", port);
1364 	}
1365 
1366 	if (ahci_portp->ahciport_reset_in_progress &&
1367 	    ! spkt->satapkt_cmd.satacmd_flags.sata_ignore_dev_reset &&
1368 	    ! ddi_in_panic()) {
1369 		spkt->satapkt_reason = SATA_PKT_BUSY;
1370 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1371 		    "ahci_tran_start returning BUSY while "
1372 		    "reset in progress: port: %d", port);
1373 		mutex_exit(&ahci_portp->ahciport_mutex);
1374 		return (SATA_TRAN_BUSY);
1375 	}
1376 
1377 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
1378 		spkt->satapkt_reason = SATA_PKT_BUSY;
1379 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1380 		    "ahci_tran_start returning BUSY while "
1381 		    "mopping in progress: port: %d", port);
1382 		mutex_exit(&ahci_portp->ahciport_mutex);
1383 		return (SATA_TRAN_BUSY);
1384 	}
1385 
1386 	if (spkt->satapkt_op_mode &
1387 	    (SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING)) {
1388 		/*
1389 		 * If a SYNC command to be executed in interrupt context,
1390 		 * bounce it back to sata module.
1391 		 */
1392 		if (!(spkt->satapkt_op_mode & SATA_OPMODE_POLLING) &&
1393 		    servicing_interrupt()) {
1394 			spkt->satapkt_reason = SATA_PKT_BUSY;
1395 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1396 			    "ahci_tran_start returning BUSY while "
1397 			    "sending SYNC mode under interrupt context: "
1398 			    "port : %d", port);
1399 			mutex_exit(&ahci_portp->ahciport_mutex);
1400 			return (SATA_TRAN_BUSY);
1401 		}
1402 
1403 		/* We need to do the sync start now */
1404 		if (ahci_do_sync_start(ahci_ctlp, ahci_portp, port,
1405 		    spkt) == AHCI_FAILURE) {
1406 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_tran_start "
1407 			    "return QUEUE_FULL: port %d", port);
1408 			mutex_exit(&ahci_portp->ahciport_mutex);
1409 			return (SATA_TRAN_QUEUE_FULL);
1410 		}
1411 	} else {
1412 		/* Async start, using interrupt */
1413 		if (ahci_deliver_satapkt(ahci_ctlp, ahci_portp, port, spkt)
1414 		    == AHCI_FAILURE) {
1415 			spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
1416 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_tran_start "
1417 			    "returning QUEUE_FULL: port %d", port);
1418 			mutex_exit(&ahci_portp->ahciport_mutex);
1419 			return (SATA_TRAN_QUEUE_FULL);
1420 		}
1421 	}
1422 
1423 	AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_tran_start "
1424 	    "sata tran accepted: port %d", port);
1425 
1426 	mutex_exit(&ahci_portp->ahciport_mutex);
1427 	return (SATA_TRAN_ACCEPTED);
1428 }
1429 
1430 /*
1431  * SATA_OPMODE_SYNCH flag is set
1432  *
1433  * If SATA_OPMODE_POLLING flag is set, then we must poll the command
1434  * without interrupt, otherwise we can still use the interrupt.
1435  *
1436  * WARNING!!! ahciport_mutex should be acquired before the function
1437  * is called.
1438  */
1439 static int
1440 ahci_do_sync_start(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
1441     uint8_t port, sata_pkt_t *spkt)
1442 {
1443 	int pkt_timeout_ticks;
1444 	uint32_t timeout_tags;
1445 	int rval;
1446 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
1447 
1448 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_do_sync_start enter: "
1449 	    "port %d spkt 0x%p", port, spkt);
1450 
1451 	if (spkt->satapkt_op_mode & SATA_OPMODE_POLLING) {
1452 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_POLLING;
1453 		if ((rval = ahci_deliver_satapkt(ahci_ctlp, ahci_portp,
1454 		    port, spkt)) == AHCI_FAILURE) {
1455 			ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_POLLING;
1456 			return (rval);
1457 		}
1458 
1459 		pkt_timeout_ticks =
1460 		    drv_usectohz((clock_t)spkt->satapkt_time * 1000000);
1461 
1462 		while (spkt->satapkt_reason == SATA_PKT_BUSY) {
1463 			mutex_exit(&ahci_portp->ahciport_mutex);
1464 
1465 			/* Simulate the interrupt */
1466 			ahci_port_intr(ahci_ctlp, ahci_portp, port);
1467 
1468 			drv_usecwait(AHCI_1MS_USECS);
1469 
1470 			mutex_enter(&ahci_portp->ahciport_mutex);
1471 			pkt_timeout_ticks -= AHCI_1MS_TICKS;
1472 			if (pkt_timeout_ticks < 0) {
1473 				cmn_err(CE_WARN, "!ahci%d: ahci_do_sync_start "
1474 				    "port %d satapkt 0x%p timed out\n",
1475 				    instance, port, (void *)spkt);
1476 				timeout_tags = (0x1 << rval);
1477 				mutex_exit(&ahci_portp->ahciport_mutex);
1478 				ahci_timeout_pkts(ahci_ctlp, ahci_portp,
1479 				    port, timeout_tags);
1480 				mutex_enter(&ahci_portp->ahciport_mutex);
1481 			}
1482 		}
1483 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_POLLING;
1484 		return (AHCI_SUCCESS);
1485 
1486 	} else {
1487 		if ((rval = ahci_deliver_satapkt(ahci_ctlp, ahci_portp,
1488 		    port, spkt)) == AHCI_FAILURE)
1489 			return (rval);
1490 
1491 #if AHCI_DEBUG
1492 		/*
1493 		 * Note that the driver always uses the slot 0 to deliver
1494 		 * REQUEST SENSE or READ LOG EXT command
1495 		 */
1496 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
1497 			ASSERT(rval == 0);
1498 #endif
1499 
1500 		while (spkt->satapkt_reason == SATA_PKT_BUSY)
1501 			cv_wait(&ahci_portp->ahciport_cv,
1502 			    &ahci_portp->ahciport_mutex);
1503 
1504 		return (AHCI_SUCCESS);
1505 	}
1506 }
1507 
1508 #define	SENDUP_PACKET(ahci_portp, satapkt, reason)			\
1509 	if (satapkt) {							\
1510 		satapkt->satapkt_reason = reason;			\
1511 		/*							\
1512 		 * We set the satapkt_reason in both sync and		\
1513 		 * non-sync cases.					\
1514 		 */							\
1515 	}								\
1516 	if (satapkt &&							\
1517 	    ! (satapkt->satapkt_op_mode & SATA_OPMODE_SYNCH) &&		\
1518 	    satapkt->satapkt_comp) {					\
1519 		mutex_exit(&ahci_portp->ahciport_mutex);		\
1520 		(*satapkt->satapkt_comp)(satapkt);			\
1521 		mutex_enter(&ahci_portp->ahciport_mutex);		\
1522 	} else {							\
1523 		if (satapkt &&						\
1524 		    (satapkt->satapkt_op_mode & SATA_OPMODE_SYNCH) &&	\
1525 		    ! (satapkt->satapkt_op_mode & SATA_OPMODE_POLLING))	\
1526 			cv_broadcast(&ahci_portp->ahciport_cv);		\
1527 	}
1528 
1529 /*
1530  * Searches for and claims a free command slot.
1531  *
1532  * Returns:
1533  *
1534  * AHCI_FAILURE if failed
1535  *	1. if no empty slot left
1536  *	2. non-queued command requested while queued command(s) is outstanding
1537  *	3. queued command requested whild non-queued command(s) is outstanding
1538  *	4. HBA doesn't support multiple-use of command list while already a
1539  *	non-queued command is oustanding
1540  *
1541  * claimed slot number if succeeded
1542  *
1543  * NOTE: it will always return slot 0 during error recovery process for
1544  * REQUEST SENSE or READ LOG EXT command to simplify the algorithm.
1545  *
1546  * WARNING!!! ahciport_mutex should be acquired before the function
1547  * is called.
1548  */
1549 static int
1550 ahci_claim_free_slot(ahci_ctl_t *ahci_ctlp,
1551     ahci_port_t *ahci_portp, int command_type)
1552 {
1553 	uint32_t free_slots;
1554 	int slot;
1555 
1556 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_claim_free_slot enter "
1557 	    "ahciport_pending_tags = 0x%x "
1558 	    "ahciport_pending_ncq_tags = 0x%x",
1559 	    ahci_portp->ahciport_pending_tags,
1560 	    ahci_portp->ahciport_pending_ncq_tags);
1561 
1562 	/*
1563 	 * According to the AHCI spec, system software is responsible to
1564 	 * ensure that queued and non-queued commands are not mixed in
1565 	 * the command list.
1566 	 */
1567 	if (command_type == AHCI_NON_NCQ_CMD) {
1568 		/* Non-NCQ command request */
1569 		if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
1570 			AHCIDBG(AHCIDBG_INFO|AHCIDBG_NCQ, ahci_ctlp,
1571 			    "ahci_claim_free_slot: there is still pending "
1572 			    "queued command(s) in the command list, "
1573 			    "so no available slot for the non-queued "
1574 			    "command", NULL);
1575 			return (AHCI_FAILURE);
1576 		}
1577 		if ((ahci_ctlp->ahcictl_cap & AHCI_CAP_NO_MCMDLIST_NONQUEUE) &&
1578 		    NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
1579 			AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
1580 			    "ahci_claim_free_slot: HBA cannot support multiple-"
1581 			    "use of the command list for non-queued commands",
1582 			    NULL);
1583 			return (AHCI_FAILURE);
1584 		}
1585 		free_slots = (~ahci_portp->ahciport_pending_tags) &
1586 		    AHCI_SLOT_MASK(ahci_ctlp);
1587 	} else if (command_type == AHCI_NCQ_CMD) {
1588 		/* NCQ command request */
1589 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
1590 			AHCIDBG(AHCIDBG_INFO|AHCIDBG_NCQ, ahci_ctlp,
1591 			    "ahci_claim_free_slot: there is still pending "
1592 			    "non-queued command(s) in the command list, "
1593 			    "so no available slot for the queued command",
1594 			    NULL);
1595 			return (AHCI_FAILURE);
1596 		}
1597 		free_slots = (~ahci_portp->ahciport_pending_ncq_tags) &
1598 		    AHCI_NCQ_SLOT_MASK(ahci_portp);
1599 	} else if (command_type == AHCI_ERR_RETRI_CMD) {
1600 		/* Error retrieval command request */
1601 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
1602 		    "ahci_claim_free_slot: slot 0 is allocated for REQUEST "
1603 		    "SENSE or READ LOG EXT command", NULL);
1604 		slot = 0;
1605 		goto out;
1606 	}
1607 
1608 	slot = ddi_ffs(free_slots) - 1;
1609 	if (slot == -1) {
1610 		AHCIDBG(AHCIDBG_VERBOSE, ahci_ctlp,
1611 		    "ahci_claim_free_slot: no empty slots", NULL);
1612 		return (AHCI_FAILURE);
1613 	}
1614 
1615 	/*
1616 	 * According to the AHCI spec, to allow a simple mechanism for the
1617 	 * HBA to map command list slots to queue entries, software must
1618 	 * match the tag number it uses to the slot it is placing the command
1619 	 * in. For example, if a queued command is placed in slot 5, the tag
1620 	 * for that command must be 5.
1621 	 */
1622 	if (command_type == AHCI_NCQ_CMD) {
1623 		ahci_portp->ahciport_pending_ncq_tags |= (0x1 << slot);
1624 	}
1625 
1626 	ahci_portp->ahciport_pending_tags |= (0x1 << slot);
1627 
1628 out:
1629 	AHCIDBG(AHCIDBG_VERBOSE, ahci_ctlp,
1630 	    "ahci_claim_free_slot: found slot: 0x%x", slot);
1631 
1632 	return (slot);
1633 }
1634 
1635 /*
1636  * Builds the Command Table for the sata packet and delivers it to controller.
1637  *
1638  * Returns:
1639  * 	slot number if we can obtain a slot successfully
1640  *	otherwise, return AHCI_FAILURE
1641  *
1642  * WARNING!!! ahciport_mutex should be acquired before the function is called.
1643  */
1644 static int
1645 ahci_deliver_satapkt(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
1646     uint8_t port, sata_pkt_t *spkt)
1647 {
1648 	int cmd_slot;
1649 	sata_cmd_t *scmd;
1650 	ahci_fis_h2d_register_t *h2d_register_fisp;
1651 	ahci_cmd_table_t *cmd_table;
1652 	ahci_cmd_header_t *cmd_header;
1653 	int ncookies;
1654 	int i;
1655 	int command_type = AHCI_NON_NCQ_CMD;
1656 	int ncq_qdepth;
1657 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
1658 #if AHCI_DEBUG
1659 	uint32_t *ptr;
1660 	uint8_t *ptr2;
1661 #endif
1662 
1663 	spkt->satapkt_reason = SATA_PKT_BUSY;
1664 
1665 	scmd = &spkt->satapkt_cmd;
1666 
1667 	/* Check if the command is a NCQ command */
1668 	if (scmd->satacmd_cmd_reg == SATAC_READ_FPDMA_QUEUED ||
1669 	    scmd->satacmd_cmd_reg == SATAC_WRITE_FPDMA_QUEUED) {
1670 		command_type = AHCI_NCQ_CMD;
1671 
1672 		/*
1673 		 * When NCQ is support, system software must determine the
1674 		 * maximum tag allowed by the device and the HBA, and it
1675 		 * must use a value not beyond of the lower bound of the two.
1676 		 *
1677 		 * Sata module is going to calculate the qdepth and send
1678 		 * down to HBA driver via sata_cmd.
1679 		 */
1680 		ncq_qdepth = scmd->satacmd_flags.sata_max_queue_depth + 1;
1681 
1682 		/*
1683 		 * At the moment, the driver doesn't support the dynamic
1684 		 * setting of the maximum ncq depth, and the value can be
1685 		 * set either during the attach or after hot-plug insertion.
1686 		 */
1687 		if (ahci_portp->ahciport_max_ncq_tags == 0) {
1688 			ahci_portp->ahciport_max_ncq_tags = ncq_qdepth;
1689 			AHCIDBG(AHCIDBG_NCQ, ahci_ctlp,
1690 			    "ahci_deliver_satapkt: port %d the max tags for "
1691 			    "NCQ command is %d", port, ncq_qdepth);
1692 		} else {
1693 			if (ncq_qdepth != ahci_portp->ahciport_max_ncq_tags) {
1694 				cmn_err(CE_WARN, "!ahci%d: ahci_deliver_satapkt"
1695 				    " port %d the max tag for NCQ command is "
1696 				    "requested to change from %d to %d, at the"
1697 				    " moment the driver doesn't support the "
1698 				    "dynamic change so it's going to "
1699 				    "still use the previous tag value",
1700 				    instance, port,
1701 				    ahci_portp->ahciport_max_ncq_tags,
1702 				    ncq_qdepth);
1703 			}
1704 		}
1705 	}
1706 
1707 	/* Check if the command is an error retrieval command */
1708 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
1709 		command_type = AHCI_ERR_RETRI_CMD;
1710 
1711 	/* Check if there is an empty command slot */
1712 	cmd_slot = ahci_claim_free_slot(ahci_ctlp, ahci_portp, command_type);
1713 	if (cmd_slot == AHCI_FAILURE) {
1714 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "no free command slot", NULL);
1715 		return (AHCI_FAILURE);
1716 	}
1717 
1718 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INFO, ahci_ctlp,
1719 	    "ahci_deliver_satapkt enter: cmd_reg: 0x%x, cmd_slot: 0x%x, "
1720 	    "port: %d, satapkt: 0x%p", scmd->satacmd_cmd_reg,
1721 	    cmd_slot, port, (void *)spkt);
1722 
1723 	cmd_table = ahci_portp->ahciport_cmd_tables[cmd_slot];
1724 	bzero((void *)cmd_table, ahci_cmd_table_size);
1725 
1726 	/* For data transfer operations, it is the H2D Register FIS */
1727 	h2d_register_fisp =
1728 	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
1729 
1730 	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
1731 	if ((spkt->satapkt_device.satadev_addr.qual == SATA_ADDR_PMPORT) ||
1732 	    (spkt->satapkt_device.satadev_addr.qual == SATA_ADDR_DPMPORT)) {
1733 		SET_FIS_PMP(h2d_register_fisp,
1734 		    spkt->satapkt_device.satadev_addr.pmport);
1735 	}
1736 
1737 	SET_FIS_CDMDEVCTL(h2d_register_fisp, 1);
1738 	SET_FIS_COMMAND(h2d_register_fisp, scmd->satacmd_cmd_reg);
1739 	SET_FIS_FEATURES(h2d_register_fisp, scmd->satacmd_features_reg);
1740 	SET_FIS_SECTOR_COUNT(h2d_register_fisp, scmd->satacmd_sec_count_lsb);
1741 
1742 	switch (scmd->satacmd_addr_type) {
1743 
1744 	case 0:
1745 		/*
1746 		 * satacmd_addr_type will be 0 for the commands below:
1747 		 * 	ATAPI command
1748 		 * 	SATAC_IDLE_IM
1749 		 * 	SATAC_STANDBY_IM
1750 		 * 	SATAC_DOWNLOAD_MICROCODE
1751 		 * 	SATAC_FLUSH_CACHE
1752 		 * 	SATAC_SET_FEATURES
1753 		 * 	SATAC_SMART
1754 		 * 	SATAC_ID_PACKET_DEVICE
1755 		 * 	SATAC_ID_DEVICE
1756 		 */
1757 		/* FALLTHRU */
1758 
1759 	case ATA_ADDR_LBA:
1760 		/* FALLTHRU */
1761 
1762 	case ATA_ADDR_LBA28:
1763 		/* LBA[7:0] */
1764 		SET_FIS_SECTOR(h2d_register_fisp, scmd->satacmd_lba_low_lsb);
1765 
1766 		/* LBA[15:8] */
1767 		SET_FIS_CYL_LOW(h2d_register_fisp, scmd->satacmd_lba_mid_lsb);
1768 
1769 		/* LBA[23:16] */
1770 		SET_FIS_CYL_HI(h2d_register_fisp, scmd->satacmd_lba_high_lsb);
1771 
1772 		/* LBA [27:24] (also called dev_head) */
1773 		SET_FIS_DEV_HEAD(h2d_register_fisp, scmd->satacmd_device_reg);
1774 
1775 		break;
1776 
1777 	case ATA_ADDR_LBA48:
1778 		/* LBA[7:0] */
1779 		SET_FIS_SECTOR(h2d_register_fisp, scmd->satacmd_lba_low_lsb);
1780 
1781 		/* LBA[15:8] */
1782 		SET_FIS_CYL_LOW(h2d_register_fisp, scmd->satacmd_lba_mid_lsb);
1783 
1784 		/* LBA[23:16] */
1785 		SET_FIS_CYL_HI(h2d_register_fisp, scmd->satacmd_lba_high_lsb);
1786 
1787 		/* LBA [31:24] */
1788 		SET_FIS_SECTOR_EXP(h2d_register_fisp,
1789 		    scmd->satacmd_lba_low_msb);
1790 
1791 		/* LBA [39:32] */
1792 		SET_FIS_CYL_LOW_EXP(h2d_register_fisp,
1793 		    scmd->satacmd_lba_mid_msb);
1794 
1795 		/* LBA [47:40] */
1796 		SET_FIS_CYL_HI_EXP(h2d_register_fisp,
1797 		    scmd->satacmd_lba_high_msb);
1798 
1799 		/* Set dev_head */
1800 		SET_FIS_DEV_HEAD(h2d_register_fisp,
1801 		    scmd->satacmd_device_reg);
1802 
1803 		/* Set the extended sector count and features */
1804 		SET_FIS_SECTOR_COUNT_EXP(h2d_register_fisp,
1805 		    scmd->satacmd_sec_count_msb);
1806 		SET_FIS_FEATURES_EXP(h2d_register_fisp,
1807 		    scmd->satacmd_features_reg_ext);
1808 		break;
1809 	}
1810 
1811 	/*
1812 	 * For NCQ command (READ/WRITE FPDMA QUEUED), sector count 7:0 is
1813 	 * filled into features field, and sector count 8:15 is filled into
1814 	 * features (exp) field. TAG is filled into sector field.
1815 	 */
1816 	if (command_type == AHCI_NCQ_CMD) {
1817 		SET_FIS_FEATURES(h2d_register_fisp,
1818 		    scmd->satacmd_sec_count_lsb);
1819 		SET_FIS_FEATURES_EXP(h2d_register_fisp,
1820 		    scmd->satacmd_sec_count_msb);
1821 
1822 		SET_FIS_SECTOR_COUNT(h2d_register_fisp,
1823 		    (cmd_slot << SATA_TAG_QUEUING_SHIFT));
1824 	}
1825 
1826 	ncookies = scmd->satacmd_num_dma_cookies;
1827 	AHCIDBG(AHCIDBG_PRDT, ahci_ctlp,
1828 	    "ncookies = 0x%x, ahci_dma_prdt_number = 0x%x",
1829 	    ncookies, ahci_dma_prdt_number);
1830 
1831 	ASSERT(ncookies <= ahci_dma_prdt_number);
1832 	ahci_portp->ahciport_prd_bytecounts[cmd_slot] = 0;
1833 
1834 	/* *** now fill the scatter gather list ******* */
1835 	for (i = 0; i < ncookies; i++) {
1836 		cmd_table->ahcict_prdt[i].ahcipi_data_base_addr =
1837 		    scmd->satacmd_dma_cookie_list[i]._dmu._dmac_la[0];
1838 		cmd_table->ahcict_prdt[i].ahcipi_data_base_addr_upper =
1839 		    scmd->satacmd_dma_cookie_list[i]._dmu._dmac_la[1];
1840 		cmd_table->ahcict_prdt[i].ahcipi_descr_info =
1841 		    scmd->satacmd_dma_cookie_list[i].dmac_size - 1;
1842 		ahci_portp->ahciport_prd_bytecounts[cmd_slot] +=
1843 		    scmd->satacmd_dma_cookie_list[i].dmac_size;
1844 	}
1845 
1846 	AHCIDBG(AHCIDBG_PRDT, ahci_ctlp,
1847 	    "ahciport_prd_bytecounts 0x%x for cmd_slot 0x%x",
1848 	    ahci_portp->ahciport_prd_bytecounts[cmd_slot], cmd_slot);
1849 
1850 	/* The ACMD field is filled in for ATAPI command */
1851 	if (scmd->satacmd_cmd_reg == SATAC_PACKET) {
1852 		bcopy(scmd->satacmd_acdb, cmd_table->ahcict_atapi_cmd,
1853 		    SATA_ATAPI_MAX_CDB_LEN);
1854 	}
1855 
1856 	/* Set Command Header in Command List */
1857 	cmd_header = &ahci_portp->ahciport_cmd_list[cmd_slot];
1858 	BZERO_DESCR_INFO(cmd_header);
1859 	BZERO_PRD_BYTE_COUNT(cmd_header);
1860 
1861 	/* Set the number of entries in the PRD table */
1862 	SET_PRD_TABLE_LENGTH(cmd_header, ncookies);
1863 
1864 	/* Set the length of the command in the CFIS area */
1865 	SET_COMMAND_FIS_LENGTH(cmd_header, AHCI_H2D_REGISTER_FIS_LENGTH);
1866 
1867 	AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "command data direction is "
1868 	    "sata_data_direction = 0x%x",
1869 	    scmd->satacmd_flags.sata_data_direction);
1870 
1871 	/* Set A bit if it is an ATAPI command */
1872 	if (scmd->satacmd_cmd_reg == SATAC_PACKET)
1873 		SET_ATAPI(cmd_header, AHCI_CMDHEAD_ATAPI);
1874 
1875 	/* Set W bit if data is going to the device */
1876 	if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE)
1877 		SET_WRITE(cmd_header, AHCI_CMDHEAD_DATA_WRITE);
1878 
1879 	/*
1880 	 * Set the prefetchable bit - this bit is only valid if the PRDTL
1881 	 * field is non-zero or the ATAPI 'A' bit is set in the command
1882 	 * header. This bit cannot be set when using native command
1883 	 * queuing commands or when using FIS-based switching with a Port
1884 	 * multiplier.
1885 	 */
1886 	if (command_type != AHCI_NCQ_CMD)
1887 		SET_PREFETCHABLE(cmd_header, AHCI_CMDHEAD_PREFETCHABLE);
1888 
1889 	/* Now remember the sata packet in ahciport_slot_pkts[]. */
1890 	if (!ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
1891 		ahci_portp->ahciport_slot_pkts[cmd_slot] = spkt;
1892 
1893 	/*
1894 	 * We are overloading satapkt_hba_driver_private with
1895 	 * watched_cycle count.
1896 	 */
1897 	spkt->satapkt_hba_driver_private = (void *)(intptr_t)0;
1898 
1899 #if AHCI_DEBUG
1900 	if (ahci_debug_flags & AHCIDBG_ATACMD &&
1901 	    scmd->satacmd_cmd_reg != SATAC_PACKET ||
1902 	    ahci_debug_flags & AHCIDBG_ATAPICMD &&
1903 	    scmd->satacmd_cmd_reg == SATAC_PACKET) {
1904 
1905 		/* Dump the command header and table */
1906 		ahci_log(ahci_ctlp, CE_WARN, "\n");
1907 		ahci_log(ahci_ctlp, CE_WARN, "Command header&table for spkt "
1908 		    "0x%p cmd_reg 0x%x port %d", spkt,
1909 		    scmd->satacmd_cmd_reg, port);
1910 		ptr = (uint32_t *)cmd_header;
1911 		ahci_log(ahci_ctlp, CE_WARN,
1912 		    "  Command Header:%8x %8x %8x %8x",
1913 		    ptr[0], ptr[1], ptr[2], ptr[3]);
1914 
1915 		/* Dump the H2D register FIS */
1916 		ptr = (uint32_t *)h2d_register_fisp;
1917 		ahci_log(ahci_ctlp, CE_WARN,
1918 		    "  Command FIS:   %8x %8x %8x %8x",
1919 		    ptr[0], ptr[1], ptr[2], ptr[3]);
1920 
1921 		/* Dump the ACMD register FIS */
1922 		ptr2 = (uint8_t *)&(cmd_table->ahcict_atapi_cmd);
1923 		for (i = 0; i < SATA_ATAPI_MAX_CDB_LEN/8; i++)
1924 			if (ahci_debug_flags & AHCIDBG_ATAPICMD)
1925 				ahci_log(ahci_ctlp, CE_WARN,
1926 				    "  ATAPI command: %2x %2x %2x %2x "
1927 				    "%2x %2x %2x %2x",
1928 				    ptr2[8 * i], ptr2[8 * i + 1],
1929 				    ptr2[8 * i + 2], ptr2[8 * i + 3],
1930 				    ptr2[8 * i + 4], ptr2[8 * i + 5],
1931 				    ptr2[8 * i + 6], ptr2[8 * i + 7]);
1932 
1933 		/* Dump the PRDT */
1934 		for (i = 0; i < ncookies; i++) {
1935 			ptr = (uint32_t *)&(cmd_table->ahcict_prdt[i]);
1936 			ahci_log(ahci_ctlp, CE_WARN,
1937 			    "  Cookie %d:      %8x %8x %8x %8x",
1938 			    i, ptr[0], ptr[1], ptr[2], ptr[3]);
1939 		}
1940 	}
1941 #endif
1942 
1943 	(void) ddi_dma_sync(
1944 	    ahci_portp->ahciport_cmd_tables_dma_handle[cmd_slot],
1945 	    0,
1946 	    ahci_cmd_table_size,
1947 	    DDI_DMA_SYNC_FORDEV);
1948 
1949 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
1950 	    cmd_slot * sizeof (ahci_cmd_header_t),
1951 	    sizeof (ahci_cmd_header_t),
1952 	    DDI_DMA_SYNC_FORDEV);
1953 
1954 	/* Set the corresponding bit in the PxSACT.DS for queued command */
1955 	if (command_type == AHCI_NCQ_CMD) {
1956 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
1957 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port),
1958 		    (0x1 << cmd_slot));
1959 	}
1960 
1961 	/* Indicate to the HBA that a command is active. */
1962 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
1963 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
1964 	    (0x1 << cmd_slot));
1965 
1966 	AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_deliver_satapkt "
1967 	    "exit: port %d", port);
1968 
1969 	return (cmd_slot);
1970 }
1971 
1972 /*
1973  * Called by the sata framework to abort the previously sent packet(s).
1974  *
1975  * Reset device to abort commands.
1976  */
1977 static int
1978 ahci_tran_abort(dev_info_t *dip, sata_pkt_t *spkt, int flag)
1979 {
1980 	ahci_ctl_t *ahci_ctlp;
1981 	ahci_port_t *ahci_portp;
1982 	uint32_t slot_status = 0;
1983 	uint32_t aborted_tags = 0;
1984 	uint32_t finished_tags = 0;
1985 	uint8_t cport = spkt->satapkt_device.satadev_addr.cport;
1986 	uint8_t port;
1987 	int tmp_slot;
1988 	int instance = ddi_get_instance(dip);
1989 
1990 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
1991 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
1992 
1993 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
1994 	    "ahci_tran_abort enter: port %d", port);
1995 
1996 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
1997 	mutex_enter(&ahci_portp->ahciport_mutex);
1998 
1999 	/*
2000 	 * If AHCI_PORT_FLAG_MOPPING flag is set, it means all the pending
2001 	 * commands are being mopped, therefore there is nothing else to do
2002 	 */
2003 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2004 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
2005 		    "ahci_tran_abort: port %d is in "
2006 		    "mopping process, so just return directly ", port);
2007 		mutex_exit(&ahci_portp->ahciport_mutex);
2008 		return (SATA_SUCCESS);
2009 	}
2010 
2011 	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED |
2012 	    ahci_portp->ahciport_port_state & SATA_PSTATE_SHUTDOWN |
2013 	    ahci_portp->ahciport_port_state & SATA_PSTATE_PWROFF) {
2014 		/*
2015 		 * In case the targer driver would send the request before
2016 		 * sata framework can have the opportunity to process those
2017 		 * event reports.
2018 		 */
2019 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
2020 		spkt->satapkt_device.satadev_state =
2021 		    ahci_portp->ahciport_port_state;
2022 		ahci_update_sata_registers(ahci_ctlp, port,
2023 		    &spkt->satapkt_device);
2024 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2025 		    "ahci_tran_abort returning SATA_FAILURE while "
2026 		    "port in FAILED/SHUTDOWN/PWROFF state: "
2027 		    "port: %d", port);
2028 		mutex_exit(&ahci_portp->ahciport_mutex);
2029 		return (SATA_FAILURE);
2030 	}
2031 
2032 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
2033 		/*
2034 		 * ahci_intr_phyrdy_change() may have rendered it to
2035 		 * AHCI_PORT_TYPE_NODEV.
2036 		 */
2037 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
2038 		spkt->satapkt_device.satadev_type = SATA_DTYPE_NONE;
2039 		spkt->satapkt_device.satadev_state =
2040 		    ahci_portp->ahciport_port_state;
2041 		ahci_update_sata_registers(ahci_ctlp, port,
2042 		    &spkt->satapkt_device);
2043 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2044 		    "ahci_tran_abort returning SATA_FAILURE while "
2045 		    "no device attached: port: %d", port);
2046 		mutex_exit(&ahci_portp->ahciport_mutex);
2047 		return (SATA_FAILURE);
2048 	}
2049 
2050 	if (flag == SATA_ABORT_ALL_PACKETS) {
2051 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2052 			aborted_tags = ahci_portp->ahciport_pending_tags;
2053 		else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2054 			aborted_tags = ahci_portp->ahciport_pending_ncq_tags;
2055 
2056 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d abort all packets",
2057 		    instance, port);
2058 	} else {
2059 		aborted_tags = 0xffffffff;
2060 		/*
2061 		 * Aborting one specific packet, first search the
2062 		 * ahciport_slot_pkts[] list for matching spkt.
2063 		 */
2064 		for (tmp_slot = 0;
2065 		    tmp_slot < ahci_ctlp->ahcictl_num_cmd_slots; tmp_slot++) {
2066 			if (ahci_portp->ahciport_slot_pkts[tmp_slot] == spkt) {
2067 				aborted_tags = (0x1 << tmp_slot);
2068 				break;
2069 			}
2070 		}
2071 
2072 		if (aborted_tags == 0xffffffff) {
2073 			/* request packet is not on the pending list */
2074 			AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
2075 			    "Cannot find the aborting pkt 0x%p on the "
2076 			    "pending list", (void *)spkt);
2077 			ahci_update_sata_registers(ahci_ctlp, port,
2078 			    &spkt->satapkt_device);
2079 			mutex_exit(&ahci_portp->ahciport_mutex);
2080 			return (SATA_FAILURE);
2081 		}
2082 		cmn_err(CE_NOTE, "!ahci%d: ahci port %d abort satapkt 0x%p",
2083 		    instance, port, (void *)spkt);
2084 	}
2085 
2086 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2087 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2088 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2089 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2090 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2091 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2092 
2093 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2094 	ahci_portp->ahciport_mop_in_progress++;
2095 
2096 	/*
2097 	 * To abort the packet(s), first we are trying to clear PxCMD.ST
2098 	 * to stop the port, and if the port can be stopped
2099 	 * successfully with PxTFD.STS.BSY and PxTFD.STS.DRQ cleared to '0',
2100 	 * then we just send back the aborted packet(s) with ABORTED flag
2101 	 * and then restart the port by setting PxCMD.ST and PxCMD.FRE.
2102 	 * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then we
2103 	 * perform a COMRESET.
2104 	 */
2105 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp,
2106 	    ahci_portp, port, NULL, NULL);
2107 
2108 	/*
2109 	 * Compute which have finished and which need to be retried.
2110 	 *
2111 	 * The finished tags are ahciport_pending_tags/ahciport_pending_ncq_tags
2112 	 * minus the slot_status. The aborted_tags has to be deducted by
2113 	 * finished_tags since we can't possibly abort a tag which had finished
2114 	 * already.
2115 	 */
2116 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2117 		finished_tags = ahci_portp->ahciport_pending_tags &
2118 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2119 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2120 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2121 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2122 
2123 	aborted_tags &= ~finished_tags;
2124 
2125 	ahci_mop_commands(ahci_ctlp,
2126 	    ahci_portp,
2127 	    slot_status,
2128 	    0, /* failed tags */
2129 	    0, /* timeout tags */
2130 	    aborted_tags,
2131 	    0); /* reset tags */
2132 
2133 	ahci_update_sata_registers(ahci_ctlp, port, &spkt->satapkt_device);
2134 	mutex_exit(&ahci_portp->ahciport_mutex);
2135 
2136 	return (SATA_SUCCESS);
2137 }
2138 
2139 /*
2140  * Used to do device reset and reject all the pending packets on a device
2141  * during the reset operation.
2142  *
2143  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2144  */
2145 static int
2146 ahci_reset_device_reject_pkts(ahci_ctl_t *ahci_ctlp,
2147     ahci_port_t *ahci_portp, uint8_t port)
2148 {
2149 	uint32_t slot_status = 0;
2150 	uint32_t reset_tags = 0;
2151 	uint32_t finished_tags = 0;
2152 	sata_device_t sdevice;
2153 	int ret;
2154 
2155 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2156 	    "ahci_reset_device_reject_pkts on port: %d", port);
2157 
2158 	/*
2159 	 * If AHCI_PORT_FLAG_MOPPING flag is set, it means all the pending
2160 	 * commands are being mopped, therefore there is nothing else to do
2161 	 */
2162 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2163 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2164 		    "ahci_reset_device_reject_pkts: port %d is in "
2165 		    "mopping process, so return directly ", port);
2166 		return (SATA_SUCCESS);
2167 	}
2168 
2169 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2170 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2171 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2172 		reset_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2173 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2174 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2175 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2176 		reset_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2177 	}
2178 
2179 	if (ahci_software_reset(ahci_ctlp, ahci_portp, port)
2180 	    != AHCI_SUCCESS) {
2181 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2182 		    "Try to do a port reset after software "
2183 		    "reset failed", port);
2184 		ret = ahci_port_reset(ahci_ctlp, ahci_portp, port);
2185 		if (ret != AHCI_SUCCESS) {
2186 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2187 			    "ahci_reset_device_reject_pkts: port %d "
2188 			    "failed", port);
2189 			return (SATA_FAILURE);
2190 		}
2191 	}
2192 	/* Set the reset in progress flag */
2193 	ahci_portp->ahciport_reset_in_progress = 1;
2194 
2195 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2196 	ahci_portp->ahciport_mop_in_progress++;
2197 
2198 	/* Indicate to the framework that a reset has happened */
2199 	bzero((void *)&sdevice, sizeof (sata_device_t));
2200 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
2201 	sdevice.satadev_addr.pmport = 0;
2202 	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
2203 
2204 	sdevice.satadev_state = SATA_DSTATE_RESET |
2205 	    SATA_DSTATE_PWR_ACTIVE;
2206 	mutex_exit(&ahci_portp->ahciport_mutex);
2207 	sata_hba_event_notify(
2208 	    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
2209 	    &sdevice,
2210 	    SATA_EVNT_DEVICE_RESET);
2211 	mutex_enter(&ahci_portp->ahciport_mutex);
2212 
2213 	AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
2214 	    "port %d sending event up: SATA_EVNT_RESET", port);
2215 
2216 	/* Next try to mop the pending commands */
2217 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2218 		finished_tags = ahci_portp->ahciport_pending_tags &
2219 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2220 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2221 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2222 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2223 
2224 	reset_tags &= ~finished_tags;
2225 
2226 	ahci_mop_commands(ahci_ctlp,
2227 	    ahci_portp,
2228 	    slot_status,
2229 	    0, /* failed tags */
2230 	    0, /* timeout tags */
2231 	    0, /* aborted tags */
2232 	    reset_tags); /* reset tags */
2233 
2234 	return (SATA_SUCCESS);
2235 }
2236 
2237 /*
2238  * Used to do port reset and reject all the pending packets on a port during
2239  * the reset operation.
2240  *
2241  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2242  */
2243 static int
2244 ahci_reset_port_reject_pkts(ahci_ctl_t *ahci_ctlp,
2245     ahci_port_t *ahci_portp, uint8_t port)
2246 {
2247 	uint32_t slot_status = 0;
2248 	uint32_t reset_tags = 0;
2249 	uint32_t finished_tags = 0;
2250 
2251 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2252 	    "ahci_reset_port_reject_pkts on port: %d", port);
2253 
2254 	/*
2255 	 * If AHCI_PORT_FLAG_MOPPING flag is set, it means all the pending
2256 	 * commands are being mopped, therefore there is nothing else to do
2257 	 */
2258 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2259 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2260 		    "ahci_reset_port_reject_pkts: port %d is in "
2261 		    "mopping process, so return directly ", port);
2262 		return (SATA_SUCCESS);
2263 	}
2264 
2265 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2266 	ahci_portp->ahciport_mop_in_progress++;
2267 
2268 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2269 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2270 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2271 		reset_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2272 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2273 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2274 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2275 		reset_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2276 	}
2277 
2278 	if (ahci_restart_port_wait_till_ready(ahci_ctlp,
2279 	    ahci_portp, port, AHCI_PORT_RESET|AHCI_RESET_NO_EVENTS_UP,
2280 	    NULL) != AHCI_SUCCESS)
2281 		return (SATA_FAILURE);
2282 
2283 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2284 		finished_tags = ahci_portp->ahciport_pending_tags &
2285 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2286 	else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2287 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
2288 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2289 
2290 	reset_tags &= ~finished_tags;
2291 
2292 	ahci_mop_commands(ahci_ctlp,
2293 	    ahci_portp,
2294 	    slot_status,
2295 	    0, /* failed tags */
2296 	    0, /* timeout tags */
2297 	    0, /* aborted tags */
2298 	    reset_tags); /* reset tags */
2299 
2300 	return (SATA_SUCCESS);
2301 }
2302 
2303 /*
2304  * Used to do hba reset and reject all the pending packets on all ports
2305  * during the reset operation.
2306  */
2307 static int
2308 ahci_reset_hba_reject_pkts(ahci_ctl_t *ahci_ctlp)
2309 {
2310 	ahci_port_t *ahci_portp;
2311 	uint32_t slot_status[AHCI_MAX_PORTS];
2312 	uint32_t reset_tags[AHCI_MAX_PORTS];
2313 	uint32_t finished_tags[AHCI_MAX_PORTS];
2314 	uint8_t port;
2315 	int ret = SATA_SUCCESS;
2316 
2317 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2318 	    "ahci_reset_hba_reject_pkts enter", NULL);
2319 
2320 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2321 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2322 			continue;
2323 		}
2324 
2325 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2326 
2327 		mutex_enter(&ahci_portp->ahciport_mutex);
2328 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2329 			slot_status[port] = ddi_get32(
2330 			    ahci_ctlp->ahcictl_ahci_acc_handle,
2331 			    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2332 			reset_tags[port] = slot_status[port] &
2333 			    AHCI_SLOT_MASK(ahci_ctlp);
2334 		} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2335 			slot_status[port] = ddi_get32(
2336 			    ahci_ctlp->ahcictl_ahci_acc_handle,
2337 			    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2338 			reset_tags[port] = slot_status[port] &
2339 			    AHCI_NCQ_SLOT_MASK(ahci_portp);
2340 		}
2341 		mutex_exit(&ahci_portp->ahciport_mutex);
2342 	}
2343 
2344 	if (ahci_hba_reset(ahci_ctlp) != AHCI_SUCCESS) {
2345 		ret = SATA_FAILURE;
2346 		goto out;
2347 	}
2348 
2349 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2350 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2351 			continue;
2352 		}
2353 
2354 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2355 
2356 		mutex_enter(&ahci_portp->ahciport_mutex);
2357 		/*
2358 		 * To prevent recursive enter to ahci_mop_commands, we need
2359 		 * check AHCI_PORT_FLAG_MOPPING flag.
2360 		 */
2361 		if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2362 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2363 			    "ahci_reset_hba_reject_pkts: port %d is in "
2364 			    "mopping process, so return directly ", port);
2365 			mutex_exit(&ahci_portp->ahciport_mutex);
2366 			continue;
2367 		}
2368 
2369 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2370 		ahci_portp->ahciport_mop_in_progress++;
2371 
2372 		if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp))
2373 			finished_tags[port]  =
2374 			    ahci_portp->ahciport_pending_tags &
2375 			    ~slot_status[port] & AHCI_SLOT_MASK(ahci_ctlp);
2376 		else if (NCQ_CMD_IN_PROGRESS(ahci_portp))
2377 			finished_tags[port] =
2378 			    ahci_portp->ahciport_pending_ncq_tags &
2379 			    ~slot_status[port] & AHCI_NCQ_SLOT_MASK(ahci_portp);
2380 
2381 		reset_tags[port] &= ~finished_tags[port];
2382 
2383 		ahci_mop_commands(ahci_ctlp,
2384 		    ahci_portp,
2385 		    slot_status[port],
2386 		    0, /* failed tags */
2387 		    0, /* timeout tags */
2388 		    0, /* aborted tags */
2389 		    reset_tags[port]); /* reset tags */
2390 		mutex_exit(&ahci_portp->ahciport_mutex);
2391 	}
2392 out:
2393 	return (ret);
2394 }
2395 
2396 /*
2397  * Called by sata framework to reset a port(s) or device.
2398  */
2399 static int
2400 ahci_tran_reset_dport(dev_info_t *dip, sata_device_t *sd)
2401 {
2402 	ahci_ctl_t *ahci_ctlp;
2403 	ahci_port_t *ahci_portp;
2404 	uint8_t cport = sd->satadev_addr.cport;
2405 	uint8_t port;
2406 	int ret = SATA_SUCCESS;
2407 	int instance = ddi_get_instance(dip);
2408 
2409 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
2410 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
2411 
2412 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2413 	    "ahci_tran_reset_port enter: cport: %d", cport);
2414 
2415 	switch (sd->satadev_addr.qual) {
2416 	case SATA_ADDR_CPORT:
2417 		/* Port reset */
2418 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2419 		cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport port %d "
2420 		    "reset port", instance, port);
2421 
2422 		mutex_enter(&ahci_portp->ahciport_mutex);
2423 		ret = ahci_reset_port_reject_pkts(ahci_ctlp, ahci_portp, port);
2424 		mutex_exit(&ahci_portp->ahciport_mutex);
2425 
2426 		break;
2427 
2428 	case SATA_ADDR_DCPORT:
2429 		/* Device reset */
2430 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2431 		cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport port %d "
2432 		    "reset device", instance, port);
2433 
2434 		mutex_enter(&ahci_portp->ahciport_mutex);
2435 		if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED |
2436 		    ahci_portp->ahciport_port_state & SATA_PSTATE_SHUTDOWN |
2437 		    ahci_portp->ahciport_port_state & SATA_PSTATE_PWROFF) {
2438 			/*
2439 			 * In case the targer driver would send the request
2440 			 * before sata framework can have the opportunity to
2441 			 * process those event reports.
2442 			 */
2443 			sd->satadev_state = ahci_portp->ahciport_port_state;
2444 			ahci_update_sata_registers(ahci_ctlp, port, sd);
2445 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2446 			    "ahci_tran_reset_dport returning SATA_FAILURE "
2447 			    "while port in FAILED/SHUTDOWN/PWROFF state: "
2448 			    "port: %d", port);
2449 			mutex_exit(&ahci_portp->ahciport_mutex);
2450 			ret = SATA_FAILURE;
2451 			break;
2452 		}
2453 
2454 		if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
2455 			/*
2456 			 * ahci_intr_phyrdy_change() may have rendered it to
2457 			 * AHCI_PORT_TYPE_NODEV.
2458 			 */
2459 			sd->satadev_type = SATA_DTYPE_NONE;
2460 			sd->satadev_state = ahci_portp->ahciport_port_state;
2461 			ahci_update_sata_registers(ahci_ctlp, port, sd);
2462 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2463 			    "ahci_tran_reset_dport returning SATA_FAILURE "
2464 			    "while no device attached: port: %d", port);
2465 			mutex_exit(&ahci_portp->ahciport_mutex);
2466 			ret = SATA_FAILURE;
2467 			break;
2468 		}
2469 
2470 		ret = ahci_reset_device_reject_pkts(ahci_ctlp,
2471 		    ahci_portp, port);
2472 		mutex_exit(&ahci_portp->ahciport_mutex);
2473 		break;
2474 
2475 	case SATA_ADDR_CNTRL:
2476 		/* Reset the whole controller */
2477 		cmn_err(CE_NOTE, "!ahci%d: ahci_tran_reset_dport port %d "
2478 		    "reset the whole hba", instance, port);
2479 		ret = ahci_reset_hba_reject_pkts(ahci_ctlp);
2480 		break;
2481 
2482 	case SATA_ADDR_PMPORT:
2483 	case SATA_ADDR_DPMPORT:
2484 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
2485 		    "ahci_tran_reset_dport: port multiplier will be "
2486 		    "supported later", NULL);
2487 		/* FALLTHRU */
2488 	default:
2489 		ret = SATA_FAILURE;
2490 	}
2491 
2492 	return (ret);
2493 }
2494 
2495 /*
2496  * Called by sata framework to activate a port as part of hotplug.
2497  * (cfgadm -c connect satax/y)
2498  * Note: Not port-mult aware.
2499  */
2500 static int
2501 ahci_tran_hotplug_port_activate(dev_info_t *dip, sata_device_t *satadev)
2502 {
2503 	ahci_ctl_t *ahci_ctlp;
2504 	ahci_port_t *ahci_portp;
2505 	uint8_t	cport = satadev->satadev_addr.cport;
2506 	uint8_t port;
2507 	int instance = ddi_get_instance(dip);
2508 
2509 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
2510 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
2511 
2512 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2513 	    "ahci_tran_hotplug_port_activate cport %d enter", cport);
2514 
2515 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
2516 
2517 	mutex_enter(&ahci_portp->ahciport_mutex);
2518 	ahci_enable_port_intrs(ahci_ctlp, port);
2519 	cmn_err(CE_NOTE, "!ahci%d: ahci port %d is activated", instance, port);
2520 
2521 	/*
2522 	 * Reset the port so that the PHY communication would be re-established.
2523 	 * But this reset is an internal operation and the sata module doesn't
2524 	 * need to know about it. Moreover, the port with a device attached will
2525 	 * be started too.
2526 	 */
2527 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp,
2528 	    ahci_portp, port,
2529 	    AHCI_PORT_RESET|AHCI_RESET_NO_EVENTS_UP,
2530 	    NULL);
2531 
2532 	/*
2533 	 * Need to check the link status and device status of the port
2534 	 * and consider raising power if the port was in D3 state
2535 	 */
2536 	ahci_portp->ahciport_port_state |= SATA_PSTATE_PWRON;
2537 	ahci_portp->ahciport_port_state &= ~SATA_PSTATE_PWROFF;
2538 	ahci_portp->ahciport_port_state &= ~SATA_PSTATE_SHUTDOWN;
2539 
2540 	satadev->satadev_state = ahci_portp->ahciport_port_state;
2541 
2542 	ahci_update_sata_registers(ahci_ctlp, port, satadev);
2543 
2544 	mutex_exit(&ahci_portp->ahciport_mutex);
2545 	return (SATA_SUCCESS);
2546 }
2547 
2548 /*
2549  * Called by sata framework to deactivate a port as part of hotplug.
2550  * (cfgadm -c disconnect satax/y)
2551  * Note: Not port-mult aware.
2552  */
2553 static int
2554 ahci_tran_hotplug_port_deactivate(dev_info_t *dip, sata_device_t *satadev)
2555 {
2556 	ahci_ctl_t *ahci_ctlp;
2557 	ahci_port_t *ahci_portp;
2558 	uint8_t cport = satadev->satadev_addr.cport;
2559 	uint8_t port;
2560 	uint32_t port_scontrol;
2561 	int instance = ddi_get_instance(dip);
2562 
2563 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
2564 	port = ahci_ctlp->ahcictl_cport_to_port[cport];
2565 
2566 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
2567 	    "ahci_tran_hotplug_port_deactivate cport %d enter", cport);
2568 
2569 	ahci_portp = ahci_ctlp->ahcictl_ports[port];
2570 
2571 	mutex_enter(&ahci_portp->ahciport_mutex);
2572 	cmn_err(CE_NOTE, "!ahci%d: ahci port %d is deactivated",
2573 	    instance, port);
2574 
2575 	/* Disable the interrupts on the port */
2576 	ahci_disable_port_intrs(ahci_ctlp, port);
2577 
2578 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
2579 		goto phy_offline;
2580 	}
2581 
2582 	/* First to abort all the pending commands */
2583 	ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
2584 
2585 	/* Then stop the port */
2586 	(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
2587 	    ahci_portp, port);
2588 
2589 	/* Next put the PHY offline */
2590 
2591 phy_offline:
2592 	port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2593 	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
2594 	SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_DISABLE);
2595 
2596 	/* Update ahciport_port_state */
2597 	ahci_portp->ahciport_port_state = SATA_PSTATE_SHUTDOWN;
2598 	satadev->satadev_state = ahci_portp->ahciport_port_state;
2599 
2600 	ahci_update_sata_registers(ahci_ctlp, port, satadev);
2601 
2602 	mutex_exit(&ahci_portp->ahciport_mutex);
2603 	return (SATA_SUCCESS);
2604 }
2605 
2606 /*
2607  * To be used to mark all the outstanding pkts with SATA_PKT_ABORTED
2608  * when a device is unplugged or a port is deactivated.
2609  *
2610  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2611  */
2612 static void
2613 ahci_reject_all_abort_pkts(ahci_ctl_t *ahci_ctlp,
2614     ahci_port_t *ahci_portp, uint8_t port)
2615 {
2616 	uint32_t slot_status = 0;
2617 	uint32_t abort_tags = 0;
2618 
2619 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
2620 	    "ahci_reject_all_abort_pkts on port: %d", port);
2621 
2622 	/*
2623 	 * When AHCI_PORT_FLAG_MOPPING is set, we need to check whether a
2624 	 * REQUEST SENSE command or READ LOG EXT command is delivered to HBA
2625 	 * to get the error data, if yes when the device is removed, the
2626 	 * command needs to be aborted too.
2627 	 */
2628 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) {
2629 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
2630 			slot_status = 0x1;
2631 			abort_tags = 0x1;
2632 			goto out;
2633 		} else {
2634 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2635 			    "ahci_reject_all_abort_pkts return directly "
2636 			    "port %d no needs to reject any outstanding "
2637 			    "commands", port);
2638 			return;
2639 		}
2640 	}
2641 
2642 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2643 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2644 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
2645 		abort_tags = slot_status & AHCI_SLOT_MASK(ahci_ctlp);
2646 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
2647 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2648 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
2649 		abort_tags = slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
2650 	}
2651 
2652 out:
2653 	/* No need to do mop when there is no outstanding commands */
2654 	if (slot_status != 0) {
2655 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
2656 		ahci_portp->ahciport_mop_in_progress++;
2657 
2658 		ahci_mop_commands(ahci_ctlp,
2659 		    ahci_portp,
2660 		    slot_status,
2661 		    0, /* failed tags */
2662 		    0, /* timeout tags */
2663 		    abort_tags, /* aborting tags */
2664 		    0); /* reset tags */
2665 	}
2666 }
2667 
2668 #if defined(__lock_lint)
2669 static int
2670 ahci_selftest(dev_info_t *dip, sata_device_t *device)
2671 {
2672 	return (SATA_SUCCESS);
2673 }
2674 #endif
2675 
2676 /*
2677  * Allocate the ports structure, only called by ahci_attach
2678  */
2679 static int
2680 ahci_alloc_ports_state(ahci_ctl_t *ahci_ctlp)
2681 {
2682 	int port, cport = 0;
2683 
2684 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
2685 	    "ahci_alloc_ports_state enter", NULL);
2686 
2687 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
2688 
2689 	/* Allocate structures only for the implemented ports */
2690 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2691 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2692 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
2693 			    "hba port %d not implemented", port);
2694 			continue;
2695 		}
2696 
2697 		ahci_ctlp->ahcictl_cport_to_port[cport] = (uint8_t)port;
2698 		ahci_ctlp->ahcictl_port_to_cport[port] =
2699 		    (uint8_t)cport++;
2700 
2701 		if (ahci_alloc_port_state(ahci_ctlp, port) != AHCI_SUCCESS) {
2702 			goto err_out;
2703 		}
2704 	}
2705 
2706 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
2707 	return (AHCI_SUCCESS);
2708 
2709 err_out:
2710 	for (port--; port >= 0; port--) {
2711 		if (AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2712 			ahci_dealloc_port_state(ahci_ctlp, port);
2713 		}
2714 	}
2715 
2716 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
2717 	return (AHCI_FAILURE);
2718 }
2719 
2720 /*
2721  * Reverse of ahci_alloc_ports_state(), only called by ahci_detach
2722  */
2723 static void
2724 ahci_dealloc_ports_state(ahci_ctl_t *ahci_ctlp)
2725 {
2726 	int port;
2727 
2728 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
2729 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2730 		/* if this port is implemented by the HBA */
2731 		if (AHCI_PORT_IMPLEMENTED(ahci_ctlp, port))
2732 			ahci_dealloc_port_state(ahci_ctlp, port);
2733 	}
2734 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
2735 }
2736 
2737 /*
2738  * Drain the taskq.
2739  */
2740 static void
2741 ahci_drain_ports_taskq(ahci_ctl_t *ahci_ctlp)
2742 {
2743 	ahci_port_t *ahci_portp;
2744 	int port;
2745 
2746 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2747 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2748 			continue;
2749 		}
2750 
2751 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2752 
2753 		mutex_enter(&ahci_portp->ahciport_mutex);
2754 		ddi_taskq_wait(ahci_portp->ahciport_event_taskq);
2755 		mutex_exit(&ahci_portp->ahciport_mutex);
2756 	}
2757 }
2758 
2759 /*
2760  * Initialize the controller and all ports. And then try to start the ports
2761  * if there are devices attached.
2762  *
2763  * This routine can be called from three seperate cases: DDI_ATTACH,
2764  * PM_LEVEL_D0 and DDI_RESUME. The DDI_ATTACH case is different from
2765  * other two cases; device signature probing are attempted only during
2766  * DDI_ATTACH case.
2767  *
2768  * WARNING!!! Disable the whole controller's interrupts before calling and
2769  * the interrupts will be enabled upon successfully return.
2770  */
2771 static int
2772 ahci_initialize_controller(ahci_ctl_t *ahci_ctlp)
2773 {
2774 	ahci_port_t *ahci_portp;
2775 	uint32_t ghc_control;
2776 	int port;
2777 
2778 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
2779 	    "ahci_initialize_controller enter", NULL);
2780 
2781 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
2782 
2783 	/*
2784 	 * Indicate that system software is AHCI aware by setting
2785 	 * GHC.AE to 1
2786 	 */
2787 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2788 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
2789 
2790 	ghc_control |= AHCI_HBA_GHC_AE;
2791 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
2792 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp),
2793 	    ghc_control);
2794 
2795 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
2796 
2797 	/* Initialize the implemented ports and structures */
2798 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2799 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2800 			continue;
2801 		}
2802 
2803 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2804 		mutex_enter(&ahci_portp->ahciport_mutex);
2805 
2806 		/*
2807 		 * Ensure that the controller is not in the running state
2808 		 * by checking every implemented port's PxCMD register
2809 		 */
2810 		if (ahci_initialize_port(ahci_ctlp, ahci_portp, port)
2811 		    != AHCI_SUCCESS) {
2812 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
2813 			    "ahci_initialize_controller: failed to "
2814 			    "initialize port %d", port);
2815 			/*
2816 			 * Set the port state to SATA_PSTATE_FAILED if
2817 			 * failed to initialize it.
2818 			 */
2819 			ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
2820 		}
2821 
2822 		mutex_exit(&ahci_portp->ahciport_mutex);
2823 	}
2824 
2825 	/* Enable the whole controller interrupts */
2826 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
2827 	ahci_enable_all_intrs(ahci_ctlp);
2828 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
2829 
2830 	return (AHCI_SUCCESS);
2831 }
2832 
2833 /*
2834  * Reverse of ahci_initialize_controller()
2835  *
2836  * We only need to stop the ports and disable the interrupt.
2837  */
2838 static void
2839 ahci_uninitialize_controller(ahci_ctl_t *ahci_ctlp)
2840 {
2841 	ahci_port_t *ahci_portp;
2842 	int port;
2843 
2844 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
2845 	    "ahci_uninitialize_controller enter", NULL);
2846 
2847 	/* disable all the interrupts. */
2848 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
2849 	ahci_disable_all_intrs(ahci_ctlp);
2850 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
2851 
2852 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
2853 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
2854 			continue;
2855 		}
2856 
2857 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
2858 
2859 		/* Stop the port by clearing PxCMD.ST */
2860 		mutex_enter(&ahci_portp->ahciport_mutex);
2861 
2862 		/*
2863 		 * Here we must disable the port interrupt because
2864 		 * ahci_disable_all_intrs only clear GHC.IE, and IS
2865 		 * register will be still set if PxIE is enabled.
2866 		 * When ahci shares one IRQ with other drivers, the
2867 		 * intr handler may claim the intr mistakenly.
2868 		 */
2869 		ahci_disable_port_intrs(ahci_ctlp, port);
2870 		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
2871 		    ahci_portp, port);
2872 		mutex_exit(&ahci_portp->ahciport_mutex);
2873 	}
2874 }
2875 
2876 /*
2877  * The routine is to initialize the port. First put the port in NOTRunning
2878  * state, then enable port interrupt and clear Serror register. And under
2879  * AHCI_ATTACH case, find device signature and then try to start the port.
2880  *
2881  * WARNING!!! ahciport_mutex should be acquired before the function is called.
2882  */
2883 static int
2884 ahci_initialize_port(ahci_ctl_t *ahci_ctlp,
2885     ahci_port_t *ahci_portp, uint8_t port)
2886 {
2887 	uint32_t port_sstatus, port_task_file, port_cmd_status;
2888 	int ret;
2889 
2890 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2891 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
2892 
2893 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
2894 	    "ahci_initialize_port: port %d "
2895 	    "port_cmd_status = 0x%x", port, port_cmd_status);
2896 	/*
2897 	 * Check whether the port is in NotRunning state, if not,
2898 	 * put the port in NotRunning state
2899 	 */
2900 	if (port_cmd_status &
2901 	    (AHCI_CMD_STATUS_ST |
2902 	    AHCI_CMD_STATUS_CR |
2903 	    AHCI_CMD_STATUS_FRE |
2904 	    AHCI_CMD_STATUS_FR)) {
2905 		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
2906 		    ahci_portp, port);
2907 	}
2908 
2909 	/* Device is unknown at first */
2910 	ahci_portp->ahciport_device_type = SATA_DTYPE_UNKNOWN;
2911 
2912 	/* Disable the interface power management */
2913 	ahci_disable_interface_pm(ahci_ctlp, port);
2914 
2915 	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2916 	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
2917 	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
2918 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
2919 
2920 	/* Check physcial link status */
2921 	if (SSTATUS_GET_IPM(port_sstatus) == SSTATUS_IPM_NODEV_NOPHYCOM ||
2922 	    SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_NOPHYCOM ||
2923 
2924 	    /* Check interface status */
2925 	    port_task_file & AHCI_TFD_STS_BSY ||
2926 	    port_task_file & AHCI_TFD_STS_DRQ ||
2927 
2928 	    /* Check whether port reset must be executed */
2929 	    ahci_ctlp->ahcictl_cap & AHCI_CAP_INIT_PORT_RESET) {
2930 
2931 		/* Incorrect task file state, we need to reset port */
2932 		ret = ahci_port_reset(ahci_ctlp, ahci_portp, port);
2933 
2934 		/* Does port reset succeed on HBA port? */
2935 		if (ret != AHCI_SUCCESS) {
2936 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
2937 			    "ahci_initialize_port:"
2938 			    "port reset faild at port %d", port);
2939 			return (AHCI_FAILURE);
2940 		}
2941 
2942 		/* Is port failed? */
2943 		if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED) {
2944 			AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
2945 			    "ahci_initialize_port: port %d state 0x%x",
2946 			    port, ahci_portp->ahciport_port_state);
2947 			return (AHCI_FAILURE);
2948 		}
2949 	}
2950 
2951 	ahci_portp->ahciport_port_state = SATA_STATE_READY;
2952 
2953 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "port %d is ready now.", port);
2954 
2955 	/*
2956 	 * At the time being, only probe ports/devices and get the types of
2957 	 * attached devices during DDI_ATTACH. In fact, the device can be
2958 	 * changed during power state changes, but at the time being, we
2959 	 * don't support the situation.
2960 	 */
2961 	if (ahci_ctlp->ahcictl_flags & AHCI_ATTACH) {
2962 		/*
2963 		 * Try to get the device signature if the port is
2964 		 * not empty.
2965 		 */
2966 		if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE)
2967 			ahci_find_dev_signature(ahci_ctlp, ahci_portp, port);
2968 	} else {
2969 
2970 		/*
2971 		 * During the resume, we need to set the PxCLB, PxCLBU, PxFB
2972 		 * and PxFBU registers in case these registers were cleared
2973 		 * during the suspend.
2974 		 */
2975 		AHCIDBG(AHCIDBG_PM, ahci_ctlp,
2976 		    "ahci_initialize_port: port %d "
2977 		    "reset the port during resume", port);
2978 		(void) ahci_port_reset(ahci_ctlp, ahci_portp, port);
2979 
2980 		AHCIDBG(AHCIDBG_PM, ahci_ctlp,
2981 		    "ahci_initialize_port: port %d "
2982 		    "set PxCLB, PxCLBU, PxFB and PxFBU "
2983 		    "during resume", port);
2984 
2985 		/* Config Port Received FIS Base Address */
2986 		ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
2987 		    (uint64_t *)AHCI_PORT_PxFB(ahci_ctlp, port),
2988 		    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
2989 
2990 		/* Config Port Command List Base Address */
2991 		ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
2992 		    (uint64_t *)AHCI_PORT_PxCLB(ahci_ctlp, port),
2993 		    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
2994 	}
2995 
2996 	/* Return directly if no device connected */
2997 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
2998 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
2999 		    "No device connected to port %d", port);
3000 		goto out;
3001 	}
3002 
3003 	/* Try to start the port */
3004 	if (ahci_start_port(ahci_ctlp, ahci_portp, port)
3005 	    != AHCI_SUCCESS) {
3006 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3007 		    "failed to start port %d", port);
3008 		return (AHCI_FAILURE);
3009 	}
3010 out:
3011 	/* Enable port interrupts */
3012 	ahci_enable_port_intrs(ahci_ctlp, port);
3013 
3014 	return (AHCI_SUCCESS);
3015 }
3016 
3017 /*
3018  *  Handle hardware defect, and check the capabilities. For example,
3019  *  power management capabilty and MSI capability.
3020  */
3021 static int
3022 ahci_config_space_init(ahci_ctl_t *ahci_ctlp)
3023 {
3024 	ushort_t venid, devid;
3025 	ushort_t caps_ptr, cap_count, cap;
3026 #if AHCI_DEBUG
3027 	ushort_t pmcap, pmcsr;
3028 	ushort_t msimc;
3029 #endif
3030 	uint8_t revision;
3031 
3032 	venid = pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3033 	    PCI_CONF_VENID);
3034 
3035 	devid = pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3036 	    PCI_CONF_DEVID);
3037 
3038 	/*
3039 	 * Modify dma_attr_align of ahcictl_buffer_dma_attr. For VT8251, those
3040 	 * controllers with 0x00 revision id work on 4-byte aligned buffer,
3041 	 * which is a bug and was fixed after 0x00 revision id controllers.
3042 	 *
3043 	 * Moreover, VT8251 cannot use multiple command slots in the command
3044 	 * list for non-queued commands because the previous register content
3045 	 * of PxCI can be re-written in the register write, so a flag will be
3046 	 * set to record this defect - AHCI_CAP_NO_MCMDLIST_NONQUEUE.
3047 	 */
3048 	if (venid == VIA_VENID) {
3049 		revision = pci_config_get8(ahci_ctlp->ahcictl_pci_conf_handle,
3050 		    PCI_CONF_REVID);
3051 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3052 		    "revision id = 0x%x", revision);
3053 		if (revision == 0x00) {
3054 			ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_align = 0x4;
3055 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3056 			    "change ddi_attr_align to 0x4", NULL);
3057 		}
3058 
3059 		ahci_ctlp->ahcictl_cap = AHCI_CAP_NO_MCMDLIST_NONQUEUE;
3060 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3061 		    "VT8251 cannot use multiple command lists for "
3062 		    "non-queued commands", NULL);
3063 	}
3064 
3065 	/*
3066 	 * AMD/ATI SB600 (1002,4380) AHCI chipset doesn't support 64-bit DMA
3067 	 * addressing for both data buffer and communication memory descriptors
3068 	 * though S64A bit of CAP register declares the support.
3069 	 *
3070 	 * We found this chipset must do port reset during initialization,
3071 	 * otherwise, when retrieving device signature, software reset will
3072 	 * get time out.
3073 	 */
3074 	if (venid == 0x1002 && devid == 0x4380) {
3075 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3076 		    "ATI SB600 cannot do 64-bit DMA for both data buffer "
3077 		    "and communication memory descriptors though CAP indicates "
3078 		    "support, so force it to use 32-bit DMA", NULL);
3079 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_BUF_32BIT_DMA;
3080 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
3081 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_INIT_PORT_RESET;
3082 	}
3083 
3084 	/*
3085 	 * AMD/ATI SB700/750 (1002,4391) AHCI chipset doesn't support 64-bit
3086 	 * DMA addressing for communication memory descriptors though S64A bit
3087 	 * of CAP register declares the support. However, it does support
3088 	 * 64-bit DMA for data buffer.
3089 	 */
3090 	if (venid == 0x1002 && devid == 0x4391) {
3091 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3092 		    "ATI SB700/750 cannot do 64-bit DMA for communication "
3093 		    "memory descriptors though CAP indicates support, "
3094 		    "so force it to use 32-bit DMA", NULL);
3095 		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
3096 	}
3097 
3098 	/*
3099 	 * Check if capabilities list is supported and if so,
3100 	 * get initial capabilities pointer and clear bits 0,1.
3101 	 */
3102 	if (pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3103 	    PCI_CONF_STAT) & PCI_STAT_CAP) {
3104 		caps_ptr = P2ALIGN(pci_config_get8(
3105 		    ahci_ctlp->ahcictl_pci_conf_handle,
3106 		    PCI_CONF_CAP_PTR), 4);
3107 	} else {
3108 		caps_ptr = PCI_CAP_NEXT_PTR_NULL;
3109 	}
3110 
3111 	/*
3112 	 * Walk capabilities if supported.
3113 	 */
3114 	for (cap_count = 0; caps_ptr != PCI_CAP_NEXT_PTR_NULL; ) {
3115 
3116 		/*
3117 		 * Check that we haven't exceeded the maximum number of
3118 		 * capabilities and that the pointer is in a valid range.
3119 		 */
3120 		if (++cap_count > PCI_CAP_MAX_PTR) {
3121 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3122 			    "too many device capabilities", NULL);
3123 			return (AHCI_FAILURE);
3124 		}
3125 		if (caps_ptr < PCI_CAP_PTR_OFF) {
3126 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3127 			    "capabilities pointer 0x%x out of range",
3128 			    caps_ptr);
3129 			return (AHCI_FAILURE);
3130 		}
3131 
3132 		/*
3133 		 * Get next capability and check that it is valid.
3134 		 * For now, we only support power management.
3135 		 */
3136 		cap = pci_config_get8(ahci_ctlp->ahcictl_pci_conf_handle,
3137 		    caps_ptr);
3138 		switch (cap) {
3139 		case PCI_CAP_ID_PM:
3140 
3141 			/* power management supported */
3142 			ahci_ctlp->ahcictl_cap |= AHCI_CAP_PM;
3143 
3144 			/* Save PMCSR offset */
3145 			ahci_ctlp->ahcictl_pmcsr_offset = caps_ptr + PCI_PMCSR;
3146 
3147 #if AHCI_DEBUG
3148 			pmcap = pci_config_get16(
3149 			    ahci_ctlp->ahcictl_pci_conf_handle,
3150 			    caps_ptr + PCI_PMCAP);
3151 			pmcsr = pci_config_get16(
3152 			    ahci_ctlp->ahcictl_pci_conf_handle,
3153 			    ahci_ctlp->ahcictl_pmcsr_offset);
3154 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3155 			    "Power Management capability found PCI_PMCAP "
3156 			    "= 0x%x PCI_PMCSR = 0x%x", pmcap, pmcsr);
3157 			if ((pmcap & 0x3) == 0x3)
3158 				AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3159 				    "PCI Power Management Interface "
3160 				    "spec 1.2 compliant", NULL);
3161 #endif
3162 			break;
3163 
3164 		case PCI_CAP_ID_MSI:
3165 #if AHCI_DEBUG
3166 			msimc = pci_config_get16(
3167 			    ahci_ctlp->ahcictl_pci_conf_handle,
3168 			    caps_ptr + PCI_MSI_CTRL);
3169 			AHCIDBG(AHCIDBG_MSI, ahci_ctlp,
3170 			    "Message Signaled Interrupt capability found "
3171 			    "MSICAP_MC.MMC = 0x%x", (msimc & 0xe) >> 1);
3172 #endif
3173 			AHCIDBG(AHCIDBG_MSI, ahci_ctlp,
3174 			    "MSI capability found", NULL);
3175 			break;
3176 
3177 		case PCI_CAP_ID_PCIX:
3178 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3179 			    "PCI-X capability found", NULL);
3180 			break;
3181 
3182 		case PCI_CAP_ID_PCI_E:
3183 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3184 			    "PCI Express capability found", NULL);
3185 			break;
3186 
3187 		case PCI_CAP_ID_MSI_X:
3188 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3189 			    "MSI-X capability found", NULL);
3190 			break;
3191 
3192 		case PCI_CAP_ID_SATA:
3193 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3194 			    "SATA capability found", NULL);
3195 			break;
3196 
3197 		case PCI_CAP_ID_VS:
3198 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3199 			    "Vendor Specific capability found", NULL);
3200 			break;
3201 
3202 		default:
3203 			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3204 			    "unrecognized capability 0x%x", cap);
3205 			break;
3206 		}
3207 
3208 		/*
3209 		 * Get next capabilities pointer and clear bits 0,1.
3210 		 */
3211 		caps_ptr = P2ALIGN(pci_config_get8(
3212 		    ahci_ctlp->ahcictl_pci_conf_handle,
3213 		    (caps_ptr + PCI_CAP_NEXT_PTR)), 4);
3214 	}
3215 
3216 	return (AHCI_SUCCESS);
3217 }
3218 
3219 /*
3220  * AHCI device reset ...; a single device on one of the ports is reset,
3221  * but the HBA and physical communication remain intact. This is the
3222  * least intrusive.
3223  *
3224  * When issuing a software reset sequence, there should not be other
3225  * commands in the command list, so we will first clear and then re-set
3226  * PxCMD.ST to clear PxCI. And before issuing the software reset,
3227  * the port must be idle and PxTFD.STS.BSY and PxTFD.STS.DRQ must be
3228  * cleared unless command list override (PxCMD.CLO) is supported.
3229  *
3230  * WARNING!!! ahciport_mutex should be acquired and PxCMD.FRE should be
3231  * set before the function is called.
3232  */
3233 static int
3234 ahci_software_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
3235     uint8_t port)
3236 {
3237 	ahci_fis_h2d_register_t *h2d_register_fisp;
3238 	ahci_cmd_table_t *cmd_table;
3239 	ahci_cmd_header_t *cmd_header;
3240 	uint32_t port_cmd_status, port_cmd_issue, port_task_file;
3241 	int slot, loop_count;
3242 	int rval = AHCI_FAILURE;
3243 
3244 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
3245 	    "Port %d device resetting", port);
3246 
3247 	/* First clear PxCMD.ST (AHCI v1.2 10.4.1) */
3248 	if (ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp,
3249 	    port) != AHCI_SUCCESS) {
3250 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3251 		    "ahci_software_reset: cannot stop HBA port %d.", port);
3252 		goto out;
3253 	}
3254 
3255 	/* Check PxTFD.STS.BSY and PxTFD.STS.DRQ */
3256 	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3257 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3258 
3259 	if (port_task_file & AHCI_TFD_STS_BSY ||
3260 	    port_task_file & AHCI_TFD_STS_DRQ) {
3261 		if (!(ahci_ctlp->ahcictl_cap & AHCI_CAP_SCLO)) {
3262 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3263 			    "PxTFD.STS.BSY/DRQ is set (PxTFD=0x%x), "
3264 			    "cannot issue a software reset.", port_task_file);
3265 			goto out;
3266 		}
3267 
3268 		/*
3269 		 * If HBA Support CLO, as Command List Override (CAP.SCLO is
3270 		 * set), PxCMD.CLO bit should be set before set PxCMD.ST, in
3271 		 * order to clear PxTFD.STS.BSY and PxTFD.STS.DRQ.
3272 		 */
3273 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3274 		    "PxTFD.STS.BSY/DRQ is set, try SCLO.", NULL)
3275 
3276 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3277 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3278 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3279 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3280 		    port_cmd_status|AHCI_CMD_STATUS_CLO);
3281 
3282 		/* Waiting till PxCMD.SCLO bit is cleared */
3283 		loop_count = 0;
3284 		do {
3285 			/* Wait for 10 millisec */
3286 			drv_usecwait(AHCI_10MS_USECS);
3287 
3288 			/* We are effectively timing out after 1 sec. */
3289 			if (loop_count++ > 100) {
3290 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3291 				    "SCLO time out. port %d is busy.", port);
3292 				goto out;
3293 			}
3294 
3295 			port_cmd_status =
3296 			    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3297 			    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3298 		} while (port_cmd_status & AHCI_CMD_STATUS_CLO);
3299 
3300 		/* Re-check */
3301 		port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3302 		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3303 		if (port_task_file & AHCI_TFD_STS_BSY ||
3304 		    port_task_file & AHCI_TFD_STS_DRQ) {
3305 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3306 			    "SCLO cannot clear PxTFD.STS.BSY/DRQ (PxTFD=0x%x)",
3307 			    port_task_file);
3308 			goto out;
3309 		}
3310 	}
3311 
3312 	/* Then start port */
3313 	if (ahci_start_port(ahci_ctlp, ahci_portp, port)
3314 	    != AHCI_SUCCESS) {
3315 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3316 		    "ahci_software_reset: cannot start AHCI port %d.", port);
3317 		goto out;
3318 	}
3319 
3320 	/*
3321 	 * When ahci_port.ahciport_mop_in_progress is set, A non-zero
3322 	 * ahci_port.ahciport_pending_ncq_tags may fail
3323 	 * ahci_claim_free_slot(). Actually according to spec, by clearing
3324 	 * PxCMD.ST there is no command outstanding while executing software
3325 	 * reseting. Hence we directly use slot 0 instead of
3326 	 * ahci_claim_free_slot().
3327 	 */
3328 	slot = 0;
3329 
3330 	/* Now send the first H2D Register FIS with SRST set to 1 */
3331 	cmd_table = ahci_portp->ahciport_cmd_tables[slot];
3332 	bzero((void *)cmd_table, ahci_cmd_table_size);
3333 
3334 	h2d_register_fisp =
3335 	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
3336 
3337 	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
3338 	SET_FIS_DEVCTL(h2d_register_fisp, SATA_DEVCTL_SRST);
3339 
3340 	/* Set Command Header in Command List */
3341 	cmd_header = &ahci_portp->ahciport_cmd_list[slot];
3342 	BZERO_DESCR_INFO(cmd_header);
3343 	BZERO_PRD_BYTE_COUNT(cmd_header);
3344 	SET_COMMAND_FIS_LENGTH(cmd_header, 5);
3345 
3346 	SET_CLEAR_BUSY_UPON_R_OK(cmd_header, 1);
3347 	SET_RESET(cmd_header, 1);
3348 	SET_WRITE(cmd_header, 1);
3349 
3350 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_tables_dma_handle[slot],
3351 	    0,
3352 	    ahci_cmd_table_size,
3353 	    DDI_DMA_SYNC_FORDEV);
3354 
3355 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
3356 	    slot * sizeof (ahci_cmd_header_t),
3357 	    sizeof (ahci_cmd_header_t),
3358 	    DDI_DMA_SYNC_FORDEV);
3359 
3360 	/* Indicate to the HBA that a command is active. */
3361 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3362 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
3363 	    (0x1 << slot));
3364 
3365 	loop_count = 0;
3366 
3367 	/* Loop till the first command is finished */
3368 	do {
3369 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3370 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
3371 
3372 		/* We are effectively timing out after 1 sec. */
3373 		if (loop_count++ > AHCI_POLLRATE_PORT_SOFTRESET) {
3374 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3375 			    "the first SRST FIS is timed out, "
3376 			    "loop_count = %d", loop_count);
3377 			goto out;
3378 		}
3379 
3380 		/* Wait for 10 millisec */
3381 		delay(AHCI_10MS_TICKS);
3382 	} while (port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp) & (0x1 << slot));
3383 
3384 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
3385 	    "ahci_software_reset: 1st loop count: %d, "
3386 	    "port_cmd_issue = 0x%x, slot = 0x%x",
3387 	    loop_count, port_cmd_issue, slot);
3388 
3389 	/* According to ATA spec, we need wait at least 5 microsecs here. */
3390 	drv_usecwait(AHCI_1MS_USECS);
3391 
3392 	/* Now send the second H2D Register FIS with SRST cleard to zero */
3393 	cmd_table = ahci_portp->ahciport_cmd_tables[slot];
3394 	bzero((void *)cmd_table, ahci_cmd_table_size);
3395 
3396 	h2d_register_fisp =
3397 	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
3398 
3399 	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
3400 
3401 	/* Set Command Header in Command List */
3402 	cmd_header = &ahci_portp->ahciport_cmd_list[slot];
3403 	BZERO_DESCR_INFO(cmd_header);
3404 	BZERO_PRD_BYTE_COUNT(cmd_header);
3405 	SET_COMMAND_FIS_LENGTH(cmd_header, 5);
3406 
3407 	SET_WRITE(cmd_header, 1);
3408 
3409 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_tables_dma_handle[slot],
3410 	    0,
3411 	    ahci_cmd_table_size,
3412 	    DDI_DMA_SYNC_FORDEV);
3413 
3414 	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
3415 	    slot * sizeof (ahci_cmd_header_t),
3416 	    sizeof (ahci_cmd_header_t),
3417 	    DDI_DMA_SYNC_FORDEV);
3418 
3419 	/* Indicate to the HBA that a command is active. */
3420 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3421 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
3422 	    (0x1 << slot));
3423 
3424 	loop_count = 0;
3425 
3426 	/* Loop till the second command is finished */
3427 	do {
3428 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3429 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
3430 
3431 		/* We are effectively timing out after 1 sec. */
3432 		if (loop_count++ > AHCI_POLLRATE_PORT_SOFTRESET) {
3433 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3434 			    "the second SRST FIS is timed out, "
3435 			    "loop_count = %d", loop_count);
3436 			goto out;
3437 		}
3438 
3439 		/* Wait for 10 millisec */
3440 		delay(AHCI_10MS_TICKS);
3441 	} while (port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp) & (0x1 << slot));
3442 
3443 	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
3444 	    "ahci_software_reset: 2nd loop count: %d, "
3445 	    "port_cmd_issue = 0x%x, slot = 0x%x",
3446 	    loop_count, port_cmd_issue, slot);
3447 
3448 	CLEAR_BIT(ahci_portp->ahciport_pending_tags, slot);
3449 
3450 	rval = AHCI_SUCCESS;
3451 out:
3452 	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3453 	    "ahci_software_reset: %s at port %d",
3454 	    rval == AHCI_SUCCESS ? "succeed" : "failed",
3455 	    port);
3456 
3457 	return (rval);
3458 }
3459 
3460 /*
3461  * AHCI port reset ...; the physical communication between the HBA and device
3462  * on a port are disabled. This is more intrusive.
3463  *
3464  * When an HBA or port reset occurs, Phy communication is going to
3465  * be re-established with the device through a COMRESET followed by the
3466  * normal out-of-band communication sequence defined in Serial ATA. AT
3467  * the end of reset, the device, if working properly, will send a D2H
3468  * Register FIS, which contains the device signature. When the HBA receives
3469  * this FIS, it updates PxTFD.STS and PxTFD.ERR register fields, and updates
3470  * the PxSIG register with the signature.
3471  *
3472  * Staggered spin-up is an optional feature in SATA II, and it enables an HBA
3473  * to individually spin-up attached devices. Please refer to chapter 10.9 of
3474  * AHCI 1.0 spec.
3475  */
3476 /*
3477  * WARNING!!! ahciport_mutex should be acquired, and PxCMD.ST should be also
3478  * cleared before the function is called.
3479  */
3480 static int
3481 ahci_port_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
3482 {
3483 	uint32_t cap_status, port_cmd_status;
3484 	uint32_t port_scontrol, port_sstatus, port_serror;
3485 	uint32_t port_intr_status, port_task_file;
3486 
3487 	int loop_count;
3488 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
3489 
3490 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3491 	    "Port %d port resetting...", port);
3492 	ahci_portp->ahciport_port_state = 0;
3493 
3494 	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3495 	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
3496 
3497 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3498 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3499 
3500 	if (cap_status & AHCI_HBA_CAP_SSS) {
3501 		/*
3502 		 * HBA support staggered spin-up, if the port has
3503 		 * not spin up yet, then force it to do spin-up
3504 		 */
3505 		if (!(port_cmd_status & AHCI_CMD_STATUS_SUD)) {
3506 			if (!(ahci_portp->ahciport_flags
3507 			    & AHCI_PORT_FLAG_SPINUP)) {
3508 				AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3509 				    "Port %d PxCMD.SUD is zero, force "
3510 				    "it to do spin-up", port);
3511 				ahci_portp->ahciport_flags |=
3512 				    AHCI_PORT_FLAG_SPINUP;
3513 			}
3514 		}
3515 	} else {
3516 		/*
3517 		 * HBA doesn't support stagger spin-up, force it
3518 		 * to do normal COMRESET
3519 		 */
3520 		if (ahci_portp->ahciport_flags &
3521 		    AHCI_PORT_FLAG_SPINUP) {
3522 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3523 			    "HBA does not support staggered spin-up "
3524 			    "force it to do normal COMRESET", NULL);
3525 			ahci_portp->ahciport_flags &=
3526 			    ~AHCI_PORT_FLAG_SPINUP;
3527 		}
3528 	}
3529 
3530 	if (!(ahci_portp->ahciport_flags & AHCI_PORT_FLAG_SPINUP)) {
3531 		/* Do normal COMRESET */
3532 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3533 		    "ahci_port_reset: do normal COMRESET", port);
3534 
3535 		/*
3536 		 * According to the spec, SUD bit should be set here,
3537 		 * but JMicron JMB363 doesn't follow it, so remove
3538 		 * the assertion, and just print a debug message.
3539 		 */
3540 #if AHCI_DEBUG
3541 		if (!(port_cmd_status & AHCI_CMD_STATUS_SUD))
3542 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3543 			    "port %d SUD bit not set", port)
3544 #endif
3545 
3546 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3547 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3548 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_COMRESET);
3549 
3550 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3551 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
3552 		    port_scontrol);
3553 
3554 		/* Enable PxCMD.FRE to read device */
3555 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3556 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3557 		    port_cmd_status|AHCI_CMD_STATUS_FRE);
3558 
3559 		/*
3560 		 * Give time for COMRESET to percolate, according to the AHCI
3561 		 * spec, software shall wait at least 1 millisecond before
3562 		 * clearing PxSCTL.DET
3563 		 */
3564 		delay(AHCI_1MS_TICKS*2);
3565 
3566 		/* Fetch the SCONTROL again and rewrite the DET part with 0 */
3567 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3568 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3569 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_NOACTION);
3570 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3571 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
3572 		    port_scontrol);
3573 	} else {
3574 		/* Do staggered spin-up */
3575 		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3576 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3577 		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_NOACTION);
3578 
3579 		/* PxSCTL.DET must be 0 */
3580 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3581 		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
3582 		    port_scontrol);
3583 
3584 		port_cmd_status &= ~AHCI_CMD_STATUS_SUD;
3585 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3586 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3587 		    port_cmd_status);
3588 
3589 		/* 0 -> 1 edge */
3590 		delay(AHCI_1MS_TICKS*2);
3591 
3592 		/* Set PxCMD.SUD to 1 */
3593 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3594 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3595 		port_cmd_status |= AHCI_CMD_STATUS_SUD;
3596 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3597 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3598 		    port_cmd_status);
3599 
3600 		/* Enable PxCMD.FRE to read device */
3601 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3602 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3603 		    port_cmd_status|AHCI_CMD_STATUS_FRE);
3604 	}
3605 
3606 	/*
3607 	 * The port enters P:StartComm state, and HBA tells link layer to
3608 	 * start communication, which involves sending COMRESET to device.
3609 	 * And the HBA resets PxTFD.STS to 7Fh.
3610 	 *
3611 	 * When a COMINIT is received from the device, then the port enters
3612 	 * P:ComInit state. And HBA sets PxTFD.STS to FFh or 80h. HBA sets
3613 	 * PxSSTS.DET to 1h to indicate a device is detected but communication
3614 	 * is not yet established. HBA sets PxSERR.DIAG.X to '1' to indicate
3615 	 * a COMINIT has been received.
3616 	 */
3617 	/*
3618 	 * The DET field is valid only if IPM field indicates
3619 	 * that the interface is in active state.
3620 	 */
3621 	loop_count = 0;
3622 	do {
3623 		port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3624 		    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
3625 
3626 		if (SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) {
3627 			/*
3628 			 * If the interface is not active, the DET field
3629 			 * is considered not accurate. So we want to
3630 			 * continue looping.
3631 			 */
3632 			SSTATUS_SET_DET(port_sstatus, SSTATUS_DET_NODEV);
3633 		}
3634 
3635 		if (loop_count++ > AHCI_POLLRATE_PORT_SSTATUS) {
3636 			/*
3637 			 * We are effectively timing out after 0.1 sec.
3638 			 */
3639 			break;
3640 		}
3641 
3642 		/* Wait for 10 millisec */
3643 		delay(AHCI_10MS_TICKS);
3644 	} while (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM);
3645 
3646 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
3647 	    "ahci_port_reset: 1st loop count: %d, "
3648 	    "port_sstatus = 0x%x port %d",
3649 	    loop_count, port_sstatus, port);
3650 
3651 	if ((SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) ||
3652 	    (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM)) {
3653 		/*
3654 		 * Either the port is not active or there
3655 		 * is no device present.
3656 		 */
3657 		ahci_portp->ahciport_device_type = SATA_DTYPE_NONE;
3658 		return (AHCI_SUCCESS);
3659 	}
3660 
3661 	/* Now we can make sure there is a device connected to the port */
3662 	port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3663 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
3664 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3665 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
3666 
3667 	/*
3668 	 * A COMINIT signal is supposed to be received
3669 	 * PxSERR.DIAG.X or PxIS.PCS should be set
3670 	 */
3671 	if (!(port_intr_status & AHCI_INTR_STATUS_PCS) &&
3672 	    !(port_serror & SERROR_EXCHANGED_ERR)) {
3673 		cmn_err(CE_WARN, "!ahci%d: ahci_port_reset port %d "
3674 		    "COMINIT signal from the device not received",
3675 		    instance, port);
3676 		ahci_portp->ahciport_port_state |= SATA_PSTATE_FAILED;
3677 		return (AHCI_FAILURE);
3678 	}
3679 
3680 	/*
3681 	 * According to the spec, when PxSCTL.DET is set to 0h, upon
3682 	 * receiving a COMINIT from the attached device, PxTFD.STS.BSY
3683 	 * shall be set to '1' by the HBA.
3684 	 *
3685 	 * However, we found JMicron JMB363 doesn't follow this, so
3686 	 * remove this check, and just print a debug message.
3687 	 */
3688 #if AHCI_DEBUG
3689 	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3690 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3691 	if (!(port_task_file & AHCI_TFD_STS_BSY)) {
3692 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_port_reset: "
3693 		    "port %d BSY bit is not set after COMINIT signal "
3694 		    "is received", port);
3695 	}
3696 #endif
3697 
3698 	/*
3699 	 * PxSERR.DIAG.X has to be cleared in order to update PxTFD with
3700 	 * the D2H FIS received by HBA.
3701 	 */
3702 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3703 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
3704 	    SERROR_EXCHANGED_ERR);
3705 
3706 	/*
3707 	 * Devices should return a FIS contains its signature to HBA after
3708 	 * COMINIT signal. Check whether a D2H FIS is received by polling
3709 	 * PxTFD.STS.ERR bit.
3710 	 */
3711 	loop_count = 0;
3712 	do {
3713 		/* Wait for 10 millisec */
3714 		delay(AHCI_10MS_TICKS);
3715 
3716 		if (loop_count++ > AHCI_POLLRATE_PORT_TFD_ERROR) {
3717 			/*
3718 			 * We are effectively timing out after 11 sec.
3719 			 */
3720 			cmn_err(CE_WARN, "!ahci%d: ahci_port_reset port %d "
3721 			    "the device hardware has been initialized and "
3722 			    "the power-up diagnostics failed",
3723 			    instance, port);
3724 
3725 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_port_reset: "
3726 			    "port %d PxTFD.STS.ERR is not set, we need another "
3727 			    "software reset.", port);
3728 
3729 			/* Clear port serror register for the port */
3730 			ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3731 			    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
3732 			    AHCI_SERROR_CLEAR_ALL);
3733 
3734 			/* Try another software reset. */
3735 			if (ahci_software_reset(ahci_ctlp, ahci_portp,
3736 			    port) != AHCI_SUCCESS) {
3737 				ahci_portp->ahciport_port_state |=
3738 				    SATA_PSTATE_FAILED;
3739 				return (AHCI_FAILURE);
3740 			}
3741 			break;
3742 		}
3743 
3744 		/*
3745 		 * The Error bit '1' means COMRESET is finished successfully
3746 		 * The device hardware has been initialized and the power-up
3747 		 * diagnostics successfully completed. The device requests
3748 		 * that the Transport layer transmit a Register - D2H FIS to
3749 		 * the host. (SATA spec 11.5, v2.6)
3750 		 */
3751 		port_task_file =
3752 		    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3753 		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3754 	} while (((port_task_file & AHCI_TFD_ERR_MASK)
3755 	    >> AHCI_TFD_ERR_SHIFT) != AHCI_TFD_ERR_SGS);
3756 
3757 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
3758 	    "ahci_port_reset: 2nd loop count: %d, "
3759 	    "port_task_file = 0x%x port %d",
3760 	    loop_count, port_task_file, port);
3761 
3762 	/* Clear port serror register for the port */
3763 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3764 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
3765 	    AHCI_SERROR_CLEAR_ALL);
3766 
3767 	/* Set port as ready */
3768 	ahci_portp->ahciport_port_state |= SATA_STATE_READY;
3769 
3770 	AHCIDBG(AHCIDBG_INFO|AHCIDBG_ERRS, ahci_ctlp,
3771 	    "ahci_port_reset: succeed at port %d.", port);
3772 	return (AHCI_SUCCESS);
3773 }
3774 
3775 /*
3776  * AHCI HBA reset ...; the entire HBA is reset, and all ports are disabled.
3777  * This is the most intrusive.
3778  *
3779  * When an HBA reset occurs, Phy communication will be re-established with
3780  * the device through a COMRESET followed by the normal out-of-band
3781  * communication sequence defined in Serial ATA. AT the end of reset, the
3782  * device, if working properly, will send a D2H Register FIS, which contains
3783  * the device signature. When the HBA receives this FIS, it updates PxTFD.STS
3784  * and PxTFD.ERR register fields, and updates the PxSIG register with the
3785  * signature.
3786  *
3787  * Remember to set GHC.AE to 1 before calling ahci_hba_reset.
3788  */
3789 static int
3790 ahci_hba_reset(ahci_ctl_t *ahci_ctlp)
3791 {
3792 	ahci_port_t *ahci_portp;
3793 	uint32_t ghc_control;
3794 	uint8_t port;
3795 	int loop_count;
3796 	int rval = AHCI_SUCCESS;
3797 
3798 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp, "HBA resetting",
3799 	    NULL);
3800 
3801 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3802 
3803 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3804 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3805 
3806 	/* Setting GHC.HR to 1, remember GHC.AE is already set to 1 before */
3807 	ghc_control |= AHCI_HBA_GHC_HR;
3808 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3809 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
3810 
3811 	/*
3812 	 * Wait until HBA Reset complete or timeout
3813 	 */
3814 	loop_count = 0;
3815 	do {
3816 		ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3817 		    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3818 
3819 		if (loop_count++ > AHCI_POLLRATE_HBA_RESET) {
3820 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3821 			    "ahci hba reset is timing out, "
3822 			    "ghc_control = 0x%x", ghc_control);
3823 			/* We are effectively timing out after 1 sec. */
3824 			break;
3825 		}
3826 
3827 		/* Wait for 10 millisec */
3828 		delay(AHCI_10MS_TICKS);
3829 	} while (ghc_control & AHCI_HBA_GHC_HR);
3830 
3831 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
3832 	    "ahci_hba_reset: 1st loop count: %d, "
3833 	    "ghc_control = 0x%x", loop_count, ghc_control);
3834 
3835 	if (ghc_control & AHCI_HBA_GHC_HR) {
3836 		/* The hba is not reset for some reasons */
3837 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3838 		    "hba reset failed: HBA in a hung or locked state", NULL);
3839 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
3840 		return (AHCI_FAILURE);
3841 	}
3842 
3843 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3844 		/* Only check implemented ports */
3845 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3846 			continue;
3847 		}
3848 
3849 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
3850 		mutex_enter(&ahci_portp->ahciport_mutex);
3851 
3852 		if (ahci_port_reset(ahci_ctlp, ahci_portp, port)
3853 		    != AHCI_SUCCESS) {
3854 			rval = AHCI_FAILURE;
3855 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3856 			    "ahci_hba_reset: port %d failed", port);
3857 		}
3858 
3859 		mutex_exit(&ahci_portp->ahciport_mutex);
3860 	}
3861 
3862 	/*
3863 	 * Indicate that system software is AHCI aware by setting
3864 	 * GHC.AE to 1
3865 	 */
3866 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3867 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3868 
3869 	ghc_control |= AHCI_HBA_GHC_AE;
3870 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3871 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
3872 
3873 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3874 
3875 	return (rval);
3876 }
3877 
3878 /*
3879  * This routine is only called from AHCI_ATTACH or phyrdy change
3880  * case. It first calls software reset, then stop the port and try to
3881  * read PxSIG register to find the type of device attached to the port.
3882  *
3883  * The caller should make sure a valid device exists on specified port and
3884  * physical communication has been established so that the signature could
3885  * be retrieved by software reset.
3886  *
3887  * WARNING!!! ahciport_mutex should be acquired before the function
3888  * is called. And the port interrupt is disabled.
3889  */
3890 static void
3891 ahci_find_dev_signature(ahci_ctl_t *ahci_ctlp,
3892     ahci_port_t *ahci_portp, uint8_t port)
3893 {
3894 	uint32_t signature;
3895 
3896 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3897 	    "ahci_find_dev_signature enter: port %d", port);
3898 
3899 	ahci_portp->ahciport_device_type = SATA_DTYPE_UNKNOWN;
3900 
3901 	/* Issue a software reset to get the signature */
3902 	if (ahci_software_reset(ahci_ctlp, ahci_portp, port)
3903 	    != AHCI_SUCCESS) {
3904 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3905 		    "ahci_find_dev_signature: software reset failed "
3906 		    "at port %d, cannot get signature.", port);
3907 		ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
3908 		return;
3909 	}
3910 
3911 	/*
3912 	 * ahci_software_reset has started the port, so we need manually stop
3913 	 * the port again.
3914 	 */
3915 	if (ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp, port)
3916 	    != AHCI_SUCCESS) {
3917 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3918 		    "ahci_find_dev_signature: cannot stop port %d.", port);
3919 		ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
3920 		return;
3921 	}
3922 
3923 	/* Now we can make sure that a valid signature is received. */
3924 	signature = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3925 	    (uint32_t *)AHCI_PORT_PxSIG(ahci_ctlp, port));
3926 
3927 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_INFO, ahci_ctlp,
3928 	    "ahci_find_dev_signature: port %d signature = 0x%x",
3929 	    port, signature);
3930 
3931 	switch (signature) {
3932 
3933 	case AHCI_SIGNATURE_DISK:
3934 		ahci_portp->ahciport_device_type = SATA_DTYPE_ATADISK;
3935 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3936 		    "Disk is found at port: %d", port);
3937 		break;
3938 
3939 	case AHCI_SIGNATURE_ATAPI:
3940 		ahci_portp->ahciport_device_type = SATA_DTYPE_ATAPI;
3941 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3942 		    "ATAPI device is found at port: %d", port);
3943 		break;
3944 
3945 	case AHCI_SIGNATURE_PORT_MULTIPLIER:
3946 		ahci_portp->ahciport_device_type = SATA_DTYPE_PMULT;
3947 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3948 		    "Port Multiplier is found at port: %d", port);
3949 		break;
3950 
3951 	default:
3952 		ahci_portp->ahciport_device_type = SATA_DTYPE_UNKNOWN;
3953 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3954 		    "Unknown device is found at port: %d", port);
3955 	}
3956 }
3957 
3958 /*
3959  * According to the spec, to reliably detect hot plug removals, software
3960  * must disable interface power management. Software should perform the
3961  * following initialization on a port after a device is attached:
3962  *   Set PxSCTL.IPM to 3h to disable interface state transitions
3963  *   Set PxCMD.ALPE to '0' to disable aggressive power management
3964  *   Disable device initiated interface power management by SET FEATURE
3965  *
3966  * We can ignore the last item because by default the feature is disabled
3967  */
3968 static void
3969 ahci_disable_interface_pm(ahci_ctl_t *ahci_ctlp, uint8_t port)
3970 {
3971 	uint32_t port_scontrol, port_cmd_status;
3972 
3973 	port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3974 	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3975 	SCONTROL_SET_IPM(port_scontrol, SCONTROL_IPM_DISABLE_BOTH);
3976 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3977 	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port), port_scontrol);
3978 
3979 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3980 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3981 	port_cmd_status &= ~AHCI_CMD_STATUS_ALPE;
3982 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3983 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port), port_cmd_status);
3984 }
3985 
3986 /*
3987  * Start the port - set PxCMD.ST to 1, if PxCMD.FRE is not set
3988  * to 1, then set it firstly.
3989  *
3990  * Each port contains two major DMA engines. One DMA engine walks through
3991  * the command list, and is controlled by PxCMD.ST. The second DMA engine
3992  * copies received FISes into system memory, and is controlled by PxCMD.FRE.
3993  *
3994  * Software shall not set PxCMD.ST to '1' until it verifies that PxCMD.CR
3995  * is '0' and has set PxCMD.FRE is '1'. And software shall not clear
3996  * PxCMD.FRE while PxCMD.ST or PxCMD.CR is set '1'.
3997  *
3998  * Software shall not set PxCMD.ST to '1' unless a functional device is
3999  * present on the port(as determined by PxTFD.STS.BSY = '0',
4000  * PxTFD.STS.DRQ = '0', and PxSSTS.DET = 3h).
4001  *
4002  * WARNING!!! ahciport_mutex should be acquired before the function
4003  * is called.
4004  */
4005 static int
4006 ahci_start_port(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
4007 {
4008 	uint32_t port_cmd_status;
4009 
4010 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_start_port: %d enter", port);
4011 
4012 	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED) {
4013 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port failed "
4014 		    "the state for port %d is 0x%x",
4015 		    port, ahci_portp->ahciport_port_state);
4016 		return (AHCI_FAILURE);
4017 	}
4018 
4019 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
4020 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port failed "
4021 		    "no device is attached at port %d", port);
4022 		return (AHCI_FAILURE);
4023 	}
4024 
4025 	/* First to set PxCMD.FRE before setting PxCMD.ST. */
4026 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4027 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4028 
4029 	if (!(port_cmd_status & AHCI_CMD_STATUS_FRE)) {
4030 		port_cmd_status |= AHCI_CMD_STATUS_FRE;
4031 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4032 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4033 		    port_cmd_status);
4034 	}
4035 
4036 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4037 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4038 
4039 	port_cmd_status |= AHCI_CMD_STATUS_ST;
4040 
4041 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4042 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4043 	    port_cmd_status);
4044 
4045 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_STARTED;
4046 
4047 	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port: "
4048 	    "PxCMD.ST set to '1' at port %d", port);
4049 
4050 	return (AHCI_SUCCESS);
4051 }
4052 
4053 /*
4054  * Allocate the ahci_port_t including Received FIS and Command List.
4055  * The argument - port is the physical port number, and not logical
4056  * port number seen by the SATA framework.
4057  *
4058  * WARNING!!! ahcictl_mutex should be acquired before the function
4059  * is called.
4060  */
4061 static int
4062 ahci_alloc_port_state(ahci_ctl_t *ahci_ctlp, uint8_t port)
4063 {
4064 	dev_info_t *dip = ahci_ctlp->ahcictl_dip;
4065 	ahci_port_t *ahci_portp;
4066 	char taskq_name[64] = "event_handle_taskq";
4067 
4068 	ahci_portp =
4069 	    (ahci_port_t *)kmem_zalloc(sizeof (ahci_port_t), KM_SLEEP);
4070 
4071 	ahci_ctlp->ahcictl_ports[port] = ahci_portp;
4072 	ahci_portp->ahciport_port_num = port;
4073 
4074 	/* Intialize the port condition variable */
4075 	cv_init(&ahci_portp->ahciport_cv, NULL, CV_DRIVER, NULL);
4076 
4077 	/* Initialize the port mutex */
4078 	mutex_init(&ahci_portp->ahciport_mutex, NULL, MUTEX_DRIVER,
4079 	    (void *)(uintptr_t)ahci_ctlp->ahcictl_intr_pri);
4080 
4081 	mutex_enter(&ahci_portp->ahciport_mutex);
4082 
4083 	/*
4084 	 * Allocate memory for received FIS structure and
4085 	 * command list for this port
4086 	 */
4087 	if (ahci_alloc_rcvd_fis(ahci_ctlp, ahci_portp, port) != AHCI_SUCCESS) {
4088 		goto err_case1;
4089 	}
4090 
4091 	if (ahci_alloc_cmd_list(ahci_ctlp, ahci_portp, port) != AHCI_SUCCESS) {
4092 		goto err_case2;
4093 	}
4094 
4095 	(void) snprintf(taskq_name + strlen(taskq_name),
4096 	    sizeof (taskq_name) - strlen(taskq_name),
4097 	    "_port%d", port);
4098 
4099 	/* Create the taskq for the port */
4100 	if ((ahci_portp->ahciport_event_taskq = ddi_taskq_create(dip,
4101 	    taskq_name, 2, TASKQ_DEFAULTPRI, 0)) == NULL) {
4102 		cmn_err(CE_WARN, "!ahci%d: ddi_taskq_create failed for event "
4103 		    "handle", ddi_get_instance(ahci_ctlp->ahcictl_dip));
4104 		goto err_case3;
4105 	}
4106 
4107 	/* Allocate the argument for the taskq */
4108 	ahci_portp->ahciport_event_args =
4109 	    kmem_zalloc(sizeof (ahci_event_arg_t), KM_SLEEP);
4110 
4111 	if (ahci_portp->ahciport_event_args == NULL)
4112 		goto err_case4;
4113 
4114 	mutex_exit(&ahci_portp->ahciport_mutex);
4115 
4116 	return (AHCI_SUCCESS);
4117 
4118 err_case4:
4119 	ddi_taskq_destroy(ahci_portp->ahciport_event_taskq);
4120 
4121 err_case3:
4122 	ahci_dealloc_cmd_list(ahci_ctlp, ahci_portp);
4123 
4124 err_case2:
4125 	ahci_dealloc_rcvd_fis(ahci_portp);
4126 
4127 err_case1:
4128 	mutex_exit(&ahci_portp->ahciport_mutex);
4129 	mutex_destroy(&ahci_portp->ahciport_mutex);
4130 	cv_destroy(&ahci_portp->ahciport_cv);
4131 
4132 	kmem_free(ahci_portp, sizeof (ahci_port_t));
4133 
4134 	return (AHCI_FAILURE);
4135 }
4136 
4137 /*
4138  * Reverse of ahci_dealloc_port_state().
4139  *
4140  * WARNING!!! ahcictl_mutex should be acquired before the function
4141  * is called.
4142  */
4143 static void
4144 ahci_dealloc_port_state(ahci_ctl_t *ahci_ctlp, uint8_t port)
4145 {
4146 	ahci_port_t *ahci_portp = ahci_ctlp->ahcictl_ports[port];
4147 
4148 	ASSERT(ahci_portp != NULL);
4149 
4150 	mutex_enter(&ahci_portp->ahciport_mutex);
4151 	kmem_free(ahci_portp->ahciport_event_args, sizeof (ahci_event_arg_t));
4152 	ahci_portp->ahciport_event_args = NULL;
4153 	ddi_taskq_destroy(ahci_portp->ahciport_event_taskq);
4154 	ahci_dealloc_cmd_list(ahci_ctlp, ahci_portp);
4155 	ahci_dealloc_rcvd_fis(ahci_portp);
4156 	mutex_exit(&ahci_portp->ahciport_mutex);
4157 
4158 	mutex_destroy(&ahci_portp->ahciport_mutex);
4159 	cv_destroy(&ahci_portp->ahciport_cv);
4160 
4161 	kmem_free(ahci_portp, sizeof (ahci_port_t));
4162 
4163 	ahci_ctlp->ahcictl_ports[port] = NULL;
4164 }
4165 
4166 /*
4167  * Allocates memory for the Received FIS Structure
4168  *
4169  * WARNING!!! ahciport_mutex should be acquired before the function
4170  * is called.
4171  */
4172 static int
4173 ahci_alloc_rcvd_fis(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4174     uint8_t port)
4175 {
4176 	size_t rcvd_fis_size;
4177 	size_t ret_len;
4178 	uint_t cookie_count;
4179 
4180 	rcvd_fis_size = sizeof (ahci_rcvd_fis_t);
4181 
4182 	/* allocate rcvd FIS dma handle. */
4183 	if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
4184 	    &ahci_ctlp->ahcictl_rcvd_fis_dma_attr,
4185 	    DDI_DMA_SLEEP,
4186 	    NULL,
4187 	    &ahci_portp->ahciport_rcvd_fis_dma_handle) !=
4188 	    DDI_SUCCESS) {
4189 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4190 		    "rcvd FIS dma handle alloc failed", NULL);
4191 
4192 		return (AHCI_FAILURE);
4193 	}
4194 
4195 	if (ddi_dma_mem_alloc(ahci_portp->ahciport_rcvd_fis_dma_handle,
4196 	    rcvd_fis_size,
4197 	    &accattr,
4198 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
4199 	    DDI_DMA_SLEEP,
4200 	    NULL,
4201 	    (caddr_t *)&ahci_portp->ahciport_rcvd_fis,
4202 	    &ret_len,
4203 	    &ahci_portp->ahciport_rcvd_fis_acc_handle) != NULL) {
4204 
4205 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4206 		    "rcvd FIS dma mem alloc fail", NULL);
4207 		/* error.. free the dma handle. */
4208 		ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
4209 		return (AHCI_FAILURE);
4210 	}
4211 
4212 	if (ddi_dma_addr_bind_handle(ahci_portp->ahciport_rcvd_fis_dma_handle,
4213 	    NULL,
4214 	    (caddr_t)ahci_portp->ahciport_rcvd_fis,
4215 	    rcvd_fis_size,
4216 	    DDI_DMA_CONSISTENT,
4217 	    DDI_DMA_SLEEP,
4218 	    NULL,
4219 	    &ahci_portp->ahciport_rcvd_fis_dma_cookie,
4220 	    &cookie_count) !=  DDI_DMA_MAPPED) {
4221 
4222 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4223 		    "rcvd FIS dma handle bind fail", NULL);
4224 		/*  error.. free the dma handle & free the memory. */
4225 		ddi_dma_mem_free(&ahci_portp->ahciport_rcvd_fis_acc_handle);
4226 		ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
4227 		return (AHCI_FAILURE);
4228 	}
4229 
4230 	bzero((void *)ahci_portp->ahciport_rcvd_fis, rcvd_fis_size);
4231 
4232 	/* Config Port Received FIS Base Address */
4233 	ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
4234 	    (uint64_t *)AHCI_PORT_PxFB(ahci_ctlp, port),
4235 	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
4236 
4237 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "64-bit, dma address: 0x%llx",
4238 	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
4239 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "32-bit, dma address: 0x%x",
4240 	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_address);
4241 
4242 	return (AHCI_SUCCESS);
4243 }
4244 
4245 /*
4246  * Deallocates the Received FIS Structure
4247  *
4248  * WARNING!!! ahciport_mutex should be acquired before the function
4249  * is called.
4250  */
4251 static void
4252 ahci_dealloc_rcvd_fis(ahci_port_t *ahci_portp)
4253 {
4254 	/* Unbind the cmd list dma handle first. */
4255 	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_rcvd_fis_dma_handle);
4256 
4257 	/* Then free the underlying memory. */
4258 	ddi_dma_mem_free(&ahci_portp->ahciport_rcvd_fis_acc_handle);
4259 
4260 	/* Now free the handle itself. */
4261 	ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
4262 }
4263 
4264 /*
4265  * Allocates memory for the Command List, which contains up to 32 entries.
4266  * Each entry contains a command header, which is a 32-byte structure that
4267  * includes the pointer to the command table.
4268  *
4269  * WARNING!!! ahciport_mutex should be acquired before the function
4270  * is called.
4271  */
4272 static int
4273 ahci_alloc_cmd_list(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4274     uint8_t port)
4275 {
4276 	size_t cmd_list_size;
4277 	size_t ret_len;
4278 	uint_t cookie_count;
4279 
4280 	cmd_list_size =
4281 	    ahci_ctlp->ahcictl_num_cmd_slots * sizeof (ahci_cmd_header_t);
4282 
4283 	/* allocate cmd list dma handle. */
4284 	if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
4285 	    &ahci_ctlp->ahcictl_cmd_list_dma_attr,
4286 	    DDI_DMA_SLEEP,
4287 	    NULL,
4288 	    &ahci_portp->ahciport_cmd_list_dma_handle) != DDI_SUCCESS) {
4289 
4290 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4291 		    "cmd list dma handle alloc failed", NULL);
4292 		return (AHCI_FAILURE);
4293 	}
4294 
4295 	if (ddi_dma_mem_alloc(ahci_portp->ahciport_cmd_list_dma_handle,
4296 	    cmd_list_size,
4297 	    &accattr,
4298 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
4299 	    DDI_DMA_SLEEP,
4300 	    NULL,
4301 	    (caddr_t *)&ahci_portp->ahciport_cmd_list,
4302 	    &ret_len,
4303 	    &ahci_portp->ahciport_cmd_list_acc_handle) != NULL) {
4304 
4305 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4306 		    "cmd list dma mem alloc fail", NULL);
4307 		/* error.. free the dma handle. */
4308 		ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4309 		return (AHCI_FAILURE);
4310 	}
4311 
4312 	if (ddi_dma_addr_bind_handle(ahci_portp->ahciport_cmd_list_dma_handle,
4313 	    NULL,
4314 	    (caddr_t)ahci_portp->ahciport_cmd_list,
4315 	    cmd_list_size,
4316 	    DDI_DMA_CONSISTENT,
4317 	    DDI_DMA_SLEEP,
4318 	    NULL,
4319 	    &ahci_portp->ahciport_cmd_list_dma_cookie,
4320 	    &cookie_count) !=  DDI_DMA_MAPPED) {
4321 
4322 		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4323 		    "cmd list dma handle bind fail", NULL);
4324 		/*  error.. free the dma handle & free the memory. */
4325 		ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
4326 		ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4327 		return (AHCI_FAILURE);
4328 	}
4329 
4330 	bzero((void *)ahci_portp->ahciport_cmd_list, cmd_list_size);
4331 
4332 	/* Config Port Command List Base Address */
4333 	ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
4334 	    (uint64_t *)AHCI_PORT_PxCLB(ahci_ctlp, port),
4335 	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
4336 
4337 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "64-bit, dma address: 0x%llx",
4338 	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
4339 
4340 	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "32-bit, dma address: 0x%x",
4341 	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_address);
4342 
4343 	if (ahci_alloc_cmd_tables(ahci_ctlp, ahci_portp) != AHCI_SUCCESS) {
4344 		goto err_out;
4345 	}
4346 
4347 	return (AHCI_SUCCESS);
4348 
4349 err_out:
4350 	/* Unbind the cmd list dma handle first. */
4351 	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_cmd_list_dma_handle);
4352 
4353 	/* Then free the underlying memory. */
4354 	ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
4355 
4356 	/* Now free the handle itself. */
4357 	ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4358 
4359 	return (AHCI_FAILURE);
4360 }
4361 
4362 /*
4363  * Deallocates the Command List
4364  *
4365  * WARNING!!! ahciport_mutex should be acquired before the function
4366  * is called.
4367  */
4368 static void
4369 ahci_dealloc_cmd_list(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
4370 {
4371 	/* First dealloc command table */
4372 	ahci_dealloc_cmd_tables(ahci_ctlp, ahci_portp);
4373 
4374 	/* Unbind the cmd list dma handle first. */
4375 	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_cmd_list_dma_handle);
4376 
4377 	/* Then free the underlying memory. */
4378 	ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
4379 
4380 	/* Now free the handle itself. */
4381 	ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4382 }
4383 
4384 /*
4385  * Allocates memory for all Command Tables, which contains Command FIS,
4386  * ATAPI Command and Physical Region Descriptor Table.
4387  *
4388  * WARNING!!! ahciport_mutex should be acquired before the function
4389  * is called.
4390  */
4391 static int
4392 ahci_alloc_cmd_tables(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
4393 {
4394 	size_t ret_len;
4395 	ddi_dma_cookie_t cmd_table_dma_cookie;
4396 	uint_t cookie_count;
4397 	int slot;
4398 
4399 	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
4400 	    "ahci_alloc_cmd_tables: port %d enter",
4401 	    ahci_portp->ahciport_port_num);
4402 
4403 	for (slot = 0; slot < ahci_ctlp->ahcictl_num_cmd_slots; slot++) {
4404 		/* Allocate cmd table dma handle. */
4405 		if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
4406 		    &ahci_ctlp->ahcictl_cmd_table_dma_attr,
4407 		    DDI_DMA_SLEEP,
4408 		    NULL,
4409 		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]) !=
4410 		    DDI_SUCCESS) {
4411 
4412 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4413 			    "cmd table dma handle alloc failed", NULL);
4414 
4415 			goto err_out;
4416 		}
4417 
4418 		if (ddi_dma_mem_alloc(
4419 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot],
4420 		    ahci_cmd_table_size,
4421 		    &accattr,
4422 		    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
4423 		    DDI_DMA_SLEEP,
4424 		    NULL,
4425 		    (caddr_t *)&ahci_portp->ahciport_cmd_tables[slot],
4426 		    &ret_len,
4427 		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]) !=
4428 		    NULL) {
4429 
4430 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4431 			    "cmd table dma mem alloc fail", NULL);
4432 
4433 			/* error.. free the dma handle. */
4434 			ddi_dma_free_handle(
4435 			    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4436 			goto err_out;
4437 		}
4438 
4439 		if (ddi_dma_addr_bind_handle(
4440 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot],
4441 		    NULL,
4442 		    (caddr_t)ahci_portp->ahciport_cmd_tables[slot],
4443 		    ahci_cmd_table_size,
4444 		    DDI_DMA_CONSISTENT,
4445 		    DDI_DMA_SLEEP,
4446 		    NULL,
4447 		    &cmd_table_dma_cookie,
4448 		    &cookie_count) !=  DDI_DMA_MAPPED) {
4449 
4450 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4451 			    "cmd table dma handle bind fail", NULL);
4452 			/*  error.. free the dma handle & free the memory. */
4453 			ddi_dma_mem_free(
4454 			    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
4455 			ddi_dma_free_handle(
4456 			    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4457 			goto err_out;
4458 		}
4459 
4460 		bzero((void *)ahci_portp->ahciport_cmd_tables[slot],
4461 		    ahci_cmd_table_size);
4462 
4463 		/* Config Port Command Table Base Address */
4464 		SET_COMMAND_TABLE_BASE_ADDR(
4465 		    (&ahci_portp->ahciport_cmd_list[slot]),
4466 		    cmd_table_dma_cookie.dmac_laddress & 0xffffffffull);
4467 
4468 #ifndef __lock_lint
4469 		SET_COMMAND_TABLE_BASE_ADDR_UPPER(
4470 		    (&ahci_portp->ahciport_cmd_list[slot]),
4471 		    cmd_table_dma_cookie.dmac_laddress >> 32);
4472 #endif
4473 	}
4474 
4475 	return (AHCI_SUCCESS);
4476 err_out:
4477 
4478 	for (slot--; slot >= 0; slot--) {
4479 		/* Unbind the cmd table dma handle first */
4480 		(void) ddi_dma_unbind_handle(
4481 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4482 
4483 		/* Then free the underlying memory */
4484 		ddi_dma_mem_free(
4485 		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
4486 
4487 		/* Now free the handle itself */
4488 		ddi_dma_free_handle(
4489 		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4490 	}
4491 
4492 	return (AHCI_FAILURE);
4493 }
4494 
4495 /*
4496  * Deallocates memory for all Command Tables.
4497  *
4498  * WARNING!!! ahciport_mutex should be acquired before the function
4499  * is called.
4500  */
4501 static void
4502 ahci_dealloc_cmd_tables(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
4503 {
4504 	int slot;
4505 
4506 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
4507 	    "ahci_dealloc_cmd_tables: %d enter",
4508 	    ahci_portp->ahciport_port_num);
4509 
4510 	for (slot = 0; slot < ahci_ctlp->ahcictl_num_cmd_slots; slot++) {
4511 		/* Unbind the cmd table dma handle first. */
4512 		(void) ddi_dma_unbind_handle(
4513 		    ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4514 
4515 		/* Then free the underlying memory. */
4516 		ddi_dma_mem_free(
4517 		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
4518 
4519 		/* Now free the handle itself. */
4520 		ddi_dma_free_handle(
4521 		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4522 	}
4523 }
4524 
4525 /*
4526  * WARNING!!! ahciport_mutex should be acquired before the function
4527  * is called.
4528  */
4529 static void
4530 ahci_update_sata_registers(ahci_ctl_t *ahci_ctlp, uint8_t port,
4531     sata_device_t *sd)
4532 {
4533 	sd->satadev_scr.sstatus =
4534 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4535 	    (uint32_t *)(AHCI_PORT_PxSSTS(ahci_ctlp, port)));
4536 	sd->satadev_scr.serror =
4537 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4538 	    (uint32_t *)(AHCI_PORT_PxSERR(ahci_ctlp, port)));
4539 	sd->satadev_scr.scontrol =
4540 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4541 	    (uint32_t *)(AHCI_PORT_PxSCTL(ahci_ctlp, port)));
4542 	sd->satadev_scr.sactive =
4543 	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4544 	    (uint32_t *)(AHCI_PORT_PxSACT(ahci_ctlp, port)));
4545 }
4546 
4547 /*
4548  * For poll mode, ahci_port_intr will be called to emulate the interrupt
4549  */
4550 static void
4551 ahci_port_intr(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
4552 {
4553 	uint32_t port_intr_status;
4554 	uint32_t port_intr_enable;
4555 
4556 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
4557 	    "ahci_port_intr enter: port %d", port);
4558 
4559 	mutex_enter(&ahci_portp->ahciport_mutex);
4560 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_POLLING) {
4561 		/* For SATA_OPMODE_POLLING commands */
4562 		port_intr_enable =
4563 		    (AHCI_INTR_STATUS_DHRS |
4564 		    AHCI_INTR_STATUS_PSS |
4565 		    AHCI_INTR_STATUS_SDBS |
4566 		    AHCI_INTR_STATUS_UFS |
4567 		    AHCI_INTR_STATUS_PCS |
4568 		    AHCI_INTR_STATUS_PRCS |
4569 		    AHCI_INTR_STATUS_OFS |
4570 		    AHCI_INTR_STATUS_INFS |
4571 		    AHCI_INTR_STATUS_IFS |
4572 		    AHCI_INTR_STATUS_HBDS |
4573 		    AHCI_INTR_STATUS_HBFS |
4574 		    AHCI_INTR_STATUS_TFES);
4575 		mutex_exit(&ahci_portp->ahciport_mutex);
4576 		goto next;
4577 	}
4578 	mutex_exit(&ahci_portp->ahciport_mutex);
4579 
4580 	/*
4581 	 * port_intr_enable indicates that the corresponding interrrupt
4582 	 * reporting is enabled.
4583 	 */
4584 	port_intr_enable = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4585 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port));
4586 next:
4587 	/*
4588 	 * port_intr_stats indicates that the corresponding interrupt
4589 	 * condition is active.
4590 	 */
4591 	port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4592 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
4593 
4594 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4595 	    "ahci_port_intr: port %d, port_intr_status = 0x%x, "
4596 	    "port_intr_enable = 0x%x",
4597 	    port, port_intr_status, port_intr_enable);
4598 
4599 	port_intr_status &= port_intr_enable;
4600 
4601 	/* First clear the port interrupts status */
4602 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4603 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
4604 	    port_intr_status);
4605 
4606 	/* Check the completed non-queued commands */
4607 	if (port_intr_status & (AHCI_INTR_STATUS_DHRS |
4608 	    AHCI_INTR_STATUS_PSS)) {
4609 		(void) ahci_intr_cmd_cmplt(ahci_ctlp,
4610 		    ahci_portp, port);
4611 	}
4612 
4613 	/* Check the completed queued commands */
4614 	if (port_intr_status & AHCI_INTR_STATUS_SDBS) {
4615 		(void) ahci_intr_set_device_bits(ahci_ctlp,
4616 		    ahci_portp, port);
4617 	}
4618 
4619 	/* Check the port connect change status interrupt bit */
4620 	if (port_intr_status & AHCI_INTR_STATUS_PCS) {
4621 		(void) ahci_intr_port_connect_change(ahci_ctlp,
4622 		    ahci_portp, port);
4623 	}
4624 
4625 	/* Check the device mechanical presence status interrupt bit */
4626 	if (port_intr_status & AHCI_INTR_STATUS_DMPS) {
4627 		(void) ahci_intr_device_mechanical_presence_status(
4628 		    ahci_ctlp, ahci_portp, port);
4629 	}
4630 
4631 	/* Check the PhyRdy change status interrupt bit */
4632 	if (port_intr_status & AHCI_INTR_STATUS_PRCS) {
4633 		(void) ahci_intr_phyrdy_change(ahci_ctlp, ahci_portp,
4634 		    port);
4635 	}
4636 
4637 	/*
4638 	 * Check the non-fatal error interrupt bits, there are three
4639 	 * kinds of non-fatal errors at the time being:
4640 	 *
4641 	 *    PxIS.UFS - Unknown FIS Error
4642 	 *    PxIS.OFS - Overflow Error
4643 	 *    PxIS.INFS - Interface Non-Fatal Error
4644 	 *
4645 	 * For these non-fatal errors, the HBA can continue to operate,
4646 	 * so the driver just log the error messages.
4647 	 */
4648 	if (port_intr_status & (AHCI_INTR_STATUS_UFS |
4649 	    AHCI_INTR_STATUS_OFS |
4650 	    AHCI_INTR_STATUS_INFS)) {
4651 		(void) ahci_intr_non_fatal_error(ahci_ctlp, ahci_portp,
4652 		    port, port_intr_status);
4653 	}
4654 
4655 	/*
4656 	 * Check the fatal error interrupt bits, there are four kinds
4657 	 * of fatal errors for AHCI controllers:
4658 	 *
4659 	 *    PxIS.HBFS - Host Bus Fatal Error
4660 	 *    PxIS.HBDS - Host Bus Data Error
4661 	 *    PxIS.IFS - Interface Fatal Error
4662 	 *    PxIS.TFES - Task File Error
4663 	 *
4664 	 * The fatal error means the HBA can not recover from it by
4665 	 * itself, and it will try to abort the transfer, and the software
4666 	 * must intervene to restart the port.
4667 	 */
4668 	if (port_intr_status & (AHCI_INTR_STATUS_IFS |
4669 	    AHCI_INTR_STATUS_HBDS |
4670 	    AHCI_INTR_STATUS_HBFS |
4671 	    AHCI_INTR_STATUS_TFES))
4672 		(void) ahci_intr_fatal_error(ahci_ctlp, ahci_portp,
4673 		    port, port_intr_status);
4674 
4675 	/* Check the cold port detect interrupt bit */
4676 	if (port_intr_status & AHCI_INTR_STATUS_CPDS) {
4677 		(void) ahci_intr_cold_port_detect(ahci_ctlp, ahci_portp, port);
4678 	}
4679 
4680 	/* Second clear the corresponding bit in IS.IPS */
4681 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4682 	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp), (0x1 << port));
4683 }
4684 
4685 /*
4686  * Interrupt service handler
4687  */
4688 static uint_t
4689 ahci_intr(caddr_t arg1, caddr_t arg2)
4690 {
4691 #ifndef __lock_lint
4692 	_NOTE(ARGUNUSED(arg2))
4693 #endif
4694 	/* LINTED */
4695 	ahci_ctl_t *ahci_ctlp = (ahci_ctl_t *)arg1;
4696 	ahci_port_t *ahci_portp;
4697 	int32_t global_intr_status;
4698 	uint8_t port;
4699 
4700 	/*
4701 	 * global_intr_status indicates that the corresponding port has
4702 	 * an interrupt pending.
4703 	 */
4704 	global_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4705 	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp));
4706 
4707 	if (!(global_intr_status & ahci_ctlp->ahcictl_ports_implemented)) {
4708 		/* The interrupt is not ours */
4709 		return (DDI_INTR_UNCLAIMED);
4710 	}
4711 
4712 	/* Loop for all the ports */
4713 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
4714 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
4715 			continue;
4716 		}
4717 		if (!((0x1 << port) & global_intr_status)) {
4718 			continue;
4719 		}
4720 
4721 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
4722 
4723 		/* Call ahci_port_intr */
4724 		ahci_port_intr(ahci_ctlp, ahci_portp, port);
4725 	}
4726 
4727 	return (DDI_INTR_CLAIMED);
4728 }
4729 
4730 /*
4731  * For non-queued commands, when the corresponding bit in the PxCI register
4732  * is cleared, it means the command is completed successfully. And according
4733  * to the HBA state machine, there are three conditions which possibly will
4734  * try to clear the PxCI register bit.
4735  *	1. Receive one D2H Register FIS which is with 'I' bit set
4736  *	2. Update PIO Setup FIS
4737  *	3. Transmit a command and receive R_OK if CTBA.C is set (software reset)
4738  *
4739  * Process completed non-queued commands when the interrupt status bit -
4740  * AHCI_INTR_STATUS_DHRS or AHCI_INTR_STATUS_PSS is set.
4741  *
4742  * AHCI_INTR_STATUS_DHRS means a D2H Register FIS has been received
4743  * with the 'I' bit set. And the following commands will send thus
4744  * FIS with 'I' bit set upon the successful completion:
4745  * 	1. Non-data commands
4746  * 	2. DMA data-in command
4747  * 	3. DMA data-out command
4748  * 	4. PIO data-out command
4749  *	5. PACKET non-data commands
4750  *	6. PACKET PIO data-in command
4751  *	7. PACKET PIO data-out command
4752  *	8. PACKET DMA data-in command
4753  *	9. PACKET DMA data-out command
4754  *
4755  * AHCI_INTR_STATUS_PSS means a PIO Setup FIS has been received
4756  * with the 'I' bit set. And the following commands will send this
4757  * FIS upon the successful completion:
4758  * 	1. PIO data-in command
4759  */
4760 static int
4761 ahci_intr_cmd_cmplt(ahci_ctl_t *ahci_ctlp,
4762     ahci_port_t *ahci_portp, uint8_t port)
4763 {
4764 	uint32_t port_cmd_issue = 0;
4765 	uint32_t finished_tags;
4766 	int finished_slot;
4767 	sata_pkt_t *satapkt;
4768 	ahci_fis_d2h_register_t *rcvd_fisp;
4769 #if AHCI_DEBUG
4770 	ahci_cmd_header_t *cmd_header;
4771 	uint32_t cmd_dmacount;
4772 #endif
4773 
4774 	mutex_enter(&ahci_portp->ahciport_mutex);
4775 
4776 	if (!ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
4777 	    !NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
4778 		/*
4779 		 * Spurious interrupt. Nothing to be done.
4780 		 */
4781 		mutex_exit(&ahci_portp->ahciport_mutex);
4782 		return (AHCI_SUCCESS);
4783 	}
4784 
4785 	port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4786 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4787 
4788 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
4789 		/* Slot 0 is always used during error recovery */
4790 		finished_tags = 0x1 & ~port_cmd_issue;
4791 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4792 		    "ahci_intr_cmd_cmplt: port %d the sata pkt for error "
4793 		    "retrieval is finished, and finished_tags = 0x%x",
4794 		    port, finished_tags);
4795 	} else {
4796 		finished_tags = ahci_portp->ahciport_pending_tags &
4797 		    ~port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp);
4798 	}
4799 
4800 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4801 	    "ahci_intr_cmd_cmplt: pending_tags = 0x%x, "
4802 	    "port_cmd_issue = 0x%x finished_tags = 0x%x",
4803 	    ahci_portp->ahciport_pending_tags, port_cmd_issue,
4804 	    finished_tags);
4805 
4806 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
4807 	    (finished_tags == 0x1)) {
4808 		satapkt = ahci_portp->ahciport_err_retri_pkt;
4809 		ASSERT(satapkt != NULL);
4810 
4811 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4812 		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
4813 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
4814 
4815 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
4816 		goto out;
4817 	}
4818 
4819 	while (finished_tags) {
4820 		finished_slot = ddi_ffs(finished_tags) - 1;
4821 		if (finished_slot == -1) {
4822 			goto out;
4823 		}
4824 
4825 		satapkt = ahci_portp->ahciport_slot_pkts[finished_slot];
4826 		ASSERT(satapkt != NULL);
4827 #if AHCI_DEBUG
4828 		/*
4829 		 * For non-native queued commands, the PRD byte count field
4830 		 * shall contain an accurate count of the number of bytes
4831 		 * transferred for the command before the PxCI bit is cleared
4832 		 * to '0' for the command.
4833 		 *
4834 		 * The purpose of this field is to let software know how many
4835 		 * bytes transferred for a given operation in order to
4836 		 * determine if underflow occurred. When issuing native command
4837 		 * queuing commands, this field should not be used and is not
4838 		 * required to be valid since in this case underflow is always
4839 		 * illegal.
4840 		 *
4841 		 * For data reads, the HBA will update its PRD byte count with
4842 		 * the total number of bytes received from the last FIS, and
4843 		 * may be able to continue normally. For data writes, the
4844 		 * device will detect an error, and HBA most likely will get
4845 		 * a fatal error.
4846 		 *
4847 		 * Therefore, here just put code to debug part. And please
4848 		 * refer to the comment above ahci_intr_fatal_error for the
4849 		 * definition of underflow error.
4850 		 */
4851 		cmd_dmacount =
4852 		    ahci_portp->ahciport_prd_bytecounts[finished_slot];
4853 		if (cmd_dmacount) {
4854 			cmd_header =
4855 			    &ahci_portp->ahciport_cmd_list[finished_slot];
4856 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_PRDT, ahci_ctlp,
4857 			    "ahci_intr_cmd_cmplt: port %d, "
4858 			    "PRD Byte Count = 0x%x, "
4859 			    "ahciport_prd_bytecounts = 0x%x", port,
4860 			    cmd_header->ahcich_prd_byte_count,
4861 			    cmd_dmacount);
4862 
4863 			if (cmd_header->ahcich_prd_byte_count != cmd_dmacount) {
4864 				AHCIDBG(AHCIDBG_UNDERFLOW, ahci_ctlp,
4865 				    "ahci_intr_cmd_cmplt: port %d, "
4866 				    "an underflow occurred", port);
4867 			}
4868 		}
4869 #endif
4870 
4871 		/*
4872 		 * For SATAC_SMART command with SATA_SMART_RETURN_STATUS
4873 		 * feature, sata_special_regs flag will be set, and the
4874 		 * driver should copy the status and the other corresponding
4875 		 * register values in the D2H Register FIS received (It's
4876 		 * working on Non-data protocol) from the device back to
4877 		 * the sata_cmd.
4878 		 *
4879 		 * For every AHCI port, there is only one Received FIS
4880 		 * structure, which contains the FISes received from the
4881 		 * device, So we're trying to copy the content of D2H
4882 		 * Register FIS in the Received FIS structure back to
4883 		 * the sata_cmd.
4884 		 */
4885 		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
4886 			rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
4887 			    ahcirf_d2h_register_fis);
4888 			satapkt->satapkt_cmd.satacmd_status_reg =
4889 			    GET_RFIS_STATUS(rcvd_fisp);
4890 			ahci_copy_out_regs(&satapkt->satapkt_cmd, rcvd_fisp);
4891 		}
4892 
4893 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4894 		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
4895 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
4896 
4897 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, finished_slot);
4898 		CLEAR_BIT(finished_tags, finished_slot);
4899 		ahci_portp->ahciport_slot_pkts[finished_slot] = NULL;
4900 
4901 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
4902 	}
4903 out:
4904 	AHCIDBG(AHCIDBG_PKTCOMP, ahci_ctlp,
4905 	    "ahci_intr_cmd_cmplt: pending_tags = 0x%x",
4906 	    ahci_portp->ahciport_pending_tags);
4907 
4908 	mutex_exit(&ahci_portp->ahciport_mutex);
4909 
4910 	return (AHCI_SUCCESS);
4911 }
4912 
4913 /*
4914  * AHCI_INTR_STATUS_SDBS means a Set Device Bits FIS has been received
4915  * with the 'I' bit set and has been copied into system memory. It will
4916  * be sent under the following situations:
4917  *
4918  * 	1. NCQ command is completed
4919  * 	2. Asynchronous notification
4920  *
4921  * The completion of NCQ commands (READ/WRITE FPDMA QUEUED) is performed
4922  * via the Set Device Bits FIS. When such event is generated, the software
4923  * needs to read PxSACT register and compares the current value to the
4924  * list of commands previously issue by software. ahciport_pending_ncq_tags
4925  * keeps the tags of previously issued commands.
4926  *
4927  * Asynchronous Notification is a feature in SATA II, which allows an
4928  * ATAPI device to send a signal to the host when media is inserted or
4929  * removed and avoids polling the device for media changes. The signal
4930  * sent to the host is a Set Device Bits FIS with the 'I' and 'N' bits
4931  * set to '1'. At the moment, it's not supported yet.
4932  */
4933 static int
4934 ahci_intr_set_device_bits(ahci_ctl_t *ahci_ctlp,
4935     ahci_port_t *ahci_portp, uint8_t port)
4936 {
4937 	uint32_t port_sactive;
4938 	uint32_t port_cmd_issue;
4939 	uint32_t issued_tags;
4940 	int issued_slot;
4941 	uint32_t finished_tags;
4942 	int finished_slot;
4943 	sata_pkt_t *satapkt;
4944 
4945 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4946 	    "ahci_intr_set_device_bits enter: port %d", port);
4947 
4948 	mutex_enter(&ahci_portp->ahciport_mutex);
4949 	if (!NCQ_CMD_IN_PROGRESS(ahci_portp)) {
4950 		mutex_exit(&ahci_portp->ahciport_mutex);
4951 		return (AHCI_SUCCESS);
4952 	}
4953 
4954 	/*
4955 	 * First the handler got which commands are finished by checking
4956 	 * PxSACT register
4957 	 */
4958 	port_sactive = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4959 	    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
4960 
4961 	finished_tags = ahci_portp->ahciport_pending_ncq_tags &
4962 	    ~port_sactive & AHCI_NCQ_SLOT_MASK(ahci_portp);
4963 
4964 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4965 	    "ahci_intr_set_device_bits: port %d pending_ncq_tags = 0x%x "
4966 	    "port_sactive = 0x%x", port,
4967 	    ahci_portp->ahciport_pending_ncq_tags, port_sactive);
4968 
4969 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4970 	    "ahci_intr_set_device_bits: finished_tags = 0x%x", finished_tags);
4971 
4972 	/*
4973 	 * For NCQ commands, the software can determine which command has
4974 	 * already been transmitted to the device by checking PxCI register.
4975 	 */
4976 	port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4977 	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4978 
4979 	issued_tags = ahci_portp->ahciport_pending_tags &
4980 	    ~port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp);
4981 
4982 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4983 	    "ahci_intr_set_device_bits: port %d pending_tags = 0x%x "
4984 	    "port_cmd_issue = 0x%x", port,
4985 	    ahci_portp->ahciport_pending_tags, port_cmd_issue);
4986 
4987 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4988 	    "ahci_intr_set_device_bits: issued_tags = 0x%x", issued_tags);
4989 
4990 	/*
4991 	 * Clear ahciport_pending_tags bit when the corresponding command
4992 	 * is already sent down to the device.
4993 	 */
4994 	while (issued_tags) {
4995 		issued_slot = ddi_ffs(issued_tags) - 1;
4996 		if (issued_slot == -1) {
4997 			goto next;
4998 		}
4999 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, issued_slot);
5000 		CLEAR_BIT(issued_tags, issued_slot);
5001 	}
5002 
5003 next:
5004 	while (finished_tags) {
5005 		finished_slot = ddi_ffs(finished_tags) - 1;
5006 		if (finished_slot == -1) {
5007 			goto out;
5008 		}
5009 
5010 		/* The command is certainly transmitted to the device */
5011 		ASSERT(!(ahci_portp->ahciport_pending_tags &
5012 		    (0x1 << finished_slot)));
5013 
5014 		satapkt = ahci_portp->ahciport_slot_pkts[finished_slot];
5015 		ASSERT(satapkt != NULL);
5016 
5017 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
5018 		    "ahci_intr_set_device_bits: sending up pkt 0x%p "
5019 		    "with SATA_PKT_COMPLETED", (void *)satapkt);
5020 
5021 		CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags, finished_slot);
5022 		CLEAR_BIT(finished_tags, finished_slot);
5023 		ahci_portp->ahciport_slot_pkts[finished_slot] = NULL;
5024 
5025 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
5026 	}
5027 out:
5028 	AHCIDBG(AHCIDBG_PKTCOMP|AHCIDBG_NCQ, ahci_ctlp,
5029 	    "ahci_intr_set_device_bits: port %d "
5030 	    "pending_ncq_tags = 0x%x pending_tags = 0x%x",
5031 	    port, ahci_portp->ahciport_pending_ncq_tags,
5032 	    ahci_portp->ahciport_pending_tags);
5033 
5034 	mutex_exit(&ahci_portp->ahciport_mutex);
5035 
5036 	return (AHCI_SUCCESS);
5037 }
5038 
5039 /*
5040  * 1=Change in Current Connect Status. 0=No change in Current Connect Status.
5041  * This bit reflects the state of PxSERR.DIAG.X. This bit is only cleared
5042  * when PxSERR.DIAG.X is cleared. When PxSERR.DIAG.X is set to one, it
5043  * indicates a COMINIT signal was received.
5044  *
5045  * Hot plug insertion is detected by reception of a COMINIT signal from the
5046  * device. On reception of unsolicited COMINIT, the HBA shall generate a
5047  * COMRESET. If the COMINIT is in responce to a COMRESET, then the HBA shall
5048  * begin the normal communication negotiation sequence as outlined in the
5049  * Serial ATA 1.0a specification. When a COMRESET is sent to the device the
5050  * PxSSTS.DET field shall be cleared to 0h. When a COMINIT is received, the
5051  * PxSSTS.DET field shall be set to 1h. When the communication negotiation
5052  * sequence is complete and PhyRdy is true the PxSSTS.DET field	shall be set
5053  * to 3h. Therefore, at the moment the ahci driver is going to check PhyRdy
5054  * to handle hot plug insertion. In this interrupt handler, just do nothing
5055  * but print some log message and clear the bit.
5056  */
5057 static int
5058 ahci_intr_port_connect_change(ahci_ctl_t *ahci_ctlp,
5059     ahci_port_t *ahci_portp, uint8_t port)
5060 {
5061 #if AHCI_DEBUG
5062 	uint32_t port_serror;
5063 #endif
5064 
5065 	mutex_enter(&ahci_portp->ahciport_mutex);
5066 
5067 #if AHCI_DEBUG
5068 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5069 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
5070 
5071 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
5072 	    "ahci_intr_port_connect_change: port %d, "
5073 	    "port_serror = 0x%x", port, port_serror);
5074 #endif
5075 
5076 	/* Clear PxSERR.DIAG.X to clear the interrupt bit */
5077 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5078 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5079 	    SERROR_EXCHANGED_ERR);
5080 
5081 	mutex_exit(&ahci_portp->ahciport_mutex);
5082 
5083 	return (AHCI_SUCCESS);
5084 }
5085 
5086 /*
5087  * Hot Plug Operation for platforms that support Mechanical Presence
5088  * Switches.
5089  *
5090  * When set, it indicates that a mechanical presence switch attached to this
5091  * port has been opened or closed, which may lead to a change in the connection
5092  * state of the device. This bit is only valid if both CAP.SMPS and PxCMD.MPSP
5093  * are set to '1'.
5094  *
5095  * At the moment, this interrupt is not needed and disabled and we just log
5096  * the debug message.
5097  */
5098 static int
5099 ahci_intr_device_mechanical_presence_status(ahci_ctl_t *ahci_ctlp,
5100     ahci_port_t *ahci_portp, uint8_t port)
5101 {
5102 	uint32_t cap_status, port_cmd_status;
5103 
5104 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
5105 	    "ahci_intr_device_mechanical_presence_status enter, "
5106 	    "port %d", port);
5107 
5108 	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5109 	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
5110 
5111 	mutex_enter(&ahci_portp->ahciport_mutex);
5112 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5113 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5114 
5115 	if (!(cap_status & AHCI_HBA_CAP_SMPS) ||
5116 	    !(port_cmd_status & AHCI_CMD_STATUS_MPSP)) {
5117 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5118 		    "CAP.SMPS or PxCMD.MPSP is not set, so just ignore "
5119 		    "the interrupt: cap_status = 0x%x, "
5120 		    "port_cmd_status = 0x%x", cap_status, port_cmd_status);
5121 		mutex_exit(&ahci_portp->ahciport_mutex);
5122 
5123 		return (AHCI_SUCCESS);
5124 	}
5125 
5126 #if AHCI_DEBUG
5127 	if (port_cmd_status & AHCI_CMD_STATUS_MPSS) {
5128 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5129 		    "The mechanical presence switch is open: "
5130 		    "port %d, port_cmd_status = 0x%x",
5131 		    port, port_cmd_status);
5132 	} else {
5133 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5134 		    "The mechanical presence switch is close: "
5135 		    "port %d, port_cmd_status = 0x%x",
5136 		    port, port_cmd_status);
5137 	}
5138 #endif
5139 
5140 	mutex_exit(&ahci_portp->ahciport_mutex);
5141 
5142 	return (AHCI_SUCCESS);
5143 }
5144 
5145 /*
5146  * Native Hot Plug Support.
5147  *
5148  * When set, it indicates that the internal PHYRDY signal changed state.
5149  * This bit reflects the state of PxSERR.DIAG.N.
5150  *
5151  * There are three kinds of conditions to generate this interrupt event:
5152  * 1. a device is inserted
5153  * 2. a device is disconnected
5154  * 3. when the link enters/exits a Partial or Slumber interface power
5155  *    management state
5156  *
5157  * If inteface power management is enabled for a port, the PxSERR.DIAG.N
5158  * bit may be set due to the link entering the Partial or Slumber power
5159  * management state, rather than due to a hot plug insertion or removal
5160  * event. So far, the interface power management is disabled, so the
5161  * driver can reliably get removal detection notification via the
5162  * PxSERR.DIAG.N bit.
5163  */
5164 static int
5165 ahci_intr_phyrdy_change(ahci_ctl_t *ahci_ctlp,
5166     ahci_port_t *ahci_portp, uint8_t port)
5167 {
5168 	uint32_t port_sstatus = 0; /* No dev present & PHY not established. */
5169 	sata_device_t sdevice;
5170 	int dev_exists_now = 0;
5171 	int dev_existed_previously = 0;
5172 
5173 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
5174 	    "ahci_intr_phyrdy_change enter, port %d", port);
5175 
5176 	/* Clear PxSERR.DIAG.N to clear the interrupt bit */
5177 	mutex_enter(&ahci_portp->ahciport_mutex);
5178 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5179 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5180 	    SERROR_PHY_RDY_CHG);
5181 	mutex_exit(&ahci_portp->ahciport_mutex);
5182 
5183 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
5184 	if ((ahci_ctlp->ahcictl_sata_hba_tran == NULL) ||
5185 	    (ahci_portp == NULL)) {
5186 		/* The whole controller setup is not yet done. */
5187 		mutex_exit(&ahci_ctlp->ahcictl_mutex);
5188 		return (AHCI_SUCCESS);
5189 	}
5190 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
5191 
5192 	mutex_enter(&ahci_portp->ahciport_mutex);
5193 
5194 	/* SStatus tells the presence of device. */
5195 	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5196 	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
5197 
5198 	if (SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_PHYCOM) {
5199 		dev_exists_now = 1;
5200 	}
5201 
5202 	if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) {
5203 		dev_existed_previously = 1;
5204 	}
5205 
5206 	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_NODEV) {
5207 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_NODEV;
5208 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5209 		    "ahci_intr_phyrdy_change: port %d "
5210 		    "AHCI_PORT_FLAG_NODEV is cleared", port);
5211 		if (dev_exists_now == 0)
5212 			dev_existed_previously = 1;
5213 	}
5214 
5215 	bzero((void *)&sdevice, sizeof (sata_device_t));
5216 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
5217 	sdevice.satadev_addr.qual = SATA_ADDR_CPORT;
5218 	sdevice.satadev_addr.pmport = 0;
5219 	sdevice.satadev_state = SATA_PSTATE_PWRON;
5220 	ahci_portp->ahciport_port_state = SATA_PSTATE_PWRON;
5221 
5222 	if (dev_exists_now) {
5223 		if (dev_existed_previously) {
5224 			/* Things are fine now. The loss was temporary. */
5225 			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
5226 			    "ahci_intr_phyrdy_change  port %d "
5227 			    "device link lost/established", port);
5228 
5229 			mutex_exit(&ahci_portp->ahciport_mutex);
5230 			sata_hba_event_notify(
5231 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5232 			    &sdevice,
5233 			    SATA_EVNT_LINK_LOST|SATA_EVNT_LINK_ESTABLISHED);
5234 			mutex_enter(&ahci_portp->ahciport_mutex);
5235 
5236 		} else {
5237 			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
5238 			    "ahci_intr_phyrdy_change: port %d "
5239 			    "device link established", port);
5240 
5241 			/* A new device has been detected. */
5242 			(void) ahci_port_reset(ahci_ctlp, ahci_portp, port);
5243 			ahci_find_dev_signature(ahci_ctlp, ahci_portp, port);
5244 
5245 			/* Try to start the port */
5246 			if (ahci_start_port(ahci_ctlp, ahci_portp, port)
5247 			    != AHCI_SUCCESS) {
5248 				sdevice.satadev_state |= SATA_PSTATE_FAILED;
5249 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5250 				    "ahci_intr_phyrdy_change: port %d failed "
5251 				    "at start port", port);
5252 			}
5253 
5254 			/* Clear the max queue depth for inserted device */
5255 			ahci_portp->ahciport_max_ncq_tags = 0;
5256 
5257 			mutex_exit(&ahci_portp->ahciport_mutex);
5258 			sata_hba_event_notify(
5259 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5260 			    &sdevice,
5261 			    SATA_EVNT_LINK_ESTABLISHED);
5262 			mutex_enter(&ahci_portp->ahciport_mutex);
5263 
5264 		}
5265 	} else { /* No device exists now */
5266 
5267 		if (dev_existed_previously) {
5268 			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
5269 			    "ahci_intr_phyrdy_change: port %d "
5270 			    "device link lost", port);
5271 
5272 			ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
5273 			(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
5274 			    ahci_portp, port);
5275 
5276 			/* An existing device is lost. */
5277 			ahci_portp->ahciport_device_type = SATA_DTYPE_NONE;
5278 
5279 			mutex_exit(&ahci_portp->ahciport_mutex);
5280 			sata_hba_event_notify(
5281 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5282 			    &sdevice,
5283 			    SATA_EVNT_LINK_LOST);
5284 			mutex_enter(&ahci_portp->ahciport_mutex);
5285 		}
5286 	}
5287 
5288 	mutex_exit(&ahci_portp->ahciport_mutex);
5289 
5290 	return (AHCI_SUCCESS);
5291 }
5292 
5293 /*
5294  * PxIS.UFS - Unknown FIS Error
5295  *
5296  * This interrupt event means an unknown FIS was received and has been
5297  * copied into system memory. An unknown FIS is not considered an illegal
5298  * FIS, unless the length received is more than 64 bytes. If an unknown
5299  * FIS arrives with length <= 64 bytes, it is posted and the HBA continues
5300  * normal operation. If the unknown FIS is more than 64 bytes, then it
5301  * won't be posted to memory and PxSERR.ERR.P will be set, which is then
5302  * a fatal error.
5303  *
5304  * PxIS.OFS - Overflow Error
5305  *
5306  * Command list overflow is defined as software building a command table
5307  * that has fewer total bytes than the transaction given to the device.
5308  * On device writes, the HBA will run out of data, and on reads, there
5309  * will be no room to put the data.
5310  *
5311  * For an overflow on data read, either PIO or DMA, the HBA will set
5312  * PxIS.OFS, and the HBA will do a best effort to continue, and it's a
5313  * non-fatal error when the HBA can continues. Sometimes, it will cause
5314  * a fatal error and need the software to do something.
5315  *
5316  * For an overflow on data write, setting PxIS.OFS is optional for both
5317  * DMA and PIO, and it's a fatal error, and a COMRESET is required by
5318  * software to clean up from this serious error.
5319  *
5320  * PxIS.INFS - Interface Non-Fatal Error
5321  *
5322  * This interrupt event indicates that the HBA encountered an error on
5323  * the Serial ATA interface but was able to continue operation. The kind
5324  * of error usually occurred during a non-Data FIS, and under this condition
5325  * the FIS will be re-transmitted by HBA automatically.
5326  *
5327  * When the FMA is implemented, there should be a stat structure to
5328  * record how many every kind of error happens.
5329  */
5330 static int
5331 ahci_intr_non_fatal_error(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
5332     uint8_t port, uint32_t intr_status)
5333 {
5334 	uint32_t port_serror;
5335 #if AHCI_DEBUG
5336 	uint32_t port_cmd_status;
5337 	uint32_t port_cmd_issue;
5338 	uint32_t port_sactive;
5339 	int current_slot;
5340 	uint32_t current_tags;
5341 	sata_pkt_t *satapkt;
5342 	ahci_cmd_header_t *cmd_header;
5343 	uint32_t cmd_dmacount;
5344 #endif
5345 
5346 	mutex_enter(&ahci_portp->ahciport_mutex);
5347 
5348 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5349 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
5350 
5351 	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY|AHCIDBG_ERRS, ahci_ctlp,
5352 	    "ahci_intr_non_fatal_error: port %d, "
5353 	    "port_serror = 0x%x", port, port_serror);
5354 
5355 	ahci_log_serror_message(ahci_ctlp, port, port_serror, 1);
5356 
5357 	if (intr_status & AHCI_INTR_STATUS_UFS) {
5358 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5359 		    "ahci port %d has unknown FIS error", port);
5360 
5361 		/* Clear the interrupt bit by clearing PxSERR.DIAG.F */
5362 		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5363 		    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5364 		    SERROR_FIS_TYPE);
5365 	}
5366 
5367 #if AHCI_DEBUG
5368 	if (intr_status & AHCI_INTR_STATUS_OFS) {
5369 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5370 		    "ahci port %d has overflow error", port);
5371 	}
5372 
5373 	if (intr_status & AHCI_INTR_STATUS_INFS) {
5374 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5375 		    "ahci port %d has interface non fatal error", port);
5376 	}
5377 
5378 	/*
5379 	 * Record the error occurred command's slot.
5380 	 */
5381 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
5382 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
5383 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5384 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5385 
5386 		current_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
5387 		    AHCI_CMD_STATUS_CCS_SHIFT;
5388 
5389 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
5390 			satapkt = ahci_portp->ahciport_err_retri_pkt;
5391 			ASSERT(satapkt != NULL);
5392 			ASSERT(current_slot == 0);
5393 		} else {
5394 			satapkt = ahci_portp->ahciport_slot_pkts[current_slot];
5395 		}
5396 
5397 		if (satapkt != NULL) {
5398 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5399 			    "ahci_intr_non_fatal_error: pending_tags = 0x%x "
5400 			    "cmd 0x%x", ahci_portp->ahciport_pending_tags,
5401 			    satapkt->satapkt_cmd.satacmd_cmd_reg);
5402 
5403 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5404 			    "ahci_intr_non_fatal_error: port %d, "
5405 			    "satapkt 0x%p is being processed when error occurs",
5406 			    port, (void *)satapkt);
5407 
5408 			/*
5409 			 * PRD Byte Count field of command header is not
5410 			 * required to reflect the total number of bytes
5411 			 * transferred when an overflow occurs, so here
5412 			 * just log the value.
5413 			 */
5414 			cmd_dmacount =
5415 			    ahci_portp->ahciport_prd_bytecounts[current_slot];
5416 			if (cmd_dmacount) {
5417 				cmd_header = &ahci_portp->
5418 				    ahciport_cmd_list[current_slot];
5419 				AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5420 				    "ahci_intr_non_fatal_error: port %d, "
5421 				    "PRD Byte Count = 0x%x, "
5422 				    "ahciport_prd_bytecounts = 0x%x", port,
5423 				    cmd_header->ahcich_prd_byte_count,
5424 				    cmd_dmacount);
5425 			}
5426 		}
5427 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
5428 		/*
5429 		 * For queued command, list those command which have already
5430 		 * been transmitted to the device and still not completed.
5431 		 */
5432 		port_sactive = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5433 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
5434 
5435 		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5436 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
5437 
5438 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ|AHCIDBG_ERRS, ahci_ctlp,
5439 		    "ahci_intr_non_fatal_error: pending_ncq_tags = 0x%x "
5440 		    "port_sactive = 0x%x port_cmd_issue = 0x%x",
5441 		    ahci_portp->ahciport_pending_ncq_tags,
5442 		    port_sactive, port_cmd_issue);
5443 
5444 		current_tags = ahci_portp->ahciport_pending_ncq_tags &
5445 		    port_sactive & ~port_cmd_issue &
5446 		    AHCI_NCQ_SLOT_MASK(ahci_portp);
5447 
5448 		while (current_tags) {
5449 			current_slot = ddi_ffs(current_tags) - 1;
5450 			if (current_slot == -1) {
5451 				goto out;
5452 			}
5453 
5454 			satapkt = ahci_portp->ahciport_slot_pkts[current_slot];
5455 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ|AHCIDBG_ERRS,
5456 			    ahci_ctlp, "ahci_intr_non_fatal_error: "
5457 			    "port %d, satapkt 0x%p is outstanding when "
5458 			    "error occurs", port, (void *)satapkt);
5459 
5460 			CLEAR_BIT(current_tags, current_slot);
5461 		}
5462 	}
5463 out:
5464 #endif
5465 	mutex_exit(&ahci_portp->ahciport_mutex);
5466 
5467 	return (AHCI_SUCCESS);
5468 }
5469 
5470 /*
5471  * According to the AHCI spec, the error types include system memory
5472  * errors, interface errors, port multiplier errors, device errors,
5473  * command list overflow, command list underflow, native command
5474  * queuing tag errors and pio data transfer errors.
5475  *
5476  * System memory errors such as target abort, master abort, and parity
5477  * may cause the host to stop, and they are serious errors and needed
5478  * to be recovered with software intervention. When system software
5479  * has given a pointer to the HBA that doesn't exist in physical memory,
5480  * a master/target abort error occurs, and PxIS.HBFS will be set. A
5481  * data error such as CRC or parity occurs, the HBA aborts the transfer
5482  * (if necessary) and PxIS.HBDS will be set.
5483  *
5484  * Interface errors are errors that occur due to electrical issues on
5485  * the interface, or protocol miscommunication between the device and
5486  * HBA, and the respective PxSERR register bit will be set. And PxIS.IFS
5487  * (fatal) or PxIS.INFS (non-fatal) will be set. The conditions that
5488  * causes PxIS.IFS/PxIS.INFS to be set are
5489  * 	1. in PxSERR.ERR, P bit is set to '1'
5490  *	2. in PxSERR.DIAG, C or H bit is set to '1'
5491  *	3. PhyRdy drop unexpectly, N bit is set to '1'
5492  * If the error occurred during a non-data FIS, the FIS must be
5493  * retransmitted, and the error is non-fatal and PxIS.INFS is set. If
5494  * the error occurred during a data FIS, the transfer will stop, so
5495  * the error is fatal and PxIS.IFS is set.
5496  *
5497  * When a FIS arrives that updates the taskfile, the HBA checks to see
5498  * if PxTFD.STS.ERR is set. If yes, PxIS.TFES will be set and the HBA
5499  * stops processing any more commands.
5500  *
5501  * Command list overflow is defined as software building a command table
5502  * that has fewer total bytes than the transaction given to the device.
5503  * On device writes, the HBA will run out of data, and on reads, there
5504  * will be no room to put the data. For an overflow on data read, either
5505  * PIO or DMA, the HBA will set PxIS.OFS, and it's a non-fatal error.
5506  * For an overflow on data write, setting PxIS.OFS is optional for both
5507  * DMA and PIO, and a COMRESET is required by software to clean up from
5508  * this serious error.
5509  *
5510  * Command list underflow is defined as software building a command
5511  * table that has more total bytes than the transaction given to the
5512  * device. For data writes, both PIO and DMA, the device will detect
5513  * an error and end the transfer. And these errors are most likely going
5514  * to be fatal errors that will cause the port to be restarted. For
5515  * data reads, the HBA updates its PRD byte count, and may be
5516  * able to continue normally, but is not required to. And The HBA is
5517  * not required to detect underflow conditions for native command
5518  * queuing command.
5519  *
5520  * The HBA does not actively check incoming DMA Setup FISes to ensure
5521  * that the PxSACT register bit for that slot is set. Existing error
5522  * mechanisms, such as host bus failure, or bad protocol, are used to
5523  * recover from this case.
5524  *
5525  * In accordance with Serial ATA 1.0a, DATA FISes prior to the final
5526  * DATA FIS must be an integral number of Dwords. If the HBA receives
5527  * a request which is not an integral number of Dwords, the HBA
5528  * set PxSERR.ERR.P to '1', set PxIS.IFS to '1' and stop running until
5529  * software restarts the port. And the HBA ensures that the size
5530  * of the DATA FIS received during a PIO command matches the size in
5531  * the Transfer Cound field of the preceding PIO Setup FIS, if not, the
5532  * HBA sets PxSERR.ERR.P to '1', set PxIS.IFS to '1', and then
5533  * stop running until software restarts the port.
5534  */
5535 /*
5536  * the fatal errors include PxIS.IFS, PxIS.HBDS, PxIS.HBFS and PxIS.TFES.
5537  *
5538  * PxIS.IFS indicates that the hba encountered an error on the serial ata
5539  * interface which caused the transfer to stop.
5540  *
5541  * PxIS.HBDS indicates that the hba encountered a data error
5542  * (uncorrectable ecc/parity) when reading from or writing to system memory.
5543  *
5544  * PxIS.HBFS indicates that the hba encountered a host bus error that it
5545  * cannot recover from, such as a bad software pointer.
5546  *
5547  * PxIS.TFES is set whenever the status register is updated by the device
5548  * and the error bit (bit 0) is set.
5549  */
5550 static int
5551 ahci_intr_fatal_error(ahci_ctl_t *ahci_ctlp,
5552     ahci_port_t *ahci_portp, uint8_t port, uint32_t intr_status)
5553 {
5554 	uint32_t port_cmd_status;
5555 	uint32_t port_serror;
5556 	uint32_t task_file_status;
5557 	int failed_slot;
5558 	sata_pkt_t *spkt = NULL;
5559 	uint8_t err_byte;
5560 	ahci_event_arg_t *args;
5561 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
5562 
5563 	mutex_enter(&ahci_portp->ahciport_mutex);
5564 
5565 	/*
5566 	 * ahci_intr_phyrdy_change() may have rendered it to
5567 	 * SATA_DTYPE_NONE.
5568 	 */
5569 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
5570 		AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
5571 		    "ahci_intr_fatal_error: port %d no device attached, "
5572 		    "and just return without doing anything", port);
5573 		goto out0;
5574 	}
5575 
5576 	if (intr_status & AHCI_INTR_STATUS_TFES) {
5577 		task_file_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5578 		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
5579 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5580 		    "ahci_intr_fatal_error: port %d "
5581 		    "task_file_status = 0x%x", port, task_file_status);
5582 	}
5583 
5584 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
5585 		/*
5586 		 * Read PxCMD.CCS to determine the slot that the HBA
5587 		 * was processing when the error occurred.
5588 		 */
5589 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5590 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5591 		failed_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
5592 		    AHCI_CMD_STATUS_CCS_SHIFT;
5593 
5594 		spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
5595 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5596 		    "ahci_intr_fatal_error: spkt 0x%p is being processed when "
5597 		    "fatal error occurred for port %d", spkt, port);
5598 
5599 		if (intr_status & AHCI_INTR_STATUS_TFES) {
5600 			err_byte = (task_file_status & AHCI_TFD_ERR_MASK)
5601 			    >> AHCI_TFD_ERR_SHIFT;
5602 
5603 			/*
5604 			 * Won't emit the error message if it is an IDENTIFY
5605 			 * DEVICE command sent to an ATAPI device.
5606 			 */
5607 			if ((spkt != NULL) &&
5608 			    (spkt->satapkt_cmd.satacmd_cmd_reg ==
5609 			    SATAC_ID_DEVICE) &&
5610 			    (err_byte == SATA_ERROR_ABORT))
5611 				goto out1;
5612 
5613 			/*
5614 			 * Won't emit the error message if it is an ATAPI PACKET
5615 			 * command
5616 			 */
5617 			if ((spkt != NULL) &&
5618 			    (spkt->satapkt_cmd.satacmd_cmd_reg == SATAC_PACKET))
5619 				goto out1;
5620 		}
5621 	}
5622 
5623 	/* print the fatal error type */
5624 	ahci_log_fatal_error_message(ahci_ctlp, port, intr_status);
5625 	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5626 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
5627 
5628 	/* print PxSERR related error message */
5629 	ahci_log_serror_message(ahci_ctlp, port, port_serror, 0);
5630 
5631 	/* print task file register value */
5632 	if (intr_status & AHCI_INTR_STATUS_TFES) {
5633 		cmn_err(CE_WARN, "!ahci%d: ahci port %d task_file_status "
5634 		    "= 0x%x", instance, port, task_file_status);
5635 	}
5636 
5637 out1:
5638 	/* Prepare the argument for the taskq */
5639 	args = ahci_portp->ahciport_event_args;
5640 	args->ahciea_ctlp = (void *)ahci_ctlp;
5641 	args->ahciea_portp = (void *)ahci_portp;
5642 	args->ahciea_event = intr_status;
5643 
5644 	/* Start the taskq to handle error recovery */
5645 	if ((ddi_taskq_dispatch(ahci_portp->ahciport_event_taskq,
5646 	    ahci_events_handler,
5647 	    (void *)args, DDI_NOSLEEP)) != DDI_SUCCESS) {
5648 		cmn_err(CE_WARN, "!ahci%d: ahci start taskq for event handler "
5649 		    "failed", instance);
5650 	}
5651 out0:
5652 	mutex_exit(&ahci_portp->ahciport_mutex);
5653 
5654 	return (AHCI_SUCCESS);
5655 }
5656 
5657 /*
5658  * Hot Plug Operation for platforms that support Cold Presence Detect.
5659  *
5660  * When set, a device status has changed as detected by the cold presence
5661  * detect logic. This bit can either be set due to a non-connected port
5662  * receiving a device, or a connected port having its device removed.
5663  * This bit is only valid if the port supports cold presence detect as
5664  * indicated by PxCMD.CPD set to '1'.
5665  *
5666  * At the moment, this interrupt is not needed and disabled and we just
5667  * log the debug message.
5668  */
5669 static int
5670 ahci_intr_cold_port_detect(ahci_ctl_t *ahci_ctlp,
5671     ahci_port_t *ahci_portp, uint8_t port)
5672 {
5673 	uint32_t port_cmd_status;
5674 	sata_device_t sdevice;
5675 
5676 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5677 	    "ahci_intr_cold_port_detect enter, port %d", port);
5678 
5679 	mutex_enter(&ahci_portp->ahciport_mutex);
5680 
5681 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5682 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5683 	if (!(port_cmd_status & AHCI_CMD_STATUS_CPD)) {
5684 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5685 		    "port %d does not support cold presence detect, so "
5686 		    "we just ignore this interrupt", port);
5687 		mutex_exit(&ahci_portp->ahciport_mutex);
5688 		return (AHCI_SUCCESS);
5689 	}
5690 
5691 	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5692 	    "port %d device status has changed", port);
5693 
5694 	bzero((void *)&sdevice, sizeof (sata_device_t));
5695 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
5696 	sdevice.satadev_addr.qual = SATA_ADDR_CPORT;
5697 	sdevice.satadev_addr.pmport = 0;
5698 	sdevice.satadev_state = SATA_PSTATE_PWRON;
5699 
5700 	if (port_cmd_status & AHCI_CMD_STATUS_CPS) {
5701 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5702 		    "port %d: a device is hot plugged", port);
5703 		mutex_exit(&ahci_portp->ahciport_mutex);
5704 		sata_hba_event_notify(
5705 		    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5706 		    &sdevice,
5707 		    SATA_EVNT_DEVICE_ATTACHED);
5708 		mutex_enter(&ahci_portp->ahciport_mutex);
5709 
5710 	} else {
5711 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5712 		    "port %d: a device is hot unplugged", port);
5713 		mutex_exit(&ahci_portp->ahciport_mutex);
5714 		sata_hba_event_notify(
5715 		    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5716 		    &sdevice,
5717 		    SATA_EVNT_DEVICE_DETACHED);
5718 		mutex_enter(&ahci_portp->ahciport_mutex);
5719 	}
5720 
5721 	mutex_exit(&ahci_portp->ahciport_mutex);
5722 
5723 	return (AHCI_SUCCESS);
5724 }
5725 
5726 /*
5727  * Enable the interrupts for a particular port.
5728  *
5729  * WARNING!!! ahciport_mutex should be acquired before the function
5730  * is called.
5731  */
5732 static void
5733 ahci_enable_port_intrs(ahci_ctl_t *ahci_ctlp, uint8_t port)
5734 {
5735 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
5736 	    "ahci_enable_port_intrs enter, port %d", port);
5737 
5738 	/*
5739 	 * Clear port interrupt status before enabling interrupt
5740 	 */
5741 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5742 	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
5743 	    AHCI_PORT_INTR_MASK);
5744 
5745 	/*
5746 	 * Clear the pending bit from IS.IPS
5747 	 */
5748 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5749 	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp), (1 << port));
5750 
5751 	/*
5752 	 * Enable the following interrupts:
5753 	 *	Device to Host Register FIS Interrupt (DHRS)
5754 	 *	PIO Setup FIS Interrupt (PSS)
5755 	 *	Set Device Bits Interrupt (SDBS)
5756 	 *	Unknown FIS Interrupt (UFS)
5757 	 *	Port Connect Change Status (PCS)
5758 	 *	PhyRdy Change Status (PRCS)
5759 	 *	Overflow Status (OFS)
5760 	 *	Interface Non-fatal Error Status (INFS)
5761 	 *	Interface Fatal Error Status (IFS)
5762 	 *	Host Bus Data Error Status (HBDS)
5763 	 *	Host Bus Fatal Error Status (HBFS)
5764 	 *	Task File Error Status (TFES)
5765 	 */
5766 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5767 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port),
5768 	    (AHCI_INTR_STATUS_DHRS |
5769 	    AHCI_INTR_STATUS_PSS |
5770 	    AHCI_INTR_STATUS_SDBS |
5771 	    AHCI_INTR_STATUS_UFS |
5772 	    AHCI_INTR_STATUS_DPS |
5773 	    AHCI_INTR_STATUS_PCS |
5774 	    AHCI_INTR_STATUS_PRCS |
5775 	    AHCI_INTR_STATUS_OFS |
5776 	    AHCI_INTR_STATUS_INFS |
5777 	    AHCI_INTR_STATUS_IFS |
5778 	    AHCI_INTR_STATUS_HBDS |
5779 	    AHCI_INTR_STATUS_HBFS |
5780 	    AHCI_INTR_STATUS_TFES));
5781 }
5782 
5783 /*
5784  * Enable interrupts for all the ports.
5785  *
5786  * WARNING!!! ahcictl_mutex should be acquired before the function
5787  * is called.
5788  */
5789 static void
5790 ahci_enable_all_intrs(ahci_ctl_t *ahci_ctlp)
5791 {
5792 	uint32_t ghc_control;
5793 
5794 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_enable_all_intrs enter", NULL);
5795 
5796 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5797 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5798 
5799 	ghc_control |= AHCI_HBA_GHC_IE;
5800 
5801 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5802 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
5803 }
5804 
5805 /*
5806  * Disable interrupts for a particular port.
5807  *
5808  * WARNING!!! ahciport_mutex should be acquired before the function
5809  * is called.
5810  */
5811 static void
5812 ahci_disable_port_intrs(ahci_ctl_t *ahci_ctlp, uint8_t port)
5813 {
5814 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
5815 	    "ahci_disable_port_intrs enter, port %d", port);
5816 
5817 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5818 	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port), 0);
5819 }
5820 
5821 /*
5822  * Disable interrupts for the whole HBA.
5823  *
5824  * The global bit is cleared, then all interrupt sources from all
5825  * ports are disabled.
5826  *
5827  * WARNING!!! ahcictl_mutex should be acquired before the function
5828  * is called.
5829  */
5830 static void
5831 ahci_disable_all_intrs(ahci_ctl_t *ahci_ctlp)
5832 {
5833 	uint32_t ghc_control;
5834 
5835 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_disable_all_intrs enter",
5836 	    NULL);
5837 
5838 	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5839 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5840 
5841 	ghc_control &= ~ AHCI_HBA_GHC_IE;
5842 
5843 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5844 	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
5845 }
5846 
5847 /*
5848  * Handle FIXED or MSI interrupts.
5849  */
5850 /*
5851  * According to AHCI spec, the HBA may support several interrupt modes:
5852  *	* pin based interrupts (FIXED)
5853  *	* single MSI message interrupts
5854  *	* multiple MSI based message interrupts
5855  *
5856  * For pin based interrupts, the software interrupt handler need to check IS
5857  * register to find out which port has pending interrupts. And then check
5858  * PxIS register to find out which interrupt events happened on that port.
5859  *
5860  * For single MSI message interrupts, MSICAP.MC.MSIE is set with '1', and
5861  * MSICAP.MC.MME is set with '0'. This mode is similar to pin based interrupts
5862  * in that software interrupt handler need to check IS register to determine
5863  * which port triggered the interrupts since it uses a single message for all
5864  * port interrupts.
5865  *
5866  * HBA may optionally support multiple MSI message for better performance. In
5867  * this mode, each port may have its own interrupt message, and thus generation
5868  * of interrupts is no longer controlled through the IS register. MSICAP.MC.MMC
5869  * represents a power-of-2 wrapper on the number of implemented ports, and
5870  * the mapping of ports to interrupts is done in a 1-1 relationship, up to the
5871  * maximum number of assigned interrupts. When the number of MSI messages
5872  * allocated is less than the number requested, then hardware may have two
5873  * implementation behaviors:
5874  *	* assign each ports its own interrupt and then force all additional
5875  *	  ports to share the last interrupt message, and this condition is
5876  *	  indicated by clearing GHC.MRSM to '0'
5877  *	* revert to single MSI mode, indicated by setting GHC.MRSM to '1'
5878  * When multiple-message MSI is enabled, hardware will still set IS register
5879  * as single message case. And this IS register may be used by software when
5880  * fewer than the requested number of messages is granted in order to determine
5881  * which port had the interrupt.
5882  *
5883  * Note: The current ahci driver only supports the first two interrupt modes:
5884  * pin based interrupts and single MSI message interrupts, and the reason
5885  * is indicated in below code.
5886  */
5887 static int
5888 ahci_add_intrs(ahci_ctl_t *ahci_ctlp, int intr_type)
5889 {
5890 	dev_info_t *dip = ahci_ctlp->ahcictl_dip;
5891 	int		count, avail, actual;
5892 	int		i, rc;
5893 
5894 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
5895 	    "ahci_add_intrs enter interrupt type 0x%x", intr_type);
5896 
5897 	/* get number of interrupts. */
5898 	rc = ddi_intr_get_nintrs(dip, intr_type, &count);
5899 	if ((rc != DDI_SUCCESS) || (count == 0)) {
5900 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5901 		    "ddi_intr_get_nintrs() failed, "
5902 		    "rc %d count %d\n", rc, count);
5903 		return (DDI_FAILURE);
5904 	}
5905 
5906 	/* get number of available interrupts. */
5907 	rc = ddi_intr_get_navail(dip, intr_type, &avail);
5908 	if ((rc != DDI_SUCCESS) || (avail == 0)) {
5909 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5910 		    "ddi_intr_get_navail() failed, "
5911 		    "rc %d avail %d\n", rc, avail);
5912 		return (DDI_FAILURE);
5913 	}
5914 
5915 #if AHCI_DEBUG
5916 	if (avail < count) {
5917 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5918 		    "ddi_intr_get_nintrs returned %d, navail() returned %d",
5919 		    count, avail);
5920 	}
5921 #endif
5922 
5923 	/*
5924 	 * Note: So far Solaris restricts the maximum number of messages for
5925 	 * x86 to 2, that is avail is 2, so here we set the count with 1 to
5926 	 * force the driver to use single MSI message interrupt. In future if
5927 	 * Solaris remove the restriction, then we need to delete the below
5928 	 * code and try to use multiple interrupt routine to gain better
5929 	 * performance.
5930 	 */
5931 	if ((intr_type == DDI_INTR_TYPE_MSI) && (count > 1)) {
5932 		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5933 		    "force to use one interrupt routine though the "
5934 		    "HBA supports %d interrupt", count);
5935 		count = 1;
5936 	}
5937 
5938 	/* Allocate an array of interrupt handles. */
5939 	ahci_ctlp->ahcictl_intr_size = count * sizeof (ddi_intr_handle_t);
5940 	ahci_ctlp->ahcictl_intr_htable =
5941 	    kmem_alloc(ahci_ctlp->ahcictl_intr_size, KM_SLEEP);
5942 
5943 	/* call ddi_intr_alloc(). */
5944 	rc = ddi_intr_alloc(dip, ahci_ctlp->ahcictl_intr_htable,
5945 	    intr_type, 0, count, &actual, DDI_INTR_ALLOC_NORMAL);
5946 
5947 	if ((rc != DDI_SUCCESS) || (actual == 0)) {
5948 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5949 		    "ddi_intr_alloc() failed, rc %d count %d actual %d "
5950 		    "avail %d\n", rc, count, actual, avail);
5951 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
5952 		    ahci_ctlp->ahcictl_intr_size);
5953 		return (DDI_FAILURE);
5954 	}
5955 
5956 	/* use interrupt count returned */
5957 #if AHCI_DEBUG
5958 	if (actual < count) {
5959 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5960 		    "Requested: %d, Received: %d", count, actual);
5961 	}
5962 #endif
5963 
5964 	ahci_ctlp->ahcictl_intr_cnt = actual;
5965 
5966 	/*
5967 	 * Get priority for first, assume remaining are all the same.
5968 	 */
5969 	if (ddi_intr_get_pri(ahci_ctlp->ahcictl_intr_htable[0],
5970 	    &ahci_ctlp->ahcictl_intr_pri) != DDI_SUCCESS) {
5971 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5972 		    "ddi_intr_get_pri() failed", NULL);
5973 
5974 		/* Free already allocated intr. */
5975 		for (i = 0; i < actual; i++) {
5976 			(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[i]);
5977 		}
5978 
5979 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
5980 		    ahci_ctlp->ahcictl_intr_size);
5981 		return (DDI_FAILURE);
5982 	}
5983 
5984 	/* Test for high level interrupt. */
5985 	if (ahci_ctlp->ahcictl_intr_pri >= ddi_intr_get_hilevel_pri()) {
5986 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5987 		    "ahci_add_intrs: Hi level intr not supported", NULL);
5988 
5989 		/* Free already allocated intr. */
5990 		for (i = 0; i < actual; i++) {
5991 			(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[i]);
5992 		}
5993 
5994 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
5995 		    sizeof (ddi_intr_handle_t));
5996 
5997 		return (DDI_FAILURE);
5998 	}
5999 
6000 	/* Call ddi_intr_add_handler(). */
6001 	for (i = 0; i < actual; i++) {
6002 		if (ddi_intr_add_handler(ahci_ctlp->ahcictl_intr_htable[i],
6003 		    ahci_intr, (caddr_t)ahci_ctlp, NULL) != DDI_SUCCESS) {
6004 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
6005 			    "ddi_intr_add_handler() failed", NULL);
6006 
6007 			/* Free already allocated intr. */
6008 			for (i = 0; i < actual; i++) {
6009 				(void) ddi_intr_free(
6010 				    ahci_ctlp->ahcictl_intr_htable[i]);
6011 			}
6012 
6013 			kmem_free(ahci_ctlp->ahcictl_intr_htable,
6014 			    ahci_ctlp->ahcictl_intr_size);
6015 			return (DDI_FAILURE);
6016 		}
6017 	}
6018 
6019 	if (ddi_intr_get_cap(ahci_ctlp->ahcictl_intr_htable[0],
6020 	    &ahci_ctlp->ahcictl_intr_cap) != DDI_SUCCESS) {
6021 		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
6022 		    "ddi_intr_get_cap() failed", NULL);
6023 
6024 		/* Free already allocated intr. */
6025 		for (i = 0; i < actual; i++) {
6026 			(void) ddi_intr_free(
6027 			    ahci_ctlp->ahcictl_intr_htable[i]);
6028 		}
6029 
6030 		kmem_free(ahci_ctlp->ahcictl_intr_htable,
6031 		    ahci_ctlp->ahcictl_intr_size);
6032 		return (DDI_FAILURE);
6033 	}
6034 
6035 	if (ahci_ctlp->ahcictl_intr_cap & DDI_INTR_FLAG_BLOCK) {
6036 		/* Call ddi_intr_block_enable() for MSI. */
6037 		(void) ddi_intr_block_enable(ahci_ctlp->ahcictl_intr_htable,
6038 		    ahci_ctlp->ahcictl_intr_cnt);
6039 	} else {
6040 		/* Call ddi_intr_enable() for FIXED or MSI non block enable. */
6041 		for (i = 0; i < ahci_ctlp->ahcictl_intr_cnt; i++) {
6042 			(void) ddi_intr_enable(
6043 			    ahci_ctlp->ahcictl_intr_htable[i]);
6044 		}
6045 	}
6046 
6047 	return (DDI_SUCCESS);
6048 }
6049 
6050 /*
6051  * Removes the registered interrupts irrespective of whether they
6052  * were legacy or MSI.
6053  *
6054  * WARNING!!! The controller interrupts must be disabled before calling
6055  * this routine.
6056  */
6057 static void
6058 ahci_rem_intrs(ahci_ctl_t *ahci_ctlp)
6059 {
6060 	int x;
6061 
6062 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_rem_intrs entered", NULL);
6063 
6064 	/* Disable all interrupts. */
6065 	if ((ahci_ctlp->ahcictl_intr_type == DDI_INTR_TYPE_MSI) &&
6066 	    (ahci_ctlp->ahcictl_intr_cap & DDI_INTR_FLAG_BLOCK)) {
6067 		/* Call ddi_intr_block_disable(). */
6068 		(void) ddi_intr_block_disable(ahci_ctlp->ahcictl_intr_htable,
6069 		    ahci_ctlp->ahcictl_intr_cnt);
6070 	} else {
6071 		for (x = 0; x < ahci_ctlp->ahcictl_intr_cnt; x++) {
6072 			(void) ddi_intr_disable(
6073 			    ahci_ctlp->ahcictl_intr_htable[x]);
6074 		}
6075 	}
6076 
6077 	/* Call ddi_intr_remove_handler(). */
6078 	for (x = 0; x < ahci_ctlp->ahcictl_intr_cnt; x++) {
6079 		(void) ddi_intr_remove_handler(
6080 		    ahci_ctlp->ahcictl_intr_htable[x]);
6081 		(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[x]);
6082 	}
6083 
6084 	kmem_free(ahci_ctlp->ahcictl_intr_htable, ahci_ctlp->ahcictl_intr_size);
6085 }
6086 
6087 /*
6088  * This routine tries to put port into P:NotRunning state by clearing
6089  * PxCMD.ST. HBA will clear PxCI to 0h, PxSACT to 0h, PxCMD.CCS to 0h
6090  * and PxCMD.CR to '0'.
6091  *
6092  * WARNING!!! ahciport_mutex should be acquired before the function
6093  * is called.
6094  */
6095 static int
6096 ahci_put_port_into_notrunning_state(ahci_ctl_t *ahci_ctlp,
6097     ahci_port_t *ahci_portp, uint8_t port)
6098 {
6099 	uint32_t port_cmd_status;
6100 	int loop_count;
6101 
6102 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6103 	    "ahci_put_port_into_notrunning_state enter: port %d", port);
6104 
6105 	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6106 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6107 
6108 	port_cmd_status &= ~AHCI_CMD_STATUS_ST;
6109 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6110 	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port), port_cmd_status);
6111 
6112 	/* Wait until PxCMD.CR is cleared */
6113 	loop_count = 0;
6114 	do {
6115 		port_cmd_status =
6116 		    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6117 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6118 
6119 		if (loop_count++ > AHCI_POLLRATE_PORT_IDLE) {
6120 			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
6121 			    "clearing port %d CMD.CR timeout, "
6122 			    "port_cmd_status = 0x%x", port,
6123 			    port_cmd_status);
6124 			/*
6125 			 * We are effectively timing out after 0.5 sec.
6126 			 * This value is specified in AHCI spec.
6127 			 */
6128 			break;
6129 		}
6130 
6131 		/* Wait for 10 millisec */
6132 		drv_usecwait(10000);
6133 	} while (port_cmd_status & AHCI_CMD_STATUS_CR);
6134 
6135 	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_STARTED;
6136 
6137 	if (port_cmd_status & AHCI_CMD_STATUS_CR) {
6138 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
6139 		    "ahci_put_port_into_notrunning_state: failed to clear "
6140 		    "PxCMD.CR to '0' after loop count: %d, and "
6141 		    "port_cmd_status = 0x%x", loop_count, port_cmd_status);
6142 		return (AHCI_FAILURE);
6143 	} else {
6144 		AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
6145 		    "ahci_put_port_into_notrunning_state: succeeded to clear "
6146 		    "PxCMD.CR to '0' after loop count: %d, and "
6147 		    "port_cmd_status = 0x%x", loop_count, port_cmd_status);
6148 		return (AHCI_SUCCESS);
6149 	}
6150 }
6151 
6152 /*
6153  * First clear PxCMD.ST, and then check PxTFD. If both PxTFD.STS.BSY
6154  * and PxTFD.STS.DRQ cleared to '0', it means the device is in a
6155  * stable state, then set PxCMD.ST to '1' to start the port directly.
6156  * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then issue a
6157  * COMRESET to the device to put it in an idle state.
6158  *
6159  * The fifth argument returns whether the port reset is involved during
6160  * the process.
6161  *
6162  * The routine will be called under following scenarios:
6163  *	+ To abort the packet(s)
6164  *	+ To reset the port
6165  *	+ To activate the port
6166  *	+ Fatal error recovery
6167  *	+ To abort the timeout packet(s)
6168  *
6169  * WARNING!!! ahciport_mutex should be acquired before the function
6170  * is called. And ahciport_mutex will be released before the reset
6171  * event is reported to sata module by calling sata_hba_event_notify,
6172  * and then be acquired again later.
6173  *
6174  * NOTES!!! During this procedure, PxSERR register will be cleared, and
6175  * according to the spec, the clearance of three bits will also clear
6176  * three interrupt status bits.
6177  *	1. PxSERR.DIAG.F will clear PxIS.UFS
6178  *	2. PxSERR.DIAG.X will clear PxIS.PCS
6179  *	3. PxSERR.DIAG.N will clear PxIS.PRCS
6180  *
6181  * Among these three interrupt events, the driver needs to take care of
6182  * PxIS.PRCS, which is the hot plug event. When the driver found out
6183  * a device was unplugged, it will call the interrupt handler.
6184  */
6185 static int
6186 ahci_restart_port_wait_till_ready(ahci_ctl_t *ahci_ctlp,
6187     ahci_port_t *ahci_portp, uint8_t port, int flag, int *reset_flag)
6188 {
6189 	uint32_t port_sstatus;
6190 	uint32_t task_file_status;
6191 	sata_device_t sdevice;
6192 	int rval;
6193 	int dev_exists_begin = 0;
6194 	int dev_exists_end = 0;
6195 
6196 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6197 	    "ahci_restart_port_wait_till_ready: port %d enter", port);
6198 
6199 	if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE)
6200 		dev_exists_begin = 1;
6201 
6202 	/* First clear PxCMD.ST */
6203 	rval = ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp,
6204 	    port);
6205 	if (rval != AHCI_SUCCESS)
6206 		/*
6207 		 * If PxCMD.CR does not clear within a reasonable time, it
6208 		 * may assume the interface is in a hung condition and may
6209 		 * continue with issuing the port reset.
6210 		 */
6211 		goto reset;
6212 
6213 	/* Then clear PxSERR */
6214 	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6215 	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
6216 	    AHCI_SERROR_CLEAR_ALL);
6217 
6218 	/* Then get PxTFD */
6219 	task_file_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6220 	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
6221 
6222 	/*
6223 	 * Check whether the device is in a stable status, if yes,
6224 	 * then start the port directly. However for ahci_tran_dport_reset,
6225 	 * we may have to perform a port reset.
6226 	 */
6227 	if (!(task_file_status & (AHCI_TFD_STS_BSY | AHCI_TFD_STS_DRQ)) &&
6228 	    !(flag & AHCI_PORT_RESET))
6229 		goto out;
6230 
6231 reset:
6232 	/*
6233 	 * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then issue
6234 	 * a COMRESET to the device
6235 	 */
6236 	rval = ahci_port_reset(ahci_ctlp, ahci_portp, port);
6237 
6238 	if (reset_flag != NULL)
6239 		*reset_flag = 1;
6240 
6241 	/* Indicate to the framework that a reset has happened. */
6242 	if ((ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) &&
6243 	    !(flag & AHCI_RESET_NO_EVENTS_UP)) {
6244 		/* Set the reset in progress flag */
6245 		ahci_portp->ahciport_reset_in_progress = 1;
6246 
6247 		bzero((void *)&sdevice, sizeof (sata_device_t));
6248 		sdevice.satadev_addr.cport =
6249 		    ahci_ctlp->ahcictl_port_to_cport[port];
6250 		sdevice.satadev_addr.pmport = 0;
6251 		sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
6252 
6253 		sdevice.satadev_state = SATA_DSTATE_RESET |
6254 		    SATA_DSTATE_PWR_ACTIVE;
6255 		if (ahci_ctlp->ahcictl_sata_hba_tran) {
6256 			mutex_exit(&ahci_portp->ahciport_mutex);
6257 			sata_hba_event_notify(
6258 			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
6259 			    &sdevice,
6260 			    SATA_EVNT_DEVICE_RESET);
6261 			mutex_enter(&ahci_portp->ahciport_mutex);
6262 		}
6263 
6264 		AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
6265 		    "port %d sending event up: SATA_EVNT_RESET", port);
6266 	} else {
6267 		ahci_portp->ahciport_reset_in_progress = 0;
6268 	}
6269 
6270 out:
6271 	(void) ahci_start_port(ahci_ctlp, ahci_portp, port);
6272 
6273 	/* SStatus tells the presence of device. */
6274 	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6275 	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
6276 
6277 	if (SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_PHYCOM) {
6278 		dev_exists_end = 1;
6279 		ASSERT(ahci_portp->ahciport_device_type != SATA_DTYPE_NONE);
6280 	}
6281 
6282 	/* Check whether a hot plug event happened */
6283 	if (dev_exists_begin == 1 && dev_exists_end == 0) {
6284 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6285 		    "ahci_restart_port_wait_till_ready: port %d "
6286 		    "device is removed", port);
6287 		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_NODEV;
6288 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6289 		    "ahci_restart_port_wait_till_ready: port %d "
6290 		    "AHCI_PORT_FLAG_NODEV flag is set", port);
6291 		mutex_exit(&ahci_portp->ahciport_mutex);
6292 		(void) ahci_intr_phyrdy_change(ahci_ctlp, ahci_portp, port);
6293 		mutex_enter(&ahci_portp->ahciport_mutex);
6294 	}
6295 
6296 	return (rval);
6297 }
6298 
6299 /*
6300  * This routine may be called under four scenarios:
6301  *	a) do the recovery from fatal error
6302  *	b) or we need to timeout some commands
6303  *	c) or we need to abort some commands
6304  *	d) or we need reset device/port/controller
6305  *
6306  * In all these scenarios, we need to send any pending unfinished
6307  * commands up to sata framework.
6308  *
6309  * WARNING!!! ahciport_mutex should be acquired before the function is called.
6310  */
6311 static void
6312 ahci_mop_commands(ahci_ctl_t *ahci_ctlp,
6313     ahci_port_t *ahci_portp,
6314     uint32_t slot_status,
6315     uint32_t failed_tags,
6316     uint32_t timeout_tags,
6317     uint32_t aborted_tags,
6318     uint32_t reset_tags)
6319 {
6320 	uint32_t finished_tags = 0;
6321 	uint32_t unfinished_tags = 0;
6322 	int tmp_slot;
6323 	sata_pkt_t *satapkt;
6324 	int ncq_cmd_in_progress = 0;
6325 	int err_retri_cmd_in_progress = 0;
6326 
6327 	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
6328 	    "ahci_mop_commands entered: port: %d slot_status: 0x%x",
6329 	    ahci_portp->ahciport_port_num, slot_status);
6330 
6331 	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
6332 	    "ahci_mop_commands: failed_tags: 0x%x, "
6333 	    "timeout_tags: 0x%x aborted_tags: 0x%x, "
6334 	    "reset_tags: 0x%x", failed_tags,
6335 	    timeout_tags, aborted_tags, reset_tags);
6336 
6337 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6338 		finished_tags = ahci_portp->ahciport_pending_tags &
6339 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
6340 
6341 		unfinished_tags = slot_status &
6342 		    AHCI_SLOT_MASK(ahci_ctlp) &
6343 		    ~failed_tags &
6344 		    ~aborted_tags &
6345 		    ~reset_tags &
6346 		    ~timeout_tags;
6347 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6348 		ncq_cmd_in_progress = 1;
6349 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
6350 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
6351 
6352 		unfinished_tags = slot_status &
6353 		    AHCI_NCQ_SLOT_MASK(ahci_portp) &
6354 		    ~failed_tags &
6355 		    ~aborted_tags &
6356 		    ~reset_tags &
6357 		    ~timeout_tags;
6358 	} else if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6359 
6360 		/*
6361 		 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT is
6362 		 * set, it means REQUEST SENSE or READ LOG EXT command doesn't
6363 		 * complete successfully due to one of the following three
6364 		 * conditions:
6365 		 *
6366 		 *	1. Fatal error - failed_tags includes its slot
6367 		 *	2. Timed out - timeout_tags includes its slot
6368 		 *	3. Aborted when hot unplug - aborted_tags includes its
6369 		 *	   slot
6370 		 *
6371 		 * Please note that the command is always sent down in Slot 0
6372 		 */
6373 		err_retri_cmd_in_progress = 1;
6374 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_NCQ, ahci_ctlp,
6375 		    "ahci_mop_commands is called for port %d while "
6376 		    "REQUEST SENSE or READ LOG EXT for error retrieval "
6377 		    "is being executed slot_status = 0x%x",
6378 		    ahci_portp->ahciport_port_num, slot_status);
6379 		ASSERT(ahci_portp->ahciport_mop_in_progress > 1);
6380 		ASSERT(slot_status == 0x1);
6381 	}
6382 
6383 	/* Send up finished packets with SATA_PKT_COMPLETED */
6384 	while (finished_tags) {
6385 		tmp_slot = ddi_ffs(finished_tags) - 1;
6386 		if (tmp_slot == -1) {
6387 			break;
6388 		}
6389 
6390 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6391 		ASSERT(satapkt != NULL);
6392 
6393 		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_mop_commands: "
6394 		    "sending up pkt 0x%p with SATA_PKT_COMPLETED",
6395 		    (void *)satapkt);
6396 
6397 		/*
6398 		 * Cannot fetch the return register content since the port
6399 		 * was restarted, so the corresponding tag will be set to
6400 		 * aborted tags.
6401 		 */
6402 		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
6403 			CLEAR_BIT(finished_tags, tmp_slot);
6404 			aborted_tags |= tmp_slot;
6405 			continue;
6406 		}
6407 
6408 		if (ncq_cmd_in_progress)
6409 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6410 			    tmp_slot);
6411 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6412 		CLEAR_BIT(finished_tags, tmp_slot);
6413 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6414 
6415 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
6416 	}
6417 
6418 	/* Send up failed packets with SATA_PKT_DEV_ERROR. */
6419 	while (failed_tags) {
6420 		if (err_retri_cmd_in_progress) {
6421 			satapkt = ahci_portp->ahciport_err_retri_pkt;
6422 			ASSERT(satapkt != NULL);
6423 			ASSERT(failed_tags == 0x1);
6424 
6425 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6426 			    "sending up pkt 0x%p with SATA_PKT_DEV_ERROR",
6427 			    (void *)satapkt);
6428 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
6429 			break;
6430 		}
6431 
6432 		tmp_slot = ddi_ffs(failed_tags) - 1;
6433 		if (tmp_slot == -1) {
6434 			break;
6435 		}
6436 
6437 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6438 		ASSERT(satapkt != NULL);
6439 
6440 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6441 		    "sending up pkt 0x%p with SATA_PKT_DEV_ERROR",
6442 		    (void *)satapkt);
6443 
6444 		if (ncq_cmd_in_progress)
6445 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6446 			    tmp_slot);
6447 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6448 		CLEAR_BIT(failed_tags, tmp_slot);
6449 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6450 
6451 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
6452 	}
6453 
6454 	/* Send up timeout packets with SATA_PKT_TIMEOUT. */
6455 	while (timeout_tags) {
6456 		if (err_retri_cmd_in_progress) {
6457 			satapkt = ahci_portp->ahciport_err_retri_pkt;
6458 			ASSERT(satapkt != NULL);
6459 			ASSERT(timeout_tags == 0x1);
6460 
6461 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6462 			    "sending up pkt 0x%p with SATA_PKT_TIMEOUT",
6463 			    (void *)satapkt);
6464 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
6465 			break;
6466 		}
6467 
6468 		tmp_slot = ddi_ffs(timeout_tags) - 1;
6469 		if (tmp_slot == -1) {
6470 			break;
6471 		}
6472 
6473 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6474 		ASSERT(satapkt != NULL);
6475 
6476 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6477 		    "sending up pkt 0x%p with SATA_PKT_TIMEOUT",
6478 		    (void *)satapkt);
6479 
6480 		if (ncq_cmd_in_progress)
6481 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6482 			    tmp_slot);
6483 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6484 		CLEAR_BIT(timeout_tags, tmp_slot);
6485 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6486 
6487 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
6488 	}
6489 
6490 	/* Send up aborted packets with SATA_PKT_ABORTED */
6491 	while (aborted_tags) {
6492 		if (err_retri_cmd_in_progress) {
6493 			satapkt = ahci_portp->ahciport_err_retri_pkt;
6494 			ASSERT(satapkt != NULL);
6495 			ASSERT(aborted_tags == 0x1);
6496 
6497 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6498 			    "sending up pkt 0x%p with SATA_PKT_ABORTED",
6499 			    (void *)satapkt);
6500 			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
6501 			break;
6502 		}
6503 
6504 		tmp_slot = ddi_ffs(aborted_tags) - 1;
6505 		if (tmp_slot == -1) {
6506 			break;
6507 		}
6508 
6509 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6510 		ASSERT(satapkt != NULL);
6511 
6512 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6513 		    "sending up pkt 0x%p with SATA_PKT_ABORTED",
6514 		    (void *)satapkt);
6515 
6516 		if (ncq_cmd_in_progress)
6517 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6518 			    tmp_slot);
6519 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6520 		CLEAR_BIT(aborted_tags, tmp_slot);
6521 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6522 
6523 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
6524 	}
6525 
6526 	/* Send up reset packets with SATA_PKT_RESET. */
6527 	while (reset_tags) {
6528 		tmp_slot = ddi_ffs(reset_tags) - 1;
6529 		if (tmp_slot == -1) {
6530 			break;
6531 		}
6532 
6533 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6534 		ASSERT(satapkt != NULL);
6535 
6536 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6537 		    "sending up pkt 0x%p with SATA_PKT_RESET",
6538 		    (void *)satapkt);
6539 
6540 		if (ncq_cmd_in_progress)
6541 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6542 			    tmp_slot);
6543 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6544 		CLEAR_BIT(reset_tags, tmp_slot);
6545 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6546 
6547 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
6548 	}
6549 
6550 	/* Send up unfinished packets with SATA_PKT_RESET */
6551 	while (unfinished_tags) {
6552 		tmp_slot = ddi_ffs(unfinished_tags) - 1;
6553 		if (tmp_slot == -1) {
6554 			break;
6555 		}
6556 
6557 		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6558 		ASSERT(satapkt != NULL);
6559 
6560 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6561 		    "sending up pkt 0x%p with SATA_PKT_RESET",
6562 		    (void *)satapkt);
6563 
6564 		if (ncq_cmd_in_progress)
6565 			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6566 			    tmp_slot);
6567 		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6568 		CLEAR_BIT(unfinished_tags, tmp_slot);
6569 		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6570 
6571 		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
6572 	}
6573 
6574 	ahci_portp->ahciport_mop_in_progress--;
6575 	ASSERT(ahci_portp->ahciport_mop_in_progress >= 0);
6576 
6577 	if (ahci_portp->ahciport_mop_in_progress == 0)
6578 		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_MOPPING;
6579 }
6580 
6581 /*
6582  * This routine is going to first request a READ LOG EXT sata pkt from sata
6583  * module, and then deliver it to the HBA to get the ncq failure context.
6584  * The return value is the exactly failed tags.
6585  */
6586 static uint32_t
6587 ahci_get_rdlogext_data(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
6588     uint8_t port)
6589 {
6590 	sata_device_t	sdevice;
6591 	sata_pkt_t	*rdlog_spkt, *spkt;
6592 	ddi_dma_handle_t buf_dma_handle;
6593 	int		loop_count;
6594 	int		rval;
6595 	int		failed_slot;
6596 	uint32_t	failed_tags = 0;
6597 	struct sata_ncq_error_recovery_page *ncq_err_page;
6598 
6599 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_NCQ, ahci_ctlp,
6600 	    "ahci_get_rdlogext_data enter: port %d", port);
6601 
6602 	/* Prepare the sdevice data */
6603 	bzero((void *)&sdevice, sizeof (sata_device_t));
6604 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
6605 
6606 	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
6607 	sdevice.satadev_addr.pmport = 0;
6608 
6609 	/*
6610 	 * Call the sata hba interface to get a rdlog spkt
6611 	 */
6612 	loop_count = 0;
6613 loop:
6614 	rdlog_spkt = sata_get_error_retrieval_pkt(ahci_ctlp->ahcictl_dip,
6615 	    &sdevice, SATA_ERR_RETR_PKT_TYPE_NCQ);
6616 	if (rdlog_spkt == NULL) {
6617 		if (loop_count++ < AHCI_POLLRATE_GET_SPKT) {
6618 			/* Sleep for a while */
6619 			delay(AHCI_10MS_TICKS);
6620 			goto loop;
6621 		}
6622 		/* Timed out after 1s */
6623 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6624 		    "failed to get rdlog spkt for port %d", port);
6625 		return (failed_tags);
6626 	}
6627 
6628 	ASSERT(rdlog_spkt->satapkt_op_mode & SATA_OPMODE_SYNCH);
6629 
6630 	/*
6631 	 * This flag is used to handle the specific error recovery when the
6632 	 * READ LOG EXT command gets a failure (fatal error or time-out).
6633 	 */
6634 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RDLOGEXT;
6635 
6636 	/*
6637 	 * This start is not supposed to fail because after port is restarted,
6638 	 * the whole command list is empty.
6639 	 */
6640 	ahci_portp->ahciport_err_retri_pkt = rdlog_spkt;
6641 	(void) ahci_do_sync_start(ahci_ctlp, ahci_portp, port, rdlog_spkt);
6642 	ahci_portp->ahciport_err_retri_pkt = NULL;
6643 
6644 	/* Remove the flag after READ LOG EXT command is completed */
6645 	ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_RDLOGEXT;
6646 
6647 	if (rdlog_spkt->satapkt_reason == SATA_PKT_COMPLETED) {
6648 		/* Update the request log data */
6649 		buf_dma_handle = *(ddi_dma_handle_t *)
6650 		    (rdlog_spkt->satapkt_cmd.satacmd_err_ret_buf_handle);
6651 		rval = ddi_dma_sync(buf_dma_handle, 0, 0,
6652 		    DDI_DMA_SYNC_FORKERNEL);
6653 		if (rval == DDI_SUCCESS) {
6654 			ncq_err_page =
6655 			    (struct sata_ncq_error_recovery_page *)rdlog_spkt->
6656 			    satapkt_cmd.satacmd_bp->b_un.b_addr;
6657 
6658 			/* Get the failed tag */
6659 			failed_slot = ncq_err_page->ncq_tag;
6660 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6661 			    "ahci_get_rdlogext_data: port %d "
6662 			    "failed slot %d", port, failed_slot);
6663 			if (failed_slot & NQ) {
6664 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6665 				    "the failed slot is not a valid tag", NULL);
6666 				goto out;
6667 			}
6668 
6669 			failed_slot &= NCQ_TAG_MASK;
6670 			spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
6671 			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6672 			    "ahci_get_rdlogext_data: failed spkt 0x%p",
6673 			    (void *)spkt);
6674 			if (spkt == NULL) {
6675 				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6676 				    "the failed slot spkt is NULL", NULL);
6677 				goto out;
6678 			}
6679 
6680 			failed_tags = 0x1 << failed_slot;
6681 
6682 			/* Fill out the error context */
6683 			ahci_copy_ncq_err_page(&spkt->satapkt_cmd,
6684 			    ncq_err_page);
6685 			ahci_update_sata_registers(ahci_ctlp, port,
6686 			    &spkt->satapkt_device);
6687 		}
6688 	}
6689 out:
6690 	sata_free_error_retrieval_pkt(rdlog_spkt);
6691 
6692 	return (failed_tags);
6693 }
6694 
6695 /*
6696  * This routine is going to first request a REQUEST SENSE sata pkt from sata
6697  * module, and then deliver it to the HBA to get the sense data and copy
6698  * the sense data back to the orignal failed sata pkt, and free the REQUEST
6699  * SENSE sata pkt later.
6700  */
6701 static void
6702 ahci_get_rqsense_data(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
6703     uint8_t port, sata_pkt_t *spkt)
6704 {
6705 	sata_device_t	sdevice;
6706 	sata_pkt_t	*rs_spkt;
6707 	sata_cmd_t	*sata_cmd;
6708 	ddi_dma_handle_t buf_dma_handle;
6709 	int		loop_count;
6710 #if AHCI_DEBUG
6711 	struct scsi_extended_sense *rqsense;
6712 #endif
6713 
6714 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6715 	    "ahci_get_rqsense_data enter: port %d", port);
6716 
6717 	/* Prepare the sdevice data */
6718 	bzero((void *)&sdevice, sizeof (sata_device_t));
6719 	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
6720 
6721 	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
6722 	sdevice.satadev_addr.pmport = 0;
6723 
6724 	sata_cmd = &spkt->satapkt_cmd;
6725 
6726 	/*
6727 	 * Call the sata hba interface to get a rs spkt
6728 	 */
6729 	loop_count = 0;
6730 loop:
6731 	rs_spkt = sata_get_error_retrieval_pkt(ahci_ctlp->ahcictl_dip,
6732 	    &sdevice, SATA_ERR_RETR_PKT_TYPE_ATAPI);
6733 	if (rs_spkt == NULL) {
6734 		if (loop_count++ < AHCI_POLLRATE_GET_SPKT) {
6735 			/* Sleep for a while */
6736 			delay(AHCI_10MS_TICKS);
6737 			goto loop;
6738 
6739 		}
6740 		/* Timed out after 1s */
6741 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6742 		    "failed to get rs spkt for port %d", port);
6743 		return;
6744 	}
6745 
6746 	ASSERT(rs_spkt->satapkt_op_mode & SATA_OPMODE_SYNCH);
6747 
6748 	/*
6749 	 * This flag is used to handle the specific error recovery when the
6750 	 * REQUEST SENSE command gets a faiure (fatal error or time-out).
6751 	 */
6752 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RQSENSE;
6753 
6754 	/*
6755 	 * This start is not supposed to fail because after port is restarted,
6756 	 * the whole command list is empty.
6757 	 */
6758 	ahci_portp->ahciport_err_retri_pkt = rs_spkt;
6759 	(void) ahci_do_sync_start(ahci_ctlp, ahci_portp, port, rs_spkt);
6760 	ahci_portp->ahciport_err_retri_pkt = NULL;
6761 
6762 	/* Remove the flag after REQUEST SENSE command is completed */
6763 	ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_RQSENSE;
6764 
6765 	if (rs_spkt->satapkt_reason == SATA_PKT_COMPLETED) {
6766 		/* Update the request sense data */
6767 		buf_dma_handle = *(ddi_dma_handle_t *)
6768 		    (rs_spkt->satapkt_cmd.satacmd_err_ret_buf_handle);
6769 		(void) ddi_dma_sync(buf_dma_handle, 0, 0,
6770 		    DDI_DMA_SYNC_FORKERNEL);
6771 		/* Copy the request sense data */
6772 		bcopy(rs_spkt->
6773 		    satapkt_cmd.satacmd_bp->b_un.b_addr,
6774 		    &sata_cmd->satacmd_rqsense,
6775 		    SATA_ATAPI_MIN_RQSENSE_LEN);
6776 #if AHCI_DEBUG
6777 		rqsense = (struct scsi_extended_sense *)
6778 		    sata_cmd->satacmd_rqsense;
6779 
6780 		/* Dump the sense data */
6781 		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp, "\n", NULL);
6782 		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp,
6783 		    "Sense data for satapkt %p ATAPI cmd 0x%x",
6784 		    spkt, sata_cmd->satacmd_acdb[0]);
6785 		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp,
6786 		    "  es_code 0x%x es_class 0x%x "
6787 		    "es_key 0x%x es_add_code 0x%x "
6788 		    "es_qual_code 0x%x",
6789 		    rqsense->es_code, rqsense->es_class,
6790 		    rqsense->es_key, rqsense->es_add_code,
6791 		    rqsense->es_qual_code);
6792 #endif
6793 	}
6794 
6795 	sata_free_error_retrieval_pkt(rs_spkt);
6796 }
6797 
6798 /*
6799  * Fatal errors will cause the HBA to enter the ERR: Fatal state. To recover,
6800  * the port must be restarted. When the HBA detects thus error, it may try
6801  * to abort a transfer. And if the transfer was aborted, the device is
6802  * expected to send a D2H Register FIS with PxTFD.STS.ERR set to '1' and both
6803  * PxTFD.STS.BSY and PxTFD.STS.DRQ cleared to '0'. Then system software knows
6804  * that the device is in a stable status and transfers may be restarted without
6805  * issuing a COMRESET to the device. If PxTFD.STS.BSY or PxTFD.STS.DRQ is set,
6806  * then the software will send the COMRESET to do the port reset.
6807  *
6808  * Software should perform the appropriate error recovery actions based on
6809  * whether non-queued commands were being issued or natived command queuing
6810  * commands were being issued.
6811  *
6812  * And software will complete the command that had the error with error mark
6813  * to higher level software.
6814  *
6815  * Fatal errors include the following:
6816  *	PxIS.IFS - Interface Fatal Error Status
6817  *	PxIS.HBDS - Host Bus Data Error Status
6818  *	PxIS.HBFS - Host Bus Fatal Error Status
6819  *	PxIS.TFES - Task File Error Status
6820  *
6821  * WARNING!!! ahciport_mutex should be acquired before the function is called.
6822  */
6823 static void
6824 ahci_fatal_error_recovery_handler(ahci_ctl_t *ahci_ctlp,
6825     ahci_port_t *ahci_portp, uint8_t port, uint32_t intr_status)
6826 {
6827 	uint32_t	port_cmd_status;
6828 	uint32_t	slot_status = 0;
6829 	uint32_t	failed_tags = 0;
6830 	int		failed_slot;
6831 	int		reset_flag = 0;
6832 	ahci_fis_d2h_register_t	*ahci_rcvd_fisp;
6833 	sata_cmd_t	*sata_cmd = NULL;
6834 	sata_pkt_t	*spkt = NULL;
6835 #if AHCI_DEBUG
6836 	ahci_cmd_header_t *cmd_header;
6837 #endif
6838 
6839 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6840 	    "ahci_fatal_error_recovery_handler enter: port %d", port);
6841 
6842 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
6843 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6844 
6845 		/* Read PxCI to see which commands are still outstanding */
6846 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6847 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
6848 
6849 		/*
6850 		 * Read PxCMD.CCS to determine the slot that the HBA
6851 		 * was processing when the error occurred.
6852 		 */
6853 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6854 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6855 		failed_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
6856 		    AHCI_CMD_STATUS_CCS_SHIFT;
6857 
6858 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6859 			spkt = ahci_portp->ahciport_err_retri_pkt;
6860 			ASSERT(spkt != NULL);
6861 		} else {
6862 			spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
6863 			if (spkt == NULL) {
6864 				/* May happen when interface errors occur? */
6865 				goto next;
6866 			}
6867 		}
6868 
6869 #if AHCI_DEBUG
6870 		/*
6871 		 * Debugging purpose...
6872 		 */
6873 		if (ahci_portp->ahciport_prd_bytecounts[failed_slot]) {
6874 			cmd_header =
6875 			    &ahci_portp->ahciport_cmd_list[failed_slot];
6876 			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
6877 			    "ahci_fatal_error_recovery_handler: port %d, "
6878 			    "PRD Byte Count = 0x%x, "
6879 			    "ahciport_prd_bytecounts = 0x%x", port,
6880 			    cmd_header->ahcich_prd_byte_count,
6881 			    ahci_portp->ahciport_prd_bytecounts[failed_slot]);
6882 		}
6883 #endif
6884 
6885 		sata_cmd = &spkt->satapkt_cmd;
6886 
6887 		/* Fill out the status and error registers for PxIS.TFES */
6888 		if (intr_status & AHCI_INTR_STATUS_TFES) {
6889 			ahci_rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
6890 			    ahcirf_d2h_register_fis);
6891 
6892 			/* Copy the error context back to the sata_cmd */
6893 			ahci_copy_err_cnxt(sata_cmd, ahci_rcvd_fisp);
6894 		}
6895 
6896 		/* The failed command must be one of the outstanding commands */
6897 		failed_tags = 0x1 << failed_slot;
6898 		ASSERT(failed_tags & slot_status);
6899 
6900 		/* Update the sata registers, especially PxSERR register */
6901 		ahci_update_sata_registers(ahci_ctlp, port,
6902 		    &spkt->satapkt_device);
6903 
6904 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6905 		/* Read PxSACT to see which commands are still outstanding */
6906 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6907 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
6908 	}
6909 next:
6910 
6911 #if AHCI_DEBUG
6912 	/*
6913 	 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT flag is
6914 	 * set, it means a fatal error happened after REQUEST SENSE command
6915 	 * or READ LOG EXT command is delivered to the HBA during the error
6916 	 * recovery process. At this time, the only outstanding command is
6917 	 * supposed to be REQUEST SENSE command or READ LOG EXT command.
6918 	 */
6919 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6920 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6921 		    "ahci_fatal_error_recovery_handler: port %d REQUEST SENSE "
6922 		    "command or READ LOG EXT command for error data retrieval "
6923 		    "failed", port);
6924 		ASSERT(slot_status == 0x1);
6925 		ASSERT(failed_slot == 0);
6926 		ASSERT(spkt->satapkt_cmd.satacmd_acdb[0] ==
6927 		    SCMD_REQUEST_SENSE ||
6928 		    spkt->satapkt_cmd.satacmd_cmd_reg ==
6929 		    SATAC_READ_LOG_EXT);
6930 	}
6931 #endif
6932 
6933 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
6934 	ahci_portp->ahciport_mop_in_progress++;
6935 
6936 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
6937 	    port, NULL, &reset_flag);
6938 
6939 	/*
6940 	 * Won't retrieve error information:
6941 	 * 1. Port reset was involved to recover
6942 	 * 2. Device is gone
6943 	 * 3. IDENTIFY DEVICE command sent to ATAPI device
6944 	 * 4. REQUEST SENSE or READ LOG EXT command during error recovery
6945 	 */
6946 	if (reset_flag ||
6947 	    ahci_portp->ahciport_device_type == SATA_DTYPE_NONE ||
6948 	    spkt && spkt->satapkt_cmd.satacmd_cmd_reg == SATAC_ID_DEVICE ||
6949 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
6950 		goto out;
6951 
6952 	/*
6953 	 * Deliver READ LOG EXT to gather information about the error when
6954 	 * a COMRESET has not been performed as part of the error recovery
6955 	 * during NCQ command processing.
6956 	 */
6957 	if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6958 		failed_tags = ahci_get_rdlogext_data(ahci_ctlp,
6959 		    ahci_portp, port);
6960 		goto out;
6961 	}
6962 
6963 	/*
6964 	 * Deliver REQUEST SENSE for ATAPI command to gather information about
6965 	 * the error when a COMRESET has not been performed as part of the
6966 	 * error recovery.
6967 	 */
6968 	if (spkt && ahci_portp->ahciport_device_type == SATA_DTYPE_ATAPI)
6969 		ahci_get_rqsense_data(ahci_ctlp, ahci_portp, port, spkt);
6970 out:
6971 	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6972 	    "ahci_fatal_error_recovery_handler: port %d fatal error "
6973 	    "occurred slot_status = 0x%x, pending_tags = 0x%x, "
6974 	    "pending_ncq_tags = 0x%x failed_tags = 0x%x",
6975 	    port, slot_status, ahci_portp->ahciport_pending_tags,
6976 	    ahci_portp->ahciport_pending_ncq_tags, failed_tags);
6977 
6978 	ahci_mop_commands(ahci_ctlp,
6979 	    ahci_portp,
6980 	    slot_status,
6981 	    failed_tags, /* failed tags */
6982 	    0, /* timeout tags */
6983 	    0, /* aborted tags */
6984 	    0); /* reset tags */
6985 }
6986 
6987 /*
6988  * Handle events - fatal error recovery
6989  */
6990 static void
6991 ahci_events_handler(void *args)
6992 {
6993 	ahci_event_arg_t *ahci_event_arg;
6994 	ahci_ctl_t *ahci_ctlp;
6995 	ahci_port_t *ahci_portp;
6996 	uint32_t event;
6997 	uint8_t port;
6998 
6999 	ahci_event_arg = (ahci_event_arg_t *)args;
7000 
7001 	ahci_ctlp = ahci_event_arg->ahciea_ctlp;
7002 	ahci_portp = ahci_event_arg->ahciea_portp;
7003 	event = ahci_event_arg->ahciea_event;
7004 	port = ahci_portp->ahciport_port_num;
7005 
7006 	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
7007 	    "ahci_events_handler enter: port %d intr_status = 0x%x",
7008 	    port, event);
7009 
7010 	mutex_enter(&ahci_portp->ahciport_mutex);
7011 
7012 	/*
7013 	 * ahci_intr_phyrdy_change() may have rendered it to
7014 	 * SATA_DTYPE_NONE.
7015 	 */
7016 	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
7017 		AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
7018 		    "ahci_events_handler: port %d no device attached, "
7019 		    "and just return without doing anything", port);
7020 		goto out;
7021 	}
7022 
7023 	if (event & (AHCI_INTR_STATUS_IFS |
7024 	    AHCI_INTR_STATUS_HBDS |
7025 	    AHCI_INTR_STATUS_HBFS |
7026 	    AHCI_INTR_STATUS_TFES))
7027 		ahci_fatal_error_recovery_handler(ahci_ctlp, ahci_portp,
7028 		    port, event);
7029 
7030 out:
7031 	mutex_exit(&ahci_portp->ahciport_mutex);
7032 }
7033 
7034 /*
7035  * ahci_watchdog_handler() and ahci_do_sync_start will call us if they
7036  * detect there are some commands which are timed out.
7037  */
7038 static void
7039 ahci_timeout_pkts(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
7040     uint8_t port, uint32_t tmp_timeout_tags)
7041 {
7042 	uint32_t slot_status = 0;
7043 	uint32_t finished_tags = 0;
7044 	uint32_t timeout_tags = 0;
7045 
7046 	AHCIDBG(AHCIDBG_TIMEOUT|AHCIDBG_ENTRY, ahci_ctlp,
7047 	    "ahci_timeout_pkts enter: port %d", port);
7048 
7049 	mutex_enter(&ahci_portp->ahciport_mutex);
7050 
7051 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
7052 	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7053 		/* Read PxCI to see which commands are still outstanding */
7054 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7055 		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
7056 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7057 		/* Read PxSACT to see which commands are still outstanding */
7058 		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7059 		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
7060 	}
7061 
7062 #if AHCI_DEBUG
7063 	/*
7064 	 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT flag is
7065 	 * set, it means a fatal error happened after REQUEST SENSE command
7066 	 * or READ LOG EXT command is delivered to the HBA during the error
7067 	 * recovery process. At this time, the only outstanding command is
7068 	 * supposed to be REQUEST SENSE command or READ LOG EXT command.
7069 	 */
7070 	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7071 		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT, ahci_ctlp,
7072 		    "ahci_timeout_pkts called while REQUEST SENSE "
7073 		    "command or READ LOG EXT command for error recovery "
7074 		    "timed out timeout_tags = 0x%x, slot_status = 0x%x, "
7075 		    "pending_tags = 0x%x, pending_ncq_tags = 0x%x",
7076 		    tmp_timeout_tags, slot_status,
7077 		    ahci_portp->ahciport_pending_tags,
7078 		    ahci_portp->ahciport_pending_ncq_tags);
7079 		ASSERT(slot_status == 0x1);
7080 	}
7081 #endif
7082 
7083 	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
7084 	ahci_portp->ahciport_mop_in_progress++;
7085 
7086 	(void) ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
7087 	    port, NULL, NULL);
7088 
7089 	/*
7090 	 * Re-identify timeout tags because some previously checked commands
7091 	 * could already complete.
7092 	 */
7093 	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7094 		finished_tags = ahci_portp->ahciport_pending_tags &
7095 		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
7096 		timeout_tags = tmp_timeout_tags & ~finished_tags;
7097 
7098 		AHCIDBG(AHCIDBG_TIMEOUT, ahci_ctlp,
7099 		    "ahci_timeout_pkts: port %d, finished_tags = 0x%x, "
7100 		    "timeout_tags = 0x%x, port_cmd_issue = 0x%x, "
7101 		    "pending_tags = 0x%x ",
7102 		    port, finished_tags, timeout_tags,
7103 		    slot_status, ahci_portp->ahciport_pending_tags);
7104 	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7105 		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
7106 		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
7107 		timeout_tags = tmp_timeout_tags & ~finished_tags;
7108 
7109 		AHCIDBG(AHCIDBG_TIMEOUT|AHCIDBG_NCQ, ahci_ctlp,
7110 		    "ahci_timeout_pkts: port %d, finished_tags = 0x%x, "
7111 		    "timeout_tags = 0x%x, port_sactive = 0x%x, "
7112 		    "pending_ncq_tags = 0x%x ",
7113 		    port, finished_tags, timeout_tags,
7114 		    slot_status, ahci_portp->ahciport_pending_ncq_tags);
7115 	} else if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7116 		timeout_tags = tmp_timeout_tags;
7117 	}
7118 
7119 	ahci_mop_commands(ahci_ctlp,
7120 	    ahci_portp,
7121 	    slot_status,
7122 	    0, /* failed tags */
7123 	    timeout_tags, /* timeout tags */
7124 	    0, /* aborted tags */
7125 	    0); /* reset tags */
7126 
7127 	mutex_exit(&ahci_portp->ahciport_mutex);
7128 }
7129 
7130 /*
7131  * Watchdog handler kicks in every 5 seconds to timeout any commands pending
7132  * for long time.
7133  */
7134 static void
7135 ahci_watchdog_handler(ahci_ctl_t *ahci_ctlp)
7136 {
7137 	ahci_port_t *ahci_portp;
7138 	sata_pkt_t *spkt;
7139 	uint32_t pending_tags;
7140 	uint32_t timeout_tags;
7141 	uint32_t port_cmd_status;
7142 	uint32_t port_sactive;
7143 	uint8_t port;
7144 	int tmp_slot;
7145 	int current_slot;
7146 	uint32_t current_tags;
7147 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
7148 	/* max number of cycles this packet should survive */
7149 	int max_life_cycles;
7150 
7151 	/* how many cycles this packet survived so far */
7152 	int watched_cycles;
7153 
7154 	mutex_enter(&ahci_ctlp->ahcictl_mutex);
7155 
7156 	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
7157 	    "ahci_watchdog_handler entered", NULL);
7158 
7159 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
7160 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
7161 			continue;
7162 		}
7163 
7164 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
7165 
7166 		mutex_enter(&ahci_portp->ahciport_mutex);
7167 		if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
7168 			mutex_exit(&ahci_portp->ahciport_mutex);
7169 			continue;
7170 		}
7171 
7172 		/* Skip the check for those ports in error recovery */
7173 		if ((ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) &&
7174 		    !(ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))) {
7175 			mutex_exit(&ahci_portp->ahciport_mutex);
7176 			continue;
7177 		}
7178 
7179 		pending_tags = 0;
7180 		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7181 		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7182 
7183 		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7184 			current_slot = 0;
7185 			pending_tags = 0x1;
7186 		} else if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7187 			current_slot =
7188 			    (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
7189 			    AHCI_CMD_STATUS_CCS_SHIFT;
7190 			pending_tags = ahci_portp->ahciport_pending_tags;
7191 		} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7192 			port_sactive = ddi_get32(
7193 			    ahci_ctlp->ahcictl_ahci_acc_handle,
7194 			    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
7195 			current_tags = port_sactive &
7196 			    ~port_cmd_status &
7197 			    AHCI_NCQ_SLOT_MASK(ahci_portp);
7198 			pending_tags = ahci_portp->ahciport_pending_ncq_tags;
7199 		}
7200 
7201 		timeout_tags = 0;
7202 		while (pending_tags) {
7203 			tmp_slot = ddi_ffs(pending_tags) - 1;
7204 			if (tmp_slot == -1) {
7205 				break;
7206 			}
7207 
7208 			if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
7209 				spkt = ahci_portp->ahciport_err_retri_pkt;
7210 			else
7211 				spkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
7212 
7213 			if ((spkt != NULL) && spkt->satapkt_time &&
7214 			    !(spkt->satapkt_op_mode & SATA_OPMODE_POLLING)) {
7215 				/*
7216 				 * We are overloading satapkt_hba_driver_private
7217 				 * with watched_cycle count.
7218 				 *
7219 				 * If a packet has survived for more than it's
7220 				 * max life cycles, it is a candidate for time
7221 				 * out.
7222 				 */
7223 				watched_cycles = (int)(intptr_t)
7224 				    spkt->satapkt_hba_driver_private;
7225 				watched_cycles++;
7226 				max_life_cycles = (spkt->satapkt_time +
7227 				    ahci_watchdog_timeout - 1) /
7228 				    ahci_watchdog_timeout;
7229 
7230 				spkt->satapkt_hba_driver_private =
7231 				    (void *)(intptr_t)watched_cycles;
7232 
7233 				if (watched_cycles <= max_life_cycles)
7234 					goto next;
7235 
7236 #if AHCI_DEBUG
7237 				if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7238 					AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT,
7239 					    ahci_ctlp, "watchdog: the current "
7240 					    "tags is 0x%x", current_tags);
7241 				} else {
7242 					AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT,
7243 					    ahci_ctlp, "watchdog: the current "
7244 					    "slot is %d", current_slot);
7245 				}
7246 #endif
7247 
7248 				/*
7249 				 * We need to check whether the HBA has
7250 				 * begun to execute the command, if not,
7251 				 * then re-set the timer of the command.
7252 				 */
7253 				if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) &&
7254 				    (tmp_slot != current_slot) ||
7255 				    NCQ_CMD_IN_PROGRESS(ahci_portp) &&
7256 				    ((0x1 << tmp_slot) & current_tags)) {
7257 					spkt->satapkt_hba_driver_private =
7258 					    (void *)(intptr_t)0;
7259 				} else {
7260 					timeout_tags |= (0x1 << tmp_slot);
7261 					cmn_err(CE_WARN, "!ahci%d: watchdog "
7262 					    "port %d satapkt 0x%p timed out\n",
7263 					    instance, port, (void *)spkt);
7264 				}
7265 			}
7266 next:
7267 			CLEAR_BIT(pending_tags, tmp_slot);
7268 		}
7269 
7270 		if (timeout_tags) {
7271 			mutex_exit(&ahci_portp->ahciport_mutex);
7272 			mutex_exit(&ahci_ctlp->ahcictl_mutex);
7273 			ahci_timeout_pkts(ahci_ctlp, ahci_portp,
7274 			    port, timeout_tags);
7275 			mutex_enter(&ahci_ctlp->ahcictl_mutex);
7276 			mutex_enter(&ahci_portp->ahciport_mutex);
7277 		}
7278 
7279 		mutex_exit(&ahci_portp->ahciport_mutex);
7280 	}
7281 
7282 	/* Re-install the watchdog timeout handler */
7283 	if (ahci_ctlp->ahcictl_timeout_id != 0) {
7284 		ahci_ctlp->ahcictl_timeout_id =
7285 		    timeout((void (*)(void *))ahci_watchdog_handler,
7286 		    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
7287 	}
7288 
7289 	mutex_exit(&ahci_ctlp->ahcictl_mutex);
7290 }
7291 
7292 /*
7293  * Fill the error context into sata_cmd for non-queued command error.
7294  */
7295 static void
7296 ahci_copy_err_cnxt(sata_cmd_t *scmd, ahci_fis_d2h_register_t *rfisp)
7297 {
7298 	scmd->satacmd_status_reg = GET_RFIS_STATUS(rfisp);
7299 	scmd->satacmd_error_reg = GET_RFIS_ERROR(rfisp);
7300 	scmd->satacmd_sec_count_lsb = GET_RFIS_SECTOR_COUNT(rfisp);
7301 	scmd->satacmd_lba_low_lsb = GET_RFIS_CYL_LOW(rfisp);
7302 	scmd->satacmd_lba_mid_lsb = GET_RFIS_CYL_MID(rfisp);
7303 	scmd->satacmd_lba_high_lsb = GET_RFIS_CYL_HI(rfisp);
7304 	scmd->satacmd_device_reg = GET_RFIS_DEV_HEAD(rfisp);
7305 
7306 	if (scmd->satacmd_addr_type == ATA_ADDR_LBA48) {
7307 		scmd->satacmd_sec_count_msb = GET_RFIS_SECTOR_COUNT_EXP(rfisp);
7308 		scmd->satacmd_lba_low_msb = GET_RFIS_CYL_LOW_EXP(rfisp);
7309 		scmd->satacmd_lba_mid_msb = GET_RFIS_CYL_MID_EXP(rfisp);
7310 		scmd->satacmd_lba_high_msb = GET_RFIS_CYL_HI_EXP(rfisp);
7311 	}
7312 }
7313 
7314 /*
7315  * Fill the ncq error page into sata_cmd for queued command error.
7316  */
7317 static void
7318 ahci_copy_ncq_err_page(sata_cmd_t *scmd,
7319     struct sata_ncq_error_recovery_page *ncq_err_page)
7320 {
7321 	scmd->satacmd_sec_count_msb = ncq_err_page->ncq_sector_count_ext;
7322 	scmd->satacmd_sec_count_lsb = ncq_err_page->ncq_sector_count;
7323 	scmd->satacmd_lba_low_msb = ncq_err_page->ncq_sector_number_ext;
7324 	scmd->satacmd_lba_low_lsb = ncq_err_page->ncq_sector_number;
7325 	scmd->satacmd_lba_mid_msb = ncq_err_page->ncq_cyl_low_ext;
7326 	scmd->satacmd_lba_mid_lsb = ncq_err_page->ncq_cyl_low;
7327 	scmd->satacmd_lba_high_msb = ncq_err_page->ncq_cyl_high_ext;
7328 	scmd->satacmd_lba_high_lsb = ncq_err_page->ncq_cyl_high;
7329 	scmd->satacmd_device_reg = ncq_err_page->ncq_dev_head;
7330 	scmd->satacmd_status_reg = ncq_err_page->ncq_status;
7331 	scmd->satacmd_error_reg = ncq_err_page->ncq_error;
7332 }
7333 
7334 /*
7335  * Put the respective register value to sata_cmd_t for satacmd_flags.
7336  */
7337 static void
7338 ahci_copy_out_regs(sata_cmd_t *scmd, ahci_fis_d2h_register_t *rfisp)
7339 {
7340 	if (scmd->satacmd_flags.sata_copy_out_sec_count_msb)
7341 		scmd->satacmd_sec_count_msb = GET_RFIS_SECTOR_COUNT_EXP(rfisp);
7342 	if (scmd->satacmd_flags.sata_copy_out_lba_low_msb)
7343 		scmd->satacmd_lba_low_msb = GET_RFIS_CYL_LOW_EXP(rfisp);
7344 	if (scmd->satacmd_flags.sata_copy_out_lba_mid_msb)
7345 		scmd->satacmd_lba_mid_msb = GET_RFIS_CYL_MID_EXP(rfisp);
7346 	if (scmd->satacmd_flags.sata_copy_out_lba_high_msb)
7347 		scmd->satacmd_lba_high_msb = GET_RFIS_CYL_HI_EXP(rfisp);
7348 	if (scmd->satacmd_flags.sata_copy_out_sec_count_lsb)
7349 		scmd->satacmd_sec_count_lsb = GET_RFIS_SECTOR_COUNT(rfisp);
7350 	if (scmd->satacmd_flags.sata_copy_out_lba_low_lsb)
7351 		scmd->satacmd_lba_low_lsb = GET_RFIS_CYL_LOW(rfisp);
7352 	if (scmd->satacmd_flags.sata_copy_out_lba_mid_lsb)
7353 		scmd->satacmd_lba_mid_lsb = GET_RFIS_CYL_MID(rfisp);
7354 	if (scmd->satacmd_flags.sata_copy_out_lba_high_lsb)
7355 		scmd->satacmd_lba_high_lsb = GET_RFIS_CYL_HI(rfisp);
7356 	if (scmd->satacmd_flags.sata_copy_out_device_reg)
7357 		scmd->satacmd_device_reg = GET_RFIS_DEV_HEAD(rfisp);
7358 	if (scmd->satacmd_flags.sata_copy_out_error_reg)
7359 		scmd->satacmd_error_reg = GET_RFIS_ERROR(rfisp);
7360 }
7361 
7362 static void
7363 ahci_log_fatal_error_message(ahci_ctl_t *ahci_ctlp, uint8_t port,
7364     uint32_t intr_status)
7365 {
7366 	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
7367 
7368 	if (intr_status & AHCI_INTR_STATUS_IFS)
7369 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has interface fatal "
7370 		    "error", instance, port);
7371 
7372 	if (intr_status & AHCI_INTR_STATUS_HBDS)
7373 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has bus data error",
7374 		    instance, port);
7375 
7376 	if (intr_status & AHCI_INTR_STATUS_HBFS)
7377 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has bus fatal error",
7378 		    instance, port);
7379 
7380 	if (intr_status & AHCI_INTR_STATUS_TFES)
7381 		cmn_err(CE_WARN, "!ahci%d: ahci port %d has task file error",
7382 		    instance, port);
7383 
7384 	cmn_err(CE_WARN, "!ahci%d: ahci port %d is trying to do error "
7385 	    "recovery", instance, port);
7386 }
7387 
7388 /*
7389  * Dump the serror message to the log.
7390  */
7391 static void
7392 ahci_log_serror_message(ahci_ctl_t *ahci_ctlp, uint8_t port,
7393     uint32_t port_serror, int debug_only)
7394 {
7395 	static char err_buf[512];
7396 	static char err_msg_header[16];
7397 	char *err_msg = err_buf;
7398 
7399 	*err_buf = '\0';
7400 	*err_msg_header = '\0';
7401 
7402 	if (port_serror & SERROR_DATA_ERR_FIXED) {
7403 		err_msg = strcat(err_msg,
7404 		    "\tRecovered Data Integrity Error (I)\n");
7405 	}
7406 
7407 	if (port_serror & SERROR_COMM_ERR_FIXED) {
7408 		err_msg = strcat(err_msg,
7409 		    "\tRecovered Communication Error (M)\n");
7410 	}
7411 
7412 	if (port_serror & SERROR_DATA_ERR) {
7413 		err_msg = strcat(err_msg,
7414 		    "\tTransient Data Integrity Error (T)\n");
7415 	}
7416 
7417 	if (port_serror & SERROR_PERSISTENT_ERR) {
7418 		err_msg = strcat(err_msg,
7419 		    "\tPersistent Communication or Data Integrity Error (C)\n");
7420 	}
7421 
7422 	if (port_serror & SERROR_PROTOCOL_ERR) {
7423 		err_msg = strcat(err_msg, "\tProtocol Error (P)\n");
7424 	}
7425 
7426 	if (port_serror & SERROR_INT_ERR) {
7427 		err_msg = strcat(err_msg, "\tInternal Error (E)\n");
7428 	}
7429 
7430 	if (port_serror & SERROR_PHY_RDY_CHG) {
7431 		err_msg = strcat(err_msg, "\tPhyRdy Change (N)\n");
7432 	}
7433 
7434 	if (port_serror & SERROR_PHY_INT_ERR) {
7435 		err_msg = strcat(err_msg, "\tPhy Internal Error (I)\n");
7436 	}
7437 
7438 	if (port_serror & SERROR_COMM_WAKE) {
7439 		err_msg = strcat(err_msg, "\tComm Wake (W)\n");
7440 	}
7441 
7442 	if (port_serror & SERROR_10B_TO_8B_ERR) {
7443 		err_msg = strcat(err_msg, "\t10B to 8B Decode Error (B)\n");
7444 	}
7445 
7446 	if (port_serror & SERROR_DISPARITY_ERR) {
7447 		err_msg = strcat(err_msg, "\tDisparity Error (D)\n");
7448 	}
7449 
7450 	if (port_serror & SERROR_CRC_ERR) {
7451 		err_msg = strcat(err_msg, "\tCRC Error (C)\n");
7452 	}
7453 
7454 	if (port_serror & SERROR_HANDSHAKE_ERR) {
7455 		err_msg = strcat(err_msg, "\tHandshake Error (H)\n");
7456 	}
7457 
7458 	if (port_serror & SERROR_LINK_SEQ_ERR) {
7459 		err_msg = strcat(err_msg, "\tLink Sequence Error (S)\n");
7460 	}
7461 
7462 	if (port_serror & SERROR_TRANS_ERR) {
7463 		err_msg = strcat(err_msg,
7464 		    "\tTransport state transition error (T)\n");
7465 	}
7466 
7467 	if (port_serror & SERROR_FIS_TYPE) {
7468 		err_msg = strcat(err_msg, "\tUnknown FIS Type (F)\n");
7469 	}
7470 
7471 	if (port_serror & SERROR_EXCHANGED_ERR) {
7472 		err_msg = strcat(err_msg, "\tExchanged (X)\n");
7473 	}
7474 
7475 	if (err_msg == NULL)
7476 		return;
7477 
7478 	if (debug_only) {
7479 		(void) sprintf(err_msg_header, "port %d", port);
7480 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, err_msg_header, NULL);
7481 		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, err_msg, NULL);
7482 	} else if (ahci_ctlp) {
7483 		cmn_err(CE_WARN, "!ahci%d: %s %s",
7484 		    ddi_get_instance(ahci_ctlp->ahcictl_dip),
7485 		    err_msg_header, err_msg);
7486 
7487 		/* sata trace debug */
7488 		sata_trace_debug(ahci_ctlp->ahcictl_dip,
7489 		    "ahci%d: %s %s", ddi_get_instance(ahci_ctlp->ahcictl_dip),
7490 		    err_msg_header, err_msg);
7491 	} else {
7492 		cmn_err(CE_WARN, "!ahci: %s %s", err_msg_header, err_msg);
7493 
7494 		/* sata trace debug */
7495 		sata_trace_debug(NULL, "ahci: %s %s", err_msg_header, err_msg);
7496 	}
7497 }
7498 
7499 /*
7500  * This routine is to calculate the total number of ports implemented
7501  * by the HBA.
7502  */
7503 static int
7504 ahci_get_num_implemented_ports(uint32_t ports_implemented)
7505 {
7506 	uint8_t i;
7507 	int num = 0;
7508 
7509 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
7510 		if (((uint32_t)0x1 << i) & ports_implemented)
7511 			num++;
7512 	}
7513 
7514 	return (num);
7515 }
7516 
7517 #if AHCI_DEBUG
7518 static void
7519 ahci_log(ahci_ctl_t *ahci_ctlp, uint_t level, char *fmt, ...)
7520 {
7521 	static char name[16];
7522 	va_list ap;
7523 
7524 	mutex_enter(&ahci_log_mutex);
7525 
7526 	va_start(ap, fmt);
7527 	if (ahci_ctlp) {
7528 		(void) sprintf(name, "ahci%d: ",
7529 		    ddi_get_instance(ahci_ctlp->ahcictl_dip));
7530 	} else {
7531 		(void) sprintf(name, "ahci: ");
7532 	}
7533 
7534 	(void) vsprintf(ahci_log_buf, fmt, ap);
7535 	va_end(ap);
7536 
7537 	cmn_err(level, "%s%s", name, ahci_log_buf);
7538 
7539 	mutex_exit(&ahci_log_mutex);
7540 }
7541 #endif
7542 
7543 /*
7544  * quiesce(9E) entry point.
7545  *
7546  * This function is called when the system is single-threaded at high
7547  * PIL with preemption disabled. Therefore, this function must not be
7548  * blocked.
7549  *
7550  * This function returns DDI_SUCCESS on success, or DDI_FAILURE on failure.
7551  * DDI_FAILURE indicates an error condition and should almost never happen.
7552  */
7553 static int
7554 ahci_quiesce(dev_info_t *dip)
7555 {
7556 	ahci_ctl_t *ahci_ctlp;
7557 	ahci_port_t *ahci_portp;
7558 	int instance, port;
7559 
7560 	instance = ddi_get_instance(dip);
7561 	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
7562 
7563 	if (ahci_ctlp == NULL)
7564 		return (DDI_FAILURE);
7565 
7566 #if AHCI_DEBUG
7567 	ahci_debug_flags = 0;
7568 #endif
7569 
7570 	/* disable all the interrupts. */
7571 	ahci_disable_all_intrs(ahci_ctlp);
7572 
7573 	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
7574 		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
7575 			continue;
7576 		}
7577 
7578 		ahci_portp = ahci_ctlp->ahcictl_ports[port];
7579 
7580 		/*
7581 		 * Stop the port by clearing PxCMD.ST
7582 		 *
7583 		 * Here we must disable the port interrupt because
7584 		 * ahci_disable_all_intrs only clear GHC.IE, and IS
7585 		 * register will be still set if PxIE is enabled.
7586 		 * When ahci shares one IRQ with other drivers, the
7587 		 * intr handler may claim the intr mistakenly.
7588 		 */
7589 		ahci_disable_port_intrs(ahci_ctlp, port);
7590 		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
7591 		    ahci_portp, port);
7592 	}
7593 
7594 	return (DDI_SUCCESS);
7595 }
7596