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