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