/* =============================================================================
 * 02_working_set.c  --  see the cache hierarchy as plateaus in access time
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The memory hierarchy is supposed to make a big memory look fast WHEN the
 *     working set fits in a cache. Can we see the level boundaries from a
 *     program, without any special tools?
 *   - Why does the time-per-access jump upward in steps as the working set
 *     grows past L1, then L2, then the last-level cache?
 *
 * [How to build & run]
 *   make && ./build/02_working_set
 *
 * [How to read the output]
 *   For each working-set SIZE, the demo repeatedly chases a pointer through a
 *   randomly-permuted cycle covering exactly that many bytes (stride that
 *   defeats prefetching), and reports the average time per access in ns. Watch
 *   for roughly flat regions (a cache level) separated by upward steps (the
 *   working set spilled to the next level). The exact ns vary run to run; the
 *   STEP STRUCTURE is the stable, meaningful part.
 *
 * [Systems link / CS:APP 6.3-6.4]
 *   This is the "temporal" ridge of the memory mountain (Lecture 10), measured
 *   on its own. Pointer-chasing makes each access depend on the previous one,
 *   so the CPU cannot overlap misses or prefetch, and the time you measure is
 *   the latency of whichever level currently holds the data.
 * -------------------------------------------------------------------------- */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "timer.h"

/* [Idea] Build a single cycle that visits every slot of `n` pointers in a
 *   random order, by permuting [0, n) and linking perm[i] -> perm[i+1] ->
 *   ... -> perm[0]. Chasing it touches all n slots with no predictable stride,
 *   so hardware prefetchers cannot help. */
static void build_cycle(void **slots, size_t n, unsigned *seed)
{
    size_t *perm = malloc(n * sizeof(size_t));
    for (size_t i = 0; i < n; i++) perm[i] = i;
    for (size_t i = n - 1; i > 0; i--) {              /* Fisher-Yates shuffle */
        *seed = *seed * 1103515245u + 12345u;         /* a fixed LCG: reproducible */
        size_t j = *seed % (i + 1);
        size_t t = perm[i]; perm[i] = perm[j]; perm[j] = t;
    }
    for (size_t i = 0; i < n; i++)
        slots[perm[i]] = &slots[perm[(i + 1) % n]];   /* link into one big cycle */
    free(perm);
}

/* [Idea] Chase the pointer `steps` times; [Returns] ns per access. The volatile
 *   sink stops the compiler from deleting the loop. */
static double chase(void **start, long steps)
{
    void *p = (void *)start;
    double t0 = wall_seconds();
    for (long i = 0; i < steps; i++) {
        p = *(void **)p;
        __asm__ volatile("" : "+r"(p));     /* force the load each iteration */
    }
    double dt = wall_seconds() - t0;
    volatile void *sink = p; (void)sink;
    return dt / steps * 1e9;
}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 02: working-set size vs access latency (%s) ===\n\n", arch);
    printf("  Pointer-chasing a random cycle of each size (no prefetch possible).\n");
    printf("  %-12s %-12s %s\n", "working set", "ns/access", "roughly");
    size_t sizes_kib[] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048,
                          4096, 8192, 16384, 32768, 65536};
    unsigned seed = 15213;
    double prev = 0;
    for (size_t k = 0; k < sizeof(sizes_kib) / sizeof(sizes_kib[0]); k++) {
        size_t bytes = sizes_kib[k] * 1024;
        size_t n = bytes / sizeof(void *);
        void **slots = malloc(n * sizeof(void *));
        if (!slots) break;
        build_cycle(slots, n, &seed);
        long steps = 50 * 1000 * 1000;                /* enough to average out noise */
        chase(slots, n);                               /* warm it once */
        double ns = chase(slots, steps);
        const char *note = "";
        if (prev > 0 && ns > prev * 1.5) note = "<-- stepped up to a slower level";
        char sz[16];
        if (sizes_kib[k] >= 1024) snprintf(sz, sizeof sz, "%zu MiB", sizes_kib[k] / 1024);
        else snprintf(sz, sizeof sz, "%zu KiB", sizes_kib[k]);
        printf("  %-12s %7.2f      %s\n", sz, ns, note);
        prev = ns;
        free(slots);
    }
    printf("\nObservations:\n");
    printf("  * The curve is a STAIRCASE, not a line: while the working set fits in a\n"
           "    cache level the time is roughly flat; when it spills to the next level\n"
           "    the time steps up. Each flat region is one level of the hierarchy.\n");
    printf("  * The first steps mark the L1 and L2 sizes; the last big step is the gap\n"
           "    to main memory (DRAM), tens of times slower than L1.\n");
    printf("  * This is why 'performance is more than big-O' (Reality 4): the SAME\n"
           "    O(n) pointer walk is many times slower once n leaves the cache.\n");
    printf("  * Exact ns vary with the machine and run; the step STRUCTURE is stable.\n");
    return 0;
}
