poll(2)

poll(2) 系统调用的功能和 select(2) 类似:等待一个文件集合中的文件描述符就绪进行I/O操作。

select(2) 的局限性:

  • 关注的文件描述符集合大小最大只有 1024
  • 文件描述符集合为顺序的,不能任意指定 fd,浪费占用的fd

poll(2) 对 select(2) 的改进,关注的文件描述符集合为动态大小,文件描述可以任意指定。

struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
}; - fd 为关注的文件描述符
- events 为关注的事件(输入),使用位掩码来表示事件
- revents 为就绪的事件(输出),同样使用位掩码表示 #include <poll.h> int poll(struct pollfd *fds, nfds_t nfds, int timeout); - \fds 为文件描述符集合的地址
- \nfds 为文件描述符集合的长度
- \timeout 为超时的时间,单位为 毫秒 返回值为 revents 不为 0 的个数,出错返回 -1

一个简单的例子:等待标准输入就绪,超时时间为3s。

#include <poll.h>
#include <unistd.h>
#include <stdio.h> int main()
{
int timeout = 3000; struct pollfd fds = {0};
fds.events |= POLLIN; // fd = 0 等待标准输入 int ret = poll(&fds, 1, timeout);
if (ret == -1)
printf("error poll\n");
else if (ret)
printf("data is avaliable now.\n");
else
printf("no data within 3000 ms.\n"); }

实现

代码位于在 fs/select.c 中,参考中的链接有一些关于文件回调和poll结构的说明

poll()

SYSCALL_DEFINE3(poll, struct pollfd __user *, ufds, unsigned int, nfds,
int, timeout_msecs)
{
struct timespec64 end_time, *to = NULL;
int ret; if (timeout_msecs >= 0) {
to = &end_time;
poll_select_set_timeout(to, timeout_msecs / MSEC_PER_SEC,
NSEC_PER_MSEC * (timeout_msecs % MSEC_PER_SEC));
} ret = do_sys_poll(ufds, nfds, to); if (ret == -EINTR) {
struct restart_block *restart_block; restart_block = &current->restart_block;
restart_block->fn = do_restart_poll;
restart_block->poll.ufds = ufds;
restart_block->poll.nfds = nfds; if (timeout_msecs >= 0) {
restart_block->poll.tv_sec = end_time.tv_sec;
restart_block->poll.tv_nsec = end_time.tv_nsec;
restart_block->poll.has_timeout = 1;
} else
restart_block->poll.has_timeout = 0; ret = -ERESTART_RESTARTBLOCK;
}
return ret;
}

poll() 代码很简单:

  1. 处理超时时间
  2. 实现 poll(2)
  3. 处理后事:判断是否超时或者重新调用。

do_sys_poll()


static int do_sys_poll(struct pollfd __user *ufds, unsigned int nfds,
struct timespec64 *end_time)
{
struct poll_wqueues table;
int err = -EFAULT, fdcount, len, size;
/* Allocate small arguments on the stack to save memory and be
faster - use long to make sure the buffer is aligned properly
on 64 bit archs to avoid unaligned access */
long stack_pps[POLL_STACK_ALLOC/sizeof(long)]; // 256 字节大小
struct poll_list *const head = (struct poll_list *)stack_pps;
struct poll_list *walk = head;
unsigned long todo = nfds; if (nfds > rlimit(RLIMIT_NOFILE)) // 最大打开的文件数量限制
return -EINVAL; // N_STACK_PPS = (256 - 16) / 8 = 30, 栈空间可以保存 30 个pollfd结构
// 将用户空间的 struct pollfd 部分移动至栈空间内的数组中
len = min_t(unsigned int, nfds, N_STACK_PPS);
for (;;) {
walk->next = NULL;
walk->len = len;
if (!len)
break; if (copy_from_user(walk->entries, ufds + nfds-todo,
sizeof(struct pollfd) * walk->len))
goto out_fds; todo -= walk->len;
if (!todo)
break; // POLLFD_PER_PAGE = (4096 - 16) / 8 = 510
// 申请页,每页可容纳 510 个 pollfd 结构
len = min(todo, POLLFD_PER_PAGE);
size = sizeof(struct poll_list) + sizeof(struct pollfd) * len;
walk = walk->next = kmalloc(size, GFP_KERNEL);
if (!walk) {
err = -ENOMEM;
goto out_fds;
}
}
// 将所有的pollfd 结构移动至以 head 为首地址的内核空间中 poll_initwait(&table); // 初始化 table,详见 select 中的分析,见下参考
fdcount = do_poll(head, &table, end_time);
poll_freewait(&table); // 释放 table // 将 revents 复制到用户空间
for (walk = head; walk; walk = walk->next) {
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;
} err = fdcount;
out_fds:
walk = head->next;
while (walk) {
struct poll_list *pos = walk;
walk = walk->next;
kfree(pos);
} return err;
}

