From fda68c41496b2ab01447438f7816ec6cd4ff37f6 Mon Sep 17 00:00:00 2001 From: Keith Packard Date: Wed, 8 Jul 2020 09:41:22 -0700 Subject: [PATCH] picolibc: Add stdout buffering [v2] Add buffering so that USB back-ends get some batching for stdout Signed-off-by: Keith Packard ---- v2: Replace tabs with spaces. --- sys/picolibc_syscalls_default/syscalls.c | 49 +++++++++++++++++++----- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/sys/picolibc_syscalls_default/syscalls.c b/sys/picolibc_syscalls_default/syscalls.c index 3baa9b3a54..1782610d08 100644 --- a/sys/picolibc_syscalls_default/syscalls.c +++ b/sys/picolibc_syscalls_default/syscalls.c @@ -61,23 +61,54 @@ int kill(pid_t pid, int sig) return -1; } -/* File descriptor pointers */ -int picolibc_get(FILE *file) +#include "mutex.h" + +static mutex_t picolibc_put_mutex = MUTEX_INIT; + +#define PICOLIBC_STDOUT_BUFSIZE 64 + +static char picolibc_stdout[PICOLIBC_STDOUT_BUFSIZE]; +static int picolibc_stdout_queued; + +static void _picolibc_flush(void) +{ + if (picolibc_stdout_queued) { + stdio_write(picolibc_stdout, picolibc_stdout_queued); + picolibc_stdout_queued = 0; + } +} + +static int picolibc_put(char c, FILE *file) { (void)file; + mutex_lock(&picolibc_put_mutex); + picolibc_stdout[picolibc_stdout_queued++] = c; + if (picolibc_stdout_queued == PICOLIBC_STDOUT_BUFSIZE || c == '\n') + _picolibc_flush(); + mutex_unlock(&picolibc_put_mutex); + return 1; +} + +static int picolibc_flush(FILE *file) +{ + (void)file; + mutex_lock(&picolibc_put_mutex); + _picolibc_flush(); + mutex_unlock(&picolibc_put_mutex); + return 0; +} + +static int picolibc_get(FILE *file) +{ + (void)file; + picolibc_flush(NULL); char c = 0; stdio_read(&c, 1); return c; } -int picolibc_put(char c, FILE *file) -{ - (void)file; - stdio_write(&c, 1); - return 1; -} FILE picolibc_stdio = - FDEV_SETUP_STREAM(picolibc_put, picolibc_get, NULL, _FDEV_SETUP_RW); + FDEV_SETUP_STREAM(picolibc_put, picolibc_get, picolibc_flush, _FDEV_SETUP_RW); FILE *const __iob[] = { &picolibc_stdio, /* stdin */