xref: /freebsd/sys/dev/siis/siis.c (revision bb15ca603fa442c72dde3f3cb8b46db6970e3950)
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 devclass_t siis_devclass;
418 static device_method_t siis_methods[] = {
419 	DEVMETHOD(device_probe,     siis_probe),
420 	DEVMETHOD(device_attach,    siis_attach),
421 	DEVMETHOD(device_detach,    siis_detach),
422 	DEVMETHOD(device_suspend,   siis_suspend),
423 	DEVMETHOD(device_resume,    siis_resume),
424 	DEVMETHOD(bus_print_child,  siis_print_child),
425 	DEVMETHOD(bus_alloc_resource,       siis_alloc_resource),
426 	DEVMETHOD(bus_release_resource,     siis_release_resource),
427 	DEVMETHOD(bus_setup_intr,   siis_setup_intr),
428 	DEVMETHOD(bus_teardown_intr,siis_teardown_intr),
429 	DEVMETHOD(bus_child_location_str, siis_child_location_str),
430 	{ 0, 0 }
431 };
432 static driver_t siis_driver = {
433         "siis",
434         siis_methods,
435         sizeof(struct siis_controller)
436 };
437 DRIVER_MODULE(siis, pci, siis_driver, siis_devclass, 0, 0);
438 MODULE_VERSION(siis, 1);
439 MODULE_DEPEND(siis, cam, 1, 1, 1);
440 
441 static int
442 siis_ch_probe(device_t dev)
443 {
444 
445 	device_set_desc_copy(dev, "SIIS channel");
446 	return (0);
447 }
448 
449 static int
450 siis_ch_attach(device_t dev)
451 {
452 	struct siis_controller *ctlr = device_get_softc(device_get_parent(dev));
453 	struct siis_channel *ch = device_get_softc(dev);
454 	struct cam_devq *devq;
455 	int rid, error, i, sata_rev = 0;
456 
457 	ch->dev = dev;
458 	ch->unit = (intptr_t)device_get_ivars(dev);
459 	ch->quirks = ctlr->quirks;
460 	resource_int_value(device_get_name(dev),
461 	    device_get_unit(dev), "pm_level", &ch->pm_level);
462 	resource_int_value(device_get_name(dev),
463 	    device_get_unit(dev), "sata_rev", &sata_rev);
464 	for (i = 0; i < 16; i++) {
465 		ch->user[i].revision = sata_rev;
466 		ch->user[i].mode = 0;
467 		ch->user[i].bytecount = 8192;
468 		ch->user[i].tags = SIIS_MAX_SLOTS;
469 		ch->curr[i] = ch->user[i];
470 		if (ch->pm_level)
471 			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ;
472 		ch->user[i].caps |= CTS_SATA_CAPS_H_AN;
473 	}
474 	mtx_init(&ch->mtx, "SIIS channel lock", NULL, MTX_DEF);
475 	rid = ch->unit;
476 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
477 	    &rid, RF_ACTIVE)))
478 		return (ENXIO);
479 	siis_dmainit(dev);
480 	siis_slotsalloc(dev);
481 	siis_ch_init(dev);
482 	mtx_lock(&ch->mtx);
483 	rid = ATA_IRQ_RID;
484 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
485 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
486 		device_printf(dev, "Unable to map interrupt\n");
487 		error = ENXIO;
488 		goto err0;
489 	}
490 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
491 	    siis_ch_intr_locked, dev, &ch->ih))) {
492 		device_printf(dev, "Unable to setup interrupt\n");
493 		error = ENXIO;
494 		goto err1;
495 	}
496 	/* Create the device queue for our SIM. */
497 	devq = cam_simq_alloc(SIIS_MAX_SLOTS);
498 	if (devq == NULL) {
499 		device_printf(dev, "Unable to allocate simq\n");
500 		error = ENOMEM;
501 		goto err1;
502 	}
503 	/* Construct SIM entry */
504 	ch->sim = cam_sim_alloc(siisaction, siispoll, "siisch", ch,
505 	    device_get_unit(dev), &ch->mtx, 2, SIIS_MAX_SLOTS, devq);
506 	if (ch->sim == NULL) {
507 		cam_simq_free(devq);
508 		device_printf(dev, "unable to allocate sim\n");
509 		error = ENOMEM;
510 		goto err1;
511 	}
512 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
513 		device_printf(dev, "unable to register xpt bus\n");
514 		error = ENXIO;
515 		goto err2;
516 	}
517 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
518 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
519 		device_printf(dev, "unable to create path\n");
520 		error = ENXIO;
521 		goto err3;
522 	}
523 	mtx_unlock(&ch->mtx);
524 	ch->led = led_create(siis_ch_led, dev, device_get_nameunit(dev));
525 	return (0);
526 
527 err3:
528 	xpt_bus_deregister(cam_sim_path(ch->sim));
529 err2:
530 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
531 err1:
532 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
533 err0:
534 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
535 	mtx_unlock(&ch->mtx);
536 	mtx_destroy(&ch->mtx);
537 	return (error);
538 }
539 
540 static int
541 siis_ch_detach(device_t dev)
542 {
543 	struct siis_channel *ch = device_get_softc(dev);
544 
545 	led_destroy(ch->led);
546 	mtx_lock(&ch->mtx);
547 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
548 	xpt_free_path(ch->path);
549 	xpt_bus_deregister(cam_sim_path(ch->sim));
550 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
551 	mtx_unlock(&ch->mtx);
552 
553 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
554 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
555 
556 	siis_ch_deinit(dev);
557 	siis_slotsfree(dev);
558 	siis_dmafini(dev);
559 
560 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
561 	mtx_destroy(&ch->mtx);
562 	return (0);
563 }
564 
565 static int
566 siis_ch_init(device_t dev)
567 {
568 	struct siis_channel *ch = device_get_softc(dev);
569 
570 	/* Get port out of reset state. */
571 	ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PORT_RESET);
572 	ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_32BIT);
573 	if (ch->pm_present)
574 		ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PME);
575 	else
576 		ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PME);
577 	/* Enable port interrupts */
578 	ATA_OUTL(ch->r_mem, SIIS_P_IESET, SIIS_P_IX_ENABLED);
579 	return (0);
580 }
581 
582 static int
583 siis_ch_deinit(device_t dev)
584 {
585 	struct siis_channel *ch = device_get_softc(dev);
586 
587 	/* Put port into reset state. */
588 	ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PORT_RESET);
589 	return (0);
590 }
591 
592 static int
593 siis_ch_suspend(device_t dev)
594 {
595 	struct siis_channel *ch = device_get_softc(dev);
596 
597 	mtx_lock(&ch->mtx);
598 	xpt_freeze_simq(ch->sim, 1);
599 	while (ch->oslots)
600 		msleep(ch, &ch->mtx, PRIBIO, "siissusp", hz/100);
601 	siis_ch_deinit(dev);
602 	mtx_unlock(&ch->mtx);
603 	return (0);
604 }
605 
606 static int
607 siis_ch_resume(device_t dev)
608 {
609 	struct siis_channel *ch = device_get_softc(dev);
610 
611 	mtx_lock(&ch->mtx);
612 	siis_ch_init(dev);
613 	siis_reset(dev);
614 	xpt_release_simq(ch->sim, TRUE);
615 	mtx_unlock(&ch->mtx);
616 	return (0);
617 }
618 
619 devclass_t siisch_devclass;
620 static device_method_t siisch_methods[] = {
621 	DEVMETHOD(device_probe,     siis_ch_probe),
622 	DEVMETHOD(device_attach,    siis_ch_attach),
623 	DEVMETHOD(device_detach,    siis_ch_detach),
624 	DEVMETHOD(device_suspend,   siis_ch_suspend),
625 	DEVMETHOD(device_resume,    siis_ch_resume),
626 	{ 0, 0 }
627 };
628 static driver_t siisch_driver = {
629         "siisch",
630         siisch_methods,
631         sizeof(struct siis_channel)
632 };
633 DRIVER_MODULE(siisch, siis, siisch_driver, siis_devclass, 0, 0);
634 
635 static void
636 siis_ch_led(void *priv, int onoff)
637 {
638 	device_t dev;
639 	struct siis_channel *ch;
640 
641 	dev = (device_t)priv;
642 	ch = device_get_softc(dev);
643 
644 	if (onoff == 0)
645 		ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_LED_ON);
646 	else
647 		ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_LED_ON);
648 }
649 
650 struct siis_dc_cb_args {
651 	bus_addr_t maddr;
652 	int error;
653 };
654 
655 static void
656 siis_dmainit(device_t dev)
657 {
658 	struct siis_channel *ch = device_get_softc(dev);
659 	struct siis_dc_cb_args dcba;
660 
661 	/* Command area. */
662 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
663 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
664 	    NULL, NULL, SIIS_WORK_SIZE, 1, SIIS_WORK_SIZE,
665 	    0, NULL, NULL, &ch->dma.work_tag))
666 		goto error;
667 	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
668 	    &ch->dma.work_map))
669 		goto error;
670 	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
671 	    SIIS_WORK_SIZE, siis_dmasetupc_cb, &dcba, 0) || dcba.error) {
672 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
673 		goto error;
674 	}
675 	ch->dma.work_bus = dcba.maddr;
676 	/* Data area. */
677 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
678 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
679 	    NULL, NULL,
680 	    SIIS_SG_ENTRIES * PAGE_SIZE * SIIS_MAX_SLOTS,
681 	    SIIS_SG_ENTRIES, 0xFFFFFFFF,
682 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
683 		goto error;
684 	}
685 	return;
686 
687 error:
688 	device_printf(dev, "WARNING - DMA initialization failed\n");
689 	siis_dmafini(dev);
690 }
691 
692 static void
693 siis_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
694 {
695 	struct siis_dc_cb_args *dcba = (struct siis_dc_cb_args *)xsc;
696 
697 	if (!(dcba->error = error))
698 		dcba->maddr = segs[0].ds_addr;
699 }
700 
701 static void
702 siis_dmafini(device_t dev)
703 {
704 	struct siis_channel *ch = device_get_softc(dev);
705 
706 	if (ch->dma.data_tag) {
707 		bus_dma_tag_destroy(ch->dma.data_tag);
708 		ch->dma.data_tag = NULL;
709 	}
710 	if (ch->dma.work_bus) {
711 		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
712 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
713 		ch->dma.work_bus = 0;
714 		ch->dma.work_map = NULL;
715 		ch->dma.work = NULL;
716 	}
717 	if (ch->dma.work_tag) {
718 		bus_dma_tag_destroy(ch->dma.work_tag);
719 		ch->dma.work_tag = NULL;
720 	}
721 }
722 
723 static void
724 siis_slotsalloc(device_t dev)
725 {
726 	struct siis_channel *ch = device_get_softc(dev);
727 	int i;
728 
729 	/* Alloc and setup command/dma slots */
730 	bzero(ch->slot, sizeof(ch->slot));
731 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
732 		struct siis_slot *slot = &ch->slot[i];
733 
734 		slot->dev = dev;
735 		slot->slot = i;
736 		slot->state = SIIS_SLOT_EMPTY;
737 		slot->ccb = NULL;
738 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
739 
740 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
741 			device_printf(ch->dev, "FAILURE - create data_map\n");
742 	}
743 }
744 
745 static void
746 siis_slotsfree(device_t dev)
747 {
748 	struct siis_channel *ch = device_get_softc(dev);
749 	int i;
750 
751 	/* Free all dma slots */
752 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
753 		struct siis_slot *slot = &ch->slot[i];
754 
755 		callout_drain(&slot->timeout);
756 		if (slot->dma.data_map) {
757 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
758 			slot->dma.data_map = NULL;
759 		}
760 	}
761 }
762 
763 static void
764 siis_notify_events(device_t dev)
765 {
766 	struct siis_channel *ch = device_get_softc(dev);
767 	struct cam_path *dpath;
768 	u_int32_t status;
769 	int i;
770 
771 	if (ch->quirks & SIIS_Q_SNTF) {
772 		status = ATA_INL(ch->r_mem, SIIS_P_SNTF);
773 		ATA_OUTL(ch->r_mem, SIIS_P_SNTF, status);
774 	} else {
775 		/*
776 		 * Without SNTF we have no idea which device sent notification.
777 		 * If PMP is connected, assume it, else - device.
778 		 */
779 		status = (ch->pm_present) ? 0x8000 : 0x0001;
780 	}
781 	if (bootverbose)
782 		device_printf(dev, "SNTF 0x%04x\n", status);
783 	for (i = 0; i < 16; i++) {
784 		if ((status & (1 << i)) == 0)
785 			continue;
786 		if (xpt_create_path(&dpath, NULL,
787 		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
788 			xpt_async(AC_SCSI_AEN, dpath, NULL);
789 			xpt_free_path(dpath);
790 		}
791 	}
792 
793 }
794 
795 static void
796 siis_phy_check_events(device_t dev)
797 {
798 	struct siis_channel *ch = device_get_softc(dev);
799 
800 	/* If we have a connection event, deal with it */
801 	if (ch->pm_level == 0) {
802 		u_int32_t status = ATA_INL(ch->r_mem, SIIS_P_SSTS);
803 		union ccb *ccb;
804 
805 		if (bootverbose) {
806 			if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
807 			    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
808 			    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
809 				device_printf(dev, "CONNECT requested\n");
810 			} else
811 				device_printf(dev, "DISCONNECT requested\n");
812 		}
813 		siis_reset(dev);
814 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
815 			return;
816 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
817 		    cam_sim_path(ch->sim),
818 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
819 			xpt_free_ccb(ccb);
820 			return;
821 		}
822 		xpt_rescan(ccb);
823 	}
824 }
825 
826 static void
827 siis_ch_intr_locked(void *data)
828 {
829 	device_t dev = (device_t)data;
830 	struct siis_channel *ch = device_get_softc(dev);
831 
832 	mtx_lock(&ch->mtx);
833 	siis_ch_intr(data);
834 	mtx_unlock(&ch->mtx);
835 }
836 
837 static void
838 siis_ch_intr(void *data)
839 {
840 	device_t dev = (device_t)data;
841 	struct siis_channel *ch = device_get_softc(dev);
842 	uint32_t istatus, sstatus, ctx, estatus, ok, err = 0;
843 	enum siis_err_type et;
844 	int i, ccs, port, tslots;
845 
846 	mtx_assert(&ch->mtx, MA_OWNED);
847 	/* Read command statuses. */
848 	sstatus = ATA_INL(ch->r_mem, SIIS_P_SS);
849 	ok = ch->rslots & ~sstatus;
850 	/* Complete all successfull commands. */
851 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
852 		if ((ok >> i) & 1)
853 			siis_end_transaction(&ch->slot[i], SIIS_ERR_NONE);
854 	}
855 	/* Do we have any other events? */
856 	if ((sstatus & SIIS_P_SS_ATTN) == 0)
857 		return;
858 	/* Read and clear interrupt statuses. */
859 	istatus = ATA_INL(ch->r_mem, SIIS_P_IS) &
860 	    (0xFFFF & ~SIIS_P_IX_COMMCOMP);
861 	ATA_OUTL(ch->r_mem, SIIS_P_IS, istatus);
862 	/* Process PHY events */
863 	if (istatus & SIIS_P_IX_PHYRDYCHG)
864 		siis_phy_check_events(dev);
865 	/* Process NOTIFY events */
866 	if (istatus & SIIS_P_IX_SDBN)
867 		siis_notify_events(dev);
868 	/* Process command errors */
869 	if (istatus & SIIS_P_IX_COMMERR) {
870 		estatus = ATA_INL(ch->r_mem, SIIS_P_CMDERR);
871 		ctx = ATA_INL(ch->r_mem, SIIS_P_CTX);
872 		ccs = (ctx & SIIS_P_CTX_SLOT) >> SIIS_P_CTX_SLOT_SHIFT;
873 		port = (ctx & SIIS_P_CTX_PMP) >> SIIS_P_CTX_PMP_SHIFT;
874 		err = ch->rslots & sstatus;
875 //device_printf(dev, "%s ERROR ss %08x is %08x rs %08x es %d act %d port %d serr %08x\n",
876 //    __func__, sstatus, istatus, ch->rslots, estatus, ccs, port,
877 //    ATA_INL(ch->r_mem, SIIS_P_SERR));
878 
879 		if (!ch->recoverycmd && !ch->recovery) {
880 			xpt_freeze_simq(ch->sim, ch->numrslots);
881 			ch->recovery = 1;
882 		}
883 		if (ch->frozen) {
884 			union ccb *fccb = ch->frozen;
885 			ch->frozen = NULL;
886 			fccb->ccb_h.status &= ~CAM_STATUS_MASK;
887 			fccb->ccb_h.status |= CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
888 			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
889 				xpt_freeze_devq(fccb->ccb_h.path, 1);
890 				fccb->ccb_h.status |= CAM_DEV_QFRZN;
891 			}
892 			xpt_done(fccb);
893 		}
894 		if (estatus == SIIS_P_CMDERR_DEV ||
895 		    estatus == SIIS_P_CMDERR_SDB ||
896 		    estatus == SIIS_P_CMDERR_DATAFIS) {
897 			tslots = ch->numtslots[port];
898 			for (i = 0; i < SIIS_MAX_SLOTS; i++) {
899 				/* XXX: requests in loading state. */
900 				if (((ch->rslots >> i) & 1) == 0)
901 					continue;
902 				if (ch->slot[i].ccb->ccb_h.target_id != port)
903 					continue;
904 				if (tslots == 0) {
905 					/* Untagged operation. */
906 					if (i == ccs)
907 						et = SIIS_ERR_TFE;
908 					else
909 						et = SIIS_ERR_INNOCENT;
910 				} else {
911 					/* Tagged operation. */
912 					et = SIIS_ERR_NCQ;
913 				}
914 				siis_end_transaction(&ch->slot[i], et);
915 			}
916 			/*
917 			 * We can't reinit port if there are some other
918 			 * commands active, use resume to complete them.
919 			 */
920 			if (ch->rslots != 0 && !ch->recoverycmd)
921 				ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_RESUME);
922 		} else {
923 			if (estatus == SIIS_P_CMDERR_SENDFIS ||
924 			    estatus == SIIS_P_CMDERR_INCSTATE ||
925 			    estatus == SIIS_P_CMDERR_PPE ||
926 			    estatus == SIIS_P_CMDERR_SERVICE) {
927 				et = SIIS_ERR_SATA;
928 			} else
929 				et = SIIS_ERR_INVALID;
930 			for (i = 0; i < SIIS_MAX_SLOTS; i++) {
931 				/* XXX: requests in loading state. */
932 				if (((ch->rslots >> i) & 1) == 0)
933 					continue;
934 				siis_end_transaction(&ch->slot[i], et);
935 			}
936 		}
937 	}
938 }
939 
940 /* Must be called with channel locked. */
941 static int
942 siis_check_collision(device_t dev, union ccb *ccb)
943 {
944 	struct siis_channel *ch = device_get_softc(dev);
945 
946 	mtx_assert(&ch->mtx, MA_OWNED);
947 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
948 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
949 		/* Tagged command while we have no supported tag free. */
950 		if (((~ch->oslots) & (0x7fffffff >> (31 -
951 		    ch->curr[ccb->ccb_h.target_id].tags))) == 0)
952 			return (1);
953 	}
954 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
955 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
956 		/* Atomic command while anything active. */
957 		if (ch->numrslots != 0)
958 			return (1);
959 	}
960        /* We have some atomic command running. */
961        if (ch->aslots != 0)
962                return (1);
963 	return (0);
964 }
965 
966 /* Must be called with channel locked. */
967 static void
968 siis_begin_transaction(device_t dev, union ccb *ccb)
969 {
970 	struct siis_channel *ch = device_get_softc(dev);
971 	struct siis_slot *slot;
972 	int tag, tags;
973 
974 	mtx_assert(&ch->mtx, MA_OWNED);
975 	/* Choose empty slot. */
976 	tags = SIIS_MAX_SLOTS;
977 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
978 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
979 		tags = ch->curr[ccb->ccb_h.target_id].tags;
980 	tag = fls((~ch->oslots) & (0x7fffffff >> (31 - tags))) - 1;
981 	/* Occupy chosen slot. */
982 	slot = &ch->slot[tag];
983 	slot->ccb = ccb;
984 	/* Update channel stats. */
985 	ch->oslots |= (1 << slot->slot);
986 	ch->numrslots++;
987 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
988 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
989 		ch->numtslots[ccb->ccb_h.target_id]++;
990 	}
991 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
992 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
993 		ch->aslots |= (1 << slot->slot);
994 	slot->dma.nsegs = 0;
995 	/* If request moves data, setup and load SG list */
996 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
997 		void *buf;
998 		bus_size_t size;
999 
1000 		slot->state = SIIS_SLOT_LOADING;
1001 		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1002 			buf = ccb->ataio.data_ptr;
1003 			size = ccb->ataio.dxfer_len;
1004 		} else {
1005 			buf = ccb->csio.data_ptr;
1006 			size = ccb->csio.dxfer_len;
1007 		}
1008 		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1009 		    buf, size, 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 	/* Get a piece of the workspace for this request */
1034 	ctp = (struct siis_cmd *)
1035 		(ch->dma.work + SIIS_CT_OFFSET + (SIIS_CT_SIZE * slot->slot));
1036 	/* Fill S/G table */
1037 	if (slot->ccb->ccb_h.func_code == XPT_ATA_IO)
1038 		prd = &ctp->u.ata.prd[0];
1039 	else
1040 		prd = &ctp->u.atapi.prd[0];
1041 	for (i = 0; i < nsegs; i++) {
1042 		prd[i].dba = htole64(segs[i].ds_addr);
1043 		prd[i].dbc = htole32(segs[i].ds_len);
1044 		prd[i].control = 0;
1045 	}
1046 	prd[nsegs - 1].control = htole32(SIIS_PRD_TRM);
1047 	slot->dma.nsegs = nsegs;
1048 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1049 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1050 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1051 	siis_execute_transaction(slot);
1052 }
1053 
1054 /* Must be called with channel locked. */
1055 static void
1056 siis_execute_transaction(struct siis_slot *slot)
1057 {
1058 	device_t dev = slot->dev;
1059 	struct siis_channel *ch = device_get_softc(dev);
1060 	struct siis_cmd *ctp;
1061 	union ccb *ccb = slot->ccb;
1062 	u_int64_t prb_bus;
1063 
1064 	mtx_assert(&ch->mtx, MA_OWNED);
1065 	/* Get a piece of the workspace for this request */
1066 	ctp = (struct siis_cmd *)
1067 		(ch->dma.work + SIIS_CT_OFFSET + (SIIS_CT_SIZE * slot->slot));
1068 	ctp->control = 0;
1069 	ctp->protocol_override = 0;
1070 	ctp->transfer_count = 0;
1071 	/* Special handling for Soft Reset command. */
1072 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1073 		if (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) {
1074 			ctp->control |= htole16(SIIS_PRB_SOFT_RESET);
1075 		} else {
1076 			ctp->control |= htole16(SIIS_PRB_PROTOCOL_OVERRIDE);
1077 			if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1078 				ctp->protocol_override |=
1079 				    htole16(SIIS_PRB_PROTO_NCQ);
1080 			}
1081 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1082 				ctp->protocol_override |=
1083 				    htole16(SIIS_PRB_PROTO_READ);
1084 			} else
1085 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1086 				ctp->protocol_override |=
1087 				    htole16(SIIS_PRB_PROTO_WRITE);
1088 			}
1089 		}
1090 	} else if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1091 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1092 			ctp->control |= htole16(SIIS_PRB_PACKET_READ);
1093 		else
1094 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT)
1095 			ctp->control |= htole16(SIIS_PRB_PACKET_WRITE);
1096 	}
1097 	/* Special handling for Soft Reset command. */
1098 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1099 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1100 	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1101 		/* Kick controller into sane state */
1102 		siis_portinit(dev);
1103 	}
1104 	/* Setup the FIS for this request */
1105 	if (!siis_setup_fis(dev, ctp, ccb, slot->slot)) {
1106 		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1107 		if (!ch->recoverycmd)
1108 			xpt_freeze_simq(ch->sim, 1);
1109 		siis_end_transaction(slot, SIIS_ERR_INVALID);
1110 		return;
1111 	}
1112 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1113 	    BUS_DMASYNC_PREWRITE);
1114 	/* Issue command to the controller. */
1115 	slot->state = SIIS_SLOT_RUNNING;
1116 	ch->rslots |= (1 << slot->slot);
1117 	prb_bus = ch->dma.work_bus +
1118 	      SIIS_CT_OFFSET + (SIIS_CT_SIZE * slot->slot);
1119 	ATA_OUTL(ch->r_mem, SIIS_P_CACTL(slot->slot), prb_bus);
1120 	ATA_OUTL(ch->r_mem, SIIS_P_CACTH(slot->slot), prb_bus >> 32);
1121 	/* Start command execution timeout */
1122 	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 1000,
1123 	    (timeout_t*)siis_timeout, slot);
1124 	return;
1125 }
1126 
1127 /* Must be called with channel locked. */
1128 static void
1129 siis_process_timeout(device_t dev)
1130 {
1131 	struct siis_channel *ch = device_get_softc(dev);
1132 	int i;
1133 
1134 	mtx_assert(&ch->mtx, MA_OWNED);
1135 	if (!ch->recoverycmd && !ch->recovery) {
1136 		xpt_freeze_simq(ch->sim, ch->numrslots);
1137 		ch->recovery = 1;
1138 	}
1139 	/* Handle the rest of commands. */
1140 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1141 		/* Do we have a running request on slot? */
1142 		if (ch->slot[i].state < SIIS_SLOT_RUNNING)
1143 			continue;
1144 		siis_end_transaction(&ch->slot[i], SIIS_ERR_TIMEOUT);
1145 	}
1146 }
1147 
1148 /* Must be called with channel locked. */
1149 static void
1150 siis_rearm_timeout(device_t dev)
1151 {
1152 	struct siis_channel *ch = device_get_softc(dev);
1153 	int i;
1154 
1155 	mtx_assert(&ch->mtx, MA_OWNED);
1156 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1157 		struct siis_slot *slot = &ch->slot[i];
1158 
1159 		/* Do we have a running request on slot? */
1160 		if (slot->state < SIIS_SLOT_RUNNING)
1161 			continue;
1162 		if ((ch->toslots & (1 << i)) == 0)
1163 			continue;
1164 		callout_reset(&slot->timeout,
1165 		    (int)slot->ccb->ccb_h.timeout * hz / 1000,
1166 		    (timeout_t*)siis_timeout, slot);
1167 	}
1168 }
1169 
1170 /* Locked by callout mechanism. */
1171 static void
1172 siis_timeout(struct siis_slot *slot)
1173 {
1174 	device_t dev = slot->dev;
1175 	struct siis_channel *ch = device_get_softc(dev);
1176 	union ccb *ccb = slot->ccb;
1177 
1178 	mtx_assert(&ch->mtx, MA_OWNED);
1179 	/* Check for stale timeout. */
1180 	if (slot->state < SIIS_SLOT_RUNNING)
1181 		return;
1182 
1183 	/* Handle soft-reset timeouts without doing hard-reset. */
1184 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1185 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1186 	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1187 		xpt_freeze_simq(ch->sim, ch->numrslots);
1188 		siis_end_transaction(slot, SIIS_ERR_TFE);
1189 		return;
1190 	}
1191 
1192 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1193 	device_printf(dev, "%s is %08x ss %08x rs %08x es %08x sts %08x serr %08x\n",
1194 	    __func__, ATA_INL(ch->r_mem, SIIS_P_IS),
1195 	    ATA_INL(ch->r_mem, SIIS_P_SS), ch->rslots,
1196 	    ATA_INL(ch->r_mem, SIIS_P_CMDERR), ATA_INL(ch->r_mem, SIIS_P_STS),
1197 	    ATA_INL(ch->r_mem, SIIS_P_SERR));
1198 
1199 	if (ch->toslots == 0)
1200 		xpt_freeze_simq(ch->sim, 1);
1201 	ch->toslots |= (1 << slot->slot);
1202 	if ((ch->rslots & ~ch->toslots) == 0)
1203 		siis_process_timeout(dev);
1204 	else
1205 		device_printf(dev, " ... waiting for slots %08x\n",
1206 		    ch->rslots & ~ch->toslots);
1207 }
1208 
1209 /* Must be called with channel locked. */
1210 static void
1211 siis_end_transaction(struct siis_slot *slot, enum siis_err_type et)
1212 {
1213 	device_t dev = slot->dev;
1214 	struct siis_channel *ch = device_get_softc(dev);
1215 	union ccb *ccb = slot->ccb;
1216 	int lastto;
1217 
1218 	mtx_assert(&ch->mtx, MA_OWNED);
1219 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1220 	    BUS_DMASYNC_POSTWRITE);
1221 	/* Read result registers to the result struct
1222 	 * May be incorrect if several commands finished same time,
1223 	 * so read only when sure or have to.
1224 	 */
1225 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1226 		struct ata_res *res = &ccb->ataio.res;
1227 		if ((et == SIIS_ERR_TFE) ||
1228 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1229 			int offs = SIIS_P_LRAM_SLOT(slot->slot) + 8;
1230 
1231 			res->status = ATA_INB(ch->r_mem, offs + 2);
1232 			res->error = ATA_INB(ch->r_mem, offs + 3);
1233 			res->lba_low = ATA_INB(ch->r_mem, offs + 4);
1234 			res->lba_mid = ATA_INB(ch->r_mem, offs + 5);
1235 			res->lba_high = ATA_INB(ch->r_mem, offs + 6);
1236 			res->device = ATA_INB(ch->r_mem, offs + 7);
1237 			res->lba_low_exp = ATA_INB(ch->r_mem, offs + 8);
1238 			res->lba_mid_exp = ATA_INB(ch->r_mem, offs + 9);
1239 			res->lba_high_exp = ATA_INB(ch->r_mem, offs + 10);
1240 			res->sector_count = ATA_INB(ch->r_mem, offs + 12);
1241 			res->sector_count_exp = ATA_INB(ch->r_mem, offs + 13);
1242 		} else
1243 			bzero(res, sizeof(*res));
1244 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
1245 		    ch->numrslots == 1) {
1246 			ccb->ataio.resid = ccb->ataio.dxfer_len -
1247 			    ATA_INL(ch->r_mem, SIIS_P_LRAM_SLOT(slot->slot) + 4);
1248 		}
1249 	} else {
1250 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
1251 		    ch->numrslots == 1) {
1252 			ccb->csio.resid = ccb->csio.dxfer_len -
1253 			    ATA_INL(ch->r_mem, SIIS_P_LRAM_SLOT(slot->slot) + 4);
1254 		}
1255 	}
1256 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1257 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1258 		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1259 		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1260 		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1261 	}
1262 	/* Set proper result status. */
1263 	if (et != SIIS_ERR_NONE || ch->recovery) {
1264 		ch->eslots |= (1 << slot->slot);
1265 		ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1266 	}
1267 	/* In case of error, freeze device for proper recovery. */
1268 	if (et != SIIS_ERR_NONE && (!ch->recoverycmd) &&
1269 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1270 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1271 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1272 	}
1273 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1274 	switch (et) {
1275 	case SIIS_ERR_NONE:
1276 		ccb->ccb_h.status |= CAM_REQ_CMP;
1277 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1278 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1279 		break;
1280 	case SIIS_ERR_INVALID:
1281 		ch->fatalerr = 1;
1282 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1283 		break;
1284 	case SIIS_ERR_INNOCENT:
1285 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1286 		break;
1287 	case SIIS_ERR_TFE:
1288 	case SIIS_ERR_NCQ:
1289 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1290 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1291 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1292 		} else {
1293 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1294 		}
1295 		break;
1296 	case SIIS_ERR_SATA:
1297 		ch->fatalerr = 1;
1298 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1299 		break;
1300 	case SIIS_ERR_TIMEOUT:
1301 		ch->fatalerr = 1;
1302 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1303 		break;
1304 	default:
1305 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1306 	}
1307 	/* Free slot. */
1308 	ch->oslots &= ~(1 << slot->slot);
1309 	ch->rslots &= ~(1 << slot->slot);
1310 	ch->aslots &= ~(1 << slot->slot);
1311 	slot->state = SIIS_SLOT_EMPTY;
1312 	slot->ccb = NULL;
1313 	/* Update channel stats. */
1314 	ch->numrslots--;
1315 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1316 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1317 		ch->numtslots[ccb->ccb_h.target_id]--;
1318 	}
1319 	/* Cancel timeout state if request completed normally. */
1320 	if (et != SIIS_ERR_TIMEOUT) {
1321 		lastto = (ch->toslots == (1 << slot->slot));
1322 		ch->toslots &= ~(1 << slot->slot);
1323 		if (lastto)
1324 			xpt_release_simq(ch->sim, TRUE);
1325 	}
1326 	/* If it was our READ LOG command - process it. */
1327 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1328 		siis_process_read_log(dev, ccb);
1329 	/* If it was our REQUEST SENSE command - process it. */
1330 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1331 		siis_process_request_sense(dev, ccb);
1332 	/* If it was NCQ or ATAPI command error, put result on hold. */
1333 	} else if (et == SIIS_ERR_NCQ ||
1334 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1335 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1336 		ch->hold[slot->slot] = ccb;
1337 		ch->numhslots++;
1338 	} else
1339 		xpt_done(ccb);
1340 	/* If we have no other active commands, ... */
1341 	if (ch->rslots == 0) {
1342 		/* if there were timeouts or fatal error - reset port. */
1343 		if (ch->toslots != 0 || ch->fatalerr) {
1344 			siis_reset(dev);
1345 		} else {
1346 			/* if we have slots in error, we can reinit port. */
1347 			if (ch->eslots != 0)
1348 				siis_portinit(dev);
1349 			/* if there commands on hold, we can do recovery. */
1350 			if (!ch->recoverycmd && ch->numhslots)
1351 				siis_issue_recovery(dev);
1352 		}
1353 	/* If all the reset of commands are in timeout - abort them. */
1354 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1355 	    et != SIIS_ERR_TIMEOUT)
1356 		siis_rearm_timeout(dev);
1357 	/* Unfreeze frozen command. */
1358 	if (ch->frozen && !siis_check_collision(dev, ch->frozen)) {
1359 		union ccb *fccb = ch->frozen;
1360 		ch->frozen = NULL;
1361 		siis_begin_transaction(dev, fccb);
1362 		xpt_release_simq(ch->sim, TRUE);
1363 	}
1364 }
1365 
1366 static void
1367 siis_issue_recovery(device_t dev)
1368 {
1369 	struct siis_channel *ch = device_get_softc(dev);
1370 	union ccb *ccb;
1371 	struct ccb_ataio *ataio;
1372 	struct ccb_scsiio *csio;
1373 	int i;
1374 
1375 	/* Find some held command. */
1376 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1377 		if (ch->hold[i])
1378 			break;
1379 	}
1380 	if (i == SIIS_MAX_SLOTS)
1381 		return;
1382 	ccb = xpt_alloc_ccb_nowait();
1383 	if (ccb == NULL) {
1384 		device_printf(dev, "Unable to allocate recovery command\n");
1385 completeall:
1386 		/* We can't do anything -- complete held commands. */
1387 		for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1388 			if (ch->hold[i] == NULL)
1389 				continue;
1390 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1391 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1392 			xpt_done(ch->hold[i]);
1393 			ch->hold[i] = NULL;
1394 			ch->numhslots--;
1395 		}
1396 		siis_reset(dev);
1397 		return;
1398 	}
1399 	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1400 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1401 		/* READ LOG */
1402 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1403 		ccb->ccb_h.func_code = XPT_ATA_IO;
1404 		ccb->ccb_h.flags = CAM_DIR_IN;
1405 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1406 		ataio = &ccb->ataio;
1407 		ataio->data_ptr = malloc(512, M_SIIS, M_NOWAIT);
1408 		if (ataio->data_ptr == NULL) {
1409 			xpt_free_ccb(ccb);
1410 			device_printf(dev,
1411 			    "Unable to allocate memory for READ LOG command\n");
1412 			goto completeall;
1413 		}
1414 		ataio->dxfer_len = 512;
1415 		bzero(&ataio->cmd, sizeof(ataio->cmd));
1416 		ataio->cmd.flags = CAM_ATAIO_48BIT;
1417 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1418 		ataio->cmd.sector_count = 1;
1419 		ataio->cmd.sector_count_exp = 0;
1420 		ataio->cmd.lba_low = 0x10;
1421 		ataio->cmd.lba_mid = 0;
1422 		ataio->cmd.lba_mid_exp = 0;
1423 	} else {
1424 		/* REQUEST SENSE */
1425 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1426 		ccb->ccb_h.recovery_slot = i;
1427 		ccb->ccb_h.func_code = XPT_SCSI_IO;
1428 		ccb->ccb_h.flags = CAM_DIR_IN;
1429 		ccb->ccb_h.status = 0;
1430 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1431 		csio = &ccb->csio;
1432 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1433 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1434 		csio->cdb_len = 6;
1435 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1436 		csio->cdb_io.cdb_bytes[0] = 0x03;
1437 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1438 	}
1439 	ch->recoverycmd = 1;
1440 	siis_begin_transaction(dev, ccb);
1441 }
1442 
1443 static void
1444 siis_process_read_log(device_t dev, union ccb *ccb)
1445 {
1446 	struct siis_channel *ch = device_get_softc(dev);
1447 	uint8_t *data;
1448 	struct ata_res *res;
1449 	int i;
1450 
1451 	ch->recoverycmd = 0;
1452 	data = ccb->ataio.data_ptr;
1453 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1454 	    (data[0] & 0x80) == 0) {
1455 		for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1456 			if (!ch->hold[i])
1457 				continue;
1458 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1459 				continue;
1460 			if ((data[0] & 0x1F) == i) {
1461 				res = &ch->hold[i]->ataio.res;
1462 				res->status = data[2];
1463 				res->error = data[3];
1464 				res->lba_low = data[4];
1465 				res->lba_mid = data[5];
1466 				res->lba_high = data[6];
1467 				res->device = data[7];
1468 				res->lba_low_exp = data[8];
1469 				res->lba_mid_exp = data[9];
1470 				res->lba_high_exp = data[10];
1471 				res->sector_count = data[12];
1472 				res->sector_count_exp = data[13];
1473 			} else {
1474 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1475 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1476 			}
1477 			xpt_done(ch->hold[i]);
1478 			ch->hold[i] = NULL;
1479 			ch->numhslots--;
1480 		}
1481 	} else {
1482 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1483 			device_printf(dev, "Error while READ LOG EXT\n");
1484 		else if ((data[0] & 0x80) == 0) {
1485 			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1486 		}
1487 		for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1488 			if (!ch->hold[i])
1489 				continue;
1490 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1491 				continue;
1492 			xpt_done(ch->hold[i]);
1493 			ch->hold[i] = NULL;
1494 			ch->numhslots--;
1495 		}
1496 	}
1497 	free(ccb->ataio.data_ptr, M_SIIS);
1498 	xpt_free_ccb(ccb);
1499 }
1500 
1501 static void
1502 siis_process_request_sense(device_t dev, union ccb *ccb)
1503 {
1504 	struct siis_channel *ch = device_get_softc(dev);
1505 	int i;
1506 
1507 	ch->recoverycmd = 0;
1508 
1509 	i = ccb->ccb_h.recovery_slot;
1510 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1511 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
1512 	} else {
1513 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1514 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
1515 	}
1516 	xpt_done(ch->hold[i]);
1517 	ch->hold[i] = NULL;
1518 	ch->numhslots--;
1519 	xpt_free_ccb(ccb);
1520 }
1521 
1522 static void
1523 siis_portinit(device_t dev)
1524 {
1525 	struct siis_channel *ch = device_get_softc(dev);
1526 	int i;
1527 
1528 	ch->eslots = 0;
1529 	ch->recovery = 0;
1530 	ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_RESUME);
1531 	for (i = 0; i < 16; i++) {
1532 		ATA_OUTL(ch->r_mem, SIIS_P_PMPSTS(i), 0),
1533 		ATA_OUTL(ch->r_mem, SIIS_P_PMPQACT(i), 0);
1534 	}
1535 	ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PORT_INIT);
1536 	siis_wait_ready(dev, 1000);
1537 }
1538 
1539 static int
1540 siis_devreset(device_t dev)
1541 {
1542 	struct siis_channel *ch = device_get_softc(dev);
1543 	int timeout = 0;
1544 	uint32_t val;
1545 
1546 	ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_DEV_RESET);
1547 	while (((val = ATA_INL(ch->r_mem, SIIS_P_STS)) &
1548 	    SIIS_P_CTL_DEV_RESET) != 0) {
1549 		DELAY(100);
1550 		if (timeout++ > 1000) {
1551 			device_printf(dev, "device reset stuck "
1552 			    "(timeout 100ms) status = %08x\n", val);
1553 			return (EBUSY);
1554 		}
1555 	}
1556 	return (0);
1557 }
1558 
1559 static int
1560 siis_wait_ready(device_t dev, int t)
1561 {
1562 	struct siis_channel *ch = device_get_softc(dev);
1563 	int timeout = 0;
1564 	uint32_t val;
1565 
1566 	while (((val = ATA_INL(ch->r_mem, SIIS_P_STS)) &
1567 	    SIIS_P_CTL_READY) == 0) {
1568 		DELAY(1000);
1569 		if (timeout++ > t) {
1570 			device_printf(dev, "port is not ready (timeout %dms) "
1571 			    "status = %08x\n", t, val);
1572 			return (EBUSY);
1573 		}
1574 	}
1575 	return (0);
1576 }
1577 
1578 static void
1579 siis_reset(device_t dev)
1580 {
1581 	struct siis_channel *ch = device_get_softc(dev);
1582 	int i, retry = 0, sata_rev;
1583 	uint32_t val;
1584 
1585 	xpt_freeze_simq(ch->sim, 1);
1586 	if (bootverbose)
1587 		device_printf(dev, "SIIS reset...\n");
1588 	if (!ch->recoverycmd && !ch->recovery)
1589 		xpt_freeze_simq(ch->sim, ch->numrslots);
1590 	/* Requeue frozen command. */
1591 	if (ch->frozen) {
1592 		union ccb *fccb = ch->frozen;
1593 		ch->frozen = NULL;
1594 		fccb->ccb_h.status &= ~CAM_STATUS_MASK;
1595 		fccb->ccb_h.status |= CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1596 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1597 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1598 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1599 		}
1600 		xpt_done(fccb);
1601 	}
1602 	/* Requeue all running commands. */
1603 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1604 		/* Do we have a running request on slot? */
1605 		if (ch->slot[i].state < SIIS_SLOT_RUNNING)
1606 			continue;
1607 		/* XXX; Commands in loading state. */
1608 		siis_end_transaction(&ch->slot[i], SIIS_ERR_INNOCENT);
1609 	}
1610 	/* Finish all held commands as-is. */
1611 	for (i = 0; i < SIIS_MAX_SLOTS; i++) {
1612 		if (!ch->hold[i])
1613 			continue;
1614 		xpt_done(ch->hold[i]);
1615 		ch->hold[i] = NULL;
1616 		ch->numhslots--;
1617 	}
1618 	if (ch->toslots != 0)
1619 		xpt_release_simq(ch->sim, TRUE);
1620 	ch->eslots = 0;
1621 	ch->recovery = 0;
1622 	ch->toslots = 0;
1623 	ch->fatalerr = 0;
1624 	/* Disable port interrupts */
1625 	ATA_OUTL(ch->r_mem, SIIS_P_IECLR, 0x0000FFFF);
1626 	/* Set speed limit. */
1627 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
1628 	if (sata_rev == 1)
1629 		val = ATA_SC_SPD_SPEED_GEN1;
1630 	else if (sata_rev == 2)
1631 		val = ATA_SC_SPD_SPEED_GEN2;
1632 	else if (sata_rev == 3)
1633 		val = ATA_SC_SPD_SPEED_GEN3;
1634 	else
1635 		val = 0;
1636 	ATA_OUTL(ch->r_mem, SIIS_P_SCTL,
1637 	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
1638 	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
1639 retry:
1640 	siis_devreset(dev);
1641 	/* Reset and reconnect PHY, */
1642 	if (!siis_sata_connect(ch)) {
1643 		ch->devices = 0;
1644 		/* Enable port interrupts */
1645 		ATA_OUTL(ch->r_mem, SIIS_P_IESET, SIIS_P_IX_ENABLED);
1646 		if (bootverbose)
1647 			device_printf(dev,
1648 			    "SIIS reset done: phy reset found no device\n");
1649 		/* Tell the XPT about the event */
1650 		xpt_async(AC_BUS_RESET, ch->path, NULL);
1651 		xpt_release_simq(ch->sim, TRUE);
1652 		return;
1653 	}
1654 	/* Wait for port ready status. */
1655 	if (siis_wait_ready(dev, 1000)) {
1656 		device_printf(dev, "port ready timeout\n");
1657 		if (!retry) {
1658 			device_printf(dev, "trying full port reset ...\n");
1659 			/* Get port to the reset state. */
1660 			ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PORT_RESET);
1661 			DELAY(10000);
1662 			/* Get port out of reset state. */
1663 			ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PORT_RESET);
1664 			ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_32BIT);
1665 			if (ch->pm_present)
1666 				ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PME);
1667 			else
1668 				ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PME);
1669 			siis_wait_ready(dev, 5000);
1670 			retry = 1;
1671 			goto retry;
1672 		}
1673 	}
1674 	ch->devices = 1;
1675 	/* Enable port interrupts */
1676 	ATA_OUTL(ch->r_mem, SIIS_P_IS, 0xFFFFFFFF);
1677 	ATA_OUTL(ch->r_mem, SIIS_P_IESET, SIIS_P_IX_ENABLED);
1678 	if (bootverbose)
1679 		device_printf(dev, "SIIS reset done: devices=%08x\n", ch->devices);
1680 	/* Tell the XPT about the event */
1681 	xpt_async(AC_BUS_RESET, ch->path, NULL);
1682 	xpt_release_simq(ch->sim, TRUE);
1683 }
1684 
1685 static int
1686 siis_setup_fis(device_t dev, struct siis_cmd *ctp, union ccb *ccb, int tag)
1687 {
1688 	struct siis_channel *ch = device_get_softc(dev);
1689 	u_int8_t *fis = &ctp->fis[0];
1690 
1691 	bzero(fis, 24);
1692 	fis[0] = 0x27;  		/* host to device */
1693 	fis[1] = (ccb->ccb_h.target_id & 0x0f);
1694 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1695 		fis[1] |= 0x80;
1696 		fis[2] = ATA_PACKET_CMD;
1697 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1698 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
1699 			fis[3] = ATA_F_DMA;
1700 		else {
1701 			fis[5] = ccb->csio.dxfer_len;
1702 		        fis[6] = ccb->csio.dxfer_len >> 8;
1703 		}
1704 		fis[7] = ATA_D_LBA;
1705 		fis[15] = ATA_A_4BIT;
1706 		bzero(ctp->u.atapi.ccb, 16);
1707 		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1708 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
1709 		    ctp->u.atapi.ccb, ccb->csio.cdb_len);
1710 	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
1711 		fis[1] |= 0x80;
1712 		fis[2] = ccb->ataio.cmd.command;
1713 		fis[3] = ccb->ataio.cmd.features;
1714 		fis[4] = ccb->ataio.cmd.lba_low;
1715 		fis[5] = ccb->ataio.cmd.lba_mid;
1716 		fis[6] = ccb->ataio.cmd.lba_high;
1717 		fis[7] = ccb->ataio.cmd.device;
1718 		fis[8] = ccb->ataio.cmd.lba_low_exp;
1719 		fis[9] = ccb->ataio.cmd.lba_mid_exp;
1720 		fis[10] = ccb->ataio.cmd.lba_high_exp;
1721 		fis[11] = ccb->ataio.cmd.features_exp;
1722 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1723 			fis[12] = tag << 3;
1724 			fis[13] = 0;
1725 		} else {
1726 			fis[12] = ccb->ataio.cmd.sector_count;
1727 			fis[13] = ccb->ataio.cmd.sector_count_exp;
1728 		}
1729 		fis[15] = ATA_A_4BIT;
1730 	} else {
1731 		/* Soft reset. */
1732 	}
1733 	return (20);
1734 }
1735 
1736 static int
1737 siis_sata_connect(struct siis_channel *ch)
1738 {
1739 	u_int32_t status;
1740 	int timeout, found = 0;
1741 
1742 	/* Wait up to 100ms for "connect well" */
1743 	for (timeout = 0; timeout < 1000 ; timeout++) {
1744 		status = ATA_INL(ch->r_mem, SIIS_P_SSTS);
1745 		if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
1746 			found = 1;
1747 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1748 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1749 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
1750 			break;
1751 		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
1752 			if (bootverbose) {
1753 				device_printf(ch->dev, "SATA offline status=%08x\n",
1754 				    status);
1755 			}
1756 			return (0);
1757 		}
1758 		if (found == 0 && timeout >= 100)
1759 			break;
1760 		DELAY(100);
1761 	}
1762 	if (timeout >= 1000 || !found) {
1763 		if (bootverbose) {
1764 			device_printf(ch->dev,
1765 			    "SATA connect timeout time=%dus status=%08x\n",
1766 			    timeout * 100, status);
1767 		}
1768 		return (0);
1769 	}
1770 	if (bootverbose) {
1771 		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
1772 		    timeout * 100, status);
1773 	}
1774 	/* Clear SATA error register */
1775 	ATA_OUTL(ch->r_mem, SIIS_P_SERR, 0xffffffff);
1776 	return (1);
1777 }
1778 
1779 static int
1780 siis_check_ids(device_t dev, union ccb *ccb)
1781 {
1782 
1783 	if (ccb->ccb_h.target_id > 15) {
1784 		ccb->ccb_h.status = CAM_TID_INVALID;
1785 		xpt_done(ccb);
1786 		return (-1);
1787 	}
1788 	if (ccb->ccb_h.target_lun != 0) {
1789 		ccb->ccb_h.status = CAM_LUN_INVALID;
1790 		xpt_done(ccb);
1791 		return (-1);
1792 	}
1793 	return (0);
1794 }
1795 
1796 static void
1797 siisaction(struct cam_sim *sim, union ccb *ccb)
1798 {
1799 	device_t dev, parent;
1800 	struct siis_channel *ch;
1801 
1802 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("siisaction func_code=%x\n",
1803 	    ccb->ccb_h.func_code));
1804 
1805 	ch = (struct siis_channel *)cam_sim_softc(sim);
1806 	dev = ch->dev;
1807 	mtx_assert(&ch->mtx, MA_OWNED);
1808 	switch (ccb->ccb_h.func_code) {
1809 	/* Common cases first */
1810 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
1811 	case XPT_SCSI_IO:
1812 		if (siis_check_ids(dev, ccb))
1813 			return;
1814 		if (ch->devices == 0 ||
1815 		    (ch->pm_present == 0 &&
1816 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
1817 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
1818 			break;
1819 		}
1820 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
1821 		/* Check for command collision. */
1822 		if (siis_check_collision(dev, ccb)) {
1823 			/* Freeze command. */
1824 			ch->frozen = ccb;
1825 			/* We have only one frozen slot, so freeze simq also. */
1826 			xpt_freeze_simq(ch->sim, 1);
1827 			return;
1828 		}
1829 		siis_begin_transaction(dev, ccb);
1830 		return;
1831 	case XPT_EN_LUN:		/* Enable LUN as a target */
1832 	case XPT_TARGET_IO:		/* Execute target I/O request */
1833 	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
1834 	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
1835 	case XPT_ABORT:			/* Abort the specified CCB */
1836 		/* XXX Implement */
1837 		ccb->ccb_h.status = CAM_REQ_INVALID;
1838 		break;
1839 	case XPT_SET_TRAN_SETTINGS:
1840 	{
1841 		struct	ccb_trans_settings *cts = &ccb->cts;
1842 		struct	siis_device *d;
1843 
1844 		if (siis_check_ids(dev, ccb))
1845 			return;
1846 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1847 			d = &ch->curr[ccb->ccb_h.target_id];
1848 		else
1849 			d = &ch->user[ccb->ccb_h.target_id];
1850 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
1851 			d->revision = cts->xport_specific.sata.revision;
1852 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
1853 			d->mode = cts->xport_specific.sata.mode;
1854 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
1855 			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
1856 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
1857 			d->tags = min(SIIS_MAX_SLOTS, cts->xport_specific.sata.tags);
1858 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM) {
1859 			ch->pm_present = cts->xport_specific.sata.pm_present;
1860 			if (ch->pm_present)
1861 				ATA_OUTL(ch->r_mem, SIIS_P_CTLSET, SIIS_P_CTL_PME);
1862 			else
1863 				ATA_OUTL(ch->r_mem, SIIS_P_CTLCLR, SIIS_P_CTL_PME);
1864 		}
1865 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
1866 			d->atapi = cts->xport_specific.sata.atapi;
1867 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
1868 			d->caps = cts->xport_specific.sata.caps;
1869 		ccb->ccb_h.status = CAM_REQ_CMP;
1870 		break;
1871 	}
1872 	case XPT_GET_TRAN_SETTINGS:
1873 	/* Get default/user set transfer settings for the target */
1874 	{
1875 		struct	ccb_trans_settings *cts = &ccb->cts;
1876 		struct  siis_device *d;
1877 		uint32_t status;
1878 
1879 		if (siis_check_ids(dev, ccb))
1880 			return;
1881 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1882 			d = &ch->curr[ccb->ccb_h.target_id];
1883 		else
1884 			d = &ch->user[ccb->ccb_h.target_id];
1885 		cts->protocol = PROTO_ATA;
1886 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
1887 		cts->transport = XPORT_SATA;
1888 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
1889 		cts->proto_specific.valid = 0;
1890 		cts->xport_specific.sata.valid = 0;
1891 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
1892 		    (ccb->ccb_h.target_id == 15 ||
1893 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
1894 			status = ATA_INL(ch->r_mem, SIIS_P_SSTS) & ATA_SS_SPD_MASK;
1895 			if (status & 0x0f0) {
1896 				cts->xport_specific.sata.revision =
1897 				    (status & 0x0f0) >> 4;
1898 				cts->xport_specific.sata.valid |=
1899 				    CTS_SATA_VALID_REVISION;
1900 			}
1901 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
1902 			if (ch->pm_level)
1903 				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
1904 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
1905 			cts->xport_specific.sata.caps &=
1906 			    ch->user[ccb->ccb_h.target_id].caps;
1907 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
1908 		} else {
1909 			cts->xport_specific.sata.revision = d->revision;
1910 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
1911 			cts->xport_specific.sata.caps = d->caps;
1912 			if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
1913 			    (ch->quirks & SIIS_Q_SNTF) == 0)
1914 				cts->xport_specific.sata.caps &= ~CTS_SATA_CAPS_H_AN;
1915 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
1916 		}
1917 		cts->xport_specific.sata.mode = d->mode;
1918 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
1919 		cts->xport_specific.sata.bytecount = d->bytecount;
1920 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
1921 		cts->xport_specific.sata.pm_present = ch->pm_present;
1922 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
1923 		cts->xport_specific.sata.tags = d->tags;
1924 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
1925 		cts->xport_specific.sata.atapi = d->atapi;
1926 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
1927 		ccb->ccb_h.status = CAM_REQ_CMP;
1928 		break;
1929 	}
1930 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
1931 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
1932 		siis_reset(dev);
1933 		ccb->ccb_h.status = CAM_REQ_CMP;
1934 		break;
1935 	case XPT_TERM_IO:		/* Terminate the I/O process */
1936 		/* XXX Implement */
1937 		ccb->ccb_h.status = CAM_REQ_INVALID;
1938 		break;
1939 	case XPT_PATH_INQ:		/* Path routing inquiry */
1940 	{
1941 		struct ccb_pathinq *cpi = &ccb->cpi;
1942 
1943 		parent = device_get_parent(dev);
1944 		cpi->version_num = 1; /* XXX??? */
1945 		cpi->hba_inquiry = PI_SDTR_ABLE | PI_TAG_ABLE;
1946 		cpi->hba_inquiry |= PI_SATAPM;
1947 		cpi->target_sprt = 0;
1948 		cpi->hba_misc = PIM_SEQSCAN;
1949 		cpi->hba_eng_cnt = 0;
1950 		cpi->max_target = 15;
1951 		cpi->max_lun = 0;
1952 		cpi->initiator_id = 0;
1953 		cpi->bus_id = cam_sim_bus(sim);
1954 		cpi->base_transfer_speed = 150000;
1955 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1956 		strncpy(cpi->hba_vid, "SIIS", HBA_IDLEN);
1957 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1958 		cpi->unit_number = cam_sim_unit(sim);
1959 		cpi->transport = XPORT_SATA;
1960 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
1961 		cpi->protocol = PROTO_ATA;
1962 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
1963 		cpi->maxio = MAXPHYS;
1964 		cpi->hba_vendor = pci_get_vendor(parent);
1965 		cpi->hba_device = pci_get_device(parent);
1966 		cpi->hba_subvendor = pci_get_subvendor(parent);
1967 		cpi->hba_subdevice = pci_get_subdevice(parent);
1968 		cpi->ccb_h.status = CAM_REQ_CMP;
1969 		break;
1970 	}
1971 	default:
1972 		ccb->ccb_h.status = CAM_REQ_INVALID;
1973 		break;
1974 	}
1975 	xpt_done(ccb);
1976 }
1977 
1978 static void
1979 siispoll(struct cam_sim *sim)
1980 {
1981 	struct siis_channel *ch = (struct siis_channel *)cam_sim_softc(sim);
1982 
1983 	siis_ch_intr(ch->dev);
1984 }
1985