file_storage.c 104 KB

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