sbp.c revision 170724
1/*-
2 * Copyright (c) 2003 Hidetoshi Shimokawa
3 * Copyright (c) 1998-2002 Katsushi Kobayashi and Hidetoshi Shimokawa
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
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 * 3. All advertising materials mentioning features or use of this software
15 *    must display the acknowledgement as bellow:
16 *
17 *    This product includes software developed by K. Kobayashi and H. Shimokawa
18 *
19 * 4. The name of the author may not be used to endorse or promote products
20 *    derived from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
26 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 *
34 * $FreeBSD: head/sys/dev/firewire/sbp.c 170724 2007-06-14 12:52:13Z simokawa $
35 *
36 */
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/module.h>
41#include <sys/bus.h>
42#include <sys/kernel.h>
43#include <sys/sysctl.h>
44#include <machine/bus.h>
45#include <sys/malloc.h>
46#if defined(__FreeBSD__) && __FreeBSD_version >= 501102
47#include <sys/lock.h>
48#include <sys/mutex.h>
49#endif
50
51#if defined(__DragonFly__) || __FreeBSD_version < 500106
52#include <sys/devicestat.h>	/* for struct devstat */
53#endif
54
55#ifdef __DragonFly__
56#include <bus/cam/cam.h>
57#include <bus/cam/cam_ccb.h>
58#include <bus/cam/cam_sim.h>
59#include <bus/cam/cam_xpt_sim.h>
60#include <bus/cam/cam_debug.h>
61#include <bus/cam/cam_periph.h>
62#include <bus/cam/scsi/scsi_all.h>
63
64#include <bus/firewire/firewire.h>
65#include <bus/firewire/firewirereg.h>
66#include <bus/firewire/fwdma.h>
67#include <bus/firewire/iec13213.h>
68#include "sbp.h"
69#else
70#include <cam/cam.h>
71#include <cam/cam_ccb.h>
72#include <cam/cam_sim.h>
73#include <cam/cam_xpt_sim.h>
74#include <cam/cam_debug.h>
75#include <cam/cam_periph.h>
76#include <cam/scsi/scsi_all.h>
77
78#include <dev/firewire/firewire.h>
79#include <dev/firewire/firewirereg.h>
80#include <dev/firewire/fwdma.h>
81#include <dev/firewire/iec13213.h>
82#include <dev/firewire/sbp.h>
83#endif
84
85#define ccb_sdev_ptr	spriv_ptr0
86#define ccb_sbp_ptr	spriv_ptr1
87
88#define SBP_NUM_TARGETS 8 /* MAX 64 */
89/*
90 * Scan_bus doesn't work for more than 8 LUNs
91 * because of CAM_SCSI2_MAXLUN in cam_xpt.c
92 */
93#define SBP_NUM_LUNS 64
94#define SBP_MAXPHYS  MIN(MAXPHYS, (512*1024) /* 512KB */)
95#define SBP_DMA_SIZE PAGE_SIZE
96#define SBP_LOGIN_SIZE sizeof(struct sbp_login_res)
97#define SBP_QUEUE_LEN ((SBP_DMA_SIZE - SBP_LOGIN_SIZE) / sizeof(struct sbp_ocb))
98#define SBP_NUM_OCB (SBP_QUEUE_LEN * SBP_NUM_TARGETS)
99
100/*
101 * STATUS FIFO addressing
102 *   bit
103 * -----------------------
104 *  0- 1( 2): 0 (alignment)
105 *  2- 7( 6): target
106 *  8-15( 8): lun
107 * 16-31( 8): reserved
108 * 32-47(16): SBP_BIND_HI
109 * 48-64(16): bus_id, node_id
110 */
111#define SBP_BIND_HI 0x1
112#define SBP_DEV2ADDR(t, l) \
113	(((u_int64_t)SBP_BIND_HI << 32) \
114	| (((l) & 0xff) << 8) \
115	| (((t) & 0x3f) << 2))
116#define SBP_ADDR2TRG(a)	(((a) >> 2) & 0x3f)
117#define SBP_ADDR2LUN(a)	(((a) >> 8) & 0xff)
118#define SBP_INITIATOR 7
119
120static char *orb_fun_name[] = {
121	ORB_FUN_NAMES
122};
123
124static int debug = 0;
125static int auto_login = 1;
126static int max_speed = -1;
127static int sbp_cold = 1;
128static int ex_login = 1;
129static int login_delay = 1000;	/* msec */
130static int scan_delay = 500;	/* msec */
131static int use_doorbell = 0;
132static int sbp_tags = 0;
133
134SYSCTL_DECL(_hw_firewire);
135SYSCTL_NODE(_hw_firewire, OID_AUTO, sbp, CTLFLAG_RD, 0, "SBP-II Subsystem");
136SYSCTL_INT(_debug, OID_AUTO, sbp_debug, CTLFLAG_RW, &debug, 0,
137	"SBP debug flag");
138SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, auto_login, CTLFLAG_RW, &auto_login, 0,
139	"SBP perform login automatically");
140SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, max_speed, CTLFLAG_RW, &max_speed, 0,
141	"SBP transfer max speed");
142SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, exclusive_login, CTLFLAG_RW,
143	&ex_login, 0, "SBP enable exclusive login");
144SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, login_delay, CTLFLAG_RW,
145	&login_delay, 0, "SBP login delay in msec");
146SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, scan_delay, CTLFLAG_RW,
147	&scan_delay, 0, "SBP scan delay in msec");
148SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, use_doorbell, CTLFLAG_RW,
149	&use_doorbell, 0, "SBP use doorbell request");
150SYSCTL_INT(_hw_firewire_sbp, OID_AUTO, tags, CTLFLAG_RW, &sbp_tags, 0,
151	"SBP tagged queuing support");
152
153TUNABLE_INT("hw.firewire.sbp.auto_login", &auto_login);
154TUNABLE_INT("hw.firewire.sbp.max_speed", &max_speed);
155TUNABLE_INT("hw.firewire.sbp.exclusive_login", &ex_login);
156TUNABLE_INT("hw.firewire.sbp.login_delay", &login_delay);
157TUNABLE_INT("hw.firewire.sbp.scan_delay", &scan_delay);
158TUNABLE_INT("hw.firewire.sbp.use_doorbell", &use_doorbell);
159TUNABLE_INT("hw.firewire.sbp.tags", &sbp_tags);
160
161#define NEED_RESPONSE 0
162
163#define SBP_SEG_MAX rounddown(0xffff, PAGE_SIZE)
164#ifdef __sparc64__ /* iommu */
165#define SBP_IND_MAX howmany(SBP_MAXPHYS, SBP_SEG_MAX)
166#else
167#define SBP_IND_MAX howmany(SBP_MAXPHYS, PAGE_SIZE)
168#endif
169struct sbp_ocb {
170	STAILQ_ENTRY(sbp_ocb)	ocb;
171	union ccb	*ccb;
172	bus_addr_t	bus_addr;
173	uint32_t	orb[8];
174#define IND_PTR_OFFSET	(8*sizeof(uint32_t))
175	struct ind_ptr  ind_ptr[SBP_IND_MAX];
176	struct sbp_dev	*sdev;
177	int		flags; /* XXX should be removed */
178	bus_dmamap_t	dmamap;
179};
180
181#define OCB_ACT_MGM 0
182#define OCB_ACT_CMD 1
183#define OCB_MATCH(o,s)	((o)->bus_addr == ntohl((s)->orb_lo))
184
185struct sbp_dev{
186#define SBP_DEV_RESET		0	/* accept login */
187#define SBP_DEV_LOGIN		1	/* to login */
188#if 0
189#define SBP_DEV_RECONN		2	/* to reconnect */
190#endif
191#define SBP_DEV_TOATTACH	3	/* to attach */
192#define SBP_DEV_PROBE		4	/* scan lun */
193#define SBP_DEV_ATTACHED	5	/* in operation */
194#define SBP_DEV_DEAD		6	/* unavailable unit */
195#define SBP_DEV_RETRY		7	/* unavailable unit */
196	uint8_t status:4,
197		 timeout:4;
198	uint8_t type;
199	uint16_t lun_id;
200	uint16_t freeze;
201#define	ORB_LINK_DEAD		(1 << 0)
202#define	VALID_LUN		(1 << 1)
203#define	ORB_POINTER_ACTIVE	(1 << 2)
204#define	ORB_POINTER_NEED	(1 << 3)
205#define	ORB_DOORBELL_ACTIVE	(1 << 4)
206#define	ORB_DOORBELL_NEED	(1 << 5)
207#define	ORB_SHORTAGE		(1 << 6)
208	uint16_t flags;
209	struct cam_path *path;
210	struct sbp_target *target;
211	struct fwdma_alloc dma;
212	struct sbp_login_res *login;
213	struct callout login_callout;
214	struct sbp_ocb *ocb;
215	STAILQ_HEAD(, sbp_ocb) ocbs;
216	STAILQ_HEAD(, sbp_ocb) free_ocbs;
217	struct sbp_ocb *last_ocb;
218	char vendor[32];
219	char product[32];
220	char revision[10];
221};
222
223struct sbp_target {
224	int target_id;
225	int num_lun;
226	struct sbp_dev	**luns;
227	struct sbp_softc *sbp;
228	struct fw_device *fwdev;
229	uint32_t mgm_hi, mgm_lo;
230	struct sbp_ocb *mgm_ocb_cur;
231	STAILQ_HEAD(, sbp_ocb) mgm_ocb_queue;
232	struct callout mgm_ocb_timeout;
233	struct callout scan_callout;
234	STAILQ_HEAD(, fw_xfer) xferlist;
235	int n_xfer;
236};
237
238struct sbp_softc {
239	struct firewire_dev_comm fd;
240	struct cam_sim  *sim;
241	struct cam_path  *path;
242	struct sbp_target targets[SBP_NUM_TARGETS];
243	struct fw_bind fwb;
244	bus_dma_tag_t	dmat;
245	struct timeval last_busreset;
246#define SIMQ_FREEZED 1
247	int flags;
248	struct mtx mtx;
249};
250#define SBP_LOCK(sbp) mtx_lock(&(sbp)->mtx)
251#define SBP_UNLOCK(sbp) mtx_unlock(&(sbp)->mtx)
252
253static void sbp_post_explore (void *);
254static void sbp_recv (struct fw_xfer *);
255static void sbp_mgm_callback (struct fw_xfer *);
256#if 0
257static void sbp_cmd_callback (struct fw_xfer *);
258#endif
259static void sbp_orb_pointer (struct sbp_dev *, struct sbp_ocb *);
260static void sbp_doorbell(struct sbp_dev *);
261static void sbp_execute_ocb (void *,  bus_dma_segment_t *, int, int);
262static void sbp_free_ocb (struct sbp_dev *, struct sbp_ocb *);
263static void sbp_abort_ocb (struct sbp_ocb *, int);
264static void sbp_abort_all_ocbs (struct sbp_dev *, int);
265static struct fw_xfer * sbp_write_cmd (struct sbp_dev *, int, int);
266static struct sbp_ocb * sbp_get_ocb (struct sbp_dev *);
267static struct sbp_ocb * sbp_enqueue_ocb (struct sbp_dev *, struct sbp_ocb *);
268static struct sbp_ocb * sbp_dequeue_ocb (struct sbp_dev *, struct sbp_status *);
269static void sbp_cam_detach_sdev(struct sbp_dev *);
270static void sbp_free_sdev(struct sbp_dev *);
271static void sbp_cam_detach_target (struct sbp_target *);
272static void sbp_free_target (struct sbp_target *);
273static void sbp_mgm_timeout (void *arg);
274static void sbp_timeout (void *arg);
275static void sbp_mgm_orb (struct sbp_dev *, int, struct sbp_ocb *);
276
277MALLOC_DEFINE(M_SBP, "sbp", "SBP-II/FireWire");
278
279/* cam related functions */
280static void	sbp_action(struct cam_sim *sim, union ccb *ccb);
281static void	sbp_poll(struct cam_sim *sim);
282static void	sbp_cam_scan_lun(struct cam_periph *, union ccb *);
283static void	sbp_cam_scan_target(void *arg);
284
285static char *orb_status0[] = {
286	/* 0 */ "No additional information to report",
287	/* 1 */ "Request type not supported",
288	/* 2 */ "Speed not supported",
289	/* 3 */ "Page size not supported",
290	/* 4 */ "Access denied",
291	/* 5 */ "Logical unit not supported",
292	/* 6 */ "Maximum payload too small",
293	/* 7 */ "Reserved for future standardization",
294	/* 8 */ "Resources unavailable",
295	/* 9 */ "Function rejected",
296	/* A */ "Login ID not recognized",
297	/* B */ "Dummy ORB completed",
298	/* C */ "Request aborted",
299	/* FF */ "Unspecified error"
300#define MAX_ORB_STATUS0 0xd
301};
302
303static char *orb_status1_object[] = {
304	/* 0 */ "Operation request block (ORB)",
305	/* 1 */ "Data buffer",
306	/* 2 */ "Page table",
307	/* 3 */ "Unable to specify"
308};
309
310static char *orb_status1_serial_bus_error[] = {
311	/* 0 */ "Missing acknowledge",
312	/* 1 */ "Reserved; not to be used",
313	/* 2 */ "Time-out error",
314	/* 3 */ "Reserved; not to be used",
315	/* 4 */ "Busy retry limit exceeded(X)",
316	/* 5 */ "Busy retry limit exceeded(A)",
317	/* 6 */ "Busy retry limit exceeded(B)",
318	/* 7 */ "Reserved for future standardization",
319	/* 8 */ "Reserved for future standardization",
320	/* 9 */ "Reserved for future standardization",
321	/* A */ "Reserved for future standardization",
322	/* B */ "Tardy retry limit exceeded",
323	/* C */ "Conflict error",
324	/* D */ "Data error",
325	/* E */ "Type error",
326	/* F */ "Address error"
327};
328
329static void
330sbp_identify(driver_t *driver, device_t parent)
331{
332	device_t child;
333SBP_DEBUG(0)
334	printf("sbp_identify\n");
335END_DEBUG
336
337	child = BUS_ADD_CHILD(parent, 0, "sbp", device_get_unit(parent));
338}
339
340/*
341 * sbp_probe()
342 */
343static int
344sbp_probe(device_t dev)
345{
346	device_t pa;
347
348SBP_DEBUG(0)
349	printf("sbp_probe\n");
350END_DEBUG
351
352	pa = device_get_parent(dev);
353	if(device_get_unit(dev) != device_get_unit(pa)){
354		return(ENXIO);
355	}
356
357	device_set_desc(dev, "SBP-2/SCSI over FireWire");
358
359#if 0
360	if (bootverbose)
361		debug = bootverbose;
362#endif
363
364	return (0);
365}
366
367static void
368sbp_show_sdev_info(struct sbp_dev *sdev, int new)
369{
370	struct fw_device *fwdev;
371
372	printf("%s:%d:%d ",
373		device_get_nameunit(sdev->target->sbp->fd.dev),
374		sdev->target->target_id,
375		sdev->lun_id
376	);
377	if (new == 2) {
378		return;
379	}
380	fwdev = sdev->target->fwdev;
381	printf("ordered:%d type:%d EUI:%08x%08x node:%d "
382		"speed:%d maxrec:%d",
383		(sdev->type & 0x40) >> 6,
384		(sdev->type & 0x1f),
385		fwdev->eui.hi,
386		fwdev->eui.lo,
387		fwdev->dst,
388		fwdev->speed,
389		fwdev->maxrec
390	);
391	if (new)
392		printf(" new!\n");
393	else
394		printf("\n");
395	sbp_show_sdev_info(sdev, 2);
396	printf("'%s' '%s' '%s'\n", sdev->vendor, sdev->product, sdev->revision);
397}
398
399static struct {
400	int bus;
401	int target;
402	struct fw_eui64 eui;
403} wired[] = {
404	/* Bus	Target	EUI64 */
405#if 0
406	{0,	2,	{0x00018ea0, 0x01fd0154}},	/* Logitec HDD */
407	{0,	0,	{0x00018ea6, 0x00100682}},	/* Logitec DVD */
408	{0,	1,	{0x00d03200, 0xa412006a}},	/* Yano HDD */
409#endif
410	{-1,	-1,	{0,0}}
411};
412
413static int
414sbp_new_target(struct sbp_softc *sbp, struct fw_device *fwdev)
415{
416	int bus, i, target=-1;
417	char w[SBP_NUM_TARGETS];
418
419	bzero(w, sizeof(w));
420	bus = device_get_unit(sbp->fd.dev);
421
422	/* XXX wired-down configuration should be gotten from
423					tunable or device hint */
424	for (i = 0; wired[i].bus >= 0; i ++) {
425		if (wired[i].bus == bus) {
426			w[wired[i].target] = 1;
427			if (wired[i].eui.hi == fwdev->eui.hi &&
428					wired[i].eui.lo == fwdev->eui.lo)
429				target = wired[i].target;
430		}
431	}
432	if (target >= 0) {
433		if(target < SBP_NUM_TARGETS &&
434				sbp->targets[target].fwdev == NULL)
435			return(target);
436		device_printf(sbp->fd.dev,
437			"target %d is not free for %08x:%08x\n",
438			target, fwdev->eui.hi, fwdev->eui.lo);
439		target = -1;
440	}
441	/* non-wired target */
442	for (i = 0; i < SBP_NUM_TARGETS; i ++)
443		if (sbp->targets[i].fwdev == NULL && w[i] == 0) {
444			target = i;
445			break;
446		}
447
448	return target;
449}
450
451static void
452sbp_alloc_lun(struct sbp_target *target)
453{
454	struct crom_context cc;
455	struct csrreg *reg;
456	struct sbp_dev *sdev, **newluns;
457	struct sbp_softc *sbp;
458	int maxlun, lun, i;
459
460	sbp = target->sbp;
461	crom_init_context(&cc, target->fwdev->csrrom);
462	/* XXX shoud parse appropriate unit directories only */
463	maxlun = -1;
464	while (cc.depth >= 0) {
465		reg = crom_search_key(&cc, CROM_LUN);
466		if (reg == NULL)
467			break;
468		lun = reg->val & 0xffff;
469SBP_DEBUG(0)
470		printf("target %d lun %d found\n", target->target_id, lun);
471END_DEBUG
472		if (maxlun < lun)
473			maxlun = lun;
474		crom_next(&cc);
475	}
476	if (maxlun < 0)
477		printf("%s:%d no LUN found\n",
478		    device_get_nameunit(target->sbp->fd.dev),
479		    target->target_id);
480
481	maxlun ++;
482	if (maxlun >= SBP_NUM_LUNS)
483		maxlun = SBP_NUM_LUNS;
484
485	/* Invalidiate stale devices */
486	for (lun = 0; lun < target->num_lun; lun ++) {
487		sdev = target->luns[lun];
488		if (sdev == NULL)
489			continue;
490		sdev->flags &= ~VALID_LUN;
491		if (lun >= maxlun) {
492			/* lost device */
493			sbp_cam_detach_sdev(sdev);
494			sbp_free_sdev(sdev);
495		}
496	}
497
498	/* Reallocate */
499	if (maxlun != target->num_lun) {
500		newluns = (struct sbp_dev **) realloc(target->luns,
501		    sizeof(struct sbp_dev *) * maxlun,
502		    M_SBP, M_NOWAIT | M_ZERO);
503
504		if (newluns == NULL) {
505			printf("%s: realloc failed\n", __func__);
506			newluns = target->luns;
507			maxlun = target->num_lun;
508		}
509
510		/*
511		 * We must zero the extended region for the case
512		 * realloc() doesn't allocate new buffer.
513		 */
514		if (maxlun > target->num_lun)
515			bzero(&newluns[target->num_lun],
516			    sizeof(struct sbp_dev *) *
517			    (maxlun - target->num_lun));
518
519		target->luns = newluns;
520		target->num_lun = maxlun;
521	}
522
523	crom_init_context(&cc, target->fwdev->csrrom);
524	while (cc.depth >= 0) {
525		int new = 0;
526
527		reg = crom_search_key(&cc, CROM_LUN);
528		if (reg == NULL)
529			break;
530		lun = reg->val & 0xffff;
531		if (lun >= SBP_NUM_LUNS) {
532			printf("too large lun %d\n", lun);
533			goto next;
534		}
535
536		sdev = target->luns[lun];
537		if (sdev == NULL) {
538			sdev = malloc(sizeof(struct sbp_dev),
539			    M_SBP, M_NOWAIT | M_ZERO);
540			if (sdev == NULL) {
541				printf("%s: malloc failed\n", __func__);
542				goto next;
543			}
544			target->luns[lun] = sdev;
545			sdev->lun_id = lun;
546			sdev->target = target;
547			STAILQ_INIT(&sdev->ocbs);
548			CALLOUT_INIT(&sdev->login_callout);
549			sdev->status = SBP_DEV_RESET;
550			new = 1;
551		}
552		sdev->flags |= VALID_LUN;
553		sdev->type = (reg->val & 0xff0000) >> 16;
554
555		if (new == 0)
556			goto next;
557
558		fwdma_malloc(sbp->fd.fc,
559			/* alignment */ sizeof(uint32_t),
560			SBP_DMA_SIZE, &sdev->dma, BUS_DMA_NOWAIT);
561		if (sdev->dma.v_addr == NULL) {
562			printf("%s: dma space allocation failed\n",
563							__func__);
564			free(sdev, M_SBP);
565			target->luns[lun] = NULL;
566			goto next;
567		}
568		sdev->login = (struct sbp_login_res *) sdev->dma.v_addr;
569		sdev->ocb = (struct sbp_ocb *)
570				((char *)sdev->dma.v_addr + SBP_LOGIN_SIZE);
571		bzero((char *)sdev->ocb,
572			sizeof (struct sbp_ocb) * SBP_QUEUE_LEN);
573
574		STAILQ_INIT(&sdev->free_ocbs);
575		for (i = 0; i < SBP_QUEUE_LEN; i++) {
576			struct sbp_ocb *ocb;
577			ocb = &sdev->ocb[i];
578			ocb->bus_addr = sdev->dma.bus_addr
579				+ SBP_LOGIN_SIZE
580				+ sizeof(struct sbp_ocb) * i
581				+ offsetof(struct sbp_ocb, orb[0]);
582			if (bus_dmamap_create(sbp->dmat, 0, &ocb->dmamap)) {
583				printf("sbp_attach: cannot create dmamap\n");
584				/* XXX */
585				goto next;
586			}
587			sbp_free_ocb(sdev, ocb);
588		}
589next:
590		crom_next(&cc);
591	}
592
593	for (lun = 0; lun < target->num_lun; lun ++) {
594		sdev = target->luns[lun];
595		if (sdev != NULL && (sdev->flags & VALID_LUN) == 0) {
596			sbp_cam_detach_sdev(sdev);
597			sbp_free_sdev(sdev);
598			target->luns[lun] = NULL;
599		}
600	}
601}
602
603static struct sbp_target *
604sbp_alloc_target(struct sbp_softc *sbp, struct fw_device *fwdev)
605{
606	int i;
607	struct sbp_target *target;
608	struct crom_context cc;
609	struct csrreg *reg;
610
611SBP_DEBUG(1)
612	printf("sbp_alloc_target\n");
613END_DEBUG
614	i = sbp_new_target(sbp, fwdev);
615	if (i < 0) {
616		device_printf(sbp->fd.dev, "increase SBP_NUM_TARGETS!\n");
617		return NULL;
618	}
619	/* new target */
620	target = &sbp->targets[i];
621	target->sbp = sbp;
622	target->fwdev = fwdev;
623	target->target_id = i;
624	/* XXX we may want to reload mgm port after each bus reset */
625	/* XXX there might be multiple management agents */
626	crom_init_context(&cc, target->fwdev->csrrom);
627	reg = crom_search_key(&cc, CROM_MGM);
628	if (reg == NULL || reg->val == 0) {
629		printf("NULL management address\n");
630		target->fwdev = NULL;
631		return NULL;
632	}
633	target->mgm_hi = 0xffff;
634	target->mgm_lo = 0xf0000000 | (reg->val << 2);
635	target->mgm_ocb_cur = NULL;
636SBP_DEBUG(1)
637	printf("target:%d mgm_port: %x\n", i, target->mgm_lo);
638END_DEBUG
639	STAILQ_INIT(&target->xferlist);
640	target->n_xfer = 0;
641	STAILQ_INIT(&target->mgm_ocb_queue);
642	CALLOUT_INIT(&target->mgm_ocb_timeout);
643	CALLOUT_INIT(&target->scan_callout);
644
645	target->luns = NULL;
646	target->num_lun = 0;
647	return target;
648}
649
650static void
651sbp_probe_lun(struct sbp_dev *sdev)
652{
653	struct fw_device *fwdev;
654	struct crom_context c, *cc = &c;
655	struct csrreg *reg;
656
657	bzero(sdev->vendor, sizeof(sdev->vendor));
658	bzero(sdev->product, sizeof(sdev->product));
659
660	fwdev = sdev->target->fwdev;
661	crom_init_context(cc, fwdev->csrrom);
662	/* get vendor string */
663	crom_search_key(cc, CSRKEY_VENDOR);
664	crom_next(cc);
665	crom_parse_text(cc, sdev->vendor, sizeof(sdev->vendor));
666	/* skip to the unit directory for SBP-2 */
667	while ((reg = crom_search_key(cc, CSRKEY_VER)) != NULL) {
668		if (reg->val == CSRVAL_T10SBP2)
669			break;
670		crom_next(cc);
671	}
672	/* get firmware revision */
673	reg = crom_search_key(cc, CSRKEY_FIRM_VER);
674	if (reg != NULL)
675		snprintf(sdev->revision, sizeof(sdev->revision),
676						"%06x", reg->val);
677	/* get product string */
678	crom_search_key(cc, CSRKEY_MODEL);
679	crom_next(cc);
680	crom_parse_text(cc, sdev->product, sizeof(sdev->product));
681}
682
683static void
684sbp_login_callout(void *arg)
685{
686	struct sbp_dev *sdev = (struct sbp_dev *)arg;
687	sbp_mgm_orb(sdev, ORB_FUN_LGI, NULL);
688}
689
690static void
691sbp_login(struct sbp_dev *sdev)
692{
693	struct timeval delta;
694	struct timeval t;
695	int ticks = 0;
696
697	microtime(&delta);
698	timevalsub(&delta, &sdev->target->sbp->last_busreset);
699	t.tv_sec = login_delay / 1000;
700	t.tv_usec = (login_delay % 1000) * 1000;
701	timevalsub(&t, &delta);
702	if (t.tv_sec >= 0 && t.tv_usec > 0)
703		ticks = (t.tv_sec * 1000 + t.tv_usec / 1000) * hz / 1000;
704SBP_DEBUG(0)
705	printf("%s: sec = %jd usec = %ld ticks = %d\n", __func__,
706	    (intmax_t)t.tv_sec, t.tv_usec, ticks);
707END_DEBUG
708	callout_reset(&sdev->login_callout, ticks,
709			sbp_login_callout, (void *)(sdev));
710}
711
712#define SBP_FWDEV_ALIVE(fwdev) (((fwdev)->status == FWDEVATTACHED) \
713	&& crom_has_specver((fwdev)->csrrom, CSRVAL_ANSIT10, CSRVAL_T10SBP2))
714
715static void
716sbp_probe_target(void *arg)
717{
718	struct sbp_target *target = (struct sbp_target *)arg;
719	struct sbp_softc *sbp;
720	struct sbp_dev *sdev;
721	struct firewire_comm *fc;
722	int i, alive;
723
724	alive = SBP_FWDEV_ALIVE(target->fwdev);
725SBP_DEBUG(1)
726	printf("sbp_probe_target %d\n", target->target_id);
727	if (!alive)
728		printf("not alive\n");
729END_DEBUG
730
731	sbp = target->sbp;
732	fc = target->sbp->fd.fc;
733	sbp_alloc_lun(target);
734
735	/* XXX untimeout mgm_ocb and dequeue */
736	for (i=0; i < target->num_lun; i++) {
737		sdev = target->luns[i];
738		if (sdev == NULL)
739			continue;
740		if (alive && (sdev->status != SBP_DEV_DEAD)) {
741			if (sdev->path != NULL) {
742				SBP_LOCK(sbp);
743				xpt_freeze_devq(sdev->path, 1);
744				sdev->freeze ++;
745				SBP_UNLOCK(sbp);
746			}
747			sbp_probe_lun(sdev);
748SBP_DEBUG(0)
749			sbp_show_sdev_info(sdev,
750					(sdev->status == SBP_DEV_RESET));
751END_DEBUG
752
753			sbp_abort_all_ocbs(sdev, CAM_SCSI_BUS_RESET);
754			switch (sdev->status) {
755			case SBP_DEV_RESET:
756				/* new or revived target */
757				if (auto_login)
758					sbp_login(sdev);
759				break;
760			case SBP_DEV_TOATTACH:
761			case SBP_DEV_PROBE:
762			case SBP_DEV_ATTACHED:
763			case SBP_DEV_RETRY:
764			default:
765				sbp_mgm_orb(sdev, ORB_FUN_RCN, NULL);
766				break;
767			}
768		} else {
769			switch (sdev->status) {
770			case SBP_DEV_ATTACHED:
771SBP_DEBUG(0)
772				/* the device has gone */
773				sbp_show_sdev_info(sdev, 2);
774				printf("lost target\n");
775END_DEBUG
776				if (sdev->path) {
777					SBP_LOCK(sbp);
778					xpt_freeze_devq(sdev->path, 1);
779					sdev->freeze ++;
780					SBP_UNLOCK(sbp);
781				}
782				sdev->status = SBP_DEV_RETRY;
783				sbp_abort_all_ocbs(sdev, CAM_SCSI_BUS_RESET);
784				break;
785			case SBP_DEV_PROBE:
786			case SBP_DEV_TOATTACH:
787				sdev->status = SBP_DEV_RESET;
788				break;
789			case SBP_DEV_RETRY:
790			case SBP_DEV_RESET:
791			case SBP_DEV_DEAD:
792				break;
793			}
794		}
795	}
796}
797
798static void
799sbp_post_busreset(void *arg)
800{
801	struct sbp_softc *sbp;
802
803	sbp = (struct sbp_softc *)arg;
804SBP_DEBUG(0)
805	printf("sbp_post_busreset\n");
806END_DEBUG
807	if ((sbp->sim->flags & SIMQ_FREEZED) == 0) {
808		SBP_LOCK(sbp);
809		xpt_freeze_simq(sbp->sim, /*count*/1);
810		sbp->sim->flags |= SIMQ_FREEZED;
811		SBP_UNLOCK(sbp);
812	}
813	microtime(&sbp->last_busreset);
814}
815
816static void
817sbp_post_explore(void *arg)
818{
819	struct sbp_softc *sbp = (struct sbp_softc *)arg;
820	struct sbp_target *target;
821	struct fw_device *fwdev;
822	int i, alive;
823
824SBP_DEBUG(0)
825	printf("sbp_post_explore (sbp_cold=%d)\n", sbp_cold);
826END_DEBUG
827	/* We need physical access */
828	if (!firewire_phydma_enable)
829		return;
830
831	if (sbp_cold > 0)
832		sbp_cold --;
833
834#if 0
835	/*
836	 * XXX don't let CAM the bus rest.
837	 * CAM tries to do something with freezed (DEV_RETRY) devices.
838	 */
839	xpt_async(AC_BUS_RESET, sbp->path, /*arg*/ NULL);
840#endif
841
842	/* Garbage Collection */
843	for(i = 0 ; i < SBP_NUM_TARGETS ; i ++){
844		target = &sbp->targets[i];
845		STAILQ_FOREACH(fwdev, &sbp->fd.fc->devices, link)
846			if (target->fwdev == NULL || target->fwdev == fwdev)
847				break;
848		if (fwdev == NULL) {
849			/* device has removed in lower driver */
850			sbp_cam_detach_target(target);
851			sbp_free_target(target);
852		}
853	}
854	/* traverse device list */
855	STAILQ_FOREACH(fwdev, &sbp->fd.fc->devices, link) {
856SBP_DEBUG(0)
857		printf("sbp_post_explore: EUI:%08x%08x ",
858				fwdev->eui.hi, fwdev->eui.lo);
859		if (fwdev->status != FWDEVATTACHED)
860			printf("not attached, state=%d.\n", fwdev->status);
861		else
862			printf("attached\n");
863END_DEBUG
864		alive = SBP_FWDEV_ALIVE(fwdev);
865		for(i = 0 ; i < SBP_NUM_TARGETS ; i ++){
866			target = &sbp->targets[i];
867			if(target->fwdev == fwdev ) {
868				/* known target */
869				break;
870			}
871		}
872		if(i == SBP_NUM_TARGETS){
873			if (alive) {
874				/* new target */
875				target = sbp_alloc_target(sbp, fwdev);
876				if (target == NULL)
877					continue;
878			} else {
879				continue;
880			}
881		}
882		sbp_probe_target((void *)target);
883		if (target->num_lun == 0)
884			sbp_free_target(target);
885	}
886	SBP_LOCK(sbp);
887	xpt_release_simq(sbp->sim, /*run queue*/TRUE);
888	sbp->sim->flags &= ~SIMQ_FREEZED;
889	SBP_UNLOCK(sbp);
890}
891
892#if NEED_RESPONSE
893static void
894sbp_loginres_callback(struct fw_xfer *xfer){
895	int s;
896	struct sbp_dev *sdev;
897	sdev = (struct sbp_dev *)xfer->sc;
898SBP_DEBUG(1)
899	sbp_show_sdev_info(sdev, 2);
900	printf("sbp_loginres_callback\n");
901END_DEBUG
902	/* recycle */
903	s = splfw();
904	STAILQ_INSERT_TAIL(&sdev->target->sbp->fwb.xferlist, xfer, link);
905	splx(s);
906	return;
907}
908#endif
909
910static __inline void
911sbp_xfer_free(struct fw_xfer *xfer)
912{
913	struct sbp_dev *sdev;
914	int s;
915
916	sdev = (struct sbp_dev *)xfer->sc;
917	fw_xfer_unload(xfer);
918	s = splfw();
919	SBP_LOCK(sdev->target->sbp);
920	STAILQ_INSERT_TAIL(&sdev->target->xferlist, xfer, link);
921	SBP_UNLOCK(sdev->target->sbp);
922	splx(s);
923}
924
925static void
926sbp_reset_start_callback(struct fw_xfer *xfer)
927{
928	struct sbp_dev *tsdev, *sdev = (struct sbp_dev *)xfer->sc;
929	struct sbp_target *target = sdev->target;
930	int i;
931
932	if (xfer->resp != 0) {
933		sbp_show_sdev_info(sdev, 2);
934		printf("sbp_reset_start failed: resp=%d\n", xfer->resp);
935	}
936
937	for (i = 0; i < target->num_lun; i++) {
938		tsdev = target->luns[i];
939		if (tsdev != NULL && tsdev->status == SBP_DEV_LOGIN)
940			sbp_login(tsdev);
941	}
942}
943
944static void
945sbp_reset_start(struct sbp_dev *sdev)
946{
947	struct fw_xfer *xfer;
948	struct fw_pkt *fp;
949
950SBP_DEBUG(0)
951	sbp_show_sdev_info(sdev, 2);
952	printf("sbp_reset_start\n");
953END_DEBUG
954
955	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0);
956	xfer->hand = sbp_reset_start_callback;
957	fp = &xfer->send.hdr;
958	fp->mode.wreqq.dest_hi = 0xffff;
959	fp->mode.wreqq.dest_lo = 0xf0000000 | RESET_START;
960	fp->mode.wreqq.data = htonl(0xf);
961	fw_asyreq(xfer->fc, -1, xfer);
962}
963
964static void
965sbp_mgm_callback(struct fw_xfer *xfer)
966{
967	struct sbp_dev *sdev;
968	int resp;
969
970	sdev = (struct sbp_dev *)xfer->sc;
971
972SBP_DEBUG(1)
973	sbp_show_sdev_info(sdev, 2);
974	printf("sbp_mgm_callback\n");
975END_DEBUG
976	resp = xfer->resp;
977	sbp_xfer_free(xfer);
978#if 0
979	if (resp != 0) {
980		sbp_show_sdev_info(sdev, 2);
981		printf("management ORB failed(%d) ... RESET_START\n", resp);
982		sbp_reset_start(sdev);
983	}
984#endif
985	return;
986}
987
988static struct sbp_dev *
989sbp_next_dev(struct sbp_target *target, int lun)
990{
991	struct sbp_dev **sdevp;
992	int i;
993
994	for (i = lun, sdevp = &target->luns[lun]; i < target->num_lun;
995	    i++, sdevp++)
996		if (*sdevp != NULL && (*sdevp)->status == SBP_DEV_PROBE)
997			return(*sdevp);
998	return(NULL);
999}
1000
1001#define SCAN_PRI 1
1002static void
1003sbp_cam_scan_lun(struct cam_periph *periph, union ccb *ccb)
1004{
1005	struct sbp_target *target;
1006	struct sbp_dev *sdev;
1007
1008	sdev = (struct sbp_dev *) ccb->ccb_h.ccb_sdev_ptr;
1009	target = sdev->target;
1010SBP_DEBUG(0)
1011	sbp_show_sdev_info(sdev, 2);
1012	printf("sbp_cam_scan_lun\n");
1013END_DEBUG
1014	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1015		sdev->status = SBP_DEV_ATTACHED;
1016	} else {
1017		sbp_show_sdev_info(sdev, 2);
1018		printf("scan failed\n");
1019	}
1020	sdev = sbp_next_dev(target, sdev->lun_id + 1);
1021	if (sdev == NULL) {
1022		free(ccb, M_SBP);
1023		return;
1024	}
1025	/* reuse ccb */
1026	xpt_setup_ccb(&ccb->ccb_h, sdev->path, SCAN_PRI);
1027	ccb->ccb_h.ccb_sdev_ptr = sdev;
1028	xpt_action(ccb);
1029	xpt_release_devq(sdev->path, sdev->freeze, TRUE);
1030	sdev->freeze = 1;
1031}
1032
1033static void
1034sbp_cam_scan_target(void *arg)
1035{
1036	struct sbp_target *target = (struct sbp_target *)arg;
1037	struct sbp_dev *sdev;
1038	union ccb *ccb;
1039
1040	sdev = sbp_next_dev(target, 0);
1041	if (sdev == NULL) {
1042		printf("sbp_cam_scan_target: nothing to do for target%d\n",
1043							target->target_id);
1044		return;
1045	}
1046SBP_DEBUG(0)
1047	sbp_show_sdev_info(sdev, 2);
1048	printf("sbp_cam_scan_target\n");
1049END_DEBUG
1050	ccb = malloc(sizeof(union ccb), M_SBP, M_NOWAIT | M_ZERO);
1051	if (ccb == NULL) {
1052		printf("sbp_cam_scan_target: malloc failed\n");
1053		return;
1054	}
1055	xpt_setup_ccb(&ccb->ccb_h, sdev->path, SCAN_PRI);
1056	ccb->ccb_h.func_code = XPT_SCAN_LUN;
1057	ccb->ccb_h.cbfcnp = sbp_cam_scan_lun;
1058	ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1059	ccb->crcn.flags = CAM_FLAG_NONE;
1060	ccb->ccb_h.ccb_sdev_ptr = sdev;
1061
1062	/* The scan is in progress now. */
1063	SBP_LOCK(target->sbp);
1064	xpt_action(ccb);
1065	xpt_release_devq(sdev->path, sdev->freeze, TRUE);
1066	sdev->freeze = 1;
1067	SBP_UNLOCK(target->sbp);
1068}
1069
1070static __inline void
1071sbp_scan_dev(struct sbp_dev *sdev)
1072{
1073	sdev->status = SBP_DEV_PROBE;
1074	callout_reset(&sdev->target->scan_callout, scan_delay * hz / 1000,
1075			sbp_cam_scan_target, (void *)sdev->target);
1076}
1077
1078static void
1079sbp_do_attach(struct fw_xfer *xfer)
1080{
1081	struct sbp_dev *sdev;
1082	struct sbp_target *target;
1083	struct sbp_softc *sbp;
1084
1085	sdev = (struct sbp_dev *)xfer->sc;
1086	target = sdev->target;
1087	sbp = target->sbp;
1088SBP_DEBUG(0)
1089	sbp_show_sdev_info(sdev, 2);
1090	printf("sbp_do_attach\n");
1091END_DEBUG
1092	sbp_xfer_free(xfer);
1093
1094	if (sdev->path == NULL)
1095		xpt_create_path(&sdev->path, xpt_periph,
1096			cam_sim_path(target->sbp->sim),
1097			target->target_id, sdev->lun_id);
1098
1099	/*
1100	 * Let CAM scan the bus if we are in the boot process.
1101	 * XXX xpt_scan_bus cannot detect LUN larger than 0
1102	 * if LUN 0 doesn't exists.
1103	 */
1104	if (sbp_cold > 0) {
1105		sdev->status = SBP_DEV_ATTACHED;
1106		return;
1107	}
1108
1109	sbp_scan_dev(sdev);
1110	return;
1111}
1112
1113static void
1114sbp_agent_reset_callback(struct fw_xfer *xfer)
1115{
1116	struct sbp_dev *sdev;
1117
1118	sdev = (struct sbp_dev *)xfer->sc;
1119SBP_DEBUG(1)
1120	sbp_show_sdev_info(sdev, 2);
1121	printf("%s\n", __func__);
1122END_DEBUG
1123	if (xfer->resp != 0) {
1124		sbp_show_sdev_info(sdev, 2);
1125		printf("%s: resp=%d\n", __func__, xfer->resp);
1126	}
1127
1128	sbp_xfer_free(xfer);
1129	if (sdev->path) {
1130		SBP_LOCK(sdev->target->sbp);
1131		xpt_release_devq(sdev->path, sdev->freeze, TRUE);
1132		sdev->freeze = 0;
1133		SBP_UNLOCK(sdev->target->sbp);
1134	}
1135}
1136
1137static void
1138sbp_agent_reset(struct sbp_dev *sdev)
1139{
1140	struct fw_xfer *xfer;
1141	struct fw_pkt *fp;
1142
1143SBP_DEBUG(0)
1144	sbp_show_sdev_info(sdev, 2);
1145	printf("sbp_agent_reset\n");
1146END_DEBUG
1147	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0x04);
1148	if (xfer == NULL)
1149		return;
1150	if (sdev->status == SBP_DEV_ATTACHED || sdev->status == SBP_DEV_PROBE)
1151		xfer->hand = sbp_agent_reset_callback;
1152	else
1153		xfer->hand = sbp_do_attach;
1154	fp = &xfer->send.hdr;
1155	fp->mode.wreqq.data = htonl(0xf);
1156	fw_asyreq(xfer->fc, -1, xfer);
1157	sbp_abort_all_ocbs(sdev, CAM_BDR_SENT);
1158}
1159
1160static void
1161sbp_busy_timeout_callback(struct fw_xfer *xfer)
1162{
1163	struct sbp_dev *sdev;
1164
1165	sdev = (struct sbp_dev *)xfer->sc;
1166SBP_DEBUG(1)
1167	sbp_show_sdev_info(sdev, 2);
1168	printf("sbp_busy_timeout_callback\n");
1169END_DEBUG
1170	sbp_xfer_free(xfer);
1171	sbp_agent_reset(sdev);
1172}
1173
1174static void
1175sbp_busy_timeout(struct sbp_dev *sdev)
1176{
1177	struct fw_pkt *fp;
1178	struct fw_xfer *xfer;
1179SBP_DEBUG(0)
1180	sbp_show_sdev_info(sdev, 2);
1181	printf("sbp_busy_timeout\n");
1182END_DEBUG
1183	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0);
1184
1185	xfer->hand = sbp_busy_timeout_callback;
1186	fp = &xfer->send.hdr;
1187	fp->mode.wreqq.dest_hi = 0xffff;
1188	fp->mode.wreqq.dest_lo = 0xf0000000 | BUSY_TIMEOUT;
1189	fp->mode.wreqq.data = htonl((1 << (13+12)) | 0xf);
1190	fw_asyreq(xfer->fc, -1, xfer);
1191}
1192
1193static void
1194sbp_orb_pointer_callback(struct fw_xfer *xfer)
1195{
1196	struct sbp_dev *sdev;
1197	sdev = (struct sbp_dev *)xfer->sc;
1198
1199SBP_DEBUG(1)
1200	sbp_show_sdev_info(sdev, 2);
1201	printf("%s\n", __func__);
1202END_DEBUG
1203	if (xfer->resp != 0) {
1204		/* XXX */
1205		printf("%s: xfer->resp = %d\n", __func__, xfer->resp);
1206	}
1207	sbp_xfer_free(xfer);
1208	sdev->flags &= ~ORB_POINTER_ACTIVE;
1209
1210	if ((sdev->flags & ORB_POINTER_NEED) != 0) {
1211		struct sbp_ocb *ocb;
1212
1213		sdev->flags &= ~ORB_POINTER_NEED;
1214		ocb = STAILQ_FIRST(&sdev->ocbs);
1215		if (ocb != NULL)
1216			sbp_orb_pointer(sdev, ocb);
1217	}
1218	return;
1219}
1220
1221static void
1222sbp_orb_pointer(struct sbp_dev *sdev, struct sbp_ocb *ocb)
1223{
1224	struct fw_xfer *xfer;
1225	struct fw_pkt *fp;
1226SBP_DEBUG(1)
1227	sbp_show_sdev_info(sdev, 2);
1228	printf("%s: 0x%08x\n", __func__, (uint32_t)ocb->bus_addr);
1229END_DEBUG
1230
1231	if ((sdev->flags & ORB_POINTER_ACTIVE) != 0) {
1232SBP_DEBUG(0)
1233		printf("%s: orb pointer active\n", __func__);
1234END_DEBUG
1235		sdev->flags |= ORB_POINTER_NEED;
1236		return;
1237	}
1238
1239	sdev->flags |= ORB_POINTER_ACTIVE;
1240	xfer = sbp_write_cmd(sdev, FWTCODE_WREQB, 0x08);
1241	if (xfer == NULL)
1242		return;
1243	xfer->hand = sbp_orb_pointer_callback;
1244
1245	fp = &xfer->send.hdr;
1246	fp->mode.wreqb.len = 8;
1247	fp->mode.wreqb.extcode = 0;
1248	xfer->send.payload[0] =
1249		htonl(((sdev->target->sbp->fd.fc->nodeid | FWLOCALBUS )<< 16));
1250	xfer->send.payload[1] = htonl((uint32_t)ocb->bus_addr);
1251
1252	if(fw_asyreq(xfer->fc, -1, xfer) != 0){
1253			sbp_xfer_free(xfer);
1254			ocb->ccb->ccb_h.status = CAM_REQ_INVALID;
1255			xpt_done(ocb->ccb);
1256	}
1257}
1258
1259static void
1260sbp_doorbell_callback(struct fw_xfer *xfer)
1261{
1262	struct sbp_dev *sdev;
1263	sdev = (struct sbp_dev *)xfer->sc;
1264
1265SBP_DEBUG(1)
1266	sbp_show_sdev_info(sdev, 2);
1267	printf("sbp_doorbell_callback\n");
1268END_DEBUG
1269	if (xfer->resp != 0) {
1270		/* XXX */
1271		printf("%s: xfer->resp = %d\n", __func__, xfer->resp);
1272	}
1273	sbp_xfer_free(xfer);
1274	sdev->flags &= ~ORB_DOORBELL_ACTIVE;
1275	if ((sdev->flags & ORB_DOORBELL_NEED) != 0) {
1276		sdev->flags &= ~ORB_DOORBELL_NEED;
1277		sbp_doorbell(sdev);
1278	}
1279	return;
1280}
1281
1282static void
1283sbp_doorbell(struct sbp_dev *sdev)
1284{
1285	struct fw_xfer *xfer;
1286	struct fw_pkt *fp;
1287SBP_DEBUG(1)
1288	sbp_show_sdev_info(sdev, 2);
1289	printf("sbp_doorbell\n");
1290END_DEBUG
1291
1292	if ((sdev->flags & ORB_DOORBELL_ACTIVE) != 0) {
1293		sdev->flags |= ORB_DOORBELL_NEED;
1294		return;
1295	}
1296	sdev->flags |= ORB_DOORBELL_ACTIVE;
1297	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0x10);
1298	if (xfer == NULL)
1299		return;
1300	xfer->hand = sbp_doorbell_callback;
1301	fp = &xfer->send.hdr;
1302	fp->mode.wreqq.data = htonl(0xf);
1303	fw_asyreq(xfer->fc, -1, xfer);
1304}
1305
1306static struct fw_xfer *
1307sbp_write_cmd(struct sbp_dev *sdev, int tcode, int offset)
1308{
1309	struct fw_xfer *xfer;
1310	struct fw_pkt *fp;
1311	struct sbp_target *target;
1312	int s, new = 0;
1313
1314	target = sdev->target;
1315	s = splfw();
1316	xfer = STAILQ_FIRST(&target->xferlist);
1317	if (xfer == NULL) {
1318		if (target->n_xfer > 5 /* XXX */) {
1319			printf("sbp: no more xfer for this target\n");
1320			splx(s);
1321			return(NULL);
1322		}
1323		xfer = fw_xfer_alloc_buf(M_SBP, 8, 0);
1324		if(xfer == NULL){
1325			printf("sbp: fw_xfer_alloc_buf failed\n");
1326			splx(s);
1327			return NULL;
1328		}
1329		target->n_xfer ++;
1330		if (debug)
1331			printf("sbp: alloc %d xfer\n", target->n_xfer);
1332		new = 1;
1333	} else {
1334		STAILQ_REMOVE_HEAD(&target->xferlist, link);
1335	}
1336	splx(s);
1337
1338	microtime(&xfer->tv);
1339
1340	if (new) {
1341		xfer->recv.pay_len = 0;
1342		xfer->send.spd = min(sdev->target->fwdev->speed, max_speed);
1343		xfer->fc = sdev->target->sbp->fd.fc;
1344	}
1345
1346	if (tcode == FWTCODE_WREQB)
1347		xfer->send.pay_len = 8;
1348	else
1349		xfer->send.pay_len = 0;
1350
1351	xfer->sc = (caddr_t)sdev;
1352	fp = &xfer->send.hdr;
1353	fp->mode.wreqq.dest_hi = sdev->login->cmd_hi;
1354	fp->mode.wreqq.dest_lo = sdev->login->cmd_lo + offset;
1355	fp->mode.wreqq.tlrt = 0;
1356	fp->mode.wreqq.tcode = tcode;
1357	fp->mode.wreqq.pri = 0;
1358	fp->mode.wreqq.dst = FWLOCALBUS | sdev->target->fwdev->dst;
1359
1360	return xfer;
1361
1362}
1363
1364static void
1365sbp_mgm_orb(struct sbp_dev *sdev, int func, struct sbp_ocb *aocb)
1366{
1367	struct fw_xfer *xfer;
1368	struct fw_pkt *fp;
1369	struct sbp_ocb *ocb;
1370	struct sbp_target *target;
1371	int s, nid;
1372
1373	target = sdev->target;
1374	nid = target->sbp->fd.fc->nodeid | FWLOCALBUS;
1375
1376	s = splfw();
1377	SBP_LOCK(target->sbp);
1378	if (func == ORB_FUN_RUNQUEUE) {
1379		ocb = STAILQ_FIRST(&target->mgm_ocb_queue);
1380		if (target->mgm_ocb_cur != NULL || ocb == NULL) {
1381			SBP_UNLOCK(target->sbp);
1382			splx(s);
1383			return;
1384		}
1385		STAILQ_REMOVE_HEAD(&target->mgm_ocb_queue, ocb);
1386		SBP_UNLOCK(target->sbp);
1387		goto start;
1388	}
1389	if ((ocb = sbp_get_ocb(sdev)) == NULL) {
1390		SBP_UNLOCK(target->sbp);
1391		splx(s);
1392		/* XXX */
1393		return;
1394	}
1395	SBP_UNLOCK(target->sbp);
1396	ocb->flags = OCB_ACT_MGM;
1397	ocb->sdev = sdev;
1398
1399	bzero((void *)ocb->orb, sizeof(ocb->orb));
1400	ocb->orb[6] = htonl((nid << 16) | SBP_BIND_HI);
1401	ocb->orb[7] = htonl(SBP_DEV2ADDR(target->target_id, sdev->lun_id));
1402
1403SBP_DEBUG(0)
1404	sbp_show_sdev_info(sdev, 2);
1405	printf("%s\n", orb_fun_name[(func>>16)&0xf]);
1406END_DEBUG
1407	switch (func) {
1408	case ORB_FUN_LGI:
1409		ocb->orb[0] = ocb->orb[1] = 0; /* password */
1410		ocb->orb[2] = htonl(nid << 16);
1411		ocb->orb[3] = htonl(sdev->dma.bus_addr);
1412		ocb->orb[4] = htonl(ORB_NOTIFY | sdev->lun_id);
1413		if (ex_login)
1414			ocb->orb[4] |= htonl(ORB_EXV);
1415		ocb->orb[5] = htonl(SBP_LOGIN_SIZE);
1416		fwdma_sync(&sdev->dma, BUS_DMASYNC_PREREAD);
1417		break;
1418	case ORB_FUN_ATA:
1419		ocb->orb[0] = htonl((0 << 16) | 0);
1420		ocb->orb[1] = htonl(aocb->bus_addr & 0xffffffff);
1421		/* fall through */
1422	case ORB_FUN_RCN:
1423	case ORB_FUN_LGO:
1424	case ORB_FUN_LUR:
1425	case ORB_FUN_RST:
1426	case ORB_FUN_ATS:
1427		ocb->orb[4] = htonl(ORB_NOTIFY | func | sdev->login->id);
1428		break;
1429	}
1430
1431	if (target->mgm_ocb_cur != NULL) {
1432		/* there is a standing ORB */
1433		SBP_LOCK(target->sbp);
1434		STAILQ_INSERT_TAIL(&sdev->target->mgm_ocb_queue, ocb, ocb);
1435		SBP_UNLOCK(target->sbp);
1436		splx(s);
1437		return;
1438	}
1439start:
1440	target->mgm_ocb_cur = ocb;
1441	splx(s);
1442
1443	callout_reset(&target->mgm_ocb_timeout, 5*hz,
1444				sbp_mgm_timeout, (caddr_t)ocb);
1445	xfer = sbp_write_cmd(sdev, FWTCODE_WREQB, 0);
1446	if(xfer == NULL){
1447		return;
1448	}
1449	xfer->hand = sbp_mgm_callback;
1450
1451	fp = &xfer->send.hdr;
1452	fp->mode.wreqb.dest_hi = sdev->target->mgm_hi;
1453	fp->mode.wreqb.dest_lo = sdev->target->mgm_lo;
1454	fp->mode.wreqb.len = 8;
1455	fp->mode.wreqb.extcode = 0;
1456	xfer->send.payload[0] = htonl(nid << 16);
1457	xfer->send.payload[1] = htonl(ocb->bus_addr & 0xffffffff);
1458SBP_DEBUG(0)
1459	sbp_show_sdev_info(sdev, 2);
1460	printf("mgm orb: %08x\n", (uint32_t)ocb->bus_addr);
1461END_DEBUG
1462
1463	fw_asyreq(xfer->fc, -1, xfer);
1464}
1465
1466static void
1467sbp_print_scsi_cmd(struct sbp_ocb *ocb)
1468{
1469	struct ccb_scsiio *csio;
1470
1471	csio = &ocb->ccb->csio;
1472	printf("%s:%d:%d XPT_SCSI_IO: "
1473		"cmd: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x"
1474		", flags: 0x%02x, "
1475		"%db cmd/%db data/%db sense\n",
1476		device_get_nameunit(ocb->sdev->target->sbp->fd.dev),
1477		ocb->ccb->ccb_h.target_id, ocb->ccb->ccb_h.target_lun,
1478		csio->cdb_io.cdb_bytes[0],
1479		csio->cdb_io.cdb_bytes[1],
1480		csio->cdb_io.cdb_bytes[2],
1481		csio->cdb_io.cdb_bytes[3],
1482		csio->cdb_io.cdb_bytes[4],
1483		csio->cdb_io.cdb_bytes[5],
1484		csio->cdb_io.cdb_bytes[6],
1485		csio->cdb_io.cdb_bytes[7],
1486		csio->cdb_io.cdb_bytes[8],
1487		csio->cdb_io.cdb_bytes[9],
1488		ocb->ccb->ccb_h.flags & CAM_DIR_MASK,
1489		csio->cdb_len, csio->dxfer_len,
1490		csio->sense_len);
1491}
1492
1493static void
1494sbp_scsi_status(struct sbp_status *sbp_status, struct sbp_ocb *ocb)
1495{
1496	struct sbp_cmd_status *sbp_cmd_status;
1497	struct scsi_sense_data *sense;
1498
1499	sbp_cmd_status = (struct sbp_cmd_status *)sbp_status->data;
1500	sense = &ocb->ccb->csio.sense_data;
1501
1502SBP_DEBUG(0)
1503	sbp_print_scsi_cmd(ocb);
1504	/* XXX need decode status */
1505	sbp_show_sdev_info(ocb->sdev, 2);
1506	printf("SCSI status %x sfmt %x valid %x key %x code %x qlfr %x len %d\n",
1507		sbp_cmd_status->status,
1508		sbp_cmd_status->sfmt,
1509		sbp_cmd_status->valid,
1510		sbp_cmd_status->s_key,
1511		sbp_cmd_status->s_code,
1512		sbp_cmd_status->s_qlfr,
1513		sbp_status->len
1514	);
1515END_DEBUG
1516
1517	switch (sbp_cmd_status->status) {
1518	case SCSI_STATUS_CHECK_COND:
1519	case SCSI_STATUS_BUSY:
1520	case SCSI_STATUS_CMD_TERMINATED:
1521		if(sbp_cmd_status->sfmt == SBP_SFMT_CURR){
1522			sense->error_code = SSD_CURRENT_ERROR;
1523		}else{
1524			sense->error_code = SSD_DEFERRED_ERROR;
1525		}
1526		if(sbp_cmd_status->valid)
1527			sense->error_code |= SSD_ERRCODE_VALID;
1528		sense->flags = sbp_cmd_status->s_key;
1529		if(sbp_cmd_status->mark)
1530			sense->flags |= SSD_FILEMARK;
1531		if(sbp_cmd_status->eom)
1532			sense->flags |= SSD_EOM;
1533		if(sbp_cmd_status->ill_len)
1534			sense->flags |= SSD_ILI;
1535
1536		bcopy(&sbp_cmd_status->info, &sense->info[0], 4);
1537
1538		if (sbp_status->len <= 1)
1539			/* XXX not scsi status. shouldn't be happened */
1540			sense->extra_len = 0;
1541		else if (sbp_status->len <= 4)
1542			/* add_sense_code(_qual), info, cmd_spec_info */
1543			sense->extra_len = 6;
1544		else
1545			/* fru, sense_key_spec */
1546			sense->extra_len = 10;
1547
1548		bcopy(&sbp_cmd_status->cdb, &sense->cmd_spec_info[0], 4);
1549
1550		sense->add_sense_code = sbp_cmd_status->s_code;
1551		sense->add_sense_code_qual = sbp_cmd_status->s_qlfr;
1552		sense->fru = sbp_cmd_status->fru;
1553
1554		bcopy(&sbp_cmd_status->s_keydep[0],
1555		    &sense->sense_key_spec[0], 3);
1556
1557		ocb->ccb->csio.scsi_status = sbp_cmd_status->status;;
1558		ocb->ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
1559							| CAM_AUTOSNS_VALID;
1560/*
1561{
1562		uint8_t j, *tmp;
1563		tmp = sense;
1564		for( j = 0 ; j < 32 ; j+=8){
1565			printf("sense %02x%02x %02x%02x %02x%02x %02x%02x\n",
1566				tmp[j], tmp[j+1], tmp[j+2], tmp[j+3],
1567				tmp[j+4], tmp[j+5], tmp[j+6], tmp[j+7]);
1568		}
1569
1570}
1571*/
1572		break;
1573	default:
1574		sbp_show_sdev_info(ocb->sdev, 2);
1575		printf("sbp_scsi_status: unknown scsi status 0x%x\n",
1576						sbp_cmd_status->status);
1577	}
1578}
1579
1580static void
1581sbp_fix_inq_data(struct sbp_ocb *ocb)
1582{
1583	union ccb *ccb;
1584	struct sbp_dev *sdev;
1585	struct scsi_inquiry_data *inq;
1586
1587	ccb = ocb->ccb;
1588	sdev = ocb->sdev;
1589
1590	if (ccb->csio.cdb_io.cdb_bytes[1] & SI_EVPD)
1591		return;
1592SBP_DEBUG(1)
1593	sbp_show_sdev_info(sdev, 2);
1594	printf("sbp_fix_inq_data\n");
1595END_DEBUG
1596	inq = (struct scsi_inquiry_data *) ccb->csio.data_ptr;
1597	switch (SID_TYPE(inq)) {
1598	case T_DIRECT:
1599#if 0
1600		/*
1601		 * XXX Convert Direct Access device to RBC.
1602		 * I've never seen FireWire DA devices which support READ_6.
1603		 */
1604		if (SID_TYPE(inq) == T_DIRECT)
1605			inq->device |= T_RBC; /*  T_DIRECT == 0 */
1606#endif
1607		/* fall through */
1608	case T_RBC:
1609		/*
1610		 * Override vendor/product/revision information.
1611		 * Some devices sometimes return strange strings.
1612		 */
1613#if 1
1614		bcopy(sdev->vendor, inq->vendor, sizeof(inq->vendor));
1615		bcopy(sdev->product, inq->product, sizeof(inq->product));
1616		bcopy(sdev->revision+2, inq->revision, sizeof(inq->revision));
1617#endif
1618		break;
1619	}
1620	/*
1621	 * Force to enable/disable tagged queuing.
1622	 * XXX CAM also checks SCP_QUEUE_DQUE flag in the control mode page.
1623	 */
1624	if (sbp_tags > 0)
1625		inq->flags |= SID_CmdQue;
1626	else if (sbp_tags < 0)
1627		inq->flags &= ~SID_CmdQue;
1628
1629}
1630
1631static void
1632sbp_recv1(struct fw_xfer *xfer)
1633{
1634	struct fw_pkt *rfp;
1635#if NEED_RESPONSE
1636	struct fw_pkt *sfp;
1637#endif
1638	struct sbp_softc *sbp;
1639	struct sbp_dev *sdev;
1640	struct sbp_ocb *ocb;
1641	struct sbp_login_res *login_res = NULL;
1642	struct sbp_status *sbp_status;
1643	struct sbp_target *target;
1644	int	orb_fun, status_valid0, status_valid, t, l, reset_agent = 0;
1645	uint32_t addr;
1646/*
1647	uint32_t *ld;
1648	ld = xfer->recv.buf;
1649printf("sbp %x %d %d %08x %08x %08x %08x\n",
1650			xfer->resp, xfer->recv.len, xfer->recv.off, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
1651printf("sbp %08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
1652printf("sbp %08x %08x %08x %08x\n", ntohl(ld[8]), ntohl(ld[9]), ntohl(ld[10]), ntohl(ld[11]));
1653*/
1654	sbp = (struct sbp_softc *)xfer->sc;
1655	if (xfer->resp != 0){
1656		printf("sbp_recv: xfer->resp = %d\n", xfer->resp);
1657		goto done0;
1658	}
1659	if (xfer->recv.payload == NULL){
1660		printf("sbp_recv: xfer->recv.payload == NULL\n");
1661		goto done0;
1662	}
1663	rfp = &xfer->recv.hdr;
1664	if(rfp->mode.wreqb.tcode != FWTCODE_WREQB){
1665		printf("sbp_recv: tcode = %d\n", rfp->mode.wreqb.tcode);
1666		goto done0;
1667	}
1668	sbp_status = (struct sbp_status *)xfer->recv.payload;
1669	addr = rfp->mode.wreqb.dest_lo;
1670SBP_DEBUG(2)
1671	printf("received address 0x%x\n", addr);
1672END_DEBUG
1673	t = SBP_ADDR2TRG(addr);
1674	if (t >= SBP_NUM_TARGETS) {
1675		device_printf(sbp->fd.dev,
1676			"sbp_recv1: invalid target %d\n", t);
1677		goto done0;
1678	}
1679	target = &sbp->targets[t];
1680	l = SBP_ADDR2LUN(addr);
1681	if (l >= target->num_lun || target->luns[l] == NULL) {
1682		device_printf(sbp->fd.dev,
1683			"sbp_recv1: invalid lun %d (target=%d)\n", l, t);
1684		goto done0;
1685	}
1686	sdev = target->luns[l];
1687
1688	ocb = NULL;
1689	switch (sbp_status->src) {
1690	case 0:
1691	case 1:
1692		/* check mgm_ocb_cur first */
1693		ocb  = target->mgm_ocb_cur;
1694		if (ocb != NULL) {
1695			if (OCB_MATCH(ocb, sbp_status)) {
1696				callout_stop(&target->mgm_ocb_timeout);
1697				target->mgm_ocb_cur = NULL;
1698				break;
1699			}
1700		}
1701		ocb = sbp_dequeue_ocb(sdev, sbp_status);
1702		if (ocb == NULL) {
1703			sbp_show_sdev_info(sdev, 2);
1704#if defined(__DragonFly__) || __FreeBSD_version < 500000
1705			printf("No ocb(%lx) on the queue\n",
1706#else
1707			printf("No ocb(%x) on the queue\n",
1708#endif
1709					ntohl(sbp_status->orb_lo));
1710		}
1711		break;
1712	case 2:
1713		/* unsolicit */
1714		sbp_show_sdev_info(sdev, 2);
1715		printf("unsolicit status received\n");
1716		break;
1717	default:
1718		sbp_show_sdev_info(sdev, 2);
1719		printf("unknown sbp_status->src\n");
1720	}
1721
1722	status_valid0 = (sbp_status->src < 2
1723			&& sbp_status->resp == ORB_RES_CMPL
1724			&& sbp_status->dead == 0);
1725	status_valid = (status_valid0 && sbp_status->status == 0);
1726
1727	if (!status_valid0 || debug > 2){
1728		int status;
1729SBP_DEBUG(0)
1730		sbp_show_sdev_info(sdev, 2);
1731		printf("ORB status src:%x resp:%x dead:%x"
1732#if defined(__DragonFly__) || __FreeBSD_version < 500000
1733				" len:%x stat:%x orb:%x%08lx\n",
1734#else
1735				" len:%x stat:%x orb:%x%08x\n",
1736#endif
1737			sbp_status->src, sbp_status->resp, sbp_status->dead,
1738			sbp_status->len, sbp_status->status,
1739			ntohs(sbp_status->orb_hi), ntohl(sbp_status->orb_lo));
1740END_DEBUG
1741		sbp_show_sdev_info(sdev, 2);
1742		status = sbp_status->status;
1743		switch(sbp_status->resp) {
1744		case 0:
1745			if (status > MAX_ORB_STATUS0)
1746				printf("%s\n", orb_status0[MAX_ORB_STATUS0]);
1747			else
1748				printf("%s\n", orb_status0[status]);
1749			break;
1750		case 1:
1751			printf("Obj: %s, Error: %s\n",
1752				orb_status1_object[(status>>6) & 3],
1753				orb_status1_serial_bus_error[status & 0xf]);
1754			break;
1755		case 2:
1756			printf("Illegal request\n");
1757			break;
1758		case 3:
1759			printf("Vendor dependent\n");
1760			break;
1761		default:
1762			printf("unknown respose code %d\n", sbp_status->resp);
1763		}
1764	}
1765
1766	/* we have to reset the fetch agent if it's dead */
1767	if (sbp_status->dead) {
1768		if (sdev->path) {
1769			SBP_LOCK(sbp);
1770			xpt_freeze_devq(sdev->path, 1);
1771			sdev->freeze ++;
1772			SBP_UNLOCK(sbp);
1773		}
1774		reset_agent = 1;
1775	}
1776
1777	if (ocb == NULL)
1778		goto done;
1779
1780	switch(ntohl(ocb->orb[4]) & ORB_FMT_MSK){
1781	case ORB_FMT_NOP:
1782		break;
1783	case ORB_FMT_VED:
1784		break;
1785	case ORB_FMT_STD:
1786		switch(ocb->flags) {
1787		case OCB_ACT_MGM:
1788			orb_fun = ntohl(ocb->orb[4]) & ORB_FUN_MSK;
1789			reset_agent = 0;
1790			switch(orb_fun) {
1791			case ORB_FUN_LGI:
1792				fwdma_sync(&sdev->dma, BUS_DMASYNC_POSTREAD);
1793				login_res = sdev->login;
1794				login_res->len = ntohs(login_res->len);
1795				login_res->id = ntohs(login_res->id);
1796				login_res->cmd_hi = ntohs(login_res->cmd_hi);
1797				login_res->cmd_lo = ntohl(login_res->cmd_lo);
1798				if (status_valid) {
1799SBP_DEBUG(0)
1800sbp_show_sdev_info(sdev, 2);
1801printf("login: len %d, ID %d, cmd %08x%08x, recon_hold %d\n", login_res->len, login_res->id, login_res->cmd_hi, login_res->cmd_lo, ntohs(login_res->recon_hold));
1802END_DEBUG
1803					sbp_busy_timeout(sdev);
1804				} else {
1805					/* forgot logout? */
1806					sbp_show_sdev_info(sdev, 2);
1807					printf("login failed\n");
1808					sdev->status = SBP_DEV_RESET;
1809				}
1810				break;
1811			case ORB_FUN_RCN:
1812				login_res = sdev->login;
1813				if (status_valid) {
1814SBP_DEBUG(0)
1815sbp_show_sdev_info(sdev, 2);
1816printf("reconnect: len %d, ID %d, cmd %08x%08x\n", login_res->len, login_res->id, login_res->cmd_hi, login_res->cmd_lo);
1817END_DEBUG
1818#if 1
1819					if (sdev->status == SBP_DEV_ATTACHED)
1820						sbp_scan_dev(sdev);
1821					else
1822						sbp_agent_reset(sdev);
1823#else
1824					sdev->status = SBP_DEV_ATTACHED;
1825					sbp_mgm_orb(sdev, ORB_FUN_ATS, NULL);
1826#endif
1827				} else {
1828					/* reconnection hold time exceed? */
1829SBP_DEBUG(0)
1830					sbp_show_sdev_info(sdev, 2);
1831					printf("reconnect failed\n");
1832END_DEBUG
1833					sbp_login(sdev);
1834				}
1835				break;
1836			case ORB_FUN_LGO:
1837				sdev->status = SBP_DEV_RESET;
1838				break;
1839			case ORB_FUN_RST:
1840				sbp_busy_timeout(sdev);
1841				break;
1842			case ORB_FUN_LUR:
1843			case ORB_FUN_ATA:
1844			case ORB_FUN_ATS:
1845				sbp_agent_reset(sdev);
1846				break;
1847			default:
1848				sbp_show_sdev_info(sdev, 2);
1849				printf("unknown function %d\n", orb_fun);
1850				break;
1851			}
1852			sbp_mgm_orb(sdev, ORB_FUN_RUNQUEUE, NULL);
1853			break;
1854		case OCB_ACT_CMD:
1855			sdev->timeout = 0;
1856			if(ocb->ccb != NULL){
1857				union ccb *ccb;
1858/*
1859				uint32_t *ld;
1860				ld = ocb->ccb->csio.data_ptr;
1861				if(ld != NULL && ocb->ccb->csio.dxfer_len != 0)
1862					printf("ptr %08x %08x %08x %08x\n", ld[0], ld[1], ld[2], ld[3]);
1863				else
1864					printf("ptr NULL\n");
1865printf("len %d\n", sbp_status->len);
1866*/
1867				ccb = ocb->ccb;
1868				if(sbp_status->len > 1){
1869					sbp_scsi_status(sbp_status, ocb);
1870				}else{
1871					if(sbp_status->resp != ORB_RES_CMPL){
1872						ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1873					}else{
1874						ccb->ccb_h.status = CAM_REQ_CMP;
1875					}
1876				}
1877				/* fix up inq data */
1878				if (ccb->csio.cdb_io.cdb_bytes[0] == INQUIRY)
1879					sbp_fix_inq_data(ocb);
1880				SBP_LOCK(sbp);
1881				xpt_done(ccb);
1882				SBP_UNLOCK(sbp);
1883			}
1884			break;
1885		default:
1886			break;
1887		}
1888	}
1889
1890	if (!use_doorbell)
1891		sbp_free_ocb(sdev, ocb);
1892done:
1893	if (reset_agent)
1894		sbp_agent_reset(sdev);
1895
1896done0:
1897	xfer->recv.pay_len = SBP_RECV_LEN;
1898/* The received packet is usually small enough to be stored within
1899 * the buffer. In that case, the controller return ack_complete and
1900 * no respose is necessary.
1901 *
1902 * XXX fwohci.c and firewire.c should inform event_code such as
1903 * ack_complete or ack_pending to upper driver.
1904 */
1905#if NEED_RESPONSE
1906	xfer->send.off = 0;
1907	sfp = (struct fw_pkt *)xfer->send.buf;
1908	sfp->mode.wres.dst = rfp->mode.wreqb.src;
1909	xfer->dst = sfp->mode.wres.dst;
1910	xfer->spd = min(sdev->target->fwdev->speed, max_speed);
1911	xfer->hand = sbp_loginres_callback;
1912
1913	sfp->mode.wres.tlrt = rfp->mode.wreqb.tlrt;
1914	sfp->mode.wres.tcode = FWTCODE_WRES;
1915	sfp->mode.wres.rtcode = 0;
1916	sfp->mode.wres.pri = 0;
1917
1918	fw_asyreq(xfer->fc, -1, xfer);
1919#else
1920	/* recycle */
1921	STAILQ_INSERT_TAIL(&sbp->fwb.xferlist, xfer, link);
1922#endif
1923
1924	return;
1925
1926}
1927
1928static void
1929sbp_recv(struct fw_xfer *xfer)
1930{
1931	int s;
1932
1933	s = splcam();
1934	sbp_recv1(xfer);
1935	splx(s);
1936}
1937/*
1938 * sbp_attach()
1939 */
1940static int
1941sbp_attach(device_t dev)
1942{
1943	struct sbp_softc *sbp;
1944	struct cam_devq *devq;
1945	struct firewire_comm *fc;
1946	int i, s, error;
1947
1948	if (DFLTPHYS > SBP_MAXPHYS)
1949		device_printf(dev, "Warning, DFLTPHYS(%dKB) is larger than "
1950			"SBP_MAXPHYS(%dKB).\n", DFLTPHYS / 1024,
1951			SBP_MAXPHYS / 1024);
1952
1953	if (!firewire_phydma_enable)
1954		device_printf(dev, "Warning, hw.firewire.phydma_enable must be 1 "
1955			"for SBP over FireWire.\n");
1956SBP_DEBUG(0)
1957	printf("sbp_attach (cold=%d)\n", cold);
1958END_DEBUG
1959
1960	if (cold)
1961		sbp_cold ++;
1962	sbp = ((struct sbp_softc *)device_get_softc(dev));
1963	bzero(sbp, sizeof(struct sbp_softc));
1964	sbp->fd.dev = dev;
1965	sbp->fd.fc = fc = device_get_ivars(dev);
1966	mtx_init(&sbp->mtx, "sbp", NULL, MTX_DEF);
1967
1968	if (max_speed < 0)
1969		max_speed = fc->speed;
1970
1971	error = bus_dma_tag_create(/*parent*/fc->dmat,
1972				/* XXX shoud be 4 for sane backend? */
1973				/*alignment*/1,
1974				/*boundary*/0,
1975				/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
1976				/*highaddr*/BUS_SPACE_MAXADDR,
1977				/*filter*/NULL, /*filterarg*/NULL,
1978				/*maxsize*/0x100000, /*nsegments*/SBP_IND_MAX,
1979				/*maxsegsz*/SBP_SEG_MAX,
1980				/*flags*/BUS_DMA_ALLOCNOW,
1981#if defined(__FreeBSD__) && __FreeBSD_version >= 501102
1982				/*lockfunc*/busdma_lock_mutex,
1983				/*lockarg*/&sbp->mtx,
1984#endif
1985				&sbp->dmat);
1986	if (error != 0) {
1987		printf("sbp_attach: Could not allocate DMA tag "
1988			"- error %d\n", error);
1989			return (ENOMEM);
1990	}
1991
1992	devq = cam_simq_alloc(/*maxopenings*/SBP_NUM_OCB);
1993	if (devq == NULL)
1994		return (ENXIO);
1995
1996	for( i = 0 ; i < SBP_NUM_TARGETS ; i++){
1997		sbp->targets[i].fwdev = NULL;
1998		sbp->targets[i].luns = NULL;
1999	}
2000
2001	sbp->sim = cam_sim_alloc(sbp_action, sbp_poll, "sbp", sbp,
2002				 device_get_unit(dev),
2003				 &sbp->mtx,
2004				 /*untagged*/ 1,
2005				 /*tagged*/ SBP_QUEUE_LEN - 1,
2006				 devq);
2007
2008	if (sbp->sim == NULL) {
2009		cam_simq_free(devq);
2010		return (ENXIO);
2011	}
2012
2013	SBP_LOCK(sbp);
2014	if (xpt_bus_register(sbp->sim, /*bus*/0) != CAM_SUCCESS)
2015		goto fail;
2016
2017	if (xpt_create_path(&sbp->path, xpt_periph, cam_sim_path(sbp->sim),
2018	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2019		xpt_bus_deregister(cam_sim_path(sbp->sim));
2020		goto fail;
2021	}
2022	SBP_UNLOCK(sbp);
2023
2024	/* We reserve 16 bit space (4 bytes X 64 targets X 256 luns) */
2025	sbp->fwb.start = ((u_int64_t)SBP_BIND_HI << 32) | SBP_DEV2ADDR(0, 0);
2026	sbp->fwb.end = sbp->fwb.start + 0xffff;
2027	/* pre-allocate xfer */
2028	STAILQ_INIT(&sbp->fwb.xferlist);
2029	fw_xferlist_add(&sbp->fwb.xferlist, M_SBP,
2030	    /*send*/ 0, /*recv*/ SBP_RECV_LEN, SBP_NUM_OCB/2,
2031	    fc, (void *)sbp, sbp_recv);
2032
2033	fw_bindadd(fc, &sbp->fwb);
2034
2035	sbp->fd.post_busreset = sbp_post_busreset;
2036	sbp->fd.post_explore = sbp_post_explore;
2037
2038	if (fc->status != -1) {
2039		s = splfw();
2040		sbp_post_busreset((void *)sbp);
2041		sbp_post_explore((void *)sbp);
2042		splx(s);
2043	}
2044	SBP_LOCK(sbp);
2045	xpt_async(AC_BUS_RESET, sbp->path, /*arg*/ NULL);
2046	SBP_UNLOCK(sbp);
2047
2048	return (0);
2049fail:
2050	SBP_UNLOCK(sbp);
2051	cam_sim_free(sbp->sim, /*free_devq*/TRUE);
2052	return (ENXIO);
2053}
2054
2055static int
2056sbp_logout_all(struct sbp_softc *sbp)
2057{
2058	struct sbp_target *target;
2059	struct sbp_dev *sdev;
2060	int i, j;
2061
2062SBP_DEBUG(0)
2063	printf("sbp_logout_all\n");
2064END_DEBUG
2065	for (i = 0 ; i < SBP_NUM_TARGETS ; i ++) {
2066		target = &sbp->targets[i];
2067		if (target->luns == NULL)
2068			continue;
2069		for (j = 0; j < target->num_lun; j++) {
2070			sdev = target->luns[j];
2071			if (sdev == NULL)
2072				continue;
2073			callout_stop(&sdev->login_callout);
2074			if (sdev->status >= SBP_DEV_TOATTACH &&
2075					sdev->status <= SBP_DEV_ATTACHED)
2076				sbp_mgm_orb(sdev, ORB_FUN_LGO, NULL);
2077		}
2078	}
2079
2080	return 0;
2081}
2082
2083static int
2084sbp_shutdown(device_t dev)
2085{
2086	struct sbp_softc *sbp = ((struct sbp_softc *)device_get_softc(dev));
2087
2088	sbp_logout_all(sbp);
2089	return (0);
2090}
2091
2092static void
2093sbp_free_sdev(struct sbp_dev *sdev)
2094{
2095	int i;
2096
2097	if (sdev == NULL)
2098		return;
2099	for (i = 0; i < SBP_QUEUE_LEN; i++)
2100		bus_dmamap_destroy(sdev->target->sbp->dmat,
2101		    sdev->ocb[i].dmamap);
2102	fwdma_free(sdev->target->sbp->fd.fc, &sdev->dma);
2103	free(sdev, M_SBP);
2104}
2105
2106static void
2107sbp_free_target(struct sbp_target *target)
2108{
2109	struct sbp_softc *sbp;
2110	struct fw_xfer *xfer, *next;
2111	int i;
2112
2113	if (target->luns == NULL)
2114		return;
2115	callout_stop(&target->mgm_ocb_timeout);
2116	sbp = target->sbp;
2117	for (i = 0; i < target->num_lun; i++)
2118		sbp_free_sdev(target->luns[i]);
2119
2120	for (xfer = STAILQ_FIRST(&target->xferlist);
2121			xfer != NULL; xfer = next) {
2122		next = STAILQ_NEXT(xfer, link);
2123		fw_xfer_free_buf(xfer);
2124	}
2125	STAILQ_INIT(&target->xferlist);
2126	free(target->luns, M_SBP);
2127	target->num_lun = 0;;
2128	target->luns = NULL;
2129	target->fwdev = NULL;
2130}
2131
2132static int
2133sbp_detach(device_t dev)
2134{
2135	struct sbp_softc *sbp = ((struct sbp_softc *)device_get_softc(dev));
2136	struct firewire_comm *fc = sbp->fd.fc;
2137	int i;
2138
2139SBP_DEBUG(0)
2140	printf("sbp_detach\n");
2141END_DEBUG
2142
2143	for (i = 0; i < SBP_NUM_TARGETS; i ++)
2144		sbp_cam_detach_target(&sbp->targets[i]);
2145
2146	SBP_LOCK(sbp);
2147	xpt_async(AC_LOST_DEVICE, sbp->path, NULL);
2148	xpt_free_path(sbp->path);
2149	xpt_bus_deregister(cam_sim_path(sbp->sim));
2150	cam_sim_free(sbp->sim, /*free_devq*/ TRUE);
2151	SBP_UNLOCK(sbp);
2152
2153	sbp_logout_all(sbp);
2154
2155	/* XXX wait for logout completion */
2156	pause("sbpdtc", hz/2);
2157
2158	for (i = 0 ; i < SBP_NUM_TARGETS ; i ++)
2159		sbp_free_target(&sbp->targets[i]);
2160
2161	fw_bindremove(fc, &sbp->fwb);
2162	fw_xferlist_remove(&sbp->fwb.xferlist);
2163
2164	bus_dma_tag_destroy(sbp->dmat);
2165	mtx_destroy(&sbp->mtx);
2166
2167	return (0);
2168}
2169
2170static void
2171sbp_cam_detach_sdev(struct sbp_dev *sdev)
2172{
2173	if (sdev == NULL)
2174		return;
2175	if (sdev->status == SBP_DEV_DEAD)
2176		return;
2177	if (sdev->status == SBP_DEV_RESET)
2178		return;
2179	sbp_abort_all_ocbs(sdev, CAM_DEV_NOT_THERE);
2180	if (sdev->path) {
2181		SBP_LOCK(sdev->target->sbp);
2182		xpt_release_devq(sdev->path,
2183				 sdev->freeze, TRUE);
2184		sdev->freeze = 0;
2185		xpt_async(AC_LOST_DEVICE, sdev->path, NULL);
2186		xpt_free_path(sdev->path);
2187		sdev->path = NULL;
2188		SBP_UNLOCK(sdev->target->sbp);
2189	}
2190}
2191
2192static void
2193sbp_cam_detach_target(struct sbp_target *target)
2194{
2195	int i;
2196
2197	if (target->luns != NULL) {
2198SBP_DEBUG(0)
2199		printf("sbp_detach_target %d\n", target->target_id);
2200END_DEBUG
2201		callout_stop(&target->scan_callout);
2202		for (i = 0; i < target->num_lun; i++)
2203			sbp_cam_detach_sdev(target->luns[i]);
2204	}
2205}
2206
2207static void
2208sbp_target_reset(struct sbp_dev *sdev, int method)
2209{
2210	int i;
2211	struct sbp_target *target = sdev->target;
2212	struct sbp_dev *tsdev;
2213
2214	for (i = 0; i < target->num_lun; i++) {
2215		tsdev = target->luns[i];
2216		if (tsdev == NULL)
2217			continue;
2218		if (tsdev->status == SBP_DEV_DEAD)
2219			continue;
2220		if (tsdev->status == SBP_DEV_RESET)
2221			continue;
2222		SBP_LOCK(target->sbp);
2223		xpt_freeze_devq(tsdev->path, 1);
2224		tsdev->freeze ++;
2225		SBP_UNLOCK(target->sbp);
2226		sbp_abort_all_ocbs(tsdev, CAM_CMD_TIMEOUT);
2227		if (method == 2)
2228			tsdev->status = SBP_DEV_LOGIN;
2229	}
2230	switch(method) {
2231	case 1:
2232		printf("target reset\n");
2233		sbp_mgm_orb(sdev, ORB_FUN_RST, NULL);
2234		break;
2235	case 2:
2236		printf("reset start\n");
2237		sbp_reset_start(sdev);
2238		break;
2239	}
2240
2241}
2242
2243static void
2244sbp_mgm_timeout(void *arg)
2245{
2246	struct sbp_ocb *ocb = (struct sbp_ocb *)arg;
2247	struct sbp_dev *sdev = ocb->sdev;
2248	struct sbp_target *target = sdev->target;
2249
2250	sbp_show_sdev_info(sdev, 2);
2251	printf("request timeout(mgm orb:0x%08x) ... ",
2252	    (uint32_t)ocb->bus_addr);
2253	target->mgm_ocb_cur = NULL;
2254	sbp_free_ocb(sdev, ocb);
2255#if 0
2256	/* XXX */
2257	printf("run next request\n");
2258	sbp_mgm_orb(sdev, ORB_FUN_RUNQUEUE, NULL);
2259#endif
2260#if 1
2261	printf("reset start\n");
2262	sbp_reset_start(sdev);
2263#endif
2264}
2265
2266static void
2267sbp_timeout(void *arg)
2268{
2269	struct sbp_ocb *ocb = (struct sbp_ocb *)arg;
2270	struct sbp_dev *sdev = ocb->sdev;
2271
2272	sbp_show_sdev_info(sdev, 2);
2273	printf("request timeout(cmd orb:0x%08x) ... ",
2274	    (uint32_t)ocb->bus_addr);
2275
2276	sdev->timeout ++;
2277	switch(sdev->timeout) {
2278	case 1:
2279		printf("agent reset\n");
2280		SBP_LOCK(sdev->target->sbp);
2281		xpt_freeze_devq(sdev->path, 1);
2282		sdev->freeze ++;
2283		SBP_UNLOCK(sdev->target->sbp);
2284		sbp_abort_all_ocbs(sdev, CAM_CMD_TIMEOUT);
2285		sbp_agent_reset(sdev);
2286		break;
2287	case 2:
2288	case 3:
2289		sbp_target_reset(sdev, sdev->timeout - 1);
2290		break;
2291#if 0
2292	default:
2293		/* XXX give up */
2294		sbp_cam_detach_target(target);
2295		if (target->luns != NULL)
2296			free(target->luns, M_SBP);
2297		target->num_lun = 0;;
2298		target->luns = NULL;
2299		target->fwdev = NULL;
2300#endif
2301	}
2302}
2303
2304static void
2305sbp_action1(struct cam_sim *sim, union ccb *ccb)
2306{
2307
2308	struct sbp_softc *sbp = (struct sbp_softc *)sim->softc;
2309	struct sbp_target *target = NULL;
2310	struct sbp_dev *sdev = NULL;
2311
2312	/* target:lun -> sdev mapping */
2313	if (sbp != NULL
2314			&& ccb->ccb_h.target_id != CAM_TARGET_WILDCARD
2315			&& ccb->ccb_h.target_id < SBP_NUM_TARGETS) {
2316		target = &sbp->targets[ccb->ccb_h.target_id];
2317		if (target->fwdev != NULL
2318				&& ccb->ccb_h.target_lun != CAM_LUN_WILDCARD
2319				&& ccb->ccb_h.target_lun < target->num_lun) {
2320			sdev = target->luns[ccb->ccb_h.target_lun];
2321			if (sdev != NULL && sdev->status != SBP_DEV_ATTACHED &&
2322				sdev->status != SBP_DEV_PROBE)
2323				sdev = NULL;
2324		}
2325	}
2326
2327SBP_DEBUG(1)
2328	if (sdev == NULL)
2329		printf("invalid target %d lun %d\n",
2330			ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2331END_DEBUG
2332
2333	switch (ccb->ccb_h.func_code) {
2334	case XPT_SCSI_IO:
2335	case XPT_RESET_DEV:
2336	case XPT_GET_TRAN_SETTINGS:
2337	case XPT_SET_TRAN_SETTINGS:
2338	case XPT_CALC_GEOMETRY:
2339		if (sdev == NULL) {
2340SBP_DEBUG(1)
2341			printf("%s:%d:%d:func_code 0x%04x: "
2342				"Invalid target (target needed)\n",
2343				device_get_nameunit(sbp->fd.dev),
2344				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2345				ccb->ccb_h.func_code);
2346END_DEBUG
2347
2348			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2349			xpt_done(ccb);
2350			return;
2351		}
2352		break;
2353	case XPT_PATH_INQ:
2354	case XPT_NOOP:
2355		/* The opcodes sometimes aimed at a target (sc is valid),
2356		 * sometimes aimed at the SIM (sc is invalid and target is
2357		 * CAM_TARGET_WILDCARD)
2358		 */
2359		if (sbp == NULL &&
2360			ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
2361SBP_DEBUG(0)
2362			printf("%s:%d:%d func_code 0x%04x: "
2363				"Invalid target (no wildcard)\n",
2364				device_get_nameunit(sbp->fd.dev),
2365				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2366				ccb->ccb_h.func_code);
2367END_DEBUG
2368			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2369			xpt_done(ccb);
2370			return;
2371		}
2372		break;
2373	default:
2374		/* XXX Hm, we should check the input parameters */
2375		break;
2376	}
2377
2378	switch (ccb->ccb_h.func_code) {
2379	case XPT_SCSI_IO:
2380	{
2381		struct ccb_scsiio *csio;
2382		struct sbp_ocb *ocb;
2383		int speed;
2384		void *cdb;
2385
2386		csio = &ccb->csio;
2387		mtx_assert(sim->mtx, MA_OWNED);
2388
2389SBP_DEBUG(2)
2390		printf("%s:%d:%d XPT_SCSI_IO: "
2391			"cmd: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x"
2392			", flags: 0x%02x, "
2393			"%db cmd/%db data/%db sense\n",
2394			device_get_nameunit(sbp->fd.dev),
2395			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2396			csio->cdb_io.cdb_bytes[0],
2397			csio->cdb_io.cdb_bytes[1],
2398			csio->cdb_io.cdb_bytes[2],
2399			csio->cdb_io.cdb_bytes[3],
2400			csio->cdb_io.cdb_bytes[4],
2401			csio->cdb_io.cdb_bytes[5],
2402			csio->cdb_io.cdb_bytes[6],
2403			csio->cdb_io.cdb_bytes[7],
2404			csio->cdb_io.cdb_bytes[8],
2405			csio->cdb_io.cdb_bytes[9],
2406			ccb->ccb_h.flags & CAM_DIR_MASK,
2407			csio->cdb_len, csio->dxfer_len,
2408			csio->sense_len);
2409END_DEBUG
2410		if(sdev == NULL){
2411			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2412			xpt_done(ccb);
2413			return;
2414		}
2415#if 0
2416		/* if we are in probe stage, pass only probe commands */
2417		if (sdev->status == SBP_DEV_PROBE) {
2418			char *name;
2419			name = xpt_path_periph(ccb->ccb_h.path)->periph_name;
2420			printf("probe stage, periph name: %s\n", name);
2421			if (strcmp(name, "probe") != 0) {
2422				ccb->ccb_h.status = CAM_REQUEUE_REQ;
2423				xpt_done(ccb);
2424				return;
2425			}
2426		}
2427#endif
2428		if ((ocb = sbp_get_ocb(sdev)) == NULL) {
2429			ccb->ccb_h.status = CAM_REQUEUE_REQ;
2430			if (sdev->freeze == 0) {
2431				SBP_LOCK(sdev->target->sbp);
2432				xpt_freeze_devq(sdev->path, 1);
2433				sdev->freeze ++;
2434				SBP_UNLOCK(sdev->target->sbp);
2435			}
2436			xpt_done(ccb);
2437			return;
2438		}
2439
2440		ocb->flags = OCB_ACT_CMD;
2441		ocb->sdev = sdev;
2442		ocb->ccb = ccb;
2443		ccb->ccb_h.ccb_sdev_ptr = sdev;
2444		ocb->orb[0] = htonl(1 << 31);
2445		ocb->orb[1] = 0;
2446		ocb->orb[2] = htonl(((sbp->fd.fc->nodeid | FWLOCALBUS )<< 16) );
2447		ocb->orb[3] = htonl(ocb->bus_addr + IND_PTR_OFFSET);
2448		speed = min(target->fwdev->speed, max_speed);
2449		ocb->orb[4] = htonl(ORB_NOTIFY | ORB_CMD_SPD(speed)
2450						| ORB_CMD_MAXP(speed + 7));
2451		if((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN){
2452			ocb->orb[4] |= htonl(ORB_CMD_IN);
2453		}
2454
2455		if (csio->ccb_h.flags & CAM_SCATTER_VALID)
2456			printf("sbp: CAM_SCATTER_VALID\n");
2457		if (csio->ccb_h.flags & CAM_DATA_PHYS)
2458			printf("sbp: CAM_DATA_PHYS\n");
2459
2460		if (csio->ccb_h.flags & CAM_CDB_POINTER)
2461			cdb = (void *)csio->cdb_io.cdb_ptr;
2462		else
2463			cdb = (void *)&csio->cdb_io.cdb_bytes;
2464		bcopy(cdb, (void *)&ocb->orb[5], csio->cdb_len);
2465/*
2466printf("ORB %08x %08x %08x %08x\n", ntohl(ocb->orb[0]), ntohl(ocb->orb[1]), ntohl(ocb->orb[2]), ntohl(ocb->orb[3]));
2467printf("ORB %08x %08x %08x %08x\n", ntohl(ocb->orb[4]), ntohl(ocb->orb[5]), ntohl(ocb->orb[6]), ntohl(ocb->orb[7]));
2468*/
2469		if (ccb->csio.dxfer_len > 0) {
2470			int s, error;
2471
2472			s = splsoftvm();
2473			error = bus_dmamap_load(/*dma tag*/sbp->dmat,
2474					/*dma map*/ocb->dmamap,
2475					ccb->csio.data_ptr,
2476					ccb->csio.dxfer_len,
2477					sbp_execute_ocb,
2478					ocb,
2479					/*flags*/0);
2480			splx(s);
2481			if (error)
2482				printf("sbp: bus_dmamap_load error %d\n", error);
2483		} else
2484			sbp_execute_ocb(ocb, NULL, 0, 0);
2485		break;
2486	}
2487	case XPT_CALC_GEOMETRY:
2488	{
2489		struct ccb_calc_geometry *ccg;
2490#if defined(__DragonFly__) || __FreeBSD_version < 501100
2491		uint32_t size_mb;
2492		uint32_t secs_per_cylinder;
2493		int extended = 1;
2494#endif
2495
2496		ccg = &ccb->ccg;
2497		if (ccg->block_size == 0) {
2498			printf("sbp_action1: block_size is 0.\n");
2499			ccb->ccb_h.status = CAM_REQ_INVALID;
2500			xpt_done(ccb);
2501			break;
2502		}
2503SBP_DEBUG(1)
2504		printf("%s:%d:%d:%d:XPT_CALC_GEOMETRY: "
2505#if defined(__DragonFly__) || __FreeBSD_version < 500000
2506			"Volume size = %d\n",
2507#else
2508			"Volume size = %jd\n",
2509#endif
2510			device_get_nameunit(sbp->fd.dev),
2511			cam_sim_path(sbp->sim),
2512			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2513#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2514			(uintmax_t)
2515#endif
2516				ccg->volume_size);
2517END_DEBUG
2518
2519#if defined(__DragonFly__) || __FreeBSD_version < 501100
2520		size_mb = ccg->volume_size
2521			/ ((1024L * 1024L) / ccg->block_size);
2522
2523		if (size_mb > 1024 && extended) {
2524			ccg->heads = 255;
2525			ccg->secs_per_track = 63;
2526		} else {
2527			ccg->heads = 64;
2528			ccg->secs_per_track = 32;
2529		}
2530		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2531		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2532		ccb->ccb_h.status = CAM_REQ_CMP;
2533#else
2534		cam_calc_geometry(ccg, /*extended*/1);
2535#endif
2536		xpt_done(ccb);
2537		break;
2538	}
2539	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2540	{
2541
2542SBP_DEBUG(1)
2543		printf("%s:%d:XPT_RESET_BUS: \n",
2544			device_get_nameunit(sbp->fd.dev), cam_sim_path(sbp->sim));
2545END_DEBUG
2546
2547		ccb->ccb_h.status = CAM_REQ_INVALID;
2548		xpt_done(ccb);
2549		break;
2550	}
2551	case XPT_PATH_INQ:		/* Path routing inquiry */
2552	{
2553		struct ccb_pathinq *cpi = &ccb->cpi;
2554
2555SBP_DEBUG(1)
2556		printf("%s:%d:%d XPT_PATH_INQ:.\n",
2557			device_get_nameunit(sbp->fd.dev),
2558			ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2559END_DEBUG
2560		cpi->version_num = 1; /* XXX??? */
2561		cpi->hba_inquiry = PI_TAG_ABLE;
2562		cpi->target_sprt = 0;
2563		cpi->hba_misc = PIM_NOBUSRESET | PIM_NO_6_BYTE;
2564		cpi->hba_eng_cnt = 0;
2565		cpi->max_target = SBP_NUM_TARGETS - 1;
2566		cpi->max_lun = SBP_NUM_LUNS - 1;
2567		cpi->initiator_id = SBP_INITIATOR;
2568		cpi->bus_id = sim->bus_id;
2569		cpi->base_transfer_speed = 400 * 1000 / 8;
2570		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2571		strncpy(cpi->hba_vid, "SBP", HBA_IDLEN);
2572		strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
2573		cpi->unit_number = sim->unit_number;
2574                cpi->transport = XPORT_SPI;	/* XX should have a FireWire */
2575                cpi->transport_version = 2;
2576                cpi->protocol = PROTO_SCSI;
2577                cpi->protocol_version = SCSI_REV_2;
2578
2579		cpi->ccb_h.status = CAM_REQ_CMP;
2580		xpt_done(ccb);
2581		break;
2582	}
2583	case XPT_GET_TRAN_SETTINGS:
2584	{
2585		struct ccb_trans_settings *cts = &ccb->cts;
2586		struct ccb_trans_settings_scsi *scsi =
2587		    &cts->proto_specific.scsi;
2588		struct ccb_trans_settings_spi *spi =
2589		    &cts->xport_specific.spi;
2590
2591		cts->protocol = PROTO_SCSI;
2592		cts->protocol_version = SCSI_REV_2;
2593		cts->transport = XPORT_SPI;	/* should have a FireWire */
2594		cts->transport_version = 2;
2595		spi->valid = CTS_SPI_VALID_DISC;
2596		spi->flags = CTS_SPI_FLAGS_DISC_ENB;
2597		scsi->valid = CTS_SCSI_VALID_TQ;
2598		scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
2599SBP_DEBUG(1)
2600		printf("%s:%d:%d XPT_GET_TRAN_SETTINGS:.\n",
2601			device_get_nameunit(sbp->fd.dev),
2602			ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2603END_DEBUG
2604		cts->ccb_h.status = CAM_REQ_CMP;
2605		xpt_done(ccb);
2606		break;
2607	}
2608	case XPT_ABORT:
2609		ccb->ccb_h.status = CAM_UA_ABORT;
2610		xpt_done(ccb);
2611		break;
2612	case XPT_SET_TRAN_SETTINGS:
2613		/* XXX */
2614	default:
2615		ccb->ccb_h.status = CAM_REQ_INVALID;
2616		xpt_done(ccb);
2617		break;
2618	}
2619	return;
2620}
2621
2622static void
2623sbp_action(struct cam_sim *sim, union ccb *ccb)
2624{
2625	int s;
2626
2627	s = splfw();
2628	sbp_action1(sim, ccb);
2629	splx(s);
2630}
2631
2632static void
2633sbp_execute_ocb(void *arg,  bus_dma_segment_t *segments, int seg, int error)
2634{
2635	int i;
2636	struct sbp_ocb *ocb;
2637	struct sbp_ocb *prev;
2638	bus_dma_segment_t *s;
2639
2640	if (error)
2641		printf("sbp_execute_ocb: error=%d\n", error);
2642
2643	ocb = (struct sbp_ocb *)arg;
2644
2645SBP_DEBUG(2)
2646	printf("sbp_execute_ocb: seg %d", seg);
2647	for (i = 0; i < seg; i++)
2648#if defined(__DragonFly__) || __FreeBSD_version < 500000
2649		printf(", %x:%d", segments[i].ds_addr, segments[i].ds_len);
2650#else
2651		printf(", %jx:%jd", (uintmax_t)segments[i].ds_addr,
2652					(uintmax_t)segments[i].ds_len);
2653#endif
2654	printf("\n");
2655END_DEBUG
2656
2657	if (seg == 1) {
2658		/* direct pointer */
2659		s = &segments[0];
2660		if (s->ds_len > SBP_SEG_MAX)
2661			panic("ds_len > SBP_SEG_MAX, fix busdma code");
2662		ocb->orb[3] = htonl(s->ds_addr);
2663		ocb->orb[4] |= htonl(s->ds_len);
2664	} else if(seg > 1) {
2665		/* page table */
2666		for (i = 0; i < seg; i++) {
2667			s = &segments[i];
2668SBP_DEBUG(0)
2669			/* XXX LSI Logic "< 16 byte" bug might be hit */
2670			if (s->ds_len < 16)
2671				printf("sbp_execute_ocb: warning, "
2672#if defined(__DragonFly__) || __FreeBSD_version < 500000
2673					"segment length(%d) is less than 16."
2674#else
2675					"segment length(%zd) is less than 16."
2676#endif
2677					"(seg=%d/%d)\n", s->ds_len, i+1, seg);
2678END_DEBUG
2679			if (s->ds_len > SBP_SEG_MAX)
2680				panic("ds_len > SBP_SEG_MAX, fix busdma code");
2681			ocb->ind_ptr[i].hi = htonl(s->ds_len << 16);
2682			ocb->ind_ptr[i].lo = htonl(s->ds_addr);
2683		}
2684		ocb->orb[4] |= htonl(ORB_CMD_PTBL | seg);
2685	}
2686
2687	if (seg > 0)
2688		bus_dmamap_sync(ocb->sdev->target->sbp->dmat, ocb->dmamap,
2689			(ntohl(ocb->orb[4]) & ORB_CMD_IN) ?
2690			BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
2691	prev = sbp_enqueue_ocb(ocb->sdev, ocb);
2692	fwdma_sync(&ocb->sdev->dma, BUS_DMASYNC_PREWRITE);
2693	if (use_doorbell) {
2694		if (prev == NULL) {
2695			if (ocb->sdev->last_ocb != NULL)
2696				sbp_doorbell(ocb->sdev);
2697			else
2698				sbp_orb_pointer(ocb->sdev, ocb);
2699		}
2700	} else {
2701		if (prev == NULL || (ocb->sdev->flags & ORB_LINK_DEAD) != 0) {
2702			ocb->sdev->flags &= ~ORB_LINK_DEAD;
2703			sbp_orb_pointer(ocb->sdev, ocb);
2704		}
2705	}
2706}
2707
2708static void
2709sbp_poll(struct cam_sim *sim)
2710{
2711	struct sbp_softc *sbp;
2712	struct firewire_comm *fc;
2713
2714	sbp = (struct sbp_softc *)sim->softc;
2715	fc = sbp->fd.fc;
2716
2717	fc->poll(fc, 0, -1);
2718
2719	return;
2720}
2721
2722static struct sbp_ocb *
2723sbp_dequeue_ocb(struct sbp_dev *sdev, struct sbp_status *sbp_status)
2724{
2725	struct sbp_ocb *ocb;
2726	struct sbp_ocb *next;
2727	int s = splfw(), order = 0;
2728	int flags;
2729
2730SBP_DEBUG(1)
2731	sbp_show_sdev_info(sdev, 2);
2732#if defined(__DragonFly__) || __FreeBSD_version < 500000
2733	printf("%s: 0x%08lx src %d\n",
2734#else
2735	printf("%s: 0x%08x src %d\n",
2736#endif
2737	    __func__, ntohl(sbp_status->orb_lo), sbp_status->src);
2738END_DEBUG
2739	SBP_LOCK(sdev->target->sbp);
2740	for (ocb = STAILQ_FIRST(&sdev->ocbs); ocb != NULL; ocb = next) {
2741		next = STAILQ_NEXT(ocb, ocb);
2742		flags = ocb->flags;
2743		if (OCB_MATCH(ocb, sbp_status)) {
2744			/* found */
2745			STAILQ_REMOVE(&sdev->ocbs, ocb, sbp_ocb, ocb);
2746			if (ocb->ccb != NULL)
2747				untimeout(sbp_timeout, (caddr_t)ocb,
2748						ocb->ccb->ccb_h.timeout_ch);
2749			if (ntohl(ocb->orb[4]) & 0xffff) {
2750				bus_dmamap_sync(sdev->target->sbp->dmat,
2751					ocb->dmamap,
2752					(ntohl(ocb->orb[4]) & ORB_CMD_IN) ?
2753					BUS_DMASYNC_POSTREAD :
2754					BUS_DMASYNC_POSTWRITE);
2755				bus_dmamap_unload(sdev->target->sbp->dmat,
2756					ocb->dmamap);
2757			}
2758			if (!use_doorbell) {
2759				if (sbp_status->src == SRC_NO_NEXT) {
2760					if (next != NULL)
2761						sbp_orb_pointer(sdev, next);
2762					else if (order > 0) {
2763						/*
2764						 * Unordered execution
2765						 * We need to send pointer for
2766						 * next ORB
2767						 */
2768						sdev->flags |= ORB_LINK_DEAD;
2769					}
2770				}
2771			} else {
2772				/*
2773				 * XXX this is not correct for unordered
2774				 * execution.
2775				 */
2776				if (sdev->last_ocb != NULL)
2777					sbp_free_ocb(sdev, sdev->last_ocb);
2778				sdev->last_ocb = ocb;
2779				if (next != NULL &&
2780				    sbp_status->src == SRC_NO_NEXT)
2781					sbp_doorbell(sdev);
2782			}
2783			break;
2784		} else
2785			order ++;
2786	}
2787	SBP_UNLOCK(sdev->target->sbp);
2788	splx(s);
2789SBP_DEBUG(0)
2790	if (ocb && order > 0) {
2791		sbp_show_sdev_info(sdev, 2);
2792		printf("unordered execution order:%d\n", order);
2793	}
2794END_DEBUG
2795	return (ocb);
2796}
2797
2798static struct sbp_ocb *
2799sbp_enqueue_ocb(struct sbp_dev *sdev, struct sbp_ocb *ocb)
2800{
2801	int s = splfw();
2802	struct sbp_ocb *prev, *prev2;
2803
2804SBP_DEBUG(1)
2805	sbp_show_sdev_info(sdev, 2);
2806#if defined(__DragonFly__) || __FreeBSD_version < 500000
2807	printf("%s: 0x%08x\n", __func__, ocb->bus_addr);
2808#else
2809	printf("%s: 0x%08jx\n", __func__, (uintmax_t)ocb->bus_addr);
2810#endif
2811END_DEBUG
2812	prev2 = prev = STAILQ_LAST(&sdev->ocbs, sbp_ocb, ocb);
2813	STAILQ_INSERT_TAIL(&sdev->ocbs, ocb, ocb);
2814
2815	if (ocb->ccb != NULL)
2816		ocb->ccb->ccb_h.timeout_ch = timeout(sbp_timeout, (caddr_t)ocb,
2817					(ocb->ccb->ccb_h.timeout * hz) / 1000);
2818
2819	if (use_doorbell && prev == NULL)
2820		prev2 = sdev->last_ocb;
2821
2822	if (prev2 != NULL) {
2823SBP_DEBUG(2)
2824#if defined(__DragonFly__) || __FreeBSD_version < 500000
2825		printf("linking chain 0x%x -> 0x%x\n",
2826		    prev2->bus_addr, ocb->bus_addr);
2827#else
2828		printf("linking chain 0x%jx -> 0x%jx\n",
2829		    (uintmax_t)prev2->bus_addr, (uintmax_t)ocb->bus_addr);
2830#endif
2831END_DEBUG
2832		/*
2833		 * Suppress compiler optimization so that orb[1] must be written first.
2834		 * XXX We may need an explicit memory barrier for other architectures
2835		 * other than i386/amd64.
2836		 */
2837		*(volatile uint32_t *)&prev2->orb[1] = htonl(ocb->bus_addr);
2838		*(volatile uint32_t *)&prev2->orb[0] = 0;
2839	}
2840	splx(s);
2841
2842	return prev;
2843}
2844
2845static struct sbp_ocb *
2846sbp_get_ocb(struct sbp_dev *sdev)
2847{
2848	struct sbp_ocb *ocb;
2849	int s = splfw();
2850
2851	mtx_assert(&sdev->target->sbp->mtx, MA_OWNED);
2852	ocb = STAILQ_FIRST(&sdev->free_ocbs);
2853	if (ocb == NULL) {
2854		sdev->flags |= ORB_SHORTAGE;
2855		printf("ocb shortage!!!\n");
2856		splx(s);
2857		return NULL;
2858	}
2859	STAILQ_REMOVE_HEAD(&sdev->free_ocbs, ocb);
2860	splx(s);
2861	ocb->ccb = NULL;
2862	return (ocb);
2863}
2864
2865static void
2866sbp_free_ocb(struct sbp_dev *sdev, struct sbp_ocb *ocb)
2867{
2868	ocb->flags = 0;
2869	ocb->ccb = NULL;
2870
2871	SBP_LOCK(sdev->target->sbp);
2872	STAILQ_INSERT_TAIL(&sdev->free_ocbs, ocb, ocb);
2873	if ((sdev->flags & ORB_SHORTAGE) != 0) {
2874		int count;
2875
2876		sdev->flags &= ~ORB_SHORTAGE;
2877		count = sdev->freeze;
2878		sdev->freeze = 0;
2879		xpt_release_devq(sdev->path, count, TRUE);
2880	}
2881	SBP_UNLOCK(sdev->target->sbp);
2882}
2883
2884static void
2885sbp_abort_ocb(struct sbp_ocb *ocb, int status)
2886{
2887	struct sbp_dev *sdev;
2888
2889	sdev = ocb->sdev;
2890SBP_DEBUG(0)
2891	sbp_show_sdev_info(sdev, 2);
2892#if defined(__DragonFly__) || __FreeBSD_version < 500000
2893	printf("sbp_abort_ocb 0x%x\n", ocb->bus_addr);
2894#else
2895	printf("sbp_abort_ocb 0x%jx\n", (uintmax_t)ocb->bus_addr);
2896#endif
2897END_DEBUG
2898SBP_DEBUG(1)
2899	if (ocb->ccb != NULL)
2900		sbp_print_scsi_cmd(ocb);
2901END_DEBUG
2902	if (ntohl(ocb->orb[4]) & 0xffff) {
2903		bus_dmamap_sync(sdev->target->sbp->dmat, ocb->dmamap,
2904			(ntohl(ocb->orb[4]) & ORB_CMD_IN) ?
2905			BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
2906		bus_dmamap_unload(sdev->target->sbp->dmat, ocb->dmamap);
2907	}
2908	if (ocb->ccb != NULL) {
2909		untimeout(sbp_timeout, (caddr_t)ocb,
2910					ocb->ccb->ccb_h.timeout_ch);
2911		ocb->ccb->ccb_h.status = status;
2912		SBP_LOCK(sdev->target->sbp);
2913		xpt_done(ocb->ccb);
2914		SBP_UNLOCK(sdev->target->sbp);
2915	}
2916	sbp_free_ocb(sdev, ocb);
2917}
2918
2919static void
2920sbp_abort_all_ocbs(struct sbp_dev *sdev, int status)
2921{
2922	int s;
2923	struct sbp_ocb *ocb, *next;
2924	STAILQ_HEAD(, sbp_ocb) temp;
2925
2926	s = splfw();
2927
2928	bcopy(&sdev->ocbs, &temp, sizeof(temp));
2929	STAILQ_INIT(&sdev->ocbs);
2930	for (ocb = STAILQ_FIRST(&temp); ocb != NULL; ocb = next) {
2931		next = STAILQ_NEXT(ocb, ocb);
2932		sbp_abort_ocb(ocb, status);
2933	}
2934	if (sdev->last_ocb != NULL) {
2935		sbp_free_ocb(sdev, sdev->last_ocb);
2936		sdev->last_ocb = NULL;
2937	}
2938
2939	splx(s);
2940}
2941
2942static devclass_t sbp_devclass;
2943
2944static device_method_t sbp_methods[] = {
2945	/* device interface */
2946	DEVMETHOD(device_identify,	sbp_identify),
2947	DEVMETHOD(device_probe,		sbp_probe),
2948	DEVMETHOD(device_attach,	sbp_attach),
2949	DEVMETHOD(device_detach,	sbp_detach),
2950	DEVMETHOD(device_shutdown,	sbp_shutdown),
2951
2952	{ 0, 0 }
2953};
2954
2955static driver_t sbp_driver = {
2956	"sbp",
2957	sbp_methods,
2958	sizeof(struct sbp_softc),
2959};
2960#ifdef __DragonFly__
2961DECLARE_DUMMY_MODULE(sbp);
2962#endif
2963DRIVER_MODULE(sbp, firewire, sbp_driver, sbp_devclass, 0, 0);
2964MODULE_VERSION(sbp, 1);
2965MODULE_DEPEND(sbp, firewire, 1, 1, 1);
2966MODULE_DEPEND(sbp, cam, 1, 1, 1);
2967