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