f_mass_storage.c 89 KB

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