]> sigrok.org Git - libsigrok.git/blobdiff - src/hardware/asix-sigma/protocol.c
asix-sigma: improve error propagation, increase robustness
[libsigrok.git] / src / hardware / asix-sigma / protocol.c
index 68bb83e558b794b0ae9f2837193f4f4ea85d0df7..60970a8d89d498755959ae8575b0d0756bfe6617 100644 (file)
@@ -4,6 +4,7 @@
  * Copyright (C) 2010-2012 Håvard Espeland <gus@ping.uio.no>,
  * Copyright (C) 2010 Martin Stensgård <mastensg@ping.uio.no>
  * Copyright (C) 2010 Carl Henrik Lunde <chlunde@ping.uio.no>
+ * Copyright (C) 2020 Gerhard Sittig <gerhard.sittig@gmx.net>
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 #include "protocol.h"
 
 /*
- * 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.
+ * The ASIX SIGMA hardware supports fixed 200MHz and 100MHz sample rates
+ * (by means of separate firmware images). As well as 50MHz divided by
+ * an integer divider in the 1..256 range (by the "typical" firmware).
+ * Which translates to a strict lower boundary of around 195kHz.
+ *
+ * This driver "suggests" a subset of the available rates by listing a
+ * few discrete values, while setter routines accept any user specified
+ * rate that is supported by the hardware.
  */
 SR_PRIV const uint64_t samplerates[] = {
-       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 */
+       /* 50MHz and integer divider. 1/2/5 steps (where possible). */
+       SR_KHZ(200), SR_KHZ(500),
+       SR_MHZ(1), SR_MHZ(2), SR_MHZ(5),
+       SR_MHZ(10), SR_MHZ(25), SR_MHZ(50),
+       /* 100MHz/200MHz, fixed rates in special firmware. */
+       SR_MHZ(100), SR_MHZ(200),
 };
 
 SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
