From d9a8b964ed35f407d60f28e29a2488886ceed5ff Mon Sep 17 00:00:00 2001 From: Ruslan Isaev Date: Thu, 27 Mar 2025 18:59:35 +0300 Subject: [PATCH] paging: with the huge help from grok, finished paging --- Makefile | 1 + include/paging.h | 7 +- src/kernel.c | 45 ++++- src/paging.c | 483 +++++++++++++++++++++++++++++++++++++++++++---- 4 files changed, 492 insertions(+), 44 deletions(-) diff --git a/Makefile b/Makefile index 9fa9449..091b454 100644 --- a/Makefile +++ b/Makefile @@ -46,6 +46,7 @@ image: test: qemu-system-i386 -drive file=boot.iso,media=disk,format=raw -m 512M -d int + #qemu-system-i386 -s -S -kernel myos.bin test-bochs: bochs -f bochsrc diff --git a/include/paging.h b/include/paging.h index 2c0583e..4a68149 100644 --- a/include/paging.h +++ b/include/paging.h @@ -1,6 +1,11 @@ #ifndef PAGING_H #define PAGING_H +#include void paging_init(); - +void heap_init(); +void* heap_alloc(uint32_t size); +void heap_free(void *ptr); +void test_paging(); +void init_allocator(); #endif diff --git a/src/kernel.c b/src/kernel.c index bb1f144..dbe8272 100644 --- a/src/kernel.c +++ b/src/kernel.c @@ -90,7 +90,18 @@ void file_fuckery() printf("%X\n", err); err = ls("/ebalo"); - err = fat_mkdir("/ebalo/numbers/"); + printf("\n\n\n"); + err = fat_mkdir("/ebalo/numbers"); + err = fat_mkdir("/ebalo/numbers/nigga"); + printf("MKDIR ERR: %X\n", err); + + err = fat_unlink("/ebalo/numbers/nigga/"); + printf("UNLINK ERR: %X\n", err); + + err = fat_unlink("/ebalo/numbers/"); + printf("UNLINK ERR: %X\n", err); + + /*err = fat_mkdir("/ebalo/numbers"); //err = cat("/ebalo/boot/grub/grub.cfg"); char *filenames[] = {"/ebalo/numbers/d","/ebalo/numbers/e"}; for(int i = 0; i < 2; i++){ @@ -98,21 +109,20 @@ void file_fuckery() file_t file; err = fat_fopen(&file, filenames[i], "w"); if (err) - printf("1 err %X", err); goto unmount; + {printf("1 err %X\n", err); goto unmount;} for (int i = 0; i < 10; i++) { cnt = fat_fprintf(&file, "This is test number %d\n", i); if (cnt < 0) - printf("2 cnt: %X", cnt); goto unmount; + {printf("2 cnt: %X\n", cnt); goto unmount;} } err = fat_fclose(&file); } - +*/ unmount: - return; - printf("err%X", err); + printf("err%X\n", err); err = fat_umount(&g_fat); test(err, "unmount"); } @@ -135,6 +145,11 @@ void kmain() apply_pic_masks(); paging_init(); + printf("paging_init done\n"); + test_paging(); + init_allocator(); + heap_init(); + printf("after heap_init\n"); __asm__ __volatile__ ("sti"); printf("Kernel init sequence completed\n"); @@ -145,7 +160,23 @@ void kmain() get_disk_info(&info); printf("CYL HEAD SECT: %X %X %X\n", info.cylinders, info.heads, info.sectors); - file_fuckery(); + //file_fuckery(); + + char *huy; + char *huy2; + char temp1[1024] = "rusya_krutoy"; + char temp2[1024] = "katya_tozhe_krutaya"; + + huy = heap_alloc(1024); + huy2 = heap_alloc(1024); + + memcpy(huy, temp1, sizeof(temp1)); + memcpy(huy2, temp2, sizeof(temp1)); + + printf("huy1 address: 0x%X huy2 address:0x%X\n", &huy, &huy2); + printf("huy1 points to: 0x%X huy2 points to:0x%X\n", huy, huy2); + printf("huy1: %s\nhuy2: %s", huy, huy2); + while(1) { /* if(inportb(0x64) & 0x1) diff --git a/src/paging.c b/src/paging.c index cb2cee4..6bf1672 100644 --- a/src/paging.c +++ b/src/paging.c @@ -1,36 +1,139 @@ #include "../include/paging.h" #include +#include "../include/stdio.h" -extern void loadPageDirectory(unsigned int*); -extern void enablePaging(); +//extern void loadPageDirectory(unsigned int*); +//extern void enablePaging(); -uint32_t page_directory[1024] __attribute__((aligned(4096))); -uint32_t first_page_table[1024] __attribute__((aligned(4096))); +void enablePaging1() { + asm volatile ( + "mov %%cr0, %%eax\n" + "or $0x80000000, %%eax\n" + "mov %%eax, %%cr0\n" + "jmp 1f\n" + "1:\n" + "mov %%cr3, %%eax\n" // Перезагрузка CR3 для сброса TLB + "mov %%eax, %%cr3\n" + "nop\n" + : + : + : "eax", "memory" + ); +} +void loadPageDirectory1(uint32_t* page_directory) { + asm volatile ( + "mov %0, %%cr3\n" // Загружаем физический адрес каталога страниц в CR3 + : // Нет выходных операндов + : "r" (page_directory) // Входной операнд — адрес каталога + : // Нет изменяемых регистров + ); +} + +uint32_t kernel_page_directory[1024] __attribute__((aligned(4096))); +uint32_t kernel_page_table[1024] __attribute__((aligned(4096))); + +// 16 МБ = 16 * 1024 * 1024 байт = 4096 страниц (по 4 КБ) +// 4096 бит = 512 байт +uint8_t page_bitmap[512]; // 1 бит на страницу + +/** +page_bitmap — массив, где каждый бит соответствует странице (0 = свободна, 1 = занята). +init_allocator помечает первые 4 МБ как занятые (там ядро). +alloc_page ищет первый свободный бит и возвращает адрес страницы. +free_page освобождает страницу, сбрасывая бит. +**/ + +void init_allocator() { + int i; + // Помечаем все страницы как свободные (0) + for (i = 0; i < 512; i++) { + page_bitmap[i] = 0; + } + // Первые 4 МБ уже заняты ядром (0x00000000–0x003FFFFF) + for (i = 0; i < 1024 / 8; i++) { // 1024 страницы = 128 байт + page_bitmap[i] = 0xFF; // Все биты = 1 (занято) + } +} + +// Выделяем свободную страницу +void* alloc_page() { + printf("alloc_page called\n"); + int i, j; + for (i = 0; i < 512; i++) { + if (page_bitmap[i] != 0xFF) { + for (j = 0; j < 8; j++) { + if (!(page_bitmap[i] & (1 << j))) { + page_bitmap[i] |= (1 << j); + return (void*)(((i * 8) + j) * 0x1000); + } + } + } + } + printf("no bitches? no free pages?\n"); + return (void*)0; // Нет свободных страниц +} + +void test_paging() { + uint32_t* pd = (uint32_t*)0xFFFFF000; + uint32_t expected = (uint32_t)kernel_page_table | 0x3; + // Игнорируем дополнительные флаги, проверяем только базовый адрес и present + if ((pd[0] & ~0xFFF) == (expected & ~0xFFF)) { + // Успех + } else { + printf("RECURSION BROKEN!!\n"); + printf("pd[0] = 0x%X\n"); + printf("(uint32_t)first_page_table | 0x3 = %X", (uint32_t)kernel_page_table | 0x3); + while (1); // Рекурсия сломана + } +} + +// Освобождаем страницу +void free_page(void *physaddr) { + uint32_t page_num = (uint32_t)physaddr / 0x1000; + uint32_t byte_idx = page_num / 8; + uint32_t bit_idx = page_num % 8; + page_bitmap[byte_idx] &= ~(1 << bit_idx); // Сбрасываем бит +} + +/** +Теперь первые 4 МБ физической памяти отображаются на виртуальный адрес 0xC0000000 (3 ГБ), а не на 0x00000000. +Это оставляет нижние 3 ГБ (0x00000000–0xBFFFFFFF) свободными для пользовательских процессов. +**/ void paging_init() { - //set each entry to not present int i; - for(i = 0; i < 1024; i++) - { - // This sets the following flags to the pages: - // Supervisor: Only kernel-mode can access them - // Write Enabled: It can be both read from and written to - // Not Present: The page table is not present - page_directory[i] = 0x00000002; - } - //we will fill all 1024 entries in the table, mapping 4 megabytes - for(i = 0; i < 1024; i++) - { - // As the address is page aligned, it will always leave 12 bits zeroed. - // Those bits are used by the attributes ;) - first_page_table[i] = (i * 0x1000) | 3; // attributes: supervisor level, read/write, present. - } - page_directory[0] = ((unsigned int)first_page_table) | 3; + // Проверяем физические адреса + uint32_t pd_phys = (uint32_t)kernel_page_directory; + uint32_t pt_phys = (uint32_t)kernel_page_table; - loadPageDirectory(page_directory); - enablePaging(); + if (pd_phys & 0xFFF || pt_phys & 0xFFF) { + while (1); // Ошибка выравнивания + } + + // Заполняем каталог страниц + for (i = 0; i < 1024; i++) { + kernel_page_directory[i] = 0x00000002; // not present + } + + // Identity mapping для 0x00000000–0x003FFFFF + for (i = 0; i < 1024; i++) { + kernel_page_table[i] = (i * 0x1000) | 0x3; // supervisor, present + } + kernel_page_directory[0] = pt_phys | 0x3; + + // Рекурсивное отображение + kernel_page_directory[1023] = pd_phys | 0x3; + + // Проверяем перед загрузкой + if (kernel_page_directory[0] != (pt_phys | 0x3) || + kernel_page_directory[1023] != (pd_phys | 0x3)) { + printf("OSHIBKA ZAPISI BLYA\n"); + while (1); // Ошибка записи + } + loadPageDirectory1(kernel_page_directory); + enablePaging1(); } void *get_physaddr(void *virtualaddr) { @@ -46,23 +149,331 @@ void *get_physaddr(void *virtualaddr) { return (void *)((pt[ptindex] & ~0xFFF) + ((unsigned long)virtualaddr & 0xFFF)); } +/** +Проверяем, существует ли таблица страниц (бит present в записи каталога). +Используем invlpg (inline assembly) для сброса TLB, чтобы процессор увидел изменения. +Пока вместо выделения новой таблицы страниц я добавил бесконечный цикл (while(1)). Позже мы заменим это аллокатором. +**/ + void map_page(void *physaddr, void *virtualaddr, unsigned int flags) { - // Make sure that both addresses are page-aligned. + // Убеждаемся, что адреса выровнены по 4 КБ + uint32_t phys = (uint32_t)physaddr & ~0xFFF; // Обнуляем младшие 12 бит + uint32_t virt = (uint32_t)virtualaddr & ~0xFFF; - unsigned long pdindex = (unsigned long)virtualaddr >> 22; - unsigned long ptindex = (unsigned long)virtualaddr >> 12 & 0x03FF; + // Вычисляем индексы + uint32_t pdindex = virt >> 22; // Индекс в каталоге страниц + uint32_t ptindex = (virt >> 12) & 0x3FF; // Индекс в таблице страниц - unsigned long *pd = (unsigned long *)0xFFFFF000; - // Here you need to check whether the PD entry is present. - // When it is not present, you need to create a new empty PT and - // adjust the PDE accordingly. + uint32_t *pd = (uint32_t *)0xFFFFF000; // Адрес каталога страниц в виртуальной памяти - unsigned long *pt = ((unsigned long *)0xFFC00000) + (0x400 * pdindex); - // Here you need to check whether the PT entry is present. - // When it is, then there is already a mapping present. What do you do now? + // Проверяем, существует ли таблица страниц + if (!(pd[pdindex] & 0x1)) { // Бит 0 — "present" + // Если таблицы нет, создаём новую (для простоты пока паникуем) + void *new_pt = alloc_page(); + if (!new_pt) while (1); // Нет памяти + pd[pdindex] = (uint32_t)new_pt | 0x3; // present, writable - pt[ptindex] = ((unsigned long)physaddr) | (flags & 0xFFF) | 0x01; // Present + // Очищаем новую таблицу + uint32_t *pt = ((uint32_t *)0xFFC00000) + (0x400 * pdindex); + for (int i = 0; i < 1024; i++) { + pt[i] = 0; // Все страницы "не присутствуют" + } + } - // Now you need to flush the entry in the TLB - // or you might not notice the change. + // Получаем адрес таблицы страниц + uint32_t *pt = ((uint32_t *)0xFFC00000) + (0x400 * pdindex); + + // Устанавливаем отображение + pt[ptindex] = phys | (flags & 0xFFF) | 0x1; // Флаги + present + + // Сбрасываем TLB для этого адреса + asm volatile("invlpg (%0)" : : "r" (virtualaddr) : "memory"); } + +//map_kernel_page((void*)0xC0100000, 0x2); — отобразит страницу в ядре. +void map_kernel_page(void* virtualaddr, unsigned int flags) { + uint32_t virt = (uint32_t)virtualaddr & ~0xFFF; // Выравниваем по 4 КБ + if (virt < 0xC0000000) while(1); // Ошибка: ядро только выше 3 ГБ + + uint32_t pdindex = virt >> 22; // Индекс в каталоге (для 0xD0000000 это 832) + uint32_t ptindex = (virt >> 12) & 0x3FF; // Индекс в таблице страниц + + uint32_t* pd = (uint32_t*)0xFFFFF000; // Каталог страниц + + // Проверяем, существует ли таблица страниц + if (!(pd[pdindex] & 0x1)) { + void* new_pt = alloc_page(); + if (!new_pt) while(1); // Нет памяти + + // Используем рекурсивное отображение для доступа к новой таблице + pd[pdindex] = ((uint32_t)new_pt) | 0x3; // Временно записываем в каталог + uint32_t* pt = ((uint32_t*)0xFFC00000) + (0x400 * pdindex); + + // Очищаем таблицу через виртуальный адрес + for (int i = 0; i < 1024; i++) { + pt[i] = 0; + } + } + + // Получаем таблицу страниц + uint32_t* pt = ((uint32_t*)0xFFC00000) + (0x400 * pdindex); + void* phys = alloc_page(); + if (!phys) while(1); + + pt[ptindex] = (uint32_t)phys | (flags & 0xFFF) | 0x1; // supervisor, present + asm volatile("invlpg (%0)" : : "r" (virtualaddr) : "memory"); +} + +/** +Dalshe idyot to chto napisal grok dlya processov v buduschem +**/ +/* +// Структура для процесса +typedef struct { + uint32_t page_directory[1024] __attribute__((aligned(4096))); // Каталог страниц процесса + uint32_t pid; // ID процесса (для примера) +} Process; + +// Создание нового процесса +//Создаёт новый каталог страниц для процесса, копируя ядро (768–1023 записи) и оставляя нижние 3 ГБ пустыми. +Process* create_process(uint32_t pid) { + Process* proc = (Process*)alloc_page(); // Выделяем страницу под структуру + if (!proc) return (Process*)0; // Нет памяти + + int i; + // Копируем каталог ядра в каталог процесса + for (i = 0; i < 1024; i++) { + proc->page_directory[i] = kernel_page_directory[i]; + } + + // Нижние 3 ГБ (0-767) изначально пустые + for (i = 0; i < 768; i++) { + proc->page_directory[i] = 0x00000002; // not present + } + + proc->pid = pid; + return proc; +} + +// Переключение на процесс +//Переключает процессор на каталог страниц процесса. +void switch_to_process(Process* proc) { + loadPageDirectory(proc->page_directory); +} + +//Выделяет страницу в пользовательском пространстве (ниже 0xC0000000) с флагами user-level (бит 2 = 1). +void map_user_page(Process* proc, void* virtualaddr, unsigned int flags) { + uint32_t virt = (uint32_t)virtualaddr & ~0xFFF; + if (virt >= 0xC0000000) while(1); // Ошибка: пользователь не может трогать ядро! + + uint32_t pdindex = virt >> 22; + uint32_t ptindex = (virt >> 12) & 0x3FF; + + // Проверяем, есть ли таблица страниц + if (!(proc->page_directory[pdindex] & 0x1)) { + void* new_pt = alloc_page(); + if (!new_pt) while(1); // Нет памяти + + // Новая таблица: user, writable, present (0x7 = 111b) + proc->page_directory[pdindex] = ((uint32_t)new_pt) | 0x7; + + // Очищаем таблицу + uint32_t* pt = (uint32_t*)new_pt; + for (int i = 0; i < 1024; i++) { + pt[i] = 0; // Все страницы "не присутствуют" + } + } + + // Получаем таблицу страниц + uint32_t* pt = (uint32_t*)(proc->page_directory[pdindex] & ~0xFFF); + void* phys = alloc_page(); + if (!phys) while(1); // Нет памяти + + // Отображаем страницу: user, flags, present + pt[ptindex] = (uint32_t)phys | (flags & 0xFFF) | 0x5; // 0x5 = 101b (present, user) + + // Сбрасываем TLB + asm volatile("invlpg (%0)" : : "r" (virtualaddr) : "memory"); +} + +// Пример использования +void test_process() { + Process* proc = create_process(1); // Создаём процесс с PID 1 + map_user_page(proc, (void*)0x1000, 0x6); // Отображаем страницу на 0x1000 (writable, user) + switch_to_process(proc); // Переключаемся на процесс +} +*/ + +// Структура заголовка блока памяти +typedef struct Block { + uint32_t size; // Размер блока (в байтах, включая заголовок) + uint32_t is_free; // 1 = свободен, 0 = занят + struct Block* next; // Указатель на следующий блок +} Block; + +// Структура для управления кучей +typedef struct { + void* start; // Начало кучи + uint32_t size; // Текущий размер кучи в байтах + Block* first; // Первый блок в куче +} Heap; + +Heap kernel_heap; + +void heap_init() { + kernel_heap.start = (void*)0xD0000000; // Начало кучи в ядре + kernel_heap.size = 0x1000; // Начальный размер — 1 страница (4 КБ) + printf("before map_kernel_page\n"); + // Отображаем первую страницу + map_kernel_page(kernel_heap.start, 0x2); // writable, supervisor + printf("after map_kernel_page\n"); + // Создаём первый блок, который занимает всю страницу + Block* initial_block = (Block*)kernel_heap.start; + initial_block->size = 0x1000 - sizeof(Block); // Размер без учёта заголовка + initial_block->is_free = 1; // Свободен + initial_block->next = (Block*)0; // Пока нет следующего + + kernel_heap.first = initial_block; +} + +// Выделение памяти из кучи +//Ищет свободный блок подходящего размера. Если блок большой, делит его. +//Если свободных блоков нет, добавляет страницу. +void* heap_alloc(uint32_t size) { + // Выравниваем размер до 4 байт + size = (size + 3) & ~3; + + Block* current = kernel_heap.first; + Block* prev = (Block*)0; + + // Ищем подходящий свободный блок + while (current) { + if (current->is_free && current->size >= size) { + // Нашли блок + if (current->size >= size + sizeof(Block) + 4) { + // Разделяем блок, если он слишком большой + Block* new_block = (Block*)((uint32_t)current + sizeof(Block) + size); + new_block->size = current->size - size - sizeof(Block); + new_block->is_free = 1; + new_block->next = current->next; + + current->size = size; + current->next = new_block; + } + current->is_free = 0; + return (void*)((uint32_t)current + sizeof(Block)); // Возвращаем адрес после заголовка + } + prev = current; + current = current->next; + } + // Нет свободного блока — добавляем новую страницу + void* new_page = (void*)((uint32_t)kernel_heap.start + kernel_heap.size); + map_kernel_page(new_page, 0x2); + kernel_heap.size += 0x1000; + + Block* new_block = (Block*)new_page; + new_block->size = 0x1000 - sizeof(Block); + new_block->is_free = 1; + new_block->next = (Block*)0; + + if (prev) prev->next = new_block; + + // Рекурсивно вызываем, чтобы выделить из нового блока + return heap_alloc(size); +} + +// Освобождение памяти +//Помечает блок как свободный и пытается объединить его с соседними свободными блоками, +//чтобы уменьшить фрагментацию. +void heap_free(void* ptr) { + if (!ptr || (uint32_t)ptr < (uint32_t)kernel_heap.start) return; + + // Находим блок по указателю (указатель указывает после заголовка) + Block* block = (Block*)((uint32_t)ptr - sizeof(Block)); + block->is_free = 1; + + // Слияние с предыдущим блоком, если он свободен + Block* current = kernel_heap.first; + Block* prev = (Block*)0; + while (current && current != block) { + prev = current; + current = current->next; + } + if (prev && prev->is_free) { + prev->size += sizeof(Block) + block->size; + prev->next = block->next; + block = prev; + } + + // Слияние с следующим блоком, если он свободен + if (block->next && block->next->is_free) { + block->size += sizeof(Block) + block->next->size; + block->next = block->next->next; + } +} + + +// Функция проверки страниц +void test_pages() { + // Тест 1: Проверка ядра + void* kernel_addr = (void*)0xC0100000; + map_kernel_page(kernel_addr, 0x2); // writable, supervisor + + // Записываем значение в страницу + uint32_t* kernel_ptr = (uint32_t*)kernel_addr; + *kernel_ptr = 0xDEADBEEF; + + // Проверяем, что значение записалось + if (*kernel_ptr == 0xDEADBEEF) { + // Успех! (в реальной ОС тут можно вывести сообщение через UART или VGA) + } else { + while (1); // Ошибка + } + /* + // Тест 2: Проверка пользовательского процесса + Process* proc = create_process(1); // Создаём процесс + void* user_addr = (void*)0x1000; + map_user_page(proc, user_addr, 0x6); // writable, user + + // Переключаемся на процесс + switch_to_process(proc); + + // Записываем значение + uint32_t* user_ptr = (uint32_t*)user_addr; + *user_ptr = 0xCAFEBABE; + + // Проверяем + if (*user_ptr == 0xCAFEBABE) { + // Успех! + } else { + while (1); // Ошибка + } + + // Возвращаемся в ядро + switch_to_process((Process*)0); // Предполагаем, что 0 вернёт нас к kernel_page_directory + */ + // Тест 3: Проверка кучи + heap_init(); + void* heap_ptr1 = heap_alloc(16); + uint32_t* heap_data1 = (uint32_t*)heap_ptr1; + *heap_data1 = 0x12345678; + + void* heap_ptr2 = heap_alloc(200); + uint32_t* heap_data2 = (uint32_t*)heap_ptr2; + *heap_data2 = 0x87654321; + + heap_free(heap_ptr1); + void* heap_ptr3 = heap_alloc(12); // Должно взять место ptr1 + + if (*heap_data1 == 0x12345678 && *heap_data2 == 0x87654321 && + heap_ptr3 == heap_ptr1) { + // Успех! + } else { + while (1); // Ошибка + } +} +/** +0xD0000000: Произвольный адрес в ядре (выше 0xC0000000), выбран для кучи, чтобы не пересекаться с другими данными. +0xFFFFF000: Виртуальный адрес каталога страниц благодаря рекурсивному отображению (последняя запись указывает на себя). +0xFFC00000: Начало области, где лежат все таблицы страниц, доступные через рекурсию. +**/