Browse Source

Added sw files

Per Mårtensson 3 years ago
parent
commit
ee26f77c86

+ 39 - 0
sw/include/README

@@ -0,0 +1,39 @@
+
+This directory is intended for project header files.
+
+A header file is a file containing C declarations and macro definitions
+to be shared between several project source files. You request the use of a
+header file in your project source file (C, C++, etc) located in `src` folder
+by including it, with the C preprocessing directive `#include'.
+
+```src/main.c
+
+#include "header.h"
+
+int main (void)
+{
+ ...
+}
+```
+
+Including a header file produces the same results as copying the header file
+into each source file that needs it. Such copying would be time-consuming
+and error-prone. With a header file, the related declarations appear
+in only one place. If they need to be changed, they can be changed in one
+place, and programs that include the header file will automatically use the
+new version when next recompiled. The header file eliminates the labor of
+finding and changing all the copies as well as the risk that a failure to
+find one copy will result in inconsistencies within a program.
+
+In C, the usual convention is to give header files names that end with `.h'.
+It is most portable to use only letters, digits, dashes, and underscores in
+header file names, and at most one dot.
+
+Read more about using header files in official GCC documentation:
+
+* Include Syntax
+* Include Operation
+* Once-Only Headers
+* Computed Includes
+
+https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

+ 0 - 0
sw/include/blacksasi.h


+ 46 - 0
sw/lib/README

@@ -0,0 +1,46 @@
+
+This directory is intended for project specific (private) libraries.
+PlatformIO will compile them to static libraries and link into executable file.
+
+The source code of each library should be placed in a an own separate directory
+("lib/your_library_name/[here are source files]").
+
+For example, see a structure of the following two libraries `Foo` and `Bar`:
+
+|--lib
+|  |
+|  |--Bar
+|  |  |--docs
+|  |  |--examples
+|  |  |--src
+|  |     |- Bar.c
+|  |     |- Bar.h
+|  |  |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
+|  |
+|  |--Foo
+|  |  |- Foo.c
+|  |  |- Foo.h
+|  |
+|  |- README --> THIS FILE
+|
+|- platformio.ini
+|--src
+   |- main.c
+
+and a contents of `src/main.c`:
+```
+#include <Foo.h>
+#include <Bar.h>
+
+int main (void)
+{
+  ...
+}
+
+```
+
+PlatformIO Library Dependency Finder will find automatically dependent
+libraries scanning project source files.
+
+More information about PlatformIO Library Dependency Finder
+- https://docs.platformio.org/page/librarymanager/ldf.html

+ 56 - 0
sw/platformio.ini

@@ -0,0 +1,56 @@
+; PlatformIO Project Configuration File
+;
+;   Build options: build flags, source filter
+;   Upload options: custom upload port, speed and extra flags
+;   Library options: dependencies, extra library storages
+;   Advanced options: extra scripting
+;
+; Please visit documentation for the other options and examples
+; https://docs.platformio.org/page/projectconf.html
+
+[env:blacksasi_f411]
+platform = ststm32
+board = blacksasi_f411m
+board.variants_dir = /home/pm/project/stm32/BlackSASI/sw/variant/blacksasi_f411m
+framework = arduino
+board_build.core = maple
+lib_deps =
+    greiman/SdFat@^2.1.2
+    bblanchon/ArduinoJson@^6.19.3
+upload_protocol = stlink
+debug_tool = stlink
+; Different gcc versions produce much different binaries in terms of speed.
+; 1.40804.0 ; 985kb/sec
+; 1.60301.0 ; 1012kb/sec ***
+; 1.70201.0 ; 926kb/sec
+; 1.80301.0 ; 935kb/sec
+; 1.80201.181220 ; 921kb/sec
+; 1.90201.191206 ; 912kb/sec
+; 1.90301.200702 ; default - 955kb/sec
+platform_packages = toolchain-gccarmnoneeabi@1.60301.0
+
+build_unflags = 
+    -Os
+    -DARDUINO_ARCH_STM32F4
+build_flags = 
+    -w
+    -DARDUINO_BLACKSASI_F411M
+    -DARDUINO_LIB_DISCOVERY_PHASE
+    -DARDUINO=10813
+    -DARDUINO_ARCH_STM32
+    -O2
+    -DSERIAL_USB
+    -DCRYSTAL_FREQ=25
+    -DLED_BUILTIN=PA5
+    -DUSBCON
+    -DPIO_FRAMEWORK_ARDUINO_ENABLE_CDC
+    -DUSBD_VID=0x0483
+    -DUSBD_PID=0x0100
+    -DUSB_MANUFACTURER="SweProj"
+    -DUSB_PRODUCT="\"BLACKSASI_F411\""
+    -DHAL_PCD_MODULE_ENABLED
+    -D USBD_USE_CDC
+
+; [env:debug]
+; build_type = debug
+; debug_tool = stlink

+ 1645 - 0
sw/src/blacksasi.cpp

