test_ida: Move ida_check_max
[linux-block.git] / lib / test_ida.c
CommitLineData
8ab8ba38
MW
1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * test_ida.c: Test the IDA API
4 * Copyright (c) 2016-2018 Microsoft Corporation
5 * Copyright (c) 2018 Oracle Corporation
6 * Author: Matthew Wilcox <willy@infradead.org>
7 */
8
9#include <linux/idr.h>
10#include <linux/module.h>
11
12static unsigned int tests_run;
13static unsigned int tests_passed;
14
15#ifdef __KERNEL__
16void ida_dump(struct ida *ida) { }
17#endif
18#define IDA_BUG_ON(ida, x) do { \
19 tests_run++; \
20 if (x) { \
21 ida_dump(ida); \
22 dump_stack(); \
23 } else { \
24 tests_passed++; \
25 } \
26} while (0)
27
0a385639
MW
28/*
29 * Check what happens when we fill a leaf and then delete it. This may
30 * discover mishandling of IDR_FREE.
31 */
32static void ida_check_leaf(struct ida *ida, unsigned int base)
33{
34 unsigned long i;
35
36 for (i = 0; i < IDA_BITMAP_BITS; i++) {
37 IDA_BUG_ON(ida, ida_alloc_min(ida, base, GFP_KERNEL) !=
38 base + i);
39 }
40
41 ida_destroy(ida);
42 IDA_BUG_ON(ida, !ida_is_empty(ida));
43
44 IDA_BUG_ON(ida, ida_alloc(ida, GFP_KERNEL) != 0);
45 IDA_BUG_ON(ida, ida_is_empty(ida));
46 ida_free(ida, 0);
47 IDA_BUG_ON(ida, !ida_is_empty(ida));
48}
49
161b47e3
MW
50/*
51 * Check allocations up to and slightly above the maximum allowed (2^31-1) ID.
52 * Allocating up to 2^31-1 should succeed, and then allocating the next one
53 * should fail.
54 */
55static void ida_check_max(struct ida *ida)
56{
57 unsigned long i, j;
58
59 for (j = 1; j < 65537; j *= 2) {
60 unsigned long base = (1UL << 31) - j;
61 for (i = 0; i < j; i++) {
62 IDA_BUG_ON(ida, ida_alloc_min(ida, base, GFP_KERNEL) !=
63 base + i);
64 }
65 IDA_BUG_ON(ida, ida_alloc_min(ida, base, GFP_KERNEL) !=
66 -ENOSPC);
67 ida_destroy(ida);
68 IDA_BUG_ON(ida, !ida_is_empty(ida));
69 }
70}
71
8ab8ba38
MW
72static int ida_checks(void)
73{
74 DEFINE_IDA(ida);
75
76 IDA_BUG_ON(&ida, !ida_is_empty(&ida));
0a385639
MW
77 ida_check_leaf(&ida, 0);
78 ida_check_leaf(&ida, 1024);
79 ida_check_leaf(&ida, 1024 * 64);
161b47e3 80 ida_check_max(&ida);
8ab8ba38
MW
81
82 printk("IDA: %u of %u tests passed\n", tests_passed, tests_run);
83 return (tests_run != tests_passed) ? 0 : -EINVAL;
84}
85
86static void ida_exit(void)
87{
88}
89
90module_init(ida_checks);
91module_exit(ida_exit);
92MODULE_AUTHOR("Matthew Wilcox <willy@infradead.org>");
93MODULE_LICENSE("GPL");