thread_self.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <linux/sched.h>
  2. #include <linux/namei.h>
  3. #include <linux/slab.h>
  4. #include <linux/pid_namespace.h>
  5. #include "internal.h"
  6. /*
  7. * /proc/thread_self:
  8. */
  9. static int proc_thread_self_readlink(struct dentry *dentry, char __user *buffer,
  10. int buflen)
  11. {
  12. struct pid_namespace *ns = dentry->d_sb->s_fs_info;
  13. pid_t tgid = task_tgid_nr_ns(current, ns);
  14. pid_t pid = task_pid_nr_ns(current, ns);
  15. char tmp[PROC_NUMBUF + 6 + PROC_NUMBUF];
  16. if (!pid)
  17. return -ENOENT;
  18. sprintf(tmp, "%d/task/%d", tgid, pid);
  19. return readlink_copy(buffer, buflen, tmp);
  20. }
  21. static void *proc_thread_self_follow_link(struct dentry *dentry, struct nameidata *nd)
  22. {
  23. struct pid_namespace *ns = dentry->d_sb->s_fs_info;
  24. pid_t tgid = task_tgid_nr_ns(current, ns);
  25. pid_t pid = task_pid_nr_ns(current, ns);
  26. char *name = ERR_PTR(-ENOENT);
  27. if (pid) {
  28. name = kmalloc(PROC_NUMBUF + 6 + PROC_NUMBUF, GFP_KERNEL);
  29. if (!name)
  30. name = ERR_PTR(-ENOMEM);
  31. else
  32. sprintf(name, "%d/task/%d", tgid, pid);
  33. }
  34. nd_set_link(nd, name);
  35. return NULL;
  36. }
  37. static const struct inode_operations proc_thread_self_inode_operations = {
  38. .readlink = proc_thread_self_readlink,
  39. .follow_link = proc_thread_self_follow_link,
  40. .put_link = kfree_put_link,
  41. };
  42. static unsigned thread_self_inum;
  43. int proc_setup_thread_self(struct super_block *s)
  44. {
  45. struct inode *root_inode = s->s_root->d_inode;
  46. struct pid_namespace *ns = s->s_fs_info;
  47. struct dentry *thread_self;
  48. mutex_lock(&root_inode->i_mutex);
  49. thread_self = d_alloc_name(s->s_root, "thread-self");
  50. if (thread_self) {
  51. struct inode *inode = new_inode_pseudo(s);
  52. if (inode) {
  53. inode->i_ino = thread_self_inum;
  54. inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
  55. inode->i_mode = S_IFLNK | S_IRWXUGO;
  56. inode->i_uid = GLOBAL_ROOT_UID;
  57. inode->i_gid = GLOBAL_ROOT_GID;
  58. inode->i_op = &proc_thread_self_inode_operations;
  59. d_add(thread_self, inode);
  60. } else {
  61. dput(thread_self);
  62. thread_self = ERR_PTR(-ENOMEM);
  63. }
  64. } else {
  65. thread_self = ERR_PTR(-ENOMEM);
  66. }
  67. mutex_unlock(&root_inode->i_mutex);
  68. if (IS_ERR(thread_self)) {
  69. pr_err("proc_fill_super: can't allocate /proc/thread_self\n");
  70. return PTR_ERR(thread_self);
  71. }
  72. ns->proc_thread_self = thread_self;
  73. return 0;
  74. }
  75. void __init proc_thread_self_init(void)
  76. {
  77. proc_alloc_inum(&thread_self_inum);
  78. }