f_mass_storage.c 95 KB

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