xref: /freebsd/sys/dev/siis/siis.c (revision dad64f0e)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/module.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/ata.h>
37 #include <sys/bus.h>
38 #include <sys/endian.h>
39 #include <sys/malloc.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/sbuf.h>
43 #include <sys/sema.h>
44 #include <sys/taskqueue.h>
45 #include <vm/uma.h>
46 #include <machine/stdarg.h>
47 #include <machine/resource.h>
48 #include <machine/bus.h>
49 #include <sys/rman.h>
50 #include <dev/led/led.h>
51 #include <dev/pci/pcivar.h>
52 #include <dev/pci/pcireg.h>
53 #include "siis.h"
54 
55 #include <cam/cam.h>
56 #include <cam/cam_ccb.h>
57 #include <cam/cam_sim.h>
58 #include <cam/cam_xpt_sim.h>
59 #include <cam/cam_debug.h>
60 
61 /* local prototypes */
62 static int siis_setup_interrupt(device_t dev);
63 static void siis_intr(void *data);
64 static int siis_suspend(device_t dev);
65 static int siis_resume(device_t dev);
66 static int siis_ch_init(device_t dev);
67 static int siis_ch_deinit(device_t dev);
68 static int siis_ch_suspend(device_t dev);
69 static int siis_ch_resume(device_t dev);
70 static void siis_ch_intr_locked(void *data);
71 static void siis_ch_intr(void *data);
72 static void siis_ch_led(void *priv, int onoff);
73 static void siis_begin_transaction(device_t dev, union ccb *ccb);
74 static void siis_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
75 static void siis_execute_transaction(struct siis_slot *slot);
76 static void siis_timeout(void *arg);
77 static void siis_end_transaction(struct siis_slot *slot, enum siis_err_type et);
78 static int siis_setup_fis(device_t dev, struct siis_cmd *ctp, union ccb *ccb, int tag);
79 static void siis_dmainit(device_t dev);
80 static void siis_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
81 static void siis_dmafini(device_t dev);
82 static void siis_slotsalloc(device_t dev);
83 static void siis_slotsfree(device_t dev);
84 static void siis_reset(device_t dev);
85 static void siis_portinit(device_t dev);
86 static int siis_wait_ready(device_t dev, int t);
87 
88 static int siis_sata_connect(struct siis_channel *ch);
89 
90 static void siis_issue_recovery(device_t dev);
91 static void siis_process_read_log(device_t dev, union ccb *ccb);
92 static void siis_process_request_sense(device_t dev, union ccb *ccb);
93 
94 static void siisaction(struct cam_sim *sim, union ccb *ccb);
95 static void siispoll(struct cam_sim *sim);
96 
97 static MALLOC_DEFINE(M_SIIS, "SIIS driver", "SIIS driver data buffers");
98 
99 static struct {
100 	uint32_t	id;
101 	const char	*name;
102 	int		ports;
103 	int		quirks;
104 #define SIIS_Q_SNTF	1
105 #define SIIS_Q_NOMSI	2
106 } siis_ids[] = {
107 	{0x31241095,	"SiI3124",	4,	0},
108 	{0x31248086,	"SiI3124",	4,	0},
109 	{0x31321095,	"SiI3132",	2,	SIIS_Q_SNTF|SIIS_Q_NOMSI},
110 	{0x02421095,	"SiI3132",	2,	SIIS_Q_SNTF|SIIS_Q_NOMSI},
111 	{0x02441095,	"SiI3132",	2,	SIIS_Q_SNTF|SIIS_Q_NOMSI},
112 	{0x31311095,	"SiI3131",	1,	SIIS_Q_SNTF|SIIS_Q_NOMSI},
113 	{0x35311095,	"SiI3531",	1,	SIIS_Q_SNTF|SIIS_Q_NOMSI},
114 	{0,		NULL,		0,	0}
115 };
116 
117 #define recovery_type		spriv_field0
118 #define RECOVERY_NONE		0
119 #define RECOVERY_READ_LOG	1
120 #define RECOVERY_REQUEST_SENSE	2
121 #define recovery_slot		spriv_field1
122 
123 static int
124 siis_probe(device_t dev)
125 {
126 	char buf[64];
127 	int i;
128 	uint32_t devid = pci_get_devid(dev);
129 
130 	for (i = 0; siis_ids[i].id != 0; i++) {
131 		if (siis_ids[i].id == devid) {
132 			snprintf(buf, sizeof(buf), "%s SATA controller",
133 			    siis_ids[i].name);
134 			device_set_desc_copy(dev, buf);
135 			return (BUS_PROBE_DEFAULT);
136 		}
137 	}
138 	return (ENXIO);
139 }
140 
141 static int
142 siis_attach(device_t dev)
143 {
144 	struct siis_controller *ctlr = device_get_softc(dev);
145 	uint32_t devid = pci_get_devid(dev);
146 	device_t child;
147 	int	error, i, unit;
148 
149 	ctlr->dev = dev;
150 	for (i = 0; siis_ids[i].id != 0; i++) {
151 		if (siis_ids[i].id == devid)
152 			break;
153 	}
154 	ctlr->quirks = siis_ids[i].quirks;
155 	/* Global memory */
156 	ctlr->r_grid = PCIR_BAR(0);
157 	if (!(ctlr->r_gmem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
158 	    &ctlr->r_grid, RF_ACTIVE)))
159 		return (ENXIO);
160 	ctlr->gctl = ATA_INL(ctlr->r_gmem, SIIS_GCTL);
161 	/* Channels memory */
162 	ctlr->r_rid = PCIR_BAR(2);
163 	if (!(ctlr->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
164 	    &ctlr->r_rid, RF_ACTIVE)))
165 		return (ENXIO);
166 	/* Setup our own memory management for channels. */
167 	ctlr->sc_iomem.rm_start = rman_get_start(ctlr->r_mem);
168 	ctlr->sc_iomem.rm_end = rman_get_end(ctlr->r_mem);
169 	ctlr->sc_iomem.rm_type = RMAN_ARRAY;
170 	ctlr->sc_iomem.rm_descr = "I/O memory addresses";
171 	if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
172 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
173 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_grid, ctlr->r_gmem);
174 		return (error);
175 	}
176 	if ((error = rman_manage_region(&ctlr->sc_iomem,
177 	    rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
178 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
179 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_grid, ctlr->r_gmem);
180 		rman_fini(&ctlr->sc_iomem);
181 		return (error);
182 	}
183 	pci_enable_busmaster(dev);
184 	/* Reset controller */
185 	siis_resume(dev);
186 	/* Number of HW channels */
187 	ctlr->channels = siis_ids[i].ports;
188 	/* Setup interrupts. */
189 	if (siis_setup_interrupt(dev)) {
190 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
191 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_grid, ctlr->r_gmem);
192 		rman_fini(&ctlr->sc_iomem);
193 		return ENXIO;
194 	}
195 	/* Attach all channels on this controller */
196 	for (unit = 0; unit < ctlr->channels; unit++) {
197 		child = device_add_child(dev, "siisch", -1);
198 		if (child == NULL)
199 			device_printf(dev, "failed to add channel device\n");
200 		else
201 			device_set_ivars(child, (void *)(intptr_t)unit);
202 	}
203 	bus_generic_attach(dev);
204 	return 0;
205 }
206 
207 static int
208 siis_detach(device_t dev)
209 {
210 	struct siis_controller *ctlr = device_get_softc(dev);
211 
212 	/* Detach & delete all children */
213 	device_delete_children(dev);
214 
215 	/* Free interrupts. */
216 	if (ctlr->irq.r_irq) {
217 		bus_teardown_intr(dev, ctlr->irq.r_irq,
218 		    ctlr->irq.handle);
219 		bus_release_resource(dev, SYS_RES_IRQ,
220 		    ctlr->irq.r_irq_rid, ctlr->irq.r_irq);
221 	}
222 	pci_release_msi(dev);
223 	/* Free memory. */
224 	rman_fini(&ctlr->sc_iomem);
225 	bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
226 	bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_grid, ctlr->r_gmem);
227 	return (0);
228 }
229 
230 static int
231 siis_suspend(device_t dev)
232 {
233 	struct siis_controller *ctlr = device_get_softc(dev);
234 
235 	bus_generic_suspend(dev);
236 	/* Put controller into reset state. */
237 	ctlr->gctl |= SIIS_GCTL_GRESET;
238 	ATA_OUTL(ctlr->r_gmem, SIIS_GCTL, ctlr->gctl);
239 	return 0;
240 }
241 
242 static int
243 siis_resume(device_t dev)
244 {
245 	struct siis_controller *ctlr = device_get_softc(dev);
246 
247 	/* Set PCIe max read request size to at least 1024 bytes */
248 	if (pci_get_max_read_req(dev) < 1024)
249 		pci_set_max_read_req(dev, 1024);
250 	/* Put controller into reset state. */
251 	ctlr->gctl |= SIIS_GCTL_GRESET;
252 	ATA_OUTL(ctlr->r_gmem, SIIS_GCTL, ctlr->gctl);
253 	DELAY(10000);
254 	/* Get controller out of reset state and enable port interrupts. */
255 	ctlr->gctl &= ~(SIIS_GCTL_GRESET | SIIS_GCTL_I2C_IE);
256 	ctlr->gctl |= 0x0000000f;
257 	ATA_OUTL(ctlr->r_gmem, SIIS_GCTL, ctlr->gctl);
258 	return (bus_generic_resume(dev));
259 }
260 
261 static int
262 siis_setup_interrupt(device_t dev)
263 {
264 	struct siis_controller *ctlr = device_get_softc(dev);
265 	int msi = ctlr->quirks & SIIS_Q_NOMSI ? 0 : 1;
266 
267 	/* Process hints. */
268 	resource_int_value(device_get_name(dev),
269 	    device_get_unit(dev), "msi", &msi);
270 	if (msi < 0)
271 		msi = 0;
272 	else if (msi > 0)
273 		msi = min(1, pci_msi_count(dev));
274 	/* Allocate MSI if needed/present. */
275 	if (msi && pci_alloc_msi(dev, &msi) != 0)
276 		msi = 0;
277 	/* Allocate all IRQs. */
278 	ctlr->irq.r_irq_rid = msi ? 1 : 0;
279 	if (!(ctlr->irq.r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
280 	    &ctlr->irq.r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
281 		device_printf(dev, "unable to map interrupt\n");
282 		return ENXIO;
283 	}
284 	if ((bus_setup_intr(dev, ctlr->irq.r_irq, ATA_INTR_FLAGS, NULL,
285 	    siis_intr, ctlr, &ctlr->irq.handle))) {
286 		/* SOS XXX release r_irq */
287 		device_printf(dev, "unable to setup interrupt\n");
288 		return ENXIO;
289 	}
290 	return (0);
291 }
292 
293 /*
294  * Common case interrupt handler.
295  */
296 static void
297 siis_intr(void *data)
298 {
299 	struct siis_controller *ctlr = (struct siis_controller *)data;
300 	u_int32_t is;
301 	void *arg;
302 	int unit;
303 
304 	is = ATA_INL(ctlr->r_gmem, SIIS_IS);
305 	for (unit = 0; unit < ctlr->channels; unit++) {
306 		if ((is & SIIS_IS_PORT(unit)) != 0 &&
307 		    (arg = ctlr->interrupt[unit].argument)) {
308 			ctlr->interrupt[unit].function(arg);
309 		}
310 	}
311 	/* Acknowledge interrupt, if MSI enabled. */
312 	if (ctlr->irq.r_irq_rid) {
313 		ATA_OUTL(ctlr->r_gmem, SIIS_GCTL,
314 		    ctlr->gctl | SIIS_GCTL_MSIACK);
315 	}
316 }
317 
318 static struct resource *
319 siis_alloc_resource(device_t dev, device_t child, int type, int *rid,
320 		    rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
321 {
322 	struct siis_controller *ctlr = device_get_softc(dev);
323 	int unit = ((struct siis_channel *)device_get_softc(child))->unit;
324 	struct resource *res = NULL;
325 	int offset = unit << 13;
326 	rman_res_t st;
327 
328 	switch (type) {
329 	case SYS_RES_MEMORY:
330 		st = rman_get_start(ctlr->r_mem);
331 		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
332 		    st + offset + 0x2000, 0x2000, RF_ACTIVE, child);
333 		if (res) {
334 			bus_space_handle_t bsh;
335 			bus_space_tag_t bst;
336 			bsh = rman_get_bushandle(ctlr->r_mem);
337 			bst = rman_get_bustag(ctlr->r_mem);
338 			bus_space_subregion(bst, bsh, offset, 0x2000, &bsh);
339 			rman_set_bushandle(res, bsh);
340 			rman_set_bustag(res, bst);
341 		}
342 		break;
343 	case SYS_RES_IRQ:
344 		if (*rid == ATA_IRQ_RID)
345 			res = ctlr->irq.r_irq;
346 		break;
347 	}
348 	return (res);
349 }
350 
351 static int
352 siis_release_resource(device_t dev, device_t child, int type, int rid,
353 			 struct resource *r)
354 {
355 
356 	switch (type) {
357 	case SYS_RES_MEMORY:
358 		rman_release_resource(r);
359 		return (0);
360 	case SYS_RES_IRQ:
361 		if (rid != ATA_IRQ_RID)
362 			return ENOENT;
363 		return (0);
364 	}
365 	return (EINVAL);
366 }
367 
368 static int
369 siis_setup_intr(device_t dev, device_t child, struct resource *irq,
370 		   int flags, driver_filter_t *filter, driver_intr_t *function,
371 		   void *argument, void **cookiep)
372 {
373 	struct siis_controller *ctlr = device_get_softc(dev);
374 	int unit = (intptr_t)device_get_ivars(child);
375 
376 	if (filter != NULL) {
377 		printf("siis.c: we cannot use a filter here\n");
378 		return (EINVAL);
379 	}
380 	ctlr->interrupt[unit].function = function;
381 	ctlr->interrupt[unit].argument = argument;
382 	return (0);
383 }
384 
385 static int
386 siis_teardown_intr(device_t dev, device_t child, struct resource *irq,
387 		      void *cookie)
388 {
389 	struct siis_controller *ctlr = device_get_softc(dev);
390 	int unit = (intptr_t)device_get_ivars(child);
391 
392 	ctlr->interrupt[unit].function = NULL;
393 	ctlr->interrupt[unit].argument = NULL;
394 	return (0);
395 }
396 
397 static int
398 siis_print_child(device_t dev, device_t child)
399 {
400 	int retval;
401 
402 	retval = bus_print_child_header(dev, child);
403 	retval += printf(" at channel %d",
404 	    (int)(intptr_t)device_get_ivars(child));
405 	retval += bus_print_child_footer(dev, child);
406 
407 	return (retval);
408 }
409 
410 static int
411 siis_child_location(device_t dev, device_t child, struct sbuf *sb)
412 {
413 
414 	sbuf_printf(sb, "channel=%d",
415 	    (int)(intptr_t)device_get_ivars(child));
416 	return (0);
417 }
418 
419 static bus_dma_tag_t
420 siis_get_dma_tag(device_t bus, device_t child)
421 {
422 
423 	return (bus_get_dma_tag(bus));
424 }
425 
426 static device_method_t siis_methods[] = {
427 	DEVMETHOD(device_probe,     siis_probe),
428 	DEVMETHOD(device_attach,    siis_attach),
429 	DEVMETHOD(device_detach,    siis_detach),
430 	DEVMETHOD(device_suspend,   siis_suspend),
431 	DEVMETHOD(device_resume,    siis_resume),
432 	DEVMETHOD(bus_print_child,  siis_print_child),
433 	DEVMETHOD(bus_alloc_resource,       siis_alloc_resource),
434 	DEVMETHOD(bus_release_resource,     siis_release_resource),
435 	DEVMETHOD(bus_setup_intr,   siis_setup_intr),
436 	DEVMETHOD(bus_teardown_intr,siis_teardown_intr),
437 	DEVMETHOD(bus_child_location, siis_child_location),
438 	DEVMETHOD(bus_get_dma_tag,  siis_get_dma_tag),
439 	{ 0, 0 }
440 };
441 
442 static driver_t siis_driver = {
443         "siis",
444         siis_methods,
445         sizeof(struct siis_controller)
446 };
447 
448 DRIVER_MODULE(siis, pci, siis_driver, 0, 0);
449 MODULE_VERSION(siis, 1);
450 MODULE_DEPEND(siis, cam, 1, 1, 1);
451 
452 static int
453 siis_ch_probe(device_t dev)
454 {
455 
456 	device_set_desc_copy(dev, "SIIS channel");
457 	return (BUS_PROBE_DEFAULT);
458 }
459 
460 static int
461 siis_ch_attach(device_t dev)
462 {
463 	struct siis_controller *ctlr = device_get_softc(device_get_parent(dev));
464 	struct siis_channel *ch = device_get_softc(dev);
465 	struct cam_devq *devq;
466 	int rid, error, i, sata_rev = 0;
467 
468 	ch->dev = dev;
469 	ch->unit = (intptr_t)device_get_ivars(dev);
470 	ch->quirks = ctlr->quirks;
471 	ch->pm_level = 0;
472 	resource_int_value(device_get_name(dev),
473 	    device_get_unit(dev), "pm_level", &ch->pm_level);
474 	resource_int_value(device_get_name(dev),
475 	    device_get_unit(dev), "sata_rev", &sata_rev);
476 	for (i = 0; i < 16; i++) {
477 		ch->user[i].revision = sata_rev;
478 		ch->user[i].mode = 0;
479 		ch->user[i].bytecount = 8192;
480 		ch->user[i].tags = SIIS_MAX_SLOTS;
481 		ch->curr[i] = ch->user[i];
482 		if (ch->pm_level)
483 			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ;
484 		ch->user[i].caps |= CTS_SATA_CAPS_H_AN;
485 	}
486 	mtx_init(&ch->mtx, "SIIS channel lock", NULL, MTX_DEF);
487 	rid = ch->unit;
488 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
489 	    &rid, RF_ACTIVE)))
490 		return (ENXIO);
491 	siis_dmainit(dev);
492 	siis_slotsalloc(dev);
493 	siis_ch_init(dev);
494 	mtx_lock(&ch->mtx);
495 	rid = ATA_IRQ_RID;
496 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
497 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
498 		device_printf(dev, "Unable to map interrupt\n");
499 		error = ENXIO;
500 		goto err0;
501 	}
502 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
503 	    siis_ch_intr_locked, dev, &ch->ih))) {
504 		device_printf(dev, "Unable to setup interrupt\n");
505 		error = ENXIO;
506 		goto err1;
507 	}
508 	/* Create the device queue for our SIM. */
509 	devq = cam_simq_alloc(SIIS_MAX_SLOTS);
510 	if (devq == NULL) {
511 		device_printf(dev, "Unable to allocate simq\n");
512 		error = ENOMEM;
513 		goto err1;
514 	}
515 	/* Construct SIM entry */
516 	ch->sim = cam_sim_alloc(siisaction, siispoll, "siisch", ch,
517 	    device_get_unit(dev), &ch->mtx, 2, SIIS_MAX_SLOTS, devq);
518 	if (ch->sim == NULL) {
519 		cam_simq_free(devq);
520 		device_printf(dev, "unable to allocate sim\n");
521 		error = ENOMEM;
522 		goto err1;
523 	}
524 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
525 		device_printf(dev, "unable to register xpt bus\n");
526 		error = ENXIO;
527 		goto err2;
528 	}
529 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
530 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
531 		device_printf(dev, "unable to create path\n");
532 		error = ENXIO;
533 		goto err3;
534 	}
535 	mtx_unlock(&ch->mtx);
536 	ch->led = led_create(siis_ch_led, dev, device_get_nameunit(dev));
537 	return (0);
538 
539 err3:
540 	xpt_bus_deregister(cam_sim_path(ch->sim));
541 err2:
542 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
543 err1:
544 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
545 err0:
546 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
547 	mtx_unlock(&ch->mtx);
548 	mtx_destroy(&ch->mtx);
549 	return (error);
550 }
551 
552 static int
553 siis_ch_detach(device_t dev)
554 {
555 	struct siis_channel *ch = device_get_softc(dev);
556 
557 	led_destroy(ch->led);
558 	mtx_lock(&ch->mtx);
559 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
560 	xpt_free_path(ch->path);
561 	xpt_bus_deregister(cam_sim_path(ch->sim));
562 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
563 	mtx_unlock(&ch->mtx);
564 
565 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
566 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
567 
568 	siis_ch_deinit(dev);
569 	siis_slotsfree(dev);
570 	siis_dmafini(dev);
571 
572 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
573 	mtx_destroy(&ch->mtx);
574 	return (0);
575 }
576 
577 static int
578 siis_ch_init(device_t dev)
579 {
580 	struct siis_channel *ch = device_get_softc(dev);
581 
582 	/* Get port out of reset state. */
583 	ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PORT_RESET);
584 	ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_32BIT);
585 	if (ch->pm_present)
586 		ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PME);
587 	else
588 		ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PME);
589 	/* Enable port interrupts */
590 	ATA_OUTL(ch->r_mem, SIIS_P_IESET, SIIS_P_IX_ENABLED);
591 	return (0);
592 }
593 
594 static int
595 siis_ch_deinit(device_t dev)
596 {
597 	struct siis_channel *ch = device_get_softc(dev);
598 
599 	/* Put port into reset state. */
600 	ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PORT_RESET);
601 	return (0);
602 }
603 
604 static int
605 siis_ch_suspend(device_t dev)
606 {
607 	struct siis_channel *ch = device_get_softc(dev);
608 
609 	mtx_lock(&ch->mtx);
610 	xpt_freeze_simq(ch->sim, 1);
611 	while (ch->oslots)
612 		msleep(ch, &ch->mtx, PRIBIO, "siissusp", hz/100);
613 	siis_ch_deinit(dev);
614 	mtx_unlock(&ch->mtx);
615 	return (0);
616 }
617 
618 static int
619 siis_ch_resume(device_t dev)
620 {
621 	struct siis_channel *ch = device_get_softc(dev);
622 
623 	mtx_lock(&ch->mtx);
624 	siis_ch_init(dev);
625 	siis_reset(dev);
626 	xpt_release_simq(ch->sim, TRUE);
627 	mtx_unlock(&ch->mtx);
628 	return (0);
629 }
630 
631 static device_method_t siisch_methods[] = {
632 	DEVMETHOD(device_probe,     siis_ch_probe),
633 	DEVMETHOD(device_attach,    siis_ch_attach),
634 	DEVMETHOD(device_detach,    siis_ch_detach),
635 	DEVMETHOD(device_suspend,   siis_ch_suspend),
636 	DEVMETHOD(device_resume,    siis_ch_resume),
637 	{ 0, 0 }
638 };
639 
640 static driver_t siisch_driver = {
641         "siisch",
642         siisch_methods,
643         sizeof(struct siis_channel)
644 };
645 
646 DRIVER_MODULE(siisch, siis, siisch_driver, 0, 0);
647 
648 static void
649 siis_ch_led(void *priv, int onoff)
650 {
651 	device_t dev;
652 	struct siis_channel *ch;
653 
654 	dev = (device_t)priv;
655 	ch = device_get_softc(dev);
656 
657 	if (onoff == 0)
658 		ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_LED_ON);
659 	else
660 		ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_LED_ON);
661 }
662 
663 struct siis_dc_cb_args {
664 	bus_addr_t maddr;
665 	int error;
666 };
667 
668 static void
669 siis_dmainit(device_t dev)
670 {
671 	struct siis_channel *ch = device_get_softc(dev);
672 	struct siis_dc_cb_args dcba;
673 
674 	/* Command area. */
675 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
676 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
677 	    NULL, NULL, SIIS_WORK_SIZE, 1, SIIS_WORK_SIZE,
678 	    0, NULL, NULL, &ch->dma.work_tag))
679 		goto error;
680 	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
681 	    &ch->dma.work_map))
682 		goto error;
683 	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
684 	    SIIS_WORK_SIZE, siis_dmasetupc_cb, &dcba, 0) || dcba.error) {
685 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
686 		goto error;
687 	}
688 	ch->dma.work_bus = dcba.maddr;
689 	/* Data area. */
690 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
691 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
692 	    NULL, NULL,
693 	    SIIS_SG_ENTRIES * PAGE_SIZE, SIIS_SG_ENTRIES, 0xFFFFFFFF,
694 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
695 		goto error;
696 	}
697 	return;
698 
699 error:
700 	device_printf(dev, "WARNING - DMA initialization failed\n");
701 	siis_dmafini(dev);
702 }
703 
704 static void
705 siis_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
706 {
707 	struct siis_dc_cb_args *dcba = (struct siis_dc_cb_args *)xsc;
708 
709 	if (!(dcba->error = error))
710 		dcba->maddr = segs[0].ds_addr;
711 }
712 
713 static void
714 siis_dmafini(device_t dev)
715 {
716 	struct siis_channel *ch = device_get_softc(dev);
717 
718 	if (ch->dma.data_tag) {
719 		bus_dma_tag_destroy(ch->dma.data_tag);
720 		ch->dma.data_tag = NULL;
721 	}
722 	if (ch->dma.work_bus) {
723 		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
724 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
725 		ch->dma.work_bus = 0;
726 		ch->dma.work_map = NULL;
727 		ch->dma.work = NULL;
728 	}
729 	if (ch->dma.work_tag) {
730 		bus_dma_tag_destroy(ch->dma.work_tag);
731 		ch->dma.work_tag = NULL;
732 	}
733 }
734 
735 static void
736 siis_slotsalloc(device_t dev)
737 {
738 	struct siis_channel *ch = device_get_softc(dev);
739 	int i;
740 
741 	/* Alloc and setup command/dma slots */
742 	bzero(ch->slot, sizeof(ch->slot));
743 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
744 		struct siis_slot *slot = &ch->slot[i];
745 
746 		slot->dev = dev;
747 		slot->slot = i;
748 		slot->state = SIIS_SLOT_EMPTY;
749 		slot->prb_offset = SIIS_PRB_SIZE * i;
750 		slot->ccb = NULL;
751 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
752 
753 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
754 			device_printf(ch->dev, "FAILURE - create data_map\n");
755 	}
756 }
757 
758 static void
759 siis_slotsfree(device_t dev)
760 {
761 	struct siis_channel *ch = device_get_softc(dev);
762 	int i;
763 
764 	/* Free all dma slots */
765 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
766 		struct siis_slot *slot = &ch->slot[i];
767 
768 		callout_drain(&slot->timeout);
769 		if (slot->dma.data_map) {
770 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
771 			slot->dma.data_map = NULL;
772 		}
773 	}
774 }
775 
776 static void
777 siis_notify_events(device_t dev)
778 {
779 	struct siis_channel *ch = device_get_softc(dev);
780 	struct cam_path *dpath;
781 	u_int32_t status;
782 	int i;
783 
784 	if (ch->quirks & SIIS_Q_SNTF) {
785 		status = ATA_INL(ch->r_mem, SIIS_P_SNTF);
786 		ATA_OUTL(ch->r_mem, SIIS_P_SNTF, status);
787 	} else {
788 		/*
789 		 * Without SNTF we have no idea which device sent notification.
790 		 * If PMP is connected, assume it, else - device.
791 		 */
792 		status = (ch->pm_present) ? 0x8000 : 0x0001;
793 	}
794 	if (bootverbose)
795 		device_printf(dev, "SNTF 0x%04x\n", status);
796 	for (i = 0; i < 16; i++) {
797 		if ((status & (1 << i)) == 0)
798 			continue;
799 		if (xpt_create_path(&dpath, NULL,
800 		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
801 			xpt_async(AC_SCSI_AEN, dpath, NULL);
802 			xpt_free_path(dpath);
803 		}
804 	}
805 
806 }
807 
808 static void
809 siis_phy_check_events(device_t dev)
810 {
811 	struct siis_channel *ch = device_get_softc(dev);
812 
813 	/* If we have a connection event, deal with it */
814 	if (ch->pm_level == 0) {
815 		u_int32_t status = ATA_INL(ch->r_mem, SIIS_P_SSTS);
816 		union ccb *ccb;
817 
818 		if (bootverbose) {
819 			if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
820 			    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
821 			    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
822 				device_printf(dev, "CONNECT requested\n");
823 			} else
824 				device_printf(dev, "DISCONNECT requested\n");
825 		}
826 		siis_reset(dev);
827 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
828 			return;
829 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
830 		    cam_sim_path(ch->sim),
831 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
832 			xpt_free_ccb(ccb);
833 			return;
834 		}
835 		xpt_rescan(ccb);
836 	}
837 }
838 
839 static void
840 siis_ch_intr_locked(void *data)
841 {
842 	device_t dev = (device_t)data;
843 	struct siis_channel *ch = device_get_softc(dev);
844 
845 	mtx_lock(&ch->mtx);
846 	siis_ch_intr(data);
847 	mtx_unlock(&ch->mtx);
848 }
849 
850 static void
851 siis_ch_intr(void *data)
852 {
853 	device_t dev = (device_t)data;
854 	struct siis_channel *ch = device_get_softc(dev);
855 	uint32_t istatus, sstatus, ctx, estatus, ok;
856 	enum siis_err_type et;
857 	int i, ccs, port, tslots;
858 
859 	mtx_assert(&ch->mtx, MA_OWNED);
860 	/* Read command statuses. */
861 	sstatus = ATA_INL(ch->r_mem, SIIS_P_SS);
862 	ok = ch->rslots & ~sstatus;
863 	/* Complete all successful commands. */
864 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
865 		if ((ok >> i) & 1)
866 			siis_end_transaction(&ch->slot[i], SIIS_ERR_NONE);
867 	}
868 	/* Do we have any other events? */
869 	if ((sstatus & SIIS_P_SS_ATTN) == 0)
870 		return;
871 	/* Read and clear interrupt statuses. */
872 	istatus = ATA_INL(ch->r_mem, SIIS_P_IS) &
873 	    (0xFFFF & ~SIIS_P_IX_COMMCOMP);
874 	ATA_OUTL(ch->r_mem, SIIS_P_IS, istatus);
875 	/* Process PHY events */
876 	if (istatus & SIIS_P_IX_PHYRDYCHG)
877 		siis_phy_check_events(dev);
878 	/* Process NOTIFY events */
879 	if (istatus & SIIS_P_IX_SDBN)
880 		siis_notify_events(dev);
881 	/* Process command errors */
882 	if (istatus & SIIS_P_IX_COMMERR) {
883 		estatus = ATA_INL(ch->r_mem, SIIS_P_CMDERR);
884 		ctx = ATA_INL(ch->r_mem, SIIS_P_CTX);
885 		ccs = (ctx & SIIS_P_CTX_SLOT) >> SIIS_P_CTX_SLOT_SHIFT;
886 		port = (ctx & SIIS_P_CTX_PMP) >> SIIS_P_CTX_PMP_SHIFT;
887 //device_printf(dev, "%s ERROR ss %08x is %08x rs %08x es %d act %d port %d serr %08x\n",
888 //    __func__, sstatus, istatus, ch->rslots, estatus, ccs, port,
889 //    ATA_INL(ch->r_mem, SIIS_P_SERR));
890 
891 		if (!ch->recoverycmd && !ch->recovery) {
892 			xpt_freeze_simq(ch->sim, ch->numrslots);
893 			ch->recovery = 1;
894 		}
895 		if (ch->frozen) {
896 			union ccb *fccb = ch->frozen;
897 			ch->frozen = NULL;
898 			fccb->ccb_h.status &= ~CAM_STATUS_MASK;
899 			fccb->ccb_h.status |= CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
900 			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
901 				xpt_freeze_devq(fccb->ccb_h.path, 1);
902 				fccb->ccb_h.status |= CAM_DEV_QFRZN;
903 			}
904 			xpt_done(fccb);
905 		}
906 		if (estatus == SIIS_P_CMDERR_DEV ||
907 		    estatus == SIIS_P_CMDERR_SDB ||
908 		    estatus == SIIS_P_CMDERR_DATAFIS) {
909 			tslots = ch->numtslots[port];
910 			for (i = 0; i < SIIS_MAX_SLOTS; i++) {
911 				/* XXX: requests in loading state. */
912 				if (((ch->rslots >> i) & 1) == 0)
913 					continue;
914 				if (ch->slot[i].ccb->ccb_h.target_id != port)
915 					continue;
916 				if (tslots == 0) {
917 					/* Untagged operation. */
918 					if (i == ccs)
919 						et = SIIS_ERR_TFE;
920 					else
921 						et = SIIS_ERR_INNOCENT;
922 				} else {
923 					/* Tagged operation. */
924 					et = SIIS_ERR_NCQ;
925 				}
926 				siis_end_transaction(&ch->slot[i], et);
927 			}
928 			/*
929 			 * We can't reinit port if there are some other
930 			 * commands active, use resume to complete them.
931 			 */
932 			if (ch->rslots != 0 && !ch->recoverycmd)
933 				ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_RESUME);
934 		} else {
935 			if (estatus == SIIS_P_CMDERR_SENDFIS ||
936 			    estatus == SIIS_P_CMDERR_INCSTATE ||
937 			    estatus == SIIS_P_CMDERR_PPE ||
938 			    estatus == SIIS_P_CMDERR_SERVICE) {
939 				et = SIIS_ERR_SATA;
940 			} else
941 				et = SIIS_ERR_INVALID;
942 			for (i = 0; i < SIIS_MAX_SLOTS; i++) {
943 				/* XXX: requests in loading state. */
944 				if (((ch->rslots >> i) & 1) == 0)
945 					continue;
946 				siis_end_transaction(&ch->slot[i], et);
947 			}
948 		}
949 	}
950 }
951 
952 /* Must be called with channel locked. */
953 static int
954 siis_check_collision(device_t dev, union ccb *ccb)
955 {
956 	struct siis_channel *ch = device_get_softc(dev);
957 
958 	mtx_assert(&ch->mtx, MA_OWNED);
959 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
960 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
961 		/* Tagged command while we have no supported tag free. */
962 		if (((~ch->oslots) & (0x7fffffff >> (31 -
963 		    ch->curr[ccb->ccb_h.target_id].tags))) == 0)
964 			return (1);
965 	}
966 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
967 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
968 		/* Atomic command while anything active. */
969 		if (ch->numrslots != 0)
970 			return (1);
971 	}
972        /* We have some atomic command running. */
973        if (ch->aslots != 0)
974                return (1);
975 	return (0);
976 }
977 
978 /* Must be called with channel locked. */
979 static void
980 siis_begin_transaction(device_t dev, union ccb *ccb)
981 {
982 	struct siis_channel *ch = device_get_softc(dev);
983 	struct siis_slot *slot;
984 	int tag, tags;
985 
986 	mtx_assert(&ch->mtx, MA_OWNED);
987 	/* Choose empty slot. */
988 	tags = SIIS_MAX_SLOTS;
989 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
990 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
991 		tags = ch->curr[ccb->ccb_h.target_id].tags;
992 	tag = fls((~ch->oslots) & (0x7fffffff >> (31 - tags))) - 1;
993 	/* Occupy chosen slot. */
994 	slot = &ch->slot[tag];
995 	slot->ccb = ccb;
996 	/* Update channel stats. */
997 	ch->oslots |= (1 << slot->slot);
998 	ch->numrslots++;
999 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1000 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1001 		ch->numtslots[ccb->ccb_h.target_id]++;
1002 	}
1003 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1004 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1005 		ch->aslots |= (1 << slot->slot);
1006 	slot->dma.nsegs = 0;
1007 	/* If request moves data, setup and load SG list */
1008 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1009 		slot->state = SIIS_SLOT_LOADING;
1010 		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map,
1011 		    ccb, siis_dmasetprd, slot, 0);
1012 	} else
1013 		siis_execute_transaction(slot);
1014 }
1015 
1016 /* Locked by busdma engine. */
1017 static void
1018 siis_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1019 {
1020 	struct siis_slot *slot = arg;
1021 	struct siis_channel *ch = device_get_softc(slot->dev);
1022 	struct siis_cmd *ctp;
1023 	struct siis_dma_prd *prd;
1024 	int i;
1025 
1026 	mtx_assert(&ch->mtx, MA_OWNED);
1027 	if (error) {
1028 		device_printf(slot->dev, "DMA load error\n");
1029 		if (!ch->recoverycmd)
1030 			xpt_freeze_simq(ch->sim, 1);
1031 		siis_end_transaction(slot, SIIS_ERR_INVALID);
1032 		return;
1033 	}
1034 	KASSERT(nsegs <= SIIS_SG_ENTRIES, ("too many DMA segment entries\n"));
1035 	slot->dma.nsegs = nsegs;
1036 	if (nsegs != 0) {
1037 		/* Get a piece of the workspace for this request */
1038 		ctp = (struct siis_cmd *)(ch->dma.work + slot->prb_offset);
1039 		/* Fill S/G table */
1040 		if (slot->ccb->ccb_h.func_code == XPT_ATA_IO)
1041 			prd = &ctp->u.ata.prd[0];
1042 		else
1043 			prd = &ctp->u.atapi.prd[0];
1044 		for (i = 0; i < nsegs; i++) {
1045 			prd[i].dba = htole64(segs[i].ds_addr);
1046 			prd[i].dbc = htole32(segs[i].ds_len);
1047 			prd[i].control = 0;
1048 		}
1049 			prd[nsegs - 1].control = htole32(SIIS_PRD_TRM);
1050 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1051 		    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1052 		    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1053 	}
1054 	siis_execute_transaction(slot);
1055 }
1056 
1057 /* Must be called with channel locked. */
1058 static void
1059 siis_execute_transaction(struct siis_slot *slot)
1060 {
1061 	device_t dev = slot->dev;
1062 	struct siis_channel *ch = device_get_softc(dev);
1063 	struct siis_cmd *ctp;
1064 	union ccb *ccb = slot->ccb;
1065 	u_int64_t prb_bus;
1066 
1067 	mtx_assert(&ch->mtx, MA_OWNED);
1068 	/* Get a piece of the workspace for this request */
1069 	ctp = (struct siis_cmd *)(ch->dma.work + slot->prb_offset);
1070 	ctp->control = 0;
1071 	ctp->protocol_override = 0;
1072 	ctp->transfer_count = 0;
1073 	/* Special handling for Soft Reset command. */
1074 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1075 		if (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) {
1076 			ctp->control |= htole16(SIIS_PRB_SOFT_RESET);
1077 		} else {
1078 			ctp->control |= htole16(SIIS_PRB_PROTOCOL_OVERRIDE);
1079 			if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1080 				ctp->protocol_override |=
1081 				    htole16(SIIS_PRB_PROTO_NCQ);
1082 			}
1083 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1084 				ctp->protocol_override |=
1085 				    htole16(SIIS_PRB_PROTO_READ);
1086 			} else
1087 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1088 				ctp->protocol_override |=
1089 				    htole16(SIIS_PRB_PROTO_WRITE);
1090 			}
1091 		}
1092 	} else if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1093 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1094 			ctp->control |= htole16(SIIS_PRB_PACKET_READ);
1095 		else
1096 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT)
1097 			ctp->control |= htole16(SIIS_PRB_PACKET_WRITE);
1098 	}
1099 	/* Special handling for Soft Reset command. */
1100 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1101 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1102 	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1103 		/* Kick controller into sane state */
1104 		siis_portinit(dev);
1105 	}
1106 	/* Setup the FIS for this request */
1107 	if (!siis_setup_fis(dev, ctp, ccb, slot->slot)) {
1108 		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1109 		if (!ch->recoverycmd)
1110 			xpt_freeze_simq(ch->sim, 1);
1111 		siis_end_transaction(slot, SIIS_ERR_INVALID);
1112 		return;
1113 	}
1114 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1115 	    BUS_DMASYNC_PREWRITE);
1116 	/* Issue command to the controller. */
1117 	slot->state = SIIS_SLOT_RUNNING;
1118 	ch->rslots |= (1 << slot->slot);
1119 	prb_bus = ch->dma.work_bus + slot->prb_offset;
1120 	ATA_OUTL(ch->r_mem, SIIS_P_CACTL(slot->slot), prb_bus);
1121 	ATA_OUTL(ch->r_mem, SIIS_P_CACTH(slot->slot), prb_bus >> 32);
1122 	/* Start command execution timeout */
1123 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout, 0,
1124 	    siis_timeout, slot, 0);
1125 	return;
1126 }
1127 
1128 /* Must be called with channel locked. */
1129 static void
1130 siis_process_timeout(device_t dev)
1131 {
1132 	struct siis_channel *ch = device_get_softc(dev);
1133 	int i;
1134 
1135 	mtx_assert(&ch->mtx, MA_OWNED);
1136 	if (!ch->recoverycmd && !ch->recovery) {
1137 		xpt_freeze_simq(ch->sim, ch->numrslots);
1138 		ch->recovery = 1;
1139 	}
1140 	/* Handle the rest of commands. */
1141 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1142 		/* Do we have a running request on slot? */
1143 		if (ch->slot[i].state < SIIS_SLOT_RUNNING)
1144 			continue;
1145 		siis_end_transaction(&ch->slot[i], SIIS_ERR_TIMEOUT);
1146 	}
1147 }
1148 
1149 /* Must be called with channel locked. */
1150 static void
1151 siis_rearm_timeout(device_t dev)
1152 {
1153 	struct siis_channel *ch = device_get_softc(dev);
1154 	int i;
1155 
1156 	mtx_assert(&ch->mtx, MA_OWNED);
1157 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1158 		struct siis_slot *slot = &ch->slot[i];
1159 
1160 		/* Do we have a running request on slot? */
1161 		if (slot->state < SIIS_SLOT_RUNNING)
1162 			continue;
1163 		if ((ch->toslots & (1 << i)) == 0)
1164 			continue;
1165 		callout_reset_sbt(&slot->timeout,
1166 		    SBT_1MS * slot->ccb->ccb_h.timeout, 0,
1167 		    siis_timeout, slot, 0);
1168 	}
1169 }
1170 
1171 /* Locked by callout mechanism. */
1172 static void
1173 siis_timeout(void *arg)
1174 {
1175 	struct siis_slot *slot = arg;
1176 	device_t dev = slot->dev;
1177 	struct siis_channel *ch = device_get_softc(dev);
1178 	union ccb *ccb = slot->ccb;
1179 
1180 	mtx_assert(&ch->mtx, MA_OWNED);
1181 	/* Check for stale timeout. */
1182 	if (slot->state < SIIS_SLOT_RUNNING)
1183 		return;
1184 
1185 	/* Handle soft-reset timeouts without doing hard-reset. */
1186 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1187 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1188 	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1189 		xpt_freeze_simq(ch->sim, ch->numrslots);
1190 		siis_end_transaction(slot, SIIS_ERR_TFE);
1191 		return;
1192 	}
1193 
1194 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1195 	device_printf(dev, "%s is %08x ss %08x rs %08x es %08x sts %08x serr %08x\n",
1196 	    __func__, ATA_INL(ch->r_mem, SIIS_P_IS),
1197 	    ATA_INL(ch->r_mem, SIIS_P_SS), ch->rslots,
1198 	    ATA_INL(ch->r_mem, SIIS_P_CMDERR), ATA_INL(ch->r_mem, SIIS_P_STS),
1199 	    ATA_INL(ch->r_mem, SIIS_P_SERR));
1200 
1201 	if (ch->toslots == 0)
1202 		xpt_freeze_simq(ch->sim, 1);
1203 	ch->toslots |= (1 << slot->slot);
1204 	if ((ch->rslots & ~ch->toslots) == 0)
1205 		siis_process_timeout(dev);
1206 	else
1207 		device_printf(dev, " ... waiting for slots %08x\n",
1208 		    ch->rslots & ~ch->toslots);
1209 }
1210 
1211 /* Must be called with channel locked. */
1212 static void
1213 siis_end_transaction(struct siis_slot *slot, enum siis_err_type et)
1214 {
1215 	device_t dev = slot->dev;
1216 	struct siis_channel *ch = device_get_softc(dev);
1217 	union ccb *ccb = slot->ccb;
1218 	int lastto;
1219 
1220 	mtx_assert(&ch->mtx, MA_OWNED);
1221 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1222 	    BUS_DMASYNC_POSTWRITE);
1223 	/* Read result registers to the result struct
1224 	 * May be incorrect if several commands finished same time,
1225 	 * so read only when sure or have to.
1226 	 */
1227 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1228 		struct ata_res *res = &ccb->ataio.res;
1229 		if ((et == SIIS_ERR_TFE) ||
1230 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1231 			int offs = SIIS_P_LRAM_SLOT(slot->slot) + 8;
1232 
1233 			res->status = ATA_INB(ch->r_mem, offs + 2);
1234 			res->error = ATA_INB(ch->r_mem, offs + 3);
1235 			res->lba_low = ATA_INB(ch->r_mem, offs + 4);
1236 			res->lba_mid = ATA_INB(ch->r_mem, offs + 5);
1237 			res->lba_high = ATA_INB(ch->r_mem, offs + 6);
1238 			res->device = ATA_INB(ch->r_mem, offs + 7);
1239 			res->lba_low_exp = ATA_INB(ch->r_mem, offs + 8);
1240 			res->lba_mid_exp = ATA_INB(ch->r_mem, offs + 9);
1241 			res->lba_high_exp = ATA_INB(ch->r_mem, offs + 10);
1242 			res->sector_count = ATA_INB(ch->r_mem, offs + 12);
1243 			res->sector_count_exp = ATA_INB(ch->r_mem, offs + 13);
1244 		} else
1245 			bzero(res, sizeof(*res));
1246 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
1247 		    ch->numrslots == 1) {
1248 			ccb->ataio.resid = ccb->ataio.dxfer_len -
1249 			    ATA_INL(ch->r_mem, SIIS_P_LRAM_SLOT(slot->slot) + 4);
1250 		}
1251 	} else {
1252 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
1253 		    ch->numrslots == 1) {
1254 			ccb->csio.resid = ccb->csio.dxfer_len -
1255 			    ATA_INL(ch->r_mem, SIIS_P_LRAM_SLOT(slot->slot) + 4);
1256 		}
1257 	}
1258 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1259 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1260 		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1261 		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1262 		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1263 	}
1264 	/* Set proper result status. */
1265 	if (et != SIIS_ERR_NONE || ch->recovery) {
1266 		ch->eslots |= (1 << slot->slot);
1267 		ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1268 	}
1269 	/* In case of error, freeze device for proper recovery. */
1270 	if (et != SIIS_ERR_NONE && (!ch->recoverycmd) &&
1271 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1272 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1273 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1274 	}
1275 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1276 	switch (et) {
1277 	case SIIS_ERR_NONE:
1278 		ccb->ccb_h.status |= CAM_REQ_CMP;
1279 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1280 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1281 		break;
1282 	case SIIS_ERR_INVALID:
1283 		ch->fatalerr = 1;
1284 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1285 		break;
1286 	case SIIS_ERR_INNOCENT:
1287 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1288 		break;
1289 	case SIIS_ERR_TFE:
1290 	case SIIS_ERR_NCQ:
1291 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1292 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1293 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1294 		} else {
1295 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1296 		}
1297 		break;
1298 	case SIIS_ERR_SATA:
1299 		ch->fatalerr = 1;
1300 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1301 		break;
1302 	case SIIS_ERR_TIMEOUT:
1303 		ch->fatalerr = 1;
1304 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1305 		break;
1306 	default:
1307 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1308 	}
1309 	/* Free slot. */
1310 	ch->oslots &= ~(1 << slot->slot);
1311 	ch->rslots &= ~(1 << slot->slot);
1312 	ch->aslots &= ~(1 << slot->slot);
1313 	slot->state = SIIS_SLOT_EMPTY;
1314 	slot->ccb = NULL;
1315 	/* Update channel stats. */
1316 	ch->numrslots--;
1317 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1318 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1319 		ch->numtslots[ccb->ccb_h.target_id]--;
1320 	}
1321 	/* Cancel timeout state if request completed normally. */
1322 	if (et != SIIS_ERR_TIMEOUT) {
1323 		lastto = (ch->toslots == (1 << slot->slot));
1324 		ch->toslots &= ~(1 << slot->slot);
1325 		if (lastto)
1326 			xpt_release_simq(ch->sim, TRUE);
1327 	}
1328 	/* If it was our READ LOG command - process it. */
1329 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1330 		siis_process_read_log(dev, ccb);
1331 	/* If it was our REQUEST SENSE command - process it. */
1332 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1333 		siis_process_request_sense(dev, ccb);
1334 	/* If it was NCQ or ATAPI command error, put result on hold. */
1335 	} else if (et == SIIS_ERR_NCQ ||
1336 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1337 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1338 		ch->hold[slot->slot] = ccb;
1339 		ch->numhslots++;
1340 	} else
1341 		xpt_done(ccb);
1342 	/* If we have no other active commands, ... */
1343 	if (ch->rslots == 0) {
1344 		/* if there were timeouts or fatal error - reset port. */
1345 		if (ch->toslots != 0 || ch->fatalerr) {
1346 			siis_reset(dev);
1347 		} else {
1348 			/* if we have slots in error, we can reinit port. */
1349 			if (ch->eslots != 0)
1350 				siis_portinit(dev);
1351 			/* if there commands on hold, we can do recovery. */
1352 			if (!ch->recoverycmd && ch->numhslots)
1353 				siis_issue_recovery(dev);
1354 		}
1355 	/* If all the reset of commands are in timeout - abort them. */
1356 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1357 	    et != SIIS_ERR_TIMEOUT)
1358 		siis_rearm_timeout(dev);
1359 	/* Unfreeze frozen command. */
1360 	if (ch->frozen && !siis_check_collision(dev, ch->frozen)) {
1361 		union ccb *fccb = ch->frozen;
1362 		ch->frozen = NULL;
1363 		siis_begin_transaction(dev, fccb);
1364 		xpt_release_simq(ch->sim, TRUE);
1365 	}
1366 }
1367 
1368 static void
1369 siis_issue_recovery(device_t dev)
1370 {
1371 	struct siis_channel *ch = device_get_softc(dev);
1372 	union ccb *ccb;
1373 	struct ccb_ataio *ataio;
1374 	struct ccb_scsiio *csio;
1375 	int i;
1376 
1377 	/* Find some held command. */
1378 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1379 		if (ch->hold[i])
1380 			break;
1381 	}
1382 	if (i == SIIS_MAX_SLOTS)
1383 		return;
1384 	ccb = xpt_alloc_ccb_nowait();
1385 	if (ccb == NULL) {
1386 		device_printf(dev, "Unable to allocate recovery command\n");
1387 completeall:
1388 		/* We can't do anything -- complete held commands. */
1389 		for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1390 			if (ch->hold[i] == NULL)
1391 				continue;
1392 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1393 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1394 			xpt_done(ch->hold[i]);
1395 			ch->hold[i] = NULL;
1396 			ch->numhslots--;
1397 		}
1398 		siis_reset(dev);
1399 		return;
1400 	}
1401 	xpt_setup_ccb(&ccb->ccb_h, ch->hold[i]->ccb_h.path,
1402 	    ch->hold[i]->ccb_h.pinfo.priority);
1403 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1404 		/* READ LOG */
1405 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1406 		ccb->ccb_h.func_code = XPT_ATA_IO;
1407 		ccb->ccb_h.flags = CAM_DIR_IN;
1408 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1409 		ataio = &ccb->ataio;
1410 		ataio->data_ptr = malloc(512, M_SIIS, M_NOWAIT);
1411 		if (ataio->data_ptr == NULL) {
1412 			xpt_free_ccb(ccb);
1413 			device_printf(dev,
1414 			    "Unable to allocate memory for READ LOG command\n");
1415 			goto completeall;
1416 		}
1417 		ataio->dxfer_len = 512;
1418 		bzero(&ataio->cmd, sizeof(ataio->cmd));
1419 		ataio->cmd.flags = CAM_ATAIO_48BIT;
1420 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1421 		ataio->cmd.sector_count = 1;
1422 		ataio->cmd.sector_count_exp = 0;
1423 		ataio->cmd.lba_low = 0x10;
1424 		ataio->cmd.lba_mid = 0;
1425 		ataio->cmd.lba_mid_exp = 0;
1426 	} else {
1427 		/* REQUEST SENSE */
1428 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1429 		ccb->ccb_h.recovery_slot = i;
1430 		ccb->ccb_h.func_code = XPT_SCSI_IO;
1431 		ccb->ccb_h.flags = CAM_DIR_IN;
1432 		ccb->ccb_h.status = 0;
1433 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1434 		csio = &ccb->csio;
1435 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1436 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1437 		csio->cdb_len = 6;
1438 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1439 		csio->cdb_io.cdb_bytes[0] = 0x03;
1440 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1441 	}
1442 	ch->recoverycmd = 1;
1443 	siis_begin_transaction(dev, ccb);
1444 }
1445 
1446 static void
1447 siis_process_read_log(device_t dev, union ccb *ccb)
1448 {
1449 	struct siis_channel *ch = device_get_softc(dev);
1450 	uint8_t *data;
1451 	struct ata_res *res;
1452 	int i;
1453 
1454 	ch->recoverycmd = 0;
1455 	data = ccb->ataio.data_ptr;
1456 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1457 	    (data[0] & 0x80) == 0) {
1458 		for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1459 			if (!ch->hold[i])
1460 				continue;
1461 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1462 				continue;
1463 			if ((data[0] & 0x1F) == i) {
1464 				res = &ch->hold[i]->ataio.res;
1465 				res->status = data[2];
1466 				res->error = data[3];
1467 				res->lba_low = data[4];
1468 				res->lba_mid = data[5];
1469 				res->lba_high = data[6];
1470 				res->device = data[7];
1471 				res->lba_low_exp = data[8];
1472 				res->lba_mid_exp = data[9];
1473 				res->lba_high_exp = data[10];
1474 				res->sector_count = data[12];
1475 				res->sector_count_exp = data[13];
1476 			} else {
1477 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1478 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1479 			}
1480 			xpt_done(ch->hold[i]);
1481 			ch->hold[i] = NULL;
1482 			ch->numhslots--;
1483 		}
1484 	} else {
1485 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1486 			device_printf(dev, "Error while READ LOG EXT\n");
1487 		else if ((data[0] & 0x80) == 0) {
1488 			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1489 		}
1490 		for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1491 			if (!ch->hold[i])
1492 				continue;
1493 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1494 				continue;
1495 			xpt_done(ch->hold[i]);
1496 			ch->hold[i] = NULL;
1497 			ch->numhslots--;
1498 		}
1499 	}
1500 	free(ccb->ataio.data_ptr, M_SIIS);
1501 	xpt_free_ccb(ccb);
1502 }
1503 
1504 static void
1505 siis_process_request_sense(device_t dev, union ccb *ccb)
1506 {
1507 	struct siis_channel *ch = device_get_softc(dev);
1508 	int i;
1509 
1510 	ch->recoverycmd = 0;
1511 
1512 	i = ccb->ccb_h.recovery_slot;
1513 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1514 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
1515 	} else {
1516 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1517 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
1518 	}
1519 	xpt_done(ch->hold[i]);
1520 	ch->hold[i] = NULL;
1521 	ch->numhslots--;
1522 	xpt_free_ccb(ccb);
1523 }
1524 
1525 static void
1526 siis_portinit(device_t dev)
1527 {
1528 	struct siis_channel *ch = device_get_softc(dev);
1529 	int i;
1530 
1531 	ch->eslots = 0;
1532 	ch->recovery = 0;
1533 	ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_RESUME);
1534 	for (i = 0; i < 16; i++) {
1535 		ATA_OUTL(ch->r_mem, SIIS_P_PMPSTS(i), 0),
1536 		ATA_OUTL(ch->r_mem, SIIS_P_PMPQACT(i), 0);
1537 	}
1538 	ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PORT_INIT);
1539 	siis_wait_ready(dev, 1000);
1540 }
1541 
1542 static int
1543 siis_devreset(device_t dev)
1544 {
1545 	struct siis_channel *ch = device_get_softc(dev);
1546 	int timeout = 0;
1547 	uint32_t val;
1548 
1549 	ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_DEV_RESET);
1550 	while (((val = ATA_INL(ch->r_mem, SIIS_P_STS)) &
1551 	    SIIS_P_CTL_DEV_RESET) != 0) {
1552 		DELAY(100);
1553 		if (timeout++ > 1000) {
1554 			device_printf(dev, "device reset stuck "
1555 			    "(timeout 100ms) status = %08x\n", val);
1556 			return (EBUSY);
1557 		}
1558 	}
1559 	return (0);
1560 }
1561 
1562 static int
1563 siis_wait_ready(device_t dev, int t)
1564 {
1565 	struct siis_channel *ch = device_get_softc(dev);
1566 	int timeout = 0;
1567 	uint32_t val;
1568 
1569 	while (((val = ATA_INL(ch->r_mem, SIIS_P_STS)) &
1570 	    SIIS_P_CTL_READY) == 0) {
1571 		DELAY(1000);
1572 		if (timeout++ > t) {
1573 			device_printf(dev, "port is not ready (timeout %dms) "
1574 			    "status = %08x\n", t, val);
1575 			return (EBUSY);
1576 		}
1577 	}
1578 	return (0);
1579 }
1580 
1581 static void
1582 siis_reset(device_t dev)
1583 {
1584 	struct siis_channel *ch = device_get_softc(dev);
1585 	int i, retry = 0, sata_rev;
1586 	uint32_t val;
1587 
1588 	xpt_freeze_simq(ch->sim, 1);
1589 	if (bootverbose)
1590 		device_printf(dev, "SIIS reset...\n");
1591 	if (!ch->recoverycmd && !ch->recovery)
1592 		xpt_freeze_simq(ch->sim, ch->numrslots);
1593 	/* Requeue frozen command. */
1594 	if (ch->frozen) {
1595 		union ccb *fccb = ch->frozen;
1596 		ch->frozen = NULL;
1597 		fccb->ccb_h.status &= ~CAM_STATUS_MASK;
1598 		fccb->ccb_h.status |= CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1599 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1600 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1601 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1602 		}
1603 		xpt_done(fccb);
1604 	}
1605 	/* Requeue all running commands. */
1606 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1607 		/* Do we have a running request on slot? */
1608 		if (ch->slot[i].state < SIIS_SLOT_RUNNING)
1609 			continue;
1610 		/* XXX; Commands in loading state. */
1611 		siis_end_transaction(&ch->slot[i], SIIS_ERR_INNOCENT);
1612 	}
1613 	/* Finish all held commands as-is. */
1614 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1615 		if (!ch->hold[i])
1616 			continue;
1617 		xpt_done(ch->hold[i]);
1618 		ch->hold[i] = NULL;
1619 		ch->numhslots--;
1620 	}
1621 	if (ch->toslots != 0)
1622 		xpt_release_simq(ch->sim, TRUE);
1623 	ch->eslots = 0;
1624 	ch->recovery = 0;
1625 	ch->toslots = 0;
1626 	ch->fatalerr = 0;
1627 	/* Disable port interrupts */
1628 	ATA_OUTL(ch->r_mem, SIIS_P_IECLR, 0x0000FFFF);
1629 	/* Set speed limit. */
1630 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
1631 	if (sata_rev == 1)
1632 		val = ATA_SC_SPD_SPEED_GEN1;
1633 	else if (sata_rev == 2)
1634 		val = ATA_SC_SPD_SPEED_GEN2;
1635 	else if (sata_rev == 3)
1636 		val = ATA_SC_SPD_SPEED_GEN3;
1637 	else
1638 		val = 0;
1639 	ATA_OUTL(ch->r_mem, SIIS_P_SCTL,
1640 	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
1641 	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
1642 retry:
1643 	siis_devreset(dev);
1644 	/* Reset and reconnect PHY, */
1645 	if (!siis_sata_connect(ch)) {
1646 		ch->devices = 0;
1647 		/* Enable port interrupts */
1648 		ATA_OUTL(ch->r_mem, SIIS_P_IESET, SIIS_P_IX_ENABLED);
1649 		if (bootverbose)
1650 			device_printf(dev,
1651 			    "SIIS reset done: phy reset found no device\n");
1652 		/* Tell the XPT about the event */
1653 		xpt_async(AC_BUS_RESET, ch->path, NULL);
1654 		xpt_release_simq(ch->sim, TRUE);
1655 		return;
1656 	}
1657 	/* Wait for port ready status. */
1658 	if (siis_wait_ready(dev, 1000)) {
1659 		device_printf(dev, "port ready timeout\n");
1660 		if (!retry) {
1661 			device_printf(dev, "trying full port reset ...\n");
1662 			/* Get port to the reset state. */
1663 			ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PORT_RESET);
1664 			DELAY(10000);
1665 			/* Get port out of reset state. */
1666 			ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PORT_RESET);
1667 			ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_32BIT);
1668 			if (ch->pm_present)
1669 				ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PME);
1670 			else
1671 				ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PME);
1672 			siis_wait_ready(dev, 5000);
1673 			retry = 1;
1674 			goto retry;
1675 		}
1676 	}
1677 	ch->devices = 1;
1678 	/* Enable port interrupts */
1679 	ATA_OUTL(ch->r_mem, SIIS_P_IS, 0xFFFFFFFF);
1680 	ATA_OUTL(ch->r_mem, SIIS_P_IESET, SIIS_P_IX_ENABLED);
1681 	if (bootverbose)
1682 		device_printf(dev, "SIIS reset done: devices=%08x\n", ch->devices);
1683 	/* Tell the XPT about the event */
1684 	xpt_async(AC_BUS_RESET, ch->path, NULL);
1685 	xpt_release_simq(ch->sim, TRUE);
1686 }
1687 
1688 static int
1689 siis_setup_fis(device_t dev, struct siis_cmd *ctp, union ccb *ccb, int tag)
1690 {
1691 	struct siis_channel *ch = device_get_softc(dev);
1692 	u_int8_t *fis = &ctp->fis[0];
1693 
1694 	bzero(fis, 24);
1695 	fis[0] = 0x27;  		/* host to device */
1696 	fis[1] = (ccb->ccb_h.target_id & 0x0f);
1697 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1698 		fis[1] |= 0x80;
1699 		fis[2] = ATA_PACKET_CMD;
1700 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1701 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
1702 			fis[3] = ATA_F_DMA;
1703 		else {
1704 			fis[5] = ccb->csio.dxfer_len;
1705 		        fis[6] = ccb->csio.dxfer_len >> 8;
1706 		}
1707 		fis[7] = ATA_D_LBA;
1708 		fis[15] = ATA_A_4BIT;
1709 		bzero(ctp->u.atapi.ccb, 16);
1710 		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1711 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
1712 		    ctp->u.atapi.ccb, ccb->csio.cdb_len);
1713 	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
1714 		fis[1] |= 0x80;
1715 		fis[2] = ccb->ataio.cmd.command;
1716 		fis[3] = ccb->ataio.cmd.features;
1717 		fis[4] = ccb->ataio.cmd.lba_low;
1718 		fis[5] = ccb->ataio.cmd.lba_mid;
1719 		fis[6] = ccb->ataio.cmd.lba_high;
1720 		fis[7] = ccb->ataio.cmd.device;
1721 		fis[8] = ccb->ataio.cmd.lba_low_exp;
1722 		fis[9] = ccb->ataio.cmd.lba_mid_exp;
1723 		fis[10] = ccb->ataio.cmd.lba_high_exp;
1724 		fis[11] = ccb->ataio.cmd.features_exp;
1725 		fis[12] = ccb->ataio.cmd.sector_count;
1726 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1727 			fis[12] &= 0x07;
1728 			fis[12] |= tag << 3;
1729 		}
1730 		fis[13] = ccb->ataio.cmd.sector_count_exp;
1731 		if (ccb->ataio.ata_flags & ATA_FLAG_ICC)
1732 			fis[14] = ccb->ataio.icc;
1733 		fis[15] = ATA_A_4BIT;
1734 		if (ccb->ataio.ata_flags & ATA_FLAG_AUX) {
1735 			fis[16] =  ccb->ataio.aux        & 0xff;
1736 			fis[17] = (ccb->ataio.aux >>  8) & 0xff;
1737 			fis[18] = (ccb->ataio.aux >> 16) & 0xff;
1738 			fis[19] = (ccb->ataio.aux >> 24) & 0xff;
1739 		}
1740 	} else {
1741 		/* Soft reset. */
1742 	}
1743 	return (20);
1744 }
1745 
1746 static int
1747 siis_sata_connect(struct siis_channel *ch)
1748 {
1749 	u_int32_t status;
1750 	int timeout, found = 0;
1751 
1752 	/* Wait up to 100ms for "connect well" */
1753 	for (timeout = 0; timeout < 1000 ; timeout++) {
1754 		status = ATA_INL(ch->r_mem, SIIS_P_SSTS);
1755 		if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
1756 			found = 1;
1757 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1758 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1759 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
1760 			break;
1761 		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
1762 			if (bootverbose) {
1763 				device_printf(ch->dev, "SATA offline status=%08x\n",
1764 				    status);
1765 			}
1766 			return (0);
1767 		}
1768 		if (found == 0 && timeout >= 100)
1769 			break;
1770 		DELAY(100);
1771 	}
1772 	if (timeout >= 1000 || !found) {
1773 		if (bootverbose) {
1774 			device_printf(ch->dev,
1775 			    "SATA connect timeout time=%dus status=%08x\n",
1776 			    timeout * 100, status);
1777 		}
1778 		return (0);
1779 	}
1780 	if (bootverbose) {
1781 		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
1782 		    timeout * 100, status);
1783 	}
1784 	/* Clear SATA error register */
1785 	ATA_OUTL(ch->r_mem, SIIS_P_SERR, 0xffffffff);
1786 	return (1);
1787 }
1788 
1789 static int
1790 siis_check_ids(device_t dev, union ccb *ccb)
1791 {
1792 
1793 	if (ccb->ccb_h.target_id > 15) {
1794 		ccb->ccb_h.status = CAM_TID_INVALID;
1795 		xpt_done(ccb);
1796 		return (-1);
1797 	}
1798 	if (ccb->ccb_h.target_lun != 0) {
1799 		ccb->ccb_h.status = CAM_LUN_INVALID;
1800 		xpt_done(ccb);
1801 		return (-1);
1802 	}
1803 	return (0);
1804 }
1805 
1806 static void
1807 siisaction(struct cam_sim *sim, union ccb *ccb)
1808 {
1809 	device_t dev, parent;
1810 	struct siis_channel *ch;
1811 
1812 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("siisaction func_code=%x\n",
1813 	    ccb->ccb_h.func_code));
1814 
1815 	ch = (struct siis_channel *)cam_sim_softc(sim);
1816 	dev = ch->dev;
1817 	mtx_assert(&ch->mtx, MA_OWNED);
1818 	switch (ccb->ccb_h.func_code) {
1819 	/* Common cases first */
1820 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
1821 	case XPT_SCSI_IO:
1822 		if (siis_check_ids(dev, ccb))
1823 			return;
1824 		if (ch->devices == 0 ||
1825 		    (ch->pm_present == 0 &&
1826 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
1827 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
1828 			break;
1829 		}
1830 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
1831 		/* Check for command collision. */
1832 		if (siis_check_collision(dev, ccb)) {
1833 			/* Freeze command. */
1834 			ch->frozen = ccb;
1835 			/* We have only one frozen slot, so freeze simq also. */
1836 			xpt_freeze_simq(ch->sim, 1);
1837 			return;
1838 		}
1839 		siis_begin_transaction(dev, ccb);
1840 		return;
1841 	case XPT_ABORT:			/* Abort the specified CCB */
1842 		/* XXX Implement */
1843 		ccb->ccb_h.status = CAM_REQ_INVALID;
1844 		break;
1845 	case XPT_SET_TRAN_SETTINGS:
1846 	{
1847 		struct	ccb_trans_settings *cts = &ccb->cts;
1848 		struct	siis_device *d;
1849 
1850 		if (siis_check_ids(dev, ccb))
1851 			return;
1852 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1853 			d = &ch->curr[ccb->ccb_h.target_id];
1854 		else
1855 			d = &ch->user[ccb->ccb_h.target_id];
1856 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
1857 			d->revision = cts->xport_specific.sata.revision;
1858 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
1859 			d->mode = cts->xport_specific.sata.mode;
1860 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
1861 			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
1862 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
1863 			d->tags = min(SIIS_MAX_SLOTS, cts->xport_specific.sata.tags);
1864 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM) {
1865 			ch->pm_present = cts->xport_specific.sata.pm_present;
1866 			if (ch->pm_present)
1867 				ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PME);
1868 			else
1869 				ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PME);
1870 		}
1871 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
1872 			d->atapi = cts->xport_specific.sata.atapi;
1873 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
1874 			d->caps = cts->xport_specific.sata.caps;
1875 		ccb->ccb_h.status = CAM_REQ_CMP;
1876 		break;
1877 	}
1878 	case XPT_GET_TRAN_SETTINGS:
1879 	/* Get default/user set transfer settings for the target */
1880 	{
1881 		struct	ccb_trans_settings *cts = &ccb->cts;
1882 		struct  siis_device *d;
1883 		uint32_t status;
1884 
1885 		if (siis_check_ids(dev, ccb))
1886 			return;
1887 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1888 			d = &ch->curr[ccb->ccb_h.target_id];
1889 		else
1890 			d = &ch->user[ccb->ccb_h.target_id];
1891 		cts->protocol = PROTO_UNSPECIFIED;
1892 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
1893 		cts->transport = XPORT_SATA;
1894 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
1895 		cts->proto_specific.valid = 0;
1896 		cts->xport_specific.sata.valid = 0;
1897 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
1898 		    (ccb->ccb_h.target_id == 15 ||
1899 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
1900 			status = ATA_INL(ch->r_mem, SIIS_P_SSTS) & ATA_SS_SPD_MASK;
1901 			if (status & 0x0f0) {
1902 				cts->xport_specific.sata.revision =
1903 				    (status & 0x0f0) >> 4;
1904 				cts->xport_specific.sata.valid |=
1905 				    CTS_SATA_VALID_REVISION;
1906 			}
1907 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
1908 			if (ch->pm_level)
1909 				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
1910 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
1911 			cts->xport_specific.sata.caps &=
1912 			    ch->user[ccb->ccb_h.target_id].caps;
1913 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
1914 		} else {
1915 			cts->xport_specific.sata.revision = d->revision;
1916 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
1917 			cts->xport_specific.sata.caps = d->caps;
1918 			if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
1919 			    (ch->quirks & SIIS_Q_SNTF) == 0)
1920 				cts->xport_specific.sata.caps &= ~CTS_SATA_CAPS_H_AN;
1921 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
1922 		}
1923 		cts->xport_specific.sata.mode = d->mode;
1924 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
1925 		cts->xport_specific.sata.bytecount = d->bytecount;
1926 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
1927 		cts->xport_specific.sata.pm_present = ch->pm_present;
1928 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
1929 		cts->xport_specific.sata.tags = d->tags;
1930 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
1931 		cts->xport_specific.sata.atapi = d->atapi;
1932 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
1933 		ccb->ccb_h.status = CAM_REQ_CMP;
1934 		break;
1935 	}
1936 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
1937 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
1938 		siis_reset(dev);
1939 		ccb->ccb_h.status = CAM_REQ_CMP;
1940 		break;
1941 	case XPT_TERM_IO:		/* Terminate the I/O process */
1942 		/* XXX Implement */
1943 		ccb->ccb_h.status = CAM_REQ_INVALID;
1944 		break;
1945 	case XPT_PATH_INQ:		/* Path routing inquiry */
1946 	{
1947 		struct ccb_pathinq *cpi = &ccb->cpi;
1948 
1949 		parent = device_get_parent(dev);
1950 		cpi->version_num = 1; /* XXX??? */
1951 		cpi->hba_inquiry = PI_SDTR_ABLE | PI_TAG_ABLE;
1952 		cpi->hba_inquiry |= PI_SATAPM;
1953 		cpi->target_sprt = 0;
1954 		cpi->hba_misc = PIM_SEQSCAN | PIM_UNMAPPED | PIM_ATA_EXT;
1955 		cpi->hba_eng_cnt = 0;
1956 		cpi->max_target = 15;
1957 		cpi->max_lun = 0;
1958 		cpi->initiator_id = 0;
1959 		cpi->bus_id = cam_sim_bus(sim);
1960 		cpi->base_transfer_speed = 150000;
1961 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1962 		strlcpy(cpi->hba_vid, "SIIS", HBA_IDLEN);
1963 		strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1964 		cpi->unit_number = cam_sim_unit(sim);
1965 		cpi->transport = XPORT_SATA;
1966 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
1967 		cpi->protocol = PROTO_ATA;
1968 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
1969 		cpi->maxio = maxphys;
1970 		cpi->hba_vendor = pci_get_vendor(parent);
1971 		cpi->hba_device = pci_get_device(parent);
1972 		cpi->hba_subvendor = pci_get_subvendor(parent);
1973 		cpi->hba_subdevice = pci_get_subdevice(parent);
1974 		cpi->ccb_h.status = CAM_REQ_CMP;
1975 		break;
1976 	}
1977 	default:
1978 		ccb->ccb_h.status = CAM_REQ_INVALID;
1979 		break;
1980 	}
1981 	xpt_done(ccb);
1982 }
1983 
1984 static void
1985 siispoll(struct cam_sim *sim)
1986 {
1987 	struct siis_channel *ch = (struct siis_channel *)cam_sim_softc(sim);
1988 
1989 	siis_ch_intr(ch->dev);
1990 }
1991