7、設備驅動中的阻塞與非阻塞 IO(一)

7.1 阻塞與非阻塞 IO

  阻塞操做是指在執行設備操做的時候,若不能獲取資源,則掛起進程直到知足可操做的條件後再進行操做。被掛起的進程進入睡眠狀態,被從調度器的運行隊列移走,直到等待的條件被知足。node

  非阻塞操做的進程在不能進行設備操做時,並不掛起,要麼放棄,要麼不停的查詢,直到能夠進行操做爲止。linux

  驅動程序應提供這樣的能力:當應用程序進行 read()、write()等系統調用時,若設備的資源不能獲取,而用戶又但願以阻塞的方式訪問設備,驅動程序應在設備驅動的 xxx_write()、xxx_read()等操做中將進程阻塞直到資源可取,此後,應用程序的 read()、write() 等調用才返回,整個過程仍然進行了正確的設備訪問,但用戶無感知;若用戶以非阻塞的方式訪問設備文件,則當設備資源不可獲取時,設備驅動的 xxx_write()、xxx_read() 等操做應當即返回, read()、write() 等調用也隨即返回,應用程序收到 -EAGAIN 的返回值。數據結構

7.1.1 等待隊列

  在 Linux 驅動中,可以使用等待隊列(wait queue)來實現阻塞進程的喚醒。等待隊列以隊列爲基礎數據結構,與進程調度機制緊密結合,能夠用來同步對系統資源的訪問。函數

 1 /**
 2  *  等待隊列頭數據結構
 3  *  定義等待隊列頭:
 4  *      wait_queue_head_t my_queue;
 5  */
 6 struct __wait_queue_head {
 7     spinlock_t        lock;
 8     struct list_head    task_list;
 9 };
10 typedef struct __wait_queue_head wait_queue_head_t;
 1 /**
 2  *  初始化等待隊列頭部
 3  */
 4 extern void __init_waitqueue_head(wait_queue_head_t *q, const char *name, struct lock_class_key *);
 5 
 6 #define init_waitqueue_head(q)                \
 7     do {                        \
 8         static struct lock_class_key __key;    \
 9                             \
10         __init_waitqueue_head((q), #q, &__key);    \
11     } while (0)
1 /** 定義並初始化等待隊列頭部 */
2 #define DECLARE_WAIT_QUEUE_HEAD(name) \
3     wait_queue_head_t name = __WAIT_QUEUE_HEAD_INITIALIZER(name)
1 /** 定義等待隊列元素,用於定義並初始化一個名爲 name 的等待隊列元素 */
2 #define DECLARE_WAITQUEUE(name, tsk)                    \
3     wait_queue_t name = __WAITQUEUE_INITIALIZER(name, tsk)
1 /** 添加等待隊列:將等待隊列元素 wait 添加到等待隊列頭部 q 指向的雙向鏈表中 */
2 extern void add_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);
1 /** 刪除等待隊列:將等待隊列元素 wait 從由等待隊列頭部 q 指向的鏈表中刪除 */
2 extern void remove_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);
 1 /**
 2  *    等待事件
 3  *        wq:做爲等待隊列頭部的隊列被喚醒
 4  *        condition:此參數必須知足,不然繼續阻塞
 5  *    wait_event 和 wait_event_interruptible 區別是後者能夠被信號打斷,而前者不能
 6  *    加上 _timeout 後表示阻塞等待的超時時間,以 jiffy 爲但聞,在第三個參數的 timeout 到達時,不論 condition 是否知足,均返回
 7  */
 8 wait_event(wq, condition);
 9 wait_event_interruptible(wq, condition);
10 wait_event_timeout(wq, condition, timeout);
11 wait_event_interruptible_timeout(wq, condition, timeout);
 1 /**
 2  *    喚醒隊列
 3  *        喚醒以 q 做爲等待隊列頭部的隊列中的全部進程
 4  *        wake_up 與 wait_event 或 wait_event_timeout 成對使用
 5  *        wake_up_interruptible 與 wait_event_interruptible 或 wait_event_interruptible_timeout 成對使用
 6  *        wake_up 可喚醒處於 TASK_INTERRUPTIBLE 和 TASK_UNINTERRUPTIBLE 的進程
 7  *        wake_up_interruptible 只能喚醒處於 TASK_INTERRUPTIBLE 的進程
 8  */
 9 void wake_up(wait_queue_head_t *q);
