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