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