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