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