linux下的/dev/mem设备认识和使用

来源:互联网 发布:吉林数据造假 编辑:程序博客网 时间:2024/05/20 22:28

最近在为了读取一个寄存器的值动心思时,突然发现,一个好用的工具”r”,源码附上:

#include <fcntl.h>#include <inttypes.h>#include <stdbool.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/mman.h>#if __LP64__#define strtoptr strtoull#else#define strtoptr strtoul#endifstatic int usage(){    fprintf(stderr,"r [-b|-s] <address> [<value>]\n");    return -1;}int r_main(int argc, char *argv[]){    if(argc < 2) return usage();    int width = 4;    if(!strcmp(argv[1], "-b")) {        width = 1;        argc--;        argv++;    } else if(!strcmp(argv[1], "-s")) {        width = 2;        argc--;        argv++;    }    if(argc < 2) return usage();    uintptr_t addr = strtoptr(argv[1], 0, 16);    uintptr_t endaddr = 0;    char* end = strchr(argv[1], '-');    if (end)        endaddr = strtoptr(end + 1, 0, 16);    if (!endaddr)        endaddr = addr + width - 1;    if (endaddr <= addr) {        fprintf(stderr, "end address <= start address\n");        return -1;    }    bool set = false;    uint32_t value = 0;    if(argc > 2) {        set = true;        value = strtoul(argv[2], 0, 16);    }    int fd = open("/dev/mem", O_RDWR | O_SYNC);    if(fd < 0) {        fprintf(stderr,"cannot open /dev/mem\n");        return -1;    }    off64_t mmap_start = addr & ~(PAGE_SIZE - 1);    size_t mmap_size = endaddr - mmap_start + 1;    mmap_size = (mmap_size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);    void* page = mmap64(0, mmap_size, PROT_READ | PROT_WRITE,                        MAP_SHARED, fd, mmap_start);    if(page == MAP_FAILED){        fprintf(stderr,"cannot mmap region\n");        return -1;    }    while (addr <= endaddr) {        switch(width){        case 4: {            uint32_t* x = (uint32_t*) (((uintptr_t) page) + (addr & 4095));            if(set) *x = value;            fprintf(stderr,"%08"PRIxPTR": %08x\n", addr, *x);            break;        }        case 2: {            uint16_t* x = (uint16_t*) (((uintptr_t) page) + (addr & 4095));            if(set) *x = value;            fprintf(stderr,"%08"PRIxPTR": %04x\n", addr, *x);            break;        }        case 1: {            uint8_t* x = (uint8_t*) (((uintptr_t) page) + (addr & 4095));            if(set) *x = value;            fprintf(stderr,"%08"PRIxPTR": %02x\n", addr, *x);            break;        }        }        addr += width;    }    return 0;}
  • 1

简单好用不是!
秉承研究一下的思想,看了一下/dev/mem和mmap读写linux内存的通用C代码及原理。
附上一个mem这个字符驱动的源码:

