file_storage.c 115 KB

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