@@ -0,0 +1,1645 @@
+/*  
+ *  F4 BlueSCSI
+ *  Copyright (c) 2021  Eric Helgeson, Tech by Androda, LLC
+ *  
+ *  This file is free software: you may copy, redistribute and/or modify it  
+ *  under the terms of the GNU General Public License as published by the  
+ *  Free Software Foundation, either version 2 of the License, or (at your  
+ *  option) any later version.  
+ *  
+ *  This file is distributed in the hope that it will be useful, but  
+ *  WITHOUT ANY WARRANTY; without even the implied warranty of  
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
+ *  General Public License for more details.  
+ *  
+ *  You should have received a copy of the GNU General Public License  
+ *  along with this program.  If not, see https://github.com/erichelgeson/bluescsi.  
+ *  
+ * This file incorporates work covered by the following copyright and  
+ * permission notice:  
+ *  
+ *     Copyright (c) 2019 komatsu   
+ *  
+ *     Permission to use, copy, modify, and/or distribute this software  
+ *     for any purpose with or without fee is hereby granted, provided  
+ *     that the above copyright notice and this permission notice appear  
+ *     in all copies.  
+ *  
+ *     THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL  
+ *     WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED  
+ *     WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE  
+ *     AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR  
+ *     CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS  
+ *     OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,  
+ *     NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN  
+ *     CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  
+ */
+ 
+#pragma GCC diagnostic warning "-fpermissive"
+
+#include <Arduino.h> // For Platform.IO
+#include <SPI.h>
+#include <SdFat.h>
+#include "sdios.h"
+#define SPI_CLOCK SD_SCK_MHZ(50)
+#ifdef USE_STM32_DMA
+#warning "warning USE_STM32_DMA"
+#endif
+#define DEBUG            1      // 0:No debug information output
+                                // 1: Debug information output to USB Serial
+                                // 2: Debug information output to LOG.txt (slow)
+
+#define SCSI_SELECT      0      // 0 for STANDARD
+                                // 1 for SHARP X1turbo
+                                // 2 for NEC PC98
+#define READ_SPEED_OPTIMIZE  1 // Faster reads
+#define WRITE_SPEED_OPTIMIZE 1 // Speeding up writes
+#define USE_DB2ID_TABLE      1 // Use table to get ID from SEL-DB
+
+// SCSI config
+#define NUM_SCSIID  7          // Maximum number of supported SCSI-IDs (The minimum is 0)
+#define NUM_SCSILUN 2          // Maximum number of LUNs supported     (The minimum is 0)
+#define READ_PARITY_CHECK 0    // Perform read parity check (unverified)
+
+// HDD format
+#define MAX_BLOCKSIZE 2048     // Maximum BLOCK size
+
+// SDFAT
+SdFs SD;
+
+#if DEBUG == 1
+#define serial Serial
+#define LOG(XX)      serial.print(XX)
+#define LOGHEX(XX)   serial.print(XX, HEX)
+#define LOGDEC(XX)   serial.print(XX, DEC)
+#define LOGBIN(XX)   serial.print(XX, BIN)
+#define LOGN(XX)     serial.println(XX)
+#define LOGHEXN(XX)  serial.println(XX, HEX)
+#define LOGDECN(XX)  serial.println(XX, DEC)
+#define LOGBIN_N(XX) serial.println(XX, BIN)
+#elif DEBUG == 2
+#define LOG(XX)      LOG_FILE.print(XX); LOG_FILE.sync();
+#define LOGHEX(XX)   LOG_FILE.print(XX, HEX); LOG_FILE.sync();
+#define LOGDEC(XX)   LOG_FILE.print(XX, DEC); LOG_FILE.sync();
+#define LOGBIN(XX)   LOG_FILE.print(XX, BIN); LOG_FILE.sync();
+#define LOGN(XX)     LOG_FILE.println(XX); LOG_FILE.sync();
+#define LOGHEXN(XX)  LOG_FILE.println(XX, HEX); LOG_FILE.sync();
+#define LOGDECN(XX)  LOG_FILE.println(XX, DEC); LOG_FILE.sync();
+#define LOGBIN_N(XX) LOG_FILE.println(XX, BIN); LOG_FILE.sync();
+#else
+#define LOG(XX)       //serial.print(XX)
+#define LOGHEX(XX)    //serial.print(XX, HEX)
+#define LOGDEC(XX)    //serial.print(XX, DEC)
+#define LOGBIN(XX)    //serial.print(XX, BIN)
+#define LOGN(XX)      //serial.println(XX)
+#define LOGHEXN(XX)   //serial.println(XX, HEX)
+#define LOGDECN(XX)   //serial.println(XX, DEC)
+#define LOGBIN_N(XX)  //serial.println(XX, BIN)
+#endif
+
+#define active   1
+#define inactive 0
+#define high 0
+#define low 1
+
+#define isHigh(XX) ((XX) == high)
+#define isLow(XX) ((XX) != high)
+
+
+// GPIO register port
+#define PAREG GPIOA->regs
+#define PBREG GPIOB->regs
+#define PCREG GPIOC->regs
+#define PDREG GPIOD->regs
+#define PEREG GPIOE->regs
+
+// LED control
+#define LED1_ON()           PAREG->BSRR = 0b0000000000010000;
+#define LED1_OFF()          PAREG->BSRR = 0b0000000000010000 << 16;
+#define LED2_ON()           PAREG->BSRR = 0b0000000000100000;
+#define LED2_OFF()          PAREG->BSRR = 0b0000000000100000 << 16;
+#define LED3_ON()           PAREG->BSRR = 0b0000000001000000;
+#define LED3_OFF()          PAREG->BSRR = 0b0000000001000000 << 16;
+#define LED_EXT_ON()        PAREG->BSRR = 0b0000000000000001;
+#define LED_EXT_OFF()       PAREG->BSRR = 0b0000000000000001 << 16;
+
+// Termination controll
+#define TERMINATION_HIGH()  PBREG->BSRR = 0b0000000100000000 << 16 | 0b0000001000000000 ;
+#define TERMINATION_LOW()   PBREG->BSRR = 0b0000001000000000 << 16 | 0b0000000100000000 ;
+#define TERMINATION_OFF()   PBREG->BSRR = 0b0000001100000000 ;
+
+// Virtual pin (Arduio compatibility is slow, so make it MCU-dependent)
+#define PA(BIT)       (BIT)
+#define PB(BIT)       (BIT + 16)
+#define PC(BIT)       (BIT + 32)
+#define PD(BIT)       (BIT + 48)
+#define PE(BIT)       (BIT + 64)
+// Virtual pin decoding
+#define GPIOREG(VPIN)     ((VPIN) >= 16 ? PBREG : PAREG)
+#define BITMASK(VPIN)     (1 << ((VPIN) & 15))
+
+#define vATN       PB(14)      // SCSI:ATN
+#define vBSY       PB(6)      // SCSI:BSY
+#define vACK       PB(7)      // SCSI:ACK
+#define vRST       PA(15)     // SCSI:RST
+#define vMSG       PE(2)      // SCSI:MSG
+#define vSEL       PE(3)      // SCSI:SEL
+#define vCD        PE(4)      // SCSI:C/D
+#define vREQ       PE(5)      // SCSI:REQ
+#define vIO        PE(6)      // SCSI:I/O
+#define vSD_CS     PB(1)      // SDCARD:CS
+#define vDTD       PC(0)      // SCSI:DTD
+#define vIND       PC(1)      // SCSI:IND
+#define vTAD       PC(2)      // SCSI:TAD
+
+// SCSI output pin control: opendrain active LOW (direct pin drive)
+#define SCSI_OUT(VPIN,ACTIVE) { GPIOREG(VPIN)->BSRR = BITMASK(VPIN) << ((ACTIVE) ? 16 : 0); }
+
+// SCSI input pin check (inactive=0,active=1)
+#define SCSI_IN(VPIN) ((~GPIOREG(VPIN)->IDR >> (VPIN & 15)) & 1)
+
+static const uint32_t scsiDbOutputRegOr = 0x55150011;
+static const uint32_t scsiDbInputOutputAnd = 0x00C0FFCC;
+// Put DB and DP in output mode
+#define SCSI_DB_OUTPUT() { PBREG->MODER = (PBREG->MODER & scsiDbInputOutputAnd) | scsiDbOutputRegOr; }
+
+// Put DB and DP in input mode
+#define SCSI_DB_INPUT()  { PBREG->MODER = (PBREG->MODER & scsiDbInputOutputAnd); }
+
+// Turn on the output only for BSY
+#define SCSI_BSY_ACTIVE()      { pinMode(BOARD_SCSI_BSY, OUTPUT_OPEN_DRAIN); SCSI_OUT(vBSY,  active) }
+// BSY,REQ,MSG,CD,IO Turn on the output (no change required for OD)
+#define SCSI_TARGET_ACTIVE()   { }
+// BSY,REQ,MSG,CD,IO Turn off output, BSY is the last input
+#define SCSI_TARGET_INACTIVE() { SCSI_OUT(vREQ,inactive); SCSI_OUT(vMSG,inactive); SCSI_OUT(vCD,inactive); SCSI_OUT(vIO,inactive); SCSI_OUT(vBSY,inactive); pinMode(BOARD_SCSI_BSY, INPUT); }
+
+// HDDiamge file
+#define HDIMG_ID_POS  2                 // Position to embed ID number
+#define HDIMG_LUN_POS 3                 // Position to embed LUN numbers
+#define HDIMG_BLK_POS 5                 // Position to embed block size numbers
+#define MAX_FILE_PATH 32                // Maximum file name length
+static ArduinoOutStream cout(Serial);
+// HDD image
+uint16_t imageSelect = 0;
+typedef struct hddimg_struct
+{
+	FsFile      m_file;                 // File object
+	uint64_t    m_fileSize;             // File size
+	size_t      m_blocksize;            // SCSI BLOCK size
+}HDDIMG;
+HDDIMG  img[NUM_SCSIID][NUM_SCSILUN]; // Maximum number
+
+uint8_t       m_senseKey = 0;         // Sense key
+unsigned      m_addition_sense = 0;   // Additional sense information
+volatile bool m_isBusReset = false;   // Bus reset
+
+byte          scsi_id_mask;           // Mask list of responding SCSI IDs
+byte          m_id;                   // Currently responding SCSI-ID
+byte          m_lun;                  // Logical unit number currently responding
+byte          m_sts;                  // Status byte
+byte          m_msg;                  // Message bytes
+HDDIMG       *m_img;                  // HDD image for current SCSI-ID, LUN
+byte          m_buf[MAX_BLOCKSIZE+1]; // General purpose buffer + overrun fetch
+int           m_msc;
+byte          m_msb[256];             // Command storage bytes
+
+/*
+ *  Data byte to BSRR register setting value and parity table
+*/
+
+/**
+ * BSRR register generator
+ * Totally configurable for which pin is each data bit, which pin is PTY, and which pin is REQ.
+ * The only requirement is that data and parity pins are in the same GPIO block.
+ * REQ can be specified as -1 to ignore, as it doens't have to be in the same GPIO block.
+ * This is dramatically slower than the original static array, but is easier to configure
+ */
+static uint32_t genBSRR(uint32_t data) {
+  uint8_t masks[] = {0UL, 1UL, 2UL, 3UL, 4UL, 5UL, 6UL, 7UL};
+  // Positions array indicates which bit position each data bit goes in
+  // positions[0] is for data bit 0, position[1] for data bit 1, etc
+  // DB0, DB1, DB2, DB4, DB5, DB6, DB7 in order
+  uint8_t positions[] = {8UL, 9UL, 10UL, 2UL, 12UL, 13UL, 14UL, 15UL};
+  uint8_t dbpPosition = 0UL;
+  int reqPosition = 6;
+  uint8_t bitsAsserted = 0;
+
+  uint32_t output = 0x00000000;
+  for (int i = 0; i < 8; i++) {
+    if (data & (0x1 << masks[i])) {
+      // There's a one in this bit position, BSRR reset
+      output |= 0x1 << (positions[i] + 16);
+      bitsAsserted++;
+    } else {
+      // There's a 0 in this bit position, BSRR set high
+      output |= (0x1 << positions[i]);
+    }
+  }
+
+  // Set the parity bit
+  if (bitsAsserted % 2 == 0) {
+    // Even number of bits asserted, Parity asserted (0, low, BSRR reset)
+    output |= 0x01 << (dbpPosition + 16);
+  } else {
+    // Odd number of bits asserted, Parity deasserted (1, high, BSRR set)
+    output |= 0x01 << dbpPosition;
+  }
+
+  // BSRR set REQ if specified
+  // Only set > 0 if it's in the same GPIO block as DB and DBP
+  if (reqPosition >= 0) {
+    output |= 0x01 << reqPosition;
+  }
+
+  return output;
+}
+
+// Set DBP, set REQ = inactive
+#define DBP(D)    genBSRR(D)
+#define DBP8(D)   DBP(D),DBP(D+1),DBP(D+2),DBP(D+3),DBP(D+4),DBP(D+5),DBP(D+6),DBP(D+7)
+#define DBP32(D)  DBP8(D),DBP8(D+8),DBP8(D+16),DBP8(D+24)
+
+// BSRR register control value that simultaneously performs DB set, DP set, and REQ = H (inactrive)
+static const uint32_t db_bsrr[256]={
+  DBP32(0x00),DBP32(0x20),DBP32(0x40),DBP32(0x60),
+  DBP32(0x80),DBP32(0xA0),DBP32(0xC0),DBP32(0xE0)
+};
+
+// Macro cleaning
+#undef DBP32
+#undef DBP8
+//#undef DBP
+//#undef PTY
+
+#if USE_DB2ID_TABLE
+/* DB to SCSI-ID translation table */
+static const byte db2scsiid[256]={
+  0xff,
+  0,
+  1,1,
+  2,2,2,2,
+  3,3,3,3,3,3,3,3,
+  4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
+  5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+  6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+  6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
+};
+#endif
+
+// Log File
+#define VERSION "1.0-SNAPSHOT-2022-03-20-F4"
+#define LOG_FILENAME "LOG.txt"
+FsFile LOG_FILE;
+
+// SCSI Drive Vendor information
+byte SCSI_INFO_BUF[36] = {
+  0x00, //device type
+  0x00, //RMB = 0
+  0x01, //ISO, ECMA, ANSI version
+  0x01, //Response data format
+  35 - 4, //Additional data length
+  0, 0, //Reserve
+  0x00, //Support function
+  'Q', 'U', 'A', 'N', 'T', 'U', 'M', ' ', // vendor 8
+  'F', 'I', 'R', 'E', 'B', 'A', 'L', 'L', '1', ' ', ' ',' ', ' ', ' ', ' ', ' ', // product 16
+  '1', '.', '0', ' ' // version 4
+};
+
+void onFalseInit(void);
+void noSDCardFound(void);
+void onBusReset(void);
+void sdCardInsert(void);
+void switchImage(void);
+void initFileLog(void);
+void finalizeFileLog(void);
+//------------------------------------------------------------------------------
+
+
+void errorPrint() {
+  if (SD.sdErrorCode()) {
+    cout << F("SD errorCode: ") << hex << showbase;
+    printSdErrorSymbol(&Serial, SD.sdErrorCode());
+    cout << F(" = ") << int(SD.sdErrorCode()) << endl;
+    cout << F("SD errorData = ") << int(SD.sdErrorData()) << endl;
+  }
+}
+//------------------------------------------------------------------------------
+void dmpVol() {
+  cout << F("\nScanning FAT, please wait.\n");
+  uint32_t freeClusterCount = SD.freeClusterCount();
+  if (SD.fatType() <= 32) {
+    cout << F("\nVolume is FAT") << int(SD.fatType()) << endl;
+  } else {
+    cout << F("\nVolume is exFAT\n");
+  }
+  cout << F("sectorsPerCluster: ") << SD.sectorsPerCluster() << endl;
+  cout << F("clusterCount:      ") << SD.clusterCount() << endl;
+  cout << F("freeClusterCount:  ") << freeClusterCount << endl;
+  cout << F("fatStartSector:    ") << SD.fatStartSector() << endl;
+  cout << F("dataStartSector:   ") << SD.dataStartSector() << endl;
+
+}
+/*
+ * IO read.
+ */
+inline byte readIO(void)
+{
+  // Port input data register
+  uint32_t ret = GPIOB->regs->IDR;
+  byte bret = (byte)~(((ret >> 8) & 0b11110111) | ((ret & 0x00000004) << 1));
+  
+#if READ_PARITY_CHECK
+  if((db_bsrr[bret]^ret)&1)  // TODO fix parity calculation
+    m_sts |= 0x01; // parity error
+#endif
+
+  return bret;
+}
+
+// If config file exists, read the first three lines and copy the contents.
+// File must be well formed or you will get junk in the SCSI Vendor fields.
+void readSCSIDeviceConfig() {
+  FsFile config_file = SD.open("scsi-config.txt", O_RDONLY);
+  if (!config_file.isOpen()) {
+    return;
+  }
+  char vendor[9];
+  memset(vendor, 0, sizeof(vendor));
+  config_file.readBytes(vendor, sizeof(vendor));
+  LOG_FILE.print("SCSI VENDOR: ");
+  LOG_FILE.println(vendor);
+  memcpy(&(SCSI_INFO_BUF[8]), vendor, 8);
+
+  char product[17];
+  memset(product, 0, sizeof(product));
+  config_file.readBytes(product, sizeof(product));
+  LOG_FILE.print("SCSI PRODUCT: ");
+  LOG_FILE.println(product);
+  memcpy(&(SCSI_INFO_BUF[16]), product, 16);
+
+  char version[5];
+  memset(version, 0, sizeof(version));
+  config_file.readBytes(version, sizeof(version));
+  LOG_FILE.print("SCSI VERSION: ");
+  LOG_FILE.println(version);
+  memcpy(&(SCSI_INFO_BUF[32]), version, 4);
+  config_file.close();
+}
+
+// read SD information and print to logfile
+void readSDCardInfo()
+{
+  cid_t sd_cid;
+
+  if(SD.card()->readCID(&sd_cid))
+  {
+    Serial.print("Sd MID:");
+    Serial.print(sd_cid.mid, 16);
+    Serial.print(" OID:");
+    Serial.print(sd_cid.oid[0]);
+    Serial.println(sd_cid.oid[1]);
+
+    Serial.print("Sd Name:");
+    Serial.print(sd_cid.pnm[0]);
+    Serial.print(sd_cid.pnm[1]);
+    Serial.print(sd_cid.pnm[2]);
+    Serial.print(sd_cid.pnm[3]);
+    Serial.println(sd_cid.pnm[4]);
+
+    Serial.print("Sd Date:");
+    Serial.print(sd_cid.mdt_month);
+    Serial.print("/20"); // CID year is 2000 + high/low
+    Serial.print(sd_cid.mdt_year_high);
+    Serial.println(sd_cid.mdt_year_low);
+
+    Serial.print("Sd Serial:");
+    Serial.println(sd_cid.psn);
+  }
+}
+void readSDCardInfo2()
+{
+  cid_t sd_cid;
+
+  if(SD.card()->readCID(&sd_cid))
+  {
+    LOG_FILE.print("Sd MID:");
+    LOG_FILE.print(sd_cid.mid, 16);
+    LOG_FILE.print(" OID:");
+    LOG_FILE.print(sd_cid.oid[0]);
+    LOG_FILE.println(sd_cid.oid[1]);
+
+    LOG_FILE.print("Sd Name:");
+    LOG_FILE.print(sd_cid.pnm[0]);
+    LOG_FILE.print(sd_cid.pnm[1]);
+    LOG_FILE.print(sd_cid.pnm[2]);
+    LOG_FILE.print(sd_cid.pnm[3]);
+    LOG_FILE.println(sd_cid.pnm[4]);
+
+    LOG_FILE.print("Sd Date:");
+    LOG_FILE.print(sd_cid.mdt_month);
+    LOG_FILE.print("/20"); // CID year is 2000 + high/low
+    LOG_FILE.print(sd_cid.mdt_year_high);
+    LOG_FILE.println(sd_cid.mdt_year_low);
+
+    LOG_FILE.print("Sd Serial:");
+    LOG_FILE.println(sd_cid.psn);
+    LOG_FILE.sync();
+  }
+}
+/*
+ * Open HDD image file
+ */
+
+bool hddimageOpen(HDDIMG *h,const char *image_name,int id,int lun,int blocksize)
+{
+  h->m_fileSize = 0;
+  h->m_blocksize = blocksize;
+  h->m_file = SD.open(image_name, O_RDWR);
+  if(h->m_file.isOpen())
+  {
+    h->m_fileSize = h->m_file.size();
+    LOG_FILE.print("Imagefile: ");
+    LOG_FILE.print(image_name);
+    if(h->m_fileSize>0)
+    {
+      // check blocksize dummy file
+      LOG_FILE.print(" / ");
+      LOG_FILE.print(h->m_fileSize);
+      LOG_FILE.print("bytes / ");
+      LOG_FILE.print(h->m_fileSize / 1024);
+      LOG_FILE.print("KiB / ");
+      LOG_FILE.print(h->m_fileSize / 1024 / 1024);
+      LOG_FILE.println("MiB");
+      return true; // File opened
+    }
+    else
+    {
+      h->m_file.close();
+      h->m_fileSize = h->m_blocksize = 0; // no file
+      LOG_FILE.println("FileSizeError");
+    }
+  }
+  return false;
+}
+/*
+ * Initialization.
+ *  Initialize the bus and set the PIN orientation
+ */
+void setup()
+{
+
+#if DEBUG > 0
+  Serial.begin(19200);
+  delay(3000);
+  Serial.println("BLACKSASI");
+  Serial.println("BLACKSASI");
+  Serial.flush();
+
+#endif
+
+  // PIN initialization
+  pinMode(BOARD_LED1_PIN , OUTPUT);
+  pinMode(BOARD_LED2_PIN , OUTPUT);
+  pinMode(BOARD_LED3_PIN , OUTPUT);
+  pinMode(BOARD_SDCARD_INSERT, INPUT_PULLUP);
+  pinMode(BOARD_SWITCH1_PIN , INPUT_PULLUP);
+  pinMode(BOARD_SWITCH2_PIN , INPUT_PULLUP);
+  pinMode(BOARD_SWITCH3_PIN , INPUT_PULLUP);
+  pinMode(BOARD_SWITCH4_PIN , INPUT_PULLUP);
+  pinMode(BOARD_SCSI_TERM_HIGH, OUTPUT);
+  pinMode(BOARD_SCSI_TERM_LOW, OUTPUT);
+  pinMode(BOARD_SCSI_TERM_POWER, INPUT); //Check if external termination power is provided
+
+  //Default turn termination off
+  TERMINATION_HIGH();
+
+  //Turn Power LED ON
+  LED2_ON();
+
+  attachInterrupt(BOARD_SDCARD_INSERT,sdCardInsert, CHANGE);
+
+  //Check if SD card is inserted
+  sdCardInsert();
+
+  attachInterrupt(BOARD_SWITCH1_PIN,switchImage, CHANGE);
+  attachInterrupt(BOARD_SWITCH2_PIN,switchImage, CHANGE);
+  attachInterrupt(BOARD_SWITCH3_PIN,switchImage, CHANGE);
+  attachInterrupt(BOARD_SWITCH4_PIN,switchImage, CHANGE);
+
+  //Check which image to load
+  switchImage();
+  /*
+  // set up OTYPER for open drain on SCSI pins of PA and PB
+  // PA 0-7, 11-14
+  uint32_t oTypeA_And = 0x000078FF;
+  // PA 8, 9, 10, 15
+  uint32_t oTypeA_Or = 0x00008700;
+  GPIOA->regs->OTYPER = (GPIOA->regs->OTYPER & oTypeA_And) | oTypeA_Or;
+
+  // PB 1, 11 are not used
+  uint32_t oTypeB_And = 0x00000802;
+  // PB 0, 2-10, 12-15 are used for SCSI, set open drain
+  uint32_t oTypeB_Or = 0x0000F7FD;
+  GPIOB->regs->OTYPER = (GPIOB->regs->OTYPER & oTypeB_And) | oTypeB_Or;
+*/
+  pinMode(BOARD_SCSI_ATN, INPUT_PULLUP);
+  pinMode(BOARD_SCSI_BSY, INPUT_PULLUP);
+  pinMode(BOARD_SCSI_ACK, INPUT_PULLUP);
+  pinMode(BOARD_SCSI_RST, INPUT_PULLUP);
+  pinMode(BOARD_SCSI_SEL, INPUT_PULLUP);
+
+  // Output port
+  pinMode(BOARD_SCSI_MSG, OUTPUT_OPEN_DRAIN);
+  pinMode(BOARD_SCSI_CD, OUTPUT_OPEN_DRAIN);
+  pinMode(BOARD_SCSI_REQ, OUTPUT_OPEN_DRAIN);
+  pinMode(BOARD_SCSI_IO, OUTPUT_OPEN_DRAIN);
+
+  // Control SCSI drivers
+  pinMode(BOARD_SCSI_DTD, OUTPUT_OPEN_DRAIN);
+  pinMode(BOARD_SCSI_IND, OUTPUT_OPEN_DRAIN);
+  pinMode(BOARD_SCSI_TAD, OUTPUT_OPEN_DRAIN);
+  pinMode(BOARD_TRANS_OE, OUTPUT_OPEN_DRAIN);
+/*
+  // Turn off the output port
+  SCSI_TARGET_INACTIVE()
+  
+  //Occurs when the RST pin state changes from HIGH to LOW
+  //attachInterrupt(PIN_MAP[RST].gpio_bit, onBusReset, FALLING);
+
+  LED_ON();
+   */
+                                        
+  if(!SD.begin(SdSpiConfig(SS, DEDICATED_SPI))) {
+#if DEBUG > 0
+    Serial.println("SD initialization failed!");
+    errorPrint();
+#endif
+    noSDCardFound();
+  }
+  readSDCardInfo();
+  dmpVol();
+  readSCSIDeviceConfig();
+  initFileLog();
+ 
+
+
+
+  //Sector data overrun byte setting
+  m_buf[MAX_BLOCKSIZE] = 0xff; // DB0 all off,DBP off
+  //HD image file open
+  scsi_id_mask = 0x00;
+
+  // Iterate over the root path in the SD card looking for candidate image files.
+  SdFile root;
+  root.open("/");
+  SdFile file;
+  bool imageReady;
+  int usedDefaultId = 0;
+  while (1) {
+    if (!file.openNext(&root, O_READ)) break;
+    char name[MAX_FILE_PATH+1];
+    if(!file.isDir()) {
+      file.getName(name, MAX_FILE_PATH+1);
+      file.close();
+      String file_name = String(name);
+      file_name.toLowerCase();
+      if(file_name.startsWith("hd")) {
+        // Defaults for Hard Disks
+        int id  = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
+        int lun = 0;
+        int blk = 512;
+
+        // Positionally read in and coerase the chars to integers.
+        // We only require the minimum and read in the next if provided.
+        int file_name_length = file_name.length();
+        if(file_name_length > 2) { // HD[N]
+          int tmp_id = name[HDIMG_ID_POS] - '0';
+
+          // If valid id, set it, else use default
+          if(tmp_id > -1 && tmp_id < 8) {
+            id = tmp_id;
+          } else {
+            usedDefaultId++;
+          }
+        }
+
+        int blk1, blk2, blk3, blk4 = 0;
+        if(file_name_length > 8) { // HD00_[111]
+          blk1 = name[HDIMG_BLK_POS] - '0';
+          blk2 = name[HDIMG_BLK_POS+1] - '0';
+          blk3 = name[HDIMG_BLK_POS+2] - '0';
+          if(file_name_length > 9) // HD00_NNN[1]
+            blk4 = name[HDIMG_BLK_POS+3] - '0';
+        }
+        if(blk1 == 2 && blk2 == 5 && blk3 == 6) {
+          blk = 256;
+        } else if(blk1 == 1 && blk2 == 0 && blk3 == 2 && blk4 == 4) {
+          blk = 1024;
+        } else if(blk1 == 2 && blk2 == 0 && blk3 == 4 && blk4 == 8) {
+          blk  = 2048;
+        }
+
+        if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
+          HDDIMG *h = &img[id][lun];
+          imageReady = hddimageOpen(h,name,id,lun,blk);
+          if(imageReady) { // Marked as a responsive ID
+            scsi_id_mask |= 1<<id;
+          }
+        } else {
+          LOG_FILE.print("Bad LUN or SCSI id for image: ");
+          LOG_FILE.println(name);
+          LOG_FILE.sync();
+        }
+      } else {
+          LOG_FILE.print("Not an image: ");
+          LOG_FILE.println(name);
+          LOG_FILE.sync();
+      }
+    }
+  }
+  if(usedDefaultId > 1) {
+    LOG_FILE.println("!! More than one image did not specify a SCSI ID. Last file will be used at ID 1 !!");
+    LOG_FILE.sync();
+  }
+  root.close();
+
+  // Error if there are 0 image files
+  if(scsi_id_mask==0) {
+    LOG_FILE.println("ERROR: No valid images found!");
+    onFalseInit();
+  }
+
+  finalizeFileLog();
+  //LED_OFF();
+  //Occurs when the RST pin state changes from HIGH to LOW
+  attachInterrupt(BOARD_SCSI_RST, onBusReset, FALLING);
+}
+
+/*
+ * Setup initialization logfile
+ */
+void initFileLog() {
+  LOG_FILE = SD.open(LOG_FILENAME, O_WRONLY | O_CREAT | O_TRUNC);
+  LOG_FILE.println("BlackSASI F411 <-> SD ");
+  LOG_FILE.print("VERSION: ");
+  LOG_FILE.println(VERSION);
+  LOG_FILE.print("DEBUG:");
+  LOG_FILE.print(DEBUG);
+  LOG_FILE.print(" SCSI_SELECT:");
+  LOG_FILE.print(SCSI_SELECT);
+  LOG_FILE.print(" SDFAT_FILE_TYPE:");
+  LOG_FILE.println(SDFAT_FILE_TYPE);
+  LOG_FILE.print("SdFat version: ");
+  LOG_FILE.println(SD_FAT_VERSION_STR);
+  LOG_FILE.print("SdFat Max FileName Length: ");
+  LOG_FILE.println(MAX_FILE_PATH);
+  LOG_FILE.println("Initialized SD Card - lets go!");
+  LOG_FILE.sync();
+}
+
+/*
+ * Finalize initialization logfile
+ */
+void finalizeFileLog() {
+  // View support drive map
+  LOG_FILE.print("ID");
+  for(int lun=0;lun<NUM_SCSILUN;lun++)
+  {
+    LOG_FILE.print(":LUN");
+    LOG_FILE.print(lun);
+  }
+  LOG_FILE.println(":");
+  //
+  for(int id=0;id<NUM_SCSIID;id++)
+  {
+    LOG_FILE.print(" ");
+    LOG_FILE.print(id);
+    for(int lun=0;lun<NUM_SCSILUN;lun++)
+    {
+      HDDIMG *h = &img[id][lun];
+      if( (lun<NUM_SCSILUN) && (h->m_file))
+      {
+        LOG_FILE.print((h->m_blocksize<1000) ? ": " : ":");
+        LOG_FILE.print(h->m_blocksize);
+      }
+      else      
+        LOG_FILE.print(":----");
+    }
+    LOG_FILE.println(":");
+  }
+  LOG_FILE.println("Finished initialization of SCSI Devices - Entering main loop.");
+  LOG_FILE.sync();
+  LOG_FILE.close();
+}
+
+/*
+ * Initialization failed, blink 3x fast
+ */
+void onFalseInit(void)
+{
+  LOG_FILE.sync();
+  while(true) {
+    for(int i = 0; i < 3; i++) {
+      LED3_ON();
+      delay(250);
+      LED3_OFF();
+      delay(250);
+    }
+    delay(3000);
+  }
+}
+
+/*
+ * No SC Card found, blink 5x fast
+ */
+void noSDCardFound(void)
+{
+  while(!SD.begin(SdSpiConfig(SS, DEDICATED_SPI))) {
+    for(int i = 0; i < 5; i++) {
+      LED3_ON();
+      delay(500);
+      LED3_OFF();
+      delay(500);
+    }
+    delay(1000);
+  }
+}
+void sdCardInsert(void){
+  if (digitalRead(BOARD_SDCARD_INSERT)){
+    LED1_OFF();
+  }else{
+    LED1_ON();
+  }
+}
+void switchImage(void){
+
+    uint16_t oldimageSelect = imageSelect;
+    imageSelect = digitalRead(BOARD_SWITCH1_PIN) | 
+                  digitalRead(BOARD_SWITCH2_PIN) << 1 |  
+                  digitalRead(BOARD_SWITCH3_PIN) << 2 |  
+                  digitalRead(BOARD_SWITCH4_PIN) << 3;
+    if ( oldimageSelect!=imageSelect){
+    Serial.print("Image: ");
+    Serial.println(15-imageSelect);
+    Serial.flush();
+    }
+
+
+}
+/*
+ * Bus reset interrupt.
+ */
+void onBusReset(void)
+{
+#if SCSI_SELECT == 1
+  // SASI I / F for X1 turbo has RST pulse write cycle +2 clock ==
+  // I can't filter because it only activates about 1.25us
+  {{
+#else
+  if(isHigh(digitalRead(BOARD_SCSI_RST))) {
+    delayMicroseconds(20);
+    if(isHigh(digitalRead(BOARD_SCSI_RST))) {
+#endif  
+  // BUS FREE is done in the main process
+//      gpio_mode(MSG, GPIO_OUTPUT_OD);
+//      gpio_mode(CD,  GPIO_OUTPUT_OD);
+//      gpio_mode(REQ, GPIO_OUTPUT_OD);
+//      gpio_mode(IO,  GPIO_OUTPUT_OD);
+      // Should I enter DB and DBP once?
+      SCSI_DB_INPUT()
+
+      LOGN("BusReset!");
+      m_isBusReset = true;
+    }
+  }
+}
+
+/*
+ * Read by handshake.
+ */
+inline byte readHandshake(void)
+{
+  SCSI_OUT(vREQ,active)
+  //SCSI_DB_INPUT()
+  while( ! SCSI_IN(vACK)) { if(m_isBusReset) return 0; }
+  byte r = readIO();
+  SCSI_OUT(vREQ,inactive)
+  while( SCSI_IN(vACK)) { if(m_isBusReset) return 0; }
+  return r;  
+}
+
+/*
+ * Write with a handshake.
+ */
+inline void writeHandshake(byte d)
+{
+  GPIOB->regs->BSRR = db_bsrr[d]; // setup DB,DBP (160ns)
+  SCSI_DB_OUTPUT() // (180ns)
+  // ACK.Fall to DB output delay 100ns(MAX)  (DTC-510B)
+  SCSI_OUT(vREQ,inactive) // setup wait (30ns)
+  SCSI_OUT(vREQ,inactive) // setup wait (30ns)
+  SCSI_OUT(vREQ,inactive) // setup wait (30ns)
+  SCSI_OUT(vREQ,active)   // (30ns)
+  //while(!SCSI_IN(vACK)) { if(m_isBusReset){ SCSI_DB_INPUT() return; }}
+  while(!m_isBusReset && !SCSI_IN(vACK));
+  
+  // ACK.Fall to REQ.Raise delay 500ns(typ.) (DTC-510B)
+  uint32_t bsrrCall = ((db_bsrr[0xff] & 0xFFBFFFFF) | 0x00000040);
+  GPIOB->regs->BSRR = bsrrCall;  // DB=0xFF , SCSI_OUT(vREQ,inactive)
+  
+  // REQ.Raise to DB hold time 0ns
+  SCSI_DB_INPUT() // (150ns)
+  while( SCSI_IN(vACK)) { if(m_isBusReset) return; }
+}
+
+/*
+ * Data in phase.
+ *  Send len bytes of data array p.
+ */
+void writeDataPhase(int len, const byte* p)
+{
+  LOGN("DATAIN PHASE");
+  SCSI_OUT(vMSG,inactive) //  gpio_write(MSG, low);
+  SCSI_OUT(vCD ,inactive) //  gpio_write(CD, low);
+  SCSI_OUT(vIO ,  active) //  gpio_write(IO, high);
+  for (int i = 0; i < len; i++) {
+    if(m_isBusReset) {
+      return;
+    }
+    writeHandshake(p[i]);
+  }
+}
+
+/* 
+ * Data in phase.
+ *  Send len block while reading from SD card.
+ */
+void writeDataPhaseSD(uint32_t adds, uint32_t len)
+{
+  LOGN("DATAIN PHASE(SD)");
+  uint32_t pos = adds * m_img->m_blocksize;
+  m_img->m_file.seek(pos);
+
+  SCSI_OUT(vMSG,inactive) //  gpio_write(MSG, low);
+  SCSI_OUT(vCD ,inactive) //  gpio_write(CD, low);
+  SCSI_OUT(vIO ,  active) //  gpio_write(IO, high);
+
+  int readStatus;
+
+  for(uint32_t i = 0; i < len; i++) {
+      // Asynchronous reads will make it faster ...
+    readStatus = m_img->m_file.read(m_buf, m_img->m_blocksize);
+    LOG("RS:");
+    LOGDECN(readStatus);
+
+#if READ_SPEED_OPTIMIZE
+
+//#define REQ_ON() SCSI_OUT(vREQ,active)
+#define REQ_ON() (*db_dst = BITMASK(vREQ) << 16)
+#define FETCH_SRC()   (src_byte = *srcptr++)
+#define FETCH_BSRR_DB() (bsrr_val = bsrr_tbl[src_byte])
+#define REQ_OFF_DB_SET(BSRR_VAL) *db_dst = BSRR_VAL  // This sets output data port(+parity) to proper values
+#define WAIT_ACK_ACTIVE()   while(!m_isBusReset && !SCSI_IN(vACK))
+#define WAIT_ACK_INACTIVE() do{ if(m_isBusReset) return; }while(SCSI_IN(vACK)) 
+
+    SCSI_DB_OUTPUT()
+    register byte *srcptr= m_buf;                 // Source buffer
+    register byte *endptr= m_buf +  m_img->m_blocksize; // End pointer
+
+    /*register*/ byte src_byte;                       // Send data bytes
+    register const uint32_t *bsrr_tbl = db_bsrr;  // Table to convert to BSRR
+    register uint32_t bsrr_val;                   // BSRR value to output (DB, DBP, REQ = ACTIVE)
+    register volatile uint32 *db_dst = &(GPIOB->regs->BSRR); // DB&DBP Output port
+
+    // prefetch & 1st out
+    FETCH_SRC();
+    FETCH_BSRR_DB();
+    REQ_OFF_DB_SET(bsrr_val);
+    // DB.set to REQ.F setup 100ns max (DTC-510B)
+    // Maybe there should be some weight here
+    // WAIT_ACK_INACTIVE();
+    do{
+      // 0
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      // ACK.F  to REQ.R       500ns typ. (DTC-510B)
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 1
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 2
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 3
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 4
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 5
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 6
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+      // 7
+      REQ_ON();
+      FETCH_SRC();
+      FETCH_BSRR_DB();
+      WAIT_ACK_ACTIVE();
+      REQ_OFF_DB_SET(bsrr_val);
+      WAIT_ACK_INACTIVE();
+    }while(srcptr < endptr);
+    SCSI_DB_INPUT()
+#else
+    for(int j = 0; j < m_img->m_blocksize; j++) {
+      if(m_isBusReset) {
+        return;
+      }
+      writeHandshake(m_buf[j]);
+    }
+#endif
+  }
+}
+
+/*
+ * Data out phase.
+ *  len block read
+ */
+void readDataPhase(int len, byte* p)
+{
+  LOGN("DATAOUT PHASE");
+  SCSI_OUT(vMSG,inactive) //  gpio_write(MSG, low);
+  SCSI_OUT(vCD ,inactive) //  gpio_write(CD, low);
+  SCSI_OUT(vIO ,inactive) //  gpio_write(IO, low);
+  for(uint32_t i = 0; i < len; i++)
+    p[i] = readHandshake();
+}
+
+/*
+ * Data out phase.
+ *  Write to SD card while reading len block.
+ */
+void readDataPhaseSD(uint32_t adds, uint32_t len)
+{
+  LOGN("DATAOUT PHASE(SD)");
+  uint32_t pos = adds * m_img->m_blocksize;
+  m_img->m_file.seek(pos);
+  SCSI_OUT(vMSG,inactive) //  gpio_write(MSG, low);
+  SCSI_OUT(vCD ,inactive) //  gpio_write(CD, low);
+  SCSI_OUT(vIO ,inactive) //  gpio_write(IO, low);
+  for(uint32_t i = 0; i < len; i++) {
+#if WRITE_SPEED_OPTIMIZE
+  register byte *dstptr= m_buf;
+	register byte *endptr= m_buf + m_img->m_blocksize;
+
+    for(dstptr=m_buf;dstptr<endptr;dstptr+=8) {
+      dstptr[0] = readHandshake();
+      dstptr[1] = readHandshake();
+      dstptr[2] = readHandshake();
+      dstptr[3] = readHandshake();
+      dstptr[4] = readHandshake();
+      dstptr[5] = readHandshake();
+      dstptr[6] = readHandshake();
+      dstptr[7] = readHandshake();
+      if(m_isBusReset) {
+        return;
+      }
+    }
+#else
+    for(int j = 0; j <  m_img->m_blocksize; j++) {
+      if(m_isBusReset) {
+        return;
+      }
+      m_buf[j] = readHandshake();
+    }
+#endif
+    m_img->m_file.write(m_buf, m_img->m_blocksize);
+  }
+  m_img->m_file.flush();
+}
+
+/*
+ * INQUIRY command processing.
+ */
+#if SCSI_SELECT == 2
+byte onInquiryCommand(byte len)
+{
+  byte buf[36] = {
+    0x00, //Device type
+    0x00, //RMB = 0
+    0x01, //ISO,ECMA,ANSI version
+    0x01, //Response data format
+    35 - 4, //Additional data length
+    0, 0, //Reserve
+    0x00, //Support function
+    'N', 'E', 'C', 'I', 'T', 'S', 'U', ' ',
+    'A', 'r', 'd', 'S', 'C', 'S', 'i', 'n', 'o', ' ', ' ',' ', ' ', ' ', ' ', ' ',
+    '0', '0', '1', '0',
+  };
+  writeDataPhase(len < 36 ? len : 36, buf);
+  return 0x00;
+}
+#else
+byte onInquiryCommand(byte len)
+{
+  writeDataPhase(len < 36 ? len : 36, SCSI_INFO_BUF);
+  return 0x00;
+}
+#endif
+
+/*
+ * REQUEST SENSE command processing.
+ */
+void onRequestSenseCommand(byte len)
+{
+  byte buf[18] = {
+    0x70,   //CheckCondition
+    0,      //Segment number
+    m_senseKey,   //Sense key
+    0, 0, 0, 0,  //information
+    10,   //Additional data length
+    0, 0, 0, 0, // command specific information bytes
+    (byte)(m_addition_sense >> 8),
+    (byte)m_addition_sense,
+    0, 0, 0, 0,
+  };
+  m_senseKey = 0;
+  m_addition_sense = 0;
+  writeDataPhase(len < 18 ? len : 18, buf);  
+}
+
+/*
+ * READ CAPACITY command processing.
+ */
+byte onReadCapacityCommand(byte pmi)
+{
+  if(!m_img) return 0x02; // Image file absent
+  
+  uint32_t bl = m_img->m_blocksize;
+  uint32_t bc = m_img->m_fileSize / bl - 1; // Points to last LBA
+  uint8_t buf[8] = {
+    bc >> 24, bc >> 16, bc >> 8, bc,
+    bl >> 24, bl >> 16, bl >> 8, bl    
+  };
+  writeDataPhase(8, buf);
+  return 0x00;
+}
+
+/*
+ * READ6 / 10 Command processing.
+ */
+byte onReadCommand(uint32_t adds, uint32_t len)
+{
+  LOG("-R ");
+  LOGHEX(adds);
+  LOG(" ");
+  LOGHEXN(len);
+
+  if(!m_img) return 0x02; // Image file absent
+  
+  //LED_ON();
+  writeDataPhaseSD(adds, len);
+  //LED_OFF();
+  return 0x00; //sts
+}
+
+/*
+ * WRITE6 / 10 Command processing.
+ */
+byte onWriteCommand(uint32_t adds, uint32_t len)
+{
+  LOGN("-W");
+  LOGHEXN(adds);
+  LOG(" ");
+  LOGHEXN(len);
+  
+  if(!m_img) return 0x02; // Image file absent
+  
+  //LED_ON();
+  readDataPhaseSD(adds, len);
+  //LED_OFF();
+  return 0; //sts
+}
+
+/*
+ * MODE SENSE command processing.
+ */
+#if SCSI_SELECT == 2
+byte onModeSenseCommand(byte scsi_cmd, byte dbd, int cmd2, uint32_t len)
+{
+  if(!m_img) return 0x02; // Image file absent
+
+  int pageCode = cmd2 & 0x3F;
+
+  // Assuming sector size 512, number of sectors 25, number of heads 8 as default settings
+  int size = m_img->m_fileSize;
+  int cylinders = (int)(size >> 9);
+  cylinders >>= 3;
+  cylinders /= 25;
+  int sectorsize = 512;
+  int sectors = 25;
+  int heads = 8;
+  // Sector size
+ int disksize = 0;
+  for(disksize = 16; disksize > 0; --(disksize)) {
+    if ((1 << disksize) == sectorsize)
+      break;
+  }
+  // Number of blocks
+  uint32_t diskblocks = (uint32_t)(size >> disksize);
+  memset(m_buf, 0, sizeof(m_buf)); 
+  int a = 4;
+  if(dbd == 0) {
+    uint32_t bl = m_img->m_blocksize;
+    uint32_t bc = m_img->m_fileSize / bl;
+    byte c[8] = {
+      0,// Density code
+      bc >> 16, bc >> 8, bc,
+      0, //Reserve
+      bl >> 16, bl >> 8, bl
+    };
+    memcpy(&m_buf[4], c, 8);
+    a += 8;
+    m_buf[3] = 0x08;
+  }
+  switch(pageCode) {
+  case 0x3F:
+  {
+    m_buf[a + 0] = 0x01;
+    m_buf[a + 1] = 0x06;
+    a += 8;
+  }
+  case 0x03:  // drive parameters
+  {
+    m_buf[a + 0] = 0x80 | 0x03; // Page code
+    m_buf[a + 1] = 0x16; // Page length
+    m_buf[a + 2] = (byte)(heads >> 8);// number of sectors / track
+    m_buf[a + 3] = (byte)(heads);// number of sectors / track
+    m_buf[a + 10] = (byte)(sectors >> 8);// number of sectors / track
+    m_buf[a + 11] = (byte)(sectors);// number of sectors / track
+    int size = 1 << disksize;
+    m_buf[a + 12] = (byte)(size >> 8);// number of sectors / track
+    m_buf[a + 13] = (byte)(size);// number of sectors / track
+    a += 24;
+    if(pageCode != 0x3F) {
+      break;
+    }
+  }
+  case 0x04:  // drive parameters
+  {
+      LOGN("AddDrive");
+      m_buf[a + 0] = 0x04; // Page code
+      m_buf[a + 1] = 0x12; // Page length
+      m_buf[a + 2] = (cylinders >> 16);// Cylinder length
+      m_buf[a + 3] = (cylinders >> 8);
+      m_buf[a + 4] = cylinders;
+      m_buf[a + 5] = heads;   // Number of heads
+      a += 20;
+    if(pageCode != 0x3F) {
+      break;
+    }
+  }
+  default:
+    break;
+  }
+  m_buf[0] = a - 1;
+  writeDataPhase(len < a ? len : a, m_buf);
+  return 0x00;
+}
+#else
+byte onModeSenseCommand(byte scsi_cmd, byte dbd, int cmd2, uint32_t len)
+{
+  if(!m_img) return 0x02; // No image file
+
+  uint32_t bl =  m_img->m_blocksize;
+  uint32_t bc = m_img->m_fileSize / bl;
+
+  memset(m_buf, 0, sizeof(m_buf));
+  int pageCode = cmd2 & 0x3F;
+  int a = 4;
+  if(scsi_cmd == 0x5A) a = 8;
+
+  if(dbd == 0) {
+    byte c[8] = {
+      0,//Density code
+      bc >> 16, bc >> 8, bc,
+      0, //Reserve
+      bl >> 16, bl >> 8, bl    
+    };
+    memcpy(&m_buf[a], c, 8);
+    a += 8;
+  }
+  switch(pageCode) {
+  case 0x3F:
+  case 0x01: // Read/Write Error Recovery
+    m_buf[a + 0] = 0x01;
+    m_buf[a + 1] = 0x0A;
+    a += 0x0C;
+    if(pageCode != 0x3F) break;
+
+  case 0x02: // Disconnect-Reconnect page
+    m_buf[a + 0] = 0x02;
+    m_buf[a + 1] = 0x0A;
+    a += 0x0C;
+    if(pageCode != 0x3f) break;
+
+  case 0x03:  //Drive parameters
+    m_buf[a + 0] = 0x03; //Page code
+    m_buf[a + 1] = 0x16; // Page length
+    m_buf[a + 11] = 0x3F;//Number of sectors / track
+    m_buf[a + 12] = (byte)(m_img->m_blocksize >> 8);
+    m_buf[a + 13] = (byte)m_img->m_blocksize;
+    m_buf[a + 15] = 0x1; // Interleave
+    a += 0x18;
+    if(pageCode != 0x3F) break;
+
+  case 0x04:  //Drive parameters
+    {
+        unsigned cylinders = bc / (16 * 63);
+        m_buf[a + 0] = 0x04; //Page code
+        m_buf[a + 1] = 0x16; // Page length
+        m_buf[a + 2] = (byte)(cylinders >> 16); // Cylinders
+        m_buf[a + 3] = (byte)(cylinders >> 8);
+        m_buf[a + 4] = (byte)cylinders;
+        m_buf[a + 5] = 16;   //Number of heads
+        a += 0x18;
+        if(pageCode != 0x3F) break;
+    }
+    break; // Don't want 0x3F falling through to error condition
+
+  default:
+    m_senseKey = 5; // Illegal request
+    m_addition_sense = 0x2400; // Invalid field in CDB
+    return 0x02;
+    break;
+  }
+  if(scsi_cmd == 0x5A) // MODE SENSE 10
+  {
+    m_buf[1] = a - 2;
+    m_buf[7] = 0x08;
+  }
+  else
+  {
+    m_buf[0] = a - 1;
+    m_buf[3] = 0x08;
+  }
+  writeDataPhase(len < a ? len : a, m_buf);
+  return 0x00;
+}
+#endif
+    
+#if SCSI_SELECT == 1
+/*
+ * dtc510b_setDriveparameter
+ */
+#define PACKED  __attribute__((packed))
+typedef struct PACKED dtc500_cmd_c2_param_struct
+{
+  uint8_t StepPlusWidth;        // Default is 13.6usec (11)
+  uint8_t StepPeriod;         // Default is  3  msec.(60)
+  uint8_t StepMode;         // Default is  Bufferd (0)
+  uint8_t MaximumHeadAdress;      // Default is 4 heads (3)
+  uint8_t HighCylinderAddressByte;  // Default set to 0   (0)
+  uint8_t LowCylinderAddressByte;   // Default is 153 cylinders (152)
+  uint8_t ReduceWrietCurrent;     // Default is above Cylinder 128 (127)
+  uint8_t DriveType_SeekCompleteOption;// (0)
+  uint8_t Reserved8;          // (0)
+  uint8_t Reserved9;          // (0)
+} DTC510_CMD_C2_PARAM;
+
+static void logStrHex(const char *msg,uint32_t num)
+{
+    LOG(msg);
+    LOGHEXN(num);
+}
+
+static byte dtc510b_setDriveparameter(void)
+{
+  DTC510_CMD_C2_PARAM DriveParameter;
+  uint16_t maxCylinder;
+  uint16_t numLAD;
+  //uint32_t stepPulseUsec;
+  int StepPeriodMsec;
+
+  // receive paramter
+  writeDataPhase(sizeof(DriveParameter),(byte *)(&DriveParameter));
+ 
+  maxCylinder =
+    (((uint16_t)DriveParameter.HighCylinderAddressByte)<<8) |
+    (DriveParameter.LowCylinderAddressByte);
+  numLAD = maxCylinder * (DriveParameter.MaximumHeadAdress+1);
+  //stepPulseUsec  = calcStepPulseUsec(DriveParameter.StepPlusWidth);
+  StepPeriodMsec = DriveParameter.StepPeriod*50;
+  logStrHex (" StepPlusWidth      : ",DriveParameter.StepPlusWidth);
+  logStrHex (" StepPeriod         : ",DriveParameter.StepPeriod   );
+  logStrHex (" StepMode           : ",DriveParameter.StepMode     );
+  logStrHex (" MaximumHeadAdress  : ",DriveParameter.MaximumHeadAdress);
+  logStrHex (" CylinderAddress    : ",maxCylinder);
+  logStrHex (" ReduceWrietCurrent : ",DriveParameter.ReduceWrietCurrent);
+  logStrHex (" DriveType/SeekCompleteOption : ",DriveParameter.DriveType_SeekCompleteOption);
+  logStrHex (" Maximum LAD        : ",numLAD-1);
+  return  0; // error result
+}
+#endif
+
+/*
+ * MsgIn2.
+ */
+void MsgIn2(int msg)
+{
+  LOGN("MsgIn2");
+  SCSI_OUT(vMSG,  active) //  gpio_write(MSG, high);
+  SCSI_OUT(vCD ,  active) //  gpio_write(CD, high);
+  SCSI_OUT(vIO ,  active) //  gpio_write(IO, high);
+  writeHandshake(msg);
+}
+
+/*
+ * MsgOut2.
+ */
+void MsgOut2()
+{
+  LOGN("MsgOut2");
+  SCSI_OUT(vMSG,  active) //  gpio_write(MSG, high);
+  SCSI_OUT(vCD ,  active) //  gpio_write(CD, high);
+  SCSI_OUT(vIO ,inactive) //  gpio_write(IO, low);
+  m_msb[m_msc] = readHandshake();
+  m_msc++;
+  m_msc %= 256;
+}
+
+/*
+ * Main loop.
+ */
+void loop() 
+{
+  //int msg = 0;
+  m_msg = 0;
+
+  // Wait until RST = H, BSY = H, SEL = L
+  do {} while( SCSI_IN(vBSY) || !SCSI_IN(vSEL) || SCSI_IN(vRST));
+
+  // BSY+ SEL-
+  // If the ID to respond is not driven, wait for the next
+  byte scsiid = readIO() & scsi_id_mask;
+  if((scsiid) == 0) {
+    delayMicroseconds(1);
+    return;
+  }
+  LOGN("Selection");
+  m_isBusReset = false;
+  // Set BSY to-when selected
+  SCSI_BSY_ACTIVE();     // Turn only BSY output ON, ACTIVE
+
+  // Ask for a TARGET-ID to respond
+#if USE_DB2ID_TABLE
+  m_id = db2scsiid[scsiid];
+  //if(m_id==0xff) return;
+#else
+  for(m_id=7;m_id>=0;m_id--)
+    if(scsiid & (1<<m_id)) break;
+  //if(m_id<0) return;
+#endif
+
+  // Wait until SEL becomes inactive
+  while(isHigh(digitalRead(BOARD_SCSI_SEL)) && isLow(digitalRead(BOARD_SCSI_BSY))) {
+    if(m_isBusReset) {
+      goto BusFree;
+    }
+  }
+  SCSI_TARGET_ACTIVE()  // (BSY), REQ, MSG, CD, IO output turned on
+  //  
+  if(isHigh(digitalRead(BOARD_SCSI_ATN))) {
+    bool syncenable = false;
+    int syncperiod = 50;
+    int syncoffset = 0;
+    int loopWait = 0;
+    m_msc = 0;
+    memset(m_msb, 0x00, sizeof(m_msb));
+    while(isHigh(digitalRead(BOARD_SCSI_ATN)) && loopWait < 255) {
+      MsgOut2();
+      loopWait++;
+    }
+    for(int i = 0; i < m_msc; i++) {
+      // ABORT
+      if (m_msb[i] == 0x06) {
+        goto BusFree;
+      }
+      // BUS DEVICE RESET
+      if (m_msb[i] == 0x0C) {
+        syncoffset = 0;
+        goto BusFree;
+      }
+      // IDENTIFY
+      if (m_msb[i] >= 0x80) {
+      }
+      // Extended message
+      if (m_msb[i] == 0x01) {
+        // Check only when synchronous transfer is possible
+        if (!syncenable || m_msb[i + 2] != 0x01) {
+          MsgIn2(0x07);
+          break;
+        }
+        // Transfer period factor(50 x 4 = Limited to 200ns)
+        syncperiod = m_msb[i + 3];
+        if (syncperiod > 50) {
+          syncperiod = 50;
+        }
+        // REQ/ACK offset(Limited to 16)
+        syncoffset = m_msb[i + 4];
+        if (syncoffset > 16) {
+          syncoffset = 16;
+        }
+        // STDR response message generation
+        MsgIn2(0x01);
+        MsgIn2(0x03);
+        MsgIn2(0x01);
+        MsgIn2(syncperiod);
+        MsgIn2(syncoffset);
+        break;
+      }
+    }
+  }
+
+  SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
+  SCSI_OUT(vCD ,  active) // gpio_write(CD, high);
+  SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
+  
+  int len;
+  byte cmd[12];
+  cmd[0] = readHandshake(); if(m_isBusReset) goto BusFree;
+  LOG("CMD:");
+  LOGHEX(cmd[0]);
+  // Command length selection, reception
+  static const int cmd_class_len[8]={6,10,10,6,6,12,6,6};
+  len = cmd_class_len[cmd[0] >> 5];
+  cmd[1] = readHandshake(); LOG(":"); LOGHEX(cmd[1]); if(m_isBusReset) goto BusFree;
+  cmd[2] = readHandshake(); LOG(":"); LOGHEX(cmd[2]); if(m_isBusReset) goto BusFree;
+  cmd[3] = readHandshake(); LOG(":"); LOGHEX(cmd[3]); if(m_isBusReset) goto BusFree;
+  cmd[4] = readHandshake(); LOG(":"); LOGHEX(cmd[4]); if(m_isBusReset) goto BusFree;
+  cmd[5] = readHandshake(); LOG(":"); LOGHEX(cmd[5]); if(m_isBusReset) goto BusFree;
+  // Receive the remaining commands
+  for(int i = 6; i < len; i++ ) {
+    cmd[i] = readHandshake();
+    LOG(":");
+    LOGHEX(cmd[i]);
+    if(m_isBusReset) goto BusFree;
+  }
+  // LUN confirmation
+  m_sts = cmd[1]&0xe0;      // Preset LUN in status byte
+  m_lun = m_sts>>5;
+  // HDD Image selection
+  m_img = (HDDIMG *)0; // None
+  if( (m_lun <= NUM_SCSILUN) )
+  {
+    m_img = &(img[m_id][m_lun]); // There is an image
+    if(!(m_img->m_file.isOpen()))
+      m_img = (HDDIMG *)0;       // Image absent
+  }
+  // if(!m_img) m_sts |= 0x02;            // Missing image file for LUN
+  //LOGHEX(((uint32_t)m_img));
+  
+  LOG(":ID ");
+  LOG(m_id);
+  LOG(":LUN ");
+  LOG(m_lun);
+
+  LOGN("");
+  switch(cmd[0]) {
+  case 0x00:
+    LOGN("[Test Unit]");
+    break;
+  case 0x01:
+    LOGN("[Rezero Unit]");
+    break;
+  case 0x03:
+    LOGN("[RequestSense]");
+    onRequestSenseCommand(cmd[4]);
+    break;
+  case 0x04:
+    LOGN("[FormatUnit]");
+    break;
+  case 0x06:
+    LOGN("[FormatUnit]");
+    break;
+  case 0x07:
+    LOGN("[ReassignBlocks]");
+    break;
+  case 0x08:
+    LOGN("[Read6]");
+    m_sts |= onReadCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
+    break;
+  case 0x0A:
+    LOGN("[Write6]");
+    m_sts |= onWriteCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]);
+    break;
+  case 0x0B:
+    LOGN("[Seek6]");
+    break;
+  case 0x12:
+    LOGN("[Inquiry]");
+    m_sts |= onInquiryCommand(cmd[4]);
+    break;
+  case 0x1A:
+    LOGN("[ModeSense6]");
+    m_sts |= onModeSenseCommand(cmd[0], cmd[1]&0x80, cmd[2], cmd[4]);
+    break;
+  case 0x1B:
+    LOGN("[StartStopUnit]");
+    break;
+  case 0x1E:
+    LOGN("[PreAllowMed.Removal]");
+    break;
+  case 0x25:
+    LOGN("[ReadCapacity]");
+    m_sts |= onReadCapacityCommand(cmd[8]);
+    break;
+  case 0x28:
+    LOGN("[Read10]");
+    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]);
+    break;
+  case 0x2A:
+    LOGN("[Write10]");
+    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]);
+    break;
+  case 0x2B:
+    LOGN("[Seek10]");
+    break;
+  case 0x5A:
+    LOGN("[ModeSense10]");
+    m_sts |= onModeSenseCommand(cmd[0], cmd[1] & 0x80, cmd[2], ((uint32_t)cmd[7] << 8) | cmd[8]);
+    break;
+#if SCSI_SELECT == 1
+  case 0xc2:
+    LOGN("[DTC510B setDriveParameter]");
+    m_sts |= dtc510b_setDriveparameter();
+    break;
+#endif    
+  default:
+    LOGN("[*Unknown]");
+    m_sts |= 0x02;
+    m_senseKey = 5;  // Illegal request
+    m_addition_sense = 0x2000; // Invalid Command Operation Code
+    break;
+  }
+  if(m_isBusReset) {
+     goto BusFree;
+  }
+
+  LOGN("Sts");
+  SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
+  SCSI_OUT(vCD ,  active) // gpio_write(CD, high);
+  SCSI_OUT(vIO ,  active) // gpio_write(IO, high);
+  writeHandshake(m_sts);
+  if(m_isBusReset) {
+     goto BusFree;
+  }
+
+  LOGN("MsgIn");
+  SCSI_OUT(vMSG,  active) // gpio_write(MSG, high);
+  SCSI_OUT(vCD ,  active) // gpio_write(CD, high);
+  SCSI_OUT(vIO ,  active) // gpio_write(IO, high);
+  writeHandshake(m_msg);
+
+BusFree:
+  LOGN("BusFree");
+  m_isBusReset = false;
+  //SCSI_OUT(vREQ,inactive) // gpio_write(REQ, low);
+  //SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low);
+  //SCSI_OUT(vCD ,inactive) // gpio_write(CD, low);
+  //SCSI_OUT(vIO ,inactive) // gpio_write(IO, low);
+  //SCSI_OUT(vBSY,inactive)
+  SCSI_TARGET_INACTIVE() // Turn off BSY, REQ, MSG, CD, IO output
+}

