]> sigrok.org Git - libsigrok.git/blob - src/hardware/fx2lafw/api.c
fx2lafw: Call dslogic_get_number_of_transfers into fx2lafw_get_number_of_transfers
[libsigrok.git] / src / hardware / fx2lafw / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 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 <config.h>
22 #include "protocol.h"
23 #include "dslogic.h"
24 #include <math.h>
25
26 static const struct fx2lafw_profile supported_fx2[] = {
27         /*
28          * CWAV USBee AX
29          * EE Electronics ESLA201A
30          * ARMFLY AX-Pro
31          */
32         { 0x08a9, 0x0014, "CWAV", "USBee AX", NULL,
33                 "fx2lafw-cwav-usbeeax.fw",
34                 DEV_CAPS_AX_ANALOG, NULL, NULL},
35         /*
36          * CWAV USBee DX
37          * XZL-Studio DX
38          */
39         { 0x08a9, 0x0015, "CWAV", "USBee DX", NULL,
40                 "fx2lafw-cwav-usbeedx.fw",
41                 DEV_CAPS_16BIT, NULL, NULL },
42
43         /*
44          * CWAV USBee SX
45          */
46         { 0x08a9, 0x0009, "CWAV", "USBee SX", NULL,
47                 "fx2lafw-cwav-usbeesx.fw",
48                 0, NULL, NULL},
49
50         /*
51          * CWAV USBee ZX
52          */
53         { 0x08a9, 0x0005, "CWAV", "USBee ZX", NULL,
54                 "fx2lafw-cwav-usbeezx.fw",
55                 0, NULL, NULL},
56
57         /* DreamSourceLab DSLogic (before FW upload) */
58         { 0x2a0e, 0x0001, "DreamSourceLab", "DSLogic", NULL,
59                 "dreamsourcelab-dslogic-fx2.fw",
60                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, NULL, NULL},
61         /* DreamSourceLab DSLogic (after FW upload) */
62         { 0x2a0e, 0x0001, "DreamSourceLab", "DSLogic", NULL,
63                 "dreamsourcelab-dslogic-fx2.fw",
64                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, "DreamSourceLab", "DSLogic"},
65
66         /* DreamSourceLab DSCope (before FW upload) */
67         { 0x2a0e, 0x0002, "DreamSourceLab", "DSCope", NULL,
68                 "dreamsourcelab-dscope-fx2.fw",
69                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, NULL, NULL},
70         /* DreamSourceLab DSCope (after FW upload) */
71         { 0x2a0e, 0x0002, "DreamSourceLab", "DSCope", NULL,
72                 "dreamsourcelab-dscope-fx2.fw",
73                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, "DreamSourceLab", "DSCope"},
74
75         /* DreamSourceLab DSLogic Pro (before FW upload) */
76         { 0x2a0e, 0x0003, "DreamSourceLab", "DSLogic Pro", NULL,
77                 "dreamsourcelab-dslogic-pro-fx2.fw",
78                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, NULL, NULL},
79         /* DreamSourceLab DSLogic Pro (after FW upload) */
80         { 0x2a0e, 0x0003, "DreamSourceLab", "DSLogic Pro", NULL,
81                 "dreamsourcelab-dslogic-pro-fx2.fw",
82                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, "DreamSourceLab", "DSLogic"},
83
84         /* DreamSourceLab DSLogic Plus (before FW upload) */
85         { 0x2a0e, 0x0020, "DreamSourceLab", "DSLogic Plus", NULL,
86                 "dreamsourcelab-dslogic-plus-fx2.fw",
87                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, NULL, NULL},
88         /* DreamSourceLab DSLogic Plus (after FW upload) */
89         { 0x2a0e, 0x0020, "DreamSourceLab", "DSLogic Plus", NULL,
90                 "dreamsourcelab-dslogic-plus-fx2.fw",
91                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, "DreamSourceLab", "DSLogic"},
92
93         /* DreamSourceLab DSLogic Basic (before FW upload) */
94         { 0x2a0e, 0x0021, "DreamSourceLab", "DSLogic Basic", NULL,
95                 "dreamsourcelab-dslogic-basic-fx2.fw",
96                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, NULL, NULL},
97         /* DreamSourceLab DSLogic Basic (after FW upload) */
98         { 0x2a0e, 0x0021, "DreamSourceLab", "DSLogic Basic", NULL,
99                 "dreamsourcelab-dslogic-basic-fx2.fw",
100                 DEV_CAPS_16BIT | DEV_CAPS_DSLOGIC_FW, "DreamSourceLab", "DSLogic"},
101
102         /*
103          * Saleae Logic
104          * EE Electronics ESLA100
105          * Robomotic MiniLogic
106          * Robomotic BugLogic 3
107          */
108         { 0x0925, 0x3881, "Saleae", "Logic", NULL,
109                 "fx2lafw-saleae-logic.fw",
110                 0, NULL, NULL},
111
112         /*
113          * Default Cypress FX2 without EEPROM, e.g.:
114          * Lcsoft Mini Board
115          * Braintechnology USB Interface V2.x
116          */
117         { 0x04B4, 0x8613, "Cypress", "FX2", NULL,
118                 "fx2lafw-cypress-fx2.fw",
119                 DEV_CAPS_16BIT, NULL, NULL },
120
121         /*
122          * Braintechnology USB-LPS
123          */
124         { 0x16d0, 0x0498, "Braintechnology", "USB-LPS", NULL,
125                 "fx2lafw-braintechnology-usb-lps.fw",
126                 DEV_CAPS_16BIT, NULL, NULL },
127
128         /*
129          * sigrok FX2 based 8-channel logic analyzer
130          */
131         { 0x1d50, 0x608c, "sigrok", "FX2 LA (8ch)", NULL,
132                 "fx2lafw-sigrok-fx2-8ch.fw",
133                 0, NULL, NULL},
134
135         /*
136          * sigrok FX2 based 16-channel logic analyzer
137          */
138         { 0x1d50, 0x608d, "sigrok", "FX2 LA (16ch)", NULL,
139                 "fx2lafw-sigrok-fx2-16ch.fw",
140                 DEV_CAPS_16BIT, NULL, NULL },
141
142         ALL_ZERO
143 };
144
145 static const uint32_t drvopts[] = {
146         SR_CONF_LOGIC_ANALYZER,
147 };
148
149 static const uint32_t scanopts[] = {
150         SR_CONF_CONN,
151 };
152
153 static const uint32_t devopts[] = {
154         SR_CONF_CONTINUOUS,
155         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
156         SR_CONF_CONN | SR_CONF_GET,
157         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
158         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
159         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
160 };
161
162 static const uint32_t dslogic_devopts[] = {
163         SR_CONF_CONTINUOUS | SR_CONF_SET | SR_CONF_GET,
164         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
165         SR_CONF_VOLTAGE_THRESHOLD | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
166         SR_CONF_CONN | SR_CONF_GET,
167         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
168         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
169         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
170         SR_CONF_EXTERNAL_CLOCK | SR_CONF_GET | SR_CONF_SET,
171         SR_CONF_CLOCK_EDGE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
172 };
173
174 static const int32_t soft_trigger_matches[] = {
175         SR_TRIGGER_ZERO,
176         SR_TRIGGER_ONE,
177         SR_TRIGGER_RISING,
178         SR_TRIGGER_FALLING,
179         SR_TRIGGER_EDGE,
180 };
181
182 /* Names assigned to available edge slope choices. */
183 static const char *const signal_edge_names[] = {
184         [DS_EDGE_RISING] = "rising",
185         [DS_EDGE_FALLING] = "falling",
186 };
187
188 static const struct {
189         int range;
190         gdouble low;
191         gdouble high;
192 } volt_thresholds[] = {
193         { DS_VOLTAGE_RANGE_18_33_V, 0.7, 1.4 },
194         { DS_VOLTAGE_RANGE_5_V, 1.4, 3.6 },
195 };
196
197 static const uint64_t samplerates[] = {
198         SR_KHZ(20),
199         SR_KHZ(25),
200         SR_KHZ(50),
201         SR_KHZ(100),
202         SR_KHZ(200),
203         SR_KHZ(250),
204         SR_KHZ(500),
205         SR_MHZ(1),
206         SR_MHZ(2),
207         SR_MHZ(3),
208         SR_MHZ(4),
209         SR_MHZ(6),
210         SR_MHZ(8),
211         SR_MHZ(12),
212         SR_MHZ(16),
213         SR_MHZ(24),
214 };
215
216 static const uint64_t dslogic_samplerates[] = {
217         SR_KHZ(10),
218         SR_KHZ(20),
219         SR_KHZ(50),
220         SR_KHZ(100),
221         SR_KHZ(200),
222         SR_KHZ(500),
223         SR_MHZ(1),
224         SR_MHZ(2),
225         SR_MHZ(5),
226         SR_MHZ(10),
227         SR_MHZ(20),
228         SR_MHZ(25),
229         SR_MHZ(50),
230         SR_MHZ(100),
231         SR_MHZ(200),
232         SR_MHZ(400),
233 };
234
235 static gboolean is_plausible(const struct libusb_device_descriptor *des)
236 {
237         int i;
238
239         for (i = 0; supported_fx2[i].vid; i++) {
240                 if (des->idVendor != supported_fx2[i].vid)
241                         continue;
242                 if (des->idProduct == supported_fx2[i].pid)
243                         return TRUE;
244         }
245
246         return FALSE;
247 }
248
249 static GSList *scan(struct sr_dev_driver *di, GSList *options)
250 {
251         struct drv_context *drvc;
252         struct dev_context *devc;
253         struct sr_dev_inst *sdi;
254         struct sr_usb_dev_inst *usb;
255         struct sr_channel *ch;
256         struct sr_channel_group *cg;
257         struct sr_config *src;
258         const struct fx2lafw_profile *prof;
259         GSList *l, *devices, *conn_devices;
260         gboolean has_firmware;
261         struct libusb_device_descriptor des;
262         libusb_device **devlist;
263         struct libusb_device_handle *hdl;
264         int ret, i, j;
265         int num_logic_channels = 0, num_analog_channels = 0;
266         const char *conn;
267         char manufacturer[64], product[64], serial_num[64], connection_id[64];
268         char channel_name[16];
269
270         drvc = di->context;
271
272         conn = NULL;
273         for (l = options; l; l = l->next) {
274                 src = l->data;
275                 switch (src->key) {
276                 case SR_CONF_CONN:
277                         conn = g_variant_get_string(src->data, NULL);
278                         break;
279                 }
280         }
281         if (conn)
282                 conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
283         else
284                 conn_devices = NULL;
285
286         /* Find all fx2lafw compatible devices and upload firmware to them. */
287         devices = NULL;
288         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
289         for (i = 0; devlist[i]; i++) {
290                 if (conn) {
291                         usb = NULL;
292                         for (l = conn_devices; l; l = l->next) {
293                                 usb = l->data;
294                                 if (usb->bus == libusb_get_bus_number(devlist[i])
295                                         && usb->address == libusb_get_device_address(devlist[i]))
296                                         break;
297                         }
298                         if (!l)
299                                 /* This device matched none of the ones that
300                                  * matched the conn specification. */
301                                 continue;
302                 }
303
304                 libusb_get_device_descriptor( devlist[i], &des);
305
306                 if (!is_plausible(&des))
307                         continue;
308
309                 if ((ret = libusb_open(devlist[i], &hdl)) < 0) {
310                         sr_warn("Failed to open potential device with "
311                                 "VID:PID %04x:%04x: %s.", des.idVendor,
312                                 des.idProduct, libusb_error_name(ret));
313                         continue;
314                 }
315
316                 if (des.iManufacturer == 0) {
317                         manufacturer[0] = '\0';
318                 } else if ((ret = libusb_get_string_descriptor_ascii(hdl,
319                                 des.iManufacturer, (unsigned char *) manufacturer,
320                                 sizeof(manufacturer))) < 0) {
321                         sr_warn("Failed to get manufacturer string descriptor: %s.",
322                                 libusb_error_name(ret));
323                         continue;
324                 }
325
326                 if (des.iProduct == 0) {
327                         product[0] = '\0';
328                 } else if ((ret = libusb_get_string_descriptor_ascii(hdl,
329                                 des.iProduct, (unsigned char *) product,
330                                 sizeof(product))) < 0) {
331                         sr_warn("Failed to get product string descriptor: %s.",
332                                 libusb_error_name(ret));
333                         continue;
334                 }
335
336                 if (des.iSerialNumber == 0) {
337                         serial_num[0] = '\0';
338                 } else if ((ret = libusb_get_string_descriptor_ascii(hdl,
339                                 des.iSerialNumber, (unsigned char *) serial_num,
340                                 sizeof(serial_num))) < 0) {
341                         sr_warn("Failed to get serial number string descriptor: %s.",
342                                 libusb_error_name(ret));
343                         continue;
344                 }
345
346                 usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
347
348                 libusb_close(hdl);
349
350                 prof = NULL;
351                 for (j = 0; supported_fx2[j].vid; j++) {
352                         if (des.idVendor == supported_fx2[j].vid &&
353                                         des.idProduct == supported_fx2[j].pid &&
354                                         (!supported_fx2[j].usb_manufacturer ||
355                                          !strcmp(manufacturer, supported_fx2[j].usb_manufacturer)) &&
356                                         (!supported_fx2[j].usb_product ||
357                                          !strcmp(product, supported_fx2[j].usb_product))) {
358                                 prof = &supported_fx2[j];
359                                 break;
360                         }
361                 }
362
363                 /* Skip if the device was not found. */
364                 if (!prof)
365                         continue;
366
367                 sdi = g_malloc0(sizeof(struct sr_dev_inst));
368                 sdi->status = SR_ST_INITIALIZING;
369                 sdi->vendor = g_strdup(prof->vendor);
370                 sdi->model = g_strdup(prof->model);
371                 sdi->version = g_strdup(prof->model_version);
372                 sdi->serial_num = g_strdup(serial_num);
373                 sdi->connection_id = g_strdup(connection_id);
374
375                 /* Fill in channellist according to this device's profile. */
376                 num_logic_channels = prof->dev_caps & DEV_CAPS_16BIT ? 16 : 8;
377                 num_analog_channels = prof->dev_caps & DEV_CAPS_AX_ANALOG ? 1 : 0;
378
379                 /* Logic channels, all in one channel group. */
380                 cg = g_malloc0(sizeof(struct sr_channel_group));
381                 cg->name = g_strdup("Logic");
382                 for (j = 0; j < num_logic_channels; j++) {
383                         sprintf(channel_name, "D%d", j);
384                         ch = sr_channel_new(sdi, j, SR_CHANNEL_LOGIC,
385                                                 TRUE, channel_name);
386                         cg->channels = g_slist_append(cg->channels, ch);
387                 }
388                 sdi->channel_groups = g_slist_append(NULL, cg);
389
390                 for (j = 0; j < num_analog_channels; j++) {
391                         snprintf(channel_name, 16, "A%d", j);
392                         ch = sr_channel_new(sdi, j + num_logic_channels,
393                                         SR_CHANNEL_ANALOG, TRUE, channel_name);
394
395                         /* Every analog channel gets its own channel group. */
396                         cg = g_malloc0(sizeof(struct sr_channel_group));
397                         cg->name = g_strdup(channel_name);
398                         cg->channels = g_slist_append(NULL, ch);
399                         sdi->channel_groups = g_slist_append(sdi->channel_groups, cg);
400                 }
401
402                 devc = fx2lafw_dev_new();
403                 devc->profile = prof;
404                 sdi->priv = devc;
405                 devices = g_slist_append(devices, sdi);
406
407                 if (!strcmp(prof->model, "DSLogic")
408                                 || !strcmp(prof->model, "DSLogic Pro")
409                                 || !strcmp(prof->model, "DSLogic Plus")
410                                 || !strcmp(prof->model, "DSLogic Basic")
411                                 || !strcmp(prof->model, "DSCope")) {
412                         devc->dslogic = TRUE;
413                         devc->samplerates = dslogic_samplerates;
414                         devc->num_samplerates = ARRAY_SIZE(dslogic_samplerates);
415                         has_firmware = match_manuf_prod(devlist[i], "DreamSourceLab", "DSLogic")
416                                         || match_manuf_prod(devlist[i], "DreamSourceLab", "DSCope");
417                 } else {
418                         devc->dslogic = FALSE;
419                         devc->samplerates = samplerates;
420                         devc->num_samplerates = ARRAY_SIZE(samplerates);
421                         has_firmware = match_manuf_prod(devlist[i],
422                                         "sigrok", "fx2lafw");
423                 }
424
425                 if (has_firmware) {
426                         /* Already has the firmware, so fix the new address. */
427                         sr_dbg("Found an fx2lafw device.");
428                         sdi->status = SR_ST_INACTIVE;
429                         sdi->inst_type = SR_INST_USB;
430                         sdi->conn = sr_usb_dev_inst_new(libusb_get_bus_number(devlist[i]),
431                                         libusb_get_device_address(devlist[i]), NULL);
432                 } else {
433                         if (ezusb_upload_firmware(drvc->sr_ctx, devlist[i],
434                                         USB_CONFIGURATION, prof->firmware) == SR_OK)
435                                 /* Store when this device's FW was updated. */
436                                 devc->fw_updated = g_get_monotonic_time();
437                         else
438                                 sr_err("Firmware upload failed for "
439                                        "device %d.%d (logical).",
440                                        libusb_get_bus_number(devlist[i]),
441                                        libusb_get_device_address(devlist[i]));
442                         sdi->inst_type = SR_INST_USB;
443                         sdi->conn = sr_usb_dev_inst_new(libusb_get_bus_number(devlist[i]),
444                                         0xff, NULL);
445                 }
446         }
447         libusb_free_device_list(devlist, 1);
448         g_slist_free_full(conn_devices, (GDestroyNotify)sr_usb_dev_inst_free);
449
450         return std_scan_complete(di, devices);
451 }
452
453 static void clear_dev_context(void *priv)
454 {
455         struct dev_context *devc;
456
457         devc = priv;
458         g_slist_free(devc->enabled_analog_channels);
459         g_free(devc);
460 }
461
462 static int dev_clear(const struct sr_dev_driver *di)
463 {
464         return std_dev_clear(di, clear_dev_context);
465 }
466
467 static int dev_open(struct sr_dev_inst *sdi)
468 {
469         struct sr_dev_driver *di = sdi->driver;
470         struct sr_usb_dev_inst *usb;
471         struct dev_context *devc;
472         const char *fpga_firmware = NULL;
473         int ret;
474         int64_t timediff_us, timediff_ms;
475
476         devc = sdi->priv;
477         usb = sdi->conn;
478
479         /*
480          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
481          * milliseconds for the FX2 to renumerate.
482          */
483         ret = SR_ERR;
484         if (devc->fw_updated > 0) {
485                 sr_info("Waiting for device to reset.");
486                 /* Takes >= 300ms for the FX2 to be gone from the USB bus. */
487                 g_usleep(300 * 1000);
488                 timediff_ms = 0;
489                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
490                         if ((ret = fx2lafw_dev_open(sdi, di)) == SR_OK)
491                                 break;
492                         g_usleep(100 * 1000);
493
494                         timediff_us = g_get_monotonic_time() - devc->fw_updated;
495                         timediff_ms = timediff_us / 1000;
496                         sr_spew("Waited %" PRIi64 "ms.", timediff_ms);
497                 }
498                 if (ret != SR_OK) {
499                         sr_err("Device failed to renumerate.");
500                         return SR_ERR;
501                 }
502                 sr_info("Device came back after %" PRIi64 "ms.", timediff_ms);
503         } else {
504                 sr_info("Firmware upload was not needed.");
505                 ret = fx2lafw_dev_open(sdi, di);
506         }
507
508         if (ret != SR_OK) {
509                 sr_err("Unable to open device.");
510                 return SR_ERR;
511         }
512
513         ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
514         if (ret != 0) {
515                 switch (ret) {
516                 case LIBUSB_ERROR_BUSY:
517                         sr_err("Unable to claim USB interface. Another "
518                                "program or driver has already claimed it.");
519                         break;
520                 case LIBUSB_ERROR_NO_DEVICE:
521                         sr_err("Device has been disconnected.");
522                         break;
523                 default:
524                         sr_err("Unable to claim interface: %s.",
525                                libusb_error_name(ret));
526                         break;
527                 }
528
529                 return SR_ERR;
530         }
531
532         if (devc->dslogic) {
533                 if (!strcmp(devc->profile->model, "DSLogic")) {
534                         if (devc->dslogic_voltage_threshold == DS_VOLTAGE_RANGE_18_33_V)
535                                 fpga_firmware = DSLOGIC_FPGA_FIRMWARE_3V3;
536                         else
537                                 fpga_firmware = DSLOGIC_FPGA_FIRMWARE_5V;
538                 } else if (!strcmp(devc->profile->model, "DSLogic Pro")){
539                         fpga_firmware = DSLOGIC_PRO_FPGA_FIRMWARE;
540                 } else if (!strcmp(devc->profile->model, "DSLogic Plus")){
541                         fpga_firmware = DSLOGIC_PLUS_FPGA_FIRMWARE;
542                 } else if (!strcmp(devc->profile->model, "DSLogic Basic")){
543                         fpga_firmware = DSLOGIC_BASIC_FPGA_FIRMWARE;
544                 } else if (!strcmp(devc->profile->model, "DSCope")) {
545                         fpga_firmware = DSCOPE_FPGA_FIRMWARE;
546                 }
547
548                 if ((ret = dslogic_fpga_firmware_upload(sdi, fpga_firmware)) != SR_OK)
549                         return ret;
550         }
551         if (devc->cur_samplerate == 0) {
552                 /* Samplerate hasn't been set; default to the slowest one. */
553                 devc->cur_samplerate = devc->samplerates[0];
554         }
555
556         return SR_OK;
557 }
558
559 static int dev_close(struct sr_dev_inst *sdi)
560 {
561         struct sr_usb_dev_inst *usb;
562
563         usb = sdi->conn;
564
565         if (!usb->devhdl)
566                 return SR_ERR;
567
568         sr_info("fx2lafw: Closing device on %d.%d (logical) / %s (physical) interface %d.",
569                 usb->bus, usb->address, sdi->connection_id, USB_INTERFACE);
570         libusb_release_interface(usb->devhdl, USB_INTERFACE);
571         libusb_close(usb->devhdl);
572         usb->devhdl = NULL;
573         sdi->status = SR_ST_INACTIVE;
574
575         return SR_OK;
576 }
577
578 static int config_get(uint32_t key, GVariant **data,
579         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
580 {
581         struct dev_context *devc;
582         struct sr_usb_dev_inst *usb;
583         GVariant *range[2];
584         unsigned int i;
585         char str[128];
586
587         (void)cg;
588
589         if (!sdi)
590                 return SR_ERR_ARG;
591
592         devc = sdi->priv;
593
594         switch (key) {
595         case SR_CONF_CONN:
596                 if (!sdi->conn)
597                         return SR_ERR_ARG;
598                 usb = sdi->conn;
599                 if (usb->address == 255)
600                         /* Device still needs to re-enumerate after firmware
601                          * upload, so we don't know its (future) address. */
602                         return SR_ERR;
603                 snprintf(str, 128, "%d.%d", usb->bus, usb->address);
604                 *data = g_variant_new_string(str);
605                 break;
606         case SR_CONF_VOLTAGE_THRESHOLD:
607                 for (i = 0; i < ARRAY_SIZE(volt_thresholds); i++) {
608                         if (volt_thresholds[i].range != devc->dslogic_voltage_threshold)
609                                 continue;
610                         range[0] = g_variant_new_double(volt_thresholds[i].low);
611                         range[1] = g_variant_new_double(volt_thresholds[i].high);
612                         *data = g_variant_new_tuple(range, 2);
613                         break;
614                 }
615                 break;
616         case SR_CONF_LIMIT_SAMPLES:
617                 *data = g_variant_new_uint64(devc->limit_samples);
618                 break;
619         case SR_CONF_SAMPLERATE:
620                 *data = g_variant_new_uint64(devc->cur_samplerate);
621                 break;
622         case SR_CONF_CAPTURE_RATIO:
623                 *data = g_variant_new_uint64(devc->capture_ratio);
624                 break;
625         case SR_CONF_EXTERNAL_CLOCK:
626                 *data = g_variant_new_boolean(devc->dslogic_external_clock);
627                 break;
628         case SR_CONF_CONTINUOUS:
629                 *data = g_variant_new_boolean(devc->dslogic_continuous_mode);
630                 break;
631         case SR_CONF_CLOCK_EDGE:
632                 i = devc->dslogic_clock_edge;
633                 if (i >= ARRAY_SIZE(signal_edge_names))
634                         return SR_ERR_BUG;
635                 *data = g_variant_new_string(signal_edge_names[0]);
636                 break;
637         default:
638                 return SR_ERR_NA;
639         }
640
641         return SR_OK;
642 }
643
644 /*
645  * Helper for mapping a string-typed configuration value to an index
646  * within a table of possible values.
647  */
648 static int lookup_index(GVariant *value, const char *const *table, int len)
649 {
650         const char *entry;
651         int i;
652
653         entry = g_variant_get_string(value, NULL);
654         if (!entry)
655                 return -1;
656
657         /* Linear search is fine for very small tables. */
658         for (i = 0; i < len; i++) {
659                 if (strcmp(entry, table[i]) == 0)
660                         return i;
661         }
662
663         return -1;
664 }
665
666 static int config_set(uint32_t key, GVariant *data,
667         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
668 {
669         struct dev_context *devc;
670         uint64_t arg;
671         int i, ret;
672         gdouble low, high;
673
674         (void)cg;
675
676         if (!sdi)
677                 return SR_ERR_ARG;
678
679         if (sdi->status != SR_ST_ACTIVE)
680                 return SR_ERR;
681
682         devc = sdi->priv;
683
684         ret = SR_OK;
685
686         switch (key) {
687         case SR_CONF_SAMPLERATE:
688                 arg = g_variant_get_uint64(data);
689                 for (i = 0; i < devc->num_samplerates; i++) {
690                         if (devc->samplerates[i] == arg) {
691                                 devc->cur_samplerate = arg;
692                                 break;
693                         }
694                 }
695                 if (i == devc->num_samplerates)
696                         ret = SR_ERR_ARG;
697                 break;
698         case SR_CONF_LIMIT_SAMPLES:
699                 devc->limit_samples = g_variant_get_uint64(data);
700                 break;
701         case SR_CONF_CAPTURE_RATIO:
702                 devc->capture_ratio = g_variant_get_uint64(data);
703                 ret = (devc->capture_ratio > 100) ? SR_ERR : SR_OK;
704                 break;
705         case SR_CONF_VOLTAGE_THRESHOLD:
706                 g_variant_get(data, "(dd)", &low, &high);
707                 ret = SR_ERR_ARG;
708                 for (i = 0; (unsigned int)i < ARRAY_SIZE(volt_thresholds); i++) {
709                         if (fabs(volt_thresholds[i].low - low) < 0.1 &&
710                             fabs(volt_thresholds[i].high - high) < 0.1) {
711                                 devc->dslogic_voltage_threshold = volt_thresholds[i].range;
712                                 break;
713                         }
714                 }
715                 if (!strcmp(devc->profile->model, "DSLogic")) {
716                         if (devc->dslogic_voltage_threshold == DS_VOLTAGE_RANGE_5_V)
717                                 ret = dslogic_fpga_firmware_upload(sdi, DSLOGIC_FPGA_FIRMWARE_5V);
718                         else
719                                 ret = dslogic_fpga_firmware_upload(sdi, DSLOGIC_FPGA_FIRMWARE_3V3);
720                 } else if (!strcmp(devc->profile->model, "DSLogic Pro")) {
721                         ret = dslogic_fpga_firmware_upload(sdi, DSLOGIC_PRO_FPGA_FIRMWARE);
722                 } else if (!strcmp(devc->profile->model, "DSLogic Plus")) {
723                         ret = dslogic_fpga_firmware_upload(sdi, DSLOGIC_PLUS_FPGA_FIRMWARE);
724                 } else if (!strcmp(devc->profile->model, "DSLogic Basic")) {
725                         ret = dslogic_fpga_firmware_upload(sdi, DSLOGIC_BASIC_FPGA_FIRMWARE);
726                 }
727                 break;
728         case SR_CONF_EXTERNAL_CLOCK:
729                 devc->dslogic_external_clock = g_variant_get_boolean(data);
730                 break;
731         case SR_CONF_CONTINUOUS:
732                 devc->dslogic_continuous_mode = g_variant_get_boolean(data);
733                 break;
734         case SR_CONF_CLOCK_EDGE:
735                 i = lookup_index(data, signal_edge_names,
736                                    ARRAY_SIZE(signal_edge_names));
737                 if (i < 0)
738                         return SR_ERR_ARG;
739                 devc->dslogic_clock_edge = i;
740                 break;
741         default:
742                 ret = SR_ERR_NA;
743         }
744
745         return ret;
746 }
747
748 static int config_list(uint32_t key, GVariant **data,
749         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
750 {
751         struct dev_context *devc;
752         GVariant *gvar, *range[2];
753         GVariantBuilder gvb;
754         unsigned int i;
755
756         (void)cg;
757
758         switch (key) {
759         case SR_CONF_SCAN_OPTIONS:
760                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
761                                 scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t));
762                 break;
763         case SR_CONF_DEVICE_OPTIONS:
764                 if (!sdi) {
765                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
766                                 drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
767                 } else {
768                         devc = sdi->priv;
769                         if (!devc->dslogic)
770                                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
771                                                                   devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
772                         else
773                                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
774                                                                   dslogic_devopts, ARRAY_SIZE(dslogic_devopts), sizeof(uint32_t));
775                 }
776                 break;
777         case SR_CONF_VOLTAGE_THRESHOLD:
778                 if (!sdi->priv)
779                         return SR_ERR_ARG;
780                 devc = sdi->priv;
781                 if (!devc->dslogic)
782                         return SR_ERR_NA;
783                 g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
784                 for (i = 0; i < ARRAY_SIZE(volt_thresholds); i++) {
785                         range[0] = g_variant_new_double(volt_thresholds[i].low);
786                         range[1] = g_variant_new_double(volt_thresholds[i].high);
787                         gvar = g_variant_new_tuple(range, 2);
788                         g_variant_builder_add_value(&gvb, gvar);
789                 }
790                 *data = g_variant_builder_end(&gvb);
791                 break;
792         case SR_CONF_SAMPLERATE:
793                 devc = sdi->priv;
794                 g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
795                 gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), devc->samplerates,
796                                 devc->num_samplerates, sizeof(uint64_t));
797                 g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
798                 *data = g_variant_builder_end(&gvb);
799                 break;
800         case SR_CONF_TRIGGER_MATCH:
801                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
802                                 soft_trigger_matches, ARRAY_SIZE(soft_trigger_matches),
803                                 sizeof(int32_t));
804                 break;
805         case SR_CONF_CLOCK_EDGE:
806                 *data = g_variant_new_strv(signal_edge_names,
807                         ARRAY_SIZE(signal_edge_names));
808                 break;
809         default:
810                 return SR_ERR_NA;
811         }
812
813         return SR_OK;
814 }
815
816 static int receive_data(int fd, int revents, void *cb_data)
817 {
818         struct timeval tv;
819         struct drv_context *drvc;
820
821         (void)fd;
822         (void)revents;
823
824         drvc = (struct drv_context *)cb_data;
825
826         tv.tv_sec = tv.tv_usec = 0;
827         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
828
829         return TRUE;
830 }
831
832 static int start_transfers(const struct sr_dev_inst *sdi)
833 {
834         struct dev_context *devc;
835         struct sr_usb_dev_inst *usb;
836         struct sr_trigger *trigger;
837         struct libusb_transfer *transfer;
838         unsigned int i, num_transfers;
839         int endpoint, timeout, ret;
840         unsigned char *buf;
841         size_t size;
842
843         devc = sdi->priv;
844         usb = sdi->conn;
845
846         devc->sent_samples = 0;
847         devc->acq_aborted = FALSE;
848         devc->empty_transfer_count = 0;
849
850         if ((trigger = sr_session_trigger_get(sdi->session)) && !devc->dslogic) {
851                 int pre_trigger_samples = 0;
852                 if (devc->limit_samples > 0)
853                         pre_trigger_samples = devc->capture_ratio * devc->limit_samples/100;
854                 devc->stl = soft_trigger_logic_new(sdi, trigger, pre_trigger_samples);
855                 if (!devc->stl)
856                         return SR_ERR_MALLOC;
857                 devc->trigger_fired = FALSE;
858         } else
859                 devc->trigger_fired = TRUE;
860
861         num_transfers = fx2lafw_get_number_of_transfers(devc);
862
863         if (devc->dslogic) {
864                 if (devc->cur_samplerate == SR_MHZ(100))
865                         num_transfers = 16;
866                 else if (devc->cur_samplerate == SR_MHZ(200))
867                         num_transfers = 8;
868                 else if (devc->cur_samplerate == SR_MHZ(400))
869                         num_transfers = 4;
870         }
871
872         size = fx2lafw_get_buffer_size(devc);
873         devc->submitted_transfers = 0;
874
875         devc->transfers = g_try_malloc0(sizeof(*devc->transfers) * num_transfers);
876         if (!devc->transfers) {
877                 sr_err("USB transfers malloc failed.");
878                 return SR_ERR_MALLOC;
879         }
880
881         timeout = fx2lafw_get_timeout(devc);
882         endpoint = devc->dslogic ? 6 : 2;
883         devc->num_transfers = num_transfers;
884         for (i = 0; i < num_transfers; i++) {
885                 if (!(buf = g_try_malloc(size))) {
886                         sr_err("USB transfer buffer malloc failed.");
887                         return SR_ERR_MALLOC;
888                 }
889                 transfer = libusb_alloc_transfer(0);
890                 libusb_fill_bulk_transfer(transfer, usb->devhdl,
891                                 endpoint | LIBUSB_ENDPOINT_IN, buf, size,
892                                 fx2lafw_receive_transfer, (void *)sdi, timeout);
893                 sr_info("submitting transfer: %d", i);
894                 if ((ret = libusb_submit_transfer(transfer)) != 0) {
895                         sr_err("Failed to submit transfer: %s.",
896                                libusb_error_name(ret));
897                         libusb_free_transfer(transfer);
898                         g_free(buf);
899                         fx2lafw_abort_acquisition(devc);
900                         return SR_ERR;
901                 }
902                 devc->transfers[i] = transfer;
903                 devc->submitted_transfers++;
904         }
905
906         /*
907          * If this device has analog channels and at least one of them is
908          * enabled, use mso_send_data_proc() to properly handle the analog
909          * data. Otherwise use la_send_data_proc().
910          */
911         if (g_slist_length(devc->enabled_analog_channels) > 0)
912                 devc->send_data_proc = mso_send_data_proc;
913         else
914                 devc->send_data_proc = la_send_data_proc;
915
916         std_session_send_df_header(sdi);
917
918         return SR_OK;
919 }
920
921 static void LIBUSB_CALL dslogic_trigger_receive(struct libusb_transfer *transfer)
922 {
923         const struct sr_dev_inst *sdi;
924         struct dslogic_trigger_pos *tpos;
925         struct dev_context *devc;
926
927         sdi = transfer->user_data;
928         devc = sdi->priv;
929         if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
930                 sr_dbg("Trigger transfer canceled.");
931                 /* Terminate session. */
932                 std_session_send_df_end(sdi);
933                 usb_source_remove(sdi->session, devc->ctx);
934                 devc->num_transfers = 0;
935                 g_free(devc->transfers);
936                 if (devc->stl) {
937                         soft_trigger_logic_free(devc->stl);
938                         devc->stl = NULL;
939                 }
940         } else if (transfer->status == LIBUSB_TRANSFER_COMPLETED
941                         && transfer->actual_length == sizeof(struct dslogic_trigger_pos)) {
942                 tpos = (struct dslogic_trigger_pos *)transfer->buffer;
943                 sr_info("tpos real_pos %d ram_saddr %d cnt %d", tpos->real_pos,
944                         tpos->ram_saddr, tpos->remain_cnt);
945                 devc->trigger_pos = tpos->real_pos;
946                 g_free(tpos);
947                 start_transfers(sdi);
948         }
949         libusb_free_transfer(transfer);
950 }
951
952 static int dslogic_trigger_request(const struct sr_dev_inst *sdi)
953 {
954         struct sr_usb_dev_inst *usb;
955         struct libusb_transfer *transfer;
956         struct dslogic_trigger_pos *tpos;
957         struct dev_context *devc;
958         int ret;
959
960         usb = sdi->conn;
961         devc = sdi->priv;
962
963         if ((ret = dslogic_stop_acquisition(sdi)) != SR_OK)
964                 return ret;
965
966         if ((ret = dslogic_fpga_configure(sdi)) != SR_OK)
967                 return ret;
968
969         /* If this is a DSLogic Pro, set the voltage threshold. */
970         if (!strcmp(devc->profile->model, "DSLogic Pro")){
971                 if (devc->dslogic_voltage_threshold == DS_VOLTAGE_RANGE_18_33_V) {
972                         dslogic_set_vth(sdi, 1.4);
973                 } else {
974                         dslogic_set_vth(sdi, 3.3);
975                 }
976         }
977
978         if ((ret = dslogic_start_acquisition(sdi)) != SR_OK)
979                 return ret;
980
981         sr_dbg("Getting trigger.");
982         tpos = g_malloc(sizeof(struct dslogic_trigger_pos));
983         transfer = libusb_alloc_transfer(0);
984         libusb_fill_bulk_transfer(transfer, usb->devhdl, 6 | LIBUSB_ENDPOINT_IN,
985                         (unsigned char *)tpos, sizeof(struct dslogic_trigger_pos),
986                         dslogic_trigger_receive, (void *)sdi, 0);
987         if ((ret = libusb_submit_transfer(transfer)) < 0) {
988                 sr_err("Failed to request trigger: %s.", libusb_error_name(ret));
989                 libusb_free_transfer(transfer);
990                 g_free(tpos);
991                 return SR_ERR;
992         }
993
994         devc->transfers = g_try_malloc0(sizeof(*devc->transfers));
995         if (!devc->transfers) {
996                 sr_err("USB trigger_pos transfer malloc failed.");
997                 return SR_ERR_MALLOC;
998         }
999         devc->num_transfers = 1;
1000         devc->submitted_transfers++;
1001         devc->transfers[0] = transfer;
1002
1003         return ret;
1004 }
1005
1006 static int configure_channels(const struct sr_dev_inst *sdi)
1007 {
1008         struct dev_context *devc;
1009         const GSList *l;
1010         int p;
1011         struct sr_channel *ch;
1012         uint32_t channel_mask = 0, num_analog = 0;
1013
1014         devc = sdi->priv;
1015
1016         g_slist_free(devc->enabled_analog_channels);
1017         devc->enabled_analog_channels = NULL;
1018
1019         for (l = sdi->channels, p = 0; l; l = l->next, p++) {
1020                 ch = l->data;
1021                 if ((p <= NUM_CHANNELS) && (ch->type == SR_CHANNEL_ANALOG)
1022                                 && (ch->enabled)) {
1023                         num_analog++;
1024                         devc->enabled_analog_channels =
1025                             g_slist_append(devc->enabled_analog_channels, ch);
1026                 } else {
1027                         channel_mask |= ch->enabled << p;
1028                 }
1029         }
1030
1031         /*
1032          * Use wide sampling if either any of the LA channels 8..15 is enabled,
1033          * and/or at least one analog channel is enabled, and/or the device
1034          * is running DSLogic firmware (not fx2lafw).
1035          */
1036         devc->sample_wide = (channel_mask > 0xff
1037                         || num_analog > 0
1038                         || (devc->profile->dev_caps & DEV_CAPS_DSLOGIC_FW));
1039
1040         return SR_OK;
1041 }
1042
1043 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
1044 {
1045         struct sr_dev_driver *di;
1046         struct drv_context *drvc;
1047         struct dev_context *devc;
1048         int timeout, ret;
1049         size_t size;
1050
1051         if (sdi->status != SR_ST_ACTIVE)
1052                 return SR_ERR_DEV_CLOSED;
1053
1054         di = sdi->driver;
1055         drvc = di->context;
1056         devc = sdi->priv;
1057
1058         devc->ctx = drvc->sr_ctx;
1059         devc->sent_samples = 0;
1060         devc->empty_transfer_count = 0;
1061         devc->acq_aborted = FALSE;
1062
1063         if (configure_channels(sdi) != SR_OK) {
1064                 sr_err("Failed to configure channels.");
1065                 return SR_ERR;
1066         }
1067
1068         timeout = fx2lafw_get_timeout(devc);
1069         usb_source_add(sdi->session, devc->ctx, timeout, receive_data, drvc);
1070
1071         if (devc->dslogic) {
1072                 dslogic_trigger_request(sdi);
1073         } else {
1074                 size = fx2lafw_get_buffer_size(devc);
1075                 /* Prepare for analog sampling. */
1076                 if (g_slist_length(devc->enabled_analog_channels) > 0) {
1077                         /* We need a buffer half the size of a transfer. */
1078                         devc->logic_buffer = g_try_malloc(size / 2);
1079                         devc->analog_buffer = g_try_malloc(
1080                                 sizeof(float) * size / 2);
1081                 }
1082                 start_transfers(sdi);
1083                 if ((ret = fx2lafw_command_start_acquisition(sdi)) != SR_OK) {
1084                         fx2lafw_abort_acquisition(devc);
1085                         return ret;
1086                 }
1087         }
1088
1089         return SR_OK;
1090 }
1091
1092 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
1093 {
1094         struct dev_context *devc;
1095
1096         devc = sdi->priv;
1097
1098         if (devc->dslogic)
1099                 dslogic_stop_acquisition(sdi);
1100
1101         fx2lafw_abort_acquisition(sdi->priv);
1102
1103         return SR_OK;
1104 }
1105
1106 static struct sr_dev_driver fx2lafw_driver_info = {
1107         .name = "fx2lafw",
1108         .longname = "fx2lafw (generic driver for FX2 based LAs)",
1109         .api_version = 1,
1110         .init = std_init,
1111         .cleanup = std_cleanup,
1112         .scan = scan,
1113         .dev_list = std_dev_list,
1114         .dev_clear = dev_clear,
1115         .config_get = config_get,
1116         .config_set = config_set,
1117         .config_list = config_list,
1118         .dev_open = dev_open,
1119         .dev_close = dev_close,
1120         .dev_acquisition_start = dev_acquisition_start,
1121         .dev_acquisition_stop = dev_acquisition_stop,
1122         .context = NULL,
1123 };
1124 SR_REGISTER_DEV_DRIVER(fx2lafw_driver_info);