3 * Copyright (C) 2008 coresystems GmbH
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <usb/usbmsc.h>
33 #include <usb/usbdisk.h>
36 msc_subclass_rbc
= 0x1,
37 msc_subclass_mmc2
= 0x2,
38 msc_subclass_qic157
= 0x3,
39 msc_subclass_ufi
= 0x4,
40 msc_subclass_sff8070i
= 0x5,
41 msc_subclass_scsitrans
= 0x6
44 static const char *msc_subclass_strings
[7] = {
54 msc_proto_cbi_wcomp
= 0x0,
55 msc_proto_cbi_wocomp
= 0x1,
56 msc_proto_bulk_only
= 0x50
58 static const char *msc_protocol_strings
[0x51] = {
59 "Control/Bulk/Interrupt protocol (with command completion interrupt)",
60 "Control/Bulk/Interrupt protocol (with no command completion interrupt)",
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
70 usb_msc_create_disk(usbdev_t
*dev
)
74 MSC_INST(dev
)->usbdisk_created
= 1;
79 usb_msc_remove_disk(usbdev_t
*dev
)
81 if (MSC_INST(dev
)->usbdisk_created
&& usbdisk_remove
) {
83 MSC_INST(dev
)->usbdisk_created
= 0;
88 usb_msc_destroy(usbdev_t
*dev
)
91 usb_msc_remove_disk(dev
);
97 const int DEV_RESET
= 0xff;
98 const int GET_MAX_LUN
= 0xfe;
99 /* Many USB3 devices do not work with large transfer requests.
100 * Limit the request size to 64KB chunks to ensure maximum compatibility. */
101 const int MAX_CHUNK_BYTES
= 1024 * 64;
103 const unsigned int cbw_signature
= 0x43425355;
104 const unsigned int csw_signature
= 0x53425355;
107 unsigned int dCBWSignature
;
108 unsigned int dCBWTag
;
109 unsigned int dCBWDataTransferLength
;
110 unsigned char bmCBWFlags
;
111 unsigned long bCBWLUN
:4;
113 unsigned long bCBWCBLength
:5;
115 unsigned char CBWCB
[31 - 15];
119 unsigned int dCSWSignature
;
120 unsigned int dCSWTag
;
121 unsigned int dCSWDataResidue
;
122 unsigned char bCSWStatus
;
127 * MSC commands can be
129 * fail with proper response or
130 * fail totally, which results in detaching of the USB device
131 * and immediate cleanup of the usbdev_t structure.
132 * In the latter case the caller has to make sure, that he won't
133 * use the device any more.
135 MSC_COMMAND_OK
= 0, MSC_COMMAND_FAIL
, MSC_COMMAND_DETACHED
139 request_sense(usbdev_t
*dev
);
141 request_sense_no_media(usbdev_t
*dev
);
143 usb_msc_poll(usbdev_t
*dev
);
146 reset_transport(usbdev_t
*dev
)
149 memset(&dr
, 0, sizeof(dr
));
150 dr
.bmRequestType
= 0;
151 dr
.data_dir
= host_to_device
;
153 dr
.req_type
= class_type
;
154 dr
.req_recp
= iface_recp
;
156 dr
.bRequest
= DEV_RESET
;
161 if (MSC_INST(dev
)->quirks
& USB_MSC_QUIRK_NO_RESET
)
162 return MSC_COMMAND_FAIL
;
164 /* if any of these fails, detach device, as we are lost */
165 if (dev
->controller
->control(dev
, OUT
, sizeof(dr
), &dr
, 0, 0) < 0 ||
166 clear_stall(MSC_INST(dev
)->bulk_in
) ||
167 clear_stall(MSC_INST(dev
)->bulk_out
)) {
168 usb_debug("Detaching unresponsive device.\n");
169 usb_detach_device(dev
->controller
, dev
->address
);
170 return MSC_COMMAND_DETACHED
;
172 /* return fail as we are only called in case of failure */
173 return MSC_COMMAND_FAIL
;
176 /* device may stall this command, so beware! */
178 initialize_luns(usbdev_t
*dev
)
180 usbmsc_inst_t
*msc
= MSC_INST(dev
);
182 dr
.bmRequestType
= 0;
183 dr
.data_dir
= device_to_host
;
185 dr
.req_type
= class_type
;
186 dr
.req_recp
= iface_recp
;
188 dr
.bRequest
= GET_MAX_LUN
;
192 if (MSC_INST(dev
)->quirks
& USB_MSC_QUIRK_NO_LUNS
||
193 dev
->controller
->control(dev
, IN
, sizeof(dr
), &dr
,
194 sizeof(msc
->num_luns
), &msc
->num_luns
) < 0)
195 msc
->num_luns
= 0; /* assume only 1 lun if req fails */
196 msc
->num_luns
++; /* Get Max LUN returns number of last LUN */
203 wrap_cbw(cbw_t
*cbw
, int datalen
, cbw_direction dir
, const u8
*cmd
,
206 memset(cbw
, 0, sizeof(cbw_t
));
208 /* commands are typically shorter, but we don't want overflows */
209 if (cmdlen
> sizeof(cbw
->CBWCB
)) {
210 cmdlen
= sizeof(cbw
->CBWCB
);
213 cbw
->dCBWSignature
= cbw_signature
;
214 cbw
->dCBWTag
= ++tag
;
217 cbw
->dCBWDataTransferLength
= datalen
;
218 cbw
->bmCBWFlags
= dir
;
219 memcpy(cbw
->CBWCB
, cmd
, cmdlen
);
220 cbw
->bCBWCBLength
= cmdlen
;
224 get_csw(endpoint_t
*ep
, csw_t
*csw
)
226 hci_t
*ctrlr
= ep
->dev
->controller
;
227 int ret
= ctrlr
->bulk(ep
, sizeof(csw_t
), (u8
*) csw
, 1);
229 /* Some broken sticks send a zero-length packet at the end of their data
230 transfer which would show up here. Skip it to get the actual CSW. */
232 ret
= ctrlr
->bulk(ep
, sizeof(csw_t
), (u8
*) csw
, 1);
236 ret
= ctrlr
->bulk(ep
, sizeof(csw_t
), (u8
*) csw
, 1);
238 return reset_transport(ep
->dev
);
240 if (ret
!= sizeof(csw_t
) || csw
->dCSWTag
!= tag
||
241 csw
->dCSWSignature
!= csw_signature
) {
242 usb_debug("MSC: received malformed CSW\n");
243 return reset_transport(ep
->dev
);
245 return MSC_COMMAND_OK
;
249 execute_command(usbdev_t
*dev
, cbw_direction dir
, const u8
*cb
, int cblen
,
250 u8
*buf
, int buflen
, int residue_ok
)
255 int always_succeed
= 0;
256 if ((cb
[0] == 0x1b) && (cb
[4] == 1)) { //start command, always succeed
259 wrap_cbw(&cbw
, buflen
, dir
, cb
, cblen
, MSC_INST(dev
)->lun
);
260 if (dev
->controller
->
261 bulk(MSC_INST(dev
)->bulk_out
, sizeof(cbw
), (u8
*) &cbw
, 0) < 0) {
262 return reset_transport(dev
);
265 if (dir
== cbw_direction_data_in
) {
266 if (dev
->controller
->
267 bulk(MSC_INST(dev
)->bulk_in
, buflen
, buf
, 0) < 0)
268 clear_stall(MSC_INST(dev
)->bulk_in
);
270 if (dev
->controller
->
271 bulk(MSC_INST(dev
)->bulk_out
, buflen
, buf
, 0) < 0)
272 clear_stall(MSC_INST(dev
)->bulk_out
);
275 int ret
= get_csw(MSC_INST(dev
)->bulk_in
, &csw
);
278 } else if (always_succeed
== 1) {
279 /* return success, regardless of message */
280 return MSC_COMMAND_OK
;
281 } else if (csw
.bCSWStatus
== 2) {
282 /* phase error, reset transport */
283 return reset_transport(dev
);
284 } else if (csw
.bCSWStatus
== 0) {
285 if ((csw
.dCSWDataResidue
== 0) || residue_ok
)
287 return MSC_COMMAND_OK
;
289 /* missed some bytes */
290 return MSC_COMMAND_FAIL
;
293 /* requesting sense failed, that's bad */
294 return MSC_COMMAND_FAIL
;
296 /* If command was TEST UNIT READY determine if the
297 * device is of removable type indicating no media
299 return request_sense_no_media(dev
);
300 /* error "check condition" or reserved error */
301 ret
= request_sense(dev
);
302 /* return fail or the status of request_sense if it's worse */
303 return ret
? ret
: MSC_COMMAND_FAIL
;
308 unsigned char command
; //0
309 unsigned char res1
; //1
310 unsigned int block
; //2-5
311 unsigned char res2
; //6
312 unsigned short numblocks
; //7-8
313 unsigned char control
; //9 - the block is 10 bytes long
314 } __packed cmdblock_t
;
317 unsigned char command
; //0
318 unsigned char res1
; //1
319 unsigned char res2
; //2
320 unsigned char res3
; //3
323 unsigned long start
:1; // for START STOP UNIT
326 unsigned char length
; // for REQUEST SENSE
328 unsigned char control
; //5
329 } __packed cmdblock6_t
;
332 * Like readwrite_blocks, but for soft-sectors of 512b size. Converts the
333 * start and count from 512b units.
334 * Start and count must be aligned so that they match the native
337 * @param dev device to access
338 * @param start first sector to access
339 * @param n number of sectors to access
340 * @param dir direction of access: cbw_direction_data_in == read, cbw_direction_data_out == write
341 * @param buf buffer to read into or write from. Must be at least n*512 bytes
342 * @return 0 on success, 1 on failure
345 readwrite_blocks_512(usbdev_t
*dev
, int start
, int n
,
346 cbw_direction dir
, u8
*buf
)
348 int blocksize_divider
= MSC_INST(dev
)->blocksize
/ 512;
349 return readwrite_blocks(dev
, start
/ blocksize_divider
,
350 n
/ blocksize_divider
, dir
, buf
);
354 * Reads or writes a number of sequential blocks on a USB storage device.
355 * As it uses the READ(10) SCSI-2 command, it's limited to storage devices
356 * of at most 2TB. It assumes sectors of 512 bytes.
358 * @param dev device to access
359 * @param start first sector to access
360 * @param n number of sectors to access
361 * @param dir direction of access: cbw_direction_data_in == read, cbw_direction_data_out == write
362 * @param buf buffer to read into or write from. Must be at least n*sectorsize bytes
363 * @return 0 on success, 1 on failure
366 readwrite_chunk(usbdev_t
*dev
, int start
, int n
, cbw_direction dir
, u8
*buf
)
369 memset(&cb
, 0, sizeof(cb
));
370 if (dir
== cbw_direction_data_in
) {
377 cb
.block
= htonl(start
);
378 cb
.numblocks
= htonw(n
);
380 return execute_command(dev
, dir
, (u8
*) &cb
, sizeof(cb
), buf
,
381 n
* MSC_INST(dev
)->blocksize
, 0)
382 != MSC_COMMAND_OK
? 1 : 0;
386 * Reads or writes a number of sequential blocks on a USB storage device
387 * that is split into MAX_CHUNK_BYTES size requests.
389 * As it uses the READ(10) SCSI-2 command, it's limited to storage devices
390 * of at most 2TB. It assumes sectors of 512 bytes.
392 * @param dev device to access
393 * @param start first sector to access
394 * @param n number of sectors to access
395 * @param dir direction of access: cbw_direction_data_in == read,
396 * cbw_direction_data_out == write
397 * @param buf buffer to read into or write from.
398 * Must be at least n*sectorsize bytes
399 * @return 0 on success, 1 on failure
402 readwrite_blocks(usbdev_t
*dev
, int start
, int n
, cbw_direction dir
, u8
*buf
)
404 int chunk_size
= MAX_CHUNK_BYTES
/ MSC_INST(dev
)->blocksize
;
407 /* Read as many full chunks as needed. */
408 for (chunk
= 0; chunk
< (n
/ chunk_size
); chunk
++) {
409 if (readwrite_chunk(dev
, start
+ (chunk
* chunk_size
),
411 buf
+ (chunk
* MAX_CHUNK_BYTES
))
416 /* Read any remaining partial chunk at the end. */
417 if (n
% chunk_size
) {
418 if (readwrite_chunk(dev
, start
+ (chunk
* chunk_size
),
420 buf
+ (chunk
* MAX_CHUNK_BYTES
))
428 /* Only request it, we don't interpret it.
429 On certain errors, that's necessary to get devices out of
430 a special state called "Contingent Allegiance Condition" */
432 request_sense(usbdev_t
*dev
)
436 memset(&cb
, 0, sizeof(cb
));
438 cb
.length
= sizeof(buf
);
440 return execute_command(dev
, cbw_direction_data_in
, (u8
*) &cb
,
441 sizeof(cb
), buf
, sizeof(buf
), 1);
444 static int request_sense_no_media(usbdev_t
*dev
)
449 memset(&cb
, 0, sizeof(cb
));
451 cb
.length
= sizeof(buf
);
453 ret
= execute_command(dev
, cbw_direction_data_in
, (u8
*) &cb
,
454 sizeof(cb
), buf
, sizeof(buf
), 1);
459 /* Check if sense key is set to NOT READY. */
460 if ((buf
[2] & 0xf) != 2)
461 return MSC_COMMAND_FAIL
;
463 /* Check if additional sense code is 0x3a. */
465 return MSC_COMMAND_FAIL
;
467 /* No media is present. Return MSC_COMMAND_OK while marking the disk
469 usb_debug("Empty media found.\n");
470 MSC_INST(dev
)->ready
= USB_MSC_NOT_READY
;
471 return MSC_COMMAND_OK
;
475 test_unit_ready(usbdev_t
*dev
)
478 memset(&cb
, 0, sizeof(cb
)); // full initialization for T-U-R
479 return execute_command(dev
, cbw_direction_data_out
, (u8
*) &cb
,
480 sizeof(cb
), 0, 0, 0);
484 spin_up(usbdev_t
*dev
)
487 memset(&cb
, 0, sizeof(cb
));
490 return execute_command(dev
, cbw_direction_data_out
, (u8
*) &cb
,
491 sizeof(cb
), 0, 0, 0);
495 read_capacity(usbdev_t
*dev
)
498 memset(&cb
, 0, sizeof(cb
));
499 cb
.command
= 0x25; // read capacity
502 usb_debug("Reading capacity of mass storage device.\n");
504 while (count
++ < 20) {
505 switch (ret
= execute_command
506 (dev
, cbw_direction_data_in
, (u8
*) &cb
,
507 sizeof(cb
), (u8
*)buf
, 8, 0)) {
510 case MSC_COMMAND_FAIL
:
512 default: /* if it's worse return */
518 // still not successful, assume 2tb in 512byte sectors, which is just the same garbage as any other number, but probably more usable.
519 usb_debug(" assuming 2 TB with 512-byte sectors as READ CAPACITY didn't answer.\n");
520 MSC_INST(dev
)->numblocks
= 0xffffffff;
521 MSC_INST(dev
)->blocksize
= 512;
523 MSC_INST(dev
)->numblocks
= ntohl(buf
[0]) + 1;
524 MSC_INST(dev
)->blocksize
= ntohl(buf
[1]);
526 usb_debug(" %d %d-byte sectors (%d MB)\n", MSC_INST(dev
)->numblocks
,
527 MSC_INST(dev
)->blocksize
,
528 /* round down high block counts to avoid integer overflow */
529 MSC_INST(dev
)->numblocks
> 1000000
530 ? (MSC_INST(dev
)->numblocks
/ 1000) * MSC_INST(dev
)->blocksize
/ 1000 :
531 MSC_INST(dev
)->numblocks
* MSC_INST(dev
)->blocksize
/ 1000 / 1000);
532 return MSC_COMMAND_OK
;
536 usb_msc_test_unit_ready(usbdev_t
*dev
)
539 time_t start_time_secs
;
541 /* SCSI/ATA specs say we have to wait up to 30s, but most devices
542 * are ready much sooner. Use a 5 sec timeout to better accommodate
543 * devices which fail to respond. */
544 const int timeout_secs
= 5;
546 usb_debug(" Waiting for device to become ready...");
548 /* Initially mark the device ready. */
549 MSC_INST(dev
)->ready
= USB_MSC_READY
;
550 gettimeofday(&tv
, NULL
);
551 start_time_secs
= tv
.tv_sec
;
553 while (tv
.tv_sec
- start_time_secs
< timeout_secs
) {
554 switch (test_unit_ready(dev
)) {
557 case MSC_COMMAND_FAIL
:
560 gettimeofday(&tv
, NULL
);
563 /* Device detached, return immediately */
564 return USB_MSC_DETACHED
;
568 if (!(tv
.tv_sec
- start_time_secs
< timeout_secs
)) {
569 usb_debug("timeout. Device not ready.\n");
570 MSC_INST(dev
)->ready
= USB_MSC_NOT_READY
;
573 /* Don't bother spinning up the storage device if the device is not
574 * ready. This can happen when empty card readers are present.
575 * Polling will pick it back up if readiness changes. */
576 if (!MSC_INST(dev
)->ready
)
577 return MSC_INST(dev
)->ready
;
581 usb_debug(" spin up");
582 for (i
= 0; i
< 30; i
++) {
584 switch (spin_up(dev
)) {
588 case MSC_COMMAND_FAIL
:
592 /* Device detached, return immediately */
593 return USB_MSC_DETACHED
;
599 if (read_capacity(dev
) == MSC_COMMAND_DETACHED
)
600 return USB_MSC_DETACHED
;
602 return MSC_INST(dev
)->ready
;
606 usb_msc_init(usbdev_t
*dev
)
608 configuration_descriptor_t
*cd
=
609 (configuration_descriptor_t
*) dev
->configuration
;
610 interface_descriptor_t
*interface
=
611 (interface_descriptor_t
*) (((char *) cd
) + cd
->bLength
);
613 usb_debug(" it uses %s command set\n",
614 msc_subclass_strings
[interface
->bInterfaceSubClass
]);
615 usb_debug(" it uses %s protocol\n",
616 msc_protocol_strings
[interface
->bInterfaceProtocol
]);
618 if (interface
->bInterfaceProtocol
!= 0x50) {
619 usb_debug(" Protocol not supported.\n");
620 usb_detach_device(dev
->controller
, dev
->address
);
624 if ((interface
->bInterfaceSubClass
!= 2) && // ATAPI 8020
625 (interface
->bInterfaceSubClass
!= 5) && // ATAPI 8070
626 (interface
->bInterfaceSubClass
!= 6)) { // SCSI
627 /* Other protocols, such as ATAPI don't seem to be very popular. looks like ATAPI would be really easy to add, if necessary. */
628 usb_debug(" Interface SubClass not supported.\n");
629 usb_detach_device(dev
->controller
, dev
->address
);
633 usb_msc_force_init(dev
, 0);
636 void usb_msc_force_init(usbdev_t
*dev
, u32 quirks
)
640 /* init .data before setting .destroy */
643 dev
->destroy
= usb_msc_destroy
;
644 dev
->poll
= usb_msc_poll
;
646 dev
->data
= malloc(sizeof(usbmsc_inst_t
));
648 fatal("Not enough memory for USB MSC device.\n");
650 MSC_INST(dev
)->bulk_in
= 0;
651 MSC_INST(dev
)->bulk_out
= 0;
652 MSC_INST(dev
)->usbdisk_created
= 0;
653 MSC_INST(dev
)->quirks
= quirks
;
655 for (i
= 1; i
<= dev
->num_endp
; i
++) {
656 if (dev
->endpoints
[i
].endpoint
== 0)
658 if (dev
->endpoints
[i
].type
!= BULK
)
660 if ((dev
->endpoints
[i
].direction
== IN
)
661 && (MSC_INST(dev
)->bulk_in
== 0))
662 MSC_INST(dev
)->bulk_in
= &dev
->endpoints
[i
];
663 if ((dev
->endpoints
[i
].direction
== OUT
)
664 && (MSC_INST(dev
)->bulk_out
== 0))
665 MSC_INST(dev
)->bulk_out
= &dev
->endpoints
[i
];
668 if (MSC_INST(dev
)->bulk_in
== 0) {
669 usb_debug("couldn't find bulk-in endpoint.\n");
670 usb_detach_device(dev
->controller
, dev
->address
);
673 if (MSC_INST(dev
)->bulk_out
== 0) {
674 usb_debug("couldn't find bulk-out endpoint.\n");
675 usb_detach_device(dev
->controller
, dev
->address
);
678 usb_debug(" using endpoint %x as in, %x as out\n",
679 MSC_INST(dev
)->bulk_in
->endpoint
,
680 MSC_INST(dev
)->bulk_out
->endpoint
);
682 /* Some sticks need a little more time to get ready after SET_CONFIG. */
685 initialize_luns(dev
);
686 usb_debug(" has %d luns\n", MSC_INST(dev
)->num_luns
);
688 /* Test if unit is ready (nothing to do if it isn't). */
689 if (usb_msc_test_unit_ready(dev
) != USB_MSC_READY
)
692 /* Create the disk. */
693 usb_msc_create_disk(dev
);
697 usb_msc_poll(usbdev_t
*dev
)
699 usbmsc_inst_t
*msc
= MSC_INST(dev
);
700 int prev_ready
= msc
->ready
;
702 if (usb_msc_test_unit_ready(dev
) == USB_MSC_DETACHED
)
705 if (!prev_ready
&& msc
->ready
) {
706 usb_debug("USB msc: not ready -> ready (lun %d)\n", msc
->lun
);
707 usb_msc_create_disk(dev
);
708 } else if (prev_ready
&& !msc
->ready
) {
709 usb_debug("USB msc: ready -> not ready (lun %d)\n", msc
->lun
);
710 usb_msc_remove_disk(dev
);
711 } else if (!prev_ready
&& !msc
->ready
) {
712 u8 new_lun
= (msc
->lun
+ 1) % msc
->num_luns
;
713 usb_debug("USB msc: not ready (lun %d) -> lun %d\n", msc
->lun
,