My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

UHS_BULK_STORAGE_INLINE.h 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. /* Copyright (C) 2015-2016 Andrew J. Kroll
  2. and
  3. Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  15. Contact information
  16. -------------------
  17. Circuits At Home, LTD
  18. Web : https://www.circuitsathome.com
  19. e-mail : support@circuitsathome.com
  20. */
  21. #if defined(LOAD_UHS_BULK_STORAGE) && defined(__UHS_BULK_STORAGE_H__) && !defined(UHS_BULK_STORAGE_LOADED)
  22. #define UHS_BULK_STORAGE_LOADED
  23. // uncomment to get 'printf' console debugging. NOT FOR UNO!
  24. //#define DEBUG_PRINTF_EXTRA_HUGE_UHS_BULK_STORAGE
  25. #if DEBUG_PRINTF_EXTRA_HUGE
  26. #ifdef DEBUG_PRINTF_EXTRA_HUGE_UHS_BULK_STORAGE
  27. #define BS_HOST_DEBUG(...) printf(__VA_ARGS__)
  28. #else
  29. #define BS_HOST_DEBUG(...) VOID0
  30. #endif
  31. #else
  32. #define BS_HOST_DEBUG(...) VOID0
  33. #endif
  34. ////////////////////////////////////////////////////////////////////////////////
  35. // Interface code
  36. ////////////////////////////////////////////////////////////////////////////////
  37. /**
  38. * Get the capacity of the media
  39. *
  40. * @param lun Logical Unit Number
  41. * @return media capacity
  42. */
  43. uint32_t UHS_NI UHS_Bulk_Storage::GetCapacity(uint8_t lun) {
  44. uint32_t v = 0LU;
  45. pUsb->DisablePoll();
  46. if(LUNOk[lun])
  47. v = CurrentCapacity[lun];
  48. pUsb->EnablePoll();
  49. return v;
  50. }
  51. /**
  52. * Get the sector (block) size used on the media
  53. *
  54. * @param lun Logical Unit Number
  55. * @return media sector size
  56. */
  57. uint16_t UHS_NI UHS_Bulk_Storage::GetSectorSize(uint8_t lun) {
  58. uint16_t v = 0U;
  59. pUsb->DisablePoll();
  60. if(LUNOk[lun])
  61. v = CurrentSectorSize[lun];
  62. pUsb->EnablePoll();
  63. return v;
  64. }
  65. /**
  66. * Test if LUN is ready for use
  67. *
  68. * @param lun Logical Unit Number
  69. * @return true if LUN is ready for use
  70. */
  71. bool UHS_NI UHS_Bulk_Storage::LUNIsGood(uint8_t lun) {
  72. bool v;
  73. pUsb->DisablePoll();
  74. v = LUNOk[lun];
  75. pUsb->EnablePoll();
  76. return v;
  77. }
  78. /**
  79. * Test if LUN is write protected
  80. *
  81. * @param lun Logical Unit Number
  82. * @return cached status of write protect switch
  83. */
  84. bool UHS_NI UHS_Bulk_Storage::WriteProtected(uint8_t lun) {
  85. bool v;
  86. pUsb->DisablePoll();
  87. v = WriteOk[lun];
  88. pUsb->EnablePoll();
  89. return v;
  90. }
  91. /**
  92. * Wrap and execute a SCSI CDB with length of 6
  93. *
  94. * @param cdb CDB to execute
  95. * @param buf_size Size of expected transaction
  96. * @param buf Buffer
  97. * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT
  98. * @return
  99. */
  100. uint8_t UHS_NI UHS_Bulk_Storage::SCSITransaction6(SCSI_CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) {
  101. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  102. pUsb->DisablePoll();
  103. // promote buf_size to 32bits.
  104. UHS_BULK_CommandBlockWrapper cbw = UHS_BULK_CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir);
  105. #if 0
  106. // Lets check the CBW here:
  107. printf("\r\n");
  108. printf("\r\n");
  109. uint8_t *dump = (uint8_t*)(&cbw);
  110. for(int i=0; i<(sizeof (UHS_BULK_CommandBlockWrapper)); i++) {
  111. printf("%02.2x ", *dump);
  112. dump++;
  113. }
  114. printf("\r\n");
  115. printf("\r\n");
  116. #endif
  117. uint8_t v = (HandleSCSIError(Transaction(&cbw, buf_size, buf)));
  118. pUsb->EnablePoll();
  119. return v;
  120. }
  121. /**
  122. * Wrap and execute a SCSI CDB with length of 10
  123. *
  124. * @param cdb CDB to execute
  125. * @param buf_size Size of expected transaction
  126. * @param buf Buffer
  127. * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT
  128. * @return
  129. */
  130. uint8_t UHS_NI UHS_Bulk_Storage::SCSITransaction10(SCSI_CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) {
  131. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  132. pUsb->DisablePoll();
  133. // promote buf_size to 32bits.
  134. UHS_BULK_CommandBlockWrapper cbw = UHS_BULK_CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir);
  135. //SetCurLUN(cdb->LUN);
  136. uint8_t v = (HandleSCSIError(Transaction(&cbw, buf_size, buf)));
  137. pUsb->EnablePoll();
  138. return v;
  139. }
  140. /**
  141. * Lock or Unlock the tray or door on device.
  142. * Caution: Some devices with buggy firmware will lock up.
  143. *
  144. * @param lun Logical Unit Number
  145. * @param lock 1 to lock, 0 to unlock
  146. * @return
  147. */
  148. uint8_t UHS_NI UHS_Bulk_Storage::LockMedia(uint8_t lun, uint8_t lock) {
  149. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  150. pUsb->DisablePoll();
  151. Notify(PSTR("\r\nLockMedia\r\n"), 0x80);
  152. Notify(PSTR("---------\r\n"), 0x80);
  153. SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_PREVENT_REMOVAL, lun, (uint8_t)0, lock);
  154. uint8_t v = SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)UHS_BULK_CMD_DIR_IN);
  155. pUsb->EnablePoll();
  156. return v;
  157. }
  158. /**
  159. * Media control, for spindle motor and media tray or door.
  160. * This includes CDROM, TAPE and anything with a media loader.
  161. *
  162. * @param lun Logical Unit Number
  163. * @param ctl 0x00 Stop Motor, 0x01 Start Motor, 0x02 Eject Media, 0x03 Load Media
  164. * @return 0 on success
  165. */
  166. uint8_t UHS_NI UHS_Bulk_Storage::MediaCTL(uint8_t lun, uint8_t ctl) {
  167. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  168. pUsb->DisablePoll();
  169. Notify(PSTR("\r\nMediaCTL\r\n"), 0x80);
  170. Notify(PSTR("-----------------\r\n"), 0x80);
  171. uint8_t rcode = UHS_BULK_ERR_UNIT_NOT_READY;
  172. if(bAddress) {
  173. SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_START_STOP_UNIT, lun, ctl & 0x03, 0);
  174. rcode = SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)UHS_BULK_CMD_DIR_OUT);
  175. } else {
  176. SetCurLUN(lun);
  177. }
  178. pUsb->EnablePoll();
  179. return rcode;
  180. }
  181. /**
  182. * Read data from media
  183. *
  184. * @param lun Logical Unit Number
  185. * @param addr LBA address on media to read
  186. * @param bsize size of a block (we should probably use the cached size)
  187. * @param blocks how many blocks to read
  188. * @param buf memory that is able to hold the requested data
  189. * @return 0 on success
  190. */
  191. uint8_t UHS_NI UHS_Bulk_Storage::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf) {
  192. if(!bAddress) return UHS_BULK_ERR_NO_MEDIA;
  193. uint8_t er = UHS_BULK_ERR_NO_MEDIA;
  194. pUsb->DisablePoll();
  195. if(LUNOk[lun]) {
  196. Notify(PSTR("\r\nRead LUN:\t"), 0x80);
  197. D_PrintHex<uint8_t > (lun, 0x90);
  198. Notify(PSTR("\r\nLBA:\t\t"), 0x90);
  199. D_PrintHex<uint32_t > (addr, 0x90);
  200. Notify(PSTR("\r\nblocks:\t\t"), 0x90);
  201. D_PrintHex<uint8_t > (blocks, 0x90);
  202. Notify(PSTR("\r\nblock size:\t"), 0x90);
  203. D_PrintHex<uint16_t > (bsize, 0x90);
  204. Notify(PSTR("\r\n---------\r\n"), 0x80);
  205. SCSI_CDB10_t cdb = SCSI_CDB10_t(SCSI_CMD_READ_10, lun, blocks, addr);
  206. again:
  207. er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), buf, (uint8_t)UHS_BULK_CMD_DIR_IN);
  208. if(er == UHS_BULK_ERR_STALL) {
  209. MediaCTL(lun, 1);
  210. if(UHS_SLEEP_MS(150)) {
  211. if(!TestUnitReady(lun)) goto again;
  212. }
  213. }
  214. }
  215. qNextPollTime = millis() + 100;
  216. pUsb->EnablePoll();
  217. return er;
  218. }
  219. /**
  220. * Write data to media
  221. *
  222. * @param lun Logical Unit Number
  223. * @param addr LBA address on media to write
  224. * @param bsize size of a block (we should probably use the cached size)
  225. * @param blocks how many blocks to write
  226. * @param buf memory that contains the data to write
  227. * @return 0 on success
  228. */
  229. uint8_t UHS_NI UHS_Bulk_Storage::Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t * buf) {
  230. if(!bAddress) return UHS_BULK_ERR_NO_MEDIA;
  231. uint8_t er = UHS_BULK_ERR_NO_MEDIA;
  232. pUsb->DisablePoll();
  233. if(LUNOk[lun]) {
  234. if(!WriteOk[lun]) {
  235. er = UHS_BULK_ERR_WRITE_PROTECTED;
  236. } else {
  237. Notify(PSTR("\r\nWrite LUN:\t"), 0x80);
  238. D_PrintHex<uint8_t > (lun, 0x90);
  239. Notify(PSTR("\r\nLBA:\t\t"), 0x90);
  240. D_PrintHex<uint32_t > (addr, 0x90);
  241. Notify(PSTR("\r\nblocks:\t\t"), 0x90);
  242. D_PrintHex<uint8_t > (blocks, 0x90);
  243. Notify(PSTR("\r\nblock size:\t"), 0x90);
  244. D_PrintHex<uint16_t > (bsize, 0x90);
  245. Notify(PSTR("\r\n---------\r\n"), 0x80);
  246. SCSI_CDB10_t cdb = SCSI_CDB10_t(SCSI_CMD_WRITE_10, lun, blocks, addr);
  247. again:
  248. er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), (void*)buf, (uint8_t)UHS_BULK_CMD_DIR_OUT);
  249. if(er == UHS_BULK_ERR_WRITE_STALL) {
  250. MediaCTL(lun, 1);
  251. if(UHS_SLEEP_MS(150)) {
  252. if(!TestUnitReady(lun)) goto again;
  253. }
  254. }
  255. }
  256. }
  257. qNextPollTime = millis() + 100;
  258. pUsb->EnablePoll();
  259. return er;
  260. }
  261. // End of user functions, the remaining code below is driver internals.
  262. // Only developer serviceable parts below!
  263. ////////////////////////////////////////////////////////////////////////////////
  264. // Main driver code
  265. ////////////////////////////////////////////////////////////////////////////////
  266. UHS_NI UHS_Bulk_Storage::UHS_Bulk_Storage(UHS_USB_HOST_BASE *p) {
  267. pUsb = p;
  268. dCBWTag = 0;
  269. if(pUsb) {
  270. DriverDefaults();
  271. pUsb->RegisterDeviceClass(this);
  272. // Serial.print("Bulk Register to USB Host @ 0x");
  273. // Serial.println((uint32_t)pUsb, HEX);
  274. // Serial.print("Bulk Register to USB Host Address Pool @ 0x");
  275. // Serial.println((uint32_t)pUsb->GetAddressPool(), HEX);
  276. }
  277. }
  278. /**
  279. * @param ei Enumeration information
  280. * @return true if this interface driver can handle this interface description
  281. */
  282. bool UHS_NI UHS_Bulk_Storage::OKtoEnumerate(ENUMERATION_INFO *ei) {
  283. BS_HOST_DEBUG("BulkOnly: checking numep %i, klass %2.2x, subklass %2.2x\r\n", ei->interface.numep, ei->klass, ei->subklass);
  284. BS_HOST_DEBUG("BulkOnly: checking protocol %2.2x, interface.klass %2.2x, interface.subklass %2.2x\r\n", ei->protocol, ei->interface.klass, ei->interface.subklass);
  285. BS_HOST_DEBUG("BulkOnly: checking interface.protocol %2.2x\r\n", ei->interface.protocol);
  286. //
  287. // TO-DO?
  288. // Check that we have 2 bulk endpoints, and one in each direction??
  289. // e.g. (ei->interface.numep > 1) && // two or more endpoints AND check types
  290. // This will work with proper hardware though.
  291. //
  292. return (
  293. ((ei->klass == UHS_USB_CLASS_MASS_STORAGE) || (ei->interface.klass == UHS_USB_CLASS_MASS_STORAGE)) && // mass storage class AND
  294. ((ei->subklass == UHS_BULK_SUBCLASS_SCSI) || (ei->interface.subklass == UHS_BULK_SUBCLASS_SCSI)) && // SCSI command set AND
  295. ((ei->protocol == UHS_STOR_PROTO_BBB) || (ei->interface.protocol == UHS_STOR_PROTO_BBB)) // Bulk Only transport
  296. );
  297. }
  298. /**
  299. * @param ei Enumeration information
  300. * @return 0 always
  301. */
  302. uint8_t UHS_NI UHS_Bulk_Storage::SetInterface(ENUMERATION_INFO *ei) {
  303. uint8_t index;
  304. bAddress = ei->address;
  305. BS_HOST_DEBUG("BS SetInterface\r\n");
  306. // Fill in the endpoint info structure
  307. for(uint8_t ep = 0; ep < ei->interface.numep; ep++) {
  308. BS_HOST_DEBUG("ep: 0x%2.2x bmAttributes: 0x%2.2x ", ep, ei->interface.epInfo[ep].bmAttributes);
  309. if(ei->interface.epInfo[ep].bmAttributes == USB_TRANSFER_TYPE_BULK) {
  310. index = ((ei->interface.epInfo[ep].bEndpointAddress & USB_TRANSFER_DIRECTION_IN) == USB_TRANSFER_DIRECTION_IN) ? epDataInIndex : epDataOutIndex;
  311. epInfo[index].epAddr = (ei->interface.epInfo[ep].bEndpointAddress & 0x0F);
  312. epInfo[index].maxPktSize = ei->interface.epInfo[ep].wMaxPacketSize;
  313. epInfo[index].epAttribs = 0;
  314. epInfo[index].bmNakPower = UHS_USB_NAK_MAX_POWER;
  315. epInfo[index].bmSndToggle = 0;
  316. epInfo[index].bmRcvToggle = 0;
  317. epInfo[index].bIface=ei->interface.bInterfaceNumber;
  318. BS_HOST_DEBUG("index: %i\r\n", index);
  319. }
  320. BS_HOST_DEBUG("\r\n");
  321. }
  322. bNumEP = 3;
  323. epInfo[0].epAddr = 0;
  324. epInfo[0].maxPktSize = ei->bMaxPacketSize0;
  325. epInfo[0].bmNakPower = UHS_USB_NAK_MAX_POWER;
  326. bIface = ei->interface.bInterfaceNumber;
  327. return 0;
  328. };
  329. /**
  330. * @return 0 for success
  331. */
  332. uint8_t UHS_NI UHS_Bulk_Storage::Start() {
  333. uint8_t rcode;
  334. // Serial.print("Bulk Start from USB Host @ 0x");
  335. // Serial.println((uint32_t)pUsb, HEX);
  336. // Serial.print("Bulk Start USB Host Address Pool @ 0x");
  337. // Serial.println((uint32_t)pUsb->GetAddressPool(), HEX);
  338. BS_HOST_DEBUG("BS Start, speed: %i\r\n", pUsb->GetAddressPool()->GetUsbDevicePtr(bAddress)->speed);
  339. BS_HOST_DEBUG("BS Start\r\n");
  340. rcode = pUsb->setEpInfoEntry(bAddress, bIface, 3, epInfo);
  341. // Serial.println(rcode,HEX);
  342. if(rcode) goto FailOnInit;
  343. // Do a 1 second delay before LUN query
  344. if(!UHS_SLEEP_MS(1000)) goto FailUnPlug;
  345. rcode = GetMaxLUN(&bMaxLUN);
  346. BS_HOST_DEBUG("GetMaxLUN 0x%2.2x\r\n", rcode);
  347. if(rcode) {
  348. goto FailGetMaxLUN;
  349. }
  350. if(bMaxLUN >= MASS_MAX_SUPPORTED_LUN) bMaxLUN = MASS_MAX_SUPPORTED_LUN - 1;
  351. BS_HOST_DEBUG("MaxLUN %u\r\n", bMaxLUN);
  352. //ErrorMessage<uint8_t > (PSTR("MaxLUN"), bMaxLUN);
  353. if(!UHS_SLEEP_MS(150)) goto FailUnPlug; // Delay a bit for slow firmware. (again)
  354. for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
  355. if(!UHS_SLEEP_MS(3)) goto FailUnPlug;
  356. SCSI_Inquiry_Response response;
  357. rcode = Inquiry(lun, sizeof (SCSI_Inquiry_Response), (uint8_t*) & response);
  358. BS_HOST_DEBUG("Inquiry 0x%2.2x 0x%2.2x\r\n", sizeof (SCSI_Inquiry_Response), rcode);
  359. if(rcode) {
  360. goto FailInquiry;
  361. #if 0
  362. } else {
  363. BS_HOST_DEBUG("LUN %i `", lun);
  364. uint8_t *buf = response.VendorID;
  365. for(int i = 0; i < 28; i++) BS_HOST_DEBUG("%c", buf[i]);
  366. BS_HOST_DEBUG("'\r\nQualifier %1.1X ", response.PeripheralQualifier);
  367. BS_HOST_DEBUG("Device type %2.2X ", response.DeviceType);
  368. BS_HOST_DEBUG("RMB %1.1X ", response.Removable);
  369. BS_HOST_DEBUG("SSCS %1.1X ", response.SCCS);
  370. uint8_t sv = response.Version;
  371. BS_HOST_DEBUG("SCSI version %2.2X\r\nDevice conforms to ", sv);
  372. switch(sv) {
  373. case 0:
  374. BS_HOST_DEBUG("No specific");
  375. break;
  376. case 1:
  377. BS_HOST_DEBUG("ANSI X3.131-1986 (ANSI 1)");
  378. break;
  379. case 2:
  380. BS_HOST_DEBUG("ANSI X3.131-1994 (ANSI 2)");
  381. break;
  382. case 3:
  383. BS_HOST_DEBUG("ANSI INCITS 301-1997 (SPC)");
  384. break;
  385. case 4:
  386. BS_HOST_DEBUG("ANSI INCITS 351-2001 (SPC-2)");
  387. break;
  388. case 5:
  389. BS_HOST_DEBUG("ANSI INCITS 408-2005 (SPC-4)");
  390. break;
  391. case 6:
  392. BS_HOST_DEBUG("T10/1731-D (SPC-4)");
  393. break;
  394. default:
  395. BS_HOST_DEBUG("unknown");
  396. }
  397. BS_HOST_DEBUG(" standards.\r\n");
  398. #endif
  399. }
  400. }
  401. for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
  402. if(!UHS_SLEEP_MS(3)) goto FailUnPlug;
  403. #ifndef USB_NO_TEST_UNIT_READY
  404. uint8_t tries = 0xF0;
  405. while((rcode = TestUnitReady(lun))) {
  406. BS_HOST_DEBUG("\r\nTry %2.2x TestUnitReady %2.2x\r\n", tries - 0xF0, rcode);
  407. if(rcode == 0x08) break; // break on no media, this is OK to do.
  408. if(rcode == UHS_BULK_ERR_DEVICE_DISCONNECTED) goto FailUnPlug;
  409. if(rcode == UHS_BULK_ERR_INVALID_CSW) goto Fail;
  410. if(rcode != UHS_BULK_ERR_MEDIA_CHANGED) goto Fail;
  411. if(!UHS_SLEEP_MS(2 * (tries + 1))) goto FailUnPlug;
  412. tries++;
  413. if(!tries) break;
  414. }
  415. #else
  416. // Don't wait for the LUN to become ready, as this will
  417. // trigger Marlin's watchdog timer
  418. rcode = -1;
  419. #endif
  420. if(!UHS_SLEEP_MS(3)) goto FailUnPlug;
  421. LockMedia(lun, 1);
  422. if(rcode == 0x08) {
  423. if(!UHS_SLEEP_MS(3)) goto FailUnPlug;
  424. if(MediaCTL(lun, 1) == UHS_BULK_ERR_DEVICE_DISCONNECTED) goto FailUnPlug; // I actually have a USB stick that needs this!
  425. }
  426. BS_HOST_DEBUG("\r\nTry %2.2x TestUnitReady %2.2x\r\n", tries - 0xF0, rcode);
  427. if(!rcode) {
  428. if(!UHS_SLEEP_MS(3)) goto FailUnPlug;
  429. BS_HOST_DEBUG("CheckLUN...\r\n");
  430. BS_HOST_DEBUG("%lu\r\n", millis()/1000);
  431. // Stalls on ***some*** devices, ***WHY***?! Device SAID it is READY!!
  432. LUNOk[lun] = CheckLUN(lun);
  433. BS_HOST_DEBUG("%lu\r\n", millis()/1000);
  434. if(!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun);
  435. if(!UHS_SLEEP_MS(1)) goto FailUnPlug;
  436. BS_HOST_DEBUG("Checked LUN...\r\n");
  437. } else {
  438. LUNOk[lun] = false;
  439. }
  440. }
  441. rcode = OnStart();
  442. if(rcode) goto FailOnInit;
  443. #ifdef DEBUG_USB_HOST
  444. USBTRACE("BS configured\r\n\r\n");
  445. #endif
  446. qNextPollTime = millis() + 100;
  447. bPollEnable = true;
  448. return 0;
  449. FailUnPlug:
  450. rcode = UHS_BULK_ERR_DEVICE_DISCONNECTED;
  451. goto Fail;
  452. FailOnInit:
  453. #ifdef DEBUG_USB_HOST
  454. USBTRACE("OnStart:");
  455. goto Fail;
  456. #endif
  457. FailGetMaxLUN:
  458. #ifdef DEBUG_USB_HOST
  459. USBTRACE("GetMaxLUN:");
  460. goto Fail;
  461. #endif
  462. FailInquiry:
  463. #ifdef DEBUG_USB_HOST
  464. USBTRACE("Inquiry:");
  465. #endif
  466. Fail:
  467. #ifdef DEBUG_USB_HOST
  468. NotifyFail(rcode);
  469. #endif
  470. Release();
  471. return rcode;
  472. }
  473. // Base class definition of Release() used. See UHS_USBInterface class definition for details
  474. /**
  475. * For driver use only.
  476. *
  477. * @return
  478. */
  479. //void UHS_NI UHS_Bulk_Storage::Release() {
  480. // pUsb->DisablePoll();
  481. // OnRelease();
  482. // DriverDefaults();
  483. // pUsb->EnablePoll();
  484. // return;
  485. //}
  486. /**
  487. * For driver use only.
  488. *
  489. * @param lun Logical Unit Number
  490. * @return true if LUN is ready for use.
  491. */
  492. bool UHS_NI UHS_Bulk_Storage::CheckLUN(uint8_t lun) {
  493. uint8_t rcode;
  494. SCSI_Capacity capacity;
  495. for(uint8_t i = 0; i < 8; i++) capacity.data[i] = 0;
  496. rcode = ReadCapacity10(lun, (uint8_t*)capacity.data);
  497. if(rcode) {
  498. BS_HOST_DEBUG(">>>>>>>>>>>>>>>>ReadCapacity returned %i\r\n", rcode);
  499. return false;
  500. }
  501. #ifdef DEBUG_USB_HOST
  502. ErrorMessage<uint8_t > (PSTR(">>>>>>>>>>>>>>>>CAPACITY OK ON LUN"), lun);
  503. for(uint8_t i = 0; i < 8 /*sizeof (Capacity)*/; i++)
  504. D_PrintHex<uint8_t > (capacity.data[i], 0x80);
  505. Notify(PSTR("\r\n\r\n"), 0x80);
  506. #endif
  507. // Only 512/1024/2048/4096 are valid values!
  508. uint32_t c = UHS_BYTES_TO_UINT32(capacity.data[4], capacity.data[5], capacity.data[6], capacity.data[7]);
  509. if(c != 0x0200LU && c != 0x0400LU && c != 0x0800LU && c != 0x1000LU) {
  510. return false;
  511. }
  512. // Store capacity information.
  513. CurrentSectorSize[lun] = (uint16_t)(c); // & 0xFFFF);
  514. CurrentCapacity[lun] = UHS_BYTES_TO_UINT32(capacity.data[0], capacity.data[1], capacity.data[2], capacity.data[3]) + 1;
  515. if(CurrentCapacity[lun] == /*0xffffffffLU */ 0x01LU || CurrentCapacity[lun] == 0x00LU) {
  516. // Buggy firmware will report 0xFFFFFFFF or 0 for no media
  517. #ifdef DEBUG_USB_HOST
  518. if(CurrentCapacity[lun])
  519. ErrorMessage<uint8_t > (PSTR(">>>>>>>>>>>>>>>>BUGGY FIRMWARE. CAPACITY FAIL ON LUN"), lun);
  520. #endif
  521. return false;
  522. }
  523. if(!UHS_SLEEP_MS(20)) return false;
  524. #ifndef SKIP_PAGE3F
  525. Page3F(lun);
  526. #endif
  527. if(!TestUnitReady(lun)) return true;
  528. return false;
  529. }
  530. /**
  531. * For driver use only.
  532. *
  533. * Scan for media change on all LUNs
  534. */
  535. void UHS_NI UHS_Bulk_Storage::CheckMedia() {
  536. if(!bAddress) return;
  537. for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
  538. if(TestUnitReady(lun)) {
  539. LUNOk[lun] = false;
  540. continue;
  541. }
  542. if(!LUNOk[lun])
  543. LUNOk[lun] = CheckLUN(lun);
  544. }
  545. #if 0
  546. BS_HOST_DEBUG("}}}}}}}}}}}}}}}}STATUS ");
  547. for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
  548. if(LUNOk[lun])
  549. BS_HOST_DEBUG("#");
  550. else BS_HOST_DEBUG(".");
  551. }
  552. BS_HOST_DEBUG("\r\n");
  553. #endif
  554. OnPoll();
  555. qNextPollTime = millis() + 100;
  556. }
  557. /**
  558. * For driver use only.
  559. */
  560. void UHS_NI UHS_Bulk_Storage::Poll() {
  561. if((long)(millis() - qNextPollTime) >= 0L) {
  562. CheckMedia();
  563. }
  564. return;
  565. }
  566. ////////////////////////////////////////////////////////////////////////////////
  567. // SCSI code
  568. ////////////////////////////////////////////////////////////////////////////////
  569. /**
  570. * For driver use only.
  571. *
  572. * @param plun
  573. * @return
  574. */
  575. uint8_t UHS_NI UHS_Bulk_Storage::GetMaxLUN(uint8_t *plun) {
  576. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  577. uint8_t ret = pUsb->ctrlReq(bAddress, mkSETUP_PKT16(UHS_BULK_bmREQ_IN, UHS_BULK_REQ_GET_MAX_LUN, 0x0000U, bIface, 1), 1, plun);
  578. if(ret == UHS_HOST_ERROR_STALL) {
  579. *plun = 0;
  580. Notify(PSTR("\r\nGetMaxLUN Stalled\r\n"), 0x80);
  581. }
  582. return 0;
  583. }
  584. /**
  585. * For driver use only. Used during Driver Start
  586. *
  587. * @param lun Logical Unit Number
  588. * @param bsize
  589. * @param buf
  590. * @return
  591. */
  592. uint8_t UHS_NI UHS_Bulk_Storage::Inquiry(uint8_t lun, uint16_t bsize, uint8_t *buf) {
  593. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  594. Notify(PSTR("\r\nInquiry\r\n"), 0x80);
  595. Notify(PSTR("---------\r\n"), 0x80);
  596. SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_INQUIRY, lun, 0LU, (uint8_t)bsize, 0);
  597. uint8_t rc = SCSITransaction6(&cdb, bsize, buf, (uint8_t)UHS_BULK_CMD_DIR_IN);
  598. return rc;
  599. }
  600. /**
  601. * For driver use only.
  602. *
  603. * @param lun Logical Unit Number
  604. * @return
  605. */
  606. uint8_t UHS_NI UHS_Bulk_Storage::TestUnitReady(uint8_t lun) {
  607. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  608. //SetCurLUN(lun);
  609. if(!bAddress)
  610. return UHS_BULK_ERR_UNIT_NOT_READY;
  611. Notify(PSTR("\r\nTestUnitReady\r\n"), 0x80);
  612. Notify(PSTR("-----------------\r\n"), 0x80);
  613. SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_TEST_UNIT_READY, lun, (uint8_t)0, 0);
  614. return SCSITransaction6(&cdb, 0, NULL, (uint8_t)UHS_BULK_CMD_DIR_IN);
  615. }
  616. /**
  617. * For driver use only.
  618. *
  619. * @param lun Logical Unit Number
  620. * @param pc
  621. * @param page
  622. * @param subpage
  623. * @param len
  624. * @param pbuf
  625. * @return
  626. */
  627. uint8_t UHS_NI UHS_Bulk_Storage::ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t * pbuf) {
  628. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  629. Notify(PSTR("\r\rModeSense\r\n"), 0x80);
  630. Notify(PSTR("------------\r\n"), 0x80);
  631. SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_MODE_SENSE_6, lun, (uint32_t)((((pc << 6) | page) << 8) | subpage), len, 0);
  632. return SCSITransaction6(&cdb, len, pbuf, (uint8_t)UHS_BULK_CMD_DIR_IN);
  633. }
  634. /**
  635. * For driver use only.
  636. *
  637. * @param lun Logical Unit Number
  638. * @param bsize
  639. * @param buf
  640. * @return
  641. */
  642. uint8_t UHS_NI UHS_Bulk_Storage::ReadCapacity10(uint8_t lun, uint8_t *buf) {
  643. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  644. Notify(PSTR("\r\nReadCapacity\r\n"), 0x80);
  645. Notify(PSTR("---------------\r\n"), 0x80);
  646. SCSI_CDB10_t cdb = SCSI_CDB10_t(SCSI_CMD_READ_CAPACITY_10, lun);
  647. return SCSITransaction10(&cdb, 8, buf, (uint8_t)UHS_BULK_CMD_DIR_IN);
  648. }
  649. /**
  650. * For driver use only.
  651. *
  652. * Page 3F contains write protect status.
  653. *
  654. * @param lun Logical Unit Number to test.
  655. * @return Write protect switch status.
  656. */
  657. uint8_t UHS_NI UHS_Bulk_Storage::Page3F(uint8_t lun) {
  658. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  659. uint8_t buf[192];
  660. for(int i = 0; i < 192; i++) {
  661. buf[i] = 0x00;
  662. }
  663. WriteOk[lun] = true;
  664. uint8_t rc = ModeSense6(lun, 0, 0x3F, 0, 192, buf);
  665. if(!rc) {
  666. WriteOk[lun] = ((buf[2] & 0x80) == 0);
  667. #ifdef DEBUG_USB_HOST
  668. Notify(PSTR("Mode Sense: "), 0x80);
  669. for(int i = 0; i < 4; i++) {
  670. D_PrintHex<uint8_t > (buf[i], 0x80);
  671. Notify(PSTR(" "), 0x80);
  672. }
  673. Notify(PSTR("\r\n"), 0x80);
  674. #endif
  675. }
  676. return rc;
  677. }
  678. /**
  679. * For driver use only.
  680. *
  681. * @param lun Logical Unit Number
  682. * @param size
  683. * @param buf
  684. * @return
  685. */
  686. uint8_t UHS_NI UHS_Bulk_Storage::RequestSense(uint8_t lun, uint16_t size, uint8_t *buf) {
  687. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  688. pUsb->DisablePoll();
  689. Notify(PSTR("\r\nRequestSense\r\n"), 0x80);
  690. Notify(PSTR("----------------\r\n"), 0x80);
  691. SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_REQUEST_SENSE, lun, 0LU, (uint8_t)size, 0);
  692. UHS_BULK_CommandBlockWrapper cbw = UHS_BULK_CommandBlockWrapper(++dCBWTag, (uint32_t)size, &cdb, (uint8_t)UHS_BULK_CMD_DIR_IN);
  693. uint8_t v = Transaction(&cbw, size, buf);
  694. pUsb->EnablePoll();
  695. return v;
  696. }
  697. ////////////////////////////////////////////////////////////////////////////////
  698. // USB code
  699. ////////////////////////////////////////////////////////////////////////////////
  700. /**
  701. * For driver use only.
  702. *
  703. * @param index
  704. * @return
  705. */
  706. uint8_t UHS_NI UHS_Bulk_Storage::ClearEpHalt(uint8_t index) {
  707. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  708. uint8_t ret = 0;
  709. if(index != 0) {
  710. uint8_t ep = (index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr;
  711. do {
  712. ret = pUsb->EPClearHalt(bAddress, ep);
  713. if(!UHS_SLEEP_MS(6)) break;
  714. } while(ret == 0x01);
  715. if(ret) {
  716. ErrorMessage<uint8_t > (PSTR("ClearEpHalt"), ret);
  717. ErrorMessage<uint8_t > (PSTR("EP"), ep);
  718. epInfo[index].bmSndToggle = 0;
  719. epInfo[index].bmRcvToggle = 0;
  720. return ret;
  721. } else {
  722. epInfo[index].bmSndToggle = 0;
  723. epInfo[index].bmRcvToggle = 0;
  724. }
  725. }
  726. return ret;
  727. }
  728. /**
  729. * For driver use only.
  730. */
  731. void UHS_NI UHS_Bulk_Storage::Reset() {
  732. if(!bAddress) return;
  733. while(pUsb->ctrlReq(bAddress, mkSETUP_PKT16(UHS_BULK_bmREQ_OUT, UHS_BULK_REQ_BOMSR, 0x0000U, bIface, 0), 0, NULL) == 0x01) {
  734. if(!UHS_SLEEP_MS(6)) break;
  735. }
  736. if(!bAddress) return;
  737. UHS_SLEEP_MS(2500);
  738. }
  739. /**
  740. * For driver use only.
  741. *
  742. * @return 0 if successful
  743. */
  744. uint8_t UHS_NI UHS_Bulk_Storage::ResetRecovery() {
  745. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  746. Notify(PSTR("\r\nResetRecovery\r\n"), 0x80);
  747. Notify(PSTR("-----------------\r\n"), 0x80);
  748. qNextPollTime = millis() + 90000;
  749. uint8_t bLastUsbError = UHS_HOST_ERROR_UNPLUGGED;
  750. if(UHS_SLEEP_MS(6)) {
  751. Reset();
  752. if(UHS_SLEEP_MS(6)) {
  753. bLastUsbError = ClearEpHalt(epDataInIndex);
  754. if(UHS_SLEEP_MS(6)) {
  755. bLastUsbError = ClearEpHalt(epDataOutIndex);
  756. UHS_SLEEP_MS(6);
  757. }
  758. }
  759. }
  760. return bLastUsbError;
  761. }
  762. /**
  763. * For driver use only.
  764. *
  765. * Clear all EP data and clear all LUN status
  766. */
  767. void UHS_NI UHS_Bulk_Storage::DriverDefaults() {
  768. pUsb->DeviceDefaults(MASS_MAX_ENDPOINTS, this);
  769. for(uint8_t i = 0; i < MASS_MAX_SUPPORTED_LUN; i++) {
  770. LUNOk[i] = false;
  771. WriteOk[i] = false;
  772. CurrentCapacity[i] = 0lu;
  773. CurrentSectorSize[i] = 0;
  774. }
  775. dCBWTag = 0;
  776. bMaxLUN = 0;
  777. bTheLUN = 0;
  778. }
  779. /**
  780. * For driver use only.
  781. *
  782. * @param pcsw
  783. * @param pcbw
  784. * @return
  785. */
  786. bool UHS_NI UHS_Bulk_Storage::IsValidCSW(UHS_BULK_CommandStatusWrapper *pcsw, UHS_BULK_CommandBlockWrapperBase *pcbw) {
  787. if(!bAddress) return false;
  788. if(pcsw->dCSWSignature != UHS_BULK_CSW_SIGNATURE) {
  789. Notify(PSTR("CSW:Sig error\r\n"), 0x80);
  790. return false;
  791. }
  792. if(pcsw->dCSWTag != pcbw->dCBWTag) {
  793. Notify(PSTR("CSW:Wrong tag\r\n"), 0x80);
  794. ErrorMessage<uint32_t > (PSTR("dCSWTag"), pcsw->dCSWTag);
  795. ErrorMessage<uint32_t > (PSTR("dCBWTag"), pcbw->dCBWTag);
  796. return false;
  797. }
  798. return true;
  799. }
  800. /**
  801. * For driver use only.
  802. *
  803. * @param error
  804. * @param index
  805. * @return
  806. */
  807. uint8_t UHS_NI UHS_Bulk_Storage::HandleUsbError(uint8_t error, uint8_t index) {
  808. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  809. uint8_t count = 3;
  810. while(error && count) {
  811. if(error != UHS_HOST_ERROR_NONE) {
  812. ErrorMessage<uint8_t > (PSTR("USB Error"), error);
  813. ErrorMessage<uint8_t > (PSTR("Index"), index);
  814. }
  815. switch(error) {
  816. // case UHS_HOST_ERROR_WRONGPID:
  817. case UHS_HOST_ERROR_NONE:
  818. return UHS_BULK_ERR_SUCCESS;
  819. case UHS_HOST_ERROR_BUSY:
  820. // SIE is busy, just hang out and try again.
  821. return UHS_BULK_ERR_UNIT_BUSY;
  822. case UHS_HOST_ERROR_NAK:
  823. return UHS_BULK_ERR_UNIT_BUSY;
  824. case UHS_HOST_ERROR_UNPLUGGED:
  825. case UHS_HOST_ERROR_TIMEOUT:
  826. case UHS_HOST_ERROR_JERR:
  827. return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  828. case UHS_HOST_ERROR_STALL:
  829. if(index == 0) return UHS_BULK_ERR_STALL;
  830. ClearEpHalt(index);
  831. if(index != epDataInIndex) return UHS_BULK_ERR_WRITE_STALL;
  832. return UHS_BULK_ERR_STALL;
  833. case UHS_HOST_ERROR_TOGERR:
  834. // Handle a very super rare corner case, where toggles become de-synched.
  835. // I have only ran into one device that has this firmware bug, and this is
  836. // the only clean way to get back into sync with the buggy device firmware.
  837. // --AJK
  838. if(bAddress && bConfNum) {
  839. error = pUsb->setConf(bAddress, bConfNum);
  840. if(error) break;
  841. }
  842. return UHS_BULK_ERR_SUCCESS;
  843. default:
  844. ErrorMessage<uint8_t > (PSTR("\r\nUSB"), error);
  845. return UHS_BULK_ERR_GENERAL_USB_ERROR;
  846. }
  847. count--;
  848. } // while
  849. return ((error && !count) ? UHS_BULK_ERR_GENERAL_USB_ERROR : UHS_BULK_ERR_SUCCESS);
  850. }
  851. /**
  852. * For driver use only.
  853. *
  854. * @param pcbw
  855. * @param buf_size
  856. * @param buf
  857. * @param flags
  858. * @return
  859. */
  860. uint8_t UHS_NI UHS_Bulk_Storage::Transaction(UHS_BULK_CommandBlockWrapper *pcbw, uint16_t buf_size, void *buf) {
  861. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  862. uint16_t bytes = buf_size;
  863. bool write = (pcbw->bmCBWFlags & UHS_BULK_CMD_DIR_IN) != UHS_BULK_CMD_DIR_IN;
  864. uint8_t ret = 0;
  865. uint8_t usberr;
  866. UHS_BULK_CommandStatusWrapper csw; // up here, we allocate ahead to save cpu cycles.
  867. SetCurLUN(pcbw->bmCBWLUN);
  868. ErrorMessage<uint32_t > (PSTR("CBW.dCBWTag"), pcbw->dCBWTag);
  869. while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (UHS_BULK_CommandBlockWrapper), (uint8_t*)pcbw)) == UHS_HOST_ERROR_BUSY) {
  870. if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  871. }
  872. ret = HandleUsbError(usberr, epDataOutIndex);
  873. if(ret) {
  874. ErrorMessage<uint8_t > (PSTR("============================ CBW"), ret);
  875. } else {
  876. if(bytes) {
  877. if(!write) {
  878. while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*)buf)) == UHS_HOST_ERROR_BUSY) {
  879. if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  880. }
  881. ret = HandleUsbError(usberr, epDataInIndex);
  882. } else {
  883. while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes, (uint8_t*)buf)) == UHS_HOST_ERROR_BUSY) {
  884. if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  885. }
  886. ret = HandleUsbError(usberr, epDataOutIndex);
  887. }
  888. if(ret) {
  889. ErrorMessage<uint8_t > (PSTR("============================ DAT"), ret);
  890. }
  891. }
  892. }
  893. {
  894. bytes = sizeof (UHS_BULK_CommandStatusWrapper);
  895. int tries = 2;
  896. while(tries--) {
  897. while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*) & csw)) == UHS_HOST_ERROR_BUSY) {
  898. if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  899. }
  900. if(!usberr) break;
  901. if(tries) {
  902. if(usberr == UHS_HOST_ERROR_STALL) {
  903. ResetRecovery();
  904. } else {
  905. ClearEpHalt(epDataInIndex);
  906. }
  907. }
  908. }
  909. if(!ret) {
  910. Notify(PSTR("CBW:\t\tOK\r\n"), 0x80);
  911. Notify(PSTR("Data Stage:\tOK\r\n"), 0x80);
  912. } else {
  913. // Throw away csw, IT IS NOT OF ANY USE.
  914. ResetRecovery();
  915. return ret;
  916. }
  917. ret = HandleUsbError(usberr, epDataInIndex);
  918. if(ret) {
  919. ErrorMessage<uint8_t > (PSTR("============================ CSW"), ret);
  920. }
  921. if(usberr == UHS_HOST_ERROR_NONE) {
  922. if(IsValidCSW(&csw, pcbw)) {
  923. //ErrorMessage<uint32_t > (PSTR("CSW.dCBWTag"), csw.dCSWTag);
  924. //ErrorMessage<uint8_t > (PSTR("bCSWStatus"), csw.bCSWStatus);
  925. //ErrorMessage<uint32_t > (PSTR("dCSWDataResidue"), csw.dCSWDataResidue);
  926. Notify(PSTR("CSW:\t\tOK\r\n\r\n"), 0x80);
  927. return csw.bCSWStatus;
  928. } else {
  929. // NOTE! Sometimes this is caused by the reported residue being wrong.
  930. // Get a different device. It isn't compliant, and should have never passed Q&A.
  931. // I own one... 05e3:0701 Genesys Logic, Inc. USB 2.0 IDE Adapter.
  932. // Other devices that exhibit this behavior exist in the wild too.
  933. // Be sure to check quirks in the Linux source code before reporting a bug. --xxxajk
  934. Notify(PSTR("Invalid CSW\r\n"), 0x80);
  935. Reset();
  936. ResetRecovery();
  937. return UHS_BULK_ERR_INVALID_CSW;
  938. }
  939. }
  940. }
  941. return ret;
  942. }
  943. /**
  944. * For driver use only.
  945. *
  946. * @param lun Logical Unit Number
  947. * @return
  948. */
  949. uint8_t UHS_NI UHS_Bulk_Storage::SetCurLUN(uint8_t lun) {
  950. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  951. if(lun > bMaxLUN)
  952. return UHS_BULK_ERR_INVALID_LUN;
  953. bTheLUN = lun;
  954. return UHS_BULK_ERR_SUCCESS;
  955. };
  956. /**
  957. * For driver use only.
  958. *
  959. * @param status
  960. * @return
  961. */
  962. uint8_t UHS_NI UHS_Bulk_Storage::HandleSCSIError(uint8_t status) {
  963. if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  964. uint8_t ret = 0;
  965. switch(status) {
  966. case 0: return UHS_BULK_ERR_SUCCESS;
  967. case 2:
  968. ErrorMessage<uint8_t > (PSTR("Phase Error"), status);
  969. ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN);
  970. ResetRecovery();
  971. return UHS_BULK_ERR_GENERAL_SCSI_ERROR;
  972. case 1:
  973. ErrorMessage<uint8_t > (PSTR("SCSI Error"), status);
  974. ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN);
  975. SCSI_Request_Sense_Response rsp;
  976. ret = RequestSense(bTheLUN, sizeof (SCSI_Request_Sense_Response), (uint8_t*) & rsp);
  977. if(ret) {
  978. if(ret == UHS_BULK_ERR_DEVICE_DISCONNECTED) return UHS_BULK_ERR_DEVICE_DISCONNECTED;
  979. return UHS_BULK_ERR_GENERAL_SCSI_ERROR;
  980. }
  981. #if ENABLE_UHS_DEBUGGING
  982. ErrorMessage<uint8_t > (PSTR("Response Code"), rsp.bResponseCode);
  983. if(rsp.bResponseCode & 0x80) {
  984. Notify(PSTR("Information field: "), 0x80);
  985. for(int i = 0; i < 4; i++) {
  986. D_PrintHex<uint8_t > (rsp.CmdSpecificInformation[i], 0x80);
  987. Notify(PSTR(" "), 0x80);
  988. }
  989. Notify(PSTR("\r\n"), 0x80);
  990. }
  991. ErrorMessage<uint8_t > (PSTR("Sense Key"), rsp.bmSenseKey);
  992. ErrorMessage<uint8_t > (PSTR("Add Sense Code"), rsp.bAdditionalSenseCode);
  993. ErrorMessage<uint8_t > (PSTR("Add Sense Qual"), rsp.bAdditionalSenseQualifier);
  994. #endif
  995. // warning, this is not testing ASQ, only SK and ASC.
  996. switch(rsp.bmSenseKey) {
  997. case SCSI_S_UNIT_ATTENTION:
  998. switch(rsp.bAdditionalSenseCode) {
  999. case SCSI_ASC_MEDIA_CHANGED:
  1000. return UHS_BULK_ERR_MEDIA_CHANGED;
  1001. default:
  1002. return UHS_BULK_ERR_UNIT_NOT_READY;
  1003. }
  1004. case SCSI_S_NOT_READY:
  1005. switch(rsp.bAdditionalSenseCode) {
  1006. case SCSI_ASC_MEDIUM_NOT_PRESENT:
  1007. return UHS_BULK_ERR_NO_MEDIA;
  1008. default:
  1009. return UHS_BULK_ERR_UNIT_NOT_READY;
  1010. }
  1011. case SCSI_S_ILLEGAL_REQUEST:
  1012. switch(rsp.bAdditionalSenseCode) {
  1013. case SCSI_ASC_LBA_OUT_OF_RANGE:
  1014. return UHS_BULK_ERR_BAD_LBA;
  1015. default:
  1016. return UHS_BULK_ERR_CMD_NOT_SUPPORTED;
  1017. }
  1018. default:
  1019. return UHS_BULK_ERR_GENERAL_SCSI_ERROR;
  1020. }
  1021. // case 4: return MASS_ERR_UNIT_BUSY; // Busy means retry later.
  1022. // case 0x05/0x14: we stalled out
  1023. // case 0x15/0x16: we naked out.
  1024. default:
  1025. ErrorMessage<uint8_t > (PSTR("Gen SCSI Err"), status);
  1026. ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN);
  1027. return status;
  1028. } // switch
  1029. }
  1030. ////////////////////////////////////////////////////////////////////////////////
  1031. // Debugging code
  1032. ////////////////////////////////////////////////////////////////////////////////
  1033. /**
  1034. * @param ep_ptr
  1035. */
  1036. void UHS_NI UHS_Bulk_Storage::PrintEndpointDescriptor(const USB_FD_ENDPOINT_DESCRIPTOR * ep_ptr) {
  1037. Notify(PSTR("Endpoint descriptor:"), 0x80);
  1038. Notify(PSTR("\r\nLength:\t\t"), 0x80);
  1039. D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
  1040. Notify(PSTR("\r\nType:\t\t"), 0x80);
  1041. D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
  1042. Notify(PSTR("\r\nAddress:\t"), 0x80);
  1043. D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
  1044. Notify(PSTR("\r\nAttributes:\t"), 0x80);
  1045. D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
  1046. Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
  1047. D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
  1048. Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
  1049. D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
  1050. Notify(PSTR("\r\n"), 0x80);
  1051. }
  1052. #else
  1053. #error "Never include UHS_BULK_STORAGE_INLINE.h, include UHS_host.h instead"
  1054. #endif