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