Linux设备驱动学习(1) 全局内存空间“设备”驱动程序globalmem

此“设备”是一个在内存中恒久的空间,在模块初始化时便已分配。

使用modinfo查看编译出来的模块信息

$modinfo ./globalmem.ko

将自定义的主设备号作为参数插入到模块中,使用

$sudo insmod ./globalmem.ko globalmem_major=xxx

来分配。


/*======================================================================
    A globalmem driver as an example of char device drivers  
   
    The initial developer of the original code is Baohua Song
    <[email protected]>. All Rights Reserved.
======================================================================*/
#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 <linux/slab.h>


#define GLOBALMEM_SIZE	0x1000	/*全局内存最大4K字节*/
#define MEM_CLEAR 0x1  /*清0全局内存*/
#define GLOBALMEM_MAJOR 200    /*预设的globalmem的主设备号*/


static int globalmem_major = GLOBALMEM_MAJOR;
/*globalmem设备结构体*/
struct globalmem_dev                                     
{                                                        
  struct cdev cdev; /*cdev结构体*/                       
  unsigned char mem[GLOBALMEM_SIZE]; /*全局内存*/        
};


struct globalmem_dev *globalmem_devp; /*设备结构体指针*/
/*文件打开函数*/
int globalmem_open(struct inode *inode, struct file *filp)
{
  /*将设备结构体指针赋值给文件私有数据指针*/
  filp->private_data = globalmem_devp;
  return 0;
}
/*文件释放函数*/
int globalmem_release(struct inode *inode, struct file *filp)
{
  return 0;
}


/* ioctl设备控制函数 */
static int globalmem_ioctl(struct inode *inodep, struct file *filp, unsigned
  int cmd, unsigned long arg)
{
  struct globalmem_dev *dev = filp->private_data;/*获得设备结构体指针*/


  switch (cmd)
  {
    case MEM_CLEAR:
      memset(dev->mem, 0, GLOBALMEM_SIZE);      
      printk(KERN_INFO "globalmem is set to zero\n");
      break;


    default:
      return  - EINVAL;
  }
  return 0;
}


/*读函数*/
static ssize_t globalmem_read(struct file *filp, char __user *buf, size_t size,
  loff_t *ppos)
{
  unsigned long p =  *ppos;             //这里的p是*ppos的一份拷贝,表示已经读取了的字节数目
  unsigned int count = size;		//需要读取的字节数
  int ret = 0;
  struct globalmem_dev *dev = filp->private_data; /*获得设备结构体指针*/


  /*分析和获取有效的写长度*/
  if (p >= GLOBALMEM_SIZE)
    return count ?  - ENXIO: 0;
  if (count > GLOBALMEM_SIZE - p)//GLOBALMEM_SIZE - p 表示还剩下的可读字节数
    count = GLOBALMEM_SIZE - p;


  /*内核空间->用户空间*/
  if (copy_to_user(buf, (void*)(dev->mem + p), count))
  {
    ret =  - EFAULT;
  }
  else                                //假设分配了0x1~0x9共9个字节的空间,读之前p=5表示已读了5个字节,count=5表示需要读6个字节,在函数中count被置9-5=4,因为只能读剩下的4个字节。
  {                                   //读完之后,*ppos = 5 + 4 ,下次再读就返回0了。写和读类似。。。
    *ppos += count;
    ret = count;
    
    printk(KERN_INFO "read %d bytes(s) from %d\n", count, p);
  }


  return ret;
}


/*写函数*/
static ssize_t globalmem_write(struct file *filp, const char __user *buf,
  size_t size, loff_t *ppos)
{
  unsigned long p =  *ppos;
  unsigned int count = size;
  int ret = 0;
  struct globalmem_dev *dev = filp->private_data; /*获得设备结构体指针*/
  
  /*分析和获取有效的写长度*/
  if (p >= GLOBALMEM_SIZE)
    return count ?  - ENXIO: 0;
  if (count > GLOBALMEM_SIZE - p)
    count = GLOBALMEM_SIZE - p;
    
  /*用户空间->内核空间*/
  if (copy_from_user(dev->mem + p, buf, count))
    ret =  - EFAULT;
  else
  {
    *ppos += count;
    ret = count;
    
    printk(KERN_INFO "written %d bytes(s) from %d\n", count, p);
  }


  return ret;
}


