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