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