/* *  linux/drivers/char/mem.c * *  Copyright (C) 1991, 1992  Linus Torvalds * *  Added devfs support. *    Jan-11-1998, C. Scott Ananian <cananian@alumni.princeton.edu> *  Shared /dev/zero mmapping support, Feb 2000, Kanoj Sarcar <kanoj@sgi.com> */#include <linux/mm.h>#include <linux/miscdevice.h>#include <linux/slab.h>#include <linux/vmalloc.h>#include <linux/mman.h>#include <linux/random.h>#include <linux/init.h>#include <linux/raw.h>#include <linux/tty.h>#include <linux/capability.h>#include <linux/ptrace.h>#include <linux/device.h>#include <linux/highmem.h>#include <linux/crash_dump.h>#include <linux/backing-dev.h>#include <linux/bootmem.h>#include <linux/splice.h>#include <linux/pfn.h>#include <linux/export.h>#include <asm/uaccess.h>#include <asm/io.h>#ifdef CONFIG_IA64# include <linux/efi.h>#endifstatic inline unsigned long size_inside_page(unsigned long start,                         unsigned long size){    unsigned long sz;    sz = PAGE_SIZE - (start & (PAGE_SIZE - 1));    return min(sz, size);}#ifndef ARCH_HAS_VALID_PHYS_ADDR_RANGEstatic inline int valid_phys_addr_range(unsigned long addr, size_t count){    return addr + count <= __pa(high_memory);}static inline int valid_mmap_phys_addr_range(unsigned long pfn, size_t size){    return 1;}#endif#if defined(CONFIG_DEVMEM) || defined(CONFIG_DEVKMEM)#ifdef CONFIG_STRICT_DEVMEMstatic inline int range_is_allowed(unsigned long pfn, unsigned long size){    u64 from = ((u64)pfn) << PAGE_SHIFT;    u64 to = from + size;    u64 cursor = from;    while (cursor < to) {        if (!devmem_is_allowed(pfn)) {            printk(KERN_INFO        "Program %s tried to access /dev/mem between %Lx->%Lx.\n",                current->comm, from, to);            return 0;        }        cursor += PAGE_SIZE;        pfn++;    }    return 1;}#elsestatic inline int range_is_allowed(unsigned long pfn, unsigned long size){    return 1;}#endif#endif#ifdef CONFIG_DEVMEMvoid __weak unxlate_dev_mem_ptr(unsigned long phys, void *addr){}/* * This funcion reads the *physical* memory. The f_pos points directly to the * memory location. */static ssize_t read_mem(struct file *file, char __user *buf,            size_t count, loff_t *ppos){    unsigned long p = *ppos;    ssize_t read, sz;    char *ptr;    if (!valid_phys_addr_range(p, count))        return -EFAULT;    read = 0;#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED    /* we don't have page 0 mapped on sparc and m68k.. */    if (p < PAGE_SIZE) {        sz = size_inside_page(p, count);        if (sz > 0) {            if (clear_user(buf, sz))                return -EFAULT;            buf += sz;            p += sz;            count -= sz;            read += sz;        }    }#endif    while (count > 0) {        unsigned long remaining;        sz = size_inside_page(p, count);        if (!range_is_allowed(p >> PAGE_SHIFT, count))            return -EPERM;        /*         * On ia64 if a page has been mapped somewhere as uncached, then         * it must also be accessed uncached by the kernel or data         * corruption may occur.         */        ptr = xlate_dev_mem_ptr(p);        if (!ptr)            return -EFAULT;        remaining = copy_to_user(buf, ptr, sz);        unxlate_dev_mem_ptr(p, ptr);        if (remaining)            return -EFAULT;        buf += sz;        p += sz;        count -= sz;        read += sz;    }    *ppos += read;    return read;}static ssize_t write_mem(struct file *file, const char __user *buf,             size_t count, loff_t *ppos){    unsigned long p = *ppos;    ssize_t written, sz;    unsigned long copied;    void *ptr;    if (!valid_phys_addr_range(p, count))        return -EFAULT;    written = 0;#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED    /* we don't have page 0 mapped on sparc and m68k.. */    if (p < PAGE_SIZE) {        sz = size_inside_page(p, count);        /* Hmm. Do something? */        buf += sz;        p += sz;        count -= sz;        written += sz;    }#endif    while (count > 0) {        sz = size_inside_page(p, count);        if (!range_is_allowed(p >> PAGE_SHIFT, sz))            return -EPERM;        /*         * On ia64 if a page has been mapped somewhere as uncached, then         * it must also be accessed uncached by the kernel or data         * corruption may occur.         */        ptr = xlate_dev_mem_ptr(p);        if (!ptr) {            if (written)                break;            return -EFAULT;        }        copied = copy_from_user(ptr, buf, sz);        unxlate_dev_mem_ptr(p, ptr);        if (copied) {            written += sz - copied;            if (written)                break;            return -EFAULT;        }        buf += sz;        p += sz;        count -= sz;        written += sz;    }    *ppos += written;    return written;}#endif  /* CONFIG_DEVMEM */#if defined(CONFIG_DEVMEM) || defined(CONFIG_DEVKMEM)int __weak phys_mem_access_prot_allowed(struct file *file,    unsigned long pfn, unsigned long size, pgprot_t *vma_prot){    return 1;}#ifndef __HAVE_PHYS_MEM_ACCESS_PROT/* * Architectures vary in how they handle caching for addresses * outside of main memory. * */#ifdef pgprot_noncachedstatic int uncached_access(struct file *file, unsigned long addr){#if defined(CONFIG_IA64)    /*     * On ia64, we ignore O_DSYNC because we cannot tolerate memory     * attribute aliases.     */    return !(efi_mem_attributes(addr) & EFI_MEMORY_WB);#elif defined(CONFIG_MIPS)    {        extern int __uncached_access(struct file *file,                         unsigned long addr);        return __uncached_access(file, addr);    }#else    /*     * Accessing memory above the top the kernel knows about or through a     * file pointer     * that was marked O_DSYNC will be done non-cached.     */    if (file->f_flags & O_DSYNC)        return 1;    return addr >= __pa(high_memory);#endif}#endifstatic pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,                     unsigned long size, pgprot_t vma_prot){#ifdef pgprot_noncached    unsigned long offset = pfn << PAGE_SHIFT;    if (uncached_access(file, offset))        return pgprot_noncached(vma_prot);#endif    return vma_prot;}#endif#ifndef CONFIG_MMUstatic unsigned long get_unmapped_area_mem(struct file *file,                       unsigned long addr,                       unsigned long len,                       unsigned long pgoff,                       unsigned long flags){    if (!valid_mmap_phys_addr_range(pgoff, len))        return (unsigned long) -EINVAL;    return pgoff << PAGE_SHIFT;}/* can't do an in-place private mapping if there's no MMU */static inline int private_mapping_ok(struct vm_area_struct *vma){    return vma->vm_flags & VM_MAYSHARE;}#else#define get_unmapped_area_mem   NULLstatic inline int private_mapping_ok(struct vm_area_struct *vma){    return 1;}#endifstatic const struct vm_operations_struct mmap_mem_ops = {#ifdef CONFIG_HAVE_IOREMAP_PROT    .access = generic_access_phys#endif};static int mmap_mem(struct file *file, struct vm_area_struct *vma){    size_t size = vma->vm_end - vma->vm_start;    if (!valid_mmap_phys_addr_range(vma->vm_pgoff, size))        return -EINVAL;    if (!private_mapping_ok(vma))        return -ENOSYS;    if (!range_is_allowed(vma->vm_pgoff, size))        return -EPERM;    if (!phys_mem_access_prot_allowed(file, vma->vm_pgoff, size,                        &vma->vm_page_prot))        return -EINVAL;    vma->vm_page_prot = phys_mem_access_prot(file, vma->vm_pgoff,                         size,                         vma->vm_page_prot);    vma->vm_ops = &mmap_mem_ops;    /* Remap-pfn-range will mark the range VM_IO and VM_RESERVED */    if (remap_pfn_range(vma,                vma->vm_start,                vma->vm_pgoff,                size,                vma->vm_page_prot)) {        return -EAGAIN;    }    return 0;}#endif  /* CONFIG_DEVMEM */#ifdef CONFIG_DEVKMEMstatic int mmap_kmem(struct file *file, struct vm_area_struct *vma){    unsigned long pfn;    /* Turn a kernel-virtual address into a physical page frame */    pfn = __pa((u64)vma->vm_pgoff << PAGE_SHIFT) >> PAGE_SHIFT;    /*     * RED-PEN: on some architectures there is more mapped memory than     * available in mem_map which pfn_valid checks for. Perhaps should add a     * new macro here.     *     * RED-PEN: vmalloc is not supported right now.     */    if (!pfn_valid(pfn))        return -EIO;    vma->vm_pgoff = pfn;    return mmap_mem(file, vma);}#endif#ifdef CONFIG_CRASH_DUMP/* * Read memory corresponding to the old kernel. */static ssize_t read_oldmem(struct file *file, char __user *buf,                size_t count, loff_t *ppos){    unsigned long pfn, offset;    size_t read = 0, csize;    int rc = 0;    while (count) {        pfn = *ppos / PAGE_SIZE;        if (pfn > saved_max_pfn)            return read;        offset = (unsigned long)(*ppos % PAGE_SIZE);        if (count > PAGE_SIZE - offset)            csize = PAGE_SIZE - offset;        else            csize = count;        rc = copy_oldmem_page(pfn, buf, csize, offset, 1);        if (rc < 0)            return rc;        buf += csize;        *ppos += csize;        read += csize;        count -= csize;    }    return read;}#endif#ifdef CONFIG_DEVKMEM/* * This function reads the *virtual* memory as seen by the kernel. */static ssize_t read_kmem(struct file *file, char __user *buf,             size_t count, loff_t *ppos){    unsigned long p = *ppos;    ssize_t low_count, read, sz;    char * kbuf; /* k-addr because vread() takes vmlist_lock rwlock */    int err = 0;    read = 0;    if (p < (unsigned long) high_memory) {        low_count = count;        if (count > (unsigned long)high_memory - p)            low_count = (unsigned long)high_memory - p;#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED        /* we don't have page 0 mapped on sparc and m68k.. */        if (p < PAGE_SIZE && low_count > 0) {            sz = size_inside_page(p, low_count);            if (clear_user(buf, sz))                return -EFAULT;            buf += sz;            p += sz;            read += sz;            low_count -= sz;            count -= sz;        }#endif        while (low_count > 0) {            sz = size_inside_page(p, low_count);            /*             * On ia64 if a page has been mapped somewhere as             * uncached, then it must also be accessed uncached             * by the kernel or data corruption may occur             */            kbuf = xlate_dev_kmem_ptr((char *)p);            if (copy_to_user(buf, kbuf, sz))                return -EFAULT;            buf += sz;            p += sz;            read += sz;            low_count -= sz;            count -= sz;        }    }    if (count > 0) {        kbuf = (char *)__get_free_page(GFP_KERNEL);        if (!kbuf)            return -ENOMEM;        while (count > 0) {            sz = size_inside_page(p, count);            if (!is_vmalloc_or_module_addr((void *)p)) {                err = -ENXIO;                break;            }            sz = vread(kbuf, (char *)p, sz);            if (!sz)                break;            if (copy_to_user(buf, kbuf, sz)) {                err = -EFAULT;                break;            }            count -= sz;            buf += sz;            read += sz;            p += sz;        }        free_page((unsigned long)kbuf);    }    *ppos = p;    return read ? read : err;}static ssize_t do_write_kmem(unsigned long p, const char __user *buf,                size_t count, loff_t *ppos){    ssize_t written, sz;    unsigned long copied;    written = 0;#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED    /* we don't have page 0 mapped on sparc and m68k.. */    if (p < PAGE_SIZE) {        sz = size_inside_page(p, count);        /* Hmm. Do something? */        buf += sz;        p += sz;        count -= sz;        written += sz;    }#endif    while (count > 0) {        char *ptr;        sz = size_inside_page(p, count);        /*         * On ia64 if a page has been mapped somewhere as uncached, then         * it must also be accessed uncached by the kernel or data         * corruption may occur.         */        ptr = xlate_dev_kmem_ptr((char *)p);        copied = copy_from_user(ptr, buf, sz);        if (copied) {            written += sz - copied;            if (written)                break;            return -EFAULT;        }        buf += sz;        p += sz;        count -= sz;        written += sz;    }    *ppos += written;    return written;}/* * This function writes to the *virtual* memory as seen by the kernel. */static ssize_t write_kmem(struct file *file, const char __user *buf,              size_t count, loff_t *ppos){    unsigned long p = *ppos;    ssize_t wrote = 0;    ssize_t virtr = 0;    char * kbuf; /* k-addr because vwrite() takes vmlist_lock rwlock */    int err = 0;    if (p < (unsigned long) high_memory) {        unsigned long to_write = min_t(unsigned long, count,                           (unsigned long)high_memory - p);        wrote = do_write_kmem(p, buf, to_write, ppos);        if (wrote != to_write)            return wrote;        p += wrote;        buf += wrote;        count -= wrote;    }    if (count > 0) {        kbuf = (char *)__get_free_page(GFP_KERNEL);        if (!kbuf)            return wrote ? wrote : -ENOMEM;        while (count > 0) {            unsigned long sz = size_inside_page(p, count);            unsigned long n;            if (!is_vmalloc_or_module_addr((void *)p)) {                err = -ENXIO;                break;            }            n = copy_from_user(kbuf, buf, sz);            if (n) {                err = -EFAULT;                break;            }            vwrite(kbuf, (char *)p, sz);            count -= sz;            buf += sz;            virtr += sz;            p += sz;        }        free_page((unsigned long)kbuf);    }    *ppos = p;    return virtr + wrote ? : err;}#endif#ifdef CONFIG_DEVPORTstatic ssize_t read_port(struct file *file, char __user *buf,             size_t count, loff_t *ppos){    unsigned long i = *ppos;    char __user *tmp = buf;    if (!access_ok(VERIFY_WRITE, buf, count))        return -EFAULT;    while (count-- > 0 && i < 65536) {        if (__put_user(inb(i), tmp) < 0)            return -EFAULT;        i++;        tmp++;    }    *ppos = i;    return tmp-buf;}static ssize_t write_port(struct file *file, const char __user *buf,              size_t count, loff_t *ppos){    unsigned long i = *ppos;    const char __user * tmp = buf;    if (!access_ok(VERIFY_READ, buf, count))        return -EFAULT;    while (count-- > 0 && i < 65536) {        char c;        if (__get_user(c, tmp)) {            if (tmp > buf)                break;            return -EFAULT;        }        outb(c, i);        i++;        tmp++;    }    *ppos = i;    return tmp-buf;}#endifstatic ssize_t read_null(struct file *file, char __user *buf,             size_t count, loff_t *ppos){    return 0;}static ssize_t write_null(struct file *file, const char __user *buf,              size_t count, loff_t *ppos){    return count;}static int pipe_to_null(struct pipe_inode_info *info, struct pipe_buffer *buf,            struct splice_desc *sd){    return sd->len;}static ssize_t splice_write_null(struct pipe_inode_info *pipe, struct file *out,                 loff_t *ppos, size_t len, unsigned int flags){    return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_null);}static ssize_t read_zero(struct file *file, char __user *buf,             size_t count, loff_t *ppos){    size_t written;    if (!count)        return 0;    if (!access_ok(VERIFY_WRITE, buf, count))        return -EFAULT;    written = 0;    while (count) {        unsigned long unwritten;        size_t chunk = count;        if (chunk > PAGE_SIZE)            chunk = PAGE_SIZE;  /* Just for latency reasons */        unwritten = __clear_user(buf, chunk);        written += chunk - unwritten;        if (unwritten)            break;        if (signal_pending(current))            return written ? written : -ERESTARTSYS;        buf += chunk;        count -= chunk;        cond_resched();    }    return written ? written : -EFAULT;}static int mmap_zero(struct file *file, struct vm_area_struct *vma){#ifndef CONFIG_MMU    return -ENOSYS;#endif    if (vma->vm_flags & VM_SHARED)        return shmem_zero_setup(vma);    return 0;}static ssize_t write_full(struct file *file, const char __user *buf,              size_t count, loff_t *ppos){    return -ENOSPC;}/* * Special lseek() function for /dev/null and /dev/zero.  Most notably, you * can fopen() both devices with "a" now.  This was previously impossible. * -- SRB. */static loff_t null_lseek(struct file *file, loff_t offset, int orig){    return file->f_pos = 0;}#if defined(CONFIG_DEVMEM) || defined(CONFIG_DEVKMEM) || defined(CONFIG_DEVPORT)/* * The memory devices use the full 32/64 bits of the offset, and so we cannot * check against negative addresses: they are ok. The return value is weird, * though, in that case (0). * * also note that seeking relative to the "end of file" isn't supported: * it has no meaning, so it returns -EINVAL. */static loff_t memory_lseek(struct file *file, loff_t offset, int orig){    loff_t ret;    mutex_lock(&file->f_path.dentry->d_inode->i_mutex);    switch (orig) {    case SEEK_CUR:        offset += file->f_pos;    case SEEK_SET:        /* to avoid userland mistaking f_pos=-9 as -EBADF=-9 */        if ((unsigned long long)offset >= ~0xFFFULL) {            ret = -EOVERFLOW;            break;        }        file->f_pos = offset;        ret = file->f_pos;        force_successful_syscall_return();        break;    default:        ret = -EINVAL;    }    mutex_unlock(&file->f_path.dentry->d_inode->i_mutex);    return ret;}#endif#if defined(CONFIG_DEVMEM) || defined(CONFIG_DEVKMEM) || defined(CONFIG_DEVPORT)static int open_port(struct inode * inode, struct file * filp){    return capable(CAP_SYS_RAWIO) ? 0 : -EPERM;}#endif#define zero_lseek  null_lseek#define full_lseek      null_lseek#define write_zero  write_null#define read_full       read_zero#define open_mem    open_port#define open_kmem   open_mem#define open_oldmem open_mem#ifdef CONFIG_DEVMEMstatic const struct file_operations mem_fops = {    .llseek     = memory_lseek,    .read       = read_mem,    .write      = write_mem,    .mmap       = mmap_mem,    .open       = open_mem,    .get_unmapped_area = get_unmapped_area_mem,};#endif#ifdef CONFIG_DEVKMEMstatic const struct file_operations kmem_fops = {    .llseek     = memory_lseek,    .read       = read_kmem,    .write      = write_kmem,    .mmap       = mmap_kmem,    .open       = open_kmem,    .get_unmapped_area = get_unmapped_area_mem,};#endifstatic const struct file_operations null_fops = {    .llseek     = null_lseek,    .read       = read_null,    .write      = write_null,    .splice_write   = splice_write_null,};#ifdef CONFIG_DEVPORTstatic const struct file_operations port_fops = {    .llseek     = memory_lseek,    .read       = read_port,    .write      = write_port,    .open       = open_port,};#endifstatic const struct file_operations zero_fops = {    .llseek     = zero_lseek,    .read       = read_zero,    .write      = write_zero,    .mmap       = mmap_zero,};/* * capabilities for /dev/zero * - permits private mappings, "copies" are taken of the source of zeros * - no writeback happens */static struct backing_dev_info zero_bdi = {    .name       = "char/mem",    .capabilities   = BDI_CAP_MAP_COPY | BDI_CAP_NO_ACCT_AND_WRITEBACK,};static const struct file_operations full_fops = {    .llseek     = full_lseek,    .read       = read_full,    .write      = write_full,};#ifdef CONFIG_CRASH_DUMPstatic const struct file_operations oldmem_fops = {    .read   = read_oldmem,    .open   = open_oldmem,    .llseek = default_llseek,};#endifstatic ssize_t kmsg_writev(struct kiocb *iocb, const struct iovec *iv,               unsigned long count, loff_t pos){    char *line, *p;    int i;    ssize_t ret = -EFAULT;    size_t len = iov_length(iv, count);    line = kmalloc(len + 1, GFP_KERNEL);    if (line == NULL)        return -ENOMEM;    /*     * copy all vectors into a single string, to ensure we do     * not interleave our log line with other printk calls     */    p = line;    for (i = 0; i < count; i++) {        if (copy_from_user(p, iv[i].iov_base, iv[i].iov_len))            goto out;        p += iv[i].iov_len;    }    p[0] = '\0';    ret = printk("%s", line);    /* printk can add a prefix */    if (ret > len)        ret = len;out:    kfree(line);    return ret;}static const struct file_operations kmsg_fops = {    .aio_write = kmsg_writev,    .llseek = noop_llseek,};static const struct memdev {    const char *name;    umode_t mode;    const struct file_operations *fops;    struct backing_dev_info *dev_info;} devlist[] = {#ifdef CONFIG_DEVMEM     [1] = { "mem", 0, &mem_fops, &directly_mappable_cdev_bdi },#endif#ifdef CONFIG_DEVKMEM     [2] = { "kmem", 0, &kmem_fops, &directly_mappable_cdev_bdi },#endif     [3] = { "null", 0666, &null_fops, NULL },#ifdef CONFIG_DEVPORT     [4] = { "port", 0, &port_fops, NULL },#endif     [5] = { "zero", 0666, &zero_fops, &zero_bdi },     [7] = { "full", 0666, &full_fops, NULL },     [8] = { "random", 0666, &random_fops, NULL },     [9] = { "urandom", 0666, &urandom_fops, NULL },    [11] = { "kmsg", 0, &kmsg_fops, NULL },#ifdef CONFIG_CRASH_DUMP    [12] = { "oldmem", 0, &oldmem_fops, NULL },#endif};static int memory_open(struct inode *inode, struct file *filp){    int minor;    const struct memdev *dev;    minor = iminor(inode);    if (minor >= ARRAY_SIZE(devlist))        return -ENXIO;    dev = &devlist[minor];    if (!dev->fops)        return -ENXIO;    filp->f_op = dev->fops;    if (dev->dev_info)        filp->f_mapping->backing_dev_info = dev->dev_info;    /* Is /dev/mem or /dev/kmem ? */    if (dev->dev_info == &directly_mappable_cdev_bdi)        filp->f_mode |= FMODE_UNSIGNED_OFFSET;    if (dev->fops->open)        return dev->fops->open(inode, filp);    return 0;}static const struct file_operations memory_fops = {    .open = memory_open,    .llseek = noop_llseek,};static char *mem_devnode(struct device *dev, umode_t *mode){    if (mode && devlist[MINOR(dev->devt)].mode)        *mode = devlist[MINOR(dev->devt)].mode;    return NULL;}static struct class *mem_class;static int __init chr_dev_init(void){    int minor;    int err;    err = bdi_init(&zero_bdi);    if (err)        return err;    if (register_chrdev(MEM_MAJOR, "mem", &memory_fops))        printk("unable to get major %d for memory devs\n", MEM_MAJOR);    mem_class = class_create(THIS_MODULE, "mem");    if (IS_ERR(mem_class))        return PTR_ERR(mem_class);    mem_class->devnode = mem_devnode;    for (minor = 1; minor < ARRAY_SIZE(devlist); minor++) {        if (!devlist[minor].name)            continue;        device_create(mem_class, NULL, MKDEV(MEM_MAJOR, minor),                  NULL, devlist[minor].name);    }    return tty_init();}fs_initcall(chr_dev_init);
  • 1

