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