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