file_storage.c 114 KB

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