Skip to content

Commit 5209aed

Browse files
committed
random: allow partial reads if later user copies fail
Rather than failing entirely if a copy_to_user() fails at some point, instead we should return a partial read for the amount that succeeded prior, unless none succeeded at all, in which case we return -EFAULT as before. This makes it consistent with other reader interfaces. For example, the following snippet for /dev/zero outputs "4" followed by "1": int fd; void *x = mmap(NULL, 4096, PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); assert(x != MAP_FAILED); fd = open("/dev/zero", O_RDONLY); assert(fd >= 0); printf("%zd\n", read(fd, x, 4)); printf("%zd\n", read(fd, x + 4095, 4)); close(fd); This brings that same standard behavior to the various RNG reader interfaces. While we're at it, we can streamline the loop logic a little bit. Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Cc: Jann Horn <jannh@google.com> Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
1 parent a199448 commit 5209aed

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

drivers/char/random.c

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -523,8 +523,7 @@ EXPORT_SYMBOL(get_random_bytes);
523523

524524
static ssize_t get_random_bytes_user(void __user *buf, size_t nbytes)
525525
{
526-
ssize_t ret = 0;
527-
size_t len;
526+
size_t len, left, ret = 0;
528527
u32 chacha_state[CHACHA_STATE_WORDS];
529528
u8 output[CHACHA_BLOCK_SIZE];
530529

@@ -543,37 +542,40 @@ static ssize_t get_random_bytes_user(void __user *buf, size_t nbytes)
543542
* the user directly.
544543
*/
545544
if (nbytes <= CHACHA_KEY_SIZE) {
546-
ret = copy_to_user(buf, &chacha_state[4], nbytes) ? -EFAULT : nbytes;
545+
ret = nbytes - copy_to_user(buf, &chacha_state[4], nbytes);
547546
goto out_zero_chacha;
548547
}
549548

550-
do {
549+
for (;;) {
551550
chacha20_block(chacha_state, output);
552551
if (unlikely(chacha_state[12] == 0))
553552
++chacha_state[13];
554553

555554
len = min_t(size_t, nbytes, CHACHA_BLOCK_SIZE);
556-
if (copy_to_user(buf, output, len)) {
557-
ret = -EFAULT;
555+
left = copy_to_user(buf, output, len);
556+
if (left) {
557+
ret += len - left;
558558
break;
559559
}
560560

561-
nbytes -= len;
562561
buf += len;
563562
ret += len;
563+
nbytes -= len;
564+
if (!nbytes)
565+
break;
564566

565567
BUILD_BUG_ON(PAGE_SIZE % CHACHA_BLOCK_SIZE != 0);
566-
if (!(ret % PAGE_SIZE) && nbytes) {
568+
if (ret % PAGE_SIZE == 0) {
567569
if (signal_pending(current))
568570
break;
569571
cond_resched();
570572
}
571-
} while (nbytes);
573+
}
572574

573575
memzero_explicit(output, sizeof(output));
574576
out_zero_chacha:
575577
memzero_explicit(chacha_state, sizeof(chacha_state));
576-
return ret;
578+
return ret ? ret : -EFAULT;
577579
}
578580

579581
/*

0 commit comments

Comments
 (0)