我正在为在Android设备(Nexus 5X)上运行的Linux内核编写内核驱动程序。
我有一个内核缓冲区,我想公开一个设备来读取它。我可以从内核缓冲区读取和写入,但我无法写入从read系统调用接收到的用户空间缓冲区。非常奇怪的是copy_to_user仅适用于少于128个字节...对我来说没有任何意义。
代码如下(截断):
static ssize_t dev_read(struct file *filep, char __user *buffer, size_t len, loff_t *offset){
unsigned long sent;
// ...
pr_err("MYLOGGER: copying from buffer: head=%d, tail=%d, cnt=%d, sent=%lu, access=%lu\n",
head, tail, cnt, sent,
access_ok(VERIFY_WRITE, buffer, sent));
if(sent >= 1) {
sent -= copy_to_user(buffer, mybuf + tail, sent);
pr_err("MYLOGGER: sent %lu bytes\n", sent);
// ...
}
// ...
}
输出如下:
[ 56.476834] MYLOGGER: device opened
[ 56.476861] MYLOGGER: reading from buffer
[ 56.476872] MYLOGGER: copying from buffer: head=5666644, tail=0, cnt=5666644, sent=4096, access=1
[ 56.476882] MYLOGGER: sent 0 bytes
从日志sent可以看到4096,这里没有整数溢出。
使用dd时,我每次通话最多可读取128个字节(dd if=/dev/mylog bs=128)。我认为当使用超过128个字节时dd使用堆中的缓冲区而内核无法再访问它,这是我无法理解的。
我使用copy_to_user系统调用处理程序中的read,我还打印了current->pid,这是相同的过程。
函数copy_to_user在arch / arm64 / include / asm / uaccess.h中定义,__copy_to_user可在arch / arm64 / lib中找到/copy_to_user.S
感谢您的时间,我希望在您宝贵的帮助下摆脱这种疯狂。
- 编辑 -
我已经写了一个小代码片段来获取目标用户空间缓冲区的vm_area_struct并打印出权限,结果就是:
MYLOGGER: buffer belongs to vm_area with permissions rw-p
因此该地址应该是可写的......
- 编辑 -
我编写了更多调试代码,记录了用户空间缓冲区使用的内存页面的状态。
MYLOGGER: page=(0x7e3782d000-0x7e3782e000) present=1
长话短说,它在页面存在时有效,不会导致页面错误。这非常奇怪,页面错误应由虚拟内存分配器管理,将页面加载到主内存中......