BlueSCSI.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. REQ_ON();
  818. FETCH_BSRR_DB();
  819. WAIT_ACK_ACTIVE();
  820. REQ_OFF_DB_SET(bsrr_val);
  821. // Align the starts of the do/while and WAIT loops to an 8 byte prefetch.
  822. asm("nop.w;nop");
  823. do{
  824. WAIT_ACK_INACTIVE();
  825. REQ_ON();
  826. // 4 cycles of work
  827. FETCH_BSRR_DB();
  828. // Extra 1 cycle delay while keeping the loop within an 8 byte prefetch.
  829. asm("nop");
  830. WAIT_ACK_ACTIVE();
  831. REQ_OFF_DB_SET(bsrr_val);
  832. // Extra 1 cycle delay, plus 4 cycles for the branch taken with prefetch.
  833. asm("nop");
  834. }while(srcptr < endptr);
  835. WAIT_ACK_INACTIVE();
  836. // Finish the last bus cycle, byte is already on DB.
  837. REQ_ON();
  838. WAIT_ACK_ACTIVE();
  839. REQ_OFF_DB_SET(bsrr_val);
  840. WAIT_ACK_INACTIVE();
  841. }
  842. #pragma GCC pop_options
  843. /*
  844. * Data in phase.
  845. * Send len bytes of data array p.
  846. */
  847. void writeDataPhase(int len, const byte* p)
  848. {
  849. LOGN("DATAIN PHASE");
  850. SCSI_PHASE_CHANGE(SCSI_PHASE_DATAIN);
  851. // Bus settle delay 400ns. Following code was measured at 800ns before REQ asserted. STM32F103.
  852. #ifdef XCVR
  853. TRANSCEIVER_IO_SET(vTR_DBP,TR_OUTPUT)
  854. #endif
  855. SCSI_DB_OUTPUT()
  856. writeDataLoop(len, p);
  857. SCSI_DB_INPUT()
  858. #ifdef XCVR
  859. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT)
  860. #endif
  861. }
  862. /*
  863. * Data in phase.
  864. * Send len block while reading from SD card.
  865. */
  866. void writeDataPhaseSD(uint32_t adds, uint32_t len)
  867. {
  868. LOGN("DATAIN PHASE(SD)");
  869. SCSI_PHASE_CHANGE(SCSI_PHASE_DATAIN);
  870. //Bus settle delay 400ns, file.seek() measured at over 1000ns.
  871. uint64_t pos = (uint64_t)adds * m_img->m_blocksize;
  872. m_img->m_file.seekSet(pos);
  873. #ifdef XCVR
  874. TRANSCEIVER_IO_SET(vTR_DBP,TR_OUTPUT)
  875. #endif
  876. SCSI_DB_OUTPUT()
  877. for(uint32_t i = 0; i < len; i++) {
  878. // Asynchronous reads will make it faster ...
  879. m_resetJmp = false;
  880. m_img->m_file.read(m_buf, m_img->m_blocksize);
  881. enableResetJmp();
  882. writeDataLoop(m_img->m_blocksize, m_buf);
  883. }
  884. SCSI_DB_INPUT()
  885. #ifdef XCVR
  886. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT)
  887. #endif
  888. }
  889. #pragma GCC push_options
  890. #pragma GCC optimize ("-Os")
  891. /*
  892. * See writeDataLoop for optimization info.
  893. */
  894. void readDataLoop(uint32_t blockSize, byte* dstptr) __attribute__ ((aligned(16)));
  895. void readDataLoop(uint32_t blockSize, byte* dstptr)
  896. {
  897. register byte *endptr= dstptr + blockSize - 1;
  898. #define REQ_ON() (port_b->BRR = req_bit);
  899. #define REQ_OFF() (port_b->BSRR = req_bit);
  900. #define WAIT_ACK_ACTIVE() while((*port_a_idr>>(vACK&15)&1))
  901. #define WAIT_ACK_INACTIVE() while(!(*port_a_idr>>(vACK&15)&1))
  902. register uint32_t req_bit = BITMASK(vREQ);
  903. register gpio_reg_map *port_b = PBREG;
  904. register volatile uint32_t *port_a_idr = &(GPIOA->regs->IDR);
  905. REQ_ON();
  906. // Fastest alignment obtained by trial and error.
  907. // Wait loop is within an 8 byte prefetch buffer.
  908. asm("nop");
  909. do {
  910. WAIT_ACK_ACTIVE();
  911. uint32_t ret = port_b->IDR;
  912. REQ_OFF();
  913. *dstptr++ = ~(ret >> 8);
  914. // Move wait loop in to a single 8 byte prefetch buffer
  915. asm("nop;nop;nop");
  916. WAIT_ACK_INACTIVE();
  917. REQ_ON();
  918. // Extra 1 cycle delay
  919. asm("nop");
  920. } while(dstptr<endptr);
  921. WAIT_ACK_ACTIVE();
  922. uint32_t ret = GPIOB->regs->IDR;
  923. REQ_OFF();
  924. *dstptr = ~(ret >> 8);
  925. WAIT_ACK_INACTIVE();
  926. }
  927. #pragma GCC pop_options
  928. /*
  929. * Data out phase.
  930. * len block read
  931. */
  932. void readDataPhase(int len, byte* p)
  933. {
  934. LOGN("DATAOUT PHASE");
  935. SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT);
  936. // Bus settle delay 400ns. The following code was measured at 450ns before REQ asserted. STM32F103.
  937. readDataLoop(len, p);
  938. }
  939. /*
  940. * Data out phase.
  941. * Write to SD card while reading len block.
  942. */
  943. void readDataPhaseSD(uint32_t adds, uint32_t len)
  944. {
  945. LOGN("DATAOUT PHASE(SD)");
  946. SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT);
  947. //Bus settle delay 400ns, file.seek() measured at over 1000ns.
  948. uint64_t pos = (uint64_t)adds * m_img->m_blocksize;
  949. m_img->m_file.seekSet(pos);
  950. for(uint32_t i = 0; i < len; i++) {
  951. m_resetJmp = true;
  952. readDataLoop(m_img->m_blocksize, m_buf);
  953. m_resetJmp = false;
  954. m_img->m_file.write(m_buf, m_img->m_blocksize);
  955. // If a reset happened while writing, break and let the flush happen before it is handled.
  956. if (m_isBusReset) {
  957. break;
  958. }
  959. }
  960. m_img->m_file.flush();
  961. enableResetJmp();
  962. }
  963. /*
  964. * Data out phase.
  965. * Compare to SD card while reading len block.
  966. */
  967. void verifyDataPhaseSD(uint32_t adds, uint32_t len)
  968. {
  969. LOGN("DATAOUT PHASE(SD)");
  970. SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT);
  971. //Bus settle delay 400ns, file.seek() measured at over 1000ns.
  972. uint64_t pos = (uint64_t)adds * m_img->m_blocksize;
  973. m_img->m_file.seekSet(pos);
  974. for(uint32_t i = 0; i < len; i++) {
  975. readDataLoop(m_img->m_blocksize, m_buf);
  976. // This has just gone through the transfer to make things work, a compare would go here.
  977. }
  978. }
  979. /*
  980. * INQUIRY command processing.
  981. */
  982. byte onInquiryCommand(byte len)
  983. {
  984. writeDataPhase(len < 36 ? len : 36, SCSI_INFO_BUF);
  985. return SCSI_STATUS_GOOD;
  986. }
  987. /*
  988. * REQUEST SENSE command processing.
  989. */
  990. void onRequestSenseCommand(byte len)
  991. {
  992. byte buf[18] = {
  993. 0x70, //CheckCondition
  994. 0, //Segment number
  995. m_senseKey, //Sense key
  996. 0, 0, 0, 0, //information
  997. 10, //Additional data length
  998. 0, 0, 0, 0, // command specific information bytes
  999. (byte)(m_addition_sense >> 8),
  1000. (byte)m_addition_sense,
  1001. 0, 0, 0, 0,
  1002. };
  1003. m_senseKey = 0;
  1004. m_addition_sense = 0;
  1005. writeDataPhase(len < 18 ? len : 18, buf);
  1006. }
  1007. /*
  1008. * READ CAPACITY command processing.
  1009. */
  1010. byte onReadCapacityCommand(byte pmi)
  1011. {
  1012. if(!m_img) {
  1013. m_senseKey = SCSI_SENSE_NOT_READY;
  1014. m_addition_sense = SCSI_ASC_LUN_NOT_READY_MANUAL_INTERVENTION_REQUIRED;
  1015. return SCSI_STATUS_CHECK_CONDITION;
  1016. }
  1017. uint32_t bl = m_img->m_blocksize;
  1018. uint32_t bc = m_img->m_fileSize / bl - 1; // Points to last LBA
  1019. uint8_t buf[8] = {
  1020. bc >> 24, bc >> 16, bc >> 8, bc,
  1021. bl >> 24, bl >> 16, bl >> 8, bl
  1022. };
  1023. writeDataPhase(8, buf);
  1024. return SCSI_STATUS_GOOD;
  1025. }
  1026. /*
  1027. * Check that the image file is present and the block range is valid.
  1028. */
  1029. byte checkBlockCommand(uint32_t adds, uint32_t len)
  1030. {
  1031. // Check that image file is present
  1032. if(!m_img) {
  1033. m_senseKey = SCSI_SENSE_NOT_READY;
  1034. m_addition_sense = SCSI_ASC_LUN_NOT_READY_MANUAL_INTERVENTION_REQUIRED;
  1035. return SCSI_STATUS_CHECK_CONDITION;
  1036. }
  1037. // Check block range is valid
  1038. uint32_t bc = m_img->m_fileSize / m_img->m_blocksize;
  1039. if (adds >= bc || (adds + len) > bc) {
  1040. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1041. m_addition_sense = SCSI_ASC_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1042. return SCSI_STATUS_CHECK_CONDITION;
  1043. }
  1044. return SCSI_STATUS_GOOD;
  1045. }
  1046. /*
  1047. * READ6 / 10 Command processing.
  1048. */
  1049. byte onReadCommand(uint32_t adds, uint32_t len)
  1050. {
  1051. LOGN("-R");
  1052. LOGHEXN(adds);
  1053. LOGHEXN(len);
  1054. byte sts = checkBlockCommand(adds, len);
  1055. if (sts) {
  1056. return sts;
  1057. }
  1058. LED_ON();
  1059. writeDataPhaseSD(adds, len);
  1060. LED_OFF();
  1061. return SCSI_STATUS_GOOD;
  1062. }
  1063. /*
  1064. * WRITE6 / 10 Command processing.
  1065. */
  1066. byte onWriteCommand(uint32_t adds, uint32_t len)
  1067. {
  1068. LOGN("-W");
  1069. LOGHEXN(adds);
  1070. LOGHEXN(len);
  1071. byte sts = checkBlockCommand(adds, len);
  1072. if (sts) {
  1073. return sts;
  1074. }
  1075. LED_ON();
  1076. readDataPhaseSD(adds, len);
  1077. LED_OFF();
  1078. return SCSI_STATUS_GOOD;
  1079. }
  1080. /*
  1081. * VERIFY10 Command processing.
  1082. */
  1083. byte onVerifyCommand(byte flags, uint32_t adds, uint32_t len)
  1084. {
  1085. byte sts = checkBlockCommand(adds, len);
  1086. if (sts) {
  1087. return sts;
  1088. }
  1089. int bytchk = (flags >> 1) & 0x03;
  1090. if (bytchk != 0) {
  1091. if (bytchk == 3) {
  1092. // Data-Out buffer is single logical block for repeated verification.
  1093. len = m_img->m_blocksize;
  1094. }
  1095. LED_ON();
  1096. verifyDataPhaseSD(adds, len);
  1097. LED_OFF();
  1098. }
  1099. return SCSI_STATUS_GOOD;
  1100. }
  1101. /*
  1102. * MODE SENSE command processing.
  1103. */
  1104. byte onModeSenseCommand(byte scsi_cmd, byte dbd, byte cmd2, uint32_t len)
  1105. {
  1106. if(!m_img) {
  1107. m_senseKey = SCSI_SENSE_NOT_READY;
  1108. m_addition_sense = SCSI_ASC_LUN_NOT_READY_MANUAL_INTERVENTION_REQUIRED;
  1109. return SCSI_STATUS_CHECK_CONDITION;
  1110. }
  1111. uint32_t bl = m_img->m_blocksize;
  1112. uint32_t bc = m_img->m_fileSize / bl;
  1113. memset(m_buf, 0, sizeof(m_buf));
  1114. int pageCode = cmd2 & 0x3F;
  1115. int pageControl = cmd2 >> 6;
  1116. int a = 4;
  1117. if(scsi_cmd == SCSI_MODE_SENSE10) a = 8;
  1118. if(dbd == 0) {
  1119. byte c[8] = {
  1120. 0,//Density code
  1121. bc >> 16, bc >> 8, bc,
  1122. 0, //Reserve
  1123. bl >> 16, bl >> 8, bl
  1124. };
  1125. memcpy(&m_buf[a], c, 8);
  1126. a += 8;
  1127. }
  1128. switch(pageCode) {
  1129. case SCSI_SENSE_MODE_ALL:
  1130. case SCSI_SENSE_MODE_READ_WRITE_ERROR_RECOVERY:
  1131. m_buf[a + 0] = SCSI_SENSE_MODE_READ_WRITE_ERROR_RECOVERY;
  1132. m_buf[a + 1] = 0x0A;
  1133. a += 0x0C;
  1134. if(pageCode != SCSI_SENSE_MODE_ALL) break;
  1135. case SCSI_SENSE_MODE_DISCONNECT_RECONNECT:
  1136. m_buf[a + 0] = SCSI_SENSE_MODE_DISCONNECT_RECONNECT;
  1137. m_buf[a + 1] = 0x0A;
  1138. a += 0x0C;
  1139. if(pageCode != SCSI_SENSE_MODE_ALL) break;
  1140. case SCSI_SENSE_MODE_FORMAT_DEVICE: //Drive parameters
  1141. m_buf[a + 0] = SCSI_SENSE_MODE_FORMAT_DEVICE; //Page code
  1142. m_buf[a + 1] = 0x16; // Page length
  1143. if(pageControl != 1) {
  1144. m_buf[a + 11] = 0x3F;//Number of sectors / track
  1145. m_buf[a + 12] = (byte)(m_img->m_blocksize >> 8);
  1146. m_buf[a + 13] = (byte)m_img->m_blocksize;
  1147. m_buf[a + 15] = 0x1; // Interleave
  1148. }
  1149. a += 0x18;
  1150. if(pageCode != SCSI_SENSE_MODE_ALL) break;
  1151. case SCSI_SENSE_MODE_DISK_GEOMETRY: //Drive parameters
  1152. m_buf[a + 0] = SCSI_SENSE_MODE_DISK_GEOMETRY; //Page code
  1153. m_buf[a + 1] = 0x16; // Page length
  1154. if(pageControl != 1) {
  1155. unsigned cylinders = bc / (16 * 63);
  1156. m_buf[a + 2] = (byte)(cylinders >> 16); // Cylinders
  1157. m_buf[a + 3] = (byte)(cylinders >> 8);
  1158. m_buf[a + 4] = (byte)cylinders;
  1159. m_buf[a + 5] = 16; //Number of heads
  1160. }
  1161. a += 0x18;
  1162. if(pageCode != SCSI_SENSE_MODE_ALL) break;
  1163. case SCSI_SENSE_MODE_FLEXABLE_GEOMETRY:
  1164. m_buf[a + 0] = SCSI_SENSE_MODE_FLEXABLE_GEOMETRY;
  1165. m_buf[a + 1] = 0x1E; // Page length
  1166. m_buf[a + 2] = 0x03E8; // Transfer rate 1 mbit/s
  1167. m_buf[a + 4] = 16; // Number of heads
  1168. m_buf[a + 5] = 18; // Sectors per track
  1169. m_buf[a + 6] = 0x2000; // Data bytes per sector
  1170. a += 0x1E;
  1171. if(pageCode != SCSI_SENSE_MODE_ALL) break;
  1172. case SCSI_SENSE_MODE_VENDOR_APPLE:
  1173. {
  1174. const byte page30[0x14] = {0x41, 0x50, 0x50, 0x4C, 0x45, 0x20, 0x43, 0x4F, 0x4D, 0x50, 0x55, 0x54, 0x45, 0x52, 0x2C, 0x20, 0x49, 0x4E, 0x43, 0x20};
  1175. m_buf[a + 0] = SCSI_SENSE_MODE_VENDOR_APPLE; // Page code
  1176. m_buf[a + 1] = sizeof(page30); // Page length
  1177. if(pageControl != 1) {
  1178. memcpy(&m_buf[a + 2], page30, sizeof(page30));
  1179. }
  1180. a += 2 + sizeof(page30);
  1181. if(pageCode != SCSI_SENSE_MODE_ALL) break;
  1182. }
  1183. break; // Don't want SCSI_SENSE_MODE_ALL falling through to error condition
  1184. default:
  1185. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1186. m_addition_sense = SCSI_ASC_INVALID_FIELD_IN_CDB;
  1187. return SCSI_STATUS_CHECK_CONDITION;
  1188. break;
  1189. }
  1190. if(scsi_cmd == SCSI_MODE_SENSE10)
  1191. {
  1192. m_buf[1] = a - 2;
  1193. m_buf[7] = 0x08;
  1194. }
  1195. else
  1196. {
  1197. m_buf[0] = a - 1;
  1198. m_buf[3] = 0x08;
  1199. }
  1200. writeDataPhase(len < a ? len : a, m_buf);
  1201. return SCSI_STATUS_GOOD;
  1202. }
  1203. byte onModeSelectCommand(byte scsi_cmd, byte flags, uint32_t len)
  1204. {
  1205. if (len > MAX_BLOCKSIZE) {
  1206. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1207. m_addition_sense = SCSI_ASC_INVALID_FIELD_IN_CDB;
  1208. return SCSI_STATUS_CHECK_CONDITION;
  1209. }
  1210. readDataPhase(len, m_buf);
  1211. //Apple HD SC Setup sends:
  1212. //0 0 0 8 0 0 0 0 0 0 2 0 0 2 10 0 1 6 24 10 8 0 0 0
  1213. //I believe mode page 0 set to 10 00 is Disable Unit Attention
  1214. //Mode page 1 set to 24 10 08 00 00 00 is TB and PER set, read retry count 16, correction span 8
  1215. #if DEBUG > 0
  1216. for (unsigned i = 0; i < len; i++) {
  1217. LOGHEX(m_buf[i]);LOG(" ");
  1218. }
  1219. LOGN("");
  1220. #endif
  1221. return SCSI_STATUS_GOOD;
  1222. }
  1223. /*
  1224. * Test Unit Ready command processing.
  1225. */
  1226. byte onTestUnitReady()
  1227. {
  1228. // Check that image file is present
  1229. if(!m_img) {
  1230. m_senseKey = SCSI_SENSE_NOT_READY;
  1231. m_addition_sense = SCSI_ASC_MEDIUM_NOT_PRESENT;
  1232. return SCSI_STATUS_CHECK_CONDITION;
  1233. }
  1234. return SCSI_STATUS_GOOD;
  1235. }
  1236. /*
  1237. * ReZero Unit - Move to Logical Block Zero in file.
  1238. */
  1239. byte onReZeroUnit() {
  1240. LOGN("-ReZeroUnit");
  1241. // Make sure we have an image with atleast a first byte.
  1242. // Actually seeking to the position wont do anything, so dont.
  1243. return checkBlockCommand(0, 0);
  1244. }
  1245. /*
  1246. * WriteBuffer - Used for testing buffer, no change to medium
  1247. */
  1248. byte onWriteBuffer(byte mode, uint32_t allocLength)
  1249. {
  1250. LOGN("-WriteBuffer");
  1251. LOGHEXN(mode);
  1252. LOGHEXN(allocLength);
  1253. if (mode == MODE_COMBINED_HEADER_DATA && (allocLength - 4) <= SCSI_BUF_SIZE)
  1254. {
  1255. byte tmp[allocLength];
  1256. readDataPhase(allocLength, tmp);
  1257. // Drop header
  1258. memcpy(m_scsi_buf, (&tmp[4]), allocLength - 4);
  1259. #if DEBUG > 0
  1260. for (unsigned i = 0; i < allocLength; i++) {
  1261. LOGHEX(tmp[i]);LOG(" ");
  1262. }
  1263. LOGN("");
  1264. #endif
  1265. return SCSI_STATUS_GOOD;
  1266. }
  1267. else if ( mode == MODE_DATA && allocLength <= SCSI_BUF_SIZE)
  1268. {
  1269. readDataPhase(allocLength, m_scsi_buf);
  1270. #if DEBUG > 0
  1271. for (unsigned i = 0; i < allocLength; i++) {
  1272. LOGHEX(m_scsi_buf[i]);LOG(" ");
  1273. }
  1274. LOGN("");
  1275. #endif
  1276. return SCSI_STATUS_GOOD;
  1277. }
  1278. else
  1279. {
  1280. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1281. m_addition_sense = SCSI_ASC_INVALID_FIELD_IN_CDB;
  1282. return SCSI_STATUS_CHECK_CONDITION;
  1283. }
  1284. }
  1285. /*
  1286. * ReadBuffer - Used for testing buffer, no change to medium
  1287. */
  1288. byte onReadBuffer(byte mode, uint32_t allocLength)
  1289. {
  1290. LOGN("-ReadBuffer");
  1291. LOGHEXN(mode);
  1292. LOGHEXN(allocLength);
  1293. if (mode == MODE_COMBINED_HEADER_DATA)
  1294. {
  1295. byte scsi_buf_response[SCSI_BUF_SIZE + 4];
  1296. // four byte read buffer header
  1297. scsi_buf_response[0] = 0;
  1298. scsi_buf_response[1] = (SCSI_BUF_SIZE >> 16) & 0xff;
  1299. scsi_buf_response[2] = (SCSI_BUF_SIZE >> 8) & 0xff;
  1300. scsi_buf_response[3] = SCSI_BUF_SIZE & 0xff;
  1301. // actual data
  1302. memcpy((&scsi_buf_response[4]), m_scsi_buf, SCSI_BUF_SIZE);
  1303. writeDataPhase(SCSI_BUF_SIZE + 4, scsi_buf_response);
  1304. #if DEBUG > 0
  1305. for (unsigned i = 0; i < allocLength; i++) {
  1306. LOGHEX(m_scsi_buf[i]);LOG(" ");
  1307. }
  1308. LOGN("");
  1309. #endif
  1310. return SCSI_STATUS_GOOD;
  1311. }
  1312. else if (mode == MODE_DATA)
  1313. {
  1314. writeDataPhase(allocLength, m_scsi_buf);
  1315. #if DEBUG > 0
  1316. for (unsigned i = 0; i < allocLength; i++) {
  1317. LOGHEX(m_scsi_buf[i]);LOG(" ");
  1318. }
  1319. LOGN("");
  1320. #endif
  1321. return SCSI_STATUS_GOOD;
  1322. }
  1323. else
  1324. {
  1325. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1326. m_addition_sense = SCSI_ASC_INVALID_FIELD_IN_CDB;
  1327. return SCSI_STATUS_CHECK_CONDITION;
  1328. }
  1329. }
  1330. /*
  1331. * On Send Diagnostic
  1332. */
  1333. byte onSendDiagnostic(byte flags)
  1334. {
  1335. int self_test = flags & 0x4;
  1336. LOGN("-SendDiagnostic");
  1337. LOGHEXN(flags);
  1338. if(self_test)
  1339. {
  1340. // Don't actually do a test, we're good.
  1341. return SCSI_STATUS_GOOD;
  1342. }
  1343. else
  1344. {
  1345. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1346. m_addition_sense = SCSI_ASC_INVALID_FIELD_IN_CDB;
  1347. return SCSI_STATUS_CHECK_CONDITION;
  1348. }
  1349. }
  1350. /*
  1351. * MsgIn2.
  1352. */
  1353. void MsgIn2(int msg)
  1354. {
  1355. LOGN("MsgIn2");
  1356. SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEIN);
  1357. // Bus settle delay 400ns built in to writeHandshake
  1358. writeHandshake(msg);
  1359. }
  1360. /*
  1361. * Main loop.
  1362. */
  1363. void loop()
  1364. {
  1365. #ifdef XCVR
  1366. // Reset all DB and Target pins, switch transceivers to input
  1367. // Precaution against bugs or jumps which don't clean up properly
  1368. SCSI_DB_INPUT();
  1369. TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT)
  1370. SCSI_TARGET_INACTIVE();
  1371. TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT)
  1372. #endif
  1373. //int msg = 0;
  1374. m_msg = 0;
  1375. // Wait until RST = H, BSY = H, SEL = L
  1376. do {} while( SCSI_IN(vBSY) || !SCSI_IN(vSEL) || SCSI_IN(vRST));
  1377. // BSY+ SEL-
  1378. // If the ID to respond is not driven, wait for the next
  1379. //byte db = readIO();
  1380. //byte scsiid = db & scsi_id_mask;
  1381. byte scsiid = readIO() & scsi_id_mask;
  1382. if((scsiid) == 0) {
  1383. delayMicroseconds(1);
  1384. return;
  1385. }
  1386. LOGN("Selection");
  1387. m_isBusReset = false;
  1388. if (setjmp(m_resetJmpBuf) == 1) {
  1389. LOGN("Reset, going to BusFree");
  1390. goto BusFree;
  1391. }
  1392. enableResetJmp();
  1393. // Set BSY to-when selected
  1394. SCSI_BSY_ACTIVE(); // Turn only BSY output ON, ACTIVE
  1395. // Ask for a TARGET-ID to respond
  1396. m_id = 31 - __builtin_clz(scsiid);
  1397. // Wait until SEL becomes inactive
  1398. while(isHigh(gpio_read(SEL)) && isLow(gpio_read(BSY))) {
  1399. }
  1400. #ifdef XCVR
  1401. // Reconfigure target pins to output mode, after resetting their values
  1402. GPIOB->regs->BSRR = 0x000000E8; // MSG, CD, REQ, IO
  1403. // GPIOA->regs->BSRR = 0x00000200; // BSY
  1404. #endif
  1405. SCSI_TARGET_ACTIVE() // (BSY), REQ, MSG, CD, IO output turned on
  1406. //
  1407. if(isHigh(gpio_read(ATN))) {
  1408. SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEOUT);
  1409. // Bus settle delay 400ns. Following code was measured at 350ns before REQ asserted. Added another 50ns. STM32F103.
  1410. SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEOUT);// 28ns delay STM32F103
  1411. SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEOUT);// 28ns delay STM32F103
  1412. bool syncenable = false;
  1413. int syncperiod = 50;
  1414. int syncoffset = 0;
  1415. int msc = 0;
  1416. while(isHigh(gpio_read(ATN)) && msc < 255) {
  1417. m_msb[msc++] = readHandshake();
  1418. }
  1419. for(int i = 0; i < msc; i++) {
  1420. // ABORT
  1421. if (m_msb[i] == 0x06) {
  1422. goto BusFree;
  1423. }
  1424. // BUS DEVICE RESET
  1425. if (m_msb[i] == 0x0C) {
  1426. syncoffset = 0;
  1427. goto BusFree;
  1428. }
  1429. // IDENTIFY
  1430. if (m_msb[i] >= 0x80) {
  1431. }
  1432. // Extended message
  1433. if (m_msb[i] == 0x01) {
  1434. // Check only when synchronous transfer is possible
  1435. if (!syncenable || m_msb[i + 2] != 0x01) {
  1436. MsgIn2(0x07);
  1437. break;
  1438. }
  1439. // Transfer period factor(50 x 4 = Limited to 200ns)
  1440. syncperiod = m_msb[i + 3];
  1441. if (syncperiod > 50) {
  1442. syncperiod = 50;
  1443. }
  1444. // REQ/ACK offset(Limited to 16)
  1445. syncoffset = m_msb[i + 4];
  1446. if (syncoffset > 16) {
  1447. syncoffset = 16;
  1448. }
  1449. // STDR response message generation
  1450. MsgIn2(0x01);
  1451. MsgIn2(0x03);
  1452. MsgIn2(0x01);
  1453. MsgIn2(syncperiod);
  1454. MsgIn2(syncoffset);
  1455. break;
  1456. }
  1457. }
  1458. }
  1459. LOG("Command:");
  1460. SCSI_PHASE_CHANGE(SCSI_PHASE_COMMAND);
  1461. // Bus settle delay 400ns. The following code was measured at 20ns before REQ asserted. Added another 380ns. STM32F103.
  1462. 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
  1463. int len;
  1464. byte cmd[12];
  1465. cmd[0] = readHandshake();
  1466. LOGHEX(cmd[0]);
  1467. // Command length selection, reception
  1468. static const int cmd_class_len[8]={6,10,10,6,6,12,6,6};
  1469. len = cmd_class_len[cmd[0] >> 5];
  1470. cmd[1] = readHandshake(); LOG(":");LOGHEX(cmd[1]);
  1471. cmd[2] = readHandshake(); LOG(":");LOGHEX(cmd[2]);
  1472. cmd[3] = readHandshake(); LOG(":");LOGHEX(cmd[3]);
  1473. cmd[4] = readHandshake(); LOG(":");LOGHEX(cmd[4]);
  1474. cmd[5] = readHandshake(); LOG(":");LOGHEX(cmd[5]);
  1475. // Receive the remaining commands
  1476. for(int i = 6; i < len; i++ ) {
  1477. cmd[i] = readHandshake();
  1478. LOG(":");
  1479. LOGHEX(cmd[i]);
  1480. }
  1481. // LUN confirmation
  1482. m_sts = cmd[1]&0xe0; // Preset LUN in status byte
  1483. m_lun = m_sts>>5;
  1484. // HDD Image selection
  1485. m_img = (HDDIMG *)0; // None
  1486. if( (m_lun <= NUM_SCSILUN) )
  1487. {
  1488. m_img = &(img[m_id][m_lun]); // There is an image
  1489. if(!(m_img->m_file.isOpen()))
  1490. m_img = (HDDIMG *)0; // Image absent
  1491. }
  1492. // if(!m_img) m_sts |= 0x02; // Missing image file for LUN
  1493. //LOGHEX(((uint32_t)m_img));
  1494. LOG(":ID ");
  1495. LOG(m_id);
  1496. LOG(":LUN ");
  1497. LOG(m_lun);
  1498. LOGN("");
  1499. switch(cmd[0]) {
  1500. case SCSI_READ6:
  1501. LOGN("[Read6]");
  1502. m_sts |= onReadCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
  1503. break;
  1504. case SCSI_WRITE6:
  1505. LOGN("[Write6]");
  1506. m_sts |= onWriteCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
  1507. break;
  1508. case SCSI_READ10:
  1509. LOGN("[Read10]");
  1510. 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]);
  1511. break;
  1512. case SCSI_WRITE10:
  1513. case SCSI_WRITE_AND_VERIFY:
  1514. LOGN("[Write10]");
  1515. 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]);
  1516. break;
  1517. case SCSI_TEST_UNIT_READY:
  1518. LOGN("[Test Unit Ready]");
  1519. m_sts |= onTestUnitReady();
  1520. break;
  1521. case SCSI_REZERO_UNIT:
  1522. LOGN("[Rezero Unit]");
  1523. m_sts |= onReZeroUnit();
  1524. break;
  1525. case SCSI_REQUEST_SENSE:
  1526. LOGN("[RequestSense]");
  1527. onRequestSenseCommand(cmd[4]);
  1528. break;
  1529. case SCSI_FORMAT_UNIT4: // TODO: Implement me!
  1530. LOGN("[FormatUnit4]");
  1531. break;
  1532. case SCSI_FORMAT_UNIT6: // TODO: Implement me!
  1533. LOGN("[FormatUnit6]");
  1534. break;
  1535. case SCSI_REASSIGN_BLOCKS: // TODO: Implement me!
  1536. LOGN("[ReassignBlocks]");
  1537. break;
  1538. case SCSI_INQUIRY:
  1539. LOGN("[Inquiry]");
  1540. m_sts |= onInquiryCommand(cmd[4]);
  1541. break;
  1542. case SCSI_MODE_SELECT6:
  1543. LOGN("[ModeSelect6]");
  1544. m_sts |= onModeSelectCommand(cmd[0], cmd[1], cmd[4]);
  1545. break;
  1546. case SCSI_MODE_SENSE6:
  1547. LOGN("[ModeSense6]");
  1548. m_sts |= onModeSenseCommand(cmd[0], cmd[1]&0x80, cmd[2], cmd[4]);
  1549. break;
  1550. case SCSI_START_STOP_UNIT: // TODO: Implement me!
  1551. LOGN("[StartStopUnit]");
  1552. break;
  1553. case SCSI_READ_CAPACITY:
  1554. LOGN("[ReadCapacity]");
  1555. m_sts |= onReadCapacityCommand(cmd[8]);
  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. case SCSI_SEEK6:
  1587. case SCSI_SEEK10:
  1588. m_sts |= SCSI_STATUS_GOOD;
  1589. break;
  1590. default:
  1591. LOGN("[*Unknown]");
  1592. m_sts |= SCSI_STATUS_CHECK_CONDITION;
  1593. m_senseKey = SCSI_SENSE_ILLEGAL_REQUEST;
  1594. m_addition_sense = SCSI_ASC_INVALID_OPERATION_CODE;
  1595. break;
  1596. }
  1597. LOGN("Sts");
  1598. SCSI_PHASE_CHANGE(SCSI_PHASE_STATUS);
  1599. // Bus settle delay 400ns built in to writeHandshake
  1600. writeHandshake(m_sts);
  1601. LOGN("MsgIn");
  1602. SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEIN);
  1603. // Bus settle delay 400ns built in to writeHandshake
  1604. writeHandshake(m_msg);
  1605. BusFree:
  1606. LOGN("BusFree");
  1607. m_isBusReset = false;
  1608. //SCSI_OUT(vREQ,inactive) // gpio_write(REQ, low);
  1609. //SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
  1610. //SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
  1611. //SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
  1612. //SCSI_OUT(vBSY,inactive)
  1613. SCSI_TARGET_INACTIVE() // Turn off BSY, REQ, MSG, CD, IO output
  1614. #ifdef XCVR
  1615. TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT);
  1616. #endif
  1617. }