do_sys_poll() 函数也是分为三步实现

  1. 将用户空间的数据复制到内核空间
  2. 调用核心实现 do_poll()
  3. 将就绪的事件数据从内核空间复制到用户空间

do_poll()

static int do_poll(struct poll_list *list, struct poll_wqueues *wait,
struct timespec64 *end_time)
{
poll_table* pt = &wait->pt;
ktime_t expire, *to = NULL;
int timed_out = 0, count = 0;
u64 slack = 0;
__poll_t busy_flag = net_busy_loop_on() ? POLL_BUSY_LOOP : 0;
unsigned long busy_start = 0; /* Optimise the no-wait case */
if (end_time && !end_time->tv_sec && !end_time->tv_nsec) {
pt->_qproc = NULL;
timed_out = 1;
} if (end_time && !timed_out)
slack = select_estimate_accuracy(end_time); // 估算进程等待的时间,函数返回 纳秒 for (;;) {
struct poll_list *walk;
bool can_busy_loop = false; for (walk = list; walk != NULL; walk = walk->next) {
struct pollfd * pfd, * pfd_end; pfd = walk->entries;
pfd_end = pfd + walk->len;
for (; pfd != pfd_end; pfd++) { // 对所有的 struct pollfd 遍历处理,do_pollfd 为单独处理一个 fd 的函数
/*
* Fish for events. If we found one, record it
* and kill poll_table->_qproc, so we don't
* needlessly register any other waiters after
* this. They'll get immediately deregistered
* when we break out and return.
*/
if (do_pollfd(pfd, pt, &can_busy_loop,
busy_flag)) {
count++;
pt->_qproc = NULL;
/* found something, stop busy polling */
busy_flag = 0;
can_busy_loop = false;
}
}
}
/*
* All waiters have already been registered, so don't provide
* a poll_table->_qproc to them on the next loop iteration.
*/
pt->_qproc = NULL;
if (!count) {
count = wait->error;
if (signal_pending(current))
count = -EINTR;
}
if (count || timed_out)
break; /* only if found POLL_BUSY_LOOP sockets && not out of time */
if (can_busy_loop && !need_resched()) {
if (!busy_start) {
busy_start = busy_loop_current_time();
continue;
}
if (!busy_loop_timeout(busy_start))
continue;
}
busy_flag = 0; /*
* If this is the first loop and we have a timeout
* given, then we convert to ktime_t and set the to
* pointer to the expiry value.
*/
if (end_time && !to) {
expire = timespec64_to_ktime(*end_time);
to = &expire;
} if (!poll_schedule_timeout(wait, TASK_INTERRUPTIBLE, to, slack)) // 调度直到超时
timed_out = 1;
}
return count;
}

这个函数写的很清楚了,也有很多注释

  1. can_busy_loop 是和 CONFIG_NET_RX_BUSY_POLL 配置相关的,不算通用处理情况,先忽略不考虑
  2. count 为函数的返回值,在 do_pollfd 有返回匹配的掩码时递增,为就绪的文件描述符数量,无就绪文件的时候为等待队列中的错误码
  3. pt->_qproc 为文件poll操作调用的函数,= NULL 的操作在注释中已经说明,函数已经注册到队列中,不必再次注册. 这个函数相关的内容可以在另外一篇 select(2) 找到具体的说明
/*
* Fish for events. If we found one, record it and kill poll_table->_qproc, so we don't
* needlessly register any other waiters after this. They'll get immediately deregistered
* when we break out and return.
*/ /*
* All waiters have already been registered, so don't provide a poll_table->_qproc to them on the next loop iteration.
*/

do_pollfd()

