open()系統調用用來打開一個文件,本文就VFS層,對open系統調用的過程進行一個簡單的分析。
- SYSCALL_DEFINE3(open, constchar __user *, filename, int, flags, int, mode)
- {
- long ret;
- if (force_o_largefile())
- flags |= O_LARGEFILE;
- ret = do_sys_open(AT_FDCWD, filename, flags, mode);
- /* avoid REGPARM breakage on x86: */
- asmlinkage_protect(3, ret, filename, flags, mode);
- return ret;
- }
force_o_largefile()用來判斷系統是否為32位的,如果不是32位,也就是說為64位,則將O_LARGEFILE置位,主體工作由do_sys_open()來做
- long do_sys_open(int dfd, constchar __user *filename, int flags, int mode)
- {
- char *tmp = getname(filename);//拷貝文件名字符串到內核空間
- int fd = PTR_ERR(tmp);
- if (!IS_ERR(tmp)) {
- fd = get_unused_fd_flags(flags);//為文件分配一個文件描述符
- if (fd >= 0) {
- //實際的OPEN操作處理
- struct file *f = do_filp_open(dfd, tmp, flags, mode, 0);
- if (IS_ERR(f)) {
- put_unused_fd(fd);
- fd = PTR_ERR(f);
- } else {
- fsnotify_open(f->f_path.dentry);
- fd_install(fd, f);
- }
- }
- putname(tmp);
- }
- return fd;
- }
open操作是特定於某個進程進行的,因此涉及到了VFS中特定於進程的結構,這裡簡單的介紹下
struct files_struct {
/*
* read mostly part
*/
atomic_t count;
struct fdtable *fdt;
struct fdtable fdtab;
/*
* written part on a separate cache line in SMP
*/
spinlock_t file_lock ____cacheline_aligned_in_smp;
int next_fd;
struct embedded_fd_set close_on_exec_init;
struct embedded_fd_set open_fds_init;
struct file * fd_array[NR_OPEN_DEFAULT];
};