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. if (force_o_largefile())
  6. flags |= O_LARGEFILE;
  7. //调用do_sys_open函数
  8. ret = do_sys_open(AT_FDCWD, filename, flags, mode);
  9. /* avoid REGPARM breakage on x86: */
  10. prevent_tail_call(ret);
  11. return ret;
  12. }

这个函数进行了简单的处理,调用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. if (!IS_ERR(tmp)) {
  7. /*得到一个没有使用的文件描述符*/
  8. fd = get_unused_fd();
  9. if (fd >= 0) {
  10. /*file对象是文件对象,存在于内存,所以没有回写,f_op被赋值*/
  11. struct file *f = do_filp_open(dfd, tmp, flags, mode);
  12. if (IS_ERR(f)) {
  13. put_unused_fd(fd);
  14. fd = PTR_ERR(f);
  15. } else {
  16. fsnotify_open(f->f_path.dentry);
  17. /*将current->files_struct和文件对象关联*/
  18. fd_install(fd, f);
  19. }
  20. }
  21. putname(tmp);
  22. }
  23. return fd;
  24. }

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

(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. repeat:
  14. /*返回files的fdt指针*/
  15. fdt = files_fdtable(files);
  16. /*从fdt->open_ds->fds_bits数组查找一个没有置位的文件描述符,open_ds表示打开的文件描述符集,当位图为1表示已经打开,为0已经关闭*/
  17. fd = find_next_zero_bit(fdt->open_fds->fds_bits, fdt->max_fds,
  18. files->next_fd);
  19. /*
  20. * N.B. For clone tasks sharing a files structure, this test
  21. * will limit the total number of files that can be opened.
  22. */
  23. if (fd >= current->signal->rlim[RLIMIT_NOFILE].rlim_cur)
  24. goto out;
  25. /* Do we need to expand the fd array or fd set?  */
  26. error = expand_files(files, fd);
  27. if (error < 0)
  28. goto out;
  29. if (error) {
  30. /*
  31. * If we needed to expand the fs array we
  32. * might have blocked - try again.
  33. */
  34. error = -EMFILE;
  35. goto repeat;
  36. }
  37. /*将文件描述符集合的fd置位*/
  38. FD_SET(fd, fdt->open_fds);
  39. FD_CLR(fd, fdt->close_on_exec);
  40. /*下一个描述符,即搜索的位置加1*/
  41. files->next_fd = fd + 1;
  42. #if 1
  43. /* Sanity check */
  44. if (fdt->fd[fd] != NULL) {
  45. printk(KERN_WARNING "get_unused_fd: slot %d not NULL!\n", fd);
  46. fdt->fd[fd] = NULL;
  47. }
  48. #endif
  49. error = fd;
  50. out:
  51. spin_unlock(&files->file_lock);
  52. return error;
  53. }

在第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. int namei_flags, error;
  19. /*创建nameidata结构体,返回的安装点对象和目录项对象放在此结构体*/
  20. struct nameidata nd;
  21. namei_flags = flags;
  22. if ((namei_flags+1) & O_ACCMODE)
  23. namei_flags++;
  24. /*根据上级的dentry对象得到新的dentry结构,并从中得到相关的inode节点号,再用iget函数分配新的inode结构,将新的dentry对象与inode对象关联起来*/
  25. error = open_namei(dfd, filename, namei_flags, mode, &nd);
  26. /*将nameidata结构体转化为struct file文件对象结构体*/
  27. if (!error)
  28. return nameidata_to_filp(&nd, flags);
  29. return ERR_PTR(error);
  30. }

初看起来,寥寥几行代码,貌似简单。其实不然,一会就知道了。此函数调用了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. /* Intent data */
  10. union {
  11. struct open_intent open;/*想要打开的文件的联合体*/
  12. } intent;
  13. };
[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. /* Pick up the filp from the open intent */
  12. /*取得文件指针*/
  13. filp = nd->intent.open.file;
  14. /* Has the filesystem initialised the file for us? */
  15. /*文件系统是否已经初始化了dentry*/
  16. if (filp->f_path.dentry == NULL)
  17. filp = __dentry_open(nd->dentry, nd->mnt, flags, filp, NULL);
  18. else
  19. path_release(nd);
  20. return filp;
  21. }