/* seek文件定位函数 */
static loff_t globalmem_llseek(struct file *filp, loff_t offset, int orig)
{
  loff_t ret = 0;
  switch (orig)
  {
    case 0:   /*相对文件开始位置偏移*/
      if (offset < 0)
      {
        ret =  - EINVAL;
        break;
      }
      if ((unsigned int)offset > GLOBALMEM_SIZE)
      {
        ret =  - EINVAL;
        break;
      }
      filp->f_pos = (unsigned int)offset;
      ret = filp->f_pos;
      break;
    case 1:   /*相对文件当前位置偏移*/
      if ((filp->f_pos + offset) > GLOBALMEM_SIZE)
      {
        ret =  - EINVAL;
        break;
      }
      if ((filp->f_pos + offset) < 0)
      {
        ret =  - EINVAL;
        break;
      }
      filp->f_pos += offset;
      ret = filp->f_pos;
      break;
    default:
      ret =  - EINVAL;
      break;
  }
  return ret;
}


/*文件操作结构体*/
static const struct file_operations globalmem_fops =
{
  .owner = THIS_MODULE,
  .llseek = globalmem_llseek,
  .read = globalmem_read,
  .write = globalmem_write,
  .ioctl = globalmem_ioctl,
  .open = globalmem_open,
  .release = globalmem_release,
};


/*初始化并注册cdev*/
static void globalmem_setup_cdev(struct globalmem_dev *dev, int index)//index为次设备号
{
  int err, devno = MKDEV(globalmem_major, index);//得到总设备号


  cdev_init(&dev->cdev, &globalmem_fops);//将字符设备和对设备操作的函数相关联
  dev->cdev.owner = THIS_MODULE;
  dev->cdev.ops = &globalmem_fops;
  err = cdev_add(&dev->cdev, devno, 1);//将字符设备和内核相关联
  if (err)
    printk(KERN_NOTICE "Error %d adding LED%d", err, index);
}


/*设备驱动模块加载函数*/
int globalmem_init(void)
{
  int result;
  dev_t devno = MKDEV(globalmem_major, 0);


  /* 申请设备号*/
  if (globalmem_major)
    result = register_chrdev_region(devno, 1, "globalmem");
  else  /* 动态申请设备号 */
  {
    result = alloc_chrdev_region(&devno, 0, 1, "globalmem");
    globalmem_major = MAJOR(devno);
  }  
  if (result < 0)
    return result;
    
  /* 动态申请设备结构体的内存*/
  globalmem_devp = kmalloc(sizeof(struct globalmem_dev), GFP_KERNEL);
  if (!globalmem_devp)    /*申请失败*/
  {
    result =  - ENOMEM;
    goto fail_malloc;
  }
  memset(globalmem_devp, 0, sizeof(struct globalmem_dev));
  
  globalmem_setup_cdev(globalmem_devp, 0); /*初始化并注册cdev*/
  return 0;


  fail_malloc: unregister_chrdev_region(devno, 1);
  return result;
}


/*模块卸载函数*/
void globalmem_exit(void)
{
  cdev_del(&globalmem_devp->cdev);   /*注销cdev*/
  kfree(globalmem_devp);     /*释放设备结构体内存*/
  unregister_chrdev_region(MKDEV(globalmem_major, 0), 1); /*释放设备号*/
}


MODULE_AUTHOR("Song Baohua");
MODULE_LICENSE("Dual BSD/GPL");


module_param(globalmem_major, int, S_IRUGO);


module_init(globalmem_init);
module_exit(globalmem_exit);





与设备号相关的宏位于

/usr/src/linux-headers-2.6.35-22/include/linux/kdev_t.h

总设备号,主设备号,次设备号
  1 #ifndef _LINUX_KDEV_T_H
  2 #define _LINUX_KDEV_T_H
  3 #ifdef __KERNEL__					//若已定义__KERNEL__符号则MAJOR
  4 #define MINORBITS       20
  5 #define MINORMASK       ((1U << MINORBITS) - 1)
  6 
  7 #define MAJOR(dev)      ((unsigned int) ((dev) >> MINORBITS))//左移20位得到高12为作为主设备号
  8 #define MINOR(dev)      ((unsigned int) ((dev) & MINORMASK))//MINORMASK为20个1(二进制),取低20位作为次设备号
  9 #define MKDEV(ma,mi)    (((ma) << MINORBITS) | (mi))	//将ma放在高12位,mi放在低20位


 90 #else /* __KERNEL__ *///未定义__KERNEL__符号
 91 
 92 /*
 93 Some programs want their definitions of MAJOR and MINOR and MKDEV
 94 from the kernel sources. These must be the externally visible ones.
 95 */
 96 #define MAJOR(dev)      ((dev)>>8)			//这里就是左移8位
 97 #define MINOR(dev)      ((dev) & 0xff)		//取低8位作为次设备号
 98 #define MKDEV(ma,mi)    ((ma)<<8 | (mi))		//ma左移8位并上mi
 99 #endif /* __KERNEL__ */
