lib/rand: fix bug with non uint64_t aligned random buffer fill
authorJens Axboe <axboe@fb.com>
Fri, 5 Dec 2014 17:48:01 +0000 (10:48 -0700)
committerJens Axboe <axboe@fb.com>
Fri, 5 Dec 2014 17:48:01 +0000 (10:48 -0700)
Now that we honor the compression percentage, we can easily
get buffer fills that are not aligned to uint64_t. Make
sure that __fill_random_buf() handles this correctly.

Signed-off-by: Jens Axboe <axboe@fb.com>
lib/rand.c

index 618a2f06349dbc90389971b8720c9ea067024e28..32aec208b6c6fc6a01f1cd1ed1301b157286638a 100644 (file)
@@ -69,11 +69,26 @@ void init_rand_seed(struct frand_state *state, unsigned int seed)
 
 void __fill_random_buf(void *buf, unsigned int len, unsigned long seed)
 {
-       long *ptr = buf;
+       void *ptr = buf;
 
-       while ((void *) ptr - buf < len) {
-               *ptr = seed;
-               ptr++;
+       while (len) {
+               if (len >= sizeof(int64_t)) {
+                       *((int64_t *) ptr) = seed;
+                       ptr += sizeof(int64_t);
+                       len -= sizeof(int64_t);
+               } else if (len >= sizeof(int32_t)) {
+                       *((int32_t *) ptr) = seed;
+                       ptr += sizeof(int32_t);
+                       len -= sizeof(int32_t);
+               } else if (len >= sizeof(int16_t)) {
+                       *((int16_t *) ptr) = seed;
+                       ptr += sizeof(int16_t);
+                       len -= sizeof(int16_t);
+               } else {
+                       *((int8_t *) ptr) = seed;
+                       ptr += sizeof(int8_t);
+                       len -= sizeof(int8_t);
+               }
                seed *= GOLDEN_RATIO_PRIME;
                seed >>= 3;
        }
@@ -146,10 +161,14 @@ void __fill_random_buf_percentage(unsigned long seed, void *buf,
                __fill_random_buf(buf, this_len, seed);
 
                len -= this_len;
+               if (!len)
+                       break;
                buf += this_len;
 
                if (this_len > len)
                        this_len = len;
+               else if (len - this_len <= sizeof(long))
+                       this_len = len;
 
                if (pbytes)
                        fill_pattern(buf, this_len, pattern, pbytes);