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