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