file_storage.c 114 KB

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