f_mass_storage.c 89 KB

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