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