]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/protocol.c
f9e54089cb5ef270f5bda887339fe53686c74c87
[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         "asix-sigma-50.fw", /* Up to 50MHz sample rate, 8bit divider. */
52         "asix-sigma-100.fw", /* 100MHz sample rate, fixed. */
53         "asix-sigma-200.fw", /* 200MHz sample rate, fixed. */
54         "asix-sigma-50sync.fw", /* Synchronous clock from external pin. */
55         "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. Run a "suicide sequence" first
317  * to terminate the regular FPGA operation before reconfiguration.
318  */
319 static int sigma_fpga_init_bitbang(struct dev_context *devc)
320 {
321         uint8_t suicide[] = {
322                 BB_PIN_D7 | BB_PIN_D2,
323                 BB_PIN_D7 | BB_PIN_D2,
324                 BB_PIN_D7 |           BB_PIN_D3,
325                 BB_PIN_D7 | BB_PIN_D2,
326                 BB_PIN_D7 |           BB_PIN_D3,
327                 BB_PIN_D7 | BB_PIN_D2,
328                 BB_PIN_D7 |           BB_PIN_D3,
329                 BB_PIN_D7 | BB_PIN_D2,
330         };
331         uint8_t init_array[] = {
332                 BB_PIN_CCLK,
333                 BB_PIN_CCLK | BB_PIN_PROG,
334                 BB_PIN_CCLK | BB_PIN_PROG,
335                 BB_PIN_CCLK,
336                 BB_PIN_CCLK,
337                 BB_PIN_CCLK,
338                 BB_PIN_CCLK,
339                 BB_PIN_CCLK,
340                 BB_PIN_CCLK,
341                 BB_PIN_CCLK,
342         };
343         int retries, ret;
344         uint8_t data;
345
346         /* Section 2. part 1), do the FPGA suicide. */
347         sigma_write(suicide, sizeof(suicide), devc);
348         sigma_write(suicide, sizeof(suicide), devc);
349         sigma_write(suicide, sizeof(suicide), devc);
350         sigma_write(suicide, sizeof(suicide), devc);
351
352         /* Section 2. part 2), pulse PROG. */
353         sigma_write(init_array, sizeof(init_array), devc);
354         ftdi_usb_purge_buffers(&devc->ftdic);
355
356         /* Wait until the FPGA asserts INIT_B. */
357         retries = 10;
358         while (retries--) {
359                 ret = sigma_read(&data, 1, devc);
360                 if (ret < 0)
361                         return ret;
362                 if (data & BB_PIN_INIT)
363                         return SR_OK;
364                 g_usleep(10 * 1000);
365         }
366
367         return SR_ERR_TIMEOUT;
368 }
369
370 /*
371  * Configure the FPGA for logic-analyzer mode.
372  */
373 static int sigma_fpga_init_la(struct dev_context *devc)
374 {
375         /*
376          * TODO Construct the sequence at runtime? Such that request data
377          * and response check values will match more apparently?
378          */
379         uint8_t mode_regval = WMR_SDRAMINIT;
380         uint8_t logic_mode_start[] = {
381                 /* Read ID register. */
382                 REG_ADDR_LOW  | (READ_ID & 0xf),
383                 REG_ADDR_HIGH | (READ_ID >> 4),
384                 REG_READ_ADDR,
385
386                 /* Write 0x55 to scratch register, read back. */
387                 REG_ADDR_LOW | (WRITE_TEST & 0xf),
388                 REG_DATA_LOW | 0x5,
389                 REG_DATA_HIGH_WRITE | 0x5,
390                 REG_READ_ADDR,
391
392                 /* Write 0xaa to scratch register, read back. */
393                 REG_DATA_LOW | 0xa,
394                 REG_DATA_HIGH_WRITE | 0xa,
395                 REG_READ_ADDR,
396
397                 /* Initiate SDRAM initialization in mode register. */
398                 REG_ADDR_LOW | (WRITE_MODE & 0xf),
399                 REG_DATA_LOW | (mode_regval & 0xf),
400                 REG_DATA_HIGH_WRITE | (mode_regval >> 4),
401         };
402         uint8_t result[3];
403         int ret;
404
405         /*
406          * Send the command sequence which contains 3 READ requests.
407          * Expect to see the corresponding 3 response bytes.
408          */
409         sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
410         ret = sigma_read(result, ARRAY_SIZE(result), devc);
411         if (ret != ARRAY_SIZE(result))
412                 goto err;
413         if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
414                 goto err;
415
416         return SR_OK;
417
418 err:
419         sr_err("Configuration failed. Invalid reply received.");
420         return SR_ERR;
421 }
422
423 /*
424  * Read the firmware from a file and transform it into a series of bitbang
425  * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
426  * by the caller of this function.
427  */
428 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
429                               uint8_t **bb_cmd, gsize *bb_cmd_size)
430 {
431         uint8_t *firmware;
432         size_t file_size;
433         uint8_t *p;
434         size_t l;
435         uint32_t imm;
436         size_t bb_size;
437         uint8_t *bb_stream, *bbs, byte, mask, v;
438
439         /* Retrieve the on-disk firmware file content. */
440         firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
441                 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
442         if (!firmware)
443                 return SR_ERR_IO;
444
445         /* Unscramble the file content (XOR with "random" sequence). */
446         p = firmware;
447         l = file_size;
448         imm = 0x3f6df2ab;
449         while (l--) {
450                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
451                 *p++ ^= imm & 0xff;
452         }
453
454         /*
455          * Generate a sequence of bitbang samples. With two samples per
456          * FPGA configuration bit, providing the level for the DIN signal
457          * as well as two edges for CCLK. See Xilinx UG332 for details
458          * ("slave serial" mode).
459          *
460          * Note that CCLK is inverted in hardware. That's why the
461          * respective bit is first set and then cleared in the bitbang
462          * sample sets. So that the DIN level will be stable when the
463          * data gets sampled at the rising CCLK edge, and the signals'
464          * setup time constraint will be met.
465          *
466          * The caller will put the FPGA into download mode, will send
467          * the bitbang samples, and release the allocated memory.
468          */
469         bb_size = file_size * 8 * 2;
470         bb_stream = g_try_malloc(bb_size);
471         if (!bb_stream) {
472                 sr_err("%s: Failed to allocate bitbang stream", __func__);
473                 g_free(firmware);
474                 return SR_ERR_MALLOC;
475         }
476         bbs = bb_stream;
477         p = firmware;
478         l = file_size;
479         while (l--) {
480                 byte = *p++;
481                 mask = 0x80;
482                 while (mask) {
483                         v = (byte & mask) ? BB_PIN_DIN : 0;
484                         mask >>= 1;
485                         *bbs++ = v | BB_PIN_CCLK;
486                         *bbs++ = v;
487                 }
488         }
489         g_free(firmware);
490
491         /* The transformation completed successfully, return the result. */
492         *bb_cmd = bb_stream;
493         *bb_cmd_size = bb_size;
494
495         return SR_OK;
496 }
497
498 static int upload_firmware(struct sr_context *ctx,
499                 int firmware_idx, struct dev_context *devc)
500 {
501         int ret;
502         unsigned char *buf;
503         unsigned char pins;
504         size_t buf_size;
505         const char *firmware;
506
507         /* Avoid downloading the same firmware multiple times. */
508         firmware = firmware_files[firmware_idx];
509         if (devc->cur_firmware == firmware_idx) {
510                 sr_info("Not uploading firmware file '%s' again.", firmware);
511                 return SR_OK;
512         }
513
514         /* Set the cable to bitbang mode. */
515         ret = ftdi_set_bitmode(&devc->ftdic, BB_PINMASK, BITMODE_BITBANG);
516         if (ret < 0) {
517                 sr_err("ftdi_set_bitmode failed: %s",
518                        ftdi_get_error_string(&devc->ftdic));
519                 return SR_ERR;
520         }
521         ret = ftdi_set_baudrate(&devc->ftdic, BB_BITRATE);
522         if (ret < 0) {
523                 sr_err("ftdi_set_baudrate failed: %s",
524                        ftdi_get_error_string(&devc->ftdic));
525                 return SR_ERR;
526         }
527
528         /* Initiate FPGA configuration mode. */
529         ret = sigma_fpga_init_bitbang(devc);
530         if (ret)
531                 return ret;
532
533         /* Prepare wire format of the firmware image. */
534         ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
535         if (ret != SR_OK) {
536                 sr_err("An error occurred while reading the firmware: %s",
537                        firmware);
538                 return ret;
539         }
540
541         /* Write the FPGA netlist to the cable. */
542         sr_info("Uploading firmware file '%s'.", firmware);
543         sigma_write(buf, buf_size, devc);
544
545         g_free(buf);
546
547         /* Leave bitbang mode and discard pending input data. */
548         ret = ftdi_set_bitmode(&devc->ftdic, 0, BITMODE_RESET);
549         if (ret < 0) {
550                 sr_err("ftdi_set_bitmode failed: %s",
551                        ftdi_get_error_string(&devc->ftdic));
552                 return SR_ERR;
553         }
554         ftdi_usb_purge_buffers(&devc->ftdic);
555         while (sigma_read(&pins, 1, devc) == 1)
556                 ;
557
558         /* Initialize the FPGA for logic-analyzer mode. */
559         ret = sigma_fpga_init_la(devc);
560         if (ret != SR_OK)
561                 return ret;
562
563         /* Keep track of successful firmware download completion. */
564         devc->cur_firmware = firmware_idx;
565         sr_info("Firmware uploaded.");
566
567         return SR_OK;
568 }
569
570 /*
571  * Sigma doesn't support limiting the number of samples, so we have to
572  * translate the number and the samplerate to an elapsed time.
573  *
574  * In addition we need to ensure that the last data cluster has passed
575  * the hardware pipeline, and became available to the PC side. With RLE
576  * compression up to 327ms could pass before another cluster accumulates
577  * at 200kHz samplerate when input pins don't change.
578  */
579 SR_PRIV uint64_t sigma_limit_samples_to_msec(const struct dev_context *devc,
580                                              uint64_t limit_samples)
581 {
582         uint64_t limit_msec;
583         uint64_t worst_cluster_time_ms;
584
585         limit_msec = limit_samples * 1000 / devc->cur_samplerate;
586         worst_cluster_time_ms = 65536 * 1000 / devc->cur_samplerate;
587         /*
588          * One cluster time is not enough to flush pipeline when sampling
589          * grounded pins with 1 sample limit at 200kHz. Hence the 2* fix.
590          */
591         return limit_msec + 2 * worst_cluster_time_ms;
592 }
593
594 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
595 {
596         struct dev_context *devc;
597         struct drv_context *drvc;
598         size_t i;
599         int ret;
600         int num_channels;
601
602         devc = sdi->priv;
603         drvc = sdi->driver->context;
604         ret = SR_OK;
605
606         /* Reject rates that are not in the list of supported rates. */
607         for (i = 0; i < samplerates_count; i++) {
608                 if (samplerates[i] == samplerate)
609                         break;
610         }
611         if (i >= samplerates_count || samplerates[i] == 0)
612                 return SR_ERR_SAMPLERATE;
613
614         /*
615          * Depending on the samplerates of 200/100/50- MHz, specific
616          * firmware is required and higher rates might limit the set
617          * of available channels.
618          */
619         num_channels = devc->num_channels;
620         if (samplerate <= SR_MHZ(50)) {
621                 ret = upload_firmware(drvc->sr_ctx, 0, devc);
622                 num_channels = 16;
623         } else if (samplerate == SR_MHZ(100)) {
624                 ret = upload_firmware(drvc->sr_ctx, 1, devc);
625                 num_channels = 8;
626         } else if (samplerate == SR_MHZ(200)) {
627                 ret = upload_firmware(drvc->sr_ctx, 2, devc);
628                 num_channels = 4;
629         }
630
631         /*
632          * Derive the sample period from the sample rate as well as the
633          * number of samples that the device will communicate within
634          * an "event" (memory organization internal to the device).
635          */
636         if (ret == SR_OK) {
637                 devc->num_channels = num_channels;
638                 devc->cur_samplerate = samplerate;
639                 devc->samples_per_event = 16 / devc->num_channels;
640                 devc->state.state = SIGMA_IDLE;
641         }
642
643         /*
644          * Support for "limit_samples" is implemented by stopping
645          * acquisition after a corresponding period of time.
646          * Re-calculate that period of time, in case the limit is
647          * set first and the samplerate gets (re-)configured later.
648          */
649         if (ret == SR_OK && devc->limit_samples) {
650                 uint64_t msecs;
651                 msecs = sigma_limit_samples_to_msec(devc, devc->limit_samples);
652                 devc->limit_msec = msecs;
653         }
654
655         return ret;
656 }
657
658 /*
659  * In 100 and 200 MHz mode, only a single pin rising/falling can be
660  * set as trigger. In other modes, two rising/falling triggers can be set,
661  * in addition to value/mask trigger for any number of channels.
662  *
663  * The Sigma supports complex triggers using boolean expressions, but this
664  * has not been implemented yet.
665  */
666 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
667 {
668         struct dev_context *devc;
669         struct sr_trigger *trigger;
670         struct sr_trigger_stage *stage;
671         struct sr_trigger_match *match;
672         const GSList *l, *m;
673         int channelbit, trigger_set;
674
675         devc = sdi->priv;
676         memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
677         if (!(trigger = sr_session_trigger_get(sdi->session)))
678                 return SR_OK;
679
680         trigger_set = 0;
681         for (l = trigger->stages; l; l = l->next) {
682                 stage = l->data;
683                 for (m = stage->matches; m; m = m->next) {
684                         match = m->data;
685                         if (!match->channel->enabled)
686                                 /* Ignore disabled channels with a trigger. */
687                                 continue;
688                         channelbit = 1 << (match->channel->index);
689                         if (devc->cur_samplerate >= SR_MHZ(100)) {
690                                 /* Fast trigger support. */
691                                 if (trigger_set) {
692                                         sr_err("Only a single pin trigger is "
693                                                         "supported in 100 and 200MHz mode.");
694                                         return SR_ERR;
695                                 }
696                                 if (match->match == SR_TRIGGER_FALLING)
697                                         devc->trigger.fallingmask |= channelbit;
698                                 else if (match->match == SR_TRIGGER_RISING)
699                                         devc->trigger.risingmask |= channelbit;
700                                 else {
701                                         sr_err("Only rising/falling trigger is "
702                                                         "supported in 100 and 200MHz mode.");
703                                         return SR_ERR;
704                                 }
705
706                                 trigger_set++;
707                         } else {
708                                 /* Simple trigger support (event). */
709                                 if (match->match == SR_TRIGGER_ONE) {
710                                         devc->trigger.simplevalue |= channelbit;
711                                         devc->trigger.simplemask |= channelbit;
712                                 } else if (match->match == SR_TRIGGER_ZERO) {
713                                         devc->trigger.simplevalue &= ~channelbit;
714                                         devc->trigger.simplemask |= channelbit;
715                                 } else if (match->match == SR_TRIGGER_FALLING) {
716                                         devc->trigger.fallingmask |= channelbit;
717                                         trigger_set++;
718                                 } else if (match->match == SR_TRIGGER_RISING) {
719                                         devc->trigger.risingmask |= channelbit;
720                                         trigger_set++;
721                                 }
722
723                                 /*
724                                  * Actually, Sigma supports 2 rising/falling triggers,
725                                  * but they are ORed and the current trigger syntax
726                                  * does not permit ORed triggers.
727                                  */
728                                 if (trigger_set > 1) {
729                                         sr_err("Only 1 rising/falling trigger "
730                                                    "is supported.");
731                                         return SR_ERR;
732                                 }
733                         }
734                 }
735         }
736
737         return SR_OK;
738 }
739
740 /* Software trigger to determine exact trigger position. */
741 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
742                               struct sigma_trigger *t)
743 {
744         int i;
745         uint16_t sample = 0;
746
747         for (i = 0; i < 8; i++) {
748                 if (i > 0)
749                         last_sample = sample;
750                 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
751
752                 /* Simple triggers. */
753                 if ((sample & t->simplemask) != t->simplevalue)
754                         continue;
755
756                 /* Rising edge. */
757                 if (((last_sample & t->risingmask) != 0) ||
758                     ((sample & t->risingmask) != t->risingmask))
759                         continue;
760
761                 /* Falling edge. */
762                 if ((last_sample & t->fallingmask) != t->fallingmask ||
763                     (sample & t->fallingmask) != 0)
764                         continue;
765
766                 break;
767         }
768
769         /* If we did not match, return original trigger pos. */
770         return i & 0x7;
771 }
772
773 /*
774  * Return the timestamp of "DRAM cluster".
775  */
776 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
777 {
778         return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
779 }
780
781 /*
782  * Return one 16bit data entity of a DRAM cluster at the specified index.
783  */
784 static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
785 {
786         uint16_t sample;
787
788         sample = 0;
789         sample |= cl->samples[idx].sample_lo << 0;
790         sample |= cl->samples[idx].sample_hi << 8;
791         sample = (sample >> 8) | (sample << 8);
792         return sample;
793 }
794
795 /*
796  * Deinterlace sample data that was retrieved at 100MHz samplerate.
797  * One 16bit item contains two samples of 8bits each. The bits of
798  * multiple samples are interleaved.
799  */
800 static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
801 {
802         uint16_t outdata;
803
804         indata >>= idx;
805         outdata = 0;
806         outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
807         outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
808         outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
809         outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
810         outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
811         outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
812         outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
813         outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
814         return outdata;
815 }
816
817 /*
818  * Deinterlace sample data that was retrieved at 200MHz samplerate.
819  * One 16bit item contains four samples of 4bits each. The bits of
820  * multiple samples are interleaved.
821  */
822 static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
823 {
824         uint16_t outdata;
825
826         indata >>= idx;
827         outdata = 0;
828         outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
829         outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
830         outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
831         outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
832         return outdata;
833 }
834
835 static void store_sr_sample(uint8_t *samples, int idx, uint16_t data)
836 {
837         samples[2 * idx + 0] = (data >> 0) & 0xff;
838         samples[2 * idx + 1] = (data >> 8) & 0xff;
839 }
840
841 /*
842  * Local wrapper around sr_session_send() calls. Make sure to not send
843  * more samples to the session's datafeed than what was requested by a
844  * previously configured (optional) sample count.
845  */
846 static void sigma_session_send(struct sr_dev_inst *sdi,
847                                 struct sr_datafeed_packet *packet)
848 {
849         struct dev_context *devc;
850         struct sr_datafeed_logic *logic;
851         uint64_t send_now;
852
853         devc = sdi->priv;
854         if (devc->limit_samples) {
855                 logic = (void *)packet->payload;
856                 send_now = logic->length / logic->unitsize;
857                 if (devc->sent_samples + send_now > devc->limit_samples) {
858                         send_now = devc->limit_samples - devc->sent_samples;
859                         logic->length = send_now * logic->unitsize;
860                 }
861                 if (!send_now)
862                         return;
863                 devc->sent_samples += send_now;
864         }
865
866         sr_session_send(sdi, packet);
867 }
868
869 /*
870  * This size translates to: number of events per row (strictly speaking
871  * 448, assuming "up to 512" does not harm here) times the sample data's
872  * unit size (16 bits), times the maximum number of samples per event (4).
873  */
874 #define SAMPLES_BUFFER_SIZE     (ROW_LENGTH_U16 * sizeof(uint16_t) * 4)
875
876 static void sigma_decode_dram_cluster(struct sigma_dram_cluster *dram_cluster,
877                                       unsigned int events_in_cluster,
878                                       unsigned int triggered,
879                                       struct sr_dev_inst *sdi)
880 {
881         struct dev_context *devc = sdi->priv;
882         struct sigma_state *ss = &devc->state;
883         struct sr_datafeed_packet packet;
884         struct sr_datafeed_logic logic;
885         uint16_t tsdiff, ts, sample, item16;
886         uint8_t samples[SAMPLES_BUFFER_SIZE];
887         uint8_t *send_ptr;
888         size_t send_count, trig_count;
889         unsigned int i;
890         int j;
891
892         ts = sigma_dram_cluster_ts(dram_cluster);
893         tsdiff = ts - ss->lastts;
894         ss->lastts = ts + EVENTS_PER_CLUSTER;
895
896         packet.type = SR_DF_LOGIC;
897         packet.payload = &logic;
898         logic.unitsize = 2;
899         logic.data = samples;
900
901         /*
902          * If this cluster is not adjacent to the previously received
903          * cluster, then send the appropriate number of samples with the
904          * previous values to the sigrok session. This "decodes RLE".
905          *
906          * TODO Improve (mostly: generalize) support for queueing data
907          * before submission to the session bus. This implementation
908          * happens to work for "up to 1024 samples" despite the "up to
909          * 512 entities of 16 bits", due to the "up to 4 sample points
910          * per event" factor. A better implementation would eliminate
911          * these magic numbers.
912          */
913         for (ts = 0; ts < tsdiff; ts++) {
914                 i = ts % 1024;
915                 store_sr_sample(samples, i, ss->lastsample);
916
917                 /*
918                  * If we have 1024 samples ready or we're at the
919                  * end of submitting the padding samples, submit
920                  * the packet to Sigrok. Since constant data is
921                  * sent, duplication of data for rates above 50MHz
922                  * is simple.
923                  */
924                 if ((i == 1023) || (ts == tsdiff - 1)) {
925                         logic.length = (i + 1) * logic.unitsize;
926                         for (j = 0; j < devc->samples_per_event; j++)
927                                 sigma_session_send(sdi, &packet);
928                 }
929         }
930
931         /*
932          * Parse the samples in current cluster and prepare them
933          * to be submitted to Sigrok. Cope with memory layouts that
934          * vary with the samplerate.
935          */
936         send_ptr = &samples[0];
937         send_count = 0;
938         sample = 0;
939         for (i = 0; i < events_in_cluster; i++) {
940                 item16 = sigma_dram_cluster_data(dram_cluster, i);
941                 if (devc->cur_samplerate == SR_MHZ(200)) {
942                         sample = sigma_deinterlace_200mhz_data(item16, 0);
943                         store_sr_sample(samples, send_count++, sample);
944                         sample = sigma_deinterlace_200mhz_data(item16, 1);
945                         store_sr_sample(samples, send_count++, sample);
946                         sample = sigma_deinterlace_200mhz_data(item16, 2);
947                         store_sr_sample(samples, send_count++, sample);
948                         sample = sigma_deinterlace_200mhz_data(item16, 3);
949                         store_sr_sample(samples, send_count++, sample);
950                 } else if (devc->cur_samplerate == SR_MHZ(100)) {
951                         sample = sigma_deinterlace_100mhz_data(item16, 0);
952                         store_sr_sample(samples, send_count++, sample);
953                         sample = sigma_deinterlace_100mhz_data(item16, 1);
954                         store_sr_sample(samples, send_count++, sample);
955                 } else {
956                         sample = item16;
957                         store_sr_sample(samples, send_count++, sample);
958                 }
959         }
960
961         /*
962          * If a trigger position applies, then provide the datafeed with
963          * the first part of data up to that position, then send the
964          * trigger marker.
965          */
966         int trigger_offset = 0;
967         if (triggered) {
968                 /*
969                  * Trigger is not always accurate to sample because of
970                  * pipeline delay. However, it always triggers before
971                  * the actual event. We therefore look at the next
972                  * samples to pinpoint the exact position of the trigger.
973                  */
974                 trigger_offset = get_trigger_offset(samples,
975                                         ss->lastsample, &devc->trigger);
976
977                 if (trigger_offset > 0) {
978                         trig_count = trigger_offset * devc->samples_per_event;
979                         packet.type = SR_DF_LOGIC;
980                         logic.length = trig_count * logic.unitsize;
981                         sigma_session_send(sdi, &packet);
982                         send_ptr += trig_count * logic.unitsize;
983                         send_count -= trig_count;
984                 }
985
986                 /* Only send trigger if explicitly enabled. */
987                 if (devc->use_triggers)
988                         std_session_send_df_trigger(sdi);
989         }
990
991         /*
992          * Send the data after the trigger, or all of the received data
993          * if no trigger position applies.
994          */
995         if (send_count) {
996                 packet.type = SR_DF_LOGIC;
997                 logic.length = send_count * logic.unitsize;
998                 logic.data = send_ptr;
999                 sigma_session_send(sdi, &packet);
1000         }
1001
1002         ss->lastsample = sample;
1003 }
1004
1005 /*
1006  * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1007  * Each event is 20ns apart, and can contain multiple samples.
1008  *
1009  * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1010  * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1011  * For 50 MHz and below, events contain one sample for each channel,
1012  * spread 20 ns apart.
1013  */
1014 static int decode_chunk_ts(struct sigma_dram_line *dram_line,
1015                            uint16_t events_in_line,
1016                            uint32_t trigger_event,
1017                            struct sr_dev_inst *sdi)
1018 {
1019         struct sigma_dram_cluster *dram_cluster;
1020         struct dev_context *devc;
1021         unsigned int clusters_in_line;
1022         unsigned int events_in_cluster;
1023         unsigned int i;
1024         uint32_t trigger_cluster, triggered;
1025
1026         devc = sdi->priv;
1027         clusters_in_line = events_in_line;
1028         clusters_in_line += EVENTS_PER_CLUSTER - 1;
1029         clusters_in_line /= EVENTS_PER_CLUSTER;
1030         trigger_cluster = ~0;
1031         triggered = 0;
1032
1033         /* Check if trigger is in this chunk. */
1034         if (trigger_event < EVENTS_PER_ROW) {
1035                 if (devc->cur_samplerate <= SR_MHZ(50)) {
1036                         trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1037                                              trigger_event);
1038                 }
1039
1040                 /* Find in which cluster the trigger occurred. */
1041                 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1042         }
1043
1044         /* For each full DRAM cluster. */
1045         for (i = 0; i < clusters_in_line; i++) {
1046                 dram_cluster = &dram_line->cluster[i];
1047
1048                 /* The last cluster might not be full. */
1049                 if ((i == clusters_in_line - 1) &&
1050                     (events_in_line % EVENTS_PER_CLUSTER)) {
1051                         events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1052                 } else {
1053                         events_in_cluster = EVENTS_PER_CLUSTER;
1054                 }
1055
1056                 triggered = (i == trigger_cluster);
1057                 sigma_decode_dram_cluster(dram_cluster, events_in_cluster,
1058                                           triggered, sdi);
1059         }
1060
1061         return SR_OK;
1062 }
1063
1064 static int download_capture(struct sr_dev_inst *sdi)
1065 {
1066         const uint32_t chunks_per_read = 32;
1067
1068         struct dev_context *devc;
1069         struct sigma_dram_line *dram_line;
1070         int bufsz;
1071         uint32_t stoppos, triggerpos;
1072         uint8_t modestatus;
1073         uint32_t i;
1074         uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1075         uint32_t dl_first_line, dl_line;
1076         uint32_t dl_events_in_line;
1077         uint32_t trg_line, trg_event;
1078
1079         devc = sdi->priv;
1080         dl_events_in_line = EVENTS_PER_ROW;
1081
1082         sr_info("Downloading sample data.");
1083         devc->state.state = SIGMA_DOWNLOAD;
1084
1085         /*
1086          * Ask the hardware to stop data acquisition. Reception of the
1087          * FORCESTOP request makes the hardware "disable RLE" (store
1088          * clusters to DRAM regardless of whether pin state changes) and
1089          * raise the POSTTRIGGERED flag.
1090          */
1091         sigma_set_register(WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN, devc);
1092         do {
1093                 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1094                         sr_err("failed while waiting for RMR_POSTTRIGGERED bit");
1095                         return FALSE;
1096                 }
1097         } while (!(modestatus & RMR_POSTTRIGGERED));
1098
1099         /* Set SDRAM Read Enable. */
1100         sigma_set_register(WRITE_MODE, WMR_SDRAMREADEN, devc);
1101
1102         /* Get the current position. */
1103         sigma_read_pos(&stoppos, &triggerpos, devc);
1104
1105         /* Check if trigger has fired. */
1106         if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1107                 sr_err("failed to read READ_MODE register");
1108                 return FALSE;
1109         }
1110         trg_line = ~0;
1111         trg_event = ~0;
1112         if (modestatus & RMR_TRIGGERED) {
1113                 trg_line = triggerpos >> 9;
1114                 trg_event = triggerpos & 0x1ff;
1115         }
1116
1117         devc->sent_samples = 0;
1118
1119         /*
1120          * Determine how many "DRAM lines" of 1024 bytes each we need to
1121          * retrieve from the Sigma hardware, so that we have a complete
1122          * set of samples. Note that the last line need not contain 64
1123          * clusters, it might be partially filled only.
1124          *
1125          * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1126          * around. Since the status of the very next line is uncertain in
1127          * that case, we skip it and start reading from the next line.
1128          */
1129         dl_first_line = 0;
1130         dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1131         if (modestatus & RMR_ROUND) {
1132                 dl_first_line = dl_lines_total + 1;
1133                 dl_lines_total = ROW_COUNT - 2;
1134         }
1135         dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1136         if (!dram_line)
1137                 return FALSE;
1138         dl_lines_done = 0;
1139         while (dl_lines_total > dl_lines_done) {
1140                 /* We can download only up-to 32 DRAM lines in one go! */
1141                 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1142
1143                 dl_line = dl_first_line + dl_lines_done;
1144                 dl_line %= ROW_COUNT;
1145                 bufsz = sigma_read_dram(dl_line, dl_lines_curr,
1146                                         (uint8_t *)dram_line, devc);
1147                 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1148                 (void)bufsz;
1149
1150                 /* This is the first DRAM line, so find the initial timestamp. */
1151                 if (dl_lines_done == 0) {
1152                         devc->state.lastts =
1153                                 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1154                         devc->state.lastsample = 0;
1155                 }
1156
1157                 for (i = 0; i < dl_lines_curr; i++) {
1158                         uint32_t trigger_event = ~0;
1159                         /* The last "DRAM line" can be only partially full. */
1160                         if (dl_lines_done + i == dl_lines_total - 1)
1161                                 dl_events_in_line = stoppos & 0x1ff;
1162
1163                         /* Test if the trigger happened on this line. */
1164                         if (dl_lines_done + i == trg_line)
1165                                 trigger_event = trg_event;
1166
1167                         decode_chunk_ts(dram_line + i, dl_events_in_line,
1168                                         trigger_event, sdi);
1169                 }
1170
1171                 dl_lines_done += dl_lines_curr;
1172         }
1173         g_free(dram_line);
1174
1175         std_session_send_df_end(sdi);
1176
1177         devc->state.state = SIGMA_IDLE;
1178         sr_dev_acquisition_stop(sdi);
1179
1180         return TRUE;
1181 }
1182
1183 /*
1184  * Periodically check the Sigma status when in CAPTURE mode. This routine
1185  * checks whether the configured sample count or sample time have passed,
1186  * and will stop acquisition and download the acquired samples.
1187  */
1188 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1189 {
1190         struct dev_context *devc;
1191         uint64_t running_msec;
1192         uint64_t current_time;
1193
1194         devc = sdi->priv;
1195
1196         /*
1197          * Check if the selected sampling duration passed. Sample count
1198          * limits are covered by this enforced timeout as well.
1199          */
1200         current_time = g_get_monotonic_time();
1201         running_msec = (current_time - devc->start_time) / 1000;
1202         if (running_msec >= devc->limit_msec)
1203                 return download_capture(sdi);
1204
1205         return TRUE;
1206 }
1207
1208 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1209 {
1210         struct sr_dev_inst *sdi;
1211         struct dev_context *devc;
1212
1213         (void)fd;
1214         (void)revents;
1215
1216         sdi = cb_data;
1217         devc = sdi->priv;
1218
1219         if (devc->state.state == SIGMA_IDLE)
1220                 return TRUE;
1221
1222         /*
1223          * When the application has requested to stop the acquisition,
1224          * then immediately start downloading sample data. Otherwise
1225          * keep checking configured limits which will terminate the
1226          * acquisition and initiate download.
1227          */
1228         if (devc->state.state == SIGMA_STOPPING)
1229                 return download_capture(sdi);
1230         if (devc->state.state == SIGMA_CAPTURE)
1231                 return sigma_capture_mode(sdi);
1232
1233         return TRUE;
1234 }
1235
1236 /* Build a LUT entry used by the trigger functions. */
1237 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1238 {
1239         int i, j, k, bit;
1240
1241         /* For each quad channel. */
1242         for (i = 0; i < 4; i++) {
1243                 entry[i] = 0xffff;
1244
1245                 /* For each bit in LUT. */
1246                 for (j = 0; j < 16; j++)
1247
1248                         /* For each channel in quad. */
1249                         for (k = 0; k < 4; k++) {
1250                                 bit = 1 << (i * 4 + k);
1251
1252                                 /* Set bit in entry */
1253                                 if ((mask & bit) && ((!(value & bit)) !=
1254                                                         (!(j & (1 << k)))))
1255                                         entry[i] &= ~(1 << j);
1256                         }
1257         }
1258 }
1259
1260 /* Add a logical function to LUT mask. */
1261 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1262                                  int index, int neg, uint16_t *mask)
1263 {
1264         int i, j;
1265         int x[2][2], tmp, a, b, aset, bset, rset;
1266
1267         memset(x, 0, 4 * sizeof(int));
1268
1269         /* Trigger detect condition. */
1270         switch (oper) {
1271         case OP_LEVEL:
1272                 x[0][1] = 1;
1273                 x[1][1] = 1;
1274                 break;
1275         case OP_NOT:
1276                 x[0][0] = 1;
1277                 x[1][0] = 1;
1278                 break;
1279         case OP_RISE:
1280                 x[0][1] = 1;
1281                 break;
1282         case OP_FALL:
1283                 x[1][0] = 1;
1284                 break;
1285         case OP_RISEFALL:
1286                 x[0][1] = 1;
1287                 x[1][0] = 1;
1288                 break;
1289         case OP_NOTRISE:
1290                 x[1][1] = 1;
1291                 x[0][0] = 1;
1292                 x[1][0] = 1;
1293                 break;
1294         case OP_NOTFALL:
1295                 x[1][1] = 1;
1296                 x[0][0] = 1;
1297                 x[0][1] = 1;
1298                 break;
1299         case OP_NOTRISEFALL:
1300                 x[1][1] = 1;
1301                 x[0][0] = 1;
1302                 break;
1303         }
1304
1305         /* Transpose if neg is set. */
1306         if (neg) {
1307                 for (i = 0; i < 2; i++) {
1308                         for (j = 0; j < 2; j++) {
1309                                 tmp = x[i][j];
1310                                 x[i][j] = x[1 - i][1 - j];
1311                                 x[1 - i][1 - j] = tmp;
1312                         }
1313                 }
1314         }
1315
1316         /* Update mask with function. */
1317         for (i = 0; i < 16; i++) {
1318                 a = (i >> (2 * index + 0)) & 1;
1319                 b = (i >> (2 * index + 1)) & 1;
1320
1321                 aset = (*mask >> i) & 1;
1322                 bset = x[b][a];
1323
1324                 rset = 0;
1325                 if (func == FUNC_AND || func == FUNC_NAND)
1326                         rset = aset & bset;
1327                 else if (func == FUNC_OR || func == FUNC_NOR)
1328                         rset = aset | bset;
1329                 else if (func == FUNC_XOR || func == FUNC_NXOR)
1330                         rset = aset ^ bset;
1331
1332                 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1333                         rset = !rset;
1334
1335                 *mask &= ~(1 << i);
1336
1337                 if (rset)
1338                         *mask |= 1 << i;
1339         }
1340 }
1341
1342 /*
1343  * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1344  * simple pin change and state triggers. Only two transitions (rise/fall) can be
1345  * set at any time, but a full mask and value can be set (0/1).
1346  */
1347 SR_PRIV int sigma_build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1348 {
1349         int i,j;
1350         uint16_t masks[2] = { 0, 0 };
1351
1352         memset(lut, 0, sizeof(struct triggerlut));
1353
1354         /* Constant for simple triggers. */
1355         lut->m4 = 0xa000;
1356
1357         /* Value/mask trigger support. */
1358         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1359                         lut->m2d);
1360
1361         /* Rise/fall trigger support. */
1362         for (i = 0, j = 0; i < 16; i++) {
1363                 if (devc->trigger.risingmask & (1 << i) ||
1364                     devc->trigger.fallingmask & (1 << i))
1365                         masks[j++] = 1 << i;
1366         }
1367
1368         build_lut_entry(masks[0], masks[0], lut->m0d);
1369         build_lut_entry(masks[1], masks[1], lut->m1d);
1370
1371         /* Add glue logic */
1372         if (masks[0] || masks[1]) {
1373                 /* Transition trigger. */
1374                 if (masks[0] & devc->trigger.risingmask)
1375                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1376                 if (masks[0] & devc->trigger.fallingmask)
1377                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1378                 if (masks[1] & devc->trigger.risingmask)
1379                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1380                 if (masks[1] & devc->trigger.fallingmask)
1381                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1382         } else {
1383                 /* Only value/mask trigger. */
1384                 lut->m3 = 0xffff;
1385         }
1386
1387         /* Triggertype: event. */
1388         lut->params.selres = 3;
1389
1390         return SR_OK;
1391 }