• 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[] = { 0, 1, INT_MAX };
30 EXPORT_SYMBOL(sysctl_vals);
31 const int sysctl_vals_new[] = { -1, 0, 1, 2, 4, 100, 200, 1000, 3000, INT_MAX };
32 EXPORT_SYMBOL(sysctl_vals_new);
33 
34 /* Support for permanently empty directories */
35 
36 struct ctl_table sysctl_mount_point[] = {
37 	{ }
38 };
39 
is_empty_dir(struct ctl_table_header * head)40 static bool is_empty_dir(struct ctl_table_header *head)
41 {
42 	return head->ctl_table[0].child == sysctl_mount_point;
43 }
44 
set_empty_dir(struct ctl_dir * dir)45 static void set_empty_dir(struct ctl_dir *dir)
46 {
47 	dir->header.ctl_table[0].child = sysctl_mount_point;
48 }
49 
clear_empty_dir(struct ctl_dir * dir)50 static void clear_empty_dir(struct ctl_dir *dir)
51 
52 {
53 	dir->header.ctl_table[0].child = NULL;
54 }
55 
proc_sys_poll_notify(struct ctl_table_poll * poll)56 void proc_sys_poll_notify(struct ctl_table_poll *poll)
57 {
58 	if (!poll)
59 		return;
60 
61 	atomic_inc(&poll->event);
62 	wake_up_interruptible(&poll->wait);
63 }
64 
65 static struct ctl_table root_table[] = {
66 	{
67 		.procname = "",
68 		.mode = S_IFDIR|S_IRUGO|S_IXUGO,
69 	},
70 	{ }
71 };
72 static struct ctl_table_root sysctl_table_root = {
73 	.default_set.dir.header = {
74 		{{.count = 1,
75 		  .nreg = 1,
76 		  .ctl_table = root_table }},
77 		.ctl_table_arg = root_table,
78 		.root = &sysctl_table_root,
79 		.set = &sysctl_table_root.default_set,
80 	},
81 };
82 
83 static DEFINE_SPINLOCK(sysctl_lock);
84 
85 static void drop_sysctl_table(struct ctl_table_header *header);
86 static int sysctl_follow_link(struct ctl_table_header **phead,
87 	struct ctl_table **pentry);
88 static int insert_links(struct ctl_table_header *head);
89 static void put_links(struct ctl_table_header *header);
90 
sysctl_print_dir(struct ctl_dir * dir)91 static void sysctl_print_dir(struct ctl_dir *dir)
92 {
93 	if (dir->header.parent)
94 		sysctl_print_dir(dir->header.parent);
95 	pr_cont("%s/", dir->header.ctl_table[0].procname);
96 }
97 
namecmp(const char * name1,int len1,const char * name2,int len2)98 static int namecmp(const char *name1, int len1, const char *name2, int len2)
99 {
100 	int cmp;
101 
102 	cmp = memcmp(name1, name2, min(len1, len2));
103 	if (cmp == 0)
104 		cmp = len1 - len2;
105 	return cmp;
106 }
107 
108 /* Called under sysctl_lock */
find_entry(struct ctl_table_header ** phead,struct ctl_dir * dir,const char * name,int namelen)109 static struct ctl_table *find_entry(struct ctl_table_header **phead,
110 	struct ctl_dir *dir, const char *name, int namelen)
111 {
112 	struct ctl_table_header *head;
113 	struct ctl_table *entry;
114 	struct rb_node *node = dir->root.rb_node;
115 
116 	while (node)
117 	{
118 		struct ctl_node *ctl_node;
119 		const char *procname;
120 		int cmp;
121 
122 		ctl_node = rb_entry(node, struct ctl_node, node);
123 		head = ctl_node->header;
124 		entry = &head->ctl_table[ctl_node - head->node];
125 		procname = entry->procname;
126 
127 		cmp = namecmp(name, namelen, procname, strlen(procname));
128 		if (cmp < 0)
129 			node = node->rb_left;
130 		else if (cmp > 0)
131 			node = node->rb_right;
132 		else {
133 			*phead = head;
134 			return entry;
135 		}
136 	}
137 	return NULL;
138 }
139 
insert_entry(struct ctl_table_header * head,struct ctl_table * entry)140 static int insert_entry(struct ctl_table_header *head, struct ctl_table *entry)
141 {
142 	struct rb_node *node = &head->node[entry - head->ctl_table].node;
143 	struct rb_node **p = &head->parent->root.rb_node;
144 	struct rb_node *parent = NULL;
145 	const char *name = entry->procname;
146 	int namelen = strlen(name);
147 
148 	while (*p) {
149 		struct ctl_table_header *parent_head;
150 		struct ctl_table *parent_entry;
151 		struct ctl_node *parent_node;
152 		const char *parent_name;
153 		int cmp;
154 
155 		parent = *p;
156 		parent_node = rb_entry(parent, struct ctl_node, node);
157 		parent_head = parent_node->header;
158 		parent_entry = &parent_head->ctl_table[parent_node - parent_head->node];
159 		parent_name = parent_entry->procname;
160 
161 		cmp = namecmp(name, namelen, parent_name, strlen(parent_name));
162 		if (cmp < 0)
163 			p = &(*p)->rb_left;
164 		else if (cmp > 0)
165 			p = &(*p)->rb_right;
166 		else {
167 			pr_err("sysctl duplicate entry: ");
168 			sysctl_print_dir(head->parent);
169 			pr_cont("/%s\n", entry->procname);
170 			return -EEXIST;
171 		}
172 	}
173 
174 	rb_link_node(node, parent, p);
175 	rb_insert_color(node, &head->parent->root);
176 	return 0;
177 }
178 
erase_entry(struct ctl_table_header * head,struct ctl_table * entry)179 static void erase_entry(struct ctl_table_header *head, struct ctl_table *entry)
180 {
181 	struct rb_node *node = &head->node[entry - head->ctl_table].node;
182 
183 	rb_erase(node, &head->parent->root);
184 }
185 
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)186 static void init_header(struct ctl_table_header *head,
187 	struct ctl_table_root *root, struct ctl_table_set *set,
188 	struct ctl_node *node, struct ctl_table *table)
189 {
190 	head->ctl_table = table;
191 	head->ctl_table_arg = table;
192 	head->used = 0;
193 	head->count = 1;
194 	head->nreg = 1;
195 	head->unregistering = NULL;
196 	head->root = root;
197 	head->set = set;
198 	head->parent = NULL;
199 	head->node = node;
200 	INIT_HLIST_HEAD(&head->inodes);
201 	if (node) {
202 		struct ctl_table *entry;
203 		for (entry = table; entry->procname; entry++, node++)
204 			node->header = head;
205 	}
206 }
207 
erase_header(struct ctl_table_header * head)208 static void erase_header(struct ctl_table_header *head)
209 {
210 	struct ctl_table *entry;
211 	for (entry = head->ctl_table; entry->procname; entry++)
212 		erase_entry(head, entry);
213 }
214 
insert_header(struct ctl_dir * dir,struct ctl_table_header * header)215 static int insert_header(struct ctl_dir *dir, struct ctl_table_header *header)
216 {
217 	struct ctl_table *entry;
218 	int err;
219 
220 	/* Is this a permanently empty directory? */
221 	if (is_empty_dir(&dir->header))
222 		return -EROFS;
223 
224 	/* Am I creating a permanently empty directory? */
225 	if (header->ctl_table == sysctl_mount_point) {
226 		if (!RB_EMPTY_ROOT(&dir->root))
227 			return -EINVAL;
228 		set_empty_dir(dir);
229 	}
230 
231 	dir->header.nreg++;
232 	header->parent = dir;
233 	err = insert_links(header);
234 	if (err)
235 		goto fail_links;
236 	for (entry = header->ctl_table; entry->procname; entry++) {
237 		err = insert_entry(header, entry);
238 		if (err)
239 			goto fail;
240 	}
241 	return 0;
242 fail:
243 	erase_header(header);
244 	put_links(header);
245 fail_links:
246 	if (header->ctl_table == sysctl_mount_point)
247 		clear_empty_dir(dir);
248 	header->parent = NULL;
249 	drop_sysctl_table(&dir->header);
250 	return err;
251 }
252 
253 /* called under sysctl_lock */
use_table(struct ctl_table_header * p)254 static int use_table(struct ctl_table_header *p)
255 {
256 	if (unlikely(p->unregistering))
257 		return 0;
258 	p->used++;
259 	return 1;
260 }
261 
262 /* called under sysctl_lock */
unuse_table(struct ctl_table_header * p)263 static void unuse_table(struct ctl_table_header *p)
264 {
265 	if (!--p->used)
266 		if (unlikely(p->unregistering))
267 			complete(p->unregistering);
268 }
269 
proc_sys_invalidate_dcache(struct ctl_table_header * head)270 static void proc_sys_invalidate_dcache(struct ctl_table_header *head)
271 {
272 	proc_invalidate_siblings_dcache(&head->inodes, &sysctl_lock);
273 }
274 
275 /* called under sysctl_lock, will reacquire if has to wait */
start_unregistering(struct ctl_table_header * p)276 static void start_unregistering(struct ctl_table_header *p)
277 {
278 	/*
279 	 * if p->used is 0, nobody will ever touch that entry again;
280 	 * we'll eliminate all paths to it before dropping sysctl_lock
281 	 */
282 	if (unlikely(p->used)) {
283 		struct completion wait;
284 		init_completion(&wait);
285 		p->unregistering = &wait;
286 		spin_unlock(&sysctl_lock);
287 		wait_for_completion(&wait);
288 	} else {
289 		/* anything non-NULL; we'll never dereference it */
290 		p->unregistering = ERR_PTR(-EINVAL);
291 		spin_unlock(&sysctl_lock);
292 	}
293 	/*
294 	 * Invalidate dentries for unregistered sysctls: namespaced sysctls
295 	 * can have duplicate names and contaminate dcache very badly.
296 	 */
297 	proc_sys_invalidate_dcache(p);
298 	/*
299 	 * do not remove from the list until nobody holds it; walking the
300 	 * list in do_sysctl() relies on that.
301 	 */
302 	spin_lock(&sysctl_lock);
303 	erase_header(p);
304 }
305 
sysctl_head_grab(struct ctl_table_header * head)306 static struct ctl_table_header *sysctl_head_grab(struct ctl_table_header *head)
307 {
308 	BUG_ON(!head);
309 	spin_lock(&sysctl_lock);
310 	if (!use_table(head))
311 		head = ERR_PTR(-ENOENT);
312 	spin_unlock(&sysctl_lock);
313 	return head;
314 }
315 
sysctl_head_finish(struct ctl_table_header * head)316 static void sysctl_head_finish(struct ctl_table_header *head)
317 {
318 	if (!head)
319 		return;
320 	spin_lock(&sysctl_lock);
321 	unuse_table(head);
322 	spin_unlock(&sysctl_lock);
323 }
324 
325 static struct ctl_table_set *
lookup_header_set(struct ctl_table_root * root)326 lookup_header_set(struct ctl_table_root *root)
327 {
328 	struct ctl_table_set *set = &root->default_set;
329 	if (root->lookup)
330 		set = root->lookup(root);
331 	return set;
332 }
333 
lookup_entry(struct ctl_table_header ** phead,struct ctl_dir * dir,const char * name,int namelen)334 static struct ctl_table *lookup_entry(struct ctl_table_header **phead,
335 				      struct ctl_dir *dir,
336 				      const char *name, int namelen)
337 {
338 	struct ctl_table_header *head;
339 	struct ctl_table *entry;
340 
341 	spin_lock(&sysctl_lock);
342 	entry = find_entry(&head, dir, name, namelen);
343 	if (entry && use_table(head))
344 		*phead = head;
345 	else
346 		entry = NULL;
347 	spin_unlock(&sysctl_lock);
348 	return entry;
349 }
350 
first_usable_entry(struct rb_node * node)351 static struct ctl_node *first_usable_entry(struct rb_node *node)
352 {
353 	struct ctl_node *ctl_node;
354 
355 	for (;node; node = rb_next(node)) {
356 		ctl_node = rb_entry(node, struct ctl_node, node);
357 		if (use_table(ctl_node->header))
358 			return ctl_node;
359 	}
360 	return NULL;
361 }
362 
first_entry(struct ctl_dir * dir,struct ctl_table_header ** phead,struct ctl_table ** pentry)363 static void first_entry(struct ctl_dir *dir,
364 	struct ctl_table_header **phead, struct ctl_table **pentry)
365 {
366 	struct ctl_table_header *head = NULL;
367 	struct ctl_table *entry = NULL;
368 	struct ctl_node *ctl_node;
369 
370 	spin_lock(&sysctl_lock);
371 	ctl_node = first_usable_entry(rb_first(&dir->root));
372 	spin_unlock(&sysctl_lock);
373 	if (ctl_node) {
374 		head = ctl_node->header;
375 		entry = &head->ctl_table[ctl_node - head->node];
376 	}
377 	*phead = head;
378 	*pentry = entry;
379 }
380 
next_entry(struct ctl_table_header ** phead,struct ctl_table ** pentry)381 static void next_entry(struct ctl_table_header **phead, struct ctl_table **pentry)
382 {
383 	struct ctl_table_header *head = *phead;
384 	struct ctl_table *entry = *pentry;
385 	struct ctl_node *ctl_node = &head->node[entry - head->ctl_table];
386 
387 	spin_lock(&sysctl_lock);
388 	unuse_table(head);
389 
390 	ctl_node = first_usable_entry(rb_next(&ctl_node->node));
391 	spin_unlock(&sysctl_lock);
392 	head = NULL;
393 	if (ctl_node) {
394 		head = ctl_node->header;
395 		entry = &head->ctl_table[ctl_node - head->node];
396 	}
397 	*phead = head;
398 	*pentry = entry;
399 }
400 
401 /*
402  * sysctl_perm does NOT grant the superuser all rights automatically, because
403  * some sysctl variables are readonly even to root.
404  */
405 
test_perm(int mode,int op)406 static int test_perm(int mode, int op)
407 {
408 	if (uid_eq(current_euid(), GLOBAL_ROOT_UID))
409 		mode >>= 6;
410 	else if (in_egroup_p(GLOBAL_ROOT_GID))
411 		mode >>= 3;
412 	if ((op & ~mode & (MAY_READ|MAY_WRITE|MAY_EXEC)) == 0)
413 		return 0;
414 	return -EACCES;
415 }
416 
sysctl_perm(struct ctl_table_header * head,struct ctl_table * table,int op)417 static int sysctl_perm(struct ctl_table_header *head, struct ctl_table *table, int op)
418 {
419 	struct ctl_table_root *root = head->root;
420 	int mode;
421 
422 	if (root->permissions)
423 		mode = root->permissions(head, table);
424 	else
425 		mode = table->mode;
426 
427 	return test_perm(mode, op);
428 }
429 
proc_sys_make_inode(struct super_block * sb,struct ctl_table_header * head,struct ctl_table * table)430 static struct inode *proc_sys_make_inode(struct super_block *sb,
431 		struct ctl_table_header *head, struct ctl_table *table)
432 {
433 	struct ctl_table_root *root = head->root;
434 	struct inode *inode;
435 	struct proc_inode *ei;
436 
437 	inode = new_inode(sb);
438 	if (!inode)
439 		return ERR_PTR(-ENOMEM);
440 
441 	inode->i_ino = get_next_ino();
442 
443 	ei = PROC_I(inode);
444 
445 	spin_lock(&sysctl_lock);
446 	if (unlikely(head->unregistering)) {
447 		spin_unlock(&sysctl_lock);
448 		iput(inode);
449 		return ERR_PTR(-ENOENT);
450 	}
451 	ei->sysctl = head;
452 	ei->sysctl_entry = table;
453 	hlist_add_head_rcu(&ei->sibling_inodes, &head->inodes);
454 	head->count++;
455 	spin_unlock(&sysctl_lock);
456 
457 	inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);
458 	inode->i_mode = table->mode;
459 	if (!S_ISDIR(table->mode)) {
460 		inode->i_mode |= S_IFREG;
461 		inode->i_op = &proc_sys_inode_operations;
462 		inode->i_fop = &proc_sys_file_operations;
463 	} else {
464 		inode->i_mode |= S_IFDIR;
465 		inode->i_op = &proc_sys_dir_operations;
466 		inode->i_fop = &proc_sys_dir_file_operations;
467 		if (is_empty_dir(head))
468 			make_empty_dir_inode(inode);
469 	}
470 
471 	if (root->set_ownership)
472 		root->set_ownership(head, table, &inode->i_uid, &inode->i_gid);
473 	else {
474 		inode->i_uid = GLOBAL_ROOT_UID;
475 		inode->i_gid = GLOBAL_ROOT_GID;
476 	}
477 
478 	return inode;
479 }
480 
proc_sys_evict_inode(struct inode * inode,struct ctl_table_header * head)481 void proc_sys_evict_inode(struct inode *inode, struct ctl_table_header *head)
482 {
483 	spin_lock(&sysctl_lock);
484 	hlist_del_init_rcu(&PROC_I(inode)->sibling_inodes);
485 	if (!--head->count)
486 		kfree_rcu(head, rcu);
487 	spin_unlock(&sysctl_lock);
488 }
489 
grab_header(struct inode * inode)490 static struct ctl_table_header *grab_header(struct inode *inode)
491 {
492 	struct ctl_table_header *head = PROC_I(inode)->sysctl;
493 	if (!head)
494 		head = &sysctl_table_root.default_set.dir.header;
495 	return sysctl_head_grab(head);
496 }
497 
proc_sys_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)498 static struct dentry *proc_sys_lookup(struct inode *dir, struct dentry *dentry,
499 					unsigned int flags)
500 {
501 	struct ctl_table_header *head = grab_header(dir);
502 	struct ctl_table_header *h = NULL;
503 	const struct qstr *name = &dentry->d_name;
504 	struct ctl_table *p;
505 	struct inode *inode;
506 	struct dentry *err = ERR_PTR(-ENOENT);
507 	struct ctl_dir *ctl_dir;
508 	int ret;
509 
510 	if (IS_ERR(head))
511 		return ERR_CAST(head);
512 
513 	ctl_dir = container_of(head, struct ctl_dir, header);
514 
515 	p = lookup_entry(&h, ctl_dir, name->name, name->len);
516 	if (!p)
517 		goto out;
518 
519 	if (S_ISLNK(p->mode)) {
520 		ret = sysctl_follow_link(&h, &p);
521 		err = ERR_PTR(ret);
522 		if (ret)
523 			goto out;
524 	}
525 
526 	inode = proc_sys_make_inode(dir->i_sb, h ? h : head, p);
527 	if (IS_ERR(inode)) {
528 		err = ERR_CAST(inode);
529 		goto out;
530 	}
531 
532 	d_set_d_op(dentry, &proc_sys_dentry_operations);
533 	err = d_splice_alias(inode, dentry);
534 
535 out:
536 	if (h)
537 		sysctl_head_finish(h);
538 	sysctl_head_finish(head);
539 	return err;
540 }
541 
proc_sys_call_handler(struct kiocb * iocb,struct iov_iter * iter,int write)542 static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter,
543 		int write)
544 {
545 	struct inode *inode = file_inode(iocb->ki_filp);
546 	struct ctl_table_header *head = grab_header(inode);
547 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
548 	size_t count = iov_iter_count(iter);
549 	char *kbuf;
550 	ssize_t error;
551 
552 	if (IS_ERR(head))
553 		return PTR_ERR(head);
554 
555 	/*
556 	 * At this point we know that the sysctl was not unregistered
557 	 * and won't be until we finish.
558 	 */
559 	error = -EPERM;
560 	if (sysctl_perm(head, table, write ? MAY_WRITE : MAY_READ))
561 		goto out;
562 
563 	/* if that can happen at all, it should be -EINVAL, not -EISDIR */
564 	error = -EINVAL;
565 	if (!table->proc_handler)
566 		goto out;
567 
568 	/* don't even try if the size is too large */
569 	error = -ENOMEM;
570 	if (count >= KMALLOC_MAX_SIZE)
571 		goto out;
572 	kbuf = kvzalloc(count + 1, GFP_KERNEL);
573 	if (!kbuf)
574 		goto out;
575 
576 	if (write) {
577 		error = -EFAULT;
578 		if (!copy_from_iter_full(kbuf, count, iter))
579 			goto out_free_buf;
580 		kbuf[count] = '\0';
581 	}
582 
583 	error = BPF_CGROUP_RUN_PROG_SYSCTL(head, table, write, &kbuf, &count,
584 					   &iocb->ki_pos);
585 	if (error)
586 		goto out_free_buf;
587 
588 	/* careful: calling conventions are nasty here */
589 	error = table->proc_handler(table, write, kbuf, &count, &iocb->ki_pos);
590 	if (error)
591 		goto out_free_buf;
592 
593 	if (!write) {
594 		error = -EFAULT;
595 		if (copy_to_iter(kbuf, count, iter) < count)
596 			goto out_free_buf;
597 	}
598 
599 	error = count;
600 out_free_buf:
601 	kvfree(kbuf);
602 out:
603 	sysctl_head_finish(head);
604 
605 	return error;
606 }
607 
proc_sys_read(struct kiocb * iocb,struct iov_iter * iter)608 static ssize_t proc_sys_read(struct kiocb *iocb, struct iov_iter *iter)
609 {
610 	return proc_sys_call_handler(iocb, iter, 0);
611 }
612 
proc_sys_write(struct kiocb * iocb,struct iov_iter * iter)613 static ssize_t proc_sys_write(struct kiocb *iocb, struct iov_iter *iter)
614 {
615 	return proc_sys_call_handler(iocb, iter, 1);
616 }
617 
proc_sys_open(struct inode * inode,struct file * filp)618 static int proc_sys_open(struct inode *inode, struct file *filp)
619 {
620 	struct ctl_table_header *head = grab_header(inode);
621 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
622 
623 	/* sysctl was unregistered */
624 	if (IS_ERR(head))
625 		return PTR_ERR(head);
626 
627 	if (table->poll)
628 		filp->private_data = proc_sys_poll_event(table->poll);
629 
630 	sysctl_head_finish(head);
631 
632 	return 0;
633 }
634 
proc_sys_poll(struct file * filp,poll_table * wait)635 static __poll_t proc_sys_poll(struct file *filp, poll_table *wait)
636 {
637 	struct inode *inode = file_inode(filp);
638 	struct ctl_table_header *head = grab_header(inode);
639 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
640 	__poll_t ret = DEFAULT_POLLMASK;
641 	unsigned long event;
642 
643 	/* sysctl was unregistered */
644 	if (IS_ERR(head))
645 		return EPOLLERR | EPOLLHUP;
646 
647 	if (!table->proc_handler)
648 		goto out;
649 
650 	if (!table->poll)
651 		goto out;
652 
653 	event = (unsigned long)filp->private_data;
654 	poll_wait(filp, &table->poll->wait, wait);
655 
656 	if (event != atomic_read(&table->poll->event)) {
657 		filp->private_data = proc_sys_poll_event(table->poll);
658 		ret = EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
659 	}
660 
661 out:
662 	sysctl_head_finish(head);
663 
664 	return ret;
665 }
666 
proc_sys_fill_cache(struct file * file,struct dir_context * ctx,struct ctl_table_header * head,struct ctl_table * table)667 static bool proc_sys_fill_cache(struct file *file,
668 				struct dir_context *ctx,
669 				struct ctl_table_header *head,
670 				struct ctl_table *table)
671 {
672 	struct dentry *child, *dir = file->f_path.dentry;
673 	struct inode *inode;
674 	struct qstr qname;
675 	ino_t ino = 0;
676 	unsigned type = DT_UNKNOWN;
677 
678 	qname.name = table->procname;
679 	qname.len  = strlen(table->procname);
680 	qname.hash = full_name_hash(dir, qname.name, qname.len);
681 
682 	child = d_lookup(dir, &qname);
683 	if (!child) {
684 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
685 		child = d_alloc_parallel(dir, &qname, &wq);
686 		if (IS_ERR(child))
687 			return false;
688 		if (d_in_lookup(child)) {
689 			struct dentry *res;
690 			inode = proc_sys_make_inode(dir->d_sb, head, table);
691 			if (IS_ERR(inode)) {
692 				d_lookup_done(child);
693 				dput(child);
694 				return false;
695 			}
696 			d_set_d_op(child, &proc_sys_dentry_operations);
697 			res = d_splice_alias(inode, child);
698 			d_lookup_done(child);
699 			if (unlikely(res)) {
700 				if (IS_ERR(res)) {
701 					dput(child);
702 					return false;
703 				}
704 				dput(child);
705 				child = res;
706 			}
707 		}
708 	}
709 	inode = d_inode(child);
710 	ino  = inode->i_ino;
711 	type = inode->i_mode >> 12;
712 	dput(child);
713 	return dir_emit(ctx, qname.name, qname.len, ino, type);
714 }
715 
proc_sys_link_fill_cache(struct file * file,struct dir_context * ctx,struct ctl_table_header * head,struct ctl_table * table)716 static bool proc_sys_link_fill_cache(struct file *file,
717 				    struct dir_context *ctx,
718 				    struct ctl_table_header *head,
719 				    struct ctl_table *table)
720 {
721 	bool ret = true;
722 
723 	head = sysctl_head_grab(head);
724 	if (IS_ERR(head))
725 		return false;
726 
727 	/* It is not an error if we can not follow the link ignore it */
728 	if (sysctl_follow_link(&head, &table))
729 		goto out;
730 
731 	ret = proc_sys_fill_cache(file, ctx, head, table);
732 out:
733 	sysctl_head_finish(head);
734 	return ret;
735 }
736 
scan(struct ctl_table_header * head,struct ctl_table * table,unsigned long * pos,struct file * file,struct dir_context * ctx)737 static int scan(struct ctl_table_header *head, struct ctl_table *table,
738 		unsigned long *pos, struct file *file,
739 		struct dir_context *ctx)
740 {
741 	bool res;
742 
743 	if ((*pos)++ < ctx->pos)
744 		return true;
745 
746 	if (unlikely(S_ISLNK(table->mode)))
747 		res = proc_sys_link_fill_cache(file, ctx, head, table);
748 	else
749 		res = proc_sys_fill_cache(file, ctx, head, table);
750 
751 	if (res)
752 		ctx->pos = *pos;
753 
754 	return res;
755 }
756 
proc_sys_readdir(struct file * file,struct dir_context * ctx)757 static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
758 {
759 	struct ctl_table_header *head = grab_header(file_inode(file));
760 	struct ctl_table_header *h = NULL;
761 	struct ctl_table *entry;
762 	struct ctl_dir *ctl_dir;
763 	unsigned long pos;
764 
765 	if (IS_ERR(head))
766 		return PTR_ERR(head);
767 
768 	ctl_dir = container_of(head, struct ctl_dir, header);
769 
770 	if (!dir_emit_dots(file, ctx))
771 		goto out;
772 
773 	pos = 2;
774 
775 	for (first_entry(ctl_dir, &h, &entry); h; next_entry(&h, &entry)) {
776 		if (!scan(h, entry, &pos, file, ctx)) {
777 			sysctl_head_finish(h);
778 			break;
779 		}
780 	}
781 out:
782 	sysctl_head_finish(head);
783 	return 0;
784 }
785 
proc_sys_permission(struct user_namespace * mnt_userns,struct inode * inode,int mask)786 static int proc_sys_permission(struct user_namespace *mnt_userns,
787 			       struct inode *inode, int mask)
788 {
789 	/*
790 	 * sysctl entries that are not writeable,
791 	 * are _NOT_ writeable, capabilities or not.
792 	 */
793 	struct ctl_table_header *head;
794 	struct ctl_table *table;
795 	int error;
796 
797 	/* Executable files are not allowed under /proc/sys/ */
798 	if ((mask & MAY_EXEC) && S_ISREG(inode->i_mode))
799 		return -EACCES;
800 
801 	head = grab_header(inode);
802 	if (IS_ERR(head))
803 		return PTR_ERR(head);
804 
805 	table = PROC_I(inode)->sysctl_entry;
806 	if (!table) /* global root - r-xr-xr-x */
807 		error = mask & MAY_WRITE ? -EACCES : 0;
808 	else /* Use the permissions on the sysctl table entry */
809 		error = sysctl_perm(head, table, mask & ~MAY_NOT_BLOCK);
810 
811 	sysctl_head_finish(head);
812 	return error;
813 }
814 
proc_sys_setattr(struct user_namespace * mnt_userns,struct dentry * dentry,struct iattr * attr)815 static int proc_sys_setattr(struct user_namespace *mnt_userns,
816 			    struct dentry *dentry, struct iattr *attr)
817 {
818 	struct inode *inode = d_inode(dentry);
819 	int error;
820 
821 	if (attr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
822 		return -EPERM;
823 
824 	error = setattr_prepare(&init_user_ns, dentry, attr);
825 	if (error)
826 		return error;
827 
828 	setattr_copy(&init_user_ns, inode, attr);
829 	mark_inode_dirty(inode);
830 	return 0;
831 }
832 
proc_sys_getattr(struct user_namespace * mnt_userns,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)833 static int proc_sys_getattr(struct user_namespace *mnt_userns,
834 			    const struct path *path, struct kstat *stat,
835 			    u32 request_mask, unsigned int query_flags)
836 {
837 	struct inode *inode = d_inode(path->dentry);
838 	struct ctl_table_header *head = grab_header(inode);
839 	struct ctl_table *table = PROC_I(inode)->sysctl_entry;
840 
841 	if (IS_ERR(head))
842 		return PTR_ERR(head);
843 
844 	generic_fillattr(&init_user_ns, 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_paths - 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 
sysctl_is_alias(char * param)1785 bool sysctl_is_alias(char *param)
1786 {
1787 	const char *alias = sysctl_find_alias(param);
1788 
1789 	return alias != NULL;
1790 }
1791 
1792 /* Set sysctl value passed on kernel command line. */
process_sysctl_arg(char * param,char * val,const char * unused,void * arg)1793 static int process_sysctl_arg(char *param, char *val,
1794 			       const char *unused, void *arg)
1795 {
1796 	char *path;
1797 	struct vfsmount **proc_mnt = arg;
1798 	struct file_system_type *proc_fs_type;
1799 	struct file *file;
1800 	int len;
1801 	int err;
1802 	loff_t pos = 0;
1803 	ssize_t wret;
1804 
1805 	if (strncmp(param, "sysctl", sizeof("sysctl") - 1) == 0) {
1806 		param += sizeof("sysctl") - 1;
1807 
1808 		if (param[0] != '/' && param[0] != '.')
1809 			return 0;
1810 
1811 		param++;
1812 	} else {
1813 		param = (char *) sysctl_find_alias(param);
1814 		if (!param)
1815 			return 0;
1816 	}
1817 
1818 	if (!val)
1819 		return -EINVAL;
1820 	len = strlen(val);
1821 	if (len == 0)
1822 		return -EINVAL;
1823 
1824 	/*
1825 	 * To set sysctl options, we use a temporary mount of proc, look up the
1826 	 * respective sys/ file and write to it. To avoid mounting it when no
1827 	 * options were given, we mount it only when the first sysctl option is
1828 	 * found. Why not a persistent mount? There are problems with a
1829 	 * persistent mount of proc in that it forces userspace not to use any
1830 	 * proc mount options.
1831 	 */
1832 	if (!*proc_mnt) {
1833 		proc_fs_type = get_fs_type("proc");
1834 		if (!proc_fs_type) {
1835 			pr_err("Failed to find procfs to set sysctl from command line\n");
1836 			return 0;
1837 		}
1838 		*proc_mnt = kern_mount(proc_fs_type);
1839 		put_filesystem(proc_fs_type);
1840 		if (IS_ERR(*proc_mnt)) {
1841 			pr_err("Failed to mount procfs to set sysctl from command line\n");
1842 			return 0;
1843 		}
1844 	}
1845 
1846 	path = kasprintf(GFP_KERNEL, "sys/%s", param);
1847 	if (!path)
1848 		panic("%s: Failed to allocate path for %s\n", __func__, param);
1849 	strreplace(path, '.', '/');
1850 
1851 	file = file_open_root_mnt(*proc_mnt, path, O_WRONLY, 0);
1852 	if (IS_ERR(file)) {
1853 		err = PTR_ERR(file);
1854 		if (err == -ENOENT)
1855 			pr_err("Failed to set sysctl parameter '%s=%s': parameter not found\n",
1856 				param, val);
1857 		else if (err == -EACCES)
1858 			pr_err("Failed to set sysctl parameter '%s=%s': permission denied (read-only?)\n",
1859 				param, val);
1860 		else
1861 			pr_err("Error %pe opening proc file to set sysctl parameter '%s=%s'\n",
1862 				file, param, val);
1863 		goto out;
1864 	}
1865 	wret = kernel_write(file, val, len, &pos);
1866 	if (wret < 0) {
1867 		err = wret;
1868 		if (err == -EINVAL)
1869 			pr_err("Failed to set sysctl parameter '%s=%s': invalid value\n",
1870 				param, val);
1871 		else
1872 			pr_err("Error %pe writing to proc file to set sysctl parameter '%s=%s'\n",
1873 				ERR_PTR(err), param, val);
1874 	} else if (wret != len) {
1875 		pr_err("Wrote only %zd bytes of %d writing to proc file %s to set sysctl parameter '%s=%s\n",
1876 			wret, len, path, param, val);
1877 	}
1878 
1879 	err = filp_close(file, NULL);
1880 	if (err)
1881 		pr_err("Error %pe closing proc file to set sysctl parameter '%s=%s\n",
1882 			ERR_PTR(err), param, val);
1883 out:
1884 	kfree(path);
1885 	return 0;
1886 }
1887 
do_sysctl_args(void)1888 void do_sysctl_args(void)
1889 {
1890 	char *command_line;
1891 	struct vfsmount *proc_mnt = NULL;
1892 
1893 	command_line = kstrdup(saved_command_line, GFP_KERNEL);
1894 	if (!command_line)
1895 		panic("%s: Failed to allocate copy of command line\n", __func__);
1896 
1897 	parse_args("Setting sysctl args", command_line,
1898 		   NULL, 0, -1, -1, &proc_mnt, process_sysctl_arg);
1899 
1900 	if (proc_mnt)
1901 		kern_unmount(proc_mnt);
1902 
1903 	kfree(command_line);
1904 }
1905