<Linux开发>驱动开发 -Linux MISC 驱动

<Linux开发>驱动开发 -Linux MISC 驱动

交叉编译环境搭建:
<Linux开发> linux开发工具-之-交叉编译环境搭建

uboot移植可参考以下:
<Linux开发> -之-系统移植 uboot移植过程详细记录(第一部分)
<Linux开发> -之-系统移植 uboot移植过程详细记录(第二部分)
<Linux开发> -之-系统移植 uboot移植过程详细记录(第三部分)(uboot移植完结)

Linux内核及设备树移植可参考以下:
<Linux开发>系统移植 -之- linux内核移植过程详细记录(第一部分)
<Linux开发>系统移植 -之- linux内核移植过程详细记录(第二部分完结)

Linux文件系统构建移植参考以下:
<Linux开发>系统移植 -之- linux构建BusyBox根文件系统及移植过程详细记录
<Linux开发>系统移植 -之-使用buildroot构建BusyBox根文件系统

Linux驱动开发参考以下:
<Linux开发>驱动开发 -之-pinctrl子系统
<Linux开发>驱动开发 -之-gpio子系统
<Linux开发>驱动开发 -之-基于pinctrl/gpio子系统的LED驱动
<Linux开发>驱动开发 -之-基于pinctrl/gpio子系统的beep驱动
<Linux开发>驱动开发 -之-资源的并发与竞争处理
<Linux开发>驱动开发 -之-内核定时器与中断
<Linux开发>驱动开发 -之-阻塞、非阻塞IO和异步通知
<Linux开发>驱动开发 -之-platform 驱动

一 前言

misc 的意思是混合、杂项的,因此 MISC 驱动也叫做杂项驱动,也就是当我们板子上的某些外设无法进行分类的时候,比如说某个外设,既不是I2C设备、也不是SPI设备、更不是USB等设备,就可以使用 MISC 驱动。MISC 驱动其实就是最简单的字符设备驱动,通常嵌套在 platform 总线驱动中,实现复杂的驱动,本文我们就来学习一下 MISC 驱动的编写。在前面的文章中我们一直以BEEP蜂鸣器来写例程,这次也依然是,因为beep蜂鸣器,既不是IIC设备,也不是SPI设备等,所以没有统一的总线,那么我们只能用misc来归类为杂项设备。

二 MISC 设备驱动简介

2.1 MISC 设备主设备号

在linux中有很多平台设备的主设备号是固定的,相关定义如下:

路径:include\uapi\linux\major.h

#ifndef _LINUX_MAJOR_H
#define _LINUX_MAJOR_H

/*
 * This file has definitions for major device numbers.
 * For the device number assignments, see Documentation/devices.txt.
 */

#define UNNAMED_MAJOR		0
#define MEM_MAJOR		1
#define RAMDISK_MAJOR		1
#define FLOPPY_MAJOR		2
#define PTY_MASTER_MAJOR	2
#define IDE0_MAJOR		3
#define HD_MAJOR		IDE0_MAJOR
#define PTY_SLAVE_MAJOR		3
#define TTY_MAJOR		4
#define TTYAUX_MAJOR		5
#define LP_MAJOR		6
#define VCS_MAJOR		7
#define LOOP_MAJOR		7
#define SCSI_DISK0_MAJOR	8
#define SCSI_TAPE_MAJOR		9
#define MD_MAJOR		9
#define MISC_MAJOR		10
#define SCSI_CDROM_MAJOR	11
#define MUX_MAJOR		11	/* PA-RISC only */
#define XT_DISK_MAJOR		13
#define INPUT_MAJOR		13
#define SOUND_MAJOR		14
#define CDU31A_CDROM_MAJOR	15
#define JOYSTICK_MAJOR		15
#define GOLDSTAR_CDROM_MAJOR	16
#define OPTICS_CDROM_MAJOR	17
#define SANYO_CDROM_MAJOR	18
......
#define IBM_TTY3270_MAJOR	227
#define IBM_FS3270_MAJOR	228

#define VIOTAPE_MAJOR		230

#define BLOCK_EXT_MAJOR		259
#define SCSI_OSD_MAJOR		260	/* open-osd's OSD scsi device */

#endif

