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