okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a74320ca
main
1// src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp. 2#include "strata/platform/direct_file.hpp" 3#include "strata/platform/aux_cpus.hpp" 4 5#include <algorithm> 6#include <chrono> 7#include <condition_variable> 8#include <cstdlib> 9#include <cstring> 10#include <deque> 11#include <mutex> 12#include <thread> 13#include <vector> 14 15#if defined(_WIN32 ) 16#define WIN32_LEAN_AND_MEAN 17#define NOMINMAX 18#include <windows.h> 19#else 20#include <fcntl.h> 21#include <sys/stat.h> 22#include <unistd.h> 23#endif 24 25namespace strata::platform { 26 27double now_us () { 28using namespace std::chrono ; 29return (double )duration_cast < nanoseconds > (steady_clock::now ().time_since_epoch ()).count () /1000.0 ; 30} 31 32void * DirectFile ::alloc_aligned (size_t bytes ) { 33#if defined(_WIN32 ) 34return VirtualAlloc (nullptr ,bytes ,MEM_RESERVE |MEM_COMMIT ,PAGE_READWRITE ); 35#else 36void * p = nullptr ; 37return posix_memalign (& p ,alignment (),bytes )== 0 ?p :nullptr ; 38#endif 39} 40 41void DirectFile ::free_aligned (void * p ) { 42if (p == nullptr )return ; 43#if defined(_WIN32 ) 44VirtualFree (p ,0 ,MEM_RELEASE ); 45#else 46 std::free (p ); 47#endif 48} 49 50namespace { 51/// A queued read: `submit` only queues it; the pool's threads issue it (perf-review C-4 / F-2). One thread 52/// issuing every read was the limit of the n-gram table's prompt reads: ~12 us of kernel time per read, ~80K 53/// reads/s, while an NVMe drive serves several times that at depth. 54struct Pending { 55uint64_t offset ; 56void * buffer ; 57uint32_t length ; 58uint64_t tag ; 59}; 60 61/// The number of issuing threads: STRATA_IO_THREADS, else 4 (Windows: overlapped submits) / 16 (Linux: each 62/// thread does one blocking pread, so the thread count is the queue depth). 63int io_threads (int dflt ) { 64const char * v = std::getenv ("STRATA_IO_THREADS" ); 65const int n = v ? std::atoi (v ) :dflt ; 66return std::clamp (n ,1 ,64 ); 67} 68}// namespace 69 70#if defined(_WIN32 ) 71// ------------------------------------------------------------------------------------------------ Windows 72namespace { 73/// One in-flight request. The OVERLAPPED must be the first member so a completion packet's OVERLAPPED* 74/// converts back to the request. 75struct Req { 76OVERLAPPED ov ; 77uint64_t tag ; 78}; 79}// namespace 80 81struct DirectFile ::Impl { 82HANDLE file = INVALID_HANDLE_VALUE ; 83HANDLE port = nullptr ; 84uint64_t size = 0 ; 85 std::mutex mu ;// everything below 86 std::deque < Req *> free_reqs ; 87 std::vector < Req *> all_reqs ; 88 std::deque < Completion > immediate ;// requests that completed without a port packet (EOF) or failed 89 std::deque < Pending > queue ;// submitted, not yet issued 90 std::condition_variable cv ; 91bool stop = false; 92 std::vector < std::thread > pool ; 93 94Req * take () { 95if (free_reqs .empty ()) { 96Req * r = new Req (); 97all_reqs .push_back (r ); 98return r ; 99 } 100Req * r = free_reqs .front (); 101free_reqs .pop_front (); 102return r ; 103 } 104 105void issue (const Pending & p ) { 106Req * r ; 107 { 108 std::lock_guard < std::mutex > lk (mu ); 109r = take (); 110 } 111 std::memset (& r -> ov ,0 ,sizeof r -> ov ); 112r -> ov .Offset = (DWORD ) (p .offset & 0xFFFFFFFFull ); 113r -> ov .OffsetHigh = (DWORD ) (p .offset >>32 ); 114r -> tag = p .tag ; 115if (!ReadFile (file ,p .buffer ,p .length ,nullptr ,& r -> ov )) { 116const DWORD e = GetLastError (); 117if (e != ERROR_IO_PENDING ) { 118 std::lock_guard < std::mutex > lk (mu ); 119free_reqs .push_back (r ); 120// at or past end of file: a zero-byte completion; anything else: a failed one 121immediate .push_back (Completion {p .tag ,0 ,e == ERROR_HANDLE_EOF }); 122PostQueuedCompletionStatus (port ,0 ,0 ,nullptr );// wake a waiter to collect it 123 } 124 } 125 } 126 127void worker () { 128 std::unique_lock < std::mutex > lk (mu ); 129for (;;) { 130cv .wait (lk , [& ] {return stop || !queue .empty (); }); 131if (stop && queue .empty ())return ; 132const Pending p = queue .front (); 133queue .pop_front (); 134lk .unlock (); 135issue (p ); 136lk .lock (); 137 } 138 } 139 140void stop_pool () { 141 { 142 std::lock_guard < std::mutex > lk (mu ); 143stop = true; 144 } 145cv .notify_all (); 146for (std::thread & t :pool )t .join (); 147pool .clear (); 148stop = false; 149 } 150}; 151 152DirectFile ::DirectFile () :impl_ (new Impl ) {} 153DirectFile ::~DirectFile () { 154close (); 155for (Req * r :impl_ -> all_reqs )delete r ; 156delete impl_ ; 157} 158 159bool DirectFile ::open (const std::string & path , std::string & err ) { 160close (); 161const int wlen = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 162 std::wstring wpath ((size_t ) (wlen > 0 ?wlen :1 ),L'\0' ); 163MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,wpath .data (),wlen ); 164// NO_BUFFERING: the cache manager never holds these pages, so the table cannot grow into RAM. 165// RANDOM_ACCESS: no read-ahead. OVERLAPPED: many reads in flight, completed through the port below. 166impl_ -> file = CreateFileW (wpath .c_str (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 167FILE_FLAG_NO_BUFFERING |FILE_FLAG_OVERLAPPED |FILE_FLAG_RANDOM_ACCESS ,nullptr ); 168if (impl_ -> file == INVALID_HANDLE_VALUE ) { 169err = "DirectFile: cannot open " + path + " (error " + std::to_string (GetLastError ())+ ")" ; 170return false; 171 } 172LARGE_INTEGER sz ; 173if (!GetFileSizeEx (impl_ -> file ,& sz )) { 174err = "DirectFile: cannot size " + path ; 175close (); 176return false; 177 } 178impl_ -> size = (uint64_t )sz .QuadPart ; 179impl_ -> port = CreateIoCompletionPort (impl_ -> file ,nullptr ,0 ,1 ); 180if (impl_ -> port == nullptr ) { 181err = "DirectFile: CreateIoCompletionPort failed (error " + std::to_string (GetLastError ())+ ")" ; 182close (); 183return false; 184 } 185// Completions of reads that finish synchronously are still queued to the port, so every issued read 186// produces exactly one packet; `wait` is the only completion path. 187const int n = io_threads (4 ); 188for (int i = 0 ;i < n ;++ i )impl_ -> pool .emplace_back ([this ] { strata::aux_cpus::pin_current_thread ();impl_ -> worker (); }); 189return true; 190} 191 192void DirectFile ::close () { 193impl_ -> stop_pool (); 194if (impl_ -> port != nullptr )CloseHandle (impl_ -> port ); 195if (impl_ -> file != INVALID_HANDLE_VALUE )CloseHandle (impl_ -> file ); 196impl_ -> port = nullptr ; 197impl_ -> file = INVALID_HANDLE_VALUE ; 198impl_ -> size = 0 ; 199impl_ -> immediate .clear (); 200impl_ -> queue .clear (); 201} 202 203bool DirectFile ::is_open ()const {return impl_ -> file != INVALID_HANDLE_VALUE ; } 204uint64_t DirectFile ::size ()const {return impl_ -> size ; } 205 206bool DirectFile ::submit (uint64_t offset ,void * buffer ,uint32_t length ,uint64_t tag , std::string & err ) { 207if (!is_open ()) {err = "DirectFile: not open" ;return false; } 208if (offset %alignment ()|| length %alignment ()|| ((uintptr_t )buffer ) %alignment ()|| length == 0 ) { 209err = "DirectFile: unaligned request" ; 210return false; 211 } 212 { 213 std::lock_guard < std::mutex > lk (impl_ -> mu ); 214impl_ -> queue .push_back (Pending {offset ,buffer ,length ,tag }); 215 } 216impl_ -> cv .notify_one (); 217return true; 218} 219 220int DirectFile ::wait (Completion * out ,int max ,int timeout_ms ) { 221int n = 0 ; 222 { 223 std::lock_guard < std::mutex > lk (impl_ -> mu ); 224while (n < max && !impl_ -> immediate .empty ()) { 225out [n ++ ]= impl_ -> immediate .front (); 226impl_ -> immediate .pop_front (); 227 } 228 } 229if (n == max || !is_open ())return n ; 230OVERLAPPED_ENTRY entries [64 ]; 231const ULONG want = (ULONG ) (max - n < 64 ?max - n :64 ); 232ULONG got = 0 ; 233const DWORD t = timeout_ms < 0 ?INFINITE : (DWORD )timeout_ms ; 234if (!GetQueuedCompletionStatusEx (impl_ -> port ,entries ,want ,& got ,n > 0 ?0 :t , FALSE))return n ; 235 std::lock_guard < std::mutex > lk (impl_ -> mu ); 236for (ULONG i = 0 ;i < got ;++ i ) { 237if (entries [i ].lpOverlapped == nullptr ) {// a wake() packet (or an immediate completion's nudge) 238while (n < max && !impl_ -> immediate .empty ()) { 239out [n ++ ]= impl_ -> immediate .front (); 240impl_ -> immediate .pop_front (); 241 } 242if (n < max )out [n ++ ]= Completion {WAKE_TAG ,0 , true}; 243continue ; 244 } 245Req * r = (Req * )entries [i ].lpOverlapped ; 246const uint32_t status = (uint32_t )r -> ov .Internal ;// an NTSTATUS 247Completion c ; 248c .tag = r -> tag ; 249c .bytes = entries [i ].dwNumberOfBytesTransferred ; 250// STATUS_END_OF_FILE (0xC0000011) is a legal short read at the table's last page. 251c .ok = status == 0 || status == 0xC0000011u ; 252out [n ++ ]= c ; 253impl_ -> free_reqs .push_back (r ); 254 } 255return n ; 256} 257 258void DirectFile ::wake () { 259if (impl_ -> port != nullptr )PostQueuedCompletionStatus (impl_ -> port ,0 ,0 ,nullptr ); 260} 261 262#else 263// ------------------------------------------------------------------------------------------------ POSIX 264// perf-review F-2: a pool of threads, each doing blocking O_DIRECT preads, so reads run in parallel (the thread 265// count is the queue depth). It replaced one synchronous pread inside `submit`, which read the n-gram table's 266// rows one at a time. 267struct DirectFile ::Impl { 268int fd = -1 ; 269uint64_t size = 0 ; 270 std::mutex mu ; 271 std::condition_variable cv_work ,cv_done ; 272 std::deque < Pending > queue ; 273 std::deque < Completion > done ; 274bool stop = false; 275 std::vector < std::thread > pool ; 276 277void worker () { 278 std::unique_lock < std::mutex > lk (mu ); 279for (;;) { 280cv_work .wait (lk , [& ] {return stop || !queue .empty (); }); 281if (stop && queue .empty ())return ; 282const Pending p = queue .front (); 283queue .pop_front (); 284lk .unlock (); 285const ssize_t got = pread (fd ,p .buffer ,p .length , (off_t )p .offset ); 286lk .lock (); 287done .push_back (Completion {p .tag ,got < 0 ?0u : (uint32_t )got ,got >=0 }); 288cv_done .notify_all (); 289 } 290 } 291 292void stop_pool () { 293 { 294 std::lock_guard < std::mutex > lk (mu ); 295stop = true; 296 } 297cv_work .notify_all (); 298for (std::thread & t :pool )t .join (); 299pool .clear (); 300stop = false; 301 } 302}; 303 304DirectFile ::DirectFile () :impl_ (new Impl ) {} 305DirectFile ::~DirectFile () {close ();delete impl_ ; } 306 307bool DirectFile ::open (const std::string & path , std::string & err ) { 308close (); 309#if defined(__APPLE__ )// macOS has no O_DIRECT: F_NOCACHE keeps the reads out of the unified buffer cache 310impl_ -> fd = ::open (path .c_str (),O_RDONLY ); 311if (impl_ -> fd >=0 && fcntl (impl_ -> fd ,F_NOCACHE ,1 )!= 0 ) { ::close (impl_ -> fd );impl_ -> fd = -1 ; } 312#else 313impl_ -> fd = ::open (path .c_str (),O_RDONLY |O_DIRECT ); 314#endif 315if (impl_ -> fd < 0 ) {err = "DirectFile: cannot open " + path ;return false; } 316struct stat st ; 317if (fstat (impl_ -> fd ,& st )!= 0 ) {err = "DirectFile: cannot size " + path ;close ();return false; } 318impl_ -> size = (uint64_t )st .st_size ; 319const int n = io_threads (16 ); 320for (int i = 0 ;i < n ;++ i )impl_ -> pool .emplace_back ([this ] { strata::aux_cpus::pin_current_thread ();impl_ -> worker (); }); 321return true; 322} 323 324void DirectFile ::close () { 325impl_ -> stop_pool (); 326if (impl_ -> fd >=0 ) ::close (impl_ -> fd ); 327impl_ -> fd = -1 ; 328impl_ -> size = 0 ; 329impl_ -> done .clear (); 330impl_ -> queue .clear (); 331} 332 333bool DirectFile ::is_open ()const {return impl_ -> fd >=0 ; } 334uint64_t DirectFile ::size ()const {return impl_ -> size ; } 335 336bool DirectFile ::submit (uint64_t offset ,void * buffer ,uint32_t length ,uint64_t tag , std::string & err ) { 337if (offset %alignment ()|| length %alignment ()|| ((uintptr_t )buffer ) %alignment ()|| length == 0 ) { 338err = "DirectFile: unaligned request" ; 339return false; 340 } 341 { 342 std::lock_guard < std::mutex > lk (impl_ -> mu ); 343impl_ -> queue .push_back (Pending {offset ,buffer ,length ,tag }); 344 } 345impl_ -> cv_work .notify_one (); 346return true; 347} 348 349void DirectFile ::wake () { 350 std::lock_guard < std::mutex > lk (impl_ -> mu ); 351impl_ -> done .push_back (Completion {WAKE_TAG ,0 , true}); 352impl_ -> cv_done .notify_all (); 353} 354 355int DirectFile ::wait (Completion * out ,int max ,int timeout_ms ) { 356 std::unique_lock < std::mutex > lk (impl_ -> mu ); 357if (impl_ -> done .empty ()&& timeout_ms != 0 ) { 358auto ready = [& ] {return !impl_ -> done .empty (); }; 359if (timeout_ms < 0 )impl_ -> cv_done .wait (lk ,ready ); 360else impl_ -> cv_done .wait_for (lk , std::chrono::milliseconds (timeout_ms ),ready ); 361 } 362int n = 0 ; 363while (n < max && !impl_ -> done .empty ()) { 364out [n ++ ]= impl_ -> done .front (); 365impl_ -> done .pop_front (); 366 } 367return n ; 368} 369#endif 370 371}// namespace strata::platform