首先取得文件对象指针,然后判断文件对象是否已经初始化,如果没有初始化,就调用__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. f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
  40. /*预读初始化*/
  41. file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
  42. /* NB: we're sure to have correct a_ops only after f_op->open */
  43. if (f->f_flags & O_DIRECT) {
  44. if (!f->f_mapping->a_ops ||
  45. ((!f->f_mapping->a_ops->direct_IO) &&
  46. (!f->f_mapping->a_ops->get_xip_page))) {
  47. fput(f);
  48. f = ERR_PTR(-EINVAL);
  49. }
  50. }
  51. return f;
  52. cleanup_all:
  53. fops_put(f->f_op);
  54. if (f->f_mode & FMODE_WRITE)
  55. put_write_access(inode);
  56. file_kill(f);
  57. f->f_path.dentry = NULL;
  58. f->f_path.mnt = NULL;
  59. cleanup_file:
  60. put_filp(f);
  61. dput(dentry);
  62. mntput(mnt);
  63. return ERR_PTR(error);
  64. }

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

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

第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. /* make sure the stuff we saved doesn't go away */
  6. /*首先备份一下安装点对象和目录项对象*/
  7. dget(save.dentry);
  8. mntget(save.mnt);
  9. /*真正的名称解析函数*/
  10. result = __link_path_walk(name, nd);
  11. if (result == -ESTALE) {
  12. *nd = save;
  13. dget(nd->dentry);
  14. mntget(nd->mnt);
  15. nd->flags |= LOOKUP_REVAL;
  16. result = __link_path_walk(name, nd);
  17. }
  18. /*减少并释放备份的nameidata对象*/
  19. dput(save.dentry);
  20. mntput(save.mnt);
  21. return result;
  22. }

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

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

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

Linux open系统调用流程(3)

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

这个函数主要做三件事:

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

第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. need_lookup:
  25. /*如果dentry cache没有,则在内存分配一个dentry,并在内存分配索引节点,将dentry和索引节点关联*/
  26. dentry = real_lookup(nd->dentry, name, nd);
  27. if (IS_ERR(dentry))
  28. goto fail;
  29. goto done;
  30. need_revalidate:
  31. /*验证目录项对象是否还有效*/
  32. dentry = do_revalidate(dentry, nd);
  33. if (!dentry)
  34. goto need_lookup;
  35. if (IS_ERR(dentry))
  36. goto fail;
  37. goto done;
  38. fail:
  39. return PTR_ERR(dentry);
  40. }

这个函数的主要功能是查询目录项对象,并将挂载点和目录项对象保存在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. rcu_read_lock();
  12. /*dentry cache查找*/
  13. hlist_for_each_entry_rcu(dentry, node, head, d_hash) {
  14. struct qstr *qstr;
  15. /*hash值是否相同,hash值和名称相关联*/
  16. if (dentry->d_name.hash != hash)
  17. continue;
  18. /*父目录项是否是parent*/
  19. if (dentry->d_parent != parent)
  20. continue;
  21. spin_lock(&dentry->d_lock);
  22. /*
  23. * Recheck the dentry after taking the lock - d_move may have
  24. * changed things.  Don't bother checking the hash because we're
  25. * about to compare the whole name anyway.
  26. */
  27. if (dentry->d_parent != parent)
  28. goto next;
  29. /*
  30. * It is safe to compare names since d_move() cannot
  31. * change the qstr (protected by d_lock).
  32. */
  33. /*detnry->d_name表示分量名,长度*/
  34. qstr = &dentry->d_name;
  35. if (parent->d_op && parent->d_op->d_compare) {/*匹配分量名,不同文件系统可以有不同的实现,如MS-DOS不分大小写*/
  36. if (parent->d_op->d_compare(parent, qstr, name))
  37. goto next;
  38. } else {
  39. if (qstr->len != len)
  40. goto next;
  41. if (memcmp(qstr->name, str, len))
  42. goto next;
  43. }
  44. if (!d_unhashed(dentry)) {
  45. atomic_inc(&dentry->d_count);
  46. found = dentry;
  47. }
  48. spin_unlock(&dentry->d_lock);
  49. break;
  50. next:
  51. spin_unlock(&dentry->d_lock);
  52. }
  53. rcu_read_unlock();
  54. return found;
  55. }

第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. * Uhhuh! Nasty case: the cache was re-populated while
  49. * we waited on the semaphore. Need to revalidate.
  50. */
  51. mutex_unlock(&dir->i_mutex);
  52. if (result->d_op && result->d_op->d_revalidate) {
  53. result = do_revalidate(result, nd);
  54. if (!result)
  55. result = ERR_PTR(-ENOENT);
  56. }
  57. return result;
  58. }

