Linux open系统调用流程


 

Linux open系统调用流程(1)


http://blog.csdn.net/chenjin_zhong/article/details/8452453 

1.概述

我们知道,Linux把设备看成特殊的文件,称为设备文件。在操作文件之前,首先必须打开文件,打开文件的函数是通过open系统调用来实现的。而简单的文件打开操作,在Linux内核实现却是非常的复杂。open函数打开原理就是将进程files_struct结构体和文件对象file相关联。那么具体是怎么实现的呢?让我们一起走进Linux内核文件打开流程。

2. 首先,通过系统调用sys_open函数:

[cpp]  view plain copy
  1. //打开文件的系统调用  
  2. asmlinkage long sys_open(const char __user *filename, int flags, int mode)  
  3. {  
  4.     long ret;  
  5.   
  6.     if (force_o_largefile())  
  7.         flags |= O_LARGEFILE;  
  8.     //调用do_sys_open函数  
  9.     ret = do_sys_open(AT_FDCWD, filename, flags, mode);  
  10.     /* avoid REGPARM breakage on x86: */  
  11.     prevent_tail_call(ret);  
  12.     return ret;  
  13. }  

这个函数进行了简单的处理,调用do_sys_open函数:

[cpp]  view plain copy
  1. long do_sys_open(int dfd, const char __user *filename, int flags, int mode)  
  2. {  
  3.     /*将从用户空间传入的路径名复制到内核空间*/  
  4.     char *tmp = getname(filename);  
  5.     int fd = PTR_ERR(tmp);  
  6.   
  7.     if (!IS_ERR(tmp)) {  
  8.         /*得到一个没有使用的文件描述符*/  
  9.         fd = get_unused_fd();  
  10.         if (fd >= 0) {  
  11.             /*file对象是文件对象,存在于内存,所以没有回写,f_op被赋值*/  
  12.             struct file *f = do_filp_open(dfd, tmp, flags, mode);  
  13.             if (IS_ERR(f)) {  
  14.                 put_unused_fd(fd);  
  15.                 fd = PTR_ERR(f);  
  16.             } else {  
  17.                 fsnotify_open(f->f_path.dentry);  
  18.                 /*将current->files_struct和文件对象关联*/  
  19.                 fd_install(fd, f);  
  20.             }  
  21.         }  
  22.         putname(tmp);  
  23.     }  
  24.     return fd;  
  25. }  

这个函数主要完成以下几件事情:

(1)调用get_unused_fd得到一个没有使用的文件描述符,这是为读,写准备的,每个打开的文件都有一个文件描述符。

  (2)  调用do_filp_open构建 struct file文件对象,并填充相关信息,这个函数非常复杂,我们以后再看。

  (3)  调用fd_install将文件对象和进程的files_struct对象关联。

 首先看一下get_unused_fd函数:

[cpp]  view plain copy
  1. /*找到一个没有使用的文件描述符,并标记为busy 
  2.  * Find an empty file descriptor entry, and mark it busy. 
  3.  */  
  4. int get_unused_fd(void)  
  5. {  
  6.     /*得到files_struct结构体*/  
  7.     struct files_struct * files = current->files;  
  8.     int fd, error;  
  9.     /*定义fdtable结构*/  
  10.     struct fdtable *fdt;  
  11.     error = -EMFILE;  
  12.     spin_lock(&files->file_lock);  
  13.   
  14. repeat:  
  15.     /*返回files的fdt指针*/  
  16.     fdt = files_fdtable(files);  
  17.     /*从fdt->open_ds->fds_bits数组查找一个没有置位的文件描述符,open_ds表示打开的文件描述符集,当位图为1表示已经打开,为0已经关闭*/  
  18.     fd = find_next_zero_bit(fdt->open_fds->fds_bits, fdt->max_fds,  
  19.                 files->next_fd);  
  20.   
  21.     /* 
  22.      * N.B. For clone tasks sharing a files structure, this test 
  23.      * will limit the total number of files that can be opened. 
  24.      */  
  25.     if (fd >= current->signal->rlim[RLIMIT_NOFILE].rlim_cur)  
  26.         goto out;  
  27.   
  28.     /* Do we need to expand the fd array or fd set?  */  
  29.     error = expand_files(files, fd);  
  30.     if (error < 0)  
  31.         goto out;  
  32.   
  33.     if (error) {  
  34.         /* 
  35.          * If we needed to expand the fs array we 
  36.          * might have blocked - try again. 
  37.          */  
  38.         error = -EMFILE;  
  39.         goto repeat;  
  40.     }  
  41.     /*将文件描述符集合的fd置位*/  
  42.     FD_SET(fd, fdt->open_fds);  
  43.     FD_CLR(fd, fdt->close_on_exec);  
  44.     /*下一个描述符,即搜索的位置加1*/  
  45.     files->next_fd = fd + 1;  
  46. #if 1  
  47.     /* Sanity check */  
  48.     if (fdt->fd[fd] != NULL) {  
  49.         printk(KERN_WARNING "get_unused_fd: slot %d not NULL!\n", fd);  
  50.         fdt->fd[fd] = NULL;  
  51.     }  
  52. #endif  
  53.     error = fd;  
  54.   
  55. out:  
  56.     spin_unlock(&files->file_lock);  
  57.     return error;  
  58. }  

在第7行,得到当前进程的files指针。 在第16-18行,返回打开文件表,在打开的文件描述符集open_ds的fds_bits数组查找对应位置为0的位图,返回位置,表示这个文件描述符没有被使用。接下来,在41-43行,分别将open_fds的fd位置的位图置位,并将fd+1赋值给下一下文件描述符。如果这个文件描述符被占用,就将fdt->fd[fd]=NULL. 最后返回文件描述符fd.

接下来,调do_filp_open函数,其主要功能是返回一个已经填充好的文件对象指针。这个函数比较复杂,在下一节进行分析。

最后,分析一下fd_install函数,传入参数文件描述符fd和文件对象f,具体如下:

[cpp]  view plain copy
  1. /* 
  2.  * Install a file pointer in the fd array. 
  3.  * 
  4.  * The VFS is full of places where we drop the files lock between 
  5.  * setting the open_fds bitmap and installing the file in the file 
  6.  * array.  At any such point, we are vulnerable to a dup2() race 
  7.  * installing a file in the array before us.  We need to detect this and 
  8.  * fput() the struct file we are about to overwrite in this case. 
  9.  * 
  10.  * It should never happen - if we allow dup2() do it, _really_ bad things 
  11.  * will follow. 
  12.  */  
  13. //将进程的current->files对象与file文件对象进行绑定,从而直接操作定义的方法  
  14. void fastcall fd_install(unsigned int fd, struct file * file)  
  15. {  
  16.     /*进程的files_struct对象*/  
  17.     struct files_struct *files = current->files;  
  18.     /*进程文件表*/  
  19.     struct fdtable *fdt;  
  20.     spin_lock(&files->file_lock);  
  21.     /*取得fdt对象*/  
  22.     fdt = files_fdtable(files);  
  23.     BUG_ON(fdt->fd[fd] != NULL);  
  24.     /*将fdt->fd[fd]指向file对象*/  
  25.     rcu_assign_pointer(fdt->fd[fd], file);  
  26.     spin_unlock(&files->file_lock);  
  27. }  
这个函数首先得到files_struct对象指针,然后调用rcu_assign_pointer,将文件对象file赋给fdt->fd[fd], 这样,文件对象就和进程相关联起来了。

因此,不同的进程打开相同的文件,每次打开都会构建一个struct file文件对象,然后将这个对象和具体的进程相关联。其实open调用可以概括如下:

(1)得到一个未使用的文件描述符

(2)构建文件对象struct file

(3)将文件对象和进程相关联

在下一节中,我们将深入理解非常复杂的do_filp_open操作。

/-------------------------------------------------------------------------------------------------------

 

Linux open系统调用流程(2)

http://blog.csdn.net/chenjin_zhong/article/details/8452487http://blog.csdn.net/chenjin_zhong/article/details/8452487

http://blog.csdn.net/chenjin_zhong/article/details/8452487 

1. 书结上文,继续分析do_filp_open函数,其传入4个参数:

dfd:相对目录

tmp:文件路径名,例如要打开/usr/src/kernels/linux-2.6.30

flags:打开标志

mode:打开模式

[cpp]  view plain copy
  1. /* 
  2.  * Note that while the flag value (low two bits) for sys_open means: 
  3.  *  00 - read-only 
  4.  *  01 - write-only 
  5.  *  10 - read-write 
  6.  *  11 - special 
  7.  * it is changed into 
  8.  *  00 - no permissions needed 
  9.  *  01 - read-permission 
  10.  *  10 - write-permission 
  11.  *  11 - read-write 
  12.  * for the internal routines (ie open_namei()/follow_link() etc). 00 is 
  13.  * used by symlinks. 
  14.  */  
  15. static struct file *do_filp_open(int dfd, const char *filename, int flags,  
  16.                  int mode)  
  17. {  
  18.      
  19.     int namei_flags, error;  
  20.     /*创建nameidata结构体,返回的安装点对象和目录项对象放在此结构体*/  
  21.     struct nameidata nd;  
  22.     namei_flags = flags;  
  23.     if ((namei_flags+1) & O_ACCMODE)  
  24.         namei_flags++;  
  25.     /*根据上级的dentry对象得到新的dentry结构,并从中得到相关的inode节点号,再用iget函数分配新的inode结构,将新的dentry对象与inode对象关联起来*/  
  26.     error = open_namei(dfd, filename, namei_flags, mode, &nd);  
  27.     /*将nameidata结构体转化为struct file文件对象结构体*/  
  28.     if (!error)  
  29.         return nameidata_to_filp(&nd, flags);  
  30.   
  31.     return ERR_PTR(error);  
  32. }  

初看起来,寥寥几行代码,貌似简单。其实不然,一会就知道了。此函数调用了open_namei和nameidata_to_filp. 后一个函数通过名字就可以猜出来,是将nameidata结构转化为filp,也就是利用nd结构赋值给文件指针file,然后返回这个文件指针。而open_namei肯定是填充nd结构体,具体功能可表述为: 根据上级目录项对象,查询下一级的目录项对象,如果在目录项缓存找到下一级的目录项对象,则直接返回,并填充nd的挂载点对象和目录项对象。否则,构建一个子目录项对象,并利用iget函数分配一个新的inode结构,将子目录项对象和inode结构相关联。这样,一直循环到最后一下分量。最后返回的是最后一个分量的目录项对象和挂载点对象。可以看到,在这两个函数中,都利用了nameidata结构,具体看一下神奇的结构:

[cpp]  view plain copy
  1. struct nameidata {  
  2.     struct dentry   *dentry;/*当前目录项对象*/  
  3.     struct vfsmount *mnt;/*已安装的文件系统对象的地址*/  
  4.     struct qstr last;/*路径名最后一部分*/  
  5.     unsigned int    flags;/*查询标志*/  
  6.     int     last_type;/*路径名最后一部分的类型*/  
  7.     unsigned    depth;/*当前符号链接的深度,一般小于6*/  
  8.     char *saved_names[MAX_NESTED_LINKS + 1];/*关联符号链接的路径名数组*/  
  9.   
  10.     /* Intent data */  
  11.     union {  
  12.         struct open_intent open;/*想要打开的文件的联合体*/  
  13.     } intent;  
  14. };  
