f_mass_storage.c 95 KB

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