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