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