Skip to content

Commit

Permalink
lib/test_meminit: add checks for the allocation functions
Browse files Browse the repository at this point in the history
alloc_pages(), kmalloc() and vmalloc() are all memory allocation functions
which can return NULL when some internal memory failures happen.  So it is
better to check the return of them to catch the failure in time for better
test them.

Link: https://lkml.kernel.org/r/tencent_D44A49FFB420EDCCBFB9221C8D14DFE12908@qq.com
Signed-off-by: Xiaoke Wang <xkernel.wang@foxmail.com>
Reviewed-by: Alexander Potapenko <glider@google.com>
Cc: Andrey Konovalov <andreyknvl@gmail.com>
Cc: Andrey Ryabinin <ryabinin.a.a@gmail.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Marco Elver <elver@google.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
  • Loading branch information
Xiaoke Wang authored and Andrew Morton committed Sep 27, 2022
1 parent 546f08c commit 016f66a
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/test_meminit.c
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,24 @@ static int __init do_alloc_pages_order(int order, int *total_failures)
size_t size = PAGE_SIZE << order;

page = alloc_pages(GFP_KERNEL, order);
if (!page)
goto err;
buf = page_address(page);
fill_with_garbage(buf, size);
__free_pages(page, order);

page = alloc_pages(GFP_KERNEL, order);
if (!page)
goto err;
buf = page_address(page);
if (count_nonzero_bytes(buf, size))
(*total_failures)++;
fill_with_garbage(buf, size);
__free_pages(page, order);
return 1;
err:
(*total_failures)++;
return 1;
}

/* Test the page allocator by calling alloc_pages with different orders. */
Expand All @@ -100,15 +107,22 @@ static int __init do_kmalloc_size(size_t size, int *total_failures)
void *buf;

buf = kmalloc(size, GFP_KERNEL);
if (!buf)
goto err;
fill_with_garbage(buf, size);
kfree(buf);

buf = kmalloc(size, GFP_KERNEL);
if (!buf)
goto err;
if (count_nonzero_bytes(buf, size))
(*total_failures)++;
fill_with_garbage(buf, size);
kfree(buf);
return 1;
err:
(*total_failures)++;
return 1;
}

/* Test vmalloc() with given parameters. */
Expand All @@ -117,15 +131,22 @@ static int __init do_vmalloc_size(size_t size, int *total_failures)
void *buf;

buf = vmalloc(size);
if (!buf)
goto err;
fill_with_garbage(buf, size);
vfree(buf);

buf = vmalloc(size);
if (!buf)
goto err;
if (count_nonzero_bytes(buf, size))
(*total_failures)++;
fill_with_garbage(buf, size);
vfree(buf);
return 1;
err:
(*total_failures)++;
return 1;
}

/* Test kmalloc()/vmalloc() by allocating objects of different sizes. */
Expand Down

0 comments on commit 016f66a

Please sign in to comment.