f_mass_storage.c 88 KB

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