file_storage.c 118 KB

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