1 #include <linux/module.h>
3 /* validate @native and @pcp counter values match @expected */
4 #define CHECK(native, pcp, expected) \
6 WARN((native) != (expected), \
7 "raw %ld (0x%lx) != expected %lld (0x%llx)", \
9 (long long)(expected), (long long)(expected)); \
10 WARN(__this_cpu_read(pcp) != (expected), \
11 "pcp %ld (0x%lx) != expected %lld (0x%llx)", \
12 __this_cpu_read(pcp), __this_cpu_read(pcp), \
13 (long long)(expected), (long long)(expected)); \
16 static DEFINE_PER_CPU(long, long_counter);
17 static DEFINE_PER_CPU(unsigned long, ulong_counter);
19 static int __init percpu_test_init(void)
22 * volatile prevents compiler from optimizing it uses, otherwise the
23 * +ul_one/-ul_one below would replace with inc/dec instructions.
25 volatile unsigned int ui_one = 1;
29 pr_info("percpu test start\n");
34 __this_cpu_add(long_counter, -1);
35 CHECK(l, long_counter, -1);
38 __this_cpu_add(long_counter, 1);
39 CHECK(l, long_counter, 0);
42 __this_cpu_write(ulong_counter, 0);
45 __this_cpu_add(ulong_counter, 1UL);
46 CHECK(ul, ulong_counter, 1);
49 __this_cpu_add(ulong_counter, -1UL);
50 CHECK(ul, ulong_counter, 0);
52 ul += -(unsigned long)1;
53 __this_cpu_add(ulong_counter, -(unsigned long)1);
54 CHECK(ul, ulong_counter, -1);
57 __this_cpu_write(ulong_counter, 0);
60 __this_cpu_dec(ulong_counter);
61 CHECK(ul, ulong_counter, -1);
62 CHECK(ul, ulong_counter, ULONG_MAX);
65 __this_cpu_add(long_counter, -ui_one);
66 CHECK(l, long_counter, 0xffffffff);
69 __this_cpu_add(long_counter, ui_one);
70 CHECK(l, long_counter, (long)0x100000000LL);
74 __this_cpu_write(long_counter, 0);
77 __this_cpu_sub(long_counter, ui_one);
78 CHECK(l, long_counter, -1);
81 __this_cpu_write(long_counter, 0);
84 __this_cpu_add(long_counter, ui_one);
85 CHECK(l, long_counter, 1);
88 __this_cpu_add(long_counter, -ui_one);
89 CHECK(l, long_counter, (long)0x100000000LL);
92 __this_cpu_write(long_counter, 0);
95 this_cpu_sub(long_counter, ui_one);
96 CHECK(l, long_counter, -1);
97 CHECK(l, long_counter, ULONG_MAX);
100 __this_cpu_write(ulong_counter, 0);
103 __this_cpu_add(ulong_counter, ui_one);
104 CHECK(ul, ulong_counter, 1);
107 __this_cpu_write(ulong_counter, 0);
110 __this_cpu_sub(ulong_counter, ui_one);
111 CHECK(ul, ulong_counter, -1);
112 CHECK(ul, ulong_counter, ULONG_MAX);
115 __this_cpu_write(ulong_counter, 3);
117 ul = this_cpu_sub_return(ulong_counter, ui_one);
118 CHECK(ul, ulong_counter, 2);
120 ul = __this_cpu_sub_return(ulong_counter, ui_one);
121 CHECK(ul, ulong_counter, 1);
125 pr_info("percpu test done\n");
126 return -EAGAIN; /* Fail will directly unload the module */
129 static void __exit percpu_test_exit(void)
133 module_init(percpu_test_init)
134 module_exit(percpu_test_exit)
136 MODULE_LICENSE("GPL");
137 MODULE_AUTHOR("Greg Thelen");
138 MODULE_DESCRIPTION("percpu operations test");