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