f_mass_storage.c 89 KB

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