1 /* 2 * f_mass_storage.c -- Mass Storage USB Composite Function 3 * 4 * Copyright (C) 2003-2008 Alan Stern 5 * Copyright (C) 2009 Samsung Electronics 6 * Author: Michal Nazarewicz <m.nazarewicz@samsung.com> 7 * All rights reserved. 8 * 9 * SPDX-License-Identifier: GPL-2.0+ BSD-3-Clause 10 */ 11 12 /* 13 * The Mass Storage Function acts as a USB Mass Storage device, 14 * appearing to the host as a disk drive or as a CD-ROM drive. In 15 * addition to providing an example of a genuinely useful composite 16 * function for a USB device, it also illustrates a technique of 17 * double-buffering for increased throughput. 18 * 19 * Function supports multiple logical units (LUNs). Backing storage 20 * for each LUN is provided by a regular file or a block device. 21 * Access for each LUN can be limited to read-only. Moreover, the 22 * function can indicate that LUN is removable and/or CD-ROM. (The 23 * later implies read-only access.) 24 * 25 * MSF is configured by specifying a fsg_config structure. It has the 26 * following fields: 27 * 28 * nluns Number of LUNs function have (anywhere from 1 29 * to FSG_MAX_LUNS which is 8). 30 * luns An array of LUN configuration values. This 31 * should be filled for each LUN that 32 * function will include (ie. for "nluns" 33 * LUNs). Each element of the array has 34 * the following fields: 35 * ->filename The path to the backing file for the LUN. 36 * Required if LUN is not marked as 37 * removable. 38 * ->ro Flag specifying access to the LUN shall be 39 * read-only. This is implied if CD-ROM 40 * emulation is enabled as well as when 41 * it was impossible to open "filename" 42 * in R/W mode. 43 * ->removable Flag specifying that LUN shall be indicated as 44 * being removable. 45 * ->cdrom Flag specifying that LUN shall be reported as 46 * being a CD-ROM. 47 * 48 * lun_name_format A printf-like format for names of the LUN 49 * devices. This determines how the 50 * directory in sysfs will be named. 51 * Unless you are using several MSFs in 52 * a single gadget (as opposed to single 53 * MSF in many configurations) you may 54 * leave it as NULL (in which case 55 * "lun%d" will be used). In the format 56 * you can use "%d" to index LUNs for 57 * MSF's with more than one LUN. (Beware 58 * that there is only one integer given 59 * as an argument for the format and 60 * specifying invalid format may cause 61 * unspecified behaviour.) 62 * thread_name Name of the kernel thread process used by the 63 * MSF. You can safely set it to NULL 64 * (in which case default "file-storage" 65 * will be used). 66 * 67 * vendor_name 68 * product_name 69 * release Information used as a reply to INQUIRY 70 * request. To use default set to NULL, 71 * NULL, 0xffff respectively. The first 72 * field should be 8 and the second 16 73 * characters or less. 74 * 75 * can_stall Set to permit function to halt bulk endpoints. 76 * Disabled on some USB devices known not 77 * to work correctly. You should set it 78 * to true. 79 * 80 * If "removable" is not set for a LUN then a backing file must be 81 * specified. If it is set, then NULL filename means the LUN's medium 82 * is not loaded (an empty string as "filename" in the fsg_config 83 * structure causes error). The CD-ROM emulation includes a single 84 * data track and no audio tracks; hence there need be only one 85 * backing file per LUN. Note also that the CD-ROM block length is 86 * set to 512 rather than the more common value 2048. 87 * 88 * 89 * MSF includes support for module parameters. If gadget using it 90 * decides to use it, the following module parameters will be 91 * available: 92 * 93 * file=filename[,filename...] 94 * Names of the files or block devices used for 95 * backing storage. 96 * ro=b[,b...] Default false, boolean for read-only access. 97 * removable=b[,b...] 98 * Default true, boolean for removable media. 99 * cdrom=b[,b...] Default false, boolean for whether to emulate 100 * a CD-ROM drive. 101 * luns=N Default N = number of filenames, number of 102 * LUNs to support. 103 * stall Default determined according to the type of 104 * USB device controller (usually true), 105 * boolean to permit the driver to halt 106 * bulk endpoints. 107 * 108 * The module parameters may be prefixed with some string. You need 109 * to consult gadget's documentation or source to verify whether it is 110 * using those module parameters and if it does what are the prefixes 111 * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is 112 * the prefix). 113 * 114 * 115 * Requirements are modest; only a bulk-in and a bulk-out endpoint are 116 * needed. The memory requirement amounts to two 16K buffers, size 117 * configurable by a parameter. Support is included for both 118 * full-speed and high-speed operation. 119 * 120 * Note that the driver is slightly non-portable in that it assumes a 121 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and 122 * interrupt-in endpoints. With most device controllers this isn't an 123 * issue, but there may be some with hardware restrictions that prevent 124 * a buffer from being used by more than one endpoint. 125 * 126 * 127 * The pathnames of the backing files and the ro settings are 128 * available in the attribute files "file" and "ro" in the lun<n> (or 129 * to be more precise in a directory which name comes from 130 * "lun_name_format" option!) subdirectory of the gadget's sysfs 131 * directory. If the "removable" option is set, writing to these 132 * files will simulate ejecting/loading the medium (writing an empty 133 * line means eject) and adjusting a write-enable tab. Changes to the 134 * ro setting are not allowed when the medium is loaded or if CD-ROM 135 * emulation is being used. 136 * 137 * When a LUN receive an "eject" SCSI request (Start/Stop Unit), 138 * if the LUN is removable, the backing file is released to simulate 139 * ejection. 140 * 141 * 142 * This function is heavily based on "File-backed Storage Gadget" by 143 * Alan Stern which in turn is heavily based on "Gadget Zero" by David 144 * Brownell. The driver's SCSI command interface was based on the 145 * "Information technology - Small Computer System Interface - 2" 146 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93, 147 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. 148 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which 149 * was based on the "Universal Serial Bus Mass Storage Class UFI 150 * Command Specification" document, Revision 1.0, December 14, 1998, 151 * available at 152 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>. 153 */ 154 155 /* 156 * Driver Design 157 * 158 * The MSF is fairly straightforward. There is a main kernel 159 * thread that handles most of the work. Interrupt routines field 160 * callbacks from the controller driver: bulk- and interrupt-request 161 * completion notifications, endpoint-0 events, and disconnect events. 162 * Completion events are passed to the main thread by wakeup calls. Many 163 * ep0 requests are handled at interrupt time, but SetInterface, 164 * SetConfiguration, and device reset requests are forwarded to the 165 * thread in the form of "exceptions" using SIGUSR1 signals (since they 166 * should interrupt any ongoing file I/O operations). 167 * 168 * The thread's main routine implements the standard command/data/status 169 * parts of a SCSI interaction. It and its subroutines are full of tests 170 * for pending signals/exceptions -- all this polling is necessary since 171 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an 172 * indication that the driver really wants to be running in userspace.) 173 * An important point is that so long as the thread is alive it keeps an 174 * open reference to the backing file. This will prevent unmounting 175 * the backing file's underlying filesystem and could cause problems 176 * during system shutdown, for example. To prevent such problems, the 177 * thread catches INT, TERM, and KILL signals and converts them into 178 * an EXIT exception. 179 * 180 * In normal operation the main thread is started during the gadget's 181 * fsg_bind() callback and stopped during fsg_unbind(). But it can 182 * also exit when it receives a signal, and there's no point leaving 183 * the gadget running when the thread is dead. At of this moment, MSF 184 * provides no way to deregister the gadget when thread dies -- maybe 185 * a callback functions is needed. 186 * 187 * To provide maximum throughput, the driver uses a circular pipeline of 188 * buffer heads (struct fsg_buffhd). In principle the pipeline can be 189 * arbitrarily long; in practice the benefits don't justify having more 190 * than 2 stages (i.e., double buffering). But it helps to think of the 191 * pipeline as being a long one. Each buffer head contains a bulk-in and 192 * a bulk-out request pointer (since the buffer can be used for both 193 * output and input -- directions always are given from the host's 194 * point of view) as well as a pointer to the buffer and various state 195 * variables. 196 * 197 * Use of the pipeline follows a simple protocol. There is a variable 198 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use. 199 * At any time that buffer head may still be in use from an earlier 200 * request, so each buffer head has a state variable indicating whether 201 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the 202 * buffer head to be EMPTY, filling the buffer either by file I/O or by 203 * USB I/O (during which the buffer head is BUSY), and marking the buffer 204 * head FULL when the I/O is complete. Then the buffer will be emptied 205 * (again possibly by USB I/O, during which it is marked BUSY) and 206 * finally marked EMPTY again (possibly by a completion routine). 207 * 208 * A module parameter tells the driver to avoid stalling the bulk 209 * endpoints wherever the transport specification allows. This is 210 * necessary for some UDCs like the SuperH, which cannot reliably clear a 211 * halt on a bulk endpoint. However, under certain circumstances the 212 * Bulk-only specification requires a stall. In such cases the driver 213 * will halt the endpoint and set a flag indicating that it should clear 214 * the halt in software during the next device reset. Hopefully this 215 * will permit everything to work correctly. Furthermore, although the 216 * specification allows the bulk-out endpoint to halt when the host sends 217 * too much data, implementing this would cause an unavoidable race. 218 * The driver will always use the "no-stall" approach for OUT transfers. 219 * 220 * One subtle point concerns sending status-stage responses for ep0 221 * requests. Some of these requests, such as device reset, can involve 222 * interrupting an ongoing file I/O operation, which might take an 223 * arbitrarily long time. During that delay the host might give up on 224 * the original ep0 request and issue a new one. When that happens the 225 * driver should not notify the host about completion of the original 226 * request, as the host will no longer be waiting for it. So the driver 227 * assigns to each ep0 request a unique tag, and it keeps track of the 228 * tag value of the request associated with a long-running exception 229 * (device-reset, interface-change, or configuration-change). When the 230 * exception handler is finished, the status-stage response is submitted 231 * only if the current ep0 request tag is equal to the exception request 232 * tag. Thus only the most recently received ep0 request will get a 233 * status-stage response. 234 * 235 * Warning: This driver source file is too long. It ought to be split up 236 * into a header file plus about 3 separate .c files, to handle the details 237 * of the Gadget, USB Mass Storage, and SCSI protocols. 238 */ 239 240 /* #define VERBOSE_DEBUG */ 241 /* #define DUMP_MSGS */ 242 243 #include <config.h> 244 #include <hexdump.h> 245 #include <malloc.h> 246 #include <common.h> 247 #include <console.h> 248 #include <g_dnl.h> 249 250 #include <linux/err.h> 251 #include <linux/usb/ch9.h> 252 #include <linux/usb/gadget.h> 253 #include <usb_mass_storage.h> 254 #include <rockusb.h> 255 256 #include <asm/unaligned.h> 257 #include <linux/bitops.h> 258 #include <linux/usb/gadget.h> 259 #include <linux/usb/gadget.h> 260 #include <linux/usb/composite.h> 261 #include <linux/bitmap.h> 262 #include <g_dnl.h> 263 264 /*------------------------------------------------------------------------*/ 265 266 #define FSG_DRIVER_DESC "Mass Storage Function" 267 #define FSG_DRIVER_VERSION "2012/06/5" 268 269 static const char fsg_string_interface[] = "Mass Storage"; 270 271 #define FSG_NO_INTR_EP 1 272 #define FSG_NO_DEVICE_STRINGS 1 273 #define FSG_NO_OTG 1 274 #define FSG_NO_INTR_EP 1 275 276 #include "storage_common.c" 277 278 /*-------------------------------------------------------------------------*/ 279 280 #define GFP_ATOMIC ((gfp_t) 0) 281 #define PAGE_CACHE_SHIFT 12 282 #define PAGE_CACHE_SIZE (1 << PAGE_CACHE_SHIFT) 283 #define kthread_create(...) __builtin_return_address(0) 284 #define wait_for_completion(...) do {} while (0) 285 286 struct kref {int x; }; 287 struct completion {int x; }; 288 289 struct fsg_dev; 290 struct fsg_common; 291 292 /* Data shared by all the FSG instances. */ 293 struct fsg_common { 294 struct usb_gadget *gadget; 295 struct fsg_dev *fsg, *new_fsg; 296 297 struct usb_ep *ep0; /* Copy of gadget->ep0 */ 298 struct usb_request *ep0req; /* Copy of cdev->req */ 299 unsigned int ep0_req_tag; 300 301 struct fsg_buffhd *next_buffhd_to_fill; 302 struct fsg_buffhd *next_buffhd_to_drain; 303 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS]; 304 305 int cmnd_size; 306 u8 cmnd[MAX_COMMAND_SIZE]; 307 308 unsigned int nluns; 309 unsigned int lun; 310 struct fsg_lun luns[FSG_MAX_LUNS]; 311 312 unsigned int bulk_out_maxpacket; 313 enum fsg_state state; /* For exception handling */ 314 unsigned int exception_req_tag; 315 316 enum data_direction data_dir; 317 u32 data_size; 318 u32 data_size_from_cmnd; 319 u32 tag; 320 u32 residue; 321 u32 usb_amount_left; 322 323 unsigned int can_stall:1; 324 unsigned int free_storage_on_release:1; 325 unsigned int phase_error:1; 326 unsigned int short_packet_received:1; 327 unsigned int bad_lun_okay:1; 328 unsigned int running:1; 329 330 int thread_wakeup_needed; 331 struct completion thread_notifier; 332 struct task_struct *thread_task; 333 334 /* Callback functions. */ 335 const struct fsg_operations *ops; 336 /* Gadget's private data. */ 337 void *private_data; 338 339 const char *vendor_name; /* 8 characters or less */ 340 const char *product_name; /* 16 characters or less */ 341 u16 release; 342 343 /* Vendor (8 chars), product (16 chars), release (4 344 * hexadecimal digits) and NUL byte */ 345 char inquiry_string[8 + 16 + 4 + 1]; 346 347 struct kref ref; 348 }; 349 350 struct fsg_config { 351 unsigned nluns; 352 struct fsg_lun_config { 353 const char *filename; 354 char ro; 355 char removable; 356 char cdrom; 357 char nofua; 358 } luns[FSG_MAX_LUNS]; 359 360 /* Callback functions. */ 361 const struct fsg_operations *ops; 362 /* Gadget's private data. */ 363 void *private_data; 364 365 const char *vendor_name; /* 8 characters or less */ 366 const char *product_name; /* 16 characters or less */ 367 368 char can_stall; 369 }; 370 371 struct fsg_dev { 372 struct usb_function function; 373 struct usb_gadget *gadget; /* Copy of cdev->gadget */ 374 struct fsg_common *common; 375 376 u16 interface_number; 377 378 unsigned int bulk_in_enabled:1; 379 unsigned int bulk_out_enabled:1; 380 381 unsigned long atomic_bitflags; 382 #define IGNORE_BULK_OUT 0 383 384 struct usb_ep *bulk_in; 385 struct usb_ep *bulk_out; 386 }; 387 388 389 static inline int __fsg_is_set(struct fsg_common *common, 390 const char *func, unsigned line) 391 { 392 if (common->fsg) 393 return 1; 394 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line); 395 WARN_ON(1); 396 return 0; 397 } 398 399 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__)) 400 401 402 static inline struct fsg_dev *fsg_from_func(struct usb_function *f) 403 { 404 return container_of(f, struct fsg_dev, function); 405 } 406 407 408 typedef void (*fsg_routine_t)(struct fsg_dev *); 409 410 static int exception_in_progress(struct fsg_common *common) 411 { 412 return common->state > FSG_STATE_IDLE; 413 } 414 415 /* Make bulk-out requests be divisible by the maxpacket size */ 416 static void set_bulk_out_req_length(struct fsg_common *common, 417 struct fsg_buffhd *bh, unsigned int length) 418 { 419 unsigned int rem; 420 421 bh->bulk_out_intended_length = length; 422 rem = length % common->bulk_out_maxpacket; 423 if (rem > 0) 424 length += common->bulk_out_maxpacket - rem; 425 bh->outreq->length = length; 426 } 427 428 /*-------------------------------------------------------------------------*/ 429 430 static struct ums *ums; 431 static int ums_count; 432 static struct fsg_common *the_fsg_common; 433 434 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep) 435 { 436 const char *name; 437 438 if (ep == fsg->bulk_in) 439 name = "bulk-in"; 440 else if (ep == fsg->bulk_out) 441 name = "bulk-out"; 442 else 443 name = ep->name; 444 DBG(fsg, "%s set halt\n", name); 445 return usb_ep_set_halt(ep); 446 } 447 448 /*-------------------------------------------------------------------------*/ 449 450 /* These routines may be called in process context or in_irq */ 451 452 /* Caller must hold fsg->lock */ 453 static void wakeup_thread(struct fsg_common *common) 454 { 455 common->thread_wakeup_needed = 1; 456 } 457 458 static void raise_exception(struct fsg_common *common, enum fsg_state new_state) 459 { 460 /* Do nothing if a higher-priority exception is already in progress. 461 * If a lower-or-equal priority exception is in progress, preempt it 462 * and notify the main thread by sending it a signal. */ 463 if (common->state <= new_state) { 464 common->exception_req_tag = common->ep0_req_tag; 465 common->state = new_state; 466 common->thread_wakeup_needed = 1; 467 } 468 } 469 470 /*-------------------------------------------------------------------------*/ 471 472 static int ep0_queue(struct fsg_common *common) 473 { 474 int rc; 475 476 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC); 477 common->ep0->driver_data = common; 478 if (rc != 0 && rc != -ESHUTDOWN) { 479 /* We can't do much more than wait for a reset */ 480 WARNING(common, "error in submission: %s --> %d\n", 481 common->ep0->name, rc); 482 } 483 return rc; 484 } 485 486 /*-------------------------------------------------------------------------*/ 487 488 /* Bulk and interrupt endpoint completion handlers. 489 * These always run in_irq. */ 490 491 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req) 492 { 493 struct fsg_common *common = ep->driver_data; 494 struct fsg_buffhd *bh = req->context; 495 496 if (req->status || req->actual != req->length) 497 DBG(common, "%s --> %d, %u/%u\n", __func__, 498 req->status, req->actual, req->length); 499 if (req->status == -ECONNRESET) /* Request was cancelled */ 500 usb_ep_fifo_flush(ep); 501 502 /* Hold the lock while we update the request and buffer states */ 503 bh->inreq_busy = 0; 504 bh->state = BUF_STATE_EMPTY; 505 wakeup_thread(common); 506 } 507 508 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req) 509 { 510 struct fsg_common *common = ep->driver_data; 511 struct fsg_buffhd *bh = req->context; 512 513 dump_msg(common, "bulk-out", req->buf, req->actual); 514 if (req->status || req->actual != bh->bulk_out_intended_length) 515 DBG(common, "%s --> %d, %u/%u\n", __func__, 516 req->status, req->actual, 517 bh->bulk_out_intended_length); 518 if (req->status == -ECONNRESET) /* Request was cancelled */ 519 usb_ep_fifo_flush(ep); 520 521 /* Hold the lock while we update the request and buffer states */ 522 bh->outreq_busy = 0; 523 bh->state = BUF_STATE_FULL; 524 wakeup_thread(common); 525 } 526 527 /*-------------------------------------------------------------------------*/ 528 529 /* Ep0 class-specific handlers. These always run in_irq. */ 530 531 static int fsg_setup(struct usb_function *f, 532 const struct usb_ctrlrequest *ctrl) 533 { 534 struct fsg_dev *fsg = fsg_from_func(f); 535 struct usb_request *req = fsg->common->ep0req; 536 u16 w_index = get_unaligned_le16(&ctrl->wIndex); 537 u16 w_value = get_unaligned_le16(&ctrl->wValue); 538 u16 w_length = get_unaligned_le16(&ctrl->wLength); 539 540 if (!fsg_is_set(fsg->common)) 541 return -EOPNOTSUPP; 542 543 switch (ctrl->bRequest) { 544 545 case USB_BULK_RESET_REQUEST: 546 if (ctrl->bRequestType != 547 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE)) 548 break; 549 if (w_index != fsg->interface_number || w_value != 0) 550 return -EDOM; 551 552 /* Raise an exception to stop the current operation 553 * and reinitialize our state. */ 554 DBG(fsg, "bulk reset request\n"); 555 raise_exception(fsg->common, FSG_STATE_RESET); 556 return DELAYED_STATUS; 557 558 case USB_BULK_GET_MAX_LUN_REQUEST: 559 if (ctrl->bRequestType != 560 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE)) 561 break; 562 if (w_index != fsg->interface_number || w_value != 0) 563 return -EDOM; 564 VDBG(fsg, "get max LUN\n"); 565 *(u8 *) req->buf = fsg->common->nluns - 1; 566 567 /* Respond with data/status */ 568 req->length = min((u16)1, w_length); 569 return ep0_queue(fsg->common); 570 } 571 572 VDBG(fsg, 573 "unknown class-specific control req " 574 "%02x.%02x v%04x i%04x l%u\n", 575 ctrl->bRequestType, ctrl->bRequest, 576 get_unaligned_le16(&ctrl->wValue), w_index, w_length); 577 return -EOPNOTSUPP; 578 } 579 580 /*-------------------------------------------------------------------------*/ 581 582 /* All the following routines run in process context */ 583 584 /* Use this for bulk or interrupt transfers, not ep0 */ 585 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep, 586 struct usb_request *req, int *pbusy, 587 enum fsg_buffer_state *state) 588 { 589 int rc; 590 591 if (ep == fsg->bulk_in) 592 dump_msg(fsg, "bulk-in", req->buf, req->length); 593 594 *pbusy = 1; 595 *state = BUF_STATE_BUSY; 596 rc = usb_ep_queue(ep, req, GFP_KERNEL); 597 if (rc != 0) { 598 *pbusy = 0; 599 *state = BUF_STATE_EMPTY; 600 601 /* We can't do much more than wait for a reset */ 602 603 /* Note: currently the net2280 driver fails zero-length 604 * submissions if DMA is enabled. */ 605 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP && 606 req->length == 0)) 607 WARNING(fsg, "error in submission: %s --> %d\n", 608 ep->name, rc); 609 } 610 } 611 612 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \ 613 if (fsg_is_set(common)) \ 614 start_transfer((common)->fsg, (common)->fsg->ep_name, \ 615 req, pbusy, state); \ 616 else 617 618 #define START_TRANSFER(common, ep_name, req, pbusy, state) \ 619 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0 620 621 static void busy_indicator(void) 622 { 623 static int state; 624 625 switch (state) { 626 case 0: 627 puts("\r|"); break; 628 case 1: 629 puts("\r/"); break; 630 case 2: 631 puts("\r-"); break; 632 case 3: 633 puts("\r\\"); break; 634 case 4: 635 puts("\r|"); break; 636 case 5: 637 puts("\r/"); break; 638 case 6: 639 puts("\r-"); break; 640 case 7: 641 puts("\r\\"); break; 642 default: 643 state = 0; 644 } 645 if (state++ == 8) 646 state = 0; 647 } 648 649 static int sleep_thread(struct fsg_common *common) 650 { 651 int rc = 0; 652 int i = 0, k = 0; 653 654 /* Wait until a signal arrives or we are woken up */ 655 for (;;) { 656 if (common->thread_wakeup_needed) 657 break; 658 659 if (++i == 20000) { 660 busy_indicator(); 661 i = 0; 662 k++; 663 } 664 665 if (k == 10) { 666 /* Handle CTRL+C */ 667 if (ctrlc()) 668 return -EPIPE; 669 670 /* Check cable connection */ 671 if (!g_dnl_board_usb_cable_connected()) 672 return -EIO; 673 674 k = 0; 675 } 676 677 #ifdef CONFIG_USB_DWC3_GADGET 678 if (rkusb_usb3_capable() && !dwc3_gadget_is_connected() 679 && !rkusb_force_usb2_enabled()) 680 return -ENODEV; 681 #endif 682 683 usb_gadget_handle_interrupts(0); 684 } 685 common->thread_wakeup_needed = 0; 686 return rc; 687 } 688 689 /*-------------------------------------------------------------------------*/ 690 691 static int do_read(struct fsg_common *common) 692 { 693 struct fsg_lun *curlun = &common->luns[common->lun]; 694 u32 lba; 695 struct fsg_buffhd *bh; 696 int rc; 697 u32 amount_left; 698 loff_t file_offset; 699 unsigned int amount; 700 unsigned int partial_page; 701 ssize_t nread; 702 703 /* Get the starting Logical Block Address and check that it's 704 * not too big */ 705 if (common->cmnd[0] == SC_READ_6) 706 lba = get_unaligned_be24(&common->cmnd[1]); 707 else { 708 lba = get_unaligned_be32(&common->cmnd[2]); 709 710 /* We allow DPO (Disable Page Out = don't save data in the 711 * cache) and FUA (Force Unit Access = don't read from the 712 * cache), but we don't implement them. */ 713 if ((common->cmnd[1] & ~0x18) != 0) { 714 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 715 return -EINVAL; 716 } 717 } 718 if (lba >= curlun->num_sectors) { 719 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 720 return -EINVAL; 721 } 722 file_offset = ((loff_t) lba) << 9; 723 724 /* Carry out the file reads */ 725 amount_left = common->data_size_from_cmnd; 726 if (unlikely(amount_left == 0)) 727 return -EIO; /* No default reply */ 728 729 for (;;) { 730 731 /* Figure out how much we need to read: 732 * Try to read the remaining amount. 733 * But don't read more than the buffer size. 734 * And don't try to read past the end of the file. 735 * Finally, if we're not at a page boundary, don't read past 736 * the next page. 737 * If this means reading 0 then we were asked to read past 738 * the end of file. */ 739 amount = min(amount_left, FSG_BUFLEN); 740 partial_page = file_offset & (PAGE_CACHE_SIZE - 1); 741 if (partial_page > 0) 742 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE - 743 partial_page); 744 745 /* Wait for the next buffer to become available */ 746 bh = common->next_buffhd_to_fill; 747 while (bh->state != BUF_STATE_EMPTY) { 748 rc = sleep_thread(common); 749 if (rc) 750 return rc; 751 } 752 753 /* If we were asked to read past the end of file, 754 * end with an empty buffer. */ 755 if (amount == 0) { 756 curlun->sense_data = 757 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 758 curlun->info_valid = 1; 759 bh->inreq->length = 0; 760 bh->state = BUF_STATE_FULL; 761 break; 762 } 763 764 /* Perform the read */ 765 rc = ums[common->lun].read_sector(&ums[common->lun], 766 file_offset / SECTOR_SIZE, 767 amount / SECTOR_SIZE, 768 (char __user *)bh->buf); 769 if (!rc) 770 return -EIO; 771 772 nread = rc * SECTOR_SIZE; 773 774 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, 775 (unsigned long long) file_offset, 776 (int) nread); 777 778 if (nread < 0) { 779 LDBG(curlun, "error in file read: %d\n", 780 (int) nread); 781 nread = 0; 782 } else if (nread < amount) { 783 LDBG(curlun, "partial file read: %d/%u\n", 784 (int) nread, amount); 785 nread -= (nread & 511); /* Round down to a block */ 786 } 787 file_offset += nread; 788 amount_left -= nread; 789 common->residue -= nread; 790 bh->inreq->length = nread; 791 bh->state = BUF_STATE_FULL; 792 793 /* If an error occurred, report it and its position */ 794 if (nread < amount) { 795 curlun->sense_data = SS_UNRECOVERED_READ_ERROR; 796 curlun->info_valid = 1; 797 break; 798 } 799 800 if (amount_left == 0) 801 break; /* No more left to read */ 802 803 /* Send this buffer and go read some more */ 804 bh->inreq->zero = 0; 805 START_TRANSFER_OR(common, bulk_in, bh->inreq, 806 &bh->inreq_busy, &bh->state) 807 /* Don't know what to do if 808 * common->fsg is NULL */ 809 return -EIO; 810 common->next_buffhd_to_fill = bh->next; 811 } 812 813 return -EIO; /* No default reply */ 814 } 815 816 /*-------------------------------------------------------------------------*/ 817 818 static int do_write(struct fsg_common *common) 819 { 820 struct fsg_lun *curlun = &common->luns[common->lun]; 821 u32 lba; 822 struct fsg_buffhd *bh; 823 int get_some_more; 824 u32 amount_left_to_req, amount_left_to_write; 825 loff_t usb_offset, file_offset; 826 unsigned int amount; 827 unsigned int partial_page; 828 ssize_t nwritten; 829 int rc; 830 const char *cdev_name __maybe_unused; 831 832 if (curlun->ro) { 833 curlun->sense_data = SS_WRITE_PROTECTED; 834 return -EINVAL; 835 } 836 837 /* Get the starting Logical Block Address and check that it's 838 * not too big */ 839 if (common->cmnd[0] == SC_WRITE_6) 840 lba = get_unaligned_be24(&common->cmnd[1]); 841 else { 842 lba = get_unaligned_be32(&common->cmnd[2]); 843 844 /* We allow DPO (Disable Page Out = don't save data in the 845 * cache) and FUA (Force Unit Access = write directly to the 846 * medium). We don't implement DPO; we implement FUA by 847 * performing synchronous output. */ 848 if (common->cmnd[1] & ~0x18) { 849 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 850 return -EINVAL; 851 } 852 } 853 if (lba >= curlun->num_sectors) { 854 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 855 return -EINVAL; 856 } 857 858 /* Carry out the file writes */ 859 get_some_more = 1; 860 file_offset = usb_offset = ((loff_t) lba) << 9; 861 amount_left_to_req = common->data_size_from_cmnd; 862 amount_left_to_write = common->data_size_from_cmnd; 863 864 while (amount_left_to_write > 0) { 865 866 /* Queue a request for more data from the host */ 867 bh = common->next_buffhd_to_fill; 868 if (bh->state == BUF_STATE_EMPTY && get_some_more) { 869 870 /* Figure out how much we want to get: 871 * Try to get the remaining amount. 872 * But don't get more than the buffer size. 873 * And don't try to go past the end of the file. 874 * If we're not at a page boundary, 875 * don't go past the next page. 876 * If this means getting 0, then we were asked 877 * to write past the end of file. 878 * Finally, round down to a block boundary. */ 879 amount = min(amount_left_to_req, FSG_BUFLEN); 880 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1); 881 if (partial_page > 0) 882 amount = min(amount, 883 (unsigned int) PAGE_CACHE_SIZE - partial_page); 884 885 if (amount == 0) { 886 get_some_more = 0; 887 curlun->sense_data = 888 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 889 curlun->info_valid = 1; 890 continue; 891 } 892 amount -= (amount & 511); 893 if (amount == 0) { 894 895 /* Why were we were asked to transfer a 896 * partial block? */ 897 get_some_more = 0; 898 continue; 899 } 900 901 /* Get the next buffer */ 902 usb_offset += amount; 903 common->usb_amount_left -= amount; 904 amount_left_to_req -= amount; 905 if (amount_left_to_req == 0) 906 get_some_more = 0; 907 908 /* amount is always divisible by 512, hence by 909 * the bulk-out maxpacket size */ 910 bh->outreq->length = amount; 911 bh->bulk_out_intended_length = amount; 912 bh->outreq->short_not_ok = 1; 913 START_TRANSFER_OR(common, bulk_out, bh->outreq, 914 &bh->outreq_busy, &bh->state) 915 /* Don't know what to do if 916 * common->fsg is NULL */ 917 return -EIO; 918 common->next_buffhd_to_fill = bh->next; 919 continue; 920 } 921 922 /* Write the received data to the backing file */ 923 bh = common->next_buffhd_to_drain; 924 if (bh->state == BUF_STATE_EMPTY && !get_some_more) 925 break; /* We stopped early */ 926 if (bh->state == BUF_STATE_FULL) { 927 common->next_buffhd_to_drain = bh->next; 928 bh->state = BUF_STATE_EMPTY; 929 930 /* Did something go wrong with the transfer? */ 931 if (bh->outreq->status != 0) { 932 curlun->sense_data = SS_COMMUNICATION_FAILURE; 933 curlun->info_valid = 1; 934 break; 935 } 936 937 amount = bh->outreq->actual; 938 939 /* Perform the write */ 940 rc = ums[common->lun].write_sector(&ums[common->lun], 941 file_offset / SECTOR_SIZE, 942 amount / SECTOR_SIZE, 943 (char __user *)bh->buf); 944 if (!rc) 945 return -EIO; 946 nwritten = rc * SECTOR_SIZE; 947 948 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount, 949 (unsigned long long) file_offset, 950 (int) nwritten); 951 952 if (nwritten < 0) { 953 LDBG(curlun, "error in file write: %d\n", 954 (int) nwritten); 955 nwritten = 0; 956 } else if (nwritten < amount) { 957 LDBG(curlun, "partial file write: %d/%u\n", 958 (int) nwritten, amount); 959 nwritten -= (nwritten & 511); 960 /* Round down to a block */ 961 } 962 file_offset += nwritten; 963 amount_left_to_write -= nwritten; 964 common->residue -= nwritten; 965 966 /* If an error occurred, report it and its position */ 967 if (nwritten < amount) { 968 printf("nwritten:%zd amount:%u\n", nwritten, 969 amount); 970 curlun->sense_data = SS_WRITE_ERROR; 971 curlun->info_valid = 1; 972 break; 973 } 974 975 /* Did the host decide to stop early? */ 976 if (bh->outreq->actual != bh->outreq->length) { 977 common->short_packet_received = 1; 978 break; 979 } 980 continue; 981 } 982 983 /* Wait for something to happen */ 984 rc = sleep_thread(common); 985 if (rc) 986 return rc; 987 } 988 989 cdev_name = common->fsg->function.config->cdev->driver->name; 990 if (IS_RKUSB_UMS_DNL(cdev_name)) 991 rkusb_do_check_parity(common); 992 993 return -EIO; /* No default reply */ 994 } 995 996 /*-------------------------------------------------------------------------*/ 997 998 static int do_synchronize_cache(struct fsg_common *common) 999 { 1000 return 0; 1001 } 1002 1003 /*-------------------------------------------------------------------------*/ 1004 1005 static int do_verify(struct fsg_common *common) 1006 { 1007 struct fsg_lun *curlun = &common->luns[common->lun]; 1008 u32 lba; 1009 u32 verification_length; 1010 struct fsg_buffhd *bh = common->next_buffhd_to_fill; 1011 loff_t file_offset; 1012 u32 amount_left; 1013 unsigned int amount; 1014 ssize_t nread; 1015 int rc; 1016 1017 /* Get the starting Logical Block Address and check that it's 1018 * not too big */ 1019 lba = get_unaligned_be32(&common->cmnd[2]); 1020 if (lba >= curlun->num_sectors) { 1021 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1022 return -EINVAL; 1023 } 1024 1025 /* We allow DPO (Disable Page Out = don't save data in the 1026 * cache) but we don't implement it. */ 1027 if (common->cmnd[1] & ~0x10) { 1028 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1029 return -EINVAL; 1030 } 1031 1032 verification_length = get_unaligned_be16(&common->cmnd[7]); 1033 if (unlikely(verification_length == 0)) 1034 return -EIO; /* No default reply */ 1035 1036 /* Prepare to carry out the file verify */ 1037 amount_left = verification_length << 9; 1038 file_offset = ((loff_t) lba) << 9; 1039 1040 /* Write out all the dirty buffers before invalidating them */ 1041 1042 /* Just try to read the requested blocks */ 1043 while (amount_left > 0) { 1044 1045 /* Figure out how much we need to read: 1046 * Try to read the remaining amount, but not more than 1047 * the buffer size. 1048 * And don't try to read past the end of the file. 1049 * If this means reading 0 then we were asked to read 1050 * past the end of file. */ 1051 amount = min(amount_left, FSG_BUFLEN); 1052 if (amount == 0) { 1053 curlun->sense_data = 1054 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1055 curlun->info_valid = 1; 1056 break; 1057 } 1058 1059 /* Perform the read */ 1060 rc = ums[common->lun].read_sector(&ums[common->lun], 1061 file_offset / SECTOR_SIZE, 1062 amount / SECTOR_SIZE, 1063 (char __user *)bh->buf); 1064 if (!rc) 1065 return -EIO; 1066 nread = rc * SECTOR_SIZE; 1067 1068 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, 1069 (unsigned long long) file_offset, 1070 (int) nread); 1071 if (nread < 0) { 1072 LDBG(curlun, "error in file verify: %d\n", 1073 (int) nread); 1074 nread = 0; 1075 } else if (nread < amount) { 1076 LDBG(curlun, "partial file verify: %d/%u\n", 1077 (int) nread, amount); 1078 nread -= (nread & 511); /* Round down to a sector */ 1079 } 1080 if (nread == 0) { 1081 curlun->sense_data = SS_UNRECOVERED_READ_ERROR; 1082 curlun->info_valid = 1; 1083 break; 1084 } 1085 file_offset += nread; 1086 amount_left -= nread; 1087 } 1088 return 0; 1089 } 1090 1091 /*-------------------------------------------------------------------------*/ 1092 1093 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh) 1094 { 1095 struct fsg_lun *curlun = &common->luns[common->lun]; 1096 static const char vendor_id[] = "Linux "; 1097 u8 *buf = (u8 *) bh->buf; 1098 1099 if (!curlun) { /* Unsupported LUNs are okay */ 1100 common->bad_lun_okay = 1; 1101 memset(buf, 0, 36); 1102 buf[0] = 0x7f; /* Unsupported, no device-type */ 1103 buf[4] = 31; /* Additional length */ 1104 return 36; 1105 } 1106 1107 memset(buf, 0, 8); 1108 buf[0] = TYPE_DISK; 1109 buf[1] = curlun->removable ? 0x80 : 0; 1110 buf[2] = 2; /* ANSI SCSI level 2 */ 1111 buf[3] = 2; /* SCSI-2 INQUIRY data format */ 1112 buf[4] = 31; /* Additional length */ 1113 /* No special options */ 1114 sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char*) vendor_id , 1115 ums[common->lun].name, (u16) 0xffff); 1116 1117 return 36; 1118 } 1119 1120 1121 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh) 1122 { 1123 struct fsg_lun *curlun = &common->luns[common->lun]; 1124 u8 *buf = (u8 *) bh->buf; 1125 u32 sd, sdinfo; 1126 int valid; 1127 1128 /* 1129 * From the SCSI-2 spec., section 7.9 (Unit attention condition): 1130 * 1131 * If a REQUEST SENSE command is received from an initiator 1132 * with a pending unit attention condition (before the target 1133 * generates the contingent allegiance condition), then the 1134 * target shall either: 1135 * a) report any pending sense data and preserve the unit 1136 * attention condition on the logical unit, or, 1137 * b) report the unit attention condition, may discard any 1138 * pending sense data, and clear the unit attention 1139 * condition on the logical unit for that initiator. 1140 * 1141 * FSG normally uses option a); enable this code to use option b). 1142 */ 1143 #if 0 1144 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) { 1145 curlun->sense_data = curlun->unit_attention_data; 1146 curlun->unit_attention_data = SS_NO_SENSE; 1147 } 1148 #endif 1149 1150 if (!curlun) { /* Unsupported LUNs are okay */ 1151 common->bad_lun_okay = 1; 1152 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; 1153 sdinfo = 0; 1154 valid = 0; 1155 } else { 1156 sd = curlun->sense_data; 1157 valid = curlun->info_valid << 7; 1158 curlun->sense_data = SS_NO_SENSE; 1159 curlun->info_valid = 0; 1160 } 1161 1162 memset(buf, 0, 18); 1163 buf[0] = valid | 0x70; /* Valid, current error */ 1164 buf[2] = SK(sd); 1165 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */ 1166 buf[7] = 18 - 8; /* Additional sense length */ 1167 buf[12] = ASC(sd); 1168 buf[13] = ASCQ(sd); 1169 return 18; 1170 } 1171 1172 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh) 1173 { 1174 struct fsg_lun *curlun = &common->luns[common->lun]; 1175 u32 lba = get_unaligned_be32(&common->cmnd[2]); 1176 int pmi = common->cmnd[8]; 1177 u8 *buf = (u8 *) bh->buf; 1178 1179 /* Check the PMI and LBA fields */ 1180 if (pmi > 1 || (pmi == 0 && lba != 0)) { 1181 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1182 return -EINVAL; 1183 } 1184 1185 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]); 1186 /* Max logical block */ 1187 put_unaligned_be32(512, &buf[4]); /* Block length */ 1188 return 8; 1189 } 1190 1191 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh) 1192 { 1193 struct fsg_lun *curlun = &common->luns[common->lun]; 1194 int msf = common->cmnd[1] & 0x02; 1195 u32 lba = get_unaligned_be32(&common->cmnd[2]); 1196 u8 *buf = (u8 *) bh->buf; 1197 1198 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */ 1199 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1200 return -EINVAL; 1201 } 1202 if (lba >= curlun->num_sectors) { 1203 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1204 return -EINVAL; 1205 } 1206 1207 memset(buf, 0, 8); 1208 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */ 1209 store_cdrom_address(&buf[4], msf, lba); 1210 return 8; 1211 } 1212 1213 1214 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh) 1215 { 1216 struct fsg_lun *curlun = &common->luns[common->lun]; 1217 int msf = common->cmnd[1] & 0x02; 1218 int start_track = common->cmnd[6]; 1219 u8 *buf = (u8 *) bh->buf; 1220 1221 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */ 1222 start_track > 1) { 1223 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1224 return -EINVAL; 1225 } 1226 1227 memset(buf, 0, 20); 1228 buf[1] = (20-2); /* TOC data length */ 1229 buf[2] = 1; /* First track number */ 1230 buf[3] = 1; /* Last track number */ 1231 buf[5] = 0x16; /* Data track, copying allowed */ 1232 buf[6] = 0x01; /* Only track is number 1 */ 1233 store_cdrom_address(&buf[8], msf, 0); 1234 1235 buf[13] = 0x16; /* Lead-out track is data */ 1236 buf[14] = 0xAA; /* Lead-out track number */ 1237 store_cdrom_address(&buf[16], msf, curlun->num_sectors); 1238 1239 return 20; 1240 } 1241 1242 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh) 1243 { 1244 struct fsg_lun *curlun = &common->luns[common->lun]; 1245 int mscmnd = common->cmnd[0]; 1246 u8 *buf = (u8 *) bh->buf; 1247 u8 *buf0 = buf; 1248 int pc, page_code; 1249 int changeable_values, all_pages; 1250 int valid_page = 0; 1251 int len, limit; 1252 1253 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */ 1254 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1255 return -EINVAL; 1256 } 1257 pc = common->cmnd[2] >> 6; 1258 page_code = common->cmnd[2] & 0x3f; 1259 if (pc == 3) { 1260 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED; 1261 return -EINVAL; 1262 } 1263 changeable_values = (pc == 1); 1264 all_pages = (page_code == 0x3f); 1265 1266 /* Write the mode parameter header. Fixed values are: default 1267 * medium type, no cache control (DPOFUA), and no block descriptors. 1268 * The only variable value is the WriteProtect bit. We will fill in 1269 * the mode data length later. */ 1270 memset(buf, 0, 8); 1271 if (mscmnd == SC_MODE_SENSE_6) { 1272 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */ 1273 buf += 4; 1274 limit = 255; 1275 } else { /* SC_MODE_SENSE_10 */ 1276 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */ 1277 buf += 8; 1278 limit = 65535; /* Should really be FSG_BUFLEN */ 1279 } 1280 1281 /* No block descriptors */ 1282 1283 /* The mode pages, in numerical order. The only page we support 1284 * is the Caching page. */ 1285 if (page_code == 0x08 || all_pages) { 1286 valid_page = 1; 1287 buf[0] = 0x08; /* Page code */ 1288 buf[1] = 10; /* Page length */ 1289 memset(buf+2, 0, 10); /* None of the fields are changeable */ 1290 1291 if (!changeable_values) { 1292 buf[2] = 0x04; /* Write cache enable, */ 1293 /* Read cache not disabled */ 1294 /* No cache retention priorities */ 1295 put_unaligned_be16(0xffff, &buf[4]); 1296 /* Don't disable prefetch */ 1297 /* Minimum prefetch = 0 */ 1298 put_unaligned_be16(0xffff, &buf[8]); 1299 /* Maximum prefetch */ 1300 put_unaligned_be16(0xffff, &buf[10]); 1301 /* Maximum prefetch ceiling */ 1302 } 1303 buf += 12; 1304 } 1305 1306 /* Check that a valid page was requested and the mode data length 1307 * isn't too long. */ 1308 len = buf - buf0; 1309 if (!valid_page || len > limit) { 1310 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1311 return -EINVAL; 1312 } 1313 1314 /* Store the mode data length */ 1315 if (mscmnd == SC_MODE_SENSE_6) 1316 buf0[0] = len - 1; 1317 else 1318 put_unaligned_be16(len - 2, buf0); 1319 return len; 1320 } 1321 1322 1323 static int do_start_stop(struct fsg_common *common) 1324 { 1325 struct fsg_lun *curlun = &common->luns[common->lun]; 1326 1327 if (!curlun) { 1328 return -EINVAL; 1329 } else if (!curlun->removable) { 1330 curlun->sense_data = SS_INVALID_COMMAND; 1331 return -EINVAL; 1332 } 1333 1334 return 0; 1335 } 1336 1337 static int do_prevent_allow(struct fsg_common *common) 1338 { 1339 struct fsg_lun *curlun = &common->luns[common->lun]; 1340 int prevent; 1341 1342 if (!curlun->removable) { 1343 curlun->sense_data = SS_INVALID_COMMAND; 1344 return -EINVAL; 1345 } 1346 1347 prevent = common->cmnd[4] & 0x01; 1348 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */ 1349 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1350 return -EINVAL; 1351 } 1352 1353 if (curlun->prevent_medium_removal && !prevent) 1354 fsg_lun_fsync_sub(curlun); 1355 curlun->prevent_medium_removal = prevent; 1356 return 0; 1357 } 1358 1359 1360 static int do_read_format_capacities(struct fsg_common *common, 1361 struct fsg_buffhd *bh) 1362 { 1363 struct fsg_lun *curlun = &common->luns[common->lun]; 1364 u8 *buf = (u8 *) bh->buf; 1365 1366 buf[0] = buf[1] = buf[2] = 0; 1367 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */ 1368 buf += 4; 1369 1370 put_unaligned_be32(curlun->num_sectors, &buf[0]); 1371 /* Number of blocks */ 1372 put_unaligned_be32(512, &buf[4]); /* Block length */ 1373 buf[4] = 0x02; /* Current capacity */ 1374 return 12; 1375 } 1376 1377 1378 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh) 1379 { 1380 struct fsg_lun *curlun = &common->luns[common->lun]; 1381 1382 /* We don't support MODE SELECT */ 1383 if (curlun) 1384 curlun->sense_data = SS_INVALID_COMMAND; 1385 return -EINVAL; 1386 } 1387 1388 1389 /*-------------------------------------------------------------------------*/ 1390 1391 static int halt_bulk_in_endpoint(struct fsg_dev *fsg) 1392 { 1393 int rc; 1394 1395 rc = fsg_set_halt(fsg, fsg->bulk_in); 1396 if (rc == -EAGAIN) 1397 VDBG(fsg, "delayed bulk-in endpoint halt\n"); 1398 while (rc != 0) { 1399 if (rc != -EAGAIN) { 1400 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc); 1401 rc = 0; 1402 break; 1403 } 1404 1405 rc = usb_ep_set_halt(fsg->bulk_in); 1406 } 1407 return rc; 1408 } 1409 1410 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg) 1411 { 1412 int rc; 1413 1414 DBG(fsg, "bulk-in set wedge\n"); 1415 rc = 0; /* usb_ep_set_wedge(fsg->bulk_in); */ 1416 if (rc == -EAGAIN) 1417 VDBG(fsg, "delayed bulk-in endpoint wedge\n"); 1418 while (rc != 0) { 1419 if (rc != -EAGAIN) { 1420 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc); 1421 rc = 0; 1422 break; 1423 } 1424 } 1425 return rc; 1426 } 1427 1428 static int pad_with_zeros(struct fsg_dev *fsg) 1429 { 1430 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill; 1431 u32 nkeep = bh->inreq->length; 1432 u32 nsend; 1433 int rc; 1434 1435 bh->state = BUF_STATE_EMPTY; /* For the first iteration */ 1436 fsg->common->usb_amount_left = nkeep + fsg->common->residue; 1437 while (fsg->common->usb_amount_left > 0) { 1438 1439 /* Wait for the next buffer to be free */ 1440 while (bh->state != BUF_STATE_EMPTY) { 1441 rc = sleep_thread(fsg->common); 1442 if (rc) 1443 return rc; 1444 } 1445 1446 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN); 1447 memset(bh->buf + nkeep, 0, nsend - nkeep); 1448 bh->inreq->length = nsend; 1449 bh->inreq->zero = 0; 1450 start_transfer(fsg, fsg->bulk_in, bh->inreq, 1451 &bh->inreq_busy, &bh->state); 1452 bh = fsg->common->next_buffhd_to_fill = bh->next; 1453 fsg->common->usb_amount_left -= nsend; 1454 nkeep = 0; 1455 } 1456 return 0; 1457 } 1458 1459 static int throw_away_data(struct fsg_common *common) 1460 { 1461 struct fsg_buffhd *bh; 1462 u32 amount; 1463 int rc; 1464 1465 for (bh = common->next_buffhd_to_drain; 1466 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0; 1467 bh = common->next_buffhd_to_drain) { 1468 1469 /* Throw away the data in a filled buffer */ 1470 if (bh->state == BUF_STATE_FULL) { 1471 bh->state = BUF_STATE_EMPTY; 1472 common->next_buffhd_to_drain = bh->next; 1473 1474 /* A short packet or an error ends everything */ 1475 if (bh->outreq->actual != bh->outreq->length || 1476 bh->outreq->status != 0) { 1477 raise_exception(common, 1478 FSG_STATE_ABORT_BULK_OUT); 1479 return -EINTR; 1480 } 1481 continue; 1482 } 1483 1484 /* Try to submit another request if we need one */ 1485 bh = common->next_buffhd_to_fill; 1486 if (bh->state == BUF_STATE_EMPTY 1487 && common->usb_amount_left > 0) { 1488 amount = min(common->usb_amount_left, FSG_BUFLEN); 1489 1490 /* amount is always divisible by 512, hence by 1491 * the bulk-out maxpacket size */ 1492 bh->outreq->length = amount; 1493 bh->bulk_out_intended_length = amount; 1494 bh->outreq->short_not_ok = 1; 1495 START_TRANSFER_OR(common, bulk_out, bh->outreq, 1496 &bh->outreq_busy, &bh->state) 1497 /* Don't know what to do if 1498 * common->fsg is NULL */ 1499 return -EIO; 1500 common->next_buffhd_to_fill = bh->next; 1501 common->usb_amount_left -= amount; 1502 continue; 1503 } 1504 1505 /* Otherwise wait for something to happen */ 1506 rc = sleep_thread(common); 1507 if (rc) 1508 return rc; 1509 } 1510 return 0; 1511 } 1512 1513 1514 static int finish_reply(struct fsg_common *common) 1515 { 1516 struct fsg_buffhd *bh = common->next_buffhd_to_fill; 1517 int rc = 0; 1518 1519 switch (common->data_dir) { 1520 case DATA_DIR_NONE: 1521 break; /* Nothing to send */ 1522 1523 /* If we don't know whether the host wants to read or write, 1524 * this must be CB or CBI with an unknown command. We mustn't 1525 * try to send or receive any data. So stall both bulk pipes 1526 * if we can and wait for a reset. */ 1527 case DATA_DIR_UNKNOWN: 1528 if (!common->can_stall) { 1529 /* Nothing */ 1530 } else if (fsg_is_set(common)) { 1531 fsg_set_halt(common->fsg, common->fsg->bulk_out); 1532 rc = halt_bulk_in_endpoint(common->fsg); 1533 } else { 1534 /* Don't know what to do if common->fsg is NULL */ 1535 rc = -EIO; 1536 } 1537 break; 1538 1539 /* All but the last buffer of data must have already been sent */ 1540 case DATA_DIR_TO_HOST: 1541 if (common->data_size == 0) { 1542 /* Nothing to send */ 1543 1544 /* If there's no residue, simply send the last buffer */ 1545 } else if (common->residue == 0) { 1546 bh->inreq->zero = 0; 1547 START_TRANSFER_OR(common, bulk_in, bh->inreq, 1548 &bh->inreq_busy, &bh->state) 1549 return -EIO; 1550 common->next_buffhd_to_fill = bh->next; 1551 1552 /* For Bulk-only, if we're allowed to stall then send the 1553 * short packet and halt the bulk-in endpoint. If we can't 1554 * stall, pad out the remaining data with 0's. */ 1555 } else if (common->can_stall) { 1556 bh->inreq->zero = 1; 1557 START_TRANSFER_OR(common, bulk_in, bh->inreq, 1558 &bh->inreq_busy, &bh->state) 1559 /* Don't know what to do if 1560 * common->fsg is NULL */ 1561 rc = -EIO; 1562 common->next_buffhd_to_fill = bh->next; 1563 if (common->fsg) 1564 rc = halt_bulk_in_endpoint(common->fsg); 1565 } else if (fsg_is_set(common)) { 1566 rc = pad_with_zeros(common->fsg); 1567 } else { 1568 /* Don't know what to do if common->fsg is NULL */ 1569 rc = -EIO; 1570 } 1571 break; 1572 1573 /* We have processed all we want from the data the host has sent. 1574 * There may still be outstanding bulk-out requests. */ 1575 case DATA_DIR_FROM_HOST: 1576 if (common->residue == 0) { 1577 /* Nothing to receive */ 1578 1579 /* Did the host stop sending unexpectedly early? */ 1580 } else if (common->short_packet_received) { 1581 raise_exception(common, FSG_STATE_ABORT_BULK_OUT); 1582 rc = -EINTR; 1583 1584 /* We haven't processed all the incoming data. Even though 1585 * we may be allowed to stall, doing so would cause a race. 1586 * The controller may already have ACK'ed all the remaining 1587 * bulk-out packets, in which case the host wouldn't see a 1588 * STALL. Not realizing the endpoint was halted, it wouldn't 1589 * clear the halt -- leading to problems later on. */ 1590 #if 0 1591 } else if (common->can_stall) { 1592 if (fsg_is_set(common)) 1593 fsg_set_halt(common->fsg, 1594 common->fsg->bulk_out); 1595 raise_exception(common, FSG_STATE_ABORT_BULK_OUT); 1596 rc = -EINTR; 1597 #endif 1598 1599 /* We can't stall. Read in the excess data and throw it 1600 * all away. */ 1601 } else { 1602 rc = throw_away_data(common); 1603 } 1604 break; 1605 } 1606 return rc; 1607 } 1608 1609 1610 static int send_status(struct fsg_common *common) 1611 { 1612 struct fsg_lun *curlun = &common->luns[common->lun]; 1613 struct fsg_buffhd *bh; 1614 struct bulk_cs_wrap *csw; 1615 int rc; 1616 u8 status = USB_STATUS_PASS; 1617 u32 sd, sdinfo = 0; 1618 1619 /* Wait for the next buffer to become available */ 1620 bh = common->next_buffhd_to_fill; 1621 while (bh->state != BUF_STATE_EMPTY) { 1622 rc = sleep_thread(common); 1623 if (rc) 1624 return rc; 1625 } 1626 1627 if (curlun) 1628 sd = curlun->sense_data; 1629 else if (common->bad_lun_okay) 1630 sd = SS_NO_SENSE; 1631 else 1632 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; 1633 1634 if (common->phase_error) { 1635 DBG(common, "sending phase-error status\n"); 1636 status = USB_STATUS_PHASE_ERROR; 1637 sd = SS_INVALID_COMMAND; 1638 } else if (sd != SS_NO_SENSE) { 1639 DBG(common, "sending command-failure status\n"); 1640 status = USB_STATUS_FAIL; 1641 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;" 1642 " info x%x\n", 1643 SK(sd), ASC(sd), ASCQ(sd), sdinfo); 1644 } 1645 1646 /* Store and send the Bulk-only CSW */ 1647 csw = (void *)bh->buf; 1648 1649 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG); 1650 csw->Tag = common->tag; 1651 csw->Residue = cpu_to_le32(common->residue); 1652 csw->Status = status; 1653 1654 bh->inreq->length = USB_BULK_CS_WRAP_LEN; 1655 bh->inreq->zero = 0; 1656 START_TRANSFER_OR(common, bulk_in, bh->inreq, 1657 &bh->inreq_busy, &bh->state) 1658 /* Don't know what to do if common->fsg is NULL */ 1659 return -EIO; 1660 1661 common->next_buffhd_to_fill = bh->next; 1662 return 0; 1663 } 1664 1665 1666 /*-------------------------------------------------------------------------*/ 1667 #ifdef CONFIG_CMD_ROCKUSB 1668 #include "f_rockusb.c" 1669 #endif 1670 1671 /* Check whether the command is properly formed and whether its data size 1672 * and direction agree with the values we already have. */ 1673 static int check_command(struct fsg_common *common, int cmnd_size, 1674 enum data_direction data_dir, unsigned int mask, 1675 int needs_medium, const char *name) 1676 { 1677 int i; 1678 int lun = common->cmnd[1] >> 5; 1679 static const char dirletter[4] = {'u', 'o', 'i', 'n'}; 1680 char hdlen[20]; 1681 struct fsg_lun *curlun; 1682 1683 hdlen[0] = 0; 1684 if (common->data_dir != DATA_DIR_UNKNOWN) 1685 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir], 1686 common->data_size); 1687 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n", 1688 name, cmnd_size, dirletter[(int) data_dir], 1689 common->data_size_from_cmnd, common->cmnd_size, hdlen); 1690 1691 /* We can't reply at all until we know the correct data direction 1692 * and size. */ 1693 if (common->data_size_from_cmnd == 0) 1694 data_dir = DATA_DIR_NONE; 1695 if (common->data_size < common->data_size_from_cmnd) { 1696 /* Host data size < Device data size is a phase error. 1697 * Carry out the command, but only transfer as much as 1698 * we are allowed. */ 1699 common->data_size_from_cmnd = common->data_size; 1700 common->phase_error = 1; 1701 } 1702 common->residue = common->data_size; 1703 common->usb_amount_left = common->data_size; 1704 1705 /* Conflicting data directions is a phase error */ 1706 if (common->data_dir != data_dir 1707 && common->data_size_from_cmnd > 0) { 1708 common->phase_error = 1; 1709 return -EINVAL; 1710 } 1711 1712 /* Verify the length of the command itself */ 1713 if (cmnd_size != common->cmnd_size) { 1714 1715 /* Special case workaround: There are plenty of buggy SCSI 1716 * implementations. Many have issues with cbw->Length 1717 * field passing a wrong command size. For those cases we 1718 * always try to work around the problem by using the length 1719 * sent by the host side provided it is at least as large 1720 * as the correct command length. 1721 * Examples of such cases would be MS-Windows, which issues 1722 * REQUEST SENSE with cbw->Length == 12 where it should 1723 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and 1724 * REQUEST SENSE with cbw->Length == 10 where it should 1725 * be 6 as well. 1726 */ 1727 if (cmnd_size <= common->cmnd_size) { 1728 DBG(common, "%s is buggy! Expected length %d " 1729 "but we got %d\n", name, 1730 cmnd_size, common->cmnd_size); 1731 cmnd_size = common->cmnd_size; 1732 } else { 1733 common->phase_error = 1; 1734 return -EINVAL; 1735 } 1736 } 1737 1738 /* Check that the LUN values are consistent */ 1739 if (common->lun != lun) 1740 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n", 1741 common->lun, lun); 1742 1743 /* Check the LUN */ 1744 if (common->lun < common->nluns) { 1745 curlun = &common->luns[common->lun]; 1746 if (common->cmnd[0] != SC_REQUEST_SENSE) { 1747 curlun->sense_data = SS_NO_SENSE; 1748 curlun->info_valid = 0; 1749 } 1750 } else { 1751 curlun = NULL; 1752 common->bad_lun_okay = 0; 1753 1754 /* INQUIRY and REQUEST SENSE commands are explicitly allowed 1755 * to use unsupported LUNs; all others may not. */ 1756 if (common->cmnd[0] != SC_INQUIRY && 1757 common->cmnd[0] != SC_REQUEST_SENSE) { 1758 DBG(common, "unsupported LUN %d\n", common->lun); 1759 return -EINVAL; 1760 } 1761 } 1762 #if 0 1763 /* If a unit attention condition exists, only INQUIRY and 1764 * REQUEST SENSE commands are allowed; anything else must fail. */ 1765 if (curlun && curlun->unit_attention_data != SS_NO_SENSE && 1766 common->cmnd[0] != SC_INQUIRY && 1767 common->cmnd[0] != SC_REQUEST_SENSE) { 1768 curlun->sense_data = curlun->unit_attention_data; 1769 curlun->unit_attention_data = SS_NO_SENSE; 1770 return -EINVAL; 1771 } 1772 #endif 1773 /* Check that only command bytes listed in the mask are non-zero */ 1774 common->cmnd[1] &= 0x1f; /* Mask away the LUN */ 1775 for (i = 1; i < cmnd_size; ++i) { 1776 if (common->cmnd[i] && !(mask & (1 << i))) { 1777 if (curlun) 1778 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1779 return -EINVAL; 1780 } 1781 } 1782 1783 return 0; 1784 } 1785 1786 1787 static int do_scsi_command(struct fsg_common *common) 1788 { 1789 struct fsg_buffhd *bh; 1790 int rc; 1791 int reply = -EINVAL; 1792 int i; 1793 static char unknown[16]; 1794 struct fsg_lun *curlun = &common->luns[common->lun]; 1795 const char *cdev_name __maybe_unused; 1796 1797 dump_cdb(common); 1798 1799 /* Wait for the next buffer to become available for data or status */ 1800 bh = common->next_buffhd_to_fill; 1801 common->next_buffhd_to_drain = bh; 1802 while (bh->state != BUF_STATE_EMPTY) { 1803 rc = sleep_thread(common); 1804 if (rc) 1805 return rc; 1806 } 1807 common->phase_error = 0; 1808 common->short_packet_received = 0; 1809 1810 down_read(&common->filesem); /* We're using the backing file */ 1811 1812 cdev_name = common->fsg->function.config->cdev->driver->name; 1813 if (IS_RKUSB_UMS_DNL(cdev_name)) { 1814 rc = rkusb_cmd_process(common, bh, &reply); 1815 if (rc == RKUSB_RC_FINISHED || rc == RKUSB_RC_ERROR) 1816 goto finish; 1817 else if (rc == RKUSB_RC_UNKNOWN_CMND) 1818 goto unknown_cmnd; 1819 } 1820 1821 switch (common->cmnd[0]) { 1822 1823 case SC_INQUIRY: 1824 common->data_size_from_cmnd = common->cmnd[4]; 1825 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1826 (1<<4), 0, 1827 "INQUIRY"); 1828 if (reply == 0) 1829 reply = do_inquiry(common, bh); 1830 break; 1831 1832 case SC_MODE_SELECT_6: 1833 common->data_size_from_cmnd = common->cmnd[4]; 1834 reply = check_command(common, 6, DATA_DIR_FROM_HOST, 1835 (1<<1) | (1<<4), 0, 1836 "MODE SELECT(6)"); 1837 if (reply == 0) 1838 reply = do_mode_select(common, bh); 1839 break; 1840 1841 case SC_MODE_SELECT_10: 1842 common->data_size_from_cmnd = 1843 get_unaligned_be16(&common->cmnd[7]); 1844 reply = check_command(common, 10, DATA_DIR_FROM_HOST, 1845 (1<<1) | (3<<7), 0, 1846 "MODE SELECT(10)"); 1847 if (reply == 0) 1848 reply = do_mode_select(common, bh); 1849 break; 1850 1851 case SC_MODE_SENSE_6: 1852 common->data_size_from_cmnd = common->cmnd[4]; 1853 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1854 (1<<1) | (1<<2) | (1<<4), 0, 1855 "MODE SENSE(6)"); 1856 if (reply == 0) 1857 reply = do_mode_sense(common, bh); 1858 break; 1859 1860 case SC_MODE_SENSE_10: 1861 common->data_size_from_cmnd = 1862 get_unaligned_be16(&common->cmnd[7]); 1863 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1864 (1<<1) | (1<<2) | (3<<7), 0, 1865 "MODE SENSE(10)"); 1866 if (reply == 0) 1867 reply = do_mode_sense(common, bh); 1868 break; 1869 1870 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL: 1871 common->data_size_from_cmnd = 0; 1872 reply = check_command(common, 6, DATA_DIR_NONE, 1873 (1<<4), 0, 1874 "PREVENT-ALLOW MEDIUM REMOVAL"); 1875 if (reply == 0) 1876 reply = do_prevent_allow(common); 1877 break; 1878 1879 case SC_READ_6: 1880 i = common->cmnd[4]; 1881 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9; 1882 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1883 (7<<1) | (1<<4), 1, 1884 "READ(6)"); 1885 if (reply == 0) 1886 reply = do_read(common); 1887 break; 1888 1889 case SC_READ_10: 1890 common->data_size_from_cmnd = 1891 get_unaligned_be16(&common->cmnd[7]) << 9; 1892 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1893 (1<<1) | (0xf<<2) | (3<<7), 1, 1894 "READ(10)"); 1895 if (reply == 0) 1896 reply = do_read(common); 1897 break; 1898 1899 case SC_READ_12: 1900 common->data_size_from_cmnd = 1901 get_unaligned_be32(&common->cmnd[6]) << 9; 1902 reply = check_command(common, 12, DATA_DIR_TO_HOST, 1903 (1<<1) | (0xf<<2) | (0xf<<6), 1, 1904 "READ(12)"); 1905 if (reply == 0) 1906 reply = do_read(common); 1907 break; 1908 1909 case SC_READ_CAPACITY: 1910 common->data_size_from_cmnd = 8; 1911 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1912 (0xf<<2) | (1<<8), 1, 1913 "READ CAPACITY"); 1914 if (reply == 0) 1915 reply = do_read_capacity(common, bh); 1916 break; 1917 1918 case SC_READ_HEADER: 1919 if (!common->luns[common->lun].cdrom) 1920 goto unknown_cmnd; 1921 common->data_size_from_cmnd = 1922 get_unaligned_be16(&common->cmnd[7]); 1923 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1924 (3<<7) | (0x1f<<1), 1, 1925 "READ HEADER"); 1926 if (reply == 0) 1927 reply = do_read_header(common, bh); 1928 break; 1929 1930 case SC_READ_TOC: 1931 if (!common->luns[common->lun].cdrom) 1932 goto unknown_cmnd; 1933 common->data_size_from_cmnd = 1934 get_unaligned_be16(&common->cmnd[7]); 1935 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1936 (7<<6) | (1<<1), 1, 1937 "READ TOC"); 1938 if (reply == 0) 1939 reply = do_read_toc(common, bh); 1940 break; 1941 1942 case SC_READ_FORMAT_CAPACITIES: 1943 common->data_size_from_cmnd = 1944 get_unaligned_be16(&common->cmnd[7]); 1945 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1946 (3<<7), 1, 1947 "READ FORMAT CAPACITIES"); 1948 if (reply == 0) 1949 reply = do_read_format_capacities(common, bh); 1950 break; 1951 1952 case SC_REQUEST_SENSE: 1953 common->data_size_from_cmnd = common->cmnd[4]; 1954 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1955 (1<<4), 0, 1956 "REQUEST SENSE"); 1957 if (reply == 0) 1958 reply = do_request_sense(common, bh); 1959 break; 1960 1961 case SC_START_STOP_UNIT: 1962 common->data_size_from_cmnd = 0; 1963 reply = check_command(common, 6, DATA_DIR_NONE, 1964 (1<<1) | (1<<4), 0, 1965 "START-STOP UNIT"); 1966 if (reply == 0) 1967 reply = do_start_stop(common); 1968 break; 1969 1970 case SC_SYNCHRONIZE_CACHE: 1971 common->data_size_from_cmnd = 0; 1972 reply = check_command(common, 10, DATA_DIR_NONE, 1973 (0xf<<2) | (3<<7), 1, 1974 "SYNCHRONIZE CACHE"); 1975 if (reply == 0) 1976 reply = do_synchronize_cache(common); 1977 break; 1978 1979 case SC_TEST_UNIT_READY: 1980 common->data_size_from_cmnd = 0; 1981 reply = check_command(common, 6, DATA_DIR_NONE, 1982 0, 1, 1983 "TEST UNIT READY"); 1984 break; 1985 1986 /* Although optional, this command is used by MS-Windows. We 1987 * support a minimal version: BytChk must be 0. */ 1988 case SC_VERIFY: 1989 common->data_size_from_cmnd = 0; 1990 reply = check_command(common, 10, DATA_DIR_NONE, 1991 (1<<1) | (0xf<<2) | (3<<7), 1, 1992 "VERIFY"); 1993 if (reply == 0) 1994 reply = do_verify(common); 1995 break; 1996 1997 case SC_WRITE_6: 1998 i = common->cmnd[4]; 1999 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9; 2000 reply = check_command(common, 6, DATA_DIR_FROM_HOST, 2001 (7<<1) | (1<<4), 1, 2002 "WRITE(6)"); 2003 if (reply == 0) 2004 reply = do_write(common); 2005 break; 2006 2007 case SC_WRITE_10: 2008 common->data_size_from_cmnd = 2009 get_unaligned_be16(&common->cmnd[7]) << 9; 2010 2011 if (IS_RKUSB_UMS_DNL(cdev_name)) { 2012 reply = check_command(common, common->cmnd_size, DATA_DIR_FROM_HOST, 2013 (1 << 1) | (0xf << 2) | (3 << 7) | (0xf << 9), 1, 2014 "WRITE(10)"); 2015 } else { 2016 reply = check_command(common, 10, DATA_DIR_FROM_HOST, 2017 (1 << 1) | (0xf << 2) | (3 << 7), 1, 2018 "WRITE(10)"); 2019 } 2020 2021 if (reply == 0) 2022 reply = do_write(common); 2023 break; 2024 2025 case SC_WRITE_12: 2026 common->data_size_from_cmnd = 2027 get_unaligned_be32(&common->cmnd[6]) << 9; 2028 reply = check_command(common, 12, DATA_DIR_FROM_HOST, 2029 (1<<1) | (0xf<<2) | (0xf<<6), 1, 2030 "WRITE(12)"); 2031 if (reply == 0) 2032 reply = do_write(common); 2033 break; 2034 2035 /* Some mandatory commands that we recognize but don't implement. 2036 * They don't mean much in this setting. It's left as an exercise 2037 * for anyone interested to implement RESERVE and RELEASE in terms 2038 * of Posix locks. */ 2039 case SC_FORMAT_UNIT: 2040 case SC_RELEASE: 2041 case SC_RESERVE: 2042 case SC_SEND_DIAGNOSTIC: 2043 /* Fall through */ 2044 2045 default: 2046 unknown_cmnd: 2047 common->data_size_from_cmnd = 0; 2048 sprintf(unknown, "Unknown x%02x", common->cmnd[0]); 2049 reply = check_command(common, common->cmnd_size, 2050 DATA_DIR_UNKNOWN, 0xff, 0, unknown); 2051 if (reply == 0) { 2052 curlun->sense_data = SS_INVALID_COMMAND; 2053 reply = -EINVAL; 2054 } 2055 break; 2056 } 2057 2058 finish: 2059 up_read(&common->filesem); 2060 2061 if (reply == -EINTR) 2062 return -EINTR; 2063 2064 /* Set up the single reply buffer for finish_reply() */ 2065 if (reply == -EINVAL) 2066 reply = 0; /* Error reply length */ 2067 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) { 2068 reply = min((u32) reply, common->data_size_from_cmnd); 2069 bh->inreq->length = reply; 2070 bh->state = BUF_STATE_FULL; 2071 common->residue -= reply; 2072 } /* Otherwise it's already set */ 2073 2074 return 0; 2075 } 2076 2077 /*-------------------------------------------------------------------------*/ 2078 2079 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh) 2080 { 2081 struct usb_request *req = bh->outreq; 2082 struct fsg_bulk_cb_wrap *cbw = req->buf; 2083 struct fsg_common *common = fsg->common; 2084 2085 /* Was this a real packet? Should it be ignored? */ 2086 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags)) 2087 return -EINVAL; 2088 2089 /* Is the CBW valid? */ 2090 if (req->actual != USB_BULK_CB_WRAP_LEN || 2091 cbw->Signature != cpu_to_le32( 2092 USB_BULK_CB_SIG)) { 2093 DBG(fsg, "invalid CBW: len %u sig 0x%x\n", 2094 req->actual, 2095 le32_to_cpu(cbw->Signature)); 2096 2097 /* The Bulk-only spec says we MUST stall the IN endpoint 2098 * (6.6.1), so it's unavoidable. It also says we must 2099 * retain this state until the next reset, but there's 2100 * no way to tell the controller driver it should ignore 2101 * Clear-Feature(HALT) requests. 2102 * 2103 * We aren't required to halt the OUT endpoint; instead 2104 * we can simply accept and discard any data received 2105 * until the next reset. */ 2106 wedge_bulk_in_endpoint(fsg); 2107 generic_set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags); 2108 return -EINVAL; 2109 } 2110 2111 /* Is the CBW meaningful? */ 2112 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG || 2113 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) { 2114 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, " 2115 "cmdlen %u\n", 2116 cbw->Lun, cbw->Flags, cbw->Length); 2117 2118 /* We can do anything we want here, so let's stall the 2119 * bulk pipes if we are allowed to. */ 2120 if (common->can_stall) { 2121 fsg_set_halt(fsg, fsg->bulk_out); 2122 halt_bulk_in_endpoint(fsg); 2123 } 2124 return -EINVAL; 2125 } 2126 2127 /* Save the command for later */ 2128 common->cmnd_size = cbw->Length; 2129 memcpy(common->cmnd, cbw->CDB, common->cmnd_size); 2130 if (cbw->Flags & USB_BULK_IN_FLAG) 2131 common->data_dir = DATA_DIR_TO_HOST; 2132 else 2133 common->data_dir = DATA_DIR_FROM_HOST; 2134 common->data_size = le32_to_cpu(cbw->DataTransferLength); 2135 if (common->data_size == 0) 2136 common->data_dir = DATA_DIR_NONE; 2137 common->lun = cbw->Lun; 2138 common->tag = cbw->Tag; 2139 return 0; 2140 } 2141 2142 2143 static int get_next_command(struct fsg_common *common) 2144 { 2145 struct fsg_buffhd *bh; 2146 int rc = 0; 2147 2148 /* Wait for the next buffer to become available */ 2149 bh = common->next_buffhd_to_fill; 2150 while (bh->state != BUF_STATE_EMPTY) { 2151 rc = sleep_thread(common); 2152 if (rc) 2153 return rc; 2154 } 2155 2156 /* Queue a request to read a Bulk-only CBW */ 2157 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN); 2158 bh->outreq->short_not_ok = 1; 2159 START_TRANSFER_OR(common, bulk_out, bh->outreq, 2160 &bh->outreq_busy, &bh->state) 2161 /* Don't know what to do if common->fsg is NULL */ 2162 return -EIO; 2163 2164 /* We will drain the buffer in software, which means we 2165 * can reuse it for the next filling. No need to advance 2166 * next_buffhd_to_fill. */ 2167 2168 /* Wait for the CBW to arrive */ 2169 while (bh->state != BUF_STATE_FULL) { 2170 rc = sleep_thread(common); 2171 if (rc) 2172 return rc; 2173 } 2174 2175 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO; 2176 bh->state = BUF_STATE_EMPTY; 2177 2178 return rc; 2179 } 2180 2181 2182 /*-------------------------------------------------------------------------*/ 2183 2184 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep, 2185 const struct usb_endpoint_descriptor *d) 2186 { 2187 int rc; 2188 2189 ep->driver_data = common; 2190 rc = usb_ep_enable(ep, d); 2191 if (rc) 2192 ERROR(common, "can't enable %s, result %d\n", ep->name, rc); 2193 return rc; 2194 } 2195 2196 static int alloc_request(struct fsg_common *common, struct usb_ep *ep, 2197 struct usb_request **preq) 2198 { 2199 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC); 2200 if (*preq) 2201 return 0; 2202 ERROR(common, "can't allocate request for %s\n", ep->name); 2203 return -ENOMEM; 2204 } 2205 2206 /* Reset interface setting and re-init endpoint state (toggle etc). */ 2207 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg) 2208 { 2209 const struct usb_endpoint_descriptor *d; 2210 struct fsg_dev *fsg; 2211 int i, rc = 0; 2212 2213 if (common->running) 2214 DBG(common, "reset interface\n"); 2215 2216 reset: 2217 /* Deallocate the requests */ 2218 if (common->fsg) { 2219 fsg = common->fsg; 2220 2221 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2222 struct fsg_buffhd *bh = &common->buffhds[i]; 2223 2224 if (bh->inreq) { 2225 usb_ep_free_request(fsg->bulk_in, bh->inreq); 2226 bh->inreq = NULL; 2227 } 2228 if (bh->outreq) { 2229 usb_ep_free_request(fsg->bulk_out, bh->outreq); 2230 bh->outreq = NULL; 2231 } 2232 } 2233 2234 /* Disable the endpoints */ 2235 if (fsg->bulk_in_enabled) { 2236 usb_ep_disable(fsg->bulk_in); 2237 fsg->bulk_in_enabled = 0; 2238 } 2239 if (fsg->bulk_out_enabled) { 2240 usb_ep_disable(fsg->bulk_out); 2241 fsg->bulk_out_enabled = 0; 2242 } 2243 2244 common->fsg = NULL; 2245 /* wake_up(&common->fsg_wait); */ 2246 } 2247 2248 common->running = 0; 2249 if (!new_fsg || rc) 2250 return rc; 2251 2252 common->fsg = new_fsg; 2253 fsg = common->fsg; 2254 2255 /* Enable the endpoints */ 2256 d = fsg_ep_desc(common->gadget, 2257 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc, 2258 &fsg_ss_bulk_in_desc, &fsg_ss_bulk_in_comp_desc, 2259 fsg->bulk_in); 2260 rc = enable_endpoint(common, fsg->bulk_in, d); 2261 if (rc) 2262 goto reset; 2263 fsg->bulk_in_enabled = 1; 2264 2265 d = fsg_ep_desc(common->gadget, 2266 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc, 2267 &fsg_ss_bulk_out_desc, &fsg_ss_bulk_out_comp_desc, 2268 fsg->bulk_out); 2269 rc = enable_endpoint(common, fsg->bulk_out, d); 2270 if (rc) 2271 goto reset; 2272 fsg->bulk_out_enabled = 1; 2273 common->bulk_out_maxpacket = 2274 le16_to_cpu(get_unaligned(&d->wMaxPacketSize)); 2275 generic_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags); 2276 2277 /* Allocate the requests */ 2278 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2279 struct fsg_buffhd *bh = &common->buffhds[i]; 2280 2281 rc = alloc_request(common, fsg->bulk_in, &bh->inreq); 2282 if (rc) 2283 goto reset; 2284 rc = alloc_request(common, fsg->bulk_out, &bh->outreq); 2285 if (rc) 2286 goto reset; 2287 bh->inreq->buf = bh->outreq->buf = bh->buf; 2288 bh->inreq->context = bh->outreq->context = bh; 2289 bh->inreq->complete = bulk_in_complete; 2290 bh->outreq->complete = bulk_out_complete; 2291 } 2292 2293 common->running = 1; 2294 2295 return rc; 2296 } 2297 2298 2299 /****************************** ALT CONFIGS ******************************/ 2300 2301 2302 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt) 2303 { 2304 struct fsg_dev *fsg = fsg_from_func(f); 2305 fsg->common->new_fsg = fsg; 2306 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); 2307 return 0; 2308 } 2309 2310 static void fsg_disable(struct usb_function *f) 2311 { 2312 struct fsg_dev *fsg = fsg_from_func(f); 2313 fsg->common->new_fsg = NULL; 2314 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); 2315 } 2316 2317 /*-------------------------------------------------------------------------*/ 2318 2319 static void handle_exception(struct fsg_common *common) 2320 { 2321 int i; 2322 struct fsg_buffhd *bh; 2323 enum fsg_state old_state; 2324 struct fsg_lun *curlun; 2325 unsigned int exception_req_tag; 2326 2327 /* Cancel all the pending transfers */ 2328 if (common->fsg) { 2329 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2330 bh = &common->buffhds[i]; 2331 if (bh->inreq_busy) 2332 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq); 2333 if (bh->outreq_busy) 2334 usb_ep_dequeue(common->fsg->bulk_out, 2335 bh->outreq); 2336 } 2337 2338 /* Wait until everything is idle */ 2339 for (;;) { 2340 int num_active = 0; 2341 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2342 bh = &common->buffhds[i]; 2343 num_active += bh->inreq_busy + bh->outreq_busy; 2344 } 2345 if (num_active == 0) 2346 break; 2347 if (sleep_thread(common)) 2348 return; 2349 } 2350 2351 /* Clear out the controller's fifos */ 2352 if (common->fsg->bulk_in_enabled) 2353 usb_ep_fifo_flush(common->fsg->bulk_in); 2354 if (common->fsg->bulk_out_enabled) 2355 usb_ep_fifo_flush(common->fsg->bulk_out); 2356 } 2357 2358 /* Reset the I/O buffer states and pointers, the SCSI 2359 * state, and the exception. Then invoke the handler. */ 2360 2361 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2362 bh = &common->buffhds[i]; 2363 bh->state = BUF_STATE_EMPTY; 2364 } 2365 common->next_buffhd_to_fill = &common->buffhds[0]; 2366 common->next_buffhd_to_drain = &common->buffhds[0]; 2367 exception_req_tag = common->exception_req_tag; 2368 old_state = common->state; 2369 2370 if (old_state == FSG_STATE_ABORT_BULK_OUT) 2371 common->state = FSG_STATE_STATUS_PHASE; 2372 else { 2373 for (i = 0; i < common->nluns; ++i) { 2374 curlun = &common->luns[i]; 2375 curlun->sense_data = SS_NO_SENSE; 2376 curlun->info_valid = 0; 2377 } 2378 common->state = FSG_STATE_IDLE; 2379 } 2380 2381 /* Carry out any extra actions required for the exception */ 2382 switch (old_state) { 2383 case FSG_STATE_ABORT_BULK_OUT: 2384 send_status(common); 2385 2386 if (common->state == FSG_STATE_STATUS_PHASE) 2387 common->state = FSG_STATE_IDLE; 2388 break; 2389 2390 case FSG_STATE_RESET: 2391 /* In case we were forced against our will to halt a 2392 * bulk endpoint, clear the halt now. (The SuperH UDC 2393 * requires this.) */ 2394 if (!fsg_is_set(common)) 2395 break; 2396 if (test_and_clear_bit(IGNORE_BULK_OUT, 2397 &common->fsg->atomic_bitflags)) 2398 usb_ep_clear_halt(common->fsg->bulk_in); 2399 2400 if (common->ep0_req_tag == exception_req_tag) 2401 ep0_queue(common); /* Complete the status stage */ 2402 2403 break; 2404 2405 case FSG_STATE_CONFIG_CHANGE: 2406 do_set_interface(common, common->new_fsg); 2407 break; 2408 2409 case FSG_STATE_EXIT: 2410 case FSG_STATE_TERMINATED: 2411 do_set_interface(common, NULL); /* Free resources */ 2412 common->state = FSG_STATE_TERMINATED; /* Stop the thread */ 2413 break; 2414 2415 case FSG_STATE_INTERFACE_CHANGE: 2416 case FSG_STATE_DISCONNECT: 2417 case FSG_STATE_COMMAND_PHASE: 2418 case FSG_STATE_DATA_PHASE: 2419 case FSG_STATE_STATUS_PHASE: 2420 case FSG_STATE_IDLE: 2421 break; 2422 } 2423 } 2424 2425 /*-------------------------------------------------------------------------*/ 2426 2427 int fsg_main_thread(void *common_) 2428 { 2429 int ret; 2430 struct fsg_common *common = the_fsg_common; 2431 /* The main loop */ 2432 do { 2433 if (exception_in_progress(common)) { 2434 handle_exception(common); 2435 continue; 2436 } 2437 2438 if (!common->running) { 2439 ret = sleep_thread(common); 2440 if (ret) 2441 return ret; 2442 2443 continue; 2444 } 2445 2446 ret = get_next_command(common); 2447 if (ret) 2448 return ret; 2449 2450 if (!exception_in_progress(common)) 2451 common->state = FSG_STATE_DATA_PHASE; 2452 2453 if (do_scsi_command(common) || finish_reply(common)) 2454 continue; 2455 2456 if (!exception_in_progress(common)) 2457 common->state = FSG_STATE_STATUS_PHASE; 2458 2459 if (send_status(common)) 2460 continue; 2461 2462 if (!exception_in_progress(common)) 2463 common->state = FSG_STATE_IDLE; 2464 } while (0); 2465 2466 common->thread_task = NULL; 2467 2468 return 0; 2469 } 2470 2471 static void fsg_common_release(struct kref *ref); 2472 2473 static struct fsg_common *fsg_common_init(struct fsg_common *common, 2474 struct usb_composite_dev *cdev) 2475 { 2476 struct usb_gadget *gadget = cdev->gadget; 2477 struct fsg_buffhd *bh; 2478 struct fsg_lun *curlun; 2479 int nluns, i, rc; 2480 2481 /* Find out how many LUNs there should be */ 2482 nluns = ums_count; 2483 if (nluns < 1 || nluns > FSG_MAX_LUNS) { 2484 printf("invalid number of LUNs: %u\n", nluns); 2485 return ERR_PTR(-EINVAL); 2486 } 2487 2488 /* Allocate? */ 2489 if (!common) { 2490 common = calloc(sizeof(*common), 1); 2491 if (!common) 2492 return ERR_PTR(-ENOMEM); 2493 common->free_storage_on_release = 1; 2494 } else { 2495 memset(common, 0, sizeof(*common)); 2496 common->free_storage_on_release = 0; 2497 } 2498 2499 common->ops = NULL; 2500 common->private_data = NULL; 2501 2502 common->gadget = gadget; 2503 common->ep0 = gadget->ep0; 2504 common->ep0req = cdev->req; 2505 2506 /* Maybe allocate device-global string IDs, and patch descriptors */ 2507 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) { 2508 rc = usb_string_id(cdev); 2509 if (unlikely(rc < 0)) 2510 goto error_release; 2511 fsg_strings[FSG_STRING_INTERFACE].id = rc; 2512 fsg_intf_desc.iInterface = rc; 2513 } 2514 2515 /* Create the LUNs, open their backing files, and register the 2516 * LUN devices in sysfs. */ 2517 curlun = calloc(nluns, sizeof *curlun); 2518 if (!curlun) { 2519 rc = -ENOMEM; 2520 goto error_release; 2521 } 2522 common->nluns = nluns; 2523 2524 for (i = 0; i < nluns; i++) { 2525 common->luns[i].removable = 1; 2526 2527 rc = fsg_lun_open(&common->luns[i], ums[i].num_sectors, ""); 2528 if (rc) 2529 goto error_luns; 2530 } 2531 common->lun = 0; 2532 2533 /* Data buffers cyclic list */ 2534 bh = common->buffhds; 2535 2536 i = FSG_NUM_BUFFERS; 2537 goto buffhds_first_it; 2538 do { 2539 bh->next = bh + 1; 2540 ++bh; 2541 buffhds_first_it: 2542 bh->inreq_busy = 0; 2543 bh->outreq_busy = 0; 2544 bh->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, FSG_BUFLEN); 2545 if (unlikely(!bh->buf)) { 2546 rc = -ENOMEM; 2547 goto error_release; 2548 } 2549 } while (--i); 2550 bh->next = common->buffhds; 2551 2552 snprintf(common->inquiry_string, sizeof common->inquiry_string, 2553 "%-8s%-16s%04x", 2554 "Linux ", 2555 "File-Store Gadget", 2556 0xffff); 2557 2558 /* Some peripheral controllers are known not to be able to 2559 * halt bulk endpoints correctly. If one of them is present, 2560 * disable stalls. 2561 */ 2562 2563 /* Tell the thread to start working */ 2564 common->thread_task = 2565 kthread_create(fsg_main_thread, common, 2566 OR(cfg->thread_name, "file-storage")); 2567 if (IS_ERR(common->thread_task)) { 2568 rc = PTR_ERR(common->thread_task); 2569 goto error_release; 2570 } 2571 2572 #undef OR 2573 /* Information */ 2574 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n"); 2575 INFO(common, "Number of LUNs=%d\n", common->nluns); 2576 2577 return common; 2578 2579 error_luns: 2580 common->nluns = i + 1; 2581 error_release: 2582 common->state = FSG_STATE_TERMINATED; /* The thread is dead */ 2583 /* Call fsg_common_release() directly, ref might be not 2584 * initialised */ 2585 fsg_common_release(&common->ref); 2586 return ERR_PTR(rc); 2587 } 2588 2589 static void fsg_common_release(struct kref *ref) 2590 { 2591 struct fsg_common *common = container_of(ref, struct fsg_common, ref); 2592 2593 /* If the thread isn't already dead, tell it to exit now */ 2594 if (common->state != FSG_STATE_TERMINATED) { 2595 raise_exception(common, FSG_STATE_EXIT); 2596 wait_for_completion(&common->thread_notifier); 2597 } 2598 2599 if (likely(common->luns)) { 2600 struct fsg_lun *lun = common->luns; 2601 unsigned i = common->nluns; 2602 2603 /* In error recovery common->nluns may be zero. */ 2604 for (; i; --i, ++lun) 2605 fsg_lun_close(lun); 2606 2607 kfree(common->luns); 2608 } 2609 2610 { 2611 struct fsg_buffhd *bh = common->buffhds; 2612 unsigned i = FSG_NUM_BUFFERS; 2613 do { 2614 kfree(bh->buf); 2615 } while (++bh, --i); 2616 } 2617 2618 if (common->free_storage_on_release) 2619 kfree(common); 2620 } 2621 2622 2623 /*-------------------------------------------------------------------------*/ 2624 2625 /** 2626 * usb_copy_descriptors - copy a vector of USB descriptors 2627 * @src: null-terminated vector to copy 2628 * Context: initialization code, which may sleep 2629 * 2630 * This makes a copy of a vector of USB descriptors. Its primary use 2631 * is to support usb_function objects which can have multiple copies, 2632 * each needing different descriptors. Functions may have static 2633 * tables of descriptors, which are used as templates and customized 2634 * with identifiers (for interfaces, strings, endpoints, and more) 2635 * as needed by a given function instance. 2636 */ 2637 struct usb_descriptor_header ** 2638 usb_copy_descriptors(struct usb_descriptor_header **src) 2639 { 2640 struct usb_descriptor_header **tmp; 2641 unsigned bytes; 2642 unsigned n_desc; 2643 void *mem; 2644 struct usb_descriptor_header **ret; 2645 2646 /* count descriptors and their sizes; then add vector size */ 2647 for (bytes = 0, n_desc = 0, tmp = src; *tmp; tmp++, n_desc++) 2648 bytes += (*tmp)->bLength; 2649 bytes += (n_desc + 1) * sizeof(*tmp); 2650 2651 mem = memalign(CONFIG_SYS_CACHELINE_SIZE, bytes); 2652 if (!mem) 2653 return NULL; 2654 2655 /* fill in pointers starting at "tmp", 2656 * to descriptors copied starting at "mem"; 2657 * and return "ret" 2658 */ 2659 tmp = mem; 2660 ret = mem; 2661 mem += (n_desc + 1) * sizeof(*tmp); 2662 while (*src) { 2663 memcpy(mem, *src, (*src)->bLength); 2664 *tmp = mem; 2665 tmp++; 2666 mem += (*src)->bLength; 2667 src++; 2668 } 2669 *tmp = NULL; 2670 2671 return ret; 2672 } 2673 2674 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f) 2675 { 2676 struct fsg_dev *fsg = fsg_from_func(f); 2677 2678 DBG(fsg, "unbind\n"); 2679 if (fsg->common->fsg == fsg) { 2680 fsg->common->new_fsg = NULL; 2681 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); 2682 } 2683 2684 free(fsg->function.descriptors); 2685 free(fsg->function.hs_descriptors); 2686 kfree(fsg); 2687 } 2688 2689 static int fsg_bind(struct usb_configuration *c, struct usb_function *f) 2690 { 2691 struct fsg_dev *fsg = fsg_from_func(f); 2692 struct usb_gadget *gadget = c->cdev->gadget; 2693 int i; 2694 struct usb_ep *ep; 2695 fsg->gadget = gadget; 2696 2697 /* New interface */ 2698 i = usb_interface_id(c, f); 2699 if (i < 0) 2700 return i; 2701 fsg_intf_desc.bInterfaceNumber = i; 2702 fsg->interface_number = i; 2703 2704 /* Find all the endpoints we will use */ 2705 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc); 2706 if (!ep) 2707 goto autoconf_fail; 2708 ep->driver_data = fsg->common; /* claim the endpoint */ 2709 fsg->bulk_in = ep; 2710 2711 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc); 2712 if (!ep) 2713 goto autoconf_fail; 2714 ep->driver_data = fsg->common; /* claim the endpoint */ 2715 fsg->bulk_out = ep; 2716 2717 /* Copy descriptors */ 2718 if (IS_RKUSB_UMS_DNL(c->cdev->driver->name)) 2719 f->descriptors = usb_copy_descriptors(rkusb_fs_function); 2720 else 2721 f->descriptors = usb_copy_descriptors(fsg_fs_function); 2722 if (unlikely(!f->descriptors)) 2723 return -ENOMEM; 2724 2725 if (gadget_is_dualspeed(gadget)) { 2726 /* Assume endpoint addresses are the same for both speeds */ 2727 fsg_hs_bulk_in_desc.bEndpointAddress = 2728 fsg_fs_bulk_in_desc.bEndpointAddress; 2729 fsg_hs_bulk_out_desc.bEndpointAddress = 2730 fsg_fs_bulk_out_desc.bEndpointAddress; 2731 2732 if (IS_RKUSB_UMS_DNL(c->cdev->driver->name)) 2733 f->hs_descriptors = 2734 usb_copy_descriptors(rkusb_hs_function); 2735 else 2736 f->hs_descriptors = 2737 usb_copy_descriptors(fsg_hs_function); 2738 if (unlikely(!f->hs_descriptors)) { 2739 free(f->descriptors); 2740 return -ENOMEM; 2741 } 2742 } 2743 2744 if (gadget_is_superspeed(gadget)) { 2745 /* Assume endpoint addresses are the same as full speed */ 2746 fsg_ss_bulk_in_desc.bEndpointAddress = 2747 fsg_fs_bulk_in_desc.bEndpointAddress; 2748 fsg_ss_bulk_out_desc.bEndpointAddress = 2749 fsg_fs_bulk_out_desc.bEndpointAddress; 2750 2751 #ifdef CONFIG_CMD_ROCKUSB 2752 if (IS_RKUSB_UMS_DNL(c->cdev->driver->name)) 2753 f->ss_descriptors = 2754 usb_copy_descriptors(rkusb_ss_function); 2755 #endif 2756 2757 if (unlikely(!f->ss_descriptors)) { 2758 free(f->descriptors); 2759 return -ENOMEM; 2760 } 2761 } 2762 return 0; 2763 2764 autoconf_fail: 2765 ERROR(fsg, "unable to autoconfigure all endpoints\n"); 2766 return -ENOTSUPP; 2767 } 2768 2769 2770 /****************************** ADD FUNCTION ******************************/ 2771 2772 static struct usb_gadget_strings *fsg_strings_array[] = { 2773 &fsg_stringtab, 2774 NULL, 2775 }; 2776 2777 static int fsg_bind_config(struct usb_composite_dev *cdev, 2778 struct usb_configuration *c, 2779 struct fsg_common *common) 2780 { 2781 struct fsg_dev *fsg; 2782 int rc; 2783 2784 fsg = calloc(1, sizeof *fsg); 2785 if (!fsg) 2786 return -ENOMEM; 2787 fsg->function.name = FSG_DRIVER_DESC; 2788 fsg->function.strings = fsg_strings_array; 2789 fsg->function.bind = fsg_bind; 2790 fsg->function.unbind = fsg_unbind; 2791 fsg->function.setup = fsg_setup; 2792 fsg->function.set_alt = fsg_set_alt; 2793 fsg->function.disable = fsg_disable; 2794 2795 fsg->common = common; 2796 common->fsg = fsg; 2797 /* Our caller holds a reference to common structure so we 2798 * don't have to be worry about it being freed until we return 2799 * from this function. So instead of incrementing counter now 2800 * and decrement in error recovery we increment it only when 2801 * call to usb_add_function() was successful. */ 2802 2803 rc = usb_add_function(c, &fsg->function); 2804 2805 if (rc) 2806 kfree(fsg); 2807 2808 return rc; 2809 } 2810 2811 int fsg_add(struct usb_configuration *c) 2812 { 2813 struct fsg_common *fsg_common; 2814 2815 fsg_common = fsg_common_init(NULL, c->cdev); 2816 2817 fsg_common->vendor_name = 0; 2818 fsg_common->product_name = 0; 2819 fsg_common->release = 0xffff; 2820 2821 fsg_common->ops = NULL; 2822 fsg_common->private_data = NULL; 2823 2824 the_fsg_common = fsg_common; 2825 2826 return fsg_bind_config(c->cdev, c, fsg_common); 2827 } 2828 2829 int fsg_init(struct ums *ums_devs, int count) 2830 { 2831 ums = ums_devs; 2832 ums_count = count; 2833 2834 return 0; 2835 } 2836 2837 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_ums, fsg_add); 2838