f_mass_storage.c 87 KB

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