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