ahci_generic.c revision 245875
1/*-
2 * Copyright (c) 2009-2012 Alexander Motin <mav@FreeBSD.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer,
10 *    without modification, immediately at the beginning of the file.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/dev/ahci/ahci.c 245875 2013-01-24 09:33:43Z mav $");
29
30#include <sys/param.h>
31#include <sys/module.h>
32#include <sys/systm.h>
33#include <sys/kernel.h>
34#include <sys/bus.h>
35#include <sys/conf.h>
36#include <sys/endian.h>
37#include <sys/malloc.h>
38#include <sys/lock.h>
39#include <sys/mutex.h>
40#include <machine/stdarg.h>
41#include <machine/resource.h>
42#include <machine/bus.h>
43#include <sys/rman.h>
44#include <dev/pci/pcivar.h>
45#include <dev/pci/pcireg.h>
46#include "ahci.h"
47
48#include <cam/cam.h>
49#include <cam/cam_ccb.h>
50#include <cam/cam_sim.h>
51#include <cam/cam_xpt_sim.h>
52#include <cam/cam_debug.h>
53
54/* local prototypes */
55static int ahci_setup_interrupt(device_t dev);
56static void ahci_intr(void *data);
57static void ahci_intr_one(void *data);
58static int ahci_suspend(device_t dev);
59static int ahci_resume(device_t dev);
60static int ahci_ch_init(device_t dev);
61static int ahci_ch_deinit(device_t dev);
62static int ahci_ch_suspend(device_t dev);
63static int ahci_ch_resume(device_t dev);
64static void ahci_ch_pm(void *arg);
65static void ahci_ch_intr_locked(void *data);
66static void ahci_ch_intr(void *data);
67static int ahci_ctlr_reset(device_t dev);
68static int ahci_ctlr_setup(device_t dev);
69static void ahci_begin_transaction(device_t dev, union ccb *ccb);
70static void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
71static void ahci_execute_transaction(struct ahci_slot *slot);
72static void ahci_timeout(struct ahci_slot *slot);
73static void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
74static int ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
75static void ahci_dmainit(device_t dev);
76static void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
77static void ahci_dmafini(device_t dev);
78static void ahci_slotsalloc(device_t dev);
79static void ahci_slotsfree(device_t dev);
80static void ahci_reset(device_t dev);
81static void ahci_start(device_t dev, int fbs);
82static void ahci_stop(device_t dev);
83static void ahci_clo(device_t dev);
84static void ahci_start_fr(device_t dev);
85static void ahci_stop_fr(device_t dev);
86
87static int ahci_sata_connect(struct ahci_channel *ch);
88static int ahci_sata_phy_reset(device_t dev);
89static int ahci_wait_ready(device_t dev, int t, int t0);
90
91static void ahci_issue_recovery(device_t dev);
92static void ahci_process_read_log(device_t dev, union ccb *ccb);
93static void ahci_process_request_sense(device_t dev, union ccb *ccb);
94
95static void ahciaction(struct cam_sim *sim, union ccb *ccb);
96static void ahcipoll(struct cam_sim *sim);
97
98static MALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
99
100static struct {
101	uint32_t	id;
102	uint8_t		rev;
103	const char	*name;
104	int		quirks;
105#define AHCI_Q_NOFORCE	1
106#define AHCI_Q_NOPMP	2
107#define AHCI_Q_NONCQ	4
108#define AHCI_Q_1CH	8
109#define AHCI_Q_2CH	16
110#define AHCI_Q_4CH	32
111#define AHCI_Q_EDGEIS	64
112#define AHCI_Q_SATA2	128
113#define AHCI_Q_NOBSYRES	256
114#define AHCI_Q_NOAA	512
115#define AHCI_Q_NOCOUNT	1024
116#define AHCI_Q_ALTSIG	2048
117#define AHCI_Q_NOMSI	4096
118} ahci_ids[] = {
119	{0x43801002, 0x00, "ATI IXP600",	AHCI_Q_NOMSI},
120	{0x43901002, 0x00, "ATI IXP700",	0},
121	{0x43911002, 0x00, "ATI IXP700",	0},
122	{0x43921002, 0x00, "ATI IXP700",	0},
123	{0x43931002, 0x00, "ATI IXP700",	0},
124	{0x43941002, 0x00, "ATI IXP800",	0},
125	{0x43951002, 0x00, "ATI IXP800",	0},
126	{0x78001022, 0x00, "AMD Hudson-2",	0},
127	{0x78011022, 0x00, "AMD Hudson-2",	0},
128	{0x78021022, 0x00, "AMD Hudson-2",	0},
129	{0x78031022, 0x00, "AMD Hudson-2",	0},
130	{0x78041022, 0x00, "AMD Hudson-2",	0},
131	{0x06121b21, 0x00, "ASMedia ASM1061",	0},
132	{0x26528086, 0x00, "Intel ICH6",	AHCI_Q_NOFORCE},
133	{0x26538086, 0x00, "Intel ICH6M",	AHCI_Q_NOFORCE},
134	{0x26818086, 0x00, "Intel ESB2",	0},
135	{0x26828086, 0x00, "Intel ESB2",	0},
136	{0x26838086, 0x00, "Intel ESB2",	0},
137	{0x27c18086, 0x00, "Intel ICH7",	0},
138	{0x27c38086, 0x00, "Intel ICH7",	0},
139	{0x27c58086, 0x00, "Intel ICH7M",	0},
140	{0x27c68086, 0x00, "Intel ICH7M",	0},
141	{0x28218086, 0x00, "Intel ICH8",	0},
142	{0x28228086, 0x00, "Intel ICH8",	0},
143	{0x28248086, 0x00, "Intel ICH8",	0},
144	{0x28298086, 0x00, "Intel ICH8M",	0},
145	{0x282a8086, 0x00, "Intel ICH8M",	0},
146	{0x29228086, 0x00, "Intel ICH9",	0},
147	{0x29238086, 0x00, "Intel ICH9",	0},
148	{0x29248086, 0x00, "Intel ICH9",	0},
149	{0x29258086, 0x00, "Intel ICH9",	0},
150	{0x29278086, 0x00, "Intel ICH9",	0},
151	{0x29298086, 0x00, "Intel ICH9M",	0},
152	{0x292a8086, 0x00, "Intel ICH9M",	0},
153	{0x292b8086, 0x00, "Intel ICH9M",	0},
154	{0x292c8086, 0x00, "Intel ICH9M",	0},
155	{0x292f8086, 0x00, "Intel ICH9M",	0},
156	{0x294d8086, 0x00, "Intel ICH9",	0},
157	{0x294e8086, 0x00, "Intel ICH9M",	0},
158	{0x3a058086, 0x00, "Intel ICH10",	0},
159	{0x3a228086, 0x00, "Intel ICH10",	0},
160	{0x3a258086, 0x00, "Intel ICH10",	0},
161	{0x3b228086, 0x00, "Intel 5 Series/3400 Series",	0},
162	{0x3b238086, 0x00, "Intel 5 Series/3400 Series",	0},
163	{0x3b258086, 0x00, "Intel 5 Series/3400 Series",	0},
164	{0x3b298086, 0x00, "Intel 5 Series/3400 Series",	0},
165	{0x3b2c8086, 0x00, "Intel 5 Series/3400 Series",	0},
166	{0x3b2f8086, 0x00, "Intel 5 Series/3400 Series",	0},
167	{0x1c028086, 0x00, "Intel Cougar Point",	0},
168	{0x1c038086, 0x00, "Intel Cougar Point",	0},
169	{0x1c048086, 0x00, "Intel Cougar Point",	0},
170	{0x1c058086, 0x00, "Intel Cougar Point",	0},
171	{0x1d028086, 0x00, "Intel Patsburg",	0},
172	{0x1d048086, 0x00, "Intel Patsburg",	0},
173	{0x1d068086, 0x00, "Intel Patsburg",	0},
174	{0x28268086, 0x00, "Intel Patsburg (RAID)",	0},
175	{0x1e028086, 0x00, "Intel Panther Point",	0},
176	{0x1e038086, 0x00, "Intel Panther Point",	0},
177	{0x1e048086, 0x00, "Intel Panther Point",	0},
178	{0x1e058086, 0x00, "Intel Panther Point",	0},
179	{0x1e068086, 0x00, "Intel Panther Point",	0},
180	{0x1e078086, 0x00, "Intel Panther Point",	0},
181	{0x1e0e8086, 0x00, "Intel Panther Point",	0},
182	{0x1e0f8086, 0x00, "Intel Panther Point",	0},
183	{0x8c028086, 0x00, "Intel Lynx Point",	0},
184	{0x8c038086, 0x00, "Intel Lynx Point",	0},
185	{0x8c048086, 0x00, "Intel Lynx Point",	0},
186	{0x8c058086, 0x00, "Intel Lynx Point",	0},
187	{0x8c068086, 0x00, "Intel Lynx Point",	0},
188	{0x8c078086, 0x00, "Intel Lynx Point",	0},
189	{0x8c0e8086, 0x00, "Intel Lynx Point",	0},
190	{0x8c0f8086, 0x00, "Intel Lynx Point",	0},
191	{0x23238086, 0x00, "Intel DH89xxCC",	0},
192	{0x2360197b, 0x00, "JMicron JMB360",	0},
193	{0x2361197b, 0x00, "JMicron JMB361",	AHCI_Q_NOFORCE},
194	{0x2362197b, 0x00, "JMicron JMB362",	0},
195	{0x2363197b, 0x00, "JMicron JMB363",	AHCI_Q_NOFORCE},
196	{0x2365197b, 0x00, "JMicron JMB365",	AHCI_Q_NOFORCE},
197	{0x2366197b, 0x00, "JMicron JMB366",	AHCI_Q_NOFORCE},
198	{0x2368197b, 0x00, "JMicron JMB368",	AHCI_Q_NOFORCE},
199	{0x611111ab, 0x00, "Marvell 88SE6111",	AHCI_Q_NOFORCE | AHCI_Q_1CH |
200	    AHCI_Q_EDGEIS},
201	{0x612111ab, 0x00, "Marvell 88SE6121",	AHCI_Q_NOFORCE | AHCI_Q_2CH |
202	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
203	{0x614111ab, 0x00, "Marvell 88SE6141",	AHCI_Q_NOFORCE | AHCI_Q_4CH |
204	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
205	{0x614511ab, 0x00, "Marvell 88SE6145",	AHCI_Q_NOFORCE | AHCI_Q_4CH |
206	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
207	{0x91201b4b, 0x00, "Marvell 88SE912x",	AHCI_Q_EDGEIS|AHCI_Q_NOBSYRES},
208	{0x91231b4b, 0x11, "Marvell 88SE912x",	AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
209	{0x91231b4b, 0x00, "Marvell 88SE912x",	AHCI_Q_EDGEIS|AHCI_Q_SATA2|AHCI_Q_NOBSYRES},
210	{0x91251b4b, 0x00, "Marvell 88SE9125",	AHCI_Q_NOBSYRES},
211	{0x91281b4b, 0x00, "Marvell 88SE9128",	AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
212	{0x91301b4b, 0x00, "Marvell 88SE9130",  AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
213	{0x91721b4b, 0x00, "Marvell 88SE9172",	AHCI_Q_NOBSYRES},
214	{0x91821b4b, 0x00, "Marvell 88SE9182",	AHCI_Q_NOBSYRES},
215	{0x92201b4b, 0x00, "Marvell 88SE9220",  AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
216	{0x92301b4b, 0x00, "Marvell 88SE9230",  AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
217	{0x92351b4b, 0x00, "Marvell 88SE9235",  AHCI_Q_NOBSYRES},
218	{0x06201103, 0x00, "HighPoint RocketRAID 620",	AHCI_Q_NOBSYRES},
219	{0x06201b4b, 0x00, "HighPoint RocketRAID 620",	AHCI_Q_NOBSYRES},
220	{0x06221103, 0x00, "HighPoint RocketRAID 622",	AHCI_Q_NOBSYRES},
221	{0x06221b4b, 0x00, "HighPoint RocketRAID 622",	AHCI_Q_NOBSYRES},
222	{0x06401103, 0x00, "HighPoint RocketRAID 640",	AHCI_Q_NOBSYRES},
223	{0x06401b4b, 0x00, "HighPoint RocketRAID 640",	AHCI_Q_NOBSYRES},
224	{0x06441103, 0x00, "HighPoint RocketRAID 644",	AHCI_Q_NOBSYRES},
225	{0x06441b4b, 0x00, "HighPoint RocketRAID 644",	AHCI_Q_NOBSYRES},
226	{0x044c10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
227	{0x044d10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
228	{0x044e10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
229	{0x044f10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
230	{0x045c10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
231	{0x045d10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
232	{0x045e10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
233	{0x045f10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
234	{0x055010de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
235	{0x055110de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
236	{0x055210de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
237	{0x055310de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
238	{0x055410de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
239	{0x055510de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
240	{0x055610de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
241	{0x055710de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
242	{0x055810de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
243	{0x055910de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
244	{0x055A10de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
245	{0x055B10de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
246	{0x058410de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
247	{0x07f010de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
248	{0x07f110de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
249	{0x07f210de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
250	{0x07f310de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
251	{0x07f410de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
252	{0x07f510de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
253	{0x07f610de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
254	{0x07f710de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
255	{0x07f810de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
256	{0x07f910de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
257	{0x07fa10de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
258	{0x07fb10de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
259	{0x0ad010de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
260	{0x0ad110de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
261	{0x0ad210de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
262	{0x0ad310de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
263	{0x0ad410de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
264	{0x0ad510de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
265	{0x0ad610de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
266	{0x0ad710de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
267	{0x0ad810de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
268	{0x0ad910de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
269	{0x0ada10de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
270	{0x0adb10de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
271	{0x0ab410de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
272	{0x0ab510de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
273	{0x0ab610de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
274	{0x0ab710de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
275	{0x0ab810de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
276	{0x0ab910de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
277	{0x0aba10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
278	{0x0abb10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
279	{0x0abc10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
280	{0x0abd10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
281	{0x0abe10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
282	{0x0abf10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
283	{0x0d8410de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
284	{0x0d8510de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOFORCE|AHCI_Q_NOAA},
285	{0x0d8610de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
286	{0x0d8710de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
287	{0x0d8810de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
288	{0x0d8910de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
289	{0x0d8a10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
290	{0x0d8b10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
291	{0x0d8c10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
292	{0x0d8d10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
293	{0x0d8e10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
294	{0x0d8f10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
295	{0x33491106, 0x00, "VIA VT8251",	AHCI_Q_NOPMP|AHCI_Q_NONCQ},
296	{0x62871106, 0x00, "VIA VT8251",	AHCI_Q_NOPMP|AHCI_Q_NONCQ},
297	{0x11841039, 0x00, "SiS 966",		0},
298	{0x11851039, 0x00, "SiS 968",		0},
299	{0x01861039, 0x00, "SiS 968",		0},
300	{0x00000000, 0x00, NULL,		0}
301};
302
303#define recovery_type		spriv_field0
304#define RECOVERY_NONE		0
305#define RECOVERY_READ_LOG	1
306#define RECOVERY_REQUEST_SENSE	2
307#define recovery_slot		spriv_field1
308
309static int force_ahci = 1;
310TUNABLE_INT("hw.ahci.force", &force_ahci);
311
312static int
313ahci_probe(device_t dev)
314{
315	char buf[64];
316	int i, valid = 0;
317	uint32_t devid = pci_get_devid(dev);
318	uint8_t revid = pci_get_revid(dev);
319
320	/* Is this a possible AHCI candidate? */
321	if (pci_get_class(dev) == PCIC_STORAGE &&
322	    pci_get_subclass(dev) == PCIS_STORAGE_SATA &&
323	    pci_get_progif(dev) == PCIP_STORAGE_SATA_AHCI_1_0)
324		valid = 1;
325	/* Is this a known AHCI chip? */
326	for (i = 0; ahci_ids[i].id != 0; i++) {
327		if (ahci_ids[i].id == devid &&
328		    ahci_ids[i].rev <= revid &&
329		    (valid || (force_ahci == 1 &&
330		     !(ahci_ids[i].quirks & AHCI_Q_NOFORCE)))) {
331			/* Do not attach JMicrons with single PCI function. */
332			if (pci_get_vendor(dev) == 0x197b &&
333			    (pci_read_config(dev, 0xdf, 1) & 0x40) == 0)
334				return (ENXIO);
335			snprintf(buf, sizeof(buf), "%s AHCI SATA controller",
336			    ahci_ids[i].name);
337			device_set_desc_copy(dev, buf);
338			return (BUS_PROBE_VENDOR);
339		}
340	}
341	if (!valid)
342		return (ENXIO);
343	device_set_desc_copy(dev, "AHCI SATA controller");
344	return (BUS_PROBE_VENDOR);
345}
346
347static int
348ahci_ata_probe(device_t dev)
349{
350	char buf[64];
351	int i;
352	uint32_t devid = pci_get_devid(dev);
353	uint8_t revid = pci_get_revid(dev);
354
355	if ((intptr_t)device_get_ivars(dev) >= 0)
356		return (ENXIO);
357	/* Is this a known AHCI chip? */
358	for (i = 0; ahci_ids[i].id != 0; i++) {
359		if (ahci_ids[i].id == devid &&
360		    ahci_ids[i].rev <= revid) {
361			snprintf(buf, sizeof(buf), "%s AHCI SATA controller",
362			    ahci_ids[i].name);
363			device_set_desc_copy(dev, buf);
364			return (BUS_PROBE_VENDOR);
365		}
366	}
367	device_set_desc_copy(dev, "AHCI SATA controller");
368	return (BUS_PROBE_VENDOR);
369}
370
371static int
372ahci_attach(device_t dev)
373{
374	struct ahci_controller *ctlr = device_get_softc(dev);
375	device_t child;
376	int	error, unit, speed, i;
377	uint32_t devid = pci_get_devid(dev);
378	uint8_t revid = pci_get_revid(dev);
379	u_int32_t version;
380
381	ctlr->dev = dev;
382	i = 0;
383	while (ahci_ids[i].id != 0 &&
384	    (ahci_ids[i].id != devid ||
385	     ahci_ids[i].rev > revid))
386		i++;
387	ctlr->quirks = ahci_ids[i].quirks;
388	resource_int_value(device_get_name(dev),
389	    device_get_unit(dev), "ccc", &ctlr->ccc);
390	/* if we have a memory BAR(5) we are likely on an AHCI part */
391	ctlr->r_rid = PCIR_BAR(5);
392	if (!(ctlr->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
393	    &ctlr->r_rid, RF_ACTIVE)))
394		return ENXIO;
395	/* Setup our own memory management for channels. */
396	ctlr->sc_iomem.rm_start = rman_get_start(ctlr->r_mem);
397	ctlr->sc_iomem.rm_end = rman_get_end(ctlr->r_mem);
398	ctlr->sc_iomem.rm_type = RMAN_ARRAY;
399	ctlr->sc_iomem.rm_descr = "I/O memory addresses";
400	if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
401		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
402		return (error);
403	}
404	if ((error = rman_manage_region(&ctlr->sc_iomem,
405	    rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
406		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
407		rman_fini(&ctlr->sc_iomem);
408		return (error);
409	}
410	pci_enable_busmaster(dev);
411	/* Reset controller */
412	if ((error = ahci_ctlr_reset(dev)) != 0) {
413		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
414		rman_fini(&ctlr->sc_iomem);
415		return (error);
416	};
417	/* Get the HW capabilities */
418	version = ATA_INL(ctlr->r_mem, AHCI_VS);
419	ctlr->caps = ATA_INL(ctlr->r_mem, AHCI_CAP);
420	if (version >= 0x00010200)
421		ctlr->caps2 = ATA_INL(ctlr->r_mem, AHCI_CAP2);
422	if (ctlr->caps & AHCI_CAP_EMS)
423		ctlr->capsem = ATA_INL(ctlr->r_mem, AHCI_EM_CTL);
424	ctlr->ichannels = ATA_INL(ctlr->r_mem, AHCI_PI);
425
426	/* Identify and set separate quirks for HBA and RAID f/w Marvells. */
427	if ((ctlr->quirks & AHCI_Q_NOBSYRES) &&
428	    (ctlr->quirks & AHCI_Q_ALTSIG) &&
429	    (ctlr->caps & AHCI_CAP_SPM) == 0)
430		ctlr->quirks &= ~AHCI_Q_NOBSYRES;
431
432	if (ctlr->quirks & AHCI_Q_1CH) {
433		ctlr->caps &= ~AHCI_CAP_NPMASK;
434		ctlr->ichannels &= 0x01;
435	}
436	if (ctlr->quirks & AHCI_Q_2CH) {
437		ctlr->caps &= ~AHCI_CAP_NPMASK;
438		ctlr->caps |= 1;
439		ctlr->ichannels &= 0x03;
440	}
441	if (ctlr->quirks & AHCI_Q_4CH) {
442		ctlr->caps &= ~AHCI_CAP_NPMASK;
443		ctlr->caps |= 3;
444		ctlr->ichannels &= 0x0f;
445	}
446	ctlr->channels = MAX(flsl(ctlr->ichannels),
447	    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
448	if (ctlr->quirks & AHCI_Q_NOPMP)
449		ctlr->caps &= ~AHCI_CAP_SPM;
450	if (ctlr->quirks & AHCI_Q_NONCQ)
451		ctlr->caps &= ~AHCI_CAP_SNCQ;
452	if ((ctlr->caps & AHCI_CAP_CCCS) == 0)
453		ctlr->ccc = 0;
454	ctlr->emloc = ATA_INL(ctlr->r_mem, AHCI_EM_LOC);
455	ahci_ctlr_setup(dev);
456	/* Setup interrupts. */
457	if (ahci_setup_interrupt(dev)) {
458		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
459		rman_fini(&ctlr->sc_iomem);
460		return ENXIO;
461	}
462	/* Announce HW capabilities. */
463	speed = (ctlr->caps & AHCI_CAP_ISS) >> AHCI_CAP_ISS_SHIFT;
464	device_printf(dev,
465		    "AHCI v%x.%02x with %d %sGbps ports, Port Multiplier %s%s\n",
466		    ((version >> 20) & 0xf0) + ((version >> 16) & 0x0f),
467		    ((version >> 4) & 0xf0) + (version & 0x0f),
468		    (ctlr->caps & AHCI_CAP_NPMASK) + 1,
469		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
470		    ((speed == 3) ? "6":"?"))),
471		    (ctlr->caps & AHCI_CAP_SPM) ?
472		    "supported" : "not supported",
473		    (ctlr->caps & AHCI_CAP_FBSS) ?
474		    " with FBS" : "");
475	if (bootverbose) {
476		device_printf(dev, "Caps:%s%s%s%s%s%s%s%s %sGbps",
477		    (ctlr->caps & AHCI_CAP_64BIT) ? " 64bit":"",
478		    (ctlr->caps & AHCI_CAP_SNCQ) ? " NCQ":"",
479		    (ctlr->caps & AHCI_CAP_SSNTF) ? " SNTF":"",
480		    (ctlr->caps & AHCI_CAP_SMPS) ? " MPS":"",
481		    (ctlr->caps & AHCI_CAP_SSS) ? " SS":"",
482		    (ctlr->caps & AHCI_CAP_SALP) ? " ALP":"",
483		    (ctlr->caps & AHCI_CAP_SAL) ? " AL":"",
484		    (ctlr->caps & AHCI_CAP_SCLO) ? " CLO":"",
485		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
486		    ((speed == 3) ? "6":"?"))));
487		printf("%s%s%s%s%s%s %dcmd%s%s%s %dports\n",
488		    (ctlr->caps & AHCI_CAP_SAM) ? " AM":"",
489		    (ctlr->caps & AHCI_CAP_SPM) ? " PM":"",
490		    (ctlr->caps & AHCI_CAP_FBSS) ? " FBS":"",
491		    (ctlr->caps & AHCI_CAP_PMD) ? " PMD":"",
492		    (ctlr->caps & AHCI_CAP_SSC) ? " SSC":"",
493		    (ctlr->caps & AHCI_CAP_PSC) ? " PSC":"",
494		    ((ctlr->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
495		    (ctlr->caps & AHCI_CAP_CCCS) ? " CCC":"",
496		    (ctlr->caps & AHCI_CAP_EMS) ? " EM":"",
497		    (ctlr->caps & AHCI_CAP_SXS) ? " eSATA":"",
498		    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
499	}
500	if (bootverbose && version >= 0x00010200) {
501		device_printf(dev, "Caps2:%s%s%s\n",
502		    (ctlr->caps2 & AHCI_CAP2_APST) ? " APST":"",
503		    (ctlr->caps2 & AHCI_CAP2_NVMP) ? " NVMP":"",
504		    (ctlr->caps2 & AHCI_CAP2_BOH) ? " BOH":"");
505	}
506	/* Attach all channels on this controller */
507	for (unit = 0; unit < ctlr->channels; unit++) {
508		child = device_add_child(dev, "ahcich", -1);
509		if (child == NULL) {
510			device_printf(dev, "failed to add channel device\n");
511			continue;
512		}
513		device_set_ivars(child, (void *)(intptr_t)unit);
514		if ((ctlr->ichannels & (1 << unit)) == 0)
515			device_disable(child);
516	}
517	if (ctlr->caps & AHCI_CAP_EMS) {
518		child = device_add_child(dev, "ahciem", -1);
519		if (child == NULL)
520			device_printf(dev, "failed to add enclosure device\n");
521		else
522			device_set_ivars(child, (void *)(intptr_t)-1);
523	}
524	bus_generic_attach(dev);
525	return 0;
526}
527
528static int
529ahci_detach(device_t dev)
530{
531	struct ahci_controller *ctlr = device_get_softc(dev);
532	int i;
533
534	/* Detach & delete all children */
535	device_delete_children(dev);
536
537	/* Free interrupts. */
538	for (i = 0; i < ctlr->numirqs; i++) {
539		if (ctlr->irqs[i].r_irq) {
540			bus_teardown_intr(dev, ctlr->irqs[i].r_irq,
541			    ctlr->irqs[i].handle);
542			bus_release_resource(dev, SYS_RES_IRQ,
543			    ctlr->irqs[i].r_irq_rid, ctlr->irqs[i].r_irq);
544		}
545	}
546	pci_release_msi(dev);
547	/* Free memory. */
548	rman_fini(&ctlr->sc_iomem);
549	if (ctlr->r_mem)
550		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
551	return (0);
552}
553
554static int
555ahci_ctlr_reset(device_t dev)
556{
557	struct ahci_controller *ctlr = device_get_softc(dev);
558	int timeout;
559
560	if (pci_read_config(dev, PCIR_DEVVENDOR, 4) == 0x28298086 &&
561	    (pci_read_config(dev, 0x92, 1) & 0xfe) == 0x04)
562		pci_write_config(dev, 0x92, 0x01, 1);
563	/* Enable AHCI mode */
564	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
565	/* Reset AHCI controller */
566	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE|AHCI_GHC_HR);
567	for (timeout = 1000; timeout > 0; timeout--) {
568		DELAY(1000);
569		if ((ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_HR) == 0)
570			break;
571	}
572	if (timeout == 0) {
573		device_printf(dev, "AHCI controller reset failure\n");
574		return ENXIO;
575	}
576	/* Reenable AHCI mode */
577	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
578	return (0);
579}
580
581static int
582ahci_ctlr_setup(device_t dev)
583{
584	struct ahci_controller *ctlr = device_get_softc(dev);
585	/* Clear interrupts */
586	ATA_OUTL(ctlr->r_mem, AHCI_IS, ATA_INL(ctlr->r_mem, AHCI_IS));
587	/* Configure CCC */
588	if (ctlr->ccc) {
589		ATA_OUTL(ctlr->r_mem, AHCI_CCCP, ATA_INL(ctlr->r_mem, AHCI_PI));
590		ATA_OUTL(ctlr->r_mem, AHCI_CCCC,
591		    (ctlr->ccc << AHCI_CCCC_TV_SHIFT) |
592		    (4 << AHCI_CCCC_CC_SHIFT) |
593		    AHCI_CCCC_EN);
594		ctlr->cccv = (ATA_INL(ctlr->r_mem, AHCI_CCCC) &
595		    AHCI_CCCC_INT_MASK) >> AHCI_CCCC_INT_SHIFT;
596		if (bootverbose) {
597			device_printf(dev,
598			    "CCC with %dms/4cmd enabled on vector %d\n",
599			    ctlr->ccc, ctlr->cccv);
600		}
601	}
602	/* Enable AHCI interrupts */
603	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
604	    ATA_INL(ctlr->r_mem, AHCI_GHC) | AHCI_GHC_IE);
605	return (0);
606}
607
608static int
609ahci_suspend(device_t dev)
610{
611	struct ahci_controller *ctlr = device_get_softc(dev);
612
613	bus_generic_suspend(dev);
614	/* Disable interupts, so the state change(s) doesn't trigger */
615	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
616	     ATA_INL(ctlr->r_mem, AHCI_GHC) & (~AHCI_GHC_IE));
617	return 0;
618}
619
620static int
621ahci_resume(device_t dev)
622{
623	int res;
624
625	if ((res = ahci_ctlr_reset(dev)) != 0)
626		return (res);
627	ahci_ctlr_setup(dev);
628	return (bus_generic_resume(dev));
629}
630
631static int
632ahci_setup_interrupt(device_t dev)
633{
634	struct ahci_controller *ctlr = device_get_softc(dev);
635	int i, msi = 1;
636
637	/* Process hints. */
638	if (ctlr->quirks & AHCI_Q_NOMSI)
639		msi = 0;
640	resource_int_value(device_get_name(dev),
641	    device_get_unit(dev), "msi", &msi);
642	if (msi < 0)
643		msi = 0;
644	else if (msi == 1)
645		msi = min(1, pci_msi_count(dev));
646	else if (msi > 1)
647		msi = pci_msi_count(dev);
648	/* Allocate MSI if needed/present. */
649	if (msi && pci_alloc_msi(dev, &msi) == 0) {
650		ctlr->numirqs = msi;
651	} else {
652		msi = 0;
653		ctlr->numirqs = 1;
654	}
655	/* Check for single MSI vector fallback. */
656	if (ctlr->numirqs > 1 &&
657	    (ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_MRSM) != 0) {
658		device_printf(dev, "Falling back to one MSI\n");
659		ctlr->numirqs = 1;
660	}
661	/* Allocate all IRQs. */
662	for (i = 0; i < ctlr->numirqs; i++) {
663		ctlr->irqs[i].ctlr = ctlr;
664		ctlr->irqs[i].r_irq_rid = i + (msi ? 1 : 0);
665		if (ctlr->numirqs == 1 || i >= ctlr->channels ||
666		    (ctlr->ccc && i == ctlr->cccv))
667			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ALL;
668		else if (i == ctlr->numirqs - 1)
669			ctlr->irqs[i].mode = AHCI_IRQ_MODE_AFTER;
670		else
671			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
672		if (!(ctlr->irqs[i].r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
673		    &ctlr->irqs[i].r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
674			device_printf(dev, "unable to map interrupt\n");
675			return ENXIO;
676		}
677		if ((bus_setup_intr(dev, ctlr->irqs[i].r_irq, ATA_INTR_FLAGS, NULL,
678		    (ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE) ? ahci_intr_one : ahci_intr,
679		    &ctlr->irqs[i], &ctlr->irqs[i].handle))) {
680			/* SOS XXX release r_irq */
681			device_printf(dev, "unable to setup interrupt\n");
682			return ENXIO;
683		}
684		if (ctlr->numirqs > 1) {
685			bus_describe_intr(dev, ctlr->irqs[i].r_irq,
686			    ctlr->irqs[i].handle,
687			    ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE ?
688			    "ch%d" : "%d", i);
689		}
690	}
691	return (0);
692}
693
694/*
695 * Common case interrupt handler.
696 */
697static void
698ahci_intr(void *data)
699{
700	struct ahci_controller_irq *irq = data;
701	struct ahci_controller *ctlr = irq->ctlr;
702	u_int32_t is, ise = 0;
703	void *arg;
704	int unit;
705
706	if (irq->mode == AHCI_IRQ_MODE_ALL) {
707		unit = 0;
708		if (ctlr->ccc)
709			is = ctlr->ichannels;
710		else
711			is = ATA_INL(ctlr->r_mem, AHCI_IS);
712	} else {	/* AHCI_IRQ_MODE_AFTER */
713		unit = irq->r_irq_rid - 1;
714		is = ATA_INL(ctlr->r_mem, AHCI_IS);
715	}
716	/* CCC interrupt is edge triggered. */
717	if (ctlr->ccc)
718		ise = 1 << ctlr->cccv;
719	/* Some controllers have edge triggered IS. */
720	if (ctlr->quirks & AHCI_Q_EDGEIS)
721		ise |= is;
722	if (ise != 0)
723		ATA_OUTL(ctlr->r_mem, AHCI_IS, ise);
724	for (; unit < ctlr->channels; unit++) {
725		if ((is & (1 << unit)) != 0 &&
726		    (arg = ctlr->interrupt[unit].argument)) {
727				ctlr->interrupt[unit].function(arg);
728		}
729	}
730	/* AHCI declares level triggered IS. */
731	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
732		ATA_OUTL(ctlr->r_mem, AHCI_IS, is);
733}
734
735/*
736 * Simplified interrupt handler for multivector MSI mode.
737 */
738static void
739ahci_intr_one(void *data)
740{
741	struct ahci_controller_irq *irq = data;
742	struct ahci_controller *ctlr = irq->ctlr;
743	void *arg;
744	int unit;
745
746	unit = irq->r_irq_rid - 1;
747	/* Some controllers have edge triggered IS. */
748	if (ctlr->quirks & AHCI_Q_EDGEIS)
749		ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
750	if ((arg = ctlr->interrupt[unit].argument))
751	    ctlr->interrupt[unit].function(arg);
752	/* AHCI declares level triggered IS. */
753	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
754		ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
755}
756
757static struct resource *
758ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
759		       u_long start, u_long end, u_long count, u_int flags)
760{
761	struct ahci_controller *ctlr = device_get_softc(dev);
762	struct resource *res;
763	long st;
764	int offset, size, unit;
765
766	unit = (intptr_t)device_get_ivars(child);
767	res = NULL;
768	switch (type) {
769	case SYS_RES_MEMORY:
770		if (unit >= 0) {
771			offset = AHCI_OFFSET + (unit << 7);
772			size = 128;
773		} else if (*rid == 0) {
774			offset = AHCI_EM_CTL;
775			size = 4;
776		} else {
777			offset = (ctlr->emloc & 0xffff0000) >> 14;
778			size = (ctlr->emloc & 0x0000ffff) << 2;
779			if (*rid != 1) {
780				if (*rid == 2 && (ctlr->capsem &
781				    (AHCI_EM_XMT | AHCI_EM_SMB)) == 0)
782					offset += size;
783				else
784					break;
785			}
786		}
787		st = rman_get_start(ctlr->r_mem);
788		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
789		    st + offset + size - 1, size, RF_ACTIVE, child);
790		if (res) {
791			bus_space_handle_t bsh;
792			bus_space_tag_t bst;
793			bsh = rman_get_bushandle(ctlr->r_mem);
794			bst = rman_get_bustag(ctlr->r_mem);
795			bus_space_subregion(bst, bsh, offset, 128, &bsh);
796			rman_set_bushandle(res, bsh);
797			rman_set_bustag(res, bst);
798		}
799		break;
800	case SYS_RES_IRQ:
801		if (*rid == ATA_IRQ_RID)
802			res = ctlr->irqs[0].r_irq;
803		break;
804	}
805	return (res);
806}
807
808static int
809ahci_release_resource(device_t dev, device_t child, int type, int rid,
810			 struct resource *r)
811{
812
813	switch (type) {
814	case SYS_RES_MEMORY:
815		rman_release_resource(r);
816		return (0);
817	case SYS_RES_IRQ:
818		if (rid != ATA_IRQ_RID)
819			return ENOENT;
820		return (0);
821	}
822	return (EINVAL);
823}
824
825static int
826ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
827		   int flags, driver_filter_t *filter, driver_intr_t *function,
828		   void *argument, void **cookiep)
829{
830	struct ahci_controller *ctlr = device_get_softc(dev);
831	int unit = (intptr_t)device_get_ivars(child);
832
833	if (filter != NULL) {
834		printf("ahci.c: we cannot use a filter here\n");
835		return (EINVAL);
836	}
837	ctlr->interrupt[unit].function = function;
838	ctlr->interrupt[unit].argument = argument;
839	return (0);
840}
841
842static int
843ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
844		      void *cookie)
845{
846	struct ahci_controller *ctlr = device_get_softc(dev);
847	int unit = (intptr_t)device_get_ivars(child);
848
849	ctlr->interrupt[unit].function = NULL;
850	ctlr->interrupt[unit].argument = NULL;
851	return (0);
852}
853
854static int
855ahci_print_child(device_t dev, device_t child)
856{
857	int retval, channel;
858
859	retval = bus_print_child_header(dev, child);
860	channel = (int)(intptr_t)device_get_ivars(child);
861	if (channel >= 0)
862		retval += printf(" at channel %d", channel);
863	retval += bus_print_child_footer(dev, child);
864	return (retval);
865}
866
867static int
868ahci_child_location_str(device_t dev, device_t child, char *buf,
869    size_t buflen)
870{
871	int channel;
872
873	channel = (int)(intptr_t)device_get_ivars(child);
874	if (channel >= 0)
875		snprintf(buf, buflen, "channel=%d", channel);
876	return (0);
877}
878
879devclass_t ahci_devclass;
880static device_method_t ahci_methods[] = {
881	DEVMETHOD(device_probe,     ahci_probe),
882	DEVMETHOD(device_attach,    ahci_attach),
883	DEVMETHOD(device_detach,    ahci_detach),
884	DEVMETHOD(device_suspend,   ahci_suspend),
885	DEVMETHOD(device_resume,    ahci_resume),
886	DEVMETHOD(bus_print_child,  ahci_print_child),
887	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
888	DEVMETHOD(bus_release_resource,     ahci_release_resource),
889	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
890	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
891	DEVMETHOD(bus_child_location_str, ahci_child_location_str),
892	{ 0, 0 }
893};
894static driver_t ahci_driver = {
895        "ahci",
896        ahci_methods,
897        sizeof(struct ahci_controller)
898};
899DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
900static device_method_t ahci_ata_methods[] = {
901	DEVMETHOD(device_probe,     ahci_ata_probe),
902	DEVMETHOD(device_attach,    ahci_attach),
903	DEVMETHOD(device_detach,    ahci_detach),
904	DEVMETHOD(device_suspend,   ahci_suspend),
905	DEVMETHOD(device_resume,    ahci_resume),
906	DEVMETHOD(bus_print_child,  ahci_print_child),
907	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
908	DEVMETHOD(bus_release_resource,     ahci_release_resource),
909	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
910	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
911	DEVMETHOD(bus_child_location_str, ahci_child_location_str),
912	{ 0, 0 }
913};
914static driver_t ahci_ata_driver = {
915        "ahci",
916        ahci_ata_methods,
917        sizeof(struct ahci_controller)
918};
919DRIVER_MODULE(ahci, atapci, ahci_ata_driver, ahci_devclass, 0, 0);
920MODULE_VERSION(ahci, 1);
921MODULE_DEPEND(ahci, cam, 1, 1, 1);
922
923static int
924ahci_ch_probe(device_t dev)
925{
926
927	device_set_desc_copy(dev, "AHCI channel");
928	return (0);
929}
930
931static int
932ahci_ch_attach(device_t dev)
933{
934	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
935	struct ahci_channel *ch = device_get_softc(dev);
936	struct cam_devq *devq;
937	int rid, error, i, sata_rev = 0;
938	u_int32_t version;
939
940	ch->dev = dev;
941	ch->unit = (intptr_t)device_get_ivars(dev);
942	ch->caps = ctlr->caps;
943	ch->caps2 = ctlr->caps2;
944	ch->quirks = ctlr->quirks;
945	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1;
946	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
947	resource_int_value(device_get_name(dev),
948	    device_get_unit(dev), "pm_level", &ch->pm_level);
949	if (ch->pm_level > 3)
950		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
951	callout_init_mtx(&ch->reset_timer, &ch->mtx, 0);
952	/* Limit speed for my onboard JMicron external port.
953	 * It is not eSATA really. */
954	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
955	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
956	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
957	    ch->unit == 0)
958		sata_rev = 1;
959	if (ch->quirks & AHCI_Q_SATA2)
960		sata_rev = 2;
961	resource_int_value(device_get_name(dev),
962	    device_get_unit(dev), "sata_rev", &sata_rev);
963	for (i = 0; i < 16; i++) {
964		ch->user[i].revision = sata_rev;
965		ch->user[i].mode = 0;
966		ch->user[i].bytecount = 8192;
967		ch->user[i].tags = ch->numslots;
968		ch->user[i].caps = 0;
969		ch->curr[i] = ch->user[i];
970		if (ch->pm_level) {
971			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
972			    CTS_SATA_CAPS_H_APST |
973			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
974		}
975		ch->user[i].caps |= CTS_SATA_CAPS_H_DMAAA |
976		    CTS_SATA_CAPS_H_AN;
977	}
978	rid = 0;
979	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
980	    &rid, RF_ACTIVE)))
981		return (ENXIO);
982	ahci_dmainit(dev);
983	ahci_slotsalloc(dev);
984	ahci_ch_init(dev);
985	mtx_lock(&ch->mtx);
986	rid = ATA_IRQ_RID;
987	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
988	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
989		device_printf(dev, "Unable to map interrupt\n");
990		error = ENXIO;
991		goto err0;
992	}
993	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
994	    ahci_ch_intr_locked, dev, &ch->ih))) {
995		device_printf(dev, "Unable to setup interrupt\n");
996		error = ENXIO;
997		goto err1;
998	}
999	ch->chcaps = ATA_INL(ch->r_mem, AHCI_P_CMD);
1000	version = ATA_INL(ctlr->r_mem, AHCI_VS);
1001	if (version < 0x00010200 && (ctlr->caps & AHCI_CAP_FBSS))
1002		ch->chcaps |= AHCI_P_CMD_FBSCP;
1003	if (bootverbose) {
1004		device_printf(dev, "Caps:%s%s%s%s%s\n",
1005		    (ch->chcaps & AHCI_P_CMD_HPCP) ? " HPCP":"",
1006		    (ch->chcaps & AHCI_P_CMD_MPSP) ? " MPSP":"",
1007		    (ch->chcaps & AHCI_P_CMD_CPD) ? " CPD":"",
1008		    (ch->chcaps & AHCI_P_CMD_ESP) ? " ESP":"",
1009		    (ch->chcaps & AHCI_P_CMD_FBSCP) ? " FBSCP":"");
1010	}
1011	/* Create the device queue for our SIM. */
1012	devq = cam_simq_alloc(ch->numslots);
1013	if (devq == NULL) {
1014		device_printf(dev, "Unable to allocate simq\n");
1015		error = ENOMEM;
1016		goto err1;
1017	}
1018	/* Construct SIM entry */
1019	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
1020	    device_get_unit(dev), &ch->mtx,
1021	    min(2, ch->numslots),
1022	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
1023	    devq);
1024	if (ch->sim == NULL) {
1025		cam_simq_free(devq);
1026		device_printf(dev, "unable to allocate sim\n");
1027		error = ENOMEM;
1028		goto err1;
1029	}
1030	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
1031		device_printf(dev, "unable to register xpt bus\n");
1032		error = ENXIO;
1033		goto err2;
1034	}
1035	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
1036	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1037		device_printf(dev, "unable to create path\n");
1038		error = ENXIO;
1039		goto err3;
1040	}
1041	if (ch->pm_level > 3) {
1042		callout_reset(&ch->pm_timer,
1043		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
1044		    ahci_ch_pm, dev);
1045	}
1046	mtx_unlock(&ch->mtx);
1047	return (0);
1048
1049err3:
1050	xpt_bus_deregister(cam_sim_path(ch->sim));
1051err2:
1052	cam_sim_free(ch->sim, /*free_devq*/TRUE);
1053err1:
1054	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
1055err0:
1056	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
1057	mtx_unlock(&ch->mtx);
1058	mtx_destroy(&ch->mtx);
1059	return (error);
1060}
1061
1062static int
1063ahci_ch_detach(device_t dev)
1064{
1065	struct ahci_channel *ch = device_get_softc(dev);
1066
1067	mtx_lock(&ch->mtx);
1068	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
1069	/* Forget about reset. */
1070	if (ch->resetting) {
1071		ch->resetting = 0;
1072		xpt_release_simq(ch->sim, TRUE);
1073	}
1074	xpt_free_path(ch->path);
1075	xpt_bus_deregister(cam_sim_path(ch->sim));
1076	cam_sim_free(ch->sim, /*free_devq*/TRUE);
1077	mtx_unlock(&ch->mtx);
1078
1079	if (ch->pm_level > 3)
1080		callout_drain(&ch->pm_timer);
1081	callout_drain(&ch->reset_timer);
1082	bus_teardown_intr(dev, ch->r_irq, ch->ih);
1083	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
1084
1085	ahci_ch_deinit(dev);
1086	ahci_slotsfree(dev);
1087	ahci_dmafini(dev);
1088
1089	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
1090	mtx_destroy(&ch->mtx);
1091	return (0);
1092}
1093
1094static int
1095ahci_ch_init(device_t dev)
1096{
1097	struct ahci_channel *ch = device_get_softc(dev);
1098	uint64_t work;
1099
1100	/* Disable port interrupts */
1101	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1102	/* Setup work areas */
1103	work = ch->dma.work_bus + AHCI_CL_OFFSET;
1104	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
1105	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
1106	work = ch->dma.rfis_bus;
1107	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
1108	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
1109	/* Activate the channel and power/spin up device */
1110	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
1111	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
1112	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
1113	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
1114	ahci_start_fr(dev);
1115	ahci_start(dev, 1);
1116	return (0);
1117}
1118
1119static int
1120ahci_ch_deinit(device_t dev)
1121{
1122	struct ahci_channel *ch = device_get_softc(dev);
1123
1124	/* Disable port interrupts. */
1125	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1126	/* Reset command register. */
1127	ahci_stop(dev);
1128	ahci_stop_fr(dev);
1129	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
1130	/* Allow everything, including partial and slumber modes. */
1131	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
1132	/* Request slumber mode transition and give some time to get there. */
1133	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
1134	DELAY(100);
1135	/* Disable PHY. */
1136	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
1137	return (0);
1138}
1139
1140static int
1141ahci_ch_suspend(device_t dev)
1142{
1143	struct ahci_channel *ch = device_get_softc(dev);
1144
1145	mtx_lock(&ch->mtx);
1146	xpt_freeze_simq(ch->sim, 1);
1147	/* Forget about reset. */
1148	if (ch->resetting) {
1149		ch->resetting = 0;
1150		callout_stop(&ch->reset_timer);
1151		xpt_release_simq(ch->sim, TRUE);
1152	}
1153	while (ch->oslots)
1154		msleep(ch, &ch->mtx, PRIBIO, "ahcisusp", hz/100);
1155	ahci_ch_deinit(dev);
1156	mtx_unlock(&ch->mtx);
1157	return (0);
1158}
1159
1160static int
1161ahci_ch_resume(device_t dev)
1162{
1163	struct ahci_channel *ch = device_get_softc(dev);
1164
1165	mtx_lock(&ch->mtx);
1166	ahci_ch_init(dev);
1167	ahci_reset(dev);
1168	xpt_release_simq(ch->sim, TRUE);
1169	mtx_unlock(&ch->mtx);
1170	return (0);
1171}
1172
1173devclass_t ahcich_devclass;
1174static device_method_t ahcich_methods[] = {
1175	DEVMETHOD(device_probe,     ahci_ch_probe),
1176	DEVMETHOD(device_attach,    ahci_ch_attach),
1177	DEVMETHOD(device_detach,    ahci_ch_detach),
1178	DEVMETHOD(device_suspend,   ahci_ch_suspend),
1179	DEVMETHOD(device_resume,    ahci_ch_resume),
1180	{ 0, 0 }
1181};
1182static driver_t ahcich_driver = {
1183        "ahcich",
1184        ahcich_methods,
1185        sizeof(struct ahci_channel)
1186};
1187DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahcich_devclass, 0, 0);
1188
1189struct ahci_dc_cb_args {
1190	bus_addr_t maddr;
1191	int error;
1192};
1193
1194static void
1195ahci_dmainit(device_t dev)
1196{
1197	struct ahci_channel *ch = device_get_softc(dev);
1198	struct ahci_dc_cb_args dcba;
1199	size_t rfsize;
1200
1201	if (ch->caps & AHCI_CAP_64BIT)
1202		ch->dma.max_address = BUS_SPACE_MAXADDR;
1203	else
1204		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
1205	/* Command area. */
1206	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
1207	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1208	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
1209	    0, NULL, NULL, &ch->dma.work_tag))
1210		goto error;
1211	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
1212	    &ch->dma.work_map))
1213		goto error;
1214	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
1215	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1216		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1217		goto error;
1218	}
1219	ch->dma.work_bus = dcba.maddr;
1220	/* FIS receive area. */
1221	if (ch->chcaps & AHCI_P_CMD_FBSCP)
1222	    rfsize = 4096;
1223	else
1224	    rfsize = 256;
1225	if (bus_dma_tag_create(bus_get_dma_tag(dev), rfsize, 0,
1226	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1227	    NULL, NULL, rfsize, 1, rfsize,
1228	    0, NULL, NULL, &ch->dma.rfis_tag))
1229		goto error;
1230	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1231	    &ch->dma.rfis_map))
1232		goto error;
1233	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1234	    rfsize, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1235		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1236		goto error;
1237	}
1238	ch->dma.rfis_bus = dcba.maddr;
1239	/* Data area. */
1240	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1241	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1242	    NULL, NULL,
1243	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
1244	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1245	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
1246		goto error;
1247	}
1248	return;
1249
1250error:
1251	device_printf(dev, "WARNING - DMA initialization failed\n");
1252	ahci_dmafini(dev);
1253}
1254
1255static void
1256ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1257{
1258	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1259
1260	if (!(dcba->error = error))
1261		dcba->maddr = segs[0].ds_addr;
1262}
1263
1264static void
1265ahci_dmafini(device_t dev)
1266{
1267	struct ahci_channel *ch = device_get_softc(dev);
1268
1269	if (ch->dma.data_tag) {
1270		bus_dma_tag_destroy(ch->dma.data_tag);
1271		ch->dma.data_tag = NULL;
1272	}
1273	if (ch->dma.rfis_bus) {
1274		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1275		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1276		ch->dma.rfis_bus = 0;
1277		ch->dma.rfis_map = NULL;
1278		ch->dma.rfis = NULL;
1279	}
1280	if (ch->dma.work_bus) {
1281		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1282		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1283		ch->dma.work_bus = 0;
1284		ch->dma.work_map = NULL;
1285		ch->dma.work = NULL;
1286	}
1287	if (ch->dma.work_tag) {
1288		bus_dma_tag_destroy(ch->dma.work_tag);
1289		ch->dma.work_tag = NULL;
1290	}
1291}
1292
1293static void
1294ahci_slotsalloc(device_t dev)
1295{
1296	struct ahci_channel *ch = device_get_softc(dev);
1297	int i;
1298
1299	/* Alloc and setup command/dma slots */
1300	bzero(ch->slot, sizeof(ch->slot));
1301	for (i = 0; i < ch->numslots; i++) {
1302		struct ahci_slot *slot = &ch->slot[i];
1303
1304		slot->dev = dev;
1305		slot->slot = i;
1306		slot->state = AHCI_SLOT_EMPTY;
1307		slot->ccb = NULL;
1308		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1309
1310		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1311			device_printf(ch->dev, "FAILURE - create data_map\n");
1312	}
1313}
1314
1315static void
1316ahci_slotsfree(device_t dev)
1317{
1318	struct ahci_channel *ch = device_get_softc(dev);
1319	int i;
1320
1321	/* Free all dma slots */
1322	for (i = 0; i < ch->numslots; i++) {
1323		struct ahci_slot *slot = &ch->slot[i];
1324
1325		callout_drain(&slot->timeout);
1326		if (slot->dma.data_map) {
1327			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1328			slot->dma.data_map = NULL;
1329		}
1330	}
1331}
1332
1333static int
1334ahci_phy_check_events(device_t dev, u_int32_t serr)
1335{
1336	struct ahci_channel *ch = device_get_softc(dev);
1337
1338	if (((ch->pm_level == 0) && (serr & ATA_SE_PHY_CHANGED)) ||
1339	    ((ch->pm_level != 0 || ch->listening) && (serr & ATA_SE_EXCHANGED))) {
1340		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1341		union ccb *ccb;
1342
1343		if (bootverbose) {
1344			if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
1345				device_printf(dev, "CONNECT requested\n");
1346			else
1347				device_printf(dev, "DISCONNECT requested\n");
1348		}
1349		ahci_reset(dev);
1350		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1351			return (0);
1352		if (xpt_create_path(&ccb->ccb_h.path, NULL,
1353		    cam_sim_path(ch->sim),
1354		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1355			xpt_free_ccb(ccb);
1356			return (0);
1357		}
1358		xpt_rescan(ccb);
1359		return (1);
1360	}
1361	return (0);
1362}
1363
1364static void
1365ahci_cpd_check_events(device_t dev)
1366{
1367	struct ahci_channel *ch = device_get_softc(dev);
1368	u_int32_t status;
1369	union ccb *ccb;
1370
1371	if (ch->pm_level == 0)
1372		return;
1373
1374	status = ATA_INL(ch->r_mem, AHCI_P_CMD);
1375	if ((status & AHCI_P_CMD_CPD) == 0)
1376		return;
1377
1378	if (bootverbose) {
1379		if (status & AHCI_P_CMD_CPS) {
1380			device_printf(dev, "COLD CONNECT requested\n");
1381		} else
1382			device_printf(dev, "COLD DISCONNECT requested\n");
1383	}
1384	ahci_reset(dev);
1385	if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1386		return;
1387	if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(ch->sim),
1388	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1389		xpt_free_ccb(ccb);
1390		return;
1391	}
1392	xpt_rescan(ccb);
1393}
1394
1395static void
1396ahci_notify_events(device_t dev, u_int32_t status)
1397{
1398	struct ahci_channel *ch = device_get_softc(dev);
1399	struct cam_path *dpath;
1400	int i;
1401
1402	if (ch->caps & AHCI_CAP_SSNTF)
1403		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1404	if (bootverbose)
1405		device_printf(dev, "SNTF 0x%04x\n", status);
1406	for (i = 0; i < 16; i++) {
1407		if ((status & (1 << i)) == 0)
1408			continue;
1409		if (xpt_create_path(&dpath, NULL,
1410		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1411			xpt_async(AC_SCSI_AEN, dpath, NULL);
1412			xpt_free_path(dpath);
1413		}
1414	}
1415}
1416
1417static void
1418ahci_ch_intr_locked(void *data)
1419{
1420	device_t dev = (device_t)data;
1421	struct ahci_channel *ch = device_get_softc(dev);
1422
1423	mtx_lock(&ch->mtx);
1424	xpt_batch_start(ch->sim);
1425	ahci_ch_intr(data);
1426	xpt_batch_done(ch->sim);
1427	mtx_unlock(&ch->mtx);
1428}
1429
1430static void
1431ahci_ch_pm(void *arg)
1432{
1433	device_t dev = (device_t)arg;
1434	struct ahci_channel *ch = device_get_softc(dev);
1435	uint32_t work;
1436
1437	if (ch->numrslots != 0)
1438		return;
1439	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1440	if (ch->pm_level == 4)
1441		work |= AHCI_P_CMD_PARTIAL;
1442	else
1443		work |= AHCI_P_CMD_SLUMBER;
1444	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1445}
1446
1447static void
1448ahci_ch_intr(void *data)
1449{
1450	device_t dev = (device_t)data;
1451	struct ahci_channel *ch = device_get_softc(dev);
1452	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1453	enum ahci_err_type et;
1454	int i, ccs, port, reset = 0;
1455
1456	/* Read and clear interrupt statuses. */
1457	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1458	if (istatus == 0)
1459		return;
1460	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1461	/* Read command statuses. */
1462	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1463	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1464	if (istatus & AHCI_P_IX_SDB) {
1465		if (ch->caps & AHCI_CAP_SSNTF)
1466			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1467		else if (ch->fbs_enabled) {
1468			u_int8_t *fis = ch->dma.rfis + 0x58;
1469
1470			for (i = 0; i < 16; i++) {
1471				if (fis[1] & 0x80) {
1472					fis[1] &= 0x7f;
1473	    				sntf |= 1 << i;
1474	    			}
1475	    			fis += 256;
1476	    		}
1477		} else {
1478			u_int8_t *fis = ch->dma.rfis + 0x58;
1479
1480			if (fis[1] & 0x80)
1481				sntf = (1 << (fis[1] & 0x0f));
1482		}
1483	}
1484	/* Process PHY events */
1485	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1486	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1487		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1488		if (serr) {
1489			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1490			reset = ahci_phy_check_events(dev, serr);
1491		}
1492	}
1493	/* Process cold presence detection events */
1494	if ((istatus & AHCI_P_IX_CPD) && !reset)
1495		ahci_cpd_check_events(dev);
1496	/* Process command errors */
1497	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1498	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1499		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1500		    >> AHCI_P_CMD_CCS_SHIFT;
1501//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1502//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1503//    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1504		port = -1;
1505		if (ch->fbs_enabled) {
1506			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1507			if (fbs & AHCI_P_FBS_SDE) {
1508				port = (fbs & AHCI_P_FBS_DWE)
1509				    >> AHCI_P_FBS_DWE_SHIFT;
1510			} else {
1511				for (i = 0; i < 16; i++) {
1512					if (ch->numrslotspd[i] == 0)
1513						continue;
1514					if (port == -1)
1515						port = i;
1516					else if (port != i) {
1517						port = -2;
1518						break;
1519					}
1520				}
1521			}
1522		}
1523		err = ch->rslots & (cstatus | sstatus);
1524	} else {
1525		ccs = 0;
1526		err = 0;
1527		port = -1;
1528	}
1529	/* Complete all successfull commands. */
1530	ok = ch->rslots & ~(cstatus | sstatus);
1531	for (i = 0; i < ch->numslots; i++) {
1532		if ((ok >> i) & 1)
1533			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1534	}
1535	/* On error, complete the rest of commands with error statuses. */
1536	if (err) {
1537		if (ch->frozen) {
1538			union ccb *fccb = ch->frozen;
1539			ch->frozen = NULL;
1540			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1541			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1542				xpt_freeze_devq(fccb->ccb_h.path, 1);
1543				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1544			}
1545			xpt_done(fccb);
1546		}
1547		for (i = 0; i < ch->numslots; i++) {
1548			/* XXX: reqests in loading state. */
1549			if (((err >> i) & 1) == 0)
1550				continue;
1551			if (port >= 0 &&
1552			    ch->slot[i].ccb->ccb_h.target_id != port)
1553				continue;
1554			if (istatus & AHCI_P_IX_TFE) {
1555			    if (port != -2) {
1556				/* Task File Error */
1557				if (ch->numtslotspd[
1558				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1559					/* Untagged operation. */
1560					if (i == ccs)
1561						et = AHCI_ERR_TFE;
1562					else
1563						et = AHCI_ERR_INNOCENT;
1564				} else {
1565					/* Tagged operation. */
1566					et = AHCI_ERR_NCQ;
1567				}
1568			    } else {
1569				et = AHCI_ERR_TFE;
1570				ch->fatalerr = 1;
1571			    }
1572			} else if (istatus & AHCI_P_IX_IF) {
1573				if (ch->numtslots == 0 && i != ccs && port != -2)
1574					et = AHCI_ERR_INNOCENT;
1575				else
1576					et = AHCI_ERR_SATA;
1577			} else
1578				et = AHCI_ERR_INVALID;
1579			ahci_end_transaction(&ch->slot[i], et);
1580		}
1581		/*
1582		 * We can't reinit port if there are some other
1583		 * commands active, use resume to complete them.
1584		 */
1585		if (ch->rslots != 0 && !ch->recoverycmd)
1586			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1587	}
1588	/* Process NOTIFY events */
1589	if (sntf)
1590		ahci_notify_events(dev, sntf);
1591}
1592
1593/* Must be called with channel locked. */
1594static int
1595ahci_check_collision(device_t dev, union ccb *ccb)
1596{
1597	struct ahci_channel *ch = device_get_softc(dev);
1598	int t = ccb->ccb_h.target_id;
1599
1600	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1601	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1602		/* Tagged command while we have no supported tag free. */
1603		if (((~ch->oslots) & (0xffffffff >> (32 -
1604		    ch->curr[t].tags))) == 0)
1605			return (1);
1606		/* If we have FBS */
1607		if (ch->fbs_enabled) {
1608			/* Tagged command while untagged are active. */
1609			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1610				return (1);
1611		} else {
1612			/* Tagged command while untagged are active. */
1613			if (ch->numrslots != 0 && ch->numtslots == 0)
1614				return (1);
1615			/* Tagged command while tagged to other target is active. */
1616			if (ch->numtslots != 0 &&
1617			    ch->taggedtarget != ccb->ccb_h.target_id)
1618				return (1);
1619		}
1620	} else {
1621		/* If we have FBS */
1622		if (ch->fbs_enabled) {
1623			/* Untagged command while tagged are active. */
1624			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1625				return (1);
1626		} else {
1627			/* Untagged command while tagged are active. */
1628			if (ch->numrslots != 0 && ch->numtslots != 0)
1629				return (1);
1630		}
1631	}
1632	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1633	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1634		/* Atomic command while anything active. */
1635		if (ch->numrslots != 0)
1636			return (1);
1637	}
1638       /* We have some atomic command running. */
1639       if (ch->aslots != 0)
1640               return (1);
1641	return (0);
1642}
1643
1644/* Must be called with channel locked. */
1645static void
1646ahci_begin_transaction(device_t dev, union ccb *ccb)
1647{
1648	struct ahci_channel *ch = device_get_softc(dev);
1649	struct ahci_slot *slot;
1650	int tag, tags;
1651
1652	/* Choose empty slot. */
1653	tags = ch->numslots;
1654	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1655	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1656		tags = ch->curr[ccb->ccb_h.target_id].tags;
1657	tag = ch->lastslot;
1658	while (1) {
1659		if (tag >= tags)
1660			tag = 0;
1661		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1662			break;
1663		tag++;
1664	};
1665	ch->lastslot = tag;
1666	/* Occupy chosen slot. */
1667	slot = &ch->slot[tag];
1668	slot->ccb = ccb;
1669	/* Stop PM timer. */
1670	if (ch->numrslots == 0 && ch->pm_level > 3)
1671		callout_stop(&ch->pm_timer);
1672	/* Update channel stats. */
1673	ch->oslots |= (1 << slot->slot);
1674	ch->numrslots++;
1675	ch->numrslotspd[ccb->ccb_h.target_id]++;
1676	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1677	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1678		ch->numtslots++;
1679		ch->numtslotspd[ccb->ccb_h.target_id]++;
1680		ch->taggedtarget = ccb->ccb_h.target_id;
1681	}
1682	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1683	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1684		ch->aslots |= (1 << slot->slot);
1685	slot->dma.nsegs = 0;
1686	/* If request moves data, setup and load SG list */
1687	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1688		void *buf;
1689		bus_size_t size;
1690
1691		slot->state = AHCI_SLOT_LOADING;
1692		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1693			buf = ccb->ataio.data_ptr;
1694			size = ccb->ataio.dxfer_len;
1695		} else {
1696			buf = ccb->csio.data_ptr;
1697			size = ccb->csio.dxfer_len;
1698		}
1699		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1700		    buf, size, ahci_dmasetprd, slot, 0);
1701	} else
1702		ahci_execute_transaction(slot);
1703}
1704
1705/* Locked by busdma engine. */
1706static void
1707ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1708{
1709	struct ahci_slot *slot = arg;
1710	struct ahci_channel *ch = device_get_softc(slot->dev);
1711	struct ahci_cmd_tab *ctp;
1712	struct ahci_dma_prd *prd;
1713	int i;
1714
1715	if (error) {
1716		device_printf(slot->dev, "DMA load error\n");
1717		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1718		return;
1719	}
1720	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1721	/* Get a piece of the workspace for this request */
1722	ctp = (struct ahci_cmd_tab *)
1723		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1724	/* Fill S/G table */
1725	prd = &ctp->prd_tab[0];
1726	for (i = 0; i < nsegs; i++) {
1727		prd[i].dba = htole64(segs[i].ds_addr);
1728		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1729	}
1730	slot->dma.nsegs = nsegs;
1731	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1732	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1733	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1734	ahci_execute_transaction(slot);
1735}
1736
1737/* Must be called with channel locked. */
1738static void
1739ahci_execute_transaction(struct ahci_slot *slot)
1740{
1741	device_t dev = slot->dev;
1742	struct ahci_channel *ch = device_get_softc(dev);
1743	struct ahci_cmd_tab *ctp;
1744	struct ahci_cmd_list *clp;
1745	union ccb *ccb = slot->ccb;
1746	int port = ccb->ccb_h.target_id & 0x0f;
1747	int fis_size, i, softreset;
1748	uint8_t *fis = ch->dma.rfis + 0x40;
1749	uint8_t val;
1750
1751	/* Get a piece of the workspace for this request */
1752	ctp = (struct ahci_cmd_tab *)
1753		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1754	/* Setup the FIS for this request */
1755	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1756		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1757		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1758		return;
1759	}
1760	/* Setup the command list entry */
1761	clp = (struct ahci_cmd_list *)
1762	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1763	clp->cmd_flags = htole16(
1764		    (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1765		    (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1766		     (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1767		    (fis_size / sizeof(u_int32_t)) |
1768		    (port << 12));
1769	clp->prd_length = htole16(slot->dma.nsegs);
1770	/* Special handling for Soft Reset command. */
1771	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1772	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1773		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1774			softreset = 1;
1775			/* Kick controller into sane state */
1776			ahci_stop(dev);
1777			ahci_clo(dev);
1778			ahci_start(dev, 0);
1779			clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1780		} else {
1781			softreset = 2;
1782			/* Prepare FIS receive area for check. */
1783			for (i = 0; i < 20; i++)
1784				fis[i] = 0xff;
1785		}
1786	} else
1787		softreset = 0;
1788	clp->bytecount = 0;
1789	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1790				  (AHCI_CT_SIZE * slot->slot));
1791	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1792	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1793	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1794	    BUS_DMASYNC_PREREAD);
1795	/* Set ACTIVE bit for NCQ commands. */
1796	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1797	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1798		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1799	}
1800	/* If FBS is enabled, set PMP port. */
1801	if (ch->fbs_enabled) {
1802		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1803		    (port << AHCI_P_FBS_DEV_SHIFT));
1804	}
1805	/* Issue command to the controller. */
1806	slot->state = AHCI_SLOT_RUNNING;
1807	ch->rslots |= (1 << slot->slot);
1808	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1809	/* Device reset commands doesn't interrupt. Poll them. */
1810	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1811	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET || softreset)) {
1812		int count, timeout = ccb->ccb_h.timeout * 100;
1813		enum ahci_err_type et = AHCI_ERR_NONE;
1814
1815		for (count = 0; count < timeout; count++) {
1816			DELAY(10);
1817			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1818				break;
1819			if ((ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) &&
1820			    softreset != 1) {
1821#if 0
1822				device_printf(ch->dev,
1823				    "Poll error on slot %d, TFD: %04x\n",
1824				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1825#endif
1826				et = AHCI_ERR_TFE;
1827				break;
1828			}
1829			/* Workaround for ATI SB600/SB700 chipsets. */
1830			if (ccb->ccb_h.target_id == 15 &&
1831			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1832			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1833				et = AHCI_ERR_TIMEOUT;
1834				break;
1835			}
1836		}
1837
1838		/* Marvell controllers do not wait for readyness. */
1839		if ((ch->quirks & AHCI_Q_NOBSYRES) && softreset == 2 &&
1840		    et == AHCI_ERR_NONE) {
1841			while ((val = fis[2]) & ATA_S_BUSY) {
1842				DELAY(10);
1843				if (count++ >= timeout)
1844					break;
1845			}
1846		}
1847
1848		if (timeout && (count >= timeout)) {
1849			device_printf(dev, "Poll timeout on slot %d port %d\n",
1850			    slot->slot, port);
1851			device_printf(dev, "is %08x cs %08x ss %08x "
1852			    "rs %08x tfd %02x serr %08x cmd %08x\n",
1853			    ATA_INL(ch->r_mem, AHCI_P_IS),
1854			    ATA_INL(ch->r_mem, AHCI_P_CI),
1855			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1856			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1857			    ATA_INL(ch->r_mem, AHCI_P_SERR),
1858			    ATA_INL(ch->r_mem, AHCI_P_CMD));
1859			et = AHCI_ERR_TIMEOUT;
1860		}
1861
1862		/* Kick controller into sane state and enable FBS. */
1863		if (softreset == 2)
1864			ch->eslots |= (1 << slot->slot);
1865		ahci_end_transaction(slot, et);
1866		return;
1867	}
1868	/* Start command execution timeout */
1869	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1870	    (timeout_t*)ahci_timeout, slot);
1871	return;
1872}
1873
1874/* Must be called with channel locked. */
1875static void
1876ahci_process_timeout(device_t dev)
1877{
1878	struct ahci_channel *ch = device_get_softc(dev);
1879	int i;
1880
1881	mtx_assert(&ch->mtx, MA_OWNED);
1882	/* Handle the rest of commands. */
1883	for (i = 0; i < ch->numslots; i++) {
1884		/* Do we have a running request on slot? */
1885		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1886			continue;
1887		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1888	}
1889}
1890
1891/* Must be called with channel locked. */
1892static void
1893ahci_rearm_timeout(device_t dev)
1894{
1895	struct ahci_channel *ch = device_get_softc(dev);
1896	int i;
1897
1898	mtx_assert(&ch->mtx, MA_OWNED);
1899	for (i = 0; i < ch->numslots; i++) {
1900		struct ahci_slot *slot = &ch->slot[i];
1901
1902		/* Do we have a running request on slot? */
1903		if (slot->state < AHCI_SLOT_RUNNING)
1904			continue;
1905		if ((ch->toslots & (1 << i)) == 0)
1906			continue;
1907		callout_reset(&slot->timeout,
1908		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1909		    (timeout_t*)ahci_timeout, slot);
1910	}
1911}
1912
1913/* Locked by callout mechanism. */
1914static void
1915ahci_timeout(struct ahci_slot *slot)
1916{
1917	device_t dev = slot->dev;
1918	struct ahci_channel *ch = device_get_softc(dev);
1919	uint32_t sstatus;
1920	int ccs;
1921	int i;
1922
1923	/* Check for stale timeout. */
1924	if (slot->state < AHCI_SLOT_RUNNING)
1925		return;
1926
1927	/* Check if slot was not being executed last time we checked. */
1928	if (slot->state < AHCI_SLOT_EXECUTING) {
1929		/* Check if slot started executing. */
1930		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1931		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1932		    >> AHCI_P_CMD_CCS_SHIFT;
1933		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1934		    ch->fbs_enabled || ch->wrongccs)
1935			slot->state = AHCI_SLOT_EXECUTING;
1936		else if ((ch->rslots & (1 << ccs)) == 0) {
1937			ch->wrongccs = 1;
1938			slot->state = AHCI_SLOT_EXECUTING;
1939		}
1940
1941		callout_reset(&slot->timeout,
1942		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1943		    (timeout_t*)ahci_timeout, slot);
1944		return;
1945	}
1946
1947	device_printf(dev, "Timeout on slot %d port %d\n",
1948	    slot->slot, slot->ccb->ccb_h.target_id & 0x0f);
1949	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x "
1950	    "serr %08x cmd %08x\n",
1951	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1952	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1953	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR),
1954	    ATA_INL(ch->r_mem, AHCI_P_CMD));
1955
1956	/* Handle frozen command. */
1957	if (ch->frozen) {
1958		union ccb *fccb = ch->frozen;
1959		ch->frozen = NULL;
1960		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1961		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1962			xpt_freeze_devq(fccb->ccb_h.path, 1);
1963			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1964		}
1965		xpt_done(fccb);
1966	}
1967	if (!ch->fbs_enabled && !ch->wrongccs) {
1968		/* Without FBS we know real timeout source. */
1969		ch->fatalerr = 1;
1970		/* Handle command with timeout. */
1971		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1972		/* Handle the rest of commands. */
1973		for (i = 0; i < ch->numslots; i++) {
1974			/* Do we have a running request on slot? */
1975			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1976				continue;
1977			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1978		}
1979	} else {
1980		/* With FBS we wait for other commands timeout and pray. */
1981		if (ch->toslots == 0)
1982			xpt_freeze_simq(ch->sim, 1);
1983		ch->toslots |= (1 << slot->slot);
1984		if ((ch->rslots & ~ch->toslots) == 0)
1985			ahci_process_timeout(dev);
1986		else
1987			device_printf(dev, " ... waiting for slots %08x\n",
1988			    ch->rslots & ~ch->toslots);
1989	}
1990}
1991
1992/* Must be called with channel locked. */
1993static void
1994ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1995{
1996	device_t dev = slot->dev;
1997	struct ahci_channel *ch = device_get_softc(dev);
1998	union ccb *ccb = slot->ccb;
1999	struct ahci_cmd_list *clp;
2000	int lastto;
2001	uint32_t sig;
2002
2003	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
2004	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2005	clp = (struct ahci_cmd_list *)
2006	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
2007	/* Read result registers to the result struct
2008	 * May be incorrect if several commands finished same time,
2009	 * so read only when sure or have to.
2010	 */
2011	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2012		struct ata_res *res = &ccb->ataio.res;
2013
2014		if ((et == AHCI_ERR_TFE) ||
2015		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
2016			u_int8_t *fis = ch->dma.rfis + 0x40;
2017
2018			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
2019			    BUS_DMASYNC_POSTREAD);
2020			if (ch->fbs_enabled) {
2021				fis += ccb->ccb_h.target_id * 256;
2022				res->status = fis[2];
2023				res->error = fis[3];
2024			} else {
2025				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
2026
2027				res->status = tfd;
2028				res->error = tfd >> 8;
2029			}
2030			res->lba_low = fis[4];
2031			res->lba_mid = fis[5];
2032			res->lba_high = fis[6];
2033			res->device = fis[7];
2034			res->lba_low_exp = fis[8];
2035			res->lba_mid_exp = fis[9];
2036			res->lba_high_exp = fis[10];
2037			res->sector_count = fis[12];
2038			res->sector_count_exp = fis[13];
2039
2040			/*
2041			 * Some weird controllers do not return signature in
2042			 * FIS receive area. Read it from PxSIG register.
2043			 */
2044			if ((ch->quirks & AHCI_Q_ALTSIG) &&
2045			    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
2046			    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
2047				sig = ATA_INL(ch->r_mem,  AHCI_P_SIG);
2048				res->lba_high = sig >> 24;
2049				res->lba_mid = sig >> 16;
2050				res->lba_low = sig >> 8;
2051				res->sector_count = sig;
2052			}
2053		} else
2054			bzero(res, sizeof(*res));
2055		if ((ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) == 0 &&
2056		    (ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2057		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
2058			ccb->ataio.resid =
2059			    ccb->ataio.dxfer_len - le32toh(clp->bytecount);
2060		}
2061	} else {
2062		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2063		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
2064			ccb->csio.resid =
2065			    ccb->csio.dxfer_len - le32toh(clp->bytecount);
2066		}
2067	}
2068	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2069		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
2070		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
2071		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
2072		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
2073	}
2074	if (et != AHCI_ERR_NONE)
2075		ch->eslots |= (1 << slot->slot);
2076	/* In case of error, freeze device for proper recovery. */
2077	if ((et != AHCI_ERR_NONE) && (!ch->recoverycmd) &&
2078	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
2079		xpt_freeze_devq(ccb->ccb_h.path, 1);
2080		ccb->ccb_h.status |= CAM_DEV_QFRZN;
2081	}
2082	/* Set proper result status. */
2083	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2084	switch (et) {
2085	case AHCI_ERR_NONE:
2086		ccb->ccb_h.status |= CAM_REQ_CMP;
2087		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
2088			ccb->csio.scsi_status = SCSI_STATUS_OK;
2089		break;
2090	case AHCI_ERR_INVALID:
2091		ch->fatalerr = 1;
2092		ccb->ccb_h.status |= CAM_REQ_INVALID;
2093		break;
2094	case AHCI_ERR_INNOCENT:
2095		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
2096		break;
2097	case AHCI_ERR_TFE:
2098	case AHCI_ERR_NCQ:
2099		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2100			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
2101			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2102		} else {
2103			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
2104		}
2105		break;
2106	case AHCI_ERR_SATA:
2107		ch->fatalerr = 1;
2108		if (!ch->recoverycmd) {
2109			xpt_freeze_simq(ch->sim, 1);
2110			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2111			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2112		}
2113		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
2114		break;
2115	case AHCI_ERR_TIMEOUT:
2116		if (!ch->recoverycmd) {
2117			xpt_freeze_simq(ch->sim, 1);
2118			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2119			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2120		}
2121		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
2122		break;
2123	default:
2124		ch->fatalerr = 1;
2125		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2126	}
2127	/* Free slot. */
2128	ch->oslots &= ~(1 << slot->slot);
2129	ch->rslots &= ~(1 << slot->slot);
2130	ch->aslots &= ~(1 << slot->slot);
2131	slot->state = AHCI_SLOT_EMPTY;
2132	slot->ccb = NULL;
2133	/* Update channel stats. */
2134	ch->numrslots--;
2135	ch->numrslotspd[ccb->ccb_h.target_id]--;
2136	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2137	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
2138		ch->numtslots--;
2139		ch->numtslotspd[ccb->ccb_h.target_id]--;
2140	}
2141	/* Cancel timeout state if request completed normally. */
2142	if (et != AHCI_ERR_TIMEOUT) {
2143		lastto = (ch->toslots == (1 << slot->slot));
2144		ch->toslots &= ~(1 << slot->slot);
2145		if (lastto)
2146			xpt_release_simq(ch->sim, TRUE);
2147	}
2148	/* If it was first request of reset sequence and there is no error,
2149	 * proceed to second request. */
2150	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2151	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
2152	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
2153	    et == AHCI_ERR_NONE) {
2154		ccb->ataio.cmd.control &= ~ATA_A_RESET;
2155		ahci_begin_transaction(dev, ccb);
2156		return;
2157	}
2158	/* If it was our READ LOG command - process it. */
2159	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
2160		ahci_process_read_log(dev, ccb);
2161	/* If it was our REQUEST SENSE command - process it. */
2162	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
2163		ahci_process_request_sense(dev, ccb);
2164	/* If it was NCQ or ATAPI command error, put result on hold. */
2165	} else if (et == AHCI_ERR_NCQ ||
2166	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
2167	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
2168		ch->hold[slot->slot] = ccb;
2169		ch->numhslots++;
2170	} else
2171		xpt_done(ccb);
2172	/* If we have no other active commands, ... */
2173	if (ch->rslots == 0) {
2174		/* if there was fatal error - reset port. */
2175		if (ch->toslots != 0 || ch->fatalerr) {
2176			ahci_reset(dev);
2177		} else {
2178			/* if we have slots in error, we can reinit port. */
2179			if (ch->eslots != 0) {
2180				ahci_stop(dev);
2181				ahci_clo(dev);
2182				ahci_start(dev, 1);
2183			}
2184			/* if there commands on hold, we can do READ LOG. */
2185			if (!ch->recoverycmd && ch->numhslots)
2186				ahci_issue_recovery(dev);
2187		}
2188	/* If all the rest of commands are in timeout - give them chance. */
2189	} else if ((ch->rslots & ~ch->toslots) == 0 &&
2190	    et != AHCI_ERR_TIMEOUT)
2191		ahci_rearm_timeout(dev);
2192	/* Unfreeze frozen command. */
2193	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
2194		union ccb *fccb = ch->frozen;
2195		ch->frozen = NULL;
2196		ahci_begin_transaction(dev, fccb);
2197		xpt_release_simq(ch->sim, TRUE);
2198	}
2199	/* Start PM timer. */
2200	if (ch->numrslots == 0 && ch->pm_level > 3 &&
2201	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
2202		callout_schedule(&ch->pm_timer,
2203		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
2204	}
2205}
2206
2207static void
2208ahci_issue_recovery(device_t dev)
2209{
2210	struct ahci_channel *ch = device_get_softc(dev);
2211	union ccb *ccb;
2212	struct ccb_ataio *ataio;
2213	struct ccb_scsiio *csio;
2214	int i;
2215
2216	/* Find some held command. */
2217	for (i = 0; i < ch->numslots; i++) {
2218		if (ch->hold[i])
2219			break;
2220	}
2221	ccb = xpt_alloc_ccb_nowait();
2222	if (ccb == NULL) {
2223		device_printf(dev, "Unable to allocate recovery command\n");
2224completeall:
2225		/* We can't do anything -- complete held commands. */
2226		for (i = 0; i < ch->numslots; i++) {
2227			if (ch->hold[i] == NULL)
2228				continue;
2229			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2230			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
2231			xpt_done(ch->hold[i]);
2232			ch->hold[i] = NULL;
2233			ch->numhslots--;
2234		}
2235		ahci_reset(dev);
2236		return;
2237	}
2238	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
2239	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2240		/* READ LOG */
2241		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
2242		ccb->ccb_h.func_code = XPT_ATA_IO;
2243		ccb->ccb_h.flags = CAM_DIR_IN;
2244		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2245		ataio = &ccb->ataio;
2246		ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
2247		if (ataio->data_ptr == NULL) {
2248			xpt_free_ccb(ccb);
2249			device_printf(dev,
2250			    "Unable to allocate memory for READ LOG command\n");
2251			goto completeall;
2252		}
2253		ataio->dxfer_len = 512;
2254		bzero(&ataio->cmd, sizeof(ataio->cmd));
2255		ataio->cmd.flags = CAM_ATAIO_48BIT;
2256		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
2257		ataio->cmd.sector_count = 1;
2258		ataio->cmd.sector_count_exp = 0;
2259		ataio->cmd.lba_low = 0x10;
2260		ataio->cmd.lba_mid = 0;
2261		ataio->cmd.lba_mid_exp = 0;
2262	} else {
2263		/* REQUEST SENSE */
2264		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
2265		ccb->ccb_h.recovery_slot = i;
2266		ccb->ccb_h.func_code = XPT_SCSI_IO;
2267		ccb->ccb_h.flags = CAM_DIR_IN;
2268		ccb->ccb_h.status = 0;
2269		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2270		csio = &ccb->csio;
2271		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
2272		csio->dxfer_len = ch->hold[i]->csio.sense_len;
2273		csio->cdb_len = 6;
2274		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
2275		csio->cdb_io.cdb_bytes[0] = 0x03;
2276		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
2277	}
2278	/* Freeze SIM while doing recovery. */
2279	ch->recoverycmd = 1;
2280	xpt_freeze_simq(ch->sim, 1);
2281	ahci_begin_transaction(dev, ccb);
2282}
2283
2284static void
2285ahci_process_read_log(device_t dev, union ccb *ccb)
2286{
2287	struct ahci_channel *ch = device_get_softc(dev);
2288	uint8_t *data;
2289	struct ata_res *res;
2290	int i;
2291
2292	ch->recoverycmd = 0;
2293
2294	data = ccb->ataio.data_ptr;
2295	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2296	    (data[0] & 0x80) == 0) {
2297		for (i = 0; i < ch->numslots; i++) {
2298			if (!ch->hold[i])
2299				continue;
2300			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2301				continue;
2302			if ((data[0] & 0x1F) == i) {
2303				res = &ch->hold[i]->ataio.res;
2304				res->status = data[2];
2305				res->error = data[3];
2306				res->lba_low = data[4];
2307				res->lba_mid = data[5];
2308				res->lba_high = data[6];
2309				res->device = data[7];
2310				res->lba_low_exp = data[8];
2311				res->lba_mid_exp = data[9];
2312				res->lba_high_exp = data[10];
2313				res->sector_count = data[12];
2314				res->sector_count_exp = data[13];
2315			} else {
2316				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2317				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2318			}
2319			xpt_done(ch->hold[i]);
2320			ch->hold[i] = NULL;
2321			ch->numhslots--;
2322		}
2323	} else {
2324		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2325			device_printf(dev, "Error while READ LOG EXT\n");
2326		else if ((data[0] & 0x80) == 0) {
2327			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
2328		}
2329		for (i = 0; i < ch->numslots; i++) {
2330			if (!ch->hold[i])
2331				continue;
2332			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2333				continue;
2334			xpt_done(ch->hold[i]);
2335			ch->hold[i] = NULL;
2336			ch->numhslots--;
2337		}
2338	}
2339	free(ccb->ataio.data_ptr, M_AHCI);
2340	xpt_free_ccb(ccb);
2341	xpt_release_simq(ch->sim, TRUE);
2342}
2343
2344static void
2345ahci_process_request_sense(device_t dev, union ccb *ccb)
2346{
2347	struct ahci_channel *ch = device_get_softc(dev);
2348	int i;
2349
2350	ch->recoverycmd = 0;
2351
2352	i = ccb->ccb_h.recovery_slot;
2353	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2354		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
2355	} else {
2356		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2357		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
2358	}
2359	xpt_done(ch->hold[i]);
2360	ch->hold[i] = NULL;
2361	ch->numhslots--;
2362	xpt_free_ccb(ccb);
2363	xpt_release_simq(ch->sim, TRUE);
2364}
2365
2366static void
2367ahci_start(device_t dev, int fbs)
2368{
2369	struct ahci_channel *ch = device_get_softc(dev);
2370	u_int32_t cmd;
2371
2372	/* Clear SATA error register */
2373	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2374	/* Clear any interrupts pending on this channel */
2375	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2376	/* Configure FIS-based switching if supported. */
2377	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2378		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2379		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2380		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2381	}
2382	/* Start operations on this channel */
2383	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2384	cmd &= ~AHCI_P_CMD_PMA;
2385	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2386	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2387}
2388
2389static void
2390ahci_stop(device_t dev)
2391{
2392	struct ahci_channel *ch = device_get_softc(dev);
2393	u_int32_t cmd;
2394	int timeout;
2395
2396	/* Kill all activity on this channel */
2397	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2398	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2399	/* Wait for activity stop. */
2400	timeout = 0;
2401	do {
2402		DELAY(10);
2403		if (timeout++ > 50000) {
2404			device_printf(dev, "stopping AHCI engine failed\n");
2405			break;
2406		}
2407	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2408	ch->eslots = 0;
2409}
2410
2411static void
2412ahci_clo(device_t dev)
2413{
2414	struct ahci_channel *ch = device_get_softc(dev);
2415	u_int32_t cmd;
2416	int timeout;
2417
2418	/* Issue Command List Override if supported */
2419	if (ch->caps & AHCI_CAP_SCLO) {
2420		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2421		cmd |= AHCI_P_CMD_CLO;
2422		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2423		timeout = 0;
2424		do {
2425			DELAY(10);
2426			if (timeout++ > 50000) {
2427			    device_printf(dev, "executing CLO failed\n");
2428			    break;
2429			}
2430		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2431	}
2432}
2433
2434static void
2435ahci_stop_fr(device_t dev)
2436{
2437	struct ahci_channel *ch = device_get_softc(dev);
2438	u_int32_t cmd;
2439	int timeout;
2440
2441	/* Kill all FIS reception on this channel */
2442	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2443	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2444	/* Wait for FIS reception stop. */
2445	timeout = 0;
2446	do {
2447		DELAY(10);
2448		if (timeout++ > 50000) {
2449			device_printf(dev, "stopping AHCI FR engine failed\n");
2450			break;
2451		}
2452	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2453}
2454
2455static void
2456ahci_start_fr(device_t dev)
2457{
2458	struct ahci_channel *ch = device_get_softc(dev);
2459	u_int32_t cmd;
2460
2461	/* Start FIS reception on this channel */
2462	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2463	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2464}
2465
2466static int
2467ahci_wait_ready(device_t dev, int t, int t0)
2468{
2469	struct ahci_channel *ch = device_get_softc(dev);
2470	int timeout = 0;
2471	uint32_t val;
2472
2473	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2474	    (ATA_S_BUSY | ATA_S_DRQ)) {
2475		if (timeout > t) {
2476			if (t != 0) {
2477				device_printf(dev,
2478				    "AHCI reset: device not ready after %dms "
2479				    "(tfd = %08x)\n",
2480				    MAX(t, 0) + t0, val);
2481			}
2482			return (EBUSY);
2483		}
2484		DELAY(1000);
2485		timeout++;
2486	}
2487	if (bootverbose)
2488		device_printf(dev, "AHCI reset: device ready after %dms\n",
2489		    timeout + t0);
2490	return (0);
2491}
2492
2493static void
2494ahci_reset_to(void *arg)
2495{
2496	device_t dev = arg;
2497	struct ahci_channel *ch = device_get_softc(dev);
2498
2499	if (ch->resetting == 0)
2500		return;
2501	ch->resetting--;
2502	if (ahci_wait_ready(dev, ch->resetting == 0 ? -1 : 0,
2503	    (310 - ch->resetting) * 100) == 0) {
2504		ch->resetting = 0;
2505		ahci_start(dev, 1);
2506		xpt_release_simq(ch->sim, TRUE);
2507		return;
2508	}
2509	if (ch->resetting == 0) {
2510		ahci_clo(dev);
2511		ahci_start(dev, 1);
2512		xpt_release_simq(ch->sim, TRUE);
2513		return;
2514	}
2515	callout_schedule(&ch->reset_timer, hz / 10);
2516}
2517
2518static void
2519ahci_reset(device_t dev)
2520{
2521	struct ahci_channel *ch = device_get_softc(dev);
2522	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
2523	int i;
2524
2525	xpt_freeze_simq(ch->sim, 1);
2526	if (bootverbose)
2527		device_printf(dev, "AHCI reset...\n");
2528	/* Forget about previous reset. */
2529	if (ch->resetting) {
2530		ch->resetting = 0;
2531		callout_stop(&ch->reset_timer);
2532		xpt_release_simq(ch->sim, TRUE);
2533	}
2534	/* Requeue freezed command. */
2535	if (ch->frozen) {
2536		union ccb *fccb = ch->frozen;
2537		ch->frozen = NULL;
2538		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2539		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2540			xpt_freeze_devq(fccb->ccb_h.path, 1);
2541			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2542		}
2543		xpt_done(fccb);
2544	}
2545	/* Kill the engine and requeue all running commands. */
2546	ahci_stop(dev);
2547	for (i = 0; i < ch->numslots; i++) {
2548		/* Do we have a running request on slot? */
2549		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2550			continue;
2551		/* XXX; Commands in loading state. */
2552		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2553	}
2554	for (i = 0; i < ch->numslots; i++) {
2555		if (!ch->hold[i])
2556			continue;
2557		xpt_done(ch->hold[i]);
2558		ch->hold[i] = NULL;
2559		ch->numhslots--;
2560	}
2561	if (ch->toslots != 0)
2562		xpt_release_simq(ch->sim, TRUE);
2563	ch->eslots = 0;
2564	ch->toslots = 0;
2565	ch->wrongccs = 0;
2566	ch->fatalerr = 0;
2567	/* Tell the XPT about the event */
2568	xpt_async(AC_BUS_RESET, ch->path, NULL);
2569	/* Disable port interrupts */
2570	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2571	/* Reset and reconnect PHY, */
2572	if (!ahci_sata_phy_reset(dev)) {
2573		if (bootverbose)
2574			device_printf(dev,
2575			    "AHCI reset: device not found\n");
2576		ch->devices = 0;
2577		/* Enable wanted port interrupts */
2578		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2579		    (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2580		     AHCI_P_IX_PRC | AHCI_P_IX_PC));
2581		xpt_release_simq(ch->sim, TRUE);
2582		return;
2583	}
2584	if (bootverbose)
2585		device_printf(dev, "AHCI reset: device found\n");
2586	/* Wait for clearing busy status. */
2587	if (ahci_wait_ready(dev, dumping ? 31000 : 0, 0)) {
2588		if (dumping)
2589			ahci_clo(dev);
2590		else
2591			ch->resetting = 310;
2592	}
2593	ch->devices = 1;
2594	/* Enable wanted port interrupts */
2595	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2596	     (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2597	      AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2598	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2599	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC : 0) | AHCI_P_IX_PC |
2600	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2601	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2602	if (ch->resetting)
2603		callout_reset(&ch->reset_timer, hz / 10, ahci_reset_to, dev);
2604	else {
2605		ahci_start(dev, 1);
2606		xpt_release_simq(ch->sim, TRUE);
2607	}
2608}
2609
2610static int
2611ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2612{
2613	struct ahci_channel *ch = device_get_softc(dev);
2614	u_int8_t *fis = &ctp->cfis[0];
2615
2616	bzero(ctp->cfis, 64);
2617	fis[0] = 0x27;  		/* host to device */
2618	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2619	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2620		fis[1] |= 0x80;
2621		fis[2] = ATA_PACKET_CMD;
2622		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2623		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2624			fis[3] = ATA_F_DMA;
2625		else {
2626			fis[5] = ccb->csio.dxfer_len;
2627		        fis[6] = ccb->csio.dxfer_len >> 8;
2628		}
2629		fis[7] = ATA_D_LBA;
2630		fis[15] = ATA_A_4BIT;
2631		bzero(ctp->acmd, 32);
2632		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2633		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2634		    ctp->acmd, ccb->csio.cdb_len);
2635	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2636		fis[1] |= 0x80;
2637		fis[2] = ccb->ataio.cmd.command;
2638		fis[3] = ccb->ataio.cmd.features;
2639		fis[4] = ccb->ataio.cmd.lba_low;
2640		fis[5] = ccb->ataio.cmd.lba_mid;
2641		fis[6] = ccb->ataio.cmd.lba_high;
2642		fis[7] = ccb->ataio.cmd.device;
2643		fis[8] = ccb->ataio.cmd.lba_low_exp;
2644		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2645		fis[10] = ccb->ataio.cmd.lba_high_exp;
2646		fis[11] = ccb->ataio.cmd.features_exp;
2647		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2648			fis[12] = tag << 3;
2649			fis[13] = 0;
2650		} else {
2651			fis[12] = ccb->ataio.cmd.sector_count;
2652			fis[13] = ccb->ataio.cmd.sector_count_exp;
2653		}
2654		fis[15] = ATA_A_4BIT;
2655	} else {
2656		fis[15] = ccb->ataio.cmd.control;
2657	}
2658	return (20);
2659}
2660
2661static int
2662ahci_sata_connect(struct ahci_channel *ch)
2663{
2664	u_int32_t status;
2665	int timeout, found = 0;
2666
2667	/* Wait up to 100ms for "connect well" */
2668	for (timeout = 0; timeout < 1000 ; timeout++) {
2669		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2670		if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
2671			found = 1;
2672		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2673		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2674		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2675			break;
2676		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2677			if (bootverbose) {
2678				device_printf(ch->dev, "SATA offline status=%08x\n",
2679				    status);
2680			}
2681			return (0);
2682		}
2683		if (found == 0 && timeout >= 100)
2684			break;
2685		DELAY(100);
2686	}
2687	if (timeout >= 1000 || !found) {
2688		if (bootverbose) {
2689			device_printf(ch->dev,
2690			    "SATA connect timeout time=%dus status=%08x\n",
2691			    timeout * 100, status);
2692		}
2693		return (0);
2694	}
2695	if (bootverbose) {
2696		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2697		    timeout * 100, status);
2698	}
2699	/* Clear SATA error register */
2700	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2701	return (1);
2702}
2703
2704static int
2705ahci_sata_phy_reset(device_t dev)
2706{
2707	struct ahci_channel *ch = device_get_softc(dev);
2708	int sata_rev;
2709	uint32_t val;
2710
2711	if (ch->listening) {
2712		val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2713		val |= AHCI_P_CMD_SUD;
2714		ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2715		ch->listening = 0;
2716	}
2717	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2718	if (sata_rev == 1)
2719		val = ATA_SC_SPD_SPEED_GEN1;
2720	else if (sata_rev == 2)
2721		val = ATA_SC_SPD_SPEED_GEN2;
2722	else if (sata_rev == 3)
2723		val = ATA_SC_SPD_SPEED_GEN3;
2724	else
2725		val = 0;
2726	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2727	    ATA_SC_DET_RESET | val |
2728	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2729	DELAY(1000);
2730	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2731	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2732	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2733	if (!ahci_sata_connect(ch)) {
2734		if (ch->caps & AHCI_CAP_SSS) {
2735			val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2736			val &= ~AHCI_P_CMD_SUD;
2737			ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2738			ch->listening = 1;
2739		} else if (ch->pm_level > 0)
2740			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2741		return (0);
2742	}
2743	return (1);
2744}
2745
2746static int
2747ahci_check_ids(device_t dev, union ccb *ccb)
2748{
2749	struct ahci_channel *ch = device_get_softc(dev);
2750
2751	if (ccb->ccb_h.target_id > ((ch->caps & AHCI_CAP_SPM) ? 15 : 0)) {
2752		ccb->ccb_h.status = CAM_TID_INVALID;
2753		xpt_done(ccb);
2754		return (-1);
2755	}
2756	if (ccb->ccb_h.target_lun != 0) {
2757		ccb->ccb_h.status = CAM_LUN_INVALID;
2758		xpt_done(ccb);
2759		return (-1);
2760	}
2761	return (0);
2762}
2763
2764static void
2765ahciaction(struct cam_sim *sim, union ccb *ccb)
2766{
2767	device_t dev, parent;
2768	struct ahci_channel *ch;
2769
2770	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2771	    ccb->ccb_h.func_code));
2772
2773	ch = (struct ahci_channel *)cam_sim_softc(sim);
2774	dev = ch->dev;
2775	switch (ccb->ccb_h.func_code) {
2776	/* Common cases first */
2777	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2778	case XPT_SCSI_IO:
2779		if (ahci_check_ids(dev, ccb))
2780			return;
2781		if (ch->devices == 0 ||
2782		    (ch->pm_present == 0 &&
2783		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2784			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2785			break;
2786		}
2787		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2788		/* Check for command collision. */
2789		if (ahci_check_collision(dev, ccb)) {
2790			/* Freeze command. */
2791			ch->frozen = ccb;
2792			/* We have only one frozen slot, so freeze simq also. */
2793			xpt_freeze_simq(ch->sim, 1);
2794			return;
2795		}
2796		ahci_begin_transaction(dev, ccb);
2797		return;
2798	case XPT_EN_LUN:		/* Enable LUN as a target */
2799	case XPT_TARGET_IO:		/* Execute target I/O request */
2800	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2801	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2802	case XPT_ABORT:			/* Abort the specified CCB */
2803		/* XXX Implement */
2804		ccb->ccb_h.status = CAM_REQ_INVALID;
2805		break;
2806	case XPT_SET_TRAN_SETTINGS:
2807	{
2808		struct	ccb_trans_settings *cts = &ccb->cts;
2809		struct	ahci_device *d;
2810
2811		if (ahci_check_ids(dev, ccb))
2812			return;
2813		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2814			d = &ch->curr[ccb->ccb_h.target_id];
2815		else
2816			d = &ch->user[ccb->ccb_h.target_id];
2817		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2818			d->revision = cts->xport_specific.sata.revision;
2819		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2820			d->mode = cts->xport_specific.sata.mode;
2821		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2822			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2823		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2824			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2825		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2826			ch->pm_present = cts->xport_specific.sata.pm_present;
2827		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2828			d->atapi = cts->xport_specific.sata.atapi;
2829		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2830			d->caps = cts->xport_specific.sata.caps;
2831		ccb->ccb_h.status = CAM_REQ_CMP;
2832		break;
2833	}
2834	case XPT_GET_TRAN_SETTINGS:
2835	/* Get default/user set transfer settings for the target */
2836	{
2837		struct	ccb_trans_settings *cts = &ccb->cts;
2838		struct  ahci_device *d;
2839		uint32_t status;
2840
2841		if (ahci_check_ids(dev, ccb))
2842			return;
2843		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2844			d = &ch->curr[ccb->ccb_h.target_id];
2845		else
2846			d = &ch->user[ccb->ccb_h.target_id];
2847		cts->protocol = PROTO_UNSPECIFIED;
2848		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2849		cts->transport = XPORT_SATA;
2850		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2851		cts->proto_specific.valid = 0;
2852		cts->xport_specific.sata.valid = 0;
2853		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2854		    (ccb->ccb_h.target_id == 15 ||
2855		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2856			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2857			if (status & 0x0f0) {
2858				cts->xport_specific.sata.revision =
2859				    (status & 0x0f0) >> 4;
2860				cts->xport_specific.sata.valid |=
2861				    CTS_SATA_VALID_REVISION;
2862			}
2863			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2864			if (ch->pm_level) {
2865				if (ch->caps & (AHCI_CAP_PSC | AHCI_CAP_SSC))
2866					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2867				if (ch->caps2 & AHCI_CAP2_APST)
2868					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_APST;
2869			}
2870			if ((ch->caps & AHCI_CAP_SNCQ) &&
2871			    (ch->quirks & AHCI_Q_NOAA) == 0)
2872				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_DMAAA;
2873			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2874			cts->xport_specific.sata.caps &=
2875			    ch->user[ccb->ccb_h.target_id].caps;
2876			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2877		} else {
2878			cts->xport_specific.sata.revision = d->revision;
2879			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2880			cts->xport_specific.sata.caps = d->caps;
2881			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2882		}
2883		cts->xport_specific.sata.mode = d->mode;
2884		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2885		cts->xport_specific.sata.bytecount = d->bytecount;
2886		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2887		cts->xport_specific.sata.pm_present = ch->pm_present;
2888		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2889		cts->xport_specific.sata.tags = d->tags;
2890		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2891		cts->xport_specific.sata.atapi = d->atapi;
2892		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2893		ccb->ccb_h.status = CAM_REQ_CMP;
2894		break;
2895	}
2896	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2897	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2898		ahci_reset(dev);
2899		ccb->ccb_h.status = CAM_REQ_CMP;
2900		break;
2901	case XPT_TERM_IO:		/* Terminate the I/O process */
2902		/* XXX Implement */
2903		ccb->ccb_h.status = CAM_REQ_INVALID;
2904		break;
2905	case XPT_PATH_INQ:		/* Path routing inquiry */
2906	{
2907		struct ccb_pathinq *cpi = &ccb->cpi;
2908
2909		parent = device_get_parent(dev);
2910		cpi->version_num = 1; /* XXX??? */
2911		cpi->hba_inquiry = PI_SDTR_ABLE;
2912		if (ch->caps & AHCI_CAP_SNCQ)
2913			cpi->hba_inquiry |= PI_TAG_ABLE;
2914		if (ch->caps & AHCI_CAP_SPM)
2915			cpi->hba_inquiry |= PI_SATAPM;
2916		cpi->target_sprt = 0;
2917		cpi->hba_misc = PIM_SEQSCAN;
2918		cpi->hba_eng_cnt = 0;
2919		if (ch->caps & AHCI_CAP_SPM)
2920			cpi->max_target = 15;
2921		else
2922			cpi->max_target = 0;
2923		cpi->max_lun = 0;
2924		cpi->initiator_id = 0;
2925		cpi->bus_id = cam_sim_bus(sim);
2926		cpi->base_transfer_speed = 150000;
2927		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2928		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2929		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2930		cpi->unit_number = cam_sim_unit(sim);
2931		cpi->transport = XPORT_SATA;
2932		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2933		cpi->protocol = PROTO_ATA;
2934		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2935		cpi->maxio = MAXPHYS;
2936		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2937		if (pci_get_devid(parent) == 0x43801002)
2938			cpi->maxio = min(cpi->maxio, 128 * 512);
2939		cpi->hba_vendor = pci_get_vendor(parent);
2940		cpi->hba_device = pci_get_device(parent);
2941		cpi->hba_subvendor = pci_get_subvendor(parent);
2942		cpi->hba_subdevice = pci_get_subdevice(parent);
2943		cpi->ccb_h.status = CAM_REQ_CMP;
2944		break;
2945	}
2946	default:
2947		ccb->ccb_h.status = CAM_REQ_INVALID;
2948		break;
2949	}
2950	xpt_done(ccb);
2951}
2952
2953static void
2954ahcipoll(struct cam_sim *sim)
2955{
2956	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2957
2958	ahci_ch_intr(ch->dev);
2959	if (ch->resetting != 0 &&
2960	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2961		ch->resetpolldiv = 1000;
2962		ahci_reset_to(ch->dev);
2963	}
2964}
2965