#include "vm/swap_hack.h" #include "threads/palloc.h" #include "threads/vaddr.h" #include #include struct swap_info { void * start; struct bitmap *map; struct lock lock; int numslots; }; static struct swap_info swap_info; void swaphack_init(int numslots) { lock_init (&swap_info.lock); swap_info.map = bitmap_create (numslots); if (swap_info.map == NULL) { PANIC ("Failure creating bitmap for swap"); } swap_info.start = palloc_get_multiple (PAL_ASSERT, numslots); swap_info.numslots = numslots; } /* Swapspace -> Physical Memory This function copies page size bytes from the logical swap slot given by swapslot into the page fram starting at page aligned kaddr. Returns true on success and false on failure. */ bool swaphack_slot2frame (int slot, void * kaddr) { bool success = false; char * slotstart; if (slot < 0 || slot >= swap_info.numslots) { printf ("slot out of range\n"); return success; } if (!bitmap_test (swap_info.map, slot)) { printf ("slot not set in bitmap\n"); return success; } if ((unsigned)kaddr & PGMASK != 0) { printf ("addr not aligned\n"); return success; } slotstart = (char *)swap_info.start + (slot << PGBITS); memcpy((char *)kaddr, slotstart, PGSIZE); return true; } int swaphack_frame2slot (void *kaddr) { lock_acquire (&swap_info.lock); int slot = bitmap_scan_and_flip(swap_info.map, 0, 1, false); lock_release (&swap_info.lock); if ((unsigned)slot == BITMAP_ERROR) { return -1; } char * slotstart = (char *)swap_info.start + (slot << PGBITS); memcpy (slotstart, (char *)kaddr, PGSIZE); return slot; } bool swaphack_release_slot (int slot) { if (slot < 0 || slot > swap_info.numslots) return false; lock_acquire (&swap_info.lock); if (!bitmap_test (swap_info.map, slot)) { lock_release (&swap_info.lock); return false; } bitmap_reset(swap_info.map, slot); lock_release (&swap_info.lock); return true; }