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 supports arbitrary integer frequency divider in
31 * the 50MHz mode. The divider is in range 1...256 , allowing for
32 * very precise sampling rate selection. This driver supports only
33 * a subset of the sampling rates.
35 SR_PRIV const uint64_t samplerates[] = {
36 SR_KHZ(200), /* div=250 */
37 SR_KHZ(250), /* div=200 */
38 SR_KHZ(500), /* div=100 */
39 SR_MHZ(1), /* div=50 */
40 SR_MHZ(5), /* div=10 */
41 SR_MHZ(10), /* div=5 */
42 SR_MHZ(25), /* div=2 */
43 SR_MHZ(50), /* div=1 */
44 SR_MHZ(100), /* Special FW needed */
45 SR_MHZ(200), /* Special FW needed */
48 SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
50 static const char *firmware_files[] = {
51 "asix-sigma-50.fw", /* Up to 50MHz sample rate, 8bit divider. */
52 "asix-sigma-100.fw", /* 100MHz sample rate, fixed. */
53 "asix-sigma-200.fw", /* 200MHz sample rate, fixed. */
54 "asix-sigma-50sync.fw", /* Synchronous clock from external pin. */
55 "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. Run a "suicide sequence" first
317 * to terminate the regular FPGA operation before reconfiguration.
319 static int sigma_fpga_init_bitbang(struct dev_context *devc)
321 uint8_t suicide[] = {
322 BB_PIN_D7 | BB_PIN_D2,
323 BB_PIN_D7 | BB_PIN_D2,
324 BB_PIN_D7 | BB_PIN_D3,
325 BB_PIN_D7 | BB_PIN_D2,
326 BB_PIN_D7 | BB_PIN_D3,
327 BB_PIN_D7 | BB_PIN_D2,
328 BB_PIN_D7 | BB_PIN_D3,
329 BB_PIN_D7 | BB_PIN_D2,
331 uint8_t init_array[] = {
333 BB_PIN_CCLK | BB_PIN_PROG,
334 BB_PIN_CCLK | BB_PIN_PROG,
346 /* Section 2. part 1), do the FPGA suicide. */
347 sigma_write(suicide, sizeof(suicide), devc);
348 sigma_write(suicide, sizeof(suicide), devc);
349 sigma_write(suicide, sizeof(suicide), devc);
350 sigma_write(suicide, sizeof(suicide), devc);
352 /* Section 2. part 2), pulse PROG. */
353 sigma_write(init_array, sizeof(init_array), devc);
354 ftdi_usb_purge_buffers(&devc->ftdic);
356 /* Wait until the FPGA asserts INIT_B. */
359 ret = sigma_read(&data, 1, devc);
362 if (data & BB_PIN_INIT)
367 return SR_ERR_TIMEOUT;
371 * Configure the FPGA for logic-analyzer mode.
373 static int sigma_fpga_init_la(struct dev_context *devc)
376 * TODO Construct the sequence at runtime? Such that request data
377 * and response check values will match more apparently?
379 uint8_t mode_regval = WMR_SDRAMINIT;
380 uint8_t logic_mode_start[] = {
381 /* Read ID register. */
382 REG_ADDR_LOW | (READ_ID & 0xf),
383 REG_ADDR_HIGH | (READ_ID >> 4),
386 /* Write 0x55 to scratch register, read back. */
387 REG_ADDR_LOW | (WRITE_TEST & 0xf),
389 REG_DATA_HIGH_WRITE | 0x5,
392 /* Write 0xaa to scratch register, read back. */
394 REG_DATA_HIGH_WRITE | 0xa,
397 /* Initiate SDRAM initialization in mode register. */
398 REG_ADDR_LOW | (WRITE_MODE & 0xf),
399 REG_DATA_LOW | (mode_regval & 0xf),
400 REG_DATA_HIGH_WRITE | (mode_regval >> 4),
406 * Send the command sequence which contains 3 READ requests.
407 * Expect to see the corresponding 3 response bytes.
409 sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
410 ret = sigma_read(result, ARRAY_SIZE(result), devc);
411 if (ret != ARRAY_SIZE(result))
413 if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
419 sr_err("Configuration failed. Invalid reply received.");
424 * Read the firmware from a file and transform it into a series of bitbang
425 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
426 * by the caller of this function.
428 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
429 uint8_t **bb_cmd, gsize *bb_cmd_size)
437 uint8_t *bb_stream, *bbs, byte, mask, v;
439 /* Retrieve the on-disk firmware file content. */
440 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
441 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
445 /* Unscramble the file content (XOR with "random" sequence). */
450 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
455 * Generate a sequence of bitbang samples. With two samples per
456 * FPGA configuration bit, providing the level for the DIN signal
457 * as well as two edges for CCLK. See Xilinx UG332 for details
458 * ("slave serial" mode).
460 * Note that CCLK is inverted in hardware. That's why the
461 * respective bit is first set and then cleared in the bitbang
462 * sample sets. So that the DIN level will be stable when the
463 * data gets sampled at the rising CCLK edge, and the signals'
464 * setup time constraint will be met.
466 * The caller will put the FPGA into download mode, will send
467 * the bitbang samples, and release the allocated memory.
469 bb_size = file_size * 8 * 2;
470 bb_stream = g_try_malloc(bb_size);
472 sr_err("%s: Failed to allocate bitbang stream", __func__);
474 return SR_ERR_MALLOC;
483 v = (byte & mask) ? BB_PIN_DIN : 0;
485 *bbs++ = v | BB_PIN_CCLK;
491 /* The transformation completed successfully, return the result. */
493 *bb_cmd_size = bb_size;
498 static int upload_firmware(struct sr_context *ctx,
499 int firmware_idx, struct dev_context *devc)
505 const char *firmware;
507 /* Avoid downloading the same firmware multiple times. */
508 firmware = firmware_files[firmware_idx];
509 if (devc->cur_firmware == firmware_idx) {
510 sr_info("Not uploading firmware file '%s' again.", firmware);
514 /* Set the cable to bitbang mode. */
515 ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
517 sr_err("ftdi_set_bitmode failed: %s",
518 ftdi_get_error_string(&devc->ftdic));
521 ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
523 sr_err("ftdi_set_baudrate failed: %s",
524 ftdi_get_error_string(&devc->ftdic));
528 /* Initiate FPGA configuration mode. */
529 ret = sigma_fpga_init_bitbang(devc);
533 /* Prepare wire format of the firmware image. */
534 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
536 sr_err("An error occurred while reading the firmware: %s",
541 /* Write the FPGA netlist to the cable. */
542 sr_info("Uploading firmware file '%s'.", firmware);
543 sigma_write(buf, buf_size, devc);
547 /* Leave bitbang mode and discard pending input data. */
548 ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
550 sr_err("ftdi_set_bitmode failed: %s",
551 ftdi_get_error_string(&devc->ftdic));
554 ftdi_usb_purge_buffers(&devc->ftdic);
555 while (sigma_read(&pins, 1, devc) == 1)
558 /* Initialize the FPGA for logic-analyzer mode. */
559 ret = sigma_fpga_init_la(devc);
563 /* Keep track of successful firmware download completion. */
564 devc->cur_firmware = firmware_idx;
565 sr_info("Firmware uploaded.");
571 * Sigma doesn't support limiting the number of samples, so we have to
572 * translate the number and the samplerate to an elapsed time.
574 * In addition we need to ensure that the last data cluster has passed
575 * the hardware pipeline, and became available to the PC side. With RLE
576 * compression up to 327ms could pass before another cluster accumulates
577 * at 200kHz samplerate when input pins don't change.
579 SR_PRIV uint64_t sigma_limit_samples_to_msec(const struct dev_context *devc,
580 uint64_t limit_samples)
583 uint64_t worst_cluster_time_ms;
585 limit_msec = limit_samples * 1000 / devc->cur_samplerate;
586 worst_cluster_time_ms = 65536 * 1000 / devc->cur_samplerate;
588 * One cluster time is not enough to flush pipeline when sampling
589 * grounded pins with 1 sample limit at 200kHz. Hence the 2* fix.
591 return limit_msec + 2 * worst_cluster_time_ms;
594 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
596 struct dev_context *devc;
597 struct drv_context *drvc;
603 drvc = sdi->driver->context;
606 /* Reject rates that are not in the list of supported rates. */
607 for (i = 0; i < samplerates_count; i++) {
608 if (samplerates[i] == samplerate)
611 if (i >= samplerates_count || samplerates[i] == 0)
612 return SR_ERR_SAMPLERATE;
615 * Depending on the samplerates of 200/100/50- MHz, specific
616 * firmware is required and higher rates might limit the set
617 * of available channels.
619 num_channels = devc->num_channels;
620 if (samplerate <= SR_MHZ(50)) {
621 ret = upload_firmware(drvc->sr_ctx, 0, devc);
623 } else if (samplerate == SR_MHZ(100)) {
624 ret = upload_firmware(drvc->sr_ctx, 1, devc);
626 } else if (samplerate == SR_MHZ(200)) {
627 ret = upload_firmware(drvc->sr_ctx, 2, devc);
632 * Derive the sample period from the sample rate as well as the
633 * number of samples that the device will communicate within
634 * an "event" (memory organization internal to the device).
637 devc->num_channels = num_channels;
638 devc->cur_samplerate = samplerate;
639 devc->samples_per_event = 16 / devc->num_channels;
640 devc->state.state = SIGMA_IDLE;
644 * Support for "limit_samples" is implemented by stopping
645 * acquisition after a corresponding period of time.
646 * Re-calculate that period of time, in case the limit is
647 * set first and the samplerate gets (re-)configured later.
649 if (ret == SR_OK && devc->limit_samples) {
651 msecs = sigma_limit_samples_to_msec(devc, devc->limit_samples);
652 devc->limit_msec = msecs;
659 * Arrange for a session feed submit buffer. A queue where a number of
660 * samples gets accumulated to reduce the number of send calls. Which
661 * also enforces an optional sample count limit for data acquisition.
663 * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
664 * driver provides a fixed channel layout regardless of samplerate).
667 #define CHUNK_SIZE (4 * 1024 * 1024)
669 struct submit_buffer {
671 size_t max_samples, curr_samples;
672 uint8_t *sample_data;
673 uint8_t *write_pointer;
674 struct sr_dev_inst *sdi;
675 struct sr_datafeed_packet packet;
676 struct sr_datafeed_logic logic;
677 struct sr_sw_limits limit_samples;
680 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
682 struct dev_context *devc;
683 struct submit_buffer *buffer;
688 buffer = g_malloc0(sizeof(*buffer));
689 devc->buffer = buffer;
691 buffer->unit_size = sizeof(uint16_t);
693 size /= buffer->unit_size;
694 buffer->max_samples = size;
695 size *= buffer->unit_size;
696 buffer->sample_data = g_try_malloc0(size);
697 if (!buffer->sample_data)
698 return SR_ERR_MALLOC;
699 buffer->write_pointer = buffer->sample_data;
700 sr_sw_limits_init(&buffer->limit_samples);
703 memset(&buffer->logic, 0, sizeof(buffer->logic));
704 buffer->logic.unitsize = buffer->unit_size;
705 buffer->logic.data = buffer->sample_data;
706 memset(&buffer->packet, 0, sizeof(buffer->packet));
707 buffer->packet.type = SR_DF_LOGIC;
708 buffer->packet.payload = &buffer->logic;
713 static int setup_submit_buffer(struct dev_context *devc)
715 struct submit_buffer *buffer;
720 buffer = devc->buffer;
722 total = devc->limit_samples;
724 data = g_variant_new_uint64(total);
725 ret = sr_sw_limits_config_set(&buffer->limit_samples,
726 SR_CONF_LIMIT_SAMPLES, data);
727 g_variant_unref(data);
732 sr_sw_limits_acquisition_start(&buffer->limit_samples);
737 static void free_submit_buffer(struct dev_context *devc)
739 struct submit_buffer *buffer;
744 buffer = devc->buffer;
749 g_free(buffer->sample_data);
753 static int flush_submit_buffer(struct dev_context *devc)
755 struct submit_buffer *buffer;
758 buffer = devc->buffer;
760 /* Is queued sample data available? */
761 if (!buffer->curr_samples)
764 /* Submit to the session feed. */
765 buffer->logic.length = buffer->curr_samples * buffer->unit_size;
766 ret = sr_session_send(buffer->sdi, &buffer->packet);
770 /* Rewind queue position. */
771 buffer->curr_samples = 0;
772 buffer->write_pointer = buffer->sample_data;
777 static int addto_submit_buffer(struct dev_context *devc,
778 uint16_t sample, size_t count)
780 struct submit_buffer *buffer;
783 buffer = devc->buffer;
784 if (sr_sw_limits_check(&buffer->limit_samples))
788 * Individually accumulate and check each sample, such that
789 * accumulation between flushes won't exceed local storage, and
790 * enforcement of user specified limits is exact.
793 WL16(buffer->write_pointer, sample);
794 buffer->write_pointer += buffer->unit_size;
795 buffer->curr_samples++;
796 if (buffer->curr_samples == buffer->max_samples) {
797 ret = flush_submit_buffer(devc);
801 sr_sw_limits_update_samples_read(&buffer->limit_samples, 1);
802 if (sr_sw_limits_check(&buffer->limit_samples))
810 * In 100 and 200 MHz mode, only a single pin rising/falling can be
811 * set as trigger. In other modes, two rising/falling triggers can be set,
812 * in addition to value/mask trigger for any number of channels.
814 * The Sigma supports complex triggers using boolean expressions, but this
815 * has not been implemented yet.
817 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
819 struct dev_context *devc;
820 struct sr_trigger *trigger;
821 struct sr_trigger_stage *stage;
822 struct sr_trigger_match *match;
824 int channelbit, trigger_set;
827 memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
828 if (!(trigger = sr_session_trigger_get(sdi->session)))
832 for (l = trigger->stages; l; l = l->next) {
834 for (m = stage->matches; m; m = m->next) {
836 if (!match->channel->enabled)
837 /* Ignore disabled channels with a trigger. */
839 channelbit = 1 << (match->channel->index);
840 if (devc->cur_samplerate >= SR_MHZ(100)) {
841 /* Fast trigger support. */
843 sr_err("Only a single pin trigger is "
844 "supported in 100 and 200MHz mode.");
847 if (match->match == SR_TRIGGER_FALLING)
848 devc->trigger.fallingmask |= channelbit;
849 else if (match->match == SR_TRIGGER_RISING)
850 devc->trigger.risingmask |= channelbit;
852 sr_err("Only rising/falling trigger is "
853 "supported in 100 and 200MHz mode.");
859 /* Simple trigger support (event). */
860 if (match->match == SR_TRIGGER_ONE) {
861 devc->trigger.simplevalue |= channelbit;
862 devc->trigger.simplemask |= channelbit;
863 } else if (match->match == SR_TRIGGER_ZERO) {
864 devc->trigger.simplevalue &= ~channelbit;
865 devc->trigger.simplemask |= channelbit;
866 } else if (match->match == SR_TRIGGER_FALLING) {
867 devc->trigger.fallingmask |= channelbit;
869 } else if (match->match == SR_TRIGGER_RISING) {
870 devc->trigger.risingmask |= channelbit;
875 * Actually, Sigma supports 2 rising/falling triggers,
876 * but they are ORed and the current trigger syntax
877 * does not permit ORed triggers.
879 if (trigger_set > 1) {
880 sr_err("Only 1 rising/falling trigger "
891 /* Software trigger to determine exact trigger position. */
892 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
893 struct sigma_trigger *t)
898 for (i = 0; i < 8; i++) {
900 last_sample = sample;
901 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
903 /* Simple triggers. */
904 if ((sample & t->simplemask) != t->simplevalue)
908 if (((last_sample & t->risingmask) != 0) ||
909 ((sample & t->risingmask) != t->risingmask))
913 if ((last_sample & t->fallingmask) != t->fallingmask ||
914 (sample & t->fallingmask) != 0)
920 /* If we did not match, return original trigger pos. */
924 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
927 * Check whether the combination of this very sample and the
928 * previous state match the configured trigger condition. This
929 * improves the resolution of the trigger marker's position.
930 * The hardware provided position is coarse, and may point to
931 * a position before the actual match.
933 * See the previous get_trigger_offset() implementation. This
934 * code needs to get re-used here.
938 (void)get_trigger_offset;
943 static int check_and_submit_sample(struct dev_context *devc,
944 uint16_t sample, size_t count, gboolean check_trigger)
949 triggered = check_trigger && sample_matches_trigger(devc, sample);
951 ret = flush_submit_buffer(devc);
954 ret = std_session_send_df_trigger(devc->buffer->sdi);
959 ret = addto_submit_buffer(devc, sample, count);
967 * Return the timestamp of "DRAM cluster".
969 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
971 return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
975 * Return one 16bit data entity of a DRAM cluster at the specified index.
977 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
982 sample |= cl->samples[idx].sample_lo << 0;
983 sample |= cl->samples[idx].sample_hi << 8;
984 sample = (sample >> 8) | (sample << 8);
989 * Deinterlace sample data that was retrieved at 100MHz samplerate.
990 * One 16bit item contains two samples of 8bits each. The bits of
991 * multiple samples are interleaved.
993 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
999 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1000 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1001 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1002 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1003 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1004 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1005 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1006 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1011 * Deinterlace sample data that was retrieved at 200MHz samplerate.
1012 * One 16bit item contains four samples of 4bits each. The bits of
1013 * multiple samples are interleaved.
1015 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1021 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1022 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1023 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1024 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1028 static void sigma_decode_dram_cluster(struct dev_context *devc,
1029 struct sigma_dram_cluster *dram_cluster,
1030 size_t events_in_cluster, gboolean triggered)
1032 struct sigma_state *ss;
1033 uint16_t tsdiff, ts, sample, item16;
1036 if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1040 * If this cluster is not adjacent to the previously received
1041 * cluster, then send the appropriate number of samples with the
1042 * previous values to the sigrok session. This "decodes RLE".
1044 * These samples cannot match the trigger since they just repeat
1045 * the previously submitted data pattern. (This assumption holds
1046 * for simple level and edge triggers. It would not for timed or
1047 * counted conditions, which currently are not supported.)
1050 ts = sigma_dram_cluster_ts(dram_cluster);
1051 tsdiff = ts - ss->lastts;
1054 count = tsdiff * devc->samples_per_event;
1055 (void)check_and_submit_sample(devc, ss->lastsample, count, FALSE);
1057 ss->lastts = ts + EVENTS_PER_CLUSTER;
1060 * Grab sample data from the current cluster and prepare their
1061 * submission to the session feed. Handle samplerate dependent
1062 * memory layout of sample data. Accumulation of data chunks
1063 * before submission is transparent to this code path, specific
1064 * buffer depth is neither assumed nor required here.
1067 for (i = 0; i < events_in_cluster; i++) {
1068 item16 = sigma_dram_cluster_data(dram_cluster, i);
1069 if (devc->cur_samplerate == SR_MHZ(200)) {
1070 sample = sigma_deinterlace_200mhz_data(item16, 0);
1071 check_and_submit_sample(devc, sample, 1, triggered);
1072 sample = sigma_deinterlace_200mhz_data(item16, 1);
1073 check_and_submit_sample(devc, sample, 1, triggered);
1074 sample = sigma_deinterlace_200mhz_data(item16, 2);
1075 check_and_submit_sample(devc, sample, 1, triggered);
1076 sample = sigma_deinterlace_200mhz_data(item16, 3);
1077 check_and_submit_sample(devc, sample, 1, triggered);
1078 } else if (devc->cur_samplerate == SR_MHZ(100)) {
1079 sample = sigma_deinterlace_100mhz_data(item16, 0);
1080 check_and_submit_sample(devc, sample, 1, triggered);
1081 sample = sigma_deinterlace_100mhz_data(item16, 1);
1082 check_and_submit_sample(devc, sample, 1, triggered);
1085 check_and_submit_sample(devc, sample, 1, triggered);
1088 ss->lastsample = sample;
1092 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1093 * Each event is 20ns apart, and can contain multiple samples.
1095 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1096 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1097 * For 50 MHz and below, events contain one sample for each channel,
1098 * spread 20 ns apart.
1100 static int decode_chunk_ts(struct dev_context *devc,
1101 struct sigma_dram_line *dram_line,
1102 size_t events_in_line, size_t trigger_event)
1104 struct sigma_dram_cluster *dram_cluster;
1105 unsigned int clusters_in_line;
1106 unsigned int events_in_cluster;
1108 uint32_t trigger_cluster;
1110 clusters_in_line = events_in_line;
1111 clusters_in_line += EVENTS_PER_CLUSTER - 1;
1112 clusters_in_line /= EVENTS_PER_CLUSTER;
1113 trigger_cluster = ~0;
1115 /* Check if trigger is in this chunk. */
1116 if (trigger_event < EVENTS_PER_ROW) {
1117 if (devc->cur_samplerate <= SR_MHZ(50)) {
1118 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1122 /* Find in which cluster the trigger occurred. */
1123 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1126 /* For each full DRAM cluster. */
1127 for (i = 0; i < clusters_in_line; i++) {
1128 dram_cluster = &dram_line->cluster[i];
1130 /* The last cluster might not be full. */
1131 if ((i == clusters_in_line - 1) &&
1132 (events_in_line % EVENTS_PER_CLUSTER)) {
1133 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1135 events_in_cluster = EVENTS_PER_CLUSTER;
1138 sigma_decode_dram_cluster(devc, dram_cluster,
1139 events_in_cluster, i == trigger_cluster);
1145 static int download_capture(struct sr_dev_inst *sdi)
1147 const uint32_t chunks_per_read = 32;
1149 struct dev_context *devc;
1150 struct sigma_dram_line *dram_line;
1152 uint32_t stoppos, triggerpos;
1155 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1156 uint32_t dl_first_line, dl_line;
1157 uint32_t dl_events_in_line;
1158 uint32_t trg_line, trg_event;
1162 dl_events_in_line = EVENTS_PER_ROW;
1164 sr_info("Downloading sample data.");
1165 devc->state.state = SIGMA_DOWNLOAD;
1168 * Ask the hardware to stop data acquisition. Reception of the
1169 * FORCESTOP request makes the hardware "disable RLE" (store
1170 * clusters to DRAM regardless of whether pin state changes) and
1171 * raise the POSTTRIGGERED flag.
1173 sigma_set_register(WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN, devc);
1175 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1176 sr_err("failed while waiting for RMR_POSTTRIGGERED bit");
1179 } while (!(modestatus & RMR_POSTTRIGGERED));
1181 /* Set SDRAM Read Enable. */
1182 sigma_set_register(WRITE_MODE, WMR_SDRAMREADEN, devc);
1184 /* Get the current position. */
1185 sigma_read_pos(&stoppos, &triggerpos, devc);
1187 /* Check if trigger has fired. */
1188 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1189 sr_err("failed to read READ_MODE register");
1194 if (modestatus & RMR_TRIGGERED) {
1195 trg_line = triggerpos >> 9;
1196 trg_event = triggerpos & 0x1ff;
1199 devc->sent_samples = 0;
1202 * Determine how many "DRAM lines" of 1024 bytes each we need to
1203 * retrieve from the Sigma hardware, so that we have a complete
1204 * set of samples. Note that the last line need not contain 64
1205 * clusters, it might be partially filled only.
1207 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1208 * around. Since the status of the very next line is uncertain in
1209 * that case, we skip it and start reading from the next line.
1212 dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1213 if (modestatus & RMR_ROUND) {
1214 dl_first_line = dl_lines_total + 1;
1215 dl_lines_total = ROW_COUNT - 2;
1217 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1220 ret = alloc_submit_buffer(sdi);
1223 ret = setup_submit_buffer(devc);
1227 while (dl_lines_total > dl_lines_done) {
1228 /* We can download only up-to 32 DRAM lines in one go! */
1229 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1231 dl_line = dl_first_line + dl_lines_done;
1232 dl_line %= ROW_COUNT;
1233 bufsz = sigma_read_dram(dl_line, dl_lines_curr,
1234 (uint8_t *)dram_line, devc);
1235 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1238 /* This is the first DRAM line, so find the initial timestamp. */
1239 if (dl_lines_done == 0) {
1240 devc->state.lastts =
1241 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1242 devc->state.lastsample = 0;
1245 for (i = 0; i < dl_lines_curr; i++) {
1246 uint32_t trigger_event = ~0;
1247 /* The last "DRAM line" can be only partially full. */
1248 if (dl_lines_done + i == dl_lines_total - 1)
1249 dl_events_in_line = stoppos & 0x1ff;
1251 /* Test if the trigger happened on this line. */
1252 if (dl_lines_done + i == trg_line)
1253 trigger_event = trg_event;
1255 decode_chunk_ts(devc, dram_line + i,
1256 dl_events_in_line, trigger_event);
1259 dl_lines_done += dl_lines_curr;
1261 flush_submit_buffer(devc);
1262 free_submit_buffer(devc);
1265 std_session_send_df_end(sdi);
1267 devc->state.state = SIGMA_IDLE;
1268 sr_dev_acquisition_stop(sdi);
1274 * Periodically check the Sigma status when in CAPTURE mode. This routine
1275 * checks whether the configured sample count or sample time have passed,
1276 * and will stop acquisition and download the acquired samples.
1278 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1280 struct dev_context *devc;
1281 uint64_t running_msec;
1282 uint64_t current_time;
1287 * Check if the selected sampling duration passed. Sample count
1288 * limits are covered by this enforced timeout as well.
1290 current_time = g_get_monotonic_time();
1291 running_msec = (current_time - devc->start_time) / 1000;
1292 if (running_msec >= devc->limit_msec)
1293 return download_capture(sdi);
1298 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1300 struct sr_dev_inst *sdi;
1301 struct dev_context *devc;
1309 if (devc->state.state == SIGMA_IDLE)
1313 * When the application has requested to stop the acquisition,
1314 * then immediately start downloading sample data. Otherwise
1315 * keep checking configured limits which will terminate the
1316 * acquisition and initiate download.
1318 if (devc->state.state == SIGMA_STOPPING)
1319 return download_capture(sdi);
1320 if (devc->state.state == SIGMA_CAPTURE)
1321 return sigma_capture_mode(sdi);
1326 /* Build a LUT entry used by the trigger functions. */
1327 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1331 /* For each quad channel. */
1332 for (i = 0; i < 4; i++) {
1335 /* For each bit in LUT. */
1336 for (j = 0; j < 16; j++)
1338 /* For each channel in quad. */
1339 for (k = 0; k < 4; k++) {
1340 bit = 1 << (i * 4 + k);
1342 /* Set bit in entry */
1343 if ((mask & bit) && ((!(value & bit)) !=
1345 entry[i] &= ~(1 << j);
1350 /* Add a logical function to LUT mask. */
1351 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1352 int index, int neg, uint16_t *mask)
1355 int x[2][2], tmp, a, b, aset, bset, rset;
1357 memset(x, 0, 4 * sizeof(int));
1359 /* Trigger detect condition. */
1389 case OP_NOTRISEFALL:
1395 /* Transpose if neg is set. */
1397 for (i = 0; i < 2; i++) {
1398 for (j = 0; j < 2; j++) {
1400 x[i][j] = x[1 - i][1 - j];
1401 x[1 - i][1 - j] = tmp;
1406 /* Update mask with function. */
1407 for (i = 0; i < 16; i++) {
1408 a = (i >> (2 * index + 0)) & 1;
1409 b = (i >> (2 * index + 1)) & 1;
1411 aset = (*mask >> i) & 1;
1415 if (func == FUNC_AND || func == FUNC_NAND)
1417 else if (func == FUNC_OR || func == FUNC_NOR)
1419 else if (func == FUNC_XOR || func == FUNC_NXOR)
1422 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1433 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1434 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1435 * set at any time, but a full mask and value can be set (0/1).
1437 SR_PRIV int sigma_build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1440 uint16_t masks[2] = { 0, 0 };
1442 memset(lut, 0, sizeof(struct triggerlut));
1444 /* Constant for simple triggers. */
1447 /* Value/mask trigger support. */
1448 build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1451 /* Rise/fall trigger support. */
1452 for (i = 0, j = 0; i < 16; i++) {
1453 if (devc->trigger.risingmask & (1 << i) ||
1454 devc->trigger.fallingmask & (1 << i))
1455 masks[j++] = 1 << i;
1458 build_lut_entry(masks[0], masks[0], lut->m0d);
1459 build_lut_entry(masks[1], masks[1], lut->m1d);
1461 /* Add glue logic */
1462 if (masks[0] || masks[1]) {
1463 /* Transition trigger. */
1464 if (masks[0] & devc->trigger.risingmask)
1465 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1466 if (masks[0] & devc->trigger.fallingmask)
1467 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1468 if (masks[1] & devc->trigger.risingmask)
1469 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1470 if (masks[1] & devc->trigger.fallingmask)
1471 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1473 /* Only value/mask trigger. */
1477 /* Triggertype: event. */
1478 lut->params.selres = 3;