xref: /linux/kernel/pid.c (revision 6d864a1b182532e7570383af8825fa4ddcd24243)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Generic pidhash and scalable, time-bounded PID allocator
4  *
5  * (C) 2002-2003 Nadia Yvette Chambers, IBM
6  * (C) 2004 Nadia Yvette Chambers, Oracle
7  * (C) 2002-2004 Ingo Molnar, Red Hat
8  *
9  * pid-structures are backing objects for tasks sharing a given ID to chain
10  * against. There is very little to them aside from hashing them and
11  * parking tasks using given ID's on a list.
12  *
13  * The hash is always changed with the tasklist_lock write-acquired,
14  * and the hash is only accessed with the tasklist_lock at least
15  * read-acquired, so there's no additional SMP locking needed here.
16  *
17  * We have a list of bitmap pages, which bitmaps represent the PID space.
18  * Allocating and freeing PIDs is completely lockless. The worst-case
19  * allocation scenario when all but one out of 1 million PIDs possible are
20  * allocated already: the scanning of 32 list entries and at most PAGE_SIZE
21  * bytes. The typical fastpath is a single successful setbit. Freeing is O(1).
22  *
23  * Pid namespaces:
24  *    (C) 2007 Pavel Emelyanov <xemul@openvz.org>, OpenVZ, SWsoft Inc.
25  *    (C) 2007 Sukadev Bhattiprolu <sukadev@us.ibm.com>, IBM
26  *     Many thanks to Oleg Nesterov for comments and help
27  *
28  */
29 
30 #include <linux/mm.h>
31 #include <linux/export.h>
32 #include <linux/slab.h>
33 #include <linux/init.h>
34 #include <linux/rculist.h>
35 #include <linux/memblock.h>
36 #include <linux/pid_namespace.h>
37 #include <linux/init_task.h>
38 #include <linux/syscalls.h>
39 #include <linux/proc_ns.h>
40 #include <linux/refcount.h>
41 #include <linux/anon_inodes.h>
42 #include <linux/sched/signal.h>
43 #include <linux/sched/task.h>
44 #include <linux/idr.h>
45 #include <linux/pidfs.h>
46 #include <linux/seqlock.h>
47 #include <net/sock.h>
48 #include <uapi/linux/pidfd.h>
49 
50 struct pid init_struct_pid = {
51 	.count		= REFCOUNT_INIT(1),
52 	.tasks		= {
53 		{ .first = NULL },
54 		{ .first = NULL },
55 		{ .first = NULL },
56 	},
57 	.level		= 0,
58 	.numbers	= { {
59 		.nr		= 0,
60 		.ns		= &init_pid_ns,
61 	}, }
62 };
63 
64 static int pid_max_min = RESERVED_PIDS + 1;
65 static int pid_max_max = PID_MAX_LIMIT;
66 
67 /*
68  * PID-map pages start out as NULL, they get allocated upon
69  * first use and are never deallocated. This way a low pid_max
70  * value does not cause lots of bitmaps to be allocated, but
71  * the scheme scales to up to 4 million PIDs, runtime.
72  */
73 struct pid_namespace init_pid_ns = {
74 	.ns = NS_COMMON_INIT(init_pid_ns),
75 	.idr = IDR_INIT(init_pid_ns.idr),
76 	.pid_allocated = PIDNS_ADDING,
77 	.level = 0,
78 	.child_reaper = &init_task,
79 	.user_ns = &init_user_ns,
80 	.pid_max = PID_MAX_DEFAULT,
81 #if defined(CONFIG_SYSCTL) && defined(CONFIG_MEMFD_CREATE)
82 	.memfd_noexec_scope = MEMFD_NOEXEC_SCOPE_EXEC,
83 #endif
84 };
85 EXPORT_SYMBOL_GPL(init_pid_ns);
86 
87 static  __cacheline_aligned_in_smp DEFINE_SPINLOCK(pidmap_lock);
88 seqcount_spinlock_t pidmap_lock_seq = SEQCNT_SPINLOCK_ZERO(pidmap_lock_seq, &pidmap_lock);
89 
90 void put_pid(struct pid *pid)
91 {
92 	struct pid_namespace *ns;
93 
94 	if (!pid)
95 		return;
96 
97 	ns = pid->numbers[pid->level].ns;
98 	if (refcount_dec_and_test(&pid->count)) {
99 		pidfs_free_pid(pid);
100 		kmem_cache_free(ns->pid_cachep, pid);
101 		put_pid_ns(ns);
102 	}
103 }
104 EXPORT_SYMBOL_GPL(put_pid);
105 
106 static void delayed_put_pid(struct rcu_head *rhp)
107 {
108 	struct pid *pid = container_of(rhp, struct pid, rcu);
109 	put_pid(pid);
110 }
111 
112 void free_pid(struct pid *pid)
113 {
114 	int i;
115 	struct pid_namespace *active_ns;
116 
117 	lockdep_assert_not_held(&tasklist_lock);
118 
119 	active_ns = pid->numbers[pid->level].ns;
120 	ns_ref_active_put(active_ns);
121 
122 	spin_lock(&pidmap_lock);
123 	for (i = 0; i <= pid->level; i++) {
124 		struct upid *upid = pid->numbers + i;
125 		struct pid_namespace *ns = upid->ns;
126 		switch (--ns->pid_allocated) {
127 		case 2:
128 		case 1:
129 			/* When all that is left in the pid namespace
130 			 * is the reaper wake up the reaper.  The reaper
131 			 * may be sleeping in zap_pid_ns_processes().
132 			 */
133 			wake_up_process(ns->child_reaper);
134 			break;
135 		case PIDNS_ADDING:
136 			/* Handle a fork failure of the first process */
137 			WARN_ON(ns->child_reaper);
138 			ns->pid_allocated = 0;
139 			break;
140 		}
141 
142 		idr_remove(&ns->idr, upid->nr);
143 	}
144 	pidfs_remove_pid(pid);
145 	spin_unlock(&pidmap_lock);
146 
147 	call_rcu(&pid->rcu, delayed_put_pid);
148 }
149 
150 void free_pids(struct pid **pids)
151 {
152 	int tmp;
153 
154 	/*
155 	 * This can batch pidmap_lock.
156 	 */
157 	for (tmp = PIDTYPE_MAX; --tmp >= 0; )
158 		if (pids[tmp])
159 			free_pid(pids[tmp]);
160 }
161 
162 struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid,
163 		      size_t arg_set_tid_size)
164 {
165 	int set_tid[MAX_PID_NS_LEVEL + 1] = {};
166 	int pid_max[MAX_PID_NS_LEVEL + 1] = {};
167 	struct pid *pid;
168 	enum pid_type type;
169 	int i, nr;
170 	struct pid_namespace *tmp;
171 	struct upid *upid;
172 	int retval = -ENOMEM;
173 	bool retried_preload;
174 
175 	/*
176 	 * arg_set_tid_size contains the size of the arg_set_tid array. Starting at
177 	 * the most nested currently active PID namespace it tells alloc_pid()
178 	 * which PID to set for a process in that most nested PID namespace
179 	 * up to arg_set_tid_size PID namespaces. It does not have to set the PID
180 	 * for a process in all nested PID namespaces but arg_set_tid_size must
181 	 * never be greater than the current ns->level + 1.
182 	 */
183 	if (arg_set_tid_size > ns->level + 1)
184 		return ERR_PTR(-EINVAL);
185 
186 	/*
187 	 * Prep before we take locks:
188 	 *
189 	 * 1. allocate and fill in pid struct
190 	 */
191 	pid = kmem_cache_alloc(ns->pid_cachep, GFP_KERNEL);
192 	if (!pid)
193 		return ERR_PTR(retval);
194 
195 	get_pid_ns(ns);
196 	pid->level = ns->level;
197 	refcount_set(&pid->count, 1);
198 	spin_lock_init(&pid->lock);
199 	for (type = 0; type < PIDTYPE_MAX; ++type)
200 		INIT_HLIST_HEAD(&pid->tasks[type]);
201 	init_waitqueue_head(&pid->wait_pidfd);
202 	INIT_HLIST_HEAD(&pid->inodes);
203 
204 	/*
205 	 * 2. perm check checkpoint_restore_ns_capable()
206 	 *
207 	 * This stores found pid_max to make sure the used value is the same should
208 	 * later code need it.
209 	 */
210 	for (tmp = ns, i = ns->level; i >= 0; i--) {
211 		pid_max[ns->level - i] = READ_ONCE(tmp->pid_max);
212 
213 		if (arg_set_tid_size) {
214 			int tid = set_tid[ns->level - i] = arg_set_tid[ns->level - i];
215 
216 			retval = -EINVAL;
217 			if (tid < 1 || tid >= pid_max[ns->level - i])
218 				goto out_abort;
219 			/*
220 			 * Also fail if a PID != 1 is requested and
221 			 * no PID 1 exists.
222 			 */
223 			if (tid != 1 && !tmp->child_reaper)
224 				goto out_abort;
225 			retval = -EPERM;
226 			if (!checkpoint_restore_ns_capable(tmp->user_ns))
227 				goto out_abort;
228 			arg_set_tid_size--;
229 		}
230 
231 		tmp = tmp->parent;
232 	}
233 
234 	/*
235 	 * Prep is done, id allocation goes here:
236 	 */
237 	retried_preload = false;
238 	idr_preload(GFP_KERNEL);
239 	spin_lock(&pidmap_lock);
240 	for (tmp = ns, i = ns->level; i >= 0;) {
241 		int tid = set_tid[ns->level - i];
242 
243 		if (tid) {
244 			nr = idr_alloc(&tmp->idr, NULL, tid,
245 				       tid + 1, GFP_ATOMIC);
246 			/*
247 			 * If ENOSPC is returned it means that the PID is
248 			 * alreay in use. Return EEXIST in that case.
249 			 */
250 			if (nr == -ENOSPC)
251 
252 				nr = -EEXIST;
253 		} else {
254 			int pid_min = 1;
255 			/*
256 			 * init really needs pid 1, but after reaching the
257 			 * maximum wrap back to RESERVED_PIDS
258 			 */
259 			if (idr_get_cursor(&tmp->idr) > RESERVED_PIDS)
260 				pid_min = RESERVED_PIDS;
261 
262 			/*
263 			 * Store a null pointer so find_pid_ns does not find
264 			 * a partially initialized PID (see below).
265 			 */
266 			nr = idr_alloc_cyclic(&tmp->idr, NULL, pid_min,
267 					      pid_max[ns->level - i], GFP_ATOMIC);
268 			if (nr == -ENOSPC)
269 				nr = -EAGAIN;
270 		}
271 
272 		if (unlikely(nr < 0)) {
273 			/*
274 			 * Preload more memory if idr_alloc{,cyclic} failed with -ENOMEM.
275 			 *
276 			 * The IDR API only allows us to preload memory for one call, while we may end
277 			 * up doing several under pidmap_lock with GFP_ATOMIC. The situation may be
278 			 * salvageable with GFP_KERNEL. But make sure to not loop indefinitely if preload
279 			 * did not help (the routine unfortunately returns void, so we have no idea
280 			 * if it got anywhere).
281 			 *
282 			 * The lock can be safely dropped and picked up as historically pid allocation
283 			 * for different namespaces was *not* atomic -- we try to hold on to it the
284 			 * entire time only for performance reasons.
285 			 */
286 			if (nr == -ENOMEM && !retried_preload) {
287 				spin_unlock(&pidmap_lock);
288 				idr_preload_end();
289 				retried_preload = true;
290 				idr_preload(GFP_KERNEL);
291 				spin_lock(&pidmap_lock);
292 				continue;
293 			}
294 			retval = nr;
295 			goto out_free;
296 		}
297 
298 		pid->numbers[i].nr = nr;
299 		pid->numbers[i].ns = tmp;
300 		tmp = tmp->parent;
301 		i--;
302 		retried_preload = false;
303 	}
304 
305 	/*
306 	 * ENOMEM is not the most obvious choice especially for the case
307 	 * where the child subreaper has already exited and the pid
308 	 * namespace denies the creation of any new processes. But ENOMEM
309 	 * is what we have exposed to userspace for a long time and it is
310 	 * documented behavior for pid namespaces. So we can't easily
311 	 * change it even if there were an error code better suited.
312 	 *
313 	 * This can't be done earlier because we need to preserve other
314 	 * error conditions.
315 	 */
316 	retval = -ENOMEM;
317 	if (unlikely(!(ns->pid_allocated & PIDNS_ADDING)))
318 		goto out_free;
319 	pidfs_add_pid(pid);
320 	for (upid = pid->numbers + ns->level; upid >= pid->numbers; --upid) {
321 		/* Make the PID visible to find_pid_ns. */
322 		idr_replace(&upid->ns->idr, pid, upid->nr);
323 		upid->ns->pid_allocated++;
324 	}
325 	spin_unlock(&pidmap_lock);
326 	idr_preload_end();
327 	ns_ref_active_get(ns);
328 
329 	return pid;
330 
331 out_free:
332 	while (++i <= ns->level) {
333 		upid = pid->numbers + i;
334 		idr_remove(&upid->ns->idr, upid->nr);
335 	}
336 
337 	/* On failure to allocate the first pid, reset the state */
338 	if (ns->pid_allocated == PIDNS_ADDING)
339 		idr_set_cursor(&ns->idr, 0);
340 
341 	spin_unlock(&pidmap_lock);
342 	idr_preload_end();
343 
344 out_abort:
345 	put_pid_ns(ns);
346 	kmem_cache_free(ns->pid_cachep, pid);
347 	return ERR_PTR(retval);
348 }
349 
350 void disable_pid_allocation(struct pid_namespace *ns)
351 {
352 	spin_lock(&pidmap_lock);
353 	ns->pid_allocated &= ~PIDNS_ADDING;
354 	spin_unlock(&pidmap_lock);
355 }
356 
357 struct pid *find_pid_ns(int nr, struct pid_namespace *ns)
358 {
359 	return idr_find(&ns->idr, nr);
360 }
361 EXPORT_SYMBOL_GPL(find_pid_ns);
362 
363 struct pid *find_vpid(int nr)
364 {
365 	return find_pid_ns(nr, task_active_pid_ns(current));
366 }
367 EXPORT_SYMBOL_GPL(find_vpid);
368 
369 static struct pid **task_pid_ptr(struct task_struct *task, enum pid_type type)
370 {
371 	return (type == PIDTYPE_PID) ?
372 		&task->thread_pid :
373 		&task->signal->pids[type];
374 }
375 
376 /*
377  * attach_pid() must be called with the tasklist_lock write-held.
378  */
379 void attach_pid(struct task_struct *task, enum pid_type type)
380 {
381 	struct pid *pid;
382 
383 	lockdep_assert_held_write(&tasklist_lock);
384 
385 	pid = *task_pid_ptr(task, type);
386 	hlist_add_head_rcu(&task->pid_links[type], &pid->tasks[type]);
387 }
388 
389 static void __change_pid(struct pid **pids, struct task_struct *task,
390 			 enum pid_type type, struct pid *new)
391 {
392 	struct pid **pid_ptr, *pid;
393 	int tmp;
394 
395 	lockdep_assert_held_write(&tasklist_lock);
396 
397 	pid_ptr = task_pid_ptr(task, type);
398 	pid = *pid_ptr;
399 
400 	hlist_del_rcu(&task->pid_links[type]);
401 	*pid_ptr = new;
402 
403 	for (tmp = PIDTYPE_MAX; --tmp >= 0; )
404 		if (pid_has_task(pid, tmp))
405 			return;
406 
407 	WARN_ON(pids[type]);
408 	pids[type] = pid;
409 }
410 
411 void detach_pid(struct pid **pids, struct task_struct *task, enum pid_type type)
412 {
413 	__change_pid(pids, task, type, NULL);
414 }
415 
416 void change_pid(struct pid **pids, struct task_struct *task, enum pid_type type,
417 		struct pid *pid)
418 {
419 	__change_pid(pids, task, type, pid);
420 	attach_pid(task, type);
421 }
422 
423 void exchange_tids(struct task_struct *left, struct task_struct *right)
424 {
425 	struct pid *pid1 = left->thread_pid;
426 	struct pid *pid2 = right->thread_pid;
427 	struct hlist_head *head1 = &pid1->tasks[PIDTYPE_PID];
428 	struct hlist_head *head2 = &pid2->tasks[PIDTYPE_PID];
429 
430 	lockdep_assert_held_write(&tasklist_lock);
431 
432 	/* Swap the single entry tid lists */
433 	hlists_swap_heads_rcu(head1, head2);
434 
435 	/* Swap the per task_struct pid */
436 	rcu_assign_pointer(left->thread_pid, pid2);
437 	rcu_assign_pointer(right->thread_pid, pid1);
438 
439 	/* Swap the cached value */
440 	WRITE_ONCE(left->pid, pid_nr(pid2));
441 	WRITE_ONCE(right->pid, pid_nr(pid1));
442 }
443 
444 /* transfer_pid is an optimization of attach_pid(new), detach_pid(old) */
445 void transfer_pid(struct task_struct *old, struct task_struct *new,
446 			   enum pid_type type)
447 {
448 	WARN_ON_ONCE(type == PIDTYPE_PID);
449 	lockdep_assert_held_write(&tasklist_lock);
450 	hlist_replace_rcu(&old->pid_links[type], &new->pid_links[type]);
451 }
452 
453 struct task_struct *pid_task(struct pid *pid, enum pid_type type)
454 {
455 	struct task_struct *result = NULL;
456 	if (pid) {
457 		struct hlist_node *first;
458 		first = rcu_dereference_check(hlist_first_rcu(&pid->tasks[type]),
459 					      lockdep_tasklist_lock_is_held());
460 		if (first)
461 			result = hlist_entry(first, struct task_struct, pid_links[(type)]);
462 	}
463 	return result;
464 }
465 EXPORT_SYMBOL(pid_task);
466 
467 /*
468  * Must be called under rcu_read_lock().
469  */
470 struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns)
471 {
472 	RCU_LOCKDEP_WARN(!rcu_read_lock_held(),
473 			 "find_task_by_pid_ns() needs rcu_read_lock() protection");
474 	return pid_task(find_pid_ns(nr, ns), PIDTYPE_PID);
475 }
476 
477 struct task_struct *find_task_by_vpid(pid_t vnr)
478 {
479 	return find_task_by_pid_ns(vnr, task_active_pid_ns(current));
480 }
481 
482 struct task_struct *find_get_task_by_vpid(pid_t nr)
483 {
484 	struct task_struct *task;
485 
486 	rcu_read_lock();
487 	task = find_task_by_vpid(nr);
488 	if (task)
489 		get_task_struct(task);
490 	rcu_read_unlock();
491 
492 	return task;
493 }
494 
495 struct pid *get_task_pid(struct task_struct *task, enum pid_type type)
496 {
497 	struct pid *pid;
498 	rcu_read_lock();
499 	pid = get_pid(rcu_dereference(*task_pid_ptr(task, type)));
500 	rcu_read_unlock();
501 	return pid;
502 }
503 EXPORT_SYMBOL_GPL(get_task_pid);
504 
505 struct task_struct *get_pid_task(struct pid *pid, enum pid_type type)
506 {
507 	struct task_struct *result;
508 	rcu_read_lock();
509 	result = pid_task(pid, type);
510 	if (result)
511 		get_task_struct(result);
512 	rcu_read_unlock();
513 	return result;
514 }
515 EXPORT_SYMBOL_GPL(get_pid_task);
516 
517 struct pid *find_get_pid(pid_t nr)
518 {
519 	struct pid *pid;
520 
521 	rcu_read_lock();
522 	pid = get_pid(find_vpid(nr));
523 	rcu_read_unlock();
524 
525 	return pid;
526 }
527 EXPORT_SYMBOL_GPL(find_get_pid);
528 
529 pid_t pid_nr_ns(struct pid *pid, struct pid_namespace *ns)
530 {
531 	struct upid *upid;
532 	pid_t nr = 0;
533 
534 	if (pid && ns && ns->level <= pid->level) {
535 		upid = &pid->numbers[ns->level];
536 		if (upid->ns == ns)
537 			nr = upid->nr;
538 	}
539 	return nr;
540 }
541 EXPORT_SYMBOL_GPL(pid_nr_ns);
542 
543 pid_t pid_vnr(struct pid *pid)
544 {
545 	return pid_nr_ns(pid, task_active_pid_ns(current));
546 }
547 EXPORT_SYMBOL_GPL(pid_vnr);
548 
549 pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
550 			struct pid_namespace *ns)
551 {
552 	pid_t nr = 0;
553 
554 	rcu_read_lock();
555 	if (!ns)
556 		ns = task_active_pid_ns(current);
557 	if (ns)
558 		nr = pid_nr_ns(rcu_dereference(*task_pid_ptr(task, type)), ns);
559 	rcu_read_unlock();
560 
561 	return nr;
562 }
563 EXPORT_SYMBOL(__task_pid_nr_ns);
564 
565 struct pid_namespace *task_active_pid_ns(struct task_struct *tsk)
566 {
567 	return ns_of_pid(task_pid(tsk));
568 }
569 EXPORT_SYMBOL_GPL(task_active_pid_ns);
570 
571 /*
572  * Used by proc to find the first pid that is greater than or equal to nr.
573  *
574  * If there is a pid at nr this function is exactly the same as find_pid_ns.
575  */
576 struct pid *find_ge_pid(int nr, struct pid_namespace *ns)
577 {
578 	return idr_get_next(&ns->idr, &nr);
579 }
580 EXPORT_SYMBOL_GPL(find_ge_pid);
581 
582 struct pid *pidfd_get_pid(unsigned int fd, unsigned int *flags)
583 {
584 	CLASS(fd, f)(fd);
585 	struct pid *pid;
586 
587 	if (fd_empty(f))
588 		return ERR_PTR(-EBADF);
589 
590 	pid = pidfd_pid(fd_file(f));
591 	if (!IS_ERR(pid)) {
592 		get_pid(pid);
593 		*flags = fd_file(f)->f_flags;
594 	}
595 	return pid;
596 }
597 
598 /**
599  * pidfd_get_task() - Get the task associated with a pidfd
600  *
601  * @pidfd: pidfd for which to get the task
602  * @flags: flags associated with this pidfd
603  *
604  * Return the task associated with @pidfd. The function takes a reference on
605  * the returned task. The caller is responsible for releasing that reference.
606  *
607  * Return: On success, the task_struct associated with the pidfd.
608  *	   On error, a negative errno number will be returned.
609  */
610 struct task_struct *pidfd_get_task(int pidfd, unsigned int *flags)
611 {
612 	unsigned int f_flags = 0;
613 	struct pid *pid;
614 	struct task_struct *task;
615 	enum pid_type type;
616 
617 	switch (pidfd) {
618 	case  PIDFD_SELF_THREAD:
619 		type = PIDTYPE_PID;
620 		pid = get_task_pid(current, type);
621 		break;
622 	case  PIDFD_SELF_THREAD_GROUP:
623 		type = PIDTYPE_TGID;
624 		pid = get_task_pid(current, type);
625 		break;
626 	default:
627 		pid = pidfd_get_pid(pidfd, &f_flags);
628 		if (IS_ERR(pid))
629 			return ERR_CAST(pid);
630 		type = PIDTYPE_TGID;
631 		break;
632 	}
633 
634 	task = get_pid_task(pid, type);
635 	put_pid(pid);
636 	if (!task)
637 		return ERR_PTR(-ESRCH);
638 
639 	*flags = f_flags;
640 	return task;
641 }
642 
643 /**
644  * pidfd_create() - Create a new pid file descriptor.
645  *
646  * @pid:   struct pid that the pidfd will reference
647  * @flags: flags to pass
648  *
649  * This creates a new pid file descriptor with the O_CLOEXEC flag set.
650  *
651  * Note, that this function can only be called after the fd table has
652  * been unshared to avoid leaking the pidfd to the new process.
653  *
654  * This symbol should not be explicitly exported to loadable modules.
655  *
656  * Return: On success, a cloexec pidfd is returned.
657  *         On error, a negative errno number will be returned.
658  */
659 static int pidfd_create(struct pid *pid, unsigned int flags)
660 {
661 	int pidfd;
662 	struct file *pidfd_file;
663 
664 	pidfd = pidfd_prepare(pid, flags, &pidfd_file);
665 	if (pidfd < 0)
666 		return pidfd;
667 
668 	fd_install(pidfd, pidfd_file);
669 	return pidfd;
670 }
671 
672 /**
673  * sys_pidfd_open() - Open new pid file descriptor.
674  *
675  * @pid:   pid for which to retrieve a pidfd
676  * @flags: flags to pass
677  *
678  * This creates a new pid file descriptor with the O_CLOEXEC flag set for
679  * the task identified by @pid. Without PIDFD_THREAD flag the target task
680  * must be a thread-group leader.
681  *
682  * Return: On success, a cloexec pidfd is returned.
683  *         On error, a negative errno number will be returned.
684  */
685 SYSCALL_DEFINE2(pidfd_open, pid_t, pid, unsigned int, flags)
686 {
687 	int fd;
688 	struct pid *p;
689 
690 	if (flags & ~(PIDFD_NONBLOCK | PIDFD_THREAD))
691 		return -EINVAL;
692 
693 	if (pid <= 0)
694 		return -EINVAL;
695 
696 	p = find_get_pid(pid);
697 	if (!p)
698 		return -ESRCH;
699 
700 	fd = pidfd_create(p, flags);
701 
702 	put_pid(p);
703 	return fd;
704 }
705 
706 #ifdef CONFIG_SYSCTL
707 static struct ctl_table_set *pid_table_root_lookup(struct ctl_table_root *root)
708 {
709 	return &task_active_pid_ns(current)->set;
710 }
711 
712 static int set_is_seen(struct ctl_table_set *set)
713 {
714 	return &task_active_pid_ns(current)->set == set;
715 }
716 
717 static int pid_table_root_permissions(struct ctl_table_header *head,
718 				      const struct ctl_table *table)
719 {
720 	struct pid_namespace *pidns =
721 		container_of(head->set, struct pid_namespace, set);
722 	int mode = table->mode;
723 
724 	if (ns_capable_noaudit(pidns->user_ns, CAP_SYS_ADMIN) ||
725 	    uid_eq(current_euid(), make_kuid(pidns->user_ns, 0)))
726 		mode = (mode & S_IRWXU) >> 6;
727 	else if (in_egroup_p(make_kgid(pidns->user_ns, 0)))
728 		mode = (mode & S_IRWXG) >> 3;
729 	else
730 		mode = mode & S_IROTH;
731 	return (mode << 6) | (mode << 3) | mode;
732 }
733 
734 static void pid_table_root_set_ownership(struct ctl_table_header *head,
735 					 kuid_t *uid, kgid_t *gid)
736 {
737 	struct pid_namespace *pidns =
738 		container_of(head->set, struct pid_namespace, set);
739 	kuid_t ns_root_uid;
740 	kgid_t ns_root_gid;
741 
742 	ns_root_uid = make_kuid(pidns->user_ns, 0);
743 	if (uid_valid(ns_root_uid))
744 		*uid = ns_root_uid;
745 
746 	ns_root_gid = make_kgid(pidns->user_ns, 0);
747 	if (gid_valid(ns_root_gid))
748 		*gid = ns_root_gid;
749 }
750 
751 static struct ctl_table_root pid_table_root = {
752 	.lookup		= pid_table_root_lookup,
753 	.permissions	= pid_table_root_permissions,
754 	.set_ownership	= pid_table_root_set_ownership,
755 };
756 
757 static int proc_do_cad_pid(const struct ctl_table *table, int write, void *buffer,
758 		size_t *lenp, loff_t *ppos)
759 {
760 	struct pid *new_pid;
761 	pid_t tmp_pid;
762 	int r;
763 	struct ctl_table tmp_table = *table;
764 
765 	tmp_pid = pid_vnr(cad_pid);
766 	tmp_table.data = &tmp_pid;
767 
768 	r = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
769 	if (r || !write)
770 		return r;
771 
772 	new_pid = find_get_pid(tmp_pid);
773 	if (!new_pid)
774 		return -ESRCH;
775 
776 	put_pid(xchg(&cad_pid, new_pid));
777 	return 0;
778 }
779 
780 static const struct ctl_table pid_table[] = {
781 	{
782 		.procname	= "pid_max",
783 		.data		= &init_pid_ns.pid_max,
784 		.maxlen		= sizeof(int),
785 		.mode		= 0644,
786 		.proc_handler	= proc_dointvec_minmax,
787 		.extra1		= &pid_max_min,
788 		.extra2		= &pid_max_max,
789 	},
790 #ifdef CONFIG_PROC_SYSCTL
791 	{
792 		.procname	= "cad_pid",
793 		.maxlen		= sizeof(int),
794 		.mode		= 0600,
795 		.proc_handler	= proc_do_cad_pid,
796 	},
797 #endif
798 };
799 #endif
800 
801 int register_pidns_sysctls(struct pid_namespace *pidns)
802 {
803 #ifdef CONFIG_SYSCTL
804 	struct ctl_table *tbl;
805 
806 	setup_sysctl_set(&pidns->set, &pid_table_root, set_is_seen);
807 
808 	tbl = kmemdup(pid_table, sizeof(pid_table), GFP_KERNEL);
809 	if (!tbl)
810 		return -ENOMEM;
811 	tbl->data = &pidns->pid_max;
812 	pidns->pid_max = min(pid_max_max, max_t(int, pidns->pid_max,
813 			     PIDS_PER_CPU_DEFAULT * num_possible_cpus()));
814 
815 	pidns->sysctls = __register_sysctl_table(&pidns->set, "kernel", tbl,
816 						 ARRAY_SIZE(pid_table));
817 	if (!pidns->sysctls) {
818 		kfree(tbl);
819 		retire_sysctl_set(&pidns->set);
820 		return -ENOMEM;
821 	}
822 #endif
823 	return 0;
824 }
825 
826 void unregister_pidns_sysctls(struct pid_namespace *pidns)
827 {
828 #ifdef CONFIG_SYSCTL
829 	const struct ctl_table *tbl;
830 
831 	tbl = pidns->sysctls->ctl_table_arg;
832 	unregister_sysctl_table(pidns->sysctls);
833 	retire_sysctl_set(&pidns->set);
834 	kfree(tbl);
835 #endif
836 }
837 
838 void __init pid_idr_init(void)
839 {
840 	/* Verify no one has done anything silly: */
841 	BUILD_BUG_ON(PID_MAX_LIMIT >= PIDNS_ADDING);
842 
843 	/* bump default and minimum pid_max based on number of cpus */
844 	init_pid_ns.pid_max = min(pid_max_max, max_t(int, init_pid_ns.pid_max,
845 				  PIDS_PER_CPU_DEFAULT * num_possible_cpus()));
846 	pid_max_min = max_t(int, pid_max_min,
847 				PIDS_PER_CPU_MIN * num_possible_cpus());
848 	pr_info("pid_max: default: %u minimum: %u\n", init_pid_ns.pid_max, pid_max_min);
849 
850 	idr_init(&init_pid_ns.idr);
851 
852 	init_pid_ns.pid_cachep = kmem_cache_create("pid",
853 			struct_size_t(struct pid, numbers, 1),
854 			__alignof__(struct pid),
855 			SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT,
856 			NULL);
857 }
858 
859 static __init int pid_namespace_sysctl_init(void)
860 {
861 #ifdef CONFIG_SYSCTL
862 	/* "kernel" directory will have already been initialized. */
863 	BUG_ON(register_pidns_sysctls(&init_pid_ns));
864 #endif
865 	return 0;
866 }
867 subsys_initcall(pid_namespace_sysctl_init);
868 
869 static struct file *__pidfd_fget(struct task_struct *task, int fd)
870 {
871 	struct file *file;
872 	int ret;
873 
874 	ret = down_read_killable(&task->signal->exec_update_lock);
875 	if (ret)
876 		return ERR_PTR(ret);
877 
878 	if (ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS))
879 		file = fget_task(task, fd);
880 	else
881 		file = ERR_PTR(-EPERM);
882 
883 	up_read(&task->signal->exec_update_lock);
884 
885 	if (!file) {
886 		/*
887 		 * It is possible that the target thread is exiting; it can be
888 		 * either:
889 		 * 1. before exit_signals(), which gives a real fd
890 		 * 2. before exit_files() takes the task_lock() gives a real fd
891 		 * 3. after exit_files() releases task_lock(), ->files is NULL;
892 		 *    this has PF_EXITING, since it was set in exit_signals(),
893 		 *    __pidfd_fget() returns EBADF.
894 		 * In case 3 we get EBADF, but that really means ESRCH, since
895 		 * the task is currently exiting and has freed its files
896 		 * struct, so we fix it up.
897 		 */
898 		if (task->flags & PF_EXITING)
899 			file = ERR_PTR(-ESRCH);
900 		else
901 			file = ERR_PTR(-EBADF);
902 	}
903 
904 	return file;
905 }
906 
907 static int pidfd_getfd(struct pid *pid, int fd)
908 {
909 	struct task_struct *task;
910 	struct file *file;
911 	int ret;
912 
913 	task = get_pid_task(pid, PIDTYPE_PID);
914 	if (!task)
915 		return -ESRCH;
916 
917 	file = __pidfd_fget(task, fd);
918 	put_task_struct(task);
919 	if (IS_ERR(file))
920 		return PTR_ERR(file);
921 
922 	ret = receive_fd(file, NULL, O_CLOEXEC);
923 	fput(file);
924 
925 	return ret;
926 }
927 
928 /**
929  * sys_pidfd_getfd() - Get a file descriptor from another process
930  *
931  * @pidfd:	the pidfd file descriptor of the process
932  * @fd:		the file descriptor number to get
933  * @flags:	flags on how to get the fd (reserved)
934  *
935  * This syscall gets a copy of a file descriptor from another process
936  * based on the pidfd, and file descriptor number. It requires that
937  * the calling process has the ability to ptrace the process represented
938  * by the pidfd. The process which is having its file descriptor copied
939  * is otherwise unaffected.
940  *
941  * Return: On success, a cloexec file descriptor is returned.
942  *         On error, a negative errno number will be returned.
943  */
944 SYSCALL_DEFINE3(pidfd_getfd, int, pidfd, int, fd,
945 		unsigned int, flags)
946 {
947 	struct pid *pid;
948 
949 	/* flags is currently unused - make sure it's unset */
950 	if (flags)
951 		return -EINVAL;
952 
953 	CLASS(fd, f)(pidfd);
954 	if (fd_empty(f))
955 		return -EBADF;
956 
957 	pid = pidfd_pid(fd_file(f));
958 	if (IS_ERR(pid))
959 		return PTR_ERR(pid);
960 
961 	return pidfd_getfd(pid, fd);
962 }
963