]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/protocol.c
f052c51cc6091ece3ff8dc0160d771a1df6ca57a
[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  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 /*
23  * ASIX SIGMA/SIGMA2 logic analyzer driver
24  */
25
26 #include <config.h>
27 #include "protocol.h"
28
29 /*
30  * The ASIX SIGMA hardware supports fixed 200MHz and 100MHz sample rates
31  * (by means of separate firmware images). As well as 50MHz divided by
32  * an integer divider in the 1..256 range (by the "typical" firmware).
33  * Which translates to a strict lower boundary of around 195kHz.
34  *
35  * This driver "suggests" a subset of the available rates by listing a
36  * few discrete values, while setter routines accept any user specified
37  * rate that is supported by the hardware.
38  */
39 SR_PRIV const uint64_t samplerates[] = {
40         /* 50MHz and integer divider. 1/2/5 steps (where possible). */
41         SR_KHZ(200), SR_KHZ(500),
42         SR_MHZ(1), SR_MHZ(2), SR_MHZ(5),
43         SR_MHZ(10), SR_MHZ(25), SR_MHZ(50),
44         /* 100MHz/200MHz, fixed rates in special firmware. */
45         SR_MHZ(100), SR_MHZ(200),
46 };
47
48 SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
49
50 static const char *firmware_files[] = {
51         [SIGMA_FW_50MHZ] = "asix-sigma-50.fw", /* 50MHz, 8bit divider. */
52         [SIGMA_FW_100MHZ] = "asix-sigma-100.fw", /* 100MHz, fixed. */
53         [SIGMA_FW_200MHZ] = "asix-sigma-200.fw", /* 200MHz, fixed. */
54         [SIGMA_FW_SYNC] = "asix-sigma-50sync.fw", /* Sync from external pin. */
55         [SIGMA_FW_FREQ] = "asix-sigma-phasor.fw", /* Frequency counter. */
56 };
57
58 #define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
59
60 static int sigma_read(struct dev_context *devc, void *buf, size_t size)
61 {
62         int ret;
63
64         ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
65         if (ret < 0) {
66                 sr_err("ftdi_read_data failed: %s",
67                         ftdi_get_error_string(&devc->ftdic));
68         }
69
70         return ret;
71 }
72
73 static int sigma_write(struct dev_context *devc, const void *buf, size_t size)
74 {
75         int ret;
76
77         ret = ftdi_write_data(&devc->ftdic, buf, size);
78         if (ret < 0)
79                 sr_err("ftdi_write_data failed: %s",
80                         ftdi_get_error_string(&devc->ftdic));
81         else if ((size_t) ret != size)
82                 sr_err("ftdi_write_data did not complete write.");
83
84         return ret;
85 }
86
87 /*
88  * NOTE: We chose the buffer size to be large enough to hold any write to the
89  * device. We still print a message just in case.
90  */
91 SR_PRIV int sigma_write_register(struct dev_context *devc,
92         uint8_t reg, uint8_t *data, size_t len)
93 {
94         uint8_t buf[80], *wrptr;
95         size_t idx, count;
96         int ret;
97
98         if (2 + 2 * len > sizeof(buf)) {
99                 sr_err("Write buffer too small to write %zu bytes.", len);
100                 return SR_ERR_BUG;
101         }
102
103         wrptr = buf;
104         write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
105         write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
106         for (idx = 0; idx < len; idx++) {
107                 write_u8_inc(&wrptr, REG_DATA_LOW | (data[idx] & 0xf));
108                 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data[idx] >> 4));
109         }
110         count = wrptr - buf;
111         ret = sigma_write(devc, buf, count);
112         if (ret != SR_OK)
113                 return ret;
114
115         return SR_OK;
116 }
117
118 SR_PRIV int sigma_set_register(struct dev_context *devc,
119         uint8_t reg, uint8_t value)
120 {
121         return sigma_write_register(devc, reg, &value, sizeof(value));
122 }
123
124 static int sigma_read_register(struct dev_context *devc,
125         uint8_t reg, uint8_t *data, size_t len)
126 {
127         uint8_t buf[3], *wrptr;
128
129         wrptr = buf;
130         write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
131         write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
132         write_u8_inc(&wrptr, REG_READ_ADDR);
133         sigma_write(devc, buf, wrptr - buf);
134
135         return sigma_read(devc, data, len);
136 }
137
138 static int sigma_read_pos(struct dev_context *devc,
139         uint32_t *stoppos, uint32_t *triggerpos)
140 {
141         /*
142          * Read 6 registers starting at trigger position LSB.
143          * Which yields two 24bit counter values.
144          */
145         const uint8_t buf[] = {
146                 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
147                 REG_READ_ADDR | REG_ADDR_INC,
148                 REG_READ_ADDR | REG_ADDR_INC,
149                 REG_READ_ADDR | REG_ADDR_INC,
150                 REG_READ_ADDR | REG_ADDR_INC,
151                 REG_READ_ADDR | REG_ADDR_INC,
152                 REG_READ_ADDR | REG_ADDR_INC,
153         }, *rdptr;
154         uint8_t result[6];
155
156         sigma_write(devc, buf, sizeof(buf));
157
158         sigma_read(devc, result, sizeof(result));
159
160         rdptr = &result[0];
161         *triggerpos = read_u24le_inc(&rdptr);
162         *stoppos = read_u24le_inc(&rdptr);
163
164         /*
165          * These positions consist of "the memory row" in the MSB fields,
166          * and "an event index" within the row in the LSB fields. Part
167          * of the memory row's content is sample data, another part is
168          * timestamps.
169          *
170          * The retrieved register values point to after the captured
171          * position. So they need to get decremented, and adjusted to
172          * cater for the timestamps when the decrement carries over to
173          * a different memory row.
174          */
175         if ((--*stoppos & ROW_MASK) == ROW_MASK)
176                 *stoppos -= CLUSTERS_PER_ROW;
177         if ((--*triggerpos & ROW_MASK) == ROW_MASK)
178                 *triggerpos -= CLUSTERS_PER_ROW;
179
180         return SR_OK;
181 }
182
183 static int sigma_read_dram(struct dev_context *devc,
184         uint16_t startchunk, size_t numchunks, uint8_t *data)
185 {
186         uint8_t buf[128], *wrptr;
187         size_t chunk;
188         int sel;
189         gboolean is_last;
190
191         if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
192                 sr_err("Read buffer too small to read %zu DRAM rows", numchunks);
193                 return SR_ERR_BUG;
194         }
195
196         /* Communicate DRAM start address (memory row, aka samples line). */
197         wrptr = buf;
198         write_u8_inc(&wrptr, startchunk >> 8);
199         write_u8_inc(&wrptr, startchunk & 0xff);
200         sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
201
202         /*
203          * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
204          * then transfer via USB. Interleave the FPGA's DRAM access and
205          * USB transfer, use alternating buffers (0/1) in the process.
206          */
207         wrptr = buf;
208         write_u8_inc(&wrptr, REG_DRAM_BLOCK);
209         write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
210         for (chunk = 0; chunk < numchunks; chunk++) {
211                 sel = chunk % 2;
212                 is_last = chunk == numchunks - 1;
213                 if (!is_last)
214                         write_u8_inc(&wrptr, REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel));
215                 write_u8_inc(&wrptr, REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel));
216                 if (!is_last)
217                         write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
218         }
219         sigma_write(devc, buf, wrptr - buf);
220
221         return sigma_read(devc, data, numchunks * ROW_LENGTH_BYTES);
222 }
223
224 /* Upload trigger look-up tables to Sigma. */
225 SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
226         struct triggerlut *lut)
227 {
228         int i;
229         uint8_t tmp[2];
230         uint16_t bit;
231         uint8_t buf[6], *wrptr, regval;
232
233         /* Transpose the table and send to Sigma. */
234         for (i = 0; i < 16; i++) {
235                 bit = 1 << i;
236
237                 tmp[0] = tmp[1] = 0;
238
239                 if (lut->m2d[0] & bit)
240                         tmp[0] |= 0x01;
241                 if (lut->m2d[1] & bit)
242                         tmp[0] |= 0x02;
243                 if (lut->m2d[2] & bit)
244                         tmp[0] |= 0x04;
245                 if (lut->m2d[3] & bit)
246                         tmp[0] |= 0x08;
247
248                 if (lut->m3 & bit)
249                         tmp[0] |= 0x10;
250                 if (lut->m3s & bit)
251                         tmp[0] |= 0x20;
252                 if (lut->m4 & bit)
253                         tmp[0] |= 0x40;
254
255                 if (lut->m0d[0] & bit)
256                         tmp[1] |= 0x01;
257                 if (lut->m0d[1] & bit)
258                         tmp[1] |= 0x02;
259                 if (lut->m0d[2] & bit)
260                         tmp[1] |= 0x04;
261                 if (lut->m0d[3] & bit)
262                         tmp[1] |= 0x08;
263
264                 if (lut->m1d[0] & bit)
265                         tmp[1] |= 0x10;
266                 if (lut->m1d[1] & bit)
267                         tmp[1] |= 0x20;
268                 if (lut->m1d[2] & bit)
269                         tmp[1] |= 0x40;
270                 if (lut->m1d[3] & bit)
271                         tmp[1] |= 0x80;
272
273                 /*
274                  * This logic seems redundant, but separates the value
275                  * determination from the wire format, and is useful
276                  * during future maintenance and research.
277                  */
278                 wrptr = buf;
279                 write_u8_inc(&wrptr, tmp[0]);
280                 write_u8_inc(&wrptr, tmp[1]);
281                 sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
282                 sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x30 | i);
283         }
284
285         /* Send the parameters */
286         wrptr = buf;
287         regval = 0;
288         regval |= lut->params.selc << 6;
289         regval |= lut->params.selpresc << 0;
290         write_u8_inc(&wrptr, regval);
291         regval = 0;
292         regval |= lut->params.selinc << 6;
293         regval |= lut->params.selres << 4;
294         regval |= lut->params.sela << 2;
295         regval |= lut->params.selb << 0;
296         write_u8_inc(&wrptr, regval);
297         write_u16le_inc(&wrptr, lut->params.cmpb);
298         write_u16le_inc(&wrptr, lut->params.cmpa);
299         sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
300
301         return SR_OK;
302 }
303
304 /*
305  * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
306  * uses FTDI bitbang mode for netlist download in slave serial mode.
307  * (LATER: The OMEGA device's cable contains a more capable FTDI chip
308  * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
309  * compatible bitbang mode? For maximum code re-use and reduced libftdi
310  * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
311  * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
312  *
313  * 750kbps rate (four times the speed of sigmalogan) works well for
314  * netlist download. All pins except INIT_B are output pins during
315  * configuration download.
316  *
317  * Some pins are inverted as a byproduct of level shifting circuitry.
318  * That's why high CCLK level (from the cable's point of view) is idle
319  * from the FPGA's perspective.
320  *
321  * The vendor's literature discusses a "suicide sequence" which ends
322  * regular FPGA execution and should be sent before entering bitbang
323  * mode and sending configuration data. Set D7 and toggle D2, D3, D4
324  * a few times.
325  */
326 #define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
327 #define BB_PIN_PROG (1 << 1) /* D1, PROG */
328 #define BB_PIN_D2   (1 << 2) /* D2, (part of) SUICIDE */
329 #define BB_PIN_D3   (1 << 3) /* D3, (part of) SUICIDE */
330 #define BB_PIN_D4   (1 << 4) /* D4, (part of) SUICIDE (unused?) */
331 #define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
332 #define BB_PIN_DIN  (1 << 6) /* D6, DIN */
333 #define BB_PIN_D7   (1 << 7) /* D7, (part of) SUICIDE */
334
335 #define BB_BITRATE (750 * 1000)
336 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
337
338 /*
339  * Initiate slave serial mode for configuration download. Which is done
340  * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
341  * initiating the configuration download.
342  *
343  * Run a "suicide sequence" first to terminate the regular FPGA operation
344  * before reconfiguration. The FTDI cable is single channel, and shares
345  * pins which are used for data communication in FIFO mode with pins that
346  * are used for FPGA configuration in bitbang mode. Hardware defaults for
347  * unconfigured hardware, and runtime conditions after FPGA configuration
348  * need to cooperate such that re-configuration of the FPGA can start.
349  */
350 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
351 {
352         const uint8_t suicide[] = {
353                 BB_PIN_D7 | BB_PIN_D2,
354                 BB_PIN_D7 | BB_PIN_D2,
355                 BB_PIN_D7 |           BB_PIN_D3,
356                 BB_PIN_D7 | BB_PIN_D2,
357                 BB_PIN_D7 |           BB_PIN_D3,
358                 BB_PIN_D7 | BB_PIN_D2,
359                 BB_PIN_D7 |           BB_PIN_D3,
360                 BB_PIN_D7 | BB_PIN_D2,
361         };
362         const uint8_t init_array[] = {
363                 BB_PIN_CCLK,
364                 BB_PIN_CCLK | BB_PIN_PROG,
365                 BB_PIN_CCLK | BB_PIN_PROG,
366                 BB_PIN_CCLK,
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         };
374         int retries, ret;
375         uint8_t data;
376
377         /* Section 2. part 1), do the FPGA suicide. */
378         sigma_write(devc, suicide, sizeof(suicide));
379         sigma_write(devc, suicide, sizeof(suicide));
380         sigma_write(devc, suicide, sizeof(suicide));
381         sigma_write(devc, suicide, sizeof(suicide));
382         g_usleep(10 * 1000);
383
384         /* Section 2. part 2), pulse PROG. */
385         sigma_write(devc, init_array, sizeof(init_array));
386         g_usleep(10 * 1000);
387         ftdi_usb_purge_buffers(&devc->ftdic);
388
389         /* Wait until the FPGA asserts INIT_B. */
390         retries = 10;
391         while (retries--) {
392                 ret = sigma_read(devc, &data, sizeof(data));
393                 if (ret < 0)
394                         return ret;
395                 if (data & BB_PIN_INIT)
396                         return SR_OK;
397                 g_usleep(10 * 1000);
398         }
399
400         return SR_ERR_TIMEOUT;
401 }
402
403 /*
404  * This is belt and braces. Re-run the bitbang initiation sequence a few
405  * times should first attempts fail. Failure is rare but can happen (was
406  * observed during driver development).
407  */
408 static int sigma_fpga_init_bitbang(struct dev_context *devc)
409 {
410         size_t retries;
411         int ret;
412
413         retries = 10;
414         while (retries--) {
415                 ret = sigma_fpga_init_bitbang_once(devc);
416                 if (ret == SR_OK)
417                         return ret;
418                 if (ret != SR_ERR_TIMEOUT)
419                         return ret;
420         }
421         return ret;
422 }
423
424 /*
425  * Configure the FPGA for logic-analyzer mode.
426  */
427 static int sigma_fpga_init_la(struct dev_context *devc)
428 {
429         uint8_t buf[16], *wrptr;
430         uint8_t data_55, data_aa, mode;
431         uint8_t result[3];
432         const uint8_t *rdptr;
433         int ret;
434
435         wrptr = buf;
436
437         /* Read ID register. */
438         write_u8_inc(&wrptr, REG_ADDR_LOW | (READ_ID & 0xf));
439         write_u8_inc(&wrptr, REG_ADDR_HIGH | (READ_ID >> 4));
440         write_u8_inc(&wrptr, REG_READ_ADDR);
441
442         /* Write 0x55 to scratch register, read back. */
443         data_55 = 0x55;
444         write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
445         write_u8_inc(&wrptr, REG_DATA_LOW | (data_55 & 0xf));
446         write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_55 >> 4));
447         write_u8_inc(&wrptr, REG_READ_ADDR);
448
449         /* Write 0xaa to scratch register, read back. */
450         data_aa = 0xaa;
451         write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
452         write_u8_inc(&wrptr, REG_DATA_LOW | (data_aa & 0xf));
453         write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_aa >> 4));
454         write_u8_inc(&wrptr, REG_READ_ADDR);
455
456         /* Initiate SDRAM initialization in mode register. */
457         mode = WMR_SDRAMINIT;
458         write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_MODE & 0xf));
459         write_u8_inc(&wrptr, REG_DATA_LOW | (mode & 0xf));
460         write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (mode >> 4));
461
462         /*
463          * Send the command sequence which contains 3 READ requests.
464          * Expect to see the corresponding 3 response bytes.
465          */
466         sigma_write(devc, buf, wrptr - buf);
467         ret = sigma_read(devc, result, ARRAY_SIZE(result));
468         if (ret != ARRAY_SIZE(result)) {
469                 sr_err("Insufficient start response length.");
470                 return SR_ERR_IO;
471         }
472         rdptr = result;
473         if (read_u8_inc(&rdptr) != 0xa6) {
474                 sr_err("Unexpected ID response.");
475                 return SR_ERR_DATA;
476         }
477         if (read_u8_inc(&rdptr) != data_55) {
478                 sr_err("Unexpected scratch read-back (55).");
479                 return SR_ERR_DATA;
480         }
481         if (read_u8_inc(&rdptr) != data_aa) {
482                 sr_err("Unexpected scratch read-back (aa).");
483                 return SR_ERR_DATA;
484         }
485
486         return SR_OK;
487 }
488
489 /*
490  * Read the firmware from a file and transform it into a series of bitbang
491  * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
492  * by the caller of this function.
493  */
494 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
495         uint8_t **bb_cmd, gsize *bb_cmd_size)
496 {
497         uint8_t *firmware;
498         size_t file_size;
499         uint8_t *p;
500         size_t l;
501         uint32_t imm;
502         size_t bb_size;
503         uint8_t *bb_stream, *bbs, byte, mask, v;
504
505         /* Retrieve the on-disk firmware file content. */
506         firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
507                 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
508         if (!firmware)
509                 return SR_ERR_IO;
510
511         /* Unscramble the file content (XOR with "random" sequence). */
512         p = firmware;
513         l = file_size;
514         imm = 0x3f6df2ab;
515         while (l--) {
516                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
517                 *p++ ^= imm & 0xff;
518         }
519
520         /*
521          * Generate a sequence of bitbang samples. With two samples per
522          * FPGA configuration bit, providing the level for the DIN signal
523          * as well as two edges for CCLK. See Xilinx UG332 for details
524          * ("slave serial" mode).
525          *
526          * Note that CCLK is inverted in hardware. That's why the
527          * respective bit is first set and then cleared in the bitbang
528          * sample sets. So that the DIN level will be stable when the
529          * data gets sampled at the rising CCLK edge, and the signals'
530          * setup time constraint will be met.
531          *
532          * The caller will put the FPGA into download mode, will send
533          * the bitbang samples, and release the allocated memory.
534          */
535         bb_size = file_size * 8 * 2;
536         bb_stream = g_try_malloc(bb_size);
537         if (!bb_stream) {
538                 sr_err("%s: Failed to allocate bitbang stream", __func__);
539                 g_free(firmware);
540                 return SR_ERR_MALLOC;
541         }
542         bbs = bb_stream;
543         p = firmware;
544         l = file_size;
545         while (l--) {
546                 byte = *p++;
547                 mask = 0x80;
548                 while (mask) {
549                         v = (byte & mask) ? BB_PIN_DIN : 0;
550                         mask >>= 1;
551                         *bbs++ = v | BB_PIN_CCLK;
552                         *bbs++ = v;
553                 }
554         }
555         g_free(firmware);
556
557         /* The transformation completed successfully, return the result. */
558         *bb_cmd = bb_stream;
559         *bb_cmd_size = bb_size;
560
561         return SR_OK;
562 }
563
564 static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
565         enum sigma_firmware_idx firmware_idx)
566 {
567         int ret;
568         uint8_t *buf;
569         uint8_t pins;
570         size_t buf_size;
571         const char *firmware;
572
573         /* Check for valid firmware file selection. */
574         if (firmware_idx >= ARRAY_SIZE(firmware_files))
575                 return SR_ERR_ARG;
576         firmware = firmware_files[firmware_idx];
577         if (!firmware || !*firmware)
578                 return SR_ERR_ARG;
579
580         /* Avoid downloading the same firmware multiple times. */
581         if (devc->firmware_idx == firmware_idx) {
582                 sr_info("Not uploading firmware file '%s' again.", firmware);
583                 return SR_OK;
584         }
585
586         devc->state.state = SIGMA_CONFIG;
587
588         /* Set the cable to bitbang mode. */
589         ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
590         if (ret < 0) {
591                 sr_err("ftdi_set_bitmode failed: %s",
592                         ftdi_get_error_string(&devc->ftdic));
593                 return SR_ERR;
594         }
595         ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
596         if (ret < 0) {
597                 sr_err("ftdi_set_baudrate failed: %s",
598                         ftdi_get_error_string(&devc->ftdic));
599                 return SR_ERR;
600         }
601
602         /* Initiate FPGA configuration mode. */
603         ret = sigma_fpga_init_bitbang(devc);
604         if (ret)
605                 return ret;
606
607         /* Prepare wire format of the firmware image. */
608         ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
609         if (ret != SR_OK) {
610                 sr_err("Could not prepare file %s for download.", firmware);
611                 return ret;
612         }
613
614         /* Write the FPGA netlist to the cable. */
615         sr_info("Uploading firmware file '%s'.", firmware);
616         sigma_write(devc, buf, buf_size);
617
618         g_free(buf);
619
620         /* Leave bitbang mode and discard pending input data. */
621         ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
622         if (ret < 0) {
623                 sr_err("ftdi_set_bitmode failed: %s",
624                         ftdi_get_error_string(&devc->ftdic));
625                 return SR_ERR;
626         }
627         ftdi_usb_purge_buffers(&devc->ftdic);
628         while (sigma_read(devc, &pins, sizeof(pins)) > 0)
629                 ;
630
631         /* Initialize the FPGA for logic-analyzer mode. */
632         ret = sigma_fpga_init_la(devc);
633         if (ret != SR_OK)
634                 return ret;
635
636         /* Keep track of successful firmware download completion. */
637         devc->state.state = SIGMA_IDLE;
638         devc->firmware_idx = firmware_idx;
639         sr_info("Firmware uploaded.");
640
641         return SR_OK;
642 }
643
644 /*
645  * The driver supports user specified time or sample count limits. The
646  * device's hardware supports neither, and hardware compression prevents
647  * reliable detection of "fill levels" (currently reached sample counts)
648  * from register values during acquisition. That's why the driver needs
649  * to apply some heuristics:
650  *
651  * - The (optional) sample count limit and the (normalized) samplerate
652  *   get mapped to an estimated duration for these samples' acquisition.
653  * - The (optional) time limit gets checked as well. The lesser of the
654  *   two limits will terminate the data acquisition phase. The exact
655  *   sample count limit gets enforced in session feed submission paths.
656  * - Some slack needs to be given to account for hardware pipelines as
657  *   well as late storage of last chunks after compression thresholds
658  *   are tripped. The resulting data set will span at least the caller
659  *   specified period of time, which shall be perfectly acceptable.
660  *
661  * With RLE compression active, up to 64K sample periods can pass before
662  * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
663  * times that period for good measure, one is not enough to flush the
664  * hardware pipeline (observation from an earlier experiment).
665  */
666 SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
667 {
668         int ret;
669         GVariant *data;
670         uint64_t user_count, user_msecs;
671         uint64_t worst_cluster_time_ms;
672         uint64_t count_msecs, acquire_msecs;
673
674         sr_sw_limits_init(&devc->acq_limits);
675
676         /* Get sample count limit, convert to msecs. */
677         ret = sr_sw_limits_config_get(&devc->cfg_limits,
678                 SR_CONF_LIMIT_SAMPLES, &data);
679         if (ret != SR_OK)
680                 return ret;
681         user_count = g_variant_get_uint64(data);
682         g_variant_unref(data);
683         count_msecs = 0;
684         if (user_count)
685                 count_msecs = 1000 * user_count / devc->samplerate + 1;
686
687         /* Get time limit, which is in msecs. */
688         ret = sr_sw_limits_config_get(&devc->cfg_limits,
689                 SR_CONF_LIMIT_MSEC, &data);
690         if (ret != SR_OK)
691                 return ret;
692         user_msecs = g_variant_get_uint64(data);
693         g_variant_unref(data);
694
695         /* Get the lesser of them, with both being optional. */
696         acquire_msecs = ~0ull;
697         if (user_count && count_msecs < acquire_msecs)
698                 acquire_msecs = count_msecs;
699         if (user_msecs && user_msecs < acquire_msecs)
700                 acquire_msecs = user_msecs;
701         if (acquire_msecs == ~0ull)
702                 return SR_OK;
703
704         /* Add some slack, and use that timeout for acquisition. */
705         worst_cluster_time_ms = 1000 * 65536 / devc->samplerate;
706         acquire_msecs += 2 * worst_cluster_time_ms;
707         data = g_variant_new_uint64(acquire_msecs);
708         ret = sr_sw_limits_config_set(&devc->acq_limits,
709                 SR_CONF_LIMIT_MSEC, data);
710         g_variant_unref(data);
711         if (ret != SR_OK)
712                 return ret;
713
714         sr_sw_limits_acquisition_start(&devc->acq_limits);
715         return SR_OK;
716 }
717
718 /*
719  * Check whether a caller specified samplerate matches the device's
720  * hardware constraints (can be used for acquisition). Optionally yield
721  * a value that approximates the original spec.
722  *
723  * This routine assumes that input specs are in the 200kHz to 200MHz
724  * range of supported rates, and callers typically want to normalize a
725  * given value to the hardware capabilities. Values in the 50MHz range
726  * get rounded up by default, to avoid a more expensive check for the
727  * closest match, while higher sampling rate is always desirable during
728  * measurement. Input specs which exactly match hardware capabilities
729  * remain unaffected. Because 100/200MHz rates also limit the number of
730  * available channels, they are not suggested by this routine, instead
731  * callers need to pick them consciously.
732  */
733 SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
734 {
735         uint64_t div, rate;
736
737         /* Accept exact matches for 100/200MHz. */
738         if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
739                 if (have_rate)
740                         *have_rate = want_rate;
741                 return SR_OK;
742         }
743
744         /* Accept 200kHz to 50MHz range, and map to near value. */
745         if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
746                 div = SR_MHZ(50) / want_rate;
747                 rate = SR_MHZ(50) / div;
748                 if (have_rate)
749                         *have_rate = rate;
750                 return SR_OK;
751         }
752
753         return SR_ERR_ARG;
754 }
755
756 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
757 {
758         struct dev_context *devc;
759         struct drv_context *drvc;
760         uint64_t samplerate;
761         int ret;
762         int num_channels;
763
764         devc = sdi->priv;
765         drvc = sdi->driver->context;
766
767         /* Accept any caller specified rate which the hardware supports. */
768         ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
769         if (ret != SR_OK)
770                 return ret;
771
772         /*
773          * Depending on the samplerates of 200/100/50- MHz, specific
774          * firmware is required and higher rates might limit the set
775          * of available channels.
776          */
777         num_channels = devc->num_channels;
778         if (samplerate <= SR_MHZ(50)) {
779                 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
780                 num_channels = 16;
781         } else if (samplerate == SR_MHZ(100)) {
782                 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
783                 num_channels = 8;
784         } else if (samplerate == SR_MHZ(200)) {
785                 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
786                 num_channels = 4;
787         }
788
789         /*
790          * The samplerate affects the number of available logic channels
791          * as well as a sample memory layout detail (the number of samples
792          * which the device will communicate within an "event").
793          */
794         if (ret == SR_OK) {
795                 devc->num_channels = num_channels;
796                 devc->samples_per_event = 16 / devc->num_channels;
797         }
798
799         return ret;
800 }
801
802 /*
803  * Arrange for a session feed submit buffer. A queue where a number of
804  * samples gets accumulated to reduce the number of send calls. Which
805  * also enforces an optional sample count limit for data acquisition.
806  *
807  * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
808  * driver provides a fixed channel layout regardless of samplerate).
809  */
810
811 #define CHUNK_SIZE      (4 * 1024 * 1024)
812
813 struct submit_buffer {
814         size_t unit_size;
815         size_t max_samples, curr_samples;
816         uint8_t *sample_data;
817         uint8_t *write_pointer;
818         struct sr_dev_inst *sdi;
819         struct sr_datafeed_packet packet;
820         struct sr_datafeed_logic logic;
821 };
822
823 static int alloc_submit_buffer(struct sr_dev_inst *sdi)
824 {
825         struct dev_context *devc;
826         struct submit_buffer *buffer;
827         size_t size;
828
829         devc = sdi->priv;
830
831         buffer = g_malloc0(sizeof(*buffer));
832         devc->buffer = buffer;
833
834         buffer->unit_size = sizeof(uint16_t);
835         size = CHUNK_SIZE;
836         size /= buffer->unit_size;
837         buffer->max_samples = size;
838         size *= buffer->unit_size;
839         buffer->sample_data = g_try_malloc0(size);
840         if (!buffer->sample_data)
841                 return SR_ERR_MALLOC;
842         buffer->write_pointer = buffer->sample_data;
843         sr_sw_limits_init(&devc->feed_limits);
844
845         buffer->sdi = sdi;
846         memset(&buffer->logic, 0, sizeof(buffer->logic));
847         buffer->logic.unitsize = buffer->unit_size;
848         buffer->logic.data = buffer->sample_data;
849         memset(&buffer->packet, 0, sizeof(buffer->packet));
850         buffer->packet.type = SR_DF_LOGIC;
851         buffer->packet.payload = &buffer->logic;
852
853         return SR_OK;
854 }
855
856 static int setup_submit_limit(struct dev_context *devc)
857 {
858         struct sr_sw_limits *limits;
859         int ret;
860         GVariant *data;
861         uint64_t total;
862
863         limits = &devc->feed_limits;
864
865         ret = sr_sw_limits_config_get(&devc->cfg_limits,
866                 SR_CONF_LIMIT_SAMPLES, &data);
867         if (ret != SR_OK)
868                 return ret;
869         total = g_variant_get_uint64(data);
870         g_variant_unref(data);
871
872         sr_sw_limits_init(limits);
873         if (total) {
874                 data = g_variant_new_uint64(total);
875                 ret = sr_sw_limits_config_set(limits,
876                         SR_CONF_LIMIT_SAMPLES, data);
877                 g_variant_unref(data);
878                 if (ret != SR_OK)
879                         return ret;
880         }
881
882         sr_sw_limits_acquisition_start(limits);
883
884         return SR_OK;
885 }
886
887 static void free_submit_buffer(struct dev_context *devc)
888 {
889         struct submit_buffer *buffer;
890
891         if (!devc)
892                 return;
893
894         buffer = devc->buffer;
895         if (!buffer)
896                 return;
897         devc->buffer = NULL;
898
899         g_free(buffer->sample_data);
900         g_free(buffer);
901 }
902
903 static int flush_submit_buffer(struct dev_context *devc)
904 {
905         struct submit_buffer *buffer;
906         int ret;
907
908         buffer = devc->buffer;
909
910         /* Is queued sample data available? */
911         if (!buffer->curr_samples)
912                 return SR_OK;
913
914         /* Submit to the session feed. */
915         buffer->logic.length = buffer->curr_samples * buffer->unit_size;
916         ret = sr_session_send(buffer->sdi, &buffer->packet);
917         if (ret != SR_OK)
918                 return ret;
919
920         /* Rewind queue position. */
921         buffer->curr_samples = 0;
922         buffer->write_pointer = buffer->sample_data;
923
924         return SR_OK;
925 }
926
927 static int addto_submit_buffer(struct dev_context *devc,
928         uint16_t sample, size_t count)
929 {
930         struct submit_buffer *buffer;
931         struct sr_sw_limits *limits;
932         int ret;
933
934         buffer = devc->buffer;
935         limits = &devc->feed_limits;
936         if (sr_sw_limits_check(limits))
937                 count = 0;
938
939         /*
940          * Individually accumulate and check each sample, such that
941          * accumulation between flushes won't exceed local storage, and
942          * enforcement of user specified limits is exact.
943          */
944         while (count--) {
945                 write_u16le_inc(&buffer->write_pointer, sample);
946                 buffer->curr_samples++;
947                 if (buffer->curr_samples == buffer->max_samples) {
948                         ret = flush_submit_buffer(devc);
949                         if (ret != SR_OK)
950                                 return ret;
951                 }
952                 sr_sw_limits_update_samples_read(limits, 1);
953                 if (sr_sw_limits_check(limits))
954                         break;
955         }
956
957         return SR_OK;
958 }
959
960 /*
961  * In 100 and 200 MHz mode, only a single pin rising/falling can be
962  * set as trigger. In other modes, two rising/falling triggers can be set,
963  * in addition to value/mask trigger for any number of channels.
964  *
965  * The Sigma supports complex triggers using boolean expressions, but this
966  * has not been implemented yet.
967  */
968 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
969 {
970         struct dev_context *devc;
971         struct sr_trigger *trigger;
972         struct sr_trigger_stage *stage;
973         struct sr_trigger_match *match;
974         const GSList *l, *m;
975         int channelbit, trigger_set;
976
977         devc = sdi->priv;
978         memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
979         if (!(trigger = sr_session_trigger_get(sdi->session)))
980                 return SR_OK;
981
982         trigger_set = 0;
983         for (l = trigger->stages; l; l = l->next) {
984                 stage = l->data;
985                 for (m = stage->matches; m; m = m->next) {
986                         match = m->data;
987                         /* Ignore disabled channels with a trigger. */
988                         if (!match->channel->enabled)
989                                 continue;
990                         channelbit = 1 << match->channel->index;
991                         if (devc->samplerate >= SR_MHZ(100)) {
992                                 /* Fast trigger support. */
993                                 if (trigger_set) {
994                                         sr_err("Only a single pin trigger is "
995                                                 "supported in 100 and 200MHz mode.");
996                                         return SR_ERR;
997                                 }
998                                 if (match->match == SR_TRIGGER_FALLING) {
999                                         devc->trigger.fallingmask |= channelbit;
1000                                 } else if (match->match == SR_TRIGGER_RISING) {
1001                                         devc->trigger.risingmask |= channelbit;
1002                                 } else {
1003                                         sr_err("Only rising/falling trigger is "
1004                                                 "supported in 100 and 200MHz mode.");
1005                                         return SR_ERR;
1006                                 }
1007
1008                                 trigger_set++;
1009                         } else {
1010                                 /* Simple trigger support (event). */
1011                                 if (match->match == SR_TRIGGER_ONE) {
1012                                         devc->trigger.simplevalue |= channelbit;
1013                                         devc->trigger.simplemask |= channelbit;
1014                                 } else if (match->match == SR_TRIGGER_ZERO) {
1015                                         devc->trigger.simplevalue &= ~channelbit;
1016                                         devc->trigger.simplemask |= channelbit;
1017                                 } else if (match->match == SR_TRIGGER_FALLING) {
1018                                         devc->trigger.fallingmask |= channelbit;
1019                                         trigger_set++;
1020                                 } else if (match->match == SR_TRIGGER_RISING) {
1021                                         devc->trigger.risingmask |= channelbit;
1022                                         trigger_set++;
1023                                 }
1024
1025                                 /*
1026                                  * Actually, Sigma supports 2 rising/falling triggers,
1027                                  * but they are ORed and the current trigger syntax
1028                                  * does not permit ORed triggers.
1029                                  */
1030                                 if (trigger_set > 1) {
1031                                         sr_err("Only 1 rising/falling trigger is supported.");
1032                                         return SR_ERR;
1033                                 }
1034                         }
1035                 }
1036         }
1037
1038         return SR_OK;
1039 }
1040
1041 /* Software trigger to determine exact trigger position. */
1042 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1043         struct sigma_trigger *t)
1044 {
1045         const uint8_t *rdptr;
1046         int i;
1047         uint16_t sample;
1048
1049         rdptr = samples;
1050         sample = 0;
1051         for (i = 0; i < 8; i++) {
1052                 if (i > 0)
1053                         last_sample = sample;
1054                 sample = read_u16le_inc(&rdptr);
1055
1056                 /* Simple triggers. */
1057                 if ((sample & t->simplemask) != t->simplevalue)
1058                         continue;
1059
1060                 /* Rising edge. */
1061                 if (((last_sample & t->risingmask) != 0) ||
1062                     ((sample & t->risingmask) != t->risingmask))
1063                         continue;
1064
1065                 /* Falling edge. */
1066                 if ((last_sample & t->fallingmask) != t->fallingmask ||
1067                     (sample & t->fallingmask) != 0)
1068                         continue;
1069
1070                 break;
1071         }
1072
1073         /* If we did not match, return original trigger pos. */
1074         return i & 0x7;
1075 }
1076
1077 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1078 {
1079         /* TODO
1080          * Check whether the combination of this very sample and the
1081          * previous state match the configured trigger condition. This
1082          * improves the resolution of the trigger marker's position.
1083          * The hardware provided position is coarse, and may point to
1084          * a position before the actual match.
1085          *
1086          * See the previous get_trigger_offset() implementation. This
1087          * code needs to get re-used here.
1088          */
1089         (void)devc;
1090         (void)sample;
1091         (void)get_trigger_offset;
1092
1093         return FALSE;
1094 }
1095
1096 static int check_and_submit_sample(struct dev_context *devc,
1097         uint16_t sample, size_t count, gboolean check_trigger)
1098 {
1099         gboolean triggered;
1100         int ret;
1101
1102         triggered = check_trigger && sample_matches_trigger(devc, sample);
1103         if (triggered) {
1104                 ret = flush_submit_buffer(devc);
1105                 if (ret != SR_OK)
1106                         return ret;
1107                 ret = std_session_send_df_trigger(devc->buffer->sdi);
1108                 if (ret != SR_OK)
1109                         return ret;
1110         }
1111
1112         ret = addto_submit_buffer(devc, sample, count);
1113         if (ret != SR_OK)
1114                 return ret;
1115
1116         return SR_OK;
1117 }
1118
1119 /*
1120  * Return the timestamp of "DRAM cluster".
1121  */
1122 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1123 {
1124         return read_u16le((const uint8_t *)&cluster->timestamp);
1125 }
1126
1127 /*
1128  * Return one 16bit data entity of a DRAM cluster at the specified index.
1129  */
1130 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1131 {
1132         return read_u16le((const uint8_t *)&cl->samples[idx]);
1133 }
1134
1135 /*
1136  * Deinterlace sample data that was retrieved at 100MHz samplerate.
1137  * One 16bit item contains two samples of 8bits each. The bits of
1138  * multiple samples are interleaved.
1139  */
1140 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1141 {
1142         uint16_t outdata;
1143
1144         indata >>= idx;
1145         outdata = 0;
1146         outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1147         outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1148         outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1149         outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1150         outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1151         outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1152         outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1153         outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1154         return outdata;
1155 }
1156
1157 /*
1158  * Deinterlace sample data that was retrieved at 200MHz samplerate.
1159  * One 16bit item contains four samples of 4bits each. The bits of
1160  * multiple samples are interleaved.
1161  */
1162 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1163 {
1164         uint16_t outdata;
1165
1166         indata >>= idx;
1167         outdata = 0;
1168         outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1169         outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1170         outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1171         outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1172         return outdata;
1173 }
1174
1175 static void sigma_decode_dram_cluster(struct dev_context *devc,
1176         struct sigma_dram_cluster *dram_cluster,
1177         size_t events_in_cluster, gboolean triggered)
1178 {
1179         struct sigma_state *ss;
1180         uint16_t tsdiff, ts, sample, item16;
1181         unsigned int i;
1182
1183         if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1184                 triggered = FALSE;
1185
1186         /*
1187          * If this cluster is not adjacent to the previously received
1188          * cluster, then send the appropriate number of samples with the
1189          * previous values to the sigrok session. This "decodes RLE".
1190          *
1191          * These samples cannot match the trigger since they just repeat
1192          * the previously submitted data pattern. (This assumption holds
1193          * for simple level and edge triggers. It would not for timed or
1194          * counted conditions, which currently are not supported.)
1195          */
1196         ss = &devc->state;
1197         ts = sigma_dram_cluster_ts(dram_cluster);
1198         tsdiff = ts - ss->lastts;
1199         if (tsdiff > 0) {
1200                 size_t count;
1201                 sample = ss->lastsample;
1202                 count = tsdiff * devc->samples_per_event;
1203                 (void)check_and_submit_sample(devc, sample, count, FALSE);
1204         }
1205         ss->lastts = ts + EVENTS_PER_CLUSTER;
1206
1207         /*
1208          * Grab sample data from the current cluster and prepare their
1209          * submission to the session feed. Handle samplerate dependent
1210          * memory layout of sample data. Accumulation of data chunks
1211          * before submission is transparent to this code path, specific
1212          * buffer depth is neither assumed nor required here.
1213          */
1214         sample = 0;
1215         for (i = 0; i < events_in_cluster; i++) {
1216                 item16 = sigma_dram_cluster_data(dram_cluster, i);
1217                 if (devc->samplerate == SR_MHZ(200)) {
1218                         sample = sigma_deinterlace_200mhz_data(item16, 0);
1219                         check_and_submit_sample(devc, sample, 1, triggered);
1220                         sample = sigma_deinterlace_200mhz_data(item16, 1);
1221                         check_and_submit_sample(devc, sample, 1, triggered);
1222                         sample = sigma_deinterlace_200mhz_data(item16, 2);
1223                         check_and_submit_sample(devc, sample, 1, triggered);
1224                         sample = sigma_deinterlace_200mhz_data(item16, 3);
1225                         check_and_submit_sample(devc, sample, 1, triggered);
1226                 } else if (devc->samplerate == SR_MHZ(100)) {
1227                         sample = sigma_deinterlace_100mhz_data(item16, 0);
1228                         check_and_submit_sample(devc, sample, 1, triggered);
1229                         sample = sigma_deinterlace_100mhz_data(item16, 1);
1230                         check_and_submit_sample(devc, sample, 1, triggered);
1231                 } else {
1232                         sample = item16;
1233                         check_and_submit_sample(devc, sample, 1, triggered);
1234                 }
1235         }
1236         ss->lastsample = sample;
1237 }
1238
1239 /*
1240  * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1241  * Each event is 20ns apart, and can contain multiple samples.
1242  *
1243  * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1244  * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1245  * For 50 MHz and below, events contain one sample for each channel,
1246  * spread 20 ns apart.
1247  */
1248 static int decode_chunk_ts(struct dev_context *devc,
1249         struct sigma_dram_line *dram_line,
1250         size_t events_in_line, size_t trigger_event)
1251 {
1252         struct sigma_dram_cluster *dram_cluster;
1253         unsigned int clusters_in_line;
1254         unsigned int events_in_cluster;
1255         unsigned int i;
1256         uint32_t trigger_cluster;
1257
1258         clusters_in_line = events_in_line;
1259         clusters_in_line += EVENTS_PER_CLUSTER - 1;
1260         clusters_in_line /= EVENTS_PER_CLUSTER;
1261         trigger_cluster = ~0;
1262
1263         /* Check if trigger is in this chunk. */
1264         if (trigger_event < EVENTS_PER_ROW) {
1265                 if (devc->samplerate <= SR_MHZ(50)) {
1266                         trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1267                                              trigger_event);
1268                 }
1269
1270                 /* Find in which cluster the trigger occurred. */
1271                 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1272         }
1273
1274         /* For each full DRAM cluster. */
1275         for (i = 0; i < clusters_in_line; i++) {
1276                 dram_cluster = &dram_line->cluster[i];
1277
1278                 /* The last cluster might not be full. */
1279                 if ((i == clusters_in_line - 1) &&
1280                     (events_in_line % EVENTS_PER_CLUSTER)) {
1281                         events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1282                 } else {
1283                         events_in_cluster = EVENTS_PER_CLUSTER;
1284                 }
1285
1286                 sigma_decode_dram_cluster(devc, dram_cluster,
1287                         events_in_cluster, i == trigger_cluster);
1288         }
1289
1290         return SR_OK;
1291 }
1292
1293 static int download_capture(struct sr_dev_inst *sdi)
1294 {
1295         const uint32_t chunks_per_read = 32;
1296
1297         struct dev_context *devc;
1298         struct sigma_dram_line *dram_line;
1299         int bufsz;
1300         uint32_t stoppos, triggerpos;
1301         uint8_t modestatus;
1302         uint32_t i;
1303         uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1304         uint32_t dl_first_line, dl_line;
1305         uint32_t dl_events_in_line;
1306         uint32_t trg_line, trg_event;
1307         int ret;
1308
1309         devc = sdi->priv;
1310         dl_events_in_line = EVENTS_PER_ROW;
1311
1312         sr_info("Downloading sample data.");
1313         devc->state.state = SIGMA_DOWNLOAD;
1314
1315         /*
1316          * Ask the hardware to stop data acquisition. Reception of the
1317          * FORCESTOP request makes the hardware "disable RLE" (store
1318          * clusters to DRAM regardless of whether pin state changes) and
1319          * raise the POSTTRIGGERED flag.
1320          */
1321         sigma_set_register(devc, WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN);
1322         do {
1323                 ret = sigma_read_register(devc, READ_MODE,
1324                         &modestatus, sizeof(modestatus));
1325                 if (ret != sizeof(modestatus)) {
1326                         sr_err("Could not poll for post-trigger condition.");
1327                         return FALSE;
1328                 }
1329         } while (!(modestatus & RMR_POSTTRIGGERED));
1330
1331         /* Set SDRAM Read Enable. */
1332         sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
1333
1334         /* Get the current position. */
1335         sigma_read_pos(devc, &stoppos, &triggerpos);
1336
1337         /* Check if trigger has fired. */
1338         ret = sigma_read_register(devc, READ_MODE,
1339                 &modestatus, sizeof(modestatus));
1340         if (ret != sizeof(modestatus)) {
1341                 sr_err("Could not query trigger hit.");
1342                 return FALSE;
1343         }
1344         trg_line = ~0;
1345         trg_event = ~0;
1346         if (modestatus & RMR_TRIGGERED) {
1347                 trg_line = triggerpos >> ROW_SHIFT;
1348                 trg_event = triggerpos & ROW_MASK;
1349         }
1350
1351         /*
1352          * Determine how many "DRAM lines" of 1024 bytes each we need to
1353          * retrieve from the Sigma hardware, so that we have a complete
1354          * set of samples. Note that the last line need not contain 64
1355          * clusters, it might be partially filled only.
1356          *
1357          * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1358          * around. Since the status of the very next line is uncertain in
1359          * that case, we skip it and start reading from the next line.
1360          */
1361         dl_first_line = 0;
1362         dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1363         if (modestatus & RMR_ROUND) {
1364                 dl_first_line = dl_lines_total + 1;
1365                 dl_lines_total = ROW_COUNT - 2;
1366         }
1367         dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1368         if (!dram_line)
1369                 return FALSE;
1370         ret = alloc_submit_buffer(sdi);
1371         if (ret != SR_OK)
1372                 return FALSE;
1373         ret = setup_submit_limit(devc);
1374         if (ret != SR_OK)
1375                 return FALSE;
1376         dl_lines_done = 0;
1377         while (dl_lines_total > dl_lines_done) {
1378                 /* We can download only up-to 32 DRAM lines in one go! */
1379                 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1380
1381                 dl_line = dl_first_line + dl_lines_done;
1382                 dl_line %= ROW_COUNT;
1383                 bufsz = sigma_read_dram(devc, dl_line, dl_lines_curr,
1384                                         (uint8_t *)dram_line);
1385                 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1386                 (void)bufsz;
1387
1388                 /* This is the first DRAM line, so find the initial timestamp. */
1389                 if (dl_lines_done == 0) {
1390                         devc->state.lastts =
1391                                 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1392                         devc->state.lastsample = 0;
1393                 }
1394
1395                 for (i = 0; i < dl_lines_curr; i++) {
1396                         uint32_t trigger_event = ~0;
1397                         /* The last "DRAM line" need not span its full length. */
1398                         if (dl_lines_done + i == dl_lines_total - 1)
1399                                 dl_events_in_line = stoppos & ROW_MASK;
1400
1401                         /* Test if the trigger happened on this line. */
1402                         if (dl_lines_done + i == trg_line)
1403                                 trigger_event = trg_event;
1404
1405                         decode_chunk_ts(devc, dram_line + i,
1406                                 dl_events_in_line, trigger_event);
1407                 }
1408
1409                 dl_lines_done += dl_lines_curr;
1410         }
1411         flush_submit_buffer(devc);
1412         free_submit_buffer(devc);
1413         g_free(dram_line);
1414
1415         std_session_send_df_end(sdi);
1416
1417         devc->state.state = SIGMA_IDLE;
1418         sr_dev_acquisition_stop(sdi);
1419
1420         return TRUE;
1421 }
1422
1423 /*
1424  * Periodically check the Sigma status when in CAPTURE mode. This routine
1425  * checks whether the configured sample count or sample time have passed,
1426  * and will stop acquisition and download the acquired samples.
1427  */
1428 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1429 {
1430         struct dev_context *devc;
1431
1432         devc = sdi->priv;
1433         if (sr_sw_limits_check(&devc->acq_limits))
1434                 return download_capture(sdi);
1435
1436         return TRUE;
1437 }
1438
1439 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1440 {
1441         struct sr_dev_inst *sdi;
1442         struct dev_context *devc;
1443
1444         (void)fd;
1445         (void)revents;
1446
1447         sdi = cb_data;
1448         devc = sdi->priv;
1449
1450         if (devc->state.state == SIGMA_IDLE)
1451                 return TRUE;
1452
1453         /*
1454          * When the application has requested to stop the acquisition,
1455          * then immediately start downloading sample data. Otherwise
1456          * keep checking configured limits which will terminate the
1457          * acquisition and initiate download.
1458          */
1459         if (devc->state.state == SIGMA_STOPPING)
1460                 return download_capture(sdi);
1461         if (devc->state.state == SIGMA_CAPTURE)
1462                 return sigma_capture_mode(sdi);
1463
1464         return TRUE;
1465 }
1466
1467 /* Build a LUT entry used by the trigger functions. */
1468 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1469 {
1470         int i, j, k, bit;
1471
1472         /* For each quad channel. */
1473         for (i = 0; i < 4; i++) {
1474                 entry[i] = 0xffff;
1475
1476                 /* For each bit in LUT. */
1477                 for (j = 0; j < 16; j++) {
1478
1479                         /* For each channel in quad. */
1480                         for (k = 0; k < 4; k++) {
1481                                 bit = 1 << (i * 4 + k);
1482
1483                                 /* Set bit in entry */
1484                                 if ((mask & bit) && ((!(value & bit)) !=
1485                                                         (!(j & (1 << k)))))
1486                                         entry[i] &= ~(1 << j);
1487                         }
1488                 }
1489         }
1490 }
1491
1492 /* Add a logical function to LUT mask. */
1493 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1494         int index, int neg, uint16_t *mask)
1495 {
1496         int i, j;
1497         int x[2][2], tmp, a, b, aset, bset, rset;
1498
1499         memset(x, 0, 4 * sizeof(int));
1500
1501         /* Trigger detect condition. */
1502         switch (oper) {
1503         case OP_LEVEL:
1504                 x[0][1] = 1;
1505                 x[1][1] = 1;
1506                 break;
1507         case OP_NOT:
1508                 x[0][0] = 1;
1509                 x[1][0] = 1;
1510                 break;
1511         case OP_RISE:
1512                 x[0][1] = 1;
1513                 break;
1514         case OP_FALL:
1515                 x[1][0] = 1;
1516                 break;
1517         case OP_RISEFALL:
1518                 x[0][1] = 1;
1519                 x[1][0] = 1;
1520                 break;
1521         case OP_NOTRISE:
1522                 x[1][1] = 1;
1523                 x[0][0] = 1;
1524                 x[1][0] = 1;
1525                 break;
1526         case OP_NOTFALL:
1527                 x[1][1] = 1;
1528                 x[0][0] = 1;
1529                 x[0][1] = 1;
1530                 break;
1531         case OP_NOTRISEFALL:
1532                 x[1][1] = 1;
1533                 x[0][0] = 1;
1534                 break;
1535         }
1536
1537         /* Transpose if neg is set. */
1538         if (neg) {
1539                 for (i = 0; i < 2; i++) {
1540                         for (j = 0; j < 2; j++) {
1541                                 tmp = x[i][j];
1542                                 x[i][j] = x[1 - i][1 - j];
1543                                 x[1 - i][1 - j] = tmp;
1544                         }
1545                 }
1546         }
1547
1548         /* Update mask with function. */
1549         for (i = 0; i < 16; i++) {
1550                 a = (i >> (2 * index + 0)) & 1;
1551                 b = (i >> (2 * index + 1)) & 1;
1552
1553                 aset = (*mask >> i) & 1;
1554                 bset = x[b][a];
1555
1556                 rset = 0;
1557                 if (func == FUNC_AND || func == FUNC_NAND)
1558                         rset = aset & bset;
1559                 else if (func == FUNC_OR || func == FUNC_NOR)
1560                         rset = aset | bset;
1561                 else if (func == FUNC_XOR || func == FUNC_NXOR)
1562                         rset = aset ^ bset;
1563
1564                 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1565                         rset = !rset;
1566
1567                 *mask &= ~(1 << i);
1568
1569                 if (rset)
1570                         *mask |= 1 << i;
1571         }
1572 }
1573
1574 /*
1575  * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1576  * simple pin change and state triggers. Only two transitions (rise/fall) can be
1577  * set at any time, but a full mask and value can be set (0/1).
1578  */
1579 SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
1580         struct triggerlut *lut)
1581 {
1582         int i,j;
1583         uint16_t masks[2] = { 0, 0 };
1584
1585         memset(lut, 0, sizeof(struct triggerlut));
1586
1587         /* Constant for simple triggers. */
1588         lut->m4 = 0xa000;
1589
1590         /* Value/mask trigger support. */
1591         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1592                         lut->m2d);
1593
1594         /* Rise/fall trigger support. */
1595         for (i = 0, j = 0; i < 16; i++) {
1596                 if (devc->trigger.risingmask & (1 << i) ||
1597                     devc->trigger.fallingmask & (1 << i))
1598                         masks[j++] = 1 << i;
1599         }
1600
1601         build_lut_entry(masks[0], masks[0], lut->m0d);
1602         build_lut_entry(masks[1], masks[1], lut->m1d);
1603
1604         /* Add glue logic */
1605         if (masks[0] || masks[1]) {
1606                 /* Transition trigger. */
1607                 if (masks[0] & devc->trigger.risingmask)
1608                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1609                 if (masks[0] & devc->trigger.fallingmask)
1610                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1611                 if (masks[1] & devc->trigger.risingmask)
1612                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1613                 if (masks[1] & devc->trigger.fallingmask)
1614                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1615         } else {
1616                 /* Only value/mask trigger. */
1617                 lut->m3 = 0xffff;
1618         }
1619
1620         /* Triggertype: event. */
1621         lut->params.selres = 3;
1622
1623         return SR_OK;
1624 }