diff --git a/CHANGELOG.md b/CHANGELOG.md index acd8f18..b015469 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,29 @@ All notable changes to the AVA1 crates and C library. The wire format is version 1 throughout; see [README](README.md#versions). +## 1.0.9 + +Read-back while the file arrives. Nothing changes on the wire format. + +C library: + +- The read-back now runs while a large file arrives: each part is read back as soon as it is safely on + the drive, and only what is left (usually the last few MiB) is read after the last byte. It used to + read every file again from the start after its last byte, which added about 30% to a large transfer + (19.5 s on a 4 GiB file on a PS5 Pro). It runs on 6 threads of its own, so a busy upload does not + hold it back, and it backs off to one read at a time while the incoming data waits to be written. +- The read-back now reads from the drive, not from memory. Read right after it was written, a file is + still in the system's cache, and a check against that copy cannot find a fault on the drive. Each + part is now dropped from the cache before it is read, and read with direct I/O where the system + allows. The log says once per job which method is in use, or that the read may come from the cache + (macOS has no way to drop it). +- A mismatch is still handled when the file is finished, as before. The read after the last byte uses + 8 threads of 8 MiB reads. The end-of-job line says how much was read back while files arrived (with + how many ranges and reads that took), how much after, and how long the threads spent reading and + hashing. +- Measured on a PS5 Pro, 4 GiB to the internal drive: 60.4 s with the check, against 83.5 s for the + 1.0.8 check and about 62 s with no check at all. + ## 1.0.8 Read-back verification. Nothing changes on the wire format: the receiver advertises a new capability bit, and a sender that sets the new job flag gets the check. diff --git a/Cargo.lock b/Cargo.lock index f886da1..cc9693a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -55,7 +55,7 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "ava1" -version = "1.0.8" +version = "1.0.9" dependencies = [ "ava1-chaos", "blake2 0.11.0", @@ -74,14 +74,14 @@ dependencies = [ [[package]] name = "ava1-chaos" -version = "1.0.8" +version = "1.0.9" dependencies = [ "tokio", ] [[package]] name = "ava1-ctest" -version = "1.0.8" +version = "1.0.9" dependencies = [ "ava1", "ava1-chaos", @@ -93,7 +93,7 @@ dependencies = [ [[package]] name = "ava1-gen" -version = "1.0.8" +version = "1.0.9" dependencies = [ "serde", "toml", diff --git a/Cargo.toml b/Cargo.toml index 1626331..8b33c3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ resolver = "3" [workspace.package] edition = "2021" license = "MIT OR Apache-2.0" -version = "1.0.8" +version = "1.0.9" # File::lock (1.89). CI builds the published crates with exactly this version. rust-version = "1.89" repository = "https://github.com/phantomptr/ava1" diff --git a/c/ava1_apply.c b/c/ava1_apply.c index 865a302..e28476d 100644 --- a/c/ava1_apply.c +++ b/c/ava1_apply.c @@ -251,6 +251,7 @@ static int u32cmp(const void *a, const void *b); static int stopping_cb(void *a); static void run_commit(ava1_job_t *j, uint32_t id); static void run_work(ava1_job_t *j, ava1_work_t *w); +static void rb_live_kick(ava1_job_t *j); /* A lf with nothing left for a batch, a commit or a snapshot to do. */ static int lf_idle(const ava1_job_t *j, uint32_t id, const ava1_lfile_t *lf) { @@ -326,6 +327,7 @@ static int write_all(int fd, const uint8_t *p, size_t n) { } size_t ava1_test_pwrite_max; +uint32_t ava1_test_chunk_delay_ms; static int pwrite_all(int fd, const uint8_t *p, size_t n, uint64_t off) { while (n) { @@ -475,13 +477,25 @@ size_t ava1_apply_summary(const ava1_job_t *j, char *out, size_t cap) { #undef SHARE if (n < 0) return 0; if ((size_t)n < cap && __atomic_load_n(&j->rb_files, __ATOMIC_RELAXED)) { - uint64_t us = __atomic_load_n(&j->rb_us, __ATOMIC_RELAXED), by = __atomic_load_n(&j->rb_bytes, __ATOMIC_RELAXED); - int m = snprintf(out + n, cap - (size_t)n, "; read back %llu files, %llu MiB in %llu ms (%.0f MiB/s; threads spent %llu ms reading, %llu ms hashing), %llu mismatches", + /* rb_us is the commits' read-back time, what the job waits for: the rate is of what they read */ + uint64_t us = __atomic_load_n(&j->rb_us, __ATOMIC_RELAXED), by = __atomic_load_n(&j->rb_bytes, __ATOMIC_RELAXED), + live = __atomic_load_n(&j->rb_live_bytes, __ATOMIC_RELAXED), after = __atomic_load_n(&j->rb_after_bytes, __ATOMIC_RELAXED); + int m = snprintf(out + n, cap - (size_t)n, + "; read back %llu files, %llu MiB: %llu MiB while they arrived (%llu ranges handed over, %llu reads, %llu " + "with chunks waiting), %llu MiB after their last byte in %llu ms (%.0f MiB/s; threads spent %llu ms " + "reading, %llu ms hashing; %llu of %llu reads with the cache dropped first, %llu with O_DIRECT), " + "%llu mismatches", (unsigned long long)__atomic_load_n(&j->rb_files, __ATOMIC_RELAXED), - (unsigned long long)(by >> 20), (unsigned long long)(us / 1000u), - us ? (double)by / 1048576.0 / ((double)us / 1e6) : 0.0, + (unsigned long long)(by >> 20), (unsigned long long)(live >> 20), + (unsigned long long)__atomic_load_n(&j->rb_todo_ranges, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&j->rb_live_reads, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&j->rb_live_crowded, __ATOMIC_RELAXED), (unsigned long long)(after >> 20), + (unsigned long long)(us / 1000u), us ? (double)after / 1048576.0 / ((double)us / 1e6) : 0.0, (unsigned long long)(__atomic_load_n(&j->rb_read_us, __ATOMIC_RELAXED) / 1000u), (unsigned long long)(__atomic_load_n(&j->rb_hash_us, __ATOMIC_RELAXED) / 1000u), + (unsigned long long)__atomic_load_n(&j->rb_drops_ok, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&j->rb_drops, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&j->rb_direct_reads, __ATOMIC_RELAXED), (unsigned long long)__atomic_load_n(&j->rb_mismatches, __ATOMIC_RELAXED)); if (m > 0) n += m; } @@ -504,6 +518,7 @@ void ava1_apply_fail(ava1_job_t *j, uint16_t status, const char *what, int err, * the data budget at once, not when the job is finally freed. */ credit = j->credit; j->credit = 0; + pthread_cond_broadcast(&j->rb_cv); /* the live read-back threads end */ } /* Commits already queued or running must finish (a queued one starts, sees `finished` and * returns) before Done is appended and JobDone sent: nothing may be journaled or acknowledged @@ -513,7 +528,7 @@ void ava1_apply_fail(ava1_job_t *j, uint16_t status, const char *what, int err, if (!first) return; ava1_log_job_event(status == AVA1_STATUS_OK ? "done" : "fail", j, status); if (j->start_us) { /* the apply engine ran: where its time went (a download or a move has none) */ - char line[600]; + char line[800]; (void)ava1_apply_summary(j, line, sizeof line); fprintf(stderr, "%s\n", line); } @@ -1044,6 +1059,10 @@ static int write_chunk(ava1_job_t *j, uint32_t id, uint64_t off, const uint8_t * if (ob >= 0) close(ob); return -err; } + { + uint32_t ms = __atomic_load_n(&ava1_test_chunk_delay_ms, __ATOMIC_RELAXED); + if (ms) ava1_platform_sleep_ms(ms); /* tests: a drive slow enough to keep every worker busy */ + } err = pwrite_all(fd, d, len, off); if (err == 0 && ob >= 0) { for (g = off / AVA1_GROUP_LEN; g * AVA1_GROUP_LEN < off + len; g++) { @@ -1066,7 +1085,18 @@ static int write_chunk(ava1_job_t *j, uint32_t id, uint64_t off, const uint8_t * } pthread_mutex_lock(&j->mu); lf->writers--; - if (!lf->committed) (void)ava1_rset_add(&lf->written, off, off + len); /* else: a late duplicate */ + if (!lf->committed) { /* else: a late duplicate */ + (void)ava1_rset_add(&lf->written, off, off + len); + /* Over durable bytes (a duplicate): they are not durable again until their batch, so what was read + * back of them no longer counts, and a read-back of the file in flight is void (see "read-back"). */ + if (ava1_rset_overlaps(&lf->durable, off, off + len)) { + if (ava1_rset_remove(&lf->rb_todo, off, off + len) < 0) ava1_rset_clear(&lf->rb_todo); + if (ava1_rset_remove(&lf->rb_done, off, off + len) < 0) ava1_rset_clear(&lf->rb_done); + if (lf->rb_found && lf->rb_found_g * AVA1_GROUP_LEN >= off && lf->rb_found_g * AVA1_GROUP_LEN < off + len) + lf->rb_found = 0; /* the wrong group was written again: it is read back again */ + lf->rb_gen++; + } + } j->unsynced_bytes += len; j->bytes_received += len; j->applied_since_tune++; @@ -2621,7 +2651,12 @@ static void sync_batch(ava1_job_t *j) { } for (i = 0; i < ng; i++) { ava1_lfile_t *lf = j->lf[rg[i].file_id]; - if (lf) (void)ava1_rset_add(&lf->durable, rg[i].offset, rg[i].offset + rg[i].len); + if (!lf) continue; + (void)ava1_rset_add(&lf->durable, rg[i].offset, rg[i].offset + rg[i].len); + /* JF_READBACK: durable now, so the live read-back may take them (out of memory: the commit does). */ + if (j->readback && groups_of(j->m.e[rg[i].file_id].size) >= 2 && !lf->committed && !lf->committing && + ava1_rset_add(&lf->rb_todo, rg[i].offset, rg[i].offset + rg[i].len) == 0) + __atomic_add_fetch(&j->rb_todo_ranges, 1, __ATOMIC_RELAXED); } for (i = 0; i < nroots; i++) if (j->lf[roots[i].file_id] && memcmp(j->lf[roots[i].file_id]->root, roots[i].root, 32) == 0) @@ -2865,6 +2900,11 @@ void ava1_apply_reset(ava1_job_t *j, uint32_t id, uint16_t reason) { j->bytes_durable -= ava1_rset_covered(&lf->durable); ava1_rset_clear(&lf->written); ava1_rset_clear(&lf->durable); + ava1_rset_clear(&lf->rb_todo); + ava1_rset_clear(&lf->rb_done); + lf->rb_found = 0; + lf->rb_found_g = 0; + lf->rb_gen++; /* a live read-back of the old bytes in flight counts for nothing */ lf->has_root = lf->root_journaled = 0; lf->committing = 0; /* a commit that found its bytes wrong starts the file over */ /* Our own descriptor, taken under the lock: from here lf is evictable, and a worker in lf_slots @@ -2903,16 +2943,38 @@ static int read_root(ava1_job_t *j, uint32_t id, uint8_t root[32]) { return k == (ssize_t)(n * 32u) ? 0 : -EIO; } -/* JF_READBACK (SPEC.md §13.5). The commit has just checked that the outboard's group CVs merge to the - * sender's root, but those CVs were computed from the bytes as they arrived, not from the drive. This - * reads the part file back (every byte is durable by now) and compares each group's CV with the - * outboard's, so a write that landed wrong (a short or misplaced write, a filesystem or drive fault, - * another process writing the file) is found before the file counts as done. A big file is read in - * stripes on a few threads of its own: the last file of a job is read back after its last byte, with - * nothing else to overlap, so its read-back is the whole of what the check adds to the job. */ -#define READBACK_GROUPS 8u /* groups per read (8 MiB; 8 threads: 64 MiB in all) */ -#define READBACK_STRIPES 8u /* threads for one big file, the worker included */ -#define READBACK_STRIPE_MIN (256ull << 20) /* a file below two of these is read by the worker alone */ +/* JF_READBACK (SPEC.md §13.5). Every check before the commit hashes the bytes as they arrived; this reads + * the part file back from the drive and compares each group's CV with the outboard's, so a write that + * landed wrong (a short or misplaced write, a filesystem or drive fault, another process writing the + * file) is found before the file counts as done. + * + * It runs in two parts, so that it costs the job little more than the tail of its last file: + * + * - While a file arrives (the live read-back). Each sync batch hands the large-file ranges it has just + * made durable (fsynced, outboard included, and journaled) to lf->rb_todo and wakes the job's read-back + * threads (AVA1_READBACK_THREADS, each one read of READBACK_GROUPS groups in flight). They take whole + * groups from there, read them back and record them in lf->rb_done. They are threads of their own, not + * the workers', so a steady stream of chunks never keeps them from reading; while chunks wait for a + * worker (the receive path is behind) all but one hold back, so they share the drive with one read in + * flight at most. They can never read more than the batches have written. On a drive that + * reads faster than the network delivers they keep up with the write front. Lanes write out of order: + * rb_todo is a range set, so any order is fine. A write over durable bytes (a late duplicate) takes its + * range out of rb_todo and rb_done and bumps lf->rb_gen, which voids any read-back of the file in flight: + * those bytes are read again once their own batch has made them durable. A reset does the same. A + * mismatch is not acted on there (an old sender does not expect a FileRetry for a file it is still + * sending): it is recorded (rb_found) and the commit acts on it as on its own. + * + * - At the commit, every group the live part did not read (the last batch's, those it had no time for, + * all of a file made durable before this process started) is read back as before, in stripes on a few + * threads of its own: the last file of a job has nothing left to overlap with. + * + * So every group is read back once after it was last made durable, and a byte that changes on the drive + * before its group is read back is found. One that changes after its group was read back (while the rest + * of the file still arrives) is not: the read-back proves what the drive held after the write, not that + * nothing touches the file later, which no check before the rename could promise either. */ +#define READBACK_GROUPS 8u /* groups per read (8 MiB) */ +#define READBACK_STRIPES 8u /* buffers (and threads) per job: 64 MiB at most, live reads included */ +#define READBACK_STRIPE_MIN (256ull << 20) /* what is left below two of these is read by the commit's worker alone */ static int pread_full(int fd, uint8_t *p, size_t len, uint64_t off, size_t *have) { *have = 0; while (*have < len) { @@ -2925,61 +2987,316 @@ static int pread_full(int fd, uint8_t *p, size_t len, uint64_t off, size_t *have return 0; } -typedef struct { - ava1_job_t *j; - uint64_t from, to; /* [from, to): group-aligned, `to` the file's size for the last stripe */ - int fd, ob_fd; - int *quit; /* shared: set when a stripe has the answer (a mismatch or an error) */ - uint64_t bad; - int rc; -} rb_stripe_t; +void (*ava1_apply_rb_hook)(ava1_job_t *j, uint32_t id, uint64_t off, uint64_t len, int fd, int live); -/* 0 = the stripe matches; 1 = it does not (bad = the first group that differs; a file shorter than its - * size counts as wrong); -errno = it could not be read; -EINTR = the job is ending, or another stripe - * already has the answer. */ -static int readback_stripe(rb_stripe_t *s) { - uint8_t *buf = malloc(READBACK_GROUPS * (size_t)AVA1_GROUP_LEN), cvs[READBACK_GROUPS][32]; - uint64_t off = s->from; - int rc = 0; - if (!buf) return -ENOMEM; - while (!rc && off < s->to) { - uint64_t g0 = off / AVA1_GROUP_LEN; - size_t len = s->to - off < READBACK_GROUPS * AVA1_GROUP_LEN ? (size_t)(s->to - off) - : READBACK_GROUPS * (size_t)AVA1_GROUP_LEN; +static int rb_ending(ava1_job_t *j) { + return is_stopping(j) || __atomic_load_n(&j->finished, __ATOMIC_RELAXED) || __atomic_load_n(&j->final_status, __ATOMIC_RELAXED); +} + +/* ---- reading from the drive ---- + * Read right after its batch, a range is still in the page cache, and a read answered from there proves + * nothing about the drive (on a console the live reads ran at ~1 GiB/s, the drive's are ~30 MiB/s a + * thread). So before each read its pages are dropped from the cache (ava1_platform_drop_cache: they are + * clean, the batch synced them), and the read goes through a descriptor of its own opened with O_DIRECT + * where the OS has one. Either may be refused (an OS without the call, a filesystem without direct I/O, + * a piece O_DIRECT cannot align): the read then goes through the cache as before, and the job's one + * "read-back ..." line says which. */ +#define RB_ALIGN 4096u /* O_DIRECT: buffer, offset and length in multiples of this */ + +/* A read-only descriptor of file `id`'s part file with O_DIRECT, or -1 (the errno is kept for the job's + * line: none on this OS, or not on this filesystem). */ +static int rb_open_direct(ava1_job_t *j, uint32_t id) { + char p[PATH_CAP]; + int fd; + ava1_apply_path(j, id, 1, p, sizeof p); + if (!p[0]) return -1; + if ((fd = ava1_platform_open_direct(p)) < 0) __atomic_store_n(&j->rb_direct_err, errno ? errno : EINVAL, __ATOMIC_RELAXED); + return fd; +} + +/* An 8 MiB read-back buffer, aligned for O_DIRECT. */ +static uint8_t *rb_buf_alloc(void) { + void *p = NULL; + return posix_memalign(&p, RB_ALIGN, READBACK_GROUPS * (size_t)AVA1_GROUP_LEN) == 0 ? p : NULL; +} + +/* The job's one line on how its read-back reaches the drive, from its first read. */ +static void rb_say_how(ava1_job_t *j, int drop, const char *how, int direct) { + char line[256]; + const char *nodirect = strerror(__atomic_load_n(&j->rb_direct_err, __ATOMIC_RELAXED)); + if (__atomic_exchange_n(&j->rb_how_logged, 1, __ATOMIC_RELAXED)) return; + if (direct && !drop) + snprintf(line, sizeof line, "read-back from the drive: O_DIRECT reads + %s", how); + else if (direct) + snprintf(line, sizeof line, "read-back from the drive: O_DIRECT reads (%s failed: %s)", how, strerror(drop)); + else if (!drop) + snprintf(line, sizeof line, "read-back from the drive: %s (no O_DIRECT: %s)", how, nodirect); + else + snprintf(line, sizeof line, "read-back may read cached pages: %s: %s, and no O_DIRECT: %s", how, strerror(drop), + nodirect); + fprintf(stderr, "[ava1] job %02x%02x%02x%02x: %s\n", j->id[0], j->id[1], j->id[2], j->id[3], line); +} + +/* Reads groups [from, to) of file `id` (bytes: `from` group-aligned, `to` too or the file's size) back + * and compares each group's CV with the outboard's, READBACK_GROUPS at a time into `buf` (rb_buf_alloc). + * `rfd` reads (O_DIRECT, or `pfd` itself); `pfd` is the part file's ordinary descriptor: the cache is + * dropped through it, and it reads what O_DIRECT will not. 0 = they match; 1 = they do not (*bad = the + * first group that differs; a file shorter than its size counts as wrong); -errno = they could not be + * read; -EINTR = the job is ending, or `*quit` was set (another stripe already has the answer). */ +static int rb_check(ava1_job_t *j, uint32_t id, int rfd, int pfd, int ob_fd, uint64_t from, uint64_t to, uint8_t *buf, + const int *quit, int live, uint64_t *bad) { + uint8_t cvs[READBACK_GROUPS][32]; + uint64_t off = from; + while (off < to) { + uint64_t g0 = off / AVA1_GROUP_LEN, t_read, t_hash; + size_t len = to - off < READBACK_GROUPS * AVA1_GROUP_LEN ? (size_t)(to - off) : READBACK_GROUPS * (size_t)AVA1_GROUP_LEN; size_t ng = (size_t)groups_of(len), have = 0, ob_have = 0, at; - if (__atomic_load_n(s->quit, __ATOMIC_RELAXED) || is_stopping(s->j) || - __atomic_load_n(&s->j->finished, __ATOMIC_RELAXED) || __atomic_load_n(&s->j->final_status, __ATOMIC_RELAXED)) { - rc = -EINTR; - break; - } - if ((rc = pread_full(s->ob_fd, &cvs[0][0], ng * 32u, g0 * 32u, &ob_have)) != 0) break; - if (ob_have != ng * 32u) { - rc = -EIO; /* the outboard was whole a moment ago (read_root) */ - break; + const char *how = ""; + int rc, drop; + if ((quit && __atomic_load_n(quit, __ATOMIC_RELAXED)) || rb_ending(j)) return -EINTR; + if ((rc = pread_full(ob_fd, &cvs[0][0], ng * 32u, g0 * 32u, &ob_have)) != 0) return rc; + if (ob_have != ng * 32u) return -EIO; /* the outboard is preallocated to every group's CV */ + if (ava1_apply_rb_hook) ava1_apply_rb_hook(j, id, off, len, pfd, live); + t_read = mono_us(); + drop = ava1_platform_drop_cache(pfd, off, len, &how); + __atomic_add_fetch(&j->rb_drops, 1, __ATOMIC_RELAXED); + if (!drop) __atomic_add_fetch(&j->rb_drops_ok, 1, __ATOMIC_RELAXED); + rb_say_how(j, drop, how, rfd != pfd); + rc = -EINVAL; + if (rfd != pfd) { /* whole aligned blocks: the file ends inside the last one, so it reads short */ + size_t alen = (len + RB_ALIGN - 1) / RB_ALIGN * RB_ALIGN; + rc = pread_full(rfd, buf, alen, off, &have); + if (rc == 0) { + if (have > len) have = len; + __atomic_add_fetch(&j->rb_direct_reads, 1, __ATOMIC_RELAXED); + } } - uint64_t t_read = mono_us(); - if ((rc = pread_full(s->fd, buf, len, off, &have)) != 0) break; - uint64_t t_hash = mono_us(); - __atomic_add_fetch(&s->j->rb_read_us, t_hash - t_read, __ATOMIC_RELAXED); + if (rc == -EINVAL && (rc = pread_full(pfd, buf, len, off, &have)) != 0) return rc; /* no O_DIRECT for this one */ + if (rc) return rc; + t_hash = mono_us(); + __atomic_add_fetch(&j->rb_read_us, t_hash - t_read, __ATOMIC_RELAXED); for (at = 0; at < len; at += AVA1_GROUP_LEN) { size_t glen = len - at < AVA1_GROUP_LEN ? len - at : (size_t)AVA1_GROUP_LEN; - uint64_t g = g0 + at / AVA1_GROUP_LEN; uint8_t cv[32]; if (at + glen > have) { /* shorter than its size: the groups past here cannot match */ - s->bad = g; + *bad = g0 + at / AVA1_GROUP_LEN; rc = 1; break; } - ava1_b3_group_cv(buf + at, glen, g, cv); + ava1_b3_group_cv(buf + at, glen, g0 + at / AVA1_GROUP_LEN, cv); if (memcmp(cv, cvs[at / AVA1_GROUP_LEN], 32) != 0) { - s->bad = g; + *bad = g0 + at / AVA1_GROUP_LEN; rc = 1; break; } } - __atomic_add_fetch(&s->j->rb_hash_us, mono_us() - t_hash, __ATOMIC_RELAXED); + __atomic_add_fetch(&j->rb_hash_us, mono_us() - t_hash, __ATOMIC_RELAXED); + if (rc) return rc; off += len; } + return 0; +} + +/* ---- the live read-back ---- */ + +/* Caller holds j->mu. Live read-backs may run: the job takes data, asked for the read-back, and is not + * being re-prepared (a changed manifest renumbers the files: ava1_apply_quiesce waits for the live reads + * in flight, and no new one starts while the feed is held). */ +static int rb_live_on(const ava1_job_t *j) { + return j->readback && j->prepared && !j->feed_hold && !j->finished && !j->final_status && !j->stopping; +} + +/* Caller holds j->mu. A file the live read-back may take groups of now. */ +static int rb_live_file(const ava1_job_t *j, uint32_t id) { + const ava1_lfile_t *lf = id < j->m.n ? j->lf[id] : NULL; + return lf && lf->rb_todo.n && !lf->rb_found && !lf->committed && !lf->committing && lf->fd >= 0 && lf->ob_fd >= 0 && + !ava1_bits_get(&j->done, id); +} + +/* Caller holds j->mu. The first file with groups to read back live, or UINT32_MAX. */ +static uint32_t rb_live_next(const ava1_job_t *j) { + uint32_t k; + if (j->lfl_all) { + for (k = 0; k < j->m.n; k++) + if (rb_live_file(j, k)) return k; + } else { + for (k = 0; k < j->lfl_n; k++) + if (rb_live_file(j, j->lfl[k])) return j->lfl[k]; + } + return UINT32_MAX; +} + +/* Caller holds j->mu. 1 when chunks (or other work) wait in the queue and the free workers cannot take all + * of it at once: the receive path is behind, so the live read-back keeps to one read in flight. */ +static int rb_live_crowded(const ava1_job_t *j) { + uint32_t idle = j->want_workers > j->busy ? j->want_workers - j->busy : 0; + return j->q_len > idle; +} + +/* Caller holds j->mu, held again on return (released for the read). One live read: up to READBACK_GROUPS + * durable groups of the first file with any, read back and recorded. 0 = nothing to take now, 1 = one + * read done (whatever it found). */ +static int rb_live_one(ava1_job_t *j, int crowded) { + uint32_t id, gen; + uint64_t from = 0, to = 0, size, bad = 0; + int fd = -1, ob = -1, rfd, rc; + uint8_t *buf; + ava1_lfile_t *lf; + for (;;) { + uint64_t a, b; + if (!rb_live_on(j) || j->rb_bufs >= READBACK_STRIPES || (id = rb_live_next(j)) == UINT32_MAX) return 0; + lf = j->lf[id]; + size = j->m.e[id].size; + a = lf->rb_todo.v[0]; + b = lf->rb_todo.v[1]; + /* Whole groups only (a range's start is a chunk's, so group-aligned; its end is too, or the + * file's): a piece that is not is left to the commit. */ + from = (a + AVA1_GROUP_LEN - 1) / AVA1_GROUP_LEN * AVA1_GROUP_LEN; + to = b >= size ? size : b / AVA1_GROUP_LEN * AVA1_GROUP_LEN; + if (from < to && to - from > READBACK_GROUPS * AVA1_GROUP_LEN) to = from + READBACK_GROUPS * AVA1_GROUP_LEN; + if (ava1_rset_remove(&lf->rb_todo, a, from < to ? to : b) < 0) ava1_rset_clear(&lf->rb_todo); + if (from < to) break; + } + fd = dup(lf->fd); + ob = dup(lf->ob_fd); + if (fd < 0 || ob < 0) { /* no descriptor to spare: the commit reads these groups */ + if (fd >= 0) close(fd); + if (ob >= 0) close(ob); + return 0; + } + gen = lf->rb_gen; + lf->rb_busy++; + j->rb_bufs++; + j->rb_live_run++; + pthread_mutex_unlock(&j->mu); + if ((rfd = rb_open_direct(j, id)) < 0) rfd = fd; + if (!(buf = rb_buf_alloc())) rc = -ENOMEM; + else rc = rb_check(j, id, rfd, fd, ob, from, to, buf, NULL, 1, &bad); + free(buf); + if (rfd != fd) close(rfd); + close(fd); + close(ob); + __atomic_add_fetch(&j->rb_live_reads, 1, __ATOMIC_RELAXED); + if (crowded) __atomic_add_fetch(&j->rb_live_crowded, 1, __ATOMIC_RELAXED); + pthread_mutex_lock(&j->mu); + lf->rb_busy--; + j->rb_bufs--; + j->rb_live_run--; + /* lf is still j->lf[id]: a file's lf is freed or moved only with no live read in flight (quiesce waits + * for rb_live_run, teardown joins these threads first). */ + if (lf->rb_gen == gen) { /* else: reset or written over since: what was read says nothing */ + if (rc == 0) { + (void)ava1_rset_add(&lf->rb_done, from, to); /* out of memory: the commit reads them again */ + __atomic_add_fetch(&j->rb_live_bytes, to - from, __ATOMIC_RELAXED); + } else if (rc == 1 && (!lf->rb_found || bad < lf->rb_found_g)) { + lf->rb_found = 1; + lf->rb_found_g = bad; + } + /* -errno: left to the commit, which reads them again and reports a failure that lasts */ + } + pthread_cond_broadcast(&j->cv); /* a commit or a quiesce may wait for this read */ + return 1; +} + +typedef struct { + ava1_job_t *j; + uint32_t idx; +} rb_thr_t; + +/* One live read-back thread. They read while there is durable work, all of them while the workers keep + * up with the chunks, only the first (one read in flight) while chunks wait for a worker; they never take + * a worker. Idle, they wait for the next batch. */ +static void *rb_live_main(void *arg) { + rb_thr_t *t = arg; + ava1_job_t *j = t->j; + uint32_t idx = t->idx; + free(t); + pthread_mutex_lock(&j->mu); + while (!j->stopping && !j->finished) { /* an ended job reads nothing more: its threads go */ + int crowded; + if (!rb_live_on(j) || rb_live_next(j) == UINT32_MAX) { + pthread_cond_wait(&j->rb_cv, &j->mu); /* the next batch, the job's end or its stop wakes us */ + continue; + } + crowded = rb_live_crowded(j); + if (crowded && idx > 0) { /* the receive path is behind: leave the drive to it but for one read */ + pthread_mutex_unlock(&j->mu); + ava1_platform_sleep_ms(20); + pthread_mutex_lock(&j->mu); + continue; + } + if (!rb_live_one(j, crowded) && !j->stopping && !j->finished) pthread_cond_wait(&j->rb_cv, &j->mu); + } + pthread_mutex_unlock(&j->mu); + return NULL; +} + +/* Job thread, after each batch: wakes the live read-back threads, starting them the first time there is + * durable work for them. */ +static void rb_live_kick(ava1_job_t *j) { + uint32_t k, n = 0; + int start; + pthread_mutex_lock(&j->mu); + start = !j->rb_th_n && rb_live_on(j) && rb_live_next(j) != UINT32_MAX; + if (!start) { + if (j->rb_th_n) pthread_cond_broadcast(&j->rb_cv); + pthread_mutex_unlock(&j->mu); + return; + } + pthread_mutex_unlock(&j->mu); + for (k = 0; k < AVA1_READBACK_THREADS; k++) { + rb_thr_t *t = malloc(sizeof *t); + if (!t) break; + t->j = j; + t->idx = n; + if (ava1_thread_start(rb_live_main, t, &j->rb_th[n]) != 0) { + free(t); + break; + } + n++; + } + pthread_mutex_lock(&j->mu); + j->rb_th_n = n; /* written by the job thread only; job_destroy reads it after joining that thread */ + pthread_cond_broadcast(&j->rb_cv); + pthread_mutex_unlock(&j->mu); + fprintf(stderr, "[ava1] job %02x%02x%02x%02x: read-back: %u threads read large files back as they arrive\n", j->id[0], + j->id[1], j->id[2], j->id[3], n); +} + +/* ---- the commit's read-back ---- */ + +typedef struct { + uint64_t g0, g1; /* groups [g0, g1) */ +} rb_span_t; + +typedef struct { + ava1_job_t *j; + uint32_t id; + const rb_span_t *sp; /* the groups to read, in order */ + uint32_t nsp; + uint64_t from, to; /* this stripe's share: the from-th to the to-th group of those */ + uint64_t size; + int fd, rfd, ob_fd; /* rfd: what reads (O_DIRECT, or fd); see rb_check */ + int *quit; /* shared: set when a stripe has the answer (a mismatch or an error) */ + uint64_t bad; + int rc; +} rb_stripe_t; + +/* rb_check over the stripe's share of the spans. */ +static int readback_stripe(rb_stripe_t *s) { + uint8_t *buf = rb_buf_alloc(); + uint64_t at = 0; /* groups of the spans before sp[k] */ + uint32_t k; + int rc = 0; + if (!buf) rc = -ENOMEM; + for (k = 0; !rc && k < s->nsp && at < s->to; k++) { + uint64_t n = s->sp[k].g1 - s->sp[k].g0, lo = s->from > at ? s->from - at : 0, hi = s->to - at < n ? s->to - at : n; + if (lo < hi) { + uint64_t b0 = (s->sp[k].g0 + lo) * AVA1_GROUP_LEN, b1 = (s->sp[k].g0 + hi) * AVA1_GROUP_LEN; + rc = rb_check(s->j, s->id, s->rfd, s->fd, s->ob_fd, b0, b1 < s->size ? b1 : s->size, buf, s->quit, 0, &s->bad); + } + at += n; + } free(buf); if (rc && rc != -EINTR) __atomic_store_n(s->quit, 1, __ATOMIC_RELAXED); return rc; @@ -2991,26 +3308,44 @@ static void *readback_stripe_main(void *arg) { return NULL; } -/* 0 = the drive holds what was sent; 1 = it does not (*bad = the first group found wrong); -errno = - * it could not be read; -EINTR = the job is ending. */ -static int readback_large(ava1_job_t *j, uint32_t id, int fd, int ob_fd, uint64_t *bad) { - uint64_t size = j->m.e[id].size, groups = groups_of(size), per; +/* Reads back the groups in `sp` (`total` of them), in stripes when they are many. 0 = the drive holds + * what was sent; 1 = it does not (*bad = the first group found wrong); -errno = it could not be read; + * -EINTR = the job is ending. */ +static int readback_large(ava1_job_t *j, uint32_t id, int fd, int rfd, int ob_fd, const rb_span_t *sp, uint32_t nsp, uint64_t total, + uint64_t *bad) { + uint64_t size = j->m.e[id].size, per; rb_stripe_t s[READBACK_STRIPES]; pthread_t th[READBACK_STRIPES]; int started[READBACK_STRIPES] = { 0 }, quit = 0, rc = 0; uint32_t n = 1, k; *bad = 0; - if (size >= 2 * READBACK_STRIPE_MIN) { - n = (uint32_t)(size / READBACK_STRIPE_MIN); - if (n > READBACK_STRIPES) n = READBACK_STRIPES; + if (!total) return 0; + if (total * AVA1_GROUP_LEN >= 2 * READBACK_STRIPE_MIN) { + n = (uint32_t)(total * AVA1_GROUP_LEN / READBACK_STRIPE_MIN < READBACK_STRIPES ? total * AVA1_GROUP_LEN / READBACK_STRIPE_MIN + : READBACK_STRIPES); } - per = (groups + n - 1) / n; + /* A buffer per stripe, shared with the live read-backs and other commits: as many as are free, one at + * least (waited for: whoever holds them is reading, and gives them back within one read). */ + pthread_mutex_lock(&j->mu); + while (j->rb_bufs >= READBACK_STRIPES && !j->stopping) pthread_cond_wait(&j->cv, &j->mu); + if (j->stopping) { + pthread_mutex_unlock(&j->mu); + return -EINTR; + } + if (n > READBACK_STRIPES - j->rb_bufs) n = READBACK_STRIPES - j->rb_bufs; + j->rb_bufs += n; + pthread_mutex_unlock(&j->mu); + per = (total + n - 1) / n; for (k = 0; k < n; k++) { - uint64_t g0 = per * k, g1 = per * (k + 1) < groups ? per * (k + 1) : groups; s[k].j = j; - s[k].from = g0 * AVA1_GROUP_LEN; - s[k].to = g1 * AVA1_GROUP_LEN < size ? g1 * AVA1_GROUP_LEN : size; + s[k].id = id; + s[k].sp = sp; + s[k].nsp = nsp; + s[k].from = per * k; + s[k].to = per * (k + 1) < total ? per * (k + 1) : total; + s[k].size = size; s[k].fd = fd; + s[k].rfd = rfd; s[k].ob_fd = ob_fd; s[k].quit = &quit; s[k].bad = 0; @@ -3022,6 +3357,10 @@ static int readback_large(ava1_job_t *j, uint32_t id, int fd, int ob_fd, uint64_ if (started[k]) pthread_join(th[k], NULL); else s[k].rc = readback_stripe(&s[k]); /* no thread: this worker reads that stripe too */ } + pthread_mutex_lock(&j->mu); + j->rb_bufs -= n; + pthread_cond_broadcast(&j->cv); + pthread_mutex_unlock(&j->mu); /* A real answer wins over the -EINTR of the stripes it stopped; of mismatches, the lowest group. */ for (k = 0; k < n; k++) { if (s[k].rc < 0 && s[k].rc != -EINTR && rc == 0) rc = s[k].rc; @@ -3036,6 +3375,37 @@ static int readback_large(ava1_job_t *j, uint32_t id, int fd, int ob_fd, uint64_ return rc; } +/* Caller holds j->mu. The groups of file `id` not read back while it arrived, as spans (malloc'd; NULL + * with *nsp = UINT32_MAX when out of memory); *total = how many groups they hold, *bytes = their bytes. */ +static rb_span_t *rb_left(const ava1_job_t *j, uint32_t id, uint32_t *nsp, uint64_t *total, uint64_t *bytes) { + const ava1_lfile_t *lf = j->lf[id]; + uint64_t size = j->m.e[id].size, groups = groups_of(size), g = 0; + rb_span_t *sp = malloc((lf->rb_done.n + 1) * sizeof *sp); + size_t r; + *nsp = 0; + *total = *bytes = 0; + if (!sp) { + *nsp = UINT32_MAX; + return NULL; + } + for (r = 0; r <= lf->rb_done.n; r++) { + /* rb_done holds whole groups (its last one may end at the file's end): [d0, d1) in groups */ + uint64_t d0 = r < lf->rb_done.n ? lf->rb_done.v[2 * r] / AVA1_GROUP_LEN : groups; + uint64_t d1 = r < lf->rb_done.n ? (lf->rb_done.v[2 * r + 1] >= size ? groups : lf->rb_done.v[2 * r + 1] / AVA1_GROUP_LEN) + : groups; + if (d0 > groups) d0 = groups; + if (d0 > g) { + sp[*nsp].g0 = g; + sp[*nsp].g1 = d0; + *total += d0 - g; + *bytes += (d0 * AVA1_GROUP_LEN < size ? d0 * AVA1_GROUP_LEN : size) - g * AVA1_GROUP_LEN; + (*nsp)++; + } + if (d1 > g) g = d1; + } + return sp; +} + /* A commit runs on a worker, and workers never end the job themselves (see worker_fail): the * failure is recorded and the job thread ends it, journaling Done when `journal_done`. */ static void commit_fail(ava1_job_t *j, uint16_t status, const char *what, int err, int journal_done) { @@ -3054,7 +3424,7 @@ static void commit_large(ava1_job_t *j, uint32_t id) { const ava1_ment_t *e = &j->m.e[id]; char part[PATH_CAP], fin[PATH_CAP], parent[PATH_CAP], ob[600]; uint8_t root[32], want[32]; - int err = 0; + int err = 0, found; pthread_mutex_lock(&j->mu); if (j->finished || j->final_status) { /* the job already ended or a sibling failed: do nothing more */ lf->committing = 0; @@ -3091,13 +3461,36 @@ static void commit_large(ava1_job_t *j, uint32_t id) { commit_fail(j, AVA1_ERR_IO, "path too long", ENAMETOOLONG, 0); return; } - /* A file of one group was just hashed from the drive by read_root; a larger one is read back here. */ - if (__atomic_load_n(&j->readback, __ATOMIC_RELAXED) && groups_of(e->size) >= 2) { - uint64_t bad = 0, t0 = mono_us(); - int rb; + /* A file of one group was just hashed from the drive by read_root; a larger one is read back here: the + * groups the live read-back has not (or the mismatch it found, which is acted on even if a resume has + * since turned the read-back off: the drive is known to hold something else). */ + pthread_mutex_lock(&j->mu); + found = lf->rb_found; + pthread_mutex_unlock(&j->mu); + if ((__atomic_load_n(&j->readback, __ATOMIC_RELAXED) || found) && groups_of(e->size) >= 2) { + uint64_t bad = 0, t0, total = 0, bytes = 0; + uint32_t nsp = 0; + rb_span_t *sp = NULL; + int rb = 0; HOOK(j, AVA1_HOOK_READBACK, id); - rb = readback_large(j, id, lf->fd, lf->ob_fd, &bad); + t0 = mono_us(); + pthread_mutex_lock(&j->mu); + /* Its live read-backs in flight end first (no new one starts: `committing` is set). */ + while (lf->rb_busy && !j->stopping) pthread_cond_wait(&j->cv, &j->mu); + found = lf->rb_found; + bad = lf->rb_found_g; + if (j->stopping) rb = -EINTR; + else if (!found && !(sp = rb_left(j, id, &nsp, &total, &bytes)) && nsp == UINT32_MAX) rb = -ENOMEM; + pthread_mutex_unlock(&j->mu); + if (found) rb = 1; + else if (!rb && total) { + int rfd = rb_open_direct(j, id); /* one for every stripe: pread shares it */ + rb = readback_large(j, id, lf->fd, rfd >= 0 ? rfd : lf->fd, lf->ob_fd, sp, nsp, total, &bad); + if (rfd >= 0) close(rfd); + } + free(sp); __atomic_add_fetch(&j->rb_us, mono_us() - t0, __ATOMIC_RELAXED); + if (!found && (rb == 0 || rb == 1)) __atomic_add_fetch(&j->rb_after_bytes, bytes, __ATOMIC_RELAXED); if (rb == -EINTR) { /* the job is ending: a resume commits (and reads back) the file again */ pthread_mutex_lock(&j->mu); lf->committing = 0; @@ -3143,6 +3536,8 @@ static void commit_large(ava1_job_t *j, uint32_t id) { pthread_mutex_lock(&j->mu); lf->committed = 1; ava1_rset_clear(&lf->written); + ava1_rset_clear(&lf->rb_todo); + ava1_rset_clear(&lf->rb_done); pthread_mutex_unlock(&j->mu); /* Truncate (preallocate may have reserved more) before the mtime: on Linux ftruncate * itself sets the mtime. The fsync makes all three durable. */ @@ -3360,7 +3755,7 @@ int ava1_apply_quiesce(ava1_job_t *j) { uint32_t i; int pend, ok, rc = 0; pthread_mutex_lock(&j->mu); - while ((j->q_len || j->busy) && !j->stopping) { + while ((j->q_len || j->busy || j->rb_live_run) && !j->stopping) { /* live reads too: the ids may move */ /* A worker may be waiting in pend_add for room: make it, or nobody ever will. */ int sync = j->pend_n != 0, can = j->prepared && !j->finished && !j->final_status; if (sync && !can) { @@ -3577,6 +3972,7 @@ static void *job_main(void *arg) { sync_batch(j); j->last_batch_ms = now; if (!j->stopping) ava1_apply_commit_ready(j); + if (!j->stopping) rb_live_kick(j); /* after the commits: a file about to commit is read back there */ } if (j->timing && j->st_batches && now - j->st_log_ms >= 10000) log_stats(j, now); if (all_done(j)) finish(j); diff --git a/c/ava1_apply.h b/c/ava1_apply.h index 5114c3e..a519bad 100644 --- a/c/ava1_apply.h +++ b/c/ava1_apply.h @@ -102,15 +102,22 @@ void ava1_apply_finish_landed(ava1_job_t *j); #define AVA1_HOOK_SWEPT 11 /* a JnlSweep was appended (the files are durable in place) */ #define AVA1_HOOK_BATCH_ALLOC 13 /* a sync batch is about to allocate its work lists: a nonzero ava1_apply_fault is "out of memory" (tests) */ #define AVA1_HOOK_PREALLOC 9 /* a part file is about to be preallocated (job mutex NOT held) */ -#define AVA1_HOOK_READBACK 14 /* JF_READBACK: a large file is about to be read back before its commit */ +#define AVA1_HOOK_READBACK 14 /* JF_READBACK: a large file is about to be read back before its commit + * (what was not already read back while it arrived) */ /* Read-backs that find a file wrong before the job fails (each one first resends the file). */ #define AVA1_READBACK_TRIES 3u /* Tests: every pwrite of file data writes at most this many bytes (0, the default: no cap). */ extern size_t ava1_test_pwrite_max; +/* Tests: every chunk's write first waits this many ms (0, the default: none). */ +extern uint32_t ava1_test_chunk_delay_ms; extern void (*ava1_apply_hook)(ava1_job_t *j, int point, uint32_t id); /* Tests only (NULL in the payload): an errno to inject at a point instead of doing the work. * Consulted at AVA1_HOOK_DIR_SYNCED of the staged tree's rename. */ extern int (*ava1_apply_fault)(ava1_job_t *j, int point, uint32_t id); +/* Tests only (NULL in the payload): JF_READBACK is about to read bytes [off, off + len) of file `id` back + * through `fd` (its own descriptor, opened for writing too), `live` while the file still arrives, else in + * the commit's pass. Called with no lock held, from any worker or read-back thread. */ +extern void (*ava1_apply_rb_hook)(ava1_job_t *j, uint32_t id, uint64_t off, uint64_t len, int fd, int live); /* Tests only (0 in the payload): while nonzero, the job thread starts no sync batch. */ extern int ava1_apply_hold_batches; diff --git a/c/ava1_job.c b/c/ava1_job.c index 6eb9a08..d89b14b 100644 --- a/c/ava1_job.c +++ b/c/ava1_job.c @@ -122,6 +122,7 @@ static ava1_job_t *create(const uint8_t id[16], const uint8_t owner[32], const u pthread_mutex_init(&j->jnl_mu, NULL); pthread_mutex_init(&j->pack_mu, NULL); pthread_cond_init(&j->cv, NULL); + pthread_cond_init(&j->rb_cv, NULL); pthread_mutex_init(&j->cmu, NULL); pthread_cond_init(&j->ccv, NULL); pthread_mutex_lock(&T.mu); @@ -158,6 +159,7 @@ static ava1_job_t *create(const uint8_t id[16], const uint8_t owner[32], const u pthread_mutex_destroy(&j->jnl_mu); pthread_mutex_destroy(&j->pack_mu); pthread_cond_destroy(&j->cv); + pthread_cond_destroy(&j->rb_cv); pthread_mutex_destroy(&j->cmu); pthread_cond_destroy(&j->ccv); free(j); @@ -237,6 +239,7 @@ static void job_destroy(ava1_job_t *j) { pthread_mutex_lock(&j->mu); j->stopping = 1; pthread_cond_broadcast(&j->cv); + pthread_cond_broadcast(&j->rb_cv); pthread_mutex_unlock(&j->mu); if (j->feeder_started) { /* first: it may be handing work to the threads below */ pthread_mutex_lock(&j->cmu); @@ -247,6 +250,7 @@ static void job_destroy(ava1_job_t *j) { } if (j->thread_started) pthread_join(j->thread, NULL); for (i = 0; i < j->nworkers; i++) pthread_join(j->workers[i], NULL); + for (i = 0; i < j->rb_th_n; i++) pthread_join(j->rb_th[i], NULL); /* the job thread started them: joined above */ /* The role's reader is the only thread left that can enqueue work (a copy's reader * applies what it reads): join it before the queue below is drained, or an * enqueue concurrent with the drain would append to a freed item. */ @@ -295,6 +299,8 @@ static void job_destroy(ava1_job_t *j) { if (j->lf[i]->held) ava1_lf_release(j->lf[i]->held); /* its slots in the large-file budget */ ava1_rset_clear(&j->lf[i]->written); ava1_rset_clear(&j->lf[i]->durable); + ava1_rset_clear(&j->lf[i]->rb_todo); + ava1_rset_clear(&j->lf[i]->rb_done); free(j->lf[i]); } free(j->lf); @@ -312,6 +318,7 @@ static void job_destroy(ava1_job_t *j) { pthread_mutex_destroy(&j->jnl_mu); pthread_mutex_destroy(&j->pack_mu); pthread_cond_destroy(&j->cv); + pthread_cond_destroy(&j->rb_cv); pthread_mutex_destroy(&j->cmu); pthread_cond_destroy(&j->ccv); free(j); diff --git a/c/ava1_job.h b/c/ava1_job.h index e14c39f..b39fbc5 100644 --- a/c/ava1_job.h +++ b/c/ava1_job.h @@ -17,6 +17,10 @@ /* JnlOpen.staged: bit 0 = staged under .ava-part; bit 1 = the receiver created the * empty as its lock (SPEC.md §11.6), so an empty on resume is its own. */ #define AVA1_STAGED_HELD 2 +/* JF_READBACK: threads per job that read large files back while they arrive (SPEC.md §13.5). An 8 MiB + * read from a PS5's drive (not its cache) runs at ~26-30 MiB/s per thread (8 threads: ~211 MiB/s), so six + * give ~150 MiB/s, twice a 65 MiB/s upload, with the drive also taking the writes. */ +#define AVA1_READBACK_THREADS 6 typedef struct ava1_job ava1_job_t; /* Where a job's outgoing messages go: a session (network jobs) or a recorder (local, tests). @@ -52,6 +56,16 @@ typedef struct { /* one large file being assembled */ int writers; /* write_chunk calls that took their own dups and have not yet recorded the range */ uint8_t held; /* descriptors counted against the large-file budget (0, 1 or 2) */ uint8_t rb_bad; /* read-backs (JF_READBACK) that found the drive's bytes wrong; the file fails at AVA1_READBACK_TRIES */ + /* JF_READBACK while the file arrives (SPEC.md §13.5; ava1_apply.c, "read-back"), under j->mu. + * rb_todo: durable bytes nobody has read back yet (a sync batch adds what it made durable, a write + * takes its range out again). rb_done: read back and right since they were last made durable. + * rb_gen: bumped by a reset and by a write over durable bytes, so a read-back in flight across + * either counts for nothing. rb_busy: read-backs of this file in flight. rb_found: one found the + * drive's bytes wrong at group rb_found_g; the commit acts on it (unless that group is written again). */ + ava1_rset_t rb_todo, rb_done; + uint32_t rb_gen; + uint8_t rb_busy, rb_found; + uint64_t rb_found_g; } ava1_lfile_t; /* Durable-by-log (SPEC.md §15.7). A small file's bytes go to `pack.` in the job directory and @@ -208,6 +222,20 @@ struct ava1_job { int readback; uint64_t rb_files, rb_bytes, rb_us, rb_mismatches; uint64_t rb_read_us, rb_hash_us; /* summed over read-back threads: where the time went */ + uint64_t rb_live_bytes, rb_after_bytes; /* read back while files arrived / after their last byte (rb_us is the latter's wall time) */ + /* The live read-back's own threads (ava1_apply.c, "read-back"): started by the job thread at the first + * durable range of a large file, joined by job_destroy. They wait on rb_cv, which each batch signals. */ + pthread_t rb_th[AVA1_READBACK_THREADS]; + uint32_t rb_th_n; + pthread_cond_t rb_cv; + uint32_t rb_live_run; /* live reads in flight (under mu): ava1_apply_quiesce waits for none */ + uint64_t rb_todo_ranges, rb_live_reads, rb_live_crowded; /* atomics, for the end-of-job line: ranges batches handed + * over, live reads done, of those with chunks waiting */ + /* Reading from the drive, not the page cache (atomics): reads whose pages were dropped from the cache + * first (asked / done), reads made with O_DIRECT; the one line per job that says how. */ + uint64_t rb_drops, rb_drops_ok, rb_direct_reads; + int rb_how_logged, rb_direct_err; /* ... and why O_DIRECT was refused, the last time it was */ + uint32_t rb_bufs; /* read-back buffers in use, live and at commit (under mu; at most READBACK_STRIPES) */ int resumed; /* decided at open (journal replay) or at an attach that finds durable work; never per re-arm */ uint64_t prog_gen; /* the attach generation `resumed` was last decided under */ uint32_t tune_ticks, tune_busy; /* queue occupancy since the last tuning step */ diff --git a/c/ava1_platform.h b/c/ava1_platform.h index 3cd8b5d..aebb0cc 100644 --- a/c/ava1_platform.h +++ b/c/ava1_platform.h @@ -12,5 +12,13 @@ void ava1_platform_sleep_ms(unsigned ms); int ava1_platform_preallocate(int fd, uint64_t len); /* Set a file's mtime (seconds). The PS5 uses utimensat on the path (verified in backup.c). */ void ava1_platform_set_mtime(int fd, const char *path, uint64_t mtime); +/* Best effort: drops the cached pages of bytes [off, off + len) of the file open at `fd` (written and + * synced, so clean), so that the next read of them comes from the drive (JF_READBACK, SPEC.md §13.5). + * `off` is page-aligned. 0 when the OS was told to, else an errno (ENOTSUP: this OS has no way; ENOSYS: + * its kernel lacks the call). *how names the method, set either way, for a log line. */ +int ava1_platform_drop_cache(int fd, uint64_t off, uint64_t len, const char **how); +/* Opens `path` read-only for direct I/O (O_DIRECT: past the page cache; reads in whole, aligned blocks). + * A descriptor, or -1 with errno (ENOTSUP: no direct I/O on this OS; EINVAL: not on this filesystem). */ +int ava1_platform_open_direct(const char *path); #endif diff --git a/c/ava1_ranges.c b/c/ava1_ranges.c index 76707c3..08e6ecd 100644 --- a/c/ava1_ranges.c +++ b/c/ava1_ranges.c @@ -49,6 +49,43 @@ int ava1_rset_covers(const ava1_rset_t *r, uint64_t start, uint64_t end) { return 0; } +int ava1_rset_overlaps(const ava1_rset_t *r, uint64_t start, uint64_t end) { + size_t i; + for (i = 0; start < end && i < r->n; i++) + if (r->v[2 * i] < end && start < r->v[2 * i + 1]) return 1; + return 0; +} + +int ava1_rset_remove(ava1_rset_t *r, uint64_t start, uint64_t end) { + size_t i = 0, j; + if (start >= end) return 0; + while (i < r->n && r->v[2 * i + 1] <= start) i++; /* the first pair that ends past start */ + if (i == r->n || r->v[2 * i] >= end) return 0; /* none overlaps */ + if (r->v[2 * i] < start && end < r->v[2 * i + 1]) { /* inside one pair: it becomes two */ + if (r->n == r->cap) { + size_t cap = r->cap ? r->cap * 2 : 4; + uint64_t *v = realloc(r->v, cap * 2 * sizeof *v); + if (!v) return -1; + r->v = v; + r->cap = cap; + } + memmove(&r->v[2 * (i + 1)], &r->v[2 * i], (r->n - i) * 2 * sizeof *r->v); + r->n++; + r->v[2 * i + 1] = start; + r->v[2 * (i + 1)] = end; + return 1; + } + if (r->v[2 * i] < start) r->v[2 * i++ + 1] = start; /* keep the head of the first pair */ + j = i; + while (j < r->n && r->v[2 * j + 1] <= end) j++; /* pairs i..j-1 lie inside: they go */ + if (j < r->n && r->v[2 * j] < end) r->v[2 * j] = end; /* keep the tail of the last pair */ + if (j > i) { + memmove(&r->v[2 * i], &r->v[2 * j], (r->n - j) * 2 * sizeof *r->v); + r->n -= j - i; + } + return 1; +} + void ava1_rset_clear(ava1_rset_t *r) { free(r->v); memset(r, 0, sizeof *r); diff --git a/c/ava1_ranges.h b/c/ava1_ranges.h index b6ca215..8c04af0 100644 --- a/c/ava1_ranges.h +++ b/c/ava1_ranges.h @@ -19,6 +19,11 @@ typedef struct { int ava1_rset_add(ava1_rset_t *r, uint64_t start, uint64_t end); /* 0, or -1 out of memory */ uint64_t ava1_rset_covered(const ava1_rset_t *r); int ava1_rset_covers(const ava1_rset_t *r, uint64_t start, uint64_t end); +/* 1 when some byte of [start, end) is in the set (never for an empty range). */ +int ava1_rset_overlaps(const ava1_rset_t *r, uint64_t start, uint64_t end); +/* Takes [start, end) out of the set: 1 when that removed something, 0 when nothing was there, -1 out of + * memory (cutting one range in two needs a pair more; the set is then unchanged). */ +int ava1_rset_remove(ava1_rset_t *r, uint64_t start, uint64_t end); void ava1_rset_clear(ava1_rset_t *r); /* frees */ /* A bitset of file ids; ava1_bits_init sets every field, ava1_bits_free releases. */ diff --git a/c/ava1_recv.c b/c/ava1_recv.c index 88f829d..2c86c58 100644 --- a/c/ava1_recv.c +++ b/c/ava1_recv.c @@ -143,6 +143,8 @@ static void forget_file(ava1_job_t *j, uint32_t i) { ava1_bits_clear(&j->done, i); if (j->lf[i]) { ava1_rset_clear(&j->lf[i]->durable); + ava1_rset_clear(&j->lf[i]->rb_todo); + ava1_rset_clear(&j->lf[i]->rb_done); j->lf[i]->has_root = j->lf[i]->root_journaled = 0; } } @@ -278,6 +280,8 @@ static void free_lf(ava1_job_t *j, uint32_t id, ava1_lfile_t *lf) { ava1_lf_close_fds(j, id, lf); /* the descriptors and their slots in the large-file budget */ ava1_rset_clear(&lf->written); ava1_rset_clear(&lf->durable); + ava1_rset_clear(&lf->rb_todo); + ava1_rset_clear(&lf->rb_done); free(lf); } diff --git a/c/platform_posix.c b/c/platform_posix.c index 500517d..00818a7 100644 --- a/c/platform_posix.c +++ b/c/platform_posix.c @@ -1,7 +1,11 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE /* glibc declares O_DIRECT only with it */ +#endif #include "ava1_platform.h" #include #include +#include #include #include #include @@ -37,3 +41,45 @@ void ava1_platform_set_mtime(int fd, const char *path, uint64_t mtime) { ts[1] = ts[0]; (void)futimens(fd, ts); } + +#if defined(__FreeBSD__) +/* FreeBSD's POSIX_FADV_DONTNEED releases the clean buffers but only deactivates their pages, which stay + * valid: a read right after is still answered from memory. msync(MS_INVALIDATE) then takes the clean, + * now unwired pages out of the file's object. */ +static int invalidate_mapped(int fd, uint64_t off, uint64_t len) { + void *p = mmap(NULL, (size_t)len, PROT_READ, MAP_SHARED, fd, (off_t)off); + int rc; + if (p == MAP_FAILED) return errno; + rc = msync(p, (size_t)len, MS_INVALIDATE) == 0 ? 0 : errno; + (void)munmap(p, (size_t)len); + return rc; +} +#endif + +int ava1_platform_drop_cache(int fd, uint64_t off, uint64_t len, const char **how) { +#if defined(__linux__) + *how = "posix_fadvise(DONTNEED)"; + return posix_fadvise(fd, (off_t)off, (off_t)len, POSIX_FADV_DONTNEED); +#elif defined(__FreeBSD__) + int rc; + *how = "posix_fadvise(DONTNEED) + msync(MS_INVALIDATE)"; + if ((rc = posix_fadvise(fd, (off_t)off, (off_t)len, POSIX_FADV_DONTNEED)) != 0) return rc; + return invalidate_mapped(fd, off, len); +#else + (void)fd; + (void)off; + (void)len; + *how = "no call to drop cached pages on this OS"; + return ENOTSUP; +#endif +} + +int ava1_platform_open_direct(const char *path) { +#ifdef O_DIRECT + return open(path, O_RDONLY | O_DIRECT | O_NOFOLLOW); +#else + (void)path; + errno = ENOTSUP; + return -1; +#endif +} diff --git a/c/platform_ps5.c b/c/platform_ps5.c index d174a0d..0c5a6df 100644 --- a/c/platform_ps5.c +++ b/c/platform_ps5.c @@ -5,6 +5,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include @@ -12,6 +16,10 @@ /* Hidden behind __POSIX_VISIBLE in the SDK headers, as in runtime.c. */ extern int posix_fallocate(int fd, off_t offset, off_t len); +extern int posix_fadvise(int fd, off_t offset, off_t len, int advice); +#ifndef POSIX_FADV_DONTNEED +#define POSIX_FADV_DONTNEED 4 +#endif #ifndef KERN_ARND #define KERN_ARND 37 @@ -44,3 +52,59 @@ void ava1_platform_set_mtime(int fd, const char *path, uint64_t mtime) { ts[1] = ts[0]; (void)utimensat(AT_FDCWD, path, ts, 0); } + +/* Dropping cached pages (JF_READBACK reads from the drive). FreeBSD 11's POSIX_FADV_DONTNEED releases the + * clean buffers but only deactivates their pages, which stay valid; msync(MS_INVALIDATE) then removes the + * clean, unwired pages from the file's object. Neither call has been seen on this kernel before, and + * FreeBSD kills a process that makes a system call the kernel lacks (SIGSYS): the first try runs with + * SIGSYS ignored, so a missing call answers ENOSYS instead, and a missing one is never made again. */ +static pthread_mutex_t g_drop_mu = PTHREAD_MUTEX_INITIALIZER; +static int g_drop_tried; /* the first try is done (under g_drop_mu, then read atomically) */ +static int g_no_fadvise, g_no_msync; + +static int drop_fadvise(int fd, uint64_t off, uint64_t len) { + int rc = posix_fadvise(fd, (off_t)off, (off_t)len, POSIX_FADV_DONTNEED); + return rc == -1 ? errno : rc; /* the error itself, or -1 and errno (a missing call) */ +} + +static int drop_msync(int fd, uint64_t off, uint64_t len) { + void *p = mmap(NULL, (size_t)len, PROT_READ, MAP_SHARED, fd, (off_t)off); + int rc; + if (p == MAP_FAILED) return errno; + rc = msync(p, (size_t)len, MS_INVALIDATE) == 0 ? 0 : errno; + (void)munmap(p, (size_t)len); + return rc; +} + +static int drop_both(int fd, uint64_t off, uint64_t len) { + int a = __atomic_load_n(&g_no_fadvise, __ATOMIC_RELAXED) ? ENOSYS : drop_fadvise(fd, off, len); + int b = __atomic_load_n(&g_no_msync, __ATOMIC_RELAXED) ? ENOSYS : drop_msync(fd, off, len); + if (a == ENOSYS) __atomic_store_n(&g_no_fadvise, 1, __ATOMIC_RELAXED); + if (b == ENOSYS) __atomic_store_n(&g_no_msync, 1, __ATOMIC_RELAXED); + return b ? b : a; /* msync is what evicts: its answer counts first */ +} + +int ava1_platform_drop_cache(int fd, uint64_t off, uint64_t len, const char **how) { + int rc; + *how = "posix_fadvise(DONTNEED) + msync(MS_INVALIDATE)"; + if (!__atomic_load_n(&g_drop_tried, __ATOMIC_ACQUIRE)) { + pthread_mutex_lock(&g_drop_mu); + if (!g_drop_tried) { + struct sigaction ign, old; + memset(&ign, 0, sizeof ign); + ign.sa_handler = SIG_IGN; + sigemptyset(&ign.sa_mask); + (void)sigaction(SIGSYS, &ign, &old); + rc = drop_both(fd, off, len); + (void)sigaction(SIGSYS, &old, NULL); + __atomic_store_n(&g_drop_tried, 1, __ATOMIC_RELEASE); + pthread_mutex_unlock(&g_drop_mu); + return rc; + } + pthread_mutex_unlock(&g_drop_mu); + } + if (__atomic_load_n(&g_no_fadvise, __ATOMIC_RELAXED) && __atomic_load_n(&g_no_msync, __ATOMIC_RELAXED)) return ENOSYS; + return drop_both(fd, off, len); +} + +int ava1_platform_open_direct(const char *path) { return open(path, O_RDONLY | O_DIRECT | O_NOFOLLOW); } diff --git a/crates/ava1-ctest/csrc/test_shim.c b/crates/ava1-ctest/csrc/test_shim.c index 75009aa..dd8f13b 100644 --- a/crates/ava1-ctest/csrc/test_shim.c +++ b/crates/ava1-ctest/csrc/test_shim.c @@ -584,6 +584,31 @@ size_t ava1_test_rset_after(const uint64_t *ops, size_t nops, uint64_t *out, siz return n; } +/* The same with removals: ops are triples (kind, start, end), kind 0 = add, 1 = remove (ava1_rset_overlaps + * is checked against the set before each removal: a mismatch with what the removal reports returns + * SIZE_MAX). */ +size_t ava1_test_rset_ops(const uint64_t *ops, size_t nops, uint64_t *out, size_t cap_pairs) { + ava1_rset_t r; + size_t i, n; + memset(&r, 0, sizeof r); + for (i = 0; i < nops; i++) { + const uint64_t *o = ops + 3 * i; + if (o[0] == 0) { + (void)ava1_rset_add(&r, o[1], o[2]); + } else { + int had = ava1_rset_overlaps(&r, o[1], o[2]), rc = ava1_rset_remove(&r, o[1], o[2]); + if (rc < 0 || rc != had) { + ava1_rset_clear(&r); + return SIZE_MAX; + } + } + } + n = r.n < cap_pairs ? r.n : cap_pairs; + if (n) memcpy(out, r.v, n * 2 * sizeof *out); + ava1_rset_clear(&r); + return n; +} + /* FileRun pairs (first, count) for the given set bits; returns pair count. */ size_t ava1_test_bits_runs(uint32_t n, const uint32_t *set, size_t nset, uint32_t *out, size_t cap_pairs) { ava1_bits_t b; @@ -1296,6 +1321,74 @@ void ava1_test_corrupt_at_commit(int n, uint64_t at) { __atomic_store_n(&g_corrupt_n, n, __ATOMIC_SEQ_CST); } int ava1_test_corrupt_left(void) { return __atomic_load_n(&g_corrupt_n, __ATOMIC_SEQ_CST); } + +/* JF_READBACK seen from its reads (ava1_apply_rb_hook): every stretch the read-back is about to read, live + * (while its file still arrives) or in the commit's pass. */ +static int g_rbc_n; /* reads that find the byte at g_rbc_at changed on the drive first */ +static uint64_t g_rbc_at; +static int g_rb_hold; /* live reads wait here while set (and the job is not stopping) */ +static uint32_t g_rb_held; /* live reads waiting there now */ +static uint64_t g_rb_reads[2]; /* reads seen: [0] the commit's, [1] live */ +static void t_rb_hook(ava1_job_t *j, uint32_t id, uint64_t off, uint64_t len, int fd, int live) { + uint64_t at = __atomic_load_n(&g_rbc_at, __ATOMIC_SEQ_CST); + (void)id; + __atomic_add_fetch(&g_rb_reads[live ? 1 : 0], 1, __ATOMIC_SEQ_CST); + if (live && __atomic_load_n(&g_rb_hold, __ATOMIC_SEQ_CST)) { + __atomic_add_fetch(&g_rb_held, 1, __ATOMIC_SEQ_CST); + while (__atomic_load_n(&g_rb_hold, __ATOMIC_SEQ_CST) && !__atomic_load_n(&j->stopping, __ATOMIC_SEQ_CST)) + ava1_platform_sleep_ms(2); + __atomic_sub_fetch(&g_rb_held, 1, __ATOMIC_SEQ_CST); + } + /* The drive's copy goes wrong after the byte was received and made durable, before it is read back. */ + if (at >= off && at < off + len && __atomic_load_n(&g_rbc_n, __ATOMIC_SEQ_CST) > 0) { + uint8_t b; + if (pread(fd, &b, 1, (off_t)at) == 1) { + b ^= 0x5a; + if (pwrite(fd, &b, 1, (off_t)at) == 1) __atomic_sub_fetch(&g_rbc_n, 1, __ATOMIC_SEQ_CST); + } + } +} +/* The next `n` read-backs of the byte at `at` find it changed on the drive (it is flipped right before + * the read, live or at the commit, whichever reads it). */ +void ava1_test_rb_corrupt(int n, uint64_t at) { + __atomic_store_n(&g_rbc_at, at, __ATOMIC_SEQ_CST); + __atomic_store_n(&g_rbc_n, n, __ATOMIC_SEQ_CST); +} +int ava1_test_rb_corrupt_left(void) { return __atomic_load_n(&g_rbc_n, __ATOMIC_SEQ_CST); } +void ava1_test_rb_hold(int on) { __atomic_store_n(&g_rb_hold, on, __ATOMIC_SEQ_CST); } +/* out: [0] bytes read back live, [1] after the last byte (the commits'), [2] files read back, [3] mismatches, + * [4] live reads seen, [5] commit reads seen, [6] live reads held now, [7] live reads done, [8] of those while + * chunks waited for a worker, [9] ranges batches handed to the live read-back, [10] its threads, [11] reads + * that first asked the OS to drop their pages from the cache, [12] of those it did, [13] reads with O_DIRECT. */ +void ava1_test_rb_stats(uint64_t out[14]) { + memset(out, 0, 14 * sizeof out[0]); + out[4] = __atomic_load_n(&g_rb_reads[1], __ATOMIC_SEQ_CST); + out[5] = __atomic_load_n(&g_rb_reads[0], __ATOMIC_SEQ_CST); + out[6] = __atomic_load_n(&g_rb_held, __ATOMIC_SEQ_CST); + if (!g_job) return; + out[0] = __atomic_load_n(&g_job->rb_live_bytes, __ATOMIC_SEQ_CST); + out[1] = __atomic_load_n(&g_job->rb_after_bytes, __ATOMIC_SEQ_CST); + out[2] = __atomic_load_n(&g_job->rb_files, __ATOMIC_SEQ_CST); + out[3] = __atomic_load_n(&g_job->rb_mismatches, __ATOMIC_SEQ_CST); + out[7] = __atomic_load_n(&g_job->rb_live_reads, __ATOMIC_SEQ_CST); + out[8] = __atomic_load_n(&g_job->rb_live_crowded, __ATOMIC_SEQ_CST); + out[9] = __atomic_load_n(&g_job->rb_todo_ranges, __ATOMIC_SEQ_CST); + out[11] = __atomic_load_n(&g_job->rb_drops, __ATOMIC_SEQ_CST); + out[12] = __atomic_load_n(&g_job->rb_drops_ok, __ATOMIC_SEQ_CST); + out[13] = __atomic_load_n(&g_job->rb_direct_reads, __ATOMIC_SEQ_CST); + pthread_mutex_lock(&g_job->mu); + out[10] = g_job->rb_th_n; + pthread_mutex_unlock(&g_job->mu); +} +/* Every chunk's write first waits `ms` (0: none): the workers stay busy, chunks queue behind them. */ +void ava1_test_chunk_delay(uint32_t ms) { __atomic_store_n(&ava1_test_chunk_delay_ms, ms, __ATOMIC_SEQ_CST); } +static void rb_knobs_reset(void) { + __atomic_store_n(&ava1_test_chunk_delay_ms, 0, __ATOMIC_SEQ_CST); + __atomic_store_n(&g_rbc_n, 0, __ATOMIC_SEQ_CST); + __atomic_store_n(&g_rb_hold, 0, __ATOMIC_SEQ_CST); + __atomic_store_n(&g_rb_reads[0], 0, __ATOMIC_SEQ_CST); + __atomic_store_n(&g_rb_reads[1], 0, __ATOMIC_SEQ_CST); +} /* Every pwrite of file data writes at most `n` bytes (0: no cap): short writes, as a drive may return them. */ void ava1_test_set_pwrite_max(size_t n) { __atomic_store_n(&ava1_test_pwrite_max, n, __ATOMIC_SEQ_CST); } void ava1_test_apply_fault_prealloc(uint32_t id) { __atomic_store_n(&g_prealloc_fault, id, __ATOMIC_SEQ_CST); } @@ -1494,6 +1587,8 @@ int ava1_test_apply_begin(const char *jobs_dir, const char *root, uint32_t flags g_trace = 0; ava1_apply_hook = t_hook; ava1_apply_fault = t_fault; + ava1_apply_rb_hook = t_rb_hook; + rb_knobs_reset(); pthread_mutex_lock(&g_ev_mu); g_ev_len = 0; g_ev_done = 0; @@ -1663,6 +1758,8 @@ void ava1_test_apply_end(void) { ava1_data_stop(); ava1_apply_hook = NULL; ava1_apply_fault = NULL; + ava1_apply_rb_hook = NULL; + rb_knobs_reset(); ava1_test_apply_fail_dir_sync(UINT32_MAX - 1); ava1_test_apply_hold(0); __atomic_store_n(&ava1_fsync_test_fail_n, 0, __ATOMIC_SEQ_CST); @@ -1719,6 +1816,7 @@ static int recv_start(int crash_at) { if (ava1_data_start(&g_cfg) != 0) return -100; ava1_apply_hook = t_hook; ava1_apply_fault = t_fault; + ava1_apply_rb_hook = t_rb_hook; /* its knobs stay across a restart: a test aims them at the next run */ /* The start's recovery pass runs on the recovery thread, and a JobOpen for a job it is recovering is BUSY * (a sender retries). The tests that open right after a start mean "after recovery": wait for the pass, so * their outcome does not depend on how fast it runs (the order-dependent flake of log_small_fail). */ diff --git a/crates/ava1-ctest/src/lib.rs b/crates/ava1-ctest/src/lib.rs index 2b9beec..13696ef 100644 --- a/crates/ava1-ctest/src/lib.rs +++ b/crates/ava1-ctest/src/lib.rs @@ -269,6 +269,8 @@ pub mod ffi { out: *mut u64, cap: usize, ) -> usize; + pub fn ava1_test_rset_ops(ops: *const u64, nops: usize, out: *mut u64, cap: usize) + -> usize; pub fn ava1_test_journal_dump(dir: *const c_char, out: *mut u8, cap: usize) -> usize; pub fn ava1_test_journal_write_sample(dir: *const c_char) -> c_int; pub fn ava1_test_journal_compact( @@ -1050,6 +1052,19 @@ pub fn c_rset_after(ops: &[(u64, u64)]) -> Vec<(u64, u64)> { out.chunks(2).take(n).map(|p| (p[0], p[1])).collect() } +/// A C range set after adds (`true`) and removals (`false`) in order; None when a removal's answer +/// disagreed with `ava1_rset_overlaps` (or it ran out of memory). +pub fn c_rset_ops(ops: &[(bool, u64, u64)]) -> Option> { + let flat: Vec = ops + .iter() + .flat_map(|(add, s, e)| [u64::from(!*add), *s, *e]) + .collect(); + let cap = 2 * ops.len() + 2; + let mut out = vec![0u64; 2 * cap]; + let n = unsafe { ffi::ava1_test_rset_ops(flat.as_ptr(), ops.len(), out.as_mut_ptr(), cap) }; + (n != usize::MAX).then(|| out.chunks(2).take(n).map(|p| (p[0], p[1])).collect()) +} + pub fn c_bits_runs(n: u32, set: &[u32]) -> Vec<(u32, u32)> { let mut out = vec![0u32; 2 * (n as usize + 1)]; let k = unsafe { diff --git a/crates/ava1-ctest/tests/ranges.rs b/crates/ava1-ctest/tests/ranges.rs index d90d248..1647373 100644 --- a/crates/ava1-ctest/tests/ranges.rs +++ b/crates/ava1-ctest/tests/ranges.rs @@ -73,6 +73,58 @@ fn c_range_sets_match_rust_at_the_boundaries() { } } +/// Removal (the read-back's to-do and done sets lose what a late write covers): against a plain bitmap, +/// with ranges that cut one pair in two, trim either end, swallow several pairs, or miss them all. +#[test] +fn c_range_set_removal_matches_a_bitmap() { + const N: u64 = 300; + let mut rng = SplitMix(14); + for _ in 0..500 { + let mut bits = [false; N as usize]; + let ops: Vec<(bool, u64, u64)> = (0..rng.below(30) + 1) + .map(|_| { + let s = rng.below(N); + let e = (s + rng.below(40)).min(N); + (rng.below(3) != 0, s, e) + }) + .collect(); + for &(add, s, e) in &ops { + for b in &mut bits[s as usize..e as usize] { + *b = add; + } + } + let mut want = Vec::new(); + let mut i = 0; + while i < N as usize { + if bits[i] { + let s = i; + while i < N as usize && bits[i] { + i += 1; + } + want.push((s as u64, i as u64)); + } else { + i += 1; + } + } + assert_eq!(c_rset_ops(&ops), Some(want), "{ops:?}"); + } + // the edges of the offset space + let m = u64::MAX; + assert_eq!( + c_rset_ops(&[(true, 0, m), (false, 1, m - 1)]), + Some(vec![(0, 1), (m - 1, m)]) + ); + assert_eq!(c_rset_ops(&[(true, 5, 9), (false, 0, m)]), Some(vec![])); + assert_eq!( + c_rset_ops(&[(true, 5, 9), (false, 9, 12), (false, 3, 5)]), + Some(vec![(5, 9)]) + ); + assert_eq!( + c_rset_ops(&[(false, 3, 3), (true, 1, 4), (false, 2, 2)]), + Some(vec![(1, 4)]) + ); +} + #[test] fn c_file_runs_match_rust() { let mut rng = SplitMix(12); diff --git a/crates/ava1-ctest/tests/readback.rs b/crates/ava1-ctest/tests/readback.rs index 5373b10..0f10960 100644 --- a/crates/ava1-ctest/tests/readback.rs +++ b/crates/ava1-ctest/tests/readback.rs @@ -1,8 +1,14 @@ #![cfg(unix)] -//! JF_READBACK (SPEC.md §13.5): the receiver reads each large file back from its drive before the -//! commit and checks it against the CVs of what it received. Without it, bytes that changed on the -//! drive after they were received (a misplaced or short write, a filesystem fault, another process) -//! commit unnoticed, because every other check hashes the bytes as they arrived. +//! JF_READBACK (SPEC.md §13.5): the receiver reads each large file back from its drive and checks it +//! against the CVs of what it received, before the commit. Without it, bytes that changed on the drive +//! after they were received (a misplaced or short write, a filesystem fault, another process) commit +//! unnoticed, because every other check hashes the bytes as they arrived. +//! +//! The read-back runs while a file arrives, on each stretch once a sync batch has made it durable, and +//! the commit reads only what is left. So a byte that changes on the drive before its group is read back +//! is found (`ava1_test_rb_corrupt` flips it right before that read, live or at the commit), and one that +//! changes after its group was read back is not (see +//! `a_byte_changed_after_its_group_was_read_back_is_not_found`). use ava1::gen::{self, ENTRY_FILE}; use ava1::manifest::{Entry, Manifest}; use ava1::verify::GROUP; @@ -14,6 +20,56 @@ extern "C" { fn ava1_test_set_pwrite_max(n: usize); fn ava1_test_recv_set_flags(flags: u32); fn ava1_test_job_readback() -> i32; + fn ava1_test_rb_corrupt(n: i32, at: u64); + fn ava1_test_rb_corrupt_left() -> i32; + fn ava1_test_rb_hold(on: i32); + fn ava1_test_rb_stats(out: *mut u64); + fn ava1_test_chunk_delay(ms: u32); + fn ava1_test_apply_summary(out: *mut u8, cap: usize) -> usize; +} + +const G: usize = GROUP as usize; + +/// [0] bytes read back while the file arrived, [1] after its last byte, [2] files read back, +/// [3] mismatches, [4] live reads seen by the hook, [5] commit reads seen, [6] live reads held now, +/// [7] live reads done, [8] of those while chunks waited for a worker, [9] ranges batches handed to the +/// live read-back, [10] its threads, [11] reads that first asked the OS to drop their pages from the +/// cache, [12] of those it did, [13] reads with O_DIRECT. +fn rb_stats() -> [u64; 14] { + let mut o = [0u64; 14]; + unsafe { ava1_test_rb_stats(o.as_mut_ptr()) }; + o +} + +fn wait_until(what: &str, ms: u64, f: impl Fn() -> bool) { + let t0 = std::time::Instant::now(); + while !f() { + assert!( + t0.elapsed().as_millis() < ms as u128, + "waiting for {what}: {:?}", + rb_stats() + ); + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + +/// The bytes of groups `gs` of `d`. +fn bytes_of(d: &[u8], gs: &[usize]) -> u64 { + gs.iter() + .map(|g| ((g + 1) * G).min(d.len()) - g * G) + .sum::() as u64 +} + +fn send_groups(job: &CApplyJob, id: u32, d: &[u8], gs: &[usize]) { + for &g in gs { + job.chunk(id, (g * G) as u64, &d[g * G..((g + 1) * G).min(d.len())]); + } +} + +fn summary() -> String { + let mut b = vec![0u8; 1024]; + let n = unsafe { ava1_test_apply_summary(b.as_mut_ptr(), b.len()) }; + String::from_utf8_lossy(&b[..n]).into_owned() } fn tmp(tag: &str) -> TempDir { @@ -77,6 +133,9 @@ impl Drop for Knobs { fn drop(&mut self) { unsafe { ava1_test_corrupt_at_commit(0, 0); + ava1_test_rb_corrupt(0, 0); + ava1_test_rb_hold(0); + ava1_test_chunk_delay(0); ava1_test_set_pwrite_max(0); } } @@ -115,11 +174,11 @@ fn readback_finds_a_byte_changed_on_the_drive_and_the_file_is_sent_again() { entries: vec![file("big.bin", d.len() as u64)], }; let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); - unsafe { ava1_test_corrupt_at_commit(1, 4 * GROUP + 1) }; + unsafe { ava1_test_rb_corrupt(1, 4 * GROUP + 1) }; send_large(&job, 0, &d); // FileRetry{file 0, RETRY_VERIFY}: the sender's cue to send the whole file again job.wait_event("retry 0 1", 10_000); - assert_eq!(unsafe { ava1_test_corrupt_left() }, 0); + assert_eq!(unsafe { ava1_test_rb_corrupt_left() }, 0); assert!(!root.join("big.bin").exists(), "nothing was committed"); send_large(&job, 0, &d); assert_eq!(job.wait(10_000), 0, "{}", job.events()); @@ -137,7 +196,7 @@ fn a_file_that_never_reads_back_right_fails_the_job_with_err_verify() { entries: vec![file("big.bin", d.len() as u64)], }; let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); - unsafe { ava1_test_corrupt_at_commit(1000, 5) }; + unsafe { ava1_test_rb_corrupt(1000, 5) }; // each mismatch asks for the file again (FileRetry), until AVA1_READBACK_TRIES (3) are spent send_large(&job, 0, &d); wait_count(&job, "retry 0 1", 1); @@ -202,7 +261,7 @@ fn a_resume_may_turn_readback_on_or_off() { r.manifest(&m); let ev = r.wait_event("map status=0", 5000); assert!(ev.contains("partial=1"), "the durable half was kept: {ev}"); - unsafe { ava1_test_corrupt_at_commit(1, 3 * GROUP) }; + unsafe { ava1_test_rb_corrupt(1, 3 * GROUP) }; r.chunk(0, 2 * GROUP, &d[2 * GROUP as usize..]); r.root(0, *blake3::hash(&d).as_bytes()); r.wait_event("retry 0 1", 10_000); // the read-back is on for the resumed job @@ -230,7 +289,7 @@ fn a_big_file_is_read_back_in_stripes_and_a_late_change_is_found() { entries: vec![file("big.bin", size as u64)], }; let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); - unsafe { ava1_test_corrupt_at_commit(1, size as u64 - 3) }; + unsafe { ava1_test_rb_corrupt(1, size as u64 - 3) }; send_large_paced(&job, 0, &d); job.wait_event("retry 0 1", 60_000); send_large_paced(&job, 0, &d); @@ -238,6 +297,355 @@ fn a_big_file_is_read_back_in_stripes_and_a_late_change_is_found() { assert!(std::fs::read(root.join("big.bin")).unwrap() == d); } +/// Four lanes, each writing its own groups and every lane in its own order: the groups are read back +/// as batches make them durable, whatever their order, and the commit reads only what is left. Every +/// byte is read back exactly once. +#[test] +fn groups_are_read_back_while_the_file_arrives_in_any_order() { + let _k = Knobs; + let t = tmp("live"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(24 * G + 4321, 8); // 25 groups, the last one short + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + // lane k has the groups k, k + 4, ...; the lanes take turns, the odd ones going backwards + let lanes: Vec> = (0..4) + .map(|k| { + let mut v: Vec = (k..25).step_by(4).collect(); + if k % 2 == 1 { + v.reverse(); + } + v + }) + .collect(); + let mut order = Vec::new(); + for i in 0..7 { + for lane in &lanes { + if let Some(&g) = lane.get(i) { + order.push(g); + } + } + } + assert_eq!(order.len(), 25); + let mut sent = 0u64; + for wave in [&order[..9], &order[9..18]] { + send_groups(&job, 0, &d, wave); + sent += bytes_of(&d, wave); + // no root yet, so nothing commits: the live read-back alone reads what is durable + wait_until("the live read-back", 10_000, || rb_stats()[0] == sent); + } + send_groups(&job, 0, &d, &order[18..]); + job.root(0, *blake3::hash(&d).as_bytes()); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); + let st = rb_stats(); + assert!(st[0] >= sent, "{st:?}"); + assert_eq!(st[0] + st[1], d.len() as u64, "every byte once: {st:?}"); + assert_eq!((st[2], st[3]), (1, 0), "{st:?}"); + let line = summary(); + assert!(line.contains("while they arrived"), "{line}"); +} + +/// The receive workers never idle: every chunk's write takes 20 ms, and chunks keep queueing behind them +/// for the whole transfer. The read-back has threads of its own, so it still reads most of the file while +/// it arrives (all but what the last batches make durable), one read in flight while chunks wait. +#[test] +fn most_of_a_file_is_read_back_while_every_worker_is_busy_with_chunks() { + let _k = Knobs; + let t = tmp("busy"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(200 * G + 9, 16); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + unsafe { ava1_test_chunk_delay(20) }; + send_large_paced(&job, 0, &d); // offers each chunk as soon as there is credit for it + assert_eq!(job.wait(30_000), 0, "{}", job.events()); + unsafe { ava1_test_chunk_delay(0) }; + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); + let st = rb_stats(); + let size = d.len() as u64; + assert_eq!(st[0] + st[1], size, "every byte once: {st:?}"); + assert!( + st[8] > 0, + "no read while chunks waited: the workers were never all busy: {st:?}" + ); + assert!( + st[0] * 2 >= size, + "only {} of {size} bytes read back live: {st:?}", + st[0] + ); + assert!(st[9] > 0 && st[10] >= 1, "{st:?}"); + let line = summary(); + assert!(line.contains("with chunks waiting"), "{line}"); +} + +/// Every read-back read, live or at the commit, first asks the OS to drop its range from the page cache +/// (a read answered from memory proves nothing about the drive). That the next read then misses the cache +/// cannot be checked portably; that the call is made for every read can. Linux has the call and must +/// answer it; macOS has none (the job's "read-back may read cached pages" line says so). +#[test] +fn every_read_back_read_first_drops_its_range_from_the_cache() { + let _k = Knobs; + let t = tmp("evict"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(20 * G + 333, 17); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + send_groups(&job, 0, &d, &(0..12).collect::>()); + wait_until("the live read-back", 10_000, || rb_stats()[0] == 12 * GROUP); + send_groups(&job, 0, &d, &(12..21).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + let st = rb_stats(); + let reads = st[4] + st[5]; + assert!(st[4] >= 2 && reads >= 3, "{st:?}"); + assert_eq!(st[11], reads, "one drop per read: {st:?}"); + if cfg!(target_os = "linux") { + assert_eq!(st[12], st[11], "posix_fadvise answered every drop: {st:?}"); + } + if cfg!(target_os = "macos") { + assert_eq!((st[12], st[13]), (0, 0), "{st:?}"); + } + assert!(st[13] <= reads, "{st:?}"); + let line = summary(); + assert!( + line.contains("reads with the cache dropped first"), + "{line}" + ); + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); +} + +/// A byte that changes on the drive after its batch made it durable and before the live read-back reads +/// its group is found then. The sender is not told while it still sends the file (an old sender does not +/// expect it); the commit acts on it as on its own read-back: the file is sent again. +#[test] +fn a_byte_changed_before_its_group_is_read_back_is_found_while_the_file_arrives() { + let _k = Knobs; + let t = tmp("live-bad"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(12 * G + 77, 9); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + unsafe { ava1_test_rb_corrupt(1, 5 * GROUP + 9) }; + let first: Vec = (0..8).rev().collect(); + send_groups(&job, 0, &d, &first); + wait_until("the changed byte read back", 10_000, || unsafe { + ava1_test_rb_corrupt_left() == 0 + }); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!(!job.events().contains("retry"), "{}", job.events()); + assert!(rb_stats()[4] >= 1); + send_groups(&job, 0, &d, &(8..13).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + job.wait_event("retry 0 1", 10_000); + assert_eq!(rb_stats()[3], 1); + assert!(!root.join("big.bin").exists(), "nothing was committed"); + send_large(&job, 0, &d); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); +} + +/// The documented gap: the read-back proves what the drive held once each group was durable. A byte +/// that changes after its group was read back, while the rest of the file still arrives, is not read +/// again, and the file commits with it. +#[test] +fn a_byte_changed_after_its_group_was_read_back_is_not_found() { + let _k = Knobs; + let t = tmp("live-late"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(10 * G, 10); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + send_groups(&job, 0, &d, &(0..6).collect::>()); + wait_until("the live read-back", 10_000, || rb_stats()[0] == 6 * GROUP); + unsafe { ava1_test_corrupt_at_commit(1, 2 * GROUP + 3) }; // flipped as the commit begins + send_groups(&job, 0, &d, &(6..10).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + assert_eq!(unsafe { ava1_test_corrupt_left() }, 0); + let got = std::fs::read(root.join("big.bin")).unwrap(); + assert_eq!(got[2 * G + 3], d[2 * G + 3] ^ 0x5a); + let st = rb_stats(); + assert_eq!(st[0] + st[1], d.len() as u64, "{st:?}"); +} + +/// A late duplicate over groups already read back: they are durable again only once its batch is done, +/// and are read back again then (the commit trusts nothing read before the last write). +#[test] +fn a_group_written_again_is_read_back_again() { + let _k = Knobs; + let t = tmp("live-dup"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(10 * G + 5, 11); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + send_groups(&job, 0, &d, &(0..6).collect::>()); + wait_until("the live read-back", 10_000, || rb_stats()[0] == 6 * GROUP); + send_groups(&job, 0, &d, &[2]); + wait_until("the group read back again", 10_000, || { + rb_stats()[0] == 7 * GROUP + }); + send_groups(&job, 0, &d, &(6..11).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); + let st = rb_stats(); + assert_eq!(st[0] + st[1], d.len() as u64 + GROUP, "{st:?}"); +} + +/// A group found wrong while the file arrives and then written again (a duplicate the sender had in +/// flight) is judged by its new bytes: read back again, right this time, and the file commits. +#[test] +fn a_group_found_wrong_and_written_again_is_judged_by_its_new_bytes() { + let _k = Knobs; + let t = tmp("live-fixed"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(9 * G, 15); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + unsafe { ava1_test_rb_corrupt(1, 3 * GROUP + 2) }; + send_groups(&job, 0, &d, &(0..5).collect::>()); + wait_until("the changed byte read back", 10_000, || unsafe { + ava1_test_rb_corrupt_left() == 0 + }); + let before = rb_stats()[0]; + send_groups(&job, 0, &d, &[3]); + wait_until("the group read back again", 10_000, || { + rb_stats()[0] >= before + GROUP + }); + send_groups(&job, 0, &d, &(5..9).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + assert!(!job.events().contains("retry"), "{}", job.events()); + assert_eq!(rb_stats()[3], 0); + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); +} + +/// Three mismatches, each found by the live read-back while the file arrives: the job fails with +/// ERR_VERIFY after the third, as when the commit finds them. +#[test] +fn mismatches_found_while_the_file_arrives_fail_the_job_after_three() { + let _k = Knobs; + let t = tmp("live-always"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(10 * G, 12); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + unsafe { ava1_test_rb_corrupt(1000, 3) }; + for round in 1..=3 { + send_groups(&job, 0, &d, &(0..5).collect::>()); + wait_until("the live read-back", 10_000, || unsafe { + ava1_test_rb_corrupt_left() == 1000 - round + }); + send_groups(&job, 0, &d, &(5..10).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + if round < 3 { + wait_count(&job, "retry 0 1", round as usize); + } + } + assert_eq!(job.wait(10_000), gen::ERR_VERIFY as i32, "{}", job.events()); + assert_eq!(job.events().matches("retry 0 1").count(), 2); + assert_eq!(rb_stats()[3], 3); + assert!(!root.join("big.bin").exists()); +} + +/// A stop while a live read-back is reading does not wait for it to finish, and the resumed job reads +/// back what this process has not (the groups made durable before the restart included). +#[test] +fn a_stop_during_a_live_read_back_is_prompt_and_the_resume_reads_back_the_rest() { + let _k = Knobs; + let t = tmp("live-stop"); + std::fs::create_dir_all(t.join("dest")).unwrap(); + let d = data(12 * G + 5, 13); + let m = Manifest { + entries: vec![file("big", d.len() as u64)], + }; + let r = CRecv::open( + &t.join("jobs"), + &t.join("dest"), + gen::JF_READBACK, + gen::POLICY_REPLACE, + 0, + ); + r.manifest(&m); + r.wait_event("map status=0", 5000); + unsafe { ava1_test_rb_hold(1) }; + send_groups(&r, 0, &d, &(0..6).collect::>()); + wait_until("a live read-back held", 10_000, || rb_stats()[6] >= 1); + let t0 = std::time::Instant::now(); + let r = r.restart(0); // the payload stops mid read-back and comes back + assert!( + t0.elapsed().as_secs() < 5, + "the stop took {:?}", + t0.elapsed() + ); + unsafe { ava1_test_rb_hold(0) }; + assert_eq!(unsafe { ava1_test_job_readback() }, 1); + r.manifest(&m); + let ev = r.wait_event("map status=0", 5000); + assert!( + ev.contains("partial=1"), + "the durable groups were kept: {ev}" + ); + send_groups(&r, 0, &d, &(6..13).collect::>()); + r.root(0, *blake3::hash(&d).as_bytes()); + assert_eq!(r.wait(10_000), 0, "{}", r.events()); + assert_eq!(std::fs::read(t.join("dest/big")).unwrap(), d); + let st = rb_stats(); + assert_eq!(st[0] + st[1], d.len() as u64, "{st:?}"); + assert_eq!(st[3], 0); +} + +/// Ending a job (a cancel) while a live read-back is reading does not wait for it either. +#[test] +fn ending_a_job_during_a_live_read_back_is_prompt() { + let _k = Knobs; + let t = tmp("live-end"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(8 * G, 14); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + unsafe { ava1_test_rb_hold(1) }; + send_groups(&job, 0, &d, &(0..4).collect::>()); + wait_until("a live read-back held", 10_000, || rb_stats()[6] >= 1); + let t0 = std::time::Instant::now(); + let _ = job.end(); + assert!( + t0.elapsed().as_secs() < 5, + "the end took {:?}", + t0.elapsed() + ); + assert_eq!(rb_stats()[6], 0, "the held read-back let go"); + assert!(!root.join("big.bin").exists()); +} + mod common; /// End to end, Rust sender to C receiver, with the read-back on: a file past 4 GiB whose bytes at diff --git a/spec/SPEC.md b/spec/SPEC.md index c03b349..273b76d 100644 --- a/spec/SPEC.md +++ b/spec/SPEC.md @@ -870,18 +870,33 @@ every partial file and resets a file on any mismatch. The verify policy re-hashe 13.5 Read-back (`JF_READBACK`). Every check above hashes the bytes as they arrived, so a write that landed wrong on the drive (a short or misplaced write, a filesystem or drive fault, another process -writing the file) commits unnoticed. With `JF_READBACK` the receiver, once every byte of a large file is -durable and its outboard's root equals the sender's root, reads the part file back from the drive and -compares each group's CV with the outboard's (a file of one group is already hashed from the drive at -commit). A mismatch resets the file and sends `FileRetry{RETRY_VERIFY}`, so the sender sends the whole -file again; the receiver logs it. After 3 mismatches of one file in a job the job ends with -`ERR_VERIFY` (journal kept). A `job.copy` has no sender to resend: there the first mismatch ends the -copy with `ERR_VERIFY` ("a copied file did not verify", as any copy retry does) and a re-issued copy -goes on from its journal. A read that fails ends the job with `ERR_IO`. The read-back runs on the -commit's worker, before the rename; a big file may be read in stripes on several threads. The read -goes through the receiver's filesystem, so a page cache may answer for bytes still held in memory; -what it proves is what any later reader of the file will get. Small files are out of its scope (their -roots are checked from the log record or the file when they are recovered, §15.7). +writing the file) commits unnoticed. With `JF_READBACK` the receiver reads every group of a large file +back from the drive and compares its CV with the outboard's before the file is committed (a file of one +group is already hashed from the drive at commit). A group is read back only once it is durable: the +sync batch that wrote it has fsynced the part file and the outboard and journaled the range. It may be +read then, while the rest of the file still arrives, in any order; the commit, once every byte is durable +and the outboard's root equals the sender's root, reads back the groups that were not (the last batch's, +those the early reads had no time for, and those made durable before a restart of the receiver). A group +written again after it was read back (a duplicate chunk) is read back again once that write is durable, +so each group is read back once after it was last made durable. A mismatch found while the file arrives +is acted on at the commit, not before (the sender is still sending the file). A mismatch resets the file +and sends `FileRetry{RETRY_VERIFY}`, so the sender sends the whole file again; the receiver logs it. +After 3 mismatches of one file in a job the job ends with `ERR_VERIFY` (journal kept). A `job.copy` has +no sender to resend: there the first mismatch ends the copy with `ERR_VERIFY` ("a copied file did not +verify", as any copy retry does) and a re-issued copy goes on from its journal. A read that fails ends the +job with `ERR_IO`. The early reads run on a few threads of the receiver's own, apart from the ones that +write the data, and read no more than the batches have made durable; while the data waits for a writer +the C node keeps one early read in flight. The commit's reads run on its worker, before the rename, and a +big remainder may be read in stripes on several threads. What the read-back proves is what the drive held +once each group was durable: a byte that changes after its group was read back, while later groups still +arrive, is not found (no more than one that changes after the commit). Read right after its batch, a +group is still in the page cache, and a read answered from memory proves nothing about the drive: a +receiver should read past the cache. The C node drops each range's cached pages first (they are clean: +`posix_fadvise(POSIX_FADV_DONTNEED)`, and on FreeBSD, where that only deactivates the pages, also +`msync(MS_INVALIDATE)` over a mapping of the range) and reads through an `O_DIRECT` descriptor where the +filesystem allows one; it logs which, once per job. Where neither is possible the read goes through the +cache, and what it proves is what any later reader of the file will get. Small files are out of its scope (their roots are checked from the +log record or the file when they are recovered, §15.7). ## 14. Journal and resume