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