• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * /proc/sys support
4  */
5 #include <linux/init.h>
6 #include <linux/sysctl.h>
7 #include <linux/poll.h>
8 #include <linux/proc_fs.h>
9 #include <linux/printk.h>
10 #include <linux/security.h>
11 #include <linux/sched.h>
12 #include <linux/cred.h>
13 #include <linux/namei.h>
14 #include <linux/mm.h>
15 #include <linux/uio.h>
16 #include <linux/module.h>
17 #include <linux/bpf-cgroup.h>
18 #include <linux/mount.h>
19 #include <linux/kmemleak.h>
20 #include "internal.h"
21 
22 #define list_for_each_table_entry(entry, header)	\
23 	entry = header->ctl_table;			\
24 	for (size_t i = 0 ; i < header->ctl_table_size; ++i, entry++)
25 
26 static const struct dentry_operations proc_sys_dentry_operations;
27 static const struct file_operations proc_sys_file_operations;
28 static const struct inode_operations proc_sys_inode_operations;
29 static const struct file_operations proc_sys_dir_file_operations;
30 static const struct inode_operations proc_sys_dir_operations;
31 
32 /*
33  * Support for permanently empty directories.
34  * Must be non-empty to avoid sharing an address with other tables.
35  */
36 static struct ctl_table sysctl_mount_point[] = {
37 	{ }
38 };
39 
40 /**
41  * register_sysctl_mount_point() - registers a sysctl mount point
42  * @path: path for the mount point
43  *
44  * Used to create a permanently empty directory to serve as mount point.
45  * There are some subtle but important permission checks this allows in the
46  * case of unprivileged mounts.
47  */
register_sysctl_mount_point(const char * path)48 struct ctl_table_header *register_sysctl_mount_point(const char *path)
49 {
50 	return register_sysctl_sz(path, sysctl_mount_point, 0);
51 }
52 EXPORT_SYMBOL(register_sysctl_mount_point);
53 
54 #define sysctl_is_perm_empty_ctl_header(hptr)		\
55 	(hptr->type == SYSCTL_TABLE_TYPE_PERMANENTLY_EMPTY)
56 #define sysctl_set_perm_empty_ctl_header(hptr)		\
57 	(hptr->type = SYSCTL_TABLE_TYPE_PERMANENTLY_EMPTY)
58 #define sysctl_clear_perm_empty_ctl_header(hptr)	\
59 	(hptr->type = SYSCTL_TABLE_TYPE_DEFAULT)
60 
proc_sys_poll_notify(struct ctl_table_poll * poll)61 void proc_sys_poll_notify(struct ctl_table_poll *poll)
62 {
63 	if (!poll)
64 		return;
65 
66 	atomic_inc(&poll->event);
67 	wake_up_interruptible(&poll->wait);
68 }
69 
70 static struct ctl_table root_table[] = {
71 	{
72 		.procname = "",
73 		.mode = S_IFDIR|S_IRUGO|S_IXUGO,
74 	},
75 };
76 static struct ctl_table_root sysctl_table_root = {
77 	.default_set.dir.header = {
78 		{{.count = 1,
79 		  .nreg = 1,
80 		  .ctl_table = root_table }},
81 		.ctl_table_arg = root_table,
82 		.root = &sysctl_table_root,
83 		.set = &sysctl_table_root.default_set,
84 	},
85 };
86 
87 static DEFINE_SPINLOCK(sysctl_lock);
88 
89 static void drop_sysctl_table(struct ctl_table_header *header);
90 static int sysctl_follow_link(struct ctl_table_header **phead,
91 	struct ctl_table **pentry);
92 static int insert_links(struct ctl_table_header *head);
93 static void put_links(struct ctl_table_header *header);
94 
sysctl_print_dir(struct ctl_dir * dir)95 static void sysctl_print_dir(struct ctl_dir *dir)
96 {
97 	if (dir->header.parent)
98 		sysctl_print_dir(dir->header.parent);
99 	pr_cont("%s/", dir->header.ctl_table[0].procname);
100 }
101 
namecmp(const char * name1,int len1,const char * name2,int len2)102 static int namecmp(const char *name1, int len1, const char *name2, int len2)
103 {
104 	int cmp;
105 
106 	cmp = memcmp(name1, name2, min(len1, len2));
107 	if (cmp == 0)
108 		cmp = len1 - len2;
109 	return cmp;
110 }
111 
112 /* Called under sysctl_lock */
find_entry(struct ctl_table_header ** phead,struct ctl_dir * dir,const char * name,int namelen)113 static struct ctl_table *find_entry(struct ctl_table_header **phead,
114 	struct ctl_dir *dir, const char *name, int namelen)
115 {
116 	struct ctl_table_header *head;
117 	struct ctl_table *entry;
118 	struct rb_node *node = dir->root.rb_node;
119 
120 	while (node)
121 	{
122 		struct ctl_node *ctl_node;
123 		const char *procname;
124 		int cmp;
125 
126 		ctl_node = rb_entry(node, struct ctl_node, node);
127 		head = ctl_node->header;
128 		entry = &head->ctl_table[ctl_node - head->node];
129 		procname = entry->procname;
130 
131 		cmp = namecmp(name, namelen, procname, strlen(procname));
132 		if (cmp < 0)
133 			node = node->rb_left;
134 		else if (cmp > 0)
135 			node = node->rb_right;
136 		else {
137 			*phead = head;
138 			return entry;
139 		}
140 	}
141 	return NULL;
142 }
143 
insert_entry(struct ctl_table_header * head,struct ctl_table * entry)144 static int insert_entry(struct ctl_table_header *head, struct ctl_table *entry)
145 {
146 	struct rb_node *node = &head->node[entry - head->ctl_table].node;
147 	struct rb_node **p = &head->parent->root.rb_node;
148 	struct rb_node *parent = NULL;
149 	const char *name = entry->procname;
150 	int namelen = strlen(name);
151 
152 	while (*p) {
153 		struct ctl_table_header *parent_head;
154 		struct ctl_table *parent_entry;
155 		struct ctl_node *parent_node;
156 		const char *parent_name;
157 		int cmp;
158 
159 		parent = *p;
160 		parent_node = rb_entry(parent, struct ctl_node, node);
161 		parent_head = parent_node->header;
162 		parent_entry = &parent_head->ctl_table[parent_node - parent_head->node];
163 		parent_name = parent_entry->procname;
164 
165 		cmp = namecmp(name, namelen, parent_name, strlen(parent_name));
166 		if (cmp < 0)
167 			p = &(*p)->rb_left;
168 		else if (cmp > 0)
169 			p = &(*p)->rb_right;
170 		else {
171 			pr_err("sysctl duplicate entry: ");
172 			sysctl_print_dir(head->parent);
173 			pr_cont("%s\n", entry->procname);
174 			return -EEXIST;
175 		}
176 	}
177 
178 	rb_link_node(node, parent, p);
179 	rb_insert_color(node, &head->parent->root);
180 	return 0;
181 }
182 
erase_entry(struct ctl_table_header * head,struct ctl_table * entry)183 static void erase_entry(struct ctl_table_header *head, struct ctl_table *entry)
184 {
185 	struct rb_node *node = &head->node[entry - head->ctl_table].node;
186 
187 	rb_erase(node, &head->parent->root);
188 }
189 
init_header(struct ctl_table_header * head,struct ctl_table_root * root,struct ctl_table_set * set,struct ctl_node * node,struct ctl_table * table,size_t table_size)190 static void init_header(struct ctl_table_header *head,
191 	struct ctl_table_root *root, struct ctl_table_set *set,
192 	struct ctl_node *node, struct ctl_table *table, size_t table_size)
193 {
194 	head->ctl_table = table;
195 	head->ctl_table_size = table_size;
196 	head->ctl_table_arg = table;
197 	head->used = 0;
198 	head->count = 1;
199 	head->nreg = 1;
200 	head->unregistering = NULL;
201 	head->root = root;
202 	head->set = set;
203 	head->parent = NULL;
204 	head->node = node;
205 	INIT_HLIST_HEAD(&head->inodes);
206 	if (node) {
207 		struct ctl_table *entry;
208 
209 		list_for_each_table_entry(entry, head) {
210 			node->header = head;
211 			node++;
212 		}
213 	}
214 	if (table == sysctl_mount_point)
215 		sysctl_set_perm_empty_ctl_header(head);
216 }
217 
erase_header(struct ctl_table_header * head)218 static void erase_header(struct ctl_table_header *head)
219 {
220 	struct ctl_table *entry;
221 
222 	list_for_each_table_entry(entry, head)
223 		erase_entry(head, entry);
224 }
225 
insert_header(struct ctl_dir * dir,struct ctl_table_header * header)226 static int insert_header(struct ctl_dir *dir, struct ctl_table_header *header)
227 {
228 	struct ctl_table *entry;
229 	struct ctl_table_header *dir_h = &dir->header;
230 	int err;
231 
232 
233 	/* Is this a permanently empty directory? */
234 	if (sysctl_is_perm_empty_ctl_header(dir_h))
235 		return -EROFS;
236 
237 	/* Am I creating a permanently empty directory? */
238 	if (sysctl_is_perm_empty_ctl_header(header)) {
239 		if (!RB_EMPTY_ROOT(&dir->root))
240 			return -EINVAL;
241 		sysctl_set_perm_empty_ctl_header(dir_h);
242 	}
243 
244 	dir_h->nreg++;
245 	header->parent = dir;
246 	err = insert_links(header);
247 	if (err)
248 		goto fail_links;
249 	list_for_each_table_entry(entry, header) {
250 		err = insert_entry(header, entry);
251 		if (err)
252 			goto fail;
253 	}
254 	return 0;
255 fail:
256 	erase_header(header);
257 	put_links(header);
258 fail_links:
259 	if (header->ctl_table == sysctl_mount_point)
260 		sysctl_clear_perm_empty_ctl_header(dir_h);
261 	header->parent = NULL;
262 	drop_sysctl_table(dir_h);
263 	return err;
264 }
265 
266 /* called under sysctl_lock */
use_table(struct ctl_table_header * p)267 static int use_table(struct ctl_table_header *p)
268 {
269 	if (unlikely(p->unregistering))
270 		return 0;
271 	p->used++;
272 	return 1;
273 }
274 
275 /* called under sysctl_lock */
unuse_table(struct ctl_table_header * p)276 static void unuse_table(struct ctl_table_header *p)
277 {
278 	if (!--p->used)
279 		if (unlikely(p->unregistering))
280 			complete(p->unregistering);
281 }
282 
proc_sys_invalidate_dcache(struct ctl_table_header * head)283 static void proc_sys_invalidate_dcache(struct ctl_table_header *head)
284 {
285 	proc_invalidate_siblings_dcache(&head->inodes, &sysctl_lock);
286 }
287 
288 /* called under sysctl_lock, will reacquire if has to wait */
start_unregistering(struct ctl_table_header * p)289 static void start_unregistering(struct ctl_table_header *p)
290 {
291 	/*
292 	 * if p->used is 0, nobody will ever touch that entry again;
293 	 * we'll eliminate all paths to it before dropping sysctl_lock
294 	 */
295 	if (unlikely(p->used)) {
296 		struct completion wait;
297 		init_completion(&wait);
298 		p->unregistering = &wait;
299 		spin_unlock(&sysctl_lock);
300 		wait_for_completion(&wait);
301 	} else {
302 		/* anything non-NULL; we'll never dereference it */
303 		p->unregistering = ERR_PTR(-EINVAL);
304 		spin_unlock(&sysctl_lock);
305 	}
306 	/*
307 	 * Invalidate dentries for unregistered sysctls: namespaced sysctls
308 	 * can have duplicate names and contaminate dcache very badly.
309 	 */
310 	proc_sys_invalidate_dcache(p);
311 	/*
312 	 * do not remove from the list until nobody holds it; walking the
313 	 * list in do_sysctl() relies on that.
314 	 */
315 	spin_lock(&sysctl_lock);
316 	erase_header(p);
317 }
318 
sysctl_head_grab(struct ctl_table_header * head)319 static struct ctl_table_header *sysctl_head_grab(struct ctl_table_header *head)
320 {
321 	BUG_ON(!head);
322 	spin_lock(&sysctl_lock);
323 	if (!use_table(head))
324 		head = ERR_PTR(-ENOENT);
325 	spin_unlock(&sysctl_lock);
326 	return head;
327 }
328 
sysctl_head_finish(struct ctl_table_header * head)329 static void sysctl_head_finish(struct ctl_table_header *head)
330 {
331 	if (!head)
332 		return;
333 	spin_lock(&sysctl_lock);
334 	unuse_table(head);
335 	spin_unlock(&sysctl_lock);
336 }
337 
338 static struct ctl_table_set *
lookup_header_set(struct ctl_table_root * root)339 lookup_header_set(struct ctl_table_root *root)
340 {
341 	struct ctl_table_set *set = &root->default_set;
342 	if (root->lookup)
343 		set = root->lookup(root);
344 	return set;
345 }
346 
lookup_entry(struct ctl_table_header ** phead,struct ctl_dir * dir,const char * name,int namelen)347 static struct ctl_table *lookup_entry(struct ctl_table_header **phead,
348 				      struct ctl_dir *dir,
349 				      const char *name, int namelen)
350 {
351 	struct ctl_table_header *head;
352 	struct ctl_table *entry;
353 
354 	spin_lock(&sysctl_lock);
355 	entry = find_entry(&head, dir, name, namelen);
356 	if (entry && use_table(head))
357 		*phead = head;
358 	else
359 		entry = NULL;
360 	spin_unlock(&sysctl_lock);
361 	return entry;
362 }
363 
first_usable_entry(struct rb_node * node)364 static struct ctl_node *first_usable_entry(struct rb_node *node)
365 {
366 	struct ctl_node *ctl_node;
367 
368 	for (;node; node = rb_next(node)) {
369 		ctl_node = rb_entry(node, struct ctl_node, node);
370 		if (use_table(ctl_node->header))
371 			return ctl_node;
372 	}
373 	return NULL;
374 }
375 
first_entry(struct ctl_dir * dir,struct ctl_table_header ** phead,struct ctl_table ** pentry)376 static void first_entry(struct ctl_dir *dir,
377 	struct ctl_table_header **phead, struct ctl_table **pentry)
378 {
379 	struct ctl_table_header *head = NULL;
380 	struct ctl_table *entry = NULL;
381 	struct ctl_node *ctl_node;
382 
383 	spin_lock(&sysctl_lock);
384 	ctl_node = first_usable_entry(rb_first(&dir->root));
385 	spin_unlock(&sysctl_lock);
386 	if (ctl_node) {
387 		head = ctl_node->header;
388 		entry = &head->ctl_table[ctl_node - head->node];
389 	}
390 	*phead = head;
391 	*pentry = entry;
392 }
393 
next_entry(struct ctl_table_header ** phead,struct ctl_table ** pentry)394 static void next_entry(struct ctl_table_header **phead, struct ctl_table **pentry)
395 {
396 	struct ctl_table_header *head = *phead;
397 	struct ctl_table *entry = *pentry;
398 	struct ctl_node *ctl_node = &head->node[entry - head->ctl_table];
399 
400 	spin_lock(&sysctl_lock);
401 	unuse_table(head);
402 
403 	ctl_node = first_usable_entry(rb_next(&ctl_node->node));
404 	spin_unlock(&sysctl_lock);
405 	head = NULL;
406 	if (ctl_node) {
407 		head = ctl_node->header;
408 		entry = &head->ctl_table[ctl_node - head->node];
409 	}
410 	*phead = head;
411 	*pentry = entry;
412 }
413 
414 /*
415  * sysctl_perm does NOT grant the superuser all rights automatically, because
416  * some sysctl variables are readonly even to root.
417  */
418 
test_perm(int mode,int op)419 static int test_perm(int mode, int op)
420 {
421 	if (uid_eq(current_euid(), GLOBAL_ROOT_UID))
422 		mode >>= 6;
423 	else if (in_egroup_p(GLOBAL_ROOT_GID))
424 		mode >>= 3;
425 	if ((op & ~mode & (MAY_READ|MAY_WRITE|MAY_EXEC)) == 0)
426 		return 0;
427 	return -EACCES;
428 }
429 
sysctl_perm(struct ctl_table_header * head,struct ctl_table * table,int op)430 static int sysctl_perm(struct ctl_table_header *head, struct ctl_table *table, int op)
431 {
432 	struct ctl_table_root *root = head->root;
433 	int mode;
434 
435 	if (root->permissions)
436 		mode = root->permissions(head, table);
437 	else
438 		mode = table->mode;
439 
440 	return test_perm(mode, op);
441 }
442 
proc_sys_make_inode(struct super_block * sb,struct ctl_table_header * head,struct ctl_table * table)443 static struct inode *proc_sys_make_inode(struct super_block *sb,
444 		struct ctl_table_header *head, struct ctl_table *table)
445 {
446 	struct ctl_table_root *root = head->root;
447 	struct inode *inode;
448 	struct proc_inode *ei;
449 
450 	inode = new_inode(sb);
451 	if (!inode)
452 		return ERR_PTR(-ENOMEM);
453 
454 	inode->i_ino = get_next_ino();
455 
456 	ei = PROC_I(inode);
457 
458 	spin_lock(&sysctl_lock);
459 	if (unlikely(head->unregistering)) {
460 		spin_unlock(&sysctl_lock);
461 		iput(inode);
462 		return ERR_PTR(-ENOENT);
463 	}
464 	ei->sysctl = head;
465 	ei->sysctl_entry = table;
466 	hlist_add_head_rcu(&ei->sibling_inodes, &head->inodes);
467 	head->count++;
468 	spin_unlock(&sysctl_lock);
469 
470 	simple_inode_init_ts(inode);
471 	inode->i_mode = table->mode;
472 	if (!S_ISDIR(table->mode)) {
473 		inode->i_mode |= S_IFREG;
474 		inode->i_op = &proc_sys_inode_operations;
475 		inode->i_fop = &proc_sys_file_operations;
476 	} else {
477 		inode->i_mode |= S_IFDIR;
478 		inode->i_op = &proc_sys_dir_operations;
479 		inode->i_fop = &proc_sys_dir_file_operations;
480 		if (sysctl_is_perm_empty_ctl_header(head))
481 			make_empty_dir_inode(inode);
482 	}
483 
484 	inode->i_uid = GLOBAL_ROOT_UID;
485 	inode->i_gid = GLOBAL_ROOT_GID;
486 	if (root->set_ownership)
487 		root->set_ownership(head, &inode->i_uid, &inode->i_gid);
488 
489 	return inode;
490 }
491 
proc_sys_evict_inode(struct inode * inode,struct ctl_table_header * head)492 void proc_sys_evict_inode(struct inode *inode, struct ctl_table_header *head)
493 {
494 	spin_lock(&sysctl_lock);
495 	hlist_del_init_rcu(&PROC_I(inode)->sibling_inodes);
496 	if (!--head->count)
497 		kfree_rcu(head, rcu);
498 	spin_unlock(&sysctl_lock);
499 }
500 
grab_header(struct inode * inode)501 static struct ctl_table_header *grab_header(struct inode *inode)
502 {
503 	struct ctl_table_header *head = PROC_I(inode)->sysctl;
504 	if (!head)
505 		head = &sysctl_table_root.default_set.dir.header;
506 	return sysctl_head_grab(head);
507 }
508 
proc_sys_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)509 static struct dentry *proc_sys_lookup(struct inode *dir, struct dentry *dentry,
510 					unsigned int flags)
511 {
512 	struct ctl_table_header *head = grab_header(dir);
513 	struct ctl_table_header *h = NULL;
514 	const struct qstr *name = &dentry->d_name;
515 	struct ctl_table *p;
516 	struct inode *inode;
517 	struct dentry *err = ERR_PTR(-ENOENT);
518 	struct ctl_dir *ctl_dir;
519 	int ret;
520 
521 	if (IS_ERR(head))
522 		return ERR_CAST(head);
523 
524 	ctl_dir = container_of(head, struct ctl_dir, header);
525 
526 	p = lookup_entry(&h, ctl_dir, name->name, name->len);
527 	if (!p)
528 		goto out;
529 
530 	if (S_ISLNK(p->mode)) {
531 		ret = sysctl_follow_link(&h, &p);
532 		err = ERR_PTR(ret);
533 		if (ret)
534 			goto out;
535 	}
536 
537 	d_set_d_op(dentry, &proc_sys_dentry_operations);
538 	inode = proc_sys_make_inode(dir->i_sb, h ? h : head, p);
539 	err = d_splice_alias(inode, dentry);
540 
541 out:
542 	if (h)
543 		sysctl_head_finish(h);
544 	sysctl_head_finish(head);
545 	return err;
546 }
547 
proc_sys_call_handler(struct kiocb * iocb,struct iov_iter * iter,int write)548 static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter,
549 		int write)
550 {
551 	struct inode *inode = file_inode(iocb->ki_filp);
552 	struct ctl_table_header *head = grab_header(inode);
553 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
554 	size_t count = iov_iter_count(iter);
555 	char *kbuf;
556 	ssize_t error;
557 
558 	if (IS_ERR(head))
559 		return PTR_ERR(head);
560 
561 	/*
562 	 * At this point we know that the sysctl was not unregistered
563 	 * and won't be until we finish.
564 	 */
565 	error = -EPERM;
566 	if (sysctl_perm(head, table, write ? MAY_WRITE : MAY_READ))
567 		goto out;
568 
569 	/* if that can happen at all, it should be -EINVAL, not -EISDIR */
570 	error = -EINVAL;
571 	if (!table->proc_handler)
572 		goto out;
573 
574 	/* don't even try if the size is too large */
575 	error = -ENOMEM;
576 	if (count >= KMALLOC_MAX_SIZE)
577 		goto out;
578 	kbuf = kvzalloc(count + 1, GFP_KERNEL);
579 	if (!kbuf)
580 		goto out;
581 
582 	if (write) {
583 		error = -EFAULT;
584 		if (!copy_from_iter_full(kbuf, count, iter))
585 			goto out_free_buf;
586 		kbuf[count] = '\0';
587 	}
588 
589 	error = BPF_CGROUP_RUN_PROG_SYSCTL(head, table, write, &kbuf, &count,
590 					   &iocb->ki_pos);
591 	if (error)
592 		goto out_free_buf;
593 
594 	/* careful: calling conventions are nasty here */
595 	error = table->proc_handler(table, write, kbuf, &count, &iocb->ki_pos);
596 	if (error)
597 		goto out_free_buf;
598 
599 	if (!write) {
600 		error = -EFAULT;
601 		if (copy_to_iter(kbuf, count, iter) < count)
602 			goto out_free_buf;
603 	}
604 
605 	error = count;
606 out_free_buf:
607 	kvfree(kbuf);
608 out:
609 	sysctl_head_finish(head);
610 
611 	return error;
612 }
613 
proc_sys_read(struct kiocb * iocb,struct iov_iter * iter)614 static ssize_t proc_sys_read(struct kiocb *iocb, struct iov_iter *iter)
615 {
616 	return proc_sys_call_handler(iocb, iter, 0);
617 }
618 
proc_sys_write(struct kiocb * iocb,struct iov_iter * iter)619 static ssize_t proc_sys_write(struct kiocb *iocb, struct iov_iter *iter)
620 {
621 	return proc_sys_call_handler(iocb, iter, 1);
622 }
623 
proc_sys_open(struct inode * inode,struct file * filp)624 static int proc_sys_open(struct inode *inode, struct file *filp)
625 {
626 	struct ctl_table_header *head = grab_header(inode);
627 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
628 
629 	/* sysctl was unregistered */
630 	if (IS_ERR(head))
631 		return PTR_ERR(head);
632 
633 	if (table->poll)
634 		filp->private_data = proc_sys_poll_event(table->poll);
635 
636 	sysctl_head_finish(head);
637 
638 	return 0;
639 }
640 
proc_sys_poll(struct file * filp,poll_table * wait)641 static __poll_t proc_sys_poll(struct file *filp, poll_table *wait)
642 {
643 	struct inode *inode = file_inode(filp);
644 	struct ctl_table_header *head = grab_header(inode);
645 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
646 	__poll_t ret = DEFAULT_POLLMASK;
647 	unsigned long event;
648 
649 	/* sysctl was unregistered */
650 	if (IS_ERR(head))
651 		return EPOLLERR | EPOLLHUP;
652 
653 	if (!table->proc_handler)
654 		goto out;
655 
656 	if (!table->poll)
657 		goto out;
658 
659 	event = (unsigned long)filp->private_data;
660 	poll_wait(filp, &table->poll->wait, wait);
661 
662 	if (event != atomic_read(&table->poll->event)) {
663 		filp->private_data = proc_sys_poll_event(table->poll);
664 		ret = EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
665 	}
666 
667 out:
668 	sysctl_head_finish(head);
669 
670 	return ret;
671 }
672 
proc_sys_fill_cache(struct file * file,struct dir_context * ctx,struct ctl_table_header * head,struct ctl_table * table)673 static bool proc_sys_fill_cache(struct file *file,
674 				struct dir_context *ctx,
675 				struct ctl_table_header *head,
676 				struct ctl_table *table)
677 {
678 	struct dentry *child, *dir = file->f_path.dentry;
679 	struct inode *inode;
680 	struct qstr qname;
681 	ino_t ino = 0;
682 	unsigned type = DT_UNKNOWN;
683 
684 	qname.name = table->procname;
685 	qname.len  = strlen(table->procname);
686 	qname.hash = full_name_hash(dir, qname.name, qname.len);
687 
688 	child = d_lookup(dir, &qname);
689 	if (!child) {
690 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
691 		child = d_alloc_parallel(dir, &qname, &wq);
692 		if (IS_ERR(child))
693 			return false;
694 		if (d_in_lookup(child)) {
695 			struct dentry *res;
696 			d_set_d_op(child, &proc_sys_dentry_operations);
697 			inode = proc_sys_make_inode(dir->d_sb, head, table);
698 			res = d_splice_alias(inode, child);
699 			d_lookup_done(child);
700 			if (unlikely(res)) {
701 				if (IS_ERR(res)) {
702 					dput(child);
703 					return false;
704 				}
705 				dput(child);
706 				child = res;
707 			}
708 		}
709 	}
710 	inode = d_inode(child);
711 	ino  = inode->i_ino;
712 	type = inode->i_mode >> 12;
713 	dput(child);
714 	return dir_emit(ctx, qname.name, qname.len, ino, type);
715 }
716 
proc_sys_link_fill_cache(struct file * file,struct dir_context * ctx,struct ctl_table_header * head,struct ctl_table * table)717 static bool proc_sys_link_fill_cache(struct file *file,
718 				    struct dir_context *ctx,
719 				    struct ctl_table_header *head,
720 				    struct ctl_table *table)
721 {
722 	bool ret = true;
723 
724 	head = sysctl_head_grab(head);
725 	if (IS_ERR(head))
726 		return false;
727 
728 	/* It is not an error if we can not follow the link ignore it */
729 	if (sysctl_follow_link(&head, &table))
730 		goto out;
731 
732 	ret = proc_sys_fill_cache(file, ctx, head, table);
733 out:
734 	sysctl_head_finish(head);
735 	return ret;
736 }
737 
scan(struct ctl_table_header * head,struct ctl_table * table,unsigned long * pos,struct file * file,struct dir_context * ctx)738 static int scan(struct ctl_table_header *head, struct ctl_table *table,
739 		unsigned long *pos, struct file *file,
740 		struct dir_context *ctx)
741 {
742 	bool res;
743 
744 	if ((*pos)++ < ctx->pos)
745 		return true;
746 
747 	if (unlikely(S_ISLNK(table->mode)))
748 		res = proc_sys_link_fill_cache(file, ctx, head, table);
749 	else
750 		res = proc_sys_fill_cache(file, ctx, head, table);
751 
752 	if (res)
753 		ctx->pos = *pos;
754 
755 	return res;
756 }
757 
proc_sys_readdir(struct file * file,struct dir_context * ctx)758 static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
759 {
760 	struct ctl_table_header *head = grab_header(file_inode(file));
761 	struct ctl_table_header *h = NULL;
762 	struct ctl_table *entry;
763 	struct ctl_dir *ctl_dir;
764 	unsigned long pos;
765 
766 	if (IS_ERR(head))
767 		return PTR_ERR(head);
768 
769 	ctl_dir = container_of(head, struct ctl_dir, header);
770 
771 	if (!dir_emit_dots(file, ctx))
772 		goto out;
773 
774 	pos = 2;
775 
776 	for (first_entry(ctl_dir, &h, &entry); h; next_entry(&h, &entry)) {
777 		if (!scan(h, entry, &pos, file, ctx)) {
778 			sysctl_head_finish(h);
779 			break;
780 		}
781 	}
782 out:
783 	sysctl_head_finish(head);
784 	return 0;
785 }
786 
proc_sys_permission(struct mnt_idmap * idmap,struct inode * inode,int mask)787 static int proc_sys_permission(struct mnt_idmap *idmap,
788 			       struct inode *inode, int mask)
789 {
790 	/*
791 	 * sysctl entries that are not writeable,
792 	 * are _NOT_ writeable, capabilities or not.
793 	 */
794 	struct ctl_table_header *head;
795 	struct ctl_table *table;
796 	int error;
797 
798 	/* Executable files are not allowed under /proc/sys/ */
799 	if ((mask & MAY_EXEC) && S_ISREG(inode->i_mode))
800 		return -EACCES;
801 
802 	head = grab_header(inode);
803 	if (IS_ERR(head))
804 		return PTR_ERR(head);
805 
806 	table = PROC_I(inode)->sysctl_entry;
807 	if (!table) /* global root - r-xr-xr-x */
808 		error = mask & MAY_WRITE ? -EACCES : 0;
809 	else /* Use the permissions on the sysctl table entry */
810 		error = sysctl_perm(head, table, mask & ~MAY_NOT_BLOCK);
811 
812 	sysctl_head_finish(head);
813 	return error;
814 }
815 
proc_sys_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * attr)816 static int proc_sys_setattr(struct mnt_idmap *idmap,
817 			    struct dentry *dentry, struct iattr *attr)
818 {
819 	struct inode *inode = d_inode(dentry);
820 	int error;
821 
822 	if (attr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
823 		return -EPERM;
824 
825 	error = setattr_prepare(&nop_mnt_idmap, dentry, attr);
826 	if (error)
827 		return error;
828 
829 	setattr_copy(&nop_mnt_idmap, inode, attr);
830 	return 0;
831 }
832 
proc_sys_getattr(struct mnt_idmap * idmap,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)833 static int proc_sys_getattr(struct mnt_idmap *idmap,
834 			    const struct path *path, struct kstat *stat,
835 			    u32 request_mask, unsigned int query_flags)
836 {
837 	struct inode *inode = d_inode(path->dentry);
838 	struct ctl_table_header *head = grab_header(inode);
839 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
840 
841 	if (IS_ERR(head))
842 		return PTR_ERR(head);
843 
844 	generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
845 	if (table)
846 		stat->mode = (stat->mode & S_IFMT) | table->mode;
847 
848 	sysctl_head_finish(head);
849 	return 0;
850 }
851 
852 static const struct file_operations proc_sys_file_operations = {
853 	.open		= proc_sys_open,
854 	.poll		= proc_sys_poll,
855 	.read_iter	= proc_sys_read,
856 	.write_iter	= proc_sys_write,
857 	.splice_read	= copy_splice_read,
858 	.splice_write	= iter_file_splice_write,
859 	.llseek		= default_llseek,
860 };
861 
862 static const struct file_operations proc_sys_dir_file_operations = {
863 	.read		= generic_read_dir,
864 	.iterate_shared	= proc_sys_readdir,
865 	.llseek		= generic_file_llseek,
866 };
867 
868 static const struct inode_operations proc_sys_inode_operations = {
869 	.permission	= proc_sys_permission,
870 	.setattr	= proc_sys_setattr,
871 	.getattr	= proc_sys_getattr,
872 };
873 
874 static const struct inode_operations proc_sys_dir_operations = {
875 	.lookup		= proc_sys_lookup,
876 	.permission	= proc_sys_permission,
877 	.setattr	= proc_sys_setattr,
878 	.getattr	= proc_sys_getattr,
879 };
880 
proc_sys_revalidate(struct dentry * dentry,unsigned int flags)881 static int proc_sys_revalidate(struct dentry *dentry, unsigned int flags)
882 {
883 	if (flags & LOOKUP_RCU)
884 		return -ECHILD;
885 	return !PROC_I(d_inode(dentry))->sysctl->unregistering;
886 }
887 
proc_sys_delete(const struct dentry * dentry)888 static int proc_sys_delete(const struct dentry *dentry)
889 {
890 	return !!PROC_I(d_inode(dentry))->sysctl->unregistering;
891 }
892 
sysctl_is_seen(struct ctl_table_header * p)893 static int sysctl_is_seen(struct ctl_table_header *p)
894 {
895 	struct ctl_table_set *set = p->set;
896 	int res;
897 	spin_lock(&sysctl_lock);
898 	if (p->unregistering)
899 		res = 0;
900 	else if (!set->is_seen)
901 		res = 1;
902 	else
903 		res = set->is_seen(set);
904 	spin_unlock(&sysctl_lock);
905 	return res;
906 }
907 
proc_sys_compare(const struct dentry * dentry,unsigned int len,const char * str,const struct qstr * name)908 static int proc_sys_compare(const struct dentry *dentry,
909 		unsigned int len, const char *str, const struct qstr *name)
910 {
911 	struct ctl_table_header *head;
912 	struct inode *inode;
913 
914 	if (name->len != len)
915 		return 1;
916 	if (memcmp(name->name, str, len))
917 		return 1;
918 
919 	// false positive is fine here - we'll recheck anyway
920 	if (d_in_lookup(dentry))
921 		return 0;
922 
923 	inode = d_inode_rcu(dentry);
924 	// we just might have run into dentry in the middle of __dentry_kill()
925 	if (!inode)
926 		return 1;
927 
928 	head = READ_ONCE(PROC_I(inode)->sysctl);
929 	return !head || !sysctl_is_seen(head);
930 }
931 
932 static const struct dentry_operations proc_sys_dentry_operations = {
933 	.d_revalidate	= proc_sys_revalidate,
934 	.d_delete	= proc_sys_delete,
935 	.d_compare	= proc_sys_compare,
936 };
937 
find_subdir(struct ctl_dir * dir,const char * name,int namelen)938 static struct ctl_dir *find_subdir(struct ctl_dir *dir,
939 				   const char *name, int namelen)
940 {
941 	struct ctl_table_header *head;
942 	struct ctl_table *entry;
943 
944 	entry = find_entry(&head, dir, name, namelen);
945 	if (!entry)
946 		return ERR_PTR(-ENOENT);
947 	if (!S_ISDIR(entry->mode))
948 		return ERR_PTR(-ENOTDIR);
949 	return container_of(head, struct ctl_dir, header);
950 }
951 
new_dir(struct ctl_table_set * set,const char * name,int namelen)952 static struct ctl_dir *new_dir(struct ctl_table_set *set,
953 			       const char *name, int namelen)
954 {
955 	struct ctl_table *table;
956 	struct ctl_dir *new;
957 	struct ctl_node *node;
958 	char *new_name;
959 
960 	new = kzalloc(sizeof(*new) + sizeof(struct ctl_node) +
961 		      sizeof(struct ctl_table) +  namelen + 1,
962 		      GFP_KERNEL);
963 	if (!new)
964 		return NULL;
965 
966 	node = (struct ctl_node *)(new + 1);
967 	table = (struct ctl_table *)(node + 1);
968 	new_name = (char *)(table + 1);
969 	memcpy(new_name, name, namelen);
970 	table[0].procname = new_name;
971 	table[0].mode = S_IFDIR|S_IRUGO|S_IXUGO;
972 	init_header(&new->header, set->dir.header.root, set, node, table, 1);
973 
974 	return new;
975 }
976 
977 /**
978  * get_subdir - find or create a subdir with the specified name.
979  * @dir:  Directory to create the subdirectory in
980  * @name: The name of the subdirectory to find or create
981  * @namelen: The length of name
982  *
983  * Takes a directory with an elevated reference count so we know that
984  * if we drop the lock the directory will not go away.  Upon success
985  * the reference is moved from @dir to the returned subdirectory.
986  * Upon error an error code is returned and the reference on @dir is
987  * simply dropped.
988  */
get_subdir(struct ctl_dir * dir,const char * name,int namelen)989 static struct ctl_dir *get_subdir(struct ctl_dir *dir,
990 				  const char *name, int namelen)
991 {
992 	struct ctl_table_set *set = dir->header.set;
993 	struct ctl_dir *subdir, *new = NULL;
994 	int err;
995 
996 	spin_lock(&sysctl_lock);
997 	subdir = find_subdir(dir, name, namelen);
998 	if (!IS_ERR(subdir))
999 		goto found;
1000 	if (PTR_ERR(subdir) != -ENOENT)
1001 		goto failed;
1002 
1003 	spin_unlock(&sysctl_lock);
1004 	new = new_dir(set, name, namelen);
1005 	spin_lock(&sysctl_lock);
1006 	subdir = ERR_PTR(-ENOMEM);
1007 	if (!new)
1008 		goto failed;
1009 
1010 	/* Was the subdir added while we dropped the lock? */
1011 	subdir = find_subdir(dir, name, namelen);
1012 	if (!IS_ERR(subdir))
1013 		goto found;
1014 	if (PTR_ERR(subdir) != -ENOENT)
1015 		goto failed;
1016 
1017 	/* Nope.  Use the our freshly made directory entry. */
1018 	err = insert_header(dir, &new->header);
1019 	subdir = ERR_PTR(err);
1020 	if (err)
1021 		goto failed;
1022 	subdir = new;
1023 found:
1024 	subdir->header.nreg++;
1025 failed:
1026 	if (IS_ERR(subdir)) {
1027 		pr_err("sysctl could not get directory: ");
1028 		sysctl_print_dir(dir);
1029 		pr_cont("%*.*s %ld\n", namelen, namelen, name,
1030 			PTR_ERR(subdir));
1031 	}
1032 	drop_sysctl_table(&dir->header);
1033 	if (new)
1034 		drop_sysctl_table(&new->header);
1035 	spin_unlock(&sysctl_lock);
1036 	return subdir;
1037 }
1038 
xlate_dir(struct ctl_table_set * set,struct ctl_dir * dir)1039 static struct ctl_dir *xlate_dir(struct ctl_table_set *set, struct ctl_dir *dir)
1040 {
1041 	struct ctl_dir *parent;
1042 	const char *procname;
1043 	if (!dir->header.parent)
1044 		return &set->dir;
1045 	parent = xlate_dir(set, dir->header.parent);
1046 	if (IS_ERR(parent))
1047 		return parent;
1048 	procname = dir->header.ctl_table[0].procname;
1049 	return find_subdir(parent, procname, strlen(procname));
1050 }
1051 
sysctl_follow_link(struct ctl_table_header ** phead,struct ctl_table ** pentry)1052 static int sysctl_follow_link(struct ctl_table_header **phead,
1053 	struct ctl_table **pentry)
1054 {
1055 	struct ctl_table_header *head;
1056 	struct ctl_table_root *root;
1057 	struct ctl_table_set *set;
1058 	struct ctl_table *entry;
1059 	struct ctl_dir *dir;
1060 	int ret;
1061 
1062 	spin_lock(&sysctl_lock);
1063 	root = (*pentry)->data;
1064 	set = lookup_header_set(root);
1065 	dir = xlate_dir(set, (*phead)->parent);
1066 	if (IS_ERR(dir))
1067 		ret = PTR_ERR(dir);
1068 	else {
1069 		const char *procname = (*pentry)->procname;
1070 		head = NULL;
1071 		entry = find_entry(&head, dir, procname, strlen(procname));
1072 		ret = -ENOENT;
1073 		if (entry && use_table(head)) {
1074 			unuse_table(*phead);
1075 			*phead = head;
1076 			*pentry = entry;
1077 			ret = 0;
1078 		}
1079 	}
1080 
1081 	spin_unlock(&sysctl_lock);
1082 	return ret;
1083 }
1084 
sysctl_err(const char * path,struct ctl_table * table,char * fmt,...)1085 static int sysctl_err(const char *path, struct ctl_table *table, char *fmt, ...)
1086 {
1087 	struct va_format vaf;
1088 	va_list args;
1089 
1090 	va_start(args, fmt);
1091 	vaf.fmt = fmt;
1092 	vaf.va = &args;
1093 
1094 	pr_err("sysctl table check failed: %s/%s %pV\n",
1095 	       path, table->procname, &vaf);
1096 
1097 	va_end(args);
1098 	return -EINVAL;
1099 }
1100 
sysctl_check_table_array(const char * path,struct ctl_table * table)1101 static int sysctl_check_table_array(const char *path, struct ctl_table *table)
1102 {
1103 	unsigned int extra;
1104 	int err = 0;
1105 
1106 	if ((table->proc_handler == proc_douintvec) ||
1107 	    (table->proc_handler == proc_douintvec_minmax)) {
1108 		if (table->maxlen != sizeof(unsigned int))
1109 			err |= sysctl_err(path, table, "array not allowed");
1110 	}
1111 
1112 	if (table->proc_handler == proc_dou8vec_minmax) {
1113 		if (table->maxlen != sizeof(u8))
1114 			err |= sysctl_err(path, table, "array not allowed");
1115 
1116 		if (table->extra1) {
1117 			extra = *(unsigned int *) table->extra1;
1118 			if (extra > 255U)
1119 				err |= sysctl_err(path, table,
1120 						"range value too large for proc_dou8vec_minmax");
1121 		}
1122 		if (table->extra2) {
1123 			extra = *(unsigned int *) table->extra2;
1124 			if (extra > 255U)
1125 				err |= sysctl_err(path, table,
1126 						"range value too large for proc_dou8vec_minmax");
1127 		}
1128 	}
1129 
1130 	if (table->proc_handler == proc_dobool) {
1131 		if (table->maxlen != sizeof(bool))
1132 			err |= sysctl_err(path, table, "array not allowed");
1133 	}
1134 
1135 	return err;
1136 }
1137 
sysctl_check_table(const char * path,struct ctl_table_header * header)1138 static int sysctl_check_table(const char *path, struct ctl_table_header *header)
1139 {
1140 	struct ctl_table *entry;
1141 	int err = 0;
1142 	list_for_each_table_entry(entry, header) {
1143 		if (!entry->procname)
1144 			err |= sysctl_err(path, entry, "procname is null");
1145 		if ((entry->proc_handler == proc_dostring) ||
1146 		    (entry->proc_handler == proc_dobool) ||
1147 		    (entry->proc_handler == proc_dointvec) ||
1148 		    (entry->proc_handler == proc_douintvec) ||
1149 		    (entry->proc_handler == proc_douintvec_minmax) ||
1150 		    (entry->proc_handler == proc_dointvec_minmax) ||
1151 		    (entry->proc_handler == proc_dou8vec_minmax) ||
1152 		    (entry->proc_handler == proc_dointvec_jiffies) ||
1153 		    (entry->proc_handler == proc_dointvec_userhz_jiffies) ||
1154 		    (entry->proc_handler == proc_dointvec_ms_jiffies) ||
1155 		    (entry->proc_handler == proc_doulongvec_minmax) ||
1156 		    (entry->proc_handler == proc_doulongvec_ms_jiffies_minmax)) {
1157 			if (!entry->data)
1158 				err |= sysctl_err(path, entry, "No data");
1159 			if (!entry->maxlen)
1160 				err |= sysctl_err(path, entry, "No maxlen");
1161 			else
1162 				err |= sysctl_check_table_array(path, entry);
1163 		}
1164 		if (!entry->proc_handler)
1165 			err |= sysctl_err(path, entry, "No proc_handler");
1166 
1167 		if ((entry->mode & (S_IRUGO|S_IWUGO)) != entry->mode)
1168 			err |= sysctl_err(path, entry, "bogus .mode 0%o",
1169 				entry->mode);
1170 	}
1171 	return err;
1172 }
1173 
new_links(struct ctl_dir * dir,struct ctl_table_header * head)1174 static struct ctl_table_header *new_links(struct ctl_dir *dir, struct ctl_table_header *head)
1175 {
1176 	struct ctl_table *link_table, *entry, *link;
1177 	struct ctl_table_header *links;
1178 	struct ctl_node *node;
1179 	char *link_name;
1180 	int name_bytes;
1181 
1182 	name_bytes = 0;
1183 	list_for_each_table_entry(entry, head) {
1184 		name_bytes += strlen(entry->procname) + 1;
1185 	}
1186 
1187 	links = kzalloc(sizeof(struct ctl_table_header) +
1188 			sizeof(struct ctl_node)*head->ctl_table_size +
1189 			sizeof(struct ctl_table)*head->ctl_table_size +
1190 			name_bytes,
1191 			GFP_KERNEL);
1192 
1193 	if (!links)
1194 		return NULL;
1195 
1196 	node = (struct ctl_node *)(links + 1);
1197 	link_table = (struct ctl_table *)(node + head->ctl_table_size);
1198 	link_name = (char *)(link_table + head->ctl_table_size);
1199 	link = link_table;
1200 
1201 	list_for_each_table_entry(entry, head) {
1202 		int len = strlen(entry->procname) + 1;
1203 		memcpy(link_name, entry->procname, len);
1204 		link->procname = link_name;
1205 		link->mode = S_IFLNK|S_IRWXUGO;
1206 		link->data = head->root;
1207 		link_name += len;
1208 		link++;
1209 	}
1210 	init_header(links, dir->header.root, dir->header.set, node, link_table,
1211 		    head->ctl_table_size);
1212 	links->nreg = head->ctl_table_size;
1213 
1214 	return links;
1215 }
1216 
get_links(struct ctl_dir * dir,struct ctl_table_header * header,struct ctl_table_root * link_root)1217 static bool get_links(struct ctl_dir *dir,
1218 		      struct ctl_table_header *header,
1219 		      struct ctl_table_root *link_root)
1220 {
1221 	struct ctl_table_header *tmp_head;
1222 	struct ctl_table *entry, *link;
1223 
1224 	if (header->ctl_table_size == 0 ||
1225 	    sysctl_is_perm_empty_ctl_header(header))
1226 		return true;
1227 
1228 	/* Are there links available for every entry in table? */
1229 	list_for_each_table_entry(entry, header) {
1230 		const char *procname = entry->procname;
1231 		link = find_entry(&tmp_head, dir, procname, strlen(procname));
1232 		if (!link)
1233 			return false;
1234 		if (S_ISDIR(link->mode) && S_ISDIR(entry->mode))
1235 			continue;
1236 		if (S_ISLNK(link->mode) && (link->data == link_root))
1237 			continue;
1238 		return false;
1239 	}
1240 
1241 	/* The checks passed.  Increase the registration count on the links */
1242 	list_for_each_table_entry(entry, header) {
1243 		const char *procname = entry->procname;
1244 		link = find_entry(&tmp_head, dir, procname, strlen(procname));
1245 		tmp_head->nreg++;
1246 	}
1247 	return true;
1248 }
1249 
insert_links(struct ctl_table_header * head)1250 static int insert_links(struct ctl_table_header *head)
1251 {
1252 	struct ctl_table_set *root_set = &sysctl_table_root.default_set;
1253 	struct ctl_dir *core_parent;
1254 	struct ctl_table_header *links;
1255 	int err;
1256 
1257 	if (head->set == root_set)
1258 		return 0;
1259 
1260 	core_parent = xlate_dir(root_set, head->parent);
1261 	if (IS_ERR(core_parent))
1262 		return 0;
1263 
1264 	if (get_links(core_parent, head, head->root))
1265 		return 0;
1266 
1267 	core_parent->header.nreg++;
1268 	spin_unlock(&sysctl_lock);
1269 
1270 	links = new_links(core_parent, head);
1271 
1272 	spin_lock(&sysctl_lock);
1273 	err = -ENOMEM;
1274 	if (!links)
1275 		goto out;
1276 
1277 	err = 0;
1278 	if (get_links(core_parent, head, head->root)) {
1279 		kfree(links);
1280 		goto out;
1281 	}
1282 
1283 	err = insert_header(core_parent, links);
1284 	if (err)
1285 		kfree(links);
1286 out:
1287 	drop_sysctl_table(&core_parent->header);
1288 	return err;
1289 }
1290 
1291 /* Find the directory for the ctl_table. If one is not found create it. */
sysctl_mkdir_p(struct ctl_dir * dir,const char * path)1292 static struct ctl_dir *sysctl_mkdir_p(struct ctl_dir *dir, const char *path)
1293 {
1294 	const char *name, *nextname;
1295 
1296 	for (name = path; name; name = nextname) {
1297 		int namelen;
1298 		nextname = strchr(name, '/');
1299 		if (nextname) {
1300 			namelen = nextname - name;
1301 			nextname++;
1302 		} else {
1303 			namelen = strlen(name);
1304 		}
1305 		if (namelen == 0)
1306 			continue;
1307 
1308 		/*
1309 		 * namelen ensures if name is "foo/bar/yay" only foo is
1310 		 * registered first. We traverse as if using mkdir -p and
1311 		 * return a ctl_dir for the last directory entry.
1312 		 */
1313 		dir = get_subdir(dir, name, namelen);
1314 		if (IS_ERR(dir))
1315 			break;
1316 	}
1317 	return dir;
1318 }
1319 
1320 /**
1321  * __register_sysctl_table - register a leaf sysctl table
1322  * @set: Sysctl tree to register on
1323  * @path: The path to the directory the sysctl table is in.
1324  *
1325  * @table: the top-level table structure. This table should not be free'd
1326  *         after registration. So it should not be used on stack. It can either
1327  *         be a global or dynamically allocated by the caller and free'd later
1328  *         after sysctl unregistration.
1329  * @table_size : The number of elements in table
1330  *
1331  * Register a sysctl table hierarchy. @table should be a filled in ctl_table
1332  * array.
1333  *
1334  * The members of the &struct ctl_table structure are used as follows:
1335  * procname - the name of the sysctl file under /proc/sys. Set to %NULL to not
1336  *            enter a sysctl file
1337  * data     - a pointer to data for use by proc_handler
1338  * maxlen   - the maximum size in bytes of the data
1339  * mode     - the file permissions for the /proc/sys file
1340  * type     - Defines the target type (described in struct definition)
1341  * proc_handler - the text handler routine (described below)
1342  *
1343  * extra1, extra2 - extra pointers usable by the proc handler routines
1344  * XXX: we should eventually modify these to use long min / max [0]
1345  * [0] https://lkml.kernel.org/87zgpte9o4.fsf@email.froward.int.ebiederm.org
1346  *
1347  * Leaf nodes in the sysctl tree will be represented by a single file
1348  * under /proc; non-leaf nodes are not allowed.
1349  *
1350  * There must be a proc_handler routine for any terminal nodes.
1351  * Several default handlers are available to cover common cases -
1352  *
1353  * proc_dostring(), proc_dointvec(), proc_dointvec_jiffies(),
1354  * proc_dointvec_userhz_jiffies(), proc_dointvec_minmax(),
1355  * proc_doulongvec_ms_jiffies_minmax(), proc_doulongvec_minmax()
1356  *
1357  * It is the handler's job to read the input buffer from user memory
1358  * and process it. The handler should return 0 on success.
1359  *
1360  * This routine returns %NULL on a failure to register, and a pointer
1361  * to the table header on success.
1362  */
__register_sysctl_table(struct ctl_table_set * set,const char * path,struct ctl_table * table,size_t table_size)1363 struct ctl_table_header *__register_sysctl_table(
1364 	struct ctl_table_set *set,
1365 	const char *path, struct ctl_table *table, size_t table_size)
1366 {
1367 	struct ctl_table_root *root = set->dir.header.root;
1368 	struct ctl_table_header *header;
1369 	struct ctl_dir *dir;
1370 	struct ctl_node *node;
1371 
1372 	header = kzalloc(sizeof(struct ctl_table_header) +
1373 			 sizeof(struct ctl_node)*table_size, GFP_KERNEL_ACCOUNT);
1374 	if (!header)
1375 		return NULL;
1376 
1377 	node = (struct ctl_node *)(header + 1);
1378 	init_header(header, root, set, node, table, table_size);
1379 	if (sysctl_check_table(path, header))
1380 		goto fail;
1381 
1382 	spin_lock(&sysctl_lock);
1383 	dir = &set->dir;
1384 	/* Reference moved down the directory tree get_subdir */
1385 	dir->header.nreg++;
1386 	spin_unlock(&sysctl_lock);
1387 
1388 	dir = sysctl_mkdir_p(dir, path);
1389 	if (IS_ERR(dir))
1390 		goto fail;
1391 	spin_lock(&sysctl_lock);
1392 	if (insert_header(dir, header))
1393 		goto fail_put_dir_locked;
1394 
1395 	drop_sysctl_table(&dir->header);
1396 	spin_unlock(&sysctl_lock);
1397 
1398 	return header;
1399 
1400 fail_put_dir_locked:
1401 	drop_sysctl_table(&dir->header);
1402 	spin_unlock(&sysctl_lock);
1403 fail:
1404 	kfree(header);
1405 	return NULL;
1406 }
1407 
1408 /**
1409  * register_sysctl_sz - register a sysctl table
1410  * @path: The path to the directory the sysctl table is in. If the path
1411  * 	doesn't exist we will create it for you.
1412  * @table: the table structure. The calller must ensure the life of the @table
1413  * 	will be kept during the lifetime use of the syctl. It must not be freed
1414  * 	until unregister_sysctl_table() is called with the given returned table
1415  * 	with this registration. If your code is non modular then you don't need
1416  * 	to call unregister_sysctl_table() and can instead use something like
1417  * 	register_sysctl_init() which does not care for the result of the syctl
1418  * 	registration.
1419  * @table_size: The number of elements in table.
1420  *
1421  * Register a sysctl table. @table should be a filled in ctl_table
1422  * array. A completely 0 filled entry terminates the table.
1423  *
1424  * See __register_sysctl_table for more details.
1425  */
register_sysctl_sz(const char * path,struct ctl_table * table,size_t table_size)1426 struct ctl_table_header *register_sysctl_sz(const char *path, struct ctl_table *table,
1427 					    size_t table_size)
1428 {
1429 	return __register_sysctl_table(&sysctl_table_root.default_set,
1430 					path, table, table_size);
1431 }
1432 EXPORT_SYMBOL(register_sysctl_sz);
1433 
1434 /**
1435  * __register_sysctl_init() - register sysctl table to path
1436  * @path: path name for sysctl base. If that path doesn't exist we will create
1437  * 	it for you.
1438  * @table: This is the sysctl table that needs to be registered to the path.
1439  * 	The caller must ensure the life of the @table will be kept during the
1440  * 	lifetime use of the sysctl.
1441  * @table_name: The name of sysctl table, only used for log printing when
1442  *              registration fails
1443  * @table_size: The number of elements in table
1444  *
1445  * The sysctl interface is used by userspace to query or modify at runtime
1446  * a predefined value set on a variable. These variables however have default
1447  * values pre-set. Code which depends on these variables will always work even
1448  * if register_sysctl() fails. If register_sysctl() fails you'd just loose the
1449  * ability to query or modify the sysctls dynamically at run time. Chances of
1450  * register_sysctl() failing on init are extremely low, and so for both reasons
1451  * this function does not return any error as it is used by initialization code.
1452  *
1453  * Context: if your base directory does not exist it will be created for you.
1454  */
__register_sysctl_init(const char * path,struct ctl_table * table,const char * table_name,size_t table_size)1455 void __init __register_sysctl_init(const char *path, struct ctl_table *table,
1456 				 const char *table_name, size_t table_size)
1457 {
1458 	struct ctl_table_header *hdr = register_sysctl_sz(path, table, table_size);
1459 
1460 	if (unlikely(!hdr)) {
1461 		pr_err("failed when register_sysctl_sz %s to %s\n", table_name, path);
1462 		return;
1463 	}
1464 	kmemleak_not_leak(hdr);
1465 }
1466 
put_links(struct ctl_table_header * header)1467 static void put_links(struct ctl_table_header *header)
1468 {
1469 	struct ctl_table_set *root_set = &sysctl_table_root.default_set;
1470 	struct ctl_table_root *root = header->root;
1471 	struct ctl_dir *parent = header->parent;
1472 	struct ctl_dir *core_parent;
1473 	struct ctl_table *entry;
1474 
1475 	if (header->set == root_set)
1476 		return;
1477 
1478 	core_parent = xlate_dir(root_set, parent);
1479 	if (IS_ERR(core_parent))
1480 		return;
1481 
1482 	list_for_each_table_entry(entry, header) {
1483 		struct ctl_table_header *link_head;
1484 		struct ctl_table *link;
1485 		const char *name = entry->procname;
1486 
1487 		link = find_entry(&link_head, core_parent, name, strlen(name));
1488 		if (link &&
1489 		    ((S_ISDIR(link->mode) && S_ISDIR(entry->mode)) ||
1490 		     (S_ISLNK(link->mode) && (link->data == root)))) {
1491 			drop_sysctl_table(link_head);
1492 		}
1493 		else {
1494 			pr_err("sysctl link missing during unregister: ");
1495 			sysctl_print_dir(parent);
1496 			pr_cont("%s\n", name);
1497 		}
1498 	}
1499 }
1500 
drop_sysctl_table(struct ctl_table_header * header)1501 static void drop_sysctl_table(struct ctl_table_header *header)
1502 {
1503 	struct ctl_dir *parent = header->parent;
1504 
1505 	if (--header->nreg)
1506 		return;
1507 
1508 	if (parent) {
1509 		put_links(header);
1510 		start_unregistering(header);
1511 	}
1512 
1513 	if (!--header->count)
1514 		kfree_rcu(header, rcu);
1515 
1516 	if (parent)
1517 		drop_sysctl_table(&parent->header);
1518 }
1519 
1520 /**
1521  * unregister_sysctl_table - unregister a sysctl table hierarchy
1522  * @header: the header returned from register_sysctl or __register_sysctl_table
1523  *
1524  * Unregisters the sysctl table and all children. proc entries may not
1525  * actually be removed until they are no longer used by anyone.
1526  */
unregister_sysctl_table(struct ctl_table_header * header)1527 void unregister_sysctl_table(struct ctl_table_header * header)
1528 {
1529 	might_sleep();
1530 
1531 	if (header == NULL)
1532 		return;
1533 
1534 	spin_lock(&sysctl_lock);
1535 	drop_sysctl_table(header);
1536 	spin_unlock(&sysctl_lock);
1537 }
1538 EXPORT_SYMBOL(unregister_sysctl_table);
1539 
setup_sysctl_set(struct ctl_table_set * set,struct ctl_table_root * root,int (* is_seen)(struct ctl_table_set *))1540 void setup_sysctl_set(struct ctl_table_set *set,
1541 	struct ctl_table_root *root,
1542 	int (*is_seen)(struct ctl_table_set *))
1543 {
1544 	memset(set, 0, sizeof(*set));
1545 	set->is_seen = is_seen;
1546 	init_header(&set->dir.header, root, set, NULL, root_table, 1);
1547 }
1548 
retire_sysctl_set(struct ctl_table_set * set)1549 void retire_sysctl_set(struct ctl_table_set *set)
1550 {
1551 	WARN_ON(!RB_EMPTY_ROOT(&set->dir.root));
1552 }
1553 
proc_sys_init(void)1554 int __init proc_sys_init(void)
1555 {
1556 	struct proc_dir_entry *proc_sys_root;
1557 
1558 	proc_sys_root = proc_mkdir("sys", NULL);
1559 	proc_sys_root->proc_iops = &proc_sys_dir_operations;
1560 	proc_sys_root->proc_dir_ops = &proc_sys_dir_file_operations;
1561 	proc_sys_root->nlink = 0;
1562 
1563 	return sysctl_init_bases();
1564 }
1565 
1566 struct sysctl_alias {
1567 	const char *kernel_param;
1568 	const char *sysctl_param;
1569 };
1570 
1571 /*
1572  * Historically some settings had both sysctl and a command line parameter.
1573  * With the generic sysctl. parameter support, we can handle them at a single
1574  * place and only keep the historical name for compatibility. This is not meant
1575  * to add brand new aliases. When adding existing aliases, consider whether
1576  * the possibly different moment of changing the value (e.g. from early_param
1577  * to the moment do_sysctl_args() is called) is an issue for the specific
1578  * parameter.
1579  */
1580 static const struct sysctl_alias sysctl_aliases[] = {
1581 	{"hardlockup_all_cpu_backtrace",	"kernel.hardlockup_all_cpu_backtrace" },
1582 	{"hung_task_panic",			"kernel.hung_task_panic" },
1583 	{"numa_zonelist_order",			"vm.numa_zonelist_order" },
1584 	{"softlockup_all_cpu_backtrace",	"kernel.softlockup_all_cpu_backtrace" },
1585 	{ }
1586 };
1587 
sysctl_find_alias(char * param)1588 static const char *sysctl_find_alias(char *param)
1589 {
1590 	const struct sysctl_alias *alias;
1591 
1592 	for (alias = &sysctl_aliases[0]; alias->kernel_param != NULL; alias++) {
1593 		if (strcmp(alias->kernel_param, param) == 0)
1594 			return alias->sysctl_param;
1595 	}
1596 
1597 	return NULL;
1598 }
1599 
sysctl_is_alias(char * param)1600 bool sysctl_is_alias(char *param)
1601 {
1602 	const char *alias = sysctl_find_alias(param);
1603 
1604 	return alias != NULL;
1605 }
1606 
1607 /* Set sysctl value passed on kernel command line. */
process_sysctl_arg(char * param,char * val,const char * unused,void * arg)1608 static int process_sysctl_arg(char *param, char *val,
1609 			       const char *unused, void *arg)
1610 {
1611 	char *path;
1612 	struct vfsmount **proc_mnt = arg;
1613 	struct file_system_type *proc_fs_type;
1614 	struct file *file;
1615 	int len;
1616 	int err;
1617 	loff_t pos = 0;
1618 	ssize_t wret;
1619 
1620 	if (strncmp(param, "sysctl", sizeof("sysctl") - 1) == 0) {
1621 		param += sizeof("sysctl") - 1;
1622 
1623 		if (param[0] != '/' && param[0] != '.')
1624 			return 0;
1625 
1626 		param++;
1627 	} else {
1628 		param = (char *) sysctl_find_alias(param);
1629 		if (!param)
1630 			return 0;
1631 	}
1632 
1633 	if (!val)
1634 		return -EINVAL;
1635 	len = strlen(val);
1636 	if (len == 0)
1637 		return -EINVAL;
1638 
1639 	/*
1640 	 * To set sysctl options, we use a temporary mount of proc, look up the
1641 	 * respective sys/ file and write to it. To avoid mounting it when no
1642 	 * options were given, we mount it only when the first sysctl option is
1643 	 * found. Why not a persistent mount? There are problems with a
1644 	 * persistent mount of proc in that it forces userspace not to use any
1645 	 * proc mount options.
1646 	 */
1647 	if (!*proc_mnt) {
1648 		proc_fs_type = get_fs_type("proc");
1649 		if (!proc_fs_type) {
1650 			pr_err("Failed to find procfs to set sysctl from command line\n");
1651 			return 0;
1652 		}
1653 		*proc_mnt = kern_mount(proc_fs_type);
1654 		put_filesystem(proc_fs_type);
1655 		if (IS_ERR(*proc_mnt)) {
1656 			pr_err("Failed to mount procfs to set sysctl from command line\n");
1657 			return 0;
1658 		}
1659 	}
1660 
1661 	path = kasprintf(GFP_KERNEL, "sys/%s", param);
1662 	if (!path)
1663 		panic("%s: Failed to allocate path for %s\n", __func__, param);
1664 	strreplace(path, '.', '/');
1665 
1666 	file = file_open_root_mnt(*proc_mnt, path, O_WRONLY, 0);
1667 	if (IS_ERR(file)) {
1668 		err = PTR_ERR(file);
1669 		if (err == -ENOENT)
1670 			pr_err("Failed to set sysctl parameter '%s=%s': parameter not found\n",
1671 				param, val);
1672 		else if (err == -EACCES)
1673 			pr_err("Failed to set sysctl parameter '%s=%s': permission denied (read-only?)\n",
1674 				param, val);
1675 		else
1676 			pr_err("Error %pe opening proc file to set sysctl parameter '%s=%s'\n",
1677 				file, param, val);
1678 		goto out;
1679 	}
1680 	wret = kernel_write(file, val, len, &pos);
1681 	if (wret < 0) {
1682 		err = wret;
1683 		if (err == -EINVAL)
1684 			pr_err("Failed to set sysctl parameter '%s=%s': invalid value\n",
1685 				param, val);
1686 		else
1687 			pr_err("Error %pe writing to proc file to set sysctl parameter '%s=%s'\n",
1688 				ERR_PTR(err), param, val);
1689 	} else if (wret != len) {
1690 		pr_err("Wrote only %zd bytes of %d writing to proc file %s to set sysctl parameter '%s=%s\n",
1691 			wret, len, path, param, val);
1692 	}
1693 
1694 	err = filp_close(file, NULL);
1695 	if (err)
1696 		pr_err("Error %pe closing proc file to set sysctl parameter '%s=%s\n",
1697 			ERR_PTR(err), param, val);
1698 out:
1699 	kfree(path);
1700 	return 0;
1701 }
1702 
do_sysctl_args(void)1703 void do_sysctl_args(void)
1704 {
1705 	char *command_line;
1706 	struct vfsmount *proc_mnt = NULL;
1707 
1708 	command_line = kstrdup(saved_command_line, GFP_KERNEL);
1709 	if (!command_line)
1710 		panic("%s: Failed to allocate copy of command line\n", __func__);
1711 
1712 	parse_args("Setting sysctl args", command_line,
1713 		   NULL, 0, -1, -1, &proc_mnt, process_sysctl_arg);
1714 
1715 	if (proc_mnt)
1716 		kern_unmount(proc_mnt);
1717 
1718 	kfree(command_line);
1719 }
1720