f_mass_storage.c 93 KB

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