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