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