f_mass_storage.c 83 KB

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