花了半天,把epoll的實現大體看了下,這裡稍總結下:
epoll相關的三個使用者態API介面:
1、epoll_create函數
函式宣告:int epoll_create(int size)
該函數產生一個epoll專用的檔案描述符。它其實是在核心申請一空間,用來存放你想關注的socket fd上是否發生以及發生了什麼事件。
size就是你在這個epoll fd上能關注的最大socket fd數。
2、epoll_ctl函數
函式宣告:int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)
該函數用於控制某個epoll檔案描述符上的事件,可以註冊事件,修改事件,刪除事件。
參數:
epfd:由 epoll_create 產生的epoll專用的檔案描述符;
op:要進行的操作例如註冊事件,可能的取值EPOLL_CTL_ADD 註冊、EPOLL_CTL_MOD 修 改、EPOLL_CTL_DEL 刪除
fd:關聯的檔案描述符;
event:指向epoll_event的指標;
如果調用成功返回0,不成功返回-1
3、epoll_wait函數
函式宣告:int epoll_wait(int epfd,struct epoll_event * events,int maxevents,int timeout)
該函數用於輪詢I/O事件的發生;
參數:
epfd:由epoll_create 產生的epoll專用的檔案描述符;
epoll_event:用於回傳代處理事件的數組;
maxevents:每次能處理的事件數目;
timeout:等待I/O事件發生的逾時值(單位我也不太清楚);-1相當於阻塞,0相當於非阻塞。一般用-1即可
返回傳生事件數目
select/poll的缺點在於:
1.每次調用時要重複地從使用者態讀入參數。
2.每次調用時要重複地掃描檔案描述符。
3.每次在調用開始時,要把當前進程放入各個檔案描述符的等待隊列。在調用結束後,又把進程從各個等待隊列中刪除。
在實際應用中,select/poll監視的檔案描述符可能會非常多,如果每次只是返回一小部分,那麼,這種情況下select/poll顯得不夠高效。epoll的設計思路,是把select/poll單個的操作拆分為1個epoll_create+多個epoll_ctrl+一個wait。此外,核心針對epoll操作添加了一個檔案系統”[eventpoll]”,每一個或者多個要監視的檔案描述符都有一個對應的eventpollfs檔案系統的inode節點,主要資訊儲存在eventpoll結構體中。而被監視的檔案的重要訊息則儲存在epitem結構體中。所以他們是一對多的關係。由於在執行epoll_create和epoll_ctrl時,已經把使用者態的資訊儲存到核心態了,所以之後即使反覆地調用epoll_wait,也不會重複地拷貝參數,掃描檔案描述符,反覆地把當前進程放入/放出等待隊列。這樣就避免了以上的三個缺點。
接下去看看它們的實現:
主要代碼路徑與檔案 linux/fs/eventpoll.c linux/include/linux/eventpoll.h
SYSCALL_DEFINE1(epoll_create, int, size){ if (size <= 0) return -EINVAL; return sys_epoll_create1(0);}
SYSCALL_DEFINE1(epoll_create1, int, flags){ int error; struct eventpoll *ep = NULL; /* Check the EPOLL_* constant for consistency. */ BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC); if (flags & ~EPOLL_CLOEXEC) return -EINVAL; /* * Create the internal data structure ("struct eventpoll"). */ error = ep_alloc(&ep); /*申請eventpoll 結構*/ if (error < 0) return error; /* * Creates all the items needed to setup an eventpoll file. That is, * a file structure and a free file descriptor. */ error = anon_inode_getfd("[eventpoll]", &eventpoll_fops, ep,flags & O_CLOEXEC);/*從eventpoll類型檔案系統中申請inode結點,遵循linux中一切皆是檔案的思想anon_inode_getfd 這個函數申請了inode結點,掛載了eventpoll_fops檔案操作函數集,並將ep設為了file->private_data變數,後面可以看到ep都是從private_data中取出來的,最後申請了一個閒置fd,將file與之關聯,最後將fd返回使用者態*/ if (error < 0) ep_free(ep); return error;}
主要資料結構:struct eventpoll { spinlock_t lock; struct mutex mtx; /* Wait queue used by sys_epoll_wait() */ wait_queue_head_t wq; /* Wait queue used by file->poll() */ wait_queue_head_t poll_wait; /* List of ready file descriptors */ struct list_head rdllist; /* RB tree root used to store monitored fd structs */ struct rb_root rbr; /*紅/黑樹狀結構根結點*/ /* * This is a single linked list that chains all the "struct epitem" that * happened while transfering ready events to userspace w/out * holding ->lock. */ struct epitem *ovflist; /* The user that created the eventpoll descriptor */ struct user_struct *user;};
static int ep_alloc(struct eventpoll **pep) /*申請函數*/{ int error; struct user_struct *user; struct eventpoll *ep; user = get_current_user(); error = -ENOMEM; ep = kzalloc(sizeof(*ep), GFP_KERNEL); if (unlikely(!ep)) goto free_uid; spin_lock_init(&ep->lock); /* 對鎖,訊號量 ,各種鏈表進行初始化操作*/ mutex_init(&ep->mtx); init_waitqueue_head(&ep->wq); init_waitqueue_head(&ep->poll_wait); INIT_LIST_HEAD(&ep->rdllist); ep->rbr = RB_ROOT; /* 設定為紅/黑樹狀結構的根結點*/ ep->ovflist = EP_UNACTIVE_PTR; ep->user = user; *pep = ep; return 0;free_uid: free_uid(user); return error;}
create後的資料結構關係如下:
我們繼續看epoll_ctl
SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd, struct epoll_event __user *, event){ int error; struct file *file, *tfile; struct eventpoll *ep; struct epitem *epi; struct epoll_event epds; error = -EFAULT; if (ep_op_has_event(op) && copy_from_user(&epds, event, sizeof(struct epoll_event)))/*從使用者態拷貝至核心態*/ goto error_return; /* Get the "struct file *" for the eventpoll file */ error = -EBADF; file = fget(epfd); /*通過epfd得到file結構 epfd是通過epoll_create建立的*/ if (!file) goto error_return; /* Get the "struct file *" for the target file */ tfile = fget(fd); /*通過fd得到file結構 fd是需要監聽的描述字*/ if (!tfile) goto error_fput; /* The target file descriptor must support poll */ error = -EPERM; if (!tfile->f_op || !tfile->f_op->poll) goto error_tgt_fput; /* * We have to check that the file structure underneath the file descriptor * the user passed to us _is_ an eventpoll file. And also we do not permit * adding an epoll file descriptor inside itself. */ error = -EINVAL; if (file == tfile || !is_file_epoll(file)) goto error_tgt_fput; /* * At this point it is safe to assume that the "private_data" contains * our own data structure. */ ep = file->private_data; /* epoll_create建立的eventpoll結構如此得到*/ mutex_lock(&ep->mtx); /* * Try to lookup the file inside our RB tree, Since we grabbed "mtx" * above, we can be sure to be able to use the item looked up by * ep_find() till we release the mutex. */ epi = ep_find(ep, tfile, fd); /* 去ep裡找fd是否存在對應的epi,epi又是個新的資料結構,見下面, 該函數主要完成紅/黑樹狀結構尋找過程,並返回尋找結構*/ error = -EINVAL; switch (op) { case EPOLL_CTL_ADD: /* 對於ADD來說*/ if (!epi) { /*如果為空白即沒找到,那麼就插入*/ epds.events |= POLLERR | POLLHUP; error = ep_insert(ep, &epds, tfile, fd); /*調用insert進行插入操作*/ } else error = -EEXIST; /*對於新add命令,而之前epi又存在,則返回錯誤*/ break; case EPOLL_CTL_DEL: /* 刪除命令*/ if (epi) error = ep_remove(ep, epi); else error = -ENOENT; break; case EPOLL_CTL_MOD: /* 修改命令*/ if (epi) { epds.events |= POLLERR | POLLHUP; error = ep_modify(ep, epi, &epds); } else error = -ENOENT; break; } mutex_unlock(&ep->mtx);error_tgt_fput: fput(tfile);error_fput: fput(file);error_return: return error;}
主要資料結構: epitem 描述的是一個需要監聽的描述符,通過eventpoll結構中的紅/黑樹狀結構進行聯絡管理struct epitem { /* RB tree node used to link this structure to the eventpoll RB tree */ struct rb_node rbn; /* 紅/黑樹狀結構節點資訊*/ /* List header used to link this structure to the eventpoll ready list */ struct list_head rdllink; /* * Works together "struct eventpoll"->ovflist in keeping the * single linked chain of items. */ struct epitem *next; /* The file descriptor information this item refers to */ struct epoll_filefd ffd; /* Number of active wait queue attached to poll operations */ int nwait; /* List containing poll wait queues */ struct list_head pwqlist; /* The "container" of this item */ struct eventpoll *ep; /* List header used to link this item to the "struct file" items list */ struct list_head fllink; /* The structure that describe the interested events and the source fd */ struct epoll_event event;};
static int ep_insert(struct eventpoll *ep, struct epoll_event *event, struct file *tfile, int fd){ int error, revents, pwake = 0; unsigned long flags; struct epitem *epi; struct ep_pqueue epq; /* pollqueue結構 if (unlikely(atomic_read(&ep->user->epoll_watches) >= max_user_watches)) return -ENOSPC; if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL))) /*申請epi結構 return -ENOMEM; /* Item initialization follow here ... */ INIT_LIST_HEAD(&epi->rdllink); INIT_LIST_HEAD(&epi->fllink); INIT_LIST_HEAD(&epi->pwqlist); epi->ep = ep; ep_set_ffd(&epi->ffd, tfile, fd); /*設定ffd結構*/ epi->event = *event; epi->nwait = 0; epi->next = EP_UNACTIVE_PTR; /* Initialize the poll table using the queue callback */ epq.epi = epi; init_poll_funcptr(&epq.pt, ep_ptable_queue_proc); /*最重要的工作就是設定了這個poll函數*/ revents = tfile->f_op->poll(tfile, &epq.pt); /*進行註冊poll函數的調用,ep_ptable_queue_proc調用過程請結合檔案操作函數集fops調用過程,這裡不再分析*/ error = -ENOMEM; if (epi->nwait < 0) goto error_unregister; spin_lock(&tfile->f_lock); list_add_tail(&epi->fllink, &tfile->f_ep_links); spin_unlock(&tfile->f_lock); ep_rbtree_insert(ep, epi); /* 插入到紅/黑樹狀結構中*/ spin_lock_irqsave(&ep->lock, flags); if ((revents & event->events) && !ep_is_linked(&epi->rdllink)) { list_add_tail(&epi->rdllink, &ep->rdllist); /*如果有期待的事件發生,則將rdllink掛接到rdlist 就緒隊列中去*/ /* Notify waiting tasks that events are available */ if (waitqueue_active(&ep->wq)) wake_up_locked(&ep->wq); /*判斷是否需要喚醒*/ if (waitqueue_active(&ep->poll_wait)) pwake++; } spin_unlock_irqrestore(&ep->lock, flags); atomic_inc(&ep->user->epoll_watches); /* We have to call this outside the lock */ if (pwake) ep_poll_safewake(&ep->poll_wait); /*進行喚醒操作*/ return 0;error_unregister: ep_unregister_pollwait(ep, epi); spin_lock_irqsave(&ep->lock, flags); if (ep_is_linked(&epi->rdllink)) list_del_init(&epi->rdllink); spin_unlock_irqrestore(&ep->lock, flags); kmem_cache_free(epi_cache, epi); return error;}
static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,poll_table *pt){ struct epitem *epi = ep_item_from_epqueue(pt); struct eppoll_entry *pwq; if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) { /* 申請一個eppoll_entry 結構 ,類似於select(poll)中使用的等待結構的那個entry結構 init_waitqueue_func_entry(&pwq->wait, ep_poll_callback); 初始化等待隊列節點,註冊通知回呼函數*/ pwq->whead = whead; pwq->base = epi; add_wait_queue(whead, &pwq->wait); /* 這裡的whead為ep的poll_wait結構,就是紅/黑樹狀結構根結點的poll_wait*/ list_add_tail(&pwq->llink, &epi->pwqlist); epi->nwait++; } else { /* We have to signal that an error occurred */ epi->nwait = -1; }}主要資料結構:struct eppoll_entry { /* List header used to link this structure to the "struct epitem" */ struct list_head llink; /* The "base" pointer is set to the container "struct epitem" */ struct epitem *base; /* * Wait queue item that will be linked to the target file wait * queue head. */ wait_queue_t wait; /* The wait queue head that linked the "wait" wait queue item */ wait_queue_head_t *whead;};struct ep_pqueue { poll_table pt; struct epitem *epi;};
上面的代碼就是ep_insert中要做的最重要的事:建立struct eppoll_entry,設定其喚醒回呼函數為ep_poll_callback,然後加入裝置等待隊列(注意這裡的whead就是上一章所說的每個裝置驅動都要帶的等待隊列)。只有這樣,當裝置就緒,喚醒等待隊列上的等待著時,ep_poll_callback就會被調用。每次調用poll系統調用,作業系統都要把current(當前進程)掛到fd對應的所有裝置的等待隊列上,可以想象,fd多到上千的時候,這樣“掛”法很費事;而每次調用epoll_wait則沒有這麼羅嗦,epoll只在epoll_ctl時把current掛一遍(這第一遍是免不了的)並給每個fd一個命令“好了就調回呼函數”,如果裝置有事件了,通過回呼函數,會把fd放入rdllist,而每次調用epoll_wait就只是收集rdllist裡的fd就可以了——epoll巧妙的利用回呼函數,實現了更高效的事件驅動模型我們弄一幅圖看下期間錯綜複雜的關係
ep_poll_callback會幹什麼了——肯定是把紅/黑樹狀結構上的收到event的epitem(代表每個fd)插入ep->rdllist中,這樣,當epoll_wait返回時,rdllist裡就都是就緒的fd了list_add_tail(&epi->rdllink, &ep->rdllist);我們最後看個wait函數
SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events, int, maxevents, int, timeout){ int error; struct file *file; struct eventpoll *ep; /* The maximum number of event must be greater than zero */ if (maxevents <= 0 || maxevents > EP_MAX_EVENTS) return -EINVAL; /* Verify that the area passed by the user is writeable */ if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event))) { error = -EFAULT; goto error_return; } /* Get the "struct file *" for the eventpoll file */ error = -EBADF; file = fget(epfd); if (!file) goto error_return; /* * We have to check that the file structure underneath the fd * the user passed to us _is_ an eventpoll file. */ error = -EINVAL; if (!is_file_epoll(file)) goto error_fput; /* * At this point it is safe to assume that the "private_data" contains * our own data structure. */ ep = file->private_data; /* Time to fish for events ... */ error = ep_poll(ep, events, maxevents, timeout); /* 最核心的在這裡進行ep_poll,即對ep這個點上面的東西進行poll*/error_fput: fput(file);error_return: return error;}static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events, int maxevents, long timeout){ int res, eavail; unsigned long flags; long jtimeout; wait_queue_t wait; /* * Calculate the timeout by checking for the "infinite" value (-1) * and the overflow condition. The passed timeout is in milliseconds, * that why (t * HZ) / 1000. */ jtimeout = (timeout < 0 || timeout >= EP_MAX_MSTIMEO) ? MAX_SCHEDULE_TIMEOUT : (timeout * HZ + 999) / 1000;retry: spin_lock_irqsave(&ep->lock, flags); res = 0; if (list_empty(&ep->rdllist)) { /*怪不得效率高,只看ep->rdllist */ /* * We don't have any available event to return to the caller. * We need to sleep here, and we will be wake up by * ep_poll_callback() when events will become available. */ init_waitqueue_entry(&wait, current); /*空的話就睡眠,至到被喚醒*/ wait.flags |= WQ_FLAG_EXCLUSIVE; __add_wait_queue(&ep->wq, &wait); for (;;) { /*被喚醒的話就進去處理*/ /* * We don't want to sleep if the ep_poll_callback() sends us * a wakeup in between. That's why we set the task state * to TASK_INTERRUPTIBLE before doing the checks. */ set_current_state(TASK_INTERRUPTIBLE); if (!list_empty(&ep->rdllist) || !jtimeout) break; if (signal_pending(current)) { res = -EINTR; break; } spin_unlock_irqrestore(&ep->lock, flags); jtimeout = schedule_timeout(jtimeout); spin_lock_irqsave(&ep->lock, flags); } __remove_wait_queue(&ep->wq, &wait); set_current_state(TASK_RUNNING); } /* Is it worth to try to dig for events ? */ eavail = !list_empty(&ep->rdllist) || ep->ovflist != EP_UNACTIVE_PTR; spin_unlock_irqrestore(&ep->lock, flags); /* * Try to transfer events to user space. In case we get 0 events and * there's still timeout left over, we go trying again in search of * more luck. */ if (!res && eavail && !(res = ep_send_events(ep, events, maxevents)) && jtimeout) goto retry;/*發事件到使用者態,將準備好的fd等傳到使用者態*/ return res;}