]> sigrok.org Git - libsigrok.git/blob - src/hardware/kingst-la2016/protocol.c
kingst-la2016: rework the device side of PWM configuration
[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 /*
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 cfg;
518         GSList *stages;
519         GSList *channel;
520         struct sr_trigger_stage *stage1;
521         struct sr_trigger_match *match;
522         uint16_t ch_mask;
523         int ret;
524         uint8_t buf[4 * sizeof(uint32_t)];
525         uint8_t *wrptr;
526
527         devc = sdi->priv;
528         trigger = sr_session_trigger_get(sdi->session);
529
530         memset(&cfg, 0, sizeof(cfg));
531
532         cfg.channels = get_channels_mask(sdi);
533
534         if (trigger && trigger->stages) {
535                 stages = trigger->stages;
536                 stage1 = stages->data;
537                 if (stages->next) {
538                         sr_err("Only one trigger stage supported for now.");
539                         return SR_ERR;
540                 }
541                 channel = stage1->matches;
542                 while (channel) {
543                         match = channel->data;
544                         ch_mask = 1UL << match->channel->index;
545
546                         switch (match->match) {
547                         case SR_TRIGGER_ZERO:
548                                 cfg.level |= ch_mask;
549                                 cfg.high_or_falling &= ~ch_mask;
550                                 break;
551                         case SR_TRIGGER_ONE:
552                                 cfg.level |= ch_mask;
553                                 cfg.high_or_falling |= ch_mask;
554                                 break;
555                         case SR_TRIGGER_RISING:
556                                 if ((cfg.enabled & ~cfg.level)) {
557                                         sr_err("Device only supports one edge trigger.");
558                                         return SR_ERR;
559                                 }
560                                 cfg.level &= ~ch_mask;
561                                 cfg.high_or_falling &= ~ch_mask;
562                                 break;
563                         case SR_TRIGGER_FALLING:
564                                 if ((cfg.enabled & ~cfg.level)) {
565                                         sr_err("Device only supports one edge trigger.");
566                                         return SR_ERR;
567                                 }
568                                 cfg.level &= ~ch_mask;
569                                 cfg.high_or_falling |= ch_mask;
570                                 break;
571                         default:
572                                 sr_err("Unknown trigger condition.");
573                                 return SR_ERR;
574                         }
575                         cfg.enabled |= ch_mask;
576                         channel = channel->next;
577                 }
578         }
579         sr_dbg("Set trigger config: "
580                 "channels 0x%04x, trigger-enabled 0x%04x, "
581                 "level-triggered 0x%04x, high/falling 0x%04x.",
582                 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
583
584         devc->trigger_involved = cfg.enabled != 0;
585
586         wrptr = buf;
587         write_u32le_inc(&wrptr, cfg.channels);
588         write_u32le_inc(&wrptr, cfg.enabled);
589         write_u32le_inc(&wrptr, cfg.level);
590         write_u32le_inc(&wrptr, cfg.high_or_falling);
591         /* TODO
592          * Comment on this literal 16. Origin, meaning? Cannot be the
593          * register offset, nor the transfer length. Is it a channels
594          * count that is relevant for 16 and 32 channel models? Is it
595          * an obsolete experiment?
596          */
597         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
598         if (ret != SR_OK) {
599                 sr_err("Cannot setup trigger configuration.");
600                 return ret;
601         }
602
603         return SR_OK;
604 }
605
606 static int set_sample_config(const struct sr_dev_inst *sdi)
607 {
608         struct dev_context *devc;
609         uint64_t min_samplerate, eff_samplerate;
610         uint16_t divider_u16;
611         uint64_t limit_samples;
612         uint64_t pre_trigger_samples;
613         uint64_t pre_trigger_memory;
614         uint8_t buf[REG_TRIGGER - REG_SAMPLING]; /* Width of REG_SAMPLING. */
615         uint8_t *wrptr;
616         int ret;
617
618         devc = sdi->priv;
619
620         if (devc->cur_samplerate > devc->model->samplerate) {
621                 sr_err("Too high a sample rate: %" PRIu64 ".",
622                         devc->cur_samplerate);
623                 return SR_ERR_ARG;
624         }
625         min_samplerate = devc->model->samplerate;
626         min_samplerate /= 65536;
627         if (devc->cur_samplerate < min_samplerate) {
628                 sr_err("Too low a sample rate: %" PRIu64 ".",
629                         devc->cur_samplerate);
630                 return SR_ERR_ARG;
631         }
632         divider_u16 = devc->model->samplerate / devc->cur_samplerate;
633         eff_samplerate = devc->model->samplerate / divider_u16;
634
635         ret = sr_sw_limits_get_remain(&devc->sw_limits,
636                 &limit_samples, NULL, NULL, NULL);
637         if (ret != SR_OK) {
638                 sr_err("Cannot get acquisition limits.");
639                 return ret;
640         }
641         if (limit_samples > LA2016_NUM_SAMPLES_MAX) {
642                 sr_warn("Too high a sample depth: %" PRIu64 ", capping.",
643                         limit_samples);
644                 limit_samples = LA2016_NUM_SAMPLES_MAX;
645         }
646         if (limit_samples == 0) {
647                 limit_samples = LA2016_NUM_SAMPLES_MAX;
648                 sr_dbg("Passing %" PRIu64 " to HW for unlimited samples.",
649                         limit_samples);
650         }
651
652         /*
653          * The acquisition configuration communicates "pre-trigger"
654          * specs in several formats. sigrok users provide a percentage
655          * (0-100%), which translates to a pre-trigger samples count
656          * (assuming that a total samples count limit was specified).
657          * The device supports hardware compression, which depends on
658          * slowly changing input data to be effective. Fast changing
659          * input data may occupy more space in sample memory than its
660          * uncompressed form would. This is why a third parameter can
661          * limit the amount of sample memory to use for pre-trigger
662          * data. Only the upper 24 bits of that memory size spec get
663          * communicated to the device (written to its FPGA register).
664          *
665          * TODO Determine whether the pre-trigger memory size gets
666          * specified in samples or in bytes. A previous implementation
667          * suggests bytes but this is suspicious when every other spec
668          * is in terms of samples.
669          */
670         if (devc->trigger_involved) {
671                 pre_trigger_samples = limit_samples;
672                 pre_trigger_samples *= devc->capture_ratio;
673                 pre_trigger_samples /= 100;
674                 pre_trigger_memory = devc->model->memory_bits;
675                 pre_trigger_memory *= UINT64_C(1024 * 1024 * 1024);
676                 pre_trigger_memory /= 8; /* devc->model->channel_count ? */
677                 pre_trigger_memory *= devc->capture_ratio;
678                 pre_trigger_memory /= 100;
679         } else {
680                 sr_dbg("No trigger setup, skipping pre-trigger config.");
681                 pre_trigger_samples = 1;
682                 pre_trigger_memory = 0;
683         }
684         /* Ensure non-zero value after LSB shift out in HW reg. */
685         if (pre_trigger_memory < 0x100) {
686                 pre_trigger_memory = 0x100;
687         }
688
689         sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples.",
690                 eff_samplerate / SR_KHZ(1), limit_samples);
691         sr_dbg("Capture ratio %" PRIu64 "%%, count %" PRIu64 ", mem %" PRIu64 ".",
692                 devc->capture_ratio, pre_trigger_samples, pre_trigger_memory);
693
694         /*
695          * The acquisition configuration occupies a total of 16 bytes:
696          * - A 34bit total samples count limit (up to 10 billions) that
697          *   is kept in a 40bit register.
698          * - A 34bit pre-trigger samples count limit (up to 10 billions)
699          *   in another 40bit register.
700          * - A 32bit pre-trigger memory space limit (in bytes) of which
701          *   the upper 24bits are kept in an FPGA register.
702          * - A 16bit clock divider which gets applied to the maximum
703          *   samplerate of the device.
704          * - An 8bit register of unknown meaning. Currently always 0.
705          */
706         wrptr = buf;
707         write_u40le_inc(&wrptr, limit_samples);
708         write_u40le_inc(&wrptr, pre_trigger_samples);
709         write_u24le_inc(&wrptr, pre_trigger_memory >> 8);
710         write_u16le_inc(&wrptr, divider_u16);
711         write_u8_inc(&wrptr, 0);
712         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
713         if (ret != SR_OK) {
714                 sr_err("Cannot setup acquisition configuration.");
715                 return ret;
716         }
717
718         return SR_OK;
719 }
720
721 /*
722  * FPGA register REG_RUN holds the run state (u16le format). Bit fields
723  * of interest:
724  *   bit 0: value 1 = idle
725  *   bit 1: value 1 = writing to SDRAM
726  *   bit 2: value 0 = waiting for trigger, 1 = trigger seen
727  *   bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
728  * The meaning of other bit fields is unknown.
729  *
730  * Typical values in order of appearance during execution:
731  *   0x85e1: idle, no acquisition pending
732  *     IDLE set, TRGD don't care, POST don't care; DRAM don't care
733  *     "In idle state." Takes precedence over all others.
734  *   0x85e2: pre-sampling, samples before the trigger position,
735  *     when capture ratio > 0%
736  *     IDLE clear, TRGD clear, POST clear; DRAM don't care
737  *     "Not idle any more, no post yet, not triggered yet."
738  *   0x85ea: pre-sampling complete, now waiting for the trigger
739  *     (whilst sampling continuously)
740  *     IDLE clear, TRGD clear, POST set; DRAM don't care
741  *     "Post set thus after pre, not triggered yet"
742  *   0x85ee: trigger seen, capturing post-trigger samples, running
743  *     IDLE clear, TRGD set, POST set; DRAM don't care
744  *     "Triggered and in post, not idle yet."
745  *   0x85ed: idle
746  *     IDLE set, TRGD don't care, POST don't care; DRAM don't care
747  *     "In idle state." TRGD/POST don't care, same meaning as above.
748  */
749 static const uint16_t runstate_mask_idle = RUNSTATE_IDLE_BIT;
750 static const uint16_t runstate_patt_idle = RUNSTATE_IDLE_BIT;
751 static const uint16_t runstate_mask_step =
752         RUNSTATE_IDLE_BIT | RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
753 static const uint16_t runstate_patt_pre_trig = 0;
754 static const uint16_t runstate_patt_wait_trig = RUNSTATE_POST_BIT;
755 static const uint16_t runstate_patt_post_trig =
756         RUNSTATE_TRGD_BIT | RUNSTATE_POST_BIT;
757
758 static uint16_t run_state(const struct sr_dev_inst *sdi)
759 {
760         static uint16_t previous_state;
761
762         int ret;
763         uint16_t state;
764         uint8_t buff[sizeof(state)];
765         const uint8_t *rdptr;
766         const char *label;
767
768         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, sizeof(state));
769         if (ret != SR_OK) {
770                 sr_err("Cannot read run state.");
771                 return ret;
772         }
773         rdptr = buff;
774         state = read_u16le_inc(&rdptr);
775
776         /*
777          * Avoid flooding the log, only dump values as they change.
778          * The routine is called about every 50ms.
779          */
780         if (state == previous_state)
781                 return state;
782
783         previous_state = state;
784         label = NULL;
785         if ((state & runstate_mask_idle) == runstate_patt_idle)
786                 label = "idle";
787         if ((state & runstate_mask_step) == runstate_patt_pre_trig)
788                 label = "pre-trigger sampling";
789         if ((state & runstate_mask_step) == runstate_patt_wait_trig)
790                 label = "sampling, waiting for trigger";
791         if ((state & runstate_mask_step) == runstate_patt_post_trig)
792                 label = "post-trigger sampling";
793         if (label && *label)
794                 sr_dbg("Run state: 0x%04x (%s).", state, label);
795         else
796                 sr_dbg("Run state: 0x%04x.", state);
797
798         return state;
799 }
800
801 static int la2016_is_idle(const struct sr_dev_inst *sdi)
802 {
803         uint16_t state;
804
805         state = run_state(sdi);
806         if ((state & runstate_mask_idle) == runstate_patt_idle)
807                 return 1;
808
809         return 0;
810 }
811
812 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
813 {
814         int ret;
815
816         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode));
817         if (ret != SR_OK) {
818                 sr_err("Cannot configure run mode %d.", mode);
819                 return ret;
820         }
821
822         return SR_OK;
823 }
824
825 static int get_capture_info(const struct sr_dev_inst *sdi)
826 {
827         struct dev_context *devc;
828         int ret;
829         uint8_t buf[3 * sizeof(uint32_t)];
830         const uint8_t *rdptr;
831
832         devc = sdi->priv;
833
834         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf));
835         if (ret != SR_OK) {
836                 sr_err("Cannot read capture info.");
837                 return ret;
838         }
839
840         rdptr = buf;
841         devc->info.n_rep_packets = read_u32le_inc(&rdptr);
842         devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
843         devc->info.write_pos = read_u32le_inc(&rdptr);
844
845         sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x/%d.",
846                 devc->info.n_rep_packets, devc->info.n_rep_packets,
847                 devc->info.n_rep_packets_before_trigger,
848                 devc->info.n_rep_packets_before_trigger,
849                 devc->info.write_pos, devc->info.write_pos);
850
851         if (devc->info.n_rep_packets % NUM_PACKETS_IN_CHUNK) {
852                 sr_warn("Unexpected packets count %lu, not a multiple of %d.",
853                         (unsigned long)devc->info.n_rep_packets,
854                         NUM_PACKETS_IN_CHUNK);
855         }
856
857         return SR_OK;
858 }
859
860 SR_PRIV int la2016_upload_firmware(const struct sr_dev_inst *sdi,
861         struct sr_context *sr_ctx, libusb_device *dev, uint16_t product_id)
862 {
863         struct dev_context *devc;
864         char *fw_file;
865         int ret;
866
867         devc = sdi ? sdi->priv : NULL;
868
869         fw_file = g_strdup_printf(MCU_FWFILE_FMT, product_id);
870         sr_info("USB PID %04hx, MCU firmware '%s'.", product_id, fw_file);
871
872         ret = ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
873         if (ret != SR_OK) {
874                 g_free(fw_file);
875                 return ret;
876         }
877
878         if (devc) {
879                 devc->mcu_firmware = fw_file;
880                 fw_file = NULL;
881         }
882         g_free(fw_file);
883
884         return SR_OK;
885 }
886
887 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
888 {
889         struct dev_context *devc;
890         int ret;
891         uint8_t cmd;
892
893         devc = sdi->priv;
894
895         ret = set_threshold_voltage(sdi, devc->threshold_voltage);
896         if (ret != SR_OK)
897                 return ret;
898
899         cmd = 0;
900         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd));
901         if (ret != SR_OK) {
902                 sr_err("Cannot send command to stop sampling.");
903                 return ret;
904         }
905
906         ret = set_trigger_config(sdi);
907         if (ret != SR_OK)
908                 return ret;
909
910         ret = set_sample_config(sdi);
911         if (ret != SR_OK)
912                 return ret;
913
914         return SR_OK;
915 }
916
917 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
918 {
919         int ret;
920
921         ret = set_run_mode(sdi, RUNMODE_RUN);
922         if (ret != SR_OK)
923                 return ret;
924
925         return SR_OK;
926 }
927
928 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
929 {
930         int ret;
931
932         ret = set_run_mode(sdi, RUNMODE_HALT);
933         if (ret != SR_OK)
934                 return ret;
935
936         return SR_OK;
937 }
938
939 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
940 {
941         int ret;
942         struct dev_context *devc;
943
944         ret = la2016_stop_acquisition(sdi);
945         if (ret != SR_OK)
946                 return ret;
947
948         devc = sdi ? sdi->priv : NULL;
949         if (devc && devc->transfer)
950                 libusb_cancel_transfer(devc->transfer);
951
952         return SR_OK;
953 }
954
955 static int la2016_start_download(const struct sr_dev_inst *sdi,
956         libusb_transfer_cb_fn cb)
957 {
958         struct dev_context *devc;
959         struct sr_usb_dev_inst *usb;
960         int ret;
961         uint8_t wrbuf[2 * sizeof(uint32_t)];
962         uint8_t *wrptr;
963         uint32_t to_read;
964         uint8_t *buffer;
965
966         devc = sdi->priv;
967         usb = sdi->conn;
968
969         ret = get_capture_info(sdi);
970         if (ret != SR_OK)
971                 return ret;
972
973         devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
974         devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
975         devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
976         devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
977
978         sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
979                 devc->n_transfer_packets_to_read, devc->read_pos);
980
981         ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
982         if (ret != SR_OK) {
983                 sr_err("Cannot reset USB bulk state.");
984                 return ret;
985         }
986         sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
987                 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
988         wrptr = wrbuf;
989         write_u32le_inc(&wrptr, devc->read_pos);
990         write_u32le_inc(&wrptr, devc->n_bytes_to_read);
991         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf);
992         if (ret != SR_OK) {
993                 sr_err("Cannot send USB bulk config.");
994                 return ret;
995         }
996         ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0);
997         if (ret != SR_OK) {
998                 sr_err("Cannot unblock USB bulk transfers.");
999                 return ret;
1000         }
1001
1002         /*
1003          * Pick a buffer size for all USB transfers. The buffer size
1004          * must be a multiple of the endpoint packet size. And cannot
1005          * exceed a maximum value.
1006          */
1007         to_read = devc->n_bytes_to_read;
1008         if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
1009                 to_read = LA2016_USB_BUFSZ;
1010         else /* One transfer. */
1011                 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
1012         buffer = g_try_malloc(to_read);
1013         if (!buffer) {
1014                 sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
1015                 sr_err("Cannot allocate buffer for USB bulk transfer.");
1016                 return SR_ERR_MALLOC;
1017         }
1018
1019         devc->transfer = libusb_alloc_transfer(0);
1020         libusb_fill_bulk_transfer(devc->transfer,
1021                 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1022                 buffer, to_read, cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
1023
1024         ret = libusb_submit_transfer(devc->transfer);
1025         if (ret != 0) {
1026                 sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
1027                 libusb_free_transfer(devc->transfer);
1028                 devc->transfer = NULL;
1029                 g_free(buffer);
1030                 return SR_ERR;
1031         }
1032
1033         return SR_OK;
1034 }
1035
1036 /*
1037  * A chunk (received via USB) contains a number of transfers (USB length
1038  * divided by 16) which contain a number of packets (5 per transfer) which
1039  * contain a number of samples (8bit repeat count per 16bit sample data).
1040  */
1041 static void send_chunk(struct sr_dev_inst *sdi,
1042         const uint8_t *packets, size_t num_xfers)
1043 {
1044         struct dev_context *devc;
1045         size_t num_pkts;
1046         const uint8_t *rp;
1047         uint16_t sample_value;
1048         size_t repetitions;
1049         uint8_t sample_buff[sizeof(sample_value)];
1050
1051         devc = sdi->priv;
1052
1053         /* Ignore incoming USB data after complete sample data download. */
1054         if (devc->download_finished)
1055                 return;
1056
1057         if (devc->trigger_involved && !devc->trigger_marked && devc->info.n_rep_packets_before_trigger == 0) {
1058                 feed_queue_logic_send_trigger(devc->feed_queue);
1059                 devc->trigger_marked = TRUE;
1060         }
1061
1062         rp = packets;
1063         while (num_xfers--) {
1064                 num_pkts = NUM_PACKETS_IN_CHUNK;
1065                 while (num_pkts--) {
1066
1067                         sample_value = read_u16le_inc(&rp);
1068                         repetitions = read_u8_inc(&rp);
1069
1070                         devc->total_samples += repetitions;
1071
1072                         write_u16le(sample_buff, sample_value);
1073                         feed_queue_logic_submit(devc->feed_queue,
1074                                 sample_buff, repetitions);
1075                         sr_sw_limits_update_samples_read(&devc->sw_limits,
1076                                 repetitions);
1077
1078                         if (devc->trigger_involved && !devc->trigger_marked) {
1079                                 if (!--devc->n_reps_until_trigger) {
1080                                         feed_queue_logic_send_trigger(devc->feed_queue);
1081                                         devc->trigger_marked = TRUE;
1082                                         sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
1083                                                 devc->total_samples,
1084                                                 (double)devc->total_samples / devc->cur_samplerate * 1e3);
1085                                 }
1086                         }
1087                 }
1088                 (void)read_u8_inc(&rp); /* Skip sequence number. */
1089         }
1090
1091         if (!devc->download_finished && sr_sw_limits_check(&devc->sw_limits)) {
1092                 sr_dbg("Acquisition limit reached.");
1093                 devc->download_finished = TRUE;
1094         }
1095         if (devc->download_finished) {
1096                 sr_dbg("Download finished, flushing session feed queue.");
1097                 feed_queue_logic_flush(devc->feed_queue);
1098         }
1099         sr_dbg("Total samples after chunk: %" PRIu64 ".", devc->total_samples);
1100 }
1101
1102 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
1103 {
1104         struct sr_dev_inst *sdi;
1105         struct dev_context *devc;
1106         struct sr_usb_dev_inst *usb;
1107         size_t num_xfers;
1108         int ret;
1109
1110         sdi = transfer->user_data;
1111         devc = sdi->priv;
1112         usb = sdi->conn;
1113
1114         sr_dbg("receive_transfer(): status %s received %d bytes.",
1115                 libusb_error_name(transfer->status), transfer->actual_length);
1116         /*
1117          * Implementation detail: A USB transfer timeout is not fatal
1118          * here. We just process whatever was received, empty input is
1119          * perfectly acceptable. Reaching (or exceeding) the sw limits
1120          * or exhausting the device's captured data will complete the
1121          * sample data download.
1122          */
1123         num_xfers = transfer->actual_length / TRANSFER_PACKET_LENGTH;
1124         send_chunk(sdi, transfer->buffer, num_xfers);
1125
1126         devc->n_bytes_to_read -= transfer->actual_length;
1127         if (devc->n_bytes_to_read) {
1128                 uint32_t to_read = devc->n_bytes_to_read;
1129                 /*
1130                  * Determine read size for the next USB transfer. Make
1131                  * the buffer size a multiple of the endpoint packet
1132                  * size. Don't exceed a maximum value.
1133                  */
1134                 if (to_read >= LA2016_USB_BUFSZ)
1135                         to_read = LA2016_USB_BUFSZ;
1136                 else
1137                         to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
1138                 libusb_fill_bulk_transfer(transfer,
1139                         usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1140                         transfer->buffer, to_read,
1141                         receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
1142
1143                 ret = libusb_submit_transfer(transfer);
1144                 if (ret == 0)
1145                         return;
1146                 sr_err("Cannot submit another USB transfer: %s.",
1147                         libusb_error_name(ret));
1148         }
1149
1150         g_free(transfer->buffer);
1151         libusb_free_transfer(transfer);
1152         devc->download_finished = TRUE;
1153 }
1154
1155 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1156 {
1157         const struct sr_dev_inst *sdi;
1158         struct dev_context *devc;
1159         struct drv_context *drvc;
1160         struct timeval tv;
1161         int ret;
1162
1163         (void)fd;
1164         (void)revents;
1165
1166         sdi = cb_data;
1167         devc = sdi->priv;
1168         drvc = sdi->driver->context;
1169
1170         /*
1171          * Wait for the acquisition to complete in hardware.
1172          * Periodically check a potentially configured msecs timeout.
1173          */
1174         if (!devc->completion_seen) {
1175                 if (!la2016_is_idle(sdi)) {
1176                         if (sr_sw_limits_check(&devc->sw_limits)) {
1177                                 devc->sw_limits.limit_msec = 0;
1178                                 sr_dbg("Limit reached. Stopping acquisition.");
1179                                 la2016_stop_acquisition(sdi);
1180                         }
1181                         /* Not yet ready for sample data download. */
1182                         return TRUE;
1183                 }
1184                 sr_dbg("Acquisition completion seen (hardware).");
1185                 devc->sw_limits.limit_msec = 0;
1186                 devc->completion_seen = TRUE;
1187                 devc->download_finished = FALSE;
1188                 devc->trigger_marked = FALSE;
1189                 devc->total_samples = 0;
1190
1191                 /* Initiate the download of acquired sample data. */
1192                 std_session_send_df_frame_begin(sdi);
1193                 ret = la2016_start_download(sdi, receive_transfer);
1194                 if (ret != SR_OK) {
1195                         sr_err("Cannot start acquisition data download.");
1196                         return FALSE;
1197                 }
1198                 sr_dbg("Acquisition data download started.");
1199
1200                 return TRUE;
1201         }
1202
1203         /* Handle USB reception. Drives sample data download. */
1204         tv.tv_sec = tv.tv_usec = 0;
1205         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1206
1207         /* Postprocess completion of sample data download. */
1208         if (devc->download_finished) {
1209                 sr_dbg("Download finished, post processing.");
1210
1211                 la2016_stop_acquisition(sdi);
1212                 usb_source_remove(sdi->session, drvc->sr_ctx);
1213                 devc->transfer = NULL;
1214
1215                 feed_queue_logic_flush(devc->feed_queue);
1216                 feed_queue_logic_free(devc->feed_queue);
1217                 devc->feed_queue = NULL;
1218                 std_session_send_df_frame_end(sdi);
1219                 std_session_send_df_end(sdi);
1220
1221                 sr_dbg("Download finished, done post processing.");
1222         }
1223
1224         return TRUE;
1225 }
1226
1227 SR_PRIV int la2016_identify_device(const struct sr_dev_inst *sdi,
1228         gboolean show_message)
1229 {
1230         struct dev_context *devc;
1231         uint8_t buf[8];
1232         size_t rdoff, rdlen;
1233         const uint8_t *rdptr;
1234         uint8_t date_yy, date_mm;
1235         uint8_t dinv_yy, dinv_mm;
1236         uint8_t magic;
1237         size_t model_idx;
1238         const struct kingst_model *model;
1239         int ret;
1240
1241         devc = sdi->priv;
1242
1243         /*
1244          * Four EEPROM bytes at offset 0x20 are the manufacturing date,
1245          * year and month in BCD format, followed by inverted values for
1246          * consistency checks. For example bytes 20 04 df fb translate
1247          * to 2020-04. This information can help identify the vintage of
1248          * devices when unknown magic numbers are seen.
1249          */
1250         rdoff = 0x20;
1251         rdlen = 4 * sizeof(uint8_t);
1252         ret = ctrl_in(sdi, CMD_EEPROM, rdoff, 0, buf, rdlen);
1253         if (ret != SR_OK && !show_message) {
1254                 /* Non-fatal weak attempt during probe. Not worth logging. */
1255                 sr_dbg("Cannot access EEPROM.");
1256                 return SR_ERR_IO;
1257         } else if (ret != SR_OK) {
1258                 /* Failed attempt in regular use. Non-fatal. Worth logging. */
1259                 sr_err("Cannot read manufacture date in EEPROM.");
1260         } else {
1261                 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
1262                         GString *txt;
1263                         txt = sr_hexdump_new(buf, rdlen);
1264                         sr_spew("Manufacture date bytes %s.", txt->str);
1265                         sr_hexdump_free(txt);
1266                 }
1267                 rdptr = &buf[0];
1268                 date_yy = read_u8_inc(&rdptr);
1269                 date_mm = read_u8_inc(&rdptr);
1270                 dinv_yy = read_u8_inc(&rdptr);
1271                 dinv_mm = read_u8_inc(&rdptr);
1272                 sr_info("Manufacture date: 20%02hx-%02hx.", date_yy, date_mm);
1273                 if ((date_mm ^ dinv_mm) != 0xff || (date_yy ^ dinv_yy) != 0xff)
1274                         sr_warn("Manufacture date fails checksum test.");
1275         }
1276
1277         /*
1278          * Several Kingst logic analyzer devices share the same USB VID
1279          * and PID. The product ID determines which MCU firmware to load.
1280          * The MCU firmware provides access to EEPROM content which then
1281          * allows to identify the device model. Which in turn determines
1282          * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1283          * to get inspected.
1284          *
1285          * EEPROM content for model identification is kept redundantly
1286          * in memory. The values are stored in verbatim and in inverted
1287          * form, multiple copies are kept at different offsets. Example
1288          * data:
1289          *
1290          *   magic 0x08
1291          *    | ~magic 0xf7
1292          *    | |
1293          *   08f7000008f710ef
1294          *            | |
1295          *            | ~magic backup
1296          *            magic backup
1297          *
1298          * Exclusively inspecting the magic byte appears to be sufficient,
1299          * other fields seem to be 'don't care'.
1300          *
1301          *   magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1302          *   magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1303          *   magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1304          *              (latest v1.3.0 PCB, perhaps others)
1305          *   magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1306          *              (latest v1.3.0 PCB, perhaps others)
1307          *
1308          * When EEPROM content does not match the hardware configuration
1309          * (the board layout), the software may load but yield incorrect
1310          * results (like swapped channels). The FPGA bitstream itself
1311          * will authenticate with IC U10 and fail when its capabilities
1312          * do not match the hardware model. An LA1016 won't become a
1313          * LA2016 by faking its EEPROM content.
1314          */
1315         devc->identify_magic = 0;
1316         rdoff = 0x08;
1317         rdlen = 8 * sizeof(uint8_t);
1318         ret = ctrl_in(sdi, CMD_EEPROM, rdoff, 0, &buf, rdlen);
1319         if (ret != SR_OK) {
1320                 sr_err("Cannot read EEPROM device identifier bytes.");
1321                 return ret;
1322         }
1323         if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
1324                 GString *txt;
1325                 txt = sr_hexdump_new(buf, rdlen);
1326                 sr_spew("EEPROM magic bytes %s.", txt->str);
1327                 sr_hexdump_free(txt);
1328         }
1329         if ((buf[0] ^ buf[1]) == 0xff) {
1330                 /* Primary copy of magic passes complement check. */
1331                 magic = buf[0];
1332                 sr_dbg("Using primary magic, value %d.", (int)magic);
1333         } else if ((buf[4] ^ buf[5]) == 0xff) {
1334                 /* Backup copy of magic passes complement check. */
1335                 magic = buf[4];
1336                 sr_dbg("Using backup magic, value %d.", (int)magic);
1337         } else {
1338                 sr_err("Cannot find consistent device type identification.");
1339                 magic = 0;
1340         }
1341         devc->identify_magic = magic;
1342
1343         devc->model = NULL;
1344         for (model_idx = 0; model_idx < ARRAY_SIZE(models); model_idx++) {
1345                 model = &models[model_idx];
1346                 if (model->magic != magic)
1347                         continue;
1348                 devc->model = model;
1349                 sr_info("Model '%s', %zu channels, max %" PRIu64 "MHz.",
1350                         model->name, model->channel_count,
1351                         model->samplerate / SR_MHZ(1));
1352                 devc->fpga_bitstream = g_strdup_printf(FPGA_FWFILE_FMT,
1353                         model->fpga_stem);
1354                 sr_info("FPGA bitstream file '%s'.", devc->fpga_bitstream);
1355                 break;
1356         }
1357         if (!devc->model) {
1358                 sr_err("Cannot identify as one of the supported models.");
1359                 return SR_ERR;
1360         }
1361
1362         return SR_OK;
1363 }
1364
1365 SR_PRIV int la2016_init_hardware(const struct sr_dev_inst *sdi)
1366 {
1367         struct dev_context *devc;
1368         const char *bitstream_fn;
1369         int ret;
1370         uint16_t state;
1371
1372         devc = sdi->priv;
1373         bitstream_fn = devc ? devc->fpga_bitstream : "";
1374
1375         ret = check_fpga_bitstream(sdi);
1376         if (ret != SR_OK) {
1377                 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1378                 if (ret != SR_OK) {
1379                         sr_err("Cannot upload FPGA bitstream.");
1380                         return ret;
1381                 }
1382         }
1383         ret = enable_fpga_bitstream(sdi);
1384         if (ret != SR_OK) {
1385                 sr_err("Cannot enable FPGA bitstream after upload.");
1386                 return ret;
1387         }
1388
1389         state = run_state(sdi);
1390         if (state != 0x85e9) {
1391                 sr_warn("Unexpected run state, want 0x85e9, got 0x%04x.", state);
1392         }
1393
1394         ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0);
1395         if (ret != SR_OK) {
1396                 sr_err("Cannot reset USB bulk transfer.");
1397                 return ret;
1398         }
1399
1400         sr_dbg("Device should be initialized.");
1401
1402         return SR_OK;
1403 }
1404
1405 SR_PRIV int la2016_deinit_hardware(const struct sr_dev_inst *sdi)
1406 {
1407         int ret;
1408
1409         ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0);
1410         if (ret != SR_OK) {
1411                 sr_err("Cannot deinitialize device's FPGA.");
1412                 return ret;
1413         }
1414
1415         return SR_OK;
1416 }
1417
1418 SR_PRIV int la2016_write_pwm_config(const struct sr_dev_inst *sdi, size_t idx)
1419 {
1420         return set_pwm_config(sdi, idx);
1421 }