1
2
3
4
5
6#include <linux/efi.h>
7#include <linux/log2.h>
8#include <asm/efi.h>
9
10#include "efistub.h"
11
12
13
14
15
16
17static unsigned long get_entry_num_slots(efi_memory_desc_t *md,
18 unsigned long size,
19 unsigned long align_shift)
20{
21 unsigned long align = 1UL << align_shift;
22 u64 first_slot, last_slot, region_end;
23
24 if (md->type != EFI_CONVENTIONAL_MEMORY)
25 return 0;
26
27 if (efi_soft_reserve_enabled() &&
28 (md->attribute & EFI_MEMORY_SP))
29 return 0;
30
31 region_end = min(md->phys_addr + md->num_pages * EFI_PAGE_SIZE - 1,
32 (u64)ULONG_MAX);
33 if (region_end < size)
34 return 0;
35
36 first_slot = round_up(md->phys_addr, align);
37 last_slot = round_down(region_end - size + 1, align);
38
39 if (first_slot > last_slot)
40 return 0;
41
42 return ((unsigned long)(last_slot - first_slot) >> align_shift) + 1;
43}
44
45
46
47
48
49
50
51#define MD_NUM_SLOTS(md) ((md)->virt_addr)
52
53efi_status_t efi_random_alloc(unsigned long size,
54 unsigned long align,
55 unsigned long *addr,
56 unsigned long random_seed)
57{
58 unsigned long map_size, desc_size, total_slots = 0, target_slot;
59 unsigned long buff_size;
60 efi_status_t status;
61 efi_memory_desc_t *memory_map;
62 int map_offset;
63 struct efi_boot_memmap map;
64
65 map.map = &memory_map;
66 map.map_size = &map_size;
67 map.desc_size = &desc_size;
68 map.desc_ver = NULL;
69 map.key_ptr = NULL;
70 map.buff_size = &buff_size;
71
72 status = efi_get_memory_map(&map);
73 if (status != EFI_SUCCESS)
74 return status;
75
76 if (align < EFI_ALLOC_ALIGN)
77 align = EFI_ALLOC_ALIGN;
78
79 size = round_up(size, EFI_ALLOC_ALIGN);
80
81
82 for (map_offset = 0; map_offset < map_size; map_offset += desc_size) {
83 efi_memory_desc_t *md = (void *)memory_map + map_offset;
84 unsigned long slots;
85
86 slots = get_entry_num_slots(md, size, ilog2(align));
87 MD_NUM_SLOTS(md) = slots;
88 total_slots += slots;
89 }
90
91
92 target_slot = (total_slots * (u64)(random_seed & U32_MAX)) >> 32;
93
94
95
96
97
98
99
100
101
102
103
104
105 for (map_offset = 0; map_offset < map_size; map_offset += desc_size) {
106 efi_memory_desc_t *md = (void *)memory_map + map_offset;
107 efi_physical_addr_t target;
108 unsigned long pages;
109
110 if (target_slot >= MD_NUM_SLOTS(md)) {
111 target_slot -= MD_NUM_SLOTS(md);
112 continue;
113 }
114
115 target = round_up(md->phys_addr, align) + target_slot * align;
116 pages = size / EFI_PAGE_SIZE;
117
118 status = efi_bs_call(allocate_pages, EFI_ALLOCATE_ADDRESS,
119 EFI_LOADER_DATA, pages, &target);
120 if (status == EFI_SUCCESS)
121 *addr = target;
122 break;
123 }
124
125 efi_bs_call(free_pool, memory_map);
126
127 return status;
128}
129