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