]> sigrok.org Git - libsigrok.git/blobdiff - src/hardware/kingst-la2016/protocol.c
kingst-la2016: use a pool of USB bulk transfers, speedup download
[libsigrok.git] / src / hardware / kingst-la2016 / protocol.c
index dc1a24a5193b6f0a96933e9f15443480b0eb2c5b..36625258e4819038c45f0a5a632b6ccdf6c74938 100644 (file)
@@ -1,6 +1,7 @@
 /*
  * This file is part of the libsigrok project.
  *
+ * Copyright (C) 2022 Gerhard Sittig <gerhard.sittig@gmx.net>
  * Copyright (C) 2020 Florian Schmidt <schmidt_florian@gmx.de>
  * Copyright (C) 2013 Marcus Comstedt <marcus@mc.pp.se>
  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
@@ -80,11 +81,16 @@ static const struct kingst_model models[] = {
 #define REG_CAPT_MODE  0x03    /* Write 0x00 capture to SDRAM, 0x01 streaming. */
 #define REG_BULK       0x08    /* Write start addr, byte count to download samples. */
 #define REG_SAMPLING   0x10    /* Write capture config, read capture SDRAM location. */
-#define REG_TRIGGER    0x20    /* write level and edge trigger config. */
+#define REG_TRIGGER    0x20    /* Write level and edge trigger config. */
+#define REG_UNKNOWN_30 0x30
 #define REG_THRESHOLD  0x68    /* Write PWM config to setup input threshold DAC. */
 #define REG_PWM1       0x70    /* Write config for user PWM1. */
 #define REG_PWM2       0x78    /* Write config for user PWM2. */
 
+/* Bit patterns to write to REG_CAPT_MODE. */
+#define CAPTMODE_TO_RAM        0x00
+#define CAPTMODE_STREAM        0x01
+
 /* Bit patterns to write to REG_RUN, setup run mode. */
 #define RUNMODE_HALT   0x00
 #define RUNMODE_RUN    0x03
@@ -95,10 +101,6 @@ static const struct kingst_model models[] = {
 #define RUNSTATE_TRGD_BIT      (1UL << 2)
 #define RUNSTATE_POST_BIT      (1UL << 3)
 
-/* Properties related to the layout of capture data downloads. */
-#define NUM_PACKETS_IN_CHUNK   5
-#define TRANSFER_PACKET_LENGTH 16
-
 static int ctrl_in(const struct sr_dev_inst *sdi,
        uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
        void *data, uint16_t wLength)
@@ -118,7 +120,7 @@ static int ctrl_in(const struct sr_dev_inst *sdi,
                        libusb_error_name(ret));
                sr_err("Cannot read %d bytes from USB: %s.",
                        wLength, libusb_error_name(ret));
-               return SR_ERR;
+               return SR_ERR_IO;
        }
 
        return SR_OK;
@@ -143,12 +145,62 @@ static int ctrl_out(const struct sr_dev_inst *sdi,
                        libusb_error_name(ret));
                sr_err("Cannot write %d bytes to USB: %s.",
                        wLength, libusb_error_name(ret));
-               return SR_ERR;
+               return SR_ERR_IO;
        }
 
        return SR_OK;
 }
 
