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