日期:2014-05-16  浏览次数:20655 次

设备驱动编译无措,加载insmod不上(无错误提示)
#include <linux/init.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/cdev.h>
#include <linux/io.h>

#define TEST_MAJOR 250
#define TEST_NAME "test"

struct cdev test_dev;


static ssize_t test_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
  return 0;
}


static ssize_t test_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)
{
  return 0;
}


static long test_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
  printk("it's my first char!!!!!\n");
  return 0;
}

struct file_operations test_fops=
{
  .owner = THIS_MODULE,
  .read = test_read,
  .write = test_write,
  .unlocked_ioctl = test_ioctl,
};


static int test_init(void)
{
  int ret;
  cdev_init(&test_dev, &test_fops);
  register_chrdev_region(TEST_MAJOR, 1, TEST_NAME);
  ret = cdev_add(&test_dev, TEST_MAJOR, 1);
  printk(KERN_INFO"hello word enter\n");
  return 0;
}


static void test_exit(void)
{
  unregister_chrdev_region(TEST_MAJOR, 1);
  cdev_del(&test_dev);
  printk(KERN_INFO"hello word exit\n");
}

module_init(test_init);
module_exit(test_exit);

MODULE_LICENSE("GPL");


附应用层代码:
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>  
#include <sys/stat.h>  
#include <fcntl.h>  
#include <termios.h>

int main()
{
  int test_fd;
   
  test_fd = open("/dev/test", O_RDONLY);
  if(test_fd != 0)
  {
  printf("open the dev is err!\n");
  return 0;
  }
  ioctl(test_fd, 5, 5);

  return 0;
}


------解决方案--------------------
register_chrdev_region(TEST_MAJOR, 1, TEST_NAME);
这句有问题,注册的设备号错误

register_chrdev_region的第一个参数dev_t应当是使用MKDEV宏生成的,而不是直接传主设备号 

所以应该是
dev_t dev = MKDEV(TEST_MAJOR, 0)
register_chrdev_region(dev, 1, TEST_NAME);

MKDEV宏定义参见内核
#define MKDEV(ma,mi) (((ma) << MINORBITS) | (mi))