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