xref: /openbmc/qemu/backends/rng-builtin.c (revision 9739b11a)
1 /*
2  * QEMU Builtin Random Number Generator Backend
3  *
4  * This work is licensed under the terms of the GNU GPL, version 2 or later.
5  * See the COPYING file in the top-level directory.
6  */
7 
8 #include "qemu/osdep.h"
9 #include "sysemu/rng.h"
10 #include "qemu/main-loop.h"
11 #include "qemu/guest-random.h"
12 
13 #define RNG_BUILTIN(obj) OBJECT_CHECK(RngBuiltin, (obj), TYPE_RNG_BUILTIN)
14 
15 typedef struct RngBuiltin {
16     RngBackend parent;
17     QEMUBH *bh;
18 } RngBuiltin;
19 
20 static void rng_builtin_receive_entropy_bh(void *opaque)
21 {
22     RngBuiltin *s = opaque;
23 
24     while (!QSIMPLEQ_EMPTY(&s->parent.requests)) {
25         RngRequest *req = QSIMPLEQ_FIRST(&s->parent.requests);
26 
27         qemu_guest_getrandom_nofail(req->data, req->size);
28 
29         req->receive_entropy(req->opaque, req->data, req->size);
30 
31         rng_backend_finalize_request(&s->parent, req);
32     }
33 }
34 
35 static void rng_builtin_request_entropy(RngBackend *b, RngRequest *req)
36 {
37     RngBuiltin *s = RNG_BUILTIN(b);
38 
39     qemu_bh_schedule(s->bh);
40 }
41 
42 static void rng_builtin_init(Object *obj)
43 {
44     RngBuiltin *s = RNG_BUILTIN(obj);
45 
46     s->bh = qemu_bh_new(rng_builtin_receive_entropy_bh, s);
47 }
48 
49 static void rng_builtin_finalize(Object *obj)
50 {
51     RngBuiltin *s = RNG_BUILTIN(obj);
52 
53     qemu_bh_delete(s->bh);
54 }
55 
56 static void rng_builtin_class_init(ObjectClass *klass, void *data)
57 {
58     RngBackendClass *rbc = RNG_BACKEND_CLASS(klass);
59 
60     rbc->request_entropy = rng_builtin_request_entropy;
61 }
62 
63 static const TypeInfo rng_builtin_info = {
64     .name = TYPE_RNG_BUILTIN,
65     .parent = TYPE_RNG_BACKEND,
66     .instance_size = sizeof(RngBuiltin),
67     .instance_init = rng_builtin_init,
68     .instance_finalize = rng_builtin_finalize,
69     .class_init = rng_builtin_class_init,
70 };
71 
72 static void register_types(void)
73 {
74     type_register_static(&rng_builtin_info);
75 }
76 
77 type_init(register_types);
78