AHCI - Normalize console reporting of the port scan to make it easier to read.
[dragonfly.git] / sys / dev / disk / ahci / ahci.c
1 /*
2  * Copyright (c) 2006 David Gwynne <dlg@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  *
16  *
17  * Copyright (c) 2009 The DragonFly Project.  All rights reserved.
18  *
19  * This code is derived from software contributed to The DragonFly Project
20  * by Matthew Dillon <dillon@backplane.com>
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  *
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in
30  *    the documentation and/or other materials provided with the
31  *    distribution.
32  * 3. Neither the name of The DragonFly Project nor the names of its
33  *    contributors may be used to endorse or promote products derived
34  *    from this software without specific, prior written permission.
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
37  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
38  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
39  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
40  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
41  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
42  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
44  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  * $OpenBSD: ahci.c,v 1.147 2009/02/16 21:19:07 miod Exp $
50  */
51
52 #include "ahci.h"
53
54 int     ahci_port_start(struct ahci_port *, int);
55 int     ahci_port_stop(struct ahci_port *, int);
56 int     ahci_port_clo(struct ahci_port *);
57 int     ahci_port_softreset(struct ahci_port *);
58 int     ahci_port_portreset(struct ahci_port *);
59
60 int     ahci_load_prdt(struct ahci_ccb *);
61 void    ahci_unload_prdt(struct ahci_ccb *);
62 static void ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs,
63                                     int nsegs, int error);
64 int     ahci_poll(struct ahci_ccb *, int, void (*)(void *));
65 void    ahci_start(struct ahci_ccb *);
66
67 static void ahci_ata_cmd_timeout_unserialized(void *arg);
68 static void ahci_ata_cmd_timeout(void *arg);
69
70 void    ahci_issue_pending_ncq_commands(struct ahci_port *);
71 void    ahci_issue_pending_commands(struct ahci_port *, int);
72
73 u_int32_t       ahci_port_intr(struct ahci_port *, u_int32_t);
74
75 struct ahci_ccb *ahci_get_ccb(struct ahci_port *);
76 void    ahci_put_ccb(struct ahci_ccb *);
77
78 struct ahci_ccb *ahci_get_err_ccb(struct ahci_port *);
79 void    ahci_put_err_ccb(struct ahci_ccb *);
80
81 int     ahci_port_read_ncq_error(struct ahci_port *, int *);
82
83 struct ahci_dmamem *ahci_dmamem_alloc(struct ahci_softc *, bus_dma_tag_t tag);
84 void    ahci_dmamem_free(struct ahci_softc *, struct ahci_dmamem *);
85 static void ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error);
86
87 void    ahci_empty_done(struct ahci_ccb *ccb);
88 void    ahci_ata_cmd_done(struct ahci_ccb *ccb);
89
90 /* Wait for all bits in _b to be cleared */
91 #define ahci_pwait_clr(_ap, _r, _b) ahci_pwait_eq((_ap), (_r), (_b), 0)
92
93 /* Wait for all bits in _b to be set */
94 #define ahci_pwait_set(_ap, _r, _b) ahci_pwait_eq((_ap), (_r), (_b), (_b))
95
96 int
97 ahci_init(struct ahci_softc *sc)
98 {
99         u_int32_t       cap, pi;
100
101         DPRINTF(AHCI_D_VERBOSE, " GHC 0x%b",
102                 ahci_read(sc, AHCI_REG_GHC), AHCI_FMT_GHC);
103
104         /* save BIOS initialised parameters, enable staggered spin up */
105         cap = ahci_read(sc, AHCI_REG_CAP);
106         cap &= AHCI_REG_CAP_SMPS;
107         cap |= AHCI_REG_CAP_SSS;
108         pi = ahci_read(sc, AHCI_REG_PI);
109
110         if (AHCI_REG_GHC_AE & ahci_read(sc, AHCI_REG_GHC)) {
111                 /* reset the controller */
112                 ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_HR);
113                 if (ahci_wait_ne(sc, AHCI_REG_GHC, AHCI_REG_GHC_HR,
114                     AHCI_REG_GHC_HR) != 0) {
115                         device_printf(sc->sc_dev,
116                                       "unable to reset controller\n");
117                         return (1);
118                 }
119         }
120
121         /* enable ahci (global interrupts disabled) */
122         ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE);
123
124         /* restore parameters */
125         ahci_write(sc, AHCI_REG_CAP, cap);
126         ahci_write(sc, AHCI_REG_PI, pi);
127
128         return (0);
129 }
130
131 int
132 ahci_port_alloc(struct ahci_softc *sc, u_int port)
133 {
134         struct ahci_port                *ap;
135         struct ahci_ccb                 *ccb;
136         u_int64_t                       dva;
137         u_int32_t                       cmd;
138         struct ahci_cmd_hdr             *hdr;
139         struct ahci_cmd_table           *table;
140         int     rc = ENOMEM;
141         int     error;
142         int     i;
143
144         ap = kmalloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO);
145         if (ap == NULL) {
146                 device_printf(sc->sc_dev,
147                               "unable to allocate memory for port %d\n",
148                               port);
149                 goto reterr;
150         }
151
152         ksnprintf(ap->ap_name, sizeof(ap->ap_name), "%s%d.%d",
153                   device_get_name(sc->sc_dev),
154                   device_get_unit(sc->sc_dev),
155                   port);
156         sc->sc_ports[port] = ap;
157
158         if (bus_space_subregion(sc->sc_iot, sc->sc_ioh,
159             AHCI_PORT_REGION(port), AHCI_PORT_SIZE, &ap->ap_ioh) != 0) {
160                 device_printf(sc->sc_dev,
161                               "unable to create register window for port %d\n",
162                               port);
163                 goto freeport;
164         }
165
166         ap->ap_sc = sc;
167         ap->ap_num = port;
168         TAILQ_INIT(&ap->ap_ccb_free);
169         TAILQ_INIT(&ap->ap_ccb_pending);
170         lockinit(&ap->ap_ccb_lock, "ahcipo", 0, 0);
171
172         /* Disable port interrupts */
173         ahci_pwrite(ap, AHCI_PREG_IE, 0);
174
175         /* Sec 10.1.2 - deinitialise port if it is already running */
176         cmd = ahci_pread(ap, AHCI_PREG_CMD);
177         if ((cmd & (AHCI_PREG_CMD_ST | AHCI_PREG_CMD_CR |
178             AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_FR)) ||
179             (ahci_pread(ap, AHCI_PREG_SCTL) & AHCI_PREG_SCTL_DET)) {
180                 int r;
181
182                 r = ahci_port_stop(ap, 1);
183                 if (r) {
184                         device_printf(sc->sc_dev,
185                                   "unable to disable %s, ignoring port %d\n",
186                                   ((r == 2) ? "CR" : "FR"), port);
187                         rc = ENXIO;
188                         goto freeport;
189                 }
190
191                 /* Write DET to zero */
192                 ahci_pwrite(ap, AHCI_PREG_SCTL, 0);
193         }
194
195         /* Allocate RFIS */
196         ap->ap_dmamem_rfis = ahci_dmamem_alloc(sc, sc->sc_tag_rfis);
197         if (ap->ap_dmamem_rfis == NULL) {
198                 kprintf("NORFIS\n");
199                 goto nomem;
200         }
201
202         /* Setup RFIS base address */
203         ap->ap_rfis = (struct ahci_rfis *) AHCI_DMA_KVA(ap->ap_dmamem_rfis);
204         dva = AHCI_DMA_DVA(ap->ap_dmamem_rfis);
205         ahci_pwrite(ap, AHCI_PREG_FBU, (u_int32_t)(dva >> 32));
206         ahci_pwrite(ap, AHCI_PREG_FB, (u_int32_t)dva);
207
208         /* Enable FIS reception and activate port. */
209         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
210         cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD | AHCI_PREG_CMD_SUD;
211         ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_ICC_ACTIVE);
212
213         /* Check whether port activated.  Skip it if not. */
214         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
215         if ((cmd & AHCI_PREG_CMD_FRE) == 0) {
216                 kprintf("NOT-ACTIVATED\n");
217                 rc = ENXIO;
218                 goto freeport;
219         }
220
221         /* Allocate a CCB for each command slot */
222         ap->ap_ccbs = kmalloc(sizeof(struct ahci_ccb) * sc->sc_ncmds, M_DEVBUF,
223                               M_WAITOK | M_ZERO);
224         if (ap->ap_ccbs == NULL) {
225                 device_printf(sc->sc_dev,
226                               "unable to allocate command list for port %d\n",
227                               port);
228                 goto freeport;
229         }
230
231         /* Command List Structures and Command Tables */
232         ap->ap_dmamem_cmd_list = ahci_dmamem_alloc(sc, sc->sc_tag_cmdh);
233         ap->ap_dmamem_cmd_table = ahci_dmamem_alloc(sc, sc->sc_tag_cmdt);
234         if (ap->ap_dmamem_cmd_table == NULL ||
235             ap->ap_dmamem_cmd_list == NULL) {
236 nomem:
237                 device_printf(sc->sc_dev,
238                               "unable to allocate DMA memory for port %d\n",
239                               port);
240                 goto freeport;
241         }
242
243         /* Setup command list base address */
244         dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_list);
245         ahci_pwrite(ap, AHCI_PREG_CLBU, (u_int32_t)(dva >> 32));
246         ahci_pwrite(ap, AHCI_PREG_CLB, (u_int32_t)dva);
247
248         /* Split CCB allocation into CCBs and assign to command header/table */
249         hdr = AHCI_DMA_KVA(ap->ap_dmamem_cmd_list);
250         table = AHCI_DMA_KVA(ap->ap_dmamem_cmd_table);
251         for (i = 0; i < sc->sc_ncmds; i++) {
252                 ccb = &ap->ap_ccbs[i];
253
254                 error = bus_dmamap_create(sc->sc_tag_data, BUS_DMA_ALLOCNOW,
255                                           &ccb->ccb_dmamap);
256                 if (error) {
257                         device_printf(sc->sc_dev,
258                                       "unable to create dmamap for port %d "
259                                       "ccb %d\n", port, i);
260                         goto freeport;
261                 }
262
263                 callout_init(&ccb->ccb_timeout);
264                 ccb->ccb_slot = i;
265                 ccb->ccb_port = ap;
266                 ccb->ccb_cmd_hdr = &hdr[i];
267                 ccb->ccb_cmd_table = &table[i];
268                 dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_table) +
269                     ccb->ccb_slot * sizeof(struct ahci_cmd_table);
270                 ccb->ccb_cmd_hdr->ctba_hi = htole32((u_int32_t)(dva >> 32));
271                 ccb->ccb_cmd_hdr->ctba_lo = htole32((u_int32_t)dva);
272
273                 ccb->ccb_xa.fis =
274                     (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
275                 ccb->ccb_xa.packetcmd = ccb->ccb_cmd_table->acmd;
276                 ccb->ccb_xa.tag = i;
277
278                 ccb->ccb_xa.ata_put_xfer = ahci_ata_put_xfer;
279
280                 ccb->ccb_xa.state = ATA_S_COMPLETE;
281                 ahci_put_ccb(ccb);
282         }
283
284         /* Wait for ICC change to complete */
285         ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_ICC);
286
287         /* Reset port */
288         rc = ahci_port_portreset(ap);
289         switch (rc) {
290         case ENODEV:
291                 switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
292                 case AHCI_PREG_SSTS_DET_DEV_NE:
293                         kprintf("%s: Device not communicating\n", PORTNAME(ap));
294                         break;
295                 case AHCI_PREG_SSTS_DET_PHYOFFLINE:
296                         kprintf("%s: PHY offline\n", PORTNAME(ap));
297                         break;
298                 default:
299                         kprintf("%s: No device detected\n", PORTNAME(ap));
300                         break;
301                 }
302                 break;
303
304         case EBUSY:
305                 device_printf(sc->sc_dev,
306                               "device on port %d didn't come ready, "
307                               "TFD: 0x%b\n",
308                               port,
309                               ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
310
311                 /* Try a soft reset to clear busy */
312                 rc = ahci_port_softreset(ap);
313                 if (rc) {
314                         device_printf(sc->sc_dev,
315                                       "unable to communicate "
316                                       "with device on port %d\n",
317                                       port);
318                         goto freeport;
319                 }
320                 break;
321
322         default:
323                 break;
324         }
325
326         /*
327          * Enable command transfers on the port if a device was detected.
328          * Otherwise leave them disabled but leave the port structure
329          * intact so we get hot-plug interrupts.
330          */
331         if (rc == 0) {
332                 DPRINTF(AHCI_D_VERBOSE, "%s: detected device on port %d\n",
333                         device_get_name(sc->sc_dev), port);
334                 if (ahci_port_start(ap, 0)) {
335                         device_printf(sc->sc_dev,
336                                       "failed to start command DMA on port %d, "
337                                       "disabling\n", port);
338                         rc = ENXIO;     /* couldn't start port */
339                 }
340         }
341
342         /*
343          * A missing or busy device is not fatal for the purposes of
344          * port allocation.  We still want to detect hot-plug
345          * state changes.
346          */
347         if (rc == ENODEV || rc == EBUSY) {
348                 rc = 0;
349         }
350
351         /* Flush interrupts for port */
352         ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
353         ahci_write(sc, AHCI_REG_IS, 1 << port);
354
355         /* Enable port interrupts */
356         ahci_pwrite(ap, AHCI_PREG_IE,
357                         AHCI_PREG_IE_TFEE | AHCI_PREG_IE_HBFE |
358                         AHCI_PREG_IE_IFE | AHCI_PREG_IE_OFE |
359                         AHCI_PREG_IE_DPE | AHCI_PREG_IE_UFE |
360                         AHCI_PREG_IE_PCE | AHCI_PREG_IE_PRCE |
361 #ifdef AHCI_COALESCE
362             ((sc->sc_ccc_ports & (1 << port)) ?
363                         0 : (AHCI_PREG_IE_SDBE | AHCI_PREG_IE_DHRE))
364 #else
365                         AHCI_PREG_IE_SDBE | AHCI_PREG_IE_DHRE
366 #endif
367             );
368
369 freeport:
370         if (rc != 0)
371                 ahci_port_free(sc, port);
372 reterr:
373         return (rc);
374 }
375
376 void
377 ahci_port_free(struct ahci_softc *sc, u_int port)
378 {
379         struct ahci_port                *ap = sc->sc_ports[port];
380         struct ahci_ccb                 *ccb;
381
382         /* Ensure port is disabled and its interrupts are flushed */
383         if (ap->ap_sc) {
384                 ahci_pwrite(ap, AHCI_PREG_CMD, 0);
385                 ahci_pwrite(ap, AHCI_PREG_IE, 0);
386                 ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
387                 ahci_write(sc, AHCI_REG_IS, 1 << port);
388         }
389
390         if (ap->ap_ccbs) {
391                 while ((ccb = ahci_get_ccb(ap)) != NULL) {
392                         if (ccb->ccb_dmamap) {
393                                 bus_dmamap_destroy(sc->sc_tag_data,
394                                                    ccb->ccb_dmamap);
395                                 ccb->ccb_dmamap = NULL;
396                         }
397                 }
398                 kfree(ap->ap_ccbs, M_DEVBUF);
399                 ap->ap_ccbs = NULL;
400         }
401
402         if (ap->ap_dmamem_cmd_list) {
403                 ahci_dmamem_free(sc, ap->ap_dmamem_cmd_list);
404                 ap->ap_dmamem_cmd_list = NULL;
405         }
406         if (ap->ap_dmamem_rfis) {
407                 ahci_dmamem_free(sc, ap->ap_dmamem_rfis);
408                 ap->ap_dmamem_rfis = NULL;
409         }
410         if (ap->ap_dmamem_cmd_table) {
411                 ahci_dmamem_free(sc, ap->ap_dmamem_cmd_table);
412                 ap->ap_dmamem_cmd_table = NULL;
413         }
414
415         /* bus_space(9) says we dont free the subregions handle */
416
417         kfree(ap, M_DEVBUF);
418         sc->sc_ports[port] = NULL;
419 }
420
421 int
422 ahci_port_start(struct ahci_port *ap, int fre_only)
423 {
424         u_int32_t                       r;
425
426         /* Turn on FRE (and ST) */
427         r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
428         r |= AHCI_PREG_CMD_FRE;
429         if (!fre_only)
430                 r |= AHCI_PREG_CMD_ST;
431         ahci_pwrite(ap, AHCI_PREG_CMD, r);
432
433 #ifdef AHCI_COALESCE
434         /* (Re-)enable coalescing on the port. */
435         if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
436                 ap->ap_sc->sc_ccc_ports_cur |= (1 << ap->ap_num);
437                 ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
438                     ap->ap_sc->sc_ccc_ports_cur);
439         }
440 #endif
441
442         if (!(ap->ap_sc->sc_flags & AHCI_F_IGN_FR)) {
443                 /* Wait for FR to come on */
444                 if (ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR))
445                         return (2);
446         }
447
448         /* Wait for CR to come on */
449         if (!fre_only && ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CR))
450                 return (1);
451
452         return (0);
453 }
454
455 int
456 ahci_port_stop(struct ahci_port *ap, int stop_fis_rx)
457 {
458         u_int32_t                       r;
459
460 #ifdef AHCI_COALESCE
461         /* Disable coalescing on the port while it is stopped. */
462         if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
463                 ap->ap_sc->sc_ccc_ports_cur &= ~(1 << ap->ap_num);
464                 ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
465                     ap->ap_sc->sc_ccc_ports_cur);
466         }
467 #endif
468
469         /* Turn off ST (and FRE) */
470         r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
471         r &= ~AHCI_PREG_CMD_ST;
472         if (stop_fis_rx)
473                 r &= ~AHCI_PREG_CMD_FRE;
474         ahci_pwrite(ap, AHCI_PREG_CMD, r);
475
476         /* Wait for CR to go off */
477         if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CR))
478                 return (1);
479
480         /* Wait for FR to go off */
481         if (stop_fis_rx && ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR))
482                 return (2);
483
484         return (0);
485 }
486
487 /* AHCI command list override -> forcibly clear TFD.STS.{BSY,DRQ} */
488 int
489 ahci_port_clo(struct ahci_port *ap)
490 {
491         struct ahci_softc               *sc = ap->ap_sc;
492         u_int32_t                       cmd;
493
494         /* Only attempt CLO if supported by controller */
495         if ((ahci_read(sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO) == 0)
496                 return (1);
497
498         /* Issue CLO */
499         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
500 #ifdef DIAGNOSTIC
501         if (cmd & AHCI_PREG_CMD_ST) {
502                 kprintf("%s: CLO requested while port running\n",
503                         PORTNAME(ap));
504         }
505 #endif
506         ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_CLO);
507
508         /* Wait for completion */
509         if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CLO)) {
510                 kprintf("%s: CLO did not complete\n", PORTNAME(ap));
511                 return (1);
512         }
513
514         return (0);
515 }
516
517 /* AHCI soft reset, Section 10.4.1 */
518 int
519 ahci_port_softreset(struct ahci_port *ap)
520 {
521         struct ahci_ccb                 *ccb = NULL;
522         struct ahci_cmd_hdr             *cmd_slot;
523         u_int8_t                        *fis;
524         int                             rc = EIO;
525         u_int32_t                       cmd;
526
527         DPRINTF(AHCI_D_VERBOSE, "%s: soft reset\n", PORTNAME(ap));
528
529         crit_enter();
530
531         /* Save previous command register state */
532         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
533
534         /* Idle port */
535         if (ahci_port_stop(ap, 0)) {
536                 kprintf("%s: failed to stop port, cannot softreset\n",
537                         PORTNAME(ap));
538                 goto err;
539         }
540
541         /* Request CLO if device appears hung */
542         if (ahci_pread(ap, AHCI_PREG_TFD) &
543              (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
544                 ahci_port_clo(ap);
545         }
546
547         /* Clear port errors to permit TFD transfer */
548         ahci_pwrite(ap, AHCI_PREG_SERR, ahci_pread(ap, AHCI_PREG_SERR));
549
550         /* Restart port */
551         if (ahci_port_start(ap, 0)) {
552                 kprintf("%s: failed to start port, cannot softreset\n",
553                         PORTNAME(ap));
554                 goto err;
555         }
556
557         /* Check whether CLO worked */
558         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
559             AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
560                 kprintf("%s: CLO %s, need port reset\n",
561                         PORTNAME(ap),
562                         (ahci_read(ap->ap_sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO)
563                         ? "failed" : "unsupported");
564                 rc = EBUSY;
565                 goto err;
566         }
567
568         /* Prep first D2H command with SRST feature & clear busy/reset flags */
569         ccb = ahci_get_err_ccb(ap);
570         cmd_slot = ccb->ccb_cmd_hdr;
571         bzero(ccb->ccb_cmd_table, sizeof(struct ahci_cmd_table));
572
573         fis = ccb->ccb_cmd_table->cfis;
574         fis[0] = 0x27;  /* Host to device */
575         fis[15] = 0x04; /* SRST DEVCTL */
576
577         cmd_slot->prdtl = 0;
578         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
579         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_C); /* Clear busy on OK */
580         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_R); /* Reset */
581         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_W); /* Write */
582
583         ccb->ccb_xa.state = ATA_S_PENDING;
584         if (ahci_poll(ccb, hz, NULL) != 0)
585                 goto err;
586
587         /* Prep second D2H command to read status and complete reset sequence */
588         fis[0] = 0x27;  /* Host to device */
589         fis[15] = 0;
590
591         cmd_slot->prdtl = 0;
592         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
593         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_W);
594
595         ccb->ccb_xa.state = ATA_S_PENDING;
596         if (ahci_poll(ccb, hz, NULL) != 0)
597                 goto err;
598
599         if (ahci_pwait_clr(ap, AHCI_PREG_TFD, AHCI_PREG_TFD_STS_BSY |
600             AHCI_PREG_TFD_STS_DRQ | AHCI_PREG_TFD_STS_ERR)) {
601                 kprintf("%s: device didn't come ready after reset, TFD: 0x%b\n",
602                         PORTNAME(ap),
603                         ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
604                 rc = EBUSY;
605                 goto err;
606         }
607
608         rc = 0;
609 err:
610         if (ccb != NULL) {
611                 /* Abort our command, if it failed, by stopping command DMA. */
612                 if (rc != 0 && (ap->ap_active & (1 << ccb->ccb_slot))) {
613                         kprintf("%s: stopping the port, softreset slot "
614                                 "%d was still active.\n",
615                                 PORTNAME(ap),
616                                 ccb->ccb_slot);
617                         ahci_port_stop(ap, 0);
618                 }
619                 ccb->ccb_xa.state = ATA_S_ERROR;
620                 ahci_put_err_ccb(ccb);
621         }
622
623         /* Restore saved CMD register state */
624         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
625
626         crit_exit();
627
628         return (rc);
629 }
630
631 /* AHCI port reset, Section 10.4.2 */
632 int
633 ahci_port_portreset(struct ahci_port *ap)
634 {
635         u_int32_t                       cmd, r;
636         int                             rc;
637
638         DPRINTF(AHCI_D_VERBOSE, "%s: port reset\n", PORTNAME(ap));
639
640         /* Save previous command register state */
641         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
642
643         /* Clear ST, ignoring failure */
644         ahci_port_stop(ap, 0);
645
646         /* Perform device detection */
647         ap->ap_ata.ap_type = ATA_PORT_T_NONE;
648         ahci_pwrite(ap, AHCI_PREG_SCTL, 0);
649         DELAY(10000);
650         r = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_INIT;
651
652         if (AhciForceGen1 & (1 << ap->ap_num)) {
653                 kprintf("%s: Force 1.5Gbits\n", PORTNAME(ap));
654                 r |= AHCI_PREG_SCTL_SPD_GEN1;
655         } else {
656                 r |= AHCI_PREG_SCTL_SPD_ANY;
657         }
658         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
659         DELAY(10000);   /* wait at least 1ms for COMRESET to be sent */
660         r &= ~AHCI_PREG_SCTL_DET_INIT;
661         r |= AHCI_PREG_SCTL_DET_NONE;
662         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
663         DELAY(10000);
664
665         /* Wait for device to be detected and communications established */
666         if (ahci_pwait_eq(ap, AHCI_PREG_SSTS, AHCI_PREG_SSTS_DET,
667                           AHCI_PREG_SSTS_DET_DEV)) {
668                 rc = ENODEV;
669                 goto err;
670         }
671
672         /* Clear SERR (incl X bit), so TFD can update */
673         ahci_pwrite(ap, AHCI_PREG_SERR, ahci_pread(ap, AHCI_PREG_SERR));
674
675         /* Wait for device to become ready */
676         /* XXX maybe more than the default wait is appropriate here? */
677         if (ahci_pwait_clr(ap, AHCI_PREG_TFD, AHCI_PREG_TFD_STS_BSY |
678                                AHCI_PREG_TFD_STS_DRQ | AHCI_PREG_TFD_STS_ERR)) {
679                 rc = EBUSY;
680                 kprintf("%s: Device will not come ready 0x%b\n",
681                         PORTNAME(ap),
682                         ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
683                 goto err;
684         }
685
686         /*
687          * Figure out if we are a ATAPI or DISK device
688          */
689         u_int32_t sig;
690         sig = ahci_pread(ap, AHCI_PREG_SIG);
691         if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000)) {
692                 ap->ap_ata.ap_type = ATA_PORT_T_ATAPI;
693         } else {
694                 ap->ap_ata.ap_type = ATA_PORT_T_DISK;
695         }
696         rc = 0;
697 err:
698         /* Restore preserved port state */
699         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
700
701         return (rc);
702 }
703
704 int
705 ahci_load_prdt(struct ahci_ccb *ccb)
706 {
707         struct ahci_port                *ap = ccb->ccb_port;
708         struct ahci_softc               *sc = ap->ap_sc;
709         struct ata_xfer                 *xa = &ccb->ccb_xa;
710         struct ahci_prdt                *prdt = ccb->ccb_cmd_table->prdt;
711         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
712         struct ahci_cmd_hdr             *cmd_slot = ccb->ccb_cmd_hdr;
713         int                             error;
714
715         if (xa->datalen == 0) {
716                 ccb->ccb_cmd_hdr->prdtl = 0;
717                 return (0);
718         }
719
720         error = bus_dmamap_load(sc->sc_tag_data, dmap,
721                                 xa->data, xa->datalen,
722                                 ahci_load_prdt_callback,
723                                 &prdt,
724                                 ((xa->flags & ATA_F_NOWAIT) ?
725                                     BUS_DMA_NOWAIT : BUS_DMA_WAITOK));
726         if (error != 0) {
727                 kprintf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
728                 return (1);
729         }
730         if (xa->flags & ATA_F_PIO)
731                 prdt->flags |= htole32(AHCI_PRDT_FLAG_INTR);
732
733         cmd_slot->prdtl = htole16(prdt - ccb->ccb_cmd_table->prdt + 1);
734
735         bus_dmamap_sync(sc->sc_tag_data, dmap,
736                         (xa->flags & ATA_F_READ) ?
737                             BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
738
739         return (0);
740
741 #ifdef DIAGNOSTIC
742 diagerr:
743         bus_dmamap_unload(sc->sc_tag_data, dmap);
744         return (1);
745 #endif
746 }
747
748 /*
749  * Callback from BUSDMA system to load the segment list.  The passed segment
750  * list is a temporary structure.
751  */
752 static
753 void
754 ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs, int nsegs,
755                         int error)
756 {
757         struct ahci_prdt *prd = *(void **)info;
758         u_int64_t addr;
759
760         KKASSERT(nsegs <= AHCI_MAX_PRDT);
761
762         while (nsegs) {
763                 addr = segs->ds_addr;
764                 prd->dba_hi = htole32((u_int32_t)(addr >> 32));
765                 prd->dba_lo = htole32((u_int32_t)addr);
766 #ifdef DIAGNOSTIC
767                 KKASSERT((addr & 1) == 0);
768                 KKASSERT((segs->ds_len & 1) == 0);
769 #endif
770                 prd->flags = htole32(segs->ds_len - 1);
771                 --nsegs;
772                 if (nsegs)
773                         ++prd;
774                 ++segs;
775         }
776         *(void **)info = prd;   /* return last valid segment */
777 }
778
779 void
780 ahci_unload_prdt(struct ahci_ccb *ccb)
781 {
782         struct ahci_port                *ap = ccb->ccb_port;
783         struct ahci_softc               *sc = ap->ap_sc;
784         struct ata_xfer                 *xa = &ccb->ccb_xa;
785         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
786
787         if (xa->datalen != 0) {
788                 bus_dmamap_sync(sc->sc_tag_data, dmap,
789                                 (xa->flags & ATA_F_READ) ?
790                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
791
792                 bus_dmamap_unload(sc->sc_tag_data, dmap);
793
794                 if (ccb->ccb_xa.flags & ATA_F_NCQ)
795                         xa->resid = 0;
796                 else
797                         xa->resid = xa->datalen -
798                             le32toh(ccb->ccb_cmd_hdr->prdbc);
799         }
800 }
801
802 int
803 ahci_poll(struct ahci_ccb *ccb, int timeout, void (*timeout_fn)(void *))
804 {
805         struct ahci_port                *ap = ccb->ccb_port;
806
807         crit_enter();
808         ahci_start(ccb);
809         do {
810                 if (ahci_port_intr(ap, AHCI_PREG_CI_ALL_SLOTS) &
811                     (1 << ccb->ccb_slot)) {
812                         crit_exit();
813                         return (0);
814                 }
815                 DELAY(1000000 / hz);
816         } while (--timeout > 0);
817         kprintf("timeout ccb state %d\n", ccb->ccb_xa.state);
818
819         if (timeout_fn != NULL)
820                 timeout_fn(ccb);
821         crit_exit();
822
823         return (1);
824 }
825
826 void
827 ahci_start(struct ahci_ccb *ccb)
828 {
829         struct ahci_port                *ap = ccb->ccb_port;
830         struct ahci_softc               *sc = ap->ap_sc;
831
832         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
833
834         /* Zero transferred byte count before transfer */
835         ccb->ccb_cmd_hdr->prdbc = 0;
836
837         /* Sync command list entry and corresponding command table entry */
838         bus_dmamap_sync(sc->sc_tag_cmdh,
839                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
840                         BUS_DMASYNC_PREWRITE);
841         bus_dmamap_sync(sc->sc_tag_cmdt,
842                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
843                         BUS_DMASYNC_PREWRITE);
844
845         /* Prepare RFIS area for write by controller */
846         bus_dmamap_sync(sc->sc_tag_rfis,
847                         AHCI_DMA_MAP(ap->ap_dmamem_rfis),
848                         BUS_DMASYNC_PREREAD);
849
850         if (ccb->ccb_xa.flags & ATA_F_NCQ) {
851                 /* Issue NCQ commands only when there are no outstanding
852                  * standard commands. */
853                 if (ap->ap_active != 0 || !TAILQ_EMPTY(&ap->ap_ccb_pending))
854                         TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
855                 else {
856                         KKASSERT(ap->ap_active_cnt == 0);
857                         ap->ap_sactive |= (1 << ccb->ccb_slot);
858                         ccb->ccb_xa.state = ATA_S_ONCHIP;
859                         ahci_pwrite(ap, AHCI_PREG_SACT, 1 << ccb->ccb_slot);
860                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
861                 }
862         } else {
863                 /* Wait for all NCQ commands to finish before issuing standard
864                  * command. */
865                 if (ap->ap_sactive != 0 || ap->ap_active_cnt == 2)
866                         TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
867                 else if (ap->ap_active_cnt < 2) {
868                         ap->ap_active |= 1 << ccb->ccb_slot;
869                         ccb->ccb_xa.state = ATA_S_ONCHIP;
870                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
871                         ap->ap_active_cnt++;
872                 }
873         }
874 }
875
876 void
877 ahci_issue_pending_ncq_commands(struct ahci_port *ap)
878 {
879         struct ahci_ccb                 *nextccb;
880         u_int32_t                       sact_change = 0;
881
882         KKASSERT(ap->ap_active_cnt == 0);
883
884         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
885         if (nextccb == NULL || !(nextccb->ccb_xa.flags & ATA_F_NCQ))
886                 return;
887
888         /* Start all the NCQ commands at the head of the pending list. */
889         do {
890                 TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
891                 sact_change |= 1 << nextccb->ccb_slot;
892                 nextccb->ccb_xa.state = ATA_S_ONCHIP;
893                 nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
894         } while (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ));
895
896         ap->ap_sactive |= sact_change;
897         ahci_pwrite(ap, AHCI_PREG_SACT, sact_change);
898         ahci_pwrite(ap, AHCI_PREG_CI, sact_change);
899
900         return;
901 }
902
903 void
904 ahci_issue_pending_commands(struct ahci_port *ap, int last_was_ncq)
905 {
906         struct ahci_ccb                 *nextccb;
907
908         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
909         if (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ)) {
910                 KKASSERT(last_was_ncq == 0);    /* otherwise it should have
911                                                  * been started already. */
912
913                 /* Issue NCQ commands only when there are no outstanding
914                  * standard commands. */
915                 ap->ap_active_cnt--;
916                 if (ap->ap_active == 0)
917                         ahci_issue_pending_ncq_commands(ap);
918                 else
919                         KKASSERT(ap->ap_active_cnt == 1);
920         } else if (nextccb) {
921                 if (ap->ap_sactive != 0 || last_was_ncq)
922                         KKASSERT(ap->ap_active_cnt == 0);
923
924                 /* Wait for all NCQ commands to finish before issuing standard
925                  * command. */
926                 if (ap->ap_sactive != 0)
927                         return;
928
929                 /* Keep up to 2 standard commands on-chip at a time. */
930                 do {
931                         TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
932                         ap->ap_active |= 1 << nextccb->ccb_slot;
933                         nextccb->ccb_xa.state = ATA_S_ONCHIP;
934                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << nextccb->ccb_slot);
935                         if (last_was_ncq)
936                                 ap->ap_active_cnt++;
937                         if (ap->ap_active_cnt == 2)
938                                 break;
939                         KKASSERT(ap->ap_active_cnt == 1);
940                         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
941                 } while (nextccb && !(nextccb->ccb_xa.flags & ATA_F_NCQ));
942         } else if (!last_was_ncq) {
943                 KKASSERT(ap->ap_active_cnt == 1 || ap->ap_active_cnt == 2);
944
945                 /* Standard command finished, none waiting to start. */
946                 ap->ap_active_cnt--;
947         } else {
948                 KKASSERT(ap->ap_active_cnt == 0);
949
950                 /* NCQ command finished. */
951         }
952 }
953
954 void
955 ahci_intr(void *arg)
956 {
957         struct ahci_softc               *sc = arg;
958         u_int32_t                       is, ack = 0;
959         int                             port;
960
961         /* Read global interrupt status */
962         is = ahci_read(sc, AHCI_REG_IS);
963         if (is == 0 || is == 0xffffffff)
964                 return;
965         ack = is;
966
967 #ifdef AHCI_COALESCE
968         /* Check coalescing interrupt first */
969         if (is & sc->sc_ccc_mask) {
970                 DPRINTF(AHCI_D_INTR, "%s: command coalescing interrupt\n",
971                     DEVNAME(sc));
972                 is &= ~sc->sc_ccc_mask;
973                 is |= sc->sc_ccc_ports_cur;
974         }
975 #endif
976
977         /* Process interrupts for each port */
978         while (is) {
979                 port = ffs(is) - 1;
980                 if (sc->sc_ports[port]) {
981                         ahci_port_intr(sc->sc_ports[port],
982                                        AHCI_PREG_CI_ALL_SLOTS);
983                 }
984                 is &= ~(1 << port);
985         }
986
987         /* Finally, acknowledge global interrupt */
988         ahci_write(sc, AHCI_REG_IS, ack);
989 }
990
991 u_int32_t
992 ahci_port_intr(struct ahci_port *ap, u_int32_t ci_mask)
993 {
994         struct ahci_softc               *sc = ap->ap_sc;
995         u_int32_t                       is, ci_saved, ci_masked, processed = 0;
996         int                             slot, need_restart = 0;
997         struct ahci_ccb                 *ccb = NULL;
998         volatile u_int32_t              *active;
999 #ifdef DIAGNOSTIC
1000         u_int32_t                       tmp;
1001 #endif
1002
1003         is = ahci_pread(ap, AHCI_PREG_IS);
1004
1005         /* Ack port interrupt only if checking all command slots. */
1006         if (ci_mask == AHCI_PREG_CI_ALL_SLOTS)
1007                 ahci_pwrite(ap, AHCI_PREG_IS, is);
1008
1009         if (is)
1010                 DPRINTF(AHCI_D_INTR, "%s: interrupt: %b\n", PORTNAME(ap),
1011                         is, AHCI_PFMT_IS);
1012
1013         if (ap->ap_sactive) {
1014                 /* Active NCQ commands - use SActive instead of CI */
1015                 KKASSERT(ap->ap_active == 0);
1016                 KKASSERT(ap->ap_active_cnt == 0);
1017                 ci_saved = ahci_pread(ap, AHCI_PREG_SACT);
1018                 active = &ap->ap_sactive;
1019         } else {
1020                 /* Save CI */
1021                 ci_saved = ahci_pread(ap, AHCI_PREG_CI);
1022                 active = &ap->ap_active;
1023         }
1024
1025         /* Command failed.  See AHCI 1.1 spec 6.2.2.1 and 6.2.2.2. */
1026         if (is & AHCI_PREG_IS_TFES) {
1027                 u_int32_t               tfd, serr;
1028                 int                     err_slot;
1029
1030                 tfd = ahci_pread(ap, AHCI_PREG_TFD);
1031                 serr = ahci_pread(ap, AHCI_PREG_SERR);
1032
1033                 if (ap->ap_sactive == 0) {
1034                         /* Errored slot is easy to determine from CMD. */
1035                         err_slot = AHCI_PREG_CMD_CCS(ahci_pread(ap,
1036                             AHCI_PREG_CMD));
1037                         ccb = &ap->ap_ccbs[err_slot];
1038
1039                         /* Preserve received taskfile data from the RFIS. */
1040                         memcpy(&ccb->ccb_xa.rfis, ap->ap_rfis->rfis,
1041                             sizeof(struct ata_fis_d2h));
1042                 } else
1043                         err_slot = -1;  /* Must extract error from log page */
1044
1045                 DPRINTF(AHCI_D_VERBOSE, "%s: errored slot %d, TFD: %b, SERR:"
1046                     " %b, DIAG: %b\n", PORTNAME(ap), err_slot, tfd,
1047                     AHCI_PFMT_TFD_STS, AHCI_PREG_SERR_ERR(serr),
1048                     AHCI_PFMT_SERR_ERR, AHCI_PREG_SERR_DIAG(serr),
1049                     AHCI_PFMT_SERR_DIAG);
1050
1051                 /* Turn off ST to clear CI and SACT. */
1052                 ahci_port_stop(ap, 0);
1053                 need_restart = 1;
1054
1055                 /* Clear SERR to enable capturing new errors. */
1056                 ahci_pwrite(ap, AHCI_PREG_SERR, serr);
1057
1058                 /* Acknowledge the interrupts we can recover from. */
1059                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_TFES |
1060                     AHCI_PREG_IS_IFS);
1061                 is = ahci_pread(ap, AHCI_PREG_IS);
1062
1063                 /* If device hasn't cleared its busy status, try to idle it. */
1064                 if (tfd & (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1065                         kprintf("%s: attempting to idle device\n",
1066                                 PORTNAME(ap));
1067                         if (ahci_port_softreset(ap)) {
1068                                 kprintf("%s: failed to soft reset device\n",
1069                                         PORTNAME(ap));
1070                                 if (ahci_port_portreset(ap)) {
1071                                         kprintf("%s: failed to port reset "
1072                                                 "device, give up on it\n",
1073                                                 PORTNAME(ap));
1074                                         goto fatal;
1075                                 }
1076                         }
1077
1078                         /* Had to reset device, can't gather extended info. */
1079                 } else if (ap->ap_sactive) {
1080                         /* Recover the NCQ error from log page 10h. */
1081                         ahci_port_read_ncq_error(ap, &err_slot);
1082                         if (err_slot < 0)
1083                                 goto failall;
1084
1085                         DPRINTF(AHCI_D_VERBOSE, "%s: NCQ errored slot %d\n",
1086                                 PORTNAME(ap), err_slot);
1087
1088                         ccb = &ap->ap_ccbs[err_slot];
1089                 } else {
1090                         /* Didn't reset, could gather extended info from log. */
1091                 }
1092
1093                 /*
1094                  * If we couldn't determine the errored slot, reset the port
1095                  * and fail all the active slots.
1096                  */
1097                 if (err_slot == -1) {
1098                         if (ahci_port_softreset(ap) != 0 &&
1099                             ahci_port_portreset(ap) != 0) {
1100                                 kprintf("%s: couldn't reset after NCQ error, "
1101                                         "disabling device.\n",
1102                                         PORTNAME(ap));
1103                                 goto fatal;
1104                         }
1105                         kprintf("%s: couldn't recover NCQ error, failing "
1106                                 "all outstanding commands.\n",
1107                                 PORTNAME(ap));
1108                         goto failall;
1109                 }
1110
1111                 /* Clear the failed command in saved CI so completion runs. */
1112                 ci_saved &= ~(1 << err_slot);
1113
1114                 /* Note the error in the ata_xfer. */
1115                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
1116                 ccb->ccb_xa.state = ATA_S_ERROR;
1117
1118 #ifdef DIAGNOSTIC
1119                 /* There may only be one outstanding standard command now. */
1120                 if (ap->ap_sactive == 0) {
1121                         tmp = ci_saved;
1122                         if (tmp) {
1123                                 slot = ffs(tmp) - 1;
1124                                 tmp &= ~(1 << slot);
1125                                 KKASSERT(tmp == 0);
1126                         }
1127                 }
1128 #endif
1129         }
1130
1131         /*
1132          * Port change (hot-plug).
1133          *
1134          * A PCS interrupt will occur on hot-plug once communication is
1135          * established.
1136          *
1137          * A PRCS interrupt will occur on hot-unplug (and possibly also
1138          * on hot-plug).
1139          *
1140          * We can then check the CPS (Cold Presence State) bit to determine
1141          * if a device is plugged in or not and do the right thing.
1142          */
1143         if (is & (AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS)) {
1144                 ahci_pwrite(ap, AHCI_PREG_SERR,
1145                         (AHCI_PREG_SERR_DIAG_N | AHCI_PREG_SERR_DIAG_X) << 16);
1146                 switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
1147                 case AHCI_PREG_SSTS_DET_DEV:
1148                         if (ap->ap_ata.ap_type == ATA_PORT_T_NONE) {
1149                                 kprintf("%s: HOTPLUG - Device added\n",
1150                                         PORTNAME(ap));
1151                                 if (ahci_port_portreset(ap) == 0)
1152                                         ahci_cam_changed(ap);
1153                         }
1154                         break;
1155                 default:
1156                         if (ap->ap_ata.ap_type != ATA_PORT_T_NONE) {
1157                                 kprintf("%s: HOTPLUG - Device removed\n",
1158                                         PORTNAME(ap));
1159                                 ahci_port_portreset(ap);
1160                                 ahci_cam_changed(ap);
1161                         }
1162                         break;
1163                 }
1164         }
1165
1166         /* Check for remaining errors - they are fatal. */
1167         if (is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS | AHCI_PREG_IS_IFS |
1168                   AHCI_PREG_IS_OFS | AHCI_PREG_IS_UFS)) {
1169                 u_int32_t serr = ahci_pread(ap, AHCI_PREG_SERR);
1170                 kprintf("%s: unrecoverable errors (IS: %b, SERR: %b %b), "
1171                         "disabling port.\n",
1172                         PORTNAME(ap),
1173                         is, AHCI_PFMT_IS,
1174                         AHCI_PREG_SERR_ERR(serr), AHCI_PFMT_SERR_ERR,
1175                         AHCI_PREG_SERR_DIAG(serr), AHCI_PFMT_SERR_DIAG
1176                 );
1177                 /* XXX try recovery first */
1178                 goto fatal;
1179         }
1180
1181         /* Fail all outstanding commands if we know the port won't recover. */
1182         if (ap->ap_state == AP_S_FATAL_ERROR) {
1183 fatal:
1184                 ap->ap_state = AP_S_FATAL_ERROR;
1185 failall:
1186
1187                 /* Ensure port is shut down. */
1188                 ahci_port_stop(ap, 1);
1189
1190                 /* Error all the active slots. */
1191                 ci_masked = ci_saved & *active;
1192                 while (ci_masked) {
1193                         slot = ffs(ci_masked) - 1;
1194                         ccb = &ap->ap_ccbs[slot];
1195                         ci_masked &= ~(1 << slot);
1196                         ccb->ccb_xa.state = ATA_S_ERROR;
1197                 }
1198
1199                 /* Run completion for all active slots. */
1200                 ci_saved &= ~*active;
1201
1202                 /*
1203                  * Don't restart the port if our problems were deemed fatal.
1204                  *
1205                  * Also acknowlege all fatal interrupt sources to prevent
1206                  * a livelock.
1207                  */
1208                 if (ap->ap_state == AP_S_FATAL_ERROR) {
1209                         need_restart = 0;
1210                         ahci_pwrite(ap, AHCI_PREG_IS,
1211                                     AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
1212                                     AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS |
1213                                     AHCI_PREG_IS_UFS);
1214                 }
1215         }
1216
1217         /*
1218          * CCB completion is detected by noticing its slot's bit in CI has
1219          * changed to zero some time after we activated it.
1220          * If we are polling, we may only be interested in particular slot(s).
1221          */
1222         ci_masked = ~ci_saved & *active & ci_mask;
1223         while (ci_masked) {
1224                 slot = ffs(ci_masked) - 1;
1225                 ccb = &ap->ap_ccbs[slot];
1226                 ci_masked &= ~(1 << slot);
1227
1228                 DPRINTF(AHCI_D_INTR, "%s: slot %d is complete%s\n",
1229                     PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
1230                     " (error)" : "");
1231
1232                 bus_dmamap_sync(sc->sc_tag_cmdh,
1233                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
1234                                 BUS_DMASYNC_POSTWRITE);
1235
1236                 bus_dmamap_sync(sc->sc_tag_cmdt,
1237                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
1238                                 BUS_DMASYNC_POSTWRITE);
1239
1240                 bus_dmamap_sync(sc->sc_tag_rfis,
1241                                 AHCI_DMA_MAP(ap->ap_dmamem_rfis),
1242                                 BUS_DMASYNC_POSTREAD);
1243
1244                 *active &= ~(1 << ccb->ccb_slot);
1245                 ccb->ccb_done(ccb);
1246
1247                 processed |= 1 << ccb->ccb_slot;
1248         }
1249
1250         if (need_restart) {
1251                 /* Restart command DMA on the port */
1252                 ahci_port_start(ap, 0);
1253
1254                 /* Re-enable outstanding commands on port. */
1255                 if (ci_saved) {
1256 #ifdef DIAGNOSTIC
1257                         tmp = ci_saved;
1258                         while (tmp) {
1259                                 slot = ffs(tmp) - 1;
1260                                 tmp &= ~(1 << slot);
1261                                 ccb = &ap->ap_ccbs[slot];
1262                                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
1263                                 KKASSERT((!!(ccb->ccb_xa.flags & ATA_F_NCQ)) ==
1264                                     (!!ap->ap_sactive));
1265                         }
1266 #endif
1267                         DPRINTF(AHCI_D_VERBOSE, "%s: ahci_port_intr "
1268                             "re-enabling%s slots %08x\n", PORTNAME(ap),
1269                             ap->ap_sactive ? " NCQ" : "", ci_saved);
1270
1271                         if (ap->ap_sactive)
1272                                 ahci_pwrite(ap, AHCI_PREG_SACT, ci_saved);
1273                         ahci_pwrite(ap, AHCI_PREG_CI, ci_saved);
1274                 }
1275         }
1276
1277         return (processed);
1278 }
1279
1280 struct ahci_ccb *
1281 ahci_get_ccb(struct ahci_port *ap)
1282 {
1283         struct ahci_ccb                 *ccb;
1284
1285         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
1286         ccb = TAILQ_FIRST(&ap->ap_ccb_free);
1287         if (ccb != NULL) {
1288                 KKASSERT(ccb->ccb_xa.state == ATA_S_PUT);
1289                 TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
1290                 ccb->ccb_xa.state = ATA_S_SETUP;
1291         }
1292         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
1293
1294         return (ccb);
1295 }
1296
1297 void
1298 ahci_put_ccb(struct ahci_ccb *ccb)
1299 {
1300         struct ahci_port                *ap = ccb->ccb_port;
1301
1302 #ifdef DIAGNOSTIC
1303         if (ccb->ccb_xa.state != ATA_S_COMPLETE &&
1304             ccb->ccb_xa.state != ATA_S_TIMEOUT &&
1305             ccb->ccb_xa.state != ATA_S_ERROR) {
1306                 kprintf("%s: invalid ata_xfer state %02x in ahci_put_ccb, "
1307                         "slot %d\n",
1308                         PORTNAME(ccb->ccb_port), ccb->ccb_xa.state,
1309                         ccb->ccb_slot);
1310         }
1311 #endif
1312
1313         ccb->ccb_xa.state = ATA_S_PUT;
1314         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
1315         TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
1316         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
1317 }
1318
1319 struct ahci_ccb *
1320 ahci_get_err_ccb(struct ahci_port *ap)
1321 {
1322         struct ahci_ccb *err_ccb;
1323         u_int32_t sact;
1324
1325         /* No commands may be active on the chip. */
1326         sact = ahci_pread(ap, AHCI_PREG_SACT);
1327         if (sact != 0)
1328                 kprintf("ahci_get_err_ccb but SACT %08x != 0?\n", sact);
1329         KKASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
1330
1331 #ifdef DIAGNOSTIC
1332         KKASSERT(ap->ap_err_busy == 0);
1333         ap->ap_err_busy = 1;
1334 #endif
1335         /* Save outstanding command state. */
1336         ap->ap_err_saved_active = ap->ap_active;
1337         ap->ap_err_saved_active_cnt = ap->ap_active_cnt;
1338         ap->ap_err_saved_sactive = ap->ap_sactive;
1339
1340         /*
1341          * Pretend we have no commands outstanding, so that completions won't
1342          * run prematurely.
1343          */
1344         ap->ap_active = ap->ap_active_cnt = ap->ap_sactive = 0;
1345
1346         /*
1347          * Grab a CCB to use for error recovery.  This should never fail, as
1348          * we ask atascsi to reserve one for us at init time.
1349          */
1350         err_ccb = ahci_get_ccb(ap);
1351         KKASSERT(err_ccb != NULL);
1352         err_ccb->ccb_xa.flags = 0;
1353         err_ccb->ccb_done = ahci_empty_done;
1354
1355         return err_ccb;
1356 }
1357
1358 void
1359 ahci_put_err_ccb(struct ahci_ccb *ccb)
1360 {
1361         struct ahci_port *ap = ccb->ccb_port;
1362         u_int32_t sact;
1363
1364 #ifdef DIAGNOSTIC
1365         KKASSERT(ap->ap_err_busy);
1366 #endif
1367         /* No commands may be active on the chip */
1368         sact = ahci_pread(ap, AHCI_PREG_SACT);
1369         if (sact != 0) {
1370                 kprintf("ahci_port_err_ccb_restore but SACT %08x != 0?\n",
1371                         sact);
1372         }
1373         KKASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
1374
1375         /* Done with the CCB */
1376         ahci_put_ccb(ccb);
1377
1378         /* Restore outstanding command state */
1379         ap->ap_sactive = ap->ap_err_saved_sactive;
1380         ap->ap_active_cnt = ap->ap_err_saved_active_cnt;
1381         ap->ap_active = ap->ap_err_saved_active;
1382
1383 #ifdef DIAGNOSTIC
1384         ap->ap_err_busy = 0;
1385 #endif
1386 }
1387
1388 int
1389 ahci_port_read_ncq_error(struct ahci_port *ap, int *err_slotp)
1390 {
1391         struct ahci_ccb                 *ccb;
1392         struct ahci_cmd_hdr             *cmd_slot;
1393         u_int32_t                       cmd;
1394         struct ata_fis_h2d              *fis;
1395         int                             rc = EIO;
1396
1397         DPRINTF(AHCI_D_VERBOSE, "%s: read log page\n", PORTNAME(ap));
1398
1399         /* Save command register state. */
1400         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1401
1402         /* Port should have been idled already.  Start it. */
1403         KKASSERT((cmd & AHCI_PREG_CMD_CR) == 0);
1404         ahci_port_start(ap, 0);
1405
1406         /* Prep error CCB for READ LOG EXT, page 10h, 1 sector. */
1407         ccb = ahci_get_err_ccb(ap);
1408         ccb->ccb_xa.flags = ATA_F_NOWAIT | ATA_F_READ | ATA_F_POLL;
1409         ccb->ccb_xa.data = ap->ap_err_scratch;
1410         ccb->ccb_xa.datalen = 512;
1411         cmd_slot = ccb->ccb_cmd_hdr;
1412         bzero(ccb->ccb_cmd_table, sizeof(struct ahci_cmd_table));
1413
1414         fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
1415         fis->type = ATA_FIS_TYPE_H2D;
1416         fis->flags = ATA_H2D_FLAGS_CMD;
1417         fis->command = ATA_C_READ_LOG_EXT;
1418         fis->lba_low = 0x10;            /* queued error log page (10h) */
1419         fis->sector_count = 1;          /* number of sectors (1) */
1420         fis->sector_count_exp = 0;
1421         fis->lba_mid = 0;               /* starting offset */
1422         fis->lba_mid_exp = 0;
1423         fis->device = 0;
1424
1425         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
1426
1427         if (ahci_load_prdt(ccb) != 0) {
1428                 rc = ENOMEM;    /* XXX caller must abort all commands */
1429                 goto err;
1430         }
1431
1432         ccb->ccb_xa.state = ATA_S_PENDING;
1433         if (ahci_poll(ccb, hz, NULL) != 0)
1434                 goto err;
1435
1436         rc = 0;
1437 err:
1438         /* Abort our command, if it failed, by stopping command DMA. */
1439         if (rc != 0 && (ap->ap_active & (1 << ccb->ccb_slot))) {
1440                 kprintf("%s: log page read failed, slot %d was still active.\n",
1441                         PORTNAME(ap), ccb->ccb_slot);
1442                 ahci_port_stop(ap, 0);
1443         }
1444
1445         /* Done with the error CCB now. */
1446         ahci_unload_prdt(ccb);
1447         ahci_put_err_ccb(ccb);
1448
1449         /* Extract failed register set and tags from the scratch space. */
1450         if (rc == 0) {
1451                 struct ata_log_page_10h         *log;
1452                 int                             err_slot;
1453
1454                 log = (struct ata_log_page_10h *)ap->ap_err_scratch;
1455                 if (log->err_regs.type & ATA_LOG_10H_TYPE_NOTQUEUED) {
1456                         /* Not queued bit was set - wasn't an NCQ error? */
1457                         kprintf("%s: read NCQ error page, but not an NCQ "
1458                                 "error?\n",
1459                                 PORTNAME(ap));
1460                         rc = ESRCH;
1461                 } else {
1462                         /* Copy back the log record as a D2H register FIS. */
1463                         *err_slotp = err_slot = log->err_regs.type &
1464                             ATA_LOG_10H_TYPE_TAG_MASK;
1465
1466                         ccb = &ap->ap_ccbs[err_slot];
1467                         memcpy(&ccb->ccb_xa.rfis, &log->err_regs,
1468                             sizeof(struct ata_fis_d2h));
1469                         ccb->ccb_xa.rfis.type = ATA_FIS_TYPE_D2H;
1470                         ccb->ccb_xa.rfis.flags = 0;
1471                 }
1472         }
1473
1474         /* Restore saved CMD register state */
1475         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1476
1477         return (rc);
1478 }
1479
1480 /*
1481  * Allocate memory for various structures DMAd by hardware.  The maximum
1482  * number of segments for these tags is 1 so the DMA memory will have a
1483  * single physical base address.
1484  */
1485 struct ahci_dmamem *
1486 ahci_dmamem_alloc(struct ahci_softc *sc, bus_dma_tag_t tag)
1487 {
1488         struct ahci_dmamem *adm;
1489         int     error;
1490
1491         adm = kmalloc(sizeof(*adm), M_DEVBUF, M_INTWAIT | M_ZERO);
1492
1493         error = bus_dmamem_alloc(tag, (void **)&adm->adm_kva,
1494                                  BUS_DMA_ZERO, &adm->adm_map);
1495         if (error == 0) {
1496                 adm->adm_tag = tag;
1497                 error = bus_dmamap_load(tag, adm->adm_map,
1498                                         adm->adm_kva,
1499                                         bus_dma_tag_getmaxsize(tag),
1500                                         ahci_dmamem_saveseg, &adm->adm_busaddr,
1501                                         0);
1502         }
1503         if (error) {
1504                 if (adm->adm_map) {
1505                         bus_dmamap_destroy(tag, adm->adm_map);
1506                         adm->adm_map = NULL;
1507                         adm->adm_tag = NULL;
1508                         adm->adm_kva = NULL;
1509                 }
1510                 kfree(adm, M_DEVBUF);
1511                 adm = NULL;
1512         }
1513         return (adm);
1514 }
1515
1516 static
1517 void
1518 ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error)
1519 {
1520         KKASSERT(error == 0);
1521         KKASSERT(nsegs == 1);
1522         *(bus_addr_t *)info = segs->ds_addr;
1523 }
1524
1525
1526 void
1527 ahci_dmamem_free(struct ahci_softc *sc, struct ahci_dmamem *adm)
1528 {
1529         if (adm->adm_map) {
1530                 bus_dmamap_unload(adm->adm_tag, adm->adm_map);
1531                 bus_dmamap_destroy(adm->adm_tag, adm->adm_map);
1532                 adm->adm_map = NULL;
1533                 adm->adm_tag = NULL;
1534                 adm->adm_kva = NULL;
1535         }
1536         kfree(adm, M_DEVBUF);
1537 }
1538
1539 u_int32_t
1540 ahci_read(struct ahci_softc *sc, bus_size_t r)
1541 {
1542         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
1543                           BUS_SPACE_BARRIER_READ);
1544         return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
1545 }
1546
1547 void
1548 ahci_write(struct ahci_softc *sc, bus_size_t r, u_int32_t v)
1549 {
1550         bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
1551         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
1552                           BUS_SPACE_BARRIER_WRITE);
1553 }
1554
1555 int
1556 ahci_wait_ne(struct ahci_softc *sc, bus_size_t r, u_int32_t mask,
1557              u_int32_t target)
1558 {
1559         int                             i;
1560
1561         for (i = 0; i < 1000; i++) {
1562                 if ((ahci_read(sc, r) & mask) != target)
1563                         return (0);
1564                 DELAY(1000);
1565         }
1566
1567         return (1);
1568 }
1569
1570 u_int32_t
1571 ahci_pread(struct ahci_port *ap, bus_size_t r)
1572 {
1573         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
1574                           BUS_SPACE_BARRIER_READ);
1575         return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
1576 }
1577
1578 void
1579 ahci_pwrite(struct ahci_port *ap, bus_size_t r, u_int32_t v)
1580 {
1581         bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
1582         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
1583                           BUS_SPACE_BARRIER_WRITE);
1584 }
1585
1586 int
1587 ahci_pwait_eq(struct ahci_port *ap, bus_size_t r, u_int32_t mask,
1588     u_int32_t target)
1589 {
1590         int                             i;
1591
1592         for (i = 0; i < 1000; i++) {
1593                 if ((ahci_pread(ap, r) & mask) == target)
1594                         return (0);
1595                 DELAY(1000);
1596         }
1597
1598         return (1);
1599 }
1600
1601 struct ata_xfer *
1602 ahci_ata_get_xfer(struct ahci_port *ap)
1603 {
1604         /*struct ahci_softc     *sc = ap->ap_sc;*/
1605         struct ahci_ccb         *ccb;
1606
1607         ccb = ahci_get_ccb(ap);
1608         if (ccb == NULL) {
1609                 DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer: NULL ccb\n",
1610                     PORTNAME(ap));
1611                 return (NULL);
1612         }
1613
1614         DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer got slot %d\n",
1615             PORTNAME(ap), ccb->ccb_slot);
1616
1617         ccb->ccb_xa.fis->type = ATA_FIS_TYPE_H2D;
1618
1619         return (&ccb->ccb_xa);
1620 }
1621
1622 void
1623 ahci_ata_put_xfer(struct ata_xfer *xa)
1624 {
1625         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
1626
1627         DPRINTF(AHCI_D_XFER, "ahci_ata_put_xfer slot %d\n", ccb->ccb_slot);
1628
1629         ahci_put_ccb(ccb);
1630 }
1631
1632 int
1633 ahci_ata_cmd(struct ata_xfer *xa)
1634 {
1635         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
1636         struct ahci_cmd_hdr             *cmd_slot;
1637
1638         KKASSERT(xa->state == ATA_S_SETUP);
1639
1640 #if 0
1641         kprintf("ahci_ata_cmd xa->flags %08x type %08x cmd=%08x\n",
1642                 xa->flags,
1643                 xa->fis->type,
1644                 xa->fis->command);
1645 #endif
1646
1647         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
1648                 goto failcmd;
1649
1650         ccb->ccb_done = ahci_ata_cmd_done;
1651
1652         cmd_slot = ccb->ccb_cmd_hdr;
1653         cmd_slot->flags = htole16(5); /* FIS length (in DWORDs) */
1654
1655         if (xa->flags & ATA_F_WRITE)
1656                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_W);
1657
1658         if (xa->flags & ATA_F_PACKET)
1659                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_A);
1660
1661         if (ahci_load_prdt(ccb) != 0)
1662                 goto failcmd;
1663
1664         xa->state = ATA_S_PENDING;
1665
1666         if (xa->flags & ATA_F_POLL) {
1667                 ahci_poll(ccb, xa->timeout, ahci_ata_cmd_timeout);
1668                 return (ATA_COMPLETE);
1669         }
1670
1671         crit_enter();
1672         xa->flags |= ATA_F_TIMEOUT_RUNNING;
1673         callout_reset(&ccb->ccb_timeout, xa->timeout,
1674                       ahci_ata_cmd_timeout_unserialized, ccb);
1675         ahci_start(ccb);
1676         crit_exit();
1677         return (ATA_QUEUED);
1678
1679 failcmd:
1680         crit_enter();
1681         xa->state = ATA_S_ERROR;
1682         xa->complete(xa);
1683         crit_exit();
1684         return (ATA_ERROR);
1685 }
1686
1687 void
1688 ahci_ata_cmd_done(struct ahci_ccb *ccb)
1689 {
1690         struct ata_xfer                 *xa = &ccb->ccb_xa;
1691
1692         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
1693                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
1694                 callout_stop(&ccb->ccb_timeout);
1695         }
1696
1697         if (xa->state == ATA_S_ONCHIP || xa->state == ATA_S_ERROR)
1698                 ahci_issue_pending_commands(ccb->ccb_port,
1699                     xa->flags & ATA_F_NCQ);
1700
1701         ahci_unload_prdt(ccb);
1702
1703         if (xa->state == ATA_S_ONCHIP)
1704                 xa->state = ATA_S_COMPLETE;
1705 #ifdef DIAGNOSTIC
1706         else if (xa->state != ATA_S_ERROR && xa->state != ATA_S_TIMEOUT)
1707                 kprintf("%s: invalid ata_xfer state %02x in ahci_ata_cmd_done, "
1708                         "slot %d\n",
1709                         PORTNAME(ccb->ccb_port), xa->state, ccb->ccb_slot);
1710 #endif
1711         if (xa->state != ATA_S_TIMEOUT)
1712                 xa->complete(xa);
1713 }
1714
1715 static void
1716 ahci_ata_cmd_timeout_unserialized(void *arg)
1717 {
1718         struct ahci_ccb         *ccb = arg;
1719         struct ahci_port        *ap = ccb->ccb_port;
1720
1721         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
1722         ahci_ata_cmd_timeout(arg);
1723         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
1724 }
1725
1726 static void
1727 ahci_ata_cmd_timeout(void *arg)
1728 {
1729         struct ahci_ccb         *ccb = arg;
1730         struct ata_xfer         *xa = &ccb->ccb_xa;
1731         struct ahci_port        *ap = ccb->ccb_port;
1732         volatile u_int32_t      *active;
1733         int                     ccb_was_started, ncq_cmd;
1734
1735         crit_enter();
1736         kprintf("CMD TIMEOUT port-cmd-reg 0x%b\n"
1737                 "\tactive=%08x sactive=%08x\n"
1738                 "\t  sact=%08x      ci=%08x\n",
1739                 ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD,
1740                 ap->ap_active, ap->ap_sactive,
1741                 ahci_pread(ap, AHCI_PREG_SACT),
1742                 ahci_pread(ap, AHCI_PREG_CI));
1743
1744         KKASSERT(xa->flags & ATA_F_TIMEOUT_RUNNING);
1745         xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
1746         ncq_cmd = (xa->flags & ATA_F_NCQ);
1747         active = ncq_cmd ? &ap->ap_sactive : &ap->ap_active;
1748
1749         if (ccb->ccb_xa.state == ATA_S_PENDING) {
1750                 DPRINTF(AHCI_D_TIMEOUT, "%s: command for slot %d timed out "
1751                     "before it got on chip\n", PORTNAME(ap), ccb->ccb_slot);
1752                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1753                 ccb_was_started = 0;
1754         } else if (ccb->ccb_xa.state == ATA_S_ONCHIP && ahci_port_intr(ap,
1755             1 << ccb->ccb_slot)) {
1756                 DPRINTF(AHCI_D_TIMEOUT, "%s: final poll of port completed "
1757                     "command in slot %d\n", PORTNAME(ap), ccb->ccb_slot);
1758                 goto ret;
1759         } else if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
1760                 DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d already "
1761                     "handled%s\n", PORTNAME(ap), ccb->ccb_slot,
1762                     (*active & (1 << ccb->ccb_slot)) ?
1763                     " but slot is still active?" : ".");
1764                 goto ret;
1765         } else if ((ahci_pread(ap, ncq_cmd ? AHCI_PREG_SACT : AHCI_PREG_CI) &
1766                     (1 << ccb->ccb_slot)) == 0 &&
1767                    (*active & (1 << ccb->ccb_slot))) {
1768                 DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d completed but "
1769                     "IRQ handler didn't detect it.  Why?\n", PORTNAME(ap),
1770                     ccb->ccb_slot);
1771                 *active &= ~(1 << ccb->ccb_slot);
1772                 ccb->ccb_done(ccb);
1773                 goto ret;
1774         } else {
1775                 ccb_was_started = 1;
1776         }
1777
1778         /* Complete the slot with a timeout error. */
1779         ccb->ccb_xa.state = ATA_S_TIMEOUT;
1780         *active &= ~(1 << ccb->ccb_slot);
1781         DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (1)\n", PORTNAME(ap));
1782         ccb->ccb_done(ccb);     /* This won't issue pending commands or run the
1783                                    atascsi completion. */
1784
1785         /* Reset port to abort running command. */
1786         if (ccb_was_started) {
1787                 DPRINTF(AHCI_D_TIMEOUT, "%s: resetting port to abort%s command "
1788                     "in slot %d, active %08x\n", PORTNAME(ap), ncq_cmd ? " NCQ"
1789                     : "", ccb->ccb_slot, *active);
1790                 if (ahci_port_softreset(ap) != 0 && ahci_port_portreset(ap)
1791                     != 0) {
1792                         kprintf("%s: failed to reset port during timeout "
1793                                 "handling, disabling it\n",
1794                                 PORTNAME(ap));
1795                         ap->ap_state = AP_S_FATAL_ERROR;
1796                 }
1797
1798                 /* Restart any other commands that were aborted by the reset. */
1799                 if (*active) {
1800                         DPRINTF(AHCI_D_TIMEOUT, "%s: re-enabling%s slots "
1801                             "%08x\n", PORTNAME(ap), ncq_cmd ? " NCQ" : "",
1802                             *active);
1803                         if (ncq_cmd)
1804                                 ahci_pwrite(ap, AHCI_PREG_SACT, *active);
1805                         ahci_pwrite(ap, AHCI_PREG_CI, *active);
1806                 }
1807         }
1808
1809         /* Issue any pending commands now. */
1810         DPRINTF(AHCI_D_TIMEOUT, "%s: issue pending\n", PORTNAME(ap));
1811         if (ccb_was_started)
1812                 ahci_issue_pending_commands(ap, ncq_cmd);
1813         else if (ap->ap_active == 0)
1814                 ahci_issue_pending_ncq_commands(ap);
1815
1816         /* Complete the timed out ata_xfer I/O (may generate new I/O). */
1817         DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (2)\n", PORTNAME(ap));
1818         xa->complete(xa);
1819
1820         DPRINTF(AHCI_D_TIMEOUT, "%s: splx\n", PORTNAME(ap));
1821 ret:
1822         crit_exit();
1823 }
1824
1825 void
1826 ahci_empty_done(struct ahci_ccb *ccb)
1827 {
1828         ccb->ccb_xa.state = ATA_S_COMPLETE;
1829 }