mm.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. #include "mm.h"
  2. #include "slab.h"
  3. #include <common/printk.h>
  4. #include <common/kprint.h>
  5. #include <driver/multiboot2/multiboot2.h>
  6. #include <process/process.h>
  7. #include <common/compiler.h>
  8. #include <common/errno.h>
  9. #include <debug/traceback/traceback.h>
  10. static ul Total_Memory = 0;
  11. static ul total_2M_pages = 0;
  12. static ul root_page_table_phys_addr = 0; // 内核层根页表的物理地址
  13. /**
  14. * @brief 虚拟地址长度所需要的entry数量
  15. *
  16. */
  17. typedef struct
  18. {
  19. int64_t num_PML4E;
  20. int64_t num_PDPTE;
  21. int64_t num_PDE;
  22. int64_t num_PTE;
  23. } mm_pgt_entry_num_t;
  24. /**
  25. * @brief 计算虚拟地址长度对应的页表entry数量
  26. *
  27. * @param length 长度
  28. * @param ent 返回的entry数量结构体
  29. */
  30. static void mm_calculate_entry_num(uint64_t length, mm_pgt_entry_num_t *ent)
  31. {
  32. if (ent == NULL)
  33. return;
  34. ent->num_PML4E = (length + (1UL << PAGE_GDT_SHIFT) - 1) >> PAGE_GDT_SHIFT;
  35. ent->num_PDPTE = (length + PAGE_1G_SIZE - 1) >> PAGE_1G_SHIFT;
  36. ent->num_PDE = (length + PAGE_2M_SIZE - 1) >> PAGE_2M_SHIFT;
  37. ent->num_PTE = (length + PAGE_4K_SIZE - 1) >> PAGE_4K_SHIFT;
  38. }
  39. /**
  40. * @brief 从页表中获取pdt页表项的内容
  41. *
  42. * @param proc_page_table_addr 页表的地址
  43. * @param is_phys 页表地址是否为物理地址
  44. * @param virt_addr_start 要清除的虚拟地址的起始地址
  45. * @param length 要清除的区域的长度
  46. * @param clear 是否清除标志位
  47. */
  48. uint64_t mm_get_PDE(ul proc_page_table_addr, bool is_phys, ul virt_addr, bool clear);
  49. /**
  50. * @brief 检查页表是否存在不为0的页表项
  51. *
  52. * @param ptr 页表基指针
  53. * @return int8_t 存在 -> 1
  54. * 不存在 -> 0
  55. */
  56. int8_t mm_check_page_table(uint64_t *ptr)
  57. {
  58. for (int i = 0; i < 512; ++i, ++ptr)
  59. {
  60. if (*ptr != 0)
  61. return 1;
  62. }
  63. return 0;
  64. }
  65. void mm_init()
  66. {
  67. kinfo("Initializing memory management unit...");
  68. // 设置内核程序不同部分的起止地址
  69. memory_management_struct.kernel_code_start = (ul)&_text;
  70. memory_management_struct.kernel_code_end = (ul)&_etext;
  71. memory_management_struct.kernel_data_end = (ul)&_edata;
  72. memory_management_struct.rodata_end = (ul)&_erodata;
  73. memory_management_struct.start_brk = (ul)&_end;
  74. struct multiboot_mmap_entry_t mb2_mem_info[512];
  75. int count;
  76. multiboot2_iter(multiboot2_get_memory, mb2_mem_info, &count);
  77. for (int i = 0; i < count; ++i)
  78. {
  79. //可用的内存
  80. if (mb2_mem_info->type == 1)
  81. Total_Memory += mb2_mem_info->len;
  82. kdebug("[i=%d] mb2_mem_info[i].type=%d, mb2_mem_info[i].addr=%#018lx", i, mb2_mem_info[i].type, mb2_mem_info[i].addr);
  83. // 保存信息到mms
  84. memory_management_struct.e820[i].BaseAddr = mb2_mem_info[i].addr;
  85. memory_management_struct.e820[i].Length = mb2_mem_info[i].len;
  86. memory_management_struct.e820[i].type = mb2_mem_info[i].type;
  87. memory_management_struct.len_e820 = i;
  88. // 脏数据
  89. if (mb2_mem_info[i].type > 4 || mb2_mem_info[i].len == 0 || mb2_mem_info[i].type < 1)
  90. break;
  91. }
  92. printk("[ INFO ] Total amounts of RAM : %ld bytes\n", Total_Memory);
  93. // 计算有效内存页数
  94. for (int i = 0; i < memory_management_struct.len_e820; ++i)
  95. {
  96. if (memory_management_struct.e820[i].type != 1)
  97. continue;
  98. // 将内存段的起始物理地址按照2M进行对齐
  99. ul addr_start = PAGE_2M_ALIGN(memory_management_struct.e820[i].BaseAddr);
  100. // 将内存段的终止物理地址的低2M区域清空,以实现对齐
  101. ul addr_end = ((memory_management_struct.e820[i].BaseAddr + memory_management_struct.e820[i].Length) & PAGE_2M_MASK);
  102. // 内存段不可用
  103. if (addr_end <= addr_start)
  104. continue;
  105. total_2M_pages += ((addr_end - addr_start) >> PAGE_2M_SHIFT);
  106. }
  107. kinfo("Total amounts of 2M pages : %ld.", total_2M_pages);
  108. // 物理地址空间的最大地址(包含了物理内存、内存空洞、ROM等)
  109. ul max_addr = memory_management_struct.e820[memory_management_struct.len_e820].BaseAddr + memory_management_struct.e820[memory_management_struct.len_e820].Length;
  110. // 初始化mms的bitmap
  111. // bmp的指针指向截止位置的4k对齐的上边界(防止修改了别的数据)
  112. memory_management_struct.bmp = (unsigned long *)((memory_management_struct.start_brk + PAGE_4K_SIZE - 1) & PAGE_4K_MASK);
  113. memory_management_struct.bits_size = max_addr >> PAGE_2M_SHIFT; // 物理地址空间的最大页面数
  114. memory_management_struct.bmp_len = (((unsigned long)(max_addr >> PAGE_2M_SHIFT) + sizeof(unsigned long) * 8 - 1) / 8) & (~(sizeof(unsigned long) - 1)); // bmp由多少个unsigned long变量组成
  115. // 初始化bitmap, 先将整个bmp空间全部置位。稍后再将可用物理内存页复位。
  116. memset(memory_management_struct.bmp, 0xff, memory_management_struct.bmp_len);
  117. // 初始化内存页结构
  118. // 将页结构映射于bmp之后
  119. memory_management_struct.pages_struct = (struct Page *)(((unsigned long)memory_management_struct.bmp + memory_management_struct.bmp_len + PAGE_4K_SIZE - 1) & PAGE_4K_MASK);
  120. memory_management_struct.count_pages = max_addr >> PAGE_2M_SHIFT;
  121. memory_management_struct.pages_struct_len = ((max_addr >> PAGE_2M_SHIFT) * sizeof(struct Page) + sizeof(long) - 1) & (~(sizeof(long) - 1));
  122. // 将pages_struct全部清空,以备后续初始化
  123. memset(memory_management_struct.pages_struct, 0x00, memory_management_struct.pages_struct_len); // init pages memory
  124. // 初始化内存区域
  125. memory_management_struct.zones_struct = (struct Zone *)(((ul)memory_management_struct.pages_struct + memory_management_struct.pages_struct_len + PAGE_4K_SIZE - 1) & PAGE_4K_MASK);
  126. // 由于暂时无法计算zone结构体的数量,因此先将其设为0
  127. memory_management_struct.count_zones = 0;
  128. // zones-struct 成员变量暂时按照5个来计算
  129. memory_management_struct.zones_struct_len = (10 * sizeof(struct Zone) + sizeof(ul) - 1) & (~(sizeof(ul) - 1));
  130. memset(memory_management_struct.zones_struct, 0x00, memory_management_struct.zones_struct_len);
  131. // ==== 遍历e820数组,完成成员变量初始化工作 ===
  132. for (int i = 0; i < memory_management_struct.len_e820; ++i)
  133. {
  134. if (memory_management_struct.e820[i].type != 1) // 不是操作系统可以使用的物理内存
  135. continue;
  136. ul addr_start = PAGE_2M_ALIGN(memory_management_struct.e820[i].BaseAddr);
  137. ul addr_end = (memory_management_struct.e820[i].BaseAddr + memory_management_struct.e820[i].Length) & PAGE_2M_MASK;
  138. if (addr_end <= addr_start)
  139. continue;
  140. // zone init
  141. struct Zone *z = memory_management_struct.zones_struct + memory_management_struct.count_zones;
  142. ++memory_management_struct.count_zones;
  143. z->zone_addr_start = addr_start;
  144. z->zone_addr_end = addr_end;
  145. z->zone_length = addr_end - addr_start;
  146. z->count_pages_using = 0;
  147. z->count_pages_free = (addr_end - addr_start) >> PAGE_2M_SHIFT;
  148. z->total_pages_link = 0;
  149. z->attr = 0;
  150. z->gmd_struct = &memory_management_struct;
  151. z->count_pages = (addr_end - addr_start) >> PAGE_2M_SHIFT;
  152. z->pages_group = (struct Page *)(memory_management_struct.pages_struct + (addr_start >> PAGE_2M_SHIFT));
  153. // 初始化页
  154. struct Page *p = z->pages_group;
  155. for (int j = 0; j < z->count_pages; ++j, ++p)
  156. {
  157. p->zone = z;
  158. p->addr_phys = addr_start + PAGE_2M_SIZE * j;
  159. p->attr = 0;
  160. p->ref_counts = 0;
  161. p->age = 0;
  162. // 将bmp中对应的位 复位
  163. *(memory_management_struct.bmp + ((p->addr_phys >> PAGE_2M_SHIFT) >> 6)) ^= (1UL << ((p->addr_phys >> PAGE_2M_SHIFT) % 64));
  164. }
  165. }
  166. // 初始化0~2MB的物理页
  167. // 由于这个区间的内存由多个内存段组成,因此不会被以上代码初始化,需要我们手动配置page[0]。
  168. memory_management_struct.pages_struct->zone = memory_management_struct.zones_struct;
  169. memory_management_struct.pages_struct->addr_phys = 0UL;
  170. set_page_attr(memory_management_struct.pages_struct, PAGE_PGT_MAPPED | PAGE_KERNEL_INIT | PAGE_KERNEL);
  171. memory_management_struct.pages_struct->ref_counts = 1;
  172. memory_management_struct.pages_struct->age = 0;
  173. // 将第0页的标志位给置上
  174. //*(memory_management_struct.bmp) |= 1UL;
  175. // 计算zone结构体的总长度(按照64位对齐)
  176. memory_management_struct.zones_struct_len = (memory_management_struct.count_zones * sizeof(struct Zone) + sizeof(ul) - 1) & (~(sizeof(ul) - 1));
  177. ZONE_DMA_INDEX = 0;
  178. ZONE_NORMAL_INDEX = 0;
  179. ZONE_UNMAPPED_INDEX = 0;
  180. /*
  181. for (int i = 0; i < memory_management_struct.count_zones; ++i)
  182. {
  183. struct Zone *z = memory_management_struct.zones_struct + i;
  184. // printk_color(ORANGE, BLACK, "zone_addr_start:%#18lx, zone_addr_end:%#18lx, zone_length:%#18lx, pages_group:%#18lx, count_pages:%#18lx\n",
  185. // z->zone_addr_start, z->zone_addr_end, z->zone_length, z->pages_group, z->count_pages);
  186. // 1GB以上的内存空间不做映射
  187. // if (z->zone_addr_start >= 0x100000000 && (!ZONE_UNMAPPED_INDEX))
  188. // ZONE_UNMAPPED_INDEX = i;
  189. }
  190. */
  191. // kdebug("ZONE_DMA_INDEX=%d\tZONE_NORMAL_INDEX=%d\tZONE_UNMAPPED_INDEX=%d", ZONE_DMA_INDEX, ZONE_NORMAL_INDEX, ZONE_UNMAPPED_INDEX);
  192. // 设置内存页管理结构的地址,预留了一段空间,防止内存越界。
  193. memory_management_struct.end_of_struct = (ul)((ul)memory_management_struct.zones_struct + memory_management_struct.zones_struct_len + sizeof(long) * 32) & (~(sizeof(long) - 1));
  194. // printk_color(ORANGE, BLACK, "code_start:%#18lx, code_end:%#18lx, data_end:%#18lx, kernel_end:%#18lx, end_of_struct:%#18lx\n",
  195. // memory_management_struct.kernel_code_start, memory_management_struct.kernel_code_end, memory_management_struct.kernel_data_end, memory_management_struct.kernel_end, memory_management_struct.end_of_struct);
  196. // 初始化内存管理单元结构所占的物理页的结构体
  197. ul mms_max_page = (virt_2_phys(memory_management_struct.end_of_struct) >> PAGE_2M_SHIFT); // 内存管理单元所占据的序号最大的物理页
  198. // kdebug("mms_max_page=%ld", mms_max_page);
  199. struct Page *tmp_page = NULL;
  200. ul page_num;
  201. // 第0个page已经在上方配置
  202. for (ul j = 1; j <= mms_max_page; ++j)
  203. {
  204. tmp_page = memory_management_struct.pages_struct + j;
  205. page_init(tmp_page, PAGE_PGT_MAPPED | PAGE_KERNEL | PAGE_KERNEL_INIT);
  206. page_num = tmp_page->addr_phys >> PAGE_2M_SHIFT;
  207. *(memory_management_struct.bmp + (page_num >> 6)) |= (1UL << (page_num % 64));
  208. ++tmp_page->zone->count_pages_using;
  209. --tmp_page->zone->count_pages_free;
  210. }
  211. kinfo("Memory management unit initialize complete!");
  212. flush_tlb();
  213. // 初始化slab内存池
  214. slab_init();
  215. page_table_init();
  216. // init_frame_buffer();
  217. }
  218. /**
  219. * @brief 初始化内存页
  220. *
  221. * @param page 内存页结构体
  222. * @param flags 标志位
  223. * 本函数只负责初始化内存页,允许对同一页面进行多次初始化
  224. * 而维护计数器及置位bmp标志位的功能,应当在分配页面的时候手动完成
  225. * @return unsigned long
  226. */
  227. unsigned long page_init(struct Page *page, ul flags)
  228. {
  229. page->attr |= flags;
  230. // 若页面的引用计数为0或是共享页,增加引用计数
  231. if ((!page->ref_counts) || (page->attr & PAGE_SHARED))
  232. {
  233. ++page->ref_counts;
  234. ++page->zone->total_pages_link;
  235. }
  236. return 0;
  237. }
  238. /**
  239. * @brief 从已初始化的页结构中搜索符合申请条件的、连续num个struct page
  240. *
  241. * @param zone_select 选择内存区域, 可选项:dma, mapped in pgt(normal), unmapped in pgt
  242. * @param num 需要申请的连续内存页的数量 num<64
  243. * @param flags 将页面属性设置成flag
  244. * @return struct Page*
  245. */
  246. struct Page *alloc_pages(unsigned int zone_select, int num, ul flags)
  247. {
  248. ul zone_start = 0, zone_end = 0;
  249. if (num >= 64 && num <= 0)
  250. {
  251. kerror("alloc_pages(): num is invalid.");
  252. return NULL;
  253. }
  254. ul attr = flags;
  255. switch (zone_select)
  256. {
  257. case ZONE_DMA:
  258. // DMA区域
  259. zone_start = 0;
  260. zone_end = ZONE_DMA_INDEX;
  261. attr |= PAGE_PGT_MAPPED;
  262. break;
  263. case ZONE_NORMAL:
  264. zone_start = ZONE_DMA_INDEX;
  265. zone_end = ZONE_NORMAL_INDEX;
  266. attr |= PAGE_PGT_MAPPED;
  267. break;
  268. case ZONE_UNMAPPED_IN_PGT:
  269. zone_start = ZONE_NORMAL_INDEX;
  270. zone_end = ZONE_UNMAPPED_INDEX;
  271. attr = 0;
  272. break;
  273. default:
  274. kerror("In alloc_pages: param: zone_select incorrect.");
  275. // 返回空
  276. return NULL;
  277. break;
  278. }
  279. for (int i = zone_start; i <= zone_end; ++i)
  280. {
  281. if ((memory_management_struct.zones_struct + i)->count_pages_free < num)
  282. continue;
  283. struct Zone *z = memory_management_struct.zones_struct + i;
  284. // 区域对应的起止页号
  285. ul page_start = (z->zone_addr_start >> PAGE_2M_SHIFT);
  286. ul page_end = (z->zone_addr_end >> PAGE_2M_SHIFT);
  287. ul tmp = 64 - page_start % 64;
  288. for (ul j = page_start; j < page_end; j += ((j % 64) ? tmp : 64))
  289. {
  290. // 按照bmp中的每一个元素进行查找
  291. // 先将p定位到bmp的起始元素
  292. ul *p = memory_management_struct.bmp + (j >> 6);
  293. ul shift = j % 64;
  294. ul tmp_num = ((1UL << num) - 1);
  295. for (ul k = shift; k < 64; ++k)
  296. {
  297. // 寻找连续num个空页
  298. if (!((k ? ((*p >> k) | (*(p + 1) << (64 - k))) : *p) & tmp_num))
  299. {
  300. ul start_page_num = j + k - shift; // 计算得到要开始获取的内存页的页号
  301. for (ul l = 0; l < num; ++l)
  302. {
  303. struct Page *x = memory_management_struct.pages_struct + start_page_num + l;
  304. // 分配页面,手动配置属性及计数器
  305. // 置位bmp
  306. *(memory_management_struct.bmp + ((x->addr_phys >> PAGE_2M_SHIFT) >> 6)) |= (1UL << (x->addr_phys >> PAGE_2M_SHIFT) % 64);
  307. ++(z->count_pages_using);
  308. --(z->count_pages_free);
  309. x->attr = attr;
  310. }
  311. // 成功分配了页面,返回第一个页面的指针
  312. // kwarn("start page num=%d\n", start_page_num);
  313. return (struct Page *)(memory_management_struct.pages_struct + start_page_num);
  314. }
  315. }
  316. }
  317. }
  318. kBUG("Cannot alloc page, ZONE=%d\tnums=%d, total_2M_pages=%d", zone_select, num, total_2M_pages);
  319. while (1)
  320. ;
  321. return NULL;
  322. }
  323. /**
  324. * @brief 清除页面的引用计数, 计数为0时清空除页表已映射以外的所有属性
  325. *
  326. * @param p 物理页结构体
  327. * @return unsigned long
  328. */
  329. unsigned long page_clean(struct Page *p)
  330. {
  331. --p->ref_counts;
  332. --p->zone->total_pages_link;
  333. // 若引用计数为空,则清空除PAGE_PGT_MAPPED以外的所有属性
  334. if (!p->ref_counts)
  335. {
  336. p->attr &= PAGE_PGT_MAPPED;
  337. }
  338. return 0;
  339. }
  340. /**
  341. * @brief Get the page's attr
  342. *
  343. * @param page 内存页结构体
  344. * @return ul 属性
  345. */
  346. ul get_page_attr(struct Page *page)
  347. {
  348. if (page == NULL)
  349. {
  350. kBUG("get_page_attr(): page == NULL");
  351. return EPAGE_NULL;
  352. }
  353. else
  354. return page->attr;
  355. }
  356. /**
  357. * @brief Set the page's attr
  358. *
  359. * @param page 内存页结构体
  360. * @param flags 属性
  361. * @return ul 错误码
  362. */
  363. ul set_page_attr(struct Page *page, ul flags)
  364. {
  365. if (page == NULL)
  366. {
  367. kBUG("get_page_attr(): page == NULL");
  368. return EPAGE_NULL;
  369. }
  370. else
  371. {
  372. page->attr = flags;
  373. return 0;
  374. }
  375. }
  376. /**
  377. * @brief 释放连续number个内存页
  378. *
  379. * @param page 第一个要被释放的页面的结构体
  380. * @param number 要释放的内存页数量 number<64
  381. */
  382. void free_pages(struct Page *page, int number)
  383. {
  384. if (page == NULL)
  385. {
  386. kerror("free_pages() page is invalid.");
  387. return;
  388. }
  389. if (number >= 64 || number <= 0)
  390. {
  391. kerror("free_pages(): number %d is invalid.", number);
  392. return;
  393. }
  394. ul page_num;
  395. for (int i = 0; i < number; ++i, ++page)
  396. {
  397. page_num = page->addr_phys >> PAGE_2M_SHIFT;
  398. // 复位bmp
  399. *(memory_management_struct.bmp + (page_num >> 6)) &= ~(1UL << (page_num % 64));
  400. // 更新计数器
  401. --page->zone->count_pages_using;
  402. ++page->zone->count_pages_free;
  403. page->attr = 0;
  404. }
  405. return;
  406. }
  407. /**
  408. * @brief 重新初始化页表的函数
  409. * 将所有物理页映射到线性地址空间
  410. */
  411. void page_table_init()
  412. {
  413. kinfo("Re-Initializing page table...");
  414. ul *global_CR3 = get_CR3();
  415. int js = 0;
  416. ul *tmp_addr;
  417. for (int i = 0; i < memory_management_struct.count_zones; ++i)
  418. {
  419. struct Zone *z = memory_management_struct.zones_struct + i;
  420. struct Page *p = z->pages_group;
  421. if (i == ZONE_UNMAPPED_INDEX && ZONE_UNMAPPED_INDEX != 0)
  422. break;
  423. for (int j = 0; j < z->count_pages; ++j)
  424. {
  425. mm_map_proc_page_table((uint64_t)get_CR3(), true, (ul)phys_2_virt(p->addr_phys), p->addr_phys, PAGE_2M_SIZE, PAGE_KERNEL_PAGE, false, true, false);
  426. ++p;
  427. ++js;
  428. }
  429. }
  430. flush_tlb();
  431. kinfo("Page table Initialized. Affects:%d", js);
  432. }
  433. /**
  434. * @brief 将物理地址映射到页表的函数
  435. *
  436. * @param virt_addr_start 要映射到的虚拟地址的起始位置
  437. * @param phys_addr_start 物理地址的起始位置
  438. * @param length 要映射的区域的长度(字节)
  439. * @param flags 标志位
  440. * @param use4k 是否使用4k页
  441. */
  442. int mm_map_phys_addr(ul virt_addr_start, ul phys_addr_start, ul length, ul flags, bool use4k)
  443. {
  444. uint64_t global_CR3 = (uint64_t)get_CR3();
  445. return mm_map_proc_page_table(global_CR3, true, virt_addr_start, phys_addr_start, length, flags, false, true, use4k);
  446. }
  447. int mm_map_phys_addr_user(ul virt_addr_start, ul phys_addr_start, ul length, ul flags)
  448. {
  449. uint64_t global_CR3 = (uint64_t)get_CR3();
  450. return mm_map_proc_page_table(global_CR3, true, virt_addr_start, phys_addr_start, length, flags, true, true, false);
  451. }
  452. /**
  453. * @brief 将将物理地址填写到进程的页表的函数
  454. *
  455. * @param proc_page_table_addr 页表的基地址
  456. * @param is_phys 页表的基地址是否为物理地址
  457. * @param virt_addr_start 要映射到的虚拟地址的起始位置
  458. * @param phys_addr_start 物理地址的起始位置
  459. * @param length 要映射的区域的长度(字节)
  460. * @param user 用户态是否可访问
  461. * @param flush 是否刷新tlb
  462. * @param use4k 是否使用4k页
  463. */
  464. int mm_map_proc_page_table(ul proc_page_table_addr, bool is_phys, ul virt_addr_start, ul phys_addr_start, ul length, ul flags, bool user, bool flush, bool use4k)
  465. {
  466. // 计算线性地址对应的pml4页表项的地址
  467. mm_pgt_entry_num_t pgt_num;
  468. mm_calculate_entry_num(length, &pgt_num);
  469. // kdebug("ent1=%d ent2=%d ent3=%d, ent4=%d", pgt_num.num_PML4E, pgt_num.num_PDPTE, pgt_num.num_PDE, pgt_num.num_PTE);
  470. // 已映射的内存大小
  471. uint64_t length_mapped = 0;
  472. uint64_t pml4e_id = ((virt_addr_start >> PAGE_GDT_SHIFT) & 0x1ff);
  473. uint64_t *pml4_ptr;
  474. if (is_phys)
  475. pml4_ptr = phys_2_virt((ul *)((ul)proc_page_table_addr & (~0xfffUL)));
  476. else
  477. pml4_ptr = (ul *)((ul)proc_page_table_addr & (~0xfffUL));
  478. // 循环填写顶层页表
  479. for (; (pgt_num.num_PML4E > 0) && pml4e_id < 512; ++pml4e_id)
  480. {
  481. // 剩余需要处理的pml4E -1
  482. --(pgt_num.num_PML4E);
  483. ul *pml4e_ptr = pml4_ptr + pml4e_id;
  484. // 创建新的二级页表
  485. if (*pml4e_ptr == 0)
  486. {
  487. ul *virt_addr = kmalloc(PAGE_4K_SIZE, 0);
  488. memset(virt_addr, 0, PAGE_4K_SIZE);
  489. set_pml4t(pml4e_ptr, mk_pml4t(virt_2_phys(virt_addr), (user ? PAGE_USER_PGT : PAGE_KERNEL_PGT)));
  490. }
  491. uint64_t pdpte_id = (((virt_addr_start + length_mapped) >> PAGE_1G_SHIFT) & 0x1ff);
  492. uint64_t *pdpt_ptr = (uint64_t *)phys_2_virt(*pml4e_ptr & (~0xfffUL));
  493. // kdebug("pdpt_ptr=%#018lx", pdpt_ptr);
  494. // 循环填写二级页表
  495. for (; (pgt_num.num_PDPTE > 0) && pdpte_id < 512; ++pdpte_id)
  496. {
  497. --pgt_num.num_PDPTE;
  498. uint64_t *pdpte_ptr = (pdpt_ptr + pdpte_id);
  499. // kdebug("pgt_num.num_PDPTE=%ld pdpte_ptr=%#018lx", pgt_num.num_PDPTE, pdpte_ptr);
  500. // 创建新的三级页表
  501. if (*pdpte_ptr == 0)
  502. {
  503. ul *virt_addr = kmalloc(PAGE_4K_SIZE, 0);
  504. memset(virt_addr, 0, PAGE_4K_SIZE);
  505. set_pdpt(pdpte_ptr, mk_pdpt(virt_2_phys(virt_addr), (user ? PAGE_USER_DIR : PAGE_KERNEL_DIR)));
  506. // kdebug("created new pdt, *pdpte_ptr=%#018lx, virt_addr=%#018lx", *pdpte_ptr, virt_addr);
  507. }
  508. uint64_t pde_id = (((virt_addr_start + length_mapped) >> PAGE_2M_SHIFT) & 0x1ff);
  509. uint64_t *pd_ptr = (uint64_t *)phys_2_virt(*pdpte_ptr & (~0xfffUL));
  510. // kdebug("pd_ptr=%#018lx, *pd_ptr=%#018lx", pd_ptr, *pd_ptr);
  511. // 循环填写三级页表,初始化2M物理页
  512. for (; (pgt_num.num_PDE > 0) && pde_id < 512; ++pde_id)
  513. {
  514. --pgt_num.num_PDE;
  515. // 计算当前2M物理页对应的pdt的页表项的物理地址
  516. ul *pde_ptr = pd_ptr + pde_id;
  517. // ====== 使用4k页 =======
  518. if (unlikely(use4k))
  519. {
  520. // kdebug("use 4k");
  521. if (*pde_ptr == 0)
  522. {
  523. // 创建四级页表
  524. // kdebug("create PT");
  525. uint64_t *vaddr = kmalloc(PAGE_4K_SIZE, 0);
  526. memset(vaddr, 0, PAGE_4K_SIZE);
  527. set_pdt(pde_ptr, mk_pdt(virt_2_phys(vaddr), (user ? PAGE_USER_PDE : PAGE_KERNEL_PDE)));
  528. }
  529. else if (unlikely(*pde_ptr & (1 << 7)))
  530. {
  531. // 当前页表项已经被映射了2MB物理页
  532. goto failed;
  533. }
  534. uint64_t pte_id = (((virt_addr_start + length_mapped) >> PAGE_4K_SHIFT) & 0x1ff);
  535. uint64_t *pt_ptr = (uint64_t *)phys_2_virt(*pde_ptr & (~0x1fffUL));
  536. // 循环填写4级页表,初始化4K页
  537. for (; pgt_num.num_PTE > 0 && pte_id < 512; ++pte_id)
  538. {
  539. --pgt_num.num_PTE;
  540. uint64_t *pte_ptr = pt_ptr + pte_id;
  541. if (unlikely(*pte_ptr != 0))
  542. {
  543. kwarn("pte already exists.");
  544. length_mapped += PAGE_4K_SIZE;
  545. }
  546. set_pt(pte_ptr, mk_pt((ul)phys_addr_start + length_mapped, flags | (user ? PAGE_USER_4K_PAGE : PAGE_KERNEL_4K_PAGE)));
  547. }
  548. }
  549. // ======= 使用2M页 ========
  550. else
  551. {
  552. if (unlikely(*pde_ptr != 0 && user))
  553. {
  554. // kwarn("page already mapped!");
  555. // 如果是用户态可访问的页,则释放当前新获取的物理页
  556. if (likely(((ul)phys_addr_start + length_mapped) < total_2M_pages)) // 校验是否为内存中的物理页
  557. free_pages(Phy_to_2M_Page((ul)phys_addr_start + length_mapped), 1);
  558. length_mapped += PAGE_2M_SIZE;
  559. continue;
  560. }
  561. // 页面写穿,禁止缓存
  562. set_pdt(pde_ptr, mk_pdt((ul)phys_addr_start + length_mapped, flags | (user ? PAGE_USER_PAGE : PAGE_KERNEL_PAGE)));
  563. length_mapped += PAGE_2M_SIZE;
  564. }
  565. }
  566. }
  567. }
  568. if (likely(flush))
  569. flush_tlb();
  570. return 0;
  571. failed:;
  572. kerror("Map memory failed. use4k=%d, vaddr=%#018lx, paddr=%#018lx", use4k, virt_addr_start, phys_addr_start);
  573. return -EFAULT;
  574. }
  575. /**
  576. * @brief 从页表中获取pdt页表项的内容
  577. *
  578. * @param proc_page_table_addr 页表的地址
  579. * @param is_phys 页表地址是否为物理地址
  580. * @param virt_addr_start 要清除的虚拟地址的起始地址
  581. * @param length 要清除的区域的长度
  582. * @param clear 是否清除标志位
  583. */
  584. uint64_t mm_get_PDE(ul proc_page_table_addr, bool is_phys, ul virt_addr, bool clear)
  585. {
  586. ul *tmp;
  587. if (is_phys)
  588. tmp = phys_2_virt((ul *)((ul)proc_page_table_addr & (~0xfffUL)) + ((virt_addr >> PAGE_GDT_SHIFT) & 0x1ff));
  589. else
  590. tmp = (ul *)((ul)proc_page_table_addr & (~0xfffUL)) + ((virt_addr >> PAGE_GDT_SHIFT) & 0x1ff);
  591. // pml4页表项为0
  592. if (*tmp == 0)
  593. return 0;
  594. tmp = phys_2_virt((ul *)(*tmp & (~0xfffUL)) + ((virt_addr >> PAGE_1G_SHIFT) & 0x1ff));
  595. // pdpt页表项为0
  596. if (*tmp == 0)
  597. return 0;
  598. // 读取pdt页表项
  599. tmp = phys_2_virt(((ul *)(*tmp & (~0xfffUL)) + (((ul)(virt_addr) >> PAGE_2M_SHIFT) & 0x1ff)));
  600. if (clear) // 清除页表项的标志位
  601. return *tmp & (~0x1fff);
  602. else
  603. return *tmp;
  604. }
  605. /**
  606. * @brief 从页表中清除虚拟地址的映射
  607. *
  608. * @param proc_page_table_addr 页表的地址
  609. * @param is_phys 页表地址是否为物理地址
  610. * @param virt_addr_start 要清除的虚拟地址的起始地址
  611. * @param length 要清除的区域的长度
  612. */
  613. void mm_unmap_proc_table(ul proc_page_table_addr, bool is_phys, ul virt_addr_start, ul length)
  614. {
  615. // 计算线性地址对应的pml4页表项的地址
  616. mm_pgt_entry_num_t pgt_num;
  617. mm_calculate_entry_num(length, &pgt_num);
  618. // kdebug("ent1=%d ent2=%d ent3=%d, ent4=%d", pgt_num.num_PML4E, pgt_num.num_PDPTE, pgt_num.num_PDE, pgt_num.num_PTE);
  619. // 已取消映射的内存大小
  620. uint64_t length_unmapped = 0;
  621. uint64_t pml4e_id = ((virt_addr_start >> PAGE_GDT_SHIFT) & 0x1ff);
  622. uint64_t *pml4_ptr;
  623. if (is_phys)
  624. pml4_ptr = phys_2_virt((ul *)((ul)proc_page_table_addr & (~0xfffUL)));
  625. else
  626. pml4_ptr = (ul *)((ul)proc_page_table_addr & (~0xfffUL));
  627. // 循环填写顶层页表
  628. for (; (pgt_num.num_PML4E > 0) && pml4e_id < 512; ++pml4e_id)
  629. {
  630. // 剩余需要处理的pml4E -1
  631. --(pgt_num.num_PML4E);
  632. ul *pml4e_ptr = NULL;
  633. pml4e_ptr = pml4_ptr + pml4e_id;
  634. // 二级页表不存在
  635. if (*pml4e_ptr == 0)
  636. {
  637. continue;
  638. }
  639. uint64_t pdpte_id = (((virt_addr_start + length_unmapped) >> PAGE_1G_SHIFT) & 0x1ff);
  640. uint64_t *pdpt_ptr = (uint64_t *)phys_2_virt(*pml4e_ptr & (~0xfffUL));
  641. // kdebug("pdpt_ptr=%#018lx", pdpt_ptr);
  642. // 循环处理二级页表
  643. for (; (pgt_num.num_PDPTE > 0) && pdpte_id < 512; ++pdpte_id)
  644. {
  645. --pgt_num.num_PDPTE;
  646. uint64_t *pdpte_ptr = (pdpt_ptr + pdpte_id);
  647. // kdebug("pgt_num.num_PDPTE=%ld pdpte_ptr=%#018lx", pgt_num.num_PDPTE, pdpte_ptr);
  648. // 三级页表为空
  649. if (*pdpte_ptr == 0)
  650. {
  651. continue;
  652. }
  653. uint64_t pde_id = (((virt_addr_start + length_unmapped) >> PAGE_2M_SHIFT) & 0x1ff);
  654. uint64_t *pd_ptr = (uint64_t *)phys_2_virt(*pdpte_ptr & (~0xfffUL));
  655. // kdebug("pd_ptr=%#018lx, *pd_ptr=%#018lx", pd_ptr, *pd_ptr);
  656. // 循环处理三级页表
  657. for (; (pgt_num.num_PDE > 0) && pde_id < 512; ++pde_id)
  658. {
  659. --pgt_num.num_PDE;
  660. // 计算当前2M物理页对应的pdt的页表项的物理地址
  661. ul *pde_ptr = pd_ptr + pde_id;
  662. // 存在4级页表
  663. if (unlikely(((*pde_ptr) & (1 << 7)) == 0))
  664. {
  665. // 存在4K页
  666. uint64_t pte_id = (((virt_addr_start + length_unmapped) >> PAGE_4K_SHIFT) & 0x1ff);
  667. uint64_t *pt_ptr = (uint64_t *)phys_2_virt(*pde_ptr & (~0x1fffUL));
  668. uint64_t *pte_ptr = pt_ptr + pte_id;
  669. // 循环处理4K页表
  670. for (; pgt_num.num_PTE > 0 && pte_id < 512; ++pte_id, ++pte_ptr)
  671. {
  672. --pgt_num.num_PTE;
  673. // todo: 当支持使用slab分配4K内存作为进程的4K页之后,在这里需要释放这些4K对象
  674. *pte_ptr = 0;
  675. length_unmapped += PAGE_4K_SIZE;
  676. }
  677. // 4级页表已经空了,释放页表
  678. if (unlikely(mm_check_page_table(pt_ptr)) == 0)
  679. kfree(pt_ptr);
  680. }
  681. else
  682. {
  683. *pde_ptr = 0;
  684. length_unmapped += PAGE_2M_SIZE;
  685. }
  686. }
  687. // 3级页表已经空了,释放页表
  688. if (unlikely(mm_check_page_table(pd_ptr)) == 0)
  689. kfree(pd_ptr);
  690. }
  691. // 2级页表已经空了,释放页表
  692. if (unlikely(mm_check_page_table(pdpt_ptr)) == 0)
  693. kfree(pdpt_ptr);
  694. }
  695. flush_tlb();
  696. }
  697. /**
  698. * @brief 从mms中寻找Page结构体
  699. *
  700. * @param phys_addr
  701. * @return struct Page*
  702. */
  703. static struct Page *mm_find_page(uint64_t phys_addr, uint32_t zone_select)
  704. {
  705. uint32_t zone_start, zone_end;
  706. switch (zone_select)
  707. {
  708. case ZONE_DMA:
  709. // DMA区域
  710. zone_start = 0;
  711. zone_end = ZONE_DMA_INDEX;
  712. break;
  713. case ZONE_NORMAL:
  714. zone_start = ZONE_DMA_INDEX;
  715. zone_end = ZONE_NORMAL_INDEX;
  716. break;
  717. case ZONE_UNMAPPED_IN_PGT:
  718. zone_start = ZONE_NORMAL_INDEX;
  719. zone_end = ZONE_UNMAPPED_INDEX;
  720. break;
  721. default:
  722. kerror("In mm_find_page: param: zone_select incorrect.");
  723. // 返回空
  724. return NULL;
  725. break;
  726. }
  727. for (int i = zone_start; i <= zone_end; ++i)
  728. {
  729. if ((memory_management_struct.zones_struct + i)->count_pages_using == 0)
  730. continue;
  731. struct Zone *z = memory_management_struct.zones_struct + i;
  732. // 区域对应的起止页号
  733. ul page_start = (z->zone_addr_start >> PAGE_2M_SHIFT);
  734. ul page_end = (z->zone_addr_end >> PAGE_2M_SHIFT);
  735. ul tmp = 64 - page_start % 64;
  736. for (ul j = page_start; j < page_end; j += ((j % 64) ? tmp : 64))
  737. {
  738. // 按照bmp中的每一个元素进行查找
  739. // 先将p定位到bmp的起始元素
  740. ul *p = memory_management_struct.bmp + (j >> 6);
  741. ul shift = j % 64;
  742. for (ul k = shift; k < 64; ++k)
  743. {
  744. if ((*p >> k) & 1) // 若当前页已分配
  745. {
  746. uint64_t page_num = j + k - shift;
  747. struct Page *x = memory_management_struct.pages_struct + page_num;
  748. if (x->addr_phys == phys_addr) // 找到对应的页
  749. return x;
  750. }
  751. }
  752. }
  753. }
  754. return NULL;
  755. }
  756. /**
  757. * @brief 调整堆区域的大小(暂时只能增加堆区域)
  758. *
  759. * @todo 缩小堆区域
  760. * @param old_brk_end_addr 原本的堆内存区域的结束地址
  761. * @param offset 新的地址相对于原地址的偏移量
  762. * @return uint64_t
  763. */
  764. uint64_t mm_do_brk(uint64_t old_brk_end_addr, int64_t offset)
  765. {
  766. uint64_t end_addr = PAGE_2M_ALIGN(old_brk_end_addr + offset);
  767. if (offset >= 0)
  768. {
  769. for (uint64_t i = old_brk_end_addr; i < end_addr; i += PAGE_2M_SIZE)
  770. {
  771. // kdebug("map [%#018lx]", i);
  772. mm_map_proc_page_table((uint64_t)current_pcb->mm->pgd, true, i, alloc_pages(ZONE_NORMAL, 1, PAGE_PGT_MAPPED)->addr_phys, PAGE_2M_SIZE, PAGE_USER_PAGE, true, true, false);
  773. }
  774. current_pcb->mm->brk_end = end_addr;
  775. }
  776. else
  777. {
  778. // 释放堆内存
  779. for (uint64_t i = end_addr; i < old_brk_end_addr; i += PAGE_2M_SIZE)
  780. {
  781. uint64_t phys = mm_get_PDE((uint64_t)phys_2_virt((uint64_t)current_pcb->mm->pgd), false, i, true);
  782. // 找到对应的页
  783. struct Page *p = mm_find_page(phys, ZONE_NORMAL);
  784. if (p == NULL)
  785. {
  786. kerror("cannot find page addr=%#018lx", phys);
  787. return end_addr;
  788. }
  789. free_pages(p, 1);
  790. }
  791. mm_unmap_proc_table((uint64_t)phys_2_virt((uint64_t)current_pcb->mm->pgd), false, end_addr, PAGE_2M_ALIGN(ABS(offset)));
  792. // 在页表中取消映射
  793. }
  794. return end_addr;
  795. }
  796. /**
  797. * @brief 检测指定地址是否已经被映射
  798. *
  799. * @param page_table_phys_addr 页表的物理地址
  800. * @param virt_addr 要检测的地址
  801. * @return true 已经被映射
  802. * @return false
  803. */
  804. bool mm_check_mapped(ul page_table_phys_addr, uint64_t virt_addr)
  805. {
  806. ul *tmp;
  807. tmp = phys_2_virt((ul *)((ul)page_table_phys_addr & (~0xfffUL)) + ((virt_addr >> PAGE_GDT_SHIFT) & 0x1ff));
  808. // pml4页表项为0
  809. if (*tmp == 0)
  810. return 0;
  811. tmp = phys_2_virt((ul *)(*tmp & (~0xfffUL)) + ((virt_addr >> PAGE_1G_SHIFT) & 0x1ff));
  812. // pdpt页表项为0
  813. if (*tmp == 0)
  814. return 0;
  815. // 读取pdt页表项
  816. tmp = phys_2_virt(((ul *)(*tmp & (~0xfffUL)) + (((ul)(virt_addr) >> PAGE_2M_SHIFT) & 0x1ff)));
  817. // pde页表项为0
  818. if (*tmp == 0)
  819. return 0;
  820. if (*tmp & (1 << 7))
  821. {
  822. // 当前为2M物理页
  823. return true;
  824. }
  825. else
  826. {
  827. // 存在4级页表
  828. tmp = phys_2_virt(((ul *)(*tmp & (~0xfffUL)) + (((ul)(virt_addr) >> PAGE_4K_SHIFT) & 0x1ff)));
  829. if (*tmp != 0)
  830. return true;
  831. else
  832. return false;
  833. }
  834. }
  835. /**
  836. * @brief 检测是否为有效的2M页(物理内存页)
  837. *
  838. * @param paddr 物理地址
  839. * @return int8_t 是 -> 1
  840. * 否 -> 0
  841. */
  842. int8_t mm_is_2M_page(uint64_t paddr)
  843. {
  844. if(likely((paddr >> PAGE_2M_SHIFT)<total_2M_pages))
  845. return 1;
  846. else return 0;
  847. }