file_storage.c 113 KB

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