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