+ 78 - 0
sw/variant/blacksasi_f411m/blacksasi_f411m.cpp

@@ -0,0 +1,78 @@
+/******************************************************************************
+ * The MIT License
+ *
+ * Copyright (c) 2011 LeafLabs, LLC.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *****************************************************************************/
+
+/**
+ * @file   blacksasi_f411m.cpp
+ * @author stevestrong
+ * @brief  blacksasi_f411m board file.
+ */
+
+#include "blacksasi_f411m.h"
+
+#include <libmaple/gpio.h>
+#include <libmaple/rcc.h>
+
+#include <libmaple/libmaple_types.h>
+
+
+//static void initSRAMChip(void);
+/*****************************************************************************/
+//  Alternate functions, see DocID022152 Rev 8, Table 9. 
+/*****************************************************************************/
+void boardInit(void) {
+
+	return;
+}
+
+/* to be defined
+const uint8 boardPWMPins[BOARD_NR_PWM_PINS] __FLASH__ = {
+    0, 1, 2, 3, 15, 16, 17, 19, 20, 21, 38, 39, 49, 41, 60, 61, 62, 63, 73, 75, 77, 78
+};
+*/
+extern const uint8 boardADCPins[BOARD_NR_ADC_PINS] = {
+    PA0, PA1, PA2, PA3, PA4, PA5, PA6, PA7, PB0, PB1, PC0, PC1, PC2, PC3, PC4, PC5
+};
+
+const uint8 boardUsedPins[BOARD_NR_USED_PINS] = {
+    BOARD_LED_PIN, BOARD_LED2_PIN, BOARD_LED2_PIN,BOARD_SWITCH1_PIN, BOARD_SWITCH2_PIN, BOARD_SWITCH3_PIN,
+	BOARD_SWITCH4_PIN, BOARD_JTMS_SWDIO_PIN, BOARD_JTCK_SWCLK_PIN,PB0,PB1,
+	USB_DM_PIN, USB_DP_PIN
+};
+//	BOARD_SDIO_D0, BOARD_SDIO_D1, BOARD_SDIO_D2, BOARD_SDIO_D3, BOARD_SDIO_CLK, BOARD_SDIO_CMD,
+
+/*
+static void initSRAMChip(void) {
+    fsmc_nor_psram_reg_map *regs = FSMC_NOR_PSRAM1_BASE;
+
+    fsmc_sram_init_gpios();
+    rcc_clk_enable(RCC_FSMC);
+
+    regs->BCR = (FSMC_BCR_WREN | FSMC_BCR_MWID_16BITS | FSMC_BCR_MTYP_SRAM |
+                 FSMC_BCR_MBKEN);
+    fsmc_nor_psram_set_addset(regs, 0);
+    fsmc_nor_psram_set_datast(regs, 3);
+}
+*/

