xref: /freebsd/sys/dev/usb/storage/umass.c (revision e24134bc0ed53f9d85377c4a645f2e86c9dc677c)
1 #include <sys/cdefs.h>
2 __FBSDID("$FreeBSD$");
3 
4 /*-
5  * Copyright (c) 1999 MAEKAWA Masahide <bishop@rr.iij4u.or.jp>,
6  *		      Nick Hibma <n_hibma@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	$FreeBSD$
31  *	$NetBSD: umass.c,v 1.28 2000/04/02 23:46:53 augustss Exp $
32  */
33 
34 /* Also already merged from NetBSD:
35  *	$NetBSD: umass.c,v 1.67 2001/11/25 19:05:22 augustss Exp $
36  *	$NetBSD: umass.c,v 1.90 2002/11/04 19:17:33 pooka Exp $
37  *	$NetBSD: umass.c,v 1.108 2003/11/07 17:03:25 wiz Exp $
38  *	$NetBSD: umass.c,v 1.109 2003/12/04 13:57:31 keihan Exp $
39  */
40 
41 /*
42  * Universal Serial Bus Mass Storage Class specs:
43  * http://www.usb.org/developers/devclass_docs/usb_msc_overview_1.2.pdf
44  * http://www.usb.org/developers/devclass_docs/usbmassbulk_10.pdf
45  * http://www.usb.org/developers/devclass_docs/usb_msc_cbi_1.1.pdf
46  * http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf
47  */
48 
49 /*
50  * Ported to NetBSD by Lennart Augustsson <augustss@NetBSD.org>.
51  * Parts of the code written by Jason R. Thorpe <thorpej@shagadelic.org>.
52  */
53 
54 /*
55  * The driver handles 3 Wire Protocols
56  * - Command/Bulk/Interrupt (CBI)
57  * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
58  * - Mass Storage Bulk-Only (BBB)
59  *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
60  *
61  * Over these wire protocols it handles the following command protocols
62  * - SCSI
63  * - UFI (floppy command set)
64  * - 8070i (ATAPI)
65  *
66  * UFI and 8070i (ATAPI) are transformed versions of the SCSI command set. The
67  * sc->sc_transform method is used to convert the commands into the appropriate
68  * format (if at all necessary). For example, UFI requires all commands to be
69  * 12 bytes in length amongst other things.
70  *
71  * The source code below is marked and can be split into a number of pieces
72  * (in this order):
73  *
74  * - probe/attach/detach
75  * - generic transfer routines
76  * - BBB
77  * - CBI
78  * - CBI_I (in addition to functions from CBI)
79  * - CAM (Common Access Method)
80  * - SCSI
81  * - UFI
82  * - 8070i (ATAPI)
83  *
84  * The protocols are implemented using a state machine, for the transfers as
85  * well as for the resets. The state machine is contained in umass_t_*_callback.
86  * The state machine is started through either umass_command_start() or
87  * umass_reset().
88  *
89  * The reason for doing this is a) CAM performs a lot better this way and b) it
90  * avoids using tsleep from interrupt context (for example after a failed
91  * transfer).
92  */
93 
94 /*
95  * The SCSI related part of this driver has been derived from the
96  * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch@FreeBSD.org).
97  *
98  * The CAM layer uses so called actions which are messages sent to the host
99  * adapter for completion. The actions come in through umass_cam_action. The
100  * appropriate block of routines is called depending on the transport protocol
101  * in use. When the transfer has finished, these routines call
102  * umass_cam_cb again to complete the CAM command.
103  */
104 
105 #include <sys/stdint.h>
106 #include <sys/stddef.h>
107 #include <sys/param.h>
108 #include <sys/queue.h>
109 #include <sys/types.h>
110 #include <sys/systm.h>
111 #include <sys/kernel.h>
112 #include <sys/bus.h>
113 #include <sys/module.h>
114 #include <sys/lock.h>
115 #include <sys/mutex.h>
116 #include <sys/condvar.h>
117 #include <sys/sysctl.h>
118 #include <sys/sx.h>
119 #include <sys/unistd.h>
120 #include <sys/callout.h>
121 #include <sys/malloc.h>
122 #include <sys/priv.h>
123 
124 #include <dev/usb/usb.h>
125 #include <dev/usb/usbdi.h>
126 #include <dev/usb/usbdi_util.h>
127 #include "usbdevs.h"
128 
129 #include <dev/usb/quirk/usb_quirk.h>
130 
131 #include <cam/cam.h>
132 #include <cam/cam_ccb.h>
133 #include <cam/cam_sim.h>
134 #include <cam/cam_xpt_sim.h>
135 #include <cam/scsi/scsi_all.h>
136 #include <cam/scsi/scsi_da.h>
137 
138 #include <cam/cam_periph.h>
139 
140 #define UMASS_EXT_BUFFER
141 #ifdef UMASS_EXT_BUFFER
142 /* this enables loading of virtual buffers into DMA */
143 #define	UMASS_USB_FLAGS .ext_buffer=1,
144 #else
145 #define	UMASS_USB_FLAGS
146 #endif
147 
148 #ifdef USB_DEBUG
149 #define	DIF(m, x)				\
150   do {						\
151     if (umass_debug & (m)) { x ; }		\
152   } while (0)
153 
154 #define	DPRINTF(sc, m, fmt, ...)			\
155   do {							\
156     if (umass_debug & (m)) {				\
157         printf("%s:%s: " fmt,				\
158 	       (sc) ? (const char *)(sc)->sc_name :	\
159 	       (const char *)"umassX",			\
160 		__FUNCTION__ ,## __VA_ARGS__);		\
161     }							\
162   } while (0)
163 
164 #define	UDMASS_GEN	0x00010000	/* general */
165 #define	UDMASS_SCSI	0x00020000	/* scsi */
166 #define	UDMASS_UFI	0x00040000	/* ufi command set */
167 #define	UDMASS_ATAPI	0x00080000	/* 8070i command set */
168 #define	UDMASS_CMD	(UDMASS_SCSI|UDMASS_UFI|UDMASS_ATAPI)
169 #define	UDMASS_USB	0x00100000	/* USB general */
170 #define	UDMASS_BBB	0x00200000	/* Bulk-Only transfers */
171 #define	UDMASS_CBI	0x00400000	/* CBI transfers */
172 #define	UDMASS_WIRE	(UDMASS_BBB|UDMASS_CBI)
173 #define	UDMASS_ALL	0xffff0000	/* all of the above */
174 static int umass_debug = 0;
175 
176 SYSCTL_NODE(_hw_usb, OID_AUTO, umass, CTLFLAG_RW, 0, "USB umass");
177 SYSCTL_INT(_hw_usb_umass, OID_AUTO, debug, CTLFLAG_RW,
178     &umass_debug, 0, "umass debug level");
179 
180 TUNABLE_INT("hw.usb.umass.debug", &umass_debug);
181 #else
182 #define	DIF(...) do { } while (0)
183 #define	DPRINTF(...) do { } while (0)
184 #endif
185 
186 #define	UMASS_GONE ((struct umass_softc *)1)
187 
188 #define	UMASS_BULK_SIZE (1 << 17)
189 #define	UMASS_CBI_DIAGNOSTIC_CMDLEN 12	/* bytes */
190 #define	UMASS_MAX_CMDLEN MAX(12, CAM_MAX_CDBLEN)	/* bytes */
191 
192 /* USB transfer definitions */
193 
194 #define	UMASS_T_BBB_RESET1      0	/* Bulk-Only */
195 #define	UMASS_T_BBB_RESET2      1
196 #define	UMASS_T_BBB_RESET3      2
197 #define	UMASS_T_BBB_COMMAND     3
198 #define	UMASS_T_BBB_DATA_READ   4
199 #define	UMASS_T_BBB_DATA_RD_CS  5
200 #define	UMASS_T_BBB_DATA_WRITE  6
201 #define	UMASS_T_BBB_DATA_WR_CS  7
202 #define	UMASS_T_BBB_STATUS      8
203 #define	UMASS_T_BBB_MAX         9
204 
205 #define	UMASS_T_CBI_RESET1      0	/* CBI */
206 #define	UMASS_T_CBI_RESET2      1
207 #define	UMASS_T_CBI_RESET3      2
208 #define	UMASS_T_CBI_COMMAND     3
209 #define	UMASS_T_CBI_DATA_READ   4
210 #define	UMASS_T_CBI_DATA_RD_CS  5
211 #define	UMASS_T_CBI_DATA_WRITE  6
212 #define	UMASS_T_CBI_DATA_WR_CS  7
213 #define	UMASS_T_CBI_STATUS      8
214 #define	UMASS_T_CBI_RESET4      9
215 #define	UMASS_T_CBI_MAX        10
216 
217 #define	UMASS_T_MAX MAX(UMASS_T_CBI_MAX, UMASS_T_BBB_MAX)
218 
219 /* Generic definitions */
220 
221 /* Direction for transfer */
222 #define	DIR_NONE	0
223 #define	DIR_IN		1
224 #define	DIR_OUT		2
225 
226 /* device name */
227 #define	DEVNAME		"umass"
228 #define	DEVNAME_SIM	"umass-sim"
229 
230 /* Approximate maximum transfer speeds (assumes 33% overhead). */
231 #define	UMASS_FULL_TRANSFER_SPEED	1000
232 #define	UMASS_HIGH_TRANSFER_SPEED	40000
233 #define	UMASS_SUPER_TRANSFER_SPEED	400000
234 #define	UMASS_FLOPPY_TRANSFER_SPEED	20
235 
236 #define	UMASS_TIMEOUT			5000	/* ms */
237 
238 /* CAM specific definitions */
239 
240 #define	UMASS_SCSIID_MAX	1	/* maximum number of drives expected */
241 #define	UMASS_SCSIID_HOST	UMASS_SCSIID_MAX
242 
243 /* Bulk-Only features */
244 
245 #define	UR_BBB_RESET		0xff	/* Bulk-Only reset */
246 #define	UR_BBB_GET_MAX_LUN	0xfe	/* Get maximum lun */
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 } __packed umass_bbb_cbw_t;
262 
263 #define	UMASS_BBB_CBW_SIZE	31
264 
265 /* Command Status Wrapper */
266 typedef struct {
267 	uDWord	dCSWSignature;
268 #define	CSWSIGNATURE	0x53425355
269 #define	CSWSIGNATURE_IMAGINATION_DBX1	0x43425355
270 #define	CSWSIGNATURE_OLYMPUS_C1	0x55425355
271 	uDWord	dCSWTag;
272 	uDWord	dCSWDataResidue;
273 	uByte	bCSWStatus;
274 #define	CSWSTATUS_GOOD	0x0
275 #define	CSWSTATUS_FAILED	0x1
276 #define	CSWSTATUS_PHASE	0x2
277 } __packed umass_bbb_csw_t;
278 
279 #define	UMASS_BBB_CSW_SIZE	13
280 
281 /* CBI features */
282 
283 #define	UR_CBI_ADSC	0x00
284 
285 typedef union {
286 	struct {
287 		uint8_t	type;
288 #define	IDB_TYPE_CCI		0x00
289 		uint8_t	value;
290 #define	IDB_VALUE_PASS		0x00
291 #define	IDB_VALUE_FAIL		0x01
292 #define	IDB_VALUE_PHASE		0x02
293 #define	IDB_VALUE_PERSISTENT	0x03
294 #define	IDB_VALUE_STATUS_MASK	0x03
295 	} __packed common;
296 
297 	struct {
298 		uint8_t	asc;
299 		uint8_t	ascq;
300 	} __packed ufi;
301 } __packed umass_cbi_sbl_t;
302 
303 struct umass_softc;			/* see below */
304 
305 typedef void (umass_callback_t)(struct umass_softc *sc, union ccb *ccb,
306     	uint32_t residue, uint8_t status);
307 
308 #define	STATUS_CMD_OK		0	/* everything ok */
309 #define	STATUS_CMD_UNKNOWN	1	/* will have to fetch sense */
310 #define	STATUS_CMD_FAILED	2	/* transfer was ok, command failed */
311 #define	STATUS_WIRE_FAILED	3	/* couldn't even get command across */
312 
313 typedef uint8_t (umass_transform_t)(struct umass_softc *sc, uint8_t *cmd_ptr,
314     	uint8_t cmd_len);
315 
316 /* Wire and command protocol */
317 #define	UMASS_PROTO_BBB		0x0001	/* USB wire protocol */
318 #define	UMASS_PROTO_CBI		0x0002
319 #define	UMASS_PROTO_CBI_I	0x0004
320 #define	UMASS_PROTO_WIRE	0x00ff	/* USB wire protocol mask */
321 #define	UMASS_PROTO_SCSI	0x0100	/* command protocol */
322 #define	UMASS_PROTO_ATAPI	0x0200
323 #define	UMASS_PROTO_UFI		0x0400
324 #define	UMASS_PROTO_RBC		0x0800
325 #define	UMASS_PROTO_COMMAND	0xff00	/* command protocol mask */
326 
327 /* Device specific quirks */
328 #define	NO_QUIRKS		0x0000
329 	/*
330 	 * The drive does not support Test Unit Ready. Convert to Start Unit
331 	 */
332 #define	NO_TEST_UNIT_READY	0x0001
333 	/*
334 	 * The drive does not reset the Unit Attention state after REQUEST
335 	 * SENSE has been sent. The INQUIRY command does not reset the UA
336 	 * either, and so CAM runs in circles trying to retrieve the initial
337 	 * INQUIRY data.
338 	 */
339 #define	RS_NO_CLEAR_UA		0x0002
340 	/* The drive does not support START STOP.  */
341 #define	NO_START_STOP		0x0004
342 	/* Don't ask for full inquiry data (255b).  */
343 #define	FORCE_SHORT_INQUIRY	0x0008
344 	/* Needs to be initialised the Shuttle way */
345 #define	SHUTTLE_INIT		0x0010
346 	/* Drive needs to be switched to alternate iface 1 */
347 #define	ALT_IFACE_1		0x0020
348 	/* Drive does not do 1Mb/s, but just floppy speeds (20kb/s) */
349 #define	FLOPPY_SPEED		0x0040
350 	/* The device can't count and gets the residue of transfers wrong */
351 #define	IGNORE_RESIDUE		0x0080
352 	/* No GetMaxLun call */
353 #define	NO_GETMAXLUN		0x0100
354 	/* The device uses a weird CSWSIGNATURE. */
355 #define	WRONG_CSWSIG		0x0200
356 	/* Device cannot handle INQUIRY so fake a generic response */
357 #define	NO_INQUIRY		0x0400
358 	/* Device cannot handle INQUIRY EVPD, return CHECK CONDITION */
359 #define	NO_INQUIRY_EVPD		0x0800
360 	/* Pad all RBC requests to 12 bytes. */
361 #define	RBC_PAD_TO_12		0x1000
362 	/*
363 	 * Device reports number of sectors from READ_CAPACITY, not max
364 	 * sector number.
365 	 */
366 #define	READ_CAPACITY_OFFBY1	0x2000
367 	/*
368 	 * Device cannot handle a SCSI synchronize cache command.  Normally
369 	 * this quirk would be handled in the cam layer, but for IDE bridges
370 	 * we need to associate the quirk with the bridge and not the
371 	 * underlying disk device.  This is handled by faking a success
372 	 * result.
373 	 */
374 #define	NO_SYNCHRONIZE_CACHE	0x4000
375 
376 struct umass_softc {
377 
378 	struct scsi_sense cam_scsi_sense;
379 	struct scsi_test_unit_ready cam_scsi_test_unit_ready;
380 	struct mtx sc_mtx;
381 	struct {
382 		uint8_t *data_ptr;
383 		union ccb *ccb;
384 		umass_callback_t *callback;
385 
386 		uint32_t data_len;	/* bytes */
387 		uint32_t data_rem;	/* bytes */
388 		uint32_t data_timeout;	/* ms */
389 		uint32_t actlen;	/* bytes */
390 
391 		uint8_t	cmd_data[UMASS_MAX_CMDLEN];
392 		uint8_t	cmd_len;	/* bytes */
393 		uint8_t	dir;
394 		uint8_t	lun;
395 	}	sc_transfer;
396 
397 	/* Bulk specific variables for transfers in progress */
398 	umass_bbb_cbw_t cbw;		/* command block wrapper */
399 	umass_bbb_csw_t csw;		/* command status wrapper */
400 
401 	/* CBI specific variables for transfers in progress */
402 	umass_cbi_sbl_t sbl;		/* status block */
403 
404 	device_t sc_dev;
405 	struct usb_device *sc_udev;
406 	struct cam_sim *sc_sim;		/* SCSI Interface Module */
407 	struct usb_xfer *sc_xfer[UMASS_T_MAX];
408 
409 	/*
410 	 * The command transform function is used to convert the SCSI
411 	 * commands into their derivatives, like UFI, ATAPI, and friends.
412 	 */
413 	umass_transform_t *sc_transform;
414 
415 	uint32_t sc_unit;
416 	uint32_t sc_quirks;		/* they got it almost right */
417 	uint32_t sc_proto;		/* wire and cmd protocol */
418 
419 	uint8_t	sc_name[16];
420 	uint8_t	sc_iface_no;		/* interface number */
421 	uint8_t	sc_maxlun;		/* maximum LUN number, inclusive */
422 	uint8_t	sc_last_xfer_index;
423 	uint8_t	sc_status_try;
424 };
425 
426 struct umass_probe_proto {
427 	uint32_t quirks;
428 	uint32_t proto;
429 
430 	int	error;
431 };
432 
433 /* prototypes */
434 
435 static device_probe_t umass_probe;
436 static device_attach_t umass_attach;
437 static device_detach_t umass_detach;
438 
439 static usb_callback_t umass_tr_error;
440 static usb_callback_t umass_t_bbb_reset1_callback;
441 static usb_callback_t umass_t_bbb_reset2_callback;
442 static usb_callback_t umass_t_bbb_reset3_callback;
443 static usb_callback_t umass_t_bbb_command_callback;
444 static usb_callback_t umass_t_bbb_data_read_callback;
445 static usb_callback_t umass_t_bbb_data_rd_cs_callback;
446 static usb_callback_t umass_t_bbb_data_write_callback;
447 static usb_callback_t umass_t_bbb_data_wr_cs_callback;
448 static usb_callback_t umass_t_bbb_status_callback;
449 static usb_callback_t umass_t_cbi_reset1_callback;
450 static usb_callback_t umass_t_cbi_reset2_callback;
451 static usb_callback_t umass_t_cbi_reset3_callback;
452 static usb_callback_t umass_t_cbi_reset4_callback;
453 static usb_callback_t umass_t_cbi_command_callback;
454 static usb_callback_t umass_t_cbi_data_read_callback;
455 static usb_callback_t umass_t_cbi_data_rd_cs_callback;
456 static usb_callback_t umass_t_cbi_data_write_callback;
457 static usb_callback_t umass_t_cbi_data_wr_cs_callback;
458 static usb_callback_t umass_t_cbi_status_callback;
459 
460 static void	umass_cancel_ccb(struct umass_softc *);
461 static void	umass_init_shuttle(struct umass_softc *);
462 static void	umass_reset(struct umass_softc *);
463 static void	umass_t_bbb_data_clear_stall_callback(struct usb_xfer *,
464 		    uint8_t, uint8_t, usb_error_t);
465 static void	umass_command_start(struct umass_softc *, uint8_t, void *,
466 		    uint32_t, uint32_t, umass_callback_t *, union ccb *);
467 static uint8_t	umass_bbb_get_max_lun(struct umass_softc *);
468 static void	umass_cbi_start_status(struct umass_softc *);
469 static void	umass_t_cbi_data_clear_stall_callback(struct usb_xfer *,
470 		    uint8_t, uint8_t, usb_error_t);
471 static int	umass_cam_attach_sim(struct umass_softc *);
472 static void	umass_cam_attach(struct umass_softc *);
473 static void	umass_cam_detach_sim(struct umass_softc *);
474 static void	umass_cam_action(struct cam_sim *, union ccb *);
475 static void	umass_cam_poll(struct cam_sim *);
476 static void	umass_cam_cb(struct umass_softc *, union ccb *, uint32_t,
477 		    uint8_t);
478 static void	umass_cam_sense_cb(struct umass_softc *, union ccb *, uint32_t,
479 		    uint8_t);
480 static void	umass_cam_quirk_cb(struct umass_softc *, union ccb *, uint32_t,
481 		    uint8_t);
482 static uint8_t	umass_scsi_transform(struct umass_softc *, uint8_t *, uint8_t);
483 static uint8_t	umass_rbc_transform(struct umass_softc *, uint8_t *, uint8_t);
484 static uint8_t	umass_ufi_transform(struct umass_softc *, uint8_t *, uint8_t);
485 static uint8_t	umass_atapi_transform(struct umass_softc *, uint8_t *,
486 		    uint8_t);
487 static uint8_t	umass_no_transform(struct umass_softc *, uint8_t *, uint8_t);
488 static uint8_t	umass_std_transform(struct umass_softc *, union ccb *, uint8_t
489 		    *, uint8_t);
490 
491 #ifdef USB_DEBUG
492 static void	umass_bbb_dump_cbw(struct umass_softc *, umass_bbb_cbw_t *);
493 static void	umass_bbb_dump_csw(struct umass_softc *, umass_bbb_csw_t *);
494 static void	umass_cbi_dump_cmd(struct umass_softc *, void *, uint8_t);
495 static void	umass_dump_buffer(struct umass_softc *, uint8_t *, uint32_t,
496 		    uint32_t);
497 #endif
498 
499 static struct usb_config umass_bbb_config[UMASS_T_BBB_MAX] = {
500 
501 	[UMASS_T_BBB_RESET1] = {
502 		.type = UE_CONTROL,
503 		.endpoint = 0x00,	/* Control pipe */
504 		.direction = UE_DIR_ANY,
505 		.bufsize = sizeof(struct usb_device_request),
506 		.callback = &umass_t_bbb_reset1_callback,
507 		.timeout = 5000,	/* 5 seconds */
508 		.interval = 500,	/* 500 milliseconds */
509 	},
510 
511 	[UMASS_T_BBB_RESET2] = {
512 		.type = UE_CONTROL,
513 		.endpoint = 0x00,	/* Control pipe */
514 		.direction = UE_DIR_ANY,
515 		.bufsize = sizeof(struct usb_device_request),
516 		.callback = &umass_t_bbb_reset2_callback,
517 		.timeout = 5000,	/* 5 seconds */
518 		.interval = 50,	/* 50 milliseconds */
519 	},
520 
521 	[UMASS_T_BBB_RESET3] = {
522 		.type = UE_CONTROL,
523 		.endpoint = 0x00,	/* Control pipe */
524 		.direction = UE_DIR_ANY,
525 		.bufsize = sizeof(struct usb_device_request),
526 		.callback = &umass_t_bbb_reset3_callback,
527 		.timeout = 5000,	/* 5 seconds */
528 		.interval = 50,	/* 50 milliseconds */
529 	},
530 
531 	[UMASS_T_BBB_COMMAND] = {
532 		.type = UE_BULK,
533 		.endpoint = UE_ADDR_ANY,
534 		.direction = UE_DIR_OUT,
535 		.bufsize = sizeof(umass_bbb_cbw_t),
536 		.callback = &umass_t_bbb_command_callback,
537 		.timeout = 5000,	/* 5 seconds */
538 	},
539 
540 	[UMASS_T_BBB_DATA_READ] = {
541 		.type = UE_BULK,
542 		.endpoint = UE_ADDR_ANY,
543 		.direction = UE_DIR_IN,
544 		.bufsize = UMASS_BULK_SIZE,
545 		.flags = {.proxy_buffer = 1,.short_xfer_ok = 1, UMASS_USB_FLAGS},
546 		.callback = &umass_t_bbb_data_read_callback,
547 		.timeout = 0,	/* overwritten later */
548 	},
549 
550 	[UMASS_T_BBB_DATA_RD_CS] = {
551 		.type = UE_CONTROL,
552 		.endpoint = 0x00,	/* Control pipe */
553 		.direction = UE_DIR_ANY,
554 		.bufsize = sizeof(struct usb_device_request),
555 		.callback = &umass_t_bbb_data_rd_cs_callback,
556 		.timeout = 5000,	/* 5 seconds */
557 	},
558 
559 	[UMASS_T_BBB_DATA_WRITE] = {
560 		.type = UE_BULK,
561 		.endpoint = UE_ADDR_ANY,
562 		.direction = UE_DIR_OUT,
563 		.bufsize = UMASS_BULK_SIZE,
564 		.flags = {.proxy_buffer = 1,.short_xfer_ok = 1, UMASS_USB_FLAGS},
565 		.callback = &umass_t_bbb_data_write_callback,
566 		.timeout = 0,	/* overwritten later */
567 	},
568 
569 	[UMASS_T_BBB_DATA_WR_CS] = {
570 		.type = UE_CONTROL,
571 		.endpoint = 0x00,	/* Control pipe */
572 		.direction = UE_DIR_ANY,
573 		.bufsize = sizeof(struct usb_device_request),
574 		.callback = &umass_t_bbb_data_wr_cs_callback,
575 		.timeout = 5000,	/* 5 seconds */
576 	},
577 
578 	[UMASS_T_BBB_STATUS] = {
579 		.type = UE_BULK,
580 		.endpoint = UE_ADDR_ANY,
581 		.direction = UE_DIR_IN,
582 		.bufsize = sizeof(umass_bbb_csw_t),
583 		.flags = {.short_xfer_ok = 1,},
584 		.callback = &umass_t_bbb_status_callback,
585 		.timeout = 5000,	/* ms */
586 	},
587 };
588 
589 static struct usb_config umass_cbi_config[UMASS_T_CBI_MAX] = {
590 
591 	[UMASS_T_CBI_RESET1] = {
592 		.type = UE_CONTROL,
593 		.endpoint = 0x00,	/* Control pipe */
594 		.direction = UE_DIR_ANY,
595 		.bufsize = (sizeof(struct usb_device_request) +
596 		    UMASS_CBI_DIAGNOSTIC_CMDLEN),
597 		.callback = &umass_t_cbi_reset1_callback,
598 		.timeout = 5000,	/* 5 seconds */
599 		.interval = 500,	/* 500 milliseconds */
600 	},
601 
602 	[UMASS_T_CBI_RESET2] = {
603 		.type = UE_CONTROL,
604 		.endpoint = 0x00,	/* Control pipe */
605 		.direction = UE_DIR_ANY,
606 		.bufsize = sizeof(struct usb_device_request),
607 		.callback = &umass_t_cbi_reset2_callback,
608 		.timeout = 5000,	/* 5 seconds */
609 		.interval = 50,	/* 50 milliseconds */
610 	},
611 
612 	[UMASS_T_CBI_RESET3] = {
613 		.type = UE_CONTROL,
614 		.endpoint = 0x00,	/* Control pipe */
615 		.direction = UE_DIR_ANY,
616 		.bufsize = sizeof(struct usb_device_request),
617 		.callback = &umass_t_cbi_reset3_callback,
618 		.timeout = 5000,	/* 5 seconds */
619 		.interval = 50,	/* 50 milliseconds */
620 	},
621 
622 	[UMASS_T_CBI_COMMAND] = {
623 		.type = UE_CONTROL,
624 		.endpoint = 0x00,	/* Control pipe */
625 		.direction = UE_DIR_ANY,
626 		.bufsize = (sizeof(struct usb_device_request) +
627 		    UMASS_MAX_CMDLEN),
628 		.callback = &umass_t_cbi_command_callback,
629 		.timeout = 5000,	/* 5 seconds */
630 	},
631 
632 	[UMASS_T_CBI_DATA_READ] = {
633 		.type = UE_BULK,
634 		.endpoint = UE_ADDR_ANY,
635 		.direction = UE_DIR_IN,
636 		.bufsize = UMASS_BULK_SIZE,
637 		.flags = {.proxy_buffer = 1,.short_xfer_ok = 1, UMASS_USB_FLAGS},
638 		.callback = &umass_t_cbi_data_read_callback,
639 		.timeout = 0,	/* overwritten later */
640 	},
641 
642 	[UMASS_T_CBI_DATA_RD_CS] = {
643 		.type = UE_CONTROL,
644 		.endpoint = 0x00,	/* Control pipe */
645 		.direction = UE_DIR_ANY,
646 		.bufsize = sizeof(struct usb_device_request),
647 		.callback = &umass_t_cbi_data_rd_cs_callback,
648 		.timeout = 5000,	/* 5 seconds */
649 	},
650 
651 	[UMASS_T_CBI_DATA_WRITE] = {
652 		.type = UE_BULK,
653 		.endpoint = UE_ADDR_ANY,
654 		.direction = UE_DIR_OUT,
655 		.bufsize = UMASS_BULK_SIZE,
656 		.flags = {.proxy_buffer = 1,.short_xfer_ok = 1, UMASS_USB_FLAGS},
657 		.callback = &umass_t_cbi_data_write_callback,
658 		.timeout = 0,	/* overwritten later */
659 	},
660 
661 	[UMASS_T_CBI_DATA_WR_CS] = {
662 		.type = UE_CONTROL,
663 		.endpoint = 0x00,	/* Control pipe */
664 		.direction = UE_DIR_ANY,
665 		.bufsize = sizeof(struct usb_device_request),
666 		.callback = &umass_t_cbi_data_wr_cs_callback,
667 		.timeout = 5000,	/* 5 seconds */
668 	},
669 
670 	[UMASS_T_CBI_STATUS] = {
671 		.type = UE_INTERRUPT,
672 		.endpoint = UE_ADDR_ANY,
673 		.direction = UE_DIR_IN,
674 		.flags = {.short_xfer_ok = 1,.no_pipe_ok = 1,},
675 		.bufsize = sizeof(umass_cbi_sbl_t),
676 		.callback = &umass_t_cbi_status_callback,
677 		.timeout = 5000,	/* ms */
678 	},
679 
680 	[UMASS_T_CBI_RESET4] = {
681 		.type = UE_CONTROL,
682 		.endpoint = 0x00,	/* Control pipe */
683 		.direction = UE_DIR_ANY,
684 		.bufsize = sizeof(struct usb_device_request),
685 		.callback = &umass_t_cbi_reset4_callback,
686 		.timeout = 5000,	/* ms */
687 	},
688 };
689 
690 /* If device cannot return valid inquiry data, fake it */
691 static const uint8_t fake_inq_data[SHORT_INQUIRY_LENGTH] = {
692 	0, /* removable */ 0x80, SCSI_REV_2, SCSI_REV_2,
693 	 /* additional_length */ 31, 0, 0, 0
694 };
695 
696 #define	UFI_COMMAND_LENGTH	12	/* UFI commands are always 12 bytes */
697 #define	ATAPI_COMMAND_LENGTH	12	/* ATAPI commands are always 12 bytes */
698 
699 static devclass_t umass_devclass;
700 
701 static device_method_t umass_methods[] = {
702 	/* Device interface */
703 	DEVMETHOD(device_probe, umass_probe),
704 	DEVMETHOD(device_attach, umass_attach),
705 	DEVMETHOD(device_detach, umass_detach),
706 	{0, 0}
707 };
708 
709 static driver_t umass_driver = {
710 	.name = "umass",
711 	.methods = umass_methods,
712 	.size = sizeof(struct umass_softc),
713 };
714 
715 DRIVER_MODULE(umass, uhub, umass_driver, umass_devclass, NULL, 0);
716 MODULE_DEPEND(umass, usb, 1, 1, 1);
717 MODULE_DEPEND(umass, cam, 1, 1, 1);
718 MODULE_VERSION(umass, 1);
719 
720 /*
721  * USB device probe/attach/detach
722  */
723 
724 static const STRUCT_USB_HOST_ID __used umass_devs[] = {
725 	/* generic mass storage class */
726 	{USB_IFACE_CLASS(UICLASS_MASS),},
727 };
728 
729 static uint16_t
730 umass_get_proto(struct usb_interface *iface)
731 {
732 	struct usb_interface_descriptor *id;
733 	uint16_t retval;
734 
735 	retval = 0;
736 
737 	/* Check for a standards compliant device */
738 	id = usbd_get_interface_descriptor(iface);
739 	if ((id == NULL) ||
740 	    (id->bInterfaceClass != UICLASS_MASS)) {
741 		goto done;
742 	}
743 	switch (id->bInterfaceSubClass) {
744 	case UISUBCLASS_SCSI:
745 		retval |= UMASS_PROTO_SCSI;
746 		break;
747 	case UISUBCLASS_UFI:
748 		retval |= UMASS_PROTO_UFI;
749 		break;
750 	case UISUBCLASS_RBC:
751 		retval |= UMASS_PROTO_RBC;
752 		break;
753 	case UISUBCLASS_SFF8020I:
754 	case UISUBCLASS_SFF8070I:
755 		retval |= UMASS_PROTO_ATAPI;
756 		break;
757 	default:
758 		goto done;
759 	}
760 
761 	switch (id->bInterfaceProtocol) {
762 	case UIPROTO_MASS_CBI:
763 		retval |= UMASS_PROTO_CBI;
764 		break;
765 	case UIPROTO_MASS_CBI_I:
766 		retval |= UMASS_PROTO_CBI_I;
767 		break;
768 	case UIPROTO_MASS_BBB_OLD:
769 	case UIPROTO_MASS_BBB:
770 		retval |= UMASS_PROTO_BBB;
771 		break;
772 	default:
773 		goto done;
774 	}
775 done:
776 	return (retval);
777 }
778 
779 /*
780  * Match the device we are seeing with the devices supported.
781  */
782 static struct umass_probe_proto
783 umass_probe_proto(device_t dev, struct usb_attach_arg *uaa)
784 {
785 	struct umass_probe_proto ret;
786 	uint32_t quirks = NO_QUIRKS;
787 	uint32_t proto = umass_get_proto(uaa->iface);
788 
789 	memset(&ret, 0, sizeof(ret));
790 	ret.error = BUS_PROBE_GENERIC;
791 
792 	/* Search for protocol enforcement */
793 
794 	if (usb_test_quirk(uaa, UQ_MSC_FORCE_WIRE_BBB)) {
795 		proto &= ~UMASS_PROTO_WIRE;
796 		proto |= UMASS_PROTO_BBB;
797 	} else if (usb_test_quirk(uaa, UQ_MSC_FORCE_WIRE_CBI)) {
798 		proto &= ~UMASS_PROTO_WIRE;
799 		proto |= UMASS_PROTO_CBI;
800 	} else if (usb_test_quirk(uaa, UQ_MSC_FORCE_WIRE_CBI_I)) {
801 		proto &= ~UMASS_PROTO_WIRE;
802 		proto |= UMASS_PROTO_CBI_I;
803 	}
804 
805 	if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_SCSI)) {
806 		proto &= ~UMASS_PROTO_COMMAND;
807 		proto |= UMASS_PROTO_SCSI;
808 	} else if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_ATAPI)) {
809 		proto &= ~UMASS_PROTO_COMMAND;
810 		proto |= UMASS_PROTO_ATAPI;
811 	} else if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_UFI)) {
812 		proto &= ~UMASS_PROTO_COMMAND;
813 		proto |= UMASS_PROTO_UFI;
814 	} else if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_RBC)) {
815 		proto &= ~UMASS_PROTO_COMMAND;
816 		proto |= UMASS_PROTO_RBC;
817 	}
818 
819 	/* Check if the protocol is invalid */
820 
821 	if ((proto & UMASS_PROTO_COMMAND) == 0) {
822 		ret.error = ENXIO;
823 		goto done;
824 	}
825 
826 	if ((proto & UMASS_PROTO_WIRE) == 0) {
827 		ret.error = ENXIO;
828 		goto done;
829 	}
830 
831 	/* Search for quirks */
832 
833 	if (usb_test_quirk(uaa, UQ_MSC_NO_TEST_UNIT_READY))
834 		quirks |= NO_TEST_UNIT_READY;
835 	if (usb_test_quirk(uaa, UQ_MSC_NO_RS_CLEAR_UA))
836 		quirks |= RS_NO_CLEAR_UA;
837 	if (usb_test_quirk(uaa, UQ_MSC_NO_START_STOP))
838 		quirks |= NO_START_STOP;
839 	if (usb_test_quirk(uaa, UQ_MSC_NO_GETMAXLUN))
840 		quirks |= NO_GETMAXLUN;
841 	if (usb_test_quirk(uaa, UQ_MSC_NO_INQUIRY))
842 		quirks |= NO_INQUIRY;
843 	if (usb_test_quirk(uaa, UQ_MSC_NO_INQUIRY_EVPD))
844 		quirks |= NO_INQUIRY_EVPD;
845 	if (usb_test_quirk(uaa, UQ_MSC_NO_SYNC_CACHE))
846 		quirks |= NO_SYNCHRONIZE_CACHE;
847 	if (usb_test_quirk(uaa, UQ_MSC_SHUTTLE_INIT))
848 		quirks |= SHUTTLE_INIT;
849 	if (usb_test_quirk(uaa, UQ_MSC_ALT_IFACE_1))
850 		quirks |= ALT_IFACE_1;
851 	if (usb_test_quirk(uaa, UQ_MSC_FLOPPY_SPEED))
852 		quirks |= FLOPPY_SPEED;
853 	if (usb_test_quirk(uaa, UQ_MSC_IGNORE_RESIDUE))
854 		quirks |= IGNORE_RESIDUE;
855 	if (usb_test_quirk(uaa, UQ_MSC_WRONG_CSWSIG))
856 		quirks |= WRONG_CSWSIG;
857 	if (usb_test_quirk(uaa, UQ_MSC_RBC_PAD_TO_12))
858 		quirks |= RBC_PAD_TO_12;
859 	if (usb_test_quirk(uaa, UQ_MSC_READ_CAP_OFFBY1))
860 		quirks |= READ_CAPACITY_OFFBY1;
861 	if (usb_test_quirk(uaa, UQ_MSC_FORCE_SHORT_INQ))
862 		quirks |= FORCE_SHORT_INQUIRY;
863 
864 done:
865 	ret.quirks = quirks;
866 	ret.proto = proto;
867 	return (ret);
868 }
869 
870 static int
871 umass_probe(device_t dev)
872 {
873 	struct usb_attach_arg *uaa = device_get_ivars(dev);
874 	struct umass_probe_proto temp;
875 
876 	if (uaa->usb_mode != USB_MODE_HOST) {
877 		return (ENXIO);
878 	}
879 	temp = umass_probe_proto(dev, uaa);
880 
881 	return (temp.error);
882 }
883 
884 static int
885 umass_attach(device_t dev)
886 {
887 	struct umass_softc *sc = device_get_softc(dev);
888 	struct usb_attach_arg *uaa = device_get_ivars(dev);
889 	struct umass_probe_proto temp = umass_probe_proto(dev, uaa);
890 	struct usb_interface_descriptor *id;
891 	int32_t err;
892 
893 	/*
894 	 * NOTE: the softc struct is bzero-ed in device_set_driver.
895 	 * We can safely call umass_detach without specifically
896 	 * initializing the struct.
897 	 */
898 
899 	sc->sc_dev = dev;
900 	sc->sc_udev = uaa->device;
901 	sc->sc_proto = temp.proto;
902 	sc->sc_quirks = temp.quirks;
903 	sc->sc_unit = device_get_unit(dev);
904 
905 	snprintf(sc->sc_name, sizeof(sc->sc_name),
906 	    "%s", device_get_nameunit(dev));
907 
908 	device_set_usb_desc(dev);
909 
910         mtx_init(&sc->sc_mtx, device_get_nameunit(dev),
911 	    NULL, MTX_DEF | MTX_RECURSE);
912 
913 	/* get interface index */
914 
915 	id = usbd_get_interface_descriptor(uaa->iface);
916 	if (id == NULL) {
917 		device_printf(dev, "failed to get "
918 		    "interface number\n");
919 		goto detach;
920 	}
921 	sc->sc_iface_no = id->bInterfaceNumber;
922 
923 #ifdef USB_DEBUG
924 	device_printf(dev, " ");
925 
926 	switch (sc->sc_proto & UMASS_PROTO_COMMAND) {
927 	case UMASS_PROTO_SCSI:
928 		printf("SCSI");
929 		break;
930 	case UMASS_PROTO_ATAPI:
931 		printf("8070i (ATAPI)");
932 		break;
933 	case UMASS_PROTO_UFI:
934 		printf("UFI");
935 		break;
936 	case UMASS_PROTO_RBC:
937 		printf("RBC");
938 		break;
939 	default:
940 		printf("(unknown 0x%02x)",
941 		    sc->sc_proto & UMASS_PROTO_COMMAND);
942 		break;
943 	}
944 
945 	printf(" over ");
946 
947 	switch (sc->sc_proto & UMASS_PROTO_WIRE) {
948 	case UMASS_PROTO_BBB:
949 		printf("Bulk-Only");
950 		break;
951 	case UMASS_PROTO_CBI:		/* uses Comand/Bulk pipes */
952 		printf("CBI");
953 		break;
954 	case UMASS_PROTO_CBI_I:	/* uses Comand/Bulk/Interrupt pipes */
955 		printf("CBI with CCI");
956 		break;
957 	default:
958 		printf("(unknown 0x%02x)",
959 		    sc->sc_proto & UMASS_PROTO_WIRE);
960 	}
961 
962 	printf("; quirks = 0x%04x\n", sc->sc_quirks);
963 #endif
964 
965 	if (sc->sc_quirks & ALT_IFACE_1) {
966 		err = usbd_set_alt_interface_index
967 		    (uaa->device, uaa->info.bIfaceIndex, 1);
968 
969 		if (err) {
970 			DPRINTF(sc, UDMASS_USB, "could not switch to "
971 			    "Alt Interface 1\n");
972 			goto detach;
973 		}
974 	}
975 	/* allocate all required USB transfers */
976 
977 	if (sc->sc_proto & UMASS_PROTO_BBB) {
978 
979 		err = usbd_transfer_setup(uaa->device,
980 		    &uaa->info.bIfaceIndex, sc->sc_xfer, umass_bbb_config,
981 		    UMASS_T_BBB_MAX, sc, &sc->sc_mtx);
982 
983 		/* skip reset first time */
984 		sc->sc_last_xfer_index = UMASS_T_BBB_COMMAND;
985 
986 	} else if (sc->sc_proto & (UMASS_PROTO_CBI | UMASS_PROTO_CBI_I)) {
987 
988 		err = usbd_transfer_setup(uaa->device,
989 		    &uaa->info.bIfaceIndex, sc->sc_xfer, umass_cbi_config,
990 		    UMASS_T_CBI_MAX, sc, &sc->sc_mtx);
991 
992 		/* skip reset first time */
993 		sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
994 
995 	} else {
996 		err = USB_ERR_INVAL;
997 	}
998 
999 	if (err) {
1000 		device_printf(dev, "could not setup required "
1001 		    "transfers, %s\n", usbd_errstr(err));
1002 		goto detach;
1003 	}
1004 	sc->sc_transform =
1005 	    (sc->sc_proto & UMASS_PROTO_SCSI) ? &umass_scsi_transform :
1006 	    (sc->sc_proto & UMASS_PROTO_UFI) ? &umass_ufi_transform :
1007 	    (sc->sc_proto & UMASS_PROTO_ATAPI) ? &umass_atapi_transform :
1008 	    (sc->sc_proto & UMASS_PROTO_RBC) ? &umass_rbc_transform :
1009 	    &umass_no_transform;
1010 
1011 	/* from here onwards the device can be used. */
1012 
1013 	if (sc->sc_quirks & SHUTTLE_INIT) {
1014 		umass_init_shuttle(sc);
1015 	}
1016 	/* get the maximum LUN supported by the device */
1017 
1018 	if (((sc->sc_proto & UMASS_PROTO_WIRE) == UMASS_PROTO_BBB) &&
1019 	    !(sc->sc_quirks & NO_GETMAXLUN))
1020 		sc->sc_maxlun = umass_bbb_get_max_lun(sc);
1021 	else
1022 		sc->sc_maxlun = 0;
1023 
1024 	/* Prepare the SCSI command block */
1025 	sc->cam_scsi_sense.opcode = REQUEST_SENSE;
1026 	sc->cam_scsi_test_unit_ready.opcode = TEST_UNIT_READY;
1027 
1028 	/*
1029 	 * some devices need a delay after that the configuration value is
1030 	 * set to function properly:
1031 	 */
1032 	usb_pause_mtx(NULL, hz);
1033 
1034 	/* register the SIM */
1035 	err = umass_cam_attach_sim(sc);
1036 	if (err) {
1037 		goto detach;
1038 	}
1039 	/* scan the SIM */
1040 	umass_cam_attach(sc);
1041 
1042 	DPRINTF(sc, UDMASS_GEN, "Attach finished\n");
1043 
1044 	return (0);			/* success */
1045 
1046 detach:
1047 	umass_detach(dev);
1048 	return (ENXIO);			/* failure */
1049 }
1050 
1051 static int
1052 umass_detach(device_t dev)
1053 {
1054 	struct umass_softc *sc = device_get_softc(dev);
1055 
1056 	DPRINTF(sc, UDMASS_USB, "\n");
1057 
1058 	/* teardown our statemachine */
1059 
1060 	usbd_transfer_unsetup(sc->sc_xfer, UMASS_T_MAX);
1061 
1062 #if (__FreeBSD_version >= 700037)
1063 	mtx_lock(&sc->sc_mtx);
1064 #endif
1065 	umass_cam_detach_sim(sc);
1066 
1067 #if (__FreeBSD_version >= 700037)
1068 	mtx_unlock(&sc->sc_mtx);
1069 #endif
1070 	mtx_destroy(&sc->sc_mtx);
1071 
1072 	return (0);			/* success */
1073 }
1074 
1075 static void
1076 umass_init_shuttle(struct umass_softc *sc)
1077 {
1078 	struct usb_device_request req;
1079 	usb_error_t err;
1080 	uint8_t status[2] = {0, 0};
1081 
1082 	/*
1083 	 * The Linux driver does this, but no one can tell us what the
1084 	 * command does.
1085 	 */
1086 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1087 	req.bRequest = 1;		/* XXX unknown command */
1088 	USETW(req.wValue, 0);
1089 	req.wIndex[0] = sc->sc_iface_no;
1090 	req.wIndex[1] = 0;
1091 	USETW(req.wLength, sizeof(status));
1092 	err = usbd_do_request(sc->sc_udev, NULL, &req, &status);
1093 
1094 	DPRINTF(sc, UDMASS_GEN, "Shuttle init returned 0x%02x%02x\n",
1095 	    status[0], status[1]);
1096 }
1097 
1098 /*
1099  * Generic functions to handle transfers
1100  */
1101 
1102 static void
1103 umass_transfer_start(struct umass_softc *sc, uint8_t xfer_index)
1104 {
1105 	DPRINTF(sc, UDMASS_GEN, "transfer index = "
1106 	    "%d\n", xfer_index);
1107 
1108 	if (sc->sc_xfer[xfer_index]) {
1109 		sc->sc_last_xfer_index = xfer_index;
1110 		usbd_transfer_start(sc->sc_xfer[xfer_index]);
1111 	} else {
1112 		umass_cancel_ccb(sc);
1113 	}
1114 }
1115 
1116 static void
1117 umass_reset(struct umass_softc *sc)
1118 {
1119 	DPRINTF(sc, UDMASS_GEN, "resetting device\n");
1120 
1121 	/*
1122 	 * stop the last transfer, if not already stopped:
1123 	 */
1124 	usbd_transfer_stop(sc->sc_xfer[sc->sc_last_xfer_index]);
1125 	umass_transfer_start(sc, 0);
1126 }
1127 
1128 static void
1129 umass_cancel_ccb(struct umass_softc *sc)
1130 {
1131 	union ccb *ccb;
1132 
1133 	mtx_assert(&sc->sc_mtx, MA_OWNED);
1134 
1135 	ccb = sc->sc_transfer.ccb;
1136 	sc->sc_transfer.ccb = NULL;
1137 	sc->sc_last_xfer_index = 0;
1138 
1139 	if (ccb) {
1140 		(sc->sc_transfer.callback)
1141 		    (sc, ccb, (sc->sc_transfer.data_len -
1142 		    sc->sc_transfer.actlen), STATUS_WIRE_FAILED);
1143 	}
1144 }
1145 
1146 static void
1147 umass_tr_error(struct usb_xfer *xfer, usb_error_t error)
1148 {
1149 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1150 
1151 	if (error != USB_ERR_CANCELLED) {
1152 
1153 		DPRINTF(sc, UDMASS_GEN, "transfer error, %s -> "
1154 		    "reset\n", usbd_errstr(error));
1155 	}
1156 	umass_cancel_ccb(sc);
1157 }
1158 
1159 /*
1160  * BBB protocol specific functions
1161  */
1162 
1163 static void
1164 umass_t_bbb_reset1_callback(struct usb_xfer *xfer, usb_error_t error)
1165 {
1166 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1167 	struct usb_device_request req;
1168 	struct usb_page_cache *pc;
1169 
1170 	switch (USB_GET_STATE(xfer)) {
1171 	case USB_ST_TRANSFERRED:
1172 		umass_transfer_start(sc, UMASS_T_BBB_RESET2);
1173 		return;
1174 
1175 	case USB_ST_SETUP:
1176 		/*
1177 		 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
1178 		 *
1179 		 * For Reset Recovery the host shall issue in the following order:
1180 		 * a) a Bulk-Only Mass Storage Reset
1181 		 * b) a Clear Feature HALT to the Bulk-In endpoint
1182 		 * c) a Clear Feature HALT to the Bulk-Out endpoint
1183 		 *
1184 		 * This is done in 3 steps, using 3 transfers:
1185 		 * UMASS_T_BBB_RESET1
1186 		 * UMASS_T_BBB_RESET2
1187 		 * UMASS_T_BBB_RESET3
1188 		 */
1189 
1190 		DPRINTF(sc, UDMASS_BBB, "BBB reset!\n");
1191 
1192 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1193 		req.bRequest = UR_BBB_RESET;	/* bulk only reset */
1194 		USETW(req.wValue, 0);
1195 		req.wIndex[0] = sc->sc_iface_no;
1196 		req.wIndex[1] = 0;
1197 		USETW(req.wLength, 0);
1198 
1199 		pc = usbd_xfer_get_frame(xfer, 0);
1200 		usbd_copy_in(pc, 0, &req, sizeof(req));
1201 
1202 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1203 		usbd_xfer_set_frames(xfer, 1);
1204 		usbd_transfer_submit(xfer);
1205 		return;
1206 
1207 	default:			/* Error */
1208 		umass_tr_error(xfer, error);
1209 		return;
1210 
1211 	}
1212 }
1213 
1214 static void
1215 umass_t_bbb_reset2_callback(struct usb_xfer *xfer, usb_error_t error)
1216 {
1217 	umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_RESET3,
1218 	    UMASS_T_BBB_DATA_READ, error);
1219 }
1220 
1221 static void
1222 umass_t_bbb_reset3_callback(struct usb_xfer *xfer, usb_error_t error)
1223 {
1224 	umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_COMMAND,
1225 	    UMASS_T_BBB_DATA_WRITE, error);
1226 }
1227 
1228 static void
1229 umass_t_bbb_data_clear_stall_callback(struct usb_xfer *xfer,
1230     uint8_t next_xfer, uint8_t stall_xfer, usb_error_t error)
1231 {
1232 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1233 
1234 	switch (USB_GET_STATE(xfer)) {
1235 	case USB_ST_TRANSFERRED:
1236 tr_transferred:
1237 		umass_transfer_start(sc, next_xfer);
1238 		return;
1239 
1240 	case USB_ST_SETUP:
1241 		if (usbd_clear_stall_callback(xfer, sc->sc_xfer[stall_xfer])) {
1242 			goto tr_transferred;
1243 		}
1244 		return;
1245 
1246 	default:			/* Error */
1247 		umass_tr_error(xfer, error);
1248 		return;
1249 
1250 	}
1251 }
1252 
1253 static void
1254 umass_t_bbb_command_callback(struct usb_xfer *xfer, usb_error_t error)
1255 {
1256 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1257 	union ccb *ccb = sc->sc_transfer.ccb;
1258 	struct usb_page_cache *pc;
1259 	uint32_t tag;
1260 
1261 	switch (USB_GET_STATE(xfer)) {
1262 	case USB_ST_TRANSFERRED:
1263 		umass_transfer_start
1264 		    (sc, ((sc->sc_transfer.dir == DIR_IN) ? UMASS_T_BBB_DATA_READ :
1265 		    (sc->sc_transfer.dir == DIR_OUT) ? UMASS_T_BBB_DATA_WRITE :
1266 		    UMASS_T_BBB_STATUS));
1267 		return;
1268 
1269 	case USB_ST_SETUP:
1270 
1271 		sc->sc_status_try = 0;
1272 
1273 		if (ccb) {
1274 
1275 			/*
1276 		         * the initial value is not important,
1277 		         * as long as the values are unique:
1278 		         */
1279 			tag = UGETDW(sc->cbw.dCBWTag) + 1;
1280 
1281 			USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
1282 			USETDW(sc->cbw.dCBWTag, tag);
1283 
1284 			/*
1285 		         * dCBWDataTransferLength:
1286 		         *   This field indicates the number of bytes of data that the host
1287 		         *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
1288 		         *   the Direction bit) during the execution of this command. If this
1289 		         *   field is set to 0, the device will expect that no data will be
1290 		         *   transferred IN or OUT during this command, regardless of the value
1291 		         *   of the Direction bit defined in dCBWFlags.
1292 		         */
1293 			USETDW(sc->cbw.dCBWDataTransferLength, sc->sc_transfer.data_len);
1294 
1295 			/*
1296 		         * dCBWFlags:
1297 		         *   The bits of the Flags field are defined as follows:
1298 		         *     Bits 0-6  reserved
1299 		         *     Bit  7    Direction - this bit shall be ignored if the
1300 		         *                           dCBWDataTransferLength field is zero.
1301 		         *               0 = data Out from host to device
1302 		         *               1 = data In from device to host
1303 		         */
1304 			sc->cbw.bCBWFlags = ((sc->sc_transfer.dir == DIR_IN) ?
1305 			    CBWFLAGS_IN : CBWFLAGS_OUT);
1306 			sc->cbw.bCBWLUN = sc->sc_transfer.lun;
1307 
1308 			if (sc->sc_transfer.cmd_len > sizeof(sc->cbw.CBWCDB)) {
1309 				sc->sc_transfer.cmd_len = sizeof(sc->cbw.CBWCDB);
1310 				DPRINTF(sc, UDMASS_BBB, "Truncating long command!\n");
1311 			}
1312 			sc->cbw.bCDBLength = sc->sc_transfer.cmd_len;
1313 
1314 			bcopy(sc->sc_transfer.cmd_data, sc->cbw.CBWCDB,
1315 			    sc->sc_transfer.cmd_len);
1316 
1317 			bzero(sc->sc_transfer.cmd_data + sc->sc_transfer.cmd_len,
1318 			    sizeof(sc->cbw.CBWCDB) - sc->sc_transfer.cmd_len);
1319 
1320 			DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
1321 
1322 			pc = usbd_xfer_get_frame(xfer, 0);
1323 			usbd_copy_in(pc, 0, &sc->cbw, sizeof(sc->cbw));
1324 			usbd_xfer_set_frame_len(xfer, 0, sizeof(sc->cbw));
1325 
1326 			usbd_transfer_submit(xfer);
1327 		}
1328 		return;
1329 
1330 	default:			/* Error */
1331 		umass_tr_error(xfer, error);
1332 		return;
1333 
1334 	}
1335 }
1336 
1337 static void
1338 umass_t_bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
1339 {
1340 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1341 	uint32_t max_bulk = usbd_xfer_max_len(xfer);
1342 #ifndef UMASS_EXT_BUFFER
1343 	struct usb_page_cache *pc;
1344 #endif
1345 	int actlen, sumlen;
1346 
1347 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1348 
1349 	switch (USB_GET_STATE(xfer)) {
1350 	case USB_ST_TRANSFERRED:
1351 #ifndef UMASS_EXT_BUFFER
1352 		pc = usbd_xfer_get_frame(xfer, 0);
1353 		usbd_copy_out(pc, 0, sc->sc_transfer.data_ptr, actlen);
1354 #endif
1355 		sc->sc_transfer.data_rem -= actlen;
1356 		sc->sc_transfer.data_ptr += actlen;
1357 		sc->sc_transfer.actlen += actlen;
1358 
1359 		if (actlen < sumlen) {
1360 			/* short transfer */
1361 			sc->sc_transfer.data_rem = 0;
1362 		}
1363 	case USB_ST_SETUP:
1364 		DPRINTF(sc, UDMASS_BBB, "max_bulk=%d, data_rem=%d\n",
1365 		    max_bulk, sc->sc_transfer.data_rem);
1366 
1367 		if (sc->sc_transfer.data_rem == 0) {
1368 			umass_transfer_start(sc, UMASS_T_BBB_STATUS);
1369 			return;
1370 		}
1371 		if (max_bulk > sc->sc_transfer.data_rem) {
1372 			max_bulk = sc->sc_transfer.data_rem;
1373 		}
1374 		usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1375 
1376 #ifdef UMASS_EXT_BUFFER
1377 		usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1378 		    max_bulk);
1379 #else
1380 		usbd_xfer_set_frame_len(xfer, 0, max_bulk);
1381 #endif
1382 		usbd_transfer_submit(xfer);
1383 		return;
1384 
1385 	default:			/* Error */
1386 		if (error == USB_ERR_CANCELLED) {
1387 			umass_tr_error(xfer, error);
1388 		} else {
1389 			umass_transfer_start(sc, UMASS_T_BBB_DATA_RD_CS);
1390 		}
1391 		return;
1392 
1393 	}
1394 }
1395 
1396 static void
1397 umass_t_bbb_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1398 {
1399 	umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_STATUS,
1400 	    UMASS_T_BBB_DATA_READ, error);
1401 }
1402 
1403 static void
1404 umass_t_bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
1405 {
1406 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1407 	uint32_t max_bulk = usbd_xfer_max_len(xfer);
1408 #ifndef UMASS_EXT_BUFFER
1409 	struct usb_page_cache *pc;
1410 #endif
1411 	int actlen, sumlen;
1412 
1413 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1414 
1415 	switch (USB_GET_STATE(xfer)) {
1416 	case USB_ST_TRANSFERRED:
1417 		sc->sc_transfer.data_rem -= actlen;
1418 		sc->sc_transfer.data_ptr += actlen;
1419 		sc->sc_transfer.actlen += actlen;
1420 
1421 		if (actlen < sumlen) {
1422 			/* short transfer */
1423 			sc->sc_transfer.data_rem = 0;
1424 		}
1425 	case USB_ST_SETUP:
1426 		DPRINTF(sc, UDMASS_BBB, "max_bulk=%d, data_rem=%d\n",
1427 		    max_bulk, sc->sc_transfer.data_rem);
1428 
1429 		if (sc->sc_transfer.data_rem == 0) {
1430 			umass_transfer_start(sc, UMASS_T_BBB_STATUS);
1431 			return;
1432 		}
1433 		if (max_bulk > sc->sc_transfer.data_rem) {
1434 			max_bulk = sc->sc_transfer.data_rem;
1435 		}
1436 		usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1437 
1438 #ifdef UMASS_EXT_BUFFER
1439 		usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1440 		    max_bulk);
1441 #else
1442 		pc = usbd_xfer_get_frame(xfer, 0);
1443 		usbd_copy_in(pc, 0, sc->sc_transfer.data_ptr, max_bulk);
1444 		usbd_xfer_set_frame_len(xfer, 0, max_bulk);
1445 #endif
1446 
1447 		usbd_transfer_submit(xfer);
1448 		return;
1449 
1450 	default:			/* Error */
1451 		if (error == USB_ERR_CANCELLED) {
1452 			umass_tr_error(xfer, error);
1453 		} else {
1454 			umass_transfer_start(sc, UMASS_T_BBB_DATA_WR_CS);
1455 		}
1456 		return;
1457 
1458 	}
1459 }
1460 
1461 static void
1462 umass_t_bbb_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1463 {
1464 	umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_STATUS,
1465 	    UMASS_T_BBB_DATA_WRITE, error);
1466 }
1467 
1468 static void
1469 umass_t_bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
1470 {
1471 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1472 	union ccb *ccb = sc->sc_transfer.ccb;
1473 	struct usb_page_cache *pc;
1474 	uint32_t residue;
1475 	int actlen;
1476 
1477 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1478 
1479 	switch (USB_GET_STATE(xfer)) {
1480 	case USB_ST_TRANSFERRED:
1481 
1482 		/*
1483 		 * Do a full reset if there is something wrong with the CSW:
1484 		 */
1485 		sc->sc_status_try = 1;
1486 
1487 		/* Zero missing parts of the CSW: */
1488 
1489 		if (actlen < sizeof(sc->csw)) {
1490 			bzero(&sc->csw, sizeof(sc->csw));
1491 		}
1492 		pc = usbd_xfer_get_frame(xfer, 0);
1493 		usbd_copy_out(pc, 0, &sc->csw, actlen);
1494 
1495 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
1496 
1497 		residue = UGETDW(sc->csw.dCSWDataResidue);
1498 
1499 		if ((!residue) || (sc->sc_quirks & IGNORE_RESIDUE)) {
1500 			residue = (sc->sc_transfer.data_len -
1501 			    sc->sc_transfer.actlen);
1502 		}
1503 		if (residue > sc->sc_transfer.data_len) {
1504 			DPRINTF(sc, UDMASS_BBB, "truncating residue from %d "
1505 			    "to %d bytes\n", residue, sc->sc_transfer.data_len);
1506 			residue = sc->sc_transfer.data_len;
1507 		}
1508 		/* translate weird command-status signatures: */
1509 		if (sc->sc_quirks & WRONG_CSWSIG) {
1510 
1511 			uint32_t temp = UGETDW(sc->csw.dCSWSignature);
1512 
1513 			if ((temp == CSWSIGNATURE_OLYMPUS_C1) ||
1514 			    (temp == CSWSIGNATURE_IMAGINATION_DBX1)) {
1515 				USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
1516 			}
1517 		}
1518 		/* check CSW and handle eventual error */
1519 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
1520 			DPRINTF(sc, UDMASS_BBB, "bad CSW signature 0x%08x != 0x%08x\n",
1521 			    UGETDW(sc->csw.dCSWSignature), CSWSIGNATURE);
1522 			/*
1523 			 * Invalid CSW: Wrong signature or wrong tag might
1524 			 * indicate that we lost synchronization. Reset the
1525 			 * device.
1526 			 */
1527 			goto tr_error;
1528 		} else if (UGETDW(sc->csw.dCSWTag) != UGETDW(sc->cbw.dCBWTag)) {
1529 			DPRINTF(sc, UDMASS_BBB, "Invalid CSW: tag 0x%08x should be "
1530 			    "0x%08x\n", UGETDW(sc->csw.dCSWTag),
1531 			    UGETDW(sc->cbw.dCBWTag));
1532 			goto tr_error;
1533 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
1534 			DPRINTF(sc, UDMASS_BBB, "Invalid CSW: status %d > %d\n",
1535 			    sc->csw.bCSWStatus, CSWSTATUS_PHASE);
1536 			goto tr_error;
1537 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
1538 			DPRINTF(sc, UDMASS_BBB, "Phase error, residue = "
1539 			    "%d\n", residue);
1540 			goto tr_error;
1541 		} else if (sc->sc_transfer.actlen > sc->sc_transfer.data_len) {
1542 			DPRINTF(sc, UDMASS_BBB, "Buffer overrun %d > %d\n",
1543 			    sc->sc_transfer.actlen, sc->sc_transfer.data_len);
1544 			goto tr_error;
1545 		} else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
1546 			DPRINTF(sc, UDMASS_BBB, "Command failed, residue = "
1547 			    "%d\n", residue);
1548 
1549 			sc->sc_transfer.ccb = NULL;
1550 
1551 			sc->sc_last_xfer_index = UMASS_T_BBB_COMMAND;
1552 
1553 			(sc->sc_transfer.callback)
1554 			    (sc, ccb, residue, STATUS_CMD_FAILED);
1555 		} else {
1556 			sc->sc_transfer.ccb = NULL;
1557 
1558 			sc->sc_last_xfer_index = UMASS_T_BBB_COMMAND;
1559 
1560 			(sc->sc_transfer.callback)
1561 			    (sc, ccb, residue, STATUS_CMD_OK);
1562 		}
1563 		return;
1564 
1565 	case USB_ST_SETUP:
1566 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1567 		usbd_transfer_submit(xfer);
1568 		return;
1569 
1570 	default:
1571 tr_error:
1572 		DPRINTF(sc, UDMASS_BBB, "Failed to read CSW: %s, try %d\n",
1573 		    usbd_errstr(error), sc->sc_status_try);
1574 
1575 		if ((error == USB_ERR_CANCELLED) ||
1576 		    (sc->sc_status_try)) {
1577 			umass_tr_error(xfer, error);
1578 		} else {
1579 			sc->sc_status_try = 1;
1580 			umass_transfer_start(sc, UMASS_T_BBB_DATA_RD_CS);
1581 		}
1582 		return;
1583 
1584 	}
1585 }
1586 
1587 static void
1588 umass_command_start(struct umass_softc *sc, uint8_t dir,
1589     void *data_ptr, uint32_t data_len,
1590     uint32_t data_timeout, umass_callback_t *callback,
1591     union ccb *ccb)
1592 {
1593 	sc->sc_transfer.lun = ccb->ccb_h.target_lun;
1594 
1595 	/*
1596 	 * NOTE: assumes that "sc->sc_transfer.cmd_data" and
1597 	 * "sc->sc_transfer.cmd_len" has been properly
1598 	 * initialized.
1599 	 */
1600 
1601 	sc->sc_transfer.dir = data_len ? dir : DIR_NONE;
1602 	sc->sc_transfer.data_ptr = data_ptr;
1603 	sc->sc_transfer.data_len = data_len;
1604 	sc->sc_transfer.data_rem = data_len;
1605 	sc->sc_transfer.data_timeout = (data_timeout + UMASS_TIMEOUT);
1606 
1607 	sc->sc_transfer.actlen = 0;
1608 	sc->sc_transfer.callback = callback;
1609 	sc->sc_transfer.ccb = ccb;
1610 
1611 	if (sc->sc_xfer[sc->sc_last_xfer_index]) {
1612 		usbd_transfer_start(sc->sc_xfer[sc->sc_last_xfer_index]);
1613 	} else {
1614 		ccb->ccb_h.status = CAM_TID_INVALID;
1615 		xpt_done(ccb);
1616 	}
1617 }
1618 
1619 static uint8_t
1620 umass_bbb_get_max_lun(struct umass_softc *sc)
1621 {
1622 	struct usb_device_request req;
1623 	usb_error_t err;
1624 	uint8_t buf = 0;
1625 
1626 	/* The Get Max Lun command is a class-specific request. */
1627 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1628 	req.bRequest = UR_BBB_GET_MAX_LUN;
1629 	USETW(req.wValue, 0);
1630 	req.wIndex[0] = sc->sc_iface_no;
1631 	req.wIndex[1] = 0;
1632 	USETW(req.wLength, 1);
1633 
1634 	err = usbd_do_request(sc->sc_udev, NULL, &req, &buf);
1635 	if (err) {
1636 		buf = 0;
1637 
1638 		/* Device doesn't support Get Max Lun request. */
1639 		printf("%s: Get Max Lun not supported (%s)\n",
1640 		    sc->sc_name, usbd_errstr(err));
1641 	}
1642 	return (buf);
1643 }
1644 
1645 /*
1646  * Command/Bulk/Interrupt (CBI) specific functions
1647  */
1648 
1649 static void
1650 umass_cbi_start_status(struct umass_softc *sc)
1651 {
1652 	if (sc->sc_xfer[UMASS_T_CBI_STATUS]) {
1653 		umass_transfer_start(sc, UMASS_T_CBI_STATUS);
1654 	} else {
1655 		union ccb *ccb = sc->sc_transfer.ccb;
1656 
1657 		sc->sc_transfer.ccb = NULL;
1658 
1659 		sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
1660 
1661 		(sc->sc_transfer.callback)
1662 		    (sc, ccb, (sc->sc_transfer.data_len -
1663 		    sc->sc_transfer.actlen), STATUS_CMD_UNKNOWN);
1664 	}
1665 }
1666 
1667 static void
1668 umass_t_cbi_reset1_callback(struct usb_xfer *xfer, usb_error_t error)
1669 {
1670 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1671 	struct usb_device_request req;
1672 	struct usb_page_cache *pc;
1673 	uint8_t buf[UMASS_CBI_DIAGNOSTIC_CMDLEN];
1674 
1675 	uint8_t i;
1676 
1677 	switch (USB_GET_STATE(xfer)) {
1678 	case USB_ST_TRANSFERRED:
1679 		umass_transfer_start(sc, UMASS_T_CBI_RESET2);
1680 		break;
1681 
1682 	case USB_ST_SETUP:
1683 		/*
1684 		 * Command Block Reset Protocol
1685 		 *
1686 		 * First send a reset request to the device. Then clear
1687 		 * any possibly stalled bulk endpoints.
1688 		 *
1689 		 * This is done in 3 steps, using 3 transfers:
1690 		 * UMASS_T_CBI_RESET1
1691 		 * UMASS_T_CBI_RESET2
1692 		 * UMASS_T_CBI_RESET3
1693 		 * UMASS_T_CBI_RESET4 (only if there is an interrupt endpoint)
1694 		 */
1695 
1696 		DPRINTF(sc, UDMASS_CBI, "CBI reset!\n");
1697 
1698 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1699 		req.bRequest = UR_CBI_ADSC;
1700 		USETW(req.wValue, 0);
1701 		req.wIndex[0] = sc->sc_iface_no;
1702 		req.wIndex[1] = 0;
1703 		USETW(req.wLength, UMASS_CBI_DIAGNOSTIC_CMDLEN);
1704 
1705 		/*
1706 		 * The 0x1d code is the SEND DIAGNOSTIC command. To
1707 		 * distinguish between the two, the last 10 bytes of the CBL
1708 		 * is filled with 0xff (section 2.2 of the CBI
1709 		 * specification)
1710 		 */
1711 		buf[0] = 0x1d;		/* Command Block Reset */
1712 		buf[1] = 0x04;
1713 
1714 		for (i = 2; i < UMASS_CBI_DIAGNOSTIC_CMDLEN; i++) {
1715 			buf[i] = 0xff;
1716 		}
1717 
1718 		pc = usbd_xfer_get_frame(xfer, 0);
1719 		usbd_copy_in(pc, 0, &req, sizeof(req));
1720 		pc = usbd_xfer_get_frame(xfer, 1);
1721 		usbd_copy_in(pc, 0, buf, sizeof(buf));
1722 
1723 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1724 		usbd_xfer_set_frame_len(xfer, 1, sizeof(buf));
1725 		usbd_xfer_set_frames(xfer, 2);
1726 		usbd_transfer_submit(xfer);
1727 		break;
1728 
1729 	default:			/* Error */
1730 		if (error == USB_ERR_CANCELLED)
1731 			umass_tr_error(xfer, error);
1732 		else
1733 			umass_transfer_start(sc, UMASS_T_CBI_RESET2);
1734 		break;
1735 
1736 	}
1737 }
1738 
1739 static void
1740 umass_t_cbi_reset2_callback(struct usb_xfer *xfer, usb_error_t error)
1741 {
1742 	umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_RESET3,
1743 	    UMASS_T_CBI_DATA_READ, error);
1744 }
1745 
1746 static void
1747 umass_t_cbi_reset3_callback(struct usb_xfer *xfer, usb_error_t error)
1748 {
1749 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1750 
1751 	umass_t_cbi_data_clear_stall_callback
1752 	    (xfer, (sc->sc_xfer[UMASS_T_CBI_RESET4] &&
1753 	    sc->sc_xfer[UMASS_T_CBI_STATUS]) ?
1754 	    UMASS_T_CBI_RESET4 : UMASS_T_CBI_COMMAND,
1755 	    UMASS_T_CBI_DATA_WRITE, error);
1756 }
1757 
1758 static void
1759 umass_t_cbi_reset4_callback(struct usb_xfer *xfer, usb_error_t error)
1760 {
1761 	umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_COMMAND,
1762 	    UMASS_T_CBI_STATUS, error);
1763 }
1764 
1765 static void
1766 umass_t_cbi_data_clear_stall_callback(struct usb_xfer *xfer,
1767     uint8_t next_xfer, uint8_t stall_xfer, usb_error_t error)
1768 {
1769 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1770 
1771 	switch (USB_GET_STATE(xfer)) {
1772 	case USB_ST_TRANSFERRED:
1773 tr_transferred:
1774 		if (next_xfer == UMASS_T_CBI_STATUS) {
1775 			umass_cbi_start_status(sc);
1776 		} else {
1777 			umass_transfer_start(sc, next_xfer);
1778 		}
1779 		break;
1780 
1781 	case USB_ST_SETUP:
1782 		if (usbd_clear_stall_callback(xfer, sc->sc_xfer[stall_xfer])) {
1783 			goto tr_transferred;	/* should not happen */
1784 		}
1785 		break;
1786 
1787 	default:			/* Error */
1788 		umass_tr_error(xfer, error);
1789 		break;
1790 
1791 	}
1792 }
1793 
1794 static void
1795 umass_t_cbi_command_callback(struct usb_xfer *xfer, usb_error_t error)
1796 {
1797 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1798 	union ccb *ccb = sc->sc_transfer.ccb;
1799 	struct usb_device_request req;
1800 	struct usb_page_cache *pc;
1801 
1802 	switch (USB_GET_STATE(xfer)) {
1803 	case USB_ST_TRANSFERRED:
1804 
1805 		if (sc->sc_transfer.dir == DIR_NONE) {
1806 			umass_cbi_start_status(sc);
1807 		} else {
1808 			umass_transfer_start
1809 			    (sc, (sc->sc_transfer.dir == DIR_IN) ?
1810 			    UMASS_T_CBI_DATA_READ : UMASS_T_CBI_DATA_WRITE);
1811 		}
1812 		break;
1813 
1814 	case USB_ST_SETUP:
1815 
1816 		if (ccb) {
1817 
1818 			/*
1819 		         * do a CBI transfer with cmd_len bytes from
1820 		         * cmd_data, possibly a data phase of data_len
1821 		         * bytes from/to the device and finally a status
1822 		         * read phase.
1823 		         */
1824 
1825 			req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1826 			req.bRequest = UR_CBI_ADSC;
1827 			USETW(req.wValue, 0);
1828 			req.wIndex[0] = sc->sc_iface_no;
1829 			req.wIndex[1] = 0;
1830 			req.wLength[0] = sc->sc_transfer.cmd_len;
1831 			req.wLength[1] = 0;
1832 
1833 			pc = usbd_xfer_get_frame(xfer, 0);
1834 			usbd_copy_in(pc, 0, &req, sizeof(req));
1835 			pc = usbd_xfer_get_frame(xfer, 1);
1836 			usbd_copy_in(pc, 0, sc->sc_transfer.cmd_data,
1837 			    sc->sc_transfer.cmd_len);
1838 
1839 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1840 			usbd_xfer_set_frame_len(xfer, 1, sc->sc_transfer.cmd_len);
1841 			usbd_xfer_set_frames(xfer,
1842 			    sc->sc_transfer.cmd_len ? 2 : 1);
1843 
1844 			DIF(UDMASS_CBI,
1845 			    umass_cbi_dump_cmd(sc,
1846 			    sc->sc_transfer.cmd_data,
1847 			    sc->sc_transfer.cmd_len));
1848 
1849 			usbd_transfer_submit(xfer);
1850 		}
1851 		break;
1852 
1853 	default:			/* Error */
1854 		/*
1855 		 * STALL on the control pipe can be result of the command error.
1856 		 * Attempt to clear this STALL same as for bulk pipe also
1857 		 * results in command completion interrupt, but ASC/ASCQ there
1858 		 * look like not always valid, so don't bother about it.
1859 		 */
1860 		if ((error == USB_ERR_STALLED) ||
1861 		    (sc->sc_transfer.callback == &umass_cam_cb)) {
1862 			sc->sc_transfer.ccb = NULL;
1863 			(sc->sc_transfer.callback)
1864 			    (sc, ccb, sc->sc_transfer.data_len,
1865 			    STATUS_CMD_UNKNOWN);
1866 		} else {
1867 			umass_tr_error(xfer, error);
1868 			/* skip reset */
1869 			sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
1870 		}
1871 		break;
1872 	}
1873 }
1874 
1875 static void
1876 umass_t_cbi_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
1877 {
1878 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1879 	uint32_t max_bulk = usbd_xfer_max_len(xfer);
1880 #ifndef UMASS_EXT_BUFFER
1881 	struct usb_page_cache *pc;
1882 #endif
1883 	int actlen, sumlen;
1884 
1885 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1886 
1887 	switch (USB_GET_STATE(xfer)) {
1888 	case USB_ST_TRANSFERRED:
1889 #ifndef UMASS_EXT_BUFFER
1890 		pc = usbd_xfer_get_frame(xfer, 0);
1891 		usbd_copy_out(pc, 0, sc->sc_transfer.data_ptr, actlen);
1892 #endif
1893 		sc->sc_transfer.data_rem -= actlen;
1894 		sc->sc_transfer.data_ptr += actlen;
1895 		sc->sc_transfer.actlen += actlen;
1896 
1897 		if (actlen < sumlen) {
1898 			/* short transfer */
1899 			sc->sc_transfer.data_rem = 0;
1900 		}
1901 	case USB_ST_SETUP:
1902 		DPRINTF(sc, UDMASS_CBI, "max_bulk=%d, data_rem=%d\n",
1903 		    max_bulk, sc->sc_transfer.data_rem);
1904 
1905 		if (sc->sc_transfer.data_rem == 0) {
1906 			umass_cbi_start_status(sc);
1907 			break;
1908 		}
1909 		if (max_bulk > sc->sc_transfer.data_rem) {
1910 			max_bulk = sc->sc_transfer.data_rem;
1911 		}
1912 		usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1913 
1914 #ifdef UMASS_EXT_BUFFER
1915 		usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1916 		    max_bulk);
1917 #else
1918 		usbd_xfer_set_frame_len(xfer, 0, max_bulk);
1919 #endif
1920 		usbd_transfer_submit(xfer);
1921 		break;
1922 
1923 	default:			/* Error */
1924 		if ((error == USB_ERR_CANCELLED) ||
1925 		    (sc->sc_transfer.callback != &umass_cam_cb)) {
1926 			umass_tr_error(xfer, error);
1927 		} else {
1928 			umass_transfer_start(sc, UMASS_T_CBI_DATA_RD_CS);
1929 		}
1930 		break;
1931 
1932 	}
1933 }
1934 
1935 static void
1936 umass_t_cbi_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1937 {
1938 	umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_STATUS,
1939 	    UMASS_T_CBI_DATA_READ, error);
1940 }
1941 
1942 static void
1943 umass_t_cbi_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
1944 {
1945 	struct umass_softc *sc = usbd_xfer_softc(xfer);
1946 	uint32_t max_bulk = usbd_xfer_max_len(xfer);
1947 #ifndef UMASS_EXT_BUFFER
1948 	struct usb_page_cache *pc;
1949 #endif
1950 	int actlen, sumlen;
1951 
1952 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1953 
1954 	switch (USB_GET_STATE(xfer)) {
1955 	case USB_ST_TRANSFERRED:
1956 		sc->sc_transfer.data_rem -= actlen;
1957 		sc->sc_transfer.data_ptr += actlen;
1958 		sc->sc_transfer.actlen += actlen;
1959 
1960 		if (actlen < sumlen) {
1961 			/* short transfer */
1962 			sc->sc_transfer.data_rem = 0;
1963 		}
1964 	case USB_ST_SETUP:
1965 		DPRINTF(sc, UDMASS_CBI, "max_bulk=%d, data_rem=%d\n",
1966 		    max_bulk, sc->sc_transfer.data_rem);
1967 
1968 		if (sc->sc_transfer.data_rem == 0) {
1969 			umass_cbi_start_status(sc);
1970 			break;
1971 		}
1972 		if (max_bulk > sc->sc_transfer.data_rem) {
1973 			max_bulk = sc->sc_transfer.data_rem;
1974 		}
1975 		usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1976 
1977 #ifdef UMASS_EXT_BUFFER
1978 		usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1979 		    max_bulk);
1980 #else
1981 		pc = usbd_xfer_get_frame(xfer, 0);
1982 		usbd_copy_in(pc, 0, sc->sc_transfer.data_ptr, max_bulk);
1983 		usbd_xfer_set_frame_len(xfer, 0, max_bulk);
1984 #endif
1985 
1986 		usbd_transfer_submit(xfer);
1987 		break;
1988 
1989 	default:			/* Error */
1990 		if ((error == USB_ERR_CANCELLED) ||
1991 		    (sc->sc_transfer.callback != &umass_cam_cb)) {
1992 			umass_tr_error(xfer, error);
1993 		} else {
1994 			umass_transfer_start(sc, UMASS_T_CBI_DATA_WR_CS);
1995 		}
1996 		break;
1997 
1998 	}
1999 }
2000 
2001 static void
2002 umass_t_cbi_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
2003 {
2004 	umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_STATUS,
2005 	    UMASS_T_CBI_DATA_WRITE, error);
2006 }
2007 
2008 static void
2009 umass_t_cbi_status_callback(struct usb_xfer *xfer, usb_error_t error)
2010 {
2011 	struct umass_softc *sc = usbd_xfer_softc(xfer);
2012 	union ccb *ccb = sc->sc_transfer.ccb;
2013 	struct usb_page_cache *pc;
2014 	uint32_t residue;
2015 	uint8_t status;
2016 	int actlen;
2017 
2018 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
2019 
2020 	switch (USB_GET_STATE(xfer)) {
2021 	case USB_ST_TRANSFERRED:
2022 
2023 		if (actlen < sizeof(sc->sbl)) {
2024 			goto tr_setup;
2025 		}
2026 		pc = usbd_xfer_get_frame(xfer, 0);
2027 		usbd_copy_out(pc, 0, &sc->sbl, sizeof(sc->sbl));
2028 
2029 		residue = (sc->sc_transfer.data_len -
2030 		    sc->sc_transfer.actlen);
2031 
2032 		/* dissect the information in the buffer */
2033 
2034 		if (sc->sc_proto & UMASS_PROTO_UFI) {
2035 
2036 			/*
2037 			 * Section 3.4.3.1.3 specifies that the UFI command
2038 			 * protocol returns an ASC and ASCQ in the interrupt
2039 			 * data block.
2040 			 */
2041 
2042 			DPRINTF(sc, UDMASS_CBI, "UFI CCI, ASC = 0x%02x, "
2043 			    "ASCQ = 0x%02x\n", sc->sbl.ufi.asc,
2044 			    sc->sbl.ufi.ascq);
2045 
2046 			status = (((sc->sbl.ufi.asc == 0) &&
2047 			    (sc->sbl.ufi.ascq == 0)) ?
2048 			    STATUS_CMD_OK : STATUS_CMD_FAILED);
2049 
2050 			sc->sc_transfer.ccb = NULL;
2051 
2052 			sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
2053 
2054 			(sc->sc_transfer.callback)
2055 			    (sc, ccb, residue, status);
2056 
2057 			break;
2058 
2059 		} else {
2060 
2061 			/* Command Interrupt Data Block */
2062 
2063 			DPRINTF(sc, UDMASS_CBI, "type=0x%02x, value=0x%02x\n",
2064 			    sc->sbl.common.type, sc->sbl.common.value);
2065 
2066 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
2067 
2068 				status = (sc->sbl.common.value & IDB_VALUE_STATUS_MASK);
2069 
2070 				status = ((status == IDB_VALUE_PASS) ? STATUS_CMD_OK :
2071 				    (status == IDB_VALUE_FAIL) ? STATUS_CMD_FAILED :
2072 				    (status == IDB_VALUE_PERSISTENT) ? STATUS_CMD_FAILED :
2073 				    STATUS_WIRE_FAILED);
2074 
2075 				sc->sc_transfer.ccb = NULL;
2076 
2077 				sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
2078 
2079 				(sc->sc_transfer.callback)
2080 				    (sc, ccb, residue, status);
2081 
2082 				break;
2083 			}
2084 		}
2085 
2086 		/* fallthrough */
2087 
2088 	case USB_ST_SETUP:
2089 tr_setup:
2090 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
2091 		usbd_transfer_submit(xfer);
2092 		break;
2093 
2094 	default:			/* Error */
2095 		DPRINTF(sc, UDMASS_CBI, "Failed to read CSW: %s\n",
2096 		    usbd_errstr(error));
2097 		umass_tr_error(xfer, error);
2098 		break;
2099 
2100 	}
2101 }
2102 
2103 /*
2104  * CAM specific functions (used by SCSI, UFI, 8070i (ATAPI))
2105  */
2106 
2107 static int
2108 umass_cam_attach_sim(struct umass_softc *sc)
2109 {
2110 	struct cam_devq *devq;		/* Per device Queue */
2111 
2112 	/*
2113 	 * A HBA is attached to the CAM layer.
2114 	 *
2115 	 * The CAM layer will then after a while start probing for devices on
2116 	 * the bus. The number of SIMs is limited to one.
2117 	 */
2118 
2119 	devq = cam_simq_alloc(1 /* maximum openings */ );
2120 	if (devq == NULL) {
2121 		return (ENOMEM);
2122 	}
2123 	sc->sc_sim = cam_sim_alloc
2124 	    (&umass_cam_action, &umass_cam_poll,
2125 	    DEVNAME_SIM,
2126 	    sc /* priv */ ,
2127 	    sc->sc_unit /* unit number */ ,
2128 #if (__FreeBSD_version >= 700037)
2129 	    &sc->sc_mtx /* mutex */ ,
2130 #endif
2131 	    1 /* maximum device openings */ ,
2132 	    0 /* maximum tagged device openings */ ,
2133 	    devq);
2134 
2135 	if (sc->sc_sim == NULL) {
2136 		cam_simq_free(devq);
2137 		return (ENOMEM);
2138 	}
2139 
2140 #if (__FreeBSD_version >= 700037)
2141 	mtx_lock(&sc->sc_mtx);
2142 #endif
2143 
2144 #if (__FreeBSD_version >= 700048)
2145 	if (xpt_bus_register(sc->sc_sim, sc->sc_dev, sc->sc_unit) != CAM_SUCCESS) {
2146 		mtx_unlock(&sc->sc_mtx);
2147 		return (ENOMEM);
2148 	}
2149 #else
2150 	if (xpt_bus_register(sc->sc_sim, sc->sc_unit) != CAM_SUCCESS) {
2151 #if (__FreeBSD_version >= 700037)
2152 		mtx_unlock(&sc->sc_mtx);
2153 #endif
2154 		return (ENOMEM);
2155 	}
2156 #endif
2157 
2158 #if (__FreeBSD_version >= 700037)
2159 	mtx_unlock(&sc->sc_mtx);
2160 #endif
2161 	return (0);
2162 }
2163 
2164 static void
2165 umass_cam_attach(struct umass_softc *sc)
2166 {
2167 #ifndef USB_DEBUG
2168 	if (bootverbose)
2169 #endif
2170 		printf("%s:%d:%d:%d: Attached to scbus%d\n",
2171 		    sc->sc_name, cam_sim_path(sc->sc_sim),
2172 		    sc->sc_unit, CAM_LUN_WILDCARD,
2173 		    cam_sim_path(sc->sc_sim));
2174 }
2175 
2176 /* umass_cam_detach
2177  *	detach from the CAM layer
2178  */
2179 
2180 static void
2181 umass_cam_detach_sim(struct umass_softc *sc)
2182 {
2183 	if (sc->sc_sim != NULL) {
2184 		if (xpt_bus_deregister(cam_sim_path(sc->sc_sim))) {
2185 			/* accessing the softc is not possible after this */
2186 			sc->sc_sim->softc = UMASS_GONE;
2187 			cam_sim_free(sc->sc_sim, /* free_devq */ TRUE);
2188 		} else {
2189 			panic("%s: CAM layer is busy\n",
2190 			    sc->sc_name);
2191 		}
2192 		sc->sc_sim = NULL;
2193 	}
2194 }
2195 
2196 /* umass_cam_action
2197  * 	CAM requests for action come through here
2198  */
2199 
2200 static void
2201 umass_cam_action(struct cam_sim *sim, union ccb *ccb)
2202 {
2203 	struct umass_softc *sc = (struct umass_softc *)sim->softc;
2204 
2205 	if (sc == UMASS_GONE ||
2206 	    (sc != NULL && !usbd_device_attached(sc->sc_udev))) {
2207 		ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2208 		xpt_done(ccb);
2209 		return;
2210 	}
2211 	if (sc) {
2212 #if (__FreeBSD_version < 700037)
2213 		mtx_lock(&sc->sc_mtx);
2214 #endif
2215 	}
2216 	/*
2217 	 * Verify, depending on the operation to perform, that we either got
2218 	 * a valid sc, because an existing target was referenced, or
2219 	 * otherwise the SIM is addressed.
2220 	 *
2221 	 * This avoids bombing out at a printf and does give the CAM layer some
2222 	 * sensible feedback on errors.
2223 	 */
2224 	switch (ccb->ccb_h.func_code) {
2225 	case XPT_SCSI_IO:
2226 	case XPT_RESET_DEV:
2227 	case XPT_GET_TRAN_SETTINGS:
2228 	case XPT_SET_TRAN_SETTINGS:
2229 	case XPT_CALC_GEOMETRY:
2230 		/* the opcodes requiring a target. These should never occur. */
2231 		if (sc == NULL) {
2232 			DPRINTF(sc, UDMASS_GEN, "%s:%d:%d:%d:func_code 0x%04x: "
2233 			    "Invalid target (target needed)\n",
2234 			    DEVNAME_SIM, cam_sim_path(sc->sc_sim),
2235 			    ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2236 			    ccb->ccb_h.func_code);
2237 
2238 			ccb->ccb_h.status = CAM_TID_INVALID;
2239 			xpt_done(ccb);
2240 			goto done;
2241 		}
2242 		break;
2243 	case XPT_PATH_INQ:
2244 	case XPT_NOOP:
2245 		/*
2246 		 * The opcodes sometimes aimed at a target (sc is valid),
2247 		 * sometimes aimed at the SIM (sc is invalid and target is
2248 		 * CAM_TARGET_WILDCARD)
2249 		 */
2250 		if ((sc == NULL) &&
2251 		    (ccb->ccb_h.target_id != CAM_TARGET_WILDCARD)) {
2252 			DPRINTF(sc, UDMASS_SCSI, "%s:%d:%d:%d:func_code 0x%04x: "
2253 			    "Invalid target (no wildcard)\n",
2254 			    DEVNAME_SIM, cam_sim_path(sc->sc_sim),
2255 			    ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2256 			    ccb->ccb_h.func_code);
2257 
2258 			ccb->ccb_h.status = CAM_TID_INVALID;
2259 			xpt_done(ccb);
2260 			goto done;
2261 		}
2262 		break;
2263 	default:
2264 		/* XXX Hm, we should check the input parameters */
2265 		break;
2266 	}
2267 
2268 	/* Perform the requested action */
2269 	switch (ccb->ccb_h.func_code) {
2270 	case XPT_SCSI_IO:
2271 		{
2272 			uint8_t *cmd;
2273 			uint8_t dir;
2274 
2275 			if (ccb->csio.ccb_h.flags & CAM_CDB_POINTER) {
2276 				cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_ptr);
2277 			} else {
2278 				cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_bytes);
2279 			}
2280 
2281 			DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_SCSI_IO: "
2282 			    "cmd: 0x%02x, flags: 0x%02x, "
2283 			    "%db cmd/%db data/%db sense\n",
2284 			    cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2285 			    ccb->ccb_h.target_lun, cmd[0],
2286 			    ccb->ccb_h.flags & CAM_DIR_MASK, ccb->csio.cdb_len,
2287 			    ccb->csio.dxfer_len, ccb->csio.sense_len);
2288 
2289 			if (sc->sc_transfer.ccb) {
2290 				DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_SCSI_IO: "
2291 				    "I/O in progress, deferring\n",
2292 				    cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2293 				    ccb->ccb_h.target_lun);
2294 				ccb->ccb_h.status = CAM_SCSI_BUSY;
2295 				xpt_done(ccb);
2296 				goto done;
2297 			}
2298 			switch (ccb->ccb_h.flags & CAM_DIR_MASK) {
2299 			case CAM_DIR_IN:
2300 				dir = DIR_IN;
2301 				break;
2302 			case CAM_DIR_OUT:
2303 				dir = DIR_OUT;
2304 				DIF(UDMASS_SCSI,
2305 				    umass_dump_buffer(sc, ccb->csio.data_ptr,
2306 				    ccb->csio.dxfer_len, 48));
2307 				break;
2308 			default:
2309 				dir = DIR_NONE;
2310 			}
2311 
2312 			ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
2313 
2314 			/*
2315 			 * sc->sc_transform will convert the command to the
2316 			 * command format needed by the specific command set
2317 			 * and return the converted command in
2318 			 * "sc->sc_transfer.cmd_data"
2319 			 */
2320 			if (umass_std_transform(sc, ccb, cmd, ccb->csio.cdb_len)) {
2321 
2322 				if (sc->sc_transfer.cmd_data[0] == INQUIRY) {
2323 					const char *pserial;
2324 
2325 					pserial = usb_get_serial(sc->sc_udev);
2326 
2327 					/*
2328 					 * Umass devices don't generally report their serial numbers
2329 					 * in the usual SCSI way.  Emulate it here.
2330 					 */
2331 					if ((sc->sc_transfer.cmd_data[1] & SI_EVPD) &&
2332 					    (sc->sc_transfer.cmd_data[2] == SVPD_UNIT_SERIAL_NUMBER) &&
2333 					    (pserial[0] != '\0')) {
2334 						struct scsi_vpd_unit_serial_number *vpd_serial;
2335 
2336 						vpd_serial = (struct scsi_vpd_unit_serial_number *)ccb->csio.data_ptr;
2337 						vpd_serial->length = strlen(pserial);
2338 						if (vpd_serial->length > sizeof(vpd_serial->serial_num))
2339 							vpd_serial->length = sizeof(vpd_serial->serial_num);
2340 						memcpy(vpd_serial->serial_num, pserial, vpd_serial->length);
2341 						ccb->csio.scsi_status = SCSI_STATUS_OK;
2342 						ccb->ccb_h.status = CAM_REQ_CMP;
2343 						xpt_done(ccb);
2344 						goto done;
2345 					}
2346 
2347 					/*
2348 					 * Handle EVPD inquiry for broken devices first
2349 					 * NO_INQUIRY also implies NO_INQUIRY_EVPD
2350 					 */
2351 					if ((sc->sc_quirks & (NO_INQUIRY_EVPD | NO_INQUIRY)) &&
2352 					    (sc->sc_transfer.cmd_data[1] & SI_EVPD)) {
2353 						struct scsi_sense_data *sense;
2354 
2355 						sense = &ccb->csio.sense_data;
2356 						bzero(sense, sizeof(*sense));
2357 						sense->error_code = SSD_CURRENT_ERROR;
2358 						sense->flags = SSD_KEY_ILLEGAL_REQUEST;
2359 						sense->add_sense_code = 0x24;
2360 						sense->extra_len = 10;
2361 						ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2362 						ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR |
2363 						    CAM_AUTOSNS_VALID;
2364 						xpt_done(ccb);
2365 						goto done;
2366 					}
2367 					/*
2368 					 * Return fake inquiry data for
2369 					 * broken devices
2370 					 */
2371 					if (sc->sc_quirks & NO_INQUIRY) {
2372 						memcpy(ccb->csio.data_ptr, &fake_inq_data,
2373 						    sizeof(fake_inq_data));
2374 						ccb->csio.scsi_status = SCSI_STATUS_OK;
2375 						ccb->ccb_h.status = CAM_REQ_CMP;
2376 						xpt_done(ccb);
2377 						goto done;
2378 					}
2379 					if (sc->sc_quirks & FORCE_SHORT_INQUIRY) {
2380 						ccb->csio.dxfer_len = SHORT_INQUIRY_LENGTH;
2381 					}
2382 				} else if (sc->sc_transfer.cmd_data[0] == SYNCHRONIZE_CACHE) {
2383 					if (sc->sc_quirks & NO_SYNCHRONIZE_CACHE) {
2384 						ccb->csio.scsi_status = SCSI_STATUS_OK;
2385 						ccb->ccb_h.status = CAM_REQ_CMP;
2386 						xpt_done(ccb);
2387 						goto done;
2388 					}
2389 				}
2390 				umass_command_start(sc, dir, ccb->csio.data_ptr,
2391 				    ccb->csio.dxfer_len,
2392 				    ccb->ccb_h.timeout,
2393 				    &umass_cam_cb, ccb);
2394 			}
2395 			break;
2396 		}
2397 	case XPT_PATH_INQ:
2398 		{
2399 			struct ccb_pathinq *cpi = &ccb->cpi;
2400 
2401 			DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_PATH_INQ:.\n",
2402 			    sc ? cam_sim_path(sc->sc_sim) : -1, ccb->ccb_h.target_id,
2403 			    ccb->ccb_h.target_lun);
2404 
2405 			/* host specific information */
2406 			cpi->version_num = 1;
2407 			cpi->hba_inquiry = 0;
2408 			cpi->target_sprt = 0;
2409 			cpi->hba_misc = PIM_NO_6_BYTE;
2410 			cpi->hba_eng_cnt = 0;
2411 			cpi->max_target = UMASS_SCSIID_MAX;	/* one target */
2412 			cpi->initiator_id = UMASS_SCSIID_HOST;
2413 			strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2414 			strlcpy(cpi->hba_vid, "USB SCSI", HBA_IDLEN);
2415 			strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2416 			cpi->unit_number = cam_sim_unit(sim);
2417 			cpi->bus_id = sc->sc_unit;
2418 #if (__FreeBSD_version >= 700025)
2419 			cpi->protocol = PROTO_SCSI;
2420 			cpi->protocol_version = SCSI_REV_2;
2421 			cpi->transport = XPORT_USB;
2422 			cpi->transport_version = 0;
2423 #endif
2424 			if (sc == NULL) {
2425 				cpi->base_transfer_speed = 0;
2426 				cpi->max_lun = 0;
2427 			} else {
2428 				if (sc->sc_quirks & FLOPPY_SPEED) {
2429 					cpi->base_transfer_speed =
2430 					    UMASS_FLOPPY_TRANSFER_SPEED;
2431 				} else {
2432 					switch (usbd_get_speed(sc->sc_udev)) {
2433 					case USB_SPEED_SUPER:
2434 						cpi->base_transfer_speed =
2435 						    UMASS_SUPER_TRANSFER_SPEED;
2436 						cpi->maxio = MAXPHYS;
2437 						break;
2438 					case USB_SPEED_HIGH:
2439 						cpi->base_transfer_speed =
2440 						    UMASS_HIGH_TRANSFER_SPEED;
2441 						break;
2442 					default:
2443 						cpi->base_transfer_speed =
2444 						    UMASS_FULL_TRANSFER_SPEED;
2445 						break;
2446 					}
2447 				}
2448 				cpi->max_lun = sc->sc_maxlun;
2449 			}
2450 
2451 			cpi->ccb_h.status = CAM_REQ_CMP;
2452 			xpt_done(ccb);
2453 			break;
2454 		}
2455 	case XPT_RESET_DEV:
2456 		{
2457 			DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_RESET_DEV:.\n",
2458 			    cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2459 			    ccb->ccb_h.target_lun);
2460 
2461 			umass_reset(sc);
2462 
2463 			ccb->ccb_h.status = CAM_REQ_CMP;
2464 			xpt_done(ccb);
2465 			break;
2466 		}
2467 	case XPT_GET_TRAN_SETTINGS:
2468 		{
2469 			struct ccb_trans_settings *cts = &ccb->cts;
2470 
2471 			DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_GET_TRAN_SETTINGS:.\n",
2472 			    cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2473 			    ccb->ccb_h.target_lun);
2474 
2475 #if (__FreeBSD_version >= 700025)
2476 			cts->protocol = PROTO_SCSI;
2477 			cts->protocol_version = SCSI_REV_2;
2478 			cts->transport = XPORT_USB;
2479 			cts->transport_version = 0;
2480 			cts->xport_specific.valid = 0;
2481 #else
2482 			cts->valid = 0;
2483 			cts->flags = 0;	/* no disconnection, tagging */
2484 #endif
2485 			ccb->ccb_h.status = CAM_REQ_CMP;
2486 			xpt_done(ccb);
2487 			break;
2488 		}
2489 	case XPT_SET_TRAN_SETTINGS:
2490 		{
2491 			DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_SET_TRAN_SETTINGS:.\n",
2492 			    cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2493 			    ccb->ccb_h.target_lun);
2494 
2495 			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2496 			xpt_done(ccb);
2497 			break;
2498 		}
2499 	case XPT_CALC_GEOMETRY:
2500 		{
2501 			cam_calc_geometry(&ccb->ccg, /* extended */ 1);
2502 			xpt_done(ccb);
2503 			break;
2504 		}
2505 	case XPT_NOOP:
2506 		{
2507 			DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:XPT_NOOP:.\n",
2508 			    sc ? cam_sim_path(sc->sc_sim) : -1, ccb->ccb_h.target_id,
2509 			    ccb->ccb_h.target_lun);
2510 
2511 			ccb->ccb_h.status = CAM_REQ_CMP;
2512 			xpt_done(ccb);
2513 			break;
2514 		}
2515 	default:
2516 		DPRINTF(sc, UDMASS_SCSI, "%d:%d:%d:func_code 0x%04x: "
2517 		    "Not implemented\n",
2518 		    sc ? cam_sim_path(sc->sc_sim) : -1, ccb->ccb_h.target_id,
2519 		    ccb->ccb_h.target_lun, ccb->ccb_h.func_code);
2520 
2521 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2522 		xpt_done(ccb);
2523 		break;
2524 	}
2525 
2526 done:
2527 #if (__FreeBSD_version < 700037)
2528 	if (sc) {
2529 		mtx_unlock(&sc->sc_mtx);
2530 	}
2531 #endif
2532 	return;
2533 }
2534 
2535 static void
2536 umass_cam_poll(struct cam_sim *sim)
2537 {
2538 	struct umass_softc *sc = (struct umass_softc *)sim->softc;
2539 
2540 	if (sc == UMASS_GONE)
2541 		return;
2542 
2543 	DPRINTF(sc, UDMASS_SCSI, "CAM poll\n");
2544 
2545 	usbd_transfer_poll(sc->sc_xfer, UMASS_T_MAX);
2546 }
2547 
2548 
2549 /* umass_cam_cb
2550  *	finalise a completed CAM command
2551  */
2552 
2553 static void
2554 umass_cam_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
2555     uint8_t status)
2556 {
2557 	ccb->csio.resid = residue;
2558 
2559 	switch (status) {
2560 	case STATUS_CMD_OK:
2561 		ccb->ccb_h.status = CAM_REQ_CMP;
2562 		if ((sc->sc_quirks & READ_CAPACITY_OFFBY1) &&
2563 		    (ccb->ccb_h.func_code == XPT_SCSI_IO) &&
2564 		    (ccb->csio.cdb_io.cdb_bytes[0] == READ_CAPACITY)) {
2565 			struct scsi_read_capacity_data *rcap;
2566 			uint32_t maxsector;
2567 
2568 			rcap = (void *)(ccb->csio.data_ptr);
2569 			maxsector = scsi_4btoul(rcap->addr) - 1;
2570 			scsi_ulto4b(maxsector, rcap->addr);
2571 		}
2572 		/*
2573 		 * We have to add SVPD_UNIT_SERIAL_NUMBER to the list
2574 		 * of pages supported by the device - otherwise, CAM
2575 		 * will never ask us for the serial number if the
2576 		 * device cannot handle that by itself.
2577 		 */
2578 		if (ccb->ccb_h.func_code == XPT_SCSI_IO &&
2579 		    sc->sc_transfer.cmd_data[0] == INQUIRY &&
2580 		    (sc->sc_transfer.cmd_data[1] & SI_EVPD) &&
2581 		    sc->sc_transfer.cmd_data[2] == SVPD_SUPPORTED_PAGE_LIST &&
2582 		    (usb_get_serial(sc->sc_udev)[0] != '\0')) {
2583 			struct ccb_scsiio *csio;
2584 			struct scsi_vpd_supported_page_list *page_list;
2585 
2586 			csio = &ccb->csio;
2587 			page_list = (struct scsi_vpd_supported_page_list *)csio->data_ptr;
2588 			if (page_list->length + 1 < SVPD_SUPPORTED_PAGES_SIZE) {
2589 				page_list->list[page_list->length] = SVPD_UNIT_SERIAL_NUMBER;
2590 				page_list->length++;
2591 			}
2592 		}
2593 		xpt_done(ccb);
2594 		break;
2595 
2596 	case STATUS_CMD_UNKNOWN:
2597 	case STATUS_CMD_FAILED:
2598 
2599 		/* fetch sense data */
2600 
2601 		/* the rest of the command was filled in at attach */
2602 		sc->cam_scsi_sense.length = ccb->csio.sense_len;
2603 
2604 		DPRINTF(sc, UDMASS_SCSI, "Fetching %d bytes of "
2605 		    "sense data\n", ccb->csio.sense_len);
2606 
2607 		if (umass_std_transform(sc, ccb, &sc->cam_scsi_sense.opcode,
2608 		    sizeof(sc->cam_scsi_sense))) {
2609 
2610 			if ((sc->sc_quirks & FORCE_SHORT_INQUIRY) &&
2611 			    (sc->sc_transfer.cmd_data[0] == INQUIRY)) {
2612 				ccb->csio.sense_len = SHORT_INQUIRY_LENGTH;
2613 			}
2614 			umass_command_start(sc, DIR_IN, &ccb->csio.sense_data.error_code,
2615 			    ccb->csio.sense_len, ccb->ccb_h.timeout,
2616 			    &umass_cam_sense_cb, ccb);
2617 		}
2618 		break;
2619 
2620 	default:
2621 		/*
2622 		 * The wire protocol failed and will hopefully have
2623 		 * recovered. We return an error to CAM and let CAM
2624 		 * retry the command if necessary.
2625 		 */
2626 		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2627 		xpt_done(ccb);
2628 		break;
2629 	}
2630 }
2631 
2632 /*
2633  * Finalise a completed autosense operation
2634  */
2635 static void
2636 umass_cam_sense_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
2637     uint8_t status)
2638 {
2639 	uint8_t *cmd;
2640 	uint8_t key;
2641 
2642 	switch (status) {
2643 	case STATUS_CMD_OK:
2644 	case STATUS_CMD_UNKNOWN:
2645 	case STATUS_CMD_FAILED:
2646 
2647 		if (ccb->csio.ccb_h.flags & CAM_CDB_POINTER) {
2648 			cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_ptr);
2649 		} else {
2650 			cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_bytes);
2651 		}
2652 
2653 		key = (ccb->csio.sense_data.flags & SSD_KEY);
2654 
2655 		/*
2656 		 * Getting sense data always succeeds (apart from wire
2657 		 * failures):
2658 		 */
2659 		if ((sc->sc_quirks & RS_NO_CLEAR_UA) &&
2660 		    (cmd[0] == INQUIRY) &&
2661 		    (key == SSD_KEY_UNIT_ATTENTION)) {
2662 			/*
2663 			 * Ignore unit attention errors in the case where
2664 			 * the Unit Attention state is not cleared on
2665 			 * REQUEST SENSE. They will appear again at the next
2666 			 * command.
2667 			 */
2668 			ccb->ccb_h.status = CAM_REQ_CMP;
2669 		} else if (key == SSD_KEY_NO_SENSE) {
2670 			/*
2671 			 * No problem after all (in the case of CBI without
2672 			 * CCI)
2673 			 */
2674 			ccb->ccb_h.status = CAM_REQ_CMP;
2675 		} else if ((sc->sc_quirks & RS_NO_CLEAR_UA) &&
2676 			    (cmd[0] == READ_CAPACITY) &&
2677 		    (key == SSD_KEY_UNIT_ATTENTION)) {
2678 			/*
2679 			 * Some devices do not clear the unit attention error
2680 			 * on request sense. We insert a test unit ready
2681 			 * command to make sure we clear the unit attention
2682 			 * condition, then allow the retry to proceed as
2683 			 * usual.
2684 			 */
2685 
2686 			ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2687 			    | CAM_AUTOSNS_VALID;
2688 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2689 
2690 #if 0
2691 			DELAY(300000);
2692 #endif
2693 			DPRINTF(sc, UDMASS_SCSI, "Doing a sneaky"
2694 			    "TEST_UNIT_READY\n");
2695 
2696 			/* the rest of the command was filled in at attach */
2697 
2698 			if (umass_std_transform(sc, ccb,
2699 			    &sc->cam_scsi_test_unit_ready.opcode,
2700 			    sizeof(sc->cam_scsi_test_unit_ready))) {
2701 				umass_command_start(sc, DIR_NONE, NULL, 0,
2702 				    ccb->ccb_h.timeout,
2703 				    &umass_cam_quirk_cb, ccb);
2704 			}
2705 			break;
2706 		} else {
2707 			ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2708 			    | CAM_AUTOSNS_VALID;
2709 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2710 		}
2711 		xpt_done(ccb);
2712 		break;
2713 
2714 	default:
2715 		DPRINTF(sc, UDMASS_SCSI, "Autosense failed, "
2716 		    "status %d\n", status);
2717 		ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
2718 		xpt_done(ccb);
2719 	}
2720 }
2721 
2722 /*
2723  * This completion code just handles the fact that we sent a test-unit-ready
2724  * after having previously failed a READ CAPACITY with CHECK_COND.  Even
2725  * though this command succeeded, we have to tell CAM to retry.
2726  */
2727 static void
2728 umass_cam_quirk_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
2729     uint8_t status)
2730 {
2731 	DPRINTF(sc, UDMASS_SCSI, "Test unit ready "
2732 	    "returned status %d\n", status);
2733 
2734 	ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2735 	    | CAM_AUTOSNS_VALID;
2736 	ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2737 	xpt_done(ccb);
2738 }
2739 
2740 /*
2741  * SCSI specific functions
2742  */
2743 
2744 static uint8_t
2745 umass_scsi_transform(struct umass_softc *sc, uint8_t *cmd_ptr,
2746     uint8_t cmd_len)
2747 {
2748 	if ((cmd_len == 0) ||
2749 	    (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2750 		DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2751 		    "length: %d bytes\n", cmd_len);
2752 		return (0);		/* failure */
2753 	}
2754 	sc->sc_transfer.cmd_len = cmd_len;
2755 
2756 	switch (cmd_ptr[0]) {
2757 	case TEST_UNIT_READY:
2758 		if (sc->sc_quirks & NO_TEST_UNIT_READY) {
2759 			DPRINTF(sc, UDMASS_SCSI, "Converted TEST_UNIT_READY "
2760 			    "to START_UNIT\n");
2761 			bzero(sc->sc_transfer.cmd_data, cmd_len);
2762 			sc->sc_transfer.cmd_data[0] = START_STOP_UNIT;
2763 			sc->sc_transfer.cmd_data[4] = SSS_START;
2764 			return (1);
2765 		}
2766 		break;
2767 
2768 	case INQUIRY:
2769 		/*
2770 		 * some drives wedge when asked for full inquiry
2771 		 * information.
2772 		 */
2773 		if (sc->sc_quirks & FORCE_SHORT_INQUIRY) {
2774 			bcopy(cmd_ptr, sc->sc_transfer.cmd_data, cmd_len);
2775 			sc->sc_transfer.cmd_data[4] = SHORT_INQUIRY_LENGTH;
2776 			return (1);
2777 		}
2778 		break;
2779 	}
2780 
2781 	bcopy(cmd_ptr, sc->sc_transfer.cmd_data, cmd_len);
2782 	return (1);
2783 }
2784 
2785 static uint8_t
2786 umass_rbc_transform(struct umass_softc *sc, uint8_t *cmd_ptr, uint8_t cmd_len)
2787 {
2788 	if ((cmd_len == 0) ||
2789 	    (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2790 		DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2791 		    "length: %d bytes\n", cmd_len);
2792 		return (0);		/* failure */
2793 	}
2794 	switch (cmd_ptr[0]) {
2795 		/* these commands are defined in RBC: */
2796 	case READ_10:
2797 	case READ_CAPACITY:
2798 	case START_STOP_UNIT:
2799 	case SYNCHRONIZE_CACHE:
2800 	case WRITE_10:
2801 	case 0x2f:			/* VERIFY_10 is absent from
2802 					 * scsi_all.h??? */
2803 	case INQUIRY:
2804 	case MODE_SELECT_10:
2805 	case MODE_SENSE_10:
2806 	case TEST_UNIT_READY:
2807 	case WRITE_BUFFER:
2808 		/*
2809 		 * The following commands are not listed in my copy of the
2810 		 * RBC specs. CAM however seems to want those, and at least
2811 		 * the Sony DSC device appears to support those as well
2812 		 */
2813 	case REQUEST_SENSE:
2814 	case PREVENT_ALLOW:
2815 
2816 		bcopy(cmd_ptr, sc->sc_transfer.cmd_data, cmd_len);
2817 
2818 		if ((sc->sc_quirks & RBC_PAD_TO_12) && (cmd_len < 12)) {
2819 			bzero(sc->sc_transfer.cmd_data + cmd_len, 12 - cmd_len);
2820 			cmd_len = 12;
2821 		}
2822 		sc->sc_transfer.cmd_len = cmd_len;
2823 		return (1);		/* sucess */
2824 
2825 		/* All other commands are not legal in RBC */
2826 	default:
2827 		DPRINTF(sc, UDMASS_SCSI, "Unsupported RBC "
2828 		    "command 0x%02x\n", cmd_ptr[0]);
2829 		return (0);		/* failure */
2830 	}
2831 }
2832 
2833 static uint8_t
2834 umass_ufi_transform(struct umass_softc *sc, uint8_t *cmd_ptr,
2835     uint8_t cmd_len)
2836 {
2837 	if ((cmd_len == 0) ||
2838 	    (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2839 		DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2840 		    "length: %d bytes\n", cmd_len);
2841 		return (0);		/* failure */
2842 	}
2843 	/* An UFI command is always 12 bytes in length */
2844 	sc->sc_transfer.cmd_len = UFI_COMMAND_LENGTH;
2845 
2846 	/* Zero the command data */
2847 	bzero(sc->sc_transfer.cmd_data, UFI_COMMAND_LENGTH);
2848 
2849 	switch (cmd_ptr[0]) {
2850 		/*
2851 		 * Commands of which the format has been verified. They
2852 		 * should work. Copy the command into the (zeroed out)
2853 		 * destination buffer.
2854 		 */
2855 	case TEST_UNIT_READY:
2856 		if (sc->sc_quirks & NO_TEST_UNIT_READY) {
2857 			/*
2858 			 * Some devices do not support this command. Start
2859 			 * Stop Unit should give the same results
2860 			 */
2861 			DPRINTF(sc, UDMASS_UFI, "Converted TEST_UNIT_READY "
2862 			    "to START_UNIT\n");
2863 
2864 			sc->sc_transfer.cmd_data[0] = START_STOP_UNIT;
2865 			sc->sc_transfer.cmd_data[4] = SSS_START;
2866 			return (1);
2867 		}
2868 		break;
2869 
2870 	case REZERO_UNIT:
2871 	case REQUEST_SENSE:
2872 	case FORMAT_UNIT:
2873 	case INQUIRY:
2874 	case START_STOP_UNIT:
2875 	case SEND_DIAGNOSTIC:
2876 	case PREVENT_ALLOW:
2877 	case READ_CAPACITY:
2878 	case READ_10:
2879 	case WRITE_10:
2880 	case POSITION_TO_ELEMENT:	/* SEEK_10 */
2881 	case WRITE_AND_VERIFY:
2882 	case VERIFY:
2883 	case MODE_SELECT_10:
2884 	case MODE_SENSE_10:
2885 	case READ_12:
2886 	case WRITE_12:
2887 	case READ_FORMAT_CAPACITIES:
2888 		break;
2889 
2890 		/*
2891 		 * SYNCHRONIZE_CACHE isn't supported by UFI, nor should it be
2892 		 * required for UFI devices, so it is appropriate to fake
2893 		 * success.
2894 		 */
2895 	case SYNCHRONIZE_CACHE:
2896 		return (2);
2897 
2898 	default:
2899 		DPRINTF(sc, UDMASS_SCSI, "Unsupported UFI "
2900 		    "command 0x%02x\n", cmd_ptr[0]);
2901 		return (0);		/* failure */
2902 	}
2903 
2904 	bcopy(cmd_ptr, sc->sc_transfer.cmd_data, cmd_len);
2905 	return (1);			/* success */
2906 }
2907 
2908 /*
2909  * 8070i (ATAPI) specific functions
2910  */
2911 static uint8_t
2912 umass_atapi_transform(struct umass_softc *sc, uint8_t *cmd_ptr,
2913     uint8_t cmd_len)
2914 {
2915 	if ((cmd_len == 0) ||
2916 	    (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2917 		DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2918 		    "length: %d bytes\n", cmd_len);
2919 		return (0);		/* failure */
2920 	}
2921 	/* An ATAPI command is always 12 bytes in length. */
2922 	sc->sc_transfer.cmd_len = ATAPI_COMMAND_LENGTH;
2923 
2924 	/* Zero the command data */
2925 	bzero(sc->sc_transfer.cmd_data, ATAPI_COMMAND_LENGTH);
2926 
2927 	switch (cmd_ptr[0]) {
2928 		/*
2929 		 * Commands of which the format has been verified. They
2930 		 * should work. Copy the command into the destination
2931 		 * buffer.
2932 		 */
2933 	case INQUIRY:
2934 		/*
2935 		 * some drives wedge when asked for full inquiry
2936 		 * information.
2937 		 */
2938 		if (sc->sc_quirks & FORCE_SHORT_INQUIRY) {
2939 			bcopy(cmd_ptr, sc->sc_transfer.cmd_data, cmd_len);
2940 
2941 			sc->sc_transfer.cmd_data[4] = SHORT_INQUIRY_LENGTH;
2942 			return (1);
2943 		}
2944 		break;
2945 
2946 	case TEST_UNIT_READY:
2947 		if (sc->sc_quirks & NO_TEST_UNIT_READY) {
2948 			DPRINTF(sc, UDMASS_SCSI, "Converted TEST_UNIT_READY "
2949 			    "to START_UNIT\n");
2950 			sc->sc_transfer.cmd_data[0] = START_STOP_UNIT;
2951 			sc->sc_transfer.cmd_data[4] = SSS_START;
2952 			return (1);
2953 		}
2954 		break;
2955 
2956 	case REZERO_UNIT:
2957 	case REQUEST_SENSE:
2958 	case START_STOP_UNIT:
2959 	case SEND_DIAGNOSTIC:
2960 	case PREVENT_ALLOW:
2961 	case READ_CAPACITY:
2962 	case READ_10:
2963 	case WRITE_10:
2964 	case POSITION_TO_ELEMENT:	/* SEEK_10 */
2965 	case SYNCHRONIZE_CACHE:
2966 	case MODE_SELECT_10:
2967 	case MODE_SENSE_10:
2968 	case READ_BUFFER:
2969 	case 0x42:			/* READ_SUBCHANNEL */
2970 	case 0x43:			/* READ_TOC */
2971 	case 0x44:			/* READ_HEADER */
2972 	case 0x47:			/* PLAY_MSF (Play Minute/Second/Frame) */
2973 	case 0x48:			/* PLAY_TRACK */
2974 	case 0x49:			/* PLAY_TRACK_REL */
2975 	case 0x4b:			/* PAUSE */
2976 	case 0x51:			/* READ_DISK_INFO */
2977 	case 0x52:			/* READ_TRACK_INFO */
2978 	case 0x54:			/* SEND_OPC */
2979 	case 0x59:			/* READ_MASTER_CUE */
2980 	case 0x5b:			/* CLOSE_TR_SESSION */
2981 	case 0x5c:			/* READ_BUFFER_CAP */
2982 	case 0x5d:			/* SEND_CUE_SHEET */
2983 	case 0xa1:			/* BLANK */
2984 	case 0xa5:			/* PLAY_12 */
2985 	case 0xa6:			/* EXCHANGE_MEDIUM */
2986 	case 0xad:			/* READ_DVD_STRUCTURE */
2987 	case 0xbb:			/* SET_CD_SPEED */
2988 	case 0xe5:			/* READ_TRACK_INFO_PHILIPS */
2989 		break;
2990 
2991 	case READ_12:
2992 	case WRITE_12:
2993 	default:
2994 		DPRINTF(sc, UDMASS_SCSI, "Unsupported ATAPI "
2995 		    "command 0x%02x - trying anyway\n",
2996 		    cmd_ptr[0]);
2997 		break;
2998 	}
2999 
3000 	bcopy(cmd_ptr, sc->sc_transfer.cmd_data, cmd_len);
3001 	return (1);			/* success */
3002 }
3003 
3004 static uint8_t
3005 umass_no_transform(struct umass_softc *sc, uint8_t *cmd,
3006     uint8_t cmdlen)
3007 {
3008 	return (0);			/* failure */
3009 }
3010 
3011 static uint8_t
3012 umass_std_transform(struct umass_softc *sc, union ccb *ccb,
3013     uint8_t *cmd, uint8_t cmdlen)
3014 {
3015 	uint8_t retval;
3016 
3017 	retval = (sc->sc_transform) (sc, cmd, cmdlen);
3018 
3019 	if (retval == 2) {
3020 		ccb->ccb_h.status = CAM_REQ_CMP;
3021 		xpt_done(ccb);
3022 		return (0);
3023 	} else if (retval == 0) {
3024 		ccb->ccb_h.status = CAM_REQ_INVALID;
3025 		xpt_done(ccb);
3026 		return (0);
3027 	}
3028 	/* Command should be executed */
3029 	return (1);
3030 }
3031 
3032 #ifdef USB_DEBUG
3033 static void
3034 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
3035 {
3036 	uint8_t *c = cbw->CBWCDB;
3037 
3038 	uint32_t dlen = UGETDW(cbw->dCBWDataTransferLength);
3039 	uint32_t tag = UGETDW(cbw->dCBWTag);
3040 
3041 	uint8_t clen = cbw->bCDBLength;
3042 	uint8_t flags = cbw->bCBWFlags;
3043 	uint8_t lun = cbw->bCBWLUN;
3044 
3045 	DPRINTF(sc, UDMASS_BBB, "CBW %d: cmd = %db "
3046 	    "(0x%02x%02x%02x%02x%02x%02x%s), "
3047 	    "data = %db, lun = %d, dir = %s\n",
3048 	    tag, clen,
3049 	    c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6 ? "..." : ""),
3050 	    dlen, lun, (flags == CBWFLAGS_IN ? "in" :
3051 	    (flags == CBWFLAGS_OUT ? "out" : "<invalid>")));
3052 }
3053 
3054 static void
3055 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
3056 {
3057 	uint32_t sig = UGETDW(csw->dCSWSignature);
3058 	uint32_t tag = UGETDW(csw->dCSWTag);
3059 	uint32_t res = UGETDW(csw->dCSWDataResidue);
3060 	uint8_t status = csw->bCSWStatus;
3061 
3062 	DPRINTF(sc, UDMASS_BBB, "CSW %d: sig = 0x%08x (%s), tag = 0x%08x, "
3063 	    "res = %d, status = 0x%02x (%s)\n",
3064 	    tag, sig, (sig == CSWSIGNATURE ? "valid" : "invalid"),
3065 	    tag, res,
3066 	    status, (status == CSWSTATUS_GOOD ? "good" :
3067 	    (status == CSWSTATUS_FAILED ? "failed" :
3068 	    (status == CSWSTATUS_PHASE ? "phase" : "<invalid>"))));
3069 }
3070 
3071 static void
3072 umass_cbi_dump_cmd(struct umass_softc *sc, void *cmd, uint8_t cmdlen)
3073 {
3074 	uint8_t *c = cmd;
3075 	uint8_t dir = sc->sc_transfer.dir;
3076 
3077 	DPRINTF(sc, UDMASS_BBB, "cmd = %db "
3078 	    "(0x%02x%02x%02x%02x%02x%02x%s), "
3079 	    "data = %db, dir = %s\n",
3080 	    cmdlen,
3081 	    c[0], c[1], c[2], c[3], c[4], c[5], (cmdlen > 6 ? "..." : ""),
3082 	    sc->sc_transfer.data_len,
3083 	    (dir == DIR_IN ? "in" :
3084 	    (dir == DIR_OUT ? "out" :
3085 	    (dir == DIR_NONE ? "no data phase" : "<invalid>"))));
3086 }
3087 
3088 static void
3089 umass_dump_buffer(struct umass_softc *sc, uint8_t *buffer, uint32_t buflen,
3090     uint32_t printlen)
3091 {
3092 	uint32_t i, j;
3093 	char s1[40];
3094 	char s2[40];
3095 	char s3[5];
3096 
3097 	s1[0] = '\0';
3098 	s3[0] = '\0';
3099 
3100 	sprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
3101 	for (i = 0; (i < buflen) && (i < printlen); i++) {
3102 		j = i % 16;
3103 		if (j == 0 && i != 0) {
3104 			DPRINTF(sc, UDMASS_GEN, "0x %s%s\n",
3105 			    s1, s2);
3106 			s2[0] = '\0';
3107 		}
3108 		sprintf(&s1[j * 2], "%02x", buffer[i] & 0xff);
3109 	}
3110 	if (buflen > printlen)
3111 		sprintf(s3, " ...");
3112 	DPRINTF(sc, UDMASS_GEN, "0x %s%s%s\n",
3113 	    s1, s2, s3);
3114 }
3115 
3116 #endif
3117