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