]> sigrok.org Git - libsigrok.git/blame_incremental - src/hardware/asix-sigma/protocol.c
asix-sigma: keep remaining samplerate handling in protocol.c
[libsigrok.git] / src / hardware / asix-sigma / protocol.c
... / ...
CommitLineData
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2010-2012 Håvard Espeland <gus@ping.uio.no>,
5 * Copyright (C) 2010 Martin Stensgård <mastensg@ping.uio.no>
6 * Copyright (C) 2010 Carl Henrik Lunde <chlunde@ping.uio.no>
7 * Copyright (C) 2020 Gerhard Sittig <gerhard.sittig@gmx.net>
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/*
24 * ASIX SIGMA/SIGMA2 logic analyzer driver
25 */
26
27#include <config.h>
28#include "protocol.h"
29
30/*
31 * The ASIX SIGMA hardware supports fixed 200MHz and 100MHz sample rates
32 * (by means of separate firmware images). As well as 50MHz divided by
33 * an integer divider in the 1..256 range (by the "typical" firmware).
34 * Which translates to a strict lower boundary of around 195kHz.
35 *
36 * This driver "suggests" a subset of the available rates by listing a
37 * few discrete values, while setter routines accept any user specified
38 * rate that is supported by the hardware.
39 */
40static const uint64_t samplerates[] = {
41 /* 50MHz and integer divider. 1/2/5 steps (where possible). */
42 SR_KHZ(200), SR_KHZ(500),
43 SR_MHZ(1), SR_MHZ(2), SR_MHZ(5),
44 SR_MHZ(10), SR_MHZ(25), SR_MHZ(50),
45 /* 100MHz/200MHz, fixed rates in special firmware. */
46 SR_MHZ(100), SR_MHZ(200),
47};
48
49SR_PRIV GVariant *sigma_get_samplerates_list(void)
50{
51 return std_gvar_samplerates(samplerates, ARRAY_SIZE(samplerates));
52}
53
54static const char *firmware_files[] = {
55 [SIGMA_FW_50MHZ] = "asix-sigma-50.fw", /* 50MHz, 8bit divider. */
56 [SIGMA_FW_100MHZ] = "asix-sigma-100.fw", /* 100MHz, fixed. */
57 [SIGMA_FW_200MHZ] = "asix-sigma-200.fw", /* 200MHz, fixed. */
58 [SIGMA_FW_SYNC] = "asix-sigma-50sync.fw", /* Sync from external pin. */
59 [SIGMA_FW_FREQ] = "asix-sigma-phasor.fw", /* Frequency counter. */
60};
61
62#define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
63
64static int sigma_ftdi_open(const struct sr_dev_inst *sdi)
65{
66 struct dev_context *devc;
67 int vid, pid;
68 const char *serno;
69 int ret;
70
71 devc = sdi->priv;
72 if (!devc)
73 return SR_ERR_ARG;
74
75 if (devc->ftdi.is_open)
76 return SR_OK;
77
78 vid = devc->id.vid;
79 pid = devc->id.pid;
80 serno = sdi->serial_num;
81 if (!vid || !pid || !serno || !*serno)
82 return SR_ERR_ARG;
83
84 ret = ftdi_init(&devc->ftdi.ctx);
85 if (ret < 0) {
86 sr_err("Cannot initialize FTDI context (%d): %s.",
87 ret, ftdi_get_error_string(&devc->ftdi.ctx));
88 return SR_ERR_IO;
89 }
90 ret = ftdi_usb_open_desc_index(&devc->ftdi.ctx,
91 vid, pid, NULL, serno, 0);
92 if (ret < 0) {
93 sr_err("Cannot open device (%d): %s.",
94 ret, ftdi_get_error_string(&devc->ftdi.ctx));
95 return SR_ERR_IO;
96 }
97 devc->ftdi.is_open = TRUE;
98
99 return SR_OK;
100}
101
102static int sigma_ftdi_close(struct dev_context *devc)
103{
104 int ret;
105
106 ret = ftdi_usb_close(&devc->ftdi.ctx);
107 devc->ftdi.is_open = FALSE;
108 devc->ftdi.must_close = FALSE;
109 ftdi_deinit(&devc->ftdi.ctx);
110
111 return ret == 0 ? SR_OK : SR_ERR_IO;
112}
113
114SR_PRIV int sigma_check_open(const struct sr_dev_inst *sdi)
115{
116 struct dev_context *devc;
117 int ret;
118
119 if (!sdi)
120 return SR_ERR_ARG;
121 devc = sdi->priv;
122 if (!devc)
123 return SR_ERR_ARG;
124
125 if (devc->ftdi.is_open)
126 return SR_OK;
127
128 ret = sigma_ftdi_open(sdi);
129 if (ret != SR_OK)
130 return ret;
131 devc->ftdi.must_close = TRUE;
132
133 return ret;
134}
135
136SR_PRIV int sigma_check_close(struct dev_context *devc)
137{
138 int ret;
139
140 if (!devc)
141 return SR_ERR_ARG;
142
143 if (devc->ftdi.must_close) {
144 ret = sigma_ftdi_close(devc);
145 if (ret != SR_OK)
146 return ret;
147 devc->ftdi.must_close = FALSE;
148 }
149
150 return SR_OK;
151}
152
153SR_PRIV int sigma_force_open(const struct sr_dev_inst *sdi)
154{
155 struct dev_context *devc;
156 int ret;
157
158 if (!sdi)
159 return SR_ERR_ARG;
160 devc = sdi->priv;
161 if (!devc)
162 return SR_ERR_ARG;
163
164 ret = sigma_ftdi_open(sdi);
165 if (ret != SR_OK)
166 return ret;
167 devc->ftdi.must_close = FALSE;
168
169 return SR_OK;
170}
171
172SR_PRIV int sigma_force_close(struct dev_context *devc)
173{
174 return sigma_ftdi_close(devc);
175}
176
177/*
178 * BEWARE! Error propagation is important, as are kinds of return values.
179 *
180 * - Raw USB tranport communicates the number of sent or received bytes,
181 * or negative error codes in the external library's(!) range of codes.
182 * - Internal routines at the "sigrok driver level" communicate success
183 * or failure in terms of SR_OK et al error codes.
184 * - Main loop style receive callbacks communicate booleans which arrange
185 * for repeated calls to drive progress during acquisition.
186 *
187 * Careful consideration by maintainers is essential, because all of the
188 * above kinds of values are assignment compatbile from the compiler's
189 * point of view. Implementation errors will go unnoticed at build time.
190 */
191
192static int sigma_read_raw(struct dev_context *devc, void *buf, size_t size)
193{
194 int ret;
195
196 ret = ftdi_read_data(&devc->ftdi.ctx, (unsigned char *)buf, size);
197 if (ret < 0) {
198 sr_err("USB data read failed: %s",
199 ftdi_get_error_string(&devc->ftdi.ctx));
200 }
201
202 return ret;
203}
204
205static int sigma_write_raw(struct dev_context *devc, const void *buf, size_t size)
206{
207 int ret;
208
209 ret = ftdi_write_data(&devc->ftdi.ctx, buf, size);
210 if (ret < 0) {
211 sr_err("USB data write failed: %s",
212 ftdi_get_error_string(&devc->ftdi.ctx));
213 } else if ((size_t)ret != size) {
214 sr_err("USB data write length mismatch.");
215 }
216
217 return ret;
218}
219
220static int sigma_read_sr(struct dev_context *devc, void *buf, size_t size)
221{
222 int ret;
223
224 ret = sigma_read_raw(devc, buf, size);
225 if (ret < 0 || (size_t)ret != size)
226 return SR_ERR_IO;
227
228 return SR_OK;
229}
230
231static int sigma_write_sr(struct dev_context *devc, const void *buf, size_t size)
232{
233 int ret;
234
235 ret = sigma_write_raw(devc, buf, size);
236 if (ret < 0 || (size_t)ret != size)
237 return SR_ERR_IO;
238
239 return SR_OK;
240}
241
242/*
243 * Implementor's note: The local write buffer's size shall suffice for
244 * any know FPGA register transaction that is involved in the supported
245 * feature set of this sigrok device driver. If the length check trips,
246 * that's a programmer's error and needs adjustment in the complete call
247 * stack of the respective code path.
248 */
249SR_PRIV int sigma_write_register(struct dev_context *devc,
250 uint8_t reg, uint8_t *data, size_t len)
251{
252 uint8_t buf[80], *wrptr;
253 size_t idx;
254
255 if (2 + 2 * len > sizeof(buf)) {
256 sr_err("Short write buffer for %zu bytes to reg %u.", len, reg);
257 return SR_ERR_BUG;
258 }
259
260 wrptr = buf;
261 write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
262 write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
263 for (idx = 0; idx < len; idx++) {
264 write_u8_inc(&wrptr, REG_DATA_LOW | (data[idx] & 0xf));
265 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data[idx] >> 4));
266 }
267
268 return sigma_write_sr(devc, buf, wrptr - buf);
269}
270
271SR_PRIV int sigma_set_register(struct dev_context *devc,
272 uint8_t reg, uint8_t value)
273{
274 return sigma_write_register(devc, reg, &value, sizeof(value));
275}
276
277static int sigma_read_register(struct dev_context *devc,
278 uint8_t reg, uint8_t *data, size_t len)
279{
280 uint8_t buf[3], *wrptr;
281 int ret;
282
283 wrptr = buf;
284 write_u8_inc(&wrptr, REG_ADDR_LOW | (reg & 0xf));
285 write_u8_inc(&wrptr, REG_ADDR_HIGH | (reg >> 4));
286 write_u8_inc(&wrptr, REG_READ_ADDR);
287 ret = sigma_write_sr(devc, buf, wrptr - buf);
288 if (ret != SR_OK)
289 return ret;
290
291 return sigma_read_sr(devc, data, len);
292}
293
294static int sigma_read_pos(struct dev_context *devc,
295 uint32_t *stoppos, uint32_t *triggerpos, uint8_t *mode)
296{
297 /*
298 * Read 7 registers starting at trigger position LSB.
299 * Which yields two 24bit counter values, and mode flags.
300 */
301 const uint8_t buf[] = {
302 /* Setup first register address. */
303 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
304 /* Retrieve trigger position. */
305 REG_READ_ADDR | REG_ADDR_INC,
306 REG_READ_ADDR | REG_ADDR_INC,
307 REG_READ_ADDR | REG_ADDR_INC,
308 /* Retrieve stop position. */
309 REG_READ_ADDR | REG_ADDR_INC,
310 REG_READ_ADDR | REG_ADDR_INC,
311 REG_READ_ADDR | REG_ADDR_INC,
312 /* Retrieve mode register. */
313 REG_READ_ADDR | REG_ADDR_INC,
314 }, *rdptr;
315 uint8_t result[7];
316 uint32_t v32;
317 uint8_t v8;
318 int ret;
319
320 ret = sigma_write_sr(devc, buf, sizeof(buf));
321 if (ret != SR_OK)
322 return ret;
323
324 ret = sigma_read_sr(devc, result, sizeof(result));
325 if (ret != SR_OK)
326 return ret;
327
328 rdptr = &result[0];
329 v32 = read_u24le_inc(&rdptr);
330 if (triggerpos)
331 *triggerpos = v32;
332 v32 = read_u24le_inc(&rdptr);
333 if (stoppos)
334 *stoppos = v32;
335 v8 = read_u8_inc(&rdptr);
336 if (mode)
337 *mode = v8;
338
339 /*
340 * These positions consist of "the memory row" in the MSB fields,
341 * and "an event index" within the row in the LSB fields. Part
342 * of the memory row's content is sample data, another part is
343 * timestamps.
344 *
345 * The retrieved register values point to after the captured
346 * position. So they need to get decremented, and adjusted to
347 * cater for the timestamps when the decrement carries over to
348 * a different memory row.
349 */
350 if (stoppos && (--*stoppos & ROW_MASK) == ROW_MASK)
351 *stoppos -= CLUSTERS_PER_ROW;
352 if (triggerpos && (--*triggerpos & ROW_MASK) == ROW_MASK)
353 *triggerpos -= CLUSTERS_PER_ROW;
354
355 return SR_OK;
356}
357
358static int sigma_read_dram(struct dev_context *devc,
359 uint16_t startchunk, size_t numchunks, uint8_t *data)
360{
361 uint8_t buf[128], *wrptr;
362 size_t chunk;
363 int sel, ret;
364 gboolean is_last;
365
366 if (2 + 3 * numchunks > ARRAY_SIZE(buf)) {
367 sr_err("Short write buffer for %zu DRAM row reads.", numchunks);
368 return SR_ERR_BUG;
369 }
370
371 /* Communicate DRAM start address (memory row, aka samples line). */
372 wrptr = buf;
373 write_u8_inc(&wrptr, startchunk >> 8);
374 write_u8_inc(&wrptr, startchunk & 0xff);
375 ret = sigma_write_register(devc, WRITE_MEMROW, buf, wrptr - buf);
376 if (ret != SR_OK)
377 return ret;
378
379 /*
380 * Access DRAM content. Fetch from DRAM to FPGA's internal RAM,
381 * then transfer via USB. Interleave the FPGA's DRAM access and
382 * USB transfer, use alternating buffers (0/1) in the process.
383 */
384 wrptr = buf;
385 write_u8_inc(&wrptr, REG_DRAM_BLOCK);
386 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
387 for (chunk = 0; chunk < numchunks; chunk++) {
388 sel = chunk % 2;
389 is_last = chunk == numchunks - 1;
390 if (!is_last)
391 write_u8_inc(&wrptr, REG_DRAM_BLOCK | REG_DRAM_SEL_BOOL(!sel));
392 write_u8_inc(&wrptr, REG_DRAM_BLOCK_DATA | REG_DRAM_SEL_BOOL(sel));
393 if (!is_last)
394 write_u8_inc(&wrptr, REG_DRAM_WAIT_ACK);
395 }
396 ret = sigma_write_sr(devc, buf, wrptr - buf);
397 if (ret != SR_OK)
398 return ret;
399
400 return sigma_read_sr(devc, data, numchunks * ROW_LENGTH_BYTES);
401}
402
403/* Upload trigger look-up tables to Sigma. */
404SR_PRIV int sigma_write_trigger_lut(struct dev_context *devc,
405 struct triggerlut *lut)
406{
407 int i;
408 uint8_t tmp[2];
409 uint16_t bit;
410 uint8_t buf[6], *wrptr, regval;
411 int ret;
412
413 /* Transpose the table and send to Sigma. */
414 for (i = 0; i < 16; i++) {
415 bit = 1 << i;
416
417 tmp[0] = tmp[1] = 0;
418
419 if (lut->m2d[0] & bit)
420 tmp[0] |= 0x01;
421 if (lut->m2d[1] & bit)
422 tmp[0] |= 0x02;
423 if (lut->m2d[2] & bit)
424 tmp[0] |= 0x04;
425 if (lut->m2d[3] & bit)
426 tmp[0] |= 0x08;
427
428 if (lut->m3 & bit)
429 tmp[0] |= 0x10;
430 if (lut->m3s & bit)
431 tmp[0] |= 0x20;
432 if (lut->m4 & bit)
433 tmp[0] |= 0x40;
434
435 if (lut->m0d[0] & bit)
436 tmp[1] |= 0x01;
437 if (lut->m0d[1] & bit)
438 tmp[1] |= 0x02;
439 if (lut->m0d[2] & bit)
440 tmp[1] |= 0x04;
441 if (lut->m0d[3] & bit)
442 tmp[1] |= 0x08;
443
444 if (lut->m1d[0] & bit)
445 tmp[1] |= 0x10;
446 if (lut->m1d[1] & bit)
447 tmp[1] |= 0x20;
448 if (lut->m1d[2] & bit)
449 tmp[1] |= 0x40;
450 if (lut->m1d[3] & bit)
451 tmp[1] |= 0x80;
452
453 /*
454 * This logic seems redundant, but separates the value
455 * determination from the wire format, and is useful
456 * during future maintenance and research.
457 */
458 wrptr = buf;
459 write_u8_inc(&wrptr, tmp[0]);
460 write_u8_inc(&wrptr, tmp[1]);
461 ret = sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
462 if (ret != SR_OK)
463 return ret;
464 ret = sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x30 | i);
465 if (ret != SR_OK)
466 return ret;
467 }
468
469 /* Send the parameters */
470 wrptr = buf;
471 regval = 0;
472 regval |= lut->params.selc << 6;
473 regval |= lut->params.selpresc << 0;
474 write_u8_inc(&wrptr, regval);
475 regval = 0;
476 regval |= lut->params.selinc << 6;
477 regval |= lut->params.selres << 4;
478 regval |= lut->params.sela << 2;
479 regval |= lut->params.selb << 0;
480 write_u8_inc(&wrptr, regval);
481 write_u16le_inc(&wrptr, lut->params.cmpb);
482 write_u16le_inc(&wrptr, lut->params.cmpa);
483 ret = sigma_write_register(devc, WRITE_TRIGGER_SELECT, buf, wrptr - buf);
484 if (ret != SR_OK)
485 return ret;
486
487 return SR_OK;
488}
489
490/*
491 * See Xilinx UG332 for Spartan-3 FPGA configuration. The SIGMA device
492 * uses FTDI bitbang mode for netlist download in slave serial mode.
493 * (LATER: The OMEGA device's cable contains a more capable FTDI chip
494 * and uses MPSSE mode for bitbang. -- Can we also use FT232H in FT245
495 * compatible bitbang mode? For maximum code re-use and reduced libftdi
496 * dependency? See section 3.5.5 of FT232H: D0 clk, D1 data (out), D2
497 * data (in), D3 select, D4-7 GPIOL. See section 3.5.7 for MCU FIFO.)
498 *
499 * 750kbps rate (four times the speed of sigmalogan) works well for
500 * netlist download. All pins except INIT_B are output pins during
501 * configuration download.
502 *
503 * Some pins are inverted as a byproduct of level shifting circuitry.
504 * That's why high CCLK level (from the cable's point of view) is idle
505 * from the FPGA's perspective.
506 *
507 * The vendor's literature discusses a "suicide sequence" which ends
508 * regular FPGA execution and should be sent before entering bitbang
509 * mode and sending configuration data. Set D7 and toggle D2, D3, D4
510 * a few times.
511 */
512#define BB_PIN_CCLK (1 << 0) /* D0, CCLK */
513#define BB_PIN_PROG (1 << 1) /* D1, PROG */
514#define BB_PIN_D2 (1 << 2) /* D2, (part of) SUICIDE */
515#define BB_PIN_D3 (1 << 3) /* D3, (part of) SUICIDE */
516#define BB_PIN_D4 (1 << 4) /* D4, (part of) SUICIDE (unused?) */
517#define BB_PIN_INIT (1 << 5) /* D5, INIT, input pin */
518#define BB_PIN_DIN (1 << 6) /* D6, DIN */
519#define BB_PIN_D7 (1 << 7) /* D7, (part of) SUICIDE */
520
521#define BB_BITRATE (750 * 1000)
522#define BB_PINMASK (0xff & ~BB_PIN_INIT)
523
524/*
525 * Initiate slave serial mode for configuration download. Which is done
526 * by pulsing PROG_B and sensing INIT_B. Make sure CCLK is idle before
527 * initiating the configuration download.
528 *
529 * Run a "suicide sequence" first to terminate the regular FPGA operation
530 * before reconfiguration. The FTDI cable is single channel, and shares
531 * pins which are used for data communication in FIFO mode with pins that
532 * are used for FPGA configuration in bitbang mode. Hardware defaults for
533 * unconfigured hardware, and runtime conditions after FPGA configuration
534 * need to cooperate such that re-configuration of the FPGA can start.
535 */
536static int sigma_fpga_init_bitbang_once(struct dev_context *devc)
537{
538 const uint8_t suicide[] = {
539 BB_PIN_D7 | BB_PIN_D2,
540 BB_PIN_D7 | BB_PIN_D2,
541 BB_PIN_D7 | BB_PIN_D3,
542 BB_PIN_D7 | BB_PIN_D2,
543 BB_PIN_D7 | BB_PIN_D3,
544 BB_PIN_D7 | BB_PIN_D2,
545 BB_PIN_D7 | BB_PIN_D3,
546 BB_PIN_D7 | BB_PIN_D2,
547 };
548 const uint8_t init_array[] = {
549 BB_PIN_CCLK,
550 BB_PIN_CCLK | BB_PIN_PROG,
551 BB_PIN_CCLK | BB_PIN_PROG,
552 BB_PIN_CCLK,
553 BB_PIN_CCLK,
554 BB_PIN_CCLK,
555 BB_PIN_CCLK,
556 BB_PIN_CCLK,
557 BB_PIN_CCLK,
558 BB_PIN_CCLK,
559 };
560 int retries, ret;
561 uint8_t data;
562
563 /* Section 2. part 1), do the FPGA suicide. */
564 ret = SR_OK;
565 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
566 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
567 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
568 ret |= sigma_write_sr(devc, suicide, sizeof(suicide));
569 if (ret != SR_OK)
570 return SR_ERR_IO;
571 g_usleep(10 * 1000);
572
573 /* Section 2. part 2), pulse PROG. */
574 ret = sigma_write_sr(devc, init_array, sizeof(init_array));
575 if (ret != SR_OK)
576 return ret;
577 g_usleep(10 * 1000);
578 ftdi_usb_purge_buffers(&devc->ftdi.ctx);
579
580 /*
581 * Wait until the FPGA asserts INIT_B. Check in a maximum number
582 * of bursts with a given delay between them. Read as many pin
583 * capture results as the combination of FTDI chip and FTID lib
584 * may provide. Cope with absence of pin capture data in a cycle.
585 * This approach shall result in fast reponse in case of success,
586 * low cost of execution during wait, reliable error handling in
587 * the transport layer, and robust response to failure or absence
588 * of result data (hardware inactivity after stimulus).
589 */
590 retries = 10;
591 while (retries--) {
592 do {
593 ret = sigma_read_raw(devc, &data, sizeof(data));
594 if (ret < 0)
595 return SR_ERR_IO;
596 if (ret == sizeof(data) && (data & BB_PIN_INIT))
597 return SR_OK;
598 } while (ret == sizeof(data));
599 if (retries)
600 g_usleep(10 * 1000);
601 }
602
603 return SR_ERR_TIMEOUT;
604}
605
606/*
607 * This is belt and braces. Re-run the bitbang initiation sequence a few
608 * times should first attempts fail. Failure is rare but can happen (was
609 * observed during driver development).
610 */
611static int sigma_fpga_init_bitbang(struct dev_context *devc)
612{
613 size_t retries;
614 int ret;
615
616 retries = 10;
617 while (retries--) {
618 ret = sigma_fpga_init_bitbang_once(devc);
619 if (ret == SR_OK)
620 return ret;
621 if (ret != SR_ERR_TIMEOUT)
622 return ret;
623 }
624 return ret;
625}
626
627/*
628 * Configure the FPGA for logic-analyzer mode.
629 */
630static int sigma_fpga_init_la(struct dev_context *devc)
631{
632 uint8_t buf[16], *wrptr;
633 uint8_t data_55, data_aa, mode;
634 uint8_t result[3];
635 const uint8_t *rdptr;
636 int ret;
637
638 wrptr = buf;
639
640 /* Read ID register. */
641 write_u8_inc(&wrptr, REG_ADDR_LOW | (READ_ID & 0xf));
642 write_u8_inc(&wrptr, REG_ADDR_HIGH | (READ_ID >> 4));
643 write_u8_inc(&wrptr, REG_READ_ADDR);
644
645 /* Write 0x55 to scratch register, read back. */
646 data_55 = 0x55;
647 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
648 write_u8_inc(&wrptr, REG_DATA_LOW | (data_55 & 0xf));
649 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_55 >> 4));
650 write_u8_inc(&wrptr, REG_READ_ADDR);
651
652 /* Write 0xaa to scratch register, read back. */
653 data_aa = 0xaa;
654 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_TEST & 0xf));
655 write_u8_inc(&wrptr, REG_DATA_LOW | (data_aa & 0xf));
656 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (data_aa >> 4));
657 write_u8_inc(&wrptr, REG_READ_ADDR);
658
659 /* Initiate SDRAM initialization in mode register. */
660 mode = WMR_SDRAMINIT;
661 write_u8_inc(&wrptr, REG_ADDR_LOW | (WRITE_MODE & 0xf));
662 write_u8_inc(&wrptr, REG_DATA_LOW | (mode & 0xf));
663 write_u8_inc(&wrptr, REG_DATA_HIGH_WRITE | (mode >> 4));
664
665 /*
666 * Send the command sequence which contains 3 READ requests.
667 * Expect to see the corresponding 3 response bytes.
668 */
669 ret = sigma_write_sr(devc, buf, wrptr - buf);
670 if (ret != SR_OK) {
671 sr_err("Could not request LA start response.");
672 return ret;
673 }
674 ret = sigma_read_sr(devc, result, ARRAY_SIZE(result));
675 if (ret != SR_OK) {
676 sr_err("Could not receive LA start response.");
677 return SR_ERR_IO;
678 }
679 rdptr = result;
680 if (read_u8_inc(&rdptr) != 0xa6) {
681 sr_err("Unexpected ID response.");
682 return SR_ERR_DATA;
683 }
684 if (read_u8_inc(&rdptr) != data_55) {
685 sr_err("Unexpected scratch read-back (55).");
686 return SR_ERR_DATA;
687 }
688 if (read_u8_inc(&rdptr) != data_aa) {
689 sr_err("Unexpected scratch read-back (aa).");
690 return SR_ERR_DATA;
691 }
692
693 return SR_OK;
694}
695
696/*
697 * Read the firmware from a file and transform it into a series of bitbang
698 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
699 * by the caller of this function.
700 */
701static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
702 uint8_t **bb_cmd, gsize *bb_cmd_size)
703{
704 uint8_t *firmware;
705 size_t file_size;
706 uint8_t *p;
707 size_t l;
708 uint32_t imm;
709 size_t bb_size;
710 uint8_t *bb_stream, *bbs, byte, mask, v;
711
712 /* Retrieve the on-disk firmware file content. */
713 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
714 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
715 if (!firmware)
716 return SR_ERR_IO;
717
718 /* Unscramble the file content (XOR with "random" sequence). */
719 p = firmware;
720 l = file_size;
721 imm = 0x3f6df2ab;
722 while (l--) {
723 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
724 *p++ ^= imm & 0xff;
725 }
726
727 /*
728 * Generate a sequence of bitbang samples. With two samples per
729 * FPGA configuration bit, providing the level for the DIN signal
730 * as well as two edges for CCLK. See Xilinx UG332 for details
731 * ("slave serial" mode).
732 *
733 * Note that CCLK is inverted in hardware. That's why the
734 * respective bit is first set and then cleared in the bitbang
735 * sample sets. So that the DIN level will be stable when the
736 * data gets sampled at the rising CCLK edge, and the signals'
737 * setup time constraint will be met.
738 *
739 * The caller will put the FPGA into download mode, will send
740 * the bitbang samples, and release the allocated memory.
741 */
742 bb_size = file_size * 8 * 2;
743 bb_stream = g_try_malloc(bb_size);
744 if (!bb_stream) {
745 sr_err("Memory allocation failed during firmware upload.");
746 g_free(firmware);
747 return SR_ERR_MALLOC;
748 }
749 bbs = bb_stream;
750 p = firmware;
751 l = file_size;
752 while (l--) {
753 byte = *p++;
754 mask = 0x80;
755 while (mask) {
756 v = (byte & mask) ? BB_PIN_DIN : 0;
757 mask >>= 1;
758 *bbs++ = v | BB_PIN_CCLK;
759 *bbs++ = v;
760 }
761 }
762 g_free(firmware);
763
764 /* The transformation completed successfully, return the result. */
765 *bb_cmd = bb_stream;
766 *bb_cmd_size = bb_size;
767
768 return SR_OK;
769}
770
771static int upload_firmware(struct sr_context *ctx, struct dev_context *devc,
772 enum sigma_firmware_idx firmware_idx)
773{
774 int ret;
775 uint8_t *buf;
776 uint8_t pins;
777 size_t buf_size;
778 const char *firmware;
779
780 /* Check for valid firmware file selection. */
781 if (firmware_idx >= ARRAY_SIZE(firmware_files))
782 return SR_ERR_ARG;
783 firmware = firmware_files[firmware_idx];
784 if (!firmware || !*firmware)
785 return SR_ERR_ARG;
786
787 /* Avoid downloading the same firmware multiple times. */
788 if (devc->firmware_idx == firmware_idx) {
789 sr_info("Not uploading firmware file '%s' again.", firmware);
790 return SR_OK;
791 }
792
793 devc->state.state = SIGMA_CONFIG;
794
795 /* Set the cable to bitbang mode. */
796 ret = ftdi_set_bitmode(&devc->ftdi.ctx, BB_PINMASK, BITMODE_BITBANG);
797 if (ret < 0) {
798 sr_err("Could not setup cable mode for upload: %s",
799 ftdi_get_error_string(&devc->ftdi.ctx));
800 return SR_ERR;
801 }
802 ret = ftdi_set_baudrate(&devc->ftdi.ctx, BB_BITRATE);
803 if (ret < 0) {
804 sr_err("Could not setup bitrate for upload: %s",
805 ftdi_get_error_string(&devc->ftdi.ctx));
806 return SR_ERR;
807 }
808
809 /* Initiate FPGA configuration mode. */
810 ret = sigma_fpga_init_bitbang(devc);
811 if (ret) {
812 sr_err("Could not initiate firmware upload to hardware");
813 return ret;
814 }
815
816 /* Prepare wire format of the firmware image. */
817 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
818 if (ret != SR_OK) {
819 sr_err("Could not prepare file %s for upload.", firmware);
820 return ret;
821 }
822
823 /* Write the FPGA netlist to the cable. */
824 sr_info("Uploading firmware file '%s'.", firmware);
825 ret = sigma_write_sr(devc, buf, buf_size);
826 g_free(buf);
827 if (ret != SR_OK) {
828 sr_err("Could not upload firmware file '%s'.", firmware);
829 return ret;
830 }
831
832 /* Leave bitbang mode and discard pending input data. */
833 ret = ftdi_set_bitmode(&devc->ftdi.ctx, 0, BITMODE_RESET);
834 if (ret < 0) {
835 sr_err("Could not setup cable mode after upload: %s",
836 ftdi_get_error_string(&devc->ftdi.ctx));
837 return SR_ERR;
838 }
839 ftdi_usb_purge_buffers(&devc->ftdi.ctx);
840 while (sigma_read_raw(devc, &pins, sizeof(pins)) > 0)
841 ;
842
843 /* Initialize the FPGA for logic-analyzer mode. */
844 ret = sigma_fpga_init_la(devc);
845 if (ret != SR_OK) {
846 sr_err("Hardware response after firmware upload failed.");
847 return ret;
848 }
849
850 /* Keep track of successful firmware download completion. */
851 devc->state.state = SIGMA_IDLE;
852 devc->firmware_idx = firmware_idx;
853 sr_info("Firmware uploaded.");
854
855 return SR_OK;
856}
857
858/*
859 * The driver supports user specified time or sample count limits. The
860 * device's hardware supports neither, and hardware compression prevents
861 * reliable detection of "fill levels" (currently reached sample counts)
862 * from register values during acquisition. That's why the driver needs
863 * to apply some heuristics:
864 *
865 * - The (optional) sample count limit and the (normalized) samplerate
866 * get mapped to an estimated duration for these samples' acquisition.
867 * - The (optional) time limit gets checked as well. The lesser of the
868 * two limits will terminate the data acquisition phase. The exact
869 * sample count limit gets enforced in session feed submission paths.
870 * - Some slack needs to be given to account for hardware pipelines as
871 * well as late storage of last chunks after compression thresholds
872 * are tripped. The resulting data set will span at least the caller
873 * specified period of time, which shall be perfectly acceptable.
874 *
875 * With RLE compression active, up to 64K sample periods can pass before
876 * a cluster accumulates. Which translates to 327ms at 200kHz. Add two
877 * times that period for good measure, one is not enough to flush the
878 * hardware pipeline (observation from an earlier experiment).
879 */
880SR_PRIV int sigma_set_acquire_timeout(struct dev_context *devc)
881{
882 int ret;
883 GVariant *data;
884 uint64_t user_count, user_msecs;
885 uint64_t worst_cluster_time_ms;
886 uint64_t count_msecs, acquire_msecs;
887
888 sr_sw_limits_init(&devc->acq_limits);
889
890 /* Get sample count limit, convert to msecs. */
891 ret = sr_sw_limits_config_get(&devc->cfg_limits,
892 SR_CONF_LIMIT_SAMPLES, &data);
893 if (ret != SR_OK)
894 return ret;
895 user_count = g_variant_get_uint64(data);
896 g_variant_unref(data);
897 count_msecs = 0;
898 if (user_count)
899 count_msecs = 1000 * user_count / devc->samplerate + 1;
900
901 /* Get time limit, which is in msecs. */
902 ret = sr_sw_limits_config_get(&devc->cfg_limits,
903 SR_CONF_LIMIT_MSEC, &data);
904 if (ret != SR_OK)
905 return ret;
906 user_msecs = g_variant_get_uint64(data);
907 g_variant_unref(data);
908
909 /* Get the lesser of them, with both being optional. */
910 acquire_msecs = ~0ull;
911 if (user_count && count_msecs < acquire_msecs)
912 acquire_msecs = count_msecs;
913 if (user_msecs && user_msecs < acquire_msecs)
914 acquire_msecs = user_msecs;
915 if (acquire_msecs == ~0ull)
916 return SR_OK;
917
918 /* Add some slack, and use that timeout for acquisition. */
919 worst_cluster_time_ms = 1000 * 65536 / devc->samplerate;
920 acquire_msecs += 2 * worst_cluster_time_ms;
921 data = g_variant_new_uint64(acquire_msecs);
922 ret = sr_sw_limits_config_set(&devc->acq_limits,
923 SR_CONF_LIMIT_MSEC, data);
924 g_variant_unref(data);
925 if (ret != SR_OK)
926 return ret;
927
928 sr_sw_limits_acquisition_start(&devc->acq_limits);
929 return SR_OK;
930}
931
932/*
933 * Check whether a caller specified samplerate matches the device's
934 * hardware constraints (can be used for acquisition). Optionally yield
935 * a value that approximates the original spec.
936 *
937 * This routine assumes that input specs are in the 200kHz to 200MHz
938 * range of supported rates, and callers typically want to normalize a
939 * given value to the hardware capabilities. Values in the 50MHz range
940 * get rounded up by default, to avoid a more expensive check for the
941 * closest match, while higher sampling rate is always desirable during
942 * measurement. Input specs which exactly match hardware capabilities
943 * remain unaffected. Because 100/200MHz rates also limit the number of
944 * available channels, they are not suggested by this routine, instead
945 * callers need to pick them consciously.
946 */
947SR_PRIV int sigma_normalize_samplerate(uint64_t want_rate, uint64_t *have_rate)
948{
949 uint64_t div, rate;
950
951 /* Accept exact matches for 100/200MHz. */
952 if (want_rate == SR_MHZ(200) || want_rate == SR_MHZ(100)) {
953 if (have_rate)
954 *have_rate = want_rate;
955 return SR_OK;
956 }
957
958 /* Accept 200kHz to 50MHz range, and map to near value. */
959 if (want_rate >= SR_KHZ(200) && want_rate <= SR_MHZ(50)) {
960 div = SR_MHZ(50) / want_rate;
961 rate = SR_MHZ(50) / div;
962 if (have_rate)
963 *have_rate = rate;
964 return SR_OK;
965 }
966
967 return SR_ERR_ARG;
968}
969
970SR_PRIV uint64_t sigma_get_samplerate(const struct sr_dev_inst *sdi)
971{
972 /* TODO Retrieve value from hardware. */
973 (void)sdi;
974 return samplerates[0];
975}
976
977SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi)
978{
979 struct dev_context *devc;
980 struct drv_context *drvc;
981 uint64_t samplerate;
982 int ret;
983 int num_channels;
984
985 devc = sdi->priv;
986 drvc = sdi->driver->context;
987
988 /* Accept any caller specified rate which the hardware supports. */
989 ret = sigma_normalize_samplerate(devc->samplerate, &samplerate);
990 if (ret != SR_OK)
991 return ret;
992
993 /*
994 * Depending on the samplerates of 200/100/50- MHz, specific
995 * firmware is required and higher rates might limit the set
996 * of available channels.
997 */
998 num_channels = devc->num_channels;
999 if (samplerate <= SR_MHZ(50)) {
1000 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_50MHZ);
1001 num_channels = 16;
1002 } else if (samplerate == SR_MHZ(100)) {
1003 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_100MHZ);
1004 num_channels = 8;
1005 } else if (samplerate == SR_MHZ(200)) {
1006 ret = upload_firmware(drvc->sr_ctx, devc, SIGMA_FW_200MHZ);
1007 num_channels = 4;
1008 }
1009
1010 /*
1011 * The samplerate affects the number of available logic channels
1012 * as well as a sample memory layout detail (the number of samples
1013 * which the device will communicate within an "event").
1014 */
1015 if (ret == SR_OK) {
1016 devc->num_channels = num_channels;
1017 devc->samples_per_event = 16 / devc->num_channels;
1018 }
1019
1020 return ret;
1021}
1022
1023/*
1024 * Arrange for a session feed submit buffer. A queue where a number of
1025 * samples gets accumulated to reduce the number of send calls. Which
1026 * also enforces an optional sample count limit for data acquisition.
1027 *
1028 * The buffer holds up to CHUNK_SIZE bytes. The unit size is fixed (the
1029 * driver provides a fixed channel layout regardless of samplerate).
1030 */
1031
1032#define CHUNK_SIZE (4 * 1024 * 1024)
1033
1034struct submit_buffer {
1035 size_t unit_size;
1036 size_t max_samples, curr_samples;
1037 uint8_t *sample_data;
1038 uint8_t *write_pointer;
1039 struct sr_dev_inst *sdi;
1040 struct sr_datafeed_packet packet;
1041 struct sr_datafeed_logic logic;
1042};
1043
1044static int alloc_submit_buffer(struct sr_dev_inst *sdi)
1045{
1046 struct dev_context *devc;
1047 struct submit_buffer *buffer;
1048 size_t size;
1049
1050 devc = sdi->priv;
1051
1052 buffer = g_malloc0(sizeof(*buffer));
1053 devc->buffer = buffer;
1054
1055 buffer->unit_size = sizeof(uint16_t);
1056 size = CHUNK_SIZE;
1057 size /= buffer->unit_size;
1058 buffer->max_samples = size;
1059 size *= buffer->unit_size;
1060 buffer->sample_data = g_try_malloc0(size);
1061 if (!buffer->sample_data)
1062 return SR_ERR_MALLOC;
1063 buffer->write_pointer = buffer->sample_data;
1064 sr_sw_limits_init(&devc->feed_limits);
1065
1066 buffer->sdi = sdi;
1067 memset(&buffer->logic, 0, sizeof(buffer->logic));
1068 buffer->logic.unitsize = buffer->unit_size;
1069 buffer->logic.data = buffer->sample_data;
1070 memset(&buffer->packet, 0, sizeof(buffer->packet));
1071 buffer->packet.type = SR_DF_LOGIC;
1072 buffer->packet.payload = &buffer->logic;
1073
1074 return SR_OK;
1075}
1076
1077static int setup_submit_limit(struct dev_context *devc)
1078{
1079 struct sr_sw_limits *limits;
1080 int ret;
1081 GVariant *data;
1082 uint64_t total;
1083
1084 limits = &devc->feed_limits;
1085
1086 ret = sr_sw_limits_config_get(&devc->cfg_limits,
1087 SR_CONF_LIMIT_SAMPLES, &data);
1088 if (ret != SR_OK)
1089 return ret;
1090 total = g_variant_get_uint64(data);
1091 g_variant_unref(data);
1092
1093 sr_sw_limits_init(limits);
1094 if (total) {
1095 data = g_variant_new_uint64(total);
1096 ret = sr_sw_limits_config_set(limits,
1097 SR_CONF_LIMIT_SAMPLES, data);
1098 g_variant_unref(data);
1099 if (ret != SR_OK)
1100 return ret;
1101 }
1102
1103 sr_sw_limits_acquisition_start(limits);
1104
1105 return SR_OK;
1106}
1107
1108static void free_submit_buffer(struct dev_context *devc)
1109{
1110 struct submit_buffer *buffer;
1111
1112 if (!devc)
1113 return;
1114
1115 buffer = devc->buffer;
1116 if (!buffer)
1117 return;
1118 devc->buffer = NULL;
1119
1120 g_free(buffer->sample_data);
1121 g_free(buffer);
1122}
1123
1124static int flush_submit_buffer(struct dev_context *devc)
1125{
1126 struct submit_buffer *buffer;
1127 int ret;
1128
1129 buffer = devc->buffer;
1130
1131 /* Is queued sample data available? */
1132 if (!buffer->curr_samples)
1133 return SR_OK;
1134
1135 /* Submit to the session feed. */
1136 buffer->logic.length = buffer->curr_samples * buffer->unit_size;
1137 ret = sr_session_send(buffer->sdi, &buffer->packet);
1138 if (ret != SR_OK)
1139 return ret;
1140
1141 /* Rewind queue position. */
1142 buffer->curr_samples = 0;
1143 buffer->write_pointer = buffer->sample_data;
1144
1145 return SR_OK;
1146}
1147
1148static int addto_submit_buffer(struct dev_context *devc,
1149 uint16_t sample, size_t count)
1150{
1151 struct submit_buffer *buffer;
1152 struct sr_sw_limits *limits;
1153 int ret;
1154
1155 buffer = devc->buffer;
1156 limits = &devc->feed_limits;
1157 if (sr_sw_limits_check(limits))
1158 count = 0;
1159
1160 /*
1161 * Individually accumulate and check each sample, such that
1162 * accumulation between flushes won't exceed local storage, and
1163 * enforcement of user specified limits is exact.
1164 */
1165 while (count--) {
1166 write_u16le_inc(&buffer->write_pointer, sample);
1167 buffer->curr_samples++;
1168 if (buffer->curr_samples == buffer->max_samples) {
1169 ret = flush_submit_buffer(devc);
1170 if (ret != SR_OK)
1171 return ret;
1172 }
1173 sr_sw_limits_update_samples_read(limits, 1);
1174 if (sr_sw_limits_check(limits))
1175 break;
1176 }
1177
1178 return SR_OK;
1179}
1180
1181/*
1182 * In 100 and 200 MHz mode, only a single pin rising/falling can be
1183 * set as trigger. In other modes, two rising/falling triggers can be set,
1184 * in addition to value/mask trigger for any number of channels.
1185 *
1186 * The Sigma supports complex triggers using boolean expressions, but this
1187 * has not been implemented yet.
1188 */
1189SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
1190{
1191 struct dev_context *devc;
1192 struct sr_trigger *trigger;
1193 struct sr_trigger_stage *stage;
1194 struct sr_trigger_match *match;
1195 const GSList *l, *m;
1196 int channelbit, trigger_set;
1197
1198 devc = sdi->priv;
1199 memset(&devc->trigger, 0, sizeof(devc->trigger));
1200 trigger = sr_session_trigger_get(sdi->session);
1201 if (!trigger)
1202 return SR_OK;
1203
1204 trigger_set = 0;
1205 for (l = trigger->stages; l; l = l->next) {
1206 stage = l->data;
1207 for (m = stage->matches; m; m = m->next) {
1208 match = m->data;
1209 /* Ignore disabled channels with a trigger. */
1210 if (!match->channel->enabled)
1211 continue;
1212 channelbit = 1 << match->channel->index;
1213 if (devc->samplerate >= SR_MHZ(100)) {
1214 /* Fast trigger support. */
1215 if (trigger_set) {
1216 sr_err("100/200MHz modes limited to single trigger pin.");
1217 return SR_ERR;
1218 }
1219 if (match->match == SR_TRIGGER_FALLING) {
1220 devc->trigger.fallingmask |= channelbit;
1221 } else if (match->match == SR_TRIGGER_RISING) {
1222 devc->trigger.risingmask |= channelbit;
1223 } else {
1224 sr_err("100/200MHz modes limited to edge trigger.");
1225 return SR_ERR;
1226 }
1227
1228 trigger_set++;
1229 } else {
1230 /* Simple trigger support (event). */
1231 if (match->match == SR_TRIGGER_ONE) {
1232 devc->trigger.simplevalue |= channelbit;
1233 devc->trigger.simplemask |= channelbit;
1234 } else if (match->match == SR_TRIGGER_ZERO) {
1235 devc->trigger.simplevalue &= ~channelbit;
1236 devc->trigger.simplemask |= channelbit;
1237 } else if (match->match == SR_TRIGGER_FALLING) {
1238 devc->trigger.fallingmask |= channelbit;
1239 trigger_set++;
1240 } else if (match->match == SR_TRIGGER_RISING) {
1241 devc->trigger.risingmask |= channelbit;
1242 trigger_set++;
1243 }
1244
1245 /*
1246 * Actually, Sigma supports 2 rising/falling triggers,
1247 * but they are ORed and the current trigger syntax
1248 * does not permit ORed triggers.
1249 */
1250 if (trigger_set > 1) {
1251 sr_err("Limited to 1 edge trigger.");
1252 return SR_ERR;
1253 }
1254 }
1255 }
1256 }
1257
1258 return SR_OK;
1259}
1260
1261/* Software trigger to determine exact trigger position. */
1262static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
1263 struct sigma_trigger *t)
1264{
1265 const uint8_t *rdptr;
1266 int i;
1267 uint16_t sample;
1268
1269 rdptr = samples;
1270 sample = 0;
1271 for (i = 0; i < 8; i++) {
1272 if (i > 0)
1273 last_sample = sample;
1274 sample = read_u16le_inc(&rdptr);
1275
1276 /* Simple triggers. */
1277 if ((sample & t->simplemask) != t->simplevalue)
1278 continue;
1279
1280 /* Rising edge. */
1281 if (((last_sample & t->risingmask) != 0) ||
1282 ((sample & t->risingmask) != t->risingmask))
1283 continue;
1284
1285 /* Falling edge. */
1286 if ((last_sample & t->fallingmask) != t->fallingmask ||
1287 (sample & t->fallingmask) != 0)
1288 continue;
1289
1290 break;
1291 }
1292
1293 /* If we did not match, return original trigger pos. */
1294 return i & 0x7;
1295}
1296
1297static gboolean sample_matches_trigger(struct dev_context *devc, uint16_t sample)
1298{
1299 /* TODO
1300 * Check whether the combination of this very sample and the
1301 * previous state match the configured trigger condition. This
1302 * improves the resolution of the trigger marker's position.
1303 * The hardware provided position is coarse, and may point to
1304 * a position before the actual match.
1305 *
1306 * See the previous get_trigger_offset() implementation. This
1307 * code needs to get re-used here.
1308 */
1309 (void)devc;
1310 (void)sample;
1311 (void)get_trigger_offset;
1312
1313 return FALSE;
1314}
1315
1316static int check_and_submit_sample(struct dev_context *devc,
1317 uint16_t sample, size_t count, gboolean check_trigger)
1318{
1319 gboolean triggered;
1320 int ret;
1321
1322 triggered = check_trigger && sample_matches_trigger(devc, sample);
1323 if (triggered) {
1324 ret = flush_submit_buffer(devc);
1325 if (ret != SR_OK)
1326 return ret;
1327 ret = std_session_send_df_trigger(devc->buffer->sdi);
1328 if (ret != SR_OK)
1329 return ret;
1330 }
1331
1332 ret = addto_submit_buffer(devc, sample, count);
1333 if (ret != SR_OK)
1334 return ret;
1335
1336 return SR_OK;
1337}
1338
1339/*
1340 * Return the timestamp of "DRAM cluster".
1341 */
1342static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
1343{
1344 return read_u16le((const uint8_t *)&cluster->timestamp);
1345}
1346
1347/*
1348 * Return one 16bit data entity of a DRAM cluster at the specified index.
1349 */
1350static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
1351{
1352 return read_u16le((const uint8_t *)&cl->samples[idx]);
1353}
1354
1355/*
1356 * Deinterlace sample data that was retrieved at 100MHz samplerate.
1357 * One 16bit item contains two samples of 8bits each. The bits of
1358 * multiple samples are interleaved.
1359 */
1360static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
1361{
1362 uint16_t outdata;
1363
1364 indata >>= idx;
1365 outdata = 0;
1366 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
1367 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
1368 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
1369 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
1370 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
1371 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
1372 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
1373 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
1374 return outdata;
1375}
1376
1377/*
1378 * Deinterlace sample data that was retrieved at 200MHz samplerate.
1379 * One 16bit item contains four samples of 4bits each. The bits of
1380 * multiple samples are interleaved.
1381 */
1382static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
1383{
1384 uint16_t outdata;
1385
1386 indata >>= idx;
1387 outdata = 0;
1388 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
1389 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
1390 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
1391 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
1392 return outdata;
1393}
1394
1395static void sigma_decode_dram_cluster(struct dev_context *devc,
1396 struct sigma_dram_cluster *dram_cluster,
1397 size_t events_in_cluster, gboolean triggered)
1398{
1399 struct sigma_state *ss;
1400 uint16_t tsdiff, ts, sample, item16;
1401 unsigned int i;
1402
1403 if (!devc->use_triggers || !ASIX_SIGMA_WITH_TRIGGER)
1404 triggered = FALSE;
1405
1406 /*
1407 * If this cluster is not adjacent to the previously received
1408 * cluster, then send the appropriate number of samples with the
1409 * previous values to the sigrok session. This "decodes RLE".
1410 *
1411 * These samples cannot match the trigger since they just repeat
1412 * the previously submitted data pattern. (This assumption holds
1413 * for simple level and edge triggers. It would not for timed or
1414 * counted conditions, which currently are not supported.)
1415 */
1416 ss = &devc->state;
1417 ts = sigma_dram_cluster_ts(dram_cluster);
1418 tsdiff = ts - ss->lastts;
1419 if (tsdiff > 0) {
1420 size_t count;
1421 sample = ss->lastsample;
1422 count = tsdiff * devc->samples_per_event;
1423 (void)check_and_submit_sample(devc, sample, count, FALSE);
1424 }
1425 ss->lastts = ts + EVENTS_PER_CLUSTER;
1426
1427 /*
1428 * Grab sample data from the current cluster and prepare their
1429 * submission to the session feed. Handle samplerate dependent
1430 * memory layout of sample data. Accumulation of data chunks
1431 * before submission is transparent to this code path, specific
1432 * buffer depth is neither assumed nor required here.
1433 */
1434 sample = 0;
1435 for (i = 0; i < events_in_cluster; i++) {
1436 item16 = sigma_dram_cluster_data(dram_cluster, i);
1437 if (devc->samplerate == SR_MHZ(200)) {
1438 sample = sigma_deinterlace_200mhz_data(item16, 0);
1439 check_and_submit_sample(devc, sample, 1, triggered);
1440 sample = sigma_deinterlace_200mhz_data(item16, 1);
1441 check_and_submit_sample(devc, sample, 1, triggered);
1442 sample = sigma_deinterlace_200mhz_data(item16, 2);
1443 check_and_submit_sample(devc, sample, 1, triggered);
1444 sample = sigma_deinterlace_200mhz_data(item16, 3);
1445 check_and_submit_sample(devc, sample, 1, triggered);
1446 } else if (devc->samplerate == SR_MHZ(100)) {
1447 sample = sigma_deinterlace_100mhz_data(item16, 0);
1448 check_and_submit_sample(devc, sample, 1, triggered);
1449 sample = sigma_deinterlace_100mhz_data(item16, 1);
1450 check_and_submit_sample(devc, sample, 1, triggered);
1451 } else {
1452 sample = item16;
1453 check_and_submit_sample(devc, sample, 1, triggered);
1454 }
1455 }
1456 ss->lastsample = sample;
1457}
1458
1459/*
1460 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
1461 * Each event is 20ns apart, and can contain multiple samples.
1462 *
1463 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
1464 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
1465 * For 50 MHz and below, events contain one sample for each channel,
1466 * spread 20 ns apart.
1467 */
1468static int decode_chunk_ts(struct dev_context *devc,
1469 struct sigma_dram_line *dram_line,
1470 size_t events_in_line, size_t trigger_event)
1471{
1472 struct sigma_dram_cluster *dram_cluster;
1473 unsigned int clusters_in_line;
1474 unsigned int events_in_cluster;
1475 unsigned int i;
1476 uint32_t trigger_cluster;
1477
1478 clusters_in_line = events_in_line;
1479 clusters_in_line += EVENTS_PER_CLUSTER - 1;
1480 clusters_in_line /= EVENTS_PER_CLUSTER;
1481 trigger_cluster = ~0;
1482
1483 /* Check if trigger is in this chunk. */
1484 if (trigger_event < EVENTS_PER_ROW) {
1485 if (devc->samplerate <= SR_MHZ(50)) {
1486 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
1487 trigger_event);
1488 }
1489
1490 /* Find in which cluster the trigger occurred. */
1491 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
1492 }
1493
1494 /* For each full DRAM cluster. */
1495 for (i = 0; i < clusters_in_line; i++) {
1496 dram_cluster = &dram_line->cluster[i];
1497
1498 /* The last cluster might not be full. */
1499 if ((i == clusters_in_line - 1) &&
1500 (events_in_line % EVENTS_PER_CLUSTER)) {
1501 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
1502 } else {
1503 events_in_cluster = EVENTS_PER_CLUSTER;
1504 }
1505
1506 sigma_decode_dram_cluster(devc, dram_cluster,
1507 events_in_cluster, i == trigger_cluster);
1508 }
1509
1510 return SR_OK;
1511}
1512
1513static int download_capture(struct sr_dev_inst *sdi)
1514{
1515 const uint32_t chunks_per_read = 32;
1516
1517 struct dev_context *devc;
1518 struct sigma_dram_line *dram_line;
1519 uint32_t stoppos, triggerpos;
1520 uint8_t modestatus;
1521 uint32_t i;
1522 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
1523 uint32_t dl_first_line, dl_line;
1524 uint32_t dl_events_in_line, trigger_event;
1525 uint32_t trg_line, trg_event;
1526 int ret;
1527
1528 devc = sdi->priv;
1529
1530 sr_info("Downloading sample data.");
1531 devc->state.state = SIGMA_DOWNLOAD;
1532
1533 /*
1534 * Ask the hardware to stop data acquisition. Reception of the
1535 * FORCESTOP request makes the hardware "disable RLE" (store
1536 * clusters to DRAM regardless of whether pin state changes) and
1537 * raise the POSTTRIGGERED flag.
1538 */
1539 modestatus = WMR_FORCESTOP | WMR_SDRAMWRITEEN;
1540 ret = sigma_set_register(devc, WRITE_MODE, modestatus);
1541 if (ret != SR_OK)
1542 return ret;
1543 do {
1544 ret = sigma_read_register(devc, READ_MODE,
1545 &modestatus, sizeof(modestatus));
1546 if (ret != SR_OK) {
1547 sr_err("Could not poll for post-trigger state.");
1548 return FALSE;
1549 }
1550 } while (!(modestatus & RMR_POSTTRIGGERED));
1551
1552 /* Set SDRAM Read Enable. */
1553 ret = sigma_set_register(devc, WRITE_MODE, WMR_SDRAMREADEN);
1554 if (ret != SR_OK)
1555 return ret;
1556
1557 /* Get the current position. Check if trigger has fired. */
1558 ret = sigma_read_pos(devc, &stoppos, &triggerpos, &modestatus);
1559 if (ret != SR_OK) {
1560 sr_err("Could not query capture positions/state.");
1561 return FALSE;
1562 }
1563 trg_line = ~0;
1564 trg_event = ~0;
1565 if (modestatus & RMR_TRIGGERED) {
1566 trg_line = triggerpos >> ROW_SHIFT;
1567 trg_event = triggerpos & ROW_MASK;
1568 }
1569
1570 /*
1571 * Determine how many "DRAM lines" of 1024 bytes each we need to
1572 * retrieve from the Sigma hardware, so that we have a complete
1573 * set of samples. Note that the last line need not contain 64
1574 * clusters, it might be partially filled only.
1575 *
1576 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1577 * around. Since the status of the very next line is uncertain in
1578 * that case, we skip it and start reading from the next line.
1579 */
1580 dl_first_line = 0;
1581 dl_lines_total = (stoppos >> ROW_SHIFT) + 1;
1582 if (modestatus & RMR_ROUND) {
1583 dl_first_line = dl_lines_total + 1;
1584 dl_lines_total = ROW_COUNT - 2;
1585 }
1586 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1587 if (!dram_line)
1588 return FALSE;
1589 ret = alloc_submit_buffer(sdi);
1590 if (ret != SR_OK)
1591 return FALSE;
1592 ret = setup_submit_limit(devc);
1593 if (ret != SR_OK)
1594 return FALSE;
1595 dl_lines_done = 0;
1596 while (dl_lines_total > dl_lines_done) {
1597 /* We can download only up-to 32 DRAM lines in one go! */
1598 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1599
1600 dl_line = dl_first_line + dl_lines_done;
1601 dl_line %= ROW_COUNT;
1602 ret = sigma_read_dram(devc, dl_line, dl_lines_curr,
1603 (uint8_t *)dram_line);
1604 if (ret != SR_OK)
1605 return FALSE;
1606
1607 /* This is the first DRAM line, so find the initial timestamp. */
1608 if (dl_lines_done == 0) {
1609 devc->state.lastts =
1610 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1611 devc->state.lastsample = 0;
1612 }
1613
1614 for (i = 0; i < dl_lines_curr; i++) {
1615 /* The last "DRAM line" need not span its full length. */
1616 dl_events_in_line = EVENTS_PER_ROW;
1617 if (dl_lines_done + i == dl_lines_total - 1)
1618 dl_events_in_line = stoppos & ROW_MASK;
1619
1620 /* Test if the trigger happened on this line. */
1621 trigger_event = ~0;
1622 if (dl_lines_done + i == trg_line)
1623 trigger_event = trg_event;
1624
1625 decode_chunk_ts(devc, dram_line + i,
1626 dl_events_in_line, trigger_event);
1627 }
1628
1629 dl_lines_done += dl_lines_curr;
1630 }
1631 flush_submit_buffer(devc);
1632 free_submit_buffer(devc);
1633 g_free(dram_line);
1634
1635 std_session_send_df_end(sdi);
1636
1637 devc->state.state = SIGMA_IDLE;
1638 sr_dev_acquisition_stop(sdi);
1639
1640 return TRUE;
1641}
1642
1643/*
1644 * Periodically check the Sigma status when in CAPTURE mode. This routine
1645 * checks whether the configured sample count or sample time have passed,
1646 * and will stop acquisition and download the acquired samples.
1647 */
1648static int sigma_capture_mode(struct sr_dev_inst *sdi)
1649{
1650 struct dev_context *devc;
1651
1652 devc = sdi->priv;
1653 if (sr_sw_limits_check(&devc->acq_limits))
1654 return download_capture(sdi);
1655
1656 return TRUE;
1657}
1658
1659SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1660{
1661 struct sr_dev_inst *sdi;
1662 struct dev_context *devc;
1663
1664 (void)fd;
1665 (void)revents;
1666
1667 sdi = cb_data;
1668 devc = sdi->priv;
1669
1670 if (devc->state.state == SIGMA_IDLE)
1671 return TRUE;
1672
1673 /*
1674 * When the application has requested to stop the acquisition,
1675 * then immediately start downloading sample data. Otherwise
1676 * keep checking configured limits which will terminate the
1677 * acquisition and initiate download.
1678 */
1679 if (devc->state.state == SIGMA_STOPPING)
1680 return download_capture(sdi);
1681 if (devc->state.state == SIGMA_CAPTURE)
1682 return sigma_capture_mode(sdi);
1683
1684 return TRUE;
1685}
1686
1687/* Build a LUT entry used by the trigger functions. */
1688static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1689{
1690 int i, j, k, bit;
1691
1692 /* For each quad channel. */
1693 for (i = 0; i < 4; i++) {
1694 entry[i] = 0xffff;
1695
1696 /* For each bit in LUT. */
1697 for (j = 0; j < 16; j++) {
1698
1699 /* For each channel in quad. */
1700 for (k = 0; k < 4; k++) {
1701 bit = 1 << (i * 4 + k);
1702
1703 /* Set bit in entry */
1704 if ((mask & bit) && ((!(value & bit)) !=
1705 (!(j & (1 << k)))))
1706 entry[i] &= ~(1 << j);
1707 }
1708 }
1709 }
1710}
1711
1712/* Add a logical function to LUT mask. */
1713static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1714 int index, int neg, uint16_t *mask)
1715{
1716 int i, j;
1717 int x[2][2], tmp, a, b, aset, bset, rset;
1718
1719 memset(x, 0, sizeof(x));
1720
1721 /* Trigger detect condition. */
1722 switch (oper) {
1723 case OP_LEVEL:
1724 x[0][1] = 1;
1725 x[1][1] = 1;
1726 break;
1727 case OP_NOT:
1728 x[0][0] = 1;
1729 x[1][0] = 1;
1730 break;
1731 case OP_RISE:
1732 x[0][1] = 1;
1733 break;
1734 case OP_FALL:
1735 x[1][0] = 1;
1736 break;
1737 case OP_RISEFALL:
1738 x[0][1] = 1;
1739 x[1][0] = 1;
1740 break;
1741 case OP_NOTRISE:
1742 x[1][1] = 1;
1743 x[0][0] = 1;
1744 x[1][0] = 1;
1745 break;
1746 case OP_NOTFALL:
1747 x[1][1] = 1;
1748 x[0][0] = 1;
1749 x[0][1] = 1;
1750 break;
1751 case OP_NOTRISEFALL:
1752 x[1][1] = 1;
1753 x[0][0] = 1;
1754 break;
1755 }
1756
1757 /* Transpose if neg is set. */
1758 if (neg) {
1759 for (i = 0; i < 2; i++) {
1760 for (j = 0; j < 2; j++) {
1761 tmp = x[i][j];
1762 x[i][j] = x[1 - i][1 - j];
1763 x[1 - i][1 - j] = tmp;
1764 }
1765 }
1766 }
1767
1768 /* Update mask with function. */
1769 for (i = 0; i < 16; i++) {
1770 a = (i >> (2 * index + 0)) & 1;
1771 b = (i >> (2 * index + 1)) & 1;
1772
1773 aset = (*mask >> i) & 1;
1774 bset = x[b][a];
1775
1776 rset = 0;
1777 if (func == FUNC_AND || func == FUNC_NAND)
1778 rset = aset & bset;
1779 else if (func == FUNC_OR || func == FUNC_NOR)
1780 rset = aset | bset;
1781 else if (func == FUNC_XOR || func == FUNC_NXOR)
1782 rset = aset ^ bset;
1783
1784 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1785 rset = !rset;
1786
1787 *mask &= ~(1 << i);
1788
1789 if (rset)
1790 *mask |= 1 << i;
1791 }
1792}
1793
1794/*
1795 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1796 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1797 * set at any time, but a full mask and value can be set (0/1).
1798 */
1799SR_PRIV int sigma_build_basic_trigger(struct dev_context *devc,
1800 struct triggerlut *lut)
1801{
1802 int i,j;
1803 uint16_t masks[2];
1804
1805 memset(lut, 0, sizeof(*lut));
1806 memset(&masks, 0, sizeof(masks));
1807
1808 /* Constant for simple triggers. */
1809 lut->m4 = 0xa000;
1810
1811 /* Value/mask trigger support. */
1812 build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1813 lut->m2d);
1814
1815 /* Rise/fall trigger support. */
1816 for (i = 0, j = 0; i < 16; i++) {
1817 if (devc->trigger.risingmask & (1 << i) ||
1818 devc->trigger.fallingmask & (1 << i))
1819 masks[j++] = 1 << i;
1820 }
1821
1822 build_lut_entry(masks[0], masks[0], lut->m0d);
1823 build_lut_entry(masks[1], masks[1], lut->m1d);
1824
1825 /* Add glue logic */
1826 if (masks[0] || masks[1]) {
1827 /* Transition trigger. */
1828 if (masks[0] & devc->trigger.risingmask)
1829 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1830 if (masks[0] & devc->trigger.fallingmask)
1831 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1832 if (masks[1] & devc->trigger.risingmask)
1833 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1834 if (masks[1] & devc->trigger.fallingmask)
1835 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1836 } else {
1837 /* Only value/mask trigger. */
1838 lut->m3 = 0xffff;
1839 }
1840
1841 /* Triggertype: event. */
1842 lut->params.selres = 3;
1843
1844 return SR_OK;
1845}