ahci_pci.c revision 239907
183553Smurray/*-
283553Smurray * Copyright (c) 2009-2012 Alexander Motin <mav@FreeBSD.org>
383553Smurray * All rights reserved.
483553Smurray *
583553Smurray * Redistribution and use in source and binary forms, with or without
683553Smurray * modification, are permitted provided that the following conditions
783553Smurray * are met:
883553Smurray * 1. Redistributions of source code must retain the above copyright
983553Smurray *    notice, this list of conditions and the following disclaimer,
1083553Smurray *    without modification, immediately at the beginning of the file.
1183553Smurray * 2. Redistributions in binary form must reproduce the above copyright
1283553Smurray *    notice, this list of conditions and the following disclaimer in the
1383553Smurray *    documentation and/or other materials provided with the distribution.
1483553Smurray *
1583553Smurray * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1683553Smurray * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1783553Smurray * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1883553Smurray * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1983553Smurray * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2083553Smurray * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2183553Smurray * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2283553Smurray * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2383553Smurray * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2483553Smurray * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2583553Smurray */
2683553Smurray
2783553Smurray#include <sys/cdefs.h>
2883553Smurray__FBSDID("$FreeBSD: head/sys/dev/ahci/ahci.c 239907 2012-08-30 15:23:59Z mav $");
2983553Smurray
3083553Smurray#include <sys/param.h>
3183553Smurray#include <sys/module.h>
3283553Smurray#include <sys/systm.h>
3383553Smurray#include <sys/kernel.h>
3483553Smurray#include <sys/bus.h>
35116192Sobrien#include <sys/conf.h>
36116192Sobrien#include <sys/endian.h>
37116192Sobrien#include <sys/malloc.h>
3883553Smurray#include <sys/lock.h>
3983553Smurray#include <sys/mutex.h>
4083553Smurray#include <machine/stdarg.h>
4183553Smurray#include <machine/resource.h>
4283553Smurray#include <machine/bus.h>
4383553Smurray#include <sys/rman.h>
4483553Smurray#include <dev/pci/pcivar.h>
4583553Smurray#include <dev/pci/pcireg.h>
4683553Smurray#include "ahci.h"
4783553Smurray
4883553Smurray#include <cam/cam.h>
4983553Smurray#include <cam/cam_ccb.h>
5083553Smurray#include <cam/cam_sim.h>
5183553Smurray#include <cam/cam_xpt_sim.h>
52119288Simp#include <cam/cam_debug.h>
53119288Simp
5483553Smurray/* local prototypes */
5583553Smurraystatic int ahci_setup_interrupt(device_t dev);
5683553Smurraystatic void ahci_intr(void *data);
5783553Smurraystatic void ahci_intr_one(void *data);
5883553Smurraystatic int ahci_suspend(device_t dev);
5983553Smurraystatic int ahci_resume(device_t dev);
6083553Smurraystatic int ahci_ch_init(device_t dev);
6183553Smurraystatic int ahci_ch_deinit(device_t dev);
6283553Smurraystatic int ahci_ch_suspend(device_t dev);
6383553Smurraystatic int ahci_ch_resume(device_t dev);
6483553Smurraystatic void ahci_ch_pm(void *arg);
6583553Smurraystatic void ahci_ch_intr_locked(void *data);
6683553Smurraystatic void ahci_ch_intr(void *data);
6783553Smurraystatic int ahci_ctlr_reset(device_t dev);
6883553Smurraystatic int ahci_ctlr_setup(device_t dev);
69119655Sdfrstatic void ahci_begin_transaction(device_t dev, union ccb *ccb);
70119655Sdfrstatic void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
7183553Smurraystatic void ahci_execute_transaction(struct ahci_slot *slot);
72103764Snsouchstatic void ahci_timeout(struct ahci_slot *slot);
73103764Snsouchstatic void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
74103764Snsouchstatic int ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
75103764Snsouchstatic void ahci_dmainit(device_t dev);
7683553Smurraystatic void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
7783553Smurraystatic void ahci_dmafini(device_t dev);
78103764Snsouchstatic void ahci_slotsalloc(device_t dev);
7983553Smurraystatic void ahci_slotsfree(device_t dev);
8083553Smurraystatic void ahci_reset(device_t dev);
8183553Smurraystatic void ahci_start(device_t dev, int fbs);
8283553Smurraystatic void ahci_stop(device_t dev);
8383553Smurraystatic void ahci_clo(device_t dev);
8483553Smurraystatic void ahci_start_fr(device_t dev);
8583553Smurraystatic void ahci_stop_fr(device_t dev);
8683553Smurray
8783553Smurraystatic int ahci_sata_connect(struct ahci_channel *ch);
8883553Smurraystatic int ahci_sata_phy_reset(device_t dev);
8983553Smurraystatic int ahci_wait_ready(device_t dev, int t, int t0);
9083553Smurray
9183553Smurraystatic void ahci_issue_recovery(device_t dev);
92103764Snsouchstatic void ahci_process_read_log(device_t dev, union ccb *ccb);
93119796Sdfrstatic void ahci_process_request_sense(device_t dev, union ccb *ccb);
9483553Smurray
9583553Smurraystatic void ahciaction(struct cam_sim *sim, union ccb *ccb);
9683553Smurraystatic void ahcipoll(struct cam_sim *sim);
9783553Smurray
9883553Smurraystatic MALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
9983553Smurray
10083553Smurraystatic struct {
10183553Smurray	uint32_t	id;
102119796Sdfr	uint8_t		rev;
10383553Smurray	const char	*name;
10483553Smurray	int		quirks;
10583553Smurray#define AHCI_Q_NOFORCE	1
10683553Smurray#define AHCI_Q_NOPMP	2
10783553Smurray#define AHCI_Q_NONCQ	4
10883553Smurray#define AHCI_Q_1CH	8
10983553Smurray#define AHCI_Q_2CH	16
11083553Smurray#define AHCI_Q_4CH	32
11183553Smurray#define AHCI_Q_EDGEIS	64
11283553Smurray#define AHCI_Q_SATA2	128
113119796Sdfr#define AHCI_Q_NOBSYRES	256
114119796Sdfr#define AHCI_Q_NOAA	512
115119796Sdfr#define AHCI_Q_NOCOUNT	1024
116119796Sdfr#define AHCI_Q_ALTSIG	2048
117119796Sdfr} ahci_ids[] = {
118119796Sdfr	{0x43801002, 0x00, "ATI IXP600",	0},
119119796Sdfr	{0x43901002, 0x00, "ATI IXP700",	0},
120119796Sdfr	{0x43911002, 0x00, "ATI IXP700",	0},
12183553Smurray	{0x43921002, 0x00, "ATI IXP700",	0},
12283553Smurray	{0x43931002, 0x00, "ATI IXP700",	0},
12383553Smurray	{0x43941002, 0x00, "ATI IXP800",	0},
12483553Smurray	{0x43951002, 0x00, "ATI IXP800",	0},
12583553Smurray	{0x06121b21, 0x00, "ASMedia ASM1061",	0},
126103764Snsouch	{0x26528086, 0x00, "Intel ICH6",	AHCI_Q_NOFORCE},
127103764Snsouch	{0x26538086, 0x00, "Intel ICH6M",	AHCI_Q_NOFORCE},
12883553Smurray	{0x26818086, 0x00, "Intel ESB2",	0},
12983553Smurray	{0x26828086, 0x00, "Intel ESB2",	0},
13083553Smurray	{0x26838086, 0x00, "Intel ESB2",	0},
13183553Smurray	{0x27c18086, 0x00, "Intel ICH7",	0},
132103764Snsouch	{0x27c38086, 0x00, "Intel ICH7",	0},
133103764Snsouch	{0x27c58086, 0x00, "Intel ICH7M",	0},
134103764Snsouch	{0x27c68086, 0x00, "Intel ICH7M",	0},
135103764Snsouch	{0x28218086, 0x00, "Intel ICH8",	0},
136103764Snsouch	{0x28228086, 0x00, "Intel ICH8",	0},
137103764Snsouch	{0x28248086, 0x00, "Intel ICH8",	0},
138103764Snsouch	{0x28298086, 0x00, "Intel ICH8M",	0},
139103764Snsouch	{0x282a8086, 0x00, "Intel ICH8M",	0},
14083553Smurray	{0x29228086, 0x00, "Intel ICH9",	0},
14183553Smurray	{0x29238086, 0x00, "Intel ICH9",	0},
14283553Smurray	{0x29248086, 0x00, "Intel ICH9",	0},
14383553Smurray	{0x29258086, 0x00, "Intel ICH9",	0},
14483553Smurray	{0x29278086, 0x00, "Intel ICH9",	0},
145119796Sdfr	{0x29298086, 0x00, "Intel ICH9M",	0},
146119655Sdfr	{0x292a8086, 0x00, "Intel ICH9M",	0},
147119655Sdfr	{0x292b8086, 0x00, "Intel ICH9M",	0},
148119796Sdfr	{0x292c8086, 0x00, "Intel ICH9M",	0},
149119655Sdfr	{0x292f8086, 0x00, "Intel ICH9M",	0},
150119796Sdfr	{0x294d8086, 0x00, "Intel ICH9",	0},
151119655Sdfr	{0x294e8086, 0x00, "Intel ICH9M",	0},
152119655Sdfr	{0x3a058086, 0x00, "Intel ICH10",	0},
153119655Sdfr	{0x3a228086, 0x00, "Intel ICH10",	0},
154119798Sdfr	{0x3a258086, 0x00, "Intel ICH10",	0},
155119798Sdfr	{0x3b228086, 0x00, "Intel 5 Series/3400 Series",	0},
156119798Sdfr	{0x3b238086, 0x00, "Intel 5 Series/3400 Series",	0},
157119798Sdfr	{0x3b258086, 0x00, "Intel 5 Series/3400 Series",	0},
158119798Sdfr	{0x3b298086, 0x00, "Intel 5 Series/3400 Series",	0},
159119798Sdfr	{0x3b2c8086, 0x00, "Intel 5 Series/3400 Series",	0},
160119798Sdfr	{0x3b2f8086, 0x00, "Intel 5 Series/3400 Series",	0},
161119798Sdfr	{0x1c028086, 0x00, "Intel Cougar Point",	0},
162119798Sdfr	{0x1c038086, 0x00, "Intel Cougar Point",	0},
163119798Sdfr	{0x1c048086, 0x00, "Intel Cougar Point",	0},
164119798Sdfr	{0x1c058086, 0x00, "Intel Cougar Point",	0},
16583553Smurray	{0x1d028086, 0x00, "Intel Patsburg",	0},
166119796Sdfr	{0x1d048086, 0x00, "Intel Patsburg",	0},
167119796Sdfr	{0x1d068086, 0x00, "Intel Patsburg",	0},
168119796Sdfr	{0x28268086, 0x00, "Intel Patsburg (RAID)",	0},
169119796Sdfr	{0x1e028086, 0x00, "Intel Panther Point",	0},
170119796Sdfr	{0x1e038086, 0x00, "Intel Panther Point",	0},
171119796Sdfr	{0x1e048086, 0x00, "Intel Panther Point",	0},
172119796Sdfr	{0x1e058086, 0x00, "Intel Panther Point",	0},
173119796Sdfr	{0x1e068086, 0x00, "Intel Panther Point",	0},
174119796Sdfr	{0x1e078086, 0x00, "Intel Panther Point",	0},
175119796Sdfr	{0x1e0e8086, 0x00, "Intel Panther Point",	0},
176119796Sdfr	{0x1e0f8086, 0x00, "Intel Panther Point",	0},
177119796Sdfr	{0x23238086, 0x00, "Intel DH89xxCC",	0},
178119796Sdfr	{0x2360197b, 0x00, "JMicron JMB360",	0},
179119796Sdfr	{0x2361197b, 0x00, "JMicron JMB361",	AHCI_Q_NOFORCE},
180119796Sdfr	{0x2362197b, 0x00, "JMicron JMB362",	0},
181119796Sdfr	{0x2363197b, 0x00, "JMicron JMB363",	AHCI_Q_NOFORCE},
182119796Sdfr	{0x2365197b, 0x00, "JMicron JMB365",	AHCI_Q_NOFORCE},
18383553Smurray	{0x2366197b, 0x00, "JMicron JMB366",	AHCI_Q_NOFORCE},
18483553Smurray	{0x2368197b, 0x00, "JMicron JMB368",	AHCI_Q_NOFORCE},
18583553Smurray	{0x611111ab, 0x00, "Marvell 88SE6111",	AHCI_Q_NOFORCE | AHCI_Q_1CH |
18683553Smurray	    AHCI_Q_EDGEIS},
18783553Smurray	{0x612111ab, 0x00, "Marvell 88SE6121",	AHCI_Q_NOFORCE | AHCI_Q_2CH |
18883553Smurray	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
18983553Smurray	{0x614111ab, 0x00, "Marvell 88SE6141",	AHCI_Q_NOFORCE | AHCI_Q_4CH |
19083553Smurray	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
19183553Smurray	{0x614511ab, 0x00, "Marvell 88SE6145",	AHCI_Q_NOFORCE | AHCI_Q_4CH |
19283553Smurray	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
19383553Smurray	{0x91201b4b, 0x00, "Marvell 88SE912x",	AHCI_Q_EDGEIS|AHCI_Q_NOBSYRES},
19483553Smurray	{0x91231b4b, 0x11, "Marvell 88SE912x",	AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
19583553Smurray	{0x91231b4b, 0x00, "Marvell 88SE912x",	AHCI_Q_EDGEIS|AHCI_Q_SATA2|AHCI_Q_NOBSYRES},
19683553Smurray	{0x91251b4b, 0x00, "Marvell 88SE9125",	AHCI_Q_NOBSYRES},
197119796Sdfr	{0x91281b4b, 0x00, "Marvell 88SE9128",	AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
198119796Sdfr	{0x91301b4b, 0x00, "Marvell 88SE9130",  AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
199119796Sdfr	{0x91721b4b, 0x00, "Marvell 88SE9172",	AHCI_Q_NOBSYRES},
200119796Sdfr	{0x91821b4b, 0x00, "Marvell 88SE9182",	AHCI_Q_NOBSYRES},
20183553Smurray	{0x92201b4b, 0x00, "Marvell 88SE9220",  AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
20283553Smurray	{0x92301b4b, 0x00, "Marvell 88SE9230",  AHCI_Q_NOBSYRES|AHCI_Q_ALTSIG},
20383553Smurray	{0x92351b4b, 0x00, "Marvell 88SE9235",  AHCI_Q_NOBSYRES},
20483553Smurray	{0x06201103, 0x00, "HighPoint RocketRAID 620",	AHCI_Q_NOBSYRES},
20583553Smurray	{0x06201b4b, 0x00, "HighPoint RocketRAID 620",	AHCI_Q_NOBSYRES},
20683553Smurray	{0x06221103, 0x00, "HighPoint RocketRAID 622",	AHCI_Q_NOBSYRES},
20783553Smurray	{0x06221b4b, 0x00, "HighPoint RocketRAID 622",	AHCI_Q_NOBSYRES},
20883553Smurray	{0x06401103, 0x00, "HighPoint RocketRAID 640",	AHCI_Q_NOBSYRES},
20983553Smurray	{0x06401b4b, 0x00, "HighPoint RocketRAID 640",	AHCI_Q_NOBSYRES},
21083553Smurray	{0x06441103, 0x00, "HighPoint RocketRAID 644",	AHCI_Q_NOBSYRES},
211103764Snsouch	{0x06441b4b, 0x00, "HighPoint RocketRAID 644",	AHCI_Q_NOBSYRES},
212103764Snsouch	{0x044c10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
213103764Snsouch	{0x044d10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
214119798Sdfr	{0x044e10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
215103764Snsouch	{0x044f10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
216103764Snsouch	{0x045c10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
217103764Snsouch	{0x045d10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
21883553Smurray	{0x045e10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
21983553Smurray	{0x045f10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
22083553Smurray	{0x055010de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
22183553Smurray	{0x055110de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
222103764Snsouch	{0x055210de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
22383553Smurray	{0x055310de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
224103764Snsouch	{0x055410de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
22583553Smurray	{0x055510de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
226103764Snsouch	{0x055610de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
227119798Sdfr	{0x055710de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
228119798Sdfr	{0x055810de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
229103764Snsouch	{0x055910de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
23093040Snsouch	{0x055A10de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
231103764Snsouch	{0x055B10de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
232119798Sdfr	{0x058410de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
233119798Sdfr	{0x07f010de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
23483553Smurray	{0x07f110de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
23583553Smurray	{0x07f210de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
23683553Smurray	{0x07f310de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
23783553Smurray	{0x07f410de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
23883553Smurray	{0x07f510de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
239103764Snsouch	{0x07f610de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
24083553Smurray	{0x07f710de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
24183553Smurray	{0x07f810de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
24283553Smurray	{0x07f910de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
24383553Smurray	{0x07fa10de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
24483553Smurray	{0x07fb10de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
24583553Smurray	{0x0ad010de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
24683553Smurray	{0x0ad110de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
24783553Smurray	{0x0ad210de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
24883553Smurray	{0x0ad310de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
24983553Smurray	{0x0ad410de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25083553Smurray	{0x0ad510de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25183553Smurray	{0x0ad610de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25283553Smurray	{0x0ad710de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25383553Smurray	{0x0ad810de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25483553Smurray	{0x0ad910de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
255103764Snsouch	{0x0ada10de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25683553Smurray	{0x0adb10de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
25783553Smurray	{0x0ab410de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
25883553Smurray	{0x0ab510de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
25983553Smurray	{0x0ab610de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26083553Smurray	{0x0ab710de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26183553Smurray	{0x0ab810de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26283553Smurray	{0x0ab910de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26391265Speter	{0x0aba10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26483553Smurray	{0x0abb10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
265103764Snsouch	{0x0abc10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26683553Smurray	{0x0abd10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26783553Smurray	{0x0abe10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26883553Smurray	{0x0abf10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
26983553Smurray	{0x0d8410de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27083553Smurray	{0x0d8510de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOFORCE|AHCI_Q_NOAA},
27183553Smurray	{0x0d8610de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27283553Smurray	{0x0d8710de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27383553Smurray	{0x0d8810de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27491265Speter	{0x0d8910de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27583553Smurray	{0x0d8a10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27683553Smurray	{0x0d8b10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
277103764Snsouch	{0x0d8c10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27883553Smurray	{0x0d8d10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
27983553Smurray	{0x0d8e10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
28083553Smurray	{0x0d8f10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
28183553Smurray	{0x33491106, 0x00, "VIA VT8251",	AHCI_Q_NOPMP|AHCI_Q_NONCQ},
28283553Smurray	{0x62871106, 0x00, "VIA VT8251",	AHCI_Q_NOPMP|AHCI_Q_NONCQ},
28383553Smurray	{0x11841039, 0x00, "SiS 966",		0},
28483553Smurray	{0x11851039, 0x00, "SiS 968",		0},
28583553Smurray	{0x01861039, 0x00, "SiS 968",		0},
28683553Smurray	{0x00000000, 0x00, NULL,		0}
28783553Smurray};
28883553Smurray
28983553Smurray#define recovery_type		spriv_field0
29083553Smurray#define RECOVERY_NONE		0
29183553Smurray#define RECOVERY_READ_LOG	1
292103764Snsouch#define RECOVERY_REQUEST_SENSE	2
29383553Smurray#define recovery_slot		spriv_field1
29483553Smurray
29583553Smurraystatic int force_ahci = 1;
29683553SmurrayTUNABLE_INT("hw.ahci.force", &force_ahci);
29783553Smurray
29883553Smurraystatic int
29983553Smurrayahci_probe(device_t dev)
30083553Smurray{
30183553Smurray	char buf[64];
30283553Smurray	int i, valid = 0;
30383553Smurray	uint32_t devid = pci_get_devid(dev);
30483553Smurray	uint8_t revid = pci_get_revid(dev);
30583553Smurray
30683553Smurray	/* Is this a possible AHCI candidate? */
30783553Smurray	if (pci_get_class(dev) == PCIC_STORAGE &&
30883553Smurray	    pci_get_subclass(dev) == PCIS_STORAGE_SATA &&
30983553Smurray	    pci_get_progif(dev) == PCIP_STORAGE_SATA_AHCI_1_0)
31083553Smurray		valid = 1;
31183553Smurray	/* Is this a known AHCI chip? */
31283553Smurray	for (i = 0; ahci_ids[i].id != 0; i++) {
31383553Smurray		if (ahci_ids[i].id == devid &&
31483553Smurray		    ahci_ids[i].rev <= revid &&
31583553Smurray		    (valid || (force_ahci == 1 &&
31683553Smurray		     !(ahci_ids[i].quirks & AHCI_Q_NOFORCE)))) {
31783553Smurray			/* Do not attach JMicrons with single PCI function. */
31883553Smurray			if (pci_get_vendor(dev) == 0x197b &&
31983553Smurray			    (pci_read_config(dev, 0xdf, 1) & 0x40) == 0)
32083553Smurray				return (ENXIO);
32183553Smurray			snprintf(buf, sizeof(buf), "%s AHCI SATA controller",
32283553Smurray			    ahci_ids[i].name);
323103764Snsouch			device_set_desc_copy(dev, buf);
32483553Smurray			return (BUS_PROBE_VENDOR);
32583553Smurray		}
32683553Smurray	}
32783553Smurray	if (!valid)
32883553Smurray		return (ENXIO);
329103764Snsouch	device_set_desc_copy(dev, "AHCI SATA controller");
33083553Smurray	return (BUS_PROBE_VENDOR);
331103764Snsouch}
33283553Smurray
33383553Smurraystatic int
33483553Smurrayahci_ata_probe(device_t dev)
335103764Snsouch{
336103764Snsouch	char buf[64];
33783553Smurray	int i;
33883553Smurray	uint32_t devid = pci_get_devid(dev);
33983553Smurray	uint8_t revid = pci_get_revid(dev);
34083553Smurray
34183553Smurray	if ((intptr_t)device_get_ivars(dev) >= 0)
34283553Smurray		return (ENXIO);
34383553Smurray	/* Is this a known AHCI chip? */
34483553Smurray	for (i = 0; ahci_ids[i].id != 0; i++) {
34583553Smurray		if (ahci_ids[i].id == devid &&
34683553Smurray		    ahci_ids[i].rev <= revid) {
34783553Smurray			snprintf(buf, sizeof(buf), "%s AHCI SATA controller",
34883553Smurray			    ahci_ids[i].name);
34987599Sobrien			device_set_desc_copy(dev, buf);
35083553Smurray			return (BUS_PROBE_VENDOR);
35183553Smurray		}
35283553Smurray	}
35383553Smurray	device_set_desc_copy(dev, "AHCI SATA controller");
354103764Snsouch	return (BUS_PROBE_VENDOR);
35583553Smurray}
35683553Smurray
35783553Smurraystatic int
35883553Smurrayahci_attach(device_t dev)
35983553Smurray{
36083553Smurray	struct ahci_controller *ctlr = device_get_softc(dev);
36183553Smurray	device_t child;
362103764Snsouch	int	error, unit, speed, i;
36383553Smurray	uint32_t devid = pci_get_devid(dev);
364103764Snsouch	uint8_t revid = pci_get_revid(dev);
36583553Smurray	u_int32_t version;
36683553Smurray
36783553Smurray	ctlr->dev = dev;
368103764Snsouch	i = 0;
369103764Snsouch	while (ahci_ids[i].id != 0 &&
37083553Smurray	    (ahci_ids[i].id != devid ||
37183553Smurray	     ahci_ids[i].rev > revid))
37283553Smurray		i++;
37383553Smurray	ctlr->quirks = ahci_ids[i].quirks;
37483553Smurray	resource_int_value(device_get_name(dev),
37583553Smurray	    device_get_unit(dev), "ccc", &ctlr->ccc);
37683553Smurray	/* if we have a memory BAR(5) we are likely on an AHCI part */
377103764Snsouch	ctlr->r_rid = PCIR_BAR(5);
37883553Smurray	if (!(ctlr->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
37983553Smurray	    &ctlr->r_rid, RF_ACTIVE)))
38083553Smurray		return ENXIO;
38183553Smurray	/* Setup our own memory management for channels. */
38283553Smurray	ctlr->sc_iomem.rm_start = rman_get_start(ctlr->r_mem);
38383553Smurray	ctlr->sc_iomem.rm_end = rman_get_end(ctlr->r_mem);
38483553Smurray	ctlr->sc_iomem.rm_type = RMAN_ARRAY;
385103764Snsouch	ctlr->sc_iomem.rm_descr = "I/O memory addresses";
38683553Smurray	if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
387103764Snsouch		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
38883553Smurray		return (error);
38983553Smurray	}
39083553Smurray	if ((error = rman_manage_region(&ctlr->sc_iomem,
391103764Snsouch	    rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
392103764Snsouch		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
39383553Smurray		rman_fini(&ctlr->sc_iomem);
39483553Smurray		return (error);
39583553Smurray	}
39683553Smurray	pci_enable_busmaster(dev);
39783553Smurray	/* Reset controller */
39883553Smurray	if ((error = ahci_ctlr_reset(dev)) != 0) {
399103764Snsouch		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
40083553Smurray		rman_fini(&ctlr->sc_iomem);
40183553Smurray		return (error);
40283553Smurray	};
40383553Smurray	/* Get the HW capabilities */
40483553Smurray	version = ATA_INL(ctlr->r_mem, AHCI_VS);
40583553Smurray	ctlr->caps = ATA_INL(ctlr->r_mem, AHCI_CAP);
40683553Smurray	if (version >= 0x00010020)
40783553Smurray		ctlr->caps2 = ATA_INL(ctlr->r_mem, AHCI_CAP2);
408103764Snsouch	if (ctlr->caps & AHCI_CAP_EMS)
40983553Smurray		ctlr->capsem = ATA_INL(ctlr->r_mem, AHCI_EM_CTL);
410103764Snsouch	ctlr->ichannels = ATA_INL(ctlr->r_mem, AHCI_PI);
41183553Smurray
41283553Smurray	/* Identify and set separate quirks for HBA and RAID f/w Marvells. */
41383553Smurray	if ((ctlr->quirks & AHCI_Q_NOBSYRES) &&
414103764Snsouch	    (ctlr->quirks & AHCI_Q_ALTSIG) &&
415103764Snsouch	    (ctlr->caps & AHCI_CAP_SPM) == 0)
41683553Smurray		ctlr->quirks &= ~AHCI_Q_NOBSYRES;
41783553Smurray
41883553Smurray	if (ctlr->quirks & AHCI_Q_1CH) {
41983553Smurray		ctlr->caps &= ~AHCI_CAP_NPMASK;
42083553Smurray		ctlr->ichannels &= 0x01;
42183553Smurray	}
42283553Smurray	if (ctlr->quirks & AHCI_Q_2CH) {
42383553Smurray		ctlr->caps &= ~AHCI_CAP_NPMASK;
424103764Snsouch		ctlr->caps |= 1;
42583553Smurray		ctlr->ichannels &= 0x03;
42683553Smurray	}
42783553Smurray	if (ctlr->quirks & AHCI_Q_4CH) {
42883553Smurray		ctlr->caps &= ~AHCI_CAP_NPMASK;
42983553Smurray		ctlr->caps |= 3;
43083553Smurray		ctlr->ichannels &= 0x0f;
43183553Smurray	}
432103764Snsouch	ctlr->channels = MAX(flsl(ctlr->ichannels),
43383553Smurray	    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
434103764Snsouch	if (ctlr->quirks & AHCI_Q_NOPMP)
43583553Smurray		ctlr->caps &= ~AHCI_CAP_SPM;
43683553Smurray	if (ctlr->quirks & AHCI_Q_NONCQ)
43783553Smurray		ctlr->caps &= ~AHCI_CAP_SNCQ;
438103764Snsouch	if ((ctlr->caps & AHCI_CAP_CCCS) == 0)
439103764Snsouch		ctlr->ccc = 0;
44083553Smurray	ctlr->emloc = ATA_INL(ctlr->r_mem, AHCI_EM_LOC);
44183553Smurray	ahci_ctlr_setup(dev);
44283553Smurray	/* Setup interrupts. */
44383553Smurray	if (ahci_setup_interrupt(dev)) {
44483553Smurray		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
44583553Smurray		rman_fini(&ctlr->sc_iomem);
44683553Smurray		return ENXIO;
447103764Snsouch	}
44883553Smurray	/* Announce HW capabilities. */
44983553Smurray	speed = (ctlr->caps & AHCI_CAP_ISS) >> AHCI_CAP_ISS_SHIFT;
45083553Smurray	device_printf(dev,
45183553Smurray		    "AHCI v%x.%02x with %d %sGbps ports, Port Multiplier %s%s\n",
45283553Smurray		    ((version >> 20) & 0xf0) + ((version >> 16) & 0x0f),
45383553Smurray		    ((version >> 4) & 0xf0) + (version & 0x0f),
45483553Smurray		    (ctlr->caps & AHCI_CAP_NPMASK) + 1,
45583553Smurray		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
456103764Snsouch		    ((speed == 3) ? "6":"?"))),
45783553Smurray		    (ctlr->caps & AHCI_CAP_SPM) ?
458103764Snsouch		    "supported" : "not supported",
45983553Smurray		    (ctlr->caps & AHCI_CAP_FBSS) ?
46083553Smurray		    " with FBS" : "");
46183553Smurray	if (bootverbose) {
462103764Snsouch		device_printf(dev, "Caps:%s%s%s%s%s%s%s%s %sGbps",
463103764Snsouch		    (ctlr->caps & AHCI_CAP_64BIT) ? " 64bit":"",
46483553Smurray		    (ctlr->caps & AHCI_CAP_SNCQ) ? " NCQ":"",
46583553Smurray		    (ctlr->caps & AHCI_CAP_SSNTF) ? " SNTF":"",
46683553Smurray		    (ctlr->caps & AHCI_CAP_SMPS) ? " MPS":"",
46783553Smurray		    (ctlr->caps & AHCI_CAP_SSS) ? " SS":"",
46883553Smurray		    (ctlr->caps & AHCI_CAP_SALP) ? " ALP":"",
46983553Smurray		    (ctlr->caps & AHCI_CAP_SAL) ? " AL":"",
47083553Smurray		    (ctlr->caps & AHCI_CAP_SCLO) ? " CLO":"",
47183553Smurray		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
472103764Snsouch		    ((speed == 3) ? "6":"?"))));
47383553Smurray		printf("%s%s%s%s%s%s %dcmd%s%s%s %dports\n",
47483553Smurray		    (ctlr->caps & AHCI_CAP_SAM) ? " AM":"",
47583553Smurray		    (ctlr->caps & AHCI_CAP_SPM) ? " PM":"",
47683553Smurray		    (ctlr->caps & AHCI_CAP_FBSS) ? " FBS":"",
47783553Smurray		    (ctlr->caps & AHCI_CAP_PMD) ? " PMD":"",
47883553Smurray		    (ctlr->caps & AHCI_CAP_SSC) ? " SSC":"",
47983553Smurray		    (ctlr->caps & AHCI_CAP_PSC) ? " PSC":"",
480103764Snsouch		    ((ctlr->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
48183553Smurray		    (ctlr->caps & AHCI_CAP_CCCS) ? " CCC":"",
482103764Snsouch		    (ctlr->caps & AHCI_CAP_EMS) ? " EM":"",
48383553Smurray		    (ctlr->caps & AHCI_CAP_SXS) ? " eSATA":"",
48483553Smurray		    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
48583553Smurray	}
486103764Snsouch	if (bootverbose && version >= 0x00010020) {
487103764Snsouch		device_printf(dev, "Caps2:%s%s%s\n",
48883553Smurray		    (ctlr->caps2 & AHCI_CAP2_APST) ? " APST":"",
48983553Smurray		    (ctlr->caps2 & AHCI_CAP2_NVMP) ? " NVMP":"",
49083553Smurray		    (ctlr->caps2 & AHCI_CAP2_BOH) ? " BOH":"");
49183553Smurray	}
49283553Smurray	/* Attach all channels on this controller */
49383553Smurray	for (unit = 0; unit < ctlr->channels; unit++) {
49483553Smurray		child = device_add_child(dev, "ahcich", -1);
495103764Snsouch		if (child == NULL) {
49683553Smurray			device_printf(dev, "failed to add channel device\n");
49783553Smurray			continue;
49883553Smurray		}
49983553Smurray		device_set_ivars(child, (void *)(intptr_t)unit);
50083553Smurray		if ((ctlr->ichannels & (1 << unit)) == 0)
50183553Smurray			device_disable(child);
50283553Smurray	}
50383553Smurray	if (ctlr->caps & AHCI_CAP_EMS) {
504103764Snsouch		child = device_add_child(dev, "ahciem", -1);
50583553Smurray		if (child == NULL)
506103764Snsouch			device_printf(dev, "failed to add enclosure device\n");
50783553Smurray		else
50883553Smurray			device_set_ivars(child, (void *)(intptr_t)-1);
50983553Smurray	}
51083553Smurray	bus_generic_attach(dev);
511103764Snsouch	return 0;
512103764Snsouch}
51383553Smurray
51483553Smurraystatic int
51583553Smurrayahci_detach(device_t dev)
51683553Smurray{
51783553Smurray	struct ahci_controller *ctlr = device_get_softc(dev);
51883553Smurray	int i;
51983553Smurray
52083553Smurray	/* Detach & delete all children */
52183553Smurray	device_delete_children(dev);
52283553Smurray
52383553Smurray	/* Free interrupts. */
52483553Smurray	for (i = 0; i < ctlr->numirqs; i++) {
52583553Smurray		if (ctlr->irqs[i].r_irq) {
52683553Smurray			bus_teardown_intr(dev, ctlr->irqs[i].r_irq,
52783553Smurray			    ctlr->irqs[i].handle);
52883553Smurray			bus_release_resource(dev, SYS_RES_IRQ,
52983553Smurray			    ctlr->irqs[i].r_irq_rid, ctlr->irqs[i].r_irq);
53083553Smurray		}
53183553Smurray	}
53283553Smurray	pci_release_msi(dev);
53383553Smurray	/* Free memory. */
53483553Smurray	rman_fini(&ctlr->sc_iomem);
53583553Smurray	if (ctlr->r_mem)
53683553Smurray		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
537103764Snsouch	return (0);
53883553Smurray}
53983553Smurray
54083553Smurraystatic int
54183553Smurrayahci_ctlr_reset(device_t dev)
54283553Smurray{
54383553Smurray	struct ahci_controller *ctlr = device_get_softc(dev);
54483553Smurray	int timeout;
54583553Smurray
54683553Smurray	if (pci_read_config(dev, 0x00, 4) == 0x28298086 &&
54783553Smurray	    (pci_read_config(dev, 0x92, 1) & 0xfe) == 0x04)
54883553Smurray		pci_write_config(dev, 0x92, 0x01, 1);
54983553Smurray	/* Enable AHCI mode */
550103764Snsouch	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
55183553Smurray	/* Reset AHCI controller */
552103764Snsouch	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE|AHCI_GHC_HR);
55383553Smurray	for (timeout = 1000; timeout > 0; timeout--) {
55483553Smurray		DELAY(1000);
55583553Smurray		if ((ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_HR) == 0)
55683553Smurray			break;
557103764Snsouch	}
558103764Snsouch	if (timeout == 0) {
55983553Smurray		device_printf(dev, "AHCI controller reset failure\n");
56083553Smurray		return ENXIO;
56183553Smurray	}
56283553Smurray	/* Reenable AHCI mode */
56383553Smurray	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
56483553Smurray	return (0);
56583553Smurray}
56683553Smurray
56783553Smurraystatic int
56883553Smurrayahci_ctlr_setup(device_t dev)
56983553Smurray{
570103764Snsouch	struct ahci_controller *ctlr = device_get_softc(dev);
57183553Smurray	/* Clear interrupts */
57283553Smurray	ATA_OUTL(ctlr->r_mem, AHCI_IS, ATA_INL(ctlr->r_mem, AHCI_IS));
57383553Smurray	/* Configure CCC */
57483553Smurray	if (ctlr->ccc) {
57583553Smurray		ATA_OUTL(ctlr->r_mem, AHCI_CCCP, ATA_INL(ctlr->r_mem, AHCI_PI));
57683553Smurray		ATA_OUTL(ctlr->r_mem, AHCI_CCCC,
57783553Smurray		    (ctlr->ccc << AHCI_CCCC_TV_SHIFT) |
57883553Smurray		    (4 << AHCI_CCCC_CC_SHIFT) |
57983553Smurray		    AHCI_CCCC_EN);
58083553Smurray		ctlr->cccv = (ATA_INL(ctlr->r_mem, AHCI_CCCC) &
58183553Smurray		    AHCI_CCCC_INT_MASK) >> AHCI_CCCC_INT_SHIFT;
58283553Smurray		if (bootverbose) {
58383553Smurray			device_printf(dev,
58483553Smurray			    "CCC with %dms/4cmd enabled on vector %d\n",
58583553Smurray			    ctlr->ccc, ctlr->cccv);
58683553Smurray		}
58783553Smurray	}
58883553Smurray	/* Enable AHCI interrupts */
58983553Smurray	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
59083553Smurray	    ATA_INL(ctlr->r_mem, AHCI_GHC) | AHCI_GHC_IE);
59183553Smurray	return (0);
59283553Smurray}
59383553Smurray
59483553Smurraystatic int
595103764Snsouchahci_suspend(device_t dev)
59683553Smurray{
597103764Snsouch	struct ahci_controller *ctlr = device_get_softc(dev);
598103764Snsouch
599103764Snsouch	bus_generic_suspend(dev);
600103764Snsouch	/* Disable interupts, so the state change(s) doesn't trigger */
601103764Snsouch	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
602103764Snsouch	     ATA_INL(ctlr->r_mem, AHCI_GHC) & (~AHCI_GHC_IE));
603103764Snsouch	return 0;
604103764Snsouch}
605103764Snsouch
606103764Snsouchstatic int
607103764Snsouchahci_resume(device_t dev)
608103764Snsouch{
60983553Smurray	int res;
61083553Smurray
61183553Smurray	if ((res = ahci_ctlr_reset(dev)) != 0)
61283553Smurray		return (res);
61383553Smurray	ahci_ctlr_setup(dev);
61483553Smurray	return (bus_generic_resume(dev));
61583553Smurray}
61683553Smurray
61783553Smurraystatic int
61883553Smurrayahci_setup_interrupt(device_t dev)
619103764Snsouch{
620113506Smdodd	struct ahci_controller *ctlr = device_get_softc(dev);
62193040Snsouch	int i, msi = 1;
62293040Snsouch
623103764Snsouch	/* Process hints. */
624	resource_int_value(device_get_name(dev),
625	    device_get_unit(dev), "msi", &msi);
626	if (msi < 0)
627		msi = 0;
628	else if (msi == 1)
629		msi = min(1, pci_msi_count(dev));
630	else if (msi > 1)
631		msi = pci_msi_count(dev);
632	/* Allocate MSI if needed/present. */
633	if (msi && pci_alloc_msi(dev, &msi) == 0) {
634		ctlr->numirqs = msi;
635	} else {
636		msi = 0;
637		ctlr->numirqs = 1;
638	}
639	/* Check for single MSI vector fallback. */
640	if (ctlr->numirqs > 1 &&
641	    (ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_MRSM) != 0) {
642		device_printf(dev, "Falling back to one MSI\n");
643		ctlr->numirqs = 1;
644	}
645	/* Allocate all IRQs. */
646	for (i = 0; i < ctlr->numirqs; i++) {
647		ctlr->irqs[i].ctlr = ctlr;
648		ctlr->irqs[i].r_irq_rid = i + (msi ? 1 : 0);
649		if (ctlr->numirqs == 1 || i >= ctlr->channels ||
650		    (ctlr->ccc && i == ctlr->cccv))
651			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ALL;
652		else if (i == ctlr->numirqs - 1)
653			ctlr->irqs[i].mode = AHCI_IRQ_MODE_AFTER;
654		else
655			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
656		if (!(ctlr->irqs[i].r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
657		    &ctlr->irqs[i].r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
658			device_printf(dev, "unable to map interrupt\n");
659			return ENXIO;
660		}
661		if ((bus_setup_intr(dev, ctlr->irqs[i].r_irq, ATA_INTR_FLAGS, NULL,
662		    (ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE) ? ahci_intr_one : ahci_intr,
663		    &ctlr->irqs[i], &ctlr->irqs[i].handle))) {
664			/* SOS XXX release r_irq */
665			device_printf(dev, "unable to setup interrupt\n");
666			return ENXIO;
667		}
668		if (ctlr->numirqs > 1) {
669			bus_describe_intr(dev, ctlr->irqs[i].r_irq,
670			    ctlr->irqs[i].handle,
671			    ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE ?
672			    "ch%d" : "%d", i);
673		}
674	}
675	return (0);
676}
677
678/*
679 * Common case interrupt handler.
680 */
681static void
682ahci_intr(void *data)
683{
684	struct ahci_controller_irq *irq = data;
685	struct ahci_controller *ctlr = irq->ctlr;
686	u_int32_t is, ise = 0;
687	void *arg;
688	int unit;
689
690	if (irq->mode == AHCI_IRQ_MODE_ALL) {
691		unit = 0;
692		if (ctlr->ccc)
693			is = ctlr->ichannels;
694		else
695			is = ATA_INL(ctlr->r_mem, AHCI_IS);
696	} else {	/* AHCI_IRQ_MODE_AFTER */
697		unit = irq->r_irq_rid - 1;
698		is = ATA_INL(ctlr->r_mem, AHCI_IS);
699	}
700	/* CCC interrupt is edge triggered. */
701	if (ctlr->ccc)
702		ise = 1 << ctlr->cccv;
703	/* Some controllers have edge triggered IS. */
704	if (ctlr->quirks & AHCI_Q_EDGEIS)
705		ise |= is;
706	if (ise != 0)
707		ATA_OUTL(ctlr->r_mem, AHCI_IS, ise);
708	for (; unit < ctlr->channels; unit++) {
709		if ((is & (1 << unit)) != 0 &&
710		    (arg = ctlr->interrupt[unit].argument)) {
711				ctlr->interrupt[unit].function(arg);
712		}
713	}
714	/* AHCI declares level triggered IS. */
715	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
716		ATA_OUTL(ctlr->r_mem, AHCI_IS, is);
717}
718
719/*
720 * Simplified interrupt handler for multivector MSI mode.
721 */
722static void
723ahci_intr_one(void *data)
724{
725	struct ahci_controller_irq *irq = data;
726	struct ahci_controller *ctlr = irq->ctlr;
727	void *arg;
728	int unit;
729
730	unit = irq->r_irq_rid - 1;
731	/* Some controllers have edge triggered IS. */
732	if (ctlr->quirks & AHCI_Q_EDGEIS)
733		ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
734	if ((arg = ctlr->interrupt[unit].argument))
735	    ctlr->interrupt[unit].function(arg);
736	/* AHCI declares level triggered IS. */
737	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
738		ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
739}
740
741static struct resource *
742ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
743		       u_long start, u_long end, u_long count, u_int flags)
744{
745	struct ahci_controller *ctlr = device_get_softc(dev);
746	struct resource *res;
747	long st;
748	int offset, size, unit;
749
750	unit = (intptr_t)device_get_ivars(child);
751	res = NULL;
752	switch (type) {
753	case SYS_RES_MEMORY:
754		if (unit >= 0) {
755			offset = AHCI_OFFSET + (unit << 7);
756			size = 128;
757		} else if (*rid == 0) {
758			offset = AHCI_EM_CTL;
759			size = 4;
760		} else {
761			offset = (ctlr->emloc & 0xffff0000) >> 14;
762			size = (ctlr->emloc & 0x0000ffff) << 2;
763			if (*rid != 1) {
764				if (*rid == 2 && (ctlr->capsem &
765				    (AHCI_EM_XMT | AHCI_EM_SMB)) == 0)
766					offset += size;
767				else
768					break;
769			}
770		}
771		st = rman_get_start(ctlr->r_mem);
772		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
773		    st + offset + size - 1, size, RF_ACTIVE, child);
774		if (res) {
775			bus_space_handle_t bsh;
776			bus_space_tag_t bst;
777			bsh = rman_get_bushandle(ctlr->r_mem);
778			bst = rman_get_bustag(ctlr->r_mem);
779			bus_space_subregion(bst, bsh, offset, 128, &bsh);
780			rman_set_bushandle(res, bsh);
781			rman_set_bustag(res, bst);
782		}
783		break;
784	case SYS_RES_IRQ:
785		if (*rid == ATA_IRQ_RID)
786			res = ctlr->irqs[0].r_irq;
787		break;
788	}
789	return (res);
790}
791
792static int
793ahci_release_resource(device_t dev, device_t child, int type, int rid,
794			 struct resource *r)
795{
796
797	switch (type) {
798	case SYS_RES_MEMORY:
799		rman_release_resource(r);
800		return (0);
801	case SYS_RES_IRQ:
802		if (rid != ATA_IRQ_RID)
803			return ENOENT;
804		return (0);
805	}
806	return (EINVAL);
807}
808
809static int
810ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
811		   int flags, driver_filter_t *filter, driver_intr_t *function,
812		   void *argument, void **cookiep)
813{
814	struct ahci_controller *ctlr = device_get_softc(dev);
815	int unit = (intptr_t)device_get_ivars(child);
816
817	if (filter != NULL) {
818		printf("ahci.c: we cannot use a filter here\n");
819		return (EINVAL);
820	}
821	ctlr->interrupt[unit].function = function;
822	ctlr->interrupt[unit].argument = argument;
823	return (0);
824}
825
826static int
827ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
828		      void *cookie)
829{
830	struct ahci_controller *ctlr = device_get_softc(dev);
831	int unit = (intptr_t)device_get_ivars(child);
832
833	ctlr->interrupt[unit].function = NULL;
834	ctlr->interrupt[unit].argument = NULL;
835	return (0);
836}
837
838static int
839ahci_print_child(device_t dev, device_t child)
840{
841	int retval, channel;
842
843	retval = bus_print_child_header(dev, child);
844	channel = (int)(intptr_t)device_get_ivars(child);
845	if (channel >= 0)
846		retval += printf(" at channel %d", channel);
847	retval += bus_print_child_footer(dev, child);
848	return (retval);
849}
850
851static int
852ahci_child_location_str(device_t dev, device_t child, char *buf,
853    size_t buflen)
854{
855	int channel;
856
857	channel = (int)(intptr_t)device_get_ivars(child);
858	if (channel >= 0)
859		snprintf(buf, buflen, "channel=%d", channel);
860	return (0);
861}
862
863devclass_t ahci_devclass;
864static device_method_t ahci_methods[] = {
865	DEVMETHOD(device_probe,     ahci_probe),
866	DEVMETHOD(device_attach,    ahci_attach),
867	DEVMETHOD(device_detach,    ahci_detach),
868	DEVMETHOD(device_suspend,   ahci_suspend),
869	DEVMETHOD(device_resume,    ahci_resume),
870	DEVMETHOD(bus_print_child,  ahci_print_child),
871	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
872	DEVMETHOD(bus_release_resource,     ahci_release_resource),
873	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
874	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
875	DEVMETHOD(bus_child_location_str, ahci_child_location_str),
876	{ 0, 0 }
877};
878static driver_t ahci_driver = {
879        "ahci",
880        ahci_methods,
881        sizeof(struct ahci_controller)
882};
883DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
884static device_method_t ahci_ata_methods[] = {
885	DEVMETHOD(device_probe,     ahci_ata_probe),
886	DEVMETHOD(device_attach,    ahci_attach),
887	DEVMETHOD(device_detach,    ahci_detach),
888	DEVMETHOD(device_suspend,   ahci_suspend),
889	DEVMETHOD(device_resume,    ahci_resume),
890	DEVMETHOD(bus_print_child,  ahci_print_child),
891	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
892	DEVMETHOD(bus_release_resource,     ahci_release_resource),
893	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
894	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
895	DEVMETHOD(bus_child_location_str, ahci_child_location_str),
896	{ 0, 0 }
897};
898static driver_t ahci_ata_driver = {
899        "ahci",
900        ahci_ata_methods,
901        sizeof(struct ahci_controller)
902};
903DRIVER_MODULE(ahci, atapci, ahci_ata_driver, ahci_devclass, 0, 0);
904MODULE_VERSION(ahci, 1);
905MODULE_DEPEND(ahci, cam, 1, 1, 1);
906
907static int
908ahci_ch_probe(device_t dev)
909{
910
911	device_set_desc_copy(dev, "AHCI channel");
912	return (0);
913}
914
915static int
916ahci_ch_attach(device_t dev)
917{
918	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
919	struct ahci_channel *ch = device_get_softc(dev);
920	struct cam_devq *devq;
921	int rid, error, i, sata_rev = 0;
922	u_int32_t version;
923
924	ch->dev = dev;
925	ch->unit = (intptr_t)device_get_ivars(dev);
926	ch->caps = ctlr->caps;
927	ch->caps2 = ctlr->caps2;
928	ch->quirks = ctlr->quirks;
929	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1;
930	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
931	resource_int_value(device_get_name(dev),
932	    device_get_unit(dev), "pm_level", &ch->pm_level);
933	if (ch->pm_level > 3)
934		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
935	callout_init_mtx(&ch->reset_timer, &ch->mtx, 0);
936	/* Limit speed for my onboard JMicron external port.
937	 * It is not eSATA really. */
938	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
939	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
940	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
941	    ch->unit == 0)
942		sata_rev = 1;
943	if (ch->quirks & AHCI_Q_SATA2)
944		sata_rev = 2;
945	resource_int_value(device_get_name(dev),
946	    device_get_unit(dev), "sata_rev", &sata_rev);
947	for (i = 0; i < 16; i++) {
948		ch->user[i].revision = sata_rev;
949		ch->user[i].mode = 0;
950		ch->user[i].bytecount = 8192;
951		ch->user[i].tags = ch->numslots;
952		ch->user[i].caps = 0;
953		ch->curr[i] = ch->user[i];
954		if (ch->pm_level) {
955			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
956			    CTS_SATA_CAPS_H_APST |
957			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
958		}
959		ch->user[i].caps |= CTS_SATA_CAPS_H_DMAAA |
960		    CTS_SATA_CAPS_H_AN;
961	}
962	rid = 0;
963	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
964	    &rid, RF_ACTIVE)))
965		return (ENXIO);
966	ahci_dmainit(dev);
967	ahci_slotsalloc(dev);
968	ahci_ch_init(dev);
969	mtx_lock(&ch->mtx);
970	rid = ATA_IRQ_RID;
971	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
972	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
973		device_printf(dev, "Unable to map interrupt\n");
974		error = ENXIO;
975		goto err0;
976	}
977	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
978	    ahci_ch_intr_locked, dev, &ch->ih))) {
979		device_printf(dev, "Unable to setup interrupt\n");
980		error = ENXIO;
981		goto err1;
982	}
983	ch->chcaps = ATA_INL(ch->r_mem, AHCI_P_CMD);
984	version = ATA_INL(ctlr->r_mem, AHCI_VS);
985	if (version < 0x00010020 && (ctlr->caps & AHCI_CAP_FBSS))
986		ch->chcaps |= AHCI_P_CMD_FBSCP;
987	if (bootverbose) {
988		device_printf(dev, "Caps:%s%s%s%s%s\n",
989		    (ch->chcaps & AHCI_P_CMD_HPCP) ? " HPCP":"",
990		    (ch->chcaps & AHCI_P_CMD_MPSP) ? " MPSP":"",
991		    (ch->chcaps & AHCI_P_CMD_CPD) ? " CPD":"",
992		    (ch->chcaps & AHCI_P_CMD_ESP) ? " ESP":"",
993		    (ch->chcaps & AHCI_P_CMD_FBSCP) ? " FBSCP":"");
994	}
995	/* Create the device queue for our SIM. */
996	devq = cam_simq_alloc(ch->numslots);
997	if (devq == NULL) {
998		device_printf(dev, "Unable to allocate simq\n");
999		error = ENOMEM;
1000		goto err1;
1001	}
1002	/* Construct SIM entry */
1003	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
1004	    device_get_unit(dev), &ch->mtx,
1005	    min(2, ch->numslots),
1006	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
1007	    devq);
1008	if (ch->sim == NULL) {
1009		cam_simq_free(devq);
1010		device_printf(dev, "unable to allocate sim\n");
1011		error = ENOMEM;
1012		goto err1;
1013	}
1014	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
1015		device_printf(dev, "unable to register xpt bus\n");
1016		error = ENXIO;
1017		goto err2;
1018	}
1019	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
1020	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1021		device_printf(dev, "unable to create path\n");
1022		error = ENXIO;
1023		goto err3;
1024	}
1025	if (ch->pm_level > 3) {
1026		callout_reset(&ch->pm_timer,
1027		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
1028		    ahci_ch_pm, dev);
1029	}
1030	mtx_unlock(&ch->mtx);
1031	return (0);
1032
1033err3:
1034	xpt_bus_deregister(cam_sim_path(ch->sim));
1035err2:
1036	cam_sim_free(ch->sim, /*free_devq*/TRUE);
1037err1:
1038	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
1039err0:
1040	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
1041	mtx_unlock(&ch->mtx);
1042	mtx_destroy(&ch->mtx);
1043	return (error);
1044}
1045
1046static int
1047ahci_ch_detach(device_t dev)
1048{
1049	struct ahci_channel *ch = device_get_softc(dev);
1050
1051	mtx_lock(&ch->mtx);
1052	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
1053	/* Forget about reset. */
1054	if (ch->resetting) {
1055		ch->resetting = 0;
1056		xpt_release_simq(ch->sim, TRUE);
1057	}
1058	xpt_free_path(ch->path);
1059	xpt_bus_deregister(cam_sim_path(ch->sim));
1060	cam_sim_free(ch->sim, /*free_devq*/TRUE);
1061	mtx_unlock(&ch->mtx);
1062
1063	if (ch->pm_level > 3)
1064		callout_drain(&ch->pm_timer);
1065	callout_drain(&ch->reset_timer);
1066	bus_teardown_intr(dev, ch->r_irq, ch->ih);
1067	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
1068
1069	ahci_ch_deinit(dev);
1070	ahci_slotsfree(dev);
1071	ahci_dmafini(dev);
1072
1073	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
1074	mtx_destroy(&ch->mtx);
1075	return (0);
1076}
1077
1078static int
1079ahci_ch_init(device_t dev)
1080{
1081	struct ahci_channel *ch = device_get_softc(dev);
1082	uint64_t work;
1083
1084	/* Disable port interrupts */
1085	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1086	/* Setup work areas */
1087	work = ch->dma.work_bus + AHCI_CL_OFFSET;
1088	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
1089	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
1090	work = ch->dma.rfis_bus;
1091	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
1092	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
1093	/* Activate the channel and power/spin up device */
1094	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
1095	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
1096	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
1097	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
1098	ahci_start_fr(dev);
1099	ahci_start(dev, 1);
1100	return (0);
1101}
1102
1103static int
1104ahci_ch_deinit(device_t dev)
1105{
1106	struct ahci_channel *ch = device_get_softc(dev);
1107
1108	/* Disable port interrupts. */
1109	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1110	/* Reset command register. */
1111	ahci_stop(dev);
1112	ahci_stop_fr(dev);
1113	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
1114	/* Allow everything, including partial and slumber modes. */
1115	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
1116	/* Request slumber mode transition and give some time to get there. */
1117	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
1118	DELAY(100);
1119	/* Disable PHY. */
1120	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
1121	return (0);
1122}
1123
1124static int
1125ahci_ch_suspend(device_t dev)
1126{
1127	struct ahci_channel *ch = device_get_softc(dev);
1128
1129	mtx_lock(&ch->mtx);
1130	xpt_freeze_simq(ch->sim, 1);
1131	/* Forget about reset. */
1132	if (ch->resetting) {
1133		ch->resetting = 0;
1134		callout_stop(&ch->reset_timer);
1135		xpt_release_simq(ch->sim, TRUE);
1136	}
1137	while (ch->oslots)
1138		msleep(ch, &ch->mtx, PRIBIO, "ahcisusp", hz/100);
1139	ahci_ch_deinit(dev);
1140	mtx_unlock(&ch->mtx);
1141	return (0);
1142}
1143
1144static int
1145ahci_ch_resume(device_t dev)
1146{
1147	struct ahci_channel *ch = device_get_softc(dev);
1148
1149	mtx_lock(&ch->mtx);
1150	ahci_ch_init(dev);
1151	ahci_reset(dev);
1152	xpt_release_simq(ch->sim, TRUE);
1153	mtx_unlock(&ch->mtx);
1154	return (0);
1155}
1156
1157devclass_t ahcich_devclass;
1158static device_method_t ahcich_methods[] = {
1159	DEVMETHOD(device_probe,     ahci_ch_probe),
1160	DEVMETHOD(device_attach,    ahci_ch_attach),
1161	DEVMETHOD(device_detach,    ahci_ch_detach),
1162	DEVMETHOD(device_suspend,   ahci_ch_suspend),
1163	DEVMETHOD(device_resume,    ahci_ch_resume),
1164	{ 0, 0 }
1165};
1166static driver_t ahcich_driver = {
1167        "ahcich",
1168        ahcich_methods,
1169        sizeof(struct ahci_channel)
1170};
1171DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahcich_devclass, 0, 0);
1172
1173struct ahci_dc_cb_args {
1174	bus_addr_t maddr;
1175	int error;
1176};
1177
1178static void
1179ahci_dmainit(device_t dev)
1180{
1181	struct ahci_channel *ch = device_get_softc(dev);
1182	struct ahci_dc_cb_args dcba;
1183	size_t rfsize;
1184
1185	if (ch->caps & AHCI_CAP_64BIT)
1186		ch->dma.max_address = BUS_SPACE_MAXADDR;
1187	else
1188		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
1189	/* Command area. */
1190	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
1191	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1192	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
1193	    0, NULL, NULL, &ch->dma.work_tag))
1194		goto error;
1195	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
1196	    &ch->dma.work_map))
1197		goto error;
1198	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
1199	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1200		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1201		goto error;
1202	}
1203	ch->dma.work_bus = dcba.maddr;
1204	/* FIS receive area. */
1205	if (ch->chcaps & AHCI_P_CMD_FBSCP)
1206	    rfsize = 4096;
1207	else
1208	    rfsize = 256;
1209	if (bus_dma_tag_create(bus_get_dma_tag(dev), rfsize, 0,
1210	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1211	    NULL, NULL, rfsize, 1, rfsize,
1212	    0, NULL, NULL, &ch->dma.rfis_tag))
1213		goto error;
1214	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1215	    &ch->dma.rfis_map))
1216		goto error;
1217	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1218	    rfsize, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1219		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1220		goto error;
1221	}
1222	ch->dma.rfis_bus = dcba.maddr;
1223	/* Data area. */
1224	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1225	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1226	    NULL, NULL,
1227	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
1228	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1229	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
1230		goto error;
1231	}
1232	return;
1233
1234error:
1235	device_printf(dev, "WARNING - DMA initialization failed\n");
1236	ahci_dmafini(dev);
1237}
1238
1239static void
1240ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1241{
1242	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1243
1244	if (!(dcba->error = error))
1245		dcba->maddr = segs[0].ds_addr;
1246}
1247
1248static void
1249ahci_dmafini(device_t dev)
1250{
1251	struct ahci_channel *ch = device_get_softc(dev);
1252
1253	if (ch->dma.data_tag) {
1254		bus_dma_tag_destroy(ch->dma.data_tag);
1255		ch->dma.data_tag = NULL;
1256	}
1257	if (ch->dma.rfis_bus) {
1258		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1259		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1260		ch->dma.rfis_bus = 0;
1261		ch->dma.rfis_map = NULL;
1262		ch->dma.rfis = NULL;
1263	}
1264	if (ch->dma.work_bus) {
1265		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1266		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1267		ch->dma.work_bus = 0;
1268		ch->dma.work_map = NULL;
1269		ch->dma.work = NULL;
1270	}
1271	if (ch->dma.work_tag) {
1272		bus_dma_tag_destroy(ch->dma.work_tag);
1273		ch->dma.work_tag = NULL;
1274	}
1275}
1276
1277static void
1278ahci_slotsalloc(device_t dev)
1279{
1280	struct ahci_channel *ch = device_get_softc(dev);
1281	int i;
1282
1283	/* Alloc and setup command/dma slots */
1284	bzero(ch->slot, sizeof(ch->slot));
1285	for (i = 0; i < ch->numslots; i++) {
1286		struct ahci_slot *slot = &ch->slot[i];
1287
1288		slot->dev = dev;
1289		slot->slot = i;
1290		slot->state = AHCI_SLOT_EMPTY;
1291		slot->ccb = NULL;
1292		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1293
1294		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1295			device_printf(ch->dev, "FAILURE - create data_map\n");
1296	}
1297}
1298
1299static void
1300ahci_slotsfree(device_t dev)
1301{
1302	struct ahci_channel *ch = device_get_softc(dev);
1303	int i;
1304
1305	/* Free all dma slots */
1306	for (i = 0; i < ch->numslots; i++) {
1307		struct ahci_slot *slot = &ch->slot[i];
1308
1309		callout_drain(&slot->timeout);
1310		if (slot->dma.data_map) {
1311			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1312			slot->dma.data_map = NULL;
1313		}
1314	}
1315}
1316
1317static int
1318ahci_phy_check_events(device_t dev, u_int32_t serr)
1319{
1320	struct ahci_channel *ch = device_get_softc(dev);
1321
1322	if (((ch->pm_level == 0) && (serr & ATA_SE_PHY_CHANGED)) ||
1323	    ((ch->pm_level != 0 || ch->listening) && (serr & ATA_SE_EXCHANGED))) {
1324		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1325		union ccb *ccb;
1326
1327		if (bootverbose) {
1328			if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
1329				device_printf(dev, "CONNECT requested\n");
1330			else
1331				device_printf(dev, "DISCONNECT requested\n");
1332		}
1333		ahci_reset(dev);
1334		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1335			return (0);
1336		if (xpt_create_path(&ccb->ccb_h.path, NULL,
1337		    cam_sim_path(ch->sim),
1338		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1339			xpt_free_ccb(ccb);
1340			return (0);
1341		}
1342		xpt_rescan(ccb);
1343		return (1);
1344	}
1345	return (0);
1346}
1347
1348static void
1349ahci_cpd_check_events(device_t dev)
1350{
1351	struct ahci_channel *ch = device_get_softc(dev);
1352	u_int32_t status;
1353	union ccb *ccb;
1354
1355	if (ch->pm_level == 0)
1356		return;
1357
1358	status = ATA_INL(ch->r_mem, AHCI_P_CMD);
1359	if ((status & AHCI_P_CMD_CPD) == 0)
1360		return;
1361
1362	if (bootverbose) {
1363		if (status & AHCI_P_CMD_CPS) {
1364			device_printf(dev, "COLD CONNECT requested\n");
1365		} else
1366			device_printf(dev, "COLD DISCONNECT requested\n");
1367	}
1368	ahci_reset(dev);
1369	if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1370		return;
1371	if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(ch->sim),
1372	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1373		xpt_free_ccb(ccb);
1374		return;
1375	}
1376	xpt_rescan(ccb);
1377}
1378
1379static void
1380ahci_notify_events(device_t dev, u_int32_t status)
1381{
1382	struct ahci_channel *ch = device_get_softc(dev);
1383	struct cam_path *dpath;
1384	int i;
1385
1386	if (ch->caps & AHCI_CAP_SSNTF)
1387		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1388	if (bootverbose)
1389		device_printf(dev, "SNTF 0x%04x\n", status);
1390	for (i = 0; i < 16; i++) {
1391		if ((status & (1 << i)) == 0)
1392			continue;
1393		if (xpt_create_path(&dpath, NULL,
1394		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1395			xpt_async(AC_SCSI_AEN, dpath, NULL);
1396			xpt_free_path(dpath);
1397		}
1398	}
1399}
1400
1401static void
1402ahci_ch_intr_locked(void *data)
1403{
1404	device_t dev = (device_t)data;
1405	struct ahci_channel *ch = device_get_softc(dev);
1406
1407	mtx_lock(&ch->mtx);
1408	xpt_batch_start(ch->sim);
1409	ahci_ch_intr(data);
1410	xpt_batch_done(ch->sim);
1411	mtx_unlock(&ch->mtx);
1412}
1413
1414static void
1415ahci_ch_pm(void *arg)
1416{
1417	device_t dev = (device_t)arg;
1418	struct ahci_channel *ch = device_get_softc(dev);
1419	uint32_t work;
1420
1421	if (ch->numrslots != 0)
1422		return;
1423	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1424	if (ch->pm_level == 4)
1425		work |= AHCI_P_CMD_PARTIAL;
1426	else
1427		work |= AHCI_P_CMD_SLUMBER;
1428	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1429}
1430
1431static void
1432ahci_ch_intr(void *data)
1433{
1434	device_t dev = (device_t)data;
1435	struct ahci_channel *ch = device_get_softc(dev);
1436	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1437	enum ahci_err_type et;
1438	int i, ccs, port, reset = 0;
1439
1440	/* Read and clear interrupt statuses. */
1441	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1442	if (istatus == 0)
1443		return;
1444	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1445	/* Read command statuses. */
1446	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1447	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1448	if (istatus & AHCI_P_IX_SDB) {
1449		if (ch->caps & AHCI_CAP_SSNTF)
1450			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1451		else if (ch->fbs_enabled) {
1452			u_int8_t *fis = ch->dma.rfis + 0x58;
1453
1454			for (i = 0; i < 16; i++) {
1455				if (fis[1] & 0x80) {
1456					fis[1] &= 0x7f;
1457	    				sntf |= 1 << i;
1458	    			}
1459	    			fis += 256;
1460	    		}
1461		} else {
1462			u_int8_t *fis = ch->dma.rfis + 0x58;
1463
1464			if (fis[1] & 0x80)
1465				sntf = (1 << (fis[1] & 0x0f));
1466		}
1467	}
1468	/* Process PHY events */
1469	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1470	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1471		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1472		if (serr) {
1473			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1474			reset = ahci_phy_check_events(dev, serr);
1475		}
1476	}
1477	/* Process cold presence detection events */
1478	if ((istatus & AHCI_P_IX_CPD) && !reset)
1479		ahci_cpd_check_events(dev);
1480	/* Process command errors */
1481	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1482	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1483		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1484		    >> AHCI_P_CMD_CCS_SHIFT;
1485//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1486//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1487//    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1488		port = -1;
1489		if (ch->fbs_enabled) {
1490			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1491			if (fbs & AHCI_P_FBS_SDE) {
1492				port = (fbs & AHCI_P_FBS_DWE)
1493				    >> AHCI_P_FBS_DWE_SHIFT;
1494			} else {
1495				for (i = 0; i < 16; i++) {
1496					if (ch->numrslotspd[i] == 0)
1497						continue;
1498					if (port == -1)
1499						port = i;
1500					else if (port != i) {
1501						port = -2;
1502						break;
1503					}
1504				}
1505			}
1506		}
1507		err = ch->rslots & (cstatus | sstatus);
1508	} else {
1509		ccs = 0;
1510		err = 0;
1511		port = -1;
1512	}
1513	/* Complete all successfull commands. */
1514	ok = ch->rslots & ~(cstatus | sstatus);
1515	for (i = 0; i < ch->numslots; i++) {
1516		if ((ok >> i) & 1)
1517			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1518	}
1519	/* On error, complete the rest of commands with error statuses. */
1520	if (err) {
1521		if (ch->frozen) {
1522			union ccb *fccb = ch->frozen;
1523			ch->frozen = NULL;
1524			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1525			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1526				xpt_freeze_devq(fccb->ccb_h.path, 1);
1527				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1528			}
1529			xpt_done(fccb);
1530		}
1531		for (i = 0; i < ch->numslots; i++) {
1532			/* XXX: reqests in loading state. */
1533			if (((err >> i) & 1) == 0)
1534				continue;
1535			if (port >= 0 &&
1536			    ch->slot[i].ccb->ccb_h.target_id != port)
1537				continue;
1538			if (istatus & AHCI_P_IX_TFE) {
1539			    if (port != -2) {
1540				/* Task File Error */
1541				if (ch->numtslotspd[
1542				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1543					/* Untagged operation. */
1544					if (i == ccs)
1545						et = AHCI_ERR_TFE;
1546					else
1547						et = AHCI_ERR_INNOCENT;
1548				} else {
1549					/* Tagged operation. */
1550					et = AHCI_ERR_NCQ;
1551				}
1552			    } else {
1553				et = AHCI_ERR_TFE;
1554				ch->fatalerr = 1;
1555			    }
1556			} else if (istatus & AHCI_P_IX_IF) {
1557				if (ch->numtslots == 0 && i != ccs && port != -2)
1558					et = AHCI_ERR_INNOCENT;
1559				else
1560					et = AHCI_ERR_SATA;
1561			} else
1562				et = AHCI_ERR_INVALID;
1563			ahci_end_transaction(&ch->slot[i], et);
1564		}
1565		/*
1566		 * We can't reinit port if there are some other
1567		 * commands active, use resume to complete them.
1568		 */
1569		if (ch->rslots != 0 && !ch->recoverycmd)
1570			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1571	}
1572	/* Process NOTIFY events */
1573	if (sntf)
1574		ahci_notify_events(dev, sntf);
1575}
1576
1577/* Must be called with channel locked. */
1578static int
1579ahci_check_collision(device_t dev, union ccb *ccb)
1580{
1581	struct ahci_channel *ch = device_get_softc(dev);
1582	int t = ccb->ccb_h.target_id;
1583
1584	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1585	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1586		/* Tagged command while we have no supported tag free. */
1587		if (((~ch->oslots) & (0xffffffff >> (32 -
1588		    ch->curr[t].tags))) == 0)
1589			return (1);
1590		/* If we have FBS */
1591		if (ch->fbs_enabled) {
1592			/* Tagged command while untagged are active. */
1593			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1594				return (1);
1595		} else {
1596			/* Tagged command while untagged are active. */
1597			if (ch->numrslots != 0 && ch->numtslots == 0)
1598				return (1);
1599			/* Tagged command while tagged to other target is active. */
1600			if (ch->numtslots != 0 &&
1601			    ch->taggedtarget != ccb->ccb_h.target_id)
1602				return (1);
1603		}
1604	} else {
1605		/* If we have FBS */
1606		if (ch->fbs_enabled) {
1607			/* Untagged command while tagged are active. */
1608			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1609				return (1);
1610		} else {
1611			/* Untagged command while tagged are active. */
1612			if (ch->numrslots != 0 && ch->numtslots != 0)
1613				return (1);
1614		}
1615	}
1616	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1617	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1618		/* Atomic command while anything active. */
1619		if (ch->numrslots != 0)
1620			return (1);
1621	}
1622       /* We have some atomic command running. */
1623       if (ch->aslots != 0)
1624               return (1);
1625	return (0);
1626}
1627
1628/* Must be called with channel locked. */
1629static void
1630ahci_begin_transaction(device_t dev, union ccb *ccb)
1631{
1632	struct ahci_channel *ch = device_get_softc(dev);
1633	struct ahci_slot *slot;
1634	int tag, tags;
1635
1636	/* Choose empty slot. */
1637	tags = ch->numslots;
1638	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1639	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1640		tags = ch->curr[ccb->ccb_h.target_id].tags;
1641	tag = ch->lastslot;
1642	while (1) {
1643		if (tag >= tags)
1644			tag = 0;
1645		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1646			break;
1647		tag++;
1648	};
1649	ch->lastslot = tag;
1650	/* Occupy chosen slot. */
1651	slot = &ch->slot[tag];
1652	slot->ccb = ccb;
1653	/* Stop PM timer. */
1654	if (ch->numrslots == 0 && ch->pm_level > 3)
1655		callout_stop(&ch->pm_timer);
1656	/* Update channel stats. */
1657	ch->oslots |= (1 << slot->slot);
1658	ch->numrslots++;
1659	ch->numrslotspd[ccb->ccb_h.target_id]++;
1660	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1661	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1662		ch->numtslots++;
1663		ch->numtslotspd[ccb->ccb_h.target_id]++;
1664		ch->taggedtarget = ccb->ccb_h.target_id;
1665	}
1666	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1667	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1668		ch->aslots |= (1 << slot->slot);
1669	slot->dma.nsegs = 0;
1670	/* If request moves data, setup and load SG list */
1671	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1672		void *buf;
1673		bus_size_t size;
1674
1675		slot->state = AHCI_SLOT_LOADING;
1676		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1677			buf = ccb->ataio.data_ptr;
1678			size = ccb->ataio.dxfer_len;
1679		} else {
1680			buf = ccb->csio.data_ptr;
1681			size = ccb->csio.dxfer_len;
1682		}
1683		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1684		    buf, size, ahci_dmasetprd, slot, 0);
1685	} else
1686		ahci_execute_transaction(slot);
1687}
1688
1689/* Locked by busdma engine. */
1690static void
1691ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1692{
1693	struct ahci_slot *slot = arg;
1694	struct ahci_channel *ch = device_get_softc(slot->dev);
1695	struct ahci_cmd_tab *ctp;
1696	struct ahci_dma_prd *prd;
1697	int i;
1698
1699	if (error) {
1700		device_printf(slot->dev, "DMA load error\n");
1701		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1702		return;
1703	}
1704	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1705	/* Get a piece of the workspace for this request */
1706	ctp = (struct ahci_cmd_tab *)
1707		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1708	/* Fill S/G table */
1709	prd = &ctp->prd_tab[0];
1710	for (i = 0; i < nsegs; i++) {
1711		prd[i].dba = htole64(segs[i].ds_addr);
1712		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1713	}
1714	slot->dma.nsegs = nsegs;
1715	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1716	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1717	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1718	ahci_execute_transaction(slot);
1719}
1720
1721/* Must be called with channel locked. */
1722static void
1723ahci_execute_transaction(struct ahci_slot *slot)
1724{
1725	device_t dev = slot->dev;
1726	struct ahci_channel *ch = device_get_softc(dev);
1727	struct ahci_cmd_tab *ctp;
1728	struct ahci_cmd_list *clp;
1729	union ccb *ccb = slot->ccb;
1730	int port = ccb->ccb_h.target_id & 0x0f;
1731	int fis_size, i, softreset;
1732	uint8_t *fis = ch->dma.rfis + 0x40;
1733	uint8_t val;
1734
1735	/* Get a piece of the workspace for this request */
1736	ctp = (struct ahci_cmd_tab *)
1737		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1738	/* Setup the FIS for this request */
1739	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1740		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1741		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1742		return;
1743	}
1744	/* Setup the command list entry */
1745	clp = (struct ahci_cmd_list *)
1746	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1747	clp->cmd_flags = htole16(
1748		    (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1749		    (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1750		     (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1751		    (fis_size / sizeof(u_int32_t)) |
1752		    (port << 12));
1753	clp->prd_length = htole16(slot->dma.nsegs);
1754	/* Special handling for Soft Reset command. */
1755	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1756	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1757		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1758			softreset = 1;
1759			/* Kick controller into sane state */
1760			ahci_stop(dev);
1761			ahci_clo(dev);
1762			ahci_start(dev, 0);
1763			clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1764		} else {
1765			softreset = 2;
1766			/* Prepare FIS receive area for check. */
1767			for (i = 0; i < 20; i++)
1768				fis[i] = 0xff;
1769		}
1770	} else
1771		softreset = 0;
1772	clp->bytecount = 0;
1773	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1774				  (AHCI_CT_SIZE * slot->slot));
1775	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1776	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1777	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1778	    BUS_DMASYNC_PREREAD);
1779	/* Set ACTIVE bit for NCQ commands. */
1780	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1781	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1782		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1783	}
1784	/* If FBS is enabled, set PMP port. */
1785	if (ch->fbs_enabled) {
1786		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1787		    (port << AHCI_P_FBS_DEV_SHIFT));
1788	}
1789	/* Issue command to the controller. */
1790	slot->state = AHCI_SLOT_RUNNING;
1791	ch->rslots |= (1 << slot->slot);
1792	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1793	/* Device reset commands doesn't interrupt. Poll them. */
1794	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1795	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET || softreset)) {
1796		int count, timeout = ccb->ccb_h.timeout * 100;
1797		enum ahci_err_type et = AHCI_ERR_NONE;
1798
1799		for (count = 0; count < timeout; count++) {
1800			DELAY(10);
1801			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1802				break;
1803			if ((ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) &&
1804			    softreset != 1) {
1805#if 0
1806				device_printf(ch->dev,
1807				    "Poll error on slot %d, TFD: %04x\n",
1808				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1809#endif
1810				et = AHCI_ERR_TFE;
1811				break;
1812			}
1813			/* Workaround for ATI SB600/SB700 chipsets. */
1814			if (ccb->ccb_h.target_id == 15 &&
1815			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1816			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1817				et = AHCI_ERR_TIMEOUT;
1818				break;
1819			}
1820		}
1821
1822		/* Marvell controllers do not wait for readyness. */
1823		if ((ch->quirks & AHCI_Q_NOBSYRES) && softreset == 2 &&
1824		    et == AHCI_ERR_NONE) {
1825			while ((val = fis[2]) & ATA_S_BUSY) {
1826				DELAY(10);
1827				if (count++ >= timeout)
1828					break;
1829			}
1830		}
1831
1832		if (timeout && (count >= timeout)) {
1833			device_printf(dev, "Poll timeout on slot %d port %d\n",
1834			    slot->slot, port);
1835			device_printf(dev, "is %08x cs %08x ss %08x "
1836			    "rs %08x tfd %02x serr %08x cmd %08x\n",
1837			    ATA_INL(ch->r_mem, AHCI_P_IS),
1838			    ATA_INL(ch->r_mem, AHCI_P_CI),
1839			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1840			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1841			    ATA_INL(ch->r_mem, AHCI_P_SERR),
1842			    ATA_INL(ch->r_mem, AHCI_P_CMD));
1843			et = AHCI_ERR_TIMEOUT;
1844		}
1845
1846		/* Kick controller into sane state and enable FBS. */
1847		if (softreset == 2)
1848			ch->eslots |= (1 << slot->slot);
1849		ahci_end_transaction(slot, et);
1850		return;
1851	}
1852	/* Start command execution timeout */
1853	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1854	    (timeout_t*)ahci_timeout, slot);
1855	return;
1856}
1857
1858/* Must be called with channel locked. */
1859static void
1860ahci_process_timeout(device_t dev)
1861{
1862	struct ahci_channel *ch = device_get_softc(dev);
1863	int i;
1864
1865	mtx_assert(&ch->mtx, MA_OWNED);
1866	/* Handle the rest of commands. */
1867	for (i = 0; i < ch->numslots; i++) {
1868		/* Do we have a running request on slot? */
1869		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1870			continue;
1871		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1872	}
1873}
1874
1875/* Must be called with channel locked. */
1876static void
1877ahci_rearm_timeout(device_t dev)
1878{
1879	struct ahci_channel *ch = device_get_softc(dev);
1880	int i;
1881
1882	mtx_assert(&ch->mtx, MA_OWNED);
1883	for (i = 0; i < ch->numslots; i++) {
1884		struct ahci_slot *slot = &ch->slot[i];
1885
1886		/* Do we have a running request on slot? */
1887		if (slot->state < AHCI_SLOT_RUNNING)
1888			continue;
1889		if ((ch->toslots & (1 << i)) == 0)
1890			continue;
1891		callout_reset(&slot->timeout,
1892		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1893		    (timeout_t*)ahci_timeout, slot);
1894	}
1895}
1896
1897/* Locked by callout mechanism. */
1898static void
1899ahci_timeout(struct ahci_slot *slot)
1900{
1901	device_t dev = slot->dev;
1902	struct ahci_channel *ch = device_get_softc(dev);
1903	uint32_t sstatus;
1904	int ccs;
1905	int i;
1906
1907	/* Check for stale timeout. */
1908	if (slot->state < AHCI_SLOT_RUNNING)
1909		return;
1910
1911	/* Check if slot was not being executed last time we checked. */
1912	if (slot->state < AHCI_SLOT_EXECUTING) {
1913		/* Check if slot started executing. */
1914		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1915		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1916		    >> AHCI_P_CMD_CCS_SHIFT;
1917		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1918		    ch->fbs_enabled || ch->wrongccs)
1919			slot->state = AHCI_SLOT_EXECUTING;
1920		else if ((ch->rslots & (1 << ccs)) == 0) {
1921			ch->wrongccs = 1;
1922			slot->state = AHCI_SLOT_EXECUTING;
1923		}
1924
1925		callout_reset(&slot->timeout,
1926		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1927		    (timeout_t*)ahci_timeout, slot);
1928		return;
1929	}
1930
1931	device_printf(dev, "Timeout on slot %d port %d\n",
1932	    slot->slot, slot->ccb->ccb_h.target_id & 0x0f);
1933	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x "
1934	    "serr %08x cmd %08x\n",
1935	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1936	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1937	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR),
1938	    ATA_INL(ch->r_mem, AHCI_P_CMD));
1939
1940	/* Handle frozen command. */
1941	if (ch->frozen) {
1942		union ccb *fccb = ch->frozen;
1943		ch->frozen = NULL;
1944		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1945		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1946			xpt_freeze_devq(fccb->ccb_h.path, 1);
1947			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1948		}
1949		xpt_done(fccb);
1950	}
1951	if (!ch->fbs_enabled && !ch->wrongccs) {
1952		/* Without FBS we know real timeout source. */
1953		ch->fatalerr = 1;
1954		/* Handle command with timeout. */
1955		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1956		/* Handle the rest of commands. */
1957		for (i = 0; i < ch->numslots; i++) {
1958			/* Do we have a running request on slot? */
1959			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1960				continue;
1961			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1962		}
1963	} else {
1964		/* With FBS we wait for other commands timeout and pray. */
1965		if (ch->toslots == 0)
1966			xpt_freeze_simq(ch->sim, 1);
1967		ch->toslots |= (1 << slot->slot);
1968		if ((ch->rslots & ~ch->toslots) == 0)
1969			ahci_process_timeout(dev);
1970		else
1971			device_printf(dev, " ... waiting for slots %08x\n",
1972			    ch->rslots & ~ch->toslots);
1973	}
1974}
1975
1976/* Must be called with channel locked. */
1977static void
1978ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1979{
1980	device_t dev = slot->dev;
1981	struct ahci_channel *ch = device_get_softc(dev);
1982	union ccb *ccb = slot->ccb;
1983	struct ahci_cmd_list *clp;
1984	int lastto;
1985	uint32_t sig;
1986
1987	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1988	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1989	clp = (struct ahci_cmd_list *)
1990	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1991	/* Read result registers to the result struct
1992	 * May be incorrect if several commands finished same time,
1993	 * so read only when sure or have to.
1994	 */
1995	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1996		struct ata_res *res = &ccb->ataio.res;
1997
1998		if ((et == AHCI_ERR_TFE) ||
1999		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
2000			u_int8_t *fis = ch->dma.rfis + 0x40;
2001
2002			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
2003			    BUS_DMASYNC_POSTREAD);
2004			if (ch->fbs_enabled) {
2005				fis += ccb->ccb_h.target_id * 256;
2006				res->status = fis[2];
2007				res->error = fis[3];
2008			} else {
2009				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
2010
2011				res->status = tfd;
2012				res->error = tfd >> 8;
2013			}
2014			res->lba_low = fis[4];
2015			res->lba_mid = fis[5];
2016			res->lba_high = fis[6];
2017			res->device = fis[7];
2018			res->lba_low_exp = fis[8];
2019			res->lba_mid_exp = fis[9];
2020			res->lba_high_exp = fis[10];
2021			res->sector_count = fis[12];
2022			res->sector_count_exp = fis[13];
2023
2024			/*
2025			 * Some weird controllers do not return signature in
2026			 * FIS receive area. Read it from PxSIG register.
2027			 */
2028			if ((ch->quirks & AHCI_Q_ALTSIG) &&
2029			    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
2030			    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
2031				sig = ATA_INL(ch->r_mem,  AHCI_P_SIG);
2032				res->lba_high = sig >> 24;
2033				res->lba_mid = sig >> 16;
2034				res->lba_low = sig >> 8;
2035				res->sector_count = sig;
2036			}
2037		} else
2038			bzero(res, sizeof(*res));
2039		if ((ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) == 0 &&
2040		    (ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2041		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
2042			ccb->ataio.resid =
2043			    ccb->ataio.dxfer_len - le32toh(clp->bytecount);
2044		}
2045	} else {
2046		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2047		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
2048			ccb->csio.resid =
2049			    ccb->csio.dxfer_len - le32toh(clp->bytecount);
2050		}
2051	}
2052	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2053		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
2054		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
2055		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
2056		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
2057	}
2058	if (et != AHCI_ERR_NONE)
2059		ch->eslots |= (1 << slot->slot);
2060	/* In case of error, freeze device for proper recovery. */
2061	if ((et != AHCI_ERR_NONE) && (!ch->recoverycmd) &&
2062	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
2063		xpt_freeze_devq(ccb->ccb_h.path, 1);
2064		ccb->ccb_h.status |= CAM_DEV_QFRZN;
2065	}
2066	/* Set proper result status. */
2067	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2068	switch (et) {
2069	case AHCI_ERR_NONE:
2070		ccb->ccb_h.status |= CAM_REQ_CMP;
2071		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
2072			ccb->csio.scsi_status = SCSI_STATUS_OK;
2073		break;
2074	case AHCI_ERR_INVALID:
2075		ch->fatalerr = 1;
2076		ccb->ccb_h.status |= CAM_REQ_INVALID;
2077		break;
2078	case AHCI_ERR_INNOCENT:
2079		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
2080		break;
2081	case AHCI_ERR_TFE:
2082	case AHCI_ERR_NCQ:
2083		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2084			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
2085			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2086		} else {
2087			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
2088		}
2089		break;
2090	case AHCI_ERR_SATA:
2091		ch->fatalerr = 1;
2092		if (!ch->recoverycmd) {
2093			xpt_freeze_simq(ch->sim, 1);
2094			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2095			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2096		}
2097		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
2098		break;
2099	case AHCI_ERR_TIMEOUT:
2100		if (!ch->recoverycmd) {
2101			xpt_freeze_simq(ch->sim, 1);
2102			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2103			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2104		}
2105		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
2106		break;
2107	default:
2108		ch->fatalerr = 1;
2109		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2110	}
2111	/* Free slot. */
2112	ch->oslots &= ~(1 << slot->slot);
2113	ch->rslots &= ~(1 << slot->slot);
2114	ch->aslots &= ~(1 << slot->slot);
2115	slot->state = AHCI_SLOT_EMPTY;
2116	slot->ccb = NULL;
2117	/* Update channel stats. */
2118	ch->numrslots--;
2119	ch->numrslotspd[ccb->ccb_h.target_id]--;
2120	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2121	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
2122		ch->numtslots--;
2123		ch->numtslotspd[ccb->ccb_h.target_id]--;
2124	}
2125	/* Cancel timeout state if request completed normally. */
2126	if (et != AHCI_ERR_TIMEOUT) {
2127		lastto = (ch->toslots == (1 << slot->slot));
2128		ch->toslots &= ~(1 << slot->slot);
2129		if (lastto)
2130			xpt_release_simq(ch->sim, TRUE);
2131	}
2132	/* If it was first request of reset sequence and there is no error,
2133	 * proceed to second request. */
2134	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2135	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
2136	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
2137	    et == AHCI_ERR_NONE) {
2138		ccb->ataio.cmd.control &= ~ATA_A_RESET;
2139		ahci_begin_transaction(dev, ccb);
2140		return;
2141	}
2142	/* If it was our READ LOG command - process it. */
2143	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
2144		ahci_process_read_log(dev, ccb);
2145	/* If it was our REQUEST SENSE command - process it. */
2146	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
2147		ahci_process_request_sense(dev, ccb);
2148	/* If it was NCQ or ATAPI command error, put result on hold. */
2149	} else if (et == AHCI_ERR_NCQ ||
2150	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
2151	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
2152		ch->hold[slot->slot] = ccb;
2153		ch->numhslots++;
2154	} else
2155		xpt_done(ccb);
2156	/* If we have no other active commands, ... */
2157	if (ch->rslots == 0) {
2158		/* if there was fatal error - reset port. */
2159		if (ch->toslots != 0 || ch->fatalerr) {
2160			ahci_reset(dev);
2161		} else {
2162			/* if we have slots in error, we can reinit port. */
2163			if (ch->eslots != 0) {
2164				ahci_stop(dev);
2165				ahci_clo(dev);
2166				ahci_start(dev, 1);
2167			}
2168			/* if there commands on hold, we can do READ LOG. */
2169			if (!ch->recoverycmd && ch->numhslots)
2170				ahci_issue_recovery(dev);
2171		}
2172	/* If all the rest of commands are in timeout - give them chance. */
2173	} else if ((ch->rslots & ~ch->toslots) == 0 &&
2174	    et != AHCI_ERR_TIMEOUT)
2175		ahci_rearm_timeout(dev);
2176	/* Unfreeze frozen command. */
2177	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
2178		union ccb *fccb = ch->frozen;
2179		ch->frozen = NULL;
2180		ahci_begin_transaction(dev, fccb);
2181		xpt_release_simq(ch->sim, TRUE);
2182	}
2183	/* Start PM timer. */
2184	if (ch->numrslots == 0 && ch->pm_level > 3 &&
2185	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
2186		callout_schedule(&ch->pm_timer,
2187		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
2188	}
2189}
2190
2191static void
2192ahci_issue_recovery(device_t dev)
2193{
2194	struct ahci_channel *ch = device_get_softc(dev);
2195	union ccb *ccb;
2196	struct ccb_ataio *ataio;
2197	struct ccb_scsiio *csio;
2198	int i;
2199
2200	/* Find some held command. */
2201	for (i = 0; i < ch->numslots; i++) {
2202		if (ch->hold[i])
2203			break;
2204	}
2205	ccb = xpt_alloc_ccb_nowait();
2206	if (ccb == NULL) {
2207		device_printf(dev, "Unable to allocate recovery command\n");
2208completeall:
2209		/* We can't do anything -- complete held commands. */
2210		for (i = 0; i < ch->numslots; i++) {
2211			if (ch->hold[i] == NULL)
2212				continue;
2213			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2214			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
2215			xpt_done(ch->hold[i]);
2216			ch->hold[i] = NULL;
2217			ch->numhslots--;
2218		}
2219		ahci_reset(dev);
2220		return;
2221	}
2222	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
2223	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2224		/* READ LOG */
2225		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
2226		ccb->ccb_h.func_code = XPT_ATA_IO;
2227		ccb->ccb_h.flags = CAM_DIR_IN;
2228		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2229		ataio = &ccb->ataio;
2230		ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
2231		if (ataio->data_ptr == NULL) {
2232			xpt_free_ccb(ccb);
2233			device_printf(dev,
2234			    "Unable to allocate memory for READ LOG command\n");
2235			goto completeall;
2236		}
2237		ataio->dxfer_len = 512;
2238		bzero(&ataio->cmd, sizeof(ataio->cmd));
2239		ataio->cmd.flags = CAM_ATAIO_48BIT;
2240		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
2241		ataio->cmd.sector_count = 1;
2242		ataio->cmd.sector_count_exp = 0;
2243		ataio->cmd.lba_low = 0x10;
2244		ataio->cmd.lba_mid = 0;
2245		ataio->cmd.lba_mid_exp = 0;
2246	} else {
2247		/* REQUEST SENSE */
2248		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
2249		ccb->ccb_h.recovery_slot = i;
2250		ccb->ccb_h.func_code = XPT_SCSI_IO;
2251		ccb->ccb_h.flags = CAM_DIR_IN;
2252		ccb->ccb_h.status = 0;
2253		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2254		csio = &ccb->csio;
2255		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
2256		csio->dxfer_len = ch->hold[i]->csio.sense_len;
2257		csio->cdb_len = 6;
2258		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
2259		csio->cdb_io.cdb_bytes[0] = 0x03;
2260		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
2261	}
2262	/* Freeze SIM while doing recovery. */
2263	ch->recoverycmd = 1;
2264	xpt_freeze_simq(ch->sim, 1);
2265	ahci_begin_transaction(dev, ccb);
2266}
2267
2268static void
2269ahci_process_read_log(device_t dev, union ccb *ccb)
2270{
2271	struct ahci_channel *ch = device_get_softc(dev);
2272	uint8_t *data;
2273	struct ata_res *res;
2274	int i;
2275
2276	ch->recoverycmd = 0;
2277
2278	data = ccb->ataio.data_ptr;
2279	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2280	    (data[0] & 0x80) == 0) {
2281		for (i = 0; i < ch->numslots; i++) {
2282			if (!ch->hold[i])
2283				continue;
2284			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2285				continue;
2286			if ((data[0] & 0x1F) == i) {
2287				res = &ch->hold[i]->ataio.res;
2288				res->status = data[2];
2289				res->error = data[3];
2290				res->lba_low = data[4];
2291				res->lba_mid = data[5];
2292				res->lba_high = data[6];
2293				res->device = data[7];
2294				res->lba_low_exp = data[8];
2295				res->lba_mid_exp = data[9];
2296				res->lba_high_exp = data[10];
2297				res->sector_count = data[12];
2298				res->sector_count_exp = data[13];
2299			} else {
2300				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2301				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2302			}
2303			xpt_done(ch->hold[i]);
2304			ch->hold[i] = NULL;
2305			ch->numhslots--;
2306		}
2307	} else {
2308		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2309			device_printf(dev, "Error while READ LOG EXT\n");
2310		else if ((data[0] & 0x80) == 0) {
2311			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
2312		}
2313		for (i = 0; i < ch->numslots; i++) {
2314			if (!ch->hold[i])
2315				continue;
2316			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2317				continue;
2318			xpt_done(ch->hold[i]);
2319			ch->hold[i] = NULL;
2320			ch->numhslots--;
2321		}
2322	}
2323	free(ccb->ataio.data_ptr, M_AHCI);
2324	xpt_free_ccb(ccb);
2325	xpt_release_simq(ch->sim, TRUE);
2326}
2327
2328static void
2329ahci_process_request_sense(device_t dev, union ccb *ccb)
2330{
2331	struct ahci_channel *ch = device_get_softc(dev);
2332	int i;
2333
2334	ch->recoverycmd = 0;
2335
2336	i = ccb->ccb_h.recovery_slot;
2337	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2338		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
2339	} else {
2340		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2341		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
2342	}
2343	xpt_done(ch->hold[i]);
2344	ch->hold[i] = NULL;
2345	ch->numhslots--;
2346	xpt_free_ccb(ccb);
2347	xpt_release_simq(ch->sim, TRUE);
2348}
2349
2350static void
2351ahci_start(device_t dev, int fbs)
2352{
2353	struct ahci_channel *ch = device_get_softc(dev);
2354	u_int32_t cmd;
2355
2356	/* Clear SATA error register */
2357	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2358	/* Clear any interrupts pending on this channel */
2359	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2360	/* Configure FIS-based switching if supported. */
2361	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2362		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2363		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2364		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2365	}
2366	/* Start operations on this channel */
2367	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2368	cmd &= ~AHCI_P_CMD_PMA;
2369	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2370	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2371}
2372
2373static void
2374ahci_stop(device_t dev)
2375{
2376	struct ahci_channel *ch = device_get_softc(dev);
2377	u_int32_t cmd;
2378	int timeout;
2379
2380	/* Kill all activity on this channel */
2381	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2382	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2383	/* Wait for activity stop. */
2384	timeout = 0;
2385	do {
2386		DELAY(10);
2387		if (timeout++ > 50000) {
2388			device_printf(dev, "stopping AHCI engine failed\n");
2389			break;
2390		}
2391	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2392	ch->eslots = 0;
2393}
2394
2395static void
2396ahci_clo(device_t dev)
2397{
2398	struct ahci_channel *ch = device_get_softc(dev);
2399	u_int32_t cmd;
2400	int timeout;
2401
2402	/* Issue Command List Override if supported */
2403	if (ch->caps & AHCI_CAP_SCLO) {
2404		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2405		cmd |= AHCI_P_CMD_CLO;
2406		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2407		timeout = 0;
2408		do {
2409			DELAY(10);
2410			if (timeout++ > 50000) {
2411			    device_printf(dev, "executing CLO failed\n");
2412			    break;
2413			}
2414		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2415	}
2416}
2417
2418static void
2419ahci_stop_fr(device_t dev)
2420{
2421	struct ahci_channel *ch = device_get_softc(dev);
2422	u_int32_t cmd;
2423	int timeout;
2424
2425	/* Kill all FIS reception on this channel */
2426	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2427	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2428	/* Wait for FIS reception stop. */
2429	timeout = 0;
2430	do {
2431		DELAY(10);
2432		if (timeout++ > 50000) {
2433			device_printf(dev, "stopping AHCI FR engine failed\n");
2434			break;
2435		}
2436	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2437}
2438
2439static void
2440ahci_start_fr(device_t dev)
2441{
2442	struct ahci_channel *ch = device_get_softc(dev);
2443	u_int32_t cmd;
2444
2445	/* Start FIS reception on this channel */
2446	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2447	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2448}
2449
2450static int
2451ahci_wait_ready(device_t dev, int t, int t0)
2452{
2453	struct ahci_channel *ch = device_get_softc(dev);
2454	int timeout = 0;
2455	uint32_t val;
2456
2457	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2458	    (ATA_S_BUSY | ATA_S_DRQ)) {
2459		if (timeout > t) {
2460			if (t != 0) {
2461				device_printf(dev,
2462				    "AHCI reset: device not ready after %dms "
2463				    "(tfd = %08x)\n",
2464				    MAX(t, 0) + t0, val);
2465			}
2466			return (EBUSY);
2467		}
2468		DELAY(1000);
2469		timeout++;
2470	}
2471	if (bootverbose)
2472		device_printf(dev, "AHCI reset: device ready after %dms\n",
2473		    timeout + t0);
2474	return (0);
2475}
2476
2477static void
2478ahci_reset_to(void *arg)
2479{
2480	device_t dev = arg;
2481	struct ahci_channel *ch = device_get_softc(dev);
2482
2483	if (ch->resetting == 0)
2484		return;
2485	ch->resetting--;
2486	if (ahci_wait_ready(dev, ch->resetting == 0 ? -1 : 0,
2487	    (310 - ch->resetting) * 100) == 0) {
2488		ch->resetting = 0;
2489		ahci_start(dev, 1);
2490		xpt_release_simq(ch->sim, TRUE);
2491		return;
2492	}
2493	if (ch->resetting == 0) {
2494		ahci_clo(dev);
2495		ahci_start(dev, 1);
2496		xpt_release_simq(ch->sim, TRUE);
2497		return;
2498	}
2499	callout_schedule(&ch->reset_timer, hz / 10);
2500}
2501
2502static void
2503ahci_reset(device_t dev)
2504{
2505	struct ahci_channel *ch = device_get_softc(dev);
2506	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
2507	int i;
2508
2509	xpt_freeze_simq(ch->sim, 1);
2510	if (bootverbose)
2511		device_printf(dev, "AHCI reset...\n");
2512	/* Forget about previous reset. */
2513	if (ch->resetting) {
2514		ch->resetting = 0;
2515		callout_stop(&ch->reset_timer);
2516		xpt_release_simq(ch->sim, TRUE);
2517	}
2518	/* Requeue freezed command. */
2519	if (ch->frozen) {
2520		union ccb *fccb = ch->frozen;
2521		ch->frozen = NULL;
2522		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2523		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2524			xpt_freeze_devq(fccb->ccb_h.path, 1);
2525			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2526		}
2527		xpt_done(fccb);
2528	}
2529	/* Kill the engine and requeue all running commands. */
2530	ahci_stop(dev);
2531	for (i = 0; i < ch->numslots; i++) {
2532		/* Do we have a running request on slot? */
2533		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2534			continue;
2535		/* XXX; Commands in loading state. */
2536		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2537	}
2538	for (i = 0; i < ch->numslots; i++) {
2539		if (!ch->hold[i])
2540			continue;
2541		xpt_done(ch->hold[i]);
2542		ch->hold[i] = NULL;
2543		ch->numhslots--;
2544	}
2545	if (ch->toslots != 0)
2546		xpt_release_simq(ch->sim, TRUE);
2547	ch->eslots = 0;
2548	ch->toslots = 0;
2549	ch->wrongccs = 0;
2550	ch->fatalerr = 0;
2551	/* Tell the XPT about the event */
2552	xpt_async(AC_BUS_RESET, ch->path, NULL);
2553	/* Disable port interrupts */
2554	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2555	/* Reset and reconnect PHY, */
2556	if (!ahci_sata_phy_reset(dev)) {
2557		if (bootverbose)
2558			device_printf(dev,
2559			    "AHCI reset: device not found\n");
2560		ch->devices = 0;
2561		/* Enable wanted port interrupts */
2562		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2563		    (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2564		     AHCI_P_IX_PRC | AHCI_P_IX_PC));
2565		xpt_release_simq(ch->sim, TRUE);
2566		return;
2567	}
2568	if (bootverbose)
2569		device_printf(dev, "AHCI reset: device found\n");
2570	/* Wait for clearing busy status. */
2571	if (ahci_wait_ready(dev, dumping ? 31000 : 0, 0)) {
2572		if (dumping)
2573			ahci_clo(dev);
2574		else
2575			ch->resetting = 310;
2576	}
2577	ch->devices = 1;
2578	/* Enable wanted port interrupts */
2579	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2580	     (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2581	      AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2582	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2583	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC : 0) | AHCI_P_IX_PC |
2584	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2585	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2586	if (ch->resetting)
2587		callout_reset(&ch->reset_timer, hz / 10, ahci_reset_to, dev);
2588	else {
2589		ahci_start(dev, 1);
2590		xpt_release_simq(ch->sim, TRUE);
2591	}
2592}
2593
2594static int
2595ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2596{
2597	struct ahci_channel *ch = device_get_softc(dev);
2598	u_int8_t *fis = &ctp->cfis[0];
2599
2600	bzero(ctp->cfis, 64);
2601	fis[0] = 0x27;  		/* host to device */
2602	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2603	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2604		fis[1] |= 0x80;
2605		fis[2] = ATA_PACKET_CMD;
2606		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2607		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2608			fis[3] = ATA_F_DMA;
2609		else {
2610			fis[5] = ccb->csio.dxfer_len;
2611		        fis[6] = ccb->csio.dxfer_len >> 8;
2612		}
2613		fis[7] = ATA_D_LBA;
2614		fis[15] = ATA_A_4BIT;
2615		bzero(ctp->acmd, 32);
2616		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2617		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2618		    ctp->acmd, ccb->csio.cdb_len);
2619	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2620		fis[1] |= 0x80;
2621		fis[2] = ccb->ataio.cmd.command;
2622		fis[3] = ccb->ataio.cmd.features;
2623		fis[4] = ccb->ataio.cmd.lba_low;
2624		fis[5] = ccb->ataio.cmd.lba_mid;
2625		fis[6] = ccb->ataio.cmd.lba_high;
2626		fis[7] = ccb->ataio.cmd.device;
2627		fis[8] = ccb->ataio.cmd.lba_low_exp;
2628		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2629		fis[10] = ccb->ataio.cmd.lba_high_exp;
2630		fis[11] = ccb->ataio.cmd.features_exp;
2631		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2632			fis[12] = tag << 3;
2633			fis[13] = 0;
2634		} else {
2635			fis[12] = ccb->ataio.cmd.sector_count;
2636			fis[13] = ccb->ataio.cmd.sector_count_exp;
2637		}
2638		fis[15] = ATA_A_4BIT;
2639	} else {
2640		fis[15] = ccb->ataio.cmd.control;
2641	}
2642	return (20);
2643}
2644
2645static int
2646ahci_sata_connect(struct ahci_channel *ch)
2647{
2648	u_int32_t status;
2649	int timeout, found = 0;
2650
2651	/* Wait up to 100ms for "connect well" */
2652	for (timeout = 0; timeout < 1000 ; timeout++) {
2653		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2654		if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
2655			found = 1;
2656		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2657		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2658		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2659			break;
2660		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2661			if (bootverbose) {
2662				device_printf(ch->dev, "SATA offline status=%08x\n",
2663				    status);
2664			}
2665			return (0);
2666		}
2667		if (found == 0 && timeout >= 100)
2668			break;
2669		DELAY(100);
2670	}
2671	if (timeout >= 1000 || !found) {
2672		if (bootverbose) {
2673			device_printf(ch->dev,
2674			    "SATA connect timeout time=%dus status=%08x\n",
2675			    timeout * 100, status);
2676		}
2677		return (0);
2678	}
2679	if (bootverbose) {
2680		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2681		    timeout * 100, status);
2682	}
2683	/* Clear SATA error register */
2684	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2685	return (1);
2686}
2687
2688static int
2689ahci_sata_phy_reset(device_t dev)
2690{
2691	struct ahci_channel *ch = device_get_softc(dev);
2692	int sata_rev;
2693	uint32_t val;
2694
2695	if (ch->listening) {
2696		val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2697		val |= AHCI_P_CMD_SUD;
2698		ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2699		ch->listening = 0;
2700	}
2701	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2702	if (sata_rev == 1)
2703		val = ATA_SC_SPD_SPEED_GEN1;
2704	else if (sata_rev == 2)
2705		val = ATA_SC_SPD_SPEED_GEN2;
2706	else if (sata_rev == 3)
2707		val = ATA_SC_SPD_SPEED_GEN3;
2708	else
2709		val = 0;
2710	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2711	    ATA_SC_DET_RESET | val |
2712	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2713	DELAY(1000);
2714	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2715	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2716	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2717	if (!ahci_sata_connect(ch)) {
2718		if (ch->caps & AHCI_CAP_SSS) {
2719			val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2720			val &= ~AHCI_P_CMD_SUD;
2721			ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2722			ch->listening = 1;
2723		} else if (ch->pm_level > 0)
2724			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2725		return (0);
2726	}
2727	return (1);
2728}
2729
2730static int
2731ahci_check_ids(device_t dev, union ccb *ccb)
2732{
2733	struct ahci_channel *ch = device_get_softc(dev);
2734
2735	if (ccb->ccb_h.target_id > ((ch->caps & AHCI_CAP_SPM) ? 15 : 0)) {
2736		ccb->ccb_h.status = CAM_TID_INVALID;
2737		xpt_done(ccb);
2738		return (-1);
2739	}
2740	if (ccb->ccb_h.target_lun != 0) {
2741		ccb->ccb_h.status = CAM_LUN_INVALID;
2742		xpt_done(ccb);
2743		return (-1);
2744	}
2745	return (0);
2746}
2747
2748static void
2749ahciaction(struct cam_sim *sim, union ccb *ccb)
2750{
2751	device_t dev, parent;
2752	struct ahci_channel *ch;
2753
2754	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2755	    ccb->ccb_h.func_code));
2756
2757	ch = (struct ahci_channel *)cam_sim_softc(sim);
2758	dev = ch->dev;
2759	switch (ccb->ccb_h.func_code) {
2760	/* Common cases first */
2761	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2762	case XPT_SCSI_IO:
2763		if (ahci_check_ids(dev, ccb))
2764			return;
2765		if (ch->devices == 0 ||
2766		    (ch->pm_present == 0 &&
2767		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2768			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2769			break;
2770		}
2771		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2772		/* Check for command collision. */
2773		if (ahci_check_collision(dev, ccb)) {
2774			/* Freeze command. */
2775			ch->frozen = ccb;
2776			/* We have only one frozen slot, so freeze simq also. */
2777			xpt_freeze_simq(ch->sim, 1);
2778			return;
2779		}
2780		ahci_begin_transaction(dev, ccb);
2781		return;
2782	case XPT_EN_LUN:		/* Enable LUN as a target */
2783	case XPT_TARGET_IO:		/* Execute target I/O request */
2784	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2785	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2786	case XPT_ABORT:			/* Abort the specified CCB */
2787		/* XXX Implement */
2788		ccb->ccb_h.status = CAM_REQ_INVALID;
2789		break;
2790	case XPT_SET_TRAN_SETTINGS:
2791	{
2792		struct	ccb_trans_settings *cts = &ccb->cts;
2793		struct	ahci_device *d;
2794
2795		if (ahci_check_ids(dev, ccb))
2796			return;
2797		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2798			d = &ch->curr[ccb->ccb_h.target_id];
2799		else
2800			d = &ch->user[ccb->ccb_h.target_id];
2801		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2802			d->revision = cts->xport_specific.sata.revision;
2803		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2804			d->mode = cts->xport_specific.sata.mode;
2805		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2806			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2807		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2808			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2809		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2810			ch->pm_present = cts->xport_specific.sata.pm_present;
2811		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2812			d->atapi = cts->xport_specific.sata.atapi;
2813		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2814			d->caps = cts->xport_specific.sata.caps;
2815		ccb->ccb_h.status = CAM_REQ_CMP;
2816		break;
2817	}
2818	case XPT_GET_TRAN_SETTINGS:
2819	/* Get default/user set transfer settings for the target */
2820	{
2821		struct	ccb_trans_settings *cts = &ccb->cts;
2822		struct  ahci_device *d;
2823		uint32_t status;
2824
2825		if (ahci_check_ids(dev, ccb))
2826			return;
2827		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2828			d = &ch->curr[ccb->ccb_h.target_id];
2829		else
2830			d = &ch->user[ccb->ccb_h.target_id];
2831		cts->protocol = PROTO_UNSPECIFIED;
2832		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2833		cts->transport = XPORT_SATA;
2834		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2835		cts->proto_specific.valid = 0;
2836		cts->xport_specific.sata.valid = 0;
2837		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2838		    (ccb->ccb_h.target_id == 15 ||
2839		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2840			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2841			if (status & 0x0f0) {
2842				cts->xport_specific.sata.revision =
2843				    (status & 0x0f0) >> 4;
2844				cts->xport_specific.sata.valid |=
2845				    CTS_SATA_VALID_REVISION;
2846			}
2847			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2848			if (ch->pm_level) {
2849				if (ch->caps & (AHCI_CAP_PSC | AHCI_CAP_SSC))
2850					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2851				if (ch->caps2 & AHCI_CAP2_APST)
2852					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_APST;
2853			}
2854			if ((ch->caps & AHCI_CAP_SNCQ) &&
2855			    (ch->quirks & AHCI_Q_NOAA) == 0)
2856				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_DMAAA;
2857			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2858			cts->xport_specific.sata.caps &=
2859			    ch->user[ccb->ccb_h.target_id].caps;
2860			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2861		} else {
2862			cts->xport_specific.sata.revision = d->revision;
2863			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2864			cts->xport_specific.sata.caps = d->caps;
2865			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2866		}
2867		cts->xport_specific.sata.mode = d->mode;
2868		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2869		cts->xport_specific.sata.bytecount = d->bytecount;
2870		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2871		cts->xport_specific.sata.pm_present = ch->pm_present;
2872		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2873		cts->xport_specific.sata.tags = d->tags;
2874		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2875		cts->xport_specific.sata.atapi = d->atapi;
2876		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2877		ccb->ccb_h.status = CAM_REQ_CMP;
2878		break;
2879	}
2880	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2881	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2882		ahci_reset(dev);
2883		ccb->ccb_h.status = CAM_REQ_CMP;
2884		break;
2885	case XPT_TERM_IO:		/* Terminate the I/O process */
2886		/* XXX Implement */
2887		ccb->ccb_h.status = CAM_REQ_INVALID;
2888		break;
2889	case XPT_PATH_INQ:		/* Path routing inquiry */
2890	{
2891		struct ccb_pathinq *cpi = &ccb->cpi;
2892
2893		parent = device_get_parent(dev);
2894		cpi->version_num = 1; /* XXX??? */
2895		cpi->hba_inquiry = PI_SDTR_ABLE;
2896		if (ch->caps & AHCI_CAP_SNCQ)
2897			cpi->hba_inquiry |= PI_TAG_ABLE;
2898		if (ch->caps & AHCI_CAP_SPM)
2899			cpi->hba_inquiry |= PI_SATAPM;
2900		cpi->target_sprt = 0;
2901		cpi->hba_misc = PIM_SEQSCAN;
2902		cpi->hba_eng_cnt = 0;
2903		if (ch->caps & AHCI_CAP_SPM)
2904			cpi->max_target = 15;
2905		else
2906			cpi->max_target = 0;
2907		cpi->max_lun = 0;
2908		cpi->initiator_id = 0;
2909		cpi->bus_id = cam_sim_bus(sim);
2910		cpi->base_transfer_speed = 150000;
2911		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2912		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2913		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2914		cpi->unit_number = cam_sim_unit(sim);
2915		cpi->transport = XPORT_SATA;
2916		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2917		cpi->protocol = PROTO_ATA;
2918		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2919		cpi->maxio = MAXPHYS;
2920		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2921		if (pci_get_devid(parent) == 0x43801002)
2922			cpi->maxio = min(cpi->maxio, 128 * 512);
2923		cpi->hba_vendor = pci_get_vendor(parent);
2924		cpi->hba_device = pci_get_device(parent);
2925		cpi->hba_subvendor = pci_get_subvendor(parent);
2926		cpi->hba_subdevice = pci_get_subdevice(parent);
2927		cpi->ccb_h.status = CAM_REQ_CMP;
2928		break;
2929	}
2930	default:
2931		ccb->ccb_h.status = CAM_REQ_INVALID;
2932		break;
2933	}
2934	xpt_done(ccb);
2935}
2936
2937static void
2938ahcipoll(struct cam_sim *sim)
2939{
2940	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2941
2942	ahci_ch_intr(ch->dev);
2943	if (ch->resetting != 0 &&
2944	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2945		ch->resetpolldiv = 1000;
2946		ahci_reset_to(ch->dev);
2947	}
2948}
2949