file_storage.c 114 KB

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