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