Virtual vs physical address in kmalloc
Posted: Sun Apr 29, 2018 3:46 pm
I am following James Molloy's Kernel tutorial. In it, he has this bit of code for kmalloc:
Accompanied with the description:
It seems to me that the virtual address returned is the same as the physical address shared. So why make the distinction?
Code: Select all
u32int kmalloc(u32int sz, int align, u32int *phys)
{
if (align == 1 && (placement_address & 0xFFFFF000)) // If the address is not already page-aligned
{
// Align it.
placement_address &= 0xFFFFF000;
placement_address += 0x1000;
}
if (phys)
{
*phys = placement_address;
}
u32int tmp = placement_address;
placement_address += sz;
return tmp;
}
I have rewritten the code snippet as follows:kmalloc will return a virtual address. But, we also (bear with me, you'll be glad we did later) need to get the physical address of the memory allocated.
Code: Select all
u32int kmalloc_ ( u32int size, int align, u32int *physical_address )
{
// Page align the address
if ( align == 1 && ( placement_address & 0xFFFFF000 ) )
{
placement_address &= 0xFFFFF000;
placement_address += 0x1000;
}
u32int base = placement_address;
// Share physical address
if ( physical_address )
{
*physical_address = base;
}
placement_address += size;
return base; // how is this different from physical_address?
}