// POSIX file primitives (Linux, macOS, BSD). #if !defined(_WIN32) #include #include #include #include #include #include #include "common/base.h" #include "io/os_file.h" namespace hk { namespace os { Handle open_read(const std::string& path, bool direct, bool /*overlapped*/, bool* got_direct) { *got_direct = false; int fd = -1; #if defined(O_DIRECT) if (direct) { fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC); if (fd >= 0) *got_direct = true; // EINVAL: the filesystem has no O_DIRECT (tmpfs, some network mounts). Open buffered. } #endif if (fd < 0) { fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); HK_CHECK(fd >= 0, "cannot open %s: %s", path.c_str(), strerror(errno)); #if defined(__APPLE__) // macOS has no O_DIRECT; F_NOCACHE turns the page cache off for this descriptor if (direct && fcntl(fd, F_NOCACHE, 1) == 0) *got_direct = true; #endif } return (Handle)fd; } void close(Handle h) { if (h != kBadHandle) ::close((int)h); } int64_t file_size(Handle h) { struct stat st; HK_CHECK(fstat((int)h, &st) == 0, "fstat failed: %s", strerror(errno)); return (int64_t)st.st_size; } int64_t pread(Handle h, uint8_t* dst, int64_t len, int64_t offset) { // one syscall moves at most about 2 GB on Linux; callers loop on short reads const int64_t kMax = (int64_t)1 << 30; size_t want = (size_t)(len > kMax ? kMax : len); while (true) { ssize_t r = ::pread((int)h, dst, want, (off_t)offset); if (r >= 0) return (int64_t)r; if (errno == EINTR) continue; return -(int64_t)errno; } } std::string error_text(int64_t code) { return strerror((int)(code < 0 ? -code : code)); } void* aligned_alloc_bytes(int64_t size, int64_t align) { void* p = nullptr; if (posix_memalign(&p, (size_t)align, (size_t)size) != 0) return nullptr; return p; } void aligned_free(void* p) { free(p); } } // namespace os #if !defined(__linux__) std::unique_ptr make_uring_io(const IoOptions&) { return nullptr; } #endif std::unique_ptr make_iocp_io(const IoOptions&) { return nullptr; } } // namespace hk #endif // !_WIN32