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"
38 * Default device configuration. Must be applicable to any of the
39 * supported devices (no model specific default values yet). Specific
40 * firmware implementation details unfortunately won't let us detect
41 * and keep using previously configured values.
43 #define LA2016_DFLT_SAMPLERATE SR_MHZ(100)
44 #define LA2016_DFLT_SAMPLEDEPTH (5 * 1000 * 1000)
45 #define LA2016_DFLT_CAPT_RATIO 5 /* Capture ratio, in percent. */
47 /* USB vendor class control requests, executed by the Cypress FX2 MCU. */
48 #define CMD_FPGA_ENABLE 0x10
49 #define CMD_FPGA_SPI 0x20 /* R/W access to FPGA registers via SPI. */
50 #define CMD_BULK_START 0x30 /* Start sample data download via USB EP6 IN. */
51 #define CMD_BULK_RESET 0x38 /* Flush FIFO of FX2 USB EP6 IN. */
52 #define CMD_FPGA_INIT 0x50 /* Used before and after FPGA bitstream upload. */
53 #define CMD_KAUTH 0x60 /* Communicate to auth IC (U10). Not used. */
54 #define CMD_EEPROM 0xa2 /* R/W access to EEPROM content. */
57 * FPGA register addresses (base addresses when registers span multiple
58 * bytes, in that case data is kept in little endian format). Passed to
59 * CMD_FPGA_SPI requests. The FX2 MCU transparently handles the detail
60 * of SPI transfers encoding the read (1) or write (0) direction in the
61 * MSB of the address field. There are some 60 byte-wide FPGA registers.
63 * Unfortunately the FPGA registers change their meaning between the
64 * read and write directions of access, or exclusively provide one of
65 * these directions and not the other. This is an arbitrary vendor's
66 * choice, there is nothing which the sigrok driver could do about it.
67 * Values written to registers typically cannot get read back, neither
68 * verified after writing a configuration, nor queried upon startup for
69 * automatic detection of the current configuration. Neither appear to
70 * be there echo registers for presence and communication checks, nor
71 * version identifying registers, as far as we know.
73 #define REG_RUN 0x00 /* Read capture status, write start capture. */
74 #define REG_PWM_EN 0x02 /* User PWM channels on/off. */
75 #define REG_CAPT_MODE 0x03 /* Write 0x00 capture to SDRAM, 0x01 streaming. */
76 #define REG_BULK 0x08 /* Write start addr, byte count to download samples. */
77 #define REG_SAMPLING 0x10 /* Write capture config, read capture SDRAM location. */
78 #define REG_TRIGGER 0x20 /* write level and edge trigger config. */
79 #define REG_THRESHOLD 0x68 /* Write PWM config to setup input threshold DAC. */
80 #define REG_PWM1 0x70 /* Write config for user PWM1. */
81 #define REG_PWM2 0x78 /* Write config for user PWM2. */
83 /* Bit patterns to write to REG_RUN, setup run mode. */
84 #define RUNMODE_HALT 0x00
85 #define RUNMODE_RUN 0x03
87 /* Bit patterns when reading from REG_RUN, get run state. */
88 #define RUNSTATE_IDLE_BIT (1UL << 0)
89 #define RUNSTATE_DRAM_BIT (1UL << 1)
90 #define RUNSTATE_TRGD_BIT (1UL << 2)
91 #define RUNSTATE_POST_BIT (1UL << 3)
93 static int ctrl_in(const struct sr_dev_inst *sdi,
94 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
95 void *data, uint16_t wLength)
97 struct sr_usb_dev_inst *usb;
102 ret = libusb_control_transfer(usb->devhdl,
103 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
104 bRequest, wValue, wIndex, data, wLength,
106 if (ret != wLength) {
107 sr_dbg("USB ctrl in: %d bytes, req %d val %#x idx %d: %s.",
108 wLength, bRequest, wValue, wIndex,
109 libusb_error_name(ret));
110 sr_err("Cannot read %d bytes from USB: %s.",
111 wLength, libusb_error_name(ret));
118 static int ctrl_out(const struct sr_dev_inst *sdi,
119 uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
120 void *data, uint16_t wLength)
122 struct sr_usb_dev_inst *usb;
127 ret = libusb_control_transfer(usb->devhdl,
128 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
129 bRequest, wValue, wIndex, data, wLength,
131 if (ret != wLength) {
132 sr_dbg("USB ctrl out: %d bytes, req %d val %#x idx %d: %s.",
133 wLength, bRequest, wValue, wIndex,
134 libusb_error_name(ret));
135 sr_err("Cannot write %d bytes to USB: %s.",
136 wLength, libusb_error_name(ret));
144 * Check the necessity for FPGA bitstream upload, because another upload
145 * would take some 600ms which is undesirable after program startup. Try
146 * to access some FPGA registers and check the values' plausibility. The
147 * check should fail on the safe side, request another upload when in
148 * doubt. A positive response (the request to continue operation with the
149 * currently active bitstream) should be conservative. Accessing multiple
150 * registers is considered cheap compared to the cost of bitstream upload.
152 * It helps though that both the vendor software and the sigrok driver
153 * use the same bundle of MCU firmware and FPGA bitstream for any of the
154 * supported models. We don't expect to successfully communicate to the
155 * device yet disagree on its protocol. Ideally we would access version
156 * identifying registers for improved robustness, but are not aware of
157 * any. A bitstream reload can always be forced by a power cycle.
159 static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
166 uint8_t buff[sizeof(run_state)];
167 const uint8_t *rdptr;
169 sr_dbg("Checking operation of the FPGA bitstream.");
172 ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
173 if (ret != SR_OK || init_rsp != 0) {
174 sr_dbg("FPGA init query failed, or unexpected response.");
178 read_len = sizeof(run_state);
179 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, read_len);
181 sr_dbg("FPGA register access failed (run state).");
185 run_state = read_u16le_inc(&rdptr);
186 sr_spew("FPGA register: run state 0x%04x.", run_state);
187 if (run_state && (run_state & 0x3) != 0x1) {
188 sr_dbg("Unexpected FPGA register content (run state).");
191 if (run_state && (run_state & ~0xf) != 0x85e0) {
192 sr_dbg("Unexpected FPGA register content (run state).");
196 read_len = sizeof(pwm_en);
197 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, buff, read_len);
199 sr_dbg("FPGA register access failed (PWM enable).");
203 pwm_en = read_u8_inc(&rdptr);
204 sr_spew("FPGA register: PWM enable 0x%02x.", pwm_en);
205 if ((pwm_en & 0x3) != 0x0) {
206 sr_dbg("Unexpected FPGA register content (PWM enable).");
210 sr_info("Could re-use current FPGA bitstream. No upload required.");
214 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
215 const char *bitstream_fname)
217 struct drv_context *drvc;
218 struct sr_usb_dev_inst *usb;
219 struct sr_resource bitstream;
220 uint32_t bitstream_size;
221 uint8_t buffer[sizeof(uint32_t)];
227 unsigned int zero_pad_to;
229 drvc = sdi->driver->context;
232 sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
234 ret = sr_resource_open(drvc->sr_ctx, &bitstream,
235 SR_RESOURCE_FIRMWARE, bitstream_fname);
237 sr_err("Cannot find FPGA bitstream %s.", bitstream_fname);
241 bitstream_size = (uint32_t)bitstream.size;
243 write_u32le_inc(&wrptr, bitstream_size);
244 ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer);
246 sr_err("Cannot initiate FPGA bitstream upload.");
247 sr_resource_close(drvc->sr_ctx, &bitstream);
250 zero_pad_to = bitstream_size;
251 zero_pad_to += LA2016_EP2_PADDING - 1;
252 zero_pad_to /= LA2016_EP2_PADDING;
253 zero_pad_to *= LA2016_EP2_PADDING;
257 if (pos < bitstream.size) {
258 len = (int)sr_resource_read(drvc->sr_ctx, &bitstream,
259 block, sizeof(block));
261 sr_err("Cannot read FPGA bitstream.");
262 sr_resource_close(drvc->sr_ctx, &bitstream);
266 /* Zero-pad until 'zero_pad_to'. */
267 len = zero_pad_to - pos;
268 if ((unsigned)len > sizeof(block))
270 memset(&block, 0, len);
275 ret = libusb_bulk_transfer(usb->devhdl, USB_EP_FPGA_BITSTREAM,
276 &block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
278 sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
279 pos, (int)len, libusb_error_name(ret));
283 if (act_len != len) {
284 sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
285 pos, (int)len, act_len);
291 sr_resource_close(drvc->sr_ctx, &bitstream);
294 sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.",
300 static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
305 ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &resp, sizeof(resp));
307 sr_err("Cannot read response after FPGA bitstream upload.");
311 sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
317 ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0);
319 sr_err("Cannot enable FPGA after bitstream upload.");
327 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
329 struct dev_context *devc;
331 uint16_t duty_R79, duty_R56;
332 uint8_t buf[2 * sizeof(uint16_t)];
337 /* Clamp threshold setting to valid range for LA2016. */
340 } else if (voltage < -4.0) {
345 * Two PWM output channels feed one DAC which generates a bias
346 * voltage, which offsets the input probe's voltage level, and
347 * in combination with the FPGA pins' fixed threshold result in
348 * a programmable input threshold from the user's perspective.
349 * The PWM outputs can be seen on R79 and R56 respectively, the
350 * frequency is 100kHz and the duty cycle varies. The R79 PWM
351 * uses three discrete settings. The R56 PWM varies with desired
352 * thresholds and depends on the R79 PWM configuration. See the
353 * schematics comments which discuss the formulae.
355 if (voltage >= 2.9) {
356 duty_R79 = 0; /* PWM off (0V). */
357 duty_R56 = (uint16_t)(302 * voltage - 363);
358 } else if (voltage > -0.4) {
359 duty_R79 = 0x00f2; /* 25% duty cycle. */
360 duty_R56 = (uint16_t)(302 * voltage + 121);
362 duty_R79 = 0x02d7; /* 72% duty cycle. */
363 duty_R56 = (uint16_t)(302 * voltage + 1090);
366 /* Clamp duty register values to sensible limits. */
369 } else if (duty_R56 > 1100) {
373 sr_dbg("Set threshold voltage %.2fV.", voltage);
374 sr_dbg("Duty cycle values: R56 0x%04x, R79 0x%04x.", duty_R56, duty_R79);
377 write_u16le_inc(&wrptr, duty_R56);
378 write_u16le_inc(&wrptr, duty_R79);
380 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_THRESHOLD, 0, buf, wrptr - buf);
382 sr_err("Cannot set threshold voltage %.2fV.", voltage);
385 devc->threshold_voltage = voltage;
390 static int enable_pwm(const struct sr_dev_inst *sdi, gboolean p1, gboolean p2)
392 struct dev_context *devc;
403 sr_dbg("Set PWM enable %d %d. Config 0x%02x.", p1, p2, cfg);
405 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, &cfg, sizeof(cfg));
407 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 configure_pwm(const struct sr_dev_inst *sdi, uint8_t which,
418 float freq, float duty)
420 static uint8_t ctrl_reg_tab[] = { REG_PWM1, REG_PWM2, };
422 struct dev_context *devc;
424 struct pwm_setting_dev cfg;
425 struct pwm_setting *setting;
427 uint8_t buf[2 * sizeof(uint32_t)];
432 if (which < 1 || which > ARRAY_SIZE(ctrl_reg_tab)) {
433 sr_err("Invalid PWM channel: %d.", which);
436 if (freq < 0 || freq > MAX_PWM_FREQ) {
437 sr_err("Too high a PWM frequency: %.1f.", freq);
440 if (duty < 0 || duty > 100) {
441 sr_err("Invalid PWM duty cycle: %f.", duty);
445 memset(&cfg, 0, sizeof(cfg));
446 cfg.period = (uint32_t)(PWM_CLOCK / freq);
447 cfg.duty = (uint32_t)(0.5f + (cfg.period * duty / 100.));
448 sr_dbg("Set PWM%d period %d, duty %d.", which, cfg.period, cfg.duty);
450 ctrl_reg = ctrl_reg_tab[which - 1];
452 write_u32le_inc(&wrptr, cfg.period);
453 write_u32le_inc(&wrptr, cfg.duty);
454 ret = ctrl_out(sdi, CMD_FPGA_SPI, ctrl_reg, 0, buf, wrptr - buf);
456 sr_err("Cannot setup PWM%d configuration %d %d.",
457 which, cfg.period, cfg.duty);
461 setting = &devc->pwm_setting[which - 1];
462 setting->freq = freq;
463 setting->duty = duty;
468 static int set_defaults(const struct sr_dev_inst *sdi)
470 struct dev_context *devc;
475 devc->capture_ratio = LA2016_DFLT_CAPT_RATIO;
476 devc->limit_samples = LA2016_DFLT_SAMPLEDEPTH;
477 devc->cur_samplerate = LA2016_DFLT_SAMPLERATE;
479 ret = set_threshold_voltage(sdi, devc->threshold_voltage);
483 ret = enable_pwm(sdi, FALSE, FALSE);
487 ret = configure_pwm(sdi, 1, SR_KHZ(1), 50);
491 ret = configure_pwm(sdi, 2, SR_KHZ(100), 50);
495 ret = enable_pwm(sdi, TRUE, TRUE);
502 static uint16_t get_channels_mask(const struct sr_dev_inst *sdi)
506 struct sr_channel *ch;
509 for (l = sdi->channels; l; l = l->next) {
511 if (ch->type != SR_CHANNEL_LOGIC)
515 channels |= 1UL << ch->index;
521 static int set_trigger_config(const struct sr_dev_inst *sdi)
523 struct dev_context *devc;
524 struct sr_trigger *trigger;
525 struct trigger_cfg cfg;
528 struct sr_trigger_stage *stage1;
529 struct sr_trigger_match *match;
532 uint8_t buf[4 * sizeof(uint32_t)];
536 trigger = sr_session_trigger_get(sdi->session);
538 memset(&cfg, 0, sizeof(cfg));
540 cfg.channels = get_channels_mask(sdi);
542 if (trigger && trigger->stages) {
543 stages = trigger->stages;
544 stage1 = stages->data;
546 sr_err("Only one trigger stage supported for now.");
549 channel = stage1->matches;
551 match = channel->data;
552 ch_mask = 1UL << match->channel->index;
554 switch (match->match) {
555 case SR_TRIGGER_ZERO:
556 cfg.level |= ch_mask;
557 cfg.high_or_falling &= ~ch_mask;
560 cfg.level |= ch_mask;
561 cfg.high_or_falling |= ch_mask;
563 case SR_TRIGGER_RISING:
564 if ((cfg.enabled & ~cfg.level)) {
565 sr_err("Device only supports one edge trigger.");
568 cfg.level &= ~ch_mask;
569 cfg.high_or_falling &= ~ch_mask;
571 case SR_TRIGGER_FALLING:
572 if ((cfg.enabled & ~cfg.level)) {
573 sr_err("Device only supports one edge trigger.");
576 cfg.level &= ~ch_mask;
577 cfg.high_or_falling |= ch_mask;
580 sr_err("Unknown trigger condition.");
583 cfg.enabled |= ch_mask;
584 channel = channel->next;
587 sr_dbg("Set trigger config: "
588 "channels 0x%04x, trigger-enabled 0x%04x, "
589 "level-triggered 0x%04x, high/falling 0x%04x.",
590 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
592 devc->trigger_involved = cfg.enabled != 0;
595 write_u32le_inc(&wrptr, cfg.channels);
596 write_u32le_inc(&wrptr, cfg.enabled);
597 write_u32le_inc(&wrptr, cfg.level);
598 write_u32le_inc(&wrptr, cfg.high_or_falling);
600 * Comment on this literal 16. Origin, meaning? Cannot be the
601 * register offset, nor the transfer length. Is it a channels
602 * count that is relevant for 16 and 32 channel models? Is it
603 * an obsolete experiment?
605 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
607 sr_err("Cannot setup trigger configuration.");
614 static int set_sample_config(const struct sr_dev_inst *sdi)
616 struct dev_context *devc;
617 double clock_divisor;
618 uint16_t divider_u16;
619 uint64_t pre_trigger_samples;
620 uint64_t pre_trigger_memory;
621 uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
627 if (devc->cur_samplerate > devc->max_samplerate) {
628 sr_err("Too high a sample rate: %" PRIu64 ".",
629 devc->cur_samplerate);
632 if (devc->cur_samplerate < MIN_SAMPLE_RATE_LA2016) {
633 sr_err("Too low a sample rate: %" PRIu64 ".",
634 devc->cur_samplerate);
638 clock_divisor = devc->max_samplerate / (double)devc->cur_samplerate;
639 if (clock_divisor > 65535)
641 divider_u16 = (uint16_t)(clock_divisor + 0.5);
642 devc->cur_samplerate = devc->max_samplerate / divider_u16;
644 if (devc->limit_samples > LA2016_NUM_SAMPLES_MAX) {
645 sr_err("Too high a sample depth: %" PRIu64 ".",
646 devc->limit_samples);
649 if (devc->limit_samples < LA2016_NUM_SAMPLES_MIN) {
650 sr_err("Too low a sample depth: %" PRIu64 ".",
651 devc->limit_samples);
656 * The acquisition configuration communicates "pre-trigger"
657 * specs in several formats. sigrok users provide a percentage
658 * (0-100%), which translates to a pre-trigger samples count
659 * (assuming that a total samples count limit was specified).
660 * The device supports hardware compression, which depends on
661 * slowly changing input data to be effective. Fast changing
662 * input data may occupy more space in sample memory than its
663 * uncompressed form would. This is why a third parameter can
664 * limit the amount of sample memory to use for pre-trigger
665 * data. Only the upper 24 bits of that memory size spec get
666 * communicated to the device (written to its FPGA register).
668 pre_trigger_samples = devc->limit_samples * devc->capture_ratio / 100;
669 pre_trigger_memory = LA2016_PRE_MEM_LIMIT_BASE;
670 pre_trigger_memory *= devc->capture_ratio;
671 pre_trigger_memory /= 100;
673 sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples.",
674 devc->cur_samplerate / 1000, devc->limit_samples);
675 sr_dbg("Capture ratio %" PRIu64 "%%, count %" PRIu64 ", mem %" PRIu64 ".",
676 devc->capture_ratio, pre_trigger_samples, pre_trigger_memory);
679 * The acquisition configuration occupies a total of 16 bytes:
680 * - A 34bit total samples count limit (up to 10 billions) that
681 * is kept in a 40bit register.
682 * - A 34bit pre-trigger samples count limit (up to 10 billions)
683 * in another 40bit register.
684 * - A 32bit pre-trigger memory space limit (in bytes) of which
685 * the upper 24bits are kept in an FPGA register.
686 * - A 16bit clock divider which gets applied to the maximum
687 * samplerate of the device.
688 * - An 8bit register of unknown meaning. Currently always 0.
691 write_u40le_inc(&wrptr, devc->limit_samples);
692 write_u40le_inc(&wrptr, pre_trigger_samples);
693 write_u24le_inc(&wrptr, pre_trigger_memory >> 8);
694 write_u16le_inc(&wrptr, divider_u16);
695 write_u8_inc(&wrptr, 0);
696 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
698 sr_err("Cannot setup acquisition configuration.");
706 * FPGA register REG_RUN holds the run state (u16le format). Bit fields
708 * bit 0: value 1 = idle
709 * bit 1: value 1 = writing to SDRAM
710 * bit 2: value 0 = waiting for trigger, 1 = trigger seen
711 * bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
712 * The meaning of other bit fields is unknown.
714 * Typical values in order of appearance during execution:
715 * 0x85e1: idle, no acquisition pending
716 * IDLE set, TRGD don't care, POST don't care; DRAM don't care
717 * "In idle state." Takes precedence over all others.
718 * 0x85e2: pre-sampling, samples before the trigger position,
719 * when capture ratio > 0%
720 * IDLE clear, TRGD clear, POST clear; DRAM don't care
721 * "Not idle any more, no post yet, not triggered yet."
722 * 0x85ea: pre-sampling complete, now waiting for the trigger
723 * (whilst sampling continuously)
724 * IDLE clear, TRGD clear, POST set; DRAM don't care
725 * "Post set thus after pre, not triggered yet"
726 * 0x85ee: trigger seen, capturing post-trigger samples, running
727 * IDLE clear, TRGD set, POST set; DRAM don't care
728 * "Triggered and in post, not idle yet."
730 * IDLE set, TRGD don't care, POST don't care; DRAM don't care
731 * "In idle state." TRGD/POST don't care, same meaning as above.
733 static const uint16_t runstate_mask_idle = RUNSTATE_IDLE_BIT;
734 static const uint16_t runstate_patt_idle = RUNSTATE_IDLE_BIT;
735 static const uint16_t runstate_mask_step =
736 RUNSTATE_IDLE_BIT | RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
737 static const uint16_t runstate_patt_pre_trig = 0;
738 static const uint16_t runstate_patt_wait_trig = RUNSTATE_POST_BIT;
739 static const uint16_t runstate_patt_post_trig =
740 RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
742 static uint16_t run_state(const struct sr_dev_inst *sdi)
744 static uint16_t previous_state;
748 uint8_t buff[sizeof(state)];
749 const uint8_t *rdptr;
752 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, sizeof(state));
754 sr_err("Cannot read run state.");
758 state = read_u16le_inc(&rdptr);
761 * Avoid flooding the log, only dump values as they change.
762 * The routine is called about every 50ms.
764 if (state == previous_state)
767 previous_state = state;
769 if ((state & runstate_mask_idle) == runstate_patt_idle)
771 if ((state & runstate_mask_step) == runstate_patt_pre_trig)
772 label = "pre-trigger sampling";
773 if ((state & runstate_mask_step) == runstate_patt_wait_trig)
774 label = "sampling, waiting for trigger";
775 if ((state & runstate_mask_step) == runstate_patt_post_trig)
776 label = "post-trigger sampling";
778 sr_dbg("Run state: 0x%04x (%s).", state, label);
780 sr_dbg("Run state: 0x%04x.", state);
785 static int la2016_is_idle(const struct sr_dev_inst *sdi)
789 state = run_state(sdi);
790 if ((state & runstate_mask_idle) == runstate_patt_idle)
796 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
800 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode));
802 sr_err("Cannot configure run mode %d.", mode);
809 static int get_capture_info(const struct sr_dev_inst *sdi)
811 struct dev_context *devc;
813 uint8_t buf[3 * sizeof(uint32_t)];
814 const uint8_t *rdptr;
818 ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf));
820 sr_err("Cannot read capture info.");
825 devc->info.n_rep_packets = read_u32le_inc(&rdptr);
826 devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
827 devc->info.write_pos = read_u32le_inc(&rdptr);
829 sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x/%d.",
830 devc->info.n_rep_packets, devc->info.n_rep_packets,
831 devc->info.n_rep_packets_before_trigger,
832 devc->info.n_rep_packets_before_trigger,
833 devc->info.write_pos, devc->info.write_pos);
835 if (devc->info.n_rep_packets % NUM_PACKETS_IN_CHUNK) {
836 sr_warn("Unexpected packets count %lu, not a multiple of %d.",
837 (unsigned long)devc->info.n_rep_packets,
838 NUM_PACKETS_IN_CHUNK);
844 SR_PRIV int la2016_upload_firmware(struct sr_context *sr_ctx,
845 libusb_device *dev, uint16_t product_id)
848 snprintf(fw_file, sizeof(fw_file), UC_FIRMWARE, product_id);
849 return ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
852 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
854 struct dev_context *devc;
860 ret = set_threshold_voltage(sdi, devc->threshold_voltage);
865 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd));
867 sr_err("Cannot send command to stop sampling.");
871 ret = set_trigger_config(sdi);
875 ret = set_sample_config(sdi);
882 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
886 ret = set_run_mode(sdi, RUNMODE_RUN);
893 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
897 ret = set_run_mode(sdi, RUNMODE_HALT);
904 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
907 struct dev_context *devc;
909 ret = la2016_stop_acquisition(sdi);
913 devc = sdi ? sdi->priv : NULL;
914 if (devc && devc->transfer)
915 libusb_cancel_transfer(devc->transfer);
920 static int la2016_start_download(const struct sr_dev_inst *sdi,
921 libusb_transfer_cb_fn cb)
923 struct dev_context *devc;
924 struct sr_usb_dev_inst *usb;
926 uint8_t wrbuf[2 * sizeof(uint32_t)];
934 ret = get_capture_info(sdi);
938 devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
939 devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
940 devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
941 devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
943 sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
944 devc->n_transfer_packets_to_read, devc->read_pos);
946 ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
948 sr_err("Cannot reset USB bulk state.");
951 sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
952 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
954 write_u32le_inc(&wrptr, devc->read_pos);
955 write_u32le_inc(&wrptr, devc->n_bytes_to_read);
956 ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf);
958 sr_err("Cannot send USB bulk config.");
961 ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0);
963 sr_err("Cannot unblock USB bulk transfers.");
968 * Pick a buffer size for all USB transfers. The buffer size
969 * must be a multiple of the endpoint packet size. And cannot
970 * exceed a maximum value.
972 to_read = devc->n_bytes_to_read;
973 if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
974 to_read = LA2016_USB_BUFSZ;
975 else /* One transfer. */
976 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
977 buffer = g_try_malloc(to_read);
979 sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
980 sr_err("Cannot allocate buffer for USB bulk transfer.");
981 return SR_ERR_MALLOC;
984 devc->transfer = libusb_alloc_transfer(0);
985 libusb_fill_bulk_transfer(devc->transfer,
986 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
987 buffer, to_read, cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
989 ret = libusb_submit_transfer(devc->transfer);
991 sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
992 libusb_free_transfer(devc->transfer);
993 devc->transfer = NULL;
1002 * A chunk (received via USB) contains a number of transfers (USB length
1003 * divided by 16) which contain a number of packets (5 per transfer) which
1004 * contain a number of samples (8bit repeat count per 16bit sample data).
1006 static void send_chunk(struct sr_dev_inst *sdi,
1007 const uint8_t *packets, size_t num_xfers)
1009 struct dev_context *devc;
1010 struct sr_datafeed_logic logic;
1011 struct sr_datafeed_packet sr_packet;
1012 unsigned int max_samples, n_samples, total_samples, free_n_samples;
1014 gboolean do_signal_trigger;
1017 uint16_t sample_value;
1019 uint8_t sample_buff[sizeof(sample_value)];
1023 logic.unitsize = sizeof(sample_buff);
1024 logic.data = devc->convbuffer;
1026 sr_packet.type = SR_DF_LOGIC;
1027 sr_packet.payload = &logic;
1029 max_samples = devc->convbuffer_size / sizeof(sample_buff);
1031 wp = devc->convbuffer;
1033 do_signal_trigger = FALSE;
1035 if (devc->trigger_involved && !devc->trigger_marked && devc->info.n_rep_packets_before_trigger == 0) {
1036 std_session_send_df_trigger(sdi);
1037 devc->trigger_marked = TRUE;
1041 while (num_xfers--) {
1042 num_pkts = NUM_PACKETS_IN_CHUNK;
1043 while (num_pkts--) {
1045 * Flush the conversion buffer when a trigger
1046 * location needs to get communicated, or when
1047 * an to-get-expected sample repetition count
1048 * would no longer fit into the buffer.
1050 free_n_samples = max_samples - n_samples;
1051 if (free_n_samples < 256 || do_signal_trigger) {
1052 logic.length = n_samples * sizeof(sample_buff);;
1053 sr_session_send(sdi, &sr_packet);
1055 wp = devc->convbuffer;
1056 if (do_signal_trigger) {
1057 std_session_send_df_trigger(sdi);
1058 do_signal_trigger = FALSE;
1062 sample_value = read_u16le_inc(&rp);
1063 repetitions = read_u8_inc(&rp);
1065 n_samples += repetitions;
1066 total_samples += repetitions;
1067 devc->total_samples += repetitions;
1069 write_u16le(sample_buff, sample_value);
1070 while (repetitions--) {
1071 memcpy(wp, sample_buff, logic.unitsize);
1072 wp += logic.unitsize;
1075 if (devc->trigger_involved && !devc->trigger_marked) {
1076 if (!--devc->n_reps_until_trigger) {
1077 devc->trigger_marked = TRUE;
1078 do_signal_trigger = TRUE;
1079 sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
1080 devc->total_samples,
1081 (double)devc->total_samples / devc->cur_samplerate * 1e3);
1085 (void)read_u8_inc(&rp); /* Skip sequence number. */
1088 logic.length = n_samples * logic.unitsize;
1089 sr_session_send(sdi, &sr_packet);
1090 if (do_signal_trigger) {
1091 std_session_send_df_trigger(sdi);
1094 sr_dbg("Send_chunk done after %u samples.", total_samples);
1097 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
1099 struct sr_dev_inst *sdi;
1100 struct dev_context *devc;
1101 struct sr_usb_dev_inst *usb;
1104 sdi = transfer->user_data;
1108 sr_dbg("receive_transfer(): status %s received %d bytes.",
1109 libusb_error_name(transfer->status), transfer->actual_length);
1111 if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
1112 sr_err("USB bulk transfer timeout.");
1113 devc->download_finished = TRUE;
1115 send_chunk(sdi, transfer->buffer, transfer->actual_length / TRANSFER_PACKET_LENGTH);
1117 devc->n_bytes_to_read -= transfer->actual_length;
1118 if (devc->n_bytes_to_read) {
1119 uint32_t to_read = devc->n_bytes_to_read;
1121 * Determine read size for the next USB transfer. Make
1122 * the buffer size a multiple of the endpoint packet
1123 * size. Don't exceed a maximum value.
1125 if (to_read >= LA2016_USB_BUFSZ)
1126 to_read = LA2016_USB_BUFSZ;
1128 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
1129 libusb_fill_bulk_transfer(transfer,
1130 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1131 transfer->buffer, to_read,
1132 receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
1134 ret = libusb_submit_transfer(transfer);
1137 sr_err("Cannot submit another USB transfer: %s.",
1138 libusb_error_name(ret));
1141 g_free(transfer->buffer);
1142 libusb_free_transfer(transfer);
1143 devc->download_finished = TRUE;
1146 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1148 const struct sr_dev_inst *sdi;
1149 struct dev_context *devc;
1150 struct drv_context *drvc;
1158 drvc = sdi->driver->context;
1160 if (!devc->completion_seen) {
1161 if (!la2016_is_idle(sdi)) {
1162 /* Not yet ready for sample data download. */
1165 devc->completion_seen = TRUE;
1166 devc->download_finished = FALSE;
1167 devc->trigger_marked = FALSE;
1168 devc->total_samples = 0;
1169 /* We can start downloading sample data. */
1170 if (la2016_start_download(sdi, receive_transfer) != SR_OK) {
1171 sr_err("Cannot start acquisition data download.");
1174 sr_dbg("Acquisition data download started.");
1175 std_session_send_df_frame_begin(sdi);
1180 tv.tv_sec = tv.tv_usec = 0;
1181 libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1183 if (devc->download_finished) {
1184 sr_dbg("Download finished, post processing.");
1185 std_session_send_df_frame_end(sdi);
1187 usb_source_remove(sdi->session, drvc->sr_ctx);
1188 std_session_send_df_end(sdi);
1190 la2016_stop_acquisition(sdi);
1192 g_free(devc->convbuffer);
1193 devc->convbuffer = NULL;
1195 devc->transfer = NULL;
1197 sr_dbg("Download finished, done post processing.");
1203 SR_PRIV int la2016_init_device(const struct sr_dev_inst *sdi)
1205 struct dev_context *devc;
1208 const uint8_t *rdptr;
1209 uint8_t date_yy, date_mm;
1210 uint8_t dinv_yy, dinv_mm;
1212 const char *bitstream_fn;
1218 * Four EEPROM bytes at offset 0x20 are the manufacturing date,
1219 * year and month in BCD format, followed by inverted values for
1220 * consistency checks. For example bytes 20 04 df fb translate
1221 * to 2020-04. This information can help identify the vintage of
1222 * devices when unknown magic numbers are seen.
1224 ret = ctrl_in(sdi, CMD_EEPROM, 0x20, 0, buf, 4 * sizeof(uint8_t));
1226 sr_err("Cannot read manufacture date in EEPROM.");
1229 date_yy = read_u8_inc(&rdptr);
1230 date_mm = read_u8_inc(&rdptr);
1231 dinv_yy = read_u8_inc(&rdptr);
1232 dinv_mm = read_u8_inc(&rdptr);
1233 sr_info("Manufacture date: 20%02hx-%02hx.", date_yy, date_mm);
1234 if ((date_mm ^ dinv_mm) != 0xff || (date_yy ^ dinv_yy) != 0xff)
1235 sr_warn("Manufacture date fails checksum test.");
1239 * Several Kingst logic analyzer devices share the same USB VID
1240 * and PID. The product ID determines which MCU firmware to load.
1241 * The MCU firmware provides access to EEPROM content which then
1242 * allows to identify the device model. Which in turn determines
1243 * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1246 * EEPROM content for model identification is kept redundantly
1247 * in memory. The values are stored in verbatim and in inverted
1248 * form, multiple copies are kept at different offsets. Example
1259 * Exclusively inspecting the magic byte appears to be sufficient,
1260 * other fields seem to be 'don't care'.
1262 * magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1263 * magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1264 * magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1265 * (latest v1.3.0 PCB, perhaps others)
1266 * magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1267 * (latest v1.3.0 PCB, perhaps others)
1269 * When EEPROM content does not match the hardware configuration
1270 * (the board layout), the software may load but yield incorrect
1271 * results (like swapped channels). The FPGA bitstream itself
1272 * will authenticate with IC U10 and fail when its capabilities
1273 * do not match the hardware model. An LA1016 won't become a
1274 * LA2016 by faking its EEPROM content.
1276 if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x08, 0, &buf, sizeof(buf))) != SR_OK) {
1277 sr_err("Cannot read EEPROM device identifier bytes.");
1280 if ((buf[0] ^ buf[1]) == 0xff) {
1281 /* Primary copy of magic passes complement check. */
1282 sr_dbg("Using primary copy of device type magic number.");
1284 } else if ((buf[4] ^ buf[5]) == 0xff) {
1285 /* Backup copy of magic passes complement check. */
1286 sr_dbg("Using backup copy of device type magic number.");
1289 sr_err("Cannot find consistent device type identification.");
1292 sr_dbg("Device type: magic number is %hhu.", magic);
1294 /* Select the FPGA bitstream depending on the model. */
1297 bitstream_fn = FPGA_FW_LA2016;
1298 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1301 bitstream_fn = FPGA_FW_LA1016;
1302 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1305 bitstream_fn = FPGA_FW_LA2016A;
1306 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1309 bitstream_fn = FPGA_FW_LA1016A;
1310 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1313 bitstream_fn = NULL;
1316 if (!bitstream_fn || !*bitstream_fn) {
1317 sr_err("Cannot identify as one of the supported models.");
1321 if (check_fpga_bitstream(sdi) != SR_OK) {
1322 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1324 sr_err("Cannot upload FPGA bitstream.");
1328 ret = enable_fpga_bitstream(sdi);
1330 sr_err("Cannot enable FPGA bitstream after upload.");
1334 state = run_state(sdi);
1335 if (state != 0x85e9) {
1336 sr_warn("Unexpected run state, want 0x85e9, got 0x%04x.", state);
1339 if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
1340 sr_err("Cannot reset USB bulk transfer.");
1344 sr_dbg("Device should be initialized.");
1346 ret = set_defaults(sdi);
1353 SR_PRIV int la2016_deinit_device(const struct sr_dev_inst *sdi)
1357 if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0)) != SR_OK) {
1358 sr_err("Cannot deinitialize device's FPGA.");