+ 157 - 0
sw/variant/blacksasi_f411m/blacksasi_f411m.h

@@ -0,0 +1,157 @@
+/******************************************************************************
+ * The MIT License
+ *
+ * Copyright (c) 2011 LeafLabs, LLC.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *****************************************************************************/
+
+/**
+ * @file   blacksasi_f411m.h
+ * @author Per Mårtensson
+ * @brief  Private include file
+ */
+
+#ifndef _BOARD_BLACKSASI_F411M_H_
+#define _BOARD_BLACKSASI_F411M_H_
+
+#define Port2Pin(port, bit) ((port-'A')*16+bit)
+
+#define CLOCK_SPEED_MHZ  96
+
+/*****************************************************************************/
+// Board pin definitions
+#define BOARD_USB_DM_PIN		PA11
+#define BOARD_USB_DP_PIN		PA12
+
+#define BOARD_LED_PIN           PA4
+#define BOARD_LED1_PIN           PA4
+#define BOARD_LED2_PIN          PA5
+#define BOARD_LED3_PIN          PA6
+#define BOARD_EXT_LED           PA0
+
+#define BOARD_SWITCH1_PIN       PC4
+#define BOARD_SWITCH2_PIN       PC5
+#define BOARD_SWITCH3_PIN       PC10
+#define BOARD_SWITCH4_PIN       PC11
+#define BOARD_SDCARD_INSERT     PB0
+
+#define BOARD_NR_USARTS         6
+#define BOARD_USART1_TX_PIN     PA9
+#define BOARD_USART1_RX_PIN     PA10
+#define BOARD_USART2_TX_PIN     PA2
+#define BOARD_USART2_RX_PIN     PA3
+#define BOARD_USART3_TX_PIN     PB10
+#define BOARD_USART3_RX_PIN     PB11
+#define BOARD_UART4_TX_PIN      PA0
+#define BOARD_UART4_RX_PIN      PA1
+#define BOARD_UART5_TX_PIN      PC12
+#define BOARD_UART5_RX_PIN      PD2
+#define BOARD_USART6_TX_PIN     PC6
+#define BOARD_USART6_RX_PIN     PC7
+
+#define BOARD_NR_I2C            0
+
+#define BOARD_NR_SPI            3
+#define BOARD_SPI1_NSS_PIN      PA4
+#define BOARD_SPI1_SCK_PIN      PA5
+#define BOARD_SPI1_MISO_PIN     PA6
+#define BOARD_SPI1_MOSI_PIN     PA7
+#define BOARD_SPI1A_NSS_PIN     PB1
+#define BOARD_SPI1A_SCK_PIN     PB3
+#define BOARD_SPI1A_MISO_PIN    PB4
+#define BOARD_SPI1A_MOSI_PIN    PB5
+
+
+#define BOARD_SPI2_NSS_PIN      PB12
+#define BOARD_SPI2_SCK_PIN      PB13
+#define BOARD_SPI2_MISO_PIN     PB14
+#define BOARD_SPI2_MOSI_PIN     PB15
+#define BOARD_SPI2A_NSS_PIN     PB9
+#define BOARD_SPI2A_SCK_PIN     PB10
+#define BOARD_SPI2A_MISO_PIN    PC2
+#define BOARD_SPI2A_MOSI_PIN    PC3
+#define BOARD_SPI3_NSS_PIN      PA15
+#define BOARD_SPI3_SCK_PIN      PD12
+#define BOARD_SPI3_MISO_PIN     PD12
+#define BOARD_SPI3_MOSI_PIN     PD12
+
+#define BOARD_SDIO_D0           PB4
+#define BOARD_SDIO_D1           PB10
+#define BOARD_SDIO_D2           PB13
+#define BOARD_SDIO_D3           PB1
+#define BOARD_SDIO_CLK          PB3
+#define BOARD_SDIO_CMD          PB5
+
+#define BOARD_SCSI_DBP          PE0
+#define BOARD_SCSI_MSG          PE2
+#define BOARD_SCSI_RST          PA15
+#define BOARD_SCSI_SEL          PE3
+#define BOARD_SCSI_CD           PE4
+#define BOARD_SCSI_REQ          PE5
+#define BOARD_SCSI_IO           PE6
+#define BOARD_SCSI_DAT0         PD0
+#define BOARD_SCSI_DAT1         PD1
+#define BOARD_SCSI_DAT2         PD2
+#define BOARD_SCSI_DAT3         PD3
+#define BOARD_SCSI_DAT4         PD4
+#define BOARD_SCSI_DAT5         PD5
+#define BOARD_SCSI_DAT6         PD6
+#define BOARD_SCSI_DAT7         PD7
+#define BOARD_SCSI_BSY          PB6
+#define BOARD_SCSI_ACK          PB7
+#define BOARD_TRANS_OE          PB12
+#define BOARD_SCSI_ATN          PB14
+#define BOARD_SCSI_DTD          PC0
+#define BOARD_SCSI_IND          PC1
+#define BOARD_SCSI_TAD          PC2
+#define BOARD_SCSI_TERM_HIGH    PB8
+#define BOARD_SCSI_TERM_LOW     PB9
+#define BOARD_SCSI_TERM_POWER   PC8
+
+#define BOARD_NR_PWM_PINS       22
+#define BOARD_NR_ADC_PINS       16
+#define BOARD_NR_USED_PINS      22
+#define BOARD_JTMS_SWDIO_PIN    PA13 //Port2Pin('A',13)
+#define BOARD_JTCK_SWCLK_PIN    PA14 //Port2Pin('A',14)
+
+
+/*****************************************************************************/
+// Pins reserved for the on-board hardware
+#define USB_DM_PIN		BOARD_USB_DM_PIN // PA11
+#define USB_DP_PIN		BOARD_USB_DP_PIN // PA12
+/*
+
+
+
+/*****************************************************************************/
+
+enum {
+PA0,PA1,PA2,PA3,PA4,PA5,PA6,PA7,PA8,PA9,PA10,PA11,PA12,PA13,PA14,PA15,
+PB0,PB1,PB2,PB3,PB4,PB5,PB6,PB7,PB8,PB9,PB10,PB11,PB12,PB13,PB14,PB15,
+PC0,PC1,PC2,PC3,PC4,PC5,PC6,PC7,PC8,PC9,PC10,PC11,PC12,PC13,PC14,PC15,
+PD0,PD1,PD2,PD3,PD4,PD5,PD6,PD7,PD8,PD9,PD10,PD11,PD12,PD13,PD14,PD15,
+PE0,PE1,PE2,PE3,PE4,PE5,PE6,PE7,PE8,PE9,PE10,PE11,PE12,PE13,PE14,PE15,
+
+BOARD_NR_GPIO_PINS
+};
+
+#endif

