文章目錄
- 1.前言
- 2.異步通知
- 2.信號
- 4.驅動中的信號處理
- 4.1 fasync__struct
- 4.2 fasync 函式
- 5.實驗程式撰寫
- 5.1 驅動程式
- 5.2 應用程式
- 6.測驗
1.前言
開發板:正點原子阿爾法
在Linux驅動中如何主動向應用程式發出通知呢,然后應用程式從驅動中讀取資料,類似于中斷,Linux中提供異步通知來完成這一功能,
2.異步通知
-
阻塞訪問驅動程式:應用程式會處于休眠態,等待驅動設備可以使用
-
非阻塞訪問驅動程式:通過 poll 函式來不斷的輪詢,查看驅動設備檔案是否可以使用
-
異步通知:驅動設備告訴應用程式自己可以訪問
阻塞、非阻塞、異步通知,這三種是針對不同的場合提出來的不同的解決方法,沒有優劣之分,在實際的作業和學習中,根據自己的實際需求選擇合適的處理方法即可,
2.信號
異步通知的核心在于信號,在在 arch/xtensa/include/uapi/asm/signal.h 檔案中定義了 Linux 所支持的所有信號,這些信號如下所示
#define SIGHUP 1 /* 終端掛起或控制行程終止 */
#define SIGINT 2 /* 終端中斷(Ctrl+C 組合鍵) */
#define SIGQUIT 3 /* 終端退出(Ctrl+\組合鍵) */
#define SIGILL 4 /* 非法指令 */
#define SIGTRAP 5 /* debug 使用,有斷點指令產生 */
#define SIGABRT 6 /* 由 abort(3)發出的退出指令 */
#define SIGIOT 6 /* IOT 指令 */
#define SIGBUS 7 /* 總線錯誤 */
#define SIGFPE 8 /* 浮點運算錯誤 */
#define SIGKILL 9 /* 殺死、終止行程 */
#define SIGUSR1 10 /* 用戶自定義信號 1 */
#define SIGSEGV 11 /* 段違例(無效的記憶體段) */
#define SIGUSR2 12 /* 用戶自定義信號 2 */
#define SIGPIPE 13 /* 向非讀管道寫入資料 */
#define SIGALRM 14 /* 鬧鐘 */
#define SIGTERM 15 /* 軟體終止 */
#define SIGSTKFLT 16 /* 堆疊例外 */
#define SIGCHLD 17 /* 子行程結束 */
#define SIGCONT 18 /* 行程繼續 */
#define SIGSTOP 19 /* 停止行程的執行,只是暫停 */
#define SIGTSTP 20 /* 停止行程的運行(Ctrl+Z 組合鍵) */
#define SIGTTIN 21 /* 后臺行程需要從終端讀取資料 */
#define SIGTTOU 22 /* 后臺行程需要向終端寫資料 */
#define SIGURG 23 /* 有"緊急"資料 */
#define SIGXCPU 24 /* 超過 CPU 資源限制 */
#define SIGXFSZ 25 /* 檔案大小超額 */
#define SIGVTALRM 26 /* 虛擬時鐘信號 */
#define SIGPROF 27 /* 時鐘信號描述 */
#define SIGWINCH 28 /* 視窗大小改變 */
#define SIGIO 29 /* 可以進行輸入/輸出操作 */
#define SIGPOLL SIGIO
/* #define SIGLOS 29 */
#define SIGPWR 30 /* 斷點重啟 */
#define SIGSYS 31 /* 非法的系統呼叫 */
#define SIGUNUSED 31 /* 未使用信號 */
在上面的信號中除了SIGKILL(9)和 SIGSTOP(19)這兩個信號不能被忽略外,其他的信號都可以忽略 ,這些信號相當于中斷號,在使用中斷的時候,需要注冊中斷處理函式,同樣的在使用信號的時候需要注冊信號處理函式,在應用程式中使用 signal 函式來設定指定信號的處理函式, signal 函式原型如下所示:
sighandler_t signal(int signum, sighandler_t handler)
-
signum:要設定處理函式的信號
-
handler: 信號的處理函式,
回傳值: 設定成功的話回傳信號的前一個處理函式,設定失敗的話回傳 SIG_ERR, -
信號處理函式原型如下所示:
typedef void (*sighandler_t)(int)
4.驅動中的信號處理
4.1 fasync__struct
首先我們需要在驅動程式中定義一個 fasync_struct 結構體指標變數, fasync_struct 結構體內容如下:
struct fasync_struct {
spinlock_t fa_lock;
int magic;
int fa_fd;
struct fasync_struct *fa_next;
struct file *fa_file;
struct rcu_head fa_rcu;
};
4.2 fasync 函式
如果要使用異步通知,需要在設備驅動中實作 file_operations 操作集中的 fasync 函式,此函式格式如下所示:
int (*fasync) (int fd, struct file *filp, int on)
在fasync中通過呼叫fasync_helper 函式來初始化前面定義的 fasync_struct 結構體
指標, fasync_helper 函式原型如下:
int fasync_helper(int fd, struct file * filp, int on, struct fasync_struct **fapp)
-
fd:對應fasync的第一個引數
-
on:對應fasync的第三個引數
-
fapp:要初始化的fasync_struct
5.實驗程式撰寫
5.1 驅動程式
1.修改設備樹,在根結點下添加
btn-gpio {
#address-cells = <1>;
#size-cells = <1>;
compatible = "imx-btn";
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_key>;
key-gpio = <&gpio1 18 GPIO_ACTIVE_LOW>; /* KEY0 */
interrupt-parent = <&gpio1>;
interrupts = <18 IRQ_TYPE_EDGE_BOTH>; /* FALLING RISING */
status = "okay";
};
2.在pinctrl結點下添加
pinctrl_key: keygrp {
fsl,pins = <
MX6UL_PAD_UART1_CTS_B__GPIO1_IO18 0xF080 /* KEY0 */
>;
};
執行make dtbs之后拷貝到tftboot下
驅動代碼:
btn.c
#include "btn.h"
static void btn_detect_handler(void)
{
if (data->async_queue)
{
/* Send signal to app program read the data */
kill_fasync(&data->async_queue, SIGIO, POLL_IN);
printk(KERN_DEBUG "%s kill SIGIO\n", __func__);
}
else
{
printk(KERN_ERR "%s kill SIGIO error\n", __func__);
}
printk(KERN_DEBUG "%s btn_status:%d (0:disable,1:enable)\n",__func__,gpio_get_value(data->gpio_num));
enable_irq(data->irq);
}
static irqreturn_t btn_interrupt(int irq, void *handle)
{
//disable_irq_nosync(data->irq);
//btn_detect_handler();
//硬體消抖
mod_timer(&data->timer, jiffies +msecs_to_jiffies(10));
return IRQ_HANDLED;
}
static void btn_timer_func(unsigned long handle)
{
disable_irq_nosync(data->irq);
btn_detect_handler();
}
//cat
static ssize_t btn_status_show(struct device *dev,struct device_attribute *attr, char *buf)
{
int ret;
ret = gpio_get_value(data->gpio_num);
printk("%s:ret=%d\n",__func__,ret);
return sprintf(buf, "%d\n", ret);
}
//宣告btn_status檔案節點
static DEVICE_ATTR(btn_status, S_IRUSR, btn_status_show,NULL);
static struct attribute *atk_imx6ul_btn_sysfs_attrs[] = {
&dev_attr_btn_status.attr,
NULL,
};
static const struct attribute_group dev_attr_grp = {
.attrs = atk_imx6ul_btn_sysfs_attrs,
NULL,
};
static int imx6ul_btn_open(struct inode *inode, struct file *file)
{
file->private_data = data;
return 0;
}
static ssize_t imx6ul_btn_read(struct file *file, char __user *buf, size_t cnt, loff_t * loff)
{
int ret;
int val;
char *readbuf = kzalloc(sizeof(char), GFP_KERNEL);
val = gpio_get_value(data->gpio_num);
//將val格式化為字串
sprintf(readbuf,"%d\n",val);
ret = copy_to_user(buf,readbuf,1);
if(ret == 0)
{
printk("senddata ok!\n");
}else
{
printk("senddata failed\n");
}
return 0;
}
static ssize_t imx6ul_btn_write(struct file *file, const char __user *buf, size_t cnt, loff_t *loff)
{
return 0;
}
static int imx6ul_btn_fasync(int fd, struct file *filp, int mode)
{
printk(KERN_DEBUG "imx6ul_btn_fasync\n");
//初始化data->async_queue
if(fasync_helper(fd, filp, mode, &data->async_queue) < 0 )
{
return -EIO;
}
return 0;
}
static int imx6ul_btn_close(struct inode *inode, struct file *file)
{
printk(KERN_INFO "imx6ul_btn_close\n");
//洗掉異步通知
return imx6ul_btn_fasync(-1, file, 0);
}
static struct file_operations btn_fops = {
.owner = THIS_MODULE,
.read = imx6ul_btn_read,
.write = imx6ul_btn_write,
.fasync = imx6ul_btn_fasync,
.open = imx6ul_btn_open,
.release = imx6ul_btn_close,
};
static int btn_parse_dt(void)
{
int ret;
/*1.獲取設備樹中compatible屬性的字串值imx-btn*/
data->dev_node = of_find_compatible_node(NULL,NULL,"imx-btn");
if(data->dev_node == NULL)
{
printk("led device node find failed\n");
return -1;
}
/*2.獲取gpio編號,將節點中的“key-gpio”屬性值轉換為對應的gpio編號,*/
data->gpio_num = of_get_named_gpio(data->dev_node, "key-gpio", 0);
if(data->gpio_num < 0)
{
printk("failed to get gpio\n");
return -1;
}
/*3.申請gpio管腳*/
ret = gpio_request(data->gpio_num, "btn-gpio");
if(ret != 0)
{
printk("gpio request failed\n");
return -1;
}
/*4.設定gpio為輸入*/
ret = gpio_direction_input(data->gpio_num);
if(ret != 0)
{
printk("gpio direction input failed\n");
return -1;
}
/*5.設定gpio為中斷gpio,獲取gpio的中斷號*/
data->irq = gpio_to_irq(data->gpio_num);
ret = devm_request_threaded_irq(data->device, data->irq, NULL,
btn_interrupt,IRQ_TYPE_EDGE_BOTH| IRQF_ONESHOT,"btn-irq", data);
if (ret) {
printk("Failed to register interrupt\n");
return -1;
}
disable_irq(data->irq);
return 0;
}
static int btn_driver_probe(struct platform_device *pdev)
{
u32 ret;
data = devm_kzalloc(&pdev->dev,sizeof(struct btn_data), GFP_KERNEL);
if(data == NULL)
{
printk(KERN_ERR"kzalloc data failed\n");
return -ENOMEM;
}
/*2.字符設備驅動框架那一套*/
/*2.1 之前定義了主設備號*/
if(data->major)
{
/*選擇次設備號*/
data->devid = MKDEV(data->major,0);
/*注冊設備號*/
ret = register_chrdev_region(data->devid, DEVICE_CNT, DEVICE_NAME);
if(ret < 0)
{
printk("register_chrdev_region faibtn\n");
return ret;
}
}else
{
/*向內核申請主次設備號,DEVICE_NAME體現在/proc/devices*/
alloc_chrdev_region(&data->devid, 0, DEVICE_CNT, DEVICE_NAME); /* 申請設備號 */
data->major = MAJOR(data->devid); /* 獲取分配號的主設備號 */
data->minor = MINOR(data->devid); /* 獲取分配號的次設備號 */
}
data->cdev.owner = THIS_MODULE;
cdev_init(&data->cdev,&btn_fops);
/*自動創建設備結點,在/dev目錄下體現*/
ret = cdev_add(&data->cdev,data->devid,DEVICE_CNT);
if(ret < 0)
{
printk("cdev_add device faibtn\n");
goto fail_cdev_add;
}
data->class = class_create(THIS_MODULE,DEVICE_NAME);
if(IS_ERR(data->class))
{
printk("class creat faibtn\n");
goto fail_class_create;
}
/*生成dev/DEVICE_NAME檔案*/
data->device = device_create(data->class,NULL,data->devid,NULL,DEVICE_NAME);
if(IS_ERR(data->device))
{
printk("device class faibtn\n");
goto fail_device_create;
}
/*創建led_enable結點,直接通過系統呼叫來操作驅動*/
ret = sysfs_create_group(&data->device->kobj,&dev_attr_grp);
if(ret)
{
printk("failed to create sys files\n");
goto fail_sys_create;
}
/*1.設備樹決議*/
ret = btn_parse_dt();
if (ret < 0) {
printk("btn parse error");
return ret;
}
//struct data *device = dev_get_drvdata(dev);
/*初始化定時器,作業佇列*/
//INIT_WORK(&data.btn_work,btn_exchange_work);
setup_timer(&data->timer,btn_timer_func,(unsigned long)data);//最后一個值可以傳指標
enable_irq(data->irq);
/*激活定時器,add_timer不激活定時器*/
//mod_timer(&data->timer, jiffies +msecs_to_jiffies(0));
printk("%s:probe success\n",__func__);
return 0;
fail_cdev_add:
unregister_chrdev_region(data->devid,DEVICE_CNT);
return -1;
fail_class_create:
cdev_del(&data->cdev);
unregister_chrdev_region(data->devid,DEVICE_CNT);
return -1;
fail_device_create:
cdev_del(&data->cdev);
unregister_chrdev_region(data->devid,DEVICE_CNT);
class_destroy(data->class);
return -1;
fail_sys_create:
sysfs_remove_group(&data->device->kobj,&dev_attr_grp);
cdev_del(&data->cdev);
unregister_chrdev_region(data->devid,DEVICE_CNT);
class_destroy(data->class);
return -1;
}
static int btn_driver_remove(struct platform_device *pdev)
{
//依賴device,先洗掉
sysfs_remove_group(&data->device->kobj, &dev_attr_grp);
cdev_del(&data->cdev);
unregister_chrdev_region(data->devid,DEVICE_CNT);
/*依賴于class所以先洗掉*/
device_destroy(data->class, data->devid);
class_destroy(data->class);
//洗掉定時器
del_timer_sync(&data->timer);
gpio_free(data->gpio_num);
return 0;
}
/* 匹配串列,btn_of_match中的compatible與設備樹中的
* compatible匹配,匹配成功則跑probe函式
*/
static const struct of_device_id btn_of_match[] = {
{ .compatible = "imx-btn" },
{ /* Sentinel */ }
};
/*
* platform 平臺驅動結構體
*/
static struct platform_driver btn_driver = {
.driver = {
.name = "imx-btn",
.of_match_table = btn_of_match,
},
.probe = btn_driver_probe,
.remove = btn_driver_remove,
};
module_platform_driver(btn_driver);
MODULE_AUTHOR("fib");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("btn driver of atk imx6ull");
btn.h
#ifndef _BTN_H
#define _BTN_H
#include <linux/types.h> /*設備號所在頭檔案*/
#include <linux/module.h> /*內核模塊宣告的相關函式*/
#include <linux/init.h> /*module_init和module_exit*/
#include <linux/kernel.h> /*內核的各種函式*/
#include <asm/io.h> /*readl函式*/
#include <linux/cdev.h> /*cdev*/
#include <linux/device.h> /*class & device*/
#include <linux/fs.h>
#include <asm/uaccess.h> /*copy_from_user*/
#include <linux/gpio.h> /*gpio fileoperation*/
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/fcntl.h>
#include <linux/signal.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#define DEVICE_NAME "btn_driver"
#define DEVICE_CNT 1
#define LED_ON 1
#define LED_OFF 0
struct btn_data
{
dev_t devid; /*設備號*/
struct cdev cdev; /*cdev*/
struct class *class; /*類*/
struct device *device; /*設備*/
int major; /*主設備號*/
int minor; /*次設備號*/
int irq;
int gpio_num;
struct fasync_struct *async_queue;
struct device_node* dev_node;
struct timer_list timer; /*定時器*/
};
struct btn_data *data;
#endif
Makefile
KERNELDIR := /home/klz/linux/linux-4.1.15
CURRENT_PATH := $(shell pwd)
obj-m := btn.o
build: kernel_modules
kernel_modules:
$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules
copy:
sudo cp *.ko /home/klz/linux/nfs/rootfs/lib/modules/4.1.15
clean:
$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean
簡單來說,將按鍵所在的GPIO申請為中斷gpio,在中斷處理函式中啟動定時器實作硬體消抖,在定時器處理函式中上報信號給應用程式,執行以下代碼編譯并且拷貝到根檔案系統
make && make copy
5.2 應用程式
法1:通過syfs結點訪問按鍵值,注意每次sysfs都要重新打開關閉
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include "poll.h"
#include "sys/select.h"
#include "sys/time.h"
#include "linux/ioctl.h"
#include "signal.h"
static int fd = 0; /* 檔案描述符 */
#define BTN_STATUS_PATH "/sys/devices/virtual/btn_driver/btn_driver/btn_status"
static void get_btn_status(unsigned char *val)
{
int fd_btn_status = 0;
fd_btn_status = open(BTN_STATUS_PATH, O_RDWR);
if (fd_btn_status < 0)
{
printf("Can't open file %s\r\n", BTN_STATUS_PATH);
}
read(fd_btn_status, val, 1);
*val = atoi((const char*)val);
close(fd_btn_status);
}
/*
* SIGIO 信號處理函式
* @param - signum : 信號值
* @return : 無
*/
static void sigio_signal_func(int signum)
{
int err = 0;
unsigned char keyvalue = 0;
/*err = read(fd, &keyvalue, sizeof(keyvalue));
keyvalue = atoi((const char*)&keyvalue);*/
get_btn_status(&keyvalue);
if(err < 0) {
/* 讀取錯誤 */
} else {
printf("sigio signal! key value=%d\r\n", keyvalue);
}
}
/*
* @description : main 主程式
* @param - argc : argv 陣列元素個數
* @param - argv : 具體引數
* @return : 0 成功;其他 失敗
*/
int main(int argc, char *argv[])
{
int flags = 0;
char *filename;
if (argc != 2) {
printf("Error Usage!\r\n");
return -1;
}
filename = argv[1];
fd = open(filename, O_RDWR);
if (fd < 0) {
printf("Can't open file %s\r\n", filename);
return -1;
}
/* 設定信號 SIGIO 的處理函式 */
signal(SIGIO, sigio_signal_func);
fcntl(fd, F_SETOWN, getpid()); /* 將當前行程的行程號告訴給內核 */
flags = fcntl(fd, F_GETFD); /* 獲取當前的行程狀態 */
fcntl(fd, F_SETFL, flags | FASYNC);/* 設定行程啟用異步通知功能 */
while(1) {
sleep(2);
}
close(fd);
return 0;
}
法2:使用設備結點通過呼叫read函式來訪問按鍵值
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include "poll.h"
#include "sys/select.h"
#include "sys/time.h"
#include "linux/ioctl.h"
#include "signal.h"
static int fd = 0; /* 檔案描述符 */
#define BTN_STATUS_PATH "/sys/devices/virtual/btn_driver/btn_driver/btn_status"
static void get_btn_status(unsigned char *val)
{
int fd_btn_status = 0;
fd_btn_status = open(BTN_STATUS_PATH, O_RDWR);
if (fd_btn_status < 0)
{
printf("Can't open file %s\r\n", BTN_STATUS_PATH);
}
read(fd_btn_status, val, 1);
*val = atoi((const char*)val);
close(fd_btn_status);
}
/*
* SIGIO 信號處理函式
* @param - signum : 信號值
* @return : 無
*/
static void sigio_signal_func(int signum)
{
int err = 0;
unsigned char keyvalue = 0;
err = read(fd, &keyvalue, sizeof(keyvalue));
keyvalue = atoi((const char*)&keyvalue);
//get_btn_status(&keyvalue);
if(err < 0) {
/* 讀取錯誤 */
} else {
printf("sigio signal! key value=%d\r\n", keyvalue);
}
}
/*
* @description : main 主程式
* @param - argc : argv 陣列元素個數
* @param - argv : 具體引數
* @return : 0 成功;其他 失敗
*/
int main(int argc, char *argv[])
{
int flags = 0;
char *filename;
if (argc != 2) {
printf("Error Usage!\r\n");
return -1;
}
filename = argv[1];
fd = open(filename, O_RDWR);
if (fd < 0) {
printf("Can't open file %s\r\n", filename);
return -1;
}
/* 設定信號 SIGIO 的處理函式 */
signal(SIGIO, sigio_signal_func);
fcntl(fd, F_SETOWN, getpid()); /* 將當前行程的行程號告訴給內核 */
flags = fcntl(fd, F_GETFD); /* 獲取當前的行程狀態 */
fcntl(fd, F_SETFL, flags | FASYNC);/* 設定行程啟用異步通知功能 */
while(1) {
sleep(2);
}
close(fd);
return 0;
}
執行以下程式編譯并拷貝應用程式到根檔案系統下
arm-linux-gnueabihf-gcc btnApp.c -o btnApp
cp btnApp ../../../nfs/rootfs/lib/modules/4.1.15/
6.測驗
加載驅動

修改sysfs屬性結點權限,執行應用程式,兩個應用程式執行代碼一樣

按下按鍵下報0,釋放按鍵時報1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299755.html
標籤:其他
