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