@@ -57,172 +58,241 @@ static const char *firmware_files[] = {
 
 #define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
 
-static int sigma_read(void *buf, size_t size, struct dev_context *devc)
+/*
+ * BEWARE! Error propagation is important, as are kinds of return values.
+ *
+ * - Raw USB tranport communicates the number of sent or received bytes,
+ *   or negative error codes in the external library's(!) range of codes.
+ * - Internal routines at the "sigrok driver level" communicate success
+ *   or failure in terms of SR_OK et al error codes.
+ * - Main loop style receive callbacks communicate booleans which arrange
+ *   for repeated calls to drive progress during acquisition.
+ *
+ * Careful consideration by maintainers is essential, because all of the
+ * above kinds of values are assignment compatbile from the compiler's
+ * point of view. Implementation errors will go unnoticed at build time.
+ */
+
+static int sigma_read_raw(struct dev_context *devc, void *buf, size_t size)
 {
        int ret;
 
        ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
        if (ret < 0) {
-               sr_err("ftdi_read_data failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+               sr_err("USB data read failed: %s",
+                       ftdi_get_error_string(&devc->ftdic));
        }
 
        return ret;
 }
 
-static int sigma_write(void *buf, size_t size, struct dev_context *devc)
+static int sigma_write_raw(struct dev_context *devc, const void *buf, size_t size)
 {
        int ret;
 
-       ret = ftdi_write_data(&devc->ftdic, (unsigned char *)buf, size);
-       if (ret < 0)
-               sr_err("ftdi_write_data failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
-       else if ((size_t) ret != size)
-               sr_err("ftdi_write_data did not complete write.");
+       ret = ftdi_write_data(&devc->ftdic, buf, size);
+       if (ret < 0) {
+               sr_err("USB data write failed: %s",
+                       ftdi_get_error_string(&devc->ftdic));
+       } else if ((size_t)ret != size) {
+               sr_err("USB data write length mismatch.");
+       }
 
        return ret;
 }
 
+static int sigma_read_sr(struct dev_context *devc, void *buf, size_t size)
+{
+       int ret;
+
+       ret = sigma_read_raw(devc, buf, size);
+       if (ret < 0 || (size_t)ret != size)
+               return SR_ERR_IO;
+
+       return SR_OK;
+}
+
+static int sigma_write_sr(struct dev_context *devc, const void *buf, size_t size)
+{
+       int ret;
+
+       ret = sigma_write_raw(devc, buf, size);
+       if (ret < 0 || (size_t)ret != size)
+               return SR_ERR_IO;
+
+       return SR_OK;
+}
+
 /*
- * NOTE: We chose the buffer size to be large enough to hold any write to the
- * device. We still print a message just in case.
+ * Implementor's note: The local write buffer's size shall suffice for
+ * any know FPGA register transaction that is involved in the supported
+ * feature set of this sigrok device driver. If the length check trips,
+ * that's a programmer's error and needs adjustment in the complete call
+ * stack of the respective code path.
  */
-SR_PRIV int sigma_write_register(uint8_t reg, uint8_t *data, size_t len,
-                                struct dev_context *devc)
+SR_PRIV int sigma_write_register(struct dev_context *devc,
+       uint8_t reg, uint8_t *data, size_t len)
 {
-       size_t i;
-       uint8_t buf[80];
-       int idx = 0;
+       uint8_t buf[80], *wrptr;
+       size_t idx;
 
-       if ((2 * len + 2) > sizeof(buf)) {
-               sr_err("Attempted to write %zu bytes, but buffer is too small.",
-                      len);
+       if (2 + 2 * len > sizeof(buf)) {
+               sr_err("Short write buffer for %zu bytes to reg %u.", len, reg);
                return SR_ERR_BUG;
        }
 
-       buf[idx++] = REG_ADDR_LOW | (reg & 0xf);
-       buf[idx++] = REG_ADDR_HIGH | (reg >> 4);
-
-       for (i = 0; i < len; i++) {
-               buf[idx++] = REG_DATA_LOW | (data[i] & 0xf);
-               buf[idx++] = REG_DATA_HIGH_WRITE | (data[i] >> 4);
+       wrptr = buf;
+       write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
+       write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
+       for (idx = 0; idx < len; idx++) {
+               write_u8_inc(&wrptr, REG_DATA_LOW | (data[idx] & 0xf));
+               write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data[idx] >> 4));
        }
 
-       return sigma_write(buf, idx, devc);
+       return sigma_write_sr(devc, buf, wrptr - buf);
 }
 
-SR_PRIV int sigma_set_register(uint8_t reg, uint8_t value, struct dev_context *devc)
+SR_PRIV int sigma_set_register(struct dev_context *devc,
+       uint8_t reg, uint8_t value)
 {
-       return sigma_write_register(reg, &value, 1, devc);
+       return sigma_write_register(devc, reg, &value, sizeof(value));
 }
 
-static int sigma_read_register(uint8_t reg, uint8_t *data, size_t len,
-                              struct dev_context *devc)
+static int sigma_read_register(struct dev_context *devc,
+       uint8_t reg, uint8_t *data, size_t len)
 {
-       uint8_t buf[3];
-
-       buf[0] = REG_ADDR_LOW | (reg & 0xf);
-       buf[1] = REG_ADDR_HIGH | (reg >> 4);
-       buf[2] = REG_READ_ADDR;
+       uint8_t buf[3], *wrptr;
+       int ret;
 
-       sigma_write(buf, sizeof(buf), devc);
+       wrptr = buf;
+       write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
+       write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
+       write_u8_inc(&wrptr, REG_READ_ADDR);
+       ret = sigma_write_sr(devc, buf, wrptr - buf);
+       if (ret != SR_OK)
+               return ret;
 
-       return sigma_read(data, len, devc);
+       return sigma_read_sr(devc, data, len);
 }
 
-static int sigma_read_pos(uint32_t *stoppos, uint32_t *triggerpos,
-                         struct dev_context *devc)
+static int sigma_read_pos(struct dev_context *devc,
+       uint32_t *stoppos, uint32_t *triggerpos, uint8_t *mode)
 {
        /*
-        * Read 6 registers starting at trigger position LSB.
-        * Which yields two 24bit counter values.
+        * Read 7 registers starting at trigger position LSB.
+        * Which yields two 24bit counter values, and mode flags.
         */
-       uint8_t buf[] = {
+       const uint8_t buf[] = {
+               /* Setup first register address. */
                REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
+               /* Retrieve trigger position. */
                REG_READ_ADDR | REG_ADDR_INC,
                REG_READ_ADDR | REG_ADDR_INC,
                REG_READ_ADDR | REG_ADDR_INC,
+               /* Retrieve stop position. */
                REG_READ_ADDR | REG_ADDR_INC,
                REG_READ_ADDR | REG_ADDR_INC,
                REG_READ_ADDR | REG_ADDR_INC,
-       };
-       uint8_t result[6];
+               /* Retrieve mode register. */
+               REG_READ_ADDR | REG_ADDR_INC,
+       }, *rdptr;
+       uint8_t result[7];
+       uint32_t v32;
+       uint8_t v8;
+       int ret;
 
-       sigma_write(buf, sizeof(buf), devc);
+       ret = sigma_write_sr(devc, buf, sizeof(buf));
+       if (ret != SR_OK)
+               return ret;
 
-       sigma_read(result, sizeof(result), devc);
+       ret = sigma_read_sr(devc, result, sizeof(result));
+       if (ret != SR_OK)
+               return ret;
 
-       *triggerpos = result[0] | (result[1] << 8) | (result[2] << 16);
-       *stoppos = result[3] | (result[4] << 8) | (result[5] << 16);
+       rdptr = &result[0];
+       v32 = read_u24le_inc(&rdptr);
+       if (triggerpos)
+               *triggerpos = v32;
+       v32 = read_u24le_inc(&rdptr);
+       if (stoppos)
+               *stoppos = v32;
+       v8 = read_u8_inc(&rdptr);
+       if (mode)
+               *mode = v8;
 
        /*
-        * These "position" values point to after the event (end of
-        * capture data, trigger condition matched). This is why they
-        * get decremented here. Sample memory consists of 512-byte
-        * chunks with meta data in the upper 64 bytes. Thus when the
-        * decrements takes us into this upper part of the chunk, then
-        * further move backwards to the end of the chunk's data part.
+        * These positions consist of "the memory row" in the MSB fields,
+        * and "an event index" within the row in the LSB fields. Part
+        * of the memory row's content is sample data, another part is
+        * timestamps.
         *
-        * TODO Re-consider the above comment's validity. It's true
-        * that a 1024byte row contains 512 u16 entities, of which 64
-        * are timestamps and 448 are events with sample data. It's not
-        * true that 64bytes of metadata reside at the top of a 512byte
-        * block in a row.
-        *
-        * TODO Use ROW_MASK and CLUSTERS_PER_ROW here?
+        * The retrieved register values point to after the captured
+        * position. So they need to get decremented, and adjusted to
+        * cater for the timestamps when the decrement carries over to
+        * a different memory row.
         */
-       if ((--*stoppos & 0x1ff) == 0x1ff)
-               *stoppos -= 64;
-       if ((--*triggerpos & 0x1ff) == 0x1ff)
-               *triggerpos -= 64;
+       if (stoppos && (--*stoppos & ROW_MASK) == ROW_MASK)
+               *stoppos -= CLUSTERS_PER_ROW;
+       if (triggerpos && (--*triggerpos & ROW_MASK) == ROW_MASK)
+               *triggerpos -= CLUSTERS_PER_ROW;
 
-       return 1;
+       return SR_OK;
 }
 
-static int sigma_read_dram(uint16_t startchunk, size_t numchunks,
-                          uint8_t *data, struct dev_context *devc)
+static int sigma_read_dram(struct dev_context *devc,
+       uint16_t startchunk, size_t numchunks, uint8_t *data)
 {
-       uint8_t buf[4096];
-       int idx;
+       uint8_t buf[128], *wrptr;
        size_t chunk;
-       int sel;
+       int sel, ret;
        gboolean is_last;
 
+       if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
+               sr_err("Short write buffer for %zu DRAM row reads.", numchunks);
+               return SR_ERR_BUG;
+       }
+
        /* Communicate DRAM start address (memory row, aka samples line). */
-       idx = 0;
-       buf[idx++] = startchunk >> 8;
-       buf[idx++] = startchunk & 0xff;
-       sigma_write_register(WRITE_MEMROW, buf, idx, devc);
+       wrptr = buf;
+       write_u8_inc(&wrptr, startchunk >> 8);
+       write_u8_inc(&wrptr, startchunk & 0xff);
+       ret = sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
+       if (ret != SR_OK)
+               return ret;
 
        /*
         * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
         * then transfer via USB. Interleave the FPGA's DRAM access and
         * USB transfer, use alternating buffers (0/1) in the process.
         */
-       idx = 0;
-       buf[idx++] = REG_DRAM_BLOCK;
-       buf[idx++] = REG_DRAM_WAIT_ACK;
+       wrptr = buf;
+       write_u8_inc(&wrptr, REG_DRAM_BLOCK);
+       write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
        for (chunk = 0; chunk < numchunks; chunk++) {
                sel = chunk % 2;
                is_last = chunk == numchunks - 1;
                if (!is_last)
-                       buf[idx++] = REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel);
-               buf[idx++] = REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel);
+                       write_u8_inc(&wrptr, REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel));
+               write_u8_inc(&wrptr, REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel));
                if (!is_last)
