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