f_mass_storage.c 77 KB

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