]> sigrok.org Git - libsigrok.git/blob - src/hardware/kingst-la2016/protocol.c
kingst-la2016: use a pool of USB bulk transfers, speedup download
[libsigrok.git] / src / hardware / kingst-la2016 / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2022 Gerhard Sittig <gerhard.sittig@gmx.net>
5  * Copyright (C) 2020 Florian Schmidt <schmidt_florian@gmx.de>
6  * Copyright (C) 2013 Marcus Comstedt <marcus@mc.pp.se>
7  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
8  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #include <config.h>
25
26 #include <libsigrok/libsigrok.h>
27 #include <string.h>
28
29 #include "libsigrok-internal.h"
30 #include "protocol.h"
31
32 /* USB PID dependent MCU firmware. Model dependent FPGA bitstream. */
33 #define MCU_FWFILE_FMT  "kingst-la-%04x.fw"
34 #define FPGA_FWFILE_FMT "kingst-%s-fpga.bitstream"
35
36 /*
37  * List of supported devices and their features. See @ref kingst_model
38  * for the fields' type and meaning. Table is sorted by EEPROM magic.
39  *
40  * TODO
41  * - Below LA1016 properties were guessed, need verification.
42  * - Add LA5016 and LA5032 devices when their EEPROM magic is known.
43  * - Does LA1010 fit the driver implementation? Samplerates vary with
44  *   channel counts, lack of local sample memory. Most probably not.
45  */
46 static const struct kingst_model models[] = {
47         { 2, "LA2016", "la2016", SR_MHZ(200), 16, 1, },
48         { 3, "LA1016", "la1016", SR_MHZ(100), 16, 1, },
49         { 8, "LA2016", "la2016a1", SR_MHZ(200), 16, 1, },
50         { 9, "LA1016", "la1016a1", SR_MHZ(100), 16, 1, },
51 };
52
53 /* USB vendor class control requests, executed by the Cypress FX2 MCU. */
54 #define CMD_FPGA_ENABLE 0x10
55 #define CMD_FPGA_SPI    0x20    /* R/W access to FPGA registers via SPI. */
56 #define CMD_BULK_START  0x30    /* Start sample data download via USB EP6 IN. */
57 #define CMD_BULK_RESET  0x38    /* Flush FIFO of FX2 USB EP6 IN. */
58 #define CMD_FPGA_INIT   0x50    /* Used before and after FPGA bitstream upload. */
59 #define CMD_KAUTH       0x60    /* Communicate to auth IC (U10). Not used. */
60 #define CMD_EEPROM      0xa2    /* R/W access to EEPROM content. */
61
62 /*
63  * FPGA register addresses (base addresses when registers span multiple
64  * bytes, in that case data is kept in little endian format). Passed to
65  * CMD_FPGA_SPI requests. The FX2 MCU transparently handles the detail
66  * of SPI transfers encoding the read (1) or write (0) direction in the
67  * MSB of the address field. There are some 60 byte-wide FPGA registers.
68  *
69  * Unfortunately the FPGA registers change their meaning between the
70  * read and write directions of access, or exclusively provide one of
71  * these directions and not the other. This is an arbitrary vendor's
72  * choice, there is nothing which the sigrok driver could do about it.
73  * Values written to registers typically cannot get read back, neither
74  * verified after writing a configuration, nor queried upon startup for
75  * automatic detection of the current configuration. Neither appear to
76  * be there echo registers for presence and communication checks, nor
77  * version identifying registers, as far as we know.
78  */
79 #define REG_RUN         0x00    /* Read capture status, write start capture. */
80 #define REG_PWM_EN      0x02    /* User PWM channels on/off. */
81 #define REG_CAPT_MODE   0x03    /* Write 0x00 capture to SDRAM, 0x01 streaming. */
82 #define REG_BULK        0x08    /* Write start addr, byte count to download samples. */
83 #define REG_SAMPLING    0x10    /* Write capture config, read capture SDRAM location. */
84 #define REG_TRIGGER     0x20    /* Write level and edge trigger config. */
85 #define REG_UNKNOWN_30  0x30
86 #define REG_THRESHOLD   0x68    /* Write PWM config to setup input threshold DAC. */
87 #define REG_PWM1        0x70    /* Write config for user PWM1. */
88 #define REG_PWM2        0x78    /* Write config for user PWM2. */
89
90 /* Bit patterns to write to REG_CAPT_MODE. */
91 #define CAPTMODE_TO_RAM 0x00
92 #define CAPTMODE_STREAM 0x01
93
94 /* Bit patterns to write to REG_RUN, setup run mode. */
95 #define RUNMODE_HALT    0x00
96 #define RUNMODE_RUN     0x03
97
98 /* Bit patterns when reading from REG_RUN, get run state. */
99 #define RUNSTATE_IDLE_BIT       (1UL << 0)
100 #define RUNSTATE_DRAM_BIT       (1UL << 1)
101 #define RUNSTATE_TRGD_BIT       (1UL << 2)
102 #define RUNSTATE_POST_BIT       (1UL << 3)
103
104 static int ctrl_in(const struct sr_dev_inst *sdi,
105         uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
106         void *data, uint16_t wLength)
107 {
108         struct sr_usb_dev_inst *usb;
109         int ret;
110
111         usb = sdi->conn;
112
113         ret = libusb_control_transfer(usb->devhdl,
114                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
115                 bRequest, wValue, wIndex, data, wLength,
116                 DEFAULT_TIMEOUT_MS);
117         if (ret != wLength) {
118                 sr_dbg("USB ctrl in: %d bytes, req %d val %#x idx %d: %s.",
119                         wLength, bRequest, wValue, wIndex,
120                         libusb_error_name(ret));
121                 sr_err("Cannot read %d bytes from USB: %s.",
122                         wLength, libusb_error_name(ret));
123                 return SR_ERR_IO;
124         }
125
126         return SR_OK;
127 }
128
129 static int ctrl_out(const struct sr_dev_inst *sdi,
130         uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
131         void *data, uint16_t wLength)
132 {
133         struct sr_usb_dev_inst *usb;
134         int ret;
135
136         usb = sdi->conn;
137
138         ret = libusb_control_transfer(usb->devhdl,
139                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
140                 bRequest, wValue, wIndex, data, wLength,
141                 DEFAULT_TIMEOUT_MS);
142         if (ret != wLength) {
143                 sr_dbg("USB ctrl out: %d bytes, req %d val %#x idx %d: %s.",
144                         wLength, bRequest, wValue, wIndex,
145                         libusb_error_name(ret));
146                 sr_err("Cannot write %d bytes to USB: %s.",
147                         wLength, libusb_error_name(ret));
148                 return SR_ERR_IO;
149         }
150
151         return SR_OK;
152 }
153
154 /* HACK Experiment to spot FPGA registers of interest. */
155 static void la2016_dump_fpga_registers(const struct sr_dev_inst *sdi,
156         const char *caption, size_t reg_lower, size_t reg_upper)
157 {
158         static const size_t dump_chunk_len = 16;
159
160         size_t rdlen;
161         uint8_t rdbuf[0x80 - 0x00];     /* Span all FPGA registers. */
162         const uint8_t *rdptr;
163         int ret;
164         size_t dump_addr, indent, dump_len;
165         GString *txt;
166
167         if (sr_log_loglevel_get() < SR_LOG_SPEW)
168                 return;
169
170         if (!reg_lower && !reg_upper) {
171                 reg_lower = 0;
172                 reg_upper = sizeof(rdbuf);
173         }
174         if (reg_upper - reg_lower > sizeof(rdbuf))
175                 reg_upper = sizeof(rdbuf) - reg_lower;
176
177         rdlen = reg_upper - reg_lower;
178         ret = ctrl_in(sdi, CMD_FPGA_SPI, reg_lower, 0, rdbuf, rdlen);
179         if (ret != SR_OK) {
180                 sr_err("Cannot get registers space.");
181                 return;
182         }
183         rdptr = rdbuf;
184
185         sr_spew("FPGA registers dump: %s", caption ? : "for fun");
186         dump_addr = reg_lower;
187         while (rdlen) {
188                 dump_len = rdlen;
189                 indent = dump_addr % dump_chunk_len;
190                 if (dump_len > dump_chunk_len)
191                         dump_len = dump_chunk_len;
192                 if (dump_len + indent > dump_chunk_len)
193                         dump_len = dump_chunk_len - indent;
194                 txt = sr_hexdump_new(rdptr, dump_len);
195                 sr_spew("  %04zx  %*s%s",
196                         dump_addr, (int)(3 * indent), "", txt->str);
197                 sr_hexdump_free(txt);
198                 dump_addr += dump_len;
199                 rdptr += dump_len;
200                 rdlen -= dump_len;
201         }
202 }
203
204 /*
205  * Check the necessity for FPGA bitstream upload, because another upload
206  * would take some 600ms which is undesirable after program startup. Try
207  * to access some FPGA registers and check the values' plausibility. The
208  * check should fail on the safe side, request another upload when in
209  * doubt. A positive response (the request to continue operation with the
210  * currently active bitstream) should be conservative. Accessing multiple
211  * registers is considered cheap compared to the cost of bitstream upload.
212  *
213  * It helps though that both the vendor software and the sigrok driver
214  * use the same bundle of MCU firmware and FPGA bitstream for any of the
215  * supported models. We don't expect to successfully communicate to the
216  * device yet disagree on its protocol. Ideally we would access version
217  * identifying registers for improved robustness, but are not aware of
218  * any. A bitstream reload can always be forced by a power cycle.
219  */
220 static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
221 {
222         uint8_t init_rsp;
223         uint8_t buff[REG_PWM_EN - REG_RUN]; /* Larger of REG_RUN, REG_PWM_EN. */
224         int ret;
225         uint16_t run_state;
226         uint8_t pwm_en;
227         size_t read_len;
228         const uint8_t *rdptr;
229
230         sr_dbg("Checking operation of the FPGA bitstream.");
231         la2016_dump_fpga_registers(sdi, "bitstream check", 0, 0);
232
233         init_rsp = ~0;
234         ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
235         if (ret != SR_OK || init_rsp != 0) {
236                 sr_dbg("FPGA init query failed, or unexpected response.");
237                 return SR_ERR_IO;
238         }
239
240         read_len = sizeof(run_state);
241         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, read_len);
242         if (ret != SR_OK) {
243                 sr_dbg("FPGA register access failed (run state).");
244                 return SR_ERR_IO;
245         }
246         rdptr = buff;
247         run_state = read_u16le_inc(&rdptr);
248         sr_spew("FPGA register: run state 0x%04x.", run_state);
249         if (run_state && (run_state & 0x3) != 0x1) {
250                 sr_dbg("Unexpected FPGA register content (run state).");
251                 return SR_ERR_DATA;
252         }
253         if (run_state && (run_state & ~0xf) != 0x85e0) {
254                 sr_dbg("Unexpected FPGA register content (run state).");
255                 return SR_ERR_DATA;
256         }
257
258         read_len = sizeof(pwm_en);
259         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, buff, read_len);
260         if (ret != SR_OK) {
261                 sr_dbg("FPGA register access failed (PWM enable).");
262                 return SR_ERR_IO;
263         }
264         rdptr = buff;
265         pwm_en = read_u8_inc(&rdptr);
266         sr_spew("FPGA register: PWM enable 0x%02x.", pwm_en);
267         if ((pwm_en & 0x3) != 0x0) {
268                 sr_dbg("Unexpected FPGA register content (PWM enable).");
269                 return SR_ERR_DATA;
270         }
271
272         sr_info("Could re-use current FPGA bitstream. No upload required.");
273         return SR_OK;
274 }
275
276 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
277         const char *bitstream_fname)
278 {
279         struct drv_context *drvc;
280         struct sr_usb_dev_inst *usb;
281         struct sr_resource bitstream;
282         uint32_t bitstream_size;
283         uint8_t buffer[sizeof(uint32_t)];
284         uint8_t *wrptr;
285         uint8_t block[4096];
286         int len, act_len;
287         unsigned int pos;
288         int ret;
289         unsigned int zero_pad_to;
290
291         drvc = sdi->driver->context;
292         usb = sdi->conn;
293
294         sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
295
296         ret = sr_resource_open(drvc->sr_ctx, &bitstream,
297                 SR_RESOURCE_FIRMWARE, bitstream_fname);
298         if (ret != SR_OK) {
299                 sr_err("Cannot find FPGA bitstream %s.", bitstream_fname);
300                 return ret;
301         }
302
303         bitstream_size = (uint32_t)bitstream.size;
304         wrptr = buffer;
305         write_u32le_inc(&wrptr, bitstream_size);
306         ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer);
307         if (ret != SR_OK) {
308                 sr_err("Cannot initiate FPGA bitstream upload.");
309                 sr_resource_close(drvc->sr_ctx, &bitstream);
310                 return ret;
311         }
312         zero_pad_to = bitstream_size;
313         zero_pad_to += LA2016_EP2_PADDING - 1;
314         zero_pad_to /= LA2016_EP2_PADDING;
315         zero_pad_to *= LA2016_EP2_PADDING;
316
317         pos = 0;
318         while (1) {
319                 if (pos < bitstream.size) {
320                         len = (int)sr_resource_read(drvc->sr_ctx, &bitstream,
321                                 block, sizeof(block));
322                         if (len < 0) {
323                                 sr_err("Cannot read FPGA bitstream.");
324                                 sr_resource_close(drvc->sr_ctx, &bitstream);
325                                 return SR_ERR_IO;
326                         }
327                 } else {
328                         /*  Zero-pad until 'zero_pad_to'. */
329                         len = zero_pad_to - pos;
330                         if ((unsigned)len > sizeof(block))
331                                 len = sizeof(block);
332                         memset(&block, 0, len);
333                 }
334                 if (len == 0)
335                         break;
336
337                 ret = libusb_bulk_transfer(usb->devhdl, USB_EP_FPGA_BITSTREAM,
338                         &block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
339                 if (ret != 0) {
340                         sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
341                                 pos, (int)len, libusb_error_name(ret));
342                         ret = SR_ERR_IO;
343                         break;
344                 }
345                 if (act_len != len) {
346                         sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
347                                 pos, (int)len, act_len);
348                         ret = SR_ERR_IO;
349                         break;
350                 }
351                 pos += len;
352         }
353         sr_resource_close(drvc->sr_ctx, &bitstream);
354         if (ret != SR_OK)
355                 return ret;
356         sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.",
357                 bitstream.size);
358
359         return SR_OK;
360 }
361
362 static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
363 {
364         int ret;
365         uint8_t resp;
366
367         ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &resp, sizeof(resp));
368         if (ret != SR_OK) {
369                 sr_err("Cannot read response after FPGA bitstream upload.");
370                 return ret;
371         }
372         if (resp != 0) {
373                 sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
374                         resp);
375                 return SR_ERR_DATA;
376         }
377         g_usleep(30 * 1000);
378
379         ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0);
380         if (ret != SR_OK) {
381                 sr_err("Cannot enable FPGA after bitstream upload.");
382                 return ret;
383         }
384         g_usleep(40 * 1000);
385
386         return SR_OK;
387 }
388
389 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
390 {
391         int ret;
392         uint16_t duty_R79, duty_R56;
393         uint8_t buf[REG_PWM1 - REG_THRESHOLD]; /* Width of REG_THRESHOLD. */
394         uint8_t *wrptr;
395
396         /* Clamp threshold setting to valid range for LA2016. */
397         if (voltage > LA2016_THR_VOLTAGE_MAX) {
398                 voltage = LA2016_THR_VOLTAGE_MAX;
399         } else if (voltage < -LA2016_THR_VOLTAGE_MAX) {
400                 voltage = -LA2016_THR_VOLTAGE_MAX;
401         }
402
403         /*
404          * Two PWM output channels feed one DAC which generates a bias
405          * voltage, which offsets the input probe's voltage level, and
406          * in combination with the FPGA pins' fixed threshold result in
407          * a programmable input threshold from the user's perspective.
408          * The PWM outputs can be seen on R79 and R56 respectively, the
409          * frequency is 100kHz and the duty cycle varies. The R79 PWM
410          * uses three discrete settings. The R56 PWM varies with desired
411          * thresholds and depends on the R79 PWM configuration. See the
412          * schematics comments which discuss the formulae.
413          */
414         if (voltage >= 2.9) {
415                 duty_R79 = 0;           /* PWM off (0V). */
416                 duty_R56 = (uint16_t)(302 * voltage - 363);
417         } else if (voltage > -0.4) {
418                 duty_R79 = 0x00f2;      /* 25% duty cycle. */
419                 duty_R56 = (uint16_t)(302 * voltage + 121);
420         } else {
421                 duty_R79 = 0x02d7;      /* 72% duty cycle. */
422                 duty_R56 = (uint16_t)(302 * voltage + 1090);
423         }
424
425         /* Clamp duty register values to sensible limits. */
426         if (duty_R56 < 10) {
427                 duty_R56 = 10;
428         } else if (duty_R56 > 1100) {
429                 duty_R56 = 1100;
430         }
431
432         sr_dbg("Set threshold voltage %.2fV.", voltage);
433         sr_dbg("Duty cycle values: R56 0x%04x, R79 0x%04x.", duty_R56, duty_R79);
434
435         wrptr = buf;
436         write_u16le_inc(&wrptr, duty_R56);
437         write_u16le_inc(&wrptr, duty_R79);
438
439         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_THRESHOLD, 0, buf, wrptr - buf);
440         if (ret != SR_OK) {
441                 sr_err("Cannot set threshold voltage %.2fV.", voltage);
442                 return ret;
443         }
444
445         return SR_OK;
446 }
447
448 /*
449  * Communicates a channel's configuration to the device after the
450  * parameters may have changed. Configuration of one channel may
451  * interfere with other channels since they share FPGA registers.
452  */
453 static int set_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
454 {
455         static uint8_t reg_bases[] = { REG_PWM1, REG_PWM2, };
456
457         struct dev_context *devc;
458         struct pwm_setting *params;
459         uint8_t reg_base;
460         double val_f;
461         uint32_t val_u;
462         uint32_t period, duty;
463         size_t ch;
464         int ret;
465         uint8_t enable_all, enable_cfg, reg_val;
466         uint8_t buf[REG_PWM2 - REG_PWM1]; /* Width of one REG_PWMx. */
467         uint8_t *wrptr;
468
469         devc = sdi->priv;
470         if (idx >= ARRAY_SIZE(devc->pwm_setting))
471                 return SR_ERR_ARG;
472         params = &devc->pwm_setting[idx];
473         if (idx >= ARRAY_SIZE(reg_bases))
474                 return SR_ERR_ARG;
475         reg_base = reg_bases[idx];
476
477         /*
478          * Map application's specs to hardware register values. Do math
479          * in floating point initially, but convert to u32 eventually.
480          */
481         sr_dbg("PWM config, app spec, ch %zu, en %d, freq %.1f, duty %.1f.",
482                 idx, params->enabled ? 1 : 0, params->freq, params->duty);
483         val_f = PWM_CLOCK;
484         val_f /= params->freq;
485         val_u = val_f;
486         period = val_u;
487         val_f = period;
488         val_f *= params->duty;
489         val_f /= 100.0;
490         val_f += 0.5;
491         val_u = val_f;
492         duty = val_u;
493         sr_dbg("PWM config, reg 0x%04x, freq %u, duty %u.",
494                 (unsigned)reg_base, (unsigned)period, (unsigned)duty);
495
496         /* Get the "enabled" state of all supported PWM channels. */
497         enable_all = 0;
498         for (ch = 0; ch < ARRAY_SIZE(devc->pwm_setting); ch++) {
499                 if (!devc->pwm_setting[ch].enabled)
500                         continue;
501                 enable_all |= 1U << ch;
502         }
503         enable_cfg = 1U << idx;
504         sr_spew("PWM config, enable all 0x%02hhx, cfg 0x%02hhx.",
505                 enable_all, enable_cfg);
506
507         /*
508          * Disable the to-get-configured channel before its parameters
509          * will change. Or disable and exit when the channel is supposed
510          * to get turned off.
511          */
512         sr_spew("PWM config, disabling before param change.");
513         reg_val = enable_all & ~enable_cfg;
514         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0,
515                 &reg_val, sizeof(reg_val));
516         if (ret != SR_OK) {
517                 sr_err("Cannot adjust PWM enabled state.");
518                 return ret;
519         }
520         if (!params->enabled)
521                 return SR_OK;
522
523         /* Write register values to device. */
524         sr_spew("PWM config, sending new parameters.");
525         wrptr = buf;
526         write_u32le_inc(&wrptr, period);
527         write_u32le_inc(&wrptr, duty);
528         ret = ctrl_out(sdi, CMD_FPGA_SPI, reg_base, 0, buf, wrptr - buf);
529         if (ret != SR_OK) {
530                 sr_err("Cannot change PWM parameters.");
531                 return ret;
532         }
533
534         /* Enable configured channel after write completion. */
535         sr_spew("PWM config, enabling after param change.");
536         reg_val = enable_all | enable_cfg;
537         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0,
538                 &reg_val, sizeof(reg_val));
539         if (ret != SR_OK) {
540                 sr_err("Cannot adjust PWM enabled state.");
541                 return ret;
542         }
543
544         return SR_OK;
545 }
546
547 static uint32_t get_channels_mask(const struct sr_dev_inst *sdi)
548 {
549         uint32_t channels;
550         GSList *l;
551         struct sr_channel *ch;
552
553         channels = 0;
554         for (l = sdi->channels; l; l = l->next) {
555                 ch = l->data;
556                 if (ch->type != SR_CHANNEL_LOGIC)
557                         continue;
558                 if (!ch->enabled)
559                         continue;
560                 channels |= 1UL << ch->index;
561         }
562
563         return channels;
564 }
565
566 static int set_trigger_config(const struct sr_dev_inst *sdi)
567 {
568         struct dev_context *devc;
569         struct sr_trigger *trigger;
570         struct trigger_cfg {
571                 uint32_t channels;      /* Actually: Enabled channels? */
572                 uint32_t enabled;       /* Actually: Triggering channels? */
573                 uint32_t level;
574                 uint32_t high_or_falling;
575         } cfg;
576         GSList *stages;
577         GSList *channel;
578         struct sr_trigger_stage *stage1;
579         struct sr_trigger_match *match;
580         uint32_t ch_mask;
581         int ret;
582         uint8_t buf[REG_UNKNOWN_30 - REG_TRIGGER]; /* Width of REG_TRIGGER. */
583         uint8_t *wrptr;
584
585         devc = sdi->priv;
586         trigger = sr_session_trigger_get(sdi->session);
587
588         memset(&cfg, 0, sizeof(cfg));
589
590         cfg.channels = get_channels_mask(sdi);
591
592         if (trigger && trigger->stages) {
593                 stages = trigger->stages;
594                 stage1 = stages->data;
595                 if (stages->next) {
596                         sr_err("Only one trigger stage supported for now.");
597                         return SR_ERR_ARG;
598                 }
599                 channel = stage1->matches;
600                 while (channel) {
601                         match = channel->data;
602                         ch_mask = 1UL << match->channel->index;
603
604                         switch (match->match) {
605                         case SR_TRIGGER_ZERO:
606                                 cfg.level |= ch_mask;
607                                 cfg.high_or_falling &= ~ch_mask;
608                                 break;
609                         case SR_TRIGGER_ONE:
610                                 cfg.level |= ch_mask;
611                                 cfg.high_or_falling |= ch_mask;
612                                 break;
613                         case SR_TRIGGER_RISING:
614                                 if ((cfg.enabled & ~cfg.level)) {
615                                         sr_err("Device only supports one edge trigger.");
616                                         return SR_ERR_ARG;
617                                 }
618                                 cfg.level &= ~ch_mask;
619                                 cfg.high_or_falling &= ~ch_mask;
620                                 break;
621                         case SR_TRIGGER_FALLING:
622                                 if ((cfg.enabled & ~cfg.level)) {
623                                         sr_err("Device only supports one edge trigger.");
624                                         return SR_ERR_ARG;
625                                 }
626                                 cfg.level &= ~ch_mask;
627                                 cfg.high_or_falling |= ch_mask;
628                                 break;
629                         default:
630                                 sr_err("Unknown trigger condition.");
631                                 return SR_ERR_ARG;
632                         }
633                         cfg.enabled |= ch_mask;
634                         channel = channel->next;
635                 }
636         }
637         sr_dbg("Set trigger config: "
638                 "enabled-channels 0x%04x, triggering-channels 0x%04x, "
639                 "level-triggered 0x%04x, high/falling 0x%04x.",
640                 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
641
642         devc->trigger_involved = cfg.enabled != 0;
643
644         wrptr = buf;
645         write_u32le_inc(&wrptr, cfg.channels);
646         write_u32le_inc(&wrptr, cfg.enabled);
647         write_u32le_inc(&wrptr, cfg.level);
648         write_u32le_inc(&wrptr, cfg.high_or_falling);
649         /* TODO
650          * Comment on this literal 16. Origin, meaning? Cannot be the
651          * register offset, nor the transfer length. Is it a channels
652          * count that is relevant for 16 and 32 channel models? Is it
653          * an obsolete experiment?
654          */
655         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
656         if (ret != SR_OK) {
657                 sr_err("Cannot setup trigger configuration.");
658                 return ret;
659         }
660
661         return SR_OK;
662 }
663
664 static int set_sample_config(const struct sr_dev_inst *sdi)
665 {
666         struct dev_context *devc;
667         uint64_t min_samplerate, eff_samplerate;
668         uint16_t divider_u16;
669         uint64_t limit_samples;
670         uint64_t pre_trigger_samples;
671         uint64_t pre_trigger_memory;
672         uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
673         uint8_t *wrptr;
674         int ret;
675
676         devc = sdi->priv;
677
678         if (devc->samplerate > devc->model->samplerate) {
679                 sr_err("Too high a sample rate: %" PRIu64 ".",
680                         devc->samplerate);
681                 return SR_ERR_ARG;
682         }
683         min_samplerate = devc->model->samplerate;
684         min_samplerate /= 65536;
685         if (devc->samplerate < min_samplerate) {
686                 sr_err("Too low a sample rate: %" PRIu64 ".",
687                         devc->samplerate);
688                 return SR_ERR_ARG;
689         }
690         divider_u16 = devc->model->samplerate / devc->samplerate;
691         eff_samplerate = devc->model->samplerate / divider_u16;
692
693         ret = sr_sw_limits_get_remain(&devc->sw_limits,
694                 &limit_samples, NULL, NULL, NULL);
695         if (ret != SR_OK) {
696                 sr_err("Cannot get acquisition limits.");
697                 return ret;
698         }
699         if (limit_samples > LA2016_NUM_SAMPLES_MAX) {
700                 sr_warn("Too high a sample depth: %" PRIu64 ", capping.",
701                         limit_samples);
702                 limit_samples = LA2016_NUM_SAMPLES_MAX;
703         }
704         if (limit_samples == 0) {
705                 limit_samples = LA2016_NUM_SAMPLES_MAX;
706                 sr_dbg("Passing %" PRIu64 " to HW for unlimited samples.",
707                         limit_samples);
708         }
709
710         /*
711          * The acquisition configuration communicates "pre-trigger"
712          * specs in several formats. sigrok users provide a percentage
713          * (0-100%), which translates to a pre-trigger samples count
714          * (assuming that a total samples count limit was specified).
715          * The device supports hardware compression, which depends on
716          * slowly changing input data to be effective. Fast changing
717          * input data may occupy more space in sample memory than its
718          * uncompressed form would. This is why a third parameter can
719          * limit the amount of sample memory to use for pre-trigger
720          * data. Only the upper 24 bits of that memory size spec get
721          * communicated to the device (written to its FPGA register).
722          *
723          * TODO Determine whether the pre-trigger memory size gets
724          * specified in samples or in bytes. A previous implementation
725          * suggests bytes but this is suspicious when every other spec
726          * is in terms of samples.
727          */
728         if (devc->trigger_involved) {
729                 pre_trigger_samples = limit_samples;
730                 pre_trigger_samples *= devc->capture_ratio;
731                 pre_trigger_samples /= 100;
732                 pre_trigger_memory = devc->model->memory_bits;
733                 pre_trigger_memory *= UINT64_C(1024 * 1024 * 1024);
734                 pre_trigger_memory /= 8; /* devc->model->channel_count ? */
735                 pre_trigger_memory *= devc->capture_ratio;
736                 pre_trigger_memory /= 100;
737         } else {
738                 sr_dbg("No trigger setup, skipping pre-trigger config.");
739                 pre_trigger_samples = 1;
740                 pre_trigger_memory = 0;
741         }
742         /* Ensure non-zero value after LSB shift out in HW reg. */
743         if (pre_trigger_memory < 0x100) {
744                 pre_trigger_memory = 0x100;
745         }
746
747         sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples.",
748                 eff_samplerate / SR_KHZ(1), limit_samples);
749         sr_dbg("Capture ratio %" PRIu64 "%%, count %" PRIu64 ", mem %" PRIu64 ".",
750                 devc->capture_ratio, pre_trigger_samples, pre_trigger_memory);
751
752         /*
753          * The acquisition configuration occupies a total of 16 bytes:
754          * - A 34bit total samples count limit (up to 10 billions) that
755          *   is kept in a 40bit register.
756          * - A 34bit pre-trigger samples count limit (up to 10 billions)
757          *   in another 40bit register.
758          * - A 32bit pre-trigger memory space limit (in bytes) of which
759          *   the upper 24bits are kept in an FPGA register.
760          * - A 16bit clock divider which gets applied to the maximum
761          *   samplerate of the device.
762          * - An 8bit register of unknown meaning. Currently always 0.
763          */
764         wrptr = buf;
765         write_u40le_inc(&wrptr, limit_samples);
766         write_u40le_inc(&wrptr, pre_trigger_samples);
767         write_u24le_inc(&wrptr, pre_trigger_memory >> 8);
768         write_u16le_inc(&wrptr, divider_u16);
769         write_u8_inc(&wrptr, 0);
770         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
771         if (ret != SR_OK) {
772                 sr_err("Cannot setup acquisition configuration.");
773                 return ret;
774         }
775
776         return SR_OK;
777 }
778
779 /*
780  * FPGA register REG_RUN holds the run state (u16le format). Bit fields
781  * of interest:
782  *   bit 0: value 1 = idle
783  *   bit 1: value 1 = writing to SDRAM
784  *   bit 2: value 0 = waiting for trigger, 1 = trigger seen
785  *   bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
786  * The meaning of other bit fields is unknown.
787  *
788  * Typical values in order of appearance during execution:
789  *   0x85e1: idle, no acquisition pending
790  *     IDLE set, TRGD don't care, POST don't care; DRAM don't care
791  *     "In idle state." Takes precedence over all others.
792  *   0x85e2: pre-sampling, samples before the trigger position,
793  *     when capture ratio > 0%
794  *     IDLE clear, TRGD clear, POST clear; DRAM don't care
795  *     "Not idle any more, no post yet, not triggered yet."
796  *   0x85ea: pre-sampling complete, now waiting for the trigger
797  *     (whilst sampling continuously)
798  *     IDLE clear, TRGD clear, POST set; DRAM don't care
799  *     "Post set thus after pre, not triggered yet"
800  *   0x85ee: trigger seen, capturing post-trigger samples, running
801  *     IDLE clear, TRGD set, POST set; DRAM don't care
802  *     "Triggered and in post, not idle yet."
803  *   0x85ed: idle
804  *     IDLE set, TRGD don't care, POST don't care; DRAM don't care
805  *     "In idle state." TRGD/POST don't care, same meaning as above.
806  */
807 static const uint16_t runstate_mask_idle = RUNSTATE_IDLE_BIT;
808 static const uint16_t runstate_patt_idle = RUNSTATE_IDLE_BIT;
809 static const uint16_t runstate_mask_step =
810         RUNSTATE_IDLE_BIT | RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
811 static const uint16_t runstate_patt_pre_trig = 0;
812 static const uint16_t runstate_patt_wait_trig = RUNSTATE_POST_BIT;
813 static const uint16_t runstate_patt_post_trig =
814         RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
815
816 static uint16_t run_state(const struct sr_dev_inst *sdi)
817 {
818         static uint16_t previous_state;
819
820         int ret;
821         uint16_t state;
822         uint8_t buff[REG_PWM_EN - REG_RUN]; /* Width of REG_RUN. */
823         const uint8_t *rdptr;
824         const char *label;
825
826         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, sizeof(state));
827         if (ret != SR_OK) {
828                 sr_err("Cannot read run state.");
829                 return ret;
830         }
831         rdptr = buff;
832         state = read_u16le_inc(&rdptr);
833
834         /*
835          * Avoid flooding the log, only dump values as they change.
836          * The routine is called about every 50ms.
837          */
838         if (state == previous_state)
839                 return state;
840
841         previous_state = state;
842         label = NULL;
843         if ((state & runstate_mask_idle) == runstate_patt_idle)
844                 label = "idle";
845         if ((state & runstate_mask_step) == runstate_patt_pre_trig)
846                 label = "pre-trigger sampling";
847         if ((state & runstate_mask_step) == runstate_patt_wait_trig)
848                 label = "sampling, waiting for trigger";
849         if ((state & runstate_mask_step) == runstate_patt_post_trig)
850                 label = "post-trigger sampling";
851         if (label && *label)
852                 sr_dbg("Run state: 0x%04x (%s).", state, label);
853         else
854                 sr_dbg("Run state: 0x%04x.", state);
855
856         return state;
857 }
858
859 static int la2016_is_idle(const struct sr_dev_inst *sdi)
860 {
861         uint16_t state;
862
863         state = run_state(sdi);
864         if ((state & runstate_mask_idle) == runstate_patt_idle)
865                 return 1;
866
867         return 0;
868 }
869
870 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
871 {
872         int ret;
873
874         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode));
875         if (ret != SR_OK) {
876                 sr_err("Cannot configure run mode %d.", mode);
877                 return ret;
878         }
879
880         return SR_OK;
881 }
882
883 static int get_capture_info(const struct sr_dev_inst *sdi)
884 {
885         struct dev_context *devc;
886         int ret;
887         uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
888         const uint8_t *rdptr;
889
890         devc = sdi->priv;
891
892         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf));
893         if (ret != SR_OK) {
894                 sr_err("Cannot read capture info.");
895                 return ret;
896         }
897
898         rdptr = buf;
899         devc->info.n_rep_packets = read_u32le_inc(&rdptr);
900         devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
901         devc->info.write_pos = read_u32le_inc(&rdptr);
902
903         sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x/%d.",
904                 devc->info.n_rep_packets, devc->info.n_rep_packets,
905                 devc->info.n_rep_packets_before_trigger,
906                 devc->info.n_rep_packets_before_trigger,
907                 devc->info.write_pos, devc->info.write_pos);
908
909         if (devc->info.n_rep_packets % devc->packets_per_chunk) {
910                 sr_warn("Unexpected packets count %lu, not a multiple of %lu.",
911                         (unsigned long)devc->info.n_rep_packets,
912                         (unsigned long)devc->packets_per_chunk);
913         }
914
915         return SR_OK;
916 }
917
918 SR_PRIV int la2016_upload_firmware(const struct sr_dev_inst *sdi,
919         struct sr_context *sr_ctx, libusb_device *dev, gboolean skip_upload)
920 {
921         struct dev_context *devc;
922         uint16_t pid;
923         char *fw;
924         int ret;
925
926         devc = sdi ? sdi->priv : NULL;
927         if (!devc || !devc->usb_pid)
928                 return SR_ERR_ARG;
929         pid = devc->usb_pid;
930
931         fw = g_strdup_printf(MCU_FWFILE_FMT, pid);
932         sr_info("USB PID %04hx, MCU firmware '%s'.", pid, fw);
933         devc->mcu_firmware = g_strdup(fw);
934
935         if (skip_upload)
936                 ret = SR_OK;
937         else
938                 ret = ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw);
939         g_free(fw);
940         if (ret != SR_OK)
941                 return ret;
942
943         return SR_OK;
944 }
945
946 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *xfer);
947
948 static void la2016_usbxfer_release_cb(gpointer p)
949 {
950         struct libusb_transfer *xfer;
951
952         xfer = p;
953         g_free(xfer->buffer);
954         libusb_free_transfer(xfer);
955 }
956
957 static int la2016_usbxfer_release(const struct sr_dev_inst *sdi)
958 {
959         struct dev_context *devc;
960
961         devc = sdi ? sdi->priv : NULL;
962         if (!devc)
963                 return SR_ERR_ARG;
964
965         /* Release all USB transfers. */
966         g_slist_free_full(devc->transfers, la2016_usbxfer_release_cb);
967         devc->transfers = NULL;
968
969         return SR_OK;
970 }
971
972 static int la2016_usbxfer_allocate(const struct sr_dev_inst *sdi)
973 {
974         struct dev_context *devc;
975         size_t bufsize, xfercount;
976         uint8_t *buffer;
977         struct libusb_transfer *xfer;
978
979         devc = sdi ? sdi->priv : NULL;
980         if (!devc)
981                 return SR_ERR_ARG;
982
983         /* Transfers were already allocated before? */
984         if (devc->transfers)
985                 return SR_OK;
986
987         /*
988          * Allocate all USB transfers and their buffers. Arrange for a
989          * buffer size which is within the device's capabilities, and
990          * is a multiple of the USB endpoint's size, to make use of the
991          * RAW_IO performance feature.
992          *
993          * Implementation detail: The LA2016_USB_BUFSZ value happens
994          * to match all those constraints. No additional arithmetics is
995          * required in this location.
996          */
997         bufsize = LA2016_USB_BUFSZ;
998         xfercount = LA2016_USB_XFER_COUNT;
999         while (xfercount--) {
1000                 buffer = g_try_malloc(bufsize);
1001                 if (!buffer) {
1002                         sr_err("Cannot allocate USB transfer buffer.");
1003                         return SR_ERR_MALLOC;
1004                 }
1005                 xfer = libusb_alloc_transfer(0);
1006                 if (!xfer) {
1007                         sr_err("Cannot allocate USB transfer.");
1008                         g_free(buffer);
1009                         return SR_ERR_MALLOC;
1010                 }
1011                 xfer->buffer = buffer;
1012                 devc->transfers = g_slist_append(devc->transfers, xfer);
1013         }
1014         devc->transfer_bufsize = bufsize;
1015
1016         return SR_OK;
1017 }
1018
1019 static int la2016_usbxfer_cancel_all(const struct sr_dev_inst *sdi)
1020 {
1021         struct dev_context *devc;
1022         GSList *l;
1023         struct libusb_transfer *xfer;
1024
1025         devc = sdi ? sdi->priv : NULL;
1026         if (!devc)
1027                 return SR_ERR_ARG;
1028
1029         /* Unconditionally cancel the transfer. Ignore errors. */
1030         for (l = devc->transfers; l; l = l->next) {
1031                 xfer = l->data;
1032                 if (!xfer)
1033                         continue;
1034                 libusb_cancel_transfer(xfer);
1035         }
1036
1037         return SR_OK;
1038 }
1039
1040 static int la2016_usbxfer_resubmit(const struct sr_dev_inst *sdi,
1041         struct libusb_transfer *xfer)
1042 {
1043         struct dev_context *devc;
1044         struct sr_usb_dev_inst *usb;
1045         libusb_transfer_cb_fn cb;
1046         int ret;
1047
1048         devc = sdi ? sdi->priv : NULL;
1049         usb = sdi ? sdi->conn : NULL;
1050         if (!devc || !usb)
1051                 return SR_ERR_ARG;
1052
1053         if (!xfer)
1054                 return SR_ERR_ARG;
1055
1056         cb = receive_transfer;
1057         libusb_fill_bulk_transfer(xfer, usb->devhdl,
1058                 USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1059                 xfer->buffer, devc->transfer_bufsize,
1060                 cb, (void *)sdi, CAPTURE_TIMEOUT_MS);
1061         ret = libusb_submit_transfer(xfer);
1062         if (ret != 0) {
1063                 sr_err("Cannot submit USB transfer: %s.",
1064                         libusb_error_name(ret));
1065                 return SR_ERR_IO;
1066         }
1067
1068         return SR_OK;
1069 }
1070
1071 static int la2016_usbxfer_submit_all(const struct sr_dev_inst *sdi)
1072 {
1073         struct dev_context *devc;
1074         GSList *l;
1075         struct libusb_transfer *xfer;
1076         int ret;
1077
1078         devc = sdi ? sdi->priv : NULL;
1079         if (!devc)
1080                 return SR_ERR_ARG;
1081
1082         for (l = devc->transfers; l; l = l->next) {
1083                 xfer = l->data;
1084                 if (!xfer)
1085                         return SR_ERR_ARG;
1086                 ret = la2016_usbxfer_resubmit(sdi, xfer);
1087                 if (ret != SR_OK)
1088                         return ret;
1089         }
1090
1091         return SR_OK;
1092 }
1093
1094 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi,
1095         double voltage)
1096 {
1097         int ret;
1098         uint8_t cmd;
1099
1100         ret = set_threshold_voltage(sdi, voltage);
1101         if (ret != SR_OK)
1102                 return ret;
1103
1104         cmd = CAPTMODE_TO_RAM;
1105         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd));
1106         if (ret != SR_OK) {
1107                 sr_err("Cannot send command to stop sampling.");
1108                 return ret;
1109         }
1110
1111         ret = set_trigger_config(sdi);
1112         if (ret != SR_OK)
1113                 return ret;
1114
1115         ret = set_sample_config(sdi);
1116         if (ret != SR_OK)
1117                 return ret;
1118
1119         return SR_OK;
1120 }
1121
1122 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
1123 {
1124         int ret;
1125
1126         ret = la2016_usbxfer_allocate(sdi);
1127         if (ret != SR_OK)
1128                 return ret;
1129
1130         ret = set_run_mode(sdi, RUNMODE_RUN);
1131         if (ret != SR_OK)
1132                 return ret;
1133
1134         return SR_OK;
1135 }
1136
1137 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
1138 {
1139         int ret;
1140
1141         ret = set_run_mode(sdi, RUNMODE_HALT);
1142         if (ret != SR_OK)
1143                 return ret;
1144
1145         return SR_OK;
1146 }
1147
1148 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
1149 {
1150         int ret;
1151
1152         ret = la2016_stop_acquisition(sdi);
1153         if (ret != SR_OK)
1154                 return ret;
1155
1156         (void)la2016_usbxfer_cancel_all(sdi);
1157
1158         return SR_OK;
1159 }
1160
1161 static int la2016_start_download(const struct sr_dev_inst *sdi)
1162 {
1163         struct dev_context *devc;
1164         int ret;
1165         uint8_t wrbuf[REG_SAMPLING - REG_BULK]; /* Width of REG_BULK. */
1166         uint8_t *wrptr;
1167
1168         devc = sdi->priv;
1169
1170         ret = get_capture_info(sdi);
1171         if (ret != SR_OK)
1172                 return ret;
1173
1174         devc->n_transfer_packets_to_read = devc->info.n_rep_packets;
1175         devc->n_transfer_packets_to_read /= devc->packets_per_chunk;
1176         devc->n_bytes_to_read = devc->n_transfer_packets_to_read;
1177         devc->n_bytes_to_read *= TRANSFER_PACKET_LENGTH;
1178         devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
1179         devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
1180
1181         sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
1182                 devc->n_transfer_packets_to_read, devc->read_pos);
1183
1184         ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
1185         if (ret != SR_OK) {
1186                 sr_err("Cannot reset USB bulk state.");
1187                 return ret;
1188         }
1189         sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
1190                 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
1191         wrptr = wrbuf;
1192         write_u32le_inc(&wrptr, devc->read_pos);
1193         write_u32le_inc(&wrptr, devc->n_bytes_to_read);
1194         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf);
1195         if (ret != SR_OK) {
1196                 sr_err("Cannot send USB bulk config.");
1197                 return ret;
1198         }
1199
1200         ret = la2016_usbxfer_submit_all(sdi);
1201         if (ret != SR_OK) {
1202                 sr_err("Cannot submit USB bulk transfers.");
1203                 return ret;
1204         }
1205
1206         ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0);
1207         if (ret != SR_OK) {
1208                 sr_err("Cannot start USB bulk transfers.");
1209                 return ret;
1210         }
1211
1212         return SR_OK;
1213 }
1214
1215 /*
1216  * A chunk (received via USB) contains a number of transfers (USB length
1217  * divided by 16) which contain a number of packets (5 per transfer) which
1218  * contain a number of samples (8bit repeat count per 16bit sample data).
1219  */
1220 static void send_chunk(struct sr_dev_inst *sdi,
1221         const uint8_t *data_buffer, size_t data_length)
1222 {
1223         struct dev_context *devc;
1224         size_t num_xfers, num_pkts;
1225         const uint8_t *rp;
1226         uint32_t sample_value;
1227         size_t repetitions;
1228         uint8_t sample_buff[sizeof(sample_value)];
1229
1230         devc = sdi->priv;
1231
1232         /* Ignore incoming USB data after complete sample data download. */
1233         if (devc->download_finished)
1234                 return;
1235
1236         if (devc->trigger_involved && !devc->trigger_marked && devc->info.n_rep_packets_before_trigger == 0) {
1237                 feed_queue_logic_send_trigger(devc->feed_queue);
1238                 devc->trigger_marked = TRUE;
1239         }
1240
1241         /*
1242          * Adjust the number of remaining bytes to read from the device
1243          * before the processing of the currently received chunk affects
1244          * the variable which holds the number of received bytes.
1245          */
1246         if (data_length > devc->n_bytes_to_read)
1247                 devc->n_bytes_to_read = 0;
1248         else
1249                 devc->n_bytes_to_read -= data_length;
1250
1251         /* Process the received chunk of capture data. */
1252         sample_value = 0;
1253         rp = data_buffer;
1254         num_xfers = data_length / TRANSFER_PACKET_LENGTH;
1255         while (num_xfers--) {
1256                 num_pkts = devc->packets_per_chunk;
1257                 while (num_pkts--) {
1258
1259                         /* TODO Verify 32channel layout. */
1260                         if (devc->model->channel_count == 32)
1261                                 sample_value = read_u32le_inc(&rp);
1262                         else if (devc->model->channel_count == 16)
1263                                 sample_value = read_u16le_inc(&rp);
1264                         repetitions = read_u8_inc(&rp);
1265
1266                         devc->total_samples += repetitions;
1267
1268                         write_u32le(sample_buff, sample_value);
1269                         feed_queue_logic_submit(devc->feed_queue,
1270                                 sample_buff, repetitions);
1271                         sr_sw_limits_update_samples_read(&devc->sw_limits,
1272                                 repetitions);
1273
1274                         if (devc->trigger_involved && !devc->trigger_marked) {
1275                                 if (!--devc->n_reps_until_trigger) {
1276                                         feed_queue_logic_send_trigger(devc->feed_queue);
1277                                         devc->trigger_marked = TRUE;
1278                                         sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
1279                                                 devc->total_samples,
1280                                                 (double)devc->total_samples / devc->samplerate * 1e3);
1281                                 }
1282                         }
1283                 }
1284                 (void)read_u8_inc(&rp); /* Skip sequence number. */
1285         }
1286
1287         /*
1288          * Check for several conditions which shall terminate the
1289          * capture data download: When the amount of capture data in
1290          * the device is exhausted. When the user specified samples
1291          * count limit is reached.
1292          */
1293         if (!devc->n_bytes_to_read) {
1294                 devc->download_finished = TRUE;
1295         } else {
1296                 sr_dbg("%" PRIu32 " more bytes to download from the device.",
1297                         devc->n_bytes_to_read);
1298         }
1299         if (!devc->download_finished && sr_sw_limits_check(&devc->sw_limits)) {
1300                 sr_dbg("Acquisition limit reached.");
1301                 devc->download_finished = TRUE;
1302         }
1303         if (devc->download_finished) {
1304                 sr_dbg("Download finished, flushing session feed queue.");
1305                 feed_queue_logic_flush(devc->feed_queue);
1306         }
1307         sr_dbg("Total samples after chunk: %" PRIu64 ".", devc->total_samples);
1308 }
1309
1310 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
1311 {
1312         struct sr_dev_inst *sdi;
1313         struct dev_context *devc;
1314         gboolean was_cancelled;
1315         int ret;
1316
1317         sdi = transfer->user_data;
1318         devc = sdi->priv;
1319
1320         was_cancelled = transfer->status == LIBUSB_TRANSFER_CANCELLED;
1321         sr_dbg("receive_transfer(): status %s received %d bytes.",
1322                 libusb_error_name(transfer->status), transfer->actual_length);
1323         /*
1324          * Implementation detail: A USB transfer timeout is not fatal
1325          * here. We just process whatever was received, empty input is
1326          * perfectly acceptable. Reaching (or exceeding) the sw limits
1327          * or exhausting the device's captured data will complete the
1328          * sample data download.
1329          */
1330         send_chunk(sdi, transfer->buffer, transfer->actual_length);
1331
1332         /*
1333          * Re-submit completed transfers (regardless of timeout or
1334          * data reception), unless the transfer was cancelled when
1335          * the acquisition was terminated or has completed.
1336          */
1337         if (!was_cancelled && !devc->download_finished) {
1338                 ret = la2016_usbxfer_resubmit(sdi, transfer);
1339                 if (ret == SR_OK)
1340                         return;
1341                 devc->download_finished = TRUE;
1342         }
1343 }
1344
1345 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1346 {
1347         const struct sr_dev_inst *sdi;
1348         struct dev_context *devc;
1349         struct drv_context *drvc;
1350         struct timeval tv;
1351         int ret;
1352
1353         (void)fd;
1354         (void)revents;
1355
1356         sdi = cb_data;
1357         devc = sdi->priv;
1358         drvc = sdi->driver->context;
1359
1360         /*
1361          * Wait for the acquisition to complete in hardware.
1362          * Periodically check a potentially configured msecs timeout.
1363          */
1364         if (!devc->completion_seen) {
1365                 if (!la2016_is_idle(sdi)) {
1366                         if (sr_sw_limits_check(&devc->sw_limits)) {
1367                                 devc->sw_limits.limit_msec = 0;
1368                                 sr_dbg("Limit reached. Stopping acquisition.");
1369                                 la2016_stop_acquisition(sdi);
1370                         }
1371                         /* Not yet ready for sample data download. */
1372                         return TRUE;
1373                 }
1374                 sr_dbg("Acquisition completion seen (hardware).");
1375                 devc->sw_limits.limit_msec = 0;
1376                 devc->completion_seen = TRUE;
1377                 devc->download_finished = FALSE;
1378                 devc->trigger_marked = FALSE;
1379                 devc->total_samples = 0;
1380
1381                 la2016_dump_fpga_registers(sdi, "acquisition complete", 0, 0);
1382
1383                 /* Initiate the download of acquired sample data. */
1384                 std_session_send_df_frame_begin(sdi);
1385                 devc->frame_begin_sent = TRUE;
1386                 ret = la2016_start_download(sdi);
1387                 if (ret != SR_OK) {
1388                         sr_err("Cannot start acquisition data download.");
1389                         return FALSE;
1390                 }
1391                 sr_dbg("Acquisition data download started.");
1392
1393                 return TRUE;
1394         }
1395
1396         /* Handle USB reception. Drives sample data download. */
1397         memset(&tv, 0, sizeof(tv));
1398         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1399
1400         /* Postprocess completion of sample data download. */
1401         if (devc->download_finished) {
1402                 sr_dbg("Download finished, post processing.");
1403
1404                 la2016_stop_acquisition(sdi);
1405                 usb_source_remove(sdi->session, drvc->sr_ctx);
1406
1407                 la2016_usbxfer_cancel_all(sdi);
1408                 memset(&tv, 0, sizeof(tv));
1409                 libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1410
1411                 feed_queue_logic_flush(devc->feed_queue);
1412                 feed_queue_logic_free(devc->feed_queue);
1413                 devc->feed_queue = NULL;
1414                 if (devc->frame_begin_sent) {
1415                         std_session_send_df_frame_end(sdi);
1416                         devc->frame_begin_sent = FALSE;
1417                 }
1418                 std_session_send_df_end(sdi);
1419
1420                 sr_dbg("Download finished, done post processing.");
1421         }
1422
1423         return TRUE;
1424 }
1425
1426 SR_PRIV int la2016_identify_device(const struct sr_dev_inst *sdi,
1427         gboolean show_message)
1428 {
1429         struct dev_context *devc;
1430         uint8_t buf[8]; /* Larger size of manuf date and device type magic. */
1431         size_t rdoff, rdlen;
1432         const uint8_t *rdptr;
1433         uint8_t date_yy, date_mm;
1434         uint8_t dinv_yy, dinv_mm;
1435         uint8_t magic;
1436         size_t model_idx;
1437         const struct kingst_model *model;
1438         int ret;
1439
1440         devc = sdi->priv;
1441
1442         /*
1443          * Four EEPROM bytes at offset 0x20 are the manufacturing date,
1444          * year and month in BCD format, followed by inverted values for
1445          * consistency checks. For example bytes 20 04 df fb translate
1446          * to 2020-04. This information can help identify the vintage of
1447          * devices when unknown magic numbers are seen.
1448          */
1449         rdoff = 0x20;
1450         rdlen = 4 * sizeof(uint8_t);
1451         ret = ctrl_in(sdi, CMD_EEPROM, rdoff, 0, buf, rdlen);
1452         if (ret != SR_OK && !show_message) {
1453                 /* Non-fatal weak attempt during probe. Not worth logging. */
1454                 sr_dbg("Cannot access EEPROM.");
1455                 return SR_ERR_IO;
1456         } else if (ret != SR_OK) {
1457                 /* Failed attempt in regular use. Non-fatal. Worth logging. */
1458                 sr_err("Cannot read manufacture date in EEPROM.");
1459         } else {
1460                 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
1461                         GString *txt;
1462                         txt = sr_hexdump_new(buf, rdlen);
1463                         sr_spew("Manufacture date bytes %s.", txt->str);
1464                         sr_hexdump_free(txt);
1465                 }
1466                 rdptr = &buf[0];
1467                 date_yy = read_u8_inc(&rdptr);
1468                 date_mm = read_u8_inc(&rdptr);
1469                 dinv_yy = read_u8_inc(&rdptr);
1470                 dinv_mm = read_u8_inc(&rdptr);
1471                 sr_info("Manufacture date: 20%02hx-%02hx.", date_yy, date_mm);
1472                 if ((date_mm ^ dinv_mm) != 0xff || (date_yy ^ dinv_yy) != 0xff)
1473                         sr_warn("Manufacture date fails checksum test.");
1474         }
1475
1476         /*
1477          * Several Kingst logic analyzer devices share the same USB VID
1478          * and PID. The product ID determines which MCU firmware to load.
1479          * The MCU firmware provides access to EEPROM content which then
1480          * allows to identify the device model. Which in turn determines
1481          * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1482          * to get inspected.
1483          *
1484          * EEPROM content for model identification is kept redundantly
1485          * in memory. The values are stored in verbatim and in inverted
1486          * form, multiple copies are kept at different offsets. Example
1487          * data:
1488          *
1489          *   magic 0x08
1490          *    | ~magic 0xf7
1491          *    | |
1492          *   08f7000008f710ef
1493          *            | |
1494          *            | ~magic backup
1495          *            magic backup
1496          *
1497          * Exclusively inspecting the magic byte appears to be sufficient,
1498          * other fields seem to be 'don't care'.
1499          *
1500          *   magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1501          *   magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1502          *   magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1503          *              (latest v1.3.0 PCB, perhaps others)
1504          *   magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1505          *              (latest v1.3.0 PCB, perhaps others)
1506          *
1507          * When EEPROM content does not match the hardware configuration
1508          * (the board layout), the software may load but yield incorrect
1509          * results (like swapped channels). The FPGA bitstream itself
1510          * will authenticate with IC U10 and fail when its capabilities
1511          * do not match the hardware model. An LA1016 won't become a
1512          * LA2016 by faking its EEPROM content.
1513          */
1514         devc->identify_magic = 0;
1515         rdoff = 0x08;
1516         rdlen = 8 * sizeof(uint8_t);
1517         ret = ctrl_in(sdi, CMD_EEPROM, rdoff, 0, &buf, rdlen);
1518         if (ret != SR_OK) {
1519                 sr_err("Cannot read EEPROM device identifier bytes.");
1520                 return ret;
1521         }
1522         if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
1523                 GString *txt;
1524                 txt = sr_hexdump_new(buf, rdlen);
1525                 sr_spew("EEPROM magic bytes %s.", txt->str);
1526                 sr_hexdump_free(txt);
1527         }
1528         if ((buf[0] ^ buf[1]) == 0xff) {
1529                 /* Primary copy of magic passes complement check. */
1530                 magic = buf[0];
1531                 sr_dbg("Using primary magic, value %d.", (int)magic);
1532         } else if ((buf[4] ^ buf[5]) == 0xff) {
1533                 /* Backup copy of magic passes complement check. */
1534                 magic = buf[4];
1535                 sr_dbg("Using backup magic, value %d.", (int)magic);
1536         } else {
1537                 sr_err("Cannot find consistent device type identification.");
1538                 magic = 0;
1539         }
1540         devc->identify_magic = magic;
1541
1542         devc->model = NULL;
1543         for (model_idx = 0; model_idx < ARRAY_SIZE(models); model_idx++) {
1544                 model = &models[model_idx];
1545                 if (model->magic != magic)
1546                         continue;
1547                 devc->model = model;
1548                 sr_info("Model '%s', %zu channels, max %" PRIu64 "MHz.",
1549                         model->name, model->channel_count,
1550                         model->samplerate / SR_MHZ(1));
1551                 devc->fpga_bitstream = g_strdup_printf(FPGA_FWFILE_FMT,
1552                         model->fpga_stem);
1553                 sr_info("FPGA bitstream file '%s'.", devc->fpga_bitstream);
1554                 break;
1555         }
1556         if (!devc->model) {
1557                 sr_err("Cannot identify as one of the supported models.");
1558                 return SR_ERR_DATA;
1559         }
1560
1561         return SR_OK;
1562 }
1563
1564 SR_PRIV int la2016_init_hardware(const struct sr_dev_inst *sdi)
1565 {
1566         struct dev_context *devc;
1567         const char *bitstream_fn;
1568         int ret;
1569         uint16_t state;
1570
1571         devc = sdi->priv;
1572         bitstream_fn = devc ? devc->fpga_bitstream : "";
1573
1574         ret = check_fpga_bitstream(sdi);
1575         if (ret != SR_OK) {
1576                 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1577                 if (ret != SR_OK) {
1578                         sr_err("Cannot upload FPGA bitstream.");
1579                         return ret;
1580                 }
1581         }
1582         ret = enable_fpga_bitstream(sdi);
1583         if (ret != SR_OK) {
1584                 sr_err("Cannot enable FPGA bitstream after upload.");
1585                 return ret;
1586         }
1587
1588         state = run_state(sdi);
1589         if ((state & 0xfff0) != 0x85e0) {
1590                 sr_warn("Unexpected run state, want 0x85eX, got 0x%04x.", state);
1591         }
1592
1593         ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
1594         if (ret != SR_OK) {
1595                 sr_err("Cannot reset USB bulk transfer.");
1596                 return ret;
1597         }
1598
1599         sr_dbg("Device should be initialized.");
1600
1601         return SR_OK;
1602 }
1603
1604 SR_PRIV int la2016_deinit_hardware(const struct sr_dev_inst *sdi)
1605 {
1606         int ret;
1607
1608         ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0);
1609         if (ret != SR_OK) {
1610                 sr_err("Cannot deinitialize device's FPGA.");
1611                 return ret;
1612         }
1613
1614         return SR_OK;
1615 }
1616
1617 SR_PRIV void la2016_release_resources(const struct sr_dev_inst *sdi)
1618 {
1619         (void)la2016_usbxfer_release(sdi);
1620 }
1621
1622 SR_PRIV int la2016_write_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
1623 {
1624         return set_pwm_config(sdi, idx);
1625 }