【轉載】Select函數實現原理分析

Select函數實現原理分析html

<原文>ide

select須要驅動程序的支持,驅動程序實現fops內的poll函數。select經過每一個設備文件對應的poll函數提供的信息判斷當前是否有資源可用(如可讀或寫),若是有的話則返回可用資源的文件描述符個數,沒有的話則睡眠,等待有資源變爲可用時再被喚醒繼續執行。函數

 

下面咱們分兩個過程來分析select:oop

 

1. select的睡眠過程ui

 

支持阻塞操做的設備驅動一般會實現一組自身的等待隊列如讀/寫等待隊列用於支持上層(用戶層)所需的BLOCK(阻塞)或NONBLOCK(非阻塞)操做。當應用程序經過設備驅動訪問該設備時(默認爲BLOCK操做),若該設備當前沒有數據可讀或寫,則將該用戶進程插入到該設備驅動對應的讀/寫等待隊列讓其睡眠一段時間,等到有數據可讀/寫時再將該進程喚醒。spa

 

select就是巧妙的利用等待隊列機制讓用戶進程適當在沒有資源可讀/寫時睡眠,有資源可讀/寫時喚醒。下面咱們看看select睡眠的詳細過程。.net

 

select會循環遍歷它所監測的fd_set內的全部文件描述符對應的驅動程序的poll函數。驅動程序提供的poll函數首先會將調用select的用戶進程插入到該設備驅動對應資源的等待隊列(如讀/寫等待隊列),而後返回一個bitmask告訴select當前資源哪些可用。當select循環遍歷完全部fd_set內指定的文件描述符對應的poll函數後,若是沒有一個資源可用(即沒有一個文件可供操做),則select讓該進程睡眠,一直等到有資源可用爲止,進程被喚醒(或者timeout)繼續往下執行。unix

 

下面分析一下代碼是如何實現的。code

select的調用path以下:sys_select -> core_sys_select -> do_selecthtm

其中最重要的函數是do_select, 最主要的工做是在這裏, 前面兩個函數主要作一些準備工做。do_select定義以下:

int do_select(int n, fd_set_bits *fds, s64 *timeout)

