]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/protocol.c
ee15bb0daacda9974e21aadb682e10809cc186ae
[libsigrok.git] / src / hardware / asix-sigma / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
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>
8  *
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.
13  *
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.
18  *
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/>.
21  */
22
23 /*
24  * ASIX SIGMA/SIGMA2 logic analyzer driver
25  */
26
27 #include <config.h>
28 #include "protocol.h"
29
30 /*
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.
35  *
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.
39  */
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),
47 };
48
49 SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
50
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. */
57 };
58
59 #define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
60
61 static int sigma_read(struct dev_context *devc, void *buf, size_t size)
62 {
63         int ret;
64
65         ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
66         if (ret < 0) {
67                 sr_err("ftdi_read_data failed: %s",
68                         ftdi_get_error_string(&devc->ftdic));
69         }
70
71         return ret;
72 }
73
74 static int sigma_write(struct dev_context *devc, const void *buf, size_t size)
75 {
76         int ret;
77
78         ret = ftdi_write_data(&devc->ftdic, buf, size);
79         if (ret < 0)
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.");
84
85         return ret;
86 }
87
88 /*
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.
91  */
92 SR_PRIV int sigma_write_register(struct dev_context *devc,
93         uint8_t reg, uint8_t *data, size_t len)
94 {
95         uint8_t buf[80], *wrptr;
96         size_t idx, count;
97         int ret;
98
99         if (2 + 2 * len > sizeof(buf)) {
100                 sr_err("Write buffer too small to write %zu bytes.", len);
101                 return SR_ERR_BUG;
102         }
103
104         wrptr = buf;
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));
110         }
111         count = wrptr - buf;
112         ret = sigma_write(devc, buf, count);
113         if (ret != SR_OK)
114                 return ret;
115
116         return SR_OK;
117 }
118
119 SR_PRIV int sigma_set_register(struct dev_context *devc,
120         uint8_t reg, uint8_t value)
121 {
122         return sigma_write_register(devc, reg, &value, sizeof(value));
123 }
124
125 static int sigma_read_register(struct dev_context *devc,
126         uint8_t reg, uint8_t *data, size_t len)
127 {
128         uint8_t buf[3], *wrptr;
129
130         wrptr = buf;
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);
135
136         return sigma_read(devc, data, len);
137 }
138
139 static int sigma_read_pos(struct dev_context *devc,
140         uint32_t *stoppos, uint32_t *triggerpos)
141 {
142         /*
143          * Read 6 registers starting at trigger position LSB.
144          * Which yields two 24bit counter values.
145          */
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,
154         }, *rdptr;
155         uint8_t result[6];
156
157         sigma_write(devc, buf, sizeof(buf));
158
159         sigma_read(devc, result, sizeof(result));
160
161         rdptr = &result[0];
162         *triggerpos = read_u24le_inc(&rdptr);
163         *stoppos = read_u24le_inc(&rdptr);
164
165         /*
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
169          * timestamps.
170          *
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.
175          */
176         if ((--*stoppos & ROW_MASK) == ROW_MASK)
177                 *stoppos -= CLUSTERS_PER_ROW;
178         if ((--*triggerpos & ROW_MASK) == ROW_MASK)
179                 *triggerpos -= CLUSTERS_PER_ROW;
180
181         return SR_OK;
182 }
183
184 static int sigma_read_dram(struct dev_context *devc,
185         uint16_t startchunk, size_t numchunks, uint8_t *data)
186 {
187         uint8_t buf[128], *wrptr;
188         size_t chunk;
189         int sel;
190         gboolean is_last;
191
192         if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
193                 sr_err("Read buffer too small to read %zu DRAM rows", numchunks);
194                 return SR_ERR_BUG;
195         }
196
197         /* Communicate DRAM start address (memory row, aka samples line). */
198         wrptr = buf;
199         write_u8_inc(&wrptr, startchunk >> 8);
200         write_u8_inc(&wrptr, startchunk & 0xff);
201         sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
202
203         /*
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.
207          */
208         wrptr = buf;
209         write_u8_inc(&wrptr, REG_DRAM_BLOCK);
210         write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
211         for (chunk = 0; chunk < numchunks; chunk++) {
212                 sel = chunk % 2;
213                 is_last = chunk == numchunks - 1;
214                 if (!is_last)
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));
217                 if (!is_last)
218                         write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
219         }
220         sigma_write(devc, buf, wrptr - buf);
221
222         return sigma_read(devc, data, numchunks * ROW_LENGTH_BYTES);
223 }
224
225 /* Upload trigger look-up tables to Sigma. */
226 SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
227         struct triggerlut *lut)
228 {
229         int i;
230         uint8_t tmp[2];
231         uint16_t bit;
232         uint8_t buf[6], *wrptr, regval;
233
234         /* Transpose the table and send to Sigma. */
235         for (i = 0; i < 16; i++) {
236                 bit = 1 << i;
237
238                 tmp[0] = tmp[1] = 0;
239
240                 if (lut->m2d[0] & bit)
241                         tmp[0] |= 0x01;
242                 if (lut->m2d[1] & bit)
243                         tmp[0] |= 0x02;
244                 if (lut->m2d[2] & bit)
245                         tmp[0] |= 0x04;
246                 if (lut->m2d[3] & bit)
247                         tmp[0] |= 0x08;
248
249                 if (lut->m3 & bit)
250                         tmp[0] |= 0x10;
251                 if (lut->m3s & bit)
252                         tmp[0] |= 0x20;
253                 if (lut->m4 & bit)
254                         tmp[0] |= 0x40;
255
256                 if (lut->m0d[0] & bit)
257                         tmp[1] |= 0x01;
258                 if (lut->m0d[1] & bit)
259                         tmp[1] |= 0x02;
260                 if (lut->m0d[2] & bit)
261                         tmp[1] |= 0x04;
262                 if (lut->m0d[3] & bit)
263                         tmp[1] |= 0x08;
264
265                 if (lut->m1d[0] & bit)
266                         tmp[1] |= 0x10;
267                 if (lut->m1d[1] & bit)
268                         tmp[1] |= 0x20;
269                 if (lut->m1d[2] & bit)
270                         tmp[1] |= 0x40;
271                 if (lut->m1d[3] & bit)
272                         tmp[1] |= 0x80;
273
274                 /*
275                  * This logic seems redundant, but separates the value
276                  * determination from the wire format, and is useful
277                  * during future maintenance and research.
278                  */
279                 wrptr = buf;
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);
284         }
285
286         /* Send the parameters */
287         wrptr = buf;
288         regval = 0;
289         regval |= lut->params.selc << 6;
290         regval |= lut->params.selpresc << 0;
291         write_u8_inc(&wrptr, regval);
292         regval = 0;
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);
301
302         return SR_OK;
303 }
304
305 /*
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.)
313  *
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.
317  *
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.
321  *
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
325  * a few times.
326  */
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 */
335
336 #define BB_BITRATE (750 * 1000)
337 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
338
339 /*
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.
343  *
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.
350  */
351 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
352 {
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,
362         };
363         const uint8_t init_array[] = {
364                 BB_PIN_CCLK,
365                 BB_PIN_CCLK | BB_PIN_PROG,
366                 BB_PIN_CCLK | BB_PIN_PROG,
367                 BB_PIN_CCLK,
368                 BB_PIN_CCLK,
369                 BB_PIN_CCLK,
370                 BB_PIN_CCLK,
371                 BB_PIN_CCLK,
372                 BB_PIN_CCLK,
373                 BB_PIN_CCLK,
374         };
375         int retries, ret;
376         uint8_t data;
377
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));
383         g_usleep(10 * 1000);
384
385         /* Section 2. part 2), pulse PROG. */
386         sigma_write(devc, init_array, sizeof(init_array));
387         g_usleep(10 * 1000);
388         ftdi_usb_purge_buffers(&devc->ftdic);
389
390         /* Wait until the FPGA asserts INIT_B. */
391         retries = 10;
392         while (retries--) {
393                 ret = sigma_read(devc, &data, sizeof(data));
394                 if (ret < 0)
395                         return ret;
396                 if (data & BB_PIN_INIT)
397                         return SR_OK;
398                 g_usleep(10 * 1000);
399         }
400
401         return SR_ERR_TIMEOUT;
402 }
403
404 /*
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).
408  */
409 static int sigma_fpga_init_bitbang(struct dev_context *devc)
410 {
411         size_t retries;
412         int ret;
413
414         retries = 10;
415         while (retries--) {
416                 ret = sigma_fpga_init_bitbang_once(devc);
417                 if (ret == SR_OK)
418                         return ret;
419                 if (ret != SR_ERR_TIMEOUT)
420                         return ret;
421         }
422         return ret;
423 }
424
425 /*
426  * Configure the FPGA for logic-analyzer mode.
427  */
428 static int sigma_fpga_init_la(struct dev_context *devc)
429 {
430         uint8_t buf[16], *wrptr;
431         uint8_t data_55, data_aa, mode;
432         uint8_t result[3];
433         const uint8_t *rdptr;
434         int ret;
435
436         wrptr = buf;
437
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);
442
443         /* Write 0x55 to scratch register, read back. */
444         data_55 = 0x55;
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);
449
450         /* Write 0xaa to scratch register, read back. */
451         data_aa = 0xaa;
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);
456
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));
462
463         /*
464          * Send the command sequence which contains 3 READ requests.
465          * Expect to see the corresponding 3 response bytes.
466          */
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.");
471                 return SR_ERR_IO;
472         }
473         rdptr = result;
474         if (read_u8_inc(&rdptr) != 0xa6) {
475                 sr_err("Unexpected ID response.");
476                 return SR_ERR_DATA;
477         }
478         if (read_u8_inc(&rdptr) != data_55) {
479                 sr_err("Unexpected scratch read-back (55).");
480                 return SR_ERR_DATA;
481         }
482         if (read_u8_inc(&rdptr) != data_aa) {
483                 sr_err("Unexpected scratch read-back (aa).");
484                 return SR_ERR_DATA;
485         }
486
487         return SR_OK;
488 }
489
490 /*
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.
494  */
495 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
496         uint8_t **bb_cmd, gsize *bb_cmd_size)
497 {
498         uint8_t *firmware;
499         size_t file_size;
500         uint8_t *p;
501         size_t l;
502         uint32_t imm;
503         size_t bb_size;
504         uint8_t *bb_stream, *bbs, byte, mask, v;
505
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);
509         if (!firmware)
510                 return SR_ERR_IO;
511
512         /* Unscramble the file content (XOR with "random" sequence). */
513         p = firmware;
514         l = file_size;
515         imm = 0x3f6df2ab;
516         while (l--) {
517                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
518                 *p++ ^= imm & 0xff;
519         }
520
521         /*
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).
526          *
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.
532          *
533          * The caller will put the FPGA into download mode, will send
534          * the bitbang samples, and release the allocated memory.
535          */
536         bb_size = file_size * 8 * 2;
537         bb_stream = g_try_malloc(bb_size);
538         if (!bb_stream) {
539                 sr_err("%s: Failed to allocate bitbang stream", __func__);
540                 g_free(firmware);
541                 return SR_ERR_MALLOC;
542         }
543         bbs = bb_stream;
544         p = firmware;
545         l = file_size;
546         while (l--) {
547                 byte = *p++;
548                 mask = 0x80;
549                 while (mask) {
550                         v = (byte & mask) ? BB_PIN_DIN : 0;
551                         mask >>= 1;
552                         *bbs++ = v | BB_PIN_CCLK;
553                         *bbs++ = v;
554                 }
555         }
556         g_free(firmware);
557
558         /* The transformation completed successfully, return the result. */
559         *bb_cmd = bb_stream;
560         *bb_cmd_size = bb_size;
561
562         return SR_OK;
563 }
564
565 static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
566         enum sigma_firmware_idx firmware_idx)
567 {
568         int ret;
569         uint8_t *buf;
570         uint8_t pins;
571         size_t buf_size;
572         const char *firmware;
573
574         /* Check for valid firmware file selection. */
575         if (firmware_idx >= ARRAY_SIZE(firmware_files))
576                 return SR_ERR_ARG;
577         firmware = firmware_files[firmware_idx];
578         if (!firmware || !*firmware)
579                 return SR_ERR_ARG;
580
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);
584                 return SR_OK;
585         }
586
587         devc->state.state = SIGMA_CONFIG;
588
589         /* Set the cable to bitbang mode. */
590         ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
591         if (ret < 0) {
592                 sr_err("ftdi_set_bitmode failed: %s",
593                         ftdi_get_error_string(&devc->ftdic));
594                 return SR_ERR;
595         }
596         ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
597         if (ret < 0) {
598                 sr_err("ftdi_set_baudrate failed: %s",
599                         ftdi_get_error_string(&devc->ftdic));
600                 return SR_ERR;
601         }
602
603         /* Initiate FPGA configuration mode. */
604         ret = sigma_fpga_init_bitbang(devc);
605         if (ret)
606                 return ret;
607
608         /* Prepare wire format of the firmware image. */
609         ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
610         if (ret != SR_OK) {
611                 sr_err("Could not prepare file %s for download.", firmware);
612                 return ret;
613         }
614
615         /* Write the FPGA netlist to the cable. */
616         sr_info("Uploading firmware file '%s'.", firmware);
617         sigma_write(devc, buf, buf_size);
618
619         g_free(buf);
620
621         /* Leave bitbang mode and discard pending input data. */
622         ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
623         if (ret < 0) {
624                 sr_err("ftdi_set_bitmode failed: %s",
625                         ftdi_get_error_string(&devc->ftdic));
626                 return SR_ERR;
627         }
628         ftdi_usb_purge_buffers(&devc->ftdic);
629         while (sigma_read(devc, &pins, sizeof(pins)) > 0)
630                 ;
631
632         /* Initialize the FPGA for logic-analyzer mode. */
633         ret = sigma_fpga_init_la(devc);
634         if (ret != SR_OK)
635                 return ret;
636
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.");
641
642         return SR_OK;
643 }
644
645 /*
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:
651  *
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.
661  *
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).
666  */
667 SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
668 {
669         int ret;
670         GVariant *data;
671         uint64_t user_count, user_msecs;
672         uint64_t worst_cluster_time_ms;
673         uint64_t count_msecs, acquire_msecs;
674
675         sr_sw_limits_init(&devc->acq_limits);
676
677         /* Get sample count limit, convert to msecs. */
678         ret = sr_sw_limits_config_get(&devc->cfg_limits,
679                 SR_CONF_LIMIT_SAMPLES, &data);
680         if (ret != SR_OK)
681                 return ret;
682         user_count = g_variant_get_uint64(data);
683         g_variant_unref(data);
684         count_msecs = 0;
685         if (user_count)
686                 count_msecs = 1000 * user_count / devc->samplerate + 1;
687
688         /* Get time limit, which is in msecs. */
689         ret = sr_sw_limits_config_get(&devc->cfg_limits,
690                 SR_CONF_LIMIT_MSEC, &data);
691         if (ret != SR_OK)
692                 return ret;
693         user_msecs = g_variant_get_uint64(data);
694         g_variant_unref(data);
695
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)
703                 return SR_OK;
704
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);
712         if (ret != SR_OK)
713                 return ret;
714
715         sr_sw_limits_acquisition_start(&devc->acq_limits);
716         return SR_OK;
717 }
718
719 /*
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.
723  *
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.
733  */
734 SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
735 {
736         uint64_t div, rate;
737
738         /* Accept exact matches for 100/200MHz. */
739         if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
740                 if (have_rate)
741                         *have_rate = want_rate;
742                 return SR_OK;
743         }
744
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;
749                 if (have_rate)
750                         *have_rate = rate;
751                 return SR_OK;
752         }
753
754         return SR_ERR_ARG;
755 }
756
757 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
758 {
759         struct dev_context *devc;
760         struct drv_context *drvc;
761         uint64_t samplerate;
762         int ret;
763         int num_channels;
764
765         devc = sdi->priv;
766         drvc = sdi->driver->context;
767
768         /* Accept any caller specified rate which the hardware supports. */
769         ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
770         if (ret != SR_OK)
771                 return ret;
772
773         /*
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.
777          */
778         num_channels = devc->num_channels;
779         if (samplerate <= SR_MHZ(50)) {
780                 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
781                 num_channels = 16;
782         } else if (samplerate == SR_MHZ(100)) {
783                 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
784                 num_channels = 8;
785         } else if (samplerate == SR_MHZ(200)) {
786                 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
787                 num_channels = 4;
788         }
789
790         /*
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").
794          */
795         if (ret == SR_OK) {
796                 devc->num_channels = num_channels;
797                 devc->samples_per_event = 16 / devc->num_channels;
798         }
799
800         return ret;
801 }
802
803 /*
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.
807  *
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).
810  */
811
812 #define CHUNK_SIZE      (4 * 1024 * 1024)
813
814 struct submit_buffer {
815         size_t unit_size;
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;
822 };
823
824 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
825 {
826         struct dev_context *devc;
827         struct submit_buffer *buffer;
828         size_t size;
829
830         devc = sdi->priv;
831
832         buffer = g_malloc0(sizeof(*buffer));
833         devc->buffer = buffer;
834
835         buffer->unit_size = sizeof(uint16_t);
836         size = CHUNK_SIZE;
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);
845
846         buffer->sdi = sdi;
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;
853
854         return SR_OK;
855 }
856
857 static int setup_submit_limit(struct dev_context *devc)
858 {
859         struct sr_sw_limits *limits;
860         int ret;
861         GVariant *data;
862         uint64_t total;
863
864         limits = &devc->feed_limits;
865
866         ret = sr_sw_limits_config_get(&devc->cfg_limits,
867                 SR_CONF_LIMIT_SAMPLES, &data);
868         if (ret != SR_OK)
869                 return ret;
870         total = g_variant_get_uint64(data);
871         g_variant_unref(data);
872
873         sr_sw_limits_init(limits);
874         if (total) {
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);
879                 if (ret != SR_OK)
880                         return ret;
881         }
882
883         sr_sw_limits_acquisition_start(limits);
884
885         return SR_OK;
886 }
887
888 static void free_submit_buffer(struct dev_context *devc)
889 {
890         struct submit_buffer *buffer;
891
892         if (!devc)
893                 return;
894
895         buffer = devc->buffer;
896         if (!buffer)
897                 return;
898         devc->buffer = NULL;
899
900         g_free(buffer->sample_data);
901         g_free(buffer);
902 }
903
904 static int flush_submit_buffer(struct dev_context *devc)
905 {
906         struct submit_buffer *buffer;
907         int ret;
908
909         buffer = devc->buffer;
910
911         /* Is queued sample data available? */
912         if (!buffer->curr_samples)
913                 return SR_OK;
914
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);
918         if (ret != SR_OK)
919                 return ret;
920
921         /* Rewind queue position. */
922         buffer->curr_samples = 0;
923         buffer->write_pointer = buffer->sample_data;
924
925         return SR_OK;
926 }
927
928 static int addto_submit_buffer(struct dev_context *devc,
929         uint16_t sample, size_t count)
930 {
931         struct submit_buffer *buffer;
932         struct sr_sw_limits *limits;
933         int ret;
934
935         buffer = devc->buffer;
936         limits = &devc->feed_limits;
937         if (sr_sw_limits_check(limits))
938                 count = 0;
939
940         /*
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.
944          */
945         while (count--) {
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);
950                         if (ret != SR_OK)
951                                 return ret;
952                 }
953                 sr_sw_limits_update_samples_read(limits, 1);
954                 if (sr_sw_limits_check(limits))
955                         break;
956         }
957
958         return SR_OK;
959 }
960
961 /*
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.
965  *
966  * The Sigma supports complex triggers using boolean expressions, but this
967  * has not been implemented yet.
968  */
969 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
970 {
971         struct dev_context *devc;
972         struct sr_trigger *trigger;
973         struct sr_trigger_stage *stage;
974         struct sr_trigger_match *match;
975         const GSList *l, *m;
976         int channelbit, trigger_set;
977
978         devc = sdi->priv;
979         memset(&devc->trigger, 0, sizeof(devc->trigger));
980         trigger = sr_session_trigger_get(sdi->session);
981         if (!trigger)
982                 return SR_OK;
983
984         trigger_set = 0;
985         for (l = trigger->stages; l; l = l->next) {
986                 stage = l->data;
987                 for (m = stage->matches; m; m = m->next) {
988                         match = m->data;
989                         /* Ignore disabled channels with a trigger. */
990                         if (!match->channel->enabled)
991                                 continue;
992                         channelbit = 1 << match->channel->index;
993                         if (devc->samplerate >= SR_MHZ(100)) {
994                                 /* Fast trigger support. */
995                                 if (trigger_set) {
996                                         sr_err("Only a single pin trigger is "
997                                                 "supported in 100 and 200MHz mode.");
998                                         return SR_ERR;
999                                 }
1000                                 if (match->match == SR_TRIGGER_FALLING) {
1001                                         devc->trigger.fallingmask |= channelbit;
1002                                 } else if (match->match == SR_TRIGGER_RISING) {
1003                                         devc->trigger.risingmask |= channelbit;
1004                                 } else {
1005                                         sr_err("Only rising/falling trigger is "
1006                                                 "supported in 100 and 200MHz mode.");
1007                                         return SR_ERR;
1008                                 }
1009
1010                                 trigger_set++;
1011                         } else {
1012                                 /* Simple trigger support (event). */
1013                                 if (match->match == SR_TRIGGER_ONE) {
1014                                         devc->trigger.simplevalue |= channelbit;
1015                                         devc->trigger.simplemask |= channelbit;
1016                                 } else if (match->match == SR_TRIGGER_ZERO) {
1017                                         devc->trigger.simplevalue &= ~channelbit;
1018                                         devc->trigger.simplemask |= channelbit;
1019                                 } else if (match->match == SR_TRIGGER_FALLING) {
1020                                         devc->trigger.fallingmask |= channelbit;
1021                                         trigger_set++;
1022                                 } else if (match->match == SR_TRIGGER_RISING) {
1023                                         devc->trigger.risingmask |= channelbit;
1024                                         trigger_set++;
1025                                 }
1026
1027                                 /*
1028                                  * Actually, Sigma supports 2 rising/falling triggers,
1029                                  * but they are ORed and the current trigger syntax
1030                                  * does not permit ORed triggers.
1031                                  */
1032                                 if (trigger_set > 1) {
1033                                         sr_err("Only 1 rising/falling trigger is supported.");
1034                                         return SR_ERR;
1035                                 }
1036                         }
1037                 }
1038         }
1039
1040         return SR_OK;
1041 }
1042
1043 /* Software trigger to determine exact trigger position. */
1044 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1045         struct sigma_trigger *t)
1046 {
1047         const uint8_t *rdptr;
1048         int i;
1049         uint16_t sample;
1050
1051         rdptr = samples;
1052         sample = 0;
1053         for (i = 0; i < 8; i++) {
1054                 if (i > 0)
1055                         last_sample = sample;
1056                 sample = read_u16le_inc(&rdptr);
1057
1058                 /* Simple triggers. */
1059                 if ((sample & t->simplemask) != t->simplevalue)
1060                         continue;
1061
1062                 /* Rising edge. */
1063                 if (((last_sample & t->risingmask) != 0) ||
1064                     ((sample & t->risingmask) != t->risingmask))
1065                         continue;
1066
1067                 /* Falling edge. */
1068                 if ((last_sample & t->fallingmask) != t->fallingmask ||
1069                     (sample & t->fallingmask) != 0)
1070                         continue;
1071
1072                 break;
1073         }
1074
1075         /* If we did not match, return original trigger pos. */
1076         return i & 0x7;
1077 }
1078
1079 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1080 {
1081         /* TODO
1082          * Check whether the combination of this very sample and the
1083          * previous state match the configured trigger condition. This
1084          * improves the resolution of the trigger marker's position.
1085          * The hardware provided position is coarse, and may point to
1086          * a position before the actual match.
1087          *
1088          * See the previous get_trigger_offset() implementation. This
1089          * code needs to get re-used here.
1090          */
1091         (void)devc;
1092         (void)sample;
1093         (void)get_trigger_offset;
1094
1095         return FALSE;
1096 }
1097
1098 static int check_and_submit_sample(struct dev_context *devc,
1099         uint16_t sample, size_t count, gboolean check_trigger)
1100 {
1101         gboolean triggered;
1102         int ret;
1103
1104         triggered = check_trigger && sample_matches_trigger(devc, sample);
1105         if (triggered) {
1106                 ret = flush_submit_buffer(devc);
1107                 if (ret != SR_OK)
1108                         return ret;
1109                 ret = std_session_send_df_trigger(devc->buffer->sdi);
1110                 if (ret != SR_OK)
1111                         return ret;
1112         }
1113
1114         ret = addto_submit_buffer(devc, sample, count);
1115         if (ret != SR_OK)
1116                 return ret;
1117
1118         return SR_OK;
1119 }
1120
1121 /*
1122  * Return the timestamp of "DRAM cluster".
1123  */
1124 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1125 {
1126         return read_u16le((const uint8_t *)&cluster->timestamp);
1127 }
1128
1129 /*
1130  * Return one 16bit data entity of a DRAM cluster at the specified index.
1131  */
1132 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1133 {
1134         return read_u16le((const uint8_t *)&cl->samples[idx]);
1135 }
1136
1137 /*
1138  * Deinterlace sample data that was retrieved at 100MHz samplerate.
1139  * One 16bit item contains two samples of 8bits each. The bits of
1140  * multiple samples are interleaved.
1141  */
1142 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1143 {
1144         uint16_t outdata;
1145
1146         indata >>= idx;
1147         outdata = 0;
1148         outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1149         outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1150         outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1151         outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1152         outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1153         outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1154         outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1155         outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1156         return outdata;
1157 }
1158
1159 /*
1160  * Deinterlace sample data that was retrieved at 200MHz samplerate.
1161  * One 16bit item contains four samples of 4bits each. The bits of
1162  * multiple samples are interleaved.
1163  */
1164 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1165 {
1166         uint16_t outdata;
1167
1168         indata >>= idx;
1169         outdata = 0;
1170         outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1171         outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1172         outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1173         outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1174         return outdata;
1175 }
1176
1177 static void sigma_decode_dram_cluster(struct dev_context *devc,
1178         struct sigma_dram_cluster *dram_cluster,
1179         size_t events_in_cluster, gboolean triggered)
1180 {
1181         struct sigma_state *ss;
1182         uint16_t tsdiff, ts, sample, item16;
1183         unsigned int i;
1184
1185         if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1186                 triggered = FALSE;
1187
1188         /*
1189          * If this cluster is not adjacent to the previously received
1190          * cluster, then send the appropriate number of samples with the
1191          * previous values to the sigrok session. This "decodes RLE".
1192          *
1193          * These samples cannot match the trigger since they just repeat
1194          * the previously submitted data pattern. (This assumption holds
1195          * for simple level and edge triggers. It would not for timed or
1196          * counted conditions, which currently are not supported.)
1197          */
1198         ss = &devc->state;
1199         ts = sigma_dram_cluster_ts(dram_cluster);
1200         tsdiff = ts - ss->lastts;
1201         if (tsdiff > 0) {
1202                 size_t count;
1203                 sample = ss->lastsample;
1204                 count = tsdiff * devc->samples_per_event;
1205                 (void)check_and_submit_sample(devc, sample, count, FALSE);
1206         }
1207         ss->lastts = ts + EVENTS_PER_CLUSTER;
1208
1209         /*
1210          * Grab sample data from the current cluster and prepare their
1211          * submission to the session feed. Handle samplerate dependent
1212          * memory layout of sample data. Accumulation of data chunks
1213          * before submission is transparent to this code path, specific
1214          * buffer depth is neither assumed nor required here.
1215          */
1216         sample = 0;
1217         for (i = 0; i < events_in_cluster; i++) {
1218                 item16 = sigma_dram_cluster_data(dram_cluster, i);
1219                 if (devc->samplerate == SR_MHZ(200)) {
1220                         sample = sigma_deinterlace_200mhz_data(item16, 0);
1221                         check_and_submit_sample(devc, sample, 1, triggered);
1222                         sample = sigma_deinterlace_200mhz_data(item16, 1);
1223                         check_and_submit_sample(devc, sample, 1, triggered);
1224                         sample = sigma_deinterlace_200mhz_data(item16, 2);
1225                         check_and_submit_sample(devc, sample, 1, triggered);
1226                         sample = sigma_deinterlace_200mhz_data(item16, 3);
1227                         check_and_submit_sample(devc, sample, 1, triggered);
1228                 } else if (devc->samplerate == SR_MHZ(100)) {
1229                         sample = sigma_deinterlace_100mhz_data(item16, 0);
1230                         check_and_submit_sample(devc, sample, 1, triggered);
1231                         sample = sigma_deinterlace_100mhz_data(item16, 1);
1232                         check_and_submit_sample(devc, sample, 1, triggered);
1233                 } else {
1234                         sample = item16;
1235                         check_and_submit_sample(devc, sample, 1, triggered);
1236                 }
1237         }
1238         ss->lastsample = sample;
1239 }
1240
1241 /*
1242  * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1243  * Each event is 20ns apart, and can contain multiple samples.
1244  *
1245  * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1246  * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1247  * For 50 MHz and below, events contain one sample for each channel,
1248  * spread 20 ns apart.
1249  */
1250 static int decode_chunk_ts(struct dev_context *devc,
1251         struct sigma_dram_line *dram_line,
1252         size_t events_in_line, size_t trigger_event)
1253 {
1254         struct sigma_dram_cluster *dram_cluster;
1255         unsigned int clusters_in_line;
1256         unsigned int events_in_cluster;
1257         unsigned int i;
1258         uint32_t trigger_cluster;
1259
1260         clusters_in_line = events_in_line;
1261         clusters_in_line += EVENTS_PER_CLUSTER - 1;
1262         clusters_in_line /= EVENTS_PER_CLUSTER;
1263         trigger_cluster = ~0;
1264
1265         /* Check if trigger is in this chunk. */
1266         if (trigger_event < EVENTS_PER_ROW) {
1267                 if (devc->samplerate <= SR_MHZ(50)) {
1268                         trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1269                                              trigger_event);
1270                 }
1271
1272                 /* Find in which cluster the trigger occurred. */
1273                 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1274         }
1275
1276         /* For each full DRAM cluster. */
1277         for (i = 0; i < clusters_in_line; i++) {
1278                 dram_cluster = &dram_line->cluster[i];
1279
1280                 /* The last cluster might not be full. */
1281                 if ((i == clusters_in_line - 1) &&
1282                     (events_in_line % EVENTS_PER_CLUSTER)) {
1283                         events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1284                 } else {
1285                         events_in_cluster = EVENTS_PER_CLUSTER;
1286                 }
1287
1288                 sigma_decode_dram_cluster(devc, dram_cluster,
1289                         events_in_cluster, i == trigger_cluster);
1290         }
1291
1292         return SR_OK;
1293 }
1294
1295 static int download_capture(struct sr_dev_inst *sdi)
1296 {
1297         const uint32_t chunks_per_read = 32;
1298
1299         struct dev_context *devc;
1300         struct sigma_dram_line *dram_line;
1301         int bufsz;
1302         uint32_t stoppos, triggerpos;
1303         uint8_t modestatus;
1304         uint32_t i;
1305         uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1306         uint32_t dl_first_line, dl_line;
1307         uint32_t dl_events_in_line, trigger_event;
1308         uint32_t trg_line, trg_event;
1309         int ret;
1310
1311         devc = sdi->priv;
1312
1313         sr_info("Downloading sample data.");
1314         devc->state.state = SIGMA_DOWNLOAD;
1315
1316         /*
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.
1321          */
1322         sigma_set_register(devc, WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN);
1323         do {
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.");
1328                         return FALSE;
1329                 }
1330         } while (!(modestatus & RMR_POSTTRIGGERED));
1331
1332         /* Set SDRAM Read Enable. */
1333         sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
1334
1335         /* Get the current position. */
1336         sigma_read_pos(devc, &stoppos, &triggerpos);
1337
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.");
1343                 return FALSE;
1344         }
1345         trg_line = ~0;
1346         trg_event = ~0;
1347         if (modestatus & RMR_TRIGGERED) {
1348                 trg_line = triggerpos >> ROW_SHIFT;
1349                 trg_event = triggerpos & ROW_MASK;
1350         }
1351
1352         /*
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.
1357          *
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.
1361          */
1362         dl_first_line = 0;
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;
1367         }
1368         dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1369         if (!dram_line)
1370                 return FALSE;
1371         ret = alloc_submit_buffer(sdi);
1372         if (ret != SR_OK)
1373                 return FALSE;
1374         ret = setup_submit_limit(devc);
1375         if (ret != SR_OK)
1376                 return FALSE;
1377         dl_lines_done = 0;
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);
1381
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. */
1387                 (void)bufsz;
1388
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;
1394                 }
1395
1396                 for (i = 0; i < dl_lines_curr; i++) {
1397                         /* The last "DRAM line" need not span its full length. */
1398                         dl_events_in_line = EVENTS_PER_ROW;
1399                         if (dl_lines_done + i == dl_lines_total - 1)
1400                                 dl_events_in_line = stoppos & ROW_MASK;
1401
1402                         /* Test if the trigger happened on this line. */
1403                         trigger_event = ~0;
1404                         if (dl_lines_done + i == trg_line)
1405                                 trigger_event = trg_event;
1406
1407                         decode_chunk_ts(devc, dram_line + i,
1408                                 dl_events_in_line, trigger_event);
1409                 }
1410
1411                 dl_lines_done += dl_lines_curr;
1412         }
1413         flush_submit_buffer(devc);
1414         free_submit_buffer(devc);
1415         g_free(dram_line);
1416
1417         std_session_send_df_end(sdi);
1418
1419         devc->state.state = SIGMA_IDLE;
1420         sr_dev_acquisition_stop(sdi);
1421
1422         return TRUE;
1423 }
1424
1425 /*
1426  * Periodically check the Sigma status when in CAPTURE mode. This routine
1427  * checks whether the configured sample count or sample time have passed,
1428  * and will stop acquisition and download the acquired samples.
1429  */
1430 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1431 {
1432         struct dev_context *devc;
1433
1434         devc = sdi->priv;
1435         if (sr_sw_limits_check(&devc->acq_limits))
1436                 return download_capture(sdi);
1437
1438         return TRUE;
1439 }
1440
1441 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1442 {
1443         struct sr_dev_inst *sdi;
1444         struct dev_context *devc;
1445
1446         (void)fd;
1447         (void)revents;
1448
1449         sdi = cb_data;
1450         devc = sdi->priv;
1451
1452         if (devc->state.state == SIGMA_IDLE)
1453                 return TRUE;
1454
1455         /*
1456          * When the application has requested to stop the acquisition,
1457          * then immediately start downloading sample data. Otherwise
1458          * keep checking configured limits which will terminate the
1459          * acquisition and initiate download.
1460          */
1461         if (devc->state.state == SIGMA_STOPPING)
1462                 return download_capture(sdi);
1463         if (devc->state.state == SIGMA_CAPTURE)
1464                 return sigma_capture_mode(sdi);
1465
1466         return TRUE;
1467 }
1468
1469 /* Build a LUT entry used by the trigger functions. */
1470 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1471 {
1472         int i, j, k, bit;
1473
1474         /* For each quad channel. */
1475         for (i = 0; i < 4; i++) {
1476                 entry[i] = 0xffff;
1477
1478                 /* For each bit in LUT. */
1479                 for (j = 0; j < 16; j++) {
1480
1481                         /* For each channel in quad. */
1482                         for (k = 0; k < 4; k++) {
1483                                 bit = 1 << (i * 4 + k);
1484
1485                                 /* Set bit in entry */
1486                                 if ((mask & bit) && ((!(value & bit)) !=
1487                                                         (!(j & (1 << k)))))
1488                                         entry[i] &= ~(1 << j);
1489                         }
1490                 }
1491         }
1492 }
1493
1494 /* Add a logical function to LUT mask. */
1495 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1496         int index, int neg, uint16_t *mask)
1497 {
1498         int i, j;
1499         int x[2][2], tmp, a, b, aset, bset, rset;
1500
1501         memset(x, 0, sizeof(x));
1502
1503         /* Trigger detect condition. */
1504         switch (oper) {
1505         case OP_LEVEL:
1506                 x[0][1] = 1;
1507                 x[1][1] = 1;
1508                 break;
1509         case OP_NOT:
1510                 x[0][0] = 1;
1511                 x[1][0] = 1;
1512                 break;
1513         case OP_RISE:
1514                 x[0][1] = 1;
1515                 break;
1516         case OP_FALL:
1517                 x[1][0] = 1;
1518                 break;
1519         case OP_RISEFALL:
1520                 x[0][1] = 1;
1521                 x[1][0] = 1;
1522                 break;
1523         case OP_NOTRISE:
1524                 x[1][1] = 1;
1525                 x[0][0] = 1;
1526                 x[1][0] = 1;
1527                 break;
1528         case OP_NOTFALL:
1529                 x[1][1] = 1;
1530                 x[0][0] = 1;
1531                 x[0][1] = 1;
1532                 break;
1533         case OP_NOTRISEFALL:
1534                 x[1][1] = 1;
1535                 x[0][0] = 1;
1536                 break;
1537         }
1538
1539         /* Transpose if neg is set. */
1540         if (neg) {
1541                 for (i = 0; i < 2; i++) {
1542                         for (j = 0; j < 2; j++) {
1543                                 tmp = x[i][j];
1544                                 x[i][j] = x[1 - i][1 - j];
1545                                 x[1 - i][1 - j] = tmp;
1546                         }
1547                 }
1548         }
1549
1550         /* Update mask with function. */
1551         for (i = 0; i < 16; i++) {
1552                 a = (i >> (2 * index + 0)) & 1;
1553                 b = (i >> (2 * index + 1)) & 1;
1554
1555                 aset = (*mask >> i) & 1;
1556                 bset = x[b][a];
1557
1558                 rset = 0;
1559                 if (func == FUNC_AND || func == FUNC_NAND)
1560                         rset = aset & bset;
1561                 else if (func == FUNC_OR || func == FUNC_NOR)
1562                         rset = aset | bset;
1563                 else if (func == FUNC_XOR || func == FUNC_NXOR)
1564                         rset = aset ^ bset;
1565
1566                 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1567                         rset = !rset;
1568
1569                 *mask &= ~(1 << i);
1570
1571                 if (rset)
1572                         *mask |= 1 << i;
1573         }
1574 }
1575
1576 /*
1577  * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1578  * simple pin change and state triggers. Only two transitions (rise/fall) can be
1579  * set at any time, but a full mask and value can be set (0/1).
1580  */
1581 SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
1582         struct triggerlut *lut)
1583 {
1584         int i,j;
1585         uint16_t masks[2];
1586
1587         memset(lut, 0, sizeof(*lut));
1588         memset(&masks, 0, sizeof(masks));
1589
1590         /* Constant for simple triggers. */
1591         lut->m4 = 0xa000;
1592
1593         /* Value/mask trigger support. */
1594         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1595                         lut->m2d);
1596
1597         /* Rise/fall trigger support. */
1598         for (i = 0, j = 0; i < 16; i++) {
1599                 if (devc->trigger.risingmask & (1 << i) ||
1600                     devc->trigger.fallingmask & (1 << i))
1601                         masks[j++] = 1 << i;
1602         }
1603
1604         build_lut_entry(masks[0], masks[0], lut->m0d);
1605         build_lut_entry(masks[1], masks[1], lut->m1d);
1606
1607         /* Add glue logic */
1608         if (masks[0] || masks[1]) {
1609                 /* Transition trigger. */
1610                 if (masks[0] & devc->trigger.risingmask)
1611                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1612                 if (masks[0] & devc->trigger.fallingmask)
1613                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1614                 if (masks[1] & devc->trigger.risingmask)
1615                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1616                 if (masks[1] & devc->trigger.fallingmask)
1617                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1618         } else {
1619                 /* Only value/mask trigger. */
1620                 lut->m3 = 0xffff;
1621         }
1622
1623         /* Triggertype: event. */
1624         lut->params.selres = 3;
1625
1626         return SR_OK;
1627 }