]> sigrok.org Git - libsigrok.git/blob - src/hardware/kingst-la2016/protocol.c
kingst-la2016: sort include directives
[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 <errno.h>
26 #include <glib.h>
27 #include <glib/gstdio.h>
28 #include <inttypes.h>
29 #include <libsigrok/libsigrok.h>
30 #include <math.h>
31 #include <stdint.h>
32 #include <stdio.h>
33 #include <string.h>
34
35 #include "libsigrok-internal.h"
36 #include "protocol.h"
37
38 #define UC_FIRMWARE     "kingst-la-%04x.fw"
39 #define FPGA_FW_LA2016  "kingst-la2016-fpga.bitstream"
40 #define FPGA_FW_LA2016A "kingst-la2016a1-fpga.bitstream"
41 #define FPGA_FW_LA1016  "kingst-la1016-fpga.bitstream"
42 #define FPGA_FW_LA1016A "kingst-la1016a1-fpga.bitstream"
43
44 #define MAX_SAMPLE_RATE_LA2016  SR_MHZ(200)
45 #define MAX_SAMPLE_RATE_LA1016  SR_MHZ(100)
46 #define MAX_SAMPLE_DEPTH 10e9
47 #define MAX_PWM_FREQ     SR_MHZ(20)
48 #define PWM_CLOCK        SR_MHZ(200)    /* this is 200MHz for both the LA2016 and LA1016 */
49
50 /* usb vendor class control requests to the cypress FX2 microcontroller */
51 #define CMD_FPGA_ENABLE 0x10
52 #define CMD_FPGA_SPI    0x20    /* access registers in the FPGA over SPI bus, ctrl_in reads, ctrl_out writes */
53 #define CMD_BULK_START  0x30    /* begin transfer of capture data via usb endpoint 6 IN */
54 #define CMD_BULK_RESET  0x38    /* flush FX2 usb endpoint 6 IN fifos */
55 #define CMD_FPGA_INIT   0x50    /* used before and after FPGA bitstream loading */
56 #define CMD_KAUTH       0x60    /* communicate with authentication ic U10, not used */
57 #define CMD_EEPROM      0xa2    /* ctrl_in reads, ctrl_out writes */
58
59 /*
60  * fpga spi register addresses for control request CMD_FPGA_SPI:
61  * There are around 60 byte-wide registers within the fpga and
62  * these are the base addresses used for accessing them.
63  * On the spi bus, the msb of the address byte is set for read
64  * and cleared for write, but that is handled by the fx2 mcu
65  * as appropriate. In this driver code just use IN transactions
66  * to read, OUT to write.
67  */
68 #define REG_RUN         0x00    /* read capture status, write capture start */
69 #define REG_PWM_EN      0x02    /* user pwm channels on/off */
70 #define REG_CAPT_MODE   0x03    /* set to 0x00 for capture to sdram, 0x01 bypass sdram for streaming */
71 #define REG_BULK        0x08    /* write start address and number of bytes for capture data bulk upload */
72 #define REG_SAMPLING    0x10    /* write capture config, read capture data location in sdram */
73 #define REG_TRIGGER     0x20    /* write level and edge trigger config */
74 #define REG_THRESHOLD   0x68    /* write two pwm configs to control input threshold dac */
75 #define REG_PWM1        0x70    /* write config for user pwm1 */
76 #define REG_PWM2        0x78    /* write config for user pwm2 */
77
78 static int ctrl_in(const struct sr_dev_inst *sdi,
79                    uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
80                    void *data, uint16_t wLength)
81 {
82         struct sr_usb_dev_inst *usb;
83         int ret;
84
85         usb = sdi->conn;
86
87         if ((ret = libusb_control_transfer(
88                      usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
89                      bRequest, wValue, wIndex, (unsigned char *)data, wLength,
90                      DEFAULT_TIMEOUT_MS)) != wLength) {
91                 sr_err("failed to read %d bytes via ctrl-in %d %#x, %d: %s.",
92                        wLength, bRequest, wValue, wIndex,
93                        libusb_error_name(ret));
94                 return SR_ERR;
95         }
96
97         return SR_OK;
98 }
99
100 static int ctrl_out(const struct sr_dev_inst *sdi,
101                     uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
102                     void *data, uint16_t wLength)
103 {
104         struct sr_usb_dev_inst *usb;
105         int ret;
106
107         usb = sdi->conn;
108
109         if ((ret = libusb_control_transfer(
110                      usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
111                      bRequest, wValue, wIndex, (unsigned char*)data, wLength,
112                      DEFAULT_TIMEOUT_MS)) != wLength) {
113                 sr_err("failed to write %d bytes via ctrl-out %d %#x, %d: %s.",
114                        wLength, bRequest, wValue, wIndex,
115                        libusb_error_name(ret));
116                 return SR_ERR;
117         }
118
119         return SR_OK;
120 }
121
122 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi, const char *bitstream_fname)
123 {
124         struct dev_context *devc;
125         struct drv_context *drvc;
126         struct sr_usb_dev_inst *usb;
127         struct sr_resource bitstream;
128         uint8_t buffer[sizeof(uint32_t)];
129         uint8_t *wrptr;
130         uint8_t cmd_resp;
131         uint8_t block[4096];
132         int len, act_len;
133         unsigned int pos;
134         int ret;
135         unsigned int zero_pad_to = 0x2c000;
136
137         devc = sdi->priv;
138         drvc = sdi->driver->context;
139         usb = sdi->conn;
140
141         sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
142
143         ret = sr_resource_open(drvc->sr_ctx, &bitstream, SR_RESOURCE_FIRMWARE, bitstream_fname);
144         if (ret != SR_OK) {
145                 sr_err("could not find fpga firmware %s!", bitstream_fname);
146                 return ret;
147         }
148
149         devc->bitstream_size = (uint32_t)bitstream.size;
150         wrptr = buffer;
151         write_u32le_inc(&wrptr, devc->bitstream_size);
152         if ((ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer)) != SR_OK) {
153                 sr_err("failed to give upload init command");
154                 sr_resource_close(drvc->sr_ctx, &bitstream);
155                 return ret;
156         }
157
158         pos = 0;
159         while (1) {
160                 if (pos < bitstream.size) {
161                         len = (int)sr_resource_read(drvc->sr_ctx, &bitstream, &block, sizeof(block));
162                         if (len < 0) {
163                                 sr_err("failed to read from fpga bitstream!");
164                                 sr_resource_close(drvc->sr_ctx, &bitstream);
165                                 return SR_ERR;
166                         }
167                 } else {
168                         // fill with zero's until zero_pad_to
169                         len = zero_pad_to - pos;
170                         if ((unsigned)len > sizeof(block))
171                                 len = sizeof(block);
172                         memset(&block, 0, len);
173                 }
174                 if (len == 0)
175                         break;
176
177                 ret = libusb_bulk_transfer(usb->devhdl, 2, (unsigned char*)&block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
178                 if (ret != 0) {
179                         sr_dbg("failed to write fpga bitstream block at %#x len %d: %s.", pos, (int)len, libusb_error_name(ret));
180                         ret = SR_ERR;
181                         break;
182                 }
183                 if (act_len != len) {
184                         sr_dbg("failed to write fpga bitstream block at %#x len %d: act_len is %d.", pos, (int)len, act_len);
185                         ret = SR_ERR;
186                         break;
187                 }
188                 pos += len;
189         }
190         sr_resource_close(drvc->sr_ctx, &bitstream);
191         if (ret != 0)
192                 return ret;
193         sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.", bitstream.size);
194
195         if ((ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &cmd_resp, sizeof(cmd_resp))) != SR_OK) {
196                 sr_err("failed to read response after FPGA bitstream upload");
197                 return ret;
198         }
199         if (cmd_resp != 0) {
200                 sr_err("after fpga bitstream upload command response is 0x%02x, expect 0!", cmd_resp);
201                 return SR_ERR;
202         }
203
204         g_usleep(30000);
205
206         if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0)) != SR_OK) {
207                 sr_err("failed enable fpga");
208                 return ret;
209         }
210
211         g_usleep(40000);
212         return SR_OK;
213 }
214
215 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
216 {
217         struct dev_context *devc;
218         int ret;
219
220         devc = sdi->priv;
221
222         uint16_t duty_R79,duty_R56;
223         uint8_t buf[2 * sizeof(uint16_t)];
224         uint8_t *wrptr;
225
226         /* clamp threshold setting within valid range for LA2016 */
227         if (voltage > 4.0) {
228                 voltage = 4.0;
229         }
230         else if (voltage < -4.0) {
231                 voltage = -4.0;
232         }
233
234         /*
235          * The fpga has two programmable pwm outputs which feed a dac that
236          * is used to adjust input offset. The dac changes the input
237          * swing around the fixed fpga input threshold.
238          * The two pwm outputs can be seen on R79 and R56 respectvely.
239          * Frequency is fixed at 100kHz and duty is varied.
240          * The R79 pwm uses just three settings.
241          * The R56 pwm varies with required threshold and its behaviour
242          * also changes depending on the setting of R79 PWM.
243          */
244
245         /*
246          * calculate required pwm duty register values from requested threshold voltage
247          * see last page of schematic (on wiki) for an explanation of these numbers
248          */
249         if (voltage >= 2.9) {
250                 duty_R79 = 0;           /* this pwm is off (0V)*/
251                 duty_R56 = (uint16_t)(302 * voltage - 363);
252         }
253         else if (voltage <= -0.4) {
254                 duty_R79 = 0x02D7;      /* 72% duty */
255                 duty_R56 = (uint16_t)(302 * voltage + 1090);
256         }
257         else {
258                 duty_R79 = 0x00f2;      /* 25% duty */
259                 duty_R56 = (uint16_t)(302 * voltage + 121);
260         }
261
262         /* clamp duty register values at sensible limits */
263         if (duty_R56 < 10) {
264                 duty_R56 = 10;
265         }
266         else if (duty_R56 > 1100) {
267                 duty_R56 = 1100;
268         }
269
270         sr_dbg("set threshold voltage %.2fV", voltage);
271         sr_dbg("duty_R56=0x%04x, duty_R79=0x%04x", duty_R56, duty_R79);
272
273         wrptr = buf;
274         write_u16le_inc(&wrptr, duty_R56);
275         write_u16le_inc(&wrptr, duty_R79);
276
277         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_THRESHOLD, 0, buf, wrptr - buf);
278         if (ret != SR_OK) {
279                 sr_err("error setting new threshold voltage of %.2fV", voltage);
280                 return ret;
281         }
282         devc->threshold_voltage = voltage;
283
284         return SR_OK;
285 }
286
287 static int enable_pwm(const struct sr_dev_inst *sdi, uint8_t p1, uint8_t p2)
288 {
289         struct dev_context *devc;
290         uint8_t cfg;
291         int ret;
292
293         devc = sdi->priv;
294         cfg = 0;
295
296         if (p1) cfg |= 1 << 0;
297         if (p2) cfg |= 1 << 1;
298
299         sr_dbg("set pwm enable %d %d", p1, p2);
300         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, &cfg, sizeof(cfg));
301         if (ret != SR_OK) {
302                 sr_err("error setting new pwm enable 0x%02x", cfg);
303                 return ret;
304         }
305         devc->pwm_setting[0].enabled = (p1) ? 1 : 0;
306         devc->pwm_setting[1].enabled = (p2) ? 1 : 0;
307
308         return SR_OK;
309 }
310
311 static int set_pwm(const struct sr_dev_inst *sdi, uint8_t which, float freq, float duty)
312 {
313         int CTRL_PWM[] = { REG_PWM1, REG_PWM2 };
314         struct dev_context *devc;
315         pwm_setting_dev_t cfg;
316         pwm_setting_t *setting;
317         int ret;
318         uint8_t buf[2 * sizeof(uint32_t)];
319         uint8_t *wrptr;
320
321         devc = sdi->priv;
322
323         if (which < 1 || which > 2) {
324                 sr_err("invalid pwm channel: %d", which);
325                 return SR_ERR;
326         }
327         if (freq > MAX_PWM_FREQ) {
328                 sr_err("pwm frequency too high: %.1f", freq);
329                 return SR_ERR;
330         }
331         if (duty > 100 || duty < 0) {
332                 sr_err("invalid pwm percentage: %f", duty);
333                 return SR_ERR;
334         }
335
336         cfg.period = (uint32_t)(PWM_CLOCK / freq);
337         cfg.duty = (uint32_t)(0.5f + (cfg.period * duty / 100.));
338         sr_dbg("set pwm%d period %d, duty %d", which, cfg.period, cfg.duty);
339
340         wrptr = buf;
341         write_u32le_inc(&wrptr, cfg.period);
342         write_u32le_inc(&wrptr, cfg.duty);
343         ret = ctrl_out(sdi, CMD_FPGA_SPI, CTRL_PWM[which - 1], 0, buf, wrptr - buf);
344         if (ret != SR_OK) {
345                 sr_err("error setting new pwm%d config %d %d", which, cfg.period, cfg.duty);
346                 return ret;
347         }
348         setting = &devc->pwm_setting[which - 1];
349         setting->freq = freq;
350         setting->duty = duty;
351
352         return SR_OK;
353 }
354
355 static int set_defaults(const struct sr_dev_inst *sdi)
356 {
357         struct dev_context *devc;
358         int ret;
359
360         devc = sdi->priv;
361
362         devc->capture_ratio = 5; /* percent */
363         devc->cur_channels = 0xffff;
364         devc->limit_samples = 5000000;
365         devc->cur_samplerate = SR_MHZ(100);
366
367         ret = set_threshold_voltage(sdi, devc->threshold_voltage);
368         if (ret)
369                 return ret;
370
371         ret = enable_pwm(sdi, 0, 0);
372         if (ret)
373                 return ret;
374
375         ret = set_pwm(sdi, 1, 1e3, 50);
376         if (ret)
377                 return ret;
378
379         ret = set_pwm(sdi, 2, 100e3, 50);
380         if (ret)
381                 return ret;
382
383         ret = enable_pwm(sdi, 1, 1);
384         if (ret)
385                 return ret;
386
387         return SR_OK;
388 }
389
390 static int set_trigger_config(const struct sr_dev_inst *sdi)
391 {
392         struct dev_context *devc;
393         struct sr_trigger *trigger;
394         trigger_cfg_t cfg;
395         GSList *stages;
396         GSList *channel;
397         struct sr_trigger_stage *stage1;
398         struct sr_trigger_match *match;
399         uint16_t ch_mask;
400         int ret;
401         uint8_t buf[4 * sizeof(uint32_t)];
402         uint8_t *wrptr;
403
404         devc = sdi->priv;
405         trigger = sr_session_trigger_get(sdi->session);
406
407         memset(&cfg, 0, sizeof(cfg));
408
409         cfg.channels = devc->cur_channels;
410
411         if (trigger && trigger->stages) {
412                 stages = trigger->stages;
413                 stage1 = stages->data;
414                 if (stages->next) {
415                         sr_err("Only one trigger stage supported for now.");
416                         return SR_ERR;
417                 }
418                 channel = stage1->matches;
419                 while (channel) {
420                         match = channel->data;
421                         ch_mask = 1 << match->channel->index;
422
423                         switch (match->match) {
424                         case SR_TRIGGER_ZERO:
425                                 cfg.level |= ch_mask;
426                                 cfg.high_or_falling &= ~ch_mask;
427                                 break;
428                         case SR_TRIGGER_ONE:
429                                 cfg.level |= ch_mask;
430                                 cfg.high_or_falling |= ch_mask;
431                                 break;
432                         case SR_TRIGGER_RISING:
433                                 if ((cfg.enabled & ~cfg.level)) {
434                                         sr_err("Only one trigger signal with falling-/rising-edge allowed.");
435                                         return SR_ERR;
436                                 }
437                                 cfg.level &= ~ch_mask;
438                                 cfg.high_or_falling &= ~ch_mask;
439                                 break;
440                         case SR_TRIGGER_FALLING:
441                                 if ((cfg.enabled & ~cfg.level)) {
442                                         sr_err("Only one trigger signal with falling-/rising-edge allowed.");
443                                         return SR_ERR;
444                                 }
445                                 cfg.level &= ~ch_mask;
446                                 cfg.high_or_falling |= ch_mask;
447                                 break;
448                         default:
449                                 sr_err("Unknown trigger value.");
450                                 return SR_ERR;
451                         }
452                         cfg.enabled |= ch_mask;
453                         channel = channel->next;
454                 }
455         }
456         sr_dbg("set trigger configuration channels: 0x%04x, "
457                "trigger-enabled 0x%04x, level-triggered 0x%04x, "
458                "high/falling 0x%04x", cfg.channels, cfg.enabled, cfg.level,
459                cfg.high_or_falling);
460
461         devc->had_triggers_configured = cfg.enabled != 0;
462
463         wrptr = buf;
464         write_u32le_inc(&wrptr, cfg.channels);
465         write_u32le_inc(&wrptr, cfg.enabled);
466         write_u32le_inc(&wrptr, cfg.level);
467         write_u32le_inc(&wrptr, cfg.high_or_falling);
468         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
469         if (ret != SR_OK) {
470                 sr_err("error setting trigger config!");
471                 return ret;
472         }
473
474         return SR_OK;
475 }
476
477 static int set_sample_config(const struct sr_dev_inst *sdi)
478 {
479         struct dev_context *devc;
480         double clock_divisor;
481         uint64_t total;
482         int ret;
483         uint16_t divisor;
484         uint8_t buf[2 * sizeof(uint32_t) + 48 / 8 + sizeof(uint16_t)];
485         uint8_t *wrptr;
486
487         devc = sdi->priv;
488         total = 128 * 1024 * 1024;
489
490         if (devc->cur_samplerate > devc->max_samplerate) {
491                 sr_err("too high sample rate: %" PRIu64, devc->cur_samplerate);
492                 return SR_ERR;
493         }
494
495         clock_divisor = devc->max_samplerate / (double)devc->cur_samplerate;
496         if (clock_divisor > 0xffff)
497                 clock_divisor = 0xffff;
498         divisor = (uint16_t)(clock_divisor + 0.5);
499         devc->cur_samplerate = devc->max_samplerate / divisor;
500
501         if (devc->limit_samples > MAX_SAMPLE_DEPTH) {
502                 sr_err("too high sample depth: %" PRIu64, devc->limit_samples);
503                 return SR_ERR;
504         }
505
506         devc->pre_trigger_size = (devc->capture_ratio * devc->limit_samples) / 100;
507
508         sr_dbg("set sampling configuration %.0fkHz, %d samples, trigger-pos %d%%",
509                devc->cur_samplerate / 1e3, (unsigned int)devc->limit_samples, (unsigned int)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("error setting sample config!");
522                 return ret;
523         }
524
525         return SR_OK;
526 }
527
528 /* The run state is read from FPGA registers 1[hi-byte] and 0[lo-byte]
529  * and the bits are interpreted as follows:
530  *
531  * register 0:
532  *      bit0 1= idle
533  *      bit1 1= writing to sdram
534  *      bit2 0= waiting_for_trigger 1=been_triggered
535  *      bit3 0= pretrigger_sampling 1=posttrigger_sampling
536  *      ...unknown...
537  * register 1:
538  *      meaning of bits unknown (but vendor software reads this, so just do the same)
539  *
540  * The run state values occur in this order:
541  * 0x85E2: pre-sampling (for samples before trigger position, capture ratio > 0%)
542  * 0x85EA: pre-sampling complete, now waiting for trigger (whilst sampling continuously)
543  * 0x85EE: running
544  * 0x85ED: idle
545  */
546 static uint16_t run_state(const struct sr_dev_inst *sdi)
547 {
548         uint16_t state;
549         static uint16_t previous_state = 0;
550         int ret;
551
552         if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, &state, sizeof(state))) != SR_OK) {
553                 sr_err("failed to read run state!");
554                 return ret;
555         }
556
557         /* This function is called about every 50ms.
558          * To avoid filling the log file with redundant information during long captures,
559          * just print a log message if status has changed.
560          */
561
562         if (state != previous_state) {
563                 previous_state = state;
564                 if ((state & 0x0003) == 0x01) {
565                         sr_dbg("run_state: 0x%04x (%s)", state, "idle");
566                 }
567                 else if ((state & 0x000f) == 0x02) {
568                         sr_dbg("run_state: 0x%04x (%s)", state, "pre-trigger sampling");
569                 }
570                 else if ((state & 0x000f) == 0x0a) {
571                         sr_dbg("run_state: 0x%04x (%s)", state, "sampling, waiting for trigger");
572                 }
573                 else if ((state & 0x000f) == 0x0e) {
574                         sr_dbg("run_state: 0x%04x (%s)", state, "post-trigger sampling");
575                 }
576                 else {
577                         sr_dbg("run_state: 0x%04x", state);
578                 }
579         }
580
581         return state;
582 }
583
584 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t fast_blinking)
585 {
586         int ret;
587
588         if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &fast_blinking, sizeof(fast_blinking))) != SR_OK) {
589                 sr_err("failed to send set-run-mode command %d", fast_blinking);
590                 return ret;
591         }
592
593         return SR_OK;
594 }
595
596 static int get_capture_info(const struct sr_dev_inst *sdi)
597 {
598         struct dev_context *devc;
599         int ret;
600         uint8_t buf[3 * sizeof(uint32_t)];
601         const uint8_t *rdptr;
602
603         devc = sdi->priv;
604
605         if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf))) != SR_OK) {
606                 sr_err("failed to read capture info!");
607                 return ret;
608         }
609
610         rdptr = buf;
611         devc->info.n_rep_packets = read_u32le_inc(&rdptr);
612         devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
613         devc->info.write_pos = read_u32le_inc(&rdptr);
614
615         sr_dbg("capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x%d",
616                devc->info.n_rep_packets, devc->info.n_rep_packets,
617                devc->info.n_rep_packets_before_trigger, devc->info.n_rep_packets_before_trigger,
618                devc->info.write_pos, devc->info.write_pos);
619
620         if (devc->info.n_rep_packets % 5)
621                 sr_warn("number of packets is not as expected multiples of 5: %d", devc->info.n_rep_packets);
622
623         return SR_OK;
624 }
625
626 SR_PRIV int la2016_upload_firmware(struct sr_context *sr_ctx, libusb_device *dev, uint16_t product_id)
627 {
628         char fw_file[1024];
629         snprintf(fw_file, sizeof(fw_file) - 1, UC_FIRMWARE, product_id);
630         return ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
631 }
632
633 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
634 {
635         struct dev_context *devc;
636         int ret;
637         uint8_t cmd;
638
639         devc = sdi->priv;
640
641         ret = set_threshold_voltage(sdi, devc->threshold_voltage);
642         if (ret != SR_OK)
643                 return ret;
644
645         cmd = 0;
646         if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd))) != SR_OK) {
647                 sr_err("failed to send stop sampling command");
648                 return ret;
649         }
650
651         ret = set_trigger_config(sdi);
652         if (ret != SR_OK)
653                 return ret;
654
655         ret = set_sample_config(sdi);
656         if (ret != SR_OK)
657                 return ret;
658
659         return SR_OK;
660 }
661
662 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
663 {
664         int ret;
665
666         ret = set_run_mode(sdi, 3);
667         if (ret != SR_OK)
668                 return ret;
669
670         return SR_OK;
671 }
672
673 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
674 {
675         int ret;
676
677         ret = set_run_mode(sdi, 0);
678         if (ret != SR_OK)
679                 return ret;
680
681         return SR_OK;
682 }
683
684 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
685 {
686         int ret;
687         struct dev_context *devc;
688
689         ret = la2016_stop_acquisition(sdi);
690         if (ret != SR_OK)
691                 return ret;
692
693         devc = sdi ? sdi->priv : NULL;
694         if (devc && devc->transfer)
695                 libusb_cancel_transfer(devc->transfer);
696
697         return SR_OK;
698 }
699
700 static int la2016_has_triggered(const struct sr_dev_inst *sdi)
701 {
702         uint16_t state;
703
704         state = run_state(sdi);
705
706         return (state & 0x3) == 1;
707 }
708
709 static int la2016_start_retrieval(const struct sr_dev_inst *sdi, libusb_transfer_cb_fn cb)
710 {
711         struct dev_context *devc;
712         struct sr_usb_dev_inst *usb;
713         int ret;
714         uint8_t wrbuf[2 * sizeof(uint32_t)];
715         uint8_t *wrptr;
716         uint32_t to_read;
717         uint8_t *buffer;
718
719         devc = sdi->priv;
720         usb = sdi->conn;
721
722         if ((ret = get_capture_info(sdi)) != SR_OK)
723                 return ret;
724
725         devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
726         devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
727         devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
728         devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
729
730         sr_dbg("want to read %d tfer-packets starting from pos %d",
731                devc->n_transfer_packets_to_read, devc->read_pos);
732
733         if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
734                 sr_err("failed to reset bulk state");
735                 return ret;
736         }
737         sr_dbg("will read from 0x%08x, 0x%08x bytes", devc->read_pos, devc->n_bytes_to_read);
738         wrptr = wrbuf;
739         write_u32le_inc(&wrptr, devc->read_pos);
740         write_u32le_inc(&wrptr, devc->n_bytes_to_read);
741         if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf)) != SR_OK) {
742                 sr_err("failed to send bulk config");
743                 return ret;
744         }
745         if ((ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0)) != SR_OK) {
746                 sr_err("failed to unblock bulk transfers");
747                 return ret;
748         }
749
750         to_read = devc->n_bytes_to_read;
751         /* choose a buffer size for all of the usb transfers */
752         if (to_read >= LA2016_USB_BUFSZ)
753                 to_read = LA2016_USB_BUFSZ; /* multiple transfers */
754         else /* one transfer, make buffer size some multiple of LA2016_EP6_PKTSZ */
755                 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
756         buffer = g_try_malloc(to_read);
757         if (!buffer) {
758                 sr_err("Failed to allocate %d bytes for bulk transfer", to_read);
759                 return SR_ERR_MALLOC;
760         }
761
762         devc->transfer = libusb_alloc_transfer(0);
763         libusb_fill_bulk_transfer(
764                 devc->transfer, usb->devhdl,
765                 0x86, buffer, to_read,
766                 cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
767
768         if ((ret = libusb_submit_transfer(devc->transfer)) != 0) {
769                 sr_err("Failed to submit transfer: %s.", libusb_error_name(ret));
770                 libusb_free_transfer(devc->transfer);
771                 devc->transfer = NULL;
772                 g_free(buffer);
773                 return SR_ERR;
774         }
775
776         return SR_OK;
777 }
778
779 static void send_chunk(struct sr_dev_inst *sdi,
780         const uint8_t *packets, unsigned int num_tfers)
781 {
782         struct dev_context *devc;
783         struct sr_datafeed_logic logic;
784         struct sr_datafeed_packet sr_packet;
785         unsigned int max_samples, n_samples, total_samples, free_n_samples;
786         unsigned int i, j, k;
787         int do_signal_trigger;
788         uint16_t *wp;
789         const uint8_t *rp;
790         uint16_t state;
791         uint8_t repetitions;
792
793         devc = sdi->priv;
794
795         logic.unitsize = 2;
796         logic.data = devc->convbuffer;
797
798         sr_packet.type = SR_DF_LOGIC;
799         sr_packet.payload = &logic;
800
801         max_samples = devc->convbuffer_size / 2;
802         n_samples = 0;
803         wp = (uint16_t *)devc->convbuffer;
804         total_samples = 0;
805         do_signal_trigger = 0;
806
807         if (devc->had_triggers_configured && devc->reading_behind_trigger == 0 && devc->info.n_rep_packets_before_trigger == 0) {
808                 std_session_send_df_trigger(sdi);
809                 devc->reading_behind_trigger = 1;
810         }
811
812         rp = packets;
813         for (i = 0; i < num_tfers; i++) {
814                 for (k = 0; k < NUM_PACKETS_IN_CHUNK; k++) {
815                         free_n_samples = max_samples - n_samples;
816                         if (free_n_samples < 256 || do_signal_trigger) {
817                                 logic.length = n_samples * 2;
818                                 sr_session_send(sdi, &sr_packet);
819                                 n_samples = 0;
820                                 wp = (uint16_t *)devc->convbuffer;
821                                 if (do_signal_trigger) {
822                                         std_session_send_df_trigger(sdi);
823                                         do_signal_trigger = 0;
824                                 }
825                         }
826
827                         state = read_u16le_inc(&rp);
828                         repetitions = read_u8_inc(&rp);
829                         for (j = 0; j < repetitions; j++)
830                                 *wp++ = state;
831
832                         n_samples += repetitions;
833                         total_samples += repetitions;
834                         devc->total_samples += repetitions;
835                         if (!devc->reading_behind_trigger) {
836                                 devc->n_reps_until_trigger--;
837                                 if (devc->n_reps_until_trigger == 0) {
838                                         devc->reading_behind_trigger = 1;
839                                         do_signal_trigger = 1;
840                                         sr_dbg("  here is trigger position after %" PRIu64 " samples, %.6fms",
841                                                devc->total_samples,
842                                                (double)devc->total_samples / devc->cur_samplerate * 1e3);
843                                 }
844                         }
845                 }
846                 (void)read_u8_inc(&rp); /* Skip sequence number. */
847         }
848         if (n_samples) {
849                 logic.length = n_samples * 2;
850                 sr_session_send(sdi, &sr_packet);
851                 if (do_signal_trigger) {
852                         std_session_send_df_trigger(sdi);
853                 }
854         }
855         sr_dbg("send_chunk done after %d samples", total_samples);
856 }
857
858 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
859 {
860         struct sr_dev_inst *sdi;
861         struct dev_context *devc;
862         struct sr_usb_dev_inst *usb;
863         int ret;
864
865         sdi = transfer->user_data;
866         devc = sdi->priv;
867         usb = sdi->conn;
868
869         sr_dbg("receive_transfer(): status %s received %d bytes.",
870                libusb_error_name(transfer->status), transfer->actual_length);
871
872         if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
873                 sr_err("bulk transfer timeout!");
874                 devc->transfer_finished = 1;
875         }
876         send_chunk(sdi, transfer->buffer, transfer->actual_length / TRANSFER_PACKET_LENGTH);
877
878         devc->n_bytes_to_read -= transfer->actual_length;
879         if (devc->n_bytes_to_read) {
880                 uint32_t to_read = devc->n_bytes_to_read;
881                 /* determine read size for the next usb transfer */
882                 if (to_read >= LA2016_USB_BUFSZ)
883                         to_read = LA2016_USB_BUFSZ;
884                 else /* last transfer, make read size some multiple of LA2016_EP6_PKTSZ */
885                         to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
886                 libusb_fill_bulk_transfer(
887                         transfer, usb->devhdl,
888                         0x86, transfer->buffer, to_read,
889                         receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
890
891                 if ((ret = libusb_submit_transfer(transfer)) == 0)
892                         return;
893                 sr_err("Failed to submit further transfer: %s.", libusb_error_name(ret));
894         }
895
896         g_free(transfer->buffer);
897         libusb_free_transfer(transfer);
898         devc->transfer_finished = 1;
899 }
900
901 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
902 {
903         const struct sr_dev_inst *sdi;
904         struct dev_context *devc;
905         struct drv_context *drvc;
906         struct timeval tv;
907
908         (void)fd;
909         (void)revents;
910
911         sdi = cb_data;
912         devc = sdi->priv;
913         drvc = sdi->driver->context;
914
915         if (devc->have_trigger == 0) {
916                 if (la2016_has_triggered(sdi) == 0) {
917                         /* not yet ready for download */
918                         return TRUE;
919                 }
920                 devc->have_trigger = 1;
921                 devc->transfer_finished = 0;
922                 devc->reading_behind_trigger = 0;
923                 devc->total_samples = 0;
924                 /* we can start retrieving data! */
925                 if (la2016_start_retrieval(sdi, receive_transfer) != SR_OK) {
926                         sr_err("failed to start retrieval!");
927                         return FALSE;
928                 }
929                 sr_dbg("retrieval is started...");
930                 std_session_send_df_frame_begin(sdi);
931
932                 return TRUE;
933         }
934
935         tv.tv_sec = tv.tv_usec = 0;
936         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
937
938         if (devc->transfer_finished) {
939                 sr_dbg("transfer is finished!");
940                 std_session_send_df_frame_end(sdi);
941
942                 usb_source_remove(sdi->session, drvc->sr_ctx);
943                 std_session_send_df_end(sdi);
944
945                 la2016_stop_acquisition(sdi);
946
947                 g_free(devc->convbuffer);
948                 devc->convbuffer = NULL;
949
950                 devc->transfer = NULL;
951
952                 sr_dbg("transfer is now finished");
953         }
954
955         return TRUE;
956 }
957
958 SR_PRIV int la2016_init_device(const struct sr_dev_inst *sdi)
959 {
960         struct dev_context *devc;
961         uint16_t state;
962         uint8_t buf[8];
963         int16_t purchase_date_bcd[2];
964         uint8_t magic;
965         int ret;
966
967         devc = sdi->priv;
968
969         /* Four bytes of eeprom at 0x20 are purchase year & month in BCD format, with 16bit
970          * complemented checksum; e.g. 2004DFFB = 2020-April.
971          * This helps to identify the age of devices if unknown magic numbers occur.
972          */
973         if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x20, 0, purchase_date_bcd, sizeof(purchase_date_bcd))) != SR_OK) {
974                 sr_err("failed to read eeprom purchase_date_bcd");
975         }
976         else {
977                 sr_dbg("purchase date: 20%02hx-%02hx", (purchase_date_bcd[0]) & 0x00ff, (purchase_date_bcd[0] >> 8) & 0x00ff);
978                 if (purchase_date_bcd[0] != (0x0ffff & ~purchase_date_bcd[1])) {
979                         sr_err("purchase date: checksum failure");
980                 }
981         }
982
983         /*
984          * There are four known kingst logic analyser devices which use this same usb vid and pid:
985          * LA2016, LA1016 and the older revision of each of these. They all use the same hardware
986          * and the same FX2 mcu firmware but each requires a different fpga bitstream. They are
987          * differentiated by a 'magic' byte within the 8 bytes of EEPROM from address 0x08.
988          * For example;
989          *
990          * magic=0x08
991          *  | ~magic=0xf7
992          *  | |
993          * 08F7000008F710EF
994          *          | |
995          *          | ~magic-backup
996          *          magic-backup
997          *
998          * It seems that only these magic bytes are used, other bytes shown above are 'don't care'.
999          * Changing the magic byte on newer device to older magic causes OEM software to load
1000          * the older fpga bitstream. The device then functions but has channels out of order.
1001          * It's likely the bitstreams were changed to move input channel pins due to PCB changes.
1002          *
1003          * magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream" (latest v1.3.0 PCB, perhaps others)
1004          * magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream" (latest v1.3.0 PCB, perhaps others)
1005          * magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1006          * magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1007          *
1008          * This was all determined by altering the eeprom contents of an LA2016 and LA1016 and observing
1009          * the vendor software actions, either raising errors or loading specific bitstreams.
1010          *
1011          * Note:
1012          * An LA1016 cannot be converted to an LA2016 by changing the magic number - the bitstream
1013          * will not authenticate with ic U10, which has different security coding for each device type.
1014          */
1015
1016         if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x08, 0, &buf, sizeof(buf))) != SR_OK) {
1017                 sr_err("failed to read eeprom device identifier bytes");
1018                 return ret;
1019         }
1020
1021         magic = 0;
1022         if (buf[0] == (0x0ff & ~buf[1])) {
1023                 /* primary copy of magic passes complement check */
1024                 magic = buf[0];
1025         }
1026         else if (buf[4] == (0x0ff & ~buf[5])) {
1027                 /* backup copy of magic passes complement check */
1028                 sr_dbg("device_type: using backup copy of magic number");
1029                 magic = buf[4];
1030         }
1031
1032         sr_dbg("device_type: magic number is %hhu", magic);
1033
1034         /* select the correct fpga bitstream for this device */
1035         switch (magic) {
1036         case 2:
1037                 ret = upload_fpga_bitstream(sdi, FPGA_FW_LA2016);
1038                 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1039                 break;
1040         case 3:
1041                 ret = upload_fpga_bitstream(sdi, FPGA_FW_LA1016);
1042                 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1043                 break;
1044         case 8:
1045                 ret = upload_fpga_bitstream(sdi, FPGA_FW_LA2016A);
1046                 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1047                 break;
1048         case 9:
1049                 ret = upload_fpga_bitstream(sdi, FPGA_FW_LA1016A);
1050                 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1051                 break;
1052         default:
1053                 sr_err("device_type: device not supported; magic number indicates this is not a LA2016 or LA1016");
1054                 return SR_ERR;
1055         }
1056
1057         if (ret != SR_OK) {
1058                 sr_err("failed to upload fpga bitstream");
1059                 return ret;
1060         }
1061
1062         state = run_state(sdi);
1063         if (state != 0x85e9) {
1064                 sr_warn("expect run state to be 0x85e9, but it reads 0x%04x", state);
1065         }
1066
1067         if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
1068                 sr_err("failed to send CMD_BULK_RESET");
1069                 return ret;
1070         }
1071
1072         sr_dbg("device should be initialized");
1073
1074         return set_defaults(sdi);
1075 }
1076
1077 SR_PRIV int la2016_deinit_device(const struct sr_dev_inst *sdi)
1078 {
1079         int ret;
1080
1081         if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0)) != SR_OK) {
1082                 sr_err("failed to send deinit command");
1083                 return ret;
1084         }
1085
1086         return SR_OK;
1087 }