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