alignedmem.c 1.7 KB

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