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