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