f_mass_storage.c 89 KB

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