xref: /openbmc/qemu/backends/rng-builtin.c (revision ad1a706f)
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 #include "qom/object.h"
13 #include "sysemu/replay.h"
14 
15 OBJECT_DECLARE_SIMPLE_TYPE(RngBuiltin, RNG_BUILTIN)
16 
17 struct RngBuiltin {
18     RngBackend parent;
19     QEMUBH *bh;
20 };
21 
22 static void rng_builtin_receive_entropy_bh(void *opaque)
23 {
24     RngBuiltin *s = opaque;
25 
26     while (!QSIMPLEQ_EMPTY(&s->parent.requests)) {
27         RngRequest *req = QSIMPLEQ_FIRST(&s->parent.requests);
28 
29         qemu_guest_getrandom_nofail(req->data, req->size);
30 
31         req->receive_entropy(req->opaque, req->data, req->size);
32 
33         rng_backend_finalize_request(&s->parent, req);
34     }
35 }
36 
37 static void rng_builtin_request_entropy(RngBackend *b, RngRequest *req)
38 {
39     RngBuiltin *s = RNG_BUILTIN(b);
40 
41     replay_bh_schedule_event(s->bh);
42 }
43 
44 static void rng_builtin_init(Object *obj)
45 {
46     RngBuiltin *s = RNG_BUILTIN(obj);
47 
48     s->bh = qemu_bh_new(rng_builtin_receive_entropy_bh, s);
49 }
50 
51 static void rng_builtin_finalize(Object *obj)
52 {
53     RngBuiltin *s = RNG_BUILTIN(obj);
54 
55     qemu_bh_delete(s->bh);
56 }
57 
58 static void rng_builtin_class_init(ObjectClass *klass, void *data)
59 {
60     RngBackendClass *rbc = RNG_BACKEND_CLASS(klass);
61 
62     rbc->request_entropy = rng_builtin_request_entropy;
63 }
64 
65 static const TypeInfo rng_builtin_info = {
66     .name = TYPE_RNG_BUILTIN,
67     .parent = TYPE_RNG_BACKEND,
68     .instance_size = sizeof(RngBuiltin),
69     .instance_init = rng_builtin_init,
70     .instance_finalize = rng_builtin_finalize,
71     .class_init = rng_builtin_class_init,
72 };
73 
74 static void register_types(void)
75 {
76     type_register_static(&rng_builtin_info);
77 }
78 
79 type_init(register_types);
80