利用/dev/mem和mmap导出系统物理地址,免去了用户虚拟地址到内核逻辑地址的繁琐拷贝,提升效率。
注意:如果地址不是一个有效物理地址(处理器地址空间分布中该地址没用),mmap建立该物理地址与用户空间虚拟地址的映射,填TLB,CPU经过TLB翻译后去访问该不存在的物理地址访问就有可能导致CPU挂掉。
内核中定义了4个变量来表示内核一些基本的物理地址和虚拟地址,如下:
KERNELBASE 内核的起始虚拟地址,
PAGE_OFFSET 低端内存的起始虚拟地址,一般是0xc0000000
PHYSICAL_START 内核的起始物理地址,
MEMORY_START 低端内存的起始物理地址,

内核在启动过程中对于lowmem的静态映射,就是以上述的物理地址和虚拟地址的差值进行线性映射的。
所以__pa __va转换的是线性映射的内存部分,也就是lowmem。
所以kmem映射的是lowmem,如果cmdline参数中mem=512M,这就意味着通过kmem的mmap最多可以访问内核地址空间开始的512M内存。
对于超过lowmem范围,访问highmem,如果使用__pa访问,由于highmem是动态映射的,其映射关系不是线性的那么简单了,根据__pa获取的物理地址与我们想要的内核虚拟地址是不对应的。
一个简单GPIO的应用层驱动:

