kzalloc() - Maxmum size at a single call?

2019-02-15 16:58发布

What is the maximum size that we can allocate using kzalloc() in a single call?

This is a very frequently asked question. Also please let me know if i can verify that value.

3条回答
仙女界的扛把子
2楼-- · 2019-02-15 17:05

No different to kmalloc(). That's the question you should ask (or search), because kzalloc is just a thin wrapper that sets GFP_ZERO.

Up to about PAGE_SIZE (at least 4k) is no problem :p. Beyond that... you're right to say lots of people people have asked, it's definitely something you have to think about. Apparently it depends on the kernel version - there used to be a hard 128k limit, but it's been increased (or maybe dropped altogether) now. That's just the hard limit though, what you can actually get depends on a given system. (And very definitely on the kernel version).

Maybe read What is the difference between vmalloc and kmalloc?

You can always "verify" the allocation by checking the return value from kzalloc(), but by then you've probably already logged an allocation failure backtrace. Other than that, no - I don't think there's a good way to check in advance.

查看更多
Root(大扎)
3楼-- · 2019-02-15 17:19

The upper limit (number of bytes that can be allocated in a single kmalloc / kzalloc request), is a function of: the processor – really, the page size – and the number of buddy system freelists (MAX_ORDER).

On both x86 and ARM, with a standard page size of 4 Kb and MAX_ORDER of 11, the kmalloc upper limit on a single call is 4 MB!

Details, including explanations and code to test this, here: http://kaiwantech.wordpress.com/2011/08/17/kmalloc-and-vmalloc-linux-kernel-memory-allocation-api-limits/

查看更多
Ridiculous、
4楼-- · 2019-02-15 17:21

However, it depends on your kernel version and config. These limits normally locate in linux/slab.h, usually descripted as below(this example is under linux 2.6.32):

#define KMALLOC_SHIFT_HIGH  ((MAX_ORDER + PAGE_SHIFT - 1) <= 25 ? \
                             (MAX_ORDER + PAGE_SHIFT - 1) : 25)
#define KMALLOC_MAX_SIZE    (1UL << KMALLOC_SHIFT_HIGH)
#define KMALLOC_MAX_ORDER   (KMALLOC_SHIFT_HIGH - PAGE_SHIFT)

And you can test them with code below:

#include <linux/module.h>
#include <linux/slab.h>
int init_module()
{

    printk(KERN_INFO "KMALLOC_SHILFT_LOW:%d, KMALLOC_SHILFT_HIGH:%d, KMALLOC_MIN_SIZE:%d, KMALLOC_MAX_SIZE:%lu\n",
            KMALLOC_SHIFT_LOW,  KMALLOC_SHIFT_HIGH, KMALLOC_MIN_SIZE, KMALLOC_MAX_SIZE);
    return 0;
}

void cleanup_module()
{
    return;
}

Finally, the results under linux 2.6.32 32bits are: 3, 22, 8, 4194304, it means the min size is 8 bytes, and the max size is 4MB.

PS. you can also check the actual size of memory allocated by kmalloc, just use ksize(), i.e.

void *p = kmalloc(15, GFP_KERNEL);
printk(KERN_INFO "%u\n", ksize(p)); /* this will print "16" under my kernel */
查看更多
登录 后发表回答