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