2 * This file is part of the libsigrok project.
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>
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.
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.
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/>.
25 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
31 #define UC_FIRMWARE "kingst-la-%04x.fw"
32 #define FPGA_FW_LA2016 "kingst-la2016-fpga.bitstream"
33 #define FPGA_FW_LA2016A "kingst-la2016a1-fpga.bitstream"
34 #define FPGA_FW_LA1016 "kingst-la1016-fpga.bitstream"
35 #define FPGA_FW_LA1016A "kingst-la1016a1-fpga.bitstream"
37 /* Maximum device capabilities. May differ between models. */
38 #define MAX_SAMPLE_RATE_LA2016 SR_MHZ(200)
39 #define MAX_SAMPLE_RATE_LA1016 SR_MHZ(100)
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 */
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.
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. */
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?
60 #define LA2016_PRE_MEM_LIMIT_BASE (128 * 1024 * 1024)
62 /* USB vendor class control requests, executed by the Cypress FX2 MCU. */
63 #define CMD_FPGA_ENABLE 0x10
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. */
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.
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.
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. */
98 /* Bit patterns to write to REG_RUN, setup run mode. */
99 #define RUNMODE_HALT 0x00
100 #define RUNMODE_RUN 0x03
102 static int ctrl_in(const struct sr_dev_inst *sdi,
103 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
104 void *data, uint16_t wLength)
106 struct sr_usb_dev_inst *usb;
111 if ((ret = libusb_control_transfer(usb->devhdl,
112 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
113 bRequest, wValue, wIndex, (unsigned char *)data, wLength,
114 DEFAULT_TIMEOUT_MS)) != wLength) {
115 sr_dbg("USB ctrl in: %d bytes, req %d val %#x idx %d: %s.",
116 wLength, bRequest, wValue, wIndex,
117 libusb_error_name(ret));
118 sr_err("Cannot read %d bytes from USB: %s.",
119 wLength, libusb_error_name(ret));
126 static int ctrl_out(const struct sr_dev_inst *sdi,
127 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
128 void *data, uint16_t wLength)
130 struct sr_usb_dev_inst *usb;
135 if ((ret = libusb_control_transfer(usb->devhdl,
136 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
137 bRequest, wValue, wIndex, (unsigned char*)data, wLength,
138 DEFAULT_TIMEOUT_MS)) != wLength) {
139 sr_dbg("USB ctrl out: %d bytes, req %d val %#x idx %d: %s.",
140 wLength, bRequest, wValue, wIndex,
141 libusb_error_name(ret));
142 sr_err("Cannot write %d bytes to USB: %s.",
143 wLength, libusb_error_name(ret));
151 * Check the necessity for FPGA bitstream upload, because another upload
152 * would take some 600ms which is undesirable after program startup. Try
153 * to access some FPGA registers and check the values' plausibility. The
154 * check should fail on the safe side, request another upload when in
155 * doubt. A positive response (the request to continue operation with the
156 * currently active bitstream) should be conservative. Accessing multiple
157 * registers is considered cheap compared to the cost of bitstream upload.
159 * It helps though that both the vendor software and the sigrok driver
160 * use the same bundle of MCU firmware and FPGA bitstream for any of the
161 * supported models. We don't expect to successfully communicate to the
162 * device yet disagree on its protocol. Ideally we would access version
163 * identifying registers for improved robustness, but are not aware of
164 * any. A bitstream reload can always be forced by a power cycle.
166 static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
173 uint8_t buff[sizeof(run_state)];
174 const uint8_t *rdptr;
176 sr_dbg("Checking operation of the FPGA bitstream.");
179 ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
180 if (ret != SR_OK || init_rsp != 0) {
181 sr_dbg("FPGA init query failed, or unexpected response.");
185 read_len = sizeof(run_state);
186 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, read_len);
188 sr_dbg("FPGA register access failed (run state).");
192 run_state = read_u16le_inc(&rdptr);
193 sr_spew("FPGA register: run state 0x%04x.", run_state);
194 if (run_state && (run_state & 0x3) != 0x1) {
195 sr_dbg("Unexpected FPGA register content (run state).");
198 if (run_state && (run_state & ~0xf) != 0x85e0) {
199 sr_dbg("Unexpected FPGA register content (run state).");
203 read_len = sizeof(pwm_en);
204 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, buff, read_len);
206 sr_dbg("FPGA register access failed (PWM enable).");
210 pwm_en = read_u8_inc(&rdptr);
211 sr_spew("FPGA register: PWM enable 0x%02x.", pwm_en);
212 if ((pwm_en & 0x3) != 0x0) {
213 sr_dbg("Unexpected FPGA register content (PWM enable).");
217 sr_info("Could re-use current FPGA bitstream. No upload required.");
221 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
222 const char *bitstream_fname)
224 struct drv_context *drvc;
225 struct sr_usb_dev_inst *usb;
226 struct sr_resource bitstream;
227 uint32_t bitstream_size;
228 uint8_t buffer[sizeof(uint32_t)];
234 unsigned int zero_pad_to;
236 drvc = sdi->driver->context;
239 sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
241 ret = sr_resource_open(drvc->sr_ctx, &bitstream, SR_RESOURCE_FIRMWARE, bitstream_fname);
243 sr_err("Cannot find FPGA bitstream %s.", bitstream_fname);
247 bitstream_size = (uint32_t)bitstream.size;
249 write_u32le_inc(&wrptr, bitstream_size);
250 if ((ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer)) != SR_OK) {
251 sr_err("Cannot initiate FPGA bitstream upload.");
252 sr_resource_close(drvc->sr_ctx, &bitstream);
255 zero_pad_to = bitstream_size;
256 zero_pad_to += LA2016_EP2_PADDING - 1;
257 zero_pad_to /= LA2016_EP2_PADDING;
258 zero_pad_to *= LA2016_EP2_PADDING;
262 if (pos < bitstream.size) {
263 len = (int)sr_resource_read(drvc->sr_ctx, &bitstream, &block, sizeof(block));
265 sr_err("Cannot read FPGA bitstream.");
266 sr_resource_close(drvc->sr_ctx, &bitstream);
270 /* Zero-pad until 'zero_pad_to'. */
271 len = zero_pad_to - pos;
272 if ((unsigned)len > sizeof(block))
274 memset(&block, 0, len);
279 ret = libusb_bulk_transfer(usb->devhdl, USB_EP_FPGA_BITSTREAM,
280 &block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
282 sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
283 pos, (int)len, libusb_error_name(ret));
287 if (act_len != len) {
288 sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
289 pos, (int)len, act_len);
295 sr_resource_close(drvc->sr_ctx, &bitstream);
298 sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.",
304 static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
309 if ((ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &cmd_resp, sizeof(cmd_resp))) != SR_OK) {
310 sr_err("Cannot read response after FPGA bitstream upload.");
314 sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
320 if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0)) != SR_OK) {
321 sr_err("Cannot enable FPGA after bitstream upload.");
329 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
331 struct dev_context *devc;
336 uint16_t duty_R79, duty_R56;
337 uint8_t buf[2 * sizeof(uint16_t)];
340 /* Clamp threshold setting to valid range for LA2016. */
343 } else if (voltage < -4.0) {
348 * Two PWM output channels feed one DAC which generates a bias
349 * voltage, which offsets the input probe's voltage level, and
350 * in combination with the FPGA pins' fixed threshold result in
351 * a programmable input threshold from the user's perspective.
352 * The PWM outputs can be seen on R79 and R56 respectively, the
353 * frequency is 100kHz and the duty cycle varies. The R79 PWM
354 * uses three discrete settings. The R56 PWM varies with desired
355 * thresholds and depends on the R79 PWM configuration. See the
356 * schematics comments which discuss the formulae.
358 if (voltage >= 2.9) {
359 duty_R79 = 0; /* PWM off (0V). */
360 duty_R56 = (uint16_t)(302 * voltage - 363);
361 } else if (voltage > -0.4) {
362 duty_R79 = 0x00f2; /* 25% duty cycle. */
363 duty_R56 = (uint16_t)(302 * voltage + 121);
365 duty_R79 = 0x02d7; /* 72% duty cycle. */
366 duty_R56 = (uint16_t)(302 * voltage + 1090);
369 /* Clamp duty register values to sensible limits. */
372 } else if (duty_R56 > 1100) {
376 sr_dbg("Set threshold voltage %.2fV.", voltage);
377 sr_dbg("Duty cycle values: R56 0x%04x, R79 0x%04x.", duty_R56, duty_R79);
380 write_u16le_inc(&wrptr, duty_R56);
381 write_u16le_inc(&wrptr, duty_R79);
383 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_THRESHOLD, 0, buf, wrptr - buf);
385 sr_err("Cannot set threshold voltage %.2fV.", voltage);
388 devc->threshold_voltage = voltage;
393 static int enable_pwm(const struct sr_dev_inst *sdi, uint8_t p1, uint8_t p2)
395 struct dev_context *devc;
402 if (p1) cfg |= 1 << 0;
403 if (p2) cfg |= 1 << 1;
405 sr_dbg("Set PWM enable %d %d. Config 0x%02x.", p1, p2, cfg);
406 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, &cfg, sizeof(cfg));
408 sr_err("Cannot setup PWM enabled state.");
411 devc->pwm_setting[0].enabled = (p1) ? 1 : 0;
412 devc->pwm_setting[1].enabled = (p2) ? 1 : 0;
417 static int set_pwm(const struct sr_dev_inst *sdi, uint8_t which,
418 float freq, float duty)
420 int CTRL_PWM[] = { REG_PWM1, REG_PWM2 };
421 struct dev_context *devc;
422 pwm_setting_dev_t cfg;
423 pwm_setting_t *setting;
425 uint8_t buf[2 * sizeof(uint32_t)];
430 if (which < 1 || which > ARRAY_SIZE(CTRL_PWM)) {
431 sr_err("Invalid PWM channel: %d.", which);
434 if (freq > MAX_PWM_FREQ) {
435 sr_err("Too high a PWM frequency: %.1f.", freq);
438 if (duty > 100 || duty < 0) {
439 sr_err("Invalid PWM duty cycle: %f.", duty);
443 cfg.period = (uint32_t)(PWM_CLOCK / freq);
444 cfg.duty = (uint32_t)(0.5f + (cfg.period * duty / 100.));
445 sr_dbg("Set PWM%d period %d, duty %d.", which, cfg.period, cfg.duty);
448 write_u32le_inc(&wrptr, cfg.period);
449 write_u32le_inc(&wrptr, cfg.duty);
450 ret = ctrl_out(sdi, CMD_FPGA_SPI, CTRL_PWM[which - 1], 0, buf, wrptr - buf);
452 sr_err("Cannot setup PWM%d configuration %d %d.",
453 which, cfg.period, cfg.duty);
456 setting = &devc->pwm_setting[which - 1];
457 setting->freq = freq;
458 setting->duty = duty;
463 static int set_defaults(const struct sr_dev_inst *sdi)
465 struct dev_context *devc;
470 devc->capture_ratio = LA2016_DFLT_CAPT_RATIO;
471 devc->cur_channels = 0xffff;
472 devc->limit_samples = LA2016_DFLT_SAMPLEDEPTH;
473 devc->cur_samplerate = LA2016_DFLT_SAMPLERATE;
475 ret = set_threshold_voltage(sdi, devc->threshold_voltage);
479 ret = enable_pwm(sdi, 0, 0);
483 ret = set_pwm(sdi, 1, SR_KHZ(1), 50);
487 ret = set_pwm(sdi, 2, SR_KHZ(100), 50);
491 ret = enable_pwm(sdi, 1, 1);
498 static int set_trigger_config(const struct sr_dev_inst *sdi)
500 struct dev_context *devc;
501 struct sr_trigger *trigger;
505 struct sr_trigger_stage *stage1;
506 struct sr_trigger_match *match;
509 uint8_t buf[4 * sizeof(uint32_t)];
513 trigger = sr_session_trigger_get(sdi->session);
515 memset(&cfg, 0, sizeof(cfg));
517 cfg.channels = devc->cur_channels;
519 if (trigger && trigger->stages) {
520 stages = trigger->stages;
521 stage1 = stages->data;
523 sr_err("Only one trigger stage supported for now.");
526 channel = stage1->matches;
528 match = channel->data;
529 ch_mask = 1 << match->channel->index;
531 switch (match->match) {
532 case SR_TRIGGER_ZERO:
533 cfg.level |= ch_mask;
534 cfg.high_or_falling &= ~ch_mask;
537 cfg.level |= ch_mask;
538 cfg.high_or_falling |= ch_mask;
540 case SR_TRIGGER_RISING:
541 if ((cfg.enabled & ~cfg.level)) {
542 sr_err("Device only supports one edge trigger.");
545 cfg.level &= ~ch_mask;
546 cfg.high_or_falling &= ~ch_mask;
548 case SR_TRIGGER_FALLING:
549 if ((cfg.enabled & ~cfg.level)) {
550 sr_err("Device only supports one edge trigger.");
553 cfg.level &= ~ch_mask;
554 cfg.high_or_falling |= ch_mask;
557 sr_err("Unknown trigger condition.");
560 cfg.enabled |= ch_mask;
561 channel = channel->next;
564 sr_dbg("Set trigger config: "
565 "channels 0x%04x, trigger-enabled 0x%04x, "
566 "level-triggered 0x%04x, high/falling 0x%04x.",
567 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
569 devc->had_triggers_configured = cfg.enabled != 0;
572 write_u32le_inc(&wrptr, cfg.channels);
573 write_u32le_inc(&wrptr, cfg.enabled);
574 write_u32le_inc(&wrptr, cfg.level);
575 write_u32le_inc(&wrptr, cfg.high_or_falling);
577 * Comment on this literal 16. Origin, meaning? Cannot be the
578 * register offset, nor the transfer length. Is it a channels
579 * count that is relevant for 16 and 32 channel models? Is it
580 * an obsolete experiment?
582 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
584 sr_err("Cannot setup trigger configuration.");
591 static int set_sample_config(const struct sr_dev_inst *sdi)
593 struct dev_context *devc;
594 double clock_divisor;
595 uint16_t divider_u16;
596 uint64_t pre_trigger_samples;
597 uint64_t pre_trigger_memory;
598 uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
604 if (devc->cur_samplerate > devc->max_samplerate) {
605 sr_err("Too high a sample rate: %" PRIu64 ".",
606 devc->cur_samplerate);
610 clock_divisor = devc->max_samplerate / (double)devc->cur_samplerate;
611 if (clock_divisor > 65535)
613 divider_u16 = (uint16_t)(clock_divisor + 0.5);
614 devc->cur_samplerate = devc->max_samplerate / divider_u16;
616 if (devc->limit_samples > MAX_SAMPLE_DEPTH) {
617 sr_err("Too high a sample depth: %" PRIu64 ".",
618 devc->limit_samples);
623 * The acquisition configuration communicates "pre-trigger"
624 * specs in several formats. sigrok users provide a percentage
625 * (0-100%), which translates to a pre-trigger samples count
626 * (assuming that a total samples count limit was specified).
627 * The device supports hardware compression, which depends on
628 * slowly changing input data to be effective. Fast changing
629 * input data may occupy more space in sample memory than its
630 * uncompressed form would. This is why a third parameter can
631 * limit the amount of sample memory to use for pre-trigger
632 * data. Only the upper 24 bits of that memory size spec get
633 * communicated to the device (written to its FPGA register).
635 pre_trigger_samples = devc->limit_samples * devc->capture_ratio / 100;
636 pre_trigger_memory = LA2016_PRE_MEM_LIMIT_BASE;
637 pre_trigger_memory *= devc->capture_ratio;
638 pre_trigger_memory /= 100;
640 sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples.",
641 devc->cur_samplerate / 1000, devc->limit_samples);
642 sr_dbg("Capture ratio %" PRIu64 "%%, count %" PRIu64 ", mem %" PRIu64 ".",
643 devc->capture_ratio, pre_trigger_samples, pre_trigger_memory);
646 * The acquisition configuration occupies a total of 16 bytes:
647 * - A 34bit total samples count limit (up to 10 billions) that
648 * is kept in a 40bit register.
649 * - A 34bit pre-trigger samples count limit (up to 10 billions)
650 * in another 40bit register.
651 * - A 32bit pre-trigger memory space limit (in bytes) of which
652 * the upper 24bits are kept in an FPGA register.
653 * - A 16bit clock divider which gets applied to the maximum
654 * samplerate of the device.
655 * - An 8bit register of unknown meaning. Currently always 0.
658 write_u40le_inc(&wrptr, devc->limit_samples);
659 write_u40le_inc(&wrptr, pre_trigger_samples);
660 write_u24le_inc(&wrptr, pre_trigger_memory >> 8);
661 write_u16le_inc(&wrptr, divider_u16);
662 write_u8_inc(&wrptr, 0);
663 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
665 sr_err("Cannot setup acquisition configuration.");
673 * FPGA register REG_RUN holds the run state (u16le format). Bit fields
675 * bit 0: value 1 = idle
676 * bit 1: value 1 = writing to SDRAM
677 * bit 2: value 0 = waiting for trigger, 1 = trigger seen
678 * bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
679 * The meaning of other bit fields is unknown.
681 * Typical values in order of appearance during execution:
682 * 0x85e2: pre-sampling, samples before the trigger position,
683 * when capture ratio > 0%
684 * 0x85ea: pre-sampling complete, now waiting for the trigger
685 * (whilst sampling continuously)
686 * 0x85ee: trigger seen, capturing post-trigger samples, running
689 static uint16_t run_state(const struct sr_dev_inst *sdi)
691 static uint16_t previous_state;
695 uint8_t buff[sizeof(state)];
696 const uint8_t *rdptr;
699 if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, sizeof(state))) != SR_OK) {
700 sr_err("Cannot read run state.");
704 state = read_u16le_inc(&rdptr);
707 * Avoid flooding the log, only dump values as they change.
708 * The routine is called about every 50ms.
710 if (state != previous_state) {
711 previous_state = state;
712 if ((state & 0x3) == 0x1) {
714 } else if ((state & 0xf) == 0x2) {
715 label = "pre-trigger sampling";
716 } else if ((state & 0xf) == 0xa) {
717 label = "sampling, waiting for trigger";
718 } else if ((state & 0xf) == 0xe) {
719 label = "post-trigger sampling";
723 if (label && *label) {
724 sr_dbg("Run state: 0x%04x (%s).", state, label);
726 sr_dbg("Run state: 0x%04x.", state);
733 static int la2016_has_triggered(const struct sr_dev_inst *sdi)
737 state = run_state(sdi);
738 if ((state & 0x3) == 0x1)
744 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
748 if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode))) != SR_OK) {
749 sr_err("Cannot configure run mode %d.", mode);
756 static int get_capture_info(const struct sr_dev_inst *sdi)
758 struct dev_context *devc;
760 uint8_t buf[3 * sizeof(uint32_t)];
761 const uint8_t *rdptr;
765 if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf))) != SR_OK) {
766 sr_err("Cannot read capture info.");
771 devc->info.n_rep_packets = read_u32le_inc(&rdptr);
772 devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
773 devc->info.write_pos = read_u32le_inc(&rdptr);
775 sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x%d.",
776 devc->info.n_rep_packets, devc->info.n_rep_packets,
777 devc->info.n_rep_packets_before_trigger,
778 devc->info.n_rep_packets_before_trigger,
779 devc->info.write_pos, devc->info.write_pos);
781 if (devc->info.n_rep_packets % NUM_PACKETS_IN_CHUNK) {
782 sr_warn("Unexpected packets count %lu, not a multiple of %d.",
783 (unsigned long)devc->info.n_rep_packets,
784 NUM_PACKETS_IN_CHUNK);
790 SR_PRIV int la2016_upload_firmware(struct sr_context *sr_ctx,
791 libusb_device *dev, uint16_t product_id)
794 snprintf(fw_file, sizeof(fw_file) - 1, UC_FIRMWARE, product_id);
795 return ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
798 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
800 struct dev_context *devc;
806 ret = set_threshold_voltage(sdi, devc->threshold_voltage);
811 if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd))) != SR_OK) {
812 sr_err("Cannot send command to stop sampling.");
816 ret = set_trigger_config(sdi);
820 ret = set_sample_config(sdi);
827 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
831 ret = set_run_mode(sdi, RUNMODE_RUN);
838 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
842 ret = set_run_mode(sdi, RUNMODE_HALT);
849 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
852 struct dev_context *devc;
854 ret = la2016_stop_acquisition(sdi);
858 devc = sdi ? sdi->priv : NULL;
859 if (devc && devc->transfer)
860 libusb_cancel_transfer(devc->transfer);
865 static int la2016_start_retrieval(const struct sr_dev_inst *sdi,
866 libusb_transfer_cb_fn cb)
868 struct dev_context *devc;
869 struct sr_usb_dev_inst *usb;
871 uint8_t wrbuf[2 * sizeof(uint32_t)];
879 if ((ret = get_capture_info(sdi)) != SR_OK)
882 devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
883 devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
884 devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
885 devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
887 sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
888 devc->n_transfer_packets_to_read, devc->read_pos);
890 if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
891 sr_err("Cannot reset USB bulk state.");
894 sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
895 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
897 write_u32le_inc(&wrptr, devc->read_pos);
898 write_u32le_inc(&wrptr, devc->n_bytes_to_read);
899 if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf)) != SR_OK) {
900 sr_err("Cannot send USB bulk config.");
903 if ((ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0)) != SR_OK) {
904 sr_err("Cannot unblock USB bulk transfers.");
909 * Pick a buffer size for all USB transfers. The buffer size
910 * must be a multiple of the endpoint packet size. And cannot
911 * exceed a maximum value.
913 to_read = devc->n_bytes_to_read;
914 if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
915 to_read = LA2016_USB_BUFSZ;
916 else /* One transfer. */
917 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
918 buffer = g_try_malloc(to_read);
920 sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
921 sr_err("Cannot allocate buffer for USB bulk transfer.");
922 return SR_ERR_MALLOC;
925 devc->transfer = libusb_alloc_transfer(0);
926 libusb_fill_bulk_transfer(devc->transfer,
927 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
929 cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
931 if ((ret = libusb_submit_transfer(devc->transfer)) != 0) {
932 sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
933 libusb_free_transfer(devc->transfer);
934 devc->transfer = NULL;
942 static void send_chunk(struct sr_dev_inst *sdi,
943 const uint8_t *packets, unsigned int num_tfers)
945 struct dev_context *devc;
946 struct sr_datafeed_logic logic;
947 struct sr_datafeed_packet sr_packet;
948 unsigned int max_samples, n_samples, total_samples, free_n_samples;
949 unsigned int i, j, k;
950 int do_signal_trigger;
955 uint8_t sample_buff[sizeof(state)];
959 logic.unitsize = sizeof(sample_buff);
960 logic.data = devc->convbuffer;
962 sr_packet.type = SR_DF_LOGIC;
963 sr_packet.payload = &logic;
965 max_samples = devc->convbuffer_size / sizeof(sample_buff);
967 wp = devc->convbuffer;
969 do_signal_trigger = 0;
971 if (devc->had_triggers_configured && devc->reading_behind_trigger == 0 && devc->info.n_rep_packets_before_trigger == 0) {
972 std_session_send_df_trigger(sdi);
973 devc->reading_behind_trigger = 1;
977 for (i = 0; i < num_tfers; i++) {
978 for (k = 0; k < NUM_PACKETS_IN_CHUNK; k++) {
979 free_n_samples = max_samples - n_samples;
980 if (free_n_samples < 256 || do_signal_trigger) {
981 logic.length = n_samples * 2;
982 sr_session_send(sdi, &sr_packet);
984 wp = devc->convbuffer;
985 if (do_signal_trigger) {
986 std_session_send_df_trigger(sdi);
987 do_signal_trigger = 0;
991 state = read_u16le_inc(&rp);
992 repetitions = read_u8_inc(&rp);
993 write_u16le((void *)&sample_buff, state);
994 for (j = 0; j < repetitions; j++) {
995 memcpy(wp, sample_buff, logic.unitsize);
996 wp += logic.unitsize;
999 n_samples += repetitions;
1000 total_samples += repetitions;
1001 devc->total_samples += repetitions;
1002 if (!devc->reading_behind_trigger) {
1003 devc->n_reps_until_trigger--;
1004 if (devc->n_reps_until_trigger == 0) {
1005 devc->reading_behind_trigger = 1;
1006 do_signal_trigger = 1;
1007 sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
1008 devc->total_samples,
1009 (double)devc->total_samples / devc->cur_samplerate * 1e3);
1013 (void)read_u8_inc(&rp); /* Skip sequence number. */
1016 logic.length = n_samples * logic.unitsize;
1017 sr_session_send(sdi, &sr_packet);
1018 if (do_signal_trigger) {
1019 std_session_send_df_trigger(sdi);
1022 sr_dbg("Send_chunk done after %u samples.", total_samples);
1025 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
1027 struct sr_dev_inst *sdi;
1028 struct dev_context *devc;
1029 struct sr_usb_dev_inst *usb;
1032 sdi = transfer->user_data;
1036 sr_dbg("receive_transfer(): status %s received %d bytes.",
1037 libusb_error_name(transfer->status), transfer->actual_length);
1039 if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
1040 sr_err("USB bulk transfer timeout.");
1041 devc->transfer_finished = 1;
1043 send_chunk(sdi, transfer->buffer, transfer->actual_length / TRANSFER_PACKET_LENGTH);
1045 devc->n_bytes_to_read -= transfer->actual_length;
1046 if (devc->n_bytes_to_read) {
1047 uint32_t to_read = devc->n_bytes_to_read;
1049 * Determine read size for the next USB transfer. Make
1050 * the buffer size a multiple of the endpoint packet
1051 * size. Don't exceed a maximum value.
1053 if (to_read >= LA2016_USB_BUFSZ)
1054 to_read = LA2016_USB_BUFSZ;
1056 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
1057 libusb_fill_bulk_transfer(transfer,
1058 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1059 transfer->buffer, to_read,
1060 receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
1062 if ((ret = libusb_submit_transfer(transfer)) == 0)
1064 sr_err("Cannot submit another USB transfer: %s.",
1065 libusb_error_name(ret));
1068 g_free(transfer->buffer);
1069 libusb_free_transfer(transfer);
1070 devc->transfer_finished = 1;
1073 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1075 const struct sr_dev_inst *sdi;
1076 struct dev_context *devc;
1077 struct drv_context *drvc;
1085 drvc = sdi->driver->context;
1087 if (devc->have_trigger == 0) {
1088 if (la2016_has_triggered(sdi) == 0) {
1089 /* Not yet ready for sample data download. */
1092 devc->have_trigger = 1;
1093 devc->transfer_finished = 0;
1094 devc->reading_behind_trigger = 0;
1095 devc->total_samples = 0;
1096 /* We can start downloading sample data. */
1097 if (la2016_start_retrieval(sdi, receive_transfer) != SR_OK) {
1098 sr_err("Cannot start acquisition data download.");
1101 sr_dbg("Acquisition data download started.");
1102 std_session_send_df_frame_begin(sdi);
1107 tv.tv_sec = tv.tv_usec = 0;
1108 libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1110 if (devc->transfer_finished) {
1111 sr_dbg("Download finished, post processing.");
1112 std_session_send_df_frame_end(sdi);
1114 usb_source_remove(sdi->session, drvc->sr_ctx);
1115 std_session_send_df_end(sdi);
1117 la2016_stop_acquisition(sdi);
1119 g_free(devc->convbuffer);
1120 devc->convbuffer = NULL;
1122 devc->transfer = NULL;
1124 sr_dbg("Download finished, done post processing.");
1130 SR_PRIV int la2016_init_device(const struct sr_dev_inst *sdi)
1132 struct dev_context *devc;
1135 const uint8_t *rdptr;
1136 uint8_t date_yy, date_mm;
1137 uint8_t dinv_yy, dinv_mm;
1139 const char *bitstream_fn;
1145 * Four EEPROM bytes at offset 0x20 are the manufacturing date,
1146 * year and month in BCD format, followed by inverted values for
1147 * consistency checks. For example bytes 20 04 df fb translate
1148 * to 2020-04. This information can help identify the vintage of
1149 * devices when unknown magic numbers are seen.
1151 ret = ctrl_in(sdi, CMD_EEPROM, 0x20, 0, buf, 4 * sizeof(uint8_t));
1153 sr_err("Cannot read manufacture date in EEPROM.");
1156 date_yy = read_u8_inc(&rdptr);
1157 date_mm = read_u8_inc(&rdptr);
1158 dinv_yy = read_u8_inc(&rdptr);
1159 dinv_mm = read_u8_inc(&rdptr);
1160 sr_info("Manufacture date: 20%02hx-%02hx.", date_yy, date_mm);
1161 if ((date_mm ^ dinv_mm) != 0xff || (date_yy ^ dinv_yy) != 0xff)
1162 sr_warn("Manufacture date fails checksum test.");
1166 * Several Kingst logic analyzer devices share the same USB VID
1167 * and PID. The product ID determines which MCU firmware to load.
1168 * The MCU firmware provides access to EEPROM content which then
1169 * allows to identify the device model. Which in turn determines
1170 * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1173 * EEPROM content for model identification is kept redundantly
1174 * in memory. The values are stored in verbatim and in inverted
1175 * form, multiple copies are kept at different offsets. Example
1186 * Exclusively inspecting the magic byte appears to be sufficient,
1187 * other fields seem to be 'don't care'.
1189 * magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1190 * magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1191 * magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1192 * (latest v1.3.0 PCB, perhaps others)
1193 * magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1194 * (latest v1.3.0 PCB, perhaps others)
1196 * When EEPROM content does not match the hardware configuration
1197 * (the board layout), the software may load but yield incorrect
1198 * results (like swapped channels). The FPGA bitstream itself
1199 * will authenticate with IC U10 and fail when its capabilities
1200 * do not match the hardware model. An LA1016 won't become a
1201 * LA2016 by faking its EEPROM content.
1203 if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x08, 0, &buf, sizeof(buf))) != SR_OK) {
1204 sr_err("Cannot read EEPROM device identifier bytes.");
1207 if ((buf[0] ^ buf[1]) == 0xff) {
1208 /* Primary copy of magic passes complement check. */
1209 sr_dbg("Using primary copy of device type magic number.");
1211 } else if ((buf[4] ^ buf[5]) == 0xff) {
1212 /* Backup copy of magic passes complement check. */
1213 sr_dbg("Using backup copy of device type magic number.");
1216 sr_err("Cannot find consistent device type identification.");
1219 sr_dbg("Device type: magic number is %hhu.", magic);
1221 /* Select the FPGA bitstream depending on the model. */
1224 bitstream_fn = FPGA_FW_LA2016;
1225 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1228 bitstream_fn = FPGA_FW_LA1016;
1229 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1232 bitstream_fn = FPGA_FW_LA2016A;
1233 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1236 bitstream_fn = FPGA_FW_LA1016A;
1237 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1240 bitstream_fn = NULL;
1243 if (!bitstream_fn || !*bitstream_fn) {
1244 sr_err("Cannot identify as one of the supported models.");
1248 if (check_fpga_bitstream(sdi) != SR_OK) {
1249 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1251 sr_err("Cannot upload FPGA bitstream.");
1255 ret = enable_fpga_bitstream(sdi);
1257 sr_err("Cannot enable FPGA bitstream after upload.");
1261 state = run_state(sdi);
1262 if (state != 0x85e9) {
1263 sr_warn("Unexpected run state, want 0x85e9, got 0x%04x.", state);
1266 if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
1267 sr_err("Cannot reset USB bulk transfer.");
1271 sr_dbg("Device should be initialized.");
1273 ret = set_defaults(sdi);
1280 SR_PRIV int la2016_deinit_device(const struct sr_dev_inst *sdi)
1284 if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0)) != SR_OK) {
1285 sr_err("Cannot deinitialize device's FPGA.");