file_storage.c 103 KB

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