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