1
votes

[I am a newbie to device driver programming, so requesting people to be patient]

I am writing a character device driver, and I am trying to mmap some portion of the allocated memory in the driver to the user space.

In the init_module() function, I allocate the some buffer space like this -

buf = (char*)vmalloc_user(SIZE_OF_BUFFER);

buf now points to some address.

Now, in the driver's mmap function, I set the VM_RESERVED flag, and call

remap_vmalloc_range(vma, (void*)buf, 0);

Then I create a character device file in /dev with the correct major number.

Now I create a simple program in the user space to open the character device file, then call mmap() and read data from this mmap'ed memory.

In the call to mmap() in userspace, I know there is an option where we can pass the start address of the area. But is there a way the user space mmap can point to the same address as done by the buf in the driver space?

I think that because the address of buf in the driver space is different from the one returned by mmap() in the user space, my user space program ends up reading junk values. Is there any other way than actually entering the address in the mmap() in the user space to solve this problem?

1

1 Answers

2
votes

You pretty much have to design your driver interface so that the userspace map address doesn't matter. This means, for example, not storing pointers in an mmap region that's accessed outside of a single userspace process.

Typically, you'd store offsets from the base mapped address instead of full pointers. The kernel driver and userspace code can both add these offsets to their base pointers, and get to the virtual address that's right for their respective contexts.