int main(int argc, char *argv[]){    int mfd;    unsigned int val=0, last_val;    void *base;    char *sys_pinstaterd;    time_t t_now, t_old;    int flag_issued = 0;#if 0    // uncomment these to make the program a daemon.    pid_t pid;        int i;        if ( (pid=fork())<0)                return -1;        else if (pid!=0)                exit(0);        setsid();        chdir("/");        umask(0);        for (i=0;i<256;i++)                close(i);#endif    // open the memery mapped file.    mfd=open("/dev/mem", O_RDWR);    if (mfd < 0){        printf("Cannot open /dev/mem.\n");        exit(-1);    }    // Initialize the map    base = mmap( NULL, 0x130,  PROT_READ | PROT_WRITE, MAP_SHARED, mfd, 0x1fe00000);    if ( base < 0){        exit(-1);    }    sys_pinstaterd = base + 0x011c;    // init the temperay variables    t_now=t_old=time(NULL);    last_val = 0;    while(1)    {        val = *( (volatile unsigned int*)sys_pinstaterd );        val = (val&0x4) ? 1:0;        printf("\tgpio 7 stat=%x.\n", val);        if (val){            // the button is pressed down !!            if ( last_val==0 ){                // starting time of press, log the time                t_old = time(NULL);                last_val=1;                printf("Button Down\n");            }else {                // already pressed down! let's count the time!                t_now = time(NULL);                if (t_now-t_old>=TIME_OUT && flag_issued==0){                    // Pressed LONG ENOUGH, issue the handler script!!                    flag_issued = 1;                    longtu_timeout();                }            }        }else{            // No button pressed.            if (flag_issued){                flag_issued = 0;                printf("Button UP.\n");            }        }        last_val = val;        usleep(100);    }    munmap(base, 0x000);    close(mfd);       return 0;}
  • 1

写在应用层的物理地址操作。快速开发的一个方法。


转自:http://blog.csdn.net/lsn946803746/article/details/52948036

阅读全文
0 0