file_storage.c 118 KB

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