+ 219 - 0
sw/variant/blacksasi_f411m/ld/common.inc

@@ -0,0 +1,219 @@
+/*
+ * Linker script for libmaple.
+ *
+ * Original author "lanchon" from ST forums, with modifications by LeafLabs.
+ */
+
+OUTPUT_FORMAT ("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
+
+/*
+ * Configure other libraries we want in the link.
+ *
+ * libgcc, libc, and libm are common across supported toolchains.
+ * However, some toolchains require additional archives which aren't
+ * present everywhere (e.g. ARM's gcc-arm-embedded releases).
+ *
+ * To hack around this, we let the build system specify additional
+ * archives by putting the right extra_libs.inc (in a directory under
+ * toolchains/) in our search path.
+ */
+GROUP(libgcc.a libc.a libm.a)
+INCLUDE extra_libs.inc
+
+/*
+ * These force the linker to search for vector table symbols.
+ *
+ * These symbols vary by STM32 family (and also within families).
+ * It's up to the build system to configure the link's search path
+ * properly for the target MCU.
+ */
+INCLUDE vector_symbols.inc
+
+/* STM32 vector table. */
+EXTERN(__stm32_vector_table)
+
+/* C runtime initialization function. */
+EXTERN(start_c)
+
+/* main entry point */
+EXTERN(main)
+
+/* Initial stack pointer value. Relocated to RAM */
+EXTERN(__msp_init)
+PROVIDE(__msp_init = ORIGIN(ram) + LENGTH(ram));
+
+/* Reset vector and chip reset entry point */
+EXTERN(__start__)
+ENTRY(__start__)
+PROVIDE(__exc_reset = __start__);
+
+/* Heap boundaries, for libmaple */
+EXTERN(_lm_heap_start);
+EXTERN(_lm_heap_end);
+
+SECTIONS
+{
+    .text :
+      {
+        __text_start__ = .;
+        /*
+         * STM32 vector table.  Leave this here.  Yes, really.
+         */
+        *(.stm32.interrupt_vector)
+
+        /*
+         * Program code and vague linking
+         */
+        *(.text .text.* .gnu.linkonce.t.*)
+        *(.plt)
+        *(.gnu.warning)
+        *(.glue_7t) *(.glue_7) *(.vfp11_veneer)
+
+        *(.ARM.extab* .gnu.linkonce.armextab.*)
+        *(.gcc_except_table)
+        *(.eh_frame_hdr)
+        *(.eh_frame)
+
+        . = ALIGN(4);
+        KEEP(*(.init))
+
+        . = ALIGN(4);
+        __preinit_array_start = .;
+        KEEP (*(.preinit_array))
+        __preinit_array_end = .;
+
+        . = ALIGN(4);
+        __init_array_start = .;
+        KEEP (*(SORT(.init_array.*)))
+        KEEP (*(.init_array))
+        __init_array_end = .;
+
+        . = ALIGN(0x4);
+        KEEP (*crtbegin.o(.ctors))
+        KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))
+        KEEP (*(SORT(.ctors.*)))
+        KEEP (*crtend.o(.ctors))
+
+        . = ALIGN(4);
+        KEEP(*(.fini))
+
+        . = ALIGN(4);
+        __fini_array_start = .;
+        KEEP (*(.fini_array))
+        KEEP (*(SORT(.fini_array.*)))
+        __fini_array_end = .;
+
+        KEEP (*crtbegin.o(.dtors))
+        KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))
+        KEEP (*(SORT(.dtors.*)))
+        KEEP (*crtend.o(.dtors))
+      } > REGION_TEXT
+
+    /*
+     * End of text
+     */
+    .text.align :
+      {
+        . = ALIGN(8);
+        __text_end__ = .;
+      } > REGION_TEXT
+
+    /*
+     * .ARM.exidx exception unwinding; mandated by ARM's C++ ABI
+     */
+    __exidx_start = .;
+    .ARM.exidx :
+      {
+        *(.ARM.exidx* .gnu.linkonce.armexidx.*)
+      } > REGION_RODATA
+    __exidx_end = .;
+
+    /*
+     * Read-only data
+     */
+    .rodata :
+      {
+        *(.rodata .rodata.* .gnu.linkonce.r.*)
+        /* .USER_FLASH: We allow users to allocate into Flash here */
+        *(.USER_FLASH)
+        /* ROM image configuration; for C startup */
+        . = ALIGN(4);
+        _lm_rom_img_cfgp = .;
+        LONG(LOADADDR(.data));
+        /*
+         * Heap: Linker scripts may choose a custom heap by overriding
+         * _lm_heap_start and _lm_heap_end. Otherwise, the heap is in
+         * internal SRAM, beginning after .bss, and growing towards
+         * the stack.
+         *
+         * I'm shoving these here naively; there's probably a cleaner way
+         * to go about this. [mbolivar]
+         */
+        _lm_heap_start = DEFINED(_lm_heap_start) ? _lm_heap_start : __data_end__;
+        _lm_heap_end   = DEFINED(_lm_heap_end) ? _lm_heap_end : __msp_init;
+      } > REGION_RODATA
+
+    /*
+     * .data
+     */
+    .data :
+      {
+        . = ALIGN(8);
+        __data_start__ = .;
+
+        *(.got.plt) *(.got)
+        *(.data .data.* .gnu.linkonce.d.*)
+
+        . = ALIGN(8);
+        __data_end__ = .;
+      } > REGION_DATA AT> REGION_RODATA
+
+    /*
+     * .bss
+     */
+    .bss :
+      {
+        . = ALIGN(8);
+        __bss_start__ = .;
+        *(.bss .bss.* .gnu.linkonce.b.*)
+        *(COMMON)
+        . = ALIGN (8);
+        __bss_end__ = .;
+        _end = __bss_end__;
+      } > REGION_BSS
+
+    /*
+     * Debugging sections
+     */
+    .stab 0 (NOLOAD) : { *(.stab) }
+    .stabstr 0 (NOLOAD) : { *(.stabstr) }
+    /* DWARF debug sections.
+     * Symbols in the DWARF debugging sections are relative to the beginning
+     * of the section so we begin them at 0.  */
+    /* DWARF 1 */
+    .debug          0 : { *(.debug) }
+    .line           0 : { *(.line) }
+    /* GNU DWARF 1 extensions */
+    .debug_srcinfo  0 : { *(.debug_srcinfo) }
+    .debug_sfnames  0 : { *(.debug_sfnames) }
+    /* DWARF 1.1 and DWARF 2 */
+    .debug_aranges  0 : { *(.debug_aranges) }
+    .debug_pubnames 0 : { *(.debug_pubnames) }
+    /* DWARF 2 */
+    .debug_info     0 : { *(.debug_info .gnu.linkonce.wi.*) }
+    .debug_abbrev   0 : { *(.debug_abbrev) }
+    .debug_line     0 : { *(.debug_line) }
+    .debug_frame    0 : { *(.debug_frame) }
+    .debug_str      0 : { *(.debug_str) }
+    .debug_loc      0 : { *(.debug_loc) }
+    .debug_macinfo  0 : { *(.debug_macinfo) }
+    /* SGI/MIPS DWARF 2 extensions */
+    .debug_weaknames 0 : { *(.debug_weaknames) }
+    .debug_funcnames 0 : { *(.debug_funcnames) }
+    .debug_typenames 0 : { *(.debug_typenames) }
+    .debug_varnames  0 : { *(.debug_varnames) }
+
+    .note.gnu.arm.ident 0 : { KEEP (*(.note.gnu.arm.ident)) }
+    .ARM.attributes 0 : { KEEP (*(.ARM.attributes)) }
+    /DISCARD/ : { *(.note.GNU-stack) }
+}