+/* HACK Experiment to spot FPGA registers of interest. */
+static void la2016_dump_fpga_registers(const struct sr_dev_inst *sdi,
+       const char *caption, size_t reg_lower, size_t reg_upper)
+{
+       static const size_t dump_chunk_len = 16;
+
+       size_t rdlen;
+       uint8_t rdbuf[0x80 - 0x00];     /* Span all FPGA registers. */
+       const uint8_t *rdptr;
+       int ret;
+       size_t dump_addr, indent, dump_len;
+       GString *txt;
+
+       if (sr_log_loglevel_get() < SR_LOG_SPEW)
+               return;
+
+       if (!reg_lower && !reg_upper) {
+               reg_lower = 0;
+               reg_upper = sizeof(rdbuf);
+       }
+       if (reg_upper - reg_lower > sizeof(rdbuf))
+               reg_upper = sizeof(rdbuf) - reg_lower;
+
+       rdlen = reg_upper - reg_lower;
+       ret = ctrl_in(sdi, CMD_FPGA_SPI, reg_lower, 0, rdbuf, rdlen);
+       if (ret != SR_OK) {
+               sr_err("Cannot get registers space.");
+               return;
+       }
+       rdptr = rdbuf;
+
+       sr_spew("FPGA registers dump: %s", caption ? : "for fun");
+       dump_addr = reg_lower;
+       while (rdlen) {
+               dump_len = rdlen;
+               indent = dump_addr % dump_chunk_len;
+               if (dump_len > dump_chunk_len)
+                       dump_len = dump_chunk_len;
+               if (dump_len + indent > dump_chunk_len)
+                       dump_len = dump_chunk_len - indent;
+               txt = sr_hexdump_new(rdptr, dump_len);
+               sr_spew("  %04zx  %*s%s",
+                       dump_addr, (int)(3 * indent), "", txt->str);
+               sr_hexdump_free(txt);
+               dump_addr += dump_len;
+               rdptr += dump_len;
+               rdlen -= dump_len;
+       }
+}
+
 /*
  * Check the necessity for FPGA bitstream upload, because another upload
  * would take some 600ms which is undesirable after program startup. Try
@@ -168,14 +220,15 @@ static int ctrl_out(const struct sr_dev_inst *sdi,
 static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
 {
        uint8_t init_rsp;
+       uint8_t buff[REG_PWM_EN - REG_RUN]; /* Larger of REG_RUN, REG_PWM_EN. */
        int ret;
        uint16_t run_state;
        uint8_t pwm_en;
        size_t read_len;
-       uint8_t buff[sizeof(run_state)];
        const uint8_t *rdptr;
 
        sr_dbg("Checking operation of the FPGA bitstream.");
+       la2016_dump_fpga_registers(sdi, "bitstream check", 0, 0);
 
        init_rsp = ~0;
        ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
@@ -269,7 +322,7 @@ static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
                        if (len < 0) {
                                sr_err("Cannot read FPGA bitstream.");
                                sr_resource_close(drvc->sr_ctx, &bitstream);
-                               return SR_ERR;
+                               return SR_ERR_IO;
                        }
                } else {
                        /*  Zero-pad until 'zero_pad_to'. */
@@ -286,13 +339,13 @@ static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
                if (ret != 0) {
                        sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
                                pos, (int)len, libusb_error_name(ret));
-                       ret = SR_ERR;
+                       ret = SR_ERR_IO;
                        break;
                }
                if (act_len != len) {
                        sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
                                pos, (int)len, act_len);
-                       ret = SR_ERR;
+                       ret = SR_ERR_IO;
                        break;
                }
                pos += len;
@@ -319,7 +372,7 @@ static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
        if (resp != 0) {
                sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
                        resp);
-               return SR_ERR;
+               return SR_ERR_DATA;
        }
        g_usleep(30 * 1000);
 
@@ -335,14 +388,11 @@ static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
 
 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
 {
-       struct dev_context *devc;
        int ret;
        uint16_t duty_R79, duty_R56;
-       uint8_t buf[2 * sizeof(uint16_t)];
+       uint8_t buf[REG_PWM1 - REG_THRESHOLD]; /* Width of REG_THRESHOLD. */
        uint8_t *wrptr;
 
-       devc = sdi->priv;
-
        /* Clamp threshold setting to valid range for LA2016. */
        if (voltage > LA2016_THR_VOLTAGE_MAX) {
                voltage = LA2016_THR_VOLTAGE_MAX;
@@ -391,7 +441,6 @@ static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
                sr_err("Cannot set threshold voltage %.2fV.", voltage);
                return ret;
        }
-       devc->threshold_voltage = voltage;
 
        return SR_OK;
 }
@@ -495,9 +544,9 @@ static int set_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
        return SR_OK;
 }
 
