1/* 2 * file_storage.c -- File-backed USB Storage Gadget, for USB development 3 * 4 * Copyright (C) 2003-2005 Alan Stern 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions, and the following disclaimer, 12 * without modification. 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 * 3. The names of the above-listed copyright holders may not be used 17 * to endorse or promote products derived from this software without 18 * specific prior written permission. 19 * 20 * ALTERNATIVELY, this software may be distributed under the terms of the 21 * GNU General Public License ("GPL") as published by the Free Software 22 * Foundation, either version 2 of that License or (at your option) any 23 * later version. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 26 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 27 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 32 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 */ 37 38 39 40 41/* 42 * Driver Design 43 * 44 * The FSG driver is fairly straightforward. There is a main kernel 45 * thread that handles most of the work. Interrupt routines field 46 * callbacks from the controller driver: bulk- and interrupt-request 47 * completion notifications, endpoint-0 events, and disconnect events. 48 * Completion events are passed to the main thread by wakeup calls. Many 49 * ep0 requests are handled at interrupt time, but SetInterface, 50 * SetConfiguration, and device reset requests are forwarded to the 51 * thread in the form of "exceptions" using SIGUSR1 signals (since they 52 * should interrupt any ongoing file I/O operations). 53 * 54 * The thread's main routine implements the standard command/data/status 55 * parts of a SCSI interaction. It and its subroutines are full of tests 56 * for pending signals/exceptions -- all this polling is necessary since 57 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an 58 * indication that the driver really wants to be running in userspace.) 59 * An important point is that so long as the thread is alive it keeps an 60 * open reference to the backing file. This will prevent unmounting 61 * the backing file's underlying filesystem and could cause problems 62 * during system shutdown, for example. To prevent such problems, the 63 * thread catches INT, TERM, and KILL signals and converts them into 64 * an EXIT exception. 65 * 66 * In normal operation the main thread is started during the gadget's 67 * fsg_bind() callback and stopped during fsg_unbind(). But it can also 68 * exit when it receives a signal, and there's no point leaving the 69 * gadget running when the thread is dead. So just before the thread 70 * exits, it deregisters the gadget driver. This makes things a little 71 * tricky: The driver is deregistered at two places, and the exiting 72 * thread can indirectly call fsg_unbind() which in turn can tell the 73 * thread to exit. The first problem is resolved through the use of the 74 * REGISTERED atomic bitflag; the driver will only be deregistered once. 75 * The second problem is resolved by having fsg_unbind() check 76 * fsg->state; it won't try to stop the thread if the state is already 77 * FSG_STATE_TERMINATED. 78 * 79 * To provide maximum throughput, the driver uses a circular pipeline of 80 * buffer heads (struct fsg_buffhd). In principle the pipeline can be 81 * arbitrarily long; in practice the benefits don't justify having more 82 * than 2 stages (i.e., double buffering). But it helps to think of the 83 * pipeline as being a long one. Each buffer head contains a bulk-in and 84 * a bulk-out request pointer (since the buffer can be used for both 85 * output and input -- directions always are given from the host's 86 * point of view) as well as a pointer to the buffer and various state 87 * variables. 88 * 89 * Use of the pipeline follows a simple protocol. There is a variable 90 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use. 91 * At any time that buffer head may still be in use from an earlier 92 * request, so each buffer head has a state variable indicating whether 93 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the 94 * buffer head to be EMPTY, filling the buffer either by file I/O or by 95 * USB I/O (during which the buffer head is BUSY), and marking the buffer 96 * head FULL when the I/O is complete. Then the buffer will be emptied 97 * (again possibly by USB I/O, during which it is marked BUSY) and 98 * finally marked EMPTY again (possibly by a completion routine). 99 * 100 * A module parameter tells the driver to avoid stalling the bulk 101 * endpoints wherever the transport specification allows. This is 102 * necessary for some UDCs like the SuperH, which cannot reliably clear a 103 * halt on a bulk endpoint. However, under certain circumstances the 104 * Bulk-only specification requires a stall. In such cases the driver 105 * will halt the endpoint and set a flag indicating that it should clear 106 * the halt in software during the next device reset. Hopefully this 107 * will permit everything to work correctly. Furthermore, although the 108 * specification allows the bulk-out endpoint to halt when the host sends 109 * too much data, implementing this would cause an unavoidable race. 110 * The driver will always use the "no-stall" approach for OUT transfers. 111 * 112 * One subtle point concerns sending status-stage responses for ep0 113 * requests. Some of these requests, such as device reset, can involve 114 * interrupting an ongoing file I/O operation, which might take an 115 * arbitrarily long time. During that delay the host might give up on 116 * the original ep0 request and issue a new one. When that happens the 117 * driver should not notify the host about completion of the original 118 * request, as the host will no longer be waiting for it. So the driver 119 * assigns to each ep0 request a unique tag, and it keeps track of the 120 * tag value of the request associated with a long-running exception 121 * (device-reset, interface-change, or configuration-change). When the 122 * exception handler is finished, the status-stage response is submitted 123 * only if the current ep0 request tag is equal to the exception request 124 * tag. Thus only the most recently received ep0 request will get a 125 * status-stage response. 126 * 127 * Warning: This driver source file is too long. It ought to be split up 128 * into a header file plus about 3 separate .c files, to handle the details 129 * of the Gadget, USB Mass Storage, and SCSI protocols. 130 */ 131 132 133#undef DEBUG 134#undef VERBOSE 135#undef DUMP_MSGS 136 137 138#include <asm/system.h> 139#include <asm/uaccess.h> 140 141#include <linux/bitops.h> 142#include <linux/blkdev.h> 143#include <linux/compiler.h> 144#include <linux/completion.h> 145#include <linux/dcache.h> 146#include <linux/delay.h> 147#include <linux/device.h> 148#include <linux/fcntl.h> 149#include <linux/file.h> 150#include <linux/fs.h> 151#include <linux/init.h> 152#include <linux/kernel.h> 153#include <linux/kref.h> 154#include <linux/kthread.h> 155#include <linux/limits.h> 156#include <linux/list.h> 157#include <linux/module.h> 158#include <linux/moduleparam.h> 159#include <linux/pagemap.h> 160#include <linux/rwsem.h> 161#include <linux/sched.h> 162#include <linux/signal.h> 163#include <linux/slab.h> 164#include <linux/spinlock.h> 165#include <linux/string.h> 166#include <linux/freezer.h> 167#include <linux/utsname.h> 168 169#include <linux/usb/ch9.h> 170#include <linux/usb_gadget.h> 171 172#include "gadget_chips.h" 173 174 175/*-------------------------------------------------------------------------*/ 176 177#define DRIVER_DESC "File-backed Storage Gadget" 178#define DRIVER_NAME "g_file_storage" 179#define DRIVER_VERSION "28 November 2005" 180 181static const char longname[] = DRIVER_DESC; 182static const char shortname[] = DRIVER_NAME; 183 184MODULE_DESCRIPTION(DRIVER_DESC); 185MODULE_AUTHOR("Alan Stern"); 186MODULE_LICENSE("Dual BSD/GPL"); 187 188/* Thanks to NetChip Technologies for donating this product ID. 189 * 190 * DO NOT REUSE THESE IDs with any other driver!! Ever!! 191 * Instead: allocate your own, using normal USB-IF procedures. */ 192#define DRIVER_VENDOR_ID 0x0525 // NetChip 193#define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget 194 195 196/* 197 * This driver assumes self-powered hardware and has no way for users to 198 * trigger remote wakeup. It uses autoconfiguration to select endpoints 199 * and endpoint addresses. 200 */ 201 202 203/*-------------------------------------------------------------------------*/ 204 205#define xprintk(f,level,fmt,args...) \ 206 dev_printk(level , &(f)->gadget->dev , fmt , ## args) 207#define yprintk(l,level,fmt,args...) \ 208 dev_printk(level , &(l)->dev , fmt , ## args) 209 210#ifdef DEBUG 211#define DBG(fsg,fmt,args...) \ 212 xprintk(fsg , KERN_DEBUG , fmt , ## args) 213#define LDBG(lun,fmt,args...) \ 214 yprintk(lun , KERN_DEBUG , fmt , ## args) 215#define MDBG(fmt,args...) \ 216 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args) 217#else 218#define DBG(fsg,fmt,args...) \ 219 do { } while (0) 220#define LDBG(lun,fmt,args...) \ 221 do { } while (0) 222#define MDBG(fmt,args...) \ 223 do { } while (0) 224#undef VERBOSE 225#undef DUMP_MSGS 226#endif /* DEBUG */ 227 228#ifdef VERBOSE 229#define VDBG DBG 230#define VLDBG LDBG 231#else 232#define VDBG(fsg,fmt,args...) \ 233 do { } while (0) 234#define VLDBG(lun,fmt,args...) \ 235 do { } while (0) 236#endif /* VERBOSE */ 237 238#define ERROR(fsg,fmt,args...) \ 239 xprintk(fsg , KERN_ERR , fmt , ## args) 240#define LERROR(lun,fmt,args...) \ 241 yprintk(lun , KERN_ERR , fmt , ## args) 242 243#define WARN(fsg,fmt,args...) \ 244 xprintk(fsg , KERN_WARNING , fmt , ## args) 245#define LWARN(lun,fmt,args...) \ 246 yprintk(lun , KERN_WARNING , fmt , ## args) 247 248#define INFO(fsg,fmt,args...) \ 249 xprintk(fsg , KERN_INFO , fmt , ## args) 250#define LINFO(lun,fmt,args...) \ 251 yprintk(lun , KERN_INFO , fmt , ## args) 252 253#define MINFO(fmt,args...) \ 254 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args) 255 256 257/*-------------------------------------------------------------------------*/ 258 259/* Encapsulate the module parameter settings */ 260 261#define MAX_LUNS 8 262 263static struct { 264 char *file[MAX_LUNS]; 265 int ro[MAX_LUNS]; 266 int num_filenames; 267 int num_ros; 268 unsigned int nluns; 269 270 int removable; 271 int can_stall; 272 273 char *transport_parm; 274 char *protocol_parm; 275 unsigned short vendor; 276 unsigned short product; 277 unsigned short release; 278 unsigned int buflen; 279 280 int transport_type; 281 char *transport_name; 282 int protocol_type; 283 char *protocol_name; 284 285} mod_data = { // Default values 286 .transport_parm = "BBB", 287 .protocol_parm = "SCSI", 288 .removable = 0, 289 .can_stall = 1, 290 .vendor = DRIVER_VENDOR_ID, 291 .product = DRIVER_PRODUCT_ID, 292 .release = 0xffff, // Use controller chip type 293 .buflen = 16384, 294 }; 295 296 297module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames, 298 S_IRUGO); 299MODULE_PARM_DESC(file, "names of backing files or devices"); 300 301module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO); 302MODULE_PARM_DESC(ro, "true to force read-only"); 303 304module_param_named(luns, mod_data.nluns, uint, S_IRUGO); 305MODULE_PARM_DESC(luns, "number of LUNs"); 306 307module_param_named(removable, mod_data.removable, bool, S_IRUGO); 308MODULE_PARM_DESC(removable, "true to simulate removable media"); 309 310module_param_named(stall, mod_data.can_stall, bool, S_IRUGO); 311MODULE_PARM_DESC(stall, "false to prevent bulk stalls"); 312 313 314/* In the non-TEST version, only the module parameters listed above 315 * are available. */ 316#ifdef CONFIG_USB_FILE_STORAGE_TEST 317 318module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO); 319MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)"); 320 321module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO); 322MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, " 323 "8070, or SCSI)"); 324 325module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO); 326MODULE_PARM_DESC(vendor, "USB Vendor ID"); 327 328module_param_named(product, mod_data.product, ushort, S_IRUGO); 329MODULE_PARM_DESC(product, "USB Product ID"); 330 331module_param_named(release, mod_data.release, ushort, S_IRUGO); 332MODULE_PARM_DESC(release, "USB release number"); 333 334module_param_named(buflen, mod_data.buflen, uint, S_IRUGO); 335MODULE_PARM_DESC(buflen, "I/O buffer size"); 336 337#endif /* CONFIG_USB_FILE_STORAGE_TEST */ 338 339 340/*-------------------------------------------------------------------------*/ 341 342/* USB protocol value = the transport method */ 343#define USB_PR_CBI 0x00 // Control/Bulk/Interrupt 344#define USB_PR_CB 0x01 // Control/Bulk w/o interrupt 345#define USB_PR_BULK 0x50 // Bulk-only 346 347/* USB subclass value = the protocol encapsulation */ 348#define USB_SC_RBC 0x01 // Reduced Block Commands (flash) 349#define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM) 350#define USB_SC_QIC 0x03 // QIC-157 (tape) 351#define USB_SC_UFI 0x04 // UFI (floppy) 352#define USB_SC_8070 0x05 // SFF-8070i (removable) 353#define USB_SC_SCSI 0x06 // Transparent SCSI 354 355/* Bulk-only data structures */ 356 357/* Command Block Wrapper */ 358struct bulk_cb_wrap { 359 __le32 Signature; // Contains 'USBC' 360 u32 Tag; // Unique per command id 361 __le32 DataTransferLength; // Size of the data 362 u8 Flags; // Direction in bit 7 363 u8 Lun; // LUN (normally 0) 364 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE 365 u8 CDB[16]; // Command Data Block 366}; 367 368#define USB_BULK_CB_WRAP_LEN 31 369#define USB_BULK_CB_SIG 0x43425355 // Spells out USBC 370#define USB_BULK_IN_FLAG 0x80 371 372/* Command Status Wrapper */ 373struct bulk_cs_wrap { 374 __le32 Signature; // Should = 'USBS' 375 u32 Tag; // Same as original command 376 __le32 Residue; // Amount not transferred 377 u8 Status; // See below 378}; 379 380#define USB_BULK_CS_WRAP_LEN 13 381#define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS' 382#define USB_STATUS_PASS 0 383#define USB_STATUS_FAIL 1 384#define USB_STATUS_PHASE_ERROR 2 385 386/* Bulk-only class specific requests */ 387#define USB_BULK_RESET_REQUEST 0xff 388#define USB_BULK_GET_MAX_LUN_REQUEST 0xfe 389 390 391/* CBI Interrupt data structure */ 392struct interrupt_data { 393 u8 bType; 394 u8 bValue; 395}; 396 397#define CBI_INTERRUPT_DATA_LEN 2 398 399/* CBI Accept Device-Specific Command request */ 400#define USB_CBI_ADSC_REQUEST 0x00 401 402 403#define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block 404 405/* SCSI commands that we recognize */ 406#define SC_FORMAT_UNIT 0x04 407#define SC_INQUIRY 0x12 408#define SC_MODE_SELECT_6 0x15 409#define SC_MODE_SELECT_10 0x55 410#define SC_MODE_SENSE_6 0x1a 411#define SC_MODE_SENSE_10 0x5a 412#define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e 413#define SC_READ_6 0x08 414#define SC_READ_10 0x28 415#define SC_READ_12 0xa8 416#define SC_READ_CAPACITY 0x25 417#define SC_READ_FORMAT_CAPACITIES 0x23 418#define SC_RELEASE 0x17 419#define SC_REQUEST_SENSE 0x03 420#define SC_RESERVE 0x16 421#define SC_SEND_DIAGNOSTIC 0x1d 422#define SC_START_STOP_UNIT 0x1b 423#define SC_SYNCHRONIZE_CACHE 0x35 424#define SC_TEST_UNIT_READY 0x00 425#define SC_VERIFY 0x2f 426#define SC_WRITE_6 0x0a 427#define SC_WRITE_10 0x2a 428#define SC_WRITE_12 0xaa 429 430/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */ 431#define SS_NO_SENSE 0 432#define SS_COMMUNICATION_FAILURE 0x040800 433#define SS_INVALID_COMMAND 0x052000 434#define SS_INVALID_FIELD_IN_CDB 0x052400 435#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100 436#define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500 437#define SS_MEDIUM_NOT_PRESENT 0x023a00 438#define SS_MEDIUM_REMOVAL_PREVENTED 0x055302 439#define SS_NOT_READY_TO_READY_TRANSITION 0x062800 440#define SS_RESET_OCCURRED 0x062900 441#define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900 442#define SS_UNRECOVERED_READ_ERROR 0x031100 443#define SS_WRITE_ERROR 0x030c02 444#define SS_WRITE_PROTECTED 0x072700 445 446#define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc. 447#define ASC(x) ((u8) ((x) >> 8)) 448#define ASCQ(x) ((u8) (x)) 449 450 451/*-------------------------------------------------------------------------*/ 452 453/* 454 * These definitions will permit the compiler to avoid generating code for 455 * parts of the driver that aren't used in the non-TEST version. Even gcc 456 * can recognize when a test of a constant expression yields a dead code 457 * path. 458 */ 459 460#ifdef CONFIG_USB_FILE_STORAGE_TEST 461 462#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK) 463#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI) 464#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI) 465 466#else 467 468#define transport_is_bbb() 1 469#define transport_is_cbi() 0 470#define protocol_is_scsi() 1 471 472#endif /* CONFIG_USB_FILE_STORAGE_TEST */ 473 474 475struct lun { 476 struct file *filp; 477 loff_t file_length; 478 loff_t num_sectors; 479 480 unsigned int ro : 1; 481 unsigned int prevent_medium_removal : 1; 482 unsigned int registered : 1; 483 unsigned int info_valid : 1; 484 485 u32 sense_data; 486 u32 sense_data_info; 487 u32 unit_attention_data; 488 489 struct device dev; 490}; 491 492#define backing_file_is_open(curlun) ((curlun)->filp != NULL) 493 494static inline struct lun *dev_to_lun(struct device *dev) 495{ 496 return container_of(dev, struct lun, dev); 497} 498 499 500/* Big enough to hold our biggest descriptor */ 501#define EP0_BUFSIZE 256 502#define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value 503 504/* Number of buffers we will use. 2 is enough for double-buffering */ 505#define NUM_BUFFERS 2 506 507enum fsg_buffer_state { 508 BUF_STATE_EMPTY = 0, 509 BUF_STATE_FULL, 510 BUF_STATE_BUSY 511}; 512 513struct fsg_buffhd { 514 void *buf; 515 dma_addr_t dma; 516 enum fsg_buffer_state state; 517 struct fsg_buffhd *next; 518 519 /* The NetChip 2280 is faster, and handles some protocol faults 520 * better, if we don't submit any short bulk-out read requests. 521 * So we will record the intended request length here. */ 522 unsigned int bulk_out_intended_length; 523 524 struct usb_request *inreq; 525 int inreq_busy; 526 struct usb_request *outreq; 527 int outreq_busy; 528}; 529 530enum fsg_state { 531 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere 532 FSG_STATE_DATA_PHASE, 533 FSG_STATE_STATUS_PHASE, 534 535 FSG_STATE_IDLE = 0, 536 FSG_STATE_ABORT_BULK_OUT, 537 FSG_STATE_RESET, 538 FSG_STATE_INTERFACE_CHANGE, 539 FSG_STATE_CONFIG_CHANGE, 540 FSG_STATE_DISCONNECT, 541 FSG_STATE_EXIT, 542 FSG_STATE_TERMINATED 543}; 544 545enum data_direction { 546 DATA_DIR_UNKNOWN = 0, 547 DATA_DIR_FROM_HOST, 548 DATA_DIR_TO_HOST, 549 DATA_DIR_NONE 550}; 551 552struct fsg_dev { 553 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */ 554 spinlock_t lock; 555 struct usb_gadget *gadget; 556 557 /* filesem protects: backing files in use */ 558 struct rw_semaphore filesem; 559 560 /* reference counting: wait until all LUNs are released */ 561 struct kref ref; 562 563 struct usb_ep *ep0; // Handy copy of gadget->ep0 564 struct usb_request *ep0req; // For control responses 565 unsigned int ep0_req_tag; 566 const char *ep0req_name; 567 568 struct usb_request *intreq; // For interrupt responses 569 int intreq_busy; 570 struct fsg_buffhd *intr_buffhd; 571 572 unsigned int bulk_out_maxpacket; 573 enum fsg_state state; // For exception handling 574 unsigned int exception_req_tag; 575 576 u8 config, new_config; 577 578 unsigned int running : 1; 579 unsigned int bulk_in_enabled : 1; 580 unsigned int bulk_out_enabled : 1; 581 unsigned int intr_in_enabled : 1; 582 unsigned int phase_error : 1; 583 unsigned int short_packet_received : 1; 584 unsigned int bad_lun_okay : 1; 585 586 unsigned long atomic_bitflags; 587#define REGISTERED 0 588#define CLEAR_BULK_HALTS 1 589#define SUSPENDED 2 590 591 struct usb_ep *bulk_in; 592 struct usb_ep *bulk_out; 593 struct usb_ep *intr_in; 594 595 struct fsg_buffhd *next_buffhd_to_fill; 596 struct fsg_buffhd *next_buffhd_to_drain; 597 struct fsg_buffhd buffhds[NUM_BUFFERS]; 598 599 int thread_wakeup_needed; 600 struct completion thread_notifier; 601 struct task_struct *thread_task; 602 603 int cmnd_size; 604 u8 cmnd[MAX_COMMAND_SIZE]; 605 enum data_direction data_dir; 606 u32 data_size; 607 u32 data_size_from_cmnd; 608 u32 tag; 609 unsigned int lun; 610 u32 residue; 611 u32 usb_amount_left; 612 613 /* The CB protocol offers no way for a host to know when a command 614 * has completed. As a result the next command may arrive early, 615 * and we will still have to handle it. For that reason we need 616 * a buffer to store new commands when using CB (or CBI, which 617 * does not oblige a host to wait for command completion either). */ 618 int cbbuf_cmnd_size; 619 u8 cbbuf_cmnd[MAX_COMMAND_SIZE]; 620 621 unsigned int nluns; 622 struct lun *luns; 623 struct lun *curlun; 624}; 625 626typedef void (*fsg_routine_t)(struct fsg_dev *); 627 628static int inline exception_in_progress(struct fsg_dev *fsg) 629{ 630 return (fsg->state > FSG_STATE_IDLE); 631} 632 633/* Make bulk-out requests be divisible by the maxpacket size */ 634static void inline set_bulk_out_req_length(struct fsg_dev *fsg, 635 struct fsg_buffhd *bh, unsigned int length) 636{ 637 unsigned int rem; 638 639 bh->bulk_out_intended_length = length; 640 rem = length % fsg->bulk_out_maxpacket; 641 if (rem > 0) 642 length += fsg->bulk_out_maxpacket - rem; 643 bh->outreq->length = length; 644} 645 646static struct fsg_dev *the_fsg; 647static struct usb_gadget_driver fsg_driver; 648 649static void close_backing_file(struct lun *curlun); 650static void close_all_backing_files(struct fsg_dev *fsg); 651 652 653/*-------------------------------------------------------------------------*/ 654 655#ifdef DUMP_MSGS 656 657static void dump_msg(struct fsg_dev *fsg, const char *label, 658 const u8 *buf, unsigned int length) 659{ 660 unsigned int start, num, i; 661 char line[52], *p; 662 663 if (length >= 512) 664 return; 665 DBG(fsg, "%s, length %u:\n", label, length); 666 667 start = 0; 668 while (length > 0) { 669 num = min(length, 16u); 670 p = line; 671 for (i = 0; i < num; ++i) { 672 if (i == 8) 673 *p++ = ' '; 674 sprintf(p, " %02x", buf[i]); 675 p += 3; 676 } 677 *p = 0; 678 printk(KERN_DEBUG "%6x: %s\n", start, line); 679 buf += num; 680 start += num; 681 length -= num; 682 } 683} 684 685static void inline dump_cdb(struct fsg_dev *fsg) 686{} 687 688#else 689 690static void inline dump_msg(struct fsg_dev *fsg, const char *label, 691 const u8 *buf, unsigned int length) 692{} 693 694static void inline dump_cdb(struct fsg_dev *fsg) 695{ 696 int i; 697 char cmdbuf[3*MAX_COMMAND_SIZE + 1]; 698 699 for (i = 0; i < fsg->cmnd_size; ++i) 700 sprintf(cmdbuf + i*3, " %02x", fsg->cmnd[i]); 701 VDBG(fsg, "SCSI CDB: %s\n", cmdbuf); 702} 703 704#endif /* DUMP_MSGS */ 705 706 707static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep) 708{ 709 const char *name; 710 711 if (ep == fsg->bulk_in) 712 name = "bulk-in"; 713 else if (ep == fsg->bulk_out) 714 name = "bulk-out"; 715 else 716 name = ep->name; 717 DBG(fsg, "%s set halt\n", name); 718 return usb_ep_set_halt(ep); 719} 720 721 722/*-------------------------------------------------------------------------*/ 723 724/* Routines for unaligned data access */ 725 726static u16 inline get_be16(u8 *buf) 727{ 728 return ((u16) buf[0] << 8) | ((u16) buf[1]); 729} 730 731static u32 inline get_be32(u8 *buf) 732{ 733 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) | 734 ((u32) buf[2] << 8) | ((u32) buf[3]); 735} 736 737static void inline put_be16(u8 *buf, u16 val) 738{ 739 buf[0] = val >> 8; 740 buf[1] = val; 741} 742 743static void inline put_be32(u8 *buf, u32 val) 744{ 745 buf[0] = val >> 24; 746 buf[1] = val >> 16; 747 buf[2] = val >> 8; 748 buf[3] = val & 0xff; 749} 750 751 752/*-------------------------------------------------------------------------*/ 753 754/* 755 * DESCRIPTORS ... most are static, but strings and (full) configuration 756 * descriptors are built on demand. Also the (static) config and interface 757 * descriptors are adjusted during fsg_bind(). 758 */ 759#define STRING_MANUFACTURER 1 760#define STRING_PRODUCT 2 761#define STRING_SERIAL 3 762#define STRING_CONFIG 4 763#define STRING_INTERFACE 5 764 765/* There is only one configuration. */ 766#define CONFIG_VALUE 1 767 768static struct usb_device_descriptor 769device_desc = { 770 .bLength = sizeof device_desc, 771 .bDescriptorType = USB_DT_DEVICE, 772 773 .bcdUSB = __constant_cpu_to_le16(0x0200), 774 .bDeviceClass = USB_CLASS_PER_INTERFACE, 775 776 /* The next three values can be overridden by module parameters */ 777 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID), 778 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID), 779 .bcdDevice = __constant_cpu_to_le16(0xffff), 780 781 .iManufacturer = STRING_MANUFACTURER, 782 .iProduct = STRING_PRODUCT, 783 .iSerialNumber = STRING_SERIAL, 784 .bNumConfigurations = 1, 785}; 786 787static struct usb_config_descriptor 788config_desc = { 789 .bLength = sizeof config_desc, 790 .bDescriptorType = USB_DT_CONFIG, 791 792 /* wTotalLength computed by usb_gadget_config_buf() */ 793 .bNumInterfaces = 1, 794 .bConfigurationValue = CONFIG_VALUE, 795 .iConfiguration = STRING_CONFIG, 796 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER, 797 .bMaxPower = 1, // self-powered 798}; 799 800static struct usb_otg_descriptor 801otg_desc = { 802 .bLength = sizeof(otg_desc), 803 .bDescriptorType = USB_DT_OTG, 804 805 .bmAttributes = USB_OTG_SRP, 806}; 807 808/* There is only one interface. */ 809 810static struct usb_interface_descriptor 811intf_desc = { 812 .bLength = sizeof intf_desc, 813 .bDescriptorType = USB_DT_INTERFACE, 814 815 .bNumEndpoints = 2, // Adjusted during fsg_bind() 816 .bInterfaceClass = USB_CLASS_MASS_STORAGE, 817 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind() 818 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind() 819 .iInterface = STRING_INTERFACE, 820}; 821 822/* Three full-speed endpoint descriptors: bulk-in, bulk-out, 823 * and interrupt-in. */ 824 825static struct usb_endpoint_descriptor 826fs_bulk_in_desc = { 827 .bLength = USB_DT_ENDPOINT_SIZE, 828 .bDescriptorType = USB_DT_ENDPOINT, 829 830 .bEndpointAddress = USB_DIR_IN, 831 .bmAttributes = USB_ENDPOINT_XFER_BULK, 832 /* wMaxPacketSize set by autoconfiguration */ 833}; 834 835static struct usb_endpoint_descriptor 836fs_bulk_out_desc = { 837 .bLength = USB_DT_ENDPOINT_SIZE, 838 .bDescriptorType = USB_DT_ENDPOINT, 839 840 .bEndpointAddress = USB_DIR_OUT, 841 .bmAttributes = USB_ENDPOINT_XFER_BULK, 842 /* wMaxPacketSize set by autoconfiguration */ 843}; 844 845static struct usb_endpoint_descriptor 846fs_intr_in_desc = { 847 .bLength = USB_DT_ENDPOINT_SIZE, 848 .bDescriptorType = USB_DT_ENDPOINT, 849 850 .bEndpointAddress = USB_DIR_IN, 851 .bmAttributes = USB_ENDPOINT_XFER_INT, 852 .wMaxPacketSize = __constant_cpu_to_le16(2), 853 .bInterval = 32, // frames -> 32 ms 854}; 855 856static const struct usb_descriptor_header *fs_function[] = { 857 (struct usb_descriptor_header *) &otg_desc, 858 (struct usb_descriptor_header *) &intf_desc, 859 (struct usb_descriptor_header *) &fs_bulk_in_desc, 860 (struct usb_descriptor_header *) &fs_bulk_out_desc, 861 (struct usb_descriptor_header *) &fs_intr_in_desc, 862 NULL, 863}; 864#define FS_FUNCTION_PRE_EP_ENTRIES 2 865 866 867#ifdef CONFIG_USB_GADGET_DUALSPEED 868 869/* 870 * USB 2.0 devices need to expose both high speed and full speed 871 * descriptors, unless they only run at full speed. 872 * 873 * That means alternate endpoint descriptors (bigger packets) 874 * and a "device qualifier" ... plus more construction options 875 * for the config descriptor. 876 */ 877static struct usb_qualifier_descriptor 878dev_qualifier = { 879 .bLength = sizeof dev_qualifier, 880 .bDescriptorType = USB_DT_DEVICE_QUALIFIER, 881 882 .bcdUSB = __constant_cpu_to_le16(0x0200), 883 .bDeviceClass = USB_CLASS_PER_INTERFACE, 884 885 .bNumConfigurations = 1, 886}; 887 888static struct usb_endpoint_descriptor 889hs_bulk_in_desc = { 890 .bLength = USB_DT_ENDPOINT_SIZE, 891 .bDescriptorType = USB_DT_ENDPOINT, 892 893 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */ 894 .bmAttributes = USB_ENDPOINT_XFER_BULK, 895 .wMaxPacketSize = __constant_cpu_to_le16(512), 896}; 897 898static struct usb_endpoint_descriptor 899hs_bulk_out_desc = { 900 .bLength = USB_DT_ENDPOINT_SIZE, 901 .bDescriptorType = USB_DT_ENDPOINT, 902 903 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */ 904 .bmAttributes = USB_ENDPOINT_XFER_BULK, 905 .wMaxPacketSize = __constant_cpu_to_le16(512), 906 .bInterval = 1, // NAK every 1 uframe 907}; 908 909static struct usb_endpoint_descriptor 910hs_intr_in_desc = { 911 .bLength = USB_DT_ENDPOINT_SIZE, 912 .bDescriptorType = USB_DT_ENDPOINT, 913 914 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */ 915 .bmAttributes = USB_ENDPOINT_XFER_INT, 916 .wMaxPacketSize = __constant_cpu_to_le16(2), 917 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms 918}; 919 920static const struct usb_descriptor_header *hs_function[] = { 921 (struct usb_descriptor_header *) &otg_desc, 922 (struct usb_descriptor_header *) &intf_desc, 923 (struct usb_descriptor_header *) &hs_bulk_in_desc, 924 (struct usb_descriptor_header *) &hs_bulk_out_desc, 925 (struct usb_descriptor_header *) &hs_intr_in_desc, 926 NULL, 927}; 928#define HS_FUNCTION_PRE_EP_ENTRIES 2 929 930/* Maxpacket and other transfer characteristics vary by speed. */ 931#define ep_desc(g,fs,hs) (((g)->speed==USB_SPEED_HIGH) ? (hs) : (fs)) 932 933#else 934 935/* If there's no high speed support, always use the full-speed descriptor. */ 936#define ep_desc(g,fs,hs) fs 937 938#endif /* !CONFIG_USB_GADGET_DUALSPEED */ 939 940 941/* The CBI specification limits the serial string to 12 uppercase hexadecimal 942 * characters. */ 943static char manufacturer[64]; 944static char serial[13]; 945 946/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */ 947static struct usb_string strings[] = { 948 {STRING_MANUFACTURER, manufacturer}, 949 {STRING_PRODUCT, longname}, 950 {STRING_SERIAL, serial}, 951 {STRING_CONFIG, "Self-powered"}, 952 {STRING_INTERFACE, "Mass Storage"}, 953 {} 954}; 955 956static struct usb_gadget_strings stringtab = { 957 .language = 0x0409, // en-us 958 .strings = strings, 959}; 960 961 962/* 963 * Config descriptors must agree with the code that sets configurations 964 * and with code managing interfaces and their altsettings. They must 965 * also handle different speeds and other-speed requests. 966 */ 967static int populate_config_buf(struct usb_gadget *gadget, 968 u8 *buf, u8 type, unsigned index) 969{ 970#ifdef CONFIG_USB_GADGET_DUALSPEED 971 enum usb_device_speed speed = gadget->speed; 972#endif 973 int len; 974 const struct usb_descriptor_header **function; 975 976 if (index > 0) 977 return -EINVAL; 978 979#ifdef CONFIG_USB_GADGET_DUALSPEED 980 if (type == USB_DT_OTHER_SPEED_CONFIG) 981 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed; 982 if (speed == USB_SPEED_HIGH) 983 function = hs_function; 984 else 985#endif 986 function = fs_function; 987 988 /* for now, don't advertise srp-only devices */ 989 if (!gadget->is_otg) 990 function++; 991 992 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function); 993 ((struct usb_config_descriptor *) buf)->bDescriptorType = type; 994 return len; 995} 996 997 998/*-------------------------------------------------------------------------*/ 999 1000/* These routines may be called in process context or in_irq */ 1001 1002/* Caller must hold fsg->lock */ 1003static void wakeup_thread(struct fsg_dev *fsg) 1004{ 1005 /* Tell the main thread that something has happened */ 1006 fsg->thread_wakeup_needed = 1; 1007 if (fsg->thread_task) 1008 wake_up_process(fsg->thread_task); 1009} 1010 1011 1012static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state) 1013{ 1014 unsigned long flags; 1015 1016 /* Do nothing if a higher-priority exception is already in progress. 1017 * If a lower-or-equal priority exception is in progress, preempt it 1018 * and notify the main thread by sending it a signal. */ 1019 spin_lock_irqsave(&fsg->lock, flags); 1020 if (fsg->state <= new_state) { 1021 fsg->exception_req_tag = fsg->ep0_req_tag; 1022 fsg->state = new_state; 1023 if (fsg->thread_task) 1024 send_sig_info(SIGUSR1, SEND_SIG_FORCED, 1025 fsg->thread_task); 1026 } 1027 spin_unlock_irqrestore(&fsg->lock, flags); 1028} 1029 1030 1031/*-------------------------------------------------------------------------*/ 1032 1033/* The disconnect callback and ep0 routines. These always run in_irq, 1034 * except that ep0_queue() is called in the main thread to acknowledge 1035 * completion of various requests: set config, set interface, and 1036 * Bulk-only device reset. */ 1037 1038static void fsg_disconnect(struct usb_gadget *gadget) 1039{ 1040 struct fsg_dev *fsg = get_gadget_data(gadget); 1041 1042 DBG(fsg, "disconnect or port reset\n"); 1043 raise_exception(fsg, FSG_STATE_DISCONNECT); 1044} 1045 1046 1047static int ep0_queue(struct fsg_dev *fsg) 1048{ 1049 int rc; 1050 1051 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC); 1052 if (rc != 0 && rc != -ESHUTDOWN) { 1053 1054 /* We can't do much more than wait for a reset */ 1055 WARN(fsg, "error in submission: %s --> %d\n", 1056 fsg->ep0->name, rc); 1057 } 1058 return rc; 1059} 1060 1061static void ep0_complete(struct usb_ep *ep, struct usb_request *req) 1062{ 1063 struct fsg_dev *fsg = ep->driver_data; 1064 1065 if (req->actual > 0) 1066 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual); 1067 if (req->status || req->actual != req->length) 1068 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__, 1069 req->status, req->actual, req->length); 1070 if (req->status == -ECONNRESET) // Request was cancelled 1071 usb_ep_fifo_flush(ep); 1072 1073 if (req->status == 0 && req->context) 1074 ((fsg_routine_t) (req->context))(fsg); 1075} 1076 1077 1078/*-------------------------------------------------------------------------*/ 1079 1080/* Bulk and interrupt endpoint completion handlers. 1081 * These always run in_irq. */ 1082 1083static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req) 1084{ 1085 struct fsg_dev *fsg = ep->driver_data; 1086 struct fsg_buffhd *bh = req->context; 1087 1088 if (req->status || req->actual != req->length) 1089 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__, 1090 req->status, req->actual, req->length); 1091 if (req->status == -ECONNRESET) // Request was cancelled 1092 usb_ep_fifo_flush(ep); 1093 1094 /* Hold the lock while we update the request and buffer states */ 1095 smp_wmb(); 1096 spin_lock(&fsg->lock); 1097 bh->inreq_busy = 0; 1098 bh->state = BUF_STATE_EMPTY; 1099 wakeup_thread(fsg); 1100 spin_unlock(&fsg->lock); 1101} 1102 1103static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req) 1104{ 1105 struct fsg_dev *fsg = ep->driver_data; 1106 struct fsg_buffhd *bh = req->context; 1107 1108 dump_msg(fsg, "bulk-out", req->buf, req->actual); 1109 if (req->status || req->actual != bh->bulk_out_intended_length) 1110 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__, 1111 req->status, req->actual, 1112 bh->bulk_out_intended_length); 1113 if (req->status == -ECONNRESET) // Request was cancelled 1114 usb_ep_fifo_flush(ep); 1115 1116 /* Hold the lock while we update the request and buffer states */ 1117 smp_wmb(); 1118 spin_lock(&fsg->lock); 1119 bh->outreq_busy = 0; 1120 bh->state = BUF_STATE_FULL; 1121 wakeup_thread(fsg); 1122 spin_unlock(&fsg->lock); 1123} 1124 1125 1126#ifdef CONFIG_USB_FILE_STORAGE_TEST 1127static void intr_in_complete(struct usb_ep *ep, struct usb_request *req) 1128{ 1129 struct fsg_dev *fsg = ep->driver_data; 1130 struct fsg_buffhd *bh = req->context; 1131 1132 if (req->status || req->actual != req->length) 1133 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__, 1134 req->status, req->actual, req->length); 1135 if (req->status == -ECONNRESET) // Request was cancelled 1136 usb_ep_fifo_flush(ep); 1137 1138 /* Hold the lock while we update the request and buffer states */ 1139 smp_wmb(); 1140 spin_lock(&fsg->lock); 1141 fsg->intreq_busy = 0; 1142 bh->state = BUF_STATE_EMPTY; 1143 wakeup_thread(fsg); 1144 spin_unlock(&fsg->lock); 1145} 1146 1147#else 1148static void intr_in_complete(struct usb_ep *ep, struct usb_request *req) 1149{} 1150#endif /* CONFIG_USB_FILE_STORAGE_TEST */ 1151 1152 1153/*-------------------------------------------------------------------------*/ 1154 1155/* Ep0 class-specific handlers. These always run in_irq. */ 1156 1157#ifdef CONFIG_USB_FILE_STORAGE_TEST 1158static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh) 1159{ 1160 struct usb_request *req = fsg->ep0req; 1161 static u8 cbi_reset_cmnd[6] = { 1162 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff}; 1163 1164 /* Error in command transfer? */ 1165 if (req->status || req->length != req->actual || 1166 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) { 1167 1168 /* Not all controllers allow a protocol stall after 1169 * receiving control-out data, but we'll try anyway. */ 1170 fsg_set_halt(fsg, fsg->ep0); 1171 return; // Wait for reset 1172 } 1173 1174 /* Is it the special reset command? */ 1175 if (req->actual >= sizeof cbi_reset_cmnd && 1176 memcmp(req->buf, cbi_reset_cmnd, 1177 sizeof cbi_reset_cmnd) == 0) { 1178 1179 /* Raise an exception to stop the current operation 1180 * and reinitialize our state. */ 1181 DBG(fsg, "cbi reset request\n"); 1182 raise_exception(fsg, FSG_STATE_RESET); 1183 return; 1184 } 1185 1186 VDBG(fsg, "CB[I] accept device-specific command\n"); 1187 spin_lock(&fsg->lock); 1188 1189 /* Save the command for later */ 1190 if (fsg->cbbuf_cmnd_size) 1191 WARN(fsg, "CB[I] overwriting previous command\n"); 1192 fsg->cbbuf_cmnd_size = req->actual; 1193 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size); 1194 1195 wakeup_thread(fsg); 1196 spin_unlock(&fsg->lock); 1197} 1198 1199#else 1200static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh) 1201{} 1202#endif /* CONFIG_USB_FILE_STORAGE_TEST */ 1203 1204 1205static int class_setup_req(struct fsg_dev *fsg, 1206 const struct usb_ctrlrequest *ctrl) 1207{ 1208 struct usb_request *req = fsg->ep0req; 1209 int value = -EOPNOTSUPP; 1210 u16 w_index = le16_to_cpu(ctrl->wIndex); 1211 u16 w_length = le16_to_cpu(ctrl->wLength); 1212 1213 if (!fsg->config) 1214 return value; 1215 1216 /* Handle Bulk-only class-specific requests */ 1217 if (transport_is_bbb()) { 1218 switch (ctrl->bRequest) { 1219 1220 case USB_BULK_RESET_REQUEST: 1221 if (ctrl->bRequestType != (USB_DIR_OUT | 1222 USB_TYPE_CLASS | USB_RECIP_INTERFACE)) 1223 break; 1224 if (w_index != 0) { 1225 value = -EDOM; 1226 break; 1227 } 1228 1229 /* Raise an exception to stop the current operation 1230 * and reinitialize our state. */ 1231 DBG(fsg, "bulk reset request\n"); 1232 raise_exception(fsg, FSG_STATE_RESET); 1233 value = DELAYED_STATUS; 1234 break; 1235 1236 case USB_BULK_GET_MAX_LUN_REQUEST: 1237 if (ctrl->bRequestType != (USB_DIR_IN | 1238 USB_TYPE_CLASS | USB_RECIP_INTERFACE)) 1239 break; 1240 if (w_index != 0) { 1241 value = -EDOM; 1242 break; 1243 } 1244 VDBG(fsg, "get max LUN\n"); 1245 *(u8 *) req->buf = fsg->nluns - 1; 1246 value = 1; 1247 break; 1248 } 1249 } 1250 1251 /* Handle CBI class-specific requests */ 1252 else { 1253 switch (ctrl->bRequest) { 1254 1255 case USB_CBI_ADSC_REQUEST: 1256 if (ctrl->bRequestType != (USB_DIR_OUT | 1257 USB_TYPE_CLASS | USB_RECIP_INTERFACE)) 1258 break; 1259 if (w_index != 0) { 1260 value = -EDOM; 1261 break; 1262 } 1263 if (w_length > MAX_COMMAND_SIZE) { 1264 value = -EOVERFLOW; 1265 break; 1266 } 1267 value = w_length; 1268 fsg->ep0req->context = received_cbi_adsc; 1269 break; 1270 } 1271 } 1272 1273 if (value == -EOPNOTSUPP) 1274 VDBG(fsg, 1275 "unknown class-specific control req " 1276 "%02x.%02x v%04x i%04x l%u\n", 1277 ctrl->bRequestType, ctrl->bRequest, 1278 le16_to_cpu(ctrl->wValue), w_index, w_length); 1279 return value; 1280} 1281 1282 1283/*-------------------------------------------------------------------------*/ 1284 1285/* Ep0 standard request handlers. These always run in_irq. */ 1286 1287static int standard_setup_req(struct fsg_dev *fsg, 1288 const struct usb_ctrlrequest *ctrl) 1289{ 1290 struct usb_request *req = fsg->ep0req; 1291 int value = -EOPNOTSUPP; 1292 u16 w_index = le16_to_cpu(ctrl->wIndex); 1293 u16 w_value = le16_to_cpu(ctrl->wValue); 1294 1295 /* Usually this just stores reply data in the pre-allocated ep0 buffer, 1296 * but config change events will also reconfigure hardware. */ 1297 switch (ctrl->bRequest) { 1298 1299 case USB_REQ_GET_DESCRIPTOR: 1300 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD | 1301 USB_RECIP_DEVICE)) 1302 break; 1303 switch (w_value >> 8) { 1304 1305 case USB_DT_DEVICE: 1306 VDBG(fsg, "get device descriptor\n"); 1307 value = sizeof device_desc; 1308 memcpy(req->buf, &device_desc, value); 1309 break; 1310#ifdef CONFIG_USB_GADGET_DUALSPEED 1311 case USB_DT_DEVICE_QUALIFIER: 1312 VDBG(fsg, "get device qualifier\n"); 1313 if (!fsg->gadget->is_dualspeed) 1314 break; 1315 value = sizeof dev_qualifier; 1316 memcpy(req->buf, &dev_qualifier, value); 1317 break; 1318 1319 case USB_DT_OTHER_SPEED_CONFIG: 1320 VDBG(fsg, "get other-speed config descriptor\n"); 1321 if (!fsg->gadget->is_dualspeed) 1322 break; 1323 goto get_config; 1324#endif 1325 case USB_DT_CONFIG: 1326 VDBG(fsg, "get configuration descriptor\n"); 1327#ifdef CONFIG_USB_GADGET_DUALSPEED 1328 get_config: 1329#endif 1330 value = populate_config_buf(fsg->gadget, 1331 req->buf, 1332 w_value >> 8, 1333 w_value & 0xff); 1334 break; 1335 1336 case USB_DT_STRING: 1337 VDBG(fsg, "get string descriptor\n"); 1338 1339 /* wIndex == language code */ 1340 value = usb_gadget_get_string(&stringtab, 1341 w_value & 0xff, req->buf); 1342 break; 1343 } 1344 break; 1345 1346 /* One config, two speeds */ 1347 case USB_REQ_SET_CONFIGURATION: 1348 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD | 1349 USB_RECIP_DEVICE)) 1350 break; 1351 VDBG(fsg, "set configuration\n"); 1352 if (w_value == CONFIG_VALUE || w_value == 0) { 1353 fsg->new_config = w_value; 1354 1355 /* Raise an exception to wipe out previous transaction 1356 * state (queued bufs, etc) and set the new config. */ 1357 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE); 1358 value = DELAYED_STATUS; 1359 } 1360 break; 1361 case USB_REQ_GET_CONFIGURATION: 1362 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD | 1363 USB_RECIP_DEVICE)) 1364 break; 1365 VDBG(fsg, "get configuration\n"); 1366 *(u8 *) req->buf = fsg->config; 1367 value = 1; 1368 break; 1369 1370 case USB_REQ_SET_INTERFACE: 1371 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD | 1372 USB_RECIP_INTERFACE)) 1373 break; 1374 if (fsg->config && w_index == 0) { 1375 1376 /* Raise an exception to wipe out previous transaction 1377 * state (queued bufs, etc) and install the new 1378 * interface altsetting. */ 1379 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE); 1380 value = DELAYED_STATUS; 1381 } 1382 break; 1383 case USB_REQ_GET_INTERFACE: 1384 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD | 1385 USB_RECIP_INTERFACE)) 1386 break; 1387 if (!fsg->config) 1388 break; 1389 if (w_index != 0) { 1390 value = -EDOM; 1391 break; 1392 } 1393 VDBG(fsg, "get interface\n"); 1394 *(u8 *) req->buf = 0; 1395 value = 1; 1396 break; 1397 1398 default: 1399 VDBG(fsg, 1400 "unknown control req %02x.%02x v%04x i%04x l%u\n", 1401 ctrl->bRequestType, ctrl->bRequest, 1402 w_value, w_index, le16_to_cpu(ctrl->wLength)); 1403 } 1404 1405 return value; 1406} 1407 1408 1409static int fsg_setup(struct usb_gadget *gadget, 1410 const struct usb_ctrlrequest *ctrl) 1411{ 1412 struct fsg_dev *fsg = get_gadget_data(gadget); 1413 int rc; 1414 int w_length = le16_to_cpu(ctrl->wLength); 1415 1416 ++fsg->ep0_req_tag; // Record arrival of a new request 1417 fsg->ep0req->context = NULL; 1418 fsg->ep0req->length = 0; 1419 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl)); 1420 1421 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) 1422 rc = class_setup_req(fsg, ctrl); 1423 else 1424 rc = standard_setup_req(fsg, ctrl); 1425 1426 /* Respond with data/status or defer until later? */ 1427 if (rc >= 0 && rc != DELAYED_STATUS) { 1428 rc = min(rc, w_length); 1429 fsg->ep0req->length = rc; 1430 fsg->ep0req->zero = rc < w_length; 1431 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ? 1432 "ep0-in" : "ep0-out"); 1433 rc = ep0_queue(fsg); 1434 } 1435 1436 /* Device either stalls (rc < 0) or reports success */ 1437 return rc; 1438} 1439 1440 1441/*-------------------------------------------------------------------------*/ 1442 1443/* All the following routines run in process context */ 1444 1445 1446/* Use this for bulk or interrupt transfers, not ep0 */ 1447static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep, 1448 struct usb_request *req, int *pbusy, 1449 enum fsg_buffer_state *state) 1450{ 1451 int rc; 1452 1453 if (ep == fsg->bulk_in) 1454 dump_msg(fsg, "bulk-in", req->buf, req->length); 1455 else if (ep == fsg->intr_in) 1456 dump_msg(fsg, "intr-in", req->buf, req->length); 1457 1458 spin_lock_irq(&fsg->lock); 1459 *pbusy = 1; 1460 *state = BUF_STATE_BUSY; 1461 spin_unlock_irq(&fsg->lock); 1462 rc = usb_ep_queue(ep, req, GFP_KERNEL); 1463 if (rc != 0) { 1464 *pbusy = 0; 1465 *state = BUF_STATE_EMPTY; 1466 1467 /* We can't do much more than wait for a reset */ 1468 1469 /* Note: currently the net2280 driver fails zero-length 1470 * submissions if DMA is enabled. */ 1471 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP && 1472 req->length == 0)) 1473 WARN(fsg, "error in submission: %s --> %d\n", 1474 ep->name, rc); 1475 } 1476} 1477 1478 1479static int sleep_thread(struct fsg_dev *fsg) 1480{ 1481 int rc = 0; 1482 1483 /* Wait until a signal arrives or we are woken up */ 1484 for (;;) { 1485 try_to_freeze(); 1486 set_current_state(TASK_INTERRUPTIBLE); 1487 if (signal_pending(current)) { 1488 rc = -EINTR; 1489 break; 1490 } 1491 if (fsg->thread_wakeup_needed) 1492 break; 1493 schedule(); 1494 } 1495 __set_current_state(TASK_RUNNING); 1496 fsg->thread_wakeup_needed = 0; 1497 return rc; 1498} 1499 1500 1501/*-------------------------------------------------------------------------*/ 1502 1503static int do_read(struct fsg_dev *fsg) 1504{ 1505 struct lun *curlun = fsg->curlun; 1506 u32 lba; 1507 struct fsg_buffhd *bh; 1508 int rc; 1509 u32 amount_left; 1510 loff_t file_offset, file_offset_tmp; 1511 unsigned int amount; 1512 unsigned int partial_page; 1513 ssize_t nread; 1514 1515 /* Get the starting Logical Block Address and check that it's 1516 * not too big */ 1517 if (fsg->cmnd[0] == SC_READ_6) 1518 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]); 1519 else { 1520 lba = get_be32(&fsg->cmnd[2]); 1521 1522 /* We allow DPO (Disable Page Out = don't save data in the 1523 * cache) and FUA (Force Unit Access = don't read from the 1524 * cache), but we don't implement them. */ 1525 if ((fsg->cmnd[1] & ~0x18) != 0) { 1526 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1527 return -EINVAL; 1528 } 1529 } 1530 if (lba >= curlun->num_sectors) { 1531 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1532 return -EINVAL; 1533 } 1534 file_offset = ((loff_t) lba) << 9; 1535 1536 /* Carry out the file reads */ 1537 amount_left = fsg->data_size_from_cmnd; 1538 if (unlikely(amount_left == 0)) 1539 return -EIO; // No default reply 1540 1541 for (;;) { 1542 1543 /* Figure out how much we need to read: 1544 * Try to read the remaining amount. 1545 * But don't read more than the buffer size. 1546 * And don't try to read past the end of the file. 1547 * Finally, if we're not at a page boundary, don't read past 1548 * the next page. 1549 * If this means reading 0 then we were asked to read past 1550 * the end of file. */ 1551 amount = min((unsigned int) amount_left, mod_data.buflen); 1552 amount = min((loff_t) amount, 1553 curlun->file_length - file_offset); 1554 partial_page = file_offset & (PAGE_CACHE_SIZE - 1); 1555 if (partial_page > 0) 1556 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE - 1557 partial_page); 1558 1559 /* Wait for the next buffer to become available */ 1560 bh = fsg->next_buffhd_to_fill; 1561 while (bh->state != BUF_STATE_EMPTY) { 1562 if ((rc = sleep_thread(fsg)) != 0) 1563 return rc; 1564 } 1565 1566 /* If we were asked to read past the end of file, 1567 * end with an empty buffer. */ 1568 if (amount == 0) { 1569 curlun->sense_data = 1570 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1571 curlun->sense_data_info = file_offset >> 9; 1572 curlun->info_valid = 1; 1573 bh->inreq->length = 0; 1574 bh->state = BUF_STATE_FULL; 1575 break; 1576 } 1577 1578 /* Perform the read */ 1579 file_offset_tmp = file_offset; 1580 nread = vfs_read(curlun->filp, 1581 (char __user *) bh->buf, 1582 amount, &file_offset_tmp); 1583 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, 1584 (unsigned long long) file_offset, 1585 (int) nread); 1586 if (signal_pending(current)) 1587 return -EINTR; 1588 1589 if (nread < 0) { 1590 LDBG(curlun, "error in file read: %d\n", 1591 (int) nread); 1592 nread = 0; 1593 } else if (nread < amount) { 1594 LDBG(curlun, "partial file read: %d/%u\n", 1595 (int) nread, amount); 1596 nread -= (nread & 511); // Round down to a block 1597 } 1598 file_offset += nread; 1599 amount_left -= nread; 1600 fsg->residue -= nread; 1601 bh->inreq->length = nread; 1602 bh->state = BUF_STATE_FULL; 1603 1604 /* If an error occurred, report it and its position */ 1605 if (nread < amount) { 1606 curlun->sense_data = SS_UNRECOVERED_READ_ERROR; 1607 curlun->sense_data_info = file_offset >> 9; 1608 curlun->info_valid = 1; 1609 break; 1610 } 1611 1612 if (amount_left == 0) 1613 break; // No more left to read 1614 1615 /* Send this buffer and go read some more */ 1616 bh->inreq->zero = 0; 1617 start_transfer(fsg, fsg->bulk_in, bh->inreq, 1618 &bh->inreq_busy, &bh->state); 1619 fsg->next_buffhd_to_fill = bh->next; 1620 } 1621 1622 return -EIO; // No default reply 1623} 1624 1625 1626/*-------------------------------------------------------------------------*/ 1627 1628static int do_write(struct fsg_dev *fsg) 1629{ 1630 struct lun *curlun = fsg->curlun; 1631 u32 lba; 1632 struct fsg_buffhd *bh; 1633 int get_some_more; 1634 u32 amount_left_to_req, amount_left_to_write; 1635 loff_t usb_offset, file_offset, file_offset_tmp; 1636 unsigned int amount; 1637 unsigned int partial_page; 1638 ssize_t nwritten; 1639 int rc; 1640 1641 if (curlun->ro) { 1642 curlun->sense_data = SS_WRITE_PROTECTED; 1643 return -EINVAL; 1644 } 1645 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait 1646 1647 /* Get the starting Logical Block Address and check that it's 1648 * not too big */ 1649 if (fsg->cmnd[0] == SC_WRITE_6) 1650 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]); 1651 else { 1652 lba = get_be32(&fsg->cmnd[2]); 1653 1654 /* We allow DPO (Disable Page Out = don't save data in the 1655 * cache) and FUA (Force Unit Access = write directly to the 1656 * medium). We don't implement DPO; we implement FUA by 1657 * performing synchronous output. */ 1658 if ((fsg->cmnd[1] & ~0x18) != 0) { 1659 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1660 return -EINVAL; 1661 } 1662 if (fsg->cmnd[1] & 0x08) // FUA 1663 curlun->filp->f_flags |= O_SYNC; 1664 } 1665 if (lba >= curlun->num_sectors) { 1666 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1667 return -EINVAL; 1668 } 1669 1670 /* Carry out the file writes */ 1671 get_some_more = 1; 1672 file_offset = usb_offset = ((loff_t) lba) << 9; 1673 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd; 1674 1675 while (amount_left_to_write > 0) { 1676 1677 /* Queue a request for more data from the host */ 1678 bh = fsg->next_buffhd_to_fill; 1679 if (bh->state == BUF_STATE_EMPTY && get_some_more) { 1680 1681 /* Figure out how much we want to get: 1682 * Try to get the remaining amount. 1683 * But don't get more than the buffer size. 1684 * And don't try to go past the end of the file. 1685 * If we're not at a page boundary, 1686 * don't go past the next page. 1687 * If this means getting 0, then we were asked 1688 * to write past the end of file. 1689 * Finally, round down to a block boundary. */ 1690 amount = min(amount_left_to_req, mod_data.buflen); 1691 amount = min((loff_t) amount, curlun->file_length - 1692 usb_offset); 1693 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1); 1694 if (partial_page > 0) 1695 amount = min(amount, 1696 (unsigned int) PAGE_CACHE_SIZE - partial_page); 1697 1698 if (amount == 0) { 1699 get_some_more = 0; 1700 curlun->sense_data = 1701 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1702 curlun->sense_data_info = usb_offset >> 9; 1703 curlun->info_valid = 1; 1704 continue; 1705 } 1706 amount -= (amount & 511); 1707 if (amount == 0) { 1708 1709 /* Why were we were asked to transfer a 1710 * partial block? */ 1711 get_some_more = 0; 1712 continue; 1713 } 1714 1715 /* Get the next buffer */ 1716 usb_offset += amount; 1717 fsg->usb_amount_left -= amount; 1718 amount_left_to_req -= amount; 1719 if (amount_left_to_req == 0) 1720 get_some_more = 0; 1721 1722 /* amount is always divisible by 512, hence by 1723 * the bulk-out maxpacket size */ 1724 bh->outreq->length = bh->bulk_out_intended_length = 1725 amount; 1726 bh->outreq->short_not_ok = 1; 1727 start_transfer(fsg, fsg->bulk_out, bh->outreq, 1728 &bh->outreq_busy, &bh->state); 1729 fsg->next_buffhd_to_fill = bh->next; 1730 continue; 1731 } 1732 1733 /* Write the received data to the backing file */ 1734 bh = fsg->next_buffhd_to_drain; 1735 if (bh->state == BUF_STATE_EMPTY && !get_some_more) 1736 break; // We stopped early 1737 if (bh->state == BUF_STATE_FULL) { 1738 smp_rmb(); 1739 fsg->next_buffhd_to_drain = bh->next; 1740 bh->state = BUF_STATE_EMPTY; 1741 1742 /* Did something go wrong with the transfer? */ 1743 if (bh->outreq->status != 0) { 1744 curlun->sense_data = SS_COMMUNICATION_FAILURE; 1745 curlun->sense_data_info = file_offset >> 9; 1746 curlun->info_valid = 1; 1747 break; 1748 } 1749 1750 amount = bh->outreq->actual; 1751 if (curlun->file_length - file_offset < amount) { 1752 LERROR(curlun, 1753 "write %u @ %llu beyond end %llu\n", 1754 amount, (unsigned long long) file_offset, 1755 (unsigned long long) curlun->file_length); 1756 amount = curlun->file_length - file_offset; 1757 } 1758 1759 /* Perform the write */ 1760 file_offset_tmp = file_offset; 1761 nwritten = vfs_write(curlun->filp, 1762 (char __user *) bh->buf, 1763 amount, &file_offset_tmp); 1764 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount, 1765 (unsigned long long) file_offset, 1766 (int) nwritten); 1767 if (signal_pending(current)) 1768 return -EINTR; // Interrupted! 1769 1770 if (nwritten < 0) { 1771 LDBG(curlun, "error in file write: %d\n", 1772 (int) nwritten); 1773 nwritten = 0; 1774 } else if (nwritten < amount) { 1775 LDBG(curlun, "partial file write: %d/%u\n", 1776 (int) nwritten, amount); 1777 nwritten -= (nwritten & 511); 1778 // Round down to a block 1779 } 1780 file_offset += nwritten; 1781 amount_left_to_write -= nwritten; 1782 fsg->residue -= nwritten; 1783 1784 /* If an error occurred, report it and its position */ 1785 if (nwritten < amount) { 1786 curlun->sense_data = SS_WRITE_ERROR; 1787 curlun->sense_data_info = file_offset >> 9; 1788 curlun->info_valid = 1; 1789 break; 1790 } 1791 1792 /* Did the host decide to stop early? */ 1793 if (bh->outreq->actual != bh->outreq->length) { 1794 fsg->short_packet_received = 1; 1795 break; 1796 } 1797 continue; 1798 } 1799 1800 /* Wait for something to happen */ 1801 if ((rc = sleep_thread(fsg)) != 0) 1802 return rc; 1803 } 1804 1805 return -EIO; // No default reply 1806} 1807 1808 1809/*-------------------------------------------------------------------------*/ 1810 1811/* Sync the file data, don't bother with the metadata. 1812 * This code was copied from fs/buffer.c:sys_fdatasync(). */ 1813static int fsync_sub(struct lun *curlun) 1814{ 1815 struct file *filp = curlun->filp; 1816 struct inode *inode; 1817 int rc, err; 1818 1819 if (curlun->ro || !filp) 1820 return 0; 1821 if (!filp->f_op->fsync) 1822 return -EINVAL; 1823 1824 inode = filp->f_path.dentry->d_inode; 1825 mutex_lock(&inode->i_mutex); 1826 rc = filemap_fdatawrite(inode->i_mapping); 1827 err = filp->f_op->fsync(filp, filp->f_path.dentry, 1); 1828 if (!rc) 1829 rc = err; 1830 err = filemap_fdatawait(inode->i_mapping); 1831 if (!rc) 1832 rc = err; 1833 mutex_unlock(&inode->i_mutex); 1834 VLDBG(curlun, "fdatasync -> %d\n", rc); 1835 return rc; 1836} 1837 1838static void fsync_all(struct fsg_dev *fsg) 1839{ 1840 int i; 1841 1842 for (i = 0; i < fsg->nluns; ++i) 1843 fsync_sub(&fsg->luns[i]); 1844} 1845 1846static int do_synchronize_cache(struct fsg_dev *fsg) 1847{ 1848 struct lun *curlun = fsg->curlun; 1849 int rc; 1850 1851 /* We ignore the requested LBA and write out all file's 1852 * dirty data buffers. */ 1853 rc = fsync_sub(curlun); 1854 if (rc) 1855 curlun->sense_data = SS_WRITE_ERROR; 1856 return 0; 1857} 1858 1859 1860/*-------------------------------------------------------------------------*/ 1861 1862static void invalidate_sub(struct lun *curlun) 1863{ 1864 struct file *filp = curlun->filp; 1865 struct inode *inode = filp->f_path.dentry->d_inode; 1866 unsigned long rc; 1867 1868 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1); 1869 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc); 1870} 1871 1872static int do_verify(struct fsg_dev *fsg) 1873{ 1874 struct lun *curlun = fsg->curlun; 1875 u32 lba; 1876 u32 verification_length; 1877 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill; 1878 loff_t file_offset, file_offset_tmp; 1879 u32 amount_left; 1880 unsigned int amount; 1881 ssize_t nread; 1882 1883 /* Get the starting Logical Block Address and check that it's 1884 * not too big */ 1885 lba = get_be32(&fsg->cmnd[2]); 1886 if (lba >= curlun->num_sectors) { 1887 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1888 return -EINVAL; 1889 } 1890 1891 /* We allow DPO (Disable Page Out = don't save data in the 1892 * cache) but we don't implement it. */ 1893 if ((fsg->cmnd[1] & ~0x10) != 0) { 1894 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1895 return -EINVAL; 1896 } 1897 1898 verification_length = get_be16(&fsg->cmnd[7]); 1899 if (unlikely(verification_length == 0)) 1900 return -EIO; // No default reply 1901 1902 /* Prepare to carry out the file verify */ 1903 amount_left = verification_length << 9; 1904 file_offset = ((loff_t) lba) << 9; 1905 1906 /* Write out all the dirty buffers before invalidating them */ 1907 fsync_sub(curlun); 1908 if (signal_pending(current)) 1909 return -EINTR; 1910 1911 invalidate_sub(curlun); 1912 if (signal_pending(current)) 1913 return -EINTR; 1914 1915 /* Just try to read the requested blocks */ 1916 while (amount_left > 0) { 1917 1918 /* Figure out how much we need to read: 1919 * Try to read the remaining amount, but not more than 1920 * the buffer size. 1921 * And don't try to read past the end of the file. 1922 * If this means reading 0 then we were asked to read 1923 * past the end of file. */ 1924 amount = min((unsigned int) amount_left, mod_data.buflen); 1925 amount = min((loff_t) amount, 1926 curlun->file_length - file_offset); 1927 if (amount == 0) { 1928 curlun->sense_data = 1929 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1930 curlun->sense_data_info = file_offset >> 9; 1931 curlun->info_valid = 1; 1932 break; 1933 } 1934 1935 /* Perform the read */ 1936 file_offset_tmp = file_offset; 1937 nread = vfs_read(curlun->filp, 1938 (char __user *) bh->buf, 1939 amount, &file_offset_tmp); 1940 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, 1941 (unsigned long long) file_offset, 1942 (int) nread); 1943 if (signal_pending(current)) 1944 return -EINTR; 1945 1946 if (nread < 0) { 1947 LDBG(curlun, "error in file verify: %d\n", 1948 (int) nread); 1949 nread = 0; 1950 } else if (nread < amount) { 1951 LDBG(curlun, "partial file verify: %d/%u\n", 1952 (int) nread, amount); 1953 nread -= (nread & 511); // Round down to a sector 1954 } 1955 if (nread == 0) { 1956 curlun->sense_data = SS_UNRECOVERED_READ_ERROR; 1957 curlun->sense_data_info = file_offset >> 9; 1958 curlun->info_valid = 1; 1959 break; 1960 } 1961 file_offset += nread; 1962 amount_left -= nread; 1963 } 1964 return 0; 1965} 1966 1967 1968/*-------------------------------------------------------------------------*/ 1969 1970static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh) 1971{ 1972 u8 *buf = (u8 *) bh->buf; 1973 1974 static char vendor_id[] = "Linux "; 1975 static char product_id[] = "File-Stor Gadget"; 1976 1977 if (!fsg->curlun) { // Unsupported LUNs are okay 1978 fsg->bad_lun_okay = 1; 1979 memset(buf, 0, 36); 1980 buf[0] = 0x7f; // Unsupported, no device-type 1981 return 36; 1982 } 1983 1984 memset(buf, 0, 8); // Non-removable, direct-access device 1985 if (mod_data.removable) 1986 buf[1] = 0x80; 1987 buf[2] = 2; // ANSI SCSI level 2 1988 buf[3] = 2; // SCSI-2 INQUIRY data format 1989 buf[4] = 31; // Additional length 1990 // No special options 1991 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id, 1992 mod_data.release); 1993 return 36; 1994} 1995 1996 1997static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh) 1998{ 1999 struct lun *curlun = fsg->curlun; 2000 u8 *buf = (u8 *) bh->buf; 2001 u32 sd, sdinfo; 2002 int valid; 2003 2004 /* 2005 * From the SCSI-2 spec., section 7.9 (Unit attention condition): 2006 * 2007 * If a REQUEST SENSE command is received from an initiator 2008 * with a pending unit attention condition (before the target 2009 * generates the contingent allegiance condition), then the 2010 * target shall either: 2011 * a) report any pending sense data and preserve the unit 2012 * attention condition on the logical unit, or, 2013 * b) report the unit attention condition, may discard any 2014 * pending sense data, and clear the unit attention 2015 * condition on the logical unit for that initiator. 2016 * 2017 * FSG normally uses option a); enable this code to use option b). 2018 */ 2019 2020 if (!curlun) { // Unsupported LUNs are okay 2021 fsg->bad_lun_okay = 1; 2022 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; 2023 sdinfo = 0; 2024 valid = 0; 2025 } else { 2026 sd = curlun->sense_data; 2027 sdinfo = curlun->sense_data_info; 2028 valid = curlun->info_valid << 7; 2029 curlun->sense_data = SS_NO_SENSE; 2030 curlun->sense_data_info = 0; 2031 curlun->info_valid = 0; 2032 } 2033 2034 memset(buf, 0, 18); 2035 buf[0] = valid | 0x70; // Valid, current error 2036 buf[2] = SK(sd); 2037 put_be32(&buf[3], sdinfo); // Sense information 2038 buf[7] = 18 - 8; // Additional sense length 2039 buf[12] = ASC(sd); 2040 buf[13] = ASCQ(sd); 2041 return 18; 2042} 2043 2044 2045static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh) 2046{ 2047 struct lun *curlun = fsg->curlun; 2048 u32 lba = get_be32(&fsg->cmnd[2]); 2049 int pmi = fsg->cmnd[8]; 2050 u8 *buf = (u8 *) bh->buf; 2051 2052 /* Check the PMI and LBA fields */ 2053 if (pmi > 1 || (pmi == 0 && lba != 0)) { 2054 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 2055 return -EINVAL; 2056 } 2057 2058 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block 2059 put_be32(&buf[4], 512); // Block length 2060 return 8; 2061} 2062 2063 2064static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh) 2065{ 2066 struct lun *curlun = fsg->curlun; 2067 int mscmnd = fsg->cmnd[0]; 2068 u8 *buf = (u8 *) bh->buf; 2069 u8 *buf0 = buf; 2070 int pc, page_code; 2071 int changeable_values, all_pages; 2072 int valid_page = 0; 2073 int len, limit; 2074 2075 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD 2076 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 2077 return -EINVAL; 2078 } 2079 pc = fsg->cmnd[2] >> 6; 2080 page_code = fsg->cmnd[2] & 0x3f; 2081 if (pc == 3) { 2082 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED; 2083 return -EINVAL; 2084 } 2085 changeable_values = (pc == 1); 2086 all_pages = (page_code == 0x3f); 2087 2088 /* Write the mode parameter header. Fixed values are: default 2089 * medium type, no cache control (DPOFUA), and no block descriptors. 2090 * The only variable value is the WriteProtect bit. We will fill in 2091 * the mode data length later. */ 2092 memset(buf, 0, 8); 2093 if (mscmnd == SC_MODE_SENSE_6) { 2094 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA 2095 buf += 4; 2096 limit = 255; 2097 } else { // SC_MODE_SENSE_10 2098 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA 2099 buf += 8; 2100 limit = 65535; // Should really be mod_data.buflen 2101 } 2102 2103 /* No block descriptors */ 2104 2105 /* The mode pages, in numerical order. The only page we support 2106 * is the Caching page. */ 2107 if (page_code == 0x08 || all_pages) { 2108 valid_page = 1; 2109 buf[0] = 0x08; // Page code 2110 buf[1] = 10; // Page length 2111 memset(buf+2, 0, 10); // None of the fields are changeable 2112 2113 if (!changeable_values) { 2114 buf[2] = 0x04; // Write cache enable, 2115 // Read cache not disabled 2116 // No cache retention priorities 2117 put_be16(&buf[4], 0xffff); // Don't disable prefetch 2118 // Minimum prefetch = 0 2119 put_be16(&buf[8], 0xffff); // Maximum prefetch 2120 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling 2121 } 2122 buf += 12; 2123 } 2124 2125 /* Check that a valid page was requested and the mode data length 2126 * isn't too long. */ 2127 len = buf - buf0; 2128 if (!valid_page || len > limit) { 2129 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 2130 return -EINVAL; 2131 } 2132 2133 /* Store the mode data length */ 2134 if (mscmnd == SC_MODE_SENSE_6) 2135 buf0[0] = len - 1; 2136 else 2137 put_be16(buf0, len - 2); 2138 return len; 2139} 2140 2141 2142static int do_start_stop(struct fsg_dev *fsg) 2143{ 2144 struct lun *curlun = fsg->curlun; 2145 int loej, start; 2146 2147 if (!mod_data.removable) { 2148 curlun->sense_data = SS_INVALID_COMMAND; 2149 return -EINVAL; 2150 } 2151 2152 // int immed = fsg->cmnd[1] & 0x01; 2153 loej = fsg->cmnd[4] & 0x02; 2154 start = fsg->cmnd[4] & 0x01; 2155 2156#ifdef CONFIG_USB_FILE_STORAGE_TEST 2157 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed 2158 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start 2159 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 2160 return -EINVAL; 2161 } 2162 2163 if (!start) { 2164 2165 /* Are we allowed to unload the media? */ 2166 if (curlun->prevent_medium_removal) { 2167 LDBG(curlun, "unload attempt prevented\n"); 2168 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED; 2169 return -EINVAL; 2170 } 2171 if (loej) { // Simulate an unload/eject 2172 up_read(&fsg->filesem); 2173 down_write(&fsg->filesem); 2174 close_backing_file(curlun); 2175 up_write(&fsg->filesem); 2176 down_read(&fsg->filesem); 2177 } 2178 } else { 2179 2180 /* Our emulation doesn't support mounting; the medium is 2181 * available for use as soon as it is loaded. */ 2182 if (!backing_file_is_open(curlun)) { 2183 curlun->sense_data = SS_MEDIUM_NOT_PRESENT; 2184 return -EINVAL; 2185 } 2186 } 2187#endif 2188 return 0; 2189} 2190 2191 2192static int do_prevent_allow(struct fsg_dev *fsg) 2193{ 2194 struct lun *curlun = fsg->curlun; 2195 int prevent; 2196 2197 if (!mod_data.removable) { 2198 curlun->sense_data = SS_INVALID_COMMAND; 2199 return -EINVAL; 2200 } 2201 2202 prevent = fsg->cmnd[4] & 0x01; 2203 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent 2204 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 2205 return -EINVAL; 2206 } 2207 2208 if (curlun->prevent_medium_removal && !prevent) 2209 fsync_sub(curlun); 2210 curlun->prevent_medium_removal = prevent; 2211 return 0; 2212} 2213 2214 2215static int do_read_format_capacities(struct fsg_dev *fsg, 2216 struct fsg_buffhd *bh) 2217{ 2218 struct lun *curlun = fsg->curlun; 2219 u8 *buf = (u8 *) bh->buf; 2220 2221 buf[0] = buf[1] = buf[2] = 0; 2222 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor 2223 buf += 4; 2224 2225 put_be32(&buf[0], curlun->num_sectors); // Number of blocks 2226 put_be32(&buf[4], 512); // Block length 2227 buf[4] = 0x02; // Current capacity 2228 return 12; 2229} 2230 2231 2232static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh) 2233{ 2234 struct lun *curlun = fsg->curlun; 2235 2236 /* We don't support MODE SELECT */ 2237 curlun->sense_data = SS_INVALID_COMMAND; 2238 return -EINVAL; 2239} 2240 2241 2242/*-------------------------------------------------------------------------*/ 2243 2244static int halt_bulk_in_endpoint(struct fsg_dev *fsg) 2245{ 2246 int rc; 2247 2248 rc = fsg_set_halt(fsg, fsg->bulk_in); 2249 if (rc == -EAGAIN) 2250 VDBG(fsg, "delayed bulk-in endpoint halt\n"); 2251 while (rc != 0) { 2252 if (rc != -EAGAIN) { 2253 WARN(fsg, "usb_ep_set_halt -> %d\n", rc); 2254 rc = 0; 2255 break; 2256 } 2257 2258 /* Wait for a short time and then try again */ 2259 if (msleep_interruptible(100) != 0) 2260 return -EINTR; 2261 rc = usb_ep_set_halt(fsg->bulk_in); 2262 } 2263 return rc; 2264} 2265 2266static int pad_with_zeros(struct fsg_dev *fsg) 2267{ 2268 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill; 2269 u32 nkeep = bh->inreq->length; 2270 u32 nsend; 2271 int rc; 2272 2273 bh->state = BUF_STATE_EMPTY; // For the first iteration 2274 fsg->usb_amount_left = nkeep + fsg->residue; 2275 while (fsg->usb_amount_left > 0) { 2276 2277 /* Wait for the next buffer to be free */ 2278 while (bh->state != BUF_STATE_EMPTY) { 2279 if ((rc = sleep_thread(fsg)) != 0) 2280 return rc; 2281 } 2282 2283 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen); 2284 memset(bh->buf + nkeep, 0, nsend - nkeep); 2285 bh->inreq->length = nsend; 2286 bh->inreq->zero = 0; 2287 start_transfer(fsg, fsg->bulk_in, bh->inreq, 2288 &bh->inreq_busy, &bh->state); 2289 bh = fsg->next_buffhd_to_fill = bh->next; 2290 fsg->usb_amount_left -= nsend; 2291 nkeep = 0; 2292 } 2293 return 0; 2294} 2295 2296static int throw_away_data(struct fsg_dev *fsg) 2297{ 2298 struct fsg_buffhd *bh; 2299 u32 amount; 2300 int rc; 2301 2302 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY || 2303 fsg->usb_amount_left > 0) { 2304 2305 /* Throw away the data in a filled buffer */ 2306 if (bh->state == BUF_STATE_FULL) { 2307 smp_rmb(); 2308 bh->state = BUF_STATE_EMPTY; 2309 fsg->next_buffhd_to_drain = bh->next; 2310 2311 /* A short packet or an error ends everything */ 2312 if (bh->outreq->actual != bh->outreq->length || 2313 bh->outreq->status != 0) { 2314 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT); 2315 return -EINTR; 2316 } 2317 continue; 2318 } 2319 2320 /* Try to submit another request if we need one */ 2321 bh = fsg->next_buffhd_to_fill; 2322 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) { 2323 amount = min(fsg->usb_amount_left, 2324 (u32) mod_data.buflen); 2325 2326 /* amount is always divisible by 512, hence by 2327 * the bulk-out maxpacket size */ 2328 bh->outreq->length = bh->bulk_out_intended_length = 2329 amount; 2330 bh->outreq->short_not_ok = 1; 2331 start_transfer(fsg, fsg->bulk_out, bh->outreq, 2332 &bh->outreq_busy, &bh->state); 2333 fsg->next_buffhd_to_fill = bh->next; 2334 fsg->usb_amount_left -= amount; 2335 continue; 2336 } 2337 2338 /* Otherwise wait for something to happen */ 2339 if ((rc = sleep_thread(fsg)) != 0) 2340 return rc; 2341 } 2342 return 0; 2343} 2344 2345 2346static int finish_reply(struct fsg_dev *fsg) 2347{ 2348 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill; 2349 int rc = 0; 2350 2351 switch (fsg->data_dir) { 2352 case DATA_DIR_NONE: 2353 break; // Nothing to send 2354 2355 /* If we don't know whether the host wants to read or write, 2356 * this must be CB or CBI with an unknown command. We mustn't 2357 * try to send or receive any data. So stall both bulk pipes 2358 * if we can and wait for a reset. */ 2359 case DATA_DIR_UNKNOWN: 2360 if (mod_data.can_stall) { 2361 fsg_set_halt(fsg, fsg->bulk_out); 2362 rc = halt_bulk_in_endpoint(fsg); 2363 } 2364 break; 2365 2366 /* All but the last buffer of data must have already been sent */ 2367 case DATA_DIR_TO_HOST: 2368 if (fsg->data_size == 0) 2369 ; // Nothing to send 2370 2371 /* If there's no residue, simply send the last buffer */ 2372 else if (fsg->residue == 0) { 2373 bh->inreq->zero = 0; 2374 start_transfer(fsg, fsg->bulk_in, bh->inreq, 2375 &bh->inreq_busy, &bh->state); 2376 fsg->next_buffhd_to_fill = bh->next; 2377 } 2378 2379 /* There is a residue. For CB and CBI, simply mark the end 2380 * of the data with a short packet. However, if we are 2381 * allowed to stall, there was no data at all (residue == 2382 * data_size), and the command failed (invalid LUN or 2383 * sense data is set), then halt the bulk-in endpoint 2384 * instead. */ 2385 else if (!transport_is_bbb()) { 2386 if (mod_data.can_stall && 2387 fsg->residue == fsg->data_size && 2388 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) { 2389 bh->state = BUF_STATE_EMPTY; 2390 rc = halt_bulk_in_endpoint(fsg); 2391 } else { 2392 bh->inreq->zero = 1; 2393 start_transfer(fsg, fsg->bulk_in, bh->inreq, 2394 &bh->inreq_busy, &bh->state); 2395 fsg->next_buffhd_to_fill = bh->next; 2396 } 2397 } 2398 2399 /* For Bulk-only, if we're allowed to stall then send the 2400 * short packet and halt the bulk-in endpoint. If we can't 2401 * stall, pad out the remaining data with 0's. */ 2402 else { 2403 if (mod_data.can_stall) { 2404 bh->inreq->zero = 1; 2405 start_transfer(fsg, fsg->bulk_in, bh->inreq, 2406 &bh->inreq_busy, &bh->state); 2407 fsg->next_buffhd_to_fill = bh->next; 2408 rc = halt_bulk_in_endpoint(fsg); 2409 } else 2410 rc = pad_with_zeros(fsg); 2411 } 2412 break; 2413 2414 /* We have processed all we want from the data the host has sent. 2415 * There may still be outstanding bulk-out requests. */ 2416 case DATA_DIR_FROM_HOST: 2417 if (fsg->residue == 0) 2418 ; // Nothing to receive 2419 2420 /* Did the host stop sending unexpectedly early? */ 2421 else if (fsg->short_packet_received) { 2422 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT); 2423 rc = -EINTR; 2424 } 2425 2426 /* We haven't processed all the incoming data. Even though 2427 * we may be allowed to stall, doing so would cause a race. 2428 * The controller may already have ACK'ed all the remaining 2429 * bulk-out packets, in which case the host wouldn't see a 2430 * STALL. Not realizing the endpoint was halted, it wouldn't 2431 * clear the halt -- leading to problems later on. */ 2432 2433 /* We can't stall. Read in the excess data and throw it 2434 * all away. */ 2435 else 2436 rc = throw_away_data(fsg); 2437 break; 2438 } 2439 return rc; 2440} 2441 2442 2443static int send_status(struct fsg_dev *fsg) 2444{ 2445 struct lun *curlun = fsg->curlun; 2446 struct fsg_buffhd *bh; 2447 int rc; 2448 u8 status = USB_STATUS_PASS; 2449 u32 sd, sdinfo = 0; 2450 2451 /* Wait for the next buffer to become available */ 2452 bh = fsg->next_buffhd_to_fill; 2453 while (bh->state != BUF_STATE_EMPTY) { 2454 if ((rc = sleep_thread(fsg)) != 0) 2455 return rc; 2456 } 2457 2458 if (curlun) { 2459 sd = curlun->sense_data; 2460 sdinfo = curlun->sense_data_info; 2461 } else if (fsg->bad_lun_okay) 2462 sd = SS_NO_SENSE; 2463 else 2464 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; 2465 2466 if (fsg->phase_error) { 2467 DBG(fsg, "sending phase-error status\n"); 2468 status = USB_STATUS_PHASE_ERROR; 2469 sd = SS_INVALID_COMMAND; 2470 } else if (sd != SS_NO_SENSE) { 2471 DBG(fsg, "sending command-failure status\n"); 2472 status = USB_STATUS_FAIL; 2473 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;" 2474 " info x%x\n", 2475 SK(sd), ASC(sd), ASCQ(sd), sdinfo); 2476 } 2477 2478 if (transport_is_bbb()) { 2479 struct bulk_cs_wrap *csw = bh->buf; 2480 2481 /* Store and send the Bulk-only CSW */ 2482 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG); 2483 csw->Tag = fsg->tag; 2484 csw->Residue = cpu_to_le32(fsg->residue); 2485 csw->Status = status; 2486 2487 bh->inreq->length = USB_BULK_CS_WRAP_LEN; 2488 bh->inreq->zero = 0; 2489 start_transfer(fsg, fsg->bulk_in, bh->inreq, 2490 &bh->inreq_busy, &bh->state); 2491 2492 } else if (mod_data.transport_type == USB_PR_CB) { 2493 2494 /* Control-Bulk transport has no status phase! */ 2495 return 0; 2496 2497 } else { // USB_PR_CBI 2498 struct interrupt_data *buf = bh->buf; 2499 2500 /* Store and send the Interrupt data. UFI sends the ASC 2501 * and ASCQ bytes. Everything else sends a Type (which 2502 * is always 0) and the status Value. */ 2503 if (mod_data.protocol_type == USB_SC_UFI) { 2504 buf->bType = ASC(sd); 2505 buf->bValue = ASCQ(sd); 2506 } else { 2507 buf->bType = 0; 2508 buf->bValue = status; 2509 } 2510 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN; 2511 2512 fsg->intr_buffhd = bh; // Point to the right buffhd 2513 fsg->intreq->buf = bh->inreq->buf; 2514 fsg->intreq->dma = bh->inreq->dma; 2515 fsg->intreq->context = bh; 2516 start_transfer(fsg, fsg->intr_in, fsg->intreq, 2517 &fsg->intreq_busy, &bh->state); 2518 } 2519 2520 fsg->next_buffhd_to_fill = bh->next; 2521 return 0; 2522} 2523 2524 2525/*-------------------------------------------------------------------------*/ 2526 2527/* Check whether the command is properly formed and whether its data size 2528 * and direction agree with the values we already have. */ 2529static int check_command(struct fsg_dev *fsg, int cmnd_size, 2530 enum data_direction data_dir, unsigned int mask, 2531 int needs_medium, const char *name) 2532{ 2533 int i; 2534 int lun = fsg->cmnd[1] >> 5; 2535 static const char dirletter[4] = {'u', 'o', 'i', 'n'}; 2536 char hdlen[20]; 2537 struct lun *curlun; 2538 2539 /* Adjust the expected cmnd_size for protocol encapsulation padding. 2540 * Transparent SCSI doesn't pad. */ 2541 if (protocol_is_scsi()) 2542 ; 2543 2544 /* There's some disagreement as to whether RBC pads commands or not. 2545 * We'll play it safe and accept either form. */ 2546 else if (mod_data.protocol_type == USB_SC_RBC) { 2547 if (fsg->cmnd_size == 12) 2548 cmnd_size = 12; 2549 2550 /* All the other protocols pad to 12 bytes */ 2551 } else 2552 cmnd_size = 12; 2553 2554 hdlen[0] = 0; 2555 if (fsg->data_dir != DATA_DIR_UNKNOWN) 2556 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir], 2557 fsg->data_size); 2558 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n", 2559 name, cmnd_size, dirletter[(int) data_dir], 2560 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen); 2561 2562 /* We can't reply at all until we know the correct data direction 2563 * and size. */ 2564 if (fsg->data_size_from_cmnd == 0) 2565 data_dir = DATA_DIR_NONE; 2566 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI 2567 fsg->data_dir = data_dir; 2568 fsg->data_size = fsg->data_size_from_cmnd; 2569 2570 } else { // Bulk-only 2571 if (fsg->data_size < fsg->data_size_from_cmnd) { 2572 2573 /* Host data size < Device data size is a phase error. 2574 * Carry out the command, but only transfer as much 2575 * as we are allowed. */ 2576 fsg->data_size_from_cmnd = fsg->data_size; 2577 fsg->phase_error = 1; 2578 } 2579 } 2580 fsg->residue = fsg->usb_amount_left = fsg->data_size; 2581 2582 /* Conflicting data directions is a phase error */ 2583 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) { 2584 fsg->phase_error = 1; 2585 return -EINVAL; 2586 } 2587 2588 /* Verify the length of the command itself */ 2589 if (cmnd_size != fsg->cmnd_size) { 2590 2591 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12) 2592 cmnd_size = fsg->cmnd_size; 2593 else { 2594 fsg->phase_error = 1; 2595 return -EINVAL; 2596 } 2597 } 2598 2599 /* Check that the LUN values are consistent */ 2600 if (transport_is_bbb()) { 2601 if (fsg->lun != lun) 2602 DBG(fsg, "using LUN %d from CBW, " 2603 "not LUN %d from CDB\n", 2604 fsg->lun, lun); 2605 } else 2606 fsg->lun = lun; // Use LUN from the command 2607 2608 /* Check the LUN */ 2609 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) { 2610 fsg->curlun = curlun = &fsg->luns[fsg->lun]; 2611 if (fsg->cmnd[0] != SC_REQUEST_SENSE) { 2612 curlun->sense_data = SS_NO_SENSE; 2613 curlun->sense_data_info = 0; 2614 curlun->info_valid = 0; 2615 } 2616 } else { 2617 fsg->curlun = curlun = NULL; 2618 fsg->bad_lun_okay = 0; 2619 2620 /* INQUIRY and REQUEST SENSE commands are explicitly allowed 2621 * to use unsupported LUNs; all others may not. */ 2622 if (fsg->cmnd[0] != SC_INQUIRY && 2623 fsg->cmnd[0] != SC_REQUEST_SENSE) { 2624 DBG(fsg, "unsupported LUN %d\n", fsg->lun); 2625 return -EINVAL; 2626 } 2627 } 2628 2629 /* If a unit attention condition exists, only INQUIRY and 2630 * REQUEST SENSE commands are allowed; anything else must fail. */ 2631 if (curlun && curlun->unit_attention_data != SS_NO_SENSE && 2632 fsg->cmnd[0] != SC_INQUIRY && 2633 fsg->cmnd[0] != SC_REQUEST_SENSE) { 2634 curlun->sense_data = curlun->unit_attention_data; 2635 curlun->unit_attention_data = SS_NO_SENSE; 2636 return -EINVAL; 2637 } 2638 2639 /* Check that only command bytes listed in the mask are non-zero */ 2640 fsg->cmnd[1] &= 0x1f; // Mask away the LUN 2641 for (i = 1; i < cmnd_size; ++i) { 2642 if (fsg->cmnd[i] && !(mask & (1 << i))) { 2643 if (curlun) 2644 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 2645 return -EINVAL; 2646 } 2647 } 2648 2649 /* If the medium isn't mounted and the command needs to access 2650 * it, return an error. */ 2651 if (curlun && !backing_file_is_open(curlun) && needs_medium) { 2652 curlun->sense_data = SS_MEDIUM_NOT_PRESENT; 2653 return -EINVAL; 2654 } 2655 2656 return 0; 2657} 2658 2659 2660static int do_scsi_command(struct fsg_dev *fsg) 2661{ 2662 struct fsg_buffhd *bh; 2663 int rc; 2664 int reply = -EINVAL; 2665 int i; 2666 static char unknown[16]; 2667 2668 dump_cdb(fsg); 2669 2670 /* Wait for the next buffer to become available for data or status */ 2671 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill; 2672 while (bh->state != BUF_STATE_EMPTY) { 2673 if ((rc = sleep_thread(fsg)) != 0) 2674 return rc; 2675 } 2676 fsg->phase_error = 0; 2677 fsg->short_packet_received = 0; 2678 2679 down_read(&fsg->filesem); // We're using the backing file 2680 switch (fsg->cmnd[0]) { 2681 2682 case SC_INQUIRY: 2683 fsg->data_size_from_cmnd = fsg->cmnd[4]; 2684 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST, 2685 (1<<4), 0, 2686 "INQUIRY")) == 0) 2687 reply = do_inquiry(fsg, bh); 2688 break; 2689 2690 case SC_MODE_SELECT_6: 2691 fsg->data_size_from_cmnd = fsg->cmnd[4]; 2692 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST, 2693 (1<<1) | (1<<4), 0, 2694 "MODE SELECT(6)")) == 0) 2695 reply = do_mode_select(fsg, bh); 2696 break; 2697 2698 case SC_MODE_SELECT_10: 2699 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]); 2700 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST, 2701 (1<<1) | (3<<7), 0, 2702 "MODE SELECT(10)")) == 0) 2703 reply = do_mode_select(fsg, bh); 2704 break; 2705 2706 case SC_MODE_SENSE_6: 2707 fsg->data_size_from_cmnd = fsg->cmnd[4]; 2708 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST, 2709 (1<<1) | (1<<2) | (1<<4), 0, 2710 "MODE SENSE(6)")) == 0) 2711 reply = do_mode_sense(fsg, bh); 2712 break; 2713 2714 case SC_MODE_SENSE_10: 2715 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]); 2716 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST, 2717 (1<<1) | (1<<2) | (3<<7), 0, 2718 "MODE SENSE(10)")) == 0) 2719 reply = do_mode_sense(fsg, bh); 2720 break; 2721 2722 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL: 2723 fsg->data_size_from_cmnd = 0; 2724 if ((reply = check_command(fsg, 6, DATA_DIR_NONE, 2725 (1<<4), 0, 2726 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0) 2727 reply = do_prevent_allow(fsg); 2728 break; 2729 2730 case SC_READ_6: 2731 i = fsg->cmnd[4]; 2732 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9; 2733 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST, 2734 (7<<1) | (1<<4), 1, 2735 "READ(6)")) == 0) 2736 reply = do_read(fsg); 2737 break; 2738 2739 case SC_READ_10: 2740 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9; 2741 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST, 2742 (1<<1) | (0xf<<2) | (3<<7), 1, 2743 "READ(10)")) == 0) 2744 reply = do_read(fsg); 2745 break; 2746 2747 case SC_READ_12: 2748 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9; 2749 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST, 2750 (1<<1) | (0xf<<2) | (0xf<<6), 1, 2751 "READ(12)")) == 0) 2752 reply = do_read(fsg); 2753 break; 2754 2755 case SC_READ_CAPACITY: 2756 fsg->data_size_from_cmnd = 8; 2757 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST, 2758 (0xf<<2) | (1<<8), 1, 2759 "READ CAPACITY")) == 0) 2760 reply = do_read_capacity(fsg, bh); 2761 break; 2762 2763 case SC_READ_FORMAT_CAPACITIES: 2764 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]); 2765 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST, 2766 (3<<7), 1, 2767 "READ FORMAT CAPACITIES")) == 0) 2768 reply = do_read_format_capacities(fsg, bh); 2769 break; 2770 2771 case SC_REQUEST_SENSE: 2772 fsg->data_size_from_cmnd = fsg->cmnd[4]; 2773 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST, 2774 (1<<4), 0, 2775 "REQUEST SENSE")) == 0) 2776 reply = do_request_sense(fsg, bh); 2777 break; 2778 2779 case SC_START_STOP_UNIT: 2780 fsg->data_size_from_cmnd = 0; 2781 if ((reply = check_command(fsg, 6, DATA_DIR_NONE, 2782 (1<<1) | (1<<4), 0, 2783 "START-STOP UNIT")) == 0) 2784 reply = do_start_stop(fsg); 2785 break; 2786 2787 case SC_SYNCHRONIZE_CACHE: 2788 fsg->data_size_from_cmnd = 0; 2789 if ((reply = check_command(fsg, 10, DATA_DIR_NONE, 2790 (0xf<<2) | (3<<7), 1, 2791 "SYNCHRONIZE CACHE")) == 0) 2792 reply = do_synchronize_cache(fsg); 2793 break; 2794 2795 case SC_TEST_UNIT_READY: 2796 fsg->data_size_from_cmnd = 0; 2797 reply = check_command(fsg, 6, DATA_DIR_NONE, 2798 0, 1, 2799 "TEST UNIT READY"); 2800 break; 2801 2802 /* Although optional, this command is used by MS-Windows. We 2803 * support a minimal version: BytChk must be 0. */ 2804 case SC_VERIFY: 2805 fsg->data_size_from_cmnd = 0; 2806 if ((reply = check_command(fsg, 10, DATA_DIR_NONE, 2807 (1<<1) | (0xf<<2) | (3<<7), 1, 2808 "VERIFY")) == 0) 2809 reply = do_verify(fsg); 2810 break; 2811 2812 case SC_WRITE_6: 2813 i = fsg->cmnd[4]; 2814 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9; 2815 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST, 2816 (7<<1) | (1<<4), 1, 2817 "WRITE(6)")) == 0) 2818 reply = do_write(fsg); 2819 break; 2820 2821 case SC_WRITE_10: 2822 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9; 2823 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST, 2824 (1<<1) | (0xf<<2) | (3<<7), 1, 2825 "WRITE(10)")) == 0) 2826 reply = do_write(fsg); 2827 break; 2828 2829 case SC_WRITE_12: 2830 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9; 2831 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST, 2832 (1<<1) | (0xf<<2) | (0xf<<6), 1, 2833 "WRITE(12)")) == 0) 2834 reply = do_write(fsg); 2835 break; 2836 2837 /* Some mandatory commands that we recognize but don't implement. 2838 * They don't mean much in this setting. It's left as an exercise 2839 * for anyone interested to implement RESERVE and RELEASE in terms 2840 * of Posix locks. */ 2841 case SC_FORMAT_UNIT: 2842 case SC_RELEASE: 2843 case SC_RESERVE: 2844 case SC_SEND_DIAGNOSTIC: 2845 // Fall through 2846 2847 default: 2848 fsg->data_size_from_cmnd = 0; 2849 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]); 2850 if ((reply = check_command(fsg, fsg->cmnd_size, 2851 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) { 2852 fsg->curlun->sense_data = SS_INVALID_COMMAND; 2853 reply = -EINVAL; 2854 } 2855 break; 2856 } 2857 up_read(&fsg->filesem); 2858 2859 if (reply == -EINTR || signal_pending(current)) 2860 return -EINTR; 2861 2862 /* Set up the single reply buffer for finish_reply() */ 2863 if (reply == -EINVAL) 2864 reply = 0; // Error reply length 2865 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) { 2866 reply = min((u32) reply, fsg->data_size_from_cmnd); 2867 bh->inreq->length = reply; 2868 bh->state = BUF_STATE_FULL; 2869 fsg->residue -= reply; 2870 } // Otherwise it's already set 2871 2872 return 0; 2873} 2874 2875 2876/*-------------------------------------------------------------------------*/ 2877 2878static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh) 2879{ 2880 struct usb_request *req = bh->outreq; 2881 struct bulk_cb_wrap *cbw = req->buf; 2882 2883 /* Was this a real packet? */ 2884 if (req->status) 2885 return -EINVAL; 2886 2887 /* Is the CBW valid? */ 2888 if (req->actual != USB_BULK_CB_WRAP_LEN || 2889 cbw->Signature != __constant_cpu_to_le32( 2890 USB_BULK_CB_SIG)) { 2891 DBG(fsg, "invalid CBW: len %u sig 0x%x\n", 2892 req->actual, 2893 le32_to_cpu(cbw->Signature)); 2894 2895 /* The Bulk-only spec says we MUST stall the bulk pipes! 2896 * If we want to avoid stalls, set a flag so that we will 2897 * clear the endpoint halts at the next reset. */ 2898 if (!mod_data.can_stall) 2899 set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags); 2900 fsg_set_halt(fsg, fsg->bulk_out); 2901 halt_bulk_in_endpoint(fsg); 2902 return -EINVAL; 2903 } 2904 2905 /* Is the CBW meaningful? */ 2906 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG || 2907 cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) { 2908 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, " 2909 "cmdlen %u\n", 2910 cbw->Lun, cbw->Flags, cbw->Length); 2911 2912 /* We can do anything we want here, so let's stall the 2913 * bulk pipes if we are allowed to. */ 2914 if (mod_data.can_stall) { 2915 fsg_set_halt(fsg, fsg->bulk_out); 2916 halt_bulk_in_endpoint(fsg); 2917 } 2918 return -EINVAL; 2919 } 2920 2921 /* Save the command for later */ 2922 fsg->cmnd_size = cbw->Length; 2923 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size); 2924 if (cbw->Flags & USB_BULK_IN_FLAG) 2925 fsg->data_dir = DATA_DIR_TO_HOST; 2926 else 2927 fsg->data_dir = DATA_DIR_FROM_HOST; 2928 fsg->data_size = le32_to_cpu(cbw->DataTransferLength); 2929 if (fsg->data_size == 0) 2930 fsg->data_dir = DATA_DIR_NONE; 2931 fsg->lun = cbw->Lun; 2932 fsg->tag = cbw->Tag; 2933 return 0; 2934} 2935 2936 2937static int get_next_command(struct fsg_dev *fsg) 2938{ 2939 struct fsg_buffhd *bh; 2940 int rc = 0; 2941 2942 if (transport_is_bbb()) { 2943 2944 /* Wait for the next buffer to become available */ 2945 bh = fsg->next_buffhd_to_fill; 2946 while (bh->state != BUF_STATE_EMPTY) { 2947 if ((rc = sleep_thread(fsg)) != 0) 2948 return rc; 2949 } 2950 2951 /* Queue a request to read a Bulk-only CBW */ 2952 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN); 2953 bh->outreq->short_not_ok = 1; 2954 start_transfer(fsg, fsg->bulk_out, bh->outreq, 2955 &bh->outreq_busy, &bh->state); 2956 2957 /* We will drain the buffer in software, which means we 2958 * can reuse it for the next filling. No need to advance 2959 * next_buffhd_to_fill. */ 2960 2961 /* Wait for the CBW to arrive */ 2962 while (bh->state != BUF_STATE_FULL) { 2963 if ((rc = sleep_thread(fsg)) != 0) 2964 return rc; 2965 } 2966 smp_rmb(); 2967 rc = received_cbw(fsg, bh); 2968 bh->state = BUF_STATE_EMPTY; 2969 2970 } else { // USB_PR_CB or USB_PR_CBI 2971 2972 /* Wait for the next command to arrive */ 2973 while (fsg->cbbuf_cmnd_size == 0) { 2974 if ((rc = sleep_thread(fsg)) != 0) 2975 return rc; 2976 } 2977 2978 /* Is the previous status interrupt request still busy? 2979 * The host is allowed to skip reading the status, 2980 * so we must cancel it. */ 2981 if (fsg->intreq_busy) 2982 usb_ep_dequeue(fsg->intr_in, fsg->intreq); 2983 2984 /* Copy the command and mark the buffer empty */ 2985 fsg->data_dir = DATA_DIR_UNKNOWN; 2986 spin_lock_irq(&fsg->lock); 2987 fsg->cmnd_size = fsg->cbbuf_cmnd_size; 2988 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size); 2989 fsg->cbbuf_cmnd_size = 0; 2990 spin_unlock_irq(&fsg->lock); 2991 } 2992 return rc; 2993} 2994 2995 2996/*-------------------------------------------------------------------------*/ 2997 2998static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep, 2999 const struct usb_endpoint_descriptor *d) 3000{ 3001 int rc; 3002 3003 ep->driver_data = fsg; 3004 rc = usb_ep_enable(ep, d); 3005 if (rc) 3006 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc); 3007 return rc; 3008} 3009 3010static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep, 3011 struct usb_request **preq) 3012{ 3013 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC); 3014 if (*preq) 3015 return 0; 3016 ERROR(fsg, "can't allocate request for %s\n", ep->name); 3017 return -ENOMEM; 3018} 3019 3020/* 3021 * Reset interface setting and re-init endpoint state (toggle etc). 3022 * Call with altsetting < 0 to disable the interface. The only other 3023 * available altsetting is 0, which enables the interface. 3024 */ 3025static int do_set_interface(struct fsg_dev *fsg, int altsetting) 3026{ 3027 int rc = 0; 3028 int i; 3029 const struct usb_endpoint_descriptor *d; 3030 3031 if (fsg->running) 3032 DBG(fsg, "reset interface\n"); 3033 3034reset: 3035 /* Deallocate the requests */ 3036 for (i = 0; i < NUM_BUFFERS; ++i) { 3037 struct fsg_buffhd *bh = &fsg->buffhds[i]; 3038 3039 if (bh->inreq) { 3040 usb_ep_free_request(fsg->bulk_in, bh->inreq); 3041 bh->inreq = NULL; 3042 } 3043 if (bh->outreq) { 3044 usb_ep_free_request(fsg->bulk_out, bh->outreq); 3045 bh->outreq = NULL; 3046 } 3047 } 3048 if (fsg->intreq) { 3049 usb_ep_free_request(fsg->intr_in, fsg->intreq); 3050 fsg->intreq = NULL; 3051 } 3052 3053 /* Disable the endpoints */ 3054 if (fsg->bulk_in_enabled) { 3055 usb_ep_disable(fsg->bulk_in); 3056 fsg->bulk_in_enabled = 0; 3057 } 3058 if (fsg->bulk_out_enabled) { 3059 usb_ep_disable(fsg->bulk_out); 3060 fsg->bulk_out_enabled = 0; 3061 } 3062 if (fsg->intr_in_enabled) { 3063 usb_ep_disable(fsg->intr_in); 3064 fsg->intr_in_enabled = 0; 3065 } 3066 3067 fsg->running = 0; 3068 if (altsetting < 0 || rc != 0) 3069 return rc; 3070 3071 DBG(fsg, "set interface %d\n", altsetting); 3072 3073 /* Enable the endpoints */ 3074 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc); 3075 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0) 3076 goto reset; 3077 fsg->bulk_in_enabled = 1; 3078 3079 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc); 3080 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0) 3081 goto reset; 3082 fsg->bulk_out_enabled = 1; 3083 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize); 3084 3085 if (transport_is_cbi()) { 3086 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc); 3087 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0) 3088 goto reset; 3089 fsg->intr_in_enabled = 1; 3090 } 3091 3092 /* Allocate the requests */ 3093 for (i = 0; i < NUM_BUFFERS; ++i) { 3094 struct fsg_buffhd *bh = &fsg->buffhds[i]; 3095 3096 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0) 3097 goto reset; 3098 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0) 3099 goto reset; 3100 bh->inreq->buf = bh->outreq->buf = bh->buf; 3101 bh->inreq->dma = bh->outreq->dma = bh->dma; 3102 bh->inreq->context = bh->outreq->context = bh; 3103 bh->inreq->complete = bulk_in_complete; 3104 bh->outreq->complete = bulk_out_complete; 3105 } 3106 if (transport_is_cbi()) { 3107 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0) 3108 goto reset; 3109 fsg->intreq->complete = intr_in_complete; 3110 } 3111 3112 fsg->running = 1; 3113 for (i = 0; i < fsg->nluns; ++i) 3114 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED; 3115 return rc; 3116} 3117 3118 3119/* 3120 * Change our operational configuration. This code must agree with the code 3121 * that returns config descriptors, and with interface altsetting code. 3122 * 3123 * It's also responsible for power management interactions. Some 3124 * configurations might not work with our current power sources. 3125 * For now we just assume the gadget is always self-powered. 3126 */ 3127static int do_set_config(struct fsg_dev *fsg, u8 new_config) 3128{ 3129 int rc = 0; 3130 3131 /* Disable the single interface */ 3132 if (fsg->config != 0) { 3133 DBG(fsg, "reset config\n"); 3134 fsg->config = 0; 3135 rc = do_set_interface(fsg, -1); 3136 } 3137 3138 /* Enable the interface */ 3139 if (new_config != 0) { 3140 fsg->config = new_config; 3141 if ((rc = do_set_interface(fsg, 0)) != 0) 3142 fsg->config = 0; // Reset on errors 3143 else { 3144 char *speed; 3145 3146 switch (fsg->gadget->speed) { 3147 case USB_SPEED_LOW: speed = "low"; break; 3148 case USB_SPEED_FULL: speed = "full"; break; 3149 case USB_SPEED_HIGH: speed = "high"; break; 3150 default: speed = "?"; break; 3151 } 3152 INFO(fsg, "%s speed config #%d\n", speed, fsg->config); 3153 } 3154 } 3155 return rc; 3156} 3157 3158 3159/*-------------------------------------------------------------------------*/ 3160 3161static void handle_exception(struct fsg_dev *fsg) 3162{ 3163 siginfo_t info; 3164 int sig; 3165 int i; 3166 int num_active; 3167 struct fsg_buffhd *bh; 3168 enum fsg_state old_state; 3169 u8 new_config; 3170 struct lun *curlun; 3171 unsigned int exception_req_tag; 3172 int rc; 3173 3174 /* Clear the existing signals. Anything but SIGUSR1 is converted 3175 * into a high-priority EXIT exception. */ 3176 for (;;) { 3177 sig = dequeue_signal_lock(current, ¤t->blocked, &info); 3178 if (!sig) 3179 break; 3180 if (sig != SIGUSR1) { 3181 if (fsg->state < FSG_STATE_EXIT) 3182 DBG(fsg, "Main thread exiting on signal\n"); 3183 raise_exception(fsg, FSG_STATE_EXIT); 3184 } 3185 } 3186 3187 /* Cancel all the pending transfers */ 3188 if (fsg->intreq_busy) 3189 usb_ep_dequeue(fsg->intr_in, fsg->intreq); 3190 for (i = 0; i < NUM_BUFFERS; ++i) { 3191 bh = &fsg->buffhds[i]; 3192 if (bh->inreq_busy) 3193 usb_ep_dequeue(fsg->bulk_in, bh->inreq); 3194 if (bh->outreq_busy) 3195 usb_ep_dequeue(fsg->bulk_out, bh->outreq); 3196 } 3197 3198 /* Wait until everything is idle */ 3199 for (;;) { 3200 num_active = fsg->intreq_busy; 3201 for (i = 0; i < NUM_BUFFERS; ++i) { 3202 bh = &fsg->buffhds[i]; 3203 num_active += bh->inreq_busy + bh->outreq_busy; 3204 } 3205 if (num_active == 0) 3206 break; 3207 if (sleep_thread(fsg)) 3208 return; 3209 } 3210 3211 /* Clear out the controller's fifos */ 3212 if (fsg->bulk_in_enabled) 3213 usb_ep_fifo_flush(fsg->bulk_in); 3214 if (fsg->bulk_out_enabled) 3215 usb_ep_fifo_flush(fsg->bulk_out); 3216 if (fsg->intr_in_enabled) 3217 usb_ep_fifo_flush(fsg->intr_in); 3218 3219 /* Reset the I/O buffer states and pointers, the SCSI 3220 * state, and the exception. Then invoke the handler. */ 3221 spin_lock_irq(&fsg->lock); 3222 3223 for (i = 0; i < NUM_BUFFERS; ++i) { 3224 bh = &fsg->buffhds[i]; 3225 bh->state = BUF_STATE_EMPTY; 3226 } 3227 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain = 3228 &fsg->buffhds[0]; 3229 3230 exception_req_tag = fsg->exception_req_tag; 3231 new_config = fsg->new_config; 3232 old_state = fsg->state; 3233 3234 if (old_state == FSG_STATE_ABORT_BULK_OUT) 3235 fsg->state = FSG_STATE_STATUS_PHASE; 3236 else { 3237 for (i = 0; i < fsg->nluns; ++i) { 3238 curlun = &fsg->luns[i]; 3239 curlun->prevent_medium_removal = 0; 3240 curlun->sense_data = curlun->unit_attention_data = 3241 SS_NO_SENSE; 3242 curlun->sense_data_info = 0; 3243 curlun->info_valid = 0; 3244 } 3245 fsg->state = FSG_STATE_IDLE; 3246 } 3247 spin_unlock_irq(&fsg->lock); 3248 3249 /* Carry out any extra actions required for the exception */ 3250 switch (old_state) { 3251 default: 3252 break; 3253 3254 case FSG_STATE_ABORT_BULK_OUT: 3255 send_status(fsg); 3256 spin_lock_irq(&fsg->lock); 3257 if (fsg->state == FSG_STATE_STATUS_PHASE) 3258 fsg->state = FSG_STATE_IDLE; 3259 spin_unlock_irq(&fsg->lock); 3260 break; 3261 3262 case FSG_STATE_RESET: 3263 /* In case we were forced against our will to halt a 3264 * bulk endpoint, clear the halt now. (The SuperH UDC 3265 * requires this.) */ 3266 if (test_and_clear_bit(CLEAR_BULK_HALTS, 3267 &fsg->atomic_bitflags)) { 3268 usb_ep_clear_halt(fsg->bulk_in); 3269 usb_ep_clear_halt(fsg->bulk_out); 3270 } 3271 3272 if (transport_is_bbb()) { 3273 if (fsg->ep0_req_tag == exception_req_tag) 3274 ep0_queue(fsg); // Complete the status stage 3275 3276 } else if (transport_is_cbi()) 3277 send_status(fsg); // Status by interrupt pipe 3278 3279 /* Technically this should go here, but it would only be 3280 * a waste of time. Ditto for the INTERFACE_CHANGE and 3281 * CONFIG_CHANGE cases. */ 3282 // for (i = 0; i < fsg->nluns; ++i) 3283 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED; 3284 break; 3285 3286 case FSG_STATE_INTERFACE_CHANGE: 3287 rc = do_set_interface(fsg, 0); 3288 if (fsg->ep0_req_tag != exception_req_tag) 3289 break; 3290 if (rc != 0) // STALL on errors 3291 fsg_set_halt(fsg, fsg->ep0); 3292 else // Complete the status stage 3293 ep0_queue(fsg); 3294 break; 3295 3296 case FSG_STATE_CONFIG_CHANGE: 3297 rc = do_set_config(fsg, new_config); 3298 if (fsg->ep0_req_tag != exception_req_tag) 3299 break; 3300 if (rc != 0) // STALL on errors 3301 fsg_set_halt(fsg, fsg->ep0); 3302 else // Complete the status stage 3303 ep0_queue(fsg); 3304 break; 3305 3306 case FSG_STATE_DISCONNECT: 3307 fsync_all(fsg); 3308 do_set_config(fsg, 0); // Unconfigured state 3309 break; 3310 3311 case FSG_STATE_EXIT: 3312 case FSG_STATE_TERMINATED: 3313 do_set_config(fsg, 0); // Free resources 3314 spin_lock_irq(&fsg->lock); 3315 fsg->state = FSG_STATE_TERMINATED; // Stop the thread 3316 spin_unlock_irq(&fsg->lock); 3317 break; 3318 } 3319} 3320 3321 3322/*-------------------------------------------------------------------------*/ 3323 3324static int fsg_main_thread(void *fsg_) 3325{ 3326 struct fsg_dev *fsg = fsg_; 3327 3328 /* Allow the thread to be killed by a signal, but set the signal mask 3329 * to block everything but INT, TERM, KILL, and USR1. */ 3330 allow_signal(SIGINT); 3331 allow_signal(SIGTERM); 3332 allow_signal(SIGKILL); 3333 allow_signal(SIGUSR1); 3334 3335 /* Arrange for userspace references to be interpreted as kernel 3336 * pointers. That way we can pass a kernel pointer to a routine 3337 * that expects a __user pointer and it will work okay. */ 3338 set_fs(get_ds()); 3339 3340 /* The main loop */ 3341 while (fsg->state != FSG_STATE_TERMINATED) { 3342 if (exception_in_progress(fsg) || signal_pending(current)) { 3343 handle_exception(fsg); 3344 continue; 3345 } 3346 3347 if (!fsg->running) { 3348 sleep_thread(fsg); 3349 continue; 3350 } 3351 3352 if (get_next_command(fsg)) 3353 continue; 3354 3355 spin_lock_irq(&fsg->lock); 3356 if (!exception_in_progress(fsg)) 3357 fsg->state = FSG_STATE_DATA_PHASE; 3358 spin_unlock_irq(&fsg->lock); 3359 3360 if (do_scsi_command(fsg) || finish_reply(fsg)) 3361 continue; 3362 3363 spin_lock_irq(&fsg->lock); 3364 if (!exception_in_progress(fsg)) 3365 fsg->state = FSG_STATE_STATUS_PHASE; 3366 spin_unlock_irq(&fsg->lock); 3367 3368 if (send_status(fsg)) 3369 continue; 3370 3371 spin_lock_irq(&fsg->lock); 3372 if (!exception_in_progress(fsg)) 3373 fsg->state = FSG_STATE_IDLE; 3374 spin_unlock_irq(&fsg->lock); 3375 } 3376 3377 spin_lock_irq(&fsg->lock); 3378 fsg->thread_task = NULL; 3379 spin_unlock_irq(&fsg->lock); 3380 3381 /* In case we are exiting because of a signal, unregister the 3382 * gadget driver and close the backing file. */ 3383 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) { 3384 usb_gadget_unregister_driver(&fsg_driver); 3385 close_all_backing_files(fsg); 3386 } 3387 3388 /* Let the unbind and cleanup routines know the thread has exited */ 3389 complete_and_exit(&fsg->thread_notifier, 0); 3390} 3391 3392 3393/*-------------------------------------------------------------------------*/ 3394 3395/* If the next two routines are called while the gadget is registered, 3396 * the caller must own fsg->filesem for writing. */ 3397 3398static int open_backing_file(struct lun *curlun, const char *filename) 3399{ 3400 int ro; 3401 struct file *filp = NULL; 3402 int rc = -EINVAL; 3403 struct inode *inode = NULL; 3404 loff_t size; 3405 loff_t num_sectors; 3406 3407 /* R/W if we can, R/O if we must */ 3408 ro = curlun->ro; 3409 if (!ro) { 3410 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0); 3411 if (-EROFS == PTR_ERR(filp)) 3412 ro = 1; 3413 } 3414 if (ro) 3415 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0); 3416 if (IS_ERR(filp)) { 3417 LINFO(curlun, "unable to open backing file: %s\n", filename); 3418 return PTR_ERR(filp); 3419 } 3420 3421 if (!(filp->f_mode & FMODE_WRITE)) 3422 ro = 1; 3423 3424 if (filp->f_path.dentry) 3425 inode = filp->f_path.dentry->d_inode; 3426 if (inode && S_ISBLK(inode->i_mode)) { 3427 if (bdev_read_only(inode->i_bdev)) 3428 ro = 1; 3429 } else if (!inode || !S_ISREG(inode->i_mode)) { 3430 LINFO(curlun, "invalid file type: %s\n", filename); 3431 goto out; 3432 } 3433 3434 /* If we can't read the file, it's no good. 3435 * If we can't write the file, use it read-only. */ 3436 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) { 3437 LINFO(curlun, "file not readable: %s\n", filename); 3438 goto out; 3439 } 3440 if (!(filp->f_op->write || filp->f_op->aio_write)) 3441 ro = 1; 3442 3443 size = i_size_read(inode->i_mapping->host); 3444 if (size < 0) { 3445 LINFO(curlun, "unable to find file size: %s\n", filename); 3446 rc = (int) size; 3447 goto out; 3448 } 3449 num_sectors = size >> 9; // File size in 512-byte sectors 3450 if (num_sectors == 0) { 3451 LINFO(curlun, "file too small: %s\n", filename); 3452 rc = -ETOOSMALL; 3453 goto out; 3454 } 3455 3456 get_file(filp); 3457 curlun->ro = ro; 3458 curlun->filp = filp; 3459 curlun->file_length = size; 3460 curlun->num_sectors = num_sectors; 3461 LDBG(curlun, "open backing file: %s\n", filename); 3462 rc = 0; 3463 3464out: 3465 filp_close(filp, current->files); 3466 return rc; 3467} 3468 3469 3470static void close_backing_file(struct lun *curlun) 3471{ 3472 if (curlun->filp) { 3473 LDBG(curlun, "close backing file\n"); 3474 fput(curlun->filp); 3475 curlun->filp = NULL; 3476 } 3477} 3478 3479static void close_all_backing_files(struct fsg_dev *fsg) 3480{ 3481 int i; 3482 3483 for (i = 0; i < fsg->nluns; ++i) 3484 close_backing_file(&fsg->luns[i]); 3485} 3486 3487 3488static ssize_t show_ro(struct device *dev, struct device_attribute *attr, char *buf) 3489{ 3490 struct lun *curlun = dev_to_lun(dev); 3491 3492 return sprintf(buf, "%d\n", curlun->ro); 3493} 3494 3495static ssize_t show_file(struct device *dev, struct device_attribute *attr, char *buf) 3496{ 3497 struct lun *curlun = dev_to_lun(dev); 3498 struct fsg_dev *fsg = dev_get_drvdata(dev); 3499 char *p; 3500 ssize_t rc; 3501 3502 down_read(&fsg->filesem); 3503 if (backing_file_is_open(curlun)) { // Get the complete pathname 3504 p = d_path(curlun->filp->f_path.dentry, curlun->filp->f_path.mnt, 3505 buf, PAGE_SIZE - 1); 3506 if (IS_ERR(p)) 3507 rc = PTR_ERR(p); 3508 else { 3509 rc = strlen(p); 3510 memmove(buf, p, rc); 3511 buf[rc] = '\n'; // Add a newline 3512 buf[++rc] = 0; 3513 } 3514 } else { // No file, return 0 bytes 3515 *buf = 0; 3516 rc = 0; 3517 } 3518 up_read(&fsg->filesem); 3519 return rc; 3520} 3521 3522 3523static ssize_t store_ro(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) 3524{ 3525 ssize_t rc = count; 3526 struct lun *curlun = dev_to_lun(dev); 3527 struct fsg_dev *fsg = dev_get_drvdata(dev); 3528 int i; 3529 3530 if (sscanf(buf, "%d", &i) != 1) 3531 return -EINVAL; 3532 3533 /* Allow the write-enable status to change only while the backing file 3534 * is closed. */ 3535 down_read(&fsg->filesem); 3536 if (backing_file_is_open(curlun)) { 3537 LDBG(curlun, "read-only status change prevented\n"); 3538 rc = -EBUSY; 3539 } else { 3540 curlun->ro = !!i; 3541 LDBG(curlun, "read-only status set to %d\n", curlun->ro); 3542 } 3543 up_read(&fsg->filesem); 3544 return rc; 3545} 3546 3547static ssize_t store_file(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) 3548{ 3549 struct lun *curlun = dev_to_lun(dev); 3550 struct fsg_dev *fsg = dev_get_drvdata(dev); 3551 int rc = 0; 3552 3553 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) { 3554 LDBG(curlun, "eject attempt prevented\n"); 3555 return -EBUSY; // "Door is locked" 3556 } 3557 3558 /* Remove a trailing newline */ 3559 if (count > 0 && buf[count-1] == '\n') 3560 ((char *) buf)[count-1] = 0; // Ugh! 3561 3562 /* Eject current medium */ 3563 down_write(&fsg->filesem); 3564 if (backing_file_is_open(curlun)) { 3565 close_backing_file(curlun); 3566 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT; 3567 } 3568 3569 /* Load new medium */ 3570 if (count > 0 && buf[0]) { 3571 rc = open_backing_file(curlun, buf); 3572 if (rc == 0) 3573 curlun->unit_attention_data = 3574 SS_NOT_READY_TO_READY_TRANSITION; 3575 } 3576 up_write(&fsg->filesem); 3577 return (rc < 0 ? rc : count); 3578} 3579 3580 3581/* The write permissions and store_xxx pointers are set in fsg_bind() */ 3582static DEVICE_ATTR(ro, 0444, show_ro, NULL); 3583static DEVICE_ATTR(file, 0444, show_file, NULL); 3584 3585 3586/*-------------------------------------------------------------------------*/ 3587 3588static void fsg_release(struct kref *ref) 3589{ 3590 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref); 3591 3592 kfree(fsg->luns); 3593 kfree(fsg); 3594} 3595 3596static void lun_release(struct device *dev) 3597{ 3598 struct fsg_dev *fsg = dev_get_drvdata(dev); 3599 3600 kref_put(&fsg->ref, fsg_release); 3601} 3602 3603static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget) 3604{ 3605 struct fsg_dev *fsg = get_gadget_data(gadget); 3606 int i; 3607 struct lun *curlun; 3608 struct usb_request *req = fsg->ep0req; 3609 3610 DBG(fsg, "unbind\n"); 3611 clear_bit(REGISTERED, &fsg->atomic_bitflags); 3612 3613 /* Unregister the sysfs attribute files and the LUNs */ 3614 for (i = 0; i < fsg->nluns; ++i) { 3615 curlun = &fsg->luns[i]; 3616 if (curlun->registered) { 3617 device_remove_file(&curlun->dev, &dev_attr_ro); 3618 device_remove_file(&curlun->dev, &dev_attr_file); 3619 device_unregister(&curlun->dev); 3620 curlun->registered = 0; 3621 } 3622 } 3623 3624 /* If the thread isn't already dead, tell it to exit now */ 3625 if (fsg->state != FSG_STATE_TERMINATED) { 3626 raise_exception(fsg, FSG_STATE_EXIT); 3627 wait_for_completion(&fsg->thread_notifier); 3628 3629 /* The cleanup routine waits for this completion also */ 3630 complete(&fsg->thread_notifier); 3631 } 3632 3633 /* Free the data buffers */ 3634 for (i = 0; i < NUM_BUFFERS; ++i) { 3635 struct fsg_buffhd *bh = &fsg->buffhds[i]; 3636 3637 if (bh->buf) 3638 usb_ep_free_buffer(fsg->bulk_in, bh->buf, bh->dma, 3639 mod_data.buflen); 3640 } 3641 3642 /* Free the request and buffer for endpoint 0 */ 3643 if (req) { 3644 if (req->buf) 3645 usb_ep_free_buffer(fsg->ep0, req->buf, 3646 req->dma, EP0_BUFSIZE); 3647 usb_ep_free_request(fsg->ep0, req); 3648 } 3649 3650 set_gadget_data(gadget, NULL); 3651} 3652 3653 3654static int __init check_parameters(struct fsg_dev *fsg) 3655{ 3656 int prot; 3657 int gcnum; 3658 3659 /* Store the default values */ 3660 mod_data.transport_type = USB_PR_BULK; 3661 mod_data.transport_name = "Bulk-only"; 3662 mod_data.protocol_type = USB_SC_SCSI; 3663 mod_data.protocol_name = "Transparent SCSI"; 3664 3665 if (gadget_is_sh(fsg->gadget)) 3666 mod_data.can_stall = 0; 3667 3668 if (mod_data.release == 0xffff) { // Parameter wasn't set 3669 /* The sa1100 controller is not supported */ 3670 if (gadget_is_sa1100(fsg->gadget)) 3671 gcnum = -1; 3672 else 3673 gcnum = usb_gadget_controller_number(fsg->gadget); 3674 if (gcnum >= 0) 3675 mod_data.release = 0x0300 + gcnum; 3676 else { 3677 WARN(fsg, "controller '%s' not recognized\n", 3678 fsg->gadget->name); 3679 mod_data.release = 0x0399; 3680 } 3681 } 3682 3683 prot = simple_strtol(mod_data.protocol_parm, NULL, 0); 3684 3685#ifdef CONFIG_USB_FILE_STORAGE_TEST 3686 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) { 3687 ; // Use default setting 3688 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) { 3689 mod_data.transport_type = USB_PR_CB; 3690 mod_data.transport_name = "Control-Bulk"; 3691 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) { 3692 mod_data.transport_type = USB_PR_CBI; 3693 mod_data.transport_name = "Control-Bulk-Interrupt"; 3694 } else { 3695 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm); 3696 return -EINVAL; 3697 } 3698 3699 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 || 3700 prot == USB_SC_SCSI) { 3701 ; // Use default setting 3702 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 || 3703 prot == USB_SC_RBC) { 3704 mod_data.protocol_type = USB_SC_RBC; 3705 mod_data.protocol_name = "RBC"; 3706 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 || 3707 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 || 3708 prot == USB_SC_8020) { 3709 mod_data.protocol_type = USB_SC_8020; 3710 mod_data.protocol_name = "8020i (ATAPI)"; 3711 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 || 3712 prot == USB_SC_QIC) { 3713 mod_data.protocol_type = USB_SC_QIC; 3714 mod_data.protocol_name = "QIC-157"; 3715 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 || 3716 prot == USB_SC_UFI) { 3717 mod_data.protocol_type = USB_SC_UFI; 3718 mod_data.protocol_name = "UFI"; 3719 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 || 3720 prot == USB_SC_8070) { 3721 mod_data.protocol_type = USB_SC_8070; 3722 mod_data.protocol_name = "8070i"; 3723 } else { 3724 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm); 3725 return -EINVAL; 3726 } 3727 3728 mod_data.buflen &= PAGE_CACHE_MASK; 3729 if (mod_data.buflen <= 0) { 3730 ERROR(fsg, "invalid buflen\n"); 3731 return -ETOOSMALL; 3732 } 3733#endif /* CONFIG_USB_FILE_STORAGE_TEST */ 3734 3735 return 0; 3736} 3737 3738 3739static int __init fsg_bind(struct usb_gadget *gadget) 3740{ 3741 struct fsg_dev *fsg = the_fsg; 3742 int rc; 3743 int i; 3744 struct lun *curlun; 3745 struct usb_ep *ep; 3746 struct usb_request *req; 3747 char *pathbuf, *p; 3748 3749 fsg->gadget = gadget; 3750 set_gadget_data(gadget, fsg); 3751 fsg->ep0 = gadget->ep0; 3752 fsg->ep0->driver_data = fsg; 3753 3754 if ((rc = check_parameters(fsg)) != 0) 3755 goto out; 3756 3757 if (mod_data.removable) { // Enable the store_xxx attributes 3758 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644; 3759 dev_attr_ro.store = store_ro; 3760 dev_attr_file.store = store_file; 3761 } 3762 3763 /* Find out how many LUNs there should be */ 3764 i = mod_data.nluns; 3765 if (i == 0) 3766 i = max(mod_data.num_filenames, 1); 3767 if (i > MAX_LUNS) { 3768 ERROR(fsg, "invalid number of LUNs: %d\n", i); 3769 rc = -EINVAL; 3770 goto out; 3771 } 3772 3773 /* Create the LUNs, open their backing files, and register the 3774 * LUN devices in sysfs. */ 3775 fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL); 3776 if (!fsg->luns) { 3777 rc = -ENOMEM; 3778 goto out; 3779 } 3780 fsg->nluns = i; 3781 3782 for (i = 0; i < fsg->nluns; ++i) { 3783 curlun = &fsg->luns[i]; 3784 curlun->ro = mod_data.ro[i]; 3785 curlun->dev.release = lun_release; 3786 curlun->dev.parent = &gadget->dev; 3787 curlun->dev.driver = &fsg_driver.driver; 3788 dev_set_drvdata(&curlun->dev, fsg); 3789 snprintf(curlun->dev.bus_id, BUS_ID_SIZE, 3790 "%s-lun%d", gadget->dev.bus_id, i); 3791 3792 if ((rc = device_register(&curlun->dev)) != 0) { 3793 INFO(fsg, "failed to register LUN%d: %d\n", i, rc); 3794 goto out; 3795 } 3796 if ((rc = device_create_file(&curlun->dev, 3797 &dev_attr_ro)) != 0 || 3798 (rc = device_create_file(&curlun->dev, 3799 &dev_attr_file)) != 0) { 3800 device_unregister(&curlun->dev); 3801 goto out; 3802 } 3803 curlun->registered = 1; 3804 kref_get(&fsg->ref); 3805 3806 if (mod_data.file[i] && *mod_data.file[i]) { 3807 if ((rc = open_backing_file(curlun, 3808 mod_data.file[i])) != 0) 3809 goto out; 3810 } else if (!mod_data.removable) { 3811 ERROR(fsg, "no file given for LUN%d\n", i); 3812 rc = -EINVAL; 3813 goto out; 3814 } 3815 } 3816 3817 /* Find all the endpoints we will use */ 3818 usb_ep_autoconfig_reset(gadget); 3819 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc); 3820 if (!ep) 3821 goto autoconf_fail; 3822 ep->driver_data = fsg; // claim the endpoint 3823 fsg->bulk_in = ep; 3824 3825 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc); 3826 if (!ep) 3827 goto autoconf_fail; 3828 ep->driver_data = fsg; // claim the endpoint 3829 fsg->bulk_out = ep; 3830 3831 if (transport_is_cbi()) { 3832 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc); 3833 if (!ep) 3834 goto autoconf_fail; 3835 ep->driver_data = fsg; // claim the endpoint 3836 fsg->intr_in = ep; 3837 } 3838 3839 /* Fix up the descriptors */ 3840 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket; 3841 device_desc.idVendor = cpu_to_le16(mod_data.vendor); 3842 device_desc.idProduct = cpu_to_le16(mod_data.product); 3843 device_desc.bcdDevice = cpu_to_le16(mod_data.release); 3844 3845 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints 3846 intf_desc.bNumEndpoints = i; 3847 intf_desc.bInterfaceSubClass = mod_data.protocol_type; 3848 intf_desc.bInterfaceProtocol = mod_data.transport_type; 3849 fs_function[i + FS_FUNCTION_PRE_EP_ENTRIES] = NULL; 3850 3851#ifdef CONFIG_USB_GADGET_DUALSPEED 3852 hs_function[i + HS_FUNCTION_PRE_EP_ENTRIES] = NULL; 3853 3854 /* Assume ep0 uses the same maxpacket value for both speeds */ 3855 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket; 3856 3857 /* Assume that all endpoint addresses are the same for both speeds */ 3858 hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress; 3859 hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress; 3860 hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress; 3861#endif 3862 3863 if (gadget->is_otg) { 3864 otg_desc.bmAttributes |= USB_OTG_HNP, 3865 config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP; 3866 } 3867 3868 rc = -ENOMEM; 3869 3870 /* Allocate the request and buffer for endpoint 0 */ 3871 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL); 3872 if (!req) 3873 goto out; 3874 req->buf = usb_ep_alloc_buffer(fsg->ep0, EP0_BUFSIZE, 3875 &req->dma, GFP_KERNEL); 3876 if (!req->buf) 3877 goto out; 3878 req->complete = ep0_complete; 3879 3880 /* Allocate the data buffers */ 3881 for (i = 0; i < NUM_BUFFERS; ++i) { 3882 struct fsg_buffhd *bh = &fsg->buffhds[i]; 3883 3884 /* Allocate for the bulk-in endpoint. We assume that 3885 * the buffer will also work with the bulk-out (and 3886 * interrupt-in) endpoint. */ 3887 bh->buf = usb_ep_alloc_buffer(fsg->bulk_in, mod_data.buflen, 3888 &bh->dma, GFP_KERNEL); 3889 if (!bh->buf) 3890 goto out; 3891 bh->next = bh + 1; 3892 } 3893 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0]; 3894 3895 /* This should reflect the actual gadget power source */ 3896 usb_gadget_set_selfpowered(gadget); 3897 3898 snprintf(manufacturer, sizeof manufacturer, "%s %s with %s", 3899 init_utsname()->sysname, init_utsname()->release, 3900 gadget->name); 3901 3902 /* On a real device, serial[] would be loaded from permanent 3903 * storage. We just encode it from the driver version string. */ 3904 for (i = 0; i < sizeof(serial) - 2; i += 2) { 3905 unsigned char c = DRIVER_VERSION[i / 2]; 3906 3907 if (!c) 3908 break; 3909 sprintf(&serial[i], "%02X", c); 3910 } 3911 3912 fsg->thread_task = kthread_create(fsg_main_thread, fsg, 3913 "file-storage-gadget"); 3914 if (IS_ERR(fsg->thread_task)) { 3915 rc = PTR_ERR(fsg->thread_task); 3916 goto out; 3917 } 3918 3919 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n"); 3920 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns); 3921 3922 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL); 3923 for (i = 0; i < fsg->nluns; ++i) { 3924 curlun = &fsg->luns[i]; 3925 if (backing_file_is_open(curlun)) { 3926 p = NULL; 3927 if (pathbuf) { 3928 p = d_path(curlun->filp->f_path.dentry, 3929 curlun->filp->f_path.mnt, 3930 pathbuf, PATH_MAX); 3931 if (IS_ERR(p)) 3932 p = NULL; 3933 } 3934 LINFO(curlun, "ro=%d, file: %s\n", 3935 curlun->ro, (p ? p : "(error)")); 3936 } 3937 } 3938 kfree(pathbuf); 3939 3940 DBG(fsg, "transport=%s (x%02x)\n", 3941 mod_data.transport_name, mod_data.transport_type); 3942 DBG(fsg, "protocol=%s (x%02x)\n", 3943 mod_data.protocol_name, mod_data.protocol_type); 3944 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n", 3945 mod_data.vendor, mod_data.product, mod_data.release); 3946 DBG(fsg, "removable=%d, stall=%d, buflen=%u\n", 3947 mod_data.removable, mod_data.can_stall, 3948 mod_data.buflen); 3949 DBG(fsg, "I/O thread pid: %d\n", fsg->thread_task->pid); 3950 3951 set_bit(REGISTERED, &fsg->atomic_bitflags); 3952 3953 /* Tell the thread to start working */ 3954 wake_up_process(fsg->thread_task); 3955 return 0; 3956 3957autoconf_fail: 3958 ERROR(fsg, "unable to autoconfigure all endpoints\n"); 3959 rc = -ENOTSUPP; 3960 3961out: 3962 fsg->state = FSG_STATE_TERMINATED; // The thread is dead 3963 fsg_unbind(gadget); 3964 close_all_backing_files(fsg); 3965 return rc; 3966} 3967 3968 3969/*-------------------------------------------------------------------------*/ 3970 3971static void fsg_suspend(struct usb_gadget *gadget) 3972{ 3973 struct fsg_dev *fsg = get_gadget_data(gadget); 3974 3975 DBG(fsg, "suspend\n"); 3976 set_bit(SUSPENDED, &fsg->atomic_bitflags); 3977} 3978 3979static void fsg_resume(struct usb_gadget *gadget) 3980{ 3981 struct fsg_dev *fsg = get_gadget_data(gadget); 3982 3983 DBG(fsg, "resume\n"); 3984 clear_bit(SUSPENDED, &fsg->atomic_bitflags); 3985} 3986 3987 3988/*-------------------------------------------------------------------------*/ 3989 3990static struct usb_gadget_driver fsg_driver = { 3991#ifdef CONFIG_USB_GADGET_DUALSPEED 3992 .speed = USB_SPEED_HIGH, 3993#else 3994 .speed = USB_SPEED_FULL, 3995#endif 3996 .function = (char *) longname, 3997 .bind = fsg_bind, 3998 .unbind = fsg_unbind, 3999 .disconnect = fsg_disconnect, 4000 .setup = fsg_setup, 4001 .suspend = fsg_suspend, 4002 .resume = fsg_resume, 4003 4004 .driver = { 4005 .name = (char *) shortname, 4006 .owner = THIS_MODULE, 4007 // .release = ... 4008 // .suspend = ... 4009 // .resume = ... 4010 }, 4011}; 4012 4013 4014static int __init fsg_alloc(void) 4015{ 4016 struct fsg_dev *fsg; 4017 4018 fsg = kzalloc(sizeof *fsg, GFP_KERNEL); 4019 if (!fsg) 4020 return -ENOMEM; 4021 spin_lock_init(&fsg->lock); 4022 init_rwsem(&fsg->filesem); 4023 kref_init(&fsg->ref); 4024 init_completion(&fsg->thread_notifier); 4025 4026 the_fsg = fsg; 4027 return 0; 4028} 4029 4030 4031static int __init fsg_init(void) 4032{ 4033 int rc; 4034 struct fsg_dev *fsg; 4035 4036 if ((rc = fsg_alloc()) != 0) 4037 return rc; 4038 fsg = the_fsg; 4039 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0) 4040 kref_put(&fsg->ref, fsg_release); 4041 return rc; 4042} 4043module_init(fsg_init); 4044 4045 4046static void __exit fsg_cleanup(void) 4047{ 4048 struct fsg_dev *fsg = the_fsg; 4049 4050 /* Unregister the driver iff the thread hasn't already done so */ 4051 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) 4052 usb_gadget_unregister_driver(&fsg_driver); 4053 4054 /* Wait for the thread to finish up */ 4055 wait_for_completion(&fsg->thread_notifier); 4056 4057 close_all_backing_files(fsg); 4058 kref_put(&fsg->ref, fsg_release); 4059} 4060module_exit(fsg_cleanup); 4061