File size: 9,875 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// io_uring engine on the raw syscalls (no liburing). One ring, one thread: submit()
// queues a READV, wait() reaps completions. Where the kernel or a container refuses
// io_uring (Docker's default seccomp profile), the factory falls back to threads.
#if defined(__linux__)

#include "io/os_file.h"

#if defined(HK_HAVE_IO_URING)

#include <cerrno>
#include <cstring>
#include <deque>
#include <vector>

#include <linux/io_uring.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <unistd.h>

#include "common/base.h"

#ifndef __NR_io_uring_setup
#define __NR_io_uring_setup 425
#endif
#ifndef __NR_io_uring_enter
#define __NR_io_uring_enter 426
#endif

namespace hk {
namespace {

int sys_setup(unsigned entries, io_uring_params* p) { return (int)syscall(__NR_io_uring_setup, entries, p); }
int sys_enter(int fd, unsigned to_submit, unsigned min_complete, unsigned flags) {
    return (int)syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, nullptr, 0);
}

class UringIo : public IoEngine {
   public:
    // throws if the ring cannot be created; the factory catches it
    explicit UringIo(const IoOptions& opt) : opt_(opt) {
        unsigned entries = 8;
        while ((int)entries < opt.queue_depth && entries < 4096) entries <<= 1;
        io_uring_params p;
        memset(&p, 0, sizeof(p));
        ring_fd_ = sys_setup(entries, &p);
        if (ring_fd_ < 0) throw Error(strfmt("io_uring_setup: %s", strerror(errno)));
        entries_ = p.sq_entries;

        sq_len_ = p.sq_off.array + p.sq_entries * sizeof(__u32);
        cq_len_ = p.cq_off.cqes + p.cq_entries * sizeof(io_uring_cqe);
        bool single = (p.features & IORING_FEAT_SINGLE_MMAP) != 0;
        if (single) sq_len_ = cq_len_ = std::max(sq_len_, cq_len_);
        sq_ptr_ = mmap(nullptr, sq_len_, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, ring_fd_, IORING_OFF_SQ_RING);
        if (sq_ptr_ == MAP_FAILED) fail_setup("mmap of the submission ring");
        if (single) {
            cq_ptr_ = sq_ptr_;
        } else {
            cq_ptr_ = mmap(nullptr, cq_len_, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, ring_fd_, IORING_OFF_CQ_RING);
            if (cq_ptr_ == MAP_FAILED) fail_setup("mmap of the completion ring");
        }
        sqes_len_ = p.sq_entries * sizeof(io_uring_sqe);
        sqes_ = (io_uring_sqe*)mmap(nullptr, sqes_len_, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, ring_fd_, IORING_OFF_SQES);
        if (sqes_ == MAP_FAILED) fail_setup("mmap of the submission entries");

        char* sq = (char*)sq_ptr_;
        sq_head_ = (unsigned*)(sq + p.sq_off.head);
        sq_tail_ = (unsigned*)(sq + p.sq_off.tail);
        sq_mask_ = *(unsigned*)(sq + p.sq_off.ring_mask);
        sq_array_ = (unsigned*)(sq + p.sq_off.array);
        char* cq = (char*)cq_ptr_;
        cq_head_ = (unsigned*)(cq + p.cq_off.head);
        cq_tail_ = (unsigned*)(cq + p.cq_off.tail);
        cq_mask_ = *(unsigned*)(cq + p.cq_off.ring_mask);
        cqes_ = (io_uring_cqe*)(cq + p.cq_off.cqes);
    }

    ~UringIo() override {
        IoCompletion c;
        while (in_flight() > 0) {
            if (wait(&c, 1, 1) == 0) break;
        }
        for (auto& f : files_) os::close(f.h);
        if (sqes_ && sqes_ != MAP_FAILED) munmap(sqes_, sqes_len_);
        if (cq_ptr_ && cq_ptr_ != MAP_FAILED && cq_ptr_ != sq_ptr_) munmap(cq_ptr_, cq_len_);
        if (sq_ptr_ && sq_ptr_ != MAP_FAILED) munmap(sq_ptr_, sq_len_);
        if (ring_fd_ >= 0) ::close(ring_fd_);
    }

    const char* name() const override { return "io_uring"; }

    int open(const std::string& path) override {
        File f;
        f.h = os::open_read(path, opt_.direct, 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());
        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_kernel_ + (int)pending_.size(); }

    void submit(const IoRequest& r) override {
        Op* op = new Op();
        op->req = r;
        pending_.push_back(op);
        flush();
    }

    int wait(IoCompletion* out, int max, int min_complete) override {
        int n = 0;
        while (n < max) {
            n += reap(out + n, max - n);
            if (n >= max) break;
            flush();
            if (in_flight() == 0) break;
            if (n >= min_complete) break;
            // block for one completion
            int r = sys_enter(ring_fd_, 0, 1, IORING_ENTER_GETEVENTS);
            if (r < 0 && errno != EINTR) HK_FAIL("io_uring_enter: %s", strerror(errno));
        }
        return n;
    }

   private:
    struct Op {
        IoRequest req;
        int64_t done = 0;
        struct iovec iov;
    };
    struct File {
        os::Handle h = os::kBadHandle;
        int64_t size = 0;
        bool direct = false;
    };

