f_mass_storage.c 89 KB

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