f_mass_storage.c 86 KB

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