"""
01_fragmentation.py -- why free memory is not the same as usable memory
========================================================================

[Questions this demo answers]
  - malloc must track block sizes and alignment, so a block is bigger than the
    payload. How much is lost to INTERNAL fragmentation?
  - Even with plenty of free bytes, a request can fail because no single free
    block is big enough -- EXTERNAL fragmentation. How does it build up?
  - The placement policy (first / next / best fit) trades speed for
    fragmentation. What does each cost on a workload?

[How to run]
  python3 01_fragmentation.py

[How to read the output]
  PART A allocates several small payloads and shows the per-block overhead
  (header, footer, alignment) that is internal fragmentation. PART B builds a
  checkerboard of freed blocks and shows a large request failing despite ample
  free bytes. PART C runs the same allocation/free workload under each
  placement policy and reports peak utilization and search cost.

[About this tool]  heap.py is a teaching allocator (Python, see its header),
  not the malloclab C deliverable.

[Systems link / CS:APP 9.9]
  An allocator's two goals -- throughput and memory utilization -- are in
  tension, and fragmentation is why utilization is never 100%. Internal
  fragmentation is per-block bookkeeping and rounding; external is the free
  space scattered into pieces too small to use.
"""

import heap


def part_a():
    print("PART A: internal fragmentation -- a block is bigger than its payload")
    h = heap.Heap(4096)
    print("  overhead per block: %d-byte header + %d-byte footer; payload aligned to %d\n"
          % (heap.HDR, heap.FTR, heap.ALIGN))
    print("  %-10s %-12s %-12s %s" % ("request", "block size", "wasted", "why"))
    for need in (1, 16, 17, 40, 100):
        h2 = heap.Heap(4096)
        h2.malloc(need)
        blk = h2.blocks[0].size
        waste = blk - need
        why = "%d hdr+ftr + %d align/min" % (heap.HDR + heap.FTR, waste - (heap.HDR + heap.FTR))
        print("  %-10d %-12d %-12d %s" % (need, blk, waste, why))
    print("  Every block pays header+footer and rounds its payload up to 16 bytes,")
    print("  so tiny allocations waste a large fraction -- internal fragmentation.\n")


def part_b():
    print("PART B: external fragmentation -- free bytes you cannot use")
    h = heap.Heap(1024)
    # Fill the heap with small blocks, then free every other one: a checkerboard.
    ptrs = []
    while True:
        p = h.malloc(48)
        if p is None:
            break
        ptrs.append(p)
    print("  filled the 1024-byte heap with %d blocks of payload 48" % len(ptrs))
    for i in range(0, len(ptrs), 2):        # free every other block
        h.free(ptrs[i])
    freed = sum(1 for i in range(0, len(ptrs), 2))
    print("  freed every other block (%d of them): %d free bytes total, but the" % (freed, h.free_bytes()))
    print("  largest single free block is only %d bytes." % h.largest_free())
    big = h.malloc(200)
    print("  malloc(200) -> %s, even though %d bytes are free: the free space is"
          % ("FAILED" if big is None else "ok", h.free_bytes()))
    print("  shattered into many small gaps. That is external fragmentation.")
    print("  " + h.dump() + "\n")


def workload(h, seed=15213, rounds=400):
    """Run a mixed alloc/free workload on h. [Returns] (peak utilization,
    number of malloc calls). h.search_steps then holds the total blocks scanned."""
    import random
    rng = random.Random(seed)
    live, peak, nmalloc = [], 0.0, 0
    h.fails = 0
    for _ in range(rounds):
        if live and rng.random() < 0.42:
            h.free(live.pop(rng.randrange(len(live))))
        else:
            p = h.malloc(rng.choice([16, 24, 48, 64, 120, 200, 400]))
            if p is not None:
                live.append(p)
            else:
                h.fails += 1
            nmalloc += 1
        peak = max(peak, h.utilization())
    return peak, nmalloc


def part_c():
    print("PART C: placement policy -- mostly a SPEED difference")
    print("  Same seeded workload under pressure (a 2 KiB heap, allocation-heavy):\n")
    print("  %-10s %-14s %-16s %s" % ("policy", "peak util.", "failed mallocs", "steps / malloc"))
    for fit in ("first", "next", "best"):
        h = heap.Heap(2048, fit)
        peak, nmalloc = workload(h, rounds=1200)
        print("  %-10s %-14.2f %-16d %.1f" % (fit, peak, h.fails, h.search_steps / nmalloc))
    print("\n  On this workload all three reach similar utilization and failure counts;")
    print("  what differs sharply is SEARCH COST: best fit scans the whole list every")
    print("  time (worst throughput) for little packing gain, next fit scans least")
    print("  (it resumes where it left off), first fit is in between. This is why real")
    print("  allocators avoid best fit and instead make the SEARCH cheap -- segregated")
    print("  free lists, Lecture 14 -- rather than chasing the best fit.\n")


def main():
    print("=== Demo 01: fragmentation and placement ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * Internal fragmentation = per-block overhead + alignment + rounding; it is")
    print("    paid on every block and hurts most for small allocations.")
    print("  * External fragmentation = free bytes split into pieces too small to use; a")
    print("    request can fail with ample total free space.")
    print("  * Placement policy is mostly a THROUGHPUT choice: best fit scans the whole")
    print("    free list for little packing gain, so real allocators make the search")
    print("    cheap (segregated lists, Lecture 14) instead of hunting the best fit.")


if __name__ == "__main__":
    main()
