fusb_msc.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. /*
  2. * Copyright : (C) 2022 Phytium Information Technology, Inc.
  3. * All Rights Reserved.
  4. *
  5. * This program is OPEN SOURCE software: you can redistribute it and/or modify it
  6. * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd,
  7. * either version 1.0 of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY;
  10. * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. * See the Phytium Public License for more details.
  12. *
  13. *
  14. * FilePath: fusb_msc.c
  15. * Date: 2022-02-11 13:33:09
  16. * LastEditTime: 2022-02-17 17:49:43
  17. * Description:  This files is for implementation of USB mass storage function
  18. *
  19. * Modify History:
  20. * Ver   Who        Date         Changes
  21. * ----- ------     --------    --------------------------------------
  22. * 1.0 Zhugengyu 2022/2/7 init commit
  23. */
  24. #include <string.h>
  25. #include "fswap.h"
  26. #include "fsleep.h"
  27. #include "fassert.h"
  28. #include "fgeneric_timer.h"
  29. #include "fdebug.h"
  30. #include "fusb.h"
  31. #include "fusb_msc.h"
  32. #define FUSB_DEBUG_TAG "FUSB_MSC"
  33. #define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__)
  34. #define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__)
  35. #define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__)
  36. #define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__)
  37. static inline tick_t FUsbMscGetTick(void)
  38. {
  39. return GenericTimerRead();
  40. }
  41. static inline tick_t FUsbMscStartTick(void)
  42. {
  43. GenericTimerStart();
  44. return FUsbMscGetTick();
  45. }
  46. static inline void FUsbMscStopTick(void)
  47. {
  48. GenericTimerStop();
  49. }
  50. static inline boolean FUsbMscTimeout(tick_t start_tick, tick_t timeout_tick)
  51. {
  52. return (FUsbMscGetTick() - start_tick) > timeout_tick;
  53. }
  54. static void FUsbMassStorageForceInit(FUsbDev *dev, u32 quirks);
  55. static int FUsbMscRwBlks(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf);
  56. static const char *FUsbMscSubClassString[7] =
  57. {
  58. "(none)",
  59. "RBC",
  60. "MMC-2",
  61. "QIC-157",
  62. "UFI",
  63. "SFF-8070i",
  64. "SCSI transparent"
  65. };
  66. static const char *FUsbMscProtocolStrings[0x51] =
  67. {
  68. "Control/Bulk/Interrupt protocol (with command completion interrupt)",
  69. "Control/Bulk/Interrupt protocol (with no command completion interrupt)",
  70. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  71. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  72. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  73. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  75. "Bulk-Only Transport"
  76. };
  77. /**
  78. * @name: FUsbMscCreateDisk
  79. * @msg: 调用应用程序实现的钩子函数,创建USB Disk
  80. * @return {*}
  81. * @param {FUsbDev} *dev, USB大容量存储设备实例
  82. */
  83. static void FUsbMscCreateDisk(FUsbDev *dev)
  84. {
  85. FASSERT(dev);
  86. if (FUsbDiskCreate)
  87. {
  88. FUsbDiskCreate(dev);
  89. MSC_INST(dev)->usbdisk_created = 1;
  90. }
  91. return;
  92. }
  93. /**
  94. * @name: FUsbMscRemoveDisk
  95. * @msg: 调用应用程序实现的钩子函数,移除USB Disk
  96. * @return {*}
  97. * @param {FUsbDev} *dev, USB大容量存储设备实例
  98. */
  99. static void FUsbMscRemoveDisk(FUsbDev *dev)
  100. {
  101. FASSERT(dev);
  102. if (MSC_INST(dev)->usbdisk_created && FUsbDiskRemove)
  103. FUsbDiskRemove(dev);
  104. return;
  105. }
  106. /**
  107. * @name: FUsbMscDestory
  108. * @msg: 移除USB大容量存储设备实例
  109. * @return {*}
  110. * @param {FUsbDev} *dev, USB大容量存储设备实例
  111. */
  112. static void FUsbMscDestory(FUsbDev *dev)
  113. {
  114. FASSERT(dev && dev->controller);
  115. FUsb *instance = dev->controller->usb;
  116. FASSERT(instance);
  117. if (NULL != dev->data)
  118. {
  119. FUsbMscRemoveDisk(dev);
  120. FUSB_FREE(instance, dev->data);
  121. }
  122. dev->data = NULL;
  123. return;
  124. }
  125. const int DEV_RESET = 0xff;
  126. const int GET_MAX_LUN = 0xfe;
  127. /* Many USB3 devices do not work with large transfer requests.
  128. * Limit the request size to 64KB chunks to ensure maximum compatibility. */
  129. const int MAX_CHUNK_BYTES = 1024 * 64;
  130. const unsigned int cbw_signature = 0x43425355; /* according to USB mass-bulk spec. helps to identify data packets */
  131. const unsigned int csw_signature = 0x53425355;
  132. /* following data structure following name convention in USB mass-bulk spec., which may not compiliance to other code */
  133. /* A packet containing a command block and associated information. */
  134. typedef struct
  135. {
  136. unsigned int dCBWSignature;
  137. unsigned int dCBWTag;
  138. unsigned int dCBWDataTransferLength;
  139. unsigned char bmCBWFlags;
  140. unsigned long bCBWLUN : 4; /* device Logical Unit Number (LUN) */
  141. unsigned long : 4;
  142. unsigned long bCBWCBLength : 5;
  143. unsigned long : 3;
  144. unsigned char CBWCB[31 - 15];
  145. } __attribute__((packed)) FUsbMscCbw; /* Command Block Wrapper (CBW) */
  146. /* A packet containing the status of a command block */
  147. typedef struct
  148. {
  149. unsigned int dCSWSignature;
  150. unsigned int dCSWTag;
  151. unsigned int dCSWDataResidue;
  152. unsigned char bCSWStatus;
  153. } __attribute__((packed)) FUsbMscCsw;
  154. enum
  155. {
  156. /*
  157. * MSC commands can be
  158. * successful,
  159. * fail with proper response or
  160. * fail totally, which results in detaching of the USB device
  161. * and immediate cleanup of the FUsbDev structure.
  162. * In the latter case the caller has to make sure, that he won't
  163. * use the device any more.
  164. */
  165. MSC_COMMAND_OK = 0,
  166. MSC_COMMAND_FAIL,
  167. MSC_COMMAND_DETACHED
  168. };
  169. static int FUsbMscRequestSense(FUsbDev *dev);
  170. static int FUsbMscRequestNoMedia(FUsbDev *dev);
  171. static void FUsbMscPoll(FUsbDev *dev);
  172. static int FUsbClearStall(FUsbEndpoint *ep)
  173. {
  174. FASSERT(ep);
  175. int ret = FUsbClearFeature(ep->dev, ep->endpoint, FUSB_ENDPOINT_HALT,
  176. FUsbGenerateReqType(FUSB_REQ_HOST_TO_DEVICE, FUSB_REQ_TYPE_STANDARD, FUSB_REQ_RECP_EP));
  177. ep->toggle = 0;
  178. return ret;
  179. }
  180. static int FUsbMscResetTransport(FUsbDev *dev)
  181. {
  182. FUsbDevReq dr;
  183. memset(&dr, 0, sizeof(dr));
  184. dr.bmRequestType = 0;
  185. dr.data_dir = FUSB_REQ_HOST_TO_DEVICE;
  186. dr.req_type = FUSB_REQ_TYPE_CLASS;
  187. dr.req_recp = FUSB_REQ_RECP_IF;
  188. dr.bRequest = DEV_RESET;
  189. dr.wValue = 0;
  190. dr.wIndex = 0;
  191. dr.wLength = 0;
  192. if (MSC_INST(dev)->quirks & FUSB_MSC_QUIRK_NO_RESET)
  193. return MSC_COMMAND_FAIL;
  194. /* if any of these fails, detach device, as we are lost */
  195. if (dev->controller->control(dev, FUSB_OUT, sizeof(dr), &dr, 0, 0) < 0 ||
  196. FUsbClearStall(MSC_INST(dev)->bulk_in) ||
  197. FUsbClearStall(MSC_INST(dev)->bulk_out))
  198. {
  199. FUSB_INFO("Detaching unresponsive device. ");
  200. FUsbDetachDev(dev->controller, dev->address);
  201. return MSC_COMMAND_DETACHED;
  202. }
  203. /* return fail as we are only called in case of failure */
  204. return MSC_COMMAND_FAIL;
  205. }
  206. /* device may stall this command, so beware! */
  207. static void FUsbMscInitLuns(FUsbDev *dev)
  208. {
  209. FUsbMassStorage *msc = MSC_INST(dev);
  210. FUsbDevReq dr;
  211. dr.bmRequestType = 0;
  212. dr.data_dir = FUSB_REQ_DEVICE_TO_HOST;
  213. dr.req_type = FUSB_REQ_TYPE_CLASS;
  214. dr.req_recp = FUSB_REQ_RECP_IF;
  215. dr.bRequest = GET_MAX_LUN;
  216. dr.wValue = 0;
  217. dr.wIndex = 0;
  218. dr.wLength = 1;
  219. /* send class-spefic request Get Max Lun */
  220. if ((MSC_INST(dev)->quirks & FUSB_MSC_QUIRK_NO_LUNS) ||
  221. (dev->controller->control(dev, FUSB_IN, sizeof(dr), &dr,
  222. sizeof(msc->num_luns), &msc->num_luns) < FUSB_CC_ZERO_BYTES))
  223. {
  224. msc->num_luns = 0; /* assume only 1 lun if req fails */
  225. }
  226. msc->num_luns++; /* Get Max LUN returns number of last LUN */
  227. msc->lun = 0;
  228. return;
  229. }
  230. unsigned int tag;
  231. static void FUsbMscWrapCbw(FUsbMscCbw *cbw, int datalen, FUsbMassStorageDirection dir, const u8 *cmd,
  232. int cmdlen, u8 lun)
  233. {
  234. memset(cbw, 0, sizeof(FUsbMscCbw));
  235. /* commands are typically shorter, but we don't want overflows */
  236. if ((size_t)cmdlen > sizeof(cbw->CBWCB))
  237. {
  238. cmdlen = (int)sizeof(cbw->CBWCB);
  239. }
  240. cbw->dCBWSignature = cbw_signature;
  241. cbw->dCBWTag = ++tag; /* command block tag to device */
  242. cbw->bCBWLUN = lun; /* logic unit number to send */
  243. cbw->dCBWDataTransferLength = datalen; /* number of bytes of data expect to transfer */
  244. cbw->bmCBWFlags = dir;
  245. memcpy(cbw->CBWCB, cmd, cmdlen); /* the command block to be executed by the device */
  246. cbw->bCBWCBLength = cmdlen; /* the valid length of the CBWCB in bytes */
  247. return;
  248. }
  249. static int FUsbMscGetCsw(FUsbEndpoint *ep, FUsbMscCsw *csw)
  250. {
  251. FUsbHc *ctrlr = ep->dev->controller;
  252. int ret = ctrlr->bulk(ep, sizeof(FUsbMscCsw), (u8 *)csw, 1);
  253. /* Some broken sticks send a zero-length packet at the end of their data
  254. transfer which would show up here. Skip it to get the actual CSW. */
  255. if (ret == 0)
  256. ret = ctrlr->bulk(ep, sizeof(FUsbMscCsw), (u8 *)csw, 1);
  257. if (ret < 0)
  258. {
  259. FUsbClearStall(ep);
  260. ret = ctrlr->bulk(ep, sizeof(FUsbMscCsw), (u8 *)csw, 1);
  261. if (ret < 0)
  262. return FUsbMscResetTransport(ep->dev);
  263. }
  264. if (ret != sizeof(FUsbMscCsw) || csw->dCSWTag != tag ||
  265. csw->dCSWSignature != csw_signature)
  266. {
  267. FUSB_INFO("MSC: received malformed CSW ");
  268. return FUsbMscResetTransport(ep->dev);
  269. }
  270. return MSC_COMMAND_OK;
  271. }
  272. static int FUsbMscExecCmd(FUsbDev *dev, FUsbMassStorageDirection dir, const u8 *cb, int cblen,
  273. u8 *buf, int buflen, int residue_ok)
  274. {
  275. FUsbMscCbw cbw;
  276. FUsbMscCsw csw;
  277. int always_succeed = 0;
  278. if ((cb[0] == 0x1b) && (cb[4] == 1)) /* check if it is Bulk-Only Mass Storage Reset request with reques type 00100001b */
  279. {
  280. /* start command, always succeed */
  281. always_succeed = 1;
  282. }
  283. FUsbMscWrapCbw(&cbw, buflen, dir, cb, cblen, MSC_INST(dev)->lun);
  284. if (dev->controller->bulk(MSC_INST(dev)->bulk_out, sizeof(cbw), (u8 *)&cbw, 0) < 0)
  285. {
  286. return FUsbMscResetTransport(dev);
  287. }
  288. if (buflen > 0)
  289. {
  290. if (dir == FUSB_DIR_DATA_IN)
  291. {
  292. if (dev->controller->bulk(MSC_INST(dev)->bulk_in, buflen, buf, 0) < 0)
  293. FUsbClearStall(MSC_INST(dev)->bulk_in);
  294. }
  295. else
  296. {
  297. if (dev->controller->bulk(MSC_INST(dev)->bulk_out, buflen, buf, 0) < 0)
  298. FUsbClearStall(MSC_INST(dev)->bulk_out);
  299. }
  300. }
  301. int ret = FUsbMscGetCsw(MSC_INST(dev)->bulk_in, &csw);
  302. if (ret)
  303. {
  304. return ret;
  305. }
  306. else if (always_succeed == 1)
  307. {
  308. /* return success, regardless of message */
  309. return MSC_COMMAND_OK;
  310. }
  311. else if (csw.bCSWStatus == 2)
  312. {
  313. /* phase error, reset transport */
  314. return FUsbMscResetTransport(dev);
  315. }
  316. else if (csw.bCSWStatus == 0)
  317. {
  318. if ((csw.dCSWDataResidue == 0) || residue_ok)
  319. /* no error, exit */
  320. return MSC_COMMAND_OK;
  321. else
  322. /* missed some bytes */
  323. return MSC_COMMAND_FAIL;
  324. }
  325. else
  326. {
  327. if (cb[0] == 0x03)
  328. /* requesting sense failed, that's bad */
  329. return MSC_COMMAND_FAIL;
  330. else if (cb[0] == 0)
  331. /* If command was TEST UNIT READY determine if the
  332. * device is of removable type indicating no media
  333. * found. */
  334. return FUsbMscRequestNoMedia(dev);
  335. /* error "check condition" or reserved error */
  336. ret = FUsbMscRequestSense(dev);
  337. /* return fail or the status of FUsbMscRequestSense if it's worse */
  338. return ret ? ret : MSC_COMMAND_FAIL;
  339. }
  340. }
  341. typedef struct
  342. {
  343. unsigned char command; /* 0 */
  344. unsigned char res1; /* 1 */
  345. unsigned int block; /* 2-5 */
  346. unsigned char res2; /* 6 */
  347. unsigned short numblocks; /* 7-8 */
  348. unsigned char control; /* 9 - the block is 10 bytes long */
  349. } __attribute__((packed)) FUsbMscCmdBlk;
  350. typedef struct
  351. {
  352. unsigned char command; /* 0 */
  353. unsigned char res1; /* 1 */
  354. unsigned char res2; /* 2 */
  355. unsigned char res3; /* 3 */
  356. union
  357. {
  358. /* 4 */
  359. struct
  360. {
  361. unsigned long start : 1; /* for START STOP UNIT */
  362. unsigned long : 7;
  363. };
  364. unsigned char length; /* for REQUEST SENSE */
  365. };
  366. unsigned char control; /* 5 */
  367. } __attribute__((packed)) FUsbMscCmdBlk6;
  368. /**
  369. * Like FUsbMscRwBlks, but for soft-sectors of 512b size. Converts the
  370. * start and count from 512b units.
  371. * Start and count must be aligned so that they match the native
  372. * sector size.
  373. *
  374. */
  375. /**
  376. * @name: FUsbMscRwBlk512
  377. * @msg: 读写USB大容量存储设备,以512字节为一块
  378. * @param dev device to access
  379. * @param start first sector to access
  380. * @param n number of sectors to access
  381. * @param dir direction of access: FUSB_DIR_DATA_IN == read, FUSB_DIR_DATA_OUT == write
  382. * @param buf buffer to read into or write from. Must be at least n*512 bytes
  383. * @return 0 on success, 1 on failure
  384. */
  385. int FUsbMscRwBlk512(FUsbDev *dev, int start, int n,
  386. FUsbMassStorageDirection dir, u8 *buf)
  387. {
  388. int blocksize_divider = MSC_INST(dev)->blocksize / 512;
  389. return FUsbMscRwBlks(dev, start / blocksize_divider,
  390. n / blocksize_divider, dir, buf);
  391. }
  392. /**
  393. * Reads or writes a number of sequential blocks on a USB storage device.
  394. * As it uses the READ(10) SCSI-2 command, it's limited to storage devices
  395. * of at most 2TB. It assumes sectors of 512 bytes.
  396. *
  397. * @param dev device to access
  398. * @param start first sector to access
  399. * @param n number of sectors to access
  400. * @param dir direction of access: FUSB_DIR_DATA_IN == read, FUSB_DIR_DATA_OUT == write
  401. * @param buf buffer to read into or write from. Must be at least n*sectorsize bytes
  402. * @return 0 on success, 1 on failure
  403. */
  404. static int FUsbMscRwChunk(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf)
  405. {
  406. FUsbMscCmdBlk cb;
  407. memset(&cb, 0, sizeof(cb));
  408. if (dir == FUSB_DIR_DATA_IN)
  409. {
  410. /* read */
  411. cb.command = 0x28;
  412. }
  413. else
  414. {
  415. /* write */
  416. cb.command = 0x2a;
  417. }
  418. cb.block = htonl(start);
  419. cb.numblocks = htons(n);
  420. return FUsbMscExecCmd(dev, dir, (u8 *)&cb, sizeof(cb), buf,
  421. n * MSC_INST(dev)->blocksize, 0) != MSC_COMMAND_OK
  422. ? 1
  423. : 0;
  424. }
  425. /**
  426. * Reads or writes a number of sequential blocks on a USB storage device
  427. * that is split into MAX_CHUNK_BYTES size requests.
  428. *
  429. * As it uses the READ(10) SCSI-2 command, it's limited to storage devices
  430. * of at most 2TB. It assumes sectors of 512 bytes.
  431. *
  432. * @param dev device to access
  433. * @param start first sector to access
  434. * @param n number of sectors to access
  435. * @param dir direction of access: FUSB_DIR_DATA_IN == read,
  436. * FUSB_DIR_DATA_OUT == write
  437. * @param buf buffer to read into or write from.
  438. * Must be at least n*sectorsize bytes
  439. * @return 0 on success, 1 on failure
  440. */
  441. static int FUsbMscRwBlks(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf)
  442. {
  443. int chunk_size = MAX_CHUNK_BYTES / MSC_INST(dev)->blocksize;
  444. int chunk;
  445. /* Read as many full chunks as needed. */
  446. for (chunk = 0; chunk < (n / chunk_size); chunk++)
  447. {
  448. if (FUsbMscRwChunk(dev, start + (chunk * chunk_size),
  449. chunk_size, dir,
  450. buf + (chunk * MAX_CHUNK_BYTES)) != MSC_COMMAND_OK)
  451. return 1;
  452. }
  453. /* Read any remaining partial chunk at the end. */
  454. if (n % chunk_size)
  455. {
  456. if (FUsbMscRwChunk(dev, start + (chunk * chunk_size),
  457. n % chunk_size, dir,
  458. buf + (chunk * MAX_CHUNK_BYTES)) != MSC_COMMAND_OK)
  459. return 1;
  460. }
  461. return 0;
  462. }
  463. /* Only request it, we don't interpret it.
  464. On certain errors, that's necessary to get devices out of
  465. a special state called "Contingent Allegiance Condition" */
  466. static int FUsbMscRequestSense(FUsbDev *dev)
  467. {
  468. u8 buf[19];
  469. FUsbMscCmdBlk6 cb;
  470. memset(&cb, 0, sizeof(cb));
  471. cb.command = 0x3;
  472. cb.length = sizeof(buf);
  473. return FUsbMscExecCmd(dev, FUSB_DIR_DATA_IN, (u8 *)&cb,
  474. sizeof(cb), buf, sizeof(buf), 1);
  475. }
  476. static int FUsbMscRequestNoMedia(FUsbDev *dev)
  477. {
  478. u8 buf[19];
  479. int ret;
  480. FUsbMscCmdBlk6 cb;
  481. memset(&cb, 0, sizeof(cb));
  482. cb.command = 0x3;
  483. cb.length = sizeof(buf);
  484. ret = FUsbMscExecCmd(dev, FUSB_DIR_DATA_IN, (u8 *)&cb,
  485. sizeof(cb), buf, sizeof(buf), 1);
  486. if (ret)
  487. return ret;
  488. /* Check if sense key is set to NOT READY. */
  489. if ((buf[2] & 0xf) != 2)
  490. return MSC_COMMAND_FAIL;
  491. /* Check if additional sense code is 0x3a. */
  492. if (buf[12] != 0x3a)
  493. return MSC_COMMAND_FAIL;
  494. /* No media is present. Return MSC_COMMAND_OK while marking the disk
  495. * not ready. */
  496. FUSB_INFO("Empty media found. ");
  497. MSC_INST(dev)->ready = FUSB_MSC_NOT_READY;
  498. return MSC_COMMAND_OK;
  499. }
  500. static int FUsbMscCheckIfReady(FUsbDev *dev)
  501. {
  502. FUsbMscCmdBlk6 cb;
  503. memset(&cb, 0, sizeof(cb)); /* full initialization for T-U-R */
  504. /* Bulk-Only Mass Storage Reset, class-specific request */
  505. return FUsbMscExecCmd(dev, FUSB_DIR_DATA_OUT, (u8 *)&cb,
  506. sizeof(cb), 0, 0, 0);
  507. }
  508. static int FUsbMscSpinUp(FUsbDev *dev)
  509. {
  510. FUsbMscCmdBlk6 cb;
  511. memset(&cb, 0, sizeof(cb));
  512. cb.command = 0x1b;
  513. cb.start = 1;
  514. return FUsbMscExecCmd(dev, FUSB_DIR_DATA_OUT, (u8 *)&cb,
  515. sizeof(cb), 0, 0, 0);
  516. }
  517. static int FUsbMscReadCapcity(FUsbDev *dev)
  518. {
  519. FUsbMscCmdBlk cb;
  520. memset(&cb, 0, sizeof(cb));
  521. cb.command = 0x25; /* read capacity */
  522. u32 buf[2];
  523. FUSB_INFO("Reading capacity of mass storage device. ");
  524. int count = 0, ret;
  525. while (count++ < 20)
  526. {
  527. switch (ret = FUsbMscExecCmd(dev, FUSB_DIR_DATA_IN, (u8 *)&cb,
  528. sizeof(cb), (u8 *)buf, 8, 0))
  529. {
  530. case MSC_COMMAND_OK:
  531. break;
  532. case MSC_COMMAND_FAIL:
  533. continue;
  534. default: /* if it's worse return */
  535. return ret;
  536. }
  537. break;
  538. }
  539. if (count >= 20)
  540. {
  541. /* still not successful, assume 2tb in 512byte sectors, which is just the same garbage as any other number, but probably more usable. */
  542. FUSB_WARN(" assuming 2 TB with 512-byte sectors as READ CAPACITY didn't answer. ");
  543. MSC_INST(dev)->numblocks = 0xffffffff;
  544. MSC_INST(dev)->blocksize = 512;
  545. }
  546. else
  547. {
  548. MSC_INST(dev)->numblocks = ntohl(buf[0]) + 1;
  549. MSC_INST(dev)->blocksize = ntohl(buf[1]);
  550. }
  551. FUSB_INFO(" %d %d-byte sectors (%d MB) ", MSC_INST(dev)->numblocks,
  552. MSC_INST(dev)->blocksize,
  553. /* round down high block counts to avoid integer overflow */
  554. MSC_INST(dev)->numblocks > 1000000
  555. ? (MSC_INST(dev)->numblocks / 1000) * MSC_INST(dev)->blocksize / 1000
  556. : MSC_INST(dev)->numblocks * MSC_INST(dev)->blocksize / 1000 / 1000);
  557. return MSC_COMMAND_OK;
  558. }
  559. static int FUsbMscWaitReady(FUsbDev *dev)
  560. {
  561. int i;
  562. /* SCSI/ATA specs say we have to wait up to 30s, but most devices
  563. * are ready much sooner. Use a 5 sec timeout to better accommodate
  564. * devices which fail to respond. */
  565. const tick_t timeout_tick = 1000000;
  566. FError ret = FUSB_ERR_WAIT_TIMEOUT;
  567. FUSB_INFO(" Waiting for device to become ready...");
  568. /* Initially mark the device ready. */
  569. MSC_INST(dev)->ready = FUSB_MSC_READY;
  570. tick_t start_tick = FUsbMscStartTick();
  571. do
  572. {
  573. switch (FUsbMscCheckIfReady(dev))
  574. {
  575. case MSC_COMMAND_OK:
  576. break;
  577. case MSC_COMMAND_FAIL:
  578. fsleep_millisec(100);
  579. FUSB_INFO(".");
  580. continue;
  581. default:
  582. /* Device detached, return immediately */
  583. return FUSB_MSC_DETACHED;
  584. }
  585. break;
  586. }
  587. while (!FUsbMscTimeout(start_tick, timeout_tick));
  588. if (FUsbMscTimeout(start_tick, timeout_tick))
  589. {
  590. FUSB_INFO("timeout. Device not ready. ");
  591. MSC_INST(dev)->ready = FUSB_MSC_NOT_READY;
  592. }
  593. /* Don't bother spinning up the storage device if the device is not
  594. * ready. This can happen when empty card readers are present.
  595. * Polling will pick it back up if readiness changes. */
  596. if (!MSC_INST(dev)->ready)
  597. return MSC_INST(dev)->ready;
  598. for (i = 0; i < 30; i++)
  599. {
  600. FUSB_INFO(".");
  601. switch (FUsbMscSpinUp(dev))
  602. {
  603. case MSC_COMMAND_OK:
  604. FUSB_INFO(" OK.");
  605. break;
  606. case MSC_COMMAND_FAIL:
  607. fsleep_millisec(100);
  608. continue;
  609. default:
  610. /* Device detached, return immediately */
  611. return FUSB_MSC_DETACHED;
  612. }
  613. break;
  614. }
  615. if (FUsbMscReadCapcity(dev) == MSC_COMMAND_DETACHED)
  616. return FUSB_MSC_DETACHED;
  617. return MSC_INST(dev)->ready;
  618. }
  619. /**
  620. * @name: FUsbMassStorageInit
  621. * @msg: USB大容量存储设备的初始化函数,由应用程序注册到FUSB框架中
  622. * @return {*}
  623. * @param {FUsbDev} *dev, USB大容量存储设备实例
  624. */
  625. void FUsbMassStorageInit(FUsbDev *dev)
  626. {
  627. FASSERT(dev && dev->configuration);
  628. FUsbConfigurationDescriptor *cd =
  629. (FUsbConfigurationDescriptor *)dev->configuration;
  630. FASSERT(FUSB_DESC_TYPE_CONFIG == cd->bDescriptorType);
  631. FUsbInterfaceDescriptor *interface =
  632. (FUsbInterfaceDescriptor *)(((char *)cd) + cd->bLength);
  633. FASSERT(FUSB_DESC_TYPE_INTERFACE == interface->bDescriptorType);
  634. if (FUSB_MASS_STORAGE_DEVICE != interface->bInterfaceClass)
  635. {
  636. FUSB_ERROR("Class %d not supported. ", interface->bInterfaceClass);
  637. return;
  638. }
  639. FUSB_INFO(" command set: %s protocol: %s ",
  640. FUsbMscSubClassString[interface->bInterfaceSubClass],
  641. FUsbMscProtocolStrings[interface->bInterfaceProtocol]);
  642. if (interface->bInterfaceProtocol != FUSB_MSC_PROTOCOL_BULK_ONLY)
  643. {
  644. FUSB_ERROR(" Protocol not supported. ");
  645. FUsbDetachDev(dev->controller, dev->address);
  646. return;
  647. }
  648. if ((interface->bInterfaceSubClass != FUSB_MSC_SUBCLASS_ATAPI_8020) && /* ATAPI 8020 */
  649. (interface->bInterfaceSubClass != FUSB_MSC_SUBCLASS_ATAPI_8070) && /* ATAPI 8070 */
  650. (interface->bInterfaceSubClass != FUSB_MSC_SUBCLASS_SCSI))
  651. {
  652. /* SCSI */
  653. /* Other protocols, such as ATAPI don't seem to be very popular. looks like ATAPI would be really easy to add, if necessary. */
  654. FUSB_ERROR(" Interface SubClass not supported. ");
  655. FUsbDetachDev(dev->controller, dev->address);
  656. return;
  657. }
  658. FUsbMassStorageForceInit(dev, 0);
  659. return;
  660. }
  661. /* Force a device to enumerate as MSC, without checking class/protocol types.
  662. It must still have a bulk endpoint pair and respond to MSC commands. */
  663. static void FUsbMassStorageForceInit(FUsbDev *dev, u32 quirks)
  664. {
  665. FASSERT(dev && dev->controller);
  666. int i;
  667. FUsb *instance = dev->controller->usb;
  668. FASSERT(instance);
  669. /* init .data before setting .destroy */
  670. dev->data = NULL;
  671. dev->destroy = FUsbMscDestory;
  672. dev->poll = FUsbMscPoll;
  673. FASSERT(NULL == dev->data);
  674. dev->data = FUSB_ALLOCATE(instance, sizeof(FUsbMassStorage), FUSB_DEFAULT_ALIGN);
  675. if (NULL == dev->data)
  676. {
  677. FUSB_ERROR("Not enough memory for USB MSC device. ");
  678. FASSERT(0);
  679. }
  680. MSC_INST(dev)->bulk_in = NULL;
  681. MSC_INST(dev)->bulk_out = NULL;
  682. MSC_INST(dev)->usbdisk_created = 0;
  683. MSC_INST(dev)->quirks = quirks;
  684. /* loop over all ep except ep0 to get bulk-in/bulk-out ep instance */
  685. for (i = 1; i <= dev->num_endp; i++)
  686. {
  687. if (dev->endpoints[i].endpoint == 0)
  688. continue;
  689. if (dev->endpoints[i].type != FUSB_BULK_EP)
  690. continue;
  691. if ((dev->endpoints[i].direction == FUSB_IN) && (MSC_INST(dev)->bulk_in == 0))
  692. MSC_INST(dev)->bulk_in = &dev->endpoints[i];
  693. if ((dev->endpoints[i].direction == FUSB_OUT) && (MSC_INST(dev)->bulk_out == 0))
  694. MSC_INST(dev)->bulk_out = &dev->endpoints[i];
  695. }
  696. /* check if non bulk-in ep */
  697. if (MSC_INST(dev)->bulk_in == NULL)
  698. {
  699. FUSB_ERROR("couldn't find bulk-in endpoint. ");
  700. FUsbDetachDev(dev->controller, dev->address);
  701. return;
  702. }
  703. /* check if non bulk-out ep */
  704. if (MSC_INST(dev)->bulk_out == NULL)
  705. {
  706. FUSB_ERROR("couldn't find bulk-out endpoint. ");
  707. FUsbDetachDev(dev->controller, dev->address);
  708. return;
  709. }
  710. FUSB_INFO("using endpoint %x as in, %x as out ",
  711. MSC_INST(dev)->bulk_in->endpoint,
  712. MSC_INST(dev)->bulk_out->endpoint);
  713. /* Some sticks need a little more time to get ready after SET_CONFIG. */
  714. fsleep_microsec(50);
  715. FUsbMscInitLuns(dev);
  716. FUSB_INFO(" has %d luns ", MSC_INST(dev)->num_luns);
  717. /* Test if msc is ready (nothing to do if it isn't). */
  718. if (FUsbMscWaitReady(dev) != FUSB_MSC_READY)
  719. return;
  720. /* Create the disk. */
  721. FUsbMscCreateDisk(dev);
  722. return;
  723. }
  724. static void FUsbMscPoll(FUsbDev *dev)
  725. {
  726. FUsbMassStorage *msc = MSC_INST(dev);
  727. int prev_ready = msc->ready;
  728. if (FUsbMscWaitReady(dev) == FUSB_MSC_DETACHED)
  729. return;
  730. if (!prev_ready && msc->ready)
  731. {
  732. FUSB_INFO("USB msc: not ready -> ready (lun %d) ", msc->lun);
  733. FUsbMscCreateDisk(dev);
  734. }
  735. else if (prev_ready && !msc->ready)
  736. {
  737. FUSB_INFO("USB msc: ready -> not ready (lun %d) ", msc->lun);
  738. FUsbMscRemoveDisk(dev);
  739. }
  740. else if (!prev_ready && !msc->ready)
  741. {
  742. u8 new_lun = (msc->lun + 1) % msc->num_luns;
  743. FUSB_INFO("USB msc: not ready (lun %d) -> lun %d ", msc->lun,
  744. new_lun);
  745. msc->lun = new_lun;
  746. }
  747. return;
  748. }