/* =============================================================================
 * 02_mmap.c  --  memory-mapped files and copy-on-write, for real
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - Virtual memory lets a page be backed by a FILE, not just by DRAM/swap.
 *     What does it mean to map a file into memory and edit it with ordinary
 *     pointer writes?
 *   - A private (copy-on-write) mapping shares pages until one is written. How
 *     does writing one page leave the file and the other pages untouched?
 *
 * [How to build & run]
 *   make && ./build/02_mmap            (native)
 *
 * [How to read the output]
 *   PART A creates a small file, mmap()s it, reads and modifies it THROUGH
 *   MEMORY (no read()/write()), and shows the file on disk changed. PART B maps
 *   the same file MAP_PRIVATE (copy-on-write), writes through the mapping, and
 *   shows the process sees its change but the file does not.
 *
 * [Systems link / CS:APP 9.8]
 *   mmap is the system call behind this: it adds an "area" to the process's
 *   virtual address space backed by a file. The pages are brought in on demand
 *   by the same page-fault machinery as any other page (Lecture 11); a shared
 *   mapping's writes go back to the file, a private mapping's writes trigger
 *   copy-on-write. This is how programs are loaded (the text segment is a
 *   read-only file mapping) and how fork() shares memory cheaply.
 * -------------------------------------------------------------------------- */

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

static const char *PATH = "build/mmap_demo.dat";

/* [Idea] create a file of `n` bytes filled with a pattern; [Returns] 0 on ok. */
static int make_file(const char *path, size_t n)
{
    FILE *f = fopen(path, "wb");
    if (!f) { perror("fopen"); return -1; }
    for (size_t i = 0; i < n; i++)
        fputc('A' + (int)(i % 26), f);
    fclose(f);
    return 0;
}

static void show_head(const char *path, const char *label)
{
    FILE *f = fopen(path, "rb");
    char buf[17] = {0};
    size_t k = fread(buf, 1, 16, f);
    fclose(f);
    buf[k] = 0;
    printf("  %-22s \"%s\"\n", label, buf);
}

static void part_a(void)
{
    printf("PART A: edit a file through memory (MAP_SHARED)\n");
    size_t n = 64;
    make_file(PATH, n);
    show_head(PATH, "file before:");
    int fd = open(PATH, O_RDWR);
    if (fd < 0) { perror("open"); return; }
    /* Map the file into our address space, read+write, SHARED (changes go back). */
    char *m = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (m == MAP_FAILED) { perror("mmap"); close(fd); return; }
    printf("  mapped %zu bytes at %p; reading m[0..3] = %c%c%c%c (no read() call)\n",
           n, (void *)m, m[0], m[1], m[2], m[3]);
    memcpy(m, "mmap!", 5);                 /* a plain memory write... */
    msync(m, n, MS_SYNC);                  /* ...flushed back to the file */
    munmap(m, n);
    close(fd);
    show_head(PATH, "file after m[0..4]=:");
    printf("  A pointer write changed the file on disk -- no write() system call.\n");
    printf("  The page fault that first touched the mapping loaded the file's bytes;\n");
    printf("  because the mapping is SHARED, the dirtied page was written back.\n\n");
}

static void part_b(void)
{
    printf("PART B: a private copy-on-write mapping (MAP_PRIVATE)\n");
    size_t n = 64;
    make_file(PATH, n);
    int fd = open(PATH, O_RDWR);
    if (fd < 0) { perror("open"); return; }
    char *m = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (m == MAP_FAILED) { perror("mmap"); close(fd); return; }
    printf("  mapped MAP_PRIVATE; this process sees m[0..3] = %c%c%c%c\n", m[0], m[1], m[2], m[3]);
    memcpy(m, "priv!", 5);                 /* write triggers copy-on-write */
    printf("  after writing, THIS process sees m[0..4] = %.5s\n", m);
    msync(m, n, MS_SYNC);
    munmap(m, n);
    close(fd);
    show_head(PATH, "file on disk:");
    printf("  The process saw its change, but the FILE is unchanged: a private\n");
    printf("  mapping copies a page on the first write (copy-on-write), leaving the\n");
    printf("  original file and any other sharers untouched. This is exactly how\n");
    printf("  fork() gives a child its own memory cheaply (Lecture 16).\n\n");
    remove(PATH);
}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 02: memory-mapped files (%s) ===\n\n", arch);
    part_a();
    part_b();
    printf("Observations:\n");
    printf("  * mmap maps a file into the address space; after that, ordinary loads and\n"
           "    stores read and write the file, brought in page by page on demand.\n");
    printf("  * MAP_SHARED writes reach the file (and other sharers); MAP_PRIVATE writes\n"
           "    trigger copy-on-write and stay local.\n");
    printf("  * The same mechanism loads executables (read-only text mappings) and makes\n"
           "    fork() cheap -- both rest on the page table and page-fault handling of L11.\n");
    return 0;
}
