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