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