/*
* Fish for pollable events on the pollfd->fd file descriptor. We're only
* interested in events matching the pollfd->events mask, and the result
* matching that mask is both recorded in pollfd->revents and returned. The
* pwait poll_table will be used by the fd-provided poll handler for waiting,
* if pwait->_qproc is non-NULL.
*/
static inline __poll_t do_pollfd(struct pollfd *pollfd, poll_table *pwait,
bool *can_busy_poll,
__poll_t busy_flag)
{
__poll_t mask;
int fd; mask = 0;
fd = pollfd->fd;
if (fd >= 0) {
struct fd f = fdget(fd);
mask = EPOLLNVAL; // 0x20
if (f.file) {
/* userland u16 ->events contains POLL... bitmap */
// 设置关注的事件
__poll_t filter = demangle_poll(pollfd->events) |
EPOLLERR | EPOLLHUP;
mask = DEFAULT_POLLMASK; // (EPOLLIN | EPOLLOUT | EPOLLRDNORM | EPOLLWRNORM)
if (f.file->f_op->poll) {
pwait->_key = filter;
pwait->_key |= busy_flag; // key 在唤醒函数的时候用到
mask = f.file->f_op->poll(f.file, pwait); // 获取就绪的文件掩码
if (mask & busy_flag)
*can_busy_poll = true;
}
/* Mask out unneeded events. */
mask &= filter; // 将文件返回的事件掩码与关注的事件做与操作得到 关注的就绪事件掩码
fdput(f);
}
}
/* ... and so does ->revents */
pollfd->revents = mangle_poll(mask); // 设置就绪掩码 return mask;
}

讨论在不考虑错误的情况下,

poll(2) 返回的是revents 非 0 的个数,在 do_pollfd() 中返回一个非 0 的 mask,poll(2) 返回的 count 就 +1。

mask = 0 有两种可能:

  1. 和 filter 做与运算,但是这样做有一个前提就是可以取到 fd
  2. fd < 0,这种属于无意义的fd了,属于用户的问题

在已了解的fd中: eventfd 和普通的文件poll函数返回情况

  • EPOLLIN 或者 EPOLLOUT 或两个都存在
  • (EPOLLIN | EPOLLOUT | EPOLLRDNORM | EPOLLWRNORM)

当关注的事件不在以上事件中,是可能返回 0,而count不增加的

struct pollfd fds[n];
rn = poll(fds, n, 0);
for (int i = 0; i < rn; ++i)
if (fds[i].revents ...)

像上面这种操作是有风险的,会访问不到rn之后的fd。

mangle_poll() 设置就绪掩码

展开一下 就绪掩码的设置函数, __MAP 函数有点绕, 大概就是将 v & from 转换至靠近 to 大小的数值,没太明白为什么这么做。在 4.17 内核中 POLLIN 和 EPOLLIN 这类宏定义大小是一样的。

#define __MAP(v, from, to) \
(from < to ? (v & from) * (to/from) : (v & from) / (from/to)) static inline __poll_t demangle_poll(u16 val) {
return (__force __poll_t)__MAP(val, POLLIN, (__force __u16)EPOLLIN) |
(__force __poll_t)__MAP(val, POLLOUT, (__force __u16)EPOLLOUT) |
(__force __poll_t)__MAP(val, POLLPRI, (__force __u16)EPOLLPRI) |
(__force __poll_t)__MAP(val, POLLERR, (__force __u16)EPOLLERR) |
(__force __poll_t)__MAP(val, POLLNVAL, (__force __u16)EPOLLNVAL) |
(__force __poll_t)__MAP(val, POLLRDNORM,
(__force __u16)EPOLLRDNORM) |
(__force __poll_t)__MAP(val, POLLRDBAND,
(__force __u16)EPOLLRDBAND) |
(__force __poll_t)__MAP(val, POLLWRNORM,
(__force __u16)EPOLLWRNORM) |
(__force __poll_t)__MAP(val, POLLWRBAND,
(__force __u16)EPOLLWRBAND) |
(__force __poll_t)__MAP(val, POLLHUP, (__force __u16)EPOLLHUP) |
(__force __poll_t)__MAP(val, POLLRDHUP, (__force __u16)EPOLLRDHUP) |
(__force __poll_t)__MAP(val, POLLMSG, (__force __u16)EPOLLMSG);
}

参考

select 源码分析,上一篇写的关于 select 的分析,有一些关于 poll 结构和文件回调的分析。