-                       buf[idx++] = REG_DRAM_WAIT_ACK;
+                       write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
        }
-       sigma_write(buf, idx, devc);
+       ret = sigma_write_sr(devc, buf, wrptr - buf);
+       if (ret != SR_OK)
+               return ret;
 
-       return sigma_read(data, numchunks * ROW_LENGTH_BYTES, devc);
+       return sigma_read_sr(devc, data, numchunks * ROW_LENGTH_BYTES);
 }
 
 /* Upload trigger look-up tables to Sigma. */
-SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *devc)
+SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
+       struct triggerlut *lut)
 {
        int i;
        uint8_t tmp[2];
        uint16_t bit;
+       uint8_t buf[6], *wrptr, regval;
+       int ret;
 
        /* Transpose the table and send to Sigma. */
        for (i = 0; i < 16; i++) {
@@ -264,14 +334,39 @@ SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *
                if (lut->m1d[3] & bit)
                        tmp[1] |= 0x80;
 
-               sigma_write_register(WRITE_TRIGGER_SELECT, tmp, sizeof(tmp),
-                                    devc);
-               sigma_set_register(WRITE_TRIGGER_SELECT2, 0x30 | i, devc);
+               /*
+                * This logic seems redundant, but separates the value
+                * determination from the wire format, and is useful
+                * during future maintenance and research.
+                */
+               wrptr = buf;
+               write_u8_inc(&wrptr, tmp[0]);
+               write_u8_inc(&wrptr, tmp[1]);
+               ret = sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
+               if (ret != SR_OK)
+                       return ret;
+               ret = sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x30 | i);
+               if (ret != SR_OK)
+                       return ret;
        }
 
        /* Send the parameters */
