f_mass_storage.c 91 KB

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