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