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