]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - sys/dev/ahci/ahci.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / sys / dev / ahci / ahci.c
1 /*-
2  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/param.h>
31 #include <sys/module.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/ata.h>
35 #include <sys/bus.h>
36 #include <sys/endian.h>
37 #include <sys/malloc.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/sema.h>
41 #include <sys/taskqueue.h>
42 #include <vm/uma.h>
43 #include <machine/stdarg.h>
44 #include <machine/resource.h>
45 #include <machine/bus.h>
46 #include <sys/rman.h>
47 #include <dev/pci/pcivar.h>
48 #include <dev/pci/pcireg.h>
49 #include "ahci.h"
50
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_sim.h>
54 #include <cam/cam_xpt_sim.h>
55 #include <cam/cam_xpt_periph.h>
56 #include <cam/cam_debug.h>
57
58 /* local prototypes */
59 static int ahci_setup_interrupt(device_t dev);
60 static void ahci_intr(void *data);
61 static void ahci_intr_one(void *data);
62 static int ahci_suspend(device_t dev);
63 static int ahci_resume(device_t dev);
64 static int ahci_ch_suspend(device_t dev);
65 static int ahci_ch_resume(device_t dev);
66 static void ahci_ch_pm(void *arg);
67 static void ahci_ch_intr_locked(void *data);
68 static void ahci_ch_intr(void *data);
69 static int ahci_ctlr_reset(device_t dev);
70 static void ahci_begin_transaction(device_t dev, union ccb *ccb);
71 static void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
72 static void ahci_execute_transaction(struct ahci_slot *slot);
73 static void ahci_timeout(struct ahci_slot *slot);
74 static void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
75 static int ahci_setup_fis(struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
76 static void ahci_dmainit(device_t dev);
77 static void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
78 static void ahci_dmafini(device_t dev);
79 static void ahci_slotsalloc(device_t dev);
80 static void ahci_slotsfree(device_t dev);
81 static void ahci_reset(device_t dev);
82 static void ahci_start(device_t dev);
83 static void ahci_stop(device_t dev);
84 static void ahci_clo(device_t dev);
85 static void ahci_start_fr(device_t dev);
86 static void ahci_stop_fr(device_t dev);
87
88 static int ahci_sata_connect(struct ahci_channel *ch);
89 static int ahci_sata_phy_reset(device_t dev, int quick);
90
91 static void ahci_issue_read_log(device_t dev);
92 static void ahci_process_read_log(device_t dev, union ccb *ccb);
93
94 static void ahciaction(struct cam_sim *sim, union ccb *ccb);
95 static void ahcipoll(struct cam_sim *sim);
96
97 MALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
98
99 /*
100  * AHCI v1.x compliant SATA chipset support functions
101  */
102 static int
103 ahci_probe(device_t dev)
104 {
105
106         /* is this a possible AHCI candidate ? */
107         if (pci_get_class(dev) != PCIC_STORAGE ||
108             pci_get_subclass(dev) != PCIS_STORAGE_SATA)
109                 return (ENXIO);
110
111         /* is this PCI device flagged as an AHCI compliant chip ? */
112         if (pci_get_progif(dev) != PCIP_STORAGE_SATA_AHCI_1_0)
113                 return (ENXIO);
114
115         device_set_desc_copy(dev, "AHCI controller");
116         return (BUS_PROBE_VENDOR);
117 }
118
119 static int
120 ahci_attach(device_t dev)
121 {
122         struct ahci_controller *ctlr = device_get_softc(dev);
123         device_t child;
124         int     error, unit, speed;
125         u_int32_t version;
126
127         ctlr->dev = dev;
128         resource_int_value(device_get_name(dev),
129             device_get_unit(dev), "ccc", &ctlr->ccc);
130         /* if we have a memory BAR(5) we are likely on an AHCI part */
131         ctlr->r_rid = PCIR_BAR(5);
132         if (!(ctlr->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
133             &ctlr->r_rid, RF_ACTIVE)))
134                 return ENXIO;
135         /* Setup our own memory management for channels. */
136         ctlr->sc_iomem.rm_type = RMAN_ARRAY;
137         ctlr->sc_iomem.rm_descr = "I/O memory addresses";
138         if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
139                 bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
140                 return (error);
141         }
142         if ((error = rman_manage_region(&ctlr->sc_iomem,
143             rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
144                 bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
145                 rman_fini(&ctlr->sc_iomem);
146                 return (error);
147         }
148         /* Reset controller */
149         if ((error = ahci_ctlr_reset(dev)) != 0) {
150                 bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
151                 rman_fini(&ctlr->sc_iomem);
152                 return (error);
153         };
154         /* Get the number of HW channels */
155         ctlr->ichannels = ATA_INL(ctlr->r_mem, AHCI_PI);
156         ctlr->channels = MAX(flsl(ctlr->ichannels),
157             (ATA_INL(ctlr->r_mem, AHCI_CAP) & AHCI_CAP_NPMASK) + 1);
158         /* Setup interrupts. */
159         if (ahci_setup_interrupt(dev)) {
160                 bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
161                 rman_fini(&ctlr->sc_iomem);
162                 return ENXIO;
163         }
164         /* Announce HW capabilities. */
165         version = ATA_INL(ctlr->r_mem, AHCI_VS);
166         ctlr->caps = ATA_INL(ctlr->r_mem, AHCI_CAP);
167         if (version >= 0x00010020)
168                 ctlr->caps2 = ATA_INL(ctlr->r_mem, AHCI_CAP2);
169         speed = (ctlr->caps & AHCI_CAP_ISS) >> AHCI_CAP_ISS_SHIFT;
170         device_printf(dev,
171                     "AHCI v%x.%02x with %d %sGbps ports, Port Multiplier %s\n",
172                     ((version >> 20) & 0xf0) + ((version >> 16) & 0x0f),
173                     ((version >> 4) & 0xf0) + (version & 0x0f),
174                     (ctlr->caps & AHCI_CAP_NPMASK) + 1,
175                     ((speed == 1) ? "1.5":((speed == 2) ? "3":
176                     ((speed == 3) ? "6":"?"))),
177                     (ctlr->caps & AHCI_CAP_SPM) ?
178                     "supported" : "not supported");
179         if (bootverbose) {
180                 device_printf(dev, "Caps:%s%s%s%s%s%s%s%s %sGbps",
181                     (ctlr->caps & AHCI_CAP_64BIT) ? " 64bit":"",
182                     (ctlr->caps & AHCI_CAP_SNCQ) ? " NCQ":"",
183                     (ctlr->caps & AHCI_CAP_SSNTF) ? " SNTF":"",
184                     (ctlr->caps & AHCI_CAP_SMPS) ? " MPS":"",
185                     (ctlr->caps & AHCI_CAP_SSS) ? " SS":"",
186                     (ctlr->caps & AHCI_CAP_SALP) ? " ALP":"",
187                     (ctlr->caps & AHCI_CAP_SAL) ? " AL":"",
188                     (ctlr->caps & AHCI_CAP_SCLO) ? " CLO":"",
189                     ((speed == 1) ? "1.5":((speed == 2) ? "3":
190                     ((speed == 3) ? "6":"?"))));
191                 printf("%s%s%s%s%s%s %dcmd%s%s%s %dports\n",
192                     (ctlr->caps & AHCI_CAP_SAM) ? " AM":"",
193                     (ctlr->caps & AHCI_CAP_SPM) ? " PM":"",
194                     (ctlr->caps & AHCI_CAP_FBSS) ? " FBS":"",
195                     (ctlr->caps & AHCI_CAP_PMD) ? " PMD":"",
196                     (ctlr->caps & AHCI_CAP_SSC) ? " SSC":"",
197                     (ctlr->caps & AHCI_CAP_PSC) ? " PSC":"",
198                     ((ctlr->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
199                     (ctlr->caps & AHCI_CAP_CCCS) ? " CCC":"",
200                     (ctlr->caps & AHCI_CAP_EMS) ? " EM":"",
201                     (ctlr->caps & AHCI_CAP_SXS) ? " eSATA":"",
202                     (ctlr->caps & AHCI_CAP_NPMASK) + 1);
203         }
204         if (bootverbose && version >= 0x00010020) {
205                 device_printf(dev, "Caps2:%s%s%s\n",
206                     (ctlr->caps2 & AHCI_CAP2_APST) ? " APST":"",
207                     (ctlr->caps2 & AHCI_CAP2_NVMP) ? " NVMP":"",
208                     (ctlr->caps2 & AHCI_CAP2_BOH) ? " BOH":"");
209         }
210         /* Attach all channels on this controller */
211         for (unit = 0; unit < ctlr->channels; unit++) {
212                 if ((ctlr->ichannels & (1 << unit)) == 0)
213                         continue;
214                 child = device_add_child(dev, "ahcich", -1);
215                 if (child == NULL)
216                         device_printf(dev, "failed to add channel device\n");
217                 else
218                         device_set_ivars(child, (void *)(intptr_t)unit);
219         }
220         bus_generic_attach(dev);
221         return 0;
222 }
223
224 static int
225 ahci_detach(device_t dev)
226 {
227         struct ahci_controller *ctlr = device_get_softc(dev);
228         device_t *children;
229         int nchildren, i;
230
231         /* Detach & delete all children */
232         if (!device_get_children(dev, &children, &nchildren)) {
233                 for (i = 0; i < nchildren; i++)
234                         device_delete_child(dev, children[i]);
235                 free(children, M_TEMP);
236         }
237         /* Free interrupts. */
238         for (i = 0; i < ctlr->numirqs; i++) {
239                 if (ctlr->irqs[i].r_irq) {
240                         bus_teardown_intr(dev, ctlr->irqs[i].r_irq,
241                             ctlr->irqs[i].handle);
242                         bus_release_resource(dev, SYS_RES_IRQ,
243                             ctlr->irqs[i].r_irq_rid, ctlr->irqs[i].r_irq);
244                 }
245         }
246         pci_release_msi(dev);
247         /* Free memory. */
248         rman_fini(&ctlr->sc_iomem);
249         if (ctlr->r_mem)
250                 bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
251         return (0);
252 }
253
254 static int
255 ahci_ctlr_reset(device_t dev)
256 {
257         struct ahci_controller *ctlr = device_get_softc(dev);
258         int timeout;
259
260         if (pci_read_config(dev, 0x00, 4) == 0x28298086 &&
261             (pci_read_config(dev, 0x92, 1) & 0xfe) == 0x04)
262                 pci_write_config(dev, 0x92, 0x01, 1);
263         /* Enable AHCI mode */
264         ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
265         /* Reset AHCI controller */
266         ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE|AHCI_GHC_HR);
267         for (timeout = 1000; timeout > 0; timeout--) {
268                 DELAY(1000);
269                 if ((ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_HR) == 0)
270                         break;
271         }
272         if (timeout == 0) {
273                 device_printf(dev, "AHCI controller reset failure\n");
274                 return ENXIO;
275         }
276         /* Reenable AHCI mode */
277         ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
278         /* Clear interrupts */
279         ATA_OUTL(ctlr->r_mem, AHCI_IS, ATA_INL(ctlr->r_mem, AHCI_IS));
280         /* Configure CCC */
281         if (ctlr->ccc) {
282                 ATA_OUTL(ctlr->r_mem, AHCI_CCCP, ATA_INL(ctlr->r_mem, AHCI_PI));
283                 ATA_OUTL(ctlr->r_mem, AHCI_CCCC,
284                     (ctlr->ccc << AHCI_CCCC_TV_SHIFT) |
285                     (4 << AHCI_CCCC_CC_SHIFT) |
286                     AHCI_CCCC_EN);
287                 ctlr->cccv = (ATA_INL(ctlr->r_mem, AHCI_CCCC) &
288                     AHCI_CCCC_INT_MASK) >> AHCI_CCCC_INT_SHIFT;
289                 if (bootverbose) {
290                         device_printf(dev,
291                             "CCC with %dms/4cmd enabled on vector %d\n",
292                             ctlr->ccc, ctlr->cccv);
293                 }
294         }
295         /* Enable AHCI interrupts */
296         ATA_OUTL(ctlr->r_mem, AHCI_GHC,
297             ATA_INL(ctlr->r_mem, AHCI_GHC) | AHCI_GHC_IE);
298         return (0);
299 }
300
301 static int
302 ahci_suspend(device_t dev)
303 {
304         struct ahci_controller *ctlr = device_get_softc(dev);
305
306         bus_generic_suspend(dev);
307         /* Disable interupts, so the state change(s) doesn't trigger */
308         ATA_OUTL(ctlr->r_mem, AHCI_GHC,
309              ATA_INL(ctlr->r_mem, AHCI_GHC) & (~AHCI_GHC_IE));
310         return 0;
311 }
312
313 static int
314 ahci_resume(device_t dev)
315 {
316         int res;
317
318         if ((res = ahci_ctlr_reset(dev)) != 0)
319                 return (res);
320         return (bus_generic_resume(dev));
321 }
322
323 static int
324 ahci_setup_interrupt(device_t dev)
325 {
326         struct ahci_controller *ctlr = device_get_softc(dev);
327         int i, msi = 1;
328
329         /* Process hints. */
330         resource_int_value(device_get_name(dev),
331             device_get_unit(dev), "msi", &msi);
332         if (msi < 0)
333                 msi = 0;
334         else if (msi == 1)
335                 msi = min(1, pci_msi_count(dev));
336         else if (msi > 1)
337                 msi = pci_msi_count(dev);
338         /* Allocate MSI if needed/present. */
339         if (msi && pci_alloc_msi(dev, &msi) == 0) {
340                 ctlr->numirqs = msi;
341         } else {
342                 msi = 0;
343                 ctlr->numirqs = 1;
344         }
345         /* Check for single MSI vector fallback. */
346         if (ctlr->numirqs > 1 &&
347             (ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_MRSM) != 0) {
348                 device_printf(dev, "Falling back to one MSI\n");
349                 ctlr->numirqs = 1;
350         }
351         /* Allocate all IRQs. */
352         for (i = 0; i < ctlr->numirqs; i++) {
353                 ctlr->irqs[i].ctlr = ctlr;
354                 ctlr->irqs[i].r_irq_rid = i + (msi ? 1 : 0);
355                 if (ctlr->numirqs == 1 || i >= ctlr->channels ||
356                     (ctlr->ccc && i == ctlr->cccv))
357                         ctlr->irqs[i].mode = AHCI_IRQ_MODE_ALL;
358                 else if (i == ctlr->numirqs - 1)
359                         ctlr->irqs[i].mode = AHCI_IRQ_MODE_AFTER;
360                 else
361                         ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
362                 if (!(ctlr->irqs[i].r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
363                     &ctlr->irqs[i].r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
364                         device_printf(dev, "unable to map interrupt\n");
365                         return ENXIO;
366                 }
367                 if ((bus_setup_intr(dev, ctlr->irqs[i].r_irq, ATA_INTR_FLAGS, NULL,
368                     (ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE) ? ahci_intr_one : ahci_intr,
369                     &ctlr->irqs[i], &ctlr->irqs[i].handle))) {
370                         /* SOS XXX release r_irq */
371                         device_printf(dev, "unable to setup interrupt\n");
372                         return ENXIO;
373                 }
374         }
375         return (0);
376 }
377
378 /*
379  * Common case interrupt handler.
380  */
381 static void
382 ahci_intr(void *data)
383 {
384         struct ahci_controller_irq *irq = data;
385         struct ahci_controller *ctlr = irq->ctlr;
386         u_int32_t is;
387         void *arg;
388         int unit;
389
390         if (irq->mode == AHCI_IRQ_MODE_ALL) {
391                 unit = 0;
392                 if (ctlr->ccc)
393                         is = ctlr->ichannels;
394                 else
395                         is = ATA_INL(ctlr->r_mem, AHCI_IS);
396         } else {        /* AHCI_IRQ_MODE_AFTER */
397                 unit = irq->r_irq_rid - 1;
398                 is = ATA_INL(ctlr->r_mem, AHCI_IS);
399         }
400         for (; unit < ctlr->channels; unit++) {
401                 if ((is & (1 << unit)) != 0 &&
402                     (arg = ctlr->interrupt[unit].argument)) {
403                         ctlr->interrupt[unit].function(arg);
404                         ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
405                 }
406         }
407 }
408
409 /*
410  * Simplified interrupt handler for multivector MSI mode.
411  */
412 static void
413 ahci_intr_one(void *data)
414 {
415         struct ahci_controller_irq *irq = data;
416         struct ahci_controller *ctlr = irq->ctlr;
417         void *arg;
418         int unit;
419
420         unit = irq->r_irq_rid - 1;
421         if ((arg = ctlr->interrupt[unit].argument))
422             ctlr->interrupt[unit].function(arg);
423 }
424
425 static struct resource *
426 ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
427                        u_long start, u_long end, u_long count, u_int flags)
428 {
429         struct ahci_controller *ctlr = device_get_softc(dev);
430         int unit = ((struct ahci_channel *)device_get_softc(child))->unit;
431         struct resource *res = NULL;
432         int offset = AHCI_OFFSET + (unit << 7);
433         long st;
434
435         switch (type) {
436         case SYS_RES_MEMORY:
437                 st = rman_get_start(ctlr->r_mem);
438                 res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
439                     st + offset + 127, 128, RF_ACTIVE, child);
440                 if (res) {
441                         bus_space_handle_t bsh;
442                         bus_space_tag_t bst;
443                         bsh = rman_get_bushandle(ctlr->r_mem);
444                         bst = rman_get_bustag(ctlr->r_mem);
445                         bus_space_subregion(bst, bsh, offset, 128, &bsh);
446                         rman_set_bushandle(res, bsh);
447                         rman_set_bustag(res, bst);
448                 }
449                 break;
450         case SYS_RES_IRQ:
451                 if (*rid == ATA_IRQ_RID)
452                         res = ctlr->irqs[0].r_irq;
453                 break;
454         }
455         return (res);
456 }
457
458 static int
459 ahci_release_resource(device_t dev, device_t child, int type, int rid,
460                          struct resource *r)
461 {
462
463         switch (type) {
464         case SYS_RES_MEMORY:
465                 rman_release_resource(r);
466                 return (0);
467         case SYS_RES_IRQ:
468                 if (rid != ATA_IRQ_RID)
469                         return ENOENT;
470                 return (0);
471         }
472         return (EINVAL);
473 }
474
475 static int
476 ahci_setup_intr(device_t dev, device_t child, struct resource *irq, 
477                    int flags, driver_filter_t *filter, driver_intr_t *function, 
478                    void *argument, void **cookiep)
479 {
480         struct ahci_controller *ctlr = device_get_softc(dev);
481         int unit = (intptr_t)device_get_ivars(child);
482
483         if (filter != NULL) {
484                 printf("ahci.c: we cannot use a filter here\n");
485                 return (EINVAL);
486         }
487         ctlr->interrupt[unit].function = function;
488         ctlr->interrupt[unit].argument = argument;
489         return (0);
490 }
491
492 static int
493 ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
494                       void *cookie)
495 {
496         struct ahci_controller *ctlr = device_get_softc(dev);
497         int unit = (intptr_t)device_get_ivars(child);
498
499         ctlr->interrupt[unit].function = NULL;
500         ctlr->interrupt[unit].argument = NULL;
501         return (0);
502 }
503
504 static int
505 ahci_print_child(device_t dev, device_t child)
506 {
507         int retval;
508
509         retval = bus_print_child_header(dev, child);
510         retval += printf(" at channel %d",
511             (int)(intptr_t)device_get_ivars(child));
512         retval += bus_print_child_footer(dev, child);
513
514         return (retval);
515 }
516
517 devclass_t ahci_devclass;
518 static device_method_t ahci_methods[] = {
519         DEVMETHOD(device_probe,     ahci_probe),
520         DEVMETHOD(device_attach,    ahci_attach),
521         DEVMETHOD(device_detach,    ahci_detach),
522         DEVMETHOD(device_suspend,   ahci_suspend),
523         DEVMETHOD(device_resume,    ahci_resume),
524         DEVMETHOD(bus_print_child,  ahci_print_child),
525         DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
526         DEVMETHOD(bus_release_resource,     ahci_release_resource),
527         DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
528         DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
529         { 0, 0 }
530 };
531 static driver_t ahci_driver = {
532         "ahci",
533         ahci_methods,
534         sizeof(struct ahci_controller)
535 };
536 DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
537 MODULE_VERSION(ahci, 1);
538 MODULE_DEPEND(ahci, cam, 1, 1, 1);
539
540 static int
541 ahci_ch_probe(device_t dev)
542 {
543
544         device_set_desc_copy(dev, "AHCI channel");
545         return (0);
546 }
547
548 static int
549 ahci_ch_attach(device_t dev)
550 {
551         struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
552         struct ahci_channel *ch = device_get_softc(dev);
553         struct cam_devq *devq;
554         int rid, error;
555
556         ch->dev = dev;
557         ch->unit = (intptr_t)device_get_ivars(dev);
558         ch->caps = ctlr->caps;
559         ch->caps2 = ctlr->caps2;
560         ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
561         mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
562         resource_int_value(device_get_name(dev),
563             device_get_unit(dev), "pm_level", &ch->pm_level);
564         if (ch->pm_level > 3)
565                 callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
566         /* Limit speed for my onboard JMicron external port.
567          * It is not eSATA really. */
568         if (pci_get_devid(ctlr->dev) == 0x2363197b &&
569             pci_get_subvendor(ctlr->dev) == 0x1043 &&
570             pci_get_subdevice(ctlr->dev) == 0x81e4 &&
571             ch->unit == 0)
572                 ch->sata_rev = 1;
573         resource_int_value(device_get_name(dev),
574             device_get_unit(dev), "sata_rev", &ch->sata_rev);
575         rid = ch->unit;
576         if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
577             &rid, RF_ACTIVE)))
578                 return (ENXIO);
579         ahci_dmainit(dev);
580         ahci_slotsalloc(dev);
581         ahci_ch_resume(dev);
582         mtx_lock(&ch->mtx);
583         rid = ATA_IRQ_RID;
584         if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
585             &rid, RF_SHAREABLE | RF_ACTIVE))) {
586                 bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
587                 device_printf(dev, "Unable to map interrupt\n");
588                 return (ENXIO);
589         }
590         if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
591             ahci_ch_intr_locked, dev, &ch->ih))) {
592                 device_printf(dev, "Unable to setup interrupt\n");
593                 error = ENXIO;
594                 goto err1;
595         }
596         /* Create the device queue for our SIM. */
597         devq = cam_simq_alloc(ch->numslots);
598         if (devq == NULL) {
599                 device_printf(dev, "Unable to allocate simq\n");
600                 error = ENOMEM;
601                 goto err1;
602         }
603         /* Construct SIM entry */
604         ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
605             device_get_unit(dev), &ch->mtx, ch->numslots, 0, devq);
606         if (ch->sim == NULL) {
607                 device_printf(dev, "unable to allocate sim\n");
608                 error = ENOMEM;
609                 goto err2;
610         }
611         if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
612                 device_printf(dev, "unable to register xpt bus\n");
613                 error = ENXIO;
614                 goto err2;
615         }
616         if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
617             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
618                 device_printf(dev, "unable to create path\n");
619                 error = ENXIO;
620                 goto err3;
621         }
622         if (ch->pm_level > 3) {
623                 callout_reset(&ch->pm_timer,
624                     (ch->pm_level == 4) ? hz / 1000 : hz / 8,
625                     ahci_ch_pm, dev);
626         }
627         mtx_unlock(&ch->mtx);
628         return (0);
629
630 err3:
631         xpt_bus_deregister(cam_sim_path(ch->sim));
632 err2:
633         cam_sim_free(ch->sim, /*free_devq*/TRUE);
634 err1:
635         bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
636         bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
637         mtx_unlock(&ch->mtx);
638         return (error);
639 }
640
641 static int
642 ahci_ch_detach(device_t dev)
643 {
644         struct ahci_channel *ch = device_get_softc(dev);
645
646         mtx_lock(&ch->mtx);
647         xpt_async(AC_LOST_DEVICE, ch->path, NULL);
648         xpt_free_path(ch->path);
649         xpt_bus_deregister(cam_sim_path(ch->sim));
650         cam_sim_free(ch->sim, /*free_devq*/TRUE);
651         mtx_unlock(&ch->mtx);
652
653         if (ch->pm_level > 3)
654                 callout_drain(&ch->pm_timer);
655         bus_teardown_intr(dev, ch->r_irq, ch->ih);
656         bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
657
658         ahci_ch_suspend(dev);
659         ahci_slotsfree(dev);
660         ahci_dmafini(dev);
661
662         bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
663         mtx_destroy(&ch->mtx);
664         return (0);
665 }
666
667 static int
668 ahci_ch_suspend(device_t dev)
669 {
670         struct ahci_channel *ch = device_get_softc(dev);
671
672         /* Disable port interrupts. */
673         ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
674         /* Reset command register. */
675         ahci_stop(dev);
676         ahci_stop_fr(dev);
677         ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
678         /* Allow everything, including partial and slumber modes. */
679         ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
680         /* Request slumber mode transition and give some time to get there. */
681         ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
682         DELAY(100);
683         /* Disable PHY. */
684         ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
685         return (0);
686 }
687
688 static int
689 ahci_ch_resume(device_t dev)
690 {
691         struct ahci_channel *ch = device_get_softc(dev);
692         uint64_t work;
693
694         /* Disable port interrupts */
695         ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
696         /* Setup work areas */
697         work = ch->dma.work_bus + AHCI_CL_OFFSET;
698         ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
699         ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
700         work = ch->dma.rfis_bus;
701         ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff); 
702         ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
703         /* Activate the channel and power/spin up device */
704         ATA_OUTL(ch->r_mem, AHCI_P_CMD,
705              (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
706              ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
707              ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
708         ahci_start_fr(dev);
709         ahci_start(dev);
710         return (0);
711 }
712
713 devclass_t ahcich_devclass;
714 static device_method_t ahcich_methods[] = {
715         DEVMETHOD(device_probe,     ahci_ch_probe),
716         DEVMETHOD(device_attach,    ahci_ch_attach),
717         DEVMETHOD(device_detach,    ahci_ch_detach),
718         DEVMETHOD(device_suspend,   ahci_ch_suspend),
719         DEVMETHOD(device_resume,    ahci_ch_resume),
720         { 0, 0 }
721 };
722 static driver_t ahcich_driver = {
723         "ahcich",
724         ahcich_methods,
725         sizeof(struct ahci_channel)
726 };
727 DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahci_devclass, 0, 0);
728
729 struct ahci_dc_cb_args {
730         bus_addr_t maddr;
731         int error;
732 };
733
734 static void
735 ahci_dmainit(device_t dev)
736 {
737         struct ahci_channel *ch = device_get_softc(dev);
738         struct ahci_dc_cb_args dcba;
739
740         if (ch->caps & AHCI_CAP_64BIT)
741                 ch->dma.max_address = BUS_SPACE_MAXADDR;
742         else
743                 ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
744         /* Command area. */
745         if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
746             ch->dma.max_address, BUS_SPACE_MAXADDR,
747             NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
748             0, NULL, NULL, &ch->dma.work_tag))
749                 goto error;
750         if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
751             &ch->dma.work_map))
752                 goto error;
753         if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
754             AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
755                 bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
756                 goto error;
757         }
758         ch->dma.work_bus = dcba.maddr;
759         /* FIS receive area. */
760         if (bus_dma_tag_create(bus_get_dma_tag(dev), 4096, 0,
761             ch->dma.max_address, BUS_SPACE_MAXADDR,
762             NULL, NULL, 4096, 1, 4096,
763             0, NULL, NULL, &ch->dma.rfis_tag))
764                 goto error;
765         if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
766             &ch->dma.rfis_map))
767                 goto error;
768         if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
769             4096, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
770                 bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
771                 goto error;
772         }
773         ch->dma.rfis_bus = dcba.maddr;
774         /* Data area. */
775         if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
776             ch->dma.max_address, BUS_SPACE_MAXADDR,
777             NULL, NULL,
778             AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
779             AHCI_SG_ENTRIES, AHCI_PRD_MAX,
780             0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
781                 goto error;
782         }
783         return;
784
785 error:
786         device_printf(dev, "WARNING - DMA initialization failed\n");
787         ahci_dmafini(dev);
788 }
789
790 static void
791 ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
792 {
793         struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
794
795         if (!(dcba->error = error))
796                 dcba->maddr = segs[0].ds_addr;
797 }
798
799 static void
800 ahci_dmafini(device_t dev)
801 {
802         struct ahci_channel *ch = device_get_softc(dev);
803
804         if (ch->dma.data_tag) {
805                 bus_dma_tag_destroy(ch->dma.data_tag);
806                 ch->dma.data_tag = NULL;
807         }
808         if (ch->dma.rfis_bus) {
809                 bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
810                 bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
811                 ch->dma.rfis_bus = 0;
812                 ch->dma.rfis_map = NULL;
813                 ch->dma.rfis = NULL;
814         }
815         if (ch->dma.work_bus) {
816                 bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
817                 bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
818                 ch->dma.work_bus = 0;
819                 ch->dma.work_map = NULL;
820                 ch->dma.work = NULL;
821         }
822         if (ch->dma.work_tag) {
823                 bus_dma_tag_destroy(ch->dma.work_tag);
824                 ch->dma.work_tag = NULL;
825         }
826 }
827
828 static void
829 ahci_slotsalloc(device_t dev)
830 {
831         struct ahci_channel *ch = device_get_softc(dev);
832         int i;
833
834         /* Alloc and setup command/dma slots */
835         bzero(ch->slot, sizeof(ch->slot));
836         for (i = 0; i < ch->numslots; i++) {
837                 struct ahci_slot *slot = &ch->slot[i];
838
839                 slot->dev = dev;
840                 slot->slot = i;
841                 slot->state = AHCI_SLOT_EMPTY;
842                 slot->ccb = NULL;
843                 callout_init_mtx(&slot->timeout, &ch->mtx, 0);
844
845                 if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
846                         device_printf(ch->dev, "FAILURE - create data_map\n");
847         }
848 }
849
850 static void
851 ahci_slotsfree(device_t dev)
852 {
853         struct ahci_channel *ch = device_get_softc(dev);
854         int i;
855
856         /* Free all dma slots */
857         for (i = 0; i < ch->numslots; i++) {
858                 struct ahci_slot *slot = &ch->slot[i];
859
860                 callout_drain(&slot->timeout);
861                 if (slot->dma.data_map) {
862                         bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
863                         slot->dma.data_map = NULL;
864                 }
865         }
866 }
867
868 static void
869 ahci_phy_check_events(device_t dev)
870 {
871         struct ahci_channel *ch = device_get_softc(dev);
872         u_int32_t error = ATA_INL(ch->r_mem, AHCI_P_SERR);
873
874         /* Clear error bits/interrupt */
875         ATA_OUTL(ch->r_mem, AHCI_P_SERR, error);
876         /* If we have a connection event, deal with it */
877         if ((error & ATA_SE_PHY_CHANGED) && (ch->pm_level == 0)) {
878                 u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
879                 if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
880                     ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
881                     ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
882                         if (bootverbose)
883                                 device_printf(dev, "CONNECT requested\n");
884                         ahci_reset(dev);
885                 } else {
886                         if (bootverbose)
887                                 device_printf(dev, "DISCONNECT requested\n");
888                         ch->devices = 0;
889                 }
890         }
891 }
892
893 static void
894 ahci_notify_events(device_t dev)
895 {
896         struct ahci_channel *ch = device_get_softc(dev);
897         struct cam_path *dpath;
898         u_int32_t status;
899         int i;
900
901         status = ATA_INL(ch->r_mem, AHCI_P_SNTF);
902         if (status == 0)
903                 return;
904         ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
905         if (bootverbose)
906                 device_printf(dev, "SNTF 0x%04x\n", status);
907         for (i = 0; i < 16; i++) {
908                 if ((status & (1 << i)) == 0)
909                         continue;
910                 if (xpt_create_path(&dpath, NULL,
911                     xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
912                         xpt_async(AC_SCSI_AEN, dpath, NULL);
913                         xpt_free_path(dpath);
914                 }
915         }
916 }
917
918 static void
919 ahci_ch_intr_locked(void *data)
920 {
921         device_t dev = (device_t)data;
922         struct ahci_channel *ch = device_get_softc(dev);
923
924         mtx_lock(&ch->mtx);
925         ahci_ch_intr(data);
926         mtx_unlock(&ch->mtx);
927 }
928
929 static void
930 ahci_ch_pm(void *arg)
931 {
932         device_t dev = (device_t)arg;
933         struct ahci_channel *ch = device_get_softc(dev);
934         uint32_t work;
935
936         if (ch->numrslots != 0)
937                 return;
938         work = ATA_INL(ch->r_mem, AHCI_P_CMD);
939         if (ch->pm_level == 4)
940                 work |= AHCI_P_CMD_PARTIAL;
941         else
942                 work |= AHCI_P_CMD_SLUMBER;
943         ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
944 }
945
946 static void
947 ahci_ch_intr(void *data)
948 {
949         device_t dev = (device_t)data;
950         struct ahci_channel *ch = device_get_softc(dev);
951         uint32_t istatus, cstatus, sstatus, ok, err;
952         enum ahci_err_type et;
953         int i, ccs, ncq_err = 0;
954
955         /* Read and clear interrupt statuses. */
956         istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
957         if (istatus == 0)
958                 return;
959         ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
960         /* Read command statuses. */
961         cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
962         sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
963         /* Process PHY events */
964         if (istatus & (AHCI_P_IX_PRC | AHCI_P_IX_PC))
965                 ahci_phy_check_events(dev);
966         /* Process command errors */
967         if (istatus & (AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF |
968                        AHCI_P_IX_TFE | AHCI_P_IX_OF)) {
969 //device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
970 //    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
971 //    ATA_INL(ch->r_mem, AHCI_P_SERR));
972                 ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
973                     >> AHCI_P_CMD_CCS_SHIFT;
974                 err = ch->rslots & (cstatus | sstatus);
975                 /* Kick controller into sane state */
976                 ahci_stop(dev);
977                 ahci_start(dev);
978         } else {
979                 ccs = 0;
980                 err = 0;
981         }
982         /* Complete all successfull commands. */
983         ok = ch->rslots & ~(cstatus | sstatus);
984         for (i = 0; i < ch->numslots; i++) {
985                 if ((ok >> i) & 1)
986                         ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
987         }
988         /* On error, complete the rest of commands with error statuses. */
989         if (err) {
990                 if (!ch->readlog)
991                         xpt_freeze_simq(ch->sim, ch->numrslots);
992                 if (ch->frozen) {
993                         union ccb *fccb = ch->frozen;
994                         ch->frozen = NULL;
995                         fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
996                         xpt_done(fccb);
997                 }
998                 for (i = 0; i < ch->numslots; i++) {
999                         /* XXX: reqests in loading state. */
1000                         if (((err >> i) & 1) == 0)
1001                                 continue;
1002                         if (istatus & AHCI_P_IX_TFE) {
1003                                 /* Task File Error */
1004                                 if (ch->numtslots == 0) {
1005                                         /* Untagged operation. */
1006                                         if (i == ccs)
1007                                                 et = AHCI_ERR_TFE;
1008                                         else
1009                                                 et = AHCI_ERR_INNOCENT;
1010                                 } else {
1011                                         /* Tagged operation. */
1012                                         et = AHCI_ERR_NCQ;
1013                                         ncq_err = 1;
1014                                 }
1015                         } else if (istatus & AHCI_P_IX_IF) {
1016                                 /* SATA error */
1017                                 et = AHCI_ERR_SATA;
1018                         } else
1019                                 et = AHCI_ERR_INVALID;
1020                         ahci_end_transaction(&ch->slot[i], et);
1021                 }
1022                 if (ncq_err)
1023                         ahci_issue_read_log(dev);
1024         }
1025         /* Process NOTIFY events */
1026         if ((istatus & AHCI_P_IX_SDB) && (ch->caps & AHCI_CAP_SSNTF))
1027                 ahci_notify_events(dev);
1028 }
1029
1030 /* Must be called with channel locked. */
1031 static int
1032 ahci_check_collision(device_t dev, union ccb *ccb)
1033 {
1034         struct ahci_channel *ch = device_get_softc(dev);
1035
1036         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1037             (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1038                 /* Tagged command while untagged are active. */
1039                 if (ch->numrslots != 0 && ch->numtslots == 0)
1040                         return (1);
1041                 /* Tagged command while tagged to other target is active. */
1042                 if (ch->numtslots != 0 &&
1043                     ch->taggedtarget != ccb->ccb_h.target_id)
1044                         return (1);
1045         } else {
1046                 /* Untagged command while tagged are active. */
1047                 if (ch->numrslots != 0 && ch->numtslots != 0)
1048                         return (1);
1049         }
1050         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1051             (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1052                 /* Atomic command while anything active. */
1053                 if (ch->numrslots != 0)
1054                         return (1);
1055         }
1056        /* We have some atomic command running. */
1057        if (ch->aslots != 0)
1058                return (1);
1059         return (0);
1060 }
1061
1062 /* Must be called with channel locked. */
1063 static void
1064 ahci_begin_transaction(device_t dev, union ccb *ccb)
1065 {
1066         struct ahci_channel *ch = device_get_softc(dev);
1067         struct ahci_slot *slot;
1068         int tag;
1069
1070         /* Choose empty slot. */
1071         tag = ch->lastslot;
1072         while (ch->slot[tag].state != AHCI_SLOT_EMPTY) {
1073                 if (++tag >= ch->numslots)
1074                         tag = 0;
1075                 KASSERT(tag != ch->lastslot, ("ahci: ALL SLOTS BUSY!"));
1076         }
1077         ch->lastslot = tag;
1078         /* Occupy chosen slot. */
1079         slot = &ch->slot[tag];
1080         slot->ccb = ccb;
1081         /* Stop PM timer. */
1082         if (ch->numrslots == 0 && ch->pm_level > 3)
1083                 callout_stop(&ch->pm_timer);
1084         /* Update channel stats. */
1085         ch->numrslots++;
1086         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1087             (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1088                 ch->numtslots++;
1089                 ch->taggedtarget = ccb->ccb_h.target_id;
1090         }
1091         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1092             (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1093                 ch->aslots |= (1 << slot->slot);
1094         slot->dma.nsegs = 0;
1095         /* If request moves data, setup and load SG list */
1096         if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1097                 void *buf;
1098                 bus_size_t size;
1099
1100                 slot->state = AHCI_SLOT_LOADING;
1101                 if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1102                         buf = ccb->ataio.data_ptr;
1103                         size = ccb->ataio.dxfer_len;
1104                 } else {
1105                         buf = ccb->csio.data_ptr;
1106                         size = ccb->csio.dxfer_len;
1107                 }
1108                 bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1109                     buf, size, ahci_dmasetprd, slot, 0);
1110         } else
1111                 ahci_execute_transaction(slot);
1112 }
1113
1114 /* Locked by busdma engine. */
1115 static void
1116 ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1117 {    
1118         struct ahci_slot *slot = arg;
1119         struct ahci_channel *ch = device_get_softc(slot->dev);
1120         struct ahci_cmd_tab *ctp;
1121         struct ahci_dma_prd *prd;
1122         int i;
1123
1124         if (error) {
1125                 device_printf(slot->dev, "DMA load error\n");
1126                 if (!ch->readlog)
1127                         xpt_freeze_simq(ch->sim, 1);
1128                 ahci_end_transaction(slot, AHCI_ERR_INVALID);
1129                 return;
1130         }
1131         KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1132         /* Get a piece of the workspace for this request */
1133         ctp = (struct ahci_cmd_tab *)
1134                 (ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1135         /* Fill S/G table */
1136         prd = &ctp->prd_tab[0];
1137         for (i = 0; i < nsegs; i++) {
1138                 prd[i].dba = htole64(segs[i].ds_addr);
1139                 prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1140         }
1141         slot->dma.nsegs = nsegs;
1142         bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1143             ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1144             BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1145         ahci_execute_transaction(slot);
1146 }
1147
1148 /* Must be called with channel locked. */
1149 static void
1150 ahci_execute_transaction(struct ahci_slot *slot)
1151 {
1152         device_t dev = slot->dev;
1153         struct ahci_channel *ch = device_get_softc(dev);
1154         struct ahci_cmd_tab *ctp;
1155         struct ahci_cmd_list *clp;
1156         union ccb *ccb = slot->ccb;
1157         int port = ccb->ccb_h.target_id & 0x0f;
1158         int fis_size;
1159
1160         /* Get a piece of the workspace for this request */
1161         ctp = (struct ahci_cmd_tab *)
1162                 (ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1163         /* Setup the FIS for this request */
1164         if (!(fis_size = ahci_setup_fis(ctp, ccb, slot->slot))) {
1165                 device_printf(ch->dev, "Setting up SATA FIS failed\n");
1166                 if (!ch->readlog)
1167                         xpt_freeze_simq(ch->sim, 1);
1168                 ahci_end_transaction(slot, AHCI_ERR_INVALID);
1169                 return;
1170         }
1171         /* Setup the command list entry */
1172         clp = (struct ahci_cmd_list *)
1173             (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1174         clp->prd_length = slot->dma.nsegs;
1175         clp->cmd_flags = (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1176                      (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1177                       (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1178                      (fis_size / sizeof(u_int32_t)) |
1179                      (port << 12);
1180         /* Special handling for Soft Reset command. */
1181         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1182             (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1183             (ccb->ataio.cmd.control & ATA_A_RESET)) {
1184                 /* Kick controller into sane state */
1185                 ahci_stop(dev);
1186                 ahci_clo(dev);
1187                 ahci_start(dev);
1188                 clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1189         }
1190         clp->bytecount = 0;
1191         clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1192                                   (AHCI_CT_SIZE * slot->slot));
1193         bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1194             BUS_DMASYNC_PREWRITE);
1195         bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1196             BUS_DMASYNC_PREREAD);
1197         /* Set ACTIVE bit for NCQ commands. */
1198         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1199             (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1200                 ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1201         }
1202         /* Issue command to the controller. */
1203         slot->state = AHCI_SLOT_RUNNING;
1204         ch->rslots |= (1 << slot->slot);
1205         ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1206         /* Device reset commands doesn't interrupt. Poll them. */
1207         if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1208             (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1209             (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1210                 int count, timeout = ccb->ccb_h.timeout;
1211                 enum ahci_err_type et = AHCI_ERR_NONE;
1212
1213                 for (count = 0; count < timeout; count++) {
1214                         DELAY(1000);
1215                         if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1216                                 break;
1217                         if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1218                                 device_printf(ch->dev,
1219                                     "Poll error on slot %d, TFD: %04x\n",
1220                                     slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1221                                 et = AHCI_ERR_TFE;
1222                                 break;
1223                         }
1224                 }
1225                 if (timeout && (count >= timeout)) {
1226                         device_printf(ch->dev,
1227                             "Poll timeout on slot %d\n", slot->slot);
1228                         et = AHCI_ERR_TIMEOUT;
1229                 }
1230                 if (et != AHCI_ERR_NONE) {
1231                         /* Kick controller into sane state */
1232                         ahci_stop(ch->dev);
1233                         ahci_start(ch->dev);
1234                         xpt_freeze_simq(ch->sim, 1);
1235                 }
1236                 ahci_end_transaction(slot, et);
1237                 return;
1238         }
1239         /* Start command execution timeout */
1240         callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 1000,
1241             (timeout_t*)ahci_timeout, slot);
1242         return;
1243 }
1244
1245 /* Locked by callout mechanism. */
1246 static void
1247 ahci_timeout(struct ahci_slot *slot)
1248 {
1249         device_t dev = slot->dev;
1250         struct ahci_channel *ch = device_get_softc(dev);
1251         int i;
1252
1253         /* Check for stale timeout. */
1254         if (slot->state != AHCI_SLOT_RUNNING)
1255                 return;
1256
1257         device_printf(dev, "Timeout on slot %d\n", slot->slot);
1258         /* Kick controller into sane state. */
1259         ahci_stop(ch->dev);
1260         ahci_start(ch->dev);
1261
1262         if (!ch->readlog)
1263                 xpt_freeze_simq(ch->sim, ch->numrslots);
1264         /* Handle command with timeout. */
1265         ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1266         /* Handle the rest of commands. */
1267         if (ch->frozen) {
1268                 union ccb *fccb = ch->frozen;
1269                 ch->frozen = NULL;
1270                 fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1271                 xpt_done(fccb);
1272         }
1273         for (i = 0; i < ch->numslots; i++) {
1274                 /* Do we have a running request on slot? */
1275                 if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1276                         continue;
1277                 ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1278         }
1279 }
1280
1281 /* Must be called with channel locked. */
1282 static void
1283 ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1284 {
1285         device_t dev = slot->dev;
1286         struct ahci_channel *ch = device_get_softc(dev);
1287         union ccb *ccb = slot->ccb;
1288
1289         bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1290             BUS_DMASYNC_POSTWRITE);
1291         /* Read result registers to the result struct
1292          * May be incorrect if several commands finished same time,
1293          * so read only when sure or have to.
1294          */
1295         if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1296                 struct ata_res *res = &ccb->ataio.res;
1297
1298                 if ((et == AHCI_ERR_TFE) ||
1299                     (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1300                         u_int8_t *fis = ch->dma.rfis + 0x40;
1301                         uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1302
1303                         bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1304                             BUS_DMASYNC_POSTREAD);
1305                         res->status = tfd;
1306                         res->error = tfd >> 8;
1307                         res->lba_low = fis[4];
1308                         res->lba_mid = fis[5];
1309                         res->lba_high = fis[6];
1310                         res->device = fis[7];
1311                         res->lba_low_exp = fis[8];
1312                         res->lba_mid_exp = fis[9];
1313                         res->lba_high_exp = fis[10];
1314                         res->sector_count = fis[12];
1315                         res->sector_count_exp = fis[13];
1316                 } else
1317                         bzero(res, sizeof(*res));
1318         }
1319         if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1320                 bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1321                     (ccb->ccb_h.flags & CAM_DIR_IN) ?
1322                     BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1323                 bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1324         }
1325         /* Set proper result status. */
1326         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1327         if (et != AHCI_ERR_NONE)
1328                 ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1329         switch (et) {
1330         case AHCI_ERR_NONE:
1331                 ccb->ccb_h.status |= CAM_REQ_CMP;
1332                 if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1333                         ccb->csio.scsi_status = SCSI_STATUS_OK;
1334                 break;
1335         case AHCI_ERR_INVALID:
1336                 ccb->ccb_h.status |= CAM_REQ_INVALID;
1337                 break;
1338         case AHCI_ERR_INNOCENT:
1339                 ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1340                 break;
1341         case AHCI_ERR_TFE:
1342                 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1343                         ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1344                         ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1345                 } else {
1346                         ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1347                 }
1348                 break;
1349         case AHCI_ERR_SATA:
1350                         ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1351                 break;
1352         case AHCI_ERR_TIMEOUT:
1353                 ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1354                 break;
1355         case AHCI_ERR_NCQ:
1356                 ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1357         default:
1358                 ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1359         }
1360         /* Free slot. */
1361         ch->rslots &= ~(1 << slot->slot);
1362         ch->aslots &= ~(1 << slot->slot);
1363         slot->state = AHCI_SLOT_EMPTY;
1364         slot->ccb = NULL;
1365         /* Update channel stats. */
1366         ch->numrslots--;
1367         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1368             (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1369                 ch->numtslots--;
1370         }
1371         /* If it was first request of reset sequence and there is no error,
1372          * proceed to second request. */
1373         if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1374             (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1375             (ccb->ataio.cmd.control & ATA_A_RESET) &&
1376             et == AHCI_ERR_NONE) {
1377                 ccb->ataio.cmd.control &= ~ATA_A_RESET;
1378                 ahci_begin_transaction(dev, ccb);
1379                 return;
1380         }
1381         /* If it was NCQ command error, put result on hold. */
1382         if (et == AHCI_ERR_NCQ) {
1383                 ch->hold[slot->slot] = ccb;
1384         } else if (ch->readlog) /* If it was our READ LOG command - process it. */
1385                 ahci_process_read_log(dev, ccb);
1386         else
1387                 xpt_done(ccb);
1388         /* Unfreeze frozen command. */
1389         if (ch->frozen && ch->numrslots == 0) {
1390                 union ccb *fccb = ch->frozen;
1391                 ch->frozen = NULL;
1392                 ahci_begin_transaction(dev, fccb);
1393                 xpt_release_simq(ch->sim, TRUE);
1394         }
1395         /* Start PM timer. */
1396         if (ch->numrslots == 0 && ch->pm_level > 3) {
1397                 callout_schedule(&ch->pm_timer,
1398                     (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1399         }
1400 }
1401
1402 static void
1403 ahci_issue_read_log(device_t dev)
1404 {
1405         struct ahci_channel *ch = device_get_softc(dev);
1406         union ccb *ccb;
1407         struct ccb_ataio *ataio;
1408         int i;
1409
1410         ch->readlog = 1;
1411         /* Find some holden command. */
1412         for (i = 0; i < ch->numslots; i++) {
1413                 if (ch->hold[i])
1414                         break;
1415         }
1416         ccb = xpt_alloc_ccb_nowait();
1417         if (ccb == NULL) {
1418                 device_printf(dev, "Unable allocate READ LOG command");
1419                 return; /* XXX */
1420         }
1421         ccb->ccb_h = ch->hold[i]->ccb_h;        /* Reuse old header. */
1422         ccb->ccb_h.func_code = XPT_ATA_IO;
1423         ccb->ccb_h.flags = CAM_DIR_IN;
1424         ccb->ccb_h.timeout = 1000;      /* 1s should be enough. */
1425         ataio = &ccb->ataio;
1426         ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1427         if (ataio->data_ptr == NULL) {
1428                 device_printf(dev, "Unable allocate memory for READ LOG command");
1429                 return; /* XXX */
1430         }
1431         ataio->dxfer_len = 512;
1432         bzero(&ataio->cmd, sizeof(ataio->cmd));
1433         ataio->cmd.flags = CAM_ATAIO_48BIT;
1434         ataio->cmd.command = 0x2F;      /* READ LOG EXT */
1435         ataio->cmd.sector_count = 1;
1436         ataio->cmd.sector_count_exp = 0;
1437         ataio->cmd.lba_low = 0x10;
1438         ataio->cmd.lba_mid = 0;
1439         ataio->cmd.lba_mid_exp = 0;
1440         
1441         ahci_begin_transaction(dev, ccb);
1442 }
1443
1444 static void
1445 ahci_process_read_log(device_t dev, union ccb *ccb)
1446 {
1447         struct ahci_channel *ch = device_get_softc(dev);
1448         uint8_t *data;
1449         struct ata_res *res;
1450         int i;
1451
1452         ch->readlog = 0;
1453
1454         data = ccb->ataio.data_ptr;
1455         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1456             (data[0] & 0x80) == 0) {
1457                 for (i = 0; i < ch->numslots; i++) {
1458                         if (!ch->hold[i])
1459                                 continue;
1460                         if ((data[0] & 0x1F) == i) {
1461                                 res = &ch->hold[i]->ataio.res;
1462                                 res->status = data[2];
1463                                 res->error = data[3];
1464                                 res->lba_low = data[4];
1465                                 res->lba_mid = data[5];
1466                                 res->lba_high = data[6];
1467                                 res->device = data[7];
1468                                 res->lba_low_exp = data[8];
1469                                 res->lba_mid_exp = data[9];
1470                                 res->lba_high_exp = data[10];
1471                                 res->sector_count = data[12];
1472                                 res->sector_count_exp = data[13];
1473                         } else {
1474                                 ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1475                                 ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1476                         }
1477                         xpt_done(ch->hold[i]);
1478                         ch->hold[i] = NULL;
1479                 }
1480         } else {
1481                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1482                         device_printf(dev, "Error while READ LOG EXT\n");
1483                 else if ((data[0] & 0x80) == 0) {
1484                         device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1485                 }
1486                 for (i = 0; i < ch->numslots; i++) {
1487                         if (!ch->hold[i])
1488                                 continue;
1489                         xpt_done(ch->hold[i]);
1490                         ch->hold[i] = NULL;
1491                 }
1492         }
1493         free(ccb->ataio.data_ptr, M_AHCI);
1494         xpt_free_ccb(ccb);
1495 }
1496
1497 static void
1498 ahci_start(device_t dev)
1499 {
1500         struct ahci_channel *ch = device_get_softc(dev);
1501         u_int32_t cmd;
1502
1503         /* Clear SATA error register */
1504         ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
1505         /* Clear any interrupts pending on this channel */
1506         ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
1507         /* Start operations on this channel */
1508         cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1509         ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
1510             (ch->pm_present ? AHCI_P_CMD_PMA : 0));
1511 }
1512
1513 static void
1514 ahci_stop(device_t dev)
1515 {
1516         struct ahci_channel *ch = device_get_softc(dev);
1517         u_int32_t cmd;
1518         int timeout;
1519
1520         /* Kill all activity on this channel */
1521         cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1522         ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
1523         /* Wait for activity stop. */
1524         timeout = 0;
1525         do {
1526                 DELAY(1000);
1527                 if (timeout++ > 1000) {
1528                         device_printf(dev, "stopping AHCI engine failed\n");
1529                         break;
1530                 }
1531         } while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
1532 }
1533
1534 static void
1535 ahci_clo(device_t dev)
1536 {
1537         struct ahci_channel *ch = device_get_softc(dev);
1538         u_int32_t cmd;
1539         int timeout;
1540
1541         /* Issue Command List Override if supported */ 
1542         if (ch->caps & AHCI_CAP_SCLO) {
1543                 cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1544                 cmd |= AHCI_P_CMD_CLO;
1545                 ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
1546                 timeout = 0;
1547                 do {
1548                         DELAY(1000);
1549                         if (timeout++ > 1000) {
1550                             device_printf(dev, "executing CLO failed\n");
1551                             break;
1552                         }
1553                 } while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
1554         }
1555 }
1556
1557 static void
1558 ahci_stop_fr(device_t dev)
1559 {
1560         struct ahci_channel *ch = device_get_softc(dev);
1561         u_int32_t cmd;
1562         int timeout;
1563
1564         /* Kill all FIS reception on this channel */
1565         cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1566         ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
1567         /* Wait for FIS reception stop. */
1568         timeout = 0;
1569         do {
1570                 DELAY(1000);
1571                 if (timeout++ > 1000) {
1572                         device_printf(dev, "stopping AHCI FR engine failed\n");
1573                         break;
1574                 }
1575         } while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
1576 }
1577
1578 static void
1579 ahci_start_fr(device_t dev)
1580 {
1581         struct ahci_channel *ch = device_get_softc(dev);
1582         u_int32_t cmd;
1583
1584         /* Start FIS reception on this channel */
1585         cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1586         ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
1587 }
1588
1589 static int
1590 ahci_wait_ready(device_t dev, int t)
1591 {
1592         struct ahci_channel *ch = device_get_softc(dev);
1593         int timeout = 0;
1594         uint32_t val;
1595
1596         while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
1597             (ATA_S_BUSY | ATA_S_DRQ)) {
1598                 DELAY(1000);
1599                 if (timeout++ > t) {
1600                         device_printf(dev, "port is not ready (timeout %dms) "
1601                             "tfd = %08x\n", t, val);
1602                         return (EBUSY);
1603                 }
1604         } 
1605         if (bootverbose)
1606                 device_printf(dev, "ready wait time=%dms\n", timeout);
1607         return (0);
1608 }
1609
1610 static void
1611 ahci_reset(device_t dev)
1612 {
1613         struct ahci_channel *ch = device_get_softc(dev);
1614         struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
1615         int i;
1616
1617         if (bootverbose)
1618                 device_printf(dev, "AHCI reset...\n");
1619         xpt_freeze_simq(ch->sim, ch->numrslots);
1620         /* Requeue freezed command. */
1621         if (ch->frozen) {
1622                 union ccb *fccb = ch->frozen;
1623                 ch->frozen = NULL;
1624                 fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1625                 xpt_done(fccb);
1626         }
1627         /* Kill the engine and requeue all running commands. */
1628         ahci_stop(dev);
1629         for (i = 0; i < ch->numslots; i++) {
1630                 /* Do we have a running request on slot? */
1631                 if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1632                         continue;
1633                 /* XXX; Commands in loading state. */
1634                 ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1635         }
1636         /* Disable port interrupts */
1637         ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1638         /* Reset and reconnect PHY, */
1639         if (!ahci_sata_phy_reset(dev, 0)) {
1640                 if (bootverbose)
1641                         device_printf(dev,
1642                             "AHCI reset done: phy reset found no device\n");
1643                 ch->devices = 0;
1644                 /* Enable wanted port interrupts */
1645                 ATA_OUTL(ch->r_mem, AHCI_P_IE,
1646                     (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
1647                 return;
1648         }
1649         /* Wait for clearing busy status. */
1650         if (ahci_wait_ready(dev, 10000)) {
1651                 device_printf(dev, "device ready timeout\n");
1652                 ahci_clo(dev);
1653         }
1654         ahci_start(dev);
1655         ch->devices = 1;
1656         /* Enable wanted port interrupts */
1657         ATA_OUTL(ch->r_mem, AHCI_P_IE,
1658              (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
1659               AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
1660               ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
1661               AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
1662               AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
1663         if (bootverbose)
1664                 device_printf(dev, "AHCI reset done: device found\n");
1665         /* Tell the XPT about the event */
1666         xpt_async(AC_BUS_RESET, ch->path, NULL);
1667 }
1668
1669 static int
1670 ahci_setup_fis(struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
1671 {
1672         u_int8_t *fis = &ctp->cfis[0];
1673
1674         bzero(ctp->cfis, 64);
1675         fis[0] = 0x27;                  /* host to device */
1676         fis[1] = (ccb->ccb_h.target_id & 0x0f);
1677         if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1678                 fis[1] |= 0x80;
1679                 fis[2] = ATA_PACKET_CMD;
1680                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
1681                         fis[3] = ATA_F_DMA;
1682                 else {
1683                         fis[5] = ccb->csio.dxfer_len;
1684                         fis[6] = ccb->csio.dxfer_len >> 8;
1685                 }
1686                 fis[7] = ATA_D_LBA;
1687                 fis[15] = ATA_A_4BIT;
1688                 bzero(ctp->acmd, 32);
1689                 bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1690                     ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
1691                     ctp->acmd, ccb->csio.cdb_len);
1692         } else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
1693                 fis[1] |= 0x80;
1694                 fis[2] = ccb->ataio.cmd.command;
1695                 fis[3] = ccb->ataio.cmd.features;
1696                 fis[4] = ccb->ataio.cmd.lba_low;
1697                 fis[5] = ccb->ataio.cmd.lba_mid;
1698                 fis[6] = ccb->ataio.cmd.lba_high;
1699                 fis[7] = ccb->ataio.cmd.device;
1700                 fis[8] = ccb->ataio.cmd.lba_low_exp;
1701                 fis[9] = ccb->ataio.cmd.lba_mid_exp;
1702                 fis[10] = ccb->ataio.cmd.lba_high_exp;
1703                 fis[11] = ccb->ataio.cmd.features_exp;
1704                 if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1705                         fis[12] = tag << 3;
1706                         fis[13] = 0;
1707                 } else {
1708                         fis[12] = ccb->ataio.cmd.sector_count;
1709                         fis[13] = ccb->ataio.cmd.sector_count_exp;
1710                 }
1711                 fis[15] = ATA_A_4BIT;
1712         } else {
1713                 fis[15] = ccb->ataio.cmd.control;
1714         }
1715         return (20);
1716 }
1717
1718 static int
1719 ahci_sata_connect(struct ahci_channel *ch)
1720 {
1721         u_int32_t status;
1722         int timeout;
1723
1724         /* Wait up to 100ms for "connect well" */
1725         for (timeout = 0; timeout < 100 ; timeout++) {
1726                 status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1727                 if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1728                     ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1729                     ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
1730                         break;
1731                 if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
1732                         if (bootverbose) {
1733                                 device_printf(ch->dev, "SATA offline status=%08x\n",
1734                                     status);
1735                         }
1736                         return (0);
1737                 }
1738                 DELAY(1000);
1739         }
1740         if (timeout >= 100) {
1741                 if (bootverbose) {
1742                         device_printf(ch->dev, "SATA connect timeout status=%08x\n",
1743                             status);
1744                 }
1745                 return (0);
1746         }
1747         if (bootverbose) {
1748                 device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
1749                     timeout, status);
1750         }
1751         /* Clear SATA error register */
1752         ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
1753         return (1);
1754 }
1755
1756 static int
1757 ahci_sata_phy_reset(device_t dev, int quick)
1758 {
1759         struct ahci_channel *ch = device_get_softc(dev);
1760         uint32_t val;
1761
1762         if (quick) {
1763                 val = ATA_INL(ch->r_mem, AHCI_P_SCTL);
1764                 if ((val & ATA_SC_DET_MASK) == ATA_SC_DET_IDLE)
1765                         return (ahci_sata_connect(ch));
1766         }
1767
1768         if (bootverbose)
1769                 device_printf(dev, "hardware reset ...\n");
1770         if (ch->sata_rev == 1)
1771                 val = ATA_SC_SPD_SPEED_GEN1;
1772         else if (ch->sata_rev == 2)
1773                 val = ATA_SC_SPD_SPEED_GEN2;
1774         else if (ch->sata_rev == 3)
1775                 val = ATA_SC_SPD_SPEED_GEN3;
1776         else
1777                 val = 0;
1778         ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
1779             ATA_SC_DET_RESET | val |
1780             ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
1781         DELAY(5000);
1782         ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
1783             ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
1784             (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
1785         DELAY(5000);
1786         return (ahci_sata_connect(ch));
1787 }
1788
1789 static void
1790 ahciaction(struct cam_sim *sim, union ccb *ccb)
1791 {
1792         device_t dev;
1793         struct ahci_channel *ch;
1794
1795         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
1796             ccb->ccb_h.func_code));
1797
1798         ch = (struct ahci_channel *)cam_sim_softc(sim);
1799         dev = ch->dev;
1800         switch (ccb->ccb_h.func_code) {
1801         /* Common cases first */
1802         case XPT_ATA_IO:        /* Execute the requested I/O operation */
1803         case XPT_SCSI_IO:
1804                 if (ch->devices == 0) {
1805                         ccb->ccb_h.status = CAM_SEL_TIMEOUT;
1806                         xpt_done(ccb);
1807                         break;
1808                 }
1809                 /* Check for command collision. */
1810                 if (ahci_check_collision(dev, ccb)) {
1811                         /* Freeze command. */
1812                         ch->frozen = ccb;
1813                         /* We have only one frozen slot, so freeze simq also. */
1814                         xpt_freeze_simq(ch->sim, 1);
1815                         return;
1816                 }
1817                 ahci_begin_transaction(dev, ccb);
1818                 break;
1819         case XPT_EN_LUN:                /* Enable LUN as a target */
1820         case XPT_TARGET_IO:             /* Execute target I/O request */
1821         case XPT_ACCEPT_TARGET_IO:      /* Accept Host Target Mode CDB */
1822         case XPT_CONT_TARGET_IO:        /* Continue Host Target I/O Connection*/
1823         case XPT_ABORT:                 /* Abort the specified CCB */
1824                 /* XXX Implement */
1825                 ccb->ccb_h.status = CAM_REQ_INVALID;
1826                 xpt_done(ccb);
1827                 break;
1828         case XPT_SET_TRAN_SETTINGS:
1829         {
1830                 struct  ccb_trans_settings *cts = &ccb->cts;
1831
1832                 if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM) {
1833                         ch->pm_present = cts->xport_specific.sata.pm_present;
1834                 }
1835                 ccb->ccb_h.status = CAM_REQ_CMP;
1836                 xpt_done(ccb);
1837                 break;
1838         }
1839         case XPT_GET_TRAN_SETTINGS:
1840         /* Get default/user set transfer settings for the target */
1841         {
1842                 struct  ccb_trans_settings *cts = &ccb->cts;
1843                 uint32_t status;
1844
1845                 cts->protocol = PROTO_ATA;
1846                 cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
1847                 cts->transport = XPORT_SATA;
1848                 cts->transport_version = XPORT_VERSION_UNSPECIFIED;
1849                 cts->proto_specific.valid = 0;
1850                 cts->xport_specific.sata.valid = 0;
1851                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1852                         status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
1853                 else
1854                         status = ATA_INL(ch->r_mem, AHCI_P_SCTL) & ATA_SC_SPD_MASK;
1855                 if (status & ATA_SS_SPD_GEN3) {
1856                         cts->xport_specific.sata.bitrate = 600000;
1857                         cts->xport_specific.sata.valid |= CTS_SATA_VALID_SPEED;
1858                 } else if (status & ATA_SS_SPD_GEN2) {
1859                         cts->xport_specific.sata.bitrate = 300000;
1860                         cts->xport_specific.sata.valid |= CTS_SATA_VALID_SPEED;
1861                 } else if (status & ATA_SS_SPD_GEN1) {
1862                         cts->xport_specific.sata.bitrate = 150000;
1863                         cts->xport_specific.sata.valid |= CTS_SATA_VALID_SPEED;
1864                 }
1865                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
1866                         cts->xport_specific.sata.pm_present =
1867                             (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_PMA) ?
1868                             1 : 0;
1869                 } else {
1870                         cts->xport_specific.sata.pm_present = ch->pm_present;
1871                 }
1872                 cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
1873                 ccb->ccb_h.status = CAM_REQ_CMP;
1874                 xpt_done(ccb);
1875                 break;
1876         }
1877 #if 0
1878         case XPT_CALC_GEOMETRY:
1879         {
1880                 struct    ccb_calc_geometry *ccg;
1881                 uint32_t size_mb;
1882                 uint32_t secs_per_cylinder;
1883
1884                 ccg = &ccb->ccg;
1885                 size_mb = ccg->volume_size
1886                         / ((1024L * 1024L) / ccg->block_size);
1887                 if (size_mb >= 1024 && (aha->extended_trans != 0)) {
1888                         if (size_mb >= 2048) {
1889                                 ccg->heads = 255;
1890                                 ccg->secs_per_track = 63;
1891                         } else {
1892                                 ccg->heads = 128;
1893                                 ccg->secs_per_track = 32;
1894                         }
1895                 } else {
1896                         ccg->heads = 64;
1897                         ccg->secs_per_track = 32;
1898                 }
1899                 secs_per_cylinder = ccg->heads * ccg->secs_per_track;
1900                 ccg->cylinders = ccg->volume_size / secs_per_cylinder;
1901                 ccb->ccb_h.status = CAM_REQ_CMP;
1902                 xpt_done(ccb);
1903                 break;
1904         }
1905 #endif
1906         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
1907         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
1908                 ahci_reset(dev);
1909                 ccb->ccb_h.status = CAM_REQ_CMP;
1910                 xpt_done(ccb);
1911                 break;
1912         case XPT_TERM_IO:               /* Terminate the I/O process */
1913                 /* XXX Implement */
1914                 ccb->ccb_h.status = CAM_REQ_INVALID;
1915                 xpt_done(ccb);
1916                 break;
1917         case XPT_PATH_INQ:              /* Path routing inquiry */
1918         {
1919                 struct ccb_pathinq *cpi = &ccb->cpi;
1920
1921                 cpi->version_num = 1; /* XXX??? */
1922                 cpi->hba_inquiry = PI_SDTR_ABLE | PI_TAG_ABLE;
1923                 if (ch->caps & AHCI_CAP_SPM)
1924                         cpi->hba_inquiry |= PI_SATAPM;
1925                 cpi->target_sprt = 0;
1926                 cpi->hba_misc = PIM_SEQSCAN;
1927                 cpi->hba_eng_cnt = 0;
1928                 if (ch->caps & AHCI_CAP_SPM)
1929                         cpi->max_target = 14;
1930                 else
1931                         cpi->max_target = 0;
1932                 cpi->max_lun = 0;
1933                 cpi->initiator_id = 0;
1934                 cpi->bus_id = cam_sim_bus(sim);
1935                 cpi->base_transfer_speed = 150000;
1936                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1937                 strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
1938                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1939                 cpi->unit_number = cam_sim_unit(sim);
1940                 cpi->transport = XPORT_SATA;
1941                 cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
1942                 cpi->protocol = PROTO_ATA;
1943                 cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
1944                 cpi->maxio = MAXPHYS;
1945                 /* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
1946                 if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
1947                         cpi->maxio = min(cpi->maxio, 128 * 512);
1948                 cpi->ccb_h.status = CAM_REQ_CMP;
1949                 xpt_done(ccb);
1950                 break;
1951         }
1952         default:
1953                 ccb->ccb_h.status = CAM_REQ_INVALID;
1954                 xpt_done(ccb);
1955                 break;
1956         }
1957 }
1958
1959 static void
1960 ahcipoll(struct cam_sim *sim)
1961 {
1962         struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
1963
1964         ahci_ch_intr(ch->dev);
1965 }