Variable.c 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905
  1. /** @file
  2. The common variable operation routines shared by DXE_RUNTIME variable
  3. module and DXE_SMM variable module.
  4. Caution: This module requires additional review when modified.
  5. This driver will have external input - variable data. They may be input in SMM mode.
  6. This external input must be validated carefully to avoid security issue like
  7. buffer overflow, integer overflow.
  8. VariableServiceGetNextVariableName () and VariableServiceQueryVariableInfo() are external API.
  9. They need check input parameter.
  10. VariableServiceGetVariable() and VariableServiceSetVariable() are external API
  11. to receive datasize and data buffer. The size should be checked carefully.
  12. VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,
  13. integer overflow. It should also check attribute to avoid authentication bypass.
  14. Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.<BR>
  15. (C) Copyright 2015-2018 Hewlett Packard Enterprise Development LP<BR>
  16. Copyright (c) Microsoft Corporation.<BR>
  17. Copyright (c) 2022, ARM Limited. All rights reserved.<BR>
  18. SPDX-License-Identifier: BSD-2-Clause-Patent
  19. **/
  20. #include "Variable.h"
  21. #include "VariableNonVolatile.h"
  22. #include "VariableParsing.h"
  23. #include "VariableRuntimeCache.h"
  24. VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal;
  25. ///
  26. /// Define a memory cache that improves the search performance for a variable.
  27. /// For EmuNvMode == TRUE, it will be equal to NonVolatileVariableBase.
  28. ///
  29. VARIABLE_STORE_HEADER *mNvVariableCache = NULL;
  30. ///
  31. /// Memory cache of Fv Header.
  32. ///
  33. EFI_FIRMWARE_VOLUME_HEADER *mNvFvHeaderCache = NULL;
  34. ///
  35. /// The memory entry used for variable statistics data.
  36. ///
  37. VARIABLE_INFO_ENTRY *gVariableInfo = NULL;
  38. ///
  39. /// The flag to indicate whether the platform has left the DXE phase of execution.
  40. ///
  41. BOOLEAN mEndOfDxe = FALSE;
  42. ///
  43. /// It indicates the var check request source.
  44. /// In the implementation, DXE is regarded as untrusted, and SMM is trusted.
  45. ///
  46. VAR_CHECK_REQUEST_SOURCE mRequestSource = VarCheckFromUntrusted;
  47. //
  48. // It will record the current boot error flag before EndOfDxe.
  49. //
  50. VAR_ERROR_FLAG mCurrentBootVarErrFlag = VAR_ERROR_FLAG_NO_ERROR;
  51. VARIABLE_ENTRY_PROPERTY mVariableEntryProperty[] = {
  52. {
  53. &gEdkiiVarErrorFlagGuid,
  54. VAR_ERROR_FLAG_NAME,
  55. {
  56. VAR_CHECK_VARIABLE_PROPERTY_REVISION,
  57. VAR_CHECK_VARIABLE_PROPERTY_READ_ONLY,
  58. VARIABLE_ATTRIBUTE_NV_BS_RT,
  59. sizeof (VAR_ERROR_FLAG),
  60. sizeof (VAR_ERROR_FLAG)
  61. }
  62. },
  63. };
  64. AUTH_VAR_LIB_CONTEXT_IN mAuthContextIn = {
  65. AUTH_VAR_LIB_CONTEXT_IN_STRUCT_VERSION,
  66. //
  67. // StructSize, TO BE FILLED
  68. //
  69. 0,
  70. //
  71. // MaxAuthVariableSize, TO BE FILLED
  72. //
  73. 0,
  74. VariableExLibFindVariable,
  75. VariableExLibFindNextVariable,
  76. VariableExLibUpdateVariable,
  77. VariableExLibGetScratchBuffer,
  78. VariableExLibCheckRemainingSpaceForConsistency,
  79. VariableExLibAtRuntime,
  80. };
  81. AUTH_VAR_LIB_CONTEXT_OUT mAuthContextOut;
  82. /**
  83. This function writes data to the FWH at the correct LBA even if the LBAs
  84. are fragmented.
  85. @param Global Pointer to VARAIBLE_GLOBAL structure.
  86. @param Volatile Point out the Variable is Volatile or Non-Volatile.
  87. @param SetByIndex TRUE if target pointer is given as index.
  88. FALSE if target pointer is absolute.
  89. @param Fvb Pointer to the writable FVB protocol.
  90. @param DataPtrIndex Pointer to the Data from the end of VARIABLE_STORE_HEADER
  91. structure.
  92. @param DataSize Size of data to be written.
  93. @param Buffer Pointer to the buffer from which data is written.
  94. @retval EFI_INVALID_PARAMETER Parameters not valid.
  95. @retval EFI_UNSUPPORTED Fvb is a NULL for Non-Volatile variable update.
  96. @retval EFI_OUT_OF_RESOURCES The remaining size is not enough.
  97. @retval EFI_SUCCESS Variable store successfully updated.
  98. **/
  99. EFI_STATUS
  100. UpdateVariableStore (
  101. IN VARIABLE_GLOBAL *Global,
  102. IN BOOLEAN Volatile,
  103. IN BOOLEAN SetByIndex,
  104. IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb,
  105. IN UINTN DataPtrIndex,
  106. IN UINT32 DataSize,
  107. IN UINT8 *Buffer
  108. )
  109. {
  110. EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry;
  111. UINTN BlockIndex2;
  112. UINTN LinearOffset;
  113. UINTN CurrWriteSize;
  114. UINTN CurrWritePtr;
  115. UINT8 *CurrBuffer;
  116. EFI_LBA LbaNumber;
  117. UINTN Size;
  118. VARIABLE_STORE_HEADER *VolatileBase;
  119. EFI_PHYSICAL_ADDRESS FvVolHdr;
  120. EFI_PHYSICAL_ADDRESS DataPtr;
  121. EFI_STATUS Status;
  122. FvVolHdr = 0;
  123. DataPtr = DataPtrIndex;
  124. //
  125. // Check if the Data is Volatile.
  126. //
  127. if (!Volatile && !mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
  128. if (Fvb == NULL) {
  129. return EFI_UNSUPPORTED;
  130. }
  131. Status = Fvb->GetPhysicalAddress (Fvb, &FvVolHdr);
  132. ASSERT_EFI_ERROR (Status);
  133. //
  134. // Data Pointer should point to the actual Address where data is to be
  135. // written.
  136. //
  137. if (SetByIndex) {
  138. DataPtr += mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
  139. }
  140. if ((DataPtr + DataSize) > (FvVolHdr + mNvFvHeaderCache->FvLength)) {
  141. return EFI_OUT_OF_RESOURCES;
  142. }
  143. } else {
  144. //
  145. // Data Pointer should point to the actual Address where data is to be
  146. // written.
  147. //
  148. if (Volatile) {
  149. VolatileBase = (VARIABLE_STORE_HEADER *)((UINTN)mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
  150. if (SetByIndex) {
  151. DataPtr += mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
  152. }
  153. if ((DataPtr + DataSize) > ((UINTN)VolatileBase + VolatileBase->Size)) {
  154. return EFI_OUT_OF_RESOURCES;
  155. }
  156. } else {
  157. //
  158. // Emulated non-volatile variable mode.
  159. //
  160. if (SetByIndex) {
  161. DataPtr += (UINTN)mNvVariableCache;
  162. }
  163. if ((DataPtr + DataSize) > ((UINTN)mNvVariableCache + mNvVariableCache->Size)) {
  164. return EFI_OUT_OF_RESOURCES;
  165. }
  166. }
  167. //
  168. // If Volatile/Emulated Non-volatile Variable just do a simple mem copy.
  169. //
  170. CopyMem ((UINT8 *)(UINTN)DataPtr, Buffer, DataSize);
  171. return EFI_SUCCESS;
  172. }
  173. //
  174. // If we are here we are dealing with Non-Volatile Variables.
  175. //
  176. LinearOffset = (UINTN)FvVolHdr;
  177. CurrWritePtr = (UINTN)DataPtr;
  178. CurrWriteSize = DataSize;
  179. CurrBuffer = Buffer;
  180. LbaNumber = 0;
  181. if (CurrWritePtr < LinearOffset) {
  182. return EFI_INVALID_PARAMETER;
  183. }
  184. for (PtrBlockMapEntry = mNvFvHeaderCache->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {
  185. for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) {
  186. //
  187. // Check to see if the Variable Writes are spanning through multiple
  188. // blocks.
  189. //
  190. if ((CurrWritePtr >= LinearOffset) && (CurrWritePtr < LinearOffset + PtrBlockMapEntry->Length)) {
  191. if ((CurrWritePtr + CurrWriteSize) <= (LinearOffset + PtrBlockMapEntry->Length)) {
  192. Status = Fvb->Write (
  193. Fvb,
  194. LbaNumber,
  195. (UINTN)(CurrWritePtr - LinearOffset),
  196. &CurrWriteSize,
  197. CurrBuffer
  198. );
  199. return Status;
  200. } else {
  201. Size = (UINT32)(LinearOffset + PtrBlockMapEntry->Length - CurrWritePtr);
  202. Status = Fvb->Write (
  203. Fvb,
  204. LbaNumber,
  205. (UINTN)(CurrWritePtr - LinearOffset),
  206. &Size,
  207. CurrBuffer
  208. );
  209. if (EFI_ERROR (Status)) {
  210. return Status;
  211. }
  212. CurrWritePtr = LinearOffset + PtrBlockMapEntry->Length;
  213. CurrBuffer = CurrBuffer + Size;
  214. CurrWriteSize = CurrWriteSize - Size;
  215. }
  216. }
  217. LinearOffset += PtrBlockMapEntry->Length;
  218. LbaNumber++;
  219. }
  220. }
  221. return EFI_SUCCESS;
  222. }
  223. /**
  224. Record variable error flag.
  225. @param[in] Flag Variable error flag to record.
  226. @param[in] VariableName Name of variable.
  227. @param[in] VendorGuid Guid of variable.
  228. @param[in] Attributes Attributes of the variable.
  229. @param[in] VariableSize Size of the variable.
  230. **/
  231. VOID
  232. RecordVarErrorFlag (
  233. IN VAR_ERROR_FLAG Flag,
  234. IN CHAR16 *VariableName,
  235. IN EFI_GUID *VendorGuid,
  236. IN UINT32 Attributes,
  237. IN UINTN VariableSize
  238. )
  239. {
  240. EFI_STATUS Status;
  241. VARIABLE_POINTER_TRACK Variable;
  242. VAR_ERROR_FLAG *VarErrFlag;
  243. VAR_ERROR_FLAG TempFlag;
  244. DEBUG_CODE_BEGIN ();
  245. DEBUG ((DEBUG_ERROR, "RecordVarErrorFlag (0x%02x) %s:%g - 0x%08x - 0x%x\n", Flag, VariableName, VendorGuid, Attributes, VariableSize));
  246. if (Flag == VAR_ERROR_FLAG_SYSTEM_ERROR) {
  247. if (AtRuntime ()) {
  248. DEBUG ((DEBUG_ERROR, "CommonRuntimeVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonRuntimeVariableSpace, mVariableModuleGlobal->CommonVariableTotalSize));
  249. } else {
  250. DEBUG ((DEBUG_ERROR, "CommonVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonVariableTotalSize));
  251. }
  252. } else {
  253. DEBUG ((DEBUG_ERROR, "CommonMaxUserVariableSpace = 0x%x - CommonUserVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonUserVariableTotalSize));
  254. }
  255. DEBUG_CODE_END ();
  256. if (!mEndOfDxe) {
  257. //
  258. // Before EndOfDxe, just record the current boot variable error flag to local variable,
  259. // and leave the variable error flag in NV flash as the last boot variable error flag.
  260. // After EndOfDxe in InitializeVarErrorFlag (), the variable error flag in NV flash
  261. // will be initialized to this local current boot variable error flag.
  262. //
  263. mCurrentBootVarErrFlag &= Flag;
  264. return;
  265. }
  266. //
  267. // Record error flag (it should have be initialized).
  268. //
  269. Status = FindVariable (
  270. VAR_ERROR_FLAG_NAME,
  271. &gEdkiiVarErrorFlagGuid,
  272. &Variable,
  273. &mVariableModuleGlobal->VariableGlobal,
  274. FALSE
  275. );
  276. if (!EFI_ERROR (Status)) {
  277. VarErrFlag = (VAR_ERROR_FLAG *)GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  278. TempFlag = *VarErrFlag;
  279. TempFlag &= Flag;
  280. if (TempFlag == *VarErrFlag) {
  281. return;
  282. }
  283. Status = UpdateVariableStore (
  284. &mVariableModuleGlobal->VariableGlobal,
  285. FALSE,
  286. FALSE,
  287. mVariableModuleGlobal->FvbInstance,
  288. (UINTN)VarErrFlag - (UINTN)mNvVariableCache + (UINTN)mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
  289. sizeof (TempFlag),
  290. &TempFlag
  291. );
  292. if (!EFI_ERROR (Status)) {
  293. //
  294. // Update the data in NV cache.
  295. //
  296. *VarErrFlag = TempFlag;
  297. Status = SynchronizeRuntimeVariableCache (
  298. &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache,
  299. 0,
  300. mNvVariableCache->Size
  301. );
  302. ASSERT_EFI_ERROR (Status);
  303. }
  304. }
  305. }
  306. /**
  307. Initialize variable error flag.
  308. Before EndOfDxe, the variable indicates the last boot variable error flag,
  309. then it means the last boot variable error flag must be got before EndOfDxe.
  310. After EndOfDxe, the variable indicates the current boot variable error flag,
  311. then it means the current boot variable error flag must be got after EndOfDxe.
  312. **/
  313. VOID
  314. InitializeVarErrorFlag (
  315. VOID
  316. )
  317. {
  318. EFI_STATUS Status;
  319. VARIABLE_POINTER_TRACK Variable;
  320. VAR_ERROR_FLAG Flag;
  321. VAR_ERROR_FLAG VarErrFlag;
  322. if (!mEndOfDxe) {
  323. return;
  324. }
  325. Flag = mCurrentBootVarErrFlag;
  326. DEBUG ((DEBUG_INFO, "Initialize variable error flag (%02x)\n", Flag));
  327. Status = FindVariable (
  328. VAR_ERROR_FLAG_NAME,
  329. &gEdkiiVarErrorFlagGuid,
  330. &Variable,
  331. &mVariableModuleGlobal->VariableGlobal,
  332. FALSE
  333. );
  334. if (!EFI_ERROR (Status)) {
  335. VarErrFlag = *((VAR_ERROR_FLAG *)GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat));
  336. if (VarErrFlag == Flag) {
  337. return;
  338. }
  339. }
  340. UpdateVariable (
  341. VAR_ERROR_FLAG_NAME,
  342. &gEdkiiVarErrorFlagGuid,
  343. &Flag,
  344. sizeof (Flag),
  345. VARIABLE_ATTRIBUTE_NV_BS_RT,
  346. 0,
  347. 0,
  348. &Variable,
  349. NULL
  350. );
  351. }
  352. /**
  353. Is user variable?
  354. @param[in] Variable Pointer to variable header.
  355. @retval TRUE User variable.
  356. @retval FALSE System variable.
  357. **/
  358. BOOLEAN
  359. IsUserVariable (
  360. IN VARIABLE_HEADER *Variable
  361. )
  362. {
  363. VAR_CHECK_VARIABLE_PROPERTY Property;
  364. //
  365. // Only after End Of Dxe, the variables belong to system variable are fixed.
  366. // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,
  367. // then no need to check if the variable is user variable or not specially.
  368. //
  369. if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {
  370. if (VarCheckLibVariablePropertyGet (
  371. GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  372. GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  373. &Property
  374. ) == EFI_NOT_FOUND)
  375. {
  376. return TRUE;
  377. }
  378. }
  379. return FALSE;
  380. }
  381. /**
  382. Calculate common user variable total size.
  383. **/
  384. VOID
  385. CalculateCommonUserVariableTotalSize (
  386. VOID
  387. )
  388. {
  389. VARIABLE_HEADER *Variable;
  390. VARIABLE_HEADER *NextVariable;
  391. UINTN VariableSize;
  392. VAR_CHECK_VARIABLE_PROPERTY Property;
  393. //
  394. // Only after End Of Dxe, the variables belong to system variable are fixed.
  395. // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,
  396. // then no need to calculate the common user variable total size specially.
  397. //
  398. if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {
  399. Variable = GetStartPointer (mNvVariableCache);
  400. while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {
  401. NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  402. VariableSize = (UINTN)NextVariable - (UINTN)Variable;
  403. if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  404. if (VarCheckLibVariablePropertyGet (
  405. GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  406. GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  407. &Property
  408. ) == EFI_NOT_FOUND)
  409. {
  410. //
  411. // No property, it is user variable.
  412. //
  413. mVariableModuleGlobal->CommonUserVariableTotalSize += VariableSize;
  414. }
  415. }
  416. Variable = NextVariable;
  417. }
  418. }
  419. }
  420. /**
  421. Initialize variable quota.
  422. **/
  423. VOID
  424. InitializeVariableQuota (
  425. VOID
  426. )
  427. {
  428. if (!mEndOfDxe) {
  429. return;
  430. }
  431. InitializeVarErrorFlag ();
  432. CalculateCommonUserVariableTotalSize ();
  433. }
  434. /**
  435. Variable store garbage collection and reclaim operation.
  436. @param[in] VariableBase Base address of variable store.
  437. @param[out] LastVariableOffset Offset of last variable.
  438. @param[in] IsVolatile The variable store is volatile or not;
  439. if it is non-volatile, need FTW.
  440. @param[in, out] UpdatingPtrTrack Pointer to updating variable pointer track structure.
  441. @param[in] NewVariable Pointer to new variable.
  442. @param[in] NewVariableSize New variable size.
  443. @return EFI_SUCCESS Reclaim operation has finished successfully.
  444. @return EFI_OUT_OF_RESOURCES No enough memory resources or variable space.
  445. @return Others Unexpect error happened during reclaim operation.
  446. **/
  447. EFI_STATUS
  448. Reclaim (
  449. IN EFI_PHYSICAL_ADDRESS VariableBase,
  450. OUT UINTN *LastVariableOffset,
  451. IN BOOLEAN IsVolatile,
  452. IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack,
  453. IN VARIABLE_HEADER *NewVariable,
  454. IN UINTN NewVariableSize
  455. )
  456. {
  457. VARIABLE_HEADER *Variable;
  458. VARIABLE_HEADER *AddedVariable;
  459. VARIABLE_HEADER *NextVariable;
  460. VARIABLE_HEADER *NextAddedVariable;
  461. VARIABLE_STORE_HEADER *VariableStoreHeader;
  462. UINT8 *ValidBuffer;
  463. UINTN MaximumBufferSize;
  464. UINTN VariableSize;
  465. UINTN NameSize;
  466. UINT8 *CurrPtr;
  467. VOID *Point0;
  468. VOID *Point1;
  469. BOOLEAN FoundAdded;
  470. EFI_STATUS Status;
  471. EFI_STATUS DoneStatus;
  472. UINTN CommonVariableTotalSize;
  473. UINTN CommonUserVariableTotalSize;
  474. UINTN HwErrVariableTotalSize;
  475. VARIABLE_HEADER *UpdatingVariable;
  476. VARIABLE_HEADER *UpdatingInDeletedTransition;
  477. BOOLEAN AuthFormat;
  478. AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
  479. UpdatingVariable = NULL;
  480. UpdatingInDeletedTransition = NULL;
  481. if (UpdatingPtrTrack != NULL) {
  482. UpdatingVariable = UpdatingPtrTrack->CurrPtr;
  483. UpdatingInDeletedTransition = UpdatingPtrTrack->InDeletedTransitionPtr;
  484. }
  485. VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)VariableBase);
  486. CommonVariableTotalSize = 0;
  487. CommonUserVariableTotalSize = 0;
  488. HwErrVariableTotalSize = 0;
  489. if (IsVolatile || mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
  490. //
  491. // Start Pointers for the variable.
  492. //
  493. Variable = GetStartPointer (VariableStoreHeader);
  494. MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);
  495. while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
  496. NextVariable = GetNextVariablePtr (Variable, AuthFormat);
  497. if (((Variable->State == VAR_ADDED) || (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED))) &&
  498. (Variable != UpdatingVariable) &&
  499. (Variable != UpdatingInDeletedTransition)
  500. )
  501. {
  502. VariableSize = (UINTN)NextVariable - (UINTN)Variable;
  503. MaximumBufferSize += VariableSize;
  504. }
  505. Variable = NextVariable;
  506. }
  507. if (NewVariable != NULL) {
  508. //
  509. // Add the new variable size.
  510. //
  511. MaximumBufferSize += NewVariableSize;
  512. }
  513. //
  514. // Reserve the 1 Bytes with Oxff to identify the
  515. // end of the variable buffer.
  516. //
  517. MaximumBufferSize += 1;
  518. ValidBuffer = AllocatePool (MaximumBufferSize);
  519. if (ValidBuffer == NULL) {
  520. return EFI_OUT_OF_RESOURCES;
  521. }
  522. } else {
  523. //
  524. // For NV variable reclaim, don't allocate pool here and just use mNvVariableCache
  525. // as the buffer to reduce SMRAM consumption for SMM variable driver.
  526. //
  527. MaximumBufferSize = mNvVariableCache->Size;
  528. ValidBuffer = (UINT8 *)mNvVariableCache;
  529. }
  530. SetMem (ValidBuffer, MaximumBufferSize, 0xff);
  531. //
  532. // Copy variable store header.
  533. //
  534. CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER));
  535. CurrPtr = (UINT8 *)GetStartPointer ((VARIABLE_STORE_HEADER *)ValidBuffer);
  536. //
  537. // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
  538. //
  539. Variable = GetStartPointer (VariableStoreHeader);
  540. while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
  541. NextVariable = GetNextVariablePtr (Variable, AuthFormat);
  542. if ((Variable != UpdatingVariable) && (Variable->State == VAR_ADDED)) {
  543. VariableSize = (UINTN)NextVariable - (UINTN)Variable;
  544. CopyMem (CurrPtr, (UINT8 *)Variable, VariableSize);
  545. CurrPtr += VariableSize;
  546. if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
  547. HwErrVariableTotalSize += VariableSize;
  548. } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
  549. CommonVariableTotalSize += VariableSize;
  550. if (IsUserVariable (Variable)) {
  551. CommonUserVariableTotalSize += VariableSize;
  552. }
  553. }
  554. }
  555. Variable = NextVariable;
  556. }
  557. //
  558. // Reinstall all in delete transition variables.
  559. //
  560. Variable = GetStartPointer (VariableStoreHeader);
  561. while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
  562. NextVariable = GetNextVariablePtr (Variable, AuthFormat);
  563. if ((Variable != UpdatingVariable) && (Variable != UpdatingInDeletedTransition) && (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED))) {
  564. //
  565. // Buffer has cached all ADDED variable.
  566. // Per IN_DELETED variable, we have to guarantee that
  567. // no ADDED one in previous buffer.
  568. //
  569. FoundAdded = FALSE;
  570. AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)ValidBuffer);
  571. while (IsValidVariableHeader (AddedVariable, GetEndPointer ((VARIABLE_STORE_HEADER *)ValidBuffer))) {
  572. NextAddedVariable = GetNextVariablePtr (AddedVariable, AuthFormat);
  573. NameSize = NameSizeOfVariable (AddedVariable, AuthFormat);
  574. if (CompareGuid (
  575. GetVendorGuidPtr (AddedVariable, AuthFormat),
  576. GetVendorGuidPtr (Variable, AuthFormat)
  577. ) && (NameSize == NameSizeOfVariable (Variable, AuthFormat)))
  578. {
  579. Point0 = (VOID *)GetVariableNamePtr (AddedVariable, AuthFormat);
  580. Point1 = (VOID *)GetVariableNamePtr (Variable, AuthFormat);
  581. if (CompareMem (Point0, Point1, NameSize) == 0) {
  582. FoundAdded = TRUE;
  583. break;
  584. }
  585. }
  586. AddedVariable = NextAddedVariable;
  587. }
  588. if (!FoundAdded) {
  589. //
  590. // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
  591. //
  592. VariableSize = (UINTN)NextVariable - (UINTN)Variable;
  593. CopyMem (CurrPtr, (UINT8 *)Variable, VariableSize);
  594. ((VARIABLE_HEADER *)CurrPtr)->State = VAR_ADDED;
  595. CurrPtr += VariableSize;
  596. if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
  597. HwErrVariableTotalSize += VariableSize;
  598. } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
  599. CommonVariableTotalSize += VariableSize;
  600. if (IsUserVariable (Variable)) {
  601. CommonUserVariableTotalSize += VariableSize;
  602. }
  603. }
  604. }
  605. }
  606. Variable = NextVariable;
  607. }
  608. //
  609. // Install the new variable if it is not NULL.
  610. //
  611. if (NewVariable != NULL) {
  612. if (((UINTN)CurrPtr - (UINTN)ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {
  613. //
  614. // No enough space to store the new variable.
  615. //
  616. Status = EFI_OUT_OF_RESOURCES;
  617. goto Done;
  618. }
  619. if (!IsVolatile) {
  620. if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  621. HwErrVariableTotalSize += NewVariableSize;
  622. } else if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  623. CommonVariableTotalSize += NewVariableSize;
  624. if (IsUserVariable (NewVariable)) {
  625. CommonUserVariableTotalSize += NewVariableSize;
  626. }
  627. }
  628. if ((HwErrVariableTotalSize > PcdGet32 (PcdHwErrStorageSize)) ||
  629. (CommonVariableTotalSize > mVariableModuleGlobal->CommonVariableSpace) ||
  630. (CommonUserVariableTotalSize > mVariableModuleGlobal->CommonMaxUserVariableSpace))
  631. {
  632. //
  633. // No enough space to store the new variable by NV or NV+HR attribute.
  634. //
  635. Status = EFI_OUT_OF_RESOURCES;
  636. goto Done;
  637. }
  638. }
  639. CopyMem (CurrPtr, (UINT8 *)NewVariable, NewVariableSize);
  640. ((VARIABLE_HEADER *)CurrPtr)->State = VAR_ADDED;
  641. if (UpdatingVariable != NULL) {
  642. UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *)ValidBuffer)));
  643. UpdatingPtrTrack->InDeletedTransitionPtr = NULL;
  644. }
  645. CurrPtr += NewVariableSize;
  646. }
  647. if (IsVolatile || mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
  648. //
  649. // If volatile/emulated non-volatile variable store, just copy valid buffer.
  650. //
  651. SetMem ((UINT8 *)(UINTN)VariableBase, VariableStoreHeader->Size, 0xff);
  652. CopyMem ((UINT8 *)(UINTN)VariableBase, ValidBuffer, (UINTN)CurrPtr - (UINTN)ValidBuffer);
  653. *LastVariableOffset = (UINTN)CurrPtr - (UINTN)ValidBuffer;
  654. if (!IsVolatile) {
  655. //
  656. // Emulated non-volatile variable mode.
  657. //
  658. mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
  659. mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
  660. mVariableModuleGlobal->CommonUserVariableTotalSize = CommonUserVariableTotalSize;
  661. }
  662. Status = EFI_SUCCESS;
  663. } else {
  664. //
  665. // If non-volatile variable store, perform FTW here.
  666. //
  667. Status = FtwVariableSpace (
  668. VariableBase,
  669. (VARIABLE_STORE_HEADER *)ValidBuffer
  670. );
  671. if (!EFI_ERROR (Status)) {
  672. *LastVariableOffset = (UINTN)CurrPtr - (UINTN)ValidBuffer;
  673. mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
  674. mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
  675. mVariableModuleGlobal->CommonUserVariableTotalSize = CommonUserVariableTotalSize;
  676. } else {
  677. mVariableModuleGlobal->HwErrVariableTotalSize = 0;
  678. mVariableModuleGlobal->CommonVariableTotalSize = 0;
  679. mVariableModuleGlobal->CommonUserVariableTotalSize = 0;
  680. Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);
  681. while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase))) {
  682. NextVariable = GetNextVariablePtr (Variable, AuthFormat);
  683. VariableSize = (UINTN)NextVariable - (UINTN)Variable;
  684. if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  685. mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
  686. } else if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  687. mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;
  688. if (IsUserVariable (Variable)) {
  689. mVariableModuleGlobal->CommonUserVariableTotalSize += VariableSize;
  690. }
  691. }
  692. Variable = NextVariable;
  693. }
  694. *LastVariableOffset = (UINTN)Variable - (UINTN)VariableBase;
  695. }
  696. }
  697. Done:
  698. DoneStatus = EFI_SUCCESS;
  699. if (IsVolatile || mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
  700. DoneStatus = SynchronizeRuntimeVariableCache (
  701. &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache,
  702. 0,
  703. VariableStoreHeader->Size
  704. );
  705. ASSERT_EFI_ERROR (DoneStatus);
  706. FreePool (ValidBuffer);
  707. } else {
  708. //
  709. // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy the data back.
  710. //
  711. CopyMem (mNvVariableCache, (UINT8 *)(UINTN)VariableBase, VariableStoreHeader->Size);
  712. DoneStatus = SynchronizeRuntimeVariableCache (
  713. &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache,
  714. 0,
  715. VariableStoreHeader->Size
  716. );
  717. ASSERT_EFI_ERROR (DoneStatus);
  718. }
  719. if (!EFI_ERROR (Status) && EFI_ERROR (DoneStatus)) {
  720. Status = DoneStatus;
  721. }
  722. return Status;
  723. }
  724. /**
  725. Finds variable in storage blocks of volatile and non-volatile storage areas.
  726. This code finds variable in storage blocks of volatile and non-volatile storage areas.
  727. If VariableName is an empty string, then we just return the first
  728. qualified variable without comparing VariableName and VendorGuid.
  729. If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check
  730. at runtime when searching existing variable, only VariableName and VendorGuid are compared.
  731. Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.
  732. @param[in] VariableName Name of the variable to be found.
  733. @param[in] VendorGuid Vendor GUID to be found.
  734. @param[out] PtrTrack VARIABLE_POINTER_TRACK structure for output,
  735. including the range searched and the target position.
  736. @param[in] Global Pointer to VARIABLE_GLOBAL structure, including
  737. base of volatile variable storage area, base of
  738. NV variable storage area, and a lock.
  739. @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
  740. check at runtime when searching variable.
  741. @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while
  742. VendorGuid is NULL.
  743. @retval EFI_SUCCESS Variable successfully found.
  744. @retval EFI_NOT_FOUND Variable not found
  745. **/
  746. EFI_STATUS
  747. FindVariable (
  748. IN CHAR16 *VariableName,
  749. IN EFI_GUID *VendorGuid,
  750. OUT VARIABLE_POINTER_TRACK *PtrTrack,
  751. IN VARIABLE_GLOBAL *Global,
  752. IN BOOLEAN IgnoreRtCheck
  753. )
  754. {
  755. EFI_STATUS Status;
  756. VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
  757. VARIABLE_STORE_TYPE Type;
  758. if ((VariableName[0] != 0) && (VendorGuid == NULL)) {
  759. return EFI_INVALID_PARAMETER;
  760. }
  761. //
  762. // 0: Volatile, 1: HOB, 2: Non-Volatile.
  763. // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName
  764. // make use of this mapping to implement search algorithm.
  765. //
  766. VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *)(UINTN)Global->VolatileVariableBase;
  767. VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *)(UINTN)Global->HobVariableBase;
  768. VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
  769. //
  770. // Find the variable by walk through HOB, volatile and non-volatile variable store.
  771. //
  772. for (Type = (VARIABLE_STORE_TYPE)0; Type < VariableStoreTypeMax; Type++) {
  773. if (VariableStoreHeader[Type] == NULL) {
  774. continue;
  775. }
  776. PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);
  777. PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]);
  778. PtrTrack->Volatile = (BOOLEAN)(Type == VariableStoreTypeVolatile);
  779. Status = FindVariableEx (
  780. VariableName,
  781. VendorGuid,
  782. IgnoreRtCheck,
  783. PtrTrack,
  784. mVariableModuleGlobal->VariableGlobal.AuthFormat
  785. );
  786. if (!EFI_ERROR (Status)) {
  787. return Status;
  788. }
  789. }
  790. return EFI_NOT_FOUND;
  791. }
  792. /**
  793. Get index from supported language codes according to language string.
  794. This code is used to get corresponding index in supported language codes. It can handle
  795. RFC4646 and ISO639 language tags.
  796. In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.
  797. In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.
  798. For example:
  799. SupportedLang = "engfraengfra"
  800. Lang = "eng"
  801. Iso639Language = TRUE
  802. The return value is "0".
  803. Another example:
  804. SupportedLang = "en;fr;en-US;fr-FR"
  805. Lang = "fr-FR"
  806. Iso639Language = FALSE
  807. The return value is "3".
  808. @param SupportedLang Platform supported language codes.
  809. @param Lang Configured language.
  810. @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
  811. @retval The index of language in the language codes.
  812. **/
  813. UINTN
  814. GetIndexFromSupportedLangCodes (
  815. IN CHAR8 *SupportedLang,
  816. IN CHAR8 *Lang,
  817. IN BOOLEAN Iso639Language
  818. )
  819. {
  820. UINTN Index;
  821. UINTN CompareLength;
  822. UINTN LanguageLength;
  823. if (Iso639Language) {
  824. CompareLength = ISO_639_2_ENTRY_SIZE;
  825. for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {
  826. if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {
  827. //
  828. // Successfully find the index of Lang string in SupportedLang string.
  829. //
  830. Index = Index / CompareLength;
  831. return Index;
  832. }
  833. }
  834. ASSERT (FALSE);
  835. return 0;
  836. } else {
  837. //
  838. // Compare RFC4646 language code
  839. //
  840. Index = 0;
  841. for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++) {
  842. }
  843. for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {
  844. //
  845. // Skip ';' characters in SupportedLang
  846. //
  847. for ( ; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++) {
  848. }
  849. //
  850. // Determine the length of the next language code in SupportedLang
  851. //
  852. for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++) {
  853. }
  854. if ((CompareLength == LanguageLength) &&
  855. (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0))
  856. {
  857. //
  858. // Successfully find the index of Lang string in SupportedLang string.
  859. //
  860. return Index;
  861. }
  862. }
  863. ASSERT (FALSE);
  864. return 0;
  865. }
  866. }
  867. /**
  868. Get language string from supported language codes according to index.
  869. This code is used to get corresponding language strings in supported language codes. It can handle
  870. RFC4646 and ISO639 language tags.
  871. In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.
  872. In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.
  873. For example:
  874. SupportedLang = "engfraengfra"
  875. Index = "1"
  876. Iso639Language = TRUE
  877. The return value is "fra".
  878. Another example:
  879. SupportedLang = "en;fr;en-US;fr-FR"
  880. Index = "1"
  881. Iso639Language = FALSE
  882. The return value is "fr".
  883. @param SupportedLang Platform supported language codes.
  884. @param Index The index in supported language codes.
  885. @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
  886. @retval The language string in the language codes.
  887. **/
  888. CHAR8 *
  889. GetLangFromSupportedLangCodes (
  890. IN CHAR8 *SupportedLang,
  891. IN UINTN Index,
  892. IN BOOLEAN Iso639Language
  893. )
  894. {
  895. UINTN SubIndex;
  896. UINTN CompareLength;
  897. CHAR8 *Supported;
  898. SubIndex = 0;
  899. Supported = SupportedLang;
  900. if (Iso639Language) {
  901. //
  902. // According to the index of Lang string in SupportedLang string to get the language.
  903. // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.
  904. // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
  905. //
  906. CompareLength = ISO_639_2_ENTRY_SIZE;
  907. mVariableModuleGlobal->Lang[CompareLength] = '\0';
  908. return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);
  909. } else {
  910. while (TRUE) {
  911. //
  912. // Take semicolon as delimitation, sequentially traverse supported language codes.
  913. //
  914. for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {
  915. Supported++;
  916. }
  917. if ((*Supported == '\0') && (SubIndex != Index)) {
  918. //
  919. // Have completed the traverse, but not find corrsponding string.
  920. // This case is not allowed to happen.
  921. //
  922. ASSERT (FALSE);
  923. return NULL;
  924. }
  925. if (SubIndex == Index) {
  926. //
  927. // According to the index of Lang string in SupportedLang string to get the language.
  928. // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.
  929. // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.
  930. //
  931. mVariableModuleGlobal->PlatformLang[CompareLength] = '\0';
  932. return CopyMem (mVariableModuleGlobal->PlatformLang, Supported - CompareLength, CompareLength);
  933. }
  934. SubIndex++;
  935. //
  936. // Skip ';' characters in Supported
  937. //
  938. for ( ; *Supported != '\0' && *Supported == ';'; Supported++) {
  939. }
  940. }
  941. }
  942. }
  943. /**
  944. Returns a pointer to an allocated buffer that contains the best matching language
  945. from a set of supported languages.
  946. This function supports both ISO 639-2 and RFC 4646 language codes, but language
  947. code types may not be mixed in a single call to this function. This function
  948. supports a variable argument list that allows the caller to pass in a prioritized
  949. list of language codes to test against all the language codes in SupportedLanguages.
  950. If SupportedLanguages is NULL, then ASSERT().
  951. @param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
  952. contains a set of language codes in the format
  953. specified by Iso639Language.
  954. @param[in] Iso639Language If not zero, then all language codes are assumed to be
  955. in ISO 639-2 format. If zero, then all language
  956. codes are assumed to be in RFC 4646 language format
  957. @param[in] ... A variable argument list that contains pointers to
  958. Null-terminated ASCII strings that contain one or more
  959. language codes in the format specified by Iso639Language.
  960. The first language code from each of these language
  961. code lists is used to determine if it is an exact or
  962. close match to any of the language codes in
  963. SupportedLanguages. Close matches only apply to RFC 4646
  964. language codes, and the matching algorithm from RFC 4647
  965. is used to determine if a close match is present. If
  966. an exact or close match is found, then the matching
  967. language code from SupportedLanguages is returned. If
  968. no matches are found, then the next variable argument
  969. parameter is evaluated. The variable argument list
  970. is terminated by a NULL.
  971. @retval NULL The best matching language could not be found in SupportedLanguages.
  972. @retval NULL There are not enough resources available to return the best matching
  973. language.
  974. @retval Other A pointer to a Null-terminated ASCII string that is the best matching
  975. language in SupportedLanguages.
  976. **/
  977. CHAR8 *
  978. EFIAPI
  979. VariableGetBestLanguage (
  980. IN CONST CHAR8 *SupportedLanguages,
  981. IN UINTN Iso639Language,
  982. ...
  983. )
  984. {
  985. VA_LIST Args;
  986. CHAR8 *Language;
  987. UINTN CompareLength;
  988. UINTN LanguageLength;
  989. CONST CHAR8 *Supported;
  990. CHAR8 *Buffer;
  991. if (SupportedLanguages == NULL) {
  992. return NULL;
  993. }
  994. VA_START (Args, Iso639Language);
  995. while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {
  996. //
  997. // Default to ISO 639-2 mode
  998. //
  999. CompareLength = 3;
  1000. LanguageLength = MIN (3, AsciiStrLen (Language));
  1001. //
  1002. // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language
  1003. //
  1004. if (Iso639Language == 0) {
  1005. for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++) {
  1006. }
  1007. }
  1008. //
  1009. // Trim back the length of Language used until it is empty
  1010. //
  1011. while (LanguageLength > 0) {
  1012. //
  1013. // Loop through all language codes in SupportedLanguages
  1014. //
  1015. for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {
  1016. //
  1017. // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages
  1018. //
  1019. if (Iso639Language == 0) {
  1020. //
  1021. // Skip ';' characters in Supported
  1022. //
  1023. for ( ; *Supported != '\0' && *Supported == ';'; Supported++) {
  1024. }
  1025. //
  1026. // Determine the length of the next language code in Supported
  1027. //
  1028. for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++) {
  1029. }
  1030. //
  1031. // If Language is longer than the Supported, then skip to the next language
  1032. //
  1033. if (LanguageLength > CompareLength) {
  1034. continue;
  1035. }
  1036. }
  1037. //
  1038. // See if the first LanguageLength characters in Supported match Language
  1039. //
  1040. if (AsciiStrnCmp (Supported, Language, LanguageLength) == 0) {
  1041. VA_END (Args);
  1042. Buffer = (Iso639Language != 0) ? mVariableModuleGlobal->Lang : mVariableModuleGlobal->PlatformLang;
  1043. Buffer[CompareLength] = '\0';
  1044. return CopyMem (Buffer, Supported, CompareLength);
  1045. }
  1046. }
  1047. if (Iso639Language != 0) {
  1048. //
  1049. // If ISO 639 mode, then each language can only be tested once
  1050. //
  1051. LanguageLength = 0;
  1052. } else {
  1053. //
  1054. // If RFC 4646 mode, then trim Language from the right to the next '-' character
  1055. //
  1056. for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--) {
  1057. }
  1058. }
  1059. }
  1060. }
  1061. VA_END (Args);
  1062. //
  1063. // No matches were found
  1064. //
  1065. return NULL;
  1066. }
  1067. /**
  1068. This function is to check if the remaining variable space is enough to set
  1069. all Variables from argument list successfully. The purpose of the check
  1070. is to keep the consistency of the Variables to be in variable storage.
  1071. Note: Variables are assumed to be in same storage.
  1072. The set sequence of Variables will be same with the sequence of VariableEntry from argument list,
  1073. so follow the argument sequence to check the Variables.
  1074. @param[in] Attributes Variable attributes for Variable entries.
  1075. @param[in] Marker VA_LIST style variable argument list.
  1076. The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.
  1077. A NULL terminates the list. The VariableSize of
  1078. VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.
  1079. It will be changed to variable total size as output.
  1080. @retval TRUE Have enough variable space to set the Variables successfully.
  1081. @retval FALSE No enough variable space to set the Variables successfully.
  1082. **/
  1083. BOOLEAN
  1084. EFIAPI
  1085. CheckRemainingSpaceForConsistencyInternal (
  1086. IN UINT32 Attributes,
  1087. IN VA_LIST Marker
  1088. )
  1089. {
  1090. EFI_STATUS Status;
  1091. VA_LIST Args;
  1092. VARIABLE_ENTRY_CONSISTENCY *VariableEntry;
  1093. UINT64 MaximumVariableStorageSize;
  1094. UINT64 RemainingVariableStorageSize;
  1095. UINT64 MaximumVariableSize;
  1096. UINTN TotalNeededSize;
  1097. UINTN OriginalVarSize;
  1098. VARIABLE_STORE_HEADER *VariableStoreHeader;
  1099. VARIABLE_POINTER_TRACK VariablePtrTrack;
  1100. VARIABLE_HEADER *NextVariable;
  1101. UINTN VarNameSize;
  1102. UINTN VarDataSize;
  1103. //
  1104. // Non-Volatile related.
  1105. //
  1106. VariableStoreHeader = mNvVariableCache;
  1107. Status = VariableServiceQueryVariableInfoInternal (
  1108. Attributes,
  1109. &MaximumVariableStorageSize,
  1110. &RemainingVariableStorageSize,
  1111. &MaximumVariableSize
  1112. );
  1113. ASSERT_EFI_ERROR (Status);
  1114. TotalNeededSize = 0;
  1115. VA_COPY (Args, Marker);
  1116. VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
  1117. while (VariableEntry != NULL) {
  1118. //
  1119. // Calculate variable total size.
  1120. //
  1121. VarNameSize = StrSize (VariableEntry->Name);
  1122. VarNameSize += GET_PAD_SIZE (VarNameSize);
  1123. VarDataSize = VariableEntry->VariableSize;
  1124. VarDataSize += GET_PAD_SIZE (VarDataSize);
  1125. VariableEntry->VariableSize = HEADER_ALIGN (
  1126. GetVariableHeaderSize (
  1127. mVariableModuleGlobal->VariableGlobal.AuthFormat
  1128. ) + VarNameSize + VarDataSize
  1129. );
  1130. TotalNeededSize += VariableEntry->VariableSize;
  1131. VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
  1132. }
  1133. VA_END (Args);
  1134. if (RemainingVariableStorageSize >= TotalNeededSize) {
  1135. //
  1136. // Already have enough space.
  1137. //
  1138. return TRUE;
  1139. } else if (AtRuntime ()) {
  1140. //
  1141. // At runtime, no reclaim.
  1142. // The original variable space of Variables can't be reused.
  1143. //
  1144. return FALSE;
  1145. }
  1146. VA_COPY (Args, Marker);
  1147. VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
  1148. while (VariableEntry != NULL) {
  1149. //
  1150. // Check if Variable[Index] has been present and get its size.
  1151. //
  1152. OriginalVarSize = 0;
  1153. VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
  1154. VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
  1155. Status = FindVariableEx (
  1156. VariableEntry->Name,
  1157. VariableEntry->Guid,
  1158. FALSE,
  1159. &VariablePtrTrack,
  1160. mVariableModuleGlobal->VariableGlobal.AuthFormat
  1161. );
  1162. if (!EFI_ERROR (Status)) {
  1163. //
  1164. // Get size of Variable[Index].
  1165. //
  1166. NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  1167. OriginalVarSize = (UINTN)NextVariable - (UINTN)VariablePtrTrack.CurrPtr;
  1168. //
  1169. // Add the original size of Variable[Index] to remaining variable storage size.
  1170. //
  1171. RemainingVariableStorageSize += OriginalVarSize;
  1172. }
  1173. if (VariableEntry->VariableSize > RemainingVariableStorageSize) {
  1174. //
  1175. // No enough space for Variable[Index].
  1176. //
  1177. VA_END (Args);
  1178. return FALSE;
  1179. }
  1180. //
  1181. // Sub the (new) size of Variable[Index] from remaining variable storage size.
  1182. //
  1183. RemainingVariableStorageSize -= VariableEntry->VariableSize;
  1184. VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
  1185. }
  1186. VA_END (Args);
  1187. return TRUE;
  1188. }
  1189. /**
  1190. This function is to check if the remaining variable space is enough to set
  1191. all Variables from argument list successfully. The purpose of the check
  1192. is to keep the consistency of the Variables to be in variable storage.
  1193. Note: Variables are assumed to be in same storage.
  1194. The set sequence of Variables will be same with the sequence of VariableEntry from argument list,
  1195. so follow the argument sequence to check the Variables.
  1196. @param[in] Attributes Variable attributes for Variable entries.
  1197. @param ... The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.
  1198. A NULL terminates the list. The VariableSize of
  1199. VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.
  1200. It will be changed to variable total size as output.
  1201. @retval TRUE Have enough variable space to set the Variables successfully.
  1202. @retval FALSE No enough variable space to set the Variables successfully.
  1203. **/
  1204. BOOLEAN
  1205. EFIAPI
  1206. CheckRemainingSpaceForConsistency (
  1207. IN UINT32 Attributes,
  1208. ...
  1209. )
  1210. {
  1211. VA_LIST Marker;
  1212. BOOLEAN Return;
  1213. VA_START (Marker, Attributes);
  1214. Return = CheckRemainingSpaceForConsistencyInternal (Attributes, Marker);
  1215. VA_END (Marker);
  1216. return Return;
  1217. }
  1218. /**
  1219. Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.
  1220. When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.
  1221. According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,
  1222. and are read-only. Therefore, in variable driver, only store the original value for other use.
  1223. @param[in] VariableName Name of variable.
  1224. @param[in] Data Variable data.
  1225. @param[in] DataSize Size of data. 0 means delete.
  1226. @retval EFI_SUCCESS The update operation is successful or ignored.
  1227. @retval EFI_WRITE_PROTECTED Update PlatformLangCodes/LangCodes at runtime.
  1228. @retval EFI_OUT_OF_RESOURCES No enough variable space to do the update operation.
  1229. @retval Others Other errors happened during the update operation.
  1230. **/
  1231. EFI_STATUS
  1232. AutoUpdateLangVariable (
  1233. IN CHAR16 *VariableName,
  1234. IN VOID *Data,
  1235. IN UINTN DataSize
  1236. )
  1237. {
  1238. EFI_STATUS Status;
  1239. CHAR8 *BestPlatformLang;
  1240. CHAR8 *BestLang;
  1241. UINTN Index;
  1242. UINT32 Attributes;
  1243. VARIABLE_POINTER_TRACK Variable;
  1244. BOOLEAN SetLanguageCodes;
  1245. VARIABLE_ENTRY_CONSISTENCY VariableEntry[2];
  1246. //
  1247. // Don't do updates for delete operation
  1248. //
  1249. if (DataSize == 0) {
  1250. return EFI_SUCCESS;
  1251. }
  1252. SetLanguageCodes = FALSE;
  1253. if (StrCmp (VariableName, EFI_PLATFORM_LANG_CODES_VARIABLE_NAME) == 0) {
  1254. //
  1255. // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.
  1256. //
  1257. if (AtRuntime ()) {
  1258. return EFI_WRITE_PROTECTED;
  1259. }
  1260. SetLanguageCodes = TRUE;
  1261. //
  1262. // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only
  1263. // Therefore, in variable driver, only store the original value for other use.
  1264. //
  1265. if (mVariableModuleGlobal->PlatformLangCodes != NULL) {
  1266. FreePool (mVariableModuleGlobal->PlatformLangCodes);
  1267. }
  1268. mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);
  1269. ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);
  1270. //
  1271. // PlatformLang holds a single language from PlatformLangCodes,
  1272. // so the size of PlatformLangCodes is enough for the PlatformLang.
  1273. //
  1274. if (mVariableModuleGlobal->PlatformLang != NULL) {
  1275. FreePool (mVariableModuleGlobal->PlatformLang);
  1276. }
  1277. mVariableModuleGlobal->PlatformLang = AllocateRuntimePool (DataSize);
  1278. ASSERT (mVariableModuleGlobal->PlatformLang != NULL);
  1279. } else if (StrCmp (VariableName, EFI_LANG_CODES_VARIABLE_NAME) == 0) {
  1280. //
  1281. // LangCodes is a volatile variable, so it can not be updated at runtime.
  1282. //
  1283. if (AtRuntime ()) {
  1284. return EFI_WRITE_PROTECTED;
  1285. }
  1286. SetLanguageCodes = TRUE;
  1287. //
  1288. // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only
  1289. // Therefore, in variable driver, only store the original value for other use.
  1290. //
  1291. if (mVariableModuleGlobal->LangCodes != NULL) {
  1292. FreePool (mVariableModuleGlobal->LangCodes);
  1293. }
  1294. mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);
  1295. ASSERT (mVariableModuleGlobal->LangCodes != NULL);
  1296. }
  1297. if ( SetLanguageCodes
  1298. && (mVariableModuleGlobal->PlatformLangCodes != NULL)
  1299. && (mVariableModuleGlobal->LangCodes != NULL))
  1300. {
  1301. //
  1302. // Update Lang if PlatformLang is already set
  1303. // Update PlatformLang if Lang is already set
  1304. //
  1305. Status = FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
  1306. if (!EFI_ERROR (Status)) {
  1307. //
  1308. // Update Lang
  1309. //
  1310. VariableName = EFI_PLATFORM_LANG_VARIABLE_NAME;
  1311. Data = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  1312. DataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  1313. } else {
  1314. Status = FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
  1315. if (!EFI_ERROR (Status)) {
  1316. //
  1317. // Update PlatformLang
  1318. //
  1319. VariableName = EFI_LANG_VARIABLE_NAME;
  1320. Data = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  1321. DataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  1322. } else {
  1323. //
  1324. // Neither PlatformLang nor Lang is set, directly return
  1325. //
  1326. return EFI_SUCCESS;
  1327. }
  1328. }
  1329. }
  1330. Status = EFI_SUCCESS;
  1331. //
  1332. // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.
  1333. //
  1334. Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;
  1335. if (StrCmp (VariableName, EFI_PLATFORM_LANG_VARIABLE_NAME) == 0) {
  1336. //
  1337. // Update Lang when PlatformLangCodes/LangCodes were set.
  1338. //
  1339. if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
  1340. //
  1341. // When setting PlatformLang, firstly get most matched language string from supported language codes.
  1342. //
  1343. BestPlatformLang = VariableGetBestLanguage (mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);
  1344. if (BestPlatformLang != NULL) {
  1345. //
  1346. // Get the corresponding index in language codes.
  1347. //
  1348. Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);
  1349. //
  1350. // Get the corresponding ISO639 language tag according to RFC4646 language tag.
  1351. //
  1352. BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);
  1353. //
  1354. // Check the variable space for both Lang and PlatformLang variable.
  1355. //
  1356. VariableEntry[0].VariableSize = ISO_639_2_ENTRY_SIZE + 1;
  1357. VariableEntry[0].Guid = &gEfiGlobalVariableGuid;
  1358. VariableEntry[0].Name = EFI_LANG_VARIABLE_NAME;
  1359. VariableEntry[1].VariableSize = AsciiStrSize (BestPlatformLang);
  1360. VariableEntry[1].Guid = &gEfiGlobalVariableGuid;
  1361. VariableEntry[1].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;
  1362. if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT, &VariableEntry[0], &VariableEntry[1], NULL)) {
  1363. //
  1364. // No enough variable space to set both Lang and PlatformLang successfully.
  1365. //
  1366. Status = EFI_OUT_OF_RESOURCES;
  1367. } else {
  1368. //
  1369. // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
  1370. //
  1371. FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
  1372. Status = UpdateVariable (
  1373. EFI_LANG_VARIABLE_NAME,
  1374. &gEfiGlobalVariableGuid,
  1375. BestLang,
  1376. ISO_639_2_ENTRY_SIZE + 1,
  1377. Attributes,
  1378. 0,
  1379. 0,
  1380. &Variable,
  1381. NULL
  1382. );
  1383. }
  1384. DEBUG ((DEBUG_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a Status: %r\n", BestPlatformLang, BestLang, Status));
  1385. }
  1386. }
  1387. } else if (StrCmp (VariableName, EFI_LANG_VARIABLE_NAME) == 0) {
  1388. //
  1389. // Update PlatformLang when PlatformLangCodes/LangCodes were set.
  1390. //
  1391. if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {
  1392. //
  1393. // When setting Lang, firstly get most matched language string from supported language codes.
  1394. //
  1395. BestLang = VariableGetBestLanguage (mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);
  1396. if (BestLang != NULL) {
  1397. //
  1398. // Get the corresponding index in language codes.
  1399. //
  1400. Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, BestLang, TRUE);
  1401. //
  1402. // Get the corresponding RFC4646 language tag according to ISO639 language tag.
  1403. //
  1404. BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);
  1405. //
  1406. // Check the variable space for both PlatformLang and Lang variable.
  1407. //
  1408. VariableEntry[0].VariableSize = AsciiStrSize (BestPlatformLang);
  1409. VariableEntry[0].Guid = &gEfiGlobalVariableGuid;
  1410. VariableEntry[0].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;
  1411. VariableEntry[1].VariableSize = ISO_639_2_ENTRY_SIZE + 1;
  1412. VariableEntry[1].Guid = &gEfiGlobalVariableGuid;
  1413. VariableEntry[1].Name = EFI_LANG_VARIABLE_NAME;
  1414. if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT, &VariableEntry[0], &VariableEntry[1], NULL)) {
  1415. //
  1416. // No enough variable space to set both PlatformLang and Lang successfully.
  1417. //
  1418. Status = EFI_OUT_OF_RESOURCES;
  1419. } else {
  1420. //
  1421. // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.
  1422. //
  1423. FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
  1424. Status = UpdateVariable (
  1425. EFI_PLATFORM_LANG_VARIABLE_NAME,
  1426. &gEfiGlobalVariableGuid,
  1427. BestPlatformLang,
  1428. AsciiStrSize (BestPlatformLang),
  1429. Attributes,
  1430. 0,
  1431. 0,
  1432. &Variable,
  1433. NULL
  1434. );
  1435. }
  1436. DEBUG ((DEBUG_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a Status: %r\n", BestLang, BestPlatformLang, Status));
  1437. }
  1438. }
  1439. }
  1440. if (SetLanguageCodes) {
  1441. //
  1442. // Continue to set PlatformLangCodes or LangCodes.
  1443. //
  1444. return EFI_SUCCESS;
  1445. } else {
  1446. return Status;
  1447. }
  1448. }
  1449. /**
  1450. Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
  1451. index of associated public key is needed.
  1452. @param[in] VariableName Name of variable.
  1453. @param[in] VendorGuid Guid of variable.
  1454. @param[in] Data Variable data.
  1455. @param[in] DataSize Size of data. 0 means delete.
  1456. @param[in] Attributes Attributes of the variable.
  1457. @param[in] KeyIndex Index of associated public key.
  1458. @param[in] MonotonicCount Value of associated monotonic count.
  1459. @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.
  1460. @param[in] TimeStamp Value of associated TimeStamp.
  1461. @retval EFI_SUCCESS The update operation is success.
  1462. @retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
  1463. **/
  1464. EFI_STATUS
  1465. UpdateVariable (
  1466. IN CHAR16 *VariableName,
  1467. IN EFI_GUID *VendorGuid,
  1468. IN VOID *Data,
  1469. IN UINTN DataSize,
  1470. IN UINT32 Attributes OPTIONAL,
  1471. IN UINT32 KeyIndex OPTIONAL,
  1472. IN UINT64 MonotonicCount OPTIONAL,
  1473. IN OUT VARIABLE_POINTER_TRACK *CacheVariable,
  1474. IN EFI_TIME *TimeStamp OPTIONAL
  1475. )
  1476. {
  1477. EFI_STATUS Status;
  1478. VARIABLE_HEADER *NextVariable;
  1479. UINTN ScratchSize;
  1480. UINTN MaxDataSize;
  1481. UINTN VarNameOffset;
  1482. UINTN VarDataOffset;
  1483. UINTN VarNameSize;
  1484. UINTN VarSize;
  1485. BOOLEAN Volatile;
  1486. EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
  1487. UINT8 State;
  1488. VARIABLE_POINTER_TRACK *Variable;
  1489. VARIABLE_POINTER_TRACK NvVariable;
  1490. VARIABLE_STORE_HEADER *VariableStoreHeader;
  1491. VARIABLE_RUNTIME_CACHE *VolatileCacheInstance;
  1492. UINT8 *BufferForMerge;
  1493. UINTN MergedBufSize;
  1494. BOOLEAN DataReady;
  1495. UINTN DataOffset;
  1496. BOOLEAN IsCommonVariable;
  1497. BOOLEAN IsCommonUserVariable;
  1498. AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
  1499. BOOLEAN AuthFormat;
  1500. if ((mVariableModuleGlobal->FvbInstance == NULL) && !mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
  1501. //
  1502. // The FVB protocol is not ready, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.
  1503. //
  1504. if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
  1505. //
  1506. // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
  1507. //
  1508. DEBUG ((DEBUG_ERROR, "Update NV variable before EFI_VARIABLE_WRITE_ARCH_PROTOCOL ready - %r\n", EFI_NOT_AVAILABLE_YET));
  1509. return EFI_NOT_AVAILABLE_YET;
  1510. } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
  1511. //
  1512. // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL
  1513. // The authenticated variable perhaps is not initialized, just return here.
  1514. //
  1515. DEBUG ((DEBUG_ERROR, "Update AUTH variable before EFI_VARIABLE_WRITE_ARCH_PROTOCOL ready - %r\n", EFI_NOT_AVAILABLE_YET));
  1516. return EFI_NOT_AVAILABLE_YET;
  1517. }
  1518. }
  1519. AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
  1520. //
  1521. // Check if CacheVariable points to the variable in variable HOB.
  1522. // If yes, let CacheVariable points to the variable in NV variable cache.
  1523. //
  1524. if ((CacheVariable->CurrPtr != NULL) &&
  1525. (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) &&
  1526. (CacheVariable->StartPtr == GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)mVariableModuleGlobal->VariableGlobal.HobVariableBase))
  1527. )
  1528. {
  1529. CacheVariable->StartPtr = GetStartPointer (mNvVariableCache);
  1530. CacheVariable->EndPtr = GetEndPointer (mNvVariableCache);
  1531. CacheVariable->Volatile = FALSE;
  1532. Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable, AuthFormat);
  1533. if ((CacheVariable->CurrPtr == NULL) || EFI_ERROR (Status)) {
  1534. //
  1535. // There is no matched variable in NV variable cache.
  1536. //
  1537. if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0)) || (Attributes == 0)) {
  1538. //
  1539. // It is to delete variable,
  1540. // go to delete this variable in variable HOB and
  1541. // try to flush other variables from HOB to flash.
  1542. //
  1543. UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, FALSE, TRUE, FALSE, &gVariableInfo);
  1544. FlushHobVariableToFlash (VariableName, VendorGuid);
  1545. return EFI_SUCCESS;
  1546. }
  1547. }
  1548. }
  1549. if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {
  1550. Variable = CacheVariable;
  1551. } else {
  1552. //
  1553. // Update/Delete existing NV variable.
  1554. // CacheVariable points to the variable in the memory copy of Flash area
  1555. // Now let Variable points to the same variable in Flash area.
  1556. //
  1557. VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);
  1558. Variable = &NvVariable;
  1559. Variable->StartPtr = GetStartPointer (VariableStoreHeader);
  1560. Variable->EndPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->EndPtr - (UINTN)CacheVariable->StartPtr));
  1561. Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
  1562. if (CacheVariable->InDeletedTransitionPtr != NULL) {
  1563. Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
  1564. } else {
  1565. Variable->InDeletedTransitionPtr = NULL;
  1566. }
  1567. Variable->Volatile = FALSE;
  1568. }
  1569. Fvb = mVariableModuleGlobal->FvbInstance;
  1570. //
  1571. // Tricky part: Use scratch data area at the end of volatile variable store
  1572. // as a temporary storage.
  1573. //
  1574. NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *)((UINTN)mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));
  1575. ScratchSize = mVariableModuleGlobal->ScratchBufferSize;
  1576. SetMem (NextVariable, ScratchSize, 0xff);
  1577. DataReady = FALSE;
  1578. if (Variable->CurrPtr != NULL) {
  1579. //
  1580. // Update/Delete existing variable.
  1581. //
  1582. if (AtRuntime ()) {
  1583. //
  1584. // If AtRuntime and the variable is Volatile and Runtime Access,
  1585. // the volatile is ReadOnly, and SetVariable should be aborted and
  1586. // return EFI_WRITE_PROTECTED.
  1587. //
  1588. if (Variable->Volatile) {
  1589. Status = EFI_WRITE_PROTECTED;
  1590. goto Done;
  1591. }
  1592. //
  1593. // Only variable that have NV attributes can be updated/deleted in Runtime.
  1594. //
  1595. if ((CacheVariable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
  1596. Status = EFI_INVALID_PARAMETER;
  1597. goto Done;
  1598. }
  1599. //
  1600. // Only variable that have RT attributes can be updated/deleted in Runtime.
  1601. //
  1602. if ((CacheVariable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {
  1603. Status = EFI_INVALID_PARAMETER;
  1604. goto Done;
  1605. }
  1606. }
  1607. //
  1608. // Setting a data variable with no access, or zero DataSize attributes
  1609. // causes it to be deleted.
  1610. // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will
  1611. // not delete the variable.
  1612. //
  1613. if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0)) || ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
  1614. if (Variable->InDeletedTransitionPtr != NULL) {
  1615. //
  1616. // Both ADDED and IN_DELETED_TRANSITION variable are present,
  1617. // set IN_DELETED_TRANSITION one to DELETED state first.
  1618. //
  1619. ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
  1620. State = CacheVariable->InDeletedTransitionPtr->State;
  1621. State &= VAR_DELETED;
  1622. Status = UpdateVariableStore (
  1623. &mVariableModuleGlobal->VariableGlobal,
  1624. Variable->Volatile,
  1625. FALSE,
  1626. Fvb,
  1627. (UINTN)&Variable->InDeletedTransitionPtr->State,
  1628. sizeof (UINT8),
  1629. &State
  1630. );
  1631. if (!EFI_ERROR (Status)) {
  1632. if (!Variable->Volatile) {
  1633. CacheVariable->InDeletedTransitionPtr->State = State;
  1634. }
  1635. } else {
  1636. goto Done;
  1637. }
  1638. }
  1639. State = CacheVariable->CurrPtr->State;
  1640. State &= VAR_DELETED;
  1641. Status = UpdateVariableStore (
  1642. &mVariableModuleGlobal->VariableGlobal,
  1643. Variable->Volatile,
  1644. FALSE,
  1645. Fvb,
  1646. (UINTN)&Variable->CurrPtr->State,
  1647. sizeof (UINT8),
  1648. &State
  1649. );
  1650. if (!EFI_ERROR (Status)) {
  1651. UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE, &gVariableInfo);
  1652. if (!Variable->Volatile) {
  1653. CacheVariable->CurrPtr->State = State;
  1654. FlushHobVariableToFlash (VariableName, VendorGuid);
  1655. }
  1656. }
  1657. goto Done;
  1658. }
  1659. //
  1660. // If the variable is marked valid, and the same data has been passed in,
  1661. // then return to the caller immediately.
  1662. //
  1663. if ((DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) == DataSize) &&
  1664. (CompareMem (Data, GetVariableDataPtr (CacheVariable->CurrPtr, AuthFormat), DataSize) == 0) &&
  1665. ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
  1666. (TimeStamp == NULL))
  1667. {
  1668. //
  1669. // Variable content unchanged and no need to update timestamp, just return.
  1670. //
  1671. UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
  1672. Status = EFI_SUCCESS;
  1673. goto Done;
  1674. } else if ((CacheVariable->CurrPtr->State == VAR_ADDED) ||
  1675. (CacheVariable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION)))
  1676. {
  1677. //
  1678. // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable.
  1679. //
  1680. if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {
  1681. //
  1682. // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name.
  1683. // From DataOffset of NextVariable is to save the existing variable data.
  1684. //
  1685. DataOffset = GetVariableDataOffset (CacheVariable->CurrPtr, AuthFormat);
  1686. BufferForMerge = (UINT8 *)((UINTN)NextVariable + DataOffset);
  1687. CopyMem (
  1688. BufferForMerge,
  1689. (UINT8 *)((UINTN)CacheVariable->CurrPtr + DataOffset),
  1690. DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat)
  1691. );
  1692. //
  1693. // Set Max Auth/Non-Volatile/Volatile Variable Data Size as default MaxDataSize.
  1694. //
  1695. if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
  1696. MaxDataSize = mVariableModuleGlobal->MaxAuthVariableSize - DataOffset;
  1697. } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
  1698. MaxDataSize = mVariableModuleGlobal->MaxVariableSize - DataOffset;
  1699. } else {
  1700. MaxDataSize = mVariableModuleGlobal->MaxVolatileVariableSize - DataOffset;
  1701. }
  1702. //
  1703. // Append the new data to the end of existing data.
  1704. // Max Harware error record variable data size is different from common/auth variable.
  1705. //
  1706. if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  1707. MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;
  1708. }
  1709. if (DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) + DataSize > MaxDataSize) {
  1710. //
  1711. // Existing data size + new data size exceed maximum variable size limitation.
  1712. //
  1713. Status = EFI_INVALID_PARAMETER;
  1714. goto Done;
  1715. }
  1716. CopyMem (
  1717. (UINT8 *)(
  1718. (UINTN)BufferForMerge + DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat)
  1719. ),
  1720. Data,
  1721. DataSize
  1722. );
  1723. MergedBufSize = DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) +
  1724. DataSize;
  1725. //
  1726. // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
  1727. //
  1728. Data = BufferForMerge;
  1729. DataSize = MergedBufSize;
  1730. DataReady = TRUE;
  1731. }
  1732. //
  1733. // Mark the old variable as in delete transition.
  1734. //
  1735. State = CacheVariable->CurrPtr->State;
  1736. State &= VAR_IN_DELETED_TRANSITION;
  1737. Status = UpdateVariableStore (
  1738. &mVariableModuleGlobal->VariableGlobal,
  1739. Variable->Volatile,
  1740. FALSE,
  1741. Fvb,
  1742. (UINTN)&Variable->CurrPtr->State,
  1743. sizeof (UINT8),
  1744. &State
  1745. );
  1746. if (EFI_ERROR (Status)) {
  1747. goto Done;
  1748. }
  1749. if (!Variable->Volatile) {
  1750. CacheVariable->CurrPtr->State = State;
  1751. }
  1752. }
  1753. } else {
  1754. //
  1755. // Not found existing variable. Create a new variable.
  1756. //
  1757. if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {
  1758. Status = EFI_SUCCESS;
  1759. goto Done;
  1760. }
  1761. //
  1762. // Make sure we are trying to create a new variable.
  1763. // Setting a data variable with zero DataSize or no access attributes means to delete it.
  1764. //
  1765. if ((DataSize == 0) || ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
  1766. Status = EFI_NOT_FOUND;
  1767. goto Done;
  1768. }
  1769. //
  1770. // Only variable have NV|RT attribute can be created in Runtime.
  1771. //
  1772. if (AtRuntime () &&
  1773. (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0)))
  1774. {
  1775. Status = EFI_INVALID_PARAMETER;
  1776. goto Done;
  1777. }
  1778. }
  1779. //
  1780. // Function part - create a new variable and copy the data.
  1781. // Both update a variable and create a variable will come here.
  1782. //
  1783. NextVariable->StartId = VARIABLE_DATA;
  1784. //
  1785. // NextVariable->State = VAR_ADDED;
  1786. //
  1787. NextVariable->Reserved = 0;
  1788. if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
  1789. AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *)NextVariable;
  1790. AuthVariable->PubKeyIndex = KeyIndex;
  1791. AuthVariable->MonotonicCount = MonotonicCount;
  1792. ZeroMem (&AuthVariable->TimeStamp, sizeof (EFI_TIME));
  1793. if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&
  1794. (TimeStamp != NULL))
  1795. {
  1796. if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {
  1797. CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
  1798. } else {
  1799. //
  1800. // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only
  1801. // when the new TimeStamp value is later than the current timestamp associated
  1802. // with the variable, we need associate the new timestamp with the updated value.
  1803. //
  1804. if (Variable->CurrPtr != NULL) {
  1805. if (VariableCompareTimeStampInternal (&(((AUTHENTICATED_VARIABLE_HEADER *)CacheVariable->CurrPtr)->TimeStamp), TimeStamp)) {
  1806. CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));
  1807. } else {
  1808. CopyMem (&AuthVariable->TimeStamp, &(((AUTHENTICATED_VARIABLE_HEADER *)CacheVariable->CurrPtr)->TimeStamp), sizeof (EFI_TIME));
  1809. }
  1810. }
  1811. }
  1812. }
  1813. }
  1814. //
  1815. // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned
  1816. // Attributes bitmask parameter of a GetVariable() call.
  1817. //
  1818. NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
  1819. VarNameOffset = GetVariableHeaderSize (AuthFormat);
  1820. VarNameSize = StrSize (VariableName);
  1821. CopyMem (
  1822. (UINT8 *)((UINTN)NextVariable + VarNameOffset),
  1823. VariableName,
  1824. VarNameSize
  1825. );
  1826. VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);
  1827. //
  1828. // If DataReady is TRUE, it means the variable data has been saved into
  1829. // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.
  1830. //
  1831. if (!DataReady) {
  1832. CopyMem (
  1833. (UINT8 *)((UINTN)NextVariable + VarDataOffset),
  1834. Data,
  1835. DataSize
  1836. );
  1837. }
  1838. CopyMem (
  1839. GetVendorGuidPtr (NextVariable, AuthFormat),
  1840. VendorGuid,
  1841. sizeof (EFI_GUID)
  1842. );
  1843. //
  1844. // There will be pad bytes after Data, the NextVariable->NameSize and
  1845. // NextVariable->DataSize should not include pad size so that variable
  1846. // service can get actual size in GetVariable.
  1847. //
  1848. SetNameSizeOfVariable (NextVariable, VarNameSize, AuthFormat);
  1849. SetDataSizeOfVariable (NextVariable, DataSize, AuthFormat);
  1850. //
  1851. // The actual size of the variable that stores in storage should
  1852. // include pad size.
  1853. //
  1854. VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);
  1855. if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
  1856. //
  1857. // Create a nonvolatile variable.
  1858. //
  1859. Volatile = FALSE;
  1860. IsCommonVariable = FALSE;
  1861. IsCommonUserVariable = FALSE;
  1862. if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) {
  1863. IsCommonVariable = TRUE;
  1864. IsCommonUserVariable = IsUserVariable (NextVariable);
  1865. }
  1866. if ( ( ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)
  1867. && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))
  1868. || (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace))
  1869. || (IsCommonVariable && AtRuntime () && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace))
  1870. || (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)))
  1871. {
  1872. if (AtRuntime ()) {
  1873. if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
  1874. RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);
  1875. }
  1876. if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace)) {
  1877. RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);
  1878. }
  1879. Status = EFI_OUT_OF_RESOURCES;
  1880. goto Done;
  1881. }
  1882. //
  1883. // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
  1884. //
  1885. Status = Reclaim (
  1886. mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
  1887. &mVariableModuleGlobal->NonVolatileLastVariableOffset,
  1888. FALSE,
  1889. Variable,
  1890. NextVariable,
  1891. HEADER_ALIGN (VarSize)
  1892. );
  1893. if (!EFI_ERROR (Status)) {
  1894. //
  1895. // The new variable has been integrated successfully during reclaiming.
  1896. //
  1897. if (Variable->CurrPtr != NULL) {
  1898. CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN)CacheVariable->StartPtr + ((UINTN)Variable->CurrPtr - (UINTN)Variable->StartPtr));
  1899. CacheVariable->InDeletedTransitionPtr = NULL;
  1900. }
  1901. UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
  1902. FlushHobVariableToFlash (VariableName, VendorGuid);
  1903. } else {
  1904. if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
  1905. RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);
  1906. }
  1907. if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace)) {
  1908. RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);
  1909. }
  1910. }
  1911. goto Done;
  1912. }
  1913. if (!mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
  1914. //
  1915. // Four steps
  1916. // 1. Write variable header
  1917. // 2. Set variable state to header valid
  1918. // 3. Write variable data
  1919. // 4. Set variable state to valid
  1920. //
  1921. //
  1922. // Step 1:
  1923. //
  1924. Status = UpdateVariableStore (
  1925. &mVariableModuleGlobal->VariableGlobal,
  1926. FALSE,
  1927. TRUE,
  1928. Fvb,
  1929. mVariableModuleGlobal->NonVolatileLastVariableOffset,
  1930. (UINT32)GetVariableHeaderSize (AuthFormat),
  1931. (UINT8 *)NextVariable
  1932. );
  1933. if (EFI_ERROR (Status)) {
  1934. goto Done;
  1935. }
  1936. //
  1937. // Step 2:
  1938. //
  1939. NextVariable->State = VAR_HEADER_VALID_ONLY;
  1940. Status = UpdateVariableStore (
  1941. &mVariableModuleGlobal->VariableGlobal,
  1942. FALSE,
  1943. TRUE,
  1944. Fvb,
  1945. mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
  1946. sizeof (UINT8),
  1947. &NextVariable->State
  1948. );
  1949. if (EFI_ERROR (Status)) {
  1950. goto Done;
  1951. }
  1952. //
  1953. // Step 3:
  1954. //
  1955. Status = UpdateVariableStore (
  1956. &mVariableModuleGlobal->VariableGlobal,
  1957. FALSE,
  1958. TRUE,
  1959. Fvb,
  1960. mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (AuthFormat),
  1961. (UINT32)(VarSize - GetVariableHeaderSize (AuthFormat)),
  1962. (UINT8 *)NextVariable + GetVariableHeaderSize (AuthFormat)
  1963. );
  1964. if (EFI_ERROR (Status)) {
  1965. goto Done;
  1966. }
  1967. //
  1968. // Step 4:
  1969. //
  1970. NextVariable->State = VAR_ADDED;
  1971. Status = UpdateVariableStore (
  1972. &mVariableModuleGlobal->VariableGlobal,
  1973. FALSE,
  1974. TRUE,
  1975. Fvb,
  1976. mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
  1977. sizeof (UINT8),
  1978. &NextVariable->State
  1979. );
  1980. if (EFI_ERROR (Status)) {
  1981. goto Done;
  1982. }
  1983. //
  1984. // Update the memory copy of Flash region.
  1985. //
  1986. CopyMem ((UINT8 *)mNvVariableCache + mVariableModuleGlobal->NonVolatileLastVariableOffset, (UINT8 *)NextVariable, VarSize);
  1987. } else {
  1988. //
  1989. // Emulated non-volatile variable mode.
  1990. //
  1991. NextVariable->State = VAR_ADDED;
  1992. Status = UpdateVariableStore (
  1993. &mVariableModuleGlobal->VariableGlobal,
  1994. FALSE,
  1995. TRUE,
  1996. Fvb,
  1997. mVariableModuleGlobal->NonVolatileLastVariableOffset,
  1998. (UINT32)VarSize,
  1999. (UINT8 *)NextVariable
  2000. );
  2001. if (EFI_ERROR (Status)) {
  2002. goto Done;
  2003. }
  2004. }
  2005. mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);
  2006. if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
  2007. mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);
  2008. } else {
  2009. mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);
  2010. if (IsCommonUserVariable) {
  2011. mVariableModuleGlobal->CommonUserVariableTotalSize += HEADER_ALIGN (VarSize);
  2012. }
  2013. }
  2014. } else {
  2015. //
  2016. // Create a volatile variable.
  2017. //
  2018. Volatile = TRUE;
  2019. if ((UINT32)(VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >
  2020. ((VARIABLE_STORE_HEADER *)((UINTN)(mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size)
  2021. {
  2022. //
  2023. // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.
  2024. //
  2025. Status = Reclaim (
  2026. mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
  2027. &mVariableModuleGlobal->VolatileLastVariableOffset,
  2028. TRUE,
  2029. Variable,
  2030. NextVariable,
  2031. HEADER_ALIGN (VarSize)
  2032. );
  2033. if (!EFI_ERROR (Status)) {
  2034. //
  2035. // The new variable has been integrated successfully during reclaiming.
  2036. //
  2037. if (Variable->CurrPtr != NULL) {
  2038. CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN)CacheVariable->StartPtr + ((UINTN)Variable->CurrPtr - (UINTN)Variable->StartPtr));
  2039. CacheVariable->InDeletedTransitionPtr = NULL;
  2040. }
  2041. UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
  2042. }
  2043. goto Done;
  2044. }
  2045. NextVariable->State = VAR_ADDED;
  2046. Status = UpdateVariableStore (
  2047. &mVariableModuleGlobal->VariableGlobal,
  2048. TRUE,
  2049. TRUE,
  2050. Fvb,
  2051. mVariableModuleGlobal->VolatileLastVariableOffset,
  2052. (UINT32)VarSize,
  2053. (UINT8 *)NextVariable
  2054. );
  2055. if (EFI_ERROR (Status)) {
  2056. goto Done;
  2057. }
  2058. mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);
  2059. }
  2060. //
  2061. // Mark the old variable as deleted.
  2062. //
  2063. if (!EFI_ERROR (Status) && (Variable->CurrPtr != NULL)) {
  2064. if (Variable->InDeletedTransitionPtr != NULL) {
  2065. //
  2066. // Both ADDED and IN_DELETED_TRANSITION old variable are present,
  2067. // set IN_DELETED_TRANSITION one to DELETED state first.
  2068. //
  2069. ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
  2070. State = CacheVariable->InDeletedTransitionPtr->State;
  2071. State &= VAR_DELETED;
  2072. Status = UpdateVariableStore (
  2073. &mVariableModuleGlobal->VariableGlobal,
  2074. Variable->Volatile,
  2075. FALSE,
  2076. Fvb,
  2077. (UINTN)&Variable->InDeletedTransitionPtr->State,
  2078. sizeof (UINT8),
  2079. &State
  2080. );
  2081. if (!EFI_ERROR (Status)) {
  2082. if (!Variable->Volatile) {
  2083. CacheVariable->InDeletedTransitionPtr->State = State;
  2084. }
  2085. } else {
  2086. goto Done;
  2087. }
  2088. }
  2089. State = CacheVariable->CurrPtr->State;
  2090. State &= VAR_DELETED;
  2091. Status = UpdateVariableStore (
  2092. &mVariableModuleGlobal->VariableGlobal,
  2093. Variable->Volatile,
  2094. FALSE,
  2095. Fvb,
  2096. (UINTN)&Variable->CurrPtr->State,
  2097. sizeof (UINT8),
  2098. &State
  2099. );
  2100. if (!EFI_ERROR (Status) && !Variable->Volatile) {
  2101. CacheVariable->CurrPtr->State = State;
  2102. }
  2103. }
  2104. if (!EFI_ERROR (Status)) {
  2105. UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
  2106. if (!Volatile) {
  2107. FlushHobVariableToFlash (VariableName, VendorGuid);
  2108. }
  2109. }
  2110. Done:
  2111. if (!EFI_ERROR (Status)) {
  2112. if (((Variable->CurrPtr != NULL) && !Variable->Volatile) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0)) {
  2113. VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache);
  2114. } else {
  2115. VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache);
  2116. }
  2117. if (VolatileCacheInstance->Store != NULL) {
  2118. Status = SynchronizeRuntimeVariableCache (
  2119. VolatileCacheInstance,
  2120. 0,
  2121. VolatileCacheInstance->Store->Size
  2122. );
  2123. ASSERT_EFI_ERROR (Status);
  2124. }
  2125. }
  2126. return Status;
  2127. }
  2128. /**
  2129. This code finds variable in storage blocks (Volatile or Non-Volatile).
  2130. Caution: This function may receive untrusted input.
  2131. This function may be invoked in SMM mode, and datasize is external input.
  2132. This function will do basic validation, before parse the data.
  2133. @param VariableName Name of Variable to be found.
  2134. @param VendorGuid Variable vendor GUID.
  2135. @param Attributes Attribute value of the variable found.
  2136. @param DataSize Size of Data found. If size is less than the
  2137. data, this value contains the required size.
  2138. @param Data The buffer to return the contents of the variable. May be NULL
  2139. with a zero DataSize in order to determine the size buffer needed.
  2140. @return EFI_INVALID_PARAMETER Invalid parameter.
  2141. @return EFI_SUCCESS Find the specified variable.
  2142. @return EFI_NOT_FOUND Not found.
  2143. @return EFI_BUFFER_TO_SMALL DataSize is too small for the result.
  2144. **/
  2145. EFI_STATUS
  2146. EFIAPI
  2147. VariableServiceGetVariable (
  2148. IN CHAR16 *VariableName,
  2149. IN EFI_GUID *VendorGuid,
  2150. OUT UINT32 *Attributes OPTIONAL,
  2151. IN OUT UINTN *DataSize,
  2152. OUT VOID *Data OPTIONAL
  2153. )
  2154. {
  2155. EFI_STATUS Status;
  2156. VARIABLE_POINTER_TRACK Variable;
  2157. UINTN VarDataSize;
  2158. if ((VariableName == NULL) || (VendorGuid == NULL) || (DataSize == NULL)) {
  2159. return EFI_INVALID_PARAMETER;
  2160. }
  2161. if (VariableName[0] == 0) {
  2162. return EFI_NOT_FOUND;
  2163. }
  2164. AcquireLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2165. Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
  2166. if ((Variable.CurrPtr == NULL) || EFI_ERROR (Status)) {
  2167. goto Done;
  2168. }
  2169. //
  2170. // Get data size
  2171. //
  2172. VarDataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2173. ASSERT (VarDataSize != 0);
  2174. if (*DataSize >= VarDataSize) {
  2175. if (Data == NULL) {
  2176. Status = EFI_INVALID_PARAMETER;
  2177. goto Done;
  2178. }
  2179. CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), VarDataSize);
  2180. *DataSize = VarDataSize;
  2181. UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE, &gVariableInfo);
  2182. Status = EFI_SUCCESS;
  2183. goto Done;
  2184. } else {
  2185. *DataSize = VarDataSize;
  2186. Status = EFI_BUFFER_TOO_SMALL;
  2187. goto Done;
  2188. }
  2189. Done:
  2190. if ((Status == EFI_SUCCESS) || (Status == EFI_BUFFER_TOO_SMALL)) {
  2191. if ((Attributes != NULL) && (Variable.CurrPtr != NULL)) {
  2192. *Attributes = Variable.CurrPtr->Attributes;
  2193. }
  2194. }
  2195. ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2196. return Status;
  2197. }
  2198. /**
  2199. This code Finds the Next available variable.
  2200. Caution: This function may receive untrusted input.
  2201. This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
  2202. @param VariableNameSize The size of the VariableName buffer. The size must be large
  2203. enough to fit input string supplied in VariableName buffer.
  2204. @param VariableName Pointer to variable name.
  2205. @param VendorGuid Variable Vendor Guid.
  2206. @retval EFI_SUCCESS The function completed successfully.
  2207. @retval EFI_NOT_FOUND The next variable was not found.
  2208. @retval EFI_BUFFER_TOO_SMALL The VariableNameSize is too small for the result.
  2209. VariableNameSize has been updated with the size needed to complete the request.
  2210. @retval EFI_INVALID_PARAMETER VariableNameSize is NULL.
  2211. @retval EFI_INVALID_PARAMETER VariableName is NULL.
  2212. @retval EFI_INVALID_PARAMETER VendorGuid is NULL.
  2213. @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
  2214. GUID of an existing variable.
  2215. @retval EFI_INVALID_PARAMETER Null-terminator is not found in the first VariableNameSize bytes of
  2216. the input VariableName buffer.
  2217. **/
  2218. EFI_STATUS
  2219. EFIAPI
  2220. VariableServiceGetNextVariableName (
  2221. IN OUT UINTN *VariableNameSize,
  2222. IN OUT CHAR16 *VariableName,
  2223. IN OUT EFI_GUID *VendorGuid
  2224. )
  2225. {
  2226. EFI_STATUS Status;
  2227. UINTN MaxLen;
  2228. UINTN VarNameSize;
  2229. BOOLEAN AuthFormat;
  2230. VARIABLE_HEADER *VariablePtr;
  2231. VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
  2232. if ((VariableNameSize == NULL) || (VariableName == NULL) || (VendorGuid == NULL)) {
  2233. return EFI_INVALID_PARAMETER;
  2234. }
  2235. AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
  2236. //
  2237. // Calculate the possible maximum length of name string, including the Null terminator.
  2238. //
  2239. MaxLen = *VariableNameSize / sizeof (CHAR16);
  2240. if ((MaxLen == 0) || (StrnLenS (VariableName, MaxLen) == MaxLen)) {
  2241. //
  2242. // Null-terminator is not found in the first VariableNameSize bytes of the input VariableName buffer,
  2243. // follow spec to return EFI_INVALID_PARAMETER.
  2244. //
  2245. return EFI_INVALID_PARAMETER;
  2246. }
  2247. AcquireLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2248. //
  2249. // 0: Volatile, 1: HOB, 2: Non-Volatile.
  2250. // The index and attributes mapping must be kept in this order as FindVariable
  2251. // makes use of this mapping to implement search algorithm.
  2252. //
  2253. VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *)(UINTN)mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
  2254. VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *)(UINTN)mVariableModuleGlobal->VariableGlobal.HobVariableBase;
  2255. VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache;
  2256. Status = VariableServiceGetNextVariableInternal (
  2257. VariableName,
  2258. VendorGuid,
  2259. VariableStoreHeader,
  2260. &VariablePtr,
  2261. AuthFormat
  2262. );
  2263. if (!EFI_ERROR (Status)) {
  2264. VarNameSize = NameSizeOfVariable (VariablePtr, AuthFormat);
  2265. ASSERT (VarNameSize != 0);
  2266. if (VarNameSize <= *VariableNameSize) {
  2267. CopyMem (
  2268. VariableName,
  2269. GetVariableNamePtr (VariablePtr, AuthFormat),
  2270. VarNameSize
  2271. );
  2272. CopyMem (
  2273. VendorGuid,
  2274. GetVendorGuidPtr (VariablePtr, AuthFormat),
  2275. sizeof (EFI_GUID)
  2276. );
  2277. Status = EFI_SUCCESS;
  2278. } else {
  2279. Status = EFI_BUFFER_TOO_SMALL;
  2280. }
  2281. *VariableNameSize = VarNameSize;
  2282. }
  2283. ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2284. return Status;
  2285. }
  2286. /**
  2287. This code sets variable in storage blocks (Volatile or Non-Volatile).
  2288. Caution: This function may receive untrusted input.
  2289. This function may be invoked in SMM mode, and datasize and data are external input.
  2290. This function will do basic validation, before parse the data.
  2291. This function will parse the authentication carefully to avoid security issues, like
  2292. buffer overflow, integer overflow.
  2293. This function will check attribute carefully to avoid authentication bypass.
  2294. @param VariableName Name of Variable to be found.
  2295. @param VendorGuid Variable vendor GUID.
  2296. @param Attributes Attribute value of the variable found
  2297. @param DataSize Size of Data found. If size is less than the
  2298. data, this value contains the required size.
  2299. @param Data Data pointer.
  2300. @return EFI_INVALID_PARAMETER Invalid parameter.
  2301. @return EFI_SUCCESS Set successfully.
  2302. @return EFI_OUT_OF_RESOURCES Resource not enough to set variable.
  2303. @return EFI_NOT_FOUND Not found.
  2304. @return EFI_WRITE_PROTECTED Variable is read-only.
  2305. **/
  2306. EFI_STATUS
  2307. EFIAPI
  2308. VariableServiceSetVariable (
  2309. IN CHAR16 *VariableName,
  2310. IN EFI_GUID *VendorGuid,
  2311. IN UINT32 Attributes,
  2312. IN UINTN DataSize,
  2313. IN VOID *Data
  2314. )
  2315. {
  2316. VARIABLE_POINTER_TRACK Variable;
  2317. EFI_STATUS Status;
  2318. VARIABLE_HEADER *NextVariable;
  2319. EFI_PHYSICAL_ADDRESS Point;
  2320. UINTN PayloadSize;
  2321. BOOLEAN AuthFormat;
  2322. AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
  2323. //
  2324. // Check input parameters.
  2325. //
  2326. if ((VariableName == NULL) || (VariableName[0] == 0) || (VendorGuid == NULL)) {
  2327. return EFI_INVALID_PARAMETER;
  2328. }
  2329. if ((DataSize != 0) && (Data == NULL)) {
  2330. return EFI_INVALID_PARAMETER;
  2331. }
  2332. //
  2333. // Check for reserverd bit in variable attribute.
  2334. // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is deprecated but we still allow
  2335. // the delete operation of common authenticated variable at user physical presence.
  2336. // So leave EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS attribute check to AuthVariableLib
  2337. //
  2338. if ((Attributes & (~(EFI_VARIABLE_ATTRIBUTES_MASK | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS))) != 0) {
  2339. return EFI_INVALID_PARAMETER;
  2340. }
  2341. //
  2342. // Check if the combination of attribute bits is valid.
  2343. //
  2344. if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
  2345. //
  2346. // Make sure if runtime bit is set, boot service bit is set also.
  2347. //
  2348. if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
  2349. return EFI_UNSUPPORTED;
  2350. } else {
  2351. return EFI_INVALID_PARAMETER;
  2352. }
  2353. } else if ((Attributes & EFI_VARIABLE_ATTRIBUTES_MASK) == EFI_VARIABLE_NON_VOLATILE) {
  2354. //
  2355. // Only EFI_VARIABLE_NON_VOLATILE attribute is invalid
  2356. //
  2357. if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
  2358. return EFI_UNSUPPORTED;
  2359. } else {
  2360. return EFI_INVALID_PARAMETER;
  2361. }
  2362. } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
  2363. if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {
  2364. //
  2365. // Not support authenticated variable write.
  2366. //
  2367. return EFI_INVALID_PARAMETER;
  2368. }
  2369. } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
  2370. if (PcdGet32 (PcdHwErrStorageSize) == 0) {
  2371. //
  2372. // Not support harware error record variable variable.
  2373. //
  2374. return EFI_INVALID_PARAMETER;
  2375. }
  2376. }
  2377. //
  2378. // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute
  2379. // cannot be set both.
  2380. //
  2381. if ( ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
  2382. && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS))
  2383. {
  2384. return EFI_UNSUPPORTED;
  2385. }
  2386. if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
  2387. //
  2388. // If DataSize == AUTHINFO_SIZE and then PayloadSize is 0.
  2389. // Maybe it's the delete operation of common authenticated variable at user physical presence.
  2390. //
  2391. if (DataSize != AUTHINFO_SIZE) {
  2392. return EFI_UNSUPPORTED;
  2393. }
  2394. PayloadSize = DataSize - AUTHINFO_SIZE;
  2395. } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
  2396. //
  2397. // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.
  2398. //
  2399. if ((DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA) ||
  2400. (((EFI_VARIABLE_AUTHENTICATION_2 *)Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo))) ||
  2401. (((EFI_VARIABLE_AUTHENTICATION_2 *)Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)))
  2402. {
  2403. return EFI_SECURITY_VIOLATION;
  2404. }
  2405. //
  2406. // The VariableSpeculationBarrier() call here is to ensure the above sanity
  2407. // check for the EFI_VARIABLE_AUTHENTICATION_2 descriptor has been completed
  2408. // before the execution of subsequent codes.
  2409. //
  2410. VariableSpeculationBarrier ();
  2411. PayloadSize = DataSize - AUTHINFO2_SIZE (Data);
  2412. } else {
  2413. PayloadSize = DataSize;
  2414. }
  2415. if ((UINTN)(~0) - PayloadSize < StrSize (VariableName)) {
  2416. //
  2417. // Prevent whole variable size overflow
  2418. //
  2419. return EFI_INVALID_PARAMETER;
  2420. }
  2421. //
  2422. // The size of the VariableName, including the Unicode Null in bytes plus
  2423. // the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)
  2424. // bytes for HwErrRec#### variable.
  2425. //
  2426. if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  2427. if (StrSize (VariableName) + PayloadSize >
  2428. PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize (AuthFormat))
  2429. {
  2430. return EFI_INVALID_PARAMETER;
  2431. }
  2432. } else {
  2433. //
  2434. // The size of the VariableName, including the Unicode Null in bytes plus
  2435. // the DataSize is limited to maximum size of Max(Auth|Volatile)VariableSize bytes.
  2436. //
  2437. if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
  2438. if (StrSize (VariableName) + PayloadSize >
  2439. mVariableModuleGlobal->MaxAuthVariableSize -
  2440. GetVariableHeaderSize (AuthFormat))
  2441. {
  2442. DEBUG ((
  2443. DEBUG_ERROR,
  2444. "%a: Failed to set variable '%s' with Guid %g\n",
  2445. __FUNCTION__,
  2446. VariableName,
  2447. VendorGuid
  2448. ));
  2449. DEBUG ((
  2450. DEBUG_ERROR,
  2451. "NameSize(0x%x) + PayloadSize(0x%x) > "
  2452. "MaxAuthVariableSize(0x%x) - HeaderSize(0x%x)\n",
  2453. StrSize (VariableName),
  2454. PayloadSize,
  2455. mVariableModuleGlobal->MaxAuthVariableSize,
  2456. GetVariableHeaderSize (AuthFormat)
  2457. ));
  2458. return EFI_INVALID_PARAMETER;
  2459. }
  2460. } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
  2461. if (StrSize (VariableName) + PayloadSize >
  2462. mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize (AuthFormat))
  2463. {
  2464. DEBUG ((
  2465. DEBUG_ERROR,
  2466. "%a: Failed to set variable '%s' with Guid %g\n",
  2467. __FUNCTION__,
  2468. VariableName,
  2469. VendorGuid
  2470. ));
  2471. DEBUG ((
  2472. DEBUG_ERROR,
  2473. "NameSize(0x%x) + PayloadSize(0x%x) > "
  2474. "MaxVariableSize(0x%x) - HeaderSize(0x%x)\n",
  2475. StrSize (VariableName),
  2476. PayloadSize,
  2477. mVariableModuleGlobal->MaxVariableSize,
  2478. GetVariableHeaderSize (AuthFormat)
  2479. ));
  2480. return EFI_INVALID_PARAMETER;
  2481. }
  2482. } else {
  2483. if (StrSize (VariableName) + PayloadSize >
  2484. mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize (AuthFormat))
  2485. {
  2486. DEBUG ((
  2487. DEBUG_ERROR,
  2488. "%a: Failed to set variable '%s' with Guid %g\n",
  2489. __FUNCTION__,
  2490. VariableName,
  2491. VendorGuid
  2492. ));
  2493. DEBUG ((
  2494. DEBUG_ERROR,
  2495. "NameSize(0x%x) + PayloadSize(0x%x) > "
  2496. "MaxVolatileVariableSize(0x%x) - HeaderSize(0x%x)\n",
  2497. StrSize (VariableName),
  2498. PayloadSize,
  2499. mVariableModuleGlobal->MaxVolatileVariableSize,
  2500. GetVariableHeaderSize (AuthFormat)
  2501. ));
  2502. return EFI_INVALID_PARAMETER;
  2503. }
  2504. }
  2505. }
  2506. //
  2507. // Special Handling for MOR Lock variable.
  2508. //
  2509. Status = SetVariableCheckHandlerMor (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *)((UINTN)Data + DataSize - PayloadSize));
  2510. if (Status == EFI_ALREADY_STARTED) {
  2511. //
  2512. // EFI_ALREADY_STARTED means the SetVariable() action is handled inside of SetVariableCheckHandlerMor().
  2513. // Variable driver can just return SUCCESS.
  2514. //
  2515. return EFI_SUCCESS;
  2516. }
  2517. if (EFI_ERROR (Status)) {
  2518. return Status;
  2519. }
  2520. Status = VarCheckLibSetVariableCheck (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *)((UINTN)Data + DataSize - PayloadSize), mRequestSource);
  2521. if (EFI_ERROR (Status)) {
  2522. return Status;
  2523. }
  2524. AcquireLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2525. //
  2526. // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.
  2527. //
  2528. if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {
  2529. Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;
  2530. //
  2531. // Parse non-volatile variable data and get last variable offset.
  2532. //
  2533. NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)Point);
  2534. while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)Point))) {
  2535. NextVariable = GetNextVariablePtr (NextVariable, AuthFormat);
  2536. }
  2537. mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN)NextVariable - (UINTN)Point;
  2538. }
  2539. //
  2540. // Check whether the input variable is already existed.
  2541. //
  2542. Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);
  2543. if (!EFI_ERROR (Status)) {
  2544. if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {
  2545. Status = EFI_WRITE_PROTECTED;
  2546. goto Done;
  2547. }
  2548. if ((Attributes != 0) && ((Attributes & (~EFI_VARIABLE_APPEND_WRITE)) != Variable.CurrPtr->Attributes)) {
  2549. //
  2550. // If a preexisting variable is rewritten with different attributes, SetVariable() shall not
  2551. // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:
  2552. // 1. No access attributes specified
  2553. // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE
  2554. //
  2555. Status = EFI_INVALID_PARAMETER;
  2556. DEBUG ((DEBUG_INFO, "[Variable]: Rewritten a preexisting variable(0x%08x) with different attributes(0x%08x) - %g:%s\n", Variable.CurrPtr->Attributes, Attributes, VendorGuid, VariableName));
  2557. goto Done;
  2558. }
  2559. }
  2560. if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
  2561. //
  2562. // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.
  2563. //
  2564. Status = AutoUpdateLangVariable (VariableName, Data, DataSize);
  2565. if (EFI_ERROR (Status)) {
  2566. //
  2567. // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.
  2568. //
  2569. goto Done;
  2570. }
  2571. }
  2572. if (mVariableModuleGlobal->VariableGlobal.AuthSupport) {
  2573. Status = AuthVariableLibProcessVariable (VariableName, VendorGuid, Data, DataSize, Attributes);
  2574. } else {
  2575. Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, 0, 0, &Variable, NULL);
  2576. }
  2577. Done:
  2578. InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);
  2579. ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2580. if (!AtRuntime ()) {
  2581. if (!EFI_ERROR (Status)) {
  2582. SecureBootHook (
  2583. VariableName,
  2584. VendorGuid
  2585. );
  2586. }
  2587. }
  2588. return Status;
  2589. }
  2590. /**
  2591. This code returns information about the EFI variables.
  2592. Caution: This function may receive untrusted input.
  2593. This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
  2594. @param Attributes Attributes bitmask to specify the type of variables
  2595. on which to return information.
  2596. @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
  2597. for the EFI variables associated with the attributes specified.
  2598. @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
  2599. for EFI variables associated with the attributes specified.
  2600. @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
  2601. associated with the attributes specified.
  2602. @return EFI_SUCCESS Query successfully.
  2603. **/
  2604. EFI_STATUS
  2605. EFIAPI
  2606. VariableServiceQueryVariableInfoInternal (
  2607. IN UINT32 Attributes,
  2608. OUT UINT64 *MaximumVariableStorageSize,
  2609. OUT UINT64 *RemainingVariableStorageSize,
  2610. OUT UINT64 *MaximumVariableSize
  2611. )
  2612. {
  2613. VARIABLE_HEADER *Variable;
  2614. VARIABLE_HEADER *NextVariable;
  2615. UINT64 VariableSize;
  2616. VARIABLE_STORE_HEADER *VariableStoreHeader;
  2617. UINT64 CommonVariableTotalSize;
  2618. UINT64 HwErrVariableTotalSize;
  2619. EFI_STATUS Status;
  2620. VARIABLE_POINTER_TRACK VariablePtrTrack;
  2621. CommonVariableTotalSize = 0;
  2622. HwErrVariableTotalSize = 0;
  2623. if ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {
  2624. //
  2625. // Query is Volatile related.
  2626. //
  2627. VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);
  2628. } else {
  2629. //
  2630. // Query is Non-Volatile related.
  2631. //
  2632. VariableStoreHeader = mNvVariableCache;
  2633. }
  2634. //
  2635. // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize
  2636. // with the storage size (excluding the storage header size).
  2637. //
  2638. *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
  2639. //
  2640. // Harware error record variable needs larger size.
  2641. //
  2642. if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
  2643. *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
  2644. *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) -
  2645. GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2646. } else {
  2647. if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
  2648. if (AtRuntime ()) {
  2649. *MaximumVariableStorageSize = mVariableModuleGlobal->CommonRuntimeVariableSpace;
  2650. } else {
  2651. *MaximumVariableStorageSize = mVariableModuleGlobal->CommonVariableSpace;
  2652. }
  2653. }
  2654. //
  2655. // Let *MaximumVariableSize be Max(Auth|Volatile)VariableSize with the exception of the variable header size.
  2656. //
  2657. if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
  2658. *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize -
  2659. GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2660. } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
  2661. *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize -
  2662. GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2663. } else {
  2664. *MaximumVariableSize = mVariableModuleGlobal->MaxVolatileVariableSize -
  2665. GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2666. }
  2667. }
  2668. //
  2669. // Point to the starting address of the variables.
  2670. //
  2671. Variable = GetStartPointer (VariableStoreHeader);
  2672. //
  2673. // Now walk through the related variable store.
  2674. //
  2675. while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
  2676. NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2677. VariableSize = (UINT64)(UINTN)NextVariable - (UINT64)(UINTN)Variable;
  2678. if (AtRuntime ()) {
  2679. //
  2680. // We don't take the state of the variables in mind
  2681. // when calculating RemainingVariableStorageSize,
  2682. // since the space occupied by variables not marked with
  2683. // VAR_ADDED is not allowed to be reclaimed in Runtime.
  2684. //
  2685. if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  2686. HwErrVariableTotalSize += VariableSize;
  2687. } else {
  2688. CommonVariableTotalSize += VariableSize;
  2689. }
  2690. } else {
  2691. //
  2692. // Only care about Variables with State VAR_ADDED, because
  2693. // the space not marked as VAR_ADDED is reclaimable now.
  2694. //
  2695. if (Variable->State == VAR_ADDED) {
  2696. if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  2697. HwErrVariableTotalSize += VariableSize;
  2698. } else {
  2699. CommonVariableTotalSize += VariableSize;
  2700. }
  2701. } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
  2702. //
  2703. // If it is a IN_DELETED_TRANSITION variable,
  2704. // and there is not also a same ADDED one at the same time,
  2705. // this IN_DELETED_TRANSITION variable is valid.
  2706. //
  2707. VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
  2708. VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader);
  2709. Status = FindVariableEx (
  2710. GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  2711. GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  2712. FALSE,
  2713. &VariablePtrTrack,
  2714. mVariableModuleGlobal->VariableGlobal.AuthFormat
  2715. );
  2716. if (!EFI_ERROR (Status) && (VariablePtrTrack.CurrPtr->State != VAR_ADDED)) {
  2717. if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  2718. HwErrVariableTotalSize += VariableSize;
  2719. } else {
  2720. CommonVariableTotalSize += VariableSize;
  2721. }
  2722. }
  2723. }
  2724. }
  2725. //
  2726. // Go to the next one.
  2727. //
  2728. Variable = NextVariable;
  2729. }
  2730. if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  2731. *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;
  2732. } else {
  2733. if (*MaximumVariableStorageSize < CommonVariableTotalSize) {
  2734. *RemainingVariableStorageSize = 0;
  2735. } else {
  2736. *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;
  2737. }
  2738. }
  2739. if (*RemainingVariableStorageSize < GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat)) {
  2740. *MaximumVariableSize = 0;
  2741. } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat)) <
  2742. *MaximumVariableSize
  2743. )
  2744. {
  2745. *MaximumVariableSize = *RemainingVariableStorageSize -
  2746. GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
  2747. }
  2748. return EFI_SUCCESS;
  2749. }
  2750. /**
  2751. This code returns information about the EFI variables.
  2752. Caution: This function may receive untrusted input.
  2753. This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
  2754. @param Attributes Attributes bitmask to specify the type of variables
  2755. on which to return information.
  2756. @param MaximumVariableStorageSize Pointer to the maximum size of the storage space available
  2757. for the EFI variables associated with the attributes specified.
  2758. @param RemainingVariableStorageSize Pointer to the remaining size of the storage space available
  2759. for EFI variables associated with the attributes specified.
  2760. @param MaximumVariableSize Pointer to the maximum size of an individual EFI variables
  2761. associated with the attributes specified.
  2762. @return EFI_INVALID_PARAMETER An invalid combination of attribute bits was supplied.
  2763. @return EFI_SUCCESS Query successfully.
  2764. @return EFI_UNSUPPORTED The attribute is not supported on this platform.
  2765. **/
  2766. EFI_STATUS
  2767. EFIAPI
  2768. VariableServiceQueryVariableInfo (
  2769. IN UINT32 Attributes,
  2770. OUT UINT64 *MaximumVariableStorageSize,
  2771. OUT UINT64 *RemainingVariableStorageSize,
  2772. OUT UINT64 *MaximumVariableSize
  2773. )
  2774. {
  2775. EFI_STATUS Status;
  2776. if ((MaximumVariableStorageSize == NULL) || (RemainingVariableStorageSize == NULL) || (MaximumVariableSize == NULL) || (Attributes == 0)) {
  2777. return EFI_INVALID_PARAMETER;
  2778. }
  2779. if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {
  2780. //
  2781. // Deprecated attribute, make this check as highest priority.
  2782. //
  2783. return EFI_UNSUPPORTED;
  2784. }
  2785. if ((Attributes & EFI_VARIABLE_ATTRIBUTES_MASK) == 0) {
  2786. //
  2787. // Make sure the Attributes combination is supported by the platform.
  2788. //
  2789. return EFI_UNSUPPORTED;
  2790. } else if ((Attributes & EFI_VARIABLE_ATTRIBUTES_MASK) == EFI_VARIABLE_NON_VOLATILE) {
  2791. //
  2792. // Only EFI_VARIABLE_NON_VOLATILE attribute is invalid
  2793. //
  2794. return EFI_INVALID_PARAMETER;
  2795. } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {
  2796. //
  2797. // Make sure if runtime bit is set, boot service bit is set also.
  2798. //
  2799. return EFI_INVALID_PARAMETER;
  2800. } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {
  2801. //
  2802. // Make sure RT Attribute is set if we are in Runtime phase.
  2803. //
  2804. return EFI_INVALID_PARAMETER;
  2805. } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
  2806. //
  2807. // Make sure Hw Attribute is set with NV.
  2808. //
  2809. return EFI_INVALID_PARAMETER;
  2810. } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
  2811. if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {
  2812. //
  2813. // Not support authenticated variable write.
  2814. //
  2815. return EFI_UNSUPPORTED;
  2816. }
  2817. } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {
  2818. if (PcdGet32 (PcdHwErrStorageSize) == 0) {
  2819. //
  2820. // Not support harware error record variable variable.
  2821. //
  2822. return EFI_UNSUPPORTED;
  2823. }
  2824. }
  2825. AcquireLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2826. Status = VariableServiceQueryVariableInfoInternal (
  2827. Attributes,
  2828. MaximumVariableStorageSize,
  2829. RemainingVariableStorageSize,
  2830. MaximumVariableSize
  2831. );
  2832. ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  2833. return Status;
  2834. }
  2835. /**
  2836. This function reclaims variable storage if free size is below the threshold.
  2837. Caution: This function may be invoked at SMM mode.
  2838. Care must be taken to make sure not security issue.
  2839. **/
  2840. VOID
  2841. ReclaimForOS (
  2842. VOID
  2843. )
  2844. {
  2845. EFI_STATUS Status;
  2846. UINTN RemainingCommonRuntimeVariableSpace;
  2847. UINTN RemainingHwErrVariableSpace;
  2848. STATIC BOOLEAN Reclaimed;
  2849. //
  2850. // This function will be called only once at EndOfDxe or ReadyToBoot event.
  2851. //
  2852. if (Reclaimed) {
  2853. return;
  2854. }
  2855. Reclaimed = TRUE;
  2856. Status = EFI_SUCCESS;
  2857. if (mVariableModuleGlobal->CommonRuntimeVariableSpace < mVariableModuleGlobal->CommonVariableTotalSize) {
  2858. RemainingCommonRuntimeVariableSpace = 0;
  2859. } else {
  2860. RemainingCommonRuntimeVariableSpace = mVariableModuleGlobal->CommonRuntimeVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;
  2861. }
  2862. RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;
  2863. //
  2864. // Check if the free area is below a threshold.
  2865. //
  2866. if (((RemainingCommonRuntimeVariableSpace < mVariableModuleGlobal->MaxVariableSize) ||
  2867. (RemainingCommonRuntimeVariableSpace < mVariableModuleGlobal->MaxAuthVariableSize)) ||
  2868. ((PcdGet32 (PcdHwErrStorageSize) != 0) &&
  2869. (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize))))
  2870. {
  2871. Status = Reclaim (
  2872. mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
  2873. &mVariableModuleGlobal->NonVolatileLastVariableOffset,
  2874. FALSE,
  2875. NULL,
  2876. NULL,
  2877. 0
  2878. );
  2879. ASSERT_EFI_ERROR (Status);
  2880. }
  2881. }
  2882. /**
  2883. Get maximum variable size, covering both non-volatile and volatile variables.
  2884. @return Maximum variable size.
  2885. **/
  2886. UINTN
  2887. GetMaxVariableSize (
  2888. VOID
  2889. )
  2890. {
  2891. UINTN MaxVariableSize;
  2892. MaxVariableSize = GetNonVolatileMaxVariableSize ();
  2893. //
  2894. // The condition below fails implicitly if PcdMaxVolatileVariableSize equals
  2895. // the default zero value.
  2896. //
  2897. if (MaxVariableSize < PcdGet32 (PcdMaxVolatileVariableSize)) {
  2898. MaxVariableSize = PcdGet32 (PcdMaxVolatileVariableSize);
  2899. }
  2900. return MaxVariableSize;
  2901. }
  2902. /**
  2903. Flush the HOB variable to flash.
  2904. @param[in] VariableName Name of variable has been updated or deleted.
  2905. @param[in] VendorGuid Guid of variable has been updated or deleted.
  2906. **/
  2907. VOID
  2908. FlushHobVariableToFlash (
  2909. IN CHAR16 *VariableName,
  2910. IN EFI_GUID *VendorGuid
  2911. )
  2912. {
  2913. EFI_STATUS Status;
  2914. VARIABLE_STORE_HEADER *VariableStoreHeader;
  2915. VARIABLE_HEADER *Variable;
  2916. VOID *VariableData;
  2917. VARIABLE_POINTER_TRACK VariablePtrTrack;
  2918. BOOLEAN ErrorFlag;
  2919. BOOLEAN AuthFormat;
  2920. ErrorFlag = FALSE;
  2921. AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
  2922. //
  2923. // Flush the HOB variable to flash.
  2924. //
  2925. if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
  2926. VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)mVariableModuleGlobal->VariableGlobal.HobVariableBase;
  2927. //
  2928. // Set HobVariableBase to 0, it can avoid SetVariable to call back.
  2929. //
  2930. mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
  2931. for ( Variable = GetStartPointer (VariableStoreHeader)
  2932. ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))
  2933. ; Variable = GetNextVariablePtr (Variable, AuthFormat)
  2934. )
  2935. {
  2936. if (Variable->State != VAR_ADDED) {
  2937. //
  2938. // The HOB variable has been set to DELETED state in local.
  2939. //
  2940. continue;
  2941. }
  2942. ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
  2943. if ((VendorGuid == NULL) || (VariableName == NULL) ||
  2944. !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable, AuthFormat)) ||
  2945. (StrCmp (VariableName, GetVariableNamePtr (Variable, AuthFormat)) != 0))
  2946. {
  2947. VariableData = GetVariableDataPtr (Variable, AuthFormat);
  2948. FindVariable (
  2949. GetVariableNamePtr (Variable, AuthFormat),
  2950. GetVendorGuidPtr (Variable, AuthFormat),
  2951. &VariablePtrTrack,
  2952. &mVariableModuleGlobal->VariableGlobal,
  2953. FALSE
  2954. );
  2955. Status = UpdateVariable (
  2956. GetVariableNamePtr (Variable, AuthFormat),
  2957. GetVendorGuidPtr (Variable, AuthFormat),
  2958. VariableData,
  2959. DataSizeOfVariable (Variable, AuthFormat),
  2960. Variable->Attributes,
  2961. 0,
  2962. 0,
  2963. &VariablePtrTrack,
  2964. NULL
  2965. );
  2966. DEBUG ((
  2967. DEBUG_INFO,
  2968. "Variable driver flush the HOB variable to flash: %g %s %r\n",
  2969. GetVendorGuidPtr (Variable, AuthFormat),
  2970. GetVariableNamePtr (Variable, AuthFormat),
  2971. Status
  2972. ));
  2973. } else {
  2974. //
  2975. // The updated or deleted variable is matched with this HOB variable.
  2976. // Don't break here because we will try to set other HOB variables
  2977. // since this variable could be set successfully.
  2978. //
  2979. Status = EFI_SUCCESS;
  2980. }
  2981. if (!EFI_ERROR (Status)) {
  2982. //
  2983. // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
  2984. // set the HOB variable to DELETED state in local.
  2985. //
  2986. DEBUG ((
  2987. DEBUG_INFO,
  2988. "Variable driver set the HOB variable to DELETED state in local: %g %s\n",
  2989. GetVendorGuidPtr (Variable, AuthFormat),
  2990. GetVariableNamePtr (Variable, AuthFormat)
  2991. ));
  2992. Variable->State &= VAR_DELETED;
  2993. } else {
  2994. ErrorFlag = TRUE;
  2995. }
  2996. }
  2997. if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Store != NULL) {
  2998. Status = SynchronizeRuntimeVariableCache (
  2999. &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache,
  3000. 0,
  3001. mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Store->Size
  3002. );
  3003. ASSERT_EFI_ERROR (Status);
  3004. }
  3005. if (ErrorFlag) {
  3006. //
  3007. // We still have HOB variable(s) not flushed in flash.
  3008. //
  3009. mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)VariableStoreHeader;
  3010. } else {
  3011. //
  3012. // All HOB variables have been flushed in flash.
  3013. //
  3014. DEBUG ((DEBUG_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
  3015. if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete != NULL) {
  3016. *(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete) = TRUE;
  3017. }
  3018. if (!AtRuntime ()) {
  3019. FreePool ((VOID *)VariableStoreHeader);
  3020. }
  3021. }
  3022. }
  3023. }
  3024. /**
  3025. Initializes variable write service.
  3026. @retval EFI_SUCCESS Function successfully executed.
  3027. @retval Others Fail to initialize the variable service.
  3028. **/
  3029. EFI_STATUS
  3030. VariableWriteServiceInitialize (
  3031. VOID
  3032. )
  3033. {
  3034. EFI_STATUS Status;
  3035. UINTN Index;
  3036. UINT8 Data;
  3037. VARIABLE_ENTRY_PROPERTY *VariableEntry;
  3038. AcquireLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  3039. //
  3040. // Check if the free area is really free.
  3041. //
  3042. for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < mNvVariableCache->Size; Index++) {
  3043. Data = ((UINT8 *)mNvVariableCache)[Index];
  3044. if (Data != 0xff) {
  3045. //
  3046. // There must be something wrong in variable store, do reclaim operation.
  3047. //
  3048. Status = Reclaim (
  3049. mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
  3050. &mVariableModuleGlobal->NonVolatileLastVariableOffset,
  3051. FALSE,
  3052. NULL,
  3053. NULL,
  3054. 0
  3055. );
  3056. if (EFI_ERROR (Status)) {
  3057. ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  3058. return Status;
  3059. }
  3060. break;
  3061. }
  3062. }
  3063. FlushHobVariableToFlash (NULL, NULL);
  3064. Status = EFI_SUCCESS;
  3065. ZeroMem (&mAuthContextOut, sizeof (mAuthContextOut));
  3066. if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
  3067. //
  3068. // Authenticated variable initialize.
  3069. //
  3070. mAuthContextIn.StructSize = sizeof (AUTH_VAR_LIB_CONTEXT_IN);
  3071. mAuthContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize -
  3072. GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
  3073. Status = AuthVariableLibInitialize (&mAuthContextIn, &mAuthContextOut);
  3074. if (!EFI_ERROR (Status)) {
  3075. DEBUG ((DEBUG_INFO, "Variable driver will work with auth variable support!\n"));
  3076. mVariableModuleGlobal->VariableGlobal.AuthSupport = TRUE;
  3077. if (mAuthContextOut.AuthVarEntry != NULL) {
  3078. for (Index = 0; Index < mAuthContextOut.AuthVarEntryCount; Index++) {
  3079. VariableEntry = &mAuthContextOut.AuthVarEntry[Index];
  3080. Status = VarCheckLibVariablePropertySet (
  3081. VariableEntry->Name,
  3082. VariableEntry->Guid,
  3083. &VariableEntry->VariableProperty
  3084. );
  3085. ASSERT_EFI_ERROR (Status);
  3086. }
  3087. }
  3088. } else if (Status == EFI_UNSUPPORTED) {
  3089. DEBUG ((DEBUG_INFO, "NOTICE - AuthVariableLibInitialize() returns %r!\n", Status));
  3090. DEBUG ((DEBUG_INFO, "Variable driver will continue to work without auth variable support!\n"));
  3091. mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;
  3092. Status = EFI_SUCCESS;
  3093. }
  3094. }
  3095. if (!EFI_ERROR (Status)) {
  3096. for (Index = 0; Index < ARRAY_SIZE (mVariableEntryProperty); Index++) {
  3097. VariableEntry = &mVariableEntryProperty[Index];
  3098. Status = VarCheckLibVariablePropertySet (VariableEntry->Name, VariableEntry->Guid, &VariableEntry->VariableProperty);
  3099. ASSERT_EFI_ERROR (Status);
  3100. }
  3101. }
  3102. ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
  3103. //
  3104. // Initialize MOR Lock variable.
  3105. //
  3106. MorLockInit ();
  3107. return Status;
  3108. }
  3109. /**
  3110. Convert normal variable storage to the allocated auth variable storage.
  3111. @param[in] NormalVarStorage Pointer to the normal variable storage header
  3112. @retval the allocated auth variable storage
  3113. **/
  3114. VOID *
  3115. ConvertNormalVarStorageToAuthVarStorage (
  3116. VARIABLE_STORE_HEADER *NormalVarStorage
  3117. )
  3118. {
  3119. VARIABLE_HEADER *StartPtr;
  3120. UINT8 *NextPtr;
  3121. VARIABLE_HEADER *EndPtr;
  3122. UINTN AuthVarStroageSize;
  3123. AUTHENTICATED_VARIABLE_HEADER *AuthStartPtr;
  3124. VARIABLE_STORE_HEADER *AuthVarStorage;
  3125. AuthVarStroageSize = sizeof (VARIABLE_STORE_HEADER);
  3126. //
  3127. // Set AuthFormat as FALSE for normal variable storage
  3128. //
  3129. mVariableModuleGlobal->VariableGlobal.AuthFormat = FALSE;
  3130. //
  3131. // Calculate Auth Variable Storage Size
  3132. //
  3133. StartPtr = GetStartPointer (NormalVarStorage);
  3134. EndPtr = GetEndPointer (NormalVarStorage);
  3135. while (StartPtr < EndPtr) {
  3136. if (StartPtr->State == VAR_ADDED) {
  3137. AuthVarStroageSize = HEADER_ALIGN (AuthVarStroageSize);
  3138. AuthVarStroageSize += sizeof (AUTHENTICATED_VARIABLE_HEADER);
  3139. AuthVarStroageSize += StartPtr->NameSize + GET_PAD_SIZE (StartPtr->NameSize);
  3140. AuthVarStroageSize += StartPtr->DataSize + GET_PAD_SIZE (StartPtr->DataSize);
  3141. }
  3142. StartPtr = GetNextVariablePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  3143. }
  3144. //
  3145. // Allocate Runtime memory for Auth Variable Storage
  3146. //
  3147. AuthVarStorage = AllocateRuntimeZeroPool (AuthVarStroageSize);
  3148. ASSERT (AuthVarStorage != NULL);
  3149. if (AuthVarStorage == NULL) {
  3150. return NULL;
  3151. }
  3152. //
  3153. // Copy Variable from Normal storage to Auth storage
  3154. //
  3155. StartPtr = GetStartPointer (NormalVarStorage);
  3156. EndPtr = GetEndPointer (NormalVarStorage);
  3157. AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *)GetStartPointer (AuthVarStorage);
  3158. while (StartPtr < EndPtr) {
  3159. if (StartPtr->State == VAR_ADDED) {
  3160. AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (AuthStartPtr);
  3161. //
  3162. // Copy Variable Header
  3163. //
  3164. AuthStartPtr->StartId = StartPtr->StartId;
  3165. AuthStartPtr->State = StartPtr->State;
  3166. AuthStartPtr->Attributes = StartPtr->Attributes;
  3167. AuthStartPtr->NameSize = StartPtr->NameSize;
  3168. AuthStartPtr->DataSize = StartPtr->DataSize;
  3169. CopyGuid (&AuthStartPtr->VendorGuid, &StartPtr->VendorGuid);
  3170. //
  3171. // Copy Variable Name
  3172. //
  3173. NextPtr = (UINT8 *)(AuthStartPtr + 1);
  3174. CopyMem (
  3175. NextPtr,
  3176. GetVariableNamePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat),
  3177. AuthStartPtr->NameSize
  3178. );
  3179. //
  3180. // Copy Variable Data
  3181. //
  3182. NextPtr = NextPtr + AuthStartPtr->NameSize + GET_PAD_SIZE (AuthStartPtr->NameSize);
  3183. CopyMem (NextPtr, GetVariableDataPtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), AuthStartPtr->DataSize);
  3184. //
  3185. // Go to next variable
  3186. //
  3187. AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *)(NextPtr + AuthStartPtr->DataSize + GET_PAD_SIZE (AuthStartPtr->DataSize));
  3188. }
  3189. StartPtr = GetNextVariablePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
  3190. }
  3191. //
  3192. // Update Auth Storage Header
  3193. //
  3194. AuthVarStorage->Format = NormalVarStorage->Format;
  3195. AuthVarStorage->State = NormalVarStorage->State;
  3196. AuthVarStorage->Size = (UINT32)((UINTN)AuthStartPtr - (UINTN)AuthVarStorage);
  3197. CopyGuid (&AuthVarStorage->Signature, &gEfiAuthenticatedVariableGuid);
  3198. ASSERT (AuthVarStorage->Size <= AuthVarStroageSize);
  3199. //
  3200. // Restore AuthFormat
  3201. //
  3202. mVariableModuleGlobal->VariableGlobal.AuthFormat = TRUE;
  3203. return AuthVarStorage;
  3204. }
  3205. /**
  3206. Get HOB variable store.
  3207. @param[in] VariableGuid NV variable store signature.
  3208. @retval EFI_SUCCESS Function successfully executed.
  3209. @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
  3210. **/
  3211. EFI_STATUS
  3212. GetHobVariableStore (
  3213. IN EFI_GUID *VariableGuid
  3214. )
  3215. {
  3216. VARIABLE_STORE_HEADER *VariableStoreHeader;
  3217. UINT64 VariableStoreLength;
  3218. EFI_HOB_GUID_TYPE *GuidHob;
  3219. BOOLEAN NeedConvertNormalToAuth;
  3220. //
  3221. // Make sure there is no more than one Variable HOB.
  3222. //
  3223. DEBUG_CODE_BEGIN ();
  3224. GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);
  3225. if (GuidHob != NULL) {
  3226. if ((GetNextGuidHob (&gEfiAuthenticatedVariableGuid, GET_NEXT_HOB (GuidHob)) != NULL)) {
  3227. DEBUG ((DEBUG_ERROR, "ERROR: Found two Auth Variable HOBs\n"));
  3228. ASSERT (FALSE);
  3229. } else if (GetFirstGuidHob (&gEfiVariableGuid) != NULL) {
  3230. DEBUG ((DEBUG_ERROR, "ERROR: Found one Auth + one Normal Variable HOBs\n"));
  3231. ASSERT (FALSE);
  3232. }
  3233. } else {
  3234. GuidHob = GetFirstGuidHob (&gEfiVariableGuid);
  3235. if (GuidHob != NULL) {
  3236. if ((GetNextGuidHob (&gEfiVariableGuid, GET_NEXT_HOB (GuidHob)) != NULL)) {
  3237. DEBUG ((DEBUG_ERROR, "ERROR: Found two Normal Variable HOBs\n"));
  3238. ASSERT (FALSE);
  3239. }
  3240. }
  3241. }
  3242. DEBUG_CODE_END ();
  3243. //
  3244. // Combinations supported:
  3245. // 1. Normal NV variable store +
  3246. // Normal HOB variable store
  3247. // 2. Auth NV variable store +
  3248. // Auth HOB variable store
  3249. // 3. Auth NV variable store +
  3250. // Normal HOB variable store (code will convert it to Auth Format)
  3251. //
  3252. NeedConvertNormalToAuth = FALSE;
  3253. GuidHob = GetFirstGuidHob (VariableGuid);
  3254. if ((GuidHob == NULL) && (VariableGuid == &gEfiAuthenticatedVariableGuid)) {
  3255. //
  3256. // Try getting it from normal variable HOB
  3257. //
  3258. GuidHob = GetFirstGuidHob (&gEfiVariableGuid);
  3259. NeedConvertNormalToAuth = TRUE;
  3260. }
  3261. if (GuidHob != NULL) {
  3262. VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);
  3263. VariableStoreLength = GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE);
  3264. if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {
  3265. if (!NeedConvertNormalToAuth) {
  3266. mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)AllocateRuntimeCopyPool ((UINTN)VariableStoreLength, (VOID *)VariableStoreHeader);
  3267. } else {
  3268. mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)ConvertNormalVarStorageToAuthVarStorage ((VOID *)VariableStoreHeader);
  3269. }
  3270. if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {
  3271. return EFI_OUT_OF_RESOURCES;
  3272. }
  3273. } else {
  3274. DEBUG ((DEBUG_ERROR, "HOB Variable Store header is corrupted!\n"));
  3275. }
  3276. }
  3277. return EFI_SUCCESS;
  3278. }
  3279. /**
  3280. Initializes variable store area for non-volatile and volatile variable.
  3281. @retval EFI_SUCCESS Function successfully executed.
  3282. @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource.
  3283. **/
  3284. EFI_STATUS
  3285. VariableCommonInitialize (
  3286. VOID
  3287. )
  3288. {
  3289. EFI_STATUS Status;
  3290. VARIABLE_STORE_HEADER *VolatileVariableStore;
  3291. UINTN ScratchSize;
  3292. EFI_GUID *VariableGuid;
  3293. //
  3294. // Allocate runtime memory for variable driver global structure.
  3295. //
  3296. mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));
  3297. if (mVariableModuleGlobal == NULL) {
  3298. return EFI_OUT_OF_RESOURCES;
  3299. }
  3300. InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);
  3301. //
  3302. // Init non-volatile variable store.
  3303. //
  3304. Status = InitNonVolatileVariableStore ();
  3305. if (EFI_ERROR (Status)) {
  3306. FreePool (mVariableModuleGlobal);
  3307. return Status;
  3308. }
  3309. //
  3310. // mVariableModuleGlobal->VariableGlobal.AuthFormat
  3311. // has been initialized in InitNonVolatileVariableStore().
  3312. //
  3313. if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
  3314. DEBUG ((DEBUG_INFO, "Variable driver will work with auth variable format!\n"));
  3315. //
  3316. // Set AuthSupport to FALSE first, VariableWriteServiceInitialize() will initialize it.
  3317. //
  3318. mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;
  3319. VariableGuid = &gEfiAuthenticatedVariableGuid;
  3320. } else {
  3321. DEBUG ((DEBUG_INFO, "Variable driver will work without auth variable support!\n"));
  3322. mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;
  3323. VariableGuid = &gEfiVariableGuid;
  3324. }
  3325. //
  3326. // Get HOB variable store.
  3327. //
  3328. Status = GetHobVariableStore (VariableGuid);
  3329. if (EFI_ERROR (Status)) {
  3330. if (mNvFvHeaderCache != NULL) {
  3331. FreePool (mNvFvHeaderCache);
  3332. }
  3333. FreePool (mVariableModuleGlobal);
  3334. return Status;
  3335. }
  3336. mVariableModuleGlobal->MaxVolatileVariableSize = ((PcdGet32 (PcdMaxVolatileVariableSize) != 0) ?
  3337. PcdGet32 (PcdMaxVolatileVariableSize) :
  3338. mVariableModuleGlobal->MaxVariableSize
  3339. );
  3340. //
  3341. // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.
  3342. //
  3343. ScratchSize = GetMaxVariableSize ();
  3344. mVariableModuleGlobal->ScratchBufferSize = ScratchSize;
  3345. VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);
  3346. if (VolatileVariableStore == NULL) {
  3347. if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {
  3348. FreePool ((VOID *)(UINTN)mVariableModuleGlobal->VariableGlobal.HobVariableBase);
  3349. }
  3350. if (mNvFvHeaderCache != NULL) {
  3351. FreePool (mNvFvHeaderCache);
  3352. }
  3353. FreePool (mVariableModuleGlobal);
  3354. return EFI_OUT_OF_RESOURCES;
  3355. }
  3356. SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);
  3357. //
  3358. // Initialize Variable Specific Data.
  3359. //
  3360. mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)VolatileVariableStore;
  3361. mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN)GetStartPointer (VolatileVariableStore) - (UINTN)VolatileVariableStore;
  3362. CopyGuid (&VolatileVariableStore->Signature, VariableGuid);
  3363. VolatileVariableStore->Size = PcdGet32 (PcdVariableStoreSize);
  3364. VolatileVariableStore->Format = VARIABLE_STORE_FORMATTED;
  3365. VolatileVariableStore->State = VARIABLE_STORE_HEALTHY;
  3366. VolatileVariableStore->Reserved = 0;
  3367. VolatileVariableStore->Reserved1 = 0;
  3368. return EFI_SUCCESS;
  3369. }
  3370. /**
  3371. Get the proper fvb handle and/or fvb protocol by the given Flash address.
  3372. @param[in] Address The Flash address.
  3373. @param[out] FvbHandle In output, if it is not NULL, it points to the proper FVB handle.
  3374. @param[out] FvbProtocol In output, if it is not NULL, it points to the proper FVB protocol.
  3375. **/
  3376. EFI_STATUS
  3377. GetFvbInfoByAddress (
  3378. IN EFI_PHYSICAL_ADDRESS Address,
  3379. OUT EFI_HANDLE *FvbHandle OPTIONAL,
  3380. OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL **FvbProtocol OPTIONAL
  3381. )
  3382. {
  3383. EFI_STATUS Status;
  3384. EFI_HANDLE *HandleBuffer;
  3385. UINTN HandleCount;
  3386. UINTN Index;
  3387. EFI_PHYSICAL_ADDRESS FvbBaseAddress;
  3388. EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
  3389. EFI_FVB_ATTRIBUTES_2 Attributes;
  3390. UINTN BlockSize;
  3391. UINTN NumberOfBlocks;
  3392. HandleBuffer = NULL;
  3393. //
  3394. // Get all FVB handles.
  3395. //
  3396. Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);
  3397. if (EFI_ERROR (Status)) {
  3398. return EFI_NOT_FOUND;
  3399. }
  3400. //
  3401. // Get the FVB to access variable store.
  3402. //
  3403. Fvb = NULL;
  3404. for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {
  3405. Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);
  3406. if (EFI_ERROR (Status)) {
  3407. Status = EFI_NOT_FOUND;
  3408. break;
  3409. }
  3410. //
  3411. // Ensure this FVB protocol supported Write operation.
  3412. //
  3413. Status = Fvb->GetAttributes (Fvb, &Attributes);
  3414. if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
  3415. continue;
  3416. }
  3417. //
  3418. // Compare the address and select the right one.
  3419. //
  3420. Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);
  3421. if (EFI_ERROR (Status)) {
  3422. continue;
  3423. }
  3424. //
  3425. // Assume one FVB has one type of BlockSize.
  3426. //
  3427. Status = Fvb->GetBlockSize (Fvb, 0, &BlockSize, &NumberOfBlocks);
  3428. if (EFI_ERROR (Status)) {
  3429. continue;
  3430. }
  3431. if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + BlockSize * NumberOfBlocks))) {
  3432. if (FvbHandle != NULL) {
  3433. *FvbHandle = HandleBuffer[Index];
  3434. }
  3435. if (FvbProtocol != NULL) {
  3436. *FvbProtocol = Fvb;
  3437. }
  3438. Status = EFI_SUCCESS;
  3439. break;
  3440. }
  3441. }
  3442. FreePool (HandleBuffer);
  3443. if (Fvb == NULL) {
  3444. Status = EFI_NOT_FOUND;
  3445. }
  3446. return Status;
  3447. }