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 usb_gadget_handle_interrupts(0); 678 } 679 common->thread_wakeup_needed = 0; 680 return rc; 681 } 682 683 /*-------------------------------------------------------------------------*/ 684 685 static int do_read(struct fsg_common *common) 686 { 687 struct fsg_lun *curlun = &common->luns[common->lun]; 688 u32 lba; 689 struct fsg_buffhd *bh; 690 int rc; 691 u32 amount_left; 692 loff_t file_offset; 693 unsigned int amount; 694 unsigned int partial_page; 695 ssize_t nread; 696 697 /* Get the starting Logical Block Address and check that it's 698 * not too big */ 699 if (common->cmnd[0] == SC_READ_6) 700 lba = get_unaligned_be24(&common->cmnd[1]); 701 else { 702 lba = get_unaligned_be32(&common->cmnd[2]); 703 704 /* We allow DPO (Disable Page Out = don't save data in the 705 * cache) and FUA (Force Unit Access = don't read from the 706 * cache), but we don't implement them. */ 707 if ((common->cmnd[1] & ~0x18) != 0) { 708 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 709 return -EINVAL; 710 } 711 } 712 if (lba >= curlun->num_sectors) { 713 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 714 return -EINVAL; 715 } 716 file_offset = ((loff_t) lba) << 9; 717 718 /* Carry out the file reads */ 719 amount_left = common->data_size_from_cmnd; 720 if (unlikely(amount_left == 0)) 721 return -EIO; /* No default reply */ 722 723 for (;;) { 724 725 /* Figure out how much we need to read: 726 * Try to read the remaining amount. 727 * But don't read more than the buffer size. 728 * And don't try to read past the end of the file. 729 * Finally, if we're not at a page boundary, don't read past 730 * the next page. 731 * If this means reading 0 then we were asked to read past 732 * the end of file. */ 733 amount = min(amount_left, FSG_BUFLEN); 734 partial_page = file_offset & (PAGE_CACHE_SIZE - 1); 735 if (partial_page > 0) 736 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE - 737 partial_page); 738 739 /* Wait for the next buffer to become available */ 740 bh = common->next_buffhd_to_fill; 741 while (bh->state != BUF_STATE_EMPTY) { 742 rc = sleep_thread(common); 743 if (rc) 744 return rc; 745 } 746 747 /* If we were asked to read past the end of file, 748 * end with an empty buffer. */ 749 if (amount == 0) { 750 curlun->sense_data = 751 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 752 curlun->info_valid = 1; 753 bh->inreq->length = 0; 754 bh->state = BUF_STATE_FULL; 755 break; 756 } 757 758 /* Perform the read */ 759 rc = ums[common->lun].read_sector(&ums[common->lun], 760 file_offset / SECTOR_SIZE, 761 amount / SECTOR_SIZE, 762 (char __user *)bh->buf); 763 if (!rc) 764 return -EIO; 765 766 nread = rc * SECTOR_SIZE; 767 768 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, 769 (unsigned long long) file_offset, 770 (int) nread); 771 772 if (nread < 0) { 773 LDBG(curlun, "error in file read: %d\n", 774 (int) nread); 775 nread = 0; 776 } else if (nread < amount) { 777 LDBG(curlun, "partial file read: %d/%u\n", 778 (int) nread, amount); 779 nread -= (nread & 511); /* Round down to a block */ 780 } 781 file_offset += nread; 782 amount_left -= nread; 783 common->residue -= nread; 784 bh->inreq->length = nread; 785 bh->state = BUF_STATE_FULL; 786 787 /* If an error occurred, report it and its position */ 788 if (nread < amount) { 789 curlun->sense_data = SS_UNRECOVERED_READ_ERROR; 790 curlun->info_valid = 1; 791 break; 792 } 793 794 if (amount_left == 0) 795 break; /* No more left to read */ 796 797 /* Send this buffer and go read some more */ 798 bh->inreq->zero = 0; 799 START_TRANSFER_OR(common, bulk_in, bh->inreq, 800 &bh->inreq_busy, &bh->state) 801 /* Don't know what to do if 802 * common->fsg is NULL */ 803 return -EIO; 804 common->next_buffhd_to_fill = bh->next; 805 } 806 807 return -EIO; /* No default reply */ 808 } 809 810 /*-------------------------------------------------------------------------*/ 811 812 static int do_write(struct fsg_common *common) 813 { 814 struct fsg_lun *curlun = &common->luns[common->lun]; 815 u32 lba; 816 struct fsg_buffhd *bh; 817 int get_some_more; 818 u32 amount_left_to_req, amount_left_to_write; 819 loff_t usb_offset, file_offset; 820 unsigned int amount; 821 unsigned int partial_page; 822 ssize_t nwritten; 823 int rc; 824 const char *cdev_name __maybe_unused; 825 826 if (curlun->ro) { 827 curlun->sense_data = SS_WRITE_PROTECTED; 828 return -EINVAL; 829 } 830 831 /* Get the starting Logical Block Address and check that it's 832 * not too big */ 833 if (common->cmnd[0] == SC_WRITE_6) 834 lba = get_unaligned_be24(&common->cmnd[1]); 835 else { 836 lba = get_unaligned_be32(&common->cmnd[2]); 837 838 /* We allow DPO (Disable Page Out = don't save data in the 839 * cache) and FUA (Force Unit Access = write directly to the 840 * medium). We don't implement DPO; we implement FUA by 841 * performing synchronous output. */ 842 if (common->cmnd[1] & ~0x18) { 843 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 844 return -EINVAL; 845 } 846 } 847 if (lba >= curlun->num_sectors) { 848 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 849 return -EINVAL; 850 } 851 852 /* Carry out the file writes */ 853 get_some_more = 1; 854 file_offset = usb_offset = ((loff_t) lba) << 9; 855 amount_left_to_req = common->data_size_from_cmnd; 856 amount_left_to_write = common->data_size_from_cmnd; 857 858 while (amount_left_to_write > 0) { 859 860 /* Queue a request for more data from the host */ 861 bh = common->next_buffhd_to_fill; 862 if (bh->state == BUF_STATE_EMPTY && get_some_more) { 863 864 /* Figure out how much we want to get: 865 * Try to get the remaining amount. 866 * But don't get more than the buffer size. 867 * And don't try to go past the end of the file. 868 * If we're not at a page boundary, 869 * don't go past the next page. 870 * If this means getting 0, then we were asked 871 * to write past the end of file. 872 * Finally, round down to a block boundary. */ 873 amount = min(amount_left_to_req, FSG_BUFLEN); 874 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1); 875 if (partial_page > 0) 876 amount = min(amount, 877 (unsigned int) PAGE_CACHE_SIZE - partial_page); 878 879 if (amount == 0) { 880 get_some_more = 0; 881 curlun->sense_data = 882 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 883 curlun->info_valid = 1; 884 continue; 885 } 886 amount -= (amount & 511); 887 if (amount == 0) { 888 889 /* Why were we were asked to transfer a 890 * partial block? */ 891 get_some_more = 0; 892 continue; 893 } 894 895 /* Get the next buffer */ 896 usb_offset += amount; 897 common->usb_amount_left -= amount; 898 amount_left_to_req -= amount; 899 if (amount_left_to_req == 0) 900 get_some_more = 0; 901 902 /* amount is always divisible by 512, hence by 903 * the bulk-out maxpacket size */ 904 bh->outreq->length = amount; 905 bh->bulk_out_intended_length = amount; 906 bh->outreq->short_not_ok = 1; 907 START_TRANSFER_OR(common, bulk_out, bh->outreq, 908 &bh->outreq_busy, &bh->state) 909 /* Don't know what to do if 910 * common->fsg is NULL */ 911 return -EIO; 912 common->next_buffhd_to_fill = bh->next; 913 continue; 914 } 915 916 /* Write the received data to the backing file */ 917 bh = common->next_buffhd_to_drain; 918 if (bh->state == BUF_STATE_EMPTY && !get_some_more) 919 break; /* We stopped early */ 920 if (bh->state == BUF_STATE_FULL) { 921 common->next_buffhd_to_drain = bh->next; 922 bh->state = BUF_STATE_EMPTY; 923 924 /* Did something go wrong with the transfer? */ 925 if (bh->outreq->status != 0) { 926 curlun->sense_data = SS_COMMUNICATION_FAILURE; 927 curlun->info_valid = 1; 928 break; 929 } 930 931 amount = bh->outreq->actual; 932 933 /* Perform the write */ 934 rc = ums[common->lun].write_sector(&ums[common->lun], 935 file_offset / SECTOR_SIZE, 936 amount / SECTOR_SIZE, 937 (char __user *)bh->buf); 938 if (!rc) 939 return -EIO; 940 nwritten = rc * SECTOR_SIZE; 941 942 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount, 943 (unsigned long long) file_offset, 944 (int) nwritten); 945 946 if (nwritten < 0) { 947 LDBG(curlun, "error in file write: %d\n", 948 (int) nwritten); 949 nwritten = 0; 950 } else if (nwritten < amount) { 951 LDBG(curlun, "partial file write: %d/%u\n", 952 (int) nwritten, amount); 953 nwritten -= (nwritten & 511); 954 /* Round down to a block */ 955 } 956 file_offset += nwritten; 957 amount_left_to_write -= nwritten; 958 common->residue -= nwritten; 959 960 /* If an error occurred, report it and its position */ 961 if (nwritten < amount) { 962 printf("nwritten:%zd amount:%u\n", nwritten, 963 amount); 964 curlun->sense_data = SS_WRITE_ERROR; 965 curlun->info_valid = 1; 966 break; 967 } 968 969 /* Did the host decide to stop early? */ 970 if (bh->outreq->actual != bh->outreq->length) { 971 common->short_packet_received = 1; 972 break; 973 } 974 continue; 975 } 976 977 /* Wait for something to happen */ 978 rc = sleep_thread(common); 979 if (rc) 980 return rc; 981 } 982 983 cdev_name = common->fsg->function.config->cdev->driver->name; 984 if (IS_RKUSB_UMS_DNL(cdev_name)) 985 rkusb_do_check_parity(common); 986 987 return -EIO; /* No default reply */ 988 } 989 990 /*-------------------------------------------------------------------------*/ 991 992 static int do_synchronize_cache(struct fsg_common *common) 993 { 994 return 0; 995 } 996 997 /*-------------------------------------------------------------------------*/ 998 999 static int do_verify(struct fsg_common *common) 1000 { 1001 struct fsg_lun *curlun = &common->luns[common->lun]; 1002 u32 lba; 1003 u32 verification_length; 1004 struct fsg_buffhd *bh = common->next_buffhd_to_fill; 1005 loff_t file_offset; 1006 u32 amount_left; 1007 unsigned int amount; 1008 ssize_t nread; 1009 int rc; 1010 1011 /* Get the starting Logical Block Address and check that it's 1012 * not too big */ 1013 lba = get_unaligned_be32(&common->cmnd[2]); 1014 if (lba >= curlun->num_sectors) { 1015 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1016 return -EINVAL; 1017 } 1018 1019 /* We allow DPO (Disable Page Out = don't save data in the 1020 * cache) but we don't implement it. */ 1021 if (common->cmnd[1] & ~0x10) { 1022 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1023 return -EINVAL; 1024 } 1025 1026 verification_length = get_unaligned_be16(&common->cmnd[7]); 1027 if (unlikely(verification_length == 0)) 1028 return -EIO; /* No default reply */ 1029 1030 /* Prepare to carry out the file verify */ 1031 amount_left = verification_length << 9; 1032 file_offset = ((loff_t) lba) << 9; 1033 1034 /* Write out all the dirty buffers before invalidating them */ 1035 1036 /* Just try to read the requested blocks */ 1037 while (amount_left > 0) { 1038 1039 /* Figure out how much we need to read: 1040 * Try to read the remaining amount, but not more than 1041 * the buffer size. 1042 * And don't try to read past the end of the file. 1043 * If this means reading 0 then we were asked to read 1044 * past the end of file. */ 1045 amount = min(amount_left, FSG_BUFLEN); 1046 if (amount == 0) { 1047 curlun->sense_data = 1048 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1049 curlun->info_valid = 1; 1050 break; 1051 } 1052 1053 /* Perform the read */ 1054 rc = ums[common->lun].read_sector(&ums[common->lun], 1055 file_offset / SECTOR_SIZE, 1056 amount / SECTOR_SIZE, 1057 (char __user *)bh->buf); 1058 if (!rc) 1059 return -EIO; 1060 nread = rc * SECTOR_SIZE; 1061 1062 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, 1063 (unsigned long long) file_offset, 1064 (int) nread); 1065 if (nread < 0) { 1066 LDBG(curlun, "error in file verify: %d\n", 1067 (int) nread); 1068 nread = 0; 1069 } else if (nread < amount) { 1070 LDBG(curlun, "partial file verify: %d/%u\n", 1071 (int) nread, amount); 1072 nread -= (nread & 511); /* Round down to a sector */ 1073 } 1074 if (nread == 0) { 1075 curlun->sense_data = SS_UNRECOVERED_READ_ERROR; 1076 curlun->info_valid = 1; 1077 break; 1078 } 1079 file_offset += nread; 1080 amount_left -= nread; 1081 } 1082 return 0; 1083 } 1084 1085 /*-------------------------------------------------------------------------*/ 1086 1087 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh) 1088 { 1089 struct fsg_lun *curlun = &common->luns[common->lun]; 1090 static const char vendor_id[] = "Linux "; 1091 u8 *buf = (u8 *) bh->buf; 1092 1093 if (!curlun) { /* Unsupported LUNs are okay */ 1094 common->bad_lun_okay = 1; 1095 memset(buf, 0, 36); 1096 buf[0] = 0x7f; /* Unsupported, no device-type */ 1097 buf[4] = 31; /* Additional length */ 1098 return 36; 1099 } 1100 1101 memset(buf, 0, 8); 1102 buf[0] = TYPE_DISK; 1103 buf[1] = curlun->removable ? 0x80 : 0; 1104 buf[2] = 2; /* ANSI SCSI level 2 */ 1105 buf[3] = 2; /* SCSI-2 INQUIRY data format */ 1106 buf[4] = 31; /* Additional length */ 1107 /* No special options */ 1108 sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char*) vendor_id , 1109 ums[common->lun].name, (u16) 0xffff); 1110 1111 return 36; 1112 } 1113 1114 1115 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh) 1116 { 1117 struct fsg_lun *curlun = &common->luns[common->lun]; 1118 u8 *buf = (u8 *) bh->buf; 1119 u32 sd, sdinfo; 1120 int valid; 1121 1122 /* 1123 * From the SCSI-2 spec., section 7.9 (Unit attention condition): 1124 * 1125 * If a REQUEST SENSE command is received from an initiator 1126 * with a pending unit attention condition (before the target 1127 * generates the contingent allegiance condition), then the 1128 * target shall either: 1129 * a) report any pending sense data and preserve the unit 1130 * attention condition on the logical unit, or, 1131 * b) report the unit attention condition, may discard any 1132 * pending sense data, and clear the unit attention 1133 * condition on the logical unit for that initiator. 1134 * 1135 * FSG normally uses option a); enable this code to use option b). 1136 */ 1137 #if 0 1138 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) { 1139 curlun->sense_data = curlun->unit_attention_data; 1140 curlun->unit_attention_data = SS_NO_SENSE; 1141 } 1142 #endif 1143 1144 if (!curlun) { /* Unsupported LUNs are okay */ 1145 common->bad_lun_okay = 1; 1146 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; 1147 sdinfo = 0; 1148 valid = 0; 1149 } else { 1150 sd = curlun->sense_data; 1151 valid = curlun->info_valid << 7; 1152 curlun->sense_data = SS_NO_SENSE; 1153 curlun->info_valid = 0; 1154 } 1155 1156 memset(buf, 0, 18); 1157 buf[0] = valid | 0x70; /* Valid, current error */ 1158 buf[2] = SK(sd); 1159 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */ 1160 buf[7] = 18 - 8; /* Additional sense length */ 1161 buf[12] = ASC(sd); 1162 buf[13] = ASCQ(sd); 1163 return 18; 1164 } 1165 1166 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh) 1167 { 1168 struct fsg_lun *curlun = &common->luns[common->lun]; 1169 u32 lba = get_unaligned_be32(&common->cmnd[2]); 1170 int pmi = common->cmnd[8]; 1171 u8 *buf = (u8 *) bh->buf; 1172 1173 /* Check the PMI and LBA fields */ 1174 if (pmi > 1 || (pmi == 0 && lba != 0)) { 1175 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1176 return -EINVAL; 1177 } 1178 1179 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]); 1180 /* Max logical block */ 1181 put_unaligned_be32(512, &buf[4]); /* Block length */ 1182 return 8; 1183 } 1184 1185 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh) 1186 { 1187 struct fsg_lun *curlun = &common->luns[common->lun]; 1188 int msf = common->cmnd[1] & 0x02; 1189 u32 lba = get_unaligned_be32(&common->cmnd[2]); 1190 u8 *buf = (u8 *) bh->buf; 1191 1192 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */ 1193 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1194 return -EINVAL; 1195 } 1196 if (lba >= curlun->num_sectors) { 1197 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; 1198 return -EINVAL; 1199 } 1200 1201 memset(buf, 0, 8); 1202 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */ 1203 store_cdrom_address(&buf[4], msf, lba); 1204 return 8; 1205 } 1206 1207 1208 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh) 1209 { 1210 struct fsg_lun *curlun = &common->luns[common->lun]; 1211 int msf = common->cmnd[1] & 0x02; 1212 int start_track = common->cmnd[6]; 1213 u8 *buf = (u8 *) bh->buf; 1214 1215 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */ 1216 start_track > 1) { 1217 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1218 return -EINVAL; 1219 } 1220 1221 memset(buf, 0, 20); 1222 buf[1] = (20-2); /* TOC data length */ 1223 buf[2] = 1; /* First track number */ 1224 buf[3] = 1; /* Last track number */ 1225 buf[5] = 0x16; /* Data track, copying allowed */ 1226 buf[6] = 0x01; /* Only track is number 1 */ 1227 store_cdrom_address(&buf[8], msf, 0); 1228 1229 buf[13] = 0x16; /* Lead-out track is data */ 1230 buf[14] = 0xAA; /* Lead-out track number */ 1231 store_cdrom_address(&buf[16], msf, curlun->num_sectors); 1232 1233 return 20; 1234 } 1235 1236 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh) 1237 { 1238 struct fsg_lun *curlun = &common->luns[common->lun]; 1239 int mscmnd = common->cmnd[0]; 1240 u8 *buf = (u8 *) bh->buf; 1241 u8 *buf0 = buf; 1242 int pc, page_code; 1243 int changeable_values, all_pages; 1244 int valid_page = 0; 1245 int len, limit; 1246 1247 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */ 1248 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1249 return -EINVAL; 1250 } 1251 pc = common->cmnd[2] >> 6; 1252 page_code = common->cmnd[2] & 0x3f; 1253 if (pc == 3) { 1254 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED; 1255 return -EINVAL; 1256 } 1257 changeable_values = (pc == 1); 1258 all_pages = (page_code == 0x3f); 1259 1260 /* Write the mode parameter header. Fixed values are: default 1261 * medium type, no cache control (DPOFUA), and no block descriptors. 1262 * The only variable value is the WriteProtect bit. We will fill in 1263 * the mode data length later. */ 1264 memset(buf, 0, 8); 1265 if (mscmnd == SC_MODE_SENSE_6) { 1266 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */ 1267 buf += 4; 1268 limit = 255; 1269 } else { /* SC_MODE_SENSE_10 */ 1270 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */ 1271 buf += 8; 1272 limit = 65535; /* Should really be FSG_BUFLEN */ 1273 } 1274 1275 /* No block descriptors */ 1276 1277 /* The mode pages, in numerical order. The only page we support 1278 * is the Caching page. */ 1279 if (page_code == 0x08 || all_pages) { 1280 valid_page = 1; 1281 buf[0] = 0x08; /* Page code */ 1282 buf[1] = 10; /* Page length */ 1283 memset(buf+2, 0, 10); /* None of the fields are changeable */ 1284 1285 if (!changeable_values) { 1286 buf[2] = 0x04; /* Write cache enable, */ 1287 /* Read cache not disabled */ 1288 /* No cache retention priorities */ 1289 put_unaligned_be16(0xffff, &buf[4]); 1290 /* Don't disable prefetch */ 1291 /* Minimum prefetch = 0 */ 1292 put_unaligned_be16(0xffff, &buf[8]); 1293 /* Maximum prefetch */ 1294 put_unaligned_be16(0xffff, &buf[10]); 1295 /* Maximum prefetch ceiling */ 1296 } 1297 buf += 12; 1298 } 1299 1300 /* Check that a valid page was requested and the mode data length 1301 * isn't too long. */ 1302 len = buf - buf0; 1303 if (!valid_page || len > limit) { 1304 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1305 return -EINVAL; 1306 } 1307 1308 /* Store the mode data length */ 1309 if (mscmnd == SC_MODE_SENSE_6) 1310 buf0[0] = len - 1; 1311 else 1312 put_unaligned_be16(len - 2, buf0); 1313 return len; 1314 } 1315 1316 1317 static int do_start_stop(struct fsg_common *common) 1318 { 1319 struct fsg_lun *curlun = &common->luns[common->lun]; 1320 1321 if (!curlun) { 1322 return -EINVAL; 1323 } else if (!curlun->removable) { 1324 curlun->sense_data = SS_INVALID_COMMAND; 1325 return -EINVAL; 1326 } 1327 1328 return 0; 1329 } 1330 1331 static int do_prevent_allow(struct fsg_common *common) 1332 { 1333 struct fsg_lun *curlun = &common->luns[common->lun]; 1334 int prevent; 1335 1336 if (!curlun->removable) { 1337 curlun->sense_data = SS_INVALID_COMMAND; 1338 return -EINVAL; 1339 } 1340 1341 prevent = common->cmnd[4] & 0x01; 1342 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */ 1343 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1344 return -EINVAL; 1345 } 1346 1347 if (curlun->prevent_medium_removal && !prevent) 1348 fsg_lun_fsync_sub(curlun); 1349 curlun->prevent_medium_removal = prevent; 1350 return 0; 1351 } 1352 1353 1354 static int do_read_format_capacities(struct fsg_common *common, 1355 struct fsg_buffhd *bh) 1356 { 1357 struct fsg_lun *curlun = &common->luns[common->lun]; 1358 u8 *buf = (u8 *) bh->buf; 1359 1360 buf[0] = buf[1] = buf[2] = 0; 1361 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */ 1362 buf += 4; 1363 1364 put_unaligned_be32(curlun->num_sectors, &buf[0]); 1365 /* Number of blocks */ 1366 put_unaligned_be32(512, &buf[4]); /* Block length */ 1367 buf[4] = 0x02; /* Current capacity */ 1368 return 12; 1369 } 1370 1371 1372 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh) 1373 { 1374 struct fsg_lun *curlun = &common->luns[common->lun]; 1375 1376 /* We don't support MODE SELECT */ 1377 if (curlun) 1378 curlun->sense_data = SS_INVALID_COMMAND; 1379 return -EINVAL; 1380 } 1381 1382 1383 /*-------------------------------------------------------------------------*/ 1384 1385 static int halt_bulk_in_endpoint(struct fsg_dev *fsg) 1386 { 1387 int rc; 1388 1389 rc = fsg_set_halt(fsg, fsg->bulk_in); 1390 if (rc == -EAGAIN) 1391 VDBG(fsg, "delayed bulk-in endpoint halt\n"); 1392 while (rc != 0) { 1393 if (rc != -EAGAIN) { 1394 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc); 1395 rc = 0; 1396 break; 1397 } 1398 1399 rc = usb_ep_set_halt(fsg->bulk_in); 1400 } 1401 return rc; 1402 } 1403 1404 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg) 1405 { 1406 int rc; 1407 1408 DBG(fsg, "bulk-in set wedge\n"); 1409 rc = 0; /* usb_ep_set_wedge(fsg->bulk_in); */ 1410 if (rc == -EAGAIN) 1411 VDBG(fsg, "delayed bulk-in endpoint wedge\n"); 1412 while (rc != 0) { 1413 if (rc != -EAGAIN) { 1414 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc); 1415 rc = 0; 1416 break; 1417 } 1418 } 1419 return rc; 1420 } 1421 1422 static int pad_with_zeros(struct fsg_dev *fsg) 1423 { 1424 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill; 1425 u32 nkeep = bh->inreq->length; 1426 u32 nsend; 1427 int rc; 1428 1429 bh->state = BUF_STATE_EMPTY; /* For the first iteration */ 1430 fsg->common->usb_amount_left = nkeep + fsg->common->residue; 1431 while (fsg->common->usb_amount_left > 0) { 1432 1433 /* Wait for the next buffer to be free */ 1434 while (bh->state != BUF_STATE_EMPTY) { 1435 rc = sleep_thread(fsg->common); 1436 if (rc) 1437 return rc; 1438 } 1439 1440 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN); 1441 memset(bh->buf + nkeep, 0, nsend - nkeep); 1442 bh->inreq->length = nsend; 1443 bh->inreq->zero = 0; 1444 start_transfer(fsg, fsg->bulk_in, bh->inreq, 1445 &bh->inreq_busy, &bh->state); 1446 bh = fsg->common->next_buffhd_to_fill = bh->next; 1447 fsg->common->usb_amount_left -= nsend; 1448 nkeep = 0; 1449 } 1450 return 0; 1451 } 1452 1453 static int throw_away_data(struct fsg_common *common) 1454 { 1455 struct fsg_buffhd *bh; 1456 u32 amount; 1457 int rc; 1458 1459 for (bh = common->next_buffhd_to_drain; 1460 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0; 1461 bh = common->next_buffhd_to_drain) { 1462 1463 /* Throw away the data in a filled buffer */ 1464 if (bh->state == BUF_STATE_FULL) { 1465 bh->state = BUF_STATE_EMPTY; 1466 common->next_buffhd_to_drain = bh->next; 1467 1468 /* A short packet or an error ends everything */ 1469 if (bh->outreq->actual != bh->outreq->length || 1470 bh->outreq->status != 0) { 1471 raise_exception(common, 1472 FSG_STATE_ABORT_BULK_OUT); 1473 return -EINTR; 1474 } 1475 continue; 1476 } 1477 1478 /* Try to submit another request if we need one */ 1479 bh = common->next_buffhd_to_fill; 1480 if (bh->state == BUF_STATE_EMPTY 1481 && common->usb_amount_left > 0) { 1482 amount = min(common->usb_amount_left, FSG_BUFLEN); 1483 1484 /* amount is always divisible by 512, hence by 1485 * the bulk-out maxpacket size */ 1486 bh->outreq->length = amount; 1487 bh->bulk_out_intended_length = amount; 1488 bh->outreq->short_not_ok = 1; 1489 START_TRANSFER_OR(common, bulk_out, bh->outreq, 1490 &bh->outreq_busy, &bh->state) 1491 /* Don't know what to do if 1492 * common->fsg is NULL */ 1493 return -EIO; 1494 common->next_buffhd_to_fill = bh->next; 1495 common->usb_amount_left -= amount; 1496 continue; 1497 } 1498 1499 /* Otherwise wait for something to happen */ 1500 rc = sleep_thread(common); 1501 if (rc) 1502 return rc; 1503 } 1504 return 0; 1505 } 1506 1507 1508 static int finish_reply(struct fsg_common *common) 1509 { 1510 struct fsg_buffhd *bh = common->next_buffhd_to_fill; 1511 int rc = 0; 1512 1513 switch (common->data_dir) { 1514 case DATA_DIR_NONE: 1515 break; /* Nothing to send */ 1516 1517 /* If we don't know whether the host wants to read or write, 1518 * this must be CB or CBI with an unknown command. We mustn't 1519 * try to send or receive any data. So stall both bulk pipes 1520 * if we can and wait for a reset. */ 1521 case DATA_DIR_UNKNOWN: 1522 if (!common->can_stall) { 1523 /* Nothing */ 1524 } else if (fsg_is_set(common)) { 1525 fsg_set_halt(common->fsg, common->fsg->bulk_out); 1526 rc = halt_bulk_in_endpoint(common->fsg); 1527 } else { 1528 /* Don't know what to do if common->fsg is NULL */ 1529 rc = -EIO; 1530 } 1531 break; 1532 1533 /* All but the last buffer of data must have already been sent */ 1534 case DATA_DIR_TO_HOST: 1535 if (common->data_size == 0) { 1536 /* Nothing to send */ 1537 1538 /* If there's no residue, simply send the last buffer */ 1539 } else if (common->residue == 0) { 1540 bh->inreq->zero = 0; 1541 START_TRANSFER_OR(common, bulk_in, bh->inreq, 1542 &bh->inreq_busy, &bh->state) 1543 return -EIO; 1544 common->next_buffhd_to_fill = bh->next; 1545 1546 /* For Bulk-only, if we're allowed to stall then send the 1547 * short packet and halt the bulk-in endpoint. If we can't 1548 * stall, pad out the remaining data with 0's. */ 1549 } else if (common->can_stall) { 1550 bh->inreq->zero = 1; 1551 START_TRANSFER_OR(common, bulk_in, bh->inreq, 1552 &bh->inreq_busy, &bh->state) 1553 /* Don't know what to do if 1554 * common->fsg is NULL */ 1555 rc = -EIO; 1556 common->next_buffhd_to_fill = bh->next; 1557 if (common->fsg) 1558 rc = halt_bulk_in_endpoint(common->fsg); 1559 } else if (fsg_is_set(common)) { 1560 rc = pad_with_zeros(common->fsg); 1561 } else { 1562 /* Don't know what to do if common->fsg is NULL */ 1563 rc = -EIO; 1564 } 1565 break; 1566 1567 /* We have processed all we want from the data the host has sent. 1568 * There may still be outstanding bulk-out requests. */ 1569 case DATA_DIR_FROM_HOST: 1570 if (common->residue == 0) { 1571 /* Nothing to receive */ 1572 1573 /* Did the host stop sending unexpectedly early? */ 1574 } else if (common->short_packet_received) { 1575 raise_exception(common, FSG_STATE_ABORT_BULK_OUT); 1576 rc = -EINTR; 1577 1578 /* We haven't processed all the incoming data. Even though 1579 * we may be allowed to stall, doing so would cause a race. 1580 * The controller may already have ACK'ed all the remaining 1581 * bulk-out packets, in which case the host wouldn't see a 1582 * STALL. Not realizing the endpoint was halted, it wouldn't 1583 * clear the halt -- leading to problems later on. */ 1584 #if 0 1585 } else if (common->can_stall) { 1586 if (fsg_is_set(common)) 1587 fsg_set_halt(common->fsg, 1588 common->fsg->bulk_out); 1589 raise_exception(common, FSG_STATE_ABORT_BULK_OUT); 1590 rc = -EINTR; 1591 #endif 1592 1593 /* We can't stall. Read in the excess data and throw it 1594 * all away. */ 1595 } else { 1596 rc = throw_away_data(common); 1597 } 1598 break; 1599 } 1600 return rc; 1601 } 1602 1603 1604 static int send_status(struct fsg_common *common) 1605 { 1606 struct fsg_lun *curlun = &common->luns[common->lun]; 1607 struct fsg_buffhd *bh; 1608 struct bulk_cs_wrap *csw; 1609 int rc; 1610 u8 status = USB_STATUS_PASS; 1611 u32 sd, sdinfo = 0; 1612 1613 /* Wait for the next buffer to become available */ 1614 bh = common->next_buffhd_to_fill; 1615 while (bh->state != BUF_STATE_EMPTY) { 1616 rc = sleep_thread(common); 1617 if (rc) 1618 return rc; 1619 } 1620 1621 if (curlun) 1622 sd = curlun->sense_data; 1623 else if (common->bad_lun_okay) 1624 sd = SS_NO_SENSE; 1625 else 1626 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; 1627 1628 if (common->phase_error) { 1629 DBG(common, "sending phase-error status\n"); 1630 status = USB_STATUS_PHASE_ERROR; 1631 sd = SS_INVALID_COMMAND; 1632 } else if (sd != SS_NO_SENSE) { 1633 DBG(common, "sending command-failure status\n"); 1634 status = USB_STATUS_FAIL; 1635 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;" 1636 " info x%x\n", 1637 SK(sd), ASC(sd), ASCQ(sd), sdinfo); 1638 } 1639 1640 /* Store and send the Bulk-only CSW */ 1641 csw = (void *)bh->buf; 1642 1643 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG); 1644 csw->Tag = common->tag; 1645 csw->Residue = cpu_to_le32(common->residue); 1646 csw->Status = status; 1647 1648 bh->inreq->length = USB_BULK_CS_WRAP_LEN; 1649 bh->inreq->zero = 0; 1650 START_TRANSFER_OR(common, bulk_in, bh->inreq, 1651 &bh->inreq_busy, &bh->state) 1652 /* Don't know what to do if common->fsg is NULL */ 1653 return -EIO; 1654 1655 common->next_buffhd_to_fill = bh->next; 1656 return 0; 1657 } 1658 1659 1660 /*-------------------------------------------------------------------------*/ 1661 #ifdef CONFIG_CMD_ROCKUSB 1662 #include "f_rockusb.c" 1663 #endif 1664 1665 /* Check whether the command is properly formed and whether its data size 1666 * and direction agree with the values we already have. */ 1667 static int check_command(struct fsg_common *common, int cmnd_size, 1668 enum data_direction data_dir, unsigned int mask, 1669 int needs_medium, const char *name) 1670 { 1671 int i; 1672 int lun = common->cmnd[1] >> 5; 1673 static const char dirletter[4] = {'u', 'o', 'i', 'n'}; 1674 char hdlen[20]; 1675 struct fsg_lun *curlun; 1676 1677 hdlen[0] = 0; 1678 if (common->data_dir != DATA_DIR_UNKNOWN) 1679 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir], 1680 common->data_size); 1681 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n", 1682 name, cmnd_size, dirletter[(int) data_dir], 1683 common->data_size_from_cmnd, common->cmnd_size, hdlen); 1684 1685 /* We can't reply at all until we know the correct data direction 1686 * and size. */ 1687 if (common->data_size_from_cmnd == 0) 1688 data_dir = DATA_DIR_NONE; 1689 if (common->data_size < common->data_size_from_cmnd) { 1690 /* Host data size < Device data size is a phase error. 1691 * Carry out the command, but only transfer as much as 1692 * we are allowed. */ 1693 common->data_size_from_cmnd = common->data_size; 1694 common->phase_error = 1; 1695 } 1696 common->residue = common->data_size; 1697 common->usb_amount_left = common->data_size; 1698 1699 /* Conflicting data directions is a phase error */ 1700 if (common->data_dir != data_dir 1701 && common->data_size_from_cmnd > 0) { 1702 common->phase_error = 1; 1703 return -EINVAL; 1704 } 1705 1706 /* Verify the length of the command itself */ 1707 if (cmnd_size != common->cmnd_size) { 1708 1709 /* Special case workaround: There are plenty of buggy SCSI 1710 * implementations. Many have issues with cbw->Length 1711 * field passing a wrong command size. For those cases we 1712 * always try to work around the problem by using the length 1713 * sent by the host side provided it is at least as large 1714 * as the correct command length. 1715 * Examples of such cases would be MS-Windows, which issues 1716 * REQUEST SENSE with cbw->Length == 12 where it should 1717 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and 1718 * REQUEST SENSE with cbw->Length == 10 where it should 1719 * be 6 as well. 1720 */ 1721 if (cmnd_size <= common->cmnd_size) { 1722 DBG(common, "%s is buggy! Expected length %d " 1723 "but we got %d\n", name, 1724 cmnd_size, common->cmnd_size); 1725 cmnd_size = common->cmnd_size; 1726 } else { 1727 common->phase_error = 1; 1728 return -EINVAL; 1729 } 1730 } 1731 1732 /* Check that the LUN values are consistent */ 1733 if (common->lun != lun) 1734 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n", 1735 common->lun, lun); 1736 1737 /* Check the LUN */ 1738 if (common->lun < common->nluns) { 1739 curlun = &common->luns[common->lun]; 1740 if (common->cmnd[0] != SC_REQUEST_SENSE) { 1741 curlun->sense_data = SS_NO_SENSE; 1742 curlun->info_valid = 0; 1743 } 1744 } else { 1745 curlun = NULL; 1746 common->bad_lun_okay = 0; 1747 1748 /* INQUIRY and REQUEST SENSE commands are explicitly allowed 1749 * to use unsupported LUNs; all others may not. */ 1750 if (common->cmnd[0] != SC_INQUIRY && 1751 common->cmnd[0] != SC_REQUEST_SENSE) { 1752 DBG(common, "unsupported LUN %d\n", common->lun); 1753 return -EINVAL; 1754 } 1755 } 1756 #if 0 1757 /* If a unit attention condition exists, only INQUIRY and 1758 * REQUEST SENSE commands are allowed; anything else must fail. */ 1759 if (curlun && curlun->unit_attention_data != SS_NO_SENSE && 1760 common->cmnd[0] != SC_INQUIRY && 1761 common->cmnd[0] != SC_REQUEST_SENSE) { 1762 curlun->sense_data = curlun->unit_attention_data; 1763 curlun->unit_attention_data = SS_NO_SENSE; 1764 return -EINVAL; 1765 } 1766 #endif 1767 /* Check that only command bytes listed in the mask are non-zero */ 1768 common->cmnd[1] &= 0x1f; /* Mask away the LUN */ 1769 for (i = 1; i < cmnd_size; ++i) { 1770 if (common->cmnd[i] && !(mask & (1 << i))) { 1771 if (curlun) 1772 curlun->sense_data = SS_INVALID_FIELD_IN_CDB; 1773 return -EINVAL; 1774 } 1775 } 1776 1777 return 0; 1778 } 1779 1780 1781 static int do_scsi_command(struct fsg_common *common) 1782 { 1783 struct fsg_buffhd *bh; 1784 int rc; 1785 int reply = -EINVAL; 1786 int i; 1787 static char unknown[16]; 1788 struct fsg_lun *curlun = &common->luns[common->lun]; 1789 const char *cdev_name __maybe_unused; 1790 1791 dump_cdb(common); 1792 1793 /* Wait for the next buffer to become available for data or status */ 1794 bh = common->next_buffhd_to_fill; 1795 common->next_buffhd_to_drain = bh; 1796 while (bh->state != BUF_STATE_EMPTY) { 1797 rc = sleep_thread(common); 1798 if (rc) 1799 return rc; 1800 } 1801 common->phase_error = 0; 1802 common->short_packet_received = 0; 1803 1804 down_read(&common->filesem); /* We're using the backing file */ 1805 1806 cdev_name = common->fsg->function.config->cdev->driver->name; 1807 if (IS_RKUSB_UMS_DNL(cdev_name)) { 1808 rc = rkusb_cmd_process(common, bh, &reply); 1809 if (rc == RKUSB_RC_FINISHED || rc == RKUSB_RC_ERROR) 1810 goto finish; 1811 else if (rc == RKUSB_RC_UNKNOWN_CMND) 1812 goto unknown_cmnd; 1813 } 1814 1815 switch (common->cmnd[0]) { 1816 1817 case SC_INQUIRY: 1818 common->data_size_from_cmnd = common->cmnd[4]; 1819 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1820 (1<<4), 0, 1821 "INQUIRY"); 1822 if (reply == 0) 1823 reply = do_inquiry(common, bh); 1824 break; 1825 1826 case SC_MODE_SELECT_6: 1827 common->data_size_from_cmnd = common->cmnd[4]; 1828 reply = check_command(common, 6, DATA_DIR_FROM_HOST, 1829 (1<<1) | (1<<4), 0, 1830 "MODE SELECT(6)"); 1831 if (reply == 0) 1832 reply = do_mode_select(common, bh); 1833 break; 1834 1835 case SC_MODE_SELECT_10: 1836 common->data_size_from_cmnd = 1837 get_unaligned_be16(&common->cmnd[7]); 1838 reply = check_command(common, 10, DATA_DIR_FROM_HOST, 1839 (1<<1) | (3<<7), 0, 1840 "MODE SELECT(10)"); 1841 if (reply == 0) 1842 reply = do_mode_select(common, bh); 1843 break; 1844 1845 case SC_MODE_SENSE_6: 1846 common->data_size_from_cmnd = common->cmnd[4]; 1847 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1848 (1<<1) | (1<<2) | (1<<4), 0, 1849 "MODE SENSE(6)"); 1850 if (reply == 0) 1851 reply = do_mode_sense(common, bh); 1852 break; 1853 1854 case SC_MODE_SENSE_10: 1855 common->data_size_from_cmnd = 1856 get_unaligned_be16(&common->cmnd[7]); 1857 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1858 (1<<1) | (1<<2) | (3<<7), 0, 1859 "MODE SENSE(10)"); 1860 if (reply == 0) 1861 reply = do_mode_sense(common, bh); 1862 break; 1863 1864 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL: 1865 common->data_size_from_cmnd = 0; 1866 reply = check_command(common, 6, DATA_DIR_NONE, 1867 (1<<4), 0, 1868 "PREVENT-ALLOW MEDIUM REMOVAL"); 1869 if (reply == 0) 1870 reply = do_prevent_allow(common); 1871 break; 1872 1873 case SC_READ_6: 1874 i = common->cmnd[4]; 1875 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9; 1876 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1877 (7<<1) | (1<<4), 1, 1878 "READ(6)"); 1879 if (reply == 0) 1880 reply = do_read(common); 1881 break; 1882 1883 case SC_READ_10: 1884 common->data_size_from_cmnd = 1885 get_unaligned_be16(&common->cmnd[7]) << 9; 1886 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1887 (1<<1) | (0xf<<2) | (3<<7), 1, 1888 "READ(10)"); 1889 if (reply == 0) 1890 reply = do_read(common); 1891 break; 1892 1893 case SC_READ_12: 1894 common->data_size_from_cmnd = 1895 get_unaligned_be32(&common->cmnd[6]) << 9; 1896 reply = check_command(common, 12, DATA_DIR_TO_HOST, 1897 (1<<1) | (0xf<<2) | (0xf<<6), 1, 1898 "READ(12)"); 1899 if (reply == 0) 1900 reply = do_read(common); 1901 break; 1902 1903 case SC_READ_CAPACITY: 1904 common->data_size_from_cmnd = 8; 1905 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1906 (0xf<<2) | (1<<8), 1, 1907 "READ CAPACITY"); 1908 if (reply == 0) 1909 reply = do_read_capacity(common, bh); 1910 break; 1911 1912 case SC_READ_HEADER: 1913 if (!common->luns[common->lun].cdrom) 1914 goto unknown_cmnd; 1915 common->data_size_from_cmnd = 1916 get_unaligned_be16(&common->cmnd[7]); 1917 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1918 (3<<7) | (0x1f<<1), 1, 1919 "READ HEADER"); 1920 if (reply == 0) 1921 reply = do_read_header(common, bh); 1922 break; 1923 1924 case SC_READ_TOC: 1925 if (!common->luns[common->lun].cdrom) 1926 goto unknown_cmnd; 1927 common->data_size_from_cmnd = 1928 get_unaligned_be16(&common->cmnd[7]); 1929 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1930 (7<<6) | (1<<1), 1, 1931 "READ TOC"); 1932 if (reply == 0) 1933 reply = do_read_toc(common, bh); 1934 break; 1935 1936 case SC_READ_FORMAT_CAPACITIES: 1937 common->data_size_from_cmnd = 1938 get_unaligned_be16(&common->cmnd[7]); 1939 reply = check_command(common, 10, DATA_DIR_TO_HOST, 1940 (3<<7), 1, 1941 "READ FORMAT CAPACITIES"); 1942 if (reply == 0) 1943 reply = do_read_format_capacities(common, bh); 1944 break; 1945 1946 case SC_REQUEST_SENSE: 1947 common->data_size_from_cmnd = common->cmnd[4]; 1948 reply = check_command(common, 6, DATA_DIR_TO_HOST, 1949 (1<<4), 0, 1950 "REQUEST SENSE"); 1951 if (reply == 0) 1952 reply = do_request_sense(common, bh); 1953 break; 1954 1955 case SC_START_STOP_UNIT: 1956 common->data_size_from_cmnd = 0; 1957 reply = check_command(common, 6, DATA_DIR_NONE, 1958 (1<<1) | (1<<4), 0, 1959 "START-STOP UNIT"); 1960 if (reply == 0) 1961 reply = do_start_stop(common); 1962 break; 1963 1964 case SC_SYNCHRONIZE_CACHE: 1965 common->data_size_from_cmnd = 0; 1966 reply = check_command(common, 10, DATA_DIR_NONE, 1967 (0xf<<2) | (3<<7), 1, 1968 "SYNCHRONIZE CACHE"); 1969 if (reply == 0) 1970 reply = do_synchronize_cache(common); 1971 break; 1972 1973 case SC_TEST_UNIT_READY: 1974 common->data_size_from_cmnd = 0; 1975 reply = check_command(common, 6, DATA_DIR_NONE, 1976 0, 1, 1977 "TEST UNIT READY"); 1978 break; 1979 1980 /* Although optional, this command is used by MS-Windows. We 1981 * support a minimal version: BytChk must be 0. */ 1982 case SC_VERIFY: 1983 common->data_size_from_cmnd = 0; 1984 reply = check_command(common, 10, DATA_DIR_NONE, 1985 (1<<1) | (0xf<<2) | (3<<7), 1, 1986 "VERIFY"); 1987 if (reply == 0) 1988 reply = do_verify(common); 1989 break; 1990 1991 case SC_WRITE_6: 1992 i = common->cmnd[4]; 1993 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9; 1994 reply = check_command(common, 6, DATA_DIR_FROM_HOST, 1995 (7<<1) | (1<<4), 1, 1996 "WRITE(6)"); 1997 if (reply == 0) 1998 reply = do_write(common); 1999 break; 2000 2001 case SC_WRITE_10: 2002 common->data_size_from_cmnd = 2003 get_unaligned_be16(&common->cmnd[7]) << 9; 2004 2005 if (IS_RKUSB_UMS_DNL(cdev_name)) { 2006 reply = check_command(common, common->cmnd_size, DATA_DIR_FROM_HOST, 2007 (1 << 1) | (0xf << 2) | (3 << 7) | (0xf << 9), 1, 2008 "WRITE(10)"); 2009 } else { 2010 reply = check_command(common, 10, DATA_DIR_FROM_HOST, 2011 (1 << 1) | (0xf << 2) | (3 << 7), 1, 2012 "WRITE(10)"); 2013 } 2014 2015 if (reply == 0) 2016 reply = do_write(common); 2017 break; 2018 2019 case SC_WRITE_12: 2020 common->data_size_from_cmnd = 2021 get_unaligned_be32(&common->cmnd[6]) << 9; 2022 reply = check_command(common, 12, DATA_DIR_FROM_HOST, 2023 (1<<1) | (0xf<<2) | (0xf<<6), 1, 2024 "WRITE(12)"); 2025 if (reply == 0) 2026 reply = do_write(common); 2027 break; 2028 2029 /* Some mandatory commands that we recognize but don't implement. 2030 * They don't mean much in this setting. It's left as an exercise 2031 * for anyone interested to implement RESERVE and RELEASE in terms 2032 * of Posix locks. */ 2033 case SC_FORMAT_UNIT: 2034 case SC_RELEASE: 2035 case SC_RESERVE: 2036 case SC_SEND_DIAGNOSTIC: 2037 /* Fall through */ 2038 2039 default: 2040 unknown_cmnd: 2041 common->data_size_from_cmnd = 0; 2042 sprintf(unknown, "Unknown x%02x", common->cmnd[0]); 2043 reply = check_command(common, common->cmnd_size, 2044 DATA_DIR_UNKNOWN, 0xff, 0, unknown); 2045 if (reply == 0) { 2046 curlun->sense_data = SS_INVALID_COMMAND; 2047 reply = -EINVAL; 2048 } 2049 break; 2050 } 2051 2052 finish: 2053 up_read(&common->filesem); 2054 2055 if (reply == -EINTR) 2056 return -EINTR; 2057 2058 /* Set up the single reply buffer for finish_reply() */ 2059 if (reply == -EINVAL) 2060 reply = 0; /* Error reply length */ 2061 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) { 2062 reply = min((u32) reply, common->data_size_from_cmnd); 2063 bh->inreq->length = reply; 2064 bh->state = BUF_STATE_FULL; 2065 common->residue -= reply; 2066 } /* Otherwise it's already set */ 2067 2068 return 0; 2069 } 2070 2071 /*-------------------------------------------------------------------------*/ 2072 2073 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh) 2074 { 2075 struct usb_request *req = bh->outreq; 2076 struct fsg_bulk_cb_wrap *cbw = req->buf; 2077 struct fsg_common *common = fsg->common; 2078 2079 /* Was this a real packet? Should it be ignored? */ 2080 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags)) 2081 return -EINVAL; 2082 2083 /* Is the CBW valid? */ 2084 if (req->actual != USB_BULK_CB_WRAP_LEN || 2085 cbw->Signature != cpu_to_le32( 2086 USB_BULK_CB_SIG)) { 2087 DBG(fsg, "invalid CBW: len %u sig 0x%x\n", 2088 req->actual, 2089 le32_to_cpu(cbw->Signature)); 2090 2091 /* The Bulk-only spec says we MUST stall the IN endpoint 2092 * (6.6.1), so it's unavoidable. It also says we must 2093 * retain this state until the next reset, but there's 2094 * no way to tell the controller driver it should ignore 2095 * Clear-Feature(HALT) requests. 2096 * 2097 * We aren't required to halt the OUT endpoint; instead 2098 * we can simply accept and discard any data received 2099 * until the next reset. */ 2100 wedge_bulk_in_endpoint(fsg); 2101 generic_set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags); 2102 return -EINVAL; 2103 } 2104 2105 /* Is the CBW meaningful? */ 2106 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG || 2107 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) { 2108 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, " 2109 "cmdlen %u\n", 2110 cbw->Lun, cbw->Flags, cbw->Length); 2111 2112 /* We can do anything we want here, so let's stall the 2113 * bulk pipes if we are allowed to. */ 2114 if (common->can_stall) { 2115 fsg_set_halt(fsg, fsg->bulk_out); 2116 halt_bulk_in_endpoint(fsg); 2117 } 2118 return -EINVAL; 2119 } 2120 2121 /* Save the command for later */ 2122 common->cmnd_size = cbw->Length; 2123 memcpy(common->cmnd, cbw->CDB, common->cmnd_size); 2124 if (cbw->Flags & USB_BULK_IN_FLAG) 2125 common->data_dir = DATA_DIR_TO_HOST; 2126 else 2127 common->data_dir = DATA_DIR_FROM_HOST; 2128 common->data_size = le32_to_cpu(cbw->DataTransferLength); 2129 if (common->data_size == 0) 2130 common->data_dir = DATA_DIR_NONE; 2131 common->lun = cbw->Lun; 2132 common->tag = cbw->Tag; 2133 return 0; 2134 } 2135 2136 2137 static int get_next_command(struct fsg_common *common) 2138 { 2139 struct fsg_buffhd *bh; 2140 int rc = 0; 2141 2142 /* Wait for the next buffer to become available */ 2143 bh = common->next_buffhd_to_fill; 2144 while (bh->state != BUF_STATE_EMPTY) { 2145 rc = sleep_thread(common); 2146 if (rc) 2147 return rc; 2148 } 2149 2150 /* Queue a request to read a Bulk-only CBW */ 2151 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN); 2152 bh->outreq->short_not_ok = 1; 2153 START_TRANSFER_OR(common, bulk_out, bh->outreq, 2154 &bh->outreq_busy, &bh->state) 2155 /* Don't know what to do if common->fsg is NULL */ 2156 return -EIO; 2157 2158 /* We will drain the buffer in software, which means we 2159 * can reuse it for the next filling. No need to advance 2160 * next_buffhd_to_fill. */ 2161 2162 /* Wait for the CBW to arrive */ 2163 while (bh->state != BUF_STATE_FULL) { 2164 rc = sleep_thread(common); 2165 if (rc) 2166 return rc; 2167 } 2168 2169 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO; 2170 bh->state = BUF_STATE_EMPTY; 2171 2172 return rc; 2173 } 2174 2175 2176 /*-------------------------------------------------------------------------*/ 2177 2178 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep, 2179 const struct usb_endpoint_descriptor *d) 2180 { 2181 int rc; 2182 2183 ep->driver_data = common; 2184 rc = usb_ep_enable(ep, d); 2185 if (rc) 2186 ERROR(common, "can't enable %s, result %d\n", ep->name, rc); 2187 return rc; 2188 } 2189 2190 static int alloc_request(struct fsg_common *common, struct usb_ep *ep, 2191 struct usb_request **preq) 2192 { 2193 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC); 2194 if (*preq) 2195 return 0; 2196 ERROR(common, "can't allocate request for %s\n", ep->name); 2197 return -ENOMEM; 2198 } 2199 2200 /* Reset interface setting and re-init endpoint state (toggle etc). */ 2201 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg) 2202 { 2203 const struct usb_endpoint_descriptor *d; 2204 struct fsg_dev *fsg; 2205 int i, rc = 0; 2206 2207 if (common->running) 2208 DBG(common, "reset interface\n"); 2209 2210 reset: 2211 /* Deallocate the requests */ 2212 if (common->fsg) { 2213 fsg = common->fsg; 2214 2215 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2216 struct fsg_buffhd *bh = &common->buffhds[i]; 2217 2218 if (bh->inreq) { 2219 usb_ep_free_request(fsg->bulk_in, bh->inreq); 2220 bh->inreq = NULL; 2221 } 2222 if (bh->outreq) { 2223 usb_ep_free_request(fsg->bulk_out, bh->outreq); 2224 bh->outreq = NULL; 2225 } 2226 } 2227 2228 /* Disable the endpoints */ 2229 if (fsg->bulk_in_enabled) { 2230 usb_ep_disable(fsg->bulk_in); 2231 fsg->bulk_in_enabled = 0; 2232 } 2233 if (fsg->bulk_out_enabled) { 2234 usb_ep_disable(fsg->bulk_out); 2235 fsg->bulk_out_enabled = 0; 2236 } 2237 2238 common->fsg = NULL; 2239 /* wake_up(&common->fsg_wait); */ 2240 } 2241 2242 common->running = 0; 2243 if (!new_fsg || rc) 2244 return rc; 2245 2246 common->fsg = new_fsg; 2247 fsg = common->fsg; 2248 2249 /* Enable the endpoints */ 2250 d = fsg_ep_desc(common->gadget, 2251 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc, 2252 &fsg_ss_bulk_in_desc, &fsg_ss_bulk_in_comp_desc, 2253 fsg->bulk_in); 2254 rc = enable_endpoint(common, fsg->bulk_in, d); 2255 if (rc) 2256 goto reset; 2257 fsg->bulk_in_enabled = 1; 2258 2259 d = fsg_ep_desc(common->gadget, 2260 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc, 2261 &fsg_ss_bulk_out_desc, &fsg_ss_bulk_out_comp_desc, 2262 fsg->bulk_out); 2263 rc = enable_endpoint(common, fsg->bulk_out, d); 2264 if (rc) 2265 goto reset; 2266 fsg->bulk_out_enabled = 1; 2267 common->bulk_out_maxpacket = 2268 le16_to_cpu(get_unaligned(&d->wMaxPacketSize)); 2269 generic_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags); 2270 2271 /* Allocate the requests */ 2272 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2273 struct fsg_buffhd *bh = &common->buffhds[i]; 2274 2275 rc = alloc_request(common, fsg->bulk_in, &bh->inreq); 2276 if (rc) 2277 goto reset; 2278 rc = alloc_request(common, fsg->bulk_out, &bh->outreq); 2279 if (rc) 2280 goto reset; 2281 bh->inreq->buf = bh->outreq->buf = bh->buf; 2282 bh->inreq->context = bh->outreq->context = bh; 2283 bh->inreq->complete = bulk_in_complete; 2284 bh->outreq->complete = bulk_out_complete; 2285 } 2286 2287 common->running = 1; 2288 2289 return rc; 2290 } 2291 2292 2293 /****************************** ALT CONFIGS ******************************/ 2294 2295 2296 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt) 2297 { 2298 struct fsg_dev *fsg = fsg_from_func(f); 2299 fsg->common->new_fsg = fsg; 2300 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); 2301 return 0; 2302 } 2303 2304 static void fsg_disable(struct usb_function *f) 2305 { 2306 struct fsg_dev *fsg = fsg_from_func(f); 2307 fsg->common->new_fsg = NULL; 2308 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); 2309 } 2310 2311 /*-------------------------------------------------------------------------*/ 2312 2313 static void handle_exception(struct fsg_common *common) 2314 { 2315 int i; 2316 struct fsg_buffhd *bh; 2317 enum fsg_state old_state; 2318 struct fsg_lun *curlun; 2319 unsigned int exception_req_tag; 2320 2321 /* Cancel all the pending transfers */ 2322 if (common->fsg) { 2323 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2324 bh = &common->buffhds[i]; 2325 if (bh->inreq_busy) 2326 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq); 2327 if (bh->outreq_busy) 2328 usb_ep_dequeue(common->fsg->bulk_out, 2329 bh->outreq); 2330 } 2331 2332 /* Wait until everything is idle */ 2333 for (;;) { 2334 int num_active = 0; 2335 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2336 bh = &common->buffhds[i]; 2337 num_active += bh->inreq_busy + bh->outreq_busy; 2338 } 2339 if (num_active == 0) 2340 break; 2341 if (sleep_thread(common)) 2342 return; 2343 } 2344 2345 /* Clear out the controller's fifos */ 2346 if (common->fsg->bulk_in_enabled) 2347 usb_ep_fifo_flush(common->fsg->bulk_in); 2348 if (common->fsg->bulk_out_enabled) 2349 usb_ep_fifo_flush(common->fsg->bulk_out); 2350 } 2351 2352 /* Reset the I/O buffer states and pointers, the SCSI 2353 * state, and the exception. Then invoke the handler. */ 2354 2355 for (i = 0; i < FSG_NUM_BUFFERS; ++i) { 2356 bh = &common->buffhds[i]; 2357 bh->state = BUF_STATE_EMPTY; 2358 } 2359 common->next_buffhd_to_fill = &common->buffhds[0]; 2360 common->next_buffhd_to_drain = &common->buffhds[0]; 2361 exception_req_tag = common->exception_req_tag; 2362 old_state = common->state; 2363 2364 if (old_state == FSG_STATE_ABORT_BULK_OUT) 2365 common->state = FSG_STATE_STATUS_PHASE; 2366 else { 2367 for (i = 0; i < common->nluns; ++i) { 2368 curlun = &common->luns[i]; 2369 curlun->sense_data = SS_NO_SENSE; 2370 curlun->info_valid = 0; 2371 } 2372 common->state = FSG_STATE_IDLE; 2373 } 2374 2375 /* Carry out any extra actions required for the exception */ 2376 switch (old_state) { 2377 case FSG_STATE_ABORT_BULK_OUT: 2378 send_status(common); 2379 2380 if (common->state == FSG_STATE_STATUS_PHASE) 2381 common->state = FSG_STATE_IDLE; 2382 break; 2383 2384 case FSG_STATE_RESET: 2385 /* In case we were forced against our will to halt a 2386 * bulk endpoint, clear the halt now. (The SuperH UDC 2387 * requires this.) */ 2388 if (!fsg_is_set(common)) 2389 break; 2390 if (test_and_clear_bit(IGNORE_BULK_OUT, 2391 &common->fsg->atomic_bitflags)) 2392 usb_ep_clear_halt(common->fsg->bulk_in); 2393 2394 if (common->ep0_req_tag == exception_req_tag) 2395 ep0_queue(common); /* Complete the status stage */ 2396 2397 break; 2398 2399 case FSG_STATE_CONFIG_CHANGE: 2400 do_set_interface(common, common->new_fsg); 2401 break; 2402 2403 case FSG_STATE_EXIT: 2404 case FSG_STATE_TERMINATED: 2405 do_set_interface(common, NULL); /* Free resources */ 2406 common->state = FSG_STATE_TERMINATED; /* Stop the thread */ 2407 break; 2408 2409 case FSG_STATE_INTERFACE_CHANGE: 2410 case FSG_STATE_DISCONNECT: 2411 case FSG_STATE_COMMAND_PHASE: 2412 case FSG_STATE_DATA_PHASE: 2413 case FSG_STATE_STATUS_PHASE: 2414 case FSG_STATE_IDLE: 2415 break; 2416 } 2417 } 2418 2419 /*-------------------------------------------------------------------------*/ 2420 2421 int fsg_main_thread(void *common_) 2422 { 2423 int ret; 2424 struct fsg_common *common = the_fsg_common; 2425 /* The main loop */ 2426 do { 2427 if (exception_in_progress(common)) { 2428 handle_exception(common); 2429 continue; 2430 } 2431 2432 if (!common->running) { 2433 ret = sleep_thread(common); 2434 if (ret) 2435 return ret; 2436 2437 continue; 2438 } 2439 2440 ret = get_next_command(common); 2441 if (ret) 2442 return ret; 2443 2444 if (!exception_in_progress(common)) 2445 common->state = FSG_STATE_DATA_PHASE; 2446 2447 if (do_scsi_command(common) || finish_reply(common)) 2448 continue; 2449 2450 if (!exception_in_progress(common)) 2451 common->state = FSG_STATE_STATUS_PHASE; 2452 2453 if (send_status(common)) 2454 continue; 2455 2456 if (!exception_in_progress(common)) 2457 common->state = FSG_STATE_IDLE; 2458 } while (0); 2459 2460 common->thread_task = NULL; 2461 2462 return 0; 2463 } 2464 2465 static void fsg_common_release(struct kref *ref); 2466 2467 static struct fsg_common *fsg_common_init(struct fsg_common *common, 2468 struct usb_composite_dev *cdev) 2469 { 2470 struct usb_gadget *gadget = cdev->gadget; 2471 struct fsg_buffhd *bh; 2472 struct fsg_lun *curlun; 2473 int nluns, i, rc; 2474 2475 /* Find out how many LUNs there should be */ 2476 nluns = ums_count; 2477 if (nluns < 1 || nluns > FSG_MAX_LUNS) { 2478 printf("invalid number of LUNs: %u\n", nluns); 2479 return ERR_PTR(-EINVAL); 2480 } 2481 2482 /* Allocate? */ 2483 if (!common) { 2484 common = calloc(sizeof(*common), 1); 2485 if (!common) 2486 return ERR_PTR(-ENOMEM); 2487 common->free_storage_on_release = 1; 2488 } else { 2489 memset(common, 0, sizeof(*common)); 2490 common->free_storage_on_release = 0; 2491 } 2492 2493 common->ops = NULL; 2494 common->private_data = NULL; 2495 2496 common->gadget = gadget; 2497 common->ep0 = gadget->ep0; 2498 common->ep0req = cdev->req; 2499 2500 /* Maybe allocate device-global string IDs, and patch descriptors */ 2501 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) { 2502 rc = usb_string_id(cdev); 2503 if (unlikely(rc < 0)) 2504 goto error_release; 2505 fsg_strings[FSG_STRING_INTERFACE].id = rc; 2506 fsg_intf_desc.iInterface = rc; 2507 } 2508 2509 /* Create the LUNs, open their backing files, and register the 2510 * LUN devices in sysfs. */ 2511 curlun = calloc(nluns, sizeof *curlun); 2512 if (!curlun) { 2513 rc = -ENOMEM; 2514 goto error_release; 2515 } 2516 common->nluns = nluns; 2517 2518 for (i = 0; i < nluns; i++) { 2519 common->luns[i].removable = 1; 2520 2521 rc = fsg_lun_open(&common->luns[i], ums[i].num_sectors, ""); 2522 if (rc) 2523 goto error_luns; 2524 } 2525 common->lun = 0; 2526 2527 /* Data buffers cyclic list */ 2528 bh = common->buffhds; 2529 2530 i = FSG_NUM_BUFFERS; 2531 goto buffhds_first_it; 2532 do { 2533 bh->next = bh + 1; 2534 ++bh; 2535 buffhds_first_it: 2536 bh->inreq_busy = 0; 2537 bh->outreq_busy = 0; 2538 bh->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, FSG_BUFLEN); 2539 if (unlikely(!bh->buf)) { 2540 rc = -ENOMEM; 2541 goto error_release; 2542 } 2543 } while (--i); 2544 bh->next = common->buffhds; 2545 2546 snprintf(common->inquiry_string, sizeof common->inquiry_string, 2547 "%-8s%-16s%04x", 2548 "Linux ", 2549 "File-Store Gadget", 2550 0xffff); 2551 2552 /* Some peripheral controllers are known not to be able to 2553 * halt bulk endpoints correctly. If one of them is present, 2554 * disable stalls. 2555 */ 2556 2557 /* Tell the thread to start working */ 2558 common->thread_task = 2559 kthread_create(fsg_main_thread, common, 2560 OR(cfg->thread_name, "file-storage")); 2561 if (IS_ERR(common->thread_task)) { 2562 rc = PTR_ERR(common->thread_task); 2563 goto error_release; 2564 } 2565 2566 #undef OR 2567 /* Information */ 2568 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n"); 2569 INFO(common, "Number of LUNs=%d\n", common->nluns); 2570 2571 return common; 2572 2573 error_luns: 2574 common->nluns = i + 1; 2575 error_release: 2576 common->state = FSG_STATE_TERMINATED; /* The thread is dead */ 2577 /* Call fsg_common_release() directly, ref might be not 2578 * initialised */ 2579 fsg_common_release(&common->ref); 2580 return ERR_PTR(rc); 2581 } 2582 2583 static void fsg_common_release(struct kref *ref) 2584 { 2585 struct fsg_common *common = container_of(ref, struct fsg_common, ref); 2586 2587 /* If the thread isn't already dead, tell it to exit now */ 2588 if (common->state != FSG_STATE_TERMINATED) { 2589 raise_exception(common, FSG_STATE_EXIT); 2590 wait_for_completion(&common->thread_notifier); 2591 } 2592 2593 if (likely(common->luns)) { 2594 struct fsg_lun *lun = common->luns; 2595 unsigned i = common->nluns; 2596 2597 /* In error recovery common->nluns may be zero. */ 2598 for (; i; --i, ++lun) 2599 fsg_lun_close(lun); 2600 2601 kfree(common->luns); 2602 } 2603 2604 { 2605 struct fsg_buffhd *bh = common->buffhds; 2606 unsigned i = FSG_NUM_BUFFERS; 2607 do { 2608 kfree(bh->buf); 2609 } while (++bh, --i); 2610 } 2611 2612 if (common->free_storage_on_release) 2613 kfree(common); 2614 } 2615 2616 2617 /*-------------------------------------------------------------------------*/ 2618 2619 /** 2620 * usb_copy_descriptors - copy a vector of USB descriptors 2621 * @src: null-terminated vector to copy 2622 * Context: initialization code, which may sleep 2623 * 2624 * This makes a copy of a vector of USB descriptors. Its primary use 2625 * is to support usb_function objects which can have multiple copies, 2626 * each needing different descriptors. Functions may have static 2627 * tables of descriptors, which are used as templates and customized 2628 * with identifiers (for interfaces, strings, endpoints, and more) 2629 * as needed by a given function instance. 2630 */ 2631 struct usb_descriptor_header ** 2632 usb_copy_descriptors(struct usb_descriptor_header **src) 2633 { 2634 struct usb_descriptor_header **tmp; 2635 unsigned bytes; 2636 unsigned n_desc; 2637 void *mem; 2638 struct usb_descriptor_header **ret; 2639 2640 /* count descriptors and their sizes; then add vector size */ 2641 for (bytes = 0, n_desc = 0, tmp = src; *tmp; tmp++, n_desc++) 2642 bytes += (*tmp)->bLength; 2643 bytes += (n_desc + 1) * sizeof(*tmp); 2644 2645 mem = memalign(CONFIG_SYS_CACHELINE_SIZE, bytes); 2646 if (!mem) 2647 return NULL; 2648 2649 /* fill in pointers starting at "tmp", 2650 * to descriptors copied starting at "mem"; 2651 * and return "ret" 2652 */ 2653 tmp = mem; 2654 ret = mem; 2655 mem += (n_desc + 1) * sizeof(*tmp); 2656 while (*src) { 2657 memcpy(mem, *src, (*src)->bLength); 2658 *tmp = mem; 2659 tmp++; 2660 mem += (*src)->bLength; 2661 src++; 2662 } 2663 *tmp = NULL; 2664 2665 return ret; 2666 } 2667 2668 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f) 2669 { 2670 struct fsg_dev *fsg = fsg_from_func(f); 2671 2672 DBG(fsg, "unbind\n"); 2673 if (fsg->common->fsg == fsg) { 2674 fsg->common->new_fsg = NULL; 2675 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); 2676 } 2677 2678 free(fsg->function.descriptors); 2679 free(fsg->function.hs_descriptors); 2680 kfree(fsg); 2681 } 2682 2683 static int fsg_bind(struct usb_configuration *c, struct usb_function *f) 2684 { 2685 struct fsg_dev *fsg = fsg_from_func(f); 2686 struct usb_gadget *gadget = c->cdev->gadget; 2687 int i; 2688 struct usb_ep *ep; 2689 fsg->gadget = gadget; 2690 2691 /* New interface */ 2692 i = usb_interface_id(c, f); 2693 if (i < 0) 2694 return i; 2695 fsg_intf_desc.bInterfaceNumber = i; 2696 fsg->interface_number = i; 2697 2698 /* Find all the endpoints we will use */ 2699 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc); 2700 if (!ep) 2701 goto autoconf_fail; 2702 ep->driver_data = fsg->common; /* claim the endpoint */ 2703 fsg->bulk_in = ep; 2704 2705 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc); 2706 if (!ep) 2707 goto autoconf_fail; 2708 ep->driver_data = fsg->common; /* claim the endpoint */ 2709 fsg->bulk_out = ep; 2710 2711 /* Copy descriptors */ 2712 if (IS_RKUSB_UMS_DNL(c->cdev->driver->name)) 2713 f->descriptors = usb_copy_descriptors(rkusb_fs_function); 2714 else 2715 f->descriptors = usb_copy_descriptors(fsg_fs_function); 2716 if (unlikely(!f->descriptors)) 2717 return -ENOMEM; 2718 2719 if (gadget_is_dualspeed(gadget)) { 2720 /* Assume endpoint addresses are the same for both speeds */ 2721 fsg_hs_bulk_in_desc.bEndpointAddress = 2722 fsg_fs_bulk_in_desc.bEndpointAddress; 2723 fsg_hs_bulk_out_desc.bEndpointAddress = 2724 fsg_fs_bulk_out_desc.bEndpointAddress; 2725 2726 if (IS_RKUSB_UMS_DNL(c->cdev->driver->name)) 2727 f->hs_descriptors = 2728 usb_copy_descriptors(rkusb_hs_function); 2729 else 2730 f->hs_descriptors = 2731 usb_copy_descriptors(fsg_hs_function); 2732 if (unlikely(!f->hs_descriptors)) { 2733 free(f->descriptors); 2734 return -ENOMEM; 2735 } 2736 } 2737 2738 if (gadget_is_superspeed(gadget)) { 2739 /* Assume endpoint addresses are the same as full speed */ 2740 fsg_ss_bulk_in_desc.bEndpointAddress = 2741 fsg_fs_bulk_in_desc.bEndpointAddress; 2742 fsg_ss_bulk_out_desc.bEndpointAddress = 2743 fsg_fs_bulk_out_desc.bEndpointAddress; 2744 2745 #ifdef CONFIG_CMD_ROCKUSB 2746 if (IS_RKUSB_UMS_DNL(c->cdev->driver->name)) 2747 f->ss_descriptors = 2748 usb_copy_descriptors(rkusb_ss_function); 2749 #endif 2750 2751 if (unlikely(!f->ss_descriptors)) { 2752 free(f->descriptors); 2753 return -ENOMEM; 2754 } 2755 } 2756 return 0; 2757 2758 autoconf_fail: 2759 ERROR(fsg, "unable to autoconfigure all endpoints\n"); 2760 return -ENOTSUPP; 2761 } 2762 2763 2764 /****************************** ADD FUNCTION ******************************/ 2765 2766 static struct usb_gadget_strings *fsg_strings_array[] = { 2767 &fsg_stringtab, 2768 NULL, 2769 }; 2770 2771 static int fsg_bind_config(struct usb_composite_dev *cdev, 2772 struct usb_configuration *c, 2773 struct fsg_common *common) 2774 { 2775 struct fsg_dev *fsg; 2776 int rc; 2777 2778 fsg = calloc(1, sizeof *fsg); 2779 if (!fsg) 2780 return -ENOMEM; 2781 fsg->function.name = FSG_DRIVER_DESC; 2782 fsg->function.strings = fsg_strings_array; 2783 fsg->function.bind = fsg_bind; 2784 fsg->function.unbind = fsg_unbind; 2785 fsg->function.setup = fsg_setup; 2786 fsg->function.set_alt = fsg_set_alt; 2787 fsg->function.disable = fsg_disable; 2788 2789 fsg->common = common; 2790 common->fsg = fsg; 2791 /* Our caller holds a reference to common structure so we 2792 * don't have to be worry about it being freed until we return 2793 * from this function. So instead of incrementing counter now 2794 * and decrement in error recovery we increment it only when 2795 * call to usb_add_function() was successful. */ 2796 2797 rc = usb_add_function(c, &fsg->function); 2798 2799 if (rc) 2800 kfree(fsg); 2801 2802 return rc; 2803 } 2804 2805 int fsg_add(struct usb_configuration *c) 2806 { 2807 struct fsg_common *fsg_common; 2808 2809 fsg_common = fsg_common_init(NULL, c->cdev); 2810 2811 fsg_common->vendor_name = 0; 2812 fsg_common->product_name = 0; 2813 fsg_common->release = 0xffff; 2814 2815 fsg_common->ops = NULL; 2816 fsg_common->private_data = NULL; 2817 2818 the_fsg_common = fsg_common; 2819 2820 return fsg_bind_config(c->cdev, c, fsg_common); 2821 } 2822 2823 int fsg_init(struct ums *ums_devs, int count) 2824 { 2825 ums = ums_devs; 2826 ums_count = count; 2827 2828 return 0; 2829 } 2830 2831 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_ums, fsg_add); 2832