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