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