-static uint16_t get_channels_mask(const struct sr_dev_inst *sdi)
+static uint32_t get_channels_mask(const struct sr_dev_inst *sdi)
 {
-       uint16_t channels;
+       uint32_t channels;
        GSList *l;
        struct sr_channel *ch;
 
@@ -519,8 +568,8 @@ static int set_trigger_config(const struct sr_dev_inst *sdi)
        struct dev_context *devc;
        struct sr_trigger *trigger;
        struct trigger_cfg {
-               uint32_t channels;
-               uint32_t enabled;
+               uint32_t channels;      /* Actually: Enabled channels? */
+               uint32_t enabled;       /* Actually: Triggering channels? */
                uint32_t level;
                uint32_t high_or_falling;
        } cfg;
@@ -528,9 +577,9 @@ static int set_trigger_config(const struct sr_dev_inst *sdi)
        GSList *channel;
        struct sr_trigger_stage *stage1;
        struct sr_trigger_match *match;
-       uint16_t ch_mask;
+       uint32_t ch_mask;
        int ret;
-       uint8_t buf[4 * sizeof(uint32_t)];
+       uint8_t buf[REG_UNKNOWN_30 - REG_TRIGGER]; /* Width of REG_TRIGGER. */
        uint8_t *wrptr;
 
        devc = sdi->priv;
@@ -545,7 +594,7 @@ static int set_trigger_config(const struct sr_dev_inst *sdi)
                stage1 = stages->data;
                if (stages->next) {
                        sr_err("Only one trigger stage supported for now.");
-                       return SR_ERR;
+                       return SR_ERR_ARG;
                }
                channel = stage1->matches;
                while (channel) {
@@ -564,7 +613,7 @@ static int set_trigger_config(const struct sr_dev_inst *sdi)
                        case SR_TRIGGER_RISING:
                                if ((cfg.enabled & ~cfg.level)) {
                                        sr_err("Device only supports one edge trigger.");
-                                       return SR_ERR;
+                                       return SR_ERR_ARG;
                                }
                                cfg.level &= ~ch_mask;
                                cfg.high_or_falling &= ~ch_mask;
@@ -572,21 +621,21 @@ static int set_trigger_config(const struct sr_dev_inst *sdi)
                        case SR_TRIGGER_FALLING:
                                if ((cfg.enabled & ~cfg.level)) {
                                        sr_err("Device only supports one edge trigger.");
-                                       return SR_ERR;
+                                       return SR_ERR_ARG;
                                }
                                cfg.level &= ~ch_mask;
                                cfg.high_or_falling |= ch_mask;
                                break;
                        default:
                                sr_err("Unknown trigger condition.");
-                               return SR_ERR;
+                               return SR_ERR_ARG;
                        }
                        cfg.enabled |= ch_mask;
                        channel = channel->next;
                }
        }
        sr_dbg("Set trigger config: "
-               "channels 0x%04x, trigger-enabled 0x%04x, "
+               "enabled-channels 0x%04x, triggering-channels 0x%04x, "
                "level-triggered 0x%04x, high/falling 0x%04x.",
                cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
 
@@ -626,19 +675,19 @@ static int set_sample_config(const struct sr_dev_inst *sdi)
 
        devc = sdi->priv;
 
-       if (devc->cur_samplerate > devc->model->samplerate) {
+       if (devc->samplerate > devc->model->samplerate) {
                sr_err("Too high a sample rate: %" PRIu64 ".",
-                       devc->cur_samplerate);
+                       devc->samplerate);
                return SR_ERR_ARG;
        }
        min_samplerate = devc->model->samplerate;
        min_samplerate /= 65536;
-       if (devc->cur_samplerate < min_samplerate) {
+       if (devc->samplerate < min_samplerate) {
                sr_err("Too low a sample rate: %" PRIu64 ".",
-                       devc->cur_samplerate);
+                       devc->samplerate);
                return SR_ERR_ARG;
        }
-       divider_u16 = devc->model->samplerate / devc->cur_samplerate;
+       divider_u16 = devc->model->samplerate / devc->samplerate;
        eff_samplerate = devc->model->samplerate / divider_u16;
 
        ret = sr_sw_limits_get_remain(&devc->sw_limits,
@@ -770,7 +819,7 @@ static uint16_t run_state(const struct sr_dev_inst *sdi)
 
        int ret;
        uint16_t state;
-       uint8_t buff[sizeof(state)];
+       uint8_t buff[REG_PWM_EN - REG_RUN]; /* Width of REG_RUN. */
        const uint8_t *rdptr;
        const char *label;
 
@@ -835,7 +884,7 @@ static int get_capture_info(const struct sr_dev_inst *sdi)
 {
        struct dev_context *devc;
        int ret;
-       uint8_t buf[3 * sizeof(uint32_t)];
+       uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
        const uint8_t *rdptr;
 
        devc = sdi->priv;
@@ -857,55 +906,202 @@ static int get_capture_info(const struct sr_dev_inst *sdi)
                devc->info.n_rep_packets_before_trigger,
                devc->info.write_pos, devc->info.write_pos);
 
-       if (devc->info.n_rep_packets % NUM_PACKETS_IN_CHUNK) {
-               sr_warn("Unexpected packets count %lu, not a multiple of %d.",
+       if (devc->info.n_rep_packets % devc->packets_per_chunk) {
+               sr_warn("Unexpected packets count %lu, not a multiple of %lu.",
                        (unsigned long)devc->info.n_rep_packets,
-                       NUM_PACKETS_IN_CHUNK);
+                       (unsigned long)devc->packets_per_chunk);
        }
 
        return SR_OK;
 }
 
 SR_PRIV int la2016_upload_firmware(const struct sr_dev_inst *sdi,
-       struct sr_context *sr_ctx, libusb_device *dev, uint16_t product_id)
+       struct sr_context *sr_ctx, libusb_device *dev, gboolean skip_upload)
 {
        struct dev_context *devc;
-       char *fw_file;
+       uint16_t pid;
+       char *fw;
        int ret;
 
        devc = sdi ? sdi->priv : NULL;
+       if (!devc || !devc->usb_pid)
+               return SR_ERR_ARG;
+       pid = devc->usb_pid;
 
-       fw_file = g_strdup_printf(MCU_FWFILE_FMT, product_id);
-       sr_info("USB PID %04hx, MCU firmware '%s'.", product_id, fw_file);
+       fw = g_strdup_printf(MCU_FWFILE_FMT, pid);
+       sr_info("USB PID %04hx, MCU firmware '%s'.", pid, fw);
+       devc->mcu_firmware = g_strdup(fw);
 
-       ret = ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
-       if (ret != SR_OK) {
-               g_free(fw_file);
+       if (skip_upload)
+               ret = SR_OK;
+       else
+               ret = ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw);
+       g_free(fw);
+       if (ret != SR_OK)
                return ret;
+
+       return SR_OK;
+}
+
+static void LIBUSB_CALL receive_transfer(struct libusb_transfer *xfer);
+
+static void la2016_usbxfer_release_cb(gpointer p)
+{
+       struct libusb_transfer *xfer;
+
+       xfer = p;
+       g_free(xfer->buffer);
+       libusb_free_transfer(xfer);
+}
+
+static int la2016_usbxfer_release(const struct sr_dev_inst *sdi)
+{
+       struct dev_context *devc;
+
+       devc = sdi ? sdi->priv : NULL;
+       if (!devc)
+               return SR_ERR_ARG;
+
+       /* Release all USB transfers. */
+       g_slist_free_full(devc->transfers, la2016_usbxfer_release_cb);
+       devc->transfers = NULL;
+
+       return SR_OK;
+}
+
+static int la2016_usbxfer_allocate(const struct sr_dev_inst *sdi)
+{
+       struct dev_context *devc;
+       size_t bufsize, xfercount;
+       uint8_t *buffer;
+       struct libusb_transfer *xfer;
+
+       devc = sdi ? sdi->priv : NULL;
+       if (!devc)
+               return SR_ERR_ARG;
+
+       /* Transfers were already allocated before? */
+       if (devc->transfers)
+               return SR_OK;
+
+       /*
+        * Allocate all USB transfers and their buffers. Arrange for a
+        * buffer size which is within the device's capabilities, and
+        * is a multiple of the USB endpoint's size, to make use of the
+        * RAW_IO performance feature.
+        *
+        * Implementation detail: The LA2016_USB_BUFSZ value happens
+        * to match all those constraints. No additional arithmetics is
+        * required in this location.
+        */
+       bufsize = LA2016_USB_BUFSZ;
+       xfercount = LA2016_USB_XFER_COUNT;
+       while (xfercount--) {
+               buffer = g_try_malloc(bufsize);
+               if (!buffer) {
+                       sr_err("Cannot allocate USB transfer buffer.");
+                       return SR_ERR_MALLOC;
+               }
+               xfer = libusb_alloc_transfer(0);
+               if (!xfer) {
+                       sr_err("Cannot allocate USB transfer.");
+                       g_free(buffer);
+                       return SR_ERR_MALLOC;
+               }
+               xfer->buffer = buffer;
+               devc->transfers = g_slist_append(devc->transfers, xfer);
+       }
+       devc->transfer_bufsize = bufsize;
+
+       return SR_OK;
+}
+
+static int la2016_usbxfer_cancel_all(const struct sr_dev_inst *sdi)
+{
+       struct dev_context *devc;
+       GSList *l;
+       struct libusb_transfer *xfer;
+
+       devc = sdi ? sdi->priv : NULL;
+       if (!devc)
+               return SR_ERR_ARG;
+
+       /* Unconditionally cancel the transfer. Ignore errors. */
+       for (l = devc->transfers; l; l = l->next) {
+               xfer = l->data;
+               if (!xfer)
+                       continue;
+               libusb_cancel_transfer(xfer);
        }
 
-       if (devc) {
-               devc->mcu_firmware = fw_file;
-               fw_file = NULL;
+       return SR_OK;
+}
+
+static int la2016_usbxfer_resubmit(const struct sr_dev_inst *sdi,
+       struct libusb_transfer *xfer)
+{
+       struct dev_context *devc;
+       struct sr_usb_dev_inst *usb;
+       libusb_transfer_cb_fn cb;
+       int ret;
+
+       devc = sdi ? sdi->priv : NULL;
+       usb = sdi ? sdi->conn : NULL;
+       if (!devc || !usb)
+               return SR_ERR_ARG;
+
+       if (!xfer)
+               return SR_ERR_ARG;
+
+       cb = receive_transfer;
+       libusb_fill_bulk_transfer(xfer, usb->devhdl,
+               USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
+               xfer->buffer, devc->transfer_bufsize,
+               cb, (void *)sdi, CAPTURE_TIMEOUT_MS);
+       ret = libusb_submit_transfer(xfer);
+       if (ret != 0) {
+               sr_err("Cannot submit USB transfer: %s.",
+                       libusb_error_name(ret));
+               return SR_ERR_IO;
        }
-       g_free(fw_file);
 
        return SR_OK;
 }
 
-SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
+static int la2016_usbxfer_submit_all(const struct sr_dev_inst *sdi)
 {
        struct dev_context *devc;
+       GSList *l;
+       struct libusb_transfer *xfer;
        int ret;
-       uint8_t cmd;
 
-       devc = sdi->priv;
+       devc = sdi ? sdi->priv : NULL;
+       if (!devc)
+               return SR_ERR_ARG;
+
+       for (l = devc->transfers; l; l = l->next) {
+               xfer = l->data;
+               if (!xfer)
+                       return SR_ERR_ARG;
+               ret = la2016_usbxfer_resubmit(sdi, xfer);
+               if (ret != SR_OK)
+                       return ret;
+       }
+
+       return SR_OK;
+}
+
+SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi,
+       double voltage)
+{
+       int ret;
+       uint8_t cmd;
 
-       ret = set_threshold_voltage(sdi, devc->threshold_voltage);
+       ret = set_threshold_voltage(sdi, voltage);
        if (ret != SR_OK)
                return ret;
 
-       cmd = 0;
+       cmd = CAPTMODE_TO_RAM;
        ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd));
        if (ret != SR_OK) {
                sr_err("Cannot send command to stop sampling.");
@@ -927,6 +1123,10 @@ SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
 {
        int ret;
 
+       ret = la2016_usbxfer_allocate(sdi);
+       if (ret != SR_OK)
+               return ret;
+
        ret = set_run_mode(sdi, RUNMODE_RUN);
        if (ret != SR_OK)
                return ret;
@@ -948,39 +1148,33 @@ static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
 {
        int ret;
-       struct dev_context *devc;
 
        ret = la2016_stop_acquisition(sdi);
        if (ret != SR_OK)
                return ret;
 
-       devc = sdi ? sdi->priv : NULL;
-       if (devc && devc->transfer)
-               libusb_cancel_transfer(devc->transfer);
+       (void)la2016_usbxfer_cancel_all(sdi);
 
        return SR_OK;
 }
 
-static int la2016_start_download(const struct sr_dev_inst *sdi,
-       libusb_transfer_cb_fn cb)
+static int la2016_start_download(const struct sr_dev_inst *sdi)
 {
        struct dev_context *devc;
-       struct sr_usb_dev_inst *usb;
        int ret;
-       uint8_t wrbuf[2 * sizeof(uint32_t)];
+       uint8_t wrbuf[REG_SAMPLING - REG_BULK]; /* Width of REG_BULK. */
        uint8_t *wrptr;
-       uint32_t to_read;
-       uint8_t *buffer;
 
        devc = sdi->priv;
-       usb = sdi->conn;
 
        ret = get_capture_info(sdi);
        if (ret != SR_OK)
                return ret;
 
-       devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
-       devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
+       devc->n_transfer_packets_to_read = devc->info.n_rep_packets;
+       devc->n_transfer_packets_to_read /= devc->packets_per_chunk;
+       devc->n_bytes_to_read = devc->n_transfer_packets_to_read;
+       devc->n_bytes_to_read *= TRANSFER_PACKET_LENGTH;
        devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
        devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
 
@@ -1002,41 +1196,17 @@ static int la2016_start_download(const struct sr_dev_inst *sdi,
                sr_err("Cannot send USB bulk config.");
                return ret;
        }
-       ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0);
+
+       ret = la2016_usbxfer_submit_all(sdi);
        if (ret != SR_OK) {
-               sr_err("Cannot unblock USB bulk transfers.");
+               sr_err("Cannot submit USB bulk transfers.");
                return ret;
        }
 
-       /*
-        * Pick a buffer size for all USB transfers. The buffer size
-        * must be a multiple of the endpoint packet size. And cannot
-        * exceed a maximum value.
-        */
-       to_read = devc->n_bytes_to_read;
-       if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
-               to_read = LA2016_USB_BUFSZ;
-       else /* One transfer. */
-               to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
-       buffer = g_try_malloc(to_read);
-       if (!buffer) {
-               sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
-               sr_err("Cannot allocate buffer for USB bulk transfer.");
-               return SR_ERR_MALLOC;
-       }
-
-       devc->transfer = libusb_alloc_transfer(0);
-       libusb_fill_bulk_transfer(devc->transfer,
-               usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
-               buffer, to_read, cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
-
-       ret = libusb_submit_transfer(devc->transfer);
-       if (ret != 0) {
-               sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
-               libusb_free_transfer(devc->transfer);
-               devc->transfer = NULL;
-               g_free(buffer);
-               return SR_ERR;
+       ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0);
+       if (ret != SR_OK) {
+               sr_err("Cannot start USB bulk transfers.");
+               return ret;
        }
 
        return SR_OK;
@@ -1048,12 +1218,12 @@ static int la2016_start_download(const struct sr_dev_inst *sdi,
  * contain a number of samples (8bit repeat count per 16bit sample data).
  */
 static void send_chunk(struct sr_dev_inst *sdi,
-       const uint8_t *packets, size_t num_xfers)
+       const uint8_t *data_buffer, size_t data_length)
 {
        struct dev_context *devc;
-       size_t num_pkts;
+       size_t num_xfers, num_pkts;
        const uint8_t *rp;
-       uint16_t sample_value;
+       uint32_t sample_value;
        size_t repetitions;
        uint8_t sample_buff[sizeof(sample_value)];
 
@@ -1068,17 +1238,34 @@ static void send_chunk(struct sr_dev_inst *sdi,
                devc->trigger_marked = TRUE;
        }
 
-       rp = packets;
+       /*
+        * Adjust the number of remaining bytes to read from the device
+        * before the processing of the currently received chunk affects
+        * the variable which holds the number of received bytes.
+        */
+       if (data_length > devc->n_bytes_to_read)
+               devc->n_bytes_to_read = 0;
+       else
+               devc->n_bytes_to_read -= data_length;
+
+       /* Process the received chunk of capture data. */
+       sample_value = 0;
+       rp = data_buffer;
+       num_xfers = data_length / TRANSFER_PACKET_LENGTH;
        while (num_xfers--) {
-               num_pkts = NUM_PACKETS_IN_CHUNK;
+               num_pkts = devc->packets_per_chunk;
                while (num_pkts--) {
 
-                       sample_value = read_u16le_inc(&rp);
+                       /* TODO Verify 32channel layout. */
+                       if (devc->model->channel_count == 32)
+                               sample_value = read_u32le_inc(&rp);
+                       else if (devc->model->channel_count == 16)
+                               sample_value = read_u16le_inc(&rp);
                        repetitions = read_u8_inc(&rp);
 
                        devc->total_samples += repetitions;
 
-                       write_u16le(sample_buff, sample_value);
+                       write_u32le(sample_buff, sample_value);
                        feed_queue_logic_submit(devc->feed_queue,
                                sample_buff, repetitions);
                        sr_sw_limits_update_samples_read(&devc->sw_limits,
@@ -1090,13 +1277,25 @@ static void send_chunk(struct sr_dev_inst *sdi,
                                        devc->trigger_marked = TRUE;
                                        sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
                                                devc->total_samples,
-                                               (double)devc->total_samples / devc->cur_samplerate * 1e3);
+                                               (double)devc->total_samples / devc->samplerate * 1e3);
                                }
                        }
                }
                (void)read_u8_inc(&rp); /* Skip sequence number. */
        }
 
+       /*
+        * Check for several conditions which shall terminate the
+        * capture data download: When the amount of capture data in
+        * the device is exhausted. When the user specified samples
+        * count limit is reached.
+        */
+       if (!devc->n_bytes_to_read) {
+               devc->download_finished = TRUE;
+       } else {
+               sr_dbg("%" PRIu32 " more bytes to download from the device.",
+                       devc->n_bytes_to_read);
+       }
        if (!devc->download_finished && sr_sw_limits_check(&devc->sw_limits)) {
                sr_dbg("Acquisition limit reached.");
                devc->download_finished = TRUE;
@@ -1112,14 +1311,13 @@ static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
 {
        struct sr_dev_inst *sdi;
        struct dev_context *devc;
-       struct sr_usb_dev_inst *usb;
-       size_t num_xfers;
+       gboolean was_cancelled;
        int ret;
 
        sdi = transfer->user_data;
        devc = sdi->priv;
-       usb = sdi->conn;
 
+       was_cancelled = transfer->status == LIBUSB_TRANSFER_CANCELLED;
        sr_dbg("receive_transfer(): status %s received %d bytes.",
                libusb_error_name(transfer->status), transfer->actual_length);
        /*
@@ -1129,36 +1327,19 @@ static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
         * or exhausting the device's captured data will complete the
         * sample data download.
         */
-       num_xfers = transfer->actual_length / TRANSFER_PACKET_LENGTH;
-       send_chunk(sdi, transfer->buffer, num_xfers);
-
-       devc->n_bytes_to_read -= transfer->actual_length;
-       if (devc->n_bytes_to_read) {
-               uint32_t to_read = devc->n_bytes_to_read;
-               /*
-                * Determine read size for the next USB transfer. Make
-                * the buffer size a multiple of the endpoint packet
-                * size. Don't exceed a maximum value.
-                */
-               if (to_read >= LA2016_USB_BUFSZ)
-                       to_read = LA2016_USB_BUFSZ;
-               else
-                       to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
-               libusb_fill_bulk_transfer(transfer,
-                       usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
-                       transfer->buffer, to_read,
-                       receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
-
-               ret = libusb_submit_transfer(transfer);
-               if (ret == 0)
+       send_chunk(sdi, transfer->buffer, transfer->actual_length);
+
+       /*
+        * Re-submit completed transfers (regardless of timeout or
+        * data reception), unless the transfer was cancelled when
+        * the acquisition was terminated or has completed.
+        */
+       if (!was_cancelled && !devc->download_finished) {
+               ret = la2016_usbxfer_resubmit(sdi, transfer);
+               if (ret == SR_OK)
                        return;
-               sr_err("Cannot submit another USB transfer: %s.",
-                       libusb_error_name(ret));
+               devc->download_finished = TRUE;
        }
-
-       g_free(transfer->buffer);
-       libusb_free_transfer(transfer);
-       devc->download_finished = TRUE;
 }
 
 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
@@ -1197,9 +1378,12 @@ SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
                devc->trigger_marked = FALSE;
                devc->total_samples = 0;
 
+               la2016_dump_fpga_registers(sdi, "acquisition complete", 0, 0);
+
                /* Initiate the download of acquired sample data. */
                std_session_send_df_frame_begin(sdi);
-               ret = la2016_start_download(sdi, receive_transfer);
+               devc->frame_begin_sent = TRUE;
+               ret = la2016_start_download(sdi);
                if (ret != SR_OK) {
                        sr_err("Cannot start acquisition data download.");
                        return FALSE;
@@ -1210,7 +1394,7 @@ SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
        }
 
        /* Handle USB reception. Drives sample data download. */
-       tv.tv_sec = tv.tv_usec = 0;
+       memset(&tv, 0, sizeof(tv));
        libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
 
        /* Postprocess completion of sample data download. */
@@ -1219,12 +1403,18 @@ SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
 
                la2016_stop_acquisition(sdi);
                usb_source_remove(sdi->session, drvc->sr_ctx);
-               devc->transfer = NULL;
+
+               la2016_usbxfer_cancel_all(sdi);
+               memset(&tv, 0, sizeof(tv));
+               libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
 
                feed_queue_logic_flush(devc->feed_queue);
                feed_queue_logic_free(devc->feed_queue);
                devc->feed_queue = NULL;
-               std_session_send_df_frame_end(sdi);
+               if (devc->frame_begin_sent) {
+                       std_session_send_df_frame_end(sdi);
+                       devc->frame_begin_sent = FALSE;
+               }
                std_session_send_df_end(sdi);
 
                sr_dbg("Download finished, done post processing.");
@@ -1237,7 +1427,7 @@ SR_PRIV int la2016_identify_device(const struct sr_dev_inst *sdi,
        gboolean show_message)
 {
        struct dev_context *devc;
-       uint8_t buf[8];
+       uint8_t buf[8]; /* Larger size of manuf date and device type magic. */
        size_t rdoff, rdlen;
        const uint8_t *rdptr;
        uint8_t date_yy, date_mm;
@@ -1365,7 +1555,7 @@ SR_PRIV int la2016_identify_device(const struct sr_dev_inst *sdi,
        }
        if (!devc->model) {
                sr_err("Cannot identify as one of the supported models.");
-               return SR_ERR;
+               return SR_ERR_DATA;
        }
 
        return SR_OK;
@@ -1396,8 +1586,8 @@ SR_PRIV int la2016_init_hardware(const struct sr_dev_inst *sdi)
        }
 
        state = run_state(sdi);
-       if (state != 0x85e9) {
-               sr_warn("Unexpected run state, want 0x85e9, got 0x%04x.", state);
+       if ((state & 0xfff0) != 0x85e0) {
+               sr_warn("Unexpected run state, want 0x85eX, got 0x%04x.", state);
        }
 
        ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
@@ -1424,6 +1614,11 @@ SR_PRIV int la2016_deinit_hardware(const struct sr_dev_inst *sdi)
        return SR_OK;
 }
 
+SR_PRIV void la2016_release_resources(const struct sr_dev_inst *sdi)
+{
+       (void)la2016_usbxfer_release(sdi);
+}
+
 SR_PRIV int la2016_write_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
 {
        return set_pwm_config(sdi, idx);