ahci_pci.c revision 218596
197403Sobrien/*-
297403Sobrien * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
3169691Skan * All rights reserved.
4169691Skan *
597403Sobrien * Redistribution and use in source and binary forms, with or without
697403Sobrien * modification, are permitted provided that the following conditions
797403Sobrien * are met:
897403Sobrien * 1. Redistributions of source code must retain the above copyright
997403Sobrien *    notice, this list of conditions and the following disclaimer,
1097403Sobrien *    without modification, immediately at the beginning of the file.
1197403Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1297403Sobrien *    notice, this list of conditions and the following disclaimer in the
1397403Sobrien *    documentation and/or other materials provided with the distribution.
1497403Sobrien *
1597403Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1697403Sobrien * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1797403Sobrien * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1897403Sobrien * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19169691Skan * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2097403Sobrien * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2197403Sobrien * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2297403Sobrien * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2397403Sobrien * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2497403Sobrien * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2597403Sobrien */
2697403Sobrien
2797403Sobrien#include <sys/cdefs.h>
2897403Sobrien__FBSDID("$FreeBSD: head/sys/dev/ahci/ahci.c 218596 2011-02-12 07:06:40Z mav $");
2997403Sobrien
3097403Sobrien#include <sys/param.h>
3197403Sobrien#include <sys/module.h>
3297403Sobrien#include <sys/systm.h>
3397403Sobrien#include <sys/kernel.h>
3497403Sobrien#include <sys/ata.h>
3597403Sobrien#include <sys/bus.h>
3697403Sobrien#include <sys/endian.h>
3797403Sobrien#include <sys/malloc.h>
3897403Sobrien#include <sys/lock.h>
3997403Sobrien#include <sys/mutex.h>
4097403Sobrien#include <sys/sema.h>
4197403Sobrien#include <sys/taskqueue.h>
4297403Sobrien#include <vm/uma.h>
4397403Sobrien#include <machine/stdarg.h>
4497403Sobrien#include <machine/resource.h>
4597403Sobrien#include <machine/bus.h>
4697403Sobrien#include <sys/rman.h>
4797403Sobrien#include <dev/pci/pcivar.h>
4897403Sobrien#include <dev/pci/pcireg.h>
4997403Sobrien#include "ahci.h"
5097403Sobrien
5197403Sobrien#include <cam/cam.h>
5297403Sobrien#include <cam/cam_ccb.h>
5397403Sobrien#include <cam/cam_sim.h>
5497403Sobrien#include <cam/cam_xpt_sim.h>
5597403Sobrien#include <cam/cam_debug.h>
5697403Sobrien
5797403Sobrien/* local prototypes */
5897403Sobrienstatic int ahci_setup_interrupt(device_t dev);
5997403Sobrienstatic void ahci_intr(void *data);
6097403Sobrienstatic void ahci_intr_one(void *data);
6197403Sobrienstatic int ahci_suspend(device_t dev);
62132720Skanstatic int ahci_resume(device_t dev);
63132720Skanstatic int ahci_ch_init(device_t dev);
6497403Sobrienstatic int ahci_ch_deinit(device_t dev);
65169691Skanstatic int ahci_ch_suspend(device_t dev);
6697403Sobrienstatic int ahci_ch_resume(device_t dev);
6797403Sobrienstatic void ahci_ch_pm(void *arg);
68169691Skanstatic void ahci_ch_intr_locked(void *data);
69169691Skanstatic void ahci_ch_intr(void *data);
7097403Sobrienstatic int ahci_ctlr_reset(device_t dev);
71117397Skanstatic int ahci_ctlr_setup(device_t dev);
72117397Skanstatic void ahci_begin_transaction(device_t dev, union ccb *ccb);
7397403Sobrienstatic void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
74117397Skanstatic void ahci_execute_transaction(struct ahci_slot *slot);
75117397Skanstatic void ahci_timeout(struct ahci_slot *slot);
7697403Sobrienstatic void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
77117397Skanstatic int ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
78117397Skanstatic void ahci_dmainit(device_t dev);
79117397Skanstatic void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
80117397Skanstatic void ahci_dmafini(device_t dev);
81117397Skanstatic void ahci_slotsalloc(device_t dev);
8297403Sobrienstatic void ahci_slotsfree(device_t dev);
83117397Skanstatic void ahci_reset(device_t dev);
8497403Sobrienstatic void ahci_start(device_t dev, int fbs);
85117397Skanstatic void ahci_stop(device_t dev);
86117397Skanstatic void ahci_clo(device_t dev);
87117397Skanstatic void ahci_start_fr(device_t dev);
88117397Skanstatic void ahci_stop_fr(device_t dev);
89117397Skan
9097403Sobrienstatic int ahci_sata_connect(struct ahci_channel *ch);
91169691Skanstatic int ahci_sata_phy_reset(device_t dev);
92169691Skanstatic int ahci_wait_ready(device_t dev, int t);
93117397Skan
94132720Skanstatic void ahci_issue_read_log(device_t dev);
95169691Skanstatic void ahci_process_read_log(device_t dev, union ccb *ccb);
96169691Skan
97169691Skanstatic void ahciaction(struct cam_sim *sim, union ccb *ccb);
98169691Skanstatic void ahcipoll(struct cam_sim *sim);
99169691Skan
100169691SkanMALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
101169691Skan
102169691Skanstatic struct {
103132720Skan	uint32_t	id;
104169691Skan	uint8_t		rev;
105132720Skan	const char	*name;
106132720Skan	int		quirks;
107132720Skan#define AHCI_Q_NOFORCE	1
108169691Skan#define AHCI_Q_NOPMP	2
109132720Skan#define AHCI_Q_NONCQ	4
110132720Skan#define AHCI_Q_1CH	8
111132720Skan#define AHCI_Q_2CH	16
112169691Skan#define AHCI_Q_4CH	32
113117397Skan#define AHCI_Q_EDGEIS	64
114169691Skan#define AHCI_Q_SATA2	128
115117397Skan#define AHCI_Q_NOBSYRES	256
116132720Skan#define AHCI_Q_NOAA	512
117132720Skan#define AHCI_Q_NOCOUNT	1024
118132720Skan} ahci_ids[] = {
119132720Skan	{0x43801002, 0x00, "ATI IXP600",	0},
120132720Skan	{0x43901002, 0x00, "ATI IXP700",	0},
121117397Skan	{0x43911002, 0x00, "ATI IXP700",	0},
122132720Skan	{0x43921002, 0x00, "ATI IXP700",	0},
123132720Skan	{0x43931002, 0x00, "ATI IXP700",	0},
124117397Skan	{0x43941002, 0x00, "ATI IXP800",	0},
125132720Skan	{0x43951002, 0x00, "ATI IXP800",	0},
126132720Skan	{0x26528086, 0x00, "Intel ICH6",	AHCI_Q_NOFORCE},
127132720Skan	{0x26538086, 0x00, "Intel ICH6M",	AHCI_Q_NOFORCE},
128169691Skan	{0x26818086, 0x00, "Intel ESB2",	0},
129169691Skan	{0x26828086, 0x00, "Intel ESB2",	0},
130169691Skan	{0x26838086, 0x00, "Intel ESB2",	0},
131169691Skan	{0x27c18086, 0x00, "Intel ICH7",	0},
132169691Skan	{0x27c38086, 0x00, "Intel ICH7",	0},
133169691Skan	{0x27c58086, 0x00, "Intel ICH7M",	0},
134132720Skan	{0x27c68086, 0x00, "Intel ICH7M",	0},
135132720Skan	{0x28218086, 0x00, "Intel ICH8",	0},
136132720Skan	{0x28228086, 0x00, "Intel ICH8",	0},
137132720Skan	{0x28248086, 0x00, "Intel ICH8",	0},
138132720Skan	{0x28298086, 0x00, "Intel ICH8M",	0},
139132720Skan	{0x282a8086, 0x00, "Intel ICH8M",	0},
140169691Skan	{0x29228086, 0x00, "Intel ICH9",	0},
141169691Skan	{0x29238086, 0x00, "Intel ICH9",	0},
142169691Skan	{0x29248086, 0x00, "Intel ICH9",	0},
143169691Skan	{0x29258086, 0x00, "Intel ICH9",	0},
144132720Skan	{0x29278086, 0x00, "Intel ICH9",	0},
145132720Skan	{0x29298086, 0x00, "Intel ICH9M",	0},
146132720Skan	{0x292a8086, 0x00, "Intel ICH9M",	0},
147132720Skan	{0x292b8086, 0x00, "Intel ICH9M",	0},
148132720Skan	{0x292c8086, 0x00, "Intel ICH9M",	0},
149132720Skan	{0x292f8086, 0x00, "Intel ICH9M",	0},
150132720Skan	{0x294d8086, 0x00, "Intel ICH9",	0},
151132720Skan	{0x294e8086, 0x00, "Intel ICH9M",	0},
152132720Skan	{0x3a058086, 0x00, "Intel ICH10",	0},
153132720Skan	{0x3a228086, 0x00, "Intel ICH10",	0},
154132720Skan	{0x3a258086, 0x00, "Intel ICH10",	0},
155132720Skan	{0x3b228086, 0x00, "Intel 5 Series/3400 Series",	0},
156132720Skan	{0x3b238086, 0x00, "Intel 5 Series/3400 Series",	0},
157132720Skan	{0x3b258086, 0x00, "Intel 5 Series/3400 Series",	0},
158132720Skan	{0x3b298086, 0x00, "Intel 5 Series/3400 Series",	0},
159132720Skan	{0x3b2c8086, 0x00, "Intel 5 Series/3400 Series",	0},
160132720Skan	{0x3b2f8086, 0x00, "Intel 5 Series/3400 Series",	0},
161132720Skan	{0x1c028086, 0x00, "Intel Cougar Point",	0},
162132720Skan	{0x1c038086, 0x00, "Intel Cougar Point",	0},
163132720Skan	{0x1c048086, 0x00, "Intel Cougar Point",	0},
164132720Skan	{0x1c058086, 0x00, "Intel Cougar Point",	0},
165132720Skan	{0x2361197b, 0x00, "JMicron JMB361",	AHCI_Q_NOFORCE},
166117397Skan	{0x2363197b, 0x00, "JMicron JMB363",	AHCI_Q_NOFORCE},
167132720Skan	{0x2365197b, 0x00, "JMicron JMB365",	AHCI_Q_NOFORCE},
168132720Skan	{0x2366197b, 0x00, "JMicron JMB366",	AHCI_Q_NOFORCE},
169132720Skan	{0x2368197b, 0x00, "JMicron JMB368",	AHCI_Q_NOFORCE},
170132720Skan	{0x611111ab, 0x00, "Marvell 88SX6111",	AHCI_Q_NOFORCE | AHCI_Q_1CH |
171132720Skan	    AHCI_Q_EDGEIS},
172132720Skan	{0x612111ab, 0x00, "Marvell 88SX6121",	AHCI_Q_NOFORCE | AHCI_Q_2CH |
173132720Skan	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
174132720Skan	{0x614111ab, 0x00, "Marvell 88SX6141",	AHCI_Q_NOFORCE | AHCI_Q_4CH |
175132720Skan	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
176117397Skan	{0x614511ab, 0x00, "Marvell 88SX6145",	AHCI_Q_NOFORCE | AHCI_Q_4CH |
177132720Skan	    AHCI_Q_EDGEIS | AHCI_Q_NONCQ | AHCI_Q_NOCOUNT},
178132720Skan	{0x91231b4b, 0x11, "Marvell 88SE912x",	AHCI_Q_NOBSYRES},
179132720Skan	{0x91231b4b, 0x00, "Marvell 88SE912x",	AHCI_Q_EDGEIS|AHCI_Q_SATA2|AHCI_Q_NOBSYRES},
180132720Skan	{0x06201103, 0x00, "HighPoint RocketRAID 620",	AHCI_Q_NOBSYRES},
181132720Skan	{0x06201b4b, 0x00, "HighPoint RocketRAID 620",	AHCI_Q_NOBSYRES},
182132720Skan	{0x06221103, 0x00, "HighPoint RocketRAID 622",	AHCI_Q_NOBSYRES},
183132720Skan	{0x06221b4b, 0x00, "HighPoint RocketRAID 622",	AHCI_Q_NOBSYRES},
184132720Skan	{0x06401103, 0x00, "HighPoint RocketRAID 640",	AHCI_Q_NOBSYRES},
185132720Skan	{0x06441103, 0x00, "HighPoint RocketRAID 644",	AHCI_Q_NOBSYRES},
186132720Skan	{0x044c10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
187132720Skan	{0x044d10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
188132720Skan	{0x044e10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
189132720Skan	{0x044f10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
190169691Skan	{0x045c10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
191132720Skan	{0x045d10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
192132720Skan	{0x045e10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
193132720Skan	{0x045f10de, 0x00, "NVIDIA MCP65",	AHCI_Q_NOAA},
194132720Skan	{0x055010de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
195132720Skan	{0x055110de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
196132720Skan	{0x055210de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
197132720Skan	{0x055310de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
198132720Skan	{0x055410de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
199132720Skan	{0x055510de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
200132720Skan	{0x055610de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
201132720Skan	{0x055710de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
202132720Skan	{0x055810de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
203132720Skan	{0x055910de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
204132720Skan	{0x055A10de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
205132720Skan	{0x055B10de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
206132720Skan	{0x058410de, 0x00, "NVIDIA MCP67",	AHCI_Q_NOAA},
207169691Skan	{0x07f010de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
208132720Skan	{0x07f110de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
209169691Skan	{0x07f210de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
210169691Skan	{0x07f310de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
211169691Skan	{0x07f410de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
212132720Skan	{0x07f510de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
213132720Skan	{0x07f610de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
214132720Skan	{0x07f710de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
215132720Skan	{0x07f810de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
216132720Skan	{0x07f910de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
217132720Skan	{0x07fa10de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
218132720Skan	{0x07fb10de, 0x00, "NVIDIA MCP73",	AHCI_Q_NOAA},
219132720Skan	{0x0ad010de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
220132720Skan	{0x0ad110de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
221132720Skan	{0x0ad210de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
222132720Skan	{0x0ad310de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
223132720Skan	{0x0ad410de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
224132720Skan	{0x0ad510de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
225132720Skan	{0x0ad610de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
226132720Skan	{0x0ad710de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
227132720Skan	{0x0ad810de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
228132720Skan	{0x0ad910de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
229132720Skan	{0x0ada10de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
230132720Skan	{0x0adb10de, 0x00, "NVIDIA MCP77",	AHCI_Q_NOAA},
231132720Skan	{0x0ab410de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
232132720Skan	{0x0ab510de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
233132720Skan	{0x0ab610de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
234132720Skan	{0x0ab710de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
235132720Skan	{0x0ab810de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
236132720Skan	{0x0ab910de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
237132720Skan	{0x0aba10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
238132720Skan	{0x0abb10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
239132720Skan	{0x0abc10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
240132720Skan	{0x0abd10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
241132720Skan	{0x0abe10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
242132720Skan	{0x0abf10de, 0x00, "NVIDIA MCP79",	AHCI_Q_NOAA},
243132720Skan	{0x0d8410de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
244132720Skan	{0x0d8510de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
245132720Skan	{0x0d8610de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
246132720Skan	{0x0d8710de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
247132720Skan	{0x0d8810de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
248132720Skan	{0x0d8910de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
249132720Skan	{0x0d8a10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
250132720Skan	{0x0d8b10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
251132720Skan	{0x0d8c10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
252132720Skan	{0x0d8d10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
253132720Skan	{0x0d8e10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
254132720Skan	{0x0d8f10de, 0x00, "NVIDIA MCP89",	AHCI_Q_NOAA},
255132720Skan	{0x33491106, 0x00, "VIA VT8251",	AHCI_Q_NOPMP|AHCI_Q_NONCQ},
256132720Skan	{0x62871106, 0x00, "VIA VT8251",	AHCI_Q_NOPMP|AHCI_Q_NONCQ},
257169691Skan	{0x11841039, 0x00, "SiS 966",		0},
258169691Skan	{0x11851039, 0x00, "SiS 968",		0},
259169691Skan	{0x01861039, 0x00, "SiS 968",		0},
260132720Skan	{0x00000000, 0x00, NULL,		0}
261132720Skan};
262132720Skan
263132720Skanstatic int
264132720Skanahci_probe(device_t dev)
265132720Skan{
266132720Skan	char buf[64];
267132720Skan	int i, valid = 0;
268132720Skan	uint32_t devid = pci_get_devid(dev);
269132720Skan	uint8_t revid = pci_get_revid(dev);
270132720Skan
271132720Skan	/* Is this a possible AHCI candidate? */
272132720Skan	if (pci_get_class(dev) == PCIC_STORAGE &&
273132720Skan	    pci_get_subclass(dev) == PCIS_STORAGE_SATA &&
274132720Skan	    pci_get_progif(dev) == PCIP_STORAGE_SATA_AHCI_1_0)
275132720Skan		valid = 1;
276132720Skan	/* Is this a known AHCI chip? */
277132720Skan	for (i = 0; ahci_ids[i].id != 0; i++) {
278132720Skan		if (ahci_ids[i].id == devid &&
279132720Skan		    ahci_ids[i].rev <= revid &&
280132720Skan		    (valid || !(ahci_ids[i].quirks & AHCI_Q_NOFORCE))) {
281132720Skan			/* Do not attach JMicrons with single PCI function. */
282132720Skan			if (pci_get_vendor(dev) == 0x197b &&
283132720Skan			    (pci_read_config(dev, 0xdf, 1) & 0x40) == 0)
284132720Skan				return (ENXIO);
285132720Skan			snprintf(buf, sizeof(buf), "%s AHCI SATA controller",
286132720Skan			    ahci_ids[i].name);
287132720Skan			device_set_desc_copy(dev, buf);
288132720Skan			return (BUS_PROBE_VENDOR);
289132720Skan		}
290132720Skan	}
291132720Skan	if (!valid)
292132720Skan		return (ENXIO);
293132720Skan	device_set_desc_copy(dev, "AHCI SATA controller");
294132720Skan	return (BUS_PROBE_VENDOR);
295132720Skan}
296132720Skan
297132720Skanstatic int
298132720Skanahci_ata_probe(device_t dev)
299132720Skan{
300132720Skan	char buf[64];
301132720Skan	int i;
302132720Skan	uint32_t devid = pci_get_devid(dev);
303132720Skan	uint8_t revid = pci_get_revid(dev);
304132720Skan
305132720Skan	if ((intptr_t)device_get_ivars(dev) >= 0)
306132720Skan		return (ENXIO);
307132720Skan	/* Is this a known AHCI chip? */
308132720Skan	for (i = 0; ahci_ids[i].id != 0; i++) {
309132720Skan		if (ahci_ids[i].id == devid &&
310132720Skan		    ahci_ids[i].rev <= revid) {
311132720Skan			snprintf(buf, sizeof(buf), "%s AHCI SATA controller",
312132720Skan			    ahci_ids[i].name);
313132720Skan			device_set_desc_copy(dev, buf);
314132720Skan			return (BUS_PROBE_VENDOR);
315132720Skan		}
316132720Skan	}
317132720Skan	device_set_desc_copy(dev, "AHCI SATA controller");
318132720Skan	return (BUS_PROBE_VENDOR);
319132720Skan}
320132720Skan
321132720Skanstatic int
322132720Skanahci_attach(device_t dev)
323132720Skan{
324132720Skan	struct ahci_controller *ctlr = device_get_softc(dev);
325132720Skan	device_t child;
326132720Skan	int	error, unit, speed, i;
327132720Skan	uint32_t devid = pci_get_devid(dev);
328132720Skan	uint8_t revid = pci_get_revid(dev);
329132720Skan	u_int32_t version;
330132720Skan
331132720Skan	ctlr->dev = dev;
332132720Skan	i = 0;
333132720Skan	while (ahci_ids[i].id != 0 &&
334169691Skan	    (ahci_ids[i].id != devid ||
335169691Skan	     ahci_ids[i].rev > revid))
336169691Skan		i++;
337169691Skan	ctlr->quirks = ahci_ids[i].quirks;
338132720Skan	resource_int_value(device_get_name(dev),
339132720Skan	    device_get_unit(dev), "ccc", &ctlr->ccc);
340132720Skan	/* if we have a memory BAR(5) we are likely on an AHCI part */
341132720Skan	ctlr->r_rid = PCIR_BAR(5);
342132720Skan	if (!(ctlr->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
343132720Skan	    &ctlr->r_rid, RF_ACTIVE)))
344132720Skan		return ENXIO;
345132720Skan	/* Setup our own memory management for channels. */
346132720Skan	ctlr->sc_iomem.rm_start = rman_get_start(ctlr->r_mem);
347132720Skan	ctlr->sc_iomem.rm_end = rman_get_end(ctlr->r_mem);
348132720Skan	ctlr->sc_iomem.rm_type = RMAN_ARRAY;
349132720Skan	ctlr->sc_iomem.rm_descr = "I/O memory addresses";
350132720Skan	if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
351132720Skan		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
352132720Skan		return (error);
353132720Skan	}
354169691Skan	if ((error = rman_manage_region(&ctlr->sc_iomem,
355169691Skan	    rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
356169691Skan		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
357169691Skan		rman_fini(&ctlr->sc_iomem);
358169691Skan		return (error);
359169691Skan	}
360169691Skan	pci_enable_busmaster(dev);
361169691Skan	/* Reset controller */
362169691Skan	if ((error = ahci_ctlr_reset(dev)) != 0) {
363169691Skan		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
364169691Skan		rman_fini(&ctlr->sc_iomem);
365169691Skan		return (error);
366169691Skan	};
367169691Skan	/* Get the HW capabilities */
368169691Skan	version = ATA_INL(ctlr->r_mem, AHCI_VS);
369169691Skan	ctlr->caps = ATA_INL(ctlr->r_mem, AHCI_CAP);
370169691Skan	if (version >= 0x00010020)
371169691Skan		ctlr->caps2 = ATA_INL(ctlr->r_mem, AHCI_CAP2);
372169691Skan	if (ctlr->caps & AHCI_CAP_EMS)
373169691Skan		ctlr->capsem = ATA_INL(ctlr->r_mem, AHCI_EM_CTL);
374169691Skan	ctlr->ichannels = ATA_INL(ctlr->r_mem, AHCI_PI);
375169691Skan	if (ctlr->quirks & AHCI_Q_1CH) {
376169691Skan		ctlr->caps &= ~AHCI_CAP_NPMASK;
377169691Skan		ctlr->ichannels &= 0x01;
378169691Skan	}
379169691Skan	if (ctlr->quirks & AHCI_Q_2CH) {
380169691Skan		ctlr->caps &= ~AHCI_CAP_NPMASK;
381132720Skan		ctlr->caps |= 1;
382132720Skan		ctlr->ichannels &= 0x03;
383132720Skan	}
384169691Skan	if (ctlr->quirks & AHCI_Q_4CH) {
385169691Skan		ctlr->caps &= ~AHCI_CAP_NPMASK;
386169691Skan		ctlr->caps |= 3;
387169691Skan		ctlr->ichannels &= 0x0f;
388169691Skan	}
389169691Skan	ctlr->channels = MAX(flsl(ctlr->ichannels),
390169691Skan	    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
391132720Skan	if (ctlr->quirks & AHCI_Q_NOPMP)
392132720Skan		ctlr->caps &= ~AHCI_CAP_SPM;
393132720Skan	if (ctlr->quirks & AHCI_Q_NONCQ)
394132720Skan		ctlr->caps &= ~AHCI_CAP_SNCQ;
395132720Skan	if ((ctlr->caps & AHCI_CAP_CCCS) == 0)
396132720Skan		ctlr->ccc = 0;
397132720Skan	ahci_ctlr_setup(dev);
398169691Skan	/* Setup interrupts. */
399132720Skan	if (ahci_setup_interrupt(dev)) {
400169691Skan		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
401132720Skan		rman_fini(&ctlr->sc_iomem);
402132720Skan		return ENXIO;
403132720Skan	}
404132720Skan	/* Announce HW capabilities. */
405132720Skan	speed = (ctlr->caps & AHCI_CAP_ISS) >> AHCI_CAP_ISS_SHIFT;
406169691Skan	device_printf(dev,
407169691Skan		    "AHCI v%x.%02x with %d %sGbps ports, Port Multiplier %s%s\n",
408132720Skan		    ((version >> 20) & 0xf0) + ((version >> 16) & 0x0f),
409132720Skan		    ((version >> 4) & 0xf0) + (version & 0x0f),
410132720Skan		    (ctlr->caps & AHCI_CAP_NPMASK) + 1,
411169691Skan		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
412169691Skan		    ((speed == 3) ? "6":"?"))),
413169691Skan		    (ctlr->caps & AHCI_CAP_SPM) ?
414169691Skan		    "supported" : "not supported",
415169691Skan		    (ctlr->caps & AHCI_CAP_FBSS) ?
416169691Skan		    " with FBS" : "");
417169691Skan	if (bootverbose) {
418132720Skan		device_printf(dev, "Caps:%s%s%s%s%s%s%s%s %sGbps",
419169691Skan		    (ctlr->caps & AHCI_CAP_64BIT) ? " 64bit":"",
420169691Skan		    (ctlr->caps & AHCI_CAP_SNCQ) ? " NCQ":"",
421132720Skan		    (ctlr->caps & AHCI_CAP_SSNTF) ? " SNTF":"",
422132720Skan		    (ctlr->caps & AHCI_CAP_SMPS) ? " MPS":"",
423132720Skan		    (ctlr->caps & AHCI_CAP_SSS) ? " SS":"",
424132720Skan		    (ctlr->caps & AHCI_CAP_SALP) ? " ALP":"",
425132720Skan		    (ctlr->caps & AHCI_CAP_SAL) ? " AL":"",
426169691Skan		    (ctlr->caps & AHCI_CAP_SCLO) ? " CLO":"",
427169691Skan		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
428132720Skan		    ((speed == 3) ? "6":"?"))));
429132720Skan		printf("%s%s%s%s%s%s %dcmd%s%s%s %dports\n",
430169691Skan		    (ctlr->caps & AHCI_CAP_SAM) ? " AM":"",
431132720Skan		    (ctlr->caps & AHCI_CAP_SPM) ? " PM":"",
432132720Skan		    (ctlr->caps & AHCI_CAP_FBSS) ? " FBS":"",
433132720Skan		    (ctlr->caps & AHCI_CAP_PMD) ? " PMD":"",
434132720Skan		    (ctlr->caps & AHCI_CAP_SSC) ? " SSC":"",
435132720Skan		    (ctlr->caps & AHCI_CAP_PSC) ? " PSC":"",
436132720Skan		    ((ctlr->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
437132720Skan		    (ctlr->caps & AHCI_CAP_CCCS) ? " CCC":"",
438132720Skan		    (ctlr->caps & AHCI_CAP_EMS) ? " EM":"",
439132720Skan		    (ctlr->caps & AHCI_CAP_SXS) ? " eSATA":"",
440169691Skan		    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
441132720Skan	}
442132720Skan	if (bootverbose && version >= 0x00010020) {
443132720Skan		device_printf(dev, "Caps2:%s%s%s\n",
444132720Skan		    (ctlr->caps2 & AHCI_CAP2_APST) ? " APST":"",
445132720Skan		    (ctlr->caps2 & AHCI_CAP2_NVMP) ? " NVMP":"",
446169691Skan		    (ctlr->caps2 & AHCI_CAP2_BOH) ? " BOH":"");
447169691Skan	}
448169691Skan	if (bootverbose && (ctlr->caps & AHCI_CAP_EMS)) {
449169691Skan		device_printf(dev, "EM Caps:%s%s%s%s%s%s%s%s\n",
450169691Skan		    (ctlr->capsem & AHCI_EM_PM) ? " PM":"",
451132720Skan		    (ctlr->capsem & AHCI_EM_ALHD) ? " ALHD":"",
452117397Skan		    (ctlr->capsem & AHCI_EM_XMT) ? " XMT":"",
453132720Skan		    (ctlr->capsem & AHCI_EM_SMB) ? " SMB":"",
454132720Skan		    (ctlr->capsem & AHCI_EM_SGPIO) ? " SGPIO":"",
455132720Skan		    (ctlr->capsem & AHCI_EM_SES2) ? " SES-2":"",
456132720Skan		    (ctlr->capsem & AHCI_EM_SAFTE) ? " SAF-TE":"",
457132720Skan		    (ctlr->capsem & AHCI_EM_LED) ? " LED":"");
458132720Skan	}
459132720Skan	/* Attach all channels on this controller */
460132720Skan	for (unit = 0; unit < ctlr->channels; unit++) {
461132720Skan		if ((ctlr->ichannels & (1 << unit)) == 0)
462132720Skan			continue;
463132720Skan		child = device_add_child(dev, "ahcich", -1);
464132720Skan		if (child == NULL)
465132720Skan			device_printf(dev, "failed to add channel device\n");
466132720Skan		else
467132720Skan			device_set_ivars(child, (void *)(intptr_t)unit);
468132720Skan	}
469132720Skan	bus_generic_attach(dev);
470132720Skan	return 0;
471132720Skan}
472132720Skan
473132720Skanstatic int
474132720Skanahci_detach(device_t dev)
475132720Skan{
476132720Skan	struct ahci_controller *ctlr = device_get_softc(dev);
477132720Skan	device_t *children;
478132720Skan	int nchildren, i;
479132720Skan
480132720Skan	/* Detach & delete all children */
481132720Skan	if (!device_get_children(dev, &children, &nchildren)) {
482132720Skan		for (i = 0; i < nchildren; i++)
483132720Skan			device_delete_child(dev, children[i]);
484132720Skan		free(children, M_TEMP);
485132720Skan	}
486132720Skan	/* Free interrupts. */
487132720Skan	for (i = 0; i < ctlr->numirqs; i++) {
488132720Skan		if (ctlr->irqs[i].r_irq) {
489132720Skan			bus_teardown_intr(dev, ctlr->irqs[i].r_irq,
490169691Skan			    ctlr->irqs[i].handle);
491169691Skan			bus_release_resource(dev, SYS_RES_IRQ,
492169691Skan			    ctlr->irqs[i].r_irq_rid, ctlr->irqs[i].r_irq);
493169691Skan		}
494169691Skan	}
495169691Skan	pci_release_msi(dev);
496132720Skan	/* Free memory. */
497132720Skan	rman_fini(&ctlr->sc_iomem);
498132720Skan	if (ctlr->r_mem)
499132720Skan		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
500132720Skan	return (0);
501132720Skan}
502169691Skan
503169691Skanstatic int
504169691Skanahci_ctlr_reset(device_t dev)
505169691Skan{
506132720Skan	struct ahci_controller *ctlr = device_get_softc(dev);
507132720Skan	int timeout;
508132720Skan
509132720Skan	if (pci_read_config(dev, 0x00, 4) == 0x28298086 &&
510132720Skan	    (pci_read_config(dev, 0x92, 1) & 0xfe) == 0x04)
511132720Skan		pci_write_config(dev, 0x92, 0x01, 1);
512132720Skan	/* Enable AHCI mode */
513132720Skan	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
514132720Skan	/* Reset AHCI controller */
515132720Skan	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE|AHCI_GHC_HR);
516132720Skan	for (timeout = 1000; timeout > 0; timeout--) {
517132720Skan		DELAY(1000);
518132720Skan		if ((ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_HR) == 0)
519132720Skan			break;
520132720Skan	}
521132720Skan	if (timeout == 0) {
522132720Skan		device_printf(dev, "AHCI controller reset failure\n");
523132720Skan		return ENXIO;
524132720Skan	}
525132720Skan	/* Reenable AHCI mode */
526132720Skan	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
527132720Skan	return (0);
528132720Skan}
529132720Skan
530132720Skanstatic int
531132720Skanahci_ctlr_setup(device_t dev)
532132720Skan{
533132720Skan	struct ahci_controller *ctlr = device_get_softc(dev);
534132720Skan	/* Clear interrupts */
535132720Skan	ATA_OUTL(ctlr->r_mem, AHCI_IS, ATA_INL(ctlr->r_mem, AHCI_IS));
536132720Skan	/* Configure CCC */
537132720Skan	if (ctlr->ccc) {
538132720Skan		ATA_OUTL(ctlr->r_mem, AHCI_CCCP, ATA_INL(ctlr->r_mem, AHCI_PI));
539132720Skan		ATA_OUTL(ctlr->r_mem, AHCI_CCCC,
540132720Skan		    (ctlr->ccc << AHCI_CCCC_TV_SHIFT) |
541132720Skan		    (4 << AHCI_CCCC_CC_SHIFT) |
542132720Skan		    AHCI_CCCC_EN);
543132720Skan		ctlr->cccv = (ATA_INL(ctlr->r_mem, AHCI_CCCC) &
544132720Skan		    AHCI_CCCC_INT_MASK) >> AHCI_CCCC_INT_SHIFT;
545132720Skan		if (bootverbose) {
546132720Skan			device_printf(dev,
547132720Skan			    "CCC with %dms/4cmd enabled on vector %d\n",
548132720Skan			    ctlr->ccc, ctlr->cccv);
549132720Skan		}
550132720Skan	}
551132720Skan	/* Enable AHCI interrupts */
552132720Skan	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
553132720Skan	    ATA_INL(ctlr->r_mem, AHCI_GHC) | AHCI_GHC_IE);
554132720Skan	return (0);
555132720Skan}
556132720Skan
557132720Skanstatic int
558132720Skanahci_suspend(device_t dev)
559132720Skan{
560132720Skan	struct ahci_controller *ctlr = device_get_softc(dev);
561132720Skan
562132720Skan	bus_generic_suspend(dev);
563132720Skan	/* Disable interupts, so the state change(s) doesn't trigger */
564132720Skan	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
565132720Skan	     ATA_INL(ctlr->r_mem, AHCI_GHC) & (~AHCI_GHC_IE));
566132720Skan	return 0;
567132720Skan}
568132720Skan
569132720Skanstatic int
570132720Skanahci_resume(device_t dev)
571132720Skan{
572132720Skan	int res;
573132720Skan
574132720Skan	if ((res = ahci_ctlr_reset(dev)) != 0)
575132720Skan		return (res);
576132720Skan	ahci_ctlr_setup(dev);
577132720Skan	return (bus_generic_resume(dev));
578132720Skan}
579132720Skan
580132720Skanstatic int
581132720Skanahci_setup_interrupt(device_t dev)
582132720Skan{
583132720Skan	struct ahci_controller *ctlr = device_get_softc(dev);
584132720Skan	int i, msi = 1;
585132720Skan
586132720Skan	/* Process hints. */
587132720Skan	resource_int_value(device_get_name(dev),
588132720Skan	    device_get_unit(dev), "msi", &msi);
589132720Skan	if (msi < 0)
590132720Skan		msi = 0;
591132720Skan	else if (msi == 1)
592132720Skan		msi = min(1, pci_msi_count(dev));
593132720Skan	else if (msi > 1)
594132720Skan		msi = pci_msi_count(dev);
595132720Skan	/* Allocate MSI if needed/present. */
596132720Skan	if (msi && pci_alloc_msi(dev, &msi) == 0) {
597132720Skan		ctlr->numirqs = msi;
598132720Skan	} else {
599132720Skan		msi = 0;
600132720Skan		ctlr->numirqs = 1;
601132720Skan	}
602132720Skan	/* Check for single MSI vector fallback. */
603132720Skan	if (ctlr->numirqs > 1 &&
604132720Skan	    (ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_MRSM) != 0) {
605132720Skan		device_printf(dev, "Falling back to one MSI\n");
606132720Skan		ctlr->numirqs = 1;
607132720Skan	}
608132720Skan	/* Allocate all IRQs. */
609132720Skan	for (i = 0; i < ctlr->numirqs; i++) {
610132720Skan		ctlr->irqs[i].ctlr = ctlr;
611132720Skan		ctlr->irqs[i].r_irq_rid = i + (msi ? 1 : 0);
612132720Skan		if (ctlr->numirqs == 1 || i >= ctlr->channels ||
613132720Skan		    (ctlr->ccc && i == ctlr->cccv))
614132720Skan			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ALL;
615132720Skan		else if (i == ctlr->numirqs - 1)
616132720Skan			ctlr->irqs[i].mode = AHCI_IRQ_MODE_AFTER;
617132720Skan		else
618132720Skan			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
619132720Skan		if (!(ctlr->irqs[i].r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
620132720Skan		    &ctlr->irqs[i].r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
621132720Skan			device_printf(dev, "unable to map interrupt\n");
622132720Skan			return ENXIO;
623132720Skan		}
624132720Skan		if ((bus_setup_intr(dev, ctlr->irqs[i].r_irq, ATA_INTR_FLAGS, NULL,
625132720Skan		    (ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE) ? ahci_intr_one : ahci_intr,
626132720Skan		    &ctlr->irqs[i], &ctlr->irqs[i].handle))) {
627132720Skan			/* SOS XXX release r_irq */
628132720Skan			device_printf(dev, "unable to setup interrupt\n");
629132720Skan			return ENXIO;
630132720Skan		}
631132720Skan		if (ctlr->numirqs > 1) {
632132720Skan			bus_describe_intr(dev, ctlr->irqs[i].r_irq,
633132720Skan			    ctlr->irqs[i].handle,
634132720Skan			    ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE ?
635132720Skan			    "ch%d" : "%d", i);
636169691Skan		}
637132720Skan	}
638132720Skan	return (0);
639132720Skan}
640132720Skan
641132720Skan/*
642132720Skan * Common case interrupt handler.
643132720Skan */
644132720Skanstatic void
645132720Skanahci_intr(void *data)
646132720Skan{
647132720Skan	struct ahci_controller_irq *irq = data;
648132720Skan	struct ahci_controller *ctlr = irq->ctlr;
649132720Skan	u_int32_t is, ise = 0;
650132720Skan	void *arg;
651132720Skan	int unit;
652132720Skan
653132720Skan	if (irq->mode == AHCI_IRQ_MODE_ALL) {
654132720Skan		unit = 0;
655169691Skan		if (ctlr->ccc)
656132720Skan			is = ctlr->ichannels;
657132720Skan		else
658132720Skan			is = ATA_INL(ctlr->r_mem, AHCI_IS);
659132720Skan	} else {	/* AHCI_IRQ_MODE_AFTER */
660132720Skan		unit = irq->r_irq_rid - 1;
661169691Skan		is = ATA_INL(ctlr->r_mem, AHCI_IS);
662169691Skan	}
663132720Skan	/* CCC interrupt is edge triggered. */
664132720Skan	if (ctlr->ccc)
665132720Skan		ise = 1 << ctlr->cccv;
666169691Skan	/* Some controllers have edge triggered IS. */
667169691Skan	if (ctlr->quirks & AHCI_Q_EDGEIS)
668132720Skan		ise |= is;
669132720Skan	if (ise != 0)
67097403Sobrien		ATA_OUTL(ctlr->r_mem, AHCI_IS, ise);
671117397Skan	for (; unit < ctlr->channels; unit++) {
672117397Skan		if ((is & (1 << unit)) != 0 &&
673117397Skan		    (arg = ctlr->interrupt[unit].argument)) {
674117397Skan				ctlr->interrupt[unit].function(arg);
67597403Sobrien		}
676117397Skan	}
677117397Skan	/* AHCI declares level triggered IS. */
678117397Skan	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
67997403Sobrien		ATA_OUTL(ctlr->r_mem, AHCI_IS, is);
680117397Skan}
681117397Skan
682169691Skan/*
683169691Skan * Simplified interrupt handler for multivector MSI mode.
684117397Skan */
685132720Skanstatic void
68697403Sobrienahci_intr_one(void *data)
687117397Skan{
688117397Skan	struct ahci_controller_irq *irq = data;
689117397Skan	struct ahci_controller *ctlr = irq->ctlr;
690132720Skan	void *arg;
69197403Sobrien	int unit;
692117397Skan
693117397Skan	unit = irq->r_irq_rid - 1;
69497403Sobrien	/* Some controllers have edge triggered IS. */
695132720Skan	if (ctlr->quirks & AHCI_Q_EDGEIS)
69697403Sobrien		ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
697117397Skan	if ((arg = ctlr->interrupt[unit].argument))
698117397Skan	    ctlr->interrupt[unit].function(arg);
699169691Skan	/* AHCI declares level triggered IS. */
700169691Skan	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
701117397Skan		ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
702132720Skan}
703117397Skan
704117397Skanstatic struct resource *
705117397Skanahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
706169691Skan		       u_long start, u_long end, u_long count, u_int flags)
707169691Skan{
708117397Skan	struct ahci_controller *ctlr = device_get_softc(dev);
709132720Skan	int unit = ((struct ahci_channel *)device_get_softc(child))->unit;
710117397Skan	struct resource *res = NULL;
711117397Skan	int offset = AHCI_OFFSET + (unit << 7);
712117397Skan	long st;
713169691Skan
714169691Skan	switch (type) {
715117397Skan	case SYS_RES_MEMORY:
716132720Skan		st = rman_get_start(ctlr->r_mem);
717117397Skan		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
718117397Skan		    st + offset + 127, 128, RF_ACTIVE, child);
719117397Skan		if (res) {
720169691Skan			bus_space_handle_t bsh;
721169691Skan			bus_space_tag_t bst;
722117397Skan			bsh = rman_get_bushandle(ctlr->r_mem);
723132720Skan			bst = rman_get_bustag(ctlr->r_mem);
724117397Skan			bus_space_subregion(bst, bsh, offset, 128, &bsh);
725117397Skan			rman_set_bushandle(res, bsh);
726117397Skan			rman_set_bustag(res, bst);
727169691Skan		}
728169691Skan		break;
729117397Skan	case SYS_RES_IRQ:
730132720Skan		if (*rid == ATA_IRQ_RID)
731117397Skan			res = ctlr->irqs[0].r_irq;
732117397Skan		break;
733117397Skan	}
734169691Skan	return (res);
735169691Skan}
736117397Skan
73797403Sobrienstatic int
738169691Skanahci_release_resource(device_t dev, device_t child, int type, int rid,
739169691Skan			 struct resource *r)
740132720Skan{
741
742	switch (type) {
743	case SYS_RES_MEMORY:
744		rman_release_resource(r);
745		return (0);
746	case SYS_RES_IRQ:
747		if (rid != ATA_IRQ_RID)
748			return ENOENT;
749		return (0);
750	}
751	return (EINVAL);
752}
753
754static int
755ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
756		   int flags, driver_filter_t *filter, driver_intr_t *function,
757		   void *argument, void **cookiep)
758{
759	struct ahci_controller *ctlr = device_get_softc(dev);
760	int unit = (intptr_t)device_get_ivars(child);
761
762	if (filter != NULL) {
763		printf("ahci.c: we cannot use a filter here\n");
764		return (EINVAL);
765	}
766	ctlr->interrupt[unit].function = function;
767	ctlr->interrupt[unit].argument = argument;
768	return (0);
769}
770
771static int
772ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
773		      void *cookie)
774{
775	struct ahci_controller *ctlr = device_get_softc(dev);
776	int unit = (intptr_t)device_get_ivars(child);
777
778	ctlr->interrupt[unit].function = NULL;
779	ctlr->interrupt[unit].argument = NULL;
780	return (0);
781}
782
783static int
784ahci_print_child(device_t dev, device_t child)
785{
786	int retval;
787
788	retval = bus_print_child_header(dev, child);
789	retval += printf(" at channel %d",
790	    (int)(intptr_t)device_get_ivars(child));
791	retval += bus_print_child_footer(dev, child);
792
793	return (retval);
794}
795
796static int
797ahci_child_location_str(device_t dev, device_t child, char *buf,
798    size_t buflen)
799{
800
801	snprintf(buf, buflen, "channel=%d",
802	    (int)(intptr_t)device_get_ivars(child));
803	return (0);
804}
805
806devclass_t ahci_devclass;
807static device_method_t ahci_methods[] = {
808	DEVMETHOD(device_probe,     ahci_probe),
809	DEVMETHOD(device_attach,    ahci_attach),
810	DEVMETHOD(device_detach,    ahci_detach),
811	DEVMETHOD(device_suspend,   ahci_suspend),
812	DEVMETHOD(device_resume,    ahci_resume),
813	DEVMETHOD(bus_print_child,  ahci_print_child),
814	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
815	DEVMETHOD(bus_release_resource,     ahci_release_resource),
816	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
817	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
818	DEVMETHOD(bus_child_location_str, ahci_child_location_str),
819	{ 0, 0 }
820};
821static driver_t ahci_driver = {
822        "ahci",
823        ahci_methods,
824        sizeof(struct ahci_controller)
825};
826DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
827static device_method_t ahci_ata_methods[] = {
828	DEVMETHOD(device_probe,     ahci_ata_probe),
829	DEVMETHOD(device_attach,    ahci_attach),
830	DEVMETHOD(device_detach,    ahci_detach),
831	DEVMETHOD(device_suspend,   ahci_suspend),
832	DEVMETHOD(device_resume,    ahci_resume),
833	DEVMETHOD(bus_print_child,  ahci_print_child),
834	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
835	DEVMETHOD(bus_release_resource,     ahci_release_resource),
836	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
837	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
838	DEVMETHOD(bus_child_location_str, ahci_child_location_str),
839	{ 0, 0 }
840};
841static driver_t ahci_ata_driver = {
842        "ahci",
843        ahci_ata_methods,
844        sizeof(struct ahci_controller)
845};
846DRIVER_MODULE(ahci, atapci, ahci_ata_driver, ahci_devclass, 0, 0);
847MODULE_VERSION(ahci, 1);
848MODULE_DEPEND(ahci, cam, 1, 1, 1);
849
850static int
851ahci_ch_probe(device_t dev)
852{
853
854	device_set_desc_copy(dev, "AHCI channel");
855	return (0);
856}
857
858static int
859ahci_ch_attach(device_t dev)
860{
861	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
862	struct ahci_channel *ch = device_get_softc(dev);
863	struct cam_devq *devq;
864	int rid, error, i, sata_rev = 0;
865	u_int32_t version;
866
867	ch->dev = dev;
868	ch->unit = (intptr_t)device_get_ivars(dev);
869	ch->caps = ctlr->caps;
870	ch->caps2 = ctlr->caps2;
871	ch->quirks = ctlr->quirks;
872	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1;
873	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
874	resource_int_value(device_get_name(dev),
875	    device_get_unit(dev), "pm_level", &ch->pm_level);
876	if (ch->pm_level > 3)
877		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
878	/* Limit speed for my onboard JMicron external port.
879	 * It is not eSATA really. */
880	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
881	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
882	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
883	    ch->unit == 0)
884		sata_rev = 1;
885	if (ch->quirks & AHCI_Q_SATA2)
886		sata_rev = 2;
887	resource_int_value(device_get_name(dev),
888	    device_get_unit(dev), "sata_rev", &sata_rev);
889	for (i = 0; i < 16; i++) {
890		ch->user[i].revision = sata_rev;
891		ch->user[i].mode = 0;
892		ch->user[i].bytecount = 8192;
893		ch->user[i].tags = ch->numslots;
894		ch->user[i].caps = 0;
895		ch->curr[i] = ch->user[i];
896		if (ch->pm_level) {
897			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
898			    CTS_SATA_CAPS_H_APST |
899			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
900		}
901		ch->user[i].caps |= CTS_SATA_CAPS_H_DMAAA;
902	}
903	rid = ch->unit;
904	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
905	    &rid, RF_ACTIVE)))
906		return (ENXIO);
907	ahci_dmainit(dev);
908	ahci_slotsalloc(dev);
909	ahci_ch_init(dev);
910	mtx_lock(&ch->mtx);
911	rid = ATA_IRQ_RID;
912	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
913	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
914		device_printf(dev, "Unable to map interrupt\n");
915		error = ENXIO;
916		goto err0;
917	}
918	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
919	    ahci_ch_intr_locked, dev, &ch->ih))) {
920		device_printf(dev, "Unable to setup interrupt\n");
921		error = ENXIO;
922		goto err1;
923	}
924	ch->chcaps = ATA_INL(ch->r_mem, AHCI_P_CMD);
925	version = ATA_INL(ctlr->r_mem, AHCI_VS);
926	if (version < 0x00010020 && (ctlr->caps & AHCI_CAP_FBSS))
927		ch->chcaps |= AHCI_P_CMD_FBSCP;
928	if (bootverbose) {
929		device_printf(dev, "Caps:%s%s%s%s%s\n",
930		    (ch->chcaps & AHCI_P_CMD_HPCP) ? " HPCP":"",
931		    (ch->chcaps & AHCI_P_CMD_MPSP) ? " MPSP":"",
932		    (ch->chcaps & AHCI_P_CMD_CPD) ? " CPD":"",
933		    (ch->chcaps & AHCI_P_CMD_ESP) ? " ESP":"",
934		    (ch->chcaps & AHCI_P_CMD_FBSCP) ? " FBSCP":"");
935	}
936	/* Create the device queue for our SIM. */
937	devq = cam_simq_alloc(ch->numslots);
938	if (devq == NULL) {
939		device_printf(dev, "Unable to allocate simq\n");
940		error = ENOMEM;
941		goto err1;
942	}
943	/* Construct SIM entry */
944	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
945	    device_get_unit(dev), &ch->mtx,
946	    min(2, ch->numslots),
947	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
948	    devq);
949	if (ch->sim == NULL) {
950		cam_simq_free(devq);
951		device_printf(dev, "unable to allocate sim\n");
952		error = ENOMEM;
953		goto err1;
954	}
955	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
956		device_printf(dev, "unable to register xpt bus\n");
957		error = ENXIO;
958		goto err2;
959	}
960	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
961	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
962		device_printf(dev, "unable to create path\n");
963		error = ENXIO;
964		goto err3;
965	}
966	if (ch->pm_level > 3) {
967		callout_reset(&ch->pm_timer,
968		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
969		    ahci_ch_pm, dev);
970	}
971	mtx_unlock(&ch->mtx);
972	return (0);
973
974err3:
975	xpt_bus_deregister(cam_sim_path(ch->sim));
976err2:
977	cam_sim_free(ch->sim, /*free_devq*/TRUE);
978err1:
979	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
980err0:
981	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
982	mtx_unlock(&ch->mtx);
983	mtx_destroy(&ch->mtx);
984	return (error);
985}
986
987static int
988ahci_ch_detach(device_t dev)
989{
990	struct ahci_channel *ch = device_get_softc(dev);
991
992	mtx_lock(&ch->mtx);
993	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
994	xpt_free_path(ch->path);
995	xpt_bus_deregister(cam_sim_path(ch->sim));
996	cam_sim_free(ch->sim, /*free_devq*/TRUE);
997	mtx_unlock(&ch->mtx);
998
999	if (ch->pm_level > 3)
1000		callout_drain(&ch->pm_timer);
1001	bus_teardown_intr(dev, ch->r_irq, ch->ih);
1002	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
1003
1004	ahci_ch_deinit(dev);
1005	ahci_slotsfree(dev);
1006	ahci_dmafini(dev);
1007
1008	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
1009	mtx_destroy(&ch->mtx);
1010	return (0);
1011}
1012
1013static int
1014ahci_ch_init(device_t dev)
1015{
1016	struct ahci_channel *ch = device_get_softc(dev);
1017	uint64_t work;
1018
1019	/* Disable port interrupts */
1020	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1021	/* Setup work areas */
1022	work = ch->dma.work_bus + AHCI_CL_OFFSET;
1023	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
1024	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
1025	work = ch->dma.rfis_bus;
1026	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
1027	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
1028	/* Activate the channel and power/spin up device */
1029	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
1030	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
1031	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
1032	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
1033	ahci_start_fr(dev);
1034	ahci_start(dev, 1);
1035	return (0);
1036}
1037
1038static int
1039ahci_ch_deinit(device_t dev)
1040{
1041	struct ahci_channel *ch = device_get_softc(dev);
1042
1043	/* Disable port interrupts. */
1044	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1045	/* Reset command register. */
1046	ahci_stop(dev);
1047	ahci_stop_fr(dev);
1048	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
1049	/* Allow everything, including partial and slumber modes. */
1050	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
1051	/* Request slumber mode transition and give some time to get there. */
1052	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
1053	DELAY(100);
1054	/* Disable PHY. */
1055	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
1056	return (0);
1057}
1058
1059static int
1060ahci_ch_suspend(device_t dev)
1061{
1062	struct ahci_channel *ch = device_get_softc(dev);
1063
1064	mtx_lock(&ch->mtx);
1065	xpt_freeze_simq(ch->sim, 1);
1066	while (ch->oslots)
1067		msleep(ch, &ch->mtx, PRIBIO, "ahcisusp", hz/100);
1068	ahci_ch_deinit(dev);
1069	mtx_unlock(&ch->mtx);
1070	return (0);
1071}
1072
1073static int
1074ahci_ch_resume(device_t dev)
1075{
1076	struct ahci_channel *ch = device_get_softc(dev);
1077
1078	mtx_lock(&ch->mtx);
1079	ahci_ch_init(dev);
1080	ahci_reset(dev);
1081	xpt_release_simq(ch->sim, TRUE);
1082	mtx_unlock(&ch->mtx);
1083	return (0);
1084}
1085
1086devclass_t ahcich_devclass;
1087static device_method_t ahcich_methods[] = {
1088	DEVMETHOD(device_probe,     ahci_ch_probe),
1089	DEVMETHOD(device_attach,    ahci_ch_attach),
1090	DEVMETHOD(device_detach,    ahci_ch_detach),
1091	DEVMETHOD(device_suspend,   ahci_ch_suspend),
1092	DEVMETHOD(device_resume,    ahci_ch_resume),
1093	{ 0, 0 }
1094};
1095static driver_t ahcich_driver = {
1096        "ahcich",
1097        ahcich_methods,
1098        sizeof(struct ahci_channel)
1099};
1100DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahcich_devclass, 0, 0);
1101
1102struct ahci_dc_cb_args {
1103	bus_addr_t maddr;
1104	int error;
1105};
1106
1107static void
1108ahci_dmainit(device_t dev)
1109{
1110	struct ahci_channel *ch = device_get_softc(dev);
1111	struct ahci_dc_cb_args dcba;
1112	size_t rfsize;
1113
1114	if (ch->caps & AHCI_CAP_64BIT)
1115		ch->dma.max_address = BUS_SPACE_MAXADDR;
1116	else
1117		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
1118	/* Command area. */
1119	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
1120	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1121	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
1122	    0, NULL, NULL, &ch->dma.work_tag))
1123		goto error;
1124	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
1125	    &ch->dma.work_map))
1126		goto error;
1127	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
1128	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1129		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1130		goto error;
1131	}
1132	ch->dma.work_bus = dcba.maddr;
1133	/* FIS receive area. */
1134	if (ch->chcaps & AHCI_P_CMD_FBSCP)
1135	    rfsize = 4096;
1136	else
1137	    rfsize = 256;
1138	if (bus_dma_tag_create(bus_get_dma_tag(dev), rfsize, 0,
1139	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1140	    NULL, NULL, rfsize, 1, rfsize,
1141	    0, NULL, NULL, &ch->dma.rfis_tag))
1142		goto error;
1143	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1144	    &ch->dma.rfis_map))
1145		goto error;
1146	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1147	    rfsize, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1148		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1149		goto error;
1150	}
1151	ch->dma.rfis_bus = dcba.maddr;
1152	/* Data area. */
1153	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1154	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1155	    NULL, NULL,
1156	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
1157	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1158	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
1159		goto error;
1160	}
1161	return;
1162
1163error:
1164	device_printf(dev, "WARNING - DMA initialization failed\n");
1165	ahci_dmafini(dev);
1166}
1167
1168static void
1169ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1170{
1171	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1172
1173	if (!(dcba->error = error))
1174		dcba->maddr = segs[0].ds_addr;
1175}
1176
1177static void
1178ahci_dmafini(device_t dev)
1179{
1180	struct ahci_channel *ch = device_get_softc(dev);
1181
1182	if (ch->dma.data_tag) {
1183		bus_dma_tag_destroy(ch->dma.data_tag);
1184		ch->dma.data_tag = NULL;
1185	}
1186	if (ch->dma.rfis_bus) {
1187		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1188		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1189		ch->dma.rfis_bus = 0;
1190		ch->dma.rfis_map = NULL;
1191		ch->dma.rfis = NULL;
1192	}
1193	if (ch->dma.work_bus) {
1194		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1195		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1196		ch->dma.work_bus = 0;
1197		ch->dma.work_map = NULL;
1198		ch->dma.work = NULL;
1199	}
1200	if (ch->dma.work_tag) {
1201		bus_dma_tag_destroy(ch->dma.work_tag);
1202		ch->dma.work_tag = NULL;
1203	}
1204}
1205
1206static void
1207ahci_slotsalloc(device_t dev)
1208{
1209	struct ahci_channel *ch = device_get_softc(dev);
1210	int i;
1211
1212	/* Alloc and setup command/dma slots */
1213	bzero(ch->slot, sizeof(ch->slot));
1214	for (i = 0; i < ch->numslots; i++) {
1215		struct ahci_slot *slot = &ch->slot[i];
1216
1217		slot->dev = dev;
1218		slot->slot = i;
1219		slot->state = AHCI_SLOT_EMPTY;
1220		slot->ccb = NULL;
1221		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1222
1223		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1224			device_printf(ch->dev, "FAILURE - create data_map\n");
1225	}
1226}
1227
1228static void
1229ahci_slotsfree(device_t dev)
1230{
1231	struct ahci_channel *ch = device_get_softc(dev);
1232	int i;
1233
1234	/* Free all dma slots */
1235	for (i = 0; i < ch->numslots; i++) {
1236		struct ahci_slot *slot = &ch->slot[i];
1237
1238		callout_drain(&slot->timeout);
1239		if (slot->dma.data_map) {
1240			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1241			slot->dma.data_map = NULL;
1242		}
1243	}
1244}
1245
1246static void
1247ahci_phy_check_events(device_t dev, u_int32_t serr)
1248{
1249	struct ahci_channel *ch = device_get_softc(dev);
1250
1251	if ((serr & ATA_SE_PHY_CHANGED) && (ch->pm_level == 0)) {
1252		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1253		union ccb *ccb;
1254
1255		if (bootverbose) {
1256			if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1257			    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1258			    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
1259				device_printf(dev, "CONNECT requested\n");
1260			} else
1261				device_printf(dev, "DISCONNECT requested\n");
1262		}
1263		ahci_reset(dev);
1264		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1265			return;
1266		if (xpt_create_path(&ccb->ccb_h.path, NULL,
1267		    cam_sim_path(ch->sim),
1268		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1269			xpt_free_ccb(ccb);
1270			return;
1271		}
1272		xpt_rescan(ccb);
1273	}
1274}
1275
1276static void
1277ahci_notify_events(device_t dev, u_int32_t status)
1278{
1279	struct ahci_channel *ch = device_get_softc(dev);
1280	struct cam_path *dpath;
1281	int i;
1282
1283	if (ch->caps & AHCI_CAP_SSNTF)
1284		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1285	if (bootverbose)
1286		device_printf(dev, "SNTF 0x%04x\n", status);
1287	for (i = 0; i < 16; i++) {
1288		if ((status & (1 << i)) == 0)
1289			continue;
1290		if (xpt_create_path(&dpath, NULL,
1291		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1292			xpt_async(AC_SCSI_AEN, dpath, NULL);
1293			xpt_free_path(dpath);
1294		}
1295	}
1296}
1297
1298static void
1299ahci_ch_intr_locked(void *data)
1300{
1301	device_t dev = (device_t)data;
1302	struct ahci_channel *ch = device_get_softc(dev);
1303
1304	mtx_lock(&ch->mtx);
1305	ahci_ch_intr(data);
1306	mtx_unlock(&ch->mtx);
1307}
1308
1309static void
1310ahci_ch_pm(void *arg)
1311{
1312	device_t dev = (device_t)arg;
1313	struct ahci_channel *ch = device_get_softc(dev);
1314	uint32_t work;
1315
1316	if (ch->numrslots != 0)
1317		return;
1318	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1319	if (ch->pm_level == 4)
1320		work |= AHCI_P_CMD_PARTIAL;
1321	else
1322		work |= AHCI_P_CMD_SLUMBER;
1323	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1324}
1325
1326static void
1327ahci_ch_intr(void *data)
1328{
1329	device_t dev = (device_t)data;
1330	struct ahci_channel *ch = device_get_softc(dev);
1331	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1332	enum ahci_err_type et;
1333	int i, ccs, port;
1334
1335	/* Read and clear interrupt statuses. */
1336	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1337	if (istatus == 0)
1338		return;
1339	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1340	/* Read command statuses. */
1341	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1342	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1343	if (istatus & AHCI_P_IX_SDB) {
1344		if (ch->caps & AHCI_CAP_SSNTF)
1345			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1346		else if (ch->fbs_enabled) {
1347			u_int8_t *fis = ch->dma.rfis + 0x58;
1348
1349			for (i = 0; i < 16; i++) {
1350				if (fis[1] & 0x80) {
1351					fis[1] &= 0x7f;
1352	    				sntf |= 1 << i;
1353	    			}
1354	    			fis += 256;
1355	    		}
1356		} else {
1357			u_int8_t *fis = ch->dma.rfis + 0x58;
1358
1359			if (fis[1] & 0x80)
1360				sntf = (1 << (fis[1] & 0x0f));
1361		}
1362	}
1363	/* Process PHY events */
1364	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1365	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1366		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1367		if (serr) {
1368			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1369			ahci_phy_check_events(dev, serr);
1370		}
1371	}
1372	/* Process command errors */
1373	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1374	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1375		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1376		    >> AHCI_P_CMD_CCS_SHIFT;
1377//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1378//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1379//    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1380		port = -1;
1381		if (ch->fbs_enabled) {
1382			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1383			if (fbs & AHCI_P_FBS_SDE) {
1384				port = (fbs & AHCI_P_FBS_DWE)
1385				    >> AHCI_P_FBS_DWE_SHIFT;
1386			} else {
1387				for (i = 0; i < 16; i++) {
1388					if (ch->numrslotspd[i] == 0)
1389						continue;
1390					if (port == -1)
1391						port = i;
1392					else if (port != i) {
1393						port = -2;
1394						break;
1395					}
1396				}
1397			}
1398		}
1399		err = ch->rslots & (cstatus | sstatus);
1400	} else {
1401		ccs = 0;
1402		err = 0;
1403		port = -1;
1404	}
1405	/* Complete all successfull commands. */
1406	ok = ch->rslots & ~(cstatus | sstatus);
1407	for (i = 0; i < ch->numslots; i++) {
1408		if ((ok >> i) & 1)
1409			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1410	}
1411	/* On error, complete the rest of commands with error statuses. */
1412	if (err) {
1413		if (ch->frozen) {
1414			union ccb *fccb = ch->frozen;
1415			ch->frozen = NULL;
1416			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1417			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1418				xpt_freeze_devq(fccb->ccb_h.path, 1);
1419				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1420			}
1421			xpt_done(fccb);
1422		}
1423		for (i = 0; i < ch->numslots; i++) {
1424			/* XXX: reqests in loading state. */
1425			if (((err >> i) & 1) == 0)
1426				continue;
1427			if (port >= 0 &&
1428			    ch->slot[i].ccb->ccb_h.target_id != port)
1429				continue;
1430			if (istatus & AHCI_P_IX_TFE) {
1431			    if (port != -2) {
1432				/* Task File Error */
1433				if (ch->numtslotspd[
1434				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1435					/* Untagged operation. */
1436					if (i == ccs)
1437						et = AHCI_ERR_TFE;
1438					else
1439						et = AHCI_ERR_INNOCENT;
1440				} else {
1441					/* Tagged operation. */
1442					et = AHCI_ERR_NCQ;
1443				}
1444			    } else {
1445				et = AHCI_ERR_TFE;
1446				ch->fatalerr = 1;
1447			    }
1448			} else if (istatus & AHCI_P_IX_IF) {
1449				if (ch->numtslots == 0 && i != ccs && port != -2)
1450					et = AHCI_ERR_INNOCENT;
1451				else
1452					et = AHCI_ERR_SATA;
1453			} else
1454				et = AHCI_ERR_INVALID;
1455			ahci_end_transaction(&ch->slot[i], et);
1456		}
1457		/*
1458		 * We can't reinit port if there are some other
1459		 * commands active, use resume to complete them.
1460		 */
1461		if (ch->rslots != 0)
1462			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1463	}
1464	/* Process NOTIFY events */
1465	if (sntf)
1466		ahci_notify_events(dev, sntf);
1467}
1468
1469/* Must be called with channel locked. */
1470static int
1471ahci_check_collision(device_t dev, union ccb *ccb)
1472{
1473	struct ahci_channel *ch = device_get_softc(dev);
1474	int t = ccb->ccb_h.target_id;
1475
1476	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1477	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1478		/* Tagged command while we have no supported tag free. */
1479		if (((~ch->oslots) & (0xffffffff >> (32 -
1480		    ch->curr[t].tags))) == 0)
1481			return (1);
1482		/* If we have FBS */
1483		if (ch->fbs_enabled) {
1484			/* Tagged command while untagged are active. */
1485			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1486				return (1);
1487		} else {
1488			/* Tagged command while untagged are active. */
1489			if (ch->numrslots != 0 && ch->numtslots == 0)
1490				return (1);
1491			/* Tagged command while tagged to other target is active. */
1492			if (ch->numtslots != 0 &&
1493			    ch->taggedtarget != ccb->ccb_h.target_id)
1494				return (1);
1495		}
1496	} else {
1497		/* If we have FBS */
1498		if (ch->fbs_enabled) {
1499			/* Untagged command while tagged are active. */
1500			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1501				return (1);
1502		} else {
1503			/* Untagged command while tagged are active. */
1504			if (ch->numrslots != 0 && ch->numtslots != 0)
1505				return (1);
1506		}
1507	}
1508	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1509	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1510		/* Atomic command while anything active. */
1511		if (ch->numrslots != 0)
1512			return (1);
1513	}
1514       /* We have some atomic command running. */
1515       if (ch->aslots != 0)
1516               return (1);
1517	return (0);
1518}
1519
1520/* Must be called with channel locked. */
1521static void
1522ahci_begin_transaction(device_t dev, union ccb *ccb)
1523{
1524	struct ahci_channel *ch = device_get_softc(dev);
1525	struct ahci_slot *slot;
1526	int tag, tags;
1527
1528	/* Choose empty slot. */
1529	tags = ch->numslots;
1530	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1531	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1532		tags = ch->curr[ccb->ccb_h.target_id].tags;
1533	tag = ch->lastslot;
1534	while (1) {
1535		if (tag >= tags)
1536			tag = 0;
1537		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1538			break;
1539		tag++;
1540	};
1541	ch->lastslot = tag;
1542	/* Occupy chosen slot. */
1543	slot = &ch->slot[tag];
1544	slot->ccb = ccb;
1545	/* Stop PM timer. */
1546	if (ch->numrslots == 0 && ch->pm_level > 3)
1547		callout_stop(&ch->pm_timer);
1548	/* Update channel stats. */
1549	ch->oslots |= (1 << slot->slot);
1550	ch->numrslots++;
1551	ch->numrslotspd[ccb->ccb_h.target_id]++;
1552	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1553	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1554		ch->numtslots++;
1555		ch->numtslotspd[ccb->ccb_h.target_id]++;
1556		ch->taggedtarget = ccb->ccb_h.target_id;
1557	}
1558	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1559	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1560		ch->aslots |= (1 << slot->slot);
1561	slot->dma.nsegs = 0;
1562	/* If request moves data, setup and load SG list */
1563	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1564		void *buf;
1565		bus_size_t size;
1566
1567		slot->state = AHCI_SLOT_LOADING;
1568		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1569			buf = ccb->ataio.data_ptr;
1570			size = ccb->ataio.dxfer_len;
1571		} else {
1572			buf = ccb->csio.data_ptr;
1573			size = ccb->csio.dxfer_len;
1574		}
1575		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1576		    buf, size, ahci_dmasetprd, slot, 0);
1577	} else
1578		ahci_execute_transaction(slot);
1579}
1580
1581/* Locked by busdma engine. */
1582static void
1583ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1584{
1585	struct ahci_slot *slot = arg;
1586	struct ahci_channel *ch = device_get_softc(slot->dev);
1587	struct ahci_cmd_tab *ctp;
1588	struct ahci_dma_prd *prd;
1589	int i;
1590
1591	if (error) {
1592		device_printf(slot->dev, "DMA load error\n");
1593		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1594		return;
1595	}
1596	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1597	/* Get a piece of the workspace for this request */
1598	ctp = (struct ahci_cmd_tab *)
1599		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1600	/* Fill S/G table */
1601	prd = &ctp->prd_tab[0];
1602	for (i = 0; i < nsegs; i++) {
1603		prd[i].dba = htole64(segs[i].ds_addr);
1604		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1605	}
1606	slot->dma.nsegs = nsegs;
1607	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1608	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1609	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1610	ahci_execute_transaction(slot);
1611}
1612
1613/* Must be called with channel locked. */
1614static void
1615ahci_execute_transaction(struct ahci_slot *slot)
1616{
1617	device_t dev = slot->dev;
1618	struct ahci_channel *ch = device_get_softc(dev);
1619	struct ahci_cmd_tab *ctp;
1620	struct ahci_cmd_list *clp;
1621	union ccb *ccb = slot->ccb;
1622	int port = ccb->ccb_h.target_id & 0x0f;
1623	int fis_size, i;
1624	uint8_t *fis = ch->dma.rfis + 0x40;
1625	uint8_t val;
1626
1627	/* Get a piece of the workspace for this request */
1628	ctp = (struct ahci_cmd_tab *)
1629		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1630	/* Setup the FIS for this request */
1631	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1632		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1633		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1634		return;
1635	}
1636	/* Setup the command list entry */
1637	clp = (struct ahci_cmd_list *)
1638	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1639	clp->cmd_flags = htole16(
1640		    (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1641		    (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1642		     (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1643		    (fis_size / sizeof(u_int32_t)) |
1644		    (port << 12));
1645	clp->prd_length = htole16(slot->dma.nsegs);
1646	/* Special handling for Soft Reset command. */
1647	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1648	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1649		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1650			/* Kick controller into sane state */
1651			ahci_stop(dev);
1652			ahci_clo(dev);
1653			ahci_start(dev, 0);
1654			clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1655		} else {
1656			/* Prepare FIS receive area for check. */
1657			for (i = 0; i < 20; i++)
1658				fis[i] = 0xff;
1659		}
1660	}
1661	clp->bytecount = 0;
1662	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1663				  (AHCI_CT_SIZE * slot->slot));
1664	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1665	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1666	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1667	    BUS_DMASYNC_PREREAD);
1668	/* Set ACTIVE bit for NCQ commands. */
1669	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1670	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1671		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1672	}
1673	/* If FBS is enabled, set PMP port. */
1674	if (ch->fbs_enabled) {
1675		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1676		    (port << AHCI_P_FBS_DEV_SHIFT));
1677	}
1678	/* Issue command to the controller. */
1679	slot->state = AHCI_SLOT_RUNNING;
1680	ch->rslots |= (1 << slot->slot);
1681	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1682	/* Device reset commands doesn't interrupt. Poll them. */
1683	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1684	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1685	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1686		int count, timeout = ccb->ccb_h.timeout;
1687		enum ahci_err_type et = AHCI_ERR_NONE;
1688
1689		for (count = 0; count < timeout; count++) {
1690			DELAY(1000);
1691			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1692				break;
1693			if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1694				device_printf(ch->dev,
1695				    "Poll error on slot %d, TFD: %04x\n",
1696				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1697				et = AHCI_ERR_TFE;
1698				break;
1699			}
1700			/* Workaround for ATI SB600/SB700 chipsets. */
1701			if (ccb->ccb_h.target_id == 15 &&
1702			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1703			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1704				et = AHCI_ERR_TIMEOUT;
1705				break;
1706			}
1707		}
1708		if (timeout && (count >= timeout)) {
1709			device_printf(ch->dev,
1710			    "Poll timeout on slot %d\n", slot->slot);
1711			device_printf(dev, "is %08x cs %08x ss %08x "
1712			    "rs %08x tfd %02x serr %08x\n",
1713			    ATA_INL(ch->r_mem, AHCI_P_IS),
1714			    ATA_INL(ch->r_mem, AHCI_P_CI),
1715			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1716			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1717			    ATA_INL(ch->r_mem, AHCI_P_SERR));
1718			et = AHCI_ERR_TIMEOUT;
1719		}
1720		/* Marvell controllers do not wait for readyness. */
1721		if ((ch->quirks & AHCI_Q_NOBSYRES) &&
1722		    (ccb->ccb_h.func_code == XPT_ATA_IO) &&
1723		    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1724		    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1725			while ((val = fis[2]) & (ATA_S_BUSY | ATA_S_DRQ)) {
1726				DELAY(1000);
1727				if (count++ >= timeout) {
1728					device_printf(dev, "device is not "
1729					    "ready after soft-reset: "
1730					    "tfd = %08x\n", val);
1731	    				et = AHCI_ERR_TIMEOUT;
1732	    				break;
1733				}
1734			}
1735		}
1736		ahci_end_transaction(slot, et);
1737		/* Kick controller into sane state and enable FBS. */
1738		if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1739		    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1740		    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1741			ahci_stop(ch->dev);
1742			ahci_start(ch->dev, 1);
1743		}
1744		return;
1745	}
1746	/* Start command execution timeout */
1747	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1748	    (timeout_t*)ahci_timeout, slot);
1749	return;
1750}
1751
1752/* Must be called with channel locked. */
1753static void
1754ahci_process_timeout(device_t dev)
1755{
1756	struct ahci_channel *ch = device_get_softc(dev);
1757	int i;
1758
1759	mtx_assert(&ch->mtx, MA_OWNED);
1760	/* Handle the rest of commands. */
1761	for (i = 0; i < ch->numslots; i++) {
1762		/* Do we have a running request on slot? */
1763		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1764			continue;
1765		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1766	}
1767}
1768
1769/* Must be called with channel locked. */
1770static void
1771ahci_rearm_timeout(device_t dev)
1772{
1773	struct ahci_channel *ch = device_get_softc(dev);
1774	int i;
1775
1776	mtx_assert(&ch->mtx, MA_OWNED);
1777	for (i = 0; i < ch->numslots; i++) {
1778		struct ahci_slot *slot = &ch->slot[i];
1779
1780		/* Do we have a running request on slot? */
1781		if (slot->state < AHCI_SLOT_RUNNING)
1782			continue;
1783		if ((ch->toslots & (1 << i)) == 0)
1784			continue;
1785		callout_reset(&slot->timeout,
1786		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1787		    (timeout_t*)ahci_timeout, slot);
1788	}
1789}
1790
1791/* Locked by callout mechanism. */
1792static void
1793ahci_timeout(struct ahci_slot *slot)
1794{
1795	device_t dev = slot->dev;
1796	struct ahci_channel *ch = device_get_softc(dev);
1797	uint32_t sstatus;
1798	int ccs;
1799	int i;
1800
1801	/* Check for stale timeout. */
1802	if (slot->state < AHCI_SLOT_RUNNING)
1803		return;
1804
1805	/* Check if slot was not being executed last time we checked. */
1806	if (slot->state < AHCI_SLOT_EXECUTING) {
1807		/* Check if slot started executing. */
1808		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1809		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1810		    >> AHCI_P_CMD_CCS_SHIFT;
1811		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1812		    ch->fbs_enabled)
1813			slot->state = AHCI_SLOT_EXECUTING;
1814
1815		callout_reset(&slot->timeout,
1816		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1817		    (timeout_t*)ahci_timeout, slot);
1818		return;
1819	}
1820
1821	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1822	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1823	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1824	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1825	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR));
1826
1827	/* Handle frozen command. */
1828	if (ch->frozen) {
1829		union ccb *fccb = ch->frozen;
1830		ch->frozen = NULL;
1831		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1832		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1833			xpt_freeze_devq(fccb->ccb_h.path, 1);
1834			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1835		}
1836		xpt_done(fccb);
1837	}
1838	if (!ch->fbs_enabled) {
1839		/* Without FBS we know real timeout source. */
1840		ch->fatalerr = 1;
1841		/* Handle command with timeout. */
1842		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1843		/* Handle the rest of commands. */
1844		for (i = 0; i < ch->numslots; i++) {
1845			/* Do we have a running request on slot? */
1846			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1847				continue;
1848			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1849		}
1850	} else {
1851		/* With FBS we wait for other commands timeout and pray. */
1852		if (ch->toslots == 0)
1853			xpt_freeze_simq(ch->sim, 1);
1854		ch->toslots |= (1 << slot->slot);
1855		if ((ch->rslots & ~ch->toslots) == 0)
1856			ahci_process_timeout(dev);
1857		else
1858			device_printf(dev, " ... waiting for slots %08x\n",
1859			    ch->rslots & ~ch->toslots);
1860	}
1861}
1862
1863/* Must be called with channel locked. */
1864static void
1865ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1866{
1867	device_t dev = slot->dev;
1868	struct ahci_channel *ch = device_get_softc(dev);
1869	union ccb *ccb = slot->ccb;
1870	struct ahci_cmd_list *clp;
1871	int lastto;
1872
1873	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1874	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1875	clp = (struct ahci_cmd_list *)
1876	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1877	/* Read result registers to the result struct
1878	 * May be incorrect if several commands finished same time,
1879	 * so read only when sure or have to.
1880	 */
1881	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1882		struct ata_res *res = &ccb->ataio.res;
1883
1884		if ((et == AHCI_ERR_TFE) ||
1885		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1886			u_int8_t *fis = ch->dma.rfis + 0x40;
1887
1888			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1889			    BUS_DMASYNC_POSTREAD);
1890			if (ch->fbs_enabled) {
1891				fis += ccb->ccb_h.target_id * 256;
1892				res->status = fis[2];
1893				res->error = fis[3];
1894			} else {
1895				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1896
1897				res->status = tfd;
1898				res->error = tfd >> 8;
1899			}
1900			res->lba_low = fis[4];
1901			res->lba_mid = fis[5];
1902			res->lba_high = fis[6];
1903			res->device = fis[7];
1904			res->lba_low_exp = fis[8];
1905			res->lba_mid_exp = fis[9];
1906			res->lba_high_exp = fis[10];
1907			res->sector_count = fis[12];
1908			res->sector_count_exp = fis[13];
1909		} else
1910			bzero(res, sizeof(*res));
1911		if ((ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) == 0 &&
1912		    (ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1913		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
1914			ccb->ataio.resid =
1915			    ccb->ataio.dxfer_len - le32toh(clp->bytecount);
1916		}
1917	} else {
1918		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1919		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
1920			ccb->csio.resid =
1921			    ccb->csio.dxfer_len - le32toh(clp->bytecount);
1922		}
1923	}
1924	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1925		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1926		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1927		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1928		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1929	}
1930	if (et != AHCI_ERR_NONE)
1931		ch->eslots |= (1 << slot->slot);
1932	/* In case of error, freeze device for proper recovery. */
1933	if ((et != AHCI_ERR_NONE) && (!ch->readlog) &&
1934	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1935		xpt_freeze_devq(ccb->ccb_h.path, 1);
1936		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1937	}
1938	/* Set proper result status. */
1939	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1940	switch (et) {
1941	case AHCI_ERR_NONE:
1942		ccb->ccb_h.status |= CAM_REQ_CMP;
1943		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1944			ccb->csio.scsi_status = SCSI_STATUS_OK;
1945		break;
1946	case AHCI_ERR_INVALID:
1947		ch->fatalerr = 1;
1948		ccb->ccb_h.status |= CAM_REQ_INVALID;
1949		break;
1950	case AHCI_ERR_INNOCENT:
1951		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1952		break;
1953	case AHCI_ERR_TFE:
1954	case AHCI_ERR_NCQ:
1955		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1956			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1957			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1958		} else {
1959			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1960		}
1961		break;
1962	case AHCI_ERR_SATA:
1963		ch->fatalerr = 1;
1964		if (!ch->readlog) {
1965			xpt_freeze_simq(ch->sim, 1);
1966			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1967			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1968		}
1969		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1970		break;
1971	case AHCI_ERR_TIMEOUT:
1972		if (!ch->readlog) {
1973			xpt_freeze_simq(ch->sim, 1);
1974			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1975			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1976		}
1977		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1978		break;
1979	default:
1980		ch->fatalerr = 1;
1981		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1982	}
1983	/* Free slot. */
1984	ch->oslots &= ~(1 << slot->slot);
1985	ch->rslots &= ~(1 << slot->slot);
1986	ch->aslots &= ~(1 << slot->slot);
1987	slot->state = AHCI_SLOT_EMPTY;
1988	slot->ccb = NULL;
1989	/* Update channel stats. */
1990	ch->numrslots--;
1991	ch->numrslotspd[ccb->ccb_h.target_id]--;
1992	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1993	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1994		ch->numtslots--;
1995		ch->numtslotspd[ccb->ccb_h.target_id]--;
1996	}
1997	/* Cancel timeout state if request completed normally. */
1998	if (et != AHCI_ERR_TIMEOUT) {
1999		lastto = (ch->toslots == (1 << slot->slot));
2000		ch->toslots &= ~(1 << slot->slot);
2001		if (lastto)
2002			xpt_release_simq(ch->sim, TRUE);
2003	}
2004	/* If it was first request of reset sequence and there is no error,
2005	 * proceed to second request. */
2006	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2007	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
2008	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
2009	    et == AHCI_ERR_NONE) {
2010		ccb->ataio.cmd.control &= ~ATA_A_RESET;
2011		ahci_begin_transaction(dev, ccb);
2012		return;
2013	}
2014	/* If it was our READ LOG command - process it. */
2015	if (ch->readlog) {
2016		ahci_process_read_log(dev, ccb);
2017	/* If it was NCQ command error, put result on hold. */
2018	} else if (et == AHCI_ERR_NCQ) {
2019		ch->hold[slot->slot] = ccb;
2020		ch->numhslots++;
2021	} else
2022		xpt_done(ccb);
2023	/* Unfreeze frozen command. */
2024	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
2025		union ccb *fccb = ch->frozen;
2026		ch->frozen = NULL;
2027		ahci_begin_transaction(dev, fccb);
2028		xpt_release_simq(ch->sim, TRUE);
2029	}
2030	/* If we have no other active commands, ... */
2031	if (ch->rslots == 0) {
2032		/* if there was fatal error - reset port. */
2033		if (ch->toslots != 0 || ch->fatalerr) {
2034			ahci_reset(dev);
2035		} else {
2036			/* if we have slots in error, we can reinit port. */
2037			if (ch->eslots != 0) {
2038				ahci_stop(dev);
2039				ahci_start(dev, 1);
2040			}
2041			/* if there commands on hold, we can do READ LOG. */
2042			if (!ch->readlog && ch->numhslots)
2043				ahci_issue_read_log(dev);
2044		}
2045	/* If all the rest of commands are in timeout - give them chance. */
2046	} else if ((ch->rslots & ~ch->toslots) == 0 &&
2047	    et != AHCI_ERR_TIMEOUT)
2048		ahci_rearm_timeout(dev);
2049	/* Start PM timer. */
2050	if (ch->numrslots == 0 && ch->pm_level > 3 &&
2051	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
2052		callout_schedule(&ch->pm_timer,
2053		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
2054	}
2055}
2056
2057static void
2058ahci_issue_read_log(device_t dev)
2059{
2060	struct ahci_channel *ch = device_get_softc(dev);
2061	union ccb *ccb;
2062	struct ccb_ataio *ataio;
2063	int i;
2064
2065	ch->readlog = 1;
2066	/* Find some holden command. */
2067	for (i = 0; i < ch->numslots; i++) {
2068		if (ch->hold[i])
2069			break;
2070	}
2071	ccb = xpt_alloc_ccb_nowait();
2072	if (ccb == NULL) {
2073		device_printf(dev, "Unable allocate READ LOG command");
2074		return; /* XXX */
2075	}
2076	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
2077	ccb->ccb_h.func_code = XPT_ATA_IO;
2078	ccb->ccb_h.flags = CAM_DIR_IN;
2079	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2080	ataio = &ccb->ataio;
2081	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
2082	if (ataio->data_ptr == NULL) {
2083		xpt_free_ccb(ccb);
2084		device_printf(dev, "Unable allocate memory for READ LOG command");
2085		return; /* XXX */
2086	}
2087	ataio->dxfer_len = 512;
2088	bzero(&ataio->cmd, sizeof(ataio->cmd));
2089	ataio->cmd.flags = CAM_ATAIO_48BIT;
2090	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
2091	ataio->cmd.sector_count = 1;
2092	ataio->cmd.sector_count_exp = 0;
2093	ataio->cmd.lba_low = 0x10;
2094	ataio->cmd.lba_mid = 0;
2095	ataio->cmd.lba_mid_exp = 0;
2096	/* Freeze SIM while doing READ LOG EXT. */
2097	xpt_freeze_simq(ch->sim, 1);
2098	ahci_begin_transaction(dev, ccb);
2099}
2100
2101static void
2102ahci_process_read_log(device_t dev, union ccb *ccb)
2103{
2104	struct ahci_channel *ch = device_get_softc(dev);
2105	uint8_t *data;
2106	struct ata_res *res;
2107	int i;
2108
2109	ch->readlog = 0;
2110
2111	data = ccb->ataio.data_ptr;
2112	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2113	    (data[0] & 0x80) == 0) {
2114		for (i = 0; i < ch->numslots; i++) {
2115			if (!ch->hold[i])
2116				continue;
2117			if ((data[0] & 0x1F) == i) {
2118				res = &ch->hold[i]->ataio.res;
2119				res->status = data[2];
2120				res->error = data[3];
2121				res->lba_low = data[4];
2122				res->lba_mid = data[5];
2123				res->lba_high = data[6];
2124				res->device = data[7];
2125				res->lba_low_exp = data[8];
2126				res->lba_mid_exp = data[9];
2127				res->lba_high_exp = data[10];
2128				res->sector_count = data[12];
2129				res->sector_count_exp = data[13];
2130			} else {
2131				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2132				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2133			}
2134			xpt_done(ch->hold[i]);
2135			ch->hold[i] = NULL;
2136			ch->numhslots--;
2137		}
2138	} else {
2139		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2140			device_printf(dev, "Error while READ LOG EXT\n");
2141		else if ((data[0] & 0x80) == 0) {
2142			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
2143		}
2144		for (i = 0; i < ch->numslots; i++) {
2145			if (!ch->hold[i])
2146				continue;
2147			xpt_done(ch->hold[i]);
2148			ch->hold[i] = NULL;
2149			ch->numhslots--;
2150		}
2151	}
2152	free(ccb->ataio.data_ptr, M_AHCI);
2153	xpt_free_ccb(ccb);
2154	xpt_release_simq(ch->sim, TRUE);
2155}
2156
2157static void
2158ahci_start(device_t dev, int fbs)
2159{
2160	struct ahci_channel *ch = device_get_softc(dev);
2161	u_int32_t cmd;
2162
2163	/* Clear SATA error register */
2164	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2165	/* Clear any interrupts pending on this channel */
2166	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2167	/* Configure FIS-based switching if supported. */
2168	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2169		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2170		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2171		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2172	}
2173	/* Start operations on this channel */
2174	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2175	cmd &= ~AHCI_P_CMD_PMA;
2176	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2177	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2178}
2179
2180static void
2181ahci_stop(device_t dev)
2182{
2183	struct ahci_channel *ch = device_get_softc(dev);
2184	u_int32_t cmd;
2185	int timeout;
2186
2187	/* Kill all activity on this channel */
2188	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2189	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2190	/* Wait for activity stop. */
2191	timeout = 0;
2192	do {
2193		DELAY(1000);
2194		if (timeout++ > 1000) {
2195			device_printf(dev, "stopping AHCI engine failed\n");
2196			break;
2197		}
2198	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2199	ch->eslots = 0;
2200}
2201
2202static void
2203ahci_clo(device_t dev)
2204{
2205	struct ahci_channel *ch = device_get_softc(dev);
2206	u_int32_t cmd;
2207	int timeout;
2208
2209	/* Issue Command List Override if supported */
2210	if (ch->caps & AHCI_CAP_SCLO) {
2211		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2212		cmd |= AHCI_P_CMD_CLO;
2213		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2214		timeout = 0;
2215		do {
2216			DELAY(1000);
2217			if (timeout++ > 1000) {
2218			    device_printf(dev, "executing CLO failed\n");
2219			    break;
2220			}
2221		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2222	}
2223}
2224
2225static void
2226ahci_stop_fr(device_t dev)
2227{
2228	struct ahci_channel *ch = device_get_softc(dev);
2229	u_int32_t cmd;
2230	int timeout;
2231
2232	/* Kill all FIS reception on this channel */
2233	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2234	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2235	/* Wait for FIS reception stop. */
2236	timeout = 0;
2237	do {
2238		DELAY(1000);
2239		if (timeout++ > 1000) {
2240			device_printf(dev, "stopping AHCI FR engine failed\n");
2241			break;
2242		}
2243	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2244}
2245
2246static void
2247ahci_start_fr(device_t dev)
2248{
2249	struct ahci_channel *ch = device_get_softc(dev);
2250	u_int32_t cmd;
2251
2252	/* Start FIS reception on this channel */
2253	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2254	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2255}
2256
2257static int
2258ahci_wait_ready(device_t dev, int t)
2259{
2260	struct ahci_channel *ch = device_get_softc(dev);
2261	int timeout = 0;
2262	uint32_t val;
2263
2264	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2265	    (ATA_S_BUSY | ATA_S_DRQ)) {
2266		DELAY(1000);
2267		if (timeout++ > t) {
2268			device_printf(dev, "device is not ready (timeout %dms) "
2269			    "tfd = %08x\n", t, val);
2270			return (EBUSY);
2271		}
2272	}
2273	if (bootverbose)
2274		device_printf(dev, "ready wait time=%dms\n", timeout);
2275	return (0);
2276}
2277
2278static void
2279ahci_reset(device_t dev)
2280{
2281	struct ahci_channel *ch = device_get_softc(dev);
2282	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
2283	int i;
2284
2285	xpt_freeze_simq(ch->sim, 1);
2286	if (bootverbose)
2287		device_printf(dev, "AHCI reset...\n");
2288	/* Requeue freezed command. */
2289	if (ch->frozen) {
2290		union ccb *fccb = ch->frozen;
2291		ch->frozen = NULL;
2292		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2293		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2294			xpt_freeze_devq(fccb->ccb_h.path, 1);
2295			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2296		}
2297		xpt_done(fccb);
2298	}
2299	/* Kill the engine and requeue all running commands. */
2300	ahci_stop(dev);
2301	for (i = 0; i < ch->numslots; i++) {
2302		/* Do we have a running request on slot? */
2303		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2304			continue;
2305		/* XXX; Commands in loading state. */
2306		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2307	}
2308	for (i = 0; i < ch->numslots; i++) {
2309		if (!ch->hold[i])
2310			continue;
2311		xpt_done(ch->hold[i]);
2312		ch->hold[i] = NULL;
2313		ch->numhslots--;
2314	}
2315	if (ch->toslots != 0)
2316		xpt_release_simq(ch->sim, TRUE);
2317	ch->eslots = 0;
2318	ch->toslots = 0;
2319	ch->fatalerr = 0;
2320	/* Tell the XPT about the event */
2321	xpt_async(AC_BUS_RESET, ch->path, NULL);
2322	/* Disable port interrupts */
2323	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2324	/* Reset and reconnect PHY, */
2325	if (!ahci_sata_phy_reset(dev)) {
2326		if (bootverbose)
2327			device_printf(dev,
2328			    "AHCI reset done: phy reset found no device\n");
2329		ch->devices = 0;
2330		/* Enable wanted port interrupts */
2331		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2332		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
2333		xpt_release_simq(ch->sim, TRUE);
2334		return;
2335	}
2336	/* Wait for clearing busy status. */
2337	if (ahci_wait_ready(dev, 15000))
2338		ahci_clo(dev);
2339	ahci_start(dev, 1);
2340	ch->devices = 1;
2341	/* Enable wanted port interrupts */
2342	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2343	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2344	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2345	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
2346	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2347	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2348	if (bootverbose)
2349		device_printf(dev, "AHCI reset done: device found\n");
2350	xpt_release_simq(ch->sim, TRUE);
2351}
2352
2353static int
2354ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2355{
2356	struct ahci_channel *ch = device_get_softc(dev);
2357	u_int8_t *fis = &ctp->cfis[0];
2358
2359	bzero(ctp->cfis, 64);
2360	fis[0] = 0x27;  		/* host to device */
2361	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2362	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2363		fis[1] |= 0x80;
2364		fis[2] = ATA_PACKET_CMD;
2365		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2366		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2367			fis[3] = ATA_F_DMA;
2368		else {
2369			fis[5] = ccb->csio.dxfer_len;
2370		        fis[6] = ccb->csio.dxfer_len >> 8;
2371		}
2372		fis[7] = ATA_D_LBA;
2373		fis[15] = ATA_A_4BIT;
2374		bzero(ctp->acmd, 32);
2375		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2376		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2377		    ctp->acmd, ccb->csio.cdb_len);
2378	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2379		fis[1] |= 0x80;
2380		fis[2] = ccb->ataio.cmd.command;
2381		fis[3] = ccb->ataio.cmd.features;
2382		fis[4] = ccb->ataio.cmd.lba_low;
2383		fis[5] = ccb->ataio.cmd.lba_mid;
2384		fis[6] = ccb->ataio.cmd.lba_high;
2385		fis[7] = ccb->ataio.cmd.device;
2386		fis[8] = ccb->ataio.cmd.lba_low_exp;
2387		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2388		fis[10] = ccb->ataio.cmd.lba_high_exp;
2389		fis[11] = ccb->ataio.cmd.features_exp;
2390		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2391			fis[12] = tag << 3;
2392			fis[13] = 0;
2393		} else {
2394			fis[12] = ccb->ataio.cmd.sector_count;
2395			fis[13] = ccb->ataio.cmd.sector_count_exp;
2396		}
2397		fis[15] = ATA_A_4BIT;
2398	} else {
2399		fis[15] = ccb->ataio.cmd.control;
2400	}
2401	return (20);
2402}
2403
2404static int
2405ahci_sata_connect(struct ahci_channel *ch)
2406{
2407	u_int32_t status;
2408	int timeout;
2409
2410	/* Wait up to 100ms for "connect well" */
2411	for (timeout = 0; timeout < 100 ; timeout++) {
2412		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2413		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2414		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2415		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2416			break;
2417		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2418			if (bootverbose) {
2419				device_printf(ch->dev, "SATA offline status=%08x\n",
2420				    status);
2421			}
2422			return (0);
2423		}
2424		DELAY(1000);
2425	}
2426	if (timeout >= 100) {
2427		if (bootverbose) {
2428			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
2429			    status);
2430		}
2431		return (0);
2432	}
2433	if (bootverbose) {
2434		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
2435		    timeout, status);
2436	}
2437	/* Clear SATA error register */
2438	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2439	return (1);
2440}
2441
2442static int
2443ahci_sata_phy_reset(device_t dev)
2444{
2445	struct ahci_channel *ch = device_get_softc(dev);
2446	int sata_rev;
2447	uint32_t val;
2448
2449	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2450	if (sata_rev == 1)
2451		val = ATA_SC_SPD_SPEED_GEN1;
2452	else if (sata_rev == 2)
2453		val = ATA_SC_SPD_SPEED_GEN2;
2454	else if (sata_rev == 3)
2455		val = ATA_SC_SPD_SPEED_GEN3;
2456	else
2457		val = 0;
2458	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2459	    ATA_SC_DET_RESET | val |
2460	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2461	DELAY(5000);
2462	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2463	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2464	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2465	DELAY(5000);
2466	if (!ahci_sata_connect(ch)) {
2467		if (ch->pm_level > 0)
2468			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2469		return (0);
2470	}
2471	return (1);
2472}
2473
2474static int
2475ahci_check_ids(device_t dev, union ccb *ccb)
2476{
2477	struct ahci_channel *ch = device_get_softc(dev);
2478
2479	if (ccb->ccb_h.target_id > ((ch->caps & AHCI_CAP_SPM) ? 15 : 0)) {
2480		ccb->ccb_h.status = CAM_TID_INVALID;
2481		xpt_done(ccb);
2482		return (-1);
2483	}
2484	if (ccb->ccb_h.target_lun != 0) {
2485		ccb->ccb_h.status = CAM_LUN_INVALID;
2486		xpt_done(ccb);
2487		return (-1);
2488	}
2489	return (0);
2490}
2491
2492static void
2493ahciaction(struct cam_sim *sim, union ccb *ccb)
2494{
2495	device_t dev, parent;
2496	struct ahci_channel *ch;
2497
2498	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2499	    ccb->ccb_h.func_code));
2500
2501	ch = (struct ahci_channel *)cam_sim_softc(sim);
2502	dev = ch->dev;
2503	switch (ccb->ccb_h.func_code) {
2504	/* Common cases first */
2505	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2506	case XPT_SCSI_IO:
2507		if (ahci_check_ids(dev, ccb))
2508			return;
2509		if (ch->devices == 0 ||
2510		    (ch->pm_present == 0 &&
2511		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2512			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2513			break;
2514		}
2515		/* Check for command collision. */
2516		if (ahci_check_collision(dev, ccb)) {
2517			/* Freeze command. */
2518			ch->frozen = ccb;
2519			/* We have only one frozen slot, so freeze simq also. */
2520			xpt_freeze_simq(ch->sim, 1);
2521			return;
2522		}
2523		ahci_begin_transaction(dev, ccb);
2524		return;
2525	case XPT_EN_LUN:		/* Enable LUN as a target */
2526	case XPT_TARGET_IO:		/* Execute target I/O request */
2527	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2528	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2529	case XPT_ABORT:			/* Abort the specified CCB */
2530		/* XXX Implement */
2531		ccb->ccb_h.status = CAM_REQ_INVALID;
2532		break;
2533	case XPT_SET_TRAN_SETTINGS:
2534	{
2535		struct	ccb_trans_settings *cts = &ccb->cts;
2536		struct	ahci_device *d;
2537
2538		if (ahci_check_ids(dev, ccb))
2539			return;
2540		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2541			d = &ch->curr[ccb->ccb_h.target_id];
2542		else
2543			d = &ch->user[ccb->ccb_h.target_id];
2544		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2545			d->revision = cts->xport_specific.sata.revision;
2546		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2547			d->mode = cts->xport_specific.sata.mode;
2548		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2549			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2550		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2551			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2552		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2553			ch->pm_present = cts->xport_specific.sata.pm_present;
2554		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2555			d->atapi = cts->xport_specific.sata.atapi;
2556		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2557			d->caps = cts->xport_specific.sata.caps;
2558		ccb->ccb_h.status = CAM_REQ_CMP;
2559		break;
2560	}
2561	case XPT_GET_TRAN_SETTINGS:
2562	/* Get default/user set transfer settings for the target */
2563	{
2564		struct	ccb_trans_settings *cts = &ccb->cts;
2565		struct  ahci_device *d;
2566		uint32_t status;
2567
2568		if (ahci_check_ids(dev, ccb))
2569			return;
2570		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2571			d = &ch->curr[ccb->ccb_h.target_id];
2572		else
2573			d = &ch->user[ccb->ccb_h.target_id];
2574		cts->protocol = PROTO_ATA;
2575		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2576		cts->transport = XPORT_SATA;
2577		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2578		cts->proto_specific.valid = 0;
2579		cts->xport_specific.sata.valid = 0;
2580		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2581		    (ccb->ccb_h.target_id == 15 ||
2582		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2583			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2584			if (status & 0x0f0) {
2585				cts->xport_specific.sata.revision =
2586				    (status & 0x0f0) >> 4;
2587				cts->xport_specific.sata.valid |=
2588				    CTS_SATA_VALID_REVISION;
2589			}
2590			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2591			if (ch->pm_level) {
2592				if (ch->caps & (AHCI_CAP_PSC | AHCI_CAP_SSC))
2593					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2594				if (ch->caps2 & AHCI_CAP2_APST)
2595					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_APST;
2596			}
2597			if ((ch->caps & AHCI_CAP_SNCQ) &&
2598			    (ch->quirks & AHCI_Q_NOAA) == 0)
2599				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_DMAAA;
2600			cts->xport_specific.sata.caps &=
2601			    ch->user[ccb->ccb_h.target_id].caps;
2602			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2603		} else {
2604			cts->xport_specific.sata.revision = d->revision;
2605			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2606			cts->xport_specific.sata.caps = d->caps;
2607			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2608		}
2609		cts->xport_specific.sata.mode = d->mode;
2610		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2611		cts->xport_specific.sata.bytecount = d->bytecount;
2612		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2613		cts->xport_specific.sata.pm_present = ch->pm_present;
2614		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2615		cts->xport_specific.sata.tags = d->tags;
2616		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2617		cts->xport_specific.sata.atapi = d->atapi;
2618		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2619		ccb->ccb_h.status = CAM_REQ_CMP;
2620		break;
2621	}
2622	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2623	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2624		ahci_reset(dev);
2625		ccb->ccb_h.status = CAM_REQ_CMP;
2626		break;
2627	case XPT_TERM_IO:		/* Terminate the I/O process */
2628		/* XXX Implement */
2629		ccb->ccb_h.status = CAM_REQ_INVALID;
2630		break;
2631	case XPT_PATH_INQ:		/* Path routing inquiry */
2632	{
2633		struct ccb_pathinq *cpi = &ccb->cpi;
2634
2635		parent = device_get_parent(dev);
2636		cpi->version_num = 1; /* XXX??? */
2637		cpi->hba_inquiry = PI_SDTR_ABLE;
2638		if (ch->caps & AHCI_CAP_SNCQ)
2639			cpi->hba_inquiry |= PI_TAG_ABLE;
2640		if (ch->caps & AHCI_CAP_SPM)
2641			cpi->hba_inquiry |= PI_SATAPM;
2642		cpi->target_sprt = 0;
2643		cpi->hba_misc = PIM_SEQSCAN;
2644		cpi->hba_eng_cnt = 0;
2645		if (ch->caps & AHCI_CAP_SPM)
2646			cpi->max_target = 15;
2647		else
2648			cpi->max_target = 0;
2649		cpi->max_lun = 0;
2650		cpi->initiator_id = 0;
2651		cpi->bus_id = cam_sim_bus(sim);
2652		cpi->base_transfer_speed = 150000;
2653		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2654		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2655		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2656		cpi->unit_number = cam_sim_unit(sim);
2657		cpi->transport = XPORT_SATA;
2658		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2659		cpi->protocol = PROTO_ATA;
2660		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2661		cpi->maxio = MAXPHYS;
2662		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2663		if (pci_get_devid(parent) == 0x43801002)
2664			cpi->maxio = min(cpi->maxio, 128 * 512);
2665		cpi->hba_vendor = pci_get_vendor(parent);
2666		cpi->hba_device = pci_get_device(parent);
2667		cpi->hba_subvendor = pci_get_subvendor(parent);
2668		cpi->hba_subdevice = pci_get_subdevice(parent);
2669		cpi->ccb_h.status = CAM_REQ_CMP;
2670		break;
2671	}
2672	default:
2673		ccb->ccb_h.status = CAM_REQ_INVALID;
2674		break;
2675	}
2676	xpt_done(ccb);
2677}
2678
2679static void
2680ahcipoll(struct cam_sim *sim)
2681{
2682	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2683
2684	ahci_ch_intr(ch->dev);
2685}
2686