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