]> sigrok.org Git - libsigrok.git/blobdiff - hardware/asix-sigma/asix-sigma.c
asix-sigma: Clearly separate the sample download
[libsigrok.git] / hardware / asix-sigma / asix-sigma.c
index 1c8e04bdad08f8315908e31efe38adcdb5a05286..cdc0988ba63971a641ca5b8023e2b08be06580ed 100644 (file)
 #define USB_VENDOR_NAME                        "ASIX"
 #define USB_MODEL_NAME                 "SIGMA"
 #define TRIGGER_TYPE                   "rf10"
-#define NUM_CHANNELS                   16
 
 SR_PRIV struct sr_dev_driver asix_sigma_driver_info;
 static struct sr_dev_driver *di = &asix_sigma_driver_info;
 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
 
+/*
+ * The ASIX Sigma supports arbitrary integer frequency divider in
+ * the 50MHz mode. The divider is in range 1...256 , allowing for
+ * very precise sampling rate selection. This driver supports only
+ * a subset of the sampling rates.
+ */
 static const uint64_t samplerates[] = {
-       SR_KHZ(200),
-       SR_KHZ(250),
-       SR_KHZ(500),
-       SR_MHZ(1),
-       SR_MHZ(5),
-       SR_MHZ(10),
-       SR_MHZ(25),
-       SR_MHZ(50),
-       SR_MHZ(100),
-       SR_MHZ(200),
+       SR_KHZ(200),    /* div=250 */
+       SR_KHZ(250),    /* div=200 */
+       SR_KHZ(500),    /* div=100 */
+       SR_MHZ(1),      /* div=50  */
+       SR_MHZ(5),      /* div=10  */
+       SR_MHZ(10),     /* div=5   */
+       SR_MHZ(25),     /* div=2   */
+       SR_MHZ(50),     /* div=1   */
+       SR_MHZ(100),    /* Special FW needed */
+       SR_MHZ(200),    /* Special FW needed */
 };
 
 /*
@@ -61,10 +66,9 @@ static const uint64_t samplerates[] = {
  * http://tools.asix.net/img/sigma_sigmacab_pins_720.jpg
  * (the cable has two additional GND pins, and a TI and TO pin)
  */
