BlueSCSI.cpp 50 KB

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