f_mass_storage.c 88 KB

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