1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <kunit/test.h>
3 #include <linux/fdtable.h>
4 #include <linux/file.h>
5
test_alloc_fdtable(struct kunit * test)6 static void test_alloc_fdtable(struct kunit *test)
7 {
8 struct fdtable *fdt;
9 unsigned int slots = 64;
10
11 fdt = alloc_fdtable(slots);
12 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fdt);
13
14 /* Check that max_fds is set correctly and is >= slots */
15 KUNIT_EXPECT_GE(test, fdt->max_fds, slots);
16
17 /* Check that fd is allocated */
18 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fdt->fd);
19
20 /*
21 * Check dynamic object size of fdt->fd if compiler supports
22 * __counted_by_ptr.
23 */
24 #ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
25 KUNIT_EXPECT_EQ(test, __struct_size(fdt->fd),
26 fdt->max_fds * sizeof(struct file *));
27 #endif
28
29 __free_fdtable(fdt);
30 }
31
test_dup_fd(struct kunit * test)32 static void test_dup_fd(struct kunit *test)
33 {
34 struct files_struct *newf;
35 struct fdtable *fdt;
36
37 newf = dup_fd(&init_files, NULL);
38 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, newf);
39
40 fdt = rcu_dereference_raw(newf->fdt);
41 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fdt);
42
43 /* Check that max_fds is set correctly and is >= NR_OPEN_DEFAULT */
44 KUNIT_EXPECT_GE(test, fdt->max_fds, NR_OPEN_DEFAULT);
45
46 /* Check that fd is allocated */
47 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fdt->fd);
48
49 /*
50 * Check dynamic object size of fdt->fd if compiler supports
51 * __counted_by_ptr.
52 */
53 #ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
54 KUNIT_EXPECT_EQ(test, __struct_size(fdt->fd),
55 fdt->max_fds * sizeof(struct file *));
56 #endif
57
58 put_files_struct(newf);
59 }
60
61 static struct kunit_case fdtable_test_cases[] = {
62 KUNIT_CASE(test_alloc_fdtable),
63 KUNIT_CASE(test_dup_fd),
64 {}
65 };
66
67 static struct kunit_suite fdtable_test_suite = {
68 .name = "fdtable",
69 .test_cases = fdtable_test_cases,
70 };
71
72 kunit_test_suite(fdtable_test_suite);
73