+ 7 - 0
sw/variant/blacksasi_f411m/ld/extra_libs.inc

@@ -0,0 +1,7 @@
+/*
+ * Extra archives needed by ARM's GCC ARM Embedded arm-none-eabi-
+ * releases (https://launchpad.net/gcc-arm-embedded/).
+ */
+
+/* This is for the provided newlib. */
+GROUP(libnosys.a)

+ 19 - 0
sw/variant/blacksasi_f411m/ld/jtag.ld

@@ -0,0 +1,19 @@
+/*
+ * STM32F401 linker script for JTAG (bare metal, no bootloader) builds.
+ */
+
+MEMORY
+{
+  ram (rwx)  : ORIGIN = 0x20000000, LENGTH = 128K
+  rom (rx)   : ORIGIN = 0x08000000, LENGTH = 512K
+}
+
+/* GROUP(libcs3_stm32_high_density.a) */
+
+REGION_ALIAS("REGION_TEXT", rom);
+REGION_ALIAS("REGION_DATA", ram);
+REGION_ALIAS("REGION_BSS", ram);
+REGION_ALIAS("REGION_RODATA", rom);
+
+_FLASH_BUILD = 1;
+INCLUDE common.inc

+ 99 - 0
sw/variant/blacksasi_f411m/ld/vector_symbols.inc

