Files
templates/tools/dsview/zynq-ethernet/zynq_record.c
T

504 lines
19 KiB
C

/* SPDX-License-Identifier: GPL-3.0-or-later */
#include "zynq_record.h"
#include <gio/gio.h>
#include <glib/gstdio.h>
#include <minizip/zip.h>
#include <minizip/unzip.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "../../log.h"
#include "libsigrok.h"
/* DSView DSL v3 uses 16 Mi samples per channel leaf. One ZIP64 archive
* receives all leaves, with one leaf per channel held in RAM. */
#define LEAF_BYTES (2u * 1024u * 1024u)
#define QUEUE_BYTES (64u * 1024u * 1024u)
struct zynq_recorder {
unsigned clock, divider, mask, channels;
GAsyncQueue *queue;
GThread *thread;
gint queued, failed;
char stop;
gboolean compress;
gboolean published;
uint8_t *planes;
size_t used;
unsigned leaves;
uint64_t samples, first_sample;
GArray *tiles;
zipFile archive;
char *file, *partial;
};
struct chunk {
size_t size;
size_t samples;
uint8_t data[];
};
static void fail(struct zynq_recorder *r, const char *reason)
{
if (g_atomic_int_compare_and_exchange(&r->failed, 0, 1))
sr_err("RJ2 recording %s: %s", r->file, reason);
}
static voidpf ZCALLBACK open_utf8(voidpf opaque, const void *name, int mode)
{
(void)opaque;
return g_fopen(name, mode & ZLIB_FILEFUNC_MODE_CREATE ? "wb" : "rb");
}
static gboolean entry(zipFile archive, const char *name, const void *data, unsigned size, int level)
{
if (zipOpenNewFileInZip(archive, name, NULL, NULL, 0, NULL, 0, NULL,
level ? Z_DEFLATED : 0, level) != ZIP_OK)
return FALSE;
int written = zipWriteInFileInZip(archive, data, size);
return zipCloseFileInZip(archive) == ZIP_OK && written == ZIP_OK;
}
static gboolean begin_file(struct zynq_recorder *r)
{
r->partial = g_strconcat(r->file, ".part-XXXXXX", NULL);
int fd = g_mkstemp(r->partial);
if (fd < 0) {
g_clear_pointer(&r->partial, g_free);
return FALSE;
}
close(fd);
zlib_filefunc64_def io;
fill_fopen64_filefunc(&io);
io.zopen64_file = open_utf8;
r->archive = zipOpen2_64(r->partial, APPEND_STATUS_CREATE, NULL, &io);
return r->archive != NULL;
}
static void summarize_plane(struct ds_zynq_tile *summary, const uint8_t *plane,
unsigned samples, unsigned mask)
{
for (unsigned offset = 0; offset < samples; offset += DS_ZYNQ_TILE_SAMPLES, summary++) {
const unsigned count = MIN(DS_ZYNQ_TILE_SAMPLES, samples - offset);
const uint8_t *data = plane + offset / 8;
const gboolean first = data[0] & 1;
if (first)
summary->first |= mask;
if ((data[(count - 1) / 8] >> ((count - 1) % 8)) & 1)
summary->last |= mask;
const uint8_t expected = first ? 255 : 0;
unsigned i = 0;
while (i < count / 8 && data[i] == expected)
i++;
if (i < count / 8 || ((count % 8) && ((data[i] ^ expected) & ((1u << (count % 8)) - 1))))
summary->changes |= mask;
}
}
static gboolean write_leaf(struct zynq_recorder *r)
{
if (!r->archive && !begin_file(r))
return FALSE;
const unsigned samples = MIN(r->samples - (uint64_t)r->leaves * LEAF_BYTES * 8, r->used * 8);
const unsigned tile_count = (samples + DS_ZYNQ_TILE_SAMPLES - 1) / DS_ZYNQ_TILE_SAMPLES;
const unsigned first_tile = r->tiles->len;
g_array_set_size(r->tiles, first_tile + tile_count);
unsigned bit = 0;
for (unsigned channel = 0; channel < r->channels; channel++) {
while (!(r->mask & (1u << bit)))
bit++;
const uint8_t *plane = r->planes + channel * LEAF_BYTES;
summarize_plane(&g_array_index(r->tiles, struct ds_zynq_tile, first_tile),
plane, samples, 1u << bit++);
char name[32];
g_snprintf(name, sizeof(name), "L-%u/%u", channel, r->leaves);
if (!entry(r->archive, name, r->planes + channel * LEAF_BYTES, r->used, r->compress ? 1 : 0))
return FALSE;
}
r->leaves++;
r->used = 0;
return TRUE;
}
static gboolean publish_file(struct zynq_recorder *r)
{
unsigned rate = r->clock / r->divider;
GString *header = g_string_new("[version]\nversion = 3\n[header]\n"
"driver = virtual-session\ndevice mode = 0\ncapturefile = data\n");
g_string_append_printf(header, "total samples = %" G_GUINT64_FORMAT
"\ntotal probes = %u\ntotal blocks = %u\nsamplerate = %u Hz\n"
"trigger time = 0\ntrigger pos = 0\n", r->samples, r->channels, r->leaves, rate);
GString *session = g_string_new("{\"Device\":\"virtual-session\",\"DeviceMode\":0,"
"\"Version\":3,\"Title\":\"DSView v1.3.2\",\"Max Height\":\"1X\",\"decoder\":[],");
g_string_append_printf(session, "\"Sample count\":\"%" G_GUINT64_FORMAT
"\",\"Sample rate\":\"%u\",\"channel\":[", r->samples, rate);
unsigned dense = 0;
for (unsigned channel = 0; channel < 8; channel++) {
if (!(r->mask & (1u << channel)))
continue;
g_string_append_printf(header, "probe%u = D%u\n", dense, channel);
g_string_append_printf(session, "%s{\"colour\":\"default\",\"enabled\":true,"
"\"index\":%u,\"name\":\"D%u\",\"strigger\":0,\"type\":10000,\"view_index\":%u}",
dense ? "," : "", dense, channel, dense);
dense++;
}
g_string_append(session, "]}");
char *info = g_strdup_printf("{\"first_sample\":%" G_GUINT64_FORMAT ",\"samples\":%" G_GUINT64_FORMAT
",\"clock_hz\":%u,\"divider\":%u,\"mask\":%u,\"leaf_samples\":%u}",
r->first_sample, r->samples, r->clock, r->divider, r->mask, LEAF_BYTES * 8);
gboolean ok = entry(r->archive, "header", header->str, header->len, 0) &&
entry(r->archive, "session", session->str, session->len, 0) &&
entry(r->archive, "decoders", "[]", 2, 0) &&
entry(r->archive, "zynq_recording.json", info, strlen(info), 0) &&
(!r->tiles || entry(r->archive, "zynq_tiles.bin", r->tiles->data,
r->tiles->len * sizeof(struct ds_zynq_tile), 0));
g_free(info);
g_string_free(session, TRUE);
g_string_free(header, TRUE);
ok = zipClose(r->archive, NULL) == ZIP_OK && ok;
r->archive = NULL;
if (!ok)
return FALSE;
GFile *source = g_file_new_for_path(r->partial);
GFile *target = g_file_new_for_path(r->file);
ok = g_file_move(source, target, G_FILE_COPY_NONE, NULL, NULL, NULL, NULL);
g_object_unref(target);
g_object_unref(source);
if (ok) {
r->published = TRUE;
g_clear_pointer(&r->partial, g_free);
}
return ok;
}
static gboolean append(struct zynq_recorder *r, const struct chunk *chunk)
{
size_t stride = 8 * r->channels;
r->samples += chunk->samples;
for (size_t offset = 0; offset < chunk->size; offset += stride) {
for (unsigned channel = 0; channel < r->channels; channel++)
memcpy(r->planes + channel * LEAF_BYTES + r->used,
chunk->data + offset + channel * 8, 8);
r->used += 8;
if (r->used == LEAF_BYTES && !write_leaf(r))
return FALSE;
}
return TRUE;
}
static gpointer writer(gpointer context)
{
struct zynq_recorder *r = context;
gpointer item;
gboolean disk_ok = TRUE;
while ((item = g_async_queue_pop(r->queue)) != &r->stop) {
struct chunk *chunk = item;
if (disk_ok && !append(r, chunk)) {
disk_ok = FALSE;
fail(r, "disk write failed or the disk is full");
}
g_atomic_int_add(&r->queued, -(gint)chunk->size);
g_free(chunk);
}
if (disk_ok && ((r->used && !write_leaf(r)) ||
(r->samples && !publish_file(r))))
fail(r, "could not finish the DSL file");
if (r->archive)
zipClose(r->archive, NULL);
if (r->partial && !zynq_record_failed(r))
g_unlink(r->partial);
return NULL;
}
struct zynq_recorder *zynq_record_open(const char *file, uint32_t clock,
unsigned divider, unsigned mask, gboolean compress)
{
struct zynq_recorder *r = g_new0(struct zynq_recorder, 1);
r->clock = clock;
r->divider = divider;
r->mask = mask;
r->compress = compress;
for (unsigned channel = 0; channel < 8; channel++)
r->channels += (mask >> channel) & 1u;
r->planes = g_try_malloc_n(r->channels, LEAF_BYTES);
r->file = g_strdup(file);
if (!r->planes || g_file_test(file, G_FILE_TEST_EXISTS) || !begin_file(r)) {
sr_err("Could not create RJ2 recording %s", file);
if (r->partial)
g_unlink(r->partial);
g_free(r->partial);
g_free(r->file);
g_free(r->planes);
g_free(r);
return NULL;
}
sr_info("RJ2 recording file: %s", r->file);
r->tiles = g_array_new(FALSE, TRUE, sizeof(struct ds_zynq_tile));
r->queue = g_async_queue_new();
r->thread = g_thread_new("zynq-disk", writer, r);
return r;
}
gboolean zynq_record_failed(const struct zynq_recorder *r)
{
return r && g_atomic_int_get(&r->failed);
}
gboolean zynq_record_write(struct zynq_recorder *r, const void *data, size_t size, size_t samples)
{
if (!r)
return TRUE;
if (zynq_record_failed(r))
return FALSE;
struct chunk *chunk = NULL;
if (size <= QUEUE_BYTES - (unsigned)g_atomic_int_get(&r->queued))
chunk = g_try_malloc(sizeof(*chunk) + size);
if (!chunk) {
fail(r, "disk queue could not keep up with capture");
return FALSE;
}
chunk->size = size;
chunk->samples = samples;
memcpy(chunk->data, data, size);
g_atomic_int_add(&r->queued, size);
g_async_queue_push(r->queue, chunk);
return TRUE;
}
gboolean zynq_record_close(struct zynq_recorder *r, gboolean *published)
{
if (published)
*published = FALSE;
if (!r)
return TRUE;
g_async_queue_push(r->queue, &r->stop);
g_thread_join(r->thread);
gboolean ok = !zynq_record_failed(r);
if (published)
*published = r->published;
g_array_unref(r->tiles);
g_async_queue_unref(r->queue);
g_free(r->planes);
g_free(r->partial);
g_free(r->file);
g_free(r);
return ok;
}
static unzFile open_capture(const char *path)
{
zlib_filefunc64_def io;
fill_fopen64_filefunc(&io);
io.zopen64_file = open_utf8;
return unzOpen2_64(path, &io);
}
static gboolean read_info(unzFile archive, struct ds_zynq_record_info *info)
{
if (unzLocateFile(archive, "zynq_recording.json", 0) != UNZ_OK ||
unzOpenCurrentFile(archive) != UNZ_OK)
return FALSE;
char json[256] = {0};
int bytes = unzReadCurrentFile(archive, json, sizeof(json) - 1);
if (unzCloseCurrentFile(archive) != UNZ_OK || bytes <= 0)
return FALSE;
uint64_t first;
return sscanf(json, "{\"first_sample\":%" G_GUINT64_FORMAT ",\"samples\":%" G_GUINT64_FORMAT
",\"clock_hz\":%u,\"divider\":%u,\"mask\":%u,\"leaf_samples\":%u}",
&first, &info->samples, &info->clock, &info->divider, &info->mask, &info->leaf_samples) == 6 &&
(info->clock == 100000000 || info->clock == 125000000 || info->clock == 200000000) &&
info->divider && info->divider <= 65535 &&
info->mask && info->mask <= 255 && info->samples &&
info->samples <= (uint64_t)G_MAXUINT / 8 * LEAF_BYTES * 8 &&
info->leaf_samples == LEAF_BYTES * 8;
}
SR_API int ds_zynq_record_info(const char *path, struct ds_zynq_record_info *info)
{
unzFile archive = open_capture(path);
if (!archive)
return SR_ERR_NA;
gboolean ok = read_info(archive, info);
if (ok)
info->indexed = unzLocateFile(archive, "zynq_tiles.bin", 0) == UNZ_OK;
unzClose(archive);
return ok ? SR_OK : SR_ERR_NA;
}
struct ds_zynq_disk {
unzFile archive;
struct ds_zynq_record_info info;
unsigned channels, leaves;
struct ds_zynq_tile *tiles;
unz64_file_pos *positions;
};
static gboolean read_member(unzFile archive, void *data, unsigned size)
{
unz_file_info64 info;
if (unzGetCurrentFileInfo64(archive, &info, NULL, 0, NULL, 0, NULL, 0) != UNZ_OK ||
info.uncompressed_size != size || unzOpenCurrentFile(archive) != UNZ_OK)
return FALSE;
int bytes = unzReadCurrentFile(archive, data, size);
return unzCloseCurrentFile(archive) == UNZ_OK && bytes == (int)size;
}
static unsigned leaf_samples(const struct ds_zynq_disk *disk, unsigned leaf)
{
return MIN(disk->info.leaf_samples,
disk->info.samples - (uint64_t)leaf * disk->info.leaf_samples);
}
static gboolean read_leaf_member(unzFile archive, unsigned leaf, unsigned channel,
void *data, unsigned bytes)
{
char name[32], actual[32] = {0};
g_snprintf(name, sizeof(name), "L-%u/%u", channel, leaf);
return unzGetCurrentFileInfo64(archive, NULL, actual, sizeof(actual), NULL, 0, NULL, 0) == UNZ_OK &&
!strncmp(name, actual, sizeof(actual)) && read_member(archive, data, bytes);
}
static gboolean index_leaves(struct ds_zynq_disk *disk)
{
const unsigned entries = disk->channels * disk->leaves;
disk->positions = g_try_new(unz64_file_pos, entries);
if (!disk->positions || unzGoToFirstFile(disk->archive) != UNZ_OK)
return FALSE;
unsigned masks[8], count = 0;
for (unsigned bit = 0; bit < 8; bit++) {
if (disk->info.mask & (1u << bit))
masks[count++] = 1u << bit;
}
// Older archives have the same sample blocks but no saved overview.
// Build it in one sequential read with a single channel block in memory.
g_autofree uint8_t *plane = disk->info.indexed ? NULL : g_try_malloc(LEAF_BYTES);
if (!disk->info.indexed && !plane)
return FALSE;
for (unsigned i = 0; i < entries; i++) {
if (unzGetFilePos64(disk->archive, &disk->positions[i]) != UNZ_OK)
return FALSE;
if (plane) {
const unsigned leaf = i / disk->channels, channel = i % disk->channels;
const unsigned samples = leaf_samples(disk, leaf);
if (!read_leaf_member(disk->archive, leaf, channel, plane, (samples + 63) / 64 * 8))
return FALSE;
const uint64_t first_tile = (uint64_t)leaf * disk->info.leaf_samples / DS_ZYNQ_TILE_SAMPLES;
summarize_plane(disk->tiles + first_tile, plane, samples, masks[channel]);
}
if (i + 1 < entries && unzGoToNextFile(disk->archive) != UNZ_OK)
return FALSE;
}
return TRUE;
}
SR_API struct ds_zynq_disk *ds_zynq_disk_open(const char *path, struct ds_zynq_record_info *info)
{
struct ds_zynq_disk *disk = g_new0(struct ds_zynq_disk, 1);
disk->archive = open_capture(path);
if (!disk->archive || !read_info(disk->archive, &disk->info))
goto error;
const uint64_t tiles = (disk->info.samples + DS_ZYNQ_TILE_SAMPLES - 1) / DS_ZYNQ_TILE_SAMPLES;
if (tiles > G_MAXINT / sizeof(struct ds_zynq_tile))
goto error;
disk->info.indexed = unzLocateFile(disk->archive, "zynq_tiles.bin", 0) == UNZ_OK;
disk->tiles = g_try_new0(struct ds_zynq_tile, tiles);
if (!disk->tiles || (disk->info.indexed &&
!read_member(disk->archive, disk->tiles, tiles * sizeof(struct ds_zynq_tile))))
goto error;
for (unsigned bit = 0; bit < 8; bit++)
disk->channels += (disk->info.mask >> bit) & 1u;
disk->leaves = (disk->info.samples + disk->info.leaf_samples - 1) / disk->info.leaf_samples;
if (!index_leaves(disk))
goto error;
*info = disk->info;
return disk;
error:
ds_zynq_disk_close(disk);
return NULL;
}
SR_API void ds_zynq_disk_close(struct ds_zynq_disk *disk)
{
if (!disk)
return;
if (disk->archive)
unzClose(disk->archive);
g_free(disk->positions);
g_free(disk->tiles);
g_free(disk);
}
SR_API const struct ds_zynq_tile *ds_zynq_disk_tiles(const struct ds_zynq_disk *disk)
{
return disk->tiles;
}
SR_API int ds_zynq_disk_leaf(struct ds_zynq_disk *disk, unsigned leaf, unsigned channel,
void *data, unsigned capacity)
{
if (leaf >= disk->leaves || channel >= disk->channels)
return SR_ERR_ARG;
const unsigned samples = leaf_samples(disk, leaf);
const unsigned bytes = (samples + 63) / 64 * 8;
if (bytes > capacity ||
unzGoToFilePos64(disk->archive, &disk->positions[leaf * disk->channels + channel]) != UNZ_OK ||
!read_leaf_member(disk->archive, leaf, channel, data, bytes))
return SR_ERR;
return SR_OK;
}
SR_API int ds_zynq_record_window(const char *source, const char *target, unsigned first_leaf)
{
struct ds_zynq_record_info info;
unzFile input = open_capture(source);
if (!input)
return SR_ERR;
gboolean ok = read_info(input, &info);
uint64_t first = ok ? (uint64_t)first_leaf * info.leaf_samples : 0;
if (!ok || first >= info.samples || g_file_test(target, G_FILE_TEST_EXISTS)) {
unzClose(input);
return SR_ERR_ARG;
}
struct zynq_recorder output = {.file = (char *)target, .clock = info.clock,
.divider = info.divider, .mask = info.mask, .first_sample = first};
for (unsigned bit = 0; bit < 8; bit++)
output.channels += (info.mask >> bit) & 1u;
output.samples = MIN(info.samples - first, (uint64_t)4 * info.leaf_samples);
output.leaves = (output.samples + info.leaf_samples - 1) / info.leaf_samples;
uint8_t *buffer = g_try_malloc(LEAF_BYTES);
ok = buffer && begin_file(&output) && unzGoToFirstFile(input) == UNZ_OK;
const unsigned skip = first_leaf * output.channels;
for (unsigned i = 0; ok && i < skip; i++)
ok = unzGoToNextFile(input) == UNZ_OK;
for (unsigned leaf = 0; ok && leaf < output.leaves; leaf++) {
const unsigned samples = MIN(info.leaf_samples, output.samples - (uint64_t)leaf * info.leaf_samples);
const unsigned expected = (samples + 63) / 64 * 8;
for (unsigned channel = 0; ok && channel < output.channels; channel++) {
char name[32], actual[32];
g_snprintf(name, sizeof(name), "L-%u/%u", channel, first_leaf + leaf);
unz_file_info64 data_info;
if (unzGetCurrentFileInfo64(input, &data_info, actual, sizeof(actual), NULL, 0, NULL, 0) != UNZ_OK ||
data_info.uncompressed_size != expected || strcmp(name, actual) ||
unzOpenCurrentFile(input) != UNZ_OK) {
ok = FALSE;
break;
}
int received = unzReadCurrentFile(input, buffer, expected);
g_snprintf(name, sizeof(name), "L-%u/%u", channel, leaf);
ok = unzCloseCurrentFile(input) == UNZ_OK && received == (int)expected &&
entry(output.archive, name, buffer, expected, 0) && unzGoToNextFile(input) == UNZ_OK;
}
}
if (ok)
ok = publish_file(&output);
if (output.archive)
zipClose(output.archive, NULL);
if (output.partial)
g_unlink(output.partial);
g_free(output.partial);
g_free(buffer);
unzClose(input);
return ok ? SR_OK : SR_ERR;
}