Hanna Khalil
Hanna Khalil

Reputation: 1055

Virtual to Kernel logical address

I have a char driver in which one of the interface functions I added is alloc_contig(int order) where order is log2 of desired number of 4K pages. This function allocates contiguous physical memory and maps it for userspace usage using remap_pfn_range function. I'm trying to write function which frees this memory dealloc_contig(va) now in Kernel I have the virtual address given by user to free and I need to obtain the underlying physical address, so I tried to use virt_to_phys but it is not giving me the desired address. Log:

//allocating
page address is ffff880868764000 //allocated using alloc_pages
//deallocating
virtual address from user 7f4c7e095000
when converted to PA using virt_to_phys got f74c7e095000 instead of ffff880868764000 

Can you please help me?

Upvotes: 2

Views: 613

Answers (1)

Lin
Lin

Reputation: 104

Quick answer: You have to use do_munmap() to unmap the pages from the user process.
virt_to_phys() can't do this job. It is used by the kernel to translate kernel virtual address(not user virtual address) to physical address.

User space memories are organized by vma regions.(struct vm_area_struct *vma). They can be found under struct mm_struct on per process basis. Processes have their own mm_structs so that the same virtual address for different processes mapped to different physcial addresses.

What you need to do is, get the virtual address. Then,in kernel space, you need to find out which vma this address belongs to, then unmap the address range from the vma and reclaim the pages.(This is what do_munmap() do.).

Another point worth mentioned is,because processes have their own mm_struct, thus their own vma regions. do_munmap() have to be called under the "correct" user process conext, or it will get the wrong mm_struct.

Sum up the steps:
1.User process which have mapped the region call your interface to release the virtual address. 2.System call to kernel space(This is under your user process' context). Your driver handler call do_munmap() to unmap the virtual address.
3.Your driver free the pages.

Hope this helps!

Upvotes: 2

Related Questions