thread_self.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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_follow_link(struct dentry *dentry, void **cookie)
  21. {
  22. struct pid_namespace *ns = dentry->d_sb->s_fs_info;
  23. pid_t tgid = task_tgid_nr_ns(current, ns);
  24. pid_t pid = task_pid_nr_ns(current, ns);
  25. char *name;
  26. if (!pid)
  27. return ERR_PTR(-ENOENT);
  28. name = kmalloc(PROC_NUMBUF + 6 + PROC_NUMBUF, GFP_KERNEL);
  29. if (!name)
  30. return ERR_PTR(-ENOMEM);
  31. sprintf(name, "%d/task/%d", tgid, pid);
  32. return *cookie = name;
  33. }
  34. static const struct inode_operations proc_thread_self_inode_operations = {
  35. .readlink = proc_thread_self_readlink,
  36. .follow_link = proc_thread_self_follow_link,
  37. .put_link = kfree_put_link,
  38. };
  39. static unsigned thread_self_inum;
  40. int proc_setup_thread_self(struct super_block *s)
  41. {
  42. struct inode *root_inode = d_inode(s->s_root);
  43. struct pid_namespace *ns = s->s_fs_info;
  44. struct dentry *thread_self;
  45. mutex_lock(&root_inode->i_mutex);
  46. thread_self = d_alloc_name(s->s_root, "thread-self");
  47. if (thread_self) {
  48. struct inode *inode = new_inode_pseudo(s);
  49. if (inode) {
  50. inode->i_ino = thread_self_inum;
  51. inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
  52. inode->i_mode = S_IFLNK | S_IRWXUGO;
  53. inode->i_uid = GLOBAL_ROOT_UID;
  54. inode->i_gid = GLOBAL_ROOT_GID;
  55. inode->i_op = &proc_thread_self_inode_operations;
  56. d_add(thread_self, inode);
  57. } else {
  58. dput(thread_self);
  59. thread_self = ERR_PTR(-ENOMEM);
  60. }
  61. } else {
  62. thread_self = ERR_PTR(-ENOMEM);
  63. }
  64. mutex_unlock(&root_inode->i_mutex);
  65. if (IS_ERR(thread_self)) {
  66. pr_err("proc_fill_super: can't allocate /proc/thread_self\n");
  67. return PTR_ERR(thread_self);
  68. }
  69. ns->proc_thread_self = thread_self;
  70. return 0;
  71. }
  72. void __init proc_thread_self_init(void)
  73. {
  74. proc_alloc_inum(&thread_self_inum);
  75. }