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