f_mass_storage.c 77 KB

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