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