]> sigrok.org Git - libsigrok.git/blob - src/hardware/kingst-la2016/protocol.c
7888ed3ec7ebd0c45bf8764b52ce5281b5858473
[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 #define UC_FIRMWARE     "kingst-la-%04x.fw"
32 #define FPGA_FW_LA2016  "kingst-la2016-fpga.bitstream"
33 #define FPGA_FW_LA2016A "kingst-la2016a1-fpga.bitstream"
34 #define FPGA_FW_LA1016  "kingst-la1016-fpga.bitstream"
35 #define FPGA_FW_LA1016A "kingst-la1016a1-fpga.bitstream"
36
37 /* Maximum device capabilities. May differ between models. */
38 #define MAX_SAMPLE_RATE_LA2016  SR_MHZ(200)
39 #define MAX_SAMPLE_RATE_LA1016  SR_MHZ(100)
40 #define MAX_SAMPLE_DEPTH        10e9
41 #define MAX_PWM_FREQ            SR_MHZ(20)
42 #define PWM_CLOCK               SR_MHZ(200)     /* 200MHz for both LA2016 and LA1016 */
43
44 /*
45  * Default device configuration. Must be applicable to any of the
46  * supported devices (no model specific default values yet). Specific
47  * firmware implementation details unfortunately won't let us detect
48  * and keep using previously configured values.
49  */
50 #define LA2016_DFLT_SAMPLERATE  SR_MHZ(100)
51 #define LA2016_DFLT_SAMPLEDEPTH (5 * 1000 * 1000)
52 #define LA2016_DFLT_CAPT_RATIO  5 /* Capture ratio, in percent. */
53
54 /* TODO
55  * What is the origin and motivation of that 128Mi literal? What is its
56  * unit? How does it relate to a device's hardware capabilities? How to
57  * map the 1GiB of RAM of an LA2016 (at 16 channels) to the 128Mi value?
58  * It cannot be sample count. Is it memory size in bytes perhaps?
59  */
60 #define LA2016_PRE_MEM_LIMIT_BASE       (128 * 1024 * 1024)
61
62 /* USB vendor class control requests, executed by the Cypress FX2 MCU. */
63 #define CMD_FPGA_ENABLE 0x10
64 #define CMD_FPGA_SPI    0x20    /* R/W access to FPGA registers via SPI. */
65 #define CMD_BULK_START  0x30    /* Start sample data download via USB EP6 IN. */
66 #define CMD_BULK_RESET  0x38    /* Flush FIFO of FX2 USB EP6 IN. */
67 #define CMD_FPGA_INIT   0x50    /* Used before and after FPGA bitstream upload. */
68 #define CMD_KAUTH       0x60    /* Communicate to auth IC (U10). Not used. */
69 #define CMD_EEPROM      0xa2    /* R/W access to EEPROM content. */
70
71 /*
72  * FPGA register addresses (base addresses when registers span multiple
73  * bytes, in that case data is kept in little endian format). Passed to
74  * CMD_FPGA_SPI requests. The FX2 MCU transparently handles the detail
75  * of SPI transfers encoding the read (1) or write (0) direction in the
76  * MSB of the address field. There are some 60 byte-wide FPGA registers.
77  *
78  * Unfortunately the FPGA registers change their meaning between the
79  * read and write directions of access, or exclusively provide one of
80  * these directions and not the other. This is an arbitrary vendor's
81  * choice, there is nothing which the sigrok driver could do about it.
82  * Values written to registers typically cannot get read back, neither
83  * verified after writing a configuration, nor queried upon startup for
84  * automatic detection of the current configuration. Neither appear to
85  * be there echo registers for presence and communication checks, nor
86  * version identifying registers, as far as we know.
87  */
88 #define REG_RUN         0x00    /* Read capture status, write start capture. */
89 #define REG_PWM_EN      0x02    /* User PWM channels on/off. */
90 #define REG_CAPT_MODE   0x03    /* Write 0x00 capture to SDRAM, 0x01 streaming. */
91 #define REG_BULK        0x08    /* Write start addr, byte count to download samples. */
92 #define REG_SAMPLING    0x10    /* Write capture config, read capture SDRAM location. */
93 #define REG_TRIGGER     0x20    /* write level and edge trigger config. */
94 #define REG_THRESHOLD   0x68    /* Write PWM config to setup input threshold DAC. */
95 #define REG_PWM1        0x70    /* Write config for user PWM1. */
96 #define REG_PWM2        0x78    /* Write config for user PWM2. */
97
98 /* Bit patterns to write to REG_RUN, setup run mode. */
99 #define RUNMODE_HALT    0x00
100 #define RUNMODE_RUN     0x03
101
102 static int ctrl_in(const struct sr_dev_inst *sdi,
103         uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
104         void *data, uint16_t wLength)
105 {
106         struct sr_usb_dev_inst *usb;
107         int ret;
108
109         usb = sdi->conn;
110
111         if ((ret = libusb_control_transfer(usb->devhdl,
112                      LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN,
113                      bRequest, wValue, wIndex, (unsigned char *)data, wLength,
114                      DEFAULT_TIMEOUT_MS)) != wLength) {
115                 sr_dbg("USB ctrl in: %d bytes, req %d val %#x idx %d: %s.",
116                         wLength, bRequest, wValue, wIndex,
117                         libusb_error_name(ret));
118                 sr_err("Cannot read %d bytes from USB: %s.",
119                         wLength, libusb_error_name(ret));
120                 return SR_ERR;
121         }
122
123         return SR_OK;
124 }
125
126 static int ctrl_out(const struct sr_dev_inst *sdi,
127         uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
128         void *data, uint16_t wLength)
129 {
130         struct sr_usb_dev_inst *usb;
131         int ret;
132
133         usb = sdi->conn;
134
135         if ((ret = libusb_control_transfer(usb->devhdl,
136                      LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
137                      bRequest, wValue, wIndex, (unsigned char*)data, wLength,
138                      DEFAULT_TIMEOUT_MS)) != wLength) {
139                 sr_dbg("USB ctrl out: %d bytes, req %d val %#x idx %d: %s.",
140                         wLength, bRequest, wValue, wIndex,
141                         libusb_error_name(ret));
142                 sr_err("Cannot write %d bytes to USB: %s.",
143                         wLength, libusb_error_name(ret));
144                 return SR_ERR;
145         }
146
147         return SR_OK;
148 }
149
150 /*
151  * Check the necessity for FPGA bitstream upload, because another upload
152  * would take some 600ms which is undesirable after program startup. Try
153  * to access some FPGA registers and check the values' plausibility. The
154  * check should fail on the safe side, request another upload when in
155  * doubt. A positive response (the request to continue operation with the
156  * currently active bitstream) should be conservative. Accessing multiple
157  * registers is considered cheap compared to the cost of bitstream upload.
158  *
159  * It helps though that both the vendor software and the sigrok driver
160  * use the same bundle of MCU firmware and FPGA bitstream for any of the
161  * supported models. We don't expect to successfully communicate to the
162  * device yet disagree on its protocol. Ideally we would access version
163  * identifying registers for improved robustness, but are not aware of
164  * any. A bitstream reload can always be forced by a power cycle.
165  */
166 static int check_fpga_bitstream(const struct sr_dev_inst *sdi)
167 {
168         uint8_t init_rsp;
169         int ret;
170         uint16_t run_state;
171         uint8_t pwm_en;
172         size_t read_len;
173         uint8_t buff[sizeof(run_state)];
174         const uint8_t *rdptr;
175
176         sr_dbg("Checking operation of the FPGA bitstream.");
177
178         init_rsp = ~0;
179         ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &init_rsp, sizeof(init_rsp));
180         if (ret != SR_OK || init_rsp != 0) {
181                 sr_dbg("FPGA init query failed, or unexpected response.");
182                 return SR_ERR_IO;
183         }
184
185         read_len = sizeof(run_state);
186         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, buff, read_len);
187         if (ret != SR_OK) {
188                 sr_dbg("FPGA register access failed (run state).");
189                 return SR_ERR_IO;
190         }
191         rdptr = buff;
192         run_state = read_u16le_inc(&rdptr);
193         sr_spew("FPGA register: run state 0x%04x.", run_state);
194         if (run_state && (run_state & 0x3) != 0x1) {
195                 sr_dbg("Unexpected FPGA register content (run state).");
196                 return SR_ERR_DATA;
197         }
198         if (run_state && (run_state & ~0xf) != 0x85e0) {
199                 sr_dbg("Unexpected FPGA register content (run state).");
200                 return SR_ERR_DATA;
201         }
202
203         read_len = sizeof(pwm_en);
204         ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, buff, read_len);
205         if (ret != SR_OK) {
206                 sr_dbg("FPGA register access failed (PWM enable).");
207                 return SR_ERR_IO;
208         }
209         rdptr = buff;
210         pwm_en = read_u8_inc(&rdptr);
211         sr_spew("FPGA register: PWM enable 0x%02x.", pwm_en);
212         if ((pwm_en & 0x3) != 0x0) {
213                 sr_dbg("Unexpected FPGA register content (PWM enable).");
214                 return SR_ERR_DATA;
215         }
216
217         sr_info("Could re-use current FPGA bitstream. No upload required.");
218         return SR_OK;
219 }
220
221 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
222         const char *bitstream_fname)
223 {
224         struct drv_context *drvc;
225         struct sr_usb_dev_inst *usb;
226         struct sr_resource bitstream;
227         uint32_t bitstream_size;
228         uint8_t buffer[sizeof(uint32_t)];
229         uint8_t *wrptr;
230         uint8_t block[4096];
231         int len, act_len;
232         unsigned int pos;
233         int ret;
234         unsigned int zero_pad_to;
235
236         drvc = sdi->driver->context;
237         usb = sdi->conn;
238
239         sr_info("Uploading FPGA bitstream '%s'.", bitstream_fname);
240
241         ret = sr_resource_open(drvc->sr_ctx, &bitstream, 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         if ((ret = ctrl_out(sdi, CMD_FPGA_INIT, 0x00, 0, buffer, wrptr - buffer)) != SR_OK) {
251                 sr_err("Cannot initiate FPGA bitstream upload.");
252                 sr_resource_close(drvc->sr_ctx, &bitstream);
253                 return ret;
254         }
255         zero_pad_to = bitstream_size;
256         zero_pad_to += LA2016_EP2_PADDING - 1;
257         zero_pad_to /= LA2016_EP2_PADDING;
258         zero_pad_to *= LA2016_EP2_PADDING;
259
260         pos = 0;
261         while (1) {
262                 if (pos < bitstream.size) {
263                         len = (int)sr_resource_read(drvc->sr_ctx, &bitstream, &block, sizeof(block));
264                         if (len < 0) {
265                                 sr_err("Cannot read FPGA bitstream.");
266                                 sr_resource_close(drvc->sr_ctx, &bitstream);
267                                 return SR_ERR;
268                         }
269                 } else {
270                         /*  Zero-pad until 'zero_pad_to'. */
271                         len = zero_pad_to - pos;
272                         if ((unsigned)len > sizeof(block))
273                                 len = sizeof(block);
274                         memset(&block, 0, len);
275                 }
276                 if (len == 0)
277                         break;
278
279                 ret = libusb_bulk_transfer(usb->devhdl, USB_EP_FPGA_BITSTREAM,
280                         &block[0], len, &act_len, DEFAULT_TIMEOUT_MS);
281                 if (ret != 0) {
282                         sr_dbg("Cannot write FPGA bitstream, block %#x len %d: %s.",
283                                 pos, (int)len, libusb_error_name(ret));
284                         ret = SR_ERR;
285                         break;
286                 }
287                 if (act_len != len) {
288                         sr_dbg("Short write for FPGA bitstream, block %#x len %d: got %d.",
289                                 pos, (int)len, act_len);
290                         ret = SR_ERR;
291                         break;
292                 }
293                 pos += len;
294         }
295         sr_resource_close(drvc->sr_ctx, &bitstream);
296         if (ret != 0)
297                 return ret;
298         sr_info("FPGA bitstream upload (%" PRIu64 " bytes) done.",
299                 bitstream.size);
300
301         return SR_OK;
302 }
303
304 static int enable_fpga_bitstream(const struct sr_dev_inst *sdi)
305 {
306         int ret;
307         uint8_t cmd_resp;
308
309         if ((ret = ctrl_in(sdi, CMD_FPGA_INIT, 0x00, 0, &cmd_resp, sizeof(cmd_resp))) != SR_OK) {
310                 sr_err("Cannot read response after FPGA bitstream upload.");
311                 return ret;
312         }
313         if (cmd_resp != 0) {
314                 sr_err("Unexpected FPGA bitstream upload response, got 0x%02x, want 0.",
315                         cmd_resp);
316                 return SR_ERR;
317         }
318         g_usleep(30 * 1000);
319
320         if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x01, 0, NULL, 0)) != SR_OK) {
321                 sr_err("Cannot enable FPGA after bitstream upload.");
322                 return ret;
323         }
324         g_usleep(40 * 1000);
325
326         return SR_OK;
327 }
328
329 static int set_threshold_voltage(const struct sr_dev_inst *sdi, float voltage)
330 {
331         struct dev_context *devc;
332         int ret;
333
334         devc = sdi->priv;
335
336         uint16_t duty_R79, duty_R56;
337         uint8_t buf[2 * sizeof(uint16_t)];
338         uint8_t *wrptr;
339
340         /* Clamp threshold setting to valid range for LA2016. */
341         if (voltage > 4.0) {
342                 voltage = 4.0;
343         } else if (voltage < -4.0) {
344                 voltage = -4.0;
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         devc->threshold_voltage = voltage;
389
390         return SR_OK;
391 }
392
393 static int enable_pwm(const struct sr_dev_inst *sdi, uint8_t p1, uint8_t p2)
394 {
395         struct dev_context *devc;
396         uint8_t cfg;
397         int ret;
398
399         devc = sdi->priv;
400         cfg = 0;
401
402         if (p1) cfg |= 1 << 0;
403         if (p2) cfg |= 1 << 1;
404
405         sr_dbg("Set PWM enable %d %d. Config 0x%02x.", p1, p2, cfg);
406         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_PWM_EN, 0, &cfg, sizeof(cfg));
407         if (ret != SR_OK) {
408                 sr_err("Cannot setup PWM enabled state.");
409                 return ret;
410         }
411         devc->pwm_setting[0].enabled = (p1) ? 1 : 0;
412         devc->pwm_setting[1].enabled = (p2) ? 1 : 0;
413
414         return SR_OK;
415 }
416
417 static int set_pwm(const struct sr_dev_inst *sdi, uint8_t which,
418         float freq, float duty)
419 {
420         int CTRL_PWM[] = { REG_PWM1, REG_PWM2 };
421         struct dev_context *devc;
422         pwm_setting_dev_t cfg;
423         pwm_setting_t *setting;
424         int ret;
425         uint8_t buf[2 * sizeof(uint32_t)];
426         uint8_t *wrptr;
427
428         devc = sdi->priv;
429
430         if (which < 1 || which > ARRAY_SIZE(CTRL_PWM)) {
431                 sr_err("Invalid PWM channel: %d.", which);
432                 return SR_ERR;
433         }
434         if (freq > MAX_PWM_FREQ) {
435                 sr_err("Too high a PWM frequency: %.1f.", freq);
436                 return SR_ERR;
437         }
438         if (duty > 100 || duty < 0) {
439                 sr_err("Invalid PWM duty cycle: %f.", duty);
440                 return SR_ERR;
441         }
442
443         cfg.period = (uint32_t)(PWM_CLOCK / freq);
444         cfg.duty = (uint32_t)(0.5f + (cfg.period * duty / 100.));
445         sr_dbg("Set PWM%d period %d, duty %d.", which, cfg.period, cfg.duty);
446
447         wrptr = buf;
448         write_u32le_inc(&wrptr, cfg.period);
449         write_u32le_inc(&wrptr, cfg.duty);
450         ret = ctrl_out(sdi, CMD_FPGA_SPI, CTRL_PWM[which - 1], 0, buf, wrptr - buf);
451         if (ret != SR_OK) {
452                 sr_err("Cannot setup PWM%d configuration %d %d.",
453                         which, cfg.period, cfg.duty);
454                 return ret;
455         }
456         setting = &devc->pwm_setting[which - 1];
457         setting->freq = freq;
458         setting->duty = duty;
459
460         return SR_OK;
461 }
462
463 static int set_defaults(const struct sr_dev_inst *sdi)
464 {
465         struct dev_context *devc;
466         int ret;
467
468         devc = sdi->priv;
469
470         devc->capture_ratio = LA2016_DFLT_CAPT_RATIO;
471         devc->cur_channels = 0xffff;
472         devc->limit_samples = LA2016_DFLT_SAMPLEDEPTH;
473         devc->cur_samplerate = LA2016_DFLT_SAMPLERATE;
474
475         ret = set_threshold_voltage(sdi, devc->threshold_voltage);
476         if (ret)
477                 return ret;
478
479         ret = enable_pwm(sdi, 0, 0);
480         if (ret)
481                 return ret;
482
483         ret = set_pwm(sdi, 1, SR_KHZ(1), 50);
484         if (ret)
485                 return ret;
486
487         ret = set_pwm(sdi, 2, SR_KHZ(100), 50);
488         if (ret)
489                 return ret;
490
491         ret = enable_pwm(sdi, 1, 1);
492         if (ret)
493                 return ret;
494
495         return SR_OK;
496 }
497
498 static int set_trigger_config(const struct sr_dev_inst *sdi)
499 {
500         struct dev_context *devc;
501         struct sr_trigger *trigger;
502         trigger_cfg_t cfg;
503         GSList *stages;
504         GSList *channel;
505         struct sr_trigger_stage *stage1;
506         struct sr_trigger_match *match;
507         uint16_t ch_mask;
508         int ret;
509         uint8_t buf[4 * sizeof(uint32_t)];
510         uint8_t *wrptr;
511
512         devc = sdi->priv;
513         trigger = sr_session_trigger_get(sdi->session);
514
515         memset(&cfg, 0, sizeof(cfg));
516
517         cfg.channels = devc->cur_channels;
518
519         if (trigger && trigger->stages) {
520                 stages = trigger->stages;
521                 stage1 = stages->data;
522                 if (stages->next) {
523                         sr_err("Only one trigger stage supported for now.");
524                         return SR_ERR;
525                 }
526                 channel = stage1->matches;
527                 while (channel) {
528                         match = channel->data;
529                         ch_mask = 1 << match->channel->index;
530
531                         switch (match->match) {
532                         case SR_TRIGGER_ZERO:
533                                 cfg.level |= ch_mask;
534                                 cfg.high_or_falling &= ~ch_mask;
535                                 break;
536                         case SR_TRIGGER_ONE:
537                                 cfg.level |= ch_mask;
538                                 cfg.high_or_falling |= ch_mask;
539                                 break;
540                         case SR_TRIGGER_RISING:
541                                 if ((cfg.enabled & ~cfg.level)) {
542                                         sr_err("Device only supports one edge trigger.");
543                                         return SR_ERR;
544                                 }
545                                 cfg.level &= ~ch_mask;
546                                 cfg.high_or_falling &= ~ch_mask;
547                                 break;
548                         case SR_TRIGGER_FALLING:
549                                 if ((cfg.enabled & ~cfg.level)) {
550                                         sr_err("Device only supports one edge trigger.");
551                                         return SR_ERR;
552                                 }
553                                 cfg.level &= ~ch_mask;
554                                 cfg.high_or_falling |= ch_mask;
555                                 break;
556                         default:
557                                 sr_err("Unknown trigger condition.");
558                                 return SR_ERR;
559                         }
560                         cfg.enabled |= ch_mask;
561                         channel = channel->next;
562                 }
563         }
564         sr_dbg("Set trigger config: "
565                 "channels 0x%04x, trigger-enabled 0x%04x, "
566                 "level-triggered 0x%04x, high/falling 0x%04x.",
567                 cfg.channels, cfg.enabled, cfg.level, cfg.high_or_falling);
568
569         devc->had_triggers_configured = cfg.enabled != 0;
570
571         wrptr = buf;
572         write_u32le_inc(&wrptr, cfg.channels);
573         write_u32le_inc(&wrptr, cfg.enabled);
574         write_u32le_inc(&wrptr, cfg.level);
575         write_u32le_inc(&wrptr, cfg.high_or_falling);
576         /* TODO
577          * Comment on this literal 16. Origin, meaning? Cannot be the
578          * register offset, nor the transfer length. Is it a channels
579          * count that is relevant for 16 and 32 channel models? Is it
580          * an obsolete experiment?
581          */
582         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_TRIGGER, 16, buf, wrptr - buf);
583         if (ret != SR_OK) {
584                 sr_err("Cannot setup trigger configuration.");
585                 return ret;
586         }
587
588         return SR_OK;
589 }
590
591 static int set_sample_config(const struct sr_dev_inst *sdi)
592 {
593         struct dev_context *devc;
594         double clock_divisor;
595         uint64_t total;
596         int ret;
597         uint16_t divisor;
598         uint8_t buf[2 * sizeof(uint32_t) + 48 / 8 + sizeof(uint16_t)];
599         uint8_t *wrptr;
600
601         devc = sdi->priv;
602         total = LA2016_PRE_MEM_LIMIT_BASE;
603
604         if (devc->cur_samplerate > devc->max_samplerate) {
605                 sr_err("Too high a sample rate: %" PRIu64 ".",
606                         devc->cur_samplerate);
607                 return SR_ERR;
608         }
609
610         clock_divisor = devc->max_samplerate / (double)devc->cur_samplerate;
611         if (clock_divisor > 0xffff)
612                 clock_divisor = 0xffff;
613         divisor = (uint16_t)(clock_divisor + 0.5);
614         devc->cur_samplerate = devc->max_samplerate / divisor;
615
616         if (devc->limit_samples > MAX_SAMPLE_DEPTH) {
617                 sr_err("Too high a sample depth: %" PRIu64 ".",
618                         devc->limit_samples);
619                 return SR_ERR;
620         }
621
622         devc->pre_trigger_size = (devc->capture_ratio * devc->limit_samples) / 100;
623
624         sr_dbg("Set sample config: %" PRIu64 "kHz, %" PRIu64 " samples, trigger-pos %" PRIu64 "%%.",
625                 devc->cur_samplerate / 1000,
626                 devc->limit_samples,
627                 devc->capture_ratio);
628
629         wrptr = buf;
630         write_u32le_inc(&wrptr, devc->limit_samples);
631         write_u8_inc(&wrptr, 0);
632         write_u32le_inc(&wrptr, devc->pre_trigger_size);
633         write_u32le_inc(&wrptr, ((total * devc->capture_ratio) / 100) & 0xffffff00);
634         write_u16le_inc(&wrptr, divisor);
635         write_u8_inc(&wrptr, 0);
636
637         ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, wrptr - buf);
638         if (ret != SR_OK) {
639                 sr_err("Cannot setup acquisition configuration.");
640                 return ret;
641         }
642
643         return SR_OK;
644 }
645
646 /*
647  * FPGA register REG_RUN holds the run state (u16le format). Bit fields
648  * of interest:
649  *   bit 0: value 1 = idle
650  *   bit 1: value 1 = writing to SDRAM
651  *   bit 2: value 0 = waiting for trigger, 1 = trigger seen
652  *   bit 3: value 0 = pretrigger sampling, 1 = posttrigger sampling
653  * The meaning of other bit fields is unknown.
654  *
655  * Typical values in order of appearance during execution:
656  *   0x85e2: pre-sampling, samples before the trigger position,
657  *     when capture ratio > 0%
658  *   0x85ea: pre-sampling complete, now waiting for the trigger
659  *     (whilst sampling continuously)
660  *   0x85ee: trigger seen, capturing post-trigger samples, running
661  *   0x85ed: idle
662  */
663 static uint16_t run_state(const struct sr_dev_inst *sdi)
664 {
665         uint16_t state;
666         static uint16_t previous_state = 0;
667         int ret;
668
669         if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_RUN, 0, &state, sizeof(state))) != SR_OK) {
670                 sr_err("Cannot read run state.");
671                 return ret;
672         }
673
674         /*
675          * Avoid flooding the log, only dump values as they change.
676          * The routine is called about every 50ms.
677          */
678         if (state != previous_state) {
679                 previous_state = state;
680                 if ((state & 0x0003) == 0x01) {
681                         sr_dbg("Run state: 0x%04x (%s).", state, "idle");
682                 } else if ((state & 0x000f) == 0x02) {
683                         sr_dbg("Run state: 0x%04x (%s).", state,
684                                 "pre-trigger sampling");
685                 } else if ((state & 0x000f) == 0x0a) {
686                         sr_dbg("Run state: 0x%04x (%s).", state,
687                                 "sampling, waiting for trigger");
688                 } else if ((state & 0x000f) == 0x0e) {
689                         sr_dbg("Run state: 0x%04x (%s).", state,
690                                 "post-trigger sampling");
691                 } else {
692                         sr_dbg("Run state: 0x%04x.", state);
693                 }
694         }
695
696         return state;
697 }
698
699 static int la2016_has_triggered(const struct sr_dev_inst *sdi)
700 {
701         uint16_t state;
702
703         state = run_state(sdi);
704         if ((state & 0x3) == 0x1)
705                 return 1;
706
707         return 0;
708 }
709
710 static int set_run_mode(const struct sr_dev_inst *sdi, uint8_t mode)
711 {
712         int ret;
713
714         if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_RUN, 0, &mode, sizeof(mode))) != SR_OK) {
715                 sr_err("Cannot configure run mode %d.", mode);
716                 return ret;
717         }
718
719         return SR_OK;
720 }
721
722 static int get_capture_info(const struct sr_dev_inst *sdi)
723 {
724         struct dev_context *devc;
725         int ret;
726         uint8_t buf[3 * sizeof(uint32_t)];
727         const uint8_t *rdptr;
728
729         devc = sdi->priv;
730
731         if ((ret = ctrl_in(sdi, CMD_FPGA_SPI, REG_SAMPLING, 0, buf, sizeof(buf))) != SR_OK) {
732                 sr_err("Cannot read capture info.");
733                 return ret;
734         }
735
736         rdptr = buf;
737         devc->info.n_rep_packets = read_u32le_inc(&rdptr);
738         devc->info.n_rep_packets_before_trigger = read_u32le_inc(&rdptr);
739         devc->info.write_pos = read_u32le_inc(&rdptr);
740
741         sr_dbg("Capture info: n_rep_packets: 0x%08x/%d, before_trigger: 0x%08x/%d, write_pos: 0x%08x%d.",
742                 devc->info.n_rep_packets, devc->info.n_rep_packets,
743                 devc->info.n_rep_packets_before_trigger,
744                 devc->info.n_rep_packets_before_trigger,
745                 devc->info.write_pos, devc->info.write_pos);
746
747         if (devc->info.n_rep_packets % NUM_PACKETS_IN_CHUNK) {
748                 sr_warn("Unexpected packets count %lu, not a multiple of %d.",
749                         (unsigned long)devc->info.n_rep_packets,
750                         NUM_PACKETS_IN_CHUNK);
751         }
752
753         return SR_OK;
754 }
755
756 SR_PRIV int la2016_upload_firmware(struct sr_context *sr_ctx,
757         libusb_device *dev, uint16_t product_id)
758 {
759         char fw_file[1024];
760         snprintf(fw_file, sizeof(fw_file) - 1, UC_FIRMWARE, product_id);
761         return ezusb_upload_firmware(sr_ctx, dev, USB_CONFIGURATION, fw_file);
762 }
763
764 SR_PRIV int la2016_setup_acquisition(const struct sr_dev_inst *sdi)
765 {
766         struct dev_context *devc;
767         int ret;
768         uint8_t cmd;
769
770         devc = sdi->priv;
771
772         ret = set_threshold_voltage(sdi, devc->threshold_voltage);
773         if (ret != SR_OK)
774                 return ret;
775
776         cmd = 0;
777         if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_CAPT_MODE, 0, &cmd, sizeof(cmd))) != SR_OK) {
778                 sr_err("Cannot send command to stop sampling.");
779                 return ret;
780         }
781
782         ret = set_trigger_config(sdi);
783         if (ret != SR_OK)
784                 return ret;
785
786         ret = set_sample_config(sdi);
787         if (ret != SR_OK)
788                 return ret;
789
790         return SR_OK;
791 }
792
793 SR_PRIV int la2016_start_acquisition(const struct sr_dev_inst *sdi)
794 {
795         int ret;
796
797         ret = set_run_mode(sdi, RUNMODE_RUN);
798         if (ret != SR_OK)
799                 return ret;
800
801         return SR_OK;
802 }
803
804 static int la2016_stop_acquisition(const struct sr_dev_inst *sdi)
805 {
806         int ret;
807
808         ret = set_run_mode(sdi, RUNMODE_HALT);
809         if (ret != SR_OK)
810                 return ret;
811
812         return SR_OK;
813 }
814
815 SR_PRIV int la2016_abort_acquisition(const struct sr_dev_inst *sdi)
816 {
817         int ret;
818         struct dev_context *devc;
819
820         ret = la2016_stop_acquisition(sdi);
821         if (ret != SR_OK)
822                 return ret;
823
824         devc = sdi ? sdi->priv : NULL;
825         if (devc && devc->transfer)
826                 libusb_cancel_transfer(devc->transfer);
827
828         return SR_OK;
829 }
830
831 static int la2016_start_retrieval(const struct sr_dev_inst *sdi,
832         libusb_transfer_cb_fn cb)
833 {
834         struct dev_context *devc;
835         struct sr_usb_dev_inst *usb;
836         int ret;
837         uint8_t wrbuf[2 * sizeof(uint32_t)];
838         uint8_t *wrptr;
839         uint32_t to_read;
840         uint8_t *buffer;
841
842         devc = sdi->priv;
843         usb = sdi->conn;
844
845         if ((ret = get_capture_info(sdi)) != SR_OK)
846                 return ret;
847
848         devc->n_transfer_packets_to_read = devc->info.n_rep_packets / NUM_PACKETS_IN_CHUNK;
849         devc->n_bytes_to_read = devc->n_transfer_packets_to_read * TRANSFER_PACKET_LENGTH;
850         devc->read_pos = devc->info.write_pos - devc->n_bytes_to_read;
851         devc->n_reps_until_trigger = devc->info.n_rep_packets_before_trigger;
852
853         sr_dbg("Want to read %u xfer-packets starting from pos %" PRIu32 ".",
854                 devc->n_transfer_packets_to_read, devc->read_pos);
855
856         if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
857                 sr_err("Cannot reset USB bulk state.");
858                 return ret;
859         }
860         sr_dbg("Will read from 0x%08lx, 0x%08x bytes.",
861                 (unsigned long)devc->read_pos, devc->n_bytes_to_read);
862         wrptr = wrbuf;
863         write_u32le_inc(&wrptr, devc->read_pos);
864         write_u32le_inc(&wrptr, devc->n_bytes_to_read);
865         if ((ret = ctrl_out(sdi, CMD_FPGA_SPI, REG_BULK, 0, wrbuf, wrptr - wrbuf)) != SR_OK) {
866                 sr_err("Cannot send USB bulk config.");
867                 return ret;
868         }
869         if ((ret = ctrl_out(sdi, CMD_BULK_START, 0x00, 0, NULL, 0)) != SR_OK) {
870                 sr_err("Cannot unblock USB bulk transfers.");
871                 return ret;
872         }
873
874         /*
875          * Pick a buffer size for all USB transfers. The buffer size
876          * must be a multiple of the endpoint packet size. And cannot
877          * exceed a maximum value.
878          */
879         to_read = devc->n_bytes_to_read;
880         if (to_read >= LA2016_USB_BUFSZ) /* Multiple transfers. */
881                 to_read = LA2016_USB_BUFSZ;
882         else /* One transfer. */
883                 to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
884         buffer = g_try_malloc(to_read);
885         if (!buffer) {
886                 sr_dbg("USB bulk transfer size %d bytes.", (int)to_read);
887                 sr_err("Cannot allocate buffer for USB bulk transfer.");
888                 return SR_ERR_MALLOC;
889         }
890
891         devc->transfer = libusb_alloc_transfer(0);
892         libusb_fill_bulk_transfer(devc->transfer,
893                 usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
894                 buffer, to_read,
895                 cb, (void *)sdi, DEFAULT_TIMEOUT_MS);
896
897         if ((ret = libusb_submit_transfer(devc->transfer)) != 0) {
898                 sr_err("Cannot submit USB transfer: %s.", libusb_error_name(ret));
899                 libusb_free_transfer(devc->transfer);
900                 devc->transfer = NULL;
901                 g_free(buffer);
902                 return SR_ERR;
903         }
904
905         return SR_OK;
906 }
907
908 static void send_chunk(struct sr_dev_inst *sdi,
909         const uint8_t *packets, unsigned int num_tfers)
910 {
911         struct dev_context *devc;
912         struct sr_datafeed_logic logic;
913         struct sr_datafeed_packet sr_packet;
914         unsigned int max_samples, n_samples, total_samples, free_n_samples;
915         unsigned int i, j, k;
916         int do_signal_trigger;
917         uint16_t *wp;
918         const uint8_t *rp;
919         uint16_t state;
920         uint8_t repetitions;
921
922         devc = sdi->priv;
923
924         logic.unitsize = 2;
925         logic.data = devc->convbuffer;
926
927         sr_packet.type = SR_DF_LOGIC;
928         sr_packet.payload = &logic;
929
930         max_samples = devc->convbuffer_size / 2;
931         n_samples = 0;
932         wp = (uint16_t *)devc->convbuffer;
933         total_samples = 0;
934         do_signal_trigger = 0;
935
936         if (devc->had_triggers_configured && devc->reading_behind_trigger == 0 && devc->info.n_rep_packets_before_trigger == 0) {
937                 std_session_send_df_trigger(sdi);
938                 devc->reading_behind_trigger = 1;
939         }
940
941         rp = packets;
942         for (i = 0; i < num_tfers; i++) {
943                 for (k = 0; k < NUM_PACKETS_IN_CHUNK; k++) {
944                         free_n_samples = max_samples - n_samples;
945                         if (free_n_samples < 256 || do_signal_trigger) {
946                                 logic.length = n_samples * 2;
947                                 sr_session_send(sdi, &sr_packet);
948                                 n_samples = 0;
949                                 wp = (uint16_t *)devc->convbuffer;
950                                 if (do_signal_trigger) {
951                                         std_session_send_df_trigger(sdi);
952                                         do_signal_trigger = 0;
953                                 }
954                         }
955
956                         state = read_u16le_inc(&rp);
957                         repetitions = read_u8_inc(&rp);
958                         for (j = 0; j < repetitions; j++)
959                                 *wp++ = state;
960
961                         n_samples += repetitions;
962                         total_samples += repetitions;
963                         devc->total_samples += repetitions;
964                         if (!devc->reading_behind_trigger) {
965                                 devc->n_reps_until_trigger--;
966                                 if (devc->n_reps_until_trigger == 0) {
967                                         devc->reading_behind_trigger = 1;
968                                         do_signal_trigger = 1;
969                                         sr_dbg("Trigger position after %" PRIu64 " samples, %.6fms.",
970                                                 devc->total_samples,
971                                                 (double)devc->total_samples / devc->cur_samplerate * 1e3);
972                                 }
973                         }
974                 }
975                 (void)read_u8_inc(&rp); /* Skip sequence number. */
976         }
977         if (n_samples) {
978                 logic.length = n_samples * 2;
979                 sr_session_send(sdi, &sr_packet);
980                 if (do_signal_trigger) {
981                         std_session_send_df_trigger(sdi);
982                 }
983         }
984         sr_dbg("Send_chunk done after %u samples.", total_samples);
985 }
986
987 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
988 {
989         struct sr_dev_inst *sdi;
990         struct dev_context *devc;
991         struct sr_usb_dev_inst *usb;
992         int ret;
993
994         sdi = transfer->user_data;
995         devc = sdi->priv;
996         usb = sdi->conn;
997
998         sr_dbg("receive_transfer(): status %s received %d bytes.",
999                 libusb_error_name(transfer->status), transfer->actual_length);
1000
1001         if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
1002                 sr_err("USB bulk transfer timeout.");
1003                 devc->transfer_finished = 1;
1004         }
1005         send_chunk(sdi, transfer->buffer, transfer->actual_length / TRANSFER_PACKET_LENGTH);
1006
1007         devc->n_bytes_to_read -= transfer->actual_length;
1008         if (devc->n_bytes_to_read) {
1009                 uint32_t to_read = devc->n_bytes_to_read;
1010                 /*
1011                  * Determine read size for the next USB transfer. Make
1012                  * the buffer size a multiple of the endpoint packet
1013                  * size. Don't exceed a maximum value.
1014                  */
1015                 if (to_read >= LA2016_USB_BUFSZ)
1016                         to_read = LA2016_USB_BUFSZ;
1017                 else
1018                         to_read = (to_read + (LA2016_EP6_PKTSZ-1)) & ~(LA2016_EP6_PKTSZ-1);
1019                 libusb_fill_bulk_transfer(transfer,
1020                         usb->devhdl, USB_EP_CAPTURE_DATA | LIBUSB_ENDPOINT_IN,
1021                         transfer->buffer, to_read,
1022                         receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
1023
1024                 if ((ret = libusb_submit_transfer(transfer)) == 0)
1025                         return;
1026                 sr_err("Cannot submit another USB transfer: %s.",
1027                         libusb_error_name(ret));
1028         }
1029
1030         g_free(transfer->buffer);
1031         libusb_free_transfer(transfer);
1032         devc->transfer_finished = 1;
1033 }
1034
1035 SR_PRIV int la2016_receive_data(int fd, int revents, void *cb_data)
1036 {
1037         const struct sr_dev_inst *sdi;
1038         struct dev_context *devc;
1039         struct drv_context *drvc;
1040         struct timeval tv;
1041
1042         (void)fd;
1043         (void)revents;
1044
1045         sdi = cb_data;
1046         devc = sdi->priv;
1047         drvc = sdi->driver->context;
1048
1049         if (devc->have_trigger == 0) {
1050                 if (la2016_has_triggered(sdi) == 0) {
1051                         /* Not yet ready for sample data download. */
1052                         return TRUE;
1053                 }
1054                 devc->have_trigger = 1;
1055                 devc->transfer_finished = 0;
1056                 devc->reading_behind_trigger = 0;
1057                 devc->total_samples = 0;
1058                 /* We can start downloading sample data. */
1059                 if (la2016_start_retrieval(sdi, receive_transfer) != SR_OK) {
1060                         sr_err("Cannot start acquisition data download.");
1061                         return FALSE;
1062                 }
1063                 sr_dbg("Acquisition data download started.");
1064                 std_session_send_df_frame_begin(sdi);
1065
1066                 return TRUE;
1067         }
1068
1069         tv.tv_sec = tv.tv_usec = 0;
1070         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
1071
1072         if (devc->transfer_finished) {
1073                 sr_dbg("Download finished, post processing.");
1074                 std_session_send_df_frame_end(sdi);
1075
1076                 usb_source_remove(sdi->session, drvc->sr_ctx);
1077                 std_session_send_df_end(sdi);
1078
1079                 la2016_stop_acquisition(sdi);
1080
1081                 g_free(devc->convbuffer);
1082                 devc->convbuffer = NULL;
1083
1084                 devc->transfer = NULL;
1085
1086                 sr_dbg("Download finished, done post processing.");
1087         }
1088
1089         return TRUE;
1090 }
1091
1092 SR_PRIV int la2016_init_device(const struct sr_dev_inst *sdi)
1093 {
1094         struct dev_context *devc;
1095         uint16_t state;
1096         uint8_t buf[8];
1097         int16_t purchase_date_bcd[2];
1098         uint8_t magic;
1099         const char *bitstream_fn;
1100         int ret;
1101
1102         devc = sdi->priv;
1103
1104         /*
1105          * Four EEPROM bytes at offset 0x20 are purchase year and month
1106          * in BCD format, with 16bit complemented checksum. For example
1107          * 20 04 df fb translates to 2020-04. This can help identify the
1108          * age of devices when unknown magic numbers are seen.
1109          */
1110         if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x20, 0, purchase_date_bcd, sizeof(purchase_date_bcd))) != SR_OK) {
1111                 sr_err("Cannot read purchase date in EEPROM.");
1112         } else {
1113                 sr_dbg("Purchase date: 20%02hx-%02hx.",
1114                         (purchase_date_bcd[0]) & 0xff,
1115                         (purchase_date_bcd[0] >> 8) & 0xff);
1116                 if (purchase_date_bcd[0] != (0x0ffff & ~purchase_date_bcd[1])) {
1117                         sr_err("Purchase date fails checksum test.");
1118                 }
1119         }
1120
1121         /*
1122          * Several Kingst logic analyzer devices share the same USB VID
1123          * and PID. The product ID determines which MCU firmware to load.
1124          * The MCU firmware provides access to EEPROM content which then
1125          * allows to identify the device model. Which in turn determines
1126          * which FPGA bitstream to load. Eight bytes at offset 0x08 are
1127          * to get inspected.
1128          *
1129          * EEPROM content for model identification is kept redundantly
1130          * in memory. The values are stored in verbatim and in inverted
1131          * form, multiple copies are kept at different offsets. Example
1132          * data:
1133          *
1134          *   magic 0x08
1135          *    | ~magic 0xf7
1136          *    | |
1137          *   08f7000008f710ef
1138          *            | |
1139          *            | ~magic backup
1140          *            magic backup
1141          *
1142          * Exclusively inspecting the magic byte appears to be sufficient,
1143          * other fields seem to be 'don't care'.
1144          *
1145          *   magic 2 == LA2016 using "kingst-la2016-fpga.bitstream"
1146          *   magic 3 == LA1016 using "kingst-la1016-fpga.bitstream"
1147          *   magic 8 == LA2016a using "kingst-la2016a1-fpga.bitstream"
1148          *              (latest v1.3.0 PCB, perhaps others)
1149          *   magic 9 == LA1016a using "kingst-la1016a1-fpga.bitstream"
1150          *              (latest v1.3.0 PCB, perhaps others)
1151          *
1152          * When EEPROM content does not match the hardware configuration
1153          * (the board layout), the software may load but yield incorrect
1154          * results (like swapped channels). The FPGA bitstream itself
1155          * will authenticate with IC U10 and fail when its capabilities
1156          * do not match the hardware model. An LA1016 won't become a
1157          * LA2016 by faking its EEPROM content.
1158          */
1159         if ((ret = ctrl_in(sdi, CMD_EEPROM, 0x08, 0, &buf, sizeof(buf))) != SR_OK) {
1160                 sr_err("Cannot read EEPROM device identifier bytes.");
1161                 return ret;
1162         }
1163
1164         magic = 0;
1165         if (buf[0] == (0xff & ~buf[1])) {
1166                 /* Primary copy of magic passes complement check. */
1167                 magic = buf[0];
1168         } else if (buf[4] == (0xff & ~buf[5])) {
1169                 /* Backup copy of magic passes complement check. */
1170                 sr_dbg("Using backup copy of device type magic number.");
1171                 magic = buf[4];
1172         }
1173
1174         sr_dbg("Device type: magic number is %hhu.", magic);
1175
1176         /* Select the FPGA bitstream depending on the model. */
1177         switch (magic) {
1178         case 2:
1179                 bitstream_fn = FPGA_FW_LA2016;
1180                 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1181                 break;
1182         case 3:
1183                 bitstream_fn = FPGA_FW_LA1016;
1184                 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1185                 break;
1186         case 8:
1187                 bitstream_fn = FPGA_FW_LA2016A;
1188                 devc->max_samplerate = MAX_SAMPLE_RATE_LA2016;
1189                 break;
1190         case 9:
1191                 bitstream_fn = FPGA_FW_LA1016A;
1192                 devc->max_samplerate = MAX_SAMPLE_RATE_LA1016;
1193                 break;
1194         default:
1195                 bitstream_fn = NULL;
1196                 break;
1197         }
1198         if (!bitstream_fn || !*bitstream_fn) {
1199                 sr_err("Cannot identify as one of the supported models.");
1200                 return SR_ERR;
1201         }
1202
1203         if (check_fpga_bitstream(sdi) != SR_OK) {
1204                 ret = upload_fpga_bitstream(sdi, bitstream_fn);
1205                 if (ret != SR_OK) {
1206                         sr_err("Cannot upload FPGA bitstream.");
1207                         return ret;
1208                 }
1209         }
1210         ret = enable_fpga_bitstream(sdi);
1211         if (ret != SR_OK) {
1212                 sr_err("Cannot enable FPGA bitstream after upload.");
1213                 return ret;
1214         }
1215
1216         state = run_state(sdi);
1217         if (state != 0x85e9) {
1218                 sr_warn("Unexpected run state, want 0x85e9, got 0x%04x.", state);
1219         }
1220
1221         if ((ret = ctrl_out(sdi, CMD_BULK_RESET, 0x00, 0, NULL, 0)) != SR_OK) {
1222                 sr_err("Cannot reset USB bulk transfer.");
1223                 return ret;
1224         }
1225
1226         sr_dbg("Device should be initialized.");
1227
1228         ret = set_defaults(sdi);
1229         if (ret != SR_OK)
1230                 return ret;
1231
1232         return SR_OK;
1233 }
1234
1235 SR_PRIV int la2016_deinit_device(const struct sr_dev_inst *sdi)
1236 {
1237         int ret;
1238
1239         if ((ret = ctrl_out(sdi, CMD_FPGA_ENABLE, 0x00, 0, NULL, 0)) != SR_OK) {
1240                 sr_err("Cannot deinitialize device's FPGA.");
1241                 return ret;
1242         }
1243
1244         return SR_OK;
1245 }