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