f_mass_storage.c 93 KB

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