1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2015 Fujitsu Ltd.
4 * Author: Xiao Yang <[email protected]>
5 * Copyright (c) Linux Test Project, 2016-2023
6 */
7
8 /*\
9 * [Description]
10 *
11 * Testcase to check the basic functionality of the pwritev(2).
12 *
13 * pwritev(2) should succeed to write the expected content of data
14 * and after writing the file, the file offset is not changed.
15 */
16
17 #define _GNU_SOURCE
18 #include <string.h>
19 #include <sys/uio.h>
20 #include "tst_test.h"
21 #include "pwritev.h"
22 #include "tst_safe_prw.h"
23
24 #define CHUNK 64
25
26 static char buf[CHUNK];
27 static char initbuf[CHUNK * 2];
28 static char preadbuf[CHUNK];
29 static int fd;
30
31 static struct iovec wr_iovec[] = {
32 {buf, CHUNK},
33 {NULL, 0},
34 };
35
36 static struct tcase {
37 int count;
38 off_t offset;
39 ssize_t size;
40 } tcases[] = {
41 {1, 0, CHUNK},
42 {2, 0, CHUNK},
43 {1, CHUNK/2, CHUNK},
44 };
45
verify_pwritev(unsigned int n)46 static void verify_pwritev(unsigned int n)
47 {
48 int i;
49 struct tcase *tc = &tcases[n];
50
51 SAFE_PWRITE(1, fd, initbuf, sizeof(initbuf), 0);
52
53 SAFE_LSEEK(fd, 0, SEEK_SET);
54
55 TEST(pwritev(fd, wr_iovec, tc->count, tc->offset));
56 if (TST_RET < 0) {
57 tst_res(TFAIL | TTERRNO, "pwritev() failed");
58 return;
59 }
60
61 if (TST_RET != tc->size) {
62 tst_res(TFAIL, "pwritev() wrote %li bytes, expected %zi",
63 TST_RET, tc->size);
64 return;
65 }
66
67 if (SAFE_LSEEK(fd, 0, SEEK_CUR) != 0) {
68 tst_res(TFAIL, "pwritev() had changed file offset");
69 return;
70 }
71
72 SAFE_PREAD(1, fd, preadbuf, tc->size, tc->offset);
73
74 for (i = 0; i < tc->size; i++) {
75 if (preadbuf[i] != 0x61)
76 break;
77 }
78
79 if (i != tc->size) {
80 tst_res(TFAIL, "buffer wrong at %i have %02x expected 61",
81 i, preadbuf[i]);
82 return;
83 }
84
85 tst_res(TPASS, "writev() wrote %zi bytes successfully "
86 "with content 'a' expectedly ", tc->size);
87 }
88
setup(void)89 static void setup(void)
90 {
91 memset(&buf, 0x61, CHUNK);
92
93 fd = SAFE_OPEN("file", O_RDWR | O_CREAT, 0644);
94 }
95
cleanup(void)96 static void cleanup(void)
97 {
98 if (fd > 0)
99 SAFE_CLOSE(fd);
100 }
101
102 static struct tst_test test = {
103 .tcnt = ARRAY_SIZE(tcases),
104 .setup = setup,
105 .cleanup = cleanup,
106 .test = verify_pwritev,
107 .needs_tmpdir = 1,
108 };
109