]> sigrok.org Git - libsigrok.git/blame - src/hardware/greatfet/protocol.c
greatfet: don't print misleading "unknown" libusb error text
[libsigrok.git] / src / hardware / greatfet / protocol.c
CommitLineData
f594b3b0
GS
1/*
2 * This file is part of the libsigrok project.
3 *
208fcedc
GS
4 * Copyright (C) 2019 Katherine J. Temkin <k@ktemkin.com>
5 * Copyright (C) 2019 Mikaela Szekely <qyriad@gmail.com>
f594b3b0
GS
6 * Copyright (C) 2023 Gerhard Sittig <gerhard.sittig@gmx.net>
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
208fcedc
GS
22#include "config.h"
23
24#include <stdio.h>
25#include <string.h>
26
f594b3b0
GS
27#include "protocol.h"
28
208fcedc
GS
29/*
30 * Communicate to GreatFET firmware, especially its Logic Analyzer mode.
31 *
32 * Firmware communication is done by two means: Control transfers to
33 * EP0 for command execution. Bulk transfer from EP1 for sample data.
34 * The sample data endpoint number is also provided by firmware in
35 * responses to LA configuration requests.
36 *
37 * Control transfers have a fixed layout: 2x u32 class and verb numbers,
38 * and u8[] payload data up to 512 bytes length. Payload layout depends
39 * on commands and the verb's parameters. Binary data is represented in
40 * LE format (firmware executes on Cortex-M). Strings are limited to a
41 * maximum of 128 bytes.
42 *
43 * The set of commands used by this sigrok driver is minimal:
44 * - Get the GreatFET's firmware version and serial number.
45 * - String queries, a core verb, individual verb codes for the
46 * version and for the serial number.
47 * - Configure Logic Analyzer mode, start and stop captures.
48 * - Configure takes a u32 samplerate and u8 channel count. Yields
49 * u32 samplerate, u32 buffer size, u8 endpoint number.
50 * - Start takes a u32 samplerate (does it? depending on firmware
51 * version?). Empty/no response.
52 * - Stop has empty/no request and response payloads.
53 *
54 * Firmware implementation details, observed during sigrok driver
55 * creation.
56 * - Serial number "strings" in responses may carry binary data and
57 * not a text presentation of the serial number. It's uncertain
58 * whether that is by design or an oversight. This sigrok driver
59 * copes when it happens. (Remainder from another request which
60 * provided the part number as well?)
61 * - The GreatFET firmware is designed for exploration by host apps.
62 * The embedded classes, their methods, their in/out parameters,
63 * including builtin help texts, can get enumerated. This driver
64 * does not use this discovery approach, assumes a given protocol.
65 * - The NXP LPC4330 chip has 16 SGPIO pins. It's assumed that the
66 * GreatFET firmware currently does not support more than 8 logic
67 * channels due to constraints on bitbang machinery synchronization
68 * which is under construction (IIUC, it's about pin banks that
69 * run independently). When firmware versions get identified which
70 * transparently (from the host's perspective) support more than
71 * 8 channels, this host driver may need a little adjustment.
72 * - The device can sample and stream 8 channels to the host at a
73 * continuous rate of 40.8MHz. Higher rates are possible assuming
74 * that fewer pins get sampled. The firmware then provides sample
75 * memory where data taken at several sample points reside in the
76 * same byte of sample memory. It helps that power-of-two bitness
77 * is applied, IOW that there are either 1, 2, 4, or 8 bits per
78 * sample point. Even when say 3 or 5 channels are enabled. The
79 * device firmware may assume that a "dense" list of channels gets
80 * enabled, the sigrok driver supports when some disabled channels
81 * preceed other enabled channels. The device is then asked to get
82 * as many channels as are needed to cover all enabled channels,
83 * including potentially disabled channels before them.
84 * - The LA configure request returns a samplerate that is supported
85 * by the hardware/firmware combination and will be used during
86 * acquisition. This returned rate is at least as high as the
87 * requested samplerate. But might exceed the USB bandwidth which
88 * the firmware is capable to sustain. Users may not expect that
89 * since numbers add up differently from their perspective. In the
90 * example of 3 enabled channels and a requested 72MHz samplerate,
91 * the firmware will derive that it needs to sample 4 channels at
92 * a 102MHz rate. Which exceeds its capabilities while users may
93 * not be aware of these constraints. This sigrok driver attempts
94 * to detect the condition, and not start an acquisition. And also
95 * emits diagnostics (at info level which is silent by default).
96 * It's assumed that users increase verbosity when diagnosing
97 * issues they may experience.
98 */
99
100/*
101 * Assign a symbolic name to endpoint 0 which is used for USB control
102 * transfers. Although those "or 0" phrases don't take effect from the
103 * compiler's perspective, they hopefully increase readability of the
104 * USB related incantations.
105 *
106 * Endpoint 1 for sample data reception is not declared here. Its value
107 * is taken from logic analyzer configure response. Which remains more
108 * portable across firmware versions and supported device models.
109 */
110#define CONTROL_ENDPOINT 0
111
112/* Header fields for USB control requests. */
113#define LIBGREAT_REQUEST_NUMBER 0x65
114#define LIBGREAT_VALUE_EXECUTE 0
115#define LIBGREAT_FLAG_SKIP_RSP (1UL << 0)
116
117/* Classes and their verbs for core and logic analyzer. */
118#define GREATFET_CLASS_CORE 0x000
119#define CORE_VERB_READ_VERSION 0x1
120#define CORE_VERB_READ_SERIAL 0x3
121
122#define GREATFET_CLASS_LA 0x10d
123#define LA_VERB_CONFIGURE 0x0
124#define LA_VERB_START_CAPTURE 0x3
125#define LA_VERB_STOP_CAPTURE 0x4
126
127/* Maximum text string and binary payload sizes for control requests. */
128#define CORE_MAX_STRING_LENGTH 128
129#define LOGIC_MAX_PAYLOAD_DATA 512
130
131/* USB communication parameters, pool dimensions. */
132#define LOGIC_DEFAULT_TIMEOUT 1000
133#define TRANSFER_POOL_SIZE 16
134#define TRANSFER_BUFFER_SIZE (256 * 1024)
135
136static int greatfet_process_receive_data(const struct sr_dev_inst *sdi,
137 const uint8_t *data, size_t dlen);
138static int greatfet_cancel_transfers(const struct sr_dev_inst *sdi);
139
140/* Communicate a GreatFET request to EP0, and get its response. */
141static int greatfet_ctrl_out_in(const struct sr_dev_inst *sdi,
142 const uint8_t *tx_data, size_t tx_size,
143 uint8_t *rx_data, size_t rx_size, unsigned int timeout_ms)
144{
145 struct sr_usb_dev_inst *usb;
146 uint16_t flags;
147 int ret;
148 size_t sent, rcvd;
149
150 usb = sdi->conn;
151 if (!usb)
152 return SR_ERR_ARG;
153
154 /* Caller can request to skip transmission of a response. */
155 flags = 0;
156 if (!rx_size)
157 flags |= LIBGREAT_FLAG_SKIP_RSP;
158
159 /* Send USB Control OUT request. */
160 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
161 GString *dump = sr_hexdump_new(tx_data, tx_size);
162 sr_spew("USB out data: %s", dump->str);
163 sr_hexdump_free(dump);
164 }
165 ret = libusb_control_transfer(usb->devhdl,
166 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_ENDPOINT |
167 LIBUSB_ENDPOINT_OUT | CONTROL_ENDPOINT,
168 LIBGREAT_REQUEST_NUMBER, LIBGREAT_VALUE_EXECUTE,
169 flags, (void *)tx_data, tx_size, timeout_ms);
170 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
171 const char *msg;
2c3fadf5 172 msg = ret < 0 ? libusb_error_name(ret) : "-";
208fcedc
GS
173 sr_spew("USB out, rc %d, %s", ret, msg);
174 }
175 if (ret < 0) {
176 /* Rate limit error messages. Skip "please retry" kinds. */
177 if (ret != LIBUSB_ERROR_BUSY) {
178 sr_err("USB out transfer failed: %s (%d)",
179 libusb_error_name(ret), ret);
180 }
181 return SR_ERR_IO;
182 }
183 sent = (size_t)ret;
184 if (sent != tx_size) {
185 sr_err("Short USB write: want %zu, got %zu: %s.",
186 tx_size, sent, libusb_error_name(ret));
187 return SR_ERR_IO;
188 }
189
190 /* Get the USB Control IN response. */
191 if (!rx_size)
192 return SR_OK;
193 ret = libusb_control_transfer(usb->devhdl,
194 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_ENDPOINT |
195 LIBUSB_ENDPOINT_IN | CONTROL_ENDPOINT,
196 LIBGREAT_REQUEST_NUMBER, LIBGREAT_VALUE_EXECUTE,
197 0, rx_data, rx_size, timeout_ms);
198 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
199 const char *msg;
2c3fadf5 200 msg = ret < 0 ? libusb_error_name(ret) : "-";
208fcedc
GS
201 sr_spew("USB in, rc %d, %s", ret, msg);
202 }
203 if (ret < 0) {
204 sr_err("USB in transfer failed: %s (%d)",
205 libusb_error_name(ret), ret);
206 return SR_ERR_IO;
207 }
208 rcvd = (size_t)ret;
209 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
210 GString *dump = sr_hexdump_new(rx_data, rcvd);
211 sr_spew("USB in data: %s", dump->str);
212 sr_hexdump_free(dump);
213 }
214 /* Short read, including zero length, is not fatal. */
215
216 return rcvd;
217}
218
219/*
220 * Use a string buffer in devc for USB transfers. This simplifies
221 * resource management in error paths.
222 */
223static int greatfet_prep_usb_buffer(const struct sr_dev_inst *sdi,
224 uint8_t **tx_buff, size_t *tx_size, uint8_t **rx_buff, size_t *rx_size)
225{
226 struct dev_context *devc;
227 size_t want_len;
228 GString *s;
229
230 if (tx_buff)
231 *tx_buff = NULL;
232 if (tx_size)
233 *tx_size = 0;
234 if (rx_buff)
235 *rx_buff = NULL;
236 if (rx_size)
237 *rx_size = 0;
238
239 if (!sdi)
240 return SR_ERR_ARG;
241 devc = sdi->priv;
242 if (!devc)
243 return SR_ERR_ARG;
244
245 /*
246 * Allocate the string buffer unless previously done.
247 * Ensure sufficient allocated space for request/response use.
248 * Assume that glib GString is suitable to hold uint8_t[] data.
249 */
250 if (!devc->usb_comm_buffer) {
251 want_len = 2 * sizeof(uint32_t) + LOGIC_MAX_PAYLOAD_DATA;
252 devc->usb_comm_buffer = g_string_sized_new(want_len);
253 if (!devc->usb_comm_buffer)
254 return SR_ERR_MALLOC;
255 }
256
257 /* Pass buffer start and size to the caller if requested. */
258 s = devc->usb_comm_buffer;
259 if (tx_buff)
260 *tx_buff = (uint8_t *)s->str;
261 if (tx_size)
262 *tx_size = s->allocated_len;
263 if (rx_buff)
264 *rx_buff = (uint8_t *)s->str;
265 if (rx_size)
266 *rx_size = s->allocated_len;
267
268 return SR_OK;
269}
270
271/* Retrieve a string by executing a core service. */
272static int greatfet_get_string(const struct sr_dev_inst *sdi,
273 uint32_t verb, char **value)
274{
275 uint8_t *req, *rsp;
276 size_t rsp_size;
277 uint8_t *wrptr;
278 size_t wrlen, rcvd;
279 const char *text;
280 int ret;
281
282 if (value)
283 *value = NULL;
284 if (!sdi)
285 return SR_ERR_ARG;
286 ret = greatfet_prep_usb_buffer(sdi, &req, NULL, &rsp, &rsp_size);
287 if (ret != SR_OK)
288 return ret;
289
290 wrptr = req;
291 write_u32le_inc(&wrptr, GREATFET_CLASS_CORE);
292 write_u32le_inc(&wrptr, verb);
293 wrlen = wrptr - req;
294 ret = greatfet_ctrl_out_in(sdi, req, wrlen,
295 rsp, rsp_size, LOGIC_DEFAULT_TIMEOUT);
296 if (ret < 0) {
297 sr_err("Cannot get core string.");
298 return ret;
299 }
300 rcvd = (size_t)ret;
301
302 rsp[rcvd] = '\0';
303 text = (const char *)rsp;
304 sr_dbg("got string, verb %u, text (%zu) %s", verb, rcvd, text);
305 if (value && *text) {
306 *value = g_strndup(text, rcvd);
307 } else if (value) {
308 /*
309 * g_strndup(3) does _not_ copy 'n' bytes. Instead it
310 * truncates the result at the first NUL character seen.
311 * That's why we need extra logic to pass binary data
312 * to callers, to not violate API layers and confuse
313 * USB readers with firmware implementation details
314 * (that may be version dependent).
315 * The very condition to determine whether text or some
316 * binary data was received is a simple check for NUL
317 * in the first position, implemented above. This is
318 * GoodEnough(TM) to handle the firmware version case.
319 */
320 *value = g_malloc0(rcvd + 1);
321 memcpy(*value, text, rcvd);
322 }
323
324 return rcvd;
325}
326
327SR_PRIV int greatfet_get_serial_number(const struct sr_dev_inst *sdi)
328{
329 struct dev_context *devc;
330 char *text;
331 int ret;
332 const uint8_t *rdptr;
333 size_t rdlen;
334 GString *snr;
335 uint32_t chunk;
336
337 if (!sdi)
338 return SR_ERR_ARG;
339 devc = sdi->priv;
340 if (!devc)
341 return SR_ERR_ARG;
342
343 ret = greatfet_get_string(sdi, CORE_VERB_READ_SERIAL, &text);
344 if (ret < 0)
345 return ret;
346 if (!text)
347 return SR_ERR_DATA;
348
349 /*
350 * The simple case, we got a text string. The 2019 K.Temkin
351 * implementation took the received string as is. So there
352 * are firmware versions which provide this presentation.
353 */
354 if (*text) {
355 devc->serial_number = text;
356 return SR_OK;
357 }
358
359 /*
360 * The complex case. The received "string" looks binary. Local
361 * setups with v2018.12.1 and v2021.2.1 firmware versions yield
362 * response data that does not look like a text string. Instead
363 * it looks like four u32 fields which carry a binary value and
364 * leading padding. Try that interpreation as well. Construct a
365 * twenty character text presentation from that binary content.
366 *
367 * Implementation detail: Is the "leader" the part number which
368 * a different firmware request may yield? Are there other verbs
369 * which reliably yield the serial number in text format?
370 */
371 rdptr = (const uint8_t *)text;
372 rdlen = (size_t)ret;
373 sr_dbg("trying to read serial nr \"text\" as binary");
374 if (rdlen != 4 * sizeof(uint32_t)) {
375 g_free(text);
376 return SR_ERR_DATA;
377 }
378 snr = g_string_sized_new(20 + 1);
379 chunk = read_u32le_inc(&rdptr);
380 if (chunk) {
381 g_free(text);
382 return SR_ERR_DATA;
383 }
384 chunk = read_u32le_inc(&rdptr);
385 if (chunk) {
386 g_free(text);
387 return SR_ERR_DATA;
388 }
389 g_string_append_printf(snr, "%04" PRIx32, chunk);
390 chunk = read_u32le_inc(&rdptr);
391 g_string_append_printf(snr, "%08" PRIx32, chunk);
392 chunk = read_u32le_inc(&rdptr);
393 g_string_append_printf(snr, "%08" PRIx32, chunk);
394 sr_dbg("got serial number text %s", snr->str);
395 g_free(text);
396 text = g_string_free(snr, FALSE);
397 devc->serial_number = text;
398 return SR_OK;
399}
400
401SR_PRIV int greatfet_get_version_number(const struct sr_dev_inst *sdi)
402{
403 struct dev_context *devc;
404 char *text;
405 int ret;
406
407 if (!sdi)
408 return SR_ERR_ARG;
409 devc = sdi->priv;
410 if (!devc)
411 return SR_ERR_ARG;
412
413 ret = greatfet_get_string(sdi, CORE_VERB_READ_VERSION, &text);
414 if (ret < SR_OK)
415 return ret;
416
417 devc->firmware_version = text;
418 return SR_OK;
419}
420
421/*
422 * Transmit a parameter-less request that wants no response. Or a
423 * request with just a few bytes worth of parameter values, still
424 * not expecting a response.
425 */
426static int greatfet_trivial_request(const struct sr_dev_inst *sdi,
427 uint32_t cls, uint32_t verb, const uint8_t *tx_data, size_t tx_dlen)
428{
429 struct dev_context *devc;
430 uint8_t *req;
431 uint8_t *wrptr;
432 size_t wrlen;
433 int ret;
434
435 if (!sdi)
436 return SR_ERR_ARG;
437 devc = sdi->priv;
438 if (!devc)
439 return SR_ERR_ARG;
440
441 ret = greatfet_prep_usb_buffer(sdi, &req, NULL, NULL, NULL);
442 if (ret != SR_OK)
443 return ret;
444
445 wrptr = req;
446 write_u32le_inc(&wrptr, cls);
447 write_u32le_inc(&wrptr, verb);
448 while (tx_dlen--)
449 write_u8_inc(&wrptr, *tx_data++);
450 wrlen = wrptr - req;
451 return greatfet_ctrl_out_in(sdi, req, wrlen,
452 NULL, 0, LOGIC_DEFAULT_TIMEOUT);
453}
454
455/*
456 * Transmit a "configure logic analyzer" request. Gets the resulting
457 * samplerate (which can differ from requested values) and endpoint
458 * (which is very useful for compatibility across devices/versions).
459 * Also gets the device firmware's buffer size, which is only used
460 * for information, while the host assumes a fixed larger buffer size
461 * for its own purposes.
462 */
463static int greatfet_logic_config(const struct sr_dev_inst *sdi)
464{
465 struct dev_context *devc;
466 struct dev_acquisition_t *acq;
467 struct sr_usb_dev_inst *usb;
468 uint8_t *req, *rsp;
469 size_t rsp_size;
470 uint8_t *wrptr;
471 size_t wrlen, rcvd, want_len;
472 const uint8_t *rdptr;
473 uint64_t rate, bw;
474 size_t bufsize;
475 uint8_t ep;
476 char *print_bw;
477 int ret;
478
479 if (!sdi)
480 return SR_ERR_ARG;
481 devc = sdi->priv;
482 usb = sdi->conn;
483 if (!devc || !usb)
484 return SR_ERR_ARG;
485 acq = &devc->acquisition;
486
487 ret = greatfet_prep_usb_buffer(sdi, &req, NULL, &rsp, &rsp_size);
488 if (ret != SR_OK)
489 return ret;
490
491 /*
492 * Prepare to get a specific amount of receive data. The logic
493 * analyzer configure response is strictly binary, in contrast
494 * to variable length string responses elsewhere.
495 */
496 want_len = 2 * sizeof(uint32_t) + sizeof(uint8_t);
497 if (rsp_size < want_len)
498 return SR_ERR_BUG;
499 rsp_size = want_len;
500
501 sr_dbg("about to config LA, rate %" PRIu64 ", chans %zu",
502 devc->samplerate, acq->capture_channels);
503 wrptr = req;
504 write_u32le_inc(&wrptr, GREATFET_CLASS_LA);
505 write_u32le_inc(&wrptr, LA_VERB_CONFIGURE);
506 write_u32le_inc(&wrptr, devc->samplerate);
507 write_u8_inc(&wrptr, acq->capture_channels);
508 wrlen = wrptr - req;
509 ret = greatfet_ctrl_out_in(sdi, req, wrlen,
510 rsp, rsp_size, LOGIC_DEFAULT_TIMEOUT);
511 if (ret < 0) {
512 sr_err("Cannot configure logic analyzer mode.");
513 return ret;
514 }
515 rcvd = (size_t)ret;
516 if (rcvd != want_len) {
517 sr_warn("Unexpected LA configuration response length.");
518 return SR_ERR_DATA;
519 }
520
521 rdptr = rsp;
522 rate = read_u32le_inc(&rdptr);
523 bufsize = read_u32le_inc(&rdptr);
524 ep = read_u8_inc(&rdptr);
525 sr_dbg("LA configured, rate %" PRIu64 ", buf %zu, ep %" PRIu8,
526 rate, bufsize, ep);
527 if (rate != devc->samplerate) {
528 sr_info("Configuration feedback, want rate %" PRIu64 ", got rate %." PRIu64,
529 devc->samplerate, rate);
530 devc->samplerate = rate;
531 }
532 acq->capture_samplerate = rate;
533 acq->firmware_bufsize = bufsize;
534 acq->samples_endpoint = ep;
535
536 /*
537 * The firmware does not reject requests that would exceed
538 * its capabilities. Yet the device becomes unaccessible when
539 * START is sent in that situation. (Observed with v2021.2.1
540 * firmware.)
541 *
542 * Assume a maximum USB bandwidth that we don't want to exceed.
543 * It's protecting the GreatFET's firmware. It's not a statement
544 * on the host's capability of keeping up with the GreatFET's
545 * firmware capabilities. :)
546 */
547 print_bw = sr_samplerate_string(acq->capture_samplerate);
548 sr_info("Capture configuration: %zu channels, samplerate %s.",
549 acq->capture_channels, print_bw);
550 g_free(print_bw);
551 bw = acq->capture_samplerate * 8 / acq->points_per_byte;
552 print_bw = sr_si_string_u64(bw, "bps");
553 sr_info("Resulting USB bandwidth: %s.", print_bw);
554 g_free(print_bw);
555 if (acq->bandwidth_threshold && bw > acq->bandwidth_threshold) {
556 sr_err("Configuration exceeds bandwidth limit. Aborting.");
557 return SR_ERR_SAMPLERATE;
558 }
559
560 return SR_OK;
561}
562
563/* Transmit "start logic capture" request. */
564static int greatfet_logic_start(const struct sr_dev_inst *sdi)
565{
566 int ret;
567
568 ret = greatfet_trivial_request(sdi,
569 GREATFET_CLASS_LA, LA_VERB_START_CAPTURE, NULL, 0);
570 sr_dbg("LA start, USB out, rc %d", ret);
571 if (ret != SR_OK)
572 sr_err("Cannot start logic analyzer capture.");
573
574 return ret;
575}
576
577/* Transmit "stop logic capture" request. */
578static int greatfet_logic_stop(const struct sr_dev_inst *sdi)
579{
580 struct dev_context *devc;
581 struct dev_acquisition_t *acq;
582 int ret;
583
584 devc = sdi->priv;
585 if (!devc)
586 return SR_ERR_ARG;
587 acq = &devc->acquisition;
588
589 /* Only send STOP when START was sent before. */
590 if (!acq->start_req_sent)
591 return SR_OK;
592
593 ret = greatfet_trivial_request(sdi,
594 GREATFET_CLASS_LA, LA_VERB_STOP_CAPTURE, NULL, 0);
595 sr_dbg("LA stop, USB out, rc %d", ret);
596 if (ret == SR_OK)
597 acq->start_req_sent = FALSE;
598 else
599 sr_warn("Cannot stop logic analyzer capture in the device.");
600
601 return ret;
602}
603
604/*
605 * Determine how many channels the device firmware needs to sample.
606 * So that resulting capture data will cover all those logic channels
607 * which currently are enabled on the sigrok side. We (have to) accept
608 * when the sequence of enabled channels "has gaps" in them. Disabling
609 * channels in the middle of the pin groups is a user's choice that we
610 * need to obey. The count of enabled channels is not good enough for
611 * the purpose of acquisition, it must be "a maximum index" or a total
612 * to-get-sampled count.
613 */
614static int greatfet_calc_capture_chans(const struct sr_dev_inst *sdi)
615{
616 struct dev_context *devc;
617 struct dev_acquisition_t *acq;
618 GSList *l;
619 struct sr_channel *ch;
620 int last_used_idx;
621 size_t logic_ch_count, en_ch_count, fw_ch_count;
622 int ret;
623
624 if (!sdi)
625 return SR_ERR_ARG;
626 devc = sdi->priv;
627 if (!devc)
628 return SR_ERR_ARG;
629 acq = &devc->acquisition;
630
631 last_used_idx = -1;
632 logic_ch_count = 0;
633 for (l = sdi->channels; l; l = l->next) {
634 ch = l->data;
635 if (ch->type != SR_CHANNEL_LOGIC)
636 continue;
637 logic_ch_count++;
638 if (!ch->enabled)
639 continue;
640 if (last_used_idx < ch->index)
641 last_used_idx = ch->index;
642 }
643 en_ch_count = last_used_idx + 1;
644 sr_dbg("channel count, logic %zu, highest enabled idx %d -> count %zu",
645 logic_ch_count, last_used_idx, en_ch_count);
646 if (!en_ch_count)
647 return SR_ERR_ARG;
648
649 acq->capture_channels = en_ch_count;
650 ret = sr_next_power_of_two(last_used_idx, NULL, &fw_ch_count);
651 if (ret != SR_OK)
652 return ret;
653 if (!fw_ch_count)
654 return SR_ERR_ARG;
655 if (fw_ch_count > 8) {
656 acq->unit_size = sizeof(uint16_t);
657 acq->points_per_byte = 1;
658 } else {
659 acq->unit_size = sizeof(uint8_t);
660 acq->points_per_byte = 8 / fw_ch_count;
661 }
662 acq->channel_shift = fw_ch_count % 8;
663 sr_dbg("unit %zu, dense %d -> shift %zu, points %zu",
664 acq->unit_size, !!acq->channel_shift,
665 acq->channel_shift, acq->points_per_byte);
666
667 return SR_OK;
668}
669
670/*
671 * This is an opportunity to adapt the host's USB transfer size to
672 * the value which the device firmware has provided in the LA config
673 * response.
674 *
675 * We let the opportunity pass. Always use a fixed value for the host
676 * configuration. BULK transfers will adopt, which reduces the number
677 * of transfer completion events for the host.
678 *
679 * Notice that transfer size adjustment is _not_ a means to get user
680 * feedback earlier at low samplerates. This may be done in other
681 * drivers but does not take effect here. Because a buffer is used to
682 * submit sample values to the session. When in doubt, the feed queue
683 * needs flushing.
684 *
685 * TODO Consider whether sample data needs flushing when sample rates
686 * are low and buffers are deep. Ideally use common feed queue support
687 * if that becomes available in the future. Translate low samplerates
688 * (and channel counts) to the amount of samples after which the queue
689 * should get flushed.
690 *
691 * This implementation assumes that samplerates start at 1MHz, and
692 * flushing is not necessary.
693 */
694static int greatfet_calc_submit_size(const struct sr_dev_inst *sdi)
695{
696 struct dev_context *devc;
697 struct dev_transfers_t *dxfer;
698
699 if (!sdi)
700 return SR_ERR_ARG;
701 devc = sdi->priv;
702 if (!devc)
703 return SR_ERR_ARG;
704 dxfer = &devc->transfers;
705
706 dxfer->capture_bufsize = dxfer->transfer_bufsize;
707 return SR_OK;
708}
709
710/*
711 * This routine is local to protocol.c and does mere data manipulation
712 * and a single attempt at sending "logic analyzer stop" to the device.
713 * This routine gets invoked from USB transfer completion callbacks as
714 * well as periodic timer or data availability callbacks. It is essential
715 * to not spend extended periods of time here.
716 */
717static void greatfet_abort_acquisition_quick(const struct sr_dev_inst *sdi)
718{
719 struct dev_context *devc;
720 struct dev_acquisition_t *acq;
721
722 if (!sdi)
723 return;
724 devc = sdi->priv;
725 if (!devc)
726 return;
727 acq = &devc->acquisition;
728
729 if (acq->acquisition_state == ACQ_RECEIVE)
730 acq->acquisition_state = ACQ_SHUTDOWN;
731
732 (void)greatfet_logic_stop(sdi);
733 greatfet_cancel_transfers(sdi);
734
735 feed_queue_logic_flush(acq->feed_queue);
736}
737
738/* Allocate USB transfers and associated receive buffers. */
739static int greatfet_allocate_transfers(const struct sr_dev_inst *sdi)
740{
741 struct dev_context *devc;
742 struct dev_transfers_t *dxfer;
743 size_t alloc_size, idx;
744 struct libusb_transfer *xfer;
745
746 if (!sdi)
747 return SR_ERR_ARG;
748 devc = sdi->priv;
749 if (!devc)
750 return SR_ERR_ARG;
751 dxfer = &devc->transfers;
752
753 dxfer->transfer_bufsize = TRANSFER_BUFFER_SIZE;
754 dxfer->transfers_count = TRANSFER_POOL_SIZE;
755
756 alloc_size = dxfer->transfers_count * dxfer->transfer_bufsize;
757 dxfer->transfer_buffer = g_malloc0(alloc_size);
758 if (!dxfer->transfer_buffer)
759 return SR_ERR_MALLOC;
760
761 alloc_size = dxfer->transfers_count;
762 alloc_size *= sizeof(dxfer->transfers[0]);
763 dxfer->transfers = g_malloc0(alloc_size);
764 if (!dxfer->transfers)
765 return SR_ERR_MALLOC;
766
767 for (idx = 0; idx < dxfer->transfers_count; idx++) {
768 xfer = libusb_alloc_transfer(0);
769 if (!xfer)
770 return SR_ERR_MALLOC;
771 dxfer->transfers[idx] = xfer;
772 }
773
774 return SR_OK;
775}
776
777/* Submit USB transfers for reception, registers the data callback. */
778static int greatfet_prepare_transfers(const struct sr_dev_inst *sdi,
779 libusb_transfer_cb_fn callback)
780{
781 struct dev_context *devc;
782 struct dev_acquisition_t *acq;
783 struct dev_transfers_t *dxfer;
784 struct sr_usb_dev_inst *conn;
785 uint8_t ep;
786 size_t submit_length;
787 size_t off, idx;
788 struct libusb_transfer *xfer;
789 int ret;
790
791 if (!sdi)
792 return SR_ERR_ARG;
793 devc = sdi->priv;
794 conn = sdi->conn;
795 if (!devc || !conn)
796 return SR_ERR_ARG;
797 acq = &devc->acquisition;
798 dxfer = &devc->transfers;
799
800 ep = acq->samples_endpoint;
801 ret = greatfet_calc_submit_size(sdi);
802 if (ret != SR_OK)
803 return ret;
804 submit_length = dxfer->capture_bufsize;
805 if (submit_length > dxfer->transfer_bufsize)
806 submit_length = dxfer->transfer_bufsize;
807 sr_dbg("prep xfer, ep %u (%u), len %zu",
808 ep, ep & ~LIBUSB_ENDPOINT_IN, submit_length);
809
810 dxfer->active_transfers = 0;
811 off = 0;
812 for (idx = 0; idx < dxfer->transfers_count; idx++) {
813 xfer = dxfer->transfers[idx];
814 libusb_fill_bulk_transfer(xfer, conn->devhdl, ep,
815 &dxfer->transfer_buffer[off], submit_length,
816 callback, (void *)sdi, 0);
817 if (!xfer->buffer)
818 return SR_ERR_MALLOC;
819 ret = libusb_submit_transfer(xfer);
820 if (ret != 0) {
821 sr_spew("submit bulk xfer failed, idx %zu, %d: %s",
822 idx, ret, libusb_error_name(ret));
823 return SR_ERR_IO;
824 }
825 dxfer->active_transfers++;
826 off += submit_length;
827 }
828
829 return SR_OK;
830}
831
832/*
833 * Initiate the termination of an acquisition. Cancel all USB transfers.
834 * Their completion will drive further progress including resource
835 * release.
836 */
837static int greatfet_cancel_transfers(const struct sr_dev_inst *sdi)
838{
839 struct dev_context *devc;
840 struct dev_transfers_t *dxfer;
841 size_t idx;
842 struct libusb_transfer *xfer;
843
844 if (!sdi)
845 return SR_ERR_ARG;
846 devc = sdi->priv;
847 if (!devc)
848 return SR_ERR_ARG;
849 dxfer = &devc->transfers;
850
851 for (idx = 0; idx < dxfer->transfers_count; idx++) {
852 xfer = dxfer->transfers[idx];
853 if (!xfer)
854 continue;
855 (void)libusb_cancel_transfer(xfer);
856 /*
857 * Cancelled transfers will cause acquisitions to abort
858 * in their callback. Keep the "active" count as is.
859 */
860 }
861
862 return SR_OK;
863}
864
865/*
866 * Free an individual transfer during its callback's execution.
867 * Releasing the last USB transfer also happens to drive more of
868 * the shutdown path.
869 */
870static void greatfet_free_transfer(const struct sr_dev_inst *sdi,
871 struct libusb_transfer *xfer)
872{
873 struct drv_context *drvc;
874 struct sr_usb_dev_inst *usb;
875 struct dev_context *devc;
876 struct dev_acquisition_t *acq;
877 struct dev_transfers_t *dxfer;
878 size_t idx;
879
880 if (!sdi || !sdi->driver)
881 return;
882 drvc = sdi->driver->context;
883 usb = sdi->conn;
884 devc = sdi->priv;
885 if (!drvc || !usb || !devc)
886 return;
887 acq = &devc->acquisition;
888 dxfer = &devc->transfers;
889
890 /* Void the transfer in the driver's list of transfers. */
891 for (idx = 0; idx < dxfer->transfers_count; idx++) {
892 if (xfer != dxfer->transfers[idx])
893 continue;
894 dxfer->transfers[idx] = NULL;
895 dxfer->active_transfers--;
896 break;
897 }
898
899 /* Release the transfer from libusb use. */
900 libusb_free_transfer(xfer);
901
902 /* Done here when more transfers are still pending. */
903 if (!dxfer->active_transfers)
904 return;
905
906 /*
907 * The last USB transfer has been freed after completion.
908 * Post process the previous acquisition's execution.
909 */
910 (void)greatfet_stop_acquisition(sdi);
911 if (acq->frame_begin_sent) {
912 std_session_send_df_end(sdi);
913 acq->frame_begin_sent = FALSE;
914 }
915 usb_source_remove(sdi->session, drvc->sr_ctx);
916 if (acq->samples_interface_claimed) {
917 libusb_release_interface(usb->devhdl, acq->samples_interface);
918 acq->samples_interface_claimed = FALSE;
919 }
920 feed_queue_logic_free(acq->feed_queue);
921 acq->feed_queue = NULL;
922 acq->acquisition_state = ACQ_IDLE;
923}
924
925/*
926 * Callback for the completion of previously submitted USB transfers.
927 * Processes received sample memory content. Initiates termination of
928 * the current acquisition in case of failed processing or failed
929 * communication to the acquisition device. Also initiates termination
930 * when previously configured acquisition limits were reached.
931 */
932static void LIBUSB_CALL xfer_complete_cb(struct libusb_transfer *xfer)
933{
934 struct sr_dev_inst *sdi;
935 struct dev_context *devc;
936 struct dev_acquisition_t *acq;
937 const uint8_t *data;
938 size_t dlen;
939 gboolean was_completed, was_cancelled;
940 gboolean has_timedout, device_gone, is_stalled;
941 int level;
942 gboolean shall_abort;
943 int ret;
944
945 sdi = xfer ? xfer->user_data : NULL;
946 devc = sdi ? sdi->priv : NULL;
947 if (!sdi || !devc) {
948 /* ShouldNotHappen(TM) */
949 sr_warn("Completion of unregistered USB transfer.");
950 libusb_free_transfer(xfer);
951 return;
952 }
953 acq = &devc->acquisition;
954
955 /*
956 * Outside of an acquisition? Or in its shutdown path?
957 * Just release the USB transfer, don't process its data.
958 */
959 if (acq->acquisition_state != ACQ_RECEIVE) {
960 greatfet_free_transfer(sdi, xfer);
961 return;
962 }
963
964 /*
965 * Avoid the unfortunate libusb identifiers and data types.
966 * Simplify USB transfer status checks for later code paths.
967 * Optionally log the USB transfers' completion.
968 */
969 data = xfer->buffer;
970 dlen = xfer->actual_length;
971 was_completed = xfer->status == LIBUSB_TRANSFER_COMPLETED;
972 has_timedout = xfer->status == LIBUSB_TRANSFER_TIMED_OUT;
973 was_cancelled = xfer->status == LIBUSB_TRANSFER_CANCELLED;
974 device_gone = xfer->status == LIBUSB_TRANSFER_NO_DEVICE;
975 is_stalled = xfer->status == LIBUSB_TRANSFER_STALL;
976 level = sr_log_loglevel_get();
977 if (level >= SR_LOG_SPEW) {
978 sr_spew("USB transfer, status %s, byte count %zu.",
979 libusb_error_name(xfer->status), dlen);
980 } else if (level >= SR_LOG_DBG && !was_completed) {
981 sr_dbg("USB transfer, status %s, byte count %zu.",
982 libusb_error_name(xfer->status), dlen);
983 }
984
985 /*
986 * Timed out transfers may contain a little data. Warn but accept.
987 * Typical case will be completed transfers. Cancelled transfers
988 * are seen in shutdown paths, their data need not get processed.
989 * Terminate acquisition in case of communication or processing
990 * failure, or when limits were reached.
991 */
992 shall_abort = FALSE;
993 if (has_timedout)
994 sr_warn("USB transfer timed out. Using available data.");
995 if (was_completed || has_timedout) {
996 ret = greatfet_process_receive_data(sdi, data, dlen);
997 if (ret != SR_OK) {
998 sr_err("Error processing sample data. Aborting.");
999 shall_abort = TRUE;
1000 }
1001 if (acq->acquisition_state != ACQ_RECEIVE) {
1002 sr_dbg("Sample data processing ends acquisition.");
1003 feed_queue_logic_flush(acq->feed_queue);
1004 shall_abort = TRUE;
1005 }
1006 } else if (device_gone) {
1007 sr_err("Device gone during USB transfer. Aborting.");
1008 shall_abort = TRUE;
1009 } else if (was_cancelled) {
1010 sr_dbg("Cancelled USB transfer. Terminating acquisition.");
1011 shall_abort = TRUE;
1012 } else if (is_stalled) {
1013 sr_err("Device firmware is stalled on USB transfer. Aborting.");
1014 shall_abort = TRUE;
1015 } else {
1016 sr_err("USB transfer failed (%s). Aborting.",
1017 libusb_error_name(xfer->status));
1018 shall_abort = TRUE;
1019 }
1020
1021 /*
1022 * Resubmit the USB transfer for continued reception of sample
1023 * data. Or release the transfer when acquisition terminates
1024 * after errors were seen, or limits were reached, or the end
1025 * was requested in other regular ways.
1026 *
1027 * In the case of error or other terminating conditions cancel
1028 * the currently executing acquisition, end all USB transfers.
1029 */
1030 if (!shall_abort) {
1031 ret = libusb_submit_transfer(xfer);
1032 if (ret < 0) {
1033 sr_err("Cannot resubmit USB transfer. Aborting.");
1034 shall_abort = TRUE;
1035 }
1036 }
1037 if (shall_abort) {
1038 greatfet_free_transfer(sdi, xfer);
1039 greatfet_abort_acquisition_quick(sdi);
1040 }
1041}
1042
1043/* The public protocol.c API to start/stop acquisitions. */
1044
1045SR_PRIV int greatfet_setup_acquisition(const struct sr_dev_inst *sdi)
1046{
1047 int ret;
1048
1049 ret = greatfet_allocate_transfers(sdi);
1050 if (ret != SR_OK)
1051 return ret;
1052
1053 ret = greatfet_calc_capture_chans(sdi);
1054 if (ret != SR_OK)
1055 return ret;
1056
1057 return SR_OK;
1058}
1059
1060SR_PRIV int greatfet_start_acquisition(const struct sr_dev_inst *sdi)
1061{
1062 struct dev_context *devc;
1063 struct dev_acquisition_t *acq;
1064 struct sr_usb_dev_inst *usb;
1065 int ret;
1066
1067 if (!sdi)
1068 return SR_ERR_ARG;
1069 devc = sdi->priv;
1070 usb = sdi->conn;
1071 if (!devc || !usb)
1072 return SR_ERR_ARG;
1073 acq = &devc->acquisition;
1074
1075 /*
1076 * Configure the logic analyzer. Claim the USB interface. This
1077 * part of the sequence is not time critical.
1078 */
1079 ret = greatfet_logic_config(sdi);
1080 if (ret != SR_OK)
1081 return ret;
1082
1083 ret = libusb_claim_interface(usb->devhdl, acq->samples_interface);
1084 acq->samples_interface_claimed = ret == 0;
1085
1086 /*
1087 * Ideally we could submit USB transfers before sending the
1088 * logic analyzer start request. Experience suggests that this
1089 * results in libusb IO errors. That's why we need to accept the
1090 * window of blindness between sending the LA start request and
1091 * initiating USB data reception.
1092 */
1093 ret = greatfet_logic_start(sdi);
1094 if (ret != SR_OK)
1095 return ret;
1096
1097 ret = greatfet_prepare_transfers(sdi, xfer_complete_cb);
1098 if (ret != SR_OK)
1099 return ret;
1100
1101 return SR_OK;
1102}
1103
1104/*
1105 * The public acquisition abort routine, invoked by api.c logic. Could
1106 * optionally spend more time than the _quick() routine.
1107 */
1108SR_PRIV void greatfet_abort_acquisition(const struct sr_dev_inst *sdi)
1109{
1110 struct dev_context *devc;
1111
1112 if (!sdi)
1113 return;
1114 devc = sdi->priv;
1115 if (!devc)
1116 return;
1117
1118 (void)greatfet_logic_stop(sdi);
1119 greatfet_abort_acquisition_quick(sdi);
1120}
1121
1122SR_PRIV int greatfet_stop_acquisition(const struct sr_dev_inst *sdi)
1123{
1124 struct sr_usb_dev_inst *usb;
1125 int ret;
1126
1127 if (!sdi)
1128 return SR_ERR_ARG;
1129 usb = sdi->conn;
1130 if (!usb)
1131 return SR_ERR_ARG;
1132
1133 ret = greatfet_logic_stop(sdi);
1134 if (ret != SR_OK)
1135 return ret;
1136
1137 return SR_OK;
1138}
1139
1140SR_PRIV void greatfet_release_resources(const struct sr_dev_inst *sdi)
1141{
1142 struct dev_context *devc;
1143 struct dev_transfers_t *dxfer;
1144
1145 if (!sdi)
1146 return;
1147 devc = sdi->priv;
1148 if (!devc)
1149 return;
1150 dxfer = &devc->transfers;
1151
1152 /*
1153 * Is there something that needs to be done here? Transfers'
1154 * cancellation gets initiated and then happens as they keep
1155 * completing. The completion handler releases their libusb
1156 * resources. The last release also unregisters the periodic
1157 * glib main loop callback.
1158 *
1159 * Can something be done here? The receive buffer still is
1160 * allocated. As is the feed queue. Can we synchronize to the
1161 * last release of the USB resources? Need we keep invoking
1162 * the receive callback until the USB transfers pool has been
1163 * released? Need we wait for the active transfers counter to
1164 * drop to zero, is more checking involved?
1165 */
1166 if (dxfer->active_transfers)
1167 sr_warn("Got active USB transfers in release code path.");
1168}
1169
1170/*
1171 * Process received sample date. There are two essential modes:
1172 * - The straight forward case. The device provides 8 bits per sample
1173 * point. Forward each byte as is to the sigrok session. It matches
1174 * the sizeof(uint8_t) feed queue allocation parameter.
1175 * - The compact presentation where a smaller number of channels is
1176 * active, and their data spans only part of a byte per sample point.
1177 * Multiple samples' data is sharing bytes, and bytes will carry data
1178 * that was taken at different times. This requires some untangling
1179 * before forwarding byte sized sample data to the sigrok session.
1180 *
1181 * Implementation details:
1182 * - Samples taken first are found in the least significant bits of a
1183 * byte. Samples taken next are found in upper bits of the byte. For
1184 * example a byte containing 4x 2bit sample data is seen as 33221100.
1185 * - Depending on the number of enabled channels there could be up to
1186 * eight samples in one byte of sample memory. This implementation
1187 * tries to accumulate one input byte's content, but not more. To
1188 * simplify the implementation. Performance can get tuned later as
1189 * the need gets identified. Sampling at 204MHz results in some 3%
1190 * CPU load with Pulseview on the local workstation.
1191 * - Samples for 16 channels transparently are handled by the simple
1192 * 8 channel case above. All logic data of an individual samplepoint
1193 * occupies full bytes, endianess of sample data as provided by the
1194 * device firmware and the sigrok session are the same. No conversion
1195 * is required.
1196 */
1197static int greatfet_process_receive_data(const struct sr_dev_inst *sdi,
1198 const uint8_t *data, size_t dlen)
1199{
1200 static int diag_shown;
1201
1202 struct dev_context *devc;
1203 struct dev_acquisition_t *acq;
1204 struct feed_queue_logic *q;
1205 uint64_t samples_remain;
1206 gboolean exceeded;
1207 size_t samples_rcvd;
1208 uint8_t raw_mask;
1209 size_t points_per_byte, points_count;
1210 uint8_t raw_data;
1211 uint8_t accum[8];
1212 const uint8_t *rdptr;
1213 uint8_t *wrptr;
1214 int ret;
1215
1216 if (!sdi)
1217 return SR_ERR_ARG;
1218 devc = sdi->priv;
1219 if (!devc)
1220 return SR_ERR_ARG;
1221 acq = &devc->acquisition;
1222 q = acq->feed_queue;
1223
1224 /*
1225 * Check whether acquisition limits apply, and whether they
1226 * were reached or exceeded before. Constrain the submission
1227 * of more sample values to what's still within the limits of
1228 * the current acquisition.
1229 */
1230 ret = sr_sw_limits_get_remain(&devc->sw_limits,
1231 &samples_remain, NULL, NULL, &exceeded);
1232 if (ret != SR_OK)
1233 return ret;
1234 if (exceeded)
1235 return SR_OK;
1236
1237 /*
1238 * Check for the simple case first. Where bytes carry samples
1239 * of exactly one sample point. Pass memory in verbatim form.
1240 * Notice that 16bit sample quantities happen to work here too.
1241 */
1242 if (!acq->channel_shift) {
1243 samples_rcvd = dlen / acq->unit_size;
1244 if (samples_remain && samples_rcvd > samples_remain)
1245 samples_rcvd = samples_remain;
1246 ret = feed_queue_logic_submit_many(q, data, samples_rcvd);
1247 if (ret != SR_OK)
1248 return ret;
1249 sr_sw_limits_update_samples_read(&devc->sw_limits, samples_rcvd);
1250 return SR_OK;
1251 }
1252
1253 /*
1254 * Handle the complex case by means of some naive logic. To
1255 * simplify the implementation for now and see if the approach
1256 * works out. It helps that the firmware provides sample data
1257 * in units of power-of-two bit counts per sample point. This
1258 * eliminates fragments which could span several transfers.
1259 *
1260 * Notice that dense sample memory only happens for channel
1261 * counts under 8. That's why we read bytes here and need not
1262 * dispatch based on unit size.
1263 */
1264 raw_mask = (1UL << acq->channel_shift) - 1;
1265 points_per_byte = 8 / acq->channel_shift;
1266 if (!diag_shown++) {
1267 sr_dbg("sample memory: ch count %zu, ch shift %zu, mask 0x%x, points %zu",
1268 acq->capture_channels, acq->channel_shift,
1269 raw_mask, points_per_byte);
1270 }
1271 samples_rcvd = dlen * points_per_byte;
1272 if (samples_remain && samples_rcvd > samples_remain) {
1273 samples_rcvd = samples_remain;
1274 dlen = samples_rcvd;
1275 dlen += points_per_byte - 1;
1276 dlen /= points_per_byte;
1277 }
1278 rdptr = data;
1279 while (dlen--) {
1280 raw_data = read_u8_inc(&rdptr);
1281 wrptr = accum;
1282 points_count = points_per_byte;
1283 while (points_count--) {
1284 write_u8_inc(&wrptr, raw_data & raw_mask);
1285 raw_data >>= acq->channel_shift;
1286 }
1287 points_count = points_per_byte;
1288 ret = feed_queue_logic_submit_many(q, accum, points_count);
1289 if (ret != SR_OK)
1290 return ret;
1291 sr_sw_limits_update_samples_read(&devc->sw_limits, points_count);
1292 }
1293 return SR_OK;
1294}
1295
1296/* Receive callback, invoked when data is available, or periodically. */
f594b3b0
GS
1297SR_PRIV int greatfet_receive_data(int fd, int revents, void *cb_data)
1298{
208fcedc 1299 struct sr_dev_inst *sdi;
f594b3b0 1300 struct dev_context *devc;
208fcedc
GS
1301 struct drv_context *drvc;
1302 libusb_context *ctx;
1303 struct timeval tv;
f594b3b0
GS
1304
1305 (void)fd;
208fcedc 1306 (void)revents;
f594b3b0
GS
1307
1308 sdi = cb_data;
208fcedc 1309 if (!sdi || !sdi->priv || !sdi->driver)
f594b3b0 1310 return TRUE;
f594b3b0
GS
1311 devc = sdi->priv;
1312 if (!devc)
1313 return TRUE;
208fcedc
GS
1314 drvc = sdi->driver->context;
1315 if (!drvc || !drvc->sr_ctx)
1316 return TRUE;
1317 ctx = drvc->sr_ctx->libusb_ctx;
1318
1319 /*
1320 * Handle those USB transfers which have completed so far
1321 * in a regular fashion. These carry desired sample values.
1322 */
1323 tv.tv_sec = tv.tv_usec = 0;
1324 libusb_handle_events_timeout(ctx, &tv);
f594b3b0 1325
208fcedc
GS
1326 /*
1327 * End the current acquisition when limites were reached.
1328 * Process USB transfers again here before returning, because
1329 * acquisition termination will unregister the receive callback,
1330 * and cancel previously submitted transfers. Reap those here.
1331 */
1332 if (sr_sw_limits_check(&devc->sw_limits)) {
1333 greatfet_abort_acquisition_quick(sdi);
1334 tv.tv_sec = tv.tv_usec = 0;
1335 libusb_handle_events_timeout(ctx, &tv);
f594b3b0
GS
1336 }
1337
1338 return TRUE;
1339}