f_mass_storage.c 77 KB

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