file_storage.c 118 KB

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