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