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