-       sigma_write_register(WRITE_TRIGGER_SELECT, (uint8_t *) &lut->params,
-                            sizeof(lut->params), devc);
+       wrptr = buf;
+       regval = 0;
+       regval |= lut->params.selc << 6;
+       regval |= lut->params.selpresc << 0;
+       write_u8_inc(&wrptr, regval);
+       regval = 0;
+       regval |= lut->params.selinc << 6;
+       regval |= lut->params.selres << 4;
+       regval |= lut->params.sela << 2;
+       regval |= lut->params.selb << 0;
+       write_u8_inc(&wrptr, regval);
+       write_u16le_inc(&wrptr, lut->params.cmpb);
+       write_u16le_inc(&wrptr, lut->params.cmpa);
+       ret = sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
+       if (ret != SR_OK)
+               return ret;
 
        return SR_OK;
 }
@@ -324,7 +419,7 @@ SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *
  */
 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
 {
-       uint8_t suicide[] = {
+       const uint8_t suicide[] = {
                BB_PIN_D7 | BB_PIN_D2,
                BB_PIN_D7 | BB_PIN_D2,
                BB_PIN_D7 |           BB_PIN_D3,
@@ -334,7 +429,7 @@ static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
                BB_PIN_D7 |           BB_PIN_D3,
                BB_PIN_D7 | BB_PIN_D2,
        };
-       uint8_t init_array[] = {
+       const uint8_t init_array[] = {
                BB_PIN_CCLK,
                BB_PIN_CCLK | BB_PIN_PROG,
                BB_PIN_CCLK | BB_PIN_PROG,
@@ -350,26 +445,43 @@ static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
        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);
+       ret = SR_OK;
+       ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
+       ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
+       ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
+       ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
+       if (ret != SR_OK)
+               return SR_ERR_IO;
        g_usleep(10 * 1000);
 
        /* Section 2. part 2), pulse PROG. */
-       sigma_write(init_array, sizeof(init_array), devc);
+       ret = sigma_write_sr(devc, init_array, sizeof(init_array));
+       if (ret != SR_OK)
+               return ret;
        g_usleep(10 * 1000);
        ftdi_usb_purge_buffers(&devc->ftdic);
 
-       /* Wait until the FPGA asserts INIT_B. */
+       /*
+        * Wait until the FPGA asserts INIT_B. Check in a maximum number
+        * of bursts with a given delay between them. Read as many pin
+        * capture results as the combination of FTDI chip and FTID lib
+        * may provide. Cope with absence of pin capture data in a cycle.
+        * This approach shall result in fast reponse in case of success,
+        * low cost of execution during wait, reliable error handling in
+        * the transport layer, and robust response to failure or absence
+        * of result data (hardware inactivity after stimulus).
+        */
        retries = 10;
        while (retries--) {
-               ret = sigma_read(&data, 1, devc);
-               if (ret < 0)
-                       return ret;
-               if (data & BB_PIN_INIT)
-                       return SR_OK;
-               g_usleep(10 * 1000);
+               do {
+                       ret = sigma_read_raw(devc, &data, sizeof(data));
+                       if (ret < 0)
+                               return SR_ERR_IO;
+                       if (ret == sizeof(data) && (data & BB_PIN_INIT))
+                               return SR_OK;
+               } while (ret == sizeof(data));
+               if (retries)
+                       g_usleep(10 * 1000);
        }
 
        return SR_ERR_TIMEOUT;
@@ -401,52 +513,68 @@ static int sigma_fpga_init_bitbang(struct dev_context *devc)
  */
 static int sigma_fpga_init_la(struct dev_context *devc)
 {
-       /*
-        * TODO Construct the sequence at runtime? Such that request data
-        * and response check values will match more apparently?
-        */
-       uint8_t mode_regval = WMR_SDRAMINIT;
-       uint8_t logic_mode_start[] = {
-               /* Read ID register. */
-               REG_ADDR_LOW  | (READ_ID & 0xf),
-               REG_ADDR_HIGH | (READ_ID >> 4),
-               REG_READ_ADDR,
-
-               /* Write 0x55 to scratch register, read back. */
-               REG_ADDR_LOW | (WRITE_TEST & 0xf),
-               REG_DATA_LOW | 0x5,
-               REG_DATA_HIGH_WRITE | 0x5,
-               REG_READ_ADDR,
-
-               /* Write 0xaa to scratch register, read back. */
-               REG_DATA_LOW | 0xa,
-               REG_DATA_HIGH_WRITE | 0xa,
-               REG_READ_ADDR,
-
-               /* Initiate SDRAM initialization in mode register. */
-               REG_ADDR_LOW | (WRITE_MODE & 0xf),
-               REG_DATA_LOW | (mode_regval & 0xf),
-               REG_DATA_HIGH_WRITE | (mode_regval >> 4),
-       };
+       uint8_t buf[16], *wrptr;
+       uint8_t data_55, data_aa, mode;
        uint8_t result[3];
+       const uint8_t *rdptr;
        int ret;
 
+       wrptr = buf;
+
+       /* Read ID register. */
+       write_u8_inc(&wrptr, REG_ADDR_LOW | (READ_ID & 0xf));
+       write_u8_inc(&wrptr, REG_ADDR_HIGH | (READ_ID >> 4));
+       write_u8_inc(&wrptr, REG_READ_ADDR);
+
+       /* Write 0x55 to scratch register, read back. */
+       data_55 = 0x55;
+       write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
+       write_u8_inc(&wrptr, REG_DATA_LOW | (data_55 & 0xf));
+       write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_55 >> 4));
+       write_u8_inc(&wrptr, REG_READ_ADDR);
+
+       /* Write 0xaa to scratch register, read back. */
+       data_aa = 0xaa;
+       write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
+       write_u8_inc(&wrptr, REG_DATA_LOW | (data_aa & 0xf));
+       write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_aa >> 4));
+       write_u8_inc(&wrptr, REG_READ_ADDR);
+
+       /* Initiate SDRAM initialization in mode register. */
+       mode = WMR_SDRAMINIT;
+       write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_MODE & 0xf));
+       write_u8_inc(&wrptr, REG_DATA_LOW | (mode & 0xf));
+       write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (mode >> 4));
+
        /*
         * Send the command sequence which contains 3 READ requests.
         * Expect to see the corresponding 3 response bytes.
         */