在第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. struct dentry *d_alloc(struct dentry * parent, const struct qstr *name)
  11. {
  12. struct dentry *dentry;
  13. char *dname;
  14. dentry = kmem_cache_alloc(dentry_cache, GFP_KERNEL);
  15. if (!dentry)
  16. return NULL;
  17. if (name->len > DNAME_INLINE_LEN-1) {
  18. dname = kmalloc(name->len + 1, GFP_KERNEL);
  19. if (!dname) {
  20. kmem_cache_free(dentry_cache, dentry);
  21. return NULL;
  22. }
  23. } else  {
  24. dname = dentry->d_iname;
  25. }
  26. dentry->d_name.name = dname;
  27. dentry->d_name.len = name->len;
  28. dentry->d_name.hash = name->hash;
  29. memcpy(dname, name->name, name->len);
  30. dname[name->len] = 0;
  31. atomic_set(&dentry->d_count, 1);
  32. dentry->d_flags = DCACHE_UNHASHED;
  33. spin_lock_init(&dentry->d_lock);
  34. dentry->d_inode = NULL;
  35. dentry->d_parent = NULL;
  36. dentry->d_sb = NULL;
  37. dentry->d_op = NULL;
  38. dentry->d_fsdata = NULL;
  39. dentry->d_mounted = 0;
  40. #ifdef CONFIG_PROFILING
  41. dentry->d_cookie = NULL;
  42. #endif
  43. INIT_HLIST_NODE(&dentry->d_hash);
  44. INIT_LIST_HEAD(&dentry->d_lru);
  45. INIT_LIST_HEAD(&dentry->d_subdirs);
  46. INIT_LIST_HEAD(&dentry->d_alias);
  47. if (parent) {
  48. /*设置父目录项对象为parent*/
  49. dentry->d_parent = dget(parent);
  50. /*目录项对象对应的超级块对象*/
  51. dentry->d_sb = parent->d_sb;
  52. } else {
  53. INIT_LIST_HEAD(&dentry->d_u.d_child);
  54. }
  55. spin_lock(&dcache_lock);
  56. if (parent)
  57. list_add(&dentry->d_u.d_child, &parent->d_subdirs);
  58. dentry_stat.nr_dentry++;
  59. spin_unlock(&dcache_lock);
  60. return dentry;
  61. }

第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. if (dentry->d_name.len > EXT3_NAME_LEN)
  8. return ERR_PTR(-ENAMETOOLONG);
  9. /*得到ext3_dir_entry_2对象,该对象包含inode节点号,再根据inode节点后从超级块的read_inode得到inode结构体*/
  10. bh = ext3_find_entry(dentry, &de);
  11. inode = NULL;
  12. if (bh) {
  13. unsigned long ino = le32_to_cpu(de->inode);
  14. brelse (bh);
  15. if (!ext3_valid_inum(dir->i_sb, ino)) {
  16. ext3_error(dir->i_sb, "ext3_lookup",
  17. "bad inode number: %lu", ino);
  18. inode = NULL;
  19. } else
  20. /*创建内存索引节点,并填充相关信息,i_fop,并将索引节点加入inode cache*/
  21. inode = iget(dir->i_sb, ino);
  22. if (!inode)
  23. return ERR_PTR(-EACCES);
  24. }
  25. /*将目录项对象关联inode节点*/
  26. return d_splice_alias(inode, dentry);
  27. }

第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. return inode;
  11. }

首先调用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. spin_lock(&inode_lock);
  13. /* We released the lock, so.. */
  14. old = find_inode_fast(sb, head, ino);
  15. if (!old) {
  16. /*设置索引节点号*/
  17. inode->i_ino = ino;
  18. inodes_stat.nr_inodes++;
  19. /*加入已经使用链表inode_in_use*/
  20. list_add(&inode->i_list, &inode_in_use);
  21. /*加入超级块链表*/
  22. list_add(&inode->i_sb_list, &sb->s_inodes);
  23. /*加入inode_hashtable*/
  24. hlist_add_head(&inode->i_hash, head);
  25. /*设置状态*/
  26. inode->i_state = I_LOCK|I_NEW;
  27. spin_unlock(&inode_lock);
  28. /* Return the locked inode with I_NEW set, the
  29. * caller is responsible for filling in the contents
  30. */
  31. return inode;
  32. }
  33. /*
  34. * Uhhuh, somebody else created the same inode under
  35. * us. Use the old inode instead of the one we just
  36. * allocated.
  37. */
  38. __iget(old);
  39. spin_unlock(&inode_lock);
  40. destroy_inode(inode);
  41. inode = old;
  42. wait_on_inode(inode);
  43. }
  44. return inode;
  45. }

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

