Reputation: 51
I try to allocate large memory in FreeBSD-x64 kernel space, but it returns NULL.
void *ptr = NULL;
static int
init_module(void)
{
u_long SIZE_ALLOC = ((u_long)2500 * 1024 * 1024);
ptr = malloc(SIZE_ALLOC, M_DEVBUF, M_NOWAIT);
if( !ptr )
uprintf("Allocation has been failed!!\n");
return (0);
}
I have enough RAM(8 [GB]
) and I have enough free memory, but it returns NULL
.
If I run this code in user-space it works fine and catch huge memory but for kernel-space it fails !!!!
Where is mistake and how can I solve this?
Upvotes: 2
Views: 1161
Reputation: 43495
You can only get a NULL result when you use the M_NOWAIT
flag.
It basically means that there is not this much memory available right now.
Try M_WAITOK
. And I would add a M_NODUMP
as well. The consequence is that the module init process might be put to sleep until enough memory is freed up.
The kernel malloc allocates phyisical memory, which is not paged. See the memory management section in "The Design and Implementation of the 4.4BSD Operating System". The same text can be found verbatim in "The Design and Implementation of the FreeBSD Operating System".
You can look at the amount of physical memory available with the sysctl vm.phys_free
. On my machine this shows:
FREE LIST 0:
ORDER (SIZE) | NUMBER
| POOL 0 | POOL 1 | POOL 2
-- -- -- -- -- -- -- --
12 ( 16384K) | 0 | 0 | 0
11 ( 8192K) | 0 | 0 | 0
10 ( 4096K) | 0 | 0 | 0
9 ( 2048K) | 0 | 0 | 0
8 ( 1024K) | 0 | 0 | 0
7 ( 512K) | 0 | 0 | 0
6 ( 256K) | 0 | 0 | 0
5 ( 128K) | 33 | 4 | 0
4 ( 64K) | 2137 | 112 | 0
3 ( 32K) | 18136 | 116 | 5
2 ( 16K) | 20492 | 47 | 11111
1 ( 8K) | 2817 | 24 | 23422
0 ( 4K) | 1396 | 32 | 4956
If I interpret this correctly, I could not allocate a contiguous block >128K using the kernel malloc.
Upvotes: 4
Reputation: 1822
whatever RAM you have it does not increase the portion, in same proportion of huge RAM, of RAM used by kernel. Usually Kernel has 1GB RAM to use for its functionality (I am not much sure about definite amount). So due to limited available RAM, failure of such huge allocation in kernel mode is not a surprize
Upvotes: 0