]> sigrok.org Git - libsigrok.git/blob - hardware/saleae-logic16/api.c
saleae-logic16: Shorten dev_list() implementation.
[libsigrok.git] / hardware / saleae-logic16 / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Marcus Comstedt <marcus@mc.pp.se>
5  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
6  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <glib.h>
23 #include <libusb.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <math.h>
27 #include "libsigrok.h"
28 #include "libsigrok-internal.h"
29 #include "protocol.h"
30
31 #define LOGIC16_VID             0x21a9
32 #define LOGIC16_PID             0x1001
33 #define NUM_PROBES              16
34
35 #define USB_INTERFACE           0
36 #define USB_CONFIGURATION       1
37 #define FX2_FIRMWARE            FIRMWARE_DIR "/saleae-logic16-fx2.fw"
38
39 #define MAX_RENUM_DELAY_MS      3000
40 #define NUM_SIMUL_TRANSFERS     32
41
42 SR_PRIV struct sr_dev_driver saleae_logic16_driver_info;
43 static struct sr_dev_driver *di = &saleae_logic16_driver_info;
44
45 static const int32_t hwopts[] = {
46         SR_CONF_CONN,
47 };
48
49 static const int32_t hwcaps[] = {
50         SR_CONF_LOGIC_ANALYZER,
51         SR_CONF_SAMPLERATE,
52         SR_CONF_VOLTAGE_THRESHOLD,
53
54         /* These are really implemented in the driver, not the hardware. */
55         SR_CONF_LIMIT_SAMPLES,
56         SR_CONF_CONTINUOUS,
57 };
58
59 static const char *probe_names[NUM_PROBES + 1] = {
60         "0", "1", "2", "3", "4", "5", "6", "7", "8",
61         "9", "10", "11", "12", "13", "14", "15",
62         NULL,
63 };
64
65 static const struct {
66         enum voltage_range range;
67         gdouble low;
68         gdouble high;
69 } volt_thresholds[] = {
70         { VOLTAGE_RANGE_18_33_V, 0.7, 1.4 },
71         { VOLTAGE_RANGE_5_V,     1.4, 3.6 },
72 };
73
74 static const uint64_t samplerates[] = {
75         SR_KHZ(500),
76         SR_MHZ(1),
77         SR_MHZ(2),
78         SR_MHZ(4),
79         SR_MHZ(5),
80         SR_MHZ(8),
81         SR_MHZ(10),
82         SR_KHZ(12500),
83         SR_MHZ(16),
84         SR_MHZ(25),
85         SR_MHZ(32),
86         SR_MHZ(40),
87         SR_MHZ(80),
88         SR_MHZ(100),
89 };
90
91 static int init(struct sr_context *sr_ctx)
92 {
93         return std_init(sr_ctx, di, LOG_PREFIX);
94 }
95
96 static gboolean check_conf_profile(libusb_device *dev)
97 {
98         struct libusb_device_descriptor des;
99         struct libusb_device_handle *hdl;
100         gboolean ret;
101         unsigned char strdesc[64];
102
103         hdl = NULL;
104         ret = FALSE;
105         while (!ret) {
106                 /* Assume the FW has not been loaded, unless proven wrong. */
107                 if (libusb_get_device_descriptor(dev, &des) != 0)
108                         break;
109
110                 if (libusb_open(dev, &hdl) != 0)
111                         break;
112
113                 if (libusb_get_string_descriptor_ascii(hdl,
114                     des.iManufacturer, strdesc, sizeof(strdesc)) < 0)
115                         break;
116                 if (strcmp((const char *)strdesc, "Saleae LLC"))
117                         break;
118
119                 if (libusb_get_string_descriptor_ascii(hdl,
120                     des.iProduct, strdesc, sizeof(strdesc)) < 0)
121                         break;
122                 if (strcmp((const char *)strdesc, "Logic S/16"))
123                         break;
124
125                 /* If we made it here, it must be a configured Logic16. */
126                 ret = TRUE;
127         }
128         if (hdl)
129                 libusb_close(hdl);
130
131         return ret;
132 }
133
134 static GSList *scan(GSList *options)
135 {
136         struct drv_context *drvc;
137         struct dev_context *devc;
138         struct sr_dev_inst *sdi;
139         struct sr_usb_dev_inst *usb;
140         struct sr_probe *probe;
141         struct sr_config *src;
142         GSList *l, *devices, *conn_devices;
143         struct libusb_device_descriptor des;
144         libusb_device **devlist;
145         int devcnt, ret, i, j;
146         const char *conn;
147
148         drvc = di->priv;
149
150         conn = NULL;
151         for (l = options; l; l = l->next) {
152                 src = l->data;
153                 switch (src->key) {
154                 case SR_CONF_CONN:
155                         conn = g_variant_get_string(src->data, NULL);
156                         break;
157                 }
158         }
159         if (conn)
160                 conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
161         else
162                 conn_devices = NULL;
163
164         /* Find all Logic16 devices and upload firmware to them. */
165         devices = NULL;
166         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
167         for (i = 0; devlist[i]; i++) {
168                 if (conn) {
169                         usb = NULL;
170                         for (l = conn_devices; l; l = l->next) {
171                                 usb = l->data;
172                                 if (usb->bus == libusb_get_bus_number(devlist[i])
173                                     && usb->address == libusb_get_device_address(devlist[i]))
174                                         break;
175                         }
176                         if (!l)
177                                 /* This device matched none of the ones that
178                                  * matched the conn specification. */
179                                 continue;
180                 }
181
182                 if ((ret = libusb_get_device_descriptor(devlist[i], &des)) != 0) {
183                         sr_warn("Failed to get device descriptor: %s.",
184                                 libusb_error_name(ret));
185                         continue;
186                 }
187
188                 if (des.idVendor != LOGIC16_VID || des.idProduct != LOGIC16_PID)
189                         continue;
190
191                 devcnt = g_slist_length(drvc->instances);
192                 sdi = sr_dev_inst_new(devcnt, SR_ST_INITIALIZING,
193                                       "Saleae", "Logic16", NULL);
194                 if (!sdi)
195                         return NULL;
196                 sdi->driver = di;
197
198                 for (j = 0; probe_names[j]; j++) {
199                         if (!(probe = sr_probe_new(j, SR_PROBE_LOGIC, TRUE,
200                                                    probe_names[j])))
201                                 return NULL;
202                         sdi->probes = g_slist_append(sdi->probes, probe);
203                 }
204
205                 if (!(devc = g_try_malloc0(sizeof(struct dev_context))))
206                         return NULL;
207                 devc->selected_voltage_range = VOLTAGE_RANGE_18_33_V;
208                 sdi->priv = devc;
209                 drvc->instances = g_slist_append(drvc->instances, sdi);
210                 devices = g_slist_append(devices, sdi);
211
212                 if (check_conf_profile(devlist[i])) {
213                         /* Already has the firmware, so fix the new address. */
214                         sr_dbg("Found a Logic16 device.");
215                         sdi->status = SR_ST_INACTIVE;
216                         sdi->inst_type = SR_INST_USB;
217                         sdi->conn = sr_usb_dev_inst_new(
218                                 libusb_get_bus_number(devlist[i]),
219                                 libusb_get_device_address(devlist[i]), NULL);
220                 } else {
221                         if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
222                                                   FX2_FIRMWARE) == SR_OK)
223                                 /* Store when this device's FW was updated. */
224                                 devc->fw_updated = g_get_monotonic_time();
225                         else
226                                 sr_err("Firmware upload failed for "
227                                        "device %d.", devcnt);
228                         sdi->inst_type = SR_INST_USB;
229                         sdi->conn = sr_usb_dev_inst_new(
230                                 libusb_get_bus_number(devlist[i]), 0xff, NULL);
231                 }
232         }
233         libusb_free_device_list(devlist, 1);
234         g_slist_free_full(conn_devices, (GDestroyNotify)sr_usb_dev_inst_free);
235
236         return devices;
237 }
238
239 static GSList *dev_list(void)
240 {
241         return ((struct drv_context *)(di->priv))->instances;
242 }
243
244 static int dev_clear(void)
245 {
246         return std_dev_clear(di, NULL);
247 }
248
249 static int logic16_dev_open(struct sr_dev_inst *sdi)
250 {
251         libusb_device **devlist;
252         struct sr_usb_dev_inst *usb;
253         struct libusb_device_descriptor des;
254         struct drv_context *drvc;
255         int ret, skip, i, device_count;
256
257         drvc = di->priv;
258         usb = sdi->conn;
259
260         if (sdi->status == SR_ST_ACTIVE)
261                 /* Device is already in use. */
262                 return SR_ERR;
263
264         skip = 0;
265         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
266         if (device_count < 0) {
267                 sr_err("Failed to get device list: %s.",
268                        libusb_error_name(device_count));
269                 return SR_ERR;
270         }
271
272         for (i = 0; i < device_count; i++) {
273                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
274                         sr_err("Failed to get device descriptor: %s.",
275                                libusb_error_name(ret));
276                         continue;
277                 }
278
279                 if (des.idVendor != LOGIC16_VID || des.idProduct != LOGIC16_PID)
280                         continue;
281
282                 if (sdi->status == SR_ST_INITIALIZING) {
283                         if (skip != sdi->index) {
284                                 /* Skip devices of this type that aren't the one we want. */
285                                 skip += 1;
286                                 continue;
287                         }
288                 } else if (sdi->status == SR_ST_INACTIVE) {
289                         /*
290                          * This device is fully enumerated, so we need to find
291                          * this device by vendor, product, bus and address.
292                          */
293                         if (libusb_get_bus_number(devlist[i]) != usb->bus
294                             || libusb_get_device_address(devlist[i]) != usb->address)
295                                 /* This is not the one. */
296                                 continue;
297                 }
298
299                 if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
300                         if (usb->address == 0xff)
301                                 /*
302                                  * First time we touch this device after FW
303                                  * upload, so we don't know the address yet.
304                                  */
305                                 usb->address = libusb_get_device_address(devlist[i]);
306                 } else {
307                         sr_err("Failed to open device: %s.",
308                                libusb_error_name(ret));
309                         break;
310                 }
311
312                 if ((ret = logic16_init_device(sdi)) != SR_OK) {
313                         sr_err("Failed to init device.");
314                         break;
315                 }
316
317                 sdi->status = SR_ST_ACTIVE;
318                 sr_info("Opened device %d on %d.%d, interface %d.",
319                         sdi->index, usb->bus, usb->address, USB_INTERFACE);
320
321                 break;
322         }
323         libusb_free_device_list(devlist, 1);
324
325         if (sdi->status != SR_ST_ACTIVE)
326                 return SR_ERR;
327
328         return SR_OK;
329 }
330
331 static int dev_open(struct sr_dev_inst *sdi)
332 {
333         struct sr_usb_dev_inst *usb;
334         struct dev_context *devc;
335         int ret;
336         int64_t timediff_us, timediff_ms;
337
338         devc = sdi->priv;
339         usb = sdi->conn;
340
341         /*
342          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
343          * milliseconds for the FX2 to renumerate.
344          */
345         ret = SR_ERR;
346         if (devc->fw_updated > 0) {
347                 sr_info("Waiting for device to reset.");
348                 /* Takes >= 300ms for the FX2 to be gone from the USB bus. */
349                 g_usleep(300 * 1000);
350                 timediff_ms = 0;
351                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
352                         if ((ret = logic16_dev_open(sdi)) == SR_OK)
353                                 break;
354                         g_usleep(100 * 1000);
355
356                         timediff_us = g_get_monotonic_time() - devc->fw_updated;
357                         timediff_ms = timediff_us / 1000;
358                         sr_spew("Waited %" PRIi64 "ms.", timediff_ms);
359                 }
360                 if (ret != SR_OK) {
361                         sr_err("Device failed to renumerate.");
362                         return SR_ERR;
363                 }
364                 sr_info("Device came back after %" PRIi64 "ms.", timediff_ms);
365         } else {
366                 sr_info("Firmware upload was not needed.");
367                 ret = logic16_dev_open(sdi);
368         }
369
370         if (ret != SR_OK) {
371                 sr_err("Unable to open device.");
372                 return SR_ERR;
373         }
374
375         ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
376         if (ret != 0) {
377                 switch (ret) {
378                 case LIBUSB_ERROR_BUSY:
379                         sr_err("Unable to claim USB interface. Another "
380                                "program or driver has already claimed it.");
381                         break;
382                 case LIBUSB_ERROR_NO_DEVICE:
383                         sr_err("Device has been disconnected.");
384                         break;
385                 default:
386                         sr_err("Unable to claim interface: %s.",
387                                libusb_error_name(ret));
388                         break;
389                 }
390
391                 return SR_ERR;
392         }
393
394         if (devc->cur_samplerate == 0) {
395                 /* Samplerate hasn't been set; default to the slowest one. */
396                 devc->cur_samplerate = samplerates[0];
397         }
398
399         return SR_OK;
400 }
401
402 static int dev_close(struct sr_dev_inst *sdi)
403 {
404         struct sr_usb_dev_inst *usb;
405
406         usb = sdi->conn;
407         if (usb->devhdl == NULL)
408                 return SR_ERR;
409
410         sr_info("Closing device %d on %d.%d interface %d.",
411                 sdi->index, usb->bus, usb->address, USB_INTERFACE);
412         libusb_release_interface(usb->devhdl, USB_INTERFACE);
413         libusb_close(usb->devhdl);
414         usb->devhdl = NULL;
415         sdi->status = SR_ST_INACTIVE;
416
417         return SR_OK;
418 }
419
420 static int cleanup(void)
421 {
422         int ret;
423         struct drv_context *drvc;
424
425         if (!(drvc = di->priv))
426                 /* Can get called on an unused driver, doesn't matter. */
427                 return SR_OK;
428
429         ret = dev_clear();
430         g_free(drvc);
431         di->priv = NULL;
432
433         return ret;
434 }
435
436 static int config_get(int key, GVariant **data, const struct sr_dev_inst *sdi)
437 {
438         struct dev_context *devc;
439         struct sr_usb_dev_inst *usb;
440         GVariant *range[2];
441         char str[128];
442         int ret;
443         unsigned int i;
444
445         ret = SR_OK;
446         switch (key) {
447         case SR_CONF_CONN:
448                 if (!sdi || !sdi->conn)
449                         return SR_ERR_ARG;
450                 usb = sdi->conn;
451                 if (usb->address == 255)
452                         /* Device still needs to re-enumerate after firmware
453                          * upload, so we don't know its (future) address. */
454                         return SR_ERR;
455                 snprintf(str, 128, "%d.%d", usb->bus, usb->address);
456                 *data = g_variant_new_string(str);
457                 break;
458         case SR_CONF_SAMPLERATE:
459                 if (!sdi)
460                         return SR_ERR;
461                 devc = sdi->priv;
462                 *data = g_variant_new_uint64(devc->cur_samplerate);
463                 break;
464         case SR_CONF_VOLTAGE_THRESHOLD:
465                 if (!sdi)
466                         return SR_ERR;
467                 devc = sdi->priv;
468                 ret = SR_ERR;
469                 for (i = 0; i < ARRAY_SIZE(volt_thresholds); i++) {
470                         if (devc->selected_voltage_range !=
471                             volt_thresholds[i].range)
472                                 continue;
473                         range[0] = g_variant_new_double(volt_thresholds[i].low);
474                         range[1] = g_variant_new_double(volt_thresholds[i].high);
475                         *data = g_variant_new_tuple(range, 2);
476                         ret = SR_OK;
477                         break;
478                 }
479                 break;
480         default:
481                 return SR_ERR_NA;
482         }
483
484         return ret;
485 }
486
487 static int config_set(int key, GVariant *data, const struct sr_dev_inst *sdi)
488 {
489         struct dev_context *devc;
490         gdouble low, high;
491         int ret;
492         unsigned int i;
493
494         if (sdi->status != SR_ST_ACTIVE)
495                 return SR_ERR_DEV_CLOSED;
496
497         devc = sdi->priv;
498
499         ret = SR_OK;
500         switch (key) {
501         case SR_CONF_SAMPLERATE:
502                 devc->cur_samplerate = g_variant_get_uint64(data);
503                 break;
504         case SR_CONF_LIMIT_SAMPLES:
505                 devc->limit_samples = g_variant_get_uint64(data);
506                 break;
507         case SR_CONF_VOLTAGE_THRESHOLD:
508                 g_variant_get(data, "(dd)", &low, &high);
509                 ret = SR_ERR_ARG;
510                 for (i = 0; i < ARRAY_SIZE(volt_thresholds); i++) {
511                         if (fabs(volt_thresholds[i].low - low) < 0.1 &&
512                             fabs(volt_thresholds[i].high - high) < 0.1) {
513                                 devc->selected_voltage_range =
514                                         volt_thresholds[i].range;
515                                 ret = SR_OK;
516                                 break;
517                         }
518                 }
519                 break;
520         default:
521                 ret = SR_ERR_NA;
522         }
523
524         return ret;
525 }
526
527 static int config_list(int key, GVariant **data, const struct sr_dev_inst *sdi)
528 {
529         GVariant *gvar, *range[2];
530         GVariantBuilder gvb;
531         int ret;
532         unsigned int i;
533
534         (void)sdi;
535
536         ret = SR_OK;
537         switch (key) {
538         case SR_CONF_SCAN_OPTIONS:
539                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
540                                 hwopts, ARRAY_SIZE(hwopts), sizeof(int32_t));
541                 break;
542         case SR_CONF_DEVICE_OPTIONS:
543                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
544                                 hwcaps, ARRAY_SIZE(hwcaps), sizeof(int32_t));
545                 break;
546         case SR_CONF_SAMPLERATE:
547                 g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
548                 gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"),
549                         samplerates, ARRAY_SIZE(samplerates), sizeof(uint64_t));
550                 g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
551                 *data = g_variant_builder_end(&gvb);
552                 break;
553         case SR_CONF_VOLTAGE_THRESHOLD:
554                 g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
555                 for (i = 0; i < ARRAY_SIZE(volt_thresholds); i++) {
556                         range[0] = g_variant_new_double(volt_thresholds[i].low);
557                         range[1] = g_variant_new_double(volt_thresholds[i].high);
558                         gvar = g_variant_new_tuple(range, 2);
559                         g_variant_builder_add_value(&gvb, gvar);
560                 }
561                 *data = g_variant_builder_end(&gvb);
562                 break;
563         default:
564                 return SR_ERR_NA;
565         }
566
567         return ret;
568 }
569
570 static void abort_acquisition(struct dev_context *devc)
571 {
572         int i;
573
574         devc->num_samples = -1;
575
576         for (i = devc->num_transfers - 1; i >= 0; i--) {
577                 if (devc->transfers[i])
578                         libusb_cancel_transfer(devc->transfers[i]);
579         }
580 }
581
582 static unsigned int bytes_per_ms(struct dev_context *devc)
583 {
584         return devc->cur_samplerate * devc->num_channels / 8000;
585 }
586
587 static size_t get_buffer_size(struct dev_context *devc)
588 {
589         size_t s;
590
591         /*
592          * The buffer should be large enough to hold 10ms of data and
593          * a multiple of 512.
594          */
595         s = 10 * bytes_per_ms(devc);
596         return (s + 511) & ~511;
597 }
598
599 static unsigned int get_number_of_transfers(struct dev_context *devc)
600 {
601         unsigned int n;
602
603         /* Total buffer size should be able to hold about 500ms of data. */
604         n = 500 * bytes_per_ms(devc) / get_buffer_size(devc);
605
606         if (n > NUM_SIMUL_TRANSFERS)
607                 return NUM_SIMUL_TRANSFERS;
608
609         return n;
610 }
611
612 static unsigned int get_timeout(struct dev_context *devc)
613 {
614         size_t total_size;
615         unsigned int timeout;
616
617         total_size = get_buffer_size(devc) * get_number_of_transfers(devc);
618         timeout = total_size / bytes_per_ms(devc);
619         return timeout + timeout / 4; /* Leave a headroom of 25% percent. */
620 }
621
622 static int configure_probes(const struct sr_dev_inst *sdi)
623 {
624         struct dev_context *devc;
625         struct sr_probe *probe;
626         GSList *l;
627         uint16_t probe_bit;
628
629         devc = sdi->priv;
630
631         devc->cur_channels = 0;
632         devc->num_channels = 0;
633         for (l = sdi->probes; l; l = l->next) {
634                 probe = (struct sr_probe *)l->data;
635                 if (probe->enabled == FALSE)
636                         continue;
637
638                 probe_bit = 1 << (probe->index);
639
640                 devc->cur_channels |= probe_bit;
641
642 #ifdef WORDS_BIGENDIAN
643                 /*
644                  * Output logic data should be stored in little endian format.
645                  * To speed things up during conversion, do the switcharoo
646                  * here instead.
647                  */
648                 probe_bit = 1 << (probe->index ^ 8);
649 #endif
650
651                 devc->channel_masks[devc->num_channels++] = probe_bit;
652         }
653
654         return SR_OK;
655 }
656
657 static int receive_data(int fd, int revents, void *cb_data)
658 {
659         struct timeval tv;
660         struct dev_context *devc;
661         struct drv_context *drvc;
662         const struct sr_dev_inst *sdi;
663
664         (void)fd;
665         (void)revents;
666
667         sdi = cb_data;
668         drvc = di->priv;
669         devc = sdi->priv;
670
671         tv.tv_sec = tv.tv_usec = 0;
672         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
673
674         if (devc->num_samples == -2) {
675                 logic16_abort_acquisition(sdi);
676                 abort_acquisition(devc);
677         }
678
679         return TRUE;
680 }
681
682 static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data)
683 {
684         struct dev_context *devc;
685         struct drv_context *drvc;
686         struct sr_usb_dev_inst *usb;
687         struct libusb_transfer *transfer;
688         const struct libusb_pollfd **lupfd;
689         unsigned int i, timeout, num_transfers;
690         int ret;
691         unsigned char *buf;
692         size_t size, convsize;
693
694         if (sdi->status != SR_ST_ACTIVE)
695                 return SR_ERR_DEV_CLOSED;
696
697         drvc = di->priv;
698         devc = sdi->priv;
699         usb = sdi->conn;
700
701         /* Configures devc->cur_channels. */
702         if (configure_probes(sdi) != SR_OK) {
703                 sr_err("Failed to configure probes.");
704                 return SR_ERR;
705         }
706
707         devc->cb_data = cb_data;
708         devc->num_samples = 0;
709         devc->empty_transfer_count = 0;
710         devc->cur_channel = 0;
711         memset(devc->channel_data, 0, sizeof(devc->channel_data));
712
713         timeout = get_timeout(devc);
714         num_transfers = get_number_of_transfers(devc);
715         size = get_buffer_size(devc);
716         convsize = (size / devc->num_channels + 2) * 16;
717         devc->submitted_transfers = 0;
718         devc->usbfd = NULL;
719
720         devc->convbuffer_size = convsize;
721         if (!(devc->convbuffer = g_try_malloc(convsize))) {
722                 sr_err("Conversion buffer malloc failed.");
723                 return SR_ERR_MALLOC;
724         }
725
726         devc->transfers = g_try_malloc0(sizeof(*devc->transfers) * num_transfers);
727         if (!devc->transfers) {
728                 sr_err("USB transfers malloc failed.");
729                 g_free(devc->convbuffer);
730                 return SR_ERR_MALLOC;
731         }
732
733         if ((ret = logic16_setup_acquisition(sdi, devc->cur_samplerate,
734                                              devc->cur_channels)) != SR_OK) {
735                 g_free(devc->transfers);
736                 g_free(devc->convbuffer);
737                 return ret;
738         }
739
740         devc->num_transfers = num_transfers;
741         for (i = 0; i < num_transfers; i++) {
742                 if (!(buf = g_try_malloc(size))) {
743                         sr_err("USB transfer buffer malloc failed.");
744                         if (devc->submitted_transfers)
745                                 abort_acquisition(devc);
746                         else {
747                                 g_free(devc->transfers);
748                                 g_free(devc->convbuffer);
749                         }
750                         return SR_ERR_MALLOC;
751                 }
752                 transfer = libusb_alloc_transfer(0);
753                 libusb_fill_bulk_transfer(transfer, usb->devhdl,
754                                 2 | LIBUSB_ENDPOINT_IN, buf, size,
755                                 logic16_receive_transfer, devc, timeout);
756                 if ((ret = libusb_submit_transfer(transfer)) != 0) {
757                         sr_err("Failed to submit transfer: %s.",
758                                libusb_error_name(ret));
759                         libusb_free_transfer(transfer);
760                         g_free(buf);
761                         abort_acquisition(devc);
762                         return SR_ERR;
763                 }
764                 devc->transfers[i] = transfer;
765                 devc->submitted_transfers++;
766         }
767
768         lupfd = libusb_get_pollfds(drvc->sr_ctx->libusb_ctx);
769         for (i = 0; lupfd[i]; i++);
770         devc->usbfd = g_try_malloc(sizeof(struct libusb_pollfd) * (i + 1));
771         if (!devc->usbfd) {
772                 abort_acquisition(devc);
773                 free(lupfd);
774                 return SR_ERR;
775         }
776         for (i = 0; lupfd[i]; i++) {
777                 sr_source_add(lupfd[i]->fd, lupfd[i]->events,
778                               timeout, receive_data, (void *)sdi);
779                 devc->usbfd[i] = lupfd[i]->fd;
780         }
781         devc->usbfd[i] = -1;
782         free(lupfd);
783
784         /* Send header packet to the session bus. */
785         std_session_send_df_header(cb_data, LOG_PREFIX);
786
787         if ((ret = logic16_start_acquisition(sdi)) != SR_OK) {
788                 abort_acquisition(devc);
789                 return ret;
790         }
791
792         return SR_OK;
793 }
794
795 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
796 {
797         int ret;
798
799         (void)cb_data;
800
801         if (sdi->status != SR_ST_ACTIVE)
802                 return SR_ERR_DEV_CLOSED;
803
804         ret = logic16_abort_acquisition(sdi);
805
806         abort_acquisition(sdi->priv);
807
808         return ret;
809 }
810
811 SR_PRIV struct sr_dev_driver saleae_logic16_driver_info = {
812         .name = "saleae-logic16",
813         .longname = "Saleae Logic16",
814         .api_version = 1,
815         .init = init,
816         .cleanup = cleanup,
817         .scan = scan,
818         .dev_list = dev_list,
819         .dev_clear = dev_clear,
820         .config_get = config_get,
821         .config_set = config_set,
822         .config_list = config_list,
823         .dev_open = dev_open,
824         .dev_close = dev_close,
825         .dev_acquisition_start = dev_acquisition_start,
826         .dev_acquisition_stop = dev_acquisition_stop,
827         .priv = NULL,
828 };