1/*	$OpenBSD: qcrng.c,v 1.1 2023/04/28 05:13:37 phessler Exp $	*/
2/*
3 * Copyright (c) 2019 Mark Kettenis <kettenis@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18#include <sys/param.h>
19#include <sys/systm.h>
20#include <sys/device.h>
21#include <sys/timeout.h>
22
23#include <machine/bus.h>
24#include <machine/fdt.h>
25
26#include <dev/ofw/openfirm.h>
27#include <dev/ofw/fdt.h>
28
29/* Registers */
30#define RNG_DATA		0x0000
31#define RNG_STATUS		0x0004
32
33#define HREAD4(sc, reg)							\
34	(bus_space_read_4((sc)->sc_iot, (sc)->sc_ioh, (reg)))
35
36struct qcrng_softc {
37	struct device		sc_dev;
38	bus_space_tag_t		sc_iot;
39	bus_space_handle_t	sc_ioh;
40
41	struct timeout		sc_to;
42};
43
44int	qcrng_match(struct device *, void *, void *);
45void	qcrng_attach(struct device *, struct device *, void *);
46
47const struct cfattach	qcrng_ca = {
48	sizeof (struct qcrng_softc), qcrng_match, qcrng_attach
49};
50
51struct cfdriver qcrng_cd = {
52	NULL, "qcrng", DV_DULL
53};
54
55void	qcrng_rnd(void *);
56
57int
58qcrng_match(struct device *parent, void *match, void *aux)
59{
60	struct fdt_attach_args *faa = aux;
61
62	return OF_is_compatible(faa->fa_node, "qcom,prng-ee");
63}
64
65void
66qcrng_attach(struct device *parent, struct device *self, void *aux)
67{
68	struct qcrng_softc *sc = (struct qcrng_softc *)self;
69	struct fdt_attach_args *faa = aux;
70
71	if (faa->fa_nreg < 1) {
72		printf(": no registers\n");
73		return;
74	}
75
76	sc->sc_iot = faa->fa_iot;
77	if (bus_space_map(sc->sc_iot, faa->fa_reg[0].addr,
78	    faa->fa_reg[0].size, 0, &sc->sc_ioh)) {
79		printf(": can't map registers\n");
80		return;
81	}
82
83	printf("\n");
84
85	timeout_set(&sc->sc_to, qcrng_rnd, sc);
86	qcrng_rnd(sc);
87}
88
89void
90qcrng_rnd(void *arg)
91{
92	struct qcrng_softc *sc = arg;
93
94	if (HREAD4(sc, RNG_STATUS) & 0x1)
95		enqueue_randomness(HREAD4(sc, RNG_DATA));
96
97	timeout_add_sec(&sc->sc_to, 1);
98}
99