f_mass_storage.c 89 KB

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