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