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