+ const uint8_t *rdptr;
+ int ret;
+
+ wrptr = buf;
+
+ /* Read ID register. */
+ write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(READ_ID));
+ write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(READ_ID));
+ write_u8_inc(&wrptr, REG_READ_ADDR);
+
+ /* Write 0x55 to scratch register, read back. */
+ data_55 = 0x55;
+ write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(WRITE_TEST));
+ write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(WRITE_TEST));
+ write_u8_inc(&wrptr, REG_DATA_LOW | LO4(data_55));
+ write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(data_55));
+ write_u8_inc(&wrptr, REG_READ_ADDR);
+
+ /* Write 0xaa to scratch register, read back. */
+ data_aa = 0xaa;
+ write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(WRITE_TEST));
+ write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(WRITE_TEST));
+ write_u8_inc(&wrptr, REG_DATA_LOW | LO4(data_aa));
+ write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(data_aa));
+ write_u8_inc(&wrptr, REG_READ_ADDR);
+
+ /* Initiate SDRAM initialization in mode register. */
+ mode = WMR_SDRAMINIT;
+ write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(WRITE_MODE));
+ write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(WRITE_MODE));
+ write_u8_inc(&wrptr, REG_DATA_LOW | LO4(mode));
+ write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(mode));
+
+ /*
+ * Send the command sequence which contains 3 READ requests.
+ * Expect to see the corresponding 3 response bytes.
+ */
+ 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;
+}
+
+/*
+ * 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(struct sr_context *ctx, const char *name,
+ uint8_t **bb_cmd, size_t *bb_cmd_size)
+{
+ uint8_t *firmware;
+ size_t file_size;
+ uint8_t *p;
+ size_t l;
+ uint32_t imm;
+ size_t bb_size;
+ uint8_t *bb_stream, *bbs, byte, mask, v;
+
+ /* Retrieve the on-disk firmware file content. */
+ firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
+ &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
+ if (!firmware)
+ return SR_ERR_IO;
+
+ /* Unscramble the file content (XOR with "random" sequence). */
+ p = firmware;
+ l = file_size;
+ imm = 0x3f6df2ab;
+ while (l--) {
+ imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
+ *p++ ^= imm & 0xff;
+ }
+
+ /*
+ * Generate a sequence of bitbang samples. With two samples per
+ * FPGA configuration bit, providing the level for the DIN signal
+ * as well as two edges for CCLK. See Xilinx UG332 for details
+ * ("slave serial" mode).
+ *
+ * Note that CCLK is inverted in hardware. That's why the
+ * respective bit is first set and then cleared in the bitbang
+ * sample sets. So that the DIN level will be stable when the
+ * data gets sampled at the rising CCLK edge, and the signals'
+ * setup time constraint will be met.
+ *
+ * The caller will put the FPGA into download mode, will send
+ * the bitbang samples, and release the allocated memory.
+ */
+ bb_size = file_size * 8 * 2;
+ bb_stream = g_try_malloc(bb_size);
+ if (!bb_stream) {
+ sr_err("Memory allocation failed during firmware upload.");
+ g_free(firmware);
+ return SR_ERR_MALLOC;
+ }
+ bbs = bb_stream;
+ p = firmware;
+ l = file_size;
+ while (l--) {
+ byte = *p++;
+ mask = 0x80;
+ while (mask) {
+ v = (byte & mask) ? BB_PIN_DIN : 0;
+ mask >>= 1;
+ *bbs++ = v | BB_PIN_CCLK;
+ *bbs++ = v;
+ }
+ }
+ g_free(firmware);
+
+ /* The transformation completed successfully, return the result. */
+ *bb_cmd = bb_stream;
+ *bb_cmd_size = bb_size;
+
+ return SR_OK;
+}
+
+static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
+ enum sigma_firmware_idx firmware_idx)
+{
+ int ret;
+ uint8_t *buf;
+ uint8_t pins;
+ size_t buf_size;
+ const char *firmware;
+
+ /* Check for valid firmware file selection. */
+ if (firmware_idx >= ARRAY_SIZE(firmware_files))
+ return SR_ERR_ARG;
+ firmware = firmware_files[firmware_idx];
+ if (!firmware || !*firmware)
+ return SR_ERR_ARG;
+
+ /* Avoid downloading the same firmware multiple times. */
+ if (devc->firmware_idx == firmware_idx) {
+ sr_info("Not uploading firmware file '%s' again.", firmware);
+ return SR_OK;
+ }
+
+ devc->state = SIGMA_CONFIG;
+
+ /* Set the cable to bitbang mode. */
+ ret = ftdi_set_bitmode(&devc->ftdi.ctx, BB_PINMASK, BITMODE_BITBANG);
+ if (ret < 0) {
+ sr_err("Could not setup cable mode for upload: %s",
+ ftdi_get_error_string(&devc->ftdi.ctx));
+ return SR_ERR;
+ }
+ ret = ftdi_set_baudrate(&devc->ftdi.ctx, BB_BITRATE);
+ if (ret < 0) {
+ sr_err("Could not setup bitrate for upload: %s",
+ ftdi_get_error_string(&devc->ftdi.ctx));
+ return SR_ERR;
+ }
+
+ /* Initiate FPGA configuration mode. */
+ ret = sigma_fpga_init_bitbang(devc);
+ 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("Could not prepare file %s for upload.", firmware);
+ return ret;
+ }
+
+ /* Write the FPGA netlist to the cable. */
+ sr_info("Uploading firmware file '%s'.", firmware);
+ 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->ftdi.ctx, 0, BITMODE_RESET);
+ if (ret < 0) {
+ sr_err("Could not setup cable mode after upload: %s",
+ ftdi_get_error_string(&devc->ftdi.ctx));
+ return SR_ERR;
+ }
+ ftdi_usb_purge_buffers(&devc->ftdi.ctx);
+ 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) {
+ sr_err("Hardware response after firmware upload failed.");
+ return ret;
+ }
+
+ /* Keep track of successful firmware download completion. */
+ devc->state = SIGMA_IDLE;
+ devc->firmware_idx = firmware_idx;
+ sr_info("Firmware uploaded.");
+
+ return SR_OK;
+}
+
+/*
+ * The driver supports user specified time or sample count limits. The
+ * device's hardware supports neither, and hardware compression prevents
+ * reliable detection of "fill levels" (currently reached sample counts)
+ * from register values during acquisition. That's why the driver needs
+ * to apply some heuristics:
+ *
+ * - The (optional) sample count limit and the (normalized) samplerate
+ * get mapped to an estimated duration for these samples' acquisition.
+ * - The (optional) time limit gets checked as well. The lesser of the
+ * two limits will terminate the data acquisition phase. The exact
+ * sample count limit gets enforced in session feed submission paths.
+ * - Some slack needs to be given to account for hardware pipelines as
+ * well as late storage of last chunks after compression thresholds
+ * are tripped. The resulting data set will span at least the caller
+ * specified period of time, which shall be perfectly acceptable.
+ *
+ * With RLE compression active, up to 64K sample periods can pass before
+ * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
+ * times that period for good measure, one is not enough to flush the
+ * hardware pipeline (observation from an earlier experiment).
+ */
+SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
+{
+ int ret;
+ GVariant *data;
+ uint64_t user_count, user_msecs;
+ uint64_t worst_cluster_time_ms;
+ uint64_t count_msecs, acquire_msecs;
+
+ sr_sw_limits_init(&devc->limit.acquire);
+
+ /* Get sample count limit, convert to msecs. */
+ ret = sr_sw_limits_config_get(&devc->limit.config,
+ SR_CONF_LIMIT_SAMPLES, &data);
+ if (ret != SR_OK)
+ return ret;
+ user_count = g_variant_get_uint64(data);
+ g_variant_unref(data);
+ count_msecs = 0;
+ if (user_count)
+ count_msecs = 1000 * user_count / devc->clock.samplerate + 1;
+
+ /* Get time limit, which is in msecs. */
+ ret = sr_sw_limits_config_get(&devc->limit.config,
+ SR_CONF_LIMIT_MSEC, &data);
+ if (ret != SR_OK)
+ return ret;
+ user_msecs = g_variant_get_uint64(data);
+ g_variant_unref(data);
+
+ /* Get the lesser of them, with both being optional. */
+ acquire_msecs = ~0ull;
+ if (user_count && count_msecs < acquire_msecs)
+ acquire_msecs = count_msecs;
+ if (user_msecs && user_msecs < acquire_msecs)
+ acquire_msecs = user_msecs;
+ if (acquire_msecs == ~0ull)
+ return SR_OK;
+
+ /* Add some slack, and use that timeout for acquisition. */
+ worst_cluster_time_ms = 1000 * 65536 / devc->clock.samplerate;
+ acquire_msecs += 2 * worst_cluster_time_ms;
+ data = g_variant_new_uint64(acquire_msecs);
+ ret = sr_sw_limits_config_set(&devc->limit.acquire,
+ SR_CONF_LIMIT_MSEC, data);
+ g_variant_unref(data);
+ if (ret != SR_OK)
+ return ret;
+
+ sr_sw_limits_acquisition_start(&devc->limit.acquire);
+ return SR_OK;
+}
+
+/*
+ * Check whether a caller specified samplerate matches the device's
+ * hardware constraints (can be used for acquisition). Optionally yield
+ * a value that approximates the original spec.
+ *
+ * This routine assumes that input specs are in the 200kHz to 200MHz
+ * range of supported rates, and callers typically want to normalize a
+ * given value to the hardware capabilities. Values in the 50MHz range
+ * get rounded up by default, to avoid a more expensive check for the
+ * closest match, while higher sampling rate is always desirable during
+ * measurement. Input specs which exactly match hardware capabilities
+ * remain unaffected. Because 100/200MHz rates also limit the number of
+ * available channels, they are not suggested by this routine, instead
+ * callers need to pick them consciously.
+ */
+SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
+{
+ uint64_t div, rate;
+
+ /* Accept exact matches for 100/200MHz. */
+ if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
+ if (have_rate)
+ *have_rate = want_rate;
+ return SR_OK;
+ }
+
+ /* Accept 200kHz to 50MHz range, and map to near value. */
+ if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
+ div = SR_MHZ(50) / want_rate;
+ rate = SR_MHZ(50) / div;
+ if (have_rate)
+ *have_rate = rate;
+ return SR_OK;
+ }
+
+ return SR_ERR_ARG;
+}
+
+/* Gets called at probe time. Can seed software settings from hardware state. */
+SR_PRIV int sigma_fetch_hw_config(const struct sr_dev_inst *sdi)
+{
+ struct dev_context *devc;
+ int ret;
+ uint8_t regaddr, regval;
+
+ devc = sdi->priv;
+ if (!devc)
+ return SR_ERR_ARG;
+
+ /* Seed configuration values from defaults. */
+ devc->firmware_idx = SIGMA_FW_NONE;
+ devc->clock.samplerate = samplerates[0];
+
+ /* TODO
+ * Ideally the device driver could retrieve recently stored
+ * details from hardware registers, thus re-use user specified
+ * configuration values across sigrok sessions. Which could
+ * avoid repeated expensive though unnecessary firmware uploads,
+ * improve performance and usability. Unfortunately it appears
+ * that the registers range which is documented as available for
+ * application use keeps providing 0xff data content. At least
+ * with the netlist version which ships with sigrok. The same
+ * was observed with unused registers in the first page.
+ */
+ return SR_ERR_NA;
+
+ /* This is for research, currently does not work yet. */
+ ret = sigma_check_open(sdi);
+ regaddr = 16;
+ regaddr = 14;
+ ret = sigma_set_register(devc, regaddr, 'F');
+ ret = sigma_get_register(devc, regaddr, ®val);
+ sr_warn("%s() reg[%u] val[%u] rc[%d]", __func__, regaddr, regval, ret);
+ ret = sigma_check_close(devc);
+ return ret;
+}
+
+/* Gets called after successful (volatile) hardware configuration. */
+SR_PRIV int sigma_store_hw_config(const struct sr_dev_inst *sdi)
+{
+ /* TODO See above, registers seem to not hold written data. */
+ (void)sdi;
+ return SR_ERR_NA;
+}
+
+SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
+{
+ struct dev_context *devc;
+ struct drv_context *drvc;
+ uint64_t samplerate;
+ int ret;
+ size_t num_channels;
+
+ devc = sdi->priv;
+ drvc = sdi->driver->context;
+
+ /* Accept any caller specified rate which the hardware supports. */
+ ret = sigma_normalize_samplerate(devc->clock.samplerate, &samplerate);
+ if (ret != SR_OK)
+ return ret;
+
+ /*
+ * Depending on the samplerates of 200/100/50- MHz, specific
+ * firmware is required and higher rates might limit the set
+ * of available channels.
+ */
+ num_channels = devc->interp.num_channels;
+ if (samplerate <= SR_MHZ(50)) {
+ ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
+ num_channels = 16;
+ } else if (samplerate == SR_MHZ(100)) {
+ ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
+ num_channels = 8;
+ } else if (samplerate == SR_MHZ(200)) {
+ ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
+ num_channels = 4;
+ }
+
+ /*
+ * The samplerate affects the number of available logic channels
+ * as well as a sample memory layout detail (the number of samples
+ * which the device will communicate within an "event").
+ */
+ if (ret == SR_OK) {
+ devc->interp.num_channels = num_channels;
+ devc->interp.samples_per_event = 16 / devc->interp.num_channels;
+ }
+
+ /*
+ * Store the firmware type and most recently configured samplerate
+ * in hardware, such that subsequent sessions can start from there.
+ * This is a "best effort" approach. Failure is non-fatal.
+ */
+ if (ret == SR_OK)
+ (void)sigma_store_hw_config(sdi);
+
+ return ret;
+}
+
+/*
+ * Arrange for a session feed submit buffer. A queue where a number of
+ * samples gets accumulated to reduce the number of send calls. Which
+ * also enforces an optional sample count limit for data acquisition.
+ *
+ * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
+ * driver provides a fixed channel layout regardless of samplerate).
+ */
+
+#define CHUNK_SIZE (4 * 1024 * 1024)
+
+struct submit_buffer {
+ size_t unit_size;
+ size_t max_samples, curr_samples;
+ uint8_t *sample_data;
+ uint8_t *write_pointer;
+ struct sr_dev_inst *sdi;
+ struct sr_datafeed_packet packet;
+ struct sr_datafeed_logic logic;
+};
+
+static int alloc_submit_buffer(struct sr_dev_inst *sdi)
+{
+ struct dev_context *devc;
+ struct submit_buffer *buffer;
+ size_t size;
+
+ devc = sdi->priv;
+
+ buffer = g_malloc0(sizeof(*buffer));
+ devc->buffer = buffer;
+
+ buffer->unit_size = sizeof(uint16_t);
+ size = CHUNK_SIZE;
+ size /= buffer->unit_size;
+ buffer->max_samples = size;
+ size *= buffer->unit_size;
+ buffer->sample_data = g_try_malloc0(size);
+ if (!buffer->sample_data)
+ return SR_ERR_MALLOC;
+ buffer->write_pointer = buffer->sample_data;
+ sr_sw_limits_init(&devc->limit.submit);
+
+ buffer->sdi = sdi;
+ memset(&buffer->logic, 0, sizeof(buffer->logic));
+ buffer->logic.unitsize = buffer->unit_size;
+ buffer->logic.data = buffer->sample_data;
+ memset(&buffer->packet, 0, sizeof(buffer->packet));
+ buffer->packet.type = SR_DF_LOGIC;
+ buffer->packet.payload = &buffer->logic;
+
+ return SR_OK;
+}
+
+static int setup_submit_limit(struct dev_context *devc)
+{
+ struct sr_sw_limits *limits;
+ int ret;
+ GVariant *data;
+ uint64_t total;
+
+ limits = &devc->limit.submit;
+
+ ret = sr_sw_limits_config_get(&devc->limit.config,
+ SR_CONF_LIMIT_SAMPLES, &data);
+ if (ret != SR_OK)
+ return ret;
+ total = g_variant_get_uint64(data);
+ g_variant_unref(data);
+
+ sr_sw_limits_init(limits);
+ if (total) {
+ data = g_variant_new_uint64(total);
+ ret = sr_sw_limits_config_set(limits,
+ SR_CONF_LIMIT_SAMPLES, data);
+ g_variant_unref(data);
+ if (ret != SR_OK)
+ return ret;
+ }
+
+ sr_sw_limits_acquisition_start(limits);
+
+ return SR_OK;
+}
+
+static void free_submit_buffer(struct dev_context *devc)
+{
+ struct submit_buffer *buffer;
+
+ if (!devc)
+ return;
+
+ buffer = devc->buffer;
+ if (!buffer)
+ return;
+ devc->buffer = NULL;
+
+ g_free(buffer->sample_data);
+ g_free(buffer);
+}
+
+static int flush_submit_buffer(struct dev_context *devc)
+{
+ struct submit_buffer *buffer;