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