]> git.proxmox.com Git - mirror_edk2.git/blob - UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c
UefiCpuPkg/PiSmmCpuDxeSmm: Add check for pointer Pml5Entry
[mirror_edk2.git] / UefiCpuPkg / PiSmmCpuDxeSmm / X64 / PageTbl.c
1 /** @file
2 Page Fault (#PF) handler for X64 processors
3
4 Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.<BR>
5 Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
6
7 SPDX-License-Identifier: BSD-2-Clause-Patent
8
9 **/
10
11 #include "PiSmmCpuDxeSmm.h"
12
13 #define PAGE_TABLE_PAGES 8
14 #define ACC_MAX_BIT BIT3
15
16 LIST_ENTRY mPagePool = INITIALIZE_LIST_HEAD_VARIABLE (mPagePool);
17 BOOLEAN m1GPageTableSupport = FALSE;
18 BOOLEAN mCpuSmmStaticPageTable;
19 BOOLEAN m5LevelPagingSupport;
20 X86_ASSEMBLY_PATCH_LABEL gPatch5LevelPagingSupport;
21
22 /**
23 Disable CET.
24 **/
25 VOID
26 EFIAPI
27 DisableCet (
28 VOID
29 );
30
31 /**
32 Enable CET.
33 **/
34 VOID
35 EFIAPI
36 EnableCet (
37 VOID
38 );
39
40 /**
41 Check if 1-GByte pages is supported by processor or not.
42
43 @retval TRUE 1-GByte pages is supported.
44 @retval FALSE 1-GByte pages is not supported.
45
46 **/
47 BOOLEAN
48 Is1GPageSupport (
49 VOID
50 )
51 {
52 UINT32 RegEax;
53 UINT32 RegEdx;
54
55 AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
56 if (RegEax >= 0x80000001) {
57 AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
58 if ((RegEdx & BIT26) != 0) {
59 return TRUE;
60 }
61 }
62 return FALSE;
63 }
64
65 /**
66 Check if 5-level paging is supported by processor or not.
67
68 @retval TRUE 5-level paging is supported.
69 @retval FALSE 5-level paging is not supported.
70
71 **/
72 BOOLEAN
73 Is5LevelPagingSupport (
74 VOID
75 )
76 {
77 CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX EcxFlags;
78
79 AsmCpuidEx (
80 CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS,
81 CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_SUB_LEAF_INFO,
82 NULL,
83 NULL,
84 &EcxFlags.Uint32,
85 NULL
86 );
87 return (BOOLEAN) (EcxFlags.Bits.FiveLevelPage != 0);
88 }
89
90 /**
91 Set sub-entries number in entry.
92
93 @param[in, out] Entry Pointer to entry
94 @param[in] SubEntryNum Sub-entries number based on 0:
95 0 means there is 1 sub-entry under this entry
96 0x1ff means there is 512 sub-entries under this entry
97
98 **/
99 VOID
100 SetSubEntriesNum (
101 IN OUT UINT64 *Entry,
102 IN UINT64 SubEntryNum
103 )
104 {
105 //
106 // Sub-entries number is saved in BIT52 to BIT60 (reserved field) in Entry
107 //
108 *Entry = BitFieldWrite64 (*Entry, 52, 60, SubEntryNum);
109 }
110
111 /**
112 Return sub-entries number in entry.
113
114 @param[in] Entry Pointer to entry
115
116 @return Sub-entries number based on 0:
117 0 means there is 1 sub-entry under this entry
118 0x1ff means there is 512 sub-entries under this entry
119 **/
120 UINT64
121 GetSubEntriesNum (
122 IN UINT64 *Entry
123 )
124 {
125 //
126 // Sub-entries number is saved in BIT52 to BIT60 (reserved field) in Entry
127 //
128 return BitFieldRead64 (*Entry, 52, 60);
129 }
130
131 /**
132 Calculate the maximum support address.
133
134 @return the maximum support address.
135 **/
136 UINT8
137 CalculateMaximumSupportAddress (
138 VOID
139 )
140 {
141 UINT32 RegEax;
142 UINT8 PhysicalAddressBits;
143 VOID *Hob;
144
145 //
146 // Get physical address bits supported.
147 //
148 Hob = GetFirstHob (EFI_HOB_TYPE_CPU);
149 if (Hob != NULL) {
150 PhysicalAddressBits = ((EFI_HOB_CPU *) Hob)->SizeOfMemorySpace;
151 } else {
152 AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
153 if (RegEax >= 0x80000008) {
154 AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL);
155 PhysicalAddressBits = (UINT8) RegEax;
156 } else {
157 PhysicalAddressBits = 36;
158 }
159 }
160 return PhysicalAddressBits;
161 }
162
163 /**
164 Set static page table.
165
166 @param[in] PageTable Address of page table.
167 **/
168 VOID
169 SetStaticPageTable (
170 IN UINTN PageTable
171 )
172 {
173 UINT64 PageAddress;
174 UINTN NumberOfPml5EntriesNeeded;
175 UINTN NumberOfPml4EntriesNeeded;
176 UINTN NumberOfPdpEntriesNeeded;
177 UINTN IndexOfPml5Entries;
178 UINTN IndexOfPml4Entries;
179 UINTN IndexOfPdpEntries;
180 UINTN IndexOfPageDirectoryEntries;
181 UINT64 *PageMapLevel5Entry;
182 UINT64 *PageMapLevel4Entry;
183 UINT64 *PageMap;
184 UINT64 *PageDirectoryPointerEntry;
185 UINT64 *PageDirectory1GEntry;
186 UINT64 *PageDirectoryEntry;
187
188 //
189 // IA-32e paging translates 48-bit linear addresses to 52-bit physical addresses
190 // when 5-Level Paging is disabled.
191 //
192 ASSERT (mPhysicalAddressBits <= 52);
193 if (!m5LevelPagingSupport && mPhysicalAddressBits > 48) {
194 mPhysicalAddressBits = 48;
195 }
196
197 NumberOfPml5EntriesNeeded = 1;
198 if (mPhysicalAddressBits > 48) {
199 NumberOfPml5EntriesNeeded = (UINTN) LShiftU64 (1, mPhysicalAddressBits - 48);
200 mPhysicalAddressBits = 48;
201 }
202
203 NumberOfPml4EntriesNeeded = 1;
204 if (mPhysicalAddressBits > 39) {
205 NumberOfPml4EntriesNeeded = (UINTN) LShiftU64 (1, mPhysicalAddressBits - 39);
206 mPhysicalAddressBits = 39;
207 }
208
209 NumberOfPdpEntriesNeeded = 1;
210 ASSERT (mPhysicalAddressBits > 30);
211 NumberOfPdpEntriesNeeded = (UINTN) LShiftU64 (1, mPhysicalAddressBits - 30);
212
213 //
214 // By architecture only one PageMapLevel4 exists - so lets allocate storage for it.
215 //
216 PageMap = (VOID *) PageTable;
217
218 PageMapLevel4Entry = PageMap;
219 PageMapLevel5Entry = NULL;
220 if (m5LevelPagingSupport) {
221 //
222 // By architecture only one PageMapLevel5 exists - so lets allocate storage for it.
223 //
224 PageMapLevel5Entry = PageMap;
225 }
226 PageAddress = 0;
227
228 for ( IndexOfPml5Entries = 0
229 ; IndexOfPml5Entries < NumberOfPml5EntriesNeeded
230 ; IndexOfPml5Entries++, PageMapLevel5Entry++) {
231 //
232 // Each PML5 entry points to a page of PML4 entires.
233 // So lets allocate space for them and fill them in in the IndexOfPml4Entries loop.
234 // When 5-Level Paging is disabled, below allocation happens only once.
235 //
236 if (m5LevelPagingSupport) {
237 PageMapLevel4Entry = (UINT64 *) ((*PageMapLevel5Entry) & ~mAddressEncMask & gPhyMask);
238 if (PageMapLevel4Entry == NULL) {
239 PageMapLevel4Entry = AllocatePageTableMemory (1);
240 ASSERT(PageMapLevel4Entry != NULL);
241 ZeroMem (PageMapLevel4Entry, EFI_PAGES_TO_SIZE(1));
242
243 *PageMapLevel5Entry = (UINT64)(UINTN)PageMapLevel4Entry | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
244 }
245 }
246
247 for (IndexOfPml4Entries = 0; IndexOfPml4Entries < (NumberOfPml5EntriesNeeded == 1 ? NumberOfPml4EntriesNeeded : 512); IndexOfPml4Entries++, PageMapLevel4Entry++) {
248 //
249 // Each PML4 entry points to a page of Page Directory Pointer entries.
250 //
251 PageDirectoryPointerEntry = (UINT64 *) ((*PageMapLevel4Entry) & ~mAddressEncMask & gPhyMask);
252 if (PageDirectoryPointerEntry == NULL) {
253 PageDirectoryPointerEntry = AllocatePageTableMemory (1);
254 ASSERT(PageDirectoryPointerEntry != NULL);
255 ZeroMem (PageDirectoryPointerEntry, EFI_PAGES_TO_SIZE(1));
256
257 *PageMapLevel4Entry = (UINT64)(UINTN)PageDirectoryPointerEntry | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
258 }
259
260 if (m1GPageTableSupport) {
261 PageDirectory1GEntry = PageDirectoryPointerEntry;
262 for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectory1GEntry++, PageAddress += SIZE_1GB) {
263 if (IndexOfPml4Entries == 0 && IndexOfPageDirectoryEntries < 4) {
264 //
265 // Skip the < 4G entries
266 //
267 continue;
268 }
269 //
270 // Fill in the Page Directory entries
271 //
272 *PageDirectory1GEntry = PageAddress | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS;
273 }
274 } else {
275 PageAddress = BASE_4GB;
276 for (IndexOfPdpEntries = 0; IndexOfPdpEntries < (NumberOfPml4EntriesNeeded == 1 ? NumberOfPdpEntriesNeeded : 512); IndexOfPdpEntries++, PageDirectoryPointerEntry++) {
277 if (IndexOfPml4Entries == 0 && IndexOfPdpEntries < 4) {
278 //
279 // Skip the < 4G entries
280 //
281 continue;
282 }
283 //
284 // Each Directory Pointer entries points to a page of Page Directory entires.
285 // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop.
286 //
287 PageDirectoryEntry = (UINT64 *) ((*PageDirectoryPointerEntry) & ~mAddressEncMask & gPhyMask);
288 if (PageDirectoryEntry == NULL) {
289 PageDirectoryEntry = AllocatePageTableMemory (1);
290 ASSERT(PageDirectoryEntry != NULL);
291 ZeroMem (PageDirectoryEntry, EFI_PAGES_TO_SIZE(1));
292
293 //
294 // Fill in a Page Directory Pointer Entries
295 //
296 *PageDirectoryPointerEntry = (UINT64)(UINTN)PageDirectoryEntry | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
297 }
298
299 for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PageAddress += SIZE_2MB) {
300 //
301 // Fill in the Page Directory entries
302 //
303 *PageDirectoryEntry = PageAddress | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS;
304 }
305 }
306 }
307 }
308 }
309 }
310
311 /**
312 Create PageTable for SMM use.
313
314 @return The address of PML4 (to set CR3).
315
316 **/
317 UINT32
318 SmmInitPageTable (
319 VOID
320 )
321 {
322 EFI_PHYSICAL_ADDRESS Pages;
323 UINT64 *PTEntry;
324 LIST_ENTRY *FreePage;
325 UINTN Index;
326 UINTN PageFaultHandlerHookAddress;
327 IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
328 EFI_STATUS Status;
329 UINT64 *Pml4Entry;
330 UINT64 *Pml5Entry;
331
332 //
333 // Initialize spin lock
334 //
335 InitializeSpinLock (mPFLock);
336
337 mCpuSmmStaticPageTable = PcdGetBool (PcdCpuSmmStaticPageTable);
338 m1GPageTableSupport = Is1GPageSupport ();
339 m5LevelPagingSupport = Is5LevelPagingSupport ();
340 mPhysicalAddressBits = CalculateMaximumSupportAddress ();
341 PatchInstructionX86 (gPatch5LevelPagingSupport, m5LevelPagingSupport, 1);
342 DEBUG ((DEBUG_INFO, "5LevelPaging Support - %d\n", m5LevelPagingSupport));
343 DEBUG ((DEBUG_INFO, "1GPageTable Support - %d\n", m1GPageTableSupport));
344 DEBUG ((DEBUG_INFO, "PcdCpuSmmStaticPageTable - %d\n", mCpuSmmStaticPageTable));
345 DEBUG ((DEBUG_INFO, "PhysicalAddressBits - %d\n", mPhysicalAddressBits));
346 //
347 // Generate PAE page table for the first 4GB memory space
348 //
349 Pages = Gen4GPageTable (FALSE);
350
351 //
352 // Set IA32_PG_PMNT bit to mask this entry
353 //
354 PTEntry = (UINT64*)(UINTN)Pages;
355 for (Index = 0; Index < 4; Index++) {
356 PTEntry[Index] |= IA32_PG_PMNT;
357 }
358
359 //
360 // Fill Page-Table-Level4 (PML4) entry
361 //
362 Pml4Entry = (UINT64*)AllocatePageTableMemory (1);
363 ASSERT (Pml4Entry != NULL);
364 *Pml4Entry = Pages | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
365 ZeroMem (Pml4Entry + 1, EFI_PAGE_SIZE - sizeof (*Pml4Entry));
366
367 //
368 // Set sub-entries number
369 //
370 SetSubEntriesNum (Pml4Entry, 3);
371 PTEntry = Pml4Entry;
372
373 if (m5LevelPagingSupport) {
374 //
375 // Fill PML5 entry
376 //
377 Pml5Entry = (UINT64*)AllocatePageTableMemory (1);
378 ASSERT (Pml5Entry != NULL);
379 *Pml5Entry = (UINTN) Pml4Entry | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
380 ZeroMem (Pml5Entry + 1, EFI_PAGE_SIZE - sizeof (*Pml5Entry));
381 //
382 // Set sub-entries number
383 //
384 SetSubEntriesNum (Pml5Entry, 1);
385 PTEntry = Pml5Entry;
386 }
387
388 if (mCpuSmmStaticPageTable) {
389 SetStaticPageTable ((UINTN)PTEntry);
390 } else {
391 //
392 // Add pages to page pool
393 //
394 FreePage = (LIST_ENTRY*)AllocatePageTableMemory (PAGE_TABLE_PAGES);
395 ASSERT (FreePage != NULL);
396 for (Index = 0; Index < PAGE_TABLE_PAGES; Index++) {
397 InsertTailList (&mPagePool, FreePage);
398 FreePage += EFI_PAGE_SIZE / sizeof (*FreePage);
399 }
400 }
401
402 if (FeaturePcdGet (PcdCpuSmmProfileEnable) ||
403 HEAP_GUARD_NONSTOP_MODE ||
404 NULL_DETECTION_NONSTOP_MODE) {
405 //
406 // Set own Page Fault entry instead of the default one, because SMM Profile
407 // feature depends on IRET instruction to do Single Step
408 //
409 PageFaultHandlerHookAddress = (UINTN)PageFaultIdtHandlerSmmProfile;
410 IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) gcSmiIdtr.Base;
411 IdtEntry += EXCEPT_IA32_PAGE_FAULT;
412 IdtEntry->Bits.OffsetLow = (UINT16)PageFaultHandlerHookAddress;
413 IdtEntry->Bits.Reserved_0 = 0;
414 IdtEntry->Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
415 IdtEntry->Bits.OffsetHigh = (UINT16)(PageFaultHandlerHookAddress >> 16);
416 IdtEntry->Bits.OffsetUpper = (UINT32)(PageFaultHandlerHookAddress >> 32);
417 IdtEntry->Bits.Reserved_1 = 0;
418 } else {
419 //
420 // Register Smm Page Fault Handler
421 //
422 Status = SmmRegisterExceptionHandler (&mSmmCpuService, EXCEPT_IA32_PAGE_FAULT, SmiPFHandler);
423 ASSERT_EFI_ERROR (Status);
424 }
425
426 //
427 // Additional SMM IDT initialization for SMM stack guard
428 //
429 if (FeaturePcdGet (PcdCpuSmmStackGuard)) {
430 InitializeIDTSmmStackGuard ();
431 }
432
433 //
434 // Return the address of PML4/PML5 (to set CR3)
435 //
436 return (UINT32)(UINTN)PTEntry;
437 }
438
439 /**
440 Set access record in entry.
441
442 @param[in, out] Entry Pointer to entry
443 @param[in] Acc Access record value
444
445 **/
446 VOID
447 SetAccNum (
448 IN OUT UINT64 *Entry,
449 IN UINT64 Acc
450 )
451 {
452 //
453 // Access record is saved in BIT9 to BIT11 (reserved field) in Entry
454 //
455 *Entry = BitFieldWrite64 (*Entry, 9, 11, Acc);
456 }
457
458 /**
459 Return access record in entry.
460
461 @param[in] Entry Pointer to entry
462
463 @return Access record value.
464
465 **/
466 UINT64
467 GetAccNum (
468 IN UINT64 *Entry
469 )
470 {
471 //
472 // Access record is saved in BIT9 to BIT11 (reserved field) in Entry
473 //
474 return BitFieldRead64 (*Entry, 9, 11);
475 }
476
477 /**
478 Return and update the access record in entry.
479
480 @param[in, out] Entry Pointer to entry
481
482 @return Access record value.
483
484 **/
485 UINT64
486 GetAndUpdateAccNum (
487 IN OUT UINT64 *Entry
488 )
489 {
490 UINT64 Acc;
491
492 Acc = GetAccNum (Entry);
493 if ((*Entry & IA32_PG_A) != 0) {
494 //
495 // If this entry has been accessed, clear access flag in Entry and update access record
496 // to the initial value 7, adding ACC_MAX_BIT is to make it larger than others
497 //
498 *Entry &= ~(UINT64)(UINTN)IA32_PG_A;
499 SetAccNum (Entry, 0x7);
500 return (0x7 + ACC_MAX_BIT);
501 } else {
502 if (Acc != 0) {
503 //
504 // If the access record is not the smallest value 0, minus 1 and update the access record field
505 //
506 SetAccNum (Entry, Acc - 1);
507 }
508 }
509 return Acc;
510 }
511
512 /**
513 Reclaim free pages for PageFault handler.
514
515 Search the whole entries tree to find the leaf entry that has the smallest
516 access record value. Insert the page pointed by this leaf entry into the
517 page pool. And check its upper entries if need to be inserted into the page
518 pool or not.
519
520 **/
521 VOID
522 ReclaimPages (
523 VOID
524 )
525 {
526 UINT64 Pml5Entry;
527 UINT64 *Pml5;
528 UINT64 *Pml4;
529 UINT64 *Pdpt;
530 UINT64 *Pdt;
531 UINTN Pml5Index;
532 UINTN Pml4Index;
533 UINTN PdptIndex;
534 UINTN PdtIndex;
535 UINTN MinPml5;
536 UINTN MinPml4;
537 UINTN MinPdpt;
538 UINTN MinPdt;
539 UINT64 MinAcc;
540 UINT64 Acc;
541 UINT64 SubEntriesNum;
542 BOOLEAN PML4EIgnore;
543 BOOLEAN PDPTEIgnore;
544 UINT64 *ReleasePageAddress;
545 IA32_CR4 Cr4;
546 BOOLEAN Enable5LevelPaging;
547
548 Pml4 = NULL;
549 Pdpt = NULL;
550 Pdt = NULL;
551 MinAcc = (UINT64)-1;
552 MinPml4 = (UINTN)-1;
553 MinPml5 = (UINTN)-1;
554 MinPdpt = (UINTN)-1;
555 MinPdt = (UINTN)-1;
556 Acc = 0;
557 ReleasePageAddress = 0;
558
559 Cr4.UintN = AsmReadCr4 ();
560 Enable5LevelPaging = (BOOLEAN) (Cr4.Bits.LA57 == 1);
561 Pml5 = (UINT64*)(UINTN)(AsmReadCr3 () & gPhyMask);
562
563 if (!Enable5LevelPaging) {
564 //
565 // Create one fake PML5 entry for 4-Level Paging
566 // so that the page table parsing logic only handles 5-Level page structure.
567 //
568 Pml5Entry = (UINTN) Pml5 | IA32_PG_P;
569 Pml5 = &Pml5Entry;
570 }
571
572 //
573 // First, find the leaf entry has the smallest access record value
574 //
575 for (Pml5Index = 0; Pml5Index < (Enable5LevelPaging ? (EFI_PAGE_SIZE / sizeof (*Pml4)) : 1); Pml5Index++) {
576 if ((Pml5[Pml5Index] & IA32_PG_P) == 0 || (Pml5[Pml5Index] & IA32_PG_PMNT) != 0) {
577 //
578 // If the PML5 entry is not present or is masked, skip it
579 //
580 continue;
581 }
582 Pml4 = (UINT64*)(UINTN)(Pml5[Pml5Index] & gPhyMask);
583 for (Pml4Index = 0; Pml4Index < EFI_PAGE_SIZE / sizeof (*Pml4); Pml4Index++) {
584 if ((Pml4[Pml4Index] & IA32_PG_P) == 0 || (Pml4[Pml4Index] & IA32_PG_PMNT) != 0) {
585 //
586 // If the PML4 entry is not present or is masked, skip it
587 //
588 continue;
589 }
590 Pdpt = (UINT64*)(UINTN)(Pml4[Pml4Index] & ~mAddressEncMask & gPhyMask);
591 PML4EIgnore = FALSE;
592 for (PdptIndex = 0; PdptIndex < EFI_PAGE_SIZE / sizeof (*Pdpt); PdptIndex++) {
593 if ((Pdpt[PdptIndex] & IA32_PG_P) == 0 || (Pdpt[PdptIndex] & IA32_PG_PMNT) != 0) {
594 //
595 // If the PDPT entry is not present or is masked, skip it
596 //
597 if ((Pdpt[PdptIndex] & IA32_PG_PMNT) != 0) {
598 //
599 // If the PDPT entry is masked, we will ignore checking the PML4 entry
600 //
601 PML4EIgnore = TRUE;
602 }
603 continue;
604 }
605 if ((Pdpt[PdptIndex] & IA32_PG_PS) == 0) {
606 //
607 // It's not 1-GByte pages entry, it should be a PDPT entry,
608 // we will not check PML4 entry more
609 //
610 PML4EIgnore = TRUE;
611 Pdt = (UINT64*)(UINTN)(Pdpt[PdptIndex] & ~mAddressEncMask & gPhyMask);
612 PDPTEIgnore = FALSE;
613 for (PdtIndex = 0; PdtIndex < EFI_PAGE_SIZE / sizeof(*Pdt); PdtIndex++) {
614 if ((Pdt[PdtIndex] & IA32_PG_P) == 0 || (Pdt[PdtIndex] & IA32_PG_PMNT) != 0) {
615 //
616 // If the PD entry is not present or is masked, skip it
617 //
618 if ((Pdt[PdtIndex] & IA32_PG_PMNT) != 0) {
619 //
620 // If the PD entry is masked, we will not PDPT entry more
621 //
622 PDPTEIgnore = TRUE;
623 }
624 continue;
625 }
626 if ((Pdt[PdtIndex] & IA32_PG_PS) == 0) {
627 //
628 // It's not 2 MByte page table entry, it should be PD entry
629 // we will find the entry has the smallest access record value
630 //
631 PDPTEIgnore = TRUE;
632 Acc = GetAndUpdateAccNum (Pdt + PdtIndex);
633 if (Acc < MinAcc) {
634 //
635 // If the PD entry has the smallest access record value,
636 // save the Page address to be released
637 //
638 MinAcc = Acc;
639 MinPml5 = Pml5Index;
640 MinPml4 = Pml4Index;
641 MinPdpt = PdptIndex;
642 MinPdt = PdtIndex;
643 ReleasePageAddress = Pdt + PdtIndex;
644 }
645 }
646 }
647 if (!PDPTEIgnore) {
648 //
649 // If this PDPT entry has no PDT entries pointer to 4 KByte pages,
650 // it should only has the entries point to 2 MByte Pages
651 //
652 Acc = GetAndUpdateAccNum (Pdpt + PdptIndex);
653 if (Acc < MinAcc) {
654 //
655 // If the PDPT entry has the smallest access record value,
656 // save the Page address to be released
657 //
658 MinAcc = Acc;
659 MinPml5 = Pml5Index;
660 MinPml4 = Pml4Index;
661 MinPdpt = PdptIndex;
662 MinPdt = (UINTN)-1;
663 ReleasePageAddress = Pdpt + PdptIndex;
664 }
665 }
666 }
667 }
668 if (!PML4EIgnore) {
669 //
670 // If PML4 entry has no the PDPT entry pointer to 2 MByte pages,
671 // it should only has the entries point to 1 GByte Pages
672 //
673 Acc = GetAndUpdateAccNum (Pml4 + Pml4Index);
674 if (Acc < MinAcc) {
675 //
676 // If the PML4 entry has the smallest access record value,
677 // save the Page address to be released
678 //
679 MinAcc = Acc;
680 MinPml5 = Pml5Index;
681 MinPml4 = Pml4Index;
682 MinPdpt = (UINTN)-1;
683 MinPdt = (UINTN)-1;
684 ReleasePageAddress = Pml4 + Pml4Index;
685 }
686 }
687 }
688 }
689 //
690 // Make sure one PML4/PDPT/PD entry is selected
691 //
692 ASSERT (MinAcc != (UINT64)-1);
693
694 //
695 // Secondly, insert the page pointed by this entry into page pool and clear this entry
696 //
697 InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(*ReleasePageAddress & ~mAddressEncMask & gPhyMask));
698 *ReleasePageAddress = 0;
699
700 //
701 // Lastly, check this entry's upper entries if need to be inserted into page pool
702 // or not
703 //
704 while (TRUE) {
705 if (MinPdt != (UINTN)-1) {
706 //
707 // If 4 KByte Page Table is released, check the PDPT entry
708 //
709 Pml4 = (UINT64 *) (UINTN) (Pml5[MinPml5] & gPhyMask);
710 Pdpt = (UINT64*)(UINTN)(Pml4[MinPml4] & ~mAddressEncMask & gPhyMask);
711 SubEntriesNum = GetSubEntriesNum(Pdpt + MinPdpt);
712 if (SubEntriesNum == 0) {
713 //
714 // Release the empty Page Directory table if there was no more 4 KByte Page Table entry
715 // clear the Page directory entry
716 //
717 InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(Pdpt[MinPdpt] & ~mAddressEncMask & gPhyMask));
718 Pdpt[MinPdpt] = 0;
719 //
720 // Go on checking the PML4 table
721 //
722 MinPdt = (UINTN)-1;
723 continue;
724 }
725 //
726 // Update the sub-entries filed in PDPT entry and exit
727 //
728 SetSubEntriesNum (Pdpt + MinPdpt, SubEntriesNum - 1);
729 break;
730 }
731 if (MinPdpt != (UINTN)-1) {
732 //
733 // One 2MB Page Table is released or Page Directory table is released, check the PML4 entry
734 //
735 SubEntriesNum = GetSubEntriesNum (Pml4 + MinPml4);
736 if (SubEntriesNum == 0) {
737 //
738 // Release the empty PML4 table if there was no more 1G KByte Page Table entry
739 // clear the Page directory entry
740 //
741 InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(Pml4[MinPml4] & ~mAddressEncMask & gPhyMask));
742 Pml4[MinPml4] = 0;
743 MinPdpt = (UINTN)-1;
744 continue;
745 }
746 //
747 // Update the sub-entries filed in PML4 entry and exit
748 //
749 SetSubEntriesNum (Pml4 + MinPml4, SubEntriesNum - 1);
750 break;
751 }
752 //
753 // PLM4 table has been released before, exit it
754 //
755 break;
756 }
757 }
758
759 /**
760 Allocate free Page for PageFault handler use.
761
762 @return Page address.
763
764 **/
765 UINT64
766 AllocPage (
767 VOID
768 )
769 {
770 UINT64 RetVal;
771
772 if (IsListEmpty (&mPagePool)) {
773 //
774 // If page pool is empty, reclaim the used pages and insert one into page pool
775 //
776 ReclaimPages ();
777 }
778
779 //
780 // Get one free page and remove it from page pool
781 //
782 RetVal = (UINT64)(UINTN)mPagePool.ForwardLink;
783 RemoveEntryList (mPagePool.ForwardLink);
784 //
785 // Clean this page and return
786 //
787 ZeroMem ((VOID*)(UINTN)RetVal, EFI_PAGE_SIZE);
788 return RetVal;
789 }
790
791 /**
792 Page Fault handler for SMM use.
793
794 **/
795 VOID
796 SmiDefaultPFHandler (
797 VOID
798 )
799 {
800 UINT64 *PageTable;
801 UINT64 *PageTableTop;
802 UINT64 PFAddress;
803 UINTN StartBit;
804 UINTN EndBit;
805 UINT64 PTIndex;
806 UINTN Index;
807 SMM_PAGE_SIZE_TYPE PageSize;
808 UINTN NumOfPages;
809 UINTN PageAttribute;
810 EFI_STATUS Status;
811 UINT64 *UpperEntry;
812 BOOLEAN Enable5LevelPaging;
813 IA32_CR4 Cr4;
814
815 //
816 // Set default SMM page attribute
817 //
818 PageSize = SmmPageSize2M;
819 NumOfPages = 1;
820 PageAttribute = 0;
821
822 EndBit = 0;
823 PageTableTop = (UINT64*)(AsmReadCr3 () & gPhyMask);
824 PFAddress = AsmReadCr2 ();
825
826 Cr4.UintN = AsmReadCr4 ();
827 Enable5LevelPaging = (BOOLEAN) (Cr4.Bits.LA57 != 0);
828
829 Status = GetPlatformPageTableAttribute (PFAddress, &PageSize, &NumOfPages, &PageAttribute);
830 //
831 // If platform not support page table attribute, set default SMM page attribute
832 //
833 if (Status != EFI_SUCCESS) {
834 PageSize = SmmPageSize2M;
835 NumOfPages = 1;
836 PageAttribute = 0;
837 }
838 if (PageSize >= MaxSmmPageSizeType) {
839 PageSize = SmmPageSize2M;
840 }
841 if (NumOfPages > 512) {
842 NumOfPages = 512;
843 }
844
845 switch (PageSize) {
846 case SmmPageSize4K:
847 //
848 // BIT12 to BIT20 is Page Table index
849 //
850 EndBit = 12;
851 break;
852 case SmmPageSize2M:
853 //
854 // BIT21 to BIT29 is Page Directory index
855 //
856 EndBit = 21;
857 PageAttribute |= (UINTN)IA32_PG_PS;
858 break;
859 case SmmPageSize1G:
860 if (!m1GPageTableSupport) {
861 DEBUG ((DEBUG_ERROR, "1-GByte pages is not supported!"));
862 ASSERT (FALSE);
863 }
864 //
865 // BIT30 to BIT38 is Page Directory Pointer Table index
866 //
867 EndBit = 30;
868 PageAttribute |= (UINTN)IA32_PG_PS;
869 break;
870 default:
871 ASSERT (FALSE);
872 }
873
874 //
875 // If execute-disable is enabled, set NX bit
876 //
877 if (mXdEnabled) {
878 PageAttribute |= IA32_PG_NX;
879 }
880
881 for (Index = 0; Index < NumOfPages; Index++) {
882 PageTable = PageTableTop;
883 UpperEntry = NULL;
884 for (StartBit = Enable5LevelPaging ? 48 : 39; StartBit > EndBit; StartBit -= 9) {
885 PTIndex = BitFieldRead64 (PFAddress, StartBit, StartBit + 8);
886 if ((PageTable[PTIndex] & IA32_PG_P) == 0) {
887 //
888 // If the entry is not present, allocate one page from page pool for it
889 //
890 PageTable[PTIndex] = AllocPage () | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
891 } else {
892 //
893 // Save the upper entry address
894 //
895 UpperEntry = PageTable + PTIndex;
896 }
897 //
898 // BIT9 to BIT11 of entry is used to save access record,
899 // initialize value is 7
900 //
901 PageTable[PTIndex] |= (UINT64)IA32_PG_A;
902 SetAccNum (PageTable + PTIndex, 7);
903 PageTable = (UINT64*)(UINTN)(PageTable[PTIndex] & ~mAddressEncMask & gPhyMask);
904 }
905
906 PTIndex = BitFieldRead64 (PFAddress, StartBit, StartBit + 8);
907 if ((PageTable[PTIndex] & IA32_PG_P) != 0) {
908 //
909 // Check if the entry has already existed, this issue may occur when the different
910 // size page entries created under the same entry
911 //
912 DEBUG ((DEBUG_ERROR, "PageTable = %lx, PTIndex = %x, PageTable[PTIndex] = %lx\n", PageTable, PTIndex, PageTable[PTIndex]));
913 DEBUG ((DEBUG_ERROR, "New page table overlapped with old page table!\n"));
914 ASSERT (FALSE);
915 }
916 //
917 // Fill the new entry
918 //
919 PageTable[PTIndex] = ((PFAddress | mAddressEncMask) & gPhyMask & ~((1ull << EndBit) - 1)) |
920 PageAttribute | IA32_PG_A | PAGE_ATTRIBUTE_BITS;
921 if (UpperEntry != NULL) {
922 SetSubEntriesNum (UpperEntry, GetSubEntriesNum (UpperEntry) + 1);
923 }
924 //
925 // Get the next page address if we need to create more page tables
926 //
927 PFAddress += (1ull << EndBit);
928 }
929 }
930
931 /**
932 ThePage Fault handler wrapper for SMM use.
933
934 @param InterruptType Defines the type of interrupt or exception that
935 occurred on the processor.This parameter is processor architecture specific.
936 @param SystemContext A pointer to the processor context when
937 the interrupt occurred on the processor.
938 **/
939 VOID
940 EFIAPI
941 SmiPFHandler (
942 IN EFI_EXCEPTION_TYPE InterruptType,
943 IN EFI_SYSTEM_CONTEXT SystemContext
944 )
945 {
946 UINTN PFAddress;
947 UINTN GuardPageAddress;
948 UINTN CpuIndex;
949
950 ASSERT (InterruptType == EXCEPT_IA32_PAGE_FAULT);
951
952 AcquireSpinLock (mPFLock);
953
954 PFAddress = AsmReadCr2 ();
955
956 if (mCpuSmmStaticPageTable && (PFAddress >= LShiftU64 (1, (mPhysicalAddressBits - 1)))) {
957 DumpCpuContext (InterruptType, SystemContext);
958 DEBUG ((DEBUG_ERROR, "Do not support address 0x%lx by processor!\n", PFAddress));
959 CpuDeadLoop ();
960 goto Exit;
961 }
962
963 //
964 // If a page fault occurs in SMRAM range, it might be in a SMM stack guard page,
965 // or SMM page protection violation.
966 //
967 if ((PFAddress >= mCpuHotPlugData.SmrrBase) &&
968 (PFAddress < (mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize))) {
969 DumpCpuContext (InterruptType, SystemContext);
970 CpuIndex = GetCpuIndex ();
971 GuardPageAddress = (mSmmStackArrayBase + EFI_PAGE_SIZE + CpuIndex * mSmmStackSize);
972 if ((FeaturePcdGet (PcdCpuSmmStackGuard)) &&
973 (PFAddress >= GuardPageAddress) &&
974 (PFAddress < (GuardPageAddress + EFI_PAGE_SIZE))) {
975 DEBUG ((DEBUG_ERROR, "SMM stack overflow!\n"));
976 } else {
977 if ((SystemContext.SystemContextX64->ExceptionData & IA32_PF_EC_ID) != 0) {
978 DEBUG ((DEBUG_ERROR, "SMM exception at execution (0x%lx)\n", PFAddress));
979 DEBUG_CODE (
980 DumpModuleInfoByIp (*(UINTN *)(UINTN)SystemContext.SystemContextX64->Rsp);
981 );
982 } else {
983 DEBUG ((DEBUG_ERROR, "SMM exception at access (0x%lx)\n", PFAddress));
984 DEBUG_CODE (
985 DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip);
986 );
987 }
988
989 if (HEAP_GUARD_NONSTOP_MODE) {
990 GuardPagePFHandler (SystemContext.SystemContextX64->ExceptionData);
991 goto Exit;
992 }
993 }
994 CpuDeadLoop ();
995 goto Exit;
996 }
997
998 //
999 // If a page fault occurs in non-SMRAM range.
1000 //
1001 if ((PFAddress < mCpuHotPlugData.SmrrBase) ||
1002 (PFAddress >= mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize)) {
1003 if ((SystemContext.SystemContextX64->ExceptionData & IA32_PF_EC_ID) != 0) {
1004 DumpCpuContext (InterruptType, SystemContext);
1005 DEBUG ((DEBUG_ERROR, "Code executed on IP(0x%lx) out of SMM range after SMM is locked!\n", PFAddress));
1006 DEBUG_CODE (
1007 DumpModuleInfoByIp (*(UINTN *)(UINTN)SystemContext.SystemContextX64->Rsp);
1008 );
1009 CpuDeadLoop ();
1010 goto Exit;
1011 }
1012
1013 //
1014 // If NULL pointer was just accessed
1015 //
1016 if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0 &&
1017 (PFAddress < EFI_PAGE_SIZE)) {
1018 DumpCpuContext (InterruptType, SystemContext);
1019 DEBUG ((DEBUG_ERROR, "!!! NULL pointer access !!!\n"));
1020 DEBUG_CODE (
1021 DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip);
1022 );
1023
1024 if (NULL_DETECTION_NONSTOP_MODE) {
1025 GuardPagePFHandler (SystemContext.SystemContextX64->ExceptionData);
1026 goto Exit;
1027 }
1028
1029 CpuDeadLoop ();
1030 goto Exit;
1031 }
1032
1033 if (mCpuSmmStaticPageTable && IsSmmCommBufferForbiddenAddress (PFAddress)) {
1034 DumpCpuContext (InterruptType, SystemContext);
1035 DEBUG ((DEBUG_ERROR, "Access SMM communication forbidden address (0x%lx)!\n", PFAddress));
1036 DEBUG_CODE (
1037 DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip);
1038 );
1039 CpuDeadLoop ();
1040 goto Exit;
1041 }
1042 }
1043
1044 if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {
1045 SmmProfilePFHandler (
1046 SystemContext.SystemContextX64->Rip,
1047 SystemContext.SystemContextX64->ExceptionData
1048 );
1049 } else {
1050 SmiDefaultPFHandler ();
1051 }
1052
1053 Exit:
1054 ReleaseSpinLock (mPFLock);
1055 }
1056
1057 /**
1058 This function sets memory attribute for page table.
1059 **/
1060 VOID
1061 SetPageTableAttributes (
1062 VOID
1063 )
1064 {
1065 UINTN Index2;
1066 UINTN Index3;
1067 UINTN Index4;
1068 UINTN Index5;
1069 UINT64 *L1PageTable;
1070 UINT64 *L2PageTable;
1071 UINT64 *L3PageTable;
1072 UINT64 *L4PageTable;
1073 UINT64 *L5PageTable;
1074 BOOLEAN IsSplitted;
1075 BOOLEAN PageTableSplitted;
1076 BOOLEAN CetEnabled;
1077 IA32_CR4 Cr4;
1078 BOOLEAN Enable5LevelPaging;
1079
1080 Cr4.UintN = AsmReadCr4 ();
1081 Enable5LevelPaging = (BOOLEAN) (Cr4.Bits.LA57 == 1);
1082
1083 //
1084 // Don't do this if
1085 // - no static page table; or
1086 // - SMM heap guard feature enabled; or
1087 // BIT2: SMM page guard enabled
1088 // BIT3: SMM pool guard enabled
1089 // - SMM profile feature enabled
1090 //
1091 if (!mCpuSmmStaticPageTable ||
1092 ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) ||
1093 FeaturePcdGet (PcdCpuSmmProfileEnable)) {
1094 //
1095 // Static paging and heap guard could not be enabled at the same time.
1096 //
1097 ASSERT (!(mCpuSmmStaticPageTable &&
1098 (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0));
1099
1100 //
1101 // Static paging and SMM profile could not be enabled at the same time.
1102 //
1103 ASSERT (!(mCpuSmmStaticPageTable && FeaturePcdGet (PcdCpuSmmProfileEnable)));
1104 return ;
1105 }
1106
1107 DEBUG ((DEBUG_INFO, "SetPageTableAttributes\n"));
1108
1109 //
1110 // Disable write protection, because we need mark page table to be write protected.
1111 // We need *write* page table memory, to mark itself to be *read only*.
1112 //
1113 CetEnabled = ((AsmReadCr4() & CR4_CET_ENABLE) != 0) ? TRUE : FALSE;
1114 if (CetEnabled) {
1115 //
1116 // CET must be disabled if WP is disabled.
1117 //
1118 DisableCet();
1119 }
1120 AsmWriteCr0 (AsmReadCr0() & ~CR0_WP);
1121
1122 do {
1123 DEBUG ((DEBUG_INFO, "Start...\n"));
1124 PageTableSplitted = FALSE;
1125 L5PageTable = NULL;
1126 if (Enable5LevelPaging) {
1127 L5PageTable = (UINT64 *)GetPageTableBase ();
1128 SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L5PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);
1129 PageTableSplitted = (PageTableSplitted || IsSplitted);
1130 }
1131
1132 for (Index5 = 0; Index5 < (Enable5LevelPaging ? SIZE_4KB/sizeof(UINT64) : 1); Index5++) {
1133 if (Enable5LevelPaging) {
1134 L4PageTable = (UINT64 *)(UINTN)(L5PageTable[Index5] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);
1135 if (L4PageTable == NULL) {
1136 continue;
1137 }
1138 } else {
1139 L4PageTable = (UINT64 *)GetPageTableBase ();
1140 }
1141 SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L4PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);
1142 PageTableSplitted = (PageTableSplitted || IsSplitted);
1143
1144 for (Index4 = 0; Index4 < SIZE_4KB/sizeof(UINT64); Index4++) {
1145 L3PageTable = (UINT64 *)(UINTN)(L4PageTable[Index4] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);
1146 if (L3PageTable == NULL) {
1147 continue;
1148 }
1149
1150 SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L3PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);
1151 PageTableSplitted = (PageTableSplitted || IsSplitted);
1152
1153 for (Index3 = 0; Index3 < SIZE_4KB/sizeof(UINT64); Index3++) {
1154 if ((L3PageTable[Index3] & IA32_PG_PS) != 0) {
1155 // 1G
1156 continue;
1157 }
1158 L2PageTable = (UINT64 *)(UINTN)(L3PageTable[Index3] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);
1159 if (L2PageTable == NULL) {
1160 continue;
1161 }
1162
1163 SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L2PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);
1164 PageTableSplitted = (PageTableSplitted || IsSplitted);
1165
1166 for (Index2 = 0; Index2 < SIZE_4KB/sizeof(UINT64); Index2++) {
1167 if ((L2PageTable[Index2] & IA32_PG_PS) != 0) {
1168 // 2M
1169 continue;
1170 }
1171 L1PageTable = (UINT64 *)(UINTN)(L2PageTable[Index2] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);
1172 if (L1PageTable == NULL) {
1173 continue;
1174 }
1175 SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L1PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);
1176 PageTableSplitted = (PageTableSplitted || IsSplitted);
1177 }
1178 }
1179 }
1180 }
1181 } while (PageTableSplitted);
1182
1183 //
1184 // Enable write protection, after page table updated.
1185 //
1186 AsmWriteCr0 (AsmReadCr0() | CR0_WP);
1187 if (CetEnabled) {
1188 //
1189 // re-enable CET.
1190 //
1191 EnableCet();
1192 }
1193
1194 return ;
1195 }
1196
1197 /**
1198 This function reads CR2 register when on-demand paging is enabled.
1199
1200 @param[out] *Cr2 Pointer to variable to hold CR2 register value.
1201 **/
1202 VOID
1203 SaveCr2 (
1204 OUT UINTN *Cr2
1205 )
1206 {
1207 if (!mCpuSmmStaticPageTable) {
1208 *Cr2 = AsmReadCr2 ();
1209 }
1210 }
1211
1212 /**
1213 This function restores CR2 register when on-demand paging is enabled.
1214
1215 @param[in] Cr2 Value to write into CR2 register.
1216 **/
1217 VOID
1218 RestoreCr2 (
1219 IN UINTN Cr2
1220 )
1221 {
1222 if (!mCpuSmmStaticPageTable) {
1223 AsmWriteCr2 (Cr2);
1224 }
1225 }