f_mass_storage.c 87 KB

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