[cpp]  view plain copy
  1. struct open_intent {  
  2.     int flags;/*标志*/  
  3.     int create_mode;/*创建模式*/  
  4.     struct file *file;/*文件对象指针*/  
  5. };  
open_intent文件对象就是最后返回的文件对象。

由于namidata_to_filp比较简单,先看一下:

[cpp]  view plain copy
  1. /**将nameidata相关项赋值给struct file对象 
  2.  * nameidata_to_filp - convert a nameidata to an open filp. 
  3.  * @nd: pointer to nameidata 
  4.  * @flags: open flags 
  5.  * 
  6.  * Note that this function destroys the original nameidata 
  7.  */  
  8. struct file *nameidata_to_filp(struct nameidata *nd, int flags)  
  9. {  
  10.     struct file *filp;  
  11.   
  12.     /* Pick up the filp from the open intent */  
  13.     /*取得文件指针*/  
  14.     filp = nd->intent.open.file;  
  15.     /* Has the filesystem initialised the file for us? */  
  16.     /*文件系统是否已经初始化了dentry*/  
  17.     if (filp->f_path.dentry == NULL)  
  18.         filp = __dentry_open(nd->dentry, nd->mnt, flags, filp, NULL);  
  19.     else  
  20.         path_release(nd);  
  21.     return filp;  
  22. }  
首先取得文件对象指针,然后判断文件对象是否已经初始化,如果没有初始化,就调用__dentry_open函数,对文件对象进行初始化。

[cpp]  view plain copy
  1. /*对struct file结构体赋值*/  
  2. static struct file *__dentry_open(struct dentry *dentry, struct vfsmount *mnt,  
  3.                     int flags, struct file *f,  
  4.                     int (*open)(struct inode *, struct file *))  
  5. {  
  6.     struct inode *inode;  
  7.     int error;  
  8.     /*设置文件打开标志*/  
  9.     f->f_flags = flags;  
  10.     f->f_mode = ((flags+1) & O_ACCMODE) | FMODE_LSEEK |  
  11.                 FMODE_PREAD | FMODE_PWRITE;  
  12.     /*取得inode节点*/  
  13.     inode = dentry->d_inode;  
  14.     if (f->f_mode & FMODE_WRITE) {  
  15.         error = get_write_access(inode);  
  16.         if (error)  
  17.             goto cleanup_file;  
  18.     }  
  19.     /*地址空间对象*/  
  20.     f->f_mapping = inode->i_mapping;  
  21.     /*目录项对象*/  
  22.     f->f_path.dentry = dentry;  
  23.     /*挂载点对象*/  
  24.     f->f_path.mnt = mnt;  
  25.     /*文件指针位置 */  
  26.     f->f_pos = 0;  
  27.     /*inode节点在初始化的时候已经赋值了i_fop,现在将文件操作赋值给f_op*/   
  28.     f->f_op = fops_get(inode->i_fop);  
  29.     file_move(f, &inode->i_sb->s_files);  
  30.     /*文件open操作*/  
  31.     if (!open && f->f_op)/*open为NULL*/  
  32.         open = f->f_op->open;  
  33.     /*普通文件open为空,如果是设备文件,需要打开*/  
  34.     if (open) {  
  35.         error = open(inode, f);  
  36.         if (error)  
  37.             goto cleanup_all;  
  38.     }  
  39.       
  40.     f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);  
  41.     /*预读初始化*/  
  42.     file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);  
  43.   
  44.     /* NB: we're sure to have correct a_ops only after f_op->open */  
  45.     if (f->f_flags & O_DIRECT) {  
  46.         if (!f->f_mapping->a_ops ||  
  47.             ((!f->f_mapping->a_ops->direct_IO) &&  
  48.             (!f->f_mapping->a_ops->get_xip_page))) {  
  49.             fput(f);  
  50.             f = ERR_PTR(-EINVAL);  
  51.         }  
  52.     }  
  53.   
  54.     return f;  
  55.   
  56. cleanup_all:  
  57.     fops_put(f->f_op);  
  58.     if (f->f_mode & FMODE_WRITE)  
  59.         put_write_access(inode);  
  60.     file_kill(f);  
  61.     f->f_path.dentry = NULL;  
  62.     f->f_path.mnt = NULL;  
  63. cleanup_file:  
  64.     put_filp(f);  
  65.     dput(dentry);  
  66.     mntput(mnt);  
  67.     return ERR_PTR(error);  
  68. }  

首先,设置文件打开标志f->f_flags. 然后初始化地址空间对象,目录项对象,挂载点对象,文件指针位置,文件相关操作。需要说明两点:

(1)地址空间对象和索引节点相关联,在构建索引节点时已经赋值了。它涉及到具体的磁盘块操作,在后面的章节将会解释。

   (2)f_op这个非常重要,也是在构建索引节点时,将具体文件系统的文件操作函数集的指针赋给索引节点的i_fop域。对于打开文件,目录,符号链接,对应的操作函数集是不相同的。

 接下来,第31行-38行,如果是普通文件,可能不需要打开。如果是设备文件,就需要打开操作。例如SCSI设备的sg_open函数。

最后,对文件预读进行初始化。

在说完nameidata_to_filp函数之后,需要解释open_namei函数:

[cpp]  view plain copy
  1. /* 
  2.  *  open_namei() 
  3.  * 
  4.  * namei for open - this is in fact almost the whole open-routine. 
  5.  * 
  6.  * Note that the low bits of "flag" aren't the same as in the open 
  7.  * system call - they are 00 - no permissions needed 
  8.  *            01 - read permission needed 
  9.  *            10 - write permission needed 
  10.  *            11 - read/write permissions needed 
  11.  * which is a lot more logical, and also allows the "no perm" needed 
  12.  * for symlinks (where the permissions are checked later). 
  13.  * SMP-safe 
  14.  */  
  15. int open_namei(int dfd, const char *pathname, int flag,  
  16.         int mode, struct nameidata *nd)  
  17. {  
  18.     int acc_mode, error;  
  19.     /*定义path结构,包括安装点对象和目录项对象*/  
  20.     struct path path;  
  21.     struct dentry *dir;  
  22.     int count = 0;  
  23.   
  24.     acc_mode = ACC_MODE(flag);  
  25.   
  26.     /* O_TRUNC implies we need access checks for write permissions */  
  27.     /*截断标志,需要写权限*/  
  28.     if (flag & O_TRUNC)  
  29.         acc_mode |= MAY_WRITE;  
  30.   
  31.     /* Allow the LSM permission hook to distinguish append  
  32.        access from general write access. */  
  33.     if (flag & O_APPEND)  
  34.         acc_mode |= MAY_APPEND;  
  35.   
  36.     /* 
  37.      * The simplest case - just a plain lookup. 
  38.        不需要创建文件,直接打开文件即可,创建目录项对象和挂载点对象,并将它们填充到nd结构体 
  39.      */  
  40.     if (!(flag & O_CREAT)) {  
  41.         error = path_lookup_open(dfd, pathname, lookup_flags(flag),  
  42.                      nd, flag);  
  43.         if (error)  
  44.             return error;  
  45.         goto ok;  
  46.     }  
  47.   
  48.     /* 
  49.      * Create - we need to know the parent. 
  50.         ,由于是创建文件,即文件不存在,所以返回父目录项对象 
  51.           在创建文件时设置  LOOKUP_PARENT 
  52.      */  
  53.     error = path_lookup_create(dfd,pathname,LOOKUP_PARENT,nd,flag,mode);  
  54.     if (error)  
  55.         return error;  
  56.   
  57.     /* 
  58.      * We have the parent and last component. First of all, check 
  59.      * that we are not asked to creat(2) an obvious directory - that 
  60.      * will not do. 
  61.      */  
  62.     error = -EISDIR;  
  63.     if (nd->last_type != LAST_NORM || nd->last.name[nd->last.len])  
  64.         goto exit;  
  65.     /*对于创建文件,nd保存了上一个分量的目录项对象和挂载点对象。对于打开文件,nd保存了最后一个分量的目录项对象和挂载点对象*/  
  66.     dir = nd->dentry;  
  67.     nd->flags &= ~LOOKUP_PARENT;  
  68.     mutex_lock(&dir->d_inode->i_mutex);  
  69.     /*将path.dentry和mnt赋值*/  
  70.     path.dentry = lookup_hash(nd);  
  71.     path.mnt = nd->mnt;  
  72.   
  73. do_last:  
  74.     error = PTR_ERR(path.dentry);  
  75.     if (IS_ERR(path.dentry)) {  
  76.         mutex_unlock(&dir->d_inode->i_mutex);  
  77.         goto exit;  
  78.     }  
  79.   
  80.     if (IS_ERR(nd->intent.open.file)) {  
  81.         mutex_unlock(&dir->d_inode->i_mutex);  
  82.         error = PTR_ERR(nd->intent.open.file);  
  83.         goto exit_dput;  
  84.     }  
  85.   
  86.     /* Negative dentry, just create the file */  
  87.     /*如果是创建文件*/  
  88.     if (!path.dentry->d_inode) {  
  89.         /*创建索引节点,并标识为*/  
  90.         error = open_namei_create(nd, &path, flag, mode);  
  91.         if (error)  
  92.             goto exit;  
  93.         return 0;  
  94.     }  
  95.   
  96.     /* 
  97.      * It already exists. 
  98.      */  
  99.     mutex_unlock(&dir->d_inode->i_mutex);  
  100.     audit_inode_update(path.dentry->d_inode);  
  101.   
  102.     error = -EEXIST;  
  103.     if (flag & O_EXCL)  
  104.         goto exit_dput;  
  105.   
  106.     if (__follow_mount(&path)) {  
  107.         error = -ELOOP;  
  108.         if (flag & O_NOFOLLOW)  
  109.             goto exit_dput;  
  110.     }  
  111.   
  112.     error = -ENOENT;  
  113.     if (!path.dentry->d_inode)  
  114.         goto exit_dput;  
  115.     if (path.dentry->d_inode->i_op && path.dentry->d_inode->i_op->follow_link)  
  116.         goto do_link;  
  117.     /*将path的目录项对象和挂载点对象赋给nd*/  
  118.     path_to_nameidata(&path, nd);  
  119.     error = -EISDIR;  
  120.     if (path.dentry->d_inode && S_ISDIR(path.dentry->d_inode->i_mode))  
  121.         goto exit;  
  122. ok:  
  123.     error = may_open(nd, acc_mode, flag);  
  124.     if (error)  
  125.         goto exit;  
  126.     return 0;  
  127.   
  128. exit_dput:  
  129.     dput_path(&path, nd);  
  130. exit:  
  131.     if (!IS_ERR(nd->intent.open.file))  
  132.         release_open_intent(nd);  
  133.     path_release(nd);  
  134.     return error;  
  135.   
  136. do_link:  
  137.     error = -ELOOP;  
  138.     if (flag & O_NOFOLLOW)  
  139.         goto exit_dput;  
  140.     /* 
  141.      * This is subtle. Instead of calling do_follow_link() we do the 
  142.      * thing by hands. The reason is that this way we have zero link_count 
  143.      * and path_walk() (called from ->follow_link) honoring LOOKUP_PARENT. 
  144.      * After that we have the parent and last component, i.e. 
  145.      * we are in the same situation as after the first path_walk(). 
  146.      * Well, almost - if the last component is normal we get its copy 
  147.      * stored in nd->last.name and we will have to putname() it when we 
  148.      * are done. Procfs-like symlinks just set LAST_BIND. 
  149.      */  
  150.     nd->flags |= LOOKUP_PARENT;  
  151.     error = security_inode_follow_link(path.dentry, nd);  
  152.     if (error)  
  153.         goto exit_dput;  
  154.     error = __do_follow_link(&path, nd);  
  155.     if (error) {  
  156.         /* Does someone understand code flow here? Or it is only 
  157.          * me so stupid? Anathema to whoever designed this non-sense 
  158.          * with "intent.open". 
  159.          */  
  160.         release_open_intent(nd);  
  161.         return error;  
  162.     }  
  163.     nd->flags &= ~LOOKUP_PARENT;  
  164.     if (nd->last_type == LAST_BIND)  
  165.         goto ok;  
  166.     error = -EISDIR;  
  167.     if (nd->last_type != LAST_NORM)  
  168.         goto exit;  
  169.     if (nd->last.name[nd->last.len]) {  
  170.         __putname(nd->last.name);  
  171.         goto exit;  
  172.     }  
  173.     error = -ELOOP;  
  174.     if (count++==32) {  
  175.         __putname(nd->last.name);  
  176.         goto exit;  
  177.     }  
  178.     dir = nd->dentry;  
  179.     mutex_lock(&dir->d_inode->i_mutex);  
  180.     path.dentry = lookup_hash(nd);  
  181.     path.mnt = nd->mnt;  
  182.     __putname(nd->last.name);  
  183.     goto do_last;  
  184. }  

