ahci.c revision 10225:c372315f6ac2
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 */
58static char ahci_ident[] = "ahci driver";
59
60/*
61 * Function prototypes for driver entry points
62 */
63static	int ahci_attach(dev_info_t *, ddi_attach_cmd_t);
64static	int ahci_detach(dev_info_t *, ddi_detach_cmd_t);
65static	int ahci_getinfo(dev_info_t *, ddi_info_cmd_t, void *, void **);
66static	int ahci_quiesce(dev_info_t *);
67
68/*
69 * Function prototypes for SATA Framework interfaces
70 */
71static	int ahci_register_sata_hba_tran(ahci_ctl_t *, uint32_t);
72static	int ahci_unregister_sata_hba_tran(ahci_ctl_t *);
73
74static	int ahci_tran_probe_port(dev_info_t *, sata_device_t *);
75static	int ahci_tran_start(dev_info_t *, sata_pkt_t *spkt);
76static	int ahci_tran_abort(dev_info_t *, sata_pkt_t *, int);
77static	int ahci_tran_reset_dport(dev_info_t *, sata_device_t *);
78static	int ahci_tran_hotplug_port_activate(dev_info_t *, sata_device_t *);
79static	int ahci_tran_hotplug_port_deactivate(dev_info_t *, sata_device_t *);
80#if defined(__lock_lint)
81static	int ahci_selftest(dev_info_t *, sata_device_t *);
82#endif
83
84/*
85 * Local function prototypes
86 */
87static	int ahci_alloc_ports_state(ahci_ctl_t *);
88static	void ahci_dealloc_ports_state(ahci_ctl_t *);
89static	int ahci_alloc_port_state(ahci_ctl_t *, uint8_t);
90static	void ahci_dealloc_port_state(ahci_ctl_t *, uint8_t);
91static	int ahci_alloc_rcvd_fis(ahci_ctl_t *, ahci_port_t *, uint8_t);
92static	void ahci_dealloc_rcvd_fis(ahci_port_t *);
93static	int ahci_alloc_cmd_list(ahci_ctl_t *, ahci_port_t *, uint8_t);
94static	void ahci_dealloc_cmd_list(ahci_ctl_t *, ahci_port_t *);
95static  int ahci_alloc_cmd_tables(ahci_ctl_t *, ahci_port_t *);
96static  void ahci_dealloc_cmd_tables(ahci_ctl_t *, ahci_port_t *);
97
98static	int ahci_initialize_controller(ahci_ctl_t *);
99static	void ahci_uninitialize_controller(ahci_ctl_t *);
100static	int ahci_initialize_port(ahci_ctl_t *, ahci_port_t *, uint8_t);
101static	int ahci_config_space_init(ahci_ctl_t *);
102
103static	void ahci_drain_ports_taskq(ahci_ctl_t *);
104static	void ahci_disable_interface_pm(ahci_ctl_t *, uint8_t);
105static	int ahci_start_port(ahci_ctl_t *, ahci_port_t *, uint8_t);
106static	void ahci_find_dev_signature(ahci_ctl_t *, ahci_port_t *, uint8_t);
107static	void ahci_update_sata_registers(ahci_ctl_t *, uint8_t, sata_device_t *);
108static	int ahci_deliver_satapkt(ahci_ctl_t *, ahci_port_t *,
109    uint8_t, sata_pkt_t *);
110static	int ahci_do_sync_start(ahci_ctl_t *, ahci_port_t *,
111    uint8_t, sata_pkt_t *);
112static	int ahci_claim_free_slot(ahci_ctl_t *, ahci_port_t *, int);
113static  void ahci_copy_err_cnxt(sata_cmd_t *, ahci_fis_d2h_register_t *);
114static	void ahci_copy_ncq_err_page(sata_cmd_t *,
115    struct sata_ncq_error_recovery_page *);
116static	void ahci_copy_out_regs(sata_cmd_t *, ahci_fis_d2h_register_t *);
117
118static	int ahci_software_reset(ahci_ctl_t *, ahci_port_t *, uint8_t);
119static	int ahci_hba_reset(ahci_ctl_t *);
120static	int ahci_port_reset(ahci_ctl_t *, ahci_port_t *, uint8_t);
121static	void ahci_reject_all_abort_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
122static	int ahci_reset_device_reject_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
123static	int ahci_reset_port_reject_pkts(ahci_ctl_t *, ahci_port_t *, uint8_t);
124static	int ahci_reset_hba_reject_pkts(ahci_ctl_t *);
125static	int ahci_put_port_into_notrunning_state(ahci_ctl_t *, ahci_port_t *,
126    uint8_t);
127static	int ahci_restart_port_wait_till_ready(ahci_ctl_t *, ahci_port_t *,
128    uint8_t, int, int *);
129static	void ahci_mop_commands(ahci_ctl_t *, ahci_port_t *, uint32_t,
130    uint32_t, uint32_t, uint32_t, uint32_t);
131static	uint32_t ahci_get_rdlogext_data(ahci_ctl_t *, ahci_port_t *, uint8_t);
132static void ahci_get_rqsense_data(ahci_ctl_t *, ahci_port_t *,
133    uint8_t, sata_pkt_t *);
134static	void ahci_fatal_error_recovery_handler(ahci_ctl_t *, ahci_port_t *,
135    uint8_t, uint32_t);
136static	void ahci_timeout_pkts(ahci_ctl_t *, ahci_port_t *,
137    uint8_t, uint32_t);
138static	void ahci_events_handler(void *);
139static	void ahci_watchdog_handler(ahci_ctl_t *);
140
141static	uint_t ahci_intr(caddr_t, caddr_t);
142static	void ahci_port_intr(ahci_ctl_t *, ahci_port_t *, uint8_t);
143static	int ahci_add_intrs(ahci_ctl_t *, int);
144static	void ahci_rem_intrs(ahci_ctl_t *);
145static	void ahci_enable_all_intrs(ahci_ctl_t *);
146static	void ahci_disable_all_intrs(ahci_ctl_t *);
147static	void ahci_enable_port_intrs(ahci_ctl_t *, uint8_t);
148static	void ahci_disable_port_intrs(ahci_ctl_t *, uint8_t);
149
150static  int ahci_intr_cmd_cmplt(ahci_ctl_t *, ahci_port_t *, uint8_t);
151static	int ahci_intr_set_device_bits(ahci_ctl_t *, ahci_port_t *, uint8_t);
152static	int ahci_intr_port_connect_change(ahci_ctl_t *, ahci_port_t *, uint8_t);
153static	int ahci_intr_device_mechanical_presence_status(ahci_ctl_t *,
154    ahci_port_t *, uint8_t);
155static	int ahci_intr_phyrdy_change(ahci_ctl_t *, ahci_port_t *, uint8_t);
156static	int ahci_intr_non_fatal_error(ahci_ctl_t *, ahci_port_t *,
157    uint8_t, uint32_t);
158static  int ahci_intr_fatal_error(ahci_ctl_t *, ahci_port_t *,
159    uint8_t, uint32_t);
160static	int ahci_intr_cold_port_detect(ahci_ctl_t *, ahci_port_t *, uint8_t);
161
162static	int ahci_get_num_implemented_ports(uint32_t);
163static  void ahci_log_fatal_error_message(ahci_ctl_t *, uint8_t port,
164    uint32_t);
165static	void ahci_log_serror_message(ahci_ctl_t *, uint8_t, uint32_t, int);
166#if AHCI_DEBUG
167static	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 */
177static 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 */
198static 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 */
219static 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 */
240static 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 */
257static ddi_device_acc_attr_t accattr = {
258	DDI_DEVICE_ATTR_V0,
259	DDI_STRUCTURE_LE_ACC,
260	DDI_STRICTORDER_ACC
261};
262
263
264static 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
279static 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
285extern struct mod_ops mod_driverops;
286
287static  struct modldrv modldrv = {
288	&mod_driverops,		/* driverops */
289	ahci_ident,		/* short description */
290	&ahcictl_dev_ops,	/* driver ops */
291};
292
293static  struct modlinkage modlinkage = {
294	MODREV_1,
295	&modldrv,
296	NULL
297};
298
299/* The following variables are watchdog handler related */
300static int ahci_watchdog_timeout = 5; /* 5 seconds */
301static 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 */
308static 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 */
320int ahci_dma_prdt_number = AHCI_PRDT_NUMBER;
321
322/* AHCI MSI is tunable */
323boolean_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 */
331boolean_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 */
342boolean_t ahci_commu_64bit_dma = B_TRUE;
343
344/*
345 * End of global tunable variable definition
346 */
347
348#if AHCI_DEBUG
349uint32_t ahci_debug_flags = 0;
350#else
351uint32_t ahci_debug_flags = (AHCIDBG_ERRS|AHCIDBG_TIMEOUT);
352#endif
353
354
355#if AHCI_DEBUG
356/* The following is needed for ahci_log() */
357static kmutex_t ahci_log_mutex;
358static char ahci_log_buf[512];
359#endif
360
361/* Opaque state pointer initialized by ddi_soft_state_init() */
362static void *ahci_statep = NULL;
363
364/*
365 *  ahci module initialization.
366 */
367int
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
404err_out:
405	cmn_err(CE_WARN, "!ahci: Module init failed");
406	return (ret);
407}
408
409/*
410 * ahci module uninitialize.
411 */
412int
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 */
435int
436_info(struct modinfo *modinfop)
437{
438	return (mod_info(&modlinkage, modinfop));
439}
440
441/*
442 * The attach entry point for dev_ops.
443 */
444static int
445ahci_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
752intr_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
843err_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 */
885static int
886ahci_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 */
989static int
990ahci_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 */
1027static int
1028ahci_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 */
1120static int
1121ahci_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 */
1153static int
1154ahci_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
1254out:
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 */
1290static int
1291ahci_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 */
1439static int
1440ahci_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 */
1549static int
1550ahci_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
1628out:
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 */
1644static int
1645ahci_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 */
1977static int
1978ahci_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 */
2145static int
2146ahci_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 */
2243static int
2244ahci_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 */
2307static int
2308ahci_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	}
2392out:
2393	return (ret);
2394}
2395
2396/*
2397 * Called by sata framework to reset a port(s) or device.
2398 */
2399static int
2400ahci_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 */
2500static int
2501ahci_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 */
2553static int
2554ahci_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
2591phy_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 */
2612static void
2613ahci_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
2652out:
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)
2669static int
2670ahci_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 */
2679static int
2680ahci_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
2709err_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 */
2723static void
2724ahci_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 */
2740static void
2741ahci_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 */
2771static int
2772ahci_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 */
2838static void
2839ahci_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 */
2883static int
2884ahci_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		/* Incorrect task file state, we need to reset port */
2929		ret = ahci_port_reset(ahci_ctlp, ahci_portp, port);
2930
2931		/* Does port reset succeed on HBA port? */
2932		if (ret != AHCI_SUCCESS) {
2933			AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
2934			    "ahci_initialize_port:"
2935			    "port reset faild at port %d", port);
2936			return (AHCI_FAILURE);
2937		}
2938
2939		/* Is port failed? */
2940		if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED) {
2941			AHCIDBG(AHCIDBG_INIT|AHCIDBG_ERRS, ahci_ctlp,
2942			    "ahci_initialize_port: port %d state 0x%x",
2943			    port, ahci_portp->ahciport_port_state);
2944			return (AHCI_FAILURE);
2945		}
2946	}
2947
2948	ahci_portp->ahciport_port_state = SATA_STATE_READY;
2949
2950	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "port %d is ready now.", port);
2951
2952	/*
2953	 * At the time being, only probe ports/devices and get the types of
2954	 * attached devices during DDI_ATTACH. In fact, the device can be
2955	 * changed during power state changes, but at the time being, we
2956	 * don't support the situation.
2957	 */
2958	if (ahci_ctlp->ahcictl_flags & AHCI_ATTACH) {
2959		/*
2960		 * Try to get the device signature if the port is
2961		 * not empty.
2962		 */
2963		if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE)
2964			ahci_find_dev_signature(ahci_ctlp, ahci_portp, port);
2965	} else {
2966
2967		/*
2968		 * During the resume, we need to set the PxCLB, PxCLBU, PxFB
2969		 * and PxFBU registers in case these registers were cleared
2970		 * during the suspend.
2971		 */
2972		AHCIDBG(AHCIDBG_PM, ahci_ctlp,
2973		    "ahci_initialize_port: port %d "
2974		    "reset the port during resume", port);
2975		(void) ahci_port_reset(ahci_ctlp, ahci_portp, port);
2976
2977		AHCIDBG(AHCIDBG_PM, ahci_ctlp,
2978		    "ahci_initialize_port: port %d "
2979		    "set PxCLB, PxCLBU, PxFB and PxFBU "
2980		    "during resume", port);
2981
2982		/* Config Port Received FIS Base Address */
2983		ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
2984		    (uint64_t *)AHCI_PORT_PxFB(ahci_ctlp, port),
2985		    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
2986
2987		/* Config Port Command List Base Address */
2988		ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
2989		    (uint64_t *)AHCI_PORT_PxCLB(ahci_ctlp, port),
2990		    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
2991	}
2992
2993	/* Return directly if no device connected */
2994	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
2995		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
2996		    "No device connected to port %d", port);
2997		goto out;
2998	}
2999
3000	/* Try to start the port */
3001	if (ahci_start_port(ahci_ctlp, ahci_portp, port)
3002	    != AHCI_SUCCESS) {
3003		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3004		    "failed to start port %d", port);
3005		return (AHCI_FAILURE);
3006	}
3007out:
3008	/* Enable port interrupts */
3009	ahci_enable_port_intrs(ahci_ctlp, port);
3010
3011	return (AHCI_SUCCESS);
3012}
3013
3014/*
3015 *  Handle hardware defect, and check the capabilities. For example,
3016 *  power management capabilty and MSI capability.
3017 */
3018static int
3019ahci_config_space_init(ahci_ctl_t *ahci_ctlp)
3020{
3021	ushort_t venid, devid;
3022	ushort_t caps_ptr, cap_count, cap;
3023#if AHCI_DEBUG
3024	ushort_t pmcap, pmcsr;
3025	ushort_t msimc;
3026#endif
3027	uint8_t revision;
3028
3029	venid = pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3030	    PCI_CONF_VENID);
3031
3032	devid = pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3033	    PCI_CONF_DEVID);
3034
3035	/*
3036	 * Modify dma_attr_align of ahcictl_buffer_dma_attr. For VT8251, those
3037	 * controllers with 0x00 revision id work on 4-byte aligned buffer,
3038	 * which is a bug and was fixed after 0x00 revision id controllers.
3039	 *
3040	 * Moreover, VT8251 cannot use multiple command slots in the command
3041	 * list for non-queued commands because the previous register content
3042	 * of PxCI can be re-written in the register write, so a flag will be
3043	 * set to record this defect - AHCI_CAP_NO_MCMDLIST_NONQUEUE.
3044	 */
3045	if (venid == VIA_VENID) {
3046		revision = pci_config_get8(ahci_ctlp->ahcictl_pci_conf_handle,
3047		    PCI_CONF_REVID);
3048		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3049		    "revision id = 0x%x", revision);
3050		if (revision == 0x00) {
3051			ahci_ctlp->ahcictl_buffer_dma_attr.dma_attr_align = 0x4;
3052			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3053			    "change ddi_attr_align to 0x4", NULL);
3054		}
3055
3056		ahci_ctlp->ahcictl_cap = AHCI_CAP_NO_MCMDLIST_NONQUEUE;
3057		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3058		    "VT8251 cannot use multiple command lists for "
3059		    "non-queued commands", NULL);
3060	}
3061
3062	/*
3063	 * AMD/ATI SB600 (1002,4380) AHCI chipset doesn't support 64-bit DMA
3064	 * addressing for both data buffer and communication memory descriptors
3065	 * though S64A bit of CAP register declares the support.
3066	 */
3067	if (venid == 0x1002 && devid == 0x4380) {
3068		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3069		    "ATI SB600 cannot do 64-bit DMA for both data buffer "
3070		    "and communication memory descriptors though CAP indicates "
3071		    "support, so force it to use 32-bit DMA", NULL);
3072		ahci_ctlp->ahcictl_cap |= AHCI_CAP_BUF_32BIT_DMA;
3073		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
3074	}
3075
3076	/*
3077	 * AMD/ATI SB700/750 (1002,4391) AHCI chipset doesn't support 64-bit
3078	 * DMA addressing for communication memory descriptors though S64A bit
3079	 * of CAP register declares the support. However, it does support
3080	 * 64-bit DMA for data buffer.
3081	 */
3082	if (venid == 0x1002 && devid == 0x4391) {
3083		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3084		    "ATI SB700/750 cannot do 64-bit DMA for communication "
3085		    "memory descriptors though CAP indicates support, "
3086		    "so force it to use 32-bit DMA", NULL);
3087		ahci_ctlp->ahcictl_cap |= AHCI_CAP_COMMU_32BIT_DMA;
3088	}
3089
3090	/*
3091	 * Check if capabilities list is supported and if so,
3092	 * get initial capabilities pointer and clear bits 0,1.
3093	 */
3094	if (pci_config_get16(ahci_ctlp->ahcictl_pci_conf_handle,
3095	    PCI_CONF_STAT) & PCI_STAT_CAP) {
3096		caps_ptr = P2ALIGN(pci_config_get8(
3097		    ahci_ctlp->ahcictl_pci_conf_handle,
3098		    PCI_CONF_CAP_PTR), 4);
3099	} else {
3100		caps_ptr = PCI_CAP_NEXT_PTR_NULL;
3101	}
3102
3103	/*
3104	 * Walk capabilities if supported.
3105	 */
3106	for (cap_count = 0; caps_ptr != PCI_CAP_NEXT_PTR_NULL; ) {
3107
3108		/*
3109		 * Check that we haven't exceeded the maximum number of
3110		 * capabilities and that the pointer is in a valid range.
3111		 */
3112		if (++cap_count > PCI_CAP_MAX_PTR) {
3113			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3114			    "too many device capabilities", NULL);
3115			return (AHCI_FAILURE);
3116		}
3117		if (caps_ptr < PCI_CAP_PTR_OFF) {
3118			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3119			    "capabilities pointer 0x%x out of range",
3120			    caps_ptr);
3121			return (AHCI_FAILURE);
3122		}
3123
3124		/*
3125		 * Get next capability and check that it is valid.
3126		 * For now, we only support power management.
3127		 */
3128		cap = pci_config_get8(ahci_ctlp->ahcictl_pci_conf_handle,
3129		    caps_ptr);
3130		switch (cap) {
3131		case PCI_CAP_ID_PM:
3132
3133			/* power management supported */
3134			ahci_ctlp->ahcictl_cap |= AHCI_CAP_PM;
3135
3136			/* Save PMCSR offset */
3137			ahci_ctlp->ahcictl_pmcsr_offset = caps_ptr + PCI_PMCSR;
3138
3139#if AHCI_DEBUG
3140			pmcap = pci_config_get16(
3141			    ahci_ctlp->ahcictl_pci_conf_handle,
3142			    caps_ptr + PCI_PMCAP);
3143			pmcsr = pci_config_get16(
3144			    ahci_ctlp->ahcictl_pci_conf_handle,
3145			    ahci_ctlp->ahcictl_pmcsr_offset);
3146			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3147			    "Power Management capability found PCI_PMCAP "
3148			    "= 0x%x PCI_PMCSR = 0x%x", pmcap, pmcsr);
3149			if ((pmcap & 0x3) == 0x3)
3150				AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3151				    "PCI Power Management Interface "
3152				    "spec 1.2 compliant", NULL);
3153#endif
3154			break;
3155
3156		case PCI_CAP_ID_MSI:
3157#if AHCI_DEBUG
3158			msimc = pci_config_get16(
3159			    ahci_ctlp->ahcictl_pci_conf_handle,
3160			    caps_ptr + PCI_MSI_CTRL);
3161			AHCIDBG(AHCIDBG_MSI, ahci_ctlp,
3162			    "Message Signaled Interrupt capability found "
3163			    "MSICAP_MC.MMC = 0x%x", (msimc & 0xe) >> 1);
3164#endif
3165			AHCIDBG(AHCIDBG_MSI, ahci_ctlp,
3166			    "MSI capability found", NULL);
3167			break;
3168
3169		case PCI_CAP_ID_PCIX:
3170			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3171			    "PCI-X capability found", NULL);
3172			break;
3173
3174		case PCI_CAP_ID_PCI_E:
3175			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3176			    "PCI Express capability found", NULL);
3177			break;
3178
3179		case PCI_CAP_ID_MSI_X:
3180			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3181			    "MSI-X capability found", NULL);
3182			break;
3183
3184		case PCI_CAP_ID_SATA:
3185			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3186			    "SATA capability found", NULL);
3187			break;
3188
3189		case PCI_CAP_ID_VS:
3190			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3191			    "Vendor Specific capability found", NULL);
3192			break;
3193
3194		default:
3195			AHCIDBG(AHCIDBG_PM, ahci_ctlp,
3196			    "unrecognized capability 0x%x", cap);
3197			break;
3198		}
3199
3200		/*
3201		 * Get next capabilities pointer and clear bits 0,1.
3202		 */
3203		caps_ptr = P2ALIGN(pci_config_get8(
3204		    ahci_ctlp->ahcictl_pci_conf_handle,
3205		    (caps_ptr + PCI_CAP_NEXT_PTR)), 4);
3206	}
3207
3208	return (AHCI_SUCCESS);
3209}
3210
3211/*
3212 * AHCI device reset ...; a single device on one of the ports is reset,
3213 * but the HBA and physical communication remain intact. This is the
3214 * least intrusive.
3215 *
3216 * When issuing a software reset sequence, there should not be other
3217 * commands in the command list, so we will first clear and then re-set
3218 * PxCMD.ST to clear PxCI. And before issuing the software reset,
3219 * the port must be idle and PxTFD.STS.BSY and PxTFD.STS.DRQ must be
3220 * cleared unless command list override (PxCMD.CLO) is supported.
3221 *
3222 * WARNING!!! ahciport_mutex should be acquired and PxCMD.FRE should be
3223 * set before the function is called.
3224 */
3225static int
3226ahci_software_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
3227    uint8_t port)
3228{
3229	ahci_fis_h2d_register_t *h2d_register_fisp;
3230	ahci_cmd_table_t *cmd_table;
3231	ahci_cmd_header_t *cmd_header;
3232	uint32_t port_cmd_status, port_cmd_issue, port_task_file;
3233	int slot, loop_count;
3234	int rval = AHCI_FAILURE;
3235
3236	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
3237	    "Port %d device resetting", port);
3238
3239	/* First clear PxCMD.ST (AHCI v1.2 10.4.1) */
3240	if (ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp,
3241	    port) != AHCI_SUCCESS) {
3242		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3243		    "ahci_software_reset: cannot stop HBA port %d.", port);
3244		goto out;
3245	}
3246
3247	/* Check PxTFD.STS.BSY and PxTFD.STS.DRQ */
3248	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3249	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3250
3251	if (port_task_file & AHCI_TFD_STS_BSY ||
3252	    port_task_file & AHCI_TFD_STS_DRQ) {
3253		if (!(ahci_ctlp->ahcictl_cap & AHCI_CAP_SCLO)) {
3254			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3255			    "PxTFD.STS.BSY/DRQ is set (PxTFD=0x%x), "
3256			    "cannot issue a software reset.", port_task_file);
3257			goto out;
3258		}
3259
3260		/*
3261		 * If HBA Support CLO, as Command List Override (CAP.SCLO is
3262		 * set), PxCMD.CLO bit should be set before set PxCMD.ST, in
3263		 * order to clear PxTFD.STS.BSY and PxTFD.STS.DRQ.
3264		 */
3265		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3266		    "PxTFD.STS.BSY/DRQ is set, try SCLO.", NULL)
3267
3268		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3269		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3270		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3271		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3272		    port_cmd_status|AHCI_CMD_STATUS_CLO);
3273
3274		/* Waiting till PxCMD.SCLO bit is cleared */
3275		loop_count = 0;
3276		do {
3277			/* Wait for 10 millisec */
3278			drv_usecwait(AHCI_10MS_USECS);
3279
3280			/* We are effectively timing out after 1 sec. */
3281			if (loop_count++ > 100) {
3282				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3283				    "SCLO time out. port %d is busy.", port);
3284				goto out;
3285			}
3286
3287			port_cmd_status =
3288			    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3289			    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3290		} while (port_cmd_status & AHCI_CMD_STATUS_CLO);
3291
3292		/* Re-check */
3293		port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3294		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3295		if (port_task_file & AHCI_TFD_STS_BSY ||
3296		    port_task_file & AHCI_TFD_STS_DRQ) {
3297			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3298			    "SCLO cannot clear PxTFD.STS.BSY/DRQ (PxTFD=0x%x)",
3299			    port_task_file);
3300			goto out;
3301		}
3302	}
3303
3304	/* Then start port */
3305	if (ahci_start_port(ahci_ctlp, ahci_portp, port)
3306	    != AHCI_SUCCESS) {
3307		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3308		    "ahci_software_reset: cannot start AHCI port %d.", port);
3309		goto out;
3310	}
3311
3312	/*
3313	 * When ahci_port.ahciport_mop_in_progress is set, A non-zero
3314	 * ahci_port.ahciport_pending_ncq_tags may fail
3315	 * ahci_claim_free_slot(). Actually according to spec, by clearing
3316	 * PxCMD.ST there is no command outstanding while executing software
3317	 * reseting. Hence we directly use slot 0 instead of
3318	 * ahci_claim_free_slot().
3319	 */
3320	slot = 0;
3321
3322	/* Now send the first H2D Register FIS with SRST set to 1 */
3323	cmd_table = ahci_portp->ahciport_cmd_tables[slot];
3324	bzero((void *)cmd_table, ahci_cmd_table_size);
3325
3326	h2d_register_fisp =
3327	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
3328
3329	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
3330	SET_FIS_DEVCTL(h2d_register_fisp, SATA_DEVCTL_SRST);
3331
3332	/* Set Command Header in Command List */
3333	cmd_header = &ahci_portp->ahciport_cmd_list[slot];
3334	BZERO_DESCR_INFO(cmd_header);
3335	BZERO_PRD_BYTE_COUNT(cmd_header);
3336	SET_COMMAND_FIS_LENGTH(cmd_header, 5);
3337
3338	SET_CLEAR_BUSY_UPON_R_OK(cmd_header, 1);
3339	SET_RESET(cmd_header, 1);
3340	SET_WRITE(cmd_header, 1);
3341
3342	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_tables_dma_handle[slot],
3343	    0,
3344	    ahci_cmd_table_size,
3345	    DDI_DMA_SYNC_FORDEV);
3346
3347	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
3348	    slot * sizeof (ahci_cmd_header_t),
3349	    sizeof (ahci_cmd_header_t),
3350	    DDI_DMA_SYNC_FORDEV);
3351
3352	/* Indicate to the HBA that a command is active. */
3353	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3354	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
3355	    (0x1 << slot));
3356
3357	loop_count = 0;
3358
3359	/* Loop till the first command is finished */
3360	do {
3361		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3362		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
3363
3364		/* We are effectively timing out after 1 sec. */
3365		if (loop_count++ > AHCI_POLLRATE_PORT_SOFTRESET) {
3366			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3367			    "the first SRST FIS is timed out, "
3368			    "loop_count = %d", loop_count);
3369			goto out;
3370		}
3371
3372		/* Wait for 10 millisec */
3373		delay(AHCI_10MS_TICKS);
3374	} while (port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp) & (0x1 << slot));
3375
3376	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
3377	    "ahci_software_reset: 1st loop count: %d, "
3378	    "port_cmd_issue = 0x%x, slot = 0x%x",
3379	    loop_count, port_cmd_issue, slot);
3380
3381	/* According to ATA spec, we need wait at least 5 microsecs here. */
3382	drv_usecwait(AHCI_1MS_USECS);
3383
3384	/* Now send the second H2D Register FIS with SRST cleard to zero */
3385	cmd_table = ahci_portp->ahciport_cmd_tables[slot];
3386	bzero((void *)cmd_table, ahci_cmd_table_size);
3387
3388	h2d_register_fisp =
3389	    &(cmd_table->ahcict_command_fis.ahcifc_fis.ahcifc_h2d_register);
3390
3391	SET_FIS_TYPE(h2d_register_fisp, AHCI_H2D_REGISTER_FIS_TYPE);
3392
3393	/* Set Command Header in Command List */
3394	cmd_header = &ahci_portp->ahciport_cmd_list[slot];
3395	BZERO_DESCR_INFO(cmd_header);
3396	BZERO_PRD_BYTE_COUNT(cmd_header);
3397	SET_COMMAND_FIS_LENGTH(cmd_header, 5);
3398
3399	SET_WRITE(cmd_header, 1);
3400
3401	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_tables_dma_handle[slot],
3402	    0,
3403	    ahci_cmd_table_size,
3404	    DDI_DMA_SYNC_FORDEV);
3405
3406	(void) ddi_dma_sync(ahci_portp->ahciport_cmd_list_dma_handle,
3407	    slot * sizeof (ahci_cmd_header_t),
3408	    sizeof (ahci_cmd_header_t),
3409	    DDI_DMA_SYNC_FORDEV);
3410
3411	/* Indicate to the HBA that a command is active. */
3412	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3413	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port),
3414	    (0x1 << slot));
3415
3416	loop_count = 0;
3417
3418	/* Loop till the second command is finished */
3419	do {
3420		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3421		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
3422
3423		/* We are effectively timing out after 1 sec. */
3424		if (loop_count++ > AHCI_POLLRATE_PORT_SOFTRESET) {
3425			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3426			    "the second SRST FIS is timed out, "
3427			    "loop_count = %d", loop_count);
3428			goto out;
3429		}
3430
3431		/* Wait for 10 millisec */
3432		delay(AHCI_10MS_TICKS);
3433	} while (port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp) & (0x1 << slot));
3434
3435	AHCIDBG(AHCIDBG_POLL_LOOP, ahci_ctlp,
3436	    "ahci_software_reset: 2nd loop count: %d, "
3437	    "port_cmd_issue = 0x%x, slot = 0x%x",
3438	    loop_count, port_cmd_issue, slot);
3439
3440	CLEAR_BIT(ahci_portp->ahciport_pending_tags, slot);
3441
3442	rval = AHCI_SUCCESS;
3443out:
3444	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3445	    "ahci_software_reset: %s at port %d",
3446	    rval == AHCI_SUCCESS ? "succeed" : "failed",
3447	    port);
3448
3449	return (rval);
3450}
3451
3452/*
3453 * AHCI port reset ...; the physical communication between the HBA and device
3454 * on a port are disabled. This is more intrusive.
3455 *
3456 * When an HBA or port reset occurs, Phy communication is going to
3457 * be re-established with the device through a COMRESET followed by the
3458 * normal out-of-band communication sequence defined in Serial ATA. AT
3459 * the end of reset, the device, if working properly, will send a D2H
3460 * Register FIS, which contains the device signature. When the HBA receives
3461 * this FIS, it updates PxTFD.STS and PxTFD.ERR register fields, and updates
3462 * the PxSIG register with the signature.
3463 *
3464 * Staggered spin-up is an optional feature in SATA II, and it enables an HBA
3465 * to individually spin-up attached devices. Please refer to chapter 10.9 of
3466 * AHCI 1.0 spec.
3467 */
3468/*
3469 * WARNING!!! ahciport_mutex should be acquired, and PxCMD.ST should be also
3470 * cleared before the function is called.
3471 */
3472static int
3473ahci_port_reset(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
3474{
3475	uint32_t cap_status, port_cmd_status;
3476	uint32_t port_scontrol, port_sstatus, port_serror;
3477	uint32_t port_intr_status, port_task_file;
3478
3479	int loop_count;
3480	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
3481
3482	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3483	    "Port %d port resetting...", port);
3484	ahci_portp->ahciport_port_state = 0;
3485
3486	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3487	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
3488
3489	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3490	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3491
3492	if (cap_status & AHCI_HBA_CAP_SSS) {
3493		/*
3494		 * HBA support staggered spin-up, if the port has
3495		 * not spin up yet, then force it to do spin-up
3496		 */
3497		if (!(port_cmd_status & AHCI_CMD_STATUS_SUD)) {
3498			if (!(ahci_portp->ahciport_flags
3499			    & AHCI_PORT_FLAG_SPINUP)) {
3500				AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3501				    "Port %d PxCMD.SUD is zero, force "
3502				    "it to do spin-up", port);
3503				ahci_portp->ahciport_flags |=
3504				    AHCI_PORT_FLAG_SPINUP;
3505			}
3506		}
3507	} else {
3508		/*
3509		 * HBA doesn't support stagger spin-up, force it
3510		 * to do normal COMRESET
3511		 */
3512		if (ahci_portp->ahciport_flags &
3513		    AHCI_PORT_FLAG_SPINUP) {
3514			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3515			    "HBA does not support staggered spin-up "
3516			    "force it to do normal COMRESET", NULL);
3517			ahci_portp->ahciport_flags &=
3518			    ~AHCI_PORT_FLAG_SPINUP;
3519		}
3520	}
3521
3522	if (!(ahci_portp->ahciport_flags & AHCI_PORT_FLAG_SPINUP)) {
3523		/* Do normal COMRESET */
3524		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3525		    "ahci_port_reset: do normal COMRESET", port);
3526
3527		/*
3528		 * According to the spec, SUD bit should be set here,
3529		 * but JMicron JMB363 doesn't follow it, so remove
3530		 * the assertion, and just print a debug message.
3531		 */
3532#if AHCI_DEBUG
3533		if (!(port_cmd_status & AHCI_CMD_STATUS_SUD))
3534			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3535			    "port %d SUD bit not set", port)
3536#endif
3537
3538		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3539		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3540		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_COMRESET);
3541
3542		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3543		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
3544		    port_scontrol);
3545
3546		/* Enable PxCMD.FRE to read device */
3547		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3548		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3549		    port_cmd_status|AHCI_CMD_STATUS_FRE);
3550
3551		/*
3552		 * Give time for COMRESET to percolate, according to the AHCI
3553		 * spec, software shall wait at least 1 millisecond before
3554		 * clearing PxSCTL.DET
3555		 */
3556		delay(AHCI_1MS_TICKS*2);
3557
3558		/* Fetch the SCONTROL again and rewrite the DET part with 0 */
3559		port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3560		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3561		SCONTROL_SET_DET(port_scontrol, SCONTROL_DET_NOACTION);
3562		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3563		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
3564		    port_scontrol);
3565	} else {
3566		/* Do staggered spin-up */
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
3571		/* PxSCTL.DET must be 0 */
3572		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3573		    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port),
3574		    port_scontrol);
3575
3576		port_cmd_status &= ~AHCI_CMD_STATUS_SUD;
3577		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3578		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3579		    port_cmd_status);
3580
3581		/* 0 -> 1 edge */
3582		delay(AHCI_1MS_TICKS*2);
3583
3584		/* Set PxCMD.SUD to 1 */
3585		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3586		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3587		port_cmd_status |= AHCI_CMD_STATUS_SUD;
3588		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3589		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3590		    port_cmd_status);
3591
3592		/* Enable PxCMD.FRE to read device */
3593		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3594		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
3595		    port_cmd_status|AHCI_CMD_STATUS_FRE);
3596	}
3597
3598	/*
3599	 * The port enters P:StartComm state, and HBA tells link layer to
3600	 * start communication, which involves sending COMRESET to device.
3601	 * And the HBA resets PxTFD.STS to 7Fh.
3602	 *
3603	 * When a COMINIT is received from the device, then the port enters
3604	 * P:ComInit state. And HBA sets PxTFD.STS to FFh or 80h. HBA sets
3605	 * PxSSTS.DET to 1h to indicate a device is detected but communication
3606	 * is not yet established. HBA sets PxSERR.DIAG.X to '1' to indicate
3607	 * a COMINIT has been received.
3608	 */
3609	/*
3610	 * The DET field is valid only if IPM field indicates
3611	 * that the interface is in active state.
3612	 */
3613	loop_count = 0;
3614	do {
3615		port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3616		    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
3617
3618		if (SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) {
3619			/*
3620			 * If the interface is not active, the DET field
3621			 * is considered not accurate. So we want to
3622			 * continue looping.
3623			 */
3624			SSTATUS_SET_DET(port_sstatus, SSTATUS_DET_NODEV);
3625		}
3626
3627		if (loop_count++ > AHCI_POLLRATE_PORT_SSTATUS) {
3628			/*
3629			 * We are effectively timing out after 0.1 sec.
3630			 */
3631			break;
3632		}
3633
3634		/* Wait for 10 millisec */
3635		delay(AHCI_10MS_TICKS);
3636	} while (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM);
3637
3638	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
3639	    "ahci_port_reset: 1st loop count: %d, "
3640	    "port_sstatus = 0x%x port %d",
3641	    loop_count, port_sstatus, port);
3642
3643	if ((SSTATUS_GET_IPM(port_sstatus) != SSTATUS_IPM_ACTIVE) ||
3644	    (SSTATUS_GET_DET(port_sstatus) != SSTATUS_DET_DEVPRE_PHYCOM)) {
3645		/*
3646		 * Either the port is not active or there
3647		 * is no device present.
3648		 */
3649		ahci_portp->ahciport_device_type = SATA_DTYPE_NONE;
3650		return (AHCI_SUCCESS);
3651	}
3652
3653	/* Now we can make sure there is a device connected to the port */
3654	port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3655	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
3656	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3657	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
3658
3659	/*
3660	 * A COMINIT signal is supposed to be received
3661	 * PxSERR.DIAG.X or PxIS.PCS should be set
3662	 */
3663	if (!(port_intr_status & AHCI_INTR_STATUS_PCS) &&
3664	    !(port_serror & SERROR_EXCHANGED_ERR)) {
3665		cmn_err(CE_WARN, "!ahci%d: ahci_port_reset port %d "
3666		    "COMINIT signal from the device not received",
3667		    instance, port);
3668		ahci_portp->ahciport_port_state |= SATA_PSTATE_FAILED;
3669		return (AHCI_FAILURE);
3670	}
3671
3672	/*
3673	 * According to the spec, when PxSCTL.DET is set to 0h, upon
3674	 * receiving a COMINIT from the attached device, PxTFD.STS.BSY
3675	 * shall be set to '1' by the HBA.
3676	 *
3677	 * However, we found JMicron JMB363 doesn't follow this, so
3678	 * remove this check, and just print a debug message.
3679	 */
3680#if AHCI_DEBUG
3681	port_task_file = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3682	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3683	if (!(port_task_file & AHCI_TFD_STS_BSY)) {
3684		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_port_reset: "
3685		    "port %d BSY bit is not set after COMINIT signal "
3686		    "is received", port);
3687	}
3688#endif
3689
3690	/*
3691	 * PxSERR.DIAG.X has to be cleared in order to update PxTFD with
3692	 * the D2H FIS received by HBA.
3693	 */
3694	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3695	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
3696	    SERROR_EXCHANGED_ERR);
3697
3698	/*
3699	 * Devices should return a FIS contains its signature to HBA after
3700	 * COMINIT signal. Check whether a D2H FIS is received by polling
3701	 * PxTFD.STS.ERR bit.
3702	 */
3703	loop_count = 0;
3704	do {
3705		/* Wait for 10 millisec */
3706		delay(AHCI_10MS_TICKS);
3707
3708		if (loop_count++ > AHCI_POLLRATE_PORT_TFD_ERROR) {
3709			/*
3710			 * We are effectively timing out after 11 sec.
3711			 */
3712			cmn_err(CE_WARN, "!ahci%d: ahci_port_reset port %d "
3713			    "the device hardware has been initialized and "
3714			    "the power-up diagnostics failed",
3715			    instance, port);
3716
3717			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_port_reset: "
3718			    "port %d PxTFD.STS.ERR is not set, we need another "
3719			    "software reset.", port);
3720
3721			/* Clear port serror register for the port */
3722			ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3723			    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
3724			    AHCI_SERROR_CLEAR_ALL);
3725
3726			/* Try another software reset. */
3727			if (ahci_software_reset(ahci_ctlp, ahci_portp,
3728			    port) != AHCI_SUCCESS) {
3729				ahci_portp->ahciport_port_state |=
3730				    SATA_PSTATE_FAILED;
3731				return (AHCI_FAILURE);
3732			}
3733			break;
3734		}
3735
3736		/*
3737		 * The Error bit '1' means COMRESET is finished successfully
3738		 * The device hardware has been initialized and the power-up
3739		 * diagnostics successfully completed. The device requests
3740		 * that the Transport layer transmit a Register - D2H FIS to
3741		 * the host. (SATA spec 11.5, v2.6)
3742		 */
3743		port_task_file =
3744		    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3745		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
3746	} while (((port_task_file & AHCI_TFD_ERR_MASK)
3747	    >> AHCI_TFD_ERR_SHIFT) != AHCI_TFD_ERR_SGS);
3748
3749	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
3750	    "ahci_port_reset: 2nd loop count: %d, "
3751	    "port_task_file = 0x%x port %d",
3752	    loop_count, port_task_file, port);
3753
3754	/* Clear port serror register for the port */
3755	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3756	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
3757	    AHCI_SERROR_CLEAR_ALL);
3758
3759	/* Set port as ready */
3760	ahci_portp->ahciport_port_state |= SATA_STATE_READY;
3761
3762	AHCIDBG(AHCIDBG_INFO|AHCIDBG_ERRS, ahci_ctlp,
3763	    "ahci_port_reset: succeed at port %d.", port);
3764	return (AHCI_SUCCESS);
3765}
3766
3767/*
3768 * AHCI HBA reset ...; the entire HBA is reset, and all ports are disabled.
3769 * This is the most intrusive.
3770 *
3771 * When an HBA reset occurs, Phy communication will be re-established with
3772 * the device through a COMRESET followed by the normal out-of-band
3773 * communication sequence defined in Serial ATA. AT the end of reset, the
3774 * device, if working properly, will send a D2H Register FIS, which contains
3775 * the device signature. When the HBA receives this FIS, it updates PxTFD.STS
3776 * and PxTFD.ERR register fields, and updates the PxSIG register with the
3777 * signature.
3778 *
3779 * Remember to set GHC.AE to 1 before calling ahci_hba_reset.
3780 */
3781static int
3782ahci_hba_reset(ahci_ctl_t *ahci_ctlp)
3783{
3784	ahci_port_t *ahci_portp;
3785	uint32_t ghc_control;
3786	uint8_t port;
3787	int loop_count;
3788	int rval = AHCI_SUCCESS;
3789
3790	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp, "HBA resetting",
3791	    NULL);
3792
3793	mutex_enter(&ahci_ctlp->ahcictl_mutex);
3794
3795	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3796	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3797
3798	/* Setting GHC.HR to 1, remember GHC.AE is already set to 1 before */
3799	ghc_control |= AHCI_HBA_GHC_HR;
3800	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3801	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
3802
3803	/*
3804	 * Wait until HBA Reset complete or timeout
3805	 */
3806	loop_count = 0;
3807	do {
3808		ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3809		    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3810
3811		if (loop_count++ > AHCI_POLLRATE_HBA_RESET) {
3812			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3813			    "ahci hba reset is timing out, "
3814			    "ghc_control = 0x%x", ghc_control);
3815			/* We are effectively timing out after 1 sec. */
3816			break;
3817		}
3818
3819		/* Wait for 10 millisec */
3820		delay(AHCI_10MS_TICKS);
3821	} while (ghc_control & AHCI_HBA_GHC_HR);
3822
3823	AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
3824	    "ahci_hba_reset: 1st loop count: %d, "
3825	    "ghc_control = 0x%x", loop_count, ghc_control);
3826
3827	if (ghc_control & AHCI_HBA_GHC_HR) {
3828		/* The hba is not reset for some reasons */
3829		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
3830		    "hba reset failed: HBA in a hung or locked state", NULL);
3831		mutex_exit(&ahci_ctlp->ahcictl_mutex);
3832		return (AHCI_FAILURE);
3833	}
3834
3835	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
3836		/* Only check implemented ports */
3837		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
3838			continue;
3839		}
3840
3841		ahci_portp = ahci_ctlp->ahcictl_ports[port];
3842		mutex_enter(&ahci_portp->ahciport_mutex);
3843
3844		if (ahci_port_reset(ahci_ctlp, ahci_portp, port)
3845		    != AHCI_SUCCESS) {
3846			rval = AHCI_FAILURE;
3847			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3848			    "ahci_hba_reset: port %d failed", port);
3849		}
3850
3851		mutex_exit(&ahci_portp->ahciport_mutex);
3852	}
3853
3854	/*
3855	 * Indicate that system software is AHCI aware by setting
3856	 * GHC.AE to 1
3857	 */
3858	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3859	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
3860
3861	ghc_control |= AHCI_HBA_GHC_AE;
3862	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3863	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
3864
3865	mutex_exit(&ahci_ctlp->ahcictl_mutex);
3866
3867	return (rval);
3868}
3869
3870/*
3871 * This routine is only called from AHCI_ATTACH or phyrdy change
3872 * case. It first calls software reset, then stop the port and try to
3873 * read PxSIG register to find the type of device attached to the port.
3874 *
3875 * The caller should make sure a valid device exists on specified port and
3876 * physical communication has been established so that the signature could
3877 * be retrieved by software reset.
3878 *
3879 * WARNING!!! ahciport_mutex should be acquired before the function
3880 * is called. And the port interrupt is disabled.
3881 */
3882static void
3883ahci_find_dev_signature(ahci_ctl_t *ahci_ctlp,
3884    ahci_port_t *ahci_portp, uint8_t port)
3885{
3886	uint32_t signature;
3887
3888	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
3889	    "ahci_find_dev_signature enter: port %d", port);
3890
3891	ahci_portp->ahciport_device_type = SATA_DTYPE_UNKNOWN;
3892
3893	/* Issue a software reset to get the signature */
3894	if (ahci_software_reset(ahci_ctlp, ahci_portp, port)
3895	    != AHCI_SUCCESS) {
3896		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
3897		    "ahci_find_dev_signature: software reset failed "
3898		    "at port %d, cannot get signature.", port);
3899		ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
3900		return;
3901	}
3902
3903	/*
3904	 * ahci_software_reset has started the port, so we need manually stop
3905	 * the port again.
3906	 */
3907	if (ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp, port)
3908	    != AHCI_SUCCESS) {
3909		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3910		    "ahci_find_dev_signature: cannot stop port %d.", port);
3911		ahci_portp->ahciport_port_state = SATA_PSTATE_FAILED;
3912		return;
3913	}
3914
3915	/* Now we can make sure that a valid signature is received. */
3916	signature = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3917	    (uint32_t *)AHCI_PORT_PxSIG(ahci_ctlp, port));
3918
3919	AHCIDBG(AHCIDBG_INIT|AHCIDBG_INFO, ahci_ctlp,
3920	    "ahci_find_dev_signature: port %d signature = 0x%x",
3921	    port, signature);
3922
3923	switch (signature) {
3924
3925	case AHCI_SIGNATURE_DISK:
3926		ahci_portp->ahciport_device_type = SATA_DTYPE_ATADISK;
3927		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3928		    "Disk is found at port: %d", port);
3929		break;
3930
3931	case AHCI_SIGNATURE_ATAPI:
3932		ahci_portp->ahciport_device_type = SATA_DTYPE_ATAPI;
3933		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3934		    "ATAPI device is found at port: %d", port);
3935		break;
3936
3937	case AHCI_SIGNATURE_PORT_MULTIPLIER:
3938		ahci_portp->ahciport_device_type = SATA_DTYPE_PMULT;
3939		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3940		    "Port Multiplier is found at port: %d", port);
3941		break;
3942
3943	default:
3944		ahci_portp->ahciport_device_type = SATA_DTYPE_UNKNOWN;
3945		AHCIDBG(AHCIDBG_INFO, ahci_ctlp,
3946		    "Unknown device is found at port: %d", port);
3947	}
3948}
3949
3950/*
3951 * According to the spec, to reliably detect hot plug removals, software
3952 * must disable interface power management. Software should perform the
3953 * following initialization on a port after a device is attached:
3954 *   Set PxSCTL.IPM to 3h to disable interface state transitions
3955 *   Set PxCMD.ALPE to '0' to disable aggressive power management
3956 *   Disable device initiated interface power management by SET FEATURE
3957 *
3958 * We can ignore the last item because by default the feature is disabled
3959 */
3960static void
3961ahci_disable_interface_pm(ahci_ctl_t *ahci_ctlp, uint8_t port)
3962{
3963	uint32_t port_scontrol, port_cmd_status;
3964
3965	port_scontrol = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3966	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port));
3967	SCONTROL_SET_IPM(port_scontrol, SCONTROL_IPM_DISABLE_BOTH);
3968	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3969	    (uint32_t *)AHCI_PORT_PxSCTL(ahci_ctlp, port), port_scontrol);
3970
3971	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
3972	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
3973	port_cmd_status &= ~AHCI_CMD_STATUS_ALPE;
3974	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
3975	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port), port_cmd_status);
3976}
3977
3978/*
3979 * Start the port - set PxCMD.ST to 1, if PxCMD.FRE is not set
3980 * to 1, then set it firstly.
3981 *
3982 * Each port contains two major DMA engines. One DMA engine walks through
3983 * the command list, and is controlled by PxCMD.ST. The second DMA engine
3984 * copies received FISes into system memory, and is controlled by PxCMD.FRE.
3985 *
3986 * Software shall not set PxCMD.ST to '1' until it verifies that PxCMD.CR
3987 * is '0' and has set PxCMD.FRE is '1'. And software shall not clear
3988 * PxCMD.FRE while PxCMD.ST or PxCMD.CR is set '1'.
3989 *
3990 * Software shall not set PxCMD.ST to '1' unless a functional device is
3991 * present on the port(as determined by PxTFD.STS.BSY = '0',
3992 * PxTFD.STS.DRQ = '0', and PxSSTS.DET = 3h).
3993 *
3994 * WARNING!!! ahciport_mutex should be acquired before the function
3995 * is called.
3996 */
3997static int
3998ahci_start_port(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
3999{
4000	uint32_t port_cmd_status;
4001
4002	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_start_port: %d enter", port);
4003
4004	if (ahci_portp->ahciport_port_state & SATA_PSTATE_FAILED) {
4005		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port failed "
4006		    "the state for port %d is 0x%x",
4007		    port, ahci_portp->ahciport_port_state);
4008		return (AHCI_FAILURE);
4009	}
4010
4011	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
4012		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port failed "
4013		    "no device is attached at port %d", port);
4014		return (AHCI_FAILURE);
4015	}
4016
4017	/* First to set PxCMD.FRE before setting PxCMD.ST. */
4018	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4019	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4020
4021	if (!(port_cmd_status & AHCI_CMD_STATUS_FRE)) {
4022		port_cmd_status |= AHCI_CMD_STATUS_FRE;
4023		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4024		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4025		    port_cmd_status);
4026	}
4027
4028	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4029	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
4030
4031	port_cmd_status |= AHCI_CMD_STATUS_ST;
4032
4033	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4034	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port),
4035	    port_cmd_status);
4036
4037	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_STARTED;
4038
4039	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_start_port: "
4040	    "PxCMD.ST set to '1' at port %d", port);
4041
4042	return (AHCI_SUCCESS);
4043}
4044
4045/*
4046 * Allocate the ahci_port_t including Received FIS and Command List.
4047 * The argument - port is the physical port number, and not logical
4048 * port number seen by the SATA framework.
4049 *
4050 * WARNING!!! ahcictl_mutex should be acquired before the function
4051 * is called.
4052 */
4053static int
4054ahci_alloc_port_state(ahci_ctl_t *ahci_ctlp, uint8_t port)
4055{
4056	dev_info_t *dip = ahci_ctlp->ahcictl_dip;
4057	ahci_port_t *ahci_portp;
4058	char taskq_name[64] = "event_handle_taskq";
4059
4060	ahci_portp =
4061	    (ahci_port_t *)kmem_zalloc(sizeof (ahci_port_t), KM_SLEEP);
4062
4063	ahci_ctlp->ahcictl_ports[port] = ahci_portp;
4064	ahci_portp->ahciport_port_num = port;
4065
4066	/* Intialize the port condition variable */
4067	cv_init(&ahci_portp->ahciport_cv, NULL, CV_DRIVER, NULL);
4068
4069	/* Initialize the port mutex */
4070	mutex_init(&ahci_portp->ahciport_mutex, NULL, MUTEX_DRIVER,
4071	    (void *)(uintptr_t)ahci_ctlp->ahcictl_intr_pri);
4072
4073	mutex_enter(&ahci_portp->ahciport_mutex);
4074
4075	/*
4076	 * Allocate memory for received FIS structure and
4077	 * command list for this port
4078	 */
4079	if (ahci_alloc_rcvd_fis(ahci_ctlp, ahci_portp, port) != AHCI_SUCCESS) {
4080		goto err_case1;
4081	}
4082
4083	if (ahci_alloc_cmd_list(ahci_ctlp, ahci_portp, port) != AHCI_SUCCESS) {
4084		goto err_case2;
4085	}
4086
4087	(void) snprintf(taskq_name + strlen(taskq_name),
4088	    sizeof (taskq_name) - strlen(taskq_name),
4089	    "_port%d", port);
4090
4091	/* Create the taskq for the port */
4092	if ((ahci_portp->ahciport_event_taskq = ddi_taskq_create(dip,
4093	    taskq_name, 2, TASKQ_DEFAULTPRI, 0)) == NULL) {
4094		cmn_err(CE_WARN, "!ahci%d: ddi_taskq_create failed for event "
4095		    "handle", ddi_get_instance(ahci_ctlp->ahcictl_dip));
4096		goto err_case3;
4097	}
4098
4099	/* Allocate the argument for the taskq */
4100	ahci_portp->ahciport_event_args =
4101	    kmem_zalloc(sizeof (ahci_event_arg_t), KM_SLEEP);
4102
4103	if (ahci_portp->ahciport_event_args == NULL)
4104		goto err_case4;
4105
4106	mutex_exit(&ahci_portp->ahciport_mutex);
4107
4108	return (AHCI_SUCCESS);
4109
4110err_case4:
4111	ddi_taskq_destroy(ahci_portp->ahciport_event_taskq);
4112
4113err_case3:
4114	ahci_dealloc_cmd_list(ahci_ctlp, ahci_portp);
4115
4116err_case2:
4117	ahci_dealloc_rcvd_fis(ahci_portp);
4118
4119err_case1:
4120	mutex_exit(&ahci_portp->ahciport_mutex);
4121	mutex_destroy(&ahci_portp->ahciport_mutex);
4122	cv_destroy(&ahci_portp->ahciport_cv);
4123
4124	kmem_free(ahci_portp, sizeof (ahci_port_t));
4125
4126	return (AHCI_FAILURE);
4127}
4128
4129/*
4130 * Reverse of ahci_dealloc_port_state().
4131 *
4132 * WARNING!!! ahcictl_mutex should be acquired before the function
4133 * is called.
4134 */
4135static void
4136ahci_dealloc_port_state(ahci_ctl_t *ahci_ctlp, uint8_t port)
4137{
4138	ahci_port_t *ahci_portp = ahci_ctlp->ahcictl_ports[port];
4139
4140	ASSERT(ahci_portp != NULL);
4141
4142	mutex_enter(&ahci_portp->ahciport_mutex);
4143	kmem_free(ahci_portp->ahciport_event_args, sizeof (ahci_event_arg_t));
4144	ahci_portp->ahciport_event_args = NULL;
4145	ddi_taskq_destroy(ahci_portp->ahciport_event_taskq);
4146	ahci_dealloc_cmd_list(ahci_ctlp, ahci_portp);
4147	ahci_dealloc_rcvd_fis(ahci_portp);
4148	mutex_exit(&ahci_portp->ahciport_mutex);
4149
4150	mutex_destroy(&ahci_portp->ahciport_mutex);
4151	cv_destroy(&ahci_portp->ahciport_cv);
4152
4153	kmem_free(ahci_portp, sizeof (ahci_port_t));
4154
4155	ahci_ctlp->ahcictl_ports[port] = NULL;
4156}
4157
4158/*
4159 * Allocates memory for the Received FIS Structure
4160 *
4161 * WARNING!!! ahciport_mutex should be acquired before the function
4162 * is called.
4163 */
4164static int
4165ahci_alloc_rcvd_fis(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4166    uint8_t port)
4167{
4168	size_t rcvd_fis_size;
4169	size_t ret_len;
4170	uint_t cookie_count;
4171
4172	rcvd_fis_size = sizeof (ahci_rcvd_fis_t);
4173
4174	/* allocate rcvd FIS dma handle. */
4175	if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
4176	    &ahci_ctlp->ahcictl_rcvd_fis_dma_attr,
4177	    DDI_DMA_SLEEP,
4178	    NULL,
4179	    &ahci_portp->ahciport_rcvd_fis_dma_handle) !=
4180	    DDI_SUCCESS) {
4181		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4182		    "rcvd FIS dma handle alloc failed", NULL);
4183
4184		return (AHCI_FAILURE);
4185	}
4186
4187	if (ddi_dma_mem_alloc(ahci_portp->ahciport_rcvd_fis_dma_handle,
4188	    rcvd_fis_size,
4189	    &accattr,
4190	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
4191	    DDI_DMA_SLEEP,
4192	    NULL,
4193	    (caddr_t *)&ahci_portp->ahciport_rcvd_fis,
4194	    &ret_len,
4195	    &ahci_portp->ahciport_rcvd_fis_acc_handle) != NULL) {
4196
4197		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4198		    "rcvd FIS dma mem alloc fail", NULL);
4199		/* error.. free the dma handle. */
4200		ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
4201		return (AHCI_FAILURE);
4202	}
4203
4204	if (ddi_dma_addr_bind_handle(ahci_portp->ahciport_rcvd_fis_dma_handle,
4205	    NULL,
4206	    (caddr_t)ahci_portp->ahciport_rcvd_fis,
4207	    rcvd_fis_size,
4208	    DDI_DMA_CONSISTENT,
4209	    DDI_DMA_SLEEP,
4210	    NULL,
4211	    &ahci_portp->ahciport_rcvd_fis_dma_cookie,
4212	    &cookie_count) !=  DDI_DMA_MAPPED) {
4213
4214		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4215		    "rcvd FIS dma handle bind fail", NULL);
4216		/*  error.. free the dma handle & free the memory. */
4217		ddi_dma_mem_free(&ahci_portp->ahciport_rcvd_fis_acc_handle);
4218		ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
4219		return (AHCI_FAILURE);
4220	}
4221
4222	bzero((void *)ahci_portp->ahciport_rcvd_fis, rcvd_fis_size);
4223
4224	/* Config Port Received FIS Base Address */
4225	ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
4226	    (uint64_t *)AHCI_PORT_PxFB(ahci_ctlp, port),
4227	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
4228
4229	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "64-bit, dma address: 0x%llx",
4230	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_laddress);
4231	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "32-bit, dma address: 0x%x",
4232	    ahci_portp->ahciport_rcvd_fis_dma_cookie.dmac_address);
4233
4234	return (AHCI_SUCCESS);
4235}
4236
4237/*
4238 * Deallocates the Received FIS Structure
4239 *
4240 * WARNING!!! ahciport_mutex should be acquired before the function
4241 * is called.
4242 */
4243static void
4244ahci_dealloc_rcvd_fis(ahci_port_t *ahci_portp)
4245{
4246	/* Unbind the cmd list dma handle first. */
4247	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_rcvd_fis_dma_handle);
4248
4249	/* Then free the underlying memory. */
4250	ddi_dma_mem_free(&ahci_portp->ahciport_rcvd_fis_acc_handle);
4251
4252	/* Now free the handle itself. */
4253	ddi_dma_free_handle(&ahci_portp->ahciport_rcvd_fis_dma_handle);
4254}
4255
4256/*
4257 * Allocates memory for the Command List, which contains up to 32 entries.
4258 * Each entry contains a command header, which is a 32-byte structure that
4259 * includes the pointer to the command table.
4260 *
4261 * WARNING!!! ahciport_mutex should be acquired before the function
4262 * is called.
4263 */
4264static int
4265ahci_alloc_cmd_list(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
4266    uint8_t port)
4267{
4268	size_t cmd_list_size;
4269	size_t ret_len;
4270	uint_t cookie_count;
4271
4272	cmd_list_size =
4273	    ahci_ctlp->ahcictl_num_cmd_slots * sizeof (ahci_cmd_header_t);
4274
4275	/* allocate cmd list dma handle. */
4276	if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
4277	    &ahci_ctlp->ahcictl_cmd_list_dma_attr,
4278	    DDI_DMA_SLEEP,
4279	    NULL,
4280	    &ahci_portp->ahciport_cmd_list_dma_handle) != DDI_SUCCESS) {
4281
4282		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4283		    "cmd list dma handle alloc failed", NULL);
4284		return (AHCI_FAILURE);
4285	}
4286
4287	if (ddi_dma_mem_alloc(ahci_portp->ahciport_cmd_list_dma_handle,
4288	    cmd_list_size,
4289	    &accattr,
4290	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
4291	    DDI_DMA_SLEEP,
4292	    NULL,
4293	    (caddr_t *)&ahci_portp->ahciport_cmd_list,
4294	    &ret_len,
4295	    &ahci_portp->ahciport_cmd_list_acc_handle) != NULL) {
4296
4297		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4298		    "cmd list dma mem alloc fail", NULL);
4299		/* error.. free the dma handle. */
4300		ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4301		return (AHCI_FAILURE);
4302	}
4303
4304	if (ddi_dma_addr_bind_handle(ahci_portp->ahciport_cmd_list_dma_handle,
4305	    NULL,
4306	    (caddr_t)ahci_portp->ahciport_cmd_list,
4307	    cmd_list_size,
4308	    DDI_DMA_CONSISTENT,
4309	    DDI_DMA_SLEEP,
4310	    NULL,
4311	    &ahci_portp->ahciport_cmd_list_dma_cookie,
4312	    &cookie_count) !=  DDI_DMA_MAPPED) {
4313
4314		AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4315		    "cmd list dma handle bind fail", NULL);
4316		/*  error.. free the dma handle & free the memory. */
4317		ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
4318		ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4319		return (AHCI_FAILURE);
4320	}
4321
4322	bzero((void *)ahci_portp->ahciport_cmd_list, cmd_list_size);
4323
4324	/* Config Port Command List Base Address */
4325	ddi_put64(ahci_ctlp->ahcictl_ahci_acc_handle,
4326	    (uint64_t *)AHCI_PORT_PxCLB(ahci_ctlp, port),
4327	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
4328
4329	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "64-bit, dma address: 0x%llx",
4330	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_laddress);
4331
4332	AHCIDBG(AHCIDBG_INIT, ahci_ctlp, "32-bit, dma address: 0x%x",
4333	    ahci_portp->ahciport_cmd_list_dma_cookie.dmac_address);
4334
4335	if (ahci_alloc_cmd_tables(ahci_ctlp, ahci_portp) != AHCI_SUCCESS) {
4336		goto err_out;
4337	}
4338
4339	return (AHCI_SUCCESS);
4340
4341err_out:
4342	/* Unbind the cmd list dma handle first. */
4343	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_cmd_list_dma_handle);
4344
4345	/* Then free the underlying memory. */
4346	ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
4347
4348	/* Now free the handle itself. */
4349	ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4350
4351	return (AHCI_FAILURE);
4352}
4353
4354/*
4355 * Deallocates the Command List
4356 *
4357 * WARNING!!! ahciport_mutex should be acquired before the function
4358 * is called.
4359 */
4360static void
4361ahci_dealloc_cmd_list(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
4362{
4363	/* First dealloc command table */
4364	ahci_dealloc_cmd_tables(ahci_ctlp, ahci_portp);
4365
4366	/* Unbind the cmd list dma handle first. */
4367	(void) ddi_dma_unbind_handle(ahci_portp->ahciport_cmd_list_dma_handle);
4368
4369	/* Then free the underlying memory. */
4370	ddi_dma_mem_free(&ahci_portp->ahciport_cmd_list_acc_handle);
4371
4372	/* Now free the handle itself. */
4373	ddi_dma_free_handle(&ahci_portp->ahciport_cmd_list_dma_handle);
4374}
4375
4376/*
4377 * Allocates memory for all Command Tables, which contains Command FIS,
4378 * ATAPI Command and Physical Region Descriptor Table.
4379 *
4380 * WARNING!!! ahciport_mutex should be acquired before the function
4381 * is called.
4382 */
4383static int
4384ahci_alloc_cmd_tables(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
4385{
4386	size_t ret_len;
4387	ddi_dma_cookie_t cmd_table_dma_cookie;
4388	uint_t cookie_count;
4389	int slot;
4390
4391	AHCIDBG(AHCIDBG_INIT|AHCIDBG_ENTRY, ahci_ctlp,
4392	    "ahci_alloc_cmd_tables: port %d enter",
4393	    ahci_portp->ahciport_port_num);
4394
4395	for (slot = 0; slot < ahci_ctlp->ahcictl_num_cmd_slots; slot++) {
4396		/* Allocate cmd table dma handle. */
4397		if (ddi_dma_alloc_handle(ahci_ctlp->ahcictl_dip,
4398		    &ahci_ctlp->ahcictl_cmd_table_dma_attr,
4399		    DDI_DMA_SLEEP,
4400		    NULL,
4401		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]) !=
4402		    DDI_SUCCESS) {
4403
4404			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4405			    "cmd table dma handle alloc failed", NULL);
4406
4407			goto err_out;
4408		}
4409
4410		if (ddi_dma_mem_alloc(
4411		    ahci_portp->ahciport_cmd_tables_dma_handle[slot],
4412		    ahci_cmd_table_size,
4413		    &accattr,
4414		    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
4415		    DDI_DMA_SLEEP,
4416		    NULL,
4417		    (caddr_t *)&ahci_portp->ahciport_cmd_tables[slot],
4418		    &ret_len,
4419		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]) !=
4420		    NULL) {
4421
4422			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4423			    "cmd table dma mem alloc fail", NULL);
4424
4425			/* error.. free the dma handle. */
4426			ddi_dma_free_handle(
4427			    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4428			goto err_out;
4429		}
4430
4431		if (ddi_dma_addr_bind_handle(
4432		    ahci_portp->ahciport_cmd_tables_dma_handle[slot],
4433		    NULL,
4434		    (caddr_t)ahci_portp->ahciport_cmd_tables[slot],
4435		    ahci_cmd_table_size,
4436		    DDI_DMA_CONSISTENT,
4437		    DDI_DMA_SLEEP,
4438		    NULL,
4439		    &cmd_table_dma_cookie,
4440		    &cookie_count) !=  DDI_DMA_MAPPED) {
4441
4442			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
4443			    "cmd table dma handle bind fail", NULL);
4444			/*  error.. free the dma handle & free the memory. */
4445			ddi_dma_mem_free(
4446			    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
4447			ddi_dma_free_handle(
4448			    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4449			goto err_out;
4450		}
4451
4452		bzero((void *)ahci_portp->ahciport_cmd_tables[slot],
4453		    ahci_cmd_table_size);
4454
4455		/* Config Port Command Table Base Address */
4456		SET_COMMAND_TABLE_BASE_ADDR(
4457		    (&ahci_portp->ahciport_cmd_list[slot]),
4458		    cmd_table_dma_cookie.dmac_laddress & 0xffffffffull);
4459
4460#ifndef __lock_lint
4461		SET_COMMAND_TABLE_BASE_ADDR_UPPER(
4462		    (&ahci_portp->ahciport_cmd_list[slot]),
4463		    cmd_table_dma_cookie.dmac_laddress >> 32);
4464#endif
4465	}
4466
4467	return (AHCI_SUCCESS);
4468err_out:
4469
4470	for (slot--; slot >= 0; slot--) {
4471		/* Unbind the cmd table dma handle first */
4472		(void) ddi_dma_unbind_handle(
4473		    ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4474
4475		/* Then free the underlying memory */
4476		ddi_dma_mem_free(
4477		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
4478
4479		/* Now free the handle itself */
4480		ddi_dma_free_handle(
4481		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4482	}
4483
4484	return (AHCI_FAILURE);
4485}
4486
4487/*
4488 * Deallocates memory for all Command Tables.
4489 *
4490 * WARNING!!! ahciport_mutex should be acquired before the function
4491 * is called.
4492 */
4493static void
4494ahci_dealloc_cmd_tables(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp)
4495{
4496	int slot;
4497
4498	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
4499	    "ahci_dealloc_cmd_tables: %d enter",
4500	    ahci_portp->ahciport_port_num);
4501
4502	for (slot = 0; slot < ahci_ctlp->ahcictl_num_cmd_slots; slot++) {
4503		/* Unbind the cmd table dma handle first. */
4504		(void) ddi_dma_unbind_handle(
4505		    ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4506
4507		/* Then free the underlying memory. */
4508		ddi_dma_mem_free(
4509		    &ahci_portp->ahciport_cmd_tables_acc_handle[slot]);
4510
4511		/* Now free the handle itself. */
4512		ddi_dma_free_handle(
4513		    &ahci_portp->ahciport_cmd_tables_dma_handle[slot]);
4514	}
4515}
4516
4517/*
4518 * WARNING!!! ahciport_mutex should be acquired before the function
4519 * is called.
4520 */
4521static void
4522ahci_update_sata_registers(ahci_ctl_t *ahci_ctlp, uint8_t port,
4523    sata_device_t *sd)
4524{
4525	sd->satadev_scr.sstatus =
4526	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4527	    (uint32_t *)(AHCI_PORT_PxSSTS(ahci_ctlp, port)));
4528	sd->satadev_scr.serror =
4529	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4530	    (uint32_t *)(AHCI_PORT_PxSERR(ahci_ctlp, port)));
4531	sd->satadev_scr.scontrol =
4532	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4533	    (uint32_t *)(AHCI_PORT_PxSCTL(ahci_ctlp, port)));
4534	sd->satadev_scr.sactive =
4535	    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4536	    (uint32_t *)(AHCI_PORT_PxSACT(ahci_ctlp, port)));
4537}
4538
4539/*
4540 * For poll mode, ahci_port_intr will be called to emulate the interrupt
4541 */
4542static void
4543ahci_port_intr(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp, uint8_t port)
4544{
4545	uint32_t port_intr_status;
4546	uint32_t port_intr_enable;
4547
4548	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
4549	    "ahci_port_intr enter: port %d", port);
4550
4551	mutex_enter(&ahci_portp->ahciport_mutex);
4552	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_POLLING) {
4553		/* For SATA_OPMODE_POLLING commands */
4554		port_intr_enable =
4555		    (AHCI_INTR_STATUS_DHRS |
4556		    AHCI_INTR_STATUS_PSS |
4557		    AHCI_INTR_STATUS_SDBS |
4558		    AHCI_INTR_STATUS_UFS |
4559		    AHCI_INTR_STATUS_PCS |
4560		    AHCI_INTR_STATUS_PRCS |
4561		    AHCI_INTR_STATUS_OFS |
4562		    AHCI_INTR_STATUS_INFS |
4563		    AHCI_INTR_STATUS_IFS |
4564		    AHCI_INTR_STATUS_HBDS |
4565		    AHCI_INTR_STATUS_HBFS |
4566		    AHCI_INTR_STATUS_TFES);
4567		mutex_exit(&ahci_portp->ahciport_mutex);
4568		goto next;
4569	}
4570	mutex_exit(&ahci_portp->ahciport_mutex);
4571
4572	/*
4573	 * port_intr_enable indicates that the corresponding interrrupt
4574	 * reporting is enabled.
4575	 */
4576	port_intr_enable = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4577	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port));
4578next:
4579	/*
4580	 * port_intr_stats indicates that the corresponding interrupt
4581	 * condition is active.
4582	 */
4583	port_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4584	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port));
4585
4586	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4587	    "ahci_port_intr: port %d, port_intr_status = 0x%x, "
4588	    "port_intr_enable = 0x%x",
4589	    port, port_intr_status, port_intr_enable);
4590
4591	port_intr_status &= port_intr_enable;
4592
4593	/* First clear the port interrupts status */
4594	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4595	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
4596	    port_intr_status);
4597
4598	/* Check the completed non-queued commands */
4599	if (port_intr_status & (AHCI_INTR_STATUS_DHRS |
4600	    AHCI_INTR_STATUS_PSS)) {
4601		(void) ahci_intr_cmd_cmplt(ahci_ctlp,
4602		    ahci_portp, port);
4603	}
4604
4605	/* Check the completed queued commands */
4606	if (port_intr_status & AHCI_INTR_STATUS_SDBS) {
4607		(void) ahci_intr_set_device_bits(ahci_ctlp,
4608		    ahci_portp, port);
4609	}
4610
4611	/* Check the port connect change status interrupt bit */
4612	if (port_intr_status & AHCI_INTR_STATUS_PCS) {
4613		(void) ahci_intr_port_connect_change(ahci_ctlp,
4614		    ahci_portp, port);
4615	}
4616
4617	/* Check the device mechanical presence status interrupt bit */
4618	if (port_intr_status & AHCI_INTR_STATUS_DMPS) {
4619		(void) ahci_intr_device_mechanical_presence_status(
4620		    ahci_ctlp, ahci_portp, port);
4621	}
4622
4623	/* Check the PhyRdy change status interrupt bit */
4624	if (port_intr_status & AHCI_INTR_STATUS_PRCS) {
4625		(void) ahci_intr_phyrdy_change(ahci_ctlp, ahci_portp,
4626		    port);
4627	}
4628
4629	/*
4630	 * Check the non-fatal error interrupt bits, there are three
4631	 * kinds of non-fatal errors at the time being:
4632	 *
4633	 *    PxIS.UFS - Unknown FIS Error
4634	 *    PxIS.OFS - Overflow Error
4635	 *    PxIS.INFS - Interface Non-Fatal Error
4636	 *
4637	 * For these non-fatal errors, the HBA can continue to operate,
4638	 * so the driver just log the error messages.
4639	 */
4640	if (port_intr_status & (AHCI_INTR_STATUS_UFS |
4641	    AHCI_INTR_STATUS_OFS |
4642	    AHCI_INTR_STATUS_INFS)) {
4643		(void) ahci_intr_non_fatal_error(ahci_ctlp, ahci_portp,
4644		    port, port_intr_status);
4645	}
4646
4647	/*
4648	 * Check the fatal error interrupt bits, there are four kinds
4649	 * of fatal errors for AHCI controllers:
4650	 *
4651	 *    PxIS.HBFS - Host Bus Fatal Error
4652	 *    PxIS.HBDS - Host Bus Data Error
4653	 *    PxIS.IFS - Interface Fatal Error
4654	 *    PxIS.TFES - Task File Error
4655	 *
4656	 * The fatal error means the HBA can not recover from it by
4657	 * itself, and it will try to abort the transfer, and the software
4658	 * must intervene to restart the port.
4659	 */
4660	if (port_intr_status & (AHCI_INTR_STATUS_IFS |
4661	    AHCI_INTR_STATUS_HBDS |
4662	    AHCI_INTR_STATUS_HBFS |
4663	    AHCI_INTR_STATUS_TFES))
4664		(void) ahci_intr_fatal_error(ahci_ctlp, ahci_portp,
4665		    port, port_intr_status);
4666
4667	/* Check the cold port detect interrupt bit */
4668	if (port_intr_status & AHCI_INTR_STATUS_CPDS) {
4669		(void) ahci_intr_cold_port_detect(ahci_ctlp, ahci_portp, port);
4670	}
4671
4672	/* Second clear the corresponding bit in IS.IPS */
4673	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
4674	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp), (0x1 << port));
4675}
4676
4677/*
4678 * Interrupt service handler
4679 */
4680static uint_t
4681ahci_intr(caddr_t arg1, caddr_t arg2)
4682{
4683#ifndef __lock_lint
4684	_NOTE(ARGUNUSED(arg2))
4685#endif
4686	/* LINTED */
4687	ahci_ctl_t *ahci_ctlp = (ahci_ctl_t *)arg1;
4688	ahci_port_t *ahci_portp;
4689	int32_t global_intr_status;
4690	uint8_t port;
4691
4692	/*
4693	 * global_intr_status indicates that the corresponding port has
4694	 * an interrupt pending.
4695	 */
4696	global_intr_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4697	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp));
4698
4699	if (!(global_intr_status & ahci_ctlp->ahcictl_ports_implemented)) {
4700		/* The interrupt is not ours */
4701		return (DDI_INTR_UNCLAIMED);
4702	}
4703
4704	/* Loop for all the ports */
4705	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
4706		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
4707			continue;
4708		}
4709		if (!((0x1 << port) & global_intr_status)) {
4710			continue;
4711		}
4712
4713		ahci_portp = ahci_ctlp->ahcictl_ports[port];
4714
4715		/* Call ahci_port_intr */
4716		ahci_port_intr(ahci_ctlp, ahci_portp, port);
4717	}
4718
4719	return (DDI_INTR_CLAIMED);
4720}
4721
4722/*
4723 * For non-queued commands, when the corresponding bit in the PxCI register
4724 * is cleared, it means the command is completed successfully. And according
4725 * to the HBA state machine, there are three conditions which possibly will
4726 * try to clear the PxCI register bit.
4727 *	1. Receive one D2H Register FIS which is with 'I' bit set
4728 *	2. Update PIO Setup FIS
4729 *	3. Transmit a command and receive R_OK if CTBA.C is set (software reset)
4730 *
4731 * Process completed non-queued commands when the interrupt status bit -
4732 * AHCI_INTR_STATUS_DHRS or AHCI_INTR_STATUS_PSS is set.
4733 *
4734 * AHCI_INTR_STATUS_DHRS means a D2H Register FIS has been received
4735 * with the 'I' bit set. And the following commands will send thus
4736 * FIS with 'I' bit set upon the successful completion:
4737 * 	1. Non-data commands
4738 * 	2. DMA data-in command
4739 * 	3. DMA data-out command
4740 * 	4. PIO data-out command
4741 *	5. PACKET non-data commands
4742 *	6. PACKET PIO data-in command
4743 *	7. PACKET PIO data-out command
4744 *	8. PACKET DMA data-in command
4745 *	9. PACKET DMA data-out command
4746 *
4747 * AHCI_INTR_STATUS_PSS means a PIO Setup FIS has been received
4748 * with the 'I' bit set. And the following commands will send this
4749 * FIS upon the successful completion:
4750 * 	1. PIO data-in command
4751 */
4752static int
4753ahci_intr_cmd_cmplt(ahci_ctl_t *ahci_ctlp,
4754    ahci_port_t *ahci_portp, uint8_t port)
4755{
4756	uint32_t port_cmd_issue = 0;
4757	uint32_t finished_tags;
4758	int finished_slot;
4759	sata_pkt_t *satapkt;
4760	ahci_fis_d2h_register_t *rcvd_fisp;
4761#if AHCI_DEBUG
4762	ahci_cmd_header_t *cmd_header;
4763	uint32_t cmd_dmacount;
4764#endif
4765
4766	mutex_enter(&ahci_portp->ahciport_mutex);
4767
4768	if (!ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
4769	    !NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
4770		/*
4771		 * Spurious interrupt. Nothing to be done.
4772		 */
4773		mutex_exit(&ahci_portp->ahciport_mutex);
4774		return (AHCI_SUCCESS);
4775	}
4776
4777	port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4778	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4779
4780	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
4781		/* Slot 0 is always used during error recovery */
4782		finished_tags = 0x1 & ~port_cmd_issue;
4783		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
4784		    "ahci_intr_cmd_cmplt: port %d the sata pkt for error "
4785		    "retrieval is finished, and finished_tags = 0x%x",
4786		    port, finished_tags);
4787	} else {
4788		finished_tags = ahci_portp->ahciport_pending_tags &
4789		    ~port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp);
4790	}
4791
4792	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4793	    "ahci_intr_cmd_cmplt: pending_tags = 0x%x, "
4794	    "port_cmd_issue = 0x%x finished_tags = 0x%x",
4795	    ahci_portp->ahciport_pending_tags, port_cmd_issue,
4796	    finished_tags);
4797
4798	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp) &&
4799	    (finished_tags == 0x1)) {
4800		satapkt = ahci_portp->ahciport_err_retri_pkt;
4801		ASSERT(satapkt != NULL);
4802
4803		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4804		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
4805		    "with SATA_PKT_COMPLETED", (void *)satapkt);
4806
4807		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
4808		goto out;
4809	}
4810
4811	while (finished_tags) {
4812		finished_slot = ddi_ffs(finished_tags) - 1;
4813		if (finished_slot == -1) {
4814			goto out;
4815		}
4816
4817		satapkt = ahci_portp->ahciport_slot_pkts[finished_slot];
4818		ASSERT(satapkt != NULL);
4819#if AHCI_DEBUG
4820		/*
4821		 * For non-native queued commands, the PRD byte count field
4822		 * shall contain an accurate count of the number of bytes
4823		 * transferred for the command before the PxCI bit is cleared
4824		 * to '0' for the command.
4825		 *
4826		 * The purpose of this field is to let software know how many
4827		 * bytes transferred for a given operation in order to
4828		 * determine if underflow occurred. When issuing native command
4829		 * queuing commands, this field should not be used and is not
4830		 * required to be valid since in this case underflow is always
4831		 * illegal.
4832		 *
4833		 * For data reads, the HBA will update its PRD byte count with
4834		 * the total number of bytes received from the last FIS, and
4835		 * may be able to continue normally. For data writes, the
4836		 * device will detect an error, and HBA most likely will get
4837		 * a fatal error.
4838		 *
4839		 * Therefore, here just put code to debug part. And please
4840		 * refer to the comment above ahci_intr_fatal_error for the
4841		 * definition of underflow error.
4842		 */
4843		cmd_dmacount =
4844		    ahci_portp->ahciport_prd_bytecounts[finished_slot];
4845		if (cmd_dmacount) {
4846			cmd_header =
4847			    &ahci_portp->ahciport_cmd_list[finished_slot];
4848			AHCIDBG(AHCIDBG_INTR|AHCIDBG_PRDT, ahci_ctlp,
4849			    "ahci_intr_cmd_cmplt: port %d, "
4850			    "PRD Byte Count = 0x%x, "
4851			    "ahciport_prd_bytecounts = 0x%x", port,
4852			    cmd_header->ahcich_prd_byte_count,
4853			    cmd_dmacount);
4854
4855			if (cmd_header->ahcich_prd_byte_count != cmd_dmacount) {
4856				AHCIDBG(AHCIDBG_UNDERFLOW, ahci_ctlp,
4857				    "ahci_intr_cmd_cmplt: port %d, "
4858				    "an underflow occurred", port);
4859			}
4860		}
4861#endif
4862
4863		/*
4864		 * For SATAC_SMART command with SATA_SMART_RETURN_STATUS
4865		 * feature, sata_special_regs flag will be set, and the
4866		 * driver should copy the status and the other corresponding
4867		 * register values in the D2H Register FIS received (It's
4868		 * working on Non-data protocol) from the device back to
4869		 * the sata_cmd.
4870		 *
4871		 * For every AHCI port, there is only one Received FIS
4872		 * structure, which contains the FISes received from the
4873		 * device, So we're trying to copy the content of D2H
4874		 * Register FIS in the Received FIS structure back to
4875		 * the sata_cmd.
4876		 */
4877		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
4878			rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
4879			    ahcirf_d2h_register_fis);
4880			satapkt->satapkt_cmd.satacmd_status_reg =
4881			    GET_RFIS_STATUS(rcvd_fisp);
4882			ahci_copy_out_regs(&satapkt->satapkt_cmd, rcvd_fisp);
4883		}
4884
4885		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
4886		    "ahci_intr_cmd_cmplt: sending up pkt 0x%p "
4887		    "with SATA_PKT_COMPLETED", (void *)satapkt);
4888
4889		CLEAR_BIT(ahci_portp->ahciport_pending_tags, finished_slot);
4890		CLEAR_BIT(finished_tags, finished_slot);
4891		ahci_portp->ahciport_slot_pkts[finished_slot] = NULL;
4892
4893		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
4894	}
4895out:
4896	AHCIDBG(AHCIDBG_PKTCOMP, ahci_ctlp,
4897	    "ahci_intr_cmd_cmplt: pending_tags = 0x%x",
4898	    ahci_portp->ahciport_pending_tags);
4899
4900	mutex_exit(&ahci_portp->ahciport_mutex);
4901
4902	return (AHCI_SUCCESS);
4903}
4904
4905/*
4906 * AHCI_INTR_STATUS_SDBS means a Set Device Bits FIS has been received
4907 * with the 'I' bit set and has been copied into system memory. It will
4908 * be sent under the following situations:
4909 *
4910 * 	1. NCQ command is completed
4911 * 	2. Asynchronous notification
4912 *
4913 * The completion of NCQ commands (READ/WRITE FPDMA QUEUED) is performed
4914 * via the Set Device Bits FIS. When such event is generated, the software
4915 * needs to read PxSACT register and compares the current value to the
4916 * list of commands previously issue by software. ahciport_pending_ncq_tags
4917 * keeps the tags of previously issued commands.
4918 *
4919 * Asynchronous Notification is a feature in SATA II, which allows an
4920 * ATAPI device to send a signal to the host when media is inserted or
4921 * removed and avoids polling the device for media changes. The signal
4922 * sent to the host is a Set Device Bits FIS with the 'I' and 'N' bits
4923 * set to '1'. At the moment, it's not supported yet.
4924 */
4925static int
4926ahci_intr_set_device_bits(ahci_ctl_t *ahci_ctlp,
4927    ahci_port_t *ahci_portp, uint8_t port)
4928{
4929	uint32_t port_sactive;
4930	uint32_t port_cmd_issue;
4931	uint32_t issued_tags;
4932	int issued_slot;
4933	uint32_t finished_tags;
4934	int finished_slot;
4935	sata_pkt_t *satapkt;
4936
4937	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4938	    "ahci_intr_set_device_bits enter: port %d", port);
4939
4940	mutex_enter(&ahci_portp->ahciport_mutex);
4941	if (!NCQ_CMD_IN_PROGRESS(ahci_portp)) {
4942		mutex_exit(&ahci_portp->ahciport_mutex);
4943		return (AHCI_SUCCESS);
4944	}
4945
4946	/*
4947	 * First the handler got which commands are finished by checking
4948	 * PxSACT register
4949	 */
4950	port_sactive = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4951	    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
4952
4953	finished_tags = ahci_portp->ahciport_pending_ncq_tags &
4954	    ~port_sactive & AHCI_NCQ_SLOT_MASK(ahci_portp);
4955
4956	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4957	    "ahci_intr_set_device_bits: port %d pending_ncq_tags = 0x%x "
4958	    "port_sactive = 0x%x", port,
4959	    ahci_portp->ahciport_pending_ncq_tags, port_sactive);
4960
4961	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4962	    "ahci_intr_set_device_bits: finished_tags = 0x%x", finished_tags);
4963
4964	/*
4965	 * For NCQ commands, the software can determine which command has
4966	 * already been transmitted to the device by checking PxCI register.
4967	 */
4968	port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
4969	    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
4970
4971	issued_tags = ahci_portp->ahciport_pending_tags &
4972	    ~port_cmd_issue & AHCI_SLOT_MASK(ahci_ctlp);
4973
4974	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4975	    "ahci_intr_set_device_bits: port %d pending_tags = 0x%x "
4976	    "port_cmd_issue = 0x%x", port,
4977	    ahci_portp->ahciport_pending_tags, port_cmd_issue);
4978
4979	AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
4980	    "ahci_intr_set_device_bits: issued_tags = 0x%x", issued_tags);
4981
4982	/*
4983	 * Clear ahciport_pending_tags bit when the corresponding command
4984	 * is already sent down to the device.
4985	 */
4986	while (issued_tags) {
4987		issued_slot = ddi_ffs(issued_tags) - 1;
4988		if (issued_slot == -1) {
4989			goto next;
4990		}
4991		CLEAR_BIT(ahci_portp->ahciport_pending_tags, issued_slot);
4992		CLEAR_BIT(issued_tags, issued_slot);
4993	}
4994
4995next:
4996	while (finished_tags) {
4997		finished_slot = ddi_ffs(finished_tags) - 1;
4998		if (finished_slot == -1) {
4999			goto out;
5000		}
5001
5002		/* The command is certainly transmitted to the device */
5003		ASSERT(!(ahci_portp->ahciport_pending_tags &
5004		    (0x1 << finished_slot)));
5005
5006		satapkt = ahci_portp->ahciport_slot_pkts[finished_slot];
5007		ASSERT(satapkt != NULL);
5008
5009		AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ, ahci_ctlp,
5010		    "ahci_intr_set_device_bits: sending up pkt 0x%p "
5011		    "with SATA_PKT_COMPLETED", (void *)satapkt);
5012
5013		CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags, finished_slot);
5014		CLEAR_BIT(finished_tags, finished_slot);
5015		ahci_portp->ahciport_slot_pkts[finished_slot] = NULL;
5016
5017		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
5018	}
5019out:
5020	AHCIDBG(AHCIDBG_PKTCOMP|AHCIDBG_NCQ, ahci_ctlp,
5021	    "ahci_intr_set_device_bits: port %d "
5022	    "pending_ncq_tags = 0x%x pending_tags = 0x%x",
5023	    port, ahci_portp->ahciport_pending_ncq_tags,
5024	    ahci_portp->ahciport_pending_tags);
5025
5026	mutex_exit(&ahci_portp->ahciport_mutex);
5027
5028	return (AHCI_SUCCESS);
5029}
5030
5031/*
5032 * 1=Change in Current Connect Status. 0=No change in Current Connect Status.
5033 * This bit reflects the state of PxSERR.DIAG.X. This bit is only cleared
5034 * when PxSERR.DIAG.X is cleared. When PxSERR.DIAG.X is set to one, it
5035 * indicates a COMINIT signal was received.
5036 *
5037 * Hot plug insertion is detected by reception of a COMINIT signal from the
5038 * device. On reception of unsolicited COMINIT, the HBA shall generate a
5039 * COMRESET. If the COMINIT is in responce to a COMRESET, then the HBA shall
5040 * begin the normal communication negotiation sequence as outlined in the
5041 * Serial ATA 1.0a specification. When a COMRESET is sent to the device the
5042 * PxSSTS.DET field shall be cleared to 0h. When a COMINIT is received, the
5043 * PxSSTS.DET field shall be set to 1h. When the communication negotiation
5044 * sequence is complete and PhyRdy is true the PxSSTS.DET field	shall be set
5045 * to 3h. Therefore, at the moment the ahci driver is going to check PhyRdy
5046 * to handle hot plug insertion. In this interrupt handler, just do nothing
5047 * but print some log message and clear the bit.
5048 */
5049static int
5050ahci_intr_port_connect_change(ahci_ctl_t *ahci_ctlp,
5051    ahci_port_t *ahci_portp, uint8_t port)
5052{
5053#if AHCI_DEBUG
5054	uint32_t port_serror;
5055#endif
5056
5057	mutex_enter(&ahci_portp->ahciport_mutex);
5058
5059#if AHCI_DEBUG
5060	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5061	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
5062
5063	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
5064	    "ahci_intr_port_connect_change: port %d, "
5065	    "port_serror = 0x%x", port, port_serror);
5066#endif
5067
5068	/* Clear PxSERR.DIAG.X to clear the interrupt bit */
5069	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5070	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5071	    SERROR_EXCHANGED_ERR);
5072
5073	mutex_exit(&ahci_portp->ahciport_mutex);
5074
5075	return (AHCI_SUCCESS);
5076}
5077
5078/*
5079 * Hot Plug Operation for platforms that support Mechanical Presence
5080 * Switches.
5081 *
5082 * When set, it indicates that a mechanical presence switch attached to this
5083 * port has been opened or closed, which may lead to a change in the connection
5084 * state of the device. This bit is only valid if both CAP.SMPS and PxCMD.MPSP
5085 * are set to '1'.
5086 *
5087 * At the moment, this interrupt is not needed and disabled and we just log
5088 * the debug message.
5089 */
5090static int
5091ahci_intr_device_mechanical_presence_status(ahci_ctl_t *ahci_ctlp,
5092    ahci_port_t *ahci_portp, uint8_t port)
5093{
5094	uint32_t cap_status, port_cmd_status;
5095
5096	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
5097	    "ahci_intr_device_mechanical_presence_status enter, "
5098	    "port %d", port);
5099
5100	cap_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5101	    (uint32_t *)AHCI_GLOBAL_CAP(ahci_ctlp));
5102
5103	mutex_enter(&ahci_portp->ahciport_mutex);
5104	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5105	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5106
5107	if (!(cap_status & AHCI_HBA_CAP_SMPS) ||
5108	    !(port_cmd_status & AHCI_CMD_STATUS_MPSP)) {
5109		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5110		    "CAP.SMPS or PxCMD.MPSP is not set, so just ignore "
5111		    "the interrupt: cap_status = 0x%x, "
5112		    "port_cmd_status = 0x%x", cap_status, port_cmd_status);
5113		mutex_exit(&ahci_portp->ahciport_mutex);
5114
5115		return (AHCI_SUCCESS);
5116	}
5117
5118#if AHCI_DEBUG
5119	if (port_cmd_status & AHCI_CMD_STATUS_MPSS) {
5120		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5121		    "The mechanical presence switch is open: "
5122		    "port %d, port_cmd_status = 0x%x",
5123		    port, port_cmd_status);
5124	} else {
5125		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5126		    "The mechanical presence switch is close: "
5127		    "port %d, port_cmd_status = 0x%x",
5128		    port, port_cmd_status);
5129	}
5130#endif
5131
5132	mutex_exit(&ahci_portp->ahciport_mutex);
5133
5134	return (AHCI_SUCCESS);
5135}
5136
5137/*
5138 * Native Hot Plug Support.
5139 *
5140 * When set, it indicates that the internal PHYRDY signal changed state.
5141 * This bit reflects the state of PxSERR.DIAG.N.
5142 *
5143 * There are three kinds of conditions to generate this interrupt event:
5144 * 1. a device is inserted
5145 * 2. a device is disconnected
5146 * 3. when the link enters/exits a Partial or Slumber interface power
5147 *    management state
5148 *
5149 * If inteface power management is enabled for a port, the PxSERR.DIAG.N
5150 * bit may be set due to the link entering the Partial or Slumber power
5151 * management state, rather than due to a hot plug insertion or removal
5152 * event. So far, the interface power management is disabled, so the
5153 * driver can reliably get removal detection notification via the
5154 * PxSERR.DIAG.N bit.
5155 */
5156static int
5157ahci_intr_phyrdy_change(ahci_ctl_t *ahci_ctlp,
5158    ahci_port_t *ahci_portp, uint8_t port)
5159{
5160	uint32_t port_sstatus = 0; /* No dev present & PHY not established. */
5161	sata_device_t sdevice;
5162	int dev_exists_now = 0;
5163	int dev_existed_previously = 0;
5164
5165	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY, ahci_ctlp,
5166	    "ahci_intr_phyrdy_change enter, port %d", port);
5167
5168	/* Clear PxSERR.DIAG.N to clear the interrupt bit */
5169	mutex_enter(&ahci_portp->ahciport_mutex);
5170	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5171	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5172	    SERROR_PHY_RDY_CHG);
5173	mutex_exit(&ahci_portp->ahciport_mutex);
5174
5175	mutex_enter(&ahci_ctlp->ahcictl_mutex);
5176	if ((ahci_ctlp->ahcictl_sata_hba_tran == NULL) ||
5177	    (ahci_portp == NULL)) {
5178		/* The whole controller setup is not yet done. */
5179		mutex_exit(&ahci_ctlp->ahcictl_mutex);
5180		return (AHCI_SUCCESS);
5181	}
5182	mutex_exit(&ahci_ctlp->ahcictl_mutex);
5183
5184	mutex_enter(&ahci_portp->ahciport_mutex);
5185
5186	/* SStatus tells the presence of device. */
5187	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5188	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
5189
5190	if (SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_PHYCOM) {
5191		dev_exists_now = 1;
5192	}
5193
5194	if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) {
5195		dev_existed_previously = 1;
5196	}
5197
5198	if (ahci_portp->ahciport_flags & AHCI_PORT_FLAG_NODEV) {
5199		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_NODEV;
5200		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5201		    "ahci_intr_phyrdy_change: port %d "
5202		    "AHCI_PORT_FLAG_NODEV is cleared", port);
5203		if (dev_exists_now == 0)
5204			dev_existed_previously = 1;
5205	}
5206
5207	bzero((void *)&sdevice, sizeof (sata_device_t));
5208	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
5209	sdevice.satadev_addr.qual = SATA_ADDR_CPORT;
5210	sdevice.satadev_addr.pmport = 0;
5211	sdevice.satadev_state = SATA_PSTATE_PWRON;
5212	ahci_portp->ahciport_port_state = SATA_PSTATE_PWRON;
5213
5214	if (dev_exists_now) {
5215		if (dev_existed_previously) {
5216			/* Things are fine now. The loss was temporary. */
5217			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
5218			    "ahci_intr_phyrdy_change  port %d "
5219			    "device link lost/established", port);
5220
5221			mutex_exit(&ahci_portp->ahciport_mutex);
5222			sata_hba_event_notify(
5223			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5224			    &sdevice,
5225			    SATA_EVNT_LINK_LOST|SATA_EVNT_LINK_ESTABLISHED);
5226			mutex_enter(&ahci_portp->ahciport_mutex);
5227
5228		} else {
5229			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
5230			    "ahci_intr_phyrdy_change: port %d "
5231			    "device link established", port);
5232
5233			/* A new device has been detected. */
5234			(void) ahci_port_reset(ahci_ctlp, ahci_portp, port);
5235			ahci_find_dev_signature(ahci_ctlp, ahci_portp, port);
5236
5237			/* Try to start the port */
5238			if (ahci_start_port(ahci_ctlp, ahci_portp, port)
5239			    != AHCI_SUCCESS) {
5240				sdevice.satadev_state |= SATA_PSTATE_FAILED;
5241				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5242				    "ahci_intr_phyrdy_change: port %d failed "
5243				    "at start port", port);
5244			}
5245
5246			/* Clear the max queue depth for inserted device */
5247			ahci_portp->ahciport_max_ncq_tags = 0;
5248
5249			mutex_exit(&ahci_portp->ahciport_mutex);
5250			sata_hba_event_notify(
5251			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5252			    &sdevice,
5253			    SATA_EVNT_LINK_ESTABLISHED);
5254			mutex_enter(&ahci_portp->ahciport_mutex);
5255
5256		}
5257	} else { /* No device exists now */
5258
5259		if (dev_existed_previously) {
5260			AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
5261			    "ahci_intr_phyrdy_change: port %d "
5262			    "device link lost", port);
5263
5264			ahci_reject_all_abort_pkts(ahci_ctlp, ahci_portp, port);
5265			(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
5266			    ahci_portp, port);
5267
5268			/* An existing device is lost. */
5269			ahci_portp->ahciport_device_type = SATA_DTYPE_NONE;
5270
5271			mutex_exit(&ahci_portp->ahciport_mutex);
5272			sata_hba_event_notify(
5273			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5274			    &sdevice,
5275			    SATA_EVNT_LINK_LOST);
5276			mutex_enter(&ahci_portp->ahciport_mutex);
5277		}
5278	}
5279
5280	mutex_exit(&ahci_portp->ahciport_mutex);
5281
5282	return (AHCI_SUCCESS);
5283}
5284
5285/*
5286 * PxIS.UFS - Unknown FIS Error
5287 *
5288 * This interrupt event means an unknown FIS was received and has been
5289 * copied into system memory. An unknown FIS is not considered an illegal
5290 * FIS, unless the length received is more than 64 bytes. If an unknown
5291 * FIS arrives with length <= 64 bytes, it is posted and the HBA continues
5292 * normal operation. If the unknown FIS is more than 64 bytes, then it
5293 * won't be posted to memory and PxSERR.ERR.P will be set, which is then
5294 * a fatal error.
5295 *
5296 * PxIS.OFS - Overflow Error
5297 *
5298 * Command list overflow is defined as software building a command table
5299 * that has fewer total bytes than the transaction given to the device.
5300 * On device writes, the HBA will run out of data, and on reads, there
5301 * will be no room to put the data.
5302 *
5303 * For an overflow on data read, either PIO or DMA, the HBA will set
5304 * PxIS.OFS, and the HBA will do a best effort to continue, and it's a
5305 * non-fatal error when the HBA can continues. Sometimes, it will cause
5306 * a fatal error and need the software to do something.
5307 *
5308 * For an overflow on data write, setting PxIS.OFS is optional for both
5309 * DMA and PIO, and it's a fatal error, and a COMRESET is required by
5310 * software to clean up from this serious error.
5311 *
5312 * PxIS.INFS - Interface Non-Fatal Error
5313 *
5314 * This interrupt event indicates that the HBA encountered an error on
5315 * the Serial ATA interface but was able to continue operation. The kind
5316 * of error usually occurred during a non-Data FIS, and under this condition
5317 * the FIS will be re-transmitted by HBA automatically.
5318 *
5319 * When the FMA is implemented, there should be a stat structure to
5320 * record how many every kind of error happens.
5321 */
5322static int
5323ahci_intr_non_fatal_error(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
5324    uint8_t port, uint32_t intr_status)
5325{
5326	uint32_t port_serror;
5327#if AHCI_DEBUG
5328	uint32_t port_cmd_status;
5329	uint32_t port_cmd_issue;
5330	uint32_t port_sactive;
5331	int current_slot;
5332	uint32_t current_tags;
5333	sata_pkt_t *satapkt;
5334	ahci_cmd_header_t *cmd_header;
5335	uint32_t cmd_dmacount;
5336#endif
5337
5338	mutex_enter(&ahci_portp->ahciport_mutex);
5339
5340	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5341	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
5342
5343	AHCIDBG(AHCIDBG_INTR|AHCIDBG_ENTRY|AHCIDBG_ERRS, ahci_ctlp,
5344	    "ahci_intr_non_fatal_error: port %d, "
5345	    "port_serror = 0x%x", port, port_serror);
5346
5347	ahci_log_serror_message(ahci_ctlp, port, port_serror, 1);
5348
5349	if (intr_status & AHCI_INTR_STATUS_UFS) {
5350		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
5351		    "ahci port %d has unknown FIS error", port);
5352
5353		/* Clear the interrupt bit by clearing PxSERR.DIAG.F */
5354		ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5355		    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
5356		    SERROR_FIS_TYPE);
5357	}
5358
5359#if AHCI_DEBUG
5360	if (intr_status & AHCI_INTR_STATUS_OFS) {
5361		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5362		    "ahci port %d has overflow error", port);
5363	}
5364
5365	if (intr_status & AHCI_INTR_STATUS_INFS) {
5366		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5367		    "ahci port %d has interface non fatal error", port);
5368	}
5369
5370	/*
5371	 * Record the error occurred command's slot.
5372	 */
5373	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
5374	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
5375		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5376		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5377
5378		current_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
5379		    AHCI_CMD_STATUS_CCS_SHIFT;
5380
5381		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
5382			satapkt = ahci_portp->ahciport_err_retri_pkt;
5383			ASSERT(satapkt != NULL);
5384			ASSERT(current_slot == 0);
5385		} else {
5386			satapkt = ahci_portp->ahciport_slot_pkts[current_slot];
5387		}
5388
5389		if (satapkt != NULL) {
5390			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5391			    "ahci_intr_non_fatal_error: pending_tags = 0x%x "
5392			    "cmd 0x%x", ahci_portp->ahciport_pending_tags,
5393			    satapkt->satapkt_cmd.satacmd_cmd_reg);
5394
5395			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5396			    "ahci_intr_non_fatal_error: port %d, "
5397			    "satapkt 0x%p is being processed when error occurs",
5398			    port, (void *)satapkt);
5399
5400			/*
5401			 * PRD Byte Count field of command header is not
5402			 * required to reflect the total number of bytes
5403			 * transferred when an overflow occurs, so here
5404			 * just log the value.
5405			 */
5406			cmd_dmacount =
5407			    ahci_portp->ahciport_prd_bytecounts[current_slot];
5408			if (cmd_dmacount) {
5409				cmd_header = &ahci_portp->
5410				    ahciport_cmd_list[current_slot];
5411				AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5412				    "ahci_intr_non_fatal_error: port %d, "
5413				    "PRD Byte Count = 0x%x, "
5414				    "ahciport_prd_bytecounts = 0x%x", port,
5415				    cmd_header->ahcich_prd_byte_count,
5416				    cmd_dmacount);
5417			}
5418		}
5419	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
5420		/*
5421		 * For queued command, list those command which have already
5422		 * been transmitted to the device and still not completed.
5423		 */
5424		port_sactive = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5425		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
5426
5427		port_cmd_issue = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5428		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
5429
5430		AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ|AHCIDBG_ERRS, ahci_ctlp,
5431		    "ahci_intr_non_fatal_error: pending_ncq_tags = 0x%x "
5432		    "port_sactive = 0x%x port_cmd_issue = 0x%x",
5433		    ahci_portp->ahciport_pending_ncq_tags,
5434		    port_sactive, port_cmd_issue);
5435
5436		current_tags = ahci_portp->ahciport_pending_ncq_tags &
5437		    port_sactive & ~port_cmd_issue &
5438		    AHCI_NCQ_SLOT_MASK(ahci_portp);
5439
5440		while (current_tags) {
5441			current_slot = ddi_ffs(current_tags) - 1;
5442			if (current_slot == -1) {
5443				goto out;
5444			}
5445
5446			satapkt = ahci_portp->ahciport_slot_pkts[current_slot];
5447			AHCIDBG(AHCIDBG_INTR|AHCIDBG_NCQ|AHCIDBG_ERRS,
5448			    ahci_ctlp, "ahci_intr_non_fatal_error: "
5449			    "port %d, satapkt 0x%p is outstanding when "
5450			    "error occurs", port, (void *)satapkt);
5451
5452			CLEAR_BIT(current_tags, current_slot);
5453		}
5454	}
5455out:
5456#endif
5457	mutex_exit(&ahci_portp->ahciport_mutex);
5458
5459	return (AHCI_SUCCESS);
5460}
5461
5462/*
5463 * According to the AHCI spec, the error types include system memory
5464 * errors, interface errors, port multiplier errors, device errors,
5465 * command list overflow, command list underflow, native command
5466 * queuing tag errors and pio data transfer errors.
5467 *
5468 * System memory errors such as target abort, master abort, and parity
5469 * may cause the host to stop, and they are serious errors and needed
5470 * to be recovered with software intervention. When system software
5471 * has given a pointer to the HBA that doesn't exist in physical memory,
5472 * a master/target abort error occurs, and PxIS.HBFS will be set. A
5473 * data error such as CRC or parity occurs, the HBA aborts the transfer
5474 * (if necessary) and PxIS.HBDS will be set.
5475 *
5476 * Interface errors are errors that occur due to electrical issues on
5477 * the interface, or protocol miscommunication between the device and
5478 * HBA, and the respective PxSERR register bit will be set. And PxIS.IFS
5479 * (fatal) or PxIS.INFS (non-fatal) will be set. The conditions that
5480 * causes PxIS.IFS/PxIS.INFS to be set are
5481 * 	1. in PxSERR.ERR, P bit is set to '1'
5482 *	2. in PxSERR.DIAG, C or H bit is set to '1'
5483 *	3. PhyRdy drop unexpectly, N bit is set to '1'
5484 * If the error occurred during a non-data FIS, the FIS must be
5485 * retransmitted, and the error is non-fatal and PxIS.INFS is set. If
5486 * the error occurred during a data FIS, the transfer will stop, so
5487 * the error is fatal and PxIS.IFS is set.
5488 *
5489 * When a FIS arrives that updates the taskfile, the HBA checks to see
5490 * if PxTFD.STS.ERR is set. If yes, PxIS.TFES will be set and the HBA
5491 * stops processing any more commands.
5492 *
5493 * Command list overflow is defined as software building a command table
5494 * that has fewer total bytes than the transaction given to the device.
5495 * On device writes, the HBA will run out of data, and on reads, there
5496 * will be no room to put the data. For an overflow on data read, either
5497 * PIO or DMA, the HBA will set PxIS.OFS, and it's a non-fatal error.
5498 * For an overflow on data write, setting PxIS.OFS is optional for both
5499 * DMA and PIO, and a COMRESET is required by software to clean up from
5500 * this serious error.
5501 *
5502 * Command list underflow is defined as software building a command
5503 * table that has more total bytes than the transaction given to the
5504 * device. For data writes, both PIO and DMA, the device will detect
5505 * an error and end the transfer. And these errors are most likely going
5506 * to be fatal errors that will cause the port to be restarted. For
5507 * data reads, the HBA updates its PRD byte count, and may be
5508 * able to continue normally, but is not required to. And The HBA is
5509 * not required to detect underflow conditions for native command
5510 * queuing command.
5511 *
5512 * The HBA does not actively check incoming DMA Setup FISes to ensure
5513 * that the PxSACT register bit for that slot is set. Existing error
5514 * mechanisms, such as host bus failure, or bad protocol, are used to
5515 * recover from this case.
5516 *
5517 * In accordance with Serial ATA 1.0a, DATA FISes prior to the final
5518 * DATA FIS must be an integral number of Dwords. If the HBA receives
5519 * a request which is not an integral number of Dwords, the HBA
5520 * set PxSERR.ERR.P to '1', set PxIS.IFS to '1' and stop running until
5521 * software restarts the port. And the HBA ensures that the size
5522 * of the DATA FIS received during a PIO command matches the size in
5523 * the Transfer Cound field of the preceding PIO Setup FIS, if not, the
5524 * HBA sets PxSERR.ERR.P to '1', set PxIS.IFS to '1', and then
5525 * stop running until software restarts the port.
5526 */
5527/*
5528 * the fatal errors include PxIS.IFS, PxIS.HBDS, PxIS.HBFS and PxIS.TFES.
5529 *
5530 * PxIS.IFS indicates that the hba encountered an error on the serial ata
5531 * interface which caused the transfer to stop.
5532 *
5533 * PxIS.HBDS indicates that the hba encountered a data error
5534 * (uncorrectable ecc/parity) when reading from or writing to system memory.
5535 *
5536 * PxIS.HBFS indicates that the hba encountered a host bus error that it
5537 * cannot recover from, such as a bad software pointer.
5538 *
5539 * PxIS.TFES is set whenever the status register is updated by the device
5540 * and the error bit (bit 0) is set.
5541 */
5542static int
5543ahci_intr_fatal_error(ahci_ctl_t *ahci_ctlp,
5544    ahci_port_t *ahci_portp, uint8_t port, uint32_t intr_status)
5545{
5546	uint32_t port_cmd_status;
5547	uint32_t port_serror;
5548	uint32_t task_file_status;
5549	int failed_slot;
5550	sata_pkt_t *spkt = NULL;
5551	uint8_t err_byte;
5552	ahci_event_arg_t *args;
5553	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
5554
5555	mutex_enter(&ahci_portp->ahciport_mutex);
5556
5557	/*
5558	 * ahci_intr_phyrdy_change() may have rendered it to
5559	 * SATA_DTYPE_NONE.
5560	 */
5561	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
5562		AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
5563		    "ahci_intr_fatal_error: port %d no device attached, "
5564		    "and just return without doing anything", port);
5565		goto out0;
5566	}
5567
5568	if (intr_status & AHCI_INTR_STATUS_TFES) {
5569		task_file_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5570		    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
5571		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5572		    "ahci_intr_fatal_error: port %d "
5573		    "task_file_status = 0x%x", port, task_file_status);
5574	}
5575
5576	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
5577		/*
5578		 * Read PxCMD.CCS to determine the slot that the HBA
5579		 * was processing when the error occurred.
5580		 */
5581		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5582		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5583		failed_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
5584		    AHCI_CMD_STATUS_CCS_SHIFT;
5585
5586		spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
5587		AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
5588		    "ahci_intr_fatal_error: spkt 0x%p is being processed when "
5589		    "fatal error occurred for port %d", spkt, port);
5590
5591		if (intr_status & AHCI_INTR_STATUS_TFES) {
5592			err_byte = (task_file_status & AHCI_TFD_ERR_MASK)
5593			    >> AHCI_TFD_ERR_SHIFT;
5594
5595			/*
5596			 * Won't emit the error message if it is an IDENTIFY
5597			 * DEVICE command sent to an ATAPI device.
5598			 */
5599			if ((spkt != NULL) &&
5600			    (spkt->satapkt_cmd.satacmd_cmd_reg ==
5601			    SATAC_ID_DEVICE) &&
5602			    (err_byte == SATA_ERROR_ABORT))
5603				goto out1;
5604
5605			/*
5606			 * Won't emit the error message if it is an ATAPI PACKET
5607			 * command
5608			 */
5609			if ((spkt != NULL) &&
5610			    (spkt->satapkt_cmd.satacmd_cmd_reg == SATAC_PACKET))
5611				goto out1;
5612		}
5613	}
5614
5615	/* print the fatal error type */
5616	ahci_log_fatal_error_message(ahci_ctlp, port, intr_status);
5617	port_serror = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5618	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port));
5619
5620	/* print PxSERR related error message */
5621	ahci_log_serror_message(ahci_ctlp, port, port_serror, 0);
5622
5623	/* print task file register value */
5624	if (intr_status & AHCI_INTR_STATUS_TFES) {
5625		cmn_err(CE_WARN, "!ahci%d: ahci port %d task_file_status "
5626		    "= 0x%x", instance, port, task_file_status);
5627	}
5628
5629out1:
5630	/* Prepare the argument for the taskq */
5631	args = ahci_portp->ahciport_event_args;
5632	args->ahciea_ctlp = (void *)ahci_ctlp;
5633	args->ahciea_portp = (void *)ahci_portp;
5634	args->ahciea_event = intr_status;
5635
5636	/* Start the taskq to handle error recovery */
5637	if ((ddi_taskq_dispatch(ahci_portp->ahciport_event_taskq,
5638	    ahci_events_handler,
5639	    (void *)args, DDI_NOSLEEP)) != DDI_SUCCESS) {
5640		cmn_err(CE_WARN, "!ahci%d: ahci start taskq for event handler "
5641		    "failed", instance);
5642	}
5643out0:
5644	mutex_exit(&ahci_portp->ahciport_mutex);
5645
5646	return (AHCI_SUCCESS);
5647}
5648
5649/*
5650 * Hot Plug Operation for platforms that support Cold Presence Detect.
5651 *
5652 * When set, a device status has changed as detected by the cold presence
5653 * detect logic. This bit can either be set due to a non-connected port
5654 * receiving a device, or a connected port having its device removed.
5655 * This bit is only valid if the port supports cold presence detect as
5656 * indicated by PxCMD.CPD set to '1'.
5657 *
5658 * At the moment, this interrupt is not needed and disabled and we just
5659 * log the debug message.
5660 */
5661static int
5662ahci_intr_cold_port_detect(ahci_ctl_t *ahci_ctlp,
5663    ahci_port_t *ahci_portp, uint8_t port)
5664{
5665	uint32_t port_cmd_status;
5666	sata_device_t sdevice;
5667
5668	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5669	    "ahci_intr_cold_port_detect enter, port %d", port);
5670
5671	mutex_enter(&ahci_portp->ahciport_mutex);
5672
5673	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5674	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
5675	if (!(port_cmd_status & AHCI_CMD_STATUS_CPD)) {
5676		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5677		    "port %d does not support cold presence detect, so "
5678		    "we just ignore this interrupt", port);
5679		mutex_exit(&ahci_portp->ahciport_mutex);
5680		return (AHCI_SUCCESS);
5681	}
5682
5683	AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5684	    "port %d device status has changed", port);
5685
5686	bzero((void *)&sdevice, sizeof (sata_device_t));
5687	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
5688	sdevice.satadev_addr.qual = SATA_ADDR_CPORT;
5689	sdevice.satadev_addr.pmport = 0;
5690	sdevice.satadev_state = SATA_PSTATE_PWRON;
5691
5692	if (port_cmd_status & AHCI_CMD_STATUS_CPS) {
5693		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5694		    "port %d: a device is hot plugged", port);
5695		mutex_exit(&ahci_portp->ahciport_mutex);
5696		sata_hba_event_notify(
5697		    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5698		    &sdevice,
5699		    SATA_EVNT_DEVICE_ATTACHED);
5700		mutex_enter(&ahci_portp->ahciport_mutex);
5701
5702	} else {
5703		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5704		    "port %d: a device is hot unplugged", port);
5705		mutex_exit(&ahci_portp->ahciport_mutex);
5706		sata_hba_event_notify(
5707		    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
5708		    &sdevice,
5709		    SATA_EVNT_DEVICE_DETACHED);
5710		mutex_enter(&ahci_portp->ahciport_mutex);
5711	}
5712
5713	mutex_exit(&ahci_portp->ahciport_mutex);
5714
5715	return (AHCI_SUCCESS);
5716}
5717
5718/*
5719 * Enable the interrupts for a particular port.
5720 *
5721 * WARNING!!! ahciport_mutex should be acquired before the function
5722 * is called.
5723 */
5724static void
5725ahci_enable_port_intrs(ahci_ctl_t *ahci_ctlp, uint8_t port)
5726{
5727	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
5728	    "ahci_enable_port_intrs enter, port %d", port);
5729
5730	/*
5731	 * Clear port interrupt status before enabling interrupt
5732	 */
5733	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5734	    (uint32_t *)AHCI_PORT_PxIS(ahci_ctlp, port),
5735	    AHCI_PORT_INTR_MASK);
5736
5737	/*
5738	 * Clear the pending bit from IS.IPS
5739	 */
5740	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5741	    (uint32_t *)AHCI_GLOBAL_IS(ahci_ctlp), (1 << port));
5742
5743	/*
5744	 * Enable the following interrupts:
5745	 *	Device to Host Register FIS Interrupt (DHRS)
5746	 *	PIO Setup FIS Interrupt (PSS)
5747	 *	Set Device Bits Interrupt (SDBS)
5748	 *	Unknown FIS Interrupt (UFS)
5749	 *	Port Connect Change Status (PCS)
5750	 *	PhyRdy Change Status (PRCS)
5751	 *	Overflow Status (OFS)
5752	 *	Interface Non-fatal Error Status (INFS)
5753	 *	Interface Fatal Error Status (IFS)
5754	 *	Host Bus Data Error Status (HBDS)
5755	 *	Host Bus Fatal Error Status (HBFS)
5756	 *	Task File Error Status (TFES)
5757	 */
5758	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5759	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port),
5760	    (AHCI_INTR_STATUS_DHRS |
5761	    AHCI_INTR_STATUS_PSS |
5762	    AHCI_INTR_STATUS_SDBS |
5763	    AHCI_INTR_STATUS_UFS |
5764	    AHCI_INTR_STATUS_DPS |
5765	    AHCI_INTR_STATUS_PCS |
5766	    AHCI_INTR_STATUS_PRCS |
5767	    AHCI_INTR_STATUS_OFS |
5768	    AHCI_INTR_STATUS_INFS |
5769	    AHCI_INTR_STATUS_IFS |
5770	    AHCI_INTR_STATUS_HBDS |
5771	    AHCI_INTR_STATUS_HBFS |
5772	    AHCI_INTR_STATUS_TFES));
5773}
5774
5775/*
5776 * Enable interrupts for all the ports.
5777 *
5778 * WARNING!!! ahcictl_mutex should be acquired before the function
5779 * is called.
5780 */
5781static void
5782ahci_enable_all_intrs(ahci_ctl_t *ahci_ctlp)
5783{
5784	uint32_t ghc_control;
5785
5786	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_enable_all_intrs enter", NULL);
5787
5788	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5789	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5790
5791	ghc_control |= AHCI_HBA_GHC_IE;
5792
5793	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5794	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
5795}
5796
5797/*
5798 * Disable interrupts for a particular port.
5799 *
5800 * WARNING!!! ahciport_mutex should be acquired before the function
5801 * is called.
5802 */
5803static void
5804ahci_disable_port_intrs(ahci_ctl_t *ahci_ctlp, uint8_t port)
5805{
5806	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
5807	    "ahci_disable_port_intrs enter, port %d", port);
5808
5809	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5810	    (uint32_t *)AHCI_PORT_PxIE(ahci_ctlp, port), 0);
5811}
5812
5813/*
5814 * Disable interrupts for the whole HBA.
5815 *
5816 * The global bit is cleared, then all interrupt sources from all
5817 * ports are disabled.
5818 *
5819 * WARNING!!! ahcictl_mutex should be acquired before the function
5820 * is called.
5821 */
5822static void
5823ahci_disable_all_intrs(ahci_ctl_t *ahci_ctlp)
5824{
5825	uint32_t ghc_control;
5826
5827	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_disable_all_intrs enter",
5828	    NULL);
5829
5830	ghc_control = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
5831	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp));
5832
5833	ghc_control &= ~ AHCI_HBA_GHC_IE;
5834
5835	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
5836	    (uint32_t *)AHCI_GLOBAL_GHC(ahci_ctlp), ghc_control);
5837}
5838
5839/*
5840 * Handle FIXED or MSI interrupts.
5841 */
5842/*
5843 * According to AHCI spec, the HBA may support several interrupt modes:
5844 *	* pin based interrupts (FIXED)
5845 *	* single MSI message interrupts
5846 *	* multiple MSI based message interrupts
5847 *
5848 * For pin based interrupts, the software interrupt handler need to check IS
5849 * register to find out which port has pending interrupts. And then check
5850 * PxIS register to find out which interrupt events happened on that port.
5851 *
5852 * For single MSI message interrupts, MSICAP.MC.MSIE is set with '1', and
5853 * MSICAP.MC.MME is set with '0'. This mode is similar to pin based interrupts
5854 * in that software interrupt handler need to check IS register to determine
5855 * which port triggered the interrupts since it uses a single message for all
5856 * port interrupts.
5857 *
5858 * HBA may optionally support multiple MSI message for better performance. In
5859 * this mode, each port may have its own interrupt message, and thus generation
5860 * of interrupts is no longer controlled through the IS register. MSICAP.MC.MMC
5861 * represents a power-of-2 wrapper on the number of implemented ports, and
5862 * the mapping of ports to interrupts is done in a 1-1 relationship, up to the
5863 * maximum number of assigned interrupts. When the number of MSI messages
5864 * allocated is less than the number requested, then hardware may have two
5865 * implementation behaviors:
5866 *	* assign each ports its own interrupt and then force all additional
5867 *	  ports to share the last interrupt message, and this condition is
5868 *	  indicated by clearing GHC.MRSM to '0'
5869 *	* revert to single MSI mode, indicated by setting GHC.MRSM to '1'
5870 * When multiple-message MSI is enabled, hardware will still set IS register
5871 * as single message case. And this IS register may be used by software when
5872 * fewer than the requested number of messages is granted in order to determine
5873 * which port had the interrupt.
5874 *
5875 * Note: The current ahci driver only supports the first two interrupt modes:
5876 * pin based interrupts and single MSI message interrupts, and the reason
5877 * is indicated in below code.
5878 */
5879static int
5880ahci_add_intrs(ahci_ctl_t *ahci_ctlp, int intr_type)
5881{
5882	dev_info_t *dip = ahci_ctlp->ahcictl_dip;
5883	int		count, avail, actual;
5884	int		i, rc;
5885
5886	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INIT|AHCIDBG_INTR, ahci_ctlp,
5887	    "ahci_add_intrs enter interrupt type 0x%x", intr_type);
5888
5889	/* get number of interrupts. */
5890	rc = ddi_intr_get_nintrs(dip, intr_type, &count);
5891	if ((rc != DDI_SUCCESS) || (count == 0)) {
5892		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5893		    "ddi_intr_get_nintrs() failed, "
5894		    "rc %d count %d\n", rc, count);
5895		return (DDI_FAILURE);
5896	}
5897
5898	/* get number of available interrupts. */
5899	rc = ddi_intr_get_navail(dip, intr_type, &avail);
5900	if ((rc != DDI_SUCCESS) || (avail == 0)) {
5901		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5902		    "ddi_intr_get_navail() failed, "
5903		    "rc %d avail %d\n", rc, avail);
5904		return (DDI_FAILURE);
5905	}
5906
5907#if AHCI_DEBUG
5908	if (avail < count) {
5909		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5910		    "ddi_intr_get_nintrs returned %d, navail() returned %d",
5911		    count, avail);
5912	}
5913#endif
5914
5915	/*
5916	 * Note: So far Solaris restricts the maximum number of messages for
5917	 * x86 to 2, that is avail is 2, so here we set the count with 1 to
5918	 * force the driver to use single MSI message interrupt. In future if
5919	 * Solaris remove the restriction, then we need to delete the below
5920	 * code and try to use multiple interrupt routine to gain better
5921	 * performance.
5922	 */
5923	if ((intr_type == DDI_INTR_TYPE_MSI) && (count > 1)) {
5924		AHCIDBG(AHCIDBG_INTR, ahci_ctlp,
5925		    "force to use one interrupt routine though the "
5926		    "HBA supports %d interrupt", count);
5927		count = 1;
5928	}
5929
5930	/* Allocate an array of interrupt handles. */
5931	ahci_ctlp->ahcictl_intr_size = count * sizeof (ddi_intr_handle_t);
5932	ahci_ctlp->ahcictl_intr_htable =
5933	    kmem_alloc(ahci_ctlp->ahcictl_intr_size, KM_SLEEP);
5934
5935	/* call ddi_intr_alloc(). */
5936	rc = ddi_intr_alloc(dip, ahci_ctlp->ahcictl_intr_htable,
5937	    intr_type, 0, count, &actual, DDI_INTR_ALLOC_NORMAL);
5938
5939	if ((rc != DDI_SUCCESS) || (actual == 0)) {
5940		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5941		    "ddi_intr_alloc() failed, rc %d count %d actual %d "
5942		    "avail %d\n", rc, count, actual, avail);
5943		kmem_free(ahci_ctlp->ahcictl_intr_htable,
5944		    ahci_ctlp->ahcictl_intr_size);
5945		return (DDI_FAILURE);
5946	}
5947
5948	/* use interrupt count returned */
5949#if AHCI_DEBUG
5950	if (actual < count) {
5951		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5952		    "Requested: %d, Received: %d", count, actual);
5953	}
5954#endif
5955
5956	ahci_ctlp->ahcictl_intr_cnt = actual;
5957
5958	/*
5959	 * Get priority for first, assume remaining are all the same.
5960	 */
5961	if (ddi_intr_get_pri(ahci_ctlp->ahcictl_intr_htable[0],
5962	    &ahci_ctlp->ahcictl_intr_pri) != DDI_SUCCESS) {
5963		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5964		    "ddi_intr_get_pri() failed", NULL);
5965
5966		/* Free already allocated intr. */
5967		for (i = 0; i < actual; i++) {
5968			(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[i]);
5969		}
5970
5971		kmem_free(ahci_ctlp->ahcictl_intr_htable,
5972		    ahci_ctlp->ahcictl_intr_size);
5973		return (DDI_FAILURE);
5974	}
5975
5976	/* Test for high level interrupt. */
5977	if (ahci_ctlp->ahcictl_intr_pri >= ddi_intr_get_hilevel_pri()) {
5978		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5979		    "ahci_add_intrs: Hi level intr not supported", NULL);
5980
5981		/* Free already allocated intr. */
5982		for (i = 0; i < actual; i++) {
5983			(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[i]);
5984		}
5985
5986		kmem_free(ahci_ctlp->ahcictl_intr_htable,
5987		    sizeof (ddi_intr_handle_t));
5988
5989		return (DDI_FAILURE);
5990	}
5991
5992	/* Call ddi_intr_add_handler(). */
5993	for (i = 0; i < actual; i++) {
5994		if (ddi_intr_add_handler(ahci_ctlp->ahcictl_intr_htable[i],
5995		    ahci_intr, (caddr_t)ahci_ctlp, NULL) != DDI_SUCCESS) {
5996			AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
5997			    "ddi_intr_add_handler() failed", NULL);
5998
5999			/* Free already allocated intr. */
6000			for (i = 0; i < actual; i++) {
6001				(void) ddi_intr_free(
6002				    ahci_ctlp->ahcictl_intr_htable[i]);
6003			}
6004
6005			kmem_free(ahci_ctlp->ahcictl_intr_htable,
6006			    ahci_ctlp->ahcictl_intr_size);
6007			return (DDI_FAILURE);
6008		}
6009	}
6010
6011	if (ddi_intr_get_cap(ahci_ctlp->ahcictl_intr_htable[0],
6012	    &ahci_ctlp->ahcictl_intr_cap) != DDI_SUCCESS) {
6013		AHCIDBG(AHCIDBG_INTR|AHCIDBG_INIT, ahci_ctlp,
6014		    "ddi_intr_get_cap() failed", NULL);
6015
6016		/* Free already allocated intr. */
6017		for (i = 0; i < actual; i++) {
6018			(void) ddi_intr_free(
6019			    ahci_ctlp->ahcictl_intr_htable[i]);
6020		}
6021
6022		kmem_free(ahci_ctlp->ahcictl_intr_htable,
6023		    ahci_ctlp->ahcictl_intr_size);
6024		return (DDI_FAILURE);
6025	}
6026
6027	if (ahci_ctlp->ahcictl_intr_cap & DDI_INTR_FLAG_BLOCK) {
6028		/* Call ddi_intr_block_enable() for MSI. */
6029		(void) ddi_intr_block_enable(ahci_ctlp->ahcictl_intr_htable,
6030		    ahci_ctlp->ahcictl_intr_cnt);
6031	} else {
6032		/* Call ddi_intr_enable() for FIXED or MSI non block enable. */
6033		for (i = 0; i < ahci_ctlp->ahcictl_intr_cnt; i++) {
6034			(void) ddi_intr_enable(
6035			    ahci_ctlp->ahcictl_intr_htable[i]);
6036		}
6037	}
6038
6039	return (DDI_SUCCESS);
6040}
6041
6042/*
6043 * Removes the registered interrupts irrespective of whether they
6044 * were legacy or MSI.
6045 *
6046 * WARNING!!! The controller interrupts must be disabled before calling
6047 * this routine.
6048 */
6049static void
6050ahci_rem_intrs(ahci_ctl_t *ahci_ctlp)
6051{
6052	int x;
6053
6054	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp, "ahci_rem_intrs entered", NULL);
6055
6056	/* Disable all interrupts. */
6057	if ((ahci_ctlp->ahcictl_intr_type == DDI_INTR_TYPE_MSI) &&
6058	    (ahci_ctlp->ahcictl_intr_cap & DDI_INTR_FLAG_BLOCK)) {
6059		/* Call ddi_intr_block_disable(). */
6060		(void) ddi_intr_block_disable(ahci_ctlp->ahcictl_intr_htable,
6061		    ahci_ctlp->ahcictl_intr_cnt);
6062	} else {
6063		for (x = 0; x < ahci_ctlp->ahcictl_intr_cnt; x++) {
6064			(void) ddi_intr_disable(
6065			    ahci_ctlp->ahcictl_intr_htable[x]);
6066		}
6067	}
6068
6069	/* Call ddi_intr_remove_handler(). */
6070	for (x = 0; x < ahci_ctlp->ahcictl_intr_cnt; x++) {
6071		(void) ddi_intr_remove_handler(
6072		    ahci_ctlp->ahcictl_intr_htable[x]);
6073		(void) ddi_intr_free(ahci_ctlp->ahcictl_intr_htable[x]);
6074	}
6075
6076	kmem_free(ahci_ctlp->ahcictl_intr_htable, ahci_ctlp->ahcictl_intr_size);
6077}
6078
6079/*
6080 * This routine tries to put port into P:NotRunning state by clearing
6081 * PxCMD.ST. HBA will clear PxCI to 0h, PxSACT to 0h, PxCMD.CCS to 0h
6082 * and PxCMD.CR to '0'.
6083 *
6084 * WARNING!!! ahciport_mutex should be acquired before the function
6085 * is called.
6086 */
6087static int
6088ahci_put_port_into_notrunning_state(ahci_ctl_t *ahci_ctlp,
6089    ahci_port_t *ahci_portp, uint8_t port)
6090{
6091	uint32_t port_cmd_status;
6092	int loop_count;
6093
6094	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6095	    "ahci_put_port_into_notrunning_state enter: port %d", port);
6096
6097	port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6098	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6099
6100	port_cmd_status &= ~AHCI_CMD_STATUS_ST;
6101	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6102	    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port), port_cmd_status);
6103
6104	/* Wait until PxCMD.CR is cleared */
6105	loop_count = 0;
6106	do {
6107		port_cmd_status =
6108		    ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6109		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6110
6111		if (loop_count++ > AHCI_POLLRATE_PORT_IDLE) {
6112			AHCIDBG(AHCIDBG_INIT, ahci_ctlp,
6113			    "clearing port %d CMD.CR timeout, "
6114			    "port_cmd_status = 0x%x", port,
6115			    port_cmd_status);
6116			/*
6117			 * We are effectively timing out after 0.5 sec.
6118			 * This value is specified in AHCI spec.
6119			 */
6120			break;
6121		}
6122
6123		/* Wait for 10 millisec */
6124		drv_usecwait(10000);
6125	} while (port_cmd_status & AHCI_CMD_STATUS_CR);
6126
6127	ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_STARTED;
6128
6129	if (port_cmd_status & AHCI_CMD_STATUS_CR) {
6130		AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
6131		    "ahci_put_port_into_notrunning_state: failed to clear "
6132		    "PxCMD.CR to '0' after loop count: %d, and "
6133		    "port_cmd_status = 0x%x", loop_count, port_cmd_status);
6134		return (AHCI_FAILURE);
6135	} else {
6136		AHCIDBG(AHCIDBG_INIT|AHCIDBG_POLL_LOOP, ahci_ctlp,
6137		    "ahci_put_port_into_notrunning_state: succeeded to clear "
6138		    "PxCMD.CR to '0' after loop count: %d, and "
6139		    "port_cmd_status = 0x%x", loop_count, port_cmd_status);
6140		return (AHCI_SUCCESS);
6141	}
6142}
6143
6144/*
6145 * First clear PxCMD.ST, and then check PxTFD. If both PxTFD.STS.BSY
6146 * and PxTFD.STS.DRQ cleared to '0', it means the device is in a
6147 * stable state, then set PxCMD.ST to '1' to start the port directly.
6148 * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then issue a
6149 * COMRESET to the device to put it in an idle state.
6150 *
6151 * The fifth argument returns whether the port reset is involved during
6152 * the process.
6153 *
6154 * The routine will be called under following scenarios:
6155 *	+ To abort the packet(s)
6156 *	+ To reset the port
6157 *	+ To activate the port
6158 *	+ Fatal error recovery
6159 *	+ To abort the timeout packet(s)
6160 *
6161 * WARNING!!! ahciport_mutex should be acquired before the function
6162 * is called. And ahciport_mutex will be released before the reset
6163 * event is reported to sata module by calling sata_hba_event_notify,
6164 * and then be acquired again later.
6165 *
6166 * NOTES!!! During this procedure, PxSERR register will be cleared, and
6167 * according to the spec, the clearance of three bits will also clear
6168 * three interrupt status bits.
6169 *	1. PxSERR.DIAG.F will clear PxIS.UFS
6170 *	2. PxSERR.DIAG.X will clear PxIS.PCS
6171 *	3. PxSERR.DIAG.N will clear PxIS.PRCS
6172 *
6173 * Among these three interrupt events, the driver needs to take care of
6174 * PxIS.PRCS, which is the hot plug event. When the driver found out
6175 * a device was unplugged, it will call the interrupt handler.
6176 */
6177static int
6178ahci_restart_port_wait_till_ready(ahci_ctl_t *ahci_ctlp,
6179    ahci_port_t *ahci_portp, uint8_t port, int flag, int *reset_flag)
6180{
6181	uint32_t port_sstatus;
6182	uint32_t task_file_status;
6183	sata_device_t sdevice;
6184	int rval;
6185	int dev_exists_begin = 0;
6186	int dev_exists_end = 0;
6187
6188	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6189	    "ahci_restart_port_wait_till_ready: port %d enter", port);
6190
6191	if (ahci_portp->ahciport_device_type != SATA_DTYPE_NONE)
6192		dev_exists_begin = 1;
6193
6194	/* First clear PxCMD.ST */
6195	rval = ahci_put_port_into_notrunning_state(ahci_ctlp, ahci_portp,
6196	    port);
6197	if (rval != AHCI_SUCCESS)
6198		/*
6199		 * If PxCMD.CR does not clear within a reasonable time, it
6200		 * may assume the interface is in a hung condition and may
6201		 * continue with issuing the port reset.
6202		 */
6203		goto reset;
6204
6205	/* Then clear PxSERR */
6206	ddi_put32(ahci_ctlp->ahcictl_ahci_acc_handle,
6207	    (uint32_t *)AHCI_PORT_PxSERR(ahci_ctlp, port),
6208	    AHCI_SERROR_CLEAR_ALL);
6209
6210	/* Then get PxTFD */
6211	task_file_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6212	    (uint32_t *)AHCI_PORT_PxTFD(ahci_ctlp, port));
6213
6214	/*
6215	 * Check whether the device is in a stable status, if yes,
6216	 * then start the port directly. However for ahci_tran_dport_reset,
6217	 * we may have to perform a port reset.
6218	 */
6219	if (!(task_file_status & (AHCI_TFD_STS_BSY | AHCI_TFD_STS_DRQ)) &&
6220	    !(flag & AHCI_PORT_RESET))
6221		goto out;
6222
6223reset:
6224	/*
6225	 * If PxTFD.STS.BSY or PxTFD.STS.DRQ is set to '1', then issue
6226	 * a COMRESET to the device
6227	 */
6228	rval = ahci_port_reset(ahci_ctlp, ahci_portp, port);
6229
6230	if (reset_flag != NULL)
6231		*reset_flag = 1;
6232
6233	/* Indicate to the framework that a reset has happened. */
6234	if ((ahci_portp->ahciport_device_type != SATA_DTYPE_NONE) &&
6235	    !(flag & AHCI_RESET_NO_EVENTS_UP)) {
6236		/* Set the reset in progress flag */
6237		ahci_portp->ahciport_reset_in_progress = 1;
6238
6239		bzero((void *)&sdevice, sizeof (sata_device_t));
6240		sdevice.satadev_addr.cport =
6241		    ahci_ctlp->ahcictl_port_to_cport[port];
6242		sdevice.satadev_addr.pmport = 0;
6243		sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
6244
6245		sdevice.satadev_state = SATA_DSTATE_RESET |
6246		    SATA_DSTATE_PWR_ACTIVE;
6247		if (ahci_ctlp->ahcictl_sata_hba_tran) {
6248			mutex_exit(&ahci_portp->ahciport_mutex);
6249			sata_hba_event_notify(
6250			    ahci_ctlp->ahcictl_sata_hba_tran->sata_tran_hba_dip,
6251			    &sdevice,
6252			    SATA_EVNT_DEVICE_RESET);
6253			mutex_enter(&ahci_portp->ahciport_mutex);
6254		}
6255
6256		AHCIDBG(AHCIDBG_EVENT, ahci_ctlp,
6257		    "port %d sending event up: SATA_EVNT_RESET", port);
6258	} else {
6259		ahci_portp->ahciport_reset_in_progress = 0;
6260	}
6261
6262out:
6263	(void) ahci_start_port(ahci_ctlp, ahci_portp, port);
6264
6265	/* SStatus tells the presence of device. */
6266	port_sstatus = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6267	    (uint32_t *)AHCI_PORT_PxSSTS(ahci_ctlp, port));
6268
6269	if (SSTATUS_GET_DET(port_sstatus) == SSTATUS_DET_DEVPRE_PHYCOM) {
6270		dev_exists_end = 1;
6271		ASSERT(ahci_portp->ahciport_device_type != SATA_DTYPE_NONE);
6272	}
6273
6274	/* Check whether a hot plug event happened */
6275	if (dev_exists_begin == 1 && dev_exists_end == 0) {
6276		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6277		    "ahci_restart_port_wait_till_ready: port %d "
6278		    "device is removed", port);
6279		ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_NODEV;
6280		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6281		    "ahci_restart_port_wait_till_ready: port %d "
6282		    "AHCI_PORT_FLAG_NODEV flag is set", port);
6283		mutex_exit(&ahci_portp->ahciport_mutex);
6284		(void) ahci_intr_phyrdy_change(ahci_ctlp, ahci_portp, port);
6285		mutex_enter(&ahci_portp->ahciport_mutex);
6286	}
6287
6288	return (rval);
6289}
6290
6291/*
6292 * This routine may be called under four scenarios:
6293 *	a) do the recovery from fatal error
6294 *	b) or we need to timeout some commands
6295 *	c) or we need to abort some commands
6296 *	d) or we need reset device/port/controller
6297 *
6298 * In all these scenarios, we need to send any pending unfinished
6299 * commands up to sata framework.
6300 *
6301 * WARNING!!! ahciport_mutex should be acquired before the function is called.
6302 */
6303static void
6304ahci_mop_commands(ahci_ctl_t *ahci_ctlp,
6305    ahci_port_t *ahci_portp,
6306    uint32_t slot_status,
6307    uint32_t failed_tags,
6308    uint32_t timeout_tags,
6309    uint32_t aborted_tags,
6310    uint32_t reset_tags)
6311{
6312	uint32_t finished_tags = 0;
6313	uint32_t unfinished_tags = 0;
6314	int tmp_slot;
6315	sata_pkt_t *satapkt;
6316	int ncq_cmd_in_progress = 0;
6317	int err_retri_cmd_in_progress = 0;
6318
6319	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
6320	    "ahci_mop_commands entered: port: %d slot_status: 0x%x",
6321	    ahci_portp->ahciport_port_num, slot_status);
6322
6323	AHCIDBG(AHCIDBG_ERRS|AHCIDBG_ENTRY, ahci_ctlp,
6324	    "ahci_mop_commands: failed_tags: 0x%x, "
6325	    "timeout_tags: 0x%x aborted_tags: 0x%x, "
6326	    "reset_tags: 0x%x", failed_tags,
6327	    timeout_tags, aborted_tags, reset_tags);
6328
6329	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6330		finished_tags = ahci_portp->ahciport_pending_tags &
6331		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
6332
6333		unfinished_tags = slot_status &
6334		    AHCI_SLOT_MASK(ahci_ctlp) &
6335		    ~failed_tags &
6336		    ~aborted_tags &
6337		    ~reset_tags &
6338		    ~timeout_tags;
6339	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6340		ncq_cmd_in_progress = 1;
6341		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
6342		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
6343
6344		unfinished_tags = slot_status &
6345		    AHCI_NCQ_SLOT_MASK(ahci_portp) &
6346		    ~failed_tags &
6347		    ~aborted_tags &
6348		    ~reset_tags &
6349		    ~timeout_tags;
6350	} else if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6351
6352		/*
6353		 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT is
6354		 * set, it means REQUEST SENSE or READ LOG EXT command doesn't
6355		 * complete successfully due to one of the following three
6356		 * conditions:
6357		 *
6358		 *	1. Fatal error - failed_tags includes its slot
6359		 *	2. Timed out - timeout_tags includes its slot
6360		 *	3. Aborted when hot unplug - aborted_tags includes its
6361		 *	   slot
6362		 *
6363		 * Please note that the command is always sent down in Slot 0
6364		 */
6365		err_retri_cmd_in_progress = 1;
6366		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_NCQ, ahci_ctlp,
6367		    "ahci_mop_commands is called for port %d while "
6368		    "REQUEST SENSE or READ LOG EXT for error retrieval "
6369		    "is being executed slot_status = 0x%x",
6370		    ahci_portp->ahciport_port_num, slot_status);
6371		ASSERT(ahci_portp->ahciport_mop_in_progress > 1);
6372		ASSERT(slot_status == 0x1);
6373	}
6374
6375	/* Send up finished packets with SATA_PKT_COMPLETED */
6376	while (finished_tags) {
6377		tmp_slot = ddi_ffs(finished_tags) - 1;
6378		if (tmp_slot == -1) {
6379			break;
6380		}
6381
6382		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6383		ASSERT(satapkt != NULL);
6384
6385		AHCIDBG(AHCIDBG_INFO, ahci_ctlp, "ahci_mop_commands: "
6386		    "sending up pkt 0x%p with SATA_PKT_COMPLETED",
6387		    (void *)satapkt);
6388
6389		/*
6390		 * Cannot fetch the return register content since the port
6391		 * was restarted, so the corresponding tag will be set to
6392		 * aborted tags.
6393		 */
6394		if (satapkt->satapkt_cmd.satacmd_flags.sata_special_regs) {
6395			CLEAR_BIT(finished_tags, tmp_slot);
6396			aborted_tags |= tmp_slot;
6397			continue;
6398		}
6399
6400		if (ncq_cmd_in_progress)
6401			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6402			    tmp_slot);
6403		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6404		CLEAR_BIT(finished_tags, tmp_slot);
6405		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6406
6407		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_COMPLETED);
6408	}
6409
6410	/* Send up failed packets with SATA_PKT_DEV_ERROR. */
6411	while (failed_tags) {
6412		if (err_retri_cmd_in_progress) {
6413			satapkt = ahci_portp->ahciport_err_retri_pkt;
6414			ASSERT(satapkt != NULL);
6415			ASSERT(failed_tags == 0x1);
6416
6417			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6418			    "sending up pkt 0x%p with SATA_PKT_DEV_ERROR",
6419			    (void *)satapkt);
6420			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
6421			break;
6422		}
6423
6424		tmp_slot = ddi_ffs(failed_tags) - 1;
6425		if (tmp_slot == -1) {
6426			break;
6427		}
6428
6429		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6430		ASSERT(satapkt != NULL);
6431
6432		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6433		    "sending up pkt 0x%p with SATA_PKT_DEV_ERROR",
6434		    (void *)satapkt);
6435
6436		if (ncq_cmd_in_progress)
6437			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6438			    tmp_slot);
6439		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6440		CLEAR_BIT(failed_tags, tmp_slot);
6441		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6442
6443		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_DEV_ERROR);
6444	}
6445
6446	/* Send up timeout packets with SATA_PKT_TIMEOUT. */
6447	while (timeout_tags) {
6448		if (err_retri_cmd_in_progress) {
6449			satapkt = ahci_portp->ahciport_err_retri_pkt;
6450			ASSERT(satapkt != NULL);
6451			ASSERT(timeout_tags == 0x1);
6452
6453			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6454			    "sending up pkt 0x%p with SATA_PKT_TIMEOUT",
6455			    (void *)satapkt);
6456			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
6457			break;
6458		}
6459
6460		tmp_slot = ddi_ffs(timeout_tags) - 1;
6461		if (tmp_slot == -1) {
6462			break;
6463		}
6464
6465		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6466		ASSERT(satapkt != NULL);
6467
6468		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6469		    "sending up pkt 0x%p with SATA_PKT_TIMEOUT",
6470		    (void *)satapkt);
6471
6472		if (ncq_cmd_in_progress)
6473			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6474			    tmp_slot);
6475		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6476		CLEAR_BIT(timeout_tags, tmp_slot);
6477		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6478
6479		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_TIMEOUT);
6480	}
6481
6482	/* Send up aborted packets with SATA_PKT_ABORTED */
6483	while (aborted_tags) {
6484		if (err_retri_cmd_in_progress) {
6485			satapkt = ahci_portp->ahciport_err_retri_pkt;
6486			ASSERT(satapkt != NULL);
6487			ASSERT(aborted_tags == 0x1);
6488
6489			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6490			    "sending up pkt 0x%p with SATA_PKT_ABORTED",
6491			    (void *)satapkt);
6492			SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
6493			break;
6494		}
6495
6496		tmp_slot = ddi_ffs(aborted_tags) - 1;
6497		if (tmp_slot == -1) {
6498			break;
6499		}
6500
6501		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6502		ASSERT(satapkt != NULL);
6503
6504		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6505		    "sending up pkt 0x%p with SATA_PKT_ABORTED",
6506		    (void *)satapkt);
6507
6508		if (ncq_cmd_in_progress)
6509			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6510			    tmp_slot);
6511		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6512		CLEAR_BIT(aborted_tags, tmp_slot);
6513		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6514
6515		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_ABORTED);
6516	}
6517
6518	/* Send up reset packets with SATA_PKT_RESET. */
6519	while (reset_tags) {
6520		tmp_slot = ddi_ffs(reset_tags) - 1;
6521		if (tmp_slot == -1) {
6522			break;
6523		}
6524
6525		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6526		ASSERT(satapkt != NULL);
6527
6528		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6529		    "sending up pkt 0x%p with SATA_PKT_RESET",
6530		    (void *)satapkt);
6531
6532		if (ncq_cmd_in_progress)
6533			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6534			    tmp_slot);
6535		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6536		CLEAR_BIT(reset_tags, tmp_slot);
6537		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6538
6539		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
6540	}
6541
6542	/* Send up unfinished packets with SATA_PKT_RESET */
6543	while (unfinished_tags) {
6544		tmp_slot = ddi_ffs(unfinished_tags) - 1;
6545		if (tmp_slot == -1) {
6546			break;
6547		}
6548
6549		satapkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
6550		ASSERT(satapkt != NULL);
6551
6552		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, "ahci_mop_commands: "
6553		    "sending up pkt 0x%p with SATA_PKT_RESET",
6554		    (void *)satapkt);
6555
6556		if (ncq_cmd_in_progress)
6557			CLEAR_BIT(ahci_portp->ahciport_pending_ncq_tags,
6558			    tmp_slot);
6559		CLEAR_BIT(ahci_portp->ahciport_pending_tags, tmp_slot);
6560		CLEAR_BIT(unfinished_tags, tmp_slot);
6561		ahci_portp->ahciport_slot_pkts[tmp_slot] = NULL;
6562
6563		SENDUP_PACKET(ahci_portp, satapkt, SATA_PKT_RESET);
6564	}
6565
6566	ahci_portp->ahciport_mop_in_progress--;
6567	ASSERT(ahci_portp->ahciport_mop_in_progress >= 0);
6568
6569	if (ahci_portp->ahciport_mop_in_progress == 0)
6570		ahci_portp->ahciport_flags &= ~AHCI_PORT_FLAG_MOPPING;
6571}
6572
6573/*
6574 * This routine is going to first request a READ LOG EXT sata pkt from sata
6575 * module, and then deliver it to the HBA to get the ncq failure context.
6576 * The return value is the exactly failed tags.
6577 */
6578static uint32_t
6579ahci_get_rdlogext_data(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
6580    uint8_t port)
6581{
6582	sata_device_t	sdevice;
6583	sata_pkt_t	*rdlog_spkt, *spkt;
6584	ddi_dma_handle_t buf_dma_handle;
6585	int		loop_count;
6586	int		rval;
6587	int		failed_slot;
6588	uint32_t	failed_tags = 0;
6589	struct sata_ncq_error_recovery_page *ncq_err_page;
6590
6591	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_NCQ, ahci_ctlp,
6592	    "ahci_get_rdlogext_data enter: port %d", port);
6593
6594	/* Prepare the sdevice data */
6595	bzero((void *)&sdevice, sizeof (sata_device_t));
6596	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
6597
6598	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
6599	sdevice.satadev_addr.pmport = 0;
6600
6601	/*
6602	 * Call the sata hba interface to get a rdlog spkt
6603	 */
6604	loop_count = 0;
6605loop:
6606	rdlog_spkt = sata_get_error_retrieval_pkt(ahci_ctlp->ahcictl_dip,
6607	    &sdevice, SATA_ERR_RETR_PKT_TYPE_NCQ);
6608	if (rdlog_spkt == NULL) {
6609		if (loop_count++ < AHCI_POLLRATE_GET_SPKT) {
6610			/* Sleep for a while */
6611			delay(AHCI_10MS_TICKS);
6612			goto loop;
6613		}
6614		/* Timed out after 1s */
6615		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6616		    "failed to get rdlog spkt for port %d", port);
6617		return (failed_tags);
6618	}
6619
6620	ASSERT(rdlog_spkt->satapkt_op_mode & SATA_OPMODE_SYNCH);
6621
6622	/*
6623	 * This flag is used to handle the specific error recovery when the
6624	 * READ LOG EXT command gets a failure (fatal error or time-out).
6625	 */
6626	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RDLOGEXT;
6627
6628	/*
6629	 * This start is not supposed to fail because after port is restarted,
6630	 * the whole command list is empty.
6631	 */
6632	ahci_portp->ahciport_err_retri_pkt = rdlog_spkt;
6633	(void) ahci_do_sync_start(ahci_ctlp, ahci_portp, port, rdlog_spkt);
6634	ahci_portp->ahciport_err_retri_pkt = NULL;
6635
6636	/* Remove the flag after READ LOG EXT command is completed */
6637	ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_RDLOGEXT;
6638
6639	if (rdlog_spkt->satapkt_reason == SATA_PKT_COMPLETED) {
6640		/* Update the request log data */
6641		buf_dma_handle = *(ddi_dma_handle_t *)
6642		    (rdlog_spkt->satapkt_cmd.satacmd_err_ret_buf_handle);
6643		rval = ddi_dma_sync(buf_dma_handle, 0, 0,
6644		    DDI_DMA_SYNC_FORKERNEL);
6645		if (rval == DDI_SUCCESS) {
6646			ncq_err_page =
6647			    (struct sata_ncq_error_recovery_page *)rdlog_spkt->
6648			    satapkt_cmd.satacmd_bp->b_un.b_addr;
6649
6650			/* Get the failed tag */
6651			failed_slot = ncq_err_page->ncq_tag;
6652			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6653			    "ahci_get_rdlogext_data: port %d "
6654			    "failed slot %d", port, failed_slot);
6655			if (failed_slot & NQ) {
6656				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6657				    "the failed slot is not a valid tag", NULL);
6658				goto out;
6659			}
6660
6661			failed_slot &= NCQ_TAG_MASK;
6662			spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
6663			AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6664			    "ahci_get_rdlogext_data: failed spkt 0x%p",
6665			    (void *)spkt);
6666			if (spkt == NULL) {
6667				AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6668				    "the failed slot spkt is NULL", NULL);
6669				goto out;
6670			}
6671
6672			failed_tags = 0x1 << failed_slot;
6673
6674			/* Fill out the error context */
6675			ahci_copy_ncq_err_page(&spkt->satapkt_cmd,
6676			    ncq_err_page);
6677			ahci_update_sata_registers(ahci_ctlp, port,
6678			    &spkt->satapkt_device);
6679		}
6680	}
6681out:
6682	sata_free_error_retrieval_pkt(rdlog_spkt);
6683
6684	return (failed_tags);
6685}
6686
6687/*
6688 * This routine is going to first request a REQUEST SENSE sata pkt from sata
6689 * module, and then deliver it to the HBA to get the sense data and copy
6690 * the sense data back to the orignal failed sata pkt, and free the REQUEST
6691 * SENSE sata pkt later.
6692 */
6693static void
6694ahci_get_rqsense_data(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
6695    uint8_t port, sata_pkt_t *spkt)
6696{
6697	sata_device_t	sdevice;
6698	sata_pkt_t	*rs_spkt;
6699	sata_cmd_t	*sata_cmd;
6700	ddi_dma_handle_t buf_dma_handle;
6701	int		loop_count;
6702#if AHCI_DEBUG
6703	struct scsi_extended_sense *rqsense;
6704#endif
6705
6706	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6707	    "ahci_get_rqsense_data enter: port %d", port);
6708
6709	/* Prepare the sdevice data */
6710	bzero((void *)&sdevice, sizeof (sata_device_t));
6711	sdevice.satadev_addr.cport = ahci_ctlp->ahcictl_port_to_cport[port];
6712
6713	sdevice.satadev_addr.qual = SATA_ADDR_DCPORT;
6714	sdevice.satadev_addr.pmport = 0;
6715
6716	sata_cmd = &spkt->satapkt_cmd;
6717
6718	/*
6719	 * Call the sata hba interface to get a rs spkt
6720	 */
6721	loop_count = 0;
6722loop:
6723	rs_spkt = sata_get_error_retrieval_pkt(ahci_ctlp->ahcictl_dip,
6724	    &sdevice, SATA_ERR_RETR_PKT_TYPE_ATAPI);
6725	if (rs_spkt == NULL) {
6726		if (loop_count++ < AHCI_POLLRATE_GET_SPKT) {
6727			/* Sleep for a while */
6728			delay(AHCI_10MS_TICKS);
6729			goto loop;
6730
6731		}
6732		/* Timed out after 1s */
6733		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6734		    "failed to get rs spkt for port %d", port);
6735		return;
6736	}
6737
6738	ASSERT(rs_spkt->satapkt_op_mode & SATA_OPMODE_SYNCH);
6739
6740	/*
6741	 * This flag is used to handle the specific error recovery when the
6742	 * REQUEST SENSE command gets a faiure (fatal error or time-out).
6743	 */
6744	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_RQSENSE;
6745
6746	/*
6747	 * This start is not supposed to fail because after port is restarted,
6748	 * the whole command list is empty.
6749	 */
6750	ahci_portp->ahciport_err_retri_pkt = rs_spkt;
6751	(void) ahci_do_sync_start(ahci_ctlp, ahci_portp, port, rs_spkt);
6752	ahci_portp->ahciport_err_retri_pkt = NULL;
6753
6754	/* Remove the flag after REQUEST SENSE command is completed */
6755	ahci_portp->ahciport_flags &= ~ AHCI_PORT_FLAG_RQSENSE;
6756
6757	if (rs_spkt->satapkt_reason == SATA_PKT_COMPLETED) {
6758		/* Update the request sense data */
6759		buf_dma_handle = *(ddi_dma_handle_t *)
6760		    (rs_spkt->satapkt_cmd.satacmd_err_ret_buf_handle);
6761		(void) ddi_dma_sync(buf_dma_handle, 0, 0,
6762		    DDI_DMA_SYNC_FORKERNEL);
6763		/* Copy the request sense data */
6764		bcopy(rs_spkt->
6765		    satapkt_cmd.satacmd_bp->b_un.b_addr,
6766		    &sata_cmd->satacmd_rqsense,
6767		    SATA_ATAPI_MIN_RQSENSE_LEN);
6768#if AHCI_DEBUG
6769		rqsense = (struct scsi_extended_sense *)
6770		    sata_cmd->satacmd_rqsense;
6771
6772		/* Dump the sense data */
6773		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp, "\n", NULL);
6774		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp,
6775		    "Sense data for satapkt %p ATAPI cmd 0x%x",
6776		    spkt, sata_cmd->satacmd_acdb[0]);
6777		AHCIDBG(AHCIDBG_SENSEDATA, ahci_ctlp,
6778		    "  es_code 0x%x es_class 0x%x "
6779		    "es_key 0x%x es_add_code 0x%x "
6780		    "es_qual_code 0x%x",
6781		    rqsense->es_code, rqsense->es_class,
6782		    rqsense->es_key, rqsense->es_add_code,
6783		    rqsense->es_qual_code);
6784#endif
6785	}
6786
6787	sata_free_error_retrieval_pkt(rs_spkt);
6788}
6789
6790/*
6791 * Fatal errors will cause the HBA to enter the ERR: Fatal state. To recover,
6792 * the port must be restarted. When the HBA detects thus error, it may try
6793 * to abort a transfer. And if the transfer was aborted, the device is
6794 * expected to send a D2H Register FIS with PxTFD.STS.ERR set to '1' and both
6795 * PxTFD.STS.BSY and PxTFD.STS.DRQ cleared to '0'. Then system software knows
6796 * that the device is in a stable status and transfers may be restarted without
6797 * issuing a COMRESET to the device. If PxTFD.STS.BSY or PxTFD.STS.DRQ is set,
6798 * then the software will send the COMRESET to do the port reset.
6799 *
6800 * Software should perform the appropriate error recovery actions based on
6801 * whether non-queued commands were being issued or natived command queuing
6802 * commands were being issued.
6803 *
6804 * And software will complete the command that had the error with error mark
6805 * to higher level software.
6806 *
6807 * Fatal errors include the following:
6808 *	PxIS.IFS - Interface Fatal Error Status
6809 *	PxIS.HBDS - Host Bus Data Error Status
6810 *	PxIS.HBFS - Host Bus Fatal Error Status
6811 *	PxIS.TFES - Task File Error Status
6812 *
6813 * WARNING!!! ahciport_mutex should be acquired before the function is called.
6814 */
6815static void
6816ahci_fatal_error_recovery_handler(ahci_ctl_t *ahci_ctlp,
6817    ahci_port_t *ahci_portp, uint8_t port, uint32_t intr_status)
6818{
6819	uint32_t	port_cmd_status;
6820	uint32_t	slot_status = 0;
6821	uint32_t	failed_tags = 0;
6822	int		failed_slot;
6823	int		reset_flag = 0;
6824	ahci_fis_d2h_register_t	*ahci_rcvd_fisp;
6825	sata_cmd_t	*sata_cmd = NULL;
6826	sata_pkt_t	*spkt = NULL;
6827#if AHCI_DEBUG
6828	ahci_cmd_header_t *cmd_header;
6829#endif
6830
6831	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
6832	    "ahci_fatal_error_recovery_handler enter: port %d", port);
6833
6834	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
6835	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6836
6837		/* Read PxCI to see which commands are still outstanding */
6838		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6839		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
6840
6841		/*
6842		 * Read PxCMD.CCS to determine the slot that the HBA
6843		 * was processing when the error occurred.
6844		 */
6845		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6846		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
6847		failed_slot = (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
6848		    AHCI_CMD_STATUS_CCS_SHIFT;
6849
6850		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6851			spkt = ahci_portp->ahciport_err_retri_pkt;
6852			ASSERT(spkt != NULL);
6853		} else {
6854			spkt = ahci_portp->ahciport_slot_pkts[failed_slot];
6855			if (spkt == NULL) {
6856				/* May happen when interface errors occur? */
6857				goto next;
6858			}
6859		}
6860
6861#if AHCI_DEBUG
6862		/*
6863		 * Debugging purpose...
6864		 */
6865		if (ahci_portp->ahciport_prd_bytecounts[failed_slot]) {
6866			cmd_header =
6867			    &ahci_portp->ahciport_cmd_list[failed_slot];
6868			AHCIDBG(AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
6869			    "ahci_fatal_error_recovery_handler: port %d, "
6870			    "PRD Byte Count = 0x%x, "
6871			    "ahciport_prd_bytecounts = 0x%x", port,
6872			    cmd_header->ahcich_prd_byte_count,
6873			    ahci_portp->ahciport_prd_bytecounts[failed_slot]);
6874		}
6875#endif
6876
6877		sata_cmd = &spkt->satapkt_cmd;
6878
6879		/* Fill out the status and error registers for PxIS.TFES */
6880		if (intr_status & AHCI_INTR_STATUS_TFES) {
6881			ahci_rcvd_fisp = &(ahci_portp->ahciport_rcvd_fis->
6882			    ahcirf_d2h_register_fis);
6883
6884			/* Copy the error context back to the sata_cmd */
6885			ahci_copy_err_cnxt(sata_cmd, ahci_rcvd_fisp);
6886		}
6887
6888		/* The failed command must be one of the outstanding commands */
6889		failed_tags = 0x1 << failed_slot;
6890		ASSERT(failed_tags & slot_status);
6891
6892		/* Update the sata registers, especially PxSERR register */
6893		ahci_update_sata_registers(ahci_ctlp, port,
6894		    &spkt->satapkt_device);
6895
6896	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6897		/* Read PxSACT to see which commands are still outstanding */
6898		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
6899		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
6900	}
6901next:
6902
6903#if AHCI_DEBUG
6904	/*
6905	 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT flag is
6906	 * set, it means a fatal error happened after REQUEST SENSE command
6907	 * or READ LOG EXT command is delivered to the HBA during the error
6908	 * recovery process. At this time, the only outstanding command is
6909	 * supposed to be REQUEST SENSE command or READ LOG EXT command.
6910	 */
6911	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
6912		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6913		    "ahci_fatal_error_recovery_handler: port %d REQUEST SENSE "
6914		    "command or READ LOG EXT command for error data retrieval "
6915		    "failed", port);
6916		ASSERT(slot_status == 0x1);
6917		ASSERT(failed_slot == 0);
6918		ASSERT(spkt->satapkt_cmd.satacmd_acdb[0] ==
6919		    SCMD_REQUEST_SENSE ||
6920		    spkt->satapkt_cmd.satacmd_cmd_reg ==
6921		    SATAC_READ_LOG_EXT);
6922	}
6923#endif
6924
6925	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
6926	ahci_portp->ahciport_mop_in_progress++;
6927
6928	(void) ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
6929	    port, NULL, &reset_flag);
6930
6931	/*
6932	 * Won't retrieve error information:
6933	 * 1. Port reset was involved to recover
6934	 * 2. Device is gone
6935	 * 3. IDENTIFY DEVICE command sent to ATAPI device
6936	 * 4. REQUEST SENSE or READ LOG EXT command during error recovery
6937	 */
6938	if (reset_flag ||
6939	    ahci_portp->ahciport_device_type == SATA_DTYPE_NONE ||
6940	    spkt && spkt->satapkt_cmd.satacmd_cmd_reg == SATAC_ID_DEVICE ||
6941	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
6942		goto out;
6943
6944	/*
6945	 * Deliver READ LOG EXT to gather information about the error when
6946	 * a COMRESET has not been performed as part of the error recovery
6947	 * during NCQ command processing.
6948	 */
6949	if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
6950		failed_tags = ahci_get_rdlogext_data(ahci_ctlp,
6951		    ahci_portp, port);
6952		goto out;
6953	}
6954
6955	/*
6956	 * Deliver REQUEST SENSE for ATAPI command to gather information about
6957	 * the error when a COMRESET has not been performed as part of the
6958	 * error recovery.
6959	 */
6960	if (spkt && ahci_portp->ahciport_device_type == SATA_DTYPE_ATAPI)
6961		ahci_get_rqsense_data(ahci_ctlp, ahci_portp, port, spkt);
6962out:
6963	AHCIDBG(AHCIDBG_ERRS, ahci_ctlp,
6964	    "ahci_fatal_error_recovery_handler: port %d fatal error "
6965	    "occurred slot_status = 0x%x, pending_tags = 0x%x, "
6966	    "pending_ncq_tags = 0x%x failed_tags = 0x%x",
6967	    port, slot_status, ahci_portp->ahciport_pending_tags,
6968	    ahci_portp->ahciport_pending_ncq_tags, failed_tags);
6969
6970	ahci_mop_commands(ahci_ctlp,
6971	    ahci_portp,
6972	    slot_status,
6973	    failed_tags, /* failed tags */
6974	    0, /* timeout tags */
6975	    0, /* aborted tags */
6976	    0); /* reset tags */
6977}
6978
6979/*
6980 * Handle events - fatal error recovery
6981 */
6982static void
6983ahci_events_handler(void *args)
6984{
6985	ahci_event_arg_t *ahci_event_arg;
6986	ahci_ctl_t *ahci_ctlp;
6987	ahci_port_t *ahci_portp;
6988	uint32_t event;
6989	uint8_t port;
6990
6991	ahci_event_arg = (ahci_event_arg_t *)args;
6992
6993	ahci_ctlp = ahci_event_arg->ahciea_ctlp;
6994	ahci_portp = ahci_event_arg->ahciea_portp;
6995	event = ahci_event_arg->ahciea_event;
6996	port = ahci_portp->ahciport_port_num;
6997
6998	AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR|AHCIDBG_ERRS, ahci_ctlp,
6999	    "ahci_events_handler enter: port %d intr_status = 0x%x",
7000	    port, event);
7001
7002	mutex_enter(&ahci_portp->ahciport_mutex);
7003
7004	/*
7005	 * ahci_intr_phyrdy_change() may have rendered it to
7006	 * SATA_DTYPE_NONE.
7007	 */
7008	if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
7009		AHCIDBG(AHCIDBG_ENTRY|AHCIDBG_INTR, ahci_ctlp,
7010		    "ahci_events_handler: port %d no device attached, "
7011		    "and just return without doing anything", port);
7012		goto out;
7013	}
7014
7015	if (event & (AHCI_INTR_STATUS_IFS |
7016	    AHCI_INTR_STATUS_HBDS |
7017	    AHCI_INTR_STATUS_HBFS |
7018	    AHCI_INTR_STATUS_TFES))
7019		ahci_fatal_error_recovery_handler(ahci_ctlp, ahci_portp,
7020		    port, event);
7021
7022out:
7023	mutex_exit(&ahci_portp->ahciport_mutex);
7024}
7025
7026/*
7027 * ahci_watchdog_handler() and ahci_do_sync_start will call us if they
7028 * detect there are some commands which are timed out.
7029 */
7030static void
7031ahci_timeout_pkts(ahci_ctl_t *ahci_ctlp, ahci_port_t *ahci_portp,
7032    uint8_t port, uint32_t tmp_timeout_tags)
7033{
7034	uint32_t slot_status = 0;
7035	uint32_t finished_tags = 0;
7036	uint32_t timeout_tags = 0;
7037
7038	AHCIDBG(AHCIDBG_TIMEOUT|AHCIDBG_ENTRY, ahci_ctlp,
7039	    "ahci_timeout_pkts enter: port %d", port);
7040
7041	mutex_enter(&ahci_portp->ahciport_mutex);
7042
7043	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) ||
7044	    ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7045		/* Read PxCI to see which commands are still outstanding */
7046		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7047		    (uint32_t *)AHCI_PORT_PxCI(ahci_ctlp, port));
7048	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7049		/* Read PxSACT to see which commands are still outstanding */
7050		slot_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7051		    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
7052	}
7053
7054#if AHCI_DEBUG
7055	/*
7056	 * When AHCI_PORT_FLAG_RQSENSE or AHCI_PORT_FLAG_RDLOGEXT flag is
7057	 * set, it means a fatal error happened after REQUEST SENSE command
7058	 * or READ LOG EXT command is delivered to the HBA during the error
7059	 * recovery process. At this time, the only outstanding command is
7060	 * supposed to be REQUEST SENSE command or READ LOG EXT command.
7061	 */
7062	if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7063		AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT, ahci_ctlp,
7064		    "ahci_timeout_pkts called while REQUEST SENSE "
7065		    "command or READ LOG EXT command for error recovery "
7066		    "timed out timeout_tags = 0x%x, slot_status = 0x%x, "
7067		    "pending_tags = 0x%x, pending_ncq_tags = 0x%x",
7068		    tmp_timeout_tags, slot_status,
7069		    ahci_portp->ahciport_pending_tags,
7070		    ahci_portp->ahciport_pending_ncq_tags);
7071		ASSERT(slot_status == 0x1);
7072	}
7073#endif
7074
7075	ahci_portp->ahciport_flags |= AHCI_PORT_FLAG_MOPPING;
7076	ahci_portp->ahciport_mop_in_progress++;
7077
7078	(void) ahci_restart_port_wait_till_ready(ahci_ctlp, ahci_portp,
7079	    port, NULL, NULL);
7080
7081	/*
7082	 * Re-identify timeout tags because some previously checked commands
7083	 * could already complete.
7084	 */
7085	if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7086		finished_tags = ahci_portp->ahciport_pending_tags &
7087		    ~slot_status & AHCI_SLOT_MASK(ahci_ctlp);
7088		timeout_tags = tmp_timeout_tags & ~finished_tags;
7089
7090		AHCIDBG(AHCIDBG_TIMEOUT, ahci_ctlp,
7091		    "ahci_timeout_pkts: port %d, finished_tags = 0x%x, "
7092		    "timeout_tags = 0x%x, port_cmd_issue = 0x%x, "
7093		    "pending_tags = 0x%x ",
7094		    port, finished_tags, timeout_tags,
7095		    slot_status, ahci_portp->ahciport_pending_tags);
7096	} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7097		finished_tags = ahci_portp->ahciport_pending_ncq_tags &
7098		    ~slot_status & AHCI_NCQ_SLOT_MASK(ahci_portp);
7099		timeout_tags = tmp_timeout_tags & ~finished_tags;
7100
7101		AHCIDBG(AHCIDBG_TIMEOUT|AHCIDBG_NCQ, ahci_ctlp,
7102		    "ahci_timeout_pkts: port %d, finished_tags = 0x%x, "
7103		    "timeout_tags = 0x%x, port_sactive = 0x%x, "
7104		    "pending_ncq_tags = 0x%x ",
7105		    port, finished_tags, timeout_tags,
7106		    slot_status, ahci_portp->ahciport_pending_ncq_tags);
7107	} else if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7108		timeout_tags = tmp_timeout_tags;
7109	}
7110
7111	ahci_mop_commands(ahci_ctlp,
7112	    ahci_portp,
7113	    slot_status,
7114	    0, /* failed tags */
7115	    timeout_tags, /* timeout tags */
7116	    0, /* aborted tags */
7117	    0); /* reset tags */
7118
7119	mutex_exit(&ahci_portp->ahciport_mutex);
7120}
7121
7122/*
7123 * Watchdog handler kicks in every 5 seconds to timeout any commands pending
7124 * for long time.
7125 */
7126static void
7127ahci_watchdog_handler(ahci_ctl_t *ahci_ctlp)
7128{
7129	ahci_port_t *ahci_portp;
7130	sata_pkt_t *spkt;
7131	uint32_t pending_tags;
7132	uint32_t timeout_tags;
7133	uint32_t port_cmd_status;
7134	uint32_t port_sactive;
7135	uint8_t port;
7136	int tmp_slot;
7137	int current_slot;
7138	uint32_t current_tags;
7139	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
7140	/* max number of cycles this packet should survive */
7141	int max_life_cycles;
7142
7143	/* how many cycles this packet survived so far */
7144	int watched_cycles;
7145
7146	mutex_enter(&ahci_ctlp->ahcictl_mutex);
7147
7148	AHCIDBG(AHCIDBG_ENTRY, ahci_ctlp,
7149	    "ahci_watchdog_handler entered", NULL);
7150
7151	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
7152		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
7153			continue;
7154		}
7155
7156		ahci_portp = ahci_ctlp->ahcictl_ports[port];
7157
7158		mutex_enter(&ahci_portp->ahciport_mutex);
7159		if (ahci_portp->ahciport_device_type == SATA_DTYPE_NONE) {
7160			mutex_exit(&ahci_portp->ahciport_mutex);
7161			continue;
7162		}
7163
7164		/* Skip the check for those ports in error recovery */
7165		if ((ahci_portp->ahciport_flags & AHCI_PORT_FLAG_MOPPING) &&
7166		    !(ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))) {
7167			mutex_exit(&ahci_portp->ahciport_mutex);
7168			continue;
7169		}
7170
7171		pending_tags = 0;
7172		port_cmd_status = ddi_get32(ahci_ctlp->ahcictl_ahci_acc_handle,
7173		    (uint32_t *)AHCI_PORT_PxCMD(ahci_ctlp, port));
7174
7175		if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp)) {
7176			current_slot = 0;
7177			pending_tags = 0x1;
7178		} else if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7179			current_slot =
7180			    (port_cmd_status & AHCI_CMD_STATUS_CCS) >>
7181			    AHCI_CMD_STATUS_CCS_SHIFT;
7182			pending_tags = ahci_portp->ahciport_pending_tags;
7183		} else if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7184			port_sactive = ddi_get32(
7185			    ahci_ctlp->ahcictl_ahci_acc_handle,
7186			    (uint32_t *)AHCI_PORT_PxSACT(ahci_ctlp, port));
7187			current_tags = port_sactive &
7188			    ~port_cmd_status &
7189			    AHCI_NCQ_SLOT_MASK(ahci_portp);
7190			pending_tags = ahci_portp->ahciport_pending_ncq_tags;
7191		}
7192
7193		timeout_tags = 0;
7194		while (pending_tags) {
7195			tmp_slot = ddi_ffs(pending_tags) - 1;
7196			if (tmp_slot == -1) {
7197				break;
7198			}
7199
7200			if (ERR_RETRI_CMD_IN_PROGRESS(ahci_portp))
7201				spkt = ahci_portp->ahciport_err_retri_pkt;
7202			else
7203				spkt = ahci_portp->ahciport_slot_pkts[tmp_slot];
7204
7205			if ((spkt != NULL) && spkt->satapkt_time &&
7206			    !(spkt->satapkt_op_mode & SATA_OPMODE_POLLING)) {
7207				/*
7208				 * We are overloading satapkt_hba_driver_private
7209				 * with watched_cycle count.
7210				 *
7211				 * If a packet has survived for more than it's
7212				 * max life cycles, it is a candidate for time
7213				 * out.
7214				 */
7215				watched_cycles = (int)(intptr_t)
7216				    spkt->satapkt_hba_driver_private;
7217				watched_cycles++;
7218				max_life_cycles = (spkt->satapkt_time +
7219				    ahci_watchdog_timeout - 1) /
7220				    ahci_watchdog_timeout;
7221
7222				spkt->satapkt_hba_driver_private =
7223				    (void *)(intptr_t)watched_cycles;
7224
7225				if (watched_cycles <= max_life_cycles)
7226					goto next;
7227
7228#if AHCI_DEBUG
7229				if (NCQ_CMD_IN_PROGRESS(ahci_portp)) {
7230					AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT,
7231					    ahci_ctlp, "watchdog: the current "
7232					    "tags is 0x%x", current_tags);
7233				} else {
7234					AHCIDBG(AHCIDBG_ERRS|AHCIDBG_TIMEOUT,
7235					    ahci_ctlp, "watchdog: the current "
7236					    "slot is %d", current_slot);
7237				}
7238#endif
7239
7240				/*
7241				 * We need to check whether the HBA has
7242				 * begun to execute the command, if not,
7243				 * then re-set the timer of the command.
7244				 */
7245				if (NON_NCQ_CMD_IN_PROGRESS(ahci_portp) &&
7246				    (tmp_slot != current_slot) ||
7247				    NCQ_CMD_IN_PROGRESS(ahci_portp) &&
7248				    ((0x1 << tmp_slot) & current_tags)) {
7249					spkt->satapkt_hba_driver_private =
7250					    (void *)(intptr_t)0;
7251				} else {
7252					timeout_tags |= (0x1 << tmp_slot);
7253					cmn_err(CE_WARN, "!ahci%d: watchdog "
7254					    "port %d satapkt 0x%p timed out\n",
7255					    instance, port, (void *)spkt);
7256				}
7257			}
7258next:
7259			CLEAR_BIT(pending_tags, tmp_slot);
7260		}
7261
7262		if (timeout_tags) {
7263			mutex_exit(&ahci_portp->ahciport_mutex);
7264			mutex_exit(&ahci_ctlp->ahcictl_mutex);
7265			ahci_timeout_pkts(ahci_ctlp, ahci_portp,
7266			    port, timeout_tags);
7267			mutex_enter(&ahci_ctlp->ahcictl_mutex);
7268			mutex_enter(&ahci_portp->ahciport_mutex);
7269		}
7270
7271		mutex_exit(&ahci_portp->ahciport_mutex);
7272	}
7273
7274	/* Re-install the watchdog timeout handler */
7275	if (ahci_ctlp->ahcictl_timeout_id != 0) {
7276		ahci_ctlp->ahcictl_timeout_id =
7277		    timeout((void (*)(void *))ahci_watchdog_handler,
7278		    (caddr_t)ahci_ctlp, ahci_watchdog_tick);
7279	}
7280
7281	mutex_exit(&ahci_ctlp->ahcictl_mutex);
7282}
7283
7284/*
7285 * Fill the error context into sata_cmd for non-queued command error.
7286 */
7287static void
7288ahci_copy_err_cnxt(sata_cmd_t *scmd, ahci_fis_d2h_register_t *rfisp)
7289{
7290	scmd->satacmd_status_reg = GET_RFIS_STATUS(rfisp);
7291	scmd->satacmd_error_reg = GET_RFIS_ERROR(rfisp);
7292	scmd->satacmd_sec_count_lsb = GET_RFIS_SECTOR_COUNT(rfisp);
7293	scmd->satacmd_lba_low_lsb = GET_RFIS_CYL_LOW(rfisp);
7294	scmd->satacmd_lba_mid_lsb = GET_RFIS_CYL_MID(rfisp);
7295	scmd->satacmd_lba_high_lsb = GET_RFIS_CYL_HI(rfisp);
7296	scmd->satacmd_device_reg = GET_RFIS_DEV_HEAD(rfisp);
7297
7298	if (scmd->satacmd_addr_type == ATA_ADDR_LBA48) {
7299		scmd->satacmd_sec_count_msb = GET_RFIS_SECTOR_COUNT_EXP(rfisp);
7300		scmd->satacmd_lba_low_msb = GET_RFIS_CYL_LOW_EXP(rfisp);
7301		scmd->satacmd_lba_mid_msb = GET_RFIS_CYL_MID_EXP(rfisp);
7302		scmd->satacmd_lba_high_msb = GET_RFIS_CYL_HI_EXP(rfisp);
7303	}
7304}
7305
7306/*
7307 * Fill the ncq error page into sata_cmd for queued command error.
7308 */
7309static void
7310ahci_copy_ncq_err_page(sata_cmd_t *scmd,
7311    struct sata_ncq_error_recovery_page *ncq_err_page)
7312{
7313	scmd->satacmd_sec_count_msb = ncq_err_page->ncq_sector_count_ext;
7314	scmd->satacmd_sec_count_lsb = ncq_err_page->ncq_sector_count;
7315	scmd->satacmd_lba_low_msb = ncq_err_page->ncq_sector_number_ext;
7316	scmd->satacmd_lba_low_lsb = ncq_err_page->ncq_sector_number;
7317	scmd->satacmd_lba_mid_msb = ncq_err_page->ncq_cyl_low_ext;
7318	scmd->satacmd_lba_mid_lsb = ncq_err_page->ncq_cyl_low;
7319	scmd->satacmd_lba_high_msb = ncq_err_page->ncq_cyl_high_ext;
7320	scmd->satacmd_lba_high_lsb = ncq_err_page->ncq_cyl_high;
7321	scmd->satacmd_device_reg = ncq_err_page->ncq_dev_head;
7322	scmd->satacmd_status_reg = ncq_err_page->ncq_status;
7323	scmd->satacmd_error_reg = ncq_err_page->ncq_error;
7324}
7325
7326/*
7327 * Put the respective register value to sata_cmd_t for satacmd_flags.
7328 */
7329static void
7330ahci_copy_out_regs(sata_cmd_t *scmd, ahci_fis_d2h_register_t *rfisp)
7331{
7332	if (scmd->satacmd_flags.sata_copy_out_sec_count_msb)
7333		scmd->satacmd_sec_count_msb = GET_RFIS_SECTOR_COUNT_EXP(rfisp);
7334	if (scmd->satacmd_flags.sata_copy_out_lba_low_msb)
7335		scmd->satacmd_lba_low_msb = GET_RFIS_CYL_LOW_EXP(rfisp);
7336	if (scmd->satacmd_flags.sata_copy_out_lba_mid_msb)
7337		scmd->satacmd_lba_mid_msb = GET_RFIS_CYL_MID_EXP(rfisp);
7338	if (scmd->satacmd_flags.sata_copy_out_lba_high_msb)
7339		scmd->satacmd_lba_high_msb = GET_RFIS_CYL_HI_EXP(rfisp);
7340	if (scmd->satacmd_flags.sata_copy_out_sec_count_lsb)
7341		scmd->satacmd_sec_count_lsb = GET_RFIS_SECTOR_COUNT(rfisp);
7342	if (scmd->satacmd_flags.sata_copy_out_lba_low_lsb)
7343		scmd->satacmd_lba_low_lsb = GET_RFIS_CYL_LOW(rfisp);
7344	if (scmd->satacmd_flags.sata_copy_out_lba_mid_lsb)
7345		scmd->satacmd_lba_mid_lsb = GET_RFIS_CYL_MID(rfisp);
7346	if (scmd->satacmd_flags.sata_copy_out_lba_high_lsb)
7347		scmd->satacmd_lba_high_lsb = GET_RFIS_CYL_HI(rfisp);
7348	if (scmd->satacmd_flags.sata_copy_out_device_reg)
7349		scmd->satacmd_device_reg = GET_RFIS_DEV_HEAD(rfisp);
7350	if (scmd->satacmd_flags.sata_copy_out_error_reg)
7351		scmd->satacmd_error_reg = GET_RFIS_ERROR(rfisp);
7352}
7353
7354static void
7355ahci_log_fatal_error_message(ahci_ctl_t *ahci_ctlp, uint8_t port,
7356    uint32_t intr_status)
7357{
7358	int instance = ddi_get_instance(ahci_ctlp->ahcictl_dip);
7359
7360	if (intr_status & AHCI_INTR_STATUS_IFS)
7361		cmn_err(CE_WARN, "!ahci%d: ahci port %d has interface fatal "
7362		    "error", instance, port);
7363
7364	if (intr_status & AHCI_INTR_STATUS_HBDS)
7365		cmn_err(CE_WARN, "!ahci%d: ahci port %d has bus data error",
7366		    instance, port);
7367
7368	if (intr_status & AHCI_INTR_STATUS_HBFS)
7369		cmn_err(CE_WARN, "!ahci%d: ahci port %d has bus fatal error",
7370		    instance, port);
7371
7372	if (intr_status & AHCI_INTR_STATUS_TFES)
7373		cmn_err(CE_WARN, "!ahci%d: ahci port %d has task file error",
7374		    instance, port);
7375
7376	cmn_err(CE_WARN, "!ahci%d: ahci port %d is trying to do error "
7377	    "recovery", instance, port);
7378}
7379
7380/*
7381 * Dump the serror message to the log.
7382 */
7383static void
7384ahci_log_serror_message(ahci_ctl_t *ahci_ctlp, uint8_t port,
7385    uint32_t port_serror, int debug_only)
7386{
7387	static char err_buf[512];
7388	static char err_msg_header[16];
7389	char *err_msg = err_buf;
7390
7391	*err_buf = '\0';
7392	*err_msg_header = '\0';
7393
7394	if (port_serror & SERROR_DATA_ERR_FIXED) {
7395		err_msg = strcat(err_msg,
7396		    "\tRecovered Data Integrity Error (I)\n");
7397	}
7398
7399	if (port_serror & SERROR_COMM_ERR_FIXED) {
7400		err_msg = strcat(err_msg,
7401		    "\tRecovered Communication Error (M)\n");
7402	}
7403
7404	if (port_serror & SERROR_DATA_ERR) {
7405		err_msg = strcat(err_msg,
7406		    "\tTransient Data Integrity Error (T)\n");
7407	}
7408
7409	if (port_serror & SERROR_PERSISTENT_ERR) {
7410		err_msg = strcat(err_msg,
7411		    "\tPersistent Communication or Data Integrity Error (C)\n");
7412	}
7413
7414	if (port_serror & SERROR_PROTOCOL_ERR) {
7415		err_msg = strcat(err_msg, "\tProtocol Error (P)\n");
7416	}
7417
7418	if (port_serror & SERROR_INT_ERR) {
7419		err_msg = strcat(err_msg, "\tInternal Error (E)\n");
7420	}
7421
7422	if (port_serror & SERROR_PHY_RDY_CHG) {
7423		err_msg = strcat(err_msg, "\tPhyRdy Change (N)\n");
7424	}
7425
7426	if (port_serror & SERROR_PHY_INT_ERR) {
7427		err_msg = strcat(err_msg, "\tPhy Internal Error (I)\n");
7428	}
7429
7430	if (port_serror & SERROR_COMM_WAKE) {
7431		err_msg = strcat(err_msg, "\tComm Wake (W)\n");
7432	}
7433
7434	if (port_serror & SERROR_10B_TO_8B_ERR) {
7435		err_msg = strcat(err_msg, "\t10B to 8B Decode Error (B)\n");
7436	}
7437
7438	if (port_serror & SERROR_DISPARITY_ERR) {
7439		err_msg = strcat(err_msg, "\tDisparity Error (D)\n");
7440	}
7441
7442	if (port_serror & SERROR_CRC_ERR) {
7443		err_msg = strcat(err_msg, "\tCRC Error (C)\n");
7444	}
7445
7446	if (port_serror & SERROR_HANDSHAKE_ERR) {
7447		err_msg = strcat(err_msg, "\tHandshake Error (H)\n");
7448	}
7449
7450	if (port_serror & SERROR_LINK_SEQ_ERR) {
7451		err_msg = strcat(err_msg, "\tLink Sequence Error (S)\n");
7452	}
7453
7454	if (port_serror & SERROR_TRANS_ERR) {
7455		err_msg = strcat(err_msg,
7456		    "\tTransport state transition error (T)\n");
7457	}
7458
7459	if (port_serror & SERROR_FIS_TYPE) {
7460		err_msg = strcat(err_msg, "\tUnknown FIS Type (F)\n");
7461	}
7462
7463	if (port_serror & SERROR_EXCHANGED_ERR) {
7464		err_msg = strcat(err_msg, "\tExchanged (X)\n");
7465	}
7466
7467	if (err_msg == NULL)
7468		return;
7469
7470	if (debug_only) {
7471		(void) sprintf(err_msg_header, "port %d", port);
7472		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, err_msg_header, NULL);
7473		AHCIDBG(AHCIDBG_ERRS, ahci_ctlp, err_msg, NULL);
7474	} else if (ahci_ctlp) {
7475		cmn_err(CE_WARN, "!ahci%d: %s %s",
7476		    ddi_get_instance(ahci_ctlp->ahcictl_dip),
7477		    err_msg_header, err_msg);
7478
7479		/* sata trace debug */
7480		sata_trace_debug(ahci_ctlp->ahcictl_dip,
7481		    "ahci%d: %s %s", ddi_get_instance(ahci_ctlp->ahcictl_dip),
7482		    err_msg_header, err_msg);
7483	} else {
7484		cmn_err(CE_WARN, "!ahci: %s %s", err_msg_header, err_msg);
7485
7486		/* sata trace debug */
7487		sata_trace_debug(NULL, "ahci: %s %s", err_msg_header, err_msg);
7488	}
7489}
7490
7491/*
7492 * This routine is to calculate the total number of ports implemented
7493 * by the HBA.
7494 */
7495static int
7496ahci_get_num_implemented_ports(uint32_t ports_implemented)
7497{
7498	uint8_t i;
7499	int num = 0;
7500
7501	for (i = 0; i < AHCI_MAX_PORTS; i++) {
7502		if (((uint32_t)0x1 << i) & ports_implemented)
7503			num++;
7504	}
7505
7506	return (num);
7507}
7508
7509#if AHCI_DEBUG
7510static void
7511ahci_log(ahci_ctl_t *ahci_ctlp, uint_t level, char *fmt, ...)
7512{
7513	static char name[16];
7514	va_list ap;
7515
7516	mutex_enter(&ahci_log_mutex);
7517
7518	va_start(ap, fmt);
7519	if (ahci_ctlp) {
7520		(void) sprintf(name, "ahci%d: ",
7521		    ddi_get_instance(ahci_ctlp->ahcictl_dip));
7522	} else {
7523		(void) sprintf(name, "ahci: ");
7524	}
7525
7526	(void) vsprintf(ahci_log_buf, fmt, ap);
7527	va_end(ap);
7528
7529	cmn_err(level, "%s%s", name, ahci_log_buf);
7530
7531	mutex_exit(&ahci_log_mutex);
7532}
7533#endif
7534
7535/*
7536 * quiesce(9E) entry point.
7537 *
7538 * This function is called when the system is single-threaded at high
7539 * PIL with preemption disabled. Therefore, this function must not be
7540 * blocked.
7541 *
7542 * This function returns DDI_SUCCESS on success, or DDI_FAILURE on failure.
7543 * DDI_FAILURE indicates an error condition and should almost never happen.
7544 */
7545static int
7546ahci_quiesce(dev_info_t *dip)
7547{
7548	ahci_ctl_t *ahci_ctlp;
7549	ahci_port_t *ahci_portp;
7550	int instance, port;
7551
7552	instance = ddi_get_instance(dip);
7553	ahci_ctlp = ddi_get_soft_state(ahci_statep, instance);
7554
7555	if (ahci_ctlp == NULL)
7556		return (DDI_FAILURE);
7557
7558#if AHCI_DEBUG
7559	ahci_debug_flags = 0;
7560#endif
7561
7562	/* disable all the interrupts. */
7563	ahci_disable_all_intrs(ahci_ctlp);
7564
7565	for (port = 0; port < ahci_ctlp->ahcictl_num_ports; port++) {
7566		if (!AHCI_PORT_IMPLEMENTED(ahci_ctlp, port)) {
7567			continue;
7568		}
7569
7570		ahci_portp = ahci_ctlp->ahcictl_ports[port];
7571
7572		/*
7573		 * Stop the port by clearing PxCMD.ST
7574		 *
7575		 * Here we must disable the port interrupt because
7576		 * ahci_disable_all_intrs only clear GHC.IE, and IS
7577		 * register will be still set if PxIE is enabled.
7578		 * When ahci shares one IRQ with other drivers, the
7579		 * intr handler may claim the intr mistakenly.
7580		 */
7581		ahci_disable_port_intrs(ahci_ctlp, port);
7582		(void) ahci_put_port_into_notrunning_state(ahci_ctlp,
7583		    ahci_portp, port);
7584	}
7585
7586	return (DDI_SUCCESS);
7587}
7588