Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

c - KMALLOC size allocation

Does KMALLOC allocates only in page size memory or it can allocate less ? What are the sizes that the kmalloc can allocate ? Where can I find description of it, as everywhere I looked it doesn't really say how much memory it allocates ? What I want to know is what are the actual sizes that KMALLOC allocates. Does it allocate size of power of 2 ? Does it just find free objects from the cache that is ready ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My understanding is as follows: the kernel is dealing with the physical memory of the system, which is available only in page-sized chunks; thus when you call kmalloc() you are going to get only certain predefined, fixed-size byte arrays.

The actual memory you get back is dependent on the system's architecture, but the smallest allocation that kmalloc can handle is as big as 32 or 64 bytes. You will get back from a call to kmalloc() at least as much memory as you asked for (usually more). Typically you will not get more than 128 KB (again, architecture dependent)

To get the page size (in bytes) of your system you can execute the command:

getconf PAGESIZE

or

getconf PAGE_SIZE

This information on max page size is in /usr/src/linux/include/linux/slab.h

And yes, the page sizes are generally powers of 2, but again, you're not going to get exactly what you ask for, but a little bit more.

You can use some code like this:

void * stuff;
stuff = kmalloc(1,GFP_KERNEL);
printk("I got: %zu bytes of memory
", ksize(stuff));
kfree(stuff);

To show the actual amount of memory allocated:

[90144.702588] I got: 32 bytes of memory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...