AHCI - Improve hot-plug sequencing.
[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 1/10 of a second before sending the second
722          * FIS.
723          *
724          * It is unclear which other fields in the FIS are used.  Just zero
725          * everything.
726          */
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 err:
771         if (ccb != NULL) {
772                 /* Abort our command, if it failed, by stopping command DMA. */
773 #if 0
774                 kprintf("rc=%d active=%08x sactive=%08x slot=%d\n",
775                         rc, ap->ap_active, ap->ap_sactive, ccb->ccb_slot);
776 #endif
777                 if (rc != 0 && (ap->ap_active & (1 << ccb->ccb_slot))) {
778                         kprintf("%s: stopping the port, softreset slot "
779                                 "%d was still active.\n",
780                                 PORTNAME(ap),
781                                 ccb->ccb_slot);
782                         ahci_port_stop(ap, 0);
783                 }
784                 ccb->ccb_xa.state = ATA_S_ERROR;
785                 ahci_put_err_ccb(ccb);
786         }
787
788         /* Restore saved CMD register state */
789         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
790
791         crit_exit();
792
793         return (rc);
794 }
795
796 /*
797  * AHCI port reset, Section 10.4.2
798  *
799  * This function does a hard reset of the port.  Note that the device
800  * connected to the port could still end-up hung.
801  */
802 int
803 ahci_port_hardreset(struct ahci_port *ap)
804 {
805         u_int32_t                       cmd, r;
806         int                             rc;
807
808         DPRINTF(AHCI_D_VERBOSE, "%s: port reset\n", PORTNAME(ap));
809
810         /* Save previous command register state */
811         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
812
813         /* Clear ST, ignoring failure */
814         ahci_port_stop(ap, 0);
815
816         /* Perform device detection */
817         ap->ap_ata.ap_type = ATA_PORT_T_NONE;
818         ahci_pwrite(ap, AHCI_PREG_SCTL, 0);
819         DELAY(10000);
820         r = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_INIT;
821
822         if (AhciForceGen1 & (1 << ap->ap_num)) {
823                 kprintf("%s: Force 1.5Gbits\n", PORTNAME(ap));
824                 r |= AHCI_PREG_SCTL_SPD_GEN1;
825         } else {
826                 r |= AHCI_PREG_SCTL_SPD_ANY;
827         }
828         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
829         DELAY(10000);   /* wait at least 1ms for COMRESET to be sent */
830         r &= ~AHCI_PREG_SCTL_DET_INIT;
831         r |= AHCI_PREG_SCTL_DET_NONE;
832         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
833         DELAY(10000);
834
835         /* Wait for device to be detected and communications established */
836         if (ahci_pwait_eq(ap, 1000,
837                           AHCI_PREG_SSTS, AHCI_PREG_SSTS_DET,
838                           AHCI_PREG_SSTS_DET_DEV)) {
839                 rc = ENODEV;
840                 goto err;
841         }
842
843         /* Clear SERR (incl X bit), so TFD can update */
844         ahci_pwrite(ap, AHCI_PREG_SERR, ahci_pread(ap, AHCI_PREG_SERR));
845
846         /*
847          * Wait for device to become ready
848          *
849          * This can take more then a second, give it 3 seconds.
850          */
851         if (ahci_pwait_clr_to(ap, 3000,
852                                AHCI_PREG_TFD, AHCI_PREG_TFD_STS_BSY |
853                                AHCI_PREG_TFD_STS_DRQ | AHCI_PREG_TFD_STS_ERR)) {
854                 rc = EBUSY;
855                 kprintf("%s: Device will not come ready 0x%b\n",
856                         PORTNAME(ap),
857                         ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
858                 goto err;
859         }
860
861         ap->ap_ata.ap_type = ahci_port_signature_detect(ap);
862         rc = 0;
863 err:
864         /* Restore preserved port state */
865         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
866
867         return (rc);
868 }
869
870 /*
871  * Figure out what type of device is connected to the port, ATAPI or
872  * DISK.
873  */
874 int
875 ahci_port_signature_detect(struct ahci_port *ap)
876 {
877         u_int32_t sig;
878
879         sig = ahci_pread(ap, AHCI_PREG_SIG);
880         if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000)) {
881                 return(ATA_PORT_T_ATAPI);
882         } else {
883                 return(ATA_PORT_T_DISK);
884         }
885 }
886
887 /*
888  * Load the DMA descriptor table for a CCB's buffer.
889  */
890 int
891 ahci_load_prdt(struct ahci_ccb *ccb)
892 {
893         struct ahci_port                *ap = ccb->ccb_port;
894         struct ahci_softc               *sc = ap->ap_sc;
895         struct ata_xfer                 *xa = &ccb->ccb_xa;
896         struct ahci_prdt                *prdt = ccb->ccb_cmd_table->prdt;
897         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
898         struct ahci_cmd_hdr             *cmd_slot = ccb->ccb_cmd_hdr;
899         int                             error;
900
901         if (xa->datalen == 0) {
902                 ccb->ccb_cmd_hdr->prdtl = 0;
903                 return (0);
904         }
905
906         error = bus_dmamap_load(sc->sc_tag_data, dmap,
907                                 xa->data, xa->datalen,
908                                 ahci_load_prdt_callback,
909                                 &prdt,
910                                 ((xa->flags & ATA_F_NOWAIT) ?
911                                     BUS_DMA_NOWAIT : BUS_DMA_WAITOK));
912         if (error != 0) {
913                 kprintf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
914                 return (1);
915         }
916         if (xa->flags & ATA_F_PIO)
917                 prdt->flags |= htole32(AHCI_PRDT_FLAG_INTR);
918
919         cmd_slot->prdtl = htole16(prdt - ccb->ccb_cmd_table->prdt + 1);
920
921         bus_dmamap_sync(sc->sc_tag_data, dmap,
922                         (xa->flags & ATA_F_READ) ?
923                             BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
924
925         return (0);
926
927 #ifdef DIAGNOSTIC
928 diagerr:
929         bus_dmamap_unload(sc->sc_tag_data, dmap);
930         return (1);
931 #endif
932 }
933
934 /*
935  * Callback from BUSDMA system to load the segment list.  The passed segment
936  * list is a temporary structure.
937  */
938 static
939 void
940 ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs, int nsegs,
941                         int error)
942 {
943         struct ahci_prdt *prd = *(void **)info;
944         u_int64_t addr;
945
946         KKASSERT(nsegs <= AHCI_MAX_PRDT);
947
948         while (nsegs) {
949                 addr = segs->ds_addr;
950                 prd->dba_hi = htole32((u_int32_t)(addr >> 32));
951                 prd->dba_lo = htole32((u_int32_t)addr);
952 #ifdef DIAGNOSTIC
953                 KKASSERT((addr & 1) == 0);
954                 KKASSERT((segs->ds_len & 1) == 0);
955 #endif
956                 prd->flags = htole32(segs->ds_len - 1);
957                 --nsegs;
958                 if (nsegs)
959                         ++prd;
960                 ++segs;
961         }
962         *(void **)info = prd;   /* return last valid segment */
963 }
964
965 void
966 ahci_unload_prdt(struct ahci_ccb *ccb)
967 {
968         struct ahci_port                *ap = ccb->ccb_port;
969         struct ahci_softc               *sc = ap->ap_sc;
970         struct ata_xfer                 *xa = &ccb->ccb_xa;
971         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
972
973         if (xa->datalen != 0) {
974                 bus_dmamap_sync(sc->sc_tag_data, dmap,
975                                 (xa->flags & ATA_F_READ) ?
976                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
977
978                 bus_dmamap_unload(sc->sc_tag_data, dmap);
979
980                 if (ccb->ccb_xa.flags & ATA_F_NCQ)
981                         xa->resid = 0;
982                 else
983                         xa->resid = xa->datalen -
984                             le32toh(ccb->ccb_cmd_hdr->prdbc);
985         }
986 }
987
988 /*
989  * Start a command and poll for completion.
990  *
991  * NOTE: If the caller specifies a NULL timeout function the caller is
992  *       responsible for clearing hardware state on failure, but we will
993  *       deal with removing the ccb from any pending queue.
994  *
995  * NOTE: NCQ should never be used with this function.
996  */
997 int
998 ahci_poll(struct ahci_ccb *ccb, int timeout, void (*timeout_fn)(void *))
999 {
1000         struct ahci_port *ap = ccb->ccb_port;
1001         u_int32_t       slot_mask = 1 << ccb->ccb_slot;
1002
1003         crit_enter();
1004         ahci_start(ccb);
1005         do {
1006                 if (ahci_port_intr(ap, AHCI_PREG_CI_ALL_SLOTS) & slot_mask) {
1007                         crit_exit();
1008                         return (0);
1009                 }
1010                 if (ccb->ccb_xa.state != ATA_S_ONCHIP &&
1011                     ccb->ccb_xa.state != ATA_S_PENDING) {
1012                         break;
1013                 }
1014                 DELAY(1000000 / hz);
1015         } while (--timeout > 0);
1016
1017         if (ccb->ccb_xa.state != ATA_S_ONCHIP &&
1018             ccb->ccb_xa.state != ATA_S_PENDING) {
1019                 kprintf("%s: Warning poll completed unexpectedly for slot %d\n",
1020                         PORTNAME(ap), ccb->ccb_slot);
1021                 crit_exit();
1022                 return (0);
1023         }
1024
1025         kprintf("%s: Poll timed-out for slot %d state %d\n",
1026                 PORTNAME(ap), ccb->ccb_slot, ccb->ccb_xa.state);
1027
1028         if (timeout_fn != NULL) {
1029                 timeout_fn(ccb);
1030         } else {
1031                 if (ccb->ccb_xa.state == ATA_S_PENDING)
1032                         TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1033                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1034         }
1035         crit_exit();
1036
1037         return (1);
1038 }
1039
1040 void
1041 ahci_start(struct ahci_ccb *ccb)
1042 {
1043         struct ahci_port                *ap = ccb->ccb_port;
1044         struct ahci_softc               *sc = ap->ap_sc;
1045
1046         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
1047
1048         /* Zero transferred byte count before transfer */
1049         ccb->ccb_cmd_hdr->prdbc = 0;
1050
1051         /* Sync command list entry and corresponding command table entry */
1052         bus_dmamap_sync(sc->sc_tag_cmdh,
1053                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
1054                         BUS_DMASYNC_PREWRITE);
1055         bus_dmamap_sync(sc->sc_tag_cmdt,
1056                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
1057                         BUS_DMASYNC_PREWRITE);
1058
1059         /* Prepare RFIS area for write by controller */
1060         bus_dmamap_sync(sc->sc_tag_rfis,
1061                         AHCI_DMA_MAP(ap->ap_dmamem_rfis),
1062                         BUS_DMASYNC_PREREAD);
1063
1064         if (ccb->ccb_xa.flags & ATA_F_NCQ) {
1065                 /* Issue NCQ commands only when there are no outstanding
1066                  * standard commands. */
1067                 if (ap->ap_active != 0 || !TAILQ_EMPTY(&ap->ap_ccb_pending))
1068                         TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1069                 else {
1070                         KKASSERT(ap->ap_active_cnt == 0);
1071                         ap->ap_sactive |= (1 << ccb->ccb_slot);
1072                         ccb->ccb_xa.state = ATA_S_ONCHIP;
1073                         ahci_pwrite(ap, AHCI_PREG_SACT, 1 << ccb->ccb_slot);
1074                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
1075                 }
1076         } else {
1077                 /*
1078                  * Wait for all NCQ commands to finish before issuing standard
1079                  * command.
1080                  */
1081                 if (ap->ap_sactive != 0 || ap->ap_active_cnt == 2)
1082                         TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1083                 else if (ap->ap_active_cnt < 2) {
1084                         ap->ap_active |= 1 << ccb->ccb_slot;
1085                         ccb->ccb_xa.state = ATA_S_ONCHIP;
1086                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
1087                         ap->ap_active_cnt++;
1088                 }
1089         }
1090 }
1091
1092 void
1093 ahci_issue_pending_ncq_commands(struct ahci_port *ap)
1094 {
1095         struct ahci_ccb                 *nextccb;
1096         u_int32_t                       sact_change = 0;
1097
1098         KKASSERT(ap->ap_active_cnt == 0);
1099
1100         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1101         if (nextccb == NULL || !(nextccb->ccb_xa.flags & ATA_F_NCQ))
1102                 return;
1103
1104         /* Start all the NCQ commands at the head of the pending list. */
1105         do {
1106                 TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
1107                 sact_change |= 1 << nextccb->ccb_slot;
1108                 nextccb->ccb_xa.state = ATA_S_ONCHIP;
1109                 nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1110         } while (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ));
1111
1112         ap->ap_sactive |= sact_change;
1113         ahci_pwrite(ap, AHCI_PREG_SACT, sact_change);
1114         ahci_pwrite(ap, AHCI_PREG_CI, sact_change);
1115
1116         return;
1117 }
1118
1119 void
1120 ahci_issue_pending_commands(struct ahci_port *ap, int last_was_ncq)
1121 {
1122         struct ahci_ccb                 *nextccb;
1123
1124         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1125         if (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ)) {
1126                 KKASSERT(last_was_ncq == 0);    /* otherwise it should have
1127                                                  * been started already. */
1128
1129                 /* Issue NCQ commands only when there are no outstanding
1130                  * standard commands. */
1131                 ap->ap_active_cnt--;
1132                 if (ap->ap_active == 0)
1133                         ahci_issue_pending_ncq_commands(ap);
1134                 else
1135                         KKASSERT(ap->ap_active_cnt == 1);
1136         } else if (nextccb) {
1137                 if (ap->ap_sactive != 0 || last_was_ncq)
1138                         KKASSERT(ap->ap_active_cnt == 0);
1139
1140                 /* Wait for all NCQ commands to finish before issuing standard
1141                  * command. */
1142                 if (ap->ap_sactive != 0)
1143                         return;
1144
1145                 /* Keep up to 2 standard commands on-chip at a time. */
1146                 do {
1147                         TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
1148                         ap->ap_active |= 1 << nextccb->ccb_slot;
1149                         nextccb->ccb_xa.state = ATA_S_ONCHIP;
1150                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << nextccb->ccb_slot);
1151                         if (last_was_ncq)
1152                                 ap->ap_active_cnt++;
1153                         if (ap->ap_active_cnt == 2)
1154                                 break;
1155                         KKASSERT(ap->ap_active_cnt == 1);
1156                         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1157                 } while (nextccb && !(nextccb->ccb_xa.flags & ATA_F_NCQ));
1158         } else if (!last_was_ncq) {
1159                 KKASSERT(ap->ap_active_cnt == 1 || ap->ap_active_cnt == 2);
1160
1161                 /* Standard command finished, none waiting to start. */
1162                 ap->ap_active_cnt--;
1163         } else {
1164                 KKASSERT(ap->ap_active_cnt == 0);
1165
1166                 /* NCQ command finished. */
1167         }
1168 }
1169
1170 void
1171 ahci_intr(void *arg)
1172 {
1173         struct ahci_softc               *sc = arg;
1174         u_int32_t                       is, ack = 0;
1175         int                             port;
1176
1177         /* Read global interrupt status */
1178         is = ahci_read(sc, AHCI_REG_IS);
1179         if (is == 0 || is == 0xffffffff)
1180                 return;
1181         ack = is;
1182
1183 #ifdef AHCI_COALESCE
1184         /* Check coalescing interrupt first */
1185         if (is & sc->sc_ccc_mask) {
1186                 DPRINTF(AHCI_D_INTR, "%s: command coalescing interrupt\n",
1187                     DEVNAME(sc));
1188                 is &= ~sc->sc_ccc_mask;
1189                 is |= sc->sc_ccc_ports_cur;
1190         }
1191 #endif
1192
1193         /* Process interrupts for each port */
1194         while (is) {
1195                 port = ffs(is) - 1;
1196                 if (sc->sc_ports[port]) {
1197                         ahci_port_intr(sc->sc_ports[port],
1198                                        AHCI_PREG_CI_ALL_SLOTS);
1199                 }
1200                 is &= ~(1 << port);
1201         }
1202
1203         /* Finally, acknowledge global interrupt */
1204         ahci_write(sc, AHCI_REG_IS, ack);
1205 }
1206
1207 u_int32_t
1208 ahci_port_intr(struct ahci_port *ap, u_int32_t ci_mask)
1209 {
1210         struct ahci_softc               *sc = ap->ap_sc;
1211         u_int32_t                       is, ci_saved, ci_masked, processed = 0;
1212         int                             slot;
1213         struct ahci_ccb                 *ccb = NULL;
1214         volatile u_int32_t              *active;
1215 #ifdef DIAGNOSTIC
1216         u_int32_t                       tmp;
1217 #endif
1218         enum { NEED_NOTHING, NEED_RESTART, NEED_HOTPLUG_INSERT,
1219                NEED_HOTPLUG_REMOVE } need = NEED_NOTHING;
1220
1221         is = ahci_pread(ap, AHCI_PREG_IS);
1222
1223         /* Ack port interrupt only if checking all command slots. */
1224         if (ci_mask == AHCI_PREG_CI_ALL_SLOTS)
1225                 ahci_pwrite(ap, AHCI_PREG_IS, is);
1226
1227         if (is)
1228                 DPRINTF(AHCI_D_INTR, "%s: interrupt: %b\n", PORTNAME(ap),
1229                         is, AHCI_PFMT_IS);
1230
1231         if (ap->ap_sactive) {
1232                 /* Active NCQ commands - use SActive instead of CI */
1233                 KKASSERT(ap->ap_active == 0);
1234                 KKASSERT(ap->ap_active_cnt == 0);
1235                 ci_saved = ahci_pread(ap, AHCI_PREG_SACT);
1236                 active = &ap->ap_sactive;
1237         } else {
1238                 /* Save CI */
1239                 ci_saved = ahci_pread(ap, AHCI_PREG_CI);
1240                 active = &ap->ap_active;
1241         }
1242
1243         /* Command failed.  See AHCI 1.1 spec 6.2.2.1 and 6.2.2.2. */
1244         if (is & AHCI_PREG_IS_TFES) {
1245                 u_int32_t               tfd, serr;
1246                 int                     err_slot;
1247
1248                 tfd = ahci_pread(ap, AHCI_PREG_TFD);
1249                 serr = ahci_pread(ap, AHCI_PREG_SERR);
1250
1251                 if (ap->ap_sactive == 0) {
1252                         /* Errored slot is easy to determine from CMD. */
1253                         err_slot = AHCI_PREG_CMD_CCS(ahci_pread(ap,
1254                             AHCI_PREG_CMD));
1255                         ccb = &ap->ap_ccbs[err_slot];
1256
1257                         /* Preserve received taskfile data from the RFIS. */
1258                         memcpy(&ccb->ccb_xa.rfis, ap->ap_rfis->rfis,
1259                             sizeof(struct ata_fis_d2h));
1260                 } else
1261                         err_slot = -1;  /* Must extract error from log page */
1262
1263                 DPRINTF(AHCI_D_VERBOSE, "%s: errored slot %d, TFD: %b, SERR:"
1264                     " %b, DIAG: %b\n", PORTNAME(ap), err_slot, tfd,
1265                     AHCI_PFMT_TFD_STS, AHCI_PREG_SERR_ERR(serr),
1266                     AHCI_PFMT_SERR_ERR, AHCI_PREG_SERR_DIAG(serr),
1267                     AHCI_PFMT_SERR_DIAG);
1268
1269                 /* Turn off ST to clear CI and SACT. */
1270                 ahci_port_stop(ap, 0);
1271                 need = NEED_RESTART;
1272
1273                 /* Clear SERR to enable capturing new errors. */
1274                 ahci_pwrite(ap, AHCI_PREG_SERR, serr);
1275
1276                 /* Acknowledge the interrupts we can recover from. */
1277                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_TFES |
1278                     AHCI_PREG_IS_IFS);
1279                 is = ahci_pread(ap, AHCI_PREG_IS);
1280
1281                 /* If device hasn't cleared its busy status, try to idle it. */
1282                 if (tfd & (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1283                         kprintf("%s: Attempting to idle device\n",
1284                                 PORTNAME(ap));
1285                         if (ahci_port_reset(ap, 0)) {
1286                                 kprintf("%s: Unable to idle device, port "
1287                                         "bricked on us\n",
1288                                         PORTNAME(ap));
1289                                 goto fatal;
1290                         }
1291
1292                         /* Had to reset device, can't gather extended info. */
1293                 } else if (ap->ap_sactive) {
1294                         /* Recover the NCQ error from log page 10h. */
1295                         ahci_port_read_ncq_error(ap, &err_slot);
1296                         if (err_slot < 0)
1297                                 goto failall;
1298
1299                         DPRINTF(AHCI_D_VERBOSE, "%s: NCQ errored slot %d\n",
1300                                 PORTNAME(ap), err_slot);
1301
1302                         ccb = &ap->ap_ccbs[err_slot];
1303                 } else {
1304                         /* Didn't reset, could gather extended info from log. */
1305                 }
1306
1307                 /*
1308                  * If we couldn't determine the errored slot, reset the port
1309                  * and fail all the active slots.
1310                  */
1311                 if (err_slot == -1) {
1312                         if (ahci_port_reset(ap, 0)) {
1313                                 kprintf("%s: Unable to idle device after "
1314                                         "NCQ error, port bricked on us\n",
1315                                         PORTNAME(ap));
1316                                 goto fatal;
1317                         }
1318                         kprintf("%s: couldn't recover NCQ error, failing "
1319                                 "all outstanding commands.\n",
1320                                 PORTNAME(ap));
1321                         goto failall;
1322                 }
1323
1324                 /* Clear the failed command in saved CI so completion runs. */
1325                 ci_saved &= ~(1 << err_slot);
1326
1327                 /* Note the error in the ata_xfer. */
1328                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
1329                 ccb->ccb_xa.state = ATA_S_ERROR;
1330
1331 #ifdef DIAGNOSTIC
1332                 /* There may only be one outstanding standard command now. */
1333                 if (ap->ap_sactive == 0) {
1334                         tmp = ci_saved;
1335                         if (tmp) {
1336                                 slot = ffs(tmp) - 1;
1337                                 tmp &= ~(1 << slot);
1338                                 KKASSERT(tmp == 0);
1339                         }
1340                 }
1341 #endif
1342         }
1343
1344         /*
1345          * Port change (hot-plug).
1346          *
1347          * A PCS interrupt will occur on hot-plug once communication is
1348          * established.
1349          *
1350          * A PRCS interrupt will occur on hot-unplug (and possibly also
1351          * on hot-plug).
1352          *
1353          * XXX We can then check the CPS (Cold Presence State) bit, if
1354          * supported, to determine if a device is plugged in or not and do
1355          * the right thing.
1356          *
1357          * WARNING:  A PCS interrupt is cleared by clearing DIAG_X, and
1358          *           can also occur if an unsolicited COMINIT is received.
1359          *           If this occurs command processing is automatically
1360          *           stopped (CR goes inactive) and the port must be stopped
1361          *           and restarted.
1362          */
1363         if (is & (AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS)) {
1364                 ahci_pwrite(ap, AHCI_PREG_SERR,
1365                         (AHCI_PREG_SERR_DIAG_N | AHCI_PREG_SERR_DIAG_X) << 16);
1366                 ahci_port_stop(ap, 0);
1367                 switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
1368                 case AHCI_PREG_SSTS_DET_DEV:
1369                         if (ap->ap_ata.ap_type == ATA_PORT_T_NONE) {
1370                                 need = NEED_HOTPLUG_INSERT;
1371                                 goto fatal;
1372                         }
1373                         need = NEED_RESTART;
1374                         break;
1375                 default:
1376                         if (ap->ap_ata.ap_type != ATA_PORT_T_NONE) {
1377                                 need = NEED_HOTPLUG_REMOVE;
1378                                 goto fatal;
1379                         }
1380                         need = NEED_RESTART;
1381                         break;
1382                 }
1383         }
1384
1385         /*
1386          * Check for remaining errors - they are fatal.
1387          */
1388         if (is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS | AHCI_PREG_IS_IFS |
1389                   AHCI_PREG_IS_OFS | AHCI_PREG_IS_UFS)) {
1390                 u_int32_t serr = ahci_pread(ap, AHCI_PREG_SERR);
1391                 kprintf("%s: unrecoverable errors (IS: %b, SERR: %b %b), "
1392                         "disabling port.\n",
1393                         PORTNAME(ap),
1394                         is, AHCI_PFMT_IS,
1395                         AHCI_PREG_SERR_ERR(serr), AHCI_PFMT_SERR_ERR,
1396                         AHCI_PREG_SERR_DIAG(serr), AHCI_PFMT_SERR_DIAG
1397                 );
1398                 /* XXX try recovery first */
1399                 goto fatal;
1400         }
1401
1402         /*
1403          * Fail all outstanding commands if we know the port won't recover.
1404          */
1405         if (ap->ap_state == AP_S_FATAL_ERROR) {
1406 fatal:
1407                 ap->ap_state = AP_S_FATAL_ERROR;
1408 failall:
1409
1410                 /* Ensure port is shut down. */
1411                 ahci_port_stop(ap, 1);
1412
1413                 /* Error all the active slots. */
1414                 ci_masked = ci_saved & *active;
1415                 while (ci_masked) {
1416                         slot = ffs(ci_masked) - 1;
1417                         ccb = &ap->ap_ccbs[slot];
1418                         ci_masked &= ~(1 << slot);
1419                         ccb->ccb_xa.state = ATA_S_ERROR;
1420                 }
1421
1422                 /* Run completion for all active slots. */
1423                 ci_saved &= ~*active;
1424
1425                 /*
1426                  * Don't restart the port if our problems were deemed fatal.
1427                  *
1428                  * Also acknowlege all fatal interrupt sources to prevent
1429                  * a livelock.
1430                  */
1431                 if (ap->ap_state == AP_S_FATAL_ERROR) {
1432                         if (need == NEED_RESTART)
1433                                 need = NEED_NOTHING;
1434                         ahci_pwrite(ap, AHCI_PREG_IS,
1435                                     AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
1436                                     AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS |
1437                                     AHCI_PREG_IS_UFS);
1438                 }
1439         }
1440
1441         /*
1442          * CCB completion is detected by noticing its slot's bit in CI has
1443          * changed to zero some time after we activated it.
1444          * If we are polling, we may only be interested in particular slot(s).
1445          */
1446         ci_masked = ~ci_saved & *active & ci_mask;
1447         while (ci_masked) {
1448                 slot = ffs(ci_masked) - 1;
1449                 ccb = &ap->ap_ccbs[slot];
1450                 ci_masked &= ~(1 << slot);
1451
1452                 DPRINTF(AHCI_D_INTR, "%s: slot %d is complete%s\n",
1453                     PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
1454                     " (error)" : "");
1455
1456                 bus_dmamap_sync(sc->sc_tag_cmdh,
1457                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
1458                                 BUS_DMASYNC_POSTWRITE);
1459
1460                 bus_dmamap_sync(sc->sc_tag_cmdt,
1461                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
1462                                 BUS_DMASYNC_POSTWRITE);
1463
1464                 bus_dmamap_sync(sc->sc_tag_rfis,
1465                                 AHCI_DMA_MAP(ap->ap_dmamem_rfis),
1466                                 BUS_DMASYNC_POSTREAD);
1467
1468                 *active &= ~(1 << ccb->ccb_slot);
1469                 ccb->ccb_done(ccb);
1470
1471                 processed |= 1 << ccb->ccb_slot;
1472         }
1473
1474         switch(need) {
1475         case NEED_RESTART:
1476                 /*
1477                  * A recoverable error occured and we can restart outstanding
1478                  * commands on the port.
1479                  */
1480                 ahci_port_start(ap);
1481
1482                 if (ci_saved) {
1483 #ifdef DIAGNOSTIC
1484                         tmp = ci_saved;
1485                         while (tmp) {
1486                                 slot = ffs(tmp) - 1;
1487                                 tmp &= ~(1 << slot);
1488                                 ccb = &ap->ap_ccbs[slot];
1489                                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
1490                                 KKASSERT((!!(ccb->ccb_xa.flags & ATA_F_NCQ)) ==
1491                                     (!!ap->ap_sactive));
1492                         }
1493 #endif
1494                         DPRINTF(AHCI_D_VERBOSE, "%s: ahci_port_intr "
1495                             "re-enabling%s slots %08x\n", PORTNAME(ap),
1496                             ap->ap_sactive ? " NCQ" : "", ci_saved);
1497
1498                         if (ap->ap_sactive)
1499                                 ahci_pwrite(ap, AHCI_PREG_SACT, ci_saved);
1500                         ahci_pwrite(ap, AHCI_PREG_CI, ci_saved);
1501                 }
1502                 break;
1503         case NEED_HOTPLUG_INSERT:
1504                 /*
1505                  *
1506                  * A hot-plug event has occured and all outstanding commands
1507                  * have been revoked.  Perform the hot-plug action.
1508                  */
1509                 kprintf("%s: HOTPLUG - Device inserted\n",
1510                         PORTNAME(ap));
1511                 if (ahci_port_init(ap) == 0)
1512                         ahci_cam_changed(ap, 1);
1513                 break;
1514         case NEED_HOTPLUG_REMOVE:
1515                 kprintf("%s: HOTPLUG - Device removed\n",
1516                         PORTNAME(ap));
1517                 ahci_port_reset(ap, 1);
1518                 ahci_cam_changed(ap, 0);
1519                 break;
1520         default:
1521                 break;
1522         }
1523         return (processed);
1524 }
1525
1526 struct ahci_ccb *
1527 ahci_get_ccb(struct ahci_port *ap)
1528 {
1529         struct ahci_ccb                 *ccb;
1530
1531         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
1532         ccb = TAILQ_FIRST(&ap->ap_ccb_free);
1533         if (ccb != NULL) {
1534                 KKASSERT(ccb->ccb_xa.state == ATA_S_PUT);
1535                 TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
1536                 ccb->ccb_xa.state = ATA_S_SETUP;
1537         }
1538         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
1539
1540         return (ccb);
1541 }
1542
1543 void
1544 ahci_put_ccb(struct ahci_ccb *ccb)
1545 {
1546         struct ahci_port                *ap = ccb->ccb_port;
1547
1548 #ifdef DIAGNOSTIC
1549         if (ccb->ccb_xa.state != ATA_S_COMPLETE &&
1550             ccb->ccb_xa.state != ATA_S_TIMEOUT &&
1551             ccb->ccb_xa.state != ATA_S_ERROR) {
1552                 kprintf("%s: invalid ata_xfer state %02x in ahci_put_ccb, "
1553                         "slot %d\n",
1554                         PORTNAME(ccb->ccb_port), ccb->ccb_xa.state,
1555                         ccb->ccb_slot);
1556         }
1557 #endif
1558
1559         ccb->ccb_xa.state = ATA_S_PUT;
1560         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
1561         TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
1562         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
1563 }
1564
1565 struct ahci_ccb *
1566 ahci_get_err_ccb(struct ahci_port *ap)
1567 {
1568         struct ahci_ccb *err_ccb;
1569         u_int32_t sact;
1570
1571         /* No commands may be active on the chip. */
1572         sact = ahci_pread(ap, AHCI_PREG_SACT);
1573         if (sact != 0)
1574                 kprintf("ahci_get_err_ccb but SACT %08x != 0?\n", sact);
1575         KKASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
1576
1577 #ifdef DIAGNOSTIC
1578         KKASSERT(ap->ap_err_busy == 0);
1579         ap->ap_err_busy = 1;
1580 #endif
1581         /* Save outstanding command state. */
1582         ap->ap_err_saved_active = ap->ap_active;
1583         ap->ap_err_saved_active_cnt = ap->ap_active_cnt;
1584         ap->ap_err_saved_sactive = ap->ap_sactive;
1585
1586         /*
1587          * Pretend we have no commands outstanding, so that completions won't
1588          * run prematurely.
1589          */
1590         ap->ap_active = ap->ap_active_cnt = ap->ap_sactive = 0;
1591
1592         /*
1593          * Grab a CCB to use for error recovery.  This should never fail, as
1594          * we ask atascsi to reserve one for us at init time.
1595          */
1596         err_ccb = ahci_get_ccb(ap);
1597         KKASSERT(err_ccb != NULL);
1598         err_ccb->ccb_xa.flags = 0;
1599         err_ccb->ccb_done = ahci_empty_done;
1600
1601         return err_ccb;
1602 }
1603
1604 void
1605 ahci_put_err_ccb(struct ahci_ccb *ccb)
1606 {
1607         struct ahci_port *ap = ccb->ccb_port;
1608         u_int32_t sact;
1609         u_int32_t ci;
1610
1611 #ifdef DIAGNOSTIC
1612         KKASSERT(ap->ap_err_busy);
1613 #endif
1614         /*
1615          * No commands may be active on the chip
1616          */
1617         sact = ahci_pread(ap, AHCI_PREG_SACT);
1618         if (sact) {
1619                 panic("ahci_port_err_ccb(%d) but SACT %08x != 0\n",
1620                       ccb->ccb_slot, sact);
1621         }
1622         ci = ahci_pread(ap, AHCI_PREG_CI);
1623         if (ci) {
1624                 panic("ahci_put_err_ccb(%d) but CI %08x != 0\n",
1625                       ccb->ccb_slot, ci);
1626         }
1627
1628         /* Done with the CCB */
1629         ahci_put_ccb(ccb);
1630
1631         /* Restore outstanding command state */
1632         ap->ap_sactive = ap->ap_err_saved_sactive;
1633         ap->ap_active_cnt = ap->ap_err_saved_active_cnt;
1634         ap->ap_active = ap->ap_err_saved_active;
1635
1636 #ifdef DIAGNOSTIC
1637         ap->ap_err_busy = 0;
1638 #endif
1639 }
1640
1641 int
1642 ahci_port_read_ncq_error(struct ahci_port *ap, int *err_slotp)
1643 {
1644         struct ahci_ccb                 *ccb;
1645         struct ahci_cmd_hdr             *cmd_slot;
1646         u_int32_t                       cmd;
1647         struct ata_fis_h2d              *fis;
1648         int                             rc = EIO;
1649
1650         DPRINTF(AHCI_D_VERBOSE, "%s: read log page\n", PORTNAME(ap));
1651
1652         /* Save command register state. */
1653         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1654
1655         /* Port should have been idled already.  Start it. */
1656         KKASSERT((cmd & AHCI_PREG_CMD_CR) == 0);
1657         ahci_port_start(ap);
1658
1659         /* Prep error CCB for READ LOG EXT, page 10h, 1 sector. */
1660         ccb = ahci_get_err_ccb(ap);
1661         ccb->ccb_xa.flags = ATA_F_NOWAIT | ATA_F_READ | ATA_F_POLL;
1662         ccb->ccb_xa.data = ap->ap_err_scratch;
1663         ccb->ccb_xa.datalen = 512;
1664         cmd_slot = ccb->ccb_cmd_hdr;
1665         bzero(ccb->ccb_cmd_table, sizeof(struct ahci_cmd_table));
1666
1667         fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
1668         fis->type = ATA_FIS_TYPE_H2D;
1669         fis->flags = ATA_H2D_FLAGS_CMD;
1670         fis->command = ATA_C_READ_LOG_EXT;
1671         fis->lba_low = 0x10;            /* queued error log page (10h) */
1672         fis->sector_count = 1;          /* number of sectors (1) */
1673         fis->sector_count_exp = 0;
1674         fis->lba_mid = 0;               /* starting offset */
1675         fis->lba_mid_exp = 0;
1676         fis->device = 0;
1677
1678         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
1679
1680         if (ahci_load_prdt(ccb) != 0) {
1681                 rc = ENOMEM;    /* XXX caller must abort all commands */
1682                 goto err;
1683         }
1684
1685         ccb->ccb_xa.state = ATA_S_PENDING;
1686         if (ahci_poll(ccb, hz, NULL) != 0)
1687                 goto err;
1688
1689         rc = 0;
1690 err:
1691         /* Abort our command, if it failed, by stopping command DMA. */
1692         if (rc != 0 && (ap->ap_active & (1 << ccb->ccb_slot))) {
1693                 kprintf("%s: log page read failed, slot %d was still active.\n",
1694                         PORTNAME(ap), ccb->ccb_slot);
1695                 ahci_port_stop(ap, 0);
1696         }
1697
1698         /* Done with the error CCB now. */
1699         ahci_unload_prdt(ccb);
1700         ahci_put_err_ccb(ccb);
1701
1702         /* Extract failed register set and tags from the scratch space. */
1703         if (rc == 0) {
1704                 struct ata_log_page_10h         *log;
1705                 int                             err_slot;
1706
1707                 log = (struct ata_log_page_10h *)ap->ap_err_scratch;
1708                 if (log->err_regs.type & ATA_LOG_10H_TYPE_NOTQUEUED) {
1709                         /* Not queued bit was set - wasn't an NCQ error? */
1710                         kprintf("%s: read NCQ error page, but not an NCQ "
1711                                 "error?\n",
1712                                 PORTNAME(ap));
1713                         rc = ESRCH;
1714                 } else {
1715                         /* Copy back the log record as a D2H register FIS. */
1716                         *err_slotp = err_slot = log->err_regs.type &
1717                             ATA_LOG_10H_TYPE_TAG_MASK;
1718
1719                         ccb = &ap->ap_ccbs[err_slot];
1720                         memcpy(&ccb->ccb_xa.rfis, &log->err_regs,
1721                             sizeof(struct ata_fis_d2h));
1722                         ccb->ccb_xa.rfis.type = ATA_FIS_TYPE_D2H;
1723                         ccb->ccb_xa.rfis.flags = 0;
1724                 }
1725         }
1726
1727         /* Restore saved CMD register state */
1728         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1729
1730         return (rc);
1731 }
1732
1733 /*
1734  * Allocate memory for various structures DMAd by hardware.  The maximum
1735  * number of segments for these tags is 1 so the DMA memory will have a
1736  * single physical base address.
1737  */
1738 struct ahci_dmamem *
1739 ahci_dmamem_alloc(struct ahci_softc *sc, bus_dma_tag_t tag)
1740 {
1741         struct ahci_dmamem *adm;
1742         int     error;
1743
1744         adm = kmalloc(sizeof(*adm), M_DEVBUF, M_INTWAIT | M_ZERO);
1745
1746         error = bus_dmamem_alloc(tag, (void **)&adm->adm_kva,
1747                                  BUS_DMA_ZERO, &adm->adm_map);
1748         if (error == 0) {
1749                 adm->adm_tag = tag;
1750                 error = bus_dmamap_load(tag, adm->adm_map,
1751                                         adm->adm_kva,
1752                                         bus_dma_tag_getmaxsize(tag),
1753                                         ahci_dmamem_saveseg, &adm->adm_busaddr,
1754                                         0);
1755         }
1756         if (error) {
1757                 if (adm->adm_map) {
1758                         bus_dmamap_destroy(tag, adm->adm_map);
1759                         adm->adm_map = NULL;
1760                         adm->adm_tag = NULL;
1761                         adm->adm_kva = NULL;
1762                 }
1763                 kfree(adm, M_DEVBUF);
1764                 adm = NULL;
1765         }
1766         return (adm);
1767 }
1768
1769 static
1770 void
1771 ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error)
1772 {
1773         KKASSERT(error == 0);
1774         KKASSERT(nsegs == 1);
1775         *(bus_addr_t *)info = segs->ds_addr;
1776 }
1777
1778
1779 void
1780 ahci_dmamem_free(struct ahci_softc *sc, struct ahci_dmamem *adm)
1781 {
1782         if (adm->adm_map) {
1783                 bus_dmamap_unload(adm->adm_tag, adm->adm_map);
1784                 bus_dmamap_destroy(adm->adm_tag, adm->adm_map);
1785                 adm->adm_map = NULL;
1786                 adm->adm_tag = NULL;
1787                 adm->adm_kva = NULL;
1788         }
1789         kfree(adm, M_DEVBUF);
1790 }
1791
1792 u_int32_t
1793 ahci_read(struct ahci_softc *sc, bus_size_t r)
1794 {
1795         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
1796                           BUS_SPACE_BARRIER_READ);
1797         return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
1798 }
1799
1800 void
1801 ahci_write(struct ahci_softc *sc, bus_size_t r, u_int32_t v)
1802 {
1803         bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
1804         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
1805                           BUS_SPACE_BARRIER_WRITE);
1806 }
1807
1808 int
1809 ahci_wait_ne(struct ahci_softc *sc, bus_size_t r, u_int32_t mask,
1810              u_int32_t target)
1811 {
1812         int                             i;
1813
1814         for (i = 0; i < 1000; i++) {
1815                 if ((ahci_read(sc, r) & mask) != target)
1816                         return (0);
1817                 DELAY(1000);
1818         }
1819
1820         return (1);
1821 }
1822
1823 u_int32_t
1824 ahci_pread(struct ahci_port *ap, bus_size_t r)
1825 {
1826         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
1827                           BUS_SPACE_BARRIER_READ);
1828         return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
1829 }
1830
1831 void
1832 ahci_pwrite(struct ahci_port *ap, bus_size_t r, u_int32_t v)
1833 {
1834         bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
1835         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
1836                           BUS_SPACE_BARRIER_WRITE);
1837 }
1838
1839 int
1840 ahci_pwait_eq(struct ahci_port *ap, int timeout,
1841               bus_size_t r, u_int32_t mask, u_int32_t target)
1842 {
1843         int                             i;
1844
1845         for (i = 0; i < timeout; i++) {
1846                 if ((ahci_pread(ap, r) & mask) == target)
1847                         return (0);
1848                 DELAY(1000);
1849         }
1850
1851         return (1);
1852 }
1853
1854 struct ata_xfer *
1855 ahci_ata_get_xfer(struct ahci_port *ap)
1856 {
1857         /*struct ahci_softc     *sc = ap->ap_sc;*/
1858         struct ahci_ccb         *ccb;
1859
1860         ccb = ahci_get_ccb(ap);
1861         if (ccb == NULL) {
1862                 DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer: NULL ccb\n",
1863                     PORTNAME(ap));
1864                 return (NULL);
1865         }
1866
1867         DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer got slot %d\n",
1868             PORTNAME(ap), ccb->ccb_slot);
1869
1870         ccb->ccb_xa.fis->type = ATA_FIS_TYPE_H2D;
1871
1872         return (&ccb->ccb_xa);
1873 }
1874
1875 void
1876 ahci_ata_put_xfer(struct ata_xfer *xa)
1877 {
1878         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
1879
1880         DPRINTF(AHCI_D_XFER, "ahci_ata_put_xfer slot %d\n", ccb->ccb_slot);
1881
1882         ahci_put_ccb(ccb);
1883 }
1884
1885 int
1886 ahci_ata_cmd(struct ata_xfer *xa)
1887 {
1888         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
1889         struct ahci_cmd_hdr             *cmd_slot;
1890
1891         KKASSERT(xa->state == ATA_S_SETUP);
1892
1893 #if 0
1894         kprintf("ahci_ata_cmd xa->flags %08x type %08x cmd=%08x\n",
1895                 xa->flags,
1896                 xa->fis->type,
1897                 xa->fis->command);
1898 #endif
1899
1900         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
1901                 goto failcmd;
1902
1903         ccb->ccb_done = ahci_ata_cmd_done;
1904
1905         cmd_slot = ccb->ccb_cmd_hdr;
1906         cmd_slot->flags = htole16(5); /* FIS length (in DWORDs) */
1907
1908         if (xa->flags & ATA_F_WRITE)
1909                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_W);
1910
1911         if (xa->flags & ATA_F_PACKET)
1912                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_A);
1913
1914         if (ahci_load_prdt(ccb) != 0)
1915                 goto failcmd;
1916
1917         xa->state = ATA_S_PENDING;
1918
1919         if (xa->flags & ATA_F_POLL) {
1920                 ahci_poll(ccb, xa->timeout, ahci_ata_cmd_timeout);
1921                 return (ATA_COMPLETE);
1922         }
1923
1924         crit_enter();
1925         xa->flags |= ATA_F_TIMEOUT_RUNNING;
1926         callout_reset(&ccb->ccb_timeout, xa->timeout,
1927                       ahci_ata_cmd_timeout_unserialized, ccb);
1928         ahci_start(ccb);
1929         crit_exit();
1930         return (ATA_QUEUED);
1931
1932 failcmd:
1933         crit_enter();
1934         xa->state = ATA_S_ERROR;
1935         xa->complete(xa);
1936         crit_exit();
1937         return (ATA_ERROR);
1938 }
1939
1940 void
1941 ahci_ata_cmd_done(struct ahci_ccb *ccb)
1942 {
1943         struct ata_xfer                 *xa = &ccb->ccb_xa;
1944
1945         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
1946                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
1947                 callout_stop(&ccb->ccb_timeout);
1948         }
1949
1950         if (xa->state == ATA_S_ONCHIP || xa->state == ATA_S_ERROR)
1951                 ahci_issue_pending_commands(ccb->ccb_port,
1952                     xa->flags & ATA_F_NCQ);
1953
1954         ahci_unload_prdt(ccb);
1955
1956         if (xa->state == ATA_S_ONCHIP)
1957                 xa->state = ATA_S_COMPLETE;
1958 #ifdef DIAGNOSTIC
1959         else if (xa->state != ATA_S_ERROR && xa->state != ATA_S_TIMEOUT)
1960                 kprintf("%s: invalid ata_xfer state %02x in ahci_ata_cmd_done, "
1961                         "slot %d\n",
1962                         PORTNAME(ccb->ccb_port), xa->state, ccb->ccb_slot);
1963 #endif
1964         if (xa->state != ATA_S_TIMEOUT)
1965                 xa->complete(xa);
1966 }
1967
1968 static void
1969 ahci_ata_cmd_timeout_unserialized(void *arg)
1970 {
1971         struct ahci_ccb         *ccb = arg;
1972         struct ahci_port        *ap = ccb->ccb_port;
1973
1974         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
1975         ahci_ata_cmd_timeout(arg);
1976         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
1977 }
1978
1979 static void
1980 ahci_ata_cmd_timeout(void *arg)
1981 {
1982         struct ahci_ccb         *ccb = arg;
1983         struct ata_xfer         *xa = &ccb->ccb_xa;
1984         struct ahci_port        *ap = ccb->ccb_port;
1985         volatile u_int32_t      *active;
1986         int                     ccb_was_started, ncq_cmd;
1987
1988         crit_enter();
1989         kprintf("CMD TIMEOUT port-cmd-reg 0x%b\n"
1990                 "\tactive=%08x sactive=%08x\n"
1991                 "\t  sact=%08x      ci=%08x\n",
1992                 ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD,
1993                 ap->ap_active, ap->ap_sactive,
1994                 ahci_pread(ap, AHCI_PREG_SACT),
1995                 ahci_pread(ap, AHCI_PREG_CI));
1996
1997         /*
1998          * NOTE: Timeout will not be running if the command was polled.
1999          */
2000         KKASSERT(xa->flags & (ATA_F_POLL|ATA_F_TIMEOUT_RUNNING));
2001         xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2002         ncq_cmd = (xa->flags & ATA_F_NCQ);
2003         active = ncq_cmd ? &ap->ap_sactive : &ap->ap_active;
2004
2005         if (ccb->ccb_xa.state == ATA_S_PENDING) {
2006                 DPRINTF(AHCI_D_TIMEOUT, "%s: command for slot %d timed out "
2007                     "before it got on chip\n", PORTNAME(ap), ccb->ccb_slot);
2008                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2009                 ccb_was_started = 0;
2010         } else if (ccb->ccb_xa.state == ATA_S_ONCHIP && ahci_port_intr(ap,
2011             1 << ccb->ccb_slot)) {
2012                 DPRINTF(AHCI_D_TIMEOUT, "%s: final poll of port completed "
2013                     "command in slot %d\n", PORTNAME(ap), ccb->ccb_slot);
2014                 goto ret;
2015         } else if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
2016                 DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d already "
2017                     "handled%s\n", PORTNAME(ap), ccb->ccb_slot,
2018                     (*active & (1 << ccb->ccb_slot)) ?
2019                     " but slot is still active?" : ".");
2020                 goto ret;
2021         } else if ((ahci_pread(ap, ncq_cmd ? AHCI_PREG_SACT : AHCI_PREG_CI) &
2022                     (1 << ccb->ccb_slot)) == 0 &&
2023                    (*active & (1 << ccb->ccb_slot))) {
2024                 DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d completed but "
2025                     "IRQ handler didn't detect it.  Why?\n", PORTNAME(ap),
2026                     ccb->ccb_slot);
2027                 *active &= ~(1 << ccb->ccb_slot);
2028                 ccb->ccb_done(ccb);
2029                 goto ret;
2030         } else {
2031                 ccb_was_started = 1;
2032         }
2033
2034         /* Complete the slot with a timeout error. */
2035         ccb->ccb_xa.state = ATA_S_TIMEOUT;
2036         *active &= ~(1 << ccb->ccb_slot);
2037         DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (1)\n", PORTNAME(ap));
2038         ccb->ccb_done(ccb);     /* This won't issue pending commands or run the
2039                                    atascsi completion. */
2040
2041         /* Reset port to abort running command. */
2042         if (ccb_was_started) {
2043                 DPRINTF(AHCI_D_TIMEOUT, "%s: resetting port to abort%s command "
2044                     "in slot %d, active %08x\n", PORTNAME(ap), ncq_cmd ? " NCQ"
2045                     : "", ccb->ccb_slot, *active);
2046                 if (ahci_port_reset(ap, 0)) {
2047                         kprintf("%s: Unable to reset during timeout, port "
2048                                 "bricked on us\n",
2049                                 PORTNAME(ap));
2050                         ap->ap_state = AP_S_FATAL_ERROR;
2051                 }
2052
2053                 /* Restart any other commands that were aborted by the reset. */
2054                 if (*active) {
2055                         DPRINTF(AHCI_D_TIMEOUT, "%s: re-enabling%s slots "
2056                             "%08x\n", PORTNAME(ap), ncq_cmd ? " NCQ" : "",
2057                             *active);
2058                         if (ncq_cmd)
2059                                 ahci_pwrite(ap, AHCI_PREG_SACT, *active);
2060                         ahci_pwrite(ap, AHCI_PREG_CI, *active);
2061                 }
2062         }
2063
2064         /* Issue any pending commands now. */
2065         DPRINTF(AHCI_D_TIMEOUT, "%s: issue pending\n", PORTNAME(ap));
2066         if (ccb_was_started)
2067                 ahci_issue_pending_commands(ap, ncq_cmd);
2068         else if (ap->ap_active == 0)
2069                 ahci_issue_pending_ncq_commands(ap);
2070
2071         /* Complete the timed out ata_xfer I/O (may generate new I/O). */
2072         DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (2)\n", PORTNAME(ap));
2073         xa->complete(xa);
2074
2075         DPRINTF(AHCI_D_TIMEOUT, "%s: splx\n", PORTNAME(ap));
2076 ret:
2077         crit_exit();
2078 }
2079
2080 void
2081 ahci_empty_done(struct ahci_ccb *ccb)
2082 {
2083         ccb->ccb_xa.state = ATA_S_COMPLETE;
2084 }