/* =============================================================================
 * 02_memory_mountain.c  --  read throughput vs working-set size and stride
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The slides show a "memory mountain": read bandwidth as a surface over
 *     (working-set size, stride). What does it look like on this machine?
 *   - Where are the cache-level ridges (temporal locality) and the stride
 *     slopes (spatial locality)?
 *
 * [How to build & run]
 *   make && ./build/02_memory_mountain
 *
 * [How to read the output]
 *   A table: rows are working-set sizes (temporal locality -- which cache the
 *   data fits in), columns are strides in elements (spatial locality -- how
 *   much of each 64-byte block is used). Each cell is read throughput in GB/s;
 *   bigger is better. Read across a row to see spatial locality fall off as the
 *   stride grows; read down a column to see the working set spill out of each
 *   cache. Throughput varies run to run; the SHAPE is the point.
 *
 * [Systems link / CS:APP 6.6]
 *   The mountain is the single most compact picture of a memory system. Its
 *   back ridge (small size, any stride) is L1 bandwidth; the terraces stepping
 *   down are L2, L3 and DRAM; the slope toward large strides is spatial
 *   locality being wasted as each cache block is used less and less.
 * -------------------------------------------------------------------------- */

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

#define MAXELEMS (1 << 24)          /* 16 M longs = 128 MiB: bigger than any cache */
static long data[MAXELEMS];

/* [Idea] The slides' test(): sum `elems` elements with the given `stride`,
 *   4x unrolled into 4 accumulators so the loop is not latency-bound and the
 *   measurement reflects memory bandwidth, not add latency.
 * [Returns] the sum (used so nothing is optimized away). */
static long test(long elems, long stride)
{
    long i, sx2 = stride * 2, sx3 = stride * 3, sx4 = stride * 4;
    long acc0 = 0, acc1 = 0, acc2 = 0, acc3 = 0;
    long limit = elems - sx4;
    for (i = 0; i < limit; i += sx4) {
        acc0 += data[i];
        acc1 += data[i + stride];
        acc2 += data[i + sx2];
        acc3 += data[i + sx3];
    }
    for (; i < elems; i += stride)
        acc0 += data[i];
    return acc0 + acc1 + acc2 + acc3;
}

/* [Idea] Run test() over `elems` at `stride` and return GB/s of data READ.
 *   Only every stride-th element is touched, so bytes read = (elems/stride)*8. */
static double run(long elems, long stride)
{
    /* Repeat enough times that even an L1-resident set takes a measurable
     * time: aim for ~200M element touches per trial. */
    long touches = elems / stride;
    long reps = 200L * 1000 * 1000 / (touches > 0 ? touches : 1);
    if (reps < 1) reps = 1;
    test(elems, stride);                        /* warm the cache for this size */
    double best = 0;
    for (int trial = 0; trial < 3; trial++) {   /* best of a few trials */
        long acc = 0;
        double t0 = wall_seconds();
        for (long r = 0; r < reps; r++)
            acc += test(elems, stride);
        double dt = wall_seconds() - t0;
        volatile long sink = acc; (void)sink;
        if (dt <= 0) continue;
        double gbs = (double)reps * touches * sizeof(long) / dt / 1e9;
        if (gbs > best) best = gbs;
    }
    return best;
}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 02: the memory mountain (%s) ===\n\n", arch);
    for (long i = 0; i < MAXELEMS; i++) data[i] = i;    /* touch so pages are mapped */

    long sizes[] = {4L << 10, 16L << 10, 64L << 10, 256L << 10, 1L << 20,
                    4L << 20, 16L << 20, 64L << 20, 128L << 20};
    const char *size_lbl[] = {"4K", "16K", "64K", "256K", "1M", "4M", "16M", "64M", "128M"};
    long strides[] = {1, 2, 4, 8, 16, 32};

    printf("  read throughput (GB/s); rows = working set, cols = stride (elements)\n");
    printf("  %-8s", "size\\str");
    for (size_t j = 0; j < sizeof(strides) / sizeof(strides[0]); j++)
        printf(" s%-7ld", strides[j]);
    printf("\n");
    for (size_t r = 0; r < sizeof(sizes) / sizeof(sizes[0]); r++) {
        long elems = sizes[r] / (long)sizeof(long);
        printf("  %-8s", size_lbl[r]);
        for (size_t j = 0; j < sizeof(strides) / sizeof(strides[0]); j++) {
            long st = strides[j];
            if (elems <= st * 4) { printf(" %-8s", "-"); continue; }
            printf(" %-8.1f", run(elems, st));
        }
        printf("\n");
    }
    printf("\nObservations:\n");
    printf("  * Top-left (small size, small stride) is the peak: data in L1, every byte\n"
           "    of each block used -- both localities maxed out.\n");
    printf("  * Down a column: throughput steps down as the working set spills from L1\n"
           "    to L2 to DRAM (temporal locality lost). The terraces are the cache sizes.\n");
    printf("  * Across a row: throughput falls as the stride grows, because each 64-byte\n"
           "    block (8 longs) delivers fewer used elements (spatial locality lost).\n");
    printf("  * By stride 8 (64 bytes) each access needs its own block, so larger\n"
           "    strides stop hurting -- the slope flattens.\n");
    printf("  * Numbers vary with the machine and run; the mountain's SHAPE is stable.\n");
    return 0;
}
