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