BlueSCSI.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  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. #include <setjmp.h>
  40. #ifdef USE_STM32_DMA
  41. #warning "warning USE_STM32_DMA"
  42. #endif
  43. #define DEBUG 0 // 0:No debug information output
  44. // 1: Debug information output to USB Serial
  45. // 2: Debug information output to LOG.txt (slow)
  46. #define SCSI_SELECT 0 // 0 for STANDARD
  47. // 1 for SHARP X1turbo
  48. // 2 for NEC PC98
  49. #define READ_SPEED_OPTIMIZE 1 // Faster reads
  50. #define WRITE_SPEED_OPTIMIZE 1 // Speeding up writes
  51. #define XCVR 1 // 0 for standard mode
  52. // 1 for transceiver hardware
  53. // SCSI config
  54. #define NUM_SCSIID 7 // Maximum number of supported SCSI-IDs (The minimum is 0)
  55. #define NUM_SCSILUN 2 // Maximum number of LUNs supported (The minimum is 0)
  56. #define READ_PARITY_CHECK 0 // Perform read parity check (unverified)
  57. // HDD format
  58. #define MAX_BLOCKSIZE 2048 // Maximum BLOCK size
  59. // SDFAT
  60. SdFs SD;
  61. #if DEBUG == 1
  62. #define LOG(XX) Serial.print(XX)
  63. #define LOGHEX(XX) Serial.print(XX, HEX)
  64. #define LOGN(XX) Serial.println(XX)
  65. #define LOGHEXN(XX) Serial.println(XX, HEX)
  66. #elif DEBUG == 2
  67. #define LOG(XX) LOG_FILE.print(XX); LOG_FILE.sync();
  68. #define LOGHEX(XX) LOG_FILE.print(XX, HEX); LOG_FILE.sync();
  69. #define LOGN(XX) LOG_FILE.println(XX); LOG_FILE.sync();
  70. #define LOGHEXN(XX) LOG_FILE.println(XX, HEX); LOG_FILE.sync();
  71. #else
  72. #define LOG(XX) //Serial.print(XX)
  73. #define LOGHEX(XX) //Serial.print(XX, HEX)
  74. #define LOGN(XX) //Serial.println(XX)
  75. #define LOGHEXN(XX) //Serial.println(XX, HEX)
  76. #endif
  77. #define active 1
  78. #define inactive 0
  79. #define high 0
  80. #define low 1
  81. #define isHigh(XX) ((XX) == high)
  82. #define isLow(XX) ((XX) != high)
  83. #define gpio_mode(pin,val) gpio_set_mode(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, val);
  84. #define gpio_write(pin,val) gpio_write_bit(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, val)
  85. #define gpio_read(pin) gpio_read_bit(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit)
  86. //#define DB0 PB8 // SCSI:DB0
  87. //#define DB1 PB9 // SCSI:DB1
  88. //#define DB2 PB10 // SCSI:DB2
  89. //#define DB3 PB11 // SCSI:DB3
  90. //#define DB4 PB12 // SCSI:DB4
  91. //#define DB5 PB13 // SCSI:DB5
  92. //#define DB6 PB14 // SCSI:DB6
  93. //#define DB7 PB15 // SCSI:DB7
  94. //#define DBP PB0 // SCSI:DBP
  95. #define ATN PA8 // SCSI:ATN
  96. #define BSY PA9 // SCSI:BSY
  97. #define ACK PA10 // SCSI:ACK
  98. #define RST PA15 // SCSI:RST
  99. #define MSG PB3 // SCSI:MSG
  100. #define SEL PB4 // SCSI:SEL
  101. #define CD PB5 // SCSI:C/D
  102. #define REQ PB6 // SCSI:REQ
  103. #define IO PB7 // SCSI:I/O
  104. #define LED2 PA0 // External LED
  105. #define SD_CS PA4 // SDCARD:CS
  106. #define LED PC13 // LED
  107. // Image Set Selector
  108. #if XCVR == 1
  109. #define IMAGE_SELECT1 PC14
  110. #define IMAGE_SELECT2 PC15
  111. #else
  112. #define IMAGE_SELECT1 PA1
  113. #define IMAGE_SELECT2 PB1
  114. #endif
  115. // GPIO register port
  116. #define PAREG GPIOA->regs
  117. #define PBREG GPIOB->regs
  118. // LED control
  119. #define LED_ON() gpio_write(LED, high); gpio_write(LED2, low);
  120. #define LED_OFF() gpio_write(LED, low); gpio_write(LED2, high);
  121. // Virtual pin (Arduio compatibility is slow, so make it MCU-dependent)
  122. #define PA(BIT) (BIT)
  123. #define PB(BIT) (BIT+16)
  124. // Virtual pin decoding
  125. #define GPIOREG(VPIN) ((VPIN)>=16?PBREG:PAREG)
  126. #define BITMASK(VPIN) (1<<((VPIN)&15))
  127. #define vATN PA(8) // SCSI:ATN
  128. #define vBSY PA(9) // SCSI:BSY
  129. #define vACK PA(10) // SCSI:ACK
  130. #define vRST PA(15) // SCSI:RST
  131. #define vMSG PB(3) // SCSI:MSG
  132. #define vSEL PB(4) // SCSI:SEL
  133. #define vCD PB(5) // SCSI:C/D
  134. #define vREQ PB(6) // SCSI:REQ
  135. #define vIO PB(7) // SCSI:I/O
  136. #define vSD_CS PA(4) // SDCARD:CS
  137. // SCSI output pin control: opendrain active LOW (direct pin drive)
  138. #define SCSI_OUT(VPIN,ACTIVE) { GPIOREG(VPIN)->BSRR = BITMASK(VPIN)<<((ACTIVE)?16:0); }
  139. // SCSI input pin check (inactive=0,avtive=1)
  140. #define SCSI_IN(VPIN) ((~GPIOREG(VPIN)->IDR>>(VPIN&15))&1)
  141. #if XCVR == 1
  142. #define TR_TARGET PA1 // Target Transceiver Control Pin
  143. #define TR_DBP PA2 // Data Pins Transceiver Control Pin
  144. #define TR_INITIATOR PA3 // Initiator Transciever Control Pin
  145. #define vTR_TARGET PA(1) // Target Transceiver Control Pin
  146. #define vTR_DBP PA(2) // Data Pins Transceiver Control Pin
  147. #define vTR_INITIATOR PA(3) // Initiator Transciever Control Pin
  148. #define TR_INPUT 1
  149. #define TR_OUTPUT 0
  150. // Transceiver control definitions
  151. #define TRANSCEIVER_IO_SET(VPIN,TR_INPUT) { GPIOREG(VPIN)->BSRR = BITMASK(VPIN) << ((TR_INPUT) ? 16 : 0); }
  152. // Turn on the output only for BSY
  153. #define SCSI_BSY_ACTIVE() { gpio_mode(BSY, GPIO_OUTPUT_PP); SCSI_OUT(vBSY, active) }
  154. // BSY,REQ,MSG,CD,IO Turn off output, BSY is the last input
  155. #define SCSI_TARGET_INACTIVE() { gpio_mode(REQ, GPIO_INPUT_FLOATING); gpio_mode(MSG, GPIO_INPUT_FLOATING); gpio_mode(CD, GPIO_INPUT_FLOATING); gpio_mode(IO, GPIO_INPUT_FLOATING); gpio_mode(BSY, GPIO_INPUT_FLOATING); TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT); }
  156. #define DB_MODE_OUT 1 // push-pull mode
  157. #define DB_MODE_IN 4 // floating inputs
  158. #else
  159. // Turn on the output only for BSY
  160. #define SCSI_BSY_ACTIVE() { gpio_mode(BSY, GPIO_OUTPUT_OD); SCSI_OUT(vBSY, active) }
  161. // BSY,REQ,MSG,CD,IO Turn off output, BSY is the last input
  162. #define SCSI_TARGET_INACTIVE() { if (DB_MODE_OUT == 7) SCSI_OUT(vREQ,inactive) else { if (DB_MODE_IN == 8) gpio_mode(REQ, GPIO_INPUT_PU) else gpio_mode(REQ, GPIO_INPUT_FLOATING)} SCSI_OUT(vMSG,inactive); SCSI_OUT(vCD,inactive);SCSI_OUT(vIO,inactive); gpio_mode(BSY, GPIO_INPUT_PU); }
  163. // GPIO mode
  164. // IN , FLOAT : 4
  165. // IN , PU/PD : 8
  166. // OUT, PUSH/PULL : 3
  167. // OUT, OD : 7
  168. #define DB_MODE_OUT 3
  169. //#define DB_MODE_OUT 7
  170. #define DB_MODE_IN 8
  171. #endif
  172. // Put DB and DP in output mode
  173. #define SCSI_DB_OUTPUT() { PBREG->CRL=(PBREG->CRL &0xfffffff0)|DB_MODE_OUT; PBREG->CRH = 0x11111111*DB_MODE_OUT; }
  174. // Put DB and DP in input mode
  175. #define SCSI_DB_INPUT() { PBREG->CRL=(PBREG->CRL &0xfffffff0)|DB_MODE_IN ; PBREG->CRH = 0x11111111*DB_MODE_IN; if (DB_MODE_IN == 8) PBREG->BSRR = 0xFF01;}
  176. // HDDiamge file
  177. #define HDIMG_ID_POS 2 // Position to embed ID number
  178. #define HDIMG_LUN_POS 3 // Position to embed LUN numbers
  179. #define HDIMG_BLK_POS 5 // Position to embed block size numbers
  180. #define MAX_FILE_PATH 32 // Maximum file name length
  181. // HDD image
  182. typedef struct hddimg_struct
  183. {
  184. FsFile m_file; // File object
  185. uint64_t m_fileSize; // File size
  186. size_t m_blocksize; // SCSI BLOCK size
  187. }HDDIMG;
  188. HDDIMG img[NUM_SCSIID][NUM_SCSILUN]; // Maximum number
  189. uint8_t m_senseKey = 0; // Sense key
  190. uint16_t m_addition_sense = 0; // Additional sense information
  191. volatile bool m_isBusReset = false; // Bus reset
  192. volatile bool m_resetJmp = false; // Call longjmp on reset
  193. jmp_buf m_resetJmpBuf;
  194. byte scsi_id_mask; // Mask list of responding SCSI IDs
  195. byte m_id; // Currently responding SCSI-ID
  196. byte m_lun; // Logical unit number currently responding
  197. byte m_sts; // Status byte
  198. byte m_msg; // Message bytes
  199. HDDIMG *m_img; // HDD image for current SCSI-ID, LUN
  200. byte m_buf[MAX_BLOCKSIZE]; // General purpose buffer
  201. int m_msc;
  202. byte m_msb[256]; // Command storage bytes
  203. /*
  204. * Data byte to BSRR register setting value and parity table
  205. */
  206. // Parity bit generation
  207. #define PTY(V) (1^((V)^((V)>>1)^((V)>>2)^((V)>>3)^((V)>>4)^((V)>>5)^((V)>>6)^((V)>>7))&1)
  208. // Data byte to BSRR register setting value conversion table
  209. // BSRR[31:24] = DB[7:0]
  210. // BSRR[ 16] = PTY(DB)
  211. // BSRR[15: 8] = ~DB[7:0]
  212. // BSRR[ 0] = ~PTY(DB)
  213. // Set DBP, set REQ = inactive
  214. #define DBP(D) ((((((uint32_t)(D)<<8)|PTY(D))*0x00010001)^0x0000ff01)|BITMASK(vREQ))
  215. // BSRR register control value that simultaneously performs DB set, DP set, and REQ = H (inactrive)
  216. uint32_t db_bsrr[256];
  217. // Parity bit acquisition
  218. #define PARITY(DB) (db_bsrr[DB]&1)
  219. // Macro cleaning
  220. #undef DBP32
  221. #undef DBP8
  222. //#undef DBP
  223. //#undef PTY
  224. // Log File
  225. #define VERSION "1.1-SNAPSHOT-20220407"
  226. #define LOG_FILENAME "LOG.txt"
  227. FsFile LOG_FILE;
  228. // SCSI Drive Vendor information
  229. byte SCSI_INFO_BUF[36] = {
  230. 0x00, //device type
  231. 0x00, //RMB = 0
  232. 0x01, //ISO, ECMA, ANSI version
  233. 0x01, //Response data format
  234. 35 - 4, //Additional data length
  235. 0, 0, //Reserve
  236. 0x00, //Support function
  237. 'Q', 'U', 'A', 'N', 'T', 'U', 'M', ' ', // vendor 8
  238. 'F', 'I', 'R', 'E', 'B', 'A', 'L', 'L', '1', ' ', ' ',' ', ' ', ' ', ' ', ' ', // product 16
  239. '1', '.', '0', ' ' // version 4
  240. };
  241. void onFalseInit(void);
  242. void noSDCardFound(void);
  243. void onBusReset(void);
  244. void initFileLog(int);
  245. void finalizeFileLog(void);
  246. void findDriveImages(FsFile root);
  247. /*
  248. * IO read.
  249. */
  250. inline byte readIO(void)
  251. {
  252. // Port input data register
  253. uint32_t ret = GPIOB->regs->IDR;
  254. byte bret = (byte)(~(ret>>8));
  255. #if READ_PARITY_CHECK
  256. if((db_bsrr[bret]^ret)&1)
  257. m_sts |= 0x01; // parity error
  258. #endif
  259. return bret;
  260. }
  261. // If config file exists, read the first three lines and copy the contents.
  262. // File must be well formed or you will get junk in the SCSI Vendor fields.
  263. void readSCSIDeviceConfig() {
  264. FsFile config_file = SD.open("scsi-config.txt", O_RDONLY);
  265. if (!config_file.isOpen()) {
  266. return;
  267. }
  268. char vendor[9];
  269. memset(vendor, 0, sizeof(vendor));
  270. config_file.readBytes(vendor, sizeof(vendor));
  271. LOG_FILE.print("SCSI VENDOR: ");
  272. LOG_FILE.println(vendor);
  273. memcpy(&(SCSI_INFO_BUF[8]), vendor, 8);
  274. char product[17];
  275. memset(product, 0, sizeof(product));
  276. config_file.readBytes(product, sizeof(product));
  277. LOG_FILE.print("SCSI PRODUCT: ");
  278. LOG_FILE.println(product);
  279. memcpy(&(SCSI_INFO_BUF[16]), product, 16);
  280. char version[5];
  281. memset(version, 0, sizeof(version));
  282. config_file.readBytes(version, sizeof(version));
  283. LOG_FILE.print("SCSI VERSION: ");
  284. LOG_FILE.println(version);
  285. memcpy(&(SCSI_INFO_BUF[32]), version, 4);
  286. config_file.close();
  287. }
  288. // read SD information and print to logfile
  289. void readSDCardInfo()
  290. {
  291. cid_t sd_cid;
  292. if(SD.card()->readCID(&sd_cid))
  293. {
  294. LOG_FILE.print("Sd MID:");
  295. LOG_FILE.print(sd_cid.mid, 16);
  296. LOG_FILE.print(" OID:");
  297. LOG_FILE.print(sd_cid.oid[0]);
  298. LOG_FILE.println(sd_cid.oid[1]);
  299. LOG_FILE.print("Sd Name:");
  300. LOG_FILE.print(sd_cid.pnm[0]);
  301. LOG_FILE.print(sd_cid.pnm[1]);
  302. LOG_FILE.print(sd_cid.pnm[2]);
  303. LOG_FILE.print(sd_cid.pnm[3]);
  304. LOG_FILE.println(sd_cid.pnm[4]);
  305. LOG_FILE.print("Sd Date:");
  306. LOG_FILE.print(sd_cid.mdt_month);
  307. LOG_FILE.print("/20"); // CID year is 2000 + high/low
  308. LOG_FILE.print(sd_cid.mdt_year_high);
  309. LOG_FILE.println(sd_cid.mdt_year_low);
  310. LOG_FILE.print("Sd Serial:");
  311. LOG_FILE.println(sd_cid.psn);
  312. LOG_FILE.sync();
  313. }
  314. }
  315. /*
  316. * Open HDD image file
  317. */
  318. bool hddimageOpen(HDDIMG *h, FsFile file,int id,int lun,int blocksize)
  319. {
  320. h->m_fileSize = 0;
  321. h->m_blocksize = blocksize;
  322. h->m_file = file;
  323. if(h->m_file.isOpen())
  324. {
  325. h->m_fileSize = h->m_file.size();
  326. if(h->m_fileSize>0)
  327. {
  328. // check blocksize dummy file
  329. LOG_FILE.print(" / ");
  330. LOG_FILE.print(h->m_fileSize);
  331. LOG_FILE.print("bytes / ");
  332. LOG_FILE.print(h->m_fileSize / 1024);
  333. LOG_FILE.print("KiB / ");
  334. LOG_FILE.print(h->m_fileSize / 1024 / 1024);
  335. LOG_FILE.println("MiB");
  336. return true; // File opened
  337. }
  338. else
  339. {
  340. LOG_FILE.println(" - file is 0 bytes, can not use.");
  341. h->m_file.close();
  342. h->m_fileSize = h->m_blocksize = 0; // no file
  343. }
  344. }
  345. return false;
  346. }
  347. /*
  348. * Initialization.
  349. * Initialize the bus and set the PIN orientation
  350. */
  351. void setup()
  352. {
  353. // PA15 / PB3 / PB4 Cannot be used
  354. // JTAG Because it is used for debugging.
  355. disableDebugPorts();
  356. // Setup BSRR table
  357. for (unsigned i = 0; i <= 255; i++) {
  358. db_bsrr[i] = DBP(i);
  359. }
  360. // Serial initialization
  361. #if DEBUG > 0
  362. Serial.begin(9600);
  363. // If using a USB->TTL monitor instead of USB serial monitor - you can uncomment this.
  364. //while (!Serial);
  365. #endif
  366. // PIN initialization
  367. gpio_mode(LED2, GPIO_OUTPUT_PP);
  368. gpio_mode(LED, GPIO_OUTPUT_OD);
  369. // Image Set Select Init
  370. gpio_mode(IMAGE_SELECT1, GPIO_INPUT_PU);
  371. gpio_mode(IMAGE_SELECT2, GPIO_INPUT_PU);
  372. pinMode(IMAGE_SELECT1, INPUT);
  373. pinMode(IMAGE_SELECT2, INPUT);
  374. int image_file_set = ((digitalRead(IMAGE_SELECT1) == LOW) ? 1 : 0) | ((digitalRead(IMAGE_SELECT2) == LOW) ? 2 : 0);
  375. LED_OFF();
  376. #if XCVR == 1
  377. // Transceiver Pin Initialization
  378. gpio_mode(TR_TARGET, GPIO_OUTPUT_PP);
  379. gpio_mode(TR_INITIATOR, GPIO_OUTPUT_PP);
  380. gpio_mode(TR_DBP, GPIO_OUTPUT_PP);
  381. TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT);
  382. #endif
  383. //GPIO(SCSI BUS)Initialization
  384. //Port setting register (lower)
  385. // GPIOB->regs->CRL |= 0x000000008; // SET INPUT W/ PUPD on PAB-PB0
  386. //Port setting register (upper)
  387. //GPIOB->regs->CRH = 0x88888888; // SET INPUT W/ PUPD on PB15-PB8
  388. // GPIOB->regs->ODR = 0x0000FF00; // SET PULL-UPs on PB15-PB8
  389. // DB and DP are input modes
  390. SCSI_DB_INPUT()
  391. #if XCVR == 1
  392. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT);
  393. // Initiator port
  394. gpio_mode(ATN, GPIO_INPUT_FLOATING);
  395. gpio_mode(BSY, GPIO_INPUT_FLOATING);
  396. gpio_mode(ACK, GPIO_INPUT_FLOATING);
  397. gpio_mode(RST, GPIO_INPUT_FLOATING);
  398. gpio_mode(SEL, GPIO_INPUT_FLOATING);
  399. TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT);
  400. // Target port
  401. gpio_mode(MSG, GPIO_INPUT_FLOATING);
  402. gpio_mode(CD, GPIO_INPUT_FLOATING);
  403. gpio_mode(REQ, GPIO_INPUT_FLOATING);
  404. gpio_mode(IO, GPIO_INPUT_FLOATING);
  405. TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT);
  406. #else
  407. // Input port
  408. gpio_mode(ATN, GPIO_INPUT_PU);
  409. gpio_mode(BSY, GPIO_INPUT_PU);
  410. gpio_mode(ACK, GPIO_INPUT_PU);
  411. gpio_mode(RST, GPIO_INPUT_PU);
  412. gpio_mode(SEL, GPIO_INPUT_PU);
  413. // Output port
  414. gpio_mode(MSG, GPIO_OUTPUT_OD);
  415. gpio_mode(CD, GPIO_OUTPUT_OD);
  416. gpio_mode(REQ, GPIO_OUTPUT_OD);
  417. gpio_mode(IO, GPIO_OUTPUT_OD);
  418. #endif
  419. // Turn off the output port
  420. SCSI_TARGET_INACTIVE()
  421. //Occurs when the RST pin state changes from HIGH to LOW
  422. //attachInterrupt(RST, onBusReset, FALLING);
  423. // Try different clock speeds till we find one that is stable.
  424. LED_ON();
  425. int mhz = 50;
  426. bool sd_ready = false;
  427. while (mhz >= 32 && !sd_ready) {
  428. if(SD.begin(SdSpiConfig(PA4, DEDICATED_SPI, SD_SCK_MHZ(mhz), &SPI))) {
  429. sd_ready = true;
  430. }
  431. else {
  432. mhz--;
  433. }
  434. }
  435. LED_OFF();
  436. if(!sd_ready) {
  437. #if DEBUG > 0
  438. Serial.println("SD initialization failed!");
  439. #endif
  440. noSDCardFound();
  441. }
  442. initFileLog(mhz);
  443. readSCSIDeviceConfig();
  444. readSDCardInfo();
  445. //HD image file open
  446. scsi_id_mask = 0x00;
  447. // Iterate over the root path in the SD card looking for candidate image files.
  448. FsFile root;
  449. char image_set_dir_name[] = "/ImageSetX/";
  450. image_set_dir_name[9] = char(image_file_set) + 0x30;
  451. root.open(image_set_dir_name);
  452. if (root.isDirectory()) {
  453. LOG_FILE.print("Looking for images in: ");
  454. LOG_FILE.println(image_set_dir_name);
  455. LOG_FILE.sync();
  456. } else {
  457. root.close();
  458. root.open("/");
  459. }
  460. findDriveImages(root);
  461. root.close();
  462. FsFile images_all_dir;
  463. images_all_dir.open("/ImageSetAll/");
  464. if (images_all_dir.isDirectory()) {
  465. LOG_FILE.println("Looking for images in: /ImageSetAll/");
  466. LOG_FILE.sync();
  467. findDriveImages(images_all_dir);
  468. }
  469. images_all_dir.close();
  470. // Error if there are 0 image files
  471. if(scsi_id_mask==0) {
  472. LOG_FILE.println("ERROR: No valid images found!");
  473. onFalseInit();
  474. }
  475. finalizeFileLog();
  476. LED_OFF();
  477. //Occurs when the RST pin state changes from HIGH to LOW
  478. attachInterrupt(RST, onBusReset, FALLING);
  479. }
  480. void findDriveImages(FsFile root) {
  481. bool image_ready;
  482. FsFile file;
  483. char path_name[MAX_FILE_PATH+1];
  484. root.getName(path_name, sizeof(path_name));
  485. SD.chdir(path_name);
  486. while (1) {
  487. // Directories can not be opened RDWR, so it will fail, but fails the same way with no file/dir, so we need to peek at the file first.
  488. FsFile file_test = root.openNextFile(O_RDONLY);
  489. char name[MAX_FILE_PATH+1];
  490. file_test.getName(name, MAX_FILE_PATH+1);
  491. String file_name = String(name);
  492. // Skip directories and already open files.
  493. if(file_test.isDir() || file_name.startsWith("LOG.txt")) {
  494. file_test.close();
  495. continue;
  496. }
  497. // If error there is no next file to open.
  498. if(file_test.getError() > 0) {
  499. file_test.close();
  500. break;
  501. }
  502. // Valid file, open for reading/writing.
  503. file = SD.open(name, O_RDWR);
  504. if(file && file.isFile()) {
  505. file_name.toLowerCase();
  506. if(file_name.startsWith("hd")) {
  507. // Defaults for Hard Disks
  508. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  509. int lun = 0;
  510. int blk = 512;
  511. // Positionally read in and coerase the chars to integers.
  512. // We only require the minimum and read in the next if provided.
  513. int file_name_length = file_name.length();
  514. if(file_name_length > 2) { // HD[N]
  515. int tmp_id = name[HDIMG_ID_POS] - '0';
  516. // If valid id, set it, else use default
  517. if(tmp_id > -1 && tmp_id < 8) {
  518. id = tmp_id;
  519. } else {
  520. LOG_FILE.print(name);
  521. LOG_FILE.println(" - bad SCSI id in filename, Using default ID 1");
  522. }
  523. }
  524. int blk1 = 0, blk2, blk3, blk4 = 0;
  525. if(file_name_length > 8) { // HD00_[111]
  526. blk1 = name[HDIMG_BLK_POS] - '0';
  527. blk2 = name[HDIMG_BLK_POS+1] - '0';
  528. blk3 = name[HDIMG_BLK_POS+2] - '0';
  529. if(file_name_length > 9) // HD00_NNN[1]
  530. blk4 = name[HDIMG_BLK_POS+3] - '0';
  531. }
  532. if(blk1 == 2 && blk2 == 5 && blk3 == 6) {
  533. blk = 256;
  534. } else if(blk1 == 1 && blk2 == 0 && blk3 == 2 && blk4 == 4) {
  535. blk = 1024;
  536. } else if(blk1 == 2 && blk2 == 0 && blk3 == 4 && blk4 == 8) {
  537. blk = 2048;
  538. }
  539. if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  540. HDDIMG *h = &img[id][lun];
  541. LOG_FILE.print(" - ");
  542. LOG_FILE.print(name);
  543. image_ready = hddimageOpen(h, file, id, lun, blk);
  544. if(image_ready) { // Marked as a responsive ID
  545. scsi_id_mask |= 1<<id;
  546. }
  547. }
  548. }
  549. } else {
  550. file.close();
  551. LOG_FILE.print("Not an image: ");
  552. LOG_FILE.println(name);
  553. }
  554. LOG_FILE.sync();
  555. }
  556. // cd .. before going back.
  557. SD.chdir("/");
  558. }
  559. /*
  560. * Setup initialization logfile
  561. */
  562. void initFileLog(int success_mhz) {
  563. LOG_FILE = SD.open(LOG_FILENAME, O_WRONLY | O_CREAT | O_TRUNC);
  564. LOG_FILE.println("BlueSCSI <-> SD - https://github.com/erichelgeson/BlueSCSI");
  565. LOG_FILE.print("VERSION: ");
  566. LOG_FILE.println(VERSION);
  567. LOG_FILE.print("DEBUG:");
  568. LOG_FILE.print(DEBUG);
  569. LOG_FILE.print(" SCSI_SELECT:");
  570. LOG_FILE.print(SCSI_SELECT);
  571. LOG_FILE.print(" SDFAT_FILE_TYPE:");
  572. LOG_FILE.println(SDFAT_FILE_TYPE);
  573. LOG_FILE.print("SdFat version: ");
  574. LOG_FILE.println(SD_FAT_VERSION_STR);
  575. LOG_FILE.print("SPI speed: ");
  576. LOG_FILE.print(success_mhz);
  577. LOG_FILE.println("Mhz");
  578. if(success_mhz < 40) {
  579. LOG_FILE.println("SPI under 40Mhz - read https://github.com/erichelgeson/BlueSCSI/wiki/Slow-SPI");
  580. }
  581. LOG_FILE.print("SdFat Max FileName Length: ");
  582. LOG_FILE.println(MAX_FILE_PATH);
  583. LOG_FILE.println("Initialized SD Card - lets go!");
  584. LOG_FILE.sync();
  585. }
  586. /*
  587. * Finalize initialization logfile
  588. */
  589. void finalizeFileLog() {
  590. // View support drive map
  591. LOG_FILE.print("ID");
  592. for(int lun=0;lun<NUM_SCSILUN;lun++)
  593. {
  594. LOG_FILE.print(":LUN");
  595. LOG_FILE.print(lun);
  596. }
  597. LOG_FILE.println(":");
  598. //
  599. for(int id=0;id<NUM_SCSIID;id++)
  600. {
  601. LOG_FILE.print(" ");
  602. LOG_FILE.print(id);
  603. for(int lun=0;lun<NUM_SCSILUN;lun++)
  604. {
  605. HDDIMG *h = &img[id][lun];
  606. if( (lun<NUM_SCSILUN) && (h->m_file))
  607. {
  608. LOG_FILE.print((h->m_blocksize<1000) ? ": " : ":");
  609. LOG_FILE.print(h->m_blocksize);
  610. }
  611. else
  612. LOG_FILE.print(":----");
  613. }
  614. LOG_FILE.println(":");
  615. }
  616. LOG_FILE.println("Finished initialization of SCSI Devices - Entering main loop.");
  617. LOG_FILE.sync();
  618. LOG_FILE.close();
  619. }
  620. /*
  621. * Initialization failed, blink 3x fast
  622. */
  623. void onFalseInit(void)
  624. {
  625. LOG_FILE.sync();
  626. while(true) {
  627. for(int i = 0; i < 3; i++) {
  628. LED_ON();
  629. delay(250);
  630. LED_OFF();
  631. delay(250);
  632. }
  633. delay(3000);
  634. }
  635. }
  636. /*
  637. * No SC Card found, blink 5x fast
  638. */
  639. void noSDCardFound(void)
  640. {
  641. while(true) {
  642. for(int i = 0; i < 5; i++) {
  643. LED_ON();
  644. delay(250);
  645. LED_OFF();
  646. delay(250);
  647. }
  648. delay(3000);
  649. }
  650. }
  651. /*
  652. * Return from exception and call longjmp
  653. */
  654. void __attribute__ ((noinline)) longjmpFromInterrupt(jmp_buf jmpb, int retval) __attribute__ ((noreturn));
  655. void longjmpFromInterrupt(jmp_buf jmpb, int retval) {
  656. // Address of longjmp with the thumb bit cleared
  657. const uint32_t longjmpaddr = ((uint32_t)longjmp) & 0xfffffffe;
  658. const uint32_t zero = 0;
  659. // Default PSR value, function calls don't require any particular value
  660. const uint32_t PSR = 0x01000000;
  661. // For documentation on what this is doing, see:
  662. // https://developer.arm.com/documentation/dui0552/a/the-cortex-m3-processor/exception-model/exception-entry-and-return
  663. // Stack frame needs to have R0-R3, R12, LR, PC, PSR (from bottom to top)
  664. // This is being set up to have R0 and R1 contain the parameters passed to longjmp, and PC is the address of the longjmp function.
  665. // This is using existing stack space, rather than allocating more, as longjmp is just going to unroll the stack even further.
  666. // 0xfffffff9 is the EXC_RETURN value to return to thread mode.
  667. asm (
  668. "str %0, [sp];\
  669. str %1, [sp, #4];\
  670. str %2, [sp, #8];\
  671. str %2, [sp, #12];\
  672. str %2, [sp, #16];\
  673. str %2, [sp, #20];\
  674. str %3, [sp, #24];\
  675. str %4, [sp, #28];\
  676. ldr lr, =0xfffffff9;\
  677. bx lr"
  678. :: "r"(jmpb),"r"(retval),"r"(zero), "r"(longjmpaddr), "r"(PSR)
  679. );
  680. }
  681. /*
  682. * Bus reset interrupt.
  683. */
  684. void onBusReset(void)
  685. {
  686. #if SCSI_SELECT == 1
  687. // SASI I / F for X1 turbo has RST pulse write cycle +2 clock ==
  688. // I can't filter because it only activates about 1.25us
  689. {{
  690. #else
  691. if(isHigh(gpio_read(RST))) {
  692. delayMicroseconds(20);
  693. if(isHigh(gpio_read(RST))) {
  694. #endif
  695. // BUS FREE is done in the main process
  696. // gpio_mode(MSG, GPIO_OUTPUT_OD);
  697. // gpio_mode(CD, GPIO_OUTPUT_OD);
  698. // gpio_mode(REQ, GPIO_OUTPUT_OD);
  699. // gpio_mode(IO, GPIO_OUTPUT_OD);
  700. // Should I enter DB and DBP once?
  701. SCSI_DB_INPUT()
  702. LOGN("BusReset!");
  703. if (m_resetJmp) {
  704. m_resetJmp = false;
  705. // Jumping out of the interrupt handler, so need to clear the interupt source.
  706. uint8 exti = PIN_MAP[RST].gpio_bit;
  707. EXTI_BASE->PR = (1U << exti);
  708. longjmpFromInterrupt(m_resetJmpBuf, 1);
  709. } else {
  710. m_isBusReset = true;
  711. }
  712. }
  713. }
  714. }
  715. /*
  716. * Enable the reset longjmp, and check if reset fired while it was disabled.
  717. */
  718. void enableResetJmp(void) {
  719. m_resetJmp = true;
  720. if (m_isBusReset) {
  721. longjmp(m_resetJmpBuf, 1);
  722. }
  723. }
  724. /*
  725. * Read by handshake.
  726. */
  727. inline byte readHandshake(void)
  728. {
  729. SCSI_OUT(vREQ,active)
  730. //SCSI_DB_INPUT()
  731. while( ! SCSI_IN(vACK));
  732. byte r = readIO();
  733. SCSI_OUT(vREQ,inactive)
  734. while( SCSI_IN(vACK));
  735. return r;
  736. }
  737. /*
  738. * Write with a handshake.
  739. */
  740. inline void writeHandshake(byte d)
  741. {
  742. GPIOB->regs->BSRR = db_bsrr[d]; // setup DB,DBP (160ns)
  743. #if XCVR == 1
  744. TRANSCEIVER_IO_SET(vTR_DBP,TR_OUTPUT)
  745. #endif
  746. SCSI_DB_OUTPUT() // (180ns)
  747. // ACK.Fall to DB output delay 100ns(MAX) (DTC-510B)
  748. SCSI_OUT(vREQ,inactive) // setup wait (30ns)
  749. SCSI_OUT(vREQ,inactive) // setup wait (30ns)
  750. SCSI_OUT(vREQ,inactive) // setup wait (30ns)
  751. SCSI_OUT(vREQ,active) // (30ns)
  752. //while(!SCSI_IN(vACK)) { if(m_isBusReset){ SCSI_DB_INPUT() return; }}
  753. while(!SCSI_IN(vACK));
  754. // ACK.Fall to REQ.Raise delay 500ns(typ.) (DTC-510B)
  755. GPIOB->regs->BSRR = DBP(0xff); // DB=0xFF , SCSI_OUT(vREQ,inactive)
  756. // REQ.Raise to DB hold time 0ns
  757. SCSI_DB_INPUT() // (150ns)
  758. #if XCVR == 1
  759. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT)
  760. #endif
  761. while( SCSI_IN(vACK));
  762. }
  763. /*
  764. * Data in phase.
  765. * Send len bytes of data array p.
  766. */
  767. void writeDataPhase(int len, const byte* p)
  768. {
  769. LOGN("DATAIN PHASE");
  770. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  771. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  772. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  773. for (int i = 0; i < len; i++) {
  774. writeHandshake(p[i]);
  775. }
  776. }
  777. #if READ_SPEED_OPTIMIZE
  778. #pragma GCC push_options
  779. #pragma GCC optimize ("-Os")
  780. /*
  781. * This loop is tuned to repeat the following pattern:
  782. * 1) Set REQ
  783. * 2) 5 cycles of work/delay
  784. * 3) Wait for ACK
  785. * Cycle time tunings are for 72MHz STM32F103
  786. * Alignment matters. For the 3 instruction wait loops,it looks like crossing
  787. * an 8 byte prefetch buffer can add 2 cycles of wait every branch taken.
  788. */
  789. void writeDataLoop(uint32_t blocksize) __attribute__ ((aligned(8)));
  790. void writeDataLoop(uint32_t blocksize)
  791. {
  792. #define REQ_ON() (port_b->BRR = req_bit);
  793. #define FETCH_BSRR_DB() (bsrr_val = bsrr_tbl[*srcptr++])
  794. #define REQ_OFF_DB_SET(BSRR_VAL) port_b->BSRR = BSRR_VAL;
  795. #define WAIT_ACK_ACTIVE() while((*port_a_idr>>(vACK&15)&1))
  796. #define WAIT_ACK_INACTIVE() while(!(*port_a_idr>>(vACK&15)&1))
  797. register byte *srcptr= m_buf; // Source buffer
  798. register byte *endptr= m_buf + blocksize; // End pointer
  799. register const uint32_t *bsrr_tbl = db_bsrr; // Table to convert to BSRR
  800. register uint32_t bsrr_val; // BSRR value to output (DB, DBP, REQ = ACTIVE)
  801. register uint32_t req_bit = BITMASK(vREQ);
  802. register gpio_reg_map *port_b = PBREG;
  803. register volatile uint32_t *port_a_idr = &(GPIOA->regs->IDR);
  804. // Start the first bus cycle.
  805. FETCH_BSRR_DB();
  806. REQ_OFF_DB_SET(bsrr_val);
  807. #if XCVR == 1
  808. TRANSCEIVER_IO_SET(vTR_DBP,TR_OUTPUT)
  809. #endif
  810. REQ_ON();
  811. FETCH_BSRR_DB();
  812. WAIT_ACK_ACTIVE();
  813. REQ_OFF_DB_SET(bsrr_val);
  814. // Align the starts of the do/while and WAIT loops to an 8 byte prefetch.
  815. asm("nop.w;nop");
  816. do{
  817. WAIT_ACK_INACTIVE();
  818. REQ_ON();
  819. // 4 cycles of work
  820. FETCH_BSRR_DB();
  821. // Extra 1 cycle delay while keeping the loop within an 8 byte prefetch.
  822. asm("nop");
  823. WAIT_ACK_ACTIVE();
  824. REQ_OFF_DB_SET(bsrr_val);
  825. // Extra 1 cycle delay, plus 4 cycles for the branch taken with prefetch.
  826. asm("nop");
  827. }while(srcptr < endptr);
  828. WAIT_ACK_INACTIVE();
  829. // Finish the last bus cycle, byte is already on DB.
  830. REQ_ON();
  831. WAIT_ACK_ACTIVE();
  832. REQ_OFF_DB_SET(bsrr_val);
  833. WAIT_ACK_INACTIVE();
  834. }
  835. #pragma GCC pop_options
  836. #endif
  837. /*
  838. * Data in phase.
  839. * Send len block while reading from SD card.
  840. */
  841. void writeDataPhaseSD(uint32_t adds, uint32_t len)
  842. {
  843. LOGN("DATAIN PHASE(SD)");
  844. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  845. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  846. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  847. //Bus settle delay 400ns, file.seek() measured at over 1000ns.
  848. uint32_t pos = adds * m_img->m_blocksize;
  849. m_img->m_file.seek(pos);
  850. SCSI_DB_OUTPUT()
  851. for(uint32_t i = 0; i < len; i++) {
  852. // Asynchronous reads will make it faster ...
  853. m_resetJmp = false;
  854. m_img->m_file.read(m_buf, m_img->m_blocksize);
  855. enableResetJmp();
  856. #if READ_SPEED_OPTIMIZE
  857. writeDataLoop(m_img->m_blocksize);
  858. #else
  859. for(int j = 0; j < m_img->m_blocksize; j++) {
  860. writeHandshake(m_buf[j]);
  861. }
  862. #endif
  863. }
  864. SCSI_DB_INPUT()
  865. #if XCVR == 1
  866. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT)
  867. #endif
  868. }
  869. /*
  870. * Data out phase.
  871. * len block read
  872. */
  873. void readDataPhase(int len, byte* p)
  874. {
  875. LOGN("DATAOUT PHASE");
  876. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  877. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  878. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  879. for(uint32_t i = 0; i < len; i++)
  880. p[i] = readHandshake();
  881. }
  882. #if WRITE_SPEED_OPTIMIZE
  883. #pragma GCC push_options
  884. #pragma GCC optimize ("-Os")
  885. /*
  886. * See writeDataLoop for optimization info.
  887. */
  888. void readDataLoop(uint32_t blockSize) __attribute__ ((aligned(16)));
  889. void readDataLoop(uint32_t blockSize)
  890. {
  891. register byte *dstptr= m_buf;
  892. register byte *endptr= m_buf + blockSize - 1;
  893. #define REQ_ON() (port_b->BRR = req_bit);
  894. #define REQ_OFF() (port_b->BSRR = req_bit);
  895. #define WAIT_ACK_ACTIVE() while((*port_a_idr>>(vACK&15)&1))
  896. #define WAIT_ACK_INACTIVE() while(!(*port_a_idr>>(vACK&15)&1))
  897. register uint32_t req_bit = BITMASK(vREQ);
  898. register gpio_reg_map *port_b = PBREG;
  899. register volatile uint32_t *port_a_idr = &(GPIOA->regs->IDR);
  900. REQ_ON();
  901. // Start of the do/while and WAIT are already aligned to 8 bytes.
  902. do {
  903. WAIT_ACK_ACTIVE();
  904. uint32_t ret = port_b->IDR;
  905. REQ_OFF();
  906. *dstptr++ = ~(ret >> 8);
  907. // Move wait loop in to a single 8 byte prefetch buffer
  908. asm("nop.w;nop");
  909. WAIT_ACK_INACTIVE();
  910. REQ_ON();
  911. // Extra 1 cycle delay
  912. asm("nop");
  913. } while(dstptr<endptr);
  914. WAIT_ACK_ACTIVE();
  915. uint32_t ret = GPIOB->regs->IDR;
  916. REQ_OFF();
  917. *dstptr = ~(ret >> 8);
  918. WAIT_ACK_INACTIVE();
  919. }
  920. #pragma GCC pop_options
  921. #endif
  922. /*
  923. * Data out phase.
  924. * Write to SD card while reading len block.
  925. */
  926. void readDataPhaseSD(uint32_t adds, uint32_t len)
  927. {
  928. LOGN("DATAOUT PHASE(SD)");
  929. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  930. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  931. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  932. //Bus settle delay 400ns, file.seek() measured at over 1000ns.
  933. uint32_t pos = adds * m_img->m_blocksize;
  934. m_img->m_file.seek(pos);
  935. for(uint32_t i = 0; i < len; i++) {
  936. m_resetJmp = true;
  937. #if WRITE_SPEED_OPTIMIZE
  938. readDataLoop(m_img->m_blocksize);
  939. #else
  940. for(int j = 0; j < m_img->m_blocksize; j++) {
  941. m_buf[j] = readHandshake();
  942. }
  943. #endif
  944. m_resetJmp = false;
  945. m_img->m_file.write(m_buf, m_img->m_blocksize);
  946. // If a reset happened while writing, break and let the flush happen before it is handled.
  947. if (m_isBusReset) {
  948. break;
  949. }
  950. }
  951. m_img->m_file.flush();
  952. enableResetJmp();
  953. }
  954. /*
  955. * Data out phase.
  956. * Compare to SD card while reading len block.
  957. */
  958. void verifyDataPhaseSD(uint32_t adds, uint32_t len)
  959. {
  960. LOGN("DATAOUT PHASE(SD)");
  961. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  962. SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  963. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  964. //Bus settle delay 400ns, file.seek() measured at over 1000ns.
  965. uint32_t pos = adds * m_img->m_blocksize;
  966. m_img->m_file.seek(pos);
  967. for(uint32_t i = 0; i < len; i++) {
  968. #if WRITE_SPEED_OPTIMIZE
  969. readDataLoop(m_img->m_blocksize);
  970. #else
  971. for(int j = 0; j < m_img->m_blocksize; j++) {
  972. m_buf[j] = readHandshake();
  973. }
  974. #endif
  975. // This has just gone through the transfer to make things work, a compare would go here.
  976. }
  977. }
  978. /*
  979. * INQUIRY command processing.
  980. */
  981. #if SCSI_SELECT == 2
  982. byte onInquiryCommand(byte len)
  983. {
  984. byte buf[36] = {
  985. 0x00, //Device type
  986. 0x00, //RMB = 0
  987. 0x01, //ISO,ECMA,ANSI version
  988. 0x01, //Response data format
  989. 35 - 4, //Additional data length
  990. 0, 0, //Reserve
  991. 0x00, //Support function
  992. 'N', 'E', 'C', 'I', 'T', 'S', 'U', ' ',
  993. 'A', 'r', 'd', 'S', 'C', 'S', 'i', 'n', 'o', ' ', ' ',' ', ' ', ' ', ' ', ' ',
  994. '0', '0', '1', '0',
  995. };
  996. writeDataPhase(len < 36 ? len : 36, buf);
  997. return 0x00;
  998. }
  999. #else
  1000. byte onInquiryCommand(byte len)
  1001. {
  1002. writeDataPhase(len < 36 ? len : 36, SCSI_INFO_BUF);
  1003. return 0x00;
  1004. }
  1005. #endif
  1006. /*
  1007. * REQUEST SENSE command processing.
  1008. */
  1009. void onRequestSenseCommand(byte len)
  1010. {
  1011. byte buf[18] = {
  1012. 0x70, //CheckCondition
  1013. 0, //Segment number
  1014. m_senseKey, //Sense key
  1015. 0, 0, 0, 0, //information
  1016. 10, //Additional data length
  1017. 0, 0, 0, 0, // command specific information bytes
  1018. (byte)(m_addition_sense >> 8),
  1019. (byte)m_addition_sense,
  1020. 0, 0, 0, 0,
  1021. };
  1022. m_senseKey = 0;
  1023. m_addition_sense = 0;
  1024. writeDataPhase(len < 18 ? len : 18, buf);
  1025. }
  1026. /*
  1027. * READ CAPACITY command processing.
  1028. */
  1029. byte onReadCapacityCommand(byte pmi)
  1030. {
  1031. if(!m_img) {
  1032. m_senseKey = 2; // Not ready
  1033. m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required
  1034. return 0x02; // Image file absent
  1035. }
  1036. uint32_t bl = m_img->m_blocksize;
  1037. uint32_t bc = m_img->m_fileSize / bl - 1; // Points to last LBA
  1038. uint8_t buf[8] = {
  1039. bc >> 24, bc >> 16, bc >> 8, bc,
  1040. bl >> 24, bl >> 16, bl >> 8, bl
  1041. };
  1042. writeDataPhase(8, buf);
  1043. return 0x00;
  1044. }
  1045. /*
  1046. * Check that the image file is present and the block range is valid.
  1047. */
  1048. byte checkBlockCommand(uint32_t adds, uint32_t len)
  1049. {
  1050. // Check that image file is present
  1051. if(!m_img) {
  1052. m_senseKey = 2; // Not ready
  1053. m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required
  1054. return 0x02;
  1055. }
  1056. // Check block range is valid
  1057. uint32_t bc = m_img->m_fileSize / m_img->m_blocksize;
  1058. if (adds >= bc || (adds + len) > bc) {
  1059. m_senseKey = 5; // Illegal request
  1060. m_addition_sense = 0x2100; // Logical block address out of range
  1061. return 0x02;
  1062. }
  1063. return 0x00;
  1064. }
  1065. /*
  1066. * READ6 / 10 Command processing.
  1067. */
  1068. byte onReadCommand(uint32_t adds, uint32_t len)
  1069. {
  1070. LOGN("-R");
  1071. LOGHEXN(adds);
  1072. LOGHEXN(len);
  1073. byte sts = checkBlockCommand(adds, len);
  1074. if (sts) {
  1075. return sts;
  1076. }
  1077. LED_ON();
  1078. writeDataPhaseSD(adds, len);
  1079. LED_OFF();
  1080. return 0x00; //sts
  1081. }
  1082. /*
  1083. * WRITE6 / 10 Command processing.
  1084. */
  1085. byte onWriteCommand(uint32_t adds, uint32_t len)
  1086. {
  1087. LOGN("-W");
  1088. LOGHEXN(adds);
  1089. LOGHEXN(len);
  1090. byte sts = checkBlockCommand(adds, len);
  1091. if (sts) {
  1092. return sts;
  1093. }
  1094. LED_ON();
  1095. readDataPhaseSD(adds, len);
  1096. LED_OFF();
  1097. return 0; //sts
  1098. }
  1099. /*
  1100. * VERIFY10 Command processing.
  1101. */
  1102. byte onVerifyCommand(byte flags, uint32_t adds, uint32_t len)
  1103. {
  1104. byte sts = checkBlockCommand(adds, len);
  1105. if (sts) {
  1106. return sts;
  1107. }
  1108. int bytchk = (flags >> 1) & 0x03;
  1109. if (bytchk != 0) {
  1110. if (bytchk == 3) {
  1111. // Data-Out buffer is single logical block for repeated verification.
  1112. len = m_img->m_blocksize;
  1113. }
  1114. LED_ON();
  1115. verifyDataPhaseSD(adds, len);
  1116. LED_OFF();
  1117. }
  1118. return 0x00;
  1119. }
  1120. /*
  1121. * MODE SENSE command processing.
  1122. */
  1123. #if SCSI_SELECT == 2
  1124. byte onModeSenseCommand(byte scsi_cmd, byte dbd, int cmd2, uint32_t len)
  1125. {
  1126. if(!m_img) {
  1127. m_senseKey = 2; // Not ready
  1128. m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required
  1129. return 0x02; // Image file absent
  1130. }
  1131. int pageCode = cmd2 & 0x3F;
  1132. // Assuming sector size 512, number of sectors 25, number of heads 8 as default settings
  1133. int size = m_img->m_fileSize;
  1134. int cylinders = (int)(size >> 9);
  1135. cylinders >>= 3;
  1136. cylinders /= 25;
  1137. int sectorsize = 512;
  1138. int sectors = 25;
  1139. int heads = 8;
  1140. // Sector size
  1141. int disksize = 0;
  1142. for(disksize = 16; disksize > 0; --(disksize)) {
  1143. if ((1 << disksize) == sectorsize)
  1144. break;
  1145. }
  1146. // Number of blocks
  1147. uint32_t diskblocks = (uint32_t)(size >> disksize);
  1148. memset(m_buf, 0, sizeof(m_buf));
  1149. int a = 4;
  1150. if(dbd == 0) {
  1151. uint32_t bl = m_img->m_blocksize;
  1152. uint32_t bc = m_img->m_fileSize / bl;
  1153. byte c[8] = {
  1154. 0,// Density code
  1155. bc >> 16, bc >> 8, bc,
  1156. 0, //Reserve
  1157. bl >> 16, bl >> 8, bl
  1158. };
  1159. memcpy(&m_buf[4], c, 8);
  1160. a += 8;
  1161. m_buf[3] = 0x08;
  1162. }
  1163. switch(pageCode) {
  1164. case 0x3F:
  1165. {
  1166. m_buf[a + 0] = 0x01;
  1167. m_buf[a + 1] = 0x06;
  1168. a += 8;
  1169. }
  1170. case 0x03: // drive parameters
  1171. {
  1172. m_buf[a + 0] = 0x80 | 0x03; // Page code
  1173. m_buf[a + 1] = 0x16; // Page length
  1174. m_buf[a + 2] = (byte)(heads >> 8);// number of sectors / track
  1175. m_buf[a + 3] = (byte)(heads);// number of sectors / track
  1176. m_buf[a + 10] = (byte)(sectors >> 8);// number of sectors / track
  1177. m_buf[a + 11] = (byte)(sectors);// number of sectors / track
  1178. int size = 1 << disksize;
  1179. m_buf[a + 12] = (byte)(size >> 8);// number of sectors / track
  1180. m_buf[a + 13] = (byte)(size);// number of sectors / track
  1181. a += 24;
  1182. if(pageCode != 0x3F) {
  1183. break;
  1184. }
  1185. }
  1186. case 0x04: // drive parameters
  1187. {
  1188. LOGN("AddDrive");
  1189. m_buf[a + 0] = 0x04; // Page code
  1190. m_buf[a + 1] = 0x12; // Page length
  1191. m_buf[a + 2] = (cylinders >> 16);// Cylinder length
  1192. m_buf[a + 3] = (cylinders >> 8);
  1193. m_buf[a + 4] = cylinders;
  1194. m_buf[a + 5] = heads; // Number of heads
  1195. a += 20;
  1196. if(pageCode != 0x3F) {
  1197. break;
  1198. }
  1199. }
  1200. default:
  1201. break;
  1202. }
  1203. m_buf[0] = a - 1;
  1204. writeDataPhase(len < a ? len : a, m_buf);
  1205. return 0x00;
  1206. }
  1207. #else
  1208. byte onModeSenseCommand(byte scsi_cmd, byte dbd, byte cmd2, uint32_t len)
  1209. {
  1210. if(!m_img) {
  1211. m_senseKey = 2; // Not ready
  1212. m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required
  1213. return 0x02; // No image file
  1214. }
  1215. uint32_t bl = m_img->m_blocksize;
  1216. uint32_t bc = m_img->m_fileSize / bl;
  1217. memset(m_buf, 0, sizeof(m_buf));
  1218. int pageCode = cmd2 & 0x3F;
  1219. int pageControl = cmd2 >> 6;
  1220. int a = 4;
  1221. if(scsi_cmd == 0x5A) a = 8;
  1222. if(dbd == 0) {
  1223. byte c[8] = {
  1224. 0,//Density code
  1225. bc >> 16, bc >> 8, bc,
  1226. 0, //Reserve
  1227. bl >> 16, bl >> 8, bl
  1228. };
  1229. memcpy(&m_buf[a], c, 8);
  1230. a += 8;
  1231. }
  1232. switch(pageCode) {
  1233. case 0x3F:
  1234. case 0x01: // Read/Write Error Recovery
  1235. m_buf[a + 0] = 0x01;
  1236. m_buf[a + 1] = 0x0A;
  1237. a += 0x0C;
  1238. if(pageCode != 0x3F) break;
  1239. case 0x02: // Disconnect-Reconnect page
  1240. m_buf[a + 0] = 0x02;
  1241. m_buf[a + 1] = 0x0A;
  1242. a += 0x0C;
  1243. if(pageCode != 0x3f) break;
  1244. case 0x03: //Drive parameters
  1245. m_buf[a + 0] = 0x03; //Page code
  1246. m_buf[a + 1] = 0x16; // Page length
  1247. if(pageControl != 1) {
  1248. m_buf[a + 11] = 0x3F;//Number of sectors / track
  1249. m_buf[a + 12] = (byte)(m_img->m_blocksize >> 8);
  1250. m_buf[a + 13] = (byte)m_img->m_blocksize;
  1251. m_buf[a + 15] = 0x1; // Interleave
  1252. }
  1253. a += 0x18;
  1254. if(pageCode != 0x3F) break;
  1255. case 0x04: //Drive parameters
  1256. m_buf[a + 0] = 0x04; //Page code
  1257. m_buf[a + 1] = 0x16; // Page length
  1258. if(pageControl != 1) {
  1259. unsigned cylinders = bc / (16 * 63);
  1260. m_buf[a + 2] = (byte)(cylinders >> 16); // Cylinders
  1261. m_buf[a + 3] = (byte)(cylinders >> 8);
  1262. m_buf[a + 4] = (byte)cylinders;
  1263. m_buf[a + 5] = 16; //Number of heads
  1264. }
  1265. a += 0x18;
  1266. if(pageCode != 0x3F) break;
  1267. case 0x30:
  1268. {
  1269. const byte page30[0x14] = {0x41, 0x50, 0x50, 0x4C, 0x45, 0x20, 0x43, 0x4F, 0x4D, 0x50, 0x55, 0x54, 0x45, 0x52, 0x2C, 0x20, 0x49, 0x4E, 0x43, 0x20};
  1270. m_buf[a + 0] = 0x30; // Page code
  1271. m_buf[a + 1] = sizeof(page30); // Page length
  1272. if(pageControl != 1) {
  1273. memcpy(&m_buf[a + 2], page30, sizeof(page30));
  1274. }
  1275. a += 2 + sizeof(page30);
  1276. if(pageCode != 0x3F) break;
  1277. }
  1278. break; // Don't want 0x3F falling through to error condition
  1279. default:
  1280. m_senseKey = 5; // Illegal request
  1281. m_addition_sense = 0x2400; // Invalid field in CDB
  1282. return 0x02;
  1283. break;
  1284. }
  1285. if(scsi_cmd == 0x5A) // MODE SENSE 10
  1286. {
  1287. m_buf[1] = a - 2;
  1288. m_buf[7] = 0x08;
  1289. }
  1290. else
  1291. {
  1292. m_buf[0] = a - 1;
  1293. m_buf[3] = 0x08;
  1294. }
  1295. writeDataPhase(len < a ? len : a, m_buf);
  1296. return 0x00;
  1297. }
  1298. #endif
  1299. byte onModeSelectCommand(byte scsi_cmd, byte flags, uint32_t len)
  1300. {
  1301. if (len > MAX_BLOCKSIZE) {
  1302. m_senseKey = 5; // Illegal request
  1303. m_addition_sense = 0x2400; // Invalid field in CDB
  1304. return 0x02;
  1305. }
  1306. readDataPhase(len, m_buf);
  1307. //Apple HD SC Setup sends:
  1308. //0 0 0 8 0 0 0 0 0 0 2 0 0 2 10 0 1 6 24 10 8 0 0 0
  1309. //I believe mode page 0 set to 10 00 is Disable Unit Attention
  1310. //Mode page 1 set to 24 10 08 00 00 00 is TB and PER set, read retry count 16, correction span 8
  1311. for (unsigned i = 0; i < len; i++) {
  1312. LOGHEX(m_buf[i]);LOG(" ");
  1313. }
  1314. LOGN("");
  1315. return 0x00;
  1316. }
  1317. #if SCSI_SELECT == 1
  1318. /*
  1319. * dtc510b_setDriveparameter
  1320. */
  1321. #define PACKED __attribute__((packed))
  1322. typedef struct PACKED dtc500_cmd_c2_param_struct
  1323. {
  1324. uint8_t StepPlusWidth; // Default is 13.6usec (11)
  1325. uint8_t StepPeriod; // Default is 3 msec.(60)
  1326. uint8_t StepMode; // Default is Bufferd (0)
  1327. uint8_t MaximumHeadAdress; // Default is 4 heads (3)
  1328. uint8_t HighCylinderAddressByte; // Default set to 0 (0)
  1329. uint8_t LowCylinderAddressByte; // Default is 153 cylinders (152)
  1330. uint8_t ReduceWrietCurrent; // Default is above Cylinder 128 (127)
  1331. uint8_t DriveType_SeekCompleteOption;// (0)
  1332. uint8_t Reserved8; // (0)
  1333. uint8_t Reserved9; // (0)
  1334. } DTC510_CMD_C2_PARAM;
  1335. static void logStrHex(const char *msg,uint32_t num)
  1336. {
  1337. LOG(msg);
  1338. LOGHEXN(num);
  1339. }
  1340. static byte dtc510b_setDriveparameter(void)
  1341. {
  1342. DTC510_CMD_C2_PARAM DriveParameter;
  1343. uint16_t maxCylinder;
  1344. uint16_t numLAD;
  1345. //uint32_t stepPulseUsec;
  1346. int StepPeriodMsec;
  1347. // receive paramter
  1348. writeDataPhase(sizeof(DriveParameter),(byte *)(&DriveParameter));
  1349. maxCylinder =
  1350. (((uint16_t)DriveParameter.HighCylinderAddressByte)<<8) |
  1351. (DriveParameter.LowCylinderAddressByte);
  1352. numLAD = maxCylinder * (DriveParameter.MaximumHeadAdress+1);
  1353. //stepPulseUsec = calcStepPulseUsec(DriveParameter.StepPlusWidth);
  1354. StepPeriodMsec = DriveParameter.StepPeriod*50;
  1355. logStrHex (" StepPlusWidth : ",DriveParameter.StepPlusWidth);
  1356. logStrHex (" StepPeriod : ",DriveParameter.StepPeriod );
  1357. logStrHex (" StepMode : ",DriveParameter.StepMode );
  1358. logStrHex (" MaximumHeadAdress : ",DriveParameter.MaximumHeadAdress);
  1359. logStrHex (" CylinderAddress : ",maxCylinder);
  1360. logStrHex (" ReduceWrietCurrent : ",DriveParameter.ReduceWrietCurrent);
  1361. logStrHex (" DriveType/SeekCompleteOption : ",DriveParameter.DriveType_SeekCompleteOption);
  1362. logStrHex (" Maximum LAD : ",numLAD-1);
  1363. return 0; // error result
  1364. }
  1365. #endif
  1366. /*
  1367. * MsgIn2.
  1368. */
  1369. void MsgIn2(int msg)
  1370. {
  1371. LOGN("MsgIn2");
  1372. SCSI_OUT(vMSG, active) // gpio_write(MSG, high);
  1373. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1374. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  1375. writeHandshake(msg);
  1376. }
  1377. /*
  1378. * MsgOut2.
  1379. */
  1380. void MsgOut2()
  1381. {
  1382. LOGN("MsgOut2");
  1383. SCSI_OUT(vMSG, active) // gpio_write(MSG, high);
  1384. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1385. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1386. m_msb[m_msc] = readHandshake();
  1387. m_msc++;
  1388. m_msc %= 256;
  1389. }
  1390. /*
  1391. * Main loop.
  1392. */
  1393. void loop()
  1394. {
  1395. #if XCVR == 1
  1396. // Reset all DB and Target pins, switch transceivers to input
  1397. // Precaution against bugs or jumps which don't clean up properly
  1398. SCSI_DB_INPUT();
  1399. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT)
  1400. SCSI_TARGET_INACTIVE();
  1401. TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT)
  1402. #endif
  1403. //int msg = 0;
  1404. m_msg = 0;
  1405. // Wait until RST = H, BSY = H, SEL = L
  1406. do {} while( SCSI_IN(vBSY) || !SCSI_IN(vSEL) || SCSI_IN(vRST));
  1407. // BSY+ SEL-
  1408. // If the ID to respond is not driven, wait for the next
  1409. //byte db = readIO();
  1410. //byte scsiid = db & scsi_id_mask;
  1411. byte scsiid = readIO() & scsi_id_mask;
  1412. if((scsiid) == 0) {
  1413. delayMicroseconds(1);
  1414. return;
  1415. }
  1416. LOGN("Selection");
  1417. m_isBusReset = false;
  1418. if (setjmp(m_resetJmpBuf) == 1) {
  1419. LOGN("Reset, going to BusFree");
  1420. goto BusFree;
  1421. }
  1422. enableResetJmp();
  1423. #if XCVR == 1
  1424. TRANSCEIVER_IO_SET(vTR_TARGET,TR_OUTPUT);
  1425. #endif
  1426. // Set BSY to-when selected
  1427. SCSI_BSY_ACTIVE(); // Turn only BSY output ON, ACTIVE
  1428. // Ask for a TARGET-ID to respond
  1429. m_id = 31 - __builtin_clz(scsiid);
  1430. // Wait until SEL becomes inactive
  1431. while(isHigh(gpio_read(SEL)) && isLow(gpio_read(BSY))) {
  1432. }
  1433. //
  1434. if(isHigh(gpio_read(ATN))) {
  1435. bool syncenable = false;
  1436. int syncperiod = 50;
  1437. int syncoffset = 0;
  1438. int loopWait = 0;
  1439. m_msc = 0;
  1440. memset(m_msb, 0x00, sizeof(m_msb));
  1441. while(isHigh(gpio_read(ATN)) && loopWait < 255) {
  1442. MsgOut2();
  1443. loopWait++;
  1444. }
  1445. for(int i = 0; i < m_msc; i++) {
  1446. // ABORT
  1447. if (m_msb[i] == 0x06) {
  1448. goto BusFree;
  1449. }
  1450. // BUS DEVICE RESET
  1451. if (m_msb[i] == 0x0C) {
  1452. syncoffset = 0;
  1453. goto BusFree;
  1454. }
  1455. // IDENTIFY
  1456. if (m_msb[i] >= 0x80) {
  1457. }
  1458. // Extended message
  1459. if (m_msb[i] == 0x01) {
  1460. // Check only when synchronous transfer is possible
  1461. if (!syncenable || m_msb[i + 2] != 0x01) {
  1462. MsgIn2(0x07);
  1463. break;
  1464. }
  1465. // Transfer period factor(50 x 4 = Limited to 200ns)
  1466. syncperiod = m_msb[i + 3];
  1467. if (syncperiod > 50) {
  1468. syncperiod = 50;
  1469. }
  1470. // REQ/ACK offset(Limited to 16)
  1471. syncoffset = m_msb[i + 4];
  1472. if (syncoffset > 16) {
  1473. syncoffset = 16;
  1474. }
  1475. // STDR response message generation
  1476. MsgIn2(0x01);
  1477. MsgIn2(0x03);
  1478. MsgIn2(0x01);
  1479. MsgIn2(syncperiod);
  1480. MsgIn2(syncoffset);
  1481. break;
  1482. }
  1483. }
  1484. }
  1485. LOG("Command:");
  1486. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1487. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1488. SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1489. int len;
  1490. byte cmd[12];
  1491. cmd[0] = readHandshake();
  1492. LOGHEX(cmd[0]);
  1493. // Command length selection, reception
  1494. static const int cmd_class_len[8]={6,10,10,6,6,12,6,6};
  1495. len = cmd_class_len[cmd[0] >> 5];
  1496. cmd[1] = readHandshake(); LOG(":");LOGHEX(cmd[1]);
  1497. cmd[2] = readHandshake(); LOG(":");LOGHEX(cmd[2]);
  1498. cmd[3] = readHandshake(); LOG(":");LOGHEX(cmd[3]);
  1499. cmd[4] = readHandshake(); LOG(":");LOGHEX(cmd[4]);
  1500. cmd[5] = readHandshake(); LOG(":");LOGHEX(cmd[5]);
  1501. // Receive the remaining commands
  1502. for(int i = 6; i < len; i++ ) {
  1503. cmd[i] = readHandshake();
  1504. LOG(":");
  1505. LOGHEX(cmd[i]);
  1506. }
  1507. // LUN confirmation
  1508. m_sts = cmd[1]&0xe0; // Preset LUN in status byte
  1509. m_lun = m_sts>>5;
  1510. // HDD Image selection
  1511. m_img = (HDDIMG *)0; // None
  1512. if( (m_lun <= NUM_SCSILUN) )
  1513. {
  1514. m_img = &(img[m_id][m_lun]); // There is an image
  1515. if(!(m_img->m_file.isOpen()))
  1516. m_img = (HDDIMG *)0; // Image absent
  1517. }
  1518. // if(!m_img) m_sts |= 0x02; // Missing image file for LUN
  1519. //LOGHEX(((uint32_t)m_img));
  1520. LOG(":ID ");
  1521. LOG(m_id);
  1522. LOG(":LUN ");
  1523. LOG(m_lun);
  1524. LOGN("");
  1525. switch(cmd[0]) {
  1526. case 0x00:
  1527. LOGN("[Test Unit]");
  1528. break;
  1529. case 0x01:
  1530. LOGN("[Rezero Unit]");
  1531. break;
  1532. case 0x03:
  1533. LOGN("[RequestSense]");
  1534. onRequestSenseCommand(cmd[4]);
  1535. break;
  1536. case 0x04:
  1537. LOGN("[FormatUnit]");
  1538. break;
  1539. case 0x06:
  1540. LOGN("[FormatUnit]");
  1541. break;
  1542. case 0x07:
  1543. LOGN("[ReassignBlocks]");
  1544. break;
  1545. case 0x08:
  1546. LOGN("[Read6]");
  1547. m_sts |= onReadCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
  1548. break;
  1549. case 0x0A:
  1550. LOGN("[Write6]");
  1551. m_sts |= onWriteCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
  1552. break;
  1553. case 0x0B:
  1554. LOGN("[Seek6]");
  1555. break;
  1556. case 0x12:
  1557. LOGN("[Inquiry]");
  1558. m_sts |= onInquiryCommand(cmd[4]);
  1559. break;
  1560. case 0x15:
  1561. LOGN("[ModeSelect6]");
  1562. m_sts |= onModeSelectCommand(cmd[0], cmd[1], cmd[4]);
  1563. break;
  1564. case 0x1A:
  1565. LOGN("[ModeSense6]");
  1566. m_sts |= onModeSenseCommand(cmd[0], cmd[1]&0x80, cmd[2], cmd[4]);
  1567. break;
  1568. case 0x1B:
  1569. LOGN("[StartStopUnit]");
  1570. break;
  1571. case 0x1E:
  1572. LOGN("[PreAllowMed.Removal]");
  1573. break;
  1574. case 0x25:
  1575. LOGN("[ReadCapacity]");
  1576. m_sts |= onReadCapacityCommand(cmd[8]);
  1577. break;
  1578. case 0x28:
  1579. LOGN("[Read10]");
  1580. 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]);
  1581. break;
  1582. case 0x2A:
  1583. LOGN("[Write10]");
  1584. 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]);
  1585. break;
  1586. case 0x2B:
  1587. LOGN("[Seek10]");
  1588. break;
  1589. case 0x2F:
  1590. LOGN("[Verify10]");
  1591. m_sts |= onVerifyCommand(cmd[1], ((uint32_t)cmd[2] << 24) | ((uint32_t)cmd[3] << 16) | ((uint32_t)cmd[4] << 8) | cmd[5], ((uint32_t)cmd[7] << 8) | cmd[8]);
  1592. break;
  1593. case 0x35:
  1594. LOGN("[SynchronizeCache10]");
  1595. break;
  1596. case 0x55:
  1597. LOGN("[ModeSelect10");
  1598. m_sts |= onModeSelectCommand(cmd[0], cmd[1], ((uint32_t)cmd[7] << 8) | cmd[8]);
  1599. break;
  1600. case 0x5A:
  1601. LOGN("[ModeSense10]");
  1602. m_sts |= onModeSenseCommand(cmd[0], cmd[1] & 0x80, cmd[2], ((uint32_t)cmd[7] << 8) | cmd[8]);
  1603. break;
  1604. #if SCSI_SELECT == 1
  1605. case 0xc2:
  1606. LOGN("[DTC510B setDriveParameter]");
  1607. m_sts |= dtc510b_setDriveparameter();
  1608. break;
  1609. #endif
  1610. default:
  1611. LOGN("[*Unknown]");
  1612. m_sts |= 0x02;
  1613. m_senseKey = 5; // Illegal request
  1614. m_addition_sense = 0x2000; // Invalid Command Operation Code
  1615. break;
  1616. }
  1617. LOGN("Sts");
  1618. SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1619. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1620. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  1621. writeHandshake(m_sts);
  1622. LOGN("MsgIn");
  1623. SCSI_OUT(vMSG, active) // gpio_write(MSG, high);
  1624. SCSI_OUT(vCD , active) // gpio_write(CD, high);
  1625. SCSI_OUT(vIO , active) // gpio_write(IO, high);
  1626. writeHandshake(m_msg);
  1627. BusFree:
  1628. LOGN("BusFree");
  1629. m_isBusReset = false;
  1630. //SCSI_OUT(vREQ,inactive) // gpio_write(REQ, low);
  1631. //SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1632. //SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  1633. //SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1634. //SCSI_OUT(vBSY,inactive)
  1635. SCSI_TARGET_INACTIVE() // Turn off BSY, REQ, MSG, CD, IO output
  1636. #if XCVR == 1
  1637. TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT);
  1638. #endif
  1639. }