{

         struct poll_wqueues table;

         poll_table *wait;

         int retval, i;

 

         rcu_read_lock();

         retval = max_select_fd(n, fds);

         rcu_read_unlock();

 

         if (retval < 0)

                   return retval;

         n = retval;

 

         poll_initwait(&table);

         wait = &table.pt;

         if (!*timeout)

                   wait = NULL;

         retval = 0;        //retval用於保存已經準備好的描述符數,初始爲0

         for (;;) {

                   unsigned long *rinp, *routp, *rexp, *inp, *outp, *exp;

                   long __timeout;

 

                   set_current_state(TASK_INTERRUPTIBLE);    //將當前進程狀態改成TASK_INTERRUPTIBLE

 

                   inp = fds->in; outp = fds->out; exp = fds->ex;

                   rinp = fds->res_in; routp = fds->res_out; rexp = fds->res_ex;

 

                   for (i = 0; i < n; ++rinp, ++routp, ++rexp) { //遍歷每一個描述符

                            unsigned long in, out, ex, all_bits, bit = 1, mask, j;

                            unsigned long res_in = 0, res_out = 0, res_ex = 0;

                            const struct file_operations *f_op = NULL;

                            struct file *file = NULL;

 

                            in = *inp++; out = *outp++; ex = *exp++;

                            all_bits = in | out | ex;

                            if (all_bits == 0) {

                                     i += __NFDBITS;       // //若是這個字沒有待查找的描述符, 跳過這個長字(32位)

                                     continue;

                            }

 

                            for (j = 0; j < __NFDBITS; ++j, ++i, bit <<= 1) {     //遍歷每一個長字裏的每一個位

                                     int fput_needed;

                                     if (i >= n)

                                               break;

                                     if (!(bit & all_bits))

                                               continue;

                                     file = fget_light(i, &fput_needed);

                                     if (file) {

                                               f_op = file->f_op;

                                               MARK(fs_select, "%d %lld",

                                                                 i, (long long)*timeout);

                                               mask = DEFAULT_POLLMASK;

                                               if (f_op && f_op->poll)

/* 在這裏循環調用所監測的fd_set內的全部文件描述符對應的驅動程序的poll函數 */

                                                        mask = (*f_op->poll)(file, retval ? NULL : wait);

                                               fput_light(file, fput_needed);

                                               if ((mask & POLLIN_SET) && (in & bit)) {

                                                        res_in |= bit; //若是是這個描述符可讀, 將這個位置位

                                                        retval++;  //返回描述符個數加1

                                               }

                                               if ((mask & POLLOUT_SET) && (out & bit)) {

                                                        res_out |= bit;

                                                        retval++;

                                               }

                                               if ((mask & POLLEX_SET) && (ex & bit)) {

                                                        res_ex |= bit;

                                                        retval++;

                                               }

                                     }

                                     cond_resched();

                            }

//返回結果

                            if (res_in)

                                     *rinp = res_in;

                            if (res_out)

                                     *routp = res_out;

                            if (res_ex)

                                     *rexp = res_ex;

                   }

                   wait = NULL;

/* 到這裏遍歷結束。retval保存了檢測到的可操做的文件描述符的個數。若是有文件可操做,則跳出for(;;)循環,直接返回。若沒有文件可操做且timeout時間未到同時沒有收到signal,則執行schedule_timeout睡眠。睡眠時間長短由__timeout決定,一直等到該進程被喚醒。

那該進程是如何被喚醒的?被誰喚醒的呢?

咱們看下面的select喚醒過程*/

                   if (retval || !*timeout || signal_pending(current))

                            break;

                  if(table.error) {

                            retval = table.error;

                            break;

                   }

 

                   if (*timeout < 0) {

                            /* Wait indefinitely */

                            __timeout = MAX_SCHEDULE_TIMEOUT;

                   } else if (unlikely(*timeout >= (s64)MAX_SCHEDULE_TIMEOUT - 1)) {

                            /* Wait for longer than MAX_SCHEDULE_TIMEOUT. Do it in a loop */

                            __timeout = MAX_SCHEDULE_TIMEOUT - 1;

                            *timeout -= __timeout;

                   } else {

                            __timeout = *timeout;

                            *timeout = 0;

                   }

                   __timeout = schedule_timeout(__timeout);

                   if (*timeout >= 0)

                            *timeout += __timeout;

         }

         __set_current_state(TASK_RUNNING);

 

         poll_freewait(&table);

 

         return retval;

}

 

2.  select的喚醒過程

前面介紹了select會循環遍歷它所監測的fd_set內的全部文件描述符對應的驅動程序的poll函數。驅動程序提供的poll函數首先會將調用select的用戶進程插入到該設備驅動對應資源的等待隊列(如讀/寫等待隊列),而後返回一個bitmask告訴select當前資源哪些可用。

一個典型的驅動程序poll函數實現以下:

(摘自《Linux Device Drivers – ThirdEdition》Page 165)

static unsigned int scull_p_poll(struct file *filp, poll_table *wait)

{

    struct scull_pipe *dev = filp->private_data;

    unsigned int mask = 0;

    /*

     * The buffer is circular; it is considered full

     * if "wp" is right behind "rp" and empty if the

     * two are equal.

     */

    down(&dev->sem);

    poll_wait(filp, &dev->inq,  wait);

    poll_wait(filp, &dev->outq, wait);

    if (dev->rp != dev->wp)

        mask |= POLLIN | POLLRDNORM;    /* readable */

    if (spacefree(dev))

        mask |= POLLOUT | POLLWRNORM;   /* writable */

    up(&dev->sem);

    return mask;

}

