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 /* USB PID dependent MCU firmware. Model dependent FPGA bitstream. */
32 #define MCU_FWFILE_FMT "kingst-la-%04x.fw"
33 #define FPGA_FWFILE_FMT "kingst-%s-fpga.bitstream"
36 * List of supported devices and their features. See @ref kingst_model
37 * for the fields' type and meaning. Table is sorted by EEPROM magic.
40 * - Below LA1016 properties were guessed, need verification.
41 * - Add LA5016 and LA5032 devices when their EEPROM magic is known.
42 * - Does LA1010 fit the driver implementation? Samplerates vary with
43 * channel counts, lack of local sample memory. Most probably not.
45 static const struct kingst_model models[] = {
46 { 2, "LA2016", "la2016", SR_MHZ(200), 16, 1, },
47 { 3, "LA1016", "la1016", SR_MHZ(100), 16, 1, },
48 { 8, "LA2016", "la2016a1", SR_MHZ(200), 16, 1, },
49 { 9, "LA1016", "la1016a1", SR_MHZ(100), 16, 1, },
52 /* USB vendor class control requests, executed by the Cypress FX2 MCU. */
53 #define CMD_FPGA_ENABLE 0x10
54 #define CMD_FPGA_SPI 0x20 /* R/W access to FPGA registers via SPI. */
55 #define CMD_BULK_START 0x30 /* Start sample data download via USB EP6 IN. */
56 #define CMD_BULK_RESET 0x38 /* Flush FIFO of FX2 USB EP6 IN. */
57 #define CMD_FPGA_INIT 0x50 /* Used before and after FPGA bitstream upload. */
58 #define CMD_KAUTH 0x60 /* Communicate to auth IC (U10). Not used. */
59 #define CMD_EEPROM 0xa2 /* R/W access to EEPROM content. */
62 * FPGA register addresses (base addresses when registers span multiple
63 * bytes, in that case data is kept in little endian format). Passed to
64 * CMD_FPGA_SPI requests. The FX2 MCU transparently handles the detail
65 * of SPI transfers encoding the read (1) or write (0) direction in the
66 * MSB of the address field. There are some 60 byte-wide FPGA registers.
68 * Unfortunately the FPGA registers change their meaning between the
69 * read and write directions of access, or exclusively provide one of
70 * these directions and not the other. This is an arbitrary vendor's
71 * choice, there is nothing which the sigrok driver could do about it.
72 * Values written to registers typically cannot get read back, neither
73 * verified after writing a configuration, nor queried upon startup for
74 * automatic detection of the current configuration. Neither appear to
75 * be there echo registers for presence and communication checks, nor
76 * version identifying registers, as far as we know.
78 #define REG_RUN 0x00 /* Read capture status, write start capture. */
79 #define REG_PWM_EN 0x02 /* User PWM channels on/off. */
80 #define REG_CAPT_MODE 0x03 /* Write 0x00 capture to SDRAM, 0x01 streaming. */
81 #define REG_BULK 0x08 /* Write start addr, byte count to download samples. */
82 #define REG_SAMPLING 0x10 /* Write capture config, read capture SDRAM location. */
83 #define REG_TRIGGER 0x20 /* Write level and edge trigger config. */
84 #define REG_UNKNOWN_30 0x30
85 #define REG_THRESHOLD 0x68 /* Write PWM config to setup input threshold DAC. */
86 #define REG_PWM1 0x70 /* Write config for user PWM1. */
87 #define REG_PWM2 0x78 /* Write config for user PWM2. */
89 /* Bit patterns to write to REG_CAPT_MODE. */
90 #define CAPTMODE_TO_RAM 0x00
91 #define CAPTMODE_STREAM 0x01
93 /* Bit patterns to write to REG_RUN, setup run mode. */
94 #define RUNMODE_HALT 0x00
95 #define RUNMODE_RUN 0x03
97 /* Bit patterns when reading from REG_RUN, get run state. */
98 #define RUNSTATE_IDLE_BIT (1UL << 0)
99 #define RUNSTATE_DRAM_BIT (1UL << 1)
100 #define RUNSTATE_TRGD_BIT (1UL << 2)
101 #define RUNSTATE_POST_BIT (1UL << 3)
103 static int ctrl_in(const struct sr_dev_inst *sdi,
104 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
105 void *data, uint16_t wLength)
107 struct sr_usb_dev_inst *usb;
112 ret = libusb_control_transfer(usb->devhdl,
113 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
114 bRequest, wValue, wIndex, data, wLength,
116 if (ret != wLength) {
117 sr_dbg("USB ctrl in: %d bytes, req %d val %#x idx %d: %s.",
118 wLength, bRequest, wValue, wIndex,
119 libusb_error_name(ret));
120 sr_err("Cannot read %d bytes from USB: %s.",
121 wLength, libusb_error_name(ret));
128 static int ctrl_out(const struct sr_dev_inst *sdi,
129 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
130 void *data, uint16_t wLength)
132 struct sr_usb_dev_inst *usb;
137 ret = libusb_control_transfer(usb->devhdl,
138 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
139 bRequest, wValue, wIndex, data, wLength,
141 if (ret != wLength) {
142 sr_dbg("USB ctrl out: %d bytes, req %d val %#x idx %d: %s.",
143 wLength, bRequest, wValue, wIndex,
144 libusb_error_name(ret));
145 sr_err("Cannot write %d bytes to USB: %s.",
146 wLength, libusb_error_name(ret));
153 /* HACK Experiment to spot FPGA registers of interest. */
154 static void la2016_dump_fpga_registers(const struct sr_dev_inst *sdi,
155 const char *caption, size_t reg_lower, size_t reg_upper)
157 static const size_t dump_chunk_len = 16;
160 uint8_t rdbuf[0x80 - 0x00]; /* Span all FPGA registers. */
161 const uint8_t *rdptr;
163 size_t dump_addr, indent, dump_len;
166 if (sr_log_loglevel_get() < SR_LOG_SPEW)
169 if (!reg_lower && !reg_upper) {
171 reg_upper = sizeof(rdbuf);
173 if (reg_upper - reg_lower > sizeof(rdbuf))
174 reg_upper = sizeof(rdbuf) - reg_lower;
176 rdlen = reg_upper - reg_lower;
177 ret = ctrl_in(sdi, CMD_FPGA_SPI, reg_lower, 0, rdbuf, rdlen);
179 sr_err("Cannot get registers space.");
184 sr_spew("FPGA registers dump: %s", caption ? : "for fun");
185 dump_addr = reg_lower;
188 indent = dump_addr % dump_chunk_len;
189 if (dump_len > dump_chunk_len)
190 dump_len = dump_chunk_len;
191 if (dump_len + indent > dump_chunk_len)
192 dump_len = dump_chunk_len - indent;
193 txt = sr_hexdump_new(rdptr, dump_len);
194 sr_spew(" %04zx %*s%s",
195 dump_addr, (int)(3 * indent), "", txt->str);
196 sr_hexdump_free(txt);
197 dump_addr += dump_len;
204 * Check the necessity for FPGA bitstream upload, because another upload
205 * would take some 600ms which is undesirable after program startup. Try
206 * to access some FPGA registers and check the values' plausibility. The
207 * check should fail on the safe side, request another upload when in
208 * doubt. A positive response (the request to continue operation with the
209 * currently active bitstream) should be conservative. Accessing multiple
210 * registers is considered cheap compared to the cost of bitstream upload.
212 * It helps though that both the vendor software and the sigrok driver
213 * use the same bundle of MCU firmware and FPGA bitstream for any of the
214 * supported models. We don't expect to successfully communicate to the
215 * device yet disagree on its protocol. Ideally we would access version
216 * identifying registers for improved robustness, but are not aware of
217 * any. A bitstream reload can always be forced by a power cycle.
219 static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
222 uint8_t buff[REG_PWM_EN - REG_RUN]; /* Larger of REG_RUN, REG_PWM_EN. */
227 const uint8_t *rdptr;
229 sr_dbg("Checking operation of the FPGA bitstream.");
230 la2016_dump_fpga_registers(sdi, "bitstream check", 0, 0);
233 ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
234 if (ret != SR_OK || init_rsp != 0) {
235 sr_dbg("FPGA init query failed, or unexpected response.");
239 read_len = sizeof(run_state);
240 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, read_len);
242 sr_dbg("FPGA register access failed (run state).");
246 run_state = read_u16le_inc(&rdptr);
247 sr_spew("FPGA register: run state 0x%04x.", run_state);
248 if (run_state && (run_state & 0x3) != 0x1) {
249 sr_dbg("Unexpected FPGA register content (run state).");
252 if (run_state && (run_state & ~0xf) != 0x85e0) {
253 sr_dbg("Unexpected FPGA register content (run state).");
257 read_len = sizeof(pwm_en);
258 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, buff, read_len);
260 sr_dbg("FPGA register access failed (PWM enable).");
264 pwm_en = read_u8_inc(&rdptr);
265 sr_spew("FPGA register: PWM enable 0x%02x.", pwm_en);
266 if ((pwm_en & 0x3) != 0x0) {
267 sr_dbg("Unexpected FPGA register content (PWM enable).");
271 sr_info("Could re-use current FPGA bitstream. No upload required.");
275 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
276 const char *bitstream_fname)
278 struct drv_context *drvc;
279 struct sr_usb_dev_inst *usb;
280 struct sr_resource bitstream;
281 uint32_t bitstream_size;
282 uint8_t buffer[sizeof(uint32_t)];
288 unsigned int zero_pad_to;
290 drvc = sdi->driver->context;
293 sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
295 ret = sr_resource_open(drvc->sr_ctx, &bitstream,
296 SR_RESOURCE_FIRMWARE, bitstream_fname);
298 sr_err("Cannot find FPGA bitstream %s.", bitstream_fname);
302 bitstream_size = (uint32_t)bitstream.size;
304 write_u32le_inc(&wrptr, bitstream_size);
305 ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer);
307 sr_err("Cannot initiate FPGA bitstream upload.");
308 sr_resource_close(drvc->sr_ctx, &bitstream);
311 zero_pad_to = bitstream_size;
312 zero_pad_to += LA2016_EP2_PADDING - 1;
313 zero_pad_to /= LA2016_EP2_PADDING;
314 zero_pad_to *= LA2016_EP2_PADDING;
318 if (pos < bitstream.size) {
319 len = (int)sr_resource_read(drvc->sr_ctx, &bitstream,
320 block, sizeof(block));
322 sr_err("Cannot read FPGA bitstream.");
323 sr_resource_close(drvc->sr_ctx, &bitstream);
327 /* Zero-pad until 'zero_pad_to'. */
328 len = zero_pad_to - pos;
329 if ((unsigned)len > sizeof(block))
331 memset(&block, 0, len);
336 ret = libusb_bulk_transfer(usb->devhdl, USB_EP_FPGA_BITSTREAM,
337 &block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
339 sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
340 pos, (int)len, libusb_error_name(ret));
344 if (act_len != len) {
345 sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
346 pos, (int)len, act_len);
352 sr_resource_close(drvc->sr_ctx, &bitstream);
355 sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.",
361 static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
366 ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &resp, sizeof(resp));
368 sr_err("Cannot read response after FPGA bitstream upload.");
372 sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
378 ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0);
380 sr_err("Cannot enable FPGA after bitstream upload.");
388 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
391 uint16_t duty_R79, duty_R56;
392 uint8_t buf[REG_PWM1 - REG_THRESHOLD]; /* Width of REG_THRESHOLD. */
395 /* Clamp threshold setting to valid range for LA2016. */
396 if (voltage > LA2016_THR_VOLTAGE_MAX) {
397 voltage = LA2016_THR_VOLTAGE_MAX;
398 } else if (voltage < -LA2016_THR_VOLTAGE_MAX) {
399 voltage = -LA2016_THR_VOLTAGE_MAX;
403 * Two PWM output channels feed one DAC which generates a bias
404 * voltage, which offsets the input probe's voltage level, and
405 * in combination with the FPGA pins' fixed threshold result in
406 * a programmable input threshold from the user's perspective.
407 * The PWM outputs can be seen on R79 and R56 respectively, the
408 * frequency is 100kHz and the duty cycle varies. The R79 PWM
409 * uses three discrete settings. The R56 PWM varies with desired
410 * thresholds and depends on the R79 PWM configuration. See the
411 * schematics comments which discuss the formulae.
413 if (voltage >= 2.9) {
414 duty_R79 = 0; /* PWM off (0V). */
415 duty_R56 = (uint16_t)(302 * voltage - 363);
416 } else if (voltage > -0.4) {
417 duty_R79 = 0x00f2; /* 25% duty cycle. */
418 duty_R56 = (uint16_t)(302 * voltage + 121);
420 duty_R79 = 0x02d7; /* 72% duty cycle. */
421 duty_R56 = (uint16_t)(302 * voltage + 1090);
424 /* Clamp duty register values to sensible limits. */
427 } else if (duty_R56 > 1100) {
431 sr_dbg("Set threshold voltage %.2fV.", voltage);
432 sr_dbg("Duty cycle values: R56 0x%04x, R79 0x%04x.", duty_R56, duty_R79);
435 write_u16le_inc(&wrptr, duty_R56);
436 write_u16le_inc(&wrptr, duty_R79);
438 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_THRESHOLD, 0, buf, wrptr - buf);
440 sr_err("Cannot set threshold voltage %.2fV.", voltage);
448 * Communicates a channel's configuration to the device after the
449 * parameters may have changed. Configuration of one channel may
450 * interfere with other channels since they share FPGA registers.
452 static int set_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
454 static uint8_t reg_bases[] = { REG_PWM1, REG_PWM2, };
456 struct dev_context *devc;
457 struct pwm_setting *params;
461 uint32_t period, duty;
464 uint8_t enable_all, enable_cfg, reg_val;
465 uint8_t buf[REG_PWM2 - REG_PWM1]; /* Width of one REG_PWMx. */
469 if (idx >= ARRAY_SIZE(devc->pwm_setting))
471 params = &devc->pwm_setting[idx];
472 if (idx >= ARRAY_SIZE(reg_bases))
474 reg_base = reg_bases[idx];
477 * Map application's specs to hardware register values. Do math
478 * in floating point initially, but convert to u32 eventually.
480 sr_dbg("PWM config, app spec, ch %zu, en %d, freq %.1f, duty %.1f.",
481 idx, params->enabled ? 1 : 0, params->freq, params->duty);
483 val_f /= params->freq;
487 val_f *= params->duty;
492 sr_dbg("PWM config, reg 0x%04x, freq %u, duty %u.",
493 (unsigned)reg_base, (unsigned)period, (unsigned)duty);
495 /* Get the "enabled" state of all supported PWM channels. */
497 for (ch = 0; ch < ARRAY_SIZE(devc->pwm_setting); ch++) {
498 if (!devc->pwm_setting[ch].enabled)
500 enable_all |= 1U << ch;
502 enable_cfg = 1U << idx;
503 sr_spew("PWM config, enable all 0x%02hhx, cfg 0x%02hhx.",
504 enable_all, enable_cfg);
507 * Disable the to-get-configured channel before its parameters
508 * will change. Or disable and exit when the channel is supposed
511 sr_spew("PWM config, disabling before param change.");
512 reg_val = enable_all & ~enable_cfg;
513 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0,
514 ®_val, sizeof(reg_val));
516 sr_err("Cannot adjust PWM enabled state.");
519 if (!params->enabled)
522 /* Write register values to device. */
523 sr_spew("PWM config, sending new parameters.");
525 write_u32le_inc(&wrptr, period);
526 write_u32le_inc(&wrptr, duty);
527 ret = ctrl_out(sdi, CMD_FPGA_SPI, reg_base, 0, buf, wrptr - buf);
529 sr_err("Cannot change PWM parameters.");
533 /* Enable configured channel after write completion. */
534 sr_spew("PWM config, enabling after param change.");
535 reg_val = enable_all | enable_cfg;
536 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0,
537 ®_val, sizeof(reg_val));
539 sr_err("Cannot adjust PWM enabled state.");
546 static uint32_t get_channels_mask(const struct sr_dev_inst *sdi)
550 struct sr_channel *ch;
553 for (l = sdi->channels; l; l = l->next) {
555 if (ch->type != SR_CHANNEL_LOGIC)
559 channels |= 1UL << ch->index;
565 static int set_trigger_config(const struct sr_dev_inst *sdi)
567 struct dev_context *devc;
568 struct sr_trigger *trigger;
570 uint32_t channels; /* Actually: Enabled channels? */
571 uint32_t enabled; /* Actually: Triggering channels? */
573 uint32_t high_or_falling;
577 struct sr_trigger_stage *stage1;
578 struct sr_trigger_match *match;
581 uint8_t buf[REG_UNKNOWN_30 - REG_TRIGGER]; /* Width of REG_TRIGGER. */
585 trigger = sr_session_trigger_get(sdi->session);
587 memset(&cfg, 0, sizeof(cfg));
589 cfg.channels = get_channels_mask(sdi);
591 if (trigger && trigger->stages) {
592 stages = trigger->stages;
593 stage1 = stages->data;
595 sr_err("Only one trigger stage supported for now.");
598 channel = stage1->matches;
600 match = channel->data;
601 ch_mask = 1UL << match->channel->index;
603 switch (match->match) {
604 case SR_TRIGGER_ZERO:
605 cfg.level |= ch_mask;
606 cfg.high_or_falling &= ~ch_mask;
609 cfg.level |= ch_mask;
610 cfg.high_or_falling |= ch_mask;
612 case SR_TRIGGER_RISING:
613 if ((cfg.enabled & ~cfg.level)) {
614 sr_err("Device only supports one edge trigger.");
617 cfg.level &= ~ch_mask;
618 cfg.high_or_falling &= ~ch_mask;
620 case SR_TRIGGER_FALLING:
621 if ((cfg.enabled & ~cfg.level)) {
622 sr_err("Device only supports one edge trigger.");
625 cfg.level &= ~ch_mask;
626 cfg.high_or_falling |= ch_mask;
629 sr_err("Unknown trigger condition.");
632 cfg.enabled |= ch_mask;
633 channel = channel->next;
636 sr_dbg("Set trigger config: "
637 "enabled-channels 0x%04x, triggering-channels 0x%04x, "
638 "level-triggered 0x%04x, high/falling 0x%04x.",
639 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
641 devc->trigger_involved = cfg.enabled != 0;
644 write_u32le_inc(&wrptr, cfg.channels);
645 write_u32le_inc(&wrptr, cfg.enabled);
646 write_u32le_inc(&wrptr, cfg.level);
647 write_u32le_inc(&wrptr, cfg.high_or_falling);
649 * Comment on this literal 16. Origin, meaning? Cannot be the
650 * register offset, nor the transfer length. Is it a channels
651 * count that is relevant for 16 and 32 channel models? Is it
652 * an obsolete experiment?
654 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
656 sr_err("Cannot setup trigger configuration.");
663 static int set_sample_config(const struct sr_dev_inst *sdi)
665 struct dev_context *devc;
666 uint64_t min_samplerate, eff_samplerate;
667 uint16_t divider_u16;
668 uint64_t limit_samples;
669 uint64_t pre_trigger_samples;
670 uint64_t pre_trigger_memory;
671 uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
677 if (devc->samplerate > devc->model->samplerate) {
678 sr_err("Too high a sample rate: %" PRIu64 ".",
682 min_samplerate = devc->model->samplerate;
683 min_samplerate /= 65536;
684 if (devc->samplerate < min_samplerate) {
685 sr_err("Too low a sample rate: %" PRIu64 ".",
689 divider_u16 = devc->model->samplerate / devc->samplerate;
690 eff_samplerate = devc->model->samplerate / divider_u16;
692 ret = sr_sw_limits_get_remain(&devc->sw_limits,
693 &limit_samples, NULL, NULL, NULL);
695 sr_err("Cannot get acquisition limits.");
698 if (limit_samples > LA2016_NUM_SAMPLES_MAX) {
699 sr_warn("Too high a sample depth: %" PRIu64 ", capping.",
701 limit_samples = LA2016_NUM_SAMPLES_MAX;
703 if (limit_samples == 0) {
704 limit_samples = LA2016_NUM_SAMPLES_MAX;
705 sr_dbg("Passing %" PRIu64 " to HW for unlimited samples.",
710 * The acquisition configuration communicates "pre-trigger"
711 * specs in several formats. sigrok users provide a percentage
712 * (0-100%), which translates to a pre-trigger samples count
713 * (assuming that a total samples count limit was specified).
714 * The device supports hardware compression, which depends on
715 * slowly changing input data to be effective. Fast changing
716 * input data may occupy more space in sample memory than its
717 * uncompressed form would. This is why a third parameter can
718 * limit the amount of sample memory to use for pre-trigger
719 * data. Only the upper 24 bits of that memory size spec get
720 * communicated to the device (written to its FPGA register).
722 * TODO Determine whether the pre-trigger memory size gets
723 * specified in samples or in bytes. A previous implementation
724 * suggests bytes but this is suspicious when every other spec
725 * is in terms of samples.
727 if (devc->trigger_involved) {
728 pre_trigger_samples = limit_samples;
729 pre_trigger_samples *= devc->capture_ratio;
730 pre_trigger_samples /= 100;
731 pre_trigger_memory = devc->model->memory_bits;
732 pre_trigger_memory *= UINT64_C(1024 * 1024 * 1024);
733 pre_trigger_memory /= 8; /* devc->model->channel_count ? */
734 pre_trigger_memory *= devc->capture_ratio;
735 pre_trigger_memory /= 100;
737 sr_dbg("No trigger setup, skipping pre-trigger config.");
738 pre_trigger_samples = 1;
739 pre_trigger_memory = 0;
741 /* Ensure non-zero value after LSB shift out in HW reg. */
742 if (pre_trigger_memory < 0x100) {
743 pre_trigger_memory = 0x100;
746 sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples.",
747 eff_samplerate / SR_KHZ(1), limit_samples);
748 sr_dbg("Capture ratio %" PRIu64 "%%, count %" PRIu64 ", mem %" PRIu64 ".",
749 devc->capture_ratio, pre_trigger_samples, pre_trigger_memory);
752 * The acquisition configuration occupies a total of 16 bytes:
753 * - A 34bit total samples count limit (up to 10 billions) that
754 * is kept in a 40bit register.
755 * - A 34bit pre-trigger samples count limit (up to 10 billions)
756 * in another 40bit register.
757 * - A 32bit pre-trigger memory space limit (in bytes) of which
758 * the upper 24bits are kept in an FPGA register.
759 * - A 16bit clock divider which gets applied to the maximum
760 * samplerate of the device.
761 * - An 8bit register of unknown meaning. Currently always 0.
764 write_u40le_inc(&wrptr, limit_samples);
765 write_u40le_inc(&wrptr, pre_trigger_samples);
766 write_u24le_inc(&wrptr, pre_trigger_memory >> 8);
767 write_u16le_inc(&wrptr, divider_u16);
768 write_u8_inc(&wrptr, 0);
769 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
771 sr_err("Cannot setup acquisition configuration.");
779 * FPGA register REG_RUN holds the run state (u16le format). Bit fields
781 * bit 0: value 1 = idle
782 * bit 1: value 1 = writing to SDRAM
783 * bit 2: value 0 = waiting for trigger, 1 = trigger seen
784 * bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
785 * The meaning of other bit fields is unknown.
787 * Typical values in order of appearance during execution:
788 * 0x85e1: idle, no acquisition pending
789 * IDLE set, TRGD don't care, POST don't care; DRAM don't care
790 * "In idle state." Takes precedence over all others.
791 * 0x85e2: pre-sampling, samples before the trigger position,
792 * when capture ratio > 0%
793 * IDLE clear, TRGD clear, POST clear; DRAM don't care
794 * "Not idle any more, no post yet, not triggered yet."
795 * 0x85ea: pre-sampling complete, now waiting for the trigger
796 * (whilst sampling continuously)
797 * IDLE clear, TRGD clear, POST set; DRAM don't care
798 * "Post set thus after pre, not triggered yet"
799 * 0x85ee: trigger seen, capturing post-trigger samples, running
800 * IDLE clear, TRGD set, POST set; DRAM don't care
801 * "Triggered and in post, not idle yet."
803 * IDLE set, TRGD don't care, POST don't care; DRAM don't care
804 * "In idle state." TRGD/POST don't care, same meaning as above.
806 static const uint16_t runstate_mask_idle = RUNSTATE_IDLE_BIT;
807 static const uint16_t runstate_patt_idle = RUNSTATE_IDLE_BIT;
808 static const uint16_t runstate_mask_step =
809 RUNSTATE_IDLE_BIT | RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
810 static const uint16_t runstate_patt_pre_trig = 0;
811 static const uint16_t runstate_patt_wait_trig = RUNSTATE_POST_BIT;
812 static const uint16_t runstate_patt_post_trig =
813 RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
815 static uint16_t run_state(const struct sr_dev_inst *sdi)
817 static uint16_t previous_state;
821 uint8_t buff[REG_PWM_EN - REG_RUN]; /* Width of REG_RUN. */
822 const uint8_t *rdptr;
825 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, sizeof(state));
827 sr_err("Cannot read run state.");
831 state = read_u16le_inc(&rdptr);
834 * Avoid flooding the log, only dump values as they change.
835 * The routine is called about every 50ms.
837 if (state == previous_state)
840 previous_state = state;
842 if ((state & runstate_mask_idle) == runstate_patt_idle)
844 if ((state & runstate_mask_step) == runstate_patt_pre_trig)
845 label = "pre-trigger sampling";
846 if ((state & runstate_mask_step) == runstate_patt_wait_trig)
847 label = "sampling, waiting for trigger";
848 if ((state & runstate_mask_step) == runstate_patt_post_trig)
849 label = "post-trigger sampling";
851 sr_dbg("Run state: 0x%04x (%s).", state, label);
853 sr_dbg("Run state: 0x%04x.", state);
858 static int la2016_is_idle(const struct sr_dev_inst *sdi)
862 state = run_state(sdi);
863 if ((state & runstate_mask_idle) == runstate_patt_idle)
869 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
873 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode));
875 sr_err("Cannot configure run mode %d.", mode);
882 static int get_capture_info(const struct sr_dev_inst *sdi)
884 struct dev_context *devc;
886 uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
887 const uint8_t *rdptr;
891 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf));
893 sr_err("Cannot read capture info.");
898 devc->info.n_rep_packets = read_u32le_inc(&rdptr);
899 devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
900 devc->info.write_pos = read_u32le_inc(&rdptr);
902 sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x/%d.",
903 devc->info.n_rep_packets, devc->info.n_rep_packets,
904 devc->info.n_rep_packets_before_trigger,
905 devc->info.n_rep_packets_before_trigger,
906 devc->info.write_pos, devc->info.write_pos);
908 if (devc->info.n_rep_packets % devc->packets_per_chunk) {
909 sr_warn("Unexpected packets count %lu, not a multiple of %lu.",
910 (unsigned long)devc->info.n_rep_packets,
911 (unsigned long)devc->packets_per_chunk);
917 SR_PRIV int la2016_upload_firmware(const struct sr_dev_inst *sdi,
918 struct sr_context *sr_ctx, libusb_device *dev, gboolean skip_upload)
920 struct dev_context *devc;
925 devc = sdi ? sdi->priv : NULL;
926 if (!devc || !devc->usb_pid)
930 fw = g_strdup_printf(MCU_FWFILE_FMT, pid);
931 sr_info("USB PID %04hx, MCU firmware '%s'.", pid, fw);
932 devc->mcu_firmware = g_strdup(fw);
937 ret = ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw);
945 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi,
951 ret = set_threshold_voltage(sdi, voltage);
955 cmd = CAPTMODE_TO_RAM;
956 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd));
958 sr_err("Cannot send command to stop sampling.");
962 ret = set_trigger_config(sdi);
966 ret = set_sample_config(sdi);
973 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
977 ret = set_run_mode(sdi, RUNMODE_RUN);
984 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
988 ret = set_run_mode(sdi, RUNMODE_HALT);
995 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
998 struct dev_context *devc;
1000 ret = la2016_stop_acquisition(sdi);
1004 devc = sdi ? sdi->priv : NULL;
1005 if (devc && devc->transfer)
1006 libusb_cancel_transfer(devc->transfer);
1011 static int la2016_start_download(const struct sr_dev_inst *sdi,
1012 libusb_transfer_cb_fn cb)
1014 struct dev_context *devc;
1015 struct sr_usb_dev_inst *usb;
1017 uint8_t wrbuf[REG_SAMPLING - REG_BULK]; /* Width of REG_BULK. */
1025 ret = get_capture_info(sdi);
1029 devc->n_transfer_packets_to_read = devc->info.n_rep_packets;
1030 devc->n_transfer_packets_to_read /= devc->packets_per_chunk;
1031 devc->n_bytes_to_read = devc->n_transfer_packets_to_read;
1032 devc->n_bytes_to_read *= TRANSFER_PACKET_LENGTH;
1033 devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
1034 devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
1036 sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
1037 devc->n_transfer_packets_to_read, devc->read_pos);
1039 ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
1041 sr_err("Cannot reset USB bulk state.");
1044 sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
1045 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
1047 write_u32le_inc(&wrptr, devc->read_pos);
1048 write_u32le_inc(&wrptr, devc->n_bytes_to_read);
1049 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf);
1051 sr_err("Cannot send USB bulk config.");
1054 ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0);
1056 sr_err("Cannot unblock USB bulk transfers.");
1061 * Pick a buffer size for all USB transfers. The buffer size
1062 * must be a multiple of the endpoint packet size. And cannot
1063 * exceed a maximum value.
1065 to_read = devc->n_bytes_to_read;
1066 if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
1067 to_read = LA2016_USB_BUFSZ;
1068 to_read += LA2016_EP6_PKTSZ - 1;
1069 to_read /= LA2016_EP6_PKTSZ;
1070 to_read *= LA2016_EP6_PKTSZ;
1071 buffer = g_try_malloc(to_read);
1073 sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
1074 sr_err("Cannot allocate buffer for USB bulk transfer.");
1075 return SR_ERR_MALLOC;
1078 devc->transfer = libusb_alloc_transfer(0);
1079 libusb_fill_bulk_transfer(devc->transfer,
1080 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1081 buffer, to_read, cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
1083 ret = libusb_submit_transfer(devc->transfer);
1085 sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
1086 libusb_free_transfer(devc->transfer);
1087 devc->transfer = NULL;
1096 * A chunk (received via USB) contains a number of transfers (USB length
1097 * divided by 16) which contain a number of packets (5 per transfer) which
1098 * contain a number of samples (8bit repeat count per 16bit sample data).
1100 static void send_chunk(struct sr_dev_inst *sdi,
1101 const uint8_t *packets, size_t num_xfers)
1103 struct dev_context *devc;
1106 uint32_t sample_value;
1108 uint8_t sample_buff[sizeof(sample_value)];
1112 /* Ignore incoming USB data after complete sample data download. */
1113 if (devc->download_finished)
1116 if (devc->trigger_involved && !devc->trigger_marked && devc->info.n_rep_packets_before_trigger == 0) {
1117 feed_queue_logic_send_trigger(devc->feed_queue);
1118 devc->trigger_marked = TRUE;
1123 while (num_xfers--) {
1124 num_pkts = devc->packets_per_chunk;
1125 while (num_pkts--) {
1127 /* TODO Verify 32channel layout. */
1128 if (devc->model->channel_count == 32)
1129 sample_value = read_u32le_inc(&rp);
1130 else if (devc->model->channel_count == 16)
1131 sample_value = read_u16le_inc(&rp);
1132 repetitions = read_u8_inc(&rp);
1134 devc->total_samples += repetitions;
1136 write_u32le(sample_buff, sample_value);
1137 feed_queue_logic_submit(devc->feed_queue,
1138 sample_buff, repetitions);
1139 sr_sw_limits_update_samples_read(&devc->sw_limits,
1142 if (devc->trigger_involved && !devc->trigger_marked) {
1143 if (!--devc->n_reps_until_trigger) {
1144 feed_queue_logic_send_trigger(devc->feed_queue);
1145 devc->trigger_marked = TRUE;
1146 sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
1147 devc->total_samples,
1148 (double)devc->total_samples / devc->samplerate * 1e3);
1152 (void)read_u8_inc(&rp); /* Skip sequence number. */
1155 if (!devc->download_finished && sr_sw_limits_check(&devc->sw_limits)) {
1156 sr_dbg("Acquisition limit reached.");
1157 devc->download_finished = TRUE;
1159 if (devc->download_finished) {
1160 sr_dbg("Download finished, flushing session feed queue.");
1161 feed_queue_logic_flush(devc->feed_queue);
1163 sr_dbg("Total samples after chunk: %" PRIu64 ".", devc->total_samples);
1166 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
1168 struct sr_dev_inst *sdi;
1169 struct dev_context *devc;
1170 struct sr_usb_dev_inst *usb;
1174 sdi = transfer->user_data;
1178 sr_dbg("receive_transfer(): status %s received %d bytes.",
1179 libusb_error_name(transfer->status), transfer->actual_length);
1181 * Implementation detail: A USB transfer timeout is not fatal
1182 * here. We just process whatever was received, empty input is
1183 * perfectly acceptable. Reaching (or exceeding) the sw limits
1184 * or exhausting the device's captured data will complete the
1185 * sample data download.
1187 num_xfers = transfer->actual_length / TRANSFER_PACKET_LENGTH;
1188 send_chunk(sdi, transfer->buffer, num_xfers);
1190 devc->n_bytes_to_read -= transfer->actual_length;
1191 if (devc->n_bytes_to_read) {
1192 uint32_t to_read = devc->n_bytes_to_read;
1194 * Determine read size for the next USB transfer. Make
1195 * the buffer size a multiple of the endpoint packet
1196 * size. Don't exceed a maximum value.
1198 if (to_read >= LA2016_USB_BUFSZ)
1199 to_read = LA2016_USB_BUFSZ;
1200 to_read += LA2016_EP6_PKTSZ - 1;
1201 to_read /= LA2016_EP6_PKTSZ;
1202 to_read *= LA2016_EP6_PKTSZ;
1203 libusb_fill_bulk_transfer(transfer,
1204 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1205 transfer->buffer, to_read,
1206 receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
1208 ret = libusb_submit_transfer(transfer);
1211 sr_err("Cannot submit another USB transfer: %s.",
1212 libusb_error_name(ret));
1215 g_free(transfer->buffer);
1216 libusb_free_transfer(transfer);
1217 devc->download_finished = TRUE;
1220 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1222 const struct sr_dev_inst *sdi;
1223 struct dev_context *devc;
1224 struct drv_context *drvc;
1233 drvc = sdi->driver->context;
1236 * Wait for the acquisition to complete in hardware.
1237 * Periodically check a potentially configured msecs timeout.
1239 if (!devc->completion_seen) {
1240 if (!la2016_is_idle(sdi)) {
1241 if (sr_sw_limits_check(&devc->sw_limits)) {
1242 devc->sw_limits.limit_msec = 0;
1243 sr_dbg("Limit reached. Stopping acquisition.");
1244 la2016_stop_acquisition(sdi);
1246 /* Not yet ready for sample data download. */
1249 sr_dbg("Acquisition completion seen (hardware).");
1250 devc->sw_limits.limit_msec = 0;
1251 devc->completion_seen = TRUE;
1252 devc->download_finished = FALSE;
1253 devc->trigger_marked = FALSE;
1254 devc->total_samples = 0;
1256 la2016_dump_fpga_registers(sdi, "acquisition complete", 0, 0);
1258 /* Initiate the download of acquired sample data. */
1259 std_session_send_df_frame_begin(sdi);
1260 devc->frame_begin_sent = TRUE;
1261 ret = la2016_start_download(sdi, receive_transfer);
1263 sr_err("Cannot start acquisition data download.");
1266 sr_dbg("Acquisition data download started.");
1271 /* Handle USB reception. Drives sample data download. */
1272 tv.tv_sec = tv.tv_usec = 0;
1273 libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1275 /* Postprocess completion of sample data download. */
1276 if (devc->download_finished) {
1277 sr_dbg("Download finished, post processing.");
1279 la2016_stop_acquisition(sdi);
1280 usb_source_remove(sdi->session, drvc->sr_ctx);
1281 devc->transfer = NULL;
1283 feed_queue_logic_flush(devc->feed_queue);
1284 feed_queue_logic_free(devc->feed_queue);
1285 devc->feed_queue = NULL;
1286 if (devc->frame_begin_sent) {
1287 std_session_send_df_frame_end(sdi);
1288 devc->frame_begin_sent = FALSE;
1290 std_session_send_df_end(sdi);
1292 sr_dbg("Download finished, done post processing.");
1298 SR_PRIV int la2016_identify_device(const struct sr_dev_inst *sdi,
1299 gboolean show_message)
1301 struct dev_context *devc;
1302 uint8_t buf[8]; /* Larger size of manuf date and device type magic. */
1303 size_t rdoff, rdlen;
1304 const uint8_t *rdptr;
1305 uint8_t date_yy, date_mm;
1306 uint8_t dinv_yy, dinv_mm;
1309 const struct kingst_model *model;
1315 * Four EEPROM bytes at offset 0x20 are the manufacturing date,
1316 * year and month in BCD format, followed by inverted values for
1317 * consistency checks. For example bytes 20 04 df fb translate
1318 * to 2020-04. This information can help identify the vintage of
1319 * devices when unknown magic numbers are seen.
1322 rdlen = 4 * sizeof(uint8_t);
1323 ret = ctrl_in(sdi, CMD_EEPROM, rdoff, 0, buf, rdlen);
1324 if (ret != SR_OK && !show_message) {
1325 /* Non-fatal weak attempt during probe. Not worth logging. */
1326 sr_dbg("Cannot access EEPROM.");
1328 } else if (ret != SR_OK) {
1329 /* Failed attempt in regular use. Non-fatal. Worth logging. */
1330 sr_err("Cannot read manufacture date in EEPROM.");
1332 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
1334 txt = sr_hexdump_new(buf, rdlen);
1335 sr_spew("Manufacture date bytes %s.", txt->str);
1336 sr_hexdump_free(txt);
1339 date_yy = read_u8_inc(&rdptr);
1340 date_mm = read_u8_inc(&rdptr);
1341 dinv_yy = read_u8_inc(&rdptr);
1342 dinv_mm = read_u8_inc(&rdptr);
1343 sr_info("Manufacture date: 20%02hx-%02hx.", date_yy, date_mm);
1344 if ((date_mm ^ dinv_mm) != 0xff || (date_yy ^ dinv_yy) != 0xff)
1345 sr_warn("Manufacture date fails checksum test.");
1349 * Several Kingst logic analyzer devices share the same USB VID
1350 * and PID. The product ID determines which MCU firmware to load.
1351 * The MCU firmware provides access to EEPROM content which then
1352 * allows to identify the device model. Which in turn determines
1353 * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1356 * EEPROM content for model identification is kept redundantly
1357 * in memory. The values are stored in verbatim and in inverted
1358 * form, multiple copies are kept at different offsets. Example
1369 * Exclusively inspecting the magic byte appears to be sufficient,
1370 * other fields seem to be 'don't care'.
1372 * magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1373 * magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1374 * magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1375 * (latest v1.3.0 PCB, perhaps others)
1376 * magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1377 * (latest v1.3.0 PCB, perhaps others)
1379 * When EEPROM content does not match the hardware configuration
1380 * (the board layout), the software may load but yield incorrect
1381 * results (like swapped channels). The FPGA bitstream itself
1382 * will authenticate with IC U10 and fail when its capabilities
1383 * do not match the hardware model. An LA1016 won't become a
1384 * LA2016 by faking its EEPROM content.
1386 devc->identify_magic = 0;
1388 rdlen = 8 * sizeof(uint8_t);
1389 ret = ctrl_in(sdi, CMD_EEPROM, rdoff, 0, &buf, rdlen);
1391 sr_err("Cannot read EEPROM device identifier bytes.");
1394 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
1396 txt = sr_hexdump_new(buf, rdlen);
1397 sr_spew("EEPROM magic bytes %s.", txt->str);
1398 sr_hexdump_free(txt);
1400 if ((buf[0] ^ buf[1]) == 0xff) {
1401 /* Primary copy of magic passes complement check. */
1403 sr_dbg("Using primary magic, value %d.", (int)magic);
1404 } else if ((buf[4] ^ buf[5]) == 0xff) {
1405 /* Backup copy of magic passes complement check. */
1407 sr_dbg("Using backup magic, value %d.", (int)magic);
1409 sr_err("Cannot find consistent device type identification.");
1412 devc->identify_magic = magic;
1415 for (model_idx = 0; model_idx < ARRAY_SIZE(models); model_idx++) {
1416 model = &models[model_idx];
1417 if (model->magic != magic)
1419 devc->model = model;
1420 sr_info("Model '%s', %zu channels, max %" PRIu64 "MHz.",
1421 model->name, model->channel_count,
1422 model->samplerate / SR_MHZ(1));
1423 devc->fpga_bitstream = g_strdup_printf(FPGA_FWFILE_FMT,
1425 sr_info("FPGA bitstream file '%s'.", devc->fpga_bitstream);
1429 sr_err("Cannot identify as one of the supported models.");
1436 SR_PRIV int la2016_init_hardware(const struct sr_dev_inst *sdi)
1438 struct dev_context *devc;
1439 const char *bitstream_fn;
1444 bitstream_fn = devc ? devc->fpga_bitstream : "";
1446 ret = check_fpga_bitstream(sdi);
1448 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1450 sr_err("Cannot upload FPGA bitstream.");
1454 ret = enable_fpga_bitstream(sdi);
1456 sr_err("Cannot enable FPGA bitstream after upload.");
1460 state = run_state(sdi);
1461 if ((state & 0xfff0) != 0x85e0) {
1462 sr_warn("Unexpected run state, want 0x85eX, got 0x%04x.", state);
1465 ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
1467 sr_err("Cannot reset USB bulk transfer.");
1471 sr_dbg("Device should be initialized.");
1476 SR_PRIV int la2016_deinit_hardware(const struct sr_dev_inst *sdi)
1480 ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0);
1482 sr_err("Cannot deinitialize device's FPGA.");
1489 SR_PRIV int la2016_write_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
1491 return set_pwm_config(sdi, idx);