ssg
ssg

Reputation: 347

malloc function in kernel space

Can I use malloc in kernel space? And when I use kmalloc function in which part of memory, allocation happens? If I am writing driver program the variables i am taking in that program will be allocated in same way as in user space like normal variable function in stack and static in initialized and uninitialized data sections or it will be at different part of memory and if it is stored differently then in which part of memory it will be stored?

Please clarify above things, i am having problem while using device driver programs.

Upvotes: 0

Views: 1949

Answers (1)

Martin Drab
Martin Drab

Reputation: 697

Well, I have experience with Windows driver which probably does not interest you. However, I expect that things would be similar on both OS.

  • local variables are allocated on stack,

  • global/static ones in the data section of the kernel driver image.

In other words, the same rules as in userspace. In the Windows world, the whole driver image is placed in so-called resident memory block – that block is never paged out to disk, nor it is moved to another physical memory location.

kmalloc (ExAllocatePoolXxx in WIndows) is an equivalent of malloc routine for allocating a block of memory (usually smaller than one page). Unlike userspace malloc, the kenrel variant allows you to specify additional options.

For example, the ExAllocatePoolXxx routine allows you to specify whether the block of allocated memory needs to be resident or not. The Linux kernel variant (kmalloc) seems to offer much more options: http://www.makelinux.net/books/lkd2/ch11lev1sec4.

If you need to allocate a memory block larger than page size, it might be better to use some other means of kernel memory allocation.

Upvotes: 1

Related Questions