在第27行,可看到所有的 MISC 设备驱动的主设备号都为 10,不同的设备使用不同的从设备号。随着 Linux字符设备驱动的不断增加,设备号变得越来越紧张,尤其是主设备号,MISC 设备驱动就用于解决此问题。MISC 设备会自动创建 cdev,不需要像我们以前那样手动创建,因此采用 MISC 设备驱动可以简化字符设备驱动的编写。

2.2 MISC 设备结构体

当我们需要向 Linux 注册一个 miscdevice 设备时,需要定义一个miscdevice结构体变量,然后通过misc_register()函数注册到内核中,miscdevice是一个结构体,定义内容如下:

路径:include\linux\miscdevice.h

struct miscdevice  {
	int minor;							/* 子设备号 */
	const char *name;					/* 设备名字 */
	const struct file_operations *fops;	/* 设备操作集 */
	struct list_head list;
	struct device *parent;
	struct device *this_device;
	const struct attribute_group **groups;
	const char *nodename;
	umode_t mode;
};

定义一个 MISC 设备(miscdevice 类型)以后我们需要设置 minor、name 和 fops 这三个成员变量。minor 表示子设备号,MISC 设备的主设备号为 10,这个是固定的,需要用户指定子设备号,Linux 系统已经预定义了一些 MISC 设备的子设备号,这些预定义的子设备号定义如下所示:

路径:include\linux\miscdevice.h
/*
 *	These allocations are managed by device@lanana.org. If you use an
 *	entry that is not in assigned your entry may well be moved and
 *	reassigned, or set dynamic if a fixed value is not justified.
 */

#define PSMOUSE_MINOR		1
#define MS_BUSMOUSE_MINOR	2	/* unused */
#define ATIXL_BUSMOUSE_MINOR	3	/* unused */
/*#define AMIGAMOUSE_MINOR	4	FIXME OBSOLETE */
#define ATARIMOUSE_MINOR	5	/* unused */
#define SUN_MOUSE_MINOR		6	/* unused */
#define APOLLO_MOUSE_MINOR	7	/* unused */
#define PC110PAD_MINOR		9	/* unused */
/*#define ADB_MOUSE_MINOR	10	FIXME OBSOLETE */
#define WATCHDOG_MINOR		130	/* Watchdog timer     */
#define TEMP_MINOR		131	/* Temperature Sensor */
#define RTC_MINOR		135
#define EFI_RTC_MINOR		136	/* EFI Time services */
#define VHCI_MINOR		137
#define SUN_OPENPROM_MINOR	139
#define DMAPI_MINOR		140	/* unused */
#define NVRAM_MINOR		144
#define SGI_MMTIMER		153
#define STORE_QUEUE_MINOR	155	/* unused */
#define I2O_MINOR		166
#define MICROCODE_MINOR		184
#define VFIO_MINOR		196
#define TUN_MINOR		200
#define CUSE_MINOR		203
#define MWAVE_MINOR		219	/* ACP/Mwave Modem */
#define MPT_MINOR		220
#define MPT2SAS_MINOR		221
#define MPT3SAS_MINOR		222
#define UINPUT_MINOR		223
#define MISC_MCELOG_MINOR	227
#define HPET_MINOR		228
#define FUSE_MINOR		229
#define KVM_MINOR		232
#define BTRFS_MINOR		234
#define AUTOFS_MINOR		235
#define MAPPER_CTRL_MINOR	236
#define LOOP_CTRL_MINOR		237
#define VHOST_NET_MINOR		238
#define UHID_MINOR		239
#define MISC_DYNAMIC_MINOR	255

我们在使用的时候可以从这些预定义的子设备号中挑选一个,当然也可以自己定义,只要这个子设备号没有被其他设备使用接口。

name: 就是此 MISC 设备名字,当此设备注册成功以后就会在/dev 目录下生成一个名为 name的设备文件。

fops: 就是字符设备的操作集合,MISC 设备驱动最终是需要使用用户提供的 fops操作集合。

2.3 MISC 设备API

当设置好 miscdevice 结构体对象以后就需要使用 misc_register 函数向系统中注册一个 MISC 设备,此函数原型如下:

路径:drivers\char\misc.c
int misc_register(struct miscdevice * misc)

函数参数和返回值含义如下:
misc:要注册的 MISC 设备。
返回值:负数,失败;0,成功。

