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