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