Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory for user space from kernel thread

My question is about passing data from kernel to a user space program. I want to implement a system call "get_data(size, char *buff, char **meta_buf)". In this call, buff is allocated by user space program and its length is passed in the size argument. However, meta_buf is a variable length buffer that is allocated (in the user space program's vm pages) and filled by kernel. User space program will free this region.

(I cant allocate data in user space as user space program does not know size of the meta_buff. Also, user space program cannot allocate a fixed amount of memory and call the system call again and again to read the entire meta data. meta_data has to be returned in one single system call)

  1. How do I allocate memory for a user space program from kernel thread? (I would even appreciate if you can point me to any other system call that does a similar operation - allocating in kernel and freeing in user space)
  2. Is this interface right or is there a better way to do it?
like image 594
Methos Avatar asked Oct 26 '09 04:10

Methos


1 Answers

Don't attempt to allocate memory for userspace from the kernel - this is a huge violation of the kernel's abstraction layering. Instead, consider a few other options:

  • Have userspace ask how much space it needs. Userspace allocates, then grabs the memory from the kernel.
  • Have userspace mmap pages owned by your driver directly into its address space.
  • Set an upper bound on the amount of data needed. Just allocate that much.

It's hard to say more without knowing why this has to be atomic. Actually allocating memory's going to need to be interruptible anyway (or you're unlikely to succeed), so it's unlikely that going out of and back into the kernel is going to hurt much. In fact, any write to userspace memory must be interruptible, as there's the potential for page faults requiring IO.

like image 84
bdonlan Avatar answered Nov 13 '22 12:11

bdonlan