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