file_storage.c 116 KB

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