]> sigrok.org Git - libsigrok.git/blame - src/hardware/kingst-la2016/protocol.c
kingst-la2016: renames to better reflect sequence of activities
[libsigrok.git] / src / hardware / kingst-la2016 / protocol.c
CommitLineData
f2cd2deb
FS
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2020 Florian Schmidt <schmidt_florian@gmx.de>
5 * Copyright (C) 2013 Marcus Comstedt <marcus@mc.pp.se>
6 * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
7 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23#include <config.h>
a7740b06 24
f2cd2deb 25#include <libsigrok/libsigrok.h>
a7740b06
GS
26#include <string.h>
27
f2cd2deb
FS
28#include "libsigrok-internal.h"
29#include "protocol.h"
30
f2cd2deb 31#define UC_FIRMWARE "kingst-la-%04x.fw"
9de389b1
KG
32#define FPGA_FW_LA2016 "kingst-la2016-fpga.bitstream"
33#define FPGA_FW_LA2016A "kingst-la2016a1-fpga.bitstream"
8b172e78
KG
34#define FPGA_FW_LA1016 "kingst-la1016-fpga.bitstream"
35#define FPGA_FW_LA1016A "kingst-la1016a1-fpga.bitstream"
f2cd2deb 36
852c7d14 37/* Maximum device capabilities. May differ between models. */
8b172e78
KG
38#define MAX_SAMPLE_RATE_LA2016 SR_MHZ(200)
39#define MAX_SAMPLE_RATE_LA1016 SR_MHZ(100)
e9430410
GS
40#define MAX_SAMPLE_DEPTH 10e9
41#define MAX_PWM_FREQ SR_MHZ(20)
42#define PWM_CLOCK SR_MHZ(200) /* 200MHz for both LA2016 and LA1016 */
f2cd2deb 43
852c7d14
GS
44/*
45 * Default device configuration. Must be applicable to any of the
46 * supported devices (no model specific default values yet). Specific
47 * firmware implementation details unfortunately won't let us detect
48 * and keep using previously configured values.
49 */
50#define LA2016_DFLT_SAMPLERATE SR_MHZ(100)
51#define LA2016_DFLT_SAMPLEDEPTH (5 * 1000 * 1000)
52#define LA2016_DFLT_CAPT_RATIO 5 /* Capture ratio, in percent. */
53
54/* TODO
55 * What is the origin and motivation of that 128Mi literal? What is its
56 * unit? How does it relate to a device's hardware capabilities? How to
57 * map the 1GiB of RAM of an LA2016 (at 16 channels) to the 128Mi value?
58 * It cannot be sample count. Is it memory size in bytes perhaps?
59 */
60#define LA2016_PRE_MEM_LIMIT_BASE (128 * 1024 * 1024)
61
96dc954e 62/* USB vendor class control requests, executed by the Cypress FX2 MCU. */
84fe94bd 63#define CMD_FPGA_ENABLE 0x10
96dc954e
GS
64#define CMD_FPGA_SPI 0x20 /* R/W access to FPGA registers via SPI. */
65#define CMD_BULK_START 0x30 /* Start sample data download via USB EP6 IN. */
66#define CMD_BULK_RESET 0x38 /* Flush FIFO of FX2 USB EP6 IN. */
67#define CMD_FPGA_INIT 0x50 /* Used before and after FPGA bitstream upload. */
68#define CMD_KAUTH 0x60 /* Communicate to auth IC (U10). Not used. */
69#define CMD_EEPROM 0xa2 /* R/W access to EEPROM content. */
00849545 70
42f6dd55 71/*
96dc954e
GS
72 * FPGA register addresses (base addresses when registers span multiple
73 * bytes, in that case data is kept in little endian format). Passed to
74 * CMD_FPGA_SPI requests. The FX2 MCU transparently handles the detail
75 * of SPI transfers encoding the read (1) or write (0) direction in the
76 * MSB of the address field. There are some 60 byte-wide FPGA registers.
d6f89d4b
GS
77 *
78 * Unfortunately the FPGA registers change their meaning between the
79 * read and write directions of access, or exclusively provide one of
80 * these directions and not the other. This is an arbitrary vendor's
81 * choice, there is nothing which the sigrok driver could do about it.
82 * Values written to registers typically cannot get read back, neither
83 * verified after writing a configuration, nor queried upon startup for
84 * automatic detection of the current configuration. Neither appear to
85 * be there echo registers for presence and communication checks, nor
86 * version identifying registers, as far as we know.
42f6dd55 87 */
96dc954e
GS
88#define REG_RUN 0x00 /* Read capture status, write start capture. */
89#define REG_PWM_EN 0x02 /* User PWM channels on/off. */
90#define REG_CAPT_MODE 0x03 /* Write 0x00 capture to SDRAM, 0x01 streaming. */
91#define REG_BULK 0x08 /* Write start addr, byte count to download samples. */
92#define REG_SAMPLING 0x10 /* Write capture config, read capture SDRAM location. */
93#define REG_TRIGGER 0x20 /* write level and edge trigger config. */
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
852c7d14
GS
98/* Bit patterns to write to REG_RUN, setup run mode. */
99#define RUNMODE_HALT 0x00
100#define RUNMODE_RUN 0x03
101
b711fd8e
GS
102/* Bit patterns when reading from REG_RUN, get run state. */
103#define RUNSTATE_IDLE_BIT (1UL << 0)
104#define RUNSTATE_DRAM_BIT (1UL << 1)
105#define RUNSTATE_TRGD_BIT (1UL << 2)
106#define RUNSTATE_POST_BIT (1UL << 3)
107
f2cd2deb 108static int ctrl_in(const struct sr_dev_inst *sdi,
1ed93110
GS
109 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
110 void *data, uint16_t wLength)
f2cd2deb
FS
111{
112 struct sr_usb_dev_inst *usb;
113 int ret;
114
115 usb = sdi->conn;
116
852c7d14
GS
117 if ((ret = libusb_control_transfer(usb->devhdl,
118 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
f2cd2deb
FS
119 bRequest, wValue, wIndex, (unsigned char *)data, wLength,
120 DEFAULT_TIMEOUT_MS)) != wLength) {
91f73872
GS
121 sr_dbg("USB ctrl in: %d bytes, req %d val %#x idx %d: %s.",
122 wLength, bRequest, wValue, wIndex,
123 libusb_error_name(ret));
124 sr_err("Cannot read %d bytes from USB: %s.",
125 wLength, libusb_error_name(ret));
f2cd2deb
FS
126 return SR_ERR;
127 }
128
129 return SR_OK;
130}
131
132static int ctrl_out(const struct sr_dev_inst *sdi,
1ed93110
GS
133 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
134 void *data, uint16_t wLength)
f2cd2deb
FS
135{
136 struct sr_usb_dev_inst *usb;
137 int ret;
138
139 usb = sdi->conn;
140
852c7d14
GS
141 if ((ret = libusb_control_transfer(usb->devhdl,
142 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
f2cd2deb
FS
143 bRequest, wValue, wIndex, (unsigned char*)data, wLength,
144 DEFAULT_TIMEOUT_MS)) != wLength) {
91f73872
GS
145 sr_dbg("USB ctrl out: %d bytes, req %d val %#x idx %d: %s.",
146 wLength, bRequest, wValue, wIndex,
147 libusb_error_name(ret));
148 sr_err("Cannot write %d bytes to USB: %s.",
149 wLength, libusb_error_name(ret));
f2cd2deb
FS
150 return SR_ERR;
151 }
152
153 return SR_OK;
154}
155
d6f89d4b
GS
156/*
157 * Check the necessity for FPGA bitstream upload, because another upload
158 * would take some 600ms which is undesirable after program startup. Try
159 * to access some FPGA registers and check the values' plausibility. The
160 * check should fail on the safe side, request another upload when in
161 * doubt. A positive response (the request to continue operation with the
162 * currently active bitstream) should be conservative. Accessing multiple
163 * registers is considered cheap compared to the cost of bitstream upload.
164 *
165 * It helps though that both the vendor software and the sigrok driver
166 * use the same bundle of MCU firmware and FPGA bitstream for any of the
167 * supported models. We don't expect to successfully communicate to the
168 * device yet disagree on its protocol. Ideally we would access version
169 * identifying registers for improved robustness, but are not aware of
170 * any. A bitstream reload can always be forced by a power cycle.
171 */
172static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
173{
174 uint8_t init_rsp;
175 int ret;
176 uint16_t run_state;
177 uint8_t pwm_en;
178 size_t read_len;
179 uint8_t buff[sizeof(run_state)];
180 const uint8_t *rdptr;
181
182 sr_dbg("Checking operation of the FPGA bitstream.");
183
852c7d14 184 init_rsp = ~0;
d6f89d4b
GS
185 ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
186 if (ret != SR_OK || init_rsp != 0) {
187 sr_dbg("FPGA init query failed, or unexpected response.");
188 return SR_ERR_IO;
189 }
190
191 read_len = sizeof(run_state);
192 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, read_len);
193 if (ret != SR_OK) {
194 sr_dbg("FPGA register access failed (run state).");
195 return SR_ERR_IO;
196 }
197 rdptr = buff;
198 run_state = read_u16le_inc(&rdptr);
199 sr_spew("FPGA register: run state 0x%04x.", run_state);
200 if (run_state && (run_state & 0x3) != 0x1) {
201 sr_dbg("Unexpected FPGA register content (run state).");
202 return SR_ERR_DATA;
203 }
204 if (run_state && (run_state & ~0xf) != 0x85e0) {
205 sr_dbg("Unexpected FPGA register content (run state).");
206 return SR_ERR_DATA;
207 }
208
209 read_len = sizeof(pwm_en);
210 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, buff, read_len);
211 if (ret != SR_OK) {
212 sr_dbg("FPGA register access failed (PWM enable).");
213 return SR_ERR_IO;
214 }
215 rdptr = buff;
216 pwm_en = read_u8_inc(&rdptr);
217 sr_spew("FPGA register: PWM enable 0x%02x.", pwm_en);
218 if ((pwm_en & 0x3) != 0x0) {
219 sr_dbg("Unexpected FPGA register content (PWM enable).");
220 return SR_ERR_DATA;
221 }
222
223 sr_info("Could re-use current FPGA bitstream. No upload required.");
224 return SR_OK;
225}
226
1ed93110
GS
227static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
228 const char *bitstream_fname)
f2cd2deb
FS
229{
230 struct drv_context *drvc;
231 struct sr_usb_dev_inst *usb;
232 struct sr_resource bitstream;
b0d0131e 233 uint32_t bitstream_size;
c3d40037
HK
234 uint8_t buffer[sizeof(uint32_t)];
235 uint8_t *wrptr;
f2cd2deb 236 uint8_t block[4096];
3f48ab02
FS
237 int len, act_len;
238 unsigned int pos;
f2cd2deb 239 int ret;
b0d0131e 240 unsigned int zero_pad_to;
f2cd2deb
FS
241
242 drvc = sdi->driver->context;
243 usb = sdi->conn;
244
9de389b1 245 sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
f2cd2deb 246
9de389b1 247 ret = sr_resource_open(drvc->sr_ctx, &bitstream, SR_RESOURCE_FIRMWARE, bitstream_fname);
f2cd2deb 248 if (ret != SR_OK) {
91f73872 249 sr_err("Cannot find FPGA bitstream %s.", bitstream_fname);
f2cd2deb
FS
250 return ret;
251 }
252
b0d0131e 253 bitstream_size = (uint32_t)bitstream.size;
c3d40037 254 wrptr = buffer;
b0d0131e 255 write_u32le_inc(&wrptr, bitstream_size);
00849545 256 if ((ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer)) != SR_OK) {
91f73872 257 sr_err("Cannot initiate FPGA bitstream upload.");
f2cd2deb
FS
258 sr_resource_close(drvc->sr_ctx, &bitstream);
259 return ret;
260 }
b0d0131e
GS
261 zero_pad_to = bitstream_size;
262 zero_pad_to += LA2016_EP2_PADDING - 1;
263 zero_pad_to /= LA2016_EP2_PADDING;
264 zero_pad_to *= LA2016_EP2_PADDING;
f2cd2deb
FS
265
266 pos = 0;
267 while (1) {
3f48ab02
FS
268 if (pos < bitstream.size) {
269 len = (int)sr_resource_read(drvc->sr_ctx, &bitstream, &block, sizeof(block));
270 if (len < 0) {
91f73872 271 sr_err("Cannot read FPGA bitstream.");
3f48ab02
FS
272 sr_resource_close(drvc->sr_ctx, &bitstream);
273 return SR_ERR;
274 }
275 } else {
96dc954e 276 /* Zero-pad until 'zero_pad_to'. */
3f48ab02
FS
277 len = zero_pad_to - pos;
278 if ((unsigned)len > sizeof(block))
279 len = sizeof(block);
280 memset(&block, 0, len);
f2cd2deb
FS
281 }
282 if (len == 0)
283 break;
284
852c7d14 285 ret = libusb_bulk_transfer(usb->devhdl, USB_EP_FPGA_BITSTREAM,
1ed93110 286 &block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
f2cd2deb 287 if (ret != 0) {
91f73872
GS
288 sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
289 pos, (int)len, libusb_error_name(ret));
f2cd2deb
FS
290 ret = SR_ERR;
291 break;
292 }
293 if (act_len != len) {
91f73872
GS
294 sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
295 pos, (int)len, act_len);
f2cd2deb
FS
296 ret = SR_ERR;
297 break;
298 }
299 pos += len;
300 }
301 sr_resource_close(drvc->sr_ctx, &bitstream);
302 if (ret != 0)
303 return ret;
91f73872
GS
304 sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.",
305 bitstream.size);
f2cd2deb 306
d6f89d4b
GS
307 return SR_OK;
308}
309
310static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
311{
312 int ret;
313 uint8_t cmd_resp;
314
00849545 315 if ((ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &cmd_resp, sizeof(cmd_resp))) != SR_OK) {
91f73872 316 sr_err("Cannot read response after FPGA bitstream upload.");
f2cd2deb
FS
317 return ret;
318 }
3f48ab02 319 if (cmd_resp != 0) {
91f73872
GS
320 sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
321 cmd_resp);
3f48ab02
FS
322 return SR_ERR;
323 }
852c7d14 324 g_usleep(30 * 1000);
f2cd2deb 325
00849545 326 if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0)) != SR_OK) {
91f73872 327 sr_err("Cannot enable FPGA after bitstream upload.");
f2cd2deb
FS
328 return ret;
329 }
852c7d14 330 g_usleep(40 * 1000);
d6f89d4b 331
f2cd2deb
FS
332 return SR_OK;
333}
334
335static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
336{
337 struct dev_context *devc;
f2cd2deb
FS
338 int ret;
339
340 devc = sdi->priv;
f2cd2deb 341
1ed93110 342 uint16_t duty_R79, duty_R56;
f2ad79d1
KG
343 uint8_t buf[2 * sizeof(uint16_t)];
344 uint8_t *wrptr;
345
96dc954e 346 /* Clamp threshold setting to valid range for LA2016. */
f2ad79d1
KG
347 if (voltage > 4.0) {
348 voltage = 4.0;
1ed93110 349 } else if (voltage < -4.0) {
f2ad79d1
KG
350 voltage = -4.0;
351 }
352
353 /*
96dc954e
GS
354 * Two PWM output channels feed one DAC which generates a bias
355 * voltage, which offsets the input probe's voltage level, and
356 * in combination with the FPGA pins' fixed threshold result in
357 * a programmable input threshold from the user's perspective.
358 * The PWM outputs can be seen on R79 and R56 respectively, the
359 * frequency is 100kHz and the duty cycle varies. The R79 PWM
360 * uses three discrete settings. The R56 PWM varies with desired
361 * thresholds and depends on the R79 PWM configuration. See the
362 * schematics comments which discuss the formulae.
f2ad79d1
KG
363 */
364 if (voltage >= 2.9) {
96dc954e 365 duty_R79 = 0; /* PWM off (0V). */
f2ad79d1 366 duty_R56 = (uint16_t)(302 * voltage - 363);
c34f4a89 367 } else if (voltage > -0.4) {
96dc954e 368 duty_R79 = 0x00f2; /* 25% duty cycle. */
f2ad79d1 369 duty_R56 = (uint16_t)(302 * voltage + 121);
c34f4a89
GS
370 } else {
371 duty_R79 = 0x02d7; /* 72% duty cycle. */
372 duty_R56 = (uint16_t)(302 * voltage + 1090);
f2ad79d1
KG
373 }
374
96dc954e 375 /* Clamp duty register values to sensible limits. */
f2ad79d1
KG
376 if (duty_R56 < 10) {
377 duty_R56 = 10;
1ed93110 378 } else if (duty_R56 > 1100) {
f2ad79d1
KG
379 duty_R56 = 1100;
380 }
381
91f73872
GS
382 sr_dbg("Set threshold voltage %.2fV.", voltage);
383 sr_dbg("Duty cycle values: R56 0x%04x, R79 0x%04x.", duty_R56, duty_R79);
f2ad79d1
KG
384
385 wrptr = buf;
386 write_u16le_inc(&wrptr, duty_R56);
387 write_u16le_inc(&wrptr, duty_R79);
388
389 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_THRESHOLD, 0, buf, wrptr - buf);
f2cd2deb 390 if (ret != SR_OK) {
91f73872 391 sr_err("Cannot set threshold voltage %.2fV.", voltage);
f2cd2deb
FS
392 return ret;
393 }
394 devc->threshold_voltage = voltage;
395
396 return SR_OK;
397}
398
399static int enable_pwm(const struct sr_dev_inst *sdi, uint8_t p1, uint8_t p2)
400{
401 struct dev_context *devc;
402 uint8_t cfg;
403 int ret;
404
405 devc = sdi->priv;
406 cfg = 0;
407
408 if (p1) cfg |= 1 << 0;
409 if (p2) cfg |= 1 << 1;
410
91f73872 411 sr_dbg("Set PWM enable %d %d. Config 0x%02x.", p1, p2, cfg);
42f6dd55 412 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, &cfg, sizeof(cfg));
f2cd2deb 413 if (ret != SR_OK) {
91f73872 414 sr_err("Cannot setup PWM enabled state.");
f2cd2deb
FS
415 return ret;
416 }
417 devc->pwm_setting[0].enabled = (p1) ? 1 : 0;
418 devc->pwm_setting[1].enabled = (p2) ? 1 : 0;
419
420 return SR_OK;
421}
422
1ed93110
GS
423static int set_pwm(const struct sr_dev_inst *sdi, uint8_t which,
424 float freq, float duty)
f2cd2deb 425{
42f6dd55 426 int CTRL_PWM[] = { REG_PWM1, REG_PWM2 };
f2cd2deb
FS
427 struct dev_context *devc;
428 pwm_setting_dev_t cfg;
429 pwm_setting_t *setting;
430 int ret;
c3d40037
HK
431 uint8_t buf[2 * sizeof(uint32_t)];
432 uint8_t *wrptr;
f2cd2deb
FS
433
434 devc = sdi->priv;
435
852c7d14 436 if (which < 1 || which > ARRAY_SIZE(CTRL_PWM)) {
91f73872 437 sr_err("Invalid PWM channel: %d.", which);
f2cd2deb
FS
438 return SR_ERR;
439 }
440 if (freq > MAX_PWM_FREQ) {
91f73872 441 sr_err("Too high a PWM frequency: %.1f.", freq);
f2cd2deb
FS
442 return SR_ERR;
443 }
444 if (duty > 100 || duty < 0) {
91f73872 445 sr_err("Invalid PWM duty cycle: %f.", duty);
f2cd2deb
FS
446 return SR_ERR;
447 }
448
449 cfg.period = (uint32_t)(PWM_CLOCK / freq);
450 cfg.duty = (uint32_t)(0.5f + (cfg.period * duty / 100.));
91f73872 451 sr_dbg("Set PWM%d period %d, duty %d.", which, cfg.period, cfg.duty);
f2cd2deb 452
c3d40037
HK
453 wrptr = buf;
454 write_u32le_inc(&wrptr, cfg.period);
455 write_u32le_inc(&wrptr, cfg.duty);
00849545 456 ret = ctrl_out(sdi, CMD_FPGA_SPI, CTRL_PWM[which - 1], 0, buf, wrptr - buf);
f2cd2deb 457 if (ret != SR_OK) {
91f73872
GS
458 sr_err("Cannot setup PWM%d configuration %d %d.",
459 which, cfg.period, cfg.duty);
f2cd2deb
FS
460 return ret;
461 }
462 setting = &devc->pwm_setting[which - 1];
463 setting->freq = freq;
464 setting->duty = duty;
f2cd2deb
FS
465
466 return SR_OK;
467}
468
469static int set_defaults(const struct sr_dev_inst *sdi)
470{
471 struct dev_context *devc;
472 int ret;
473
474 devc = sdi->priv;
475
852c7d14 476 devc->capture_ratio = LA2016_DFLT_CAPT_RATIO;
852c7d14
GS
477 devc->limit_samples = LA2016_DFLT_SAMPLEDEPTH;
478 devc->cur_samplerate = LA2016_DFLT_SAMPLERATE;
f2cd2deb
FS
479
480 ret = set_threshold_voltage(sdi, devc->threshold_voltage);
481 if (ret)
482 return ret;
483
484 ret = enable_pwm(sdi, 0, 0);
485 if (ret)
486 return ret;
487
852c7d14 488 ret = set_pwm(sdi, 1, SR_KHZ(1), 50);
f2cd2deb
FS
489 if (ret)
490 return ret;
491
852c7d14 492 ret = set_pwm(sdi, 2, SR_KHZ(100), 50);
f2cd2deb
FS
493 if (ret)
494 return ret;
495
496 ret = enable_pwm(sdi, 1, 1);
497 if (ret)
498 return ret;
499
500 return SR_OK;
501}
502
503static int set_trigger_config(const struct sr_dev_inst *sdi)
504{
505 struct dev_context *devc;
506 struct sr_trigger *trigger;
507 trigger_cfg_t cfg;
508 GSList *stages;
509 GSList *channel;
510 struct sr_trigger_stage *stage1;
511 struct sr_trigger_match *match;
512 uint16_t ch_mask;
513 int ret;
c3d40037
HK
514 uint8_t buf[4 * sizeof(uint32_t)];
515 uint8_t *wrptr;
f2cd2deb
FS
516
517 devc = sdi->priv;
518 trigger = sr_session_trigger_get(sdi->session);
519
520 memset(&cfg, 0, sizeof(cfg));
521
522 cfg.channels = devc->cur_channels;
523
524 if (trigger && trigger->stages) {
525 stages = trigger->stages;
526 stage1 = stages->data;
527 if (stages->next) {
528 sr_err("Only one trigger stage supported for now.");
529 return SR_ERR;
530 }
531 channel = stage1->matches;
532 while (channel) {
533 match = channel->data;
cf057ac4 534 ch_mask = 1UL << match->channel->index;
f2cd2deb
FS
535
536 switch (match->match) {
537 case SR_TRIGGER_ZERO:
538 cfg.level |= ch_mask;
539 cfg.high_or_falling &= ~ch_mask;
540 break;
541 case SR_TRIGGER_ONE:
542 cfg.level |= ch_mask;
543 cfg.high_or_falling |= ch_mask;
544 break;
545 case SR_TRIGGER_RISING:
546 if ((cfg.enabled & ~cfg.level)) {
91f73872 547 sr_err("Device only supports one edge trigger.");
f2cd2deb
FS
548 return SR_ERR;
549 }
550 cfg.level &= ~ch_mask;
551 cfg.high_or_falling &= ~ch_mask;
552 break;
553 case SR_TRIGGER_FALLING:
554 if ((cfg.enabled & ~cfg.level)) {
91f73872 555 sr_err("Device only supports one edge trigger.");
f2cd2deb
FS
556 return SR_ERR;
557 }
558 cfg.level &= ~ch_mask;
559 cfg.high_or_falling |= ch_mask;
560 break;
561 default:
91f73872 562 sr_err("Unknown trigger condition.");
f2cd2deb
FS
563 return SR_ERR;
564 }
565 cfg.enabled |= ch_mask;
566 channel = channel->next;
567 }
568 }
91f73872
GS
569 sr_dbg("Set trigger config: "
570 "channels 0x%04x, trigger-enabled 0x%04x, "
571 "level-triggered 0x%04x, high/falling 0x%04x.",
572 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
f2cd2deb 573
cf057ac4 574 devc->trigger_involved = cfg.enabled != 0;
f2cd2deb 575
c3d40037
HK
576 wrptr = buf;
577 write_u32le_inc(&wrptr, cfg.channels);
578 write_u32le_inc(&wrptr, cfg.enabled);
579 write_u32le_inc(&wrptr, cfg.level);
580 write_u32le_inc(&wrptr, cfg.high_or_falling);
852c7d14
GS
581 /* TODO
582 * Comment on this literal 16. Origin, meaning? Cannot be the
583 * register offset, nor the transfer length. Is it a channels
584 * count that is relevant for 16 and 32 channel models? Is it
585 * an obsolete experiment?
586 */
42f6dd55 587 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
f2cd2deb 588 if (ret != SR_OK) {
91f73872 589 sr_err("Cannot setup trigger configuration.");
f2cd2deb
FS
590 return ret;
591 }
592
593 return SR_OK;
594}
595
596static int set_sample_config(const struct sr_dev_inst *sdi)
597{
598 struct dev_context *devc;
f2cd2deb 599 double clock_divisor;
adab4d91
GS
600 uint16_t divider_u16;
601 uint64_t pre_trigger_samples;
602 uint64_t pre_trigger_memory;
603 uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
c3d40037 604 uint8_t *wrptr;
adab4d91 605 int ret;
f2cd2deb
FS
606
607 devc = sdi->priv;
f2cd2deb 608
8b172e78 609 if (devc->cur_samplerate > devc->max_samplerate) {
91f73872
GS
610 sr_err("Too high a sample rate: %" PRIu64 ".",
611 devc->cur_samplerate);
f2cd2deb
FS
612 return SR_ERR;
613 }
614
8b172e78 615 clock_divisor = devc->max_samplerate / (double)devc->cur_samplerate;
adab4d91
GS
616 if (clock_divisor > 65535)
617 return SR_ERR_ARG;
618 divider_u16 = (uint16_t)(clock_divisor + 0.5);
619 devc->cur_samplerate = devc->max_samplerate / divider_u16;
f2cd2deb
FS
620
621 if (devc->limit_samples > MAX_SAMPLE_DEPTH) {
91f73872
GS
622 sr_err("Too high a sample depth: %" PRIu64 ".",
623 devc->limit_samples);
f2cd2deb
FS
624 return SR_ERR;
625 }
f2cd2deb 626
adab4d91
GS
627 /*
628 * The acquisition configuration communicates "pre-trigger"
629 * specs in several formats. sigrok users provide a percentage
630 * (0-100%), which translates to a pre-trigger samples count
631 * (assuming that a total samples count limit was specified).
632 * The device supports hardware compression, which depends on
633 * slowly changing input data to be effective. Fast changing
634 * input data may occupy more space in sample memory than its
635 * uncompressed form would. This is why a third parameter can
636 * limit the amount of sample memory to use for pre-trigger
637 * data. Only the upper 24 bits of that memory size spec get
638 * communicated to the device (written to its FPGA register).
639 */
640 pre_trigger_samples = devc->limit_samples * devc->capture_ratio / 100;
641 pre_trigger_memory = LA2016_PRE_MEM_LIMIT_BASE;
642 pre_trigger_memory *= devc->capture_ratio;
643 pre_trigger_memory /= 100;
f2cd2deb 644
adab4d91
GS
645 sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples.",
646 devc->cur_samplerate / 1000, devc->limit_samples);
647 sr_dbg("Capture ratio %" PRIu64 "%%, count %" PRIu64 ", mem %" PRIu64 ".",
648 devc->capture_ratio, pre_trigger_samples, pre_trigger_memory);
f2cd2deb 649
b1a17c1a
GS
650 /*
651 * The acquisition configuration occupies a total of 16 bytes:
652 * - A 34bit total samples count limit (up to 10 billions) that
653 * is kept in a 40bit register.
654 * - A 34bit pre-trigger samples count limit (up to 10 billions)
655 * in another 40bit register.
656 * - A 32bit pre-trigger memory space limit (in bytes) of which
657 * the upper 24bits are kept in an FPGA register.
658 * - A 16bit clock divider which gets applied to the maximum
659 * samplerate of the device.
660 * - An 8bit register of unknown meaning. Currently always 0.
661 */
c3d40037 662 wrptr = buf;
b1a17c1a
GS
663 write_u40le_inc(&wrptr, devc->limit_samples);
664 write_u40le_inc(&wrptr, pre_trigger_samples);
665 write_u24le_inc(&wrptr, pre_trigger_memory >> 8);
adab4d91 666 write_u16le_inc(&wrptr, divider_u16);
0d8e1ffc 667 write_u8_inc(&wrptr, 0);
42f6dd55 668 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
f2cd2deb 669 if (ret != SR_OK) {
91f73872 670 sr_err("Cannot setup acquisition configuration.");
f2cd2deb
FS
671 return ret;
672 }
673
674 return SR_OK;
675}
676
96dc954e
GS
677/*
678 * FPGA register REG_RUN holds the run state (u16le format). Bit fields
679 * of interest:
680 * bit 0: value 1 = idle
681 * bit 1: value 1 = writing to SDRAM
682 * bit 2: value 0 = waiting for trigger, 1 = trigger seen
683 * bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
684 * The meaning of other bit fields is unknown.
7601dca7 685 *
96dc954e 686 * Typical values in order of appearance during execution:
b711fd8e
GS
687 * 0x85e1: idle, no acquisition pending
688 * IDLE set, TRGD don't care, POST don't care; DRAM don't care
689 * "In idle state." Takes precedence over all others.
96dc954e
GS
690 * 0x85e2: pre-sampling, samples before the trigger position,
691 * when capture ratio > 0%
b711fd8e
GS
692 * IDLE clear, TRGD clear, POST clear; DRAM don't care
693 * "Not idle any more, no post yet, not triggered yet."
96dc954e
GS
694 * 0x85ea: pre-sampling complete, now waiting for the trigger
695 * (whilst sampling continuously)
b711fd8e
GS
696 * IDLE clear, TRGD clear, POST set; DRAM don't care
697 * "Post set thus after pre, not triggered yet"
96dc954e 698 * 0x85ee: trigger seen, capturing post-trigger samples, running
b711fd8e
GS
699 * IDLE clear, TRGD set, POST set; DRAM don't care
700 * "Triggered and in post, not idle yet."
96dc954e 701 * 0x85ed: idle
b711fd8e
GS
702 * IDLE set, TRGD don't care, POST don't care; DRAM don't care
703 * "In idle state." TRGD/POST don't care, same meaning as above.
f2cd2deb 704 */
b711fd8e
GS
705static const uint16_t runstate_mask_idle = RUNSTATE_IDLE_BIT;
706static const uint16_t runstate_patt_idle = RUNSTATE_IDLE_BIT;
707static const uint16_t runstate_mask_step =
708 RUNSTATE_IDLE_BIT | RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
709static const uint16_t runstate_patt_pre_trig = 0;
710static const uint16_t runstate_patt_wait_trig = RUNSTATE_POST_BIT;
711static const uint16_t runstate_patt_post_trig =
712 RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
713
f2cd2deb
FS
714static uint16_t run_state(const struct sr_dev_inst *sdi)
715{
21d68fd9
GS
716 static uint16_t previous_state;
717
f2cd2deb 718 int ret;
21d68fd9
GS
719 uint16_t state;
720 uint8_t buff[sizeof(state)];
721 const uint8_t *rdptr;
722 const char *label;
f2cd2deb 723
21d68fd9 724 if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, sizeof(state))) != SR_OK) {
91f73872 725 sr_err("Cannot read run state.");
f2cd2deb
FS
726 return ret;
727 }
21d68fd9
GS
728 rdptr = buff;
729 state = read_u16le_inc(&rdptr);
7601dca7 730
96dc954e
GS
731 /*
732 * Avoid flooding the log, only dump values as they change.
733 * The routine is called about every 50ms.
7601dca7 734 */
b711fd8e
GS
735 if (state == previous_state)
736 return state;
737
738 previous_state = state;
739 label = NULL;
740 if ((state & runstate_mask_idle) == runstate_patt_idle)
741 label = "idle";
742 if ((state & runstate_mask_step) == runstate_patt_pre_trig)
743 label = "pre-trigger sampling";
744 if ((state & runstate_mask_step) == runstate_patt_wait_trig)
745 label = "sampling, waiting for trigger";
746 if ((state & runstate_mask_step) == runstate_patt_post_trig)
747 label = "post-trigger sampling";
748 if (label && *label)
749 sr_dbg("Run state: 0x%04x (%s).", state, label);
750 else
751 sr_dbg("Run state: 0x%04x.", state);
f2cd2deb
FS
752
753 return state;
754}
755
cf057ac4 756static int la2016_is_idle(const struct sr_dev_inst *sdi)
c34f4a89
GS
757{
758 uint16_t state;
759
760 state = run_state(sdi);
b711fd8e 761 if ((state & runstate_mask_idle) == runstate_patt_idle)
c34f4a89
GS
762 return 1;
763
764 return 0;
765}
766
767static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
f2cd2deb
FS
768{
769 int ret;
770
c34f4a89
GS
771 if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode))) != SR_OK) {
772 sr_err("Cannot configure run mode %d.", mode);
f2cd2deb
FS
773 return ret;
774 }
775
776 return SR_OK;
777}
778
779static int get_capture_info(const struct sr_dev_inst *sdi)
780{
781 struct dev_context *devc;
782 int ret;
c3d40037
HK
783 uint8_t buf[3 * sizeof(uint32_t)];
784 const uint8_t *rdptr;
f2cd2deb
FS
785
786 devc = sdi->priv;
787
42f6dd55 788 if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf))) != SR_OK) {
91f73872 789 sr_err("Cannot read capture info.");
f2cd2deb
FS
790 return ret;
791 }
c3d40037
HK
792
793 rdptr = buf;
794 devc->info.n_rep_packets = read_u32le_inc(&rdptr);
795 devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
796 devc->info.write_pos = read_u32le_inc(&rdptr);
f2cd2deb 797
cf057ac4 798 sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x/%d.",
1ed93110
GS
799 devc->info.n_rep_packets, devc->info.n_rep_packets,
800 devc->info.n_rep_packets_before_trigger,
801 devc->info.n_rep_packets_before_trigger,
802 devc->info.write_pos, devc->info.write_pos);
f2cd2deb 803
852c7d14
GS
804 if (devc->info.n_rep_packets % NUM_PACKETS_IN_CHUNK) {
805 sr_warn("Unexpected packets count %lu, not a multiple of %d.",
806 (unsigned long)devc->info.n_rep_packets,
807 NUM_PACKETS_IN_CHUNK);
91f73872 808 }
f2cd2deb
FS
809
810 return SR_OK;
811}
812
1ed93110
GS
813SR_PRIV int la2016_upload_firmware(struct sr_context *sr_ctx,
814 libusb_device *dev, uint16_t product_id)
f2cd2deb
FS
815{
816 char fw_file[1024];
817 snprintf(fw_file, sizeof(fw_file) - 1, UC_FIRMWARE, product_id);
40a0b2f4 818 return ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
f2cd2deb
FS
819}
820
821SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
822{
823 struct dev_context *devc;
824 int ret;
825 uint8_t cmd;
826
827 devc = sdi->priv;
828
829 ret = set_threshold_voltage(sdi, devc->threshold_voltage);
830 if (ret != SR_OK)
831 return ret;
832
833 cmd = 0;
42f6dd55 834 if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd))) != SR_OK) {
91f73872 835 sr_err("Cannot send command to stop sampling.");
f2cd2deb
FS
836 return ret;
837 }
838
839 ret = set_trigger_config(sdi);
840 if (ret != SR_OK)
841 return ret;
842
843 ret = set_sample_config(sdi);
844 if (ret != SR_OK)
845 return ret;
846
847 return SR_OK;
848}
849
850SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
851{
3ebc1cb2
GS
852 int ret;
853
852c7d14 854 ret = set_run_mode(sdi, RUNMODE_RUN);
3ebc1cb2
GS
855 if (ret != SR_OK)
856 return ret;
857
858 return SR_OK;
f2cd2deb
FS
859}
860
3ebc1cb2 861static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
f2cd2deb 862{
3ebc1cb2
GS
863 int ret;
864
852c7d14 865 ret = set_run_mode(sdi, RUNMODE_HALT);
3ebc1cb2
GS
866 if (ret != SR_OK)
867 return ret;
868
869 return SR_OK;
f2cd2deb
FS
870}
871
872SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
873{
3ebc1cb2
GS
874 int ret;
875 struct dev_context *devc;
876
877 ret = la2016_stop_acquisition(sdi);
878 if (ret != SR_OK)
879 return ret;
880
881 devc = sdi ? sdi->priv : NULL;
882 if (devc && devc->transfer)
883 libusb_cancel_transfer(devc->transfer);
884
885 return SR_OK;
f2cd2deb
FS
886}
887
cf057ac4 888static int la2016_start_download(const struct sr_dev_inst *sdi,
1ed93110 889 libusb_transfer_cb_fn cb)
f2cd2deb
FS
890{
891 struct dev_context *devc;
892 struct sr_usb_dev_inst *usb;
893 int ret;
c3d40037
HK
894 uint8_t wrbuf[2 * sizeof(uint32_t)];
895 uint8_t *wrptr;
f2cd2deb
FS
896 uint32_t to_read;
897 uint8_t *buffer;
898
899 devc = sdi->priv;
900 usb = sdi->conn;
901
902 if ((ret = get_capture_info(sdi)) != SR_OK)
903 return ret;
904
c3d40037
HK
905 devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
906 devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
f2cd2deb
FS
907 devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
908 devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
909
91f73872 910 sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
1ed93110 911 devc->n_transfer_packets_to_read, devc->read_pos);
f2cd2deb 912
00849545 913 if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
91f73872 914 sr_err("Cannot reset USB bulk state.");
f2cd2deb
FS
915 return ret;
916 }
91f73872
GS
917 sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
918 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
c3d40037
HK
919 wrptr = wrbuf;
920 write_u32le_inc(&wrptr, devc->read_pos);
921 write_u32le_inc(&wrptr, devc->n_bytes_to_read);
42f6dd55 922 if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf)) != SR_OK) {
91f73872 923 sr_err("Cannot send USB bulk config.");
f2cd2deb
FS
924 return ret;
925 }
00849545 926 if ((ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0)) != SR_OK) {
91f73872 927 sr_err("Cannot unblock USB bulk transfers.");
f2cd2deb
FS
928 return ret;
929 }
930
96dc954e
GS
931 /*
932 * Pick a buffer size for all USB transfers. The buffer size
933 * must be a multiple of the endpoint packet size. And cannot
934 * exceed a maximum value.
935 */
f2cd2deb 936 to_read = devc->n_bytes_to_read;
96dc954e
GS
937 if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
938 to_read = LA2016_USB_BUFSZ;
939 else /* One transfer. */
e847645b 940 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
f2cd2deb
FS
941 buffer = g_try_malloc(to_read);
942 if (!buffer) {
91f73872
GS
943 sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
944 sr_err("Cannot allocate buffer for USB bulk transfer.");
f2cd2deb
FS
945 return SR_ERR_MALLOC;
946 }
947
948 devc->transfer = libusb_alloc_transfer(0);
852c7d14
GS
949 libusb_fill_bulk_transfer(devc->transfer,
950 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
951 buffer, to_read,
f2cd2deb
FS
952 cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
953
954 if ((ret = libusb_submit_transfer(devc->transfer)) != 0) {
91f73872 955 sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
f2cd2deb
FS
956 libusb_free_transfer(devc->transfer);
957 devc->transfer = NULL;
958 g_free(buffer);
959 return SR_ERR;
960 }
961
962 return SR_OK;
963}
964
dfac9592
GS
965static void send_chunk(struct sr_dev_inst *sdi,
966 const uint8_t *packets, unsigned int num_tfers)
967{
968 struct dev_context *devc;
969 struct sr_datafeed_logic logic;
970 struct sr_datafeed_packet sr_packet;
971 unsigned int max_samples, n_samples, total_samples, free_n_samples;
972 unsigned int i, j, k;
cf057ac4 973 gboolean do_signal_trigger;
fe953391 974 uint8_t *wp;
dfac9592
GS
975 const uint8_t *rp;
976 uint16_t state;
977 uint8_t repetitions;
fe953391 978 uint8_t sample_buff[sizeof(state)];
dfac9592
GS
979
980 devc = sdi->priv;
981
fe953391 982 logic.unitsize = sizeof(sample_buff);
dfac9592
GS
983 logic.data = devc->convbuffer;
984
985 sr_packet.type = SR_DF_LOGIC;
986 sr_packet.payload = &logic;
987
fe953391 988 max_samples = devc->convbuffer_size / sizeof(sample_buff);
dfac9592 989 n_samples = 0;
fe953391 990 wp = devc->convbuffer;
dfac9592 991 total_samples = 0;
cf057ac4 992 do_signal_trigger = FALSE;
dfac9592 993
cf057ac4 994 if (devc->trigger_involved && !devc->trigger_marked && devc->info.n_rep_packets_before_trigger == 0) {
dfac9592 995 std_session_send_df_trigger(sdi);
cf057ac4 996 devc->trigger_marked = TRUE;
dfac9592
GS
997 }
998
999 rp = packets;
1000 for (i = 0; i < num_tfers; i++) {
1001 for (k = 0; k < NUM_PACKETS_IN_CHUNK; k++) {
1002 free_n_samples = max_samples - n_samples;
1003 if (free_n_samples < 256 || do_signal_trigger) {
1004 logic.length = n_samples * 2;
1005 sr_session_send(sdi, &sr_packet);
1006 n_samples = 0;
fe953391 1007 wp = devc->convbuffer;
dfac9592
GS
1008 if (do_signal_trigger) {
1009 std_session_send_df_trigger(sdi);
cf057ac4 1010 do_signal_trigger = FALSE;
dfac9592
GS
1011 }
1012 }
1013
1014 state = read_u16le_inc(&rp);
1015 repetitions = read_u8_inc(&rp);
fe953391
GS
1016 write_u16le((void *)&sample_buff, state);
1017 for (j = 0; j < repetitions; j++) {
1018 memcpy(wp, sample_buff, logic.unitsize);
1019 wp += logic.unitsize;
1020 }
dfac9592
GS
1021
1022 n_samples += repetitions;
1023 total_samples += repetitions;
1024 devc->total_samples += repetitions;
cf057ac4
GS
1025 if (devc->trigger_involved && !devc->trigger_marked) {
1026 if (!--devc->n_reps_until_trigger) {
1027 devc->trigger_marked = TRUE;
1028 do_signal_trigger = TRUE;
91f73872 1029 sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
1ed93110
GS
1030 devc->total_samples,
1031 (double)devc->total_samples / devc->cur_samplerate * 1e3);
dfac9592
GS
1032 }
1033 }
1034 }
1035 (void)read_u8_inc(&rp); /* Skip sequence number. */
1036 }
1037 if (n_samples) {
fe953391 1038 logic.length = n_samples * logic.unitsize;
dfac9592
GS
1039 sr_session_send(sdi, &sr_packet);
1040 if (do_signal_trigger) {
1041 std_session_send_df_trigger(sdi);
1042 }
1043 }
91f73872 1044 sr_dbg("Send_chunk done after %u samples.", total_samples);
dfac9592
GS
1045}
1046
1047static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
1048{
1049 struct sr_dev_inst *sdi;
1050 struct dev_context *devc;
1051 struct sr_usb_dev_inst *usb;
1052 int ret;
1053
1054 sdi = transfer->user_data;
1055 devc = sdi->priv;
1056 usb = sdi->conn;
1057
1058 sr_dbg("receive_transfer(): status %s received %d bytes.",
1ed93110 1059 libusb_error_name(transfer->status), transfer->actual_length);
dfac9592
GS
1060
1061 if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
91f73872 1062 sr_err("USB bulk transfer timeout.");
cf057ac4 1063 devc->download_finished = TRUE;
dfac9592
GS
1064 }
1065 send_chunk(sdi, transfer->buffer, transfer->actual_length / TRANSFER_PACKET_LENGTH);
1066
1067 devc->n_bytes_to_read -= transfer->actual_length;
1068 if (devc->n_bytes_to_read) {
1069 uint32_t to_read = devc->n_bytes_to_read;
96dc954e
GS
1070 /*
1071 * Determine read size for the next USB transfer. Make
1072 * the buffer size a multiple of the endpoint packet
1073 * size. Don't exceed a maximum value.
1074 */
dfac9592
GS
1075 if (to_read >= LA2016_USB_BUFSZ)
1076 to_read = LA2016_USB_BUFSZ;
96dc954e 1077 else
dfac9592 1078 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
852c7d14
GS
1079 libusb_fill_bulk_transfer(transfer,
1080 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1081 transfer->buffer, to_read,
dfac9592
GS
1082 receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
1083
1084 if ((ret = libusb_submit_transfer(transfer)) == 0)
1085 return;
91f73872
GS
1086 sr_err("Cannot submit another USB transfer: %s.",
1087 libusb_error_name(ret));
dfac9592
GS
1088 }
1089
1090 g_free(transfer->buffer);
1091 libusb_free_transfer(transfer);
cf057ac4 1092 devc->download_finished = TRUE;
dfac9592
GS
1093}
1094
1095SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1096{
1097 const struct sr_dev_inst *sdi;
1098 struct dev_context *devc;
1099 struct drv_context *drvc;
1100 struct timeval tv;
1101
1102 (void)fd;
1103 (void)revents;
1104
1105 sdi = cb_data;
1106 devc = sdi->priv;
1107 drvc = sdi->driver->context;
1108
cf057ac4
GS
1109 if (!devc->completion_seen) {
1110 if (!la2016_is_idle(sdi)) {
96dc954e 1111 /* Not yet ready for sample data download. */
dfac9592
GS
1112 return TRUE;
1113 }
cf057ac4
GS
1114 devc->completion_seen = TRUE;
1115 devc->download_finished = FALSE;
1116 devc->trigger_marked = FALSE;
dfac9592 1117 devc->total_samples = 0;
96dc954e 1118 /* We can start downloading sample data. */
cf057ac4 1119 if (la2016_start_download(sdi, receive_transfer) != SR_OK) {
91f73872 1120 sr_err("Cannot start acquisition data download.");
dfac9592
GS
1121 return FALSE;
1122 }
91f73872 1123 sr_dbg("Acquisition data download started.");
dfac9592
GS
1124 std_session_send_df_frame_begin(sdi);
1125
1126 return TRUE;
1127 }
1128
1129 tv.tv_sec = tv.tv_usec = 0;
1130 libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1131
cf057ac4 1132 if (devc->download_finished) {
91f73872 1133 sr_dbg("Download finished, post processing.");
dfac9592
GS
1134 std_session_send_df_frame_end(sdi);
1135
1136 usb_source_remove(sdi->session, drvc->sr_ctx);
1137 std_session_send_df_end(sdi);
1138
1139 la2016_stop_acquisition(sdi);
1140
1141 g_free(devc->convbuffer);
1142 devc->convbuffer = NULL;
1143
1144 devc->transfer = NULL;
1145
91f73872 1146 sr_dbg("Download finished, done post processing.");
dfac9592
GS
1147 }
1148
1149 return TRUE;
1150}
1151
f2cd2deb
FS
1152SR_PRIV int la2016_init_device(const struct sr_dev_inst *sdi)
1153{
8b172e78 1154 struct dev_context *devc;
f2cd2deb 1155 uint16_t state;
9de389b1 1156 uint8_t buf[8];
43d2e52f
GS
1157 const uint8_t *rdptr;
1158 uint8_t date_yy, date_mm;
1159 uint8_t dinv_yy, dinv_mm;
9de389b1 1160 uint8_t magic;
d6f89d4b 1161 const char *bitstream_fn;
9de389b1 1162 int ret;
f2cd2deb 1163
8b172e78
KG
1164 devc = sdi->priv;
1165
96dc954e 1166 /*
43d2e52f
GS
1167 * Four EEPROM bytes at offset 0x20 are the manufacturing date,
1168 * year and month in BCD format, followed by inverted values for
1169 * consistency checks. For example bytes 20 04 df fb translate
1170 * to 2020-04. This information can help identify the vintage of
1171 * devices when unknown magic numbers are seen.
9de389b1 1172 */
43d2e52f
GS
1173 ret = ctrl_in(sdi, CMD_EEPROM, 0x20, 0, buf, 4 * sizeof(uint8_t));
1174 if (ret != SR_OK) {
1175 sr_err("Cannot read manufacture date in EEPROM.");
1ed93110 1176 } else {
43d2e52f
GS
1177 rdptr = &buf[0];
1178 date_yy = read_u8_inc(&rdptr);
1179 date_mm = read_u8_inc(&rdptr);
1180 dinv_yy = read_u8_inc(&rdptr);
1181 dinv_mm = read_u8_inc(&rdptr);
1182 sr_info("Manufacture date: 20%02hx-%02hx.", date_yy, date_mm);
1183 if ((date_mm ^ dinv_mm) != 0xff || (date_yy ^ dinv_yy) != 0xff)
1184 sr_warn("Manufacture date fails checksum test.");
f2cd2deb 1185 }
f2cd2deb 1186
9de389b1 1187 /*
96dc954e
GS
1188 * Several Kingst logic analyzer devices share the same USB VID
1189 * and PID. The product ID determines which MCU firmware to load.
1190 * The MCU firmware provides access to EEPROM content which then
1191 * allows to identify the device model. Which in turn determines
1192 * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1193 * to get inspected.
9de389b1 1194 *
96dc954e
GS
1195 * EEPROM content for model identification is kept redundantly
1196 * in memory. The values are stored in verbatim and in inverted
1197 * form, multiple copies are kept at different offsets. Example
1198 * data:
9de389b1 1199 *
96dc954e
GS
1200 * magic 0x08
1201 * | ~magic 0xf7
1202 * | |
1203 * 08f7000008f710ef
1204 * | |
1205 * | ~magic backup
1206 * magic backup
9de389b1 1207 *
96dc954e
GS
1208 * Exclusively inspecting the magic byte appears to be sufficient,
1209 * other fields seem to be 'don't care'.
9de389b1 1210 *
96dc954e
GS
1211 * magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1212 * magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1213 * magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1214 * (latest v1.3.0 PCB, perhaps others)
1215 * magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1216 * (latest v1.3.0 PCB, perhaps others)
9de389b1 1217 *
96dc954e
GS
1218 * When EEPROM content does not match the hardware configuration
1219 * (the board layout), the software may load but yield incorrect
1220 * results (like swapped channels). The FPGA bitstream itself
1221 * will authenticate with IC U10 and fail when its capabilities
1222 * do not match the hardware model. An LA1016 won't become a
1223 * LA2016 by faking its EEPROM content.
9de389b1 1224 */
9de389b1 1225 if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x08, 0, &buf, sizeof(buf))) != SR_OK) {
91f73872 1226 sr_err("Cannot read EEPROM device identifier bytes.");
f2cd2deb
FS
1227 return ret;
1228 }
43d2e52f 1229 if ((buf[0] ^ buf[1]) == 0xff) {
96dc954e 1230 /* Primary copy of magic passes complement check. */
43d2e52f 1231 sr_dbg("Using primary copy of device type magic number.");
9de389b1 1232 magic = buf[0];
43d2e52f 1233 } else if ((buf[4] ^ buf[5]) == 0xff) {
96dc954e 1234 /* Backup copy of magic passes complement check. */
91f73872 1235 sr_dbg("Using backup copy of device type magic number.");
9de389b1 1236 magic = buf[4];
43d2e52f
GS
1237 } else {
1238 sr_err("Cannot find consistent device type identification.");
1239 magic = 0;
f2cd2deb 1240 }
91f73872 1241 sr_dbg("Device type: magic number is %hhu.", magic);
9de389b1 1242
96dc954e 1243 /* Select the FPGA bitstream depending on the model. */
9de389b1
KG
1244 switch (magic) {
1245 case 2:
d6f89d4b 1246 bitstream_fn = FPGA_FW_LA2016;
8b172e78
KG
1247 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1248 break;
1249 case 3:
d6f89d4b 1250 bitstream_fn = FPGA_FW_LA1016;
8b172e78 1251 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
9de389b1
KG
1252 break;
1253 case 8:
d6f89d4b 1254 bitstream_fn = FPGA_FW_LA2016A;
8b172e78
KG
1255 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1256 break;
1257 case 9:
d6f89d4b 1258 bitstream_fn = FPGA_FW_LA1016A;
8b172e78 1259 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
9de389b1
KG
1260 break;
1261 default:
d6f89d4b
GS
1262 bitstream_fn = NULL;
1263 break;
1264 }
1265 if (!bitstream_fn || !*bitstream_fn) {
91f73872 1266 sr_err("Cannot identify as one of the supported models.");
3f48ab02
FS
1267 return SR_ERR;
1268 }
f2cd2deb 1269
d6f89d4b
GS
1270 if (check_fpga_bitstream(sdi) != SR_OK) {
1271 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1272 if (ret != SR_OK) {
1273 sr_err("Cannot upload FPGA bitstream.");
1274 return ret;
1275 }
1276 }
1277 ret = enable_fpga_bitstream(sdi);
9de389b1 1278 if (ret != SR_OK) {
d6f89d4b 1279 sr_err("Cannot enable FPGA bitstream after upload.");
9de389b1
KG
1280 return ret;
1281 }
1282
f2cd2deb 1283 state = run_state(sdi);
9de389b1 1284 if (state != 0x85e9) {
91f73872 1285 sr_warn("Unexpected run state, want 0x85e9, got 0x%04x.", state);
9de389b1 1286 }
f2cd2deb 1287
00849545 1288 if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
91f73872 1289 sr_err("Cannot reset USB bulk transfer.");
f2cd2deb
FS
1290 return ret;
1291 }
9de389b1 1292
91f73872 1293 sr_dbg("Device should be initialized.");
f2cd2deb 1294
c34f4a89
GS
1295 ret = set_defaults(sdi);
1296 if (ret != SR_OK)
1297 return ret;
1298
1299 return SR_OK;
f2cd2deb
FS
1300}
1301
1302SR_PRIV int la2016_deinit_device(const struct sr_dev_inst *sdi)
1303{
1304 int ret;
1305
00849545 1306 if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0)) != SR_OK) {
91f73872 1307 sr_err("Cannot deinitialize device's FPGA.");
f2cd2deb
FS
1308 return ret;
1309 }
1310
1311 return SR_OK;
1312}