以前我们需要自己调用一堆的函数去创建设备,比如在以前的字符设备驱动中我们会使用如下几个函数完成设备创建过程:

 alloc_chrdev_region(); /* 申请设备号 */
 cdev_init(); /* 初始化 cdev */
 cdev_add(); /* 添加 cdev */
 class_create(); /* 创建类 */
 device_create(); /* 创建设备 */

现在我们可以直接使用 misc_register 一个函数来完成上述代码中的这些步骤。

当我们卸载设备驱动模块的时候需要调用 misc_deregister 函数来注销掉 MISC 设备,函数原型如下:

路径:drivers\char\misc.c
int misc_deregister(struct miscdevice *misc)

函数参数和返回值含义如下:
misc:要注销的 MISC 设备。
返回值:负数,失败;0,成功。

以前注销设备驱动的时候,我们需要调用一堆的函数去删除此前创建的 cdev、设备等等内容,如下所示:

cdev_del(&beepdev.cdev);								/*  删除cdev */
unregister_chrdev_region(beepdev.devid, BEEPDEV_CNT);	/* 注销设备号 */
device_destroy(beepdev.class, beepdev.devid);	 		/* 删除设备 */
class_destroy(beepdev.class);							/* 删除类 */

现在我们只需要一个 misc_deregister 函数即可完成上述代码中的这些工作。

关于MISC 设备驱动主要就设计这两个API,更多API可参考“drivers\char\misc.c”中的内容,接下来我们就使用 platform 加 MISC 驱动框架来编写 beep 蜂鸣器驱动。

三 实现misc驱动

3.1 原理图

本文以beep蜂鸣器为例,所以硬件信息可参考<Linux开发>驱动开发 -之-platform 驱动中的4.1小节,设备树可参考5.1小节。

3.2 驱动编写

新建文件miscbeep.c,并输入以下内容:

#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_gpio.h>
#include <linux/platform_device.h>
#include <linux/miscdevice.h>
#include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>

/
/// Copyright © 2018-2023  XINWEN Electronic Technology Co., Ltd.
/// All rights reserved.                                       
/
/// @file(文件)            miscbeep.c                                   
/// @brief(简述)           采用MISC的蜂鸣器驱动程序                   
/// @details(详情)         采用MISC的蜂鸣器驱动程序                  
/// @version(版本)         1.0                                       
/// @author(作者)          water                                    
/// @date(日期)            2023-06-19                                
/
/// Edit History                                               
/// -----------------------------------------------------------
/// DATE        NAME          DESCRIPTION                      
/// 2023-06-19  water     Create.                             
///                                                            
/
#define MISCBEEP_NAME		"miscbeep"	/* 名字 	*/
#define MISCBEEP_MINOR		144			/* 子设备号 */
#define BEEPOFF 			0			/* 关蜂鸣器 */
#define BEEPON 				1			/* 开蜂鸣器 */

/* miscbeep设备结构体 */
struct miscbeep_dev{
	dev_t devid;			/* 设备号 	 */
	struct cdev cdev;		/* cdev 	*/
	struct class *class;	/* 类 		*/
	struct device *device;	/* 设备 	 */
	struct device_node	*nd; /* 设备节点 */
	int beep_gpio;			/* beep所使用的GPIO编号		*/
};

struct miscbeep_dev miscbeep;		/* beep设备 */

/*
 * @description		: 打开设备
 * @param - inode 	: 传递给驱动的inode
 * @param - filp 	: 设备文件,file结构体有个叫做private_data的成员变量
 * 					  一般在open的时候将private_data指向设备结构体。
 * @return 			: 0 成功;其他 失败
 */
static int miscbeep_open(struct inode *inode, struct file *filp)
{
	filp->private_data = &miscbeep; /* 设置私有数据 */
	return 0;
}

/*
 * @description		: 向设备写数据 
 * @param - filp 	: 设备文件,表示打开的文件描述符
 * @param - buf 	: 要写给设备写入的数据
 * @param - cnt 	: 要写入的数据长度
 * @param - offt 	: 相对于文件首地址的偏移
 * @return 			: 写入的字节数,如果为负值,表示写入失败
 */
