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