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 static 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 GVariant *sigma_get_samplerates_list(void)
51 return std_gvar_samplerates(samplerates, ARRAY_SIZE(samplerates));
54 static const char *firmware_files[] = {
55 [SIGMA_FW_50MHZ] = "asix-sigma-50.fw", /* 50MHz, 8bit divider. */
56 [SIGMA_FW_100MHZ] = "asix-sigma-100.fw", /* 100MHz, fixed. */
57 [SIGMA_FW_200MHZ] = "asix-sigma-200.fw", /* 200MHz, fixed. */
58 [SIGMA_FW_SYNC] = "asix-sigma-50sync.fw", /* Sync from external pin. */
59 [SIGMA_FW_FREQ] = "asix-sigma-phasor.fw", /* Frequency counter. */
62 #define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
64 static int sigma_ftdi_open(const struct sr_dev_inst *sdi)
66 struct dev_context *devc;
75 if (devc->ftdi.is_open)
80 serno = sdi->serial_num;
81 if (!vid || !pid || !serno || !*serno)
84 ret = ftdi_init(&devc->ftdi.ctx);
86 sr_err("Cannot initialize FTDI context (%d): %s.",
87 ret, ftdi_get_error_string(&devc->ftdi.ctx));
90 ret = ftdi_usb_open_desc_index(&devc->ftdi.ctx,
91 vid, pid, NULL, serno, 0);
93 sr_err("Cannot open device (%d): %s.",
94 ret, ftdi_get_error_string(&devc->ftdi.ctx));
97 devc->ftdi.is_open = TRUE;
102 static int sigma_ftdi_close(struct dev_context *devc)
106 ret = ftdi_usb_close(&devc->ftdi.ctx);
107 devc->ftdi.is_open = FALSE;
108 devc->ftdi.must_close = FALSE;
109 ftdi_deinit(&devc->ftdi.ctx);
111 return ret == 0 ? SR_OK : SR_ERR_IO;
114 SR_PRIV int sigma_check_open(const struct sr_dev_inst *sdi)
116 struct dev_context *devc;
125 if (devc->ftdi.is_open)
128 ret = sigma_ftdi_open(sdi);
131 devc->ftdi.must_close = TRUE;
136 SR_PRIV int sigma_check_close(struct dev_context *devc)
143 if (devc->ftdi.must_close) {
144 ret = sigma_ftdi_close(devc);
147 devc->ftdi.must_close = FALSE;
153 SR_PRIV int sigma_force_open(const struct sr_dev_inst *sdi)
155 struct dev_context *devc;
164 ret = sigma_ftdi_open(sdi);
167 devc->ftdi.must_close = FALSE;
172 SR_PRIV int sigma_force_close(struct dev_context *devc)
174 return sigma_ftdi_close(devc);
178 * BEWARE! Error propagation is important, as are kinds of return values.
180 * - Raw USB tranport communicates the number of sent or received bytes,
181 * or negative error codes in the external library's(!) range of codes.
182 * - Internal routines at the "sigrok driver level" communicate success
183 * or failure in terms of SR_OK et al error codes.
184 * - Main loop style receive callbacks communicate booleans which arrange
185 * for repeated calls to drive progress during acquisition.
187 * Careful consideration by maintainers is essential, because all of the
188 * above kinds of values are assignment compatbile from the compiler's
189 * point of view. Implementation errors will go unnoticed at build time.
192 static int sigma_read_raw(struct dev_context *devc, void *buf, size_t size)
196 ret = ftdi_read_data(&devc->ftdi.ctx, (unsigned char *)buf, size);
198 sr_err("USB data read failed: %s",
199 ftdi_get_error_string(&devc->ftdi.ctx));
205 static int sigma_write_raw(struct dev_context *devc, const void *buf, size_t size)
209 ret = ftdi_write_data(&devc->ftdi.ctx, buf, size);
211 sr_err("USB data write failed: %s",
212 ftdi_get_error_string(&devc->ftdi.ctx));
213 } else if ((size_t)ret != size) {
214 sr_err("USB data write length mismatch.");
220 static int sigma_read_sr(struct dev_context *devc, void *buf, size_t size)
224 ret = sigma_read_raw(devc, buf, size);
225 if (ret < 0 || (size_t)ret != size)
231 static int sigma_write_sr(struct dev_context *devc, const void *buf, size_t size)
235 ret = sigma_write_raw(devc, buf, size);
236 if (ret < 0 || (size_t)ret != size)
243 * Implementor's note: The local write buffer's size shall suffice for
244 * any know FPGA register transaction that is involved in the supported
245 * feature set of this sigrok device driver. If the length check trips,
246 * that's a programmer's error and needs adjustment in the complete call
247 * stack of the respective code path.
249 #define SIGMA_MAX_REG_DEPTH 32
252 * Implementor's note: The FPGA command set supports register access
253 * with automatic address adjustment. This operation is documented to
254 * wrap within a 16-address range, it cannot cross boundaries where the
255 * register address' nibble overflows. An internal helper assumes that
256 * callers remain within this auto-adjustment range, and thus multi
257 * register access requests can never exceed that count.
259 #define SIGMA_MAX_REG_COUNT 16
261 SR_PRIV int sigma_write_register(struct dev_context *devc,
262 uint8_t reg, uint8_t *data, size_t len)
264 uint8_t buf[2 + SIGMA_MAX_REG_DEPTH * 2], *wrptr;
267 if (len > SIGMA_MAX_REG_DEPTH) {
268 sr_err("Short write buffer for %zu bytes to reg %u.", len, reg);
273 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(reg));
274 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(reg));
275 for (idx = 0; idx < len; idx++) {
276 write_u8_inc(&wrptr, REG_DATA_LOW | LO4(data[idx]));
277 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(data[idx]));
280 return sigma_write_sr(devc, buf, wrptr - buf);
283 SR_PRIV int sigma_set_register(struct dev_context *devc,
284 uint8_t reg, uint8_t value)
286 return sigma_write_register(devc, reg, &value, sizeof(value));
289 static int sigma_read_register(struct dev_context *devc,
290 uint8_t reg, uint8_t *data, size_t len)
292 uint8_t buf[3], *wrptr;
296 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(reg));
297 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(reg));
298 write_u8_inc(&wrptr, REG_READ_ADDR);
299 ret = sigma_write_sr(devc, buf, wrptr - buf);
303 return sigma_read_sr(devc, data, len);
306 static int sigma_get_register(struct dev_context *devc,
307 uint8_t reg, uint8_t *data)
309 return sigma_read_register(devc, reg, data, sizeof(*data));
312 static int sigma_get_registers(struct dev_context *devc,
313 uint8_t reg, uint8_t *data, size_t count)
315 uint8_t buf[2 + SIGMA_MAX_REG_COUNT], *wrptr;
319 if (count > SIGMA_MAX_REG_COUNT) {
320 sr_err("Short command buffer for %zu reg reads at %u.", count, reg);
325 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(reg));
326 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(reg));
327 for (idx = 0; idx < count; idx++)
328 write_u8_inc(&wrptr, REG_READ_ADDR | REG_ADDR_INC);
329 ret = sigma_write_sr(devc, buf, wrptr - buf);
333 return sigma_read_sr(devc, data, count);
336 static int sigma_read_pos(struct dev_context *devc,
337 uint32_t *stoppos, uint32_t *triggerpos, uint8_t *mode)
340 const uint8_t *rdptr;
346 * Read 7 registers starting at trigger position LSB.
347 * Which yields two 24bit counter values, and mode flags.
349 ret = sigma_get_registers(devc, READ_TRIGGER_POS_LOW,
350 result, sizeof(result));
355 v32 = read_u24le_inc(&rdptr);
358 v32 = read_u24le_inc(&rdptr);
361 v8 = read_u8_inc(&rdptr);
366 * These positions consist of "the memory row" in the MSB fields,
367 * and "an event index" within the row in the LSB fields. Part
368 * of the memory row's content is sample data, another part is
371 * The retrieved register values point to after the captured
372 * position. So they need to get decremented, and adjusted to
373 * cater for the timestamps when the decrement carries over to
374 * a different memory row.
376 if (stoppos && (--*stoppos & ROW_MASK) == ROW_MASK)
377 *stoppos -= CLUSTERS_PER_ROW;
378 if (triggerpos && (--*triggerpos & ROW_MASK) == ROW_MASK)
379 *triggerpos -= CLUSTERS_PER_ROW;
384 static int sigma_read_dram(struct dev_context *devc,
385 uint16_t startchunk, size_t numchunks, uint8_t *data)
387 uint8_t buf[128], *wrptr, regval;
392 if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
393 sr_err("Short write buffer for %zu DRAM row reads.", numchunks);
397 /* Communicate DRAM start address (memory row, aka samples line). */
399 write_u16be_inc(&wrptr, startchunk);
400 ret = sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
405 * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
406 * then transfer via USB. Interleave the FPGA's DRAM access and
407 * USB transfer, use alternating buffers (0/1) in the process.
410 write_u8_inc(&wrptr, REG_DRAM_BLOCK);
411 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
412 for (chunk = 0; chunk < numchunks; chunk++) {
414 is_last = chunk == numchunks - 1;
416 regval = REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel);
417 write_u8_inc(&wrptr, regval);
419 regval = REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel);
420 write_u8_inc(&wrptr, regval);
422 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
424 ret = sigma_write_sr(devc, buf, wrptr - buf);
428 return sigma_read_sr(devc, data, numchunks * ROW_LENGTH_BYTES);
431 /* Upload trigger look-up tables to Sigma. */
432 SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
433 struct triggerlut *lut)
437 uint8_t m3d, m2d, m1d, m0d;
438 uint8_t buf[6], *wrptr;
443 * Translate the LUT part of the trigger configuration from the
444 * application's perspective to the hardware register's bitfield
445 * layout. Send the LUT to the device. This configures the logic
446 * which combines pin levels or edges.
448 for (lut_addr = 0; lut_addr < 16; lut_addr++) {
460 /* M2D3 M2D2 M2D1 M2D0 */
462 if (lut->m2d[3] & bit)
464 if (lut->m2d[2] & bit)
466 if (lut->m2d[1] & bit)
468 if (lut->m2d[0] & bit)
471 /* M1D3 M1D2 M1D1 M1D0 */
473 if (lut->m1d[3] & bit)
475 if (lut->m1d[2] & bit)
477 if (lut->m1d[1] & bit)
479 if (lut->m1d[0] & bit)
482 /* M0D3 M0D2 M0D1 M0D0 */
484 if (lut->m0d[3] & bit)
486 if (lut->m0d[2] & bit)
488 if (lut->m0d[1] & bit)
490 if (lut->m0d[0] & bit)
494 * Send 16bits with M3D/M2D and M1D/M0D bit masks to the
495 * TriggerSelect register, then strobe the LUT write by
496 * passing A3-A0 to TriggerSelect2. Hold RESET during LUT
500 write_u8_inc(&wrptr, (m3d << 4) | (m2d << 0));
501 write_u8_inc(&wrptr, (m1d << 4) | (m0d << 0));
502 ret = sigma_write_register(devc, WRITE_TRIGGER_SELECT,
506 ret = sigma_set_register(devc, WRITE_TRIGGER_SELECT2,
507 TRGSEL2_RESET | TRGSEL2_LUT_WRITE |
508 (lut_addr & TRGSEL2_LUT_ADDR_MASK));
514 * Send the parameters. This covers counters and durations.
518 selreg |= (lut->params.selinc & TRGSEL_SELINC_MASK) << TRGSEL_SELINC_SHIFT;
519 selreg |= (lut->params.selres & TRGSEL_SELRES_MASK) << TRGSEL_SELRES_SHIFT;
520 selreg |= (lut->params.sela & TRGSEL_SELA_MASK) << TRGSEL_SELA_SHIFT;
521 selreg |= (lut->params.selb & TRGSEL_SELB_MASK) << TRGSEL_SELB_SHIFT;
522 selreg |= (lut->params.selc & TRGSEL_SELC_MASK) << TRGSEL_SELC_SHIFT;
523 selreg |= (lut->params.selpresc & TRGSEL_SELPRESC_MASK) << TRGSEL_SELPRESC_SHIFT;
524 write_u16be_inc(&wrptr, selreg);
525 write_u16be_inc(&wrptr, lut->params.cmpb);
526 write_u16be_inc(&wrptr, lut->params.cmpa);
527 ret = sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
535 * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
536 * uses FTDI bitbang mode for netlist download in slave serial mode.
537 * (LATER: The OMEGA device's cable contains a more capable FTDI chip
538 * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
539 * compatible bitbang mode? For maximum code re-use and reduced libftdi
540 * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
541 * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
543 * 750kbps rate (four times the speed of sigmalogan) works well for
544 * netlist download. All pins except INIT_B are output pins during
545 * configuration download.
547 * Some pins are inverted as a byproduct of level shifting circuitry.
548 * That's why high CCLK level (from the cable's point of view) is idle
549 * from the FPGA's perspective.
551 * The vendor's literature discusses a "suicide sequence" which ends
552 * regular FPGA execution and should be sent before entering bitbang
553 * mode and sending configuration data. Set D7 and toggle D2, D3, D4
556 #define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
557 #define BB_PIN_PROG (1 << 1) /* D1, PROG */
558 #define BB_PIN_D2 (1 << 2) /* D2, (part of) SUICIDE */
559 #define BB_PIN_D3 (1 << 3) /* D3, (part of) SUICIDE */
560 #define BB_PIN_D4 (1 << 4) /* D4, (part of) SUICIDE (unused?) */
561 #define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
562 #define BB_PIN_DIN (1 << 6) /* D6, DIN */
563 #define BB_PIN_D7 (1 << 7) /* D7, (part of) SUICIDE */
565 #define BB_BITRATE (750 * 1000)
566 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
569 * Initiate slave serial mode for configuration download. Which is done
570 * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
571 * initiating the configuration download.
573 * Run a "suicide sequence" first to terminate the regular FPGA operation
574 * before reconfiguration. The FTDI cable is single channel, and shares
575 * pins which are used for data communication in FIFO mode with pins that
576 * are used for FPGA configuration in bitbang mode. Hardware defaults for
577 * unconfigured hardware, and runtime conditions after FPGA configuration
578 * need to cooperate such that re-configuration of the FPGA can start.
580 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
582 const uint8_t suicide[] = {
583 BB_PIN_D7 | BB_PIN_D2,
584 BB_PIN_D7 | BB_PIN_D2,
585 BB_PIN_D7 | BB_PIN_D3,
586 BB_PIN_D7 | BB_PIN_D2,
587 BB_PIN_D7 | BB_PIN_D3,
588 BB_PIN_D7 | BB_PIN_D2,
589 BB_PIN_D7 | BB_PIN_D3,
590 BB_PIN_D7 | BB_PIN_D2,
592 const uint8_t init_array[] = {
594 BB_PIN_CCLK | BB_PIN_PROG,
595 BB_PIN_CCLK | BB_PIN_PROG,
607 /* Section 2. part 1), do the FPGA suicide. */
609 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
610 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
611 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
612 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
617 /* Section 2. part 2), pulse PROG. */
618 ret = sigma_write_sr(devc, init_array, sizeof(init_array));
622 ftdi_usb_purge_buffers(&devc->ftdi.ctx);
625 * Wait until the FPGA asserts INIT_B. Check in a maximum number
626 * of bursts with a given delay between them. Read as many pin
627 * capture results as the combination of FTDI chip and FTID lib
628 * may provide. Cope with absence of pin capture data in a cycle.
629 * This approach shall result in fast reponse in case of success,
630 * low cost of execution during wait, reliable error handling in
631 * the transport layer, and robust response to failure or absence
632 * of result data (hardware inactivity after stimulus).
637 ret = sigma_read_raw(devc, &data, sizeof(data));
640 if (ret == sizeof(data) && (data & BB_PIN_INIT))
642 } while (ret == sizeof(data));
647 return SR_ERR_TIMEOUT;
651 * This is belt and braces. Re-run the bitbang initiation sequence a few
652 * times should first attempts fail. Failure is rare but can happen (was
653 * observed during driver development).
655 static int sigma_fpga_init_bitbang(struct dev_context *devc)
662 ret = sigma_fpga_init_bitbang_once(devc);
665 if (ret != SR_ERR_TIMEOUT)
672 * Configure the FPGA for logic-analyzer mode.
674 static int sigma_fpga_init_la(struct dev_context *devc)
676 uint8_t buf[20], *wrptr;
677 uint8_t data_55, data_aa, mode;
679 const uint8_t *rdptr;
684 /* Read ID register. */
685 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(READ_ID));
686 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(READ_ID));
687 write_u8_inc(&wrptr, REG_READ_ADDR);
689 /* Write 0x55 to scratch register, read back. */
691 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(WRITE_TEST));
692 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(WRITE_TEST));
693 write_u8_inc(&wrptr, REG_DATA_LOW | LO4(data_55));
694 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(data_55));
695 write_u8_inc(&wrptr, REG_READ_ADDR);
697 /* Write 0xaa to scratch register, read back. */
699 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(WRITE_TEST));
700 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(WRITE_TEST));
701 write_u8_inc(&wrptr, REG_DATA_LOW | LO4(data_aa));
702 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(data_aa));
703 write_u8_inc(&wrptr, REG_READ_ADDR);
705 /* Initiate SDRAM initialization in mode register. */
706 mode = WMR_SDRAMINIT;
707 write_u8_inc(&wrptr, REG_ADDR_LOW | LO4(WRITE_MODE));
708 write_u8_inc(&wrptr, REG_ADDR_HIGH | HI4(WRITE_MODE));
709 write_u8_inc(&wrptr, REG_DATA_LOW | LO4(mode));
710 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | HI4(mode));
713 * Send the command sequence which contains 3 READ requests.
714 * Expect to see the corresponding 3 response bytes.
716 ret = sigma_write_sr(devc, buf, wrptr - buf);
718 sr_err("Could not request LA start response.");
721 ret = sigma_read_sr(devc, result, ARRAY_SIZE(result));
723 sr_err("Could not receive LA start response.");
727 if (read_u8_inc(&rdptr) != 0xa6) {
728 sr_err("Unexpected ID response.");
731 if (read_u8_inc(&rdptr) != data_55) {
732 sr_err("Unexpected scratch read-back (55).");
735 if (read_u8_inc(&rdptr) != data_aa) {
736 sr_err("Unexpected scratch read-back (aa).");
744 * Read the firmware from a file and transform it into a series of bitbang
745 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
746 * by the caller of this function.
748 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
749 uint8_t **bb_cmd, gsize *bb_cmd_size)
757 uint8_t *bb_stream, *bbs, byte, mask, v;
759 /* Retrieve the on-disk firmware file content. */
760 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
761 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
765 /* Unscramble the file content (XOR with "random" sequence). */
770 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
775 * Generate a sequence of bitbang samples. With two samples per
776 * FPGA configuration bit, providing the level for the DIN signal
777 * as well as two edges for CCLK. See Xilinx UG332 for details
778 * ("slave serial" mode).
780 * Note that CCLK is inverted in hardware. That's why the
781 * respective bit is first set and then cleared in the bitbang
782 * sample sets. So that the DIN level will be stable when the
783 * data gets sampled at the rising CCLK edge, and the signals'
784 * setup time constraint will be met.
786 * The caller will put the FPGA into download mode, will send
787 * the bitbang samples, and release the allocated memory.
789 bb_size = file_size * 8 * 2;
790 bb_stream = g_try_malloc(bb_size);
792 sr_err("Memory allocation failed during firmware upload.");
794 return SR_ERR_MALLOC;
803 v = (byte & mask) ? BB_PIN_DIN : 0;
805 *bbs++ = v | BB_PIN_CCLK;
811 /* The transformation completed successfully, return the result. */
813 *bb_cmd_size = bb_size;
818 static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
819 enum sigma_firmware_idx firmware_idx)
825 const char *firmware;
827 /* Check for valid firmware file selection. */
828 if (firmware_idx >= ARRAY_SIZE(firmware_files))
830 firmware = firmware_files[firmware_idx];
831 if (!firmware || !*firmware)
834 /* Avoid downloading the same firmware multiple times. */
835 if (devc->firmware_idx == firmware_idx) {
836 sr_info("Not uploading firmware file '%s' again.", firmware);
840 devc->state.state = SIGMA_CONFIG;
842 /* Set the cable to bitbang mode. */
843 ret = ftdi_set_bitmode(&devc->ftdi.ctx, BB_PINMASK, BITMODE_BITBANG);
845 sr_err("Could not setup cable mode for upload: %s",
846 ftdi_get_error_string(&devc->ftdi.ctx));
849 ret = ftdi_set_baudrate(&devc->ftdi.ctx, BB_BITRATE);
851 sr_err("Could not setup bitrate for upload: %s",
852 ftdi_get_error_string(&devc->ftdi.ctx));
856 /* Initiate FPGA configuration mode. */
857 ret = sigma_fpga_init_bitbang(devc);
859 sr_err("Could not initiate firmware upload to hardware");
863 /* Prepare wire format of the firmware image. */
864 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
866 sr_err("Could not prepare file %s for upload.", firmware);
870 /* Write the FPGA netlist to the cable. */
871 sr_info("Uploading firmware file '%s'.", firmware);
872 ret = sigma_write_sr(devc, buf, buf_size);
875 sr_err("Could not upload firmware file '%s'.", firmware);
879 /* Leave bitbang mode and discard pending input data. */
880 ret = ftdi_set_bitmode(&devc->ftdi.ctx, 0, BITMODE_RESET);
882 sr_err("Could not setup cable mode after upload: %s",
883 ftdi_get_error_string(&devc->ftdi.ctx));
886 ftdi_usb_purge_buffers(&devc->ftdi.ctx);
887 while (sigma_read_raw(devc, &pins, sizeof(pins)) > 0)
890 /* Initialize the FPGA for logic-analyzer mode. */
891 ret = sigma_fpga_init_la(devc);
893 sr_err("Hardware response after firmware upload failed.");
897 /* Keep track of successful firmware download completion. */
898 devc->state.state = SIGMA_IDLE;
899 devc->firmware_idx = firmware_idx;
900 sr_info("Firmware uploaded.");
906 * The driver supports user specified time or sample count limits. The
907 * device's hardware supports neither, and hardware compression prevents
908 * reliable detection of "fill levels" (currently reached sample counts)
909 * from register values during acquisition. That's why the driver needs
910 * to apply some heuristics:
912 * - The (optional) sample count limit and the (normalized) samplerate
913 * get mapped to an estimated duration for these samples' acquisition.
914 * - The (optional) time limit gets checked as well. The lesser of the
915 * two limits will terminate the data acquisition phase. The exact
916 * sample count limit gets enforced in session feed submission paths.
917 * - Some slack needs to be given to account for hardware pipelines as
918 * well as late storage of last chunks after compression thresholds
919 * are tripped. The resulting data set will span at least the caller
920 * specified period of time, which shall be perfectly acceptable.
922 * With RLE compression active, up to 64K sample periods can pass before
923 * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
924 * times that period for good measure, one is not enough to flush the
925 * hardware pipeline (observation from an earlier experiment).
927 SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
931 uint64_t user_count, user_msecs;
932 uint64_t worst_cluster_time_ms;
933 uint64_t count_msecs, acquire_msecs;
935 sr_sw_limits_init(&devc->acq_limits);
937 /* Get sample count limit, convert to msecs. */
938 ret = sr_sw_limits_config_get(&devc->cfg_limits,
939 SR_CONF_LIMIT_SAMPLES, &data);
942 user_count = g_variant_get_uint64(data);
943 g_variant_unref(data);
946 count_msecs = 1000 * user_count / devc->samplerate + 1;
948 /* Get time limit, which is in msecs. */
949 ret = sr_sw_limits_config_get(&devc->cfg_limits,
950 SR_CONF_LIMIT_MSEC, &data);
953 user_msecs = g_variant_get_uint64(data);
954 g_variant_unref(data);
956 /* Get the lesser of them, with both being optional. */
957 acquire_msecs = ~0ull;
958 if (user_count && count_msecs < acquire_msecs)
959 acquire_msecs = count_msecs;
960 if (user_msecs && user_msecs < acquire_msecs)
961 acquire_msecs = user_msecs;
962 if (acquire_msecs == ~0ull)
965 /* Add some slack, and use that timeout for acquisition. */
966 worst_cluster_time_ms = 1000 * 65536 / devc->samplerate;
967 acquire_msecs += 2 * worst_cluster_time_ms;
968 data = g_variant_new_uint64(acquire_msecs);
969 ret = sr_sw_limits_config_set(&devc->acq_limits,
970 SR_CONF_LIMIT_MSEC, data);
971 g_variant_unref(data);
975 sr_sw_limits_acquisition_start(&devc->acq_limits);
980 * Check whether a caller specified samplerate matches the device's
981 * hardware constraints (can be used for acquisition). Optionally yield
982 * a value that approximates the original spec.
984 * This routine assumes that input specs are in the 200kHz to 200MHz
985 * range of supported rates, and callers typically want to normalize a
986 * given value to the hardware capabilities. Values in the 50MHz range
987 * get rounded up by default, to avoid a more expensive check for the
988 * closest match, while higher sampling rate is always desirable during
989 * measurement. Input specs which exactly match hardware capabilities
990 * remain unaffected. Because 100/200MHz rates also limit the number of
991 * available channels, they are not suggested by this routine, instead
992 * callers need to pick them consciously.
994 SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
998 /* Accept exact matches for 100/200MHz. */
999 if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
1001 *have_rate = want_rate;
1005 /* Accept 200kHz to 50MHz range, and map to near value. */
1006 if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
1007 div = SR_MHZ(50) / want_rate;
1008 rate = SR_MHZ(50) / div;
1017 SR_PRIV uint64_t sigma_get_samplerate(const struct sr_dev_inst *sdi)
1019 /* TODO Retrieve value from hardware. */
1021 return samplerates[0];
1024 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
1026 struct dev_context *devc;
1027 struct drv_context *drvc;
1028 uint64_t samplerate;
1033 drvc = sdi->driver->context;
1035 /* Accept any caller specified rate which the hardware supports. */
1036 ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
1041 * Depending on the samplerates of 200/100/50- MHz, specific
1042 * firmware is required and higher rates might limit the set
1043 * of available channels.
1045 num_channels = devc->num_channels;
1046 if (samplerate <= SR_MHZ(50)) {
1047 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
1049 } else if (samplerate == SR_MHZ(100)) {
1050 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
1052 } else if (samplerate == SR_MHZ(200)) {
1053 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
1058 * The samplerate affects the number of available logic channels
1059 * as well as a sample memory layout detail (the number of samples
1060 * which the device will communicate within an "event").
1063 devc->num_channels = num_channels;
1064 devc->samples_per_event = 16 / devc->num_channels;
1071 * Arrange for a session feed submit buffer. A queue where a number of
1072 * samples gets accumulated to reduce the number of send calls. Which
1073 * also enforces an optional sample count limit for data acquisition.
1075 * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
1076 * driver provides a fixed channel layout regardless of samplerate).
1079 #define CHUNK_SIZE (4 * 1024 * 1024)
1081 struct submit_buffer {
1083 size_t max_samples, curr_samples;
1084 uint8_t *sample_data;
1085 uint8_t *write_pointer;
1086 struct sr_dev_inst *sdi;
1087 struct sr_datafeed_packet packet;
1088 struct sr_datafeed_logic logic;
1091 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
1093 struct dev_context *devc;
1094 struct submit_buffer *buffer;
1099 buffer = g_malloc0(sizeof(*buffer));
1100 devc->buffer = buffer;
1102 buffer->unit_size = sizeof(uint16_t);
1104 size /= buffer->unit_size;
1105 buffer->max_samples = size;
1106 size *= buffer->unit_size;
1107 buffer->sample_data = g_try_malloc0(size);
1108 if (!buffer->sample_data)
1109 return SR_ERR_MALLOC;
1110 buffer->write_pointer = buffer->sample_data;
1111 sr_sw_limits_init(&devc->feed_limits);
1114 memset(&buffer->logic, 0, sizeof(buffer->logic));
1115 buffer->logic.unitsize = buffer->unit_size;
1116 buffer->logic.data = buffer->sample_data;
1117 memset(&buffer->packet, 0, sizeof(buffer->packet));
1118 buffer->packet.type = SR_DF_LOGIC;
1119 buffer->packet.payload = &buffer->logic;
1124 static int setup_submit_limit(struct dev_context *devc)
1126 struct sr_sw_limits *limits;
1131 limits = &devc->feed_limits;
1133 ret = sr_sw_limits_config_get(&devc->cfg_limits,
1134 SR_CONF_LIMIT_SAMPLES, &data);
1137 total = g_variant_get_uint64(data);
1138 g_variant_unref(data);
1140 sr_sw_limits_init(limits);
1142 data = g_variant_new_uint64(total);
1143 ret = sr_sw_limits_config_set(limits,
1144 SR_CONF_LIMIT_SAMPLES, data);
1145 g_variant_unref(data);
1150 sr_sw_limits_acquisition_start(limits);
1155 static void free_submit_buffer(struct dev_context *devc)
1157 struct submit_buffer *buffer;
1162 buffer = devc->buffer;
1165 devc->buffer = NULL;
1167 g_free(buffer->sample_data);
1171 static int flush_submit_buffer(struct dev_context *devc)
1173 struct submit_buffer *buffer;
1176 buffer = devc->buffer;
1178 /* Is queued sample data available? */
1179 if (!buffer->curr_samples)
1182 /* Submit to the session feed. */
1183 buffer->logic.length = buffer->curr_samples * buffer->unit_size;
1184 ret = sr_session_send(buffer->sdi, &buffer->packet);
1188 /* Rewind queue position. */
1189 buffer->curr_samples = 0;
1190 buffer->write_pointer = buffer->sample_data;
1195 static int addto_submit_buffer(struct dev_context *devc,
1196 uint16_t sample, size_t count)
1198 struct submit_buffer *buffer;
1199 struct sr_sw_limits *limits;
1202 buffer = devc->buffer;
1203 limits = &devc->feed_limits;
1204 if (sr_sw_limits_check(limits))
1208 * Individually accumulate and check each sample, such that
1209 * accumulation between flushes won't exceed local storage, and
1210 * enforcement of user specified limits is exact.
1213 write_u16le_inc(&buffer->write_pointer, sample);
1214 buffer->curr_samples++;
1215 if (buffer->curr_samples == buffer->max_samples) {
1216 ret = flush_submit_buffer(devc);
1220 sr_sw_limits_update_samples_read(limits, 1);
1221 if (sr_sw_limits_check(limits))
1229 * In 100 and 200 MHz mode, only a single pin rising/falling can be
1230 * set as trigger. In other modes, two rising/falling triggers can be set,
1231 * in addition to value/mask trigger for any number of channels.
1233 * The Sigma supports complex triggers using boolean expressions, but this
1234 * has not been implemented yet.
1236 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
1238 struct dev_context *devc;
1239 struct sr_trigger *trigger;
1240 struct sr_trigger_stage *stage;
1241 struct sr_trigger_match *match;
1242 const GSList *l, *m;
1243 int channelbit, trigger_set;
1246 memset(&devc->trigger, 0, sizeof(devc->trigger));
1247 trigger = sr_session_trigger_get(sdi->session);
1252 for (l = trigger->stages; l; l = l->next) {
1254 for (m = stage->matches; m; m = m->next) {
1256 /* Ignore disabled channels with a trigger. */
1257 if (!match->channel->enabled)
1259 channelbit = 1 << match->channel->index;
1260 if (devc->samplerate >= SR_MHZ(100)) {
1261 /* Fast trigger support. */
1263 sr_err("100/200MHz modes limited to single trigger pin.");
1266 if (match->match == SR_TRIGGER_FALLING) {
1267 devc->trigger.fallingmask |= channelbit;
1268 } else if (match->match == SR_TRIGGER_RISING) {
1269 devc->trigger.risingmask |= channelbit;
1271 sr_err("100/200MHz modes limited to edge trigger.");
1277 /* Simple trigger support (event). */
1278 if (match->match == SR_TRIGGER_ONE) {
1279 devc->trigger.simplevalue |= channelbit;
1280 devc->trigger.simplemask |= channelbit;
1281 } else if (match->match == SR_TRIGGER_ZERO) {
1282 devc->trigger.simplevalue &= ~channelbit;
1283 devc->trigger.simplemask |= channelbit;
1284 } else if (match->match == SR_TRIGGER_FALLING) {
1285 devc->trigger.fallingmask |= channelbit;
1287 } else if (match->match == SR_TRIGGER_RISING) {
1288 devc->trigger.risingmask |= channelbit;
1293 * Actually, Sigma supports 2 rising/falling triggers,
1294 * but they are ORed and the current trigger syntax
1295 * does not permit ORed triggers.
1297 if (trigger_set > 1) {
1298 sr_err("Limited to 1 edge trigger.");
1308 /* Software trigger to determine exact trigger position. */
1309 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1310 struct sigma_trigger *t)
1312 const uint8_t *rdptr;
1318 for (i = 0; i < 8; i++) {
1320 last_sample = sample;
1321 sample = read_u16le_inc(&rdptr);
1323 /* Simple triggers. */
1324 if ((sample & t->simplemask) != t->simplevalue)
1328 if (((last_sample & t->risingmask) != 0) ||
1329 ((sample & t->risingmask) != t->risingmask))
1333 if ((last_sample & t->fallingmask) != t->fallingmask ||
1334 (sample & t->fallingmask) != 0)
1340 /* If we did not match, return original trigger pos. */
1344 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1347 * Check whether the combination of this very sample and the
1348 * previous state match the configured trigger condition. This
1349 * improves the resolution of the trigger marker's position.
1350 * The hardware provided position is coarse, and may point to
1351 * a position before the actual match.
1353 * See the previous get_trigger_offset() implementation. This
1354 * code needs to get re-used here.
1358 (void)get_trigger_offset;
1363 static int check_and_submit_sample(struct dev_context *devc,
1364 uint16_t sample, size_t count, gboolean check_trigger)
1369 triggered = check_trigger && sample_matches_trigger(devc, sample);
1371 ret = flush_submit_buffer(devc);
1374 ret = std_session_send_df_trigger(devc->buffer->sdi);
1379 ret = addto_submit_buffer(devc, sample, count);
1387 * Return the timestamp of "DRAM cluster".
1389 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1391 return read_u16le((const uint8_t *)&cluster->timestamp);
1395 * Return one 16bit data entity of a DRAM cluster at the specified index.
1397 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1399 return read_u16le((const uint8_t *)&cl->samples[idx]);
1403 * Deinterlace sample data that was retrieved at 100MHz samplerate.
1404 * One 16bit item contains two samples of 8bits each. The bits of
1405 * multiple samples are interleaved.
1407 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1413 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1414 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1415 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1416 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1417 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1418 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1419 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1420 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1425 * Deinterlace sample data that was retrieved at 200MHz samplerate.
1426 * One 16bit item contains four samples of 4bits each. The bits of
1427 * multiple samples are interleaved.
1429 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1435 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1436 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1437 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1438 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1442 static void sigma_decode_dram_cluster(struct dev_context *devc,
1443 struct sigma_dram_cluster *dram_cluster,
1444 size_t events_in_cluster, gboolean triggered)
1446 struct sigma_state *ss;
1447 uint16_t tsdiff, ts, sample, item16;
1450 if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1454 * If this cluster is not adjacent to the previously received
1455 * cluster, then send the appropriate number of samples with the
1456 * previous values to the sigrok session. This "decodes RLE".
1458 * These samples cannot match the trigger since they just repeat
1459 * the previously submitted data pattern. (This assumption holds
1460 * for simple level and edge triggers. It would not for timed or
1461 * counted conditions, which currently are not supported.)
1464 ts = sigma_dram_cluster_ts(dram_cluster);
1465 tsdiff = ts - ss->lastts;
1468 sample = ss->lastsample;
1469 count = tsdiff * devc->samples_per_event;
1470 (void)check_and_submit_sample(devc, sample, count, FALSE);
1472 ss->lastts = ts + EVENTS_PER_CLUSTER;
1475 * Grab sample data from the current cluster and prepare their
1476 * submission to the session feed. Handle samplerate dependent
1477 * memory layout of sample data. Accumulation of data chunks
1478 * before submission is transparent to this code path, specific
1479 * buffer depth is neither assumed nor required here.
1482 for (i = 0; i < events_in_cluster; i++) {
1483 item16 = sigma_dram_cluster_data(dram_cluster, i);
1484 if (devc->samplerate == SR_MHZ(200)) {
1485 sample = sigma_deinterlace_200mhz_data(item16, 0);
1486 check_and_submit_sample(devc, sample, 1, triggered);
1487 sample = sigma_deinterlace_200mhz_data(item16, 1);
1488 check_and_submit_sample(devc, sample, 1, triggered);
1489 sample = sigma_deinterlace_200mhz_data(item16, 2);
1490 check_and_submit_sample(devc, sample, 1, triggered);
1491 sample = sigma_deinterlace_200mhz_data(item16, 3);
1492 check_and_submit_sample(devc, sample, 1, triggered);
1493 } else if (devc->samplerate == SR_MHZ(100)) {
1494 sample = sigma_deinterlace_100mhz_data(item16, 0);
1495 check_and_submit_sample(devc, sample, 1, triggered);
1496 sample = sigma_deinterlace_100mhz_data(item16, 1);
1497 check_and_submit_sample(devc, sample, 1, triggered);
1500 check_and_submit_sample(devc, sample, 1, triggered);
1503 ss->lastsample = sample;
1507 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1508 * Each event is 20ns apart, and can contain multiple samples.
1510 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1511 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1512 * For 50 MHz and below, events contain one sample for each channel,
1513 * spread 20 ns apart.
1515 static int decode_chunk_ts(struct dev_context *devc,
1516 struct sigma_dram_line *dram_line,
1517 size_t events_in_line, size_t trigger_event)
1519 struct sigma_dram_cluster *dram_cluster;
1520 unsigned int clusters_in_line;
1521 unsigned int events_in_cluster;
1523 uint32_t trigger_cluster;
1525 clusters_in_line = events_in_line;
1526 clusters_in_line += EVENTS_PER_CLUSTER - 1;
1527 clusters_in_line /= EVENTS_PER_CLUSTER;
1528 trigger_cluster = ~0;
1530 /* Check if trigger is in this chunk. */
1531 if (trigger_event < EVENTS_PER_ROW) {
1532 if (devc->samplerate <= SR_MHZ(50)) {
1533 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1537 /* Find in which cluster the trigger occurred. */
1538 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1541 /* For each full DRAM cluster. */
1542 for (i = 0; i < clusters_in_line; i++) {
1543 dram_cluster = &dram_line->cluster[i];
1545 /* The last cluster might not be full. */
1546 if ((i == clusters_in_line - 1) &&
1547 (events_in_line % EVENTS_PER_CLUSTER)) {
1548 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1550 events_in_cluster = EVENTS_PER_CLUSTER;
1553 sigma_decode_dram_cluster(devc, dram_cluster,
1554 events_in_cluster, i == trigger_cluster);
1560 static int download_capture(struct sr_dev_inst *sdi)
1562 const uint32_t chunks_per_read = 32;
1564 struct dev_context *devc;
1565 struct sigma_dram_line *dram_line;
1566 uint32_t stoppos, triggerpos;
1569 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1570 uint32_t dl_first_line, dl_line;
1571 uint32_t dl_events_in_line, trigger_event;
1572 uint32_t trg_line, trg_event;
1577 sr_info("Downloading sample data.");
1578 devc->state.state = SIGMA_DOWNLOAD;
1581 * Ask the hardware to stop data acquisition. Reception of the
1582 * FORCESTOP request makes the hardware "disable RLE" (store
1583 * clusters to DRAM regardless of whether pin state changes) and
1584 * raise the POSTTRIGGERED flag.
1586 modestatus = WMR_FORCESTOP | WMR_SDRAMWRITEEN;
1587 ret = sigma_set_register(devc, WRITE_MODE, modestatus);
1591 ret = sigma_get_register(devc, READ_MODE, &modestatus);
1593 sr_err("Could not poll for post-trigger state.");
1596 } while (!(modestatus & RMR_POSTTRIGGERED));
1598 /* Set SDRAM Read Enable. */
1599 ret = sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
1603 /* Get the current position. Check if trigger has fired. */
1604 ret = sigma_read_pos(devc, &stoppos, &triggerpos, &modestatus);
1606 sr_err("Could not query capture positions/state.");
1611 if (modestatus & RMR_TRIGGERED) {
1612 trg_line = triggerpos >> ROW_SHIFT;
1613 trg_event = triggerpos & ROW_MASK;
1617 * Determine how many "DRAM lines" of 1024 bytes each we need to
1618 * retrieve from the Sigma hardware, so that we have a complete
1619 * set of samples. Note that the last line need not contain 64
1620 * clusters, it might be partially filled only.
1622 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1623 * around. Since the status of the very next line is uncertain in
1624 * that case, we skip it and start reading from the next line.
1627 dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1628 if (modestatus & RMR_ROUND) {
1629 dl_first_line = dl_lines_total + 1;
1630 dl_lines_total = ROW_COUNT - 2;
1632 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1635 ret = alloc_submit_buffer(sdi);
1638 ret = setup_submit_limit(devc);
1642 while (dl_lines_total > dl_lines_done) {
1643 /* We can download only up-to 32 DRAM lines in one go! */
1644 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1646 dl_line = dl_first_line + dl_lines_done;
1647 dl_line %= ROW_COUNT;
1648 ret = sigma_read_dram(devc, dl_line, dl_lines_curr,
1649 (uint8_t *)dram_line);
1653 /* This is the first DRAM line, so find the initial timestamp. */
1654 if (dl_lines_done == 0) {
1655 devc->state.lastts =
1656 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1657 devc->state.lastsample = 0;
1660 for (i = 0; i < dl_lines_curr; i++) {
1661 /* The last "DRAM line" need not span its full length. */
1662 dl_events_in_line = EVENTS_PER_ROW;
1663 if (dl_lines_done + i == dl_lines_total - 1)
1664 dl_events_in_line = stoppos & ROW_MASK;
1666 /* Test if the trigger happened on this line. */
1668 if (dl_lines_done + i == trg_line)
1669 trigger_event = trg_event;
1671 decode_chunk_ts(devc, dram_line + i,
1672 dl_events_in_line, trigger_event);
1675 dl_lines_done += dl_lines_curr;
1677 flush_submit_buffer(devc);
1678 free_submit_buffer(devc);
1681 std_session_send_df_end(sdi);
1683 devc->state.state = SIGMA_IDLE;
1684 sr_dev_acquisition_stop(sdi);
1690 * Periodically check the Sigma status when in CAPTURE mode. This routine
1691 * checks whether the configured sample count or sample time have passed,
1692 * and will stop acquisition and download the acquired samples.
1694 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1696 struct dev_context *devc;
1699 if (sr_sw_limits_check(&devc->acq_limits))
1700 return download_capture(sdi);
1705 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1707 struct sr_dev_inst *sdi;
1708 struct dev_context *devc;
1716 if (devc->state.state == SIGMA_IDLE)
1720 * When the application has requested to stop the acquisition,
1721 * then immediately start downloading sample data. Otherwise
1722 * keep checking configured limits which will terminate the
1723 * acquisition and initiate download.
1725 if (devc->state.state == SIGMA_STOPPING)
1726 return download_capture(sdi);
1727 if (devc->state.state == SIGMA_CAPTURE)
1728 return sigma_capture_mode(sdi);
1733 /* Build a LUT entry used by the trigger functions. */
1734 static void build_lut_entry(uint16_t *lut_entry,
1735 uint16_t spec_value, uint16_t spec_mask)
1737 size_t quad, bitidx, ch;
1738 uint16_t quadmask, bitmask;
1739 gboolean spec_value_low, bit_idx_low;
1742 * For each quad-channel-group, for each bit in the LUT (each
1743 * bit pattern of the channel signals, aka LUT address), for
1744 * each channel in the quad, setup the bit in the LUT entry.
1746 * Start from all-ones in the LUT (true, always matches), then
1747 * "pessimize the truthness" for specified conditions.
1749 for (quad = 0; quad < 4; quad++) {
1750 lut_entry[quad] = ~0;
1751 for (bitidx = 0; bitidx < 16; bitidx++) {
1752 for (ch = 0; ch < 4; ch++) {
1754 bitmask = quadmask << (quad * 4);
1755 if (!(spec_mask & bitmask))
1758 * This bit is part of the spec. The
1759 * condition which gets checked here
1760 * (got checked in all implementations
1761 * so far) is uncertain. A bit position
1762 * in the current index' number(!) is
1765 spec_value_low = !(spec_value & bitmask);
1766 bit_idx_low = !(bitidx & quadmask);
1767 if (spec_value_low == bit_idx_low)
1769 lut_entry[quad] &= ~(1 << bitidx);
1775 /* Add a logical function to LUT mask. */
1776 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1777 int index, int neg, uint16_t *mask)
1780 int x[2][2], tmp, a, b, aset, bset, rset;
1782 memset(x, 0, sizeof(x));
1784 /* Trigger detect condition. */
1814 case OP_NOTRISEFALL:
1820 /* Transpose if neg is set. */
1822 for (i = 0; i < 2; i++) {
1823 for (j = 0; j < 2; j++) {
1825 x[i][j] = x[1 - i][1 - j];
1826 x[1 - i][1 - j] = tmp;
1831 /* Update mask with function. */
1832 for (i = 0; i < 16; i++) {
1833 a = (i >> (2 * index + 0)) & 1;
1834 b = (i >> (2 * index + 1)) & 1;
1836 aset = (*mask >> i) & 1;
1840 if (func == FUNC_AND || func == FUNC_NAND)
1842 else if (func == FUNC_OR || func == FUNC_NOR)
1844 else if (func == FUNC_XOR || func == FUNC_NXOR)
1847 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1858 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1859 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1860 * set at any time, but a full mask and value can be set (0/1).
1862 SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
1863 struct triggerlut *lut)
1866 int bitidx, condidx;
1867 uint16_t value, mask;
1869 /* Start assuming simple triggers. */
1870 memset(lut, 0, sizeof(*lut));
1874 /* Process value/mask triggers. */
1875 value = devc->trigger.simplevalue;
1876 mask = devc->trigger.simplemask;
1877 build_lut_entry(lut->m2d, value, mask);
1879 /* Scan for and process rise/fall triggers. */
1880 memset(&masks, 0, sizeof(masks));
1882 for (bitidx = 0; bitidx < 16; bitidx++) {
1884 value = devc->trigger.risingmask | devc->trigger.fallingmask;
1885 if (!(value & mask))
1888 build_lut_entry(lut->m0d, mask, mask);
1890 build_lut_entry(lut->m1d, mask, mask);
1891 masks[condidx++] = mask;
1892 if (condidx == ARRAY_SIZE(masks))
1896 /* Add glue logic for rise/fall triggers. */
1897 if (masks[0] || masks[1]) {
1899 if (masks[0] & devc->trigger.risingmask)
1900 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3q);
1901 if (masks[0] & devc->trigger.fallingmask)
1902 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3q);
1903 if (masks[1] & devc->trigger.risingmask)
1904 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3q);
1905 if (masks[1] & devc->trigger.fallingmask)
1906 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3q);
1909 /* Triggertype: event. */
1910 lut->params.selres = TRGSEL_SELCODE_NEVER;
1911 lut->params.selinc = TRGSEL_SELCODE_LEVEL;
1912 lut->params.sela = 0; /* Counter >= CMPA && LEVEL */
1913 lut->params.cmpa = 0; /* Count 0 -> 1 already triggers. */