hkimi / src /io /file_io.cpp
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
8.24 kB
// Portable part: the buffer type, the convenience reads, the threaded engine, the factory.
#include "io/file_io.h"
#include <algorithm>
#include <condition_variable>
#include <cstring>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include "common/base.h"
#include "io/os_file.h"
namespace hk {
void AlignedBuf::resize(int64_t size) {
reset();
if (size <= 0) return;
n_ = align_up(size);
p_ = (uint8_t*)os::aligned_alloc_bytes(n_, kIoAlign);
HK_CHECK(p_ != nullptr, "out of memory allocating %s", human_bytes((double)n_).c_str());
}
void AlignedBuf::reset() {
if (p_) os::aligned_free(p_);
p_ = nullptr;
n_ = 0;
}
std::string io_error_text(int64_t code) { return os::error_text(code); }
// Reads are split into pieces of this size: no request holds a queue slot for long,
// and Windows' 32-bit read length is never an issue.
static const int64_t kChunk = 8 << 20;
void IoEngine::read_aligned(int file, int64_t offset, int64_t len, uint8_t* dst) {
HK_CHECK(in_flight() == 0, "read_aligned called while async requests are in flight");
HK_CHECK(offset % kIoAlign == 0 && len % kIoAlign == 0, "read_aligned needs 4 KB aligned offset and length");
int64_t fsize = file_size(file);
int submitted = 0;
for (int64_t pos = 0; pos < len; pos += kChunk) {
IoRequest r;
r.file = file;
r.offset = offset + pos;
r.len = std::min(kChunk, len - pos);
r.dst = dst + pos;
r.tag = (uint64_t)pos;
if (r.offset >= fsize) { // entirely past the end: nothing to read
memset(r.dst, 0, (size_t)r.len);
continue;
}
submit(r);
++submitted;
}
IoCompletion c[16];
while (submitted > 0) {
int n = wait(c, 16, 1);
HK_CHECK(n > 0, "I/O engine returned no completions with %d requests outstanding", submitted);
for (int i = 0; i < n; ++i) {
HK_CHECK(c[i].error == 0, "read failed at offset %lld: %s", (long long)(offset + (int64_t)c[i].tag),
io_error_text(c[i].error).c_str());
int64_t pos = (int64_t)c[i].tag;
int64_t want = std::min(kChunk, len - pos);
if (c[i].bytes < want) {
// only legal when the file ends inside this chunk: zero the tail
HK_CHECK(offset + pos + c[i].bytes >= fsize, "short read: %lld of %lld bytes at offset %lld",
(long long)c[i].bytes, (long long)want, (long long)(offset + pos));
memset(dst + pos + c[i].bytes, 0, (size_t)(want - c[i].bytes));
}
}
submitted -= n;
}
}
void IoEngine::read_range(int file, int64_t offset, int64_t len, uint8_t* dst) {
if (len <= 0) return;
HK_CHECK(offset >= 0 && offset + len <= file_size(file), "read_range [%lld, +%lld) is outside the file",
(long long)offset, (long long)len);
int64_t a0 = align_down(offset);
int64_t a1 = align_up(offset + len);
bool dst_aligned = ((uintptr_t)dst % (uintptr_t)kIoAlign) == 0;
if (a0 == offset && a1 == offset + len && dst_aligned) {
read_aligned(file, offset, len, dst);
return;
}
// in pieces, so that a 1 GB tensor does not need a 1 GB bounce buffer
const int64_t kBounce = 32 << 20;
AlignedBuf buf(std::min(kBounce, a1 - a0));
for (int64_t pos = a0; pos < a1; pos += kBounce) {
int64_t n = std::min(kBounce, a1 - pos);
read_aligned(file, pos, n, buf.data());
int64_t lo = std::max(pos, offset), hi = std::min(pos + n, offset + len);
memcpy(dst + (lo - offset), buf.data() + (lo - pos), (size_t)(hi - lo));
}
}
// Threaded engine: N workers doing blocking positional reads. Works everywhere; with
// direct I/O the kernel still sees N requests in flight.
namespace {
class ThreadedIo : public IoEngine {
public:
explicit ThreadedIo(const IoOptions& opt) : opt_(opt) {
int n = std::max(1, opt.threads);
for (int i = 0; i < n; ++i) threads_.emplace_back([this] { worker(); });
}
~ThreadedIo() override {
{
std::lock_guard<std::mutex> lock(mu_);
stop_ = true;
}
cv_req_.notify_all();
for (auto& t : threads_) t.join();
for (auto& f : files_) os::close(f.h);
}
const char* name() const override { return "threads"; }
int open(const std::string& path) override {
File f;
f.h = os::open_read(path, opt_.direct, /*overlapped=*/false, &f.direct);
f.size = os::file_size(f.h);
if (opt_.direct && !f.direct) HK_WARN("%s: direct I/O refused by the filesystem, using buffered reads", path.c_str());
std::lock_guard<std::mutex> lock(mu_);
files_.push_back(f);
return (int)files_.size() - 1;
}
int64_t file_size(int file) const override { return files_.at((size_t)file).size; }
bool is_direct(int file) const override { return files_.at((size_t)file).direct; }
int in_flight() const override { return in_flight_; }
void submit(const IoRequest& r) override {
{
std::lock_guard<std::mutex> lock(mu_);
queue_.push_back(r);
++in_flight_;
}
cv_req_.notify_one();
}
int wait(IoCompletion* out, int max, int min_complete) override {
std::unique_lock<std::mutex> lock(mu_);
int need = std::min(min_complete, in_flight_);
cv_done_.wait(lock, [&] { return (int)done_.size() >= need; });
int n = 0;
while (n < max && !done_.empty()) {
out[n++] = done_.front();
done_.pop_front();
--in_flight_;
}
return n;
}
private:
struct File {
os::Handle h = os::kBadHandle;
int64_t size = 0;
bool direct = false;
};
void worker() {
while (true) {
IoRequest r;
File f;
{
std::unique_lock<std::mutex> lock(mu_);
cv_req_.wait(lock, [&] { return stop_ || !queue_.empty(); });
if (stop_) return;
r = queue_.front();
queue_.pop_front();
f = files_[(size_t)r.file];
}
IoCompletion c;
c.tag = r.tag;
int64_t done = 0;
while (done < r.len) {
int64_t got = os::pread(f.h, r.dst + done, r.len - done, r.offset + done);
if (got < 0) {
c.error = -got;
break;
}
if (got == 0) break; // end of file
done += got;
// a direct read that stops off a 4 KB boundary hit the end of the file
if (f.direct && (got % kIoAlign) != 0) break;
}
c.bytes = done;
{
std::lock_guard<std::mutex> lock(mu_);
done_.push_back(c);
}
cv_done_.notify_all();
}
}
IoOptions opt_;
std::vector<std::thread> threads_;
std::vector<File> files_;
mutable std::mutex mu_;
std::condition_variable cv_req_, cv_done_;
std::deque<IoRequest> queue_;
std::deque<IoCompletion> done_;
bool stop_ = false;
int in_flight_ = 0;
};
} // namespace
std::unique_ptr<IoEngine> make_threaded_io(const IoOptions& opt) { return std::unique_ptr<IoEngine>(new ThreadedIo(opt)); }
std::unique_ptr<IoEngine> IoEngine::create(const IoOptions& opt) {
const std::string& want = opt.engine;
HK_CHECK(want == "auto" || want == "uring" || want == "iocp" || want == "threads",
"unknown I/O engine \"%s\" (use auto, uring, iocp or threads)", want.c_str());
std::unique_ptr<IoEngine> e;
if (want == "auto" || want == "uring") {
e = make_uring_io(opt);
if (e) return e;
HK_CHECK(want == "auto", "io_uring is not available here (old kernel, or blocked as in most Docker setups)");
}
if (want == "auto" || want == "iocp") {
e = make_iocp_io(opt);
if (e) return e;
HK_CHECK(want == "auto", "the completion-port engine only exists on Windows");
}
return make_threaded_io(opt);
}
} // namespace hk