static ssize_t miscbeep_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
	int retvalue;
	unsigned char databuf[1];
	unsigned char beepstat;
	struct miscbeep_dev *dev = filp->private_data;

	retvalue = copy_from_user(databuf, buf, cnt);
	if(retvalue < 0) {
		printk("kernel write failed!\r\n");
		return -EFAULT;
	}

	beepstat = databuf[0];		/* 获取状态值 */
	if(beepstat == BEEPON) {	
		gpio_set_value(dev->beep_gpio, 0);	/* 打开蜂鸣器 */
	} else if(beepstat == BEEPOFF) {
		gpio_set_value(dev->beep_gpio, 1);	/* 关闭蜂鸣器 */
	}
	return 0;
}

/* 设备操作函数 */
static struct file_operations miscbeep_fops = {
	.owner = THIS_MODULE,
	.open = miscbeep_open,
	.write = miscbeep_write,
};

/* MISC设备结构体 */
static struct miscdevice beep_miscdev = {
	.minor = MISCBEEP_MINOR,
	.name = MISCBEEP_NAME,
	.fops = &miscbeep_fops,
};

 /*
  * @description     : flatform驱动的probe函数,当驱动与
  *                    设备匹配以后此函数就会执行
  * @param - dev     : platform设备
  * @return          : 0,成功;其他负值,失败
  */
static int miscbeep_probe(struct platform_device *dev)
{
	int ret = 0;

	printk("beep driver and device was matched!\r\n");
	/* 设置BEEP所使用的GPIO */
	/* 1、获取设备节点:beep */
	miscbeep.nd = of_find_node_by_path("/beep");
	if(miscbeep.nd == NULL) {
		printk("beep node not find!\r\n");
		return -EINVAL;
	} 

	/* 2、 获取设备树中的gpio属性,得到BEEP所使用的BEEP编号 */
	miscbeep.beep_gpio = of_get_named_gpio(miscbeep.nd, "beep-gpio", 0);
	if(miscbeep.beep_gpio < 0) {
		printk("can't get beep-gpio");
		return -EINVAL;
	}

	/* 3、设置GPIO5_IO01为输出,并且输出高电平,默认关闭BEEP */
	ret = gpio_direction_output(miscbeep.beep_gpio, 1);
	if(ret < 0) {
		printk("can't set gpio!\r\n");
	}
	
	/* 一般情况下会注册对应的字符设备,但是这里我们使用MISC设备
  	 * 所以我们不需要自己注册字符设备驱动,只需要注册misc设备驱动即可
	 */
	ret = misc_register(&beep_miscdev);
	if(ret < 0){
		printk("misc device register failed!\r\n");
		return -EFAULT;
	}

	return 0;
}

/*
 * @description     : platform驱动的remove函数,移除platform驱动的时候此函数会执行
 * @param - dev     : platform设备
 * @return          : 0,成功;其他负值,失败
 */
static int miscbeep_remove(struct platform_device *dev)
{
	/* 注销设备的时候关闭LED灯 */
	gpio_set_value(miscbeep.beep_gpio, 1);

	/* 注销misc设备 */
	misc_deregister(&beep_miscdev);
	return 0;
}

 /* 匹配列表 */
 static const struct of_device_id beep_of_match[] = {
     { .compatible = "water-beep" },
     { /* Sentinel */ }
 };
 
 /* platform驱动结构体 */
static struct platform_driver beep_driver = {
     .driver     = {
         .name   = "water-beep",         /* 驱动名字,用于和设备匹配 */
         .of_match_table = beep_of_match, /* 设备树匹配表          */
     },
     .probe      = miscbeep_probe,
     .remove     = miscbeep_remove,
};

/*
 * @description	: 驱动出口函数
 * @param 		: 无
 * @return 		: 无
 */
static int __init miscbeep_init(void)
{
	return platform_driver_register(&beep_driver);
}

/*
 * @description	: 驱动出口函数
 * @param 		: 无
 * @return 		: 无
 */
static void __exit miscbeep_exit(void)
{
	platform_driver_unregister(&beep_driver);
}

