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