简单说一下功能:

第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. if (inode && S_ISDIR(inode->i_mode)) {
  21. spin_lock(&dcache_lock);
  22. new = __d_find_alias(inode, 1);
  23. if (new) {
  24. BUG_ON(!(new->d_flags & DCACHE_DISCONNECTED));
  25. fsnotify_d_instantiate(new, inode);
  26. spin_unlock(&dcache_lock);
  27. security_d_instantiate(new, inode);
  28. d_rehash(dentry);
  29. d_move(new, dentry);
  30. iput(inode);
  31. } else {
  32. /* d_instantiate takes dcache_lock, so we do it by hand */
  33. /*加入正在使用目录项链表,即表头在i_dentry*/
  34. list_add(&dentry->d_alias, &inode->i_dentry);
  35. /*目录项对象和索引节点对象关联*/
  36. dentry->d_inode = inode;
  37. fsnotify_d_instantiate(dentry, inode);
  38. spin_unlock(&dcache_lock);
  39. security_d_instantiate(dentry, inode);
  40. /*将目录项对象加入dentry_hashtable即目录项缓存*/
  41. d_rehash(dentry);
  42. }
  43. } else
  44. d_add(dentry, inode);
  45. return new;
  46. }

第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. touch_atime(path->mnt, dentry);/*更新inode节点的存取时间*/
  7. /*先将nd->saved_names数组置空*/
  8. nd_set_link(nd, NULL);
  9. if (path->mnt != nd->mnt) {
  10. path_to_nameidata(path, nd);
  11. dget(dentry);
  12. }
  13. mntget(path->mnt);
  14. cookie = dentry->d_inode->i_op->follow_link(dentry, nd);/*提取存储在符号链接的路径,并保存在nd->saved_names数组*/
  15. error = PTR_ERR(cookie);
  16. if (!IS_ERR(cookie)) {
  17. /*路径名放在s*/
  18. char *s = nd_get_link(nd);
  19. error = 0;
  20. if (s)
  21. error = __vfs_follow_link(nd, s);/*解析路径名*/
  22. if (dentry->d_inode->i_op->put_link)
  23. dentry->d_inode->i_op->put_link(dentry, nd, cookie);
  24. }
  25. dput(dentry);
  26. mntput(path->mnt);
  27. return error;
  28. }

第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. if (!IS_POSIXACL(dir->d_inode))
  7. mode &= ~current->fs->umask;
  8. error = vfs_create(dir->d_inode, path->dentry, mode, nd);
  9. mutex_unlock(&dir->d_inode->i_mutex);
  10. dput(nd->dentry);
  11. nd->dentry = path->dentry;/*更改nd目录项对象指向新创建的文件*/
  12. if (error)
  13. return error;
  14. /* Don't check for write permission, don't truncate */
  15. return may_open(nd, 0, flag & ~O_TRUNC);
  16. }

封装了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. if (error)
  6. return error;
  7. if (!dir->i_op || !dir->i_op->create)
  8. return -EACCES; /* shouldn't it be ENOSYS? */
  9. mode &= S_IALLUGO;
  10. mode |= S_IFREG;
  11. error = security_inode_create(dir, dentry, mode);
  12. if (error)
  13. return error;
  14. DQUOT_INIT(dir);
  15. error = dir->i_op->create(dir, dentry, mode, nd);
  16. if (!error)
  17. fsnotify_create(dir, dentry);
  18. return error;
  19. }

调用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. retry:
  16. handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS(dir->i_sb) +
  17. EXT3_INDEX_EXTRA_TRANS_BLOCKS + 3 +
  18. 2*EXT3_QUOTA_INIT_BLOCKS(dir->i_sb));
  19. if (IS_ERR(handle))
  20. return PTR_ERR(handle);
  21. if (IS_DIRSYNC(dir))
  22. handle->h_sync = 1;
  23. inode = ext3_new_inode (handle, dir, mode);
  24. err = PTR_ERR(inode);
  25. if (!IS_ERR(inode)) {
  26. inode->i_op = &ext3_file_inode_operations;
  27. inode->i_fop = &ext3_file_operations;
  28. ext3_set_aops(inode);
  29. err = ext3_add_nondir(handle, dentry, inode);
  30. }
  31. ext3_journal_stop(handle);
  32. if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))
  33. goto retry;
  34. return err;
  35. }

第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版>