module_init(miscbeep_init);
module_exit(miscbeep_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("water");

第 37~102 行,标准的字符设备驱动。

第 104~109 行,MISC 设备 beep_miscdev,第 106 行设置子设备号为 144,第 107 行设置设备名字为“miscbeep”,这样当系统启动以后就会在/dev/目录下存在一个名为“miscbeep”的设备文件。第 108 行,设置 MISC 设备的操作函数集合,为 file_operations 类型。

第 111~153 行,platform 框架的 probe 函数,当驱动与设备匹配以后此函数就会执行,首先在此函数中初始化 BEEP 所使用的 IO。最后在 146 行通过 misc_register 函数向 Linux 内核注册MISC 设备,也就是前面定义的 beep_miscdev。

第 155~168 行,platform 框架的 remove 函数,在此函数中调用 misc_deregister 函数来注销MISC 设备。

第 170~204,标准的 platform 驱动。

3.2 编写测试 APP

新建测试app文件名为,miscbeep_App.c,内容如下:

#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
/***************************************************************
/// Copyright © 2018-2023  XINWEN Electronic Technology Co., Ltd.
/// All rights reserved.                                       
/// @file(文件)            miscbeep_App.c                                   
/// @brief(简述)           MISC驱动框架下的beep测试APP               
/// @details(详情)         MISC驱动框架下的beep测试APP                 
/// @version(版本)         1.0                                       
/// @author(作者)          water                                    
/// @date(日期)            2023-06-19                                
/// Edit History                                               
/// -----------------------------------------------------------
/// DATE        NAME          DESCRIPTION                      
/// 2023-06-19  water     Create.                             
///
///使用方法:	
///			./miscbeepApp  /dev/miscbeep  0 关闭蜂鸣器
///			./misdcbeepApp /dev/miscbeep  1 打开蜂鸣器
***************************************************************/
#define BEEPOFF	0
#define BEEPON 	1

/*
 * @description		: main主程序
 * @param - argc 	: argv数组元素个数
 * @param - argv 	: 具体参数
 * @return 			: 0 成功;其他 失败
 */
int main(int argc, char *argv[])
{
	int fd, retvalue;
	char *filename;
	unsigned char databuf[1];
	
	if(argc != 3){
		printf("Error Usage!\r\n");
		return -1;
	}

	filename = argv[1];
	fd = open(filename, O_RDWR);	/* 打开beep驱动 */
	if(fd < 0){
		printf("file %s open failed!\r\n", argv[1]);
		return -1;
	}

	databuf[0] = atoi(argv[2]);	/* 要执行的操作:打开或关闭 */
	retvalue = write(fd, databuf, sizeof(databuf));
	if(retvalue < 0){
		printf("BEEP Control Failed!\r\n");
		close(fd);
		return -1;
	}

	retvalue = close(fd); /* 关闭文件 */
	if(retvalue < 0){
		printf("file %s close failed!\r\n", argv[1]);
		return -1;
	}
	return 0;
}

//编译命令: arm-linux-gnueabihf-gcc miscbeep_App.c -o miscbeep_App

四 编译验证

4.1 编写Makefile

编写编译驱动所需的Makrfile文件,内容如下:

RCH=arm
CROSS_COMPILE=arm-linux-gnueabihf-

KERNELDIR := /home/water/imax/NXP/kernel/linux-imx-rel_imx_4.1.15_2.1.0_ga/
CURRENT_PATH := $(shell pwd)

obj-m := miscbeep.o

build: kernel_modules

kernel_modules:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules

clean:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean

在这里插入图片描述

4.2 编译驱动

编写好Makefile之后即可在命令行执行“make”命令进行编译如下:

在这里插入图片描述

4.3 编译app

执行以下命令进行编译:

arm-linux-gnueabihf-gcc miscbeep_App.c -o miscbeep_App

在这里插入图片描述

4.4 资源文件导入设备

cp app/miscbeep_App  ../../nfs/buildrootfs/root/water_soft/misc/
cp miscbeep.ko  ../../nfs/buildrootfs/lib/modules/4.1.15+/

在这里插入图片描述

4.5 挂载驱动

挂载驱动命令:

cd /lib/modules/4.1.15\+/
# depmod 
# modprobe miscbeep.ko 

在这里插入图片描述

4.6 运行测试app

开启beep:

./miscbeep_App  /dev/miscbeep 1

关闭beep:

./miscbeep_App  /dev/miscbeep 0

在这里插入图片描述

4.7 卸载驱动

卸载驱动命令:

cd /lib/modules/4.1.15\+/
rmmod miscbeep.ko 

在这里插入图片描述

验证符合设计。

5 总结

在大多数的平台话设备基本上时为了简化开发人员的工作量,由前面2.3小节讲解的API内容可知,实际注册字符设备时,所使用的函数,大大简化了,这也更加有助于提升开发效率。后续分析的设备大部分都是平台化的设备。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

waterfxw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值