ahci: Add some DevSleep defintions. Recognize DevSleep link state.
[dragonfly.git] / sys / dev / disk / ahci / ahci.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 2006 David Gwynne <dlg@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  *
18  *
19  * Copyright (c) 2009 The DragonFly Project.  All rights reserved.
20  *
21  * This code is derived from software contributed to The DragonFly Project
22  * by Matthew Dillon <dillon@backplane.com>
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  *
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in
32  *    the documentation and/or other materials provided with the
33  *    distribution.
34  * 3. Neither the name of The DragonFly Project nor the names of its
35  *    contributors may be used to endorse or promote products derived
36  *    from this software without specific, prior written permission.
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
39  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
40  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
41  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
42  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
43  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
44  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
46  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
47  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
48  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49  * SUCH DAMAGE.
50  *
51  * $OpenBSD: ahci.c,v 1.147 2009/02/16 21:19:07 miod Exp $
52  */
53
54 #include "ahci.h"
55
56 void    ahci_port_interrupt_enable(struct ahci_port *ap);
57
58 int     ahci_load_prdt(struct ahci_ccb *);
59 void    ahci_unload_prdt(struct ahci_ccb *);
60 static void ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs,
61                                     int nsegs, int error);
62 void    ahci_start(struct ahci_ccb *);
63 int     ahci_port_softreset(struct ahci_port *ap);
64 int     ahci_port_hardreset(struct ahci_port *ap, int hard);
65 void    ahci_port_hardstop(struct ahci_port *ap);
66
67 static void ahci_ata_cmd_timeout_unserialized(void *);
68 void    ahci_check_active_timeouts(struct ahci_port *ap);
69
70 void    ahci_beg_exclusive_access(struct ahci_port *ap, struct ata_port *at);
71 void    ahci_end_exclusive_access(struct ahci_port *ap, struct ata_port *at);
72 void    ahci_issue_pending_commands(struct ahci_port *ap, struct ahci_ccb *ccb);
73 void    ahci_issue_saved_commands(struct ahci_port *ap, u_int32_t mask);
74
75 int     ahci_port_read_ncq_error(struct ahci_port *, int);
76
77 struct ahci_dmamem *ahci_dmamem_alloc(struct ahci_softc *, bus_dma_tag_t tag);
78 void    ahci_dmamem_free(struct ahci_softc *, struct ahci_dmamem *);
79 static void ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error);
80
81 static void ahci_dummy_done(struct ata_xfer *xa);
82 static void ahci_empty_done(struct ahci_ccb *ccb);
83 static void ahci_ata_cmd_done(struct ahci_ccb *ccb);
84 static u_int32_t ahci_pactive(struct ahci_port *ap);
85
86 /*
87  * Initialize the global AHCI hardware.  This code does not set up any of
88  * its ports.
89  */
90 int
91 ahci_init(struct ahci_softc *sc)
92 {
93         u_int32_t       pi, pleft;
94         u_int32_t       bios_cap, vers;
95         int             i;
96         struct ahci_port *ap;
97
98         DPRINTF(AHCI_D_VERBOSE, " GHC 0x%b",
99                 ahci_read(sc, AHCI_REG_GHC), AHCI_FMT_GHC);
100
101         /*
102          * AHCI version.
103          */
104         vers = ahci_read(sc, AHCI_REG_VS);
105
106         /*
107          * save BIOS initialised parameters, enable staggered spin up
108          */
109         bios_cap = ahci_read(sc, AHCI_REG_CAP);
110         bios_cap &= AHCI_REG_CAP_SMPS | AHCI_REG_CAP_SSS;
111
112         pi = ahci_read(sc, AHCI_REG_PI);
113
114         /*
115          * Unconditionally reset the controller, do not conditionalize on
116          * trying to figure it if it was previously active or not.
117          *
118          * NOTE: On AE before HR.  The AHCI-1.1 spec has a note in section
119          *       5.2.2.1 regarding this.  HR should be set to 1 only after
120          *       AE is set to 1.  The reset sequence will clear HR when
121          *       it completes, and will also clear AE if SAM is 0.  AE must
122          *       then be set again.  When SAM is 1 the AE bit typically reads
123          *       as 1 (and is read-only).
124          *
125          * NOTE: Avoid PCI[e] transaction burst by issuing dummy reads,
126          *       otherwise the writes will only be separated by a few
127          *       nanoseconds.
128          *
129          * NOTE BRICKS (1)
130          *
131          *      If you have a port multiplier and it does not have a device
132          *      in target 0, and it probes normally, but a later operation
133          *      mis-probes a target behind that PM, it is possible for the
134          *      port to brick such that only (a) a power cycle of the host
135          *      or (b) placing a device in target 0 will fix the problem.
136          *      Power cycling the PM has no effect (it works fine on another
137          *      host port).  This issue is unrelated to CLO.
138          */
139         /*
140          * Wait for any prior reset sequence to complete
141          */
142         if (ahci_wait_ne(sc, AHCI_REG_GHC,
143                          AHCI_REG_GHC_HR, AHCI_REG_GHC_HR) != 0) {
144                 device_printf(sc->sc_dev, "Controller is stuck in reset\n");
145                 return (1);
146         }
147         ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE);
148         ahci_os_sleep(500);
149         ahci_read(sc, AHCI_REG_GHC);            /* flush */
150         ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE | AHCI_REG_GHC_HR);
151         ahci_os_sleep(500);
152         ahci_read(sc, AHCI_REG_GHC);            /* flush */
153         if (ahci_wait_ne(sc, AHCI_REG_GHC,
154                          AHCI_REG_GHC_HR, AHCI_REG_GHC_HR) != 0) {
155                 device_printf(sc->sc_dev, "unable to reset controller\n");
156                 return (1);
157         }
158         if (ahci_read(sc, AHCI_REG_GHC) & AHCI_REG_GHC_AE) {
159                 device_printf(sc->sc_dev, "AE did not auto-clear!\n");
160                 ahci_write(sc, AHCI_REG_GHC, 0);
161                 ahci_os_sleep(500);
162         }
163
164         /*
165          * Enable ahci (global interrupts disabled)
166          *
167          * Restore saved parameters.  Avoid pci transaction burst write
168          * by issuing dummy reads.
169          */
170         ahci_os_sleep(500);
171         ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE);
172         ahci_os_sleep(500);
173
174         ahci_read(sc, AHCI_REG_GHC);            /* flush */
175
176         bios_cap |= AHCI_REG_CAP_SSS;
177         ahci_write(sc, AHCI_REG_CAP, ahci_read(sc, AHCI_REG_CAP) | bios_cap);
178         ahci_write(sc, AHCI_REG_PI, pi);
179         ahci_read(sc, AHCI_REG_GHC);            /* flush */
180
181         /*
182          * Intel hocus pocus in case the BIOS has not set the chip up
183          * properly for AHCI operation.
184          */
185         if (pci_get_vendor(sc->sc_dev) == PCI_VENDOR_INTEL) {
186                 if ((pci_read_config(sc->sc_dev, 0x92, 2) & 0x0F) != 0x0F)
187                         device_printf(sc->sc_dev, "Intel hocus pocus\n");
188                 pci_write_config(sc->sc_dev, 0x92,
189                              pci_read_config(sc->sc_dev, 0x92, 2) | 0x0F, 2);
190         }
191
192         /*
193          * This is a hack that currently does not appear to have
194          * a significant effect, but I noticed the port registers
195          * do not appear to be completely cleared after the host
196          * controller is reset.
197          *
198          * Use a temporary ap structure so we can call ahci_pwrite().
199          *
200          * We must be sure to stop the port
201          */
202         ap = kmalloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO);
203         ap->ap_sc = sc;
204         pleft = pi;
205         for (i = 0; i < AHCI_MAX_PORTS; ++i) {
206                 if (pleft == 0)
207                         break;
208                 if ((pi & (1 << i)) == 0)
209                         continue;
210                 if (bus_space_subregion(sc->sc_iot, sc->sc_ioh,
211                     AHCI_PORT_REGION(i), AHCI_PORT_SIZE, &ap->ap_ioh) != 0) {
212                         device_printf(sc->sc_dev, "can't map port\n");
213                         return (1);
214                 }
215                 /*
216                  * NOTE!  Setting AHCI_PREG_SCTL_DET_DISABLE on AHCI1.0 or
217                  *        AHCI1.1 can brick the chipset.  Not only brick it,
218                  *        but also crash the PC.  The bit seems unreliable
219                  *        on AHCI1.2 as well.
220                  */
221                 ahci_port_stop(ap, 1);
222                 ahci_pwrite(ap, AHCI_PREG_SCTL, AHCI_PREG_SCTL_IPM_DISABLED);
223                 ahci_pwrite(ap, AHCI_PREG_SERR, -1);
224                 ahci_pwrite(ap, AHCI_PREG_IE, 0);
225                 ahci_write(ap->ap_sc, AHCI_REG_IS, 1 << i);
226                 ahci_pwrite(ap, AHCI_PREG_CMD, 0);
227                 ahci_pwrite(ap, AHCI_PREG_IS, -1);
228                 sc->sc_portmask |= (1 << i);
229                 pleft &= ~(1 << i);
230         }
231         sc->sc_numports = i;
232         kfree(ap, M_DEVBUF);
233
234         return (0);
235 }
236
237 /*
238  * Allocate and initialize an AHCI port.
239  */
240 int
241 ahci_port_alloc(struct ahci_softc *sc, u_int port)
242 {
243         struct ahci_port        *ap;
244         struct ata_port         *at;
245         struct ahci_ccb         *ccb;
246         u_int64_t               dva;
247         u_int32_t               cmd;
248         u_int32_t               data;
249         struct ahci_cmd_hdr     *hdr;
250         struct ahci_cmd_table   *table;
251         int     rc = ENOMEM;
252         int     error;
253         int     i;
254
255         ap = kmalloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO);
256         ap->ap_err_scratch = kmalloc(512, M_DEVBUF, M_WAITOK | M_ZERO);
257
258         ksnprintf(ap->ap_name, sizeof(ap->ap_name), "%s%d.%d",
259                   device_get_name(sc->sc_dev),
260                   device_get_unit(sc->sc_dev),
261                   port);
262         sc->sc_ports[port] = ap;
263
264         /*
265          * Allocate enough so we never have to reallocate, it makes
266          * it easier.
267          *
268          * ap_pmcount will be reduced by the scan if we encounter the
269          * port multiplier port prior to target 15.
270          *
271          * kmalloc power-of-2 allocations are guaranteed not to cross
272          * a page boundary.  Make sure the identify sub-structure in the
273          * at structure does not cross a page boundary, just in case the
274          * part is AHCI-1.1 and can't handle multiple DRQ blocks.
275          */
276         if (ap->ap_ata[0] == NULL) {
277                 int pw2;
278
279                 for (pw2 = 1; pw2 < sizeof(*at); pw2 <<= 1)
280                         ;
281                 for (i = 0; i < AHCI_MAX_PMPORTS; ++i) {
282                         at = kmalloc(pw2, M_DEVBUF, M_INTWAIT | M_ZERO);
283                         ap->ap_ata[i] = at;
284                         at->at_ahci_port = ap;
285                         at->at_target = i;
286                         at->at_probe = ATA_PROBE_NEED_INIT;
287                         at->at_features |= ATA_PORT_F_RESCAN;
288                         ksnprintf(at->at_name, sizeof(at->at_name),
289                                   "%s.%d", ap->ap_name, i);
290                 }
291         }
292         if (bus_space_subregion(sc->sc_iot, sc->sc_ioh,
293             AHCI_PORT_REGION(port), AHCI_PORT_SIZE, &ap->ap_ioh) != 0) {
294                 device_printf(sc->sc_dev,
295                               "unable to create register window for port %d\n",
296                               port);
297                 goto freeport;
298         }
299
300         ap->ap_sc = sc;
301         ap->ap_num = port;
302         ap->ap_probe = ATA_PROBE_NEED_INIT;
303         ap->link_pwr_mgmt = AHCI_LINK_PWR_MGMT_NONE;
304         ap->sysctl_tree = NULL;
305         TAILQ_INIT(&ap->ap_ccb_free);
306         TAILQ_INIT(&ap->ap_ccb_pending);
307         lockinit(&ap->ap_ccb_lock, "ahcipo", 0, 0);
308
309         /* Disable port interrupts */
310         ahci_pwrite(ap, AHCI_PREG_IE, 0);
311         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
312
313         /*
314          * Sec 10.1.2 - deinitialise port if it is already running
315          */
316         cmd = ahci_pread(ap, AHCI_PREG_CMD);
317         kprintf("%s: Caps %b\n", PORTNAME(ap), cmd, AHCI_PFMT_CMD);
318
319         if ((cmd & (AHCI_PREG_CMD_ST | AHCI_PREG_CMD_CR |
320                     AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_FR)) ||
321             (ahci_pread(ap, AHCI_PREG_SCTL) & AHCI_PREG_SCTL_DET)) {
322                 int r;
323
324                 r = ahci_port_stop(ap, 1);
325                 if (r) {
326                         device_printf(sc->sc_dev,
327                                   "unable to disable %s, ignoring port %d\n",
328                                   ((r == 2) ? "CR" : "FR"), port);
329                         rc = ENXIO;
330                         goto freeport;
331                 }
332
333                 /* Write DET to zero */
334                 ahci_pwrite(ap, AHCI_PREG_SCTL, AHCI_PREG_SCTL_IPM_DISABLED);
335         }
336
337         /* Allocate RFIS */
338         ap->ap_dmamem_rfis = ahci_dmamem_alloc(sc, sc->sc_tag_rfis);
339         if (ap->ap_dmamem_rfis == NULL) {
340                 kprintf("%s: NORFIS\n", PORTNAME(ap));
341                 goto nomem;
342         }
343
344         /* Setup RFIS base address */
345         ap->ap_rfis = (struct ahci_rfis *) AHCI_DMA_KVA(ap->ap_dmamem_rfis);
346         dva = AHCI_DMA_DVA(ap->ap_dmamem_rfis);
347         ahci_pwrite(ap, AHCI_PREG_FBU, (u_int32_t)(dva >> 32));
348         ahci_pwrite(ap, AHCI_PREG_FB, (u_int32_t)dva);
349
350         /* Clear SERR before starting FIS reception or ST or anything */
351         ahci_flush_tfd(ap);
352         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
353
354         /* Enable FIS reception and activate port. */
355         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
356         cmd &= ~(AHCI_PREG_CMD_CLO | AHCI_PREG_CMD_PMA);
357         cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD | AHCI_PREG_CMD_SUD;
358         ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_ICC_ACTIVE);
359
360         /* Check whether port activated.  Skip it if not. */
361         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
362         if ((cmd & AHCI_PREG_CMD_FRE) == 0) {
363                 kprintf("%s: NOT-ACTIVATED\n", PORTNAME(ap));
364                 rc = ENXIO;
365                 goto freeport;
366         }
367
368         /* Allocate a CCB for each command slot */
369         ap->ap_ccbs = kmalloc(sizeof(struct ahci_ccb) * sc->sc_ncmds, M_DEVBUF,
370                               M_WAITOK | M_ZERO);
371         if (ap->ap_ccbs == NULL) {
372                 device_printf(sc->sc_dev,
373                               "unable to allocate command list for port %d\n",
374                               port);
375                 goto freeport;
376         }
377
378         /* Command List Structures and Command Tables */
379         ap->ap_dmamem_cmd_list = ahci_dmamem_alloc(sc, sc->sc_tag_cmdh);
380         ap->ap_dmamem_cmd_table = ahci_dmamem_alloc(sc, sc->sc_tag_cmdt);
381         if (ap->ap_dmamem_cmd_table == NULL ||
382             ap->ap_dmamem_cmd_list == NULL) {
383 nomem:
384                 device_printf(sc->sc_dev,
385                               "unable to allocate DMA memory for port %d\n",
386                               port);
387                 goto freeport;
388         }
389
390         /* Setup command list base address */
391         dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_list);
392         ahci_pwrite(ap, AHCI_PREG_CLBU, (u_int32_t)(dva >> 32));
393         ahci_pwrite(ap, AHCI_PREG_CLB, (u_int32_t)dva);
394
395         /* Split CCB allocation into CCBs and assign to command header/table */
396         hdr = AHCI_DMA_KVA(ap->ap_dmamem_cmd_list);
397         table = AHCI_DMA_KVA(ap->ap_dmamem_cmd_table);
398         for (i = 0; i < sc->sc_ncmds; i++) {
399                 ccb = &ap->ap_ccbs[i];
400
401                 error = bus_dmamap_create(sc->sc_tag_data, BUS_DMA_ALLOCNOW,
402                                           &ccb->ccb_dmamap);
403                 if (error) {
404                         device_printf(sc->sc_dev,
405                                       "unable to create dmamap for port %d "
406                                       "ccb %d\n", port, i);
407                         goto freeport;
408                 }
409
410                 callout_init_mp(&ccb->ccb_timeout);
411                 ccb->ccb_slot = i;
412                 ccb->ccb_port = ap;
413                 ccb->ccb_cmd_hdr = &hdr[i];
414                 ccb->ccb_cmd_table = &table[i];
415                 dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_table) +
416                     ccb->ccb_slot * sizeof(struct ahci_cmd_table);
417                 ccb->ccb_cmd_hdr->ctba_hi = htole32((u_int32_t)(dva >> 32));
418                 ccb->ccb_cmd_hdr->ctba_lo = htole32((u_int32_t)dva);
419
420                 ccb->ccb_xa.fis =
421                     (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
422                 ccb->ccb_xa.packetcmd = ccb->ccb_cmd_table->acmd;
423                 ccb->ccb_xa.tag = i;
424
425                 ccb->ccb_xa.state = ATA_S_COMPLETE;
426
427                 /*
428                  * CCB[1] is the error CCB and is not get or put.  It is
429                  * also used for probing.  Numerous HBAs only load the
430                  * signature from CCB[1] so it MUST be used for the second
431                  * FIS.
432                  */
433                 if (i == 1)
434                         ap->ap_err_ccb = ccb;
435                 else
436                         ahci_put_ccb(ccb);
437         }
438
439         /*
440          * Wait for ICC change to complete
441          */
442         ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_ICC);
443
444         /*
445          * Calculate the interrupt mask
446          */
447         data = AHCI_PREG_IE_TFEE | AHCI_PREG_IE_HBFE |
448                AHCI_PREG_IE_IFE | AHCI_PREG_IE_OFE |
449                AHCI_PREG_IE_DPE | AHCI_PREG_IE_UFE |
450                AHCI_PREG_IE_PCE | AHCI_PREG_IE_PRCE |
451                AHCI_PREG_IE_DHRE | AHCI_PREG_IE_SDBE;
452         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF)
453                 data |= AHCI_PREG_IE_IPME;
454 #ifdef AHCI_COALESCE
455         if (sc->sc_ccc_ports & (1 << port)
456                 data &= ~(AHCI_PREG_IE_SDBE | AHCI_PREG_IE_DHRE);
457 #endif
458         ap->ap_intmask = data;
459
460         /*
461          * Start the port helper thread.  The helper thread will call
462          * ahci_port_init() so the ports can all be started in parallel.
463          * A failure by ahci_port_init() does not deallocate the port
464          * since we still want hot-plug events.
465          */
466         ahci_os_start_port(ap);
467         return(0);
468 freeport:
469         ahci_port_free(sc, port);
470         return (rc);
471 }
472
473 /*
474  * [re]initialize an idle port.  No CCBs should be active.  (from port thread)
475  *
476  * This function is called during the initial port allocation sequence
477  * and is also called on hot-plug insertion.  We take no chances and
478  * use a portreset instead of a softreset.
479  *
480  * This function is the only way to move a failed port back to active
481  * status.
482  *
483  * Returns 0 if a device is successfully detected.
484  */
485 int
486 ahci_port_init(struct ahci_port *ap)
487 {
488         u_int32_t cmd;
489
490         /*
491          * Register [re]initialization
492          *
493          * Flush the TFD and SERR and make sure the port is stopped before
494          * enabling its interrupt.  We no longer cycle the port start as
495          * the port should not be started unless a device is present.
496          *
497          * XXX should we enable FIS reception? (FRE)?
498          */
499         ahci_pwrite(ap, AHCI_PREG_IE, 0);
500         ahci_port_stop(ap, 0);
501         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF)
502                 ahci_pwrite(ap, AHCI_PREG_SNTF, -1);
503         ahci_flush_tfd(ap);
504         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
505
506         /*
507          * If we are being harsh try to kill the port completely.  Normally
508          * we would want to hold on to some of the state the BIOS may have
509          * set, such as SUD (spin up device).
510          *
511          * AP_F_HARSH_REINIT is cleared in the hard reset state
512          */
513         if (ap->ap_flags & AP_F_HARSH_REINIT) {
514                 ahci_pwrite(ap, AHCI_PREG_SCTL, AHCI_PREG_SCTL_IPM_DISABLED);
515                 ahci_pwrite(ap, AHCI_PREG_CMD, 0);
516
517                 ahci_os_sleep(1000);
518
519                 cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
520                 cmd &= ~(AHCI_PREG_CMD_CLO | AHCI_PREG_CMD_PMA);
521                 cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD |
522                        AHCI_PREG_CMD_SUD;
523                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_ICC_ACTIVE);
524                 cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
525                 if ((cmd & AHCI_PREG_CMD_FRE) == 0) {
526                         kprintf("%s: Warning: FRE did not come up during "
527                                 "harsh reinitialization\n",
528                                 PORTNAME(ap));
529                 }
530                 ahci_os_sleep(1000);
531         }
532
533         /*
534          * Clear any pending garbage and re-enable the interrupt before
535          * going to the next stage.
536          */
537         ap->ap_probe = ATA_PROBE_NEED_HARD_RESET;
538         ap->ap_pmcount = 0;
539
540         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF)
541                 ahci_pwrite(ap, AHCI_PREG_SNTF, -1);
542         ahci_flush_tfd(ap);
543         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
544         ahci_pwrite(ap, AHCI_PREG_IS, -1);
545
546         ahci_port_interrupt_enable(ap);
547
548         return (0);
549 }
550
551 /*
552  * Enable or re-enable interrupts on a port.
553  *
554  * This routine is called from the port initialization code or from the
555  * helper thread as the real interrupt may be forced to turn off certain
556  * interrupt sources.
557  */
558 void
559 ahci_port_interrupt_enable(struct ahci_port *ap)
560 {
561         ahci_pwrite(ap, AHCI_PREG_IE, ap->ap_intmask);
562 }
563
564 /*
565  * Manage the agressive link power management capability.
566  */
567 void
568 ahci_port_link_pwr_mgmt(struct ahci_port *ap, int link_pwr_mgmt)
569 {
570         u_int32_t cmd, sctl;
571
572         if (link_pwr_mgmt == ap->link_pwr_mgmt)
573                 return;
574
575         if ((ap->ap_sc->sc_cap & AHCI_REG_CAP_SALP) == 0) {
576                 kprintf("%s: link power management not supported.\n",
577                         PORTNAME(ap));
578                 return;
579         }
580
581         ahci_os_lock_port(ap);
582
583         if (link_pwr_mgmt == AHCI_LINK_PWR_MGMT_AGGR &&
584             (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSC)) {
585                 kprintf("%s: enabling aggressive link power management.\n",
586                         PORTNAME(ap));
587
588                 ap->link_pwr_mgmt = link_pwr_mgmt;
589
590                 ap->ap_intmask &= ~AHCI_PREG_IE_PRCE;
591                 ahci_port_interrupt_enable(ap);
592
593                 sctl = ahci_pread(ap, AHCI_PREG_SCTL);
594                 sctl &= ~(AHCI_PREG_SCTL_IPM_DISABLED);
595                 ahci_pwrite(ap, AHCI_PREG_SCTL, sctl);
596
597                 /*
598                  * Enable device initiated link power management for
599                  * directly attached devices that support it.
600                  */
601                 if (ap->ap_type != ATA_PORT_T_PM &&
602                     (ap->ap_ata[0]->at_identify.satafsup &
603                     SATA_FEATURE_SUP_DEVIPS)) {
604                         if (ahci_set_feature(ap, NULL, ATA_SATAFT_DEVIPS, 1))
605                                 kprintf("%s: Could not enable device initiated "
606                                     "link power management.\n",
607                                     PORTNAME(ap));
608                 }
609
610                 cmd = ahci_pread(ap, AHCI_PREG_CMD);
611                 cmd |= AHCI_PREG_CMD_ASP;
612                 cmd |= AHCI_PREG_CMD_ALPE;
613                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
614
615         } else if (link_pwr_mgmt == AHCI_LINK_PWR_MGMT_MEDIUM &&
616                    (ap->ap_sc->sc_cap & AHCI_REG_CAP_PSC)) {
617                 kprintf("%s: enabling medium link power management.\n",
618                         PORTNAME(ap));
619
620                 ap->link_pwr_mgmt = link_pwr_mgmt;
621
622                 ap->ap_intmask &= ~AHCI_PREG_IE_PRCE;
623                 ahci_port_interrupt_enable(ap);
624
625                 sctl = ahci_pread(ap, AHCI_PREG_SCTL);
626                 sctl |= AHCI_PREG_SCTL_IPM_DISABLED;
627                 sctl &= ~AHCI_PREG_SCTL_IPM_NOPARTIAL;
628                 ahci_pwrite(ap, AHCI_PREG_SCTL, sctl);
629
630                 cmd = ahci_pread(ap, AHCI_PREG_CMD);
631                 cmd &= ~AHCI_PREG_CMD_ASP;
632                 cmd |= AHCI_PREG_CMD_ALPE;
633                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
634
635         } else if (link_pwr_mgmt == AHCI_LINK_PWR_MGMT_NONE) {
636                 kprintf("%s: disabling link power management.\n",
637                         PORTNAME(ap));
638
639                 /* Disable device initiated link power management */
640                 if (ap->ap_type != ATA_PORT_T_PM &&
641                     (ap->ap_ata[0]->at_identify.satafsup &
642                     SATA_FEATURE_SUP_DEVIPS)) {
643                         ahci_set_feature(ap, NULL, ATA_SATAFT_DEVIPS, 0);
644                 }
645
646                 cmd = ahci_pread(ap, AHCI_PREG_CMD);
647                 cmd &= ~(AHCI_PREG_CMD_ALPE | AHCI_PREG_CMD_ASP);
648                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
649
650                 sctl = ahci_pread(ap, AHCI_PREG_SCTL);
651                 sctl |= AHCI_PREG_SCTL_IPM_DISABLED;
652                 ahci_pwrite(ap, AHCI_PREG_SCTL, sctl);
653
654                 /* let the drive come back to avoid PRCS interrupts later */
655                 ahci_os_unlock_port(ap);
656                 ahci_os_sleep(1000);
657                 ahci_os_lock_port(ap);
658
659                 ahci_pwrite(ap, AHCI_PREG_SERR,
660                             AHCI_PREG_SERR_DIAG_N | AHCI_PREG_SERR_DIAG_W);
661                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_PRCS);
662
663                 ap->ap_intmask |= AHCI_PREG_IE_PRCE;
664                 ahci_port_interrupt_enable(ap);
665
666                 ap->link_pwr_mgmt = link_pwr_mgmt;
667         } else {
668                 kprintf("%s: unsupported link power management state %d.\n",
669                         PORTNAME(ap), link_pwr_mgmt);
670         }
671
672         ahci_os_unlock_port(ap);
673 }
674
675 /*
676  * Return current link power state.
677  */
678 int
679 ahci_port_link_pwr_state(struct ahci_port *ap)
680 {
681         uint32_t r;
682
683         r = ahci_pread(ap, AHCI_PREG_SSTS);
684         switch (r & AHCI_PREG_SSTS_IPM) {
685         case AHCI_PREG_SSTS_IPM_ACTIVE:
686                 return 1;
687         case AHCI_PREG_SSTS_IPM_PARTIAL:
688                 return 2;
689         case AHCI_PREG_SSTS_IPM_SLUMBER:
690                 return 3;
691         case AHCI_PREG_SSTS_IPM_DEVSLEEP:
692                 return 4;
693         default:
694                 return 0;
695         }
696 }
697
698 /*
699  * Run the port / target state machine from a main context.
700  *
701  * The state machine for the port is always run.
702  *
703  * If atx is non-NULL run the state machine for a particular target.
704  * If atx is NULL run the state machine for all targets.
705  */
706 void
707 ahci_port_state_machine(struct ahci_port *ap, int initial)
708 {
709         struct ata_port *at;
710         u_int32_t data;
711         int target;
712         int didsleep;
713         int loop;
714
715         /*
716          * State machine for port.  Note that CAM is not yet associated
717          * during the initial parallel probe and the port's probe state
718          * will not get past ATA_PROBE_NEED_IDENT.
719          */
720         {
721                 if (initial == 0 && ap->ap_probe <= ATA_PROBE_NEED_HARD_RESET) {
722                         kprintf("%s: Waiting 10 seconds on insertion\n",
723                                 PORTNAME(ap));
724                         ahci_os_sleep(10000);
725                         initial = 1;
726                 }
727                 if (ap->ap_probe == ATA_PROBE_NEED_INIT)
728                         ahci_port_init(ap);
729                 if (ap->ap_probe == ATA_PROBE_NEED_HARD_RESET)
730                         ahci_port_reset(ap, NULL, 1);
731                 if (ap->ap_probe == ATA_PROBE_NEED_SOFT_RESET)
732                         ahci_port_reset(ap, NULL, 0);
733                 if (ap->ap_probe == ATA_PROBE_NEED_IDENT)
734                         ahci_cam_probe(ap, NULL);
735         }
736         if (ap->ap_type != ATA_PORT_T_PM) {
737                 if (ap->ap_probe == ATA_PROBE_FAILED) {
738                         ahci_cam_changed(ap, NULL, 0);
739                 } else if (ap->ap_probe >= ATA_PROBE_NEED_IDENT) {
740                         ahci_cam_changed(ap, NULL, 1);
741                 }
742                 return;
743         }
744
745         /*
746          * Port Multiplier state machine.
747          *
748          * Get a mask of changed targets and combine with any runnable
749          * states already present.
750          */
751         for (loop = 0; ;++loop) {
752                 if (ahci_pm_read(ap, 15, SATA_PMREG_EINFO, &data)) {
753                         kprintf("%s: PM unable to read hot-plug bitmap\n",
754                                 PORTNAME(ap));
755                         break;
756                 }
757
758                 /*
759                  * Do at least one loop, then stop if no more state changes
760                  * have occured.  The PM might not generate a new
761                  * notification until we clear the entire bitmap.
762                  */
763                 if (loop && data == 0)
764                         break;
765
766                 /*
767                  * New devices showing up in the bitmap require some spin-up
768                  * time before we start probing them.  Reset didsleep.  The
769                  * first new device we detect will sleep before probing.
770                  *
771                  * This only applies to devices whos change bit is set in
772                  * the data, and does not apply to the initial boot-time
773                  * probe.
774                  */
775                 didsleep = 0;
776
777                 for (target = 0; target < ap->ap_pmcount; ++target) {
778                         at = ap->ap_ata[target];
779
780                         /*
781                          * Check the target state for targets behind the PM
782                          * which have changed state.  This will adjust
783                          * at_probe and set ATA_PORT_F_RESCAN
784                          *
785                          * We want to wait at least 10 seconds before probing
786                          * a newly inserted device.  If the check status
787                          * indicates a device is present and in need of a
788                          * hard reset, we make sure we have slept before
789                          * continuing.
790                          *
791                          * We also need to wait at least 1 second for the
792                          * PHY state to change after insertion, if we
793                          * haven't already waited the 10 seconds.
794                          *
795                          * NOTE: When pm_check_good finds a good port it
796                          *       typically starts us in probe state
797                          *       NEED_HARD_RESET rather than INIT.
798                          */
799                         if (data & (1 << target)) {
800                                 if (initial == 0 && didsleep == 0)
801                                         ahci_os_sleep(1000);
802                                 ahci_pm_check_good(ap, target);
803                                 if (initial == 0 && didsleep == 0 &&
804                                     at->at_probe <= ATA_PROBE_NEED_HARD_RESET
805                                 ) {
806                                         didsleep = 1;
807                                         kprintf("%s: Waiting 10 seconds on insertion\n", PORTNAME(ap));
808                                         ahci_os_sleep(10000);
809                                 }
810                         }
811
812                         /*
813                          * Report hot-plug events before the probe state
814                          * really gets hot.  Only actual events are reported
815                          * here to reduce spew.
816                          */
817                         if (data & (1 << target)) {
818                                 kprintf("%s: HOTPLUG (PM) - ", ATANAME(ap, at));
819                                 switch(at->at_probe) {
820                                 case ATA_PROBE_NEED_INIT:
821                                 case ATA_PROBE_NEED_HARD_RESET:
822                                         kprintf("Device inserted\n");
823                                         break;
824                                 case ATA_PROBE_FAILED:
825                                         kprintf("Device removed\n");
826                                         break;
827                                 default:
828                                         kprintf("Device probe in progress\n");
829                                         break;
830                                 }
831                         }
832
833                         /*
834                          * Run through the state machine as necessary if
835                          * the port is not marked failed.
836                          *
837                          * The state machine may stop at NEED_IDENT if
838                          * CAM is not yet attached.
839                          *
840                          * Acquire exclusive access to the port while we
841                          * are doing this.  This prevents command-completion
842                          * from queueing commands for non-polled targets
843                          * inbetween our probe steps.  We need to do this
844                          * because the reset probes can generate severe PHY
845                          * and protocol errors and soft-brick the port.
846                          */
847                         if (at->at_probe != ATA_PROBE_FAILED &&
848                             at->at_probe != ATA_PROBE_GOOD) {
849                                 ahci_beg_exclusive_access(ap, at);
850                                 if (at->at_probe == ATA_PROBE_NEED_INIT)
851                                         ahci_pm_port_init(ap, at);
852                                 if (at->at_probe == ATA_PROBE_NEED_HARD_RESET)
853                                         ahci_port_reset(ap, at, 1);
854                                 if (at->at_probe == ATA_PROBE_NEED_SOFT_RESET)
855                                         ahci_port_reset(ap, at, 0);
856                                 if (at->at_probe == ATA_PROBE_NEED_IDENT)
857                                         ahci_cam_probe(ap, at);
858                                 ahci_end_exclusive_access(ap, at);
859                         }
860
861                         /*
862                          * Add or remove from CAM
863                          */
864                         if (at->at_features & ATA_PORT_F_RESCAN) {
865                                 at->at_features &= ~ATA_PORT_F_RESCAN;
866                                 if (at->at_probe == ATA_PROBE_FAILED) {
867                                         ahci_cam_changed(ap, at, 0);
868                                 } else if (at->at_probe >= ATA_PROBE_NEED_IDENT) {
869                                         ahci_cam_changed(ap, at, 1);
870                                 }
871                         }
872                         data &= ~(1 << target);
873                 }
874                 if (data) {
875                         kprintf("%s: WARNING (PM): extra bits set in "
876                                 "EINFO: %08x\n", PORTNAME(ap), data);
877                         while (target < AHCI_MAX_PMPORTS) {
878                                 ahci_pm_check_good(ap, target);
879                                 ++target;
880                         }
881                 }
882         }
883 }
884
885
886 /*
887  * De-initialize and detach a port.
888  */
889 void
890 ahci_port_free(struct ahci_softc *sc, u_int port)
891 {
892         struct ahci_port        *ap = sc->sc_ports[port];
893         struct ahci_ccb         *ccb;
894         int i;
895
896         /*
897          * Ensure port is disabled and its interrupts are all flushed.
898          */
899         if (ap->ap_sc) {
900                 ahci_port_stop(ap, 1);
901                 ahci_os_stop_port(ap);
902                 ahci_pwrite(ap, AHCI_PREG_CMD, 0);
903                 ahci_pwrite(ap, AHCI_PREG_IE, 0);
904                 ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
905                 ahci_write(sc, AHCI_REG_IS, 1 << port);
906         }
907
908         if (ap->ap_ccbs) {
909                 while ((ccb = ahci_get_ccb(ap)) != NULL) {
910                         if (ccb->ccb_dmamap) {
911                                 bus_dmamap_destroy(sc->sc_tag_data,
912                                                    ccb->ccb_dmamap);
913                                 ccb->ccb_dmamap = NULL;
914                         }
915                 }
916                 if ((ccb = ap->ap_err_ccb) != NULL) {
917                         if (ccb->ccb_dmamap) {
918                                 bus_dmamap_destroy(sc->sc_tag_data,
919                                                    ccb->ccb_dmamap);
920                                 ccb->ccb_dmamap = NULL;
921                         }
922                         ap->ap_err_ccb = NULL;
923                 }
924                 kfree(ap->ap_ccbs, M_DEVBUF);
925                 ap->ap_ccbs = NULL;
926         }
927
928         if (ap->ap_dmamem_cmd_list) {
929                 ahci_dmamem_free(sc, ap->ap_dmamem_cmd_list);
930                 ap->ap_dmamem_cmd_list = NULL;
931         }
932         if (ap->ap_dmamem_rfis) {
933                 ahci_dmamem_free(sc, ap->ap_dmamem_rfis);
934                 ap->ap_dmamem_rfis = NULL;
935         }
936         if (ap->ap_dmamem_cmd_table) {
937                 ahci_dmamem_free(sc, ap->ap_dmamem_cmd_table);
938                 ap->ap_dmamem_cmd_table = NULL;
939         }
940         if (ap->ap_ata) {
941                 for (i = 0; i < AHCI_MAX_PMPORTS; ++i) {
942                         if (ap->ap_ata[i]) {
943                                 kfree(ap->ap_ata[i], M_DEVBUF);
944                                 ap->ap_ata[i] = NULL;
945                         }
946                 }
947         }
948         if (ap->ap_err_scratch) {
949                 kfree(ap->ap_err_scratch, M_DEVBUF);
950                 ap->ap_err_scratch = NULL;
951         }
952
953         /* bus_space(9) says we dont free the subregions handle */
954
955         kfree(ap, M_DEVBUF);
956         sc->sc_ports[port] = NULL;
957 }
958
959 static
960 u_int32_t
961 ahci_pactive(struct ahci_port *ap)
962 {
963         u_int32_t mask;
964
965         mask = ahci_pread(ap, AHCI_PREG_CI);
966         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SNCQ)
967                 mask |= ahci_pread(ap, AHCI_PREG_SACT);
968         return(mask);
969 }
970
971 /*
972  * Start high-level command processing on the port
973  */
974 int
975 ahci_port_start(struct ahci_port *ap)
976 {
977         u_int32_t       r, s, is, tfd;
978
979         /*
980          * FRE must be turned on before ST.  Wait for FR to go active
981          * before turning on ST.  The spec doesn't seem to think this
982          * is necessary but waiting here avoids an on-off race in the
983          * ahci_port_stop() code.
984          */
985         r = ahci_pread(ap, AHCI_PREG_CMD);
986         if ((r & AHCI_PREG_CMD_FRE) == 0) {
987                 r |= AHCI_PREG_CMD_FRE;
988                 ahci_pwrite(ap, AHCI_PREG_CMD, r);
989         }
990         if ((ap->ap_sc->sc_flags & AHCI_F_IGN_FR) == 0) {
991                 if (ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR)) {
992                         kprintf("%s: Cannot start FIS reception\n",
993                                 PORTNAME(ap));
994                         return (2);
995                 }
996         } else {
997                 ahci_os_sleep(10);
998         }
999
1000         /*
1001          * Turn on ST, wait for CR to come up.
1002          */
1003         r |= AHCI_PREG_CMD_ST;
1004         ahci_pwrite(ap, AHCI_PREG_CMD, r);
1005         if (ahci_pwait_set_to(ap, 2000, AHCI_PREG_CMD, AHCI_PREG_CMD_CR)) {
1006                 s = ahci_pread(ap, AHCI_PREG_SERR);
1007                 is = ahci_pread(ap, AHCI_PREG_IS);
1008                 tfd = ahci_pread(ap, AHCI_PREG_TFD);
1009                 kprintf("%s: Cannot start command DMA\n"
1010                         "NCMP=%b NSERR=%b\n"
1011                         "NEWIS=%b\n"
1012                         "NEWTFD=%b\n",
1013                         PORTNAME(ap),
1014                         r, AHCI_PFMT_CMD, s, AHCI_PFMT_SERR,
1015                         is, AHCI_PFMT_IS,
1016                         tfd, AHCI_PFMT_TFD_STS);
1017                 return (1);
1018         }
1019
1020 #ifdef AHCI_COALESCE
1021         /*
1022          * (Re-)enable coalescing on the port.
1023          */
1024         if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
1025                 ap->ap_sc->sc_ccc_ports_cur |= (1 << ap->ap_num);
1026                 ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
1027                     ap->ap_sc->sc_ccc_ports_cur);
1028         }
1029 #endif
1030
1031         return (0);
1032 }
1033
1034 /*
1035  * Stop high-level command processing on a port
1036  *
1037  * WARNING!  If the port is stopped while CR is still active our saved
1038  *           CI/SACT will race any commands completed by the command
1039  *           processor prior to being able to stop.  Thus we never call
1040  *           this function unless we intend to dispose of any remaining
1041  *           active commands.  In particular, this complicates the timeout
1042  *           code.
1043  */
1044 int
1045 ahci_port_stop(struct ahci_port *ap, int stop_fis_rx)
1046 {
1047         u_int32_t       r;
1048
1049 #ifdef AHCI_COALESCE
1050         /*
1051          * Disable coalescing on the port while it is stopped.
1052          */
1053         if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
1054                 ap->ap_sc->sc_ccc_ports_cur &= ~(1 << ap->ap_num);
1055                 ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
1056                     ap->ap_sc->sc_ccc_ports_cur);
1057         }
1058 #endif
1059
1060         /*
1061          * Turn off ST, then wait for CR to go off.
1062          */
1063         r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1064         r &= ~AHCI_PREG_CMD_ST;
1065         ahci_pwrite(ap, AHCI_PREG_CMD, r);
1066
1067         if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CR)) {
1068                 kprintf("%s: Port bricked, unable to stop (ST)\n",
1069                         PORTNAME(ap));
1070                 return (1);
1071         }
1072
1073 #if 0
1074         /*
1075          * Turn off FRE, then wait for FR to go off.  FRE cannot
1076          * be turned off until CR transitions to 0.
1077          */
1078         if ((r & AHCI_PREG_CMD_FR) == 0) {
1079                 kprintf("%s: FR stopped, clear FRE for next start\n",
1080                         PORTNAME(ap));
1081                 stop_fis_rx = 2;
1082         }
1083 #endif
1084         if (stop_fis_rx) {
1085                 r &= ~AHCI_PREG_CMD_FRE;
1086                 ahci_pwrite(ap, AHCI_PREG_CMD, r);
1087                 if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR)) {
1088                         kprintf("%s: Port bricked, unable to stop (FRE)\n",
1089                                 PORTNAME(ap));
1090                         return (2);
1091                 }
1092         }
1093
1094         return (0);
1095 }
1096
1097 /*
1098  * AHCI command list override -> forcibly clear TFD.STS.{BSY,DRQ}
1099  */
1100 int
1101 ahci_port_clo(struct ahci_port *ap)
1102 {
1103         struct ahci_softc               *sc = ap->ap_sc;
1104         u_int32_t                       cmd;
1105
1106         /* Only attempt CLO if supported by controller */
1107         if ((ahci_read(sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO) == 0)
1108                 return (1);
1109
1110         /* Issue CLO */
1111         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1112         ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_CLO);
1113
1114         /* Wait for completion */
1115         if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CLO)) {
1116                 kprintf("%s: CLO did not complete\n", PORTNAME(ap));
1117                 return (1);
1118         }
1119
1120         return (0);
1121 }
1122
1123 /*
1124  * Reset a port.
1125  *
1126  * If hard is 0 perform a softreset of the port.
1127  * If hard is 1 perform a hard reset of the port.
1128  *
1129  * If at is non-NULL an indirect port via a port-multiplier is being
1130  * reset, otherwise a direct port is being reset.
1131  *
1132  * NOTE: Indirect ports can only be soft-reset.
1133  */
1134 int
1135 ahci_port_reset(struct ahci_port *ap, struct ata_port *at, int hard)
1136 {
1137         int rc;
1138
1139         if (hard) {
1140                 if (at)
1141                         rc = ahci_pm_hardreset(ap, at->at_target, hard);
1142                 else
1143                         rc = ahci_port_hardreset(ap, hard);
1144         } else {
1145                 if (at)
1146                         rc = ahci_pm_softreset(ap, at->at_target);
1147                 else
1148                         rc = ahci_port_softreset(ap);
1149         }
1150         return(rc);
1151 }
1152
1153 /*
1154  * AHCI soft reset, Section 10.4.1
1155  *
1156  * (at) will be NULL when soft-resetting a directly-attached device, and
1157  * non-NULL when soft-resetting a device through a port multiplier.
1158  *
1159  * This function keeps port communications intact and attempts to generate
1160  * a reset to the connected device using device commands.
1161  */
1162 int
1163 ahci_port_softreset(struct ahci_port *ap)
1164 {
1165         struct ahci_ccb         *ccb = NULL;
1166         struct ahci_cmd_hdr     *cmd_slot;
1167         u_int8_t                *fis;
1168         int                     error;
1169
1170         error = EIO;
1171
1172         if (bootverbose) {
1173                 kprintf("%s: START SOFTRESET %b\n", PORTNAME(ap),
1174                         ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD);
1175         }
1176
1177         DPRINTF(AHCI_D_VERBOSE, "%s: soft reset\n", PORTNAME(ap));
1178
1179         crit_enter();
1180         ap->ap_flags |= AP_F_IN_RESET;
1181         ap->ap_state = AP_S_NORMAL;
1182
1183         /*
1184          * Remember port state in cmd (main to restore start/stop)
1185          *
1186          * Idle port.
1187          */
1188         if (ahci_port_stop(ap, 0)) {
1189                 kprintf("%s: failed to stop port, cannot softreset\n",
1190                         PORTNAME(ap));
1191                 goto err;
1192         }
1193
1194         /*
1195          * Request CLO if device appears hung.
1196          */
1197         if (ahci_pread(ap, AHCI_PREG_TFD) &
1198                    (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1199                 ahci_port_clo(ap);
1200         }
1201
1202         /*
1203          * This is an attempt to clear errors so a new signature will
1204          * be latched.  It isn't working properly.  XXX
1205          */
1206         ahci_flush_tfd(ap);
1207         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1208
1209         /* Restart port */
1210         if (ahci_port_start(ap)) {
1211                 kprintf("%s: failed to start port, cannot softreset\n",
1212                         PORTNAME(ap));
1213                 goto err;
1214         }
1215
1216         /* Check whether CLO worked */
1217         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1218                                AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1219                 kprintf("%s: CLO %s, need port reset\n",
1220                         PORTNAME(ap),
1221                         (ahci_read(ap->ap_sc, AHCI_REG_CAP) & AHCI_REG_CAP_SCLO)
1222                         ? "failed" : "unsupported");
1223                 error = EBUSY;
1224                 goto err;
1225         }
1226
1227         /*
1228          * Prep first D2H command with SRST feature & clear busy/reset flags
1229          *
1230          * It is unclear which other fields in the FIS are used.  Just zero
1231          * everything.
1232          *
1233          * NOTE!  This CCB is used for both the first and second commands.
1234          *        The second command must use CCB slot 1 to properly load
1235          *        the signature.
1236          */
1237         ccb = ahci_get_err_ccb(ap);
1238         ccb->ccb_xa.complete = ahci_dummy_done;
1239         ccb->ccb_xa.flags = ATA_F_POLL | ATA_F_EXCLUSIVE;
1240         KKASSERT(ccb->ccb_slot == 1);
1241         ccb->ccb_xa.at = NULL;
1242         cmd_slot = ccb->ccb_cmd_hdr;
1243
1244         fis = ccb->ccb_cmd_table->cfis;
1245         bzero(fis, sizeof(ccb->ccb_cmd_table->cfis));
1246         fis[0] = ATA_FIS_TYPE_H2D;
1247         fis[15] = ATA_FIS_CONTROL_SRST|ATA_FIS_CONTROL_4BIT;
1248
1249         cmd_slot->prdtl = 0;
1250         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
1251         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_C); /* Clear busy on OK */
1252         cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_R); /* Reset */
1253
1254         ccb->ccb_xa.state = ATA_S_PENDING;
1255
1256         if (ahci_poll(ccb, 1000, ahci_quick_timeout) != ATA_S_COMPLETE) {
1257                 kprintf("%s: First FIS failed\n", PORTNAME(ap));
1258                 goto err;
1259         }
1260
1261         /*
1262          * WARNING!     TIME SENSITIVE SPACE!   WARNING!
1263          *
1264          * The two FISes are supposed to be back to back.  Don't issue other
1265          * commands or even delay if we can help it.
1266          */
1267
1268         /*
1269          * Prep second D2H command to read status and complete reset sequence
1270          * AHCI 10.4.1 and "Serial ATA Revision 2.6".  I can't find the ATA
1271          * Rev 2.6 and it is unclear how the second FIS should be set up
1272          * from the AHCI document.
1273          *
1274          * It is unclear which other fields in the FIS are used.  Just zero
1275          * everything.
1276          */
1277         ccb->ccb_xa.flags = ATA_F_POLL | ATA_F_AUTOSENSE | ATA_F_EXCLUSIVE;
1278
1279         bzero(fis, sizeof(ccb->ccb_cmd_table->cfis));
1280         fis[0] = ATA_FIS_TYPE_H2D;
1281         fis[15] = ATA_FIS_CONTROL_4BIT;
1282
1283         cmd_slot->prdtl = 0;
1284         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
1285
1286         ccb->ccb_xa.state = ATA_S_PENDING;
1287         if (ahci_poll(ccb, 1000, ahci_quick_timeout) != ATA_S_COMPLETE) {
1288                 kprintf("%s: Second FIS failed\n", PORTNAME(ap));
1289                 goto err;
1290         }
1291
1292         if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1293                             AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1294                 kprintf("%s: device didn't come ready after reset, TFD: 0x%b\n",
1295                         PORTNAME(ap),
1296                         ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
1297                 error = EBUSY;
1298                 goto err;
1299         }
1300
1301         /*
1302          * If the softreset is trying to clear a BSY condition after a
1303          * normal portreset we assign the port type.
1304          *
1305          * If the softreset is being run first as part of the ccb error
1306          * processing code then report if the device signature changed
1307          * unexpectedly.
1308          */
1309         ahci_os_sleep(100);
1310         if (ap->ap_type == ATA_PORT_T_NONE) {
1311                 ap->ap_type = ahci_port_signature_detect(ap, NULL);
1312         } else {
1313                 if (ahci_port_signature_detect(ap, NULL) != ap->ap_type) {
1314                         kprintf("%s: device signature unexpectedly "
1315                                 "changed\n", PORTNAME(ap));
1316                         error = EBUSY; /* XXX */
1317                 }
1318         }
1319         error = 0;
1320
1321         ahci_os_sleep(3);
1322 err:
1323         if (ccb != NULL) {
1324                 ahci_put_err_ccb(ccb);
1325
1326                 /*
1327                  * If the target is busy use CLO to clear the busy
1328                  * condition.  The BSY should be cleared on the next
1329                  * start.
1330                  */
1331                 if (ahci_pread(ap, AHCI_PREG_TFD) &
1332                     (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1333                         ahci_port_clo(ap);
1334                 }
1335         }
1336
1337         /*
1338          * If we failed to softreset make the port quiescent, otherwise
1339          * make sure the port's start/stop state matches what it was on
1340          * entry.
1341          *
1342          * Don't kill the port if the softreset is on a port multiplier
1343          * target, that would kill all the targets!
1344          */
1345         if (error) {
1346                 ahci_port_hardstop(ap);
1347                 /* ap_probe set to failed */
1348         } else {
1349                 ap->ap_probe = ATA_PROBE_NEED_IDENT;
1350                 ap->ap_pmcount = 1;
1351                 ahci_port_start(ap);
1352         }
1353         ap->ap_flags &= ~AP_F_IN_RESET;
1354         crit_exit();
1355
1356         if (bootverbose)
1357                 kprintf("%s: END SOFTRESET\n", PORTNAME(ap));
1358
1359         return (error);
1360 }
1361
1362 /*
1363  * Issue just do the core COMRESET and basic device detection on a port.
1364  *
1365  * NOTE: Only called by ahci_port_hardreset().
1366  */
1367 static int
1368 ahci_comreset(struct ahci_port *ap, int *pmdetectp)
1369 {
1370         u_int32_t cmd;
1371         u_int32_t r;
1372         int error;
1373         int loop;
1374         int retries = 0;
1375
1376         /*
1377          * Idle the port,
1378          */
1379         *pmdetectp = 0;
1380         ahci_port_stop(ap, 0);
1381         ap->ap_state = AP_S_NORMAL;
1382         ahci_os_sleep(10);
1383
1384         /*
1385          * The port may have been quiescent with its SUD bit cleared, so
1386          * set the SUD (spin up device).
1387          *
1388          * NOTE: I do not know if SUD is a hardware pin/low-level signal
1389          *       or if it is messaged.
1390          */
1391         cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1392
1393         cmd |= AHCI_PREG_CMD_SUD | AHCI_PREG_CMD_POD;
1394         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1395         ahci_os_sleep(10);
1396
1397         /*
1398          * Make sure that all power management is disabled.
1399          *
1400          * NOTE!  AHCI_PREG_SCTL_DET_DISABLE seems to be highly unreliable
1401          *        on multiple chipsets and can brick the chipset or even
1402          *        the whole PC.  Never use it.
1403          */
1404         ap->ap_type = ATA_PORT_T_NONE;
1405
1406         r = AHCI_PREG_SCTL_IPM_DISABLED |
1407             AHCI_PREG_SCTL_SPM_DISABLED;
1408         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1409
1410 retry:
1411         /*
1412          * Give the new power management state time to settle, then clear
1413          * pending status.
1414          */
1415         ahci_os_sleep(1000);
1416         ahci_flush_tfd(ap);
1417         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1418
1419         /*
1420          * Start transmitting COMRESET.  The spec says that COMRESET must
1421          * be sent for at least 1ms but in actual fact numerous devices
1422          * appear to take much longer.  Delay a whole second here.
1423          *
1424          * In addition, SATA-3 ports can take longer to train, so even
1425          * SATA-2 devices which would normally detect very quickly may
1426          * take longer when plugged into a SATA-3 port.
1427          */
1428         r |= AHCI_PREG_SCTL_DET_INIT;
1429         switch(AhciForceGen) {
1430         case 0:
1431                 r |= AHCI_PREG_SCTL_SPD_ANY;
1432                 break;
1433         case 1:
1434                 r |= AHCI_PREG_SCTL_SPD_GEN1;
1435                 break;
1436         case 2:
1437                 r |= AHCI_PREG_SCTL_SPD_GEN2;
1438                 break;
1439         case 3:
1440                 r |= AHCI_PREG_SCTL_SPD_GEN3;
1441                 break;
1442         default:
1443                 r |= AHCI_PREG_SCTL_SPD_GEN3;
1444                 break;
1445         }
1446         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1447         ahci_os_sleep(1000);
1448
1449         ap->ap_flags &= ~AP_F_HARSH_REINIT;
1450
1451         /*
1452          * Only SERR_DIAG_X needs to be cleared for TFD updates, but
1453          * since we are hard-resetting the port we might as well clear
1454          * the whole enchillada.  Also be sure to clear any spurious BSY
1455          * prior to clearing INIT.
1456          *
1457          * Wait 1 whole second after clearing INIT before checking
1458          * the device detection bits in an attempt to work around chipsets
1459          * which do not properly mask PCS/PRCS during low level init.
1460          */
1461         ahci_flush_tfd(ap);
1462         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1463 /*      ahci_port_clo(ap);*/
1464         ahci_os_sleep(10);
1465
1466         r &= ~AHCI_PREG_SCTL_SPD;
1467         r &= ~AHCI_PREG_SCTL_DET_INIT;
1468         r |= AHCI_PREG_SCTL_DET_NONE;
1469         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1470         ahci_os_sleep(1000);
1471
1472         /*
1473          * Try to determine if there is a device on the port.
1474          *
1475          * Give the device 3/10 second to at least be detected.
1476          * If we fail clear PRCS (phy detect) since we may cycled
1477          * the phy and probably caused another PRCS interrupt.
1478          */
1479         loop = 300;
1480         while (loop > 0) {
1481                 r = ahci_pread(ap, AHCI_PREG_SSTS);
1482                 if (r & AHCI_PREG_SSTS_DET)
1483                         break;
1484                 loop -= ahci_os_softsleep();
1485         }
1486         if (loop == 0) {
1487                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_PRCS);
1488                 if (bootverbose) {
1489                         kprintf("%s: Port appears to be unplugged\n",
1490                                 PORTNAME(ap));
1491                 }
1492                 error = ENODEV;
1493                 goto done;
1494         }
1495
1496         /*
1497          * There is something on the port.  Regardless of what happens
1498          * after this tell the caller to try to detect a port multiplier.
1499          *
1500          * Give the device 3 seconds to fully negotiate.
1501          */
1502         *pmdetectp = 1;
1503
1504         if (ahci_pwait_eq(ap, 3000, AHCI_PREG_SSTS,
1505                           AHCI_PREG_SSTS_DET, AHCI_PREG_SSTS_DET_DEV)) {
1506                 if (bootverbose) {
1507                         kprintf("%s: Device may be powered down\n",
1508                                 PORTNAME(ap));
1509                 }
1510                 error = ENODEV;
1511                 goto done;
1512         }
1513
1514         /*
1515          * We got something that definitely looks like a device.  Give
1516          * the device time to send us its first D2H FIS.  Waiting for
1517          * BSY to clear accomplishes this.
1518          *
1519          * NOTE: A port multiplier may or may not clear BSY here,
1520          *       depending on what is sitting in target 0 behind it.
1521          *
1522          * NOTE: Intel SSDs seem to have compatibility problems with Intel
1523          *       mobo's on cold boots and may leave BSY set.  A single
1524          *       retry works around the problem.  This is definitely a bug
1525          *       with the mobo and/or the SSD and does not appear to occur
1526          *       with other devices connected to the same port.
1527          */
1528         ahci_flush_tfd(ap);
1529         if (ahci_pwait_clr_to(ap, 8000, AHCI_PREG_TFD,
1530                             AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
1531                 kprintf("%s: Device BUSY: %b\n",
1532                         PORTNAME(ap),
1533                         ahci_pread(ap, AHCI_PREG_TFD),
1534                                 AHCI_PFMT_TFD_STS);
1535                 if (retries == 0) {
1536                         kprintf("%s: Retrying\n", PORTNAME(ap));
1537                         retries = 1;
1538                         goto retry;
1539                 }
1540                 error = EBUSY;
1541         } else {
1542                 error = 0;
1543         }
1544
1545 done:
1546         ahci_flush_tfd(ap);
1547         return error;
1548 }
1549
1550
1551 /*
1552  * AHCI port reset, Section 10.4.2
1553  *
1554  * This function does a hard reset of the port.  Note that the device
1555  * connected to the port could still end-up hung.
1556  */
1557 int
1558 ahci_port_hardreset(struct ahci_port *ap, int hard)
1559 {
1560         u_int32_t data;
1561         int     error;
1562         int     pmdetect;
1563
1564         if (bootverbose)
1565                 kprintf("%s: START HARDRESET\n", PORTNAME(ap));
1566         ap->ap_flags |= AP_F_IN_RESET;
1567
1568         error = ahci_comreset(ap, &pmdetect);
1569
1570         /*
1571          * We may be asked to perform a port multiplier check even if the
1572          * comreset failed.  This typically occurs when the PM has nothing
1573          * in slot 0, which can cause BSY to remain set.
1574          *
1575          * If the PM detection is successful it will override (error),
1576          * otherwise (error) is retained.  If an error does occur it
1577          * is possible that a normal device has blown up on us DUE to
1578          * the PM detection code, so re-run the comreset and assume
1579          * a normal device.
1580          */
1581         if (pmdetect) {
1582                 if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SPM) {
1583                         error = ahci_pm_port_probe(ap, error);
1584                         if (error) {
1585                                 error = ahci_comreset(ap, &pmdetect);
1586                         }
1587                 }
1588         }
1589
1590         /*
1591          * Finish up.
1592          */
1593         ahci_os_sleep(500);
1594
1595         switch(error) {
1596         case 0:
1597                 /*
1598                  * All good, make sure the port is running and set the
1599                  * probe state.  Ignore the signature junk (it's unreliable)
1600                  * until we get to the softreset code.
1601                  */
1602                 if (ahci_port_start(ap)) {
1603                         kprintf("%s: failed to start command DMA on port, "
1604                                 "disabling\n", PORTNAME(ap));
1605                         error = EBUSY;
1606                         break;
1607                 }
1608                 if (ap->ap_type == ATA_PORT_T_PM)
1609                         ap->ap_probe = ATA_PROBE_GOOD;
1610                 else
1611                         ap->ap_probe = ATA_PROBE_NEED_SOFT_RESET;
1612                 break;
1613         case ENODEV:
1614                 /*
1615                  * Normal device probe failure
1616                  */
1617                 data = ahci_pread(ap, AHCI_PREG_SSTS);
1618
1619                 switch(data & AHCI_PREG_SSTS_DET) {
1620                 case AHCI_PREG_SSTS_DET_DEV_NE:
1621                         kprintf("%s: Device not communicating\n",
1622                                 PORTNAME(ap));
1623                         break;
1624                 case AHCI_PREG_SSTS_DET_PHYOFFLINE:
1625                         kprintf("%s: PHY offline\n",
1626                                 PORTNAME(ap));
1627                         break;
1628                 default:
1629                         kprintf("%s: No device detected\n",
1630                                 PORTNAME(ap));
1631                         break;
1632                 }
1633                 ahci_port_hardstop(ap);
1634                 break;
1635         default:
1636                 /*
1637                  * Abnormal probe (EBUSY)
1638                  */
1639                 kprintf("%s: Device on port is bricked\n",
1640                         PORTNAME(ap));
1641                 ahci_port_hardstop(ap);
1642 #if 0
1643                 rc = ahci_port_reset(ap, atx, 0);
1644                 if (rc) {
1645                         kprintf("%s: Unable unbrick device\n",
1646                                 PORTNAME(ap));
1647                 } else {
1648                         kprintf("%s: Successfully unbricked\n",
1649                                 PORTNAME(ap));
1650                 }
1651 #endif
1652                 break;
1653         }
1654
1655         /*
1656          * Clean up
1657          */
1658         ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1659         ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS);
1660
1661         ap->ap_flags &= ~AP_F_IN_RESET;
1662
1663         if (bootverbose)
1664                 kprintf("%s: END HARDRESET %d\n", PORTNAME(ap), error);
1665         return (error);
1666 }
1667
1668 /*
1669  * Hard-stop on hot-swap device removal.  See 10.10.1
1670  *
1671  * Place the port in a mode that will allow it to detect hot-swap insertions.
1672  * This is a bit imprecise because just setting-up SCTL to DET_INIT doesn't
1673  * seem to do the job.
1674  *
1675  * FIS reception is left enabled but command processing is disabled.
1676  * Cycling FIS reception (FRE) can brick ports.
1677  */
1678 void
1679 ahci_port_hardstop(struct ahci_port *ap)
1680 {
1681         struct ahci_ccb *ccb;
1682         struct ata_port *at;
1683         u_int32_t r;
1684         u_int32_t cmd;
1685         int slot;
1686         int i;
1687         int serial;
1688
1689         /*
1690          * Stop the port.  We can't modify things like SUD if the port
1691          * is running.
1692          */
1693         ap->ap_state = AP_S_FATAL_ERROR;
1694         ap->ap_probe = ATA_PROBE_FAILED;
1695         ap->ap_type = ATA_PORT_T_NONE;
1696         ahci_port_stop(ap, 0);
1697         cmd = ahci_pread(ap, AHCI_PREG_CMD);
1698         cmd &= ~(AHCI_PREG_CMD_CLO | AHCI_PREG_CMD_PMA | AHCI_PREG_CMD_ICC);
1699         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1700
1701         /*
1702          * Clean up AT sub-ports on SATA port.
1703          */
1704         for (i = 0; ap->ap_ata && i < AHCI_MAX_PMPORTS; ++i) {
1705                 at = ap->ap_ata[i];
1706                 at->at_type = ATA_PORT_T_NONE;
1707                 at->at_probe = ATA_PROBE_FAILED;
1708         }
1709
1710         /*
1711          * Make sure FRE is active.  There isn't anything we can do if it
1712          * fails so just ignore errors.
1713          */
1714         if ((cmd & AHCI_PREG_CMD_FRE) == 0) {
1715                 cmd |= AHCI_PREG_CMD_FRE;
1716                 ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1717                 if ((ap->ap_sc->sc_flags & AHCI_F_IGN_FR) == 0)
1718                         ahci_pwait_set(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR);
1719         }
1720
1721         /*
1722          * 10.10.1 place us in the Listen state.
1723          *
1724          * 10.10.3 DET must be set to 0 and found to be 0 before
1725          * setting SUD to 0.
1726          *
1727          * Deactivating SUD only applies if the controller supports SUD, it
1728          * is a bit unclear what happens w/regards to detecting hotplug
1729          * if it doesn't.
1730          */
1731         r = AHCI_PREG_SCTL_IPM_DISABLED |
1732             AHCI_PREG_SCTL_SPM_DISABLED;
1733         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1734         ahci_os_sleep(10);
1735         cmd &= ~AHCI_PREG_CMD_SUD;
1736         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1737         ahci_os_sleep(10);
1738
1739         /*
1740          * 10.10.1
1741          *
1742          * Transition su to the spin-up state.  HBA shall send COMRESET and
1743          * begin initialization sequence (whatever that means).  Presumably
1744          * this is edge-triggered.  Following the spin-up state the HBA
1745          * will automatically transition to the Normal state.
1746          *
1747          * This only applies if the controller supports SUD.
1748          * NEVER use AHCI_PREG_DET_DISABLE.
1749          */
1750         cmd |= AHCI_PREG_CMD_POD |
1751                AHCI_PREG_CMD_SUD |
1752                AHCI_PREG_CMD_ICC_ACTIVE;
1753         ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1754         ahci_os_sleep(10);
1755
1756         /*
1757          * Flush SERR_DIAG_X so the TFD can update.
1758          */
1759         ahci_flush_tfd(ap);
1760
1761         /*
1762          * Clean out pending ccbs
1763          */
1764 restart:
1765         while (ap->ap_active) {
1766                 slot = ffs(ap->ap_active) - 1;
1767                 ap->ap_active &= ~(1 << slot);
1768                 --ap->ap_active_cnt;
1769                 ccb = &ap->ap_ccbs[slot];
1770                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_RUNNING) {
1771                         serial = ccb->ccb_xa.serial;
1772                         callout_stop_sync(&ccb->ccb_timeout);
1773                         if (serial != ccb->ccb_xa.serial) {
1774                                 kprintf("%s: Warning: timeout race ccb %p\n",
1775                                         PORTNAME(ap), ccb);
1776                                 goto restart;
1777                         }
1778                         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
1779                 }
1780                 ap->ap_expired &= ~(1 << slot);
1781                 ccb->ccb_xa.flags &= ~(ATA_F_TIMEOUT_DESIRED |
1782                                        ATA_F_TIMEOUT_EXPIRED);
1783                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1784                 ccb->ccb_done(ccb);
1785                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1786         }
1787         while (ap->ap_sactive) {
1788                 slot = ffs(ap->ap_sactive) - 1;
1789                 ap->ap_sactive &= ~(1 << slot);
1790                 ccb = &ap->ap_ccbs[slot];
1791                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_RUNNING) {
1792                         serial = ccb->ccb_xa.serial;
1793                         callout_stop_sync(&ccb->ccb_timeout);
1794                         if (serial != ccb->ccb_xa.serial) {
1795                                 kprintf("%s: Warning: timeout race ccb %p\n",
1796                                         PORTNAME(ap), ccb);
1797                                 goto restart;
1798                         }
1799                         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
1800                 }
1801                 ap->ap_expired &= ~(1 << slot);
1802                 ccb->ccb_xa.flags &= ~(ATA_F_TIMEOUT_DESIRED |
1803                                        ATA_F_TIMEOUT_EXPIRED);
1804                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1805                 ccb->ccb_done(ccb);
1806                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1807         }
1808         KKASSERT(ap->ap_active_cnt == 0);
1809
1810         while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
1811                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1812                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1813                 ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_DESIRED;
1814                 ccb->ccb_done(ccb);
1815                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1816         }
1817
1818         /*
1819          * Hot-plug device detection should work at this point.  e.g. on
1820          * AMD chipsets Spin-Up/Normal state is sufficient for hot-plug
1821          * detection and entering RESET (continuous COMRESET by setting INIT)
1822          * will actually prevent hot-plug detection from working properly.
1823          *
1824          * There may be cases where this will fail to work, I have some
1825          * additional code to place the HBA in RESET (send continuous
1826          * COMRESET) and hopefully get DIAG.X or other events when something
1827          * is plugged in.  Unfortunately this isn't universal and can
1828          * also prevent events from generating interrupts.
1829          */
1830
1831 #if 0
1832         /*
1833          * Transition us to the Reset state.  Theoretically we send a
1834          * continuous stream of COMRESETs in this state.
1835          */
1836         r |= AHCI_PREG_SCTL_DET_INIT;
1837         if (AhciForceGen1 & (1 << ap->ap_num)) {
1838                 kprintf("%s: Force 1.5Gbits\n", PORTNAME(ap));
1839                 r |= AHCI_PREG_SCTL_SPD_GEN1;
1840         } else {
1841                 r |= AHCI_PREG_SCTL_SPD_ANY;
1842         }
1843         ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1844         ahci_os_sleep(10);
1845
1846         /*
1847          * Flush SERR_DIAG_X so the TFD can update.
1848          */
1849         ahci_flush_tfd(ap);
1850 #endif
1851         /* NOP */
1852 }
1853
1854 /*
1855  * We can't loop on the X bit, a continuous COMINIT received will make
1856  * it loop forever.  Just assume one event has built up and clear X
1857  * so the task file descriptor can update.
1858  */
1859 void
1860 ahci_flush_tfd(struct ahci_port *ap)
1861 {
1862         u_int32_t r;
1863
1864         r = ahci_pread(ap, AHCI_PREG_SERR);
1865         if (r & AHCI_PREG_SERR_DIAG_X)
1866                 ahci_pwrite(ap, AHCI_PREG_SERR, AHCI_PREG_SERR_DIAG_X);
1867 }
1868
1869 /*
1870  * Figure out what type of device is connected to the port, ATAPI or
1871  * DISK.
1872  */
1873 int
1874 ahci_port_signature_detect(struct ahci_port *ap, struct ata_port *at)
1875 {
1876         u_int32_t sig;
1877
1878         sig = ahci_pread(ap, AHCI_PREG_SIG);
1879         if (bootverbose)
1880                 kprintf("%s: sig %08x\n", ATANAME(ap, at), sig);
1881         if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000)) {
1882                 return(ATA_PORT_T_ATAPI);
1883         } else if ((sig & 0xffff0000) ==
1884                  (SATA_SIGNATURE_PORT_MULTIPLIER & 0xffff0000)) {
1885                 return(ATA_PORT_T_PM);
1886         } else {
1887                 return(ATA_PORT_T_DISK);
1888         }
1889 }
1890
1891 /*
1892  * Load the DMA descriptor table for a CCB's buffer.
1893  */
1894 int
1895 ahci_load_prdt(struct ahci_ccb *ccb)
1896 {
1897         struct ahci_port                *ap = ccb->ccb_port;
1898         struct ahci_softc               *sc = ap->ap_sc;
1899         struct ata_xfer                 *xa = &ccb->ccb_xa;
1900         struct ahci_prdt                *prdt = ccb->ccb_cmd_table->prdt;
1901         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1902         struct ahci_cmd_hdr             *cmd_slot = ccb->ccb_cmd_hdr;
1903         int                             error;
1904
1905         if (xa->datalen == 0) {
1906                 ccb->ccb_cmd_hdr->prdtl = 0;
1907                 return (0);
1908         }
1909
1910         error = bus_dmamap_load(sc->sc_tag_data, dmap,
1911                                 xa->data, xa->datalen,
1912                                 ahci_load_prdt_callback,
1913                                 &prdt,
1914                                 ((xa->flags & ATA_F_NOWAIT) ?
1915                                     BUS_DMA_NOWAIT : BUS_DMA_WAITOK));
1916         if (error != 0) {
1917                 kprintf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
1918                 return (1);
1919         }
1920 #if 0
1921         if (xa->flags & ATA_F_PIO)
1922                 prdt->flags |= htole32(AHCI_PRDT_FLAG_INTR);
1923 #endif
1924
1925         cmd_slot->prdtl = htole16(prdt - ccb->ccb_cmd_table->prdt + 1);
1926
1927         if (xa->flags & ATA_F_READ)
1928                 bus_dmamap_sync(sc->sc_tag_data, dmap, BUS_DMASYNC_PREREAD);
1929         if (xa->flags & ATA_F_WRITE)
1930                 bus_dmamap_sync(sc->sc_tag_data, dmap, BUS_DMASYNC_PREWRITE);
1931
1932         return (0);
1933 }
1934
1935 /*
1936  * Callback from BUSDMA system to load the segment list.  The passed segment
1937  * list is a temporary structure.
1938  */
1939 static
1940 void
1941 ahci_load_prdt_callback(void *info, bus_dma_segment_t *segs, int nsegs,
1942                         int error)
1943 {
1944         struct ahci_prdt *prd = *(void **)info;
1945         u_int64_t addr;
1946
1947         KKASSERT(nsegs <= AHCI_MAX_PRDT);
1948
1949         while (nsegs) {
1950                 addr = segs->ds_addr;
1951                 prd->dba_hi = htole32((u_int32_t)(addr >> 32));
1952                 prd->dba_lo = htole32((u_int32_t)addr);
1953                 prd->flags = htole32(segs->ds_len - 1);
1954                 --nsegs;
1955                 if (nsegs)
1956                         ++prd;
1957                 ++segs;
1958         }
1959         *(void **)info = prd;   /* return last valid segment */
1960 }
1961
1962 void
1963 ahci_unload_prdt(struct ahci_ccb *ccb)
1964 {
1965         struct ahci_port                *ap = ccb->ccb_port;
1966         struct ahci_softc               *sc = ap->ap_sc;
1967         struct ata_xfer                 *xa = &ccb->ccb_xa;
1968         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1969
1970         if (xa->datalen != 0) {
1971                 if (xa->flags & ATA_F_READ) {
1972                         bus_dmamap_sync(sc->sc_tag_data, dmap,
1973                                         BUS_DMASYNC_POSTREAD);
1974                 }
1975                 if (xa->flags & ATA_F_WRITE) {
1976                         bus_dmamap_sync(sc->sc_tag_data, dmap,
1977                                         BUS_DMASYNC_POSTWRITE);
1978                 }
1979                 bus_dmamap_unload(sc->sc_tag_data, dmap);
1980
1981                 /*
1982                  * prdbc is only updated by hardware for non-NCQ commands.
1983                  */
1984                 if (ccb->ccb_xa.flags & ATA_F_NCQ) {
1985                         xa->resid = 0;
1986                 } else {
1987                         if (ccb->ccb_cmd_hdr->prdbc == 0 &&
1988                             ccb->ccb_xa.state == ATA_S_COMPLETE) {
1989                                 kprintf("%s: WARNING!  Unload prdbc resid "
1990                                         "was zero! tag=%d\n",
1991                                         ATANAME(ap, xa->at), ccb->ccb_slot);
1992                         }
1993                         xa->resid = xa->datalen -
1994                             le32toh(ccb->ccb_cmd_hdr->prdbc);
1995                 }
1996         }
1997 }
1998
1999 /*
2000  * Start a command and poll for completion.
2001  *
2002  * timeout is in ms and only counts once the command gets on-chip.
2003  *
2004  * Returns ATA_S_* state, compare against ATA_S_COMPLETE to determine
2005  * that no error occured.
2006  *
2007  * NOTE: If the caller specifies a NULL timeout function the caller is
2008  *       responsible for clearing hardware state on failure, but we will
2009  *       deal with removing the ccb from any pending queue.
2010  *
2011  * NOTE: NCQ should never be used with this function.
2012  *
2013  * NOTE: If the port is in a failed state and stopped we do not try
2014  *       to activate the ccb.
2015  */
2016 int
2017 ahci_poll(struct ahci_ccb *ccb, int timeout,
2018           void (*timeout_fn)(struct ahci_ccb *))
2019 {
2020         struct ahci_port *ap = ccb->ccb_port;
2021
2022         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR) {
2023                 ccb->ccb_xa.state = ATA_S_ERROR;
2024                 return(ccb->ccb_xa.state);
2025         }
2026         crit_enter();
2027 #if 0
2028         kprintf("%s: Start command %02x tag=%d\n",
2029                 ATANAME(ccb->ccb_port, ccb->ccb_xa.at),
2030                 ccb->ccb_xa.fis->command, ccb->ccb_slot);
2031 #endif
2032         ahci_start(ccb);
2033
2034         do {
2035                 ahci_port_intr(ap, 1);
2036                 switch(ccb->ccb_xa.state) {
2037                 case ATA_S_ONCHIP:
2038                         timeout -= ahci_os_softsleep();
2039                         break;
2040                 case ATA_S_PENDING:
2041                         ahci_os_softsleep();
2042                         ahci_check_active_timeouts(ap);
2043                         break;
2044                 default:
2045                         crit_exit();
2046                         return (ccb->ccb_xa.state);
2047                 }
2048         } while (timeout > 0);
2049
2050         if ((ccb->ccb_xa.flags & ATA_F_SILENT) == 0) {
2051                 kprintf("%s: Poll timeout slot %d CMD: %b TFD: 0x%b SERR: %b\n",
2052                         ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot,
2053                         ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD,
2054                         ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS,
2055                         ahci_pread(ap, AHCI_PREG_SERR), AHCI_PFMT_SERR);
2056         }
2057
2058         timeout_fn(ccb);
2059
2060         crit_exit();
2061
2062         return(ccb->ccb_xa.state);
2063 }
2064
2065 /*
2066  * When polling we have to check if the currently active CCB(s)
2067  * have timed out as the callout will be deadlocked while we
2068  * hold the port lock.
2069  */
2070 void
2071 ahci_check_active_timeouts(struct ahci_port *ap)
2072 {
2073         struct ahci_ccb *ccb;
2074         u_int32_t mask;
2075         int tag;
2076
2077         mask = ap->ap_active | ap->ap_sactive;
2078         while (mask) {
2079                 tag = ffs(mask) - 1;
2080                 mask &= ~(1 << tag);
2081                 ccb = &ap->ap_ccbs[tag];
2082                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_EXPIRED) {
2083                         ahci_ata_cmd_timeout(ccb);
2084                 }
2085         }
2086 }
2087
2088 static
2089 __inline
2090 void
2091 ahci_start_timeout(struct ahci_ccb *ccb)
2092 {
2093         if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_DESIRED) {
2094                 ccb->ccb_xa.flags |= ATA_F_TIMEOUT_RUNNING;
2095                 callout_reset(&ccb->ccb_timeout,
2096                               (ccb->ccb_xa.timeout * hz + 999) / 1000,
2097                               ahci_ata_cmd_timeout_unserialized, ccb);
2098         }
2099 }
2100
2101 void
2102 ahci_start(struct ahci_ccb *ccb)
2103 {
2104         struct ahci_port                *ap = ccb->ccb_port;
2105         struct ahci_softc               *sc = ap->ap_sc;
2106
2107         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
2108
2109         /* Zero transferred byte count before transfer */
2110         ccb->ccb_cmd_hdr->prdbc = 0;
2111
2112         /* Sync command list entry and corresponding command table entry */
2113         bus_dmamap_sync(sc->sc_tag_cmdh,
2114                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
2115                         BUS_DMASYNC_PREWRITE);
2116         bus_dmamap_sync(sc->sc_tag_cmdt,
2117                         AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
2118                         BUS_DMASYNC_PREWRITE);
2119
2120         /* Prepare RFIS area for write by controller */
2121         bus_dmamap_sync(sc->sc_tag_rfis,
2122                         AHCI_DMA_MAP(ap->ap_dmamem_rfis),
2123                         BUS_DMASYNC_PREREAD);
2124
2125         /*
2126          * There's no point trying to optimize this, it only shaves a few
2127          * nanoseconds so just queue the command and call our generic issue.
2128          */
2129         ahci_issue_pending_commands(ap, ccb);
2130 }
2131
2132 /*
2133  * While holding the port lock acquire exclusive access to the port.
2134  *
2135  * This is used when running the state machine to initialize and identify
2136  * targets over a port multiplier.  Setting exclusive access prevents
2137  * ahci_port_intr() from activating any requests sitting on the pending
2138  * queue.
2139  */
2140 void
2141 ahci_beg_exclusive_access(struct ahci_port *ap, struct ata_port *at)
2142 {
2143         KKASSERT((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) == 0);
2144         ap->ap_flags |= AP_F_EXCLUSIVE_ACCESS;
2145         while (ap->ap_active || ap->ap_sactive) {
2146                 ahci_port_intr(ap, 1);
2147                 ahci_os_softsleep();
2148         }
2149 }
2150
2151 void
2152 ahci_end_exclusive_access(struct ahci_port *ap, struct ata_port *at)
2153 {
2154         KKASSERT((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) != 0);
2155         ap->ap_flags &= ~AP_F_EXCLUSIVE_ACCESS;
2156         ahci_issue_pending_commands(ap, NULL);
2157 }
2158
2159 /*
2160  * If ccb is not NULL enqueue and/or issue it.
2161  *
2162  * If ccb is NULL issue whatever we can from the queue.  However, nothing
2163  * new is issued if the exclusive access flag is set or expired ccb's are
2164  * present.
2165  *
2166  * If existing commands are still active (ap_active/ap_sactive) we can only
2167  * issue matching new commands.
2168  */
2169 void
2170 ahci_issue_pending_commands(struct ahci_port *ap, struct ahci_ccb *ccb)
2171 {
2172         u_int32_t               mask;
2173         int                     limit;
2174
2175         /*
2176          * Enqueue the ccb.
2177          *
2178          * If just running the queue and in exclusive access mode we
2179          * just return.  Also in this case if there are any expired ccb's
2180          * we want to clear the queue so the port can be safely stopped.
2181          */
2182         if (ccb) {
2183                 TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
2184         } else if ((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) || ap->ap_expired) {
2185                 return;
2186         }
2187
2188         /*
2189          * Pull the next ccb off the queue and run it if possible.
2190          *
2191          * The error CCB supercedes all normal queue operations and
2192          * implies exclusive access while the error CCB is active.
2193          */
2194         if (ccb != ap->ap_err_ccb) {
2195                 if ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) == NULL)
2196                         return;
2197                 if (ap->ap_flags & AP_F_ERR_CCB_RESERVED) {
2198                         kprintf("DELAY CCB slot %d\n", ccb->ccb_slot);
2199                         return;
2200                 }
2201         }
2202
2203         /*
2204          * Handle exclusivity requirements.
2205          *
2206          * ATA_F_EXCLUSIVE is used when we want to be the only command
2207          * running.
2208          *
2209          * ATA_F_AUTOSENSE is used when we want the D2H rfis loaded
2210          * back into the ccb on a normal (non-errored) command completion.
2211          * For example, for PM requests to target 15.  Because the AHCI
2212          * spec does not stop the command processor and has only one rfis
2213          * area (for non-FBSS anyway), AUTOSENSE currently implies EXCLUSIVE.
2214          * Otherwise multiple completions can destroy the rfis data before
2215          * we have a chance to copy it.
2216          */
2217         if (ap->ap_active & ~ap->ap_expired) {
2218                 /*
2219                  * There may be multiple ccb's already running,
2220                  * if any are running and ap_run_flags sets
2221                  * one of these flags then we know only one is
2222                  * running.
2223                  *
2224                  * XXX Current AUTOSENSE code forces exclusivity
2225                  *     to simplify the code.
2226                  */
2227                 if (ap->ap_run_flags &
2228                     (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE)) {
2229                         return;
2230                 }
2231
2232                 if (ccb->ccb_xa.flags &
2233                     (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE)) {
2234                         return;
2235                 }
2236         }
2237
2238         if (ccb->ccb_xa.flags & ATA_F_NCQ) {
2239                 /*
2240                  * The next command is a NCQ command and can be issued as
2241                  * long as currently active commands are not standard.
2242                  */
2243                 if (ap->ap_active) {
2244                         KKASSERT(ap->ap_active_cnt > 0);
2245                         return;
2246                 }
2247                 KKASSERT(ap->ap_active_cnt == 0);
2248
2249                 mask = 0;
2250                 do {
2251                         TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2252                         KKASSERT((mask & (1 << ccb->ccb_slot)) == 0);
2253                         mask |= 1 << ccb->ccb_slot;
2254                         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
2255                         KKASSERT(ccb == &ap->ap_ccbs[ccb->ccb_slot]);
2256                         ccb->ccb_xa.state = ATA_S_ONCHIP;
2257                         ahci_start_timeout(ccb);
2258                         ap->ap_run_flags = ccb->ccb_xa.flags;
2259                         ccb = TAILQ_FIRST(&ap->ap_ccb_pending);
2260                 } while (ccb && (ccb->ccb_xa.flags & ATA_F_NCQ) &&
2261                          (ap->ap_run_flags &
2262                              (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE)) == 0);
2263
2264                 KKASSERT(((ap->ap_active | ap->ap_sactive) & mask) == 0);
2265
2266                 ap->ap_sactive |= mask;
2267                 ahci_pwrite(ap, AHCI_PREG_SACT, mask);
2268                 ahci_pwrite(ap, AHCI_PREG_CI, mask);
2269         } else {
2270                 /*
2271                  * The next command is a standard command and can be issued
2272                  * as long as currently active commands are not NCQ.
2273                  *
2274                  * We limit ourself to 1 command if we have a port multiplier,
2275                  * (at least without FBSS support), otherwise timeouts on
2276                  * one port can race completions on other ports (see
2277                  * ahci_ata_cmd_timeout() for more information).
2278                  *
2279                  * If not on a port multiplier generally allow up to 4
2280                  * standard commands to be enqueued.  Remember that the
2281                  * command processor will still process them sequentially.
2282                  */
2283                 if (ap->ap_sactive)
2284                         return;
2285                 if (ap->ap_type == ATA_PORT_T_PM)
2286                         limit = 1;
2287                 else if (ap->ap_sc->sc_ncmds > 4)
2288                         limit = 4;
2289                 else
2290                         limit = 2;
2291
2292                 while (ap->ap_active_cnt < limit && ccb &&
2293                        (ccb->ccb_xa.flags & ATA_F_NCQ) == 0) {
2294                         TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2295                         KKASSERT(((ap->ap_active | ap->ap_sactive) &
2296                                   (1 << ccb->ccb_slot)) == 0);
2297                         ap->ap_active |= 1 << ccb->ccb_slot;
2298                         ap->ap_active_cnt++;
2299                         ap->ap_run_flags = ccb->ccb_xa.flags;
2300                         ccb->ccb_xa.state = ATA_S_ONCHIP;
2301                         ahci_start_timeout(ccb);
2302                         ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
2303                         if ((ap->ap_run_flags &
2304                             (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE)) == 0) {
2305                                 break;
2306                         }
2307                         ccb = TAILQ_FIRST(&ap->ap_ccb_pending);
2308                         if (ccb && (ccb->ccb_xa.flags &
2309                                     (ATA_F_EXCLUSIVE | ATA_F_AUTOSENSE))) {
2310                                 break;
2311                         }
2312                 }
2313         }
2314 }
2315
2316 void
2317 ahci_intr(void *arg)
2318 {
2319         struct ahci_softc       *sc = arg;
2320         struct ahci_port        *ap;
2321         u_int32_t               is;
2322         u_int32_t               ack;
2323         int                     port;
2324
2325         /*
2326          * Check if the master enable is up, and whether any interrupts are
2327          * pending.
2328          */
2329         if ((sc->sc_flags & AHCI_F_INT_GOOD) == 0)
2330                 return;
2331         is = ahci_read(sc, AHCI_REG_IS);
2332         if (is == 0 || is == 0xffffffff) {
2333                 return;
2334         }
2335         is &= sc->sc_portmask;
2336
2337 #ifdef AHCI_COALESCE
2338         /* Check coalescing interrupt first */
2339         if (is & sc->sc_ccc_mask) {
2340                 DPRINTF(AHCI_D_INTR, "%s: command coalescing interrupt\n",
2341                     DEVNAME(sc));
2342                 is &= ~sc->sc_ccc_mask;
2343                 is |= sc->sc_ccc_ports_cur;
2344         }
2345 #endif
2346
2347         /*
2348          * Process interrupts for each port in a non-blocking fashion.
2349          *
2350          * The global IS bit is supposed to be forced on if any unmasked
2351          * port interrupt is pending, even if we clear it.
2352          *
2353          * However it would appear that it is simply latched on some parts,
2354          * which means we have to clear it BEFORE processing the status bits
2355          * to avoid races.
2356          */
2357         ahci_write(sc, AHCI_REG_IS, is);
2358         for (ack = 0; is; is &= ~(1 << port)) {
2359                 port = ffs(is) - 1;
2360                 ack |= 1 << port;
2361
2362                 ap = sc->sc_ports[port];
2363                 if (ap == NULL)
2364                         continue;
2365
2366                 if (ahci_os_lock_port_nb(ap) == 0) {
2367                         ahci_port_intr(ap, 0);
2368                         ahci_os_unlock_port(ap);
2369                 } else {
2370                         ahci_pwrite(ap, AHCI_PREG_IE, 0);
2371                         ahci_os_signal_port_thread(ap, AP_SIGF_PORTINT);
2372                 }
2373         }
2374 }
2375
2376 /*
2377  * Core called from helper thread.
2378  */
2379 void
2380 ahci_port_thread_core(struct ahci_port *ap, int mask)
2381 {
2382         /*
2383          * Process any expired timedouts.
2384          */
2385         ahci_os_lock_port(ap);
2386         if (mask & AP_SIGF_TIMEOUT) {
2387                 ahci_check_active_timeouts(ap);
2388         }
2389
2390         /*
2391          * Process port interrupts which require a higher level of
2392          * intervention.
2393          */
2394         if (mask & AP_SIGF_PORTINT) {
2395                 ahci_port_intr(ap, 1);
2396                 ahci_port_interrupt_enable(ap);
2397         } else if (ap->ap_probe != ATA_PROBE_FAILED) {
2398                 ahci_port_intr(ap, 1);
2399                 ahci_port_interrupt_enable(ap);
2400         }
2401         ahci_os_unlock_port(ap);
2402 }
2403
2404 /*
2405  * Core per-port interrupt handler.
2406  *
2407  * If blockable is 0 we cannot call ahci_os_sleep() at all and we can only
2408  * deal with normal command completions which do not require blocking.
2409  */
2410 void
2411 ahci_port_intr(struct ahci_port *ap, int blockable)
2412 {
2413         struct ahci_softc       *sc = ap->ap_sc;
2414         u_int32_t               is, ci_saved, ci_masked;
2415         int                     slot;
2416         int                     stopped = 0;
2417         struct ahci_ccb         *ccb = NULL;
2418         struct ata_port         *ccb_at = NULL;
2419         volatile u_int32_t      *active;
2420         const u_int32_t         blockable_mask = AHCI_PREG_IS_TFES |
2421                                                  AHCI_PREG_IS_IFS |
2422                                                  AHCI_PREG_IS_PCS |
2423                                                  AHCI_PREG_IS_PRCS |
2424                                                  AHCI_PREG_IS_HBFS |
2425                                                  AHCI_PREG_IS_OFS |
2426                                                  AHCI_PREG_IS_UFS;
2427
2428         enum { NEED_NOTHING, NEED_REINIT, NEED_RESTART,
2429                NEED_HOTPLUG_INSERT, NEED_HOTPLUG_REMOVE } need = NEED_NOTHING;
2430
2431         /*
2432          * All basic command completions are always processed.
2433          */
2434         is = ahci_pread(ap, AHCI_PREG_IS);
2435         if (is & AHCI_PREG_IS_DPS)
2436                 ahci_pwrite(ap, AHCI_PREG_IS, is & AHCI_PREG_IS_DPS);
2437
2438         /*
2439          * If we can't block then we can't handle these here.  Disable
2440          * the interrupts in question so we don't live-lock, the helper
2441          * thread will re-enable them.
2442          *
2443          * If the port is in a completely failed state we do not want
2444          * to drop through to failed-command-processing if blockable is 0,
2445          * just let the thread deal with it all.
2446          *
2447          * Otherwise we fall through and still handle DHRS and any commands
2448          * which completed normally.  Even if we are errored we haven't
2449          * stopped the port yet so CI/SACT are still good.
2450          */
2451         if (blockable == 0) {
2452                 if (ap->ap_state == AP_S_FATAL_ERROR) {
2453                         ahci_pwrite(ap, AHCI_PREG_IE, 0);
2454                         ahci_os_signal_port_thread(ap, AP_SIGF_PORTINT);
2455                         return;
2456                 }
2457                 if (is & blockable_mask) {
2458                         ahci_pwrite(ap, AHCI_PREG_IE, 0);
2459                         ahci_os_signal_port_thread(ap, AP_SIGF_PORTINT);
2460                         return;
2461                 }
2462         }
2463
2464         /*
2465          * Either NCQ or non-NCQ commands will be active, never both.
2466          */
2467         if (ap->ap_sactive) {
2468                 KKASSERT(ap->ap_active == 0);
2469                 KKASSERT(ap->ap_active_cnt == 0);
2470                 ci_saved = ahci_pread(ap, AHCI_PREG_SACT);
2471                 active = &ap->ap_sactive;
2472         } else {
2473                 ci_saved = ahci_pread(ap, AHCI_PREG_CI);
2474                 active = &ap->ap_active;
2475         }
2476         KKASSERT(!(ap->ap_sactive && ap->ap_active));
2477         KKASSERT((ci_saved & (ap->ap_sactive | ap->ap_active)) == ci_saved);
2478 #if 0
2479         kprintf("CHECK act=%08x/%08x sact=%08x/%08x\n",
2480                 ap->ap_active, ahci_pread(ap, AHCI_PREG_CI),
2481                 ap->ap_sactive, ahci_pread(ap, AHCI_PREG_SACT));
2482 #endif
2483
2484         /*
2485          * Ignore AHCI_PREG_IS_PRCS when link power management is on
2486          */
2487         if (ap->link_pwr_mgmt != AHCI_LINK_PWR_MGMT_NONE) {
2488                 is &= ~AHCI_PREG_IS_PRCS;
2489                 ahci_pwrite(ap, AHCI_PREG_SERR,
2490                             AHCI_PREG_SERR_DIAG_N | AHCI_PREG_SERR_DIAG_W);
2491         }
2492
2493         /*
2494          * Command failed (blockable).
2495          *
2496          * See AHCI 1.1 spec 6.2.2.1 and 6.2.2.2.
2497          *
2498          * This stops command processing.
2499          */
2500         if (is & AHCI_PREG_IS_TFES) {
2501                 u_int32_t tfd, serr;
2502                 int     err_slot;
2503
2504 process_error:
2505                 tfd = ahci_pread(ap, AHCI_PREG_TFD);
2506                 serr = ahci_pread(ap, AHCI_PREG_SERR);
2507
2508                 /*
2509                  * Load the error slot and restart command processing.
2510                  * CLO if we need to.  The error slot may not be valid.
2511                  * MUST BE DONE BEFORE CLEARING ST!
2512                  *
2513                  * Cycle ST.
2514                  *
2515                  * It is unclear but we may have to clear SERR to reenable
2516                  * error processing.
2517                  */
2518                 err_slot = AHCI_PREG_CMD_CCS(ahci_pread(ap, AHCI_PREG_CMD));
2519                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_TFES |
2520                                               AHCI_PREG_IS_PSS |
2521                                               AHCI_PREG_IS_DHRS |
2522                                               AHCI_PREG_IS_SDBS);
2523                 is &= ~(AHCI_PREG_IS_TFES | AHCI_PREG_IS_PSS |
2524                         AHCI_PREG_IS_DHRS | AHCI_PREG_IS_SDBS);
2525                 ahci_pwrite(ap, AHCI_PREG_SERR, serr);
2526                 ahci_port_stop(ap, 0);
2527                 ahci_os_hardsleep(10);
2528                 if (tfd & (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
2529                         kprintf("%s: Issuing CLO\n", PORTNAME(ap));
2530                         ahci_port_clo(ap);
2531                 }
2532
2533                 /*
2534                  * We are now stopped and need a restart.  If we have to
2535                  * process a NCQ error we will temporarily start and then
2536                  * stop the port again, so this condition holds.
2537                  */
2538                 stopped = 1;
2539                 need = NEED_RESTART;
2540
2541                 /*
2542                  * ATAPI errors are fairly common from probing, just
2543                  * report disk errors or if bootverbose is on.
2544                  */
2545                 if (bootverbose || ap->ap_type != ATA_PORT_T_ATAPI) {
2546                         kprintf("%s: TFES slot %d ci_saved = %08x\n",
2547                                 PORTNAME(ap), err_slot, ci_saved);
2548                 }
2549
2550                 /*
2551                  * If we got an error on an error CCB just complete it
2552                  * with an error.  ci_saved has the mask to restart
2553                  * (the err_ccb will be removed from it by finish_error).
2554                  */
2555                 if (ap->ap_flags & AP_F_ERR_CCB_RESERVED) {
2556                         err_slot = ap->ap_err_ccb->ccb_slot;
2557                         goto finish_error;
2558                 }
2559
2560                 /*
2561                  * If NCQ commands were active get the error slot from
2562                  * the log page.  NCQ is not supported for PM's so this
2563                  * is a direct-attached target.
2564                  *
2565                  * Otherwise if no commands were active we have a problem.
2566                  *
2567                  * Otherwise if the error slot is bad we have a problem.
2568                  *
2569                  * Otherwise process the error for the slot.
2570                  */
2571                 if (ap->ap_sactive) {
2572                         ahci_port_start(ap);
2573                         err_slot = ahci_port_read_ncq_error(ap, 0);
2574                         ahci_port_stop(ap, 0);
2575                 } else if (ap->ap_active == 0) {
2576                         kprintf("%s: TFES with no commands pending\n",
2577                                 PORTNAME(ap));
2578                         err_slot = -1;
2579                 } else if (err_slot < 0 || err_slot >= ap->ap_sc->sc_ncmds) {
2580                         kprintf("%s: bad error slot %d\n",
2581                                 PORTNAME(ap), err_slot);
2582                         err_slot = -1;
2583                 } else {
2584                         ccb = &ap->ap_ccbs[err_slot];
2585
2586                         /*
2587                          * Validate the errored ccb.  Note that ccb_at can
2588                          * be NULL for direct-attached ccb's.
2589                          *
2590                          * Copy received taskfile data from the RFIS.
2591                          */
2592                         if (ccb->ccb_xa.state == ATA_S_ONCHIP) {
2593                                 ccb_at = ccb->ccb_xa.at;
2594                                 memcpy(&ccb->ccb_xa.rfis, ap->ap_rfis->rfis,
2595                                        sizeof(struct ata_fis_d2h));
2596                                 if (bootverbose) {
2597                                         kprintf("%s: Copying rfis slot %d\n",
2598                                                 ATANAME(ap, ccb_at), err_slot);
2599                                 }
2600                         } else {
2601                                 kprintf("%s: Cannot copy rfis, CCB slot "
2602                                         "%d is not on-chip (state=%d)\n",
2603                                         ATANAME(ap, ccb->ccb_xa.at),
2604                                         err_slot, ccb->ccb_xa.state);
2605                                 err_slot = -1;
2606                         }
2607                 }
2608
2609                 /*
2610                  * If we could not determine the errored slot then
2611                  * reset the port.
2612                  */
2613                 if (err_slot < 0) {
2614                         kprintf("%s: TFES: Unable to determine errored slot\n",
2615                                 PORTNAME(ap));
2616                         if (ap->ap_flags & AP_F_IN_RESET)
2617                                 goto fatal;
2618                         goto failall;
2619                 }
2620
2621                 /*
2622                  * Finish error on slot.  We will restart ci_saved
2623                  * commands except the errored slot which we generate
2624                  * a failure for.
2625                  */
2626 finish_error:
2627                 ccb = &ap->ap_ccbs[err_slot];
2628                 ci_saved &= ~(1 << err_slot);
2629                 KKASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
2630                 ccb->ccb_xa.state = ATA_S_ERROR;
2631         } else if (is & AHCI_PREG_IS_DHRS) {
2632                 /*
2633                  * Command posted D2H register FIS to the rfis (non-blocking).
2634                  *
2635                  * A normal completion with an error may set DHRS instead
2636                  * of TFES.  The CCS bits are only valid if ERR was set.
2637                  * If ERR is set command processing was probably stopped.
2638                  *
2639                  * If ERR was not set we can only copy-back data for
2640                  * exclusive-mode commands because otherwise we won't know
2641                  * which tag the rfis belonged to.
2642                  *
2643                  * err_slot must be read from the CCS before any other port
2644                  * action, such as stopping the port.
2645                  *
2646                  * WARNING!     This is not well documented in the AHCI spec.
2647                  *              It can be found in the state machine tables
2648                  *              but not in the explanations.
2649                  */
2650                 u_int32_t tfd;
2651                 u_int32_t cmd;
2652                 int err_slot;
2653
2654                 tfd = ahci_pread(ap, AHCI_PREG_TFD);
2655                 cmd = ahci_pread(ap, AHCI_PREG_CMD);
2656
2657                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_DHRS);
2658                 if ((tfd & AHCI_PREG_TFD_STS_ERR) &&
2659                     (cmd & AHCI_PREG_CMD_CR) == 0) {
2660                         err_slot = AHCI_PREG_CMD_CCS(
2661                                                 ahci_pread(ap, AHCI_PREG_CMD));
2662                         ccb = &ap->ap_ccbs[err_slot];
2663                         kprintf("%s: DHRS tfd=%b err_slot=%d cmd=%02x\n",
2664                                 PORTNAME(ap),
2665                                 tfd, AHCI_PFMT_TFD_STS,
2666                                 err_slot, ccb->ccb_xa.fis->command);
2667                         goto process_error;
2668                 }
2669                 /*
2670                  * NO ELSE... copy back is in the normal command completion
2671                  * code and only if no error occured and ATA_F_AUTOSENSE
2672                  * was set.
2673                  */
2674         }
2675
2676         /*
2677          * Device notification to us (non-blocking)
2678          *
2679          * NOTE!  On some parts notification bits can cause an IPMS
2680          *        interrupt instead of a SDBS interrupt.
2681          *
2682          * NOTE!  On some parts (e.g. VBOX, probably intel ICHx),
2683          *        SDBS notifies us of the completion of a NCQ command
2684          *        and DBS does not.
2685          */
2686         if (is & (AHCI_PREG_IS_SDBS | AHCI_PREG_IS_IPMS)) {
2687                 u_int32_t data;
2688
2689                 ahci_pwrite(ap, AHCI_PREG_IS,
2690                                 AHCI_PREG_IS_SDBS | AHCI_PREG_IS_IPMS);
2691                 if (sc->sc_cap & AHCI_REG_CAP_SSNTF) {
2692                         data = ahci_pread(ap, AHCI_PREG_SNTF);
2693                         if (data) {
2694                                 ahci_pwrite(ap, AHCI_PREG_IS,
2695                                                 AHCI_PREG_IS_SDBS);
2696                                 kprintf("%s: NOTIFY %08x\n",
2697                                         PORTNAME(ap), data);
2698                                 ahci_pwrite(ap, AHCI_PREG_SERR,
2699                                                 AHCI_PREG_SERR_DIAG_N);
2700                                 ahci_pwrite(ap, AHCI_PREG_SNTF, data);
2701                                 ahci_cam_changed(ap, NULL, -1);
2702                         }
2703                 }
2704                 is &= ~(AHCI_PREG_IS_SDBS | AHCI_PREG_IS_IPMS);
2705         }
2706
2707         /*
2708          * Spurious IFS errors (blockable) - when AP_F_IGNORE_IFS is set.
2709          *
2710          * Spurious IFS errors can occur while we are doing a reset
2711          * sequence through a PM, probably due to an unexpected FIS
2712          * being received during the PM target reset sequence.  Chipsets
2713          * are supposed to mask these events but some do not.
2714          *
2715          * Try to recover from the condition.
2716          */
2717         if ((is & AHCI_PREG_IS_IFS) && (ap->ap_flags & AP_F_IGNORE_IFS)) {
2718                 u_int32_t serr = ahci_pread(ap, AHCI_PREG_SERR);
2719                 if ((ap->ap_flags & AP_F_IFS_IGNORED) == 0) {
2720                         kprintf("%s: IFS during PM probe (ignored) "
2721                                 "IS=%b, SERR=%b\n",
2722                                 PORTNAME(ap),
2723                                 is, AHCI_PFMT_IS,
2724                                 serr, AHCI_PFMT_SERR);
2725                         ap->ap_flags |= AP_F_IFS_IGNORED;
2726                 }
2727
2728                 /*
2729                  * Try to clear the error condition.  The IFS error killed
2730                  * the port so stop it so we can restart it.
2731                  */
2732                 ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IFS);
2733                 ahci_pwrite(ap, AHCI_PREG_SERR, -1);
2734                 is &= ~AHCI_PREG_IS_IFS;
2735                 need = NEED_RESTART;
2736                 goto failall;
2737         }
2738
2739         /*
2740          * Port change (hot-plug) (blockable).
2741          *
2742          * A PRCS interrupt can occur:
2743          *      (1) On hot-unplug / normal-unplug (phy lost)
2744          *      (2) Sometimes on hot-plug too.
2745          *
2746          * A PCS interrupt can occur in a number of situations:
2747          *      (1) On hot-plug once communication is established
2748          *      (2) On hot-unplug sometimes.
2749          *      (3) For chipsets with badly written firmware it can occur
2750          *          during INIT/RESET sequences due to the device reset.
2751          *      (4) For chipsets with badly written firmware it can occur
2752          *          when it thinks an unsolicited COMRESET is received
2753          *          during a INIT/RESET sequence, even though we actually
2754          *          did request it.
2755          *
2756          * XXX We can then check the CPS (Cold Presence State) bit, if
2757          * supported, to determine if a device is plugged in or not and do
2758          * the right thing.
2759          *
2760          * PCS interrupts are cleared by clearing DIAG_X.  If this occurs
2761          * command processing is automatically stopped (CR goes inactive)
2762          * and the port must be stopped and restarted.
2763          *
2764          * WARNING: AMD parts (e.g. 880G chipset, probably others) can
2765          *          generate PCS on initialization even when device is
2766          *          already connected up.  It is unclear why this happens.
2767          *          Depending on the state of the device detect this can
2768          *          cause us to go into harsh reinit or hot-plug insertion
2769          *          mode.
2770          *
2771          * WARNING: PCS errors can be repetitive (e.g. unsolicited COMRESET
2772          *          continues to flow in from the device), we must clear the
2773          *          interrupt in all cases and enforce a delay to prevent
2774          *          a livelock and give the port time to settle down.
2775          *          Only print something if we aren't in INIT/HARD-RESET.
2776          */
2777         if (is & (AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS)) {
2778                 ahci_pwrite(ap, AHCI_PREG_IS,
2779                             is & (AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS));
2780                 /*
2781                  * Try to clear the error.  Because of the repetitiveness
2782                  * of this interrupt avoid any harsh action if the port is
2783                  * already in the init or hard-reset probe state.
2784                  */
2785                 ahci_pwrite(ap, AHCI_PREG_SERR, -1);
2786                 /* (AHCI_PREG_SERR_DIAG_N | AHCI_PREG_SERR_DIAG_X) */
2787
2788                 /*
2789                  * Ignore PCS/PRCS errors during probes (but still clear the
2790                  * interrupt to avoid a livelock).  The AMD 880/890/SB850
2791                  * chipsets do not mask PCS/PRCS internally during reset
2792                  * sequences.
2793                  */
2794                 if (ap->ap_flags & AP_F_IN_RESET)
2795                         goto skip_pcs;
2796
2797                 if (ap->ap_probe == ATA_PROBE_NEED_INIT ||
2798                     ap->ap_probe == ATA_PROBE_NEED_HARD_RESET) {
2799                         is &= ~(AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS);
2800                         need = NEED_NOTHING;
2801                         ahci_os_sleep(1000);
2802                         goto failall;
2803                 }
2804                 kprintf("%s: Transient Errors: %b (%d)\n",
2805                         PORTNAME(ap), is, AHCI_PFMT_IS, ap->ap_probe);
2806                 is &= ~(AHCI_PREG_IS_PCS | AHCI_PREG_IS_PRCS);
2807                 ahci_os_sleep(200);
2808
2809                 /*
2810                  * Stop the port and figure out what to do next.
2811                  */
2812                 ahci_port_stop(ap, 0);
2813                 stopped = 1;
2814
2815                 switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
2816                 case AHCI_PREG_SSTS_DET_DEV:
2817                         /*
2818                          * Device detect
2819                          */
2820                         if (ap->ap_probe == ATA_PROBE_FAILED) {
2821                                 need = NEED_HOTPLUG_INSERT;
2822                                 goto fatal;
2823                         }
2824                         need = NEED_RESTART;
2825                         break;
2826                 case AHCI_PREG_SSTS_DET_DEV_NE:
2827                         /*
2828                          * Device not communicating.  AMD parts seem to
2829                          * like to throw this error on initialization
2830                          * for no reason that I can fathom.
2831                          */
2832                         kprintf("%s: Device present but not communicating, "
2833                                 "attempting port restart\n",
2834                                 PORTNAME(ap));
2835                         need = NEED_REINIT;
2836                         goto fatal;
2837                 default:
2838                         if (ap->ap_probe != ATA_PROBE_FAILED) {
2839                                 need = NEED_HOTPLUG_REMOVE;
2840                                 goto fatal;
2841                         }
2842                         need = NEED_RESTART;
2843                         break;
2844                 }
2845 skip_pcs:
2846                 ;
2847         }
2848
2849         /*
2850          * Check for remaining errors - they are fatal. (blockable)
2851          */
2852         if (is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS | AHCI_PREG_IS_IFS |
2853                   AHCI_PREG_IS_OFS | AHCI_PREG_IS_UFS)) {
2854                 u_int32_t serr;
2855
2856                 ahci_pwrite(ap, AHCI_PREG_IS,
2857                             is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
2858                                   AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS |
2859                                   AHCI_PREG_IS_UFS));
2860                 serr = ahci_pread(ap, AHCI_PREG_SERR);
2861                 kprintf("%s: Unrecoverable errors (IS: %b, SERR: %b), "
2862                         "disabling port.\n",
2863                         PORTNAME(ap),
2864                         is, AHCI_PFMT_IS,
2865                         serr, AHCI_PFMT_SERR
2866                 );
2867                 is &= ~(AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
2868                         AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS |
2869                         AHCI_PREG_IS_UFS);
2870
2871                 /*
2872                  * Fail all commands but then what?  For now try to
2873                  * reinitialize the port.
2874                  */
2875                 need = NEED_REINIT;
2876                 goto fatal;
2877         }
2878
2879         /*
2880          * Fail all outstanding commands if we know the port won't recover.
2881          *
2882          * We may have a ccb_at if the failed command is known and was
2883          * being sent to a device over a port multiplier (PM).  In this
2884          * case if the port itself has not completely failed we fail just
2885          * the commands related to that target.
2886          *
2887          * ci_saved contains the mask of active commands as of when the
2888          * error occured, prior to any port stops.
2889          */
2890         if (ap->ap_state == AP_S_FATAL_ERROR) {
2891 fatal:
2892                 ap->ap_state = AP_S_FATAL_ERROR;
2893 failall:
2894                 ahci_port_stop(ap, 0);
2895                 stopped = 1;
2896
2897                 /*
2898                  * Error all the active slots not already errored.
2899                  */
2900                 ci_masked = ci_saved & *active & ~ap->ap_expired;
2901                 if (ci_masked) {
2902                         kprintf("%s: Failing all commands: %08x\n",
2903                                 PORTNAME(ap), ci_masked);
2904                 }
2905
2906                 while (ci_masked) {
2907                         slot = ffs(ci_masked) - 1;
2908                         ccb = &ap->ap_ccbs[slot];
2909                         ccb->ccb_xa.state = ATA_S_TIMEOUT;
2910                         ap->ap_expired |= 1 << slot;
2911                         ci_saved &= ~(1 << slot);
2912                         ci_masked &= ~(1 << slot);
2913                 }
2914
2915                 /*
2916                  * Clear bits in ci_saved (cause completions to be run)
2917                  * for all slots which are not active.
2918                  */
2919                 ci_saved &= ~*active;
2920
2921                 /*
2922                  * Don't restart the port if our problems were deemed fatal.
2923                  *
2924                  * Also acknowlege all fatal interrupt sources to prevent
2925                  * a livelock.
2926                  */
2927                 if (ap->ap_state == AP_S_FATAL_ERROR) {
2928                         if (need == NEED_RESTART)
2929                                 need = NEED_NOTHING;
2930                         ahci_pwrite(ap, AHCI_PREG_IS,
2931                                     AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
2932                                     AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS |
2933                                     AHCI_PREG_IS_UFS);
2934                 }
2935         }
2936
2937         /*
2938          * If we are stopped the AHCI chipset is supposed to have cleared
2939          * CI and SACT.  Did it?  If it didn't we try very hard to clear
2940          * the fields otherwise we may end up completing CCBs which are
2941          * actually still active.
2942          *
2943          * IFS errors on (at least) AMD chipsets create this confusion.
2944          */
2945         if (stopped) {
2946                 u_int32_t mask;
2947                 if ((mask = ahci_pactive(ap)) != 0) {
2948                         kprintf("%s: chipset failed to clear "
2949                                 "active cmds %08x\n",
2950                                 PORTNAME(ap), mask);
2951                         ahci_port_start(ap);
2952                         ahci_port_stop(ap, 0);
2953                         if ((mask = ahci_pactive(ap)) != 0) {
2954                                 kprintf("%s: unable to prod the chip into "
2955                                         "clearing active cmds %08x\n",
2956                                         PORTNAME(ap), mask);
2957                                 /* what do we do now? */
2958                         }
2959                 }
2960         }
2961
2962         /*
2963          * CCB completion (non blocking).
2964          *
2965          * CCB completion is detected by noticing its slot's bit in CI has
2966          * changed to zero some time after we activated it.
2967          * If we are polling, we may only be interested in particular slot(s).
2968          *
2969          * Any active bits not saved are completed within the restrictions
2970          * imposed by the caller.
2971          */
2972         ci_masked = ~ci_saved & *active;
2973         while (ci_masked) {
2974                 slot = ffs(ci_masked) - 1;
2975                 ccb = &ap->ap_ccbs[slot];
2976                 ci_masked &= ~(1 << slot);
2977
2978                 DPRINTF(AHCI_D_INTR, "%s: slot %d is complete%s\n",
2979                     PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
2980                     " (error)" : "");
2981
2982                 bus_dmamap_sync(sc->sc_tag_cmdh,
2983                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
2984                                 BUS_DMASYNC_POSTWRITE);
2985
2986                 bus_dmamap_sync(sc->sc_tag_cmdt,
2987                                 AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
2988                                 BUS_DMASYNC_POSTWRITE);
2989
2990                 bus_dmamap_sync(sc->sc_tag_rfis,
2991                                 AHCI_DMA_MAP(ap->ap_dmamem_rfis),
2992                                 BUS_DMASYNC_POSTREAD);
2993
2994                 *active &= ~(1 << ccb->ccb_slot);
2995                 if (active == &ap->ap_active) {
2996                         KKASSERT(ap->ap_active_cnt > 0);
2997                         --ap->ap_active_cnt;
2998                 }
2999
3000                 /*
3001                  * Complete the ccb.  If the ccb was marked expired it
3002                  * was probably already removed from the command processor,
3003                  * so don't take the clear ci_saved bit as meaning the
3004                  * command actually succeeded, it didn't.
3005                  */
3006                 if (ap->ap_expired & (1 << ccb->ccb_slot)) {
3007                         ap->ap_expired &= ~(1 << ccb->ccb_slot);
3008                         ccb->ccb_xa.state = ATA_S_TIMEOUT;
3009                         ccb->ccb_done(ccb);
3010                         ccb->ccb_xa.complete(&ccb->ccb_xa);
3011                 } else {
3012                         if (ccb->ccb_xa.state == ATA_S_ONCHIP) {
3013                                 ccb->ccb_xa.state = ATA_S_COMPLETE;
3014                                 if (ccb->ccb_xa.flags & ATA_F_AUTOSENSE) {
3015                                         memcpy(&ccb->ccb_xa.rfis,
3016                                             ap->ap_rfis->rfis,
3017                                             sizeof(struct ata_fis_d2h));
3018                                         if (ccb->ccb_xa.state == ATA_S_TIMEOUT)
3019                                                 ccb->ccb_xa.state = ATA_S_ERROR;
3020                                 }
3021                         }
3022                         ccb->ccb_done(ccb);
3023                 }
3024         }
3025
3026         /*
3027          * Cleanup.  Will not be set if non-blocking.
3028          */
3029         switch(need) {
3030         case NEED_NOTHING:
3031                 /*
3032                  * If operating normally and not stopped the interrupt was
3033                  * probably just a normal completion and we may be able to
3034                  * issue more commands.
3035                  */
3036                 if (stopped == 0 && ap->ap_state != AP_S_FATAL_ERROR)
3037                         ahci_issue_pending_commands(ap, NULL);
3038                 break;
3039         case NEED_RESTART:
3040                 /*
3041                  * A recoverable error occured and we can restart outstanding
3042                  * commands on the port.
3043                  */
3044                 ci_saved &= ~ap->ap_expired;
3045                 if (ci_saved) {
3046                         kprintf("%s: Restart %08x\n", PORTNAME(ap), ci_saved);
3047                         ahci_issue_saved_commands(ap, ci_saved);
3048                 }
3049
3050                 /*
3051                  * Potentially issue new commands if not in a failed
3052                  * state.
3053                  */
3054                 if (ap->ap_state != AP_S_FATAL_ERROR) {
3055                         ahci_port_start(ap);
3056                         ahci_issue_pending_commands(ap, NULL);
3057                 }
3058                 break;
3059         case NEED_REINIT:
3060                 /*
3061                  * Something horrible happened to the port and we
3062                  * need to reinitialize it.
3063                  */
3064                 kprintf("%s: REINIT - Attempting to reinitialize the port "
3065                         "after it had a horrible accident\n",
3066                         PORTNAME(ap));
3067                 ap->ap_flags |= AP_F_IN_RESET;
3068                 ap->ap_flags |= AP_F_HARSH_REINIT;
3069                 ap->ap_probe = ATA_PROBE_NEED_INIT;
3070                 ahci_cam_changed(ap, NULL, -1);
3071                 break;
3072         case NEED_HOTPLUG_INSERT:
3073                 /*
3074                  * A hot-plug insertion event has occured and all
3075                  * outstanding commands have already been revoked.
3076                  *
3077                  * Don't recurse if this occurs while we are
3078                  * resetting the port.
3079                  */
3080                 if ((ap->ap_flags & AP_F_IN_RESET) == 0) {
3081                         kprintf("%s: HOTPLUG - Device inserted\n",
3082                                 PORTNAME(ap));
3083                         ap->ap_probe = ATA_PROBE_NEED_INIT;
3084                         ahci_cam_changed(ap, NULL, -1);
3085                 }
3086                 break;
3087         case NEED_HOTPLUG_REMOVE:
3088                 /*
3089                  * A hot-plug removal event has occured and all
3090                  * outstanding commands have already been revoked.
3091                  *
3092                  * Don't recurse if this occurs while we are
3093                  * resetting the port.
3094                  */
3095                 if ((ap->ap_flags & AP_F_IN_RESET) == 0) {
3096                         kprintf("%s: HOTPLUG - Device removed\n",
3097                                 PORTNAME(ap));
3098                         ahci_port_hardstop(ap);
3099                         /* ap_probe set to failed */
3100                         ahci_cam_changed(ap, NULL, -1);
3101                 }
3102                 break;
3103         default:
3104                 break;
3105         }
3106 }
3107
3108 struct ahci_ccb *
3109 ahci_get_ccb(struct ahci_port *ap)
3110 {
3111         struct ahci_ccb                 *ccb;
3112
3113         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
3114         ccb = TAILQ_FIRST(&ap->ap_ccb_free);
3115         if (ccb != NULL) {
3116                 KKASSERT((ap->ap_sactive & (1 << ccb->ccb_slot)) == 0);
3117                 KKASSERT(ccb->ccb_xa.state == ATA_S_PUT);
3118                 TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
3119                 ccb->ccb_xa.state = ATA_S_SETUP;
3120                 ccb->ccb_xa.flags = 0;
3121                 ccb->ccb_xa.at = NULL;
3122         }
3123         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
3124
3125         return (ccb);
3126 }
3127
3128 void
3129 ahci_put_ccb(struct ahci_ccb *ccb)
3130 {
3131         struct ahci_port                *ap = ccb->ccb_port;
3132
3133         KKASSERT(ccb->ccb_xa.state != ATA_S_PUT);
3134         KKASSERT((ap->ap_sactive & (1 << ccb->ccb_slot)) == 0);
3135         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
3136         ccb->ccb_xa.state = ATA_S_PUT;
3137         ++ccb->ccb_xa.serial;
3138         TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
3139         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
3140 }
3141
3142 struct ahci_ccb *
3143 ahci_get_err_ccb(struct ahci_port *ap)
3144 {
3145         struct ahci_ccb *err_ccb;
3146         u_int32_t sact;
3147         u_int32_t ci;
3148
3149         /* No commands may be active on the chip. */
3150
3151         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SNCQ) {
3152                 sact = ahci_pread(ap, AHCI_PREG_SACT);
3153                 if (sact != 0) {
3154                         kprintf("%s: ahci_get_err_ccb but SACT %08x != 0?\n",
3155                                 PORTNAME(ap), sact);
3156                 }
3157         }
3158         ci = ahci_pread(ap, AHCI_PREG_CI);
3159         if (ci) {
3160                 kprintf("%s: ahci_get_err_ccb: ci not 0 (%08x)\n",
3161                         ap->ap_name, ci);
3162         }
3163         KKASSERT(ci == 0);
3164         KKASSERT((ap->ap_flags & AP_F_ERR_CCB_RESERVED) == 0);
3165         ap->ap_flags |= AP_F_ERR_CCB_RESERVED;
3166
3167         /* Save outstanding command state. */
3168         ap->ap_err_saved_active = ap->ap_active;
3169         ap->ap_err_saved_active_cnt = ap->ap_active_cnt;
3170         ap->ap_err_saved_sactive = ap->ap_sactive;
3171
3172         /*
3173          * Pretend we have no commands outstanding, so that completions won't
3174          * run prematurely.
3175          */
3176         ap->ap_active = ap->ap_active_cnt = ap->ap_sactive = 0;
3177
3178         /*
3179          * Grab a CCB to use for error recovery.  This should never fail, as
3180          * we ask atascsi to reserve one for us at init time.
3181          */
3182         err_ccb = ap->ap_err_ccb;
3183         KKASSERT(err_ccb != NULL);
3184         err_ccb->ccb_xa.flags = 0;
3185         err_ccb->ccb_done = ahci_empty_done;
3186
3187         return err_ccb;
3188 }
3189
3190 void
3191 ahci_put_err_ccb(struct ahci_ccb *ccb)
3192 {
3193         struct ahci_port *ap = ccb->ccb_port;
3194         u_int32_t sact;
3195         u_int32_t ci;
3196
3197         KKASSERT((ap->ap_flags & AP_F_ERR_CCB_RESERVED) != 0);
3198
3199         /*
3200          * No commands may be active on the chip
3201          */
3202         if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SNCQ) {
3203                 sact = ahci_pread(ap, AHCI_PREG_SACT);
3204                 if (sact) {
3205                         panic("ahci_port_err_ccb(%d) but SACT %08x != 0",
3206                               ccb->ccb_slot, sact);
3207                 }
3208         }
3209         ci = ahci_pread(ap, AHCI_PREG_CI);
3210         if (ci) {
3211                 panic("ahci_put_err_ccb(%d) but CI %08x != 0 "
3212                       "(act=%08x sact=%08x)\n",
3213                       ccb->ccb_slot, ci,
3214                       ap->ap_active, ap->ap_sactive);
3215         }
3216
3217         KKASSERT(ccb == ap->ap_err_ccb);
3218
3219         /* Restore outstanding command state */
3220         ap->ap_sactive = ap->ap_err_saved_sactive;
3221         ap->ap_active_cnt = ap->ap_err_saved_active_cnt;
3222         ap->ap_active = ap->ap_err_saved_active;
3223
3224         ap->ap_flags &= ~AP_F_ERR_CCB_RESERVED;
3225 }
3226
3227 /*
3228  * Read log page to get NCQ error.
3229  *
3230  * NOTE: NCQ not currently supported on port multipliers. XXX
3231  */
3232 int
3233 ahci_port_read_ncq_error(struct ahci_port *ap, int target)
3234 {
3235         struct ata_log_page_10h *log;
3236         struct ahci_ccb         *ccb;
3237         struct ahci_ccb         *ccb2;
3238         struct ahci_cmd_hdr     *cmd_slot;
3239         struct ata_fis_h2d      *fis;
3240         int                     err_slot;
3241
3242         if (bootverbose) {
3243                 kprintf("%s: READ LOG PAGE target %d\n", PORTNAME(ap),
3244                         target);
3245         }
3246
3247         /*
3248          * Prep error CCB for READ LOG EXT, page 10h, 1 sector.
3249          *
3250          * Getting err_ccb clears active/sactive/active_cnt, putting
3251          * it back restores the fields.
3252          */
3253         ccb = ahci_get_err_ccb(ap);
3254         ccb->ccb_xa.flags = ATA_F_READ | ATA_F_POLL;
3255         ccb->ccb_xa.data = ap->ap_err_scratch;
3256         ccb->ccb_xa.datalen = 512;
3257         ccb->ccb_xa.complete = ahci_dummy_done;
3258         ccb->ccb_xa.at = ap->ap_ata[target];
3259
3260         fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
3261         bzero(fis, sizeof(*fis));
3262         fis->type = ATA_FIS_TYPE_H2D;
3263         fis->flags = ATA_H2D_FLAGS_CMD | target;
3264         fis->command = ATA_C_READ_LOG_EXT;
3265         fis->lba_low = 0x10;            /* queued error log page (10h) */
3266         fis->sector_count = 1;          /* number of sectors (1) */
3267         fis->sector_count_exp = 0;
3268         fis->lba_mid = 0;               /* starting offset */
3269         fis->lba_mid_exp = 0;
3270         fis->device = 0;
3271
3272         cmd_slot = ccb->ccb_cmd_hdr;
3273         cmd_slot->flags = htole16(5);   /* FIS length: 5 DWORDS */
3274
3275         if (ahci_load_prdt(ccb) != 0) {
3276                 err_slot = -1;
3277                 goto err;
3278         }
3279
3280         ccb->ccb_xa.state = ATA_S_PENDING;
3281         if (ahci_poll(ccb, 1000, ahci_quick_timeout) != ATA_S_COMPLETE) {
3282                 err_slot = -1;
3283                 ahci_unload_prdt(ccb);
3284                 goto err;
3285         }
3286         ahci_unload_prdt(ccb);
3287
3288         /*
3289          * Success, extract failed register set and tags from the scratch
3290          * space.
3291          */
3292         log = (struct ata_log_page_10h *)ap->ap_err_scratch;
3293         if (log->err_regs.type & ATA_LOG_10H_TYPE_NOTQUEUED) {
3294                 /* Not queued bit was set - wasn't an NCQ error? */
3295                 kprintf("%s: read NCQ error page, but not an NCQ error?\n",
3296                         PORTNAME(ap));
3297                 err_slot = -1;
3298         } else {
3299                 /* Copy back the log record as a D2H register FIS. */
3300                 err_slot = log->err_regs.type & ATA_LOG_10H_TYPE_TAG_MASK;
3301
3302                 ccb2 = &ap->ap_ccbs[err_slot];
3303                 if (ccb2->ccb_xa.state == ATA_S_ONCHIP) {
3304                         kprintf("%s: read NCQ error page slot=%d\n",
3305                                 ATANAME(ap, ccb2->ccb_xa.at),
3306                                 err_slot);
3307                         memcpy(&ccb2->ccb_xa.rfis, &log->err_regs,
3308                                 sizeof(struct ata_fis_d2h));
3309                         ccb2->ccb_xa.rfis.type = ATA_FIS_TYPE_D2H;
3310                         ccb2->ccb_xa.rfis.flags = 0;
3311                 } else {
3312                         kprintf("%s: read NCQ error page slot=%d, "
3313                                 "slot does not match any cmds\n",
3314                                 ATANAME(ccb2->ccb_port, ccb2->ccb_xa.at),
3315                                 err_slot);
3316                         err_slot = -1;
3317                 }
3318         }
3319 err:
3320         ahci_put_err_ccb(ccb);
3321         kprintf("%s: DONE log page target %d err_slot=%d\n",
3322                 PORTNAME(ap), target, err_slot);
3323         return (err_slot);
3324 }
3325
3326 /*
3327  * Allocate memory for various structures DMAd by hardware.  The maximum
3328  * number of segments for these tags is 1 so the DMA memory will have a
3329  * single physical base address.
3330  */
3331 struct ahci_dmamem *
3332 ahci_dmamem_alloc(struct ahci_softc *sc, bus_dma_tag_t tag)
3333 {
3334         struct ahci_dmamem *adm;
3335         int     error;
3336
3337         adm = kmalloc(sizeof(*adm), M_DEVBUF, M_INTWAIT | M_ZERO);
3338
3339         error = bus_dmamem_alloc(tag, (void **)&adm->adm_kva,
3340                                  BUS_DMA_ZERO, &adm->adm_map);
3341         if (error == 0) {
3342                 adm->adm_tag = tag;
3343                 error = bus_dmamap_load(tag, adm->adm_map,
3344                                         adm->adm_kva,
3345                                         bus_dma_tag_getmaxsize(tag),
3346                                         ahci_dmamem_saveseg, &adm->adm_busaddr,
3347                                         0);
3348         }
3349         if (error) {
3350                 if (adm->adm_map) {
3351                         bus_dmamap_destroy(tag, adm->adm_map);
3352                         adm->adm_map = NULL;
3353                         adm->adm_tag = NULL;
3354                         adm->adm_kva = NULL;
3355                 }
3356                 kfree(adm, M_DEVBUF);
3357                 adm = NULL;
3358         }
3359         return (adm);
3360 }
3361
3362 static
3363 void
3364 ahci_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error)
3365 {
3366         KKASSERT(error == 0);
3367         KKASSERT(nsegs == 1);
3368         *(bus_addr_t *)info = segs->ds_addr;
3369 }
3370
3371
3372 void
3373 ahci_dmamem_free(struct ahci_softc *sc, struct ahci_dmamem *adm)
3374 {
3375         if (adm->adm_map) {
3376                 bus_dmamap_unload(adm->adm_tag, adm->adm_map);
3377                 bus_dmamap_destroy(adm->adm_tag, adm->adm_map);
3378                 adm->adm_map = NULL;
3379                 adm->adm_tag = NULL;
3380                 adm->adm_kva = NULL;
3381         }
3382         kfree(adm, M_DEVBUF);
3383 }
3384
3385 u_int32_t
3386 ahci_read(struct ahci_softc *sc, bus_size_t r)
3387 {
3388         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
3389                           BUS_SPACE_BARRIER_READ);
3390         return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
3391 }
3392
3393 void
3394 ahci_write(struct ahci_softc *sc, bus_size_t r, u_int32_t v)
3395 {
3396         bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
3397         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
3398                           BUS_SPACE_BARRIER_WRITE);
3399 }
3400
3401 u_int32_t
3402 ahci_pread(struct ahci_port *ap, bus_size_t r)
3403 {
3404         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
3405                           BUS_SPACE_BARRIER_READ);
3406         return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
3407 }
3408
3409 void
3410 ahci_pwrite(struct ahci_port *ap, bus_size_t r, u_int32_t v)
3411 {
3412         bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
3413         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
3414                           BUS_SPACE_BARRIER_WRITE);
3415 }
3416
3417 /*
3418  * Wait up to (timeout) milliseconds for the masked port register to
3419  * match the target.
3420  *
3421  * Timeout is in milliseconds.
3422  */
3423 int
3424 ahci_pwait_eq(struct ahci_port *ap, int timeout,
3425               bus_size_t r, u_int32_t mask, u_int32_t target)
3426 {
3427         int     t;
3428
3429         /*
3430          * Loop hard up to 100uS
3431          */
3432         for (t = 0; t < 100; ++t) {
3433                 if ((ahci_pread(ap, r) & mask) == target)
3434                         return (0);
3435                 ahci_os_hardsleep(1);   /* us */
3436         }
3437
3438         do {
3439                 timeout -= ahci_os_softsleep();
3440                 if ((ahci_pread(ap, r) & mask) == target)
3441                         return (0);
3442         } while (timeout > 0);
3443         return (1);
3444 }
3445
3446 int
3447 ahci_wait_ne(struct ahci_softc *sc, bus_size_t r, u_int32_t mask,
3448              u_int32_t target)
3449 {
3450         int     t;
3451
3452         /*
3453          * Loop hard up to 100uS
3454          */
3455         for (t = 0; t < 100; ++t) {
3456                 if ((ahci_read(sc, r) & mask) != target)
3457                         return (0);
3458                 ahci_os_hardsleep(1);   /* us */
3459         }
3460
3461         /*
3462          * And one millisecond the slow way
3463          */
3464         t = 1000;
3465         do {
3466                 t -= ahci_os_softsleep();
3467                 if ((ahci_read(sc, r) & mask) != target)
3468                         return (0);
3469         } while (t > 0);
3470
3471         return (1);
3472 }
3473
3474
3475 /*
3476  * Acquire an ata transfer.
3477  *
3478  * Pass a NULL at for direct-attached transfers, and a non-NULL at for
3479  * targets that go through the port multiplier.
3480  */
3481 struct ata_xfer *
3482 ahci_ata_get_xfer(struct ahci_port *ap, struct ata_port *at)
3483 {
3484         struct ahci_ccb         *ccb;
3485
3486         ccb = ahci_get_ccb(ap);
3487         if (ccb == NULL) {
3488                 DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer: NULL ccb\n",
3489                     PORTNAME(ap));
3490                 return (NULL);
3491         }
3492
3493         DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer got slot %d\n",
3494             PORTNAME(ap), ccb->ccb_slot);
3495
3496         bzero(ccb->ccb_xa.fis, sizeof(*ccb->ccb_xa.fis));
3497         ccb->ccb_xa.at = at;
3498         ccb->ccb_xa.fis->type = ATA_FIS_TYPE_H2D;
3499
3500         return (&ccb->ccb_xa);
3501 }
3502
3503 void
3504 ahci_ata_put_xfer(struct ata_xfer *xa)
3505 {
3506         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
3507
3508         DPRINTF(AHCI_D_XFER, "ahci_ata_put_xfer slot %d\n", ccb->ccb_slot);
3509
3510         ahci_put_ccb(ccb);
3511 }
3512
3513 int
3514 ahci_ata_cmd(struct ata_xfer *xa)
3515 {
3516         struct ahci_ccb                 *ccb = (struct ahci_ccb *)xa;
3517         struct ahci_cmd_hdr             *cmd_slot;
3518
3519         KKASSERT(xa->state == ATA_S_SETUP);
3520
3521         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
3522                 goto failcmd;
3523         ccb->ccb_done = ahci_ata_cmd_done;
3524
3525         cmd_slot = ccb->ccb_cmd_hdr;
3526         cmd_slot->flags = htole16(5); /* FIS length (in DWORDs) */
3527         if (ccb->ccb_xa.at) {
3528                 cmd_slot->flags |= htole16(ccb->ccb_xa.at->at_target <<
3529                                            AHCI_CMD_LIST_FLAG_PMP_SHIFT);
3530         }
3531
3532         if (xa->flags & ATA_F_WRITE)
3533                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_W);
3534
3535         if (xa->flags & ATA_F_PACKET)
3536                 cmd_slot->flags |= htole16(AHCI_CMD_LIST_FLAG_A);
3537
3538         if (ahci_load_prdt(ccb) != 0)
3539                 goto failcmd;
3540
3541         xa->state = ATA_S_PENDING;
3542
3543         if (xa->flags & ATA_F_POLL)
3544                 return (ahci_poll(ccb, xa->timeout, ahci_ata_cmd_timeout));
3545
3546         crit_enter();
3547         KKASSERT((xa->flags & ATA_F_TIMEOUT_EXPIRED) == 0);
3548         xa->flags |= ATA_F_TIMEOUT_DESIRED;
3549         ahci_start(ccb);
3550         crit_exit();
3551         return (xa->state);
3552
3553 failcmd:
3554         crit_enter();
3555         xa->state = ATA_S_ERROR;
3556         xa->complete(xa);
3557         crit_exit();
3558         return (ATA_S_ERROR);
3559 }
3560
3561 void
3562 ahci_ata_cmd_done(struct ahci_ccb *ccb)
3563 {
3564         struct ata_xfer *xa = &ccb->ccb_xa;
3565         int serial;
3566
3567         /*
3568          * NOTE: Callout does not lock port and may race us modifying
3569          *       the flags, so make sure its stopped.
3570          *
3571          *       A callout race can clean up the ccb.  A change in the
3572          *       serial number should catch this condition.
3573          */
3574         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
3575                 serial = ccb->ccb_xa.serial;
3576                 callout_stop_sync(&ccb->ccb_timeout);
3577                 if (serial != ccb->ccb_xa.serial) {
3578                         kprintf("%s: Warning: timeout race ccb %p\n",
3579                                 PORTNAME(ccb->ccb_port), ccb);
3580                         return;
3581                 }
3582                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
3583         }
3584         xa->flags &= ~(ATA_F_TIMEOUT_DESIRED | ATA_F_TIMEOUT_EXPIRED);
3585         ccb->ccb_port->ap_expired &= ~(1 << ccb->ccb_slot);
3586
3587         KKASSERT(xa->state != ATA_S_ONCHIP && xa->state != ATA_S_PUT);
3588         ahci_unload_prdt(ccb);
3589
3590         if (xa->state != ATA_S_TIMEOUT)
3591                 xa->complete(xa);
3592 }
3593
3594 /*
3595  * Timeout from callout, MPSAFE - nothing can mess with the CCB's flags
3596  * while the callout is runing.
3597  *
3598  * We can't safely get the port lock here or delay, we could block
3599  * the callout thread.
3600  */
3601 static void
3602 ahci_ata_cmd_timeout_unserialized(void *arg)
3603 {
3604         struct ahci_ccb         *ccb = arg;
3605         struct ahci_port        *ap = ccb->ccb_port;
3606
3607         KKASSERT(ccb->ccb_xa.flags & ATA_F_TIMEOUT_RUNNING);
3608         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
3609         ccb->ccb_xa.flags |= ATA_F_TIMEOUT_EXPIRED;
3610         ahci_os_signal_port_thread(ap, AP_SIGF_TIMEOUT);
3611 }
3612
3613 /*
3614  * Timeout code, typically called when the port command processor is running.
3615  *
3616  * We have to be very very careful here.  We cannot stop the port unless
3617  * CR is already clear or the only active commands remaining are timed-out
3618  * ones.  Otherwise stopping the port will race the command processor and
3619  * we can lose events.  While we can theoretically just restart everything
3620  * that could result in a double-issue which will not work for ATAPI commands.
3621  */
3622 void
3623 ahci_ata_cmd_timeout(struct ahci_ccb *ccb)
3624 {
3625         struct ata_xfer         *xa = &ccb->ccb_xa;
3626         struct ahci_port        *ap = ccb->ccb_port;
3627         struct ata_port         *at;
3628         u_int32_t               ci_saved;
3629         u_int32_t               mask;
3630         int                     slot;
3631
3632         at = ccb->ccb_xa.at;
3633
3634         kprintf("%s: CMD TIMEOUT state=%d slot=%d\n"
3635                 "\tglb-status 0x%08x\n"
3636                 "\tcmd-reg 0x%b\n"
3637                 "\tport_status 0x%b\n"
3638                 "\tsactive=%08x active=%08x expired=%08x\n"
3639                 "\t   sact=%08x     ci=%08x\n"
3640                 "\t    STS=%b\n",
3641                 ATANAME(ap, at),
3642                 ccb->ccb_xa.state, ccb->ccb_slot,
3643                 ahci_read(ap->ap_sc, AHCI_REG_IS),
3644                 ahci_pread(ap, AHCI_PREG_CMD), AHCI_PFMT_CMD,
3645                 ahci_pread(ap, AHCI_PREG_IS), AHCI_PFMT_IS,
3646                 ap->ap_sactive, ap->ap_active, ap->ap_expired,
3647                 ahci_pread(ap, AHCI_PREG_SACT),
3648                 ahci_pread(ap, AHCI_PREG_CI),
3649                 ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS
3650         );
3651
3652
3653         /*
3654          * NOTE: Timeout will not be running if the command was polled.
3655          *       If we got here at least one of these flags should be set.
3656          */
3657         KKASSERT(xa->flags & (ATA_F_POLL | ATA_F_TIMEOUT_DESIRED |
3658                               ATA_F_TIMEOUT_RUNNING));
3659         xa->flags &= ~(ATA_F_TIMEOUT_RUNNING | ATA_F_TIMEOUT_EXPIRED);
3660
3661         if (ccb->ccb_xa.state == ATA_S_PENDING) {
3662                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
3663                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
3664                 ccb->ccb_done(ccb);
3665                 xa->complete(xa);
3666                 ahci_issue_pending_commands(ap, NULL);
3667                 return;
3668         }
3669         if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
3670                 kprintf("%s: Unexpected state during timeout: %d\n",
3671                         ATANAME(ap, at), ccb->ccb_xa.state);
3672                 return;
3673         }
3674
3675         /*
3676          * Ok, we can only get this command off the chip if CR is inactive
3677          * or if the only commands running on the chip are all expired.
3678          * Otherwise we have to wait until the port is in a safe state.
3679          *
3680          * Do not set state here, it will cause polls to return when the
3681          * ccb is not yet off the chip.
3682          */
3683         ap->ap_expired |= 1 << ccb->ccb_slot;
3684
3685         if ((ahci_pread(ap, AHCI_PREG_CMD) & AHCI_PREG_CMD_CR) &&
3686             (ap->ap_active | ap->ap_sactive) != ap->ap_expired) {
3687                 /*
3688                  * If using FBSS or NCQ we can't safely stop the port
3689                  * right now.
3690                  */
3691                 kprintf("%s: Deferred timeout until its safe, slot %d\n",
3692                         ATANAME(ap, at), ccb->ccb_slot);
3693                 return;
3694         }
3695
3696         /*
3697          * We can safely stop the port and process all expired ccb's,
3698          * which will include our current ccb.
3699          */
3700         ci_saved = (ap->ap_sactive) ? ahci_pread(ap, AHCI_PREG_SACT) :
3701                                       ahci_pread(ap, AHCI_PREG_CI);
3702         ahci_port_stop(ap, 0);
3703
3704         while (ap->ap_expired) {
3705                 slot = ffs(ap->ap_expired) - 1;
3706                 ap->ap_expired &= ~(1 << slot);
3707                 ci_saved &= ~(1 << slot);
3708                 ccb = &ap->ap_ccbs[slot];
3709                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
3710                 if (ccb->ccb_xa.flags & ATA_F_NCQ) {
3711                         KKASSERT(ap->ap_sactive & (1 << slot));
3712                         ap->ap_sactive &= ~(1 << slot);
3713                 } else {
3714                         KKASSERT(ap->ap_active & (1 << slot));
3715                         ap->ap_active &= ~(1 << slot);
3716                         --ap->ap_active_cnt;
3717                 }
3718                 ccb->ccb_done(ccb);
3719                 ccb->ccb_xa.complete(&ccb->ccb_xa);
3720         }
3721         /* ccb invalid now */
3722
3723         /*
3724          * We can safely CLO the port to clear any BSY/DRQ, a case which
3725          * can occur with port multipliers.  This will unbrick the port
3726          * and allow commands to other targets behind the PM continue.
3727          * (FBSS).
3728          *
3729          * Finally, once the port has been restarted we can issue any
3730          * previously saved pending commands, and run the port interrupt
3731          * code to handle any completions which may have occured when
3732          * we saved CI.
3733          */
3734         if (ahci_pread(ap, AHCI_PREG_TFD) &
3735                    (AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
3736                 kprintf("%s: Warning, issuing CLO after timeout\n",
3737                         ATANAME(ap, at));
3738                 ahci_port_clo(ap);
3739         }
3740         ahci_port_start(ap);
3741
3742         /*
3743          * We absolutely must make sure the chipset cleared activity on
3744          * all slots.  This sometimes might not happen due to races with
3745          * a chipset interrupt which stops the port before we can manage
3746          * to.  For some reason some chipsets don't clear the active
3747          * commands when we turn off CMD_ST after the chip has stopped
3748          * operations itself.
3749          */
3750         if (ahci_pactive(ap) != 0) {
3751                 ahci_port_stop(ap, 0);
3752                 ahci_port_start(ap);
3753                 if ((mask = ahci_pactive(ap)) != 0) {
3754                         kprintf("%s: quick-timeout: chipset failed "
3755                                 "to clear active cmds %08x\n",
3756                                 PORTNAME(ap), mask);
3757                 }
3758         }
3759         ahci_issue_saved_commands(ap, ci_saved & ~ap->ap_expired);
3760         ahci_issue_pending_commands(ap, NULL);
3761         ahci_port_intr(ap, 0);
3762 }
3763
3764 /*
3765  * Issue a previously saved set of commands
3766  */
3767 void
3768 ahci_issue_saved_commands(struct ahci_port *ap, u_int32_t ci_saved)
3769 {
3770         if (ci_saved) {
3771                 KKASSERT(!((ap->ap_active & ci_saved) &&
3772                            (ap->ap_sactive & ci_saved)));
3773                 KKASSERT((ci_saved & ap->ap_expired) == 0);
3774                 if (ap->ap_sactive & ci_saved)
3775                         ahci_pwrite(ap, AHCI_PREG_SACT, ci_saved);
3776                 ahci_pwrite(ap, AHCI_PREG_CI, ci_saved);
3777         }
3778 }
3779
3780 /*
3781  * Used by the softreset, pmprobe, and read_ncq_error only, in very
3782  * specialized, controlled circumstances.
3783  *
3784  * Only one command may be pending.
3785  */
3786 void
3787 ahci_quick_timeout(struct ahci_ccb *ccb)
3788 {
3789         struct ahci_port *ap = ccb->ccb_port;
3790         u_int32_t mask;
3791
3792         switch (ccb->ccb_xa.state) {
3793         case ATA_S_PENDING:
3794                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
3795                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
3796                 break;
3797         case ATA_S_ONCHIP:
3798                 /*
3799                  * We have to clear the command on-chip.
3800                  */
3801                 KKASSERT(ap->ap_active == (1 << ccb->ccb_slot) &&
3802                          ap->ap_sactive == 0);
3803                 ahci_port_stop(ap, 0);
3804                 ahci_port_start(ap);
3805                 if (ahci_pactive(ap) != 0) {
3806                         ahci_port_stop(ap, 0);
3807                         ahci_port_start(ap);
3808                         if ((mask = ahci_pactive(ap)) != 0) {
3809                                 kprintf("%s: quick-timeout: chipset failed "
3810                                         "to clear active cmds %08x\n",
3811                                         PORTNAME(ap), mask);
3812                         }
3813                 }
3814
3815                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
3816                 ap->ap_active &= ~(1 << ccb->ccb_slot);
3817                 KKASSERT(ap->ap_active_cnt > 0);
3818                 --ap->ap_active_cnt;
3819                 break;
3820         default:
3821                 panic("%s: ahci_quick_timeout: ccb in bad state %d",
3822                       ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_xa.state);
3823         }
3824 }
3825
3826 static void
3827 ahci_dummy_done(struct ata_xfer *xa)
3828 {
3829 }
3830
3831 static void
3832 ahci_empty_done(struct ahci_ccb *ccb)
3833 {
3834 }
3835
3836 int
3837 ahci_set_feature(struct ahci_port *ap, struct ata_port *atx,
3838                  int feature, int enable)
3839 {
3840         struct ata_port *at;
3841         struct ata_xfer *xa;
3842         int error;
3843
3844         at = atx ? atx : ap->ap_ata[0];
3845
3846         xa = ahci_ata_get_xfer(ap, atx);
3847
3848         xa->fis->type = ATA_FIS_TYPE_H2D;
3849         xa->fis->flags = ATA_H2D_FLAGS_CMD | at->at_target;
3850         xa->fis->command = ATA_C_SET_FEATURES;
3851         xa->fis->features = enable ? ATA_SF_SATAFT_ENA : ATA_SF_SATAFT_DIS;
3852         xa->fis->sector_count = feature;
3853         xa->fis->control = ATA_FIS_CONTROL_4BIT;
3854
3855         xa->complete = ahci_dummy_done;
3856         xa->datalen = 0;
3857         xa->flags = ATA_F_POLL;
3858         xa->timeout = 1000;
3859
3860         if (ahci_ata_cmd(xa) == ATA_S_COMPLETE)
3861                 error = 0;
3862         else
3863                 error = EIO;
3864         ahci_ata_put_xfer(xa);
3865         return(error);
3866 }