BlueSCSI.cpp 40 KB

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