file_storage.c 115 KB

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