xref: /kvm-unit-tests/lib/alloc_page.h (revision 322cdd6405250a2a3e48db199f97a45ef519e226)
1 /*
2  * This work is licensed under the terms of the GNU LGPL, version 2.
3  *
4  * This is a simple allocator that provides contiguous physical addresses
5  * with byte granularity.
6  */
7 
8 #ifndef ALLOC_PAGE_H
9 #define ALLOC_PAGE_H 1
10 
11 #include <asm/memory_areas.h>
12 
13 #define AREA_ANY -1
14 #define AREA_ANY_NUMBER 0xff
15 
16 /* Returns true if the page allocator has been initialized */
17 bool page_alloc_initialized(void);
18 
19 /*
20  * Initializes a memory area.
21  * n is the number of the area to initialize
22  * base_pfn is the physical frame number of the start of the area to initialize
23  * top_pfn is the physical frame number of the first page immediately after
24  * the end of the area to initialize
25  */
26 void page_alloc_init_area(u8 n, uintptr_t base_pfn, uintptr_t top_pfn);
27 
28 /* Enables the page allocator. At least one area must have been initialized */
29 void page_alloc_ops_enable(void);
30 
31 /*
32  * Allocate aligned memory from the specified areas.
33  * areas is a bitmap of allowed areas
34  * alignment must be a power of 2
35  */
36 void *memalign_pages_area(unsigned int areas, size_t alignment, size_t size);
37 
38 /*
39  * Allocate aligned memory from any area.
40  * Equivalent to memalign_pages_area(~0, alignment, size).
41  */
42 void *memalign_pages(size_t alignment, size_t size);
43 
44 /*
45  * Allocate naturally aligned memory from the specified areas.
46  * Equivalent to memalign_pages_area(areas, 1ull << order, 1ull << order).
47  */
48 void *alloc_pages_area(unsigned int areas, unsigned int order);
49 
50 /*
51  * Allocate one page from any area.
52  * Equivalent to alloc_pages(0);
53  */
54 void *alloc_page(void);
55 
56 /*
57  * Allocate naturally aligned memory from any area.
58  * Equivalent to alloc_pages_area(~0, order);
59  */
60 void *alloc_pages(unsigned int order);
61 
62 /*
63  * Frees a memory block allocated with any of the memalign_pages* or
64  * alloc_pages* functions.
65  * The pointer must point to the start of the block.
66  */
67 void free_pages(void *mem);
68 
69 /* For backwards compatibility */
70 static inline void free_page(void *mem)
71 {
72 	return free_pages(mem);
73 }
74 
75 /* For backwards compatibility */
76 static inline void free_pages_by_order(void *mem, unsigned int order)
77 {
78 	free_pages(mem);
79 }
80 
81 /*
82  * Allocates and reserves the specified memory range if possible.
83  * Returns NULL in case of failure.
84  */
85 void *alloc_pages_special(uintptr_t addr, size_t npages);
86 
87 /*
88  * Frees a reserved memory range that had been reserved with
89  * alloc_pages_special.
90  * The memory range does not need to match a previous allocation
91  * exactly, it can also be a subset, in which case only the specified
92  * pages will be freed and unreserved.
93  */
94 void free_pages_special(uintptr_t addr, size_t npages);
95 
96 #endif
97