]> sigrok.org Git - libsigrok.git/blob - hardware/fx2lafw/fx2lafw.c
sr/drivers: use sr_dev_inst instead of device index for dev_config_set()
[libsigrok.git] / hardware / fx2lafw / fx2lafw.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <inttypes.h>
25 #include <libusb.h>
26 #include "config.h"
27 #include "libsigrok.h"
28 #include "libsigrok-internal.h"
29 #include "fx2lafw.h"
30 #include "command.h"
31
32 static const struct fx2lafw_profile supported_fx2[] = {
33         /*
34          * CWAV USBee AX
35          * EE Electronics ESLA201A
36          * ARMFLY AX-Pro
37          */
38         { 0x08a9, 0x0014, "CWAV", "USBee AX", NULL,
39                 FIRMWARE_DIR "/fx2lafw-cwav-usbeeax.fw",
40                 0 },
41         /*
42          * CWAV USBee DX
43          * XZL-Studio DX
44          */
45         { 0x08a9, 0x0015, "CWAV", "USBee DX", NULL,
46                 FIRMWARE_DIR "/fx2lafw-cwav-usbeedx.fw",
47                 DEV_CAPS_16BIT },
48
49         /*
50          * CWAV USBee SX
51          */
52         { 0x08a9, 0x0009, "CWAV", "USBee SX", NULL,
53                 FIRMWARE_DIR "/fx2lafw-cwav-usbeesx.fw",
54                 0 },
55
56         /*
57          * Saleae Logic
58          * EE Electronics ESLA100
59          * Robomotic MiniLogic
60          * Robomotic BugLogic 3
61          */
62         { 0x0925, 0x3881, "Saleae", "Logic", NULL,
63                 FIRMWARE_DIR "/fx2lafw-saleae-logic.fw",
64                 0 },
65
66         /*
67          * Default Cypress FX2 without EEPROM, e.g.:
68          * Lcsoft Mini Board
69          * Braintechnology USB Interface V2.x
70          */
71         { 0x04B4, 0x8613, "Cypress", "FX2", NULL,
72                 FIRMWARE_DIR "/fx2lafw-cypress-fx2.fw",
73                 DEV_CAPS_16BIT },
74
75         /*
76          * Braintechnology USB-LPS
77          */
78         { 0x16d0, 0x0498, "Braintechnology", "USB-LPS", NULL,
79                 FIRMWARE_DIR "/fx2lafw-braintechnology-usb-lps.fw",
80                 DEV_CAPS_16BIT },
81
82         { 0, 0, 0, 0, 0, 0, 0 }
83 };
84
85 static const int hwcaps[] = {
86         SR_HWCAP_LOGIC_ANALYZER,
87         SR_HWCAP_SAMPLERATE,
88
89         /* These are really implemented in the driver, not the hardware. */
90         SR_HWCAP_LIMIT_SAMPLES,
91         SR_HWCAP_CONTINUOUS,
92         0,
93 };
94
95 static const char *probe_names[] = {
96         "0",
97         "1",
98         "2",
99         "3",
100         "4",
101         "5",
102         "6",
103         "7",
104         "8",
105         "9",
106         "10",
107         "11",
108         "12",
109         "13",
110         "14",
111         "15",
112         NULL,
113 };
114
115 static const uint64_t supported_samplerates[] = {
116         SR_KHZ(20),
117         SR_KHZ(25),
118         SR_KHZ(50),
119         SR_KHZ(100),
120         SR_KHZ(200),
121         SR_KHZ(250),
122         SR_KHZ(500),
123         SR_MHZ(1),
124         SR_MHZ(2),
125         SR_MHZ(3),
126         SR_MHZ(4),
127         SR_MHZ(6),
128         SR_MHZ(8),
129         SR_MHZ(12),
130         SR_MHZ(16),
131         SR_MHZ(24),
132         0,
133 };
134
135 static const struct sr_samplerates samplerates = {
136         0,
137         0,
138         0,
139         supported_samplerates,
140 };
141
142 static libusb_context *usb_context = NULL;
143
144 SR_PRIV struct sr_dev_driver fx2lafw_driver_info;
145 static struct sr_dev_driver *fdi = &fx2lafw_driver_info;
146 static int hw_dev_config_set(const struct sr_dev_inst *sdi, int hwcap,
147                 const void *value);
148 static int hw_dev_acquisition_stop(int dev_index, void *cb_data);
149
150 /**
151  * Check the USB configuration to determine if this is an fx2lafw device.
152  *
153  * @return TRUE if the device's configuration profile match fx2lafw
154  *         configuration, FALSE otherwise.
155  */
156 static gboolean check_conf_profile(libusb_device *dev)
157 {
158         struct libusb_device_descriptor des;
159         struct libusb_device_handle *hdl;
160         gboolean ret;
161         unsigned char strdesc[64];
162
163         hdl = NULL;
164         ret = FALSE;
165         while (!ret) {
166                 /* Assume the FW has not been loaded, unless proven wrong. */
167                 if (libusb_get_device_descriptor(dev, &des) != 0)
168                         break;
169
170                 if (libusb_open(dev, &hdl) != 0)
171                         break;
172
173                 if (libusb_get_string_descriptor_ascii(hdl,
174                                 des.iManufacturer, strdesc, sizeof(strdesc)) < 0)
175                         break;
176                 if (strncmp((const char *)strdesc, "sigrok", 6))
177                         break;
178
179                 if (libusb_get_string_descriptor_ascii(hdl,
180                                 des.iProduct, strdesc, sizeof(strdesc)) < 0)
181                         break;
182                 if (strncmp((const char *)strdesc, "fx2lafw", 7))
183                         break;
184
185                 /* If we made it here, it must be an fx2lafw. */
186                 ret = TRUE;
187         }
188         if (hdl)
189                 libusb_close(hdl);
190
191         return ret;
192 }
193
194 static int fx2lafw_dev_open(int dev_index)
195 {
196         libusb_device **devlist;
197         struct libusb_device_descriptor des;
198         struct sr_dev_inst *sdi;
199         struct context *ctx;
200         struct version_info vi;
201         int ret, skip, i;
202         uint8_t revid;
203
204         if (!(sdi = sr_dev_inst_get(fdi->instances, dev_index)))
205                 return SR_ERR;
206         ctx = sdi->priv;
207
208         if (sdi->status == SR_ST_ACTIVE)
209                 /* already in use */
210                 return SR_ERR;
211
212         skip = 0;
213         const int device_count = libusb_get_device_list(usb_context, &devlist);
214         if (device_count < 0) {
215                 sr_err("fx2lafw: Failed to retrieve device list (%d)",
216                         device_count);
217                 return SR_ERR;
218         }
219
220         for (i = 0; i < device_count; i++) {
221                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
222                         sr_err("fx2lafw: Failed to get device descriptor: %d.",
223                                ret);
224                         continue;
225                 }
226
227                 if (des.idVendor != ctx->profile->vid
228                     || des.idProduct != ctx->profile->pid)
229                         continue;
230
231                 if (sdi->status == SR_ST_INITIALIZING) {
232                         if (skip != dev_index) {
233                                 /* Skip devices of this type that aren't the one we want. */
234                                 skip += 1;
235                                 continue;
236                         }
237                 } else if (sdi->status == SR_ST_INACTIVE) {
238                         /*
239                          * This device is fully enumerated, so we need to find
240                          * this device by vendor, product, bus and address.
241                          */
242                         if (libusb_get_bus_number(devlist[i]) != ctx->usb->bus
243                                 || libusb_get_device_address(devlist[i]) != ctx->usb->address)
244                                 /* this is not the one */
245                                 continue;
246                 }
247
248                 if (!(ret = libusb_open(devlist[i], &ctx->usb->devhdl))) {
249                         if (ctx->usb->address == 0xff)
250                                 /*
251                                  * first time we touch this device after firmware upload,
252                                  * so we don't know the address yet.
253                                  */
254                                 ctx->usb->address = libusb_get_device_address(devlist[i]);
255                 } else {
256                         sr_err("fx2lafw: Failed to open device: %d.", ret);
257                         break;
258                 }
259
260                 ret = command_get_fw_version(ctx->usb->devhdl, &vi);
261                 if (ret != SR_OK) {
262                         sr_err("fx2lafw: Failed to retrieve "
263                                "firmware version information.");
264                         break;
265                 }
266
267                 ret = command_get_revid_version(ctx->usb->devhdl, &revid);
268                 if (ret != SR_OK) {
269                         sr_err("fx2lafw: Failed to retrieve REVID.");
270                         break;
271                 }
272
273                 /*
274                  * Changes in major version mean incompatible/API changes, so
275                  * bail out if we encounter an incompatible version.
276                  * Different minor versions are OK, they should be compatible.
277                  */
278                 if (vi.major != FX2LAFW_REQUIRED_VERSION_MAJOR) {
279                         sr_err("fx2lafw: Expected firmware version %d.x, "
280                                "got %d.%d.", FX2LAFW_REQUIRED_VERSION_MAJOR,
281                                vi.major, vi.minor);
282                         break;
283                 }
284
285                 sdi->status = SR_ST_ACTIVE;
286                 sr_info("fx2lafw: Opened device %d on %d.%d "
287                         "interface %d, firmware %d.%d, REVID %d.",
288                         sdi->index, ctx->usb->bus, ctx->usb->address,
289                         USB_INTERFACE, vi.major, vi.minor, revid);
290
291                 break;
292         }
293         libusb_free_device_list(devlist, 1);
294
295         if (sdi->status != SR_ST_ACTIVE)
296                 return SR_ERR;
297
298         return SR_OK;
299 }
300
301 static void close_dev(struct sr_dev_inst *sdi)
302 {
303         struct context *ctx;
304
305         ctx = sdi->priv;
306
307         if (ctx->usb->devhdl == NULL)
308                 return;
309
310         sr_info("fx2lafw: Closing device %d on %d.%d interface %d.",
311                 sdi->index, ctx->usb->bus, ctx->usb->address, USB_INTERFACE);
312         libusb_release_interface(ctx->usb->devhdl, USB_INTERFACE);
313         libusb_close(ctx->usb->devhdl);
314         ctx->usb->devhdl = NULL;
315         sdi->status = SR_ST_INACTIVE;
316 }
317
318 static int configure_probes(struct context *ctx, GSList *probes)
319 {
320         struct sr_probe *probe;
321         GSList *l;
322         int probe_bit, stage, i;
323         char *tc;
324
325         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
326                 ctx->trigger_mask[i] = 0;
327                 ctx->trigger_value[i] = 0;
328         }
329
330         stage = -1;
331         for (l = probes; l; l = l->next) {
332                 probe = (struct sr_probe *)l->data;
333                 if (probe->enabled == FALSE)
334                         continue;
335
336                 if (probe->index > 8)
337                         ctx->sample_wide = TRUE;
338
339                 probe_bit = 1 << (probe->index - 1);
340                 if (!(probe->trigger))
341                         continue;
342
343                 stage = 0;
344                 for (tc = probe->trigger; *tc; tc++) {
345                         ctx->trigger_mask[stage] |= probe_bit;
346                         if (*tc == '1')
347                                 ctx->trigger_value[stage] |= probe_bit;
348                         stage++;
349                         if (stage > NUM_TRIGGER_STAGES)
350                                 return SR_ERR;
351                 }
352         }
353
354         if (stage == -1)
355                 /*
356                  * We didn't configure any triggers, make sure acquisition
357                  * doesn't wait for any.
358                  */
359                 ctx->trigger_stage = TRIGGER_FIRED;
360         else
361                 ctx->trigger_stage = 0;
362
363         return SR_OK;
364 }
365
366 static struct context *fx2lafw_dev_new(void)
367 {
368         struct context *ctx;
369
370         if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
371                 sr_err("fx2lafw: %s: ctx malloc failed.", __func__);
372                 return NULL;
373         }
374
375         ctx->trigger_stage = TRIGGER_FIRED;
376
377         return ctx;
378 }
379
380 static int clear_instances(void)
381 {
382         GSList *l;
383         struct sr_dev_inst *sdi;
384         struct context *ctx;
385         int ret;
386
387         ret = SR_OK;
388         for (l = fdi->instances; l; l = l->next) {
389                 if (!(sdi = l->data)) {
390                         /* Log error, but continue cleaning up the rest. */
391                         sr_err("fx2lafw: %s: sdi was NULL, continuing.",
392                                    __func__);
393                         ret = SR_ERR_BUG;
394                         continue;
395                 }
396                 if (!(ctx = sdi->priv)) {
397                         /* Log error, but continue cleaning up the rest. */
398                         sr_err("fx2lafw: %s: sdi->priv was NULL, continuing",
399                                    __func__);
400                         ret = SR_ERR_BUG;
401                         continue;
402                 }
403                 close_dev(sdi);
404                 sdi = l->data;
405                 sr_dev_inst_free(sdi);
406         }
407
408         g_slist_free(fdi->instances);
409         fdi->instances = NULL;
410
411         return ret;
412 }
413
414
415 /*
416  * API callbacks
417  */
418
419 static int hw_init(void)
420 {
421
422         if (libusb_init(&usb_context) != 0) {
423                 sr_warn("fx2lafw: Failed to initialize libusb.");
424                 return SR_ERR;
425         }
426
427         return SR_OK;
428 }
429
430 static GSList *hw_scan(GSList *options)
431 {
432         GSList *devices;
433         struct libusb_device_descriptor des;
434         struct sr_dev_inst *sdi;
435         const struct fx2lafw_profile *prof;
436         struct context *ctx;
437         struct sr_probe *probe;
438         libusb_device **devlist;
439         int devcnt, num_logic_probes, ret, i, j;
440
441         /* Avoid compiler warnings. */
442         (void)options;
443
444         /* This scan always invalidates any previous scans. */
445         clear_instances();
446
447         /* Find all fx2lafw compatible devices and upload firmware to them. */
448         devices = NULL;
449         libusb_get_device_list(usb_context, &devlist);
450         for (i = 0; devlist[i]; i++) {
451
452                 if ((ret = libusb_get_device_descriptor(
453                      devlist[i], &des)) != 0) {
454                         sr_warn("fx2lafw: Failed to get device descriptor: %d.", ret);
455                         continue;
456                 }
457
458                 prof = NULL;
459                 for (j = 0; supported_fx2[j].vid; j++) {
460                         if (des.idVendor == supported_fx2[j].vid &&
461                                 des.idProduct == supported_fx2[j].pid) {
462                                 prof = &supported_fx2[j];
463                         }
464                 }
465
466                 /* Skip if the device was not found */
467                 if (!prof)
468                         continue;
469
470                 devcnt = g_slist_length(fdi->instances);
471                 sdi = sr_dev_inst_new(devcnt, SR_ST_INITIALIZING,
472                         prof->vendor, prof->model, prof->model_version);
473                 if (!sdi)
474                         return 0;
475                 sdi->driver = fdi;
476
477                 /* Fill in probelist according to this device's profile. */
478                 num_logic_probes = prof->dev_caps & DEV_CAPS_16BIT ? 16 : 8;
479                 for (j = 0; j < num_logic_probes; j++) {
480                         if (!(probe = sr_probe_new(j, SR_PROBE_LOGIC, TRUE,
481                                         probe_names[j])))
482                                 return 0;
483                         sdi->probes = g_slist_append(sdi->probes, probe);
484                 }
485
486                 ctx = fx2lafw_dev_new();
487                 ctx->profile = prof;
488                 sdi->priv = ctx;
489                 fdi->instances = g_slist_append(fdi->instances, sdi);
490                 devices = g_slist_append(devices, sdi);
491
492                 if (check_conf_profile(devlist[i])) {
493                         /* Already has the firmware, so fix the new address. */
494                         sr_dbg("fx2lafw: Found an fx2lafw device.");
495                         sdi->status = SR_ST_INACTIVE;
496                         ctx->usb = sr_usb_dev_inst_new
497                             (libusb_get_bus_number(devlist[i]),
498                              libusb_get_device_address(devlist[i]), NULL);
499                 } else {
500                         if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
501                                 prof->firmware) == SR_OK)
502                                 /* Remember when the firmware on this device was updated */
503                                 ctx->fw_updated = g_get_monotonic_time();
504                         else
505                                 sr_err("fx2lafw: Firmware upload failed for "
506                                        "device %d.", devcnt);
507                         ctx->usb = sr_usb_dev_inst_new
508                                 (libusb_get_bus_number(devlist[i]), 0xff, NULL);
509                 }
510         }
511         libusb_free_device_list(devlist, 1);
512
513         return devices;
514 }
515
516 static int hw_dev_open(int dev_index)
517 {
518         struct sr_dev_inst *sdi;
519         struct context *ctx;
520         int ret;
521         int64_t timediff_us, timediff_ms;
522
523         if (!(sdi = sr_dev_inst_get(fdi->instances, dev_index)))
524                 return SR_ERR;
525         ctx = sdi->priv;
526
527         /*
528          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
529          * milliseconds for the FX2 to renumerate.
530          */
531         ret = SR_ERR;
532         if (ctx->fw_updated > 0) {
533                 sr_info("fx2lafw: Waiting for device to reset.");
534                 /* takes at least 300ms for the FX2 to be gone from the USB bus */
535                 g_usleep(300 * 1000);
536                 timediff_ms = 0;
537                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
538                         if ((ret = fx2lafw_dev_open(dev_index)) == SR_OK)
539                                 break;
540                         g_usleep(100 * 1000);
541
542                         timediff_us = g_get_monotonic_time() - ctx->fw_updated;
543                         timediff_ms = timediff_us / 1000;
544                         sr_spew("fx2lafw: waited %" PRIi64 " ms", timediff_ms);
545                 }
546                 sr_info("fx2lafw: Device came back after %d ms.", timediff_ms);
547         } else {
548                 ret = fx2lafw_dev_open(dev_index);
549         }
550
551         if (ret != SR_OK) {
552                 sr_err("fx2lafw: Unable to open device.");
553                 return SR_ERR;
554         }
555         ctx = sdi->priv;
556
557         ret = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
558         if (ret != 0) {
559                 switch(ret) {
560                 case LIBUSB_ERROR_BUSY:
561                         sr_err("fx2lafw: Unable to claim USB interface. Another "
562                                 "program or driver has already claimed it.");
563                         break;
564
565                 case LIBUSB_ERROR_NO_DEVICE:
566                         sr_err("fx2lafw: Device has been disconnected.");
567                         break;
568
569                 default:
570                         sr_err("fx2lafw: Unable to claim interface: %d.", ret);
571                         break;
572                 }
573
574                 return SR_ERR;
575         }
576
577         if (ctx->cur_samplerate == 0) {
578                 /* Samplerate hasn't been set; default to the slowest one. */
579                 if (hw_dev_config_set(sdi, SR_HWCAP_SAMPLERATE,
580                     &supported_samplerates[0]) == SR_ERR)
581                         return SR_ERR;
582         }
583
584         return SR_OK;
585 }
586
587 static int hw_dev_close(int dev_index)
588 {
589         struct sr_dev_inst *sdi;
590
591         if (!(sdi = sr_dev_inst_get(fdi->instances, dev_index))) {
592                 sr_err("fx2lafw: %s: sdi was NULL.", __func__);
593                 return SR_ERR_BUG;
594         }
595
596         /* TODO */
597         close_dev(sdi);
598
599         return SR_OK;
600 }
601
602 static int hw_cleanup(void)
603 {
604         int ret;
605
606         ret = clear_instances();
607
608         if (usb_context)
609                 libusb_exit(usb_context);
610         usb_context = NULL;
611
612         return ret;
613 }
614
615 static int hw_info_get(int info_id, const void **data,
616                 const struct sr_dev_inst *sdi)
617 {
618         struct context *ctx;
619
620         switch (info_id) {
621         case SR_DI_INST:
622                 *data = sdi;
623                 break;
624         case SR_DI_HWCAPS:
625                 *data = hwcaps;
626                 break;
627         case SR_DI_NUM_PROBES:
628                 if (sdi) {
629                         ctx = sdi->priv;
630                         *data = GINT_TO_POINTER(
631                                 (ctx->profile->dev_caps & DEV_CAPS_16BIT) ?
632                                 16 : 8);
633                 } else
634                         return SR_ERR;
635                 break;
636         case SR_DI_PROBE_NAMES:
637                 *data = probe_names;
638                 break;
639         case SR_DI_SAMPLERATES:
640                 *data = &samplerates;
641                 break;
642         case SR_DI_TRIGGER_TYPES:
643                 *data = TRIGGER_TYPES;
644                 break;
645         case SR_DI_CUR_SAMPLERATE:
646                 if (sdi) {
647                         ctx = sdi->priv;
648                         *data = &ctx->cur_samplerate;
649                 } else
650                         return SR_ERR;
651                 break;
652         default:
653                 return SR_ERR_ARG;
654         }
655
656         return SR_OK;
657 }
658
659 static int hw_dev_status_get(int dev_index)
660 {
661         const struct sr_dev_inst *const sdi =
662                 sr_dev_inst_get(fdi->instances, dev_index);
663
664         if (!sdi)
665                 return SR_ST_NOT_FOUND;
666
667         return sdi->status;
668 }
669
670 static int hw_dev_config_set(const struct sr_dev_inst *sdi, int hwcap,
671                 const void *value)
672 {
673         struct context *ctx;
674         int ret;
675
676         ctx = sdi->priv;
677
678         if (hwcap == SR_HWCAP_SAMPLERATE) {
679                 ctx->cur_samplerate = *(const uint64_t *)value;
680                 ret = SR_OK;
681         } else if (hwcap == SR_HWCAP_PROBECONFIG) {
682                 ret = configure_probes(ctx, (GSList *) value);
683         } else if (hwcap == SR_HWCAP_LIMIT_SAMPLES) {
684                 ctx->limit_samples = *(const uint64_t *)value;
685                 ret = SR_OK;
686         } else {
687                 ret = SR_ERR;
688         }
689
690         return ret;
691 }
692
693 static int receive_data(int fd, int revents, void *cb_data)
694 {
695         struct timeval tv;
696
697         /* Avoid compiler warnings. */
698         (void)fd;
699         (void)revents;
700         (void)cb_data;
701
702         tv.tv_sec = tv.tv_usec = 0;
703         libusb_handle_events_timeout(usb_context, &tv);
704
705         return TRUE;
706 }
707
708 static void abort_acquisition(struct context *ctx)
709 {
710         int i;
711
712         ctx->num_samples = -1;
713
714         for (i = ctx->num_transfers - 1; i >= 0; i--) {
715                 if (ctx->transfers[i])
716                         libusb_cancel_transfer(ctx->transfers[i]);
717         }
718 }
719
720 static void finish_acquisition(struct context *ctx)
721 {
722         struct sr_datafeed_packet packet;
723         int i;
724
725         /* Terminate session */
726         packet.type = SR_DF_END;
727         sr_session_send(ctx->session_dev_id, &packet);
728
729         /* Remove fds from polling */
730         const struct libusb_pollfd **const lupfd =
731                 libusb_get_pollfds(usb_context);
732         for (i = 0; lupfd[i]; i++)
733                 sr_source_remove(lupfd[i]->fd);
734         free(lupfd); /* NOT g_free()! */
735
736         ctx->num_transfers = 0;
737         g_free(ctx->transfers);
738 }
739
740 static void free_transfer(struct libusb_transfer *transfer)
741 {
742         struct context *ctx = transfer->user_data;
743         unsigned int i;
744
745         g_free(transfer->buffer);
746         transfer->buffer = NULL;
747         libusb_free_transfer(transfer);
748
749         for (i = 0; i < ctx->num_transfers; i++) {
750                 if (ctx->transfers[i] == transfer) {
751                         ctx->transfers[i] = NULL;
752                         break;
753                 }
754         }
755
756         ctx->submitted_transfers--;
757         if (ctx->submitted_transfers == 0)
758                 finish_acquisition(ctx);
759
760 }
761
762 static void resubmit_transfer(struct libusb_transfer *transfer)
763 {
764         if (libusb_submit_transfer(transfer) != 0) {
765                 free_transfer(transfer);
766                 /* TODO: Stop session? */
767                 /* TODO: Better error message. */
768                 sr_err("fx2lafw: %s: libusb_submit_transfer error.", __func__);
769         }
770 }
771
772 static void receive_transfer(struct libusb_transfer *transfer)
773 {
774         gboolean packet_has_error = FALSE;
775         struct sr_datafeed_packet packet;
776         struct sr_datafeed_logic logic;
777         struct context *ctx = transfer->user_data;
778         int trigger_offset, i;
779
780         /*
781          * If acquisition has already ended, just free any queued up
782          * transfer that come in.
783          */
784         if (ctx->num_samples == -1) {
785                 free_transfer(transfer);
786                 return;
787         }
788
789         sr_info("fx2lafw: receive_transfer(): status %d received %d bytes.",
790                 transfer->status, transfer->actual_length);
791
792         /* Save incoming transfer before reusing the transfer struct. */
793         uint8_t *const cur_buf = transfer->buffer;
794         const int sample_width = ctx->sample_wide ? 2 : 1;
795         const int cur_sample_count = transfer->actual_length / sample_width;
796
797         switch (transfer->status) {
798         case LIBUSB_TRANSFER_NO_DEVICE:
799                 abort_acquisition(ctx);
800                 free_transfer(transfer);
801                 return;
802         case LIBUSB_TRANSFER_COMPLETED:
803         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though */
804                 break;
805         default:
806                 packet_has_error = TRUE;
807                 break;
808         }
809
810         if (transfer->actual_length == 0 || packet_has_error) {
811                 ctx->empty_transfer_count++;
812                 if (ctx->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
813                         /*
814                          * The FX2 gave up. End the acquisition, the frontend
815                          * will work out that the samplecount is short.
816                          */
817                         abort_acquisition(ctx);
818                         free_transfer(transfer);
819                 } else {
820                         resubmit_transfer(transfer);
821                 }
822                 return;
823         } else {
824                 ctx->empty_transfer_count = 0;
825         }
826
827         trigger_offset = 0;
828         if (ctx->trigger_stage >= 0) {
829                 for (i = 0; i < cur_sample_count; i++) {
830
831                         const uint16_t cur_sample = ctx->sample_wide ?
832                                 *((const uint16_t*)cur_buf + i) :
833                                 *((const uint8_t*)cur_buf + i);
834
835                         if ((cur_sample & ctx->trigger_mask[ctx->trigger_stage]) ==
836                                 ctx->trigger_value[ctx->trigger_stage]) {
837                                 /* Match on this trigger stage. */
838                                 ctx->trigger_buffer[ctx->trigger_stage] = cur_sample;
839                                 ctx->trigger_stage++;
840
841                                 if (ctx->trigger_stage == NUM_TRIGGER_STAGES ||
842                                         ctx->trigger_mask[ctx->trigger_stage] == 0) {
843                                         /* Match on all trigger stages, we're done. */
844                                         trigger_offset = i + 1;
845
846                                         /*
847                                          * TODO: Send pre-trigger buffer to session bus.
848                                          * Tell the frontend we hit the trigger here.
849                                          */
850                                         packet.type = SR_DF_TRIGGER;
851                                         packet.payload = NULL;
852                                         sr_session_send(ctx->session_dev_id, &packet);
853
854                                         /*
855                                          * Send the samples that triggered it, since we're
856                                          * skipping past them.
857                                          */
858                                         packet.type = SR_DF_LOGIC;
859                                         packet.payload = &logic;
860                                         logic.unitsize = sizeof(*ctx->trigger_buffer);
861                                         logic.length = ctx->trigger_stage * logic.unitsize;
862                                         logic.data = ctx->trigger_buffer;
863                                         sr_session_send(ctx->session_dev_id, &packet);
864
865                                         ctx->trigger_stage = TRIGGER_FIRED;
866                                         break;
867                                 }
868                         } else if (ctx->trigger_stage > 0) {
869                                 /*
870                                  * We had a match before, but not in the next sample. However, we may
871                                  * have a match on this stage in the next bit -- trigger on 0001 will
872                                  * fail on seeing 00001, so we need to go back to stage 0 -- but at
873                                  * the next sample from the one that matched originally, which the
874                                  * counter increment at the end of the loop takes care of.
875                                  */
876                                 i -= ctx->trigger_stage;
877                                 if (i < -1)
878                                         i = -1; /* Oops, went back past this buffer. */
879                                 /* Reset trigger stage. */
880                                 ctx->trigger_stage = 0;
881                         }
882                 }
883         }
884
885         if (ctx->trigger_stage == TRIGGER_FIRED) {
886                 /* Send the incoming transfer to the session bus. */
887                 const int trigger_offset_bytes = trigger_offset * sample_width;
888                 packet.type = SR_DF_LOGIC;
889                 packet.payload = &logic;
890                 logic.length = transfer->actual_length - trigger_offset_bytes;
891                 logic.unitsize = sample_width;
892                 logic.data = cur_buf + trigger_offset_bytes;
893                 sr_session_send(ctx->session_dev_id, &packet);
894
895                 ctx->num_samples += cur_sample_count;
896                 if (ctx->limit_samples &&
897                         (unsigned int)ctx->num_samples > ctx->limit_samples) {
898                         abort_acquisition(ctx);
899                         free_transfer(transfer);
900                         return;
901                 }
902         } else {
903                 /*
904                  * TODO: Buffer pre-trigger data in capture
905                  * ratio-sized buffer.
906                  */
907         }
908
909         resubmit_transfer(transfer);
910 }
911
912 static unsigned int to_bytes_per_ms(unsigned int samplerate)
913 {
914         return samplerate / 1000;
915 }
916
917 static size_t get_buffer_size(struct context *ctx)
918 {
919         size_t s;
920
921         /* The buffer should be large enough to hold 10ms of data and a multiple
922          * of 512. */
923         s = 10 * to_bytes_per_ms(ctx->cur_samplerate);
924         return (s + 511) & ~511;
925 }
926
927 static unsigned int get_number_of_transfers(struct context *ctx)
928 {
929         unsigned int n;
930
931         /* Total buffer size should be able to hold about 500ms of data */
932         n = 500 * to_bytes_per_ms(ctx->cur_samplerate) / get_buffer_size(ctx);
933
934         if (n > NUM_SIMUL_TRANSFERS)
935                 return NUM_SIMUL_TRANSFERS;
936
937         return n;
938 }
939
940 static unsigned int get_timeout(struct context *ctx)
941 {
942         size_t total_size;
943         unsigned int timeout;
944
945         total_size = get_buffer_size(ctx) * get_number_of_transfers(ctx);
946         timeout = total_size / to_bytes_per_ms(ctx->cur_samplerate);
947         return timeout + timeout / 4; /* Leave a headroom of 25% percent */
948 }
949
950 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
951 {
952         struct sr_dev_inst *sdi;
953         struct sr_datafeed_packet packet;
954         struct sr_datafeed_header header;
955         struct sr_datafeed_meta_logic meta;
956         struct context *ctx;
957         struct libusb_transfer *transfer;
958         const struct libusb_pollfd **lupfd;
959         unsigned int i;
960         int ret;
961         unsigned char *buf;
962
963         if (!(sdi = sr_dev_inst_get(fdi->instances, dev_index)))
964                 return SR_ERR;
965         ctx = sdi->priv;
966
967         if (ctx->submitted_transfers != 0)
968                 return SR_ERR;
969
970         ctx->session_dev_id = cb_data;
971         ctx->num_samples = 0;
972         ctx->empty_transfer_count = 0;
973
974         const unsigned int timeout = get_timeout(ctx);
975         const unsigned int num_transfers = get_number_of_transfers(ctx);
976         const size_t size = get_buffer_size(ctx);
977
978         ctx->transfers = g_try_malloc0(sizeof(*ctx->transfers) * num_transfers);
979         if (!ctx->transfers)
980                 return SR_ERR;
981
982         ctx->num_transfers = num_transfers;
983
984         for (i = 0; i < num_transfers; i++) {
985                 if (!(buf = g_try_malloc(size))) {
986                         sr_err("fx2lafw: %s: buf malloc failed.", __func__);
987                         return SR_ERR_MALLOC;
988                 }
989                 transfer = libusb_alloc_transfer(0);
990                 libusb_fill_bulk_transfer(transfer, ctx->usb->devhdl,
991                                 2 | LIBUSB_ENDPOINT_IN, buf, size,
992                                 receive_transfer, ctx, timeout);
993                 if (libusb_submit_transfer(transfer) != 0) {
994                         libusb_free_transfer(transfer);
995                         g_free(buf);
996                         abort_acquisition(ctx);
997                         return SR_ERR;
998                 }
999                 ctx->transfers[i] = transfer;
1000                 ctx->submitted_transfers++;
1001         }
1002
1003         lupfd = libusb_get_pollfds(usb_context);
1004         for (i = 0; lupfd[i]; i++)
1005                 sr_source_add(lupfd[i]->fd, lupfd[i]->events,
1006                               timeout, receive_data, NULL);
1007         free(lupfd); /* NOT g_free()! */
1008
1009         packet.type = SR_DF_HEADER;
1010         packet.payload = &header;
1011         header.feed_version = 1;
1012         gettimeofday(&header.starttime, NULL);
1013         sr_session_send(cb_data, &packet);
1014
1015         /* Send metadata about the SR_DF_LOGIC packets to come. */
1016         packet.type = SR_DF_META_LOGIC;
1017         packet.payload = &meta;
1018         meta.samplerate = ctx->cur_samplerate;
1019         meta.num_probes = ctx->sample_wide ? 16 : 8;
1020         sr_session_send(cb_data, &packet);
1021
1022         if ((ret = command_start_acquisition (ctx->usb->devhdl,
1023                 ctx->cur_samplerate, ctx->sample_wide)) != SR_OK) {
1024                 abort_acquisition(ctx);
1025                 return ret;
1026         }
1027
1028         return SR_OK;
1029 }
1030
1031 /* TODO: This stops acquisition on ALL devices, ignoring dev_index. */
1032 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
1033 {
1034         struct sr_dev_inst *sdi;
1035
1036         /* Avoid compiler warnings. */
1037         (void)cb_data;
1038
1039         if (!(sdi = sr_dev_inst_get(fdi->instances, dev_index)))
1040                 return SR_ERR;
1041  
1042         abort_acquisition(sdi->priv);
1043
1044         return SR_OK;
1045 }
1046
1047 SR_PRIV struct sr_dev_driver fx2lafw_driver_info = {
1048         .name = "fx2lafw",
1049         .longname = "fx2lafw (generic driver for FX2 based LAs)",
1050         .api_version = 1,
1051         .init = hw_init,
1052         .cleanup = hw_cleanup,
1053         .scan = hw_scan,
1054         .dev_open = hw_dev_open,
1055         .dev_close = hw_dev_close,
1056         .info_get = hw_info_get,
1057         .dev_status_get = hw_dev_status_get,
1058         .dev_config_set = hw_dev_config_set,
1059         .dev_acquisition_start = hw_dev_acquisition_start,
1060         .dev_acquisition_stop = hw_dev_acquisition_stop,
1061         .instances = NULL,
1062 };