poll源碼剖析

Poll系統調用,是在指定時間內輪詢一定數量的文件描述符,以測試是否有就緒者。

函數原型:

int poll (struct poddfd *fds, nfds_t nfds, int timeout);

 

· fds參數是一個pollfd結構類型的數組,指定所有感興趣的文件描述符上發生的可讀,可寫和異常等事件。

· nfds參數指定被監聽事件集合fds的大小。

    typedef unsigned long int nfds_t;

· timeout參數指定poll的超時值,單位是毫秒。

  當超時爲-1時,輪詢調用將一直阻塞,直到某個事件發生;當超時爲0時,輪詢調用立即返回。

 

基本數據結構

一個pollfd結構類型的數組,指定所有感興趣的文件描述符上發生的可讀,可寫和異常等事件。

fd是文件描述符;事件是註冊的事件,即監聽FD上的事件; revents中是指實際發生的事情,由內核填充。

struct pollfd {
	int fd;
	short events;
	short revents;
};

poll_wqueues:

struct poll_wqueues {
	poll_table pt;
	struct poll_table_page * table;
	int error;
};

poll_table_entry:

struct poll_table_entry {
	struct file * filp;
	wait_queue_t wait;/* 等待隊列*/
	wait_queue_head_t * wait_address;
};

poll_list:

struct poll_list {
	struct poll_list *next;
	int len;
	struct pollfd entries[0];
};

鏈表結點由一個指向struct poll_list的指針掌控,而衆多strut pollfd就通過struct list的entries成員訪問。

每個鏈表的節點是一個page大小(通常是4K)

 

基本結構關係:

 

 

 

 

Poll系統調用原理:

    先註冊回調函數__poll_wait,再初始化table variable(類型爲struct poll_wqueues);拷貝用戶傳入的struct pollfd;

    輪流調用所有FD對應的輪詢(把current掛到每個FD對應的設備等待隊列上)。在設備收到一條消息或填寫完文件數據(磁盤設備)後,會喚醒設備等待隊列上的進程,這時current便被喚醒了。

    當前喚醒後離開sys_poll。

 

(主要基於內核源代碼2.6.9版本,在FD \ select.c中)

sys_poll

asmlinkage long sys_poll(struct pollfd __user * ufds, unsigned int nfds, long timeout)
{
	struct poll_wqueues table;
 	int fdcount, err;
 	unsigned int i;
	struct poll_list *head;
 	struct poll_list *walk;

	/* Do a sanity check on nfds ... OPEN_MAX=256*/
	if (nfds > current->files->max_fdset && nfds > OPEN_MAX)
		return -EINVAL;

	if (timeout) {
		/* Careful about overflow in the intermediate values */
		if ((unsigned long) timeout < MAX_SCHEDULE_TIMEOUT / HZ)
			timeout = (unsigned long)(timeout*HZ+999)/1000+1;
		else /* Negative or overflow */
			timeout = MAX_SCHEDULE_TIMEOUT;
	}

	poll_initwait(&table);

	head = NULL;
	walk = NULL;
	i = nfds;
	err = -ENOMEM;
	while(i!=0) {
		struct poll_list *pp;
		pp = kmalloc(sizeof(struct poll_list)+
				sizeof(struct pollfd)*
				(i>POLLFD_PER_PAGE?POLLFD_PER_PAGE:i),
					GFP_KERNEL);
		if(pp==NULL)
			goto out_fds;
		pp->next=NULL;
		pp->len = (i>POLLFD_PER_PAGE?POLLFD_PER_PAGE:i);
		if (head == NULL)
			head = pp;
		else
			walk->next = pp;

		walk = pp;
		if (copy_from_user(pp->entries, ufds + nfds-i, 
				sizeof(struct pollfd)*pp->len)) {
			err = -EFAULT;
			goto out_fds;
		}
		i -= pp->len;
	}
	fdcount = do_poll(nfds, head, &table, timeout);

	/* OK, now copy the revents fields back to user space. */
	walk = head;
	err = -EFAULT;
	while(walk != NULL) {
		struct pollfd *fds = walk->entries;
		int j;

		for (j=0; j < walk->len; j++, ufds++) {
			if(__put_user(fds[j].revents, &ufds->revents))
				goto out_fds;
		}
		walk = walk->next;
  	}
	err = fdcount;
	if (!fdcount && signal_pending(current))
		err = -EINTR;
out_fds:
	walk = head;
	while(walk!=NULL) {
		struct poll_list *pp = walk->next;
		kfree(walk);
		walk = pp;
	}
	poll_freewait(&table);
	return err;
}

(1)poll_initwait()

