epoll相關視頻解析:
支撐億級io的底層基石 epoll實戰揭祕
linux多線程之epoll原理剖析與reactor原理及應用
epoll的網絡模型,從redis、memcached到nginx,一起搞定
epoll 是Linux平臺下的一種特有的多路複用IO實現方式,與傳統的 select 相比,epoll 在性能上有很大的提升。
epoll 的創建
要使用 epoll 首先需要調用 epoll_create() 函數創建一個 epoll 的句柄,epoll_create() 函數定義如下:
int epoll_create(int size);
參數 size 是由於歷史原因遺留下來的,現在不起作用。當用戶調用 epoll_create() 函數時,會進入到內核空間,並且調用 sys_epoll_create() 內核函數來創建 epoll 句柄,sys_epoll_create() 函數代碼如下:
asmlinkage long sys_epoll_create(int size)
{
int error, fd = -1;
struct eventpoll *ep;
error = -EINVAL;
if (size <= 0 || (error = ep_alloc(&ep)) < 0) {
fd = error;
goto error_return;
}
fd = anon_inode_getfd("[eventpoll]", &eventpoll_fops, ep);
if (fd < 0)
ep_free(ep);
error_return:
return fd;
}
sys_epoll_create() 主要做兩件事情:
- 調用 ep_alloc() 函數創建並初始化一個 eventpoll 對象。
- 調用 anon_inode_getfd() 函數把 eventpoll 對象映射到一個文件句柄,並返回這個文件句柄。
我們先來看看 eventpoll 這個對象,eventpoll 對象用於管理 epoll 監聽的文件列表,其定義如下:
struct eventpoll {
...
wait_queue_head_t wq;
...
struct list_head rdllist;
struct rb_root rbr;
...
};
先來說明一下 eventpoll 對象各個成員的作用:
- wq: 等待隊列,當調用 epoll_wait(fd) 時會把進程添加到 eventpoll 對象的 wq 等待隊列中。
- rdllist: 保存已經就緒的文件列表。
- rbr: 使用紅黑樹來管理所有被監聽的文件。
下圖展示了 eventpoll 對象與被監聽的文件關係:
由於被監聽的文件是通過 epitem 對象來管理的,所以上圖中的節點都是以 epitem 對象的形式存在的。爲什麼要使用紅黑樹來管理被監聽的文件呢?這是爲了能夠通過文件句柄快速查找到其對應的 epitem 對象。紅黑樹是一種平衡二叉樹,如果對其不瞭解可以查閱相關的文檔。
向 epoll 添加文件句柄
前面介紹了怎麼創建 epoll,接下來介紹一下怎麼向 epoll 添加要監聽的文件。
通過調用 epoll_ctl() 函數可以向 epoll 添加要監聽的文件,其原型如下:
long epoll_ctl(int epfd, int op, int fd,struct epoll_event *event);
下面說明一下各個參數的作用:
1、epfd: 通過調用 epoll_create() 函數返回的文件句柄。
2、op: 要進行的操作,有3個選項:
- EPOLL_CTL_ADD:表示要進行添加操作。
- EPOLL_CTL_DEL:表示要進行刪除操作。
- EPOLL_CTL_MOD:表示要進行修改操作
3、fd: 要監聽的文件句柄。
4、event: 告訴內核需要監聽什麼事。其定義如下:
struct epoll_event {
__uint32_t events; /* Epoll events */
epoll_data_t data; /* User data variable */
};
events 可以是以下幾個宏的集合:
- EPOLLIN :表示對應的文件句柄可以讀(包括對端SOCKET正常關閉);
- EPOLLOUT:表示對應的文件句柄可以寫;
- EPOLLPRI:表示對應的文件句柄有緊急的數據可讀;
- EPOLLERR:表示對應的文件句柄發生錯誤;
- EPOLLHUP:表示對應的文件句柄被掛斷;
- EPOLLET:將EPOLL設爲邊緣觸發(Edge Triggered)模式,這是相對於水平觸發(Level Triggered)來說的。
- EPOLLONESHOT:只監聽一次事件,當監聽完這次事件之後,如果還需要繼續監聽這個socket的話,需要再次把這個socket加入到EPOLL隊列裏。
【文章福利】需要C/C++ Linux服務器架構師學習資料加羣812855908(資料包括C/C++,Linux,golang技術,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒體,CDN,P2P,K8S,Docker,TCP/IP,協程,DPDK,ffmpeg等)
data 用來保存用戶自定義數據。
epoll_ctl() 函數會調用 sys_epoll_ctl() 內核函數,sys_epoll_ctl() 內核函數的實現如下:
asmlinkage long sys_epoll_ctl(int epfd, int op,
int fd, struct epoll_event __user *event)
{
...
file = fget(epfd);
tfile = fget(fd);
...
ep = file->private_data;
mutex_lock(&ep->mtx);
epi = ep_find(ep, tfile, fd);
error = -EINVAL;
switch (op) {
case EPOLL_CTL_ADD:
if (!epi) {
epds.events |= POLLERR | POLLHUP;
error = ep_insert(ep, &epds, tfile, fd);
} else
error = -EEXIST;
break;
...
}
mutex_unlock(&ep->mtx);
...
return error;
}
sys_epoll_ctl() 函數會根據傳入不同 op 的值來進行不同操作,比如傳入 EPOLL_CTL_ADD 表示要進行添加操作,那麼就調用 ep_insert() 函數來進行添加操作。
我們繼續來分析添加操作 ep_insert() 函數的實現:
static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
struct file *tfile, int fd)
{
...
error = -ENOMEM;
// 申請一個 epitem 對象
if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL)))
goto error_return;
// 初始化 epitem 對象
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);
epi->event = *event;
epi->nwait = 0;
epi->next = EP_UNACTIVE_PTR;
epq.epi = epi;
// 等價於: epq.pt->qproc = ep_ptable_queue_proc
init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
// 調用被監聽文件的 poll 接口.
// 這個接口又各自文件系統實現, 如socket的話, 那麼這個接口就是 tcp_poll().
revents = tfile->f_op->poll(tfile, &epq.pt);
...
ep_rbtree_insert(ep, epi); // 把 epitem 對象添加到epoll的紅黑樹中進行管理
spin_lock_irqsave(&ep->lock, flags);
// 如果被監聽的文件已經可以進行對應的讀寫操作
// 那麼就把文件添加到epoll的就緒隊列 rdllink 中, 並且喚醒調用 epoll_wait() 的進程.
if ((revents & event->events) && !ep_is_linked(&epi->rdllink)) {
list_add_tail(&epi->rdllink, &ep->rdllist);
if (waitqueue_active(&ep->wq))
wake_up_locked(&ep->wq);
if (waitqueue_active(&ep->poll_wait))
pwake++;
}
spin_unlock_irqrestore(&ep->lock, flags);
...
return 0;
...
}
被監聽的文件是通過 epitem 對象進行管理的,也就是說被監聽的文件會被封裝成 epitem 對象,然後會被添加到 eventpoll 對象的紅黑樹中進行管理(如上述代碼中的 ep_rbtree_insert(ep, epi))。
tfile->f_op->poll(tfile, &epq.pt) 這行代碼的作用是調用被監聽文件的 poll() 接口,如果被監聽的文件是一個socket句柄,那麼就會調用 tcp_poll(),我們來看看 tcp_poll() 做了什麼操作:
unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
...
poll_wait(file, sk->sk_sleep, wait);
...
return mask;
}
每個 socket 對象都有個等待隊列(waitqueue, 關於等待隊列可以參考文章: 等待隊列原理與實現),用於存放等待 socket 狀態更改的進程。
從上述代碼可以知道,tcp_poll() 調用了 poll_wait() 函數,而 poll_wait() 最終會調用 ep_ptable_queue_proc() 函數,ep_ptable_queue_proc() 函數實現如下:
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))) {
init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
pwq->whead = whead;
pwq->base = epi;
add_wait_queue(whead, &pwq->wait);
list_add_tail(&pwq->llink, &epi->pwqlist);
epi->nwait++;
} else {
epi->nwait = -1;
}
}
ep_ptable_queue_proc() 函數主要工作是把當前 epitem 對象添加到 socket 對象的等待隊列中,並且設置喚醒函數爲 ep_poll_callback(),也就是說,當socket狀態發生變化時,會觸發調用 ep_poll_callback() 函數。ep_poll_callback() 函數實現如下:
static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
{
...
// 把就緒的文件添加到就緒隊列中
list_add_tail(&epi->rdllink, &ep->rdllist);
is_linked:
// 喚醒調用 epoll_wait() 而被阻塞的進程
if (waitqueue_active(&ep->wq))
wake_up_locked(&ep->wq);
...
return 1;
}
ep_poll_callback() 函數的主要工作是把就緒的文件添加到 eventepoll 對象的就緒隊列中,然後喚醒調用 epoll_wait() 被阻塞的進程。
等待被監聽的文件狀態發生改變
把被監聽的文件句柄添加到epoll後,就可以通過調用 epoll_wait() 等待被監聽的文件狀態發生改變。
epoll_wait() 調用會阻塞當前進程,當被監聽的文件狀態發生改變時,epoll_wait() 調用便會返回。
epoll_wait() 系統調用的原型如下:
long epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
各個參數的意義:
- epfd: 調用 epoll_create() 函數創建的epoll句柄。
- events: 用來存放就緒文件列表。
- maxevents: events 數組的大小。
- timeout: 設置等待的超時時間。
epoll_wait() 函數會調用 sys_epoll_wait() 內核函數,而 sys_epoll_wait() 函數最終會調用 ep_poll() 函數,我們來看看 ep_poll() 函數的實現:
static int ep_poll(struct eventpoll *ep,
struct epoll_event __user *events, int maxevents, long timeout)
{
...
// 如果就緒文件列表爲空
if (list_empty(&ep->rdllist)) {
// 把當前進程添加到epoll的等待隊列中
init_waitqueue_entry(&wait, current);
wait.flags |= WQ_FLAG_EXCLUSIVE;
__add_wait_queue(&ep->wq, &wait);
for (;;) {
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); // 讓出CPU, 切換到其他進程進行執行
spin_lock_irqsave(&ep->lock, flags);
}
// 有3種情況會執行到這裏:
// 1. 被監聽的文件集合中有就緒的文件
// 2. 設置了超時時間並且超時了
// 3. 接收到信號
__remove_wait_queue(&ep->wq, &wait);
set_current_state(TASK_RUNNING);
}
/* 是否有就緒的文件? */
eavail = !list_empty(&ep->rdllist);
spin_unlock_irqrestore(&ep->lock, flags);
if (!res && eavail
&& !(res = ep_send_events(ep, events, maxevents)) && jtimeout)
goto retry;
return res;
}
ep_poll() 函數主要做以下幾件事:
1、判斷被監聽的文件集合中是否有就緒的文件,如果有就返回。
2、如果沒有就把當前進程添加到epoll的等待隊列中,並且進入睡眠。
3、進程會一直睡眠直到有以下幾種情況發生:
- 被監聽的文件集合中有就緒的文件
- 設置了超時時間並且超時了
- 接收到信號
4、如果有就緒的文件,那麼就調用 ep_send_events() 函數把就緒文件複製到 events 參數中。
5、返回就緒文件的個數。
最後,我們通過一張圖來總結epoll的原理:
下面通過文字來描述一下這個過程:
- 通過調用 epoll_create() 函數創建並初始化一個 eventpoll 對象。
- 通過調用 epoll_ctl() 函數把被監聽的文件句柄 (如socket句柄) 封裝成 epitem 對象並且添加到
eventpoll 對象的紅黑樹中進行管理。 - 通過調用 epoll_wait() 函數等待被監聽的文件狀態發生改變。
- 當被監聽的文件狀態發生改變時(如socket接收到數據),會把文件句柄對應 epitem 對象添加到 eventpoll 對象的就緒隊列 rdllist 中。並且把就緒隊列的文件列表複製到 epoll_wait() 函數的 events 參數中。
- 喚醒調用 epoll_wait() 函數被阻塞(睡眠)的進程。