@@ -0,0 +1,99 @@
+EXTERN(__msp_init)
+EXTERN(__exc_reset)
+EXTERN(__exc_nmi)
+EXTERN(__exc_hardfault)
+EXTERN(__exc_memmanage)
+EXTERN(__exc_busfault)
+EXTERN(__exc_usagefault)
+EXTERN(__stm32reservedexception7)
+EXTERN(__stm32reservedexception8)
+EXTERN(__stm32reservedexception9)
+EXTERN(__stm32reservedexception10)
+EXTERN(__exc_svc)
+EXTERN(__exc_debug_monitor)
+EXTERN(__stm32reservedexception13)
+EXTERN(__exc_pendsv)
+EXTERN(__exc_systick)
+
+EXTERN(__irq_wwdg)
+EXTERN(__irq_pvd)
+EXTERN(__irq_tamper)
+EXTERN(__irq_rtc)
+EXTERN(__irq_flash)
+EXTERN(__irq_rcc)
+EXTERN(__irq_exti0)
+EXTERN(__irq_exti1)
+EXTERN(__irq_exti2)
+EXTERN(__irq_exti3)
+EXTERN(__irq_exti4)
+EXTERN(__irq_dma1_stream0)
+EXTERN(__irq_dma1_stream1)
+EXTERN(__irq_dma1_stream2)
+EXTERN(__irq_dma1_stream3)
+EXTERN(__irq_dma1_stream4)
+EXTERN(__irq_dma1_stream5)
+EXTERN(__irq_dma1_stream6)
+EXTERN(__irq_adc)
+EXTERN(__irq_can1_tx)
+EXTERN(__irq_can1_rx0)
+EXTERN(__irq_can1_rx1)
+EXTERN(__irq_can1_sce)
+EXTERN(__irq_exti9_5)
+EXTERN(__irq_tim1_brk)
+EXTERN(__irq_tim1_up)
+EXTERN(__irq_tim1_trg_com)
+EXTERN(__irq_tim1_cc)
+EXTERN(__irq_tim2)
+EXTERN(__irq_tim3)
+EXTERN(__irq_tim4)
+EXTERN(__irq_i2c1_ev)
+EXTERN(__irq_i2c1_er)
+EXTERN(__irq_i2c2_ev)
+EXTERN(__irq_i2c2_er)
+EXTERN(__irq_spi1)
+EXTERN(__irq_spi2)
+EXTERN(__irq_usart1)
+EXTERN(__irq_usart2)
+EXTERN(__irq_usart3)
+EXTERN(__irq_exti15_10)
+EXTERN(__irq_rtcalarm)
+EXTERN(__irq_usbwakeup)
+EXTERN(__irq_tim8_brk)
+EXTERN(__irq_tim8_up)
+EXTERN(__irq_tim8_trg_com)
+EXTERN(__irq_tim8_cc)
+EXTERN(__irq_dma1_stream7)
+EXTERN(__irq_fsmc)
+EXTERN(__irq_sdio)
+EXTERN(__irq_tim5)
+EXTERN(__irq_spi3)
+EXTERN(__irq_uart4)
+EXTERN(__irq_uart5)
+EXTERN(__irq_tim6_dac)
+EXTERN(__irq_tim7)
+EXTERN(__irq_dma2_stream0)
+EXTERN(__irq_dma2_stream1)
+EXTERN(__irq_dma2_stream2)
+EXTERN(__irq_dma2_stream3)
+EXTERN(__irq_dma2_stream4)
+EXTERN(__irq_eth)
+EXTERN(__irq_eth_wkup)
+EXTERN(__irq_can2_tx)
+EXTERN(__irq_can2_rx0)
+EXTERN(__irq_can2_rx1)
+EXTERN(__irq_can2_sce)
+EXTERN(__irq_usb_fs)
+EXTERN(__irq_dma2_stream5)
+EXTERN(__irq_dma2_stream6)
+EXTERN(__irq_dma2_stream7)
+EXTERN(__irq_usart6)
+EXTERN(__irq_i2c3_ev)
+EXTERN(__irq_i2c3_er)
+EXTERN(__irq_usb_hs_ep1_out)
+EXTERN(__irq_usb_hs_ep1_in)
+EXTERN(__irq_usb_hs_wkup)
+EXTERN(__irq_usb_hs)
+EXTERN(__irq_dcmi)
+EXTERN(__irq_cryp)
+EXTERN(__irq_hash_rng)
+EXTERN(__irq_fpu)

+ 2 - 0
sw/variant/blacksasi_f411m/pins_arduino.h

@@ -0,0 +1,2 @@
+// API compatibility
+#include "variant.h"

+ 10 - 0
sw/variant/blacksasi_f411m/variant.h

@@ -0,0 +1,10 @@
+#ifndef _VARIANT_ARDUINO_STM32_
+#define _VARIANT_ARDUINO_STM32_
+
+static const uint8_t SS   = BOARD_SPI1A_NSS_PIN;
+
+static const uint8_t MOSI = BOARD_SPI1A_MOSI_PIN;
+static const uint8_t MISO = BOARD_SPI1A_MISO_PIN;
+static const uint8_t SCK  = BOARD_SPI1A_SCK_PIN;
+
+#endif /* _VARIANT_ARDUINO_STM32_ */