f_mass_storage.c 89 KB

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