void poll_initwait(struct poll_wqueues *pwq)
{
	init_poll_funcptr(&pwq->pt, __pollwait);
	pwq->error = 0;
	pwq->table = NULL;
}
static inline void init_poll_funcptr(poll_table *pt, poll_queue_proc qproc)
{
	pt->qproc = qproc;
}

註冊回調函數__pollwait,

void __pollwait(struct file *filp, wait_queue_head_t *wait_address, poll_table *_p)
{
	struct poll_wqueues *p = container_of(_p, struct poll_wqueues, pt);
	struct poll_table_page *table = p->table;

	if (!table || POLL_TABLE_FULL(table)) {
		struct poll_table_page *new_table;

		new_table = (struct poll_table_page *) __get_free_page(GFP_KERNEL);
		if (!new_table) {
			p->error = -ENOMEM;
			__set_current_state(TASK_RUNNING);
			return;
		}
		new_table->entry = new_table->entries;
		new_table->next = table;
		p->table = new_table;
		table = new_table;
	}

	/* Add a new entry */

		struct poll_table_entry * entry = table->entry;
		table->entry = entry+1;
		get_file(filp);
		entry->filp = filp;
		entry->wait_address = wait_address;
		init_waitqueue_entry(&entry->wait, current);
		add_wait_queue(wait_address, &entry->wait);
}

(2)調用copy_from_user()

    這裏的循環中,建立鏈表,然後調用copy_from_user將文件描述符從用戶空間拷貝到內核空間。也就是把用戶態的struct pollfd拷進進這些條目中。通常用戶程序的poll調用就監控幾個fd,所以上面這個鏈表通常也就只需要一個節點,即操作系統的一頁。

但是,當用戶傳入的fd很多時,由於poll系統調用每次要把所有的struct pollfd拷進進內核,所以參數傳遞和頁分配此時就成了poll系統調用的性能瓶頸。

/**
 * 從用戶空間複製任意大小的塊。
 */
unsigned long
copy_from_user(void *to, const void __user *from, unsigned long n)
{
	might_sleep();
	BUG_ON((long) n < 0);
	if (access_ok(VERIFY_READ, from, n))
		n = __copy_from_user(to, from, n);
	else
		memset(to, 0, n);
	return n;
}

(3)do_poll()

static int do_poll(unsigned int nfds,  struct poll_list *list,
			struct poll_wqueues *wait, long timeout)
{
	int count = 0;
	poll_table* pt = &wait->pt;

	if (!timeout)
		pt = NULL;
 
	for (;;) {
		struct poll_list *walk;
		set_current_state(TASK_INTERRUPTIBLE);
		walk = list;
		while(walk != NULL) {
			do_pollfd( walk->len, walk->entries, &pt, &count);
			walk = walk->next;
		}
		pt = NULL;
		if (count || !timeout || signal_pending(current))
			break;
		count = wait->error;
		if (count)
			break;
		timeout = schedule_timeout(timeout);
	}
	__set_current_state(TASK_RUNNING);
	return count;
}

在對循環中,直到計數大於0才跳出循環。而count 主要是依靠do_pollfd函數處理。

當用戶傳入的FD很多時(比如1000個),對do_pollfd就會調用很多次,調查效率出現瓶頸。

 

set_current _STATE和signal_pending函數

    保障了當用戶程序在調用調查後掛起時,發信號可以讓程序迅速退出民調調用,而通常的系統調用是不會被信號打斷的。

 

do_pollfd()

static void do_pollfd(unsigned int num, struct pollfd * fdpage,
	poll_table ** pwait, int *count)
{
	int i;

	for (i = 0; i < num; i++) {
		int fd;
		unsigned int mask;
		struct pollfd *fdp;

		mask = 0;
		fdp = fdpage+i;
		fd = fdp->fd;
		if (fd >= 0) {
			struct file * file = fget(fd);
			mask = POLLNVAL;
			if (file != NULL) {
				mask = DEFAULT_POLLMASK;
				if (file->f_op && file->f_op->poll)
					mask = file->f_op->poll(file, *pwait);
				mask &= fdp->events | POLLERR | POLLHUP;
				fput(file);
			}
			if (mask) {
				*pwait = NULL;
				(*count)++;
			}
		}
		fdp->revents = mask;
	}
}

 

    如果FD對應的是某個 socket,do_pollfd調用的就是網絡設備驅動實現的輪詢;

 

    如果FD對應的是某個EXT3文件系統的一個打開文件,那麼do_pollfd調用的就是EXT3文件系統驅動實現的Poll。

這個file- > f_op->poll的是設備驅動程序實現的。

而設備驅動程序的標準實現是:

