f_mass_storage.c 78 KB

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