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