/* =============================================================================
 * 04_machine_info.c -- ask the machine what it actually is
 * =============================================================================
 *
 * [Idea]
 *   Every number in this lecture depends on the hardware: how many cores, how
 *   fast each one is, how big a cache line is, how much cache there is. Before
 *   reasoning about speedup you should know what you are running on. On Linux
 *   you read /proc/cpuinfo; macOS has no /proc, so the equivalent is sysctl.
 *
 *   The detail that matters most here: an Apple-silicon machine is
 *   HETEROGENEOUS. Its cores are not interchangeable -- some are performance
 *   cores and some are efficiency cores -- so "12 cores" does not mean "12x".
 *
 * [What it answers]
 *   - How many cores do I have, and are they the same kind?
 *   - What is the cache-line size (the unit of false sharing)?
 *   - Where do these numbers come from on this OS?
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <string.h>
#ifdef __APPLE__
#include <sys/sysctl.h>

/* Read one integer sysctl by name; returns -1 if it does not exist. */
static long get_int(const char *name)
{
    long v = 0; size_t len = sizeof(v);
    if (sysctlbyname(name, &v, &len, NULL, 0) != 0) return -1;
    return v;
}

static void get_str(const char *name, char *buf, size_t buflen)
{
    size_t len = buflen;
    if (sysctlbyname(name, buf, &len, NULL, 0) != 0)
        snprintf(buf, buflen, "(unavailable)");
}
#endif

static void line(const char *label, long v, const char *unit)
{
    if (v < 0) printf("  %-34s %s\n", label, "(not reported)");
    else       printf("  %-34s %ld %s\n", label, v, unit);
}

int main(void)
{
#ifdef __APPLE__
    char brand[128];
    get_str("machdep.cpu.brand_string", brand, sizeof(brand));
    printf("CPU: %s\n", brand);
    printf("(source: sysctl -- macOS has no /proc/cpuinfo)\n\n");

    long logical  = get_int("hw.logicalcpu");
    long physical = get_int("hw.physicalcpu");
    long p_cores  = get_int("hw.perflevel0.logicalcpu");
    long e_cores  = get_int("hw.perflevel1.logicalcpu");
    long nlevels  = get_int("hw.nperflevels");

    line("logical CPUs (hw.logicalcpu)", logical, "");
    line("physical cores (hw.physicalcpu)", physical, "");
    line("performance levels", nlevels, "");
    line("  performance cores (perflevel0)", p_cores, "");
    line("  efficiency cores  (perflevel1)", e_cores, "");
    printf("\n");
    line("cache line (hw.cachelinesize)", get_int("hw.cachelinesize"), "bytes");
    line("L1 data cache (hw.l1dcachesize)", get_int("hw.l1dcachesize") / 1024, "KB");
    line("L1 instr cache (hw.l1icachesize)", get_int("hw.l1icachesize") / 1024, "KB");
    line("L2 cache (hw.l2cachesize)", get_int("hw.l2cachesize") / 1024, "KB");
    line("page size (hw.pagesize)", get_int("hw.pagesize"), "bytes");
    long mem = get_int("hw.memsize");
    line("physical memory (hw.memsize)", mem > 0 ? mem / (1024*1024*1024) : -1, "GB");

    printf("\nObservations\n------------\n");
    if (p_cores > 0 && e_cores > 0) {
        printf("- This CPU is HETEROGENEOUS: %ld performance cores and %ld\n",
               p_cores, e_cores);
        printf("  efficiency cores, %ld in total. They are NOT interchangeable,\n",
               logical);
        printf("  so perfect %ldx speedup is impossible even in principle: once\n",
               logical);
        printf("  the %ld fast cores are busy, extra threads land on slower ones.\n",
               p_cores);
        printf("  Expect the speedup curve in demo 01 to bend near %ld threads.\n",
               p_cores);
    } else {
        printf("- This CPU reports a single performance level: all %ld cores are\n",
               logical);
        printf("  equivalent, so speedup should scale smoothly up to %ld.\n", logical);
    }
    printf("- The cache line is %ld bytes. That is the unit of coherence, and\n",
           get_int("hw.cachelinesize"));
    printf("  therefore the unit of FALSE SHARING (demo 02): two variables in\n");
    printf("  the same %ld-byte line contend even if no thread shares a variable.\n",
           get_int("hw.cachelinesize"));
    printf("  Note it is %ld, not the 64 bytes most textbooks assume -- so the\n",
           get_int("hw.cachelinesize"));
    printf("  padding needed here is twice the usual figure.\n");
    printf("- physicalcpu == logicalcpu means NO hyper-threading/SMT on this\n");
    printf("  machine: one hardware thread per core. On an SMT machine (most\n");
    printf("  x86 servers) logicalcpu is 2x physicalcpu, and two threads on one\n");
    printf("  core share its functional units -- so they do not scale like two\n");
    printf("  independent cores either.\n");
#else
    printf("This demo reads macOS sysctl values. On Linux, use:\n");
    printf("  lscpu                 cores, sockets, caches, SMT\n");
    printf("  cat /proc/cpuinfo     per-CPU detail\n");
    printf("  getconf LEVEL1_DCACHE_LINESIZE    the cache line size\n");
#endif
    return 0;
}
