]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/asix-sigma.c
Build: Include <config.h> first in all source files
[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[] = {
94         /* 50 MHz, supports 8 bit fractions */
95         FIRMWARE_DIR "/asix-sigma-50.fw",
96         /* 100 MHz */
97         FIRMWARE_DIR "/asix-sigma-100.fw",
98         /* 200 MHz */
99         FIRMWARE_DIR "/asix-sigma-200.fw",
100         /* Synchronous clock from pin */
101         FIRMWARE_DIR "/asix-sigma-50sync.fw",
102         /* Frequency counter */
103         FIRMWARE_DIR "/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(const char *filename,
512                               uint8_t **bb_cmd, gsize *bb_cmd_size)
513 {
514         GMappedFile *file;
515         GError *error;
516         gsize i, file_size, bb_size;
517         gchar *firmware;
518         uint8_t *bb_stream, *bbs;
519         uint32_t imm;
520         int bit, v;
521         int ret = SR_OK;
522
523         /*
524          * Map the file and make the mapped buffer writable.
525          * NOTE: Using writable=TRUE does _NOT_ mean that file that is mapped
526          *       will be modified. It will not be modified until someone uses
527          *       g_file_set_contents() on it.
528          */
529         error = NULL;
530         file = g_mapped_file_new(filename, TRUE, &error);
531         g_assert_no_error(error);
532
533         file_size = g_mapped_file_get_length(file);
534         firmware = g_mapped_file_get_contents(file);
535         g_assert(firmware);
536
537         /* Weird magic transformation below, I have no idea what it does. */
538         imm = 0x3f6df2ab;
539         for (i = 0; i < file_size; i++) {
540                 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
541                 firmware[i] ^= imm & 0xff;
542         }
543
544         /*
545          * Now that the firmware is "transformed", we will transcribe the
546          * firmware blob into a sequence of toggles of the Dx wires. This
547          * sequence will be fed directly into the Sigma, which must be in
548          * the FPGA bitbang programming mode.
549          */
550
551         /* Each bit of firmware is transcribed as two toggles of Dx wires. */
552         bb_size = file_size * 8 * 2;
553         bb_stream = (uint8_t *)g_try_malloc(bb_size);
554         if (!bb_stream) {
555                 sr_err("%s: Failed to allocate bitbang stream", __func__);
556                 ret = SR_ERR_MALLOC;
557                 goto exit;
558         }
559
560         bbs = bb_stream;
561         for (i = 0; i < file_size; i++) {
562                 for (bit = 7; bit >= 0; bit--) {
563                         v = (firmware[i] & (1 << bit)) ? 0x40 : 0x00;
564                         *bbs++ = v | 0x01;
565                         *bbs++ = v;
566                 }
567         }
568
569         /* The transformation completed successfully, return the result. */
570         *bb_cmd = bb_stream;
571         *bb_cmd_size = bb_size;
572
573 exit:
574         g_mapped_file_unref(file);
575         return ret;
576 }
577
578 static int upload_firmware(int firmware_idx, struct dev_context *devc)
579 {
580         int ret;
581         unsigned char *buf;
582         unsigned char pins;
583         size_t buf_size;
584         const char *firmware = sigma_firmware_files[firmware_idx];
585         struct ftdi_context *ftdic = &devc->ftdic;
586
587         /* Make sure it's an ASIX SIGMA. */
588         ret = ftdi_usb_open_desc(ftdic, USB_VENDOR, USB_PRODUCT,
589                                  USB_DESCRIPTION, NULL);
590         if (ret < 0) {
591                 sr_err("ftdi_usb_open failed: %s",
592                        ftdi_get_error_string(ftdic));
593                 return 0;
594         }
595
596         ret = ftdi_set_bitmode(ftdic, 0xdf, BITMODE_BITBANG);
597         if (ret < 0) {
598                 sr_err("ftdi_set_bitmode failed: %s",
599                        ftdi_get_error_string(ftdic));
600                 return 0;
601         }
602
603         /* Four times the speed of sigmalogan - Works well. */
604         ret = ftdi_set_baudrate(ftdic, 750 * 1000);
605         if (ret < 0) {
606                 sr_err("ftdi_set_baudrate failed: %s",
607                        ftdi_get_error_string(ftdic));
608                 return 0;
609         }
610
611         /* Initialize the FPGA for firmware upload. */
612         ret = sigma_fpga_init_bitbang(devc);
613         if (ret)
614                 return ret;
615
616         /* Prepare firmware. */
617         ret = sigma_fw_2_bitbang(firmware, &buf, &buf_size);
618         if (ret != SR_OK) {
619                 sr_err("An error occurred while reading the firmware: %s",
620                        firmware);
621                 return ret;
622         }
623
624         /* Upload firmware. */
625         sr_info("Uploading firmware file '%s'.", firmware);
626         sigma_write(buf, buf_size, devc);
627
628         g_free(buf);
629
630         ret = ftdi_set_bitmode(ftdic, 0x00, BITMODE_RESET);
631         if (ret < 0) {
632                 sr_err("ftdi_set_bitmode failed: %s",
633                        ftdi_get_error_string(ftdic));
634                 return SR_ERR;
635         }
636
637         ftdi_usb_purge_buffers(ftdic);
638
639         /* Discard garbage. */
640         while (sigma_read(&pins, 1, devc) == 1)
641                 ;
642
643         /* Initialize the FPGA for logic-analyzer mode. */
644         ret = sigma_fpga_init_la(devc);
645         if (ret != SR_OK)
646                 return ret;
647
648         devc->cur_firmware = firmware_idx;
649
650         sr_info("Firmware uploaded.");
651
652         return SR_OK;
653 }
654
655 static int dev_open(struct sr_dev_inst *sdi)
656 {
657         struct dev_context *devc;
658         int ret;
659
660         devc = sdi->priv;
661
662         /* Make sure it's an ASIX SIGMA. */
663         if ((ret = ftdi_usb_open_desc(&devc->ftdic,
664                 USB_VENDOR, USB_PRODUCT, USB_DESCRIPTION, NULL)) < 0) {
665
666                 sr_err("ftdi_usb_open failed: %s",
667                        ftdi_get_error_string(&devc->ftdic));
668
669                 return 0;
670         }
671
672         sdi->status = SR_ST_ACTIVE;
673
674         return SR_OK;
675 }
676
677 static int set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
678 {
679         struct dev_context *devc;
680         unsigned int i;
681         int ret;
682
683         devc = sdi->priv;
684         ret = SR_OK;
685
686         for (i = 0; i < ARRAY_SIZE(samplerates); i++) {
687                 if (samplerates[i] == samplerate)
688                         break;
689         }
690         if (samplerates[i] == 0)
691                 return SR_ERR_SAMPLERATE;
692
693         if (samplerate <= SR_MHZ(50)) {
694                 ret = upload_firmware(0, devc);
695                 devc->num_channels = 16;
696         } else if (samplerate == SR_MHZ(100)) {
697                 ret = upload_firmware(1, devc);
698                 devc->num_channels = 8;
699         } else if (samplerate == SR_MHZ(200)) {
700                 ret = upload_firmware(2, devc);
701                 devc->num_channels = 4;
702         }
703
704         if (ret == SR_OK) {
705                 devc->cur_samplerate = samplerate;
706                 devc->period_ps = 1000000000000ULL / samplerate;
707                 devc->samples_per_event = 16 / devc->num_channels;
708                 devc->state.state = SIGMA_IDLE;
709         }
710
711         return ret;
712 }
713
714 /*
715  * In 100 and 200 MHz mode, only a single pin rising/falling can be
716  * set as trigger. In other modes, two rising/falling triggers can be set,
717  * in addition to value/mask trigger for any number of channels.
718  *
719  * The Sigma supports complex triggers using boolean expressions, but this
720  * has not been implemented yet.
721  */
722 static int convert_trigger(const struct sr_dev_inst *sdi)
723 {
724         struct dev_context *devc;
725         struct sr_trigger *trigger;
726         struct sr_trigger_stage *stage;
727         struct sr_trigger_match *match;
728         const GSList *l, *m;
729         int channelbit, trigger_set;
730
731         devc = sdi->priv;
732         memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
733         if (!(trigger = sr_session_trigger_get(sdi->session)))
734                 return SR_OK;
735
736         trigger_set = 0;
737         for (l = trigger->stages; l; l = l->next) {
738                 stage = l->data;
739                 for (m = stage->matches; m; m = m->next) {
740                         match = m->data;
741                         if (!match->channel->enabled)
742                                 /* Ignore disabled channels with a trigger. */
743                                 continue;
744                         channelbit = 1 << (match->channel->index);
745                         if (devc->cur_samplerate >= SR_MHZ(100)) {
746                                 /* Fast trigger support. */
747                                 if (trigger_set) {
748                                         sr_err("Only a single pin trigger is "
749                                                         "supported in 100 and 200MHz mode.");
750                                         return SR_ERR;
751                                 }
752                                 if (match->match == SR_TRIGGER_FALLING)
753                                         devc->trigger.fallingmask |= channelbit;
754                                 else if (match->match == SR_TRIGGER_RISING)
755                                         devc->trigger.risingmask |= channelbit;
756                                 else {
757                                         sr_err("Only rising/falling trigger is "
758                                                         "supported in 100 and 200MHz mode.");
759                                         return SR_ERR;
760                                 }
761
762                                 ++trigger_set;
763                         } else {
764                                 /* Simple trigger support (event). */
765                                 if (match->match == SR_TRIGGER_ONE) {
766                                         devc->trigger.simplevalue |= channelbit;
767                                         devc->trigger.simplemask |= channelbit;
768                                 }
769                                 else if (match->match == SR_TRIGGER_ZERO) {
770                                         devc->trigger.simplevalue &= ~channelbit;
771                                         devc->trigger.simplemask |= channelbit;
772                                 }
773                                 else if (match->match == SR_TRIGGER_FALLING) {
774                                         devc->trigger.fallingmask |= channelbit;
775                                         ++trigger_set;
776                                 }
777                                 else if (match->match == SR_TRIGGER_RISING) {
778                                         devc->trigger.risingmask |= channelbit;
779                                         ++trigger_set;
780                                 }
781
782                                 /*
783                                  * Actually, Sigma supports 2 rising/falling triggers,
784                                  * but they are ORed and the current trigger syntax
785                                  * does not permit ORed triggers.
786                                  */
787                                 if (trigger_set > 1) {
788                                         sr_err("Only 1 rising/falling trigger "
789                                                    "is supported.");
790                                         return SR_ERR;
791                                 }
792                         }
793                 }
794         }
795
796         return SR_OK;
797 }
798
799 static int dev_close(struct sr_dev_inst *sdi)
800 {
801         struct dev_context *devc;
802
803         devc = sdi->priv;
804
805         /* TODO */
806         if (sdi->status == SR_ST_ACTIVE)
807                 ftdi_usb_close(&devc->ftdic);
808
809         sdi->status = SR_ST_INACTIVE;
810
811         return SR_OK;
812 }
813
814 static int cleanup(const struct sr_dev_driver *di)
815 {
816         return dev_clear(di);
817 }
818
819 static int config_get(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
820                 const struct sr_channel_group *cg)
821 {
822         struct dev_context *devc;
823
824         (void)cg;
825
826         if (!sdi)
827                 return SR_ERR;
828         devc = sdi->priv;
829
830         switch (key) {
831         case SR_CONF_SAMPLERATE:
832                 *data = g_variant_new_uint64(devc->cur_samplerate);
833                 break;
834         case SR_CONF_LIMIT_MSEC:
835                 *data = g_variant_new_uint64(devc->limit_msec);
836                 break;
837         case SR_CONF_CAPTURE_RATIO:
838                 *data = g_variant_new_uint64(devc->capture_ratio);
839                 break;
840         default:
841                 return SR_ERR_NA;
842         }
843
844         return SR_OK;
845 }
846
847 static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi,
848                 const struct sr_channel_group *cg)
849 {
850         struct dev_context *devc;
851         uint64_t tmp;
852         int ret;
853
854         (void)cg;
855
856         if (sdi->status != SR_ST_ACTIVE)
857                 return SR_ERR_DEV_CLOSED;
858
859         devc = sdi->priv;
860
861         ret = SR_OK;
862         switch (key) {
863         case SR_CONF_SAMPLERATE:
864                 ret = set_samplerate(sdi, g_variant_get_uint64(data));
865                 break;
866         case SR_CONF_LIMIT_MSEC:
867                 tmp = g_variant_get_uint64(data);
868                 if (tmp > 0)
869                         devc->limit_msec = g_variant_get_uint64(data);
870                 else
871                         ret = SR_ERR;
872                 break;
873         case SR_CONF_LIMIT_SAMPLES:
874                 tmp = g_variant_get_uint64(data);
875                 devc->limit_msec = tmp * 1000 / devc->cur_samplerate;
876                 break;
877         case SR_CONF_CAPTURE_RATIO:
878                 tmp = g_variant_get_uint64(data);
879                 if (tmp <= 100)
880                         devc->capture_ratio = tmp;
881                 else
882                         ret = SR_ERR;
883                 break;
884         default:
885                 ret = SR_ERR_NA;
886         }
887
888         return ret;
889 }
890
891 static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
892                 const struct sr_channel_group *cg)
893 {
894         GVariant *gvar;
895         GVariantBuilder gvb;
896
897         (void)cg;
898
899         switch (key) {
900         case SR_CONF_DEVICE_OPTIONS:
901                 if (!sdi)
902                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
903                                         drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
904                 else
905                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
906                                         devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
907                 break;
908         case SR_CONF_SAMPLERATE:
909                 g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
910                 gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), samplerates,
911                                 ARRAY_SIZE(samplerates), sizeof(uint64_t));
912                 g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
913                 *data = g_variant_builder_end(&gvb);
914                 break;
915         case SR_CONF_TRIGGER_MATCH:
916                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
917                                 trigger_matches, ARRAY_SIZE(trigger_matches),
918                                 sizeof(int32_t));
919                 break;
920         default:
921                 return SR_ERR_NA;
922         }
923
924         return SR_OK;
925 }
926
927 /* Software trigger to determine exact trigger position. */
928 static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
929                               struct sigma_trigger *t)
930 {
931         int i;
932         uint16_t sample = 0;
933
934         for (i = 0; i < 8; ++i) {
935                 if (i > 0)
936                         last_sample = sample;
937                 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
938
939                 /* Simple triggers. */
940                 if ((sample & t->simplemask) != t->simplevalue)
941                         continue;
942
943                 /* Rising edge. */
944                 if (((last_sample & t->risingmask) != 0) ||
945                     ((sample & t->risingmask) != t->risingmask))
946                         continue;
947
948                 /* Falling edge. */
949                 if ((last_sample & t->fallingmask) != t->fallingmask ||
950                     (sample & t->fallingmask) != 0)
951                         continue;
952
953                 break;
954         }
955
956         /* If we did not match, return original trigger pos. */
957         return i & 0x7;
958 }
959
960 /*
961  * Return the timestamp of "DRAM cluster".
962  */
963 static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
964 {
965         return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
966 }
967
968 static void sigma_decode_dram_cluster(struct sigma_dram_cluster *dram_cluster,
969                                       unsigned int events_in_cluster,
970                                       unsigned int triggered,
971                                       struct sr_dev_inst *sdi)
972 {
973         struct dev_context *devc = sdi->priv;
974         struct sigma_state *ss = &devc->state;
975         struct sr_datafeed_packet packet;
976         struct sr_datafeed_logic logic;
977         uint16_t tsdiff, ts;
978         uint8_t samples[2048];
979         unsigned int i;
980
981         ts = sigma_dram_cluster_ts(dram_cluster);
982         tsdiff = ts - ss->lastts;
983         ss->lastts = ts;
984
985         packet.type = SR_DF_LOGIC;
986         packet.payload = &logic;
987         logic.unitsize = 2;
988         logic.data = samples;
989
990         /*
991          * First of all, send Sigrok a copy of the last sample from
992          * previous cluster as many times as needed to make up for
993          * the differential characteristics of data we get from the
994          * Sigma. Sigrok needs one sample of data per period.
995          *
996          * One DRAM cluster contains a timestamp and seven samples,
997          * the units of timestamp are "devc->period_ps" , the first
998          * sample in the cluster happens at the time of the timestamp
999          * and the remaining samples happen at timestamp +1...+6 .
1000          */
1001         for (ts = 0; ts < tsdiff - (EVENTS_PER_CLUSTER - 1); ts++) {
1002                 i = ts % 1024;
1003                 samples[2 * i + 0] = ss->lastsample & 0xff;
1004                 samples[2 * i + 1] = ss->lastsample >> 8;
1005
1006                 /*
1007                  * If we have 1024 samples ready or we're at the
1008                  * end of submitting the padding samples, submit
1009                  * the packet to Sigrok.
1010                  */
1011                 if ((i == 1023) || (ts == (tsdiff - EVENTS_PER_CLUSTER))) {
1012                         logic.length = (i + 1) * logic.unitsize;
1013                         sr_session_send(sdi, &packet);
1014                 }
1015         }
1016
1017         /*
1018          * Parse the samples in current cluster and prepare them
1019          * to be submitted to Sigrok.
1020          */
1021         for (i = 0; i < events_in_cluster; i++) {
1022                 samples[2 * i + 1] = dram_cluster->samples[i].sample_lo;
1023                 samples[2 * i + 0] = dram_cluster->samples[i].sample_hi;
1024         }
1025
1026         /* Send data up to trigger point (if triggered). */
1027         int trigger_offset = 0;
1028         if (triggered) {
1029                 /*
1030                  * Trigger is not always accurate to sample because of
1031                  * pipeline delay. However, it always triggers before
1032                  * the actual event. We therefore look at the next
1033                  * samples to pinpoint the exact position of the trigger.
1034                  */
1035                 trigger_offset = get_trigger_offset(samples,
1036                                         ss->lastsample, &devc->trigger);
1037
1038                 if (trigger_offset > 0) {
1039                         packet.type = SR_DF_LOGIC;
1040                         logic.length = trigger_offset * logic.unitsize;
1041                         sr_session_send(sdi, &packet);
1042                         events_in_cluster -= trigger_offset;
1043                 }
1044
1045                 /* Only send trigger if explicitly enabled. */
1046                 if (devc->use_triggers) {
1047                         packet.type = SR_DF_TRIGGER;
1048                         sr_session_send(sdi, &packet);
1049                 }
1050         }
1051
1052         if (events_in_cluster > 0) {
1053                 packet.type = SR_DF_LOGIC;
1054                 logic.length = events_in_cluster * logic.unitsize;
1055                 logic.data = samples + (trigger_offset * logic.unitsize);
1056                 sr_session_send(sdi, &packet);
1057         }
1058
1059         ss->lastsample =
1060                 samples[2 * (events_in_cluster - 1) + 0] |
1061                 (samples[2 * (events_in_cluster - 1) + 1] << 8);
1062
1063 }
1064
1065 /*
1066  * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1067  * Each event is 20ns apart, and can contain multiple samples.
1068  *
1069  * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1070  * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1071  * For 50 MHz and below, events contain one sample for each channel,
1072  * spread 20 ns apart.
1073  */
1074 static int decode_chunk_ts(struct sigma_dram_line *dram_line,
1075                            uint16_t events_in_line,
1076                            uint32_t trigger_event,
1077                            struct sr_dev_inst *sdi)
1078 {
1079         struct sigma_dram_cluster *dram_cluster;
1080         struct dev_context *devc = sdi->priv;
1081         unsigned int clusters_in_line =
1082                 (events_in_line + (EVENTS_PER_CLUSTER - 1)) / EVENTS_PER_CLUSTER;
1083         unsigned int events_in_cluster;
1084         unsigned int i;
1085         uint32_t trigger_cluster = ~0, triggered = 0;
1086
1087         /* Check if trigger is in this chunk. */
1088         if (trigger_event < (64 * 7)) {
1089                 if (devc->cur_samplerate <= SR_MHZ(50)) {
1090                         trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1091                                              trigger_event);
1092                 }
1093
1094                 /* Find in which cluster the trigger occurred. */
1095                 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1096         }
1097
1098         /* For each full DRAM cluster. */
1099         for (i = 0; i < clusters_in_line; i++) {
1100                 dram_cluster = &dram_line->cluster[i];
1101
1102                 /* The last cluster might not be full. */
1103                 if ((i == clusters_in_line - 1) &&
1104                     (events_in_line % EVENTS_PER_CLUSTER)) {
1105                         events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1106                 } else {
1107                         events_in_cluster = EVENTS_PER_CLUSTER;
1108                 }
1109
1110                 triggered = (i == trigger_cluster);
1111                 sigma_decode_dram_cluster(dram_cluster, events_in_cluster,
1112                                           triggered, sdi);
1113         }
1114
1115         return SR_OK;
1116 }
1117
1118 static int download_capture(struct sr_dev_inst *sdi)
1119 {
1120         struct dev_context *devc = sdi->priv;
1121         const uint32_t chunks_per_read = 32;
1122         struct sigma_dram_line *dram_line;
1123         int bufsz;
1124         uint32_t stoppos, triggerpos;
1125         struct sr_datafeed_packet packet;
1126         uint8_t modestatus;
1127
1128         uint32_t i;
1129         uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1130         uint32_t dl_events_in_line = 64 * 7;
1131         uint32_t trg_line = ~0, trg_event = ~0;
1132
1133         dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1134         if (!dram_line)
1135                 return FALSE;
1136
1137         sr_info("Downloading sample data.");
1138
1139         /* Stop acquisition. */
1140         sigma_set_register(WRITE_MODE, 0x11, devc);
1141
1142         /* Set SDRAM Read Enable. */
1143         sigma_set_register(WRITE_MODE, 0x02, devc);
1144
1145         /* Get the current position. */
1146         sigma_read_pos(&stoppos, &triggerpos, devc);
1147
1148         /* Check if trigger has fired. */
1149         modestatus = sigma_get_register(READ_MODE, devc);
1150         if (modestatus & 0x20) {
1151                 trg_line = triggerpos >> 9;
1152                 trg_event = triggerpos & 0x1ff;
1153         }
1154
1155         /*
1156          * Determine how many 1024b "DRAM lines" do we need to read from the
1157          * Sigma so we have a complete set of samples. Note that the last
1158          * line can be only partial, containing less than 64 clusters.
1159          */
1160         dl_lines_total = (stoppos >> 9) + 1;
1161
1162         dl_lines_done = 0;
1163
1164         while (dl_lines_total > dl_lines_done) {
1165                 /* We can download only up-to 32 DRAM lines in one go! */
1166                 dl_lines_curr = MIN(chunks_per_read, dl_lines_total);
1167
1168                 bufsz = sigma_read_dram(dl_lines_done, dl_lines_curr,
1169                                         (uint8_t *)dram_line, devc);
1170                 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1171                 (void)bufsz;
1172
1173                 /* This is the first DRAM line, so find the initial timestamp. */
1174                 if (dl_lines_done == 0) {
1175                         devc->state.lastts =
1176                                 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1177                         devc->state.lastsample = 0;
1178                 }
1179
1180                 for (i = 0; i < dl_lines_curr; i++) {
1181                         uint32_t trigger_event = ~0;
1182                         /* The last "DRAM line" can be only partially full. */
1183                         if (dl_lines_done + i == dl_lines_total - 1)
1184                                 dl_events_in_line = stoppos & 0x1ff;
1185
1186                         /* Test if the trigger happened on this line. */
1187                         if (dl_lines_done + i == trg_line)
1188                                 trigger_event = trg_event;
1189
1190                         decode_chunk_ts(dram_line + i, dl_events_in_line,
1191                                         trigger_event, sdi);
1192                 }
1193
1194                 dl_lines_done += dl_lines_curr;
1195         }
1196
1197         /* All done. */
1198         packet.type = SR_DF_END;
1199         sr_session_send(sdi, &packet);
1200
1201         dev_acquisition_stop(sdi, sdi);
1202
1203         g_free(dram_line);
1204
1205         return TRUE;
1206 }
1207
1208 /*
1209  * Handle the Sigma when in CAPTURE mode. This function checks:
1210  * - Sampling time ended
1211  * - DRAM capacity overflow
1212  * This function triggers download of the samples from Sigma
1213  * in case either of the above conditions is true.
1214  */
1215 static int sigma_capture_mode(struct sr_dev_inst *sdi)
1216 {
1217         struct dev_context *devc = sdi->priv;
1218
1219         uint64_t running_msec;
1220         struct timeval tv;
1221
1222         uint32_t stoppos, triggerpos;
1223
1224         /* Check if the selected sampling duration passed. */
1225         gettimeofday(&tv, 0);
1226         running_msec = (tv.tv_sec - devc->start_tv.tv_sec) * 1000 +
1227                        (tv.tv_usec - devc->start_tv.tv_usec) / 1000;
1228         if (running_msec >= devc->limit_msec)
1229                 return download_capture(sdi);
1230
1231         /* Get the position in DRAM to which the FPGA is writing now. */
1232         sigma_read_pos(&stoppos, &triggerpos, devc);
1233         /* Test if DRAM is full and if so, download the data. */
1234         if ((stoppos >> 9) == 32767)
1235                 return download_capture(sdi);
1236
1237         return TRUE;
1238 }
1239
1240 static int receive_data(int fd, int revents, void *cb_data)
1241 {
1242         struct sr_dev_inst *sdi;
1243         struct dev_context *devc;
1244
1245         (void)fd;
1246         (void)revents;
1247
1248         sdi = cb_data;
1249         devc = sdi->priv;
1250
1251         if (devc->state.state == SIGMA_IDLE)
1252                 return TRUE;
1253
1254         if (devc->state.state == SIGMA_CAPTURE)
1255                 return sigma_capture_mode(sdi);
1256
1257         return TRUE;
1258 }
1259
1260 /* Build a LUT entry used by the trigger functions. */
1261 static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1262 {
1263         int i, j, k, bit;
1264
1265         /* For each quad channel. */
1266         for (i = 0; i < 4; ++i) {
1267                 entry[i] = 0xffff;
1268
1269                 /* For each bit in LUT. */
1270                 for (j = 0; j < 16; ++j)
1271
1272                         /* For each channel in quad. */
1273                         for (k = 0; k < 4; ++k) {
1274                                 bit = 1 << (i * 4 + k);
1275
1276                                 /* Set bit in entry */
1277                                 if ((mask & bit) &&
1278                                     ((!(value & bit)) !=
1279                                     (!(j & (1 << k)))))
1280                                         entry[i] &= ~(1 << j);
1281                         }
1282         }
1283 }
1284
1285 /* Add a logical function to LUT mask. */
1286 static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1287                                  int index, int neg, uint16_t *mask)
1288 {
1289         int i, j;
1290         int x[2][2], tmp, a, b, aset, bset, rset;
1291
1292         memset(x, 0, 4 * sizeof(int));
1293
1294         /* Trigger detect condition. */
1295         switch (oper) {
1296         case OP_LEVEL:
1297                 x[0][1] = 1;
1298                 x[1][1] = 1;
1299                 break;
1300         case OP_NOT:
1301                 x[0][0] = 1;
1302                 x[1][0] = 1;
1303                 break;
1304         case OP_RISE:
1305                 x[0][1] = 1;
1306                 break;
1307         case OP_FALL:
1308                 x[1][0] = 1;
1309                 break;
1310         case OP_RISEFALL:
1311                 x[0][1] = 1;
1312                 x[1][0] = 1;
1313                 break;
1314         case OP_NOTRISE:
1315                 x[1][1] = 1;
1316                 x[0][0] = 1;
1317                 x[1][0] = 1;
1318                 break;
1319         case OP_NOTFALL:
1320                 x[1][1] = 1;
1321                 x[0][0] = 1;
1322                 x[0][1] = 1;
1323                 break;
1324         case OP_NOTRISEFALL:
1325                 x[1][1] = 1;
1326                 x[0][0] = 1;
1327                 break;
1328         }
1329
1330         /* Transpose if neg is set. */
1331         if (neg) {
1332                 for (i = 0; i < 2; ++i) {
1333                         for (j = 0; j < 2; ++j) {
1334                                 tmp = x[i][j];
1335                                 x[i][j] = x[1-i][1-j];
1336                                 x[1-i][1-j] = tmp;
1337                         }
1338                 }
1339         }
1340
1341         /* Update mask with function. */
1342         for (i = 0; i < 16; ++i) {
1343                 a = (i >> (2 * index + 0)) & 1;
1344                 b = (i >> (2 * index + 1)) & 1;
1345
1346                 aset = (*mask >> i) & 1;
1347                 bset = x[b][a];
1348
1349                 rset = 0;
1350                 if (func == FUNC_AND || func == FUNC_NAND)
1351                         rset = aset & bset;
1352                 else if (func == FUNC_OR || func == FUNC_NOR)
1353                         rset = aset | bset;
1354                 else if (func == FUNC_XOR || func == FUNC_NXOR)
1355                         rset = aset ^ bset;
1356
1357                 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1358                         rset = !rset;
1359
1360                 *mask &= ~(1 << i);
1361
1362                 if (rset)
1363                         *mask |= 1 << i;
1364         }
1365 }
1366
1367 /*
1368  * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1369  * simple pin change and state triggers. Only two transitions (rise/fall) can be
1370  * set at any time, but a full mask and value can be set (0/1).
1371  */
1372 static int build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1373 {
1374         int i,j;
1375         uint16_t masks[2] = { 0, 0 };
1376
1377         memset(lut, 0, sizeof(struct triggerlut));
1378
1379         /* Constant for simple triggers. */
1380         lut->m4 = 0xa000;
1381
1382         /* Value/mask trigger support. */
1383         build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1384                         lut->m2d);
1385
1386         /* Rise/fall trigger support. */
1387         for (i = 0, j = 0; i < 16; ++i) {
1388                 if (devc->trigger.risingmask & (1 << i) ||
1389                     devc->trigger.fallingmask & (1 << i))
1390                         masks[j++] = 1 << i;
1391         }
1392
1393         build_lut_entry(masks[0], masks[0], lut->m0d);
1394         build_lut_entry(masks[1], masks[1], lut->m1d);
1395
1396         /* Add glue logic */
1397         if (masks[0] || masks[1]) {
1398                 /* Transition trigger. */
1399                 if (masks[0] & devc->trigger.risingmask)
1400                         add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1401                 if (masks[0] & devc->trigger.fallingmask)
1402                         add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1403                 if (masks[1] & devc->trigger.risingmask)
1404                         add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1405                 if (masks[1] & devc->trigger.fallingmask)
1406                         add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1407         } else {
1408                 /* Only value/mask trigger. */
1409                 lut->m3 = 0xffff;
1410         }
1411
1412         /* Triggertype: event. */
1413         lut->params.selres = 3;
1414
1415         return SR_OK;
1416 }
1417
1418 static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data)
1419 {
1420         struct dev_context *devc;
1421         struct clockselect_50 clockselect;
1422         int frac, triggerpin, ret;
1423         uint8_t triggerselect = 0;
1424         struct triggerinout triggerinout_conf;
1425         struct triggerlut lut;
1426
1427         if (sdi->status != SR_ST_ACTIVE)
1428                 return SR_ERR_DEV_CLOSED;
1429
1430         devc = sdi->priv;
1431
1432         if (convert_trigger(sdi) != SR_OK) {
1433                 sr_err("Failed to configure triggers.");
1434                 return SR_ERR;
1435         }
1436
1437         /* If the samplerate has not been set, default to 200 kHz. */
1438         if (devc->cur_firmware == -1) {
1439                 if ((ret = set_samplerate(sdi, SR_KHZ(200))) != SR_OK)
1440                         return ret;
1441         }
1442
1443         /* Enter trigger programming mode. */
1444         sigma_set_register(WRITE_TRIGGER_SELECT1, 0x20, devc);
1445
1446         /* 100 and 200 MHz mode. */
1447         if (devc->cur_samplerate >= SR_MHZ(100)) {
1448                 sigma_set_register(WRITE_TRIGGER_SELECT1, 0x81, devc);
1449
1450                 /* Find which pin to trigger on from mask. */
1451                 for (triggerpin = 0; triggerpin < 8; ++triggerpin)
1452                         if ((devc->trigger.risingmask | devc->trigger.fallingmask) &
1453                             (1 << triggerpin))
1454                                 break;
1455
1456                 /* Set trigger pin and light LED on trigger. */
1457                 triggerselect = (1 << LEDSEL1) | (triggerpin & 0x7);
1458
1459                 /* Default rising edge. */
1460                 if (devc->trigger.fallingmask)
1461                         triggerselect |= 1 << 3;
1462
1463         /* All other modes. */
1464         } else if (devc->cur_samplerate <= SR_MHZ(50)) {
1465                 build_basic_trigger(&lut, devc);
1466
1467                 sigma_write_trigger_lut(&lut, devc);
1468
1469                 triggerselect = (1 << LEDSEL1) | (1 << LEDSEL0);
1470         }
1471
1472         /* Setup trigger in and out pins to default values. */
1473         memset(&triggerinout_conf, 0, sizeof(struct triggerinout));
1474         triggerinout_conf.trgout_bytrigger = 1;
1475         triggerinout_conf.trgout_enable = 1;
1476
1477         sigma_write_register(WRITE_TRIGGER_OPTION,
1478                              (uint8_t *) &triggerinout_conf,
1479                              sizeof(struct triggerinout), devc);
1480
1481         /* Go back to normal mode. */
1482         sigma_set_register(WRITE_TRIGGER_SELECT1, triggerselect, devc);
1483
1484         /* Set clock select register. */
1485         if (devc->cur_samplerate == SR_MHZ(200))
1486                 /* Enable 4 channels. */
1487                 sigma_set_register(WRITE_CLOCK_SELECT, 0xf0, devc);
1488         else if (devc->cur_samplerate == SR_MHZ(100))
1489                 /* Enable 8 channels. */
1490                 sigma_set_register(WRITE_CLOCK_SELECT, 0x00, devc);
1491         else {
1492                 /*
1493                  * 50 MHz mode (or fraction thereof). Any fraction down to
1494                  * 50 MHz / 256 can be used, but is not supported by sigrok API.
1495                  */
1496                 frac = SR_MHZ(50) / devc->cur_samplerate - 1;
1497
1498                 clockselect.async = 0;
1499                 clockselect.fraction = frac;
1500                 clockselect.disabled_channels = 0;
1501
1502                 sigma_write_register(WRITE_CLOCK_SELECT,
1503                                      (uint8_t *) &clockselect,
1504                                      sizeof(clockselect), devc);
1505         }
1506
1507         /* Setup maximum post trigger time. */
1508         sigma_set_register(WRITE_POST_TRIGGER,
1509                            (devc->capture_ratio * 255) / 100, devc);
1510
1511         /* Start acqusition. */
1512         gettimeofday(&devc->start_tv, 0);
1513         sigma_set_register(WRITE_MODE, 0x0d, devc);
1514
1515         devc->cb_data = cb_data;
1516
1517         /* Send header packet to the session bus. */
1518         std_session_send_df_header(sdi, LOG_PREFIX);
1519
1520         /* Add capture source. */
1521         sr_session_source_add(sdi->session, -1, 0, 10, receive_data, (void *)sdi);
1522
1523         devc->state.state = SIGMA_CAPTURE;
1524
1525         return SR_OK;
1526 }
1527
1528 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
1529 {
1530         struct dev_context *devc;
1531
1532         (void)cb_data;
1533
1534         devc = sdi->priv;
1535         devc->state.state = SIGMA_IDLE;
1536
1537         sr_session_source_remove(sdi->session, -1);
1538
1539         return SR_OK;
1540 }
1541
1542 SR_PRIV struct sr_dev_driver asix_sigma_driver_info = {
1543         .name = "asix-sigma",
1544         .longname = "ASIX SIGMA/SIGMA2",
1545         .api_version = 1,
1546         .init = init,
1547         .cleanup = cleanup,
1548         .scan = scan,
1549         .dev_list = dev_list,
1550         .dev_clear = dev_clear,
1551         .config_get = config_get,
1552         .config_set = config_set,
1553         .config_list = config_list,
1554         .dev_open = dev_open,
1555         .dev_close = dev_close,
1556         .dev_acquisition_start = dev_acquisition_start,
1557         .dev_acquisition_stop = dev_acquisition_stop,
1558         .context = NULL,
1559 };