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