← Back to Index

mmap kernel层函数原型

static int mmap(struct file *file, struct vm_area_struct *vma)

mmap用户层函数原型

mmap (caddr_t addr, size_t len, int prot, int flags, int fd, off_t offset)
@addr:指定被映射后的起始地址(进程虚拟地址)
@len:映射大小(必须为PAGE_SIZE)
@prot:可读,可写标识
@flags:标识位
@fd:文件描述符
@offset:被映射文件偏移

测试代码

kernel层测试代码框架请参考ldd3,simple模块的实现,

unsigned char *test_buf;

static int simple_remap_mmap(struct file *filp, struct vm_area_struct *vma)
{
        printk(KERN_NOTICE "mmap \r\n");
//     if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
//                       vma->vm_end - vma->vm_start,
//                       vma->vm_page_prot))
//            return -EAGAIN;
test_buf = kmalloc(4096, GFP_KERNEL);
test_buf[0] = 0x11;
test_buf[1] = 0x22;
test_buf[2] = 0x22;
test_buf[3] = 0x33;
       if (remap_pfn_range(vma, vma->vm_start, virt_to_phys(test_buf)>>PAGE_SHIFT,
                         vma->vm_end - vma->vm_start,
                         vma->vm_page_prot))
              return -EAGAIN;
       vma->vm_ops = &simple_remap_vm_ops;
       simple_vma_open(vma);
       return 0;
}

应用程序代码

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/mman.h>
int main()
{
    int fd;
    unsigned char val1, val2;
    unsigned char *addr;
    fd = open("/dev/simpler", O_RDONLY);
    printf("fd %d\r\n", fd);
    addr = mmap(NULL, 10, PROT_READ, MAP_SHARED, fd, 0);
    printf("mmap address 0x%lx\r\n", (unsigned long)addr);
    val1=*addr;
    val2=*(addr+1);
    printf("0x%x, 0x%x\r\n", val1, val2);
    munmap(addr, 10);
    close(fd);
    return 0;
}