]> sigrok.org Git - libsigrok.git/blob - hardware/saleae-logic/saleae-logic.c
opendev2/opendev3: Don't depend on global vars.
[libsigrok.git] / hardware / saleae-logic / saleae-logic.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/time.h>
23 #include <inttypes.h>
24 #include <glib.h>
25 #include <libusb.h>
26 #include <sigrok.h>
27 #include "config.h"
28
29 #define USB_VENDOR                      0x0925
30 #define USB_PRODUCT                     0x3881
31 #define USB_VENDOR_NAME                 "Saleae"
32 #define USB_MODEL_NAME                  "Logic"
33 #define USB_MODEL_VERSION               ""
34
35 #define USB_INTERFACE                   0
36 #define USB_CONFIGURATION               1
37 #define NUM_PROBES                      8
38 #define NUM_TRIGGER_STAGES              4
39 #define TRIGGER_TYPES                   "01"
40 #define FIRMWARE                        FIRMWARE_DIR "/saleae-logic.fw"
41
42 /* delay in ms */
43 #define FIRMWARE_RENUM_DELAY            2000
44 #define NUM_SIMUL_TRANSFERS             10
45 #define MAX_EMPTY_TRANSFERS             (NUM_SIMUL_TRANSFERS * 2)
46
47 /* Software trigger implementation: positive values indicate trigger stage. */
48 #define TRIGGER_FIRED                   -1
49
50 /* There is only one model Saleae Logic, and this is what it supports: */
51 static int capabilities[] = {
52         HWCAP_LOGIC_ANALYZER,
53         HWCAP_SAMPLERATE,
54
55         /* These are really implemented in the driver, not the hardware. */
56         HWCAP_LIMIT_SAMPLES,
57         0,
58 };
59
60 /* List of struct sigrok_device_instance, maintained by opendev()/closedev(). */
61 static GSList *device_instances = NULL;
62
63 /*
64  * Since we can't keep track of a Saleae Logic device after upgrading the
65  * firmware -- it re-enumerates into a different device address after the
66  * upgrade -- this is like a global lock. No device will open until a proper
67  * delay after the last device was upgraded.
68  */
69 GTimeVal firmware_updated = { 0, 0 };
70
71 static libusb_context *usb_context = NULL;
72
73 static uint64_t supported_samplerates[] = {
74         KHZ(200),
75         KHZ(250),
76         KHZ(500),
77         MHZ(1),
78         MHZ(2),
79         MHZ(4),
80         MHZ(8),
81         MHZ(12),
82         MHZ(16),
83         MHZ(24),
84         0,
85 };
86
87 static struct samplerates samplerates = {
88         KHZ(200),
89         MHZ(24),
90         0,
91         supported_samplerates,
92 };
93
94 /* TODO: All of these should go in a device-specific struct. */
95 static uint64_t cur_samplerate = 0;
96 static uint64_t limit_samples = 0;
97 static uint8_t probe_mask = 0;
98 static uint8_t trigger_mask[NUM_TRIGGER_STAGES] = { 0 };
99 static uint8_t trigger_value[NUM_TRIGGER_STAGES] = { 0 };
100 static uint8_t trigger_buffer[NUM_TRIGGER_STAGES] = { 0 };
101
102 int trigger_stage = TRIGGER_FIRED;
103
104 static int hw_set_configuration(int device_index, int capability, void *value);
105 static void hw_stop_acquisition(int device_index, gpointer session_device_id);
106
107 /**
108  * Check the USB configuration to determine if this is a Saleae Logic.
109  *
110  * @return 1 if the device's configuration profile match the Logic firmware's
111  *         configuration, 0 otherwise.
112  */
113 int check_conf_profile(libusb_device *dev)
114 {
115         struct libusb_device_descriptor des;
116         struct libusb_config_descriptor *conf_dsc = NULL;
117         const struct libusb_interface_descriptor *intf_dsc;
118         int ret = -1;
119
120         while (ret == -1) {
121                 /* Assume it's not a Saleae Logic unless proven wrong. */
122                 ret = 0;
123
124                 if (libusb_get_device_descriptor(dev, &des) != 0)
125                         break;
126
127                 if (des.bNumConfigurations != 1)
128                         /* Need exactly 1 configuration. */
129                         break;
130
131                 if (libusb_get_config_descriptor(dev, 0, &conf_dsc) != 0)
132                         break;
133
134                 if (conf_dsc->bNumInterfaces != 1)
135                         /* Need exactly 1 interface. */
136                         break;
137
138                 if (conf_dsc->interface[0].num_altsetting != 1)
139                         /* Need just one alternate setting. */
140                         break;
141
142                 intf_dsc = &(conf_dsc->interface[0].altsetting[0]);
143                 if (intf_dsc->bNumEndpoints != 2)
144                         /* Need 2 endpoints. */
145                         break;
146
147                 if ((intf_dsc->endpoint[0].bEndpointAddress & 0x8f) !=
148                     (1 | LIBUSB_ENDPOINT_OUT))
149                         /* First endpoint should be 1 (outbound). */
150                         break;
151
152                 if ((intf_dsc->endpoint[1].bEndpointAddress & 0x8f) !=
153                     (2 | LIBUSB_ENDPOINT_IN))
154                         /* First endpoint should be 2 (inbound). */
155                         break;
156
157                 /* If we made it here, it must be a Saleae Logic. */
158                 ret = 1;
159         }
160
161         if (conf_dsc)
162                 libusb_free_config_descriptor(conf_dsc);
163
164         return ret;
165 }
166
167 static int opendev2(int device_index, struct sigrok_device_instance **sdi,
168                     libusb_device *dev, struct libusb_device_descriptor *des,
169                     int *skip, uint16_t vid, uint16_t pid, int interface)
170 {
171         int err;
172
173         if ((err = libusb_get_device_descriptor(dev, des))) {
174                 g_warning("failed to get device descriptor: %d", err);
175                 return -1;
176         }
177
178         if (des->idVendor != vid || des->idProduct != pid)
179                 return 0;
180
181         if (*skip != device_index) {
182                 /* Skip devices of this type that aren't the one we want. */
183                 *skip += 1;
184                 return 0;
185         }
186
187         /*
188          * Should check the bus here, since we know that already. But what are
189          * we going to do if it doesn't match after the right number of skips?
190          */
191         if (!(err = libusb_open(dev, &((*sdi)->usb->devhdl)))) {
192                 (*sdi)->usb->address = libusb_get_device_address(dev);
193                 (*sdi)->status = ST_ACTIVE;
194                 g_message("opened device %d on %d.%d interface %d",
195                           (*sdi)->index, (*sdi)->usb->bus,
196                           (*sdi)->usb->address, interface);
197         } else {
198                 g_warning("failed to open device: %d", err);
199                 *sdi = NULL;
200         }
201
202         return 0;
203 }
204
205 static int opendev3(struct sigrok_device_instance **sdi, libusb_device *dev,
206                     struct libusb_device_descriptor *des,
207                     uint16_t vid, uint16_t pid, int interface)
208 {
209         int err;
210
211         if ((err = libusb_get_device_descriptor(dev, des))) {
212                 g_warning("failed to get device descriptor: %d", err);
213                 return -1;
214         }
215
216         if (des->idVendor != vid || des->idProduct != pid)
217                 return 0;
218
219         if (libusb_get_bus_number(dev) == (*sdi)->usb->bus
220             && libusb_get_device_address(dev) == (*sdi)->usb->address) {
221                 /* Found it. */
222                 if (!(err = libusb_open(dev, &((*sdi)->usb->devhdl)))) {
223                         (*sdi)->status = ST_ACTIVE;
224                         g_message("opened device %d on %d.%d interface %d",
225                                   (*sdi)->index, (*sdi)->usb->bus,
226                                   (*sdi)->usb->address, interface);
227                 } else {
228                         g_warning("failed to open device: %d", err);
229                         *sdi = NULL;
230                 }
231         }
232
233         return 0;
234 }
235
236 struct sigrok_device_instance *sl_open_device(int device_index)
237 {
238         struct sigrok_device_instance *sdi;
239         libusb_device **devlist;
240         struct libusb_device_descriptor des;
241         int err, skip, i;
242
243         if (!(sdi = get_sigrok_device_instance(device_instances, device_index)))
244                 return NULL;
245
246         libusb_get_device_list(usb_context, &devlist);
247         if (sdi->status == ST_INITIALIZING) {
248                 /*
249                  * This device was renumerating last time we touched it.
250                  * opendev() guarantees we've waited long enough for it to
251                  * have booted properly, so now we need to find it on
252                  * the bus and record its new address.
253                  */
254                 skip = 0;
255                 for (i = 0; devlist[i]; i++) {
256                         /* TODO: Error handling. */
257                         err = opendev2(device_index, &sdi, devlist[i], &des,
258                                        &skip, USB_VENDOR, USB_PRODUCT,
259                                        USB_INTERFACE);
260                 }
261         } else if (sdi->status == ST_INACTIVE) {
262                 /*
263                  * This device is fully enumerated, so we need to find this
264                  * device by vendor, product, bus and address.
265                  */
266                 libusb_get_device_list(usb_context, &devlist);
267                 for (i = 0; devlist[i]; i++) {
268                         /* TODO: Error handling. */
269                         err = opendev3(&sdi, devlist[i], &des, USB_VENDOR,
270                                        USB_PRODUCT, USB_INTERFACE);
271                 }
272         } else {
273                 /* Status must be ST_ACTIVE, i.e. already in use... */
274                 sdi = NULL;
275         }
276         libusb_free_device_list(devlist, 1);
277
278         if (sdi && sdi->status != ST_ACTIVE)
279                 sdi = NULL;
280
281         return sdi;
282 }
283
284 int upload_firmware(libusb_device *dev)
285 {
286         int ret;
287
288         ret = ezusb_upload_firmware(dev, USB_CONFIGURATION, FIRMWARE);
289         if (ret != 0)
290                 return 1;
291
292         /* Remember when the last firmware update was done. */
293         g_get_current_time(&firmware_updated);
294
295         return 0;
296 }
297
298 static void close_device(struct sigrok_device_instance *sdi)
299 {
300         if (sdi->usb->devhdl == NULL)
301                 return;
302
303         g_message("closing device %d on %d.%d interface %d", sdi->index,
304                   sdi->usb->bus, sdi->usb->address, USB_INTERFACE);
305         libusb_release_interface(sdi->usb->devhdl, USB_INTERFACE);
306         libusb_close(sdi->usb->devhdl);
307         sdi->usb->devhdl = NULL;
308         sdi->status = ST_INACTIVE;
309 }
310
311 static int configure_probes(GSList *probes)
312 {
313         struct probe *probe;
314         GSList *l;
315         int probe_bit, stage, i;
316         char *tc;
317
318         probe_mask = 0;
319         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
320                 trigger_mask[i] = 0;
321                 trigger_value[i] = 0;
322         }
323
324         stage = -1;
325         for (l = probes; l; l = l->next) {
326                 probe = (struct probe *)l->data;
327                 if (probe->enabled == FALSE)
328                         continue;
329                 probe_bit = 1 << (probe->index - 1);
330                 probe_mask |= probe_bit;
331                 if (probe->trigger) {
332                         stage = 0;
333                         for (tc = probe->trigger; *tc; tc++) {
334                                 trigger_mask[stage] |= probe_bit;
335                                 if (*tc == '1')
336                                         trigger_value[stage] |= probe_bit;
337                                 stage++;
338                                 if (stage > NUM_TRIGGER_STAGES)
339                                         return SIGROK_ERR;
340                         }
341                 }
342         }
343
344         if (stage == -1)
345                 /*
346                  * We didn't configure any triggers, make sure acquisition
347                  * doesn't wait for any.
348                  */
349                 trigger_stage = TRIGGER_FIRED;
350         else
351                 trigger_stage = 0;
352
353         return SIGROK_OK;
354 }
355
356 /*
357  * API callbacks
358  */
359
360 static int hw_init(char *deviceinfo)
361 {
362         struct sigrok_device_instance *sdi;
363         struct libusb_device_descriptor des;
364         libusb_device **devlist;
365         int err, devcnt, i;
366
367         /* QUICK HACK */
368         deviceinfo = deviceinfo;
369
370         if (libusb_init(&usb_context) != 0) {
371                 g_warning("Failed to initialize USB.");
372                 return 0;
373         }
374         libusb_set_debug(usb_context, 3);
375
376         /* Find all Saleae Logic devices and upload firmware to all of them. */
377         devcnt = 0;
378         libusb_get_device_list(usb_context, &devlist);
379         for (i = 0; devlist[i]; i++) {
380                 err = libusb_get_device_descriptor(devlist[i], &des);
381                 if (err != 0) {
382                         g_warning("failed to get device descriptor: %d", err);
383                         continue;
384                 }
385
386                 if (des.idVendor != USB_VENDOR || des.idProduct != USB_PRODUCT)
387                         continue; /* Not a Saleae Logic... */
388
389                 sdi = sigrok_device_instance_new(devcnt, ST_INITIALIZING,
390                         USB_VENDOR_NAME, USB_MODEL_NAME, USB_MODEL_VERSION);
391                 if (!sdi)
392                         return 0;
393                 device_instances = g_slist_append(device_instances, sdi);
394
395                 if (check_conf_profile(devlist[i]) == 0) {
396                         /*
397                          * Continue on the off chance that the device is in a
398                          * working state. TODO: Could maybe try a USB reset,
399                          * or uploading the firmware again.
400                          */
401                         if (upload_firmware(devlist[i]) > 0)
402                                 g_warning("firmware upload failed for "
403                                           "device %d", devcnt);
404
405                         sdi->usb = usb_device_instance_new
406                                 (libusb_get_bus_number(devlist[i]), 0, NULL);
407                 } else {
408                         /* Already has the firmware, so fix the new address. */
409                         sdi->usb = usb_device_instance_new
410                             (libusb_get_bus_number(devlist[i]),
411                              libusb_get_device_address(devlist[i]), NULL);
412                 }
413                 devcnt++;
414         }
415         libusb_free_device_list(devlist, 1);
416
417         return devcnt;
418 }
419
420 static int hw_opendev(int device_index)
421 {
422         GTimeVal cur_time;
423         struct sigrok_device_instance *sdi;
424         int timediff, err;
425         unsigned int cur, upd;
426
427         if (firmware_updated.tv_sec > 0) {
428                 /* Firmware was recently uploaded. */
429                 g_get_current_time(&cur_time);
430                 cur = cur_time.tv_sec * 1000 + cur_time.tv_usec / 1000;
431                 upd = firmware_updated.tv_sec * 1000 +
432                       firmware_updated.tv_usec / 1000;
433                 timediff = cur - upd;
434                 if (timediff < FIRMWARE_RENUM_DELAY) {
435                         timediff = FIRMWARE_RENUM_DELAY - timediff;
436                         g_message("waiting %d ms for device to reset",
437                                   timediff);
438                         g_usleep(timediff * 1000);
439                         firmware_updated.tv_sec = 0;
440                 }
441         }
442
443         if (!(sdi = sl_open_device(device_index))) {
444                 g_warning("unable to open device");
445                 return SIGROK_ERR;
446         }
447
448         err = libusb_claim_interface(sdi->usb->devhdl, USB_INTERFACE);
449         if (err != 0) {
450                 g_warning("Unable to claim interface: %d", err);
451                 return SIGROK_ERR;
452         }
453
454         if (cur_samplerate == 0) {
455                 /* Samplerate hasn't been set; default to the slowest one. */
456                 if (hw_set_configuration(device_index, HWCAP_SAMPLERATE,
457                     &supported_samplerates[0]) == SIGROK_ERR)
458                         return SIGROK_ERR;
459         }
460
461         return SIGROK_OK;
462 }
463
464 static void hw_closedev(int device_index)
465 {
466         struct sigrok_device_instance *sdi;
467
468         if ((sdi = get_sigrok_device_instance(device_instances, device_index)))
469                 close_device(sdi);
470 }
471
472 static void hw_cleanup(void)
473 {
474         GSList *l;
475
476         /* Properly close all devices... */
477         for (l = device_instances; l; l = l->next)
478                 close_device((struct sigrok_device_instance *)l->data);
479
480         /* ...and free all their memory. */
481         for (l = device_instances; l; l = l->next)
482                 g_free(l->data);
483         g_slist_free(device_instances);
484         device_instances = NULL;
485
486         if (usb_context)
487                 libusb_exit(usb_context);
488         usb_context = NULL;
489 }
490
491 static void *hw_get_device_info(int device_index, int device_info_id)
492 {
493         struct sigrok_device_instance *sdi;
494         void *info = NULL;
495
496         if (!(sdi = get_sigrok_device_instance(device_instances, device_index)))
497                 return NULL;
498
499         switch (device_info_id) {
500         case DI_INSTANCE:
501                 info = sdi;
502                 break;
503         case DI_NUM_PROBES:
504                 info = GINT_TO_POINTER(NUM_PROBES);
505                 break;
506         case DI_SAMPLERATES:
507                 info = &samplerates;
508                 break;
509         case DI_TRIGGER_TYPES:
510                 info = TRIGGER_TYPES;
511                 break;
512         case DI_CUR_SAMPLERATE:
513                 info = &cur_samplerate;
514                 break;
515         }
516
517         return info;
518 }
519
520 static int hw_get_status(int device_index)
521 {
522         struct sigrok_device_instance *sdi;
523
524         sdi = get_sigrok_device_instance(device_instances, device_index);
525         if (sdi)
526                 return sdi->status;
527         else
528                 return ST_NOT_FOUND;
529 }
530
531 static int *hw_get_capabilities(void)
532 {
533         return capabilities;
534 }
535
536 static int set_configuration_samplerate(struct sigrok_device_instance *sdi,
537                                         uint64_t samplerate)
538 {
539         uint8_t divider;
540         int ret, result, i;
541         unsigned char buf[2];
542
543         for (i = 0; supported_samplerates[i]; i++) {
544                 if (supported_samplerates[i] == samplerate)
545                         break;
546         }
547         if (supported_samplerates[i] == 0)
548                 return SIGROK_ERR_SAMPLERATE;
549
550         divider = (uint8_t) (48 / (samplerate / 1000000.0)) - 1;
551
552         g_message("setting samplerate to %" PRIu64 " Hz (divider %d)",
553                   samplerate, divider);
554         buf[0] = 0x01;
555         buf[1] = divider;
556         ret = libusb_bulk_transfer(sdi->usb->devhdl, 1 | LIBUSB_ENDPOINT_OUT,
557                                    buf, 2, &result, 500);
558         if (ret != 0) {
559                 g_warning("failed to set samplerate: %d", ret);
560                 return SIGROK_ERR;
561         }
562         cur_samplerate = samplerate;
563
564         return SIGROK_OK;
565 }
566
567 static int hw_set_configuration(int device_index, int capability, void *value)
568 {
569         struct sigrok_device_instance *sdi;
570         int ret;
571         uint64_t *tmp_u64;
572
573         if (!(sdi = get_sigrok_device_instance(device_instances, device_index)))
574                 return SIGROK_ERR;
575
576         if (capability == HWCAP_SAMPLERATE) {
577                 tmp_u64 = value;
578                 ret = set_configuration_samplerate(sdi, *tmp_u64);
579         } else if (capability == HWCAP_PROBECONFIG) {
580                 ret = configure_probes((GSList *) value);
581         } else if (capability == HWCAP_LIMIT_SAMPLES) {
582                 limit_samples = strtoull(value, NULL, 10);
583                 ret = SIGROK_OK;
584         } else {
585                 ret = SIGROK_ERR;
586         }
587
588         return ret;
589 }
590
591 static int receive_data(int fd, int revents, void *user_data)
592 {
593         struct timeval tv;
594
595         /* QUICK HACK */
596         fd = fd;
597         revents = revents;
598         user_data = user_data;
599
600         tv.tv_sec = tv.tv_usec = 0;
601         libusb_handle_events_timeout(usb_context, &tv);
602
603         return TRUE;
604 }
605
606 static void trigger_helper(int i, unsigned char *cur_buf,
607                            struct datafeed_packet *packet, void *user_data,
608                            int *trigger_offset)
609 {
610         if ((cur_buf[i] & trigger_mask[trigger_stage])
611             == trigger_value[trigger_stage]) {
612                 /* Match on this trigger stage. */
613                 trigger_buffer[trigger_stage] = cur_buf[i];
614                 trigger_stage++;
615                 if (trigger_stage == NUM_TRIGGER_STAGES
616                     || trigger_mask[trigger_stage] == 0) {
617                         /* Match on all trigger stages, we're done. */
618                         *trigger_offset = i + 1;
619
620                         /*
621                          * TODO: Send pre-trigger buffer to session bus.
622                          * Tell the frontend we hit the trigger here.
623                          */
624                         packet->type = DF_TRIGGER;
625                         packet->length = 0;
626                         session_bus(user_data, packet);
627
628                         /*
629                          * Send the samples that triggered it, since we're
630                          * skipping past them.
631                          */
632                         packet->type = DF_LOGIC8;
633                         packet->length = trigger_stage;
634                         packet->payload = trigger_buffer;
635                         session_bus(user_data, packet);
636                         // break; // FIXME???
637
638                         trigger_stage = TRIGGER_FIRED;
639                 }
640                 return;
641         }
642
643         /*
644          * We had a match before, but not in the next sample. However, we may
645          * have a match on this stage in the next bit -- trigger on 0001 will
646          * fail on seeing 00001, so we need to go back to stage 0 -- but at
647          * the next sample from the one that matched originally, which the
648          * counter increment at the end of the loop takes care of.
649          */
650         if (trigger_stage > 0) {
651                 i -= trigger_stage;
652                 if (i < -1)
653                         i = -1; /* Oops, went back past this buffer. */
654                 /* Reset trigger stage. */
655                 trigger_stage = 0;
656         }
657 }
658
659 void receive_transfer(struct libusb_transfer *transfer)
660 {
661         static int num_samples = 0;
662         static int empty_transfer_count = 0;
663         struct datafeed_packet packet;
664         void *user_data;
665         int cur_buflen, trigger_offset, i;
666         unsigned char *cur_buf, *new_buf;
667
668         /* hw_stop_acquisition() is telling us to stop. */
669         if (transfer == NULL)
670                 num_samples = -1;
671
672         /*
673          * If acquisition has already ended, just free any queued up
674          * transfer that come in.
675          */
676         if (num_samples == -1) {
677                 if (transfer)
678                         libusb_free_transfer(transfer);
679                 return;
680         }
681
682         g_message("receive_transfer(): status %d received %d bytes",
683                   transfer->status, transfer->actual_length);
684
685         /* Save incoming transfer before reusing the transfer struct. */
686         cur_buf = transfer->buffer;
687         cur_buflen = transfer->actual_length;
688         user_data = transfer->user_data;
689
690         /* Fire off a new request. */
691         new_buf = g_malloc(4096);
692         transfer->buffer = new_buf;
693         transfer->length = 4096;
694         if (libusb_submit_transfer(transfer) != 0) {
695                 /* TODO: Stop session? */
696                 g_warning("eek");
697         }
698
699         if (cur_buflen == 0) {
700                 empty_transfer_count++;
701                 if (empty_transfer_count > MAX_EMPTY_TRANSFERS) {
702                         /*
703                          * The FX2 gave up. End the acquisition, the frontend
704                          * will work out that the samplecount is short.
705                          */
706                         hw_stop_acquisition(-1, user_data);
707                 }
708                 return;
709         } else {
710                 empty_transfer_count = 0;
711         }
712
713         trigger_offset = 0;
714         if (trigger_stage >= 0) {
715                 for (i = 0; i < cur_buflen; i++) {
716                         trigger_helper(i, cur_buf, &packet, user_data,
717                                        &trigger_offset);
718                 }
719         }
720
721         if (trigger_stage == TRIGGER_FIRED) {
722                 /* Send the incoming transfer to the session bus. */
723                 packet.type = DF_LOGIC8;
724                 packet.length = cur_buflen - trigger_offset;
725                 packet.payload = cur_buf + trigger_offset;
726                 session_bus(user_data, &packet);
727                 g_free(cur_buf);
728
729                 num_samples += cur_buflen;
730                 if ((unsigned int)num_samples > limit_samples) {
731                         hw_stop_acquisition(-1, user_data);
732                 }
733         } else {
734                 /*
735                  * TODO: Buffer pre-trigger data in capture
736                  * ratio-sized buffer.
737                  */
738         }
739 }
740
741 static int hw_start_acquisition(int device_index, gpointer session_device_id)
742 {
743         struct sigrok_device_instance *sdi;
744         struct datafeed_packet *packet;
745         struct datafeed_header *header;
746         struct libusb_transfer *transfer;
747         const struct libusb_pollfd **lupfd;
748         int size, i;
749         unsigned char *buf;
750
751         if (!(sdi = get_sigrok_device_instance(device_instances, device_index)))
752                 return SIGROK_ERR;
753
754         packet = g_malloc(sizeof(struct datafeed_packet));
755         header = g_malloc(sizeof(struct datafeed_header));
756         if (!packet || !header)
757                 return SIGROK_ERR;
758
759         /* Start with 2K transfer, subsequently increased to 4K. */
760         size = 2048;
761         for (i = 0; i < NUM_SIMUL_TRANSFERS; i++) {
762                 buf = g_malloc(size);
763                 transfer = libusb_alloc_transfer(0);
764                 libusb_fill_bulk_transfer(transfer, sdi->usb->devhdl,
765                                 2 | LIBUSB_ENDPOINT_IN, buf, size,
766                                 receive_transfer, session_device_id, 40);
767                 if (libusb_submit_transfer(transfer) != 0) {
768                         /* TODO: Free them all. */
769                         libusb_free_transfer(transfer);
770                         g_free(buf);
771                         return SIGROK_ERR;
772                 }
773                 size = 4096;
774         }
775
776         lupfd = libusb_get_pollfds(usb_context);
777         for (i = 0; lupfd[i]; i++)
778                 source_add(lupfd[i]->fd, lupfd[i]->events, 40, receive_data,
779                            NULL);
780         free(lupfd);
781
782         packet->type = DF_HEADER;
783         packet->length = sizeof(struct datafeed_header);
784         packet->payload = (unsigned char *)header;
785         header->feed_version = 1;
786         gettimeofday(&header->starttime, NULL);
787         header->samplerate = cur_samplerate;
788         header->protocol_id = PROTO_RAW;
789         header->num_probes = NUM_PROBES;
790         session_bus(session_device_id, packet);
791         g_free(header);
792         g_free(packet);
793
794         return SIGROK_OK;
795 }
796
797 /* This stops acquisition on ALL devices, ignoring device_index. */
798 static void hw_stop_acquisition(int device_index, gpointer session_device_id)
799 {
800         struct datafeed_packet packet;
801
802         /* QUICK HACK */
803         device_index = device_index;
804
805         packet.type = DF_END;
806         session_bus(session_device_id, &packet);
807
808         receive_transfer(NULL);
809
810         /* TODO: Need to cancel and free any queued up transfers. */
811 }
812
813 struct device_plugin saleae_logic_plugin_info = {
814         "saleae-logic",
815         1,
816         hw_init,
817         hw_cleanup,
818
819         hw_opendev,
820         hw_closedev,
821         hw_get_device_info,
822         hw_get_status,
823         hw_get_capabilities,
824         hw_set_configuration,
825         hw_start_acquisition,
826         hw_stop_acquisition,
827 };