f_mass_storage.c 87 KB

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