htl: move pthread_attr_init into libc.
[glibc.git] / sysdeps / posix / preadv_common.c
blobcb220ca97fd8bb1d7a35b1d3c891534284238950
1 /* Read data into multiple buffers. Base implementation for preadv
2 and preadv64.
3 Copyright (C) 2017-2024 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
20 #include <unistd.h>
21 #include <sys/uio.h>
22 #include <sys/param.h>
23 #include <errno.h>
24 #include <malloc.h>
26 #include <ldsodefs.h>
27 #include <libc-pointer-arith.h>
29 /* Read data from file descriptor FD at the given position OFFSET
30 without change the file pointer, and put the result in the buffers
31 described by VECTOR, which is a vector of COUNT 'struct iovec's.
32 The buffers are filled in the order specified. Operates just like
33 'pread' (see <unistd.h>) except that data are put in VECTOR instead
34 of a contiguous buffer. */
35 ssize_t
36 PREADV (int fd, const struct iovec *vector, int count, OFF_T offset)
38 /* Find the total number of bytes to be read. */
39 size_t bytes = 0;
40 for (int i = 0; i < count; ++i)
42 /* Check for ssize_t overflow. */
43 if (SSIZE_MAX - bytes < vector[i].iov_len)
45 __set_errno (EINVAL);
46 return -1;
48 bytes += vector[i].iov_len;
51 /* Allocate a temporary buffer to hold the data. It could be done with a
52 stack allocation, but due limitations on some system (Linux with
53 O_DIRECT) it aligns the buffer to pagesize. A possible optimization
54 would be querying if the syscall would impose any alignment constraint,
55 but 1. it is system specific (not meant in generic implementation), and
56 2. it would make the implementation more complex, and 3. it will require
57 another syscall (fcntl). */
58 void *buffer = __mmap (NULL, bytes, PROT_READ | PROT_WRITE,
59 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
60 if (__glibc_unlikely (buffer == MAP_FAILED))
61 return -1;
63 ssize_t bytes_read = PREAD (fd, buffer, bytes, offset);
64 if (bytes_read < 0)
65 goto end;
67 /* Copy the data from BUFFER into the memory specified by VECTOR. */
68 bytes = bytes_read;
69 void *buf = buffer;
70 for (int i = 0; i < count; ++i)
72 size_t copy = MIN (vector[i].iov_len, bytes);
74 memcpy (vector[i].iov_base, buf, copy);
76 buf += copy;
77 bytes -= copy;
78 if (bytes == 0)
79 break;
82 end:
83 __munmap (buffer, bytes);
84 return bytes_read;