Search code examples
memory-managementlinux-kernellinux-device-driverkernel-modulekmalloc

Pool of Memory in Kernel driver for Multiple processes


Suppose we want to maintain a pool of memory in a device driver or module. How can that pool be created and be available to multiple processes lets say 4 processes, accessing this driver/module.

Assume 1 MB of memory in the pool.

When I was reading LDD I came across api's mempool_create() but then there's also kmalloc.

If someone has done such a thing kindly share the knowledge.

My initial approach is to allocate using kmalloc() and then maintain start and end pointers in the private object for each process that opens the module.

EDIT: Thanks @kikigood for spending some time on this. So based on your comments, I do something like this.

Lets say I allocated 1MB of mempool during init. And I want to restrict the count of processes to 4, so I keep a count. Increment this count at every

atomic_t count =0;
    open()
    { 
        if(count >4) 
            return -ENOMEM;
        count++; 
    } 

Also I maintain a buffer within my private device structure per process.

How to assign some memory from pool to this buffer.


Solution

  • In order to create a memory pool, you need to use the kernel's slab allocator, or by maintaining the memory pool by yourself like what you did (kmalloc). By using kernel's slab allocator, you can use one of those:

    • kmem_cache_create()

    • mempool_create()

    I think the key problem for you to maintain a pool by yourself is a risk of creating memory fragmentation issue which will quickly run out of your memory or you can't allocate a large memory block even if there are lots of free memory.

    Another benefit of using kernel's slab allocator is you can easily monitor the memory usage by looking into your /proc/slab entries.