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