100 #endif


Makefile如下,稍微加了一点改进

OBJ     = globalmem
obj-m += $(OBJ).o
MAJOR   = 200 
MINOR   = 0
#generate the path
CURRENT_PATH:=$(shell pwd)
#the current kernel version number
LINUX_KERNEL:=$(shell uname -r)
#the absolute path
LINUX_KERNEL_PATH:=/usr/src/linux-headers-$(LINUX_KERNEL)
#complie object
all:
        make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules

install:
        sudo insmod ./$(OBJ).ko
        sudo mknod /dev/my_$(OBJ) c $(MAJOR) $(MINOR)

uninstall:
        sudo rmmod $(OBJ)
        sudo rm -rf /dev/my_$(OBJ)
#clean
clean:
        make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean

可以使用命令来测试设备

#ls > /dev/my_globalmem

#cat /dev/my_globalmem


或者用测试程序

这里的程序是从设备中读取数据,测试之前要先向设备中写入数据。

#cat file > /dev/my_globalmem

/*main.c*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
 
 
int main(void)
{
        int testdev;
        int i,rf=0;
        char buf[100];
 
        memset(buf, 0, sizeof(buf));
        testdev = open("/dev/my_globalmem",O_RDWR); //open the device 
        if ( testdev == -1 )
        {   
        perror("open\n");
        exit(0);
        }   
        for(i=0;i<10;i++)
        {   
                rf=read(testdev,buf,100);               //read some bytes from the device and put the data to buf
                if(rf<0)
                perror("read error\n");
                printf("times %d ,Read:\n%s", i, buf);
                printf("\ntimes %d ,Read finish\n", i); 
        }   
        close(testdev);                         //close the device 
        return 0;


这是有两个globalmem“设备”的驱动程序,只需要更改设备初始化函数和卸载函数

/*设备驱动模块加载函数*/
int globalmem_init(void)
{
  int result;
  dev_t devno = MKDEV(globalmem_major, 0);

  /* 申请设备号*/
  if (globalmem_major)
    result = register_chrdev_region(devno, 2, "globalmem");//申请使用两个总设备号
  else  /* 动态申请设备号 */
  {
    result = alloc_chrdev_region(&devno, 0, 2, "globalmem");
    globalmem_major = MAJOR(devno);
  }  
  if (result < 0)
    return result;
    
  /* 动态申请2个设备结构体的内存*/
  globalmem_devp = kmalloc(2*sizeof(struct globalmem_dev), GFP_KERNEL);
  if (!globalmem_devp)    /*申请失败*/
  {
    result =  - ENOMEM;
    goto fail_malloc;
  }
  memset(globalmem_devp, 0, 2*sizeof(struct globalmem_dev));
  
  globalmem_setup_cdev(&globalmem_devp[0], 0);//从设备号为0
  globalmem_setup_cdev(&globalmem_devp[1], 1);//从设备号为1
  return 0;

  fail_malloc: unregister_chrdev_region(devno, 2);
  return result;
}

/*模块卸载函数*/
void globalmem_exit(void)
{
  cdev_del(&(globalmem_devp[0].cdev));   
  cdev_del(&(globalmem_devp[1].cdev));   /*注销cdev*/
  kfree(globalmem_devp);     /*释放设备结构体内存*/
  unregister_chrdev_region(MKDEV(globalmem_major, 0), 2); /*释放设备号*/
}


我们可以看到以上程序是没有加锁的,在对设备的read,write,ioctl操作中会产生竞态,多个进程同时访问的话,驱动极易崩溃。

所以在对这块内存“设备”做操作时(读,写,清空),要加锁。

注意/dev下建立的设备文件和驱动程序中设置的主从设备号一定要一致,不然是无法读取的。


你可能感兴趣的:(linux,struct,user,Module,File,Path)