Linux open系统调用流程相关推荐

  1. 基于 arm64 Linux nanosleep 系统调用流程分析

    nanosleep (高分辨率睡眠)可实现纳秒级的睡眠,暂停调用线程的执行.在 Linux 内核中是如何实现的?下面基于 arm64 cpu 架构去分析. #include <time.h> ...

  2. Linux的系统调用、网络连接状态、磁盘I/O;可疑行为监控/日志收集、SHELL命令执行流程

    http://man7.org/linux/man-pages/man7/capabilities.7.html http://www.cnblogs.com/LittleHann/p/3850653 ...

  3. 【内核】linux内核启动流程详细分析【转】

    转自:http://www.cnblogs.com/lcw/p/3337937.html Linux内核启动流程 arch/arm/kernel/head-armv.S 该文件是内核最先执行的一个文件 ...

  4. 【内核】linux内核启动流程详细分析

    Linux内核启动流程 arch/arm/kernel/head-armv.S 该文件是内核最先执行的一个文件,包括内核入口ENTRY(stext)到start_kernel间的初始化代码, 主要作用 ...

  5. open函数返回-1_4.6 linux的系统调用执行探究(1)

    arm64大约支持280个系统调用,我们平时使用的这些系统调用,到底工作原理是什么,调用后又是到哪里实现的呢,这篇文章初步了解下内核系统调用的流程,并告诉跟踪这个流程的方法. 废话不多说,如上就是li ...

  6. Linux的启动流程简析(以Debian为例)

    Linux的启动流程简析(以Debian为例) 正文: 前面的文章探讨BIOS和主引导记录的作用.那篇文章不涉及操作系统,只与主板的板载程序有关.今天,我想接着往下写,探讨操作系统接管硬件以后发生的事 ...

  7. linux操作系统启动流程与kickstart文件制作

    文章目录 一.Linux操作系统启动流程 1.1.简单回顾linux系统组成以及内核作用 1.2.简单了解一下磁盘构成以及相关基础知识 二.CentOS 启动流程(只适用于MBR类型的PC架构主机) ...

  8. Linux开机启动流程分析

    Linux开机启动十步骤 收藏分享2012-2-6 11:15| 发布者: 红黑魂| 查看数: 1366| 评论数: 0|来自: 比特网 摘要: 开机过程指的是从打开计算机电源直到LINUX显示用户登 ...

  9. 文件编程之Linux下系统调用

    说明: linux下文件编程可使用两种方法: ****linux系统调用 ****C语言库函数 前者依赖于linux系统,后者与操作系统是独立的. 在任何操作系统下,使用C语言库函数操作文件的方法都是 ...

最新文章

  1. java card applet_可多选的javacard applet | 学步园
  2. Python学习全家桶,Python初学者十一个热门问题
  3. 设计模式 命令模式 之 管理智能家电
  4. 简述基于EDA技术的FPGA设计
  5. kali linux下安装TOR
  6. 信息收集——Office钓鱼
  7. mysql环境变量的配置
  8. 二分法:木棒切割问题
  9. 教资高中计算机知识点,如何备考教师资格证高中信息技术
  10. 汽车EMI/EMC测试标准ISO7637-2详解
  11. 用R做meta分析(附效应量计算神器)
  12. nginx学习:搭建静态资源服务器
  13. html全屏显示两个显示器,google-chrome – 跨多个显示器的Windows / Chrome / ATI /浏览器全屏...
  14. linux服务器开机管理,中标麒麟Linux服务器操作系统启动管理(29页)-原创力文档...
  15. Java 在Word中创建多级项目符号列表和编号列表
  16. 最好的 6 个免费天气 API 接口对比测评
  17. offline translator android app,PROMT Offline Translator English Pack
  18. ZigBee网络数据传递流程_蓝牙、WIFI、Zigbee谁更适合物联网,各有哪些优缺点?...
  19. 【综述】对话系统中的口语理解技术
  20. spring boot指定运行环境

热门文章

  1. android 蓝牙控制开发,Android开发工控软件--蓝牙控制
  2. 【转】HTTP认证机制
  3. 8大网页设计新趋势(转载)
  4. #今日论文推荐#ACL 2022 | 引入角度margin构建对比学习目标,增强文本语义判别能力
  5. idea调试如何回退到上个断点
  6. 《C#设计模式》【装饰者模式】
  7. JavaScript 技术篇 - js 查看哪个元素获取了焦点,js 指定元素获取焦点方法
  8. 【第五届集创赛备赛】九、SD卡控制器开发总结
  9. 【标准解读】JJG 126-2022实施,该如何选择变送器检定方案?
  10. 元宵节动画贺卡制作_2016猴年动画版元宵节flash贺卡(2份)