ZuluSCSI_platform_msc.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * Copyright (c) 2023-2024 zigzagjoe
  3. *
  4. * ZuluSCSI™ firmware is licensed under the GPL version 3 or any later version. 
  5. *
  6. * https://www.gnu.org/licenses/gpl-3.0.html
  7. * ----
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version. 
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. * GNU General Public License for more details. 
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  20. **/
  21. /* platform specific MSC routines */
  22. #ifdef PLATFORM_MASS_STORAGE
  23. #include <SdFat.h>
  24. #include <device/usbd.h>
  25. #include <hardware/gpio.h>
  26. #include "ZuluSCSI_platform.h"
  27. #include "ZuluSCSI_log.h"
  28. #include "ZuluSCSI_msc.h"
  29. #include "ZuluSCSI_msc_initiator.h"
  30. #include "ZuluSCSI_config.h"
  31. #include "ZuluSCSI_settings.h"
  32. #include <class/msc/msc.h>
  33. #include <class/msc/msc_device.h>
  34. #include <pico/mutex.h>
  35. extern mutex_t __usb_mutex;
  36. #if CFG_TUD_MSC_EP_BUFSIZE < SD_SECTOR_SIZE
  37. #error "CFG_TUD_MSC_EP_BUFSIZE is too small! It needs to be at least 512 (SD_SECTOR_SIZE)"
  38. #endif
  39. #define DIGITAL_PIN_CYW43_OFFSET 64
  40. // external global SD variable
  41. extern SdFs SD;
  42. static bool unitReady = false;
  43. static bool g_msc_lock; // To block re-entrant calls
  44. static bool g_msc_usb_mutex_held;
  45. void platform_msc_lock_set(bool block)
  46. {
  47. if (block)
  48. {
  49. if (g_msc_lock)
  50. {
  51. logmsg("Re-entrant MSC lock!");
  52. assert(false);
  53. }
  54. g_msc_usb_mutex_held = mutex_try_enter(&__usb_mutex, NULL); // Blocks USB IRQ if not already blocked
  55. g_msc_lock = true; // Blocks platform USB polling
  56. }
  57. else
  58. {
  59. if (!g_msc_lock)
  60. {
  61. logmsg("MSC lock released when not held!");
  62. assert(false);
  63. }
  64. g_msc_lock = false;
  65. if (g_msc_usb_mutex_held)
  66. {
  67. g_msc_usb_mutex_held = false;
  68. mutex_exit(&__usb_mutex);
  69. }
  70. }
  71. }
  72. bool platform_msc_lock_get()
  73. {
  74. return g_msc_lock;
  75. }
  76. struct MSCScopedLock {
  77. public:
  78. MSCScopedLock() { platform_msc_lock_set(true); }
  79. ~MSCScopedLock() { platform_msc_lock_set(false); }
  80. };
  81. /* return true if USB presence detected / eligble to enter CR mode */
  82. bool platform_sense_msc() {
  83. #if defined(ZULUSCSI_PICO) || defined(ZULUSCSI_PICO_2)
  84. // check if we're USB powered, if not, exit immediately
  85. // pin on the wireless module, see https://github.com/earlephilhower/arduino-pico/discussions/835
  86. // Update: from the above discussion the offset 32 has been changed to 64 to access CYW43 GPIO pins
  87. // since the addition of the RP2350 chips, now stored in the DIGITAL_PIN_CYW43_OFFSET define
  88. if (rp2040.isPicoW() && !digitalRead(DIGITAL_PIN_CYW43_OFFSET + 2))
  89. return false;
  90. if (!rp2040.isPicoW() && !digitalRead(24))
  91. return false;
  92. #endif
  93. logmsg("Waiting for USB enumeration to enter Card Reader mode.");
  94. // wait for up to a second to be enumerated
  95. uint32_t start = millis();
  96. bool timed_out = false;
  97. uint16_t usb_timeout = g_scsi_settings.getSystem()->usbMassStorageWaitPeriod;
  98. while (!tud_connected())
  99. {
  100. if ((uint32_t)(millis() - start) > usb_timeout)
  101. {
  102. logmsg("Waiting for USB enumeration timed out after ", usb_timeout, "ms.");
  103. logmsg("-- Try increasing 'USBMassStorageWaitPeriod' in the ", CONFIGFILE);
  104. timed_out = true;
  105. break;
  106. }
  107. delay(100);
  108. }
  109. if (!timed_out)
  110. dbgmsg("USB enumeration took ", (int)((uint32_t)(millis() - start)), "ms");
  111. // tud_connected returns True if just got out of Bus Reset and received the very first data from host
  112. // https://github.com/hathach/tinyusb/blob/master/src/device/usbd.h#L63
  113. return tud_connected();
  114. }
  115. /* return true if we should remain in card reader mode and perform periodic tasks */
  116. bool platform_run_msc() {
  117. return unitReady;
  118. }
  119. /* perform MSC class preinit tasks */
  120. void platform_enter_msc() {
  121. dbgmsg("USB MSC buffer size: ", CFG_TUD_MSC_EP_BUFSIZE);
  122. // MSC is ready for read/write
  123. // we don't need any prep, but the var is requried as the MSC callbacks are always active
  124. unitReady = true;
  125. }
  126. /* perform any cleanup tasks for the MSC-specific functionality */
  127. void platform_exit_msc() {
  128. unitReady = false;
  129. }
  130. /* TinyUSB mass storage callbacks follow */
  131. // usb framework checks this func exists for mass storage config. no code needed.
  132. void __USBInstallMassStorage() { }
  133. // Invoked when received SCSI_CMD_INQUIRY
  134. // fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively
  135. extern "C" void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8],
  136. uint8_t product_id[16], uint8_t product_rev[4]) {
  137. MSCScopedLock lock;
  138. if (g_msc_initiator) return init_msc_inquiry_cb(lun, vendor_id, product_id, product_rev);
  139. const char vid[] = "ZuluSCSI";
  140. const char pid[] = PLATFORM_PID;
  141. const char rev[] = "1.0";
  142. memcpy(vendor_id, vid, tu_min32(strlen(vid), 8));
  143. memcpy(product_id, pid, tu_min32(strlen(pid), 16));
  144. memcpy(product_rev, rev, tu_min32(strlen(rev), 4));
  145. }
  146. // max LUN supported
  147. // we only have the one SD card
  148. extern "C" uint8_t tud_msc_get_maxlun_cb(void)
  149. {
  150. MSCScopedLock lock;
  151. if (g_msc_initiator) return init_msc_get_maxlun_cb();
  152. return 1; // number of LUNs supported
  153. }
  154. // return writable status
  155. // on platform supporting write protect switch, could do that here.
  156. // otherwise this is not actually needed
  157. extern "C" bool tud_msc_is_writable_cb (uint8_t lun)
  158. {
  159. MSCScopedLock lock;
  160. if (g_msc_initiator) return init_msc_is_writable_cb(lun);
  161. (void) lun;
  162. return unitReady;
  163. }
  164. // see https://www.seagate.com/files/staticfiles/support/docs/manual/Interface%20manuals/100293068j.pdf pg 221
  165. extern "C" bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject)
  166. {
  167. MSCScopedLock lock;
  168. if (g_msc_initiator) return init_msc_start_stop_cb(lun, power_condition, start, load_eject);
  169. if (load_eject) {
  170. if (start) {
  171. // load disk storage
  172. // do nothing as we started "loaded"
  173. } else {
  174. unitReady = false;
  175. }
  176. }
  177. return true;
  178. }
  179. // return true if we are ready to service reads/writes
  180. extern "C" bool tud_msc_test_unit_ready_cb(uint8_t lun)
  181. {
  182. MSCScopedLock lock;
  183. if (g_msc_initiator) return init_msc_test_unit_ready_cb(lun);
  184. return unitReady;
  185. }
  186. // return size in blocks and block size
  187. extern "C" void tud_msc_capacity_cb(uint8_t lun, uint32_t *block_count,
  188. uint16_t *block_size)
  189. {
  190. MSCScopedLock lock;
  191. if (g_msc_initiator) return init_msc_capacity_cb(lun, block_count, block_size);
  192. *block_count = unitReady ? (SD.card()->sectorCount()) : 0;
  193. *block_size = SD_SECTOR_SIZE;
  194. }
  195. // Callback invoked when received an SCSI command not in built-in list (below) which have their own callbacks
  196. // - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE, READ10 and WRITE10
  197. extern "C" int32_t tud_msc_scsi_cb(uint8_t lun, const uint8_t scsi_cmd[16], void *buffer,
  198. uint16_t bufsize)
  199. {
  200. MSCScopedLock lock;
  201. if (g_msc_initiator) return init_msc_scsi_cb(lun, scsi_cmd, buffer, bufsize);
  202. const void *response = NULL;
  203. uint16_t resplen = 0;
  204. switch (scsi_cmd[0]) {
  205. case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
  206. // Host is about to read/write etc ... better not to disconnect disk
  207. resplen = 0;
  208. break;
  209. default:
  210. // Set Sense = Invalid Command Operation
  211. tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00);
  212. // negative means error -> tinyusb could stall and/or response with failed status
  213. resplen = -1;
  214. break;
  215. }
  216. // return len must not larger than bufsize
  217. if (resplen > bufsize) {
  218. resplen = bufsize;
  219. }
  220. // copy response to stack's buffer if any
  221. if (response && resplen) {
  222. memcpy(buffer, response, resplen);
  223. }
  224. return resplen;
  225. }
  226. // Callback invoked when received READ10 command.
  227. // Copy disk's data to buffer (up to bufsize) and return number of copied bytes (must be multiple of block size)
  228. extern "C" int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset,
  229. void* buffer, uint32_t bufsize)
  230. {
  231. MSCScopedLock lock;
  232. if (g_msc_initiator) return init_msc_read10_cb(lun, lba, offset, buffer, bufsize);
  233. bool rc = SD.card()->readSectors(lba, (uint8_t*) buffer, bufsize/SD_SECTOR_SIZE);
  234. // only blink fast on reads; writes will override this
  235. if (MSC_LEDMode == LED_SOLIDON)
  236. MSC_LEDMode = LED_BLINK_FAST;
  237. return rc ? bufsize : -1;
  238. }
  239. // Callback invoked when receive WRITE10 command.
  240. // Process data in buffer to disk's storage and return number of written bytes (must be multiple of block size)
  241. extern "C" int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset,
  242. uint8_t *buffer, uint32_t bufsize)
  243. {
  244. MSCScopedLock lock;
  245. if (g_msc_initiator) return init_msc_read10_cb(lun, lba, offset, buffer, bufsize);
  246. bool rc = SD.card()->writeSectors(lba, buffer, bufsize/SD_SECTOR_SIZE);
  247. // always slow blink
  248. MSC_LEDMode = LED_BLINK_SLOW;
  249. return rc ? bufsize : -1;
  250. }
  251. // Callback invoked when WRITE10 command is completed (status received and accepted by host).
  252. // used to flush any pending cache to storage
  253. extern "C" void tud_msc_write10_complete_cb(uint8_t lun)
  254. {
  255. MSCScopedLock lock;
  256. if (g_msc_initiator) return init_msc_write10_complete_cb(lun);
  257. }
  258. #endif