首先进行文件打开设置工作,第40行,如果是打开操作,则调用path_lookup_open函数。第53行,如果文件不存在,就创建一个文件,调用path_lookup_create函数。在第88行,如果是创建文件,需要建立磁盘上的索引节点,即调用open_namei_create函数。我们逐一解释:

首先path_lookup_open函数:

[cpp]  view plain copy
  1. /** 
  2.  * path_lookup_open - lookup a file path with open intent 
  3.  * @dfd: the directory to use as base, or AT_FDCWD 
  4.  * @name: pointer to file name 
  5.  * @lookup_flags: lookup intent flags 
  6.  * @nd: pointer to nameidata 
  7.  * @open_flags: open intent flags 
  8.  */  
  9. int path_lookup_open(int dfd, const char *name, unsigned int lookup_flags,  
  10.         struct nameidata *nd, int open_flags)  
  11. {  
  12.     return __path_lookup_intent_open(dfd, name, lookup_flags, nd,  
  13.             open_flags, 0);  
  14. }  
封装了__path_lookup_intent_open函数。

path_lookup_create函数:

[cpp]  view plain copy
  1. /** 
  2.  * path_lookup_create - lookup a file path with open + create intent 
  3.  * @dfd: the directory to use as base, or AT_FDCWD 
  4.  * @name: pointer to file name 
  5.  * @lookup_flags: lookup intent flags 
  6.  * @nd: pointer to nameidata 
  7.  * @open_flags: open intent flags 
  8.  * @create_mode: create intent flags 
  9.  */  
  10. static int path_lookup_create(int dfd, const char *name,  
  11.                   unsigned int lookup_flags, struct nameidata *nd,  
  12.                   int open_flags, int create_mode)  
  13. {  
  14.     return __path_lookup_intent_open(dfd, name, lookup_flags|LOOKUP_CREATE,  
  15.             nd, open_flags, create_mode);  
  16. }  
也封装了__path_lookup_intent_open函数,只是增加了创建标志LOOKUP_CREATE, 在create操作的lookup_flags设置了LOOKUP_PARENT,接下来,将看到这个标志的作用。

继续跟踪__path_lookup_intent_open函数:

static int __path_lookup_intent_open(int dfd, const char *name,

[cpp]  view plain copy
  1.         unsigned int lookup_flags, struct nameidata *nd,  
  2.         int open_flags, int create_mode)  
  3. {  
  4.     /*分配struct file对象指针*/  
  5.     struct file *filp = get_empty_filp();  
  6.     int err;  
  7.     if (filp == NULL)  
  8.         return -ENFILE;  
  9.     /*想要打开的文件*/  
  10.     nd->intent.open.file = filp;  
  11.     /*打开标志*/  
  12.     nd->intent.open.flags = open_flags;  
  13.     /*创建模式*/  
  14.     nd->intent.open.create_mode = create_mode;  
  15.     /*调用do_path_lookup函数,设置LOOKUP_OPEN*/  
  16.     err = do_path_lookup(dfd, name, lookup_flags|LOOKUP_OPEN, nd);  
  17.     if (IS_ERR(nd->intent.open.file)) {  
  18.         if (err == 0) {  
  19.             err = PTR_ERR(nd->intent.open.file);  
  20.             path_release(nd);  
  21.         }  
  22.     } else if (err != 0)  
  23.         release_open_intent(nd);  
  24.     return err;  
  25. }  

首先调用get_empty_flip函数分配一个空闲的文件对象filp, 设置intent.open的相关域,包括“想要打开的文件”,打开标志和创建模式。最后,调用do_path_lookup对文件路径进行解析,并填充nd。

[cpp]  view plain copy
  1. /*路径查找函数do_path_lookup*/  
  2. /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */  
  3.   
  4. static int fastcall do_path_lookup(int dfd, const char *name,  
  5.                 unsigned int flags, struct nameidata *nd)  
  6. {  
  7.     int retval = 0;  
  8.     int fput_needed;  
  9.     struct file *file;  
  10.     struct fs_struct *fs = current->fs;  
  11.     /*如果只有斜线号,设置最后一个分量的类型为LAST_ROOT*/  
  12.     nd->last_type = LAST_ROOT; /* if there are only slashes... */  
  13.     nd->flags = flags;  
  14.     nd->depth = 0;  
  15.     /*如果是从根目录开始查找*/  
  16.     if (*name=='/') {  
  17.         read_lock(&fs->lock);  
  18.         if (fs->altroot && !(nd->flags & LOOKUP_NOALT)) {  
  19.             /*nd->mnt设置为根安装点*/  
  20.             nd->mnt = mntget(fs->altrootmnt);  
  21.             /*nd->dentry开始目录项对象设置为根目录项对象*/  
  22.             nd->dentry = dget(fs->altroot);  
  23.             read_unlock(&fs->lock);  
  24.             if (__emul_lookup_dentry(name,nd))  
  25.                 goto out; /* found in altroot */  
  26.             read_lock(&fs->lock);  
  27.         }  
  28.         /*增加安装点的引用计数*/  
  29.         nd->mnt = mntget(fs->rootmnt);  
  30.         /*增加目录项的使用计数*/  
  31.         nd->dentry = dget(fs->root);  
  32.         read_unlock(&fs->lock);  
  33.     /*如果是当前工作目录*/  
  34.     } else if (dfd == AT_FDCWD) {  
  35.         read_lock(&fs->lock);  
  36.         /*从进程的fs_struct对象找到当前挂载点对象*/  
  37.         nd->mnt = mntget(fs->pwdmnt);  
  38.         /*从进程的fs_struct对象找到当前目录的目录项对象*/  
  39.         nd->dentry = dget(fs->pwd);  
  40.         read_unlock(&fs->lock);  
  41.     } else {/*当dfd!=AT_FDCWD,这种情况也是有可能出现的*/  
  42.         struct dentry *dentry;  
  43.         /*根据dfd得到file对象*/  
  44.         file = fget_light(dfd, &fput_needed);  
  45.         retval = -EBADF;  
  46.         if (!file)  
  47.             goto out_fail;  
  48.         /*目录项对象*/  
  49.         dentry = file->f_path.dentry;  
  50.         retval = -ENOTDIR;  
  51.         if (!S_ISDIR(dentry->d_inode->i_mode))  
  52.             goto fput_fail;  
  53.   
  54.         retval = file_permission(file, MAY_EXEC);  
  55.         if (retval)  
  56.             goto fput_fail;  
  57.         /*nd->mnt赋值*/  
  58.         nd->mnt = mntget(file->f_path.mnt);  
  59.         /*nd->dentry赋值,f_path.dentry是和文件相关的目录项对象*/  
  60.         nd->dentry = dget(dentry);  
  61.         fput_light(file, fput_needed);  
  62.     }  
  63.     current->total_link_count = 0;  
  64.     /*路径分解函数,调用实际文件系统操作*/  
  65.     retval = link_path_walk(name, nd);  
  66. out:  
  67.     if (likely(retval == 0)) {  
  68.         if (unlikely(!audit_dummy_context() && nd && nd->dentry &&  
  69.                 nd->dentry->d_inode))  
  70.         audit_inode(name, nd->dentry->d_inode);  
  71.     }  
  72. out_fail:  
  73.     return retval;  
  74.   
  75. fput_fail:  
  76.     fput_light(file, fput_needed);  
  77.     goto out_fail;  
  78. }  

第11-14行,设置初始化nd->last_type, flags和depth. 其中depth表示符号链接的深度。由于符号链接可以链接自己,因此需要限制链接的深度。

第16行,如果第一个字符为/,表示从根目录开始解析,设置nd->mnt为根挂载点对象,nd->dentry为根目录项对象,然后增加引用计数。

第34行,如果是从当前目录开始,将nd->mnt设置为当前目录的挂载点对象,nd->dentry设置为当前目录的目录项对象。

第41行,否则,将nd->mnt和nd->dentry分别设置为f_path.mnt和f_pat.dentry. 

接下来,第63行,初始化符号链接总数,调用实际文件系统的路径分解函数link_path_walk.

[cpp]  view plain copy
  1. int fastcall link_path_walk(const char *name, struct nameidata *nd)  
  2. {  
  3.     struct nameidata save = *nd;  
  4.     int result;  
  5.   
  6.     /* make sure the stuff we saved doesn't go away */  
  7.     /*首先备份一下安装点对象和目录项对象*/  
  8.     dget(save.dentry);  
  9.     mntget(save.mnt);  
  10.     /*真正的名称解析函数*/  
  11.     result = __link_path_walk(name, nd);  
  12.     if (result == -ESTALE) {  
  13.         *nd = save;  
  14.         dget(nd->dentry);  
  15.         mntget(nd->mnt);  
  16.         nd->flags |= LOOKUP_REVAL;  
  17.         result = __link_path_walk(name, nd);  
  18.     }  
  19.     /*减少并释放备份的nameidata对象*/  
  20.     dput(save.dentry);  
  21.     mntput(save.mnt);  
  22.        return result;  
  23. }  

