Pool of Memory in Kernel driver for Multiple processes
Asked Answered
E

1

9

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.

Ecuador answered 27/4, 2015 at 12:18 Comment(0)
M
6

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.

Michaeu answered 14/5, 2015 at 16:22 Comment(4)
How can I manage the memory distribution between processes using mempool_create() or kmem_cache_create(). Those API's I can use during init() of the module...what to use in the open() for each process.Ecuador
You can do kmem_cache_create() in module init and pass its return value(handle) to open method. like the following code: int scull_open(struct inode inode, struct file *filp){ filp->private_data = dev; / for other methods */ }. so you can simply store the handle into your dev structure.Michaeu
but if you are asking how to implement device driver's method while handling the cases that multiple process can access the same device or different virtual devices, it is a different thing which is not related with how to use memory pool.Michaeu
Normally, if you driver need to support the access from different processes and you need to differentiate them from driver side, then you can store a pid key(current->pid) for each process in a shared link list. For more info,you can refer to makelinux.net/ldd3/chp-6-sect-6 "6.6.4. Cloning the Device on open"Michaeu

© 2022 - 2024 — McMap. All rights reserved.