file_storage.c 113 KB

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