MpService.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. /** @file
  2. SMM MP service implementation
  3. Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.<BR>
  4. Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
  5. SPDX-License-Identifier: BSD-2-Clause-Patent
  6. **/
  7. #include "PiSmmCpuDxeSmm.h"
  8. //
  9. // Slots for all MTRR( FIXED MTRR + VARIABLE MTRR + MTRR_LIB_IA32_MTRR_DEF_TYPE)
  10. //
  11. MTRR_SETTINGS gSmiMtrrs;
  12. UINT64 gPhyMask;
  13. SMM_DISPATCHER_MP_SYNC_DATA *mSmmMpSyncData = NULL;
  14. UINTN mSmmMpSyncDataSize;
  15. SMM_CPU_SEMAPHORES mSmmCpuSemaphores;
  16. UINTN mSemaphoreSize;
  17. SPIN_LOCK *mPFLock = NULL;
  18. SMM_CPU_SYNC_MODE mCpuSmmSyncMode;
  19. BOOLEAN mMachineCheckSupported = FALSE;
  20. MM_COMPLETION mSmmStartupThisApToken;
  21. extern UINTN mSmmShadowStackSize;
  22. /**
  23. Performs an atomic compare exchange operation to get semaphore.
  24. The compare exchange operation must be performed using
  25. MP safe mechanisms.
  26. @param Sem IN: 32-bit unsigned integer
  27. OUT: original integer - 1
  28. @return Original integer - 1
  29. **/
  30. UINT32
  31. WaitForSemaphore (
  32. IN OUT volatile UINT32 *Sem
  33. )
  34. {
  35. UINT32 Value;
  36. for ( ; ;) {
  37. Value = *Sem;
  38. if ((Value != 0) &&
  39. (InterlockedCompareExchange32 (
  40. (UINT32 *)Sem,
  41. Value,
  42. Value - 1
  43. ) == Value))
  44. {
  45. break;
  46. }
  47. CpuPause ();
  48. }
  49. return Value - 1;
  50. }
  51. /**
  52. Performs an atomic compare exchange operation to release semaphore.
  53. The compare exchange operation must be performed using
  54. MP safe mechanisms.
  55. @param Sem IN: 32-bit unsigned integer
  56. OUT: original integer + 1
  57. @return Original integer + 1
  58. **/
  59. UINT32
  60. ReleaseSemaphore (
  61. IN OUT volatile UINT32 *Sem
  62. )
  63. {
  64. UINT32 Value;
  65. do {
  66. Value = *Sem;
  67. } while (Value + 1 != 0 &&
  68. InterlockedCompareExchange32 (
  69. (UINT32 *)Sem,
  70. Value,
  71. Value + 1
  72. ) != Value);
  73. return Value + 1;
  74. }
  75. /**
  76. Performs an atomic compare exchange operation to lock semaphore.
  77. The compare exchange operation must be performed using
  78. MP safe mechanisms.
  79. @param Sem IN: 32-bit unsigned integer
  80. OUT: -1
  81. @return Original integer
  82. **/
  83. UINT32
  84. LockdownSemaphore (
  85. IN OUT volatile UINT32 *Sem
  86. )
  87. {
  88. UINT32 Value;
  89. do {
  90. Value = *Sem;
  91. } while (InterlockedCompareExchange32 (
  92. (UINT32 *)Sem,
  93. Value,
  94. (UINT32)-1
  95. ) != Value);
  96. return Value;
  97. }
  98. /**
  99. Wait all APs to performs an atomic compare exchange operation to release semaphore.
  100. @param NumberOfAPs AP number
  101. **/
  102. VOID
  103. WaitForAllAPs (
  104. IN UINTN NumberOfAPs
  105. )
  106. {
  107. UINTN BspIndex;
  108. BspIndex = mSmmMpSyncData->BspIndex;
  109. while (NumberOfAPs-- > 0) {
  110. WaitForSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  111. }
  112. }
  113. /**
  114. Performs an atomic compare exchange operation to release semaphore
  115. for each AP.
  116. **/
  117. VOID
  118. ReleaseAllAPs (
  119. VOID
  120. )
  121. {
  122. UINTN Index;
  123. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  124. if (IsPresentAp (Index)) {
  125. ReleaseSemaphore (mSmmMpSyncData->CpuData[Index].Run);
  126. }
  127. }
  128. }
  129. /**
  130. Checks if all CPUs (with certain exceptions) have checked in for this SMI run
  131. @param Exceptions CPU Arrival exception flags.
  132. @retval TRUE if all CPUs the have checked in.
  133. @retval FALSE if at least one Normal AP hasn't checked in.
  134. **/
  135. BOOLEAN
  136. AllCpusInSmmWithExceptions (
  137. SMM_CPU_ARRIVAL_EXCEPTIONS Exceptions
  138. )
  139. {
  140. UINTN Index;
  141. SMM_CPU_DATA_BLOCK *CpuData;
  142. EFI_PROCESSOR_INFORMATION *ProcessorInfo;
  143. ASSERT (*mSmmMpSyncData->Counter <= mNumberOfCpus);
  144. if (*mSmmMpSyncData->Counter == mNumberOfCpus) {
  145. return TRUE;
  146. }
  147. CpuData = mSmmMpSyncData->CpuData;
  148. ProcessorInfo = gSmmCpuPrivate->ProcessorInfo;
  149. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  150. if (!(*(CpuData[Index].Present)) && (ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID)) {
  151. if (((Exceptions & ARRIVAL_EXCEPTION_DELAYED) != 0) && (SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmDelayed) != 0)) {
  152. continue;
  153. }
  154. if (((Exceptions & ARRIVAL_EXCEPTION_BLOCKED) != 0) && (SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmBlocked) != 0)) {
  155. continue;
  156. }
  157. if (((Exceptions & ARRIVAL_EXCEPTION_SMI_DISABLED) != 0) && (SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmEnable) != 0)) {
  158. continue;
  159. }
  160. return FALSE;
  161. }
  162. }
  163. return TRUE;
  164. }
  165. /**
  166. Has OS enabled Lmce in the MSR_IA32_MCG_EXT_CTL
  167. @retval TRUE Os enable lmce.
  168. @retval FALSE Os not enable lmce.
  169. **/
  170. BOOLEAN
  171. IsLmceOsEnabled (
  172. VOID
  173. )
  174. {
  175. MSR_IA32_MCG_CAP_REGISTER McgCap;
  176. MSR_IA32_FEATURE_CONTROL_REGISTER FeatureCtrl;
  177. MSR_IA32_MCG_EXT_CTL_REGISTER McgExtCtrl;
  178. McgCap.Uint64 = AsmReadMsr64 (MSR_IA32_MCG_CAP);
  179. if (McgCap.Bits.MCG_LMCE_P == 0) {
  180. return FALSE;
  181. }
  182. FeatureCtrl.Uint64 = AsmReadMsr64 (MSR_IA32_FEATURE_CONTROL);
  183. if (FeatureCtrl.Bits.LmceOn == 0) {
  184. return FALSE;
  185. }
  186. McgExtCtrl.Uint64 = AsmReadMsr64 (MSR_IA32_MCG_EXT_CTL);
  187. return (BOOLEAN)(McgExtCtrl.Bits.LMCE_EN == 1);
  188. }
  189. /**
  190. Return if Local machine check exception signaled.
  191. Indicates (when set) that a local machine check exception was generated. This indicates that the current machine-check event was
  192. delivered to only the logical processor.
  193. @retval TRUE LMCE was signaled.
  194. @retval FALSE LMCE was not signaled.
  195. **/
  196. BOOLEAN
  197. IsLmceSignaled (
  198. VOID
  199. )
  200. {
  201. MSR_IA32_MCG_STATUS_REGISTER McgStatus;
  202. McgStatus.Uint64 = AsmReadMsr64 (MSR_IA32_MCG_STATUS);
  203. return (BOOLEAN)(McgStatus.Bits.LMCE_S == 1);
  204. }
  205. /**
  206. Given timeout constraint, wait for all APs to arrive, and insure when this function returns, no AP will execute normal mode code before
  207. entering SMM, except SMI disabled APs.
  208. **/
  209. VOID
  210. SmmWaitForApArrival (
  211. VOID
  212. )
  213. {
  214. UINT64 Timer;
  215. UINTN Index;
  216. BOOLEAN LmceEn;
  217. BOOLEAN LmceSignal;
  218. ASSERT (*mSmmMpSyncData->Counter <= mNumberOfCpus);
  219. LmceEn = FALSE;
  220. LmceSignal = FALSE;
  221. if (mMachineCheckSupported) {
  222. LmceEn = IsLmceOsEnabled ();
  223. LmceSignal = IsLmceSignaled ();
  224. }
  225. //
  226. // Platform implementor should choose a timeout value appropriately:
  227. // - The timeout value should balance the SMM time constrains and the likelihood that delayed CPUs are excluded in the SMM run. Note
  228. // the SMI Handlers must ALWAYS take into account the cases that not all APs are available in an SMI run.
  229. // - The timeout value must, in the case of 2nd timeout, be at least long enough to give time for all APs to receive the SMI IPI
  230. // and either enter SMM or buffer the SMI, to insure there is no CPU running normal mode code when SMI handling starts. This will
  231. // be TRUE even if a blocked CPU is brought out of the blocked state by a normal mode CPU (before the normal mode CPU received the
  232. // SMI IPI), because with a buffered SMI, and CPU will enter SMM immediately after it is brought out of the blocked state.
  233. // - The timeout value must be longer than longest possible IO operation in the system
  234. //
  235. //
  236. // Sync with APs 1st timeout
  237. //
  238. for (Timer = StartSyncTimer ();
  239. !IsSyncTimerTimeout (Timer) && !(LmceEn && LmceSignal);
  240. )
  241. {
  242. mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmWithExceptions (ARRIVAL_EXCEPTION_BLOCKED | ARRIVAL_EXCEPTION_SMI_DISABLED);
  243. if (mSmmMpSyncData->AllApArrivedWithException) {
  244. break;
  245. }
  246. CpuPause ();
  247. }
  248. //
  249. // Not all APs have arrived, so we need 2nd round of timeout. IPIs should be sent to ALL none present APs,
  250. // because:
  251. // a) Delayed AP may have just come out of the delayed state. Blocked AP may have just been brought out of blocked state by some AP running
  252. // normal mode code. These APs need to be guaranteed to have an SMI pending to insure that once they are out of delayed / blocked state, they
  253. // enter SMI immediately without executing instructions in normal mode. Note traditional flow requires there are no APs doing normal mode
  254. // work while SMI handling is on-going.
  255. // b) As a consequence of SMI IPI sending, (spurious) SMI may occur after this SMM run.
  256. // c) ** NOTE **: Use SMI disabling feature VERY CAREFULLY (if at all) for traditional flow, because a processor in SMI-disabled state
  257. // will execute normal mode code, which breaks the traditional SMI handlers' assumption that no APs are doing normal
  258. // mode work while SMI handling is on-going.
  259. // d) We don't add code to check SMI disabling status to skip sending IPI to SMI disabled APs, because:
  260. // - In traditional flow, SMI disabling is discouraged.
  261. // - In relaxed flow, CheckApArrival() will check SMI disabling status before calling this function.
  262. // In both cases, adding SMI-disabling checking code increases overhead.
  263. //
  264. if (*mSmmMpSyncData->Counter < mNumberOfCpus) {
  265. //
  266. // Send SMI IPIs to bring outside processors in
  267. //
  268. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  269. if (!(*(mSmmMpSyncData->CpuData[Index].Present)) && (gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID)) {
  270. SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId);
  271. }
  272. }
  273. //
  274. // Sync with APs 2nd timeout.
  275. //
  276. for (Timer = StartSyncTimer ();
  277. !IsSyncTimerTimeout (Timer);
  278. )
  279. {
  280. mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmWithExceptions (ARRIVAL_EXCEPTION_BLOCKED | ARRIVAL_EXCEPTION_SMI_DISABLED);
  281. if (mSmmMpSyncData->AllApArrivedWithException) {
  282. break;
  283. }
  284. CpuPause ();
  285. }
  286. }
  287. return;
  288. }
  289. /**
  290. Replace OS MTRR's with SMI MTRR's.
  291. @param CpuIndex Processor Index
  292. **/
  293. VOID
  294. ReplaceOSMtrrs (
  295. IN UINTN CpuIndex
  296. )
  297. {
  298. SmmCpuFeaturesDisableSmrr ();
  299. //
  300. // Replace all MTRRs registers
  301. //
  302. MtrrSetAllMtrrs (&gSmiMtrrs);
  303. }
  304. /**
  305. Wheck whether task has been finished by all APs.
  306. @param BlockMode Whether did it in block mode or non-block mode.
  307. @retval TRUE Task has been finished by all APs.
  308. @retval FALSE Task not has been finished by all APs.
  309. **/
  310. BOOLEAN
  311. WaitForAllAPsNotBusy (
  312. IN BOOLEAN BlockMode
  313. )
  314. {
  315. UINTN Index;
  316. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  317. //
  318. // Ignore BSP and APs which not call in SMM.
  319. //
  320. if (!IsPresentAp (Index)) {
  321. continue;
  322. }
  323. if (BlockMode) {
  324. AcquireSpinLock (mSmmMpSyncData->CpuData[Index].Busy);
  325. ReleaseSpinLock (mSmmMpSyncData->CpuData[Index].Busy);
  326. } else {
  327. if (AcquireSpinLockOrFail (mSmmMpSyncData->CpuData[Index].Busy)) {
  328. ReleaseSpinLock (mSmmMpSyncData->CpuData[Index].Busy);
  329. } else {
  330. return FALSE;
  331. }
  332. }
  333. }
  334. return TRUE;
  335. }
  336. /**
  337. Check whether it is an present AP.
  338. @param CpuIndex The AP index which calls this function.
  339. @retval TRUE It's a present AP.
  340. @retval TRUE This is not an AP or it is not present.
  341. **/
  342. BOOLEAN
  343. IsPresentAp (
  344. IN UINTN CpuIndex
  345. )
  346. {
  347. return ((CpuIndex != gSmmCpuPrivate->SmmCoreEntryContext.CurrentlyExecutingCpu) &&
  348. *(mSmmMpSyncData->CpuData[CpuIndex].Present));
  349. }
  350. /**
  351. Clean up the status flags used during executing the procedure.
  352. @param CpuIndex The AP index which calls this function.
  353. **/
  354. VOID
  355. ReleaseToken (
  356. IN UINTN CpuIndex
  357. )
  358. {
  359. PROCEDURE_TOKEN *Token;
  360. Token = mSmmMpSyncData->CpuData[CpuIndex].Token;
  361. if (InterlockedDecrement (&Token->RunningApCount) == 0) {
  362. ReleaseSpinLock (Token->SpinLock);
  363. }
  364. mSmmMpSyncData->CpuData[CpuIndex].Token = NULL;
  365. }
  366. /**
  367. Free the tokens in the maintained list.
  368. **/
  369. VOID
  370. ResetTokens (
  371. VOID
  372. )
  373. {
  374. //
  375. // Reset the FirstFreeToken to the beginning of token list upon exiting SMI.
  376. //
  377. gSmmCpuPrivate->FirstFreeToken = GetFirstNode (&gSmmCpuPrivate->TokenList);
  378. }
  379. /**
  380. SMI handler for BSP.
  381. @param CpuIndex BSP processor Index
  382. @param SyncMode SMM MP sync mode
  383. **/
  384. VOID
  385. BSPHandler (
  386. IN UINTN CpuIndex,
  387. IN SMM_CPU_SYNC_MODE SyncMode
  388. )
  389. {
  390. UINTN Index;
  391. MTRR_SETTINGS Mtrrs;
  392. UINTN ApCount;
  393. BOOLEAN ClearTopLevelSmiResult;
  394. UINTN PresentCount;
  395. ASSERT (CpuIndex == mSmmMpSyncData->BspIndex);
  396. ApCount = 0;
  397. //
  398. // Flag BSP's presence
  399. //
  400. *mSmmMpSyncData->InsideSmm = TRUE;
  401. //
  402. // Initialize Debug Agent to start source level debug in BSP handler
  403. //
  404. InitializeDebugAgent (DEBUG_AGENT_INIT_ENTER_SMI, NULL, NULL);
  405. //
  406. // Mark this processor's presence
  407. //
  408. *(mSmmMpSyncData->CpuData[CpuIndex].Present) = TRUE;
  409. //
  410. // Clear platform top level SMI status bit before calling SMI handlers. If
  411. // we cleared it after SMI handlers are run, we would miss the SMI that
  412. // occurs after SMI handlers are done and before SMI status bit is cleared.
  413. //
  414. ClearTopLevelSmiResult = ClearTopLevelSmiStatus ();
  415. ASSERT (ClearTopLevelSmiResult == TRUE);
  416. //
  417. // Set running processor index
  418. //
  419. gSmmCpuPrivate->SmmCoreEntryContext.CurrentlyExecutingCpu = CpuIndex;
  420. //
  421. // If Traditional Sync Mode or need to configure MTRRs: gather all available APs.
  422. //
  423. if ((SyncMode == SmmCpuSyncModeTradition) || SmmCpuFeaturesNeedConfigureMtrrs ()) {
  424. //
  425. // Wait for APs to arrive
  426. //
  427. SmmWaitForApArrival ();
  428. //
  429. // Lock the counter down and retrieve the number of APs
  430. //
  431. *mSmmMpSyncData->AllCpusInSync = TRUE;
  432. ApCount = LockdownSemaphore (mSmmMpSyncData->Counter) - 1;
  433. //
  434. // Wait for all APs to get ready for programming MTRRs
  435. //
  436. WaitForAllAPs (ApCount);
  437. if (SmmCpuFeaturesNeedConfigureMtrrs ()) {
  438. //
  439. // Signal all APs it's time for backup MTRRs
  440. //
  441. ReleaseAllAPs ();
  442. //
  443. // WaitForSemaphore() may wait for ever if an AP happens to enter SMM at
  444. // exactly this point. Please make sure PcdCpuSmmMaxSyncLoops has been set
  445. // to a large enough value to avoid this situation.
  446. // Note: For HT capable CPUs, threads within a core share the same set of MTRRs.
  447. // We do the backup first and then set MTRR to avoid race condition for threads
  448. // in the same core.
  449. //
  450. MtrrGetAllMtrrs (&Mtrrs);
  451. //
  452. // Wait for all APs to complete their MTRR saving
  453. //
  454. WaitForAllAPs (ApCount);
  455. //
  456. // Let all processors program SMM MTRRs together
  457. //
  458. ReleaseAllAPs ();
  459. //
  460. // WaitForSemaphore() may wait for ever if an AP happens to enter SMM at
  461. // exactly this point. Please make sure PcdCpuSmmMaxSyncLoops has been set
  462. // to a large enough value to avoid this situation.
  463. //
  464. ReplaceOSMtrrs (CpuIndex);
  465. //
  466. // Wait for all APs to complete their MTRR programming
  467. //
  468. WaitForAllAPs (ApCount);
  469. }
  470. }
  471. //
  472. // The BUSY lock is initialized to Acquired state
  473. //
  474. AcquireSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy);
  475. //
  476. // Perform the pre tasks
  477. //
  478. PerformPreTasks ();
  479. //
  480. // Invoke SMM Foundation EntryPoint with the processor information context.
  481. //
  482. gSmmCpuPrivate->SmmCoreEntry (&gSmmCpuPrivate->SmmCoreEntryContext);
  483. //
  484. // Make sure all APs have completed their pending none-block tasks
  485. //
  486. WaitForAllAPsNotBusy (TRUE);
  487. //
  488. // Perform the remaining tasks
  489. //
  490. PerformRemainingTasks ();
  491. //
  492. // If Relaxed-AP Sync Mode: gather all available APs after BSP SMM handlers are done, and
  493. // make those APs to exit SMI synchronously. APs which arrive later will be excluded and
  494. // will run through freely.
  495. //
  496. if ((SyncMode != SmmCpuSyncModeTradition) && !SmmCpuFeaturesNeedConfigureMtrrs ()) {
  497. //
  498. // Lock the counter down and retrieve the number of APs
  499. //
  500. *mSmmMpSyncData->AllCpusInSync = TRUE;
  501. ApCount = LockdownSemaphore (mSmmMpSyncData->Counter) - 1;
  502. //
  503. // Make sure all APs have their Present flag set
  504. //
  505. while (TRUE) {
  506. PresentCount = 0;
  507. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  508. if (*(mSmmMpSyncData->CpuData[Index].Present)) {
  509. PresentCount++;
  510. }
  511. }
  512. if (PresentCount > ApCount) {
  513. break;
  514. }
  515. }
  516. }
  517. //
  518. // Notify all APs to exit
  519. //
  520. *mSmmMpSyncData->InsideSmm = FALSE;
  521. ReleaseAllAPs ();
  522. //
  523. // Wait for all APs to complete their pending tasks
  524. //
  525. WaitForAllAPs (ApCount);
  526. if (SmmCpuFeaturesNeedConfigureMtrrs ()) {
  527. //
  528. // Signal APs to restore MTRRs
  529. //
  530. ReleaseAllAPs ();
  531. //
  532. // Restore OS MTRRs
  533. //
  534. SmmCpuFeaturesReenableSmrr ();
  535. MtrrSetAllMtrrs (&Mtrrs);
  536. //
  537. // Wait for all APs to complete MTRR programming
  538. //
  539. WaitForAllAPs (ApCount);
  540. }
  541. //
  542. // Stop source level debug in BSP handler, the code below will not be
  543. // debugged.
  544. //
  545. InitializeDebugAgent (DEBUG_AGENT_INIT_EXIT_SMI, NULL, NULL);
  546. //
  547. // Signal APs to Reset states/semaphore for this processor
  548. //
  549. ReleaseAllAPs ();
  550. //
  551. // Perform pending operations for hot-plug
  552. //
  553. SmmCpuUpdate ();
  554. //
  555. // Clear the Present flag of BSP
  556. //
  557. *(mSmmMpSyncData->CpuData[CpuIndex].Present) = FALSE;
  558. //
  559. // Gather APs to exit SMM synchronously. Note the Present flag is cleared by now but
  560. // WaitForAllAps does not depend on the Present flag.
  561. //
  562. WaitForAllAPs (ApCount);
  563. //
  564. // Reset the tokens buffer.
  565. //
  566. ResetTokens ();
  567. //
  568. // Reset BspIndex to -1, meaning BSP has not been elected.
  569. //
  570. if (FeaturePcdGet (PcdCpuSmmEnableBspElection)) {
  571. mSmmMpSyncData->BspIndex = (UINT32)-1;
  572. }
  573. //
  574. // Allow APs to check in from this point on
  575. //
  576. *mSmmMpSyncData->Counter = 0;
  577. *mSmmMpSyncData->AllCpusInSync = FALSE;
  578. mSmmMpSyncData->AllApArrivedWithException = FALSE;
  579. }
  580. /**
  581. SMI handler for AP.
  582. @param CpuIndex AP processor Index.
  583. @param ValidSmi Indicates that current SMI is a valid SMI or not.
  584. @param SyncMode SMM MP sync mode.
  585. **/
  586. VOID
  587. APHandler (
  588. IN UINTN CpuIndex,
  589. IN BOOLEAN ValidSmi,
  590. IN SMM_CPU_SYNC_MODE SyncMode
  591. )
  592. {
  593. UINT64 Timer;
  594. UINTN BspIndex;
  595. MTRR_SETTINGS Mtrrs;
  596. EFI_STATUS ProcedureStatus;
  597. //
  598. // Timeout BSP
  599. //
  600. for (Timer = StartSyncTimer ();
  601. !IsSyncTimerTimeout (Timer) &&
  602. !(*mSmmMpSyncData->InsideSmm);
  603. )
  604. {
  605. CpuPause ();
  606. }
  607. if (!(*mSmmMpSyncData->InsideSmm)) {
  608. //
  609. // BSP timeout in the first round
  610. //
  611. if (mSmmMpSyncData->BspIndex != -1) {
  612. //
  613. // BSP Index is known
  614. //
  615. BspIndex = mSmmMpSyncData->BspIndex;
  616. ASSERT (CpuIndex != BspIndex);
  617. //
  618. // Send SMI IPI to bring BSP in
  619. //
  620. SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[BspIndex].ProcessorId);
  621. //
  622. // Now clock BSP for the 2nd time
  623. //
  624. for (Timer = StartSyncTimer ();
  625. !IsSyncTimerTimeout (Timer) &&
  626. !(*mSmmMpSyncData->InsideSmm);
  627. )
  628. {
  629. CpuPause ();
  630. }
  631. if (!(*mSmmMpSyncData->InsideSmm)) {
  632. //
  633. // Give up since BSP is unable to enter SMM
  634. // and signal the completion of this AP
  635. WaitForSemaphore (mSmmMpSyncData->Counter);
  636. return;
  637. }
  638. } else {
  639. //
  640. // Don't know BSP index. Give up without sending IPI to BSP.
  641. //
  642. WaitForSemaphore (mSmmMpSyncData->Counter);
  643. return;
  644. }
  645. }
  646. //
  647. // BSP is available
  648. //
  649. BspIndex = mSmmMpSyncData->BspIndex;
  650. ASSERT (CpuIndex != BspIndex);
  651. //
  652. // Mark this processor's presence
  653. //
  654. *(mSmmMpSyncData->CpuData[CpuIndex].Present) = TRUE;
  655. if ((SyncMode == SmmCpuSyncModeTradition) || SmmCpuFeaturesNeedConfigureMtrrs ()) {
  656. //
  657. // Notify BSP of arrival at this point
  658. //
  659. ReleaseSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  660. }
  661. if (SmmCpuFeaturesNeedConfigureMtrrs ()) {
  662. //
  663. // Wait for the signal from BSP to backup MTRRs
  664. //
  665. WaitForSemaphore (mSmmMpSyncData->CpuData[CpuIndex].Run);
  666. //
  667. // Backup OS MTRRs
  668. //
  669. MtrrGetAllMtrrs (&Mtrrs);
  670. //
  671. // Signal BSP the completion of this AP
  672. //
  673. ReleaseSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  674. //
  675. // Wait for BSP's signal to program MTRRs
  676. //
  677. WaitForSemaphore (mSmmMpSyncData->CpuData[CpuIndex].Run);
  678. //
  679. // Replace OS MTRRs with SMI MTRRs
  680. //
  681. ReplaceOSMtrrs (CpuIndex);
  682. //
  683. // Signal BSP the completion of this AP
  684. //
  685. ReleaseSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  686. }
  687. while (TRUE) {
  688. //
  689. // Wait for something to happen
  690. //
  691. WaitForSemaphore (mSmmMpSyncData->CpuData[CpuIndex].Run);
  692. //
  693. // Check if BSP wants to exit SMM
  694. //
  695. if (!(*mSmmMpSyncData->InsideSmm)) {
  696. break;
  697. }
  698. //
  699. // BUSY should be acquired by SmmStartupThisAp()
  700. //
  701. ASSERT (
  702. !AcquireSpinLockOrFail (mSmmMpSyncData->CpuData[CpuIndex].Busy)
  703. );
  704. //
  705. // Invoke the scheduled procedure
  706. //
  707. ProcedureStatus = (*mSmmMpSyncData->CpuData[CpuIndex].Procedure)(
  708. (VOID *)mSmmMpSyncData->CpuData[CpuIndex].Parameter
  709. );
  710. if (mSmmMpSyncData->CpuData[CpuIndex].Status != NULL) {
  711. *mSmmMpSyncData->CpuData[CpuIndex].Status = ProcedureStatus;
  712. }
  713. if (mSmmMpSyncData->CpuData[CpuIndex].Token != NULL) {
  714. ReleaseToken (CpuIndex);
  715. }
  716. //
  717. // Release BUSY
  718. //
  719. ReleaseSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy);
  720. }
  721. if (SmmCpuFeaturesNeedConfigureMtrrs ()) {
  722. //
  723. // Notify BSP the readiness of this AP to program MTRRs
  724. //
  725. ReleaseSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  726. //
  727. // Wait for the signal from BSP to program MTRRs
  728. //
  729. WaitForSemaphore (mSmmMpSyncData->CpuData[CpuIndex].Run);
  730. //
  731. // Restore OS MTRRs
  732. //
  733. SmmCpuFeaturesReenableSmrr ();
  734. MtrrSetAllMtrrs (&Mtrrs);
  735. }
  736. //
  737. // Notify BSP the readiness of this AP to Reset states/semaphore for this processor
  738. //
  739. ReleaseSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  740. //
  741. // Wait for the signal from BSP to Reset states/semaphore for this processor
  742. //
  743. WaitForSemaphore (mSmmMpSyncData->CpuData[CpuIndex].Run);
  744. //
  745. // Reset states/semaphore for this processor
  746. //
  747. *(mSmmMpSyncData->CpuData[CpuIndex].Present) = FALSE;
  748. //
  749. // Notify BSP the readiness of this AP to exit SMM
  750. //
  751. ReleaseSemaphore (mSmmMpSyncData->CpuData[BspIndex].Run);
  752. }
  753. /**
  754. Create 4G PageTable in SMRAM.
  755. @param[in] Is32BitPageTable Whether the page table is 32-bit PAE
  756. @return PageTable Address
  757. **/
  758. UINT32
  759. Gen4GPageTable (
  760. IN BOOLEAN Is32BitPageTable
  761. )
  762. {
  763. VOID *PageTable;
  764. UINTN Index;
  765. UINT64 *Pte;
  766. UINTN PagesNeeded;
  767. UINTN Low2MBoundary;
  768. UINTN High2MBoundary;
  769. UINTN Pages;
  770. UINTN GuardPage;
  771. UINT64 *Pdpte;
  772. UINTN PageIndex;
  773. UINTN PageAddress;
  774. Low2MBoundary = 0;
  775. High2MBoundary = 0;
  776. PagesNeeded = 0;
  777. if (FeaturePcdGet (PcdCpuSmmStackGuard)) {
  778. //
  779. // Add one more page for known good stack, then find the lower 2MB aligned address.
  780. //
  781. Low2MBoundary = (mSmmStackArrayBase + EFI_PAGE_SIZE) & ~(SIZE_2MB-1);
  782. //
  783. // Add two more pages for known good stack and stack guard page,
  784. // then find the lower 2MB aligned address.
  785. //
  786. High2MBoundary = (mSmmStackArrayEnd - mSmmStackSize - mSmmShadowStackSize + EFI_PAGE_SIZE * 2) & ~(SIZE_2MB-1);
  787. PagesNeeded = ((High2MBoundary - Low2MBoundary) / SIZE_2MB) + 1;
  788. }
  789. //
  790. // Allocate the page table
  791. //
  792. PageTable = AllocatePageTableMemory (5 + PagesNeeded);
  793. ASSERT (PageTable != NULL);
  794. PageTable = (VOID *)((UINTN)PageTable);
  795. Pte = (UINT64 *)PageTable;
  796. //
  797. // Zero out all page table entries first
  798. //
  799. ZeroMem (Pte, EFI_PAGES_TO_SIZE (1));
  800. //
  801. // Set Page Directory Pointers
  802. //
  803. for (Index = 0; Index < 4; Index++) {
  804. Pte[Index] = ((UINTN)PageTable + EFI_PAGE_SIZE * (Index + 1)) | mAddressEncMask |
  805. (Is32BitPageTable ? IA32_PAE_PDPTE_ATTRIBUTE_BITS : PAGE_ATTRIBUTE_BITS);
  806. }
  807. Pte += EFI_PAGE_SIZE / sizeof (*Pte);
  808. //
  809. // Fill in Page Directory Entries
  810. //
  811. for (Index = 0; Index < EFI_PAGE_SIZE * 4 / sizeof (*Pte); Index++) {
  812. Pte[Index] = (Index << 21) | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS;
  813. }
  814. Pdpte = (UINT64 *)PageTable;
  815. if (FeaturePcdGet (PcdCpuSmmStackGuard)) {
  816. Pages = (UINTN)PageTable + EFI_PAGES_TO_SIZE (5);
  817. GuardPage = mSmmStackArrayBase + EFI_PAGE_SIZE;
  818. for (PageIndex = Low2MBoundary; PageIndex <= High2MBoundary; PageIndex += SIZE_2MB) {
  819. Pte = (UINT64 *)(UINTN)(Pdpte[BitFieldRead32 ((UINT32)PageIndex, 30, 31)] & ~mAddressEncMask & ~(EFI_PAGE_SIZE - 1));
  820. Pte[BitFieldRead32 ((UINT32)PageIndex, 21, 29)] = (UINT64)Pages | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
  821. //
  822. // Fill in Page Table Entries
  823. //
  824. Pte = (UINT64 *)Pages;
  825. PageAddress = PageIndex;
  826. for (Index = 0; Index < EFI_PAGE_SIZE / sizeof (*Pte); Index++) {
  827. if (PageAddress == GuardPage) {
  828. //
  829. // Mark the guard page as non-present
  830. //
  831. Pte[Index] = PageAddress | mAddressEncMask;
  832. GuardPage += (mSmmStackSize + mSmmShadowStackSize);
  833. if (GuardPage > mSmmStackArrayEnd) {
  834. GuardPage = 0;
  835. }
  836. } else {
  837. Pte[Index] = PageAddress | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
  838. }
  839. PageAddress += EFI_PAGE_SIZE;
  840. }
  841. Pages += EFI_PAGE_SIZE;
  842. }
  843. }
  844. if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0) {
  845. Pte = (UINT64 *)(UINTN)(Pdpte[0] & ~mAddressEncMask & ~(EFI_PAGE_SIZE - 1));
  846. if ((Pte[0] & IA32_PG_PS) == 0) {
  847. // 4K-page entries are already mapped. Just hide the first one anyway.
  848. Pte = (UINT64 *)(UINTN)(Pte[0] & ~mAddressEncMask & ~(EFI_PAGE_SIZE - 1));
  849. Pte[0] &= ~(UINT64)IA32_PG_P; // Hide page 0
  850. } else {
  851. // Create 4K-page entries
  852. Pages = (UINTN)AllocatePageTableMemory (1);
  853. ASSERT (Pages != 0);
  854. Pte[0] = (UINT64)(Pages | mAddressEncMask | PAGE_ATTRIBUTE_BITS);
  855. Pte = (UINT64 *)Pages;
  856. PageAddress = 0;
  857. Pte[0] = PageAddress | mAddressEncMask; // Hide page 0 but present left
  858. for (Index = 1; Index < EFI_PAGE_SIZE / sizeof (*Pte); Index++) {
  859. PageAddress += EFI_PAGE_SIZE;
  860. Pte[Index] = PageAddress | mAddressEncMask | PAGE_ATTRIBUTE_BITS;
  861. }
  862. }
  863. }
  864. return (UINT32)(UINTN)PageTable;
  865. }
  866. /**
  867. Checks whether the input token is the current used token.
  868. @param[in] Token This parameter describes the token that was passed into DispatchProcedure or
  869. BroadcastProcedure.
  870. @retval TRUE The input token is the current used token.
  871. @retval FALSE The input token is not the current used token.
  872. **/
  873. BOOLEAN
  874. IsTokenInUse (
  875. IN SPIN_LOCK *Token
  876. )
  877. {
  878. LIST_ENTRY *Link;
  879. PROCEDURE_TOKEN *ProcToken;
  880. if (Token == NULL) {
  881. return FALSE;
  882. }
  883. Link = GetFirstNode (&gSmmCpuPrivate->TokenList);
  884. //
  885. // Only search used tokens.
  886. //
  887. while (Link != gSmmCpuPrivate->FirstFreeToken) {
  888. ProcToken = PROCEDURE_TOKEN_FROM_LINK (Link);
  889. if (ProcToken->SpinLock == Token) {
  890. return TRUE;
  891. }
  892. Link = GetNextNode (&gSmmCpuPrivate->TokenList, Link);
  893. }
  894. return FALSE;
  895. }
  896. /**
  897. Allocate buffer for the SPIN_LOCK and PROCEDURE_TOKEN.
  898. @return First token of the token buffer.
  899. **/
  900. LIST_ENTRY *
  901. AllocateTokenBuffer (
  902. VOID
  903. )
  904. {
  905. UINTN SpinLockSize;
  906. UINT32 TokenCountPerChunk;
  907. UINTN Index;
  908. SPIN_LOCK *SpinLock;
  909. UINT8 *SpinLockBuffer;
  910. PROCEDURE_TOKEN *ProcTokens;
  911. SpinLockSize = GetSpinLockProperties ();
  912. TokenCountPerChunk = FixedPcdGet32 (PcdCpuSmmMpTokenCountPerChunk);
  913. ASSERT (TokenCountPerChunk != 0);
  914. if (TokenCountPerChunk == 0) {
  915. DEBUG ((DEBUG_ERROR, "PcdCpuSmmMpTokenCountPerChunk should not be Zero!\n"));
  916. CpuDeadLoop ();
  917. }
  918. DEBUG ((DEBUG_INFO, "CpuSmm: SpinLock Size = 0x%x, PcdCpuSmmMpTokenCountPerChunk = 0x%x\n", SpinLockSize, TokenCountPerChunk));
  919. //
  920. // Separate the Spin_lock and Proc_token because the alignment requires by Spin_Lock.
  921. //
  922. SpinLockBuffer = AllocatePool (SpinLockSize * TokenCountPerChunk);
  923. ASSERT (SpinLockBuffer != NULL);
  924. ProcTokens = AllocatePool (sizeof (PROCEDURE_TOKEN) * TokenCountPerChunk);
  925. ASSERT (ProcTokens != NULL);
  926. for (Index = 0; Index < TokenCountPerChunk; Index++) {
  927. SpinLock = (SPIN_LOCK *)(SpinLockBuffer + SpinLockSize * Index);
  928. InitializeSpinLock (SpinLock);
  929. ProcTokens[Index].Signature = PROCEDURE_TOKEN_SIGNATURE;
  930. ProcTokens[Index].SpinLock = SpinLock;
  931. ProcTokens[Index].RunningApCount = 0;
  932. InsertTailList (&gSmmCpuPrivate->TokenList, &ProcTokens[Index].Link);
  933. }
  934. return &ProcTokens[0].Link;
  935. }
  936. /**
  937. Get the free token.
  938. If no free token, allocate new tokens then return the free one.
  939. @param RunningApsCount The Running Aps count for this token.
  940. @retval return the first free PROCEDURE_TOKEN.
  941. **/
  942. PROCEDURE_TOKEN *
  943. GetFreeToken (
  944. IN UINT32 RunningApsCount
  945. )
  946. {
  947. PROCEDURE_TOKEN *NewToken;
  948. //
  949. // If FirstFreeToken meets the end of token list, enlarge the token list.
  950. // Set FirstFreeToken to the first free token.
  951. //
  952. if (gSmmCpuPrivate->FirstFreeToken == &gSmmCpuPrivate->TokenList) {
  953. gSmmCpuPrivate->FirstFreeToken = AllocateTokenBuffer ();
  954. }
  955. NewToken = PROCEDURE_TOKEN_FROM_LINK (gSmmCpuPrivate->FirstFreeToken);
  956. gSmmCpuPrivate->FirstFreeToken = GetNextNode (&gSmmCpuPrivate->TokenList, gSmmCpuPrivate->FirstFreeToken);
  957. NewToken->RunningApCount = RunningApsCount;
  958. AcquireSpinLock (NewToken->SpinLock);
  959. return NewToken;
  960. }
  961. /**
  962. Checks status of specified AP.
  963. This function checks whether the specified AP has finished the task assigned
  964. by StartupThisAP(), and whether timeout expires.
  965. @param[in] Token This parameter describes the token that was passed into DispatchProcedure or
  966. BroadcastProcedure.
  967. @retval EFI_SUCCESS Specified AP has finished task assigned by StartupThisAPs().
  968. @retval EFI_NOT_READY Specified AP has not finished task and timeout has not expired.
  969. **/
  970. EFI_STATUS
  971. IsApReady (
  972. IN SPIN_LOCK *Token
  973. )
  974. {
  975. if (AcquireSpinLockOrFail (Token)) {
  976. ReleaseSpinLock (Token);
  977. return EFI_SUCCESS;
  978. }
  979. return EFI_NOT_READY;
  980. }
  981. /**
  982. Schedule a procedure to run on the specified CPU.
  983. @param[in] Procedure The address of the procedure to run
  984. @param[in] CpuIndex Target CPU Index
  985. @param[in,out] ProcArguments The parameter to pass to the procedure
  986. @param[in] Token This is an optional parameter that allows the caller to execute the
  987. procedure in a blocking or non-blocking fashion. If it is NULL the
  988. call is blocking, and the call will not return until the AP has
  989. completed the procedure. If the token is not NULL, the call will
  990. return immediately. The caller can check whether the procedure has
  991. completed with CheckOnProcedure or WaitForProcedure.
  992. @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for the APs to finish
  993. execution of Procedure, either for blocking or non-blocking mode.
  994. Zero means infinity. If the timeout expires before all APs return
  995. from Procedure, then Procedure on the failed APs is terminated. If
  996. the timeout expires in blocking mode, the call returns EFI_TIMEOUT.
  997. If the timeout expires in non-blocking mode, the timeout determined
  998. can be through CheckOnProcedure or WaitForProcedure.
  999. Note that timeout support is optional. Whether an implementation
  1000. supports this feature can be determined via the Attributes data
  1001. member.
  1002. @param[in,out] CpuStatus This optional pointer may be used to get the status code returned
  1003. by Procedure when it completes execution on the target AP, or with
  1004. EFI_TIMEOUT if the Procedure fails to complete within the optional
  1005. timeout. The implementation will update this variable with
  1006. EFI_NOT_READY prior to starting Procedure on the target AP.
  1007. @retval EFI_INVALID_PARAMETER CpuNumber not valid
  1008. @retval EFI_INVALID_PARAMETER CpuNumber specifying BSP
  1009. @retval EFI_INVALID_PARAMETER The AP specified by CpuNumber did not enter SMM
  1010. @retval EFI_INVALID_PARAMETER The AP specified by CpuNumber is busy
  1011. @retval EFI_SUCCESS The procedure has been successfully scheduled
  1012. **/
  1013. EFI_STATUS
  1014. InternalSmmStartupThisAp (
  1015. IN EFI_AP_PROCEDURE2 Procedure,
  1016. IN UINTN CpuIndex,
  1017. IN OUT VOID *ProcArguments OPTIONAL,
  1018. IN MM_COMPLETION *Token,
  1019. IN UINTN TimeoutInMicroseconds,
  1020. IN OUT EFI_STATUS *CpuStatus
  1021. )
  1022. {
  1023. PROCEDURE_TOKEN *ProcToken;
  1024. if (CpuIndex >= gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus) {
  1025. DEBUG ((DEBUG_ERROR, "CpuIndex(%d) >= gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus(%d)\n", CpuIndex, gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus));
  1026. return EFI_INVALID_PARAMETER;
  1027. }
  1028. if (CpuIndex == gSmmCpuPrivate->SmmCoreEntryContext.CurrentlyExecutingCpu) {
  1029. DEBUG ((DEBUG_ERROR, "CpuIndex(%d) == gSmmCpuPrivate->SmmCoreEntryContext.CurrentlyExecutingCpu\n", CpuIndex));
  1030. return EFI_INVALID_PARAMETER;
  1031. }
  1032. if (gSmmCpuPrivate->ProcessorInfo[CpuIndex].ProcessorId == INVALID_APIC_ID) {
  1033. return EFI_INVALID_PARAMETER;
  1034. }
  1035. if (!(*(mSmmMpSyncData->CpuData[CpuIndex].Present))) {
  1036. if (mSmmMpSyncData->EffectiveSyncMode == SmmCpuSyncModeTradition) {
  1037. DEBUG ((DEBUG_ERROR, "!mSmmMpSyncData->CpuData[%d].Present\n", CpuIndex));
  1038. }
  1039. return EFI_INVALID_PARAMETER;
  1040. }
  1041. if (gSmmCpuPrivate->Operation[CpuIndex] == SmmCpuRemove) {
  1042. if (!FeaturePcdGet (PcdCpuHotPlugSupport)) {
  1043. DEBUG ((DEBUG_ERROR, "gSmmCpuPrivate->Operation[%d] == SmmCpuRemove\n", CpuIndex));
  1044. }
  1045. return EFI_INVALID_PARAMETER;
  1046. }
  1047. if ((TimeoutInMicroseconds != 0) && ((mSmmMp.Attributes & EFI_MM_MP_TIMEOUT_SUPPORTED) == 0)) {
  1048. return EFI_INVALID_PARAMETER;
  1049. }
  1050. if (Procedure == NULL) {
  1051. return EFI_INVALID_PARAMETER;
  1052. }
  1053. AcquireSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy);
  1054. mSmmMpSyncData->CpuData[CpuIndex].Procedure = Procedure;
  1055. mSmmMpSyncData->CpuData[CpuIndex].Parameter = ProcArguments;
  1056. if (Token != NULL) {
  1057. if (Token != &mSmmStartupThisApToken) {
  1058. //
  1059. // When Token points to mSmmStartupThisApToken, this routine is called
  1060. // from SmmStartupThisAp() in non-blocking mode (PcdCpuSmmBlockStartupThisAp == FALSE).
  1061. //
  1062. // In this case, caller wants to startup AP procedure in non-blocking
  1063. // mode and cannot get the completion status from the Token because there
  1064. // is no way to return the Token to caller from SmmStartupThisAp().
  1065. // Caller needs to use its implementation specific way to query the completion status.
  1066. //
  1067. // There is no need to allocate a token for such case so the 3 overheads
  1068. // can be avoided:
  1069. // 1. Call AllocateTokenBuffer() when there is no free token.
  1070. // 2. Get a free token from the token buffer.
  1071. // 3. Call ReleaseToken() in APHandler().
  1072. //
  1073. ProcToken = GetFreeToken (1);
  1074. mSmmMpSyncData->CpuData[CpuIndex].Token = ProcToken;
  1075. *Token = (MM_COMPLETION)ProcToken->SpinLock;
  1076. }
  1077. }
  1078. mSmmMpSyncData->CpuData[CpuIndex].Status = CpuStatus;
  1079. if (mSmmMpSyncData->CpuData[CpuIndex].Status != NULL) {
  1080. *mSmmMpSyncData->CpuData[CpuIndex].Status = EFI_NOT_READY;
  1081. }
  1082. ReleaseSemaphore (mSmmMpSyncData->CpuData[CpuIndex].Run);
  1083. if (Token == NULL) {
  1084. AcquireSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy);
  1085. ReleaseSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy);
  1086. }
  1087. return EFI_SUCCESS;
  1088. }
  1089. /**
  1090. Worker function to execute a caller provided function on all enabled APs.
  1091. @param[in] Procedure A pointer to the function to be run on
  1092. enabled APs of the system.
  1093. @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for
  1094. APs to return from Procedure, either for
  1095. blocking or non-blocking mode.
  1096. @param[in,out] ProcedureArguments The parameter passed into Procedure for
  1097. all APs.
  1098. @param[in,out] Token This is an optional parameter that allows the caller to execute the
  1099. procedure in a blocking or non-blocking fashion. If it is NULL the
  1100. call is blocking, and the call will not return until the AP has
  1101. completed the procedure. If the token is not NULL, the call will
  1102. return immediately. The caller can check whether the procedure has
  1103. completed with CheckOnProcedure or WaitForProcedure.
  1104. @param[in,out] CPUStatus This optional pointer may be used to get the status code returned
  1105. by Procedure when it completes execution on the target AP, or with
  1106. EFI_TIMEOUT if the Procedure fails to complete within the optional
  1107. timeout. The implementation will update this variable with
  1108. EFI_NOT_READY prior to starting Procedure on the target AP.
  1109. @retval EFI_SUCCESS In blocking mode, all APs have finished before
  1110. the timeout expired.
  1111. @retval EFI_SUCCESS In non-blocking mode, function has been dispatched
  1112. to all enabled APs.
  1113. @retval others Failed to Startup all APs.
  1114. **/
  1115. EFI_STATUS
  1116. InternalSmmStartupAllAPs (
  1117. IN EFI_AP_PROCEDURE2 Procedure,
  1118. IN UINTN TimeoutInMicroseconds,
  1119. IN OUT VOID *ProcedureArguments OPTIONAL,
  1120. IN OUT MM_COMPLETION *Token,
  1121. IN OUT EFI_STATUS *CPUStatus
  1122. )
  1123. {
  1124. UINTN Index;
  1125. UINTN CpuCount;
  1126. PROCEDURE_TOKEN *ProcToken;
  1127. if ((TimeoutInMicroseconds != 0) && ((mSmmMp.Attributes & EFI_MM_MP_TIMEOUT_SUPPORTED) == 0)) {
  1128. return EFI_INVALID_PARAMETER;
  1129. }
  1130. if (Procedure == NULL) {
  1131. return EFI_INVALID_PARAMETER;
  1132. }
  1133. CpuCount = 0;
  1134. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  1135. if (IsPresentAp (Index)) {
  1136. CpuCount++;
  1137. if (gSmmCpuPrivate->Operation[Index] == SmmCpuRemove) {
  1138. return EFI_INVALID_PARAMETER;
  1139. }
  1140. if (!AcquireSpinLockOrFail (mSmmMpSyncData->CpuData[Index].Busy)) {
  1141. return EFI_NOT_READY;
  1142. }
  1143. ReleaseSpinLock (mSmmMpSyncData->CpuData[Index].Busy);
  1144. }
  1145. }
  1146. if (CpuCount == 0) {
  1147. return EFI_NOT_STARTED;
  1148. }
  1149. if (Token != NULL) {
  1150. ProcToken = GetFreeToken ((UINT32)mMaxNumberOfCpus);
  1151. *Token = (MM_COMPLETION)ProcToken->SpinLock;
  1152. } else {
  1153. ProcToken = NULL;
  1154. }
  1155. //
  1156. // Make sure all BUSY should be acquired.
  1157. //
  1158. // Because former code already check mSmmMpSyncData->CpuData[***].Busy for each AP.
  1159. // Here code always use AcquireSpinLock instead of AcquireSpinLockOrFail for not
  1160. // block mode.
  1161. //
  1162. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  1163. if (IsPresentAp (Index)) {
  1164. AcquireSpinLock (mSmmMpSyncData->CpuData[Index].Busy);
  1165. }
  1166. }
  1167. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  1168. if (IsPresentAp (Index)) {
  1169. mSmmMpSyncData->CpuData[Index].Procedure = (EFI_AP_PROCEDURE2)Procedure;
  1170. mSmmMpSyncData->CpuData[Index].Parameter = ProcedureArguments;
  1171. if (ProcToken != NULL) {
  1172. mSmmMpSyncData->CpuData[Index].Token = ProcToken;
  1173. }
  1174. if (CPUStatus != NULL) {
  1175. mSmmMpSyncData->CpuData[Index].Status = &CPUStatus[Index];
  1176. if (mSmmMpSyncData->CpuData[Index].Status != NULL) {
  1177. *mSmmMpSyncData->CpuData[Index].Status = EFI_NOT_READY;
  1178. }
  1179. }
  1180. } else {
  1181. //
  1182. // PI spec requirement:
  1183. // For every excluded processor, the array entry must contain a value of EFI_NOT_STARTED.
  1184. //
  1185. if (CPUStatus != NULL) {
  1186. CPUStatus[Index] = EFI_NOT_STARTED;
  1187. }
  1188. //
  1189. // Decrease the count to mark this processor(AP or BSP) as finished.
  1190. //
  1191. if (ProcToken != NULL) {
  1192. WaitForSemaphore (&ProcToken->RunningApCount);
  1193. }
  1194. }
  1195. }
  1196. ReleaseAllAPs ();
  1197. if (Token == NULL) {
  1198. //
  1199. // Make sure all APs have completed their tasks.
  1200. //
  1201. WaitForAllAPsNotBusy (TRUE);
  1202. }
  1203. return EFI_SUCCESS;
  1204. }
  1205. /**
  1206. ISO C99 6.5.2.2 "Function calls", paragraph 9:
  1207. If the function is defined with a type that is not compatible with
  1208. the type (of the expression) pointed to by the expression that
  1209. denotes the called function, the behavior is undefined.
  1210. So add below wrapper function to convert between EFI_AP_PROCEDURE
  1211. and EFI_AP_PROCEDURE2.
  1212. Wrapper for Procedures.
  1213. @param[in] Buffer Pointer to PROCEDURE_WRAPPER buffer.
  1214. **/
  1215. EFI_STATUS
  1216. EFIAPI
  1217. ProcedureWrapper (
  1218. IN VOID *Buffer
  1219. )
  1220. {
  1221. PROCEDURE_WRAPPER *Wrapper;
  1222. Wrapper = Buffer;
  1223. Wrapper->Procedure (Wrapper->ProcedureArgument);
  1224. return EFI_SUCCESS;
  1225. }
  1226. /**
  1227. Schedule a procedure to run on the specified CPU in blocking mode.
  1228. @param[in] Procedure The address of the procedure to run
  1229. @param[in] CpuIndex Target CPU Index
  1230. @param[in, out] ProcArguments The parameter to pass to the procedure
  1231. @retval EFI_INVALID_PARAMETER CpuNumber not valid
  1232. @retval EFI_INVALID_PARAMETER CpuNumber specifying BSP
  1233. @retval EFI_INVALID_PARAMETER The AP specified by CpuNumber did not enter SMM
  1234. @retval EFI_INVALID_PARAMETER The AP specified by CpuNumber is busy
  1235. @retval EFI_SUCCESS The procedure has been successfully scheduled
  1236. **/
  1237. EFI_STATUS
  1238. EFIAPI
  1239. SmmBlockingStartupThisAp (
  1240. IN EFI_AP_PROCEDURE Procedure,
  1241. IN UINTN CpuIndex,
  1242. IN OUT VOID *ProcArguments OPTIONAL
  1243. )
  1244. {
  1245. PROCEDURE_WRAPPER Wrapper;
  1246. Wrapper.Procedure = Procedure;
  1247. Wrapper.ProcedureArgument = ProcArguments;
  1248. //
  1249. // Use wrapper function to convert EFI_AP_PROCEDURE to EFI_AP_PROCEDURE2.
  1250. //
  1251. return InternalSmmStartupThisAp (ProcedureWrapper, CpuIndex, &Wrapper, NULL, 0, NULL);
  1252. }
  1253. /**
  1254. Schedule a procedure to run on the specified CPU.
  1255. @param Procedure The address of the procedure to run
  1256. @param CpuIndex Target CPU Index
  1257. @param ProcArguments The parameter to pass to the procedure
  1258. @retval EFI_INVALID_PARAMETER CpuNumber not valid
  1259. @retval EFI_INVALID_PARAMETER CpuNumber specifying BSP
  1260. @retval EFI_INVALID_PARAMETER The AP specified by CpuNumber did not enter SMM
  1261. @retval EFI_INVALID_PARAMETER The AP specified by CpuNumber is busy
  1262. @retval EFI_SUCCESS The procedure has been successfully scheduled
  1263. **/
  1264. EFI_STATUS
  1265. EFIAPI
  1266. SmmStartupThisAp (
  1267. IN EFI_AP_PROCEDURE Procedure,
  1268. IN UINTN CpuIndex,
  1269. IN OUT VOID *ProcArguments OPTIONAL
  1270. )
  1271. {
  1272. gSmmCpuPrivate->ApWrapperFunc[CpuIndex].Procedure = Procedure;
  1273. gSmmCpuPrivate->ApWrapperFunc[CpuIndex].ProcedureArgument = ProcArguments;
  1274. //
  1275. // Use wrapper function to convert EFI_AP_PROCEDURE to EFI_AP_PROCEDURE2.
  1276. //
  1277. return InternalSmmStartupThisAp (
  1278. ProcedureWrapper,
  1279. CpuIndex,
  1280. &gSmmCpuPrivate->ApWrapperFunc[CpuIndex],
  1281. FeaturePcdGet (PcdCpuSmmBlockStartupThisAp) ? NULL : &mSmmStartupThisApToken,
  1282. 0,
  1283. NULL
  1284. );
  1285. }
  1286. /**
  1287. This function sets DR6 & DR7 according to SMM save state, before running SMM C code.
  1288. They are useful when you want to enable hardware breakpoints in SMM without entry SMM mode.
  1289. NOTE: It might not be appreciated in runtime since it might
  1290. conflict with OS debugging facilities. Turn them off in RELEASE.
  1291. @param CpuIndex CPU Index
  1292. **/
  1293. VOID
  1294. EFIAPI
  1295. CpuSmmDebugEntry (
  1296. IN UINTN CpuIndex
  1297. )
  1298. {
  1299. SMRAM_SAVE_STATE_MAP *CpuSaveState;
  1300. if (FeaturePcdGet (PcdCpuSmmDebug)) {
  1301. ASSERT (CpuIndex < mMaxNumberOfCpus);
  1302. CpuSaveState = (SMRAM_SAVE_STATE_MAP *)gSmmCpuPrivate->CpuSaveState[CpuIndex];
  1303. if (mSmmSaveStateRegisterLma == EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT) {
  1304. AsmWriteDr6 (CpuSaveState->x86._DR6);
  1305. AsmWriteDr7 (CpuSaveState->x86._DR7);
  1306. } else {
  1307. AsmWriteDr6 ((UINTN)CpuSaveState->x64._DR6);
  1308. AsmWriteDr7 ((UINTN)CpuSaveState->x64._DR7);
  1309. }
  1310. }
  1311. }
  1312. /**
  1313. This function restores DR6 & DR7 to SMM save state.
  1314. NOTE: It might not be appreciated in runtime since it might
  1315. conflict with OS debugging facilities. Turn them off in RELEASE.
  1316. @param CpuIndex CPU Index
  1317. **/
  1318. VOID
  1319. EFIAPI
  1320. CpuSmmDebugExit (
  1321. IN UINTN CpuIndex
  1322. )
  1323. {
  1324. SMRAM_SAVE_STATE_MAP *CpuSaveState;
  1325. if (FeaturePcdGet (PcdCpuSmmDebug)) {
  1326. ASSERT (CpuIndex < mMaxNumberOfCpus);
  1327. CpuSaveState = (SMRAM_SAVE_STATE_MAP *)gSmmCpuPrivate->CpuSaveState[CpuIndex];
  1328. if (mSmmSaveStateRegisterLma == EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT) {
  1329. CpuSaveState->x86._DR7 = (UINT32)AsmReadDr7 ();
  1330. CpuSaveState->x86._DR6 = (UINT32)AsmReadDr6 ();
  1331. } else {
  1332. CpuSaveState->x64._DR7 = AsmReadDr7 ();
  1333. CpuSaveState->x64._DR6 = AsmReadDr6 ();
  1334. }
  1335. }
  1336. }
  1337. /**
  1338. C function for SMI entry, each processor comes here upon SMI trigger.
  1339. @param CpuIndex CPU Index
  1340. **/
  1341. VOID
  1342. EFIAPI
  1343. SmiRendezvous (
  1344. IN UINTN CpuIndex
  1345. )
  1346. {
  1347. EFI_STATUS Status;
  1348. BOOLEAN ValidSmi;
  1349. BOOLEAN IsBsp;
  1350. BOOLEAN BspInProgress;
  1351. UINTN Index;
  1352. UINTN Cr2;
  1353. ASSERT (CpuIndex < mMaxNumberOfCpus);
  1354. //
  1355. // Save Cr2 because Page Fault exception in SMM may override its value,
  1356. // when using on-demand paging for above 4G memory.
  1357. //
  1358. Cr2 = 0;
  1359. SaveCr2 (&Cr2);
  1360. //
  1361. // Call the user register Startup function first.
  1362. //
  1363. if (mSmmMpSyncData->StartupProcedure != NULL) {
  1364. mSmmMpSyncData->StartupProcedure (mSmmMpSyncData->StartupProcArgs);
  1365. }
  1366. //
  1367. // Perform CPU specific entry hooks
  1368. //
  1369. SmmCpuFeaturesRendezvousEntry (CpuIndex);
  1370. //
  1371. // Determine if this is a valid SMI
  1372. //
  1373. ValidSmi = PlatformValidSmi ();
  1374. //
  1375. // Determine if BSP has been already in progress. Note this must be checked after
  1376. // ValidSmi because BSP may clear a valid SMI source after checking in.
  1377. //
  1378. BspInProgress = *mSmmMpSyncData->InsideSmm;
  1379. if (!BspInProgress && !ValidSmi) {
  1380. //
  1381. // If we reach here, it means when we sampled the ValidSmi flag, SMI status had not
  1382. // been cleared by BSP in a new SMI run (so we have a truly invalid SMI), or SMI
  1383. // status had been cleared by BSP and an existing SMI run has almost ended. (Note
  1384. // we sampled ValidSmi flag BEFORE judging BSP-in-progress status.) In both cases, there
  1385. // is nothing we need to do.
  1386. //
  1387. goto Exit;
  1388. } else {
  1389. //
  1390. // Signal presence of this processor
  1391. //
  1392. if (ReleaseSemaphore (mSmmMpSyncData->Counter) == 0) {
  1393. //
  1394. // BSP has already ended the synchronization, so QUIT!!!
  1395. //
  1396. //
  1397. // Wait for BSP's signal to finish SMI
  1398. //
  1399. while (*mSmmMpSyncData->AllCpusInSync) {
  1400. CpuPause ();
  1401. }
  1402. goto Exit;
  1403. } else {
  1404. //
  1405. // The BUSY lock is initialized to Released state.
  1406. // This needs to be done early enough to be ready for BSP's SmmStartupThisAp() call.
  1407. // E.g., with Relaxed AP flow, SmmStartupThisAp() may be called immediately
  1408. // after AP's present flag is detected.
  1409. //
  1410. InitializeSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy);
  1411. }
  1412. if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {
  1413. ActivateSmmProfile (CpuIndex);
  1414. }
  1415. if (BspInProgress) {
  1416. //
  1417. // BSP has been elected. Follow AP path, regardless of ValidSmi flag
  1418. // as BSP may have cleared the SMI status
  1419. //
  1420. APHandler (CpuIndex, ValidSmi, mSmmMpSyncData->EffectiveSyncMode);
  1421. } else {
  1422. //
  1423. // We have a valid SMI
  1424. //
  1425. //
  1426. // Elect BSP
  1427. //
  1428. IsBsp = FALSE;
  1429. if (FeaturePcdGet (PcdCpuSmmEnableBspElection)) {
  1430. if (!mSmmMpSyncData->SwitchBsp || mSmmMpSyncData->CandidateBsp[CpuIndex]) {
  1431. //
  1432. // Call platform hook to do BSP election
  1433. //
  1434. Status = PlatformSmmBspElection (&IsBsp);
  1435. if (EFI_SUCCESS == Status) {
  1436. //
  1437. // Platform hook determines successfully
  1438. //
  1439. if (IsBsp) {
  1440. mSmmMpSyncData->BspIndex = (UINT32)CpuIndex;
  1441. }
  1442. } else {
  1443. //
  1444. // Platform hook fails to determine, use default BSP election method
  1445. //
  1446. InterlockedCompareExchange32 (
  1447. (UINT32 *)&mSmmMpSyncData->BspIndex,
  1448. (UINT32)-1,
  1449. (UINT32)CpuIndex
  1450. );
  1451. }
  1452. }
  1453. }
  1454. //
  1455. // "mSmmMpSyncData->BspIndex == CpuIndex" means this is the BSP
  1456. //
  1457. if (mSmmMpSyncData->BspIndex == CpuIndex) {
  1458. //
  1459. // Clear last request for SwitchBsp.
  1460. //
  1461. if (mSmmMpSyncData->SwitchBsp) {
  1462. mSmmMpSyncData->SwitchBsp = FALSE;
  1463. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  1464. mSmmMpSyncData->CandidateBsp[Index] = FALSE;
  1465. }
  1466. }
  1467. if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {
  1468. SmmProfileRecordSmiNum ();
  1469. }
  1470. //
  1471. // BSP Handler is always called with a ValidSmi == TRUE
  1472. //
  1473. BSPHandler (CpuIndex, mSmmMpSyncData->EffectiveSyncMode);
  1474. } else {
  1475. APHandler (CpuIndex, ValidSmi, mSmmMpSyncData->EffectiveSyncMode);
  1476. }
  1477. }
  1478. ASSERT (*mSmmMpSyncData->CpuData[CpuIndex].Run == 0);
  1479. //
  1480. // Wait for BSP's signal to exit SMI
  1481. //
  1482. while (*mSmmMpSyncData->AllCpusInSync) {
  1483. CpuPause ();
  1484. }
  1485. }
  1486. Exit:
  1487. SmmCpuFeaturesRendezvousExit (CpuIndex);
  1488. //
  1489. // Restore Cr2
  1490. //
  1491. RestoreCr2 (Cr2);
  1492. }
  1493. /**
  1494. Allocate buffer for SpinLock and Wrapper function buffer.
  1495. **/
  1496. VOID
  1497. InitializeDataForMmMp (
  1498. VOID
  1499. )
  1500. {
  1501. gSmmCpuPrivate->ApWrapperFunc = AllocatePool (sizeof (PROCEDURE_WRAPPER) * gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus);
  1502. ASSERT (gSmmCpuPrivate->ApWrapperFunc != NULL);
  1503. InitializeListHead (&gSmmCpuPrivate->TokenList);
  1504. gSmmCpuPrivate->FirstFreeToken = AllocateTokenBuffer ();
  1505. }
  1506. /**
  1507. Allocate buffer for all semaphores and spin locks.
  1508. **/
  1509. VOID
  1510. InitializeSmmCpuSemaphores (
  1511. VOID
  1512. )
  1513. {
  1514. UINTN ProcessorCount;
  1515. UINTN TotalSize;
  1516. UINTN GlobalSemaphoresSize;
  1517. UINTN CpuSemaphoresSize;
  1518. UINTN SemaphoreSize;
  1519. UINTN Pages;
  1520. UINTN *SemaphoreBlock;
  1521. UINTN SemaphoreAddr;
  1522. SemaphoreSize = GetSpinLockProperties ();
  1523. ProcessorCount = gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus;
  1524. GlobalSemaphoresSize = (sizeof (SMM_CPU_SEMAPHORE_GLOBAL) / sizeof (VOID *)) * SemaphoreSize;
  1525. CpuSemaphoresSize = (sizeof (SMM_CPU_SEMAPHORE_CPU) / sizeof (VOID *)) * ProcessorCount * SemaphoreSize;
  1526. TotalSize = GlobalSemaphoresSize + CpuSemaphoresSize;
  1527. DEBUG ((DEBUG_INFO, "One Semaphore Size = 0x%x\n", SemaphoreSize));
  1528. DEBUG ((DEBUG_INFO, "Total Semaphores Size = 0x%x\n", TotalSize));
  1529. Pages = EFI_SIZE_TO_PAGES (TotalSize);
  1530. SemaphoreBlock = AllocatePages (Pages);
  1531. ASSERT (SemaphoreBlock != NULL);
  1532. ZeroMem (SemaphoreBlock, TotalSize);
  1533. SemaphoreAddr = (UINTN)SemaphoreBlock;
  1534. mSmmCpuSemaphores.SemaphoreGlobal.Counter = (UINT32 *)SemaphoreAddr;
  1535. SemaphoreAddr += SemaphoreSize;
  1536. mSmmCpuSemaphores.SemaphoreGlobal.InsideSmm = (BOOLEAN *)SemaphoreAddr;
  1537. SemaphoreAddr += SemaphoreSize;
  1538. mSmmCpuSemaphores.SemaphoreGlobal.AllCpusInSync = (BOOLEAN *)SemaphoreAddr;
  1539. SemaphoreAddr += SemaphoreSize;
  1540. mSmmCpuSemaphores.SemaphoreGlobal.PFLock = (SPIN_LOCK *)SemaphoreAddr;
  1541. SemaphoreAddr += SemaphoreSize;
  1542. mSmmCpuSemaphores.SemaphoreGlobal.CodeAccessCheckLock
  1543. = (SPIN_LOCK *)SemaphoreAddr;
  1544. SemaphoreAddr += SemaphoreSize;
  1545. SemaphoreAddr = (UINTN)SemaphoreBlock + GlobalSemaphoresSize;
  1546. mSmmCpuSemaphores.SemaphoreCpu.Busy = (SPIN_LOCK *)SemaphoreAddr;
  1547. SemaphoreAddr += ProcessorCount * SemaphoreSize;
  1548. mSmmCpuSemaphores.SemaphoreCpu.Run = (UINT32 *)SemaphoreAddr;
  1549. SemaphoreAddr += ProcessorCount * SemaphoreSize;
  1550. mSmmCpuSemaphores.SemaphoreCpu.Present = (BOOLEAN *)SemaphoreAddr;
  1551. mPFLock = mSmmCpuSemaphores.SemaphoreGlobal.PFLock;
  1552. mConfigSmmCodeAccessCheckLock = mSmmCpuSemaphores.SemaphoreGlobal.CodeAccessCheckLock;
  1553. mSemaphoreSize = SemaphoreSize;
  1554. }
  1555. /**
  1556. Initialize un-cacheable data.
  1557. **/
  1558. VOID
  1559. EFIAPI
  1560. InitializeMpSyncData (
  1561. VOID
  1562. )
  1563. {
  1564. UINTN CpuIndex;
  1565. if (mSmmMpSyncData != NULL) {
  1566. //
  1567. // mSmmMpSyncDataSize includes one structure of SMM_DISPATCHER_MP_SYNC_DATA, one
  1568. // CpuData array of SMM_CPU_DATA_BLOCK and one CandidateBsp array of BOOLEAN.
  1569. //
  1570. ZeroMem (mSmmMpSyncData, mSmmMpSyncDataSize);
  1571. mSmmMpSyncData->CpuData = (SMM_CPU_DATA_BLOCK *)((UINT8 *)mSmmMpSyncData + sizeof (SMM_DISPATCHER_MP_SYNC_DATA));
  1572. mSmmMpSyncData->CandidateBsp = (BOOLEAN *)(mSmmMpSyncData->CpuData + gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus);
  1573. if (FeaturePcdGet (PcdCpuSmmEnableBspElection)) {
  1574. //
  1575. // Enable BSP election by setting BspIndex to -1
  1576. //
  1577. mSmmMpSyncData->BspIndex = (UINT32)-1;
  1578. }
  1579. mSmmMpSyncData->EffectiveSyncMode = mCpuSmmSyncMode;
  1580. mSmmMpSyncData->Counter = mSmmCpuSemaphores.SemaphoreGlobal.Counter;
  1581. mSmmMpSyncData->InsideSmm = mSmmCpuSemaphores.SemaphoreGlobal.InsideSmm;
  1582. mSmmMpSyncData->AllCpusInSync = mSmmCpuSemaphores.SemaphoreGlobal.AllCpusInSync;
  1583. ASSERT (
  1584. mSmmMpSyncData->Counter != NULL && mSmmMpSyncData->InsideSmm != NULL &&
  1585. mSmmMpSyncData->AllCpusInSync != NULL
  1586. );
  1587. *mSmmMpSyncData->Counter = 0;
  1588. *mSmmMpSyncData->InsideSmm = FALSE;
  1589. *mSmmMpSyncData->AllCpusInSync = FALSE;
  1590. mSmmMpSyncData->AllApArrivedWithException = FALSE;
  1591. for (CpuIndex = 0; CpuIndex < gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus; CpuIndex++) {
  1592. mSmmMpSyncData->CpuData[CpuIndex].Busy =
  1593. (SPIN_LOCK *)((UINTN)mSmmCpuSemaphores.SemaphoreCpu.Busy + mSemaphoreSize * CpuIndex);
  1594. mSmmMpSyncData->CpuData[CpuIndex].Run =
  1595. (UINT32 *)((UINTN)mSmmCpuSemaphores.SemaphoreCpu.Run + mSemaphoreSize * CpuIndex);
  1596. mSmmMpSyncData->CpuData[CpuIndex].Present =
  1597. (BOOLEAN *)((UINTN)mSmmCpuSemaphores.SemaphoreCpu.Present + mSemaphoreSize * CpuIndex);
  1598. *(mSmmMpSyncData->CpuData[CpuIndex].Busy) = 0;
  1599. *(mSmmMpSyncData->CpuData[CpuIndex].Run) = 0;
  1600. *(mSmmMpSyncData->CpuData[CpuIndex].Present) = FALSE;
  1601. }
  1602. }
  1603. }
  1604. /**
  1605. Initialize global data for MP synchronization.
  1606. @param Stacks Base address of SMI stack buffer for all processors.
  1607. @param StackSize Stack size for each processor in SMM.
  1608. @param ShadowStackSize Shadow Stack size for each processor in SMM.
  1609. **/
  1610. UINT32
  1611. InitializeMpServiceData (
  1612. IN VOID *Stacks,
  1613. IN UINTN StackSize,
  1614. IN UINTN ShadowStackSize
  1615. )
  1616. {
  1617. UINT32 Cr3;
  1618. UINTN Index;
  1619. UINT8 *GdtTssTables;
  1620. UINTN GdtTableStepSize;
  1621. CPUID_VERSION_INFO_EDX RegEdx;
  1622. UINT32 MaxExtendedFunction;
  1623. CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize;
  1624. //
  1625. // Determine if this CPU supports machine check
  1626. //
  1627. AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, &RegEdx.Uint32);
  1628. mMachineCheckSupported = (BOOLEAN)(RegEdx.Bits.MCA == 1);
  1629. //
  1630. // Allocate memory for all locks and semaphores
  1631. //
  1632. InitializeSmmCpuSemaphores ();
  1633. //
  1634. // Initialize mSmmMpSyncData
  1635. //
  1636. mSmmMpSyncDataSize = sizeof (SMM_DISPATCHER_MP_SYNC_DATA) +
  1637. (sizeof (SMM_CPU_DATA_BLOCK) + sizeof (BOOLEAN)) * gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus;
  1638. mSmmMpSyncData = (SMM_DISPATCHER_MP_SYNC_DATA *)AllocatePages (EFI_SIZE_TO_PAGES (mSmmMpSyncDataSize));
  1639. ASSERT (mSmmMpSyncData != NULL);
  1640. mCpuSmmSyncMode = (SMM_CPU_SYNC_MODE)PcdGet8 (PcdCpuSmmSyncMode);
  1641. InitializeMpSyncData ();
  1642. //
  1643. // Initialize physical address mask
  1644. // NOTE: Physical memory above virtual address limit is not supported !!!
  1645. //
  1646. AsmCpuid (CPUID_EXTENDED_FUNCTION, &MaxExtendedFunction, NULL, NULL, NULL);
  1647. if (MaxExtendedFunction >= CPUID_VIR_PHY_ADDRESS_SIZE) {
  1648. AsmCpuid (CPUID_VIR_PHY_ADDRESS_SIZE, &VirPhyAddressSize.Uint32, NULL, NULL, NULL);
  1649. } else {
  1650. VirPhyAddressSize.Bits.PhysicalAddressBits = 36;
  1651. }
  1652. gPhyMask = LShiftU64 (1, VirPhyAddressSize.Bits.PhysicalAddressBits) - 1;
  1653. //
  1654. // Clear the low 12 bits
  1655. //
  1656. gPhyMask &= 0xfffffffffffff000ULL;
  1657. //
  1658. // Create page tables
  1659. //
  1660. Cr3 = SmmInitPageTable ();
  1661. GdtTssTables = InitGdt (Cr3, &GdtTableStepSize);
  1662. //
  1663. // Install SMI handler for each CPU
  1664. //
  1665. for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
  1666. InstallSmiHandler (
  1667. Index,
  1668. (UINT32)mCpuHotPlugData.SmBase[Index],
  1669. (VOID *)((UINTN)Stacks + (StackSize + ShadowStackSize) * Index),
  1670. StackSize,
  1671. (UINTN)(GdtTssTables + GdtTableStepSize * Index),
  1672. gcSmiGdtr.Limit + 1,
  1673. gcSmiIdtr.Base,
  1674. gcSmiIdtr.Limit + 1,
  1675. Cr3
  1676. );
  1677. }
  1678. //
  1679. // Record current MTRR settings
  1680. //
  1681. ZeroMem (&gSmiMtrrs, sizeof (gSmiMtrrs));
  1682. MtrrGetAllMtrrs (&gSmiMtrrs);
  1683. return Cr3;
  1684. }
  1685. /**
  1686. Register the SMM Foundation entry point.
  1687. @param This Pointer to EFI_SMM_CONFIGURATION_PROTOCOL instance
  1688. @param SmmEntryPoint SMM Foundation EntryPoint
  1689. @retval EFI_SUCCESS Successfully to register SMM foundation entry point
  1690. **/
  1691. EFI_STATUS
  1692. EFIAPI
  1693. RegisterSmmEntry (
  1694. IN CONST EFI_SMM_CONFIGURATION_PROTOCOL *This,
  1695. IN EFI_SMM_ENTRY_POINT SmmEntryPoint
  1696. )
  1697. {
  1698. //
  1699. // Record SMM Foundation EntryPoint, later invoke it on SMI entry vector.
  1700. //
  1701. gSmmCpuPrivate->SmmCoreEntry = SmmEntryPoint;
  1702. return EFI_SUCCESS;
  1703. }
  1704. /**
  1705. Register the SMM Foundation entry point.
  1706. @param[in] Procedure A pointer to the code stream to be run on the designated target AP
  1707. of the system. Type EFI_AP_PROCEDURE is defined below in Volume 2
  1708. with the related definitions of
  1709. EFI_MP_SERVICES_PROTOCOL.StartupAllAPs.
  1710. If caller may pass a value of NULL to deregister any existing
  1711. startup procedure.
  1712. @param[in,out] ProcedureArguments Allows the caller to pass a list of parameters to the code that is
  1713. run by the AP. It is an optional common mailbox between APs and
  1714. the caller to share information
  1715. @retval EFI_SUCCESS The Procedure has been set successfully.
  1716. @retval EFI_INVALID_PARAMETER The Procedure is NULL but ProcedureArguments not NULL.
  1717. **/
  1718. EFI_STATUS
  1719. RegisterStartupProcedure (
  1720. IN EFI_AP_PROCEDURE Procedure,
  1721. IN OUT VOID *ProcedureArguments OPTIONAL
  1722. )
  1723. {
  1724. if ((Procedure == NULL) && (ProcedureArguments != NULL)) {
  1725. return EFI_INVALID_PARAMETER;
  1726. }
  1727. if (mSmmMpSyncData == NULL) {
  1728. return EFI_NOT_READY;
  1729. }
  1730. mSmmMpSyncData->StartupProcedure = Procedure;
  1731. mSmmMpSyncData->StartupProcArgs = ProcedureArguments;
  1732. return EFI_SUCCESS;
  1733. }