Which is the correct way to map in an user space process a buffer allocated with kmalloc? Maybe i didn't understand memory mapping yet...I write a kernel module that allocs this buffer (for example 120 bytes) and i would read and write it in a user-space process. Obviously i created a char device and implemented a mmap method in the file_operations struct. My method is:
static int my_mmap(struct file *filp, struct vm_area_struct *vma)
{
//printk(KERN_INFO "Allocated virtual memory length = %d", vma->vm_end - vma->vm_start);
long unsigned int size = vma->vm_end - vma->vm_start;
if (remap_pfn_range(vma, vma->vm_start,
__pa(mem_area) >> PAGE_SHIFT, //what about vma->vm_pgoff?
size,
vma->vm_page_prot) < 0)
return -EAGAIN;
vma->vm_flags |= VM_LOCKED;
vma->vm_ops = &vmops;
vma->vm_flags |= VM_RESERVED;
my_vm_open(vma);
return 0;
}
where mem_area points at a memory area allocated with kmalloc at module init. The area is filled with the same value (for example 0x10). All works but i think there is something wrong in this code:
kmalloccould return a pointer that isn't page aligned and, in that case, i don't think is correct the value of the third parameter ofremap_pfn_rangein fact in user space i read the wrong value. Instead all works if i use__get_free_page(because the the function always returns a pointer that is page aligned) or whenkmallocreturns a page aligned pointer. Memory mapping works with memory regions that are multple ofPAGE_SIZEso, should i allocate an entire page instead of usingkmalloc?When
my_mmapis called, the kernel has allocated some pages yet? I ask this because i found some implementations of custommmapmethod that callremap_pfn_rangewithvma->vm_pgoffas third parameter...how could be useful this? Is this the page frame of the first new allocated page? If i pass as third parameter a page frame like i do inmy_mmap, i should free pages starting from page invma->vm_pgoff?However i found an implementation of
mmapmethod that maps a buffer allocated withkmalloc. To correctly map the buffer an operation (that i don't undestand for now) is performed beforeremap_pfn_range. Suppose thatmemis the pointer returned bykmalloc,mem_areais initialized in this manner:mem_area=(int *)(((unsigned long)mem + PAGE_SIZE - 1) & PAGE_MASK);
So mem_area contains the same value of mem only if mem is page aligned otherwise is should contain the pointer at the beginning of the next page. However, with this operation if i pass as third param of remap_pfn_range the value __pa(mem_area) >> PAGE_SHIFT mapping works well. Why?
Thank you all!