1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Linux Test Project, 2021
4 * Copyright (c) International Business Machines Corp., 2001
5 * 07/2001 Ported by Wayne Boyer
6 */
7
8 /*\
9 * [Description]
10 *
11 * Verify the functionality of pread() by writing known data using pwrite()
12 * to the file at various specified offsets and later read from the file from
13 * various specified offsets, comparing the data read against the data written.
14 */
15
16 #include <stdlib.h>
17 #include <inttypes.h>
18 #include "tst_test.h"
19 #include "tst_safe_prw.h"
20
21 #define TEMPFILE "pread_file"
22 #define K1 1024
23 #define K2 (K1 * 2)
24 #define K3 (K1 * 3)
25 #define K4 (K1 * 4)
26 #define NBUFS 4
27
28 static int fildes;
29 static char *write_buf[NBUFS];
30 static char *read_buf[NBUFS];
31
l_seek(int fdesc,off_t offset,int whence,off_t checkoff)32 static void l_seek(int fdesc, off_t offset, int whence, off_t checkoff)
33 {
34 off_t offloc;
35
36 offloc = SAFE_LSEEK(fdesc, offset, whence);
37 if (offloc != checkoff) {
38 tst_res(TFAIL, "return = %" PRId64 ", expected %" PRId64,
39 (int64_t) offloc, (int64_t) checkoff);
40 }
41 }
42
compare_bufers(void)43 static void compare_bufers(void)
44 {
45 int count;
46 int err_flg = 0;
47
48 for (count = 0; count < NBUFS; count++) {
49 if (memcmp(write_buf[count], read_buf[count], K1) != 0) {
50 tst_res(TFAIL, "read/write buffer[%d] data mismatch", count);
51 err_flg++;
52 }
53 }
54
55 if (!err_flg)
56 tst_res(TPASS, "Functionality of pread() is correct");
57 }
58
verify_pread(void)59 static void verify_pread(void)
60 {
61 SAFE_PREAD(1, fildes, read_buf[2], K1, K2);
62 l_seek(fildes, 0, SEEK_CUR, K4);
63 l_seek(fildes, 0, SEEK_SET, 0);
64
65 SAFE_PREAD(1, fildes, read_buf[3], K1, K3);
66 l_seek(fildes, 0, SEEK_CUR, 0);
67
68 SAFE_READ(1, fildes, read_buf[0], K1);
69 l_seek(fildes, 0, SEEK_CUR, K1);
70
71 SAFE_PREAD(1, fildes, read_buf[1], K1, K1);
72 l_seek(fildes, 0, SEEK_CUR, K1);
73
74 compare_bufers();
75
76 l_seek(fildes, K4, SEEK_SET, K4);
77 }
78
setup(void)79 static void setup(void)
80 {
81 int count;
82
83 for (count = 0; count < NBUFS; count++) {
84 write_buf[count] = SAFE_MALLOC(K1);
85 read_buf[count] = SAFE_MALLOC(K1);
86 memset(write_buf[count], count, K1);
87 }
88
89 fildes = SAFE_OPEN(TEMPFILE, O_RDWR | O_CREAT, 0666);
90
91 SAFE_PWRITE(1, fildes, write_buf[0], K1, 0);
92 SAFE_PWRITE(1, fildes, write_buf[2], K1, K2);
93 SAFE_PWRITE(1, fildes, write_buf[3], K1, K3);
94 SAFE_PWRITE(1, fildes, write_buf[1], K1, K1);
95 SAFE_LSEEK(fildes, K4, SEEK_SET);
96 }
97
cleanup(void)98 static void cleanup(void)
99 {
100 int count;
101
102 for (count = 0; count < NBUFS; count++) {
103 free(write_buf[count]);
104 free(read_buf[count]);
105 }
106
107 if (fildes > 0)
108 SAFE_CLOSE(fildes);
109 }
110
111 static struct tst_test test = {
112 .needs_tmpdir = 1,
113 .setup = setup,
114 .cleanup = cleanup,
115 .test_all = verify_pread,
116 };
117