summaryrefslogtreecommitdiffstats
path: root/drivers/serial/serial_sbi.c
blob: dd3eef41d1c937cc81bd70c8f88f19093e4ccf0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (C) 2021 Marcelo Politzer <marcelo.politzer@cartesi.io>
 */

#include <common.h>
#include <driver.h>
#include <malloc.h>
#include <asm/sbi.h>

struct sbi_serial_priv {
	struct console_device cdev;
	uint8_t b[2], head, tail;
};

static int sbi_serial_getc(struct console_device *cdev)
{
	struct sbi_serial_priv *priv = cdev->dev->priv;
	if (priv->head == priv->tail)
		return -1;
	return priv->b[priv->head++ & 0x1];
}

static void sbi_serial_putc(struct console_device *cdev, const char ch)
{
	sbi_console_putchar(ch);
}

static int sbi_serial_tstc(struct console_device *cdev)
{
	struct sbi_serial_priv *priv = cdev->dev->priv;
	int c = sbi_console_getchar();

	if (c != -1)
		priv->b[priv->tail++ & 0x1] = c;
	return priv->head != priv->tail;
}

static int sbi_serial_probe(struct device *dev)
{
	struct sbi_serial_priv *priv;

	priv = dev->priv = xzalloc(sizeof(*priv));
	priv->cdev.dev    = dev;
	priv->cdev.putc   = sbi_serial_putc;
	priv->cdev.getc   = sbi_serial_getc;
	priv->cdev.tstc   = sbi_serial_tstc;
	priv->cdev.flush  = 0;
	priv->cdev.setbrg = 0;

	return console_register(&priv->cdev);
}

static struct driver serial_sbi_driver = {
	.name   = "riscv-serial-sbi",
	.probe  = sbi_serial_probe,
};
postcore_platform_driver(serial_sbi_driver);