0

In the user space programm I am allocating some memory via mmap as the following function call:

void *memory;
int fd;
fd = open(filepath, O_RDWR);
if (fd < 0)
   return errno;

memory = mmap(NULL, 4096, PROT_WRITE, MAP_SHARED, fd, 0);
if (memory == MAP_FAILED)
      return -1;

//syscall() goes here

In the kernel space in my system call I am trying to copy data to the memory mapped region as follows:

copy_to_user(memory,src,4096);

EDIT: added error checking code to the post for clarification The copy_to_user() call is repeatedly failing in this case, whereas if I would have done a memory = malloc() it was succeeding always.

Am I getting some permission flags wrong in this case for mmap ?

bawejakunal
  • 1,678
  • 2
  • 25
  • 54
  • what is the error ? Do you use [perror()](http://man7.org/linux/man-pages/man3/perror.3.html) ? We can't help you with only what you actually write. – Stargateur Nov 20 '16 at 15:23
  • copy_to_user() in kernel space does not sets `errno` which can be predicted via `perror()` – bawejakunal Nov 20 '16 at 15:50

1 Answers1

0

Does the open succeed? What about mmap? Is the target file big enough? Can you write to the file through the mapping in userspace?

Also, the repeated 4096 is a strong hit your code is wrong. Userspace should pass the expected size instead.

  • The target file is newly created, I do not understand what you mean by "big enough", for write purposes the data will be written to the file right ? The open() call definitely succeeds, 4096 is not repeated just for representation purposes. – bawejakunal Nov 20 '16 at 15:20
  • What about the mmap (and how do you check it, in particular do you test for MAP_FAILED?). I suspect the file is of 0 size, which will prevent copy_to_user from working. I don't understand what's unclear with the question about writting through the mapping - memory[0] = 'A' or similar, for instnace. When done, it would likely trigger SIGBUS clearly showing the issue has nothing to do with copy_to_user. –  Nov 20 '16 at 15:43
  • So what about that size, for the 3rd time. –  Nov 20 '16 at 15:51
  • For second time: The target file is newly created, I do not understand what you mean by "big enough", for write purposes the data will be written to the file right ? How is file size supposed to affect copy_to_user or mmap for write purposes ? – bawejakunal Nov 20 '16 at 15:52
  • 1
    Writing through mapped areas does not grow the file. It has to be big enough to cover the area already. So, in particular, if the file is of 0 size, things like copy_to_user which are able to catch the condition will fail. ftruncate the file to 4096 or more. –  Nov 20 '16 at 15:58
  • @bawejakunal http://stackoverflow.com/questions/15684771/how-to-portably-extend-a-file-accessed-using-mmap – Stargateur Nov 20 '16 at 16:04