我正在研究Linux中的系统调用,我阅读了read()系统调用。
SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_read(file, buf, count, &pos);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
return ret;
}
这是fget_light()的定义
struct file *fget_light(unsigned int fd, int *fput_needed)
{
struct file *file;
struct files_struct *files = current->files;
*fput_needed = 0;
if (likely((atomic_read(&files->count) == 1))) {
file = fcheck_files(files, fd);
} else {
rcu_read_lock();
file = fcheck_files(files, fd);
if (file) {
if (atomic_long_inc_not_zero(&file->f_count))
*fput_needed = 1;
else
/* Didn't get the reference, someone's freed */
file = NULL;
}
rcu_read_unlock();
}
return file;
}
你能给我解释一下,fgetu light是做什么的吗?
最佳答案
每个任务都有一个文件描述符表。此文件描述符表按文件描述符编号编制索引,并包含有关每个打开文件的信息(文件描述)。
与内核中的许多其他对象一样,文件描述也被计算为引用。这意味着当内核的某个部分想要访问一个文件描述时,它必须获取一个引用,做它需要做的任何事情,然后释放该引用。当引用计数降至零时,可以释放对象。对于文件描述,open()
会增加引用计数,而close()
会减少引用计数,因此在文件描述打开和/或内核使用它们时无法释放文件描述(例如:假设进程中的一个线程正在处理一个文件,而另一个线程仍在处理该文件:在读取之前,文件描述实际上不会被释放它的参考)。
要从文件描述符获取对文件描述的引用,内核具有函数close()
,并且read()
会释放该引用。由于多个线程可能同时在不同CPU上访问同一文件描述,fput()
和fget()
必须使用适当的锁定。在现代,它们使用rcu;仅仅是文件描述符表的读卡器不需要/几乎不需要成本。
但rcu还不够优化。考虑一下,拥有不是多线程的进程是非常常见的。在这种情况下,您不必担心来自同一进程的其他线程访问相同的文件描述。唯一可以访问文件描述符表的任务是我们。因此,作为优化,fput()
/fget()
当当前文件描述符表仅在单个任务中使用时,不要触摸引用计数。
struct file *fget_light(unsigned int fd, int *fput_needed)
{
struct file *file;
/* The file descriptor table for our _current_ task */
struct files_struct *files = current->files;
/* Assume we won't need to touch the reference count,
* since the count won't reach zero (we are not close(),
* and hope we don't run concurrently to close()),
* fput_light() won't actually need to fput().
*/
*fput_needed = 0;
/* Check whether we are actually the only task with access to the fd table */
if (likely((atomic_read(&files->count) == 1))) {
/* Yep, get the reference to the file description */
file = fcheck_files(files, fd);
} else {
/* Nope, we'll need some locking */
rcu_read_lock();
/* Get the reference to the file description */
file = fcheck_files(files, fd);
if (file) {
/* Increment the reference count */
if (atomic_long_inc_not_zero(&file->f_count))
/* fput_light() will actually need to fput() */
*fput_needed = 1;
else
/* Didn't get the reference, someone's freed */
/* Happens if the file was close()d and all the
* other accessors ended its work and fput().
*/
file = NULL;
}
rcu_read_unlock();
}
return file;
}