xref: /DragonStub/apps/alignedmem.c (revision 823f04931913f01ee1fc0dc0c7876156ad150388)
1*823f0493SLoGin #include <dragonstub/dragonstub.h>
2*823f0493SLoGin #include <dragonstub/linux/align.h>
3*823f0493SLoGin #include <dragonstub/linux/math.h>
4*823f0493SLoGin 
5*823f0493SLoGin 
6*823f0493SLoGin /**
7*823f0493SLoGin  * efi_allocate_pages_aligned() - Allocate memory pages
8*823f0493SLoGin  * @size:	minimum number of bytes to allocate
9*823f0493SLoGin  * @addr:	On return the address of the first allocated page. The first
10*823f0493SLoGin  *		allocated page has alignment EFI_ALLOC_ALIGN which is an
11*823f0493SLoGin  *		architecture dependent multiple of the page size.
12*823f0493SLoGin  * @max:	the address that the last allocated memory page shall not
13*823f0493SLoGin  *		exceed
14*823f0493SLoGin  * @align:	minimum alignment of the base of the allocation
15*823f0493SLoGin  *
16*823f0493SLoGin  * Allocate pages as EFI_LOADER_DATA. The allocated pages are aligned according
17*823f0493SLoGin  * to @align, which should be >= EFI_ALLOC_ALIGN. The last allocated page will
18*823f0493SLoGin  * not exceed the address given by @max.
19*823f0493SLoGin  *
20*823f0493SLoGin  * Return:	status code
21*823f0493SLoGin  */
efi_allocate_pages_aligned(unsigned long size,unsigned long * addr,unsigned long max,unsigned long align,int memory_type)22*823f0493SLoGin efi_status_t efi_allocate_pages_aligned(unsigned long size, unsigned long *addr,
23*823f0493SLoGin 					unsigned long max, unsigned long align,
24*823f0493SLoGin 					int memory_type)
25*823f0493SLoGin {
26*823f0493SLoGin 	efi_physical_addr_t alloc_addr;
27*823f0493SLoGin 	efi_status_t status;
28*823f0493SLoGin 	int slack;
29*823f0493SLoGin 
30*823f0493SLoGin 	max = min(max, EFI_ALLOC_LIMIT);
31*823f0493SLoGin 
32*823f0493SLoGin 	if (align < EFI_ALLOC_ALIGN)
33*823f0493SLoGin 		align = EFI_ALLOC_ALIGN;
34*823f0493SLoGin 
35*823f0493SLoGin 	alloc_addr = ALIGN_DOWN(max + 1, align) - 1;
36*823f0493SLoGin 	size = round_up(size, EFI_ALLOC_ALIGN);
37*823f0493SLoGin 	slack = align / EFI_PAGE_SIZE - 1;
38*823f0493SLoGin 
39*823f0493SLoGin 	status = efi_bs_call(AllocatePages, EFI_ALLOCATE_MAX_ADDRESS,
40*823f0493SLoGin 			     memory_type, size / EFI_PAGE_SIZE + slack,
41*823f0493SLoGin 			     &alloc_addr);
42*823f0493SLoGin 	if (status != EFI_SUCCESS)
43*823f0493SLoGin 		return status;
44*823f0493SLoGin 
45*823f0493SLoGin 	*addr = ALIGN_UP((unsigned long)alloc_addr, align);
46*823f0493SLoGin 
47*823f0493SLoGin 	if (slack > 0) {
48*823f0493SLoGin 		int l = (alloc_addr & (align - 1)) / EFI_PAGE_SIZE;
49*823f0493SLoGin 
50*823f0493SLoGin 		if (l) {
51*823f0493SLoGin 			efi_bs_call(FreePages, alloc_addr, slack - l + 1);
52*823f0493SLoGin 			slack = l - 1;
53*823f0493SLoGin 		}
54*823f0493SLoGin 		if (slack)
55*823f0493SLoGin 			efi_bs_call(FreePages, *addr + size, slack);
56*823f0493SLoGin 	}
57*823f0493SLoGin 	return EFI_SUCCESS;
58*823f0493SLoGin }
59