將用戶進程插入驅動的等待隊列是經過poll_wait作的。

Poll_wait定義以下:

static inline void poll_wait(struct file * filp, wait_queue_head_t * wait_address, poll_table *p)

{

         if (p && wait_address)

                   p->qproc(filp, wait_address, p);

}

這裏的p->qproc在do_select內poll_initwait(&table)被初始化爲__pollwait,以下:

void poll_initwait(struct poll_wqueues *pwq)

{

         init_poll_funcptr(&pwq->pt, __pollwait);

         pwq->error = 0;

         pwq->table = NULL;

         pwq->inline_index = 0;

}

__pollwait定義以下:

/* Add a new entry */

static void __pollwait(struct file *filp, wait_queue_head_t *wait_address,

                                     poll_table *p)

{

         struct poll_table_entry *entry = poll_get_entry(p);

         if (!entry)

                   return;

         get_file(filp);

         entry->filp = filp;

         entry->wait_address = wait_address;

         init_waitqueue_entry(&entry->wait, current);

         add_wait_queue(wait_address,&entry->wait);

}

經過init_waitqueue_entry初始化一個等待隊列項,這個等待隊列項關聯的進程即當前調用select的進程。而後將這個等待隊列項插入等待隊列wait_address。Wait_address即在驅動poll函數內調用poll_wait(filp, &dev->inq,  wait);時傳入的該驅動的&dev->inq或者&dev->outq等待隊列。

 

注: 關於等待隊列的工做原理能夠參考下面這篇文檔:

http://blog.chinaunix.net/u2/60011/showart_1334657.html

 

到這裏咱們明白了select如何當前進程插入全部所監測的fd_set關聯的驅動內的等待隊列,那進程到底是什麼時候讓出CPU進入睡眠狀態的呢?

進入睡眠狀態是在do_select內調用schedule_timeout(__timeout)實現的。當select遍歷完fd_set內的全部設備文件,發現沒有文件可操做時(即retval=0),則調用schedule_timeout(__timeout)進入睡眠狀態。

 

喚醒該進程的過程一般是在所監測文件的設備驅動內實現的,驅動程序維護了針對自身資源讀寫的等待隊列。當設備驅動發現自身資源變爲可讀寫而且有進程睡眠在該資源的等待隊列上時,就會喚醒這個資源等待隊列上的進程。

舉個例子,好比內核的8250 uart driver:

Uart是使用的Tty層維護的兩個等待隊列, 分別對應於讀和寫: (uart是tty設備的一種)

struct tty_struct {

         ……

         wait_queue_head_t write_wait;

         wait_queue_head_t read_wait;

         ……

}

當uart設備接收到數據,會調用tty_flip_buffer_push(tty);將收到的數據push到tty層的buffer。

而後查看是否有進程睡眠的讀等待隊列上,若是有則喚醒該等待會列。

過程以下:

serial8250_interrupt -> serial8250_handle_port -> receive_chars -> tty_flip_buffer_push ->

flush_to_ldisc -> disc->receive_buf

在disc->receive_buf函數內:

if (waitqueue_active(&tty->read_wait)) //如有進程阻塞在read_wait上則喚醒

wake_up_interruptible(&tty->read_wait);

 

到這裏明白了select進程被喚醒的過程。因爲該進程是阻塞在全部監測的文件對應的設備等待隊列上的,所以在timeout時間內,只要任意個設備變爲可操做,都會當即喚醒該進程,從而繼續往下執行。這就實現了select的當有一個文件描述符可操做時就當即喚醒執行的基本原理。

 

Referece:

1.       Linux Device Drivers – ThirdEdition

2.       內核等待隊列機制原理分析

http://blog.chinaunix.net/u2/60011/showart_1334657.html

3.       Kernel code : Linux 2.6.18_pro500 - Montavista

相關文章
相關標籤/搜索