f_mass_storage.c 95 KB

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