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>
7 * Copyright (C) 2020 Gerhard Sittig <gerhard.sittig@gmx.net>
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * ASIX SIGMA/SIGMA2 logic analyzer driver
31 * The ASIX SIGMA hardware supports fixed 200MHz and 100MHz sample rates
32 * (by means of separate firmware images). As well as 50MHz divided by
33 * an integer divider in the 1..256 range (by the "typical" firmware).
34 * Which translates to a strict lower boundary of around 195kHz.
36 * This driver "suggests" a subset of the available rates by listing a
37 * few discrete values, while setter routines accept any user specified
38 * rate that is supported by the hardware.
40 SR_PRIV const uint64_t samplerates[] = {
41 /* 50MHz and integer divider. 1/2/5 steps (where possible). */
42 SR_KHZ(200), SR_KHZ(500),
43 SR_MHZ(1), SR_MHZ(2), SR_MHZ(5),
44 SR_MHZ(10), SR_MHZ(25), SR_MHZ(50),
45 /* 100MHz/200MHz, fixed rates in special firmware. */
46 SR_MHZ(100), SR_MHZ(200),
49 SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
51 static const char *firmware_files[] = {
52 [SIGMA_FW_50MHZ] = "asix-sigma-50.fw", /* 50MHz, 8bit divider. */
53 [SIGMA_FW_100MHZ] = "asix-sigma-100.fw", /* 100MHz, fixed. */
54 [SIGMA_FW_200MHZ] = "asix-sigma-200.fw", /* 200MHz, fixed. */
55 [SIGMA_FW_SYNC] = "asix-sigma-50sync.fw", /* Sync from external pin. */
56 [SIGMA_FW_FREQ] = "asix-sigma-phasor.fw", /* Frequency counter. */
59 #define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
61 static int sigma_read(struct dev_context *devc, void *buf, size_t size)
65 ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
67 sr_err("ftdi_read_data failed: %s",
68 ftdi_get_error_string(&devc->ftdic));
74 static int sigma_write(struct dev_context *devc, const void *buf, size_t size)
78 ret = ftdi_write_data(&devc->ftdic, buf, size);
80 sr_err("ftdi_write_data failed: %s",
81 ftdi_get_error_string(&devc->ftdic));
82 else if ((size_t) ret != size)
83 sr_err("ftdi_write_data did not complete write.");
89 * NOTE: We chose the buffer size to be large enough to hold any write to the
90 * device. We still print a message just in case.
92 SR_PRIV int sigma_write_register(struct dev_context *devc,
93 uint8_t reg, uint8_t *data, size_t len)
95 uint8_t buf[80], *wrptr;
99 if (2 + 2 * len > sizeof(buf)) {
100 sr_err("Write buffer too small to write %zu bytes.", len);
105 write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
106 write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
107 for (idx = 0; idx < len; idx++) {
108 write_u8_inc(&wrptr, REG_DATA_LOW | (data[idx] & 0xf));
109 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data[idx] >> 4));
112 ret = sigma_write(devc, buf, count);
119 SR_PRIV int sigma_set_register(struct dev_context *devc,
120 uint8_t reg, uint8_t value)
122 return sigma_write_register(devc, reg, &value, sizeof(value));
125 static int sigma_read_register(struct dev_context *devc,
126 uint8_t reg, uint8_t *data, size_t len)
128 uint8_t buf[3], *wrptr;
131 write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
132 write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
133 write_u8_inc(&wrptr, REG_READ_ADDR);
134 sigma_write(devc, buf, wrptr - buf);
136 return sigma_read(devc, data, len);
139 static int sigma_read_pos(struct dev_context *devc,
140 uint32_t *stoppos, uint32_t *triggerpos)
143 * Read 6 registers starting at trigger position LSB.
144 * Which yields two 24bit counter values.
146 const uint8_t buf[] = {
147 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
148 REG_READ_ADDR | REG_ADDR_INC,
149 REG_READ_ADDR | REG_ADDR_INC,
150 REG_READ_ADDR | REG_ADDR_INC,
151 REG_READ_ADDR | REG_ADDR_INC,
152 REG_READ_ADDR | REG_ADDR_INC,
153 REG_READ_ADDR | REG_ADDR_INC,
157 sigma_write(devc, buf, sizeof(buf));
159 sigma_read(devc, result, sizeof(result));
162 *triggerpos = read_u24le_inc(&rdptr);
163 *stoppos = read_u24le_inc(&rdptr);
166 * These positions consist of "the memory row" in the MSB fields,
167 * and "an event index" within the row in the LSB fields. Part
168 * of the memory row's content is sample data, another part is
171 * The retrieved register values point to after the captured
172 * position. So they need to get decremented, and adjusted to
173 * cater for the timestamps when the decrement carries over to
174 * a different memory row.
176 if ((--*stoppos & ROW_MASK) == ROW_MASK)
177 *stoppos -= CLUSTERS_PER_ROW;
178 if ((--*triggerpos & ROW_MASK) == ROW_MASK)
179 *triggerpos -= CLUSTERS_PER_ROW;
184 static int sigma_read_dram(struct dev_context *devc,
185 uint16_t startchunk, size_t numchunks, uint8_t *data)
187 uint8_t buf[128], *wrptr;
192 if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
193 sr_err("Read buffer too small to read %zu DRAM rows", numchunks);
197 /* Communicate DRAM start address (memory row, aka samples line). */
199 write_u8_inc(&wrptr, startchunk >> 8);
200 write_u8_inc(&wrptr, startchunk & 0xff);
201 sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
204 * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
205 * then transfer via USB. Interleave the FPGA's DRAM access and
206 * USB transfer, use alternating buffers (0/1) in the process.
209 write_u8_inc(&wrptr, REG_DRAM_BLOCK);
210 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
211 for (chunk = 0; chunk < numchunks; chunk++) {
213 is_last = chunk == numchunks - 1;
215 write_u8_inc(&wrptr, REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel));
216 write_u8_inc(&wrptr, REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel));
218 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
220 sigma_write(devc, buf, wrptr - buf);
222 return sigma_read(devc, data, numchunks * ROW_LENGTH_BYTES);
225 /* Upload trigger look-up tables to Sigma. */
226 SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
227 struct triggerlut *lut)
232 uint8_t buf[6], *wrptr, regval;
234 /* Transpose the table and send to Sigma. */
235 for (i = 0; i < 16; i++) {
240 if (lut->m2d[0] & bit)
242 if (lut->m2d[1] & bit)
244 if (lut->m2d[2] & bit)
246 if (lut->m2d[3] & bit)
256 if (lut->m0d[0] & bit)
258 if (lut->m0d[1] & bit)
260 if (lut->m0d[2] & bit)
262 if (lut->m0d[3] & bit)
265 if (lut->m1d[0] & bit)
267 if (lut->m1d[1] & bit)
269 if (lut->m1d[2] & bit)
271 if (lut->m1d[3] & bit)
275 * This logic seems redundant, but separates the value
276 * determination from the wire format, and is useful
277 * during future maintenance and research.
280 write_u8_inc(&wrptr, tmp[0]);
281 write_u8_inc(&wrptr, tmp[1]);
282 sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
283 sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x30 | i);
286 /* Send the parameters */
289 regval |= lut->params.selc << 6;
290 regval |= lut->params.selpresc << 0;
291 write_u8_inc(&wrptr, regval);
293 regval |= lut->params.selinc << 6;
294 regval |= lut->params.selres << 4;
295 regval |= lut->params.sela << 2;
296 regval |= lut->params.selb << 0;
297 write_u8_inc(&wrptr, regval);
298 write_u16le_inc(&wrptr, lut->params.cmpb);
299 write_u16le_inc(&wrptr, lut->params.cmpa);
300 sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
306 * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
307 * uses FTDI bitbang mode for netlist download in slave serial mode.
308 * (LATER: The OMEGA device's cable contains a more capable FTDI chip
309 * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
310 * compatible bitbang mode? For maximum code re-use and reduced libftdi
311 * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
312 * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
314 * 750kbps rate (four times the speed of sigmalogan) works well for
315 * netlist download. All pins except INIT_B are output pins during
316 * configuration download.
318 * Some pins are inverted as a byproduct of level shifting circuitry.
319 * That's why high CCLK level (from the cable's point of view) is idle
320 * from the FPGA's perspective.
322 * The vendor's literature discusses a "suicide sequence" which ends
323 * regular FPGA execution and should be sent before entering bitbang
324 * mode and sending configuration data. Set D7 and toggle D2, D3, D4
327 #define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
328 #define BB_PIN_PROG (1 << 1) /* D1, PROG */
329 #define BB_PIN_D2 (1 << 2) /* D2, (part of) SUICIDE */
330 #define BB_PIN_D3 (1 << 3) /* D3, (part of) SUICIDE */
331 #define BB_PIN_D4 (1 << 4) /* D4, (part of) SUICIDE (unused?) */
332 #define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
333 #define BB_PIN_DIN (1 << 6) /* D6, DIN */
334 #define BB_PIN_D7 (1 << 7) /* D7, (part of) SUICIDE */
336 #define BB_BITRATE (750 * 1000)
337 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
340 * Initiate slave serial mode for configuration download. Which is done
341 * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
342 * initiating the configuration download.
344 * Run a "suicide sequence" first to terminate the regular FPGA operation
345 * before reconfiguration. The FTDI cable is single channel, and shares
346 * pins which are used for data communication in FIFO mode with pins that
347 * are used for FPGA configuration in bitbang mode. Hardware defaults for
348 * unconfigured hardware, and runtime conditions after FPGA configuration
349 * need to cooperate such that re-configuration of the FPGA can start.
351 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
353 const uint8_t suicide[] = {
354 BB_PIN_D7 | BB_PIN_D2,
355 BB_PIN_D7 | BB_PIN_D2,
356 BB_PIN_D7 | BB_PIN_D3,
357 BB_PIN_D7 | BB_PIN_D2,
358 BB_PIN_D7 | BB_PIN_D3,
359 BB_PIN_D7 | BB_PIN_D2,
360 BB_PIN_D7 | BB_PIN_D3,
361 BB_PIN_D7 | BB_PIN_D2,
363 const uint8_t init_array[] = {
365 BB_PIN_CCLK | BB_PIN_PROG,
366 BB_PIN_CCLK | BB_PIN_PROG,
378 /* Section 2. part 1), do the FPGA suicide. */
379 sigma_write(devc, suicide, sizeof(suicide));
380 sigma_write(devc, suicide, sizeof(suicide));
381 sigma_write(devc, suicide, sizeof(suicide));
382 sigma_write(devc, suicide, sizeof(suicide));
385 /* Section 2. part 2), pulse PROG. */
386 sigma_write(devc, init_array, sizeof(init_array));
388 ftdi_usb_purge_buffers(&devc->ftdic);
390 /* Wait until the FPGA asserts INIT_B. */
393 ret = sigma_read(devc, &data, sizeof(data));
396 if (data & BB_PIN_INIT)
401 return SR_ERR_TIMEOUT;
405 * This is belt and braces. Re-run the bitbang initiation sequence a few
406 * times should first attempts fail. Failure is rare but can happen (was
407 * observed during driver development).
409 static int sigma_fpga_init_bitbang(struct dev_context *devc)
416 ret = sigma_fpga_init_bitbang_once(devc);
419 if (ret != SR_ERR_TIMEOUT)
426 * Configure the FPGA for logic-analyzer mode.
428 static int sigma_fpga_init_la(struct dev_context *devc)
430 uint8_t buf[16], *wrptr;
431 uint8_t data_55, data_aa, mode;
433 const uint8_t *rdptr;
438 /* Read ID register. */
439 write_u8_inc(&wrptr, REG_ADDR_LOW | (READ_ID & 0xf));
440 write_u8_inc(&wrptr, REG_ADDR_HIGH | (READ_ID >> 4));
441 write_u8_inc(&wrptr, REG_READ_ADDR);
443 /* Write 0x55 to scratch register, read back. */
445 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
446 write_u8_inc(&wrptr, REG_DATA_LOW | (data_55 & 0xf));
447 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_55 >> 4));
448 write_u8_inc(&wrptr, REG_READ_ADDR);
450 /* Write 0xaa to scratch register, read back. */
452 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
453 write_u8_inc(&wrptr, REG_DATA_LOW | (data_aa & 0xf));
454 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_aa >> 4));
455 write_u8_inc(&wrptr, REG_READ_ADDR);
457 /* Initiate SDRAM initialization in mode register. */
458 mode = WMR_SDRAMINIT;
459 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_MODE & 0xf));
460 write_u8_inc(&wrptr, REG_DATA_LOW | (mode & 0xf));
461 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (mode >> 4));
464 * Send the command sequence which contains 3 READ requests.
465 * Expect to see the corresponding 3 response bytes.
467 sigma_write(devc, buf, wrptr - buf);
468 ret = sigma_read(devc, result, ARRAY_SIZE(result));
469 if (ret != ARRAY_SIZE(result)) {
470 sr_err("Insufficient start response length.");
474 if (read_u8_inc(&rdptr) != 0xa6) {
475 sr_err("Unexpected ID response.");
478 if (read_u8_inc(&rdptr) != data_55) {
479 sr_err("Unexpected scratch read-back (55).");
482 if (read_u8_inc(&rdptr) != data_aa) {
483 sr_err("Unexpected scratch read-back (aa).");
491 * Read the firmware from a file and transform it into a series of bitbang
492 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
493 * by the caller of this function.
495 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
496 uint8_t **bb_cmd, gsize *bb_cmd_size)
504 uint8_t *bb_stream, *bbs, byte, mask, v;
506 /* Retrieve the on-disk firmware file content. */
507 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
508 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
512 /* Unscramble the file content (XOR with "random" sequence). */
517 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
522 * Generate a sequence of bitbang samples. With two samples per
523 * FPGA configuration bit, providing the level for the DIN signal
524 * as well as two edges for CCLK. See Xilinx UG332 for details
525 * ("slave serial" mode).
527 * Note that CCLK is inverted in hardware. That's why the
528 * respective bit is first set and then cleared in the bitbang
529 * sample sets. So that the DIN level will be stable when the
530 * data gets sampled at the rising CCLK edge, and the signals'
531 * setup time constraint will be met.
533 * The caller will put the FPGA into download mode, will send
534 * the bitbang samples, and release the allocated memory.
536 bb_size = file_size * 8 * 2;
537 bb_stream = g_try_malloc(bb_size);
539 sr_err("%s: Failed to allocate bitbang stream", __func__);
541 return SR_ERR_MALLOC;
550 v = (byte & mask) ? BB_PIN_DIN : 0;
552 *bbs++ = v | BB_PIN_CCLK;
558 /* The transformation completed successfully, return the result. */
560 *bb_cmd_size = bb_size;
565 static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
566 enum sigma_firmware_idx firmware_idx)
572 const char *firmware;
574 /* Check for valid firmware file selection. */
575 if (firmware_idx >= ARRAY_SIZE(firmware_files))
577 firmware = firmware_files[firmware_idx];
578 if (!firmware || !*firmware)
581 /* Avoid downloading the same firmware multiple times. */
582 if (devc->firmware_idx == firmware_idx) {
583 sr_info("Not uploading firmware file '%s' again.", firmware);
587 devc->state.state = SIGMA_CONFIG;
589 /* Set the cable to bitbang mode. */
590 ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
592 sr_err("ftdi_set_bitmode failed: %s",
593 ftdi_get_error_string(&devc->ftdic));
596 ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
598 sr_err("ftdi_set_baudrate failed: %s",
599 ftdi_get_error_string(&devc->ftdic));
603 /* Initiate FPGA configuration mode. */
604 ret = sigma_fpga_init_bitbang(devc);
608 /* Prepare wire format of the firmware image. */
609 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
611 sr_err("Could not prepare file %s for download.", firmware);
615 /* Write the FPGA netlist to the cable. */
616 sr_info("Uploading firmware file '%s'.", firmware);
617 sigma_write(devc, buf, buf_size);
621 /* Leave bitbang mode and discard pending input data. */
622 ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
624 sr_err("ftdi_set_bitmode failed: %s",
625 ftdi_get_error_string(&devc->ftdic));
628 ftdi_usb_purge_buffers(&devc->ftdic);
629 while (sigma_read(devc, &pins, sizeof(pins)) > 0)
632 /* Initialize the FPGA for logic-analyzer mode. */
633 ret = sigma_fpga_init_la(devc);
637 /* Keep track of successful firmware download completion. */
638 devc->state.state = SIGMA_IDLE;
639 devc->firmware_idx = firmware_idx;
640 sr_info("Firmware uploaded.");
646 * The driver supports user specified time or sample count limits. The
647 * device's hardware supports neither, and hardware compression prevents
648 * reliable detection of "fill levels" (currently reached sample counts)
649 * from register values during acquisition. That's why the driver needs
650 * to apply some heuristics:
652 * - The (optional) sample count limit and the (normalized) samplerate
653 * get mapped to an estimated duration for these samples' acquisition.
654 * - The (optional) time limit gets checked as well. The lesser of the
655 * two limits will terminate the data acquisition phase. The exact
656 * sample count limit gets enforced in session feed submission paths.
657 * - Some slack needs to be given to account for hardware pipelines as
658 * well as late storage of last chunks after compression thresholds
659 * are tripped. The resulting data set will span at least the caller
660 * specified period of time, which shall be perfectly acceptable.
662 * With RLE compression active, up to 64K sample periods can pass before
663 * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
664 * times that period for good measure, one is not enough to flush the
665 * hardware pipeline (observation from an earlier experiment).
667 SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
671 uint64_t user_count, user_msecs;
672 uint64_t worst_cluster_time_ms;
673 uint64_t count_msecs, acquire_msecs;
675 sr_sw_limits_init(&devc->acq_limits);
677 /* Get sample count limit, convert to msecs. */
678 ret = sr_sw_limits_config_get(&devc->cfg_limits,
679 SR_CONF_LIMIT_SAMPLES, &data);
682 user_count = g_variant_get_uint64(data);
683 g_variant_unref(data);
686 count_msecs = 1000 * user_count / devc->samplerate + 1;
688 /* Get time limit, which is in msecs. */
689 ret = sr_sw_limits_config_get(&devc->cfg_limits,
690 SR_CONF_LIMIT_MSEC, &data);
693 user_msecs = g_variant_get_uint64(data);
694 g_variant_unref(data);
696 /* Get the lesser of them, with both being optional. */
697 acquire_msecs = ~0ull;
698 if (user_count && count_msecs < acquire_msecs)
699 acquire_msecs = count_msecs;
700 if (user_msecs && user_msecs < acquire_msecs)
701 acquire_msecs = user_msecs;
702 if (acquire_msecs == ~0ull)
705 /* Add some slack, and use that timeout for acquisition. */
706 worst_cluster_time_ms = 1000 * 65536 / devc->samplerate;
707 acquire_msecs += 2 * worst_cluster_time_ms;
708 data = g_variant_new_uint64(acquire_msecs);
709 ret = sr_sw_limits_config_set(&devc->acq_limits,
710 SR_CONF_LIMIT_MSEC, data);
711 g_variant_unref(data);
715 sr_sw_limits_acquisition_start(&devc->acq_limits);
720 * Check whether a caller specified samplerate matches the device's
721 * hardware constraints (can be used for acquisition). Optionally yield
722 * a value that approximates the original spec.
724 * This routine assumes that input specs are in the 200kHz to 200MHz
725 * range of supported rates, and callers typically want to normalize a
726 * given value to the hardware capabilities. Values in the 50MHz range
727 * get rounded up by default, to avoid a more expensive check for the
728 * closest match, while higher sampling rate is always desirable during
729 * measurement. Input specs which exactly match hardware capabilities
730 * remain unaffected. Because 100/200MHz rates also limit the number of
731 * available channels, they are not suggested by this routine, instead
732 * callers need to pick them consciously.
734 SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
738 /* Accept exact matches for 100/200MHz. */
739 if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
741 *have_rate = want_rate;
745 /* Accept 200kHz to 50MHz range, and map to near value. */
746 if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
747 div = SR_MHZ(50) / want_rate;
748 rate = SR_MHZ(50) / div;
757 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
759 struct dev_context *devc;
760 struct drv_context *drvc;
766 drvc = sdi->driver->context;
768 /* Accept any caller specified rate which the hardware supports. */
769 ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
774 * Depending on the samplerates of 200/100/50- MHz, specific
775 * firmware is required and higher rates might limit the set
776 * of available channels.
778 num_channels = devc->num_channels;
779 if (samplerate <= SR_MHZ(50)) {
780 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
782 } else if (samplerate == SR_MHZ(100)) {
783 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
785 } else if (samplerate == SR_MHZ(200)) {
786 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
791 * The samplerate affects the number of available logic channels
792 * as well as a sample memory layout detail (the number of samples
793 * which the device will communicate within an "event").
796 devc->num_channels = num_channels;
797 devc->samples_per_event = 16 / devc->num_channels;
804 * Arrange for a session feed submit buffer. A queue where a number of
805 * samples gets accumulated to reduce the number of send calls. Which
806 * also enforces an optional sample count limit for data acquisition.
808 * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
809 * driver provides a fixed channel layout regardless of samplerate).
812 #define CHUNK_SIZE (4 * 1024 * 1024)
814 struct submit_buffer {
816 size_t max_samples, curr_samples;
817 uint8_t *sample_data;
818 uint8_t *write_pointer;
819 struct sr_dev_inst *sdi;
820 struct sr_datafeed_packet packet;
821 struct sr_datafeed_logic logic;
824 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
826 struct dev_context *devc;
827 struct submit_buffer *buffer;
832 buffer = g_malloc0(sizeof(*buffer));
833 devc->buffer = buffer;
835 buffer->unit_size = sizeof(uint16_t);
837 size /= buffer->unit_size;
838 buffer->max_samples = size;
839 size *= buffer->unit_size;
840 buffer->sample_data = g_try_malloc0(size);
841 if (!buffer->sample_data)
842 return SR_ERR_MALLOC;
843 buffer->write_pointer = buffer->sample_data;
844 sr_sw_limits_init(&devc->feed_limits);
847 memset(&buffer->logic, 0, sizeof(buffer->logic));
848 buffer->logic.unitsize = buffer->unit_size;
849 buffer->logic.data = buffer->sample_data;
850 memset(&buffer->packet, 0, sizeof(buffer->packet));
851 buffer->packet.type = SR_DF_LOGIC;
852 buffer->packet.payload = &buffer->logic;
857 static int setup_submit_limit(struct dev_context *devc)
859 struct sr_sw_limits *limits;
864 limits = &devc->feed_limits;
866 ret = sr_sw_limits_config_get(&devc->cfg_limits,
867 SR_CONF_LIMIT_SAMPLES, &data);
870 total = g_variant_get_uint64(data);
871 g_variant_unref(data);
873 sr_sw_limits_init(limits);
875 data = g_variant_new_uint64(total);
876 ret = sr_sw_limits_config_set(limits,
877 SR_CONF_LIMIT_SAMPLES, data);
878 g_variant_unref(data);
883 sr_sw_limits_acquisition_start(limits);
888 static void free_submit_buffer(struct dev_context *devc)
890 struct submit_buffer *buffer;
895 buffer = devc->buffer;
900 g_free(buffer->sample_data);
904 static int flush_submit_buffer(struct dev_context *devc)
906 struct submit_buffer *buffer;
909 buffer = devc->buffer;
911 /* Is queued sample data available? */
912 if (!buffer->curr_samples)
915 /* Submit to the session feed. */
916 buffer->logic.length = buffer->curr_samples * buffer->unit_size;
917 ret = sr_session_send(buffer->sdi, &buffer->packet);
921 /* Rewind queue position. */
922 buffer->curr_samples = 0;
923 buffer->write_pointer = buffer->sample_data;
928 static int addto_submit_buffer(struct dev_context *devc,
929 uint16_t sample, size_t count)
931 struct submit_buffer *buffer;
932 struct sr_sw_limits *limits;
935 buffer = devc->buffer;
936 limits = &devc->feed_limits;
937 if (sr_sw_limits_check(limits))
941 * Individually accumulate and check each sample, such that
942 * accumulation between flushes won't exceed local storage, and
943 * enforcement of user specified limits is exact.
946 write_u16le_inc(&buffer->write_pointer, sample);
947 buffer->curr_samples++;
948 if (buffer->curr_samples == buffer->max_samples) {
949 ret = flush_submit_buffer(devc);
953 sr_sw_limits_update_samples_read(limits, 1);
954 if (sr_sw_limits_check(limits))
962 * In 100 and 200 MHz mode, only a single pin rising/falling can be
963 * set as trigger. In other modes, two rising/falling triggers can be set,
964 * in addition to value/mask trigger for any number of channels.
966 * The Sigma supports complex triggers using boolean expressions, but this
967 * has not been implemented yet.
969 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
971 struct dev_context *devc;
972 struct sr_trigger *trigger;
973 struct sr_trigger_stage *stage;
974 struct sr_trigger_match *match;
976 int channelbit, trigger_set;
979 memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
980 if (!(trigger = sr_session_trigger_get(sdi->session)))
984 for (l = trigger->stages; l; l = l->next) {
986 for (m = stage->matches; m; m = m->next) {
988 /* Ignore disabled channels with a trigger. */
989 if (!match->channel->enabled)
991 channelbit = 1 << match->channel->index;
992 if (devc->samplerate >= SR_MHZ(100)) {
993 /* Fast trigger support. */
995 sr_err("Only a single pin trigger is "
996 "supported in 100 and 200MHz mode.");
999 if (match->match == SR_TRIGGER_FALLING) {
1000 devc->trigger.fallingmask |= channelbit;
1001 } else if (match->match == SR_TRIGGER_RISING) {
1002 devc->trigger.risingmask |= channelbit;
1004 sr_err("Only rising/falling trigger is "
1005 "supported in 100 and 200MHz mode.");
1011 /* Simple trigger support (event). */
1012 if (match->match == SR_TRIGGER_ONE) {
1013 devc->trigger.simplevalue |= channelbit;
1014 devc->trigger.simplemask |= channelbit;
1015 } else if (match->match == SR_TRIGGER_ZERO) {
1016 devc->trigger.simplevalue &= ~channelbit;
1017 devc->trigger.simplemask |= channelbit;
1018 } else if (match->match == SR_TRIGGER_FALLING) {
1019 devc->trigger.fallingmask |= channelbit;
1021 } else if (match->match == SR_TRIGGER_RISING) {
1022 devc->trigger.risingmask |= channelbit;
1027 * Actually, Sigma supports 2 rising/falling triggers,
1028 * but they are ORed and the current trigger syntax
1029 * does not permit ORed triggers.
1031 if (trigger_set > 1) {
1032 sr_err("Only 1 rising/falling trigger is supported.");
1042 /* Software trigger to determine exact trigger position. */
1043 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1044 struct sigma_trigger *t)
1046 const uint8_t *rdptr;
1052 for (i = 0; i < 8; i++) {
1054 last_sample = sample;
1055 sample = read_u16le_inc(&rdptr);
1057 /* Simple triggers. */
1058 if ((sample & t->simplemask) != t->simplevalue)
1062 if (((last_sample & t->risingmask) != 0) ||
1063 ((sample & t->risingmask) != t->risingmask))
1067 if ((last_sample & t->fallingmask) != t->fallingmask ||
1068 (sample & t->fallingmask) != 0)
1074 /* If we did not match, return original trigger pos. */
1078 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1081 * Check whether the combination of this very sample and the
1082 * previous state match the configured trigger condition. This
1083 * improves the resolution of the trigger marker's position.
1084 * The hardware provided position is coarse, and may point to
1085 * a position before the actual match.
1087 * See the previous get_trigger_offset() implementation. This
1088 * code needs to get re-used here.
1092 (void)get_trigger_offset;
1097 static int check_and_submit_sample(struct dev_context *devc,
1098 uint16_t sample, size_t count, gboolean check_trigger)
1103 triggered = check_trigger && sample_matches_trigger(devc, sample);
1105 ret = flush_submit_buffer(devc);
1108 ret = std_session_send_df_trigger(devc->buffer->sdi);
1113 ret = addto_submit_buffer(devc, sample, count);
1121 * Return the timestamp of "DRAM cluster".
1123 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1125 return read_u16le((const uint8_t *)&cluster->timestamp);
1129 * Return one 16bit data entity of a DRAM cluster at the specified index.
1131 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1133 return read_u16le((const uint8_t *)&cl->samples[idx]);
1137 * Deinterlace sample data that was retrieved at 100MHz samplerate.
1138 * One 16bit item contains two samples of 8bits each. The bits of
1139 * multiple samples are interleaved.
1141 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1147 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1148 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1149 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1150 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1151 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1152 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1153 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1154 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1159 * Deinterlace sample data that was retrieved at 200MHz samplerate.
1160 * One 16bit item contains four samples of 4bits each. The bits of
1161 * multiple samples are interleaved.
1163 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1169 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1170 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1171 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1172 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1176 static void sigma_decode_dram_cluster(struct dev_context *devc,
1177 struct sigma_dram_cluster *dram_cluster,
1178 size_t events_in_cluster, gboolean triggered)
1180 struct sigma_state *ss;
1181 uint16_t tsdiff, ts, sample, item16;
1184 if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1188 * If this cluster is not adjacent to the previously received
1189 * cluster, then send the appropriate number of samples with the
1190 * previous values to the sigrok session. This "decodes RLE".
1192 * These samples cannot match the trigger since they just repeat
1193 * the previously submitted data pattern. (This assumption holds
1194 * for simple level and edge triggers. It would not for timed or
1195 * counted conditions, which currently are not supported.)
1198 ts = sigma_dram_cluster_ts(dram_cluster);
1199 tsdiff = ts - ss->lastts;
1202 sample = ss->lastsample;
1203 count = tsdiff * devc->samples_per_event;
1204 (void)check_and_submit_sample(devc, sample, count, FALSE);
1206 ss->lastts = ts + EVENTS_PER_CLUSTER;
1209 * Grab sample data from the current cluster and prepare their
1210 * submission to the session feed. Handle samplerate dependent
1211 * memory layout of sample data. Accumulation of data chunks
1212 * before submission is transparent to this code path, specific
1213 * buffer depth is neither assumed nor required here.
1216 for (i = 0; i < events_in_cluster; i++) {
1217 item16 = sigma_dram_cluster_data(dram_cluster, i);
1218 if (devc->samplerate == SR_MHZ(200)) {
1219 sample = sigma_deinterlace_200mhz_data(item16, 0);
1220 check_and_submit_sample(devc, sample, 1, triggered);
1221 sample = sigma_deinterlace_200mhz_data(item16, 1);
1222 check_and_submit_sample(devc, sample, 1, triggered);
1223 sample = sigma_deinterlace_200mhz_data(item16, 2);
1224 check_and_submit_sample(devc, sample, 1, triggered);
1225 sample = sigma_deinterlace_200mhz_data(item16, 3);
1226 check_and_submit_sample(devc, sample, 1, triggered);
1227 } else if (devc->samplerate == SR_MHZ(100)) {
1228 sample = sigma_deinterlace_100mhz_data(item16, 0);
1229 check_and_submit_sample(devc, sample, 1, triggered);
1230 sample = sigma_deinterlace_100mhz_data(item16, 1);
1231 check_and_submit_sample(devc, sample, 1, triggered);
1234 check_and_submit_sample(devc, sample, 1, triggered);
1237 ss->lastsample = sample;
1241 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1242 * Each event is 20ns apart, and can contain multiple samples.
1244 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1245 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1246 * For 50 MHz and below, events contain one sample for each channel,
1247 * spread 20 ns apart.
1249 static int decode_chunk_ts(struct dev_context *devc,
1250 struct sigma_dram_line *dram_line,
1251 size_t events_in_line, size_t trigger_event)
1253 struct sigma_dram_cluster *dram_cluster;
1254 unsigned int clusters_in_line;
1255 unsigned int events_in_cluster;
1257 uint32_t trigger_cluster;
1259 clusters_in_line = events_in_line;
1260 clusters_in_line += EVENTS_PER_CLUSTER - 1;
1261 clusters_in_line /= EVENTS_PER_CLUSTER;
1262 trigger_cluster = ~0;
1264 /* Check if trigger is in this chunk. */
1265 if (trigger_event < EVENTS_PER_ROW) {
1266 if (devc->samplerate <= SR_MHZ(50)) {
1267 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1271 /* Find in which cluster the trigger occurred. */
1272 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1275 /* For each full DRAM cluster. */
1276 for (i = 0; i < clusters_in_line; i++) {
1277 dram_cluster = &dram_line->cluster[i];
1279 /* The last cluster might not be full. */
1280 if ((i == clusters_in_line - 1) &&
1281 (events_in_line % EVENTS_PER_CLUSTER)) {
1282 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1284 events_in_cluster = EVENTS_PER_CLUSTER;
1287 sigma_decode_dram_cluster(devc, dram_cluster,
1288 events_in_cluster, i == trigger_cluster);
1294 static int download_capture(struct sr_dev_inst *sdi)
1296 const uint32_t chunks_per_read = 32;
1298 struct dev_context *devc;
1299 struct sigma_dram_line *dram_line;
1301 uint32_t stoppos, triggerpos;
1304 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1305 uint32_t dl_first_line, dl_line;
1306 uint32_t dl_events_in_line;
1307 uint32_t trg_line, trg_event;
1311 dl_events_in_line = EVENTS_PER_ROW;
1313 sr_info("Downloading sample data.");
1314 devc->state.state = SIGMA_DOWNLOAD;
1317 * Ask the hardware to stop data acquisition. Reception of the
1318 * FORCESTOP request makes the hardware "disable RLE" (store
1319 * clusters to DRAM regardless of whether pin state changes) and
1320 * raise the POSTTRIGGERED flag.
1322 sigma_set_register(devc, WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN);
1324 ret = sigma_read_register(devc, READ_MODE,
1325 &modestatus, sizeof(modestatus));
1326 if (ret != sizeof(modestatus)) {
1327 sr_err("Could not poll for post-trigger condition.");
1330 } while (!(modestatus & RMR_POSTTRIGGERED));
1332 /* Set SDRAM Read Enable. */
1333 sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
1335 /* Get the current position. */
1336 sigma_read_pos(devc, &stoppos, &triggerpos);
1338 /* Check if trigger has fired. */
1339 ret = sigma_read_register(devc, READ_MODE,
1340 &modestatus, sizeof(modestatus));
1341 if (ret != sizeof(modestatus)) {
1342 sr_err("Could not query trigger hit.");
1347 if (modestatus & RMR_TRIGGERED) {
1348 trg_line = triggerpos >> ROW_SHIFT;
1349 trg_event = triggerpos & ROW_MASK;
1353 * Determine how many "DRAM lines" of 1024 bytes each we need to
1354 * retrieve from the Sigma hardware, so that we have a complete
1355 * set of samples. Note that the last line need not contain 64
1356 * clusters, it might be partially filled only.
1358 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1359 * around. Since the status of the very next line is uncertain in
1360 * that case, we skip it and start reading from the next line.
1363 dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1364 if (modestatus & RMR_ROUND) {
1365 dl_first_line = dl_lines_total + 1;
1366 dl_lines_total = ROW_COUNT - 2;
1368 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1371 ret = alloc_submit_buffer(sdi);
1374 ret = setup_submit_limit(devc);
1378 while (dl_lines_total > dl_lines_done) {
1379 /* We can download only up-to 32 DRAM lines in one go! */
1380 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1382 dl_line = dl_first_line + dl_lines_done;
1383 dl_line %= ROW_COUNT;
1384 bufsz = sigma_read_dram(devc, dl_line, dl_lines_curr,
1385 (uint8_t *)dram_line);
1386 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1389 /* This is the first DRAM line, so find the initial timestamp. */
1390 if (dl_lines_done == 0) {
1391 devc->state.lastts =
1392 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1393 devc->state.lastsample = 0;
1396 for (i = 0; i < dl_lines_curr; i++) {
1397 uint32_t trigger_event = ~0;
1398 /* The last "DRAM line" need not span its full length. */
1399 if (dl_lines_done + i == dl_lines_total - 1)
1400 dl_events_in_line = stoppos & ROW_MASK;
1402 /* Test if the trigger happened on this line. */
1403 if (dl_lines_done + i == trg_line)
1404 trigger_event = trg_event;
1406 decode_chunk_ts(devc, dram_line + i,
1407 dl_events_in_line, trigger_event);
1410 dl_lines_done += dl_lines_curr;
1412 flush_submit_buffer(devc);
1413 free_submit_buffer(devc);
1416 std_session_send_df_end(sdi);
1418 devc->state.state = SIGMA_IDLE;
1419 sr_dev_acquisition_stop(sdi);
1425 * Periodically check the Sigma status when in CAPTURE mode. This routine
1426 * checks whether the configured sample count or sample time have passed,
1427 * and will stop acquisition and download the acquired samples.
1429 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1431 struct dev_context *devc;
1434 if (sr_sw_limits_check(&devc->acq_limits))
1435 return download_capture(sdi);
1440 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1442 struct sr_dev_inst *sdi;
1443 struct dev_context *devc;
1451 if (devc->state.state == SIGMA_IDLE)
1455 * When the application has requested to stop the acquisition,
1456 * then immediately start downloading sample data. Otherwise
1457 * keep checking configured limits which will terminate the
1458 * acquisition and initiate download.
1460 if (devc->state.state == SIGMA_STOPPING)
1461 return download_capture(sdi);
1462 if (devc->state.state == SIGMA_CAPTURE)
1463 return sigma_capture_mode(sdi);
1468 /* Build a LUT entry used by the trigger functions. */
1469 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1473 /* For each quad channel. */
1474 for (i = 0; i < 4; i++) {
1477 /* For each bit in LUT. */
1478 for (j = 0; j < 16; j++) {
1480 /* For each channel in quad. */
1481 for (k = 0; k < 4; k++) {
1482 bit = 1 << (i * 4 + k);
1484 /* Set bit in entry */
1485 if ((mask & bit) && ((!(value & bit)) !=
1487 entry[i] &= ~(1 << j);
1493 /* Add a logical function to LUT mask. */
1494 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1495 int index, int neg, uint16_t *mask)
1498 int x[2][2], tmp, a, b, aset, bset, rset;
1500 memset(x, 0, 4 * sizeof(int));
1502 /* Trigger detect condition. */
1532 case OP_NOTRISEFALL:
1538 /* Transpose if neg is set. */
1540 for (i = 0; i < 2; i++) {
1541 for (j = 0; j < 2; j++) {
1543 x[i][j] = x[1 - i][1 - j];
1544 x[1 - i][1 - j] = tmp;
1549 /* Update mask with function. */
1550 for (i = 0; i < 16; i++) {
1551 a = (i >> (2 * index + 0)) & 1;
1552 b = (i >> (2 * index + 1)) & 1;
1554 aset = (*mask >> i) & 1;
1558 if (func == FUNC_AND || func == FUNC_NAND)
1560 else if (func == FUNC_OR || func == FUNC_NOR)
1562 else if (func == FUNC_XOR || func == FUNC_NXOR)
1565 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1576 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1577 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1578 * set at any time, but a full mask and value can be set (0/1).
1580 SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
1581 struct triggerlut *lut)
1584 uint16_t masks[2] = { 0, 0 };
1586 memset(lut, 0, sizeof(struct triggerlut));
1588 /* Constant for simple triggers. */
1591 /* Value/mask trigger support. */
1592 build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1595 /* Rise/fall trigger support. */
1596 for (i = 0, j = 0; i < 16; i++) {
1597 if (devc->trigger.risingmask & (1 << i) ||
1598 devc->trigger.fallingmask & (1 << i))
1599 masks[j++] = 1 << i;
1602 build_lut_entry(masks[0], masks[0], lut->m0d);
1603 build_lut_entry(masks[1], masks[1], lut->m1d);
1605 /* Add glue logic */
1606 if (masks[0] || masks[1]) {
1607 /* Transition trigger. */
1608 if (masks[0] & devc->trigger.risingmask)
1609 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1610 if (masks[0] & devc->trigger.fallingmask)
1611 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1612 if (masks[1] & devc->trigger.risingmask)
1613 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1614 if (masks[1] & devc->trigger.fallingmask)
1615 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1617 /* Only value/mask trigger. */
1621 /* Triggertype: event. */
1622 lut->params.selres = 3;