file_storage.c 104 KB

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