GNU Linux-libre 4.14.313-gnu1
[releases.git] / fs / proc / self.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/sched.h>
3 #include <linux/slab.h>
4 #include <linux/pid_namespace.h>
5 #include "internal.h"
6
7 /*
8  * /proc/self:
9  */
10 static const char *proc_self_get_link(struct dentry *dentry,
11                                       struct inode *inode,
12                                       struct delayed_call *done)
13 {
14         struct pid_namespace *ns = inode->i_sb->s_fs_info;
15         pid_t tgid = task_tgid_nr_ns(current, ns);
16         char *name;
17
18         /*
19          * Not currently supported. Once we can inherit all of struct pid,
20          * we can allow this.
21          */
22         if (current->flags & PF_KTHREAD)
23                 return ERR_PTR(-EOPNOTSUPP);
24
25         if (!tgid)
26                 return ERR_PTR(-ENOENT);
27         /* 11 for max length of signed int in decimal + NULL term */
28         name = kmalloc(12, dentry ? GFP_KERNEL : GFP_ATOMIC);
29         if (unlikely(!name))
30                 return dentry ? ERR_PTR(-ENOMEM) : ERR_PTR(-ECHILD);
31         sprintf(name, "%d", tgid);
32         set_delayed_call(done, kfree_link, name);
33         return name;
34 }
35
36 static const struct inode_operations proc_self_inode_operations = {
37         .get_link       = proc_self_get_link,
38 };
39
40 static unsigned self_inum;
41
42 int proc_setup_self(struct super_block *s)
43 {
44         struct inode *root_inode = d_inode(s->s_root);
45         struct pid_namespace *ns = s->s_fs_info;
46         struct dentry *self;
47         
48         inode_lock(root_inode);
49         self = d_alloc_name(s->s_root, "self");
50         if (self) {
51                 struct inode *inode = new_inode(s);
52                 if (inode) {
53                         inode->i_ino = 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_self_inode_operations;
59                         d_add(self, inode);
60                 } else {
61                         dput(self);
62                         self = ERR_PTR(-ENOMEM);
63                 }
64         } else {
65                 self = ERR_PTR(-ENOMEM);
66         }
67         inode_unlock(root_inode);
68         if (IS_ERR(self)) {
69                 pr_err("proc_fill_super: can't allocate /proc/self\n");
70                 return PTR_ERR(self);
71         }
72         ns->proc_self = self;
73         return 0;
74 }
75
76 void __init proc_self_init(void)
77 {
78         proc_alloc_inum(&self_inum);
79 }