file_storage.c 102 KB

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