Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
io.h
Go to the documentation of this file.
1/* Copyright (C) 2026 Wildfire Games.
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining
4 * a copy of this software and associated documentation files (the
5 * "Software"), to deal in the Software without restriction, including
6 * without limitation the rights to use, copy, modify, merge, publish,
7 * distribute, sublicense, and/or sell copies of the Software, and to
8 * permit persons to whom the Software is furnished to do so, subject to
9 * the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23/*
24 * provide asynchronous and synchronous I/O with hooks to allow
25 * overlapped processing or progress reporting.
26 */
27
28#ifndef INCLUDED_IO
29#define INCLUDED_IO
30
31#include "lib/alignment.h"
32#include "lib/bits.h"
33#include "lib/code_annotation.h"
34#include "lib/debug.h"
35#include "lib/file/file.h"
36#include "lib/lib.h"
37#include "lib/os_path.h"
38#include "lib/posix/posix_aio.h" // LIO_READ, LIO_WRITE
40#include "lib/status.h"
42#include "lib/sysdep/os.h"
43#include "lib/sysdep/rtl.h"
44
45#include <algorithm>
46#include <bit>
47#include <cstddef>
48#include <cstdint>
49#include <fcntl.h>
50#include <filesystem>
51#include <memory>
52#include <system_error>
53
54namespace ERR
55{
56 const Status IO = -110301;
57}
58
59namespace io {
60
62{
63 void operator()(void* pointer) { rtl_FreeAligned(pointer); }
64};
65
66using BufferPtr = std::unique_ptr<std::uint8_t, FreeAligned>;
67
68// @return memory suitable for use as an I/O buffer (address is a
69// multiple of alignment, size is rounded up to a multiple of alignment)
70// @param alignment is automatically increased if required.
71//
72// use this instead of the file cache for write buffers that are
73// never reused (avoids displacing other items).
74static inline io::BufferPtr Allocate(size_t size, size_t alignment = maxSectorSize)
75{
76 ENSURE(std::has_single_bit(alignment));
77 alignment = std::max(alignment, allocationAlignment);
78
79 std::uint8_t* p = static_cast<std::uint8_t*>(rtl_AllocateAligned(round_up(size, alignment),
80 alignment));
81
82 return {p, FreeAligned{}};
83}
84
85
86#pragma pack(push, 1)
87
88// required information for any I/O (this is basically the same as aiocb,
89// but also applies to synchronous I/O and has shorter/nicer names.)
91{
92 // @param m_Buffer can be 0, in which case temporary block buffers are allocated.
93 // otherwise, it must be aligned and padded to the I/O alignment, e.g. via
94 // io::Allocate.
95 Operation(const File& file, void* buf, off_t size, off_t offset = 0)
96 : m_FileDescriptor(file.Descriptor()), m_OpenFlag((file.Flags() & O_WRONLY)? LIO_WRITE : LIO_READ)
97 , m_Offset(offset), m_Size(size), m_Buffer(buf)
98 {
99 }
100
101 void Validate() const
102 {
105
106 ENSURE(m_Offset >= 0);
107 ENSURE(m_Size >= 0);
108 // m_Buffer can legitimately be 0 (see above)
109 }
110
113
116 void* m_Buffer;
117};
118
119
120// optional information how an Operation is to be carried out
122{
123 // default to single blocking I/Os
125 : alignment(1) // no alignment requirements
126 , blockSize(0) // do not split into blocks
127 , queueDepth(1) // disable aio
128 {
129 }
130
131 // parameters for asynchronous I/O that maximize throughput on current drives
132 struct OverlappedTag {};
135 {
136 }
137
140 {
141 }
142
143 void Validate(const Operation& op) const
144 {
145 ENSURE(alignment > 0);
146 ENSURE(std::has_single_bit(static_cast<uint64_t>(alignment)));
147
148 if(blockSize != 0)
149 {
150 ENSURE(std::has_single_bit(blockSize));
151 ENSURE(g_PageSize <= blockSize); // (don't bother checking an upper bound)
152 }
153
155
157 // op.size doesn't need to be aligned
159 }
160
161 // (ATTO only allows 10, which improves upon 8)
162 static const size_t maxQueueDepth = 32;
163
165
166 size_t blockSize; // 0 for one big "block"
167
169};
170
171#define IO_OVERLAPPED io::Parameters(io::Parameters::OverlappedTag())
172
173
175{
176 /**
177 * called after a block I/O has completed.
178 * @return Status (see RETURN_STATUS_FROM_CALLBACK).
179 *
180 * allows progress notification and processing data while waiting for
181 * previous I/Os to complete.
182 **/
183 Status operator()(const std::uint8_t* /*block*/, size_t /*blockSize*/) const
184 {
185 return INFO::OK;
186 }
187};
188
189
191{
192 /**
193 * called before a block I/O is issued.
194 * @return Status (see RETURN_STATUS_FROM_CALLBACK).
195 *
196 * allows generating the data to write while waiting for
197 * previous I/Os to complete.
198 **/
200 {
201 return INFO::OK;
202 }
203};
204
205
206// ring buffer of partially initialized aiocb that can be passed
207// directly to aio_write etc. after setting offset and buffer.
209{
210public:
212 : controlBlocks() // zero-initialize
213 {
214 const size_t blockSize = p.blockSize? p.blockSize : static_cast<size_t>(op.m_Size);
215
216 const bool temporaryBuffersRequested = (op.m_Buffer == 0);
217 if(temporaryBuffersRequested)
218 buffers = io::Allocate(blockSize * p.queueDepth, p.alignment);
219
220 for(size_t i = 0; i < ARRAY_SIZE(controlBlocks); i++)
221 {
222 aiocb& cb = operator[](i);
224 cb.aio_nbytes = blockSize;
226 if(temporaryBuffersRequested)
227 cb.aio_buf = (volatile void*)(uintptr_t(buffers.get()) + i * blockSize);
228 }
229 }
230
231 INLINE aiocb& operator[](size_t counter)
232 {
233 return controlBlocks[counter % ARRAY_SIZE(controlBlocks)];
234 }
235
236private:
239};
240
241#pragma pack(pop)
242
243
244Status Issue(aiocb& cb, size_t queueDepth);
245Status WaitUntilComplete(aiocb& cb, size_t queueDepth);
246
247
248//-----------------------------------------------------------------------------
249// Run
250
251#ifndef ENABLE_IO_STATS
252#define ENABLE_IO_STATS 0
253#endif
254
255// (hooks must be passed by const reference to allow passing rvalues.
256// functors with non-const member data can mark them as mutable.)
257template<class CompletedHook, class IssueHook>
258static inline Status Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook())
259{
260 op.Validate();
261 p.Validate(op);
262
263 ControlBlockRingBuffer controlBlockRingBuffer(op, p);
264
265#if ENABLE_IO_STATS
266 const double t0 = timer_Time();
267 std::atomic_signal_fence(std::memory_order::seq_cst);
268#endif
269
270 size_t numBlocks = p.blockSize? DivideRoundUp(static_cast<size_t>(op.m_Size), p.blockSize) : 1;
271 for(size_t blocksIssued = 0, blocksCompleted = 0; blocksCompleted < numBlocks; blocksCompleted++)
272 {
273 for(; blocksIssued != numBlocks && blocksIssued < blocksCompleted + (off_t)p.queueDepth; blocksIssued++)
274 {
275 aiocb& cb = controlBlockRingBuffer[blocksIssued];
276 cb.aio_offset = op.m_Offset + blocksIssued * p.blockSize;
277 if(op.m_Buffer)
278 cb.aio_buf = (volatile void*)(uintptr_t(op.m_Buffer) + blocksIssued * p.blockSize);
279 if(blocksIssued == numBlocks-1)
280 cb.aio_nbytes = round_up(size_t(op.m_Size - blocksIssued * p.blockSize), size_t(p.alignment));
281
282 RETURN_STATUS_FROM_CALLBACK(issueHook(cb));
283
284 RETURN_STATUS_IF_ERR(Issue(cb, p.queueDepth));
285 }
286
287 aiocb& cb = controlBlockRingBuffer[blocksCompleted];
288 RETURN_STATUS_IF_ERR(WaitUntilComplete(cb, p.queueDepth));
289
290 RETURN_STATUS_FROM_CALLBACK(completedHook(const_cast<const std::uint8_t*>(
291 reinterpret_cast<volatile std::uint8_t*>(cb.aio_buf)), cb.aio_nbytes));
292 }
293
294#if ENABLE_IO_STATS
295 std::atomic_signal_fence(std::memory_order::seq_cst);
296 const double t1 = timer_Time();
297 const off_t totalSize = p.blockSize? numBlocks*p.blockSize : op.m_Size;
298 debug_printf("IO: %.2f MB/s (%.2f)\n", totalSize/(t1-t0)/1e6, (t1-t0)*1e3);
299#endif
300
301 return INFO::OK;
302}
303
304// (overloads allow omitting parameters without requiring a template argument list)
305template<class CompletedHook>
306static inline Status Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook())
307{
308 return Run(op, p, completedHook, DefaultIssueHook());
309}
310
311static inline Status Run(const Operation& op, const Parameters& p = Parameters())
312{
313 return Run(op, p, DefaultCompletedHook(), DefaultIssueHook());
314}
315
316
317//-----------------------------------------------------------------------------
318// Store
319
320// efficient writing requires preallocation; the resulting file is
321// padded to the sector size and needs to be truncated afterwards.
322// this function takes care of both.
323template<class CompletedHook, class IssueHook>
324static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook())
325{
326 File file;
327 int oflag = O_WRONLY;
328 if(p.queueDepth != 1)
329 oflag |= O_DIRECT;
330 RETURN_STATUS_IF_ERR(file.Open(pathname, oflag));
331 io::Operation op(file, (void*)data, size);
332
333#if OS_WIN
334 std::ignore = waio_Preallocate(op.m_FileDescriptor, (off_t)size);
335#endif
336
337 RETURN_STATUS_IF_ERR(io::Run(op, p, completedHook, issueHook));
338
339 file.Close(); // (required by resize_file)
340
341 std::error_code ec{};
342 std::filesystem::resize_file(pathname.string(), size, ec);
343 if (ec)
344 return StatusFromSystemError(ec);
345
346 return INFO::OK;
347}
348
349template<class CompletedHook>
350static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook())
351{
352 return Store(pathname, data, size, p, completedHook, DefaultIssueHook());
353}
354
355static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters())
356{
357 return Store(pathname, data, size, p, DefaultCompletedHook(), DefaultIssueHook());
358}
359
360
361//-----------------------------------------------------------------------------
362// Load
363
364// convenience function provided for symmetry with Store.
365template<class CompletedHook, class IssueHook>
366static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook())
367{
368 File file;
369 int oflag = O_RDONLY;
370 if(p.queueDepth != 1)
371 oflag |= O_DIRECT;
372 RETURN_STATUS_IF_ERR(file.Open(pathname, oflag));
373 io::Operation op(file, buf, size);
374 return io::Run(op, p, completedHook, issueHook);
375}
376
377template<class CompletedHook>
378static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook())
379{
380 return Load(pathname, buf, size, p, completedHook, DefaultIssueHook());
381}
382
383static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters())
384{
385 return Load(pathname, buf, size, p, DefaultCompletedHook(), DefaultIssueHook());
386}
387
388} // namespace io
389
390#endif // #ifndef INCLUDED_IO
static const size_t KiB
Definition: alignment.h:107
static const size_t g_PageSize
Definition: alignment.h:94
static const size_t allocationAlignment
Definition: alignment.h:105
bool IsAligned(T t, uintptr_t multiple)
Definition: alignment.h:34
static const uintptr_t maxSectorSize
Definition: alignment.h:118
T round_up(T n, T multiple)
round number up/down to the next given multiple.
Definition: bits.h:122
Definition: file.h:48
Status Open(const OsPath &pathName, int openFlag)
Definition: file.h:65
void Close()
Definition: file.h:75
Definition: path.h:84
const String & string() const
Definition: path.h:164
Definition: io.h:209
INLINE aiocb & operator[](size_t counter)
Definition: io.h:231
ControlBlockRingBuffer(const Operation &op, const Parameters &p)
Definition: io.h:211
io::BufferPtr buffers
Definition: io.h:237
aiocb controlBlocks[Parameters::maxQueueDepth]
Definition: io.h:238
#define INLINE
Definition: code_annotation.h:310
#define ARRAY_SIZE(name)
Definition: code_annotation.h:283
void debug_printf(const char *fmt,...)
write a formatted string to the debug channel.
Definition: debug.cpp:71
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
Definition: debug.h:222
#define O_DIRECT
Definition: filesystem.h:41
T DivideRoundUp(T dividend, T divisor)
Definition: lib.h:70
Definition: debug.h:340
const Status IO
Definition: io.h:56
const Status OK
Definition: status.h:394
Definition: io.cpp:36
Status WaitUntilComplete(aiocb &cb, size_t queueDepth)
Definition: io.cpp:73
static Status Store(const OsPath &pathname, const void *data, size_t size, const Parameters &p=Parameters(), const CompletedHook &completedHook=CompletedHook(), const IssueHook &issueHook=IssueHook())
Definition: io.h:324
static Status Load(const OsPath &pathname, void *buf, size_t size, const Parameters &p=Parameters(), const CompletedHook &completedHook=CompletedHook(), const IssueHook &issueHook=IssueHook())
Definition: io.h:366
static io::BufferPtr Allocate(size_t size, size_t alignment=maxSectorSize)
Definition: io.h:74
std::unique_ptr< std::uint8_t, FreeAligned > BufferPtr
Definition: io.h:66
static Status Run(const Operation &op, const Parameters &p=Parameters(), const CompletedHook &completedHook=CompletedHook(), const IssueHook &issueHook=IssueHook())
Definition: io.h:258
Status Issue(aiocb &cb, size_t queueDepth)
Definition: io.cpp:42
void rtl_FreeAligned(void *alignedPointer)
Definition: gcc.cpp:96
void * rtl_AllocateAligned(size_t size, size_t alignment)
Definition: gcc.cpp:69
Status StatusFromSystemError(std::error_code &ec)
Definition: status.cpp:103
#define RETURN_STATUS_IF_ERR(expression)
Definition: status.h:284
std::int64_t Status
Error handling system.
Definition: status.h:174
#define RETURN_STATUS_FROM_CALLBACK(expression)
Definition: status.h:346
Definition: waio.h:65
off_t aio_offset
Definition: waio.h:67
volatile void * aio_buf
Definition: waio.h:68
size_t aio_nbytes
Definition: waio.h:69
int aio_lio_opcode
Definition: waio.h:72
int aio_fildes
Definition: waio.h:66
Definition: io.h:175
Status operator()(const std::uint8_t *, size_t) const
called after a block I/O has completed.
Definition: io.h:183
Definition: io.h:191
Status operator()(aiocb &) const
called before a block I/O is issued.
Definition: io.h:199
Definition: io.h:62
void operator()(void *pointer)
Definition: io.h:63
Definition: io.h:91
void Validate() const
Definition: io.h:101
int m_OpenFlag
Definition: io.h:112
int m_FileDescriptor
Definition: io.h:111
off_t m_Offset
Definition: io.h:114
void * m_Buffer
Definition: io.h:116
off_t m_Size
Definition: io.h:115
Operation(const File &file, void *buf, off_t size, off_t offset=0)
Definition: io.h:95
Definition: io.h:132
Definition: io.h:122
Parameters(OverlappedTag)
Definition: io.h:133
static const size_t maxQueueDepth
Definition: io.h:162
size_t blockSize
Definition: io.h:166
Parameters()
Definition: io.h:124
off_t alignment
Definition: io.h:164
Parameters(size_t blockSize, size_t queueDepth, off_t alignment=maxSectorSize)
Definition: io.h:138
size_t queueDepth
Definition: io.h:168
void Validate(const Operation &op) const
Definition: io.h:143
double timer_Time()
Definition: timer.cpp:132
Status waio_Preallocate(int fd, off_t size)
Definition: waio.cpp:429
@ LIO_WRITE
Definition: waio.h:94
@ LIO_READ
Definition: waio.h:93
__int64 off_t
Definition: wposix_types.h:47