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