9

I am trying to understand how mmap works. User level call of mmap looks like below.

void *mmap(void *addr, size_t len, int prot, int flags,
       int fildes, off_t off); 

but kernel level mmap for a particular device driver looks like:

int <device_name>_mmap(struct file*fp, struct vm_area_struct *vma)

I also looked at the source code but I am not able to find the connection in between.

How does mmap for particular device gets its arguments "struct vm_area_struct *vma" ? Can you please help me understand that ? Appreciate your help.

caf
  • 233,326
  • 40
  • 323
  • 462
vindyz
  • 1,079
  • 2
  • 11
  • 23

1 Answers1

18

The mmap() library call is implemented by libc, which converts the offset in bytes to an offset in pages, then calls the mmap_pgoff() system call.

The mmap_pgoff() system call fetches the struct file * corresponding to the file descriptor argument, and calls do_mmap_pgoff().

do_mmap_pgoff() calculates the actual address and length that will be used based on the hint and the available address space, converts the provided flags into VM flags, and tests for permission to perform the mapping. It then calls mmap_region().

mmap_region() removes any prior mappings in the area being replaced by the new mapping, performs memory accounting and creates the new struct vm_area_struct describing the region of the address space being mapped (this encapsulates the address, length, offset and VM flags of the mapping). It then calls the file's ->mmap() implementation, passing the struct file * and struct vm_area_struct *. For device files this will be a call to the device's mmap implementation function.

caf
  • 233,326
  • 40
  • 323
  • 462
  • Its very well explained. where can I find such explanation for other kernel functions. Is there anything I can refer to besides source code. – vindyz Mar 21 '12 at 04:23
  • @vinay: I think you just need to practice reading the source code - it really isn't that hard. [lxr.linux.no](http://lxr.linux.no/) is good for tracing through the source. For syscall entry points, look for `SYSCALL_DEFINE`. – caf Mar 21 '12 at 04:53
  • @caf - So, it is correct to infer that in case of text files saved on the disk , the file's->mmap() implementation is done by the filesystem? For example, ext4 mmap implementation will get called by mmap_region() if a file saved on the disk(formatted with ext4) is mmaped ? – bornfree Feb 09 '16 at 09:15
  • 1
    @bornfree: Yes, for an ordinary file on ext4, `ext4_file_mmap()` is used. – caf Feb 09 '16 at 11:39