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