Skip to main content

kmalloc

实现kmalloc/kfree

有了buddy sys和slab的api之后,kmalloc/kfree已经呼之欲出了

kmalloc: 如果是大块,buddy sys malloc; 否则slab malloc

kfree: 由addr 得到page, 如果 page->slab , slab free; 如果 page->pool buddy free

void *_kmalloc(size_t size, bool is_record, size_t *real_size)
{
void *addr;
int order;

if (unlikely(size == 0))
return ZERO_SIZE_PTR;

if (size <= SLAB_MAX_SIZE) {
addr = alloc_in_slab(size, real_size);
#if ENABLE_MEMORY_USAGE_COLLECTING == ON
if(is_record && collecting_switch) {
record_mem_usage(*real_size, addr);
}
#endif
} else {
if (size <= BUDDY_PAGE_SIZE)
order = 0;
else
order = size_to_page_order(size);
addr = get_pages(order);
}

return addr;
}

void _kfree(void *ptr, bool is_revoke_record)
{
struct page *page;

if (unlikely(ptr == ZERO_SIZE_PTR))
return;

page = virt_to_page(ptr);
#if ENABLE_MEMORY_USAGE_COLLECTING == ON
if (collecting_switch && is_revoke_record) {
revoke_mem_usage(ptr);
}
#endif
if (page && page->slab)
free_in_slab(ptr);
else if (page && page->pool)
buddy_free_pages(page->pool, page);
else
kwarn("unexpected state in %s\n", __func__);
}