-       sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
-       ret = sigma_read(result, ARRAY_SIZE(result), devc);
-       if (ret != ARRAY_SIZE(result))
-               goto err;
-       if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
-               goto err;
+       ret = sigma_write_sr(devc, buf, wrptr - buf);
+       if (ret != SR_OK) {
+               sr_err("Could not request LA start response.");
+               return ret;
+       }
+       ret = sigma_read_sr(devc, result, ARRAY_SIZE(result));
+       if (ret != SR_OK) {
+               sr_err("Could not receive LA start response.");
+               return SR_ERR_IO;
+       }
+       rdptr = result;
+       if (read_u8_inc(&rdptr) != 0xa6) {
+               sr_err("Unexpected ID response.");
+               return SR_ERR_DATA;
+       }
+       if (read_u8_inc(&rdptr) != data_55) {
+               sr_err("Unexpected scratch read-back (55).");
+               return SR_ERR_DATA;
+       }
+       if (read_u8_inc(&rdptr) != data_aa) {
+               sr_err("Unexpected scratch read-back (aa).");
+               return SR_ERR_DATA;
+       }
 
        return SR_OK;
-
-err:
-       sr_err("Configuration failed. Invalid reply received.");
-       return SR_ERR;
 }
 
 /*
@@ -455,7 +583,7 @@ err:
  * by the caller of this function.
  */
 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
