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