+/**\r
+ Allocates one or more 4KB pages of a certain memory type at a specified\r
+ alignment.\r
+\r
+ Allocates the number of 4KB pages specified by Pages of a certain memory type\r
+ with an alignment specified by Alignment. The allocated buffer is returned.\r
+ If Pages is 0, then NULL is returned. If there is not enough memory at the\r
+ specified alignment remaining to satisfy the request, then NULL is returned.\r
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().\r
+ If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT().\r
+\r
+ @param MemoryType The type of memory to allocate.\r
+ @param Pages The number of 4 KB pages to allocate.\r
+ @param Alignment The requested alignment of the allocation.\r
+ Must be a power of two.\r
+ If Alignment is zero, then byte alignment is\r
+ used.\r
+\r
+ @return A pointer to the allocated buffer or NULL if allocation fails.\r
+\r
+**/\r
+STATIC\r
+VOID *\r
+InternalAllocateAlignedPages (\r
+ IN EFI_MEMORY_TYPE MemoryType,\r
+ IN UINTN Pages,\r
+ IN UINTN Alignment\r
+ )\r
+{\r
+ EFI_STATUS Status;\r
+ EFI_PHYSICAL_ADDRESS Memory;\r
+ UINTN AlignedMemory;\r
+ UINTN AlignmentMask;\r
+ UINTN UnalignedPages;\r
+ UINTN RealPages;\r
+\r
+ //\r
+ // Alignment must be a power of two or zero.\r
+ //\r
+ ASSERT ((Alignment & (Alignment - 1)) == 0);\r
+\r
+ if (Pages == 0) {\r
+ return NULL;\r
+ }\r
+ if (Alignment > EFI_PAGE_SIZE) {\r
+ //\r
+ // Calculate the total number of pages since alignment is larger than page\r
+ // size.\r
+ //\r
+ AlignmentMask = Alignment - 1;\r
+ RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment);\r
+ //\r
+ // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not\r
+ // overflow.\r
+ //\r
+ ASSERT (RealPages > Pages);\r
+\r
+ Memory = mDmaHostAddressLimit;\r
+ Status = gBS->AllocatePages (AllocateMaxAddress, MemoryType, RealPages,\r
+ &Memory);\r
+ if (EFI_ERROR (Status)) {\r
+ return NULL;\r
+ }\r
+ AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask;\r
+ UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory);\r
+ if (UnalignedPages > 0) {\r
+ //\r
+ // Free first unaligned page(s).\r
+ //\r
+ Status = gBS->FreePages (Memory, UnalignedPages);\r
+ ASSERT_EFI_ERROR (Status);\r
+ }\r
+ Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages);\r
+ UnalignedPages = RealPages - Pages - UnalignedPages;\r
+ if (UnalignedPages > 0) {\r
+ //\r
+ // Free last unaligned page(s).\r
+ //\r
+ Status = gBS->FreePages (Memory, UnalignedPages);\r
+ ASSERT_EFI_ERROR (Status);\r
+ }\r
+ } else {\r
+ //\r
+ // Do not over-allocate pages in this case.\r
+ //\r
+ Memory = mDmaHostAddressLimit;\r
+ Status = gBS->AllocatePages (AllocateMaxAddress, MemoryType, Pages,\r
+ &Memory);\r
+ if (EFI_ERROR (Status)) {\r
+ return NULL;\r
+ }\r
+ AlignedMemory = (UINTN)Memory;\r
+ }\r
+ return (VOID *)AlignedMemory;\r
+}\r
+\r