PageRenderTime 31ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/drivers/usb/gadget/f_mass_storage.c

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