]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/protocol.c
asix-sigma: Nit, remove redundant USB VID/PID declaration
[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 sigma_firmware_files[][24] = {
51         /* 50 MHz, supports 8 bit fractions */
52         "asix-sigma-50.fw",
53         /* 100 MHz */
54         "asix-sigma-100.fw",
55         /* 200 MHz */
56         "asix-sigma-200.fw",
57         /* Synchronous clock from pin */
58         "asix-sigma-50sync.fw",
59         /* Frequency counter */
60         "asix-sigma-phasor.fw",
61 };
62
63 static int sigma_read(void *buf, size_t size, struct dev_context *devc)
64 {
65         int ret;
66
67         ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
68         if (ret < 0) {
69                 sr_err("ftdi_read_data failed: %s",
70                        ftdi_get_error_string(&devc->ftdic));
71         }
72
73         return ret;
74 }
75
76 static int sigma_write(void *buf, size_t size, struct dev_context *devc)
77 {
78         int ret;
79
80         ret = ftdi_write_data(&devc->ftdic, (unsigned char *)buf, size);
81         if (ret < 0) {
82                 sr_err("ftdi_write_data failed: %s",
83                        ftdi_get_error_string(&devc->ftdic));
84         } else if ((size_t) ret != size) {
85                 sr_err("ftdi_write_data did not complete write.");
86         }
87
88         return ret;
89 }
90
91 /*
92  * NOTE: We chose the buffer size to be large enough to hold any write to the
93  * device. We still print a message just in case.
94  */
95 SR_PRIV int sigma_write_register(uint8_t reg, uint8_t *data, size_t len,
96                                  struct dev_context *devc)
97 {
98         size_t i;
99         uint8_t buf[80];
100         int idx = 0;
101
102         if ((2 * len + 2) > sizeof(buf)) {
103                 sr_err("Attempted to write %zu bytes, but buffer is too small.",
104                        len);
105                 return SR_ERR_BUG;
106         }
107
108         buf[idx++] = REG_ADDR_LOW | (reg & 0xf);
109         buf[idx++] = REG_ADDR_HIGH | (reg >> 4);
110
111         for (i = 0; i < len; i++) {
112                 buf[idx++] = REG_DATA_LOW | (data[i] & 0xf);
113                 buf[idx++] = REG_DATA_HIGH_WRITE | (data[i] >> 4);
114         }
115
116         return sigma_write(buf, idx, devc);
117 }
118
119 SR_PRIV int sigma_set_register(uint8_t reg, uint8_t value, struct dev_context *devc)
120 {
121         return sigma_write_register(reg, &value, 1, devc);
122 }
123
124 static int sigma_read_register(uint8_t reg, uint8_t *data, size_t len,
125                                struct dev_context *devc)
126 {
127         uint8_t buf[3];
128
129         buf[0] = REG_ADDR_LOW | (reg & 0xf);
130         buf[1] = REG_ADDR_HIGH | (reg >> 4);
131         buf[2] = REG_READ_ADDR;
132
133         sigma_write(buf, sizeof(buf), devc);
134
135         return sigma_read(data, len, devc);
136 }
137
138 static uint8_t sigma_get_register(uint8_t reg, struct dev_context *devc)
139 {
140         uint8_t value;
141
142         if (1 != sigma_read_register(reg, &value, 1, devc)) {
143                 sr_err("sigma_get_register: 1 byte expected");
144                 return 0;
145         }
146
147         return value;
148 }
149
150 static int sigma_read_pos(uint32_t *stoppos, uint32_t *triggerpos,
151                           struct dev_context *devc)
152 {
153         uint8_t buf[] = {
154                 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
155
156                 REG_READ_ADDR | NEXT_REG,
157                 REG_READ_ADDR | NEXT_REG,
158                 REG_READ_ADDR | NEXT_REG,
159                 REG_READ_ADDR | NEXT_REG,
160                 REG_READ_ADDR | NEXT_REG,
161                 REG_READ_ADDR | NEXT_REG,
162         };
163         uint8_t result[6];
164
165         sigma_write(buf, sizeof(buf), devc);
166
167         sigma_read(result, sizeof(result), devc);
168
169         *triggerpos = result[0] | (result[1] << 8) | (result[2] << 16);
170         *stoppos = result[3] | (result[4] << 8) | (result[5] << 16);
171
172         /* Not really sure why this must be done, but according to spec. */
173         if ((--*stoppos & 0x1ff) == 0x1ff)
174                 *stoppos -= 64;
175
176         if ((*--triggerpos & 0x1ff) == 0x1ff)
177                 *triggerpos -= 64;
178
179         return 1;
180 }
181
182 static int sigma_read_dram(uint16_t startchunk, size_t numchunks,
183                            uint8_t *data, struct dev_context *devc)
184 {
185         size_t i;
186         uint8_t buf[4096];
187         int idx = 0;
188
189         /* Send the startchunk. Index start with 1. */
190         buf[0] = startchunk >> 8;
191         buf[1] = startchunk & 0xff;
192         sigma_write_register(WRITE_MEMROW, buf, 2, devc);
193
194         /* Read the DRAM. */
195         buf[idx++] = REG_DRAM_BLOCK;
196         buf[idx++] = REG_DRAM_WAIT_ACK;
197
198         for (i = 0; i < numchunks; i++) {
199                 /* Alternate bit to copy from DRAM to cache. */
200                 if (i != (numchunks - 1))
201                         buf[idx++] = REG_DRAM_BLOCK | (((i + 1) % 2) << 4);
202
203                 buf[idx++] = REG_DRAM_BLOCK_DATA | ((i % 2) << 4);
204
205                 if (i != (numchunks - 1))
206                         buf[idx++] = REG_DRAM_WAIT_ACK;
207         }
208
209         sigma_write(buf, idx, devc);
210
211         return sigma_read(data, numchunks * CHUNK_SIZE, devc);
212 }
213
214 /* Upload trigger look-up tables to Sigma. */
215 SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *devc)
216 {
217         int i;
218         uint8_t tmp[2];
219         uint16_t bit;
220
221         /* Transpose the table and send to Sigma. */
222         for (i = 0; i < 16; i++) {
223                 bit = 1 << i;
224
225                 tmp[0] = tmp[1] = 0;
226
227                 if (lut->m2d[0] & bit)
228                         tmp[0] |= 0x01;
229                 if (lut->m2d[1] & bit)
230                         tmp[0] |= 0x02;
231                 if (lut->m2d[2] & bit)
232                         tmp[0] |= 0x04;
233                 if (lut->m2d[3] & bit)
234                         tmp[0] |= 0x08;
235
236                 if (lut->m3 & bit)
237                         tmp[0] |= 0x10;
238                 if (lut->m3s & bit)
239                         tmp[0] |= 0x20;
240                 if (lut->m4 & bit)
241                         tmp[0] |= 0x40;
242
243                 if (lut->m0d[0] & bit)
244                         tmp[1] |= 0x01;
245                 if (lut->m0d[1] & bit)
246                         tmp[1] |= 0x02;
247                 if (lut->m0d[2] & bit)
248                         tmp[1] |= 0x04;
249                 if (lut->m0d[3] & bit)
250                         tmp[1] |= 0x08;
251
252                 if (lut->m1d[0] & bit)
253                         tmp[1] |= 0x10;
254                 if (lut->m1d[1] & bit)
255                         tmp[1] |= 0x20;
256                 if (lut->m1d[2] & bit)
257                         tmp[1] |= 0x40;
258                 if (lut->m1d[3] & bit)
259                         tmp[1] |= 0x80;
260
261                 sigma_write_register(WRITE_TRIGGER_SELECT0, tmp, sizeof(tmp),
262                                      devc);
263                 sigma_set_register(WRITE_TRIGGER_SELECT1, 0x30 | i, devc);
264         }
265
266         /* Send the parameters */
267         sigma_write_register(WRITE_TRIGGER_SELECT0, (uint8_t *) &lut->params,
268                              sizeof(lut->params), devc);
269
270         return SR_OK;
271 }
272
273 SR_PRIV void sigma_clear_helper(void *priv)
274 {
275         struct dev_context *devc;
276
277         devc = priv;
278
279         ftdi_deinit(&devc->ftdic);
280 }
281
282 /*
283  * Configure the FPGA for bitbang mode.
284  * This sequence is documented in section 2. of the ASIX Sigma programming
285  * manual. This sequence is necessary to configure the FPGA in the Sigma
286  * into Bitbang mode, in which it can be programmed with the firmware.
287  */
288 static int sigma_fpga_init_bitbang(struct dev_context *devc)
289 {
290         uint8_t suicide[] = {
291                 0x84, 0x84, 0x88, 0x84, 0x88, 0x84, 0x88, 0x84,
292         };
293         uint8_t init_array[] = {
294                 0x01, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01,
295                 0x01, 0x01,
296         };
297         int i, ret, timeout = (10 * 1000);
298         uint8_t data;
299
300         /* Section 2. part 1), do the FPGA suicide. */
301         sigma_write(suicide, sizeof(suicide), devc);
302         sigma_write(suicide, sizeof(suicide), devc);
303         sigma_write(suicide, sizeof(suicide), devc);
304         sigma_write(suicide, sizeof(suicide), devc);
305
306         /* Section 2. part 2), do pulse on D1. */
307         sigma_write(init_array, sizeof(init_array), devc);
308         ftdi_usb_purge_buffers(&devc->ftdic);
309
310         /* Wait until the FPGA asserts D6/INIT_B. */
311         for (i = 0; i < timeout; i++) {
312                 ret = sigma_read(&data, 1, devc);
313                 if (ret < 0)
314                         return ret;
315                 /* Test if pin D6 got asserted. */
316                 if (data & (1 << 5))
317                         return 0;
318                 /* The D6 was not asserted yet, wait a bit. */
319                 g_usleep(10 * 1000);
320         }
321
322         return SR_ERR_TIMEOUT;
323 }
324
325 /*
326  * Configure the FPGA for logic-analyzer mode.
327  */
328 static int sigma_fpga_init_la(struct dev_context *devc)
329 {
330         /* Initialize the logic analyzer mode. */
331         uint8_t logic_mode_start[] = {
332                 REG_ADDR_LOW  | (READ_ID & 0xf),
333                 REG_ADDR_HIGH | (READ_ID >> 8),
334                 REG_READ_ADDR,  /* Read ID register. */
335
336                 REG_ADDR_LOW | (WRITE_TEST & 0xf),
337                 REG_DATA_LOW | 0x5,
338                 REG_DATA_HIGH_WRITE | 0x5,
339                 REG_READ_ADDR,  /* Read scratch register. */
340
341                 REG_DATA_LOW | 0xa,
342                 REG_DATA_HIGH_WRITE | 0xa,
343                 REG_READ_ADDR,  /* Read scratch register. */
344
345                 REG_ADDR_LOW | (WRITE_MODE & 0xf),
346                 REG_DATA_LOW | 0x0,
347                 REG_DATA_HIGH_WRITE | 0x8,
348         };
349
350         uint8_t result[3];
351         int ret;
352
353         /* Initialize the logic analyzer mode. */
354         sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
355
356         /* Expect a 3 byte reply since we issued three READ requests. */
357         ret = sigma_read(result, 3, devc);
358         if (ret != 3)
359                 goto err;
360
361         if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
362                 goto err;
363
364         return SR_OK;
365 err:
366         sr_err("Configuration failed. Invalid reply received.");
367         return SR_ERR;
368 }
369
370 /*
371  * Read the firmware from a file and transform it into a series of bitbang
372  * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
373  * by the caller of this function.
374  */
375 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
376                               uint8_t **bb_cmd, gsize *bb_cmd_size)
377 {
378         size_t i, file_size, bb_size;
379         char *firmware;
380         uint8_t *bb_stream, *bbs;
381         uint32_t imm;
382         int bit, v;
383         int ret = SR_OK;
384
385         /* Retrieve the on-disk firmware file content. */
386         firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE,
387                         name, &file_size, 256 * 1024);
388         if (!firmware)
389                 return SR_ERR;
390
391         /* Unscramble the file content (XOR with "random" sequence). */
392         imm = 0x3f6df2ab;
393         for (i = 0; i < file_size; i++) {
394                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
395                 firmware[i] ^= imm & 0xff;
396         }
397
398         /*
399          * Generate a sequence of bitbang samples. With two samples per
400          * FPGA configuration bit, providing the level for the DIN signal
401          * as well as two edges for CCLK. See Xilinx UG332 for details
402          * ("slave serial" mode).
403          *
404          * Note that CCLK is inverted in hardware. That's why the
405          * respective bit is first set and then cleared in the bitbang
406          * sample sets. So that the DIN level will be stable when the
407          * data gets sampled at the rising CCLK edge, and the signals'
408          * setup time constraint will be met.
409          *
410          * The caller will put the FPGA into download mode, will send
411          * the bitbang samples, and release the allocated memory.
412          */
413         bb_size = file_size * 8 * 2;
414         bb_stream = (uint8_t *)g_try_malloc(bb_size);
415         if (!bb_stream) {
416                 sr_err("%s: Failed to allocate bitbang stream", __func__);
417                 ret = SR_ERR_MALLOC;
418                 goto exit;
419         }
420         bbs = bb_stream;
421         for (i = 0; i < file_size; i++) {
422                 for (bit = 7; bit >= 0; bit--) {
423                         v = (firmware[i] & (1 << bit)) ? 0x40 : 0x00;
424                         *bbs++ = v | 0x01;
425                         *bbs++ = v;
426                 }
427         }
428
429         /* The transformation completed successfully, return the result. */
430         *bb_cmd = bb_stream;
431         *bb_cmd_size = bb_size;
432
433 exit:
434         g_free(firmware);
435         return ret;
436 }
437
438 static int upload_firmware(struct sr_context *ctx,
439                 int firmware_idx, struct dev_context *devc)
440 {
441         int ret;
442         unsigned char *buf;
443         unsigned char pins;
444         size_t buf_size;
445         const char *firmware = sigma_firmware_files[firmware_idx];
446         struct ftdi_context *ftdic = &devc->ftdic;
447
448         /* Make sure it's an ASIX SIGMA. */
449         ret = ftdi_usb_open_desc(ftdic, USB_VENDOR, USB_PRODUCT,
450                                  USB_DESCRIPTION, NULL);
451         if (ret < 0) {
452                 sr_err("ftdi_usb_open failed: %s",
453                        ftdi_get_error_string(ftdic));
454                 return 0;
455         }
456
457         ret = ftdi_set_bitmode(ftdic, 0xdf, BITMODE_BITBANG);
458         if (ret < 0) {
459                 sr_err("ftdi_set_bitmode failed: %s",
460                        ftdi_get_error_string(ftdic));
461                 return 0;
462         }
463
464         /* Four times the speed of sigmalogan - Works well. */
465         ret = ftdi_set_baudrate(ftdic, 750 * 1000);
466         if (ret < 0) {
467                 sr_err("ftdi_set_baudrate failed: %s",
468                        ftdi_get_error_string(ftdic));
469                 return 0;
470         }
471
472         /* Initialize the FPGA for firmware upload. */
473         ret = sigma_fpga_init_bitbang(devc);
474         if (ret)
475                 return ret;
476
477         /* Prepare firmware. */
478         ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
479         if (ret != SR_OK) {
480                 sr_err("An error occurred while reading the firmware: %s",
481                        firmware);
482                 return ret;
483         }
484
485         /* Upload firmware. */
486         sr_info("Uploading firmware file '%s'.", firmware);
487         sigma_write(buf, buf_size, devc);
488
489         g_free(buf);
490
491         ret = ftdi_set_bitmode(ftdic, 0x00, BITMODE_RESET);
492         if (ret < 0) {
493                 sr_err("ftdi_set_bitmode failed: %s",
494                        ftdi_get_error_string(ftdic));
495                 return SR_ERR;
496         }
497
498         ftdi_usb_purge_buffers(ftdic);
499
500         /* Discard garbage. */
501         while (sigma_read(&pins, 1, devc) == 1)
502                 ;
503
504         /* Initialize the FPGA for logic-analyzer mode. */
505         ret = sigma_fpga_init_la(devc);
506         if (ret != SR_OK)
507                 return ret;
508
509         devc->cur_firmware = firmware_idx;
510
511         sr_info("Firmware uploaded.");
512
513         return SR_OK;
514 }
515
516 /*
517  * Sigma doesn't support limiting the number of samples, so we have to
518  * translate the number and the samplerate to an elapsed time.
519  *
520  * In addition we need to ensure that the last data cluster has passed
521  * the hardware pipeline, and became available to the PC side. With RLE
522  * compression up to 327ms could pass before another cluster accumulates
523  * at 200kHz samplerate when input pins don't change.
524  */
525 SR_PRIV uint64_t sigma_limit_samples_to_msec(const struct dev_context *devc,
526                                              uint64_t limit_samples)
527 {
528         uint64_t limit_msec;
529         uint64_t worst_cluster_time_ms;
530
531         limit_msec = limit_samples * 1000 / devc->cur_samplerate;
532         worst_cluster_time_ms = 65536 * 1000 / devc->cur_samplerate;
533         /*
534          * One cluster time is not enough to flush pipeline when sampling
535          * grounded pins with 1 sample limit at 200kHz. Hence the 2* fix.
536          */
537         return limit_msec + 2 * worst_cluster_time_ms;
538 }
539
540 SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
541 {
542         struct dev_context *devc;
543         struct drv_context *drvc;
544         size_t i;
545         int ret;
546
547         devc = sdi->priv;
548         drvc = sdi->driver->context;
549         ret = SR_OK;
550
551         /* Reject rates that are not in the list of supported rates. */
552         for (i = 0; i < samplerates_count; i++) {
553                 if (samplerates[i] == samplerate)
554                         break;
555         }
556         if (i >= samplerates_count || samplerates[i] == 0)
557                 return SR_ERR_SAMPLERATE;
558
559         /*
560          * Depending on the samplerates of 200/100/50- MHz, specific
561          * firmware is required and higher rates might limit the set
562          * of available channels.
563          */
564         if (samplerate <= SR_MHZ(50)) {
565                 ret = upload_firmware(drvc->sr_ctx, 0, devc);
566                 devc->num_channels = 16;
567         } else if (samplerate == SR_MHZ(100)) {
568                 ret = upload_firmware(drvc->sr_ctx, 1, devc);
569                 devc->num_channels = 8;
570         } else if (samplerate == SR_MHZ(200)) {
571                 ret = upload_firmware(drvc->sr_ctx, 2, devc);
572                 devc->num_channels = 4;
573         }
574
575         /*
576          * Derive the sample period from the sample rate as well as the
577          * number of samples that the device will communicate within
578          * an "event" (memory organization internal to the device).
579          */
580         if (ret == SR_OK) {
581                 devc->cur_samplerate = samplerate;
582                 devc->period_ps = 1000000000000ULL / samplerate;
583                 devc->samples_per_event = 16 / devc->num_channels;
584                 devc->state.state = SIGMA_IDLE;
585         }
586
587         /*
588          * Support for "limit_samples" is implemented by stopping
589          * acquisition after a corresponding period of time.
590          * Re-calculate that period of time, in case the limit is
591          * set first and the samplerate gets (re-)configured later.
592          */
593         if (ret == SR_OK && devc->limit_samples) {
594                 uint64_t msecs;
595                 msecs = sigma_limit_samples_to_msec(devc, devc->limit_samples);
596                 devc->limit_msec = msecs;
597         }
598
599         return ret;
600 }
601
602 /*
603  * In 100 and 200 MHz mode, only a single pin rising/falling can be
604  * set as trigger. In other modes, two rising/falling triggers can be set,
605  * in addition to value/mask trigger for any number of channels.
606  *
607  * The Sigma supports complex triggers using boolean expressions, but this
608  * has not been implemented yet.
609  */
610 SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
611 {
612         struct dev_context *devc;
613         struct sr_trigger *trigger;
614         struct sr_trigger_stage *stage;
615         struct sr_trigger_match *match;
616         const GSList *l, *m;
617         int channelbit, trigger_set;
618
619         devc = sdi->priv;
620         memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
621         if (!(trigger = sr_session_trigger_get(sdi->session)))
622                 return SR_OK;
623
624         trigger_set = 0;
625         for (l = trigger->stages; l; l = l->next) {
626                 stage = l->data;
627                 for (m = stage->matches; m; m = m->next) {
628                         match = m->data;
629                         if (!match->channel->enabled)
630                                 /* Ignore disabled channels with a trigger. */
631                                 continue;
632                         channelbit = 1 << (match->channel->index);
633                         if (devc->cur_samplerate >= SR_MHZ(100)) {
634                                 /* Fast trigger support. */
635                                 if (trigger_set) {
636                                         sr_err("Only a single pin trigger is "
637                                                         "supported in 100 and 200MHz mode.");
638                                         return SR_ERR;
639                                 }
640                                 if (match->match == SR_TRIGGER_FALLING)
641                                         devc->trigger.fallingmask |= channelbit;
642                                 else if (match->match == SR_TRIGGER_RISING)
643                                         devc->trigger.risingmask |= channelbit;
644                                 else {
645                                         sr_err("Only rising/falling trigger is "
646                                                         "supported in 100 and 200MHz mode.");
647                                         return SR_ERR;
648                                 }
649
650                                 trigger_set++;
651                         } else {
652                                 /* Simple trigger support (event). */
653                                 if (match->match == SR_TRIGGER_ONE) {
654                                         devc->trigger.simplevalue |= channelbit;
655                                         devc->trigger.simplemask |= channelbit;
656                                 }
657                                 else if (match->match == SR_TRIGGER_ZERO) {
658                                         devc->trigger.simplevalue &= ~channelbit;
659                                         devc->trigger.simplemask |= channelbit;
660                                 }
661                                 else if (match->match == SR_TRIGGER_FALLING) {
662                                         devc->trigger.fallingmask |= channelbit;
663                                         trigger_set++;
664                                 }
665                                 else if (match->match == SR_TRIGGER_RISING) {
666                                         devc->trigger.risingmask |= channelbit;
667                                         trigger_set++;
668                                 }
669
670                                 /*
671                                  * Actually, Sigma supports 2 rising/falling triggers,
672                                  * but they are ORed and the current trigger syntax
673                                  * does not permit ORed triggers.
674                                  */
675                                 if (trigger_set > 1) {
676                                         sr_err("Only 1 rising/falling trigger "
677                                                    "is supported.");
678                                         return SR_ERR;
679                                 }
680                         }
681                 }
682         }
683
684         return SR_OK;
685 }
686
687
688 /* Software trigger to determine exact trigger position. */
689 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
690                               struct sigma_trigger *t)
691 {
692         int i;
693         uint16_t sample = 0;
694
695         for (i = 0; i < 8; i++) {
696                 if (i > 0)
697                         last_sample = sample;
698                 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
699
700                 /* Simple triggers. */
701                 if ((sample & t->simplemask) != t->simplevalue)
702                         continue;
703
704                 /* Rising edge. */
705                 if (((last_sample & t->risingmask) != 0) ||
706                     ((sample & t->risingmask) != t->risingmask))
707                         continue;
708
709                 /* Falling edge. */
710                 if ((last_sample & t->fallingmask) != t->fallingmask ||
711                     (sample & t->fallingmask) != 0)
712                         continue;
713
714                 break;
715         }
716
717         /* If we did not match, return original trigger pos. */
718         return i & 0x7;
719 }
720
721 /*
722  * Return the timestamp of "DRAM cluster".
723  */
724 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
725 {
726         return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
727 }
728
729 static void sigma_decode_dram_cluster(struct sigma_dram_cluster *dram_cluster,
730                                       unsigned int events_in_cluster,
731                                       unsigned int triggered,
732                                       struct sr_dev_inst *sdi)
733 {
734         struct dev_context *devc = sdi->priv;
735         struct sigma_state *ss = &devc->state;
736         struct sr_datafeed_packet packet;
737         struct sr_datafeed_logic logic;
738         uint16_t tsdiff, ts;
739         uint8_t samples[2048];
740         unsigned int i;
741
742         ts = sigma_dram_cluster_ts(dram_cluster);
743         tsdiff = ts - ss->lastts;
744         ss->lastts = ts + EVENTS_PER_CLUSTER;
745
746         packet.type = SR_DF_LOGIC;
747         packet.payload = &logic;
748         logic.unitsize = 2;
749         logic.data = samples;
750
751         /*
752          * First of all, send Sigrok a copy of the last sample from
753          * previous cluster as many times as needed to make up for
754          * the differential characteristics of data we get from the
755          * Sigma. Sigrok needs one sample of data per period.
756          *
757          * One DRAM cluster contains a timestamp and seven samples,
758          * the units of timestamp are "devc->period_ps" , the first
759          * sample in the cluster happens at the time of the timestamp
760          * and the remaining samples happen at timestamp +1...+6 .
761          */
762         for (ts = 0; ts < tsdiff; ts++) {
763                 i = ts % 1024;
764                 samples[2 * i + 0] = ss->lastsample & 0xff;
765                 samples[2 * i + 1] = ss->lastsample >> 8;
766
767                 /*
768                  * If we have 1024 samples ready or we're at the
769                  * end of submitting the padding samples, submit
770                  * the packet to Sigrok.
771                  */
772                 if ((i == 1023) || (ts == tsdiff - 1)) {
773                         logic.length = (i + 1) * logic.unitsize;
774                         sr_session_send(sdi, &packet);
775                 }
776         }
777
778         /*
779          * Parse the samples in current cluster and prepare them
780          * to be submitted to Sigrok.
781          */
782         for (i = 0; i < events_in_cluster; i++) {
783                 samples[2 * i + 1] = dram_cluster->samples[i].sample_lo;
784                 samples[2 * i + 0] = dram_cluster->samples[i].sample_hi;
785         }
786
787         /* Send data up to trigger point (if triggered). */
788         int trigger_offset = 0;
789         if (triggered) {
790                 /*
791                  * Trigger is not always accurate to sample because of
792                  * pipeline delay. However, it always triggers before
793                  * the actual event. We therefore look at the next
794                  * samples to pinpoint the exact position of the trigger.
795                  */
796                 trigger_offset = get_trigger_offset(samples,
797                                         ss->lastsample, &devc->trigger);
798
799                 if (trigger_offset > 0) {
800                         packet.type = SR_DF_LOGIC;
801                         logic.length = trigger_offset * logic.unitsize;
802                         sr_session_send(sdi, &packet);
803                         events_in_cluster -= trigger_offset;
804                 }
805
806                 /* Only send trigger if explicitly enabled. */
807                 if (devc->use_triggers) {
808                         packet.type = SR_DF_TRIGGER;
809                         sr_session_send(sdi, &packet);
810                 }
811         }
812
813         if (events_in_cluster > 0) {
814                 packet.type = SR_DF_LOGIC;
815                 logic.length = events_in_cluster * logic.unitsize;
816                 logic.data = samples + (trigger_offset * logic.unitsize);
817                 sr_session_send(sdi, &packet);
818         }
819
820         ss->lastsample =
821                 samples[2 * (events_in_cluster - 1) + 0] |
822                 (samples[2 * (events_in_cluster - 1) + 1] << 8);
823
824 }
825
826 /*
827  * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
828  * Each event is 20ns apart, and can contain multiple samples.
829  *
830  * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
831  * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
832  * For 50 MHz and below, events contain one sample for each channel,
833  * spread 20 ns apart.
834  */
835 static int decode_chunk_ts(struct sigma_dram_line *dram_line,
836                            uint16_t events_in_line,
837                            uint32_t trigger_event,
838                            struct sr_dev_inst *sdi)
839 {
840         struct sigma_dram_cluster *dram_cluster;
841         struct dev_context *devc = sdi->priv;
842         unsigned int clusters_in_line =
843                 (events_in_line + (EVENTS_PER_CLUSTER - 1)) / EVENTS_PER_CLUSTER;
844         unsigned int events_in_cluster;
845         unsigned int i;
846         uint32_t trigger_cluster = ~0, triggered = 0;
847
848         /* Check if trigger is in this chunk. */
849         if (trigger_event < (64 * 7)) {
850                 if (devc->cur_samplerate <= SR_MHZ(50)) {
851                         trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
852                                              trigger_event);
853                 }
854
855                 /* Find in which cluster the trigger occurred. */
856                 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
857         }
858
859         /* For each full DRAM cluster. */
860         for (i = 0; i < clusters_in_line; i++) {
861                 dram_cluster = &dram_line->cluster[i];
862
863                 /* The last cluster might not be full. */
864                 if ((i == clusters_in_line - 1) &&
865                     (events_in_line % EVENTS_PER_CLUSTER)) {
866                         events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
867                 } else {
868                         events_in_cluster = EVENTS_PER_CLUSTER;
869                 }
870
871                 triggered = (i == trigger_cluster);
872                 sigma_decode_dram_cluster(dram_cluster, events_in_cluster,
873                                           triggered, sdi);
874         }
875
876         return SR_OK;
877 }
878
879 static int download_capture(struct sr_dev_inst *sdi)
880 {
881         struct dev_context *devc = sdi->priv;
882         const uint32_t chunks_per_read = 32;
883         struct sigma_dram_line *dram_line;
884         int bufsz;
885         uint32_t stoppos, triggerpos;
886         uint8_t modestatus;
887
888         uint32_t i;
889         uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
890         uint32_t dl_events_in_line = 64 * 7;
891         uint32_t trg_line = ~0, trg_event = ~0;
892
893         dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
894         if (!dram_line)
895                 return FALSE;
896
897         sr_info("Downloading sample data.");
898
899         /* Stop acquisition. */
900         sigma_set_register(WRITE_MODE, 0x11, devc);
901
902         /* Set SDRAM Read Enable. */
903         sigma_set_register(WRITE_MODE, 0x02, devc);
904
905         /* Get the current position. */
906         sigma_read_pos(&stoppos, &triggerpos, devc);
907
908         /* Check if trigger has fired. */
909         modestatus = sigma_get_register(READ_MODE, devc);
910         if (modestatus & 0x20) {
911                 trg_line = triggerpos >> 9;
912                 trg_event = triggerpos & 0x1ff;
913         }
914
915         /*
916          * Determine how many 1024b "DRAM lines" do we need to read from the
917          * Sigma so we have a complete set of samples. Note that the last
918          * line can be only partial, containing less than 64 clusters.
919          */
920         dl_lines_total = (stoppos >> 9) + 1;
921
922         dl_lines_done = 0;
923
924         while (dl_lines_total > dl_lines_done) {
925                 /* We can download only up-to 32 DRAM lines in one go! */
926                 dl_lines_curr = MIN(chunks_per_read, dl_lines_total);
927
928                 bufsz = sigma_read_dram(dl_lines_done, dl_lines_curr,
929                                         (uint8_t *)dram_line, devc);
930                 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
931                 (void)bufsz;
932
933                 /* This is the first DRAM line, so find the initial timestamp. */
934                 if (dl_lines_done == 0) {
935                         devc->state.lastts =
936                                 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
937                         devc->state.lastsample = 0;
938                 }
939
940                 for (i = 0; i < dl_lines_curr; i++) {
941                         uint32_t trigger_event = ~0;
942                         /* The last "DRAM line" can be only partially full. */
943                         if (dl_lines_done + i == dl_lines_total - 1)
944                                 dl_events_in_line = stoppos & 0x1ff;
945
946                         /* Test if the trigger happened on this line. */
947                         if (dl_lines_done + i == trg_line)
948                                 trigger_event = trg_event;
949
950                         decode_chunk_ts(dram_line + i, dl_events_in_line,
951                                         trigger_event, sdi);
952                 }
953
954                 dl_lines_done += dl_lines_curr;
955         }
956
957         std_session_send_df_end(sdi);
958
959         sdi->driver->dev_acquisition_stop(sdi);
960
961         g_free(dram_line);
962
963         return TRUE;
964 }
965
966 /*
967  * Handle the Sigma when in CAPTURE mode. This function checks:
968  * - Sampling time ended
969  * - DRAM capacity overflow
970  * This function triggers download of the samples from Sigma
971  * in case either of the above conditions is true.
972  */
973 static int sigma_capture_mode(struct sr_dev_inst *sdi)
974 {
975         struct dev_context *devc = sdi->priv;
976
977         uint64_t running_msec;
978         struct timeval tv;
979
980         uint32_t stoppos, triggerpos;
981
982         /* Check if the selected sampling duration passed. */
983         gettimeofday(&tv, 0);
984         running_msec = (tv.tv_sec - devc->start_tv.tv_sec) * 1000 +
985                        (tv.tv_usec - devc->start_tv.tv_usec) / 1000;
986         if (running_msec >= devc->limit_msec)
987                 return download_capture(sdi);
988
989         /* Get the position in DRAM to which the FPGA is writing now. */
990         sigma_read_pos(&stoppos, &triggerpos, devc);
991         /* Test if DRAM is full and if so, download the data. */
992         if ((stoppos >> 9) == 32767)
993                 return download_capture(sdi);
994
995         return TRUE;
996 }
997
998 SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
999 {
1000         struct sr_dev_inst *sdi;
1001         struct dev_context *devc;
1002
1003         (void)fd;
1004         (void)revents;
1005
1006         sdi = cb_data;
1007         devc = sdi->priv;
1008
1009         if (devc->state.state == SIGMA_IDLE)
1010                 return TRUE;
1011
1012         if (devc->state.state == SIGMA_CAPTURE)
1013                 return sigma_capture_mode(sdi);
1014
1015         return TRUE;
1016 }
1017
1018 /* Build a LUT entry used by the trigger functions. */
1019 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1020 {
1021         int i, j, k, bit;
1022
1023         /* For each quad channel. */
1024         for (i = 0; i < 4; i++) {
1025                 entry[i] = 0xffff;
1026
1027                 /* For each bit in LUT. */
1028                 for (j = 0; j < 16; j++)
1029
1030                         /* For each channel in quad. */
1031                         for (k = 0; k < 4; k++) {
1032                                 bit = 1 << (i * 4 + k);
1033
1034                                 /* Set bit in entry */
1035                                 if ((mask & bit) && ((!(value & bit)) !=
1036                                                         (!(j & (1 << k)))))
1037                                         entry[i] &= ~(1 << j);
1038                         }
1039         }
1040 }
1041
1042 /* Add a logical function to LUT mask. */
1043 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1044                                  int index, int neg, uint16_t *mask)
1045 {
1046         int i, j;
1047         int x[2][2], tmp, a, b, aset, bset, rset;
1048
1049         memset(x, 0, 4 * sizeof(int));
1050
1051         /* Trigger detect condition. */
1052         switch (oper) {
1053         case OP_LEVEL:
1054                 x[0][1] = 1;
1055                 x[1][1] = 1;
1056                 break;
1057         case OP_NOT:
1058                 x[0][0] = 1;
1059                 x[1][0] = 1;
1060                 break;
1061         case OP_RISE:
1062                 x[0][1] = 1;
1063                 break;
1064         case OP_FALL:
1065                 x[1][0] = 1;
1066                 break;
1067         case OP_RISEFALL:
1068                 x[0][1] = 1;
1069                 x[1][0] = 1;
1070                 break;
1071         case OP_NOTRISE:
1072                 x[1][1] = 1;
1073                 x[0][0] = 1;
1074                 x[1][0] = 1;
1075                 break;
1076         case OP_NOTFALL:
1077                 x[1][1] = 1;
1078                 x[0][0] = 1;
1079                 x[0][1] = 1;
1080                 break;
1081         case OP_NOTRISEFALL:
1082                 x[1][1] = 1;
1083                 x[0][0] = 1;
1084                 break;
1085         }
1086
1087         /* Transpose if neg is set. */
1088         if (neg) {
1089                 for (i = 0; i < 2; i++) {
1090                         for (j = 0; j < 2; j++) {
1091                                 tmp = x[i][j];
1092                                 x[i][j] = x[1 - i][1 - j];
1093                                 x[1 - i][1 - j] = tmp;
1094                         }
1095                 }
1096         }
1097
1098         /* Update mask with function. */
1099         for (i = 0; i < 16; i++) {
1100                 a = (i >> (2 * index + 0)) & 1;
1101                 b = (i >> (2 * index + 1)) & 1;
1102
1103                 aset = (*mask >> i) & 1;
1104                 bset = x[b][a];
1105
1106                 rset = 0;
1107                 if (func == FUNC_AND || func == FUNC_NAND)
1108                         rset = aset & bset;
1109                 else if (func == FUNC_OR || func == FUNC_NOR)
1110                         rset = aset | bset;
1111                 else if (func == FUNC_XOR || func == FUNC_NXOR)
1112                         rset = aset ^ bset;
1113
1114                 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1115                         rset = !rset;
1116
1117                 *mask &= ~(1 << i);
1118
1119                 if (rset)
1120                         *mask |= 1 << i;
1121         }
1122 }
1123
1124 /*
1125  * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1126  * simple pin change and state triggers. Only two transitions (rise/fall) can be
1127  * set at any time, but a full mask and value can be set (0/1).
1128  */
1129 SR_PRIV int sigma_build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1130 {
1131         int i,j;
1132         uint16_t masks[2] = { 0, 0 };
1133
1134         memset(lut, 0, sizeof(struct triggerlut));
1135
1136         /* Constant for simple triggers. */
1137         lut->m4 = 0xa000;
1138
1139         /* Value/mask trigger support. */
1140         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1141                         lut->m2d);
1142
1143         /* Rise/fall trigger support. */
1144         for (i = 0, j = 0; i < 16; i++) {
1145                 if (devc->trigger.risingmask & (1 << i) ||
1146                     devc->trigger.fallingmask & (1 << i))
1147                         masks[j++] = 1 << i;
1148         }
1149
1150         build_lut_entry(masks[0], masks[0], lut->m0d);
1151         build_lut_entry(masks[1], masks[1], lut->m1d);
1152
1153         /* Add glue logic */
1154         if (masks[0] || masks[1]) {
1155                 /* Transition trigger. */
1156                 if (masks[0] & devc->trigger.risingmask)
1157                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1158                 if (masks[0] & devc->trigger.fallingmask)
1159                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1160                 if (masks[1] & devc->trigger.risingmask)
1161                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1162                 if (masks[1] & devc->trigger.fallingmask)
1163                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1164         } else {
1165                 /* Only value/mask trigger. */
1166                 lut->m3 = 0xffff;
1167         }
1168
1169         /* Triggertype: event. */
1170         lut->params.selres = 3;
1171
1172         return SR_OK;
1173 }