file_storage.c 104 KB

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