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