LCOV - code coverage report
Current view: top level - source/lib/file/io - io.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 87 96 90.6 %
Date: 2026-12-03 01:19:39 Functions: 7 9 77.8 %

          Line data    Source code
       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
      39             : #include "lib/posix/posix_types.h"
      40             : #include "lib/status.h"
      41             : #include "lib/sysdep/filesystem.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             : 
      54             : namespace ERR
      55             : {
      56             :     const Status IO = -110301;
      57             : }
      58             : 
      59             : namespace io {
      60             : 
      61             : struct FreeAligned
      62             : {
      63           2 :     void operator()(void* pointer) { rtl_FreeAligned(pointer); }
      64             : };
      65             : 
      66             : using 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).
      74           2 : static inline io::BufferPtr Allocate(size_t size, size_t alignment = maxSectorSize)
      75             : {
      76           2 :     ENSURE(std::has_single_bit(alignment));
      77           2 :     alignment = std::max(alignment, allocationAlignment);
      78             : 
      79           2 :     std::uint8_t* p = static_cast<std::uint8_t*>(rtl_AllocateAligned(round_up(size, alignment),
      80             :         alignment));
      81             : 
      82           2 :     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.)
      90             : struct Operation
      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       16205 :     Operation(const File& file, void* buf, off_t size, off_t offset = 0)
      96       16205 :         : m_FileDescriptor(file.Descriptor()), m_OpenFlag((file.Flags() & O_WRONLY)? LIO_WRITE : LIO_READ)
      97       16205 :         , m_Offset(offset), m_Size(size), m_Buffer(buf)
      98             :     {
      99             :     }
     100             : 
     101       16205 :     void Validate() const
     102             :     {
     103       16205 :         ENSURE(m_FileDescriptor >= 0);
     104       16205 :         ENSURE(m_OpenFlag == LIO_READ || m_OpenFlag == LIO_WRITE);
     105             : 
     106       16205 :         ENSURE(m_Offset >= 0);
     107       16205 :         ENSURE(m_Size >= 0);
     108             :         // m_Buffer can legitimately be 0 (see above)
     109       16205 :     }
     110             : 
     111             :     int m_FileDescriptor;
     112             :     int m_OpenFlag;
     113             : 
     114             :     off_t m_Offset;
     115             :     off_t m_Size;
     116             :     void* m_Buffer;
     117             : };
     118             : 
     119             : 
     120             : // optional information how an Operation is to be carried out
     121             : struct Parameters
     122             : {
     123             :     // default to single blocking I/Os
     124       16205 :     Parameters()
     125       16205 :         : alignment(1)  // no alignment requirements
     126       16205 :         , blockSize(0)  // do not split into blocks
     127       16205 :         , queueDepth(1) // disable aio
     128             :     {
     129             :     }
     130             : 
     131             :     // parameters for asynchronous I/O that maximize throughput on current drives
     132             :     struct OverlappedTag {};
     133             :     Parameters(OverlappedTag)
     134             :         : alignment(maxSectorSize), blockSize(128*KiB), queueDepth(32)
     135             :     {
     136             :     }
     137             : 
     138             :     Parameters(size_t blockSize, size_t queueDepth, off_t alignment = maxSectorSize)
     139             :         : alignment(alignment), blockSize(blockSize), queueDepth(queueDepth)
     140             :     {
     141             :     }
     142             : 
     143       16205 :     void Validate(const Operation& op) const
     144             :     {
     145       16205 :         ENSURE(alignment > 0);
     146       16205 :         ENSURE(std::has_single_bit(static_cast<uint64_t>(alignment)));
     147             : 
     148       16205 :         if(blockSize != 0)
     149             :         {
     150           0 :             ENSURE(std::has_single_bit(blockSize));
     151           0 :             ENSURE(g_PageSize <= blockSize); // (don't bother checking an upper bound)
     152             :         }
     153             : 
     154       16205 :         ENSURE(1 <= queueDepth && queueDepth <= maxQueueDepth);
     155             : 
     156       16205 :         ENSURE(IsAligned(op.m_Offset, alignment));
     157             :         // op.size doesn't need to be aligned
     158       16205 :         ENSURE(IsAligned(op.m_Buffer, alignment));
     159       16205 :     }
     160             : 
     161             :     // (ATTO only allows 10, which improves upon 8)
     162             :     static const size_t maxQueueDepth = 32;
     163             : 
     164             :     off_t alignment;
     165             : 
     166             :     size_t blockSize;   // 0 for one big "block"
     167             : 
     168             :     size_t queueDepth;
     169             : };
     170             : 
     171             : #define IO_OVERLAPPED io::Parameters(io::Parameters::OverlappedTag())
     172             : 
     173             : 
     174             : struct DefaultCompletedHook
     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             : 
     190             : struct DefaultIssueHook
     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             :      **/
     199             :     Status operator()(aiocb&) const
     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.
     208       16205 : class ControlBlockRingBuffer
     209             : {
     210             : public:
     211       16205 :     ControlBlockRingBuffer(const Operation& op, const Parameters& p)
     212       16205 :         : controlBlocks()   // zero-initialize
     213             :     {
     214       16205 :         const size_t blockSize = p.blockSize? p.blockSize : static_cast<size_t>(op.m_Size);
     215             : 
     216       16205 :         const bool temporaryBuffersRequested = (op.m_Buffer == 0);
     217       16205 :         if(temporaryBuffersRequested)
     218           0 :             buffers = io::Allocate(blockSize * p.queueDepth, p.alignment);
     219             : 
     220      534765 :         for(size_t i = 0; i < ARRAY_SIZE(controlBlocks); i++)
     221             :         {
     222      518560 :             aiocb& cb = operator[](i);
     223      518560 :             cb.aio_fildes = op.m_FileDescriptor;
     224      518560 :             cb.aio_nbytes = blockSize;
     225      518560 :             cb.aio_lio_opcode = op.m_OpenFlag;
     226      518560 :             if(temporaryBuffersRequested)
     227           0 :                 cb.aio_buf = (volatile void*)(uintptr_t(buffers.get()) + i * blockSize);
     228             :         }
     229       16205 :     }
     230             : 
     231      550970 :     INLINE aiocb& operator[](size_t counter)
     232             :     {
     233      518560 :         return controlBlocks[counter % ARRAY_SIZE(controlBlocks)];
     234             :     }
     235             : 
     236             : private:
     237             :     io::BufferPtr buffers;
     238             :     aiocb controlBlocks[Parameters::maxQueueDepth];
     239             : };
     240             : 
     241             : #pragma pack(pop)
     242             : 
     243             : 
     244             : Status Issue(aiocb& cb, size_t queueDepth);
     245             : Status 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.)
     257             : template<class CompletedHook, class IssueHook>
     258       16205 : static inline Status Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook())
     259             : {
     260       16205 :     op.Validate();
     261       16205 :     p.Validate(op);
     262             : 
     263       16205 :     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       16205 :     size_t numBlocks = p.blockSize? DivideRoundUp(static_cast<size_t>(op.m_Size), p.blockSize) : 1;
     271       32410 :     for(size_t blocksIssued = 0, blocksCompleted = 0; blocksCompleted < numBlocks; blocksCompleted++)
     272             :     {
     273       32410 :         for(; blocksIssued != numBlocks && blocksIssued < blocksCompleted + (off_t)p.queueDepth; blocksIssued++)
     274             :         {
     275       16205 :             aiocb& cb = controlBlockRingBuffer[blocksIssued];
     276       16205 :             cb.aio_offset = op.m_Offset + blocksIssued * p.blockSize;
     277       16205 :             if(op.m_Buffer)
     278       16205 :                 cb.aio_buf = (volatile void*)(uintptr_t(op.m_Buffer) + blocksIssued * p.blockSize);
     279       16205 :             if(blocksIssued == numBlocks-1)
     280       16205 :                 cb.aio_nbytes = round_up(size_t(op.m_Size - blocksIssued * p.blockSize), size_t(p.alignment));
     281             : 
     282       16205 :             RETURN_STATUS_FROM_CALLBACK(issueHook(cb));
     283             : 
     284       16205 :             RETURN_STATUS_IF_ERR(Issue(cb, p.queueDepth));
     285             :         }
     286             : 
     287       16205 :         aiocb& cb = controlBlockRingBuffer[blocksCompleted];
     288       16205 :         RETURN_STATUS_IF_ERR(WaitUntilComplete(cb, p.queueDepth));
     289             : 
     290       16205 :         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       16205 : }
     303             : 
     304             : // (overloads allow omitting parameters without requiring a template argument list)
     305             : template<class CompletedHook>
     306           0 : static inline Status Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook())
     307             : {
     308           0 :     return Run(op, p, completedHook, DefaultIssueHook());
     309             : }
     310             : 
     311           2 : static inline Status Run(const Operation& op, const Parameters& p = Parameters())
     312             : {
     313           2 :     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.
     323             : template<class CompletedHook, class IssueHook>
     324        2115 : static 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        2115 :     File file;
     327        2115 :     int oflag = O_WRONLY;
     328        2115 :     if(p.queueDepth != 1)
     329           0 :         oflag |= O_DIRECT;
     330        2115 :     RETURN_STATUS_IF_ERR(file.Open(pathname, oflag));
     331        2115 :     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        2115 :     RETURN_STATUS_IF_ERR(io::Run(op, p, completedHook, issueHook));
     338             : 
     339        2115 :     file.Close();   // (required by resize_file)
     340             : 
     341        2115 :     std::error_code ec{};
     342        2115 :     std::filesystem::resize_file(pathname.string(), size, ec);
     343        2115 :     if (ec)
     344           0 :         return StatusFromSystemError(ec);
     345             : 
     346             :     return INFO::OK;
     347        2115 : }
     348             : 
     349             : template<class CompletedHook>
     350             : static 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             : 
     355        2115 : static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters())
     356             : {
     357        2115 :     return Store(pathname, data, size, p, DefaultCompletedHook(), DefaultIssueHook());
     358             : }
     359             : 
     360             : 
     361             : //-----------------------------------------------------------------------------
     362             : // Load
     363             : 
     364             : // convenience function provided for symmetry with Store.
     365             : template<class CompletedHook, class IssueHook>
     366       14088 : static 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       14088 :     File file;
     369       14088 :     int oflag = O_RDONLY;
     370       14088 :     if(p.queueDepth != 1)
     371           0 :         oflag |= O_DIRECT;
     372       14088 :     RETURN_STATUS_IF_ERR(file.Open(pathname, oflag));
     373       14088 :     io::Operation op(file, buf, size);
     374       14088 :     return io::Run(op, p, completedHook, issueHook);
     375       14088 : }
     376             : 
     377             : template<class CompletedHook>
     378             : static 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             : 
     383       14088 : static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters())
     384             : {
     385       14088 :     return Load(pathname, buf, size, p, DefaultCompletedHook(), DefaultIssueHook());
     386             : }
     387             : 
     388             : }   // namespace io
     389             : 
     390             : #endif  // #ifndef INCLUDED_IO

Generated by: LCOV version 1.16