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