LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Allocating memory for user program variable from kernel module (https://www.linuxquestions.org/questions/programming-9/allocating-memory-for-user-program-variable-from-kernel-module-216607/)

appas 08-12-2004 06:02 AM

Allocating memory for user program variable from kernel module
 
Hi,

Is it possible to allocate to allocate memory for char * variable defined in user program from
kernel module.

I would put things in detail with the below code.
The below code is part of character driver . "xxx_read" function is called by a user program passing
a char * pointer (buf in below code).

Code:

ssize_t xxx_read (struct file *filp, char *buf, size_t count, loff_t *pos)
{
  printk("PROCESS %i (%s) GOING TO SLEEP\n",current->pid, current->comm);
  interruptible_sleep_on(waitQueueRef);
  // initialize 'modifiedFile"
  // can i use:  buf = (char *) kmalloc(sizeof(modifiedFile), GFP_KERNEL);
  copy_to_user(buf,modifiedFile,strlen(modifiedFile));
  return 0;
}

What i need is whether i can use kmalloc for the variable "buf" inside the "xxx_read" and free the
memory using "free" in my user program which calls the kernel read function.

infamous41md 08-12-2004 12:41 PM

no, you cannot do that. a little hack that you can do to allocate space in a user program is this: adjust the top of the user heap manually, and then stick the data there. however, you CANNNOT call free on that pointer, as malloc has no idea that it even exists. if you wanted to do that:

user_ptr = current->mm->brk;
current->mm->brk += NUM_BYTES;
/* now user_ptr can be copied to */

however that is not something that 'proper' people will want you to do, it's rather hackish. why not just have the user pass a buffer instead?

appas 08-12-2004 10:52 PM

Thank you for your response,
I can pass the buffer from user program but i cannot determine the size of buffer at user level which will contain the data read.
I want to fetch all the data with single read without repeating the read function multiple times till end of file is reached.
Any way, I made an workaround, once again thanks for your support.


All times are GMT -5. The time now is 05:35 AM.