首先,备份挂载点对象和目录项对象,然后调用__link_path_walk解析.

这个函数也比较复杂,在下一节中继续分析!

/----------------------------------------------------------------------------------------------
http://blog.csdn.net/chenjin_zhong/article/details/8452640 
 

Linux open系统调用流程(3)

分类: Linux文件系统   1131人阅读  评论(1)  收藏  举报

1. 闲言少叙,继续分析__link_path_walk函数:

[cpp]  view plain copy
  1. /* 
  2.  * Name resolution. 
  3.  * This is the basic name resolution function, turning a pathname into 
  4.  * the final dentry. We expect 'base' to be positive and a directory. 
  5.  * 
  6.  * Returns 0 and nd will have valid dentry and mnt on success. 
  7.  * Returns error and drops reference to input namei data on failure. 
  8.  */  
  9. /** 
  10. 处理三种情形: 
  11. (1)正在解析路径名 
  12. (2)解析父目录 
  13. (3)解析符号链接(第一次找出符号链接对应的文件路径,第二次解析文件路径) 
  14. **/  
  15. static fastcall int __link_path_walk(const char * name, struct nameidata *nd)  
  16. {  
  17.     struct path next;  
  18.     struct inode *inode;  
  19.     int err;  
  20.     /*查询标志*/  
  21.     unsigned int lookup_flags = nd->flags;  
  22.     /*如果第一个字符为/*/  
  23.     while (*name=='/')  
  24.         name++;  
  25.     /*只有一个根*/  
  26.     if (!*name)  
  27.         goto return_reval;  
  28.     /*得到索引节点,第一次是开始目录的索引节点,以后就是上一次目录的索引节点*/  
  29.     inode = nd->dentry->d_inode;  
  30.     /*设置符号链接*/  
  31.     if (nd->depth)  
  32.         lookup_flags = LOOKUP_FOLLOW | (nd->flags & LOOKUP_CONTINUE);  
  33.   
  34.     /* At this point we know we have a real path component. */  
  35.     for(;;) {  
  36.         /*hash值*/  
  37.         unsigned long hash;  
  38.         /*包括hash值,分量长度和分量名*/  
  39.         struct qstr this;  
  40.         unsigned int c;  
  41.         /*设置继续查询标志*/  
  42.         nd->flags |= LOOKUP_CONTINUE;  
  43.         /*检查权限信息,如果一个目录能够被遍历,首先必须具有执行权限*/  
  44.         err = exec_permission_lite(inode, nd);  
  45.         if (err == -EAGAIN)  
  46.             err = vfs_permission(nd, MAY_EXEC);  
  47.         if (err)  
  48.             break;  
  49.         /*name指的是第一个分量的第一个字符的地址*/  
  50.         this.name = name;  
  51.         /*取得第一个字符,如/proc,那么c='p'*/  
  52.         c = *(const unsigned char *)name;  
  53.         /*初始化hash值*/  
  54.         hash = init_name_hash();  
  55.         do {  
  56.             name++;  
  57.         /*计算部分hash,直到结尾,如/proc,那么计算的hash值就是proc*/     
  58.             hash = partial_name_hash(c, hash);  
  59.             c = *(const unsigned char *)name;  
  60.         } while (c && (c != '/'));  
  61.         /*计算每个分量的长度*/  
  62.         this.len = name - (const char *) this.name;  
  63.         /*this.hash赋上hash值*/  
  64.         this.hash = end_name_hash(hash);  
  65.   
  66.         /* remove trailing slashes? */  
  67.         /*到达最后一个分量*/  
  68.         if (!c)  
  69.             goto last_component;  
  70.         while (*++name == '/');  
  71.         /*最后一个字符是/*/  
  72.         if (!*name)  
  73.             goto last_with_slashes;  
  74.   
  75.         /* 
  76.          * "." and ".." are special - ".." especially so because it has 
  77.          * to be able to know about the current root directory and 
  78.          * parent relationships. 
  79.          */  
  80.         /*如果分量名第一个是.*/  
  81.         if (this.name[0] == '.'switch (this.len) {  
  82.             default:  
  83.                 break;  
  84.             case 2: /*并且第二个字符不是.,那么可能是隐藏文件,即不影响*/  
  85.                 if (this.name[1] != '.')  
  86.                     break;  
  87.                 /*如果第二个字符也是.,需要回溯到父目录*/  
  88.                 follow_dotdot(nd);  
  89.                 inode = nd->dentry->d_inode;  
  90.                 /* fallthrough */  
  91.             case 1:  
  92.                 continue;  
  93.         }  
  94.         /* 
  95.          * See if the low-level filesystem might want 
  96.          * to use its own hash.. 
  97.          如果底层文件系统具有计算hash值的函数,则使用 
  98.          */  
  99.         if (nd->dentry->d_op && nd->dentry->d_op->d_hash) {  
  100.             err = nd->dentry->d_op->d_hash(nd->dentry, &this);  
  101.             if (err < 0)  
  102.                 break;  
  103.         }  
  104.         /* This does the actual lookups..真正的查找函数*/  
  105.         /*nd结构体,this包含了分量名,next指向分量的目录项对象和安装点对象*/  
  106.         err = do_lookup(nd, &this, &next);  
  107.         if (err)  
  108.             break;  
  109.   
  110.         err = -ENOENT;  
  111.         /*上一次解析分量的索引节点对象*/  
  112.         inode = next.dentry->d_inode;  
  113.         if (!inode)  
  114.             goto out_dput;  
  115.         err = -ENOTDIR;   
  116.         if (!inode->i_op)  
  117.             goto out_dput;  
  118.         /*处理符号链接*/  
  119.         if (inode->i_op->follow_link) {  
  120.             /*处理符号链接*/  
  121.             err = do_follow_link(&next, nd);  
  122.             if (err)  
  123.                 goto return_err;  
  124.             err = -ENOENT;  
  125.             inode = nd->dentry->d_inode;  
  126.             if (!inode)  
  127.                 break;  
  128.             err = -ENOTDIR;   
  129.             if (!inode->i_op)  
  130.                 break;  
  131.         } else  
  132.             /*将目录项对象和安装点对象赋值给nd*/  
  133.             path_to_nameidata(&next, nd);  
  134.         err = -ENOTDIR;   
  135.         if (!inode->i_op->lookup)/*如果不是目录*/  
  136.             break;  
  137.         continue;  
  138.         /* here ends the main loop */  
  139.   
  140. last_with_slashes:  
  141.         lookup_flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;  
  142. last_component:  
  143.         /* Clear LOOKUP_CONTINUE iff it was previously unset 解析到最后一项,清除掉LOOKUP_CONTINUE*/  
  144.         nd->flags &= lookup_flags | ~LOOKUP_CONTINUE;  
  145.         /*有些情况下,不需要找到最后一个分量,例如创建一个文件/foo/bar,此时bar文件不存在,则应该找到foo的目录项对象*/  
  146.         if (lookup_flags & LOOKUP_PARENT)  
  147.             goto lookup_parent;  
  148.         if (this.name[0] == '.'switch (this.len) {  
  149.             default:  
  150.                 break;  
  151.             case 2:   
  152.                 if (this.name[1] != '.')  
  153.                     break;  
  154.                 follow_dotdot(nd);  
  155.                 inode = nd->dentry->d_inode;  
  156.                 /* fallthrough */  
  157.             case 1:  
  158.                 goto return_reval;  
  159.         }  
  160.         /*如果底层文件系统定义了计算hash值的方法,则使用它*/  
  161.         if (nd->dentry->d_op && nd->dentry->d_op->d_hash) {  
  162.             err = nd->dentry->d_op->d_hash(nd->dentry, &this);  
  163.             if (err < 0)  
  164.                 break;  
  165.         }  
  166.         /*查询最后一个component的hash值*/  
  167.         err = do_lookup(nd, &this, &next);  
  168.         if (err)  
  169.             break;  
  170.         /*最后一个分量的索引节点*/  
  171.         inode = next.dentry->d_inode;  
  172.         if ((lookup_flags & LOOKUP_FOLLOW)/*如果是符号链接*/  
  173.             && inode && inode->i_op && inode->i_op->follow_link) {  
  174.             err = do_follow_link(&next, nd);  
  175.             if (err)  
  176.                 goto return_err;  
  177.             inode = nd->dentry->d_inode;  
  178.         } else  
  179.             /*设置nameidata的mnt和dentry*/  
  180.             path_to_nameidata(&next, nd);  
  181.         err = -ENOENT;  
  182.         if (!inode)/*如果索引节点为空,即文件不存在*/  
  183.             break;  
  184.         if (lookup_flags & LOOKUP_DIRECTORY) {/*如果是目录*/  
  185.             err = -ENOTDIR;   
  186.             if (!inode->i_op || !inode->i_op->lookup)/*如果没有目录方法*/  
  187.                 break;  
  188.         }  
  189.         goto return_base;/*正常返回0,则nd包含了最后一个分量的目录项对象和所属的文件系统安装点*/  
  190. lookup_parent:/*创建一个文件时需要父目录项对象*/  
  191.         /*最后一个分量名*/  
  192.         nd->last = this;  
  193.         /*最后一个分量类型*/  
  194.         nd->last_type = LAST_NORM;  
  195.         /*不是.代表文件*/  
  196.         if (this.name[0] != '.')  
  197.             goto return_base;  
  198.         /*如果长度为1,代表当前目录*/  
  199.         if (this.len == 1)  
  200.             nd->last_type = LAST_DOT;  
  201.         /*长度为2,代表父目录*/  
  202.         else if (this.len == 2 && this.name[1] == '.')  
  203.             nd->last_type = LAST_DOTDOT;  
  204.         else  
  205.             goto return_base;  
  206. return_reval:  
  207.         /* 
  208.          * We bypassed the ordinary revalidation routines. 
  209.          * We may need to check the cached dentry for staleness. 
  210.          */  
  211.         if (nd->dentry && nd->dentry->d_sb &&  
  212.             (nd->dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT)) {  
  213.             err = -ESTALE;  
  214.             /* Note: we do not d_invalidate() */  
  215.             if (!nd->dentry->d_op->d_revalidate(nd->dentry, nd))  
  216.                 break;  
  217.         }  
  218. return_base:  
  219.         return 0;  
  220. out_dput:  
  221.         dput_path(&next, nd);  
  222.         break;  
  223.     }  
  224.     path_release(nd);  
  225. return_err:  
  226.     return err;  
  227. }  

这个函数主要做三件事:

(1)解析已经存在的文件路径,即打开标志

(2)解析不存在的文件路径,即创建文件标志,这样,需要得到父目录项对象和安装点对象

(3)解析符号链接,第一次找到符号链接的文件路径,第二次解析路径名

第23-26行,只有/,跳至return_reval. 这里多个根当作一个根处理,如//

第31-32行,设置符号链接标志。

第39行,定义qstr结构,这个结构包括hash值,分量长度和分量名。

第43-46行,进行权限检查,遍厍目录,必须具有执行权限。

第55-60行,计算每个分量的hash值。

第68行,如果解析到最后一个分量,跳至last_component.

第72行,如果遇到类似/proc/的目录,跳至last_with_slashes.

第80行,如果分量的第一个字符是.,但第二个字符不是.,则正常解析。

第88行,当第二个字符也是. ,说明是父目录,调用follow_dotdot进行回溯。

我们分析一下这个函数:

[cpp]  view plain copy
  1. static __always_inline void follow_dotdot(struct nameidata *nd)  
  2. {  
  3.     /*得到fs_struct结构体*/  
  4.     struct fs_struct *fs = current->fs;  
  5.   
  6.     while(1) {  
  7.         struct vfsmount *parent;  
  8.         /*上一次的目录项对象*/  
  9.         struct dentry *old = nd->dentry;  
  10.                 read_lock(&fs->lock);  
  11.         /*如果回溯的目录是进程的根目录,则不允许,调用follow_mount函数*/  
  12.         if (nd->dentry == fs->root &&  
  13.             nd->mnt == fs->rootmnt) {  
  14.                         read_unlock(&fs->lock);  
  15.             break;  
  16.         }  
  17.                 read_unlock(&fs->lock);  
  18.         spin_lock(&dcache_lock);  
  19.         /*如果目录项对象不是根目录,则返回上一级目录项对象*/  
  20.         if (nd->dentry != nd->mnt->mnt_root) {  
  21.             nd->dentry = dget(nd->dentry->d_parent);  
  22.             spin_unlock(&dcache_lock);  
  23.             dput(old);  
  24.             break;  
  25.         }  
  26.         spin_unlock(&dcache_lock);  
  27.         spin_lock(&vfsmount_lock);  
  28.         parent = nd->mnt->mnt_parent;  
  29.         if (parent == nd->mnt) {  
  30.             spin_unlock(&vfsmount_lock);  
  31.             break;  
  32.         }  
  33.         mntget(parent);  
  34.         nd->dentry = dget(nd->mnt->mnt_mountpoint);  
  35.         spin_unlock(&vfsmount_lock);  
  36.         dput(old);  
  37.         mntput(nd->mnt);  
  38.         nd->mnt = parent;  
  39.     }  
  40.     /*回溯到最底层的文件系统,nd->mnt指向挂载点*/  
  41.     follow_mount(&nd->mnt, &nd->dentry);  
  42. }  

第11-16行,如果回溯的是进程的根目录,则不允许,调用follow_mount函数。

第19-23行,如果目录项对象不是根目录,则通过nd->dentry=dget(nd->dentry->d_parent)返回上一级目录项对象。

不管怎么样,最终会调用follow_mount函数。有时,人的好奇心是很强的,同样,对于Linux内核源码,也需要好奇心。哈哈,看一下follow_mount函数:

[cpp]  view plain copy
  1. /*一直回溯到没有挂载其它文件系统的挂载点,mnt指向这个最底层的挂载点*/  
  2. static void follow_mount(struct vfsmount **mnt, struct dentry **dentry)  
  3. {  
  4.     while (d_mountpoint(*dentry)) {  
  5.         /*返回子挂载点*/  
  6.         struct vfsmount *mounted = lookup_mnt(*mnt, *dentry);  
  7.         if (!mounted)  
  8.             break;  
  9.         dput(*dentry);  
  10.         mntput(*mnt);  
  11.         *mnt = mounted;  
  12.         *dentry = dget(mounted->mnt_root);  
  13.     }  
  14. }  
这个函数首先判断一下dentry目录项是不是挂载点,如果是,调用lookup_mnt函数返回子挂载点。在第11行,将mnt赋值mounted,接着,寻找子挂载点。最终,找到一个没有其它文件系统安装在其之上的文件系统挂载点。这里,需要解释一下,如果/dev/sda1和/dev/sda2先后挂载在/usr目录下,那么/dev/sda1的相关目录将会被隐藏,而/dev/sda2的父挂载点是/dev/sda1. 而上面的过程是通过父挂载点找子挂载点,直到找到一个没有挂载其它文件系统的挂载点为止。这个,文件系统称暂且称为底层文件系统。也不知道,这么叫对不对,或许是顶层文件系统。总之,follow_dotdot回溯到了上一级目录。

接着__link_path_walk解释,

第97行,如果底层文件系统具有计算hash值的函数,则调用。

第106行,查找分量的目录项对象函数do_lookup,这个函数一会分析。

第119行,判断是否是符号链接,调用do_follow_link处理符号链接,稍后分析。

第142行,处理最后一个分量。

第167行,调用do_lookup函数,找到一个最后分量的目录项对象和挂载点对象。

第172行,如果最后一个分量是符号链接,调用do_follow_link进一步处理。

第190行,当只是建立文件时,跳至lookup_parent. 

第192-205行,最后一个分量名和分量类型,此时,nd保存了上一个分量的目录项对象和挂载点对象。

如果正确解析,返回0.

下面,分析一下do_lookup函数:

[cpp]  view plain copy
  1. /* 查询目录项对象,其结果保存在nameidata中,如果目录项缓存中存在,则直接返回,否则,创建目录项对象并插入目录项缓存,在创建索引节点,插入索引节点缓存(inode cache),然后让ndr dentry与mtn分别指向目录项对象和分量名所属的文件系统的安装点对象 
  2.  传入参数:nd,name指分量名 
  3.  *  It's more convoluted than I'd like it to be, but... it's still fairly 
  4.  *  small and for now I'd prefer to have fast path as straight as possible. 
  5.  *  It _is_ time-critical. 
  6.  */  
  7. static int do_lookup(struct nameidata *nd, struct qstr *name,  
  8.              struct path *path)  
  9. {  
  10.     struct vfsmount *mnt = nd->mnt;  
  11.     /*首先在目录项缓存查找,如果没有,则从底层建立目录项对象*/  
  12.     struct dentry *dentry = __d_lookup(nd->dentry, name);  
  13.     /*如果目录项缓存不存在*/  
  14.     if (!dentry)  
  15.         goto need_lookup;  
  16.     if (dentry->d_op && dentry->d_op->d_revalidate)  
  17.         goto need_revalidate;  
  18. done:  
  19.     path->mnt = mnt;/*安装点对象*/  
  20.     path->dentry = dentry;/*目录项对象*/  
  21.     /*找到子挂载点的mnt和目录项对象,即最底层的文件系统挂载点对象*/  
  22.     __follow_mount(path);  
  23.     return 0;  
  24.   
  25. need_lookup:  
  26.     /*如果dentry cache没有,则在内存分配一个dentry,并在内存分配索引节点,将dentry和索引节点关联*/  
  27.     dentry = real_lookup(nd->dentry, name, nd);  
  28.     if (IS_ERR(dentry))  
  29.         goto fail;  
  30.     goto done;  
  31.   
  32. need_revalidate:  
  33.     /*验证目录项对象是否还有效*/  
  34.     dentry = do_revalidate(dentry, nd);  
  35.     if (!dentry)  
  36.         goto need_lookup;  
  37.     if (IS_ERR(dentry))  
  38.         goto fail;  
  39.     goto done;  
  40.   
  41. fail:  
  42.     return PTR_ERR(dentry);  
  43. }  

这个函数的主要功能是查询目录项对象,并将挂载点和目录项对象保存在nameidata结构。具体如下:

第10行,nd保存了上一个目录项对象和挂载点对象。

第12行,首先在目录项缓存dentry cache查找,如果缓存不存在,跳转到need_lookup,调用real_lookup在内存分配一个dentry,并将dentry和索引节点关联。

第17行,如果存在,需要验证目录项对象是否有效,跳至34行,如果有效,将mnt和dentry赋值给path. 在__link_path_walk会将path值赋给nd.

继续跟踪__do_lookup函数:

[cpp]  view plain copy
  1. //从目录项缓存查找相应的目录项对象即struct dentry  
  2. struct dentry * __d_lookup(struct dentry * parent, struct qstr * name)  
  3. {  
  4.     unsigned int len = name->len;/*分量名的长度*/  
  5.     unsigned int hash = name->hash;/*分量名的hash值*/  
  6.     const unsigned char *str = name->name;/*分量名*/  
  7.     struct hlist_head *head = d_hash(parent,hash);/*得到hash节点指针*/  
  8.     struct dentry *found = NULL;  
  9.     struct hlist_node *node;  
  10.     struct dentry *dentry;  
  11.   
  12.     rcu_read_lock();  
  13.     /*dentry cache查找*/  
  14.     hlist_for_each_entry_rcu(dentry, node, head, d_hash) {  
  15.         struct qstr *qstr;  
  16.         /*hash值是否相同,hash值和名称相关联*/  
  17.         if (dentry->d_name.hash != hash)  
  18.             continue;  
  19.         /*父目录项是否是parent*/  
  20.         if (dentry->d_parent != parent)  
  21.             continue;  
  22.   
  23.         spin_lock(&dentry->d_lock);  
  24.   
  25.         /* 
  26.          * Recheck the dentry after taking the lock - d_move may have 
  27.          * changed things.  Don't bother checking the hash because we're 
  28.          * about to compare the whole name anyway. 
  29.          */  
  30.         if (dentry->d_parent != parent)  
  31.             goto next;  
  32.   
  33.         /* 
  34.          * It is safe to compare names since d_move() cannot 
  35.          * change the qstr (protected by d_lock). 
  36.          */  
  37.         /*detnry->d_name表示分量名,长度*/  
  38.         qstr = &dentry->d_name;  
  39.         if (parent->d_op && parent->d_op->d_compare) {/*匹配分量名,不同文件系统可以有不同的实现,如MS-DOS不分大小写*/  
  40.             if (parent->d_op->d_compare(parent, qstr, name))  
  41.                 goto next;  
  42.         } else {  
  43.             if (qstr->len != len)  
  44.                 goto next;  
  45.             if (memcmp(qstr->name, str, len))  
  46.                 goto next;  
  47.         }  
  48.           
  49.         if (!d_unhashed(dentry)) {  
  50.             atomic_inc(&dentry->d_count);  
  51.             found = dentry;  
  52.         }  
  53.         spin_unlock(&dentry->d_lock);  
  54.         break;  
  55. next:  
  56.         spin_unlock(&dentry->d_lock);  
  57.     }  
  58.     rcu_read_unlock();  
  59.   
  60.     return found;  
  61. }  
第4-7行,赋值len,hash和name,并取得head指针,为下面比较做准备。

第14行,判断hash值是是否相同。

第20行,判断父目录项parent是否相同。

第39行,匹配分量名。

如果找到,返回目录项对象。

从这个查找过程,可以看出,是用目录名或是文件名计算hash值,然后返回对应的目录项对象。这也是为什么目录名或文件名不放在索引节点而放在目录项对象的原因。

如果目录项缓存没有,继续跟踪real_lookup函数:

[cpp]  view plain copy
  1. /* 
  2.  * This is called when everything else fails, and we actually have 
  3.  * to go to the low-level filesystem to find out what we should do.. 
  4.  * 
  5.  * We get the directory semaphore, and after getting that we also 
  6.  * make sure that nobody added the entry to the dcache in the meantime.. 
  7.  * SMP-safe 
  8. 返回目录项对象 
  9.  */  
  10. static struct dentry * real_lookup(struct dentry * parent, struct qstr * name, struct nameidata *nd)  
  11. {  
  12.     struct dentry * result;  
  13.     /*上一级的inode节点*/  
  14.     struct inode *dir = parent->d_inode;  
  15.     mutex_lock(&dir->i_mutex);  
  16.     /* 
  17.      * First re-do the cached lookup just in case it was created 
  18.      * while we waited for the directory semaphore.. 
  19.      * 
  20.      * FIXME! This could use version numbering or similar to 
  21.      * avoid unnecessary cache lookups. 
  22.      * 
  23.      * The "dcache_lock" is purely to protect the RCU list walker 
  24.      * from concurrent renames at this point (we mustn't get false 
  25.      * negatives from the RCU list walk here, unlike the optimistic 
  26.      * fast walk). 
  27.      * 
  28.      * so doing d_lookup() (with seqlock), instead of lockfree __d_lookup 
  29.      */  
  30.     /*重新搜索一下目录项缓存*/  
  31.     result = d_lookup(parent, name);  
  32.     if (!result) {/*如果没有*/  
  33.     /*分配一个目录项对象,并初始化,对应分量的目录项对象的父目录项对象设置为上一次解析出来的目录项对象,即nd->dentry*/  
  34.         struct dentry * dentry = d_alloc(parent, name);  
  35.         result = ERR_PTR(-ENOMEM);  
  36.         if (dentry) {  
  37.             /*具体的文件系统相关函数,读取磁盘的inode节点信息,并将inode节点和目录项对象相关联,在iget索引节点时,将索引节点加入了inode cache,在关联inode节点时,将目录项对象加入了dentry cache*/  
  38.             result = dir->i_op->lookup(dir, dentry, nd);  
  39.             if (result)  
  40.                 dput(dentry);  
  41.             else  
  42.                 result = dentry;  
  43.         }  
  44.         mutex_unlock(&dir->i_mutex);  
  45.         return result;  
  46.     }  
  47.   
  48.     /* 
  49.      * Uhhuh! Nasty case: the cache was re-populated while 
  50.      * we waited on the semaphore. Need to revalidate. 
  51.      */  
  52.     mutex_unlock(&dir->i_mutex);  
  53.     if (result->d_op && result->d_op->d_revalidate) {  
  54.         result = do_revalidate(result, nd);  
  55.         if (!result)  
  56.             result = ERR_PTR(-ENOENT);  
  57.     }  
  58.     return result;  
  59. }  

在第33行,重新搜索一下目录项缓存,由于进程在查找过程中可能阻塞,在这期间,目录项可能已经加入了dentry cache,所以需要重新查找一下。

第34行,如果没有找到,调用d_alloc分配一个目录项对象。

第35行,具体的文件系统索引节点查找函数,读取磁盘索引节点信息,并将索引节点和目录项对象关联。在iget索引节点时,将索引节点加入了inode cache. 在关联inode节点时,将目录项对象加入了dentry cache.

在第53行,验证目录项对象是否有效,最终返回目录项对象。

可以看到,此时返回的目录项对象已经加入到了dentry cache,并关联了索引节点。即dentry->d_innode=inode.

我们继续跟踪上面的两个函数,首先跟踪d_alloc函数:

[cpp]  view plain copy
  1. /**分配一个目录项对象,并初始化 
  2.  * d_alloc  -   allocate a dcache entry 
  3.  * @parent: parent of entry to allocate 
  4.  * @name: qstr of the name 
  5.  * 
  6.  * Allocates a dentry. It returns %NULL if there is insufficient memory 
  7.  * available. On a success the dentry is returned. The name passed in is 
  8.  * copied and the copy passed in may be reused after this call. 
  9.  */  
  10.    
  11. struct dentry *d_alloc(struct dentry * parent, const struct qstr *name)  
  12. {  
  13.     struct dentry *dentry;  
  14.     char *dname;  
  15.   
  16.     dentry = kmem_cache_alloc(dentry_cache, GFP_KERNEL);   
  17.     if (!dentry)  
  18.         return NULL;  
  19.   
  20.     if (name->len > DNAME_INLINE_LEN-1) {  
  21.         dname = kmalloc(name->len + 1, GFP_KERNEL);  
  22.         if (!dname) {  
  23.             kmem_cache_free(dentry_cache, dentry);   
  24.             return NULL;  
  25.         }  
  26.     } else  {  
  27.         dname = dentry->d_iname;  
  28.     }     
  29.     dentry->d_name.name = dname;  
  30.   
  31.     dentry->d_name.len = name->len;  
  32.     dentry->d_name.hash = name->hash;  
  33.     memcpy(dname, name->name, name->len);  
  34.     dname[name->len] = 0;  
  35.   
  36.     atomic_set(&dentry->d_count, 1);  
  37.     dentry->d_flags = DCACHE_UNHASHED;  
  38.     spin_lock_init(&dentry->d_lock);  
  39.     dentry->d_inode = NULL;  
  40.     dentry->d_parent = NULL;  
  41.     dentry->d_sb = NULL;  
  42.     dentry->d_op = NULL;  
  43.     dentry->d_fsdata = NULL;  
  44.     dentry->d_mounted = 0;  
  45. #ifdef CONFIG_PROFILING  
  46.     dentry->d_cookie = NULL;  
  47. #endif  
  48.     INIT_HLIST_NODE(&dentry->d_hash);  
  49.     INIT_LIST_HEAD(&dentry->d_lru);  
  50.     INIT_LIST_HEAD(&dentry->d_subdirs);  
  51.     INIT_LIST_HEAD(&dentry->d_alias);  
  52.   
  53.     if (parent) {  
  54.         /*设置父目录项对象为parent*/  
  55.         dentry->d_parent = dget(parent);  
  56.         /*目录项对象对应的超级块对象*/  
  57.         dentry->d_sb = parent->d_sb;  
  58.     } else {  
  59.         INIT_LIST_HEAD(&dentry->d_u.d_child);  
  60.     }  
  61.   
  62.     spin_lock(&dcache_lock);  
  63.     if (parent)  
  64.         list_add(&dentry->d_u.d_child, &parent->d_subdirs);  
  65.     dentry_stat.nr_dentry++;  
  66.     spin_unlock(&dcache_lock);  
  67.   
  68.     return dentry;  
  69. }  

第16行,为目录项对象分配内存。

第29-32行,设置名称,长度和hash值。

第48-51行,初始化相关链表。

第53行,如果父目录项对象存在,就设置父目录项对象和超级块对象。这样,就建立了一个子目录项对象。


接着跟踪lookup函数,以ext3为例,ext3_lookup:

[cpp]  view plain copy
  1. /*查找文件名在目录项对象dentry下的inode节点*/  
  2. static struct dentry *ext3_lookup(struct inode * dir, struct dentry *dentry, struct nameidata *nd)  
  3. {  
  4.     struct inode * inode;  
  5.     struct ext3_dir_entry_2 * de;  
  6.     struct buffer_head * bh;  
  7.   
  8.     if (dentry->d_name.len > EXT3_NAME_LEN)  
  9.         return ERR_PTR(-ENAMETOOLONG);  
  10.     /*得到ext3_dir_entry_2对象,该对象包含inode节点号,再根据inode节点后从超级块的read_inode得到inode结构体*/  
  11.     bh = ext3_find_entry(dentry, &de);  
  12.     inode = NULL;  
  13.     if (bh) {  
  14.         unsigned long ino = le32_to_cpu(de->inode);  
  15.         brelse (bh);  
  16.         if (!ext3_valid_inum(dir->i_sb, ino)) {  
  17.             ext3_error(dir->i_sb, "ext3_lookup",  
  18.                    "bad inode number: %lu", ino);  
  19.             inode = NULL;  
  20.         } else  
  21.             /*创建内存索引节点,并填充相关信息,i_fop,并将索引节点加入inode cache*/  
  22.             inode = iget(dir->i_sb, ino);  
  23.   
  24.         if (!inode)  
  25.             return ERR_PTR(-EACCES);  
  26.     }  
  27.     /*将目录项对象关联inode节点*/  
  28.     return d_splice_alias(inode, dentry);  
  29. }  

第11行,得到ext3_dir_entry_2对象,该对象包含了索引节点号。

第13-16行,判断索引节点号是否合法。

第21行,创建内存索引节点,并填充相关信息,将索引节点加入inode cache.

第28行,将目录项对象和索引节点关联。

首先,跟踪iget函数:

 

[cpp]  view plain copy
  1. static inline struct inode *iget(struct super_block *sb, unsigned long ino)  
  2. {  
  3.     /*在内存分配一个新的索引节点*/  
  4.     struct inode *inode = iget_locked(sb, ino);  
  5.     /*如果是一个新的索引节点,读取磁盘上的索引节点并填充内存索引节点的相关信息*/  
  6.     if (inode && (inode->i_state & I_NEW)) {  
  7.         sb->s_op->read_inode(inode);  
  8.         unlock_new_inode(inode);  
  9.     }  
  10.   
  11.     return inode;  
  12. }  
首先调用iget_locked分配内存索引节点。如果是新分配的,需要调用read_inode调用磁盘上的索引节点填充相关信息。

继续跟踪iget_locked函数:

[cpp]  view plain copy
  1. /** 
  2.  * iget_locked - obtain an inode from a mounted file system 
  3.  * @sb:     super block of file system 
  4.  * @ino:    inode number to get 
  5.  * 
  6.  * This is iget() without the read_inode() portion of get_new_inode_fast(). 
  7.  * 
  8.  * iget_locked() uses ifind_fast() to search for the inode specified by @ino in 
  9.  * the inode cache and if present it is returned with an increased reference 
  10.  * count. This is for file systems where the inode number is sufficient for 
  11.  * unique identification of an inode. 
  12.  * 
  13.  * If the inode is not in cache, get_new_inode_fast() is called to allocate a 
  14.  * new inode and this is returned locked, hashed, and with the I_NEW flag set. 
  15.  * The file system gets to fill it in before unlocking it via 
  16.  * unlock_new_inode(). 
  17.  */  
  18. /** 
  19. 这个函数首先在inode节点缓存查找inode节点,如果存在,则返回 
  20. 如果缓存不存在,调用get_new_inode_fast分配一个inode节点 
  21. **/  
  22. struct inode *iget_locked(struct super_block *sb, unsigned long ino)  
  23. {  
  24.     /*inode_hashtable查找*/  
  25.     struct hlist_head *head = inode_hashtable + hash(sb, ino);  
  26.     struct inode *inode;  
  27.     /*首先在inode cache查找*/  
  28.     inode = ifind_fast(sb, head, ino);  
  29.     if (inode)  
  30.         return inode;  
  31.     /* 
  32.      * get_new_inode_fast() will do the right thing, re-trying the search 
  33.      * in case it had to block at any point. 
  34.      */  
  35.     /*新分配一个索引节点,并加入到inode cache,即inode_hashtable*/  
  36.     return get_new_inode_fast(sb, head, ino);  
  37. }  

第28行,在inode cache查找,如果没有,调用get_new_inode_fast分配一个索引节点并插入inode cache.

ifind_fast留给读者自行分析吧!

分析一下,get_new_inode_fast函数:

[cpp]  view plain copy
  1. /* 
  2.  * get_new_inode_fast is the fast path version of get_new_inode, see the 
  3.  * comment at iget_locked for details. 
  4.  */  
  5. static struct inode * get_new_inode_fast(struct super_block *sb, struct hlist_head *head, unsigned long ino)  
  6. {  
  7.     struct inode * inode;  
  8.     /*分配一个索引节点*/  
  9.     inode = alloc_inode(sb);  
  10.     if (inode) {  
  11.         struct inode * old;  
  12.   
  13.         spin_lock(&inode_lock);  
  14.         /* We released the lock, so.. */  
  15.         old = find_inode_fast(sb, head, ino);  
  16.         if (!old) {  
  17.             /*设置索引节点号*/  
  18.             inode->i_ino = ino;  
  19.             inodes_stat.nr_inodes++;  
  20.             /*加入已经使用链表inode_in_use*/  
  21.             list_add(&inode->i_list, &inode_in_use);  
  22.             /*加入超级块链表*/  
  23.             list_add(&inode->i_sb_list, &sb->s_inodes);  
  24.             /*加入inode_hashtable*/  
  25.             hlist_add_head(&inode->i_hash, head);  
  26.             /*设置状态*/  
  27.             inode->i_state = I_LOCK|I_NEW;  
  28.             spin_unlock(&inode_lock);  
  29.   
  30.             /* Return the locked inode with I_NEW set, the 
  31.              * caller is responsible for filling in the contents 
  32.              */  
  33.             return inode;  
  34.         }  
  35.   
  36.         /* 
  37.          * Uhhuh, somebody else created the same inode under 
  38.          * us. Use the old inode instead of the one we just 
  39.          * allocated. 
  40.          */  
  41.         __iget(old);  
  42.         spin_unlock(&inode_lock);  
  43.         destroy_inode(inode);  
  44.         inode = old;  
  45.         wait_on_inode(inode);  
  46.     }  
  47.     return inode;  
  48. }  

第9行,分配索引节点。

第17-28行,索引节点的初始化。包括:

(1)设置索引节点号

(2)加入inode_in_use链表

(3)加入inode_hashtable,即加入inode cache

(4)设置状态为I_NEW

返回索引节点。

接下来,继续分析iget函数中的第二个函数read_inode.

[cpp]  view plain copy
  1. void ext3_read_inode(struct inode * inode)  
  2. {   /*描述索引节点的位置信息*/  
  3.     struct ext3_iloc iloc;  
  4.     struct ext3_inode *raw_inode;  
  5.     struct ext3_inode_info *ei = EXT3_I(inode);  
  6.     struct buffer_head *bh;  
  7.     int block;  
  8.   
  9. #ifdef CONFIG_EXT3_FS_POSIX_ACL  
  10.     ei->i_acl = EXT3_ACL_NOT_CACHED;  
  11.     ei->i_default_acl = EXT3_ACL_NOT_CACHED;  
  12. #endif  
  13.     ei->i_block_alloc_info = NULL;  
  14.   
  15.     if (__ext3_get_inode_loc(inode, &iloc, 0))  
  16.         goto bad_inode;  
  17.     bh = iloc.bh;  
  18.     /*磁盘上原始索引节点,读取它并填充新分配的索引节点*/  
  19.     raw_inode = ext3_raw_inode(&iloc);  
  20.     inode->i_mode = le16_to_cpu(raw_inode->i_mode);  
  21.     inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);  
  22.     inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);  
  23.     if(!(test_opt (inode->i_sb, NO_UID32))) {  
  24.         inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;  
  25.         inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;  
  26.     }  
  27.     inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);  
  28.     inode->i_size = le32_to_cpu(raw_inode->i_size);  
  29.     inode->i_atime.tv_sec = le32_to_cpu(raw_inode->i_atime);  
  30.     inode->i_ctime.tv_sec = le32_to_cpu(raw_inode->i_ctime);  
  31.     inode->i_mtime.tv_sec = le32_to_cpu(raw_inode->i_mtime);  
  32.     inode->i_atime.tv_nsec = inode->i_ctime.tv_nsec = inode->i_mtime.tv_nsec = 0;  
  33.   
  34.     ei->i_state = 0;  
  35.     ei->i_dir_start_lookup = 0;  
  36.     ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);  
  37.     /* We now have enough fields to check if the inode was active or not. 
  38.      * This is needed because nfsd might try to access dead inodes 
  39.      * the test is that same one that e2fsck uses 
  40.      * NeilBrown 1999oct15 
  41.      */  
  42.     if (inode->i_nlink == 0) {  
  43.         if (inode->i_mode == 0 ||  
  44.             !(EXT3_SB(inode->i_sb)->s_mount_state & EXT3_ORPHAN_FS)) {  
  45.             /* this inode is deleted */  
  46.             brelse (bh);  
  47.             goto bad_inode;  
  48.         }  
  49.         /* The only unlinked inodes we let through here have 
  50.          * valid i_mode and are being read by the orphan 
  51.          * recovery code: that's fine, we're about to complete 
  52.          * the process of deleting those. */  
  53.     }  
  54.     inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);  
  55.     ei->i_flags = le32_to_cpu(raw_inode->i_flags);  
  56. #ifdef EXT3_FRAGMENTS  
  57.     ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);  
  58.     ei->i_frag_no = raw_inode->i_frag;  
  59.     ei->i_frag_size = raw_inode->i_fsize;  
  60. #endif  
  61.     ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);  
  62.     if (!S_ISREG(inode->i_mode)) {  
  63.         ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);  
  64.     } else {  
  65.         inode->i_size |=  
  66.             ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;  
  67.     }  
  68.     ei->i_disksize = inode->i_size;  
  69.     inode->i_generation = le32_to_cpu(raw_inode->i_generation);  
  70.     ei->i_block_group = iloc.block_group;  
  71.     /* 
  72.      * NOTE! The in-memory inode i_data array is in little-endian order 
  73.      * even on big-endian machines: we do NOT byteswap the block numbers! 
  74.      */  
  75.     for (block = 0; block < EXT3_N_BLOCKS; block++)  
  76.         ei->i_data[block] = raw_inode->i_block[block];  
  77.     INIT_LIST_HEAD(&ei->i_orphan);  
  78.   
  79.     if (inode->i_ino >= EXT3_FIRST_INO(inode->i_sb) + 1 &&  
  80.         EXT3_INODE_SIZE(inode->i_sb) > EXT3_GOOD_OLD_INODE_SIZE) {  
  81.         /* 
  82.          * When mke2fs creates big inodes it does not zero out 
  83.          * the unused bytes above EXT3_GOOD_OLD_INODE_SIZE, 
  84.          * so ignore those first few inodes. 
  85.          */  
  86.         ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);  
  87.         if (EXT3_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >  
  88.             EXT3_INODE_SIZE(inode->i_sb))  
  89.             goto bad_inode;  
  90.         if (ei->i_extra_isize == 0) {  
  91.             /* The extra space is currently unused. Use it. */  
  92.             ei->i_extra_isize = sizeof(struct ext3_inode) -  
  93.                         EXT3_GOOD_OLD_INODE_SIZE;  
  94.         } else {  
  95.             __le32 *magic = (void *)raw_inode +  
  96.                     EXT3_GOOD_OLD_INODE_SIZE +  
  97.                     ei->i_extra_isize;  
  98.             if (*magic == cpu_to_le32(EXT3_XATTR_MAGIC))  
  99.                  ei->i_state |= EXT3_STATE_XATTR;  
  100.         }  
  101.     } else  
  102.         ei->i_extra_isize = 0;  
  103.   
  104.     if (S_ISREG(inode->i_mode)) {  
  105.         /*inode节点相关方法和文件操作方法,这个非常重要,最后将inode->i_fop赋给file对象*/  
  106.         inode->i_op = &ext3_file_inode_operations;  
  107.         inode->i_fop = &ext3_file_operations;  
  108.         ext3_set_aops(inode);  
  109.     } else if (S_ISDIR(inode->i_mode)) {  
  110.         inode->i_op = &ext3_dir_inode_operations;  
  111.         inode->i_fop = &ext3_dir_operations;  
  112.     } else if (S_ISLNK(inode->i_mode)) {  
  113.         if (ext3_inode_is_fast_symlink(inode))  
  114.             inode->i_op = &ext3_fast_symlink_inode_operations;  
  115.         else {  
  116.             inode->i_op = &ext3_symlink_inode_operations;  
  117.             ext3_set_aops(inode);  
  118.         }  
  119.     } else {//将相关操作赋值给inode->i_op  
  120.         inode->i_op = &ext3_special_inode_operations;  
  121.         if (raw_inode->i_block[0])  
  122.             init_special_inode(inode, inode->i_mode,  
  123.                old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));  
  124.         else  
  125.             init_special_inode(inode, inode->i_mode,  
  126.                new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));  
  127.     }  
  128.     brelse (iloc.bh);  
  129.     ext3_set_inode_flags(inode);  
  130.     return;  
  131.   
  132. bad_inode:  
  133.     make_bad_inode(inode);  
  134.     return;  
  135. }  

