Memory Allocation in Linux Kernel

旧巷老猫 提交于 2019-12-04 14:29:52

问题


I had an interview today and was asked this question. What Kernel Memory allocation strategy would you use, if you were asked to allocate memory of size 2KB and that allocated memory should be page aligned.

KMALLOC handles smaller memory allocation strategies but the lowest unit that it supports is 4KB, which is the size of the physical page. I asked him, if he was expecting slab allocators? He didn't reply positively.


回答1:


I read in: http://www.makelinux.net/books/lkd2/ch11lev1sec4

The function returns a pointer to a region of memory that is at least size bytes in length

I know the system Operation x86 ( 32 bits ) - the max size mapping in RAM 4GB, but it include Reference and information brute.

so 4GB is the all space available, convert for 'KB' = 4194304 KB, The Memory Ram iqual the Grid 4194304 spaces( index and bory information ), or the side of square( in latin Radix Quadratum ) SQRT(4194304)= all size only index the information, as well as below "int flags")

void * kmalloc(size_t size, int flags)

you might want to you use the function, for use KB diferent 2 or 4.

att




回答2:


For page aligned memory allocation use alloc_pages/alloc_page. You can also use __get_free_pages/__get_free_page. __get_free_page eventually uses alloc_pages only. These functions are used to allocate page from physical memory. The allocator for these is physical memory allocator or buddy allocator

Your assumption that kmalloc allocates minimum 4KB of memory is wrong. The kmalloc is based on slab allocator . Do a cat /proc/slabinfo you will know that there are several slabs already created for kmalloc. These slabs will reduce the internal memory fragmentation for allocations using kmalloc. So if you allocate 4 bytes then only 8 bytes will be allocated from kmalloc slab of kmalloc-8(4 bytes of internal fragmentation). If you allocate 9 bytes then 16 bytes are allocated from kmalloc-16 slab, and so on.

kmalloc, alloc_page/s, __get_free_page/s dont require page tables. The virtual memory address returned are just offsetted address.

Though you have not asked, I will mention that vmalloc is another allocation technique which uses resource map allocator. The noncontiguous memory allocated via vmalloc is accessed by using kernel master page table(swapper_pg_dir)

The different Linux allocators are mentioned in Mel Gorman book and Professional linux kernel architecture book. Go through these, it will help.



来源:https://stackoverflow.com/questions/30085876/memory-allocation-in-linux-kernel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!