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