linux驱动:[2]字符设备驱动memdev
Linux 内存模拟字符设备 驱动程序
测试平台: Xunlong Orange Pi Zero
代码一览(解析见下方)
驱动程序以及Makefile如下:
- memdev.c:
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#ifndef MEMDEV_MAJOR
#define MEMDEV_MAJOR 254
#endif
#ifndef MEMDEV_NR_DEVS
#define MEMDEV_NR_DEVS 2
#endif
#ifndef MEMDEV_SIZE
#define MEMDEV_SIZE 4096
#endif
struct mem_dev {
char *data;
unsigned long size;
};
static int mem_major = MEMDEV_MAJOR;
module_param(mem_major, int, S_IRUGO);
struct mem_dev *mem_devp;
struct cdev cdev;
int mem_open(struct inode *inode, struct file *filp)
{
struct mem_dev *dev;
int num = MINOR(inode->i_rdev);
if (num >= MEMDEV_NR_DEVS)
return -ENODEV;
dev = &mem_devp[num];
filp->private_data = dev;
return 0;
}
int mem_release(struct inode *inode, struct file *filp)
{
return 0;
}
static ssize_t mem_read(struct file *filp, char __user *buf, size_t size, loff_t *poss)
{
unsigned long p = *poss;
unsigned int count = size;
int ret = 0;
struct mem_dev *dev = filp->private_data;
if (p >= MEMDEV_SIZE)
return 0;
if (count > MEMDEV_SIZE-p)
count = MEMDEV_SIZE-p;