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