Skip to content

Commit e8422de

Browse files
DannyDaemonicvxiiduu
and
vxiiduu
authored
@vxiiduu's fix for PrefetchVirtualMemory (#2930)
Reimplement fix for `PrefetchVirtualMemory`. Co-authored-by: vxiiduu <[email protected]>
1 parent 92d0b75 commit e8422de

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

llama.cpp

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -611,20 +611,25 @@ struct llama_mmap {
611611
throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
612612
}
613613

614-
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
615614
if (prefetch) {
616-
// Advise the kernel to preload the mapped memory
617-
WIN32_MEMORY_RANGE_ENTRY range;
618-
range.VirtualAddress = addr;
619-
range.NumberOfBytes = (SIZE_T)size;
620-
if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
621-
fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
622-
llama_format_win_err(GetLastError()).c_str());
615+
// PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
616+
BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
617+
HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
618+
619+
// may fail on pre-Windows 8 systems
620+
pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
621+
622+
if (pPrefetchVirtualMemory) {
623+
// advise the kernel to preload the mapped memory
624+
WIN32_MEMORY_RANGE_ENTRY range;
625+
range.VirtualAddress = addr;
626+
range.NumberOfBytes = (SIZE_T)size;
627+
if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
628+
fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
629+
llama_format_win_err(GetLastError()).c_str());
630+
}
623631
}
624632
}
625-
#else
626-
#pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
627-
#endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
628633
}
629634

630635
~llama_mmap() {

0 commit comments

Comments
 (0)