I'm implementing a naive memory manager for Vulkan device memory, and would like to make sure that I understand the alignment requirements for memory and how to satisfy them.
So, assuming that I've allocated a 'pool' of memory using vkAllocateMemory and wish to sub-allocate blocks of memory in this pool to individual resources (based on a VkMemoryRequirements struct), will the following pseudocode be able to allocate a section of this memory with the correct size and alignment requirements?
- Request memory with RequiredSize and RequiredAlignment
- Iterate over blocks in the pool looking for one that is free and has size > RequiredSize
- If the offset in memory of the current block is NOT divisible by RequiredAlignment, figure out the difference between the alignment and the remainder
- If the size of the current block minus the difference is less than RequiredSize, skip to the next block in the pool
- If the difference is more than 0, insert a padding block with size equal to the difference, and adjust the current unallocated block size and offset
- Allocate RequiredSize bytes from the start of the current unallocated block (now aligned), adjust the Size and Offset of the unallocated block accordingly
- Return vkDeviceMemory handle (of pool), size and offset (of new allocated block)
- If we reach the end of the block list instead, this pool cannot allocate the memory
In other words, do we just need to make sure that Offset is a multiple of RequiredAlignment?