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