f_mass_storage.c 87 KB

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