xref: /qemu/hw/virtio/virtio-rng.c (revision 2f780b6a91fe99652266004bf78191ceddfae09c)
1 /*
2  * A virtio device implementing a hardware random number generator.
3  *
4  * Copyright 2012 Red Hat, Inc.
5  * Copyright 2012 Amit Shah <amit.shah@redhat.com>
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or
8  * (at your option) any later version.  See the COPYING file in the
9  * top-level directory.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qapi/error.h"
14 #include "qemu/iov.h"
15 #include "qemu/module.h"
16 #include "hw/virtio/virtio.h"
17 #include "hw/qdev-properties.h"
18 #include "hw/virtio/virtio-rng.h"
19 #include "sysemu/rng.h"
20 #include "sysemu/sysemu.h"
21 #include "qom/object_interfaces.h"
22 #include "trace.h"
23 
24 static bool is_guest_ready(VirtIORNG *vrng)
25 {
26     VirtIODevice *vdev = VIRTIO_DEVICE(vrng);
27     if (virtio_queue_ready(vrng->vq)
28         && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
29         return true;
30     }
31     trace_virtio_rng_guest_not_ready(vrng);
32     return false;
33 }
34 
35 static size_t get_request_size(VirtQueue *vq, unsigned quota)
36 {
37     unsigned int in, out;
38 
39     virtqueue_get_avail_bytes(vq, &in, &out, quota, 0);
40     return in;
41 }
42 
43 static void virtio_rng_process(VirtIORNG *vrng);
44 
45 /* Send data from a char device over to the guest */
46 static void chr_read(void *opaque, const void *buf, size_t size)
47 {
48     VirtIORNG *vrng = opaque;
49     VirtIODevice *vdev = VIRTIO_DEVICE(vrng);
50     VirtQueueElement *elem;
51     size_t len;
52     int offset;
53 
54     if (!is_guest_ready(vrng)) {
55         return;
56     }
57 
58     /* we can't modify the virtqueue until
59      * our state is fully synced
60      */
61 
62     if (!runstate_check(RUN_STATE_RUNNING)) {
63         trace_virtio_rng_cpu_is_stopped(vrng, size);
64         return;
65     }
66 
67     vrng->quota_remaining -= size;
68 
69     offset = 0;
70     while (offset < size) {
71         elem = virtqueue_pop(vrng->vq, sizeof(VirtQueueElement));
72         if (!elem) {
73             break;
74         }
75         trace_virtio_rng_popped(vrng);
76         len = iov_from_buf(elem->in_sg, elem->in_num,
77                            0, buf + offset, size - offset);
78         offset += len;
79 
80         virtqueue_push(vrng->vq, elem, len);
81         trace_virtio_rng_pushed(vrng, len);
82         g_free(elem);
83     }
84     virtio_notify(vdev, vrng->vq);
85 
86     if (!virtio_queue_empty(vrng->vq)) {
87         /* If we didn't drain the queue, call virtio_rng_process
88          * to take care of asking for more data as appropriate.
89          */
90         virtio_rng_process(vrng);
91     }
92 }
93 
94 static void virtio_rng_process(VirtIORNG *vrng)
95 {
96     size_t size;
97     unsigned quota;
98 
99     if (!is_guest_ready(vrng)) {
100         return;
101     }
102 
103     if (vrng->activate_timer) {
104         timer_mod(vrng->rate_limit_timer,
105                   qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vrng->conf.period_ms);
106         vrng->activate_timer = false;
107     }
108 
109     if (vrng->quota_remaining < 0) {
110         quota = 0;
111     } else {
112         quota = MIN((uint64_t)vrng->quota_remaining, (uint64_t)UINT32_MAX);
113     }
114     size = get_request_size(vrng->vq, quota);
115 
116     trace_virtio_rng_request(vrng, size, quota);
117 
118     size = MIN(vrng->quota_remaining, size);
119     if (size) {
120         rng_backend_request_entropy(vrng->rng, size, chr_read, vrng);
121     }
122 }
123 
124 static void handle_input(VirtIODevice *vdev, VirtQueue *vq)
125 {
126     VirtIORNG *vrng = VIRTIO_RNG(vdev);
127     virtio_rng_process(vrng);
128 }
129 
130 static uint64_t get_features(VirtIODevice *vdev, uint64_t f, Error **errp)
131 {
132     return f;
133 }
134 
135 static void virtio_rng_vm_state_change(void *opaque, int running,
136                                        RunState state)
137 {
138     VirtIORNG *vrng = opaque;
139 
140     trace_virtio_rng_vm_state_change(vrng, running, state);
141 
142     /* We may have an element ready but couldn't process it due to a quota
143      * limit or because CPU was stopped.  Make sure to try again when the
144      * CPU restart.
145      */
146 
147     if (running && is_guest_ready(vrng)) {
148         virtio_rng_process(vrng);
149     }
150 }
151 
152 static void check_rate_limit(void *opaque)
153 {
154     VirtIORNG *vrng = opaque;
155 
156     vrng->quota_remaining = vrng->conf.max_bytes;
157     virtio_rng_process(vrng);
158     vrng->activate_timer = true;
159 }
160 
161 static void virtio_rng_set_status(VirtIODevice *vdev, uint8_t status)
162 {
163     VirtIORNG *vrng = VIRTIO_RNG(vdev);
164 
165     if (!vdev->vm_running) {
166         return;
167     }
168     vdev->status = status;
169 
170     /* Something changed, try to process buffers */
171     virtio_rng_process(vrng);
172 }
173 
174 static void virtio_rng_device_realize(DeviceState *dev, Error **errp)
175 {
176     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
177     VirtIORNG *vrng = VIRTIO_RNG(dev);
178     Error *local_err = NULL;
179 
180     if (vrng->conf.period_ms <= 0) {
181         error_setg(errp, "'period' parameter expects a positive integer");
182         return;
183     }
184 
185     /* Workaround: Property parsing does not enforce unsigned integers,
186      * So this is a hack to reject such numbers. */
187     if (vrng->conf.max_bytes > INT64_MAX) {
188         error_setg(errp, "'max-bytes' parameter must be non-negative, "
189                    "and less than 2^63");
190         return;
191     }
192 
193     if (vrng->conf.rng == NULL) {
194         vrng->conf.default_backend = RNG_RANDOM(object_new(TYPE_RNG_RANDOM));
195 
196         user_creatable_complete(USER_CREATABLE(vrng->conf.default_backend),
197                                 &local_err);
198         if (local_err) {
199             error_propagate(errp, local_err);
200             object_unref(OBJECT(vrng->conf.default_backend));
201             return;
202         }
203 
204         object_property_add_child(OBJECT(dev),
205                                   "default-backend",
206                                   OBJECT(vrng->conf.default_backend),
207                                   NULL);
208 
209         /* The child property took a reference, we can safely drop ours now */
210         object_unref(OBJECT(vrng->conf.default_backend));
211 
212         object_property_set_link(OBJECT(dev),
213                                  OBJECT(vrng->conf.default_backend),
214                                  "rng", NULL);
215     }
216 
217     vrng->rng = vrng->conf.rng;
218     if (vrng->rng == NULL) {
219         error_setg(errp, "'rng' parameter expects a valid object");
220         return;
221     }
222 
223     virtio_init(vdev, "virtio-rng", VIRTIO_ID_RNG, 0);
224 
225     vrng->vq = virtio_add_queue(vdev, 8, handle_input);
226     vrng->quota_remaining = vrng->conf.max_bytes;
227     vrng->rate_limit_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
228                                                check_rate_limit, vrng);
229     vrng->activate_timer = true;
230 
231     vrng->vmstate = qemu_add_vm_change_state_handler(virtio_rng_vm_state_change,
232                                                      vrng);
233 }
234 
235 static void virtio_rng_device_unrealize(DeviceState *dev, Error **errp)
236 {
237     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
238     VirtIORNG *vrng = VIRTIO_RNG(dev);
239 
240     qemu_del_vm_change_state_handler(vrng->vmstate);
241     timer_del(vrng->rate_limit_timer);
242     timer_free(vrng->rate_limit_timer);
243     virtio_cleanup(vdev);
244 }
245 
246 static const VMStateDescription vmstate_virtio_rng = {
247     .name = "virtio-rng",
248     .minimum_version_id = 1,
249     .version_id = 1,
250     .fields = (VMStateField[]) {
251         VMSTATE_VIRTIO_DEVICE,
252         VMSTATE_END_OF_LIST()
253     },
254 };
255 
256 static Property virtio_rng_properties[] = {
257     /* Set a default rate limit of 2^47 bytes per minute or roughly 2TB/s.  If
258      * you have an entropy source capable of generating more entropy than this
259      * and you can pass it through via virtio-rng, then hats off to you.  Until
260      * then, this is unlimited for all practical purposes.
261      */
262     DEFINE_PROP_UINT64("max-bytes", VirtIORNG, conf.max_bytes, INT64_MAX),
263     DEFINE_PROP_UINT32("period", VirtIORNG, conf.period_ms, 1 << 16),
264     DEFINE_PROP_LINK("rng", VirtIORNG, conf.rng, TYPE_RNG_BACKEND, RngBackend *),
265     DEFINE_PROP_END_OF_LIST(),
266 };
267 
268 static void virtio_rng_class_init(ObjectClass *klass, void *data)
269 {
270     DeviceClass *dc = DEVICE_CLASS(klass);
271     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
272 
273     dc->props = virtio_rng_properties;
274     dc->vmsd = &vmstate_virtio_rng;
275     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
276     vdc->realize = virtio_rng_device_realize;
277     vdc->unrealize = virtio_rng_device_unrealize;
278     vdc->get_features = get_features;
279     vdc->set_status = virtio_rng_set_status;
280 }
281 
282 static const TypeInfo virtio_rng_info = {
283     .name = TYPE_VIRTIO_RNG,
284     .parent = TYPE_VIRTIO_DEVICE,
285     .instance_size = sizeof(VirtIORNG),
286     .class_init = virtio_rng_class_init,
287 };
288 
289 static void virtio_register_types(void)
290 {
291     type_register_static(&virtio_rng_info);
292 }
293 
294 type_init(virtio_register_types)
295