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