-                             uint8_t **bb_cmd, gsize *bb_cmd_size)
+       uint8_t **bb_cmd, gsize *bb_cmd_size)
 {
        uint8_t *firmware;
        size_t file_size;
@@ -498,7 +626,7 @@ static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
        bb_size = file_size * 8 * 2;
        bb_stream = g_try_malloc(bb_size);
        if (!bb_stream) {
-               sr_err("%s: Failed to allocate bitbang stream", __func__);
+               sr_err("Memory allocation failed during firmware upload.");
                g_free(firmware);
                return SR_ERR_MALLOC;
        }
@@ -524,12 +652,12 @@ static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
        return SR_OK;
 }
 
-static int upload_firmware(struct sr_context *ctx,
-       struct dev_context *devc, enum sigma_firmware_idx firmware_idx)
+static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
+       enum sigma_firmware_idx firmware_idx)
 {
        int ret;
-       unsigned char *buf;
-       unsigned char pins;
+       uint8_t *buf;
+       uint8_t pins;
        size_t buf_size;
        const char *firmware;
 
@@ -551,51 +679,57 @@ static int upload_firmware(struct sr_context *ctx,
        /* Set the cable to bitbang mode. */
        ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
        if (ret < 0) {
-               sr_err("ftdi_set_bitmode failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+               sr_err("Could not setup cable mode for upload: %s",
+                       ftdi_get_error_string(&devc->ftdic));
                return SR_ERR;
        }
        ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
        if (ret < 0) {
-               sr_err("ftdi_set_baudrate failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+               sr_err("Could not setup bitrate for upload: %s",
+                       ftdi_get_error_string(&devc->ftdic));
                return SR_ERR;
        }
 
        /* Initiate FPGA configuration mode. */
        ret = sigma_fpga_init_bitbang(devc);
-       if (ret)
+       if (ret) {
+               sr_err("Could not initiate firmware upload to hardware");
                return ret;
+       }
 
        /* Prepare wire format of the firmware image. */
        ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
        if (ret != SR_OK) {
-               sr_err("An error occurred while reading the firmware: %s",
-                      firmware);
+               sr_err("Could not prepare file %s for upload.", firmware);
                return ret;
        }
 
        /* Write the FPGA netlist to the cable. */
        sr_info("Uploading firmware file '%s'.", firmware);
-       sigma_write(buf, buf_size, devc);
-
+       ret = sigma_write_sr(devc, buf, buf_size);
        g_free(buf);
+       if (ret != SR_OK) {
+               sr_err("Could not upload firmware file '%s'.", firmware);
+               return ret;
+       }
 
        /* Leave bitbang mode and discard pending input data. */
        ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
        if (ret < 0) {
-               sr_err("ftdi_set_bitmode failed: %s",
-                      ftdi_get_error_string(&devc->ftdic));
+               sr_err("Could not setup cable mode after upload: %s",
+                       ftdi_get_error_string(&devc->ftdic));
                return SR_ERR;
        }
        ftdi_usb_purge_buffers(&devc->ftdic);
-       while (sigma_read(&pins, 1, devc) == 1)
+       while (sigma_read_raw(devc, &pins, sizeof(pins)) > 0)
                ;
 
        /* Initialize the FPGA for logic-analyzer mode. */
        ret = sigma_fpga_init_la(devc);
-       if (ret != SR_OK)
+       if (ret != SR_OK) {
+               sr_err("Hardware response after firmware upload failed.");
                return ret;
+       }
 
        /* Keep track of successful firmware download completion. */
        devc->state.state = SIGMA_IDLE;
@@ -906,8 +1040,7 @@ static int addto_submit_buffer(struct dev_context *devc,
         * enforcement of user specified limits is exact.
         */
        while (count--) {
-               WL16(buffer->write_pointer, sample);
-               buffer->write_pointer += buffer->unit_size;
+               write_u16le_inc(&buffer->write_pointer, sample);
                buffer->curr_samples++;
                if (buffer->curr_samples == buffer->max_samples) {
                        ret = flush_submit_buffer(devc);
@@ -940,8 +1073,9 @@ SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
        int channelbit, trigger_set;
 
        devc = sdi->priv;
-       memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
-       if (!(trigger = sr_session_trigger_get(sdi->session)))
+       memset(&devc->trigger, 0, sizeof(devc->trigger));
+       trigger = sr_session_trigger_get(sdi->session);
+       if (!trigger)
                return SR_OK;
 
        trigger_set = 0;
@@ -949,24 +1083,22 @@ SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
                stage = l->data;
                for (m = stage->matches; m; m = m->next) {
                        match = m->data;
+                       /* Ignore disabled channels with a trigger. */
                        if (!match->channel->enabled)
-                               /* Ignore disabled channels with a trigger. */
                                continue;
-                       channelbit = 1 << (match->channel->index);
+                       channelbit = 1 << match->channel->index;
                        if (devc->samplerate >= SR_MHZ(100)) {
                                /* Fast trigger support. */
                                if (trigger_set) {
-                                       sr_err("Only a single pin trigger is "
-                                                       "supported in 100 and 200MHz mode.");
+                                       sr_err("100/200MHz modes limited to single trigger pin.");
                                        return SR_ERR;
                                }
-                               if (match->match == SR_TRIGGER_FALLING)
+                               if (match->match == SR_TRIGGER_FALLING) {
                                        devc->trigger.fallingmask |= channelbit;
-                               else if (match->match == SR_TRIGGER_RISING)
+                               } else if (match->match == SR_TRIGGER_RISING) {
                                        devc->trigger.risingmask |= channelbit;
-                               else {
-                                       sr_err("Only rising/falling trigger is "
-                                                       "supported in 100 and 200MHz mode.");
+                               } else {
+                                       sr_err("100/200MHz modes limited to edge trigger.");
                                        return SR_ERR;
                                }
 
@@ -993,8 +1125,7 @@ SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
                                 * does not permit ORed triggers.
                                 */
                                if (trigger_set > 1) {
-                                       sr_err("Only 1 rising/falling trigger "
-                                                  "is supported.");
+                                       sr_err("Limited to 1 edge trigger.");
                                        return SR_ERR;
                                }
                        }
@@ -1006,15 +1137,18 @@ SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
 
 /* Software trigger to determine exact trigger position. */
 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
-                             struct sigma_trigger *t)
+       struct sigma_trigger *t)
 {
+       const uint8_t *rdptr;
        int i;
-       uint16_t sample = 0;
+       uint16_t sample;
 
+       rdptr = samples;
+       sample = 0;
        for (i = 0; i < 8; i++) {
                if (i > 0)
                        last_sample = sample;
-               sample = samples[2 * i] | (samples[2 * i + 1] << 8);
+               sample = read_u16le_inc(&rdptr);
 
                /* Simple triggers. */
                if ((sample & t->simplemask) != t->simplevalue)
@@ -1084,7 +1218,7 @@ static int check_and_submit_sample(struct dev_context *devc,
  */
 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
 {
-       return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
+       return read_u16le((const uint8_t *)&cluster->timestamp);
 }
 
 /*
@@ -1092,13 +1226,7 @@ static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
  */
 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
 {
-       uint16_t sample;
-
-       sample = 0;
-       sample |= cl->samples[idx].sample_lo << 0;
-       sample |= cl->samples[idx].sample_hi << 8;
-       sample = (sample >> 8) | (sample << 8);
-       return sample;
+       return read_u16le((const uint8_t *)&cl->samples[idx]);
 }
 
 /*
@@ -1167,8 +1295,9 @@ static void sigma_decode_dram_cluster(struct dev_context *devc,
        tsdiff = ts - ss->lastts;
        if (tsdiff > 0) {
                size_t count;
+               sample = ss->lastsample;
                count = tsdiff * devc->samples_per_event;
-               (void)check_and_submit_sample(devc, ss->lastsample, count, FALSE);
+               (void)check_and_submit_sample(devc, sample, count, FALSE);
        }
        ss->lastts = ts + EVENTS_PER_CLUSTER;
 
@@ -1264,18 +1393,16 @@ static int download_capture(struct sr_dev_inst *sdi)
 
        struct dev_context *devc;
        struct sigma_dram_line *dram_line;
-       int bufsz;
        uint32_t stoppos, triggerpos;
        uint8_t modestatus;
        uint32_t i;
        uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
        uint32_t dl_first_line, dl_line;
-       uint32_t dl_events_in_line;
+       uint32_t dl_events_in_line, trigger_event;
        uint32_t trg_line, trg_event;
        int ret;
 
        devc = sdi->priv;
-       dl_events_in_line = EVENTS_PER_ROW;
 
        sr_info("Downloading sample data.");
        devc->state.state = SIGMA_DOWNLOAD;
@@ -1286,30 +1413,35 @@ static int download_capture(struct sr_dev_inst *sdi)
         * clusters to DRAM regardless of whether pin state changes) and
         * raise the POSTTRIGGERED flag.
         */
-       sigma_set_register(WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN, devc);
+       modestatus = WMR_FORCESTOP | WMR_SDRAMWRITEEN;
+       ret = sigma_set_register(devc, WRITE_MODE, modestatus);
+       if (ret != SR_OK)
+               return ret;
        do {
-               if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
-                       sr_err("failed while waiting for RMR_POSTTRIGGERED bit");
+               ret = sigma_read_register(devc, READ_MODE,
+                       &modestatus, sizeof(modestatus));
+               if (ret != SR_OK) {
+                       sr_err("Could not poll for post-trigger state.");
                        return FALSE;
                }
        } while (!(modestatus & RMR_POSTTRIGGERED));
 
        /* Set SDRAM Read Enable. */
-       sigma_set_register(WRITE_MODE, WMR_SDRAMREADEN, devc);
-
-       /* Get the current position. */
-       sigma_read_pos(&stoppos, &triggerpos, devc);
+       ret = sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
+       if (ret != SR_OK)
+               return ret;
 
-       /* Check if trigger has fired. */
-       if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
-               sr_err("failed to read READ_MODE register");
+       /* Get the current position. Check if trigger has fired. */
+       ret = sigma_read_pos(devc, &stoppos, &triggerpos, &modestatus);
+       if (ret != SR_OK) {
+               sr_err("Could not query capture positions/state.");
                return FALSE;
        }
        trg_line = ~0;
        trg_event = ~0;
        if (modestatus & RMR_TRIGGERED) {
-               trg_line = triggerpos >> 9;
-               trg_event = triggerpos & 0x1ff;
+               trg_line = triggerpos >> ROW_SHIFT;
+               trg_event = triggerpos & ROW_MASK;
        }
 
        /*
@@ -1344,10 +1476,10 @@ static int download_capture(struct sr_dev_inst *sdi)
 
                dl_line = dl_first_line + dl_lines_done;
                dl_line %= ROW_COUNT;
-               bufsz = sigma_read_dram(dl_line, dl_lines_curr,
-                                       (uint8_t *)dram_line, devc);
-               /* TODO: Check bufsz. For now, just avoid compiler warnings. */
-               (void)bufsz;
+               ret = sigma_read_dram(devc, dl_line, dl_lines_curr,
+                       (uint8_t *)dram_line);
+               if (ret != SR_OK)
+                       return FALSE;
 
                /* This is the first DRAM line, so find the initial timestamp. */
                if (dl_lines_done == 0) {
@@ -1357,12 +1489,13 @@ static int download_capture(struct sr_dev_inst *sdi)
                }
 
                for (i = 0; i < dl_lines_curr; i++) {
-                       uint32_t trigger_event = ~0;
-                       /* The last "DRAM line" can be only partially full. */
+                       /* The last "DRAM line" need not span its full length. */
+                       dl_events_in_line = EVENTS_PER_ROW;
                        if (dl_lines_done + i == dl_lines_total - 1)
-                               dl_events_in_line = stoppos & 0x1ff;
+                               dl_events_in_line = stoppos & ROW_MASK;
 
                        /* Test if the trigger happened on this line. */
+                       trigger_event = ~0;
                        if (dl_lines_done + i == trg_line)
                                trigger_event = trg_event;
 
@@ -1438,7 +1571,7 @@ static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
                entry[i] = 0xffff;
 
                /* For each bit in LUT. */
-               for (j = 0; j < 16; j++)
+               for (j = 0; j < 16; j++) {
 
                        /* For each channel in quad. */
                        for (k = 0; k < 4; k++) {
@@ -1449,17 +1582,18 @@ static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
                                                        (!(j & (1 << k)))))
                                        entry[i] &= ~(1 << j);
                        }
+               }
        }
 }
 
 /* Add a logical function to LUT mask. */
 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
-                                int index, int neg, uint16_t *mask)
+       int index, int neg, uint16_t *mask)
 {
        int i, j;
        int x[2][2], tmp, a, b, aset, bset, rset;
 
-       memset(x, 0, 4 * sizeof(int));
+       memset(x, 0, sizeof(x));
 
        /* Trigger detect condition. */
        switch (oper) {
@@ -1539,12 +1673,14 @@ static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
  * simple pin change and state triggers. Only two transitions (rise/fall) can be
  * set at any time, but a full mask and value can be set (0/1).
  */
-SR_PRIV int sigma_build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
+SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
+       struct triggerlut *lut)
 {
        int i,j;
-       uint16_t masks[2] = { 0, 0 };
+       uint16_t masks[2];
 
-       memset(lut, 0, sizeof(struct triggerlut));
+       memset(lut, 0, sizeof(*lut));
+       memset(&masks, 0, sizeof(masks));
 
        /* Constant for simple triggers. */
        lut->m4 = 0xa000;