SmmProfile.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. /** @file
  2. Enable SMM profile.
  3. Copyright (c) 2012 - 2019, Intel Corporation. All rights reserved.<BR>
  4. Copyright (c) 2017 - 2020, AMD Incorporated. All rights reserved.<BR>
  5. SPDX-License-Identifier: BSD-2-Clause-Patent
  6. **/
  7. #include "PiSmmCpuDxeSmm.h"
  8. #include "SmmProfileInternal.h"
  9. UINT32 mSmmProfileCr3;
  10. SMM_PROFILE_HEADER *mSmmProfileBase;
  11. MSR_DS_AREA_STRUCT *mMsrDsAreaBase;
  12. //
  13. // The buffer to store SMM profile data.
  14. //
  15. UINTN mSmmProfileSize;
  16. //
  17. // The buffer to enable branch trace store.
  18. //
  19. UINTN mMsrDsAreaSize = SMM_PROFILE_DTS_SIZE;
  20. //
  21. // The flag indicates if execute-disable is supported by processor.
  22. //
  23. BOOLEAN mXdSupported = TRUE;
  24. //
  25. // The flag indicates if execute-disable is enabled on processor.
  26. //
  27. BOOLEAN mXdEnabled = FALSE;
  28. //
  29. // The flag indicates if BTS is supported by processor.
  30. //
  31. BOOLEAN mBtsSupported = TRUE;
  32. //
  33. // The flag indicates if SMM profile starts to record data.
  34. //
  35. BOOLEAN mSmmProfileStart = FALSE;
  36. //
  37. // The flag indicates if #DB will be setup in #PF handler.
  38. //
  39. BOOLEAN mSetupDebugTrap = FALSE;
  40. //
  41. // Record the page fault exception count for one instruction execution.
  42. //
  43. UINTN *mPFEntryCount;
  44. UINT64 (*mLastPFEntryValue)[MAX_PF_ENTRY_COUNT];
  45. UINT64 *(*mLastPFEntryPointer)[MAX_PF_ENTRY_COUNT];
  46. MSR_DS_AREA_STRUCT **mMsrDsArea;
  47. BRANCH_TRACE_RECORD **mMsrBTSRecord;
  48. UINTN mBTSRecordNumber;
  49. PEBS_RECORD **mMsrPEBSRecord;
  50. //
  51. // These memory ranges are always present, they does not generate the access type of page fault exception,
  52. // but they possibly generate instruction fetch type of page fault exception.
  53. //
  54. MEMORY_PROTECTION_RANGE *mProtectionMemRange = NULL;
  55. UINTN mProtectionMemRangeCount = 0;
  56. //
  57. // Some predefined memory ranges.
  58. //
  59. MEMORY_PROTECTION_RANGE mProtectionMemRangeTemplate[] = {
  60. //
  61. // SMRAM range (to be fixed in runtime).
  62. // It is always present and instruction fetches are allowed.
  63. //
  64. {
  65. { 0x00000000, 0x00000000 }, TRUE, FALSE
  66. },
  67. //
  68. // SMM profile data range( to be fixed in runtime).
  69. // It is always present and instruction fetches are not allowed.
  70. //
  71. {
  72. { 0x00000000, 0x00000000 }, TRUE, TRUE
  73. },
  74. //
  75. // SMRAM ranges not covered by mCpuHotPlugData.SmrrBase/mCpuHotPlugData.SmrrSiz (to be fixed in runtime).
  76. // It is always present and instruction fetches are allowed.
  77. // {{0x00000000, 0x00000000},TRUE,FALSE},
  78. //
  79. //
  80. // Future extended range could be added here.
  81. //
  82. //
  83. // PCI MMIO ranges (to be added in runtime).
  84. // They are always present and instruction fetches are not allowed.
  85. //
  86. };
  87. //
  88. // These memory ranges are mapped by 4KB-page instead of 2MB-page.
  89. //
  90. MEMORY_RANGE *mSplitMemRange = NULL;
  91. UINTN mSplitMemRangeCount = 0;
  92. //
  93. // SMI command port.
  94. //
  95. UINT32 mSmiCommandPort;
  96. /**
  97. Disable branch trace store.
  98. **/
  99. VOID
  100. DisableBTS (
  101. VOID
  102. )
  103. {
  104. AsmMsrAnd64 (MSR_DEBUG_CTL, ~((UINT64)(MSR_DEBUG_CTL_BTS | MSR_DEBUG_CTL_TR)));
  105. }
  106. /**
  107. Enable branch trace store.
  108. **/
  109. VOID
  110. EnableBTS (
  111. VOID
  112. )
  113. {
  114. AsmMsrOr64 (MSR_DEBUG_CTL, (MSR_DEBUG_CTL_BTS | MSR_DEBUG_CTL_TR));
  115. }
  116. /**
  117. Get CPU Index from APIC ID.
  118. **/
  119. UINTN
  120. GetCpuIndex (
  121. VOID
  122. )
  123. {
  124. UINTN Index;
  125. UINT32 ApicId;
  126. ApicId = GetApicId ();
  127. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  128. if (gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId == ApicId) {
  129. return Index;
  130. }
  131. }
  132. ASSERT (FALSE);
  133. return 0;
  134. }
  135. /**
  136. Get the source of IP after execute-disable exception is triggered.
  137. @param CpuIndex The index of CPU.
  138. @param DestinationIP The destination address.
  139. **/
  140. UINT64
  141. GetSourceFromDestinationOnBts (
  142. UINTN CpuIndex,
  143. UINT64 DestinationIP
  144. )
  145. {
  146. BRANCH_TRACE_RECORD *CurrentBTSRecord;
  147. UINTN Index;
  148. BOOLEAN FirstMatch;
  149. FirstMatch = FALSE;
  150. CurrentBTSRecord = (BRANCH_TRACE_RECORD *)mMsrDsArea[CpuIndex]->BTSIndex;
  151. for (Index = 0; Index < mBTSRecordNumber; Index++) {
  152. if ((UINTN)CurrentBTSRecord < (UINTN)mMsrBTSRecord[CpuIndex]) {
  153. //
  154. // Underflow
  155. //
  156. CurrentBTSRecord = (BRANCH_TRACE_RECORD *)((UINTN)mMsrDsArea[CpuIndex]->BTSAbsoluteMaximum - 1);
  157. CurrentBTSRecord--;
  158. }
  159. if (CurrentBTSRecord->LastBranchTo == DestinationIP) {
  160. //
  161. // Good! find 1st one, then find 2nd one.
  162. //
  163. if (!FirstMatch) {
  164. //
  165. // The first one is DEBUG exception
  166. //
  167. FirstMatch = TRUE;
  168. } else {
  169. //
  170. // Good find proper one.
  171. //
  172. return CurrentBTSRecord->LastBranchFrom;
  173. }
  174. }
  175. CurrentBTSRecord--;
  176. }
  177. return 0;
  178. }
  179. /**
  180. SMM profile specific INT 1 (single-step) exception handler.
  181. @param InterruptType Defines the type of interrupt or exception that
  182. occurred on the processor.This parameter is processor architecture specific.
  183. @param SystemContext A pointer to the processor context when
  184. the interrupt occurred on the processor.
  185. **/
  186. VOID
  187. EFIAPI
  188. DebugExceptionHandler (
  189. IN EFI_EXCEPTION_TYPE InterruptType,
  190. IN EFI_SYSTEM_CONTEXT SystemContext
  191. )
  192. {
  193. UINTN CpuIndex;
  194. UINTN PFEntry;
  195. if (!mSmmProfileStart &&
  196. !HEAP_GUARD_NONSTOP_MODE &&
  197. !NULL_DETECTION_NONSTOP_MODE)
  198. {
  199. return;
  200. }
  201. CpuIndex = GetCpuIndex ();
  202. //
  203. // Clear last PF entries
  204. //
  205. for (PFEntry = 0; PFEntry < mPFEntryCount[CpuIndex]; PFEntry++) {
  206. *mLastPFEntryPointer[CpuIndex][PFEntry] = mLastPFEntryValue[CpuIndex][PFEntry];
  207. }
  208. //
  209. // Reset page fault exception count for next page fault.
  210. //
  211. mPFEntryCount[CpuIndex] = 0;
  212. //
  213. // Flush TLB
  214. //
  215. CpuFlushTlb ();
  216. //
  217. // Clear TF in EFLAGS
  218. //
  219. ClearTrapFlag (SystemContext);
  220. }
  221. /**
  222. Check if the input address is in SMM ranges.
  223. @param[in] Address The input address.
  224. @retval TRUE The input address is in SMM.
  225. @retval FALSE The input address is not in SMM.
  226. **/
  227. BOOLEAN
  228. IsInSmmRanges (
  229. IN EFI_PHYSICAL_ADDRESS Address
  230. )
  231. {
  232. UINTN Index;
  233. if ((Address >= mCpuHotPlugData.SmrrBase) && (Address < mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize)) {
  234. return TRUE;
  235. }
  236. for (Index = 0; Index < mSmmCpuSmramRangeCount; Index++) {
  237. if ((Address >= mSmmCpuSmramRanges[Index].CpuStart) &&
  238. (Address < mSmmCpuSmramRanges[Index].CpuStart + mSmmCpuSmramRanges[Index].PhysicalSize))
  239. {
  240. return TRUE;
  241. }
  242. }
  243. return FALSE;
  244. }
  245. /**
  246. Check if the memory address will be mapped by 4KB-page.
  247. @param Address The address of Memory.
  248. @param Nx The flag indicates if the memory is execute-disable.
  249. **/
  250. BOOLEAN
  251. IsAddressValid (
  252. IN EFI_PHYSICAL_ADDRESS Address,
  253. IN BOOLEAN *Nx
  254. )
  255. {
  256. UINTN Index;
  257. if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {
  258. //
  259. // Check configuration
  260. //
  261. for (Index = 0; Index < mProtectionMemRangeCount; Index++) {
  262. if ((Address >= mProtectionMemRange[Index].Range.Base) && (Address < mProtectionMemRange[Index].Range.Top)) {
  263. *Nx = mProtectionMemRange[Index].Nx;
  264. return mProtectionMemRange[Index].Present;
  265. }
  266. }
  267. *Nx = TRUE;
  268. return FALSE;
  269. } else {
  270. *Nx = TRUE;
  271. if (IsInSmmRanges (Address)) {
  272. *Nx = FALSE;
  273. }
  274. return TRUE;
  275. }
  276. }
  277. /**
  278. Check if the memory address will be mapped by 4KB-page.
  279. @param Address The address of Memory.
  280. **/
  281. BOOLEAN
  282. IsAddressSplit (
  283. IN EFI_PHYSICAL_ADDRESS Address
  284. )
  285. {
  286. UINTN Index;
  287. if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {
  288. //
  289. // Check configuration
  290. //
  291. for (Index = 0; Index < mSplitMemRangeCount; Index++) {
  292. if ((Address >= mSplitMemRange[Index].Base) && (Address < mSplitMemRange[Index].Top)) {
  293. return TRUE;
  294. }
  295. }
  296. } else {
  297. if (Address < mCpuHotPlugData.SmrrBase) {
  298. if ((mCpuHotPlugData.SmrrBase - Address) < BASE_2MB) {
  299. return TRUE;
  300. }
  301. } else if (Address > (mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize - BASE_2MB)) {
  302. if ((Address - (mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize - BASE_2MB)) < BASE_2MB) {
  303. return TRUE;
  304. }
  305. }
  306. }
  307. //
  308. // Return default
  309. //
  310. return FALSE;
  311. }
  312. /**
  313. Initialize the protected memory ranges and the 4KB-page mapped memory ranges.
  314. **/
  315. VOID
  316. InitProtectedMemRange (
  317. VOID
  318. )
  319. {
  320. UINTN Index;
  321. UINTN NumberOfDescriptors;
  322. UINTN NumberOfAddedDescriptors;
  323. UINTN NumberOfProtectRange;
  324. UINTN NumberOfSpliteRange;
  325. EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap;
  326. UINTN TotalSize;
  327. EFI_PHYSICAL_ADDRESS ProtectBaseAddress;
  328. EFI_PHYSICAL_ADDRESS ProtectEndAddress;
  329. EFI_PHYSICAL_ADDRESS Top2MBAlignedAddress;
  330. EFI_PHYSICAL_ADDRESS Base2MBAlignedAddress;
  331. UINT64 High4KBPageSize;
  332. UINT64 Low4KBPageSize;
  333. NumberOfDescriptors = 0;
  334. NumberOfAddedDescriptors = mSmmCpuSmramRangeCount;
  335. NumberOfSpliteRange = 0;
  336. MemorySpaceMap = NULL;
  337. //
  338. // Get MMIO ranges from GCD and add them into protected memory ranges.
  339. //
  340. gDS->GetMemorySpaceMap (
  341. &NumberOfDescriptors,
  342. &MemorySpaceMap
  343. );
  344. for (Index = 0; Index < NumberOfDescriptors; Index++) {
  345. if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) {
  346. NumberOfAddedDescriptors++;
  347. }
  348. }
  349. if (NumberOfAddedDescriptors != 0) {
  350. TotalSize = NumberOfAddedDescriptors * sizeof (MEMORY_PROTECTION_RANGE) + sizeof (mProtectionMemRangeTemplate);
  351. mProtectionMemRange = (MEMORY_PROTECTION_RANGE *)AllocateZeroPool (TotalSize);
  352. ASSERT (mProtectionMemRange != NULL);
  353. mProtectionMemRangeCount = TotalSize / sizeof (MEMORY_PROTECTION_RANGE);
  354. //
  355. // Copy existing ranges.
  356. //
  357. CopyMem (mProtectionMemRange, mProtectionMemRangeTemplate, sizeof (mProtectionMemRangeTemplate));
  358. //
  359. // Create split ranges which come from protected ranges.
  360. //
  361. TotalSize = (TotalSize / sizeof (MEMORY_PROTECTION_RANGE)) * sizeof (MEMORY_RANGE);
  362. mSplitMemRange = (MEMORY_RANGE *)AllocateZeroPool (TotalSize);
  363. ASSERT (mSplitMemRange != NULL);
  364. //
  365. // Create SMM ranges which are set to present and execution-enable.
  366. //
  367. NumberOfProtectRange = sizeof (mProtectionMemRangeTemplate) / sizeof (MEMORY_PROTECTION_RANGE);
  368. for (Index = 0; Index < mSmmCpuSmramRangeCount; Index++) {
  369. if ((mSmmCpuSmramRanges[Index].CpuStart >= mProtectionMemRange[0].Range.Base) &&
  370. (mSmmCpuSmramRanges[Index].CpuStart + mSmmCpuSmramRanges[Index].PhysicalSize < mProtectionMemRange[0].Range.Top))
  371. {
  372. //
  373. // If the address have been already covered by mCpuHotPlugData.SmrrBase/mCpuHotPlugData.SmrrSiz
  374. //
  375. break;
  376. }
  377. mProtectionMemRange[NumberOfProtectRange].Range.Base = mSmmCpuSmramRanges[Index].CpuStart;
  378. mProtectionMemRange[NumberOfProtectRange].Range.Top = mSmmCpuSmramRanges[Index].CpuStart + mSmmCpuSmramRanges[Index].PhysicalSize;
  379. mProtectionMemRange[NumberOfProtectRange].Present = TRUE;
  380. mProtectionMemRange[NumberOfProtectRange].Nx = FALSE;
  381. NumberOfProtectRange++;
  382. }
  383. //
  384. // Create MMIO ranges which are set to present and execution-disable.
  385. //
  386. for (Index = 0; Index < NumberOfDescriptors; Index++) {
  387. if (MemorySpaceMap[Index].GcdMemoryType != EfiGcdMemoryTypeMemoryMappedIo) {
  388. continue;
  389. }
  390. mProtectionMemRange[NumberOfProtectRange].Range.Base = MemorySpaceMap[Index].BaseAddress;
  391. mProtectionMemRange[NumberOfProtectRange].Range.Top = MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length;
  392. mProtectionMemRange[NumberOfProtectRange].Present = TRUE;
  393. mProtectionMemRange[NumberOfProtectRange].Nx = TRUE;
  394. NumberOfProtectRange++;
  395. }
  396. //
  397. // Check and updated actual protected memory ranges count
  398. //
  399. ASSERT (NumberOfProtectRange <= mProtectionMemRangeCount);
  400. mProtectionMemRangeCount = NumberOfProtectRange;
  401. }
  402. //
  403. // According to protected ranges, create the ranges which will be mapped by 2KB page.
  404. //
  405. NumberOfSpliteRange = 0;
  406. NumberOfProtectRange = mProtectionMemRangeCount;
  407. for (Index = 0; Index < NumberOfProtectRange; Index++) {
  408. //
  409. // If MMIO base address is not 2MB alignment, make 2MB alignment for create 4KB page in page table.
  410. //
  411. ProtectBaseAddress = mProtectionMemRange[Index].Range.Base;
  412. ProtectEndAddress = mProtectionMemRange[Index].Range.Top;
  413. if (((ProtectBaseAddress & (SIZE_2MB - 1)) != 0) || ((ProtectEndAddress & (SIZE_2MB - 1)) != 0)) {
  414. //
  415. // Check if it is possible to create 4KB-page for not 2MB-aligned range and to create 2MB-page for 2MB-aligned range.
  416. // A mix of 4KB and 2MB page could save SMRAM space.
  417. //
  418. Top2MBAlignedAddress = ProtectEndAddress & ~(SIZE_2MB - 1);
  419. Base2MBAlignedAddress = (ProtectBaseAddress + SIZE_2MB - 1) & ~(SIZE_2MB - 1);
  420. if ((Top2MBAlignedAddress > Base2MBAlignedAddress) &&
  421. ((Top2MBAlignedAddress - Base2MBAlignedAddress) >= SIZE_2MB))
  422. {
  423. //
  424. // There is an range which could be mapped by 2MB-page.
  425. //
  426. High4KBPageSize = ((ProtectEndAddress + SIZE_2MB - 1) & ~(SIZE_2MB - 1)) - (ProtectEndAddress & ~(SIZE_2MB - 1));
  427. Low4KBPageSize = ((ProtectBaseAddress + SIZE_2MB - 1) & ~(SIZE_2MB - 1)) - (ProtectBaseAddress & ~(SIZE_2MB - 1));
  428. if (High4KBPageSize != 0) {
  429. //
  430. // Add not 2MB-aligned range to be mapped by 4KB-page.
  431. //
  432. mSplitMemRange[NumberOfSpliteRange].Base = ProtectEndAddress & ~(SIZE_2MB - 1);
  433. mSplitMemRange[NumberOfSpliteRange].Top = (ProtectEndAddress + SIZE_2MB - 1) & ~(SIZE_2MB - 1);
  434. NumberOfSpliteRange++;
  435. }
  436. if (Low4KBPageSize != 0) {
  437. //
  438. // Add not 2MB-aligned range to be mapped by 4KB-page.
  439. //
  440. mSplitMemRange[NumberOfSpliteRange].Base = ProtectBaseAddress & ~(SIZE_2MB - 1);
  441. mSplitMemRange[NumberOfSpliteRange].Top = (ProtectBaseAddress + SIZE_2MB - 1) & ~(SIZE_2MB - 1);
  442. NumberOfSpliteRange++;
  443. }
  444. } else {
  445. //
  446. // The range could only be mapped by 4KB-page.
  447. //
  448. mSplitMemRange[NumberOfSpliteRange].Base = ProtectBaseAddress & ~(SIZE_2MB - 1);
  449. mSplitMemRange[NumberOfSpliteRange].Top = (ProtectEndAddress + SIZE_2MB - 1) & ~(SIZE_2MB - 1);
  450. NumberOfSpliteRange++;
  451. }
  452. }
  453. }
  454. mSplitMemRangeCount = NumberOfSpliteRange;
  455. DEBUG ((DEBUG_INFO, "SMM Profile Memory Ranges:\n"));
  456. for (Index = 0; Index < mProtectionMemRangeCount; Index++) {
  457. DEBUG ((DEBUG_INFO, "mProtectionMemRange[%d].Base = %lx\n", Index, mProtectionMemRange[Index].Range.Base));
  458. DEBUG ((DEBUG_INFO, "mProtectionMemRange[%d].Top = %lx\n", Index, mProtectionMemRange[Index].Range.Top));
  459. }
  460. for (Index = 0; Index < mSplitMemRangeCount; Index++) {
  461. DEBUG ((DEBUG_INFO, "mSplitMemRange[%d].Base = %lx\n", Index, mSplitMemRange[Index].Base));
  462. DEBUG ((DEBUG_INFO, "mSplitMemRange[%d].Top = %lx\n", Index, mSplitMemRange[Index].Top));
  463. }
  464. }
  465. /**
  466. Update page table according to protected memory ranges and the 4KB-page mapped memory ranges.
  467. **/
  468. VOID
  469. InitPaging (
  470. VOID
  471. )
  472. {
  473. UINT64 Pml5Entry;
  474. UINT64 Pml4Entry;
  475. UINT64 *Pml5;
  476. UINT64 *Pml4;
  477. UINT64 *Pdpt;
  478. UINT64 *Pd;
  479. UINT64 *Pt;
  480. UINTN Address;
  481. UINTN Pml5Index;
  482. UINTN Pml4Index;
  483. UINTN PdptIndex;
  484. UINTN PdIndex;
  485. UINTN PtIndex;
  486. UINTN NumberOfPdptEntries;
  487. UINTN NumberOfPml4Entries;
  488. UINTN NumberOfPml5Entries;
  489. UINTN SizeOfMemorySpace;
  490. BOOLEAN Nx;
  491. IA32_CR4 Cr4;
  492. BOOLEAN Enable5LevelPaging;
  493. Cr4.UintN = AsmReadCr4 ();
  494. Enable5LevelPaging = (BOOLEAN)(Cr4.Bits.LA57 == 1);
  495. if (sizeof (UINTN) == sizeof (UINT64)) {
  496. if (!Enable5LevelPaging) {
  497. Pml5Entry = (UINTN)mSmmProfileCr3 | IA32_PG_P;
  498. Pml5 = &Pml5Entry;
  499. } else {
  500. Pml5 = (UINT64 *)(UINTN)mSmmProfileCr3;
  501. }
  502. SizeOfMemorySpace = HighBitSet64 (gPhyMask) + 1;
  503. //
  504. // Calculate the table entries of PML4E and PDPTE.
  505. //
  506. NumberOfPml5Entries = 1;
  507. if (SizeOfMemorySpace > 48) {
  508. NumberOfPml5Entries = (UINTN)LShiftU64 (1, SizeOfMemorySpace - 48);
  509. SizeOfMemorySpace = 48;
  510. }
  511. NumberOfPml4Entries = 1;
  512. if (SizeOfMemorySpace > 39) {
  513. NumberOfPml4Entries = (UINTN)LShiftU64 (1, SizeOfMemorySpace - 39);
  514. SizeOfMemorySpace = 39;
  515. }
  516. NumberOfPdptEntries = 1;
  517. ASSERT (SizeOfMemorySpace > 30);
  518. NumberOfPdptEntries = (UINTN)LShiftU64 (1, SizeOfMemorySpace - 30);
  519. } else {
  520. Pml4Entry = (UINTN)mSmmProfileCr3 | IA32_PG_P;
  521. Pml4 = &Pml4Entry;
  522. Pml5Entry = (UINTN)Pml4 | IA32_PG_P;
  523. Pml5 = &Pml5Entry;
  524. NumberOfPml5Entries = 1;
  525. NumberOfPml4Entries = 1;
  526. NumberOfPdptEntries = 4;
  527. }
  528. //
  529. // Go through page table and change 2MB-page into 4KB-page.
  530. //
  531. for (Pml5Index = 0; Pml5Index < NumberOfPml5Entries; Pml5Index++) {
  532. if ((Pml5[Pml5Index] & IA32_PG_P) == 0) {
  533. //
  534. // If PML5 entry does not exist, skip it
  535. //
  536. continue;
  537. }
  538. Pml4 = (UINT64 *)(UINTN)(Pml5[Pml5Index] & PHYSICAL_ADDRESS_MASK);
  539. for (Pml4Index = 0; Pml4Index < NumberOfPml4Entries; Pml4Index++) {
  540. if ((Pml4[Pml4Index] & IA32_PG_P) == 0) {
  541. //
  542. // If PML4 entry does not exist, skip it
  543. //
  544. continue;
  545. }
  546. Pdpt = (UINT64 *)(UINTN)(Pml4[Pml4Index] & ~mAddressEncMask & PHYSICAL_ADDRESS_MASK);
  547. for (PdptIndex = 0; PdptIndex < NumberOfPdptEntries; PdptIndex++, Pdpt++) {
  548. if ((*Pdpt & IA32_PG_P) == 0) {
  549. //
  550. // If PDPT entry does not exist, skip it
  551. //
  552. continue;
  553. }
  554. if ((*Pdpt & IA32_PG_PS) != 0) {
  555. //
  556. // This is 1G entry, skip it
  557. //
  558. continue;
  559. }
  560. Pd = (UINT64 *)(UINTN)(*Pdpt & ~mAddressEncMask & PHYSICAL_ADDRESS_MASK);
  561. if (Pd == 0) {
  562. continue;
  563. }
  564. for (PdIndex = 0; PdIndex < SIZE_4KB / sizeof (*Pd); PdIndex++, Pd++) {
  565. if ((*Pd & IA32_PG_P) == 0) {
  566. //
  567. // If PD entry does not exist, skip it
  568. //
  569. continue;
  570. }
  571. Address = (UINTN)LShiftU64 (
  572. LShiftU64 (
  573. LShiftU64 ((Pml5Index << 9) + Pml4Index, 9) + PdptIndex,
  574. 9
  575. ) + PdIndex,
  576. 21
  577. );
  578. //
  579. // If it is 2M page, check IsAddressSplit()
  580. //
  581. if (((*Pd & IA32_PG_PS) != 0) && IsAddressSplit (Address)) {
  582. //
  583. // Based on current page table, create 4KB page table for split area.
  584. //
  585. ASSERT (Address == (*Pd & PHYSICAL_ADDRESS_MASK));
  586. Pt = AllocatePageTableMemory (1);
  587. ASSERT (Pt != NULL);
  588. // Split it
  589. for (PtIndex = 0; PtIndex < SIZE_4KB / sizeof (*Pt); PtIndex++) {
  590. Pt[PtIndex] = Address + ((PtIndex << 12) | mAddressEncMask | PAGE_ATTRIBUTE_BITS);
  591. } // end for PT
  592. *Pd = (UINT64)(UINTN)Pt | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
  593. } // end if IsAddressSplit
  594. } // end for PD
  595. } // end for PDPT
  596. } // end for PML4
  597. } // end for PML5
  598. //
  599. // Go through page table and set several page table entries to absent or execute-disable.
  600. //
  601. DEBUG ((DEBUG_INFO, "Patch page table start ...\n"));
  602. for (Pml5Index = 0; Pml5Index < NumberOfPml5Entries; Pml5Index++) {
  603. if ((Pml5[Pml5Index] & IA32_PG_P) == 0) {
  604. //
  605. // If PML5 entry does not exist, skip it
  606. //
  607. continue;
  608. }
  609. Pml4 = (UINT64 *)(UINTN)(Pml5[Pml5Index] & PHYSICAL_ADDRESS_MASK);
  610. for (Pml4Index = 0; Pml4Index < NumberOfPml4Entries; Pml4Index++) {
  611. if ((Pml4[Pml4Index] & IA32_PG_P) == 0) {
  612. //
  613. // If PML4 entry does not exist, skip it
  614. //
  615. continue;
  616. }
  617. Pdpt = (UINT64 *)(UINTN)(Pml4[Pml4Index] & ~mAddressEncMask & PHYSICAL_ADDRESS_MASK);
  618. for (PdptIndex = 0; PdptIndex < NumberOfPdptEntries; PdptIndex++, Pdpt++) {
  619. if ((*Pdpt & IA32_PG_P) == 0) {
  620. //
  621. // If PDPT entry does not exist, skip it
  622. //
  623. continue;
  624. }
  625. if ((*Pdpt & IA32_PG_PS) != 0) {
  626. //
  627. // This is 1G entry, set NX bit and skip it
  628. //
  629. if (mXdSupported) {
  630. *Pdpt = *Pdpt | IA32_PG_NX;
  631. }
  632. continue;
  633. }
  634. Pd = (UINT64 *)(UINTN)(*Pdpt & ~mAddressEncMask & PHYSICAL_ADDRESS_MASK);
  635. if (Pd == 0) {
  636. continue;
  637. }
  638. for (PdIndex = 0; PdIndex < SIZE_4KB / sizeof (*Pd); PdIndex++, Pd++) {
  639. if ((*Pd & IA32_PG_P) == 0) {
  640. //
  641. // If PD entry does not exist, skip it
  642. //
  643. continue;
  644. }
  645. Address = (UINTN)LShiftU64 (
  646. LShiftU64 (
  647. LShiftU64 ((Pml5Index << 9) + Pml4Index, 9) + PdptIndex,
  648. 9
  649. ) + PdIndex,
  650. 21
  651. );
  652. if ((*Pd & IA32_PG_PS) != 0) {
  653. // 2MB page
  654. if (!IsAddressValid (Address, &Nx)) {
  655. //
  656. // Patch to remove Present flag and RW flag
  657. //
  658. *Pd = *Pd & (INTN)(INT32)(~PAGE_ATTRIBUTE_BITS);
  659. }
  660. if (Nx && mXdSupported) {
  661. *Pd = *Pd | IA32_PG_NX;
  662. }
  663. } else {
  664. // 4KB page
  665. Pt = (UINT64 *)(UINTN)(*Pd & ~mAddressEncMask & PHYSICAL_ADDRESS_MASK);
  666. if (Pt == 0) {
  667. continue;
  668. }
  669. for (PtIndex = 0; PtIndex < SIZE_4KB / sizeof (*Pt); PtIndex++, Pt++) {
  670. if (!IsAddressValid (Address, &Nx)) {
  671. *Pt = *Pt & (INTN)(INT32)(~PAGE_ATTRIBUTE_BITS);
  672. }
  673. if (Nx && mXdSupported) {
  674. *Pt = *Pt | IA32_PG_NX;
  675. }
  676. Address += SIZE_4KB;
  677. } // end for PT
  678. } // end if PS
  679. } // end for PD
  680. } // end for PDPT
  681. } // end for PML4
  682. } // end for PML5
  683. //
  684. // Flush TLB
  685. //
  686. CpuFlushTlb ();
  687. DEBUG ((DEBUG_INFO, "Patch page table done!\n"));
  688. //
  689. // Set execute-disable flag
  690. //
  691. mXdEnabled = TRUE;
  692. return;
  693. }
  694. /**
  695. To get system port address of the SMI Command Port in FADT table.
  696. **/
  697. VOID
  698. GetSmiCommandPort (
  699. VOID
  700. )
  701. {
  702. EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE *Fadt;
  703. Fadt = (EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE *)EfiLocateFirstAcpiTable (
  704. EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE
  705. );
  706. ASSERT (Fadt != NULL);
  707. mSmiCommandPort = Fadt->SmiCmd;
  708. DEBUG ((DEBUG_INFO, "mSmiCommandPort = %x\n", mSmiCommandPort));
  709. }
  710. /**
  711. Updates page table to make some memory ranges (like system memory) absent
  712. and make some memory ranges (like MMIO) present and execute disable. It also
  713. update 2MB-page to 4KB-page for some memory ranges.
  714. **/
  715. VOID
  716. SmmProfileStart (
  717. VOID
  718. )
  719. {
  720. //
  721. // The flag indicates SMM profile starts to work.
  722. //
  723. mSmmProfileStart = TRUE;
  724. }
  725. /**
  726. Initialize SMM profile in SmmReadyToLock protocol callback function.
  727. @param Protocol Points to the protocol's unique identifier.
  728. @param Interface Points to the interface instance.
  729. @param Handle The handle on which the interface was installed.
  730. @retval EFI_SUCCESS SmmReadyToLock protocol callback runs successfully.
  731. **/
  732. EFI_STATUS
  733. EFIAPI
  734. InitSmmProfileCallBack (
  735. IN CONST EFI_GUID *Protocol,
  736. IN VOID *Interface,
  737. IN EFI_HANDLE Handle
  738. )
  739. {
  740. //
  741. // Save to variable so that SMM profile data can be found.
  742. //
  743. gRT->SetVariable (
  744. SMM_PROFILE_NAME,
  745. &gEfiCallerIdGuid,
  746. EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
  747. sizeof (mSmmProfileBase),
  748. &mSmmProfileBase
  749. );
  750. //
  751. // Get Software SMI from FADT
  752. //
  753. GetSmiCommandPort ();
  754. //
  755. // Initialize protected memory range for patching page table later.
  756. //
  757. InitProtectedMemRange ();
  758. return EFI_SUCCESS;
  759. }
  760. /**
  761. Initialize SMM profile data structures.
  762. **/
  763. VOID
  764. InitSmmProfileInternal (
  765. VOID
  766. )
  767. {
  768. EFI_STATUS Status;
  769. EFI_PHYSICAL_ADDRESS Base;
  770. VOID *Registration;
  771. UINTN Index;
  772. UINTN MsrDsAreaSizePerCpu;
  773. UINTN TotalSize;
  774. mPFEntryCount = (UINTN *)AllocateZeroPool (sizeof (UINTN) * mMaxNumberOfCpus);
  775. ASSERT (mPFEntryCount != NULL);
  776. mLastPFEntryValue = (UINT64 (*)[MAX_PF_ENTRY_COUNT])AllocateZeroPool (
  777. sizeof (mLastPFEntryValue[0]) * mMaxNumberOfCpus
  778. );
  779. ASSERT (mLastPFEntryValue != NULL);
  780. mLastPFEntryPointer = (UINT64 *(*)[MAX_PF_ENTRY_COUNT])AllocateZeroPool (
  781. sizeof (mLastPFEntryPointer[0]) * mMaxNumberOfCpus
  782. );
  783. ASSERT (mLastPFEntryPointer != NULL);
  784. //
  785. // Allocate memory for SmmProfile below 4GB.
  786. // The base address
  787. //
  788. mSmmProfileSize = PcdGet32 (PcdCpuSmmProfileSize);
  789. ASSERT ((mSmmProfileSize & 0xFFF) == 0);
  790. if (mBtsSupported) {
  791. TotalSize = mSmmProfileSize + mMsrDsAreaSize;
  792. } else {
  793. TotalSize = mSmmProfileSize;
  794. }
  795. Base = 0xFFFFFFFF;
  796. Status = gBS->AllocatePages (
  797. AllocateMaxAddress,
  798. EfiReservedMemoryType,
  799. EFI_SIZE_TO_PAGES (TotalSize),
  800. &Base
  801. );
  802. ASSERT_EFI_ERROR (Status);
  803. ZeroMem ((VOID *)(UINTN)Base, TotalSize);
  804. mSmmProfileBase = (SMM_PROFILE_HEADER *)(UINTN)Base;
  805. //
  806. // Initialize SMM profile data header.
  807. //
  808. mSmmProfileBase->HeaderSize = sizeof (SMM_PROFILE_HEADER);
  809. mSmmProfileBase->MaxDataEntries = (UINT64)((mSmmProfileSize - sizeof (SMM_PROFILE_HEADER)) / sizeof (SMM_PROFILE_ENTRY));
  810. mSmmProfileBase->MaxDataSize = MultU64x64 (mSmmProfileBase->MaxDataEntries, sizeof (SMM_PROFILE_ENTRY));
  811. mSmmProfileBase->CurDataEntries = 0;
  812. mSmmProfileBase->CurDataSize = 0;
  813. mSmmProfileBase->TsegStart = mCpuHotPlugData.SmrrBase;
  814. mSmmProfileBase->TsegSize = mCpuHotPlugData.SmrrSize;
  815. mSmmProfileBase->NumSmis = 0;
  816. mSmmProfileBase->NumCpus = gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus;
  817. if (mBtsSupported) {
  818. mMsrDsArea = (MSR_DS_AREA_STRUCT **)AllocateZeroPool (sizeof (MSR_DS_AREA_STRUCT *) * mMaxNumberOfCpus);
  819. ASSERT (mMsrDsArea != NULL);
  820. mMsrBTSRecord = (BRANCH_TRACE_RECORD **)AllocateZeroPool (sizeof (BRANCH_TRACE_RECORD *) * mMaxNumberOfCpus);
  821. ASSERT (mMsrBTSRecord != NULL);
  822. mMsrPEBSRecord = (PEBS_RECORD **)AllocateZeroPool (sizeof (PEBS_RECORD *) * mMaxNumberOfCpus);
  823. ASSERT (mMsrPEBSRecord != NULL);
  824. mMsrDsAreaBase = (MSR_DS_AREA_STRUCT *)((UINTN)Base + mSmmProfileSize);
  825. MsrDsAreaSizePerCpu = mMsrDsAreaSize / mMaxNumberOfCpus;
  826. mBTSRecordNumber = (MsrDsAreaSizePerCpu - sizeof (PEBS_RECORD) * PEBS_RECORD_NUMBER - sizeof (MSR_DS_AREA_STRUCT)) / sizeof (BRANCH_TRACE_RECORD);
  827. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  828. mMsrDsArea[Index] = (MSR_DS_AREA_STRUCT *)((UINTN)mMsrDsAreaBase + MsrDsAreaSizePerCpu * Index);
  829. mMsrBTSRecord[Index] = (BRANCH_TRACE_RECORD *)((UINTN)mMsrDsArea[Index] + sizeof (MSR_DS_AREA_STRUCT));
  830. mMsrPEBSRecord[Index] = (PEBS_RECORD *)((UINTN)mMsrDsArea[Index] + MsrDsAreaSizePerCpu - sizeof (PEBS_RECORD) * PEBS_RECORD_NUMBER);
  831. mMsrDsArea[Index]->BTSBufferBase = (UINTN)mMsrBTSRecord[Index];
  832. mMsrDsArea[Index]->BTSIndex = mMsrDsArea[Index]->BTSBufferBase;
  833. mMsrDsArea[Index]->BTSAbsoluteMaximum = mMsrDsArea[Index]->BTSBufferBase + mBTSRecordNumber * sizeof (BRANCH_TRACE_RECORD) + 1;
  834. mMsrDsArea[Index]->BTSInterruptThreshold = mMsrDsArea[Index]->BTSAbsoluteMaximum + 1;
  835. mMsrDsArea[Index]->PEBSBufferBase = (UINTN)mMsrPEBSRecord[Index];
  836. mMsrDsArea[Index]->PEBSIndex = mMsrDsArea[Index]->PEBSBufferBase;
  837. mMsrDsArea[Index]->PEBSAbsoluteMaximum = mMsrDsArea[Index]->PEBSBufferBase + PEBS_RECORD_NUMBER * sizeof (PEBS_RECORD) + 1;
  838. mMsrDsArea[Index]->PEBSInterruptThreshold = mMsrDsArea[Index]->PEBSAbsoluteMaximum + 1;
  839. }
  840. }
  841. mProtectionMemRange = mProtectionMemRangeTemplate;
  842. mProtectionMemRangeCount = sizeof (mProtectionMemRangeTemplate) / sizeof (MEMORY_PROTECTION_RANGE);
  843. //
  844. // Update TSeg entry.
  845. //
  846. mProtectionMemRange[0].Range.Base = mCpuHotPlugData.SmrrBase;
  847. mProtectionMemRange[0].Range.Top = mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize;
  848. //
  849. // Update SMM profile entry.
  850. //
  851. mProtectionMemRange[1].Range.Base = (EFI_PHYSICAL_ADDRESS)(UINTN)mSmmProfileBase;
  852. mProtectionMemRange[1].Range.Top = (EFI_PHYSICAL_ADDRESS)(UINTN)mSmmProfileBase + TotalSize;
  853. //
  854. // Allocate memory reserved for creating 4KB pages.
  855. //
  856. InitPagesForPFHandler ();
  857. //
  858. // Start SMM profile when SmmReadyToLock protocol is installed.
  859. //
  860. Status = gSmst->SmmRegisterProtocolNotify (
  861. &gEfiSmmReadyToLockProtocolGuid,
  862. InitSmmProfileCallBack,
  863. &Registration
  864. );
  865. ASSERT_EFI_ERROR (Status);
  866. return;
  867. }
  868. /**
  869. Check if feature is supported by a processor.
  870. **/
  871. VOID
  872. CheckFeatureSupported (
  873. VOID
  874. )
  875. {
  876. UINT32 RegEax;
  877. UINT32 RegEcx;
  878. UINT32 RegEdx;
  879. MSR_IA32_MISC_ENABLE_REGISTER MiscEnableMsr;
  880. if ((PcdGet32 (PcdControlFlowEnforcementPropertyMask) != 0) && mCetSupported) {
  881. AsmCpuid (CPUID_SIGNATURE, &RegEax, NULL, NULL, NULL);
  882. if (RegEax >= CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS) {
  883. AsmCpuidEx (CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS, CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_SUB_LEAF_INFO, NULL, NULL, &RegEcx, NULL);
  884. if ((RegEcx & CPUID_CET_SS) == 0) {
  885. mCetSupported = FALSE;
  886. PatchInstructionX86 (mPatchCetSupported, mCetSupported, 1);
  887. }
  888. } else {
  889. mCetSupported = FALSE;
  890. PatchInstructionX86 (mPatchCetSupported, mCetSupported, 1);
  891. }
  892. }
  893. if (mXdSupported) {
  894. AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
  895. if (RegEax <= CPUID_EXTENDED_FUNCTION) {
  896. //
  897. // Extended CPUID functions are not supported on this processor.
  898. //
  899. mXdSupported = FALSE;
  900. PatchInstructionX86 (gPatchXdSupported, mXdSupported, 1);
  901. }
  902. AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);
  903. if ((RegEdx & CPUID1_EDX_XD_SUPPORT) == 0) {
  904. //
  905. // Execute Disable Bit feature is not supported on this processor.
  906. //
  907. mXdSupported = FALSE;
  908. PatchInstructionX86 (gPatchXdSupported, mXdSupported, 1);
  909. }
  910. if (StandardSignatureIsAuthenticAMD ()) {
  911. //
  912. // AMD processors do not support MSR_IA32_MISC_ENABLE
  913. //
  914. PatchInstructionX86 (gPatchMsrIa32MiscEnableSupported, FALSE, 1);
  915. }
  916. }
  917. if (mBtsSupported) {
  918. AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, &RegEdx);
  919. if ((RegEdx & CPUID1_EDX_BTS_AVAILABLE) != 0) {
  920. //
  921. // Per IA32 manuals:
  922. // When CPUID.1:EDX[21] is set, the following BTS facilities are available:
  923. // 1. The BTS_UNAVAILABLE flag in the IA32_MISC_ENABLE MSR indicates the
  924. // availability of the BTS facilities, including the ability to set the BTS and
  925. // BTINT bits in the MSR_DEBUGCTLA MSR.
  926. // 2. The IA32_DS_AREA MSR can be programmed to point to the DS save area.
  927. //
  928. MiscEnableMsr.Uint64 = AsmReadMsr64 (MSR_IA32_MISC_ENABLE);
  929. if (MiscEnableMsr.Bits.BTS == 1) {
  930. //
  931. // BTS facilities is not supported if MSR_IA32_MISC_ENABLE.BTS bit is set.
  932. //
  933. mBtsSupported = FALSE;
  934. }
  935. }
  936. }
  937. }
  938. /**
  939. Enable single step.
  940. **/
  941. VOID
  942. ActivateSingleStepDB (
  943. VOID
  944. )
  945. {
  946. UINTN Dr6;
  947. Dr6 = AsmReadDr6 ();
  948. if ((Dr6 & DR6_SINGLE_STEP) != 0) {
  949. return;
  950. }
  951. Dr6 |= DR6_SINGLE_STEP;
  952. AsmWriteDr6 (Dr6);
  953. }
  954. /**
  955. Enable last branch.
  956. **/
  957. VOID
  958. ActivateLBR (
  959. VOID
  960. )
  961. {
  962. UINT64 DebugCtl;
  963. DebugCtl = AsmReadMsr64 (MSR_DEBUG_CTL);
  964. if ((DebugCtl & MSR_DEBUG_CTL_LBR) != 0) {
  965. return;
  966. }
  967. DebugCtl |= MSR_DEBUG_CTL_LBR;
  968. AsmWriteMsr64 (MSR_DEBUG_CTL, DebugCtl);
  969. }
  970. /**
  971. Enable branch trace store.
  972. @param CpuIndex The index of the processor.
  973. **/
  974. VOID
  975. ActivateBTS (
  976. IN UINTN CpuIndex
  977. )
  978. {
  979. UINT64 DebugCtl;
  980. DebugCtl = AsmReadMsr64 (MSR_DEBUG_CTL);
  981. if ((DebugCtl & MSR_DEBUG_CTL_BTS) != 0) {
  982. return;
  983. }
  984. AsmWriteMsr64 (MSR_DS_AREA, (UINT64)(UINTN)mMsrDsArea[CpuIndex]);
  985. DebugCtl |= (UINT64)(MSR_DEBUG_CTL_BTS | MSR_DEBUG_CTL_TR);
  986. DebugCtl &= ~((UINT64)MSR_DEBUG_CTL_BTINT);
  987. AsmWriteMsr64 (MSR_DEBUG_CTL, DebugCtl);
  988. }
  989. /**
  990. Increase SMI number in each SMI entry.
  991. **/
  992. VOID
  993. SmmProfileRecordSmiNum (
  994. VOID
  995. )
  996. {
  997. if (mSmmProfileStart) {
  998. mSmmProfileBase->NumSmis++;
  999. }
  1000. }
  1001. /**
  1002. Initialize processor environment for SMM profile.
  1003. @param CpuIndex The index of the processor.
  1004. **/
  1005. VOID
  1006. ActivateSmmProfile (
  1007. IN UINTN CpuIndex
  1008. )
  1009. {
  1010. //
  1011. // Enable Single Step DB#
  1012. //
  1013. ActivateSingleStepDB ();
  1014. if (mBtsSupported) {
  1015. //
  1016. // We can not get useful information from LER, so we have to use BTS.
  1017. //
  1018. ActivateLBR ();
  1019. //
  1020. // Enable BTS
  1021. //
  1022. ActivateBTS (CpuIndex);
  1023. }
  1024. }
  1025. /**
  1026. Initialize SMM profile in SMM CPU entry point.
  1027. @param[in] Cr3 The base address of the page tables to use in SMM.
  1028. **/
  1029. VOID
  1030. InitSmmProfile (
  1031. UINT32 Cr3
  1032. )
  1033. {
  1034. //
  1035. // Save Cr3
  1036. //
  1037. mSmmProfileCr3 = Cr3;
  1038. //
  1039. // Skip SMM profile initialization if feature is disabled
  1040. //
  1041. if (!FeaturePcdGet (PcdCpuSmmProfileEnable) &&
  1042. !HEAP_GUARD_NONSTOP_MODE &&
  1043. !NULL_DETECTION_NONSTOP_MODE)
  1044. {
  1045. return;
  1046. }
  1047. //
  1048. // Initialize SmmProfile here
  1049. //
  1050. InitSmmProfileInternal ();
  1051. //
  1052. // Initialize profile IDT.
  1053. //
  1054. InitIdtr ();
  1055. //
  1056. // Tell #PF handler to prepare a #DB subsequently.
  1057. //
  1058. mSetupDebugTrap = TRUE;
  1059. }
  1060. /**
  1061. Update page table to map the memory correctly in order to make the instruction
  1062. which caused page fault execute successfully. And it also save the original page
  1063. table to be restored in single-step exception.
  1064. @param PageTable PageTable Address.
  1065. @param PFAddress The memory address which caused page fault exception.
  1066. @param CpuIndex The index of the processor.
  1067. @param ErrorCode The Error code of exception.
  1068. **/
  1069. VOID
  1070. RestorePageTableBelow4G (
  1071. UINT64 *PageTable,
  1072. UINT64 PFAddress,
  1073. UINTN CpuIndex,
  1074. UINTN ErrorCode
  1075. )
  1076. {
  1077. UINTN PTIndex;
  1078. UINTN PFIndex;
  1079. IA32_CR4 Cr4;
  1080. BOOLEAN Enable5LevelPaging;
  1081. Cr4.UintN = AsmReadCr4 ();
  1082. Enable5LevelPaging = (BOOLEAN)(Cr4.Bits.LA57 == 1);
  1083. //
  1084. // PML5
  1085. //
  1086. if (Enable5LevelPaging) {
  1087. PTIndex = (UINTN)BitFieldRead64 (PFAddress, 48, 56);
  1088. ASSERT (PageTable[PTIndex] != 0);
  1089. PageTable = (UINT64 *)(UINTN)(PageTable[PTIndex] & PHYSICAL_ADDRESS_MASK);
  1090. }
  1091. //
  1092. // PML4
  1093. //
  1094. if (sizeof (UINT64) == sizeof (UINTN)) {
  1095. PTIndex = (UINTN)BitFieldRead64 (PFAddress, 39, 47);
  1096. ASSERT (PageTable[PTIndex] != 0);
  1097. PageTable = (UINT64 *)(UINTN)(PageTable[PTIndex] & PHYSICAL_ADDRESS_MASK);
  1098. }
  1099. //
  1100. // PDPTE
  1101. //
  1102. PTIndex = (UINTN)BitFieldRead64 (PFAddress, 30, 38);
  1103. ASSERT (PageTable[PTIndex] != 0);
  1104. PageTable = (UINT64 *)(UINTN)(PageTable[PTIndex] & PHYSICAL_ADDRESS_MASK);
  1105. //
  1106. // PD
  1107. //
  1108. PTIndex = (UINTN)BitFieldRead64 (PFAddress, 21, 29);
  1109. if ((PageTable[PTIndex] & IA32_PG_PS) != 0) {
  1110. //
  1111. // Large page
  1112. //
  1113. //
  1114. // Record old entries with non-present status
  1115. // Old entries include the memory which instruction is at and the memory which instruction access.
  1116. //
  1117. //
  1118. ASSERT (mPFEntryCount[CpuIndex] < MAX_PF_ENTRY_COUNT);
  1119. if (mPFEntryCount[CpuIndex] < MAX_PF_ENTRY_COUNT) {
  1120. PFIndex = mPFEntryCount[CpuIndex];
  1121. mLastPFEntryValue[CpuIndex][PFIndex] = PageTable[PTIndex];
  1122. mLastPFEntryPointer[CpuIndex][PFIndex] = &PageTable[PTIndex];
  1123. mPFEntryCount[CpuIndex]++;
  1124. }
  1125. //
  1126. // Set new entry
  1127. //
  1128. PageTable[PTIndex] = (PFAddress & ~((1ull << 21) - 1));
  1129. PageTable[PTIndex] |= (UINT64)IA32_PG_PS;
  1130. PageTable[PTIndex] |= (UINT64)PAGE_ATTRIBUTE_BITS;
  1131. if ((ErrorCode & IA32_PF_EC_ID) != 0) {
  1132. PageTable[PTIndex] &= ~IA32_PG_NX;
  1133. }
  1134. } else {
  1135. //
  1136. // Small page
  1137. //
  1138. ASSERT (PageTable[PTIndex] != 0);
  1139. PageTable = (UINT64 *)(UINTN)(PageTable[PTIndex] & PHYSICAL_ADDRESS_MASK);
  1140. //
  1141. // 4K PTE
  1142. //
  1143. PTIndex = (UINTN)BitFieldRead64 (PFAddress, 12, 20);
  1144. //
  1145. // Record old entries with non-present status
  1146. // Old entries include the memory which instruction is at and the memory which instruction access.
  1147. //
  1148. //
  1149. ASSERT (mPFEntryCount[CpuIndex] < MAX_PF_ENTRY_COUNT);
  1150. if (mPFEntryCount[CpuIndex] < MAX_PF_ENTRY_COUNT) {
  1151. PFIndex = mPFEntryCount[CpuIndex];
  1152. mLastPFEntryValue[CpuIndex][PFIndex] = PageTable[PTIndex];
  1153. mLastPFEntryPointer[CpuIndex][PFIndex] = &PageTable[PTIndex];
  1154. mPFEntryCount[CpuIndex]++;
  1155. }
  1156. //
  1157. // Set new entry
  1158. //
  1159. PageTable[PTIndex] = (PFAddress & ~((1ull << 12) - 1));
  1160. PageTable[PTIndex] |= (UINT64)PAGE_ATTRIBUTE_BITS;
  1161. if ((ErrorCode & IA32_PF_EC_ID) != 0) {
  1162. PageTable[PTIndex] &= ~IA32_PG_NX;
  1163. }
  1164. }
  1165. }
  1166. /**
  1167. Handler for Page Fault triggered by Guard page.
  1168. @param ErrorCode The Error code of exception.
  1169. **/
  1170. VOID
  1171. GuardPagePFHandler (
  1172. UINTN ErrorCode
  1173. )
  1174. {
  1175. UINT64 *PageTable;
  1176. UINT64 PFAddress;
  1177. UINT64 RestoreAddress;
  1178. UINTN RestorePageNumber;
  1179. UINTN CpuIndex;
  1180. PageTable = (UINT64 *)AsmReadCr3 ();
  1181. PFAddress = AsmReadCr2 ();
  1182. CpuIndex = GetCpuIndex ();
  1183. //
  1184. // Memory operation cross pages, like "rep mov" instruction, will cause
  1185. // infinite loop between this and Debug Trap handler. We have to make sure
  1186. // that current page and the page followed are both in PRESENT state.
  1187. //
  1188. RestorePageNumber = 2;
  1189. RestoreAddress = PFAddress;
  1190. while (RestorePageNumber > 0) {
  1191. RestorePageTableBelow4G (PageTable, RestoreAddress, CpuIndex, ErrorCode);
  1192. RestoreAddress += EFI_PAGE_SIZE;
  1193. RestorePageNumber--;
  1194. }
  1195. //
  1196. // Flush TLB
  1197. //
  1198. CpuFlushTlb ();
  1199. }
  1200. /**
  1201. The Page fault handler to save SMM profile data.
  1202. @param Rip The RIP when exception happens.
  1203. @param ErrorCode The Error code of exception.
  1204. **/
  1205. VOID
  1206. SmmProfilePFHandler (
  1207. UINTN Rip,
  1208. UINTN ErrorCode
  1209. )
  1210. {
  1211. UINT64 *PageTable;
  1212. UINT64 PFAddress;
  1213. UINT64 RestoreAddress;
  1214. UINTN RestorePageNumber;
  1215. UINTN CpuIndex;
  1216. UINTN Index;
  1217. UINT64 InstructionAddress;
  1218. UINTN MaxEntryNumber;
  1219. UINTN CurrentEntryNumber;
  1220. BOOLEAN IsValidPFAddress;
  1221. SMM_PROFILE_ENTRY *SmmProfileEntry;
  1222. UINT64 SmiCommand;
  1223. EFI_STATUS Status;
  1224. UINT8 SoftSmiValue;
  1225. EFI_SMM_SAVE_STATE_IO_INFO IoInfo;
  1226. if (!mSmmProfileStart) {
  1227. //
  1228. // If SMM profile does not start, call original page fault handler.
  1229. //
  1230. SmiDefaultPFHandler ();
  1231. return;
  1232. }
  1233. if (mBtsSupported) {
  1234. DisableBTS ();
  1235. }
  1236. IsValidPFAddress = FALSE;
  1237. PageTable = (UINT64 *)AsmReadCr3 ();
  1238. PFAddress = AsmReadCr2 ();
  1239. CpuIndex = GetCpuIndex ();
  1240. //
  1241. // Memory operation cross pages, like "rep mov" instruction, will cause
  1242. // infinite loop between this and Debug Trap handler. We have to make sure
  1243. // that current page and the page followed are both in PRESENT state.
  1244. //
  1245. RestorePageNumber = 2;
  1246. RestoreAddress = PFAddress;
  1247. while (RestorePageNumber > 0) {
  1248. if (RestoreAddress <= 0xFFFFFFFF) {
  1249. RestorePageTableBelow4G (PageTable, RestoreAddress, CpuIndex, ErrorCode);
  1250. } else {
  1251. RestorePageTableAbove4G (PageTable, RestoreAddress, CpuIndex, ErrorCode, &IsValidPFAddress);
  1252. }
  1253. RestoreAddress += EFI_PAGE_SIZE;
  1254. RestorePageNumber--;
  1255. }
  1256. if (!IsValidPFAddress) {
  1257. InstructionAddress = Rip;
  1258. if (((ErrorCode & IA32_PF_EC_ID) != 0) && (mBtsSupported)) {
  1259. //
  1260. // If it is instruction fetch failure, get the correct IP from BTS.
  1261. //
  1262. InstructionAddress = GetSourceFromDestinationOnBts (CpuIndex, Rip);
  1263. if (InstructionAddress == 0) {
  1264. //
  1265. // It indicates the instruction which caused page fault is not a jump instruction,
  1266. // set instruction address same as the page fault address.
  1267. //
  1268. InstructionAddress = PFAddress;
  1269. }
  1270. }
  1271. //
  1272. // Indicate it is not software SMI
  1273. //
  1274. SmiCommand = 0xFFFFFFFFFFFFFFFFULL;
  1275. for (Index = 0; Index < gSmst->NumberOfCpus; Index++) {
  1276. Status = SmmReadSaveState (&mSmmCpu, sizeof (IoInfo), EFI_SMM_SAVE_STATE_REGISTER_IO, Index, &IoInfo);
  1277. if (EFI_ERROR (Status)) {
  1278. continue;
  1279. }
  1280. if (IoInfo.IoPort == mSmiCommandPort) {
  1281. //
  1282. // A software SMI triggered by SMI command port has been found, get SmiCommand from SMI command port.
  1283. //
  1284. SoftSmiValue = IoRead8 (mSmiCommandPort);
  1285. SmiCommand = (UINT64)SoftSmiValue;
  1286. break;
  1287. }
  1288. }
  1289. SmmProfileEntry = (SMM_PROFILE_ENTRY *)(UINTN)(mSmmProfileBase + 1);
  1290. //
  1291. // Check if there is already a same entry in profile data.
  1292. //
  1293. for (Index = 0; Index < (UINTN)mSmmProfileBase->CurDataEntries; Index++) {
  1294. if ((SmmProfileEntry[Index].ErrorCode == (UINT64)ErrorCode) &&
  1295. (SmmProfileEntry[Index].Address == PFAddress) &&
  1296. (SmmProfileEntry[Index].CpuNum == (UINT64)CpuIndex) &&
  1297. (SmmProfileEntry[Index].Instruction == InstructionAddress) &&
  1298. (SmmProfileEntry[Index].SmiCmd == SmiCommand))
  1299. {
  1300. //
  1301. // Same record exist, need not save again.
  1302. //
  1303. break;
  1304. }
  1305. }
  1306. if (Index == mSmmProfileBase->CurDataEntries) {
  1307. CurrentEntryNumber = (UINTN)mSmmProfileBase->CurDataEntries;
  1308. MaxEntryNumber = (UINTN)mSmmProfileBase->MaxDataEntries;
  1309. if (FeaturePcdGet (PcdCpuSmmProfileRingBuffer)) {
  1310. CurrentEntryNumber = CurrentEntryNumber % MaxEntryNumber;
  1311. }
  1312. if (CurrentEntryNumber < MaxEntryNumber) {
  1313. //
  1314. // Log the new entry
  1315. //
  1316. SmmProfileEntry[CurrentEntryNumber].SmiNum = mSmmProfileBase->NumSmis;
  1317. SmmProfileEntry[CurrentEntryNumber].ErrorCode = (UINT64)ErrorCode;
  1318. SmmProfileEntry[CurrentEntryNumber].ApicId = (UINT64)GetApicId ();
  1319. SmmProfileEntry[CurrentEntryNumber].CpuNum = (UINT64)CpuIndex;
  1320. SmmProfileEntry[CurrentEntryNumber].Address = PFAddress;
  1321. SmmProfileEntry[CurrentEntryNumber].Instruction = InstructionAddress;
  1322. SmmProfileEntry[CurrentEntryNumber].SmiCmd = SmiCommand;
  1323. //
  1324. // Update current entry index and data size in the header.
  1325. //
  1326. mSmmProfileBase->CurDataEntries++;
  1327. mSmmProfileBase->CurDataSize = MultU64x64 (mSmmProfileBase->CurDataEntries, sizeof (SMM_PROFILE_ENTRY));
  1328. }
  1329. }
  1330. }
  1331. //
  1332. // Flush TLB
  1333. //
  1334. CpuFlushTlb ();
  1335. if (mBtsSupported) {
  1336. EnableBTS ();
  1337. }
  1338. }
  1339. /**
  1340. Replace INT1 exception handler to restore page table to absent/execute-disable state
  1341. in order to trigger page fault again to save SMM profile data..
  1342. **/
  1343. VOID
  1344. InitIdtr (
  1345. VOID
  1346. )
  1347. {
  1348. EFI_STATUS Status;
  1349. Status = SmmRegisterExceptionHandler (&mSmmCpuService, EXCEPT_IA32_DEBUG, DebugExceptionHandler);
  1350. ASSERT_EFI_ERROR (Status);
  1351. }