+ // meaning in addition to the requested size for the aligned mem,\r
+ // we simply reserve an overhead memory equal to Alignmemt(page-aligned), no matter what.\r
+ // The overhead mem size could be reduced later with more involved malloc mechanisms\r
+ // (e.g., somthing that can detect the alignment boundary before allocating memory or \r
+ // can request that memory be allocated at a certain address that is aleady aligned).\r
+ //\r
+ TotalPages = Pages + (Alignment <= EFI_PAGE_SIZE ? 0 : EFI_SIZE_TO_PAGES(Alignment));\r
+ Memory = (EFI_PHYSICAL_ADDRESS) (UINTN) InternalAllocatePages (MemoryType, TotalPages);\r
+ if (Memory == 0) {\r
+ DEBUG((DEBUG_INFO, "Out of memory resource! \n"));\r
+ return NULL;\r
+ }\r
+ DEBUG ((DEBUG_INFO, "Allocated Memory unaligned: Address = 0x%LX, Pages = 0x%X, Type = %d \n", Memory, TotalPages, (UINTN) MemoryType));\r
+\r
+ //\r
+ // Alignment calculation\r
+ //\r
+ AlignedMemory = Memory;\r
+ if (Alignment > EFI_PAGE_SIZE) {\r
+ AlignedMemory = ALIGN_VALUE (Memory, Alignment);\r
+ }\r
+ DEBUG ((DEBUG_INFO, "After aligning to 0x%X bytes: Address = 0x%LX, Pages = 0x%X \n", Alignment, AlignedMemory, Pages));\r
+\r
+ //\r
+ // In general three HOBs cover the total allocated space.\r
+ // The aligned portion is covered by the aligned mem HOB and\r
+ // the unaligned(to be freed) portions before and after the aligned portion are covered by newly created HOBs.\r
+ //\r
+ // Before mem HOB covers the region between "Memory" and "AlignedMemory"\r
+ // Aligned mem HOB covers the region between "AlignedMemory" and "AlignedMemory + EFI_PAGES_TO_SIZE(Pages)"\r
+ // After mem HOB covers the region between "AlignedMemory + EFI_PAGES_TO_SIZE(Pages)" and "Memory + EFI_PAGES_TO_SIZE(TotalPages)"\r
+ //\r
+ // The before or after mem HOBs need to be skipped under special cases where the aligned portion\r
+ // touches either the top or bottom of the original allocated space.\r
+ //\r
+ SkipBeforeMemHob = FALSE;\r
+ SkipAfterMemHob = FALSE;\r
+ if (Memory == AlignedMemory) {\r
+ SkipBeforeMemHob = TRUE;\r
+ }\r
+ if ((Memory + EFI_PAGES_TO_SIZE(TotalPages)) == (AlignedMemory + EFI_PAGES_TO_SIZE(Pages))) {\r
+ //\r
+ // This condition is never met in the current implementation.\r
+ // There is always some after-mem since the overhead mem(used in TotalPages)\r
+ // is no less than Alignment.\r
+ //\r
+ SkipAfterMemHob = TRUE;\r
+ }\r
+\r
+ // \r
+ // Search for the mem HOB referring to the original(unaligned) allocation \r
+ // and update the size and type if needed.\r