xref: /openbsd-src/sys/dev/usb/umass.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: umass.c,v 1.11 2001/05/24 06:21:44 csapuntz Exp $ */
2 /*	$NetBSD: umass.c,v 1.49 2001/01/21 18:56:38 augustss Exp $	*/
3 /*-
4  * Copyright (c) 1999 MAEKAWA Masahide <bishop@rr.iij4u.or.jp>,
5  *		      Nick Hibma <n_hibma@freebsd.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *     $FreeBSD: src/sys/dev/usb/umass.c,v 1.13 2000/03/26 01:39:12 n_hibma Exp $
30  */
31 
32 /*
33  * Universal Serial Bus Mass Storage Class Bulk-Only Transport
34  * http://www.usb.org/developers/data/devclass/usbmassover_11.pdf
35  * http://www.usb.org/developers/data/devclass/usbmassbulk_10.pdf
36  * http://www.usb.org/developers/data/devclass/usbmass-cbi10.pdf
37  * http://www.usb.org/developers/data/devclass/usbmass-ufi10.pdf
38  */
39 
40 /*
41  * Ported to NetBSD by Lennart Augustsson <augustss@netbsd.org>.
42  * Parts of the code written my Jason R. Thorpe <thorpej@shagadelic.org>.
43  */
44 
45 /*
46  * The driver handles 3 Wire Protocols
47  * - Command/Bulk/Interrupt (CBI)
48  * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
49  * - Mass Storage Bulk-Only (BBB)
50  *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
51  *
52  * Over these wire protocols it handles the following command protocols
53  * - SCSI
54  * - UFI (floppy command set)
55  * - 8070 (ATA/ATAPI)
56  *
57  * UFI and 8070i are transformed versions of the SCSI command set. The
58  * sc->transform method is used to convert the commands into the appropriate
59  * format (if at all necessary). For example, UFI requires all commands to be
60  * 12 bytes in length amongst other things.
61  *
62  * The source code below is marked and can be split into a number of pieces
63  * (in this order):
64  *
65  * - probe/attach/detach
66  * - generic transfer routines
67  * - BBB
68  * - CBI
69  * - CBI_I (in addition to functions from CBI)
70  * - CAM (Common Access Method)
71  * - SCSI
72  * - UFI
73  * - 8070i
74  *
75  * The protocols are implemented using a state machine, for the transfers as
76  * well as for the resets. The state machine is contained in umass_*_state.
77  * The state machine is started through either umass_*_transfer or
78  * umass_*_reset.
79  *
80  * The reason for doing this is a) CAM performs a lot better this way and b) it
81  * avoids using tsleep from interrupt context (for example after a failed
82  * transfer).
83  */
84 
85 /*
86  * The SCSI related part of this driver has been derived from the
87  * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch@freebsd.org).
88  *
89  * The CAM layer uses so called actions which are messages sent to the host
90  * adapter for completion. The actions come in through umass_cam_action. The
91  * appropriate block of routines is called depending on the transport protocol
92  * in use. When the transfer has finished, these routines call
93  * umass_cam_cb again to complete the CAM command.
94  */
95 
96 /* XXX Should we split the driver into a number of files?  umass.c,
97  *     umass_scsi.c, umass_8070.c, umass_ufi.c, umass_bbb.c, umass_cbi.c or
98  *     something similar?
99  */
100 
101 #if !defined(__OpenBSD__)
102 #include "atapibus.h"
103 #endif
104 
105 #include <sys/param.h>
106 #include <sys/systm.h>
107 #include <sys/kernel.h>
108 #include <sys/conf.h>
109 #if defined(__NetBSD__) || defined(__OpenBSD__)
110 #include <sys/buf.h>
111 #include <sys/device.h>
112 #include <sys/ioctl.h>
113 #include <sys/malloc.h>
114 #undef KASSERT
115 #define KASSERT(cond, msg)
116 #elif defined(__FreeBSD__)
117 #include <sys/module.h>
118 #include <sys/bus.h>
119 #include <machine/clock.h>
120 #endif
121 
122 #include <dev/usb/usb.h>
123 #include <dev/usb/usbdi.h>
124 #include <dev/usb/usbdi_util.h>
125 #include <dev/usb/usbdevs.h>
126 
127 #if defined(__FreeBSD__)
128 #include <cam/cam.h>
129 #include <cam/cam_ccb.h>
130 #include <cam/cam_sim.h>
131 #include <cam/cam_xpt_sim.h>
132 #include <cam/scsi/scsi_all.h>
133 #include <cam/scsi/scsi_da.h>
134 
135 #ifdef UMASS_DO_CAM_RESCAN
136 #include <sys/devicestat.h>
137 #include <cam/cam_periph.h>
138 #endif
139 
140 #elif defined(__NetBSD__)
141 #include <sys/scsiio.h>
142 #include <dev/scsipi/scsi_all.h>
143 #include <dev/scsipi/scsipi_all.h>
144 #include <dev/scsipi/scsiconf.h>
145 
146 #include <dev/scsipi/atapiconf.h>
147 
148 #include <dev/scsipi/scsipi_disk.h>
149 #include <dev/scsipi/scsi_disk.h>
150 #include <dev/scsipi/scsi_changer.h>
151 
152 #include <dev/ata/atavar.h>	/* XXX */
153 
154 #define SCSI_LINK_TARGET(sc)  ((sc)->scsipi_scsi.target)
155 #define SCSI_LINK_LUN(sc)     ((sc)->scsipi_scsi.lun)
156 #elif defined(__OpenBSD__)
157 #include <scsi/scsi_all.h>
158 #include <scsi/scsiconf.h>
159 #include <scsi/scsi_disk.h>
160 #include <machine/bus.h>
161 
162 #define SCSI_LINK_TARGET(sc)  ((sc)->target)
163 #define SCSI_LINK_LUN(sc)     ((sc)->lun)
164 #define scsipi_generic   scsi_generic
165 
166 #endif
167 
168 #define SHORT_INQUIRY_LENGTH    36 /* XXX */
169 
170 #ifdef UMASS_DEBUG
171 #define DIF(m, x)	if (umassdebug & (m)) do { x ; } while (0)
172 #define DPRINTF(m, x)	if (umassdebug & (m)) logprintf x
173 #define UDMASS_UPPER	0x00008000	/* upper layer */
174 #define UDMASS_GEN	0x00010000	/* general */
175 #define UDMASS_SCSI	0x00020000	/* scsi */
176 #define UDMASS_UFI	0x00040000	/* ufi command set */
177 #define UDMASS_8070	0x00080000	/* 8070i command set */
178 #define UDMASS_USB	0x00100000	/* USB general */
179 #define UDMASS_BBB	0x00200000	/* Bulk-Only transfers */
180 #define UDMASS_CBI	0x00400000	/* CBI transfers */
181 #define UDMASS_ALL	0xffff0000	/* all of the above */
182 
183 #define UDMASS_XFER	0x40000000	/* all transfers */
184 #define UDMASS_CMD	0x80000000
185 
186 int umassdebug = 0;
187 #else
188 #define DIF(m, x)	/* nop */
189 #define DPRINTF(m, x)	/* nop */
190 #endif
191 
192 
193 /* Generic definitions */
194 
195 #define UFI_COMMAND_LENGTH 12
196 #define ATAPI_COMMAND_LENGTH 12
197 
198 /* Direction for umass_*_transfer */
199 #define DIR_NONE	0
200 #define DIR_IN		1
201 #define DIR_OUT		2
202 
203 /* The transfer speed determines the timeout value */
204 #define UMASS_DEFAULT_TRANSFER_SPEED	150	/* in kb/s, conservative est. */
205 #define UMASS_FLOPPY_TRANSFER_SPEED	20
206 #define UMASS_ZIP100_TRANSFER_SPEED	650
207 
208 #define UMASS_SPINUP_TIME 10000	/* ms */
209 
210 #ifdef __FreeBSD__
211 /* device name */
212 #define DEVNAME		"umass"
213 #define DEVNAME_SIM	"umass-"
214 
215 #define UMASS_MAX_TRANSFER_SIZE		65536
216 
217 /* CAM specific definitions */
218 
219 /* The bus id, whatever that is */
220 #define UMASS_SCSI_BUS		0
221 
222 /* All USB drives are 'connected' to one SIM (SCSI controller). umass3
223  * ends up being target 3 on that SIM. When a request for target 3
224  * comes in we fetch the softc with devclass_get_softc(target_id).
225  *
226  * The SIM is the highest target number. This makes sure that umass0 corresponds
227  * to target 0 on the USB SCSI bus.
228  */
229 #ifndef UMASS_DEBUG
230 #define UMASS_SCSIID_MAX	32	/* maximum number of drives expected */
231 #else
232 /* while debugging avoid unnecessary clutter in the output at umass_cam_rescan
233  * (XPT_PATH_INQ)
234  */
235 #define UMASS_SCSIID_MAX	3	/* maximum number of drives expected */
236 #endif
237 #define UMASS_SCSIID_HOST	UMASS_SCSIID_MAX
238 #endif
239 
240 #define MS_TO_TICKS(ms) ((ms) * hz / 1000)
241 
242 
243 /* Bulk-Only features */
244 
245 #define UR_BBB_RESET	0xff		/* Bulk-Only reset */
246 #define	UR_BBB_GET_MAX_LUN	0xfe
247 
248 /* Command Block Wrapper */
249 typedef struct {
250 	uDWord		dCBWSignature;
251 #	define CBWSIGNATURE	0x43425355
252 	uDWord		dCBWTag;
253 	uDWord		dCBWDataTransferLength;
254 	uByte		bCBWFlags;
255 #	define CBWFLAGS_OUT	0x00
256 #	define CBWFLAGS_IN	0x80
257 	uByte		bCBWLUN;
258 	uByte		bCDBLength;
259 #	define CBWCDBLENGTH	16
260 	uByte		CBWCDB[CBWCDBLENGTH];
261 } umass_bbb_cbw_t;
262 #define UMASS_BBB_CBW_SIZE	31
263 
264 /* Command Status Wrapper */
265 typedef struct {
266 	uDWord		dCSWSignature;
267 #	define CSWSIGNATURE	0x53425355
268 	uDWord		dCSWTag;
269 	uDWord		dCSWDataResidue;
270 	uByte		bCSWStatus;
271 #	define CSWSTATUS_GOOD	0x0
272 #	define CSWSTATUS_FAILED 0x1
273 #	define CSWSTATUS_PHASE	0x2
274 } umass_bbb_csw_t;
275 #define UMASS_BBB_CSW_SIZE	13
276 
277 /* CBI features */
278 
279 #define UR_CBI_ADSC	0x00
280 
281 typedef unsigned char umass_cbi_cbl_t[16];	/* Command block */
282 
283 typedef union {
284 	struct {
285 		unsigned char	type;
286 		#define IDB_TYPE_CCI		0x00
287 		unsigned char	value;
288 		#define IDB_VALUE_PASS		0x00
289 		#define IDB_VALUE_FAIL		0x01
290 		#define IDB_VALUE_PHASE		0x02
291 		#define IDB_VALUE_PERSISTENT	0x03
292 		#define IDB_VALUE_STATUS_MASK	0x03
293 	} common;
294 
295 	struct {
296 		unsigned char	asc;
297 		unsigned char	ascq;
298 	} ufi;
299 } umass_cbi_sbl_t;
300 
301 
302 
303 struct umass_softc;		/* see below */
304 
305 typedef void (*transfer_cb_f)	__P((struct umass_softc *sc, void *priv,
306 				int residue, int status));
307 #define STATUS_CMD_OK		0	/* everything ok */
308 #define STATUS_CMD_UNKNOWN	1	/* will have to fetch sense */
309 #define STATUS_CMD_FAILED	2	/* transfer was ok, command failed */
310 #define STATUS_WIRE_FAILED	3	/* couldn't even get command across */
311 
312 typedef void (*wire_reset_f)	__P((struct umass_softc *sc, int status));
313 typedef void (*wire_transfer_f) __P((struct umass_softc *sc, int lun,
314 				void *cmd, int cmdlen, void *data, int datalen,
315 				int dir, transfer_cb_f cb, void *priv));
316 typedef void (*wire_state_f)	__P((usbd_xfer_handle xfer,
317 				usbd_private_handle priv, usbd_status err));
318 
319 #if defined(__FreeBSD__)
320 typedef int (*command_transform_f)	__P((struct umass_softc *sc,
321 				unsigned char *cmd, int cmdlen,
322 				unsigned char **rcmd, int *rcmdlen));
323 #endif
324 
325 
326 /* the per device structure */
327 struct umass_softc {
328 	USBBASEDEVICE		sc_dev;		/* base device */
329 	usbd_device_handle	sc_udev;	/* device */
330 
331 	unsigned char		drive;
332 #	define DRIVE_GENERIC		0	/* use defaults for this one */
333 #	define ZIP_100			1	/* to be used for quirks */
334 #       define ZIP_250                  2
335 #	define SHUTTLE_EUSB		3
336 #       define INSYSTEM_USBCABLE        4
337 	unsigned char		quirks;
338 	/* The drive does not support Test Unit Ready. Convert to
339 	 * Start Unit.
340 	 * Y-E Data
341 	 * ZIP 100
342 	 */
343 #	define NO_TEST_UNIT_READY	0x01
344 	/* The drive does not reset the Unit Attention state after
345 	 * REQUEST SENSE has been sent. The INQUIRY command does not reset
346 	 * the UA either, and so CAM runs in circles trying to retrieve the
347 	 * initial INQUIRY data.
348 	 * Y-E Data
349 	 */
350 #	define RS_NO_CLEAR_UA		0x02	/* no REQUEST SENSE on INQUIRY*/
351 	/* The drive does not support START_STOP.
352 	 * Shuttle E-USB
353 	 */
354 #	define NO_START_STOP		0x04
355 	/* Don't ask for full inquiry data (255 bytes).
356 	 * Yano ATAPI-USB
357 	 */
358 #       define FORCE_SHORT_INQUIRY      0x08
359 
360 	unsigned int		proto;
361 #	define PROTO_UNKNOWN	0x0000		/* unknown protocol */
362 #	define PROTO_BBB	0x0001		/* USB wire protocol */
363 #	define PROTO_CBI	0x0002
364 #	define PROTO_CBI_I	0x0004
365 #	define PROTO_WIRE	0x00ff		/* USB wire protocol mask */
366 #	define PROTO_SCSI	0x0100		/* command protocol */
367 #	define PROTO_ATAPI	0x0200
368 #	define PROTO_UFI	0x0400
369 #       define PROTO_RBC        0x0800
370 #	define PROTO_COMMAND	0xff00		/* command protocol mask */
371 
372 	u_char                  subclass;       /* interface subclass */
373 	u_char                  protocol;       /* interface protocol */
374 
375 	usbd_interface_handle	iface;		/* Mass Storage interface */
376 	int			ifaceno;	/* MS iface number */
377 
378 	u_int8_t		bulkin;		/* bulk-in Endpoint Address */
379 	u_int8_t		bulkout;	/* bulk-out Endpoint Address */
380 	u_int8_t		intrin;		/* intr-in Endp. (CBI) */
381 	usbd_pipe_handle	bulkin_pipe;
382 	usbd_pipe_handle	bulkout_pipe;
383 	usbd_pipe_handle	intrin_pipe;
384 
385 	/* Reset the device in a wire protocol specific way */
386 	wire_reset_f		reset;
387 
388 	/* The start of a wire transfer. It prepares the whole transfer (cmd,
389 	 * data, and status stage) and initiates it. It is up to the state
390 	 * machine (below) to handle the various stages and errors in these
391 	 */
392 	wire_transfer_f		transfer;
393 
394 	/* The state machine, handling the various states during a transfer */
395 	wire_state_f		state;
396 
397 #if defined(__FreeBSD__)
398 	/* The command transform function is used to conver the SCSI commands
399 	 * into their derivatives, like UFI, ATAPI, and friends.
400 	 */
401 	command_transform_f	transform;	/* command transform */
402 #endif
403 
404 	/* Bulk specific variables for transfers in progress */
405 	umass_bbb_cbw_t		cbw;	/* command block wrapper */
406 	umass_bbb_csw_t		csw;	/* command status wrapper*/
407 	/* CBI specific variables for transfers in progress */
408 	umass_cbi_cbl_t		cbl;	/* command block */
409 	umass_cbi_sbl_t		sbl;	/* status block */
410 
411 	/* generic variables for transfers in progress */
412 	/* ctrl transfer requests */
413 	usb_device_request_t	request;
414 
415 	/* xfer handles
416 	 * Most of our operations are initiated from interrupt context, so
417 	 * we need to avoid using the one that is in use. We want to avoid
418 	 * allocating them in the interrupt context as well.
419 	 */
420 	/* indices into array below */
421 #	define XFER_BBB_CBW		0	/* Bulk-Only */
422 #	define XFER_BBB_DATA		1
423 #	define XFER_BBB_DCLEAR		2
424 #	define XFER_BBB_CSW1		3
425 #	define XFER_BBB_CSW2		4
426 #	define XFER_BBB_SCLEAR		5
427 #	define XFER_BBB_RESET1		6
428 #	define XFER_BBB_RESET2		7
429 #	define XFER_BBB_RESET3		8
430 
431 #	define XFER_CBI_CB		0	/* CBI */
432 #	define XFER_CBI_DATA		1
433 #	define XFER_CBI_STATUS		2
434 #	define XFER_CBI_DCLEAR		3
435 #	define XFER_CBI_SCLEAR		4
436 #	define XFER_CBI_RESET1		5
437 #	define XFER_CBI_RESET2		6
438 #	define XFER_CBI_RESET3		7
439 
440 #	define XFER_NR			9	/* maximum number */
441 
442 	usbd_xfer_handle	transfer_xfer[XFER_NR]; /* for ctrl xfers */
443 
444 	void			*data_buffer;
445 
446 	int			transfer_dir;		/* data direction */
447 	void			*transfer_data;		/* data buffer */
448 	int			transfer_datalen;	/* (maximum) length */
449 	int			transfer_actlen;	/* actual length */
450 	transfer_cb_f		transfer_cb;		/* callback */
451 	void			*transfer_priv;		/* for callback */
452 	int			transfer_status;
453 
454 	int			transfer_state;
455 #	define TSTATE_IDLE			0
456 #	define TSTATE_BBB_COMMAND		1	/* CBW transfer */
457 #	define TSTATE_BBB_DATA			2	/* Data transfer */
458 #	define TSTATE_BBB_DCLEAR		3	/* clear endpt stall */
459 #	define TSTATE_BBB_STATUS1		4	/* clear endpt stall */
460 #	define TSTATE_BBB_SCLEAR		5	/* clear endpt stall */
461 #	define TSTATE_BBB_STATUS2		6	/* CSW transfer */
462 #	define TSTATE_BBB_RESET1		7	/* reset command */
463 #	define TSTATE_BBB_RESET2		8	/* in clear stall */
464 #	define TSTATE_BBB_RESET3		9	/* out clear stall */
465 #	define TSTATE_CBI_COMMAND		10	/* command transfer */
466 #	define TSTATE_CBI_DATA			11	/* data transfer */
467 #	define TSTATE_CBI_STATUS		12	/* status transfer */
468 #	define TSTATE_CBI_DCLEAR		13	/* clear ep stall */
469 #	define TSTATE_CBI_SCLEAR		14	/* clear ep stall */
470 #	define TSTATE_CBI_RESET1		15	/* reset command */
471 #	define TSTATE_CBI_RESET2		16	/* in clear stall */
472 #	define TSTATE_CBI_RESET3		17	/* out clear stall */
473 #	define TSTATE_STATES			18	/* # of states above */
474 
475 
476 	int			transfer_speed;		/* in kb/s */
477 	int			timeout;		/* in msecs */
478 
479 	u_int8_t		maxlun;			/* max lun supported */
480 
481 #ifdef UMASS_DEBUG
482 	struct timeval tv;
483 #endif
484 
485 #if defined(__FreeBSD__)
486 	/* SCSI/CAM specific variables */
487 	struct scsi_sense	cam_scsi_sense;
488 
489 #elif defined(__NetBSD__) || defined(__OpenBSD__)
490 	union {
491 		struct scsipi_link	sc_link;
492 #if defined(__NetBSD__)
493 		struct {
494 			struct ata_atapi_attach	sc_aa;
495 			struct ata_drive_datas	sc_aa_drive;
496 		} aa;
497 #endif
498 	} u;
499 #if defined(__NetBSD__)
500 	struct atapi_adapter	sc_atapi_adapter;
501 #define sc_adapter sc_atapi_adapter._generic
502 #else
503 	struct scsi_adapter	sc_atapi_adapter;
504 #define sc_adapter sc_atapi_adapter
505 #endif
506 	int			sc_xfer_flags;
507 	usbd_status		sc_sync_status;
508 	struct scsipi_sense	sc_sense_cmd;
509 
510 	device_ptr_t		sc_child;	/* child device, for detach */
511 	char			sc_dying;
512 
513 #endif
514 };
515 
516 #ifdef UMASS_DEBUG
517 char *states[TSTATE_STATES+1] = {
518 	/* should be kept in sync with the list at transfer_state */
519 	"Idle",
520 	"BBB CBW",
521 	"BBB Data",
522 	"BBB Data bulk-in/-out clear stall",
523 	"BBB CSW, 1st attempt",
524 	"BBB CSW bulk-in clear stall",
525 	"BBB CSW, 2nd attempt",
526 	"BBB Reset",
527 	"BBB bulk-in clear stall",
528 	"BBB bulk-out clear stall",
529 	"CBI Command",
530 	"CBI Data",
531 	"CBI Status",
532 	"CBI Data bulk-in/-out clear stall",
533 	"CBI Status intr-in clear stall",
534 	"CBI Reset",
535 	"CBI bulk-in clear stall",
536 	"CBI bulk-out clear stall",
537 	NULL
538 };
539 #endif
540 
541 struct cam_sim *umass_sim;	/* SCSI Interface Module */
542 struct cam_path *umass_path;	/*   and its path */
543 
544 
545 /* USB device probe/attach/detach functions */
546 USB_DECLARE_DRIVER(umass);
547 Static void umass_disco		__P((struct umass_softc *sc));
548 Static int umass_match_proto	__P((struct umass_softc *sc,
549 				usbd_interface_handle iface,
550 				usbd_device_handle dev));
551 Static void umass_init_shuttle	__P((struct umass_softc *sc));
552 
553 /* generic transfer functions */
554 Static usbd_status umass_setup_transfer __P((struct umass_softc *sc,
555 				usbd_pipe_handle pipe,
556 				void *buffer, int buflen, int flags,
557 				usbd_xfer_handle xfer));
558 Static usbd_status umass_setup_ctrl_transfer	__P((struct umass_softc *sc,
559 				usbd_device_handle dev,
560 				usb_device_request_t *req,
561 				void *buffer, int buflen, int flags,
562 				usbd_xfer_handle xfer));
563 Static void umass_clear_endpoint_stall	__P((struct umass_softc *sc,
564 				u_int8_t endpt, usbd_pipe_handle pipe,
565 				int state, usbd_xfer_handle xfer));
566 #if 0
567 Static void umass_reset		__P((struct umass_softc *sc,
568 				transfer_cb_f cb, void *priv));
569 #endif
570 
571 /* Bulk-Only related functions */
572 Static void umass_bbb_reset	__P((struct umass_softc *sc, int status));
573 Static void umass_bbb_transfer	__P((struct umass_softc *sc, int lun,
574 				void *cmd, int cmdlen,
575 				void *data, int datalen, int dir,
576 				transfer_cb_f cb, void *priv));
577 Static void umass_bbb_state	__P((usbd_xfer_handle xfer,
578 				usbd_private_handle priv,
579 				usbd_status err));
580 usbd_status umass_bbb_get_max_lun __P((struct umass_softc *sc,
581 				       u_int8_t *maxlun));
582 
583 
584 /* CBI related functions */
585 Static int umass_cbi_adsc	__P((struct umass_softc *sc, char *buffer,int buflen,
586 				usbd_xfer_handle xfer));
587 Static void umass_cbi_reset	__P((struct umass_softc *sc, int status));
588 Static void umass_cbi_transfer	__P((struct umass_softc *sc, int lun,
589 				void *cmd, int cmdlen,
590 				void *data, int datalen, int dir,
591 				transfer_cb_f cb, void *priv));
592 Static void umass_cbi_state	__P((usbd_xfer_handle xfer,
593 				usbd_private_handle priv, usbd_status err));
594 
595 #if defined(__FreeBSD__)
596 /* CAM related functions */
597 Static void umass_cam_action	__P((struct cam_sim *sim, union ccb *ccb));
598 Static void umass_cam_poll	__P((struct cam_sim *sim));
599 
600 Static void umass_cam_cb	__P((struct umass_softc *sc, void *priv,
601 				int residue, int status));
602 Static void umass_cam_sense_cb	__P((struct umass_softc *sc, void *priv,
603 				int residue, int status));
604 
605 #ifdef UMASS_DO_CAM_RESCAN
606 Static void umass_cam_rescan	__P((struct umass_softc *sc));
607 #endif
608 
609 Static int umass_cam_attach_sim __P((void));
610 Static int umass_cam_attach	__P((struct umass_softc *sc));
611 Static int umass_cam_detach_sim __P((void));
612 Static int umass_cam_detach	__P((struct umass_softc *sc));
613 
614 #elif defined(__NetBSD__) || defined(__OpenBSD__)
615 
616 #define UMASS_SCSIID_HOST	0x00
617 #define UMASS_SCSIID_DEVICE	0x01
618 
619 #define UMASS_ATAPI_DRIVE       0
620 
621 #define UMASS_MAX_TRANSFER_SIZE	MAXBSIZE
622 
623 struct scsipi_device umass_dev =
624 {
625 	NULL,			/* Use default error handler */
626 	NULL,			/* have a queue, served by this */
627 	NULL,			/* have no async handler */
628 	NULL,			/* Use default 'done' routine */
629 };
630 
631 Static int umass_scsipi_cmd __P((struct scsipi_xfer *xs));
632 Static void umass_scsipi_minphys __P((struct buf *bp));
633 Static int umass_scsipi_ioctl __P((struct scsipi_link *, u_long,
634 				   caddr_t, int, struct proc *));
635 Static void umass_scsipi_cb	__P((struct umass_softc *sc, void *priv,
636 				     int residue, int status));
637 Static void umass_scsipi_sense_cb __P((struct umass_softc *sc, void *priv,
638 				       int residue, int status));
639 
640 Static int scsipiprint __P((void *aux, const char *pnp));
641 Static int umass_ufi_transform __P((struct umass_softc *sc,
642     struct scsipi_generic *cmd, int cmdlen,
643     struct scsipi_generic *rcmd, int *rcmdlen));
644 
645 #if NATAPIBUS > 0
646 Static void umass_atapi_probedev __P((struct atapibus_softc *, int));
647 #endif
648 #endif
649 
650 #if defined(__FreeBSD__)
651 /* SCSI specific functions */
652 Static int umass_scsi_transform __P((struct umass_softc *sc,
653 				unsigned char *cmd, int cmdlen,
654 				unsigned char **rcmd, int *rcmdlen));
655 
656 /* UFI specific functions */
657 Static int umass_ufi_transform	__P((struct umass_softc *sc,
658 				unsigned char *cmd, int cmdlen,
659 				unsigned char **rcmd, int *rcmdlen));
660 
661 /* 8070 specific functions */
662 Static int umass_8070_transform __P((struct umass_softc *sc,
663 				unsigned char *cmd, int cmdlen,
664 				unsigned char **rcmd, int *rcmdlen));
665 #endif
666 
667 #ifdef UMASS_DEBUG
668 /* General debugging functions */
669 Static void umass_bbb_dump_cbw	__P((struct umass_softc *sc,
670 				umass_bbb_cbw_t *cbw));
671 Static void umass_bbb_dump_csw	__P((struct umass_softc *sc,
672 				umass_bbb_csw_t *csw));
673 Static void umass_dump_buffer	__P((struct umass_softc *sc, u_int8_t *buffer,
674 				int buflen, int printlen));
675 #endif
676 
677 
678 void usbd_clear_endpoint_toggle(usbd_pipe_handle pipe);	/* XXXXX */
679 
680 /*
681  * USB device probe/attach/detach
682  */
683 
684 /*
685  * Match the device we are seeing with the devices supported. Fill in the
686  * proto and drive fields in the softc accordingly.
687  * This function is called from both probe and attach.
688  */
689 
690 Static int
691 umass_match_proto(sc, iface, dev)
692 	struct umass_softc *sc;
693 	usbd_interface_handle iface;
694 	usbd_device_handle dev;
695 {
696 	usb_device_descriptor_t *dd;
697 	usb_interface_descriptor_t *id;
698 	u_int vendor, product;
699 
700 	/*
701 	 * Fill in sc->drive and sc->proto and return a match
702 	 * value if both are determined and 0 otherwise.
703 	 */
704 
705 	sc->drive = DRIVE_GENERIC;
706 	sc->proto = PROTO_UNKNOWN;
707 	sc->transfer_speed = UMASS_DEFAULT_TRANSFER_SPEED;
708 
709 	sc->sc_udev = dev;
710 	dd = usbd_get_device_descriptor(dev);
711 	vendor = UGETW(dd->idVendor);
712 	product = UGETW(dd->idProduct);
713 
714 	if (vendor == USB_VENDOR_SHUTTLE &&
715 	    product == USB_PRODUCT_SHUTTLE_EUSB) {
716 		sc->drive = SHUTTLE_EUSB;
717 #if CBI_I
718 		sc->proto = PROTO_ATAPI | PROTO_CBI_I;
719 #else
720 		sc->proto = PROTO_ATAPI | PROTO_CBI;
721 #endif
722 		sc->subclass = UISUBCLASS_SFF8020I;
723 		sc->protocol = UIPROTO_MASS_CBI;
724 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
725 		return (UMATCH_VENDOR_PRODUCT);
726 	}
727 
728 	if (vendor == USB_VENDOR_YANO &&
729 	    product == USB_PRODUCT_YANO_U640MO) {
730 		sc->proto = PROTO_ATAPI | PROTO_CBI_I;
731 		sc->quirks |= FORCE_SHORT_INQUIRY;
732 		return (UMATCH_VENDOR_PRODUCT);
733 	}
734 
735 	if (vendor == USB_VENDOR_SONY &&
736 	    product == USB_PRODUCT_SONY_MSC) {
737 		printf ("XXX Sony MSC\n");
738 		sc->quirks |= FORCE_SHORT_INQUIRY;
739 	}
740 
741 	if (vendor == USB_VENDOR_YEDATA &&
742 	    product == USB_PRODUCT_YEDATA_FLASHBUSTERU) {
743 
744 		/* Revisions < 1.28 do not handle the interrupt endpoint
745 		 * very well.
746 		 */
747 		if (UGETW(dd->bcdDevice) < 0x128)
748 			sc->proto = PROTO_UFI | PROTO_CBI;
749 		else
750 #if CBI_I
751 			sc->proto = PROTO_UFI | PROTO_CBI_I;
752 #else
753 			sc->proto = PROTO_UFI | PROTO_CBI;
754 #endif
755 		/*
756 		 * Revisions < 1.28 do not have the TEST UNIT READY command
757 		 * Revisions == 1.28 have a broken TEST UNIT READY
758 		 */
759 		if (UGETW(dd->bcdDevice) <= 0x128)
760 			sc->quirks |= NO_TEST_UNIT_READY;
761 
762 		sc->subclass = UISUBCLASS_UFI;
763 		sc->protocol = UIPROTO_MASS_CBI;
764 
765 		sc->quirks |= RS_NO_CLEAR_UA;
766 		sc->transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
767 		return (UMATCH_VENDOR_PRODUCT_REV);
768 	}
769 
770 	if (vendor == USB_VENDOR_INSYSTEM &&
771 	    product == USB_PRODUCT_INSYSTEM_USBCABLE) {
772 		sc->drive = INSYSTEM_USBCABLE;
773 		sc->proto = PROTO_ATAPI | PROTO_CBI;
774 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
775 		return (UMATCH_VENDOR_PRODUCT);
776 	}
777 
778 	id = usbd_get_interface_descriptor(iface);
779 	if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
780 		return (UMATCH_NONE);
781 
782 	if (vendor == USB_VENDOR_SONY && id->bInterfaceSubClass == 0xff) {
783 		/*
784 		 * Sony DSC devices set the sub class to 0xff
785 		 * instead of 1 (RBC). Fix that here.
786 		 */
787 		id->bInterfaceSubClass = UISUBCLASS_RBC;
788 		/* They also should be able to do higher speed. */
789 		sc->transfer_speed = 500;
790 	}
791 
792 	if (vendor == USB_VENDOR_FUJIPHOTO &&
793 	    product == USB_PRODUCT_FUJIPHOTO_MASS0100)
794 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
795 
796 	sc->subclass = id->bInterfaceSubClass;
797 	sc->protocol = id->bInterfaceProtocol;
798 
799 	switch (sc->subclass) {
800 	case UISUBCLASS_SCSI:
801 		sc->proto |= PROTO_SCSI;
802 		break;
803 	case UISUBCLASS_UFI:
804 		sc->transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
805 		sc->proto |= PROTO_UFI;
806 		break;
807 	case UISUBCLASS_SFF8020I:
808 	case UISUBCLASS_SFF8070I:
809 	case UISUBCLASS_QIC157:
810 		sc->proto |= PROTO_ATAPI;
811 		break;
812 	case UISUBCLASS_RBC:
813 		sc->proto |= PROTO_RBC;
814 		break;
815 	default:
816 		/* Assume that unsupported devices are ATAPI */
817 		DPRINTF(UDMASS_GEN, ("%s: Unsupported command protocol %d\n",
818 			USBDEVNAME(sc->sc_dev), id->bInterfaceSubClass));
819 
820 		sc->proto |= PROTO_ATAPI;
821 		break;
822 	}
823 
824 	switch (sc->protocol) {
825 	case UIPROTO_MASS_CBI:
826 		sc->proto |= PROTO_CBI;
827 		break;
828 	case UIPROTO_MASS_CBI_I:
829 #if CBI_I
830 		sc->proto |= PROTO_CBI_I;
831 #else
832 		sc->proto |= PROTO_CBI;
833 #endif
834 		break;
835 	case UIPROTO_MASS_BBB:
836 		sc->proto |= PROTO_BBB;
837 		break;
838 	case UIPROTO_MASS_BBB_P:
839 		sc->drive = ZIP_100;
840 		sc->proto |= PROTO_BBB;
841 		sc->transfer_speed = UMASS_ZIP100_TRANSFER_SPEED;
842 		sc->quirks |= NO_TEST_UNIT_READY;
843 		break;
844 	default:
845 		DPRINTF(UDMASS_GEN, ("%s: Unsupported wire protocol %d\n",
846 			USBDEVNAME(sc->sc_dev), id->bInterfaceProtocol));
847 		return (UMATCH_NONE);
848 	}
849 
850 	return (UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO);
851 }
852 
853 USB_MATCH(umass)
854 {
855 	USB_MATCH_START(umass, uaa);
856 #if defined(__FreeBSD__)
857 	struct umass_softc *sc = device_get_softc(self);
858 #elif defined(__NetBSD__) || defined(__OpenBSD__)
859 	struct umass_softc scs, *sc = &scs;
860 	memset(sc, 0, sizeof *sc);
861 	strcpy(sc->sc_dev.dv_xname, "umass");
862 #endif
863 
864 	if (uaa->iface == NULL)
865 		return(UMATCH_NONE);
866 
867 	return (umass_match_proto(sc, uaa->iface, uaa->device));
868 }
869 
870 USB_ATTACH(umass)
871 {
872 	USB_ATTACH_START(umass, sc, uaa);
873 	usb_interface_descriptor_t *id;
874 	usb_endpoint_descriptor_t *ed;
875 	const char *sSubclass, *sProto;
876 	char devinfo[1024];
877 	int i, bno;
878 	int err;
879 
880 	/*
881 	 * the softc struct is bzero-ed in device_set_driver. We can safely
882 	 * call umass_detach without specifically initialising the struct.
883 	 */
884 
885 	usbd_devinfo(uaa->device, 0, devinfo);
886 	USB_ATTACH_SETUP;
887 
888 	sc->iface = uaa->iface;
889 	sc->ifaceno = uaa->ifaceno;
890 
891 	/* initialise the proto and drive values in the umass_softc (again) */
892 	if (umass_match_proto(sc, sc->iface, uaa->device) == 0) {
893 		printf("%s: match failed\n", USBDEVNAME(sc->sc_dev));
894 		USB_ATTACH_ERROR_RETURN;
895 	}
896 
897 	/*
898 	 * The timeout is based on the maximum expected transfer size
899 	 * divided by the expected transfer speed.
900 	 * We multiply by 4 to make sure a busy system doesn't make things
901 	 * fail.
902 	 */
903 	sc->timeout = 4 * UMASS_MAX_TRANSFER_SIZE / sc->transfer_speed;
904 	sc->timeout += UMASS_SPINUP_TIME;	/* allow for spinning up */
905 
906 	id = usbd_get_interface_descriptor(sc->iface);
907 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
908 
909 	switch (sc->subclass) {
910 	case UISUBCLASS_RBC:
911 		sSubclass = "RBC";
912 		break;
913 	case UISUBCLASS_SCSI:
914 		sSubclass = "SCSI";
915 		break;
916 	case UISUBCLASS_UFI:
917 		sSubclass = "UFI";
918 		break;
919 	case UISUBCLASS_SFF8020I:
920 		sSubclass = "SFF8020i";
921 		break;
922 	case UISUBCLASS_SFF8070I:
923 		sSubclass = "SFF8070i";
924 		break;
925 	case UISUBCLASS_QIC157:
926 		sSubclass = "QIC157";
927 		break;
928 	default:
929 		sSubclass = "unknown";
930 		break;
931 	}
932 	switch (sc->protocol) {
933 	case UIPROTO_MASS_CBI:
934 		sProto = "CBI";
935 		break;
936 	case UIPROTO_MASS_CBI_I:
937 		sProto = "CBI-I";
938 		break;
939 	case UIPROTO_MASS_BBB:
940 		sProto = "BBB";
941 		break;
942 	case UIPROTO_MASS_BBB_P:
943 		sProto = "BBB-P";
944 		break;
945 	default:
946 		sProto = "unknown";
947 		break;
948 	}
949 	printf("%s: using %s over %s\n", USBDEVNAME(sc->sc_dev), sSubclass,
950 	       sProto);
951 
952 	if (sc->drive == INSYSTEM_USBCABLE) {
953 		err = usbd_set_interface(0, 1);
954 		if (err) {
955 			DPRINTF(UDMASS_USB, ("%s: could not switch to "
956 					     "Alt Interface %d\n",
957 					     USBDEVNAME(sc->sc_dev), 1));
958 			umass_disco(sc);
959 			USB_ATTACH_ERROR_RETURN;
960                 }
961 	}
962 
963 	/*
964 	 * In addition to the Control endpoint the following endpoints
965 	 * are required:
966 	 * a) bulk-in endpoint.
967 	 * b) bulk-out endpoint.
968 	 * and for Control/Bulk/Interrupt with CCI (CBI_I)
969 	 * c) intr-in
970 	 *
971 	 * The endpoint addresses are not fixed, so we have to read them
972 	 * from the device descriptors of the current interface.
973 	 */
974 	for (i = 0 ; i < id->bNumEndpoints ; i++) {
975 		ed = usbd_interface2endpoint_descriptor(sc->iface, i);
976 		if (!ed) {
977 			printf("%s: could not read endpoint descriptor\n",
978 			       USBDEVNAME(sc->sc_dev));
979 			USB_ATTACH_ERROR_RETURN;
980 		}
981 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
982 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
983 			sc->bulkin = ed->bEndpointAddress;
984 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT
985 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
986 			sc->bulkout = ed->bEndpointAddress;
987 		} else if (sc->proto & PROTO_CBI_I
988 		    && UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
989 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
990 			sc->intrin = ed->bEndpointAddress;
991 #ifdef UMASS_DEBUG
992 			if (UGETW(ed->wMaxPacketSize) > 2) {
993 				DPRINTF(UDMASS_CBI, ("%s: intr size is %d\n",
994 					USBDEVNAME(sc->sc_dev),
995 					UGETW(ed->wMaxPacketSize)));
996 			}
997 #endif
998 		}
999 	}
1000 
1001 	/* check whether we found all the endpoints we need */
1002 	if (!sc->bulkin || !sc->bulkout
1003 	    || (sc->proto & PROTO_CBI_I && !sc->intrin) ) {
1004 		DPRINTF(UDMASS_USB, ("%s: endpoint not found %d/%d/%d\n",
1005 			USBDEVNAME(sc->sc_dev),
1006 			sc->bulkin, sc->bulkout, sc->intrin));
1007 		umass_disco(sc);
1008 		USB_ATTACH_ERROR_RETURN;
1009 	}
1010 
1011 	/*
1012 	 * Get the maximum LUN supported by the device.
1013 	 */
1014 	if ((sc->proto & PROTO_WIRE) == PROTO_BBB) {
1015 		err = umass_bbb_get_max_lun(sc, &sc->maxlun);
1016 		if (err) {
1017 			printf("%s: unable to get Max Lun: %s\n",
1018 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
1019 			USB_ATTACH_ERROR_RETURN;
1020 		}
1021 	} else {
1022 		sc->maxlun = 0;
1023 	}
1024 
1025 	/* Open the bulk-in and -out pipe */
1026 	err = usbd_open_pipe(sc->iface, sc->bulkout,
1027 				USBD_EXCLUSIVE_USE, &sc->bulkout_pipe);
1028 	if (err) {
1029 		DPRINTF(UDMASS_USB, ("%s: cannot open %d-out pipe (bulk)\n",
1030 			USBDEVNAME(sc->sc_dev), sc->bulkout));
1031 		umass_disco(sc);
1032 		USB_ATTACH_ERROR_RETURN;
1033 	}
1034 	err = usbd_open_pipe(sc->iface, sc->bulkin,
1035 				USBD_EXCLUSIVE_USE, &sc->bulkin_pipe);
1036 	if (err) {
1037 		DPRINTF(UDMASS_USB, ("%s: could not open %d-in pipe (bulk)\n",
1038 			USBDEVNAME(sc->sc_dev), sc->bulkin));
1039 		umass_disco(sc);
1040 		USB_ATTACH_ERROR_RETURN;
1041 	}
1042 	/*
1043 	 * Open the intr-in pipe if the protocol is CBI with CCI.
1044 	 * Note: early versions of the Zip drive do have an interrupt pipe, but
1045 	 * this pipe is unused
1046 	 *
1047 	 * We do not open the interrupt pipe as an interrupt pipe, but as a
1048 	 * normal bulk endpoint. We send an IN transfer down the wire at the
1049 	 * appropriate time, because we know exactly when to expect data on
1050 	 * that endpoint. This saves bandwidth, but more important, makes the
1051 	 * code for handling the data on that endpoint simpler. No data
1052 	 * arriving concurrently.
1053 	 */
1054 	if (sc->proto & PROTO_CBI_I) {
1055 		err = usbd_open_pipe(sc->iface, sc->intrin,
1056 				USBD_EXCLUSIVE_USE, &sc->intrin_pipe);
1057 		if (err) {
1058 			DPRINTF(UDMASS_USB, ("%s: couldn't open %d-in (intr)\n",
1059 				USBDEVNAME(sc->sc_dev), sc->intrin));
1060 			umass_disco(sc);
1061 			USB_ATTACH_ERROR_RETURN;
1062 		}
1063 	}
1064 
1065 	/* initialisation of generic part */
1066 	sc->transfer_state = TSTATE_IDLE;
1067 
1068 	/* request a sufficient number of xfer handles */
1069 	for (i = 0; i < XFER_NR; i++) {
1070 		sc->transfer_xfer[i] = usbd_alloc_xfer(uaa->device);
1071 		if (sc->transfer_xfer[i] == 0) {
1072 			DPRINTF(UDMASS_USB, ("%s: Out of memory\n",
1073 				USBDEVNAME(sc->sc_dev)));
1074 			umass_disco(sc);
1075 			USB_ATTACH_ERROR_RETURN;
1076 		}
1077 	}
1078 	/* Allocate buffer for data transfer (it's huge). */
1079 	switch (sc->proto & PROTO_WIRE) {
1080 	case PROTO_BBB:
1081 		bno = XFER_BBB_DATA;
1082 		goto dalloc;
1083 	case PROTO_CBI:
1084 		bno = XFER_CBI_DATA;
1085 		goto dalloc;
1086 	case PROTO_CBI_I:
1087 		bno = XFER_CBI_DATA;
1088 	dalloc:
1089 		sc->data_buffer = usbd_alloc_buffer(sc->transfer_xfer[bno],
1090 						    UMASS_MAX_TRANSFER_SIZE);
1091 		if (sc->data_buffer == NULL) {
1092 			umass_disco(sc);
1093 			USB_ATTACH_ERROR_RETURN;
1094 		}
1095 		break;
1096 	default:
1097 		break;
1098 	}
1099 
1100 	/* Initialise the wire protocol specific methods */
1101 	if (sc->proto & PROTO_BBB) {
1102 		sc->reset = umass_bbb_reset;
1103 		sc->transfer = umass_bbb_transfer;
1104 		sc->state = umass_bbb_state;
1105 	} else if ((sc->proto & PROTO_CBI) || (sc->proto & PROTO_CBI_I)) {
1106 		sc->reset = umass_cbi_reset;
1107 		sc->transfer = umass_cbi_transfer;
1108 		sc->state = umass_cbi_state;
1109 #ifdef UMASS_DEBUG
1110 	} else {
1111 		panic("%s:%d: Unknown proto 0x%02x\n",
1112 		      __FILE__, __LINE__, sc->proto);
1113 #endif
1114 	}
1115 
1116 	if (sc->drive == SHUTTLE_EUSB)
1117 		umass_init_shuttle(sc);
1118 
1119 	/*
1120 	 * Fill in the adapter.
1121 	 */
1122 	sc->sc_adapter.scsipi_cmd = umass_scsipi_cmd;
1123 	sc->sc_adapter.scsipi_minphys = umass_scsipi_minphys;
1124 
1125 	/*
1126 	 * fill in the prototype scsipi_link.
1127 	 */
1128 	switch (sc->proto & PROTO_COMMAND) {
1129 	case PROTO_SCSI:
1130 	case PROTO_UFI:
1131 	case PROTO_ATAPI:
1132 	case PROTO_RBC:
1133 		if ((sc->proto & PROTO_COMMAND) != PROTO_SCSI)
1134 			sc->u.sc_link.flags |= SDEV_ATAPI;
1135 		else
1136 			sc->u.sc_link.flags &= ~SDEV_ATAPI;
1137 
1138 		sc->u.sc_link.adapter_buswidth = 2;
1139 		sc->u.sc_link.adapter_target = UMASS_SCSIID_HOST;
1140 		sc->u.sc_link.luns = sc->maxlun + 1;
1141 
1142 		sc->u.sc_link.adapter_softc = sc;
1143 		sc->u.sc_link.adapter = &sc->sc_adapter;
1144 		sc->u.sc_link.device = &umass_dev;
1145 		sc->u.sc_link.openings = 1;
1146 
1147 		if(sc->quirks & NO_TEST_UNIT_READY)
1148 			sc->u.sc_link.quirks |= ADEV_NOTUR;
1149 		break;
1150 
1151 
1152 	default:
1153 		printf("%s: proto=0x%x not supported yet\n",
1154 		       USBDEVNAME(sc->sc_dev), sc->proto);
1155 		umass_disco(sc);
1156 		USB_ATTACH_ERROR_RETURN;
1157 	}
1158 
1159 	sc->sc_child = config_found(&sc->sc_dev, &sc->u, scsipiprint);
1160 	if (sc->sc_child == NULL) {
1161 		umass_disco(sc);
1162 		/* Not an error, just not a complete success. */
1163 		USB_ATTACH_SUCCESS_RETURN;
1164 	}
1165 
1166 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
1167 			   USBDEV(sc->sc_dev));
1168 
1169 	DPRINTF(UDMASS_GEN, ("%s: Attach finished\n", USBDEVNAME(sc->sc_dev)));
1170 
1171 	USB_ATTACH_SUCCESS_RETURN;
1172 }
1173 
1174 Static int
1175 scsipiprint(aux, pnp)
1176 	void *aux;
1177 	const char *pnp;
1178 {
1179 #if !defined(__OpenBSD__)
1180 	extern int atapi_print __P((void *aux, const char *pnp));
1181 	struct scsipi_link *l = aux;
1182 
1183 	if (l->type == BUS_SCSI)
1184 		return (scsiprint(aux, pnp));
1185 	else
1186 		return (atapi_print(aux, pnp));
1187 #else
1188 	return (scsiprint(aux, pnp));
1189 #endif
1190 }
1191 
1192 USB_DETACH(umass)
1193 {
1194 	USB_DETACH_START(umass, sc);
1195 	int rv = 0;
1196 
1197 	DPRINTF(UDMASS_USB, ("%s: detached\n", USBDEVNAME(sc->sc_dev)));
1198 
1199 	/* Abort the pipes to wake up any waiting processes. */
1200 	if (sc->bulkout_pipe != NULL)
1201 		usbd_abort_pipe(sc->bulkout_pipe);
1202 	if (sc->bulkin_pipe != NULL)
1203 		usbd_abort_pipe(sc->bulkin_pipe);
1204 	if (sc->intrin_pipe != NULL)
1205 		usbd_abort_pipe(sc->intrin_pipe);
1206 
1207 #if 0
1208 	/* Do we really need reference counting?  Perhaps in ioctl() */
1209 	s = splusb();
1210 	if (--sc->sc_refcnt >= 0) {
1211 		/* Wait for processes to go away. */
1212 		usb_detach_wait(USBDEV(sc->sc_dev));
1213 	}
1214 	splx(s);
1215 #endif
1216 
1217 #if defined(__FreeBSD__)
1218 	if ((sc->proto & PROTO_SCSI) ||
1219 	    (sc->proto & PROTO_ATAPI) ||
1220 	    (sc->proto & PROTO_UFI))
1221 		/* detach the device from the SCSI host controller (SIM) */
1222 		rv = umass_cam_detach(sc);
1223 #elif defined(__NetBSD__) || defined(__OpenBSD__)
1224 	if (sc->sc_child != NULL)
1225 		rv = config_detach(sc->sc_child, flags);
1226 #endif
1227 	if (rv != 0)
1228 		return (rv);
1229 
1230 	umass_disco(sc);
1231 
1232 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
1233 			   USBDEV(sc->sc_dev));
1234 
1235 	return (0);
1236 }
1237 
1238 #if defined(__NetBSD__) || defined(__OpenBSD__)
1239 int
1240 umass_activate(self, act)
1241 	struct device *self;
1242 	enum devact act;
1243 {
1244 	struct umass_softc *sc = (struct umass_softc *) self;
1245 	int rv = 0;
1246 
1247 	DPRINTF(UDMASS_USB, ("%s: umass_activate: %d\n",
1248 	    USBDEVNAME(sc->sc_dev), act));
1249 
1250 	switch (act) {
1251 	case DVACT_ACTIVATE:
1252 		rv = EOPNOTSUPP;
1253 		break;
1254 
1255 	case DVACT_DEACTIVATE:
1256 		if (sc->sc_child == NULL)
1257 			break;
1258 		rv = config_deactivate(sc->sc_child);
1259 		DPRINTF(UDMASS_USB, ("%s: umass_activate: child "
1260 		    "returned %d\n", USBDEVNAME(sc->sc_dev), rv));
1261 		if (rv == 0)
1262 			sc->sc_dying = 1;
1263 		break;
1264 	}
1265 	return (rv);
1266 }
1267 #endif
1268 
1269 Static void
1270 umass_disco(sc)
1271 	struct umass_softc *sc;
1272 {
1273 	int i;
1274 
1275 	DPRINTF(UDMASS_GEN, ("umass_disco\n"));
1276 
1277 	/* Free the xfers. */
1278 	for (i = 0; i < XFER_NR; i++)
1279 		if (sc->transfer_xfer[i] != NULL) {
1280 			usbd_free_xfer(sc->transfer_xfer[i]);
1281 			sc->transfer_xfer[i] = NULL;
1282 		}
1283 
1284 	/* Remove all the pipes. */
1285 	if (sc->bulkout_pipe != NULL)
1286 		usbd_close_pipe(sc->bulkout_pipe);
1287 	if (sc->bulkin_pipe != NULL)
1288 		usbd_close_pipe(sc->bulkin_pipe);
1289 	if (sc->intrin_pipe != NULL)
1290 		usbd_close_pipe(sc->intrin_pipe);
1291 }
1292 
1293 Static void
1294 umass_init_shuttle(struct umass_softc *sc)
1295 {
1296 	usb_device_request_t req;
1297 	u_char status[2];
1298 
1299 	/* The Linux driver does this */
1300 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1301 	req.bRequest = 1;
1302 	USETW(req.wValue, 0);
1303 	USETW(req.wIndex, sc->ifaceno);
1304 	USETW(req.wLength, sizeof status);
1305 	(void)usbd_do_request(sc->sc_udev, &req, &status);
1306 }
1307 
1308 /*
1309  * Generic functions to handle transfers
1310  */
1311 
1312 Static usbd_status
1313 umass_setup_transfer(struct umass_softc *sc, usbd_pipe_handle pipe,
1314 			void *buffer, int buflen, int flags,
1315 			usbd_xfer_handle xfer)
1316 {
1317 	usbd_status err;
1318 
1319 	if (sc->sc_dying)
1320 		return (USBD_IOERROR);
1321 
1322 	/* Initialiase a USB transfer and then schedule it */
1323 
1324 	usbd_setup_xfer(xfer, pipe, (void *)sc, buffer, buflen,
1325 	    flags | sc->sc_xfer_flags, sc->timeout, sc->state);
1326 
1327 	err = usbd_transfer(xfer);
1328 	DPRINTF(UDMASS_XFER,("%s: start xfer buffer=%p buflen=%d flags=0x%x "
1329 	    "timeout=%d\n", USBDEVNAME(sc->sc_dev),
1330 	    buffer, buflen, flags | sc->sc_xfer_flags, sc->timeout));
1331 	if (err && err != USBD_IN_PROGRESS) {
1332 		DPRINTF(UDMASS_BBB, ("%s: failed to setup transfer, %s\n",
1333 			USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
1334 		return (err);
1335 	}
1336 
1337 	return (USBD_NORMAL_COMPLETION);
1338 }
1339 
1340 
1341 Static usbd_status
1342 umass_setup_ctrl_transfer(struct umass_softc *sc, usbd_device_handle dev,
1343 	 usb_device_request_t *req,
1344 	 void *buffer, int buflen, int flags,
1345 	 usbd_xfer_handle xfer)
1346 {
1347 	usbd_status err;
1348 
1349 	if (sc->sc_dying)
1350 		return (USBD_IOERROR);
1351 
1352 	/* Initialiase a USB control transfer and then schedule it */
1353 
1354 	usbd_setup_default_xfer(xfer, dev, (void *) sc,
1355 	    sc->timeout, req, buffer, buflen, flags, sc->state);
1356 
1357 	err = usbd_transfer(xfer);
1358 	if (err && err != USBD_IN_PROGRESS) {
1359 		DPRINTF(UDMASS_BBB, ("%s: failed to setup ctrl transfer, %s\n",
1360 			 USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
1361 
1362 		/* do not reset, as this would make us loop */
1363 		return (err);
1364 	}
1365 
1366 	return (USBD_NORMAL_COMPLETION);
1367 }
1368 
1369 Static void
1370 umass_clear_endpoint_stall(struct umass_softc *sc,
1371 	u_int8_t endpt, usbd_pipe_handle pipe,
1372 	int state, usbd_xfer_handle xfer)
1373 {
1374 	usbd_device_handle dev;
1375 
1376 	if (sc->sc_dying)
1377 		return;
1378 
1379 	DPRINTF(UDMASS_BBB, ("%s: Clear endpoint 0x%02x stall\n",
1380 		USBDEVNAME(sc->sc_dev), endpt));
1381 
1382 	usbd_interface2device_handle(sc->iface, &dev);
1383 
1384 	sc->transfer_state = state;
1385 
1386 	usbd_clear_endpoint_toggle(pipe);
1387 
1388 	sc->request.bmRequestType = UT_WRITE_ENDPOINT;
1389 	sc->request.bRequest = UR_CLEAR_FEATURE;
1390 	USETW(sc->request.wValue, UF_ENDPOINT_HALT);
1391 	USETW(sc->request.wIndex, endpt);
1392 	USETW(sc->request.wLength, 0);
1393 	umass_setup_ctrl_transfer(sc, dev, &sc->request, NULL, 0, 0, xfer);
1394 }
1395 
1396 #if 0
1397 Static void
1398 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
1399 {
1400 	sc->transfer_cb = cb;
1401 	sc->transfer_priv = priv;
1402 
1403 	/* The reset is a forced reset, so no error (yet) */
1404 	sc->reset(sc, STATUS_CMD_OK);
1405 }
1406 #endif
1407 
1408 /*
1409  * Bulk protocol specific functions
1410  */
1411 
1412 Static void
1413 umass_bbb_reset(struct umass_softc *sc, int status)
1414 {
1415 	usbd_device_handle dev;
1416 
1417 	KASSERT(sc->proto & PROTO_BBB,
1418 		("sc->proto == 0x%02x wrong for umass_bbb_reset\n", sc->proto));
1419 
1420 	if (sc->sc_dying)
1421 		return;
1422 
1423 	/*
1424 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
1425 	 *
1426 	 * For Reset Recovery the host shall issue in the following order:
1427 	 * a) a Bulk-Only Mass Storage Reset
1428 	 * b) a Clear Feature HALT to the Bulk-In endpoint
1429 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
1430 	 *
1431 	 * This is done in 3 steps, states:
1432 	 * TSTATE_BBB_RESET1
1433 	 * TSTATE_BBB_RESET2
1434 	 * TSTATE_BBB_RESET3
1435 	 *
1436 	 * If the reset doesn't succeed, the device should be port reset.
1437 	 */
1438 
1439 	DPRINTF(UDMASS_BBB, ("%s: Bulk Reset\n",
1440 		USBDEVNAME(sc->sc_dev)));
1441 
1442 	sc->transfer_state = TSTATE_BBB_RESET1;
1443 	sc->transfer_status = status;
1444 
1445 	usbd_interface2device_handle(sc->iface, &dev);
1446 
1447 	/* reset is a class specific interface write */
1448 	sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1449 	sc->request.bRequest = UR_BBB_RESET;
1450 	USETW(sc->request.wValue, 0);
1451 	USETW(sc->request.wIndex, sc->ifaceno);
1452 	USETW(sc->request.wLength, 0);
1453 	umass_setup_ctrl_transfer(sc, dev, &sc->request, NULL, 0, 0,
1454 				  sc->transfer_xfer[XFER_BBB_RESET1]);
1455 }
1456 
1457 Static void
1458 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
1459 		    void *data, int datalen, int dir,
1460 		    transfer_cb_f cb, void *priv)
1461 {
1462 	static int dCBWtag = 42;	/* unique for CBW of transfer */
1463 
1464 	DPRINTF(UDMASS_BBB,("%s: umass_bbb_transfer cmd=0x%02x\n",
1465 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd));
1466 
1467 	KASSERT(sc->proto & PROTO_BBB,
1468 		("sc->proto == 0x%02x wrong for umass_bbb_transfer\n",
1469 		sc->proto));
1470 
1471 	/*
1472 	 * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
1473 	 * a data phase of datalen bytes from/to the device and finally a
1474 	 * csw read phase.
1475 	 * If the data direction was inbound a maximum of datalen bytes
1476 	 * is stored in the buffer pointed to by data.
1477 	 *
1478 	 * umass_bbb_transfer initialises the transfer and lets the state
1479 	 * machine in umass_bbb_state handle the completion. It uses the
1480 	 * following states:
1481 	 * TSTATE_BBB_COMMAND
1482 	 *   -> TSTATE_BBB_DATA
1483 	 *   -> TSTATE_BBB_STATUS
1484 	 *   -> TSTATE_BBB_STATUS2
1485 	 *   -> TSTATE_BBB_IDLE
1486 	 *
1487 	 * An error in any of those states will invoke
1488 	 * umass_bbb_reset.
1489 	 */
1490 
1491 	/* check the given arguments */
1492 	KASSERT(datalen == 0 || data != NULL,
1493 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
1494 	KASSERT(cmdlen <= CBWCDBLENGTH,
1495 		("%s: cmdlen exceeds CDB length in CBW (%d > %d)",
1496 			USBDEVNAME(sc->sc_dev), cmdlen, CBWCDBLENGTH));
1497 	KASSERT(dir == DIR_NONE || datalen > 0,
1498 		("%s: datalen == 0 while direction is not NONE\n",
1499 			USBDEVNAME(sc->sc_dev)));
1500 	KASSERT(datalen == 0 || dir != DIR_NONE,
1501 		("%s: direction is NONE while datalen is not zero\n",
1502 			USBDEVNAME(sc->sc_dev)));
1503 	KASSERT(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
1504 		("%s: CBW struct does not have the right size (%d vs. %d)\n",
1505 			USBDEVNAME(sc->sc_dev),
1506 			sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE));
1507 	KASSERT(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
1508 		("%s: CSW struct does not have the right size (%d vs. %d)\n",
1509 			USBDEVNAME(sc->sc_dev),
1510 			sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE));
1511 
1512 	/*
1513 	 * Determine the direction of the data transfer and the length.
1514 	 *
1515 	 * dCBWDataTransferLength (datalen) :
1516 	 *   This field indicates the number of bytes of data that the host
1517 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
1518 	 *   the Direction bit) during the execution of this command. If this
1519 	 *   field is set to 0, the device will expect that no data will be
1520 	 *   transferred IN or OUT during this command, regardless of the value
1521 	 *   of the Direction bit defined in dCBWFlags.
1522 	 *
1523 	 * dCBWFlags (dir) :
1524 	 *   The bits of the Flags field are defined as follows:
1525 	 *     Bits 0-6	 reserved
1526 	 *     Bit  7	 Direction - this bit shall be ignored if the
1527 	 *			     dCBWDataTransferLength field is zero.
1528 	 *		 0 = data Out from host to device
1529 	 *		 1 = data In from device to host
1530 	 */
1531 
1532 	/* Fill in the Command Block Wrapper */
1533 	USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
1534 	USETDW(sc->cbw.dCBWTag, dCBWtag);
1535 	dCBWtag++;	/* cannot be done in macro (it will be done 4 times) */
1536 	USETDW(sc->cbw.dCBWDataTransferLength, datalen);
1537 	/* DIR_NONE is treated as DIR_OUT (0x00) */
1538 	sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
1539 	sc->cbw.bCBWLUN = lun;
1540 	sc->cbw.bCDBLength = cmdlen;
1541 	bcopy(cmd, sc->cbw.CBWCDB, cmdlen);
1542 
1543 	DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
1544 
1545 	/* store the details for the data transfer phase */
1546 	sc->transfer_dir = dir;
1547 	sc->transfer_data = data;
1548 	sc->transfer_datalen = datalen;
1549 	sc->transfer_actlen = 0;
1550 	sc->transfer_cb = cb;
1551 	sc->transfer_priv = priv;
1552 	sc->transfer_status = STATUS_CMD_OK;
1553 
1554 	/* move from idle to the command state */
1555 	sc->transfer_state = TSTATE_BBB_COMMAND;
1556 
1557 	/* Send the CBW from host to device via bulk-out endpoint. */
1558 	if (umass_setup_transfer(sc, sc->bulkout_pipe,
1559 			&sc->cbw, UMASS_BBB_CBW_SIZE, 0,
1560 			sc->transfer_xfer[XFER_BBB_CBW])) {
1561 		umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1562 	}
1563 }
1564 
1565 
1566 Static void
1567 umass_bbb_state(usbd_xfer_handle xfer, usbd_private_handle priv,
1568 		usbd_status err)
1569 {
1570 	struct umass_softc *sc = (struct umass_softc *) priv;
1571 	usbd_xfer_handle next_xfer;
1572 
1573 	KASSERT(sc->proto & PROTO_BBB,
1574 		("sc->proto == 0x%02x wrong for umass_bbb_state\n",sc->proto));
1575 
1576 	if (sc->sc_dying)
1577 		return;
1578 
1579 	/*
1580 	 * State handling for BBB transfers.
1581 	 *
1582 	 * The subroutine is rather long. It steps through the states given in
1583 	 * Annex A of the Bulk-Only specification.
1584 	 * Each state first does the error handling of the previous transfer
1585 	 * and then prepares the next transfer.
1586 	 * Each transfer is done asynchroneously so after the request/transfer
1587 	 * has been submitted you will find a 'return;'.
1588 	 */
1589 
1590 	DPRINTF(UDMASS_BBB, ("%s: Handling BBB state %d (%s), xfer=%p, %s\n",
1591 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
1592 		states[sc->transfer_state], xfer, usbd_errstr(err)));
1593 
1594 	switch (sc->transfer_state) {
1595 
1596 	/***** Bulk Transfer *****/
1597 	case TSTATE_BBB_COMMAND:
1598 		/* Command transport phase, error handling */
1599 		if (err) {
1600 			DPRINTF(UDMASS_BBB, ("%s: failed to send CBW\n",
1601 				USBDEVNAME(sc->sc_dev)));
1602 			/* If the device detects that the CBW is invalid, then
1603 			 * the device may STALL both bulk endpoints and require
1604 			 * a Bulk-Reset
1605 			 */
1606 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1607 			return;
1608 		}
1609 
1610 		/* Data transport phase, setup transfer */
1611 		sc->transfer_state = TSTATE_BBB_DATA;
1612 		if (sc->transfer_dir == DIR_IN) {
1613 			if (umass_setup_transfer(sc, sc->bulkin_pipe,
1614 					sc->data_buffer, sc->transfer_datalen,
1615 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
1616 					sc->transfer_xfer[XFER_BBB_DATA]))
1617 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1618 
1619 			return;
1620 		} else if (sc->transfer_dir == DIR_OUT) {
1621 			memcpy(sc->data_buffer, sc->transfer_data,
1622 			       sc->transfer_datalen);
1623 			if (umass_setup_transfer(sc, sc->bulkout_pipe,
1624 					sc->data_buffer, sc->transfer_datalen,
1625 					USBD_NO_COPY,/* fixed length transfer */
1626 					sc->transfer_xfer[XFER_BBB_DATA]))
1627 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1628 
1629 			return;
1630 		} else {
1631 			DPRINTF(UDMASS_BBB, ("%s: no data phase\n",
1632 				USBDEVNAME(sc->sc_dev)));
1633 		}
1634 
1635 		/* FALLTHROUGH if no data phase, err == 0 */
1636 	case TSTATE_BBB_DATA:
1637 		/* Command transport phase, error handling (ignored if no data
1638 		 * phase (fallthrough from previous state)) */
1639 		if (sc->transfer_dir != DIR_NONE) {
1640 			/* retrieve the length of the transfer that was done */
1641 			usbd_get_xfer_status(xfer, NULL, NULL,
1642 					     &sc->transfer_actlen, NULL);
1643 
1644 			if (err) {
1645 				DPRINTF(UDMASS_BBB, ("%s: Data-%s %db failed, "
1646 					"%s\n", USBDEVNAME(sc->sc_dev),
1647 					(sc->transfer_dir == DIR_IN?"in":"out"),
1648 					sc->transfer_datalen,usbd_errstr(err)));
1649 
1650 				if (err == USBD_STALLED) {
1651 					umass_clear_endpoint_stall(sc,
1652 					  (sc->transfer_dir == DIR_IN?
1653 					    sc->bulkin:sc->bulkout),
1654 					  (sc->transfer_dir == DIR_IN?
1655 					    sc->bulkin_pipe:sc->bulkout_pipe),
1656 					  TSTATE_BBB_DCLEAR,
1657 					  sc->transfer_xfer[XFER_BBB_DCLEAR]);
1658 					return;
1659 				} else {
1660 					/* Unless the error is a pipe stall the
1661 					 * error is fatal.
1662 					 */
1663 					umass_bbb_reset(sc,STATUS_WIRE_FAILED);
1664 					return;
1665 				}
1666 			}
1667 		}
1668 
1669 		if (sc->transfer_dir == DIR_IN)
1670 			memcpy(sc->transfer_data, sc->data_buffer,
1671 			       sc->transfer_actlen);
1672 
1673 		DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
1674 					umass_dump_buffer(sc, sc->transfer_data,
1675 						sc->transfer_datalen, 48));
1676 
1677 		/* FALLTHROUGH, err == 0 (no data phase or successfull) */
1678 	case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
1679 	case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
1680 		/* Reading of CSW after bulk stall condition in data phase
1681 		 * (TSTATE_BBB_DATA2) or bulk-in stall condition after
1682 		 * reading CSW (TSTATE_BBB_SCLEAR).
1683 		 * In the case of no data phase or successfull data phase,
1684 		 * err == 0 and the following if block is passed.
1685 		 */
1686 		if (err) {	/* should not occur */
1687 			/* try the transfer below, even if clear stall failed */
1688 			DPRINTF(UDMASS_BBB, ("%s: bulk-%s stall clear failed"
1689 				", %s\n", USBDEVNAME(sc->sc_dev),
1690 				(sc->transfer_dir == DIR_IN? "in":"out"),
1691 				usbd_errstr(err)));
1692 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1693 			return;
1694 		}
1695 
1696 		/* Status transport phase, setup transfer */
1697 		if (sc->transfer_state == TSTATE_BBB_COMMAND ||
1698 		    sc->transfer_state == TSTATE_BBB_DATA ||
1699 		    sc->transfer_state == TSTATE_BBB_DCLEAR) {
1700 			/* After no data phase, successfull data phase and
1701 			 * after clearing bulk-in/-out stall condition
1702 			 */
1703 			sc->transfer_state = TSTATE_BBB_STATUS1;
1704 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
1705 		} else {
1706 			/* After first attempt of fetching CSW */
1707 			sc->transfer_state = TSTATE_BBB_STATUS2;
1708 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
1709 		}
1710 
1711 		/* Read the Command Status Wrapper via bulk-in endpoint. */
1712 		if (umass_setup_transfer(sc, sc->bulkin_pipe,
1713 				&sc->csw, UMASS_BBB_CSW_SIZE, 0,
1714 				next_xfer)) {
1715 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1716 			return;
1717 		}
1718 
1719 		return;
1720 	case TSTATE_BBB_STATUS1:	/* first attempt */
1721 	case TSTATE_BBB_STATUS2:	/* second attempt */
1722 		/* Status transfer, error handling */
1723 		if (err) {
1724 			DPRINTF(UDMASS_BBB, ("%s: Failed to read CSW, %s%s\n",
1725 				USBDEVNAME(sc->sc_dev), usbd_errstr(err),
1726 				(sc->transfer_state == TSTATE_BBB_STATUS1?
1727 					", retrying":"")));
1728 
1729 			/* If this was the first attempt at fetching the CSW
1730 			 * retry it, otherwise fail.
1731 			 */
1732 			if (sc->transfer_state == TSTATE_BBB_STATUS1) {
1733 				umass_clear_endpoint_stall(sc,
1734 						sc->bulkin, sc->bulkin_pipe,
1735 						TSTATE_BBB_SCLEAR,
1736 						sc->transfer_xfer[XFER_BBB_SCLEAR]);
1737 				return;
1738 			} else {
1739 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1740 				return;
1741 			}
1742 		}
1743 
1744 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
1745 
1746 		/* Check CSW and handle any error */
1747 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
1748 			/* Invalid CSW: Wrong signature or wrong tag might
1749 			 * indicate that the device is confused -> reset it.
1750 			 */
1751 			printf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
1752 				USBDEVNAME(sc->sc_dev),
1753 				UGETDW(sc->csw.dCSWSignature),
1754 				CSWSIGNATURE);
1755 
1756 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1757 			return;
1758 		} else if (UGETDW(sc->csw.dCSWTag)
1759 				!= UGETDW(sc->cbw.dCBWTag)) {
1760 			printf("%s: Invalid CSW: tag %d should be %d\n",
1761 				USBDEVNAME(sc->sc_dev),
1762 				UGETDW(sc->csw.dCSWTag),
1763 				UGETDW(sc->cbw.dCBWTag));
1764 
1765 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1766 			return;
1767 
1768 		/* CSW is valid here */
1769 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
1770 			printf("%s: Invalid CSW: status %d > %d\n",
1771 				USBDEVNAME(sc->sc_dev),
1772 				sc->csw.bCSWStatus,
1773 				CSWSTATUS_PHASE);
1774 
1775 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1776 			return;
1777 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
1778 			printf("%s: Phase Error, residue = %d\n",
1779 				USBDEVNAME(sc->sc_dev),
1780 				UGETDW(sc->csw.dCSWDataResidue));
1781 
1782 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1783 			return;
1784 
1785 		} else if (sc->transfer_actlen > sc->transfer_datalen) {
1786 			/* Buffer overrun! Don't let this go by unnoticed */
1787 			panic("%s: transferred %d bytes instead of %d bytes\n",
1788 				USBDEVNAME(sc->sc_dev),
1789 				sc->transfer_actlen, sc->transfer_datalen);
1790 		}
1791 #if 0
1792 		else if (sc->transfer_datalen - sc->transfer_actlen
1793 			   != UGETDW(sc->csw.dCSWDataResidue)) {
1794 			DPRINTF(UDMASS_BBB, ("%s: actlen=%d != residue=%d\n",
1795 				USBDEVNAME(sc->sc_dev),
1796 				sc->transfer_datalen - sc->transfer_actlen,
1797 				UGETDW(sc->csw.dCSWDataResidue)));
1798 
1799 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1800 			return;
1801 
1802 		}
1803 #endif
1804 		else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
1805 			DPRINTF(UDMASS_BBB, ("%s: Command Failed, res = %d\n",
1806 				USBDEVNAME(sc->sc_dev),
1807 				UGETDW(sc->csw.dCSWDataResidue)));
1808 
1809 			/* SCSI command failed but transfer was succesful */
1810 			sc->transfer_state = TSTATE_IDLE;
1811 			sc->transfer_cb(sc, sc->transfer_priv,
1812 					UGETDW(sc->csw.dCSWDataResidue),
1813 					STATUS_CMD_FAILED);
1814 
1815 			return;
1816 
1817 		} else {	/* success */
1818 			sc->transfer_state = TSTATE_IDLE;
1819 			sc->transfer_cb(sc, sc->transfer_priv,
1820 					UGETDW(sc->csw.dCSWDataResidue),
1821 					STATUS_CMD_OK);
1822 
1823 			return;
1824 		}
1825 
1826 	/***** Bulk Reset *****/
1827 	case TSTATE_BBB_RESET1:
1828 		if (err)
1829 			printf("%s: BBB reset failed, %s\n",
1830 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
1831 
1832 		umass_clear_endpoint_stall(sc,
1833 			sc->bulkin, sc->bulkin_pipe, TSTATE_BBB_RESET2,
1834 			sc->transfer_xfer[XFER_BBB_RESET2]);
1835 
1836 		return;
1837 	case TSTATE_BBB_RESET2:
1838 		if (err)	/* should not occur */
1839 			printf("%s: BBB bulk-in clear stall failed, %s\n",
1840 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
1841 			/* no error recovery, otherwise we end up in a loop */
1842 
1843 		umass_clear_endpoint_stall(sc,
1844 			sc->bulkout, sc->bulkout_pipe, TSTATE_BBB_RESET3,
1845 			sc->transfer_xfer[XFER_BBB_RESET3]);
1846 
1847 		return;
1848 	case TSTATE_BBB_RESET3:
1849 		if (err)	/* should not occur */
1850 			printf("%s: BBB bulk-out clear stall failed, %s\n",
1851 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
1852 			/* no error recovery, otherwise we end up in a loop */
1853 
1854 		sc->transfer_state = TSTATE_IDLE;
1855 		if (sc->transfer_priv) {
1856 			sc->transfer_cb(sc, sc->transfer_priv,
1857 					sc->transfer_datalen,
1858 					sc->transfer_status);
1859 		}
1860 
1861 		return;
1862 
1863 	/***** Default *****/
1864 	default:
1865 		panic("%s: Unknown state %d\n",
1866 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
1867 	}
1868 }
1869 
1870 /*
1871  * Command/Bulk/Interrupt (CBI) specific functions
1872  */
1873 
1874 Static int
1875 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen,
1876 	       usbd_xfer_handle xfer)
1877 {
1878 	usbd_device_handle dev;
1879 
1880 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
1881 		("sc->proto == 0x%02x wrong for umass_cbi_adsc\n",sc->proto));
1882 
1883 	usbd_interface2device_handle(sc->iface, &dev);
1884 
1885 	sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1886 	sc->request.bRequest = UR_CBI_ADSC;
1887 	USETW(sc->request.wValue, 0);
1888 	USETW(sc->request.wIndex, sc->ifaceno);
1889 	USETW(sc->request.wLength, buflen);
1890 	return umass_setup_ctrl_transfer(sc, dev, &sc->request, buffer,
1891 					 buflen, 0, xfer);
1892 }
1893 
1894 
1895 Static void
1896 umass_cbi_reset(struct umass_softc *sc, int status)
1897 {
1898 	int i;
1899 #	define SEND_DIAGNOSTIC_CMDLEN	12
1900 
1901 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
1902 		("sc->proto == 0x%02x wrong for umass_cbi_reset\n",sc->proto));
1903 
1904 	if (sc->sc_dying)
1905 		return;
1906 
1907 	/*
1908 	 * Command Block Reset Protocol
1909 	 *
1910 	 * First send a reset request to the device. Then clear
1911 	 * any possibly stalled bulk endpoints.
1912 
1913 	 * This is done in 3 steps, states:
1914 	 * TSTATE_CBI_RESET1
1915 	 * TSTATE_CBI_RESET2
1916 	 * TSTATE_CBI_RESET3
1917 	 *
1918 	 * If the reset doesn't succeed, the device should be port reset.
1919 	 */
1920 
1921 	DPRINTF(UDMASS_CBI, ("%s: CBI Reset\n",
1922 		USBDEVNAME(sc->sc_dev)));
1923 
1924 	KASSERT(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
1925 		("%s: CBL struct is too small (%d < %d)\n",
1926 			USBDEVNAME(sc->sc_dev),
1927 			sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN));
1928 
1929 	sc->transfer_state = TSTATE_CBI_RESET1;
1930 	sc->transfer_status = status;
1931 
1932 	/* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
1933 	 * the two the last 10 bytes of the cbl is filled with 0xff (section
1934 	 * 2.2 of the CBI spec).
1935 	 */
1936 	sc->cbl[0] = 0x1d;	/* Command Block Reset */
1937 	sc->cbl[1] = 0x04;
1938 	for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
1939 		sc->cbl[i] = 0xff;
1940 
1941 	umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN,
1942 		       sc->transfer_xfer[XFER_CBI_RESET1]);
1943 	/* XXX if the command fails we should reset the port on the bub */
1944 }
1945 
1946 Static void
1947 umass_cbi_transfer(struct umass_softc *sc, int lun,
1948 		void *cmd, int cmdlen, void *data, int datalen, int dir,
1949 		transfer_cb_f cb, void *priv)
1950 {
1951 	DPRINTF(UDMASS_CBI,("%s: umass_cbi_transfer cmd=0x%02x, len=%d\n",
1952 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd, datalen));
1953 
1954 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
1955 		("sc->proto == 0x%02x wrong for umass_cbi_transfer\n",
1956 		sc->proto));
1957 
1958 	if (sc->sc_dying)
1959 		return;
1960 
1961 	/*
1962 	 * Do a CBI transfer with cmdlen bytes from cmd, possibly
1963 	 * a data phase of datalen bytes from/to the device and finally a
1964 	 * csw read phase.
1965 	 * If the data direction was inbound a maximum of datalen bytes
1966 	 * is stored in the buffer pointed to by data.
1967 	 *
1968 	 * umass_cbi_transfer initialises the transfer and lets the state
1969 	 * machine in umass_cbi_state handle the completion. It uses the
1970 	 * following states:
1971 	 * TSTATE_CBI_COMMAND
1972 	 *   -> XXX fill in
1973 	 *
1974 	 * An error in any of those states will invoke
1975 	 * umass_cbi_reset.
1976 	 */
1977 
1978 	/* check the given arguments */
1979 	KASSERT(datalen == 0 || data != NULL,
1980 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
1981 	KASSERT(datalen == 0 || dir != DIR_NONE,
1982 		("%s: direction is NONE while datalen is not zero\n",
1983 			USBDEVNAME(sc->sc_dev)));
1984 
1985 	/* store the details for the data transfer phase */
1986 	sc->transfer_dir = dir;
1987 	sc->transfer_data = data;
1988 	sc->transfer_datalen = datalen;
1989 	sc->transfer_actlen = 0;
1990 	sc->transfer_cb = cb;
1991 	sc->transfer_priv = priv;
1992 	sc->transfer_status = STATUS_CMD_OK;
1993 
1994 	/* move from idle to the command state */
1995 	sc->transfer_state = TSTATE_CBI_COMMAND;
1996 
1997 	/* Send the Command Block from host to device via control endpoint. */
1998 	if (umass_cbi_adsc(sc, cmd, cmdlen, sc->transfer_xfer[XFER_CBI_CB]))
1999 		umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2000 }
2001 
2002 Static void
2003 umass_cbi_state(usbd_xfer_handle xfer, usbd_private_handle priv,
2004 		usbd_status err)
2005 {
2006 	struct umass_softc *sc = (struct umass_softc *) priv;
2007 
2008 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
2009 		("sc->proto == 0x%02x wrong for umass_cbi_state\n", sc->proto));
2010 
2011 	if (sc->sc_dying)
2012 		return;
2013 
2014 	/*
2015 	 * State handling for CBI transfers.
2016 	 */
2017 
2018 	DPRINTF(UDMASS_CBI, ("%s: Handling CBI state %d (%s), xfer=%p, %s\n",
2019 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
2020 		states[sc->transfer_state], xfer, usbd_errstr(err)));
2021 
2022 	switch (sc->transfer_state) {
2023 
2024 	/***** CBI Transfer *****/
2025 	case TSTATE_CBI_COMMAND:
2026 		if (err == USBD_STALLED) {
2027 			DPRINTF(UDMASS_CBI, ("%s: Command Transport failed\n",
2028 				USBDEVNAME(sc->sc_dev)));
2029 			/* Status transport by control pipe (section 2.3.2.1).
2030 			 * The command contained in the command block failed.
2031 			 *
2032                          * The control pipe has already been unstalled by the
2033                          * USB stack.
2034                          * Section 2.4.3.1.1 states that the bulk in endpoints
2035                          * should not stalled at this point.
2036 			 */
2037 
2038 			sc->transfer_state = TSTATE_IDLE;
2039 			sc->transfer_cb(sc, sc->transfer_priv,
2040 					sc->transfer_datalen,
2041 					STATUS_CMD_FAILED);
2042 
2043 			return;
2044 		} else if (err) {
2045 			DPRINTF(UDMASS_CBI, ("%s: failed to send ADSC\n",
2046 				USBDEVNAME(sc->sc_dev)));
2047 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2048 
2049 			return;
2050 		}
2051 
2052 		sc->transfer_state = TSTATE_CBI_DATA;
2053 		if (sc->transfer_dir == DIR_IN) {
2054 			if (umass_setup_transfer(sc, sc->bulkin_pipe,
2055 					sc->transfer_data, sc->transfer_datalen,
2056 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
2057 					sc->transfer_xfer[XFER_CBI_DATA]))
2058 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2059 
2060 		} else if (sc->transfer_dir == DIR_OUT) {
2061 			memcpy(sc->data_buffer, sc->transfer_data,
2062 			       sc->transfer_datalen);
2063 			if (umass_setup_transfer(sc, sc->bulkout_pipe,
2064 					sc->transfer_data, sc->transfer_datalen,
2065 					USBD_NO_COPY,/* fixed length transfer */
2066 					sc->transfer_xfer[XFER_CBI_DATA]))
2067 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2068 
2069 		} else if (sc->proto & PROTO_CBI_I) {
2070 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
2071 				USBDEVNAME(sc->sc_dev)));
2072 			sc->transfer_state = TSTATE_CBI_STATUS;
2073 			if (umass_setup_transfer(sc, sc->intrin_pipe,
2074 					&sc->sbl, sizeof(sc->sbl),
2075 					0,	/* fixed length transfer */
2076 					sc->transfer_xfer[XFER_CBI_STATUS])){
2077 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2078 			}
2079 		} else {
2080 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
2081 				USBDEVNAME(sc->sc_dev)));
2082 			/* No command completion interrupt. Request
2083 			 * sense data.
2084 			 */
2085 			sc->transfer_state = TSTATE_IDLE;
2086 			sc->transfer_cb(sc, sc->transfer_priv,
2087 			       0, STATUS_CMD_UNKNOWN);
2088 		}
2089 
2090 		return;
2091 
2092 	case TSTATE_CBI_DATA:
2093 		/* retrieve the length of the transfer that was done */
2094 		usbd_get_xfer_status(xfer,NULL,NULL,&sc->transfer_actlen,NULL);
2095 		DPRINTF(UDMASS_CBI, ("%s: CBI_DATA actlen=%d\n",
2096 			USBDEVNAME(sc->sc_dev), sc->transfer_actlen));
2097 
2098 		if (err) {
2099 			DPRINTF(UDMASS_CBI, ("%s: Data-%s %db failed, "
2100 				"%s\n", USBDEVNAME(sc->sc_dev),
2101 				(sc->transfer_dir == DIR_IN?"in":"out"),
2102 				sc->transfer_datalen,usbd_errstr(err)));
2103 
2104 			if (err == USBD_STALLED) {
2105 				umass_clear_endpoint_stall(sc,
2106 					sc->bulkin, sc->bulkin_pipe,
2107 					TSTATE_CBI_DCLEAR,
2108 					sc->transfer_xfer[XFER_CBI_DCLEAR]);
2109 			} else {
2110 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2111 			}
2112 			return;
2113 		}
2114 
2115 		if (sc->transfer_dir == DIR_IN)
2116 			memcpy(sc->transfer_data, sc->data_buffer,
2117 			       sc->transfer_actlen);
2118 
2119 		DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
2120 					umass_dump_buffer(sc, sc->transfer_data,
2121 						sc->transfer_actlen, 48));
2122 
2123 		if (sc->proto & PROTO_CBI_I) {
2124 			sc->transfer_state = TSTATE_CBI_STATUS;
2125 			memset(&sc->sbl, 0, sizeof(sc->sbl));
2126 			if (umass_setup_transfer(sc, sc->intrin_pipe,
2127 				    &sc->sbl, sizeof(sc->sbl),
2128 				    0,	/* fixed length transfer */
2129 				    sc->transfer_xfer[XFER_CBI_STATUS])){
2130 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2131 			}
2132 		} else {
2133 			/* No command completion interrupt. Request
2134 			 * sense to get status of command.
2135 			 */
2136 			sc->transfer_state = TSTATE_IDLE;
2137 			sc->transfer_cb(sc, sc->transfer_priv,
2138 				sc->transfer_datalen - sc->transfer_actlen,
2139 				STATUS_CMD_UNKNOWN);
2140 		}
2141 		return;
2142 
2143 	case TSTATE_CBI_STATUS:
2144 		if (err) {
2145 			DPRINTF(UDMASS_CBI, ("%s: Status Transport failed\n",
2146 				USBDEVNAME(sc->sc_dev)));
2147 			/* Status transport by interrupt pipe (section 2.3.2.2).
2148 			 */
2149 
2150 			if (err == USBD_STALLED) {
2151 				umass_clear_endpoint_stall(sc,
2152 					sc->intrin, sc->intrin_pipe,
2153 					TSTATE_CBI_SCLEAR,
2154 					sc->transfer_xfer[XFER_CBI_SCLEAR]);
2155 			} else {
2156 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2157 			}
2158 			return;
2159 		}
2160 
2161 		/* Dissect the information in the buffer */
2162 
2163 		if (sc->proto & PROTO_UFI) {
2164 			int status;
2165 
2166 			/* Section 3.4.3.1.3 specifies that the UFI command
2167 			 * protocol returns an ASC and ASCQ in the interrupt
2168 			 * data block.
2169 			 */
2170 
2171 			DPRINTF(UDMASS_CBI, ("%s: UFI CCI, ASC = 0x%02x, "
2172 				"ASCQ = 0x%02x\n",
2173 				USBDEVNAME(sc->sc_dev),
2174 				sc->sbl.ufi.asc, sc->sbl.ufi.ascq));
2175 
2176 			if (sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0)
2177 				status = STATUS_CMD_OK;
2178 			else
2179 				status = STATUS_CMD_FAILED;
2180 
2181 			/* No sense, command successfull */
2182 		} else {
2183 			/* Command Interrupt Data Block */
2184 			DPRINTF(UDMASS_CBI, ("%s: type=0x%02x, value=0x%02x\n",
2185 				USBDEVNAME(sc->sc_dev),
2186 				sc->sbl.common.type, sc->sbl.common.value));
2187 
2188 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
2189 				int err;
2190 
2191 				if ((sc->sbl.common.value&IDB_VALUE_STATUS_MASK)
2192 							== IDB_VALUE_PASS) {
2193 					err = STATUS_CMD_OK;
2194 				} else if ((sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
2195 							== IDB_VALUE_FAIL ||
2196 					   (sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
2197 						== IDB_VALUE_PERSISTENT) {
2198 					err = STATUS_CMD_FAILED;
2199 				} else {
2200 					err = STATUS_WIRE_FAILED;
2201 				}
2202 
2203 				sc->transfer_state = TSTATE_IDLE;
2204 				sc->transfer_cb(sc, sc->transfer_priv,
2205 						sc->transfer_datalen,
2206 						err);
2207 			}
2208 		}
2209 		return;
2210 
2211 	case TSTATE_CBI_DCLEAR:
2212 		if (err) {	/* should not occur */
2213 			printf("%s: CBI bulk-in/out stall clear failed, %s\n",
2214 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
2215 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2216 		}
2217 
2218 		sc->transfer_state = TSTATE_IDLE;
2219 		sc->transfer_cb(sc, sc->transfer_priv,
2220 				sc->transfer_datalen,
2221 				STATUS_CMD_FAILED);
2222 		return;
2223 
2224 	case TSTATE_CBI_SCLEAR:
2225 		if (err)	/* should not occur */
2226 			printf("%s: CBI intr-in stall clear failed, %s\n",
2227 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
2228 
2229 		/* Something really bad is going on. Reset the device */
2230 		umass_cbi_reset(sc, STATUS_CMD_FAILED);
2231 		return;
2232 
2233 	/***** CBI Reset *****/
2234 	case TSTATE_CBI_RESET1:
2235 		if (err)
2236 			printf("%s: CBI reset failed, %s\n",
2237 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
2238 
2239 		umass_clear_endpoint_stall(sc,
2240 			sc->bulkin, sc->bulkin_pipe, TSTATE_CBI_RESET2,
2241 			sc->transfer_xfer[XFER_CBI_RESET2]);
2242 
2243 		return;
2244 	case TSTATE_CBI_RESET2:
2245 		if (err)	/* should not occur */
2246 			printf("%s: CBI bulk-in stall clear failed, %s\n",
2247 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
2248 			/* no error recovery, otherwise we end up in a loop */
2249 
2250 		umass_clear_endpoint_stall(sc,
2251 			sc->bulkout, sc->bulkout_pipe, TSTATE_CBI_RESET3,
2252 			sc->transfer_xfer[XFER_CBI_RESET3]);
2253 
2254 		return;
2255 	case TSTATE_CBI_RESET3:
2256 		if (err)	/* should not occur */
2257 			printf("%s: CBI bulk-out stall clear failed, %s\n",
2258 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
2259 			/* no error recovery, otherwise we end up in a loop */
2260 
2261 		sc->transfer_state = TSTATE_IDLE;
2262 		if (sc->transfer_priv) {
2263 			sc->transfer_cb(sc, sc->transfer_priv,
2264 					sc->transfer_datalen,
2265 					sc->transfer_status);
2266 		}
2267 
2268 		return;
2269 
2270 
2271 	/***** Default *****/
2272 	default:
2273 		panic("%s: Unknown state %d\n",
2274 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
2275 	}
2276 }
2277 
2278 usbd_status
2279 umass_bbb_get_max_lun(struct umass_softc *sc, u_int8_t *maxlun)
2280 {
2281 	usbd_device_handle dev;
2282 	usb_device_request_t req;
2283 	usbd_status err;
2284 	usb_interface_descriptor_t *id;
2285 
2286 	*maxlun = 0;		/* Default to 0. */
2287 
2288 	DPRINTF(UDMASS_BBB, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
2289 
2290 	usbd_interface2device_handle(sc->iface, &dev);
2291 	id = usbd_get_interface_descriptor(sc->iface);
2292 
2293 	/* The Get Max Lun command is a class-specific request. */
2294 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
2295 	req.bRequest = UR_BBB_GET_MAX_LUN;
2296 	USETW(req.wValue, 0);
2297 	USETW(req.wIndex, id->bInterfaceNumber);
2298 	USETW(req.wLength, 1);
2299 
2300 	err = usbd_do_request(dev, &req, maxlun);
2301 	switch (err) {
2302 	case USBD_NORMAL_COMPLETION:
2303 		DPRINTF(UDMASS_BBB, ("%s: Max Lun %d\n",
2304 		    USBDEVNAME(sc->sc_dev), *maxlun));
2305 		break;
2306 
2307 	case USBD_STALLED:
2308 		/*
2309 		 * Device doesn't support Get Max Lun request.
2310 		 */
2311 		err = USBD_NORMAL_COMPLETION;
2312 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun not supported\n",
2313 		    USBDEVNAME(sc->sc_dev)));
2314 		break;
2315 
2316 	case USBD_SHORT_XFER:
2317 		/*
2318 		 * XXX This must mean Get Max Lun is not supported, too!
2319 		 */
2320 		err = USBD_NORMAL_COMPLETION;
2321 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun SHORT_XFER\n",
2322 		    USBDEVNAME(sc->sc_dev)));
2323 		break;
2324 
2325 	default:
2326 		printf("%s: Get Max Lun failed: %s\n",
2327 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
2328 		/* XXX Should we port_reset the device? */
2329 		break;
2330 	}
2331 
2332 	return (err);
2333 }
2334 
2335 
2336 
2337 #if defined(__FreeBSD__)
2338 /*
2339  * CAM specific functions (used by SCSI, UFI, 8070)
2340  */
2341 
2342 Static int
2343 umass_cam_attach_sim()
2344 {
2345 	struct cam_devq *devq;		/* Per device Queue */
2346 
2347 	/* A HBA is attached to the CAM layer.
2348 	 *
2349 	 * The CAM layer will then after a while start probing for
2350 	 * devices on the bus. The number of devices is limitted to one.
2351 	 */
2352 
2353 	/* SCSI transparent command set */
2354 
2355 	devq = cam_simq_alloc(1 /*maximum openings*/);
2356 	if (devq == NULL)
2357 		return(ENOMEM);
2358 
2359 	umass_sim = cam_sim_alloc(umass_cam_action, umass_cam_poll, DEVNAME,
2360 				NULL /*priv*/, 0 /*unit number*/,
2361 				1 /*maximum device openings*/,
2362 				0 /*maximum tagged device openings*/,
2363 				devq);
2364 	if (umass_sim == NULL) {
2365 		cam_simq_free(devq);
2366 		return(ENOMEM);
2367 	}
2368 
2369 	if(xpt_bus_register(umass_sim, 0) != CAM_SUCCESS)
2370 		return(ENOMEM);
2371 
2372 	if (xpt_create_path(&umass_path, NULL, cam_sim_path(umass_sim),
2373 			    UMASS_SCSIID_HOST, 0)
2374 	    != CAM_REQ_CMP)
2375 		return(ENOMEM);
2376 
2377 	return(0);
2378 }
2379 
2380 #ifdef UMASS_DO_CAM_RESCAN
2381 /* this function is only used from umass_cam_rescan, so mention
2382  * prototype down here.
2383  */
2384 Static void umass_cam_rescan_callback(struct cam_periph *periph,union ccb *ccb);
2385 
2386 Static void
2387 umass_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2388 {
2389 #ifdef UMASS_DEBUG
2390 	struct umass_softc *sc = devclass_get_softc(umass_devclass,
2391 					       ccb->ccb_h.target_id);
2392 
2393 	if (ccb->ccb_h.status != CAM_REQ_CMP) {
2394 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d: Rescan failed, 0x%04x\n",
2395 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2396 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2397 			ccb->ccb_h.status));
2398 	} else {
2399 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d: Rescan succeeded, freeing resources.\n",
2400 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2401 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2402 	}
2403 #endif
2404 
2405 	xpt_free_path(ccb->ccb_h.path);
2406 	free(ccb, M_USBDEV);
2407 }
2408 
2409 Static void
2410 umass_cam_rescan(struct umass_softc *sc)
2411 {
2412 	struct cam_path *path;
2413 	union ccb *ccb = malloc(sizeof(union ccb), M_USBDEV, M_WAITOK);
2414 
2415 	memset(ccb, 0, sizeof(union ccb));
2416 
2417 	DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d: scanning bus for new device %d\n",
2418 		USBDEVNAME(sc->sc_dev),	 cam_sim_path(umass_sim),
2419 		device_get_unit(sc->sc_dev), 0,
2420 		device_get_unit(sc->sc_dev)));
2421 
2422 	if (xpt_create_path(&path, xpt_periph, cam_sim_path(umass_sim),
2423 		    device_get_unit(sc->sc_dev), 0)
2424 	    != CAM_REQ_CMP)
2425 		return;
2426 
2427 	xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
2428 	ccb->ccb_h.func_code = XPT_SCAN_BUS;
2429 	ccb->ccb_h.cbfcnp = umass_cam_rescan_callback;
2430 	ccb->crcn.flags = CAM_FLAG_NONE;
2431 	xpt_action(ccb);
2432 
2433 	/* The scan is in progress now. */
2434 }
2435 #endif
2436 
2437 Static int
2438 umass_cam_attach(struct umass_softc *sc)
2439 {
2440 	/* SIM already attached at module load. The device is a target on the
2441 	 * one SIM we registered: target device_get_unit(self).
2442 	 */
2443 
2444 	/* The artificial limit UMASS_SCSIID_MAX is there because CAM expects
2445 	 * a limit to the number of targets that are present on a SIM.
2446 	 */
2447 	if (device_get_unit(sc->sc_dev) > UMASS_SCSIID_MAX) {
2448 		printf("%s: Increase UMASS_SCSIID_MAX (currently %d) in %s "
2449 			"and try again.\n", USBDEVNAME(sc->sc_dev),
2450 			UMASS_SCSIID_MAX, __FILE__);
2451 		return(1);
2452 	}
2453 
2454 #ifdef UMASS_DO_CAM_RESCAN
2455 	if (!cold) {
2456 		/* Notify CAM of the new device. Any failure is benign, as the
2457 		 * user can still do it by hand (camcontrol rescan <busno>).
2458 		 * Only do this if we are not booting, because CAM does a scan
2459 		 * after booting has completed, when interrupts have been
2460 		 * enabled.
2461 		 */
2462 		umass_cam_rescan(sc);
2463 	}
2464 #endif
2465 
2466 	return(0);	/* always succesful */
2467 }
2468 
2469 /* umass_cam_detach
2470  *	detach from the CAM layer
2471  */
2472 
2473 Static int
2474 umass_cam_detach_sim()
2475 {
2476 	if (umass_sim)
2477 		return(EBUSY);	/* XXX CAM can't handle disappearing SIMs yet */
2478 
2479 	if (umass_path) {
2480 		/* XXX do we need to send an asynchroneous event for the SIM?
2481 		xpt_async(AC_LOST_DEVICE, umass_path, NULL);
2482 		 */
2483 		xpt_free_path(umass_path);
2484 		umass_path = NULL;
2485 	}
2486 
2487 	if (umass_sim) {
2488 		if (xpt_bus_deregister(cam_sim_path(umass_sim)))
2489 			cam_sim_free(umass_sim, /*free_devq*/TRUE);
2490 		else
2491 			return(EBUSY);
2492 
2493 		umass_sim = NULL;
2494 	}
2495 
2496 	return(0);
2497 }
2498 
2499 Static int
2500 umass_cam_detach(struct umass_softc *sc)
2501 {
2502 	struct cam_path *path;
2503 
2504 	/* detach of sim not done until module unload */
2505 	DPRINTF(UDMASS_SCSI, ("%s: losing CAM device entry\n",
2506 		USBDEVNAME(sc->sc_dev)));
2507 
2508 	if (xpt_create_path(&path, NULL, cam_sim_path(umass_sim),
2509 		    device_get_unit(sc->sc_dev), CAM_LUN_WILDCARD)
2510 	    != CAM_REQ_CMP)
2511 		return(ENOMEM);
2512 	xpt_async(AC_LOST_DEVICE, path, NULL);
2513 	xpt_free_path(path);
2514 
2515 	return(0);
2516 }
2517 
2518 
2519 
2520 /* umass_cam_action
2521  *	CAM requests for action come through here
2522  */
2523 
2524 Static void
2525 umass_cam_action(struct cam_sim *sim, union ccb *ccb)
2526 {
2527 	struct umass_softc *sc = devclass_get_softc(umass_devclass,
2528 					       ccb->ccb_h.target_id);
2529 
2530 	/* The softc is still there, but marked as going away. umass_cam_detach
2531 	 * has not yet notified CAM of the lost device however.
2532 	 */
2533 	if (sc && sc->sc_dying) {
2534 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
2535 			"Invalid target (gone)\n",
2536 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2537 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2538 			ccb->ccb_h.func_code));
2539 		ccb->ccb_h.status = CAM_TID_INVALID;
2540 		xpt_done(ccb);
2541 		return;
2542 	}
2543 
2544 	/* Verify, depending on the operation to perform, that we either got a
2545 	 * valid sc, because an existing target was referenced, or otherwise
2546 	 * the SIM is addressed.
2547 	 *
2548 	 * This avoids bombing out at a printf and does give the CAM layer some
2549 	 * sensible feedback on errors.
2550 	 */
2551 	switch (ccb->ccb_h.func_code) {
2552 	case XPT_SCSI_IO:
2553 	case XPT_RESET_DEV:
2554 	case XPT_GET_TRAN_SETTINGS:
2555 	case XPT_SET_TRAN_SETTINGS:
2556 	case XPT_CALC_GEOMETRY:
2557 		/* the opcodes requiring a target. These should never occur. */
2558 		if (sc == NULL) {
2559 			printf("%s:%d:%d:%d:func_code 0x%04x: "
2560 				"Invalid target\n",
2561 				DEVNAME_SIM, UMASS_SCSI_BUS,
2562 				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2563 				ccb->ccb_h.func_code);
2564 
2565 			ccb->ccb_h.status = CAM_TID_INVALID;
2566 			xpt_done(ccb);
2567 			return;
2568 		}
2569 		break;
2570 	case XPT_PATH_INQ:
2571 	case XPT_NOOP:
2572 		/* The opcodes sometimes aimed at a target (sc is valid),
2573 		 * sometimes aimed at the SIM (sc is invalid and target is
2574 		 * CAM_TARGET_WILDCARD)
2575 		 */
2576 		if (sc == NULL && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
2577 			DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
2578 				"Invalid target\n",
2579 				DEVNAME_SIM, UMASS_SCSI_BUS,
2580 				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2581 				ccb->ccb_h.func_code));
2582 
2583 			ccb->ccb_h.status = CAM_TID_INVALID;
2584 			xpt_done(ccb);
2585 			return;
2586 		}
2587 		break;
2588 	default:
2589 		/* XXX Hm, we should check the input parameters */
2590 	}
2591 
2592 	/* Perform the requested action */
2593 	switch (ccb->ccb_h.func_code) {
2594 	case XPT_SCSI_IO:
2595 	{
2596 		struct ccb_scsiio *csio = &ccb->csio;	/* deref union */
2597 		int dir;
2598 		unsigned char *cmd;
2599 		int cmdlen;
2600 
2601 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SCSI_IO: "
2602 			"cmd: 0x%02x, flags: 0x%02x, "
2603 			"%db cmd/%db data/%db sense\n",
2604 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2605 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2606 			csio->cdb_io.cdb_bytes[0],
2607 			ccb->ccb_h.flags & CAM_DIR_MASK,
2608 			csio->cdb_len, csio->dxfer_len,
2609 			csio->sense_len));
2610 
2611 		/* clear the end of the buffer to make sure we don't send out
2612 		 * garbage.
2613 		 */
2614 		DIF(UDMASS_SCSI, if ((ccb->ccb_h.flags & CAM_DIR_MASK)
2615 				     == CAM_DIR_OUT)
2616 					umass_dump_buffer(sc, csio->data_ptr,
2617 						csio->dxfer_len, 48));
2618 
2619 		if (sc->transfer_state != TSTATE_IDLE) {
2620 			DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SCSI_IO: "
2621 				"I/O requested while busy (state %d, %s)\n",
2622 				USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2623 				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2624 				sc->transfer_state,states[sc->transfer_state]));
2625 			ccb->ccb_h.status = CAM_SCSI_BUSY;
2626 			xpt_done(ccb);
2627 			return;
2628 		}
2629 
2630 		switch(ccb->ccb_h.flags&CAM_DIR_MASK) {
2631 		case CAM_DIR_IN:
2632 			dir = DIR_IN;
2633 			break;
2634 		case CAM_DIR_OUT:
2635 			dir = DIR_OUT;
2636 			break;
2637 		default:
2638 			dir = DIR_NONE;
2639 		}
2640 
2641 		ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
2642 		if (sc->transform(sc, csio->cdb_io.cdb_bytes, csio->cdb_len,
2643 				  &cmd, &cmdlen)) {
2644 			sc->transfer(sc, ccb->ccb_h.target_lun, cmd, cmdlen,
2645 				     csio->data_ptr,
2646 				     csio->dxfer_len, dir,
2647 				     umass_cam_cb, (void *) ccb);
2648 		} else {
2649 			ccb->ccb_h.status = CAM_REQ_INVALID;
2650 			xpt_done(ccb);
2651 		}
2652 
2653 		break;
2654 	}
2655 	case XPT_PATH_INQ:
2656 	{
2657 		struct ccb_pathinq *cpi = &ccb->cpi;
2658 
2659 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_PATH_INQ:.\n",
2660 			(sc == NULL? DEVNAME_SIM:USBDEVNAME(sc->sc_dev)),
2661 			UMASS_SCSI_BUS,
2662 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2663 
2664 		/* host specific information */
2665 		cpi->version_num = 1;
2666 		cpi->hba_inquiry = 0;
2667 		cpi->target_sprt = 0;
2668 		cpi->hba_misc = 0;
2669 		cpi->hba_eng_cnt = 0;
2670 		cpi->max_target = UMASS_SCSIID_MAX;	/* one target */
2671 		cpi->max_lun = 0;	/* no LUN's supported */
2672 		cpi->initiator_id = UMASS_SCSIID_HOST;
2673 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2674 		strncpy(cpi->hba_vid, "USB SCSI", HBA_IDLEN);
2675 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2676 		cpi->unit_number = cam_sim_unit(sim);
2677 		cpi->bus_id = UMASS_SCSI_BUS;
2678 		if (sc) {
2679 			cpi->base_transfer_speed = sc->transfer_speed;
2680 			cpi->max_lun = sc->maxlun;
2681 		}
2682 
2683 		cpi->ccb_h.status = CAM_REQ_CMP;
2684 		xpt_done(ccb);
2685 		break;
2686 	}
2687 	case XPT_RESET_DEV:
2688 	{
2689 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_RESET_DEV:.\n",
2690 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2691 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2692 
2693 		ccb->ccb_h.status = CAM_REQ_INPROG;
2694 		umass_reset(sc, umass_cam_cb, (void *) ccb);
2695 		break;
2696 	}
2697 	case XPT_GET_TRAN_SETTINGS:
2698 	{
2699 		struct ccb_trans_settings *cts = &ccb->cts;
2700 
2701 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_GET_TRAN_SETTINGS:.\n",
2702 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2703 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2704 
2705 		cts->valid = 0;
2706 		cts->flags = 0;		/* no disconnection, tagging */
2707 
2708 		ccb->ccb_h.status = CAM_REQ_CMP;
2709 		xpt_done(ccb);
2710 		break;
2711 	}
2712 	case XPT_SET_TRAN_SETTINGS:
2713 	{
2714 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SET_TRAN_SETTINGS:.\n",
2715 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2716 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2717 
2718 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2719 		xpt_done(ccb);
2720 		break;
2721 	}
2722 	case XPT_CALC_GEOMETRY:
2723 	{
2724 		struct ccb_calc_geometry *ccg = &ccb->ccg;
2725 
2726 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_CALC_GEOMETRY: "
2727 			"Volume size = %d\n",
2728 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
2729 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2730 			ccg->volume_size));
2731 
2732 		/* XXX We should probably ask the drive for the details
2733 		 *     instead of cluching them up ourselves
2734 		 */
2735 		if (sc->drive == ZIP_100) {
2736 			ccg->heads = 64;
2737 			ccg->secs_per_track = 32;
2738 			ccg->cylinders = ccg->volume_size / ccg->heads
2739 					  / ccg->secs_per_track;
2740 			ccb->ccb_h.status = CAM_REQ_CMP;
2741 			break;
2742 		} else if (sc->proto & PROTO_UFI) {
2743 			ccg->heads = 2;
2744 			if (ccg->volume_size == 2880)
2745 				ccg->secs_per_track = 18;
2746 			else
2747 				ccg->secs_per_track = 9;
2748 			ccg->cylinders = 80;
2749 			break;
2750 		} else {
2751 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2752 		}
2753 
2754 		xpt_done(ccb);
2755 		break;
2756 	}
2757 	case XPT_NOOP:
2758 	{
2759 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_NOOP:.\n",
2760 			(sc == NULL? DEVNAME_SIM:USBDEVNAME(sc->sc_dev)),
2761 			UMASS_SCSI_BUS,
2762 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2763 
2764 		ccb->ccb_h.status = CAM_REQ_CMP;
2765 		xpt_done(ccb);
2766 		break;
2767 	}
2768 	default:
2769 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
2770 			"Not implemented\n",
2771 			(sc == NULL? DEVNAME_SIM:USBDEVNAME(sc->sc_dev)),
2772 			UMASS_SCSI_BUS,
2773 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2774 			ccb->ccb_h.func_code));
2775 
2776 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2777 		xpt_done(ccb);
2778 		break;
2779 	}
2780 }
2781 
2782 /* umass_cam_poll
2783  *	all requests are handled through umass_cam_action, requests
2784  *	are never pending. So, nothing to do here.
2785  */
2786 Static void
2787 umass_cam_poll(struct cam_sim *sim)
2788 {
2789 #ifdef UMASS_DEBUG
2790 	struct umass_softc *sc = (struct umass_softc *) sim->softc;
2791 
2792 	DPRINTF(UDMASS_SCSI, ("%s: CAM poll\n",
2793 		USBDEVNAME(sc->sc_dev)));
2794 #endif
2795 
2796 	/* nop */
2797 }
2798 
2799 
2800 /* umass_cam_cb
2801  *	finalise a completed CAM command
2802  */
2803 
2804 Static void
2805 umass_cam_cb(struct umass_softc *sc, void *priv, int residue, int status)
2806 {
2807 	union ccb *ccb = (union ccb *) priv;
2808 	struct ccb_scsiio *csio = &ccb->csio;		/* deref union */
2809 
2810 	csio->resid = residue;
2811 
2812 	switch (status) {
2813 	case STATUS_CMD_OK:
2814 		ccb->ccb_h.status = CAM_REQ_CMP;
2815 		xpt_done(ccb);
2816 		break;
2817 
2818 	case STATUS_CMD_UNKNOWN:
2819 	case STATUS_CMD_FAILED:
2820 		switch (ccb->ccb_h.func_code) {
2821 		case XPT_SCSI_IO:
2822 		{
2823 			unsigned char *cmd;
2824 			int cmdlen;
2825 
2826 			/* fetch sense data */
2827 			DPRINTF(UDMASS_SCSI,("%s: Fetching %db sense data\n",
2828 			        USBDEVNAME(sc->sc_dev),
2829 			        sc->cam_scsi_sense.length));
2830 
2831 			sc->cam_scsi_sense.length = csio->sense_len;
2832 
2833 			if (sc->transform(sc, (char *) &sc->cam_scsi_sense,
2834 				      sizeof(sc->cam_scsi_sense),
2835 				      &cmd, &cmdlen)) {
2836 				sc->transfer(sc, ccb->ccb_h.target_lun,
2837 					     cmd, cmdlen,
2838 					     &csio->sense_data,
2839 					     csio->sense_len, DIR_IN,
2840 					     umass_cam_sense_cb, (void *) ccb);
2841 			} else {
2842 #ifdef UMASS_DEBUG
2843 				panic("transform(REQUEST_SENSE) failed\n");
2844 #else
2845 				csio->resid = sc->transfer_datalen;
2846 				ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2847 				xpt_done(ccb);
2848 #endif
2849 			}
2850 			break;
2851 		}
2852 		case XPT_RESET_DEV: /* Reset failed */
2853 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2854 			xpt_done(ccb);
2855 			break;
2856 		default:
2857 			panic("umass_cam_cb called for func_code %d\n",
2858 			      ccb->ccb_h.func_code);
2859 		}
2860 		break;
2861 
2862 	case STATUS_WIRE_FAILED:
2863 		/* the wire protocol failed and will have recovered
2864 		 * (hopefully).	 We return an error to CAM and let CAM retry
2865 		 * the command if necessary.
2866 		 */
2867 		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2868 		xpt_done(ccb);
2869 		break;
2870 
2871 	default:
2872 		panic("%s: Unknown status %d in umass_cam_cb\n",
2873 			USBDEVNAME(sc->sc_dev), status);
2874 	}
2875 }
2876 
2877 /* Finalise a completed autosense operation
2878  */
2879 Static void
2880 umass_cam_sense_cb(struct umass_softc *sc, void *priv, int residue, int status)
2881 {
2882 	union ccb *ccb = (union ccb *) priv;
2883 	struct ccb_scsiio *csio = &ccb->csio;		/* deref union */
2884 
2885 	switch (status) {
2886 	case STATUS_CMD_OK:
2887 	case STATUS_CMD_UNKNOWN:
2888 		/* Getting sense data succeeded. The length of the sense data
2889 		 * is not returned in any way. The sense data itself contains
2890 		 * the length of the sense data that is valid.
2891 		 */
2892 		if (sc->quirks & RS_NO_CLEAR_UA
2893 		    && csio->cdb_io.cdb_bytes[0] == INQUIRY
2894 		    && (csio->sense_data.flags & SSD_KEY)
2895 						== SSD_KEY_UNIT_ATTENTION) {
2896 			/* Ignore unit attention errors in the case where
2897 			 * the Unit Attention state is not cleared on
2898 			 * REQUEST SENSE. They will appear again at the next
2899 			 * command.
2900 			 */
2901 			ccb->ccb_h.status = CAM_REQ_CMP;
2902 		} else if ((csio->sense_data.flags & SSD_KEY)
2903 						== SSD_KEY_NO_SENSE) {
2904 			/* No problem after all (in the case of CBI without
2905 			 * CCI)
2906 			 */
2907 			ccb->ccb_h.status = CAM_REQ_CMP;
2908 		} else {
2909 			ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2910 					    | CAM_AUTOSNS_VALID;
2911 			csio->scsi_status = SCSI_STATUS_CHECK_COND;
2912 		}
2913 		xpt_done(ccb);
2914 		break;
2915 
2916 	default:
2917 		DPRINTF(UDMASS_SCSI, ("%s: Autosense failed, status %d\n",
2918 			USBDEVNAME(sc->sc_dev), status));
2919 		ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
2920 		xpt_done(ccb);
2921 	}
2922 }
2923 
2924 
2925 Static int
2926 umass_driver_load(module_t mod, int what, void *arg)
2927 {
2928 	int err;
2929 
2930 	switch (what) {
2931 	case MOD_UNLOAD:
2932 		err = umass_cam_detach_sim();
2933 		if (err)
2934 			return(err);
2935 		return(usbd_driver_load(mod, what, arg));
2936 	case MOD_LOAD:
2937 		/* We don't attach to CAM at this point, because it will try
2938 		 * and malloc memory for it. This is not possible when the
2939 		 * boot loader loads umass as a module before the kernel
2940 		 * has been bootstrapped.
2941 		 */
2942 	default:
2943 		return(usbd_driver_load(mod, what, arg));
2944 	}
2945 }
2946 
2947 
2948 
2949 /* (even the comment is missing) */
2950 
2951 DRIVER_MODULE(umass, uhub, umass_driver, umass_devclass, umass_driver_load, 0);
2952 
2953 
2954 /*
2955  * SCSI specific functions
2956  */
2957 
2958 Static int
2959 umass_scsi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
2960 		     unsigned char **rcmd, int *rcmdlen)
2961 {
2962 	*rcmd = cmd;		/* trivial copy */
2963 	*rcmdlen = cmdlen;
2964 
2965 	switch (cmd[0]) {
2966 	case TEST_UNIT_READY:
2967 		if (sc->quirks & NO_TEST_UNIT_READY) {
2968 			DPRINTF(UDMASS_SCSI, ("%s: Converted TEST_UNIT_READY "
2969 				"to START_UNIT\n", USBDEVNAME(sc->sc_dev)));
2970 			cmd[0] = START_STOP_UNIT;
2971 			cmd[4] = SSS_START;
2972 		}
2973 		break;
2974 	}
2975 
2976 	return 1;		/* success */
2977 }
2978 
2979 /*
2980  * UFI specific functions
2981  */
2982 
2983 Static int
2984 umass_ufi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
2985 		    unsigned char **rcmd, int *rcmdlen)
2986 {
2987 	*rcmd = cmd;
2988 	/* A UFI command is always 12 bytes in length */
2989 	/* XXX cmd[(cmdlen+1)..12] contains garbage */
2990 	*rcmdlen = 12;
2991 
2992 	switch (cmd[0]) {
2993 	case TEST_UNIT_READY:
2994 		if (sc->quirks & NO_TEST_UNIT_READY) {
2995 			DPRINTF(UDMASS_UFI, ("%s: Converted TEST_UNIT_READY "
2996 				"to START_UNIT\n", USBDEVNAME(sc->sc_dev)));
2997 			cmd[0] = START_STOP_UNIT;
2998 			cmd[4] = SSS_START;
2999 		}
3000 		return 1;
3001 	case INQUIRY:
3002 	case START_STOP_UNIT:
3003 	case MODE_SENSE:
3004 	case PREVENT_ALLOW:
3005 	case READ_10:
3006 	case READ_12:
3007 	case READ_CAPACITY:
3008 	case REQUEST_SENSE:
3009 	case REZERO_UNIT:
3010 	case POSITION_TO_ELEMENT:	/* SEEK_10 */
3011 	case SEND_DIAGNOSTIC:
3012 	case WRITE_10:
3013 	case WRITE_12:
3014 	/* FORMAT_UNIT */
3015 	/* MODE_SELECT */
3016 	/* READ_FORMAT_CAPACITY */
3017 	/* VERIFY */
3018 	/* WRITE_AND_VERIFY */
3019 		return 1;	/* success */
3020 	default:
3021 		return 0;	/* success */
3022 	}
3023 }
3024 
3025 /*
3026  * 8070 specific functions
3027  */
3028 Static int
3029 umass_8070_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
3030 		     unsigned char **rcmd, int *rcmdlen)
3031 {
3032 	return 0;	/* failure */
3033 }
3034 
3035 #endif /* __FreeBSD__ */
3036 
3037 
3038 #ifdef UMASS_DEBUG
3039 Static void
3040 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
3041 {
3042 	int clen = cbw->bCDBLength;
3043 	int dlen = UGETDW(cbw->dCBWDataTransferLength);
3044 	u_int8_t *c = cbw->CBWCDB;
3045 	int tag = UGETDW(cbw->dCBWTag);
3046 	int flags = cbw->bCBWFlags;
3047 
3048 	DPRINTF(UDMASS_BBB, ("%s: CBW %d: cmd = %db "
3049 		"(0x%02x%02x%02x%02x%02x%02x%s), "
3050 		"data = %d bytes, dir = %s\n",
3051 		USBDEVNAME(sc->sc_dev), tag, clen,
3052 		c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6? "...":""),
3053 		dlen, (flags == CBWFLAGS_IN? "in":
3054 		       (flags == CBWFLAGS_OUT? "out":"<invalid>"))));
3055 }
3056 
3057 Static void
3058 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
3059 {
3060 	int sig = UGETDW(csw->dCSWSignature);
3061 	int tag = UGETW(csw->dCSWTag);
3062 	int res = UGETDW(csw->dCSWDataResidue);
3063 	int status = csw->bCSWStatus;
3064 
3065 	DPRINTF(UDMASS_BBB, ("%s: CSW %d: sig = 0x%08x (%s), tag = %d, "
3066 		"res = %d, status = 0x%02x (%s)\n", USBDEVNAME(sc->sc_dev),
3067 		tag, sig, (sig == CSWSIGNATURE?	 "valid":"invalid"),
3068 		tag, res,
3069 		status, (status == CSWSTATUS_GOOD? "good":
3070 			 (status == CSWSTATUS_FAILED? "failed":
3071 			  (status == CSWSTATUS_PHASE? "phase":"<invalid>")))));
3072 }
3073 
3074 Static void
3075 umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer, int buflen,
3076 		  int printlen)
3077 {
3078 	int i, j;
3079 	char s1[40];
3080 	char s2[40];
3081 	char s3[5];
3082 
3083 	s1[0] = '\0';
3084 	s3[0] = '\0';
3085 
3086 	sprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
3087 	for (i = 0; i < buflen && i < printlen; i++) {
3088 		j = i % 16;
3089 		if (j == 0 && i != 0) {
3090 			DPRINTF(UDMASS_GEN, ("%s: 0x %s%s\n",
3091 				USBDEVNAME(sc->sc_dev), s1, s2));
3092 			s2[0] = '\0';
3093 		}
3094 		sprintf(&s1[j*2], "%02x", buffer[i] & 0xff);
3095 	}
3096 	if (buflen > printlen)
3097 		sprintf(s3, " ...");
3098 	DPRINTF(UDMASS_GEN, ("%s: 0x %s%s%s\n",
3099 		USBDEVNAME(sc->sc_dev), s1, s2, s3));
3100 }
3101 #endif
3102 
3103 
3104 
3105 
3106 
3107 
3108 
3109 
3110 #if defined(__NetBSD__) || defined(__OpenBSD__)
3111 Static int
3112 umass_scsipi_cmd(xs)
3113 	struct scsipi_xfer *xs;
3114 {
3115 	struct scsipi_link *sc_link = xs->sc_link;
3116 	struct umass_softc *sc = sc_link->adapter_softc;
3117 	struct scsipi_generic *cmd, trcmd;
3118 	int cmdlen;
3119 	int dir;
3120 #ifdef UMASS_DEBUG
3121 	microtime(&sc->tv);
3122 #endif
3123 
3124 	memset(&trcmd, 0, sizeof(trcmd));
3125 
3126 #if defined(__NetBSD__)
3127 	DIF(UDMASS_UPPER, sc_link->flags |= DEBUGLEVEL);
3128 #endif
3129 #if defined(__OpenBSD__)
3130 	DIF(UDMASS_UPPER, sc_link->flags |= SCSIDEBUG_LEVEL);
3131 #endif
3132 
3133 #if defined(__NetBSD__) || defined(__OpenBSD__)
3134 	DPRINTF(UDMASS_CMD, ("%s: umass_scsi_cmd:  %d:%d xs=%p cmd=0x%02x "
3135 	    "(quirks=0x%x, poll=%d)\n", USBDEVNAME(sc->sc_dev),
3136 	    SCSI_LINK_TARGET(sc_link), SCSI_LINK_LUN(sc_link),
3137 	    xs, xs->cmd->opcode, sc_link->quirks,
3138 	    xs->xs_control & XS_CTL_POLL));
3139 #endif
3140 
3141 #if defined(USB_DEBUG) && defined(SCSIDEBUG)
3142 	if (umassdebug & UDMASS_SCSI)
3143 		show_scsipi_xs(xs);
3144 	else if (umassdebug & ~UDMASS_CMD)
3145 		show_scsipi_cmd(xs);
3146 #endif
3147 
3148 	if (sc->sc_dying) {
3149 		xs->error = XS_DRIVER_STUFFUP;
3150 		goto done;
3151 	}
3152 
3153 #ifdef UMASS_DEBUG
3154 #if defined(__NetBSD__)
3155 	if ((sc_link->type == BUS_ATAPI ?
3156 	     sc_link->scsipi_atapi.drive : SCSI_LINK_TARGET(sc_link))
3157 	    != UMASS_SCSIID_DEVICE) {
3158 		DPRINTF(UDMASS_SCSI, ("%s: wrong SCSI ID %d\n",
3159 		    USBDEVNAME(sc->sc_dev),
3160 		    SCSI_LINK_TARGET(sc_link)));
3161 		xs->error = XS_DRIVER_STUFFUP;
3162 		goto done;
3163 	}
3164 #endif
3165 #if defined(__OpenBSD__)
3166 	if (sc_link->target != UMASS_SCSIID_DEVICE) {
3167 		DPRINTF(UDMASS_SCSI, ("%s: wrong SCSI ID %d\n",
3168 		    USBDEVNAME(sc->sc_dev),
3169 		    sc_link->target));
3170 		xs->error = XS_DRIVER_STUFFUP;
3171 		goto done;
3172 	}
3173 #endif
3174 #endif
3175 
3176 	cmd = xs->cmd;
3177 
3178 	if (xs->cmd->opcode == SCSI_MODE_SENSE &&
3179 	    (sc_link->quirks & SDEV_NOMODESENSE)) {
3180 		/*printf("%s: SCSI_MODE_SENSE\n", USBDEVNAME(sc->sc_dev));*/
3181 		xs->error = XS_TIMEOUT;
3182 		goto done;
3183 	}
3184 
3185 	if (xs->cmd->opcode == START_STOP &&
3186 	    (sc->quirks & NO_START_STOP)) {
3187 		/*printf("%s: START_STOP\n", USBDEVNAME(sc->sc_dev));*/
3188 		xs->error = XS_NOERROR;
3189 		goto done;
3190 	}
3191 
3192 	if (xs->cmd->opcode == INQUIRY &&
3193 	    (sc->quirks & FORCE_SHORT_INQUIRY)) {
3194        		memcpy(&trcmd, cmd, sizeof trcmd);
3195 		trcmd.bytes[4] = SHORT_INQUIRY_LENGTH;
3196 		cmd = &trcmd;
3197 	}
3198 
3199 	dir = DIR_NONE;
3200 	if (xs->datalen) {
3201 		switch (xs->xs_control & (XS_CTL_DATA_IN | XS_CTL_DATA_OUT)) {
3202 		case XS_CTL_DATA_IN:
3203 			dir = DIR_IN;
3204 			break;
3205 		case XS_CTL_DATA_OUT:
3206 			dir = DIR_OUT;
3207 			break;
3208 		}
3209 	}
3210 
3211 	if (xs->datalen > UMASS_MAX_TRANSFER_SIZE) {
3212 		printf("umass_cmd: large datalen, %d\n", xs->datalen);
3213 		xs->error = XS_DRIVER_STUFFUP;
3214 		goto done;
3215 	}
3216 
3217 	cmdlen = xs->cmdlen;
3218 	if (sc->proto & PROTO_UFI) {
3219 		if (!umass_ufi_transform(sc, cmd, cmdlen, &trcmd, &cmdlen)) {
3220 			xs->error = XS_DRIVER_STUFFUP;
3221 			goto done;
3222 		}
3223 		cmd= &trcmd;
3224 	}
3225 
3226 	if (sc->proto & PROTO_ATAPI) {
3227 		bcopy(cmd, &trcmd, cmdlen);
3228 		cmd = &trcmd;
3229 		cmdlen = ATAPI_COMMAND_LENGTH;
3230 	}
3231 
3232 	if (xs->xs_control & XS_CTL_POLL) {
3233 		/* Use sync transfer. XXX Broken! */
3234 		DPRINTF(UDMASS_SCSI, ("umass_scsi_cmd: sync dir=%d\n", dir));
3235 		sc->sc_xfer_flags = USBD_SYNCHRONOUS;
3236 		sc->sc_sync_status = USBD_INVAL;
3237 		sc->transfer(sc, SCSI_LINK_LUN(sc_link), cmd, cmdlen,
3238 			     xs->data, xs->datalen, dir, 0, xs);
3239 		sc->sc_xfer_flags = 0;
3240 		DPRINTF(UDMASS_SCSI, ("umass_scsi_cmd: done err=%d\n",
3241 				      sc->sc_sync_status));
3242 		switch (sc->sc_sync_status) {
3243 		case USBD_NORMAL_COMPLETION:
3244 			xs->error = XS_NOERROR;
3245 			break;
3246 		case USBD_TIMEOUT:
3247 			xs->error = XS_TIMEOUT;
3248 			break;
3249 		default:
3250 			xs->error = XS_DRIVER_STUFFUP;
3251 			break;
3252 		}
3253 		goto done;
3254 	} else {
3255 		DPRINTF(UDMASS_SCSI, ("umass_scsi_cmd: async dir=%d, cmdlen=%d"
3256 				      " datalen=%d\n",
3257 				      dir, cmdlen, xs->datalen));
3258 		sc->transfer(sc, SCSI_LINK_LUN(sc_link), cmd, cmdlen,
3259 		    xs->data, xs->datalen, dir, umass_scsipi_cb, xs);
3260 		return (SUCCESSFULLY_QUEUED);
3261 	}
3262 
3263 	/* Return if command finishes early. */
3264  done:
3265 #if defined(__NetBSD__)
3266 	xs->xs_status |= XS_STS_DONE;
3267 #endif
3268 #if defined(__OpenBSD__)
3269 	xs->flags |= ITSDONE;
3270 #endif
3271 
3272 	scsipi_done(xs);
3273 	if (xs->xs_control & XS_CTL_POLL)
3274 		return (COMPLETE);
3275 	else
3276 		return (SUCCESSFULLY_QUEUED);
3277 }
3278 
3279 Static void
3280 umass_scsipi_minphys(bp)
3281 	struct buf *bp;
3282 {
3283 	if (bp->b_bcount > UMASS_MAX_TRANSFER_SIZE)
3284 		bp->b_bcount = UMASS_MAX_TRANSFER_SIZE;
3285 	minphys(bp);
3286 }
3287 
3288 int
3289 umass_scsipi_ioctl(link, cmd, arg, flag, p)
3290 	struct scsipi_link *link;
3291 	u_long cmd;
3292 	caddr_t arg;
3293 	int flag;
3294 	struct proc *p;
3295 {
3296 	/*struct umass_softc *sc = link->adapter_softc;*/
3297 
3298 	switch (cmd) {
3299 #if 0
3300 	case SCBUSIORESET:
3301 		ccb->ccb_h.status = CAM_REQ_INPROG;
3302 		umass_reset(sc, umass_cam_cb, (void *) ccb);
3303 		return (0);
3304 #endif
3305 	default:
3306 		return (ENOTTY);
3307 	}
3308 }
3309 
3310 Static void
3311 umass_scsipi_cb(struct umass_softc *sc, void *priv, int residue, int status)
3312 {
3313 	struct scsipi_xfer *xs = priv;
3314 	struct scsipi_link *sc_link = xs->sc_link;
3315 	int cmdlen;
3316 	int s;
3317 #ifdef UMASS_DEBUG
3318 	struct timeval tv;
3319 	u_int delta;
3320 	microtime(&tv);
3321 	delta = (tv.tv_sec - sc->tv.tv_sec) * 1000000 + tv.tv_usec - sc->tv.tv_usec;
3322 #endif
3323 
3324 	DPRINTF(UDMASS_CMD,("umass_scsipi_cb: at %lu.%06lu, delta=%u: xs=%p residue=%d"
3325 	    " status=%d\n", tv.tv_sec, tv.tv_usec, delta, xs, residue, status));
3326 	xs->resid = residue;
3327 
3328 	switch (status) {
3329 	case STATUS_CMD_OK:
3330 		xs->error = XS_NOERROR;
3331 		break;
3332 
3333 	case STATUS_CMD_UNKNOWN:
3334 	case STATUS_CMD_FAILED:
3335 		/* fetch sense data */
3336 		memset(&sc->sc_sense_cmd, 0, sizeof(sc->sc_sense_cmd));
3337 		sc->sc_sense_cmd.opcode = REQUEST_SENSE;
3338 		sc->sc_sense_cmd.byte2 = SCSI_LINK_LUN(sc_link) <<
3339 		    SCSI_CMD_LUN_SHIFT;
3340 		sc->sc_sense_cmd.length = sizeof(xs->sense);
3341 
3342 		cmdlen = sizeof(sc->sc_sense_cmd);
3343 		if (sc->proto & PROTO_UFI)
3344 			cmdlen = UFI_COMMAND_LENGTH;
3345 		else if (sc->proto & PROTO_ATAPI)
3346 			cmdlen = ATAPI_COMMAND_LENGTH;
3347 
3348 		sc->transfer(sc, SCSI_LINK_LUN(sc_link),
3349 			     &sc->sc_sense_cmd, cmdlen,
3350 			     &xs->sense, sizeof(xs->sense), DIR_IN,
3351 			     umass_scsipi_sense_cb, xs);
3352 		return;
3353 
3354 	case STATUS_WIRE_FAILED:
3355 		xs->error = XS_RESET;
3356 		break;
3357 
3358 	default:
3359 		panic("%s: Unknown status %d in umass_scsipi_cb\n",
3360 			USBDEVNAME(sc->sc_dev), status);
3361 	}
3362 
3363 #if defined(__NetBSD__)
3364 	xs->xs_status |= XS_STS_DONE;
3365 #endif
3366 #if defined(__OpenBSD__)
3367 	xs->flags |= ITSDONE;
3368 #endif
3369 
3370 	DPRINTF(UDMASS_CMD,("umass_scsipi_cb: at %lu.%06lu: return xs->error="
3371             "%d, xs->xs_status=0x%x xs->resid=%d\n",
3372 	     tv.tv_sec, tv.tv_usec,
3373 	     xs->error, xs->xs_status, xs->resid));
3374 
3375 	s = splbio();
3376 	scsipi_done(xs);
3377 	splx(s);
3378 }
3379 
3380 /*
3381  * Finalise a completed autosense operation
3382  */
3383 Static void
3384 umass_scsipi_sense_cb(struct umass_softc *sc, void *priv, int residue,
3385 		      int status)
3386 {
3387 	struct scsipi_xfer *xs = priv;
3388 	int s;
3389 	int bytes_received;
3390 
3391 	DPRINTF(UDMASS_CMD,("umass_scsipi_sense_cb: xs=%p residue=%d "
3392 	    "status=%d\n", xs, residue, status));
3393 
3394 	switch (status) {
3395 	case STATUS_CMD_OK:
3396 	case STATUS_CMD_UNKNOWN:
3397 		/* getting sense data succeeded */
3398 		if ((xs->cmd->opcode == INQUIRY)
3399 		    && (xs->resid < xs->datalen)) {
3400 			/* Some drivers return SENSE errors even after INQUIRY
3401 			 * The upper layer doesn't like that.
3402 			 */
3403 			xs->error = XS_NOERROR;
3404 			break;
3405 		}
3406 
3407 		bytes_received = sizeof(xs->sense) - residue;
3408 
3409 		if (bytes_received < 8 ||
3410 		    (bytes_received < xs->sense.extra_len + 8))
3411 			xs->error = XS_SHORTSENSE;
3412 	        else
3413 			xs->error = XS_SENSE;
3414 
3415 #if defined(__OpenBSD__)
3416 		/* Note that this test may need to be revised
3417 		   with QIC-157a/SCSI tape drives that return
3418 		   ILI, EOM in the high bits of flags.
3419 	         */
3420 		if ((xs->sense.error_code & SSD_ERRCODE) == 0x70 &&
3421 		    (xs->sense.flags == 0))
3422 			xs->error = XS_NOERROR;
3423 #endif
3424 
3425 		break;
3426 	default:
3427 		DPRINTF(UDMASS_SCSI, ("%s: Autosense failed, status %d\n",
3428 			USBDEVNAME(sc->sc_dev), status));
3429 		xs->error = XS_DRIVER_STUFFUP;
3430 		break;
3431 	}
3432 
3433 #if defined(__NetBSD__)
3434 	xs->xs_status |= XS_STS_DONE;
3435 #endif
3436 #if defined(__OpenBSD__)
3437 	xs->flags |= ITSDONE;
3438 #endif
3439 
3440 	DPRINTF(UDMASS_CMD,("umass_scsipi_sense_cb: return xs->error=%d, "
3441 		"xs->xs_status=0x%x xs->resid=%d\n", xs->error, xs->xs_status,
3442 		xs->resid));
3443 
3444 	s = splbio();
3445 	scsipi_done(xs);
3446 	splx(s);
3447 }
3448 
3449 /*
3450  * UFI specific functions
3451  */
3452 
3453 Static int
3454 umass_ufi_transform(struct umass_softc *sc, struct scsipi_generic *cmd,
3455 		    int cmdlen, struct scsipi_generic *rcmd, int *rcmdlen)
3456 {
3457 	*rcmdlen = UFI_COMMAND_LENGTH;
3458 	memset(rcmd, 0, sizeof *rcmd);
3459 
3460 	/* Handle any quirks */
3461 	if (cmd->opcode == TEST_UNIT_READY
3462 	    && (sc->quirks & NO_TEST_UNIT_READY)) {
3463 		/*
3464 		 * Some devices do not support this command.
3465 		 * Start Stop Unit should give the same results
3466 		 */
3467 		DPRINTF(UDMASS_UFI, ("%s: Converted TEST_UNIT_READY "
3468 			"to START_UNIT\n", USBDEVNAME(sc->sc_dev)));
3469 		rcmd->opcode = START_STOP;
3470 		rcmd->bytes[3] = SSS_START;
3471 		return 1;
3472 	}
3473 
3474 	switch (cmd->opcode) {
3475 	/* Commands of which the format has been verified. They should work. */
3476 	case TEST_UNIT_READY:
3477 	case SCSI_REZERO_UNIT:
3478 	case REQUEST_SENSE:
3479 	case INQUIRY:
3480 	case START_STOP:
3481 	/*case SEND_DIAGNOSTIC: ??*/
3482 	case PREVENT_ALLOW:
3483 	case READ_CAPACITY:
3484 	case READ_BIG:
3485 	case WRITE_BIG:
3486 	case POSITION_TO_ELEMENT:	/* SEEK_10 */
3487 	case SCSI_MODE_SELECT_BIG:
3488 	case SCSI_MODE_SENSE_BIG:
3489 	default:
3490 		/* Copy the command into the (zeroed out) destination buffer */
3491 		memcpy(rcmd, cmd, cmdlen);
3492 		return (1);	/* success */
3493 
3494 	/*
3495 	 * Other UFI commands: FORMAT_UNIT, MODE_SELECT, READ_FORMAT_CAPACITY,
3496 	 * VERIFY, WRITE_AND_VERIFY.
3497 	 * These should be checked whether they somehow can be made to fit.
3498 	 */
3499 
3500 	/* These commands are known _not_ to work. They should be converted. */
3501 	case SCSI_READ_COMMAND:
3502 	case SCSI_WRITE_COMMAND:
3503 	case SCSI_MODE_SENSE:
3504 	case SCSI_MODE_SELECT:
3505 		printf("%s: Unsupported UFI command 0x%02x",
3506 			USBDEVNAME(sc->sc_dev), cmd->opcode);
3507 		if (cmdlen == 6)
3508 			printf(", 6 byte command should have been converted");
3509 		printf("\n");
3510 		return (0);	/* failure */
3511 	}
3512 }
3513 
3514 
3515 #if NATAPIBUS > 0
3516 Static void
3517 umass_atapi_probedev(atapi, target)
3518 	struct atapibus_softc *atapi;
3519 	int target;
3520 {
3521 	struct scsipi_link *sc_link;
3522 	struct scsipibus_attach_args sa;
3523 	struct ata_drive_datas *drvp = &atapi->sc_drvs[target];
3524 	char vendor[33], product[65], revision[17];
3525 	struct scsipi_inquiry_data inqbuf;
3526 
3527 	DPRINTF(UDMASS_SCSI,("umass_atapi_probedev: atapi=%p target=%d\n",
3528 			     atapi, target));
3529 
3530 	if (atapi->sc_link[target])
3531 		return;
3532 
3533 	sc_link = malloc(sizeof(*sc_link), M_DEVBUF, M_NOWAIT);
3534 	if (sc_link == NULL) {
3535 		printf("%s: can't allocate link for drive %d\n",
3536 		       atapi->sc_dev.dv_xname, target);
3537 		return;
3538 	}
3539 	*sc_link = *atapi->adapter_link;
3540 
3541 	DIF(UDMASS_UPPER, sc_link->flags |= DEBUGLEVEL);
3542 
3543 	/* Fill generic parts of the link. */
3544 	sc_link->active = 0;
3545 	sc_link->scsipi_atapi.drive = target;
3546 	sc_link->device = &umass_dev;
3547 	TAILQ_INIT(&sc_link->pending_xfers);
3548 
3549 	DPRINTF(UDMASS_SCSI, ("umass_atapi_probedev: doing inquiry\n"));
3550 	/* Now go ask the device all about itself. */
3551 	memset(&inqbuf, 0, sizeof(inqbuf));
3552 	if (scsipi_inquire(sc_link, &inqbuf, XS_CTL_DISCOVERY) != 0)
3553 		goto bad;
3554 
3555 	scsipi_strvis(vendor, 33, inqbuf.vendor, 8);
3556 	scsipi_strvis(product, 65, inqbuf.product, 16);
3557 	scsipi_strvis(revision, 17, inqbuf.revision, 4);
3558 
3559 	sa.sa_sc_link = sc_link;
3560 	sa.sa_inqbuf.type = inqbuf.device;
3561 	sa.sa_inqbuf.removable = inqbuf.dev_qual2 & SID_REMOVABLE ?
3562 	    T_REMOV : T_FIXED;
3563 	if (sa.sa_inqbuf.removable)
3564 		sc_link->flags |= SDEV_REMOVABLE;
3565 	/* XXX how? sc_link->scsipi_atapi.cap |= ACAP_LEN;*/
3566 	sa.sa_inqbuf.vendor = vendor;
3567 	sa.sa_inqbuf.product = product;
3568 	sa.sa_inqbuf.revision = revision;
3569 	sa.sa_inqptr = NULL;
3570 
3571 	drvp->drv_softc = atapi_probedev(atapi, target, sc_link, &sa);
3572 	/* atapi_probedev() frees the scsipi_link when there is no device. */
3573 	return;
3574 
3575 bad:
3576 	free(sc_link, M_DEVBUF);
3577 	return;
3578 }
3579 #endif
3580 #endif
3581