thread_self.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <linux/sched.h>
  2. #include <linux/slab.h>
  3. #include <linux/pid_namespace.h>
  4. #include "internal.h"
  5. /*
  6. * /proc/thread_self:
  7. */
  8. static int proc_thread_self_readlink(struct dentry *dentry, char __user *buffer,
  9. int buflen)
  10. {
  11. struct pid_namespace *ns = dentry->d_sb->s_fs_info;
  12. pid_t tgid = task_tgid_nr_ns(current, ns);
  13. pid_t pid = task_pid_nr_ns(current, ns);
  14. char tmp[PROC_NUMBUF + 6 + PROC_NUMBUF];
  15. if (!pid)
  16. return -ENOENT;
  17. sprintf(tmp, "%d/task/%d", tgid, pid);
  18. return readlink_copy(buffer, buflen, tmp);
  19. }
  20. static const char *proc_thread_self_get_link(struct dentry *dentry,
  21. struct inode *inode,
  22. struct delayed_call *done)
  23. {
  24. struct pid_namespace *ns = inode->i_sb->s_fs_info;
  25. pid_t tgid = task_tgid_nr_ns(current, ns);
  26. pid_t pid = task_pid_nr_ns(current, ns);
  27. char *name;
  28. if (!pid)
  29. return ERR_PTR(-ENOENT);
  30. name = kmalloc(PROC_NUMBUF + 6 + PROC_NUMBUF,
  31. dentry ? GFP_KERNEL : GFP_ATOMIC);
  32. if (unlikely(!name))
  33. return dentry ? ERR_PTR(-ENOMEM) : ERR_PTR(-ECHILD);
  34. sprintf(name, "%d/task/%d", tgid, pid);
  35. set_delayed_call(done, kfree_link, name);
  36. return name;
  37. }
  38. static const struct inode_operations proc_thread_self_inode_operations = {
  39. .readlink = proc_thread_self_readlink,
  40. .get_link = proc_thread_self_get_link,
  41. };
  42. static unsigned thread_self_inum;
  43. int proc_setup_thread_self(struct super_block *s)
  44. {
  45. struct inode *root_inode = d_inode(s->s_root);
  46. struct pid_namespace *ns = s->s_fs_info;
  47. struct dentry *thread_self;
  48. inode_lock(root_inode);
  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(inode);
  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. inode_unlock(root_inode);
  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. }