sr/drivers: add API calls sr_dev_inst_list() and sr_dev_inst_clear()
[sigrok:sigrok.git] / libsigrok / 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 SR_PRIV struct sr_dev_driver fx2lafw_driver_info;
143 static struct sr_dev_driver *fdi = &fx2lafw_driver_info;
144 static int hw_dev_close(struct sr_dev_inst *sdi);
145 static int hw_dev_config_set(const struct sr_dev_inst *sdi, int hwcap,
146                 const void *value);
147 static int hw_dev_acquisition_stop(const struct sr_dev_inst *sdi,
148                 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(struct sr_dev_inst *sdi)
195 {
196         libusb_device **devlist;
197         struct libusb_device_descriptor des;
198         struct drv_context *drvc;
199         struct dev_context *devc;
200         struct version_info vi;
201         int ret, skip, i;
202         uint8_t revid;
203
204         drvc = fdi->priv;
205         devc = sdi->priv;
206
207         if (sdi->status == SR_ST_ACTIVE)
208                 /* already in use */
209                 return SR_ERR;
210
211         skip = 0;
212         const int device_count = libusb_get_device_list(drvc->usb_context, &devlist);
213         if (device_count < 0) {
214                 sr_err("fx2lafw: Failed to retrieve device list (%d)",
215                         device_count);
216                 return SR_ERR;
217         }
218
219         for (i = 0; i < device_count; i++) {
220                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
221                         sr_err("fx2lafw: Failed to get device descriptor: %d.",
222                                ret);
223                         continue;
224                 }
225
226                 if (des.idVendor != devc->profile->vid
227                     || des.idProduct != devc->profile->pid)
228                         continue;
229
230                 if (sdi->status == SR_ST_INITIALIZING) {
231                         if (skip != sdi->index) {
232                                 /* Skip devices of this type that aren't the one we want. */
233                                 skip += 1;
234                                 continue;
235                         }
236                 } else if (sdi->status == SR_ST_INACTIVE) {
237                         /*
238                          * This device is fully enumerated, so we need to find
239                          * this device by vendor, product, bus and address.
240                          */
241                         if (libusb_get_bus_number(devlist[i]) != devc->usb->bus
242                                 || libusb_get_device_address(devlist[i]) != devc->usb->address)
243                                 /* this is not the one */
244                                 continue;
245                 }
246
247                 if (!(ret = libusb_open(devlist[i], &devc->usb->devhdl))) {
248                         if (devc->usb->address == 0xff)
249                                 /*
250                                  * first time we touch this device after firmware upload,
251                                  * so we don't know the address yet.
252                                  */
253                                 devc->usb->address = libusb_get_device_address(devlist[i]);
254                 } else {
255                         sr_err("fx2lafw: Failed to open device: %d.", ret);
256                         break;
257                 }
258
259                 ret = command_get_fw_version(devc->usb->devhdl, &vi);
260                 if (ret != SR_OK) {
261                         sr_err("fx2lafw: Failed to retrieve "
262                                "firmware version information.");
263                         break;
264                 }
265
266                 ret = command_get_revid_version(devc->usb->devhdl, &revid);
267                 if (ret != SR_OK) {
268                         sr_err("fx2lafw: Failed to retrieve REVID.");
269                         break;
270                 }
271
272                 /*
273                  * Changes in major version mean incompatible/API changes, so
274                  * bail out if we encounter an incompatible version.
275                  * Different minor versions are OK, they should be compatible.
276                  */
277                 if (vi.major != FX2LAFW_REQUIRED_VERSION_MAJOR) {
278                         sr_err("fx2lafw: Expected firmware version %d.x, "
279                                "got %d.%d.", FX2LAFW_REQUIRED_VERSION_MAJOR,
280                                vi.major, vi.minor);
281                         break;
282                 }
283
284                 sdi->status = SR_ST_ACTIVE;
285                 sr_info("fx2lafw: Opened device %d on %d.%d "
286                         "interface %d, firmware %d.%d, REVID %d.",
287                         sdi->index, devc->usb->bus, devc->usb->address,
288                         USB_INTERFACE, vi.major, vi.minor, revid);
289
290                 break;
291         }
292         libusb_free_device_list(devlist, 1);
293
294         if (sdi->status != SR_ST_ACTIVE)
295                 return SR_ERR;
296
297         return SR_OK;
298 }
299
300 static int configure_probes(const struct sr_dev_inst *sdi)
301 {
302         struct dev_context *devc;
303         struct sr_probe *probe;
304         GSList *l;
305         int probe_bit, stage, i;
306         char *tc;
307
308         devc = sdi->priv;
309         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
310                 devc->trigger_mask[i] = 0;
311                 devc->trigger_value[i] = 0;
312         }
313
314         stage = -1;
315         for (l = sdi->probes; l; l = l->next) {
316                 probe = (struct sr_probe *)l->data;
317                 if (probe->enabled == FALSE)
318                         continue;
319
320                 if (probe->index > 7)
321                         devc->sample_wide = TRUE;
322
323                 probe_bit = 1 << (probe->index);
324                 if (!(probe->trigger))
325                         continue;
326
327                 stage = 0;
328                 for (tc = probe->trigger; *tc; tc++) {
329                         devc->trigger_mask[stage] |= probe_bit;
330                         if (*tc == '1')
331                                 devc->trigger_value[stage] |= probe_bit;
332                         stage++;
333                         if (stage > NUM_TRIGGER_STAGES)
334                                 return SR_ERR;
335                 }
336         }
337
338         if (stage == -1)
339                 /*
340                  * We didn't configure any triggers, make sure acquisition
341                  * doesn't wait for any.
342                  */
343                 devc->trigger_stage = TRIGGER_FIRED;
344         else
345                 devc->trigger_stage = 0;
346
347         return SR_OK;
348 }
349
350 static struct dev_context *fx2lafw_dev_new(void)
351 {
352         struct dev_context *devc;
353
354         if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
355                 sr_err("fx2lafw: %s: devc malloc failed.", __func__);
356                 return NULL;
357         }
358
359         devc->trigger_stage = TRIGGER_FIRED;
360
361         return devc;
362 }
363
364 static int clear_instances(void)
365 {
366         GSList *l;
367         struct sr_dev_inst *sdi;
368         struct drv_context *drvc;
369         struct dev_context *devc;
370         int ret;
371
372         drvc = fdi->priv;
373         ret = SR_OK;
374         for (l = drvc->instances; l; l = l->next) {
375                 if (!(sdi = l->data)) {
376                         /* Log error, but continue cleaning up the rest. */
377                         sr_err("fx2lafw: %s: sdi was NULL, continuing.",
378                                    __func__);
379                         ret = SR_ERR_BUG;
380                         continue;
381                 }
382                 if (!(devc = sdi->priv)) {
383                         /* Log error, but continue cleaning up the rest. */
384                         sr_err("fx2lafw: %s: sdi->priv was NULL, continuing",
385                                    __func__);
386                         ret = SR_ERR_BUG;
387                         continue;
388                 }
389                 hw_dev_close(sdi);
390                 sr_usb_dev_inst_free(devc->usb);
391                 sdi = l->data;
392                 sr_dev_inst_free(sdi);
393         }
394
395         g_slist_free(drvc->instances);
396         drvc->instances = NULL;
397
398         return ret;
399 }
400
401
402 /*
403  * API callbacks
404  */
405
406 static int hw_init(void)
407 {
408         struct drv_context *drvc;
409
410         if (!(drvc = g_try_malloc0(sizeof(struct drv_context)))) {
411                 sr_err("fx2lafw: driver context malloc failed.");
412                 return SR_ERR;
413         }
414
415         if (libusb_init(&drvc->usb_context) != 0) {
416                 g_free(drvc);
417                 sr_warn("fx2lafw: Failed to initialize libusb.");
418                 return SR_ERR;
419         }
420
421         fdi->priv = drvc;
422
423         return SR_OK;
424 }
425
426 static GSList *hw_scan(GSList *options)
427 {
428         GSList *devices;
429         struct libusb_device_descriptor des;
430         struct sr_dev_inst *sdi;
431         const struct fx2lafw_profile *prof;
432         struct drv_context *drvc;
433         struct dev_context *devc;
434         struct sr_probe *probe;
435         libusb_device **devlist;
436         int devcnt, num_logic_probes, ret, i, j;
437
438         /* Avoid compiler warnings. */
439         (void)options;
440         drvc = fdi->priv;
441
442         /* This scan always invalidates any previous scans. */
443         clear_instances();
444
445         /* Find all fx2lafw compatible devices and upload firmware to them. */
446         devices = NULL;
447         libusb_get_device_list(drvc->usb_context, &devlist);
448         for (i = 0; devlist[i]; i++) {
449
450                 if ((ret = libusb_get_device_descriptor(
451                      devlist[i], &des)) != 0) {
452                         sr_warn("fx2lafw: Failed to get device descriptor: %d.", ret);
453                         continue;
454                 }
455
456                 prof = NULL;
457                 for (j = 0; supported_fx2[j].vid; j++) {
458                         if (des.idVendor == supported_fx2[j].vid &&
459                                 des.idProduct == supported_fx2[j].pid) {
460                                 prof = &supported_fx2[j];
461                         }
462                 }
463
464                 /* Skip if the device was not found */
465                 if (!prof)
466                         continue;
467
468                 devcnt = g_slist_length(drvc->instances);
469                 sdi = sr_dev_inst_new(devcnt, SR_ST_INITIALIZING,
470                         prof->vendor, prof->model, prof->model_version);
471                 if (!sdi)
472                         return NULL;
473                 sdi->driver = fdi;
474
475                 /* Fill in probelist according to this device's profile. */
476                 num_logic_probes = prof->dev_caps & DEV_CAPS_16BIT ? 16 : 8;
477                 for (j = 0; j < num_logic_probes; j++) {
478                         if (!(probe = sr_probe_new(j, SR_PROBE_LOGIC, TRUE,
479                                         probe_names[j])))
480                                 return NULL;
481                         sdi->probes = g_slist_append(sdi->probes, probe);
482                 }
483
484                 devc = fx2lafw_dev_new();
485                 devc->profile = prof;
486                 sdi->priv = devc;
487                 drvc->instances = g_slist_append(drvc->instances, sdi);
488                 devices = g_slist_append(devices, sdi);
489
490                 if (check_conf_profile(devlist[i])) {
491                         /* Already has the firmware, so fix the new address. */
492                         sr_dbg("fx2lafw: Found an fx2lafw device.");
493                         sdi->status = SR_ST_INACTIVE;
494                         devc->usb = sr_usb_dev_inst_new
495                             (libusb_get_bus_number(devlist[i]),
496                              libusb_get_device_address(devlist[i]), NULL);
497                 } else {
498                         if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
499                                 prof->firmware) == SR_OK)
500                                 /* Remember when the firmware on this device was updated */
501                                 devc->fw_updated = g_get_monotonic_time();
502                         else
503                                 sr_err("fx2lafw: Firmware upload failed for "
504                                        "device %d.", devcnt);
505                         devc->usb = sr_usb_dev_inst_new
506                                 (libusb_get_bus_number(devlist[i]), 0xff, NULL);
507                 }
508         }
509         libusb_free_device_list(devlist, 1);
510
511         return devices;
512 }
513
514 static GSList *hw_dev_list(void)
515 {
516         struct drv_context *drvc;
517
518         drvc = fdi->priv;
519
520         return drvc->instances;
521 }
522
523 static int hw_dev_open(struct sr_dev_inst *sdi)
524 {
525         struct dev_context *devc;
526         int ret;
527         int64_t timediff_us, timediff_ms;
528
529         devc = sdi->priv;
530
531         /*
532          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
533          * milliseconds for the FX2 to renumerate.
534          */
535         ret = SR_ERR;
536         if (devc->fw_updated > 0) {
537                 sr_info("fx2lafw: Waiting for device to reset.");
538                 /* takes at least 300ms for the FX2 to be gone from the USB bus */
539                 g_usleep(300 * 1000);
540                 timediff_ms = 0;
541                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
542                         if ((ret = fx2lafw_dev_open(sdi)) == SR_OK)
543                                 break;
544                         g_usleep(100 * 1000);
545
546                         timediff_us = g_get_monotonic_time() - devc->fw_updated;
547                         timediff_ms = timediff_us / 1000;
548                         sr_spew("fx2lafw: waited %" PRIi64 " ms", timediff_ms);
549                 }
550                 sr_info("fx2lafw: Device came back after %d ms.", timediff_ms);
551         } else {
552                 ret = fx2lafw_dev_open(sdi);
553         }
554
555         if (ret != SR_OK) {
556                 sr_err("fx2lafw: Unable to open device.");
557                 return SR_ERR;
558         }
559         devc = sdi->priv;
560
561         ret = libusb_claim_interface(devc->usb->devhdl, USB_INTERFACE);
562         if (ret != 0) {
563                 switch(ret) {
564                 case LIBUSB_ERROR_BUSY:
565                         sr_err("fx2lafw: Unable to claim USB interface. Another "
566                                 "program or driver has already claimed it.");
567                         break;
568
569                 case LIBUSB_ERROR_NO_DEVICE:
570                         sr_err("fx2lafw: Device has been disconnected.");
571                         break;
572
573                 default:
574                         sr_err("fx2lafw: Unable to claim interface: %d.", ret);
575                         break;
576                 }
577
578                 return SR_ERR;
579         }
580
581         if (devc->cur_samplerate == 0) {
582                 /* Samplerate hasn't been set; default to the slowest one. */
583                 if (hw_dev_config_set(sdi, SR_HWCAP_SAMPLERATE,
584                     &supported_samplerates[0]) == SR_ERR)
585                         return SR_ERR;
586         }
587
588         return SR_OK;
589 }
590
591 static int hw_dev_close(struct sr_dev_inst *sdi)
592 {
593         struct dev_context *devc;
594
595         devc = sdi->priv;
596         if (devc->usb->devhdl == NULL)
597                 return SR_ERR;
598
599         sr_info("fx2lafw: Closing device %d on %d.%d interface %d.",
600                 sdi->index, devc->usb->bus, devc->usb->address, USB_INTERFACE);
601         libusb_release_interface(devc->usb->devhdl, USB_INTERFACE);
602         libusb_close(devc->usb->devhdl);
603         devc->usb->devhdl = NULL;
604         sdi->status = SR_ST_INACTIVE;
605
606         return SR_OK;
607 }
608
609 static int hw_cleanup(void)
610 {
611         struct drv_context *drvc;
612         int ret;
613
614         if (!(drvc = fdi->priv))
615                 return SR_OK;
616
617         ret = clear_instances();
618
619         if (drvc->usb_context)
620                 libusb_exit(drvc->usb_context);
621         drvc->usb_context = NULL;
622
623         g_free(drvc);
624         fdi->priv = NULL;
625
626         return ret;
627 }
628
629 static int hw_info_get(int info_id, const void **data,
630                 const struct sr_dev_inst *sdi)
631 {
632         struct dev_context *devc;
633
634         switch (info_id) {
635         case SR_DI_HWCAPS:
636                 *data = hwcaps;
637                 break;
638         case SR_DI_NUM_PROBES:
639                 if (sdi) {
640                         devc = sdi->priv;
641                         *data = GINT_TO_POINTER(
642                                 (devc->profile->dev_caps & DEV_CAPS_16BIT) ?
643                                 16 : 8);
644                 } else
645                         return SR_ERR;
646                 break;
647         case SR_DI_PROBE_NAMES:
648                 *data = probe_names;
649                 break;
650         case SR_DI_SAMPLERATES:
651                 *data = &samplerates;
652                 break;
653         case SR_DI_TRIGGER_TYPES:
654                 *data = TRIGGER_TYPES;
655                 break;
656         case SR_DI_CUR_SAMPLERATE:
657                 if (sdi) {
658                         devc = sdi->priv;
659                         *data = &devc->cur_samplerate;
660                 } else
661                         return SR_ERR;
662                 break;
663         default:
664                 return SR_ERR_ARG;
665         }
666
667         return SR_OK;
668 }
669
670 static int hw_dev_config_set(const struct sr_dev_inst *sdi, int hwcap,
671                 const void *value)
672 {
673         struct dev_context *devc;
674         int ret;
675
676         devc = sdi->priv;
677
678         if (hwcap == SR_HWCAP_SAMPLERATE) {
679                 devc->cur_samplerate = *(const uint64_t *)value;
680                 ret = SR_OK;
681         } else if (hwcap == SR_HWCAP_LIMIT_SAMPLES) {
682                 devc->limit_samples = *(const uint64_t *)value;
683                 ret = SR_OK;
684         } else {
685                 ret = SR_ERR;
686         }
687
688         return ret;
689 }
690
691 static int receive_data(int fd, int revents, void *cb_data)
692 {
693         struct drv_context *drvc;
694         struct timeval tv;
695
696         /* Avoid compiler warnings. */
697         (void)fd;
698         (void)revents;
699         (void)cb_data;
700
701         drvc = fdi->priv;
702         tv.tv_sec = tv.tv_usec = 0;
703         libusb_handle_events_timeout(drvc->usb_context, &tv);
704
705         return TRUE;
706 }
707
708 static void abort_acquisition(struct dev_context *devc)
709 {
710         int i;
711
712         devc->num_samples = -1;
713
714         for (i = devc->num_transfers - 1; i >= 0; i--) {
715                 if (devc->transfers[i])
716                         libusb_cancel_transfer(devc->transfers[i]);
717         }
718 }
719
720 static void finish_acquisition(struct dev_context *devc)
721 {
722         struct drv_context *drvc;
723         struct sr_datafeed_packet packet;
724         int i;
725
726         drvc = fdi->priv;
727
728         /* Terminate session */
729         packet.type = SR_DF_END;
730         sr_session_send(devc->session_dev_id, &packet);
731
732         /* Remove fds from polling */
733         const struct libusb_pollfd **const lupfd =
734                 libusb_get_pollfds(drvc->usb_context);
735         for (i = 0; lupfd[i]; i++)
736                 sr_source_remove(lupfd[i]->fd);
737         free(lupfd); /* NOT g_free()! */
738
739         devc->num_transfers = 0;
740         g_free(devc->transfers);
741 }
742
743 static void free_transfer(struct libusb_transfer *transfer)
744 {
745         struct dev_context *devc = transfer->user_data;
746         unsigned int i;
747
748         g_free(transfer->buffer);
749         transfer->buffer = NULL;
750         libusb_free_transfer(transfer);
751
752         for (i = 0; i < devc->num_transfers; i++) {
753                 if (devc->transfers[i] == transfer) {
754                         devc->transfers[i] = NULL;
755                         break;
756                 }
757         }
758
759         devc->submitted_transfers--;
760         if (devc->submitted_transfers == 0)
761                 finish_acquisition(devc);
762
763 }
764
765 static void resubmit_transfer(struct libusb_transfer *transfer)
766 {
767         if (libusb_submit_transfer(transfer) != 0) {
768                 free_transfer(transfer);
769                 /* TODO: Stop session? */
770                 /* TODO: Better error message. */
771                 sr_err("fx2lafw: %s: libusb_submit_transfer error.", __func__);
772         }
773 }
774
775 static void receive_transfer(struct libusb_transfer *transfer)
776 {
777         gboolean packet_has_error = FALSE;
778         struct sr_datafeed_packet packet;
779         struct sr_datafeed_logic logic;
780         struct dev_context *devc = transfer->user_data;
781         int trigger_offset, i;
782
783         /*
784          * If acquisition has already ended, just free any queued up
785          * transfer that come in.
786          */
787         if (devc->num_samples == -1) {
788                 free_transfer(transfer);
789                 return;
790         }
791
792         sr_info("fx2lafw: receive_transfer(): status %d received %d bytes.",
793                 transfer->status, transfer->actual_length);
794
795         /* Save incoming transfer before reusing the transfer struct. */
796         uint8_t *const cur_buf = transfer->buffer;
797         const int sample_width = devc->sample_wide ? 2 : 1;
798         const int cur_sample_count = transfer->actual_length / sample_width;
799
800         switch (transfer->status) {
801         case LIBUSB_TRANSFER_NO_DEVICE:
802                 abort_acquisition(devc);
803                 free_transfer(transfer);
804                 return;
805         case LIBUSB_TRANSFER_COMPLETED:
806         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though */
807                 break;
808         default:
809                 packet_has_error = TRUE;
810                 break;
811         }
812
813         if (transfer->actual_length == 0 || packet_has_error) {
814                 devc->empty_transfer_count++;
815                 if (devc->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
816                         /*
817                          * The FX2 gave up. End the acquisition, the frontend
818                          * will work out that the samplecount is short.
819                          */
820                         abort_acquisition(devc);
821                         free_transfer(transfer);
822                 } else {
823                         resubmit_transfer(transfer);
824                 }
825                 return;
826         } else {
827                 devc->empty_transfer_count = 0;
828         }
829
830         trigger_offset = 0;
831         if (devc->trigger_stage >= 0) {
832                 for (i = 0; i < cur_sample_count; i++) {
833
834                         const uint16_t cur_sample = devc->sample_wide ?
835                                 *((const uint16_t*)cur_buf + i) :
836                                 *((const uint8_t*)cur_buf + i);
837
838                         if ((cur_sample & devc->trigger_mask[devc->trigger_stage]) ==
839                                 devc->trigger_value[devc->trigger_stage]) {
840                                 /* Match on this trigger stage. */
841                                 devc->trigger_buffer[devc->trigger_stage] = cur_sample;
842                                 devc->trigger_stage++;
843
844                                 if (devc->trigger_stage == NUM_TRIGGER_STAGES ||
845                                         devc->trigger_mask[devc->trigger_stage] == 0) {
846                                         /* Match on all trigger stages, we're done. */
847                                         trigger_offset = i + 1;
848
849                                         /*
850                                          * TODO: Send pre-trigger buffer to session bus.
851                                          * Tell the frontend we hit the trigger here.
852                                          */
853                                         packet.type = SR_DF_TRIGGER;
854                                         packet.payload = NULL;
855                                         sr_session_send(devc->session_dev_id, &packet);
856
857                                         /*
858                                          * Send the samples that triggered it, since we're
859                                          * skipping past them.
860                                          */
861                                         packet.type = SR_DF_LOGIC;
862                                         packet.payload = &logic;
863                                         logic.unitsize = sizeof(*devc->trigger_buffer);
864                                         logic.length = devc->trigger_stage * logic.unitsize;
865                                         logic.data = devc->trigger_buffer;
866                                         sr_session_send(devc->session_dev_id, &packet);
867
868                                         devc->trigger_stage = TRIGGER_FIRED;
869                                         break;
870                                 }
871                         } else if (devc->trigger_stage > 0) {
872                                 /*
873                                  * We had a match before, but not in the next sample. However, we may
874                                  * have a match on this stage in the next bit -- trigger on 0001 will
875                                  * fail on seeing 00001, so we need to go back to stage 0 -- but at
876                                  * the next sample from the one that matched originally, which the
877                                  * counter increment at the end of the loop takes care of.
878                                  */
879                                 i -= devc->trigger_stage;
880                                 if (i < -1)
881                                         i = -1; /* Oops, went back past this buffer. */
882                                 /* Reset trigger stage. */
883                                 devc->trigger_stage = 0;
884                         }
885                 }
886         }
887
888         if (devc->trigger_stage == TRIGGER_FIRED) {
889                 /* Send the incoming transfer to the session bus. */
890                 const int trigger_offset_bytes = trigger_offset * sample_width;
891                 packet.type = SR_DF_LOGIC;
892                 packet.payload = &logic;
893                 logic.length = transfer->actual_length - trigger_offset_bytes;
894                 logic.unitsize = sample_width;
895                 logic.data = cur_buf + trigger_offset_bytes;
896                 sr_session_send(devc->session_dev_id, &packet);
897
898                 devc->num_samples += cur_sample_count;
899                 if (devc->limit_samples &&
900                         (unsigned int)devc->num_samples > devc->limit_samples) {
901                         abort_acquisition(devc);
902                         free_transfer(transfer);
903                         return;
904                 }
905         } else {
906                 /*
907                  * TODO: Buffer pre-trigger data in capture
908                  * ratio-sized buffer.
909                  */
910         }
911
912         resubmit_transfer(transfer);
913 }
914
915 static unsigned int to_bytes_per_ms(unsigned int samplerate)
916 {
917         return samplerate / 1000;
918 }
919
920 static size_t get_buffer_size(struct dev_context *devc)
921 {
922         size_t s;
923
924         /* The buffer should be large enough to hold 10ms of data and a multiple
925          * of 512. */
926         s = 10 * to_bytes_per_ms(devc->cur_samplerate);
927         return (s + 511) & ~511;
928 }
929
930 static unsigned int get_number_of_transfers(struct dev_context *devc)
931 {
932         unsigned int n;
933
934         /* Total buffer size should be able to hold about 500ms of data */
935         n = 500 * to_bytes_per_ms(devc->cur_samplerate) / get_buffer_size(devc);
936
937         if (n > NUM_SIMUL_TRANSFERS)
938                 return NUM_SIMUL_TRANSFERS;
939
940         return n;
941 }
942
943 static unsigned int get_timeout(struct dev_context *devc)
944 {
945         size_t total_size;
946         unsigned int timeout;
947
948         total_size = get_buffer_size(devc) * get_number_of_transfers(devc);
949         timeout = total_size / to_bytes_per_ms(devc->cur_samplerate);
950         return timeout + timeout / 4; /* Leave a headroom of 25% percent */
951 }
952
953 static int hw_dev_acquisition_start(const struct sr_dev_inst *sdi,
954                 void *cb_data)
955 {
956         struct sr_datafeed_packet packet;
957         struct sr_datafeed_header header;
958         struct sr_datafeed_meta_logic meta;
959         struct drv_context *drvc;
960         struct dev_context *devc;
961         struct libusb_transfer *transfer;
962         const struct libusb_pollfd **lupfd;
963         unsigned int i;
964         int ret;
965         unsigned char *buf;
966
967         drvc = fdi->priv;
968         devc = sdi->priv;
969         if (devc->submitted_transfers != 0)
970                 return SR_ERR;
971
972         if (configure_probes(sdi) != SR_OK) {
973                 sr_err("fx2lafw: failed to configured probes");
974                 return SR_ERR;
975         }
976
977         devc->session_dev_id = cb_data;
978         devc->num_samples = 0;
979         devc->empty_transfer_count = 0;
980
981         const unsigned int timeout = get_timeout(devc);
982         const unsigned int num_transfers = get_number_of_transfers(devc);
983         const size_t size = get_buffer_size(devc);
984
985         devc->transfers = g_try_malloc0(sizeof(*devc->transfers) * num_transfers);
986         if (!devc->transfers)
987                 return SR_ERR;
988
989         devc->num_transfers = num_transfers;
990
991         for (i = 0; i < num_transfers; i++) {
992                 if (!(buf = g_try_malloc(size))) {
993                         sr_err("fx2lafw: %s: buf malloc failed.", __func__);
994                         return SR_ERR_MALLOC;
995                 }
996                 transfer = libusb_alloc_transfer(0);
997                 libusb_fill_bulk_transfer(transfer, devc->usb->devhdl,
998                                 2 | LIBUSB_ENDPOINT_IN, buf, size,
999                                 receive_transfer, devc, timeout);
1000                 if (libusb_submit_transfer(transfer) != 0) {
1001                         libusb_free_transfer(transfer);
1002                         g_free(buf);
1003                         abort_acquisition(devc);
1004                         return SR_ERR;
1005                 }
1006                 devc->transfers[i] = transfer;
1007                 devc->submitted_transfers++;
1008         }
1009
1010         lupfd = libusb_get_pollfds(drvc->usb_context);
1011         for (i = 0; lupfd[i]; i++)
1012                 sr_source_add(lupfd[i]->fd, lupfd[i]->events,
1013                               timeout, receive_data, NULL);
1014         free(lupfd); /* NOT g_free()! */
1015
1016         packet.type = SR_DF_HEADER;
1017         packet.payload = &header;
1018         header.feed_version = 1;
1019         gettimeofday(&header.starttime, NULL);
1020         sr_session_send(cb_data, &packet);
1021
1022         /* Send metadata about the SR_DF_LOGIC packets to come. */
1023         packet.type = SR_DF_META_LOGIC;
1024         packet.payload = &meta;
1025         meta.samplerate = devc->cur_samplerate;
1026         meta.num_probes = devc->sample_wide ? 16 : 8;
1027         sr_session_send(cb_data, &packet);
1028
1029         if ((ret = command_start_acquisition (devc->usb->devhdl,
1030                 devc->cur_samplerate, devc->sample_wide)) != SR_OK) {
1031                 abort_acquisition(devc);
1032                 return ret;
1033         }
1034
1035         return SR_OK;
1036 }
1037
1038 /* TODO: This stops acquisition on ALL devices, ignoring dev_index. */
1039 static int hw_dev_acquisition_stop(const struct sr_dev_inst *sdi,
1040                 void *cb_data)
1041 {
1042
1043         /* Avoid compiler warnings. */
1044         (void)cb_data;
1045
1046         abort_acquisition(sdi->priv);
1047
1048         return SR_OK;
1049 }
1050
1051 SR_PRIV struct sr_dev_driver fx2lafw_driver_info = {
1052         .name = "fx2lafw",
1053         .longname = "fx2lafw (generic driver for FX2 based LAs)",
1054         .api_version = 1,
1055         .init = hw_init,
1056         .cleanup = hw_cleanup,
1057         .scan = hw_scan,
1058         .dev_list = hw_dev_list,
1059         .dev_clear = clear_instances,
1060         .dev_open = hw_dev_open,
1061         .dev_close = hw_dev_close,
1062         .info_get = hw_info_get,
1063         .dev_config_set = hw_dev_config_set,
1064         .dev_acquisition_start = hw_dev_acquisition_start,
1065         .dev_acquisition_stop = hw_dev_acquisition_stop,
1066         .priv = NULL,
1067 };