file_storage.c 103 KB

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