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