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 <asm/system.h>
#include <asm/uaccess.h>
#include "memdev.h"
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;
}
/* IO操作 */
int memdev_ioctl ( struct inode *inode, struct file *filp,
unsigned int cmd, unsigned long arg ) {
int err = 0;
int ret = 0;
int ioarg = 0;
if ( _IOC_TYPE ( cmd ) != MEMDEV_IOC_MAGIC ) {
/* 检测命令的有效性 */
return -EINVAL;
}
if ( _IOC_NR ( cmd ) > MEMDEV_IOC_MAXNR ) {
return -EINVAL;
}
if ( _IOC_DIR ( cmd ) & _IOC_READ ) {
/* 根据命令类型,检测参数空间是否可以访问 */
err = !access_ok ( VERIFY_WRITE, ( void * ) arg, _IOC_SIZE ( cmd ) );
} else if ( _IOC_DIR