file_storage.c 114 KB

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