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