// SPDX-License-Identifier: MIT
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/statfs.h>
#include <sys/syscall.h>
#include <sys/utsname.h>
#include <unistd.h>

#ifndef SYS_cachestat
int main(void) { fputs("cachestat syscall headers unavailable\n", stderr); return 77; }
#else
static int report(int fd, uint64_t off, uint64_t len, const char *name) {
    struct cachestat_range range = {.off = off, .len = len};
    struct cachestat stats = {0};
    if (syscall(SYS_cachestat, fd, &range, &stats, 0) != 0) {
        perror("cachestat");
        return -1;
    }
    printf("{\"name\":\"%s\",\"off\":%" PRIu64 ",\"len\":%" PRIu64
           ",\"nr_cache\":%llu,\"nr_dirty\":%llu,\"nr_writeback\":%llu,"
           "\"nr_evicted\":%llu,\"nr_recently_evicted\":%llu}",
           name, off, len, (unsigned long long)stats.nr_cache,
           (unsigned long long)stats.nr_dirty, (unsigned long long)stats.nr_writeback,
           (unsigned long long)stats.nr_evicted, (unsigned long long)stats.nr_recently_evicted);
    return 0;
}
int main(void) {
    const long page = sysconf(_SC_PAGESIZE);
    if (page <= 0 || page > 1048576) return 1;
    const size_t size = (size_t)page * 2;
    char filename[] = "cachestat-own-XXXXXX";
    int fd = mkstemp(filename);
    if (fd < 0) { perror("mkstemp"); return 1; }
    if (unlink(filename) != 0) { perror("unlink"); close(fd); return 1; }
    int status = 1;
    unsigned char *bytes = malloc(size);
    void *mapping = MAP_FAILED;
    if (!bytes) goto cleanup;
    memset(bytes, 0x5a, size);
    for (size_t offset = 0; offset < size;) {
        ssize_t count = write(fd, bytes + offset, size - offset);
        if (count < 0 && errno == EINTR) continue;
        if (count <= 0) { perror("write"); goto cleanup; }
        offset += (size_t)count;
    }
    mapping = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
    if (mapping == MAP_FAILED) { perror("mmap"); goto cleanup; }
    // Pin only this private two-page fixture so eviction cannot obscure the range boundary.
    if (mlock(mapping, size) != 0) { perror("mlock"); status = 77; goto cleanup; }
    if (memcmp(mapping, bytes, size) != 0) goto cleanup;
    struct utsname system;
    struct statfs filesystem;
    if (uname(&system) != 0 || fstatfs(fd, &filesystem) != 0) goto cleanup;
    struct cachestat_range range = {.off = 0, .len = size};
    struct cachestat stats = {0};
    if (syscall(SYS_cachestat, fd, &range, &stats, 0) != 0) {
        int error = errno;
        perror("cachestat unavailable or denied");
        status = (error == ENOSYS || error == EPERM || error == EOPNOTSUPP) ? 77 : 1;
        goto cleanup;
    }
    errno = 0;
    long bad_fd = syscall(SYS_cachestat, -1, &range, &stats, 0);
    int bad_fd_errno = errno;
    errno = 0;
    long bad_flags = syscall(SYS_cachestat, fd, &range, &stats, 1);
    int bad_flags_errno = errno;
    if (bad_fd != -1 || bad_fd_errno != EBADF || bad_flags != -1 || bad_flags_errno != EINVAL) goto cleanup;
    printf("{\"kernel\":\"%s\",\"machine\":\"%s\",\"page_size\":%ld,"
           "\"filesystem_magic\":\"0x%lx\",\"locked_pages\":2,"
           "\"negative_controls\":{\"bad_fd_errno\":%d,\"bad_flags_errno\":%d},\"samples\":[",
           system.release, system.machine, page, (unsigned long)filesystem.f_type,
           bad_fd_errno, bad_flags_errno);
    if (report(fd, 0, size, "after_write") != 0) goto cleanup;
    if (fsync(fd) != 0) { perror("fsync"); goto cleanup; }
    struct { uint64_t off, len; const char *name; } cases[] = {
        {0, 1, "first_byte"}, {0, page, "first_page"},
        {page - 1, 1, "last_byte_first_page"}, {page - 1, 2, "cross_boundary"},
        {page, page, "second_page"}, {page, 0, "zero_length_to_end"}
    };
    for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
        putchar(',');
        if (report(fd, cases[i].off, cases[i].len, cases[i].name) != 0) goto cleanup;
    }
    puts("]}");
    status = 0;
cleanup:
    if (mapping != MAP_FAILED) munmap(mapping, size);
    free(bytes);
    close(fd);
    return status;
}
#endif