简单说一下功能:

第19行,读取磁盘上原始索引节点,用来填充新分配的索引节点。

第20-32行,inode相关域设置。

第104行,如果是文件,则将文件相关操作的指针赋给inode->i_fop,这非常重要,因为,最后将i_fop赋给了文件对象file->f_op. 表示了文件的相关操作。

第109-111行,目录相关操作。

第112-118行,符号链接相关操作。

第119-128行,设备相关操作。具体就不分析了。

到此为止,我们已经得到了一个inode节点,并且填充了相关域。

iget函数返回,ext3_lookup继续往下走,调用d_splice_alias函数:

[cpp]  view plain copy
  1. /**将索引节点和目录项对象相关联 
  2.  * d_splice_alias - splice a disconnected dentry into the tree if one exists 
  3.  * @inode:  the inode which may have a disconnected dentry 
  4.  * @dentry: a negative dentry which we want to point to the inode. 
  5.  * 
  6.  * If inode is a directory and has a 'disconnected' dentry (i.e. IS_ROOT and 
  7.  * DCACHE_DISCONNECTED), then d_move that in place of the given dentry 
  8.  * and return it, else simply d_add the inode to the dentry and return NULL. 
  9.  * 
  10.  * This is needed in the lookup routine of any filesystem that is exportable 
  11.  * (via knfsd) so that we can build dcache paths to directories effectively. 
  12.  * 
  13.  * If a dentry was found and moved, then it is returned.  Otherwise NULL 
  14.  * is returned.  This matches the expected return value of ->lookup. 
  15.  * 
  16.  */  
  17. struct dentry *d_splice_alias(struct inode *inode, struct dentry *dentry)  
  18. {  
  19.     struct dentry *new = NULL;  
  20.   
  21.     if (inode && S_ISDIR(inode->i_mode)) {  
  22.         spin_lock(&dcache_lock);  
  23.         new = __d_find_alias(inode, 1);  
  24.         if (new) {  
  25.             BUG_ON(!(new->d_flags & DCACHE_DISCONNECTED));  
  26.             fsnotify_d_instantiate(new, inode);  
  27.             spin_unlock(&dcache_lock);  
  28.             security_d_instantiate(new, inode);  
  29.             d_rehash(dentry);  
  30.             d_move(new, dentry);  
  31.             iput(inode);  
  32.         } else {  
  33.             /* d_instantiate takes dcache_lock, so we do it by hand */  
  34.             /*加入正在使用目录项链表,即表头在i_dentry*/  
  35.             list_add(&dentry->d_alias, &inode->i_dentry);  
  36.             /*目录项对象和索引节点对象关联*/  
  37.             dentry->d_inode = inode;  
  38.             fsnotify_d_instantiate(dentry, inode);  
  39.             spin_unlock(&dcache_lock);  
  40.             security_d_instantiate(dentry, inode);  
  41.             /*将目录项对象加入dentry_hashtable即目录项缓存*/  
  42.             d_rehash(dentry);  
  43.         }  
  44.     } else  
  45.         d_add(dentry, inode);  
  46.     return new;  
  47. }  

