]> sigrok.org Git - libsigrok.git/blob - hardware/chronovu-la8/chronovu-la8.c
22164cfe8693a5b676fad91ea5a9f3ada3cfb088
[libsigrok.git] / hardware / chronovu-la8 / chronovu-la8.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2011 Uwe Hermann <uwe@hermann-uwe.de>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <ftdi.h>
22 #include <glib.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include "sigrok.h"
26 #include "sigrok-internal.h"
27
28 #define USB_VENDOR_ID                   0x0403
29 #define USB_PRODUCT_ID                  0x6001
30 #define USB_DESCRIPTION                 "ChronoVu LA8"
31 #define USB_VENDOR_NAME                 "ChronoVu"
32 #define USB_MODEL_NAME                  "LA8"
33 #define USB_MODEL_VERSION               ""
34
35 #define NUM_PROBES                      8
36 #define TRIGGER_TYPES                   "01"
37 #define SDRAM_SIZE                      (8 * 1024 * 1024)
38 #define MIN_NUM_SAMPLES                 1
39
40 #define BS                              4096 /* Block size */
41 #define NUM_BLOCKS                      2048 /* Number of blocks */
42
43 static GSList *dev_insts = NULL;
44
45 static const char *probe_names[NUM_PROBES + 1] = {
46         "0",
47         "1",
48         "2",
49         "3",
50         "4",
51         "5",
52         "6",
53         "7",
54         NULL,
55 };
56
57 struct la8 {
58         /** FTDI device context (used by libftdi). */
59         struct ftdi_context *ftdic;
60
61         /** The currently configured samplerate of the device. */
62         uint64_t cur_samplerate;
63
64         /** The current sampling limit (in ms). */
65         uint64_t limit_msec;
66
67         /** The current sampling limit (in number of samples). */
68         uint64_t limit_samples;
69
70         /** TODO */
71         gpointer session_id;
72
73         /**
74          * A buffer containing some (mangled) samples from the device.
75          * Format: Pretty mangled-up (due to hardware reasons), see code.
76          */
77         uint8_t mangled_buf[BS];
78
79         /**
80          * An 8MB buffer where we'll store the de-mangled samples.
81          * Format: Each sample is 1 byte, MSB is channel 7, LSB is channel 0.
82          */
83         uint8_t *final_buf;
84
85         /**
86          * Trigger pattern (MSB = channel 7, LSB = channel 0).
87          * A 1 bit matches a high signal, 0 matches a low signal on a probe.
88          * Only low/high triggers (but not e.g. rising/falling) are supported.
89          */
90         uint8_t trigger_pattern;
91
92         /**
93          * Trigger mask (MSB = channel 7, LSB = channel 0).
94          * A 1 bit means "must match trigger_pattern", 0 means "don't care".
95          */
96         uint8_t trigger_mask;
97
98         /** Time (in seconds) before the trigger times out. */
99         uint64_t trigger_timeout;
100
101         /** Tells us whether an SR_DF_TRIGGER packet was already sent. */
102         int trigger_found;
103
104         /** TODO */
105         time_t done;
106
107         /** Counter/index for the data block to be read. */
108         int block_counter;
109
110         /** The divcount value (determines the sample period) for the LA8. */
111         uint8_t divcount;
112 };
113
114 /* This will be initialized via hw_get_device_info()/SR_DI_SAMPLERATES. */
115 static uint64_t supported_samplerates[255 + 1] = { 0 };
116
117 /*
118  * Min: 1 sample per 0.01us -> sample time is 0.084s, samplerate 100MHz
119  * Max: 1 sample per 2.55us -> sample time is 21.391s, samplerate 392.15kHz
120  */
121 static struct sr_samplerates samplerates = {
122         .low  = 0,
123         .high = 0,
124         .step = 0,
125         .list = supported_samplerates,
126 };
127
128 /* Note: Continuous sampling is not supported by the hardware. */
129 static int capabilities[] = {
130         SR_HWCAP_LOGIC_ANALYZER,
131         SR_HWCAP_SAMPLERATE,
132         SR_HWCAP_LIMIT_MSEC, /* TODO: Not yet implemented. */
133         SR_HWCAP_LIMIT_SAMPLES, /* TODO: Not yet implemented. */
134         0,
135 };
136
137 /* Function prototypes. */
138 static int la8_close_usb_reset_sequencer(struct la8 *la8);
139 static int hw_stop_acquisition(int device_index, gpointer session_data);
140 static int la8_reset(struct la8 *la8);
141
142 static void fill_supported_samplerates_if_needed(void)
143 {
144         int i;
145
146         /* Do nothing if supported_samplerates[] is already filled. */
147         if (supported_samplerates[0] != 0)
148                 return;
149
150         /* Fill supported_samplerates[] with the proper values. */
151         for (i = 0; i < 255; i++)
152                 supported_samplerates[254 - i] = SR_MHZ(100) / (i + 1);
153         supported_samplerates[255] = 0;
154 }
155
156 /**
157  * Check if the given samplerate is supported by the LA8 hardware.
158  *
159  * @param samplerate The samplerate (in Hz) to check.
160  * @return 1 if the samplerate is supported/valid, 0 otherwise.
161  */
162 static int is_valid_samplerate(uint64_t samplerate)
163 {
164         int i;
165
166         fill_supported_samplerates_if_needed();
167
168         for (i = 0; i < 255; i++) {
169                 if (supported_samplerates[i] == samplerate)
170                         return 1;
171         }
172
173         sr_err("la8: %s: invalid samplerate (%" PRIu64 "Hz)",
174                __func__, samplerate);
175
176         return 0;
177 }
178
179 /**
180  * Convert a samplerate (in Hz) to the 'divcount' value the LA8 wants.
181  *
182  * LA8 hardware: sample period = (divcount + 1) * 10ns.
183  * Min. value for divcount: 0x00 (10ns sample period, 100MHz samplerate).
184  * Max. value for divcount: 0xfe (2550ns sample period, 392.15kHz samplerate).
185  *
186  * @param samplerate The samplerate in Hz.
187  * @return The divcount value as needed by the hardware, or 0xff upon errors.
188  */
189 static uint8_t samplerate_to_divcount(uint64_t samplerate)
190 {
191         if (samplerate == 0) {
192                 sr_err("la8: %s: samplerate was 0", __func__);
193                 return 0xff;
194         }
195
196         if (!is_valid_samplerate(samplerate)) {
197                 sr_err("la8: %s: can't get divcount, samplerate invalid",
198                        __func__);
199                 return 0xff;
200         }
201
202         return (SR_MHZ(100) / samplerate) - 1;
203 }
204
205 /**
206  * Write data of a certain length to the LA8's FTDI device.
207  *
208  * @param la8 The LA8 struct containing private per-device-instance data.
209  * @param buf The buffer containing the data to write.
210  * @param size The number of bytes to write.
211  * @return The number of bytes written, or a negative value upon errors.
212  */
213 static int la8_write(struct la8 *la8, uint8_t *buf, int size)
214 {
215         int bytes_written;
216
217         if (!la8) {
218                 sr_err("la8: %s: la8 was NULL", __func__);
219                 return SR_ERR_ARG;
220         }
221
222         if (!la8->ftdic) {
223                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
224                 return SR_ERR_ARG;
225         }
226
227         if (!buf) {
228                 sr_err("la8: %s: buf was NULL", __func__);
229                 return SR_ERR_ARG;
230         }
231
232         if (size < 0) {
233                 sr_err("la8: %s: size was < 0", __func__);
234                 return SR_ERR_ARG;
235         }
236
237         bytes_written = ftdi_write_data(la8->ftdic, buf, size);
238
239         if (bytes_written < 0) {
240                 sr_err("la8: %s: ftdi_write_data: (%d) %s", __func__,
241                        bytes_written, ftdi_get_error_string(la8->ftdic));
242                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
243         } else if (bytes_written != size) {
244                 sr_err("la8: %s: bytes to write: %d, bytes written: %d",
245                        __func__, size, bytes_written);
246                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
247         }
248
249         return bytes_written;
250 }
251
252 /**
253  * Read a certain amount of bytes from the LA8's FTDI device.
254  *
255  * @param la8 The LA8 struct containing private per-device-instance data.
256  * @param buf The buffer where the received data will be stored.
257  * @param size The number of bytes to read.
258  * @return The number of bytes read, or a negative value upon errors.
259  */
260 static int la8_read(struct la8 *la8, uint8_t *buf, int size)
261 {
262         int bytes_read;
263
264         if (!la8) {
265                 sr_err("la8: %s: la8 was NULL", __func__);
266                 return SR_ERR_ARG;
267         }
268
269         if (!la8->ftdic) {
270                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
271                 return SR_ERR_ARG;
272         }
273
274         if (!buf) {
275                 sr_err("la8: %s: buf was NULL", __func__);
276                 return SR_ERR_ARG;
277         }
278
279         if (size <= 0) {
280                 sr_err("la8: %s: size was <= 0", __func__);
281                 return SR_ERR_ARG;
282         }
283
284         bytes_read = ftdi_read_data(la8->ftdic, buf, size);
285
286         if (bytes_read < 0) {
287                 sr_err("la8: %s: ftdi_read_data: (%d) %s", __func__,
288                        bytes_read, ftdi_get_error_string(la8->ftdic));
289         } else if (bytes_read != size) {
290                 // sr_err("la8: %s: bytes to read: %d, bytes read: %d",
291                 //        __func__, size, bytes_read);
292         }
293
294         return bytes_read;
295 }
296
297 static int la8_close(struct la8 *la8)
298 {
299         int ret;
300
301         if (!la8) {
302                 sr_err("la8: %s: la8 was NULL", __func__);
303                 return SR_ERR_ARG;
304         }
305
306         if (!la8->ftdic) {
307                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
308                 return SR_ERR_ARG;
309         }
310
311         if ((ret = ftdi_usb_close(la8->ftdic)) < 0) {
312                 sr_err("la8: %s: ftdi_usb_close: (%d) %s",
313                        __func__, ret, ftdi_get_error_string(la8->ftdic));
314         }
315
316         return ret;
317 }
318
319 /**
320  * Close the ChronoVu LA8 USB port and reset the LA8 sequencer logic.
321  *
322  * @param la8 The LA8 struct containing private per-device-instance data.
323  * @return SR_OK upon success, SR_ERR upon failure.
324  */
325 static int la8_close_usb_reset_sequencer(struct la8 *la8)
326 {
327         /* Magic sequence of bytes for resetting the LA8 sequencer logic. */
328         uint8_t buf[8] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
329         int ret;
330
331         if (!la8) {
332                 sr_err("la8: %s: la8 was NULL", __func__);
333                 return SR_ERR_ARG;
334         }
335
336         if (!la8->ftdic) {
337                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
338                 return SR_ERR_ARG;
339         }
340
341         if (la8->ftdic->usb_dev) {
342                 /* Reset the LA8 sequencer logic, then wait 100ms. */
343                 sr_dbg("la8: resetting sequencer logic");
344                 (void) la8_write(la8, buf, 8); /* Ignore errors. */
345                 g_usleep(100 * 1000);
346
347                 /* Purge FTDI buffers, then reset and close the FTDI device. */
348                 sr_dbg("la8: purging buffers, resetting+closing FTDI device");
349
350                 /* Log errors, but ignore them (i.e., don't abort). */
351                 if ((ret = ftdi_usb_purge_buffers(la8->ftdic)) < 0)
352                         sr_err("la8: %s: ftdi_usb_purge_buffers: (%d) %s",
353                             __func__, ret, ftdi_get_error_string(la8->ftdic));
354                 if ((ret = ftdi_usb_reset(la8->ftdic)) < 0)
355                         sr_err("la8: %s: ftdi_usb_reset: (%d) %s", __func__,
356                                ret, ftdi_get_error_string(la8->ftdic));
357                 if ((ret = ftdi_usb_close(la8->ftdic)) < 0)
358                         sr_err("la8: %s: ftdi_usb_close: (%d) %s", __func__,
359                                ret, ftdi_get_error_string(la8->ftdic));
360         }
361
362         ftdi_free(la8->ftdic); /* Returns void. */
363         la8->ftdic = NULL;
364
365         return SR_OK;
366 }
367
368 /**
369  * Reset the ChronoVu LA8.
370  *
371  * The LA8 must be reset after a failed read/write operation or upon timeouts.
372  *
373  * @param la8 The LA8 struct containing private per-device-instance data.
374  * @return SR_OK upon success, SR_ERR upon failure.
375  */
376 static int la8_reset(struct la8 *la8)
377 {
378         uint8_t buf[BS];
379         time_t done, now;
380         int bytes_read;
381
382         if (!la8) {
383                 sr_err("la8: %s: la8 was NULL", __func__);
384                 return SR_ERR_ARG;
385         }
386
387         if (!la8->ftdic) {
388                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
389                 return SR_ERR_ARG;
390         }
391
392         sr_dbg("la8: resetting the device");
393
394         /*
395          * Purge pending read data from the FTDI hardware FIFO until
396          * no more data is left, or a timeout occurs (after 20s).
397          */
398         done = 20 + time(NULL);
399         do {
400                 /* TODO: Ignore errors? Check for < 0 at least! */
401                 bytes_read = la8_read(la8, (uint8_t *)&buf, BS);
402                 now = time(NULL);
403         } while ((done > now) && (bytes_read > 0));
404
405         /* Reset the LA8 sequencer logic and close the USB port. */
406         (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
407
408         sr_dbg("la8: device reset finished");
409
410         return SR_OK;
411 }
412
413 static int configure_probes(struct la8 *la8, GSList *probes)
414 {
415         struct sr_probe *probe;
416         GSList *l;
417         uint8_t probe_bit;
418         char *tc;
419
420         la8->trigger_pattern = 0;
421         la8->trigger_mask = 0; /* Default to "don't care" for all probes. */
422
423         for (l = probes; l; l = l->next) {
424                 probe = (struct sr_probe *)l->data;
425
426                 if (!probe) {
427                         sr_err("la8: %s: probe was NULL", __func__);
428                         return SR_ERR;
429                 }
430
431                 /* Skip disabled probes. */
432                 if (!probe->enabled)
433                         continue;
434
435                 /* Skip (enabled) probes with no configured trigger. */
436                 if (!probe->trigger)
437                         continue;
438
439                 /* Note: Must only be run if probe->trigger != NULL. */
440                 if (probe->index < 0 || probe->index > 7) {
441                         sr_err("la8: %s: invalid probe index %d, must be "
442                                "between 0 and 7", __func__, probe->index);
443                         return SR_ERR;
444                 }
445
446                 probe_bit = (1 << (probe->index - 1));
447
448                 /* Configure the probe's trigger mask and trigger pattern. */
449                 for (tc = probe->trigger; tc && *tc; tc++) {
450                         la8->trigger_mask |= probe_bit;
451
452                         /* Sanity check, LA8 only supports low/high trigger. */
453                         if (*tc != '0' && *tc != '1') {
454                                 sr_err("la8: %s: invalid trigger '%c', only "
455                                        "'0'/'1' supported", __func__, *tc);
456                                 return SR_ERR;
457                         }
458
459                         if (*tc == '1')
460                                 la8->trigger_pattern |= probe_bit;
461                 }
462         }
463
464         sr_dbg("la8: %s: trigger_mask = 0x%x, trigger_pattern = 0x%x",
465                __func__, la8->trigger_mask, la8->trigger_pattern);
466
467         return SR_OK;
468 }
469
470 static int hw_init(const char *deviceinfo)
471 {
472         int ret;
473         struct sr_dev_inst *sdi;
474         struct la8 *la8;
475
476         /* Avoid compiler errors. */
477         (void)deviceinfo;
478
479         /* Allocate memory for our private driver context. */
480         if (!(la8 = g_try_malloc(sizeof(struct la8)))) {
481                 sr_err("la8: %s: struct la8 malloc failed", __func__);
482                 goto err_free_nothing;
483         }
484
485         /* Set some sane defaults. */
486         la8->ftdic = NULL;
487         la8->cur_samplerate = SR_MHZ(100); /* 100MHz == max. samplerate */
488         la8->limit_msec = 0;
489         la8->limit_samples = 0;
490         la8->session_id = NULL;
491         memset(la8->mangled_buf, 0, BS);
492         la8->final_buf = NULL;
493         la8->trigger_pattern = 0x00; /* Value irrelevant, see trigger_mask. */
494         la8->trigger_mask = 0x00; /* All probes are "don't care". */
495         la8->trigger_timeout = 10; /* Default to 10s trigger timeout. */
496         la8->trigger_found = 0;
497         la8->done = 0;
498         la8->block_counter = 0;
499         la8->divcount = 0; /* 10ns sample period == 100MHz samplerate */
500
501         /* Allocate memory where we'll store the de-mangled data. */
502         if (!(la8->final_buf = g_try_malloc(SDRAM_SIZE))) {
503                 sr_err("la8: %s: final_buf malloc failed", __func__);
504                 goto err_free_la8;
505         }
506
507         /* Allocate memory for the FTDI context (ftdic) and initialize it. */
508         if (!(la8->ftdic = ftdi_new())) {
509                 sr_err("la8: %s: ftdi_new failed", __func__);
510                 goto err_free_final_buf;
511         }
512
513         /* Check for the device and temporarily open it. */
514         if ((ret = ftdi_usb_open_desc(la8->ftdic, USB_VENDOR_ID,
515                         USB_PRODUCT_ID, USB_DESCRIPTION, NULL)) < 0) {
516                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
517                 goto err_free_ftdic;
518         }
519         sr_dbg("la8: found device");
520
521         /* Register the device with libsigrok. */
522         sdi = sr_dev_inst_new(0, SR_ST_INITIALIZING,
523                         USB_VENDOR_NAME, USB_MODEL_NAME, USB_MODEL_VERSION);
524         if (!sdi) {
525                 sr_err("la8: %s: sr_dev_inst_new failed", __func__);
526                 goto err_close_ftdic;
527         }
528
529         sdi->priv = la8;
530
531         dev_insts = g_slist_append(dev_insts, sdi);
532
533         sr_spew("la8: %s finished successfully", __func__);
534
535         /* Close device. We'll reopen it again when we need it. */
536         (void) la8_close(la8); /* Log, but ignore errors. */
537
538         return 1;
539
540 err_close_ftdic:
541         (void) la8_close(la8); /* Log, but ignore errors. */
542 err_free_ftdic:
543         free(la8->ftdic); /* NOT g_free()! */
544 err_free_final_buf:
545         g_free(la8->final_buf);
546 err_free_la8:
547         g_free(la8);
548 err_free_nothing:
549
550         return 0;
551 }
552
553 static int hw_opendev(int device_index)
554 {
555         int ret;
556         struct sr_dev_inst *sdi;
557         struct la8 *la8;
558
559         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
560                 sr_err("la8: %s: sdi was NULL", __func__);
561                 return SR_ERR; /* TODO: SR_ERR_ARG? */
562         }
563
564         if (!(la8 = sdi->priv)) {
565                 sr_err("la8: %s: sdi->priv was NULL", __func__);
566                 return SR_ERR; /* TODO: SR_ERR_ARG? */
567         }
568
569         sr_dbg("la8: opening device");
570
571         /* Open the device. */
572         if ((ret = ftdi_usb_open_desc(la8->ftdic, USB_VENDOR_ID,
573                         USB_PRODUCT_ID, USB_DESCRIPTION, NULL)) < 0) {
574                 sr_err("la8: %s: ftdi_usb_open_desc: (%d) %s",
575                        __func__, ret, ftdi_get_error_string(la8->ftdic));
576                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
577                 return SR_ERR;
578         }
579         sr_dbg("la8: device opened successfully");
580
581         /* Purge RX/TX buffers in the FTDI chip. */
582         if ((ret = ftdi_usb_purge_buffers(la8->ftdic)) < 0) {
583                 sr_err("la8: %s: ftdi_usb_purge_buffers: (%d) %s",
584                        __func__, ret, ftdi_get_error_string(la8->ftdic));
585                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
586                 goto err_opendev_close_ftdic;
587         }
588         sr_dbg("la8: FTDI buffers purged successfully");
589
590         /* Enable flow control in the FTDI chip. */
591         if ((ret = ftdi_setflowctrl(la8->ftdic, SIO_RTS_CTS_HS)) < 0) {
592                 sr_err("la8: %s: ftdi_setflowcontrol: (%d) %s",
593                        __func__, ret, ftdi_get_error_string(la8->ftdic));
594                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
595                 goto err_opendev_close_ftdic;
596         }
597         sr_dbg("la8: FTDI flow control enabled successfully");
598
599         /* Wait 100ms. */
600         g_usleep(100 * 1000);
601
602         sdi->status = SR_ST_ACTIVE;
603
604         return SR_OK;
605
606 err_opendev_close_ftdic:
607         (void) la8_close(la8); /* Log, but ignore errors. */
608         return SR_ERR;
609 }
610
611 static int set_samplerate(struct sr_dev_inst *sdi, uint64_t samplerate)
612 {
613         struct la8 *la8;
614
615         if (!sdi) {
616                 sr_err("la8: %s: sdi was NULL", __func__);
617                 return SR_ERR_ARG;
618         }
619
620         if (!(la8 = sdi->priv)) {
621                 sr_err("la8: %s: sdi->priv was NULL", __func__);
622                 return SR_ERR_ARG;
623         }
624
625         sr_spew("la8: setting samplerate");
626
627         fill_supported_samplerates_if_needed();
628
629         /* Check if this is a samplerate supported by the hardware. */
630         if (!is_valid_samplerate(samplerate))
631                 return SR_ERR;
632
633         /* Set the new samplerate. */
634         la8->cur_samplerate = samplerate;
635
636         sr_dbg("la8: samplerate set to %" PRIu64 "Hz", la8->cur_samplerate);
637
638         return SR_OK;
639 }
640
641 static int hw_closedev(int device_index)
642 {
643         struct sr_dev_inst *sdi;
644         struct la8 *la8;
645
646         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
647                 sr_err("la8: %s: sdi was NULL", __func__);
648                 return SR_ERR; /* TODO: SR_ERR_ARG? */
649         }
650
651         if (!(la8 = sdi->priv)) {
652                 sr_err("la8: %s: sdi->priv was NULL", __func__);
653                 return SR_ERR; /* TODO: SR_ERR_ARG? */
654         }
655
656         sr_dbg("la8: closing device");
657
658         if (sdi->status == SR_ST_ACTIVE) {
659                 sr_dbg("la8: %s: status ACTIVE, closing device", __func__);
660                 /* TODO: Really ignore errors here, or return SR_ERR? */
661                 (void) la8_close_usb_reset_sequencer(la8); /* Ignore errors. */
662         } else {
663                 sr_spew("la8: %s: status not ACTIVE, nothing to do", __func__);
664         }
665
666         sdi->status = SR_ST_INACTIVE;
667
668         sr_dbg("la8: %s: freeing sample buffers", __func__);
669         g_free(la8->final_buf);
670
671         return SR_OK;
672 }
673
674 static int hw_cleanup(void)
675 {
676         GSList *l;
677         struct sr_dev_inst *sdi;
678         int ret = SR_OK;
679
680         /* Properly close all devices. */
681         for (l = dev_insts; l; l = l->next) {
682                 if (!(sdi = l->data)) {
683                         /* Log error, but continue cleaning up the rest. */
684                         sr_err("la8: %s: sdi was NULL, continuing", __func__);
685                         ret = SR_ERR_BUG;
686                         continue;
687                 }
688                 sr_dev_inst_free(sdi); /* Returns void. */
689         }
690         g_slist_free(dev_insts); /* Returns void. */
691         dev_insts = NULL;
692
693         return ret;
694 }
695
696 static void *hw_get_device_info(int device_index, int device_info_id)
697 {
698         struct sr_dev_inst *sdi;
699         struct la8 *la8;
700         void *info;
701
702         sr_spew("la8: entering %s", __func__);
703
704         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
705                 sr_err("la8: %s: sdi was NULL", __func__);
706                 return NULL;
707         }
708
709         if (!(la8 = sdi->priv)) {
710                 sr_err("la8: %s: sdi->priv was NULL", __func__);
711                 return NULL;
712         }
713
714         switch (device_info_id) {
715         case SR_DI_INSTANCE:
716                 info = sdi;
717                 break;
718         case SR_DI_NUM_PROBES:
719                 info = GINT_TO_POINTER(NUM_PROBES);
720                 break;
721         case SR_DI_PROBE_NAMES:
722                 info = probe_names;
723                 break;
724         case SR_DI_SAMPLERATES:
725                 fill_supported_samplerates_if_needed();
726                 info = &samplerates;
727                 break;
728         case SR_DI_TRIGGER_TYPES:
729                 info = (char *)TRIGGER_TYPES;
730                 break;
731         case SR_DI_CUR_SAMPLERATE:
732                 info = &la8->cur_samplerate;
733                 break;
734         default:
735                 /* Unknown device info ID, return NULL. */
736                 sr_err("la8: %s: Unknown device info ID", __func__);
737                 info = NULL;
738                 break;
739         }
740
741         return info;
742 }
743
744 static int hw_get_status(int device_index)
745 {
746         struct sr_dev_inst *sdi;
747
748         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
749                 sr_err("la8: %s: sdi was NULL, device not found", __func__);
750                 return SR_ST_NOT_FOUND;
751         }
752
753         sr_dbg("la8: %s: returning status %d", __func__, sdi->status);
754
755         return sdi->status;
756 }
757
758 static int *hw_get_capabilities(void)
759 {
760         sr_spew("la8: entering %s", __func__);
761
762         return capabilities;
763 }
764
765 static int hw_set_configuration(int device_index, int capability, void *value)
766 {
767         struct sr_dev_inst *sdi;
768         struct la8 *la8;
769
770         sr_spew("la8: entering %s", __func__);
771
772         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
773                 sr_err("la8: %s: sdi was NULL", __func__);
774                 return SR_ERR; /* TODO: SR_ERR_ARG? */
775         }
776
777         if (!(la8 = sdi->priv)) {
778                 sr_err("la8: %s: sdi->priv was NULL", __func__);
779                 return SR_ERR; /* TODO: SR_ERR_ARG? */
780         }
781
782         switch (capability) {
783         case SR_HWCAP_SAMPLERATE:
784                 if (set_samplerate(sdi, *(uint64_t *)value) == SR_ERR)
785                         return SR_ERR;
786                 sr_dbg("la8: SAMPLERATE = %" PRIu64, la8->cur_samplerate);
787                 break;
788         case SR_HWCAP_PROBECONFIG:
789                 if (configure_probes(la8, (GSList *)value) != SR_OK) {
790                         sr_err("la8: %s: probe config failed", __func__);
791                         return SR_ERR;
792                 }
793                 break;
794         case SR_HWCAP_LIMIT_MSEC:
795                 if (*(uint64_t *)value == 0) {
796                         sr_err("la8: %s: LIMIT_MSEC can't be 0", __func__);
797                         return SR_ERR;
798                 }
799                 la8->limit_msec = *(uint64_t *)value;
800                 sr_dbg("la8: LIMIT_MSEC = %" PRIu64, la8->limit_msec);
801                 break;
802         case SR_HWCAP_LIMIT_SAMPLES:
803                 if (*(uint64_t *)value < MIN_NUM_SAMPLES) {
804                         sr_err("la8: %s: LIMIT_SAMPLES too small", __func__);
805                         return SR_ERR;
806                 }
807                 la8->limit_samples = *(uint64_t *)value;
808                 sr_dbg("la8: LIMIT_SAMPLES = %" PRIu64, la8->limit_samples);
809                 break;
810         default:
811                 /* Unknown capability, return SR_ERR. */
812                 sr_err("la8: %s: Unknown capability", __func__);
813                 return SR_ERR;
814                 break;
815         }
816
817         return SR_OK;
818 }
819
820 /**
821  * Get a block of data from the LA8.
822  *
823  * @param la8 The LA8 struct containing private per-device-instance data.
824  * @return SR_OK upon success, or SR_ERR upon errors.
825  */
826 static int la8_read_block(struct la8 *la8)
827 {
828         int i, byte_offset, m, mi, p, index, bytes_read;
829         time_t now;
830
831         if (!la8) {
832                 sr_err("la8: %s: la8 was NULL", __func__);
833                 return SR_ERR_ARG;
834         }
835
836         if (!la8->ftdic) {
837                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
838                 return SR_ERR_ARG;
839         }
840
841         sr_spew("la8: %s: reading block %d", __func__, la8->block_counter);
842
843         bytes_read = la8_read(la8, la8->mangled_buf, BS);
844
845         /* If first block read got 0 bytes, retry until success or timeout. */
846         if ((bytes_read == 0) && (la8->block_counter == 0)) {
847                 do {
848                         sr_spew("la8: %s: reading block 0 again", __func__);
849                         bytes_read = la8_read(la8, la8->mangled_buf, BS);
850                         /* TODO: How to handle read errors here? */
851                         now = time(NULL);
852                 } while ((la8->done > now) && (bytes_read == 0));
853         }
854
855         /* Check if block read was successful or a timeout occured. */
856         if (bytes_read != BS) {
857                 sr_err("la8: %s: trigger timed out", __func__);
858                 (void) la8_reset(la8); /* Ignore errors. */
859                 return SR_ERR;
860         }
861
862         /* De-mangle the data. */
863         sr_spew("la8: de-mangling samples of block %d", la8->block_counter);
864         byte_offset = la8->block_counter * BS;
865         m = byte_offset / (1024 * 1024);
866         mi = m * (1024 * 1024);
867         for (i = 0; i < BS; i++) {
868                 p = i & (1 << 0);
869                 index = m * 2 + (((byte_offset + i) - mi) / 2) * 16;
870                 index += (la8->divcount == 0) ? p : (1 - p);
871                 la8->final_buf[index] = la8->mangled_buf[i];
872         }
873
874         return SR_OK;
875 }
876
877 static void send_block_to_session_bus(struct la8 *la8, int block)
878 {
879         int i;
880         uint8_t sample, expected_sample;
881         struct sr_datafeed_packet packet;
882         struct sr_datafeed_logic logic;
883         int trigger_point; /* Relative trigger point (in this block). */
884
885         /* Note: No sanity checks on la8/block, caller is responsible. */
886
887         /* Check if we can find the trigger condition in this block. */
888         trigger_point = -1;
889         expected_sample = la8->trigger_pattern & la8->trigger_mask;
890         for (i = 0; i < BS; i++) {
891                 /* Don't continue if the trigger was found previously. */
892                 if (la8->trigger_found)
893                         break;
894
895                 /*
896                  * Also, don't continue if triggers are "don't care", i.e. if
897                  * no trigger conditions were specified by the user. In that
898                  * case we don't want to send an SR_DF_TRIGGER packet at all.
899                  */
900                 if (la8->trigger_mask == 0x00)
901                         break;
902
903                 sample = *(la8->final_buf + (block * BS) + i);
904
905                 if ((sample & la8->trigger_mask) == expected_sample) {
906                         trigger_point = i;
907                         la8->trigger_found = 1;
908                         break;
909                 }
910         }
911
912         /* If no trigger was found, send one SR_DF_LOGIC packet. */
913         if (trigger_point == -1) {
914                 /* Send an SR_DF_LOGIC packet to the session bus. */
915                 sr_spew("la8: sending SR_DF_LOGIC packet (%d bytes) for "
916                         "block %d", BS, block);
917                 packet.type = SR_DF_LOGIC;
918                 packet.payload = &logic;
919                 logic.length = BS;
920                 logic.unitsize = 1;
921                 logic.data = la8->final_buf + (block * BS);
922                 sr_session_bus(la8->session_id, &packet);
923                 return;
924         }
925
926         /*
927          * We found the trigger, so some special handling is needed. We have
928          * to send an SR_DF_LOGIC packet with the samples before the trigger
929          * (if any), then the SD_DF_TRIGGER packet itself, then another
930          * SR_DF_LOGIC packet with the samples after the trigger (if any).
931          */
932
933         /* TODO: Send SR_DF_TRIGGER packet before or after the actual sample? */
934
935         /* If at least one sample is located before the trigger... */
936         if (trigger_point > 0) {
937                 /* Send pre-trigger SR_DF_LOGIC packet to the session bus. */
938                 sr_spew("la8: sending pre-trigger SR_DF_LOGIC packet, "
939                         "start = %d, length = %d", block * BS, trigger_point);
940                 packet.type = SR_DF_LOGIC;
941                 packet.payload = &logic;
942                 logic.length = trigger_point;
943                 logic.unitsize = 1;
944                 logic.data = la8->final_buf + (block * BS);
945                 sr_session_bus(la8->session_id, &packet);
946         }
947
948         /* Send the SR_DF_TRIGGER packet to the session bus. */
949         sr_spew("la8: sending SR_DF_TRIGGER packet, sample = %d",
950                 (block * BS) + trigger_point);
951         packet.type = SR_DF_TRIGGER;
952         packet.payload = NULL;
953         sr_session_bus(la8->session_id, &packet);
954
955         /* If at least one sample is located after the trigger... */
956         if (trigger_point < (BS - 1)) {
957                 /* Send post-trigger SR_DF_LOGIC packet to the session bus. */
958                 sr_spew("la8: sending post-trigger SR_DF_LOGIC packet, "
959                         "start = %d, length = %d",
960                         (block * BS) + trigger_point, BS - trigger_point);
961                 packet.type = SR_DF_LOGIC;
962                 packet.payload = &logic;
963                 logic.length = BS - trigger_point;
964                 logic.unitsize = 1;
965                 logic.data = la8->final_buf + (block * BS) + trigger_point;
966                 sr_session_bus(la8->session_id, &packet);
967         }
968 }
969
970 static int receive_data(int fd, int revents, void *session_data)
971 {
972         int i, ret;
973         struct sr_dev_inst *sdi;
974         struct la8 *la8;
975
976         /* Avoid compiler errors. */
977         (void)fd;
978         (void)revents;
979
980         if (!(sdi = session_data)) {
981                 sr_err("la8: %s: session_data was NULL", __func__);
982                 return FALSE;
983         }
984
985         if (!(la8 = sdi->priv)) {
986                 sr_err("la8: %s: sdi->priv was NULL", __func__);
987                 return FALSE;
988         }
989
990         /* Get one block of data. */
991         if ((ret = la8_read_block(la8)) < 0) {
992                 sr_err("la8: %s: la8_read_block error: %d", __func__, ret);
993                 hw_stop_acquisition(sdi->index, session_data);
994                 return FALSE;
995         }
996
997         /* We need to get exactly NUM_BLOCKS blocks (i.e. 8MB) of data. */
998         if (la8->block_counter != (NUM_BLOCKS - 1)) {
999                 la8->block_counter++;
1000                 return TRUE;
1001         }
1002
1003         sr_dbg("la8: sampling finished, sending data to session bus now");
1004
1005         /* All data was received and demangled, send it to the session bus. */
1006         for (i = 0; i < NUM_BLOCKS; i++)
1007                 send_block_to_session_bus(la8, i);
1008
1009         hw_stop_acquisition(sdi->index, session_data);
1010
1011         // return FALSE; /* FIXME? */
1012         return TRUE;
1013 }
1014
1015 static int hw_start_acquisition(int device_index, gpointer session_data)
1016 {
1017         struct sr_dev_inst *sdi;
1018         struct la8 *la8;
1019         struct sr_datafeed_packet packet;
1020         struct sr_datafeed_header header;
1021         uint8_t buf[4];
1022         int bytes_written;
1023
1024         sr_spew("la8: entering %s", __func__);
1025
1026         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
1027                 sr_err("la8: %s: sdi was NULL", __func__);
1028                 return SR_ERR; /* TODO: SR_ERR_ARG? */
1029         }
1030
1031         if (!(la8 = sdi->priv)) {
1032                 sr_err("la8: %s: sdi->priv was NULL", __func__);
1033                 return SR_ERR; /* TODO: SR_ERR_ARG? */
1034         }
1035
1036         if (!la8->ftdic) {
1037                 sr_err("la8: %s: la8->ftdic was NULL", __func__);
1038                 return SR_ERR_ARG;
1039         }
1040
1041         la8->divcount = samplerate_to_divcount(la8->cur_samplerate);
1042         if (la8->divcount == 0xff) {
1043                 sr_err("la8: %s: invalid divcount/samplerate", __func__);
1044                 return SR_ERR;
1045         }
1046
1047         /* Fill acquisition parameters into buf[]. */
1048         buf[0] = la8->divcount;
1049         buf[1] = 0xff; /* This byte must always be 0xff. */
1050         buf[2] = la8->trigger_pattern;
1051         buf[3] = la8->trigger_mask;
1052
1053         /* Start acquisition. */
1054         bytes_written = la8_write(la8, buf, 4);
1055
1056         if (bytes_written < 0) {
1057                 sr_err("la8: acquisition failed to start");
1058                 return SR_ERR;
1059         } else if (bytes_written != 4) {
1060                 sr_err("la8: acquisition failed to start");
1061                 return SR_ERR; /* TODO: Other error and return code? */
1062         }
1063
1064         sr_dbg("la8: acquisition started successfully");
1065
1066         la8->session_id = session_data;
1067
1068         /* Send header packet to the session bus. */
1069         sr_dbg("la8: %s: sending SR_DF_HEADER", __func__);
1070         packet.type = SR_DF_HEADER;
1071         packet.payload = &header;
1072         header.feed_version = 1;
1073         gettimeofday(&header.starttime, NULL);
1074         header.samplerate = la8->cur_samplerate;
1075         header.num_logic_probes = NUM_PROBES;
1076         sr_session_bus(session_data, &packet);
1077
1078         /* Time when we should be done (for detecting trigger timeouts). */
1079         la8->done = (la8->divcount + 1) * 0.08388608 + time(NULL)
1080                         + la8->trigger_timeout;
1081         la8->block_counter = 0;
1082         la8->trigger_found = 0;
1083
1084         /* Hook up a dummy handler to receive data from the LA8. */
1085         sr_source_add(-1, G_IO_IN, 0, receive_data, sdi);
1086
1087         return SR_OK;
1088 }
1089
1090 static int hw_stop_acquisition(int device_index, gpointer session_data)
1091 {
1092         struct sr_dev_inst *sdi;
1093         struct la8 *la8;
1094         struct sr_datafeed_packet packet;
1095
1096         sr_dbg("la8: stopping acquisition");
1097
1098         if (!(sdi = sr_dev_inst_get(dev_insts, device_index))) {
1099                 sr_err("la8: %s: sdi was NULL", __func__);
1100                 return SR_ERR_BUG;
1101         }
1102
1103         if (!(la8 = sdi->priv)) {
1104                 sr_err("la8: %s: sdi->priv was NULL", __func__);
1105                 return SR_ERR_BUG;
1106         }
1107
1108         /* Send end packet to the session bus. */
1109         sr_dbg("la8: %s: sending SR_DF_END", __func__);
1110         packet.type = SR_DF_END;
1111         sr_session_bus(session_data, &packet);
1112
1113         return SR_OK;
1114 }
1115
1116 SR_PRIV struct sr_device_plugin chronovu_la8_plugin_info = {
1117         .name = "chronovu-la8",
1118         .longname = "ChronoVu LA8",
1119         .api_version = 1,
1120         .init = hw_init,
1121         .cleanup = hw_cleanup,
1122         .opendev = hw_opendev,
1123         .closedev = hw_closedev,
1124         .get_device_info = hw_get_device_info,
1125         .get_status = hw_get_status,
1126         .get_capabilities = hw_get_capabilities,
1127         .set_configuration = hw_set_configuration,
1128         .start_acquisition = hw_start_acquisition,
1129         .stop_acquisition = hw_stop_acquisition,
1130 };