(1)調用poll_wait,即以設備自己的等待隊列爲參數(通常設備都有自己的等待隊列)

(2)調用struct poll_talbe的回調函數。

 

__pollwait

    回調函數__pollwait的作用是創建一個poll_table_entry數據結構(一次__poll_wait即一次設備poll調用只創建一個poll_table_entry),並通過struct poll_table_entry的wait成員,把currrent掛在設備的等待隊列上,此處的等待隊列是wait_address,對應tcp_poll中的SK-Ⅱ> sk_sleep。

void __pollwait(struct file *filp, wait_queue_head_t *wait_address, poll_table *_p)
{
	struct poll_wqueues *p = container_of(_p, struct poll_wqueues, pt);
	struct poll_table_page *table = p->table;

	if (!table || POLL_TABLE_FULL(table)) {
		struct poll_table_page *new_table;

		new_table = (struct poll_table_page *) __get_free_page(GFP_KERNEL);
		if (!new_table) {
			p->error = -ENOMEM;
			__set_current_state(TASK_RUNNING);
			return;
		}
		new_table->entry = new_table->entries;
		new_table->next = table;
		p->table = new_table;
		table = new_table;
	}

	/* Add a new entry */

		struct poll_table_entry * entry = table->entry;
		table->entry = entry+1;
		get_file(filp);
		entry->filp = filp;
		entry->wait_address = wait_address;
		init_waitqueue_entry(&entry->wait, current);
		add_wait_queue(wait_address, &entry->wait);
}

接着調用tcp_poll(),

unsigned int tcp_poll(struct file *file, struct socket *sock, poll_talbe *wait)

{

    unsigned int mask;

    struct sock *sk = sock->sk;

    struct tcp_sock *tp = tcp_sk(sk);

    poll_wait(file, sk->sk_sleep, wait);

    ......//省略判斷狀態,返回狀態值

}

 

struct sock是socket連接的內核表示,sk->sk_sleep是struct wait_queue_head_t結構類型,這表示的是socket的等待隊列,每一個socket都有自己的一個等待隊列,由內核結構struct sock來維護。

其實大多數驅動實現的時候,此時都調用這個函數poll_wait.

poll_wait(file, sk->sk_slepp, wait);

間接調用p->qproc(file, sk->sk_slepp, wait);

 

總結:

1. 統一處理所有事件類型,只需一個事件集參數。用戶通過pollfd.events傳入感興趣事件,內核通過修改pollfd.revents成員反饋其中就緒的事件,而events成員保持不變,下此調用poll時無須重置pollfd類型的事件集參數。

2. poll和select類似,每次調用都返回整個用戶註冊的事件集合(包括就緒的和未就緒的),應用程序索引就緒文件描述符的時間複雜度爲O(n)。而epoll是在內核中維護一個事件表,epoll_wait的events參數返回就緒的事件,時間複雜度爲O(1).

3. poll和epoll_wait分別用nfds和maxevents參數指定最多監聽多少個文件描述符和事件個數,即65535(cat/proc/sys/fs/file-max)。而select允許監聽的最大文件描述符個數爲1024.

4. poll只能工作在相對低效的LT模式(電平觸發),而epoll可工作在ET高效模式(邊沿觸發)。

5. poll採用輪詢方式,即每次調用都要掃描整個註冊文件描述符集合,並將其中就緒的文件描述符返回個用戶,因此檢測就緒事件的時間複雜度是O(n)。epoll則採用回調方式。內核檢測到就緒的文件描述符,將觸發回調函數,回調函數將該文件描述符上對應的事件插入內核就緒事件隊列。內核最後將該就緒事件隊列的內容拷貝到用戶空間。時間複雜度爲O(1).

 

缺點

 

1. 在sys_poll中的循環中,建立鏈表,然後調用copy_from_user將文件描述符從用戶空間拷貝到內核空間。也就是把用戶態的struct pollfd拷進進這些條目中。通常用戶程序的poll調用就監控幾個fd,所以上面這個鏈表通常也就只需要一個節點,即操作系統的一頁。

但是,當用戶傳入的fd很多時,由於poll系統調用每次要把所有的struct pollfd拷進進內核,所以參數傳遞和頁分配此時就成了poll系統調用的性能瓶頸。

2. 在函數do_poll()中的循環語句中,直到計數大於0才跳出循環。而count 主要是依靠do_pollfd函數處理。

當用戶傳入的FD很多時(比如1000個),對do_pollfd就會調用很多次,調查效率出現瓶頸。

 

應用場景

1. 適用於I/O少,即連接數量少,但活動連接多的情況。socket少於1000個。

2. 沒有其他線程干擾。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章