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