Document mm
cover Document mm
Daniel K asked me to document some of the grub mm code as part of my work on grub mm arising from my work on secure boot. Hopefully this suffices.
I'd appreciate checks for technical correctness! I have found a number of mistakes during the writing process arising from my own misunderstandings, and it's likely there are others.
[I haven't been able to make much progress on the guts of the mm work so far due to busyness. I know I need to fix some issues around Stefan's TPM support work and address the review comments. But I thought if I get these docs out, some of them might be mergable as-is and if not I'll keep revising them and keep them at the start of any future series. And having the stuff worked out should make it easier to do work the substantive work in mm.]
PATCH 1/6 mm: document grub internal memory management structures
I spent more than a trivial quantity of time figuring out pre_size and whether a memory region's size contains the header cell or not.
Document the meanings of all the properties. Hopefully now no-one else has to figure it out!
---
This version: thanks to Glenn Washburn for catching various issues.
--- include/grub/mm_private.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+)
include/grub/mm_private.h +28 -0
@@ -21,15 +21,27 @@#include <grub/mm.h> +/* For context, see kern/mm.c */ +/* Magic words. */ #define GRUB_MM_FREE_MAGIC 0x2d3c2808#define GRUB_MM_ALLOC_MAGIC 0x6db08fa4 +/* A header describing a block of memory - either allocated or free */ typedef struct grub_mm_header { + /* + * The 'next' free block in this region's circular free list. + * Only meaningful if the block is free. + */ struct grub_mm_header *next; + /* The block size, not in bytes but the number of cells of + * GRUB_MM_ALIGN bytes. Includes the header cell. + */ grub_size_t size; + /* either free or alloc magic, depending on the block type. */ grub_size_t magic; + /* pad to cell size: see the top of kern/mm.c. */ #if GRUB_CPU_SIZEOF_VOID_P == 4 char padding[4]; #elif GRUB_CPU_SIZEOF_VOID_P == 8
@@ -48,11 +60,27 @@ typedef struct grub_mm_header#define GRUB_MM_ALIGN (1 << GRUB_MM_ALIGN_LOG2) +/* A region from which we can make allocations. */ typedef struct grub_mm_region { +/* The first free block in this region. */ struct grub_mm_header *first; + +/* +* The next region in the linked list of regions. Regions are initially +* sorted in order of increasing size, but can grow, in which case the +* ordering may not be preserved. +*/ struct grub_mm_region *next; + +/* +* A grub_mm_region will always be aligned to cell size. The pre-size is +* the number of bytes we were given but had to skip in order to get that +* alignment. +*/ grub_size_t pre_size; + +/* How many bytes are in this region? (free and allocated) */ grub_size_t size; } *grub_mm_region_t ;
Signature · 1 line
2.32.0
Re: [PATCH 1/6] mm: document grub internal memory management structures
Quoted 7 lines · Daniel Axtens
I spent more than a trivial quantity of time figuring out
pre_sizeand whether a memory region's size contains the header cell or not.Document the meanings of all the properties. Hopefully now no-one else has to figure it out!
Signed-off-by Daniel Axtens <[email protected]>
Daniel
PATCH 2/6 mm: clarify grub_real_malloc
In reply to Daniel AxtensWhen iterating through the singly linked list of free blocks, grub_real_malloc uses p and q for the current and previous blocks respectively. This isn't super clear, so swap to using prev and cur.
This makes another quirk more obvious. The comment at the top of grub_real_malloc might lead you to believe that the function will allocate from *first if there is space in that block.
It actually doesn't do that, and it can't do that with the current data structures. If we used up all of *first, we would need to change the ->next of the previous block to point to *first->next, but we can't do that because it's a singly linked list and we don't have access to *first's previous block.
What grub_real_malloc actually does is set *first to the initial previous block, and *first->next is the block we try to allocate from. That allows us to keep all the data structures consistent.
Document that.
--- grub-core/kern/mm.c | 76 ++++++++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 35 deletions(-)
grub-core/kern/mm.c +41 -35
@@ -178,13 +178,20 @@ grub_mm_init_region (void *addr, grub_size_t size) }/* Allocate the number of units N with the alignment ALIGN from the ring -buffer starting from *FIRST. ALIGN must be a power of two. Both N and -ALIGN are in units of GRUB_MM_ALIGN. Return a non-NULL if successful, -otherwise return NULL. */ +* buffer given in *FIRST. ALIGN must be a power of two. Both N and +* ALIGN are in units of GRUB_MM_ALIGN. Return a non-NULL if successful, +* otherwise return NULL. +* +* Note: because in certain circumstances we need to adjust the ->next +* pointer of the previous block, we iterate over the singly linked +* list with the pair (prev, cur). *FIRST is our initial previous, and +* *FIRST->next is our initial current pointer. So we will actually +* allocate from *FIRST->next first and *FIRST itself last. +*/ static void *grub_real_malloc (grub_mm_header_t *first,grub_size_t n,grub_size_t align) { -grub_mm_header_t p, q; +grub_mm_header_t cur, prev;/* When everything is allocated side effect is that *first will have alloc magic marked, meaning that there is no room in this region. */
@@ -192,24 +199,24 @@ grub_real_malloc (grub_mm_header_t *first, grub_size_t n, grub_size_t align)return 0 ;/* Try to search free slot for allocation in this memory region. */ -for (q = *first, p = q->next; ; q = p, p = p->next) +for (prev = *first, cur = prev->next; ; prev = cur, cur = cur->next) {grub_off_t extra; - extra = ((grub_addr_t) (p +1 ) >>GRUB_MM_ALIGN_LOG2 ) & (align -1 ); + extra = ((grub_addr_t) (cur +1 ) >>GRUB_MM_ALIGN_LOG2 ) & (align -1 );if (extra) extra = align - extra; -if (! p) +if (! cur)grub_fatal ("null in the ring" ); -if (p->magic !=GRUB_MM_FREE_MAGIC ) -grub_fatal ("free magic is broken at %p: 0x%x" , p, p->magic); +if (cur->magic !=GRUB_MM_FREE_MAGIC ) +grub_fatal ("free magic is broken at %p: 0x%x" , cur, cur->magic); -if (p->size >= n + extra) +if (cur->size >= n + extra) { - extra += (p->size - extra - n) & (~(align -1 )); -if (extra ==0 && p->size == n) + extra += (cur->size - extra - n) & (~(align -1 )); +if (extra ==0 && cur->size == n) {/* There is no special alignment requirement and memory block is complete match.
@@ -222,9 +229,9 @@ grub_real_malloc (grub_mm_header_t *first, grub_size_t n, grub_size_t align)| alloc, size=n | | +---------------+ v */ - q->next = p->next; + prev->next = cur->next; } -else if (align ==1 || p->size == n + extra) +else if (align ==1 || cur->size == n + extra) {/* There might be alignment requirement, when taking it into account memory block fits in.
@@ -241,23 +248,22 @@ grub_real_malloc (grub_mm_header_t *first, grub_size_t n, grub_size_t align)| alloc, size=n | | +---------------+ v */ - - p->size -= n; - p += p->size; + cur->size -= n; + cur += cur->size; }else if (extra ==0 ) {grub_mm_header_t r; - r = p + extra + n; + r = cur + extra + n; r->magic =GRUB_MM_FREE_MAGIC ; - r->size = p->size - extra - n; - r->next = p->next; - q->next = r; + r->size = cur->size - extra - n; + r->next = cur->next; + prev->next = r; -if (q == p) +if (prev == cur) { - q = r; + prev = r; r->next = r; } }
@@ -284,32 +290,32 @@ grub_real_malloc (grub_mm_header_t *first, grub_size_t n, grub_size_t align)*/ grub_mm_header_t r; - r = p + extra + n; + r = cur + extra + n; r->magic =GRUB_MM_FREE_MAGIC ; - r->size = p->size - extra - n; - r->next = p; + r->size = cur->size - extra - n; + r->next = cur; - p->size = extra; - q->next = r; - p += extra; + cur->size = extra; + prev->next = r; + cur += extra; } - p->magic =GRUB_MM_ALLOC_MAGIC ; - p->size = n; + cur->magic =GRUB_MM_ALLOC_MAGIC ; + cur->size = n;/* Mark find as a start marker for next allocation to fasten it. This will have side effect of fragmenting memory as small pieces before this will be un-used. */ /* So do it only for chunks under 64K. */ if (n < (0x8000 >>GRUB_MM_ALIGN_LOG2 ) - || *first == p) - *first = q; + || *first == cur) + *first = prev; -return p +1 ; +return cur +1 ; }/* Search was completed without result. */ -if (p == *first) +if (cur == *first)break ; }
Signature · 1 line
2.32.0
Re: [PATCH 2/6] mm: clarify grub_real_malloc
Quoted 14 lines · Daniel Axtens
When iterating through the singly linked list of free blocks,
grub_real_mallocuses p and q for the current and previous blocks respectively. This isn't super clear, so swap to using prev and cur.This makes another quirk more obvious. The comment at the top of
grub_real_mallocmight lead you to believe that the function will allocate from *first if there is space in that block.It actually doesn't do that, and it can't do that with the current data structures. If we used up all of *first, we would need to change the ->next of the previous block to point to
*first->next, but we can't do that because it's a singly linked list and we don't have access to *first's previous block.
Quoted 7 lines
What
grub_real_mallocactually does is set *first to the initial previous block, and*first->nextis the block we try to allocate from. That allows us to keep all the data structures consistent.Document that.
Signed-off-by Daniel Axtens <[email protected]>
Daniel
PATCH 3/6 mm: grub_real_malloc: make small allocs comment match code
In reply to Daniel AxtensSmall allocations move the region's *first pointer. The comment says that this happens for allocations under 64K. The code says it's for allocations under 32K. Commit 45bf8b3a7549 changed the code intentionally: make the comment match.
--- grub-core/kern/mm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
grub-core/kern/mm.c +1 -1
@@ -306,7 +306,7 @@ grub_real_malloc (grub_mm_header_t *first, grub_size_t n, grub_size_t align)/* Mark find as a start marker for next allocation to fasten it. This will have side effect of fragmenting memory as small pieces before this will be un-used. */ -/* So do it only for chunks under 64K. */ +/* So do it only for chunks under 32K. */ if (n < (0x8000 >>GRUB_MM_ALIGN_LOG2 ) || *first == cur) *first = prev;
Signature · 1 line
2.32.0
Re: [PATCH 3/6] mm: grub_real_malloc: make small allocs comment match code
Quoted 7 lines · Daniel Axtens
Small allocations move the region's *first pointer. The comment says that this happens for allocations under 64K. The code says it's for allocations under 32K. Commit
45bf8b3a7549changed the code intentionally: make the comment match.Fixes 45bf8b3a7549 (" * grub-core/kern/mm.c (grub_real_malloc): Decrease cut-off of moving the")Signed-off-by Daniel Axtens <[email protected]>
Daniel
PATCH 4/6 mm: document grub_free
In reply to Daniel Axtensgrub_free () posesses a surprising number of quirks, and also uses single-letter variable names confusingly to iterate through the free list.
Document what's going on.
Use prev and cur to iterate over the free list.
--- grub-core/kern/mm.c | 63 +++++++++++++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 22 deletions(-)
grub-core/kern/mm.c +41 -22
@@ -446,54 +446,73 @@ grub_free (void *ptr) }else { -grub_mm_header_t q, s; +grub_mm_header_t cur, prev;#if 0 - q = r->first; + cur = r->first;do {grub_printf ("%s:%d: q=%p, q->size=0x%x, q->magic=0x%x\n" , -GRUB_FILE , __LINE__, q, q->size, q->magic); - q = q->next; +GRUB_FILE , __LINE__, cur, cur->size, cur->magic); + cur = cur->next; } -while (q != r->first); +while (cur != r->first);#endif - -for (s = r->first, q = s->next; q <= p || q->next >= p; s = q, q = s->next) +/* Iterate over all blocks in the free ring. +* +* The free ring is arranged from high addresses to low +* addresses, modulo wraparound. +* +* We are looking for a block with a higher address than p or +* whose next address is lower than p. +*/ +for (prev = r->first, cur = prev->next; cur <= p || cur->next >= p; + prev = cur, cur = prev->next) { -if (q->magic !=GRUB_MM_FREE_MAGIC ) -grub_fatal ("free magic is broken at %p: 0x%x" , q, q->magic); +if (cur->magic !=GRUB_MM_FREE_MAGIC ) +grub_fatal ("free magic is broken at %p: 0x%x" , cur, cur->magic); -if (q <= q->next && (q > p || q->next < p)) +/* Deal with wrap-around */ +if (cur <= cur->next && (cur > p || cur->next < p))break ; } +/* mark p as free and insert it between cur and cur->next */ p->magic =GRUB_MM_FREE_MAGIC ; - p->next = q->next; - q->next = p; + p->next = cur->next; + cur->next = p; +/* +* If the block we are freeing can be merged with the next +* free block, do that. +*/ if (p->next + p->next->size == p) { p->magic =0 ; p->next->size += p->size; - q->next = p->next; + cur->next = p->next; p = p->next; } - r->first = q; + r->first = cur; -if (q == p + p->size) +/* Likewise if can be merged with the preceeding free block */ +if (cur == p + p->size) { - q->magic =0 ; - p->size += q->size; -if (q == s) - s = p; - s->next = p; - q = s; + cur->magic =0 ; + p->size += cur->size; +if (cur == prev) + prev = p; + prev->next = p; + cur = prev; } - r->first = q; +/* +* Set r->first such that the just free()d block is tried first. +* (An allocation is tried from *first->next, and cur->next == p.) +*/ + r->first = cur; } }
Signature · 1 line
2.32.0
Re: [PATCH 4/6] mm: document grub_free
Quoted 9 lines · Daniel Axtens
grub_free() posesses a surprising number of quirks, and also uses single-letter variable names confusingly to iterate through the free list.Document what's going on.
Use prev and cur to iterate over the free list.
Signed-off-by Daniel Axtens <[email protected]>
Daniel
PATCH 5/6 mm: document grub_mm_init_region
In reply to Daniel Axtensgrub_mm_init_region does some things that seem magical, especially around region merging. Make it a bit clearer.
--- grub-core/kern/mm.c | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-)
grub-core/kern/mm.c +29 -1
@@ -128,23 +128,51 @@ grub_mm_init_region (void *addr, grub_size_t size)if (((grub_addr_t ) addr +0x1000 ) > ~(grub_addr_t ) size) size = ((grub_addr_t) -0x1000 ) - (grub_addr_t ) addr; +/* Attempt to merge this region with every existing region */ for (p = &grub_mm_base, q = *p; q; p = &(q->next), q = *p) +/* +* Is the new region immediately below an existing region? That +* is, is the address of the memory we're adding now (addr) + size +* of the memory we're adding (size) + the bytes we couldn't use +* at the start of the region we're considering (q->pre_size) +* equal to the address of q? In other words, does the memory +* looks like this? +* +* addr q +* |----size-----|-q->pre_size-|<q region>| +*/ if ((grub_uint8_t *) addr + size + q->pre_size == (grub_uint8_t *) q) { +/* +* Yes, we can merge. r is our new region, it's address is the +* first GRUB_MM_ALIGNed address above addr. +*/ r = (grub_mm_region_t )ALIGN_UP ((grub_addr_t ) addr,GRUB_MM_ALIGN ); +/* Copy the region data across */ *r = *q; +/* Consider all the new size as pre-size */ r->pre_size += size; - + +/* +* If we have enough pre-size to create a block, create a +* block with it. Mark it as allocated and pass it to +* grub_free (), which will sort out getting it into the free +* list. +*/ if (r->pre_size >>GRUB_MM_ALIGN_LOG2 ) { h = (grub_mm_header_t) (r +1 ); +/* block size is pre-size converted to cells */ h->size = (r->pre_size >>GRUB_MM_ALIGN_LOG2 ); h->magic =GRUB_MM_ALLOC_MAGIC ; +/* region size grows by block size converted back to bytes */ r->size += h->size <<GRUB_MM_ALIGN_LOG2 ; +/* adjust pre_size to be accurate */ r->pre_size &= (GRUB_MM_ALIGN -1 ); *p = r;grub_free (h +1 ); } +/* Replace the old region with the new region */ *p = r;return ; }
Signature · 1 line
2.32.0
Re: [PATCH 5/6] mm: document grub_mm_init_region
Quoted 24 lines · Daniel Axtens
grub_mm_init_regiondoes some things that seem magical, especially around region merging. Make it a bit clearer.Signed-off-by Daniel Axtens <[email protected]>--- grub-core/kern/mm.c | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-)grub-core/kern/mm.c +7
-0@@ -128,23 +128,51 @@ grub_mm_init_region (void *addr, grub_size_t size)if (((grub_addr_t ) addr +0x1000 ) > ~(grub_addr_t ) size) size = ((grub_addr_t) -0x1000 ) - (grub_addr_t ) addr; +/* Attempt to merge this region with every existing region */ for (p = &grub_mm_base, q = *p; q; p = &(q->next), q = *p) +/* +* Is the new region immediately below an existing region? That +* is, is the address of the memory we're adding now (addr) + size +* of the memory we're adding (size) + the bytes we couldn't use +* at the start of the region we're considering (q->pre_size) +* equal to the address of q? In other words, does the memory
grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 148
Quoted 10 lines
grub-core/kern/mm.c +8
-0+* looks like this? +* +* addr q +* |----size-----|-q->pre_size-|<q region>| +*/ if ((grub_uint8_t *) addr + size + q->pre_size == (grub_uint8_t *) q) { +/* +* Yes, we can merge. r is our new region, it's address is the +* first GRUB_MM_ALIGNed address above addr.
I think s/above/below/...
Quoted 21 lines
grub-core/kern/mm.c +12
-1+*/ r = (grub_mm_region_t )ALIGN_UP ((grub_addr_t ) addr,GRUB_MM_ALIGN ); +/* Copy the region data across */ *r = *q; +/* Consider all the new size as pre-size */ r->pre_size += size; - + +/* +* If we have enough pre-size to create a block, create a +* block with it. Mark it as allocated and pass it to +* grub_free (), which will sort out getting it into the free +* list. +*/ if (r->pre_size >>GRUB_MM_ALIGN_LOG2 ) { h = (grub_mm_header_t) (r +1 ); +/* block size is pre-size converted to cells */ h->size = (r->pre_size >>GRUB_MM_ALIGN_LOG2 ); h->magic =GRUB_MM_ALLOC_MAGIC ; +/* region size grows by block size converted back to bytes */
grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 178
Quoted 10 lines
grub-core/kern/mm.c +2
-0r->size += h->size <<GRUB_MM_ALIGN_LOG2 ; +/* adjust pre_size to be accurate */ r->pre_size &= (GRUB_MM_ALIGN -1 ); *p = r;grub_free (h +1 ); } +/* Replace the old region with the new region */ *p = r;return ; }
Otherwise LGTM...
If you are OK with the change above then I can make it for you before applying the patch.
Daniel
Re: [PATCH 5/6] mm: document grub_mm_init_region
Quoted 39 lines · Daniel Kiper
Quoted 24 lines · Daniel Axtens
grub_mm_init_regiondoes some things that seem magical, especially around region merging. Make it a bit clearer.Signed-off-by Daniel Axtens <[email protected]>--- grub-core/kern/mm.c | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-)grub-core/kern/mm.c +7
-0@@ -128,23 +128,51 @@ grub_mm_init_region (void *addr, grub_size_t size)if (((grub_addr_t ) addr +0x1000 ) > ~(grub_addr_t ) size) size = ((grub_addr_t) -0x1000 ) - (grub_addr_t ) addr; +/* Attempt to merge this region with every existing region */ for (p = &grub_mm_base, q = *p; q; p = &(q->next), q = *p) +/* +* Is the new region immediately below an existing region? That +* is, is the address of the memory we're adding now (addr) + size +* of the memory we're adding (size) + the bytes we couldn't use +* at the start of the region we're considering (q->pre_size) +* equal to the address of q? In other words, does the memory grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 148
Quoted 10 lines
grub-core/kern/mm.c +8
-0+* looks like this? +* +* addr q +* |----size-----|-q->pre_size-|<q region>| +*/ if ((grub_uint8_t *) addr + size + q->pre_size == (grub_uint8_t *) q) { +/* +* Yes, we can merge. r is our new region, it's address is the +* first GRUB_MM_ALIGNed address above addr. I think s/above/below/...
Quoted 2 lines
grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 150
Quoted 2 lines
grub-core/kern/mm.c +1
-0+*/ r = (grub_mm_region_t )ALIGN_UP ((grub_addr_t ) addr,GRUB_MM_ALIGN );
We do r = ALIGN_UP(addr, GRUB_MM_ALIGN), so 'above' is actually correct.
But that probably indicates that I'm not explaining it well.
How does this sound:
/*
* Yes, we can merge the memory starting at addr into the
* existing region from below. Align up addr to GRUB_MM_ALIGN
* so that our new region has proper alignment.
*/
If you want you can change the comment and apply it, otherwise I will submit a v2.
Kind regards,
Daniel
Quoted 36 lines
Quoted 19 lines
grub-core/kern/mm.c +11
-1+/* Copy the region data across */ *r = *q; +/* Consider all the new size as pre-size */ r->pre_size += size; - + +/* +* If we have enough pre-size to create a block, create a +* block with it. Mark it as allocated and pass it to +* grub_free (), which will sort out getting it into the free +* list. +*/ if (r->pre_size >>GRUB_MM_ALIGN_LOG2 ) { h = (grub_mm_header_t) (r +1 ); +/* block size is pre-size converted to cells */ h->size = (r->pre_size >>GRUB_MM_ALIGN_LOG2 ); h->magic =GRUB_MM_ALLOC_MAGIC ; +/* region size grows by block size converted back to bytes */ grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 178
Quoted 10 lines
grub-core/kern/mm.c +2
-0r->size += h->size <<GRUB_MM_ALIGN_LOG2 ; +/* adjust pre_size to be accurate */ r->pre_size &= (GRUB_MM_ALIGN -1 ); *p = r;grub_free (h +1 ); } +/* Replace the old region with the new region */ *p = r;return ; }Otherwise LGTM...
If you are OK with the change above then I can make it for you before applying the patch.
Daniel
Re: [PATCH 5/6] mm: document grub_mm_init_region
Quoted 50 lines · Daniel Axtens
Quoted 39 lines · Daniel Kiper
Quoted 24 lines · Daniel Axtens
grub_mm_init_regiondoes some things that seem magical, especially around region merging. Make it a bit clearer.Signed-off-by Daniel Axtens <[email protected]>--- grub-core/kern/mm.c | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-)grub-core/kern/mm.c +7
-0@@ -128,23 +128,51 @@ grub_mm_init_region (void *addr, grub_size_t size)if (((grub_addr_t ) addr +0x1000 ) > ~(grub_addr_t ) size) size = ((grub_addr_t) -0x1000 ) - (grub_addr_t ) addr; +/* Attempt to merge this region with every existing region */ for (p = &grub_mm_base, q = *p; q; p = &(q->next), q = *p) +/* +* Is the new region immediately below an existing region? That +* is, is the address of the memory we're adding now (addr) + size +* of the memory we're adding (size) + the bytes we couldn't use +* at the start of the region we're considering (q->pre_size) +* equal to the address of q? In other words, does the memory grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 148
Quoted 10 lines
grub-core/kern/mm.c +8
-0+* looks like this? +* +* addr q +* |----size-----|-q->pre_size-|<q region>| +*/ if ((grub_uint8_t *) addr + size + q->pre_size == (grub_uint8_t *) q) { +/* +* Yes, we can merge. r is our new region, it's address is the +* first GRUB_MM_ALIGNed address above addr. I think s/above/below/...
Quoted 2 lines
grub-core/kern/mm.c grub_mm_init_region (void *addr, grub_size_t size) · line 150
Quoted 2 lines
grub-core/kern/mm.c +1
-0+*/ r = (grub_mm_region_t )ALIGN_UP ((grub_addr_t ) addr,GRUB_MM_ALIGN );We do r =
ALIGN_UP(addr, GRUB_MM_ALIGN), so 'above' is actually correct.But that probably indicates that I'm not explaining it well.
How does this sound:
Quoted 8 lines
/*
* Yes, we can merge the memory starting at addr into the
* existing region from below. Align up addr toGRUB_MM_ALIGN
* so that our new region has proper alignment.
*/If you want you can change the comment and apply it, otherwise I will submit a v2.
Now it is better. I will update the patch and apply it together with the other patches which got my RB.
Thanks,
Daniel
RFC PATCH 6/6 docs: document mm
In reply to Daniel AxtensThis is a sketch of much more detailed descriptions of how grub mm works. I expect we'll want to bikeshed it a bit so I will roll up change requests into subsequent series I send that touch mm.
--- docs/grub-dev.texi | 405 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 399 insertions(+), 6 deletions(-)
docs/grub-dev.texi +399 -6
@@ -80,8 +80,7 @@ This edition documents version @value{VERSION}. * Updating External Code:: * Porting:: * Error Handling:: -* Stack and heap size:: -* BIOS port memory map:: +* Memory Management:: * Video Subsystem:: * PFF2 Font File Format:: * Graphical Menu Software Design::
@@ -1025,8 +1024,403 @@ if (grub_errno != GRUB_ERR_NONE) grub_error_pop (); @end example -@node Stack and heap size -@chapter Stack and heap size +@node Memory Management +@chapter Memory Management + +Grub supports both stack and heap memory. + +@section Heap management overview + +Grub memory management boils down to cells, blocks and regions. + +The most fundamental concept in grub mm data structures is that of the +`cell'. The cell is the atomic unit of memory in grub's memory management. A +cell is @code{GRUB_MM_ALIGN} bytes in size, which is 16 bytes on a 32-bit +platform and 32 bytes on a 64-bit platform. + +All metadata structures are exactly one cell in size and are cell-aligned. + +A block represents a block of memory that is either: +@itemize + +@item an allocation: memory that has been allocated by another part of + grub and is being used, or + +@item free: memory from which an allocation can be made. + +@end itemize + +All blocks are cell-aligned and all blocks are a whole number of cells in size. + +A region is an area of memory from firmware which contains one or more blocks. + +For more details, see the comment at the top of @code{kern/mm.c}. + +@subsection Where does heap memory come from? + +Heap memory comes from platform-specific code: the platform's memory map must be +consulted to find free memory regions. Depending on the platform, these regions +may need to be `claimed' in some way to protect them from being used by +firmware. Firmware may provide grub with a range of differently sized and +dis-contiguous regions. + +A region is defined by a @code{grub_mm_region_t} structure. This metadata +structure is stored in the first cell of each region. + +Region metadata consists of a pointer to a free block to speed up allocations +(@code{first}), a pointer to the next region (@code{next}) if one exists, the +number of bytes lost at the beginning to retain alignment (@code{pre_size}) and +the total size of the allocatable space in bytes (@code{size}). + +Regions are tracked as a linked list, with the head being @code{grub_mm_base}. + +Regions are created by platform-specific code. Once platform-specific code has +performed any necessary initialisation, it calls @code{grub_mm_init_region ()} +on the memory to make it available as a new region. Then it can used by the grub +memory management code to service allocation requests. + +If firmware passes a non-cell-aligned address to @code{grub_mm_init_region}, +then the address will be rounded up to cell-alignment, and the number of +`wasted' bytes stored in @code{pre_size}. Likewise, if the size after aligning +is not a multiple of the cell size, those bytes beyond the end of the last cell +cannot be used. (These bytes are not recorded.) + +When a region is added, grub will prefer to extend an existing region, if it can +do so. This allows for larger individual allocations to be satisfied. Currently +the code only supports merging when the new allocation is directly below an +existing region, that is, @code{new address + new size + previous region +pre_size = previous region base}. + +If a region cannot be merged into an existing region, a new region is created +and marked as containing a single free block. Regions are added in sorted order, +smallest first, but the region merging process does not respect the sorted order +and so the linked list may not remain in sorted order. + +@subsection Blocks: Free blocks and allocations + +Metadata for a block (either an allocation or a free block) is stored in a +@code{grub_mm_header_t} structure. + +The type of a block is set by the @code{magic} value. Its @code{size} is +measured in cells and includes the header cell. If it is a free block, the +@code{next} pointer points to the next free block in the circular linked +list. If the block is allocated, the @code{next} pointer is undefined. + +Metadata for a block is always stored in the cell immediately preceding the +block data. + +A region starts as one big free block. + +@subsection Example + +Say firmware provides you with one region running from 0xffff0 (1MB - 16 bytes) +to 0x10ffff0 (17MB - 16 bytes). Say you're on a 64-bit platform, so cell size is +32 bytes (0x20). The resultant layout is: + +@example +0x00ffff0 +- Start of region as seen by firmware + | ("pre-space", considered in region merging) +0x0100000 +- grub_mm_region_t + | first free block: 0x100020 + | next region: NULL + | pre_size (wasted bytes to ensure alignment): 0x10 + | size: 0xffffa0 (bytes, rounded to cells, not including our cell) + | (The last 16 bytes are wasted as there is not enough + | to form a cell. These are not recorded.) + | +0x0100020 +- grub_mm_header_t + | next free block: 0x100020 (circular linked list) + | size: 0x7ffff cells (region size in cells) + | magic: GRUB_MM_FREE_MAGIC + | <padding> +0x0100040 | -- + | free space belonging to the block + | +0x10fffe0 +- End of region as seen by grub + | (lost space) +0x10ffff0 +- End of region as seen by firmware +@end example + +Now say you want to allocate 1MB of memory with 1MB alignment. You would call +something like @code{grub_memalign (1024 * 1024, 1024 * 1024)}. This would then +call @code{grub_real_malloc ()} with our region. That function is well +documented: refer to the comments there for precisely how it operates. + +In this case, @code{grub_real_malloc ()} will satisfy the allocation, splitting +the free block into 3 and allocating as high an address as possible: + +@example +0x0100000 +- grub_mm_region_t + | first free block: 0x0100020 + | next region: NULL + | pre_size (wasted bytes to ensure alignment): 0x10 + | size: 0xffffa0 (bytes, rounded to cells, not including our cell) + | +0x0100020 +- grub_mm_header_t + | next free block: 0x1000000 + | size: 0x6ffff cells + | magic: GRUB_MM_FREE_MAGIC + | <padding> +0x0100040 | -- + | free space belonging to the block + | +0x0efffe0 +- grub_mm_header_t + | next free block: undefined + | size: 0x8001 cells (1MB + header cell) + | magic: GRUB_MM_ALLOC_MAGIC + | <padding> +0x0f00000 | -- + | allocated space + | +0x1000000 +- grub_mm_header_t + | next free block: 0x0100020 + | size: 0x7fff cells + | magic: GRUB_MM_FREE_MAGIC + | <padding> +0x1000020 | -- + | free space belonging to block + | +0x10fffe0 +- End of region as seen by grub +@end example + +In this case the free pointer in the region will not be updated. In some cases +it is updated on allocations: for example when the region it points to is no +longer free, or for small allocations. + +Now we make a small allocation of a few bytes. This will be rounded up to two +cells - one for the data and one for the header. @code{grub_real_malloc ()} will +iterate over the linked list of free block using a pair of pointers representing +the previous and current free block, @code{prev} and @code{cur} +respectively. @code{prev} starts at the region's @code{*first} pointer, and +@code{cur} starts as @code{*first->next}. + +This will be the result: + +@example +0x0100000 +- grub_mm_region_t + | first free block: 0x0100020 + | next region: NULL + | pre_size (wasted bytes to ensure alignment): 0x10 + | size: 0xffffa0 (bytes) + | +0x0100020 +- grub_mm_header_t + | next free block: 0x1000000 + | size: 0x6ffff cells + | magic: GRUB_MM_FREE_MAGIC +0x0100040 | -- + | free space belonging to the block + | +0x0efffe0 +- grub_mm_header_t + | size: 0x8001 cells (1MB + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x0f00000 | -- + | allocated space + | +0x1000000 +- grub_mm_header_t + | next free block: 0x0100020 + | size: 0x7ffd cells + | magic: GRUB_MM_FREE_MAGIC +0x1000020 | -- + | free space belonging to block + | +0x10fffa0 +- grub_mm_header_t + | size: 0x2 cells (32 bytes + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x10fffc0 | -- + | allocated space + | +0x10fffe0 +- End of region as seen by grub +@end example + +In this case, we do hit the code block at the end of @code{grub_real_malloc} +that would move @code{first}, but because we never advanced @code{prev}, +@code{*first} remains unchanged. + +So a subsequent allocation will again be made from the second free block if +possible - for example if we were to allocate 64kB, the result would be the +following: + +@example +0x0100000 +- grub_mm_region_t + | first free block: 0x0100020 + | next region: NULL + | pre_size (wasted bytes to ensure alignment): 0x10 + | size: 0xffffa0 (bytes) + | +0x0100020 +- grub_mm_header_t + | next free block: 0x1000000 + | size: 0x6ffff cells + | magic: GRUB_MM_FREE_MAGIC +0x0100040 | -- + | free space belonging to the block + | +0x0efffe0 +- grub_mm_header_t + | size: 0x8001 cells (1MB + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x0f00000 | -- + | allocated space + | +0x1000000 +- grub_mm_header_t + | next free block: 0x0100020 + | size: 0x77fc cells + | magic: GRUB_MM_FREE_MAGIC +0x1000020 | -- + | free space belonging to block + | +0x10eff80 +- grub_mm_header_t + | size: 0x801 cells (64kB + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x10effa0 | -- + | allocated space + | +0x10fffa0 +- grub_mm_header_t + | size: 0x2 cells (32 bytes + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x10fffc0 | -- + | allocated space + | +0x10fffe0 +- End of region as seen by grub +@end example + +@subsection Freeing an allocation + +To free an allocation, the block's magic is flipped to +@code{GRUB_MM_FREE_MAGIC}, it's placed into the free list, and merged with any +adjacent free blocks. + +There are two things to be aware of. + +Firstly, the free-list ordering goes `backwards', from high addresses to low +addresses. That is, except in the case where the list wraps around, +@code{free_block > free_block->next}. + +Secondly, the region's @code{first} pointer is updated to the block preceding +the block that has just been freed. This means (because the first pointer points +to the region @emph{before} the region that will be used to service an +allocation) that the next allocation will try to use the newly freed block. + +To illustrate, say we free our 32 byte allocation: + +@example +0x0100000 +- grub_mm_region_t + | first free block: 0x0100020 + | next region: NULL + | pre_size (wasted bytes to ensure alignment): 0x10 + | size: 0xffffa0 (bytes) + | +0x0100020 +- grub_mm_header_t + | next free block: 0x10fffa0 + | size: 0x6ffff cells + | magic: GRUB_MM_FREE_MAGIC +0x0100040 | -- + | free space belonging to the block + | +0x0efffe0 +- grub_mm_header_t + | size: 0x8001 cells (1MB + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x0f00000 | -- + | allocated space + | +0x1000000 +- grub_mm_header_t + | next free block: 0x0100020 + | size: 0x77fc cells + | magic: GRUB_MM_FREE_MAGIC +0x1000020 | -- + | free space belonging to block + | +0x10eff80 +- grub_mm_header_t + | size: 0x801 cells (64kB + header cell) + | magic: GRUB_MM_ALLOC_MAGIC +0x10effa0 | -- + | allocated space + | +0x10fffa0 +- grub_mm_header_t + | next free block: 0x1000000 + | size: 0x2 cells (32 bytes + header cell) + | magic: GRUB_MM_FREE_MAGIC +0x10fffc0 | -- + | free space belonging to block + | +0x10fffe0 +- End of region as seen by grub +@end example + +The final block is now freed; it is inserted in the ring such that each region's +next is at a lower address that the previous free region, modulo wrapping. The +region's @code{first} is set such that @code{*first->next} is the block we just +freed. + +@subsection Memory pressure and large allocations + +The largest allocation that can be serviced depends on the platform and heap +fragmentation. + +If an allocation cannot be serviced, grub will attempt to invalidate disk caches +to free up memory, and try again. + +Grub does not implement virtual memory or paging: there is no way for it to +stitch together various dis-contiguous pages from firmware into a contiguous +address space. + +Grub always searches regions in order: if you are trying to allocate, for +example, a number of 64kB objects and your region list starts with small regions +with numerous free blocks that are all too small to satisfy the allocation, +@code{grub_memalign ()} will have to check each of those regions every time +before finally getting to a region that can satisfy the allocation. + +@subsection Summary: the life-cycle of an allocation from the heap + +@itemize @bullet + +@item A heap region is added in grub initialisation by calling + @code{grub_mm_init_region ()}. The region is marked as a single free + block. It is inserted into the list of regions. + +@item A call to @code{grub_malloc ()} is made, seeking a certain amount of + memory. + +@item This is translated into a call to @code{grub_memalign ()} with no + alignment requirement. + +@item For each region from first to last: + + @itemize + + @item Call @code{grub_real_malloc ()} with that region to try to satisfy the + allocation. + + @item Starting from the region's @code{*first->next}, which is usually the + most recently freed block, try each block in the free ring. + + @item If it is large enough to satisfy the size and alignment requirements, + use it. Carve out an appropriate block, mark it as allocated, and adjust + the size and shape of the free space as required. + + @item If we found a block, and we allocated less than 32kB, or we allocated + the entire free block, mark the previous block as the first free block. + + @item Return the block we found. If we cannot find an appropriate block, + return NULL. + +@end itemize + +@item The caller uses their block of memory. + +@item A call to @code{grub_free ()} is made to release the memory back to + grub. The block is reinserted into the free list, merging with adjacent + free blocks if possible. The region's @code{first} pointer is set such + that @code{*first->next} is the most recently freed region. + +@end itemize + +@section Another memory user: the relocator + +The grub mm code is not the only piece of code that uses memory from +firmware. Grub also a `relocator' infrastructure that can be used to find +appropriate places in memory to lay out boot material. This code talks to the +platform specific code to iterate over available memory from firmware, but +rather than adding it to the heap as a region, the relocator uses it directly. + +@section Stack and heap sizes On emu stack and heap are just normal host OS stack and heap. Stack is typically 8 MiB although it's OS-dependent.
@@ -1088,8 +1482,7 @@ In short: @end multitable -@node BIOS port memory map -@chapter BIOS port memory map +@section BIOS port memory map @c By Yoshinori K Okuji @multitable @columnfractions .15 .25 .5
Signature · 1 line
2.32.0