10 void wake_up_interruptible(wait_queue_head_t *q);

7.1.2 globalmem 增長隊列操做

  增長約束:把 globalmem 中的全局內存變爲一個 FIFO,只有當 FIFO 有數據的時候(即有進程把數據寫到這個 FIFO 並且沒有沒有被讀進程讀空),讀進程才能把數據讀出,並且讀取後的數據會從 globalmem 的全局內存中被拿掉;只有當 FIFO 不是滿的時候(即還有一些空間未被寫,或寫滿後被讀進程從這個 FIFO 中讀出了數據),寫進程才能往這個 FIFO 中寫數據。spa

  1 #include <linux/module.h>
  2 #include <linux/fs.h>
  3 #include <linux/init.h>
  4 #include <linux/cdev.h>
  5 #include <linux/slab.h>
  6 #include <linux/uaccess.h>
  7 #include <linux/mutex.h>
  8 #include <linux/wait.h>
  9 #include <linux/sched/signal.h> ///< 內核>5.0 使用
 10 //#include <linux/sched.h>
 11 
 12 #define GLOBALFIFO_SIZE      0x1000
 13 //#define MEM_CLEAR           0X1
 14 #define GLOBALFIFO_MAGIC     'g'
 15 #define MEM_CLEAR           _IO(GLOBALFIFO_MAGIC, 0)
 16 #define GLOBALFIFO_MAJOR     230
 17 #define DEVICE_NUMBER       10
 18 
 19 static int globalfifo_major = GLOBALFIFO_MAJOR;
 20 module_param(globalfifo_major, int, S_IRUGO);
 21 
 22 struct globalfifo_dev {
 23     struct cdev cdev;
 24     /** 
 25      *  目前 FIFO 中有效數據長度 
 26      *  current_len = 0, 表示 FIFO 爲空
 27      *  current_len = GLOBALFIFO_SIZE, 表示 FIFO 滿
 28      */
 29     unsigned int current_len;   
 30     unsigned char mem[GLOBALFIFO_SIZE];
 31     struct mutex mutex;
 32     wait_queue_head_t r_wait;   ///< 讀等待隊列頭
 33     wait_queue_head_t w_wait;   ///< 寫等待隊列頭
 34 };
 35 
 36 struct globalfifo_dev *globalfifo_devp;
 37 
 38 /** 
 39  * 這裏涉及到私有數據的定義,大多數遵循將文件私有數據 pirvate_data 指向設備結構體,
 40  * 再用 read write llseek ioctl 等函數經過 private_data 訪問設備結構體。
 41  * 對於此驅動而言,私有數據的設置是在 open 函數中完成的
 42  */
 43 static int globalfifo_open(struct inode *inode, struct file *filp)
 44 {
 45     /**
 46      *  NOTA: 
 47      *      container_of 的做用是經過結構體成員的指針找到對應結構體的指針。
 48      *      第一個參數是結構體成員的指針
 49      *      第二個參數是整個結構體的類型
 50      *      第三個參數爲傳入的第一個參數(即結構體成員)的類型
 51      *      container_of 返回值爲整個結構體指針
 52      */ 
 53     struct globalfifo_dev *dev = container_of(inode->i_cdev, struct globalfifo_dev, cdev);
 54     filp->private_data = dev;
 55     return 0;
 56 }
 57 
 58 static int globalfifo_release(struct inode *inode, struct file *filp)
 59 {
 60     return 0;
 61 }
 62 
 63 static long globalfifo_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
 64 {
 65     struct globalfifo_dev *dev = filp->private_data;
 66 
 67     switch(cmd){
 68     case MEM_CLEAR:
 69         mutex_lock(&dev->mutex);
 70         memset(dev->mem, 0, GLOBALFIFO_SIZE);
 71         printk(KERN_INFO "globalfifo is set to zero\n");
 72         mutex_unlock(&dev->mutex);
 73         break;
 74     default:
 75         return -EINVAL;
 76     }
 77 
 78     return 0;
 79 }
 80 
 81 static loff_t globalfifo_llseek(struct file *filp, loff_t offset, int orig)
 82 {
 83     loff_t ret = 0;
 84     switch(orig) {
 85     case 0: /** 從文件開頭位置 seek */
 86         if(offset < 0){
 87             ret = -EINVAL;
 88             break;
 89         }
 90         if((unsigned int)offset > GLOBALFIFO_SIZE){
 91             ret = -EINVAL;
 92             break;
 93         }
 94         filp->f_pos = (unsigned int)offset;
 95         ret = filp->f_pos;
 96         break;
 97     case 1: /** 從文件當前位置開始 seek */
 98         if((filp->f_pos + offset) > GLOBALFIFO_SIZE){
 99             ret = -EINVAL;
100             break;
101         }
102         if((filp->f_pos + offset) < 0){
103             ret = -EINVAL;
104             break;
105         }
106         filp->f_pos += offset;
107         ret = filp->f_pos;
108         break;
109     default:
110         ret = -EINVAL;
111         break;
112     }
113 
114     return ret;
115 }
116 
117 static ssize_t globalfifo_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
118 {
119     unsigned int count = size;
120     int ret = 0;
121     struct globalfifo_dev *dev = filp->private_data;
122     
123     DECLARE_WAITQUEUE(wait, current);   ///< 將當前進程加入到 wait 等待隊列
124     mutex_lock(&dev->mutex);
125     add_wait_queue(&dev->w_wait, &wait);   ///< 添加等待隊列元到讀隊列頭中
126 
127     /** 判斷設備是否可寫 */
128     while(dev->current_len == GLOBALFIFO_SIZE){
129         /** 如果非阻塞訪問, 設備忙時, 直接返回 -EAGAIN */
130         if(filp->f_flags & O_NONBLOCK) {
131             ret = -EAGAIN;
132             goto out;
133         }
134         
135         __set_current_state(TASK_INTERRUPTIBLE);    ///<改變進程狀態爲睡眠
136         schedule();
137         if(signal_pending(current)){    ///< 由於信號而喚醒
138             ret = -ERESTARTSYS;
139             goto out2;
140         }
141     }
142 
143     if(count > GLOBALFIFO_SIZE - dev->current_len)
144         count = GLOBALFIFO_SIZE - dev->current_len;
145     
146     if(copy_from_user(dev->mem + dev->current_len, buf, count)){
147         ret = -EFAULT;
148         goto out;
149     } else {
150         dev->current_len += count;
151         printk(KERN_INFO "written %u bytes(s), current len:%d\n", count, dev->current_len);
152 
153         wake_up_interruptible(&dev->r_wait);    ///< 喚醒讀等待隊列
154         ret = count;
155     }
156 out:
157     mutex_unlock(&dev->mutex);
158 out2:
159     remove_wait_queue(&dev->w_wait, &wait); ///< 移除等待隊列
160     set_current_state(TASK_RUNNING);
161     return ret;
162 }
163 
164 /**
165  * *ppos 是要讀的位置相對於文件開頭的偏移,若是該偏移大於或等於 GLOBALFIFO_SIZE,意味着已經獨到文件末尾
166  */
167 static ssize_t globalfifo_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
168 {
169     unsigned int count = size;
170     int ret = 0;
171     struct globalfifo_dev *dev = filp->private_data;
172 
173     DECLARE_WAITQUEUE(wait, current);   ///< 將當前進程加入到 wait 等待隊列
174     mutex_lock(&dev->mutex);
175     add_wait_queue(&dev->r_wait, &wait);   ///< 添加等待隊列元到讀隊列頭中
176 
177     /** 等待 FIFO 非空,即判斷設備是否可讀 */
178     while(dev->current_len == 0) {
179         /** 如果非阻塞訪問, 設備忙時, 直接返回 -EAGAIN */
180         /** filp->f_flags 是用戶空間 */
181         if(filp->f_flags & O_NONBLOCK) {
182             ret = -EAGAIN;
183             goto out;
184         }
185 
186         /** 
187          *  阻塞訪問,調度其餘進程執行 
188          *  FIFO 爲空的狀況下,讀進程阻塞,必須依賴寫進程往 FIFO 裏面寫東西喚醒它;
189          *  但寫的進程爲了 FIFO,它必須拿到這個互斥體來訪問 FIFO 這個臨界資源;
190          *  若是讀進程把本身調度出去以前不釋放這個互斥體,那麼讀寫進程之間就死鎖了
191          */
192         __set_current_state(TASK_INTERRUPTIBLE);    ///<改變進程狀態爲睡眠
193         mutex_unlock(&dev->mutex);
194         schedule();
195         if(signal_pending(current)){    ///< 由於信號而喚醒
196             ret = -ERESTARTSYS;
197             goto out2;
198         }
199 
200         mutex_lock(&dev->mutex);
201     }
202 
203     /** 要讀取的字節數大於設備文件中的有效數據長度 */
204     if(count > dev->current_len)
205         count = dev->current_len;
206     
207     /** 從用戶空間拷貝數據 */
208     if(copy_to_user(buf, dev->mem, count)) {
209         ret = -EFAULT;
210         goto out;
211     } else {
212         /** FIFO 中數據前移 */
213         memcpy(dev->mem, dev->mem + count, dev->current_len - count);
214         dev->current_len -= count;  ///< 有效數據長度減小
215         printk(KERN_INFO "read %u bytes(s), current_len: %d\n", count, dev->current_len);
216 
217         wake_up_interruptible(&dev->w_wait);    ///< 喚醒寫等待隊列
218 
219         ret = count;
220     }
221 out:
222     mutex_unlock(&dev->mutex);
223 out2:
224     remove_wait_queue(&dev->r_wait, &wait); ///< 移除等待隊列
225     set_current_state(TASK_RUNNING);
226     return ret;
227 }
228 
229 static const struct file_operations globalfifo_fops = {
230     .owner = THIS_MODULE,
231     .llseek = globalfifo_llseek,
232     .read = globalfifo_read,
233     .write = globalfifo_write,
234     .unlocked_ioctl = globalfifo_ioctl,
235     .open = globalfifo_open,
236     .release = globalfifo_release,
237 };
238 
239 
240 /**
241  * @brief  globalfifo_setup_cdev     
242  *
243  * @param  dev
244  * @param  index    次設備號
245  */
246 static void globalfifo_setup_cdev(struct globalfifo_dev *dev, int index)
247 {
248     int err;
249     int devno = MKDEV(globalfifo_major, index);
250 
251     /** 使用 cdev_init 便是靜態初始化了 cdev */
252     cdev_init(&dev->cdev, &globalfifo_fops);
253     dev->cdev.owner = THIS_MODULE;
254 
255     /** 設備編號範圍設置爲1,表示咱們只申請了一個設備 */
256     err = cdev_add(&dev->cdev, devno, 1);
257     if(err)
258         printk(KERN_NOTICE "Error %d adding globalfifo%d\n", err, index);
259 }
260 
261 static int __init globalfifo_init(void)
262 {
263     int ret;
264     int i;
265     dev_t devno = MKDEV(globalfifo_major, 0);
266 
267     if(globalfifo_major)
268         ret = register_chrdev_region(devno, DEVICE_NUMBER, "globalfifo");
269     else {
270         ret = alloc_chrdev_region(&devno, 0, DEVICE_NUMBER, "globalfifo");
271         globalfifo_major = MAJOR(devno);
272     }
273 
274     if(ret < 0)
275         return ret;
276 
277     globalfifo_devp = kzalloc(sizeof(struct globalfifo_dev), GFP_KERNEL);
278     if(!globalfifo_devp){
279         ret = -ENOMEM;
280         goto fail_malloc;
281     }
282 
283     for(i = 0; i < DEVICE_NUMBER; i++){
284         globalfifo_setup_cdev(globalfifo_devp + i, i);
285     }
286     
287     mutex_init(&globalfifo_devp->mutex);
288 
289     /** 初始化讀寫等待隊列 */
290     init_waitqueue_head(&globalfifo_devp->r_wait);
291     init_waitqueue_head(&globalfifo_devp->w_wait);
292 
293 fail_malloc:
294     unregister_chrdev_region(devno, 1);
295     return ret;
296 }
297 
298 static void __exit globalfifo_exit(void)
299 {
300     int i;
301     for(i = 0; i < DEVICE_NUMBER; i++) {
302         cdev_del(&(globalfifo_devp + i)->cdev);
303     }
304     kfree(globalfifo_devp);
305     unregister_chrdev_region(MKDEV(globalfifo_major, 0), 1);
306 }
307 
308 module_init(globalfifo_init);
309 module_exit(globalfifo_exit);

  編譯驗證:指針

  插入模塊:insmod globalfifo.kocode

  建立設備節點:mknod /dev/globalfifo c 230 0blog

  啓動兩個進程:隊列

    • 讀進程,在後臺運行:cat /dev/globalfifo &
    • 寫進程,在前臺運行:echo 'hello world' > /dev/globalfifo
相關文章
相關標籤/搜索