]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/asix-sigma.c
Java: Remove explicit constructor deletes since SWIG 2 doesn't like them
[libsigrok.git] / src / hardware / asix-sigma / asix-sigma.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 <glib.h>
28 #include <glib/gstdio.h>
29 #include <ftdi.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <libsigrok/libsigrok.h>
33 #include "libsigrok-internal.h"
34 #include "asix-sigma.h"
35
36 #define USB_VENDOR                      0xa600
37 #define USB_PRODUCT                     0xa000
38 #define USB_DESCRIPTION                 "ASIX SIGMA"
39 #define USB_VENDOR_NAME                 "ASIX"
40 #define USB_MODEL_NAME                  "SIGMA"
41
42 SR_PRIV struct sr_dev_driver asix_sigma_driver_info;
43 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
44
45 /*
46  * The ASIX Sigma supports arbitrary integer frequency divider in
47  * the 50MHz mode. The divider is in range 1...256 , allowing for
48  * very precise sampling rate selection. This driver supports only
49  * a subset of the sampling rates.
50  */
51 static const uint64_t samplerates[] = {
52         SR_KHZ(200),    /* div=250 */
53         SR_KHZ(250),    /* div=200 */
54         SR_KHZ(500),    /* div=100 */
55         SR_MHZ(1),      /* div=50  */
56         SR_MHZ(5),      /* div=10  */
57         SR_MHZ(10),     /* div=5   */
58         SR_MHZ(25),     /* div=2   */
59         SR_MHZ(50),     /* div=1   */
60         SR_MHZ(100),    /* Special FW needed */
61         SR_MHZ(200),    /* Special FW needed */
62 };
63
64 /*
65  * Channel numbers seem to go from 1-16, according to this image:
66  * http://tools.asix.net/img/sigma_sigmacab_pins_720.jpg
67  * (the cable has two additional GND pins, and a TI and TO pin)
68  */
69 static const char *channel_names[] = {
70         "1", "2", "3", "4", "5", "6", "7", "8",
71         "9", "10", "11", "12", "13", "14", "15", "16",
72 };
73
74 static const uint32_t drvopts[] = {
75         SR_CONF_LOGIC_ANALYZER,
76 };
77
78 static const uint32_t devopts[] = {
79         SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
80         SR_CONF_LIMIT_SAMPLES | SR_CONF_SET,
81         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
82         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
83         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
84 };
85
86 static const int32_t trigger_matches[] = {
87         SR_TRIGGER_ZERO,
88         SR_TRIGGER_ONE,
89         SR_TRIGGER_RISING,
90         SR_TRIGGER_FALLING,
91 };
92
93 static const char sigma_firmware_files[][24] = {
94         /* 50 MHz, supports 8 bit fractions */
95         "asix-sigma-50.fw",
96         /* 100 MHz */
97         "asix-sigma-100.fw",
98         /* 200 MHz */
99         "asix-sigma-200.fw",
100         /* Synchronous clock from pin */
101         "asix-sigma-50sync.fw",
102         /* Frequency counter */
103         "asix-sigma-phasor.fw",
104 };
105
106 static int sigma_read(void *buf, size_t size, struct dev_context *devc)
107 {
108         int ret;
109
110         ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
111         if (ret < 0) {
112                 sr_err("ftdi_read_data failed: %s",
113                        ftdi_get_error_string(&devc->ftdic));
114         }
115
116         return ret;
117 }
118
119 static int sigma_write(void *buf, size_t size, struct dev_context *devc)
120 {
121         int ret;
122
123         ret = ftdi_write_data(&devc->ftdic, (unsigned char *)buf, size);
124         if (ret < 0) {
125                 sr_err("ftdi_write_data failed: %s",
126                        ftdi_get_error_string(&devc->ftdic));
127         } else if ((size_t) ret != size) {
128                 sr_err("ftdi_write_data did not complete write.");
129         }
130
131         return ret;
132 }
133
134 /*
135  * NOTE: We chose the buffer size to be large enough to hold any write to the
136  * device. We still print a message just in case.
137  */
138 static int sigma_write_register(uint8_t reg, uint8_t *data, size_t len,
139                                 struct dev_context *devc)
140 {
141         size_t i;
142         uint8_t buf[80];
143         int idx = 0;
144
145         if ((len + 2) > sizeof(buf)) {
146                 sr_err("Attempted to write %zu bytes, but buffer is too small.",
147                        len + 2);
148                 return SR_ERR_BUG;
149         }
150
151         buf[idx++] = REG_ADDR_LOW | (reg & 0xf);
152         buf[idx++] = REG_ADDR_HIGH | (reg >> 4);
153
154         for (i = 0; i < len; ++i) {
155                 buf[idx++] = REG_DATA_LOW | (data[i] & 0xf);
156                 buf[idx++] = REG_DATA_HIGH_WRITE | (data[i] >> 4);
157         }
158
159         return sigma_write(buf, idx, devc);
160 }
161
162 static int sigma_set_register(uint8_t reg, uint8_t value, struct dev_context *devc)
163 {
164         return sigma_write_register(reg, &value, 1, devc);
165 }
166
167 static int sigma_read_register(uint8_t reg, uint8_t *data, size_t len,
168                                struct dev_context *devc)
169 {
170         uint8_t buf[3];
171
172         buf[0] = REG_ADDR_LOW | (reg & 0xf);
173         buf[1] = REG_ADDR_HIGH | (reg >> 4);
174         buf[2] = REG_READ_ADDR;
175
176         sigma_write(buf, sizeof(buf), devc);
177
178         return sigma_read(data, len, devc);
179 }
180
181 static uint8_t sigma_get_register(uint8_t reg, struct dev_context *devc)
182 {
183         uint8_t value;
184
185         if (1 != sigma_read_register(reg, &value, 1, devc)) {
186                 sr_err("sigma_get_register: 1 byte expected");
187                 return 0;
188         }
189
190         return value;
191 }
192
193 static int sigma_read_pos(uint32_t *stoppos, uint32_t *triggerpos,
194                           struct dev_context *devc)
195 {
196         uint8_t buf[] = {
197                 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
198
199                 REG_READ_ADDR | NEXT_REG,
200                 REG_READ_ADDR | NEXT_REG,
201                 REG_READ_ADDR | NEXT_REG,
202                 REG_READ_ADDR | NEXT_REG,
203                 REG_READ_ADDR | NEXT_REG,
204                 REG_READ_ADDR | NEXT_REG,
205         };
206         uint8_t result[6];
207
208         sigma_write(buf, sizeof(buf), devc);
209
210         sigma_read(result, sizeof(result), devc);
211
212         *triggerpos = result[0] | (result[1] << 8) | (result[2] << 16);
213         *stoppos = result[3] | (result[4] << 8) | (result[5] << 16);
214
215         /* Not really sure why this must be done, but according to spec. */
216         if ((--*stoppos & 0x1ff) == 0x1ff)
217                 *stoppos -= 64;
218
219         if ((*--triggerpos & 0x1ff) == 0x1ff)
220                 *triggerpos -= 64;
221
222         return 1;
223 }
224
225 static int sigma_read_dram(uint16_t startchunk, size_t numchunks,
226                            uint8_t *data, struct dev_context *devc)
227 {
228         size_t i;
229         uint8_t buf[4096];
230         int idx = 0;
231
232         /* Send the startchunk. Index start with 1. */
233         buf[0] = startchunk >> 8;
234         buf[1] = startchunk & 0xff;
235         sigma_write_register(WRITE_MEMROW, buf, 2, devc);
236
237         /* Read the DRAM. */
238         buf[idx++] = REG_DRAM_BLOCK;
239         buf[idx++] = REG_DRAM_WAIT_ACK;
240
241         for (i = 0; i < numchunks; ++i) {
242                 /* Alternate bit to copy from DRAM to cache. */
243                 if (i != (numchunks - 1))
244                         buf[idx++] = REG_DRAM_BLOCK | (((i + 1) % 2) << 4);
245
246                 buf[idx++] = REG_DRAM_BLOCK_DATA | ((i % 2) << 4);
247
248                 if (i != (numchunks - 1))
249                         buf[idx++] = REG_DRAM_WAIT_ACK;
250         }
251
252         sigma_write(buf, idx, devc);
253
254         return sigma_read(data, numchunks * CHUNK_SIZE, devc);
255 }
256
257 /* Upload trigger look-up tables to Sigma. */
258 static int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *devc)
259 {
260         int i;
261         uint8_t tmp[2];
262         uint16_t bit;
263
264         /* Transpose the table and send to Sigma. */
265         for (i = 0; i < 16; ++i) {
266                 bit = 1 << i;
267
268                 tmp[0] = tmp[1] = 0;
269
270                 if (lut->m2d[0] & bit)
271                         tmp[0] |= 0x01;
272                 if (lut->m2d[1] & bit)
273                         tmp[0] |= 0x02;
274                 if (lut->m2d[2] & bit)
275                         tmp[0] |= 0x04;
276                 if (lut->m2d[3] & bit)
277                         tmp[0] |= 0x08;
278
279                 if (lut->m3 & bit)
280                         tmp[0] |= 0x10;
281                 if (lut->m3s & bit)
282                         tmp[0] |= 0x20;
283                 if (lut->m4 & bit)
284                         tmp[0] |= 0x40;
285
286                 if (lut->m0d[0] & bit)
287                         tmp[1] |= 0x01;
288                 if (lut->m0d[1] & bit)
289                         tmp[1] |= 0x02;
290                 if (lut->m0d[2] & bit)
291                         tmp[1] |= 0x04;
292                 if (lut->m0d[3] & bit)
293                         tmp[1] |= 0x08;
294
295                 if (lut->m1d[0] & bit)
296                         tmp[1] |= 0x10;
297                 if (lut->m1d[1] & bit)
298                         tmp[1] |= 0x20;
299                 if (lut->m1d[2] & bit)
300                         tmp[1] |= 0x40;
301                 if (lut->m1d[3] & bit)
302                         tmp[1] |= 0x80;
303
304                 sigma_write_register(WRITE_TRIGGER_SELECT0, tmp, sizeof(tmp),
305                                      devc);
306                 sigma_set_register(WRITE_TRIGGER_SELECT1, 0x30 | i, devc);
307         }
308
309         /* Send the parameters */
310         sigma_write_register(WRITE_TRIGGER_SELECT0, (uint8_t *) &lut->params,
311                              sizeof(lut->params), devc);
312
313         return SR_OK;
314 }
315
316 static void clear_helper(void *priv)
317 {
318         struct dev_context *devc;
319
320         devc = priv;
321
322         ftdi_deinit(&devc->ftdic);
323 }
324
325 static int dev_clear(const struct sr_dev_driver *di)
326 {
327         return std_dev_clear(di, clear_helper);
328 }
329
330 static int init(struct sr_dev_driver *di, struct sr_context *sr_ctx)
331 {
332         return std_init(sr_ctx, di, LOG_PREFIX);
333 }
334
335 static GSList *scan(struct sr_dev_driver *di, GSList *options)
336 {
337         struct sr_dev_inst *sdi;
338         struct drv_context *drvc;
339         struct dev_context *devc;
340         GSList *devices;
341         struct ftdi_device_list *devlist;
342         char serial_txt[10];
343         uint32_t serial;
344         int ret;
345         unsigned int i;
346
347         (void)options;
348
349         drvc = di->context;
350
351         devices = NULL;
352
353         devc = g_malloc0(sizeof(struct dev_context));
354
355         ftdi_init(&devc->ftdic);
356
357         /* Look for SIGMAs. */
358
359         if ((ret = ftdi_usb_find_all(&devc->ftdic, &devlist,
360             USB_VENDOR, USB_PRODUCT)) <= 0) {
361                 if (ret < 0)
362                         sr_err("ftdi_usb_find_all(): %d", ret);
363                 goto free;
364         }
365
366         /* Make sure it's a version 1 or 2 SIGMA. */
367         ftdi_usb_get_strings(&devc->ftdic, devlist->dev, NULL, 0, NULL, 0,
368                              serial_txt, sizeof(serial_txt));
369         sscanf(serial_txt, "%x", &serial);
370
371         if (serial < 0xa6010000 || serial > 0xa602ffff) {
372                 sr_err("Only SIGMA and SIGMA2 are supported "
373                        "in this version of libsigrok.");
374                 goto free;
375         }
376
377         sr_info("Found ASIX SIGMA - Serial: %s", serial_txt);
378
379         devc->cur_samplerate = samplerates[0];
380         devc->period_ps = 0;
381         devc->limit_msec = 0;
382         devc->cur_firmware = -1;
383         devc->num_channels = 0;
384         devc->samples_per_event = 0;
385         devc->capture_ratio = 50;
386         devc->use_triggers = 0;
387
388         /* Register SIGMA device. */
389         sdi = g_malloc0(sizeof(struct sr_dev_inst));
390         sdi->status = SR_ST_INITIALIZING;
391         sdi->vendor = g_strdup(USB_VENDOR_NAME);
392         sdi->model = g_strdup(USB_MODEL_NAME);
393         sdi->driver = di;
394
395         for (i = 0; i < ARRAY_SIZE(channel_names); i++)
396                 sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_names[i]);
397
398         devices = g_slist_append(devices, sdi);
399         drvc->instances = g_slist_append(drvc->instances, sdi);
400         sdi->priv = devc;
401
402         /* We will open the device again when we need it. */
403         ftdi_list_free(&devlist);
404
405         return devices;
406
407 free:
408         ftdi_deinit(&devc->ftdic);
409         g_free(devc);
410         return NULL;
411 }
412
413 static GSList *dev_list(const struct sr_dev_driver *di)
414 {
415         return ((struct drv_context *)(di->context))->instances;
416 }
417
418 /*
419  * Configure the FPGA for bitbang mode.
420  * This sequence is documented in section 2. of the ASIX Sigma programming
421  * manual. This sequence is necessary to configure the FPGA in the Sigma
422  * into Bitbang mode, in which it can be programmed with the firmware.
423  */
424 static int sigma_fpga_init_bitbang(struct dev_context *devc)
425 {
426         uint8_t suicide[] = {
427                 0x84, 0x84, 0x88, 0x84, 0x88, 0x84, 0x88, 0x84,
428         };
429         uint8_t init_array[] = {
430                 0x01, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01,
431                 0x01, 0x01,
432         };
433         int i, ret, timeout = (10 * 1000);
434         uint8_t data;
435
436         /* Section 2. part 1), do the FPGA suicide. */
437         sigma_write(suicide, sizeof(suicide), devc);
438         sigma_write(suicide, sizeof(suicide), devc);
439         sigma_write(suicide, sizeof(suicide), devc);
440         sigma_write(suicide, sizeof(suicide), devc);
441
442         /* Section 2. part 2), do pulse on D1. */
443         sigma_write(init_array, sizeof(init_array), devc);
444         ftdi_usb_purge_buffers(&devc->ftdic);
445
446         /* Wait until the FPGA asserts D6/INIT_B. */
447         for (i = 0; i < timeout; i++) {
448                 ret = sigma_read(&data, 1, devc);
449                 if (ret < 0)
450                         return ret;
451                 /* Test if pin D6 got asserted. */
452                 if (data & (1 << 5))
453                         return 0;
454                 /* The D6 was not asserted yet, wait a bit. */
455                 g_usleep(10 * 1000);
456         }
457
458         return SR_ERR_TIMEOUT;
459 }
460
461 /*
462  * Configure the FPGA for logic-analyzer mode.
463  */
464 static int sigma_fpga_init_la(struct dev_context *devc)
465 {
466         /* Initialize the logic analyzer mode. */
467         uint8_t logic_mode_start[] = {
468                 REG_ADDR_LOW  | (READ_ID & 0xf),
469                 REG_ADDR_HIGH | (READ_ID >> 8),
470                 REG_READ_ADDR,  /* Read ID register. */
471
472                 REG_ADDR_LOW | (WRITE_TEST & 0xf),
473                 REG_DATA_LOW | 0x5,
474                 REG_DATA_HIGH_WRITE | 0x5,
475                 REG_READ_ADDR,  /* Read scratch register. */
476
477                 REG_DATA_LOW | 0xa,
478                 REG_DATA_HIGH_WRITE | 0xa,
479                 REG_READ_ADDR,  /* Read scratch register. */
480
481                 REG_ADDR_LOW | (WRITE_MODE & 0xf),
482                 REG_DATA_LOW | 0x0,
483                 REG_DATA_HIGH_WRITE | 0x8,
484         };
485
486         uint8_t result[3];
487         int ret;
488
489         /* Initialize the logic analyzer mode. */
490         sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
491
492         /* Expect a 3 byte reply since we issued three READ requests. */
493         ret = sigma_read(result, 3, devc);
494         if (ret != 3)
495                 goto err;
496
497         if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
498                 goto err;
499
500         return SR_OK;
501 err:
502         sr_err("Configuration failed. Invalid reply received.");
503         return SR_ERR;
504 }
505
506 /*
507  * Read the firmware from a file and transform it into a series of bitbang
508  * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
509  * by the caller of this function.
510  */
511 static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
512                               uint8_t **bb_cmd, gsize *bb_cmd_size)
513 {
514         size_t i, file_size, bb_size;
515         char *firmware;
516         uint8_t *bb_stream, *bbs;
517         uint32_t imm;
518         int bit, v;
519         int ret = SR_OK;
520
521         firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE,
522                         name, &file_size, 256 * 1024);
523         if (!firmware)
524                 return SR_ERR;
525
526         /* Weird magic transformation below, I have no idea what it does. */
527         imm = 0x3f6df2ab;
528         for (i = 0; i < file_size; i++) {
529                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
530                 firmware[i] ^= imm & 0xff;
531         }
532
533         /*
534          * Now that the firmware is "transformed", we will transcribe the
535          * firmware blob into a sequence of toggles of the Dx wires. This
536          * sequence will be fed directly into the Sigma, which must be in
537          * the FPGA bitbang programming mode.
538          */
539
540         /* Each bit of firmware is transcribed as two toggles of Dx wires. */
541         bb_size = file_size * 8 * 2;
542         bb_stream = (uint8_t *)g_try_malloc(bb_size);
543         if (!bb_stream) {
544                 sr_err("%s: Failed to allocate bitbang stream", __func__);
545                 ret = SR_ERR_MALLOC;
546                 goto exit;
547         }
548
549         bbs = bb_stream;
550         for (i = 0; i < file_size; i++) {
551                 for (bit = 7; bit >= 0; bit--) {
552                         v = (firmware[i] & (1 << bit)) ? 0x40 : 0x00;
553                         *bbs++ = v | 0x01;
554                         *bbs++ = v;
555                 }
556         }
557
558         /* The transformation completed successfully, return the result. */
559         *bb_cmd = bb_stream;
560         *bb_cmd_size = bb_size;
561
562 exit:
563         g_free(firmware);
564         return ret;
565 }
566
567 static int upload_firmware(struct sr_context *ctx,
568                 int firmware_idx, struct dev_context *devc)
569 {
570         int ret;
571         unsigned char *buf;
572         unsigned char pins;
573         size_t buf_size;
574         const char *firmware = sigma_firmware_files[firmware_idx];
575         struct ftdi_context *ftdic = &devc->ftdic;
576
577         /* Make sure it's an ASIX SIGMA. */
578         ret = ftdi_usb_open_desc(ftdic, USB_VENDOR, USB_PRODUCT,
579                                  USB_DESCRIPTION, NULL);
580         if (ret < 0) {
581                 sr_err("ftdi_usb_open failed: %s",
582                        ftdi_get_error_string(ftdic));
583                 return 0;
584         }
585
586         ret = ftdi_set_bitmode(ftdic, 0xdf, BITMODE_BITBANG);
587         if (ret < 0) {
588                 sr_err("ftdi_set_bitmode failed: %s",
589                        ftdi_get_error_string(ftdic));
590                 return 0;
591         }
592
593         /* Four times the speed of sigmalogan - Works well. */
594         ret = ftdi_set_baudrate(ftdic, 750 * 1000);
595         if (ret < 0) {
596                 sr_err("ftdi_set_baudrate failed: %s",
597                        ftdi_get_error_string(ftdic));
598                 return 0;
599         }
600
601         /* Initialize the FPGA for firmware upload. */
602         ret = sigma_fpga_init_bitbang(devc);
603         if (ret)
604                 return ret;
605
606         /* Prepare firmware. */
607         ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
608         if (ret != SR_OK) {
609                 sr_err("An error occurred while reading the firmware: %s",
610                        firmware);
611                 return ret;
612         }
613
614         /* Upload firmware. */
615         sr_info("Uploading firmware file '%s'.", firmware);
616         sigma_write(buf, buf_size, devc);
617
618         g_free(buf);
619
620         ret = ftdi_set_bitmode(ftdic, 0x00, BITMODE_RESET);
621         if (ret < 0) {
622                 sr_err("ftdi_set_bitmode failed: %s",
623                        ftdi_get_error_string(ftdic));
624                 return SR_ERR;
625         }
626
627         ftdi_usb_purge_buffers(ftdic);
628
629         /* Discard garbage. */
630         while (sigma_read(&pins, 1, devc) == 1)
631                 ;
632
633         /* Initialize the FPGA for logic-analyzer mode. */
634         ret = sigma_fpga_init_la(devc);
635         if (ret != SR_OK)
636                 return ret;
637
638         devc->cur_firmware = firmware_idx;
639
640         sr_info("Firmware uploaded.");
641
642         return SR_OK;
643 }
644
645 static int dev_open(struct sr_dev_inst *sdi)
646 {
647         struct dev_context *devc;
648         int ret;
649
650         devc = sdi->priv;
651
652         /* Make sure it's an ASIX SIGMA. */
653         if ((ret = ftdi_usb_open_desc(&devc->ftdic,
654                 USB_VENDOR, USB_PRODUCT, USB_DESCRIPTION, NULL)) < 0) {
655
656                 sr_err("ftdi_usb_open failed: %s",
657                        ftdi_get_error_string(&devc->ftdic));
658
659                 return 0;
660         }
661
662         sdi->status = SR_ST_ACTIVE;
663
664         return SR_OK;
665 }
666
667 static int set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
668 {
669         struct dev_context *devc;
670         struct drv_context *drvc;
671         unsigned int i;
672         int ret;
673
674         devc = sdi->priv;
675         drvc = sdi->driver->context;
676         ret = SR_OK;
677
678         for (i = 0; i < ARRAY_SIZE(samplerates); i++) {
679                 if (samplerates[i] == samplerate)
680                         break;
681         }
682         if (samplerates[i] == 0)
683                 return SR_ERR_SAMPLERATE;
684
685         if (samplerate <= SR_MHZ(50)) {
686                 ret = upload_firmware(drvc->sr_ctx, 0, devc);
687                 devc->num_channels = 16;
688         } else if (samplerate == SR_MHZ(100)) {
689                 ret = upload_firmware(drvc->sr_ctx, 1, devc);
690                 devc->num_channels = 8;
691         } else if (samplerate == SR_MHZ(200)) {
692                 ret = upload_firmware(drvc->sr_ctx, 2, devc);
693                 devc->num_channels = 4;
694         }
695
696         if (ret == SR_OK) {
697                 devc->cur_samplerate = samplerate;
698                 devc->period_ps = 1000000000000ULL / samplerate;
699                 devc->samples_per_event = 16 / devc->num_channels;
700                 devc->state.state = SIGMA_IDLE;
701         }
702
703         return ret;
704 }
705
706 /*
707  * In 100 and 200 MHz mode, only a single pin rising/falling can be
708  * set as trigger. In other modes, two rising/falling triggers can be set,
709  * in addition to value/mask trigger for any number of channels.
710  *
711  * The Sigma supports complex triggers using boolean expressions, but this
712  * has not been implemented yet.
713  */
714 static int convert_trigger(const struct sr_dev_inst *sdi)
715 {
716         struct dev_context *devc;
717         struct sr_trigger *trigger;
718         struct sr_trigger_stage *stage;
719         struct sr_trigger_match *match;
720         const GSList *l, *m;
721         int channelbit, trigger_set;
722
723         devc = sdi->priv;
724         memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
725         if (!(trigger = sr_session_trigger_get(sdi->session)))
726                 return SR_OK;
727
728         trigger_set = 0;
729         for (l = trigger->stages; l; l = l->next) {
730                 stage = l->data;
731                 for (m = stage->matches; m; m = m->next) {
732                         match = m->data;
733                         if (!match->channel->enabled)
734                                 /* Ignore disabled channels with a trigger. */
735                                 continue;
736                         channelbit = 1 << (match->channel->index);
737                         if (devc->cur_samplerate >= SR_MHZ(100)) {
738                                 /* Fast trigger support. */
739                                 if (trigger_set) {
740                                         sr_err("Only a single pin trigger is "
741                                                         "supported in 100 and 200MHz mode.");
742                                         return SR_ERR;
743                                 }
744                                 if (match->match == SR_TRIGGER_FALLING)
745                                         devc->trigger.fallingmask |= channelbit;
746                                 else if (match->match == SR_TRIGGER_RISING)
747                                         devc->trigger.risingmask |= channelbit;
748                                 else {
749                                         sr_err("Only rising/falling trigger is "
750                                                         "supported in 100 and 200MHz mode.");
751                                         return SR_ERR;
752                                 }
753
754                                 ++trigger_set;
755                         } else {
756                                 /* Simple trigger support (event). */
757                                 if (match->match == SR_TRIGGER_ONE) {
758                                         devc->trigger.simplevalue |= channelbit;
759                                         devc->trigger.simplemask |= channelbit;
760                                 }
761                                 else if (match->match == SR_TRIGGER_ZERO) {
762                                         devc->trigger.simplevalue &= ~channelbit;
763                                         devc->trigger.simplemask |= channelbit;
764                                 }
765                                 else if (match->match == SR_TRIGGER_FALLING) {
766                                         devc->trigger.fallingmask |= channelbit;
767                                         ++trigger_set;
768                                 }
769                                 else if (match->match == SR_TRIGGER_RISING) {
770                                         devc->trigger.risingmask |= channelbit;
771                                         ++trigger_set;
772                                 }
773
774                                 /*
775                                  * Actually, Sigma supports 2 rising/falling triggers,
776                                  * but they are ORed and the current trigger syntax
777                                  * does not permit ORed triggers.
778                                  */
779                                 if (trigger_set > 1) {
780                                         sr_err("Only 1 rising/falling trigger "
781                                                    "is supported.");
782                                         return SR_ERR;
783                                 }
784                         }
785                 }
786         }
787
788         return SR_OK;
789 }
790
791 static int dev_close(struct sr_dev_inst *sdi)
792 {
793         struct dev_context *devc;
794
795         devc = sdi->priv;
796
797         /* TODO */
798         if (sdi->status == SR_ST_ACTIVE)
799                 ftdi_usb_close(&devc->ftdic);
800
801         sdi->status = SR_ST_INACTIVE;
802
803         return SR_OK;
804 }
805
806 static int cleanup(const struct sr_dev_driver *di)
807 {
808         return dev_clear(di);
809 }
810
811 static int config_get(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
812                 const struct sr_channel_group *cg)
813 {
814         struct dev_context *devc;
815
816         (void)cg;
817
818         if (!sdi)
819                 return SR_ERR;
820         devc = sdi->priv;
821
822         switch (key) {
823         case SR_CONF_SAMPLERATE:
824                 *data = g_variant_new_uint64(devc->cur_samplerate);
825                 break;
826         case SR_CONF_LIMIT_MSEC:
827                 *data = g_variant_new_uint64(devc->limit_msec);
828                 break;
829         case SR_CONF_CAPTURE_RATIO:
830                 *data = g_variant_new_uint64(devc->capture_ratio);
831                 break;
832         default:
833                 return SR_ERR_NA;
834         }
835
836         return SR_OK;
837 }
838
839 static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi,
840                 const struct sr_channel_group *cg)
841 {
842         struct dev_context *devc;
843         uint64_t tmp;
844         int ret;
845
846         (void)cg;
847
848         if (sdi->status != SR_ST_ACTIVE)
849                 return SR_ERR_DEV_CLOSED;
850
851         devc = sdi->priv;
852
853         ret = SR_OK;
854         switch (key) {
855         case SR_CONF_SAMPLERATE:
856                 ret = set_samplerate(sdi, g_variant_get_uint64(data));
857                 break;
858         case SR_CONF_LIMIT_MSEC:
859                 tmp = g_variant_get_uint64(data);
860                 if (tmp > 0)
861                         devc->limit_msec = g_variant_get_uint64(data);
862                 else
863                         ret = SR_ERR;
864                 break;
865         case SR_CONF_LIMIT_SAMPLES:
866                 tmp = g_variant_get_uint64(data);
867                 devc->limit_msec = tmp * 1000 / devc->cur_samplerate;
868                 break;
869         case SR_CONF_CAPTURE_RATIO:
870                 tmp = g_variant_get_uint64(data);
871                 if (tmp <= 100)
872                         devc->capture_ratio = tmp;
873                 else
874                         ret = SR_ERR;
875                 break;
876         default:
877                 ret = SR_ERR_NA;
878         }
879
880         return ret;
881 }
882
883 static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
884                 const struct sr_channel_group *cg)
885 {
886         GVariant *gvar;
887         GVariantBuilder gvb;
888
889         (void)cg;
890
891         switch (key) {
892         case SR_CONF_DEVICE_OPTIONS:
893                 if (!sdi)
894                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
895                                         drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
896                 else
897                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
898                                         devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
899                 break;
900         case SR_CONF_SAMPLERATE:
901                 g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
902                 gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), samplerates,
903                                 ARRAY_SIZE(samplerates), sizeof(uint64_t));
904                 g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
905                 *data = g_variant_builder_end(&gvb);
906                 break;
907         case SR_CONF_TRIGGER_MATCH:
908                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
909                                 trigger_matches, ARRAY_SIZE(trigger_matches),
910                                 sizeof(int32_t));
911                 break;
912         default:
913                 return SR_ERR_NA;
914         }
915
916         return SR_OK;
917 }
918
919 /* Software trigger to determine exact trigger position. */
920 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
921                               struct sigma_trigger *t)
922 {
923         int i;
924         uint16_t sample = 0;
925
926         for (i = 0; i < 8; ++i) {
927                 if (i > 0)
928                         last_sample = sample;
929                 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
930
931                 /* Simple triggers. */
932                 if ((sample & t->simplemask) != t->simplevalue)
933                         continue;
934
935                 /* Rising edge. */
936                 if (((last_sample & t->risingmask) != 0) ||
937                     ((sample & t->risingmask) != t->risingmask))
938                         continue;
939
940                 /* Falling edge. */
941                 if ((last_sample & t->fallingmask) != t->fallingmask ||
942                     (sample & t->fallingmask) != 0)
943                         continue;
944
945                 break;
946         }
947
948         /* If we did not match, return original trigger pos. */
949         return i & 0x7;
950 }
951
952 /*
953  * Return the timestamp of "DRAM cluster".
954  */
955 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
956 {
957         return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
958 }
959
960 static void sigma_decode_dram_cluster(struct sigma_dram_cluster *dram_cluster,
961                                       unsigned int events_in_cluster,
962                                       unsigned int triggered,
963                                       struct sr_dev_inst *sdi)
964 {
965         struct dev_context *devc = sdi->priv;
966         struct sigma_state *ss = &devc->state;
967         struct sr_datafeed_packet packet;
968         struct sr_datafeed_logic logic;
969         uint16_t tsdiff, ts;
970         uint8_t samples[2048];
971         unsigned int i;
972
973         ts = sigma_dram_cluster_ts(dram_cluster);
974         tsdiff = ts - ss->lastts;
975         ss->lastts = ts;
976
977         packet.type = SR_DF_LOGIC;
978         packet.payload = &logic;
979         logic.unitsize = 2;
980         logic.data = samples;
981
982         /*
983          * First of all, send Sigrok a copy of the last sample from
984          * previous cluster as many times as needed to make up for
985          * the differential characteristics of data we get from the
986          * Sigma. Sigrok needs one sample of data per period.
987          *
988          * One DRAM cluster contains a timestamp and seven samples,
989          * the units of timestamp are "devc->period_ps" , the first
990          * sample in the cluster happens at the time of the timestamp
991          * and the remaining samples happen at timestamp +1...+6 .
992          */
993         for (ts = 0; ts < tsdiff - (EVENTS_PER_CLUSTER - 1); ts++) {
994                 i = ts % 1024;
995                 samples[2 * i + 0] = ss->lastsample & 0xff;
996                 samples[2 * i + 1] = ss->lastsample >> 8;
997
998                 /*
999                  * If we have 1024 samples ready or we're at the
1000                  * end of submitting the padding samples, submit
1001                  * the packet to Sigrok.
1002                  */
1003                 if ((i == 1023) || (ts == (tsdiff - EVENTS_PER_CLUSTER))) {
1004                         logic.length = (i + 1) * logic.unitsize;
1005                         sr_session_send(sdi, &packet);
1006                 }
1007         }
1008
1009         /*
1010          * Parse the samples in current cluster and prepare them
1011          * to be submitted to Sigrok.
1012          */
1013         for (i = 0; i < events_in_cluster; i++) {
1014                 samples[2 * i + 1] = dram_cluster->samples[i].sample_lo;
1015                 samples[2 * i + 0] = dram_cluster->samples[i].sample_hi;
1016         }
1017
1018         /* Send data up to trigger point (if triggered). */
1019         int trigger_offset = 0;
1020         if (triggered) {
1021                 /*
1022                  * Trigger is not always accurate to sample because of
1023                  * pipeline delay. However, it always triggers before
1024                  * the actual event. We therefore look at the next
1025                  * samples to pinpoint the exact position of the trigger.
1026                  */
1027                 trigger_offset = get_trigger_offset(samples,
1028                                         ss->lastsample, &devc->trigger);
1029
1030                 if (trigger_offset > 0) {
1031                         packet.type = SR_DF_LOGIC;
1032                         logic.length = trigger_offset * logic.unitsize;
1033                         sr_session_send(sdi, &packet);
1034                         events_in_cluster -= trigger_offset;
1035                 }
1036
1037                 /* Only send trigger if explicitly enabled. */
1038                 if (devc->use_triggers) {
1039                         packet.type = SR_DF_TRIGGER;
1040                         sr_session_send(sdi, &packet);
1041                 }
1042         }
1043
1044         if (events_in_cluster > 0) {
1045                 packet.type = SR_DF_LOGIC;
1046                 logic.length = events_in_cluster * logic.unitsize;
1047                 logic.data = samples + (trigger_offset * logic.unitsize);
1048                 sr_session_send(sdi, &packet);
1049         }
1050
1051         ss->lastsample =
1052                 samples[2 * (events_in_cluster - 1) + 0] |
1053                 (samples[2 * (events_in_cluster - 1) + 1] << 8);
1054
1055 }
1056
1057 /*
1058  * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1059  * Each event is 20ns apart, and can contain multiple samples.
1060  *
1061  * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1062  * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1063  * For 50 MHz and below, events contain one sample for each channel,
1064  * spread 20 ns apart.
1065  */
1066 static int decode_chunk_ts(struct sigma_dram_line *dram_line,
1067                            uint16_t events_in_line,
1068                            uint32_t trigger_event,
1069                            struct sr_dev_inst *sdi)
1070 {
1071         struct sigma_dram_cluster *dram_cluster;
1072         struct dev_context *devc = sdi->priv;
1073         unsigned int clusters_in_line =
1074                 (events_in_line + (EVENTS_PER_CLUSTER - 1)) / EVENTS_PER_CLUSTER;
1075         unsigned int events_in_cluster;
1076         unsigned int i;
1077         uint32_t trigger_cluster = ~0, triggered = 0;
1078
1079         /* Check if trigger is in this chunk. */
1080         if (trigger_event < (64 * 7)) {
1081                 if (devc->cur_samplerate <= SR_MHZ(50)) {
1082                         trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1083                                              trigger_event);
1084                 }
1085
1086                 /* Find in which cluster the trigger occurred. */
1087                 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1088         }
1089
1090         /* For each full DRAM cluster. */
1091         for (i = 0; i < clusters_in_line; i++) {
1092                 dram_cluster = &dram_line->cluster[i];
1093
1094                 /* The last cluster might not be full. */
1095                 if ((i == clusters_in_line - 1) &&
1096                     (events_in_line % EVENTS_PER_CLUSTER)) {
1097                         events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1098                 } else {
1099                         events_in_cluster = EVENTS_PER_CLUSTER;
1100                 }
1101
1102                 triggered = (i == trigger_cluster);
1103                 sigma_decode_dram_cluster(dram_cluster, events_in_cluster,
1104                                           triggered, sdi);
1105         }
1106
1107         return SR_OK;
1108 }
1109
1110 static int download_capture(struct sr_dev_inst *sdi)
1111 {
1112         struct dev_context *devc = sdi->priv;
1113         const uint32_t chunks_per_read = 32;
1114         struct sigma_dram_line *dram_line;
1115         int bufsz;
1116         uint32_t stoppos, triggerpos;
1117         struct sr_datafeed_packet packet;
1118         uint8_t modestatus;
1119
1120         uint32_t i;
1121         uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1122         uint32_t dl_events_in_line = 64 * 7;
1123         uint32_t trg_line = ~0, trg_event = ~0;
1124
1125         dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1126         if (!dram_line)
1127                 return FALSE;
1128
1129         sr_info("Downloading sample data.");
1130
1131         /* Stop acquisition. */
1132         sigma_set_register(WRITE_MODE, 0x11, devc);
1133
1134         /* Set SDRAM Read Enable. */
1135         sigma_set_register(WRITE_MODE, 0x02, devc);
1136
1137         /* Get the current position. */
1138         sigma_read_pos(&stoppos, &triggerpos, devc);
1139
1140         /* Check if trigger has fired. */
1141         modestatus = sigma_get_register(READ_MODE, devc);
1142         if (modestatus & 0x20) {
1143                 trg_line = triggerpos >> 9;
1144                 trg_event = triggerpos & 0x1ff;
1145         }
1146
1147         /*
1148          * Determine how many 1024b "DRAM lines" do we need to read from the
1149          * Sigma so we have a complete set of samples. Note that the last
1150          * line can be only partial, containing less than 64 clusters.
1151          */
1152         dl_lines_total = (stoppos >> 9) + 1;
1153
1154         dl_lines_done = 0;
1155
1156         while (dl_lines_total > dl_lines_done) {
1157                 /* We can download only up-to 32 DRAM lines in one go! */
1158                 dl_lines_curr = MIN(chunks_per_read, dl_lines_total);
1159
1160                 bufsz = sigma_read_dram(dl_lines_done, dl_lines_curr,
1161                                         (uint8_t *)dram_line, devc);
1162                 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1163                 (void)bufsz;
1164
1165                 /* This is the first DRAM line, so find the initial timestamp. */
1166                 if (dl_lines_done == 0) {
1167                         devc->state.lastts =
1168                                 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1169                         devc->state.lastsample = 0;
1170                 }
1171
1172                 for (i = 0; i < dl_lines_curr; i++) {
1173                         uint32_t trigger_event = ~0;
1174                         /* The last "DRAM line" can be only partially full. */
1175                         if (dl_lines_done + i == dl_lines_total - 1)
1176                                 dl_events_in_line = stoppos & 0x1ff;
1177
1178                         /* Test if the trigger happened on this line. */
1179                         if (dl_lines_done + i == trg_line)
1180                                 trigger_event = trg_event;
1181
1182                         decode_chunk_ts(dram_line + i, dl_events_in_line,
1183                                         trigger_event, sdi);
1184                 }
1185
1186                 dl_lines_done += dl_lines_curr;
1187         }
1188
1189         /* All done. */
1190         packet.type = SR_DF_END;
1191         sr_session_send(sdi, &packet);
1192
1193         dev_acquisition_stop(sdi, sdi);
1194
1195         g_free(dram_line);
1196
1197         return TRUE;
1198 }
1199
1200 /*
1201  * Handle the Sigma when in CAPTURE mode. This function checks:
1202  * - Sampling time ended
1203  * - DRAM capacity overflow
1204  * This function triggers download of the samples from Sigma
1205  * in case either of the above conditions is true.
1206  */
1207 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1208 {
1209         struct dev_context *devc = sdi->priv;
1210
1211         uint64_t running_msec;
1212         struct timeval tv;
1213
1214         uint32_t stoppos, triggerpos;
1215
1216         /* Check if the selected sampling duration passed. */
1217         gettimeofday(&tv, 0);
1218         running_msec = (tv.tv_sec - devc->start_tv.tv_sec) * 1000 +
1219                        (tv.tv_usec - devc->start_tv.tv_usec) / 1000;
1220         if (running_msec >= devc->limit_msec)
1221                 return download_capture(sdi);
1222
1223         /* Get the position in DRAM to which the FPGA is writing now. */
1224         sigma_read_pos(&stoppos, &triggerpos, devc);
1225         /* Test if DRAM is full and if so, download the data. */
1226         if ((stoppos >> 9) == 32767)
1227                 return download_capture(sdi);
1228
1229         return TRUE;
1230 }
1231
1232 static int receive_data(int fd, int revents, void *cb_data)
1233 {
1234         struct sr_dev_inst *sdi;
1235         struct dev_context *devc;
1236
1237         (void)fd;
1238         (void)revents;
1239
1240         sdi = cb_data;
1241         devc = sdi->priv;
1242
1243         if (devc->state.state == SIGMA_IDLE)
1244                 return TRUE;
1245
1246         if (devc->state.state == SIGMA_CAPTURE)
1247                 return sigma_capture_mode(sdi);
1248
1249         return TRUE;
1250 }
1251
1252 /* Build a LUT entry used by the trigger functions. */
1253 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1254 {
1255         int i, j, k, bit;
1256
1257         /* For each quad channel. */
1258         for (i = 0; i < 4; ++i) {
1259                 entry[i] = 0xffff;
1260
1261                 /* For each bit in LUT. */
1262                 for (j = 0; j < 16; ++j)
1263
1264                         /* For each channel in quad. */
1265                         for (k = 0; k < 4; ++k) {
1266                                 bit = 1 << (i * 4 + k);
1267
1268                                 /* Set bit in entry */
1269                                 if ((mask & bit) &&
1270                                     ((!(value & bit)) !=
1271                                     (!(j & (1 << k)))))
1272                                         entry[i] &= ~(1 << j);
1273                         }
1274         }
1275 }
1276
1277 /* Add a logical function to LUT mask. */
1278 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1279                                  int index, int neg, uint16_t *mask)
1280 {
1281         int i, j;
1282         int x[2][2], tmp, a, b, aset, bset, rset;
1283
1284         memset(x, 0, 4 * sizeof(int));
1285
1286         /* Trigger detect condition. */
1287         switch (oper) {
1288         case OP_LEVEL:
1289                 x[0][1] = 1;
1290                 x[1][1] = 1;
1291                 break;
1292         case OP_NOT:
1293                 x[0][0] = 1;
1294                 x[1][0] = 1;
1295                 break;
1296         case OP_RISE:
1297                 x[0][1] = 1;
1298                 break;
1299         case OP_FALL:
1300                 x[1][0] = 1;
1301                 break;
1302         case OP_RISEFALL:
1303                 x[0][1] = 1;
1304                 x[1][0] = 1;
1305                 break;
1306         case OP_NOTRISE:
1307                 x[1][1] = 1;
1308                 x[0][0] = 1;
1309                 x[1][0] = 1;
1310                 break;
1311         case OP_NOTFALL:
1312                 x[1][1] = 1;
1313                 x[0][0] = 1;
1314                 x[0][1] = 1;
1315                 break;
1316         case OP_NOTRISEFALL:
1317                 x[1][1] = 1;
1318                 x[0][0] = 1;
1319                 break;
1320         }
1321
1322         /* Transpose if neg is set. */
1323         if (neg) {
1324                 for (i = 0; i < 2; ++i) {
1325                         for (j = 0; j < 2; ++j) {
1326                                 tmp = x[i][j];
1327                                 x[i][j] = x[1-i][1-j];
1328                                 x[1-i][1-j] = tmp;
1329                         }
1330                 }
1331         }
1332
1333         /* Update mask with function. */
1334         for (i = 0; i < 16; ++i) {
1335                 a = (i >> (2 * index + 0)) & 1;
1336                 b = (i >> (2 * index + 1)) & 1;
1337
1338                 aset = (*mask >> i) & 1;
1339                 bset = x[b][a];
1340
1341                 rset = 0;
1342                 if (func == FUNC_AND || func == FUNC_NAND)
1343                         rset = aset & bset;
1344                 else if (func == FUNC_OR || func == FUNC_NOR)
1345                         rset = aset | bset;
1346                 else if (func == FUNC_XOR || func == FUNC_NXOR)
1347                         rset = aset ^ bset;
1348
1349                 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1350                         rset = !rset;
1351
1352                 *mask &= ~(1 << i);
1353
1354                 if (rset)
1355                         *mask |= 1 << i;
1356         }
1357 }
1358
1359 /*
1360  * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1361  * simple pin change and state triggers. Only two transitions (rise/fall) can be
1362  * set at any time, but a full mask and value can be set (0/1).
1363  */
1364 static int build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1365 {
1366         int i,j;
1367         uint16_t masks[2] = { 0, 0 };
1368
1369         memset(lut, 0, sizeof(struct triggerlut));
1370
1371         /* Constant for simple triggers. */
1372         lut->m4 = 0xa000;
1373
1374         /* Value/mask trigger support. */
1375         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1376                         lut->m2d);
1377
1378         /* Rise/fall trigger support. */
1379         for (i = 0, j = 0; i < 16; ++i) {
1380                 if (devc->trigger.risingmask & (1 << i) ||
1381                     devc->trigger.fallingmask & (1 << i))
1382                         masks[j++] = 1 << i;
1383         }
1384
1385         build_lut_entry(masks[0], masks[0], lut->m0d);
1386         build_lut_entry(masks[1], masks[1], lut->m1d);
1387
1388         /* Add glue logic */
1389         if (masks[0] || masks[1]) {
1390                 /* Transition trigger. */
1391                 if (masks[0] & devc->trigger.risingmask)
1392                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1393                 if (masks[0] & devc->trigger.fallingmask)
1394                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1395                 if (masks[1] & devc->trigger.risingmask)
1396                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1397                 if (masks[1] & devc->trigger.fallingmask)
1398                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1399         } else {
1400                 /* Only value/mask trigger. */
1401                 lut->m3 = 0xffff;
1402         }
1403
1404         /* Triggertype: event. */
1405         lut->params.selres = 3;
1406
1407         return SR_OK;
1408 }
1409
1410 static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data)
1411 {
1412         struct dev_context *devc;
1413         struct clockselect_50 clockselect;
1414         int frac, triggerpin, ret;
1415         uint8_t triggerselect = 0;
1416         struct triggerinout triggerinout_conf;
1417         struct triggerlut lut;
1418
1419         if (sdi->status != SR_ST_ACTIVE)
1420                 return SR_ERR_DEV_CLOSED;
1421
1422         devc = sdi->priv;
1423
1424         if (convert_trigger(sdi) != SR_OK) {
1425                 sr_err("Failed to configure triggers.");
1426                 return SR_ERR;
1427         }
1428
1429         /* If the samplerate has not been set, default to 200 kHz. */
1430         if (devc->cur_firmware == -1) {
1431                 if ((ret = set_samplerate(sdi, SR_KHZ(200))) != SR_OK)
1432                         return ret;
1433         }
1434
1435         /* Enter trigger programming mode. */
1436         sigma_set_register(WRITE_TRIGGER_SELECT1, 0x20, devc);
1437
1438         /* 100 and 200 MHz mode. */
1439         if (devc->cur_samplerate >= SR_MHZ(100)) {
1440                 sigma_set_register(WRITE_TRIGGER_SELECT1, 0x81, devc);
1441
1442                 /* Find which pin to trigger on from mask. */
1443                 for (triggerpin = 0; triggerpin < 8; ++triggerpin)
1444                         if ((devc->trigger.risingmask | devc->trigger.fallingmask) &
1445                             (1 << triggerpin))
1446                                 break;
1447
1448                 /* Set trigger pin and light LED on trigger. */
1449                 triggerselect = (1 << LEDSEL1) | (triggerpin & 0x7);
1450
1451                 /* Default rising edge. */
1452                 if (devc->trigger.fallingmask)
1453                         triggerselect |= 1 << 3;
1454
1455         /* All other modes. */
1456         } else if (devc->cur_samplerate <= SR_MHZ(50)) {
1457                 build_basic_trigger(&lut, devc);
1458
1459                 sigma_write_trigger_lut(&lut, devc);
1460
1461                 triggerselect = (1 << LEDSEL1) | (1 << LEDSEL0);
1462         }
1463
1464         /* Setup trigger in and out pins to default values. */
1465         memset(&triggerinout_conf, 0, sizeof(struct triggerinout));
1466         triggerinout_conf.trgout_bytrigger = 1;
1467         triggerinout_conf.trgout_enable = 1;
1468
1469         sigma_write_register(WRITE_TRIGGER_OPTION,
1470                              (uint8_t *) &triggerinout_conf,
1471                              sizeof(struct triggerinout), devc);
1472
1473         /* Go back to normal mode. */
1474         sigma_set_register(WRITE_TRIGGER_SELECT1, triggerselect, devc);
1475
1476         /* Set clock select register. */
1477         if (devc->cur_samplerate == SR_MHZ(200))
1478                 /* Enable 4 channels. */
1479                 sigma_set_register(WRITE_CLOCK_SELECT, 0xf0, devc);
1480         else if (devc->cur_samplerate == SR_MHZ(100))
1481                 /* Enable 8 channels. */
1482                 sigma_set_register(WRITE_CLOCK_SELECT, 0x00, devc);
1483         else {
1484                 /*
1485                  * 50 MHz mode (or fraction thereof). Any fraction down to
1486                  * 50 MHz / 256 can be used, but is not supported by sigrok API.
1487                  */
1488                 frac = SR_MHZ(50) / devc->cur_samplerate - 1;
1489
1490                 clockselect.async = 0;
1491                 clockselect.fraction = frac;
1492                 clockselect.disabled_channels = 0;
1493
1494                 sigma_write_register(WRITE_CLOCK_SELECT,
1495                                      (uint8_t *) &clockselect,
1496                                      sizeof(clockselect), devc);
1497         }
1498
1499         /* Setup maximum post trigger time. */
1500         sigma_set_register(WRITE_POST_TRIGGER,
1501                            (devc->capture_ratio * 255) / 100, devc);
1502
1503         /* Start acqusition. */
1504         gettimeofday(&devc->start_tv, 0);
1505         sigma_set_register(WRITE_MODE, 0x0d, devc);
1506
1507         devc->cb_data = cb_data;
1508
1509         /* Send header packet to the session bus. */
1510         std_session_send_df_header(sdi, LOG_PREFIX);
1511
1512         /* Add capture source. */
1513         sr_session_source_add(sdi->session, -1, 0, 10, receive_data, (void *)sdi);
1514
1515         devc->state.state = SIGMA_CAPTURE;
1516
1517         return SR_OK;
1518 }
1519
1520 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
1521 {
1522         struct dev_context *devc;
1523
1524         (void)cb_data;
1525
1526         devc = sdi->priv;
1527         devc->state.state = SIGMA_IDLE;
1528
1529         sr_session_source_remove(sdi->session, -1);
1530
1531         return SR_OK;
1532 }
1533
1534 SR_PRIV struct sr_dev_driver asix_sigma_driver_info = {
1535         .name = "asix-sigma",
1536         .longname = "ASIX SIGMA/SIGMA2",
1537         .api_version = 1,
1538         .init = init,
1539         .cleanup = cleanup,
1540         .scan = scan,
1541         .dev_list = dev_list,
1542         .dev_clear = dev_clear,
1543         .config_get = config_get,
1544         .config_set = config_set,
1545         .config_list = config_list,
1546         .dev_open = dev_open,
1547         .dev_close = dev_close,
1548         .dev_acquisition_start = dev_acquisition_start,
1549         .dev_acquisition_stop = dev_acquisition_stop,
1550         .context = NULL,
1551 };