f_mass_storage.c 89 KB

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