| 1 | #include <stddef.h> |
| 2 | #include <stdint.h> |
| 3 | #include <stdbool.h> |
| 4 | #include <mm/pmm.h> |
| 5 | #include <lib/rand.h> |
| 6 | #include <lib/print.h> |
| 7 | #include <lib/misc.h> |
| 8 | |
| 9 | static bool full_overlap_check(uint64_t base1, uint64_t top1, |
| 10 | uint64_t base2, uint64_t top2) { |
| 11 | return ((base1 >= base2 && base1 < top2) |
| 12 | && (top1 > base2 && top1 <= top2)); |
| 13 | } |
| 14 | |
| 15 | bool check_usable_memory(uint64_t base, uint64_t top) { |
| 16 | uint64_t overlap_remaining = top - base; |
| 17 | |
| 18 | for (size_t i = 0; i < memmap_entries; i++) { |
| 19 | if (memmap[i].type != MEMMAP_USABLE |
| 20 | #if defined (UEFI) |
| 21 | && memmap[i].type != MEMMAP_EFI_RECLAIMABLE |
| 22 | #endif |
| 23 | && memmap[i].type != MEMMAP_BOOTLOADER_RECLAIMABLE |
| 24 | && memmap[i].type != MEMMAP_KERNEL_AND_MODULES) { |
| 25 | continue; |
| 26 | } |
| 27 | |
| 28 | uint64_t memmap_top = CHECKED_ADD(memmap[i].base, memmap[i].length, continue); |
| 29 | |
| 30 | if (full_overlap_check(base, top, memmap[i].base, memmap_top)) { |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | // Count how many bytes from a real-RAM entry overlap our range |
| 35 | if (memmap[i].base < top && memmap_top > base) { |
| 36 | uint64_t overlap_bottom = memmap[i].base > base ? memmap[i].base : base; |
| 37 | uint64_t overlap_top = memmap_top < top ? memmap_top : top; |
| 38 | |
| 39 | uint64_t overlap_size = overlap_top - overlap_bottom; |
| 40 | overlap_remaining -= overlap_size; |
| 41 | |
| 42 | if (overlap_remaining == 0) { |
| 43 | return true; |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | return false; |
| 49 | } |
| 50 | |
| 51 | void pmm_randomise_memory(void) { |
| 52 | print("pmm: Randomising memory contents..."); |
| 53 | |
| 54 | for (size_t i = 0; i < memmap_entries; i++) { |
| 55 | if (memmap[i].type != MEMMAP_USABLE) |
| 56 | continue; |
| 57 | |
| 58 | #if defined (BIOS) |
| 59 | // We're not going to randomise memory above 4GiB from protected mode, |
| 60 | // are we? |
| 61 | if (memmap[i].base >= 0x100000000) { |
| 62 | continue; |
| 63 | } |
| 64 | #endif |
| 65 | |
| 66 | uint8_t *ptr = (void *)(uintptr_t)memmap[i].base; |
| 67 | size_t len = memmap[i].length; |
| 68 | |
| 69 | for (size_t j = 0;;) { |
| 70 | uint32_t random = rand32(); |
| 71 | uint8_t *rnd_data = (void *)&random; |
| 72 | if (j >= len) |
| 73 | break; |
| 74 | ptr[j++] = rnd_data[0]; |
| 75 | if (j >= len) |
| 76 | break; |
| 77 | ptr[j++] = rnd_data[1]; |
| 78 | if (j >= len) |
| 79 | break; |
| 80 | ptr[j++] = rnd_data[2]; |
| 81 | if (j >= len) |
| 82 | break; |
| 83 | ptr[j++] = rnd_data[3]; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | print("\n"); |
| 88 | } |