file_storage.c 102 KB

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