sbp.c revision 170374
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 170374 2007-06-06 14:31:36Z 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	if (sbp_cold > 0)
828		sbp_cold --;
829
830#if 0
831	/*
832	 * XXX don't let CAM the bus rest.
833	 * CAM tries to do something with freezed (DEV_RETRY) devices.
834	 */
835	xpt_async(AC_BUS_RESET, sbp->path, /*arg*/ NULL);
836#endif
837
838	/* Garbage Collection */
839	for(i = 0 ; i < SBP_NUM_TARGETS ; i ++){
840		target = &sbp->targets[i];
841		STAILQ_FOREACH(fwdev, &sbp->fd.fc->devices, link)
842			if (target->fwdev == NULL || target->fwdev == fwdev)
843				break;
844		if (fwdev == NULL) {
845			/* device has removed in lower driver */
846			sbp_cam_detach_target(target);
847			sbp_free_target(target);
848		}
849	}
850	/* traverse device list */
851	STAILQ_FOREACH(fwdev, &sbp->fd.fc->devices, link) {
852SBP_DEBUG(0)
853		printf("sbp_post_explore: EUI:%08x%08x ",
854				fwdev->eui.hi, fwdev->eui.lo);
855		if (fwdev->status != FWDEVATTACHED)
856			printf("not attached, state=%d.\n", fwdev->status);
857		else
858			printf("attached\n");
859END_DEBUG
860		alive = SBP_FWDEV_ALIVE(fwdev);
861		for(i = 0 ; i < SBP_NUM_TARGETS ; i ++){
862			target = &sbp->targets[i];
863			if(target->fwdev == fwdev ) {
864				/* known target */
865				break;
866			}
867		}
868		if(i == SBP_NUM_TARGETS){
869			if (alive) {
870				/* new target */
871				target = sbp_alloc_target(sbp, fwdev);
872				if (target == NULL)
873					continue;
874			} else {
875				continue;
876			}
877		}
878		sbp_probe_target((void *)target);
879		if (target->num_lun == 0)
880			sbp_free_target(target);
881	}
882	SBP_LOCK(sbp);
883	xpt_release_simq(sbp->sim, /*run queue*/TRUE);
884	sbp->sim->flags &= ~SIMQ_FREEZED;
885	SBP_UNLOCK(sbp);
886}
887
888#if NEED_RESPONSE
889static void
890sbp_loginres_callback(struct fw_xfer *xfer){
891	int s;
892	struct sbp_dev *sdev;
893	sdev = (struct sbp_dev *)xfer->sc;
894SBP_DEBUG(1)
895	sbp_show_sdev_info(sdev, 2);
896	printf("sbp_loginres_callback\n");
897END_DEBUG
898	/* recycle */
899	s = splfw();
900	STAILQ_INSERT_TAIL(&sdev->target->sbp->fwb.xferlist, xfer, link);
901	splx(s);
902	return;
903}
904#endif
905
906static __inline void
907sbp_xfer_free(struct fw_xfer *xfer)
908{
909	struct sbp_dev *sdev;
910	int s;
911
912	sdev = (struct sbp_dev *)xfer->sc;
913	fw_xfer_unload(xfer);
914	s = splfw();
915	SBP_LOCK(sdev->target->sbp);
916	STAILQ_INSERT_TAIL(&sdev->target->xferlist, xfer, link);
917	SBP_UNLOCK(sdev->target->sbp);
918	splx(s);
919}
920
921static void
922sbp_reset_start_callback(struct fw_xfer *xfer)
923{
924	struct sbp_dev *tsdev, *sdev = (struct sbp_dev *)xfer->sc;
925	struct sbp_target *target = sdev->target;
926	int i;
927
928	if (xfer->resp != 0) {
929		sbp_show_sdev_info(sdev, 2);
930		printf("sbp_reset_start failed: resp=%d\n", xfer->resp);
931	}
932
933	for (i = 0; i < target->num_lun; i++) {
934		tsdev = target->luns[i];
935		if (tsdev != NULL && tsdev->status == SBP_DEV_LOGIN)
936			sbp_login(tsdev);
937	}
938}
939
940static void
941sbp_reset_start(struct sbp_dev *sdev)
942{
943	struct fw_xfer *xfer;
944	struct fw_pkt *fp;
945
946SBP_DEBUG(0)
947	sbp_show_sdev_info(sdev, 2);
948	printf("sbp_reset_start\n");
949END_DEBUG
950
951	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0);
952	xfer->hand = sbp_reset_start_callback;
953	fp = &xfer->send.hdr;
954	fp->mode.wreqq.dest_hi = 0xffff;
955	fp->mode.wreqq.dest_lo = 0xf0000000 | RESET_START;
956	fp->mode.wreqq.data = htonl(0xf);
957	fw_asyreq(xfer->fc, -1, xfer);
958}
959
960static void
961sbp_mgm_callback(struct fw_xfer *xfer)
962{
963	struct sbp_dev *sdev;
964	int resp;
965
966	sdev = (struct sbp_dev *)xfer->sc;
967
968SBP_DEBUG(1)
969	sbp_show_sdev_info(sdev, 2);
970	printf("sbp_mgm_callback\n");
971END_DEBUG
972	resp = xfer->resp;
973	sbp_xfer_free(xfer);
974#if 0
975	if (resp != 0) {
976		sbp_show_sdev_info(sdev, 2);
977		printf("management ORB failed(%d) ... RESET_START\n", resp);
978		sbp_reset_start(sdev);
979	}
980#endif
981	return;
982}
983
984static struct sbp_dev *
985sbp_next_dev(struct sbp_target *target, int lun)
986{
987	struct sbp_dev **sdevp;
988	int i;
989
990	for (i = lun, sdevp = &target->luns[lun]; i < target->num_lun;
991	    i++, sdevp++)
992		if (*sdevp != NULL && (*sdevp)->status == SBP_DEV_PROBE)
993			return(*sdevp);
994	return(NULL);
995}
996
997#define SCAN_PRI 1
998static void
999sbp_cam_scan_lun(struct cam_periph *periph, union ccb *ccb)
1000{
1001	struct sbp_target *target;
1002	struct sbp_dev *sdev;
1003
1004	sdev = (struct sbp_dev *) ccb->ccb_h.ccb_sdev_ptr;
1005	target = sdev->target;
1006SBP_DEBUG(0)
1007	sbp_show_sdev_info(sdev, 2);
1008	printf("sbp_cam_scan_lun\n");
1009END_DEBUG
1010	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1011		sdev->status = SBP_DEV_ATTACHED;
1012	} else {
1013		sbp_show_sdev_info(sdev, 2);
1014		printf("scan failed\n");
1015	}
1016	sdev = sbp_next_dev(target, sdev->lun_id + 1);
1017	if (sdev == NULL) {
1018		free(ccb, M_SBP);
1019		return;
1020	}
1021	/* reuse ccb */
1022	xpt_setup_ccb(&ccb->ccb_h, sdev->path, SCAN_PRI);
1023	ccb->ccb_h.ccb_sdev_ptr = sdev;
1024	xpt_action(ccb);
1025	xpt_release_devq(sdev->path, sdev->freeze, TRUE);
1026	sdev->freeze = 1;
1027}
1028
1029static void
1030sbp_cam_scan_target(void *arg)
1031{
1032	struct sbp_target *target = (struct sbp_target *)arg;
1033	struct sbp_dev *sdev;
1034	union ccb *ccb;
1035
1036	sdev = sbp_next_dev(target, 0);
1037	if (sdev == NULL) {
1038		printf("sbp_cam_scan_target: nothing to do for target%d\n",
1039							target->target_id);
1040		return;
1041	}
1042SBP_DEBUG(0)
1043	sbp_show_sdev_info(sdev, 2);
1044	printf("sbp_cam_scan_target\n");
1045END_DEBUG
1046	ccb = malloc(sizeof(union ccb), M_SBP, M_NOWAIT | M_ZERO);
1047	if (ccb == NULL) {
1048		printf("sbp_cam_scan_target: malloc failed\n");
1049		return;
1050	}
1051	xpt_setup_ccb(&ccb->ccb_h, sdev->path, SCAN_PRI);
1052	ccb->ccb_h.func_code = XPT_SCAN_LUN;
1053	ccb->ccb_h.cbfcnp = sbp_cam_scan_lun;
1054	ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1055	ccb->crcn.flags = CAM_FLAG_NONE;
1056	ccb->ccb_h.ccb_sdev_ptr = sdev;
1057
1058	/* The scan is in progress now. */
1059	SBP_LOCK(target->sbp);
1060	xpt_action(ccb);
1061	xpt_release_devq(sdev->path, sdev->freeze, TRUE);
1062	sdev->freeze = 1;
1063	SBP_UNLOCK(target->sbp);
1064}
1065
1066static __inline void
1067sbp_scan_dev(struct sbp_dev *sdev)
1068{
1069	sdev->status = SBP_DEV_PROBE;
1070	callout_reset(&sdev->target->scan_callout, scan_delay * hz / 1000,
1071			sbp_cam_scan_target, (void *)sdev->target);
1072}
1073
1074static void
1075sbp_do_attach(struct fw_xfer *xfer)
1076{
1077	struct sbp_dev *sdev;
1078	struct sbp_target *target;
1079	struct sbp_softc *sbp;
1080
1081	sdev = (struct sbp_dev *)xfer->sc;
1082	target = sdev->target;
1083	sbp = target->sbp;
1084SBP_DEBUG(0)
1085	sbp_show_sdev_info(sdev, 2);
1086	printf("sbp_do_attach\n");
1087END_DEBUG
1088	sbp_xfer_free(xfer);
1089
1090	if (sdev->path == NULL)
1091		xpt_create_path(&sdev->path, xpt_periph,
1092			cam_sim_path(target->sbp->sim),
1093			target->target_id, sdev->lun_id);
1094
1095	/*
1096	 * Let CAM scan the bus if we are in the boot process.
1097	 * XXX xpt_scan_bus cannot detect LUN larger than 0
1098	 * if LUN 0 doesn't exists.
1099	 */
1100	if (sbp_cold > 0) {
1101		sdev->status = SBP_DEV_ATTACHED;
1102		return;
1103	}
1104
1105	sbp_scan_dev(sdev);
1106	return;
1107}
1108
1109static void
1110sbp_agent_reset_callback(struct fw_xfer *xfer)
1111{
1112	struct sbp_dev *sdev;
1113
1114	sdev = (struct sbp_dev *)xfer->sc;
1115SBP_DEBUG(1)
1116	sbp_show_sdev_info(sdev, 2);
1117	printf("%s\n", __func__);
1118END_DEBUG
1119	if (xfer->resp != 0) {
1120		sbp_show_sdev_info(sdev, 2);
1121		printf("%s: resp=%d\n", __func__, xfer->resp);
1122	}
1123
1124	sbp_xfer_free(xfer);
1125	if (sdev->path) {
1126		SBP_LOCK(sdev->target->sbp);
1127		xpt_release_devq(sdev->path, sdev->freeze, TRUE);
1128		sdev->freeze = 0;
1129		SBP_UNLOCK(sdev->target->sbp);
1130	}
1131}
1132
1133static void
1134sbp_agent_reset(struct sbp_dev *sdev)
1135{
1136	struct fw_xfer *xfer;
1137	struct fw_pkt *fp;
1138
1139SBP_DEBUG(0)
1140	sbp_show_sdev_info(sdev, 2);
1141	printf("sbp_agent_reset\n");
1142END_DEBUG
1143	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0x04);
1144	if (xfer == NULL)
1145		return;
1146	if (sdev->status == SBP_DEV_ATTACHED || sdev->status == SBP_DEV_PROBE)
1147		xfer->hand = sbp_agent_reset_callback;
1148	else
1149		xfer->hand = sbp_do_attach;
1150	fp = &xfer->send.hdr;
1151	fp->mode.wreqq.data = htonl(0xf);
1152	fw_asyreq(xfer->fc, -1, xfer);
1153	sbp_abort_all_ocbs(sdev, CAM_BDR_SENT);
1154}
1155
1156static void
1157sbp_busy_timeout_callback(struct fw_xfer *xfer)
1158{
1159	struct sbp_dev *sdev;
1160
1161	sdev = (struct sbp_dev *)xfer->sc;
1162SBP_DEBUG(1)
1163	sbp_show_sdev_info(sdev, 2);
1164	printf("sbp_busy_timeout_callback\n");
1165END_DEBUG
1166	sbp_xfer_free(xfer);
1167	sbp_agent_reset(sdev);
1168}
1169
1170static void
1171sbp_busy_timeout(struct sbp_dev *sdev)
1172{
1173	struct fw_pkt *fp;
1174	struct fw_xfer *xfer;
1175SBP_DEBUG(0)
1176	sbp_show_sdev_info(sdev, 2);
1177	printf("sbp_busy_timeout\n");
1178END_DEBUG
1179	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0);
1180
1181	xfer->hand = sbp_busy_timeout_callback;
1182	fp = &xfer->send.hdr;
1183	fp->mode.wreqq.dest_hi = 0xffff;
1184	fp->mode.wreqq.dest_lo = 0xf0000000 | BUSY_TIMEOUT;
1185	fp->mode.wreqq.data = htonl((1 << (13+12)) | 0xf);
1186	fw_asyreq(xfer->fc, -1, xfer);
1187}
1188
1189static void
1190sbp_orb_pointer_callback(struct fw_xfer *xfer)
1191{
1192	struct sbp_dev *sdev;
1193	sdev = (struct sbp_dev *)xfer->sc;
1194
1195SBP_DEBUG(1)
1196	sbp_show_sdev_info(sdev, 2);
1197	printf("%s\n", __func__);
1198END_DEBUG
1199	if (xfer->resp != 0) {
1200		/* XXX */
1201		printf("%s: xfer->resp = %d\n", __func__, xfer->resp);
1202	}
1203	sbp_xfer_free(xfer);
1204	sdev->flags &= ~ORB_POINTER_ACTIVE;
1205
1206	if ((sdev->flags & ORB_POINTER_NEED) != 0) {
1207		struct sbp_ocb *ocb;
1208
1209		sdev->flags &= ~ORB_POINTER_NEED;
1210		ocb = STAILQ_FIRST(&sdev->ocbs);
1211		if (ocb != NULL)
1212			sbp_orb_pointer(sdev, ocb);
1213	}
1214	return;
1215}
1216
1217static void
1218sbp_orb_pointer(struct sbp_dev *sdev, struct sbp_ocb *ocb)
1219{
1220	struct fw_xfer *xfer;
1221	struct fw_pkt *fp;
1222SBP_DEBUG(1)
1223	sbp_show_sdev_info(sdev, 2);
1224	printf("%s: 0x%08x\n", __func__, (uint32_t)ocb->bus_addr);
1225END_DEBUG
1226
1227	if ((sdev->flags & ORB_POINTER_ACTIVE) != 0) {
1228SBP_DEBUG(0)
1229		printf("%s: orb pointer active\n", __func__);
1230END_DEBUG
1231		sdev->flags |= ORB_POINTER_NEED;
1232		return;
1233	}
1234
1235	sdev->flags |= ORB_POINTER_ACTIVE;
1236	xfer = sbp_write_cmd(sdev, FWTCODE_WREQB, 0x08);
1237	if (xfer == NULL)
1238		return;
1239	xfer->hand = sbp_orb_pointer_callback;
1240
1241	fp = &xfer->send.hdr;
1242	fp->mode.wreqb.len = 8;
1243	fp->mode.wreqb.extcode = 0;
1244	xfer->send.payload[0] =
1245		htonl(((sdev->target->sbp->fd.fc->nodeid | FWLOCALBUS )<< 16));
1246	xfer->send.payload[1] = htonl((uint32_t)ocb->bus_addr);
1247
1248	if(fw_asyreq(xfer->fc, -1, xfer) != 0){
1249			sbp_xfer_free(xfer);
1250			ocb->ccb->ccb_h.status = CAM_REQ_INVALID;
1251			xpt_done(ocb->ccb);
1252	}
1253}
1254
1255static void
1256sbp_doorbell_callback(struct fw_xfer *xfer)
1257{
1258	struct sbp_dev *sdev;
1259	sdev = (struct sbp_dev *)xfer->sc;
1260
1261SBP_DEBUG(1)
1262	sbp_show_sdev_info(sdev, 2);
1263	printf("sbp_doorbell_callback\n");
1264END_DEBUG
1265	if (xfer->resp != 0) {
1266		/* XXX */
1267		printf("%s: xfer->resp = %d\n", __func__, xfer->resp);
1268	}
1269	sbp_xfer_free(xfer);
1270	sdev->flags &= ~ORB_DOORBELL_ACTIVE;
1271	if ((sdev->flags & ORB_DOORBELL_NEED) != 0) {
1272		sdev->flags &= ~ORB_DOORBELL_NEED;
1273		sbp_doorbell(sdev);
1274	}
1275	return;
1276}
1277
1278static void
1279sbp_doorbell(struct sbp_dev *sdev)
1280{
1281	struct fw_xfer *xfer;
1282	struct fw_pkt *fp;
1283SBP_DEBUG(1)
1284	sbp_show_sdev_info(sdev, 2);
1285	printf("sbp_doorbell\n");
1286END_DEBUG
1287
1288	if ((sdev->flags & ORB_DOORBELL_ACTIVE) != 0) {
1289		sdev->flags |= ORB_DOORBELL_NEED;
1290		return;
1291	}
1292	sdev->flags |= ORB_DOORBELL_ACTIVE;
1293	xfer = sbp_write_cmd(sdev, FWTCODE_WREQQ, 0x10);
1294	if (xfer == NULL)
1295		return;
1296	xfer->hand = sbp_doorbell_callback;
1297	fp = &xfer->send.hdr;
1298	fp->mode.wreqq.data = htonl(0xf);
1299	fw_asyreq(xfer->fc, -1, xfer);
1300}
1301
1302static struct fw_xfer *
1303sbp_write_cmd(struct sbp_dev *sdev, int tcode, int offset)
1304{
1305	struct fw_xfer *xfer;
1306	struct fw_pkt *fp;
1307	struct sbp_target *target;
1308	int s, new = 0;
1309
1310	target = sdev->target;
1311	s = splfw();
1312	xfer = STAILQ_FIRST(&target->xferlist);
1313	if (xfer == NULL) {
1314		if (target->n_xfer > 5 /* XXX */) {
1315			printf("sbp: no more xfer for this target\n");
1316			splx(s);
1317			return(NULL);
1318		}
1319		xfer = fw_xfer_alloc_buf(M_SBP, 8, 0);
1320		if(xfer == NULL){
1321			printf("sbp: fw_xfer_alloc_buf failed\n");
1322			splx(s);
1323			return NULL;
1324		}
1325		target->n_xfer ++;
1326		if (debug)
1327			printf("sbp: alloc %d xfer\n", target->n_xfer);
1328		new = 1;
1329	} else {
1330		STAILQ_REMOVE_HEAD(&target->xferlist, link);
1331	}
1332	splx(s);
1333
1334	microtime(&xfer->tv);
1335
1336	if (new) {
1337		xfer->recv.pay_len = 0;
1338		xfer->send.spd = min(sdev->target->fwdev->speed, max_speed);
1339		xfer->fc = sdev->target->sbp->fd.fc;
1340	}
1341
1342	if (tcode == FWTCODE_WREQB)
1343		xfer->send.pay_len = 8;
1344	else
1345		xfer->send.pay_len = 0;
1346
1347	xfer->sc = (caddr_t)sdev;
1348	fp = &xfer->send.hdr;
1349	fp->mode.wreqq.dest_hi = sdev->login->cmd_hi;
1350	fp->mode.wreqq.dest_lo = sdev->login->cmd_lo + offset;
1351	fp->mode.wreqq.tlrt = 0;
1352	fp->mode.wreqq.tcode = tcode;
1353	fp->mode.wreqq.pri = 0;
1354	fp->mode.wreqq.dst = FWLOCALBUS | sdev->target->fwdev->dst;
1355
1356	return xfer;
1357
1358}
1359
1360static void
1361sbp_mgm_orb(struct sbp_dev *sdev, int func, struct sbp_ocb *aocb)
1362{
1363	struct fw_xfer *xfer;
1364	struct fw_pkt *fp;
1365	struct sbp_ocb *ocb;
1366	struct sbp_target *target;
1367	int s, nid;
1368
1369	target = sdev->target;
1370	nid = target->sbp->fd.fc->nodeid | FWLOCALBUS;
1371
1372	s = splfw();
1373	SBP_LOCK(target->sbp);
1374	if (func == ORB_FUN_RUNQUEUE) {
1375		ocb = STAILQ_FIRST(&target->mgm_ocb_queue);
1376		if (target->mgm_ocb_cur != NULL || ocb == NULL) {
1377			SBP_UNLOCK(target->sbp);
1378			splx(s);
1379			return;
1380		}
1381		STAILQ_REMOVE_HEAD(&target->mgm_ocb_queue, ocb);
1382		SBP_UNLOCK(target->sbp);
1383		goto start;
1384	}
1385	if ((ocb = sbp_get_ocb(sdev)) == NULL) {
1386		SBP_UNLOCK(target->sbp);
1387		splx(s);
1388		/* XXX */
1389		return;
1390	}
1391	SBP_UNLOCK(target->sbp);
1392	ocb->flags = OCB_ACT_MGM;
1393	ocb->sdev = sdev;
1394
1395	bzero((void *)ocb->orb, sizeof(ocb->orb));
1396	ocb->orb[6] = htonl((nid << 16) | SBP_BIND_HI);
1397	ocb->orb[7] = htonl(SBP_DEV2ADDR(target->target_id, sdev->lun_id));
1398
1399SBP_DEBUG(0)
1400	sbp_show_sdev_info(sdev, 2);
1401	printf("%s\n", orb_fun_name[(func>>16)&0xf]);
1402END_DEBUG
1403	switch (func) {
1404	case ORB_FUN_LGI:
1405		ocb->orb[0] = ocb->orb[1] = 0; /* password */
1406		ocb->orb[2] = htonl(nid << 16);
1407		ocb->orb[3] = htonl(sdev->dma.bus_addr);
1408		ocb->orb[4] = htonl(ORB_NOTIFY | sdev->lun_id);
1409		if (ex_login)
1410			ocb->orb[4] |= htonl(ORB_EXV);
1411		ocb->orb[5] = htonl(SBP_LOGIN_SIZE);
1412		fwdma_sync(&sdev->dma, BUS_DMASYNC_PREREAD);
1413		break;
1414	case ORB_FUN_ATA:
1415		ocb->orb[0] = htonl((0 << 16) | 0);
1416		ocb->orb[1] = htonl(aocb->bus_addr & 0xffffffff);
1417		/* fall through */
1418	case ORB_FUN_RCN:
1419	case ORB_FUN_LGO:
1420	case ORB_FUN_LUR:
1421	case ORB_FUN_RST:
1422	case ORB_FUN_ATS:
1423		ocb->orb[4] = htonl(ORB_NOTIFY | func | sdev->login->id);
1424		break;
1425	}
1426
1427	if (target->mgm_ocb_cur != NULL) {
1428		/* there is a standing ORB */
1429		SBP_LOCK(target->sbp);
1430		STAILQ_INSERT_TAIL(&sdev->target->mgm_ocb_queue, ocb, ocb);
1431		SBP_UNLOCK(target->sbp);
1432		splx(s);
1433		return;
1434	}
1435start:
1436	target->mgm_ocb_cur = ocb;
1437	splx(s);
1438
1439	callout_reset(&target->mgm_ocb_timeout, 5*hz,
1440				sbp_mgm_timeout, (caddr_t)ocb);
1441	xfer = sbp_write_cmd(sdev, FWTCODE_WREQB, 0);
1442	if(xfer == NULL){
1443		return;
1444	}
1445	xfer->hand = sbp_mgm_callback;
1446
1447	fp = &xfer->send.hdr;
1448	fp->mode.wreqb.dest_hi = sdev->target->mgm_hi;
1449	fp->mode.wreqb.dest_lo = sdev->target->mgm_lo;
1450	fp->mode.wreqb.len = 8;
1451	fp->mode.wreqb.extcode = 0;
1452	xfer->send.payload[0] = htonl(nid << 16);
1453	xfer->send.payload[1] = htonl(ocb->bus_addr & 0xffffffff);
1454SBP_DEBUG(0)
1455	sbp_show_sdev_info(sdev, 2);
1456	printf("mgm orb: %08x\n", (uint32_t)ocb->bus_addr);
1457END_DEBUG
1458
1459	fw_asyreq(xfer->fc, -1, xfer);
1460}
1461
1462static void
1463sbp_print_scsi_cmd(struct sbp_ocb *ocb)
1464{
1465	struct ccb_scsiio *csio;
1466
1467	csio = &ocb->ccb->csio;
1468	printf("%s:%d:%d XPT_SCSI_IO: "
1469		"cmd: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x"
1470		", flags: 0x%02x, "
1471		"%db cmd/%db data/%db sense\n",
1472		device_get_nameunit(ocb->sdev->target->sbp->fd.dev),
1473		ocb->ccb->ccb_h.target_id, ocb->ccb->ccb_h.target_lun,
1474		csio->cdb_io.cdb_bytes[0],
1475		csio->cdb_io.cdb_bytes[1],
1476		csio->cdb_io.cdb_bytes[2],
1477		csio->cdb_io.cdb_bytes[3],
1478		csio->cdb_io.cdb_bytes[4],
1479		csio->cdb_io.cdb_bytes[5],
1480		csio->cdb_io.cdb_bytes[6],
1481		csio->cdb_io.cdb_bytes[7],
1482		csio->cdb_io.cdb_bytes[8],
1483		csio->cdb_io.cdb_bytes[9],
1484		ocb->ccb->ccb_h.flags & CAM_DIR_MASK,
1485		csio->cdb_len, csio->dxfer_len,
1486		csio->sense_len);
1487}
1488
1489static void
1490sbp_scsi_status(struct sbp_status *sbp_status, struct sbp_ocb *ocb)
1491{
1492	struct sbp_cmd_status *sbp_cmd_status;
1493	struct scsi_sense_data *sense;
1494
1495	sbp_cmd_status = (struct sbp_cmd_status *)sbp_status->data;
1496	sense = &ocb->ccb->csio.sense_data;
1497
1498SBP_DEBUG(0)
1499	sbp_print_scsi_cmd(ocb);
1500	/* XXX need decode status */
1501	sbp_show_sdev_info(ocb->sdev, 2);
1502	printf("SCSI status %x sfmt %x valid %x key %x code %x qlfr %x len %d\n",
1503		sbp_cmd_status->status,
1504		sbp_cmd_status->sfmt,
1505		sbp_cmd_status->valid,
1506		sbp_cmd_status->s_key,
1507		sbp_cmd_status->s_code,
1508		sbp_cmd_status->s_qlfr,
1509		sbp_status->len
1510	);
1511END_DEBUG
1512
1513	switch (sbp_cmd_status->status) {
1514	case SCSI_STATUS_CHECK_COND:
1515	case SCSI_STATUS_BUSY:
1516	case SCSI_STATUS_CMD_TERMINATED:
1517		if(sbp_cmd_status->sfmt == SBP_SFMT_CURR){
1518			sense->error_code = SSD_CURRENT_ERROR;
1519		}else{
1520			sense->error_code = SSD_DEFERRED_ERROR;
1521		}
1522		if(sbp_cmd_status->valid)
1523			sense->error_code |= SSD_ERRCODE_VALID;
1524		sense->flags = sbp_cmd_status->s_key;
1525		if(sbp_cmd_status->mark)
1526			sense->flags |= SSD_FILEMARK;
1527		if(sbp_cmd_status->eom)
1528			sense->flags |= SSD_EOM;
1529		if(sbp_cmd_status->ill_len)
1530			sense->flags |= SSD_ILI;
1531
1532		bcopy(&sbp_cmd_status->info, &sense->info[0], 4);
1533
1534		if (sbp_status->len <= 1)
1535			/* XXX not scsi status. shouldn't be happened */
1536			sense->extra_len = 0;
1537		else if (sbp_status->len <= 4)
1538			/* add_sense_code(_qual), info, cmd_spec_info */
1539			sense->extra_len = 6;
1540		else
1541			/* fru, sense_key_spec */
1542			sense->extra_len = 10;
1543
1544		bcopy(&sbp_cmd_status->cdb, &sense->cmd_spec_info[0], 4);
1545
1546		sense->add_sense_code = sbp_cmd_status->s_code;
1547		sense->add_sense_code_qual = sbp_cmd_status->s_qlfr;
1548		sense->fru = sbp_cmd_status->fru;
1549
1550		bcopy(&sbp_cmd_status->s_keydep[0],
1551		    &sense->sense_key_spec[0], 3);
1552
1553		ocb->ccb->csio.scsi_status = sbp_cmd_status->status;;
1554		ocb->ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
1555							| CAM_AUTOSNS_VALID;
1556/*
1557{
1558		uint8_t j, *tmp;
1559		tmp = sense;
1560		for( j = 0 ; j < 32 ; j+=8){
1561			printf("sense %02x%02x %02x%02x %02x%02x %02x%02x\n",
1562				tmp[j], tmp[j+1], tmp[j+2], tmp[j+3],
1563				tmp[j+4], tmp[j+5], tmp[j+6], tmp[j+7]);
1564		}
1565
1566}
1567*/
1568		break;
1569	default:
1570		sbp_show_sdev_info(ocb->sdev, 2);
1571		printf("sbp_scsi_status: unknown scsi status 0x%x\n",
1572						sbp_cmd_status->status);
1573	}
1574}
1575
1576static void
1577sbp_fix_inq_data(struct sbp_ocb *ocb)
1578{
1579	union ccb *ccb;
1580	struct sbp_dev *sdev;
1581	struct scsi_inquiry_data *inq;
1582
1583	ccb = ocb->ccb;
1584	sdev = ocb->sdev;
1585
1586	if (ccb->csio.cdb_io.cdb_bytes[1] & SI_EVPD)
1587		return;
1588SBP_DEBUG(1)
1589	sbp_show_sdev_info(sdev, 2);
1590	printf("sbp_fix_inq_data\n");
1591END_DEBUG
1592	inq = (struct scsi_inquiry_data *) ccb->csio.data_ptr;
1593	switch (SID_TYPE(inq)) {
1594	case T_DIRECT:
1595#if 0
1596		/*
1597		 * XXX Convert Direct Access device to RBC.
1598		 * I've never seen FireWire DA devices which support READ_6.
1599		 */
1600		if (SID_TYPE(inq) == T_DIRECT)
1601			inq->device |= T_RBC; /*  T_DIRECT == 0 */
1602#endif
1603		/* fall through */
1604	case T_RBC:
1605		/*
1606		 * Override vendor/product/revision information.
1607		 * Some devices sometimes return strange strings.
1608		 */
1609#if 1
1610		bcopy(sdev->vendor, inq->vendor, sizeof(inq->vendor));
1611		bcopy(sdev->product, inq->product, sizeof(inq->product));
1612		bcopy(sdev->revision+2, inq->revision, sizeof(inq->revision));
1613#endif
1614		break;
1615	}
1616	/*
1617	 * Force to enable/disable tagged queuing.
1618	 * XXX CAM also checks SCP_QUEUE_DQUE flag in the control mode page.
1619	 */
1620	if (sbp_tags > 0)
1621		inq->flags |= SID_CmdQue;
1622	else if (sbp_tags < 0)
1623		inq->flags &= ~SID_CmdQue;
1624
1625}
1626
1627static void
1628sbp_recv1(struct fw_xfer *xfer)
1629{
1630	struct fw_pkt *rfp;
1631#if NEED_RESPONSE
1632	struct fw_pkt *sfp;
1633#endif
1634	struct sbp_softc *sbp;
1635	struct sbp_dev *sdev;
1636	struct sbp_ocb *ocb;
1637	struct sbp_login_res *login_res = NULL;
1638	struct sbp_status *sbp_status;
1639	struct sbp_target *target;
1640	int	orb_fun, status_valid0, status_valid, t, l, reset_agent = 0;
1641	uint32_t addr;
1642/*
1643	uint32_t *ld;
1644	ld = xfer->recv.buf;
1645printf("sbp %x %d %d %08x %08x %08x %08x\n",
1646			xfer->resp, xfer->recv.len, xfer->recv.off, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
1647printf("sbp %08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
1648printf("sbp %08x %08x %08x %08x\n", ntohl(ld[8]), ntohl(ld[9]), ntohl(ld[10]), ntohl(ld[11]));
1649*/
1650	sbp = (struct sbp_softc *)xfer->sc;
1651	if (xfer->resp != 0){
1652		printf("sbp_recv: xfer->resp = %d\n", xfer->resp);
1653		goto done0;
1654	}
1655	if (xfer->recv.payload == NULL){
1656		printf("sbp_recv: xfer->recv.payload == NULL\n");
1657		goto done0;
1658	}
1659	rfp = &xfer->recv.hdr;
1660	if(rfp->mode.wreqb.tcode != FWTCODE_WREQB){
1661		printf("sbp_recv: tcode = %d\n", rfp->mode.wreqb.tcode);
1662		goto done0;
1663	}
1664	sbp_status = (struct sbp_status *)xfer->recv.payload;
1665	addr = rfp->mode.wreqb.dest_lo;
1666SBP_DEBUG(2)
1667	printf("received address 0x%x\n", addr);
1668END_DEBUG
1669	t = SBP_ADDR2TRG(addr);
1670	if (t >= SBP_NUM_TARGETS) {
1671		device_printf(sbp->fd.dev,
1672			"sbp_recv1: invalid target %d\n", t);
1673		goto done0;
1674	}
1675	target = &sbp->targets[t];
1676	l = SBP_ADDR2LUN(addr);
1677	if (l >= target->num_lun || target->luns[l] == NULL) {
1678		device_printf(sbp->fd.dev,
1679			"sbp_recv1: invalid lun %d (target=%d)\n", l, t);
1680		goto done0;
1681	}
1682	sdev = target->luns[l];
1683
1684	ocb = NULL;
1685	switch (sbp_status->src) {
1686	case 0:
1687	case 1:
1688		/* check mgm_ocb_cur first */
1689		ocb  = target->mgm_ocb_cur;
1690		if (ocb != NULL) {
1691			if (OCB_MATCH(ocb, sbp_status)) {
1692				callout_stop(&target->mgm_ocb_timeout);
1693				target->mgm_ocb_cur = NULL;
1694				break;
1695			}
1696		}
1697		ocb = sbp_dequeue_ocb(sdev, sbp_status);
1698		if (ocb == NULL) {
1699			sbp_show_sdev_info(sdev, 2);
1700#if defined(__DragonFly__) || __FreeBSD_version < 500000
1701			printf("No ocb(%lx) on the queue\n",
1702#else
1703			printf("No ocb(%x) on the queue\n",
1704#endif
1705					ntohl(sbp_status->orb_lo));
1706		}
1707		break;
1708	case 2:
1709		/* unsolicit */
1710		sbp_show_sdev_info(sdev, 2);
1711		printf("unsolicit status received\n");
1712		break;
1713	default:
1714		sbp_show_sdev_info(sdev, 2);
1715		printf("unknown sbp_status->src\n");
1716	}
1717
1718	status_valid0 = (sbp_status->src < 2
1719			&& sbp_status->resp == ORB_RES_CMPL
1720			&& sbp_status->dead == 0);
1721	status_valid = (status_valid0 && sbp_status->status == 0);
1722
1723	if (!status_valid0 || debug > 2){
1724		int status;
1725SBP_DEBUG(0)
1726		sbp_show_sdev_info(sdev, 2);
1727		printf("ORB status src:%x resp:%x dead:%x"
1728#if defined(__DragonFly__) || __FreeBSD_version < 500000
1729				" len:%x stat:%x orb:%x%08lx\n",
1730#else
1731				" len:%x stat:%x orb:%x%08x\n",
1732#endif
1733			sbp_status->src, sbp_status->resp, sbp_status->dead,
1734			sbp_status->len, sbp_status->status,
1735			ntohs(sbp_status->orb_hi), ntohl(sbp_status->orb_lo));
1736END_DEBUG
1737		sbp_show_sdev_info(sdev, 2);
1738		status = sbp_status->status;
1739		switch(sbp_status->resp) {
1740		case 0:
1741			if (status > MAX_ORB_STATUS0)
1742				printf("%s\n", orb_status0[MAX_ORB_STATUS0]);
1743			else
1744				printf("%s\n", orb_status0[status]);
1745			break;
1746		case 1:
1747			printf("Obj: %s, Error: %s\n",
1748				orb_status1_object[(status>>6) & 3],
1749				orb_status1_serial_bus_error[status & 0xf]);
1750			break;
1751		case 2:
1752			printf("Illegal request\n");
1753			break;
1754		case 3:
1755			printf("Vendor dependent\n");
1756			break;
1757		default:
1758			printf("unknown respose code %d\n", sbp_status->resp);
1759		}
1760	}
1761
1762	/* we have to reset the fetch agent if it's dead */
1763	if (sbp_status->dead) {
1764		if (sdev->path) {
1765			SBP_LOCK(sbp);
1766			xpt_freeze_devq(sdev->path, 1);
1767			sdev->freeze ++;
1768			SBP_UNLOCK(sbp);
1769		}
1770		reset_agent = 1;
1771	}
1772
1773	if (ocb == NULL)
1774		goto done;
1775
1776	switch(ntohl(ocb->orb[4]) & ORB_FMT_MSK){
1777	case ORB_FMT_NOP:
1778		break;
1779	case ORB_FMT_VED:
1780		break;
1781	case ORB_FMT_STD:
1782		switch(ocb->flags) {
1783		case OCB_ACT_MGM:
1784			orb_fun = ntohl(ocb->orb[4]) & ORB_FUN_MSK;
1785			reset_agent = 0;
1786			switch(orb_fun) {
1787			case ORB_FUN_LGI:
1788				fwdma_sync(&sdev->dma, BUS_DMASYNC_POSTREAD);
1789				login_res = sdev->login;
1790				login_res->len = ntohs(login_res->len);
1791				login_res->id = ntohs(login_res->id);
1792				login_res->cmd_hi = ntohs(login_res->cmd_hi);
1793				login_res->cmd_lo = ntohl(login_res->cmd_lo);
1794				if (status_valid) {
1795SBP_DEBUG(0)
1796sbp_show_sdev_info(sdev, 2);
1797printf("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));
1798END_DEBUG
1799					sbp_busy_timeout(sdev);
1800				} else {
1801					/* forgot logout? */
1802					sbp_show_sdev_info(sdev, 2);
1803					printf("login failed\n");
1804					sdev->status = SBP_DEV_RESET;
1805				}
1806				break;
1807			case ORB_FUN_RCN:
1808				login_res = sdev->login;
1809				if (status_valid) {
1810SBP_DEBUG(0)
1811sbp_show_sdev_info(sdev, 2);
1812printf("reconnect: len %d, ID %d, cmd %08x%08x\n", login_res->len, login_res->id, login_res->cmd_hi, login_res->cmd_lo);
1813END_DEBUG
1814#if 1
1815					if (sdev->status == SBP_DEV_ATTACHED)
1816						sbp_scan_dev(sdev);
1817					else
1818						sbp_agent_reset(sdev);
1819#else
1820					sdev->status = SBP_DEV_ATTACHED;
1821					sbp_mgm_orb(sdev, ORB_FUN_ATS, NULL);
1822#endif
1823				} else {
1824					/* reconnection hold time exceed? */
1825SBP_DEBUG(0)
1826					sbp_show_sdev_info(sdev, 2);
1827					printf("reconnect failed\n");
1828END_DEBUG
1829					sbp_login(sdev);
1830				}
1831				break;
1832			case ORB_FUN_LGO:
1833				sdev->status = SBP_DEV_RESET;
1834				break;
1835			case ORB_FUN_RST:
1836				sbp_busy_timeout(sdev);
1837				break;
1838			case ORB_FUN_LUR:
1839			case ORB_FUN_ATA:
1840			case ORB_FUN_ATS:
1841				sbp_agent_reset(sdev);
1842				break;
1843			default:
1844				sbp_show_sdev_info(sdev, 2);
1845				printf("unknown function %d\n", orb_fun);
1846				break;
1847			}
1848			sbp_mgm_orb(sdev, ORB_FUN_RUNQUEUE, NULL);
1849			break;
1850		case OCB_ACT_CMD:
1851			sdev->timeout = 0;
1852			if(ocb->ccb != NULL){
1853				union ccb *ccb;
1854/*
1855				uint32_t *ld;
1856				ld = ocb->ccb->csio.data_ptr;
1857				if(ld != NULL && ocb->ccb->csio.dxfer_len != 0)
1858					printf("ptr %08x %08x %08x %08x\n", ld[0], ld[1], ld[2], ld[3]);
1859				else
1860					printf("ptr NULL\n");
1861printf("len %d\n", sbp_status->len);
1862*/
1863				ccb = ocb->ccb;
1864				if(sbp_status->len > 1){
1865					sbp_scsi_status(sbp_status, ocb);
1866				}else{
1867					if(sbp_status->resp != ORB_RES_CMPL){
1868						ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1869					}else{
1870						ccb->ccb_h.status = CAM_REQ_CMP;
1871					}
1872				}
1873				/* fix up inq data */
1874				if (ccb->csio.cdb_io.cdb_bytes[0] == INQUIRY)
1875					sbp_fix_inq_data(ocb);
1876				SBP_LOCK(sbp);
1877				xpt_done(ccb);
1878				SBP_UNLOCK(sbp);
1879			}
1880			break;
1881		default:
1882			break;
1883		}
1884	}
1885
1886	if (!use_doorbell)
1887		sbp_free_ocb(sdev, ocb);
1888done:
1889	if (reset_agent)
1890		sbp_agent_reset(sdev);
1891
1892done0:
1893	xfer->recv.pay_len = SBP_RECV_LEN;
1894/* The received packet is usually small enough to be stored within
1895 * the buffer. In that case, the controller return ack_complete and
1896 * no respose is necessary.
1897 *
1898 * XXX fwohci.c and firewire.c should inform event_code such as
1899 * ack_complete or ack_pending to upper driver.
1900 */
1901#if NEED_RESPONSE
1902	xfer->send.off = 0;
1903	sfp = (struct fw_pkt *)xfer->send.buf;
1904	sfp->mode.wres.dst = rfp->mode.wreqb.src;
1905	xfer->dst = sfp->mode.wres.dst;
1906	xfer->spd = min(sdev->target->fwdev->speed, max_speed);
1907	xfer->hand = sbp_loginres_callback;
1908
1909	sfp->mode.wres.tlrt = rfp->mode.wreqb.tlrt;
1910	sfp->mode.wres.tcode = FWTCODE_WRES;
1911	sfp->mode.wres.rtcode = 0;
1912	sfp->mode.wres.pri = 0;
1913
1914	fw_asyreq(xfer->fc, -1, xfer);
1915#else
1916	/* recycle */
1917	STAILQ_INSERT_TAIL(&sbp->fwb.xferlist, xfer, link);
1918#endif
1919
1920	return;
1921
1922}
1923
1924static void
1925sbp_recv(struct fw_xfer *xfer)
1926{
1927	int s;
1928
1929	s = splcam();
1930	sbp_recv1(xfer);
1931	splx(s);
1932}
1933/*
1934 * sbp_attach()
1935 */
1936static int
1937sbp_attach(device_t dev)
1938{
1939	struct sbp_softc *sbp;
1940	struct cam_devq *devq;
1941	struct firewire_comm *fc;
1942	int i, s, error;
1943
1944	if (DFLTPHYS > SBP_MAXPHYS)
1945		device_printf(dev, "Warning, DFLTPHYS(%dKB) is larger than "
1946			"SBP_MAXPHYS(%dKB).\n", DFLTPHYS / 1024,
1947			SBP_MAXPHYS / 1024);
1948
1949SBP_DEBUG(0)
1950	printf("sbp_attach (cold=%d)\n", cold);
1951END_DEBUG
1952
1953	if (cold)
1954		sbp_cold ++;
1955	sbp = ((struct sbp_softc *)device_get_softc(dev));
1956	bzero(sbp, sizeof(struct sbp_softc));
1957	sbp->fd.dev = dev;
1958	sbp->fd.fc = fc = device_get_ivars(dev);
1959	mtx_init(&sbp->mtx, "sbp", NULL, MTX_DEF);
1960
1961	if (max_speed < 0)
1962		max_speed = fc->speed;
1963
1964	error = bus_dma_tag_create(/*parent*/fc->dmat,
1965				/* XXX shoud be 4 for sane backend? */
1966				/*alignment*/1,
1967				/*boundary*/0,
1968				/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
1969				/*highaddr*/BUS_SPACE_MAXADDR,
1970				/*filter*/NULL, /*filterarg*/NULL,
1971				/*maxsize*/0x100000, /*nsegments*/SBP_IND_MAX,
1972				/*maxsegsz*/SBP_SEG_MAX,
1973				/*flags*/BUS_DMA_ALLOCNOW,
1974#if defined(__FreeBSD__) && __FreeBSD_version >= 501102
1975				/*lockfunc*/busdma_lock_mutex,
1976				/*lockarg*/&sbp->mtx,
1977#endif
1978				&sbp->dmat);
1979	if (error != 0) {
1980		printf("sbp_attach: Could not allocate DMA tag "
1981			"- error %d\n", error);
1982			return (ENOMEM);
1983	}
1984
1985	devq = cam_simq_alloc(/*maxopenings*/SBP_NUM_OCB);
1986	if (devq == NULL)
1987		return (ENXIO);
1988
1989	for( i = 0 ; i < SBP_NUM_TARGETS ; i++){
1990		sbp->targets[i].fwdev = NULL;
1991		sbp->targets[i].luns = NULL;
1992	}
1993
1994	sbp->sim = cam_sim_alloc(sbp_action, sbp_poll, "sbp", sbp,
1995				 device_get_unit(dev),
1996				 &sbp->mtx,
1997				 /*untagged*/ 1,
1998				 /*tagged*/ SBP_QUEUE_LEN - 1,
1999				 devq);
2000
2001	if (sbp->sim == NULL) {
2002		cam_simq_free(devq);
2003		return (ENXIO);
2004	}
2005
2006	SBP_LOCK(sbp);
2007	if (xpt_bus_register(sbp->sim, /*bus*/0) != CAM_SUCCESS)
2008		goto fail;
2009
2010	if (xpt_create_path(&sbp->path, xpt_periph, cam_sim_path(sbp->sim),
2011	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2012		xpt_bus_deregister(cam_sim_path(sbp->sim));
2013		goto fail;
2014	}
2015	SBP_UNLOCK(sbp);
2016
2017	/* We reserve 16 bit space (4 bytes X 64 targets X 256 luns) */
2018	sbp->fwb.start = ((u_int64_t)SBP_BIND_HI << 32) | SBP_DEV2ADDR(0, 0);
2019	sbp->fwb.end = sbp->fwb.start + 0xffff;
2020	/* pre-allocate xfer */
2021	STAILQ_INIT(&sbp->fwb.xferlist);
2022	fw_xferlist_add(&sbp->fwb.xferlist, M_SBP,
2023	    /*send*/ 0, /*recv*/ SBP_RECV_LEN, SBP_NUM_OCB/2,
2024	    fc, (void *)sbp, sbp_recv);
2025
2026	fw_bindadd(fc, &sbp->fwb);
2027
2028	sbp->fd.post_busreset = sbp_post_busreset;
2029	sbp->fd.post_explore = sbp_post_explore;
2030
2031	if (fc->status != -1) {
2032		s = splfw();
2033		sbp_post_busreset((void *)sbp);
2034		sbp_post_explore((void *)sbp);
2035		splx(s);
2036	}
2037	SBP_LOCK(sbp);
2038	xpt_async(AC_BUS_RESET, sbp->path, /*arg*/ NULL);
2039	SBP_UNLOCK(sbp);
2040
2041	return (0);
2042fail:
2043	SBP_UNLOCK(sbp);
2044	cam_sim_free(sbp->sim, /*free_devq*/TRUE);
2045	return (ENXIO);
2046}
2047
2048static int
2049sbp_logout_all(struct sbp_softc *sbp)
2050{
2051	struct sbp_target *target;
2052	struct sbp_dev *sdev;
2053	int i, j;
2054
2055SBP_DEBUG(0)
2056	printf("sbp_logout_all\n");
2057END_DEBUG
2058	for (i = 0 ; i < SBP_NUM_TARGETS ; i ++) {
2059		target = &sbp->targets[i];
2060		if (target->luns == NULL)
2061			continue;
2062		for (j = 0; j < target->num_lun; j++) {
2063			sdev = target->luns[j];
2064			if (sdev == NULL)
2065				continue;
2066			callout_stop(&sdev->login_callout);
2067			if (sdev->status >= SBP_DEV_TOATTACH &&
2068					sdev->status <= SBP_DEV_ATTACHED)
2069				sbp_mgm_orb(sdev, ORB_FUN_LGO, NULL);
2070		}
2071	}
2072
2073	return 0;
2074}
2075
2076static int
2077sbp_shutdown(device_t dev)
2078{
2079	struct sbp_softc *sbp = ((struct sbp_softc *)device_get_softc(dev));
2080
2081	sbp_logout_all(sbp);
2082	return (0);
2083}
2084
2085static void
2086sbp_free_sdev(struct sbp_dev *sdev)
2087{
2088	int i;
2089
2090	if (sdev == NULL)
2091		return;
2092	for (i = 0; i < SBP_QUEUE_LEN; i++)
2093		bus_dmamap_destroy(sdev->target->sbp->dmat,
2094		    sdev->ocb[i].dmamap);
2095	fwdma_free(sdev->target->sbp->fd.fc, &sdev->dma);
2096	free(sdev, M_SBP);
2097}
2098
2099static void
2100sbp_free_target(struct sbp_target *target)
2101{
2102	struct sbp_softc *sbp;
2103	struct fw_xfer *xfer, *next;
2104	int i;
2105
2106	if (target->luns == NULL)
2107		return;
2108	callout_stop(&target->mgm_ocb_timeout);
2109	sbp = target->sbp;
2110	for (i = 0; i < target->num_lun; i++)
2111		sbp_free_sdev(target->luns[i]);
2112
2113	for (xfer = STAILQ_FIRST(&target->xferlist);
2114			xfer != NULL; xfer = next) {
2115		next = STAILQ_NEXT(xfer, link);
2116		fw_xfer_free_buf(xfer);
2117	}
2118	STAILQ_INIT(&target->xferlist);
2119	free(target->luns, M_SBP);
2120	target->num_lun = 0;;
2121	target->luns = NULL;
2122	target->fwdev = NULL;
2123}
2124
2125static int
2126sbp_detach(device_t dev)
2127{
2128	struct sbp_softc *sbp = ((struct sbp_softc *)device_get_softc(dev));
2129	struct firewire_comm *fc = sbp->fd.fc;
2130	int i;
2131
2132SBP_DEBUG(0)
2133	printf("sbp_detach\n");
2134END_DEBUG
2135
2136	for (i = 0; i < SBP_NUM_TARGETS; i ++)
2137		sbp_cam_detach_target(&sbp->targets[i]);
2138
2139	SBP_LOCK(sbp);
2140	xpt_async(AC_LOST_DEVICE, sbp->path, NULL);
2141	xpt_free_path(sbp->path);
2142	xpt_bus_deregister(cam_sim_path(sbp->sim));
2143	cam_sim_free(sbp->sim, /*free_devq*/ TRUE),
2144	SBP_UNLOCK(sbp);
2145
2146	sbp_logout_all(sbp);
2147
2148	/* XXX wait for logout completion */
2149	pause("sbpdtc", hz/2);
2150
2151	for (i = 0 ; i < SBP_NUM_TARGETS ; i ++)
2152		sbp_free_target(&sbp->targets[i]);
2153
2154	fw_bindremove(fc, &sbp->fwb);
2155	fw_xferlist_remove(&sbp->fwb.xferlist);
2156
2157	bus_dma_tag_destroy(sbp->dmat);
2158	mtx_destroy(&sbp->mtx);
2159
2160	return (0);
2161}
2162
2163static void
2164sbp_cam_detach_sdev(struct sbp_dev *sdev)
2165{
2166	if (sdev == NULL)
2167		return;
2168	if (sdev->status == SBP_DEV_DEAD)
2169		return;
2170	if (sdev->status == SBP_DEV_RESET)
2171		return;
2172	sbp_abort_all_ocbs(sdev, CAM_DEV_NOT_THERE);
2173	if (sdev->path) {
2174		SBP_LOCK(sdev->target->sbp);
2175		xpt_release_devq(sdev->path,
2176				 sdev->freeze, TRUE);
2177		sdev->freeze = 0;
2178		xpt_async(AC_LOST_DEVICE, sdev->path, NULL);
2179		xpt_free_path(sdev->path);
2180		sdev->path = NULL;
2181		SBP_UNLOCK(sdev->target->sbp);
2182	}
2183}
2184
2185static void
2186sbp_cam_detach_target(struct sbp_target *target)
2187{
2188	int i;
2189
2190	if (target->luns != NULL) {
2191SBP_DEBUG(0)
2192		printf("sbp_detach_target %d\n", target->target_id);
2193END_DEBUG
2194		callout_stop(&target->scan_callout);
2195		for (i = 0; i < target->num_lun; i++)
2196			sbp_cam_detach_sdev(target->luns[i]);
2197	}
2198}
2199
2200static void
2201sbp_target_reset(struct sbp_dev *sdev, int method)
2202{
2203	int i;
2204	struct sbp_target *target = sdev->target;
2205	struct sbp_dev *tsdev;
2206
2207	for (i = 0; i < target->num_lun; i++) {
2208		tsdev = target->luns[i];
2209		if (tsdev == NULL)
2210			continue;
2211		if (tsdev->status == SBP_DEV_DEAD)
2212			continue;
2213		if (tsdev->status == SBP_DEV_RESET)
2214			continue;
2215		SBP_LOCK(target->sbp);
2216		xpt_freeze_devq(tsdev->path, 1);
2217		tsdev->freeze ++;
2218		SBP_UNLOCK(target->sbp);
2219		sbp_abort_all_ocbs(tsdev, CAM_CMD_TIMEOUT);
2220		if (method == 2)
2221			tsdev->status = SBP_DEV_LOGIN;
2222	}
2223	switch(method) {
2224	case 1:
2225		printf("target reset\n");
2226		sbp_mgm_orb(sdev, ORB_FUN_RST, NULL);
2227		break;
2228	case 2:
2229		printf("reset start\n");
2230		sbp_reset_start(sdev);
2231		break;
2232	}
2233
2234}
2235
2236static void
2237sbp_mgm_timeout(void *arg)
2238{
2239	struct sbp_ocb *ocb = (struct sbp_ocb *)arg;
2240	struct sbp_dev *sdev = ocb->sdev;
2241	struct sbp_target *target = sdev->target;
2242
2243	sbp_show_sdev_info(sdev, 2);
2244	printf("request timeout(mgm orb:0x%08x) ... ",
2245	    (uint32_t)ocb->bus_addr);
2246	target->mgm_ocb_cur = NULL;
2247	sbp_free_ocb(sdev, ocb);
2248#if 0
2249	/* XXX */
2250	printf("run next request\n");
2251	sbp_mgm_orb(sdev, ORB_FUN_RUNQUEUE, NULL);
2252#endif
2253#if 1
2254	printf("reset start\n");
2255	sbp_reset_start(sdev);
2256#endif
2257}
2258
2259static void
2260sbp_timeout(void *arg)
2261{
2262	struct sbp_ocb *ocb = (struct sbp_ocb *)arg;
2263	struct sbp_dev *sdev = ocb->sdev;
2264
2265	sbp_show_sdev_info(sdev, 2);
2266	printf("request timeout(cmd orb:0x%08x) ... ",
2267	    (uint32_t)ocb->bus_addr);
2268
2269	sdev->timeout ++;
2270	switch(sdev->timeout) {
2271	case 1:
2272		printf("agent reset\n");
2273		SBP_LOCK(sdev->target->sbp);
2274		xpt_freeze_devq(sdev->path, 1);
2275		sdev->freeze ++;
2276		SBP_UNLOCK(sdev->target->sbp);
2277		sbp_abort_all_ocbs(sdev, CAM_CMD_TIMEOUT);
2278		sbp_agent_reset(sdev);
2279		break;
2280	case 2:
2281	case 3:
2282		sbp_target_reset(sdev, sdev->timeout - 1);
2283		break;
2284#if 0
2285	default:
2286		/* XXX give up */
2287		sbp_cam_detach_target(target);
2288		if (target->luns != NULL)
2289			free(target->luns, M_SBP);
2290		target->num_lun = 0;;
2291		target->luns = NULL;
2292		target->fwdev = NULL;
2293#endif
2294	}
2295}
2296
2297static void
2298sbp_action1(struct cam_sim *sim, union ccb *ccb)
2299{
2300
2301	struct sbp_softc *sbp = (struct sbp_softc *)sim->softc;
2302	struct sbp_target *target = NULL;
2303	struct sbp_dev *sdev = NULL;
2304
2305	/* target:lun -> sdev mapping */
2306	if (sbp != NULL
2307			&& ccb->ccb_h.target_id != CAM_TARGET_WILDCARD
2308			&& ccb->ccb_h.target_id < SBP_NUM_TARGETS) {
2309		target = &sbp->targets[ccb->ccb_h.target_id];
2310		if (target->fwdev != NULL
2311				&& ccb->ccb_h.target_lun != CAM_LUN_WILDCARD
2312				&& ccb->ccb_h.target_lun < target->num_lun) {
2313			sdev = target->luns[ccb->ccb_h.target_lun];
2314			if (sdev != NULL && sdev->status != SBP_DEV_ATTACHED &&
2315				sdev->status != SBP_DEV_PROBE)
2316				sdev = NULL;
2317		}
2318	}
2319
2320SBP_DEBUG(1)
2321	if (sdev == NULL)
2322		printf("invalid target %d lun %d\n",
2323			ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2324END_DEBUG
2325
2326	switch (ccb->ccb_h.func_code) {
2327	case XPT_SCSI_IO:
2328	case XPT_RESET_DEV:
2329	case XPT_GET_TRAN_SETTINGS:
2330	case XPT_SET_TRAN_SETTINGS:
2331	case XPT_CALC_GEOMETRY:
2332		if (sdev == NULL) {
2333SBP_DEBUG(1)
2334			printf("%s:%d:%d:func_code 0x%04x: "
2335				"Invalid target (target needed)\n",
2336				device_get_nameunit(sbp->fd.dev),
2337				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2338				ccb->ccb_h.func_code);
2339END_DEBUG
2340
2341			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2342			xpt_done(ccb);
2343			return;
2344		}
2345		break;
2346	case XPT_PATH_INQ:
2347	case XPT_NOOP:
2348		/* The opcodes sometimes aimed at a target (sc is valid),
2349		 * sometimes aimed at the SIM (sc is invalid and target is
2350		 * CAM_TARGET_WILDCARD)
2351		 */
2352		if (sbp == NULL &&
2353			ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
2354SBP_DEBUG(0)
2355			printf("%s:%d:%d func_code 0x%04x: "
2356				"Invalid target (no wildcard)\n",
2357				device_get_nameunit(sbp->fd.dev),
2358				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2359				ccb->ccb_h.func_code);
2360END_DEBUG
2361			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2362			xpt_done(ccb);
2363			return;
2364		}
2365		break;
2366	default:
2367		/* XXX Hm, we should check the input parameters */
2368		break;
2369	}
2370
2371	switch (ccb->ccb_h.func_code) {
2372	case XPT_SCSI_IO:
2373	{
2374		struct ccb_scsiio *csio;
2375		struct sbp_ocb *ocb;
2376		int speed;
2377		void *cdb;
2378
2379		csio = &ccb->csio;
2380		mtx_assert(sim->mtx, MA_OWNED);
2381
2382SBP_DEBUG(2)
2383		printf("%s:%d:%d XPT_SCSI_IO: "
2384			"cmd: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x"
2385			", flags: 0x%02x, "
2386			"%db cmd/%db data/%db sense\n",
2387			device_get_nameunit(sbp->fd.dev),
2388			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2389			csio->cdb_io.cdb_bytes[0],
2390			csio->cdb_io.cdb_bytes[1],
2391			csio->cdb_io.cdb_bytes[2],
2392			csio->cdb_io.cdb_bytes[3],
2393			csio->cdb_io.cdb_bytes[4],
2394			csio->cdb_io.cdb_bytes[5],
2395			csio->cdb_io.cdb_bytes[6],
2396			csio->cdb_io.cdb_bytes[7],
2397			csio->cdb_io.cdb_bytes[8],
2398			csio->cdb_io.cdb_bytes[9],
2399			ccb->ccb_h.flags & CAM_DIR_MASK,
2400			csio->cdb_len, csio->dxfer_len,
2401			csio->sense_len);
2402END_DEBUG
2403		if(sdev == NULL){
2404			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2405			xpt_done(ccb);
2406			return;
2407		}
2408#if 0
2409		/* if we are in probe stage, pass only probe commands */
2410		if (sdev->status == SBP_DEV_PROBE) {
2411			char *name;
2412			name = xpt_path_periph(ccb->ccb_h.path)->periph_name;
2413			printf("probe stage, periph name: %s\n", name);
2414			if (strcmp(name, "probe") != 0) {
2415				ccb->ccb_h.status = CAM_REQUEUE_REQ;
2416				xpt_done(ccb);
2417				return;
2418			}
2419		}
2420#endif
2421		if ((ocb = sbp_get_ocb(sdev)) == NULL) {
2422			ccb->ccb_h.status = CAM_REQUEUE_REQ;
2423			if (sdev->freeze == 0) {
2424				SBP_LOCK(sdev->target->sbp);
2425				xpt_freeze_devq(sdev->path, 1);
2426				sdev->freeze ++;
2427				SBP_UNLOCK(sdev->target->sbp);
2428			}
2429			xpt_done(ccb);
2430			return;
2431		}
2432
2433		ocb->flags = OCB_ACT_CMD;
2434		ocb->sdev = sdev;
2435		ocb->ccb = ccb;
2436		ccb->ccb_h.ccb_sdev_ptr = sdev;
2437		ocb->orb[0] = htonl(1 << 31);
2438		ocb->orb[1] = 0;
2439		ocb->orb[2] = htonl(((sbp->fd.fc->nodeid | FWLOCALBUS )<< 16) );
2440		ocb->orb[3] = htonl(ocb->bus_addr + IND_PTR_OFFSET);
2441		speed = min(target->fwdev->speed, max_speed);
2442		ocb->orb[4] = htonl(ORB_NOTIFY | ORB_CMD_SPD(speed)
2443						| ORB_CMD_MAXP(speed + 7));
2444		if((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN){
2445			ocb->orb[4] |= htonl(ORB_CMD_IN);
2446		}
2447
2448		if (csio->ccb_h.flags & CAM_SCATTER_VALID)
2449			printf("sbp: CAM_SCATTER_VALID\n");
2450		if (csio->ccb_h.flags & CAM_DATA_PHYS)
2451			printf("sbp: CAM_DATA_PHYS\n");
2452
2453		if (csio->ccb_h.flags & CAM_CDB_POINTER)
2454			cdb = (void *)csio->cdb_io.cdb_ptr;
2455		else
2456			cdb = (void *)&csio->cdb_io.cdb_bytes;
2457		bcopy(cdb, (void *)&ocb->orb[5], csio->cdb_len);
2458/*
2459printf("ORB %08x %08x %08x %08x\n", ntohl(ocb->orb[0]), ntohl(ocb->orb[1]), ntohl(ocb->orb[2]), ntohl(ocb->orb[3]));
2460printf("ORB %08x %08x %08x %08x\n", ntohl(ocb->orb[4]), ntohl(ocb->orb[5]), ntohl(ocb->orb[6]), ntohl(ocb->orb[7]));
2461*/
2462		if (ccb->csio.dxfer_len > 0) {
2463			int s, error;
2464
2465			s = splsoftvm();
2466			error = bus_dmamap_load(/*dma tag*/sbp->dmat,
2467					/*dma map*/ocb->dmamap,
2468					ccb->csio.data_ptr,
2469					ccb->csio.dxfer_len,
2470					sbp_execute_ocb,
2471					ocb,
2472					/*flags*/0);
2473			splx(s);
2474			if (error)
2475				printf("sbp: bus_dmamap_load error %d\n", error);
2476		} else
2477			sbp_execute_ocb(ocb, NULL, 0, 0);
2478		break;
2479	}
2480	case XPT_CALC_GEOMETRY:
2481	{
2482		struct ccb_calc_geometry *ccg;
2483#if defined(__DragonFly__) || __FreeBSD_version < 501100
2484		uint32_t size_mb;
2485		uint32_t secs_per_cylinder;
2486		int extended = 1;
2487#endif
2488
2489		ccg = &ccb->ccg;
2490		if (ccg->block_size == 0) {
2491			printf("sbp_action1: block_size is 0.\n");
2492			ccb->ccb_h.status = CAM_REQ_INVALID;
2493			xpt_done(ccb);
2494			break;
2495		}
2496SBP_DEBUG(1)
2497		printf("%s:%d:%d:%d:XPT_CALC_GEOMETRY: "
2498#if defined(__DragonFly__) || __FreeBSD_version < 500000
2499			"Volume size = %d\n",
2500#else
2501			"Volume size = %jd\n",
2502#endif
2503			device_get_nameunit(sbp->fd.dev),
2504			cam_sim_path(sbp->sim),
2505			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2506#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2507			(uintmax_t)
2508#endif
2509				ccg->volume_size);
2510END_DEBUG
2511
2512#if defined(__DragonFly__) || __FreeBSD_version < 501100
2513		size_mb = ccg->volume_size
2514			/ ((1024L * 1024L) / ccg->block_size);
2515
2516		if (size_mb > 1024 && extended) {
2517			ccg->heads = 255;
2518			ccg->secs_per_track = 63;
2519		} else {
2520			ccg->heads = 64;
2521			ccg->secs_per_track = 32;
2522		}
2523		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2524		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2525		ccb->ccb_h.status = CAM_REQ_CMP;
2526#else
2527		cam_calc_geometry(ccg, /*extended*/1);
2528#endif
2529		xpt_done(ccb);
2530		break;
2531	}
2532	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2533	{
2534
2535SBP_DEBUG(1)
2536		printf("%s:%d:XPT_RESET_BUS: \n",
2537			device_get_nameunit(sbp->fd.dev), cam_sim_path(sbp->sim));
2538END_DEBUG
2539
2540		ccb->ccb_h.status = CAM_REQ_INVALID;
2541		xpt_done(ccb);
2542		break;
2543	}
2544	case XPT_PATH_INQ:		/* Path routing inquiry */
2545	{
2546		struct ccb_pathinq *cpi = &ccb->cpi;
2547
2548SBP_DEBUG(1)
2549		printf("%s:%d:%d XPT_PATH_INQ:.\n",
2550			device_get_nameunit(sbp->fd.dev),
2551			ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2552END_DEBUG
2553		cpi->version_num = 1; /* XXX??? */
2554		cpi->hba_inquiry = PI_TAG_ABLE;
2555		cpi->target_sprt = 0;
2556		cpi->hba_misc = PIM_NOBUSRESET | PIM_NO_6_BYTE;
2557		cpi->hba_eng_cnt = 0;
2558		cpi->max_target = SBP_NUM_TARGETS - 1;
2559		cpi->max_lun = SBP_NUM_LUNS - 1;
2560		cpi->initiator_id = SBP_INITIATOR;
2561		cpi->bus_id = sim->bus_id;
2562		cpi->base_transfer_speed = 400 * 1000 / 8;
2563		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2564		strncpy(cpi->hba_vid, "SBP", HBA_IDLEN);
2565		strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
2566		cpi->unit_number = sim->unit_number;
2567                cpi->transport = XPORT_SPI;	/* XX should have a FireWire */
2568                cpi->transport_version = 2;
2569                cpi->protocol = PROTO_SCSI;
2570                cpi->protocol_version = SCSI_REV_2;
2571
2572		cpi->ccb_h.status = CAM_REQ_CMP;
2573		xpt_done(ccb);
2574		break;
2575	}
2576	case XPT_GET_TRAN_SETTINGS:
2577	{
2578		struct ccb_trans_settings *cts = &ccb->cts;
2579		struct ccb_trans_settings_scsi *scsi =
2580		    &cts->proto_specific.scsi;
2581		struct ccb_trans_settings_spi *spi =
2582		    &cts->xport_specific.spi;
2583
2584		cts->protocol = PROTO_SCSI;
2585		cts->protocol_version = SCSI_REV_2;
2586		cts->transport = XPORT_SPI;	/* should have a FireWire */
2587		cts->transport_version = 2;
2588		spi->valid = CTS_SPI_VALID_DISC;
2589		spi->flags = CTS_SPI_FLAGS_DISC_ENB;
2590		scsi->valid = CTS_SCSI_VALID_TQ;
2591		scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
2592SBP_DEBUG(1)
2593		printf("%s:%d:%d XPT_GET_TRAN_SETTINGS:.\n",
2594			device_get_nameunit(sbp->fd.dev),
2595			ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2596END_DEBUG
2597		cts->ccb_h.status = CAM_REQ_CMP;
2598		xpt_done(ccb);
2599		break;
2600	}
2601	case XPT_ABORT:
2602		ccb->ccb_h.status = CAM_UA_ABORT;
2603		xpt_done(ccb);
2604		break;
2605	case XPT_SET_TRAN_SETTINGS:
2606		/* XXX */
2607	default:
2608		ccb->ccb_h.status = CAM_REQ_INVALID;
2609		xpt_done(ccb);
2610		break;
2611	}
2612	return;
2613}
2614
2615static void
2616sbp_action(struct cam_sim *sim, union ccb *ccb)
2617{
2618	int s;
2619
2620	s = splfw();
2621	sbp_action1(sim, ccb);
2622	splx(s);
2623}
2624
2625static void
2626sbp_execute_ocb(void *arg,  bus_dma_segment_t *segments, int seg, int error)
2627{
2628	int i;
2629	struct sbp_ocb *ocb;
2630	struct sbp_ocb *prev;
2631	bus_dma_segment_t *s;
2632
2633	if (error)
2634		printf("sbp_execute_ocb: error=%d\n", error);
2635
2636	ocb = (struct sbp_ocb *)arg;
2637
2638SBP_DEBUG(2)
2639	printf("sbp_execute_ocb: seg %d", seg);
2640	for (i = 0; i < seg; i++)
2641#if defined(__DragonFly__) || __FreeBSD_version < 500000
2642		printf(", %x:%d", segments[i].ds_addr, segments[i].ds_len);
2643#else
2644		printf(", %jx:%jd", (uintmax_t)segments[i].ds_addr,
2645					(uintmax_t)segments[i].ds_len);
2646#endif
2647	printf("\n");
2648END_DEBUG
2649
2650	if (seg == 1) {
2651		/* direct pointer */
2652		s = &segments[0];
2653		if (s->ds_len > SBP_SEG_MAX)
2654			panic("ds_len > SBP_SEG_MAX, fix busdma code");
2655		ocb->orb[3] = htonl(s->ds_addr);
2656		ocb->orb[4] |= htonl(s->ds_len);
2657	} else if(seg > 1) {
2658		/* page table */
2659		for (i = 0; i < seg; i++) {
2660			s = &segments[i];
2661SBP_DEBUG(0)
2662			/* XXX LSI Logic "< 16 byte" bug might be hit */
2663			if (s->ds_len < 16)
2664				printf("sbp_execute_ocb: warning, "
2665#if defined(__DragonFly__) || __FreeBSD_version < 500000
2666					"segment length(%d) is less than 16."
2667#else
2668					"segment length(%zd) is less than 16."
2669#endif
2670					"(seg=%d/%d)\n", s->ds_len, i+1, seg);
2671END_DEBUG
2672			if (s->ds_len > SBP_SEG_MAX)
2673				panic("ds_len > SBP_SEG_MAX, fix busdma code");
2674			ocb->ind_ptr[i].hi = htonl(s->ds_len << 16);
2675			ocb->ind_ptr[i].lo = htonl(s->ds_addr);
2676		}
2677		ocb->orb[4] |= htonl(ORB_CMD_PTBL | seg);
2678	}
2679
2680	if (seg > 0)
2681		bus_dmamap_sync(ocb->sdev->target->sbp->dmat, ocb->dmamap,
2682			(ntohl(ocb->orb[4]) & ORB_CMD_IN) ?
2683			BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
2684	prev = sbp_enqueue_ocb(ocb->sdev, ocb);
2685	fwdma_sync(&ocb->sdev->dma, BUS_DMASYNC_PREWRITE);
2686	if (use_doorbell) {
2687		if (prev == NULL) {
2688			if (ocb->sdev->last_ocb != NULL)
2689				sbp_doorbell(ocb->sdev);
2690			else
2691				sbp_orb_pointer(ocb->sdev, ocb);
2692		}
2693	} else {
2694		if (prev == NULL || (ocb->sdev->flags & ORB_LINK_DEAD) != 0) {
2695			ocb->sdev->flags &= ~ORB_LINK_DEAD;
2696			sbp_orb_pointer(ocb->sdev, ocb);
2697		}
2698	}
2699}
2700
2701static void
2702sbp_poll(struct cam_sim *sim)
2703{
2704	struct sbp_softc *sbp;
2705	struct firewire_comm *fc;
2706
2707	sbp = (struct sbp_softc *)sim->softc;
2708	fc = sbp->fd.fc;
2709
2710	fc->poll(fc, 0, -1);
2711
2712	return;
2713}
2714
2715static struct sbp_ocb *
2716sbp_dequeue_ocb(struct sbp_dev *sdev, struct sbp_status *sbp_status)
2717{
2718	struct sbp_ocb *ocb;
2719	struct sbp_ocb *next;
2720	int s = splfw(), order = 0;
2721	int flags;
2722
2723SBP_DEBUG(1)
2724	sbp_show_sdev_info(sdev, 2);
2725#if defined(__DragonFly__) || __FreeBSD_version < 500000
2726	printf("%s: 0x%08lx src %d\n",
2727#else
2728	printf("%s: 0x%08x src %d\n",
2729#endif
2730	    __func__, ntohl(sbp_status->orb_lo), sbp_status->src);
2731END_DEBUG
2732	SBP_LOCK(sdev->target->sbp);
2733	for (ocb = STAILQ_FIRST(&sdev->ocbs); ocb != NULL; ocb = next) {
2734		next = STAILQ_NEXT(ocb, ocb);
2735		flags = ocb->flags;
2736		if (OCB_MATCH(ocb, sbp_status)) {
2737			/* found */
2738			STAILQ_REMOVE(&sdev->ocbs, ocb, sbp_ocb, ocb);
2739			if (ocb->ccb != NULL)
2740				untimeout(sbp_timeout, (caddr_t)ocb,
2741						ocb->ccb->ccb_h.timeout_ch);
2742			if (ntohl(ocb->orb[4]) & 0xffff) {
2743				bus_dmamap_sync(sdev->target->sbp->dmat,
2744					ocb->dmamap,
2745					(ntohl(ocb->orb[4]) & ORB_CMD_IN) ?
2746					BUS_DMASYNC_POSTREAD :
2747					BUS_DMASYNC_POSTWRITE);
2748				bus_dmamap_unload(sdev->target->sbp->dmat,
2749					ocb->dmamap);
2750			}
2751			if (!use_doorbell) {
2752				if (sbp_status->src == SRC_NO_NEXT) {
2753					if (next != NULL)
2754						sbp_orb_pointer(sdev, next);
2755					else if (order > 0) {
2756						/*
2757						 * Unordered execution
2758						 * We need to send pointer for
2759						 * next ORB
2760						 */
2761						sdev->flags |= ORB_LINK_DEAD;
2762					}
2763				}
2764			} else {
2765				/*
2766				 * XXX this is not correct for unordered
2767				 * execution.
2768				 */
2769				if (sdev->last_ocb != NULL)
2770					sbp_free_ocb(sdev, sdev->last_ocb);
2771				sdev->last_ocb = ocb;
2772				if (next != NULL &&
2773				    sbp_status->src == SRC_NO_NEXT)
2774					sbp_doorbell(sdev);
2775			}
2776			break;
2777		} else
2778			order ++;
2779	}
2780	SBP_UNLOCK(sdev->target->sbp);
2781	splx(s);
2782SBP_DEBUG(0)
2783	if (ocb && order > 0) {
2784		sbp_show_sdev_info(sdev, 2);
2785		printf("unordered execution order:%d\n", order);
2786	}
2787END_DEBUG
2788	return (ocb);
2789}
2790
2791static struct sbp_ocb *
2792sbp_enqueue_ocb(struct sbp_dev *sdev, struct sbp_ocb *ocb)
2793{
2794	int s = splfw();
2795	struct sbp_ocb *prev, *prev2;
2796
2797SBP_DEBUG(1)
2798	sbp_show_sdev_info(sdev, 2);
2799#if defined(__DragonFly__) || __FreeBSD_version < 500000
2800	printf("%s: 0x%08x\n", __func__, ocb->bus_addr);
2801#else
2802	printf("%s: 0x%08jx\n", __func__, (uintmax_t)ocb->bus_addr);
2803#endif
2804END_DEBUG
2805	prev2 = prev = STAILQ_LAST(&sdev->ocbs, sbp_ocb, ocb);
2806	STAILQ_INSERT_TAIL(&sdev->ocbs, ocb, ocb);
2807
2808	if (ocb->ccb != NULL)
2809		ocb->ccb->ccb_h.timeout_ch = timeout(sbp_timeout, (caddr_t)ocb,
2810					(ocb->ccb->ccb_h.timeout * hz) / 1000);
2811
2812	if (use_doorbell && prev == NULL)
2813		prev2 = sdev->last_ocb;
2814
2815	if (prev2 != NULL) {
2816SBP_DEBUG(2)
2817#if defined(__DragonFly__) || __FreeBSD_version < 500000
2818		printf("linking chain 0x%x -> 0x%x\n",
2819		    prev2->bus_addr, ocb->bus_addr);
2820#else
2821		printf("linking chain 0x%jx -> 0x%jx\n",
2822		    (uintmax_t)prev2->bus_addr, (uintmax_t)ocb->bus_addr);
2823#endif
2824END_DEBUG
2825		prev2->orb[1] = htonl(ocb->bus_addr);
2826		prev2->orb[0] = 0;
2827	}
2828	splx(s);
2829
2830	return prev;
2831}
2832
2833static struct sbp_ocb *
2834sbp_get_ocb(struct sbp_dev *sdev)
2835{
2836	struct sbp_ocb *ocb;
2837	int s = splfw();
2838
2839	mtx_assert(&sdev->target->sbp->mtx, MA_OWNED);
2840	ocb = STAILQ_FIRST(&sdev->free_ocbs);
2841	if (ocb == NULL) {
2842		sdev->flags |= ORB_SHORTAGE;
2843		printf("ocb shortage!!!\n");
2844		splx(s);
2845		return NULL;
2846	}
2847	STAILQ_REMOVE_HEAD(&sdev->free_ocbs, ocb);
2848	splx(s);
2849	ocb->ccb = NULL;
2850	return (ocb);
2851}
2852
2853static void
2854sbp_free_ocb(struct sbp_dev *sdev, struct sbp_ocb *ocb)
2855{
2856	ocb->flags = 0;
2857	ocb->ccb = NULL;
2858
2859	SBP_LOCK(sdev->target->sbp);
2860	STAILQ_INSERT_TAIL(&sdev->free_ocbs, ocb, ocb);
2861	if ((sdev->flags & ORB_SHORTAGE) != 0) {
2862		int count;
2863
2864		sdev->flags &= ~ORB_SHORTAGE;
2865		count = sdev->freeze;
2866		sdev->freeze = 0;
2867		xpt_release_devq(sdev->path, count, TRUE);
2868	}
2869	SBP_UNLOCK(sdev->target->sbp);
2870}
2871
2872static void
2873sbp_abort_ocb(struct sbp_ocb *ocb, int status)
2874{
2875	struct sbp_dev *sdev;
2876
2877	sdev = ocb->sdev;
2878SBP_DEBUG(0)
2879	sbp_show_sdev_info(sdev, 2);
2880#if defined(__DragonFly__) || __FreeBSD_version < 500000
2881	printf("sbp_abort_ocb 0x%x\n", ocb->bus_addr);
2882#else
2883	printf("sbp_abort_ocb 0x%jx\n", (uintmax_t)ocb->bus_addr);
2884#endif
2885END_DEBUG
2886SBP_DEBUG(1)
2887	if (ocb->ccb != NULL)
2888		sbp_print_scsi_cmd(ocb);
2889END_DEBUG
2890	if (ntohl(ocb->orb[4]) & 0xffff) {
2891		bus_dmamap_sync(sdev->target->sbp->dmat, ocb->dmamap,
2892			(ntohl(ocb->orb[4]) & ORB_CMD_IN) ?
2893			BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
2894		bus_dmamap_unload(sdev->target->sbp->dmat, ocb->dmamap);
2895	}
2896	if (ocb->ccb != NULL) {
2897		untimeout(sbp_timeout, (caddr_t)ocb,
2898					ocb->ccb->ccb_h.timeout_ch);
2899		ocb->ccb->ccb_h.status = status;
2900		SBP_LOCK(sdev->target->sbp);
2901		xpt_done(ocb->ccb);
2902		SBP_UNLOCK(sdev->target->sbp);
2903	}
2904	sbp_free_ocb(sdev, ocb);
2905}
2906
2907static void
2908sbp_abort_all_ocbs(struct sbp_dev *sdev, int status)
2909{
2910	int s;
2911	struct sbp_ocb *ocb, *next;
2912	STAILQ_HEAD(, sbp_ocb) temp;
2913
2914	s = splfw();
2915
2916	bcopy(&sdev->ocbs, &temp, sizeof(temp));
2917	STAILQ_INIT(&sdev->ocbs);
2918	for (ocb = STAILQ_FIRST(&temp); ocb != NULL; ocb = next) {
2919		next = STAILQ_NEXT(ocb, ocb);
2920		sbp_abort_ocb(ocb, status);
2921	}
2922	if (sdev->last_ocb != NULL) {
2923		sbp_free_ocb(sdev, sdev->last_ocb);
2924		sdev->last_ocb = NULL;
2925	}
2926
2927	splx(s);
2928}
2929
2930static devclass_t sbp_devclass;
2931
2932static device_method_t sbp_methods[] = {
2933	/* device interface */
2934	DEVMETHOD(device_identify,	sbp_identify),
2935	DEVMETHOD(device_probe,		sbp_probe),
2936	DEVMETHOD(device_attach,	sbp_attach),
2937	DEVMETHOD(device_detach,	sbp_detach),
2938	DEVMETHOD(device_shutdown,	sbp_shutdown),
2939
2940	{ 0, 0 }
2941};
2942
2943static driver_t sbp_driver = {
2944	"sbp",
2945	sbp_methods,
2946	sizeof(struct sbp_softc),
2947};
2948#ifdef __DragonFly__
2949DECLARE_DUMMY_MODULE(sbp);
2950#endif
2951DRIVER_MODULE(sbp, firewire, sbp_driver, sbp_devclass, 0, 0);
2952MODULE_VERSION(sbp, 1);
2953MODULE_DEPEND(sbp, firewire, 1, 1, 1);
2954MODULE_DEPEND(sbp, cam, 1, 1, 1);
2955