f_mass_storage.c 93 KB

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