-static const char *channel_names[NUM_CHANNELS + 1] = {
+static const char *channel_names[] = {
        "1", "2", "3", "4", "5", "6", "7", "8",
        "9", "10", "11", "12", "13", "14", "15", "16",
-       NULL,
 };
 
 static const int32_t hwcaps[] = {
@@ -76,28 +80,17 @@ static const int32_t hwcaps[] = {
        SR_CONF_LIMIT_SAMPLES,
 };
 
-/* Force the FPGA to reboot. */
-static uint8_t suicide[] = {
-       0x84, 0x84, 0x88, 0x84, 0x88, 0x84, 0x88, 0x84,
-};
-
-/* Prepare to upload firmware (FPGA specific). */
-static uint8_t init_array[] = {
-       0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-};
-
-/* Initialize the logic analyzer mode. */
-static uint8_t logic_mode_start[] = {
-       0x00, 0x40, 0x0f, 0x25, 0x35, 0x40,
-       0x2a, 0x3a, 0x40, 0x03, 0x20, 0x38,
-};
-
-static const char *firmware_files[] = {
-       "asix-sigma-50.fw",     /* 50 MHz, supports 8 bit fractions */
-       "asix-sigma-100.fw",    /* 100 MHz */
-       "asix-sigma-200.fw",    /* 200 MHz */
-       "asix-sigma-50sync.fw", /* Synchronous clock from pin */
-       "asix-sigma-phasor.fw", /* Frequency counter */
+static const char *sigma_firmware_files[] = {
+       /* 50 MHz, supports 8 bit fractions */
+       FIRMWARE_DIR "/asix-sigma-50.fw",
+       /* 100 MHz */
+       FIRMWARE_DIR "/asix-sigma-100.fw",
+       /* 200 MHz */
+       FIRMWARE_DIR "/asix-sigma-200.fw",
+       /* Synchronous clock from pin */
+       FIRMWARE_DIR "/asix-sigma-50sync.fw",
+       /* Frequency counter */
+       FIRMWARE_DIR "/asix-sigma-phasor.fw",
 };
 
 static int sigma_read(void *buf, size_t size, struct dev_context *devc)
@@ -300,87 +293,6 @@ static int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *d
        return SR_OK;
 }
 
-/* Generate the bitbang stream for programming the FPGA. */
-static int bin2bitbang(const char *filename,
-                      unsigned char **buf, size_t *buf_size)
-{
-       FILE *f;
-       unsigned long file_size;
-       unsigned long offset = 0;
-       unsigned char *p;
-       uint8_t *firmware;
-       unsigned long fwsize = 0;
-       const int buffer_size = 65536;
-       size_t i;
-       int c, bit, v;
-       uint32_t imm = 0x3f6df2ab;
-
-       f = g_fopen(filename, "rb");
-       if (!f) {
-               sr_err("g_fopen(\"%s\", \"rb\")", filename);
-               return SR_ERR;
-       }
-
-       if (-1 == fseek(f, 0, SEEK_END)) {
-               sr_err("fseek on %s failed", filename);
-               fclose(f);
-               return SR_ERR;
-       }
-
-       file_size = ftell(f);
-
-       fseek(f, 0, SEEK_SET);
-
-       if (!(firmware = g_try_malloc(buffer_size))) {
-               sr_err("%s: firmware malloc failed", __func__);
-               fclose(f);
-               return SR_ERR_MALLOC;
-       }
-
-       while ((c = getc(f)) != EOF) {
-               imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
-               firmware[fwsize++] = c ^ imm;
-       }
-       fclose(f);
-
-       if(fwsize != file_size) {
-           sr_err("%s: Error reading firmware", filename);
-           fclose(f);
-           g_free(firmware);
-           return SR_ERR;
-       }
-
-       *buf_size = fwsize * 2 * 8;
-
-       *buf = p = (unsigned char *)g_try_malloc(*buf_size);
-       if (!p) {
-               sr_err("%s: buf/p malloc failed", __func__);
-               g_free(firmware);
-               return SR_ERR_MALLOC;
-       }
-
-       for (i = 0; i < fwsize; ++i) {
-               for (bit = 7; bit >= 0; --bit) {
-                       v = firmware[i] & 1 << bit ? 0x40 : 0x00;
-                       p[offset++] = v | 0x01;
-                       p[offset++] = v;
-               }
-       }
-
-       g_free(firmware);
-
-       if (offset != *buf_size) {
-               g_free(*buf);
-               sr_err("Error reading firmware %s "
-                      "offset=%ld, file_size=%ld, buf_size=%zd.",
-                      filename, offset, file_size, *buf_size);
-
-               return SR_ERR;
-       }
-
-       return SR_OK;
-}
-
 static void clear_helper(void *priv)
 {
        struct dev_context *devc;
@@ -410,7 +322,8 @@ static GSList *scan(GSList *options)
        struct ftdi_device_list *devlist;
        char serial_txt[10];
        uint32_t serial;
-       int ret, i;
+       int ret;
+       unsigned int i;
 
        (void)options;
 
@@ -464,9 +377,10 @@ static GSList *scan(GSList *options)
        }
        sdi->driver = di;
 
-       for (i = 0; channel_names[i]; i++) {
-               if (!(ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE,
-                               channel_names[i])))
+       for (i = 0; i < ARRAY_SIZE(channel_names); i++) {
+               ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE,
+                                   channel_names[i]);
+               if (!ch)
                        return NULL;
                sdi->channels = g_slist_append(sdi->channels, ch);
        }
@@ -491,92 +405,235 @@ static GSList *dev_list(void)
        return ((struct drv_context *)(di->priv))->instances;
 }
 
