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