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 pwrite() 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 written aganist the data
14 * read using read().
15 */
16
17 #include <stdlib.h>
18 #include <inttypes.h>
19 #include "tst_test.h"
20 #include "tst_safe_prw.h"
21
22 #define TEMPFILE "pwrite_file"
23 #define K1 1024
24 #define K2 (K1 * 2)
25 #define K3 (K1 * 3)
26 #define K4 (K1 * 4)
27 #define NBUFS 4
28
29 static int fildes;
30 static char *write_buf[NBUFS];
31 static char *read_buf[NBUFS];
32
l_seek(int fdesc,off_t offset,int whence,off_t checkoff)33 static void l_seek(int fdesc, off_t offset, int whence, off_t checkoff)
34 {
35 off_t offloc;
36
37 offloc = SAFE_LSEEK(fdesc, offset, whence);
38 if (offloc != checkoff) {
39 tst_res(TFAIL, "return = %" PRId64 ", expected %" PRId64,
40 (int64_t) offloc, (int64_t) checkoff);
41 }
42 }
43
check_file_contents(void)44 static void check_file_contents(void)
45 {
46 int count, err_flg = 0;
47
48 for (count = 0; count < NBUFS; count++) {
49 l_seek(fildes, count * K1, SEEK_SET, count * K1);
50
51 SAFE_READ(1, fildes, read_buf[count], K1);
52
53 if (memcmp(write_buf[count], read_buf[count], K1) != 0) {
54 tst_res(TFAIL, "read/write buffer[%d] data mismatch", count);
55 err_flg++;
56 }
57 }
58
59 if (!err_flg)
60 tst_res(TPASS, "Functionality of pwrite() successful");
61 }
62
verify_pwrite(void)63 static void verify_pwrite(void)
64 {
65 SAFE_PWRITE(1, fildes, write_buf[0], K1, 0);
66 l_seek(fildes, 0, SEEK_CUR, 0);
67 l_seek(fildes, K1 / 2, SEEK_SET, K1 / 2);
68
69 SAFE_PWRITE(1, fildes, write_buf[2], K1, K2);
70 l_seek(fildes, 0, SEEK_CUR, K1 / 2);
71 l_seek(fildes, K3, SEEK_SET, K3);
72
73 SAFE_WRITE(SAFE_WRITE_ALL, fildes, write_buf[3], K1);
74 l_seek(fildes, 0, SEEK_CUR, K4);
75
76 SAFE_PWRITE(1, fildes, write_buf[1], K1, K1);
77
78 check_file_contents();
79
80 l_seek(fildes, 0, SEEK_SET, 0);
81 }
82
setup(void)83 static void setup(void)
84 {
85 int count;
86
87 for (count = 0; count < NBUFS; count++) {
88 write_buf[count] = SAFE_MALLOC(K1);
89 read_buf[count] = SAFE_MALLOC(K1);
90 memset(write_buf[count], count, K1);
91 }
92
93 fildes = SAFE_OPEN(TEMPFILE, O_RDWR | O_CREAT, 0666);
94 }
95
cleanup(void)96 static void cleanup(void)
97 {
98 int count;
99
100 for (count = 0; count < NBUFS; count++) {
101 free(write_buf[count]);
102 free(read_buf[count]);
103 }
104
105 if (fildes > 0)
106 SAFE_CLOSE(fildes);
107 }
108
109 static struct tst_test test = {
110 .needs_tmpdir = 1,
111 .setup = setup,
112 .cleanup = cleanup,
113 .test_all = verify_pwrite,
114 };
115