f_mass_storage.c 88 KB

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