file_storage.c 103 KB

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