Skip to content

Commit

Permalink
virtio: handle short buffers in virtio_rng.
Browse files Browse the repository at this point in the history
If the device fills less than 4 bytes of our random buffer, we'll
BUG_ON.  It's nicer to handle the case where it partially fills the
buffer (the protocol doesn't explicitly bad that).

Signed-off-by: Rusty Russell <[email protected]>
  • Loading branch information
rustyrussell committed Jun 12, 2009
1 parent 98e9444 commit 594de1d
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions drivers/char/hw_random/virtio-rng.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,21 @@ static DECLARE_COMPLETION(have_data);

static void random_recv_done(struct virtqueue *vq)
{
int len;
unsigned int len;

/* We can get spurious callbacks, e.g. shared IRQs + virtio_pci. */
if (!vq->vq_ops->get_buf(vq, &len))
return;

data_left = len / sizeof(random_data[0]);
data_left += len;
complete(&have_data);
}

static void register_buffer(void)
{
struct scatterlist sg;

sg_init_one(&sg, random_data, RANDOM_DATA_SIZE);
sg_init_one(&sg, random_data+data_left, RANDOM_DATA_SIZE-data_left);
/* There should always be room for one buffer. */
if (vq->vq_ops->add_buf(vq, &sg, 0, 1, random_data) != 0)
BUG();
Expand All @@ -59,24 +59,32 @@ static void register_buffer(void)
/* At least we don't udelay() in a loop like some other drivers. */
static int virtio_data_present(struct hwrng *rng, int wait)
{
if (data_left)
if (data_left >= sizeof(u32))
return 1;

again:
if (!wait)
return 0;

wait_for_completion(&have_data);

/* Not enough? Re-register. */
if (unlikely(data_left < sizeof(u32))) {
register_buffer();
goto again;
}

return 1;
}

/* virtio_data_present() must have succeeded before this is called. */
static int virtio_data_read(struct hwrng *rng, u32 *data)
{
BUG_ON(!data_left);

*data = random_data[--data_left];
BUG_ON(data_left < sizeof(u32));
data_left -= sizeof(u32);
*data = random_data[data_left / 4];

if (!data_left) {
if (data_left < sizeof(u32)) {
init_completion(&have_data);
register_buffer();
}
Expand Down

0 comments on commit 594de1d

Please sign in to comment.