poll(2) 源码分析的更多相关文章

  1. zookeeper源码分析之五服务端(集群leader)处理请求流程

    leader的实现类为LeaderZooKeeperServer,它间接继承自标准ZookeeperServer.它规定了请求到达leader时需要经历的路径: PrepRequestProcesso ...

  2. zookeeper源码分析之四服务端(单机)处理请求流程

    上文: zookeeper源码分析之一服务端启动过程 中,我们介绍了zookeeper服务器的启动过程,其中单机是ZookeeperServer启动,集群使用QuorumPeer启动,那么这次我们分析 ...

  3. zookeeper源码分析之三客户端发送请求流程

    znode 可以被监控,包括这个目录节点中存储的数据的修改,子节点目录的变化等,一旦变化可以通知设置监控的客户端,这个功能是zookeeper对于应用最重要的特性,通过这个特性可以实现的功能包括配置的 ...

  4. MyCat源码分析系列之——BufferPool与缓存机制

    更多MyCat源码分析,请戳MyCat源码分析系列 BufferPool MyCat的缓冲区采用的是java.nio.ByteBuffer,由BufferPool类统一管理,相关的设置在SystemC ...

  5. MyCat源码分析系列之——前后端验证

    更多MyCat源码分析,请戳MyCat源码分析系列 MyCat前端验证 MyCat的前端验证指的是应用连接MyCat时进行的用户验证过程,如使用MySQL客户端时,$ mysql -uroot -pr ...

  6. Java并发包源码分析

    并发是一种能并行运行多个程序或并行运行一个程序中多个部分的能力.如果程序中一个耗时的任务能以异步或并行的方式运行,那么整个程序的吞吐量和可交互性将大大改善.现代的PC都有多个CPU或一个CPU中有多个 ...

  7. MyBatis源码分析(3)—— Cache接口以及实现

    @(MyBatis)[Cache] MyBatis源码分析--Cache接口以及实现 Cache接口 MyBatis中的Cache以SPI实现,给需要集成其它Cache或者自定义Cache提供了接口. ...

  8. 【JUC】JDK1.8源码分析之ArrayBlockingQueue(三)

    一.前言 在完成Map下的并发集合后,现在来分析ArrayBlockingQueue,ArrayBlockingQueue可以用作一个阻塞型队列,支持多任务并发操作,有了之前看源码的积累,再看Arra ...

  9. 【JUC】JDK1.8源码分析之LinkedBlockingQueue(四)

    一.前言 分析完了ArrayBlockingQueue后,接着分析LinkedBlockingQueue,与ArrayBlockingQueue不相同,LinkedBlockingQueue底层采用的 ...

随机推荐

  1. CodeForces 416 B Appleman and Tree DP

    Appleman and Tree 题解: 定义dp[u][1] 为以u的子树范围内,u这个点已经和某个黑点相连的方案数. dp[u][0] 为在u的子树范围内, u这个点还未和某个黑点相连的方案数. ...

  2. Maven学习归纳(二)——几个常用命令解析

    Maven的常用命令 第一次执行命令的时候,因为需要下载执行命令的基础环境,所以会从远程仓库下载该环境到本地仓库中 运行mvn命令,必须在pom.xml文件所在的目录 一. JavaProject的p ...

  3. 浅谈独立特征(independent features)、潜在特征(underlying features)提取、以及它们在网络安全中的应用

    1. 关于特征提取 0x1:什么是特征提取 特征提取研究的主要问题是,如何在数据集未明确表示结果的前提下,从中提取出重要的潜在特征来.和无监督聚类一样,特征提取算法的目的不是为了预测,而是要尝试对数据 ...

  4. SpringBoot 2 快速整合 | Hibernate Validator 数据校验

    概述 在开发RESTFull API 和普通的表单提交都需要对用户提交的数据进行校验,例如:用户姓名不能为空,年龄必须大于0 等等.这里我们主要说的是后台的校验,在 SpringBoot 中我们可以通 ...

  5. Docker的优缺点

    Docker解决的问题 由于不同的机器有不同的操作系统,以及不同的库和组件,将一个应用程序部署到多台机器上需要进行大量的环境配置操作.(例如经常出现的类似"在我的机器上就没问题"这 ...

  6. apache ignite系列(八):问题汇总

    1,java.lang.ClassNotFoundException Unknown pair 1.Please try to turn on isStoreKeepBinary in cache s ...

  7. 腾讯云和阿里云部署web 项目tomcat 日志 中文变成问号

    在部署项目到云上的时候,遇到了tomcat logs 日志中文变问号的问题,今天终于得到解决了 这是中文变成问号的的截图 打开到tomcat bin 目录的文件夹 找到catalina.sh  文件 ...

  8. Linux 笔记 - 第六章 Linux 磁盘管理

    博客地址:http://www.moonxy.com 一.前言 1.1 硬盘 硬盘一般分为 IDE 硬盘.SCSI 硬盘和 SATA 硬盘.在 Linux 中,IDE 接口的设备被称为 hd,SCSI ...

  9. activity的隐式和显式启动

    显式Intent(Explicit intent):通过指定Intent组件名称来实现的,它一般用在知道目标组件名称的前提下,一般是在相同的应用程序内部实现的. 隐式Intent(Implicit i ...

  10. mysql重新设置递增值

    alter table table_name AUTO_INCREMENT=value;