xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/readahead/readahead01.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2012 Linux Test Project, Inc.
4  * Copyright (C) 2023-2024 Cyril Hrubis <[email protected]>
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Verify that readahead() syscall fails with:
11  *
12  * - EBADF when fd is not a valid file descriptor or is not open for reading.
13  * - EINVAL when fd does not refer to a file type to which readahead()
14  *          can be applied.
15  */
16 #define _GNU_SOURCE
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 #include <sys/syscall.h>
25 #include <sys/types.h>
26 #include "config.h"
27 #include "tst_test.h"
28 #include "lapi/syscalls.h"
29 
30 #if defined(__NR_readahead)
31 
test_bad_fd(void)32 static void test_bad_fd(void)
33 {
34 	int fd[2];
35 
36 	TST_EXP_FAIL(readahead(-1, 0, getpagesize()), EBADF,
37 	             "readahead() with fd = -1");
38 
39 	SAFE_PIPE(fd);
40 	SAFE_CLOSE(fd[0]);
41 	SAFE_CLOSE(fd[1]);
42 
43 	TST_EXP_FAIL(readahead(fd[0], 0, getpagesize()), EBADF,
44 	             "readahead() with invalid fd");
45 }
46 
test_invalid_fd(struct tst_fd * fd)47 static void test_invalid_fd(struct tst_fd *fd)
48 {
49 
50 	switch (fd->type) {
51 	/* These succeed */
52 	case TST_FD_FILE:
53 	case TST_FD_MEMFD:
54 	case TST_FD_MEMFD_SECRET:
55 	case TST_FD_PROC_MAPS:
56 	case TST_FD_PIDFD:
57 		return;
58 	default:
59 		break;
60 	}
61 
62 	int exp_errnos[] = {EBADF, EINVAL, ESPIPE};
63 
64 	TST_EXP_FAIL_ARR(readahead(fd->fd, 0, getpagesize()), exp_errnos,
65 			ARRAY_SIZE(exp_errnos), "readahead() on %s", tst_fd_desc(fd));
66 }
67 
test_readahead(void)68 static void test_readahead(void)
69 {
70 	test_bad_fd();
71 
72 	TST_FD_FOREACH(fd)
73 		test_invalid_fd(&fd);
74 }
75 
setup(void)76 static void setup(void)
77 {
78 	/* check if readahead syscall is supported */
79 	tst_syscall(__NR_readahead, 0, 0, 0);
80 }
81 
82 static struct tst_test test = {
83 	.needs_tmpdir = 1,
84 	.setup = setup,
85 	.test_all = test_readahead,
86 };
87 
88 #else /* __NR_readahead */
89 	TST_TEST_TCONF("System doesn't support __NR_readahead");
90 #endif
91