f_mass_storage.c 96 KB

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