xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/pipe/pipe15.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2023 SUSE LLC Marius Kittler <[email protected]>
4  */
5 
6 /*\
7  * [Description]
8  *
9  * This is a regression test for hangup on pipe operations. See
10  * https://www.spinics.net/lists/linux-api/msg49762.html for
11  * additional context. It tests that pipe operations do not block
12  * indefinitely when going to the soft limit on the total size of
13  * all pipes created by a single user.
14  */
15 
16 #define _GNU_SOURCE
17 #include <fcntl.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 
21 #include "tst_test.h"
22 #include "tst_safe_stdio.h"
23 #include "tst_safe_macros.h"
24 
25 static int pipe_count;
26 static int *pipes;
27 static char *buffer;
28 
run(void)29 static void run(void)
30 {
31 	const int *const pipe = pipes + 2 * (pipe_count - 1);
32 	const int buffer_size = SAFE_FCNTL(pipe[1], F_GETPIPE_SZ);
33 
34 	tst_res(TINFO, "Soft-limited buffer size: %d bytes", buffer_size);
35 	SAFE_WRITE(1, pipe[1], buffer, buffer_size);
36 	SAFE_READ(1, pipe[0], buffer, buffer_size - 1);
37 	SAFE_WRITE(1, pipe[1], buffer, 1);
38 	tst_res(TPASS, "Pipe operation did not block");
39 
40 	SAFE_READ(1, pipe[0], buffer, 2);
41 }
42 
setup(void)43 static void setup(void)
44 {
45 	int pipe[2];
46 	int page_size = getpagesize(), soft_limit;
47 	struct rlimit nfd;
48 
49 	SAFE_PIPE(pipe);
50 	const int buffer_size = SAFE_FCNTL(pipe[1], F_GETPIPE_SZ);
51 
52 	SAFE_CLOSE(pipe[0]);
53 	SAFE_CLOSE(pipe[1]);
54 
55 	SAFE_FILE_SCANF("/proc/sys/fs/pipe-user-pages-soft", "%i", &soft_limit);
56 	pipe_count = soft_limit * page_size / buffer_size;
57 
58 	tst_res(TINFO, "Soft limit for pipes: %i pages", soft_limit);
59 	tst_res(TINFO, "Buffer size: %d byte", buffer_size);
60 	tst_res(TINFO, "Creating %i pipes", pipe_count);
61 
62 	SAFE_GETRLIMIT(RLIMIT_NOFILE, &nfd);
63 	if (nfd.rlim_max < (unsigned long)pipe_count * 2 + 3)
64 		tst_brk(TCONF, "NOFILE limit max too low: %lu < %i", nfd.rlim_max, pipe_count);
65 
66 	if (nfd.rlim_cur < nfd.rlim_max) {
67 		nfd.rlim_cur = nfd.rlim_max;
68 		SAFE_SETRLIMIT(RLIMIT_NOFILE, &nfd);
69 	}
70 
71 	buffer = SAFE_MALLOC(buffer_size);
72 	pipes = SAFE_MALLOC(pipe_count * 2 * sizeof(int));
73 	for (int i = 0; i < pipe_count; ++i)
74 		SAFE_PIPE(pipes + i * 2);
75 
76 }
77 
cleanup(void)78 static void cleanup(void)
79 {
80 	if (pipes) {
81 		for (int i = 0; i < pipe_count * 2; i++) {
82 			if (pipes[i] > 0)
83 				SAFE_CLOSE(pipes[i]);
84 		}
85 		free(pipes);
86 	}
87 
88 	if (buffer)
89 		free(buffer);
90 }
91 
92 static struct tst_test test = {
93 	.setup = setup,
94 	.test_all = run,
95 	.cleanup = cleanup,
96 	.tags = (const struct tst_tag[]){
97 		{"linux-git", "46c4c9d1beb7"},
98 	},
99 };
100