f_mass_storage.c 93 KB

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