承接上文,這裏繼續學習linux內核驅動併發控制阻塞型I/O。
廢話不多說,直接看代碼,基礎接口函數請自行查閱相關資料,比如《LDD》。
另外併發控制信號量和linux應用層的信號量概念和原理是差不多的,在內核態使用有所差別而已。
驅動code:wqlkp.c
關鍵詞: init_waitqueue_head()、wait_event_interruptible()、wake_up_interruptible()
sema_init()、down_interruptible()、up()
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <linux/semaphore.h>
MODULE_LICENSE("Dual BSD/GPL");
#define DEBUG_SWITCH 1
#if DEBUG_SWITCH
#define P_DEBUG(fmt, args...) printk("<1>" "<kernel>[%s]"fmt,__FUNCTION__, ##args)
#else
#define P_DEBUG(fmt, args...) printk("<7>" "<kernel>[%s]"fmt,__FUNCTION__, ##args)
#endif
#define DEV_SIZE 20//方便測試寫進程阻塞
#define WQ_MAJOR 230
struct wq_dev{
char kbuf[DEV_SIZE];//緩衝區
dev_t devno;//設備號
unsigned int major;
struct cdev wq_cdev;
unsigned int cur_size;//可讀可寫的數據量
struct semaphore sem;//信號量
wait_queue_head_t r_wait;//讀等待隊列
wait_queue_head_t w_wait;//寫等待隊列
};
//struct wq_dev *wq_devp;
int wq_open(struct inode *inodep, struct file *filp)
{
struct wq_dev *dev;
dev = container_of(inodep->i_cdev, struct wq_dev, wq_cdev);
filp->private_data = dev;
printk(KERN_ALERT "open is ok!\n");
return 0;
}
int wq_release(struct inode *inodep, struct file *filp)
{
printk(KERN_ALERT "release is ok!\n");
return 0;
}
static ssize_t wq_read(struct file *filp, char __user *buf, size_t count, loff_t *offset)
{
struct wq_dev *dev = filp->private_data;
P_DEBUG("read data...\n");
if(down_interruptible(&dev->sem))//獲取信號量
{
P_DEBUG("enter read down_interruptible\n");
return -ERESTARTSYS;
}
P_DEBUG("read first down\n");
while(dev->cur_size == 0){//無數據可讀,進入休眠lon
up(&dev->sem);//釋放信號量,不然寫進程沒有機會來喚醒(沒有獲得鎖)
if(filp->f_flags & O_NONBLOCK)//檢查是否是阻塞型I/O
return -EAGAIN;
P_DEBUG("%s reading:going to sleep\n", current->comm);
if(wait_event_interruptible(dev->r_wait, dev->cur_size != 0))//休眠等待被喚醒
{
P_DEBUG("read wait interruptible\n");
return -ERESTARTSYS;
}
P_DEBUG("wake up r_wait\n");
if(down_interruptible(&dev->sem))//獲取信號量
return -ERESTARTSYS;
}
//數據已就緒
P_DEBUG("[2]dev->cur_size is %d\n", dev->cur_size);
if(dev->cur_size > 0)
count = min(count, dev->cur_size);
//從內核緩衝區賦值數據到用戶空間,複製成功返回0
if(copy_to_user(buf, dev->kbuf, count))
{
up(&dev->sem);
return -EFAULT;
}
dev->cur_size -= count;//可讀數據量更新
up(&dev->sem);
wake_up_interruptible(&dev->w_wait);//喚醒寫進程
P_DEBUG("%s did read %d bytes\n", current->comm, (unsigned int)count);
return count;
}
static ssize_t wq_write(struct file *filp, char __user *buf, size_t count, loff_t *offset)
{
struct wq_dev *dev = filp->private_data;
//wait_queue_t my_wait;
P_DEBUG("write is doing\n");
if(down_interruptible(&dev->sem))//獲取信號量
{
P_DEBUG("enter write down_interruptible\n");
return -ERESTARTSYS;
}
// init_wait(&my_wait);
// add_wait_queue(&dev->w_wait, &my_wait);
P_DEBUG("write first down\n");
while(dev->cur_size == DEV_SIZE){//判斷空間是否已滿
up(&dev->sem);//釋放信號量
if(filp->f_flags & O_NONBLOCK)
return -EAGAIN;
P_DEBUG("writing going to sleep\n");
if(wait_event_interruptible(dev->w_wait, dev->cur_size < DEV_SIZE))
return -ERESTARTSYS;
// __set_current_state(TASK_INTERRUPTIBLE);//設置當前進程狀態
// up(&dev->sem);//釋放信號量
// P_DEBUG("befor schedule\n");
// schedule();//進程調度,當前進程進入休眠
// if(signal_pending(current))//檢查當前進程是否有信號處理,返回不爲0表示有信號處理
// return -EAGAIN;
// P_DEBUG("after schedule\n");
if(down_interruptible(&dev->sem))//獲取信號量
return -ERESTARTSYS;
}
if(count > DEV_SIZE - dev->cur_size)
count = DEV_SIZE - dev->cur_size;
if(copy_from_user(dev->kbuf, buf, count))//數據複製
return -EFAULT;
dev->cur_size += count;//更新數據量
P_DEBUG("write %d bytes , cur_size:[%d]\n", count, dev->cur_size);
P_DEBUG("kbuf is [%s]\n", dev->kbuf);
up(&dev->sem);
wake_up_interruptible(&dev->r_wait);//喚醒讀進程隊列
//__set_current_state(TASK_RUNNING);
return count;
}
struct file_operations wq_fops = {
.open = wq_open,
.release = wq_release,
.write = wq_write,
.read = wq_read,
};
struct wq_dev my_dev;
static int __init wq_init(void)
{
int result = 0;
my_dev.cur_size = 0;
my_dev.devno = MKDEV(WQ_MAJOR, 0);
//設備號分配
if(WQ_MAJOR)
result = register_chrdev_region(my_dev.devno, 1, "wqlkp");
else
{
result = alloc_chrdev_region(&my_dev.devno, 0, 1, "wqlkp");
my_dev.major = MAJOR(my_dev.devno);
}
if(result < 0)
return result;
cdev_init(&my_dev.wq_cdev, &wq_fops);//設備初始化
my_dev.wq_cdev.owner = THIS_MODULE;
sema_init(&my_dev.sem, 1);//信號量初始化
init_waitqueue_head(&my_dev.r_wait);//等待隊列初始化
init_waitqueue_head(&my_dev.w_wait);
result = cdev_add(&my_dev.wq_cdev, my_dev.devno, 1);//設備註冊
if(result < 0)
{
P_DEBUG("cdev_add error!\n");
goto err;
}
printk(KERN_ALERT "hello kernel\n");
return 0;
err:
unregister_chrdev_region(my_dev.devno,1);
}
static void __exit wq_exit(void)
{
cdev_del(&my_dev.wq_cdev);
unregister_chrdev_region(my_dev.devno, 1);
}
module_init(wq_init);
module_exit(wq_exit);
一開始read和write函數在最後沒有釋放信號量,導致運行讀寫進程時出現死鎖,我用的最多的調試方式是printk。
回顧上面的實現,設備緩衝用的是一個普通的數組,理論上更好的方式應該是用一個循環隊列,海康面試的時候就問了這個,讀寫文件時,讀寫指針是怎麼變化的。
通常,我們應該在一個驅動程序中使用同種方法,如同上面程序那樣。
但是對於休眠還有其餘方法,程序中註釋掉的休眠方式是其中一種(本例中運行時有寫些許問題..),《LDD》上闡述的是另一種休眠方法,其實就是分解wait_event_interruptible()函數,我們看下他的源碼(linux2.6.18;linux/wait.h)
/**
* wait_event_interruptible - sleep until a condition gets true
* @wq: the waitqueue to wait on
* @condition: a C expression for the event to wait for
*
* The process is put to sleep (TASK_INTERRUPTIBLE) until the
* @condition evaluates to true or a signal is received.
* The @condition is checked each time the waitqueue @wq is woken up.
*
* wake_up() has to be called after changing any variable that could
* change the result of the wait condition.
*
* The function will return -ERESTARTSYS if it was interrupted by a
* signal and 0 if @condition evaluated to true.
*/
#define wait_event_interruptible(wq, condition) \
({ \
int __ret = 0; \
if (!(condition)) \
__wait_event_interruptible(wq, condition, __ret); \
__ret; \
})
#define __wait_event_interruptible_timeout(wq, condition, ret) \
do { \
DEFINE_WAIT(__wait); \
\
for (;;) { \
prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \
if (condition) \
break; \
if (!signal_pending(current)) { \
ret = schedule_timeout(ret); \
if (!ret) \
break; \
continue; \
} \
ret = -ERESTARTSYS; \
break; \
} \
finish_wait(&wq, &__wait); \
} while (0)
簡單分析一下:
1、DEFINE_WAIT(__wait);//建立並初始化一個等待隊列入口,其等效於:wait_queue_t __wait; init_wait(&__wait);
2、prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE);//將等待隊列入口添加到隊列中,並設置進程的狀態
3、schedule_timeout(ret);//進程調度變種程序,調度其餘程序運行
4、finish_wait(&wq, &__wait);//這個函數內部會調用__set_current_state(TASK_RUNNING);跳出for循環後,就得設置當前進程爲可運行態
看了上面的wait_event_interruptible()函數實現,相信你應該知道進程休眠是怎麼回事了,進程休眠在等待隊列中添加了一個wait_queue_t結構體(prepare_to_wait),這樣可以在wq_read、wq_write等函數中直接根據條件進入休眠。
用戶態驗證程序:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
char buf[20];
int fd;
int ret;
fd = open("/dev/wqlkp", O_RDWR);
if(fd < 0)
{
perror("open");
return -1;
}
read(fd, buf, 10);
printf("<app>buf is [%s]\n", buf);
close(fd);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
char buf[20];
int fd;
int ret;
fd = open("/dev/wqlkp", O_RDWR);
if(fd < 0)
{
perror("open");
return -1;
}
write(fd, "wen qian", 10);
close(fd);
return 0;
}
整個需要注意的地方就是處理休眠喚醒以及信號量併發控制的問題,要確保你的程序不會出現死鎖,或者都等待對待喚醒的狀態。
技術交流,永無止境,如有錯誤,歡迎指正。