1 /* SPDX-License-Identifier: GPL-2.0 */
2 
3 #ifndef __PIDFD_H
4 #define __PIDFD_H
5 
6 #define _GNU_SOURCE
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sched.h>
10 #include <signal.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <syscall.h>
15 #include <sys/mount.h>
16 
17 #include "../kselftest.h"
18 
19 #ifndef P_PIDFD
20 #define P_PIDFD 3
21 #endif
22 
23 #ifndef CLONE_PIDFD
24 #define CLONE_PIDFD 0x00001000
25 #endif
26 
27 #ifndef __NR_pidfd_open
28 #define __NR_pidfd_open -1
29 #endif
30 
31 #ifndef __NR_pidfd_send_signal
32 #define __NR_pidfd_send_signal -1
33 #endif
34 
35 #ifndef __NR_clone3
36 #define __NR_clone3 -1
37 #endif
38 
39 /*
40  * The kernel reserves 300 pids via RESERVED_PIDS in kernel/pid.c
41  * That means, when it wraps around any pid < 300 will be skipped.
42  * So we need to use a pid > 300 in order to test recycling.
43  */
44 #define PID_RECYCLE 1000
45 
46 /*
47  * Define a few custom error codes for the child process to clearly indicate
48  * what is happening. This way we can tell the difference between a system
49  * error, a test error, etc.
50  */
51 #define PIDFD_PASS 0
52 #define PIDFD_FAIL 1
53 #define PIDFD_ERROR 2
54 #define PIDFD_SKIP 3
55 #define PIDFD_XFAIL 4
56 
57 int wait_for_pid(pid_t pid)
58 {
59 	int status, ret;
60 
61 again:
62 	ret = waitpid(pid, &status, 0);
63 	if (ret == -1) {
64 		if (errno == EINTR)
65 			goto again;
66 
67 		return -1;
68 	}
69 
70 	if (!WIFEXITED(status))
71 		return -1;
72 
73 	return WEXITSTATUS(status);
74 }
75 
76 static inline int sys_pidfd_open(pid_t pid, unsigned int flags)
77 {
78 	return syscall(__NR_pidfd_open, pid, flags);
79 }
80 
81 static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
82 					unsigned int flags)
83 {
84 	return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
85 }
86 
87 #endif /* __PIDFD_H */
88