第37行,将目录项对象和索引节点相关联。

第42行,将目录项对象加入到目录项缓存。

最后,返回dentry.

如果,你现在仍然很清醒,那么恭喜你,你已经基本了解了整个过程。

lookup函数返回,在__link_path_walk函数调用path_to_nameidata将path->mnt和path->dentry赋给nd->mnt和nd->dentry.表示找到的目录项对象和挂载点对象。

接下来,处理符号链接,调用do_follow_link函数:

[cpp]  view plain copy
  1. /* 
  2.  * This limits recursive symlink follows to 8, while 
  3.  * limiting consecutive symlinks to 40. 
  4.  * 
  5.  * Without that kind of total limit, nasty chains of consecutive 
  6.  * symlinks can cause almost arbitrarily long lookups.  
  7.  */  
  8. static inline int do_follow_link(struct path *path, struct nameidata *nd)  
  9. {  
  10.     int err = -ELOOP;  
  11.     if (current->link_count >= MAX_NESTED_LINKS)/*检查符号链接数,如果软链接不停的链接自己,可能导致内核栈溢出*/  
  12.         goto loop;  
  13.     /*表示总的符号链接数*/  
  14.     if (current->total_link_count >= 40)  
  15.         goto loop;  
  16.     BUG_ON(nd->depth >= MAX_NESTED_LINKS);  
  17.     cond_resched();  
  18.     err = security_inode_follow_link(path->dentry, nd);  
  19.     if (err)  
  20.         goto loop;  
  21.     current->link_count++;/*增加链接数*/  
  22.     current->total_link_count++;  
  23.     nd->depth++;/*增加链接深度*/  
  24.     err = __do_follow_link(path, nd);  
  25.     current->link_count--;  
  26.     nd->depth--;  
  27.     return err;  
  28. loop:  
  29.     dput_path(path, nd);  
  30.     path_release(nd);  
  31.     return err;  
  32. }  

