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