f_mass_storage.c 95 KB

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