这个函数首先松果符号链接数,不能超过MAX_NESTED_LINKS.

最终调用__do_follow_link进行处理。

[cpp]  view plain copy
  1. static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd)  
  2. {  
  3.     int error;  
  4.     void *cookie;  
  5.     struct dentry *dentry = path->dentry;  
  6.   
  7.     touch_atime(path->mnt, dentry);/*更新inode节点的存取时间*/  
  8.     /*先将nd->saved_names数组置空*/  
  9.     nd_set_link(nd, NULL);  
  10.     if (path->mnt != nd->mnt) {  
  11.         path_to_nameidata(path, nd);  
  12.         dget(dentry);  
  13.     }  
  14.     mntget(path->mnt);  
  15.     cookie = dentry->d_inode->i_op->follow_link(dentry, nd);/*提取存储在符号链接的路径,并保存在nd->saved_names数组*/  
  16.     error = PTR_ERR(cookie);  
  17.     if (!IS_ERR(cookie)) {  
  18.         /*路径名放在s*/  
  19.         char *s = nd_get_link(nd);  
  20.         error = 0;  
  21.         if (s)  
  22.             error = __vfs_follow_link(nd, s);/*解析路径名*/  
  23.         if (dentry->d_inode->i_op->put_link)  
  24.             dentry->d_inode->i_op->put_link(dentry, nd, cookie);  
  25.     }  
  26.     dput(dentry);  
  27.     mntput(path->mnt);  
  28.   
  29.     return error;  
  30. }  

