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