file_storage.c 103 KB

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