2 * This file is part of the libsigrok project.
4 * Copyright (C) 2010-2012 Håvard Espeland <gus@ping.uio.no>,
5 * Copyright (C) 2010 Martin Stensgård <mastensg@ping.uio.no>
6 * Copyright (C) 2010 Carl Henrik Lunde <chlunde@ping.uio.no>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * ASIX SIGMA/SIGMA2 logic analyzer driver
30 * The ASIX SIGMA hardware supports fixed 200MHz and 100MHz sample rates
31 * (by means of separate firmware images). As well as 50MHz divided by
32 * an integer divider in the 1..256 range (by the "typical" firmware).
33 * Which translates to a strict lower boundary of around 195kHz.
35 * This driver "suggests" a subset of the available rates by listing a
36 * few discrete values, while setter routines accept any user specified
37 * rate that is supported by the hardware.
39 SR_PRIV const uint64_t samplerates[] = {
40 /* 50MHz and integer divider. 1/2/5 steps (where possible). */
41 SR_KHZ(200), SR_KHZ(500),
42 SR_MHZ(1), SR_MHZ(2), SR_MHZ(5),
43 SR_MHZ(10), SR_MHZ(25), SR_MHZ(50),
44 /* 100MHz/200MHz, fixed rates in special firmware. */
45 SR_MHZ(100), SR_MHZ(200),
48 SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
50 static const char *firmware_files[] = {
51 [SIGMA_FW_50MHZ] = "asix-sigma-50.fw", /* 50MHz, 8bit divider. */
52 [SIGMA_FW_100MHZ] = "asix-sigma-100.fw", /* 100MHz, fixed. */
53 [SIGMA_FW_200MHZ] = "asix-sigma-200.fw", /* 200MHz, fixed. */
54 [SIGMA_FW_SYNC] = "asix-sigma-50sync.fw", /* Sync from external pin. */
55 [SIGMA_FW_FREQ] = "asix-sigma-phasor.fw", /* Frequency counter. */
58 #define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
60 static int sigma_read(void *buf, size_t size, struct dev_context *devc)
64 ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
66 sr_err("ftdi_read_data failed: %s",
67 ftdi_get_error_string(&devc->ftdic));
73 static int sigma_write(void *buf, size_t size, struct dev_context *devc)
77 ret = ftdi_write_data(&devc->ftdic, (unsigned char *)buf, size);
79 sr_err("ftdi_write_data failed: %s",
80 ftdi_get_error_string(&devc->ftdic));
81 else if ((size_t) ret != size)
82 sr_err("ftdi_write_data did not complete write.");
88 * NOTE: We chose the buffer size to be large enough to hold any write to the
89 * device. We still print a message just in case.
91 SR_PRIV int sigma_write_register(uint8_t reg, uint8_t *data, size_t len,
92 struct dev_context *devc)
98 if ((2 * len + 2) > sizeof(buf)) {
99 sr_err("Attempted to write %zu bytes, but buffer is too small.",
104 buf[idx++] = REG_ADDR_LOW | (reg & 0xf);
105 buf[idx++] = REG_ADDR_HIGH | (reg >> 4);
107 for (i = 0; i < len; i++) {
108 buf[idx++] = REG_DATA_LOW | (data[i] & 0xf);
109 buf[idx++] = REG_DATA_HIGH_WRITE | (data[i] >> 4);
112 return sigma_write(buf, idx, devc);
115 SR_PRIV int sigma_set_register(uint8_t reg, uint8_t value, struct dev_context *devc)
117 return sigma_write_register(reg, &value, 1, devc);
120 static int sigma_read_register(uint8_t reg, uint8_t *data, size_t len,
121 struct dev_context *devc)
125 buf[0] = REG_ADDR_LOW | (reg & 0xf);
126 buf[1] = REG_ADDR_HIGH | (reg >> 4);
127 buf[2] = REG_READ_ADDR;
129 sigma_write(buf, sizeof(buf), devc);
131 return sigma_read(data, len, devc);
134 static int sigma_read_pos(uint32_t *stoppos, uint32_t *triggerpos,
135 struct dev_context *devc)
138 * Read 6 registers starting at trigger position LSB.
139 * Which yields two 24bit counter values.
142 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
143 REG_READ_ADDR | REG_ADDR_INC,
144 REG_READ_ADDR | REG_ADDR_INC,
145 REG_READ_ADDR | REG_ADDR_INC,
146 REG_READ_ADDR | REG_ADDR_INC,
147 REG_READ_ADDR | REG_ADDR_INC,
148 REG_READ_ADDR | REG_ADDR_INC,
152 sigma_write(buf, sizeof(buf), devc);
154 sigma_read(result, sizeof(result), devc);
156 *triggerpos = result[0] | (result[1] << 8) | (result[2] << 16);
157 *stoppos = result[3] | (result[4] << 8) | (result[5] << 16);
160 * These "position" values point to after the event (end of
161 * capture data, trigger condition matched). This is why they
162 * get decremented here. Sample memory consists of 512-byte
163 * chunks with meta data in the upper 64 bytes. Thus when the
164 * decrements takes us into this upper part of the chunk, then
165 * further move backwards to the end of the chunk's data part.
167 * TODO Re-consider the above comment's validity. It's true
168 * that a 1024byte row contains 512 u16 entities, of which 64
169 * are timestamps and 448 are events with sample data. It's not
170 * true that 64bytes of metadata reside at the top of a 512byte
173 * TODO Use ROW_MASK and CLUSTERS_PER_ROW here?
175 if ((--*stoppos & 0x1ff) == 0x1ff)
177 if ((--*triggerpos & 0x1ff) == 0x1ff)
183 static int sigma_read_dram(uint16_t startchunk, size_t numchunks,
184 uint8_t *data, struct dev_context *devc)
192 /* Communicate DRAM start address (memory row, aka samples line). */
194 buf[idx++] = startchunk >> 8;
195 buf[idx++] = startchunk & 0xff;
196 sigma_write_register(WRITE_MEMROW, buf, idx, devc);
199 * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
200 * then transfer via USB. Interleave the FPGA's DRAM access and
201 * USB transfer, use alternating buffers (0/1) in the process.
204 buf[idx++] = REG_DRAM_BLOCK;
205 buf[idx++] = REG_DRAM_WAIT_ACK;
206 for (chunk = 0; chunk < numchunks; chunk++) {
208 is_last = chunk == numchunks - 1;
210 buf[idx++] = REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel);
211 buf[idx++] = REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel);
213 buf[idx++] = REG_DRAM_WAIT_ACK;
215 sigma_write(buf, idx, devc);
217 return sigma_read(data, numchunks * ROW_LENGTH_BYTES, devc);
220 /* Upload trigger look-up tables to Sigma. */
221 SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *devc)
227 /* Transpose the table and send to Sigma. */
228 for (i = 0; i < 16; i++) {
233 if (lut->m2d[0] & bit)
235 if (lut->m2d[1] & bit)
237 if (lut->m2d[2] & bit)
239 if (lut->m2d[3] & bit)
249 if (lut->m0d[0] & bit)
251 if (lut->m0d[1] & bit)
253 if (lut->m0d[2] & bit)
255 if (lut->m0d[3] & bit)
258 if (lut->m1d[0] & bit)
260 if (lut->m1d[1] & bit)
262 if (lut->m1d[2] & bit)
264 if (lut->m1d[3] & bit)
267 sigma_write_register(WRITE_TRIGGER_SELECT, tmp, sizeof(tmp),
269 sigma_set_register(WRITE_TRIGGER_SELECT2, 0x30 | i, devc);
272 /* Send the parameters */
273 sigma_write_register(WRITE_TRIGGER_SELECT, (uint8_t *) &lut->params,
274 sizeof(lut->params), devc);
280 * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
281 * uses FTDI bitbang mode for netlist download in slave serial mode.
282 * (LATER: The OMEGA device's cable contains a more capable FTDI chip
283 * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
284 * compatible bitbang mode? For maximum code re-use and reduced libftdi
285 * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
286 * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
288 * 750kbps rate (four times the speed of sigmalogan) works well for
289 * netlist download. All pins except INIT_B are output pins during
290 * configuration download.
292 * Some pins are inverted as a byproduct of level shifting circuitry.
293 * That's why high CCLK level (from the cable's point of view) is idle
294 * from the FPGA's perspective.
296 * The vendor's literature discusses a "suicide sequence" which ends
297 * regular FPGA execution and should be sent before entering bitbang
298 * mode and sending configuration data. Set D7 and toggle D2, D3, D4
301 #define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
302 #define BB_PIN_PROG (1 << 1) /* D1, PROG */
303 #define BB_PIN_D2 (1 << 2) /* D2, (part of) SUICIDE */
304 #define BB_PIN_D3 (1 << 3) /* D3, (part of) SUICIDE */
305 #define BB_PIN_D4 (1 << 4) /* D4, (part of) SUICIDE (unused?) */
306 #define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
307 #define BB_PIN_DIN (1 << 6) /* D6, DIN */
308 #define BB_PIN_D7 (1 << 7) /* D7, (part of) SUICIDE */
310 #define BB_BITRATE (750 * 1000)
311 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
314 * Initiate slave serial mode for configuration download. Which is done
315 * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
316 * initiating the configuration download.
318 * Run a "suicide sequence" first to terminate the regular FPGA operation
319 * before reconfiguration. The FTDI cable is single channel, and shares
320 * pins which are used for data communication in FIFO mode with pins that
321 * are used for FPGA configuration in bitbang mode. Hardware defaults for
322 * unconfigured hardware, and runtime conditions after FPGA configuration
323 * need to cooperate such that re-configuration of the FPGA can start.
325 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
327 uint8_t suicide[] = {
328 BB_PIN_D7 | BB_PIN_D2,
329 BB_PIN_D7 | BB_PIN_D2,
330 BB_PIN_D7 | BB_PIN_D3,
331 BB_PIN_D7 | BB_PIN_D2,
332 BB_PIN_D7 | BB_PIN_D3,
333 BB_PIN_D7 | BB_PIN_D2,
334 BB_PIN_D7 | BB_PIN_D3,
335 BB_PIN_D7 | BB_PIN_D2,
337 uint8_t init_array[] = {
339 BB_PIN_CCLK | BB_PIN_PROG,
340 BB_PIN_CCLK | BB_PIN_PROG,
352 /* Section 2. part 1), do the FPGA suicide. */
353 sigma_write(suicide, sizeof(suicide), devc);
354 sigma_write(suicide, sizeof(suicide), devc);
355 sigma_write(suicide, sizeof(suicide), devc);
356 sigma_write(suicide, sizeof(suicide), devc);
359 /* Section 2. part 2), pulse PROG. */
360 sigma_write(init_array, sizeof(init_array), devc);
362 ftdi_usb_purge_buffers(&devc->ftdic);
364 /* Wait until the FPGA asserts INIT_B. */
367 ret = sigma_read(&data, 1, devc);
370 if (data & BB_PIN_INIT)
375 return SR_ERR_TIMEOUT;
379 * This is belt and braces. Re-run the bitbang initiation sequence a few
380 * times should first attempts fail. Failure is rare but can happen (was
381 * observed during driver development).
383 static int sigma_fpga_init_bitbang(struct dev_context *devc)
390 ret = sigma_fpga_init_bitbang_once(devc);
393 if (ret != SR_ERR_TIMEOUT)
400 * Configure the FPGA for logic-analyzer mode.
402 static int sigma_fpga_init_la(struct dev_context *devc)
405 * TODO Construct the sequence at runtime? Such that request data
406 * and response check values will match more apparently?
408 uint8_t mode_regval = WMR_SDRAMINIT;
409 uint8_t logic_mode_start[] = {
410 /* Read ID register. */
411 REG_ADDR_LOW | (READ_ID & 0xf),
412 REG_ADDR_HIGH | (READ_ID >> 4),
415 /* Write 0x55 to scratch register, read back. */
416 REG_ADDR_LOW | (WRITE_TEST & 0xf),
418 REG_DATA_HIGH_WRITE | 0x5,
421 /* Write 0xaa to scratch register, read back. */
423 REG_DATA_HIGH_WRITE | 0xa,
426 /* Initiate SDRAM initialization in mode register. */
427 REG_ADDR_LOW | (WRITE_MODE & 0xf),
428 REG_DATA_LOW | (mode_regval & 0xf),
429 REG_DATA_HIGH_WRITE | (mode_regval >> 4),
435 * Send the command sequence which contains 3 READ requests.
436 * Expect to see the corresponding 3 response bytes.
438 sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
439 ret = sigma_read(result, ARRAY_SIZE(result), devc);
440 if (ret != ARRAY_SIZE(result))
442 if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
448 sr_err("Configuration failed. Invalid reply received.");
453 * Read the firmware from a file and transform it into a series of bitbang
454 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
455 * by the caller of this function.
457 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
458 uint8_t **bb_cmd, gsize *bb_cmd_size)
466 uint8_t *bb_stream, *bbs, byte, mask, v;
468 /* Retrieve the on-disk firmware file content. */
469 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
470 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
474 /* Unscramble the file content (XOR with "random" sequence). */
479 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
484 * Generate a sequence of bitbang samples. With two samples per
485 * FPGA configuration bit, providing the level for the DIN signal
486 * as well as two edges for CCLK. See Xilinx UG332 for details
487 * ("slave serial" mode).
489 * Note that CCLK is inverted in hardware. That's why the
490 * respective bit is first set and then cleared in the bitbang
491 * sample sets. So that the DIN level will be stable when the
492 * data gets sampled at the rising CCLK edge, and the signals'
493 * setup time constraint will be met.
495 * The caller will put the FPGA into download mode, will send
496 * the bitbang samples, and release the allocated memory.
498 bb_size = file_size * 8 * 2;
499 bb_stream = g_try_malloc(bb_size);
501 sr_err("%s: Failed to allocate bitbang stream", __func__);
503 return SR_ERR_MALLOC;
512 v = (byte & mask) ? BB_PIN_DIN : 0;
514 *bbs++ = v | BB_PIN_CCLK;
520 /* The transformation completed successfully, return the result. */
522 *bb_cmd_size = bb_size;
527 static int upload_firmware(struct sr_context *ctx,
528 struct dev_context *devc, enum sigma_firmware_idx firmware_idx)
534 const char *firmware;
536 /* Check for valid firmware file selection. */
537 if (firmware_idx >= ARRAY_SIZE(firmware_files))
539 firmware = firmware_files[firmware_idx];
540 if (!firmware || !*firmware)
543 /* Avoid downloading the same firmware multiple times. */
544 if (devc->firmware_idx == firmware_idx) {
545 sr_info("Not uploading firmware file '%s' again.", firmware);
549 devc->state.state = SIGMA_CONFIG;
551 /* Set the cable to bitbang mode. */
552 ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
554 sr_err("ftdi_set_bitmode failed: %s",
555 ftdi_get_error_string(&devc->ftdic));
558 ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
560 sr_err("ftdi_set_baudrate failed: %s",
561 ftdi_get_error_string(&devc->ftdic));
565 /* Initiate FPGA configuration mode. */
566 ret = sigma_fpga_init_bitbang(devc);
570 /* Prepare wire format of the firmware image. */
571 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
573 sr_err("An error occurred while reading the firmware: %s",
578 /* Write the FPGA netlist to the cable. */
579 sr_info("Uploading firmware file '%s'.", firmware);
580 sigma_write(buf, buf_size, devc);
584 /* Leave bitbang mode and discard pending input data. */
585 ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
587 sr_err("ftdi_set_bitmode failed: %s",
588 ftdi_get_error_string(&devc->ftdic));
591 ftdi_usb_purge_buffers(&devc->ftdic);
592 while (sigma_read(&pins, 1, devc) == 1)
595 /* Initialize the FPGA for logic-analyzer mode. */
596 ret = sigma_fpga_init_la(devc);
600 /* Keep track of successful firmware download completion. */
601 devc->state.state = SIGMA_IDLE;
602 devc->firmware_idx = firmware_idx;
603 sr_info("Firmware uploaded.");
609 * The driver supports user specified time or sample count limits. The
610 * device's hardware supports neither, and hardware compression prevents
611 * reliable detection of "fill levels" (currently reached sample counts)
612 * from register values during acquisition. That's why the driver needs
613 * to apply some heuristics:
615 * - The (optional) sample count limit and the (normalized) samplerate
616 * get mapped to an estimated duration for these samples' acquisition.
617 * - The (optional) time limit gets checked as well. The lesser of the
618 * two limits will terminate the data acquisition phase. The exact
619 * sample count limit gets enforced in session feed submission paths.
620 * - Some slack needs to be given to account for hardware pipelines as
621 * well as late storage of last chunks after compression thresholds
622 * are tripped. The resulting data set will span at least the caller
623 * specified period of time, which shall be perfectly acceptable.
625 * With RLE compression active, up to 64K sample periods can pass before
626 * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
627 * times that period for good measure, one is not enough to flush the
628 * hardware pipeline (observation from an earlier experiment).
630 SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
634 uint64_t user_count, user_msecs;
635 uint64_t worst_cluster_time_ms;
636 uint64_t count_msecs, acquire_msecs;
638 sr_sw_limits_init(&devc->acq_limits);
640 /* Get sample count limit, convert to msecs. */
641 ret = sr_sw_limits_config_get(&devc->cfg_limits,
642 SR_CONF_LIMIT_SAMPLES, &data);
645 user_count = g_variant_get_uint64(data);
646 g_variant_unref(data);
649 count_msecs = 1000 * user_count / devc->samplerate + 1;
651 /* Get time limit, which is in msecs. */
652 ret = sr_sw_limits_config_get(&devc->cfg_limits,
653 SR_CONF_LIMIT_MSEC, &data);
656 user_msecs = g_variant_get_uint64(data);
657 g_variant_unref(data);
659 /* Get the lesser of them, with both being optional. */
660 acquire_msecs = ~0ull;
661 if (user_count && count_msecs < acquire_msecs)
662 acquire_msecs = count_msecs;
663 if (user_msecs && user_msecs < acquire_msecs)
664 acquire_msecs = user_msecs;
665 if (acquire_msecs == ~0ull)
668 /* Add some slack, and use that timeout for acquisition. */
669 worst_cluster_time_ms = 1000 * 65536 / devc->samplerate;
670 acquire_msecs += 2 * worst_cluster_time_ms;
671 data = g_variant_new_uint64(acquire_msecs);
672 ret = sr_sw_limits_config_set(&devc->acq_limits,
673 SR_CONF_LIMIT_MSEC, data);
674 g_variant_unref(data);
678 sr_sw_limits_acquisition_start(&devc->acq_limits);
683 * Check whether a caller specified samplerate matches the device's
684 * hardware constraints (can be used for acquisition). Optionally yield
685 * a value that approximates the original spec.
687 * This routine assumes that input specs are in the 200kHz to 200MHz
688 * range of supported rates, and callers typically want to normalize a
689 * given value to the hardware capabilities. Values in the 50MHz range
690 * get rounded up by default, to avoid a more expensive check for the
691 * closest match, while higher sampling rate is always desirable during
692 * measurement. Input specs which exactly match hardware capabilities
693 * remain unaffected. Because 100/200MHz rates also limit the number of
694 * available channels, they are not suggested by this routine, instead
695 * callers need to pick them consciously.
697 SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
701 /* Accept exact matches for 100/200MHz. */
702 if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
704 *have_rate = want_rate;
708 /* Accept 200kHz to 50MHz range, and map to near value. */
709 if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
710 div = SR_MHZ(50) / want_rate;
711 rate = SR_MHZ(50) / div;
720 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
722 struct dev_context *devc;
723 struct drv_context *drvc;
729 drvc = sdi->driver->context;
731 /* Accept any caller specified rate which the hardware supports. */
732 ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
737 * Depending on the samplerates of 200/100/50- MHz, specific
738 * firmware is required and higher rates might limit the set
739 * of available channels.
741 num_channels = devc->num_channels;
742 if (samplerate <= SR_MHZ(50)) {
743 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
745 } else if (samplerate == SR_MHZ(100)) {
746 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
748 } else if (samplerate == SR_MHZ(200)) {
749 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
754 * The samplerate affects the number of available logic channels
755 * as well as a sample memory layout detail (the number of samples
756 * which the device will communicate within an "event").
759 devc->num_channels = num_channels;
760 devc->samples_per_event = 16 / devc->num_channels;
767 * Arrange for a session feed submit buffer. A queue where a number of
768 * samples gets accumulated to reduce the number of send calls. Which
769 * also enforces an optional sample count limit for data acquisition.
771 * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
772 * driver provides a fixed channel layout regardless of samplerate).
775 #define CHUNK_SIZE (4 * 1024 * 1024)
777 struct submit_buffer {
779 size_t max_samples, curr_samples;
780 uint8_t *sample_data;
781 uint8_t *write_pointer;
782 struct sr_dev_inst *sdi;
783 struct sr_datafeed_packet packet;
784 struct sr_datafeed_logic logic;
787 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
789 struct dev_context *devc;
790 struct submit_buffer *buffer;
795 buffer = g_malloc0(sizeof(*buffer));
796 devc->buffer = buffer;
798 buffer->unit_size = sizeof(uint16_t);
800 size /= buffer->unit_size;
801 buffer->max_samples = size;
802 size *= buffer->unit_size;
803 buffer->sample_data = g_try_malloc0(size);
804 if (!buffer->sample_data)
805 return SR_ERR_MALLOC;
806 buffer->write_pointer = buffer->sample_data;
807 sr_sw_limits_init(&devc->feed_limits);
810 memset(&buffer->logic, 0, sizeof(buffer->logic));
811 buffer->logic.unitsize = buffer->unit_size;
812 buffer->logic.data = buffer->sample_data;
813 memset(&buffer->packet, 0, sizeof(buffer->packet));
814 buffer->packet.type = SR_DF_LOGIC;
815 buffer->packet.payload = &buffer->logic;
820 static int setup_submit_limit(struct dev_context *devc)
822 struct sr_sw_limits *limits;
827 limits = &devc->feed_limits;
829 ret = sr_sw_limits_config_get(&devc->cfg_limits,
830 SR_CONF_LIMIT_SAMPLES, &data);
833 total = g_variant_get_uint64(data);
834 g_variant_unref(data);
836 sr_sw_limits_init(limits);
838 data = g_variant_new_uint64(total);
839 ret = sr_sw_limits_config_set(limits,
840 SR_CONF_LIMIT_SAMPLES, data);
841 g_variant_unref(data);
846 sr_sw_limits_acquisition_start(limits);
851 static void free_submit_buffer(struct dev_context *devc)
853 struct submit_buffer *buffer;
858 buffer = devc->buffer;
863 g_free(buffer->sample_data);
867 static int flush_submit_buffer(struct dev_context *devc)
869 struct submit_buffer *buffer;
872 buffer = devc->buffer;
874 /* Is queued sample data available? */
875 if (!buffer->curr_samples)
878 /* Submit to the session feed. */
879 buffer->logic.length = buffer->curr_samples * buffer->unit_size;
880 ret = sr_session_send(buffer->sdi, &buffer->packet);
884 /* Rewind queue position. */
885 buffer->curr_samples = 0;
886 buffer->write_pointer = buffer->sample_data;
891 static int addto_submit_buffer(struct dev_context *devc,
892 uint16_t sample, size_t count)
894 struct submit_buffer *buffer;
895 struct sr_sw_limits *limits;
898 buffer = devc->buffer;
899 limits = &devc->feed_limits;
900 if (sr_sw_limits_check(limits))
904 * Individually accumulate and check each sample, such that
905 * accumulation between flushes won't exceed local storage, and
906 * enforcement of user specified limits is exact.
909 WL16(buffer->write_pointer, sample);
910 buffer->write_pointer += buffer->unit_size;
911 buffer->curr_samples++;
912 if (buffer->curr_samples == buffer->max_samples) {
913 ret = flush_submit_buffer(devc);
917 sr_sw_limits_update_samples_read(limits, 1);
918 if (sr_sw_limits_check(limits))
926 * In 100 and 200 MHz mode, only a single pin rising/falling can be
927 * set as trigger. In other modes, two rising/falling triggers can be set,
928 * in addition to value/mask trigger for any number of channels.
930 * The Sigma supports complex triggers using boolean expressions, but this
931 * has not been implemented yet.
933 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
935 struct dev_context *devc;
936 struct sr_trigger *trigger;
937 struct sr_trigger_stage *stage;
938 struct sr_trigger_match *match;
940 int channelbit, trigger_set;
943 memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
944 if (!(trigger = sr_session_trigger_get(sdi->session)))
948 for (l = trigger->stages; l; l = l->next) {
950 for (m = stage->matches; m; m = m->next) {
952 if (!match->channel->enabled)
953 /* Ignore disabled channels with a trigger. */
955 channelbit = 1 << (match->channel->index);
956 if (devc->samplerate >= SR_MHZ(100)) {
957 /* Fast trigger support. */
959 sr_err("Only a single pin trigger is "
960 "supported in 100 and 200MHz mode.");
963 if (match->match == SR_TRIGGER_FALLING)
964 devc->trigger.fallingmask |= channelbit;
965 else if (match->match == SR_TRIGGER_RISING)
966 devc->trigger.risingmask |= channelbit;
968 sr_err("Only rising/falling trigger is "
969 "supported in 100 and 200MHz mode.");
975 /* Simple trigger support (event). */
976 if (match->match == SR_TRIGGER_ONE) {
977 devc->trigger.simplevalue |= channelbit;
978 devc->trigger.simplemask |= channelbit;
979 } else if (match->match == SR_TRIGGER_ZERO) {
980 devc->trigger.simplevalue &= ~channelbit;
981 devc->trigger.simplemask |= channelbit;
982 } else if (match->match == SR_TRIGGER_FALLING) {
983 devc->trigger.fallingmask |= channelbit;
985 } else if (match->match == SR_TRIGGER_RISING) {
986 devc->trigger.risingmask |= channelbit;
991 * Actually, Sigma supports 2 rising/falling triggers,
992 * but they are ORed and the current trigger syntax
993 * does not permit ORed triggers.
995 if (trigger_set > 1) {
996 sr_err("Only 1 rising/falling trigger "
1007 /* Software trigger to determine exact trigger position. */
1008 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1009 struct sigma_trigger *t)
1012 uint16_t sample = 0;
1014 for (i = 0; i < 8; i++) {
1016 last_sample = sample;
1017 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
1019 /* Simple triggers. */
1020 if ((sample & t->simplemask) != t->simplevalue)
1024 if (((last_sample & t->risingmask) != 0) ||
1025 ((sample & t->risingmask) != t->risingmask))
1029 if ((last_sample & t->fallingmask) != t->fallingmask ||
1030 (sample & t->fallingmask) != 0)
1036 /* If we did not match, return original trigger pos. */
1040 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1043 * Check whether the combination of this very sample and the
1044 * previous state match the configured trigger condition. This
1045 * improves the resolution of the trigger marker's position.
1046 * The hardware provided position is coarse, and may point to
1047 * a position before the actual match.
1049 * See the previous get_trigger_offset() implementation. This
1050 * code needs to get re-used here.
1054 (void)get_trigger_offset;
1059 static int check_and_submit_sample(struct dev_context *devc,
1060 uint16_t sample, size_t count, gboolean check_trigger)
1065 triggered = check_trigger && sample_matches_trigger(devc, sample);
1067 ret = flush_submit_buffer(devc);
1070 ret = std_session_send_df_trigger(devc->buffer->sdi);
1075 ret = addto_submit_buffer(devc, sample, count);
1083 * Return the timestamp of "DRAM cluster".
1085 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1087 return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
1091 * Return one 16bit data entity of a DRAM cluster at the specified index.
1093 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1098 sample |= cl->samples[idx].sample_lo << 0;
1099 sample |= cl->samples[idx].sample_hi << 8;
1100 sample = (sample >> 8) | (sample << 8);
1105 * Deinterlace sample data that was retrieved at 100MHz samplerate.
1106 * One 16bit item contains two samples of 8bits each. The bits of
1107 * multiple samples are interleaved.
1109 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1115 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1116 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1117 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1118 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1119 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1120 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1121 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1122 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1127 * Deinterlace sample data that was retrieved at 200MHz samplerate.
1128 * One 16bit item contains four samples of 4bits each. The bits of
1129 * multiple samples are interleaved.
1131 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1137 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1138 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1139 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1140 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1144 static void sigma_decode_dram_cluster(struct dev_context *devc,
1145 struct sigma_dram_cluster *dram_cluster,
1146 size_t events_in_cluster, gboolean triggered)
1148 struct sigma_state *ss;
1149 uint16_t tsdiff, ts, sample, item16;
1152 if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1156 * If this cluster is not adjacent to the previously received
1157 * cluster, then send the appropriate number of samples with the
1158 * previous values to the sigrok session. This "decodes RLE".
1160 * These samples cannot match the trigger since they just repeat
1161 * the previously submitted data pattern. (This assumption holds
1162 * for simple level and edge triggers. It would not for timed or
1163 * counted conditions, which currently are not supported.)
1166 ts = sigma_dram_cluster_ts(dram_cluster);
1167 tsdiff = ts - ss->lastts;
1170 count = tsdiff * devc->samples_per_event;
1171 (void)check_and_submit_sample(devc, ss->lastsample, count, FALSE);
1173 ss->lastts = ts + EVENTS_PER_CLUSTER;
1176 * Grab sample data from the current cluster and prepare their
1177 * submission to the session feed. Handle samplerate dependent
1178 * memory layout of sample data. Accumulation of data chunks
1179 * before submission is transparent to this code path, specific
1180 * buffer depth is neither assumed nor required here.
1183 for (i = 0; i < events_in_cluster; i++) {
1184 item16 = sigma_dram_cluster_data(dram_cluster, i);
1185 if (devc->samplerate == SR_MHZ(200)) {
1186 sample = sigma_deinterlace_200mhz_data(item16, 0);
1187 check_and_submit_sample(devc, sample, 1, triggered);
1188 sample = sigma_deinterlace_200mhz_data(item16, 1);
1189 check_and_submit_sample(devc, sample, 1, triggered);
1190 sample = sigma_deinterlace_200mhz_data(item16, 2);
1191 check_and_submit_sample(devc, sample, 1, triggered);
1192 sample = sigma_deinterlace_200mhz_data(item16, 3);
1193 check_and_submit_sample(devc, sample, 1, triggered);
1194 } else if (devc->samplerate == SR_MHZ(100)) {
1195 sample = sigma_deinterlace_100mhz_data(item16, 0);
1196 check_and_submit_sample(devc, sample, 1, triggered);
1197 sample = sigma_deinterlace_100mhz_data(item16, 1);
1198 check_and_submit_sample(devc, sample, 1, triggered);
1201 check_and_submit_sample(devc, sample, 1, triggered);
1204 ss->lastsample = sample;
1208 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1209 * Each event is 20ns apart, and can contain multiple samples.
1211 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1212 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1213 * For 50 MHz and below, events contain one sample for each channel,
1214 * spread 20 ns apart.
1216 static int decode_chunk_ts(struct dev_context *devc,
1217 struct sigma_dram_line *dram_line,
1218 size_t events_in_line, size_t trigger_event)
1220 struct sigma_dram_cluster *dram_cluster;
1221 unsigned int clusters_in_line;
1222 unsigned int events_in_cluster;
1224 uint32_t trigger_cluster;
1226 clusters_in_line = events_in_line;
1227 clusters_in_line += EVENTS_PER_CLUSTER - 1;
1228 clusters_in_line /= EVENTS_PER_CLUSTER;
1229 trigger_cluster = ~0;
1231 /* Check if trigger is in this chunk. */
1232 if (trigger_event < EVENTS_PER_ROW) {
1233 if (devc->samplerate <= SR_MHZ(50)) {
1234 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1238 /* Find in which cluster the trigger occurred. */
1239 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1242 /* For each full DRAM cluster. */
1243 for (i = 0; i < clusters_in_line; i++) {
1244 dram_cluster = &dram_line->cluster[i];
1246 /* The last cluster might not be full. */
1247 if ((i == clusters_in_line - 1) &&
1248 (events_in_line % EVENTS_PER_CLUSTER)) {
1249 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1251 events_in_cluster = EVENTS_PER_CLUSTER;
1254 sigma_decode_dram_cluster(devc, dram_cluster,
1255 events_in_cluster, i == trigger_cluster);
1261 static int download_capture(struct sr_dev_inst *sdi)
1263 const uint32_t chunks_per_read = 32;
1265 struct dev_context *devc;
1266 struct sigma_dram_line *dram_line;
1268 uint32_t stoppos, triggerpos;
1271 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1272 uint32_t dl_first_line, dl_line;
1273 uint32_t dl_events_in_line;
1274 uint32_t trg_line, trg_event;
1278 dl_events_in_line = EVENTS_PER_ROW;
1280 sr_info("Downloading sample data.");
1281 devc->state.state = SIGMA_DOWNLOAD;
1284 * Ask the hardware to stop data acquisition. Reception of the
1285 * FORCESTOP request makes the hardware "disable RLE" (store
1286 * clusters to DRAM regardless of whether pin state changes) and
1287 * raise the POSTTRIGGERED flag.
1289 sigma_set_register(WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN, devc);
1291 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1292 sr_err("failed while waiting for RMR_POSTTRIGGERED bit");
1295 } while (!(modestatus & RMR_POSTTRIGGERED));
1297 /* Set SDRAM Read Enable. */
1298 sigma_set_register(WRITE_MODE, WMR_SDRAMREADEN, devc);
1300 /* Get the current position. */
1301 sigma_read_pos(&stoppos, &triggerpos, devc);
1303 /* Check if trigger has fired. */
1304 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1305 sr_err("failed to read READ_MODE register");
1310 if (modestatus & RMR_TRIGGERED) {
1311 trg_line = triggerpos >> 9;
1312 trg_event = triggerpos & 0x1ff;
1316 * Determine how many "DRAM lines" of 1024 bytes each we need to
1317 * retrieve from the Sigma hardware, so that we have a complete
1318 * set of samples. Note that the last line need not contain 64
1319 * clusters, it might be partially filled only.
1321 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1322 * around. Since the status of the very next line is uncertain in
1323 * that case, we skip it and start reading from the next line.
1326 dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1327 if (modestatus & RMR_ROUND) {
1328 dl_first_line = dl_lines_total + 1;
1329 dl_lines_total = ROW_COUNT - 2;
1331 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1334 ret = alloc_submit_buffer(sdi);
1337 ret = setup_submit_limit(devc);
1341 while (dl_lines_total > dl_lines_done) {
1342 /* We can download only up-to 32 DRAM lines in one go! */
1343 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1345 dl_line = dl_first_line + dl_lines_done;
1346 dl_line %= ROW_COUNT;
1347 bufsz = sigma_read_dram(dl_line, dl_lines_curr,
1348 (uint8_t *)dram_line, devc);
1349 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1352 /* This is the first DRAM line, so find the initial timestamp. */
1353 if (dl_lines_done == 0) {
1354 devc->state.lastts =
1355 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1356 devc->state.lastsample = 0;
1359 for (i = 0; i < dl_lines_curr; i++) {
1360 uint32_t trigger_event = ~0;
1361 /* The last "DRAM line" can be only partially full. */
1362 if (dl_lines_done + i == dl_lines_total - 1)
1363 dl_events_in_line = stoppos & 0x1ff;
1365 /* Test if the trigger happened on this line. */
1366 if (dl_lines_done + i == trg_line)
1367 trigger_event = trg_event;
1369 decode_chunk_ts(devc, dram_line + i,
1370 dl_events_in_line, trigger_event);
1373 dl_lines_done += dl_lines_curr;
1375 flush_submit_buffer(devc);
1376 free_submit_buffer(devc);
1379 std_session_send_df_end(sdi);
1381 devc->state.state = SIGMA_IDLE;
1382 sr_dev_acquisition_stop(sdi);
1388 * Periodically check the Sigma status when in CAPTURE mode. This routine
1389 * checks whether the configured sample count or sample time have passed,
1390 * and will stop acquisition and download the acquired samples.
1392 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1394 struct dev_context *devc;
1397 if (sr_sw_limits_check(&devc->acq_limits))
1398 return download_capture(sdi);
1403 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1405 struct sr_dev_inst *sdi;
1406 struct dev_context *devc;
1414 if (devc->state.state == SIGMA_IDLE)
1418 * When the application has requested to stop the acquisition,
1419 * then immediately start downloading sample data. Otherwise
1420 * keep checking configured limits which will terminate the
1421 * acquisition and initiate download.
1423 if (devc->state.state == SIGMA_STOPPING)
1424 return download_capture(sdi);
1425 if (devc->state.state == SIGMA_CAPTURE)
1426 return sigma_capture_mode(sdi);
1431 /* Build a LUT entry used by the trigger functions. */
1432 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1436 /* For each quad channel. */
1437 for (i = 0; i < 4; i++) {
1440 /* For each bit in LUT. */
1441 for (j = 0; j < 16; j++)
1443 /* For each channel in quad. */
1444 for (k = 0; k < 4; k++) {
1445 bit = 1 << (i * 4 + k);
1447 /* Set bit in entry */
1448 if ((mask & bit) && ((!(value & bit)) !=
1450 entry[i] &= ~(1 << j);
1455 /* Add a logical function to LUT mask. */
1456 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1457 int index, int neg, uint16_t *mask)
1460 int x[2][2], tmp, a, b, aset, bset, rset;
1462 memset(x, 0, 4 * sizeof(int));
1464 /* Trigger detect condition. */
1494 case OP_NOTRISEFALL:
1500 /* Transpose if neg is set. */
1502 for (i = 0; i < 2; i++) {
1503 for (j = 0; j < 2; j++) {
1505 x[i][j] = x[1 - i][1 - j];
1506 x[1 - i][1 - j] = tmp;
1511 /* Update mask with function. */
1512 for (i = 0; i < 16; i++) {
1513 a = (i >> (2 * index + 0)) & 1;
1514 b = (i >> (2 * index + 1)) & 1;
1516 aset = (*mask >> i) & 1;
1520 if (func == FUNC_AND || func == FUNC_NAND)
1522 else if (func == FUNC_OR || func == FUNC_NOR)
1524 else if (func == FUNC_XOR || func == FUNC_NXOR)
1527 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1538 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1539 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1540 * set at any time, but a full mask and value can be set (0/1).
1542 SR_PRIV int sigma_build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1545 uint16_t masks[2] = { 0, 0 };
1547 memset(lut, 0, sizeof(struct triggerlut));
1549 /* Constant for simple triggers. */
1552 /* Value/mask trigger support. */
1553 build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1556 /* Rise/fall trigger support. */
1557 for (i = 0, j = 0; i < 16; i++) {
1558 if (devc->trigger.risingmask & (1 << i) ||
1559 devc->trigger.fallingmask & (1 << i))
1560 masks[j++] = 1 << i;
1563 build_lut_entry(masks[0], masks[0], lut->m0d);
1564 build_lut_entry(masks[1], masks[1], lut->m1d);
1566 /* Add glue logic */
1567 if (masks[0] || masks[1]) {
1568 /* Transition trigger. */
1569 if (masks[0] & devc->trigger.risingmask)
1570 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1571 if (masks[0] & devc->trigger.fallingmask)
1572 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1573 if (masks[1] & devc->trigger.risingmask)
1574 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1575 if (masks[1] & devc->trigger.fallingmask)
1576 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1578 /* Only value/mask trigger. */
1582 /* Triggertype: event. */
1583 lut->params.selres = 3;