]> sigrok.org Git - libsigrok.git/blame_incremental - src/hardware/asix-sigma/protocol.c
asix-sigma: rework scan for USB devices, add support for conn= specs
[libsigrok.git] / src / hardware / asix-sigma / protocol.c
... / ...
CommitLineData
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2010-2012 Håvard Espeland <gus@ping.uio.no>,
5 * Copyright (C) 2010 Martin Stensgård <mastensg@ping.uio.no>
6 * Copyright (C) 2010 Carl Henrik Lunde <chlunde@ping.uio.no>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22/*
23 * ASIX SIGMA/SIGMA2 logic analyzer driver
24 */
25
26#include <config.h>
27#include "protocol.h"
28
29/*
30 * The ASIX Sigma supports arbitrary integer frequency divider in
31 * the 50MHz mode. The divider is in range 1...256 , allowing for
32 * very precise sampling rate selection. This driver supports only
33 * a subset of the sampling rates.
34 */
35SR_PRIV const uint64_t samplerates[] = {
36 SR_KHZ(200), /* div=250 */
37 SR_KHZ(250), /* div=200 */
38 SR_KHZ(500), /* div=100 */
39 SR_MHZ(1), /* div=50 */
40 SR_MHZ(5), /* div=10 */
41 SR_MHZ(10), /* div=5 */
42 SR_MHZ(25), /* div=2 */
43 SR_MHZ(50), /* div=1 */
44 SR_MHZ(100), /* Special FW needed */
45 SR_MHZ(200), /* Special FW needed */
46};
47
48SR_PRIV const size_t samplerates_count = ARRAY_SIZE(samplerates);
49
50static const char *firmware_files[] = {
51 "asix-sigma-50.fw", /* Up to 50MHz sample rate, 8bit divider. */
52 "asix-sigma-100.fw", /* 100MHz sample rate, fixed. */
53 "asix-sigma-200.fw", /* 200MHz sample rate, fixed. */
54 "asix-sigma-50sync.fw", /* Synchronous clock from external pin. */
55 "asix-sigma-phasor.fw", /* Frequency counter. */
56};
57
58#define SIGMA_FIRMWARE_SIZE_LIMIT (256 * 1024)
59
60static int sigma_read(void *buf, size_t size, struct dev_context *devc)
61{
62 int ret;
63
64 ret = ftdi_read_data(&devc->ftdic, (unsigned char *)buf, size);
65 if (ret < 0) {
66 sr_err("ftdi_read_data failed: %s",
67 ftdi_get_error_string(&devc->ftdic));
68 }
69
70 return ret;
71}
72
73static int sigma_write(void *buf, size_t size, struct dev_context *devc)
74{
75 int ret;
76
77 ret = ftdi_write_data(&devc->ftdic, (unsigned char *)buf, size);
78 if (ret < 0)
79 sr_err("ftdi_write_data failed: %s",
80 ftdi_get_error_string(&devc->ftdic));
81 else if ((size_t) ret != size)
82 sr_err("ftdi_write_data did not complete write.");
83
84 return ret;
85}
86
87/*
88 * NOTE: We chose the buffer size to be large enough to hold any write to the
89 * device. We still print a message just in case.
90 */
91SR_PRIV int sigma_write_register(uint8_t reg, uint8_t *data, size_t len,
92 struct dev_context *devc)
93{
94 size_t i;
95 uint8_t buf[80];
96 int idx = 0;
97
98 if ((2 * len + 2) > sizeof(buf)) {
99 sr_err("Attempted to write %zu bytes, but buffer is too small.",
100 len);
101 return SR_ERR_BUG;
102 }
103
104 buf[idx++] = REG_ADDR_LOW | (reg & 0xf);
105 buf[idx++] = REG_ADDR_HIGH | (reg >> 4);
106
107 for (i = 0; i < len; i++) {
108 buf[idx++] = REG_DATA_LOW | (data[i] & 0xf);
109 buf[idx++] = REG_DATA_HIGH_WRITE | (data[i] >> 4);
110 }
111
112 return sigma_write(buf, idx, devc);
113}
114
115SR_PRIV int sigma_set_register(uint8_t reg, uint8_t value, struct dev_context *devc)
116{
117 return sigma_write_register(reg, &value, 1, devc);
118}
119
120static int sigma_read_register(uint8_t reg, uint8_t *data, size_t len,
121 struct dev_context *devc)
122{
123 uint8_t buf[3];
124
125 buf[0] = REG_ADDR_LOW | (reg & 0xf);
126 buf[1] = REG_ADDR_HIGH | (reg >> 4);
127 buf[2] = REG_READ_ADDR;
128
129 sigma_write(buf, sizeof(buf), devc);
130
131 return sigma_read(data, len, devc);
132}
133
134static int sigma_read_pos(uint32_t *stoppos, uint32_t *triggerpos,
135 struct dev_context *devc)
136{
137 uint8_t buf[] = {
138 REG_ADDR_LOW | READ_TRIGGER_POS_LOW,
139
140 REG_READ_ADDR | NEXT_REG,
141 REG_READ_ADDR | NEXT_REG,
142 REG_READ_ADDR | NEXT_REG,
143 REG_READ_ADDR | NEXT_REG,
144 REG_READ_ADDR | NEXT_REG,
145 REG_READ_ADDR | NEXT_REG,
146 };
147 uint8_t result[6];
148
149 sigma_write(buf, sizeof(buf), devc);
150
151 sigma_read(result, sizeof(result), devc);
152
153 *triggerpos = result[0] | (result[1] << 8) | (result[2] << 16);
154 *stoppos = result[3] | (result[4] << 8) | (result[5] << 16);
155
156 /*
157 * These "position" values point to after the event (end of
158 * capture data, trigger condition matched). This is why they
159 * get decremented here. Sample memory consists of 512-byte
160 * chunks with meta data in the upper 64 bytes. Thus when the
161 * decrements takes us into this upper part of the chunk, then
162 * further move backwards to the end of the chunk's data part.
163 */
164 if ((--*stoppos & 0x1ff) == 0x1ff)
165 *stoppos -= 64;
166 if ((--*triggerpos & 0x1ff) == 0x1ff)
167 *triggerpos -= 64;
168
169 return 1;
170}
171
172static int sigma_read_dram(uint16_t startchunk, size_t numchunks,
173 uint8_t *data, struct dev_context *devc)
174{
175 size_t i;
176 uint8_t buf[4096];
177 int idx;
178
179 /* Send the startchunk. Index start with 1. */
180 idx = 0;
181 buf[idx++] = startchunk >> 8;
182 buf[idx++] = startchunk & 0xff;
183 sigma_write_register(WRITE_MEMROW, buf, idx, devc);
184
185 /* Read the DRAM. */
186 idx = 0;
187 buf[idx++] = REG_DRAM_BLOCK;
188 buf[idx++] = REG_DRAM_WAIT_ACK;
189
190 for (i = 0; i < numchunks; i++) {
191 /* Alternate bit to copy from DRAM to cache. */
192 if (i != (numchunks - 1))
193 buf[idx++] = REG_DRAM_BLOCK | (((i + 1) % 2) << 4);
194
195 buf[idx++] = REG_DRAM_BLOCK_DATA | ((i % 2) << 4);
196
197 if (i != (numchunks - 1))
198 buf[idx++] = REG_DRAM_WAIT_ACK;
199 }
200
201 sigma_write(buf, idx, devc);
202
203 return sigma_read(data, numchunks * CHUNK_SIZE, devc);
204}
205
206/* Upload trigger look-up tables to Sigma. */
207SR_PRIV int sigma_write_trigger_lut(struct triggerlut *lut, struct dev_context *devc)
208{
209 int i;
210 uint8_t tmp[2];
211 uint16_t bit;
212
213 /* Transpose the table and send to Sigma. */
214 for (i = 0; i < 16; i++) {
215 bit = 1 << i;
216
217 tmp[0] = tmp[1] = 0;
218
219 if (lut->m2d[0] & bit)
220 tmp[0] |= 0x01;
221 if (lut->m2d[1] & bit)
222 tmp[0] |= 0x02;
223 if (lut->m2d[2] & bit)
224 tmp[0] |= 0x04;
225 if (lut->m2d[3] & bit)
226 tmp[0] |= 0x08;
227
228 if (lut->m3 & bit)
229 tmp[0] |= 0x10;
230 if (lut->m3s & bit)
231 tmp[0] |= 0x20;
232 if (lut->m4 & bit)
233 tmp[0] |= 0x40;
234
235 if (lut->m0d[0] & bit)
236 tmp[1] |= 0x01;
237 if (lut->m0d[1] & bit)
238 tmp[1] |= 0x02;
239 if (lut->m0d[2] & bit)
240 tmp[1] |= 0x04;
241 if (lut->m0d[3] & bit)
242 tmp[1] |= 0x08;
243
244 if (lut->m1d[0] & bit)
245 tmp[1] |= 0x10;
246 if (lut->m1d[1] & bit)
247 tmp[1] |= 0x20;
248 if (lut->m1d[2] & bit)
249 tmp[1] |= 0x40;
250 if (lut->m1d[3] & bit)
251 tmp[1] |= 0x80;
252
253 sigma_write_register(WRITE_TRIGGER_SELECT0, tmp, sizeof(tmp),
254 devc);
255 sigma_set_register(WRITE_TRIGGER_SELECT1, 0x30 | i, devc);
256 }
257
258 /* Send the parameters */
259 sigma_write_register(WRITE_TRIGGER_SELECT0, (uint8_t *) &lut->params,
260 sizeof(lut->params), devc);
261
262 return SR_OK;
263}
264
265/*
266 * Configure the FPGA for bitbang mode.
267 * This sequence is documented in section 2. of the ASIX Sigma programming
268 * manual. This sequence is necessary to configure the FPGA in the Sigma
269 * into Bitbang mode, in which it can be programmed with the firmware.
270 */
271static int sigma_fpga_init_bitbang(struct dev_context *devc)
272{
273 uint8_t suicide[] = {
274 0x84, 0x84, 0x88, 0x84, 0x88, 0x84, 0x88, 0x84,
275 };
276 uint8_t init_array[] = {
277 0x01, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01,
278 0x01, 0x01,
279 };
280 int i, ret, timeout = (10 * 1000);
281 uint8_t data;
282
283 /* Section 2. part 1), do the FPGA suicide. */
284 sigma_write(suicide, sizeof(suicide), devc);
285 sigma_write(suicide, sizeof(suicide), devc);
286 sigma_write(suicide, sizeof(suicide), devc);
287 sigma_write(suicide, sizeof(suicide), devc);
288
289 /* Section 2. part 2), do pulse on D1. */
290 sigma_write(init_array, sizeof(init_array), devc);
291 ftdi_usb_purge_buffers(&devc->ftdic);
292
293 /* Wait until the FPGA asserts D6/INIT_B. */
294 for (i = 0; i < timeout; i++) {
295 ret = sigma_read(&data, 1, devc);
296 if (ret < 0)
297 return ret;
298 /* Test if pin D6 got asserted. */
299 if (data & (1 << 5))
300 return 0;
301 /* The D6 was not asserted yet, wait a bit. */
302 g_usleep(10 * 1000);
303 }
304
305 return SR_ERR_TIMEOUT;
306}
307
308/*
309 * Configure the FPGA for logic-analyzer mode.
310 */
311static int sigma_fpga_init_la(struct dev_context *devc)
312{
313 /* Initialize the logic analyzer mode. */
314 uint8_t mode_regval = WMR_SDRAMINIT;
315 uint8_t logic_mode_start[] = {
316 REG_ADDR_LOW | (READ_ID & 0xf),
317 REG_ADDR_HIGH | (READ_ID >> 4),
318 REG_READ_ADDR, /* Read ID register. */
319
320 REG_ADDR_LOW | (WRITE_TEST & 0xf),
321 REG_DATA_LOW | 0x5,
322 REG_DATA_HIGH_WRITE | 0x5,
323 REG_READ_ADDR, /* Read scratch register. */
324
325 REG_DATA_LOW | 0xa,
326 REG_DATA_HIGH_WRITE | 0xa,
327 REG_READ_ADDR, /* Read scratch register. */
328
329 REG_ADDR_LOW | (WRITE_MODE & 0xf),
330 REG_DATA_LOW | (mode_regval & 0xf),
331 REG_DATA_HIGH_WRITE | (mode_regval >> 4),
332 };
333
334 uint8_t result[3];
335 int ret;
336
337 /* Initialize the logic analyzer mode. */
338 sigma_write(logic_mode_start, sizeof(logic_mode_start), devc);
339
340 /* Expect a 3 byte reply since we issued three READ requests. */
341 ret = sigma_read(result, 3, devc);
342 if (ret != 3)
343 goto err;
344
345 if (result[0] != 0xa6 || result[1] != 0x55 || result[2] != 0xaa)
346 goto err;
347
348 return SR_OK;
349err:
350 sr_err("Configuration failed. Invalid reply received.");
351 return SR_ERR;
352}
353
354/*
355 * Read the firmware from a file and transform it into a series of bitbang
356 * pulses used to program the FPGA. Note that the *bb_cmd must be free()'d
357 * by the caller of this function.
358 */
359static int sigma_fw_2_bitbang(struct sr_context *ctx, const char *name,
360 uint8_t **bb_cmd, gsize *bb_cmd_size)
361{
362 size_t i, file_size, bb_size;
363 char *firmware;
364 uint8_t *bb_stream, *bbs;
365 uint32_t imm;
366 int bit, v;
367 int ret = SR_OK;
368
369 /* Retrieve the on-disk firmware file content. */
370 firmware = sr_resource_load(ctx, SR_RESOURCE_FIRMWARE, name,
371 &file_size, SIGMA_FIRMWARE_SIZE_LIMIT);
372 if (!firmware)
373 return SR_ERR;
374
375 /* Unscramble the file content (XOR with "random" sequence). */
376 imm = 0x3f6df2ab;
377 for (i = 0; i < file_size; i++) {
378 imm = (imm + 0xa853753) % 177 + (imm * 0x8034052);
379 firmware[i] ^= imm & 0xff;
380 }
381
382 /*
383 * Generate a sequence of bitbang samples. With two samples per
384 * FPGA configuration bit, providing the level for the DIN signal
385 * as well as two edges for CCLK. See Xilinx UG332 for details
386 * ("slave serial" mode).
387 *
388 * Note that CCLK is inverted in hardware. That's why the
389 * respective bit is first set and then cleared in the bitbang
390 * sample sets. So that the DIN level will be stable when the
391 * data gets sampled at the rising CCLK edge, and the signals'
392 * setup time constraint will be met.
393 *
394 * The caller will put the FPGA into download mode, will send
395 * the bitbang samples, and release the allocated memory.
396 */
397 bb_size = file_size * 8 * 2;
398 bb_stream = (uint8_t *)g_try_malloc(bb_size);
399 if (!bb_stream) {
400 sr_err("%s: Failed to allocate bitbang stream", __func__);
401 ret = SR_ERR_MALLOC;
402 goto exit;
403 }
404 bbs = bb_stream;
405 for (i = 0; i < file_size; i++) {
406 for (bit = 7; bit >= 0; bit--) {
407 v = (firmware[i] & (1 << bit)) ? 0x40 : 0x00;
408 *bbs++ = v | 0x01;
409 *bbs++ = v;
410 }
411 }
412
413 /* The transformation completed successfully, return the result. */
414 *bb_cmd = bb_stream;
415 *bb_cmd_size = bb_size;
416
417exit:
418 g_free(firmware);
419 return ret;
420}
421
422static int upload_firmware(struct sr_context *ctx,
423 int firmware_idx, struct dev_context *devc)
424{
425 int ret;
426 unsigned char *buf;
427 unsigned char pins;
428 size_t buf_size;
429 const char *firmware;
430
431 /* Avoid downloading the same firmware multiple times. */
432 firmware = firmware_files[firmware_idx];
433 if (devc->cur_firmware == firmware_idx) {
434 sr_info("Not uploading firmware file '%s' again.", firmware);
435 return SR_OK;
436 }
437
438 ret = ftdi_set_bitmode(&devc->ftdic, 0xdf, BITMODE_BITBANG);
439 if (ret < 0) {
440 sr_err("ftdi_set_bitmode failed: %s",
441 ftdi_get_error_string(&devc->ftdic));
442 return SR_ERR;
443 }
444
445 /* Four times the speed of sigmalogan - Works well. */
446 ret = ftdi_set_baudrate(&devc->ftdic, 750 * 1000);
447 if (ret < 0) {
448 sr_err("ftdi_set_baudrate failed: %s",
449 ftdi_get_error_string(&devc->ftdic));
450 return SR_ERR;
451 }
452
453 /* Initialize the FPGA for firmware upload. */
454 ret = sigma_fpga_init_bitbang(devc);
455 if (ret)
456 return ret;
457
458 /* Prepare firmware. */
459 ret = sigma_fw_2_bitbang(ctx, firmware, &buf, &buf_size);
460 if (ret != SR_OK) {
461 sr_err("An error occurred while reading the firmware: %s",
462 firmware);
463 return ret;
464 }
465
466 /* Upload firmware. */
467 sr_info("Uploading firmware file '%s'.", firmware);
468 sigma_write(buf, buf_size, devc);
469
470 g_free(buf);
471
472 ret = ftdi_set_bitmode(&devc->ftdic, 0x00, BITMODE_RESET);
473 if (ret < 0) {
474 sr_err("ftdi_set_bitmode failed: %s",
475 ftdi_get_error_string(&devc->ftdic));
476 return SR_ERR;
477 }
478
479 ftdi_usb_purge_buffers(&devc->ftdic);
480
481 /* Discard garbage. */
482 while (sigma_read(&pins, 1, devc) == 1)
483 ;
484
485 /* Initialize the FPGA for logic-analyzer mode. */
486 ret = sigma_fpga_init_la(devc);
487 if (ret != SR_OK)
488 return ret;
489
490 devc->cur_firmware = firmware_idx;
491
492 sr_info("Firmware uploaded.");
493
494 return SR_OK;
495}
496
497/*
498 * Sigma doesn't support limiting the number of samples, so we have to
499 * translate the number and the samplerate to an elapsed time.
500 *
501 * In addition we need to ensure that the last data cluster has passed
502 * the hardware pipeline, and became available to the PC side. With RLE
503 * compression up to 327ms could pass before another cluster accumulates
504 * at 200kHz samplerate when input pins don't change.
505 */
506SR_PRIV uint64_t sigma_limit_samples_to_msec(const struct dev_context *devc,
507 uint64_t limit_samples)
508{
509 uint64_t limit_msec;
510 uint64_t worst_cluster_time_ms;
511
512 limit_msec = limit_samples * 1000 / devc->cur_samplerate;
513 worst_cluster_time_ms = 65536 * 1000 / devc->cur_samplerate;
514 /*
515 * One cluster time is not enough to flush pipeline when sampling
516 * grounded pins with 1 sample limit at 200kHz. Hence the 2* fix.
517 */
518 return limit_msec + 2 * worst_cluster_time_ms;
519}
520
521SR_PRIV int sigma_set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
522{
523 struct dev_context *devc;
524 struct drv_context *drvc;
525 size_t i;
526 int ret;
527 int num_channels;
528
529 devc = sdi->priv;
530 drvc = sdi->driver->context;
531 ret = SR_OK;
532
533 /* Reject rates that are not in the list of supported rates. */
534 for (i = 0; i < samplerates_count; i++) {
535 if (samplerates[i] == samplerate)
536 break;
537 }
538 if (i >= samplerates_count || samplerates[i] == 0)
539 return SR_ERR_SAMPLERATE;
540
541 /*
542 * Depending on the samplerates of 200/100/50- MHz, specific
543 * firmware is required and higher rates might limit the set
544 * of available channels.
545 */
546 num_channels = devc->num_channels;
547 if (samplerate <= SR_MHZ(50)) {
548 ret = upload_firmware(drvc->sr_ctx, 0, devc);
549 num_channels = 16;
550 } else if (samplerate == SR_MHZ(100)) {
551 ret = upload_firmware(drvc->sr_ctx, 1, devc);
552 num_channels = 8;
553 } else if (samplerate == SR_MHZ(200)) {
554 ret = upload_firmware(drvc->sr_ctx, 2, devc);
555 num_channels = 4;
556 }
557
558 /*
559 * Derive the sample period from the sample rate as well as the
560 * number of samples that the device will communicate within
561 * an "event" (memory organization internal to the device).
562 */
563 if (ret == SR_OK) {
564 devc->num_channels = num_channels;
565 devc->cur_samplerate = samplerate;
566 devc->samples_per_event = 16 / devc->num_channels;
567 devc->state.state = SIGMA_IDLE;
568 }
569
570 /*
571 * Support for "limit_samples" is implemented by stopping
572 * acquisition after a corresponding period of time.
573 * Re-calculate that period of time, in case the limit is
574 * set first and the samplerate gets (re-)configured later.
575 */
576 if (ret == SR_OK && devc->limit_samples) {
577 uint64_t msecs;
578 msecs = sigma_limit_samples_to_msec(devc, devc->limit_samples);
579 devc->limit_msec = msecs;
580 }
581
582 return ret;
583}
584
585/*
586 * In 100 and 200 MHz mode, only a single pin rising/falling can be
587 * set as trigger. In other modes, two rising/falling triggers can be set,
588 * in addition to value/mask trigger for any number of channels.
589 *
590 * The Sigma supports complex triggers using boolean expressions, but this
591 * has not been implemented yet.
592 */
593SR_PRIV int sigma_convert_trigger(const struct sr_dev_inst *sdi)
594{
595 struct dev_context *devc;
596 struct sr_trigger *trigger;
597 struct sr_trigger_stage *stage;
598 struct sr_trigger_match *match;
599 const GSList *l, *m;
600 int channelbit, trigger_set;
601
602 devc = sdi->priv;
603 memset(&devc->trigger, 0, sizeof(struct sigma_trigger));
604 if (!(trigger = sr_session_trigger_get(sdi->session)))
605 return SR_OK;
606
607 trigger_set = 0;
608 for (l = trigger->stages; l; l = l->next) {
609 stage = l->data;
610 for (m = stage->matches; m; m = m->next) {
611 match = m->data;
612 if (!match->channel->enabled)
613 /* Ignore disabled channels with a trigger. */
614 continue;
615 channelbit = 1 << (match->channel->index);
616 if (devc->cur_samplerate >= SR_MHZ(100)) {
617 /* Fast trigger support. */
618 if (trigger_set) {
619 sr_err("Only a single pin trigger is "
620 "supported in 100 and 200MHz mode.");
621 return SR_ERR;
622 }
623 if (match->match == SR_TRIGGER_FALLING)
624 devc->trigger.fallingmask |= channelbit;
625 else if (match->match == SR_TRIGGER_RISING)
626 devc->trigger.risingmask |= channelbit;
627 else {
628 sr_err("Only rising/falling trigger is "
629 "supported in 100 and 200MHz mode.");
630 return SR_ERR;
631 }
632
633 trigger_set++;
634 } else {
635 /* Simple trigger support (event). */
636 if (match->match == SR_TRIGGER_ONE) {
637 devc->trigger.simplevalue |= channelbit;
638 devc->trigger.simplemask |= channelbit;
639 } else if (match->match == SR_TRIGGER_ZERO) {
640 devc->trigger.simplevalue &= ~channelbit;
641 devc->trigger.simplemask |= channelbit;
642 } else if (match->match == SR_TRIGGER_FALLING) {
643 devc->trigger.fallingmask |= channelbit;
644 trigger_set++;
645 } else if (match->match == SR_TRIGGER_RISING) {
646 devc->trigger.risingmask |= channelbit;
647 trigger_set++;
648 }
649
650 /*
651 * Actually, Sigma supports 2 rising/falling triggers,
652 * but they are ORed and the current trigger syntax
653 * does not permit ORed triggers.
654 */
655 if (trigger_set > 1) {
656 sr_err("Only 1 rising/falling trigger "
657 "is supported.");
658 return SR_ERR;
659 }
660 }
661 }
662 }
663
664 return SR_OK;
665}
666
667/* Software trigger to determine exact trigger position. */
668static int get_trigger_offset(uint8_t *samples, uint16_t last_sample,
669 struct sigma_trigger *t)
670{
671 int i;
672 uint16_t sample = 0;
673
674 for (i = 0; i < 8; i++) {
675 if (i > 0)
676 last_sample = sample;
677 sample = samples[2 * i] | (samples[2 * i + 1] << 8);
678
679 /* Simple triggers. */
680 if ((sample & t->simplemask) != t->simplevalue)
681 continue;
682
683 /* Rising edge. */
684 if (((last_sample & t->risingmask) != 0) ||
685 ((sample & t->risingmask) != t->risingmask))
686 continue;
687
688 /* Falling edge. */
689 if ((last_sample & t->fallingmask) != t->fallingmask ||
690 (sample & t->fallingmask) != 0)
691 continue;
692
693 break;
694 }
695
696 /* If we did not match, return original trigger pos. */
697 return i & 0x7;
698}
699
700/*
701 * Return the timestamp of "DRAM cluster".
702 */
703static uint16_t sigma_dram_cluster_ts(struct sigma_dram_cluster *cluster)
704{
705 return (cluster->timestamp_hi << 8) | cluster->timestamp_lo;
706}
707
708/*
709 * Return one 16bit data entity of a DRAM cluster at the specified index.
710 */
711static uint16_t sigma_dram_cluster_data(struct sigma_dram_cluster *cl, int idx)
712{
713 uint16_t sample;
714
715 sample = 0;
716 sample |= cl->samples[idx].sample_lo << 0;
717 sample |= cl->samples[idx].sample_hi << 8;
718 sample = (sample >> 8) | (sample << 8);
719 return sample;
720}
721
722/*
723 * Deinterlace sample data that was retrieved at 100MHz samplerate.
724 * One 16bit item contains two samples of 8bits each. The bits of
725 * multiple samples are interleaved.
726 */
727static uint16_t sigma_deinterlace_100mhz_data(uint16_t indata, int idx)
728{
729 uint16_t outdata;
730
731 indata >>= idx;
732 outdata = 0;
733 outdata |= (indata >> (0 * 2 - 0)) & (1 << 0);
734 outdata |= (indata >> (1 * 2 - 1)) & (1 << 1);
735 outdata |= (indata >> (2 * 2 - 2)) & (1 << 2);
736 outdata |= (indata >> (3 * 2 - 3)) & (1 << 3);
737 outdata |= (indata >> (4 * 2 - 4)) & (1 << 4);
738 outdata |= (indata >> (5 * 2 - 5)) & (1 << 5);
739 outdata |= (indata >> (6 * 2 - 6)) & (1 << 6);
740 outdata |= (indata >> (7 * 2 - 7)) & (1 << 7);
741 return outdata;
742}
743
744/*
745 * Deinterlace sample data that was retrieved at 200MHz samplerate.
746 * One 16bit item contains four samples of 4bits each. The bits of
747 * multiple samples are interleaved.
748 */
749static uint16_t sigma_deinterlace_200mhz_data(uint16_t indata, int idx)
750{
751 uint16_t outdata;
752
753 indata >>= idx;
754 outdata = 0;
755 outdata |= (indata >> (0 * 4 - 0)) & (1 << 0);
756 outdata |= (indata >> (1 * 4 - 1)) & (1 << 1);
757 outdata |= (indata >> (2 * 4 - 2)) & (1 << 2);
758 outdata |= (indata >> (3 * 4 - 3)) & (1 << 3);
759 return outdata;
760}
761
762static void store_sr_sample(uint8_t *samples, int idx, uint16_t data)
763{
764 samples[2 * idx + 0] = (data >> 0) & 0xff;
765 samples[2 * idx + 1] = (data >> 8) & 0xff;
766}
767
768/*
769 * Local wrapper around sr_session_send() calls. Make sure to not send
770 * more samples to the session's datafeed than what was requested by a
771 * previously configured (optional) sample count.
772 */
773static void sigma_session_send(struct sr_dev_inst *sdi,
774 struct sr_datafeed_packet *packet)
775{
776 struct dev_context *devc;
777 struct sr_datafeed_logic *logic;
778 uint64_t send_now;
779
780 devc = sdi->priv;
781 if (devc->limit_samples) {
782 logic = (void *)packet->payload;
783 send_now = logic->length / logic->unitsize;
784 if (devc->sent_samples + send_now > devc->limit_samples) {
785 send_now = devc->limit_samples - devc->sent_samples;
786 logic->length = send_now * logic->unitsize;
787 }
788 if (!send_now)
789 return;
790 devc->sent_samples += send_now;
791 }
792
793 sr_session_send(sdi, packet);
794}
795
796/*
797 * This size translates to: event count (1K events per cluster), times
798 * the sample width (unitsize, 16bits per event), times the maximum
799 * number of samples per event.
800 */
801#define SAMPLES_BUFFER_SIZE (1024 * 2 * 4)
802
803static void sigma_decode_dram_cluster(struct sigma_dram_cluster *dram_cluster,
804 unsigned int events_in_cluster,
805 unsigned int triggered,
806 struct sr_dev_inst *sdi)
807{
808 struct dev_context *devc = sdi->priv;
809 struct sigma_state *ss = &devc->state;
810 struct sr_datafeed_packet packet;
811 struct sr_datafeed_logic logic;
812 uint16_t tsdiff, ts, sample, item16;
813 uint8_t samples[SAMPLES_BUFFER_SIZE];
814 uint8_t *send_ptr;
815 size_t send_count, trig_count;
816 unsigned int i;
817 int j;
818
819 ts = sigma_dram_cluster_ts(dram_cluster);
820 tsdiff = ts - ss->lastts;
821 ss->lastts = ts + EVENTS_PER_CLUSTER;
822
823 packet.type = SR_DF_LOGIC;
824 packet.payload = &logic;
825 logic.unitsize = 2;
826 logic.data = samples;
827
828 /*
829 * If this cluster is not adjacent to the previously received
830 * cluster, then send the appropriate number of samples with the
831 * previous values to the sigrok session. This "decodes RLE".
832 */
833 for (ts = 0; ts < tsdiff; ts++) {
834 i = ts % 1024;
835 store_sr_sample(samples, i, ss->lastsample);
836
837 /*
838 * If we have 1024 samples ready or we're at the
839 * end of submitting the padding samples, submit
840 * the packet to Sigrok. Since constant data is
841 * sent, duplication of data for rates above 50MHz
842 * is simple.
843 */
844 if ((i == 1023) || (ts == tsdiff - 1)) {
845 logic.length = (i + 1) * logic.unitsize;
846 for (j = 0; j < devc->samples_per_event; j++)
847 sigma_session_send(sdi, &packet);
848 }
849 }
850
851 /*
852 * Parse the samples in current cluster and prepare them
853 * to be submitted to Sigrok. Cope with memory layouts that
854 * vary with the samplerate.
855 */
856 send_ptr = &samples[0];
857 send_count = 0;
858 sample = 0;
859 for (i = 0; i < events_in_cluster; i++) {
860 item16 = sigma_dram_cluster_data(dram_cluster, i);
861 if (devc->cur_samplerate == SR_MHZ(200)) {
862 sample = sigma_deinterlace_200mhz_data(item16, 0);
863 store_sr_sample(samples, send_count++, sample);
864 sample = sigma_deinterlace_200mhz_data(item16, 1);
865 store_sr_sample(samples, send_count++, sample);
866 sample = sigma_deinterlace_200mhz_data(item16, 2);
867 store_sr_sample(samples, send_count++, sample);
868 sample = sigma_deinterlace_200mhz_data(item16, 3);
869 store_sr_sample(samples, send_count++, sample);
870 } else if (devc->cur_samplerate == SR_MHZ(100)) {
871 sample = sigma_deinterlace_100mhz_data(item16, 0);
872 store_sr_sample(samples, send_count++, sample);
873 sample = sigma_deinterlace_100mhz_data(item16, 1);
874 store_sr_sample(samples, send_count++, sample);
875 } else {
876 sample = item16;
877 store_sr_sample(samples, send_count++, sample);
878 }
879 }
880
881 /*
882 * If a trigger position applies, then provide the datafeed with
883 * the first part of data up to that position, then send the
884 * trigger marker.
885 */
886 int trigger_offset = 0;
887 if (triggered) {
888 /*
889 * Trigger is not always accurate to sample because of
890 * pipeline delay. However, it always triggers before
891 * the actual event. We therefore look at the next
892 * samples to pinpoint the exact position of the trigger.
893 */
894 trigger_offset = get_trigger_offset(samples,
895 ss->lastsample, &devc->trigger);
896
897 if (trigger_offset > 0) {
898 trig_count = trigger_offset * devc->samples_per_event;
899 packet.type = SR_DF_LOGIC;
900 logic.length = trig_count * logic.unitsize;
901 sigma_session_send(sdi, &packet);
902 send_ptr += trig_count * logic.unitsize;
903 send_count -= trig_count;
904 }
905
906 /* Only send trigger if explicitly enabled. */
907 if (devc->use_triggers)
908 std_session_send_df_trigger(sdi);
909 }
910
911 /*
912 * Send the data after the trigger, or all of the received data
913 * if no trigger position applies.
914 */
915 if (send_count) {
916 packet.type = SR_DF_LOGIC;
917 logic.length = send_count * logic.unitsize;
918 logic.data = send_ptr;
919 sigma_session_send(sdi, &packet);
920 }
921
922 ss->lastsample = sample;
923}
924
925/*
926 * Decode chunk of 1024 bytes, 64 clusters, 7 events per cluster.
927 * Each event is 20ns apart, and can contain multiple samples.
928 *
929 * For 200 MHz, events contain 4 samples for each channel, spread 5 ns apart.
930 * For 100 MHz, events contain 2 samples for each channel, spread 10 ns apart.
931 * For 50 MHz and below, events contain one sample for each channel,
932 * spread 20 ns apart.
933 */
934static int decode_chunk_ts(struct sigma_dram_line *dram_line,
935 uint16_t events_in_line,
936 uint32_t trigger_event,
937 struct sr_dev_inst *sdi)
938{
939 struct sigma_dram_cluster *dram_cluster;
940 struct dev_context *devc;
941 unsigned int clusters_in_line;
942 unsigned int events_in_cluster;
943 unsigned int i;
944 uint32_t trigger_cluster, triggered;
945
946 devc = sdi->priv;
947 clusters_in_line = events_in_line;
948 clusters_in_line += EVENTS_PER_CLUSTER - 1;
949 clusters_in_line /= EVENTS_PER_CLUSTER;
950 trigger_cluster = ~0;
951 triggered = 0;
952
953 /* Check if trigger is in this chunk. */
954 if (trigger_event < (64 * 7)) {
955 if (devc->cur_samplerate <= SR_MHZ(50)) {
956 trigger_event -= MIN(EVENTS_PER_CLUSTER - 1,
957 trigger_event);
958 }
959
960 /* Find in which cluster the trigger occurred. */
961 trigger_cluster = trigger_event / EVENTS_PER_CLUSTER;
962 }
963
964 /* For each full DRAM cluster. */
965 for (i = 0; i < clusters_in_line; i++) {
966 dram_cluster = &dram_line->cluster[i];
967
968 /* The last cluster might not be full. */
969 if ((i == clusters_in_line - 1) &&
970 (events_in_line % EVENTS_PER_CLUSTER)) {
971 events_in_cluster = events_in_line % EVENTS_PER_CLUSTER;
972 } else {
973 events_in_cluster = EVENTS_PER_CLUSTER;
974 }
975
976 triggered = (i == trigger_cluster);
977 sigma_decode_dram_cluster(dram_cluster, events_in_cluster,
978 triggered, sdi);
979 }
980
981 return SR_OK;
982}
983
984static int download_capture(struct sr_dev_inst *sdi)
985{
986 const uint32_t chunks_per_read = 32;
987
988 struct dev_context *devc;
989 struct sigma_dram_line *dram_line;
990 int bufsz;
991 uint32_t stoppos, triggerpos;
992 uint8_t modestatus;
993 uint32_t i;
994 uint32_t dl_lines_total, dl_lines_curr, dl_lines_done;
995 uint32_t dl_first_line, dl_line;
996 uint32_t dl_events_in_line;
997 uint32_t trg_line, trg_event;
998
999 devc = sdi->priv;
1000 dl_events_in_line = 64 * 7;
1001
1002 sr_info("Downloading sample data.");
1003 devc->state.state = SIGMA_DOWNLOAD;
1004
1005 /*
1006 * Ask the hardware to stop data acquisition. Reception of the
1007 * FORCESTOP request makes the hardware "disable RLE" (store
1008 * clusters to DRAM regardless of whether pin state changes) and
1009 * raise the POSTTRIGGERED flag.
1010 */
1011 sigma_set_register(WRITE_MODE, WMR_FORCESTOP | WMR_SDRAMWRITEEN, devc);
1012 do {
1013 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1014 sr_err("failed while waiting for RMR_POSTTRIGGERED bit");
1015 return FALSE;
1016 }
1017 } while (!(modestatus & RMR_POSTTRIGGERED));
1018
1019 /* Set SDRAM Read Enable. */
1020 sigma_set_register(WRITE_MODE, WMR_SDRAMREADEN, devc);
1021
1022 /* Get the current position. */
1023 sigma_read_pos(&stoppos, &triggerpos, devc);
1024
1025 /* Check if trigger has fired. */
1026 if (sigma_read_register(READ_MODE, &modestatus, 1, devc) != 1) {
1027 sr_err("failed to read READ_MODE register");
1028 return FALSE;
1029 }
1030 trg_line = ~0;
1031 trg_event = ~0;
1032 if (modestatus & RMR_TRIGGERED) {
1033 trg_line = triggerpos >> 9;
1034 trg_event = triggerpos & 0x1ff;
1035 }
1036
1037 devc->sent_samples = 0;
1038
1039 /*
1040 * Determine how many "DRAM lines" of 1024 bytes each we need to
1041 * retrieve from the Sigma hardware, so that we have a complete
1042 * set of samples. Note that the last line need not contain 64
1043 * clusters, it might be partially filled only.
1044 *
1045 * When RMR_ROUND is set, the circular buffer in DRAM has wrapped
1046 * around. Since the status of the very next line is uncertain in
1047 * that case, we skip it and start reading from the next line. The
1048 * circular buffer has 32K lines (0x8000).
1049 */
1050 dl_lines_total = (stoppos >> 9) + 1;
1051 if (modestatus & RMR_ROUND) {
1052 dl_first_line = dl_lines_total + 1;
1053 dl_lines_total = 0x8000 - 2;
1054 } else {
1055 dl_first_line = 0;
1056 }
1057 dram_line = g_try_malloc0(chunks_per_read * sizeof(*dram_line));
1058 if (!dram_line)
1059 return FALSE;
1060 dl_lines_done = 0;
1061 while (dl_lines_total > dl_lines_done) {
1062 /* We can download only up-to 32 DRAM lines in one go! */
1063 dl_lines_curr = MIN(chunks_per_read, dl_lines_total - dl_lines_done);
1064
1065 dl_line = dl_first_line + dl_lines_done;
1066 dl_line %= 0x8000;
1067 bufsz = sigma_read_dram(dl_line, dl_lines_curr,
1068 (uint8_t *)dram_line, devc);
1069 /* TODO: Check bufsz. For now, just avoid compiler warnings. */
1070 (void)bufsz;
1071
1072 /* This is the first DRAM line, so find the initial timestamp. */
1073 if (dl_lines_done == 0) {
1074 devc->state.lastts =
1075 sigma_dram_cluster_ts(&dram_line[0].cluster[0]);
1076 devc->state.lastsample = 0;
1077 }
1078
1079 for (i = 0; i < dl_lines_curr; i++) {
1080 uint32_t trigger_event = ~0;
1081 /* The last "DRAM line" can be only partially full. */
1082 if (dl_lines_done + i == dl_lines_total - 1)
1083 dl_events_in_line = stoppos & 0x1ff;
1084
1085 /* Test if the trigger happened on this line. */
1086 if (dl_lines_done + i == trg_line)
1087 trigger_event = trg_event;
1088
1089 decode_chunk_ts(dram_line + i, dl_events_in_line,
1090 trigger_event, sdi);
1091 }
1092
1093 dl_lines_done += dl_lines_curr;
1094 }
1095 g_free(dram_line);
1096
1097 std_session_send_df_end(sdi);
1098
1099 devc->state.state = SIGMA_IDLE;
1100 sr_dev_acquisition_stop(sdi);
1101
1102 return TRUE;
1103}
1104
1105/*
1106 * Periodically check the Sigma status when in CAPTURE mode. This routine
1107 * checks whether the configured sample count or sample time have passed,
1108 * and will stop acquisition and download the acquired samples.
1109 */
1110static int sigma_capture_mode(struct sr_dev_inst *sdi)
1111{
1112 struct dev_context *devc;
1113 uint64_t running_msec;
1114 uint64_t current_time;
1115
1116 devc = sdi->priv;
1117
1118 /*
1119 * Check if the selected sampling duration passed. Sample count
1120 * limits are covered by this enforced timeout as well.
1121 */
1122 current_time = g_get_monotonic_time();
1123 running_msec = (current_time - devc->start_time) / 1000;
1124 if (running_msec >= devc->limit_msec)
1125 return download_capture(sdi);
1126
1127 return TRUE;
1128}
1129
1130SR_PRIV int sigma_receive_data(int fd, int revents, void *cb_data)
1131{
1132 struct sr_dev_inst *sdi;
1133 struct dev_context *devc;
1134
1135 (void)fd;
1136 (void)revents;
1137
1138 sdi = cb_data;
1139 devc = sdi->priv;
1140
1141 if (devc->state.state == SIGMA_IDLE)
1142 return TRUE;
1143
1144 /*
1145 * When the application has requested to stop the acquisition,
1146 * then immediately start downloading sample data. Otherwise
1147 * keep checking configured limits which will terminate the
1148 * acquisition and initiate download.
1149 */
1150 if (devc->state.state == SIGMA_STOPPING)
1151 return download_capture(sdi);
1152 if (devc->state.state == SIGMA_CAPTURE)
1153 return sigma_capture_mode(sdi);
1154
1155 return TRUE;
1156}
1157
1158/* Build a LUT entry used by the trigger functions. */
1159static void build_lut_entry(uint16_t value, uint16_t mask, uint16_t *entry)
1160{
1161 int i, j, k, bit;
1162
1163 /* For each quad channel. */
1164 for (i = 0; i < 4; i++) {
1165 entry[i] = 0xffff;
1166
1167 /* For each bit in LUT. */
1168 for (j = 0; j < 16; j++)
1169
1170 /* For each channel in quad. */
1171 for (k = 0; k < 4; k++) {
1172 bit = 1 << (i * 4 + k);
1173
1174 /* Set bit in entry */
1175 if ((mask & bit) && ((!(value & bit)) !=
1176 (!(j & (1 << k)))))
1177 entry[i] &= ~(1 << j);
1178 }
1179 }
1180}
1181
1182/* Add a logical function to LUT mask. */
1183static void add_trigger_function(enum triggerop oper, enum triggerfunc func,
1184 int index, int neg, uint16_t *mask)
1185{
1186 int i, j;
1187 int x[2][2], tmp, a, b, aset, bset, rset;
1188
1189 memset(x, 0, 4 * sizeof(int));
1190
1191 /* Trigger detect condition. */
1192 switch (oper) {
1193 case OP_LEVEL:
1194 x[0][1] = 1;
1195 x[1][1] = 1;
1196 break;
1197 case OP_NOT:
1198 x[0][0] = 1;
1199 x[1][0] = 1;
1200 break;
1201 case OP_RISE:
1202 x[0][1] = 1;
1203 break;
1204 case OP_FALL:
1205 x[1][0] = 1;
1206 break;
1207 case OP_RISEFALL:
1208 x[0][1] = 1;
1209 x[1][0] = 1;
1210 break;
1211 case OP_NOTRISE:
1212 x[1][1] = 1;
1213 x[0][0] = 1;
1214 x[1][0] = 1;
1215 break;
1216 case OP_NOTFALL:
1217 x[1][1] = 1;
1218 x[0][0] = 1;
1219 x[0][1] = 1;
1220 break;
1221 case OP_NOTRISEFALL:
1222 x[1][1] = 1;
1223 x[0][0] = 1;
1224 break;
1225 }
1226
1227 /* Transpose if neg is set. */
1228 if (neg) {
1229 for (i = 0; i < 2; i++) {
1230 for (j = 0; j < 2; j++) {
1231 tmp = x[i][j];
1232 x[i][j] = x[1 - i][1 - j];
1233 x[1 - i][1 - j] = tmp;
1234 }
1235 }
1236 }
1237
1238 /* Update mask with function. */
1239 for (i = 0; i < 16; i++) {
1240 a = (i >> (2 * index + 0)) & 1;
1241 b = (i >> (2 * index + 1)) & 1;
1242
1243 aset = (*mask >> i) & 1;
1244 bset = x[b][a];
1245
1246 rset = 0;
1247 if (func == FUNC_AND || func == FUNC_NAND)
1248 rset = aset & bset;
1249 else if (func == FUNC_OR || func == FUNC_NOR)
1250 rset = aset | bset;
1251 else if (func == FUNC_XOR || func == FUNC_NXOR)
1252 rset = aset ^ bset;
1253
1254 if (func == FUNC_NAND || func == FUNC_NOR || func == FUNC_NXOR)
1255 rset = !rset;
1256
1257 *mask &= ~(1 << i);
1258
1259 if (rset)
1260 *mask |= 1 << i;
1261 }
1262}
1263
1264/*
1265 * Build trigger LUTs used by 50 MHz and lower sample rates for supporting
1266 * simple pin change and state triggers. Only two transitions (rise/fall) can be
1267 * set at any time, but a full mask and value can be set (0/1).
1268 */
1269SR_PRIV int sigma_build_basic_trigger(struct triggerlut *lut, struct dev_context *devc)
1270{
1271 int i,j;
1272 uint16_t masks[2] = { 0, 0 };
1273
1274 memset(lut, 0, sizeof(struct triggerlut));
1275
1276 /* Constant for simple triggers. */
1277 lut->m4 = 0xa000;
1278
1279 /* Value/mask trigger support. */
1280 build_lut_entry(devc->trigger.simplevalue, devc->trigger.simplemask,
1281 lut->m2d);
1282
1283 /* Rise/fall trigger support. */
1284 for (i = 0, j = 0; i < 16; i++) {
1285 if (devc->trigger.risingmask & (1 << i) ||
1286 devc->trigger.fallingmask & (1 << i))
1287 masks[j++] = 1 << i;
1288 }
1289
1290 build_lut_entry(masks[0], masks[0], lut->m0d);
1291 build_lut_entry(masks[1], masks[1], lut->m1d);
1292
1293 /* Add glue logic */
1294 if (masks[0] || masks[1]) {
1295 /* Transition trigger. */
1296 if (masks[0] & devc->trigger.risingmask)
1297 add_trigger_function(OP_RISE, FUNC_OR, 0, 0, &lut->m3);
1298 if (masks[0] & devc->trigger.fallingmask)
1299 add_trigger_function(OP_FALL, FUNC_OR, 0, 0, &lut->m3);
1300 if (masks[1] & devc->trigger.risingmask)
1301 add_trigger_function(OP_RISE, FUNC_OR, 1, 0, &lut->m3);
1302 if (masks[1] & devc->trigger.fallingmask)
1303 add_trigger_function(OP_FALL, FUNC_OR, 1, 0, &lut->m3);
1304 } else {
1305 /* Only value/mask trigger. */
1306 lut->m3 = 0xffff;
1307 }
1308
1309 /* Triggertype: event. */
1310 lut->params.selres = 3;
1311
1312 return SR_OK;
1313}