BlueSCSI.cpp 51 KB

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