f_mass_storage.c 91 KB

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