xref: /linux/kernel/exit.c (revision 55ab7e14222e5f0b0fd9f7711ca391d2924b35e3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/kernel/exit.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  */
7 
8 #include <linux/mm.h>
9 #include <linux/slab.h>
10 #include <linux/sched/autogroup.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/stat.h>
13 #include <linux/sched/task.h>
14 #include <linux/sched/task_stack.h>
15 #include <linux/sched/cputime.h>
16 #include <linux/interrupt.h>
17 #include <linux/module.h>
18 #include <linux/capability.h>
19 #include <linux/completion.h>
20 #include <linux/personality.h>
21 #include <linux/tty.h>
22 #include <linux/iocontext.h>
23 #include <linux/key.h>
24 #include <linux/cpu.h>
25 #include <linux/acct.h>
26 #include <linux/tsacct_kern.h>
27 #include <linux/file.h>
28 #include <linux/freezer.h>
29 #include <linux/binfmts.h>
30 #include <linux/nsproxy.h>
31 #include <linux/pid_namespace.h>
32 #include <linux/ptrace.h>
33 #include <linux/profile.h>
34 #include <linux/mount.h>
35 #include <linux/proc_fs.h>
36 #include <linux/kthread.h>
37 #include <linux/mempolicy.h>
38 #include <linux/taskstats_kern.h>
39 #include <linux/delayacct.h>
40 #include <linux/cgroup.h>
41 #include <linux/syscalls.h>
42 #include <linux/signal.h>
43 #include <linux/posix-timers.h>
44 #include <linux/cn_proc.h>
45 #include <linux/mutex.h>
46 #include <linux/futex.h>
47 #include <linux/pipe_fs_i.h>
48 #include <linux/audit.h> /* for audit_free() */
49 #include <linux/resource.h>
50 #include <linux/task_io_accounting_ops.h>
51 #include <linux/task_work.h>
52 #include <linux/fs_struct.h>
53 #include <linux/init_task.h>
54 #include <linux/perf_event.h>
55 #include <trace/events/sched.h>
56 #include <linux/hw_breakpoint.h>
57 #include <linux/oom.h>
58 #include <linux/writeback.h>
59 #include <linux/shm.h>
60 #include <linux/kcov.h>
61 #include <linux/kmsan.h>
62 #include <linux/random.h>
63 #include <linux/rcuwait.h>
64 #include <linux/compat.h>
65 #include <linux/io_uring.h>
66 #include <linux/kprobes.h>
67 #include <linux/rethook.h>
68 #include <linux/sysfs.h>
69 #include <linux/user_events.h>
70 #include <linux/unwind_deferred.h>
71 #include <linux/uaccess.h>
72 #include <linux/pidfs.h>
73 
74 #include <uapi/linux/wait.h>
75 
76 #include <asm/unistd.h>
77 #include <asm/mmu_context.h>
78 
79 #include "exit.h"
80 
81 /*
82  * The default value should be high enough to not crash a system that randomly
83  * crashes its kernel from time to time, but low enough to at least not permit
84  * overflowing 32-bit refcounts or the ldsem writer count.
85  */
86 static unsigned int oops_limit = 10000;
87 
88 #ifdef CONFIG_SYSCTL
89 static const struct ctl_table kern_exit_table[] = {
90 	{
91 		.procname       = "oops_limit",
92 		.data           = &oops_limit,
93 		.maxlen         = sizeof(oops_limit),
94 		.mode           = 0644,
95 		.proc_handler   = proc_douintvec,
96 	},
97 };
98 
kernel_exit_sysctls_init(void)99 static __init int kernel_exit_sysctls_init(void)
100 {
101 	register_sysctl_init("kernel", kern_exit_table);
102 	return 0;
103 }
104 late_initcall(kernel_exit_sysctls_init);
105 #endif
106 
107 static atomic_t oops_count = ATOMIC_INIT(0);
108 
109 #ifdef CONFIG_SYSFS
oops_count_show(struct kobject * kobj,struct kobj_attribute * attr,char * page)110 static ssize_t oops_count_show(struct kobject *kobj, struct kobj_attribute *attr,
111 			       char *page)
112 {
113 	return sysfs_emit(page, "%d\n", atomic_read(&oops_count));
114 }
115 
116 static struct kobj_attribute oops_count_attr = __ATTR_RO(oops_count);
117 
kernel_exit_sysfs_init(void)118 static __init int kernel_exit_sysfs_init(void)
119 {
120 	sysfs_add_file_to_group(kernel_kobj, &oops_count_attr.attr, NULL);
121 	return 0;
122 }
123 late_initcall(kernel_exit_sysfs_init);
124 #endif
125 
126 /*
127  * For things release_task() would like to do *after* tasklist_lock is released.
128  */
129 struct release_task_post {
130 	struct pid *pids[PIDTYPE_MAX];
131 };
132 
__unhash_process(struct release_task_post * post,struct task_struct * p,bool group_dead)133 static void __unhash_process(struct release_task_post *post, struct task_struct *p,
134 			     bool group_dead)
135 {
136 	struct pid *pid = task_pid(p);
137 
138 	nr_threads--;
139 
140 	detach_pid(post->pids, p, PIDTYPE_PID);
141 	wake_up_all(&pid->wait_pidfd);
142 
143 	if (group_dead) {
144 		detach_pid(post->pids, p, PIDTYPE_TGID);
145 		detach_pid(post->pids, p, PIDTYPE_PGID);
146 		detach_pid(post->pids, p, PIDTYPE_SID);
147 
148 		list_del_rcu(&p->tasks);
149 		list_del_init(&p->sibling);
150 		__this_cpu_dec(process_counts);
151 	}
152 	list_del_rcu(&p->thread_node);
153 }
154 
155 /*
156  * This function expects the tasklist_lock write-locked.
157  */
__exit_signal(struct release_task_post * post,struct task_struct * tsk)158 static void __exit_signal(struct release_task_post *post, struct task_struct *tsk)
159 {
160 	struct signal_struct *sig = tsk->signal;
161 	bool group_dead = thread_group_leader(tsk);
162 	struct sighand_struct *sighand;
163 	struct tty_struct *tty;
164 	u64 utime, stime;
165 
166 	sighand = rcu_dereference_check(tsk->sighand,
167 					lockdep_tasklist_lock_is_held());
168 	spin_lock(&sighand->siglock);
169 
170 #ifdef CONFIG_POSIX_TIMERS
171 	posix_cpu_timers_exit(tsk);
172 	if (group_dead)
173 		posix_cpu_timers_exit_group(tsk);
174 #endif
175 
176 	if (group_dead) {
177 		tty = sig->tty;
178 		sig->tty = NULL;
179 	} else {
180 		/*
181 		 * If there is any task waiting for the group exit
182 		 * then notify it:
183 		 */
184 		if (sig->notify_count > 0 && !--sig->notify_count)
185 			wake_up_process(sig->group_exec_task);
186 
187 		if (tsk == sig->curr_target)
188 			sig->curr_target = next_thread(tsk);
189 	}
190 
191 	/*
192 	 * Accumulate here the counters for all threads as they die. We could
193 	 * skip the group leader because it is the last user of signal_struct,
194 	 * but we want to avoid the race with thread_group_cputime() which can
195 	 * see the empty ->thread_head list.
196 	 */
197 	task_cputime(tsk, &utime, &stime);
198 	write_seqlock(&sig->stats_lock);
199 	sig->utime += utime;
200 	sig->stime += stime;
201 	sig->gtime += task_gtime(tsk);
202 	sig->min_flt += tsk->min_flt;
203 	sig->maj_flt += tsk->maj_flt;
204 	sig->nvcsw += tsk->nvcsw;
205 	sig->nivcsw += tsk->nivcsw;
206 	sig->inblock += task_io_get_inblock(tsk);
207 	sig->oublock += task_io_get_oublock(tsk);
208 	task_io_accounting_add(&sig->ioac, &tsk->ioac);
209 	sig->sum_sched_runtime += tsk->se.sum_exec_runtime;
210 	sig->nr_threads--;
211 	__unhash_process(post, tsk, group_dead);
212 	write_sequnlock(&sig->stats_lock);
213 
214 	/*
215 	 * Ensure that all preceeding state is visible. Pairs with
216 	 * the smp_acquire__after_ctrl_dep() in the sighand == NULL
217 	 * path of lock_task_sighand().
218 	 */
219 	smp_store_release(&tsk->sighand, NULL);
220 	spin_unlock(&sighand->siglock);
221 
222 	__cleanup_sighand(sighand);
223 	if (group_dead)
224 		tty_kref_put(tty);
225 }
226 
delayed_put_task_struct(struct rcu_head * rhp)227 static void delayed_put_task_struct(struct rcu_head *rhp)
228 {
229 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
230 
231 	kprobe_flush_task(tsk);
232 	rethook_flush_task(tsk);
233 	perf_event_delayed_put(tsk);
234 	trace_sched_process_free(tsk);
235 	put_task_struct(tsk);
236 }
237 
put_task_struct_rcu_user(struct task_struct * task)238 void put_task_struct_rcu_user(struct task_struct *task)
239 {
240 	if (refcount_dec_and_test(&task->rcu_users))
241 		call_rcu(&task->rcu, delayed_put_task_struct);
242 }
243 
release_thread(struct task_struct * dead_task)244 void __weak release_thread(struct task_struct *dead_task)
245 {
246 }
247 
release_task(struct task_struct * p)248 void release_task(struct task_struct *p)
249 {
250 	struct release_task_post post;
251 	struct task_struct *leader;
252 	struct pid *thread_pid;
253 	int zap_leader;
254 repeat:
255 	memset(&post, 0, sizeof(post));
256 
257 	/* don't need to get the RCU readlock here - the process is dead and
258 	 * can't be modifying its own credentials. */
259 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
260 
261 	pidfs_exit(p);
262 	cgroup_task_release(p);
263 
264 	/* Retrieve @thread_pid before __unhash_process() may set it to NULL. */
265 	thread_pid = task_pid(p);
266 
267 	write_lock_irq(&tasklist_lock);
268 	ptrace_release_task(p);
269 	__exit_signal(&post, p);
270 
271 	/*
272 	 * If we are the last non-leader member of the thread
273 	 * group, and the leader is zombie, then notify the
274 	 * group leader's parent process. (if it wants notification.)
275 	 */
276 	zap_leader = 0;
277 	leader = p->group_leader;
278 	if (leader != p && thread_group_empty(leader)
279 			&& leader->exit_state == EXIT_ZOMBIE) {
280 		/* for pidfs_exit() and do_notify_parent() */
281 		if (leader->signal->flags & SIGNAL_GROUP_EXIT)
282 			leader->exit_code = leader->signal->group_exit_code;
283 		/*
284 		 * If we were the last child thread and the leader has
285 		 * exited already, and the leader's parent ignores SIGCHLD,
286 		 * then we are the one who should release the leader.
287 		 */
288 		zap_leader = do_notify_parent(leader, leader->exit_signal);
289 		if (zap_leader)
290 			leader->exit_state = EXIT_DEAD;
291 	}
292 
293 	write_unlock_irq(&tasklist_lock);
294 	/* @thread_pid can't go away until free_pids() below */
295 	proc_flush_pid(thread_pid);
296 	exit_cred_namespaces(p);
297 	add_device_randomness(&p->se.sum_exec_runtime,
298 			      sizeof(p->se.sum_exec_runtime));
299 	free_pids(post.pids);
300 	release_thread(p);
301 	/*
302 	 * This task was already removed from the process/thread/pid lists
303 	 * and lock_task_sighand(p) can't succeed. Nobody else can touch
304 	 * ->pending or, if group dead, signal->shared_pending. We can call
305 	 * flush_sigqueue() lockless.
306 	 */
307 	flush_sigqueue(&p->pending);
308 	if (thread_group_leader(p))
309 		flush_sigqueue(&p->signal->shared_pending);
310 
311 	put_task_struct_rcu_user(p);
312 
313 	p = leader;
314 	if (unlikely(zap_leader))
315 		goto repeat;
316 }
317 
rcuwait_wake_up(struct rcuwait * w)318 int rcuwait_wake_up(struct rcuwait *w)
319 {
320 	int ret = 0;
321 	struct task_struct *task;
322 
323 	rcu_read_lock();
324 
325 	/*
326 	 * Order condition vs @task, such that everything prior to the load
327 	 * of @task is visible. This is the condition as to why the user called
328 	 * rcuwait_wake() in the first place. Pairs with set_current_state()
329 	 * barrier (A) in rcuwait_wait_event().
330 	 *
331 	 *    WAIT                WAKE
332 	 *    [S] tsk = current	  [S] cond = true
333 	 *        MB (A)	      MB (B)
334 	 *    [L] cond		  [L] tsk
335 	 */
336 	smp_mb(); /* (B) */
337 
338 	task = rcu_dereference(w->task);
339 	if (task)
340 		ret = wake_up_process(task);
341 	rcu_read_unlock();
342 
343 	return ret;
344 }
345 EXPORT_SYMBOL_GPL(rcuwait_wake_up);
346 
347 /*
348  * Determine if a process group is "orphaned", according to the POSIX
349  * definition in 2.2.2.52.  Orphaned process groups are not to be affected
350  * by terminal-generated stop signals.  Newly orphaned process groups are
351  * to receive a SIGHUP and a SIGCONT.
352  *
353  * "I ask you, have you ever known what it is to be an orphan?"
354  */
will_become_orphaned_pgrp(struct pid * pgrp,struct task_struct * ignored_task)355 static int will_become_orphaned_pgrp(struct pid *pgrp,
356 					struct task_struct *ignored_task)
357 {
358 	struct task_struct *p;
359 
360 	do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
361 		if ((p == ignored_task) ||
362 		    (p->exit_state && thread_group_empty(p)) ||
363 		    is_global_init(p->real_parent))
364 			continue;
365 
366 		if (task_pgrp(p->real_parent) != pgrp &&
367 		    task_session(p->real_parent) == task_session(p))
368 			return 0;
369 	} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
370 
371 	return 1;
372 }
373 
is_current_pgrp_orphaned(void)374 int is_current_pgrp_orphaned(void)
375 {
376 	int retval;
377 
378 	read_lock(&tasklist_lock);
379 	retval = will_become_orphaned_pgrp(task_pgrp(current), NULL);
380 	read_unlock(&tasklist_lock);
381 
382 	return retval;
383 }
384 
has_stopped_jobs(struct pid * pgrp)385 static bool has_stopped_jobs(struct pid *pgrp)
386 {
387 	struct task_struct *p;
388 
389 	do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
390 		if (p->signal->flags & SIGNAL_STOP_STOPPED)
391 			return true;
392 	} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
393 
394 	return false;
395 }
396 
397 /*
398  * Check to see if any process groups have become orphaned as
399  * a result of our exiting, and if they have any stopped jobs,
400  * send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2)
401  */
402 static void
kill_orphaned_pgrp(struct task_struct * tsk,struct task_struct * parent)403 kill_orphaned_pgrp(struct task_struct *tsk, struct task_struct *parent)
404 {
405 	struct pid *pgrp = task_pgrp(tsk);
406 	struct task_struct *ignored_task = tsk;
407 
408 	if (!parent)
409 		/* exit: our father is in a different pgrp than
410 		 * we are and we were the only connection outside.
411 		 */
412 		parent = tsk->real_parent;
413 	else
414 		/* reparent: our child is in a different pgrp than
415 		 * we are, and it was the only connection outside.
416 		 */
417 		ignored_task = NULL;
418 
419 	if (task_pgrp(parent) != pgrp &&
420 	    task_session(parent) == task_session(tsk) &&
421 	    will_become_orphaned_pgrp(pgrp, ignored_task) &&
422 	    has_stopped_jobs(pgrp)) {
423 		__kill_pgrp_info(SIGHUP, SEND_SIG_PRIV, pgrp);
424 		__kill_pgrp_info(SIGCONT, SEND_SIG_PRIV, pgrp);
425 	}
426 }
427 
coredump_task_exit(struct task_struct * tsk,struct core_state * core_state)428 static void coredump_task_exit(struct task_struct *tsk,
429 			       struct core_state *core_state)
430 {
431 	struct core_thread self;
432 
433 	self.task = tsk;
434 	if (self.task->flags & PF_SIGNALED)
435 		self.next = xchg(&core_state->dumper.next, &self);
436 	else
437 		self.task = NULL;
438 	/*
439 	 * Implies mb(), the result of xchg() must be visible
440 	 * to core_state->dumper.
441 	 */
442 	if (atomic_dec_and_test(&core_state->nr_threads))
443 		complete(&core_state->startup);
444 
445 	for (;;) {
446 		set_current_state(TASK_IDLE|TASK_FREEZABLE);
447 		if (!self.task) /* see coredump_finish() */
448 			break;
449 		schedule();
450 	}
451 	__set_current_state(TASK_RUNNING);
452 }
453 
454 #ifdef CONFIG_MEMCG
455 /* drops tasklist_lock if succeeds */
__try_to_set_owner(struct task_struct * tsk,struct mm_struct * mm)456 static bool __try_to_set_owner(struct task_struct *tsk, struct mm_struct *mm)
457 {
458 	bool ret = false;
459 
460 	task_lock(tsk);
461 	if (likely(tsk->mm == mm)) {
462 		/* tsk can't pass exit_mm/exec_mmap and exit */
463 		read_unlock(&tasklist_lock);
464 		WRITE_ONCE(mm->owner, tsk);
465 		lru_gen_migrate_mm(mm);
466 		ret = true;
467 	}
468 	task_unlock(tsk);
469 	return ret;
470 }
471 
try_to_set_owner(struct task_struct * g,struct mm_struct * mm)472 static bool try_to_set_owner(struct task_struct *g, struct mm_struct *mm)
473 {
474 	struct task_struct *t;
475 
476 	for_each_thread(g, t) {
477 		struct mm_struct *t_mm = READ_ONCE(t->mm);
478 		if (t_mm == mm) {
479 			if (__try_to_set_owner(t, mm))
480 				return true;
481 		} else if (t_mm)
482 			break;
483 	}
484 
485 	return false;
486 }
487 
488 /*
489  * A task is exiting.   If it owned this mm, find a new owner for the mm.
490  */
mm_update_next_owner(struct mm_struct * mm)491 void mm_update_next_owner(struct mm_struct *mm)
492 {
493 	struct task_struct *g, *p = current;
494 
495 	/*
496 	 * If the exiting or execing task is not the owner, it's
497 	 * someone else's problem.
498 	 */
499 	if (mm->owner != p)
500 		return;
501 	/*
502 	 * The current owner is exiting/execing and there are no other
503 	 * candidates.  Do not leave the mm pointing to a possibly
504 	 * freed task structure.
505 	 */
506 	if (atomic_read(&mm->mm_users) <= 1) {
507 		WRITE_ONCE(mm->owner, NULL);
508 		return;
509 	}
510 
511 	read_lock(&tasklist_lock);
512 	/*
513 	 * Search in the children
514 	 */
515 	list_for_each_entry(g, &p->children, sibling) {
516 		if (try_to_set_owner(g, mm))
517 			goto ret;
518 	}
519 	/*
520 	 * Search in the siblings
521 	 */
522 	list_for_each_entry(g, &p->real_parent->children, sibling) {
523 		if (try_to_set_owner(g, mm))
524 			goto ret;
525 	}
526 	/*
527 	 * Search through everything else, we should not get here often.
528 	 */
529 	for_each_process(g) {
530 		if (atomic_read(&mm->mm_users) <= 1)
531 			break;
532 		if (g->flags & PF_KTHREAD)
533 			continue;
534 		if (try_to_set_owner(g, mm))
535 			goto ret;
536 	}
537 	read_unlock(&tasklist_lock);
538 	/*
539 	 * We found no owner yet mm_users > 1: this implies that we are
540 	 * most likely racing with swapoff (try_to_unuse()) or /proc or
541 	 * ptrace or page migration (get_task_mm()).  Mark owner as NULL.
542 	 */
543 	WRITE_ONCE(mm->owner, NULL);
544  ret:
545 	return;
546 
547 }
548 #endif /* CONFIG_MEMCG */
549 
550 #if defined(CONFIG_SCHED_CACHE) && defined(CONFIG_NUMA_BALANCING)
551 /*
552  * Subtract the memory footprint of the current task from
553  * mm.
554  */
exit_mm_sched_cache(struct mm_struct * mm)555 static void exit_mm_sched_cache(struct mm_struct *mm)
556 {
557 	unsigned long fp, sub;
558 
559 	if (!current->total_numa_faults)
560 		return;
561 	/*
562 	 * No lock protection due to performance considerations.
563 	 * Make sure mm->sc_stat.footprint does not become
564 	 * negative.
565 	 */
566 	fp = READ_ONCE(mm->sc_stat.footprint);
567 	sub = min(fp, current->total_numa_faults);
568 	WRITE_ONCE(mm->sc_stat.footprint, fp - sub);
569 }
570 #else
exit_mm_sched_cache(struct mm_struct * mm)571 static inline void exit_mm_sched_cache(struct mm_struct *mm)
572 {
573 }
574 #endif /* CONFIG_SCHED_CACHE CONFIG_NUMA_BALANCING */
575 
576 /*
577  * Turn us into a lazy TLB process if we
578  * aren't already..
579  */
exit_mm(void)580 static void exit_mm(void)
581 {
582 	struct mm_struct *mm = current->mm;
583 
584 	exit_mm_release(current, mm);
585 	if (!mm)
586 		return;
587 
588 	exit_mm_sched_cache(mm);
589 
590 	mmap_read_lock(mm);
591 	mmgrab_lazy_tlb(mm);
592 	BUG_ON(mm != current->active_mm);
593 	/* more a memory barrier than a real lock */
594 	task_lock(current);
595 	/*
596 	 * When a thread stops operating on an address space, the loop
597 	 * in membarrier_private_expedited() may not observe that
598 	 * tsk->mm, and the loop in membarrier_global_expedited() may
599 	 * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
600 	 * rq->membarrier_state, so those would not issue an IPI.
601 	 * Membarrier requires a memory barrier after accessing
602 	 * user-space memory, before clearing tsk->mm or the
603 	 * rq->membarrier_state.
604 	 */
605 	smp_mb__after_spinlock();
606 	local_irq_disable();
607 	current->mm = NULL;
608 	membarrier_update_current_mm(NULL);
609 	enter_lazy_tlb(mm, current);
610 	local_irq_enable();
611 	task_unlock(current);
612 	mmap_read_unlock(mm);
613 	mm_update_next_owner(mm);
614 	mmput(mm);
615 	if (test_thread_flag(TIF_MEMDIE))
616 		exit_oom_victim();
617 }
618 
find_alive_thread(struct task_struct * p)619 static struct task_struct *find_alive_thread(struct task_struct *p)
620 {
621 	struct task_struct *t;
622 
623 	for_each_thread(p, t) {
624 		if (!(t->flags & PF_EXITING))
625 			return t;
626 	}
627 	return NULL;
628 }
629 
find_child_reaper(struct task_struct * father,struct list_head * dead)630 static struct task_struct *find_child_reaper(struct task_struct *father,
631 						struct list_head *dead)
632 	__releases(&tasklist_lock)
633 	__acquires(&tasklist_lock)
634 {
635 	struct pid_namespace *pid_ns = task_active_pid_ns(father);
636 	struct task_struct *reaper = pid_ns->child_reaper;
637 	struct task_struct *p, *n;
638 
639 	if (likely(reaper != father))
640 		return reaper;
641 
642 	reaper = find_alive_thread(father);
643 	if (reaper) {
644 		ASSERT_EXCLUSIVE_WRITER(pid_ns->child_reaper);
645 		WRITE_ONCE(pid_ns->child_reaper, reaper);
646 		return reaper;
647 	}
648 
649 	write_unlock_irq(&tasklist_lock);
650 
651 	list_for_each_entry_safe(p, n, dead, ptrace_entry) {
652 		list_del_init(&p->ptrace_entry);
653 		release_task(p);
654 	}
655 
656 	zap_pid_ns_processes(pid_ns);
657 	write_lock_irq(&tasklist_lock);
658 
659 	return father;
660 }
661 
662 /*
663  * When we die, we re-parent all our children, and try to:
664  * 1. give them to another thread in our thread group, if such a member exists
665  * 2. give it to the first ancestor process which prctl'd itself as a
666  *    child_subreaper for its children (like a service manager)
667  * 3. give it to the init process (PID 1) in our pid namespace
668  */
find_new_reaper(struct task_struct * father,struct task_struct * child_reaper)669 static struct task_struct *find_new_reaper(struct task_struct *father,
670 					   struct task_struct *child_reaper)
671 {
672 	struct task_struct *thread, *reaper;
673 
674 	thread = find_alive_thread(father);
675 	if (thread)
676 		return thread;
677 
678 	if (father->signal->has_child_subreaper) {
679 		unsigned int ns_level = task_pid(father)->level;
680 		/*
681 		 * Find the first ->is_child_subreaper ancestor in our pid_ns.
682 		 * We can't check reaper != child_reaper to ensure we do not
683 		 * cross the namespaces, the exiting parent could be injected
684 		 * by setns() + fork().
685 		 * We check pid->level, this is slightly more efficient than
686 		 * task_active_pid_ns(reaper) != task_active_pid_ns(father).
687 		 */
688 		for (reaper = father->real_parent;
689 		     task_pid(reaper)->level == ns_level;
690 		     reaper = reaper->real_parent) {
691 			if (reaper == &init_task)
692 				break;
693 			if (!reaper->signal->is_child_subreaper)
694 				continue;
695 			thread = find_alive_thread(reaper);
696 			if (thread)
697 				return thread;
698 		}
699 	}
700 
701 	return child_reaper;
702 }
703 
704 /*
705 * Any that need to be release_task'd are put on the @dead list.
706  */
reparent_leader(struct task_struct * father,struct task_struct * p,struct list_head * dead)707 static void reparent_leader(struct task_struct *father, struct task_struct *p,
708 				struct list_head *dead)
709 {
710 	if (unlikely(p->exit_state == EXIT_DEAD))
711 		return;
712 
713 	/* We don't want people slaying init. */
714 	p->exit_signal = SIGCHLD;
715 
716 	/* If it has exited notify the new parent about this child's death. */
717 	if (!p->ptrace &&
718 	    p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) {
719 		if (do_notify_parent(p, p->exit_signal)) {
720 			p->exit_state = EXIT_DEAD;
721 			list_add(&p->ptrace_entry, dead);
722 		}
723 	}
724 
725 	kill_orphaned_pgrp(p, father);
726 }
727 
728 /*
729  * Make init inherit all the child processes
730  */
forget_original_parent(struct task_struct * father,struct list_head * dead)731 static void forget_original_parent(struct task_struct *father,
732 					struct list_head *dead)
733 {
734 	struct task_struct *p, *t, *reaper;
735 
736 	if (unlikely(!list_empty(&father->ptraced)))
737 		exit_ptrace(father, dead);
738 
739 	/* Can drop and reacquire tasklist_lock */
740 	reaper = find_child_reaper(father, dead);
741 	if (list_empty(&father->children))
742 		return;
743 
744 	reaper = find_new_reaper(father, reaper);
745 	list_for_each_entry(p, &father->children, sibling) {
746 		for_each_thread(p, t) {
747 			RCU_INIT_POINTER(t->real_parent, reaper);
748 			BUG_ON((!t->ptrace) != (rcu_access_pointer(t->parent) == father));
749 			if (likely(!t->ptrace))
750 				t->parent = t->real_parent;
751 			if (t->pdeath_signal)
752 				group_send_sig_info(t->pdeath_signal,
753 						    SEND_SIG_NOINFO, t,
754 						    PIDTYPE_TGID);
755 		}
756 		/*
757 		 * If this is a threaded reparent there is no need to
758 		 * notify anyone anything has happened.
759 		 */
760 		if (!same_thread_group(reaper, father))
761 			reparent_leader(father, p, dead);
762 	}
763 	list_splice_tail_init(&father->children, &reaper->children);
764 }
765 
766 /*
767  * Send signals to all our closest relatives so that they know
768  * to properly mourn us..
769  */
exit_notify(struct task_struct * tsk,int group_dead)770 static void exit_notify(struct task_struct *tsk, int group_dead)
771 {
772 	bool autoreap;
773 	struct task_struct *p, *n;
774 	LIST_HEAD(dead);
775 
776 	write_lock_irq(&tasklist_lock);
777 	forget_original_parent(tsk, &dead);
778 
779 	if (group_dead)
780 		kill_orphaned_pgrp(tsk->group_leader, NULL);
781 
782 	tsk->exit_state = EXIT_ZOMBIE;
783 
784 	if (unlikely(tsk->ptrace)) {
785 		int sig = thread_group_empty(tsk) && !ptrace_reparented(tsk)
786 			  ? tsk->exit_signal : SIGCHLD;
787 		autoreap = do_notify_parent(tsk, sig);
788 	} else if (thread_group_leader(tsk)) {
789 		autoreap = thread_group_empty(tsk) &&
790 			   do_notify_parent(tsk, tsk->exit_signal);
791 	} else {
792 		autoreap = true;
793 		/* untraced sub-thread */
794 		do_notify_pidfd(tsk);
795 	}
796 
797 	if (autoreap) {
798 		tsk->exit_state = EXIT_DEAD;
799 		list_add(&tsk->ptrace_entry, &dead);
800 	}
801 
802 	/* mt-exec, de_thread() is waiting for group leader */
803 	if (unlikely(tsk->signal->notify_count < 0))
804 		wake_up_process(tsk->signal->group_exec_task);
805 	write_unlock_irq(&tasklist_lock);
806 
807 	list_for_each_entry_safe(p, n, &dead, ptrace_entry) {
808 		list_del_init(&p->ptrace_entry);
809 		release_task(p);
810 	}
811 }
812 
813 #ifdef CONFIG_DEBUG_STACK_USAGE
814 #ifdef CONFIG_STACK_GROWSUP
stack_not_used(struct task_struct * p)815 unsigned long stack_not_used(struct task_struct *p)
816 {
817 	unsigned long *n = end_of_stack(p);
818 
819 	do {	/* Skip over canary */
820 		n--;
821 	} while (!*n);
822 
823 	return (unsigned long)end_of_stack(p) - (unsigned long)n;
824 }
825 #else /* !CONFIG_STACK_GROWSUP */
stack_not_used(struct task_struct * p)826 unsigned long stack_not_used(struct task_struct *p)
827 {
828 	unsigned long *n = end_of_stack(p);
829 
830 	do {	/* Skip over canary */
831 		n++;
832 	} while (!*n);
833 
834 	return (unsigned long)n - (unsigned long)end_of_stack(p);
835 }
836 #endif /* CONFIG_STACK_GROWSUP */
837 
838 /* Count the maximum pages reached in kernel stacks */
kstack_histogram(unsigned long used_stack)839 static inline void kstack_histogram(unsigned long used_stack)
840 {
841 #ifdef CONFIG_VM_EVENT_COUNTERS
842 	if (used_stack <= 1024)
843 		count_vm_event(KSTACK_1K);
844 #if THREAD_SIZE > 1024
845 	else if (used_stack <= 2048)
846 		count_vm_event(KSTACK_2K);
847 #endif
848 #if THREAD_SIZE > 2048
849 	else if (used_stack <= 4096)
850 		count_vm_event(KSTACK_4K);
851 #endif
852 #if THREAD_SIZE > 4096
853 	else if (used_stack <= 8192)
854 		count_vm_event(KSTACK_8K);
855 #endif
856 #if THREAD_SIZE > 8192
857 	else if (used_stack <= 16384)
858 		count_vm_event(KSTACK_16K);
859 #endif
860 #if THREAD_SIZE > 16384
861 	else if (used_stack <= 32768)
862 		count_vm_event(KSTACK_32K);
863 #endif
864 #if THREAD_SIZE > 32768
865 	else if (used_stack <= 65536)
866 		count_vm_event(KSTACK_64K);
867 #endif
868 #if THREAD_SIZE > 65536
869 	else
870 		count_vm_event(KSTACK_REST);
871 #endif
872 #endif /* CONFIG_VM_EVENT_COUNTERS */
873 }
874 
check_stack_usage(void)875 static void check_stack_usage(void)
876 {
877 	static DEFINE_SPINLOCK(low_water_lock);
878 	static int lowest_to_date = THREAD_SIZE;
879 	unsigned long free;
880 
881 	free = stack_not_used(current);
882 	kstack_histogram(THREAD_SIZE - free);
883 
884 	if (free >= lowest_to_date)
885 		return;
886 
887 	spin_lock(&low_water_lock);
888 	if (free < lowest_to_date) {
889 		pr_info("%s (%d) used greatest stack depth: %lu bytes left\n",
890 			current->comm, task_pid_nr(current), free);
891 		lowest_to_date = free;
892 	}
893 	spin_unlock(&low_water_lock);
894 }
895 #else /* !CONFIG_DEBUG_STACK_USAGE */
check_stack_usage(void)896 static inline void check_stack_usage(void) {}
897 #endif /* CONFIG_DEBUG_STACK_USAGE */
898 
synchronize_group_exit(struct task_struct * tsk,long code)899 static void synchronize_group_exit(struct task_struct *tsk, long code)
900 {
901 	struct sighand_struct *sighand = tsk->sighand;
902 	struct signal_struct *signal = tsk->signal;
903 	struct core_state *core_state;
904 
905 	spin_lock_irq(&sighand->siglock);
906 	signal->quick_threads--;
907 	if ((signal->quick_threads == 0) &&
908 	    !(signal->flags & SIGNAL_GROUP_EXIT)) {
909 		signal->flags = SIGNAL_GROUP_EXIT;
910 		signal->group_exit_code = code;
911 		signal->group_stop_count = 0;
912 	}
913 	/*
914 	 * Serialize with any possible pending coredump.
915 	 * We must hold siglock around checking core_state
916 	 * and setting PF_POSTCOREDUMP.  The core-inducing thread
917 	 * will increment ->nr_threads for each thread in the
918 	 * group without PF_POSTCOREDUMP set.
919 	 */
920 	tsk->flags |= PF_POSTCOREDUMP;
921 	core_state = signal->core_state;
922 	spin_unlock_irq(&sighand->siglock);
923 
924 	if (unlikely(core_state))
925 		coredump_task_exit(tsk, core_state);
926 }
927 
do_exit(long code)928 void __noreturn do_exit(long code)
929 {
930 	struct task_struct *tsk = current;
931 	struct kthread *kthread;
932 	int group_dead;
933 
934 	WARN_ON(irqs_disabled());
935 	WARN_ON(tsk->plug);
936 
937 	kthread = tsk_is_kthread(tsk);
938 	if (unlikely(kthread))
939 		kthread_do_exit(kthread, code);
940 
941 	kcov_task_exit(tsk);
942 	kmsan_task_exit(tsk);
943 
944 	synchronize_group_exit(tsk, code);
945 	ptrace_event(PTRACE_EVENT_EXIT, code);
946 	user_events_exit(tsk);
947 
948 	io_uring_files_cancel();
949 	sched_mm_cid_exit(tsk);
950 	exit_signals(tsk);  /* sets PF_EXITING */
951 
952 	seccomp_filter_release(tsk);
953 
954 	acct_update_integrals(tsk);
955 	group_dead = atomic_dec_and_test(&tsk->signal->live);
956 	if (group_dead) {
957 		/*
958 		 * If the last thread of global init has exited, panic
959 		 * immediately to get a useable coredump.
960 		 */
961 		if (unlikely(is_global_init(tsk)))
962 			panic("Attempted to kill init! exitcode=0x%08x\n",
963 				tsk->signal->group_exit_code ?: (int)code);
964 
965 #ifdef CONFIG_POSIX_TIMERS
966 		hrtimer_cancel(&tsk->signal->real_timer);
967 		exit_itimers(tsk);
968 #endif
969 		if (tsk->mm)
970 			setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
971 	}
972 	acct_collect(code, group_dead);
973 	if (group_dead)
974 		tty_audit_exit();
975 	audit_free(tsk);
976 
977 	tsk->exit_code = code;
978 	taskstats_exit(tsk, group_dead);
979 	trace_sched_process_exit(tsk, group_dead);
980 
981 	/*
982 	 * Since sampling can touch ->mm, make sure to stop everything before we
983 	 * tear it down.
984 	 *
985 	 * Also flushes inherited counters to the parent - before the parent
986 	 * gets woken up by child-exit notifications.
987 	 */
988 	perf_event_exit_task(tsk);
989 	/*
990 	 * PF_EXITING (above) ensures unwind_deferred_request() will no
991 	 * longer add new unwinds. While exit_mm() (below) will destroy the
992 	 * abaility to do unwinds. So flush any pending unwinds here.
993 	 */
994 	unwind_deferred_task_exit(tsk);
995 
996 	exit_mm();
997 
998 	if (group_dead)
999 		acct_process();
1000 
1001 	exit_sem(tsk);
1002 	exit_shm(tsk);
1003 	exit_files(tsk);
1004 	exit_fs(tsk);
1005 	if (group_dead)
1006 		disassociate_ctty(1);
1007 	exit_nsproxy_namespaces(tsk);
1008 	exit_task_work(tsk);
1009 	exit_thread(tsk);
1010 
1011 	sched_autogroup_exit_task(tsk);
1012 	cgroup_task_exit(tsk);
1013 
1014 	/*
1015 	 * FIXME: do that only when needed, using sched_exit tracepoint
1016 	 */
1017 	flush_ptrace_hw_breakpoint(tsk);
1018 
1019 	exit_tasks_rcu_start();
1020 	exit_notify(tsk, group_dead);
1021 	proc_exit_connector(tsk);
1022 	mpol_put_task_policy(tsk);
1023 #ifdef CONFIG_FUTEX
1024 	if (unlikely(current->futex.pi_state_cache))
1025 		kfree(current->futex.pi_state_cache);
1026 #endif
1027 	/*
1028 	 * Make sure we are holding no locks:
1029 	 */
1030 	debug_check_no_locks_held();
1031 
1032 	if (tsk->io_context)
1033 		exit_io_context(tsk);
1034 
1035 	if (tsk->splice_pipe)
1036 		free_pipe_info(tsk->splice_pipe);
1037 
1038 	if (tsk->task_frag.page)
1039 		put_page(tsk->task_frag.page);
1040 
1041 	exit_task_stack_account(tsk);
1042 
1043 	check_stack_usage();
1044 	preempt_disable();
1045 	if (tsk->nr_dirtied)
1046 		__this_cpu_add(dirty_throttle_leaks, tsk->nr_dirtied);
1047 	exit_rcu();
1048 	exit_tasks_rcu_finish();
1049 
1050 	lockdep_free_task(tsk);
1051 	do_task_dead();
1052 }
1053 EXPORT_SYMBOL(do_exit);
1054 
make_task_dead(int signr)1055 void __noreturn make_task_dead(int signr)
1056 {
1057 	/*
1058 	 * Take the task off the cpu after something catastrophic has
1059 	 * happened.
1060 	 *
1061 	 * We can get here from a kernel oops, sometimes with preemption off.
1062 	 * Start by checking for critical errors.
1063 	 * Then fix up important state like USER_DS and preemption.
1064 	 * Then do everything else.
1065 	 */
1066 	struct task_struct *tsk = current;
1067 	unsigned int limit;
1068 
1069 	if (unlikely(in_interrupt()))
1070 		panic("Aiee, killing interrupt handler!");
1071 	if (unlikely(!tsk->pid))
1072 		panic("Attempted to kill the idle task!");
1073 
1074 	if (unlikely(irqs_disabled())) {
1075 		pr_info("note: %s[%d] exited with irqs disabled\n",
1076 			current->comm, task_pid_nr(current));
1077 		local_irq_enable();
1078 	}
1079 	if (unlikely(in_atomic())) {
1080 		pr_info("note: %s[%d] exited with preempt_count %d\n",
1081 			current->comm, task_pid_nr(current),
1082 			preempt_count());
1083 		preempt_count_set(PREEMPT_ENABLED);
1084 	}
1085 
1086 	/*
1087 	 * Every time the system oopses, if the oops happens while a reference
1088 	 * to an object was held, the reference leaks.
1089 	 * If the oops doesn't also leak memory, repeated oopsing can cause
1090 	 * reference counters to wrap around (if they're not using refcount_t).
1091 	 * This means that repeated oopsing can make unexploitable-looking bugs
1092 	 * exploitable through repeated oopsing.
1093 	 * To make sure this can't happen, place an upper bound on how often the
1094 	 * kernel may oops without panic().
1095 	 */
1096 	limit = READ_ONCE(oops_limit);
1097 	if (atomic_inc_return(&oops_count) >= limit && limit)
1098 		panic("Oopsed too often (kernel.oops_limit is %d)", limit);
1099 
1100 	/*
1101 	 * We're taking recursive faults here in make_task_dead. Safest is to just
1102 	 * leave this task alone and wait for reboot.
1103 	 */
1104 	if (unlikely(tsk->flags & PF_EXITING)) {
1105 		pr_alert("Fixing recursive fault but reboot is needed!\n");
1106 		futex_exit_recursive(tsk);
1107 		tsk->exit_state = EXIT_DEAD;
1108 		refcount_inc(&tsk->rcu_users);
1109 		preempt_disable();
1110 		do_task_dead();
1111 	}
1112 
1113 	do_exit(signr);
1114 }
1115 
SYSCALL_DEFINE1(exit,int,error_code)1116 SYSCALL_DEFINE1(exit, int, error_code)
1117 {
1118 	do_exit((error_code & 0xff) << 8);
1119 }
1120 
1121 /*
1122  * Take down every thread in the group.  This is called by fatal signals
1123  * as well as by sys_exit_group (below).
1124  */
1125 void __noreturn
do_group_exit(int exit_code)1126 do_group_exit(int exit_code)
1127 {
1128 	struct signal_struct *sig = current->signal;
1129 
1130 	if (sig->flags & SIGNAL_GROUP_EXIT)
1131 		exit_code = sig->group_exit_code;
1132 	else if (sig->group_exec_task)
1133 		exit_code = 0;
1134 	else {
1135 		struct sighand_struct *const sighand = current->sighand;
1136 
1137 		spin_lock_irq(&sighand->siglock);
1138 		if (sig->flags & SIGNAL_GROUP_EXIT)
1139 			/* Another thread got here before we took the lock.  */
1140 			exit_code = sig->group_exit_code;
1141 		else if (sig->group_exec_task)
1142 			exit_code = 0;
1143 		else {
1144 			sig->group_exit_code = exit_code;
1145 			sig->flags = SIGNAL_GROUP_EXIT;
1146 			zap_other_threads(current);
1147 		}
1148 		spin_unlock_irq(&sighand->siglock);
1149 	}
1150 
1151 	do_exit(exit_code);
1152 	/* NOTREACHED */
1153 }
1154 
1155 /*
1156  * this kills every thread in the thread group. Note that any externally
1157  * wait4()-ing process will get the correct exit code - even if this
1158  * thread is not the thread group leader.
1159  */
SYSCALL_DEFINE1(exit_group,int,error_code)1160 SYSCALL_DEFINE1(exit_group, int, error_code)
1161 {
1162 	do_group_exit((error_code & 0xff) << 8);
1163 	/* NOTREACHED */
1164 	return 0;
1165 }
1166 
eligible_pid(struct wait_opts * wo,struct task_struct * p)1167 static int eligible_pid(struct wait_opts *wo, struct task_struct *p)
1168 {
1169 	return	wo->wo_type == PIDTYPE_MAX ||
1170 		task_pid_type(p, wo->wo_type) == wo->wo_pid;
1171 }
1172 
1173 static int
eligible_child(struct wait_opts * wo,bool ptrace,struct task_struct * p)1174 eligible_child(struct wait_opts *wo, bool ptrace, struct task_struct *p)
1175 {
1176 	if (!eligible_pid(wo, p))
1177 		return 0;
1178 
1179 	/*
1180 	 * Wait for all children (clone and not) if __WALL is set or
1181 	 * if it is traced by us.
1182 	 */
1183 	if (ptrace || (wo->wo_flags & __WALL))
1184 		return 1;
1185 
1186 	/*
1187 	 * Otherwise, wait for clone children *only* if __WCLONE is set;
1188 	 * otherwise, wait for non-clone children *only*.
1189 	 *
1190 	 * Note: a "clone" child here is one that reports to its parent
1191 	 * using a signal other than SIGCHLD, or a non-leader thread which
1192 	 * we can only see if it is traced by us.
1193 	 */
1194 	if ((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE))
1195 		return 0;
1196 
1197 	return 1;
1198 }
1199 
1200 /*
1201  * Handle sys_wait4 work for one task in state EXIT_ZOMBIE.  We hold
1202  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1203  * the lock and this task is uninteresting.  If we return nonzero, we have
1204  * released the lock and the system call should return.
1205  */
wait_task_zombie(struct wait_opts * wo,struct task_struct * p)1206 static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p)
1207 {
1208 	int state, status;
1209 	pid_t pid = task_pid_vnr(p);
1210 	uid_t uid = from_kuid_munged(current_user_ns(), task_uid(p));
1211 	struct waitid_info *infop;
1212 
1213 	if (!likely(wo->wo_flags & WEXITED))
1214 		return 0;
1215 
1216 	if (unlikely(wo->wo_flags & WNOWAIT)) {
1217 		status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1218 			? p->signal->group_exit_code : p->exit_code;
1219 		get_task_struct(p);
1220 		read_unlock(&tasklist_lock);
1221 		sched_annotate_sleep();
1222 		if (wo->wo_rusage)
1223 			getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1224 		put_task_struct(p);
1225 		goto out_info;
1226 	}
1227 	/*
1228 	 * Move the task's state to DEAD/TRACE, only one thread can do this.
1229 	 */
1230 	state = (ptrace_reparented(p) && thread_group_leader(p)) ?
1231 		EXIT_TRACE : EXIT_DEAD;
1232 	if (cmpxchg(&p->exit_state, EXIT_ZOMBIE, state) != EXIT_ZOMBIE)
1233 		return 0;
1234 	/*
1235 	 * We own this thread, nobody else can reap it.
1236 	 */
1237 	read_unlock(&tasklist_lock);
1238 	sched_annotate_sleep();
1239 
1240 	/*
1241 	 * Check thread_group_leader() to exclude the traced sub-threads.
1242 	 */
1243 	if (state == EXIT_DEAD && thread_group_leader(p)) {
1244 		struct signal_struct *sig = p->signal;
1245 		struct signal_struct *psig = current->signal;
1246 		unsigned long maxrss;
1247 		u64 tgutime, tgstime;
1248 
1249 		/*
1250 		 * The resource counters for the group leader are in its
1251 		 * own task_struct.  Those for dead threads in the group
1252 		 * are in its signal_struct, as are those for the child
1253 		 * processes it has previously reaped.  All these
1254 		 * accumulate in the parent's signal_struct c* fields.
1255 		 *
1256 		 * We don't bother to take a lock here to protect these
1257 		 * p->signal fields because the whole thread group is dead
1258 		 * and nobody can change them.
1259 		 *
1260 		 * psig->stats_lock also protects us from our sub-threads
1261 		 * which can reap other children at the same time.
1262 		 *
1263 		 * We use thread_group_cputime_adjusted() to get times for
1264 		 * the thread group, which consolidates times for all threads
1265 		 * in the group including the group leader.
1266 		 */
1267 		thread_group_cputime_adjusted(p, &tgutime, &tgstime);
1268 		write_seqlock_irq(&psig->stats_lock);
1269 		psig->cutime += tgutime + sig->cutime;
1270 		psig->cstime += tgstime + sig->cstime;
1271 		psig->cgtime += task_gtime(p) + sig->gtime + sig->cgtime;
1272 		psig->cmin_flt +=
1273 			p->min_flt + sig->min_flt + sig->cmin_flt;
1274 		psig->cmaj_flt +=
1275 			p->maj_flt + sig->maj_flt + sig->cmaj_flt;
1276 		psig->cnvcsw +=
1277 			p->nvcsw + sig->nvcsw + sig->cnvcsw;
1278 		psig->cnivcsw +=
1279 			p->nivcsw + sig->nivcsw + sig->cnivcsw;
1280 		psig->cinblock +=
1281 			task_io_get_inblock(p) +
1282 			sig->inblock + sig->cinblock;
1283 		psig->coublock +=
1284 			task_io_get_oublock(p) +
1285 			sig->oublock + sig->coublock;
1286 		maxrss = max(sig->maxrss, sig->cmaxrss);
1287 		if (psig->cmaxrss < maxrss)
1288 			psig->cmaxrss = maxrss;
1289 		task_io_accounting_add(&psig->ioac, &p->ioac);
1290 		task_io_accounting_add(&psig->ioac, &sig->ioac);
1291 		write_sequnlock_irq(&psig->stats_lock);
1292 	}
1293 
1294 	if (wo->wo_rusage)
1295 		getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1296 	status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1297 		? p->signal->group_exit_code : p->exit_code;
1298 	wo->wo_stat = status;
1299 
1300 	if (state == EXIT_TRACE) {
1301 		write_lock_irq(&tasklist_lock);
1302 		/* We dropped tasklist, ptracer could die and untrace */
1303 		ptrace_unlink(p);
1304 
1305 		/* If parent wants a zombie, don't release it now */
1306 		state = EXIT_ZOMBIE;
1307 		if (do_notify_parent(p, p->exit_signal))
1308 			state = EXIT_DEAD;
1309 		p->exit_state = state;
1310 		write_unlock_irq(&tasklist_lock);
1311 	}
1312 	if (state == EXIT_DEAD)
1313 		release_task(p);
1314 
1315 out_info:
1316 	infop = wo->wo_info;
1317 	if (infop) {
1318 		if ((status & 0x7f) == 0) {
1319 			infop->cause = CLD_EXITED;
1320 			infop->status = status >> 8;
1321 		} else {
1322 			infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
1323 			infop->status = status & 0x7f;
1324 		}
1325 		infop->pid = pid;
1326 		infop->uid = uid;
1327 	}
1328 
1329 	return pid;
1330 }
1331 
task_stopped_code(struct task_struct * p,bool ptrace)1332 static int *task_stopped_code(struct task_struct *p, bool ptrace)
1333 {
1334 	if (ptrace) {
1335 		if (task_is_traced(p) && !(p->jobctl & JOBCTL_LISTENING))
1336 			return &p->exit_code;
1337 	} else {
1338 		if (p->signal->flags & SIGNAL_STOP_STOPPED)
1339 			return &p->signal->group_exit_code;
1340 	}
1341 	return NULL;
1342 }
1343 
1344 /**
1345  * wait_task_stopped - Wait for %TASK_STOPPED or %TASK_TRACED
1346  * @wo: wait options
1347  * @ptrace: is the wait for ptrace
1348  * @p: task to wait for
1349  *
1350  * Handle sys_wait4() work for %p in state %TASK_STOPPED or %TASK_TRACED.
1351  *
1352  * CONTEXT:
1353  * read_lock(&tasklist_lock), which is released if return value is
1354  * non-zero.  Also, grabs and releases @p->sighand->siglock.
1355  *
1356  * RETURNS:
1357  * 0 if wait condition didn't exist and search for other wait conditions
1358  * should continue.  Non-zero return, -errno on failure and @p's pid on
1359  * success, implies that tasklist_lock is released and wait condition
1360  * search should terminate.
1361  */
wait_task_stopped(struct wait_opts * wo,int ptrace,struct task_struct * p)1362 static int wait_task_stopped(struct wait_opts *wo,
1363 				int ptrace, struct task_struct *p)
1364 {
1365 	struct waitid_info *infop;
1366 	int exit_code, *p_code, why;
1367 	uid_t uid = 0; /* unneeded, required by compiler */
1368 	pid_t pid;
1369 
1370 	/*
1371 	 * Traditionally we see ptrace'd stopped tasks regardless of options.
1372 	 */
1373 	if (!ptrace && !(wo->wo_flags & WUNTRACED))
1374 		return 0;
1375 
1376 	if (!task_stopped_code(p, ptrace))
1377 		return 0;
1378 
1379 	exit_code = 0;
1380 	spin_lock_irq(&p->sighand->siglock);
1381 
1382 	p_code = task_stopped_code(p, ptrace);
1383 	if (unlikely(!p_code))
1384 		goto unlock_sig;
1385 
1386 	exit_code = *p_code;
1387 	if (!exit_code)
1388 		goto unlock_sig;
1389 
1390 	if (!unlikely(wo->wo_flags & WNOWAIT))
1391 		*p_code = 0;
1392 
1393 	uid = from_kuid_munged(current_user_ns(), task_uid(p));
1394 unlock_sig:
1395 	spin_unlock_irq(&p->sighand->siglock);
1396 	if (!exit_code)
1397 		return 0;
1398 
1399 	/*
1400 	 * Now we are pretty sure this task is interesting.
1401 	 * Make sure it doesn't get reaped out from under us while we
1402 	 * give up the lock and then examine it below.  We don't want to
1403 	 * keep holding onto the tasklist_lock while we call getrusage and
1404 	 * possibly take page faults for user memory.
1405 	 */
1406 	get_task_struct(p);
1407 	pid = task_pid_vnr(p);
1408 	why = ptrace ? CLD_TRAPPED : CLD_STOPPED;
1409 	read_unlock(&tasklist_lock);
1410 	sched_annotate_sleep();
1411 	if (wo->wo_rusage)
1412 		getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1413 	put_task_struct(p);
1414 
1415 	if (likely(!(wo->wo_flags & WNOWAIT)))
1416 		wo->wo_stat = (exit_code << 8) | 0x7f;
1417 
1418 	infop = wo->wo_info;
1419 	if (infop) {
1420 		infop->cause = why;
1421 		infop->status = exit_code;
1422 		infop->pid = pid;
1423 		infop->uid = uid;
1424 	}
1425 	return pid;
1426 }
1427 
1428 /*
1429  * Handle do_wait work for one task in a live, non-stopped state.
1430  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1431  * the lock and this task is uninteresting.  If we return nonzero, we have
1432  * released the lock and the system call should return.
1433  */
wait_task_continued(struct wait_opts * wo,struct task_struct * p)1434 static int wait_task_continued(struct wait_opts *wo, struct task_struct *p)
1435 {
1436 	struct waitid_info *infop;
1437 	pid_t pid;
1438 	uid_t uid;
1439 
1440 	if (!unlikely(wo->wo_flags & WCONTINUED))
1441 		return 0;
1442 
1443 	if (!(p->signal->flags & SIGNAL_STOP_CONTINUED))
1444 		return 0;
1445 
1446 	spin_lock_irq(&p->sighand->siglock);
1447 	/* Re-check with the lock held.  */
1448 	if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) {
1449 		spin_unlock_irq(&p->sighand->siglock);
1450 		return 0;
1451 	}
1452 	if (!unlikely(wo->wo_flags & WNOWAIT))
1453 		p->signal->flags &= ~SIGNAL_STOP_CONTINUED;
1454 	uid = from_kuid_munged(current_user_ns(), task_uid(p));
1455 	spin_unlock_irq(&p->sighand->siglock);
1456 
1457 	pid = task_pid_vnr(p);
1458 	get_task_struct(p);
1459 	read_unlock(&tasklist_lock);
1460 	sched_annotate_sleep();
1461 	if (wo->wo_rusage)
1462 		getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1463 	put_task_struct(p);
1464 
1465 	infop = wo->wo_info;
1466 	if (!infop) {
1467 		wo->wo_stat = 0xffff;
1468 	} else {
1469 		infop->cause = CLD_CONTINUED;
1470 		infop->pid = pid;
1471 		infop->uid = uid;
1472 		infop->status = SIGCONT;
1473 	}
1474 	return pid;
1475 }
1476 
1477 /*
1478  * Consider @p for a wait by @parent.
1479  *
1480  * -ECHILD should be in ->notask_error before the first call.
1481  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1482  * Returns zero if the search for a child should continue;
1483  * then ->notask_error is 0 if @p is an eligible child,
1484  * or still -ECHILD.
1485  */
wait_consider_task(struct wait_opts * wo,int ptrace,struct task_struct * p)1486 static int wait_consider_task(struct wait_opts *wo, int ptrace,
1487 				struct task_struct *p)
1488 {
1489 	/*
1490 	 * We can race with wait_task_zombie() from another thread.
1491 	 * Ensure that EXIT_ZOMBIE -> EXIT_DEAD/EXIT_TRACE transition
1492 	 * can't confuse the checks below.
1493 	 */
1494 	int exit_state = READ_ONCE(p->exit_state);
1495 	int ret;
1496 
1497 	if (unlikely(exit_state == EXIT_DEAD))
1498 		return 0;
1499 
1500 	ret = eligible_child(wo, ptrace, p);
1501 	if (!ret)
1502 		return ret;
1503 
1504 	if (unlikely(exit_state == EXIT_TRACE)) {
1505 		/*
1506 		 * ptrace == 0 means we are the natural parent. In this case
1507 		 * we should clear notask_error, debugger will notify us.
1508 		 */
1509 		if (likely(!ptrace))
1510 			wo->notask_error = 0;
1511 		return 0;
1512 	}
1513 
1514 	if (likely(!ptrace) && unlikely(p->ptrace)) {
1515 		/*
1516 		 * If it is traced by its real parent's group, just pretend
1517 		 * the caller is ptrace_do_wait() and reap this child if it
1518 		 * is zombie.
1519 		 *
1520 		 * This also hides group stop state from real parent; otherwise
1521 		 * a single stop can be reported twice as group and ptrace stop.
1522 		 * If a ptracer wants to distinguish these two events for its
1523 		 * own children it should create a separate process which takes
1524 		 * the role of real parent.
1525 		 */
1526 		if (!ptrace_reparented(p))
1527 			ptrace = 1;
1528 	}
1529 
1530 	/* slay zombie? */
1531 	if (exit_state == EXIT_ZOMBIE) {
1532 		/* we don't reap group leaders with subthreads */
1533 		if (!delay_group_leader(p)) {
1534 			/*
1535 			 * A zombie ptracee is only visible to its ptracer.
1536 			 * Notification and reaping will be cascaded to the
1537 			 * real parent when the ptracer detaches.
1538 			 */
1539 			if (unlikely(ptrace) || likely(!p->ptrace))
1540 				return wait_task_zombie(wo, p);
1541 		}
1542 
1543 		/*
1544 		 * Allow access to stopped/continued state via zombie by
1545 		 * falling through.  Clearing of notask_error is complex.
1546 		 *
1547 		 * When !@ptrace:
1548 		 *
1549 		 * If WEXITED is set, notask_error should naturally be
1550 		 * cleared.  If not, subset of WSTOPPED|WCONTINUED is set,
1551 		 * so, if there are live subthreads, there are events to
1552 		 * wait for.  If all subthreads are dead, it's still safe
1553 		 * to clear - this function will be called again in finite
1554 		 * amount time once all the subthreads are released and
1555 		 * will then return without clearing.
1556 		 *
1557 		 * When @ptrace:
1558 		 *
1559 		 * Stopped state is per-task and thus can't change once the
1560 		 * target task dies.  Only continued and exited can happen.
1561 		 * Clear notask_error if WCONTINUED | WEXITED.
1562 		 */
1563 		if (likely(!ptrace) || (wo->wo_flags & (WCONTINUED | WEXITED)))
1564 			wo->notask_error = 0;
1565 	} else {
1566 		/*
1567 		 * @p is alive and it's gonna stop, continue or exit, so
1568 		 * there always is something to wait for.
1569 		 */
1570 		wo->notask_error = 0;
1571 	}
1572 
1573 	/*
1574 	 * Wait for stopped.  Depending on @ptrace, different stopped state
1575 	 * is used and the two don't interact with each other.
1576 	 */
1577 	ret = wait_task_stopped(wo, ptrace, p);
1578 	if (ret)
1579 		return ret;
1580 
1581 	/*
1582 	 * Wait for continued.  There's only one continued state and the
1583 	 * ptracer can consume it which can confuse the real parent.  Don't
1584 	 * use WCONTINUED from ptracer.  You don't need or want it.
1585 	 */
1586 	return wait_task_continued(wo, p);
1587 }
1588 
1589 /*
1590  * Do the work of do_wait() for one thread in the group, @tsk.
1591  *
1592  * -ECHILD should be in ->notask_error before the first call.
1593  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1594  * Returns zero if the search for a child should continue; then
1595  * ->notask_error is 0 if there were any eligible children,
1596  * or still -ECHILD.
1597  */
do_wait_thread(struct wait_opts * wo,struct task_struct * tsk)1598 static int do_wait_thread(struct wait_opts *wo, struct task_struct *tsk)
1599 {
1600 	struct task_struct *p;
1601 
1602 	list_for_each_entry(p, &tsk->children, sibling) {
1603 		int ret = wait_consider_task(wo, 0, p);
1604 
1605 		if (ret)
1606 			return ret;
1607 	}
1608 
1609 	return 0;
1610 }
1611 
ptrace_do_wait(struct wait_opts * wo,struct task_struct * tsk)1612 static int ptrace_do_wait(struct wait_opts *wo, struct task_struct *tsk)
1613 {
1614 	struct task_struct *p;
1615 
1616 	list_for_each_entry(p, &tsk->ptraced, ptrace_entry) {
1617 		int ret = wait_consider_task(wo, 1, p);
1618 
1619 		if (ret)
1620 			return ret;
1621 	}
1622 
1623 	return 0;
1624 }
1625 
pid_child_should_wake(struct wait_opts * wo,struct task_struct * p)1626 bool pid_child_should_wake(struct wait_opts *wo, struct task_struct *p)
1627 {
1628 	if (!eligible_pid(wo, p))
1629 		return false;
1630 
1631 	if ((wo->wo_flags & __WNOTHREAD) && wo->child_wait.private != p->parent)
1632 		return false;
1633 
1634 	return true;
1635 }
1636 
child_wait_callback(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)1637 static int child_wait_callback(wait_queue_entry_t *wait, unsigned mode,
1638 				int sync, void *key)
1639 {
1640 	struct wait_opts *wo = container_of(wait, struct wait_opts,
1641 						child_wait);
1642 	struct task_struct *p = key;
1643 
1644 	if (pid_child_should_wake(wo, p))
1645 		return default_wake_function(wait, mode, sync, key);
1646 
1647 	return 0;
1648 }
1649 
__wake_up_parent(struct task_struct * p,struct task_struct * parent)1650 void __wake_up_parent(struct task_struct *p, struct task_struct *parent)
1651 {
1652 	__wake_up_sync_key(&parent->signal->wait_chldexit,
1653 			   TASK_INTERRUPTIBLE, p);
1654 }
1655 
is_effectively_child(struct wait_opts * wo,bool ptrace,struct task_struct * target)1656 static bool is_effectively_child(struct wait_opts *wo, bool ptrace,
1657 				 struct task_struct *target)
1658 {
1659 	struct task_struct *parent =
1660 		!ptrace ? target->real_parent : target->parent;
1661 
1662 	return current == parent || (!(wo->wo_flags & __WNOTHREAD) &&
1663 				     same_thread_group(current, parent));
1664 }
1665 
1666 /*
1667  * Optimization for waiting on PIDTYPE_PID. No need to iterate through child
1668  * and tracee lists to find the target task.
1669  */
do_wait_pid(struct wait_opts * wo)1670 static int do_wait_pid(struct wait_opts *wo)
1671 {
1672 	bool ptrace;
1673 	struct task_struct *target;
1674 	int retval;
1675 
1676 	ptrace = false;
1677 	target = pid_task(wo->wo_pid, PIDTYPE_TGID);
1678 	if (target && is_effectively_child(wo, ptrace, target)) {
1679 		retval = wait_consider_task(wo, ptrace, target);
1680 		if (retval)
1681 			return retval;
1682 	}
1683 
1684 	ptrace = true;
1685 	target = pid_task(wo->wo_pid, PIDTYPE_PID);
1686 	if (target && target->ptrace &&
1687 	    is_effectively_child(wo, ptrace, target)) {
1688 		retval = wait_consider_task(wo, ptrace, target);
1689 		if (retval)
1690 			return retval;
1691 	}
1692 
1693 	return 0;
1694 }
1695 
__do_wait(struct wait_opts * wo)1696 long __do_wait(struct wait_opts *wo)
1697 {
1698 	long retval;
1699 
1700 	/*
1701 	 * If there is nothing that can match our criteria, just get out.
1702 	 * We will clear ->notask_error to zero if we see any child that
1703 	 * might later match our criteria, even if we are not able to reap
1704 	 * it yet.
1705 	 */
1706 	wo->notask_error = -ECHILD;
1707 	if ((wo->wo_type < PIDTYPE_MAX) &&
1708 	   (!wo->wo_pid || !pid_has_task(wo->wo_pid, wo->wo_type)))
1709 		goto notask;
1710 
1711 	read_lock(&tasklist_lock);
1712 
1713 	if (wo->wo_type == PIDTYPE_PID) {
1714 		retval = do_wait_pid(wo);
1715 		if (retval)
1716 			return retval;
1717 	} else {
1718 		struct task_struct *tsk = current;
1719 
1720 		do {
1721 			retval = do_wait_thread(wo, tsk);
1722 			if (retval)
1723 				return retval;
1724 
1725 			retval = ptrace_do_wait(wo, tsk);
1726 			if (retval)
1727 				return retval;
1728 
1729 			if (wo->wo_flags & __WNOTHREAD)
1730 				break;
1731 		} while_each_thread(current, tsk);
1732 	}
1733 	read_unlock(&tasklist_lock);
1734 
1735 notask:
1736 	retval = wo->notask_error;
1737 	if (!retval && !(wo->wo_flags & WNOHANG))
1738 		return -ERESTARTSYS;
1739 
1740 	return retval;
1741 }
1742 
do_wait(struct wait_opts * wo)1743 static long do_wait(struct wait_opts *wo)
1744 {
1745 	int retval;
1746 
1747 	trace_sched_process_wait(wo->wo_pid);
1748 
1749 	init_waitqueue_func_entry(&wo->child_wait, child_wait_callback);
1750 	wo->child_wait.private = current;
1751 	add_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1752 
1753 	do {
1754 		set_current_state(TASK_INTERRUPTIBLE);
1755 		retval = __do_wait(wo);
1756 		if (retval != -ERESTARTSYS)
1757 			break;
1758 		if (signal_pending(current))
1759 			break;
1760 		schedule();
1761 	} while (1);
1762 
1763 	__set_current_state(TASK_RUNNING);
1764 	remove_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1765 	return retval;
1766 }
1767 
kernel_waitid_prepare(struct wait_opts * wo,int which,pid_t upid,struct waitid_info * infop,int options,struct rusage * ru)1768 int kernel_waitid_prepare(struct wait_opts *wo, int which, pid_t upid,
1769 			  struct waitid_info *infop, int options,
1770 			  struct rusage *ru)
1771 {
1772 	unsigned int f_flags = 0;
1773 	struct pid *pid = NULL;
1774 	enum pid_type type;
1775 
1776 	if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED|
1777 			__WNOTHREAD|__WCLONE|__WALL))
1778 		return -EINVAL;
1779 	if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
1780 		return -EINVAL;
1781 
1782 	switch (which) {
1783 	case P_ALL:
1784 		type = PIDTYPE_MAX;
1785 		break;
1786 	case P_PID:
1787 		type = PIDTYPE_PID;
1788 		if (upid <= 0)
1789 			return -EINVAL;
1790 
1791 		pid = find_get_pid(upid);
1792 		break;
1793 	case P_PGID:
1794 		type = PIDTYPE_PGID;
1795 		if (upid < 0)
1796 			return -EINVAL;
1797 
1798 		if (upid)
1799 			pid = find_get_pid(upid);
1800 		else
1801 			pid = get_task_pid(current, PIDTYPE_PGID);
1802 		break;
1803 	case P_PIDFD:
1804 		type = PIDTYPE_PID;
1805 		if (upid < 0)
1806 			return -EINVAL;
1807 
1808 		pid = pidfd_get_pid(upid, &f_flags);
1809 		if (IS_ERR(pid))
1810 			return PTR_ERR(pid);
1811 
1812 		break;
1813 	default:
1814 		return -EINVAL;
1815 	}
1816 
1817 	wo->wo_type	= type;
1818 	wo->wo_pid	= pid;
1819 	wo->wo_flags	= options;
1820 	wo->wo_info	= infop;
1821 	wo->wo_rusage	= ru;
1822 	if (f_flags & O_NONBLOCK)
1823 		wo->wo_flags |= WNOHANG;
1824 
1825 	return 0;
1826 }
1827 
kernel_waitid(int which,pid_t upid,struct waitid_info * infop,int options,struct rusage * ru)1828 static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
1829 			  int options, struct rusage *ru)
1830 {
1831 	struct wait_opts wo;
1832 	long ret;
1833 
1834 	ret = kernel_waitid_prepare(&wo, which, upid, infop, options, ru);
1835 	if (ret)
1836 		return ret;
1837 
1838 	ret = do_wait(&wo);
1839 	if (!ret && !(options & WNOHANG) && (wo.wo_flags & WNOHANG))
1840 		ret = -EAGAIN;
1841 
1842 	put_pid(wo.wo_pid);
1843 	return ret;
1844 }
1845 
SYSCALL_DEFINE5(waitid,int,which,pid_t,upid,struct siginfo __user *,infop,int,options,struct rusage __user *,ru)1846 SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
1847 		infop, int, options, struct rusage __user *, ru)
1848 {
1849 	struct rusage r;
1850 	struct waitid_info info = {.status = 0};
1851 	long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);
1852 	int signo = 0;
1853 
1854 	if (err > 0) {
1855 		signo = SIGCHLD;
1856 		err = 0;
1857 		if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1858 			return -EFAULT;
1859 	}
1860 	if (!infop)
1861 		return err;
1862 
1863 	if (!user_write_access_begin(infop, sizeof(*infop)))
1864 		return -EFAULT;
1865 
1866 	unsafe_put_user(signo, &infop->si_signo, Efault);
1867 	unsafe_put_user(0, &infop->si_errno, Efault);
1868 	unsafe_put_user(info.cause, &infop->si_code, Efault);
1869 	unsafe_put_user(info.pid, &infop->si_pid, Efault);
1870 	unsafe_put_user(info.uid, &infop->si_uid, Efault);
1871 	unsafe_put_user(info.status, &infop->si_status, Efault);
1872 	user_write_access_end();
1873 	return err;
1874 Efault:
1875 	user_write_access_end();
1876 	return -EFAULT;
1877 }
1878 
kernel_wait4(pid_t upid,int __user * stat_addr,int options,struct rusage * ru)1879 long kernel_wait4(pid_t upid, int __user *stat_addr, int options,
1880 		  struct rusage *ru)
1881 {
1882 	struct wait_opts wo;
1883 	struct pid *pid = NULL;
1884 	enum pid_type type;
1885 	long ret;
1886 
1887 	if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
1888 			__WNOTHREAD|__WCLONE|__WALL))
1889 		return -EINVAL;
1890 
1891 	/* -INT_MIN is not defined */
1892 	if (upid == INT_MIN)
1893 		return -ESRCH;
1894 
1895 	if (upid == -1)
1896 		type = PIDTYPE_MAX;
1897 	else if (upid < 0) {
1898 		type = PIDTYPE_PGID;
1899 		pid = find_get_pid(-upid);
1900 	} else if (upid == 0) {
1901 		type = PIDTYPE_PGID;
1902 		pid = get_task_pid(current, PIDTYPE_PGID);
1903 	} else /* upid > 0 */ {
1904 		type = PIDTYPE_PID;
1905 		pid = find_get_pid(upid);
1906 	}
1907 
1908 	wo.wo_type	= type;
1909 	wo.wo_pid	= pid;
1910 	wo.wo_flags	= options | WEXITED;
1911 	wo.wo_info	= NULL;
1912 	wo.wo_stat	= 0;
1913 	wo.wo_rusage	= ru;
1914 	ret = do_wait(&wo);
1915 	put_pid(pid);
1916 	if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
1917 		ret = -EFAULT;
1918 
1919 	return ret;
1920 }
1921 
kernel_wait(pid_t pid,int * stat)1922 int kernel_wait(pid_t pid, int *stat)
1923 {
1924 	struct wait_opts wo = {
1925 		.wo_type	= PIDTYPE_PID,
1926 		.wo_pid		= find_get_pid(pid),
1927 		.wo_flags	= WEXITED,
1928 	};
1929 	int ret;
1930 
1931 	ret = do_wait(&wo);
1932 	if (ret > 0 && wo.wo_stat)
1933 		*stat = wo.wo_stat;
1934 	put_pid(wo.wo_pid);
1935 	return ret;
1936 }
1937 
SYSCALL_DEFINE4(wait4,pid_t,upid,int __user *,stat_addr,int,options,struct rusage __user *,ru)1938 SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
1939 		int, options, struct rusage __user *, ru)
1940 {
1941 	struct rusage r;
1942 	long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL);
1943 
1944 	if (err > 0) {
1945 		if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1946 			return -EFAULT;
1947 	}
1948 	return err;
1949 }
1950 
1951 #ifdef __ARCH_WANT_SYS_WAITPID
1952 
1953 /*
1954  * sys_waitpid() remains for compatibility. waitpid() should be
1955  * implemented by calling sys_wait4() from libc.a.
1956  */
SYSCALL_DEFINE3(waitpid,pid_t,pid,int __user *,stat_addr,int,options)1957 SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options)
1958 {
1959 	return kernel_wait4(pid, stat_addr, options, NULL);
1960 }
1961 
1962 #endif
1963 
1964 #ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(wait4,compat_pid_t,pid,compat_uint_t __user *,stat_addr,int,options,struct compat_rusage __user *,ru)1965 COMPAT_SYSCALL_DEFINE4(wait4,
1966 	compat_pid_t, pid,
1967 	compat_uint_t __user *, stat_addr,
1968 	int, options,
1969 	struct compat_rusage __user *, ru)
1970 {
1971 	struct rusage r;
1972 	long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL);
1973 	if (err > 0) {
1974 		if (ru && put_compat_rusage(&r, ru))
1975 			return -EFAULT;
1976 	}
1977 	return err;
1978 }
1979 
COMPAT_SYSCALL_DEFINE5(waitid,int,which,compat_pid_t,pid,struct compat_siginfo __user *,infop,int,options,struct compat_rusage __user *,uru)1980 COMPAT_SYSCALL_DEFINE5(waitid,
1981 		int, which, compat_pid_t, pid,
1982 		struct compat_siginfo __user *, infop, int, options,
1983 		struct compat_rusage __user *, uru)
1984 {
1985 	struct rusage ru;
1986 	struct waitid_info info = {.status = 0};
1987 	long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
1988 	int signo = 0;
1989 	if (err > 0) {
1990 		signo = SIGCHLD;
1991 		err = 0;
1992 		if (uru) {
1993 			/* kernel_waitid() overwrites everything in ru */
1994 			if (COMPAT_USE_64BIT_TIME)
1995 				err = copy_to_user(uru, &ru, sizeof(ru));
1996 			else
1997 				err = put_compat_rusage(&ru, uru);
1998 			if (err)
1999 				return -EFAULT;
2000 		}
2001 	}
2002 
2003 	if (!infop)
2004 		return err;
2005 
2006 	if (!user_write_access_begin(infop, sizeof(*infop)))
2007 		return -EFAULT;
2008 
2009 	unsafe_put_user(signo, &infop->si_signo, Efault);
2010 	unsafe_put_user(0, &infop->si_errno, Efault);
2011 	unsafe_put_user(info.cause, &infop->si_code, Efault);
2012 	unsafe_put_user(info.pid, &infop->si_pid, Efault);
2013 	unsafe_put_user(info.uid, &infop->si_uid, Efault);
2014 	unsafe_put_user(info.status, &infop->si_status, Efault);
2015 	user_write_access_end();
2016 	return err;
2017 Efault:
2018 	user_write_access_end();
2019 	return -EFAULT;
2020 }
2021 #endif
2022 
2023 /*
2024  * This needs to be __function_aligned as GCC implicitly makes any
2025  * implementation of abort() cold and drops alignment specified by
2026  * -falign-functions=N.
2027  *
2028  * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88345#c11
2029  */
abort(void)2030 __weak __function_aligned void abort(void)
2031 {
2032 	BUG();
2033 
2034 	/* if that doesn't kill us, halt */
2035 	panic("Oops failed to kill thread");
2036 }
2037 EXPORT_SYMBOL(abort);
2038