]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/protocol.c
68bb83e558b794b0ae9f2837193f4f4ea85d0df7
[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 supports arbitrary integer frequency divider in
31  * the 50MHz mode. The divider is in range 1...256 , allowing for
32  * very precise sampling rate selection. This driver supports only
33  * a subset of the sampling rates.
34  */
35 SR_PRIV const uint64_t samplerates[] = {
36         SR_KHZ(200),    /* div=250 */
37         SR_KHZ(250),    /* div=200 */
38         SR_KHZ(500),    /* div=100 */
39         SR_MHZ(1),      /* div=50  */
40         SR_MHZ(5),      /* div=10  */
41         SR_MHZ(10),     /* div=5   */
42         SR_MHZ(25),     /* div=2   */
43         SR_MHZ(50),     /* div=1   */
44         SR_MHZ(100),    /* Special FW needed */
45         SR_MHZ(200),    /* Special FW needed */
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(void *buf, size_t size, struct dev_context *devc)
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(void *buf, size_t size, struct dev_context *devc)
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(uint8_t reg, uint8_t *data, size_t len,
92                                  struct dev_context *devc)
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("Attempted to write %zu bytes, but buffer is too small.",
100                        len);
101                 return SR_ERR_BUG;
102         }
103
104         buf[idx++] = REG_ADDR_LOW | (reg & 0xf);
105         buf[idx++] = REG_ADDR_HIGH | (reg >> 4);
106
107         for (i = 0; i < len; i++) {
108                 buf[idx++] = REG_DATA_LOW | (data[i] & 0xf);
109                 buf[idx++] = REG_DATA_HIGH_WRITE | (data[i] >> 4);
110         }
111
112         return sigma_write(buf, idx, devc);
113 }
114
115 SR_PRIV int sigma_set_register(uint8_t reg, uint8_t value, struct dev_context *devc)
116 {
117         return sigma_write_register(reg, &value, 1, devc);
118 }
119
120 static int sigma_read_register(uint8_t reg, uint8_t *data, size_t len,
121                                struct dev_context *devc)
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(buf, sizeof(buf), devc);
130
131         return sigma_read(data, len, devc);
132 }
133
134 static int sigma_read_pos(uint32_t *stoppos, uint32_t *triggerpos,
135                           struct dev_context *devc)
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(buf, sizeof(buf), devc);
153
154         sigma_read(result, sizeof(result), devc);
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(uint16_t startchunk, size_t numchunks,
184                            uint8_t *data, struct dev_context *devc)
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(WRITE_MEMROW, buf, idx, devc);
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(buf, idx, devc);
216
217         return sigma_read(data, numchunks * ROW_LENGTH_BYTES, devc);
218 }
219
220 /* Upload trigger look-up tables to Sigma. */
221 SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *devc)
222 {
223         int i;
224         uint8_t tmp[2];
225         uint16_t bit;
226
227         /* Transpose the table and send to Sigma. */
228         for (i = 0; i < 16; i++) {
229                 bit = 1 << i;
230
231                 tmp[0] = tmp[1] = 0;
232
233                 if (lut->m2d[0] & bit)
234                         tmp[0] |= 0x01;
235                 if (lut->m2d[1] & bit)
236                         tmp[0] |= 0x02;
237                 if (lut->m2d[2] & bit)
238                         tmp[0] |= 0x04;
239                 if (lut->m2d[3] & bit)
240                         tmp[0] |= 0x08;
241
242                 if (lut->m3 & bit)
243                         tmp[0] |= 0x10;
244                 if (lut->m3s & bit)
245                         tmp[0] |= 0x20;
246                 if (lut->m4 & bit)
247                         tmp[0] |= 0x40;
248
249                 if (lut->m0d[0] & bit)
250                         tmp[1] |= 0x01;
251                 if (lut->m0d[1] & bit)
252                         tmp[1] |= 0x02;
253                 if (lut->m0d[2] & bit)
254                         tmp[1] |= 0x04;
255                 if (lut->m0d[3] & bit)
256                         tmp[1] |= 0x08;
257
258                 if (lut->m1d[0] & bit)
259                         tmp[1] |= 0x10;
260                 if (lut->m1d[1] & bit)
261                         tmp[1] |= 0x20;
262                 if (lut->m1d[2] & bit)
263                         tmp[1] |= 0x40;
264                 if (lut->m1d[3] & bit)
265                         tmp[1] |= 0x80;
266
267                 sigma_write_register(WRITE_TRIGGER_SELECT, tmp, sizeof(tmp),
268                                      devc);
269                 sigma_set_register(WRITE_TRIGGER_SELECT2, 0x30 | i, devc);
270         }
271
272         /* Send the parameters */
273         sigma_write_register(WRITE_TRIGGER_SELECT, (uint8_t *) &lut->params,
274                              sizeof(lut->params), devc);
275
276         return SR_OK;
277 }
278
279 /*
280  * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
281  * uses FTDI bitbang mode for netlist download in slave serial mode.
282  * (LATER: The OMEGA device's cable contains a more capable FTDI chip
283  * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
284  * compatible bitbang mode? For maximum code re-use and reduced libftdi
285  * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
286  * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
287  *
288  * 750kbps rate (four times the speed of sigmalogan) works well for
289  * netlist download. All pins except INIT_B are output pins during
290  * configuration download.
291  *
292  * Some pins are inverted as a byproduct of level shifting circuitry.
293  * That's why high CCLK level (from the cable's point of view) is idle
294  * from the FPGA's perspective.
295  *
296  * The vendor's literature discusses a "suicide sequence" which ends
297  * regular FPGA execution and should be sent before entering bitbang
298  * mode and sending configuration data. Set D7 and toggle D2, D3, D4
299  * a few times.
300  */
301 #define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
302 #define BB_PIN_PROG (1 << 1) /* D1, PROG */
303 #define BB_PIN_D2   (1 << 2) /* D2, (part of) SUICIDE */
304 #define BB_PIN_D3   (1 << 3) /* D3, (part of) SUICIDE */
305 #define BB_PIN_D4   (1 << 4) /* D4, (part of) SUICIDE (unused?) */
306 #define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
307 #define BB_PIN_DIN  (1 << 6) /* D6, DIN */
308 #define BB_PIN_D7   (1 << 7) /* D7, (part of) SUICIDE */
309
310 #define BB_BITRATE (750 * 1000)
311 #define BB_PINMASK (0xff & ~BB_PIN_INIT)
312
313 /*
314  * Initiate slave serial mode for configuration download. Which is done
315  * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
316  * initiating the configuration download.
317  *
318  * Run a "suicide sequence" first to terminate the regular FPGA operation
319  * before reconfiguration. The FTDI cable is single channel, and shares
320  * pins which are used for data communication in FIFO mode with pins that
321  * are used for FPGA configuration in bitbang mode. Hardware defaults for
322  * unconfigured hardware, and runtime conditions after FPGA configuration
323  * need to cooperate such that re-configuration of the FPGA can start.
324  */
325 static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
326 {
327         uint8_t suicide[] = {
328                 BB_PIN_D7 | BB_PIN_D2,
329                 BB_PIN_D7 | BB_PIN_D2,
330                 BB_PIN_D7 |           BB_PIN_D3,
331                 BB_PIN_D7 | BB_PIN_D2,
332                 BB_PIN_D7 |           BB_PIN_D3,
333                 BB_PIN_D7 | BB_PIN_D2,
334                 BB_PIN_D7 |           BB_PIN_D3,
335                 BB_PIN_D7 | BB_PIN_D2,
336         };
337         uint8_t init_array[] = {
338                 BB_PIN_CCLK,
339                 BB_PIN_CCLK | BB_PIN_PROG,
340                 BB_PIN_CCLK | BB_PIN_PROG,
341                 BB_PIN_CCLK,
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         };
349         int retries, ret;
350         uint8_t data;
351
352         /* Section 2. part 1), do the FPGA suicide. */
353         sigma_write(suicide, sizeof(suicide), devc);
354         sigma_write(suicide, sizeof(suicide), devc);
355         sigma_write(suicide, sizeof(suicide), devc);
356         sigma_write(suicide, sizeof(suicide), devc);
357         g_usleep(10 * 1000);
358
359         /* Section 2. part 2), pulse PROG. */
360         sigma_write(init_array, sizeof(init_array), devc);
361         g_usleep(10 * 1000);
362         ftdi_usb_purge_buffers(&devc->ftdic);
363
364         /* Wait until the FPGA asserts INIT_B. */
365         retries = 10;
366         while (retries--) {
367                 ret = sigma_read(&data, 1, devc);
368                 if (ret < 0)
369                         return ret;
370                 if (data & BB_PIN_INIT)
371                         return SR_OK;
372                 g_usleep(10 * 1000);
373         }
374
375         return SR_ERR_TIMEOUT;
376 }
377
378 /*
379  * This is belt and braces. Re-run the bitbang initiation sequence a few
380  * times should first attempts fail. Failure is rare but can happen (was
381  * observed during driver development).
382  */
383 static int sigma_fpga_init_bitbang(struct dev_context *devc)
384 {
385         size_t retries;
386         int ret;
387
388         retries = 10;
389         while (retries--) {
390                 ret = sigma_fpga_init_bitbang_once(devc);
391                 if (ret == SR_OK)
392                         return ret;
393                 if (ret != SR_ERR_TIMEOUT)
394                         return ret;
395         }
396         return ret;
397 }
398
399 /*
400  * Configure the FPGA for logic-analyzer mode.
401  */
402 static int sigma_fpga_init_la(struct dev_context *devc)
403 {
404         /*
405          * TODO Construct the sequence at runtime? Such that request data
406          * and response check values will match more apparently?
407          */
408         uint8_t mode_regval = WMR_SDRAMINIT;
409         uint8_t logic_mode_start[] = {
410                 /* Read ID register. */
411                 REG_ADDR_LOW  | (READ_ID & 0xf),
412                 REG_ADDR_HIGH | (READ_ID >> 4),
413                 REG_READ_ADDR,
414
415                 /* Write 0x55 to scratch register, read back. */
416                 REG_ADDR_LOW | (WRITE_TEST & 0xf),
417                 REG_DATA_LOW | 0x5,
418                 REG_DATA_HIGH_WRITE | 0x5,
419                 REG_READ_ADDR,
420
421                 /* Write 0xaa to scratch register, read back. */
422                 REG_DATA_LOW | 0xa,
423                 REG_DATA_HIGH_WRITE | 0xa,
424                 REG_READ_ADDR,
425
426                 /* Initiate SDRAM initialization in mode register. */
427                 REG_ADDR_LOW | (WRITE_MODE & 0xf),
428                 REG_DATA_LOW | (mode_regval & 0xf),
429                 REG_DATA_HIGH_WRITE | (mode_regval >> 4),
430         };
431         uint8_t result[3];
432         int ret;
433
434         /*
435          * Send the command sequence which contains 3 READ requests.
436          * Expect to see the corresponding 3 response bytes.
437          */
438         sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
439         ret = sigma_read(result, ARRAY_SIZE(result), devc);
440         if (ret != ARRAY_SIZE(result))
441                 goto err;
442         if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
443                 goto err;
444
445         return SR_OK;
446
447 err:
448         sr_err("Configuration failed. Invalid reply received.");
449         return SR_ERR;
450 }
451
452 /*
453  * Read the firmware from a file and transform it into a series of bitbang
454  * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
455  * by the caller of this function.
456  */
457 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
458                               uint8_t **bb_cmd, gsize *bb_cmd_size)
459 {
460         uint8_t *firmware;
461         size_t file_size;
462         uint8_t *p;
463         size_t l;
464         uint32_t imm;
465         size_t bb_size;
466         uint8_t *bb_stream, *bbs, byte, mask, v;
467
468         /* Retrieve the on-disk firmware file content. */
469         firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
470                 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
471         if (!firmware)
472                 return SR_ERR_IO;
473
474         /* Unscramble the file content (XOR with "random" sequence). */
475         p = firmware;
476         l = file_size;
477         imm = 0x3f6df2ab;
478         while (l--) {
479                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
480                 *p++ ^= imm & 0xff;
481         }
482
483         /*
484          * Generate a sequence of bitbang samples. With two samples per
485          * FPGA configuration bit, providing the level for the DIN signal
486          * as well as two edges for CCLK. See Xilinx UG332 for details
487          * ("slave serial" mode).
488          *
489          * Note that CCLK is inverted in hardware. That's why the
490          * respective bit is first set and then cleared in the bitbang
491          * sample sets. So that the DIN level will be stable when the
492          * data gets sampled at the rising CCLK edge, and the signals'
493          * setup time constraint will be met.
494          *
495          * The caller will put the FPGA into download mode, will send
496          * the bitbang samples, and release the allocated memory.
497          */
498         bb_size = file_size * 8 * 2;
499         bb_stream = g_try_malloc(bb_size);
500         if (!bb_stream) {
501                 sr_err("%s: Failed to allocate bitbang stream", __func__);
502                 g_free(firmware);
503                 return SR_ERR_MALLOC;
504         }
505         bbs = bb_stream;
506         p = firmware;
507         l = file_size;
508         while (l--) {
509                 byte = *p++;
510                 mask = 0x80;
511                 while (mask) {
512                         v = (byte & mask) ? BB_PIN_DIN : 0;
513                         mask >>= 1;
514                         *bbs++ = v | BB_PIN_CCLK;
515                         *bbs++ = v;
516                 }
517         }
518         g_free(firmware);
519
520         /* The transformation completed successfully, return the result. */
521         *bb_cmd = bb_stream;
522         *bb_cmd_size = bb_size;
523
524         return SR_OK;
525 }
526
527 static int upload_firmware(struct sr_context *ctx,
528         struct dev_context *devc, enum sigma_firmware_idx firmware_idx)
529 {
530         int ret;
531         unsigned char *buf;
532         unsigned char pins;
533         size_t buf_size;
534         const char *firmware;
535
536         /* Check for valid firmware file selection. */
537         if (firmware_idx >= ARRAY_SIZE(firmware_files))
538                 return SR_ERR_ARG;
539         firmware = firmware_files[firmware_idx];
540         if (!firmware || !*firmware)
541                 return SR_ERR_ARG;
542
543         /* Avoid downloading the same firmware multiple times. */
544         if (devc->firmware_idx == firmware_idx) {
545                 sr_info("Not uploading firmware file '%s' again.", firmware);
546                 return SR_OK;
547         }
548
549         devc->state.state = SIGMA_CONFIG;
550
551         /* Set the cable to bitbang mode. */
552         ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
553         if (ret < 0) {
554                 sr_err("ftdi_set_bitmode failed: %s",
555                        ftdi_get_error_string(&devc->ftdic));
556                 return SR_ERR;
557         }
558         ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
559         if (ret < 0) {
560                 sr_err("ftdi_set_baudrate failed: %s",
561                        ftdi_get_error_string(&devc->ftdic));
562                 return SR_ERR;
563         }
564
565         /* Initiate FPGA configuration mode. */
566         ret = sigma_fpga_init_bitbang(devc);
567         if (ret)
568                 return ret;
569
570         /* Prepare wire format of the firmware image. */
571         ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
572         if (ret != SR_OK) {
573                 sr_err("An error occurred while reading the firmware: %s",
574                        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(buf, buf_size, devc);
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(&pins, 1, devc) == 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                         if (!match->channel->enabled)
953                                 /* Ignore disabled channels with a trigger. */
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 "
997                                                    "is supported.");
998                                         return SR_ERR;
999                                 }
1000                         }
1001                 }
1002         }
1003
1004         return SR_OK;
1005 }
1006
1007 /* Software trigger to determine exact trigger position. */
1008 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1009                               struct sigma_trigger *t)
1010 {
1011         int i;
1012         uint16_t sample = 0;
1013
1014         for (i = 0; i < 8; i++) {
1015                 if (i > 0)
1016                         last_sample = sample;
1017                 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
1018
1019                 /* Simple triggers. */
1020                 if ((sample & t->simplemask) != t->simplevalue)
1021                         continue;
1022
1023                 /* Rising edge. */
1024                 if (((last_sample & t->risingmask) != 0) ||
1025                     ((sample & t->risingmask) != t->risingmask))
1026                         continue;
1027
1028                 /* Falling edge. */
1029                 if ((last_sample & t->fallingmask) != t->fallingmask ||
1030                     (sample & t->fallingmask) != 0)
1031                         continue;
1032
1033                 break;
1034         }
1035
1036         /* If we did not match, return original trigger pos. */
1037         return i & 0x7;
1038 }
1039
1040 static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1041 {
1042         /* TODO
1043          * Check whether the combination of this very sample and the
1044          * previous state match the configured trigger condition. This
1045          * improves the resolution of the trigger marker's position.
1046          * The hardware provided position is coarse, and may point to
1047          * a position before the actual match.
1048          *
1049          * See the previous get_trigger_offset() implementation. This
1050          * code needs to get re-used here.
1051          */
1052         (void)devc;
1053         (void)sample;
1054         (void)get_trigger_offset;
1055
1056         return FALSE;
1057 }
1058
1059 static int check_and_submit_sample(struct dev_context *devc,
1060         uint16_t sample, size_t count, gboolean check_trigger)
1061 {
1062         gboolean triggered;
1063         int ret;
1064
1065         triggered = check_trigger && sample_matches_trigger(devc, sample);
1066         if (triggered) {
1067                 ret = flush_submit_buffer(devc);
1068                 if (ret != SR_OK)
1069                         return ret;
1070                 ret = std_session_send_df_trigger(devc->buffer->sdi);
1071                 if (ret != SR_OK)
1072                         return ret;
1073         }
1074
1075         ret = addto_submit_buffer(devc, sample, count);
1076         if (ret != SR_OK)
1077                 return ret;
1078
1079         return SR_OK;
1080 }
1081
1082 /*
1083  * Return the timestamp of "DRAM cluster".
1084  */
1085 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1086 {
1087         return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
1088 }
1089
1090 /*
1091  * Return one 16bit data entity of a DRAM cluster at the specified index.
1092  */
1093 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1094 {
1095         uint16_t sample;
1096
1097         sample = 0;
1098         sample |= cl->samples[idx].sample_lo << 0;
1099         sample |= cl->samples[idx].sample_hi << 8;
1100         sample = (sample >> 8) | (sample << 8);
1101         return sample;
1102 }
1103
1104 /*
1105  * Deinterlace sample data that was retrieved at 100MHz samplerate.
1106  * One 16bit item contains two samples of 8bits each. The bits of
1107  * multiple samples are interleaved.
1108  */
1109 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1110 {
1111         uint16_t outdata;
1112
1113         indata >>= idx;
1114         outdata = 0;
1115         outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1116         outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1117         outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1118         outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1119         outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1120         outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1121         outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1122         outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1123         return outdata;
1124 }
1125
1126 /*
1127  * Deinterlace sample data that was retrieved at 200MHz samplerate.
1128  * One 16bit item contains four samples of 4bits each. The bits of
1129  * multiple samples are interleaved.
1130  */
1131 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1132 {
1133         uint16_t outdata;
1134
1135         indata >>= idx;
1136         outdata = 0;
1137         outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1138         outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1139         outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1140         outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1141         return outdata;
1142 }
1143
1144 static void sigma_decode_dram_cluster(struct dev_context *devc,
1145         struct sigma_dram_cluster *dram_cluster,
1146         size_t events_in_cluster, gboolean triggered)
1147 {
1148         struct sigma_state *ss;
1149         uint16_t tsdiff, ts, sample, item16;
1150         unsigned int i;
1151
1152         if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1153                 triggered = FALSE;
1154
1155         /*
1156          * If this cluster is not adjacent to the previously received
1157          * cluster, then send the appropriate number of samples with the
1158          * previous values to the sigrok session. This "decodes RLE".
1159          *
1160          * These samples cannot match the trigger since they just repeat
1161          * the previously submitted data pattern. (This assumption holds
1162          * for simple level and edge triggers. It would not for timed or
1163          * counted conditions, which currently are not supported.)
1164          */
1165         ss = &devc->state;
1166         ts = sigma_dram_cluster_ts(dram_cluster);
1167         tsdiff = ts - ss->lastts;
1168         if (tsdiff > 0) {
1169                 size_t count;
1170                 count = tsdiff * devc->samples_per_event;
1171                 (void)check_and_submit_sample(devc, ss->lastsample, 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(WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN, devc);
1290         do {
1291                 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 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(WRITE_MODE, WMR_SDRAMREADEN, devc);
1299
1300         /* Get the current position. */
1301         sigma_read_pos(&stoppos, &triggerpos, devc);
1302
1303         /* Check if trigger has fired. */
1304         if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 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(dl_line, dl_lines_curr,
1348                                         (uint8_t *)dram_line, devc);
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 triggerlut *lut, struct dev_context *devc)
1543 {
1544         int i,j;
1545         uint16_t masks[2] = { 0, 0 };
1546
1547         memset(lut, 0, sizeof(struct triggerlut));
1548
1549         /* Constant for simple triggers. */
1550         lut->m4 = 0xa000;
1551
1552         /* Value/mask trigger support. */
1553         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1554                         lut->m2d);
1555
1556         /* Rise/fall trigger support. */
1557         for (i = 0, j = 0; i < 16; i++) {
1558                 if (devc->trigger.risingmask & (1 << i) ||
1559                     devc->trigger.fallingmask & (1 << i))
1560                         masks[j++] = 1 << i;
1561         }
1562
1563         build_lut_entry(masks[0], masks[0], lut->m0d);
1564         build_lut_entry(masks[1], masks[1], lut->m1d);
1565
1566         /* Add glue logic */
1567         if (masks[0] || masks[1]) {
1568                 /* Transition trigger. */
1569                 if (masks[0] & devc->trigger.risingmask)
1570                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1571                 if (masks[0] & devc->trigger.fallingmask)
1572                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1573                 if (masks[1] & devc->trigger.risingmask)
1574                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1575                 if (masks[1] & devc->trigger.fallingmask)
1576                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1577         } else {
1578                 /* Only value/mask trigger. */
1579                 lut->m3 = 0xffff;
1580         }
1581
1582         /* Triggertype: event. */
1583         lut->params.selres = 3;
1584
1585         return SR_OK;
1586 }