    [[noreturn]] void fail_setup(const char* what) {
        std::string msg = strfmt("%s: %s", what, strerror(errno));
        ::close(ring_fd_);
        ring_fd_ = -1;
        throw Error(msg);
    }

    // move queued ops into the submission ring and tell the kernel
    void flush() {
        unsigned to_submit = 0;
        unsigned tail = *sq_tail_;  // only this thread writes the tail
        while (!pending_.empty() && in_kernel_ < (int)entries_) {
            unsigned head = __atomic_load_n(sq_head_, __ATOMIC_ACQUIRE);
            if (tail - head >= entries_) break;  // ring full
            Op* op = pending_.front();
            pending_.pop_front();
            op->iov.iov_base = op->req.dst + op->done;
            op->iov.iov_len = (size_t)(op->req.len - op->done);
            unsigned idx = tail & sq_mask_;
            io_uring_sqe* sqe = &sqes_[idx];
            memset(sqe, 0, sizeof(*sqe));
            sqe->opcode = IORING_OP_READV;  // READV exists on every io_uring kernel (5.1+)
            sqe->fd = (int)files_.at((size_t)op->req.file).h;
            sqe->off = (__u64)(op->req.offset + op->done);
            sqe->addr = (__u64)(uintptr_t)&op->iov;
            sqe->len = 1;
            sqe->user_data = (__u64)(uintptr_t)op;
            sq_array_[idx] = idx;
            ++tail;
            ++to_submit;
            ++in_kernel_;
        }
        if (to_submit == 0) return;
        __atomic_store_n(sq_tail_, tail, __ATOMIC_RELEASE);
        unsigned left = to_submit;
        while (left > 0) {
            int r = sys_enter(ring_fd_, left, 0, 0);
            if (r < 0) {
                if (errno == EINTR || errno == EAGAIN || errno == EBUSY) {
                    // the kernel wants completions reaped first: wait for one and retry
                    sys_enter(ring_fd_, 0, 1, IORING_ENTER_GETEVENTS);
                    stash_completions();
                    continue;
                }
                HK_FAIL("io_uring_enter(submit): %s", strerror(errno));
            }
            left -= (unsigned)r;
        }
    }

    // completions taken off the ring while submitting wait here for wait()
    void stash_completions() {
        IoCompletion c[32];
        int n;
        while ((n = reap_ring(c, 32)) > 0)
            for (int i = 0; i < n; ++i) ready_.push_back(c[i]);
    }

    int reap(IoCompletion* out, int max) {
        int n = 0;
        while (n < max && !ready_.empty()) {
            out[n++] = ready_.front();
            ready_.pop_front();
        }
        if (n < max) n += reap_ring(out + n, max - n);
        return n;
    }

    int reap_ring(IoCompletion* out, int max) {
        int n = 0;
        unsigned head = *cq_head_;
        while (n < max) {
            unsigned tail = __atomic_load_n(cq_tail_, __ATOMIC_ACQUIRE);
            if (head == tail) break;
            io_uring_cqe* cqe = &cqes_[head & cq_mask_];
            Op* op = (Op*)(uintptr_t)cqe->user_data;
            int res = cqe->res;
            ++head;
            --in_kernel_;
            if (res < 0) {
                out[n++] = IoCompletion{op->req.tag, op->done, (int64_t)-res};
                delete op;
                continue;
            }
            op->done += res;
            bool at_eof = op->req.offset + op->done >= files_[(size_t)op->req.file].size;
            if (res > 0 && op->done < op->req.len && !at_eof) {
                pending_.push_front(op);  // short read: ask for the rest
            } else {
                out[n++] = IoCompletion{op->req.tag, op->done, 0};
                delete op;
            }
        }
        __atomic_store_n(cq_head_, head, __ATOMIC_RELEASE);
        return n;
    }

    IoOptions opt_;
    int ring_fd_ = -1;
    unsigned entries_ = 0;
    void* sq_ptr_ = nullptr;
    void* cq_ptr_ = nullptr;
    size_t sq_len_ = 0, cq_len_ = 0, sqes_len_ = 0;
    io_uring_sqe* sqes_ = nullptr;
    unsigned *sq_head_ = nullptr, *sq_tail_ = nullptr, *sq_array_ = nullptr;
    unsigned sq_mask_ = 0;
    unsigned *cq_head_ = nullptr, *cq_tail_ = nullptr;
    unsigned cq_mask_ = 0;
    io_uring_cqe* cqes_ = nullptr;
    std::vector<File> files_;
    std::deque<Op*> pending_;
    std::deque<IoCompletion> ready_;
    int in_kernel_ = 0;
};

}  // namespace

std::unique_ptr<IoEngine> make_uring_io(const IoOptions& opt) {
    try {
        return std::unique_ptr<IoEngine>(new UringIo(opt));
    } catch (const Error& e) {
        HK_DEBUG("io_uring unavailable (%s), falling back", e.what());
        return nullptr;
    }
}

}  // namespace hk

#else  // no <linux/io_uring.h> at build time

namespace hk {
std::unique_ptr<IoEngine> make_uring_io(const IoOptions&) { return nullptr; }
}  // namespace hk

#endif  // HK_HAVE_IO_URING
#endif  // __linux__