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