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