+/*
+ * Configure the FPGA for bitbang mode.
+ * This sequence is documented in section 2. of the ASIX Sigma programming
+ * manual. This sequence is necessary to configure the FPGA in the Sigma
+ * into Bitbang mode, in which it can be programmed with the firmware.
+ */
+static int sigma_fpga_init_bitbang(struct dev_context *devc)
+{
+       uint8_t suicide[] = {
+               0x84, 0x84, 0x88, 0x84, 0x88, 0x84, 0x88, 0x84,
+       };
+       uint8_t init_array[] = {
+               0x01, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01,
+               0x01, 0x01,
+       };
+       int i, ret, timeout = 10000;
+       uint8_t data;
+
+       /* Section 2. part 1), do the FPGA suicide. */
+       sigma_write(suicide, sizeof(suicide), devc);
+       sigma_write(suicide, sizeof(suicide), devc);
+       sigma_write(suicide, sizeof(suicide), devc);
+       sigma_write(suicide, sizeof(suicide), devc);
+
+       /* Section 2. part 2), do pulse on D1. */
+       sigma_write(init_array, sizeof(init_array), devc);
+       ftdi_usb_purge_buffers(&devc->ftdic);
+
+       /* Wait until the FPGA asserts D6/INIT_B. */
+       for (i = 0; i < timeout; i++) {
+               ret = sigma_read(&data, 1, devc);
+               if (ret < 0)
+                       return ret;
+               /* Test if pin D6 got asserted. */
+               if (data & (1 << 5))
+                       return 0;
+               /* The D6 was not asserted yet, wait a bit. */
+               usleep(10000);
+       }
+
+       return SR_ERR_TIMEOUT;
+}
+
+/*
+ * Configure the FPGA for logic-analyzer mode.
+ */
+static int sigma_fpga_init_la(struct dev_context *devc)
+{
+       /* Initialize the logic analyzer mode. */
+       uint8_t logic_mode_start[] = {
+               REG_ADDR_LOW  | (READ_ID & 0xf),
+               REG_ADDR_HIGH | (READ_ID >> 8),
+               REG_READ_ADDR,  /* Read ID register. */
+
+               REG_ADDR_LOW | (WRITE_TEST & 0xf),
+               REG_DATA_LOW | 0x5,
+               REG_DATA_HIGH_WRITE | 0x5,
+               REG_READ_ADDR,  /* Read scratch register. */
+
+               REG_DATA_LOW | 0xa,
+               REG_DATA_HIGH_WRITE | 0xa,
+               REG_READ_ADDR,  /* Read scratch register. */
+
+               REG_ADDR_LOW | (WRITE_MODE & 0xf),
+               REG_DATA_LOW | 0x0,
+               REG_DATA_HIGH_WRITE | 0x8,
+       };
+
+       uint8_t result[3];
+       int ret;
+
+       /* Initialize the logic analyzer mode. */
+       sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
+
+       /* Expect a 3 byte reply since we issued three READ requests. */
+       ret = sigma_read(result, 3, devc);
+       if (ret != 3)
+               goto err;
+
+       if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
+               goto err;
+
+       return SR_OK;
+err:
+       sr_err("Configuration failed. Invalid reply received.");
+       return SR_ERR;
+}
+
+/*
+ * Read the firmware from a file and transform it into a series of bitbang
+ * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
+ * by the caller of this function.
+ */
+static int sigma_fw_2_bitbang(const char *filename,
+                             uint8_t **bb_cmd, gsize *bb_cmd_size)
+{
+       GMappedFile *file;
+       GError *error;
+       gsize i, file_size, bb_size;
+       gchar *firmware;
+       uint8_t *bb_stream, *bbs;
+       uint32_t imm;
+       int bit, v;
+       int ret = SR_OK;
+
+       /*
+        * Map the file and make the mapped buffer writable.
+        * NOTE: Using writable=TRUE does _NOT_ mean that file that is mapped
+        *       will be modified. It will not be modified until someone uses
+        *       g_file_set_contents() on it.
+        */
+       error = NULL;
+       file = g_mapped_file_new(filename, TRUE, &error);
+       g_assert_no_error(error);
+
+       file_size = g_mapped_file_get_length(file);
+       firmware = g_mapped_file_get_contents(file);
+       g_assert(firmware);
+
+       /* Weird magic transformation below, I have no idea what it does. */
+       imm = 0x3f6df2ab;
+       for (i = 0; i < file_size; i++) {
+               imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
+               firmware[i] ^= imm & 0xff;
+       }
+
+       /*
+        * Now that the firmware is "transformed", we will transcribe the
+        * firmware blob into a sequence of toggles of the Dx wires. This
+        * sequence will be fed directly into the Sigma, which must be in
+        * the FPGA bitbang programming mode.
+        */
+
+       /* Each bit of firmware is transcribed as two toggles of Dx wires. */
+       bb_size = file_size * 8 * 2;
+       bb_stream = (uint8_t *)g_try_malloc(bb_size);
+       if (!bb_stream) {
+               sr_err("%s: Failed to allocate bitbang stream", __func__);
+               ret = SR_ERR_MALLOC;
+               goto exit;
+       }
+
+       bbs = bb_stream;
+       for (i = 0; i < file_size; i++) {
+               for (bit = 7; bit >= 0; bit--) {
+                       v = (firmware[i] & (1 << bit)) ? 0x40 : 0x00;
+                       *bbs++ = v | 0x01;
+                       *bbs++ = v;
+               }
+       }
+
+       /* The transformation completed successfully, return the result. */
+       *bb_cmd = bb_stream;
+       *bb_cmd_size = bb_size;
+
+exit:
+       g_mapped_file_unref(file);
+       return ret;
+}
+
 static int upload_firmware(int firmware_idx, struct dev_context *devc)
 {
        int ret;
        unsigned char *buf;
        unsigned char pins;
        size_t buf_size;
-       unsigned char result[32];
-       char firmware_path[128];
+       const char *firmware = sigma_firmware_files[firmware_idx];
+       struct ftdi_context *ftdic = &devc->ftdic;
 
        /* Make sure it's an ASIX SIGMA. */
-       if ((ret = ftdi_usb_open_desc(&devc->ftdic,
-               USB_VENDOR, USB_PRODUCT, USB_DESCRIPTION, NULL)) < 0) {
+       ret = ftdi_usb_open_desc(ftdic, USB_VENDOR, USB_PRODUCT,
+                                USB_DESCRIPTION, NULL);
+       if (ret < 0) {
                sr_err("ftdi_usb_open failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+                      ftdi_get_error_string(ftdic));
                return 0;
        }
 
-       if ((ret = ftdi_set_bitmode(&devc->ftdic, 0xdf, BITMODE_BITBANG)) < 0) {
+       ret = ftdi_set_bitmode(ftdic, 0xdf, BITMODE_BITBANG);
+       if (ret < 0) {
                sr_err("ftdi_set_bitmode failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+                      ftdi_get_error_string(ftdic));
                return 0;
        }
 
        /* Four times the speed of sigmalogan - Works well. */
-       if ((ret = ftdi_set_baudrate(&devc->ftdic, 750000)) < 0) {
+       ret = ftdi_set_baudrate(ftdic, 750000);
+       if (ret < 0) {
                sr_err("ftdi_set_baudrate failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+                      ftdi_get_error_string(ftdic));
                return 0;
        }
 
-       /* Force the FPGA to reboot. */
-       sigma_write(suicide, sizeof(suicide), devc);
-       sigma_write(suicide, sizeof(suicide), devc);
-       sigma_write(suicide, sizeof(suicide), devc);
-       sigma_write(suicide, sizeof(suicide), devc);
-
-       /* Prepare to upload firmware (FPGA specific). */
-       sigma_write(init_array, sizeof(init_array), devc);
-
-       ftdi_usb_purge_buffers(&devc->ftdic);
-
-       /* Wait until the FPGA asserts INIT_B. */
-       while (1) {
-               ret = sigma_read(result, 1, devc);
-               if (result[0] & 0x20)
-                       break;
-       }
+       /* Initialize the FPGA for firmware upload. */
+       ret = sigma_fpga_init_bitbang(devc);
+       if (ret)
+               return ret;
 
        /* Prepare firmware. */
-       snprintf(firmware_path, sizeof(firmware_path), "%s/%s", FIRMWARE_DIR,
-                firmware_files[firmware_idx]);
-
-       if ((ret = bin2bitbang(firmware_path, &buf, &buf_size)) != SR_OK) {
+       ret = sigma_fw_2_bitbang(firmware, &buf, &buf_size);
+       if (ret != SR_OK) {
                sr_err("An error occured while reading the firmware: %s",
-                      firmware_path);
+                      firmware);
                return ret;
        }
 
        /* Upload firmare. */
-       sr_info("Uploading firmware file '%s'.", firmware_files[firmware_idx]);
+       sr_info("Uploading firmware file '%s'.", firmware);
        sigma_write(buf, buf_size, devc);
 
        g_free(buf);
 
-       if ((ret = ftdi_set_bitmode(&devc->ftdic, 0x00, BITMODE_RESET)) < 0) {
+       ret = ftdi_set_bitmode(ftdic, 0x00, BITMODE_RESET);
+       if (ret < 0) {
                sr_err("ftdi_set_bitmode failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+                      ftdi_get_error_string(ftdic));
                return SR_ERR;
        }
 
-       ftdi_usb_purge_buffers(&devc->ftdic);
+       ftdi_usb_purge_buffers(ftdic);
 
        /* Discard garbage. */
-       while (1 == sigma_read(&pins, 1, devc))
+       while (sigma_read(&pins, 1, devc) == 1)
                ;
 
-       /* Initialize the logic analyzer mode. */
-       sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
-
-       /* Expect a 3 byte reply. */
-       ret = sigma_read(result, 3, devc);
-       if (ret != 3 ||
-           result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa) {
-               sr_err("Configuration failed. Invalid reply received.");
-               return SR_ERR;
-       }
+       /* Initialize the FPGA for logic-analyzer mode. */
+       ret = sigma_fpga_init_la(devc);
+       if (ret != SR_OK)
+               return ret;
 
        devc->cur_firmware = firmware_idx;
 
@@ -1063,65 +1120,85 @@ static void download_capture(struct sr_dev_inst *sdi)
 
 }
 
-static int receive_data(int fd, int revents, void *cb_data)
+/*
+ * Handle the Sigma when in CAPTURE mode. This function checks:
+ * - Sampling time ended
+ * - DRAM capacity overflow
+ * This function triggers download of the samples from Sigma
+ * in case either of the above conditions is true.
+ */
+static int sigma_capture_mode(struct sr_dev_inst *sdi)
 {
-       struct sr_dev_inst *sdi;
-       struct dev_context *devc;
+       struct dev_context *devc = sdi->priv;
+
        struct sr_datafeed_packet packet;
        uint64_t running_msec;
        struct timeval tv;
-       int numchunks;
        uint8_t modestatus;
 
-       (void)fd;
-       (void)revents;
+       uint32_t stoppos, triggerpos;
 
-       sdi = cb_data;
-       devc = sdi->priv;
+       /* Check if the selected sampling duration passed. */
+       gettimeofday(&tv, 0);
+       running_msec = (tv.tv_sec - devc->start_tv.tv_sec) * 1000 +
+                      (tv.tv_usec - devc->start_tv.tv_usec) / 1000;
+       if (running_msec >= devc->limit_msec)
+               goto download;
+
+       /* Get the position in DRAM to which the FPGA is writing now. */
+       sigma_read_pos(&stoppos, &triggerpos, devc);
+       /* Test if DRAM is full and if so, download the data. */
+       if ((stoppos >> 9) == 32767)
+               goto download;
+
+       return TRUE;
+
+download:
+
+       /* Stop acquisition. */
+       sigma_set_register(WRITE_MODE, 0x11, devc);
+
+       /* Set SDRAM Read Enable. */
+       sigma_set_register(WRITE_MODE, 0x02, devc);
 
        /* Get the current position. */
        sigma_read_pos(&devc->state.stoppos, &devc->state.triggerpos, devc);
 
-       if (devc->state.state == SIGMA_IDLE)
-               return TRUE;
-
-       if (devc->state.state == SIGMA_CAPTURE) {
-               numchunks = (devc->state.stoppos + 511) / 512;
+       /* Check if trigger has fired. */
+       modestatus = sigma_get_register(READ_MODE, devc);
+       if (modestatus & 0x20)
+               devc->state.triggerchunk = devc->state.triggerpos / 512;
+       else
+               devc->state.triggerchunk = -1;
 
-               /* Check if the timer has expired, or memory is full. */
-               gettimeofday(&tv, 0);
-               running_msec = (tv.tv_sec - devc->start_tv.tv_sec) * 1000 +
-                       (tv.tv_usec - devc->start_tv.tv_usec) / 1000;
+       /* Transfer captured data from device. */
+       download_capture(sdi);
 
-               if (running_msec < devc->limit_msec && numchunks < 32767)
-                       /* Still capturing. */
-                       return TRUE;
+       /* All done. */
+       packet.type = SR_DF_END;
+       sr_session_send(sdi, &packet);
 
-               /* Stop acquisition. */
-               sigma_set_register(WRITE_MODE, 0x11, devc);
+       dev_acquisition_stop(sdi, sdi);
 
-               /* Set SDRAM Read Enable. */
-               sigma_set_register(WRITE_MODE, 0x02, devc);
+       return TRUE;
+}
 
-               /* Get the current position. */
-               sigma_read_pos(&devc->state.stoppos, &devc->state.triggerpos, devc);
+static int receive_data(int fd, int revents, void *cb_data)
+{
+       struct sr_dev_inst *sdi;
+       struct dev_context *devc;
 
-               /* Check if trigger has fired. */
-               modestatus = sigma_get_register(READ_MODE, devc);
-               if (modestatus & 0x20)
-                       devc->state.triggerchunk = devc->state.triggerpos / 512;
-               else
-                       devc->state.triggerchunk = -1;
+       (void)fd;
+       (void)revents;
 
-               /* Transfer captured data from device. */
-               download_capture(sdi);
+       sdi = cb_data;
+       devc = sdi->priv;
 
-               /* All done. */
-               packet.type = SR_DF_END;
-               sr_session_send(sdi, &packet);
+       if (devc->state.state == SIGMA_IDLE)
+               return TRUE;
 
-               dev_acquisition_stop(sdi, sdi);
-       }
+       if (devc->state.state == SIGMA_CAPTURE)
+               return sigma_capture_mode(sdi);
 
        return TRUE;
 }