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