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