]> sigrok.org Git - libsigrok.git/blob - hardware/fx2lafw/fx2lafw.c
fx2lafw: supported_samplerates[] should be 0-terminated.
[libsigrok.git] / hardware / fx2lafw / fx2lafw.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <inttypes.h>
23 #include <glib.h>
24 #include <libusb.h>
25 #include "config.h"
26 #include "sigrok.h"
27 #include "sigrok-internal.h"
28 #include "fx2lafw.h"
29 #include "command.h"
30
31 static const struct fx2lafw_profile supported_fx2[] = {
32         /*
33          * CWAV USBee AX
34          * EE Electronics ESLA201A
35          */
36         { 0x08a9, 0x0014, "CWAV", "USBee AX", NULL,
37                 FIRMWARE_DIR "/fx2lafw-cwav-usbeeax.fw", 8 },
38
39         /*
40          * CWAV USBee SX
41          */
42         { 0x08a9, 0x0009, "CWAV", "USBee SX", NULL,
43                 FIRMWARE_DIR "/fx2lafw-cwav-usbeesx.fw", 8 },
44
45         /*
46          * Saleae Logic
47          * EE Electronics ESLA100
48          * Robomotic MiniLogic
49          */
50         { 0x0925, 0x3881, "Saleae", "Logic", NULL,
51                 FIRMWARE_DIR "/fx2lafw-saleae-logic.fw", 8 },
52
53         /*
54          * Default Cypress FX2 without EEPROM
55          */
56         { 0x04B4, 0x8613, "Cypress", "FX2", NULL,
57                 FIRMWARE_DIR "/fx2lafw-cypress-fx2.fw", 8 },
58
59         { 0, 0, 0, 0, 0, 0, 0 }
60 };
61
62 static int hwcaps[] = {
63         SR_HWCAP_LOGIC_ANALYZER,
64         SR_HWCAP_SAMPLERATE,
65
66         /* These are really implemented in the driver, not the hardware. */
67         SR_HWCAP_LIMIT_SAMPLES,
68         SR_HWCAP_CONTINUOUS,
69         0,
70 };
71
72 /*
73  * TODO: Different probe_names[] for each supported device.
74  */
75 static const char *probe_names[] = {
76         "0",
77         "1",
78         "2",
79         "3",
80         "4",
81         "5",
82         "6",
83         "7",
84         NULL,
85 };
86
87 static uint64_t supported_samplerates[] = {
88         SR_KHZ(200),
89         SR_KHZ(250),
90         SR_KHZ(500),
91         SR_MHZ(1),
92         SR_MHZ(2),
93         SR_MHZ(3),
94         SR_MHZ(4),
95         SR_MHZ(6),
96         SR_MHZ(8),
97         SR_MHZ(12),
98         SR_MHZ(16),
99         SR_MHZ(24),
100         0,
101 };
102
103 static struct sr_samplerates samplerates = {
104         0,
105         0,
106         0,
107         supported_samplerates,
108 };
109
110 static GSList *dev_insts = NULL;
111 static libusb_context *usb_context = NULL;
112
113 static int hw_dev_config_set(int dev_index, int hwcap, void *value);
114 static int hw_dev_acquisition_stop(int dev_index, void *cb_data);
115
116 /**
117  * Check the USB configuration to determine if this is an fx2lafw device.
118  *
119  * @return TRUE if the device's configuration profile match fx2lafw
120  *         configuration, FALSE otherwise.
121  */
122 static gboolean check_conf_profile(libusb_device *dev)
123 {
124         struct libusb_device_descriptor des;
125         struct libusb_config_descriptor *conf_dsc = NULL;
126         const struct libusb_interface_descriptor *intf_dsc;
127         gboolean ret = FALSE;
128
129         while (!ret) {
130                 /* Assume the FW has not been loaded, unless proven wrong. */
131                 ret = FALSE;
132
133                 if (libusb_get_device_descriptor(dev, &des) != 0)
134                         break;
135
136                 /* Need exactly 1 configuration. */
137                 if (des.bNumConfigurations != 1)
138                         break;
139
140                 if (libusb_get_config_descriptor(dev, 0, &conf_dsc) != 0)
141                         break;
142
143                 /* Need exactly 1 interface. */
144                 if (conf_dsc->bNumInterfaces != 1)
145                         break;
146
147                 /* Need just one alternate setting. */
148                 if (conf_dsc->interface[0].num_altsetting != 1)
149                         break;
150
151                 /* Need exactly 2 endpoints. */
152                 intf_dsc = &(conf_dsc->interface[0].altsetting[0]);
153                 if (intf_dsc->bNumEndpoints != 2)
154                         break;
155
156                 /* The first endpoint should be 2 (inbound). */
157                 if ((intf_dsc->endpoint[0].bEndpointAddress & 0x8f) !=
158                     (2 | LIBUSB_ENDPOINT_IN))
159                         break;
160
161                 /* If we made it here, it must be an fx2lafw. */
162                 ret = TRUE;
163         }
164
165         if (conf_dsc)
166                 libusb_free_config_descriptor(conf_dsc);
167
168         return ret;
169 }
170
171 static int fx2lafw_dev_open(int dev_index)
172 {
173         libusb_device **devlist;
174         struct libusb_device_descriptor des;
175         struct sr_dev_inst *sdi;
176         struct context *ctx;
177         struct version_info vi;
178         int ret, skip, i;
179
180         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
181                 return SR_ERR;
182         ctx = sdi->priv;
183
184         if (sdi->status == SR_ST_ACTIVE)
185                 /* already in use */
186                 return SR_ERR;
187
188         skip = 0;
189         const int device_count = libusb_get_device_list(usb_context, &devlist);
190         if (device_count < 0) {
191                 sr_err("fx2lafw: Failed to retrieve device list (%d)",
192                         device_count);
193                 return SR_ERR;
194         }
195
196         for (i = 0; i < device_count; i++) {
197                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
198                         sr_err("fx2lafw: Failed to get device descriptor: %d.",
199                                ret);
200                         continue;
201                 }
202
203                 if (des.idVendor != ctx->profile->vid
204                     || des.idProduct != ctx->profile->pid)
205                         continue;
206
207                 if (sdi->status == SR_ST_INITIALIZING) {
208                         if (skip != dev_index) {
209                                 /* Skip devices of this type that aren't the one we want. */
210                                 skip += 1;
211                                 continue;
212                         }
213                 } else if (sdi->status == SR_ST_INACTIVE) {
214                         /*
215                          * This device is fully enumerated, so we need to find
216                          * this device by vendor, product, bus and address.
217                          */
218                         if (libusb_get_bus_number(devlist[i]) != ctx->usb->bus
219                                 || libusb_get_device_address(devlist[i]) != ctx->usb->address)
220                                 /* this is not the one */
221                                 continue;
222                 }
223
224                 if (!(ret = libusb_open(devlist[i], &ctx->usb->devhdl))) {
225                         if (ctx->usb->address == 0xff)
226                                 /*
227                                  * first time we touch this device after firmware upload,
228                                  * so we don't know the address yet.
229                                  */
230                                 ctx->usb->address = libusb_get_device_address(devlist[i]);
231                 } else {
232                         sr_err("fx2lafw: Failed to open device: %d.", ret);
233                         break;
234                 }
235
236                 ret = command_get_fw_version(ctx->usb->devhdl, &vi);
237                 if (ret != SR_OK) {
238                         sr_err("fx2lafw: Failed to retrieve "
239                                "firmware version information.");
240                         break;
241                 }
242
243                 if (vi.major != FX2LAFW_VERSION_MAJOR ||
244                     vi.minor != FX2LAFW_VERSION_MINOR) {
245                         sr_err("fx2lafw: Expected firmware version %d.%02d "
246                                "got %d.%02d.", FX2LAFW_VERSION_MAJOR,
247                                FX2LAFW_VERSION_MINOR, vi.major, vi.minor);
248                         break;
249                 }
250
251                 sdi->status = SR_ST_ACTIVE;
252                 sr_info("fx2lafw: Opened device %d on %d.%d "
253                         "interface %d, firmware version %d.%02d",
254                         sdi->index, ctx->usb->bus, ctx->usb->address,
255                         USB_INTERFACE, vi.major, vi.minor);
256
257                 break;
258         }
259         libusb_free_device_list(devlist, 1);
260
261         if (sdi->status != SR_ST_ACTIVE)
262                 return SR_ERR;
263
264         return SR_OK;
265 }
266
267 static void close_dev(struct sr_dev_inst *sdi)
268 {
269         struct context *ctx;
270
271         ctx = sdi->priv;
272
273         if (ctx->usb->devhdl == NULL)
274                 return;
275
276         sr_info("fx2lafw: Closing device %d on %d.%d interface %d.",
277                 sdi->index, ctx->usb->bus, ctx->usb->address, USB_INTERFACE);
278         libusb_release_interface(ctx->usb->devhdl, USB_INTERFACE);
279         libusb_close(ctx->usb->devhdl);
280         ctx->usb->devhdl = NULL;
281         sdi->status = SR_ST_INACTIVE;
282 }
283
284 static int configure_probes(struct context *ctx, GSList *probes)
285 {
286         struct sr_probe *probe;
287         GSList *l;
288         int probe_bit, stage, i;
289         char *tc;
290
291         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
292                 ctx->trigger_mask[i] = 0;
293                 ctx->trigger_value[i] = 0;
294         }
295
296         stage = -1;
297         for (l = probes; l; l = l->next) {
298                 probe = (struct sr_probe *)l->data;
299                 if (probe->enabled == FALSE)
300                         continue;
301                 probe_bit = 1 << (probe->index - 1);
302                 if (!(probe->trigger))
303                         continue;
304
305                 stage = 0;
306                 for (tc = probe->trigger; *tc; tc++) {
307                         ctx->trigger_mask[stage] |= probe_bit;
308                         if (*tc == '1')
309                                 ctx->trigger_value[stage] |= probe_bit;
310                         stage++;
311                         if (stage > NUM_TRIGGER_STAGES)
312                                 return SR_ERR;
313                 }
314         }
315
316         if (stage == -1)
317                 /*
318                  * We didn't configure any triggers, make sure acquisition
319                  * doesn't wait for any.
320                  */
321                 ctx->trigger_stage = TRIGGER_FIRED;
322         else
323                 ctx->trigger_stage = 0;
324
325         return SR_OK;
326 }
327
328 static struct context *fx2lafw_dev_new(void)
329 {
330         struct context *ctx;
331
332         if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
333                 sr_err("fx2lafw: %s: ctx malloc failed.", __func__);
334                 return NULL;
335         }
336
337         ctx->trigger_stage = TRIGGER_FIRED;
338
339         return ctx;
340 }
341
342 /*
343  * API callbacks
344  */
345
346 static int hw_init(const char *devinfo)
347 {
348         struct sr_dev_inst *sdi;
349         struct libusb_device_descriptor des;
350         const struct fx2lafw_profile *prof;
351         struct context *ctx;
352         libusb_device **devlist;
353         int ret;
354         int devcnt = 0;
355         int i, j;
356
357         /* Avoid compiler warnings. */
358         (void)devinfo;
359
360         if (libusb_init(&usb_context) != 0) {
361                 sr_warn("fx2lafw: Failed to initialize libusb.");
362                 return 0;
363         }
364
365         /* Find all fx2lafw compatible devices and upload firware to them. */
366         libusb_get_device_list(usb_context, &devlist);
367         for (i = 0; devlist[i]; i++) {
368
369                 if ((ret = libusb_get_device_descriptor(
370                      devlist[i], &des)) != 0) {
371                         sr_warn("fx2lafw: Failed to get device descriptor: %d.", ret);
372                         continue;
373                 }
374
375                 prof = NULL;
376                 for (j = 0; supported_fx2[j].vid; j++) {
377                         if (des.idVendor == supported_fx2[j].vid &&
378                                 des.idProduct == supported_fx2[j].pid) {
379                                 prof = &supported_fx2[j];
380                         }
381                 }
382
383                 /* Skip if the device was not found */
384                 if (!prof)
385                         continue;
386
387                 sdi = sr_dev_inst_new(devcnt, SR_ST_INITIALIZING,
388                         prof->vendor, prof->model, prof->model_version);
389                 if (!sdi)
390                         return 0;
391
392                 ctx = fx2lafw_dev_new();
393                 ctx->profile = prof;
394                 sdi->priv = ctx;
395                 dev_insts = g_slist_append(dev_insts, sdi);
396
397                 if (check_conf_profile(devlist[i])) {
398                         /* Already has the firmware, so fix the new address. */
399                         sr_dbg("fx2lafw: Found an fx2lafw device.");
400                         sdi->status = SR_ST_INACTIVE;
401                         ctx->usb = sr_usb_dev_inst_new
402                             (libusb_get_bus_number(devlist[i]),
403                              libusb_get_device_address(devlist[i]), NULL);
404                 } else {
405                         if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
406                                 prof->firmware) == SR_OK)
407                                 /* Remember when the firmware on this device was updated */
408                                 g_get_current_time(&ctx->fw_updated);
409                         else
410                                 sr_err("fx2lafw: Firmware upload failed for "
411                                        "device %d.", devcnt);
412                         ctx->usb = sr_usb_dev_inst_new
413                                 (libusb_get_bus_number(devlist[i]), 0xff, NULL);
414                 }
415
416                 devcnt++;
417         }
418         libusb_free_device_list(devlist, 1);
419
420         return devcnt;
421 }
422
423 static int hw_dev_open(int dev_index)
424 {
425         GTimeVal cur_time;
426         struct sr_dev_inst *sdi;
427         struct context *ctx;
428         int timediff, ret;
429
430         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
431                 return SR_ERR;
432         ctx = sdi->priv;
433
434         /*
435          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY ms
436          * for the FX2 to renumerate.
437          */
438         ret = 0;
439         if (GTV_TO_MSEC(ctx->fw_updated) > 0) {
440                 sr_info("fx2lafw: Waiting for device to reset.");
441                 /* takes at least 300ms for the FX2 to be gone from the USB bus */
442                 g_usleep(300 * 1000);
443                 timediff = 0;
444                 while (timediff < MAX_RENUM_DELAY) {
445                         if ((ret = fx2lafw_dev_open(dev_index)) == SR_OK)
446                                 break;
447                         g_usleep(100 * 1000);
448                         g_get_current_time(&cur_time);
449                         timediff = GTV_TO_MSEC(cur_time) - GTV_TO_MSEC(ctx->fw_updated);
450                 }
451                 sr_info("fx2lafw: Device came back after %d ms.", timediff);
452         } else {
453                 ret = fx2lafw_dev_open(dev_index);
454         }
455
456         if (ret != SR_OK) {
457                 sr_err("fx2lafw: Unable to open device.");
458                 return SR_ERR;
459         }
460         ctx = sdi->priv;
461
462         ret = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
463         if (ret != 0) {
464                 sr_err("fx2lafw: Unable to claim interface: %d.", ret);
465                 return SR_ERR;
466         }
467
468         if (ctx->cur_samplerate == 0) {
469                 /* Samplerate hasn't been set; default to the slowest one. */
470                 if (hw_dev_config_set(dev_index, SR_HWCAP_SAMPLERATE,
471                     &supported_samplerates[0]) == SR_ERR)
472                         return SR_ERR;
473         }
474
475         return SR_OK;
476 }
477
478 static int hw_dev_close(int dev_index)
479 {
480         struct sr_dev_inst *sdi;
481
482         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index))) {
483                 sr_err("fx2lafw: %s: sdi was NULL.", __func__);
484                 return SR_ERR_BUG;
485         }
486
487         /* TODO */
488         close_dev(sdi);
489
490         return SR_OK;
491 }
492
493 static int hw_cleanup(void)
494 {
495         GSList *l;
496         struct sr_dev_inst *sdi;
497         struct context *ctx;
498         int ret = SR_OK;
499
500         for (l = dev_insts; l; l = l->next) {
501                 if (!(sdi = l->data)) {
502                         /* Log error, but continue cleaning up the rest. */
503                         sr_err("fx2lafw: %s: sdi was NULL, continuing.",
504                                __func__);
505                         ret = SR_ERR_BUG;
506                         continue;
507                 }
508                 if (!(ctx = sdi->priv)) {
509                         /* Log error, but continue cleaning up the rest. */
510                         sr_err("fx2lafw: %s: sdi->priv was NULL, continuing",
511                                __func__);
512                         ret = SR_ERR_BUG;
513                         continue;
514                 }
515                 close_dev(sdi);
516                 sdi = l->data;
517                 sr_dev_inst_free(sdi);
518         }
519
520         g_slist_free(dev_insts);
521         dev_insts = NULL;
522
523         if (usb_context)
524                 libusb_exit(usb_context);
525         usb_context = NULL;
526
527         return ret;
528 }
529
530 static void *hw_dev_info_get(int dev_index, int dev_info_id)
531 {
532         struct sr_dev_inst *sdi;
533         struct context *ctx;
534
535         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
536                 return NULL;
537         ctx = sdi->priv;
538
539         switch (dev_info_id) {
540         case SR_DI_INST:
541                 return sdi;
542         case SR_DI_NUM_PROBES:
543                 return GINT_TO_POINTER(ctx->profile->num_probes);
544         case SR_DI_PROBE_NAMES:
545                 return probe_names;
546         case SR_DI_SAMPLERATES:
547                 return &samplerates;
548         case SR_DI_TRIGGER_TYPES:
549                 return TRIGGER_TYPES;
550         case SR_DI_CUR_SAMPLERATE:
551                 return &ctx->cur_samplerate;
552         }
553
554         return NULL;
555 }
556
557 static int hw_dev_status_get(int dev_index)
558 {
559         const struct sr_dev_inst *const sdi =
560                 sr_dev_inst_get(dev_insts, dev_index);
561
562         if (!sdi)
563                 return SR_ST_NOT_FOUND;
564
565         return sdi->status;
566 }
567
568 static int *hw_hwcap_get_all(void)
569 {
570         return hwcaps;
571 }
572
573 static int hw_dev_config_set(int dev_index, int hwcap, void *value)
574 {
575         struct sr_dev_inst *sdi;
576         struct context *ctx;
577         int ret;
578
579         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
580                 return SR_ERR;
581         ctx = sdi->priv;
582
583         if (hwcap == SR_HWCAP_SAMPLERATE) {
584                 ctx->cur_samplerate = *(uint64_t *)value;
585                 ret = SR_OK;
586         } else if (hwcap == SR_HWCAP_PROBECONFIG) {
587                 ret = configure_probes(ctx, (GSList *) value);
588         } else if (hwcap == SR_HWCAP_LIMIT_SAMPLES) {
589                 ctx->limit_samples = *(uint64_t *)value;
590                 ret = SR_OK;
591         } else {
592                 ret = SR_ERR;
593         }
594
595         return ret;
596 }
597
598 static int receive_data(int fd, int revents, void *cb_data)
599 {
600         struct timeval tv;
601
602         /* Avoid compiler warnings. */
603         (void)fd;
604         (void)revents;
605         (void)cb_data;
606
607         tv.tv_sec = tv.tv_usec = 0;
608         libusb_handle_events_timeout(usb_context, &tv);
609
610         return TRUE;
611 }
612
613 static void abort_acquisition(struct context *ctx)
614 {
615         ctx->num_samples = -1;
616 }
617
618 static void finish_acquisition(struct context *ctx)
619 {
620         struct sr_datafeed_packet packet;
621         int i;
622
623         /* Terminate session */
624         packet.type = SR_DF_END;
625         sr_session_send(ctx->session_dev_id, &packet);
626
627         /* Remove fds from polling */
628         const struct libusb_pollfd **const lupfd =
629                 libusb_get_pollfds(usb_context);
630         for (i = 0; lupfd[i]; i++)
631                 sr_source_remove(lupfd[i]->fd);
632         free(lupfd); /* NOT g_free()! */
633 }
634
635 static void receive_transfer(struct libusb_transfer *transfer)
636 {
637         /* TODO: These statics have to move to the ctx struct. */
638         static int empty_transfer_count = 0;
639         struct sr_datafeed_packet packet;
640         struct sr_datafeed_logic logic;
641         struct context *ctx = transfer->user_data;
642         int cur_buflen, trigger_offset, i;
643         unsigned char *cur_buf, *new_buf;
644
645         /*
646          * If acquisition has already ended, just free any queued up
647          * transfer that come in.
648          */
649         if (ctx->num_samples == -1) {
650                 if (transfer)
651                         libusb_free_transfer(transfer);
652
653                 ctx->submitted_transfers--;
654                 if (ctx->submitted_transfers == 0)
655                         finish_acquisition(ctx);
656
657                 return;
658         }
659
660         sr_info("fx2lafw: receive_transfer(): status %d received %d bytes.",
661                 transfer->status, transfer->actual_length);
662
663         /* Save incoming transfer before reusing the transfer struct. */
664         cur_buf = transfer->buffer;
665         cur_buflen = transfer->actual_length;
666
667         /* Fire off a new request. */
668         if (!(new_buf = g_try_malloc(4096))) {
669                 sr_err("fx2lafw: %s: new_buf malloc failed.", __func__);
670                 return; /* TODO: SR_ERR_MALLOC */
671         }
672
673         transfer->buffer = new_buf;
674         transfer->length = 4096;
675         if (libusb_submit_transfer(transfer) != 0) {
676                 /* TODO: Stop session? */
677                 /* TODO: Better error message. */
678                 sr_err("fx2lafw: %s: libusb_submit_transfer error.", __func__);
679         }
680
681         if (cur_buflen == 0) {
682                 empty_transfer_count++;
683                 if (empty_transfer_count > MAX_EMPTY_TRANSFERS) {
684                         /*
685                          * The FX2 gave up. End the acquisition, the frontend
686                          * will work out that the samplecount is short.
687                          */
688                         abort_acquisition(ctx);
689                 }
690                 return;
691         } else {
692                 empty_transfer_count = 0;
693         }
694
695         trigger_offset = 0;
696         if (ctx->trigger_stage >= 0) {
697                 for (i = 0; i < cur_buflen; i++) {
698
699                         if ((cur_buf[i] & ctx->trigger_mask[ctx->trigger_stage]) == ctx->trigger_value[ctx->trigger_stage]) {
700                                 /* Match on this trigger stage. */
701                                 ctx->trigger_buffer[ctx->trigger_stage] = cur_buf[i];
702                                 ctx->trigger_stage++;
703
704                                 if (ctx->trigger_stage == NUM_TRIGGER_STAGES || ctx->trigger_mask[ctx->trigger_stage] == 0) {
705                                         /* Match on all trigger stages, we're done. */
706                                         trigger_offset = i + 1;
707
708                                         /*
709                                          * TODO: Send pre-trigger buffer to session bus.
710                                          * Tell the frontend we hit the trigger here.
711                                          */
712                                         packet.type = SR_DF_TRIGGER;
713                                         packet.payload = NULL;
714                                         sr_session_send(ctx->session_dev_id, &packet);
715
716                                         /*
717                                          * Send the samples that triggered it, since we're
718                                          * skipping past them.
719                                          */
720                                         packet.type = SR_DF_LOGIC;
721                                         packet.payload = &logic;
722                                         logic.length = ctx->trigger_stage;
723                                         logic.unitsize = 1;
724                                         logic.data = ctx->trigger_buffer;
725                                         sr_session_send(ctx->session_dev_id, &packet);
726
727                                         ctx->trigger_stage = TRIGGER_FIRED;
728                                         break;
729                                 }
730                                 return;
731                         }
732
733                         /*
734                          * We had a match before, but not in the next sample. However, we may
735                          * have a match on this stage in the next bit -- trigger on 0001 will
736                          * fail on seeing 00001, so we need to go back to stage 0 -- but at
737                          * the next sample from the one that matched originally, which the
738                          * counter increment at the end of the loop takes care of.
739                          */
740                         if (ctx->trigger_stage > 0) {
741                                 i -= ctx->trigger_stage;
742                                 if (i < -1)
743                                         i = -1; /* Oops, went back past this buffer. */
744                                 /* Reset trigger stage. */
745                                 ctx->trigger_stage = 0;
746                         }
747                 }
748         }
749
750         if (ctx->trigger_stage == TRIGGER_FIRED) {
751                 /* Send the incoming transfer to the session bus. */
752                 packet.type = SR_DF_LOGIC;
753                 packet.payload = &logic;
754                 logic.length = cur_buflen - trigger_offset;
755                 logic.unitsize = 1;
756                 logic.data = cur_buf + trigger_offset;
757                 sr_session_send(ctx->session_dev_id, &packet);
758                 g_free(cur_buf);
759
760                 ctx->num_samples += cur_buflen;
761                 if (ctx->limit_samples &&
762                         (unsigned int)ctx->num_samples > ctx->limit_samples) {
763                         abort_acquisition(ctx);
764                 }
765         } else {
766                 /*
767                  * TODO: Buffer pre-trigger data in capture
768                  * ratio-sized buffer.
769                  */
770         }
771 }
772
773 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
774 {
775         struct sr_dev_inst *sdi;
776         struct sr_datafeed_packet *packet;
777         struct sr_datafeed_header *header;
778         struct context *ctx;
779         struct libusb_transfer *transfer;
780         const struct libusb_pollfd **lupfd;
781         int ret, size, i;
782         unsigned char *buf;
783
784         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
785                 return SR_ERR;
786         ctx = sdi->priv;
787         ctx->session_dev_id = cb_data;
788         ctx->num_samples = 0;
789
790         if (!(packet = g_try_malloc(sizeof(struct sr_datafeed_packet)))) {
791                 sr_err("fx2lafw: %s: packet malloc failed.", __func__);
792                 return SR_ERR_MALLOC;
793         }
794
795         if (!(header = g_try_malloc(sizeof(struct sr_datafeed_header)))) {
796                 sr_err("fx2lafw: %s: header malloc failed.", __func__);
797                 return SR_ERR_MALLOC;
798         }
799
800         /* Start with 2K transfer, subsequently increased to 4K. */
801         size = 2048;
802         for (i = 0; i < NUM_SIMUL_TRANSFERS; i++) {
803                 if (!(buf = g_try_malloc(size))) {
804                         sr_err("fx2lafw: %s: buf malloc failed.", __func__);
805                         return SR_ERR_MALLOC;
806                 }
807                 transfer = libusb_alloc_transfer(0);
808                 libusb_fill_bulk_transfer(transfer, ctx->usb->devhdl,
809                                 2 | LIBUSB_ENDPOINT_IN, buf, size,
810                                 receive_transfer, ctx, 40);
811                 if (libusb_submit_transfer(transfer) != 0) {
812                         /* TODO: Free them all. */
813                         libusb_free_transfer(transfer);
814                         g_free(buf);
815                         return SR_ERR;
816                 }
817
818                 ctx->submitted_transfers++;
819                 size = 4096;
820         }
821
822         lupfd = libusb_get_pollfds(usb_context);
823         for (i = 0; lupfd[i]; i++)
824                 sr_source_add(lupfd[i]->fd, lupfd[i]->events,
825                               40, receive_data, NULL);
826         free(lupfd); /* NOT g_free()! */
827
828         packet->type = SR_DF_HEADER;
829         packet->payload = header;
830         header->feed_version = 1;
831         gettimeofday(&header->starttime, NULL);
832         header->samplerate = ctx->cur_samplerate;
833         header->num_logic_probes = ctx->profile->num_probes;
834         sr_session_send(cb_data, packet);
835         g_free(header);
836         g_free(packet);
837
838         if ((ret = command_start_acquisition (ctx->usb->devhdl,
839                 ctx->cur_samplerate)) != SR_OK) {
840                 return ret;
841         }
842
843         return SR_OK;
844 }
845
846 /* TODO: This stops acquisition on ALL devices, ignoring dev_index. */
847 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
848 {
849         struct sr_dev_inst *sdi;
850
851         /* Avoid compiler warnings. */
852         (void)cb_data;
853
854         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
855                 return SR_ERR;
856  
857         abort_acquisition(sdi->priv);
858
859         return SR_OK;
860 }
861
862 SR_PRIV struct sr_dev_driver fx2lafw_driver_info = {
863         .name = "fx2lafw",
864         .longname = "fx2lafw (generic driver for FX2 based LAs)",
865         .api_version = 1,
866         .init = hw_init,
867         .cleanup = hw_cleanup,
868         .dev_open = hw_dev_open,
869         .dev_close = hw_dev_close,
870         .dev_info_get = hw_dev_info_get,
871         .dev_status_get = hw_dev_status_get,
872         .hwcap_get_all = hw_hwcap_get_all,
873         .dev_config_set = hw_dev_config_set,
874         .dev_acquisition_start = hw_dev_acquisition_start,
875         .dev_acquisition_stop = hw_dev_acquisition_stop,
876 };