f_mass_storage.c 93 KB

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