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