BlueSCSI.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. /*
  2. * BlueSCSI
  3. * Copyright (c) 2021 Eric Helgeson, Androda
  4. *
  5. * This file is free software: you may copy, redistribute and/or modify it
  6. * under the terms of the GNU General Public License as published by the
  7. * Free Software Foundation, either version 2 of the License, or (at your
  8. * option) any later version.
  9. *
  10. * This file is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see https://github.com/erichelgeson/bluescsi.
  17. *
  18. * This file incorporates work covered by the following copyright and
  19. * permission notice:
  20. *
  21. * Copyright (c) 2019 komatsu
  22. *
  23. * Permission to use, copy, modify, and/or distribute this software
  24. * for any purpose with or without fee is hereby granted, provided
  25. * that the above copyright notice and this permission notice appear
  26. * in all copies.
  27. *
  28. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  29. * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  30. * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  31. * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  32. * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  33. * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  34. * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  35. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  36. */
  37. #include <Arduino.h> // For Platform.IO
  38. #include <SdFat.h>
  39. #ifdef USE_STM32_DMA
  40. #warning "warning USE_STM32_DMA"
  41. #endif
  42. #define DEBUG 0 // 0:No debug information output
  43. // 1: Debug information output to USB Serial
  44. // 2: Debug information output to LOG.txt (slow)
  45. #define SCSI_SELECT 0 // 0 for STANDARD
  46. // 1 for SHARP X1turbo
  47. // 2 for NEC PC98
  48. #define READ_SPEED_OPTIMIZE 1 // Faster reads
  49. #define WRITE_SPEED_OPTIMIZE 1 // Speeding up writes
  50. // SCSI config
  51. #define NUM_SCSIID 7 // Maximum number of supported SCSI-IDs (The minimum is 0)
  52. #define NUM_SCSILUN 2 // Maximum number of LUNs supported (The minimum is 0)
  53. #define READ_PARITY_CHECK 0 // Perform read parity check (unverified)
  54. // HDD format
  55. #define MAX_BLOCKSIZE 2048 // Maximum BLOCK size
  56. // SDFAT
  57. #define SD1_CONFIG SdSpiConfig(PA4, DEDICATED_SPI, SD_SCK_MHZ(SPI_FULL_SPEED), &SPI)
  58. SdFs SD;
  59. #if DEBUG == 1
  60. #define LOG(XX) Serial.print(XX)
  61. #define LOGHEX(XX) Serial.print(XX, HEX)
  62. #define LOGN(XX) Serial.println(XX)
  63. #define LOGHEXN(XX) Serial.println(XX, HEX)
  64. #elif DEBUG == 2
  65. #define LOG(XX) LOG_FILE.print(XX); LOG_FILE.sync();
  66. #define LOGHEX(XX) LOG_FILE.print(XX, HEX); LOG_FILE.sync();
  67. #define LOGN(XX) LOG_FILE.println(XX); LOG_FILE.sync();
  68. #define LOGHEXN(XX) LOG_FILE.println(XX, HEX); LOG_FILE.sync();
  69. #else
  70. #define LOG(XX) //Serial.print(XX)
  71. #define LOGHEX(XX) //Serial.print(XX, HEX)
  72. #define LOGN(XX) //Serial.println(XX)
  73. #define LOGHEXN(XX) //Serial.println(XX, HEX)
  74. #endif
  75. #define active 1
  76. #define inactive 0
  77. #define high 0
  78. #define low 1
  79. #define isHigh(XX) ((XX) == high)
  80. #define isLow(XX) ((XX) != high)
  81. #define gpio_mode(pin,val) gpio_set_mode(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, val);
  82. #define gpio_write(pin,val) gpio_write_bit(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, val)
  83. #define gpio_read(pin) gpio_read_bit(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit)
  84. //#define DB0 PB8 // SCSI:DB0
  85. //#define DB1 PB9 // SCSI:DB1
  86. //#define DB2 PB10 // SCSI:DB2
  87. //#define DB3 PB11 // SCSI:DB3
  88. //#define DB4 PB12 // SCSI:DB4
  89. //#define DB5 PB13 // SCSI:DB5
  90. //#define DB6 PB14 // SCSI:DB6
  91. //#define DB7 PB15 // SCSI:DB7
  92. //#define DBP PB0 // SCSI:DBP
  93. #define ATN PA8 // SCSI:ATN
  94. #define BSY PA9 // SCSI:BSY
  95. #define ACK PA10 // SCSI:ACK
  96. #define RST PA15 // SCSI:RST
  97. #define MSG PB3 // SCSI:MSG
  98. #define SEL PB4 // SCSI:SEL
  99. #define CD PB5 // SCSI:C/D
  100. #define REQ PB6 // SCSI:REQ
  101. #define IO PB7 // SCSI:I/O
  102. #define LED2 PA0 // External LED
  103. #define SD_CS PA4 // SDCARD:CS
  104. #define LED PC13 // LED
  105. // GPIO register port
  106. #define PAREG GPIOA->regs
  107. #define PBREG GPIOB->regs
  108. // LED control
  109. #define LED_ON() gpio_write(LED, high); gpio_write(LED2, low);
  110. #define LED_OFF() gpio_write(LED, low); gpio_write(LED2, high);
  111. // Virtual pin (Arduio compatibility is slow, so make it MCU-dependent)
  112. #define PA(BIT) (BIT)
  113. #define PB(BIT) (BIT+16)
  114. // Virtual pin decoding
  115. #define GPIOREG(VPIN) ((VPIN)>=16?PBREG:PAREG)
  116. #define BITMASK(VPIN) (1<<((VPIN)&15))
  117. #define vATN PA(8) // SCSI:ATN
  118. #define vBSY PA(9) // SCSI:BSY
  119. #define vACK PA(10) // SCSI:ACK
  120. #define vRST PA(15) // SCSI:RST
  121. #define vMSG PB(3) // SCSI:MSG
  122. #define vSEL PB(4) // SCSI:SEL
  123. #define vCD PB(5) // SCSI:C/D
  124. #define vREQ PB(6) // SCSI:REQ
  125. #define vIO PB(7) // SCSI:I/O
  126. #define vSD_CS PA(4) // SDCARD:CS
  127. // SCSI output pin control: opendrain active LOW (direct pin drive)
  128. #define SCSI_OUT(VPIN,ACTIVE) { GPIOREG(VPIN)->BSRR = BITMASK(VPIN)<<((ACTIVE)?16:0); }
  129. // SCSI input pin check (inactive=0,avtive=1)
  130. #define SCSI_IN(VPIN) ((~GPIOREG(VPIN)->IDR>>(VPIN&15))&1)
  131. // GPIO mode
  132. // IN , FLOAT : 4
  133. // IN , PU/PD : 8
  134. // OUT, PUSH/PULL : 3
  135. // OUT, OD : 1
  136. //#define DB_MODE_OUT 3
  137. #define DB_MODE_OUT 1
  138. #define DB_MODE_IN 8
  139. // Put DB and DP in output mode
  140. #define SCSI_DB_OUTPUT() { PBREG->CRL=(PBREG->CRL &0xfffffff0)|DB_MODE_OUT; PBREG->CRH = 0x11111111*DB_MODE_OUT; }
  141. // Put DB and DP in input mode
  142. #define SCSI_DB_INPUT() { PBREG->CRL=(PBREG->CRL &0xfffffff0)|DB_MODE_IN ; PBREG->CRH = 0x11111111*DB_MODE_IN; }
  143. // Turn on the output only for BSY
  144. #define SCSI_BSY_ACTIVE() { gpio_mode(BSY, GPIO_OUTPUT_OD); SCSI_OUT(vBSY, active) }
  145. // BSY,REQ,MSG,CD,IO Turn on the output (no change required for OD)
  146. #define SCSI_TARGET_ACTIVE() { }
  147. // BSY,REQ,MSG,CD,IO Turn off output, BSY is the last input
  148. #define SCSI_TARGET_INACTIVE() { SCSI_OUT(vREQ,inactive); SCSI_OUT(vMSG,inactive); SCSI_OUT(vCD,inactive);SCSI_OUT(vIO,inactive); SCSI_OUT(vBSY,inactive); gpio_mode(BSY, GPIO_INPUT_PU); }
  149. // HDDiamge file
  150. #define HDIMG_ID_POS 2 // Position to embed ID number
  151. #define HDIMG_LUN_POS 3 // Position to embed LUN numbers
  152. #define HDIMG_BLK_POS 5 // Position to embed block size numbers
  153. #define MAX_FILE_PATH 32 // Maximum file name length
  154. // HDD image
  155. typedef struct hddimg_struct
  156. {
  157. FsFile m_file; // File object
  158. uint64_t m_fileSize; // File size
  159. size_t m_blocksize; // SCSI BLOCK size
  160. }HDDIMG;
  161. HDDIMG img[NUM_SCSIID][NUM_SCSILUN]; // Maximum number
  162. uint8_t m_senseKey = 0; // Sense key
  163. unsigned m_addition_sense = 0; // Additional sense information
  164. volatile bool m_isBusReset = false; // Bus reset
  165. byte scsi_id_mask; // Mask list of responding SCSI IDs
  166. byte m_id; // Currently responding SCSI-ID
  167. byte m_lun; // Logical unit number currently responding
  168. byte m_sts; // Status byte
  169. byte m_msg; // Message bytes
  170. HDDIMG *m_img; // HDD image for current SCSI-ID, LUN
  171. byte m_buf[MAX_BLOCKSIZE+1]; // General purpose buffer + overrun fetch
  172. int m_msc;
  173. byte m_msb[256]; // Command storage bytes
  174. /*
  175. * Data byte to BSRR register setting value and parity table
  176. */
  177. // Parity bit generation
  178. #define PTY(V) (1^((V)^((V)>>1)^((V)>>2)^((V)>>3)^((V)>>4)^((V)>>5)^((V)>>6)^((V)>>7))&1)
  179. // Data byte to BSRR register setting value conversion table
  180. // BSRR[31:24] = DB[7:0]
  181. // BSRR[ 16] = PTY(DB)
  182. // BSRR[15: 8] = ~DB[7:0]
  183. // BSRR[ 0] = ~PTY(DB)
  184. // Set DBP, set REQ = inactive
  185. #define DBP(D) ((((((uint32_t)(D)<<8)|PTY(D))*0x00010001)^0x0000ff01)|BITMASK(vREQ))
  186. #define DBP8(D) DBP(D),DBP(D+1),DBP(D+2),DBP(D+3),DBP(D+4),DBP(D+5),DBP(D+6),DBP(D+7)
  187. #define DBP32(D) DBP8(D),DBP8(D+8),DBP8(D+16),DBP8(D+24)
  188. // BSRR register control value that simultaneously performs DB set, DP set, and REQ = H (inactrive)
  189. static const uint32_t db_bsrr[256]={
  190. DBP32(0x00),DBP32(0x20),DBP32(0x40),DBP32(0x60),
  191. DBP32(0x80),DBP32(0xA0),DBP32(0xC0),DBP32(0xE0)
  192. };
  193. // Parity bit acquisition
  194. #define PARITY(DB) (db_bsrr[DB]&1)
  195. // Macro cleaning
  196. #undef DBP32
  197. #undef DBP8
  198. //#undef DBP
  199. //#undef PTY
  200. // Log File
  201. #define VERSION "1.1-SNAPSHOT-20220107"
  202. #define LOG_FILENAME "LOG.txt"
  203. FsFile LOG_FILE;
  204. // SCSI Drive Vendor information
  205. byte SCSI_INFO_BUF[36] = {
  206. 0x00, //device type
  207. 0x00, //RMB = 0
  208. 0x01, //ISO, ECMA, ANSI version
  209. 0x01, //Response data format
  210. 35 - 4, //Additional data length
  211. 0, 0, //Reserve
  212. 0x00, //Support function
  213. 'Q', 'U', 'A', 'N', 'T', 'U', 'M', ' ', // vendor 8
  214. 'F', 'I', 'R', 'E', 'B', 'A', 'L', 'L', '1', ' ', ' ',' ', ' ', ' ', ' ', ' ', // product 16
  215. '1', '.', '0', ' ' // version 4
  216. };
  217. void onFalseInit(void);
  218. void noSDCardFound(void);
  219. void onBusReset(void);
  220. void initFileLog(void);
  221. void finalizeFileLog(void);
  222. /*
  223. * IO read.
  224. */
  225. inline byte readIO(void)
  226. {
  227. // Port input data register
  228. uint32_t ret = GPIOB->regs->IDR;
  229. byte bret = (byte)((~ret)>>8);
  230. #if READ_PARITY_CHECK
  231. if((db_bsrr[bret]^ret)&1)
  232. m_sts |= 0x01; // parity error
  233. #endif
  234. return bret;
  235. }
  236. // If config file exists, read the first three lines and copy the contents.
  237. // File must be well formed or you will get junk in the SCSI Vendor fields.
  238. void readSCSIDeviceConfig() {
  239. FsFile config_file = SD.open("scsi-config.txt", O_RDONLY);
  240. if (!config_file.isOpen()) {
  241. return;
  242. }
  243. char vendor[9];
  244. memset(vendor, 0, sizeof(vendor));
  245. config_file.readBytes(vendor, sizeof(vendor));
  246. LOG_FILE.print("SCSI VENDOR: ");
  247. LOG_FILE.println(vendor);
  248. memcpy(&(SCSI_INFO_BUF[8]), vendor, 8);
  249. char product[17];
  250. memset(product, 0, sizeof(product));
  251. config_file.readBytes(product, sizeof(product));
  252. LOG_FILE.print("SCSI PRODUCT: ");
  253. LOG_FILE.println(product);
  254. memcpy(&(SCSI_INFO_BUF[16]), product, 16);
  255. char version[5];
  256. memset(version, 0, sizeof(version));
  257. config_file.readBytes(version, sizeof(version));
  258. LOG_FILE.print("SCSI VERSION: ");
  259. LOG_FILE.println(version);
  260. memcpy(&(SCSI_INFO_BUF[32]), version, 4);
  261. config_file.close();
  262. }
  263. // read SD information and print to logfile
  264. void readSDCardInfo()
  265. {
  266. cid_t sd_cid;
  267. if(SD.card()->readCID(&sd_cid))
  268. {
  269. LOG_FILE.print("Sd MID:");
  270. LOG_FILE.print(sd_cid.mid, 16);
  271. LOG_FILE.print(" OID:");
  272. LOG_FILE.print(sd_cid.oid[0]);
  273. LOG_FILE.println(sd_cid.oid[1]);
  274. LOG_FILE.print("Sd Name:");
  275. LOG_FILE.print(sd_cid.pnm[0]);
  276. LOG_FILE.print(sd_cid.pnm[1]);
  277. LOG_FILE.print(sd_cid.pnm[2]);
  278. LOG_FILE.print(sd_cid.pnm[3]);
  279. LOG_FILE.println(sd_cid.pnm[4]);
  280. LOG_FILE.print("Sd Date:");
  281. LOG_FILE.print(sd_cid.mdt_month);
  282. LOG_FILE.print("/20"); // CID year is 2000 + high/low
  283. LOG_FILE.print(sd_cid.mdt_year_high);
  284. LOG_FILE.println(sd_cid.mdt_year_low);
  285. LOG_FILE.print("Sd Serial:");
  286. LOG_FILE.println(sd_cid.psn);
  287. LOG_FILE.sync();
  288. }
  289. }
  290. /*
  291. * Open HDD image file
  292. */
  293. bool hddimageOpen(HDDIMG *h,const char *image_name,int id,int lun,int blocksize)
  294. {
  295. h->m_fileSize = 0;
  296. h->m_blocksize = blocksize;
  297. h->m_file = SD.open(image_name, O_RDWR);
  298. if(h->m_file.isOpen())
  299. {
  300. h->m_fileSize = h->m_file.size();
  301. LOG_FILE.print("Imagefile: ");
  302. LOG_FILE.print(image_name);
  303. if(h->m_fileSize>0)
  304. {
  305. // check blocksize dummy file
  306. LOG_FILE.print(" / ");
  307. LOG_FILE.print(h->m_fileSize);
  308. LOG_FILE.print("bytes / ");
  309. LOG_FILE.print(h->m_fileSize / 1024);
  310. LOG_FILE.print("KiB / ");
  311. LOG_FILE.print(h->m_fileSize / 1024 / 1024);
  312. LOG_FILE.println("MiB");
  313. return true; // File opened
  314. }
  315. else
  316. {
  317. h->m_file.close();
  318. h->m_fileSize = h->m_blocksize = 0; // no file
  319. LOG_FILE.println("FileSizeError");
  320. }
  321. }
  322. return false;
  323. }
  324. /*
  325. * Initialization.
  326. * Initialize the bus and set the PIN orientation
  327. */
  328. void setup()
  329. {
  330. // PA15 / PB3 / PB4 Cannot be used
  331. // JTAG Because it is used for debugging.
  332. disableDebugPorts();
  333. // Serial initialization
  334. #if DEBUG > 0
  335. Serial.begin(9600);
  336. // If using a USB->TTL monitor instead of USB serial monitor - you can uncomment this.
  337. //while (!Serial);
  338. #endif
  339. // PIN initialization
  340. gpio_mode(LED2, GPIO_OUTPUT_PP);
  341. gpio_mode(LED, GPIO_OUTPUT_OD);
  342. LED_OFF();
  343. //GPIO(SCSI BUS)Initialization
  344. //Port setting register (lower)
  345. // GPIOB->regs->CRL |= 0x000000008; // SET INPUT W/ PUPD on PAB-PB0
  346. //Port setting register (upper)
  347. //GPIOB->regs->CRH = 0x88888888; // SET INPUT W/ PUPD on PB15-PB8
  348. // GPIOB->regs->ODR = 0x0000FF00; // SET PULL-UPs on PB15-PB8
  349. // DB and DP are input modes
  350. SCSI_DB_INPUT()
  351. // Input port
  352. gpio_mode(ATN, GPIO_INPUT_PU);
  353. gpio_mode(BSY, GPIO_INPUT_PU);
  354. gpio_mode(ACK, GPIO_INPUT_PU);
  355. gpio_mode(RST, GPIO_INPUT_PU);
  356. gpio_mode(SEL, GPIO_INPUT_PU);
  357. // Output port
  358. gpio_mode(MSG, GPIO_OUTPUT_OD);
  359. gpio_mode(CD, GPIO_OUTPUT_OD);
  360. gpio_mode(REQ, GPIO_OUTPUT_OD);
  361. gpio_mode(IO, GPIO_OUTPUT_OD);
  362. // Turn off the output port
  363. SCSI_TARGET_INACTIVE()
  364. //Occurs when the RST pin state changes from HIGH to LOW
  365. //attachInterrupt(PIN_MAP[RST].gpio_bit, onBusReset, FALLING);
  366. LED_ON();
  367. // clock = 36MHz , about 4Mbytes/sec
  368. if(!SD.begin(SD1_CONFIG)) {
  369. #if DEBUG > 0
  370. Serial.println("SD initialization failed!");
  371. #endif
  372. noSDCardFound();
  373. }
  374. initFileLog();
  375. readSCSIDeviceConfig();
  376. readSDCardInfo();
  377. //Sector data overrun byte setting
  378. m_buf[MAX_BLOCKSIZE] = 0xff; // DB0 all off,DBP off
  379. //HD image file open
  380. scsi_id_mask = 0x00;
  381. // Iterate over the root path in the SD card looking for candidate image files.
  382. SdFile root;
  383. root.open("/");
  384. SdFile file;
  385. bool imageReady;
  386. int usedDefaultId = 0;
  387. while (1) {
  388. if (!file.openNext(&root, O_READ)) break;
  389. char name[MAX_FILE_PATH+1];
  390. if(!file.isDir()) {
  391. file.getName(name, MAX_FILE_PATH+1);
  392. file.close();
  393. String file_name = String(name);
  394. file_name.toLowerCase();
  395. if(file_name.startsWith("hd")) {
  396. // Defaults for Hard Disks
  397. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  398. int lun = 0;
  399. int blk = 512;
  400. // Positionally read in and coerase the chars to integers.
  401. // We only require the minimum and read in the next if provided.
  402. int file_name_length = file_name.length();
  403. if(file_name_length > 2) { // HD[N]
  404. int tmp_id = name[HDIMG_ID_POS] - '0';
  405. // If valid id, set it, else use default
  406. if(tmp_id > -1 && tmp_id < 8) {
  407. id = tmp_id;
  408. } else {
  409. usedDefaultId++;
  410. }
  411. }
  412. int blk1, blk2, blk3, blk4 = 0;
  413. if(file_name_length > 8) { // HD00_[111]
  414. blk1 = name[HDIMG_BLK_POS] - '0';
  415. blk2 = name[HDIMG_BLK_POS+1] - '0';
  416. blk3 = name[HDIMG_BLK_POS+2] - '0';
  417. if(file_name_length > 9) // HD00_NNN[1]
  418. blk4 = name[HDIMG_BLK_POS+3] - '0';
  419. }
  420. if(blk1 == 2 && blk2 == 5 && blk3 == 6) {
  421. blk = 256;
  422. } else if(blk1 == 1 && blk2 == 0 && blk3 == 2 && blk4 == 4) {
  423. blk = 1024;
  424. } else if(blk1 == 2 && blk2 == 0 && blk3 == 4 && blk4 == 8) {
  425. blk = 2048;
  426. }
  427. if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  428. HDDIMG *h = &img[id][lun];
  429. imageReady = hddimageOpen(h,name,id,lun,blk);
  430. if(imageReady) { // Marked as a responsive ID
  431. scsi_id_mask |= 1<<id;
  432. }
  433. } else {
  434. LOG_FILE.print("Bad LUN or SCSI id for image: ");
  435. LOG_FILE.println(name);
  436. LOG_FILE.sync();
  437. }
  438. } else {
  439. LOG_FILE.print("Not an image: ");
  440. LOG_FILE.println(name);
  441. LOG_FILE.sync();
  442. }
  443. }
  444. }
  445. if(usedDefaultId > 1) {
  446. LOG_FILE.println("!! More than one image did not specify a SCSI ID. Last file will be used at ID 1 !!");
  447. LOG_FILE.sync();
  448. }
  449. root.close();
  450. // Error if there are 0 image files
  451. if(scsi_id_mask==0) {
  452. LOG_FILE.println("ERROR: No valid images found!");
  453. onFalseInit();
  454. }
  455. finalizeFileLog();
  456. LED_OFF();
  457. //Occurs when the RST pin state changes from HIGH to LOW
  458. attachInterrupt(PIN_MAP[RST].gpio_bit, onBusReset, FALLING);
  459. }
  460. /*
  461. * Setup initialization logfile
  462. */
  463. void initFileLog() {
  464. LOG_FILE = SD.open(LOG_FILENAME, O_WRONLY | O_CREAT | O_TRUNC);
  465. LOG_FILE.println("BlueSCSI <-> SD - https://github.com/erichelgeson/BlueSCSI");
  466. LOG_FILE.print("VERSION: ");
  467. LOG_FILE.println(VERSION);
  468. LOG_FILE.print("DEBUG:");
  469. LOG_FILE.print(DEBUG);
  470. LOG_FILE.print(" SCSI_SELECT:");
  471. LOG_FILE.print(SCSI_SELECT);
  472. LOG_FILE.print(" SDFAT_FILE_TYPE:");
  473. LOG_FILE.println(SDFAT_FILE_TYPE);
  474. LOG_FILE.print("SdFat version: ");
  475. LOG_FILE.println(SD_FAT_VERSION_STR);
  476. LOG_FILE.print("SdFat Max FileName Length: ");
  477. LOG_FILE.println(MAX_FILE_PATH);
  478. LOG_FILE.println("Initialized SD Card - lets go!");
  479. LOG_FILE.sync();
  480. }
  481. /*
  482. * Finalize initialization logfile
  483. */
  484. void finalizeFileLog() {
  485. // View support drive map
  486. LOG_FILE.print("ID");
  487. for(int lun=0;lun<NUM_SCSILUN;lun++)
  488. {
  489. LOG_FILE.print(":LUN");
  490. LOG_FILE.print(lun);
  491. }
  492. LOG_FILE.println(":");
  493. //
  494. for(int id=0;id<NUM_SCSIID;id++)
  495. {
  496. LOG_FILE.print(" ");
  497. LOG_FILE.print(id);
  498. for(int lun=0;lun<NUM_SCSILUN;lun++)
  499. {
  500. HDDIMG *h = &img[id][lun];
  501. if( (lun<NUM_SCSILUN) && (h->m_file))
  502. {
  503. LOG_FILE.print((h->m_blocksize<1000) ? ": " : ":");
  504. LOG_FILE.print(h->m_blocksize);
  505. }
  506. else
  507. LOG_FILE.print(":----");
  508. }
  509. LOG_FILE.println(":");
  510. }
  511. LOG_FILE.println("Finished initialization of SCSI Devices - Entering main loop.");
  512. LOG_FILE.sync();
  513. LOG_FILE.close();
  514. }
  515. /*
  516. * Initialization failed, blink 3x fast
  517. */
  518. void onFalseInit(void)
  519. {
  520. LOG_FILE.sync();
  521. while(true) {
  522. for(int i = 0; i < 3; i++) {
  523. LED_ON();
  524. delay(250);
  525. LED_OFF();
  526. delay(250);
  527. }
  528. delay(3000);
  529. }
  530. }
  531. /*
  532. * No SC Card found, blink 5x fast
  533. */
  534. void noSDCardFound(void)
  535. {
  536. while(true) {
  537. for(int i = 0; i < 5; i++) {
  538. LED_ON();
  539. delay(250);
  540. LED_OFF();
  541. delay(250);
  542. }
  543. delay(3000);
  544. }
  545. }
  546. /*
  547. * Bus reset interrupt.
  548. */
  549. void onBusReset(void)
  550. {
  551. #if SCSI_SELECT == 1
  552. // SASI I / F for X1 turbo has RST pulse write cycle +2 clock ==
  553. // I can't filter because it only activates about 1.25us
  554. {{
  555. #else
  556. if(isHigh(gpio_read(RST))) {
  557. delayMicroseconds(20);
  558. if(isHigh(gpio_read(RST))) {
  559. #endif
  560. // BUS FREE is done in the main process
  561. // gpio_mode(MSG, GPIO_OUTPUT_OD);
  562. // gpio_mode(CD, GPIO_OUTPUT_OD);
  563. // gpio_mode(REQ, GPIO_OUTPUT_OD);
  564. // gpio_mode(IO, GPIO_OUTPUT_OD);
  565. // Should I enter DB and DBP once?
  566. SCSI_DB_INPUT()
  567. LOGN("BusReset!");
  568. m_isBusReset = true;
  569. }
  570. }
  571. }
  572. /*
  573. * Read by handshake.
  574. */
  575. inline byte readHandshake(void)
  576. {
  577. SCSI_OUT(vREQ,active)
  578. //SCSI_DB_INPUT()
  579. while( ! SCSI_IN(vACK)) { if(m_isBusReset) return 0; }
  580. byte r = readIO();
  581. SCSI_OUT(vREQ,inactive)
  582. while( SCSI_IN(vACK)) { if(m_isBusReset) return 0; }
  583. return r;
  584. }
  585. /*
  586. * Write with a handshake.
  587. */
  588. inline void writeHandshake(byte d)
  589. {
  590. GPIOB->regs->BSRR = db_bsrr[d]; // setup DB,DBP (160ns)
  591. SCSI_DB_OUTPUT() // (180ns)
  592. // ACK.Fall to DB output delay 100ns(MAX) (DTC-510B)
  593. SCSI_OUT(vREQ,inactive) // setup wait (30ns)
  594. SCSI_OUT(vREQ,inactive) // setup wait (30ns)
  595. SCSI_OUT(vREQ,inactive) // setup wait (30ns)
  596. SCSI_OUT(vREQ,active) // (30ns)
  597. //while(!SCSI_IN(vACK)) { if(m_isBusReset){ SCSI_DB_INPUT() return; }}
  598. while(!m_isBusReset && !SCSI_IN(vACK));
  599. // ACK.Fall to REQ.Raise delay 500ns(typ.) (DTC-510B)
  600. GPIOB->regs->BSRR = DBP(0xff); // DB=0xFF , SCSI_OUT(vREQ,inactive)
  601. // REQ.Raise to DB hold time 0ns
  602. SCSI_DB_INPUT() // (150ns)
  603. while( SCSI_IN(vACK)) { if(m_isBusReset) return; }
  604. }
  605. /*
  606. * Data in phase.
  607. * Send len bytes of data array p.
  608. */
  609. void writeDataPhase(int len, const byte* p)
  610. {
  611. LOGN("DATAIN PHASE");
  612. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  613. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  614. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  615. for (int i = 0; i < len; i++) {
  616. if(m_isBusReset) {
  617. return;
  618. }
  619. writeHandshake(p[i]);
  620. }
  621. }
  622. /*
  623. * Data in phase.
  624. * Send len block while reading from SD card.
  625. */
  626. void writeDataPhaseSD(uint32_t adds, uint32_t len)
  627. {
  628. LOGN("DATAIN PHASE(SD)");
  629. uint32_t pos = adds * m_img->m_blocksize;
  630. m_img->m_file.seek(pos);
  631. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  632. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  633. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  634. for(uint32_t i = 0; i < len; i++) {
  635. // Asynchronous reads will make it faster ...
  636. m_img->m_file.read(m_buf, m_img->m_blocksize);
  637. #if READ_SPEED_OPTIMIZE
  638. //#define REQ_ON() SCSI_OUT(vREQ,active)
  639. #define REQ_ON() (*db_dst = BITMASK(vREQ)<<16)
  640. #define FETCH_SRC() (src_byte = *srcptr++)
  641. #define FETCH_BSRR_DB() (bsrr_val = bsrr_tbl[src_byte])
  642. #define REQ_OFF_DB_SET(BSRR_VAL) *db_dst = BSRR_VAL
  643. #define WAIT_ACK_ACTIVE() while(!m_isBusReset && !SCSI_IN(vACK))
  644. #define WAIT_ACK_INACTIVE() do{ if(m_isBusReset) return; }while(SCSI_IN(vACK))
  645. SCSI_DB_OUTPUT()
  646. register byte *srcptr= m_buf; // Source buffer
  647. register byte *endptr= m_buf + m_img->m_blocksize; // End pointer
  648. /*register*/ byte src_byte; // Send data bytes
  649. register const uint32_t *bsrr_tbl = db_bsrr; // Table to convert to BSRR
  650. register uint32_t bsrr_val; // BSRR value to output (DB, DBP, REQ = ACTIVE)
  651. register volatile uint32_t *db_dst = &(GPIOB->regs->BSRR); // Output port
  652. // prefetch & 1st out
  653. FETCH_SRC();
  654. FETCH_BSRR_DB();
  655. REQ_OFF_DB_SET(bsrr_val);
  656. // DB.set to REQ.F setup 100ns max (DTC-510B)
  657. // Maybe there should be some weight here
  658. // WAIT_ACK_INACTIVE();
  659. do{
  660. // 0
  661. REQ_ON();
  662. FETCH_SRC();
  663. FETCH_BSRR_DB();
  664. WAIT_ACK_ACTIVE();
  665. // ACK.F to REQ.R 500ns typ. (DTC-510B)
  666. REQ_OFF_DB_SET(bsrr_val);
  667. WAIT_ACK_INACTIVE();
  668. // 1
  669. REQ_ON();
  670. FETCH_SRC();
  671. FETCH_BSRR_DB();
  672. WAIT_ACK_ACTIVE();
  673. REQ_OFF_DB_SET(bsrr_val);
  674. WAIT_ACK_INACTIVE();
  675. // 2
  676. REQ_ON();
  677. FETCH_SRC();
  678. FETCH_BSRR_DB();
  679. WAIT_ACK_ACTIVE();
  680. REQ_OFF_DB_SET(bsrr_val);
  681. WAIT_ACK_INACTIVE();
  682. // 3
  683. REQ_ON();
  684. FETCH_SRC();
  685. FETCH_BSRR_DB();
  686. WAIT_ACK_ACTIVE();
  687. REQ_OFF_DB_SET(bsrr_val);
  688. WAIT_ACK_INACTIVE();
  689. // 4
  690. REQ_ON();
  691. FETCH_SRC();
  692. FETCH_BSRR_DB();
  693. WAIT_ACK_ACTIVE();
  694. REQ_OFF_DB_SET(bsrr_val);
  695. WAIT_ACK_INACTIVE();
  696. // 5
  697. REQ_ON();
  698. FETCH_SRC();
  699. FETCH_BSRR_DB();
  700. WAIT_ACK_ACTIVE();
  701. REQ_OFF_DB_SET(bsrr_val);
  702. WAIT_ACK_INACTIVE();
  703. // 6
  704. REQ_ON();
  705. FETCH_SRC();
  706. FETCH_BSRR_DB();
  707. WAIT_ACK_ACTIVE();
  708. REQ_OFF_DB_SET(bsrr_val);
  709. WAIT_ACK_INACTIVE();
  710. // 7
  711. REQ_ON();
  712. FETCH_SRC();
  713. FETCH_BSRR_DB();
  714. WAIT_ACK_ACTIVE();
  715. REQ_OFF_DB_SET(bsrr_val);
  716. WAIT_ACK_INACTIVE();
  717. }while(srcptr < endptr);
  718. SCSI_DB_INPUT()
  719. #else
  720. for(int j = 0; j < m_img->m_blocksize; j++) {
  721. if(m_isBusReset) {
  722. return;
  723. }
  724. writeHandshake(m_buf[j]);
  725. }
  726. #endif
  727. }
  728. }
  729. /*
  730. * Data out phase.
  731. * len block read
  732. */
  733. void readDataPhase(int len, byte* p)
  734. {
  735. LOGN("DATAOUT PHASE");
  736. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  737. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  738. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  739. for(uint32_t i = 0; i < len; i++)
  740. p[i] = readHandshake();
  741. }
  742. /*
  743. * Data out phase.
  744. * Write to SD card while reading len block.
  745. */
  746. void readDataPhaseSD(uint32_t adds, uint32_t len)
  747. {
  748. LOGN("DATAOUT PHASE(SD)");
  749. uint32_t pos = adds * m_img->m_blocksize;
  750. m_img->m_file.seek(pos);
  751. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  752. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  753. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  754. for(uint32_t i = 0; i < len; i++) {
  755. #if WRITE_SPEED_OPTIMIZE
  756. register byte *dstptr= m_buf;
  757. register byte *endptr= m_buf + m_img->m_blocksize;
  758. for(dstptr=m_buf;dstptr<endptr;dstptr+=8) {
  759. dstptr[0] = readHandshake();
  760. dstptr[1] = readHandshake();
  761. dstptr[2] = readHandshake();
  762. dstptr[3] = readHandshake();
  763. dstptr[4] = readHandshake();
  764. dstptr[5] = readHandshake();
  765. dstptr[6] = readHandshake();
  766. dstptr[7] = readHandshake();
  767. if(m_isBusReset) {
  768. return;
  769. }
  770. }
  771. #else
  772. for(int j = 0; j < m_img->m_blocksize; j++) {
  773. if(m_isBusReset) {
  774. return;
  775. }
  776. m_buf[j] = readHandshake();
  777. }
  778. #endif
  779. m_img->m_file.write(m_buf, m_img->m_blocksize);
  780. }
  781. m_img->m_file.flush();
  782. }
  783. /*
  784. * INQUIRY command processing.
  785. */
  786. #if SCSI_SELECT == 2
  787. byte onInquiryCommand(byte len)
  788. {
  789. byte buf[36] = {
  790. 0x00, //Device type
  791. 0x00, //RMB = 0
  792. 0x01, //ISO,ECMA,ANSI version
  793. 0x01, //Response data format
  794. 35 - 4, //Additional data length
  795. 0, 0, //Reserve
  796. 0x00, //Support function
  797. 'N', 'E', 'C', 'I', 'T', 'S', 'U', ' ',
  798. 'A', 'r', 'd', 'S', 'C', 'S', 'i', 'n', 'o', ' ', ' ',' ', ' ', ' ', ' ', ' ',
  799. '0', '0', '1', '0',
  800. };
  801. writeDataPhase(len < 36 ? len : 36, buf);
  802. return 0x00;
  803. }
  804. #else
  805. byte onInquiryCommand(byte len)
  806. {
  807. writeDataPhase(len < 36 ? len : 36, SCSI_INFO_BUF);
  808. return 0x00;
  809. }
  810. #endif
  811. /*
  812. * REQUEST SENSE command processing.
  813. */
  814. void onRequestSenseCommand(byte len)
  815. {
  816. byte buf[18] = {
  817. 0x70, //CheckCondition
  818. 0, //Segment number
  819. m_senseKey, //Sense key
  820. 0, 0, 0, 0, //information
  821. 10, //Additional data length
  822. 0, 0, 0, 0, // command specific information bytes
  823. (byte)(m_addition_sense >> 8),
  824. (byte)m_addition_sense,
  825. 0, 0, 0, 0,
  826. };
  827. m_senseKey = 0;
  828. m_addition_sense = 0;
  829. writeDataPhase(len < 18 ? len : 18, buf);
  830. }
  831. /*
  832. * READ CAPACITY command processing.
  833. */
  834. byte onReadCapacityCommand(byte pmi)
  835. {
  836. if(!m_img) return 0x02; // Image file absent
  837. uint32_t bl = m_img->m_blocksize;
  838. uint32_t bc = m_img->m_fileSize / bl - 1; // Points to last LBA
  839. uint8_t buf[8] = {
  840. bc >> 24, bc >> 16, bc >> 8, bc,
  841. bl >> 24, bl >> 16, bl >> 8, bl
  842. };
  843. writeDataPhase(8, buf);
  844. return 0x00;
  845. }
  846. /*
  847. * READ6 / 10 Command processing.
  848. */
  849. byte onReadCommand(uint32_t adds, uint32_t len)
  850. {
  851. LOGN("-R");
  852. LOGHEXN(adds);
  853. LOGHEXN(len);
  854. if(!m_img) return 0x02; // Image file absent
  855. LED_ON();
  856. writeDataPhaseSD(adds, len);
  857. LED_OFF();
  858. return 0x00; //sts
  859. }
  860. /*
  861. * WRITE6 / 10 Command processing.
  862. */
  863. byte onWriteCommand(uint32_t adds, uint32_t len)
  864. {
  865. LOGN("-W");
  866. LOGHEXN(adds);
  867. LOGHEXN(len);
  868. if(!m_img) return 0x02; // Image file absent
  869. LED_ON();
  870. readDataPhaseSD(adds, len);
  871. LED_OFF();
  872. return 0; //sts
  873. }
  874. /*
  875. * MODE SENSE command processing.
  876. */
  877. #if SCSI_SELECT == 2
  878. byte onModeSenseCommand(byte scsi_cmd, byte dbd, int cmd2, uint32_t len)
  879. {
  880. if(!m_img) return 0x02; // Image file absent
  881. int pageCode = cmd2 & 0x3F;
  882. // Assuming sector size 512, number of sectors 25, number of heads 8 as default settings
  883. int size = m_img->m_fileSize;
  884. int cylinders = (int)(size >> 9);
  885. cylinders >>= 3;
  886. cylinders /= 25;
  887. int sectorsize = 512;
  888. int sectors = 25;
  889. int heads = 8;
  890. // Sector size
  891. int disksize = 0;
  892. for(disksize = 16; disksize > 0; --(disksize)) {
  893. if ((1 << disksize) == sectorsize)
  894. break;
  895. }
  896. // Number of blocks
  897. uint32_t diskblocks = (uint32_t)(size >> disksize);
  898. memset(m_buf, 0, sizeof(m_buf));
  899. int a = 4;
  900. if(dbd == 0) {
  901. uint32_t bl = m_img->m_blocksize;
  902. uint32_t bc = m_img->m_fileSize / bl;
  903. byte c[8] = {
  904. 0,// Density code
  905. bc >> 16, bc >> 8, bc,
  906. 0, //Reserve
  907. bl >> 16, bl >> 8, bl
  908. };
  909. memcpy(&m_buf[4], c, 8);
  910. a += 8;
  911. m_buf[3] = 0x08;
  912. }
  913. switch(pageCode) {
  914. case 0x3F:
  915. {
  916. m_buf[a + 0] = 0x01;
  917. m_buf[a + 1] = 0x06;
  918. a += 8;
  919. }
  920. case 0x03: // drive parameters
  921. {
  922. m_buf[a + 0] = 0x80 | 0x03; // Page code
  923. m_buf[a + 1] = 0x16; // Page length
  924. m_buf[a + 2] = (byte)(heads >> 8);// number of sectors / track
  925. m_buf[a + 3] = (byte)(heads);// number of sectors / track
  926. m_buf[a + 10] = (byte)(sectors >> 8);// number of sectors / track
  927. m_buf[a + 11] = (byte)(sectors);// number of sectors / track
  928. int size = 1 << disksize;
  929. m_buf[a + 12] = (byte)(size >> 8);// number of sectors / track
  930. m_buf[a + 13] = (byte)(size);// number of sectors / track
  931. a += 24;
  932. if(pageCode != 0x3F) {
  933. break;
  934. }
  935. }
  936. case 0x04: // drive parameters
  937. {
  938. LOGN("AddDrive");
  939. m_buf[a + 0] = 0x04; // Page code
  940. m_buf[a + 1] = 0x12; // Page length
  941. m_buf[a + 2] = (cylinders >> 16);// Cylinder length
  942. m_buf[a + 3] = (cylinders >> 8);
  943. m_buf[a + 4] = cylinders;
  944. m_buf[a + 5] = heads; // Number of heads
  945. a += 20;
  946. if(pageCode != 0x3F) {
  947. break;
  948. }
  949. }
  950. default:
  951. break;
  952. }
  953. m_buf[0] = a - 1;
  954. writeDataPhase(len < a ? len : a, m_buf);
  955. return 0x00;
  956. }
  957. #else
  958. byte onModeSenseCommand(byte scsi_cmd, byte dbd, int cmd2, uint32_t len)
  959. {
  960. if(!m_img) return 0x02; // No image file
  961. uint32_t bl = m_img->m_blocksize;
  962. uint32_t bc = m_img->m_fileSize / bl;
  963. memset(m_buf, 0, sizeof(m_buf));
  964. int pageCode = cmd2 & 0x3F;
  965. int a = 4;
  966. if(scsi_cmd == 0x5A) a = 8;
  967. if(dbd == 0) {
  968. byte c[8] = {
  969. 0,//Density code
  970. bc >> 16, bc >> 8, bc,
  971. 0, //Reserve
  972. bl >> 16, bl >> 8, bl
  973. };
  974. memcpy(&m_buf[a], c, 8);
  975. a += 8;
  976. }
  977. switch(pageCode) {
  978. case 0x3F:
  979. case 0x01: // Read/Write Error Recovery
  980. m_buf[a + 0] = 0x01;
  981. m_buf[a + 1] = 0x0A;
  982. a += 0x0C;
  983. if(pageCode != 0x3F) break;
  984. case 0x02: // Disconnect-Reconnect page
  985. m_buf[a + 0] = 0x02;
  986. m_buf[a + 1] = 0x0A;
  987. a += 0x0C;
  988. if(pageCode != 0x3f) break;
  989. case 0x03: //Drive parameters
  990. m_buf[a + 0] = 0x03; //Page code
  991. m_buf[a + 1] = 0x16; // Page length
  992. m_buf[a + 11] = 0x3F;//Number of sectors / track
  993. m_buf[a + 12] = (byte)(m_img->m_blocksize >> 8);
  994. m_buf[a + 13] = (byte)m_img->m_blocksize;
  995. m_buf[a + 15] = 0x1; // Interleave
  996. a += 0x18;
  997. if(pageCode != 0x3F) break;
  998. case 0x04: //Drive parameters
  999. {
  1000. unsigned cylinders = bc / (16 * 63);
  1001. m_buf[a + 0] = 0x04; //Page code
  1002. m_buf[a + 1] = 0x16; // Page length
  1003. m_buf[a + 2] = (byte)(cylinders >> 16); // Cylinders
  1004. m_buf[a + 3] = (byte)(cylinders >> 8);
  1005. m_buf[a + 4] = (byte)cylinders;
  1006. m_buf[a + 5] = 16; //Number of heads
  1007. a += 0x18;
  1008. if(pageCode != 0x3F) break;
  1009. }
  1010. break; // Don't want 0x3F falling through to error condition
  1011. default:
  1012. m_senseKey = 5; // Illegal request
  1013. m_addition_sense = 0x2400; // Invalid field in CDB
  1014. return 0x02;
  1015. break;
  1016. }
  1017. if(scsi_cmd == 0x5A) // MODE SENSE 10
  1018. {
  1019. m_buf[1] = a - 2;
  1020. m_buf[7] = 0x08;
  1021. }
  1022. else
  1023. {
  1024. m_buf[0] = a - 1;
  1025. m_buf[3] = 0x08;
  1026. }
  1027. writeDataPhase(len < a ? len : a, m_buf);
  1028. return 0x00;
  1029. }
  1030. #endif
  1031. #if SCSI_SELECT == 1
  1032. /*
  1033. * dtc510b_setDriveparameter
  1034. */
  1035. #define PACKED __attribute__((packed))
  1036. typedef struct PACKED dtc500_cmd_c2_param_struct
  1037. {
  1038. uint8_t StepPlusWidth; // Default is 13.6usec (11)
  1039. uint8_t StepPeriod; // Default is 3 msec.(60)
  1040. uint8_t StepMode; // Default is Bufferd (0)
  1041. uint8_t MaximumHeadAdress; // Default is 4 heads (3)
  1042. uint8_t HighCylinderAddressByte; // Default set to 0 (0)
  1043. uint8_t LowCylinderAddressByte; // Default is 153 cylinders (152)
  1044. uint8_t ReduceWrietCurrent; // Default is above Cylinder 128 (127)
  1045. uint8_t DriveType_SeekCompleteOption;// (0)
  1046. uint8_t Reserved8; // (0)
  1047. uint8_t Reserved9; // (0)
  1048. } DTC510_CMD_C2_PARAM;
  1049. static void logStrHex(const char *msg,uint32_t num)
  1050. {
  1051. LOG(msg);
  1052. LOGHEXN(num);
  1053. }
  1054. static byte dtc510b_setDriveparameter(void)
  1055. {
  1056. DTC510_CMD_C2_PARAM DriveParameter;
  1057. uint16_t maxCylinder;
  1058. uint16_t numLAD;
  1059. //uint32_t stepPulseUsec;
  1060. int StepPeriodMsec;
  1061. // receive paramter
  1062. writeDataPhase(sizeof(DriveParameter),(byte *)(&DriveParameter));
  1063. maxCylinder =
  1064. (((uint16_t)DriveParameter.HighCylinderAddressByte)<<8) |
  1065. (DriveParameter.LowCylinderAddressByte);
  1066. numLAD = maxCylinder * (DriveParameter.MaximumHeadAdress+1);
  1067. //stepPulseUsec = calcStepPulseUsec(DriveParameter.StepPlusWidth);
  1068. StepPeriodMsec = DriveParameter.StepPeriod*50;
  1069. logStrHex (" StepPlusWidth : ",DriveParameter.StepPlusWidth);
  1070. logStrHex (" StepPeriod : ",DriveParameter.StepPeriod );
  1071. logStrHex (" StepMode : ",DriveParameter.StepMode );
  1072. logStrHex (" MaximumHeadAdress : ",DriveParameter.MaximumHeadAdress);
  1073. logStrHex (" CylinderAddress : ",maxCylinder);
  1074. logStrHex (" ReduceWrietCurrent : ",DriveParameter.ReduceWrietCurrent);
  1075. logStrHex (" DriveType/SeekCompleteOption : ",DriveParameter.DriveType_SeekCompleteOption);
  1076. logStrHex (" Maximum LAD : ",numLAD-1);
  1077. return 0; // error result
  1078. }
  1079. #endif
  1080. /*
  1081. * MsgIn2.
  1082. */
  1083. void MsgIn2(int msg)
  1084. {
  1085. LOGN("MsgIn2");
  1086. SCSI_OUT(vMSG, active) // gpio_write(MSG, high);
  1087. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1088. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  1089. writeHandshake(msg);
  1090. }
  1091. /*
  1092. * MsgOut2.
  1093. */
  1094. void MsgOut2()
  1095. {
  1096. LOGN("MsgOut2");
  1097. SCSI_OUT(vMSG, active) // gpio_write(MSG, high);
  1098. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1099. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1100. m_msb[m_msc] = readHandshake();
  1101. m_msc++;
  1102. m_msc %= 256;
  1103. }
  1104. /*
  1105. * Main loop.
  1106. */
  1107. void loop()
  1108. {
  1109. //int msg = 0;
  1110. m_msg = 0;
  1111. // Wait until RST = H, BSY = H, SEL = L
  1112. do {} while( SCSI_IN(vBSY) || !SCSI_IN(vSEL) || SCSI_IN(vRST));
  1113. // BSY+ SEL-
  1114. // If the ID to respond is not driven, wait for the next
  1115. //byte db = readIO();
  1116. //byte scsiid = db & scsi_id_mask;
  1117. byte scsiid = readIO() & scsi_id_mask;
  1118. if((scsiid) == 0) {
  1119. delayMicroseconds(1);
  1120. return;
  1121. }
  1122. LOGN("Selection");
  1123. m_isBusReset = false;
  1124. // Set BSY to-when selected
  1125. SCSI_BSY_ACTIVE(); // Turn only BSY output ON, ACTIVE
  1126. // Ask for a TARGET-ID to respond
  1127. m_id = 31 - __builtin_clz(scsiid);
  1128. // Wait until SEL becomes inactive
  1129. while(isHigh(gpio_read(SEL)) && isLow(gpio_read(BSY))) {
  1130. if(m_isBusReset) {
  1131. goto BusFree;
  1132. }
  1133. }
  1134. SCSI_TARGET_ACTIVE() // (BSY), REQ, MSG, CD, IO output turned on
  1135. //
  1136. if(isHigh(gpio_read(ATN))) {
  1137. bool syncenable = false;
  1138. int syncperiod = 50;
  1139. int syncoffset = 0;
  1140. int loopWait = 0;
  1141. m_msc = 0;
  1142. memset(m_msb, 0x00, sizeof(m_msb));
  1143. while(isHigh(gpio_read(ATN)) && loopWait < 255) {
  1144. MsgOut2();
  1145. loopWait++;
  1146. }
  1147. for(int i = 0; i < m_msc; i++) {
  1148. // ABORT
  1149. if (m_msb[i] == 0x06) {
  1150. goto BusFree;
  1151. }
  1152. // BUS DEVICE RESET
  1153. if (m_msb[i] == 0x0C) {
  1154. syncoffset = 0;
  1155. goto BusFree;
  1156. }
  1157. // IDENTIFY
  1158. if (m_msb[i] >= 0x80) {
  1159. }
  1160. // Extended message
  1161. if (m_msb[i] == 0x01) {
  1162. // Check only when synchronous transfer is possible
  1163. if (!syncenable || m_msb[i + 2] != 0x01) {
  1164. MsgIn2(0x07);
  1165. break;
  1166. }
  1167. // Transfer period factor(50 x 4 = Limited to 200ns)
  1168. syncperiod = m_msb[i + 3];
  1169. if (syncperiod > 50) {
  1170. syncperiod = 50;
  1171. }
  1172. // REQ/ACK offset(Limited to 16)
  1173. syncoffset = m_msb[i + 4];
  1174. if (syncoffset > 16) {
  1175. syncoffset = 16;
  1176. }
  1177. // STDR response message generation
  1178. MsgIn2(0x01);
  1179. MsgIn2(0x03);
  1180. MsgIn2(0x01);
  1181. MsgIn2(syncperiod);
  1182. MsgIn2(syncoffset);
  1183. break;
  1184. }
  1185. }
  1186. }
  1187. LOG("Command:");
  1188. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1189. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1190. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1191. int len;
  1192. byte cmd[12];
  1193. cmd[0] = readHandshake(); if(m_isBusReset) goto BusFree;
  1194. LOGHEX(cmd[0]);
  1195. // Command length selection, reception
  1196. static const int cmd_class_len[8]={6,10,10,6,6,12,6,6};
  1197. len = cmd_class_len[cmd[0] >> 5];
  1198. cmd[1] = readHandshake(); LOG(":");LOGHEX(cmd[1]); if(m_isBusReset) goto BusFree;
  1199. cmd[2] = readHandshake(); LOG(":");LOGHEX(cmd[2]); if(m_isBusReset) goto BusFree;
  1200. cmd[3] = readHandshake(); LOG(":");LOGHEX(cmd[3]); if(m_isBusReset) goto BusFree;
  1201. cmd[4] = readHandshake(); LOG(":");LOGHEX(cmd[4]); if(m_isBusReset) goto BusFree;
  1202. cmd[5] = readHandshake(); LOG(":");LOGHEX(cmd[5]); if(m_isBusReset) goto BusFree;
  1203. // Receive the remaining commands
  1204. for(int i = 6; i < len; i++ ) {
  1205. cmd[i] = readHandshake();
  1206. LOG(":");
  1207. LOGHEX(cmd[i]);
  1208. if(m_isBusReset) goto BusFree;
  1209. }
  1210. // LUN confirmation
  1211. m_sts = cmd[1]&0xe0; // Preset LUN in status byte
  1212. m_lun = m_sts>>5;
  1213. // HDD Image selection
  1214. m_img = (HDDIMG *)0; // None
  1215. if( (m_lun <= NUM_SCSILUN) )
  1216. {
  1217. m_img = &(img[m_id][m_lun]); // There is an image
  1218. if(!(m_img->m_file.isOpen()))
  1219. m_img = (HDDIMG *)0; // Image absent
  1220. }
  1221. // if(!m_img) m_sts |= 0x02; // Missing image file for LUN
  1222. //LOGHEX(((uint32_t)m_img));
  1223. LOG(":ID ");
  1224. LOG(m_id);
  1225. LOG(":LUN ");
  1226. LOG(m_lun);
  1227. LOGN("");
  1228. switch(cmd[0]) {
  1229. case 0x00:
  1230. LOGN("[Test Unit]");
  1231. break;
  1232. case 0x01:
  1233. LOGN("[Rezero Unit]");
  1234. break;
  1235. case 0x03:
  1236. LOGN("[RequestSense]");
  1237. onRequestSenseCommand(cmd[4]);
  1238. break;
  1239. case 0x04:
  1240. LOGN("[FormatUnit]");
  1241. break;
  1242. case 0x06:
  1243. LOGN("[FormatUnit]");
  1244. break;
  1245. case 0x07:
  1246. LOGN("[ReassignBlocks]");
  1247. break;
  1248. case 0x08:
  1249. LOGN("[Read6]");
  1250. m_sts |= onReadCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
  1251. break;
  1252. case 0x0A:
  1253. LOGN("[Write6]");
  1254. m_sts |= onWriteCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
  1255. break;
  1256. case 0x0B:
  1257. LOGN("[Seek6]");
  1258. break;
  1259. case 0x12:
  1260. LOGN("[Inquiry]");
  1261. m_sts |= onInquiryCommand(cmd[4]);
  1262. break;
  1263. case 0x1A:
  1264. LOGN("[ModeSense6]");
  1265. m_sts |= onModeSenseCommand(cmd[0], cmd[1]&0x80, cmd[2], cmd[4]);
  1266. break;
  1267. case 0x1B:
  1268. LOGN("[StartStopUnit]");
  1269. break;
  1270. case 0x1E:
  1271. LOGN("[PreAllowMed.Removal]");
  1272. break;
  1273. case 0x25:
  1274. LOGN("[ReadCapacity]");
  1275. m_sts |= onReadCapacityCommand(cmd[8]);
  1276. break;
  1277. case 0x28:
  1278. LOGN("[Read10]");
  1279. m_sts |= onReadCommand(((uint32_t)cmd[2] << 24) | ((uint32_t)cmd[3] << 16) | ((uint32_t)cmd[4] << 8) | cmd[5], ((uint32_t)cmd[7] << 8) | cmd[8]);
  1280. break;
  1281. case 0x2A:
  1282. LOGN("[Write10]");
  1283. m_sts |= onWriteCommand(((uint32_t)cmd[2] << 24) | ((uint32_t)cmd[3] << 16) | ((uint32_t)cmd[4] << 8) | cmd[5], ((uint32_t)cmd[7] << 8) | cmd[8]);
  1284. break;
  1285. case 0x2B:
  1286. LOGN("[Seek10]");
  1287. break;
  1288. case 0x5A:
  1289. LOGN("[ModeSense10]");
  1290. m_sts |= onModeSenseCommand(cmd[0], cmd[1] & 0x80, cmd[2], ((uint32_t)cmd[7] << 8) | cmd[8]);
  1291. break;
  1292. #if SCSI_SELECT == 1
  1293. case 0xc2:
  1294. LOGN("[DTC510B setDriveParameter]");
  1295. m_sts |= dtc510b_setDriveparameter();
  1296. break;
  1297. #endif
  1298. default:
  1299. LOGN("[*Unknown]");
  1300. m_sts |= 0x02;
  1301. m_senseKey = 5; // Illegal request
  1302. m_addition_sense = 0x2000; // Invalid Command Operation Code
  1303. break;
  1304. }
  1305. if(m_isBusReset) {
  1306. goto BusFree;
  1307. }
  1308. LOGN("Sts");
  1309. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1310. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1311. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  1312. writeHandshake(m_sts);
  1313. if(m_isBusReset) {
  1314. goto BusFree;
  1315. }
  1316. LOGN("MsgIn");
  1317. SCSI_OUT(vMSG, active) // gpio_write(MSG, high);
  1318. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1319. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  1320. writeHandshake(m_msg);
  1321. BusFree:
  1322. LOGN("BusFree");
  1323. m_isBusReset = false;
  1324. //SCSI_OUT(vREQ,inactive) // gpio_write(REQ, low);
  1325. //SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1326. //SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  1327. //SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1328. //SCSI_OUT(vBSY,inactive)
  1329. SCSI_TARGET_INACTIVE() // Turn off BSY, REQ, MSG, CD, IO output
  1330. }