第15行,取出符号链接的路径,放到nd->saved_names可以看出,符号链接有自己的inode节点,并且inode节点保存的内容是真正的文件路径。所以,符号链接可以跨文件系统。

第22行,调用__vfs_follow_link解析路径名。

[cpp]  view plain copy
  1. /*按照符号链接保存的路径名调用link_path_walk解析真正的链接*/  
  2. static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)  
  3. {  
  4.     int res = 0;  
  5.     char *name;  
  6.     if (IS_ERR(link))  
  7.         goto fail;  
  8.     /*如果第一个字符是/,那么从根开始查找*/  
  9.     if (*link == '/') {  
  10.         path_release(nd);  
  11.         if (!walk_init_root(link, nd))  
  12.             /* weird __emul_prefix() stuff did it */  
  13.             goto out;  
  14.     }  
  15.     res = link_path_walk(link, nd);  
  16. out:  
  17.     if (nd->depth || res || nd->last_type!=LAST_NORM)  
  18.         return res;  
  19.     /* 
  20.      * If it is an iterative symlinks resolution in open_namei() we 
  21.      * have to copy the last component. And all that crap because of 
  22.      * bloody create() on broken symlinks. Furrfu... 
  23.      */  
  24.     name = __getname();  
  25.     if (unlikely(!name)) {  
  26.         path_release(nd);  
  27.         return -ENOMEM;  
  28.     }  
  29.     strcpy(name, nd->last.name);  
  30.     nd->last.name = name;  
  31.     return 0;  
  32. fail:  
  33.     path_release(nd);  
  34.     return PTR_ERR(link);  
  35. }  

第15行,调用link_path_walk. 看到这个函数,松了一口气,因为前面已经分析过了。

当__link_path_walk返回时,link_path_walk也跟着返回,之后do_path_lookup也返回了,最终回到open_namei函数。

如果是打开文件,返回即可。

如果是创建文件,还需调用open_namei_create函数:

[cpp]  view plain copy
  1. static int open_namei_create(struct nameidata *nd, struct path *path,  
  2.                 int flag, int mode)  
  3. {  
  4.     int error;  
  5.     struct dentry *dir = nd->dentry;  
  6.   
  7.     if (!IS_POSIXACL(dir->d_inode))  
  8.         mode &= ~current->fs->umask;  
  9.     error = vfs_create(dir->d_inode, path->dentry, mode, nd);  
  10.     mutex_unlock(&dir->d_inode->i_mutex);  
  11.     dput(nd->dentry);  
  12.     nd->dentry = path->dentry;/*更改nd目录项对象指向新创建的文件*/  
  13.     if (error)  
  14.         return error;  
  15.     /* Don't check for write permission, don't truncate */  
  16.     return may_open(nd, 0, flag & ~O_TRUNC);  
  17. }  
封装了vfs_create函数:

[cpp]  view plain copy
  1. int vfs_create(struct inode *dir, struct dentry *dentry, int mode,  
  2.         struct nameidata *nd)  
  3. {  
  4.     int error = may_create(dir, dentry, nd);  
  5.   
  6.     if (error)  
  7.         return error;  
  8.   
  9.     if (!dir->i_op || !dir->i_op->create)  
  10.         return -EACCES; /* shouldn't it be ENOSYS? */  
  11.     mode &= S_IALLUGO;  
  12.     mode |= S_IFREG;  
  13.     error = security_inode_create(dir, dentry, mode);  
  14.     if (error)  
  15.         return error;  
  16.     DQUOT_INIT(dir);  
  17.     error = dir->i_op->create(dir, dentry, mode, nd);  
  18.     if (!error)  
  19.         fsnotify_create(dir, dentry);  
  20.     return error;  
  21. }  

调用inode的create方法创建索引节点。以ext3为例,调用ext3_create函数:

[cpp]  view plain copy
  1. /*已经创建了目录项缓存对象,但是没有创建索引节点对象 
  2.  * By the time this is called, we already have created 
  3.  * the directory cache entry for the new file, but it 
  4.  * is so far negative - it has no inode. 
  5.  * 
  6.  * If the create succeeds, we fill in the inode information 
  7.  * with d_instantiate(). 
  8.  */  
  9. static int ext3_create (struct inode * dir, struct dentry * dentry, int mode,  
  10.         struct nameidata *nd)  
  11. {  
  12.     handle_t *handle;  
  13.     struct inode * inode;  
  14.     int err, retries = 0;  
  15.   
  16. retry:  
  17.     handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS(dir->i_sb) +  
  18.                     EXT3_INDEX_EXTRA_TRANS_BLOCKS + 3 +  
  19.                     2*EXT3_QUOTA_INIT_BLOCKS(dir->i_sb));  
  20.     if (IS_ERR(handle))  
  21.         return PTR_ERR(handle);  
  22.   
  23.     if (IS_DIRSYNC(dir))  
  24.         handle->h_sync = 1;  
  25.   
  26.     inode = ext3_new_inode (handle, dir, mode);  
  27.     err = PTR_ERR(inode);  
  28.     if (!IS_ERR(inode)) {  
  29.         inode->i_op = &ext3_file_inode_operations;  
  30.         inode->i_fop = &ext3_file_operations;  
  31.         ext3_set_aops(inode);  
  32.         err = ext3_add_nondir(handle, dentry, inode);  
  33.     }  
  34.     ext3_journal_stop(handle);  
  35.     if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))  
  36.         goto retry;  
  37.     return err;  
  38. }  

第26行,创建索引节点。

第29-33行,inode->i_op和inode->i_fop赋值。

之后,还会将索引节点标识为脏,需要回写到磁盘上,具体实现就不分析了。

当open_namei函数返回时,open系统调用也就分析完了。


总结:

(1)建立一个struct file结构体,将nameidata相关域填充到这个结构体,最重要的两个域mnt, dentry. 从dentry可得到inode,从而将i_fop赋给文件对象。

(2)在路径查找时,通过父目录项建立子目录项,然后将子目录项关联inode节点。

(3)打开文件和建立文件不同。打开文件,只需要找到目录项对象,然后关联索引节点即可,因为索引节点存在。而建立文件时,由于文件不存在,首先找到目录的目录项对象,然后建立子目录项对象和索引节点对象,最后索引节点对象需要同步到磁盘上。

(4)有两个缓存,dentry cache和inode cache,分别用来缓存目录项对象和索引节点对象。

(5)将文件对象和进程的files_struct相关联。

(6)对于普通文件,不需要打开操作,而对于设备文件,需要打开操作,例如SCSI设备的sg_open函数。

(7)主要处理三种情形:打开文件,建立文件和符号链接

参考文献: <深入理解Linux内核第3版>




  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值