Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / dev / disk / ahci / ahci.c
1 /*
2  * Copyright (c) 2006 David Gwynne <dlg@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  *
16  *
17  * Copyright (c) 2009 The DragonFly Project.  All rights reserved.
18  *
19  * This code is derived from software contributed to The DragonFly Project
20  * by Matthew Dillon <dillon@backplane.com>
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  *
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in
30  *    the documentation and/or other materials provided with the
31  *    distribution.
32  * 3. Neither the name of The DragonFly Project nor the names of its
33  *    contributors may be used to endorse or promote products derived
34  *    from this software without specific, prior written permission.
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
37  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
38  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
39  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
40  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
41  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
42  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
44  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  * $OpenBSD: ahci.c,v 1.147 2009/02/16 21:19:07 miod Exp $
50  */
51
52 #include "ahci.h"
53
54 int     ahci_port_init(struct ahci_port *ap, struct ata_port *at);
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_load_prdt(struct ahci_ccb *);
60 void    ahci_unload_prdt(struct ahci_ccb *);
61 static void ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs,
62                                     int nsegs, int error);
63 void    ahci_start(struct ahci_ccb *);
64 int     ahci_port_softreset(struct ahci_port *ap);
65 int     ahci_port_pmprobe(struct ahci_port *ap);
66 int     ahci_port_hardreset(struct ahci_port *ap, int hard);
67 void    ahci_port_hardstop(struct ahci_port *ap);
68 void    ahci_flush_tfd(struct ahci_port *ap);
69
70 static void ahci_ata_cmd_timeout_unserialized(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_err_ccb(struct ahci_port *);
76 void    ahci_put_err_ccb(struct ahci_ccb *);
77
78 int     ahci_port_read_ncq_error(struct ahci_port *, int *);
79
80 struct ahci_dmamem *ahci_dmamem_alloc(struct ahci_softc *, bus_dma_tag_t tag);
81 void    ahci_dmamem_free(struct ahci_softc *, struct ahci_dmamem *);
82 static void ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error);
83
84 void    ahci_empty_done(struct ahci_ccb *ccb);
85 void    ahci_ata_cmd_done(struct ahci_ccb *ccb);
86
87 /* Wait for all bits in _b to be cleared */
88 #define ahci_pwait_clr(_ap, _r, _b) \
89         ahci_pwait_eq((_ap), AHCI_PWAIT_TIMEOUT, (_r), (_b), 0)
90 #define ahci_pwait_clr_to(_ap, _to,  _r, _b) \
91         ahci_pwait_eq((_ap), _to, (_r), (_b), 0)
92
93 /* Wait for all bits in _b to be set */
94 #define ahci_pwait_set(_ap, _r, _b) \
95         ahci_pwait_eq((_ap), AHCI_PWAIT_TIMEOUT, (_r), (_b), (_b))
96 #define ahci_pwait_set_to(_ap, _to, _r, _b) \
97         ahci_pwait_eq((_ap), _to, (_r), (_b), (_b))
98
99 #define AHCI_PWAIT_TIMEOUT      1000
100
101 /*
102  * Initialize the global AHCI hardware.  This code does not set up any of
103  * its ports.
104  */
105 int
106 ahci_init(struct ahci_softc *sc)
107 {
108         u_int32_t       cap, pi;
109
110         DPRINTF(AHCI_D_VERBOSE, " GHC 0x%b",
111                 ahci_read(sc, AHCI_REG_GHC), AHCI_FMT_GHC);
112
113         /* save BIOS initialised parameters, enable staggered spin up */
114         cap = ahci_read(sc, AHCI_REG_CAP);
115         cap &= AHCI_REG_CAP_SMPS;
116         cap |= AHCI_REG_CAP_SSS;
117         pi = ahci_read(sc, AHCI_REG_PI);
118
119         /*
120          * Unconditionally reset the controller, do not conditionalize on
121          * trying to figure it if it was previously active or not.
122          */
123         ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_HR);
124         if (ahci_wait_ne(sc, AHCI_REG_GHC, AHCI_REG_GHC_HR,
125             AHCI_REG_GHC_HR) != 0) {
126                 device_printf(sc->sc_dev,
127                               "unable to reset controller\n");
128                 return (1);
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 ata_port         *at;
149         struct ahci_ccb         *ccb;
150         u_int64_t               dva;
151         u_int32_t               cmd;
152         struct ahci_cmd_hdr     *hdr;
153         struct ahci_cmd_table   *table;
154         int     rc = ENOMEM;
155         int     error;
156         int     i;
157
158         ap = kmalloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO);
159         if (ap == NULL) {
160                 device_printf(sc->sc_dev,
161                               "unable to allocate memory for port %d\n",
162                               port);
163                 goto reterr;
164         }
165
166         ksnprintf(ap->ap_name, sizeof(ap->ap_name), "%s%d.%d",
167                   device_get_name(sc->sc_dev),
168                   device_get_unit(sc->sc_dev),
169                   port);
170         sc->sc_ports[port] = ap;
171
172         /*
173          * Allocate enough so we never have to reallocate, it makes
174          * it easier.
175          *
176          * ap_pmcount will be reduced by the scan if we encounter the
177          * port multiplier port prior to target 15.
178          */
179         if (ap->ap_ata == NULL) {
180                 ap->ap_ata = kmalloc(sizeof(*ap->ap_ata) * AHCI_MAX_PMPORTS,
181                                      M_DEVBUF, M_INTWAIT | M_ZERO);
182                 for (i = 0; i < AHCI_MAX_PMPORTS; ++i) {
183                         at = &ap->ap_ata[i];
184                         at->at_ahci_port = ap;
185                         at->at_target = i;
186                         at->at_probe = ATA_PROBE_NEED_HARD_RESET;
187                         ksnprintf(at->at_name, sizeof(at->at_name),
188                                   "%s.%d", ap->ap_name, i);
189                 }
190         }
191         if (bus_space_subregion(sc->sc_iot, sc->sc_ioh,
192             AHCI_PORT_REGION(port), AHCI_PORT_SIZE, &ap->ap_ioh) != 0) {
193                 device_printf(sc->sc_dev,
194                               "unable to create register window for port %d\n",
195                               port);
196                 goto freeport;
197         }
198
199         ap->ap_sc = sc;
200         ap->ap_num = port;
201         ap->ap_probe = ATA_PROBE_NEED_HARD_RESET;
202         TAILQ_INIT(&ap->ap_ccb_free);
203         TAILQ_INIT(&ap->ap_ccb_pending);
204         lockinit(&ap->ap_ccb_lock, "ahcipo", 0, 0);
205
206         /* Disable port interrupts */
207         ahci_pwrite(ap, AHCI_PREG_IE, 0);
208
209         /*
210          * Sec 10.1.2 - deinitialise port if it is already running
211          */
212         cmd = ahci_pread(ap, AHCI_PREG_CMD);
213         if ((cmd & (AHCI_PREG_CMD_ST | AHCI_PREG_CMD_CR |
214                     AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_FR)) ||
215             (ahci_pread(ap, AHCI_PREG_SCTL) & AHCI_PREG_SCTL_DET)) {
216                 int r;
217
218                 r = ahci_port_stop(ap, 1);
219                 if (r) {
220                         device_printf(sc->sc_dev,
221                                   "unable to disable %s, ignoring port %d\n",
222                                   ((r == 2) ? "CR" : "FR"), port);
223                         rc = ENXIO;
224                         goto freeport;
225                 }
226
227                 /* Write DET to zero */
228                 ahci_pwrite(ap, AHCI_PREG_SCTL, AHCI_PREG_SCTL_IPM_DISABLED);
229         }
230
231         /* Allocate RFIS */
232         ap->ap_dmamem_rfis = ahci_dmamem_alloc(sc, sc->sc_tag_rfis);
233         if (ap->ap_dmamem_rfis == NULL) {
234                 kprintf("%s: NORFIS\n", PORTNAME(ap));
235                 goto nomem;
236         }
237
238         /* Setup RFIS base address */
239         ap->ap_rfis = (struct ahci_rfis *) AHCI_DMA_KVA(ap->ap_dmamem_rfis);
240         dva = AHCI_DMA_DVA(ap->ap_dmamem_rfis);
241         ahci_pwrite(ap, AHCI_PREG_FBU, (u_int32_t)(dva >> 32));
242         ahci_pwrite(ap, AHCI_PREG_FB, (u_int32_t)dva);
243
244         /* Enable FIS reception and activate port. */
245         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
246         cmd &= ~(AHCI_PREG_CMD_CLO | AHCI_PREG_CMD_PMA);
247         cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD | AHCI_PREG_CMD_SUD;
248         ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_ICC_ACTIVE);
249
250         /* Check whether port activated.  Skip it if not. */
251         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
252         if ((cmd & AHCI_PREG_CMD_FRE) == 0) {
253                 kprintf("%s: NOT-ACTIVATED\n", PORTNAME(ap));
254                 rc = ENXIO;
255                 goto freeport;
256         }
257
258         /* Allocate a CCB for each command slot */
259         ap->ap_ccbs = kmalloc(sizeof(struct ahci_ccb) * sc->sc_ncmds, M_DEVBUF,
260                               M_WAITOK | M_ZERO);
261         if (ap->ap_ccbs == NULL) {
262                 device_printf(sc->sc_dev,
263                               "unable to allocate command list for port %d\n",
264                               port);
265                 goto freeport;
266         }
267
268         /* Command List Structures and Command Tables */
269         ap->ap_dmamem_cmd_list = ahci_dmamem_alloc(sc, sc->sc_tag_cmdh);
270         ap->ap_dmamem_cmd_table = ahci_dmamem_alloc(sc, sc->sc_tag_cmdt);
271         if (ap->ap_dmamem_cmd_table == NULL ||
272             ap->ap_dmamem_cmd_list == NULL) {
273 nomem:
274                 device_printf(sc->sc_dev,
275                               "unable to allocate DMA memory for port %d\n",
276                               port);
277                 goto freeport;
278         }
279
280         /* Setup command list base address */
281         dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_list);
282         ahci_pwrite(ap, AHCI_PREG_CLBU, (u_int32_t)(dva >> 32));
283         ahci_pwrite(ap, AHCI_PREG_CLB, (u_int32_t)dva);
284
285         /* Split CCB allocation into CCBs and assign to command header/table */
286         hdr = AHCI_DMA_KVA(ap->ap_dmamem_cmd_list);
287         table = AHCI_DMA_KVA(ap->ap_dmamem_cmd_table);
288         for (i = 0; i < sc->sc_ncmds; i++) {
289                 ccb = &ap->ap_ccbs[i];
290
291                 error = bus_dmamap_create(sc->sc_tag_data, BUS_DMA_ALLOCNOW,
292                                           &ccb->ccb_dmamap);
293                 if (error) {
294                         device_printf(sc->sc_dev,
295                                       "unable to create dmamap for port %d "
296                                       "ccb %d\n", port, i);
297                         goto freeport;
298                 }
299
300                 callout_init(&ccb->ccb_timeout);
301                 ccb->ccb_slot = i;
302                 ccb->ccb_port = ap;
303                 ccb->ccb_cmd_hdr = &hdr[i];
304                 ccb->ccb_cmd_table = &table[i];
305                 dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_table) +
306                     ccb->ccb_slot * sizeof(struct ahci_cmd_table);
307                 ccb->ccb_cmd_hdr->ctba_hi = htole32((u_int32_t)(dva >> 32));
308                 ccb->ccb_cmd_hdr->ctba_lo = htole32((u_int32_t)dva);
309
310                 ccb->ccb_xa.fis =
311                     (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
312                 ccb->ccb_xa.packetcmd = ccb->ccb_cmd_table->acmd;
313                 ccb->ccb_xa.tag = i;
314
315                 ccb->ccb_xa.state = ATA_S_COMPLETE;
316                 ahci_put_ccb(ccb);
317         }
318
319         /* Wait for ICC change to complete */
320         ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_ICC);
321
322         /*
323          * Do device-related port initialization.  A failure here does not
324          * cause the port to be deallocated as we want to receive future
325          * hot-plug events.
326          */
327         ahci_port_init(ap, NULL);
328         return(0);
329 freeport:
330         ahci_port_free(sc, port);
331 reterr:
332         return (rc);
333 }
334
335 /*
336  * [re]initialize an idle port.  No CCBs should be active.
337  *
338  * If at is NULL we are initializing a directly connected port, otherwise
339  * we are indirectly initializing a port multiplier port.
340  *
341  * This function is called during the initial port allocation sequence
342  * and is also called on hot-plug insertion.  We take no chances and
343  * use a portreset instead of a softreset.
344  *
345  * This function is the only way to move a failed port back to active
346  * status.
347  *
348  * Returns 0 if a device is successfully detected.
349  */
350 int
351 ahci_port_init(struct ahci_port *ap, struct ata_port *at)
352 {
353         u_int32_t data;
354         int rc;
355
356         /*
357          * Clear all notification bits
358          */
359         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF)
360                 ahci_pwrite(ap, AHCI_PREG_SNTF, -1);
361
362         /*
363          * Hard-reset the port.  If a device is detected but it is busy
364          * we try a second time, this time cycling the phy as well.
365          */
366         ap->ap_probe = ATA_PROBE_NEED_HARD_RESET;
367         rc = ahci_port_reset(ap, at, 1);
368         if (rc == EBUSY) {
369                 rc = ahci_port_reset(ap, at, 2);
370         }
371
372         switch (rc) {
373         case ENODEV:
374                 /*
375                  * We had problems talking to the device on the port.
376                  */
377                 switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
378                 case AHCI_PREG_SSTS_DET_DEV_NE:
379                         kprintf("%s: Device not communicating\n", PORTNAME(ap));
380                         break;
381                 case AHCI_PREG_SSTS_DET_PHYOFFLINE:
382                         kprintf("%s: PHY offline\n", PORTNAME(ap));
383                         break;
384                 default:
385                         kprintf("%s: No device detected\n", PORTNAME(ap));
386                         break;
387                 }
388                 break;
389
390         case EBUSY:
391                 /*
392                  * The device on the port is still telling us its busy,
393                  * which means that it is not properly handling a SATA
394                  * port COMRESET.
395                  *
396                  * It may be possible to softreset the device using CLO
397                  * and a device reset command.
398                  */
399                 kprintf("%s: Device on port is bricked, trying softreset\n",
400                         PORTNAME(ap));
401
402                 rc = ahci_port_reset(ap, at, 0);
403                 if (rc) {
404                         kprintf("%s: Unable unbrick device\n",
405                                 PORTNAME(ap));
406                 } else {
407                         kprintf("%s: Successfully unbricked\n",
408                                 PORTNAME(ap));
409                 }
410                 break;
411
412         default:
413                 break;
414         }
415
416         /*
417          * Command transfers can only be enabled if a device was successfully
418          * detected.
419          *
420          * Allocate or deallocate the ap_ata array here too.
421          */
422         switch(ap->ap_type) {
423         case ATA_PORT_T_NONE:
424                 ap->ap_pmcount = 0;
425                 break;
426         case ATA_PORT_T_PM:
427                 /* already set */
428                 break;
429         default:
430                 ap->ap_pmcount = 1;
431                 break;
432         }
433
434         /*
435          * Start the port if we succeeded.
436          *
437          * There's nothing to start for devices behind a port multiplier.
438          */
439         if (rc == 0 && at == NULL) {
440                 if (ahci_port_start(ap)) {
441                         kprintf("%s: failed to start command DMA on port, "
442                                 "disabling\n", PORTNAME(ap));
443                         rc = ENXIO;     /* couldn't start port */
444                 }
445         }
446
447         /*
448          * Flush interupts on the port. XXX
449          *
450          * Enable interrupts on the port whether a device is sitting on
451          * it or not, to handle hot-plug events.
452          */
453         if (at == NULL) {
454                 ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
455                 ahci_write(ap->ap_sc, AHCI_REG_IS, 1 << ap->ap_num);
456
457                 data = AHCI_PREG_IE_TFEE | AHCI_PREG_IE_HBFE |
458                        AHCI_PREG_IE_IFE | AHCI_PREG_IE_OFE |
459                        AHCI_PREG_IE_DPE | AHCI_PREG_IE_UFE |
460                        AHCI_PREG_IE_PCE | AHCI_PREG_IE_PRCE |
461                        AHCI_PREG_IE_DHRE;
462                 if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF)
463                         data |= AHCI_PREG_IE_SDBE;
464 #ifdef AHCI_COALESCE
465                 if (sc->sc_ccc_ports & (1 << port)
466                         data &= ~(AHCI_PREG_IE_SDBE | AHCI_PREG_IE_DHRE);
467 #endif
468                 ahci_pwrite(ap, AHCI_PREG_IE, data);
469         }
470         return(rc);
471 }
472
473 /*
474  * De-initialize and detach a port.
475  */
476 void
477 ahci_port_free(struct ahci_softc *sc, u_int port)
478 {
479         struct ahci_port                *ap = sc->sc_ports[port];
480         struct ahci_ccb                 *ccb;
481
482         /*
483          * Ensure port is disabled and its interrupts are all flushed.
484          */
485         if (ap->ap_sc) {
486                 ahci_port_stop(ap, 1);
487                 ahci_pwrite(ap, AHCI_PREG_CMD, 0);
488                 ahci_pwrite(ap, AHCI_PREG_IE, 0);
489                 ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
490                 ahci_write(sc, AHCI_REG_IS, 1 << port);
491         }
492
493         if (ap->ap_ccbs) {
494                 while ((ccb = ahci_get_ccb(ap)) != NULL) {
495                         if (ccb->ccb_dmamap) {
496                                 bus_dmamap_destroy(sc->sc_tag_data,
497                                                    ccb->ccb_dmamap);
498                                 ccb->ccb_dmamap = NULL;
499                         }
500                 }
501                 kfree(ap->ap_ccbs, M_DEVBUF);
502                 ap->ap_ccbs = NULL;
503         }
504
505         if (ap->ap_dmamem_cmd_list) {
506                 ahci_dmamem_free(sc, ap->ap_dmamem_cmd_list);
507                 ap->ap_dmamem_cmd_list = NULL;
508         }
509         if (ap->ap_dmamem_rfis) {
510                 ahci_dmamem_free(sc, ap->ap_dmamem_rfis);
511                 ap->ap_dmamem_rfis = NULL;
512         }
513         if (ap->ap_dmamem_cmd_table) {
514                 ahci_dmamem_free(sc, ap->ap_dmamem_cmd_table);
515                 ap->ap_dmamem_cmd_table = NULL;
516         }
517         if (ap->ap_ata) {
518                 kfree(ap->ap_ata, M_DEVBUF);
519                 ap->ap_ata = NULL;
520         }
521
522         /* bus_space(9) says we dont free the subregions handle */
523
524         kfree(ap, M_DEVBUF);
525         sc->sc_ports[port] = NULL;
526 }
527
528 /*
529  * Start high-level command processing on the port
530  */
531 int
532 ahci_port_start(struct ahci_port *ap)
533 {
534         u_int32_t       r, oldr, s, olds, is, oldis;
535
536         /*
537          * FRE must be turned on before ST.  Wait for FR to go active
538          * before turning on ST.  The spec doesn't seem to think this
539          * is necessary but waiting here avoids an on-off race in the
540          * ahci_port_stop() code.
541          */
542         olds = ahci_pread(ap, AHCI_PREG_SERR);
543         oldis= ahci_pread(ap, AHCI_PREG_IS);
544         oldr = r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
545         if ((r & AHCI_PREG_CMD_FRE) == 0) {
546                 r |= AHCI_PREG_CMD_FRE;
547                 ahci_pwrite(ap, AHCI_PREG_CMD, r);
548         }
549         if ((ap->ap_sc->sc_flags & AHCI_F_IGN_FR) == 0) {
550                 if (ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR)) {
551                         kprintf("%s: Cannot start FIS reception\n",
552                                 PORTNAME(ap));
553                         return (2);
554                 }
555         }
556
557         /*
558          * Turn on ST, wait for CR to come up.
559          */
560         s = ahci_pread(ap, AHCI_PREG_SERR);
561         is = ahci_pread(ap, AHCI_PREG_IS);
562         r |= AHCI_PREG_CMD_ST;
563         ahci_pwrite(ap, AHCI_PREG_CMD, r);
564         if (ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CR)) {
565                 kprintf("%s: Cannot start command DMA\n"
566                         "OCMD=%b OSERR=%b\n"
567                         "NCMP=%b NSERR=%b\n"
568                         "OLDIS=%b\nNEWIS=%b",
569                         PORTNAME(ap),
570                         oldr, AHCI_PFMT_CMD, olds, AHCI_PFMT_SERR,
571                         r, AHCI_PFMT_CMD, s, AHCI_PFMT_SERR,
572                         oldis, AHCI_PFMT_IS, is, AHCI_PFMT_IS);
573                 return (1);
574         }
575
576 #ifdef AHCI_COALESCE
577         /*
578          * (Re-)enable coalescing on the port.
579          */
580         if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
581                 ap->ap_sc->sc_ccc_ports_cur |= (1 << ap->ap_num);
582                 ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
583                     ap->ap_sc->sc_ccc_ports_cur);
584         }
585 #endif
586
587         return (0);
588 }
589
590 /*
591  * Stop high-level command processing on a port
592  */
593 int
594 ahci_port_stop(struct ahci_port *ap, int stop_fis_rx)
595 {
596         u_int32_t                       r;
597
598 #ifdef AHCI_COALESCE
599         /*
600          * Disable coalescing on the port while it is stopped.
601          */
602         if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
603                 ap->ap_sc->sc_ccc_ports_cur &= ~(1 << ap->ap_num);
604                 ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
605                     ap->ap_sc->sc_ccc_ports_cur);
606         }
607 #endif
608
609         /*
610          * Turn off ST, then wait for CR to go off.
611          */
612         r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
613         r &= ~AHCI_PREG_CMD_ST;
614         ahci_pwrite(ap, AHCI_PREG_CMD, r);
615
616         if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CR)) {
617                 kprintf("%s: Port bricked, unable to stop (ST)\n",
618                         PORTNAME(ap));
619                 return (1);
620         }
621
622 #if 0
623         /*
624          * Turn off FRE, then wait for FR to go off.  FRE cannot
625          * be turned off until CR transitions to 0.
626          */
627         if ((r & AHCI_PREG_CMD_FR) == 0) {
628                 kprintf("%s: FR stopped, clear FRE for next start\n",
629                         PORTNAME(ap));
630                 stop_fis_rx = 2;
631         }
632 #endif
633         if (stop_fis_rx) {
634                 r &= ~AHCI_PREG_CMD_FRE;
635                 ahci_pwrite(ap, AHCI_PREG_CMD, r);
636                 if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR)) {
637                         kprintf("%s: Port bricked, unable to stop (FRE)\n",
638                                 PORTNAME(ap));
639                         return (2);
640                 }
641         }
642
643         return (0);
644 }
645
646 /*
647  * AHCI command list override -> forcibly clear TFD.STS.{BSY,DRQ}
648  */
649 int
650 ahci_port_clo(struct ahci_port *ap)
651 {
652         struct ahci_softc               *sc = ap->ap_sc;
653         u_int32_t                       cmd;
654
655         /* Only attempt CLO if supported by controller */
656         if ((ahci_read(sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO) == 0)
657                 return (1);
658
659         /* Issue CLO */
660         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
661 #ifdef DIAGNOSTIC
662         if (cmd & AHCI_PREG_CMD_ST) {
663                 kprintf("%s: CLO requested while port running\n",
664                         PORTNAME(ap));
665         }
666 #endif
667         ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_CLO);
668
669         /* Wait for completion */
670         if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CLO)) {
671                 kprintf("%s: CLO did not complete\n", PORTNAME(ap));
672                 return (1);
673         }
674
675         return (0);
676 }
677
678 /*
679  * Reset a port.
680  *
681  * If hard is 0 perform a softreset of the port.
682  * If hard is 1 perform a hard reset of the port.
683  * If hard is 2 perform a hard reset of the port and cycle the phy.
684  *
685  * If at is non-NULL an indirect port via a port-multiplier is being
686  * reset, otherwise a direct port is being reset.
687  *
688  * NOTE: Indirect ports can only be soft-reset.
689  */
690 int
691 ahci_port_reset(struct ahci_port *ap, struct ata_port *at, int hard)
692 {
693         int rc;
694
695         if (hard) {
696                 if (at)
697                         rc = ahci_pm_hardreset(ap, at->at_target, hard);
698                 else
699                         rc = ahci_port_hardreset(ap, hard);
700         } else {
701                 if (at)
702                         rc = ahci_pm_softreset(ap, at->at_target);
703                 else
704                         rc = ahci_port_softreset(ap);
705 #if 0
706                 if (rc && at == NULL)
707                         rc = ahci_port_hardreset(ap, hard);
708 #endif
709         }
710         return(rc);
711 }
712
713 /*
714  * AHCI soft reset, Section 10.4.1
715  *
716  * (at) will be NULL when soft-resetting a directly-attached device, and
717  * non-NULL when soft-resetting a device through a port multiplier.
718  *
719  * This function keeps port communications intact and attempts to generate
720  * a reset to the connected device using device commands.
721  */
722 int
723 ahci_port_softreset(struct ahci_port *ap)
724 {
725         struct ahci_ccb         *ccb = NULL;
726         struct ahci_cmd_hdr     *cmd_slot;
727         u_int8_t                *fis;
728         int                     rc, count;
729         u_int32_t               cmd;
730
731         rc = EIO;
732         count = 10;     /* device reset delay x 100ms */
733
734         kprintf("%s: START SOFTRESET %b\n", PORTNAME(ap),
735                 ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD);
736
737         DPRINTF(AHCI_D_VERBOSE, "%s: soft reset\n", PORTNAME(ap));
738
739         crit_enter();
740         ap->ap_flags |= AP_F_IN_RESET;
741         ap->ap_state = AP_S_NORMAL;
742
743         /*
744          * Remember port state in cmd (main to restore start/stop)
745          *
746          * Idle port.
747          */
748         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
749         if (ahci_port_stop(ap, 0)) {
750                 kprintf("%s: failed to stop port, cannot softreset\n",
751                         PORTNAME(ap));
752                 goto err;
753         }
754
755         /*
756          * Request CLO if device appears hung.
757          */
758         if (ahci_pread(ap, AHCI_PREG_TFD) &
759                    (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
760                 ahci_port_clo(ap);
761         }
762
763         /*
764          * This is an attempt to clear errors so a new signature will
765          * be latched.  It isn't working properly.  XXX
766          */
767         ahci_flush_tfd(ap);
768         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
769
770         /* Restart port */
771         if (ahci_port_start(ap)) {
772                 kprintf("%s: failed to start port, cannot softreset\n",
773                         PORTNAME(ap));
774                 goto err;
775         }
776
777         /* Check whether CLO worked */
778         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
779                                AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
780                 kprintf("%s: CLO %s, need port reset\n",
781                         PORTNAME(ap),
782                         (ahci_read(ap->ap_sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO)
783                         ? "failed" : "unsupported");
784                 rc = EBUSY;
785                 goto err;
786         }
787
788         /*
789          * Prep first D2H command with SRST feature & clear busy/reset flags
790          *
791          * It is unclear which other fields in the FIS are used.  Just zero
792          * everything.
793          */
794         ccb = ahci_get_err_ccb(ap);
795         ccb->ccb_xa.at = NULL;
796         cmd_slot = ccb->ccb_cmd_hdr;
797
798         fis = ccb->ccb_cmd_table->cfis;
799         bzero(fis, sizeof(ccb->ccb_cmd_table->cfis));
800         fis[0] = ATA_FIS_TYPE_H2D;
801         fis[15] = ATA_FIS_CONTROL_SRST|ATA_FIS_CONTROL_4BIT;
802
803         cmd_slot->prdtl = 0;
804         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
805         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_C); /* Clear busy on OK */
806         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_R); /* Reset */
807
808         ccb->ccb_xa.state = ATA_S_PENDING;
809         ccb->ccb_xa.flags = 0;
810         if (ahci_poll(ccb, hz, NULL) != 0 ||
811             ccb->ccb_xa.state != ATA_S_COMPLETE) {
812                 kprintf("%s: First FIS failed\n", PORTNAME(ap));
813                 goto err;
814         }
815
816         /*
817          * The device may muff the PHY up.
818          */
819         DELAY(10000);   /* XXX 3000 */
820
821         /*
822          * Prep second D2H command to read status and complete reset sequence
823          * AHCI 10.4.1 and "Serial ATA Revision 2.6".  I can't find the ATA
824          * Rev 2.6 and it is unclear how the second FIS should be set up
825          * from the AHCI document.
826          *
827          * Give the device 3ms before sending the second FIS.
828          *
829          * It is unclear which other fields in the FIS are used.  Just zero
830          * everything.
831          */
832         bzero(fis, sizeof(ccb->ccb_cmd_table->cfis));
833         fis[0] = ATA_FIS_TYPE_H2D;
834         fis[15] = ATA_FIS_CONTROL_4BIT;
835
836         cmd_slot->prdtl = 0;
837         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
838
839         ccb->ccb_xa.state = ATA_S_PENDING;
840         ccb->ccb_xa.flags = 0;
841         if (ahci_poll(ccb, hz, NULL) != 0 ||
842             ccb->ccb_xa.state != ATA_S_COMPLETE) {
843                 kprintf("%s: Second FIS failed\n", PORTNAME(ap));
844                 goto err;
845         }
846
847         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
848                             AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
849                 kprintf("%s: device didn't come ready after reset, TFD: 0x%b\n",
850                         PORTNAME(ap),
851                         ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
852                 rc = EBUSY;
853                 goto err;
854         }
855         DELAY(10000);
856
857         /*
858          * If the softreset is trying to clear a BSY condition after a
859          * normal portreset we assign the port type.
860          *
861          * If the softreset is being run first as part of the ccb error
862          * processing code then report if the device signature changed
863          * unexpectedly.
864          */
865         if (ap->ap_type == ATA_PORT_T_NONE) {
866                 ap->ap_type = ahci_port_signature_detect(ap, NULL);
867         } else {
868                 if (ahci_port_signature_detect(ap, NULL) != ap->ap_type) {
869                         kprintf("%s: device signature unexpectedly "
870                                 "changed\n", PORTNAME(ap));
871                         rc = EBUSY; /* XXX */
872                 }
873         }
874         rc = 0;
875
876         DELAY(3000);
877 err:
878         if (ccb != NULL) {
879                 /*
880                  * Abort our command, if it failed, by stopping command DMA.
881                  */
882                 if (rc && (ap->ap_active & (1 << ccb->ccb_slot))) {
883                         kprintf("%s: stopping the port, softreset slot "
884                                 "%d was still active.\n",
885                                 PORTNAME(ap),
886                                 ccb->ccb_slot);
887                         ahci_port_stop(ap, 0);
888                 }
889                 ccb->ccb_xa.state = ATA_S_ERROR;
890                 fis[15] = 0;
891                 ahci_put_err_ccb(ccb);
892
893                 /*
894                  * If the target is busy use CLO to clear the busy
895                  * condition.  The BSY should be cleared on the next
896                  * start.
897                  */
898                 if (ahci_pread(ap, AHCI_PREG_TFD) &
899                     (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
900                         ahci_port_clo(ap);
901                 }
902         }
903
904         /*
905          * If we failed to softreset make the port quiescent, otherwise
906          * make sure the port's start/stop state matches what it was on
907          * entry.
908          *
909          * Don't kill the port if the softreset is on a port multiplier
910          * target, that would kill all the targets!
911          */
912         if (rc) {
913                 ahci_port_hardstop(ap);
914         } else if (cmd & AHCI_PREG_CMD_ST) {
915                 kprintf("%s: STARTING PORT\n", PORTNAME(ap));
916                 ahci_port_start(ap);
917         } else {
918                 kprintf("%s: STOPPING PORT\n", PORTNAME(ap));
919                 ahci_port_stop(ap, !(cmd & AHCI_PREG_CMD_FRE));
920         }
921         if (rc)
922                 ap->ap_probe = ATA_PROBE_FAILED;
923         else
924                 ap->ap_probe = ATA_PROBE_NEED_IDENT;
925
926         crit_exit();
927
928         kprintf("%s: END SOFTRESET\n", PORTNAME(ap));
929         ap->ap_flags &= ~AP_F_IN_RESET;
930
931         return (rc);
932 }
933
934 /*
935  * AHCI port reset, Section 10.4.2
936  *
937  * This function does a hard reset of the port.  Note that the device
938  * connected to the port could still end-up hung.
939  */
940 int
941 ahci_port_hardreset(struct ahci_port *ap, int hard)
942 {
943         u_int32_t cmd, r;
944         int     rc;
945         int     loop;
946         int     type;
947
948         DPRINTF(AHCI_D_VERBOSE, "%s: port reset\n", PORTNAME(ap));
949
950         ap->ap_flags |= AP_F_IN_RESET;
951
952         /*
953          * Idle the port,
954          */
955         ahci_port_stop(ap, 0);
956         ap->ap_state = AP_S_NORMAL;
957         ap->ap_probe = ATA_PROBE_FAILED;
958         rc = 0;
959
960         /*
961          * The port may have been quiescent with its SUD bit cleared, so
962          * set the SUD (spin up device).
963          */
964         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
965         cmd |= AHCI_PREG_CMD_SUD;
966         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
967
968         /*
969          * Perform device detection.  Cycle the PHY off, wait 10ms.
970          * This simulates the SATA cable being physically unplugged.
971          */
972         ap->ap_type = ATA_PORT_T_NONE;
973
974         r = AHCI_PREG_SCTL_IPM_DISABLED;
975         if (hard == 2)
976                 r |= AHCI_PREG_SCTL_DET_DISABLE;
977         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
978         DELAY(10000);
979
980         /*
981          * Start transmitting COMRESET.  COMRESET must be sent for at
982          * least 1ms.
983          */
984         r = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_INIT;
985         if (AhciForceGen1 & (1 << ap->ap_num)) {
986                 kprintf("%s: Force 1.5Gbits\n", PORTNAME(ap));
987                 r |= AHCI_PREG_SCTL_SPD_GEN1;
988         } else {
989                 r |= AHCI_PREG_SCTL_SPD_ANY;
990         }
991         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
992         DELAY(1000);
993
994         /*
995          * Only SERR_DIAG_X needs to be cleared for TFD updates, but
996          * since we are hard-resetting the port we might as well clear
997          * the whole enchillada
998          */
999         ahci_flush_tfd(ap);
1000         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1001         r &= ~AHCI_PREG_SCTL_DET_INIT;
1002         r |= AHCI_PREG_SCTL_DET_NONE;
1003         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1004
1005         /*
1006          * Try to determine if there is a device on the port.
1007          *
1008          * Give the device 3/10 second to at least be detected.
1009          * If we fail clear PRCS (phy detect) since we may cycled
1010          * the phy and probably caused another PRCS interrupt.
1011          */
1012         for (loop = 30; loop; --loop) {
1013                 r = ahci_pread(ap, AHCI_PREG_SSTS);
1014                 if (r & AHCI_PREG_SSTS_DET)
1015                         break;
1016                 DELAY(10000);
1017         }
1018         if (loop == 0) {
1019                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_PRCS);
1020                 kprintf("%s: Port appears to be unplugged\n",
1021                         PORTNAME(ap));
1022                 rc = ENODEV;
1023         }
1024
1025         /*
1026          * There is something on the port.  Give the device 3 seconds
1027          * to fully negotiate.
1028          */
1029         if (rc == 0 &&
1030             ahci_pwait_eq(ap, 3000, AHCI_PREG_SSTS,
1031                           AHCI_PREG_SSTS_DET, AHCI_PREG_SSTS_DET_DEV)) {
1032                 kprintf("%s: Device may be powered down\n",
1033                         PORTNAME(ap));
1034                 rc = ENODEV;
1035         }
1036
1037         /*
1038          * Wait for the device to become ready.
1039          *
1040          * This can take more then a second, give it 3 seconds.  If we
1041          * succeed give the device another 3ms after that.
1042          *
1043          * NOTE: Port Multipliers can do two things here.  First they can
1044          *       return device-ready if a device is on target 0 and also
1045          *       return the signature for that device.  If there is no
1046          *       device on target 0 then BSY/DRQ is never cleared and
1047          *       it never comes ready.
1048          */
1049         if (rc == 0 &&
1050             ahci_pwait_clr_to(ap, 3000, AHCI_PREG_TFD,
1051                             AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1052                 /*
1053                  * The device is bricked or its a port multiplier and will
1054                  * not unbusy until we do the pmprobe CLO softreset sequence.
1055                  */
1056                 rc = ahci_port_pmprobe(ap);
1057                 if (rc) {
1058                         kprintf("%s: Device will not come ready 0x%b\n",
1059                                 PORTNAME(ap),
1060                                 ahci_pread(ap, AHCI_PREG_TFD),
1061                                 AHCI_PFMT_TFD_STS);
1062                 } else {
1063                         ap->ap_type = ATA_PORT_T_PM;
1064                         ap->ap_probe = ATA_PROBE_NEED_SOFT_RESET;
1065                         kprintf("%s: Port Multiplier detected\n",
1066                                 PORTNAME(ap));
1067                 }
1068         } else if (rc == 0) {
1069                 /*
1070                  * We generally will not get a port multiplier signature in
1071                  * this case even if this is a port multiplier, because of
1072                  * Intel's stupidity.  We almost certainly got target 0
1073                  * behind the PM, if there is a PM.
1074                  *
1075                  * Save the signature and probe for a PM.  If we do not
1076                  * find a PM then use the saved signature and return
1077                  * success.
1078                  */
1079                 type = ahci_port_signature_detect(ap, NULL);
1080                 rc = ahci_port_pmprobe(ap);
1081                 if (rc) {
1082                         ap->ap_type = type;
1083                         ap->ap_probe = ATA_PROBE_NEED_SOFT_RESET;
1084                         rc = 0;
1085                 } else {
1086                         ap->ap_type = ATA_PORT_T_PM;
1087                         ap->ap_probe = ATA_PROBE_NEED_SOFT_RESET;
1088                         kprintf("%s: Port Multiplier detected\n",
1089                                 PORTNAME(ap));
1090                 }
1091         }
1092
1093         /*
1094          * hard-stop the port if we failed.  This will set ap_probe
1095          * to FAILED.
1096          */
1097         if (rc)
1098                 ahci_port_hardstop(ap);
1099         ap->ap_flags &= ~AP_F_IN_RESET;
1100         return (rc);
1101 }
1102
1103 /*
1104  * AHCI port multiplier probe.  This routine is run by the hardreset code
1105  * if it gets past the device detect, whether or not BSY is found to be
1106  * stuck.
1107  *
1108  * We MUST use CLO to properly probe whether the port multiplier exists
1109  * or not.
1110  *
1111  * Return 0 on success, non-zero on failure.
1112  */
1113 int
1114 ahci_port_pmprobe(struct ahci_port *ap)
1115 {
1116         struct ahci_cmd_hdr *cmd_slot;
1117         struct ahci_ccb *ccb = NULL;
1118         u_int8_t        *fis = NULL;
1119         int             rc = EIO;
1120         u_int32_t       cmd;
1121         int             count;
1122
1123         /*
1124          * If we don't support port multipliers don't try to detect one.
1125          */
1126         if ((ap->ap_sc->sc_cap & AHCI_REG_CAP_SPM) == 0)
1127                 return (ENODEV);
1128
1129         count = 2;
1130 #if 0
1131         kprintf("%s: START PMPROBE\n", PORTNAME(ap));
1132 #endif
1133 retry:
1134         /*
1135          * This code is only called from hardreset, which does not
1136          * high level command processing.  The port should be stopped.
1137          *
1138          * Set PMA mode while the port is stopped.
1139          *
1140          * NOTE: On retry the port might be running, stopped, or failed.
1141          */
1142         ahci_port_stop(ap, 0);
1143         ap->ap_state = AP_S_NORMAL;
1144         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1145         cmd |= AHCI_PREG_CMD_PMA;
1146         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1147
1148         /*
1149          * Flush any errors and request CLO unconditionally, then start
1150          * the port.
1151          */
1152         ahci_flush_tfd(ap);
1153         ahci_port_clo(ap);
1154         if (ahci_port_start(ap)) {
1155                 kprintf("%s: PMPROBE failed to start port, cannot softreset\n",
1156                         PORTNAME(ap));
1157                 goto err;
1158         }
1159
1160         /*
1161          * Check whether CLO worked
1162          */
1163         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1164                                AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1165                 kprintf("%s: PMPROBE CLO %s, need port reset\n",
1166                         PORTNAME(ap),
1167                         (ahci_read(ap->ap_sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO)
1168                         ? "failed" : "unsupported");
1169                 rc = EBUSY;
1170                 goto err;
1171         }
1172
1173         /*
1174          * Prep the first H2D command with SRST feature & clear busy/reset
1175          * flags.
1176          */
1177         ccb = ahci_get_err_ccb(ap);
1178         cmd_slot = ccb->ccb_cmd_hdr;
1179
1180         fis = ccb->ccb_cmd_table->cfis;
1181         bzero(fis, sizeof(ccb->ccb_cmd_table->cfis));
1182         fis[0] = ATA_FIS_TYPE_H2D;
1183         fis[1] = 0x0F;                  /* Target 15 */
1184         fis[15] = ATA_FIS_CONTROL_SRST | ATA_FIS_CONTROL_4BIT;
1185
1186         cmd_slot->prdtl = 0;
1187         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
1188         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_C); /* Clear busy on OK */
1189         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_R); /* Reset */
1190         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_PMP); /* port 0xF */
1191
1192         ccb->ccb_xa.state = ATA_S_PENDING;
1193         ccb->ccb_xa.flags = 0;
1194
1195         if (ahci_poll(ccb, hz, NULL) != 0 ||
1196             ccb->ccb_xa.state != ATA_S_COMPLETE) {
1197                 kprintf("%s: PMPROBE First FIS failed\n", PORTNAME(ap));
1198                 if (--count) {
1199                         fis[15] = 0;
1200                         ahci_put_err_ccb(ccb);
1201                         goto retry;
1202                 }
1203                 goto err;
1204         }
1205         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1206                                AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1207                 kprintf("%s: PMPROBE Busy after first FIS\n", PORTNAME(ap));
1208         }
1209
1210         /*
1211          * The device may have muffed up the PHY when it reset.
1212          */
1213         DELAY(10000);
1214         ahci_flush_tfd(ap);
1215         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1216         /* ahci_pm_phy_status(ap, 15, &cmd); */
1217
1218         /*
1219          * Prep second D2H command to read status and complete reset sequence
1220          * AHCI 10.4.1 and "Serial ATA Revision 2.6".  I can't find the ATA
1221          * Rev 2.6 and it is unclear how the second FIS should be set up
1222          * from the AHCI document.
1223          *
1224          * Give the device 3ms before sending the second FIS.
1225          *
1226          * It is unclear which other fields in the FIS are used.  Just zero
1227          * everything.
1228          */
1229         bzero(fis, sizeof(ccb->ccb_cmd_table->cfis));
1230         fis[0] = ATA_FIS_TYPE_H2D;
1231         fis[1] = 0x0F;
1232         fis[15] = ATA_FIS_CONTROL_4BIT;
1233
1234         cmd_slot->prdtl = 0;
1235         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
1236         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_PMP); /* port 0xF */
1237
1238         ccb->ccb_xa.state = ATA_S_PENDING;
1239         ccb->ccb_xa.flags = 0;
1240
1241         if (ahci_poll(ccb, hz, NULL) != 0 ||
1242             ccb->ccb_xa.state != ATA_S_COMPLETE) {
1243                 kprintf("%s: PMPROBE Second FIS failed\n", PORTNAME(ap));
1244                 if (--count) {
1245                         fis[15] = 0;
1246                         ahci_put_err_ccb(ccb);
1247                         goto retry;
1248                 }
1249                 goto err;
1250         }
1251
1252         /*
1253          * What? We succeeded?  Yup, but for some reason the signature
1254          * is still latched from the original detect (that saw target 0
1255          * behind the PM), and I don't know how to clear the condition
1256          * other then by retrying the whole reset sequence.
1257          */
1258         if (--count) {
1259                 fis[15] = 0;
1260                 ahci_put_err_ccb(ccb);
1261                 goto retry;
1262         }
1263
1264         /*
1265          * Get the signature.  The caller sets the ap fields.
1266          */
1267         if (ahci_port_signature_detect(ap, NULL) == ATA_PORT_T_PM) {
1268                 ap->ap_ata[15].at_probe = ATA_PROBE_GOOD;
1269                 rc = 0;
1270         } else {
1271                 rc = EBUSY;
1272         }
1273
1274         /*
1275          * Fall through / clean up the CCB and perform error processing.
1276          */
1277 err:
1278         if (ccb != NULL) {
1279                 /*
1280                  * Abort our command, if it failed, by stopping command DMA.
1281                  */
1282 #if 0
1283                 kprintf("rc=%d active=%08x sactive=%08x slot=%d\n",
1284                         rc, ap->ap_active, ap->ap_sactive, ccb->ccb_slot);
1285 #endif
1286                 if (rc && (ap->ap_active & (1 << ccb->ccb_slot))) {
1287                         kprintf("%s: PMP stopping the port, softreset slot "
1288                                 "%d was still active.\n",
1289                                 PORTNAME(ap),
1290                                 ccb->ccb_slot);
1291                         ahci_port_stop(ap, 0);
1292                 }
1293                 ccb->ccb_xa.state = ATA_S_ERROR;
1294                 fis[15] = 0;
1295                 ahci_put_err_ccb(ccb);
1296         }
1297
1298         /*
1299          * If we failed turn off PMA, otherwise identify the port multiplier.
1300          * CAM will iterate the devices.
1301          */
1302         if (rc) {
1303                 ahci_port_stop(ap, 0);
1304                 cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1305                 cmd &= ~AHCI_PREG_CMD_PMA;
1306                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1307         } else {
1308                 ahci_pm_identify(ap);
1309 #if 0
1310                 ahci_pm_hardreset(ap, 0);
1311                 ahci_pm_hardreset(ap, 1);
1312                 ahci_pm_hardreset(ap, 2);
1313                 ahci_pm_hardreset(ap, 3);
1314                 ahci_pm_hardreset(ap, 4);
1315 #endif
1316         }
1317         ahci_port_stop(ap, 0);
1318
1319 #if 0
1320         kprintf("%s: END PMPROBE\n", PORTNAME(ap));
1321 #endif
1322
1323         return(rc);
1324 }
1325
1326
1327 /*
1328  * Hard-stop on hot-swap device removal.  See 10.10.1
1329  *
1330  * Place the port in a mode that will allow it to detect hot-swap insertions.
1331  * This is a bit imprecise because just setting-up SCTL to DET_INIT doesn't
1332  * seem to do the job.
1333  */
1334 void
1335 ahci_port_hardstop(struct ahci_port *ap)
1336 {
1337         struct ata_port *at;
1338         u_int32_t r;
1339         u_int32_t cmd;
1340         int i;
1341
1342         /*
1343          * Stop the port.  We can't modify things like SUD if the port
1344          * is running.
1345          */
1346         ap->ap_state = AP_S_FATAL_ERROR;
1347         ap->ap_probe = ATA_PROBE_FAILED;
1348         ap->ap_type = ATA_PORT_T_NONE;
1349         ahci_port_stop(ap, 0);
1350         cmd = ahci_pread(ap, AHCI_PREG_CMD);
1351
1352         /*
1353          * Clean up AT sub-ports on SATA port.
1354          */
1355         for (i = 0; ap->ap_ata && i < AHCI_MAX_PMPORTS; ++i) {
1356                 at = &ap->ap_ata[i];
1357                 at->at_type = ATA_PORT_T_NONE;
1358                 at->at_probe = ATA_PORT_T_NONE;
1359         }
1360
1361         /*
1362          * Turn off port-multiplier control bit
1363          */
1364         if (cmd & AHCI_PREG_CMD_PMA) {
1365                 cmd &= ~AHCI_PREG_CMD_PMA;
1366                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1367         }
1368
1369         /*
1370          * Make sure FRE is active.  There isn't anything we can do if it
1371          * fails so just ignore errors.
1372          */
1373         if ((cmd & AHCI_PREG_CMD_FRE) == 0) {
1374                 cmd |= AHCI_PREG_CMD_FRE;
1375                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1376                 if ((ap->ap_sc->sc_flags & AHCI_F_IGN_FR) == 0)
1377                         ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR);
1378         }
1379
1380         /*
1381          * 10.10.3 DET must be set to 0 before setting SUD to 0.
1382          * 10.10.1 place us in the Listen state.
1383          *
1384          * Deactivating SUD only applies if the controller supports SUD.
1385          */
1386         ahci_pwrite(ap, AHCI_PREG_SCTL, AHCI_PREG_SCTL_IPM_DISABLED);
1387         DELAY(1000);
1388         if (cmd & AHCI_PREG_CMD_SUD) {
1389                 cmd &= ~AHCI_PREG_CMD_SUD;
1390                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1391         }
1392         DELAY(1000);
1393
1394         /*
1395          * Transition su to the spin-up state.  HVA shall send COMRESET and
1396          * begin initialization sequence (whatever that means).
1397          *
1398          * This only applies if the controller supports SUD.
1399          */
1400         cmd |= AHCI_PREG_CMD_SUD;
1401         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1402         DELAY(1000);
1403
1404         /*
1405          * Transition us to the Reset state.  Theoretically we send a
1406          * continuous stream of COMRESETs in this state.
1407          */
1408         r = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_INIT;
1409         if (AhciForceGen1 & (1 << ap->ap_num)) {
1410                 kprintf("%s: Force 1.5Gbits\n", PORTNAME(ap));
1411                 r |= AHCI_PREG_SCTL_SPD_GEN1;
1412         } else {
1413                 r |= AHCI_PREG_SCTL_SPD_ANY;
1414         }
1415         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1416         DELAY(1000);
1417
1418         /*
1419          * Flush SERR_DIAG_X so the TFD can update.
1420          */
1421         ahci_flush_tfd(ap);
1422
1423         /*
1424          * Leave us in COMRESET (both SUD and INIT active), the HBA should
1425          * hopefully send us a DIAG_X-related interrupt if it receives
1426          * a COMINIT, and if not that then at least a Phy transition
1427          * interrupt.
1428          *
1429          * If we transition INIT from 1->0 to begin the initalization
1430          * sequence it is unclear if that sequence will remain active
1431          * until the next device insertion.
1432          *
1433          * If we go back to the listen state it is unclear if the
1434          * device will actually send us a COMINIT, since we aren't
1435          * sending any COMRESET's
1436          */
1437         /* NOP */
1438 }
1439
1440 /*
1441  * Multiple events may have built up in the TFD.  The spec is not very
1442  * clear on this but it does seem to serialize events so clearing DIAG_X
1443  * just once might not do the job during a reset sequence.
1444  */
1445 void
1446 ahci_flush_tfd(struct ahci_port *ap)
1447 {
1448         u_int32_t r;
1449
1450         r = ahci_pread(ap, AHCI_PREG_SERR);
1451         while (r & AHCI_PREG_SERR_DIAG_X) {
1452                 ahci_pwrite(ap, AHCI_PREG_SERR, AHCI_PREG_SERR_DIAG_X);
1453                 DELAY(1000);
1454                 r = ahci_pread(ap, AHCI_PREG_SERR);
1455         }
1456 }
1457
1458 /*
1459  * Figure out what type of device is connected to the port, ATAPI or
1460  * DISK.
1461  */
1462 int
1463 ahci_port_signature_detect(struct ahci_port *ap, struct ata_port *at)
1464 {
1465         u_int32_t sig;
1466
1467         sig = ahci_pread(ap, AHCI_PREG_SIG);
1468         kprintf("%s: sig %08x\n", ATANAME(ap, at), sig);
1469         if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000)) {
1470                 return(ATA_PORT_T_ATAPI);
1471         } else if ((sig & 0xffff0000) ==
1472                  (SATA_SIGNATURE_PORT_MULTIPLIER & 0xffff0000)) {
1473                 kprintf("found PM\n");
1474                 return(ATA_PORT_T_PM);
1475         } else {
1476                 return(ATA_PORT_T_DISK);
1477         }
1478 }
1479
1480 /*
1481  * Load the DMA descriptor table for a CCB's buffer.
1482  */
1483 int
1484 ahci_load_prdt(struct ahci_ccb *ccb)
1485 {
1486         struct ahci_port                *ap = ccb->ccb_port;
1487         struct ahci_softc               *sc = ap->ap_sc;
1488         struct ata_xfer                 *xa = &ccb->ccb_xa;
1489         struct ahci_prdt                *prdt = ccb->ccb_cmd_table->prdt;
1490         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1491         struct ahci_cmd_hdr             *cmd_slot = ccb->ccb_cmd_hdr;
1492         int                             error;
1493
1494         if (xa->datalen == 0) {
1495                 ccb->ccb_cmd_hdr->prdtl = 0;
1496                 return (0);
1497         }
1498
1499         error = bus_dmamap_load(sc->sc_tag_data, dmap,
1500                                 xa->data, xa->datalen,
1501                                 ahci_load_prdt_callback,
1502                                 &prdt,
1503                                 ((xa->flags & ATA_F_NOWAIT) ?
1504                                     BUS_DMA_NOWAIT : BUS_DMA_WAITOK));
1505         if (error != 0) {
1506                 kprintf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
1507                 return (1);
1508         }
1509         if (xa->flags & ATA_F_PIO)
1510                 prdt->flags |= htole32(AHCI_PRDT_FLAG_INTR);
1511
1512         cmd_slot->prdtl = htole16(prdt - ccb->ccb_cmd_table->prdt + 1);
1513
1514         bus_dmamap_sync(sc->sc_tag_data, dmap,
1515                         (xa->flags & ATA_F_READ) ?
1516                             BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
1517
1518         return (0);
1519
1520 #ifdef DIAGNOSTIC
1521 diagerr:
1522         bus_dmamap_unload(sc->sc_tag_data, dmap);
1523         return (1);
1524 #endif
1525 }
1526
1527 /*
1528  * Callback from BUSDMA system to load the segment list.  The passed segment
1529  * list is a temporary structure.
1530  */
1531 static
1532 void
1533 ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs, int nsegs,
1534                         int error)
1535 {
1536         struct ahci_prdt *prd = *(void **)info;
1537         u_int64_t addr;
1538
1539         KKASSERT(nsegs <= AHCI_MAX_PRDT);
1540
1541         while (nsegs) {
1542                 addr = segs->ds_addr;
1543                 prd->dba_hi = htole32((u_int32_t)(addr >> 32));
1544                 prd->dba_lo = htole32((u_int32_t)addr);
1545 #ifdef DIAGNOSTIC
1546                 KKASSERT((addr & 1) == 0);
1547                 KKASSERT((segs->ds_len & 1) == 0);
1548 #endif
1549                 prd->flags = htole32(segs->ds_len - 1);
1550                 --nsegs;
1551                 if (nsegs)
1552                         ++prd;
1553                 ++segs;
1554         }
1555         *(void **)info = prd;   /* return last valid segment */
1556 }
1557
1558 void
1559 ahci_unload_prdt(struct ahci_ccb *ccb)
1560 {
1561         struct ahci_port                *ap = ccb->ccb_port;
1562         struct ahci_softc               *sc = ap->ap_sc;
1563         struct ata_xfer                 *xa = &ccb->ccb_xa;
1564         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1565
1566         if (xa->datalen != 0) {
1567                 bus_dmamap_sync(sc->sc_tag_data, dmap,
1568                                 (xa->flags & ATA_F_READ) ?
1569                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1570
1571                 bus_dmamap_unload(sc->sc_tag_data, dmap);
1572
1573                 if (ccb->ccb_xa.flags & ATA_F_NCQ)
1574                         xa->resid = 0;
1575                 else
1576                         xa->resid = xa->datalen -
1577                             le32toh(ccb->ccb_cmd_hdr->prdbc);
1578         }
1579 }
1580
1581 /*
1582  * Start a command and poll for completion.
1583  *
1584  * NOTE: If the caller specifies a NULL timeout function the caller is
1585  *       responsible for clearing hardware state on failure, but we will
1586  *       deal with removing the ccb from any pending queue.
1587  *
1588  * NOTE: NCQ should never be used with this function.
1589  *
1590  * NOTE: If the port is in a failed state and stopped we do not try
1591  *       to activate the ccb.
1592  */
1593 int
1594 ahci_poll(struct ahci_ccb *ccb, int timeout, void (*timeout_fn)(void *))
1595 {
1596         struct ahci_port *ap = ccb->ccb_port;
1597         u_int32_t       slot_mask = 1 << ccb->ccb_slot;
1598
1599         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR) {
1600                 ccb->ccb_xa.state = ATA_S_ERROR;
1601                 return(1);
1602         }
1603         crit_enter();
1604         ahci_start(ccb);
1605
1606         do {
1607                 if (ahci_port_intr(ap, AHCI_PREG_CI_ALL_SLOTS) & slot_mask) {
1608                         crit_exit();
1609                         return (0);
1610                 }
1611                 if (ccb->ccb_xa.state != ATA_S_ONCHIP &&
1612                     ccb->ccb_xa.state != ATA_S_PENDING) {
1613                         break;
1614                 }
1615                 DELAY(1000000 / hz);
1616         } while (--timeout > 0);
1617
1618         if (ccb->ccb_xa.state != ATA_S_ONCHIP &&
1619             ccb->ccb_xa.state != ATA_S_PENDING) {
1620                 kprintf("%s: Warning poll completed unexpectedly for slot %d\n",
1621                         PORTNAME(ap), ccb->ccb_slot);
1622                 crit_exit();
1623                 return (0);
1624         }
1625
1626         kprintf("%s: Poll timed-out for slot %d state %d\n",
1627                 ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot, ccb->ccb_xa.state);
1628
1629         if (timeout_fn != NULL) {
1630                 timeout_fn(ccb);
1631         } else {
1632                 if (ccb->ccb_xa.state == ATA_S_PENDING)
1633                         TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1634                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1635         }
1636         crit_exit();
1637
1638         return (1);
1639 }
1640
1641 void
1642 ahci_start(struct ahci_ccb *ccb)
1643 {
1644         struct ahci_port                *ap = ccb->ccb_port;
1645         struct ahci_softc               *sc = ap->ap_sc;
1646
1647         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
1648
1649         /* Zero transferred byte count before transfer */
1650         ccb->ccb_cmd_hdr->prdbc = 0;
1651
1652         /* Sync command list entry and corresponding command table entry */
1653         bus_dmamap_sync(sc->sc_tag_cmdh,
1654                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
1655                         BUS_DMASYNC_PREWRITE);
1656         bus_dmamap_sync(sc->sc_tag_cmdt,
1657                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
1658                         BUS_DMASYNC_PREWRITE);
1659
1660         /* Prepare RFIS area for write by controller */
1661         bus_dmamap_sync(sc->sc_tag_rfis,
1662                         AHCI_DMA_MAP(ap->ap_dmamem_rfis),
1663                         BUS_DMASYNC_PREREAD);
1664
1665         if (ccb->ccb_xa.flags & ATA_F_NCQ) {
1666                 /*
1667                  * Issue NCQ commands only when there are no outstanding
1668                  * standard commands.
1669                  */
1670                 if (ap->ap_active || TAILQ_FIRST(&ap->ap_ccb_pending)) {
1671                         TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1672                 } else {
1673                         KKASSERT(ap->ap_active_cnt == 0);
1674                         ap->ap_sactive |= (1 << ccb->ccb_slot);
1675                         ccb->ccb_xa.state = ATA_S_ONCHIP;
1676                         ahci_pwrite(ap, AHCI_PREG_SACT, 1 << ccb->ccb_slot);
1677                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
1678                 }
1679         } else {
1680                 /*
1681                  * Wait for all NCQ commands to finish before issuing standard
1682                  * command.  Allow up to <limit> non-NCQ commands to be active.
1683                  *
1684                  * XXX If ap is a port multiplier only allow 1.  At least the
1685                  *     NVidia-MCP77 part seems to barf if more then one
1686                  *     command is activated, even though it isn't NCQ.
1687                  *
1688                  *     If I set up more then one I get phy errors and the
1689                  *     port fails.
1690                  */
1691                 int limit = (ap->ap_type == ATA_PORT_T_PM) ? 1 : 2;
1692                 if (ap->ap_sactive || ap->ap_active_cnt >= limit) {
1693                         TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1694                 } else {
1695                         ap->ap_active |= 1 << ccb->ccb_slot;
1696                         ccb->ccb_xa.state = ATA_S_ONCHIP;
1697                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
1698                         ap->ap_active_cnt++;
1699                 }
1700         }
1701 }
1702
1703 void
1704 ahci_issue_pending_ncq_commands(struct ahci_port *ap)
1705 {
1706         struct ahci_ccb                 *nextccb;
1707         u_int32_t                       sact_change = 0;
1708
1709         KKASSERT(ap->ap_active_cnt == 0);
1710
1711         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1712         if (nextccb == NULL || !(nextccb->ccb_xa.flags & ATA_F_NCQ))
1713                 return;
1714
1715         /* Start all the NCQ commands at the head of the pending list. */
1716         do {
1717                 TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
1718                 sact_change |= 1 << nextccb->ccb_slot;
1719                 nextccb->ccb_xa.state = ATA_S_ONCHIP;
1720                 nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1721         } while (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ));
1722
1723         ap->ap_sactive |= sact_change;
1724         ahci_pwrite(ap, AHCI_PREG_SACT, sact_change);
1725         ahci_pwrite(ap, AHCI_PREG_CI, sact_change);
1726
1727         return;
1728 }
1729
1730 void
1731 ahci_issue_pending_commands(struct ahci_port *ap, int last_was_ncq)
1732 {
1733         struct ahci_ccb                 *nextccb;
1734
1735         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1736         if (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ)) {
1737                 KKASSERT(last_was_ncq == 0);    /* otherwise it should have
1738                                                  * been started already. */
1739
1740                 /*
1741                  * Issue NCQ commands only when there are no outstanding
1742                  * standard commands.
1743                  */
1744                 if (ap->ap_active == 0)
1745                         ahci_issue_pending_ncq_commands(ap);
1746                 else
1747                         KKASSERT(ap->ap_active_cnt > 0);
1748         } else if (nextccb) {
1749                 if (ap->ap_sactive || last_was_ncq)
1750                         KKASSERT(ap->ap_active_cnt == 0);
1751
1752                 /*
1753                  * Wait for all NCQ commands to finish before issuing standard
1754                  * command.  Then keep up to 2 standard commands on-chip at
1755                  * a time.
1756                  */
1757                 if (ap->ap_sactive)
1758                         return;
1759
1760                 while (ap->ap_active_cnt < 2 &&
1761                        nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ) == 0) {
1762                         TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
1763                         ap->ap_active |= 1 << nextccb->ccb_slot;
1764                         nextccb->ccb_xa.state = ATA_S_ONCHIP;
1765                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << nextccb->ccb_slot);
1766                         ap->ap_active_cnt++;
1767                         nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1768                 }
1769         }
1770 }
1771
1772 void
1773 ahci_intr(void *arg)
1774 {
1775         struct ahci_softc               *sc = arg;
1776         u_int32_t                       is, ack = 0;
1777         int                             port;
1778
1779         /* Read global interrupt status */
1780         is = ahci_read(sc, AHCI_REG_IS);
1781         if (is == 0 || is == 0xffffffff)
1782                 return;
1783         ack = is;
1784
1785 #ifdef AHCI_COALESCE
1786         /* Check coalescing interrupt first */
1787         if (is & sc->sc_ccc_mask) {
1788                 DPRINTF(AHCI_D_INTR, "%s: command coalescing interrupt\n",
1789                     DEVNAME(sc));
1790                 is &= ~sc->sc_ccc_mask;
1791                 is |= sc->sc_ccc_ports_cur;
1792         }
1793 #endif
1794
1795         /* Process interrupts for each port */
1796         while (is) {
1797                 port = ffs(is) - 1;
1798                 if (sc->sc_ports[port]) {
1799                         ahci_port_intr(sc->sc_ports[port],
1800                                        AHCI_PREG_CI_ALL_SLOTS);
1801                 }
1802                 is &= ~(1 << port);
1803         }
1804
1805         /* Finally, acknowledge global interrupt */
1806         ahci_write(sc, AHCI_REG_IS, ack);
1807 }
1808
1809 u_int32_t
1810 ahci_port_intr(struct ahci_port *ap, u_int32_t ci_mask)
1811 {
1812         struct ahci_softc               *sc = ap->ap_sc;
1813         u_int32_t                       is, ci_saved, ci_masked, processed = 0;
1814         int                             slot;
1815         struct ahci_ccb                 *ccb = NULL;
1816         struct ata_port                 *ccb_at = NULL;
1817         volatile u_int32_t              *active;
1818 #ifdef DIAGNOSTIC
1819         u_int32_t                       tmp;
1820 #endif
1821         enum { NEED_NOTHING, NEED_RESTART, NEED_HOTPLUG_INSERT,
1822                NEED_HOTPLUG_REMOVE } need = NEED_NOTHING;
1823
1824         is = ahci_pread(ap, AHCI_PREG_IS);
1825
1826 #if 0
1827         kprintf("%s: INTERRUPT %b\n", PORTNAME(ap),
1828                 is, AHCI_PFMT_IS);
1829 #endif
1830
1831         /* Ack port interrupt only if checking all command slots. */
1832         if (ci_mask == AHCI_PREG_CI_ALL_SLOTS)
1833                 ahci_pwrite(ap, AHCI_PREG_IS, is);
1834
1835         if (is)
1836                 DPRINTF(AHCI_D_INTR, "%s: interrupt: %b\n", PORTNAME(ap),
1837                         is, AHCI_PFMT_IS);
1838
1839         if (ap->ap_sactive) {
1840                 /* Active NCQ commands - use SActive instead of CI */
1841                 KKASSERT(ap->ap_active == 0);
1842                 KKASSERT(ap->ap_active_cnt == 0);
1843                 ci_saved = ahci_pread(ap, AHCI_PREG_SACT);
1844                 active = &ap->ap_sactive;
1845         } else {
1846                 /* Save CI */
1847                 ci_saved = ahci_pread(ap, AHCI_PREG_CI);
1848                 active = &ap->ap_active;
1849         }
1850
1851         if (is & AHCI_PREG_IS_TFES) {
1852                 /*
1853                  * Command failed.  See AHCI 1.1 spec 6.2.2.1 and 6.2.2.2.
1854                  *
1855                  * This stops command processing.
1856                  */
1857                 u_int32_t tfd, serr;
1858                 int     err_slot;
1859
1860                 tfd = ahci_pread(ap, AHCI_PREG_TFD);
1861                 serr = ahci_pread(ap, AHCI_PREG_SERR);
1862
1863                 /*
1864                  * If no NCQ commands are active the error slot is easily
1865                  * determined, otherwise we have to extract the error
1866                  * from the log page.
1867                  */
1868                 if (ap->ap_sactive == 0) {
1869                         err_slot = AHCI_PREG_CMD_CCS(
1870                                         ahci_pread(ap, AHCI_PREG_CMD));
1871                         ccb = &ap->ap_ccbs[err_slot];
1872                         ccb_at = ccb->ccb_xa.at;        /* can be NULL */
1873
1874                         /* Preserve received taskfile data from the RFIS. */
1875                         memcpy(&ccb->ccb_xa.rfis, ap->ap_rfis->rfis,
1876                                sizeof(struct ata_fis_d2h));
1877                 } else {
1878                         err_slot = -1;
1879                 }
1880
1881                 DPRINTF(AHCI_D_VERBOSE, "%s: errd slot %d, TFD: %b, SERR: %b\n",
1882                         PORTNAME(ap), err_slot,
1883                         tfd, AHCI_PFMT_TFD_STS,
1884                         serr, AHCI_PFMT_SERR);
1885
1886                 /* Stopping the port clears CI and SACT */
1887                 ahci_port_stop(ap, 0);
1888                 need = NEED_RESTART;
1889
1890                 /*
1891                  * Clear SERR (primarily DIAG_X) to enable capturing of the
1892                  * next error.
1893                  */
1894                 ahci_pwrite(ap, AHCI_PREG_SERR, serr);
1895
1896                 /* Acknowledge the interrupts we can recover from. */
1897                 ahci_pwrite(ap, AHCI_PREG_IS,
1898                             AHCI_PREG_IS_TFES | AHCI_PREG_IS_IFS);
1899                 is &= ~(AHCI_PREG_IS_TFES | AHCI_PREG_IS_IFS);
1900
1901                 /* If device hasn't cleared its busy status, try to idle it. */
1902                 if (tfd & (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1903                         kprintf("%s: Attempting to idle device ccb=%p\n",
1904                                 PORTNAME(ap), ccb_at);
1905                         if (ap->ap_flags & AP_F_IN_RESET)
1906                                 goto fatal;
1907                         /*
1908                          * XXX how do we unbrick a PM target (ccb_at != NULL).
1909                          *
1910                          * For now fail the target and use CLO to clear the
1911                          * busy condition and make the ahci port usable for
1912                          * the remaining devices.
1913                          */
1914                         if (ccb_at) {
1915                                 ccb_at->at_probe = ATA_PROBE_FAILED;
1916                                 ahci_port_clo(ap);
1917                         } else if (ahci_port_reset(ap, ccb_at, 0)) {
1918                                 kprintf("%s: Unable to idle device, port "
1919                                         "bricked on us\n",
1920                                         PORTNAME(ap));
1921                                 goto fatal;
1922                         }
1923
1924                         /* Had to reset device, can't gather extended info. */
1925                 } else if (ap->ap_sactive) {
1926                         /*
1927                          * Recover the NCQ error from log page 10h.
1928                          *
1929                          * XXX NCQ currently not supported with port
1930                          *     multiplier.
1931                          */
1932                         ahci_port_read_ncq_error(ap, &err_slot);
1933                         kprintf("recover from NCQ error err_slot %d\n", err_slot);
1934                         if (err_slot < 0)
1935                                 goto failall;
1936
1937                         DPRINTF(AHCI_D_VERBOSE, "%s: NCQ errored slot %d\n",
1938                                 PORTNAME(ap), err_slot);
1939
1940                         ccb = &ap->ap_ccbs[err_slot];
1941                 } else {
1942                         /* Didn't reset, could gather extended info from log. */
1943                         kprintf("%s: didn't reset err_slot %d "
1944                                 "sact=%08x act=%08x\n",
1945                                 PORTNAME(ap),
1946                                 err_slot, ap->ap_sactive, ap->ap_active);
1947                 }
1948
1949                 /*
1950                  * If we couldn't determine the errored slot, reset the port
1951                  * and fail all the active slots.
1952                  */
1953                 if (err_slot == -1) {
1954                         if (ap->ap_flags & AP_F_IN_RESET)
1955                                 goto fatal;
1956                         /*
1957                          * XXX how do we unbrick a PM target (ccb_at != NULL).
1958                          *
1959                          * For now fail the target and use CLO to clear the
1960                          * busy condition and make the ahci port usable for
1961                          * the remaining devices.
1962                          */
1963                         if (ccb_at) {
1964                                 ccb_at->at_probe = ATA_PROBE_FAILED;
1965                                 ahci_port_clo(ap);
1966                         } else if (ahci_port_reset(ap, ccb_at, 0)) {
1967                                 kprintf("%s: Unable to idle device after "
1968                                         "NCQ error, port bricked on us\n",
1969                                         PORTNAME(ap));
1970                                 goto fatal;
1971                         }
1972                         kprintf("%s: couldn't recover NCQ error, failing "
1973                                 "all outstanding commands.\n",
1974                                 PORTNAME(ap));
1975                         goto failall;
1976                 }
1977
1978                 /* Clear the failed command in saved CI so completion runs. */
1979                 ci_saved &= ~(1 << err_slot);
1980
1981                 /* Note the error in the ata_xfer. */
1982                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
1983                 ccb->ccb_xa.state = ATA_S_ERROR;
1984
1985 #ifdef DIAGNOSTIC
1986                 /* There may only be one outstanding standard command now. */
1987                 if (ap->ap_sactive == 0) {
1988                         tmp = ci_saved;
1989                         if (tmp) {
1990                                 slot = ffs(tmp) - 1;
1991                                 tmp &= ~(1 << slot);
1992                                 KKASSERT(tmp == 0);
1993                         }
1994                 }
1995 #endif
1996         } else if (is & AHCI_PREG_IS_DHRS) {
1997                 /*
1998                  * Command posted D2H register FIS to the rfis.  This
1999                  * stops command processing.  We must copy the port
2000                  * rfis to the ccb and restart command processing.
2001                  */
2002                 int     err_slot;
2003
2004                 if (ap->ap_sactive == 0) {
2005                         err_slot = AHCI_PREG_CMD_CCS(
2006                                         ahci_pread(ap, AHCI_PREG_CMD));
2007                         ccb = &ap->ap_ccbs[err_slot];
2008                         ccb_at = ccb->ccb_xa.at;        /* can be NULL */
2009
2010                         memcpy(&ccb->ccb_xa.rfis, ap->ap_rfis->rfis,
2011                                sizeof(struct ata_fis_d2h));
2012                 } else {
2013                         kprintf("%s: Unexpected DHRS posted while "
2014                                 "NCQ running\n", PORTNAME(ap));
2015                         err_slot = -1;
2016                 }
2017                 ahci_port_stop(ap, 0);
2018                 ahci_port_start(ap);
2019         }
2020
2021         /*
2022          * Device notification to us.
2023          *
2024          * For some reason this interrupt can occur without any notification
2025          * bits actually being set.
2026          */
2027         if ((is & AHCI_PREG_IS_SDBS) && (sc->sc_cap & AHCI_REG_CAP_SSNTF)) {
2028                 u_int32_t data;
2029
2030                 data = ahci_pread(ap, AHCI_PREG_SNTF);
2031                 if (data) {
2032                         kprintf("%s: NOTIFY %08x\n", PORTNAME(ap), data);
2033                         ahci_pwrite(ap, AHCI_PREG_SNTF, data);
2034                         ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_SDBS);
2035                 }
2036         }
2037 #if 0
2038         /* XXX future IFS recovery code? or just scrap it */
2039         if (is & AHCI_PREG_IS_IFS) {
2040                 u_int32_t serr = ahci_pread(ap, AHCI_PREG_SERR);
2041                 kprintf("%s: Ignoring IFS (XXX) (IS: %b, SERR: %b)\n",
2042                         PORTNAME(ap),
2043                         is, AHCI_PFMT_IS,
2044                         serr, AHCI_PFMT_SERR);
2045                 ahci_pwrite(ap, AHCI_PREG_SERR, -1);
2046                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IFS);
2047                 is &= ~AHCI_PREG_IS_IFS;
2048                 ahci_port_stop(ap, 0);
2049                 ahci_port_start(ap);
2050                 need = NEED_RESTART;
2051         }
2052 #endif
2053
2054         /*
2055          * Port change (hot-plug).
2056          *
2057          * A PCS interrupt will occur on hot-plug once communication is
2058          * established.
2059          *
2060          * A PRCS interrupt will occur on hot-unplug (and possibly also
2061          * on hot-plug).
2062          *
2063          * XXX We can then check the CPS (Cold Presence State) bit, if
2064          * supported, to determine if a device is plugged in or not and do
2065          * the right thing.
2066          *
2067          * WARNING:  A PCS interrupt is cleared by clearing DIAG_X, and
2068          *           can also occur if an unsolicited COMINIT is received.
2069          *           If this occurs command processing is automatically
2070          *           stopped (CR goes inactive) and the port must be stopped
2071          *           and restarted.
2072          */
2073         if (is & (AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS)) {
2074                 ahci_pwrite(ap, AHCI_PREG_SERR,
2075                         (AHCI_PREG_SERR_DIAG_N | AHCI_PREG_SERR_DIAG_X));
2076                 ahci_port_stop(ap, 0);
2077                 switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
2078                 case AHCI_PREG_SSTS_DET_DEV:
2079                         if (ap->ap_type == ATA_PORT_T_NONE) {
2080                                 need = NEED_HOTPLUG_INSERT;
2081                                 goto fatal;
2082                         }
2083                         need = NEED_RESTART;
2084                         break;
2085                 default:
2086                         if (ap->ap_type != ATA_PORT_T_NONE) {
2087                                 need = NEED_HOTPLUG_REMOVE;
2088                                 goto fatal;
2089                         }
2090                         need = NEED_RESTART;
2091                         break;
2092                 }
2093         }
2094
2095         /*
2096          * Check for remaining errors - they are fatal.
2097          */
2098         if (is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS | AHCI_PREG_IS_IFS |
2099                   AHCI_PREG_IS_OFS | AHCI_PREG_IS_UFS)) {
2100                 u_int32_t serr = ahci_pread(ap, AHCI_PREG_SERR);
2101                 kprintf("%s: unrecoverable errors (IS: %b, SERR: %b), "
2102                         "disabling port.\n",
2103                         PORTNAME(ap),
2104                         is, AHCI_PFMT_IS,
2105                         serr, AHCI_PFMT_SERR
2106                 );
2107                 /* XXX try recovery first */
2108                 goto fatal;
2109         }
2110
2111         /*
2112          * Fail all outstanding commands if we know the port won't recover.
2113          *
2114          * We may have a ccb_at if the failed command is known and was
2115          * being sent to a device over a port multiplier (PM).  In this
2116          * case if the port itself has not completely failed we fail just
2117          * the commands related to that target.
2118          */
2119         if (ap->ap_state == AP_S_FATAL_ERROR) {
2120 fatal:
2121                 ap->ap_state = AP_S_FATAL_ERROR;
2122 failall:
2123
2124                 /* Stopping the port clears CI/SACT */
2125                 ahci_port_stop(ap, 0);
2126
2127                 /*
2128                  * Error all the active slots.  If running across a PM
2129                  * try to error out just the slots related to the target.
2130                  */
2131                 ci_masked = ci_saved & *active;
2132                 while (ci_masked) {
2133                         slot = ffs(ci_masked) - 1;
2134                         ccb = &ap->ap_ccbs[slot];
2135                         if (ccb_at == ccb->ccb_xa.at ||
2136                             ap->ap_state == AP_S_FATAL_ERROR) {
2137                                 ci_masked &= ~(1 << slot);
2138                                 ccb->ccb_xa.state = ATA_S_ERROR;
2139                         }
2140                 }
2141
2142                 /* Run completion for all active slots. */
2143                 ci_saved &= ~*active;
2144
2145                 /*
2146                  * Don't restart the port if our problems were deemed fatal.
2147                  *
2148                  * Also acknowlege all fatal interrupt sources to prevent
2149                  * a livelock.
2150                  */
2151                 if (ap->ap_state == AP_S_FATAL_ERROR) {
2152                         if (need == NEED_RESTART)
2153                                 need = NEED_NOTHING;
2154                         ahci_pwrite(ap, AHCI_PREG_IS,
2155                                     AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
2156                                     AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS |
2157                                     AHCI_PREG_IS_UFS);
2158                 }
2159         }
2160
2161         /*
2162          * CCB completion is detected by noticing its slot's bit in CI has
2163          * changed to zero some time after we activated it.
2164          * If we are polling, we may only be interested in particular slot(s).
2165          *
2166          * Any active bits not saved are completed within the restrictions
2167          * imposed by the caller.
2168          */
2169         ci_masked = ~ci_saved & *active & ci_mask;
2170         while (ci_masked) {
2171                 slot = ffs(ci_masked) - 1;
2172                 ccb = &ap->ap_ccbs[slot];
2173                 ci_masked &= ~(1 << slot);
2174
2175                 DPRINTF(AHCI_D_INTR, "%s: slot %d is complete%s\n",
2176                     PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
2177                     " (error)" : "");
2178
2179                 bus_dmamap_sync(sc->sc_tag_cmdh,
2180                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
2181                                 BUS_DMASYNC_POSTWRITE);
2182
2183                 bus_dmamap_sync(sc->sc_tag_cmdt,
2184                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
2185                                 BUS_DMASYNC_POSTWRITE);
2186
2187                 bus_dmamap_sync(sc->sc_tag_rfis,
2188                                 AHCI_DMA_MAP(ap->ap_dmamem_rfis),
2189                                 BUS_DMASYNC_POSTREAD);
2190
2191                 *active &= ~(1 << ccb->ccb_slot);
2192                 if (active == &ap->ap_active) {
2193                         KKASSERT(ap->ap_active_cnt > 0);
2194                         --ap->ap_active_cnt;
2195                 }
2196                 ccb->ccb_done(ccb);
2197
2198                 processed |= 1 << ccb->ccb_slot;
2199         }
2200
2201         switch(need) {
2202         case NEED_RESTART:
2203                 /*
2204                  * A recoverable error occured and we can restart outstanding
2205                  * commands on the port.
2206                  */
2207                 ahci_port_start(ap);
2208
2209                 if (ci_saved) {
2210 #ifdef DIAGNOSTIC
2211                         tmp = ci_saved;
2212                         while (tmp) {
2213                                 slot = ffs(tmp) - 1;
2214                                 tmp &= ~(1 << slot);
2215                                 ccb = &ap->ap_ccbs[slot];
2216                                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
2217                                 KKASSERT((!!(ccb->ccb_xa.flags & ATA_F_NCQ)) ==
2218                                     (!!ap->ap_sactive));
2219                         }
2220 #endif
2221                         DPRINTF(AHCI_D_VERBOSE, "%s: ahci_port_intr "
2222                             "re-enabling%s slots %08x\n", PORTNAME(ap),
2223                             ap->ap_sactive ? " NCQ" : "", ci_saved);
2224
2225                         if (ap->ap_sactive)
2226                                 ahci_pwrite(ap, AHCI_PREG_SACT, ci_saved);
2227                         ahci_pwrite(ap, AHCI_PREG_CI, ci_saved);
2228                 }
2229                 break;
2230         case NEED_HOTPLUG_INSERT:
2231                 /*
2232                  * A hot-plug insertion event has occured and all
2233                  * outstanding commands have already been revoked.
2234                  *
2235                  * Don't recurse if this occurs while we are
2236                  * resetting the port.
2237                  */
2238                 if ((ap->ap_flags & AP_F_IN_RESET) == 0) {
2239                         kprintf("%s: HOTPLUG - Device inserted\n",
2240                                 PORTNAME(ap));
2241                         if (ahci_port_init(ap, NULL) == 0)
2242                                 ahci_cam_changed(ap, 1);
2243                 }
2244                 break;
2245         case NEED_HOTPLUG_REMOVE:
2246                 /*
2247                  * A hot-plug removal event has occured and all
2248                  * outstanding commands have already been revoked.
2249                  *
2250                  * Don't recurse if this occurs while we are
2251                  * resetting the port.
2252                  */
2253                 if ((ap->ap_flags & AP_F_IN_RESET) == 0) {
2254                         kprintf("%s: HOTPLUG - Device removed\n",
2255                                 PORTNAME(ap));
2256                         ahci_port_hardstop(ap);
2257                         ahci_cam_changed(ap, 0);
2258                 }
2259                 break;
2260         default:
2261                 break;
2262         }
2263         return (processed);
2264 }
2265
2266 struct ahci_ccb *
2267 ahci_get_ccb(struct ahci_port *ap)
2268 {
2269         struct ahci_ccb                 *ccb;
2270
2271         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
2272         ccb = TAILQ_FIRST(&ap->ap_ccb_free);
2273         if (ccb != NULL) {
2274                 KKASSERT(ccb->ccb_xa.state == ATA_S_PUT);
2275                 TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
2276                 ccb->ccb_xa.state = ATA_S_SETUP;
2277                 ccb->ccb_xa.at = NULL;
2278         }
2279         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
2280
2281         return (ccb);
2282 }
2283
2284 void
2285 ahci_put_ccb(struct ahci_ccb *ccb)
2286 {
2287         struct ahci_port                *ap = ccb->ccb_port;
2288
2289 #ifdef DIAGNOSTIC
2290         if (ccb->ccb_xa.state != ATA_S_COMPLETE &&
2291             ccb->ccb_xa.state != ATA_S_TIMEOUT &&
2292             ccb->ccb_xa.state != ATA_S_ERROR) {
2293                 kprintf("%s: invalid ata_xfer state %02x in ahci_put_ccb, "
2294                         "slot %d\n",
2295                         PORTNAME(ccb->ccb_port), ccb->ccb_xa.state,
2296                         ccb->ccb_slot);
2297         }
2298 #endif
2299
2300         ccb->ccb_xa.state = ATA_S_PUT;
2301         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
2302         TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
2303         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
2304 }
2305
2306 struct ahci_ccb *
2307 ahci_get_err_ccb(struct ahci_port *ap)
2308 {
2309         struct ahci_ccb *err_ccb;
2310         u_int32_t sact;
2311
2312         /* No commands may be active on the chip. */
2313         sact = ahci_pread(ap, AHCI_PREG_SACT);
2314         if (sact != 0)
2315                 kprintf("ahci_get_err_ccb but SACT %08x != 0?\n", sact);
2316         KKASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
2317
2318 #ifdef DIAGNOSTIC
2319         KKASSERT(ap->ap_err_busy == 0);
2320         ap->ap_err_busy = 1;
2321 #endif
2322         /* Save outstanding command state. */
2323         ap->ap_err_saved_active = ap->ap_active;
2324         ap->ap_err_saved_active_cnt = ap->ap_active_cnt;
2325         ap->ap_err_saved_sactive = ap->ap_sactive;
2326
2327         /*
2328          * Pretend we have no commands outstanding, so that completions won't
2329          * run prematurely.
2330          */
2331         ap->ap_active = ap->ap_active_cnt = ap->ap_sactive = 0;
2332
2333         /*
2334          * Grab a CCB to use for error recovery.  This should never fail, as
2335          * we ask atascsi to reserve one for us at init time.
2336          */
2337         err_ccb = ahci_get_ccb(ap);
2338         KKASSERT(err_ccb != NULL);
2339         err_ccb->ccb_xa.flags = 0;
2340         err_ccb->ccb_done = ahci_empty_done;
2341
2342         return err_ccb;
2343 }
2344
2345 void
2346 ahci_put_err_ccb(struct ahci_ccb *ccb)
2347 {
2348         struct ahci_port *ap = ccb->ccb_port;
2349         u_int32_t sact;
2350         u_int32_t ci;
2351
2352 #ifdef DIAGNOSTIC
2353         KKASSERT(ap->ap_err_busy);
2354 #endif
2355         /*
2356          * No commands may be active on the chip
2357          */
2358         sact = ahci_pread(ap, AHCI_PREG_SACT);
2359         if (sact) {
2360                 panic("ahci_port_err_ccb(%d) but SACT %08x != 0\n",
2361                       ccb->ccb_slot, sact);
2362         }
2363         ci = ahci_pread(ap, AHCI_PREG_CI);
2364         if (ci) {
2365                 panic("ahci_put_err_ccb(%d) but CI %08x != 0 "
2366                       "(act=%08x sact=%08x)\n",
2367                       ccb->ccb_slot, ci,
2368                       ap->ap_active, ap->ap_sactive);
2369         }
2370
2371         /* Done with the CCB */
2372         ahci_put_ccb(ccb);
2373
2374         /* Restore outstanding command state */
2375         ap->ap_sactive = ap->ap_err_saved_sactive;
2376         ap->ap_active_cnt = ap->ap_err_saved_active_cnt;
2377         ap->ap_active = ap->ap_err_saved_active;
2378
2379 #ifdef DIAGNOSTIC
2380         ap->ap_err_busy = 0;
2381 #endif
2382 }
2383
2384 /*
2385  * Read log page to get NCQ error.
2386  *
2387  * NOTE: NCQ not currently supported on port multipliers. XXX
2388  */
2389 int
2390 ahci_port_read_ncq_error(struct ahci_port *ap, int *err_slotp)
2391 {
2392         struct ahci_ccb                 *ccb;
2393         struct ahci_cmd_hdr             *cmd_slot;
2394         u_int32_t                       cmd;
2395         struct ata_fis_h2d              *fis;
2396         int                             rc = EIO;
2397
2398         DPRINTF(AHCI_D_VERBOSE, "%s: read log page\n", PORTNAME(ap));
2399
2400         /* Save command register state. */
2401         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
2402
2403         /* Port should have been idled already.  Start it. */
2404         KKASSERT((cmd & AHCI_PREG_CMD_CR) == 0);
2405         ahci_port_start(ap);
2406
2407         /* Prep error CCB for READ LOG EXT, page 10h, 1 sector. */
2408         ccb = ahci_get_err_ccb(ap);
2409         ccb->ccb_xa.flags = ATA_F_NOWAIT | ATA_F_READ | ATA_F_POLL;
2410         ccb->ccb_xa.data = ap->ap_err_scratch;
2411         ccb->ccb_xa.datalen = 512;
2412         cmd_slot = ccb->ccb_cmd_hdr;
2413         bzero(ccb->ccb_cmd_table, sizeof(struct ahci_cmd_table));
2414
2415         fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
2416         fis->type = ATA_FIS_TYPE_H2D;
2417         fis->flags = ATA_H2D_FLAGS_CMD;
2418         fis->command = ATA_C_READ_LOG_EXT;
2419         fis->lba_low = 0x10;            /* queued error log page (10h) */
2420         fis->sector_count = 1;          /* number of sectors (1) */
2421         fis->sector_count_exp = 0;
2422         fis->lba_mid = 0;               /* starting offset */
2423         fis->lba_mid_exp = 0;
2424         fis->device = 0;
2425
2426         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
2427
2428         if (ahci_load_prdt(ccb) != 0) {
2429                 rc = ENOMEM;    /* XXX caller must abort all commands */
2430                 goto err;
2431         }
2432
2433         ccb->ccb_xa.state = ATA_S_PENDING;
2434         if (ahci_poll(ccb, hz, NULL) != 0)
2435                 goto err;
2436
2437         rc = 0;
2438 err:
2439         /* Abort our command, if it failed, by stopping command DMA. */
2440         if (rc && (ap->ap_active & (1 << ccb->ccb_slot))) {
2441                 kprintf("%s: log page read failed, slot %d was still active.\n",
2442                         PORTNAME(ap), ccb->ccb_slot);
2443                 ahci_port_stop(ap, 0);
2444         }
2445
2446         /* Done with the error CCB now. */
2447         ahci_unload_prdt(ccb);
2448         ahci_put_err_ccb(ccb);
2449
2450         /* Extract failed register set and tags from the scratch space. */
2451         if (rc == 0) {
2452                 struct ata_log_page_10h         *log;
2453                 int                             err_slot;
2454
2455                 log = (struct ata_log_page_10h *)ap->ap_err_scratch;
2456                 if (log->err_regs.type & ATA_LOG_10H_TYPE_NOTQUEUED) {
2457                         /* Not queued bit was set - wasn't an NCQ error? */
2458                         kprintf("%s: read NCQ error page, but not an NCQ "
2459                                 "error?\n",
2460                                 PORTNAME(ap));
2461                         rc = ESRCH;
2462                 } else {
2463                         /* Copy back the log record as a D2H register FIS. */
2464                         *err_slotp = err_slot = log->err_regs.type &
2465                             ATA_LOG_10H_TYPE_TAG_MASK;
2466
2467                         ccb = &ap->ap_ccbs[err_slot];
2468                         memcpy(&ccb->ccb_xa.rfis, &log->err_regs,
2469                             sizeof(struct ata_fis_d2h));
2470                         ccb->ccb_xa.rfis.type = ATA_FIS_TYPE_D2H;
2471                         ccb->ccb_xa.rfis.flags = 0;
2472                 }
2473         }
2474
2475         /* Restore saved CMD register state */
2476         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
2477
2478         return (rc);
2479 }
2480
2481 /*
2482  * Allocate memory for various structures DMAd by hardware.  The maximum
2483  * number of segments for these tags is 1 so the DMA memory will have a
2484  * single physical base address.
2485  */
2486 struct ahci_dmamem *
2487 ahci_dmamem_alloc(struct ahci_softc *sc, bus_dma_tag_t tag)
2488 {
2489         struct ahci_dmamem *adm;
2490         int     error;
2491
2492         adm = kmalloc(sizeof(*adm), M_DEVBUF, M_INTWAIT | M_ZERO);
2493
2494         error = bus_dmamem_alloc(tag, (void **)&adm->adm_kva,
2495                                  BUS_DMA_ZERO, &adm->adm_map);
2496         if (error == 0) {
2497                 adm->adm_tag = tag;
2498                 error = bus_dmamap_load(tag, adm->adm_map,
2499                                         adm->adm_kva,
2500                                         bus_dma_tag_getmaxsize(tag),
2501                                         ahci_dmamem_saveseg, &adm->adm_busaddr,
2502                                         0);
2503         }
2504         if (error) {
2505                 if (adm->adm_map) {
2506                         bus_dmamap_destroy(tag, adm->adm_map);
2507                         adm->adm_map = NULL;
2508                         adm->adm_tag = NULL;
2509                         adm->adm_kva = NULL;
2510                 }
2511                 kfree(adm, M_DEVBUF);
2512                 adm = NULL;
2513         }
2514         return (adm);
2515 }
2516
2517 static
2518 void
2519 ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error)
2520 {
2521         KKASSERT(error == 0);
2522         KKASSERT(nsegs == 1);
2523         *(bus_addr_t *)info = segs->ds_addr;
2524 }
2525
2526
2527 void
2528 ahci_dmamem_free(struct ahci_softc *sc, struct ahci_dmamem *adm)
2529 {
2530         if (adm->adm_map) {
2531                 bus_dmamap_unload(adm->adm_tag, adm->adm_map);
2532                 bus_dmamap_destroy(adm->adm_tag, adm->adm_map);
2533                 adm->adm_map = NULL;
2534                 adm->adm_tag = NULL;
2535                 adm->adm_kva = NULL;
2536         }
2537         kfree(adm, M_DEVBUF);
2538 }
2539
2540 u_int32_t
2541 ahci_read(struct ahci_softc *sc, bus_size_t r)
2542 {
2543         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2544                           BUS_SPACE_BARRIER_READ);
2545         return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
2546 }
2547
2548 void
2549 ahci_write(struct ahci_softc *sc, bus_size_t r, u_int32_t v)
2550 {
2551         bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
2552         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2553                           BUS_SPACE_BARRIER_WRITE);
2554 }
2555
2556 int
2557 ahci_wait_ne(struct ahci_softc *sc, bus_size_t r, u_int32_t mask,
2558              u_int32_t target)
2559 {
2560         int                             i;
2561
2562         for (i = 0; i < 1000; i++) {
2563                 if ((ahci_read(sc, r) & mask) != target)
2564                         return (0);
2565                 DELAY(1000);
2566         }
2567
2568         return (1);
2569 }
2570
2571 u_int32_t
2572 ahci_pread(struct ahci_port *ap, bus_size_t r)
2573 {
2574         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2575                           BUS_SPACE_BARRIER_READ);
2576         return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
2577 }
2578
2579 void
2580 ahci_pwrite(struct ahci_port *ap, bus_size_t r, u_int32_t v)
2581 {
2582         bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
2583         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2584                           BUS_SPACE_BARRIER_WRITE);
2585 }
2586
2587 int
2588 ahci_pwait_eq(struct ahci_port *ap, int timeout,
2589               bus_size_t r, u_int32_t mask, u_int32_t target)
2590 {
2591         int                             i;
2592
2593         for (i = 0; i < timeout; i++) {
2594                 if ((ahci_pread(ap, r) & mask) == target)
2595                         return (0);
2596                 DELAY(1000);
2597         }
2598
2599         return (1);
2600 }
2601
2602 /*
2603  * Acquire an ata transfer.
2604  *
2605  * Pass a NULL at for direct-attached transfers, and a non-NULL at for
2606  * targets that go through the port multiplier.
2607  */
2608 struct ata_xfer *
2609 ahci_ata_get_xfer(struct ahci_port *ap, struct ata_port *at)
2610 {
2611         struct ahci_ccb         *ccb;
2612
2613         ccb = ahci_get_ccb(ap);
2614         if (ccb == NULL) {
2615                 DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer: NULL ccb\n",
2616                     PORTNAME(ap));
2617                 return (NULL);
2618         }
2619
2620         DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer got slot %d\n",
2621             PORTNAME(ap), ccb->ccb_slot);
2622
2623         ccb->ccb_xa.at = at;
2624         ccb->ccb_xa.fis->type = ATA_FIS_TYPE_H2D;
2625
2626         return (&ccb->ccb_xa);
2627 }
2628
2629 void
2630 ahci_ata_put_xfer(struct ata_xfer *xa)
2631 {
2632         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
2633
2634         DPRINTF(AHCI_D_XFER, "ahci_ata_put_xfer slot %d\n", ccb->ccb_slot);
2635
2636         ahci_put_ccb(ccb);
2637 }
2638
2639 int
2640 ahci_ata_cmd(struct ata_xfer *xa)
2641 {
2642         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
2643         struct ahci_cmd_hdr             *cmd_slot;
2644
2645         KKASSERT(xa->state == ATA_S_SETUP);
2646
2647         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
2648                 goto failcmd;
2649 #if 0
2650         kprintf("%s: started std command %b ccb %d ccb_at %p %d\n",
2651                 ATANAME(ccb->ccb_port, ccb->ccb_xa.at),
2652                 ahci_pread(ccb->ccb_port, AHCI_PREG_CMD), AHCI_PFMT_CMD,
2653                 ccb->ccb_slot,
2654                 ccb->ccb_xa.at,
2655                 ccb->ccb_xa.at ? ccb->ccb_xa.at->at_target : -1);
2656 #endif
2657
2658         ccb->ccb_done = ahci_ata_cmd_done;
2659
2660         cmd_slot = ccb->ccb_cmd_hdr;
2661         cmd_slot->flags = htole16(5); /* FIS length (in DWORDs) */
2662         if (ccb->ccb_xa.at) {
2663                 cmd_slot->flags |= htole16(ccb->ccb_xa.at->at_target <<
2664                                            AHCI_CMD_LIST_FLAG_PMP_SHIFT);
2665         }
2666
2667         if (xa->flags & ATA_F_WRITE)
2668                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_W);
2669
2670         if (xa->flags & ATA_F_PACKET)
2671                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_A);
2672
2673         if (ahci_load_prdt(ccb) != 0)
2674                 goto failcmd;
2675
2676         xa->state = ATA_S_PENDING;
2677
2678         if (xa->flags & ATA_F_POLL) {
2679                 ahci_poll(ccb, xa->timeout, ahci_ata_cmd_timeout);
2680                 return (ATA_COMPLETE);
2681         }
2682
2683         crit_enter();
2684         xa->flags |= ATA_F_TIMEOUT_RUNNING;
2685         callout_reset(&ccb->ccb_timeout, xa->timeout,
2686                       ahci_ata_cmd_timeout_unserialized, ccb);
2687         ahci_start(ccb);
2688         crit_exit();
2689         return (ATA_QUEUED);
2690
2691 failcmd:
2692         crit_enter();
2693         xa->state = ATA_S_ERROR;
2694         xa->complete(xa);
2695         crit_exit();
2696         return (ATA_ERROR);
2697 }
2698
2699 void
2700 ahci_ata_cmd_done(struct ahci_ccb *ccb)
2701 {
2702         struct ata_xfer                 *xa = &ccb->ccb_xa;
2703
2704         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
2705                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2706                 callout_stop(&ccb->ccb_timeout);
2707         }
2708
2709         if (xa->state == ATA_S_ONCHIP || xa->state == ATA_S_ERROR)
2710                 ahci_issue_pending_commands(ccb->ccb_port,
2711                     xa->flags & ATA_F_NCQ);
2712
2713         ahci_unload_prdt(ccb);
2714
2715         if (xa->state == ATA_S_ONCHIP)
2716                 xa->state = ATA_S_COMPLETE;
2717 #ifdef DIAGNOSTIC
2718         else if (xa->state != ATA_S_ERROR && xa->state != ATA_S_TIMEOUT)
2719                 kprintf("%s: invalid ata_xfer state %02x in ahci_ata_cmd_done, "
2720                         "slot %d\n",
2721                         PORTNAME(ccb->ccb_port), xa->state, ccb->ccb_slot);
2722 #endif
2723         if (xa->state != ATA_S_TIMEOUT)
2724                 xa->complete(xa);
2725 }
2726
2727 static void
2728 ahci_ata_cmd_timeout_unserialized(void *arg)
2729 {
2730         struct ahci_ccb         *ccb = arg;
2731         struct ahci_port        *ap = ccb->ccb_port;
2732
2733         lwkt_serialize_enter(&ap->ap_sc->sc_serializer);
2734         ahci_ata_cmd_timeout(arg);
2735         lwkt_serialize_exit(&ap->ap_sc->sc_serializer);
2736 }
2737
2738 void
2739 ahci_ata_cmd_timeout(void *arg)
2740 {
2741         struct ahci_ccb         *ccb = arg;
2742         struct ata_xfer         *xa = &ccb->ccb_xa;
2743         struct ahci_port        *ap = ccb->ccb_port;
2744         volatile u_int32_t      *active;
2745         int                     ccb_was_started, ncq_cmd;
2746
2747         crit_enter();
2748         kprintf("%s: CMD TIMEOUT cmd-reg 0x%b\n"
2749                 "\tsactive=%08x active=%08x\n"
2750                 "\t   sact=%08x     ci=%08x\n",
2751                 ATANAME(ap, ccb->ccb_xa.at),
2752                 ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD,
2753                 ap->ap_sactive, ap->ap_active,
2754                 ahci_pread(ap, AHCI_PREG_SACT),
2755                 ahci_pread(ap, AHCI_PREG_CI));
2756
2757         /*
2758          * NOTE: Timeout will not be running if the command was polled.
2759          */
2760         KKASSERT(xa->flags & (ATA_F_POLL|ATA_F_TIMEOUT_RUNNING));
2761         xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2762         ncq_cmd = (xa->flags & ATA_F_NCQ);
2763         active = ncq_cmd ? &ap->ap_sactive : &ap->ap_active;
2764
2765         if (ccb->ccb_xa.state == ATA_S_PENDING) {
2766                 DPRINTF(AHCI_D_TIMEOUT, "%s: command for slot %d timed out "
2767                     "before it got on chip\n", PORTNAME(ap), ccb->ccb_slot);
2768                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2769                 ccb_was_started = 0;
2770         } else if (ccb->ccb_xa.state == ATA_S_ONCHIP &&
2771                    ahci_port_intr(ap, 1 << ccb->ccb_slot)) {
2772                 DPRINTF(AHCI_D_TIMEOUT, "%s: final poll of port completed "
2773                     "command in slot %d\n", PORTNAME(ap), ccb->ccb_slot);
2774                 goto ret;
2775         } else if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
2776                 DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d already "
2777                     "handled%s\n", PORTNAME(ap), ccb->ccb_slot,
2778                     (*active & (1 << ccb->ccb_slot)) ?
2779                     " but slot is still active?" : ".");
2780                 goto ret;
2781         } else if ((ahci_pread(ap, ncq_cmd ? AHCI_PREG_SACT : AHCI_PREG_CI) &
2782                     (1 << ccb->ccb_slot)) == 0 &&
2783                    (*active & (1 << ccb->ccb_slot))) {
2784                 DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d completed but "
2785                     "IRQ handler didn't detect it.  Why?\n", PORTNAME(ap),
2786                     ccb->ccb_slot);
2787                 *active &= ~(1 << ccb->ccb_slot);
2788                 if (ncq_cmd == 0) {
2789                         KKASSERT(ap->ap_active_cnt > 0);
2790                         --ap->ap_active_cnt;
2791                 }
2792                 ccb->ccb_done(ccb);
2793                 goto ret;
2794         } else {
2795                 ccb_was_started = 1;
2796         }
2797
2798         /* Complete the slot with a timeout error. */
2799         ccb->ccb_xa.state = ATA_S_TIMEOUT;
2800         *active &= ~(1 << ccb->ccb_slot);
2801         if (ncq_cmd == 0) {
2802                 KKASSERT(ap->ap_active_cnt > 0);
2803                 --ap->ap_active_cnt;
2804         }
2805         DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (1)\n", PORTNAME(ap));
2806         ccb->ccb_done(ccb);     /* This won't issue pending commands or run the
2807                                    atascsi completion. */
2808
2809         /* Reset port to abort running command. */
2810         if (ccb_was_started) {
2811                 DPRINTF(AHCI_D_TIMEOUT, "%s: resetting port to abort%s command "
2812                     "in slot %d, active %08x\n", PORTNAME(ap), ncq_cmd ? " NCQ"
2813                     : "", ccb->ccb_slot, *active);
2814                 /* XXX */
2815                 if (ccb->ccb_xa.at) {
2816                         /* XXX how do we unbrick a PM target? */
2817                         kprintf("%s: Unable to reset PM target during timeout"
2818                                 ", port bricked on us\n",
2819                                 PORTNAME(ap));
2820                         ap->ap_state = AP_S_FATAL_ERROR;
2821                         ahci_port_intr(ap, AHCI_PREG_CI_ALL_SLOTS);
2822                 } else if (ahci_port_reset(ap, ccb->ccb_xa.at, 0)) {
2823                         /*
2824                          * If the softreset failed place the port in a
2825                          * failed state and use ahci_port_intr() to cancel
2826                          * any remaining commands.
2827                          */
2828                         kprintf("%s: Unable to reset during timeout, port "
2829                                 "bricked on us\n",
2830                                 PORTNAME(ap));
2831                         ap->ap_state = AP_S_FATAL_ERROR;
2832                         ahci_port_intr(ap, AHCI_PREG_CI_ALL_SLOTS);
2833                 } else {
2834                         /*
2835                          * Restart any other commands that were aborted
2836                          * by the reset.
2837                          */
2838                         if (*active) {
2839                                 DPRINTF(AHCI_D_TIMEOUT, "%s: re-enabling%s slots "
2840                                     "%08x\n", PORTNAME(ap), ncq_cmd ? " NCQ" : "",
2841                                     *active);
2842                                 if (ncq_cmd)
2843                                         ahci_pwrite(ap, AHCI_PREG_SACT, *active);
2844                                 ahci_pwrite(ap, AHCI_PREG_CI, *active);
2845                         }
2846                 }
2847         }
2848
2849         /* Issue any pending commands now. */
2850         DPRINTF(AHCI_D_TIMEOUT, "%s: issue pending\n", PORTNAME(ap));
2851         if (ccb_was_started)
2852                 ahci_issue_pending_commands(ap, ncq_cmd);
2853         else if (ap->ap_active == 0)
2854                 ahci_issue_pending_ncq_commands(ap);
2855
2856         /* Complete the timed out ata_xfer I/O (may generate new I/O). */
2857         DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (2)\n", PORTNAME(ap));
2858         xa->complete(xa);
2859
2860         DPRINTF(AHCI_D_TIMEOUT, "%s: splx\n", PORTNAME(ap));
2861 ret:
2862         crit_exit();
2863 }
2864
2865 void
2866 ahci_empty_done(struct ahci_ccb *ccb)
2867 {
2868         ccb->ccb_xa.state = ATA_S_COMPLETE;
2869 }