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(struct dev_context *devc, void *buf, size_t size)
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(struct dev_context *devc, const void *buf, size_t size)
77 ret = ftdi_write_data(&devc->ftdic, 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(struct dev_context *devc,
92 uint8_t reg, uint8_t *data, size_t len)
94 uint8_t buf[80], *wrptr;
98 if (2 + 2 * len > sizeof(buf)) {
99 sr_err("Write buffer too small to write %zu bytes.", len);
104 write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
105 write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
106 for (idx = 0; idx < len; idx++) {
107 write_u8_inc(&wrptr, REG_DATA_LOW | (data[idx] & 0xf));
108 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data[idx] >> 4));
111 ret = sigma_write(devc, buf, count);
118 SR_PRIV int sigma_set_register(struct dev_context *devc,
119 uint8_t reg, uint8_t value)
121 return sigma_write_register(devc, reg, &value, sizeof(value));
124 static int sigma_read_register(struct dev_context *devc,
125 uint8_t reg, uint8_t *data, size_t len)
127 uint8_t buf[3], *wrptr;
130 write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
131 write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
132 write_u8_inc(&wrptr, REG_READ_ADDR);
133 sigma_write(devc, buf, wrptr - buf);
135 return sigma_read(devc, data, len);
138 static int sigma_read_pos(struct dev_context *devc,
139 uint32_t *stoppos, uint32_t *triggerpos)
142 * Read 6 registers starting at trigger position LSB.
143 * Which yields two 24bit counter values.
145 const uint8_t buf[] = {
146 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
147 REG_READ_ADDR | REG_ADDR_INC,
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,
156 sigma_write(devc, buf, sizeof(buf));
158 sigma_read(devc, result, sizeof(result));
161 *triggerpos = read_u24le_inc(&rdptr);
162 *stoppos = read_u24le_inc(&rdptr);
165 * These positions consist of "the memory row" in the MSB fields,
166 * and "an event index" within the row in the LSB fields. Part
167 * of the memory row's content is sample data, another part is
170 * The retrieved register values point to after the captured
171 * position. So they need to get decremented, and adjusted to
172 * cater for the timestamps when the decrement carries over to
173 * a different memory row.
175 if ((--*stoppos & ROW_MASK) == ROW_MASK)
176 *stoppos -= CLUSTERS_PER_ROW;
177 if ((--*triggerpos & ROW_MASK) == ROW_MASK)
178 *triggerpos -= CLUSTERS_PER_ROW;
183 static int sigma_read_dram(struct dev_context *devc,
184 uint16_t startchunk, size_t numchunks, uint8_t *data)
186 uint8_t buf[128], *wrptr;
191 if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
192 sr_err("Read buffer too small to read %zu DRAM rows", numchunks);
196 /* Communicate DRAM start address (memory row, aka samples line). */
198 write_u8_inc(&wrptr, startchunk >> 8);
199 write_u8_inc(&wrptr, startchunk & 0xff);
200 sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
203 * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
204 * then transfer via USB. Interleave the FPGA's DRAM access and
205 * USB transfer, use alternating buffers (0/1) in the process.
208 write_u8_inc(&wrptr, REG_DRAM_BLOCK);
209 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
210 for (chunk = 0; chunk < numchunks; chunk++) {
212 is_last = chunk == numchunks - 1;
214 write_u8_inc(&wrptr, REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel));
215 write_u8_inc(&wrptr, REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel));
217 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
219 sigma_write(devc, buf, wrptr - buf);
221 return sigma_read(devc, data, numchunks * ROW_LENGTH_BYTES);
224 /* Upload trigger look-up tables to Sigma. */
225 SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
226 struct triggerlut *lut)
231 uint8_t buf[6], *wrptr, regval;
233 /* Transpose the table and send to Sigma. */
234 for (i = 0; i < 16; i++) {
239 if (lut->m2d[0] & bit)
241 if (lut->m2d[1] & bit)
243 if (lut->m2d[2] & bit)
245 if (lut->m2d[3] & bit)
255 if (lut->m0d[0] & bit)
257 if (lut->m0d[1] & bit)
259 if (lut->m0d[2] & bit)
261 if (lut->m0d[3] & bit)
264 if (lut->m1d[0] & bit)
266 if (lut->m1d[1] & bit)
268 if (lut->m1d[2] & bit)
270 if (lut->m1d[3] & bit)
274 * This logic seems redundant, but separates the value
275 * determination from the wire format, and is useful
276 * during future maintenance and research.
279 write_u8_inc(&wrptr, tmp[0]);
280 write_u8_inc(&wrptr, tmp[1]);
281 sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
282 sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x30 | i);
285 /* Send the parameters */
288 regval |= lut->params.selc << 6;
289 regval |= lut->params.selpresc << 0;
290 write_u8_inc(&wrptr, regval);
292 regval |= lut->params.selinc << 6;
293 regval |= lut->params.selres << 4;
294 regval |= lut->params.sela << 2;
295 regval |= lut->params.selb << 0;
296 write_u8_inc(&wrptr, regval);
297 write_u16le_inc(&wrptr, lut->params.cmpb);
298 write_u16le_inc(&wrptr, lut->params.cmpa);
299 sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
305 * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
306 * uses FTDI bitbang mode for netlist download in slave serial mode.
307 * (LATER: The OMEGA device's cable contains a more capable FTDI chip
308 * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
309 * compatible bitbang mode? For maximum code re-use and reduced libftdi
310 * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
311 * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
313 * 750kbps rate (four times the speed of sigmalogan) works well for
314 * netlist download. All pins except INIT_B are output pins during
315 * configuration download.
317 * Some pins are inverted as a byproduct of level shifting circuitry.
318 * That's why high CCLK level (from the cable's point of view) is idle
319 * from the FPGA's perspective.
321 * The vendor's literature discusses a "suicide sequence" which ends
322 * regular FPGA execution and should be sent before entering bitbang
323 * mode and sending configuration data. Set D7 and toggle D2, D3, D4
326 #define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
327 #define BB_PIN_PROG (1 << 1) /* D1, PROG */
328 #define BB_PIN_D2 (1 << 2) /* D2, (part of) SUICIDE */
329 #define BB_PIN_D3 (1 << 3) /* D3, (part of) SUICIDE */
330 #define BB_PIN_D4 (1 << 4) /* D4, (part of) SUICIDE (unused?) */
331 #define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
332 #define BB_PIN_DIN (1 << 6) /* D6, DIN */
333 #define BB_PIN_D7 (1 << 7) /* D7, (part of) SUICIDE */
335 #define BB_BITRATE (750 * 1000)
336 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
339 * Initiate slave serial mode for configuration download. Which is done
340 * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
341 * initiating the configuration download.
343 * Run a "suicide sequence" first to terminate the regular FPGA operation
344 * before reconfiguration. The FTDI cable is single channel, and shares
345 * pins which are used for data communication in FIFO mode with pins that
346 * are used for FPGA configuration in bitbang mode. Hardware defaults for
347 * unconfigured hardware, and runtime conditions after FPGA configuration
348 * need to cooperate such that re-configuration of the FPGA can start.
350 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
352 const uint8_t suicide[] = {
353 BB_PIN_D7 | BB_PIN_D2,
354 BB_PIN_D7 | BB_PIN_D2,
355 BB_PIN_D7 | BB_PIN_D3,
356 BB_PIN_D7 | BB_PIN_D2,
357 BB_PIN_D7 | BB_PIN_D3,
358 BB_PIN_D7 | BB_PIN_D2,
359 BB_PIN_D7 | BB_PIN_D3,
360 BB_PIN_D7 | BB_PIN_D2,
362 const uint8_t init_array[] = {
364 BB_PIN_CCLK | BB_PIN_PROG,
365 BB_PIN_CCLK | BB_PIN_PROG,
377 /* Section 2. part 1), do the FPGA suicide. */
378 sigma_write(devc, suicide, sizeof(suicide));
379 sigma_write(devc, suicide, sizeof(suicide));
380 sigma_write(devc, suicide, sizeof(suicide));
381 sigma_write(devc, suicide, sizeof(suicide));
384 /* Section 2. part 2), pulse PROG. */
385 sigma_write(devc, init_array, sizeof(init_array));
387 ftdi_usb_purge_buffers(&devc->ftdic);
389 /* Wait until the FPGA asserts INIT_B. */
392 ret = sigma_read(devc, &data, sizeof(data));
395 if (data & BB_PIN_INIT)
400 return SR_ERR_TIMEOUT;
404 * This is belt and braces. Re-run the bitbang initiation sequence a few
405 * times should first attempts fail. Failure is rare but can happen (was
406 * observed during driver development).
408 static int sigma_fpga_init_bitbang(struct dev_context *devc)
415 ret = sigma_fpga_init_bitbang_once(devc);
418 if (ret != SR_ERR_TIMEOUT)
425 * Configure the FPGA for logic-analyzer mode.
427 static int sigma_fpga_init_la(struct dev_context *devc)
429 uint8_t buf[16], *wrptr;
430 uint8_t data_55, data_aa, mode;
432 const uint8_t *rdptr;
437 /* Read ID register. */
438 write_u8_inc(&wrptr, REG_ADDR_LOW | (READ_ID & 0xf));
439 write_u8_inc(&wrptr, REG_ADDR_HIGH | (READ_ID >> 4));
440 write_u8_inc(&wrptr, REG_READ_ADDR);
442 /* Write 0x55 to scratch register, read back. */
444 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
445 write_u8_inc(&wrptr, REG_DATA_LOW | (data_55 & 0xf));
446 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_55 >> 4));
447 write_u8_inc(&wrptr, REG_READ_ADDR);
449 /* Write 0xaa to scratch register, read back. */
451 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
452 write_u8_inc(&wrptr, REG_DATA_LOW | (data_aa & 0xf));
453 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_aa >> 4));
454 write_u8_inc(&wrptr, REG_READ_ADDR);
456 /* Initiate SDRAM initialization in mode register. */
457 mode = WMR_SDRAMINIT;
458 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_MODE & 0xf));
459 write_u8_inc(&wrptr, REG_DATA_LOW | (mode & 0xf));
460 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (mode >> 4));
463 * Send the command sequence which contains 3 READ requests.
464 * Expect to see the corresponding 3 response bytes.
466 sigma_write(devc, buf, wrptr - buf);
467 ret = sigma_read(devc, result, ARRAY_SIZE(result));
468 if (ret != ARRAY_SIZE(result)) {
469 sr_err("Insufficient start response length.");
473 if (read_u8_inc(&rdptr) != 0xa6) {
474 sr_err("Unexpected ID response.");
477 if (read_u8_inc(&rdptr) != data_55) {
478 sr_err("Unexpected scratch read-back (55).");
481 if (read_u8_inc(&rdptr) != data_aa) {
482 sr_err("Unexpected scratch read-back (aa).");
490 * Read the firmware from a file and transform it into a series of bitbang
491 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
492 * by the caller of this function.
494 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
495 uint8_t **bb_cmd, gsize *bb_cmd_size)
503 uint8_t *bb_stream, *bbs, byte, mask, v;
505 /* Retrieve the on-disk firmware file content. */
506 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
507 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
511 /* Unscramble the file content (XOR with "random" sequence). */
516 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
521 * Generate a sequence of bitbang samples. With two samples per
522 * FPGA configuration bit, providing the level for the DIN signal
523 * as well as two edges for CCLK. See Xilinx UG332 for details
524 * ("slave serial" mode).
526 * Note that CCLK is inverted in hardware. That's why the
527 * respective bit is first set and then cleared in the bitbang
528 * sample sets. So that the DIN level will be stable when the
529 * data gets sampled at the rising CCLK edge, and the signals'
530 * setup time constraint will be met.
532 * The caller will put the FPGA into download mode, will send
533 * the bitbang samples, and release the allocated memory.
535 bb_size = file_size * 8 * 2;
536 bb_stream = g_try_malloc(bb_size);
538 sr_err("%s: Failed to allocate bitbang stream", __func__);
540 return SR_ERR_MALLOC;
549 v = (byte & mask) ? BB_PIN_DIN : 0;
551 *bbs++ = v | BB_PIN_CCLK;
557 /* The transformation completed successfully, return the result. */
559 *bb_cmd_size = bb_size;
564 static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
565 enum sigma_firmware_idx firmware_idx)
571 const char *firmware;
573 /* Check for valid firmware file selection. */
574 if (firmware_idx >= ARRAY_SIZE(firmware_files))
576 firmware = firmware_files[firmware_idx];
577 if (!firmware || !*firmware)
580 /* Avoid downloading the same firmware multiple times. */
581 if (devc->firmware_idx == firmware_idx) {
582 sr_info("Not uploading firmware file '%s' again.", firmware);
586 devc->state.state = SIGMA_CONFIG;
588 /* Set the cable to bitbang mode. */
589 ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
591 sr_err("ftdi_set_bitmode failed: %s",
592 ftdi_get_error_string(&devc->ftdic));
595 ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
597 sr_err("ftdi_set_baudrate failed: %s",
598 ftdi_get_error_string(&devc->ftdic));
602 /* Initiate FPGA configuration mode. */
603 ret = sigma_fpga_init_bitbang(devc);
607 /* Prepare wire format of the firmware image. */
608 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
610 sr_err("Could not prepare file %s for download.", firmware);
614 /* Write the FPGA netlist to the cable. */
615 sr_info("Uploading firmware file '%s'.", firmware);
616 sigma_write(devc, buf, buf_size);
620 /* Leave bitbang mode and discard pending input data. */
621 ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
623 sr_err("ftdi_set_bitmode failed: %s",
624 ftdi_get_error_string(&devc->ftdic));
627 ftdi_usb_purge_buffers(&devc->ftdic);
628 while (sigma_read(devc, &pins, sizeof(pins)) > 0)
631 /* Initialize the FPGA for logic-analyzer mode. */
632 ret = sigma_fpga_init_la(devc);
636 /* Keep track of successful firmware download completion. */
637 devc->state.state = SIGMA_IDLE;
638 devc->firmware_idx = firmware_idx;
639 sr_info("Firmware uploaded.");
645 * The driver supports user specified time or sample count limits. The
646 * device's hardware supports neither, and hardware compression prevents
647 * reliable detection of "fill levels" (currently reached sample counts)
648 * from register values during acquisition. That's why the driver needs
649 * to apply some heuristics:
651 * - The (optional) sample count limit and the (normalized) samplerate
652 * get mapped to an estimated duration for these samples' acquisition.
653 * - The (optional) time limit gets checked as well. The lesser of the
654 * two limits will terminate the data acquisition phase. The exact
655 * sample count limit gets enforced in session feed submission paths.
656 * - Some slack needs to be given to account for hardware pipelines as
657 * well as late storage of last chunks after compression thresholds
658 * are tripped. The resulting data set will span at least the caller
659 * specified period of time, which shall be perfectly acceptable.
661 * With RLE compression active, up to 64K sample periods can pass before
662 * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
663 * times that period for good measure, one is not enough to flush the
664 * hardware pipeline (observation from an earlier experiment).
666 SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
670 uint64_t user_count, user_msecs;
671 uint64_t worst_cluster_time_ms;
672 uint64_t count_msecs, acquire_msecs;
674 sr_sw_limits_init(&devc->acq_limits);
676 /* Get sample count limit, convert to msecs. */
677 ret = sr_sw_limits_config_get(&devc->cfg_limits,
678 SR_CONF_LIMIT_SAMPLES, &data);
681 user_count = g_variant_get_uint64(data);
682 g_variant_unref(data);
685 count_msecs = 1000 * user_count / devc->samplerate + 1;
687 /* Get time limit, which is in msecs. */
688 ret = sr_sw_limits_config_get(&devc->cfg_limits,
689 SR_CONF_LIMIT_MSEC, &data);
692 user_msecs = g_variant_get_uint64(data);
693 g_variant_unref(data);
695 /* Get the lesser of them, with both being optional. */
696 acquire_msecs = ~0ull;
697 if (user_count && count_msecs < acquire_msecs)
698 acquire_msecs = count_msecs;
699 if (user_msecs && user_msecs < acquire_msecs)
700 acquire_msecs = user_msecs;
701 if (acquire_msecs == ~0ull)
704 /* Add some slack, and use that timeout for acquisition. */
705 worst_cluster_time_ms = 1000 * 65536 / devc->samplerate;
706 acquire_msecs += 2 * worst_cluster_time_ms;
707 data = g_variant_new_uint64(acquire_msecs);
708 ret = sr_sw_limits_config_set(&devc->acq_limits,
709 SR_CONF_LIMIT_MSEC, data);
710 g_variant_unref(data);
714 sr_sw_limits_acquisition_start(&devc->acq_limits);
719 * Check whether a caller specified samplerate matches the device's
720 * hardware constraints (can be used for acquisition). Optionally yield
721 * a value that approximates the original spec.
723 * This routine assumes that input specs are in the 200kHz to 200MHz
724 * range of supported rates, and callers typically want to normalize a
725 * given value to the hardware capabilities. Values in the 50MHz range
726 * get rounded up by default, to avoid a more expensive check for the
727 * closest match, while higher sampling rate is always desirable during
728 * measurement. Input specs which exactly match hardware capabilities
729 * remain unaffected. Because 100/200MHz rates also limit the number of
730 * available channels, they are not suggested by this routine, instead
731 * callers need to pick them consciously.
733 SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
737 /* Accept exact matches for 100/200MHz. */
738 if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
740 *have_rate = want_rate;
744 /* Accept 200kHz to 50MHz range, and map to near value. */
745 if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
746 div = SR_MHZ(50) / want_rate;
747 rate = SR_MHZ(50) / div;
756 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
758 struct dev_context *devc;
759 struct drv_context *drvc;
765 drvc = sdi->driver->context;
767 /* Accept any caller specified rate which the hardware supports. */
768 ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
773 * Depending on the samplerates of 200/100/50- MHz, specific
774 * firmware is required and higher rates might limit the set
775 * of available channels.
777 num_channels = devc->num_channels;
778 if (samplerate <= SR_MHZ(50)) {
779 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
781 } else if (samplerate == SR_MHZ(100)) {
782 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
784 } else if (samplerate == SR_MHZ(200)) {
785 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
790 * The samplerate affects the number of available logic channels
791 * as well as a sample memory layout detail (the number of samples
792 * which the device will communicate within an "event").
795 devc->num_channels = num_channels;
796 devc->samples_per_event = 16 / devc->num_channels;
803 * Arrange for a session feed submit buffer. A queue where a number of
804 * samples gets accumulated to reduce the number of send calls. Which
805 * also enforces an optional sample count limit for data acquisition.
807 * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
808 * driver provides a fixed channel layout regardless of samplerate).
811 #define CHUNK_SIZE (4 * 1024 * 1024)
813 struct submit_buffer {
815 size_t max_samples, curr_samples;
816 uint8_t *sample_data;
817 uint8_t *write_pointer;
818 struct sr_dev_inst *sdi;
819 struct sr_datafeed_packet packet;
820 struct sr_datafeed_logic logic;
823 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
825 struct dev_context *devc;
826 struct submit_buffer *buffer;
831 buffer = g_malloc0(sizeof(*buffer));
832 devc->buffer = buffer;
834 buffer->unit_size = sizeof(uint16_t);
836 size /= buffer->unit_size;
837 buffer->max_samples = size;
838 size *= buffer->unit_size;
839 buffer->sample_data = g_try_malloc0(size);
840 if (!buffer->sample_data)
841 return SR_ERR_MALLOC;
842 buffer->write_pointer = buffer->sample_data;
843 sr_sw_limits_init(&devc->feed_limits);
846 memset(&buffer->logic, 0, sizeof(buffer->logic));
847 buffer->logic.unitsize = buffer->unit_size;
848 buffer->logic.data = buffer->sample_data;
849 memset(&buffer->packet, 0, sizeof(buffer->packet));
850 buffer->packet.type = SR_DF_LOGIC;
851 buffer->packet.payload = &buffer->logic;
856 static int setup_submit_limit(struct dev_context *devc)
858 struct sr_sw_limits *limits;
863 limits = &devc->feed_limits;
865 ret = sr_sw_limits_config_get(&devc->cfg_limits,
866 SR_CONF_LIMIT_SAMPLES, &data);
869 total = g_variant_get_uint64(data);
870 g_variant_unref(data);
872 sr_sw_limits_init(limits);
874 data = g_variant_new_uint64(total);
875 ret = sr_sw_limits_config_set(limits,
876 SR_CONF_LIMIT_SAMPLES, data);
877 g_variant_unref(data);
882 sr_sw_limits_acquisition_start(limits);
887 static void free_submit_buffer(struct dev_context *devc)
889 struct submit_buffer *buffer;
894 buffer = devc->buffer;
899 g_free(buffer->sample_data);
903 static int flush_submit_buffer(struct dev_context *devc)
905 struct submit_buffer *buffer;
908 buffer = devc->buffer;
910 /* Is queued sample data available? */
911 if (!buffer->curr_samples)
914 /* Submit to the session feed. */
915 buffer->logic.length = buffer->curr_samples * buffer->unit_size;
916 ret = sr_session_send(buffer->sdi, &buffer->packet);
920 /* Rewind queue position. */
921 buffer->curr_samples = 0;
922 buffer->write_pointer = buffer->sample_data;
927 static int addto_submit_buffer(struct dev_context *devc,
928 uint16_t sample, size_t count)
930 struct submit_buffer *buffer;
931 struct sr_sw_limits *limits;
934 buffer = devc->buffer;
935 limits = &devc->feed_limits;
936 if (sr_sw_limits_check(limits))
940 * Individually accumulate and check each sample, such that
941 * accumulation between flushes won't exceed local storage, and
942 * enforcement of user specified limits is exact.
945 write_u16le_inc(&buffer->write_pointer, sample);
946 buffer->curr_samples++;
947 if (buffer->curr_samples == buffer->max_samples) {
948 ret = flush_submit_buffer(devc);
952 sr_sw_limits_update_samples_read(limits, 1);
953 if (sr_sw_limits_check(limits))
961 * In 100 and 200 MHz mode, only a single pin rising/falling can be
962 * set as trigger. In other modes, two rising/falling triggers can be set,
963 * in addition to value/mask trigger for any number of channels.
965 * The Sigma supports complex triggers using boolean expressions, but this
966 * has not been implemented yet.
968 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
970 struct dev_context *devc;
971 struct sr_trigger *trigger;
972 struct sr_trigger_stage *stage;
973 struct sr_trigger_match *match;
975 int channelbit, trigger_set;
978 memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
979 if (!(trigger = sr_session_trigger_get(sdi->session)))
983 for (l = trigger->stages; l; l = l->next) {
985 for (m = stage->matches; m; m = m->next) {
987 /* Ignore disabled channels with a trigger. */
988 if (!match->channel->enabled)
990 channelbit = 1 << match->channel->index;
991 if (devc->samplerate >= SR_MHZ(100)) {
992 /* Fast trigger support. */
994 sr_err("Only a single pin trigger is "
995 "supported in 100 and 200MHz mode.");
998 if (match->match == SR_TRIGGER_FALLING) {
999 devc->trigger.fallingmask |= channelbit;
1000 } else if (match->match == SR_TRIGGER_RISING) {
1001 devc->trigger.risingmask |= channelbit;
1003 sr_err("Only rising/falling trigger is "
1004 "supported in 100 and 200MHz mode.");
1010 /* Simple trigger support (event). */
1011 if (match->match == SR_TRIGGER_ONE) {
1012 devc->trigger.simplevalue |= channelbit;
1013 devc->trigger.simplemask |= channelbit;
1014 } else if (match->match == SR_TRIGGER_ZERO) {
1015 devc->trigger.simplevalue &= ~channelbit;
1016 devc->trigger.simplemask |= channelbit;
1017 } else if (match->match == SR_TRIGGER_FALLING) {
1018 devc->trigger.fallingmask |= channelbit;
1020 } else if (match->match == SR_TRIGGER_RISING) {
1021 devc->trigger.risingmask |= channelbit;
1026 * Actually, Sigma supports 2 rising/falling triggers,
1027 * but they are ORed and the current trigger syntax
1028 * does not permit ORed triggers.
1030 if (trigger_set > 1) {
1031 sr_err("Only 1 rising/falling trigger is supported.");
1041 /* Software trigger to determine exact trigger position. */
1042 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1043 struct sigma_trigger *t)
1045 const uint8_t *rdptr;
1051 for (i = 0; i < 8; i++) {
1053 last_sample = sample;
1054 sample = read_u16le_inc(&rdptr);
1056 /* Simple triggers. */
1057 if ((sample & t->simplemask) != t->simplevalue)
1061 if (((last_sample & t->risingmask) != 0) ||
1062 ((sample & t->risingmask) != t->risingmask))
1066 if ((last_sample & t->fallingmask) != t->fallingmask ||
1067 (sample & t->fallingmask) != 0)
1073 /* If we did not match, return original trigger pos. */
1077 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1080 * Check whether the combination of this very sample and the
1081 * previous state match the configured trigger condition. This
1082 * improves the resolution of the trigger marker's position.
1083 * The hardware provided position is coarse, and may point to
1084 * a position before the actual match.
1086 * See the previous get_trigger_offset() implementation. This
1087 * code needs to get re-used here.
1091 (void)get_trigger_offset;
1096 static int check_and_submit_sample(struct dev_context *devc,
1097 uint16_t sample, size_t count, gboolean check_trigger)
1102 triggered = check_trigger && sample_matches_trigger(devc, sample);
1104 ret = flush_submit_buffer(devc);
1107 ret = std_session_send_df_trigger(devc->buffer->sdi);
1112 ret = addto_submit_buffer(devc, sample, count);
1120 * Return the timestamp of "DRAM cluster".
1122 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1124 return read_u16le(&cluster->timestamp[0]);
1128 * Return one 16bit data entity of a DRAM cluster at the specified index.
1130 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1132 return read_u16le(&cl->samples[idx].sample[0]);
1136 * Deinterlace sample data that was retrieved at 100MHz samplerate.
1137 * One 16bit item contains two samples of 8bits each. The bits of
1138 * multiple samples are interleaved.
1140 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1146 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1147 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1148 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1149 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1150 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1151 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1152 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1153 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1158 * Deinterlace sample data that was retrieved at 200MHz samplerate.
1159 * One 16bit item contains four samples of 4bits each. The bits of
1160 * multiple samples are interleaved.
1162 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1168 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1169 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1170 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1171 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1175 static void sigma_decode_dram_cluster(struct dev_context *devc,
1176 struct sigma_dram_cluster *dram_cluster,
1177 size_t events_in_cluster, gboolean triggered)
1179 struct sigma_state *ss;
1180 uint16_t tsdiff, ts, sample, item16;
1183 if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1187 * If this cluster is not adjacent to the previously received
1188 * cluster, then send the appropriate number of samples with the
1189 * previous values to the sigrok session. This "decodes RLE".
1191 * These samples cannot match the trigger since they just repeat
1192 * the previously submitted data pattern. (This assumption holds
1193 * for simple level and edge triggers. It would not for timed or
1194 * counted conditions, which currently are not supported.)
1197 ts = sigma_dram_cluster_ts(dram_cluster);
1198 tsdiff = ts - ss->lastts;
1201 sample = ss->lastsample;
1202 count = tsdiff * devc->samples_per_event;
1203 (void)check_and_submit_sample(devc, sample, count, FALSE);
1205 ss->lastts = ts + EVENTS_PER_CLUSTER;
1208 * Grab sample data from the current cluster and prepare their
1209 * submission to the session feed. Handle samplerate dependent
1210 * memory layout of sample data. Accumulation of data chunks
1211 * before submission is transparent to this code path, specific
1212 * buffer depth is neither assumed nor required here.
1215 for (i = 0; i < events_in_cluster; i++) {
1216 item16 = sigma_dram_cluster_data(dram_cluster, i);
1217 if (devc->samplerate == SR_MHZ(200)) {
1218 sample = sigma_deinterlace_200mhz_data(item16, 0);
1219 check_and_submit_sample(devc, sample, 1, triggered);
1220 sample = sigma_deinterlace_200mhz_data(item16, 1);
1221 check_and_submit_sample(devc, sample, 1, triggered);
1222 sample = sigma_deinterlace_200mhz_data(item16, 2);
1223 check_and_submit_sample(devc, sample, 1, triggered);
1224 sample = sigma_deinterlace_200mhz_data(item16, 3);
1225 check_and_submit_sample(devc, sample, 1, triggered);
1226 } else if (devc->samplerate == SR_MHZ(100)) {
1227 sample = sigma_deinterlace_100mhz_data(item16, 0);
1228 check_and_submit_sample(devc, sample, 1, triggered);
1229 sample = sigma_deinterlace_100mhz_data(item16, 1);
1230 check_and_submit_sample(devc, sample, 1, triggered);
1233 check_and_submit_sample(devc, sample, 1, triggered);
1236 ss->lastsample = sample;
1240 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1241 * Each event is 20ns apart, and can contain multiple samples.
1243 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1244 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1245 * For 50 MHz and below, events contain one sample for each channel,
1246 * spread 20 ns apart.
1248 static int decode_chunk_ts(struct dev_context *devc,
1249 struct sigma_dram_line *dram_line,
1250 size_t events_in_line, size_t trigger_event)
1252 struct sigma_dram_cluster *dram_cluster;
1253 unsigned int clusters_in_line;
1254 unsigned int events_in_cluster;
1256 uint32_t trigger_cluster;
1258 clusters_in_line = events_in_line;
1259 clusters_in_line += EVENTS_PER_CLUSTER - 1;
1260 clusters_in_line /= EVENTS_PER_CLUSTER;
1261 trigger_cluster = ~0;
1263 /* Check if trigger is in this chunk. */
1264 if (trigger_event < EVENTS_PER_ROW) {
1265 if (devc->samplerate <= SR_MHZ(50)) {
1266 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1270 /* Find in which cluster the trigger occurred. */
1271 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1274 /* For each full DRAM cluster. */
1275 for (i = 0; i < clusters_in_line; i++) {
1276 dram_cluster = &dram_line->cluster[i];
1278 /* The last cluster might not be full. */
1279 if ((i == clusters_in_line - 1) &&
1280 (events_in_line % EVENTS_PER_CLUSTER)) {
1281 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1283 events_in_cluster = EVENTS_PER_CLUSTER;
1286 sigma_decode_dram_cluster(devc, dram_cluster,
1287 events_in_cluster, i == trigger_cluster);
1293 static int download_capture(struct sr_dev_inst *sdi)
1295 const uint32_t chunks_per_read = 32;
1297 struct dev_context *devc;
1298 struct sigma_dram_line *dram_line;
1300 uint32_t stoppos, triggerpos;
1303 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1304 uint32_t dl_first_line, dl_line;
1305 uint32_t dl_events_in_line;
1306 uint32_t trg_line, trg_event;
1310 dl_events_in_line = EVENTS_PER_ROW;
1312 sr_info("Downloading sample data.");
1313 devc->state.state = SIGMA_DOWNLOAD;
1316 * Ask the hardware to stop data acquisition. Reception of the
1317 * FORCESTOP request makes the hardware "disable RLE" (store
1318 * clusters to DRAM regardless of whether pin state changes) and
1319 * raise the POSTTRIGGERED flag.
1321 sigma_set_register(devc, WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN);
1323 ret = sigma_read_register(devc, READ_MODE,
1324 &modestatus, sizeof(modestatus));
1325 if (ret != sizeof(modestatus)) {
1326 sr_err("Could not poll for post-trigger condition.");
1329 } while (!(modestatus & RMR_POSTTRIGGERED));
1331 /* Set SDRAM Read Enable. */
1332 sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
1334 /* Get the current position. */
1335 sigma_read_pos(devc, &stoppos, &triggerpos);
1337 /* Check if trigger has fired. */
1338 ret = sigma_read_register(devc, READ_MODE,
1339 &modestatus, sizeof(modestatus));
1340 if (ret != sizeof(modestatus)) {
1341 sr_err("Could not query trigger hit.");
1346 if (modestatus & RMR_TRIGGERED) {
1347 trg_line = triggerpos >> ROW_SHIFT;
1348 trg_event = triggerpos & ROW_MASK;
1352 * Determine how many "DRAM lines" of 1024 bytes each we need to
1353 * retrieve from the Sigma hardware, so that we have a complete
1354 * set of samples. Note that the last line need not contain 64
1355 * clusters, it might be partially filled only.
1357 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1358 * around. Since the status of the very next line is uncertain in
1359 * that case, we skip it and start reading from the next line.
1362 dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1363 if (modestatus & RMR_ROUND) {
1364 dl_first_line = dl_lines_total + 1;
1365 dl_lines_total = ROW_COUNT - 2;
1367 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1370 ret = alloc_submit_buffer(sdi);
1373 ret = setup_submit_limit(devc);
1377 while (dl_lines_total > dl_lines_done) {
1378 /* We can download only up-to 32 DRAM lines in one go! */
1379 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1381 dl_line = dl_first_line + dl_lines_done;
1382 dl_line %= ROW_COUNT;
1383 bufsz = sigma_read_dram(devc, dl_line, dl_lines_curr,
1384 (uint8_t *)dram_line);
1385 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1388 /* This is the first DRAM line, so find the initial timestamp. */
1389 if (dl_lines_done == 0) {
1390 devc->state.lastts =
1391 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1392 devc->state.lastsample = 0;
1395 for (i = 0; i < dl_lines_curr; i++) {
1396 uint32_t trigger_event = ~0;
1397 /* The last "DRAM line" need not span its full length. */
1398 if (dl_lines_done + i == dl_lines_total - 1)
1399 dl_events_in_line = stoppos & ROW_MASK;
1401 /* Test if the trigger happened on this line. */
1402 if (dl_lines_done + i == trg_line)
1403 trigger_event = trg_event;
1405 decode_chunk_ts(devc, dram_line + i,
1406 dl_events_in_line, trigger_event);
1409 dl_lines_done += dl_lines_curr;
1411 flush_submit_buffer(devc);
1412 free_submit_buffer(devc);
1415 std_session_send_df_end(sdi);
1417 devc->state.state = SIGMA_IDLE;
1418 sr_dev_acquisition_stop(sdi);
1424 * Periodically check the Sigma status when in CAPTURE mode. This routine
1425 * checks whether the configured sample count or sample time have passed,
1426 * and will stop acquisition and download the acquired samples.
1428 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1430 struct dev_context *devc;
1433 if (sr_sw_limits_check(&devc->acq_limits))
1434 return download_capture(sdi);
1439 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1441 struct sr_dev_inst *sdi;
1442 struct dev_context *devc;
1450 if (devc->state.state == SIGMA_IDLE)
1454 * When the application has requested to stop the acquisition,
1455 * then immediately start downloading sample data. Otherwise
1456 * keep checking configured limits which will terminate the
1457 * acquisition and initiate download.
1459 if (devc->state.state == SIGMA_STOPPING)
1460 return download_capture(sdi);
1461 if (devc->state.state == SIGMA_CAPTURE)
1462 return sigma_capture_mode(sdi);
1467 /* Build a LUT entry used by the trigger functions. */
1468 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1472 /* For each quad channel. */
1473 for (i = 0; i < 4; i++) {
1476 /* For each bit in LUT. */
1477 for (j = 0; j < 16; j++) {
1479 /* For each channel in quad. */
1480 for (k = 0; k < 4; k++) {
1481 bit = 1 << (i * 4 + k);
1483 /* Set bit in entry */
1484 if ((mask & bit) && ((!(value & bit)) !=
1486 entry[i] &= ~(1 << j);
1492 /* Add a logical function to LUT mask. */
1493 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1494 int index, int neg, uint16_t *mask)
1497 int x[2][2], tmp, a, b, aset, bset, rset;
1499 memset(x, 0, 4 * sizeof(int));
1501 /* Trigger detect condition. */
1531 case OP_NOTRISEFALL:
1537 /* Transpose if neg is set. */
1539 for (i = 0; i < 2; i++) {
1540 for (j = 0; j < 2; j++) {
1542 x[i][j] = x[1 - i][1 - j];
1543 x[1 - i][1 - j] = tmp;
1548 /* Update mask with function. */
1549 for (i = 0; i < 16; i++) {
1550 a = (i >> (2 * index + 0)) & 1;
1551 b = (i >> (2 * index + 1)) & 1;
1553 aset = (*mask >> i) & 1;
1557 if (func == FUNC_AND || func == FUNC_NAND)
1559 else if (func == FUNC_OR || func == FUNC_NOR)
1561 else if (func == FUNC_XOR || func == FUNC_NXOR)
1564 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1575 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1576 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1577 * set at any time, but a full mask and value can be set (0/1).
1579 SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
1580 struct triggerlut *lut)
1583 uint16_t masks[2] = { 0, 0 };
1585 memset(lut, 0, sizeof(struct triggerlut));
1587 /* Constant for simple triggers. */
1590 /* Value/mask trigger support. */
1591 build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1594 /* Rise/fall trigger support. */
1595 for (i = 0, j = 0; i < 16; i++) {
1596 if (devc->trigger.risingmask & (1 << i) ||
1597 devc->trigger.fallingmask & (1 << i))
1598 masks[j++] = 1 << i;
1601 build_lut_entry(masks[0], masks[0], lut->m0d);
1602 build_lut_entry(masks[1], masks[1], lut->m1d);
1604 /* Add glue logic */
1605 if (masks[0] || masks[1]) {
1606 /* Transition trigger. */
1607 if (masks[0] & devc->trigger.risingmask)
1608 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1609 if (masks[0] & devc->trigger.fallingmask)
1610 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1611 if (masks[1] & devc->trigger.risingmask)
1612 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1613 if (masks[1] & devc->trigger.fallingmask)
1614 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1616 /* Only value/mask trigger. */
1620 /* Triggertype: event. */
1621 lut->params.selres = 3;