xref: /linux/kernel/exit.c (revision 813b46808822db6838c43e92ba21ce013d23fcdc)
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/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 
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
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 
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 
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  */
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 	tsk->sighand = NULL;
215 	spin_unlock(&sighand->siglock);
216 
217 	__cleanup_sighand(sighand);
218 	if (group_dead)
219 		tty_kref_put(tty);
220 }
221 
222 static void delayed_put_task_struct(struct rcu_head *rhp)
223 {
224 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
225 
226 	kprobe_flush_task(tsk);
227 	rethook_flush_task(tsk);
228 	perf_event_delayed_put(tsk);
229 	trace_sched_process_free(tsk);
230 	put_task_struct(tsk);
231 }
232 
233 void put_task_struct_rcu_user(struct task_struct *task)
234 {
235 	if (refcount_dec_and_test(&task->rcu_users))
236 		call_rcu(&task->rcu, delayed_put_task_struct);
237 }
238 
239 void __weak release_thread(struct task_struct *dead_task)
240 {
241 }
242 
243 void release_task(struct task_struct *p)
244 {
245 	struct release_task_post post;
246 	struct task_struct *leader;
247 	struct pid *thread_pid;
248 	int zap_leader;
249 repeat:
250 	memset(&post, 0, sizeof(post));
251 
252 	/* don't need to get the RCU readlock here - the process is dead and
253 	 * can't be modifying its own credentials. But shut RCU-lockdep up */
254 	rcu_read_lock();
255 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
256 	rcu_read_unlock();
257 
258 	pidfs_exit(p);
259 	cgroup_release(p);
260 
261 	/* Retrieve @thread_pid before __unhash_process() may set it to NULL. */
262 	thread_pid = task_pid(p);
263 
264 	write_lock_irq(&tasklist_lock);
265 	ptrace_release_task(p);
266 	__exit_signal(&post, p);
267 
268 	/*
269 	 * If we are the last non-leader member of the thread
270 	 * group, and the leader is zombie, then notify the
271 	 * group leader's parent process. (if it wants notification.)
272 	 */
273 	zap_leader = 0;
274 	leader = p->group_leader;
275 	if (leader != p && thread_group_empty(leader)
276 			&& leader->exit_state == EXIT_ZOMBIE) {
277 		/* for pidfs_exit() and do_notify_parent() */
278 		if (leader->signal->flags & SIGNAL_GROUP_EXIT)
279 			leader->exit_code = leader->signal->group_exit_code;
280 		/*
281 		 * If we were the last child thread and the leader has
282 		 * exited already, and the leader's parent ignores SIGCHLD,
283 		 * then we are the one who should release the leader.
284 		 */
285 		zap_leader = do_notify_parent(leader, leader->exit_signal);
286 		if (zap_leader)
287 			leader->exit_state = EXIT_DEAD;
288 	}
289 
290 	write_unlock_irq(&tasklist_lock);
291 	/* @thread_pid can't go away until free_pids() below */
292 	proc_flush_pid(thread_pid);
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->mm = NULL;
575 	membarrier_update_current_mm(NULL);
576 	enter_lazy_tlb(mm, current);
577 	local_irq_enable();
578 	task_unlock(current);
579 	mmap_read_unlock(mm);
580 	mm_update_next_owner(mm);
581 	mmput(mm);
582 	if (test_thread_flag(TIF_MEMDIE))
583 		exit_oom_victim();
584 }
585 
586 static struct task_struct *find_alive_thread(struct task_struct *p)
587 {
588 	struct task_struct *t;
589 
590 	for_each_thread(p, t) {
591 		if (!(t->flags & PF_EXITING))
592 			return t;
593 	}
594 	return NULL;
595 }
596 
597 static struct task_struct *find_child_reaper(struct task_struct *father,
598 						struct list_head *dead)
599 	__releases(&tasklist_lock)
600 	__acquires(&tasklist_lock)
601 {
602 	struct pid_namespace *pid_ns = task_active_pid_ns(father);
603 	struct task_struct *reaper = pid_ns->child_reaper;
604 	struct task_struct *p, *n;
605 
606 	if (likely(reaper != father))
607 		return reaper;
608 
609 	reaper = find_alive_thread(father);
610 	if (reaper) {
611 		pid_ns->child_reaper = reaper;
612 		return reaper;
613 	}
614 
615 	write_unlock_irq(&tasklist_lock);
616 
617 	list_for_each_entry_safe(p, n, dead, ptrace_entry) {
618 		list_del_init(&p->ptrace_entry);
619 		release_task(p);
620 	}
621 
622 	zap_pid_ns_processes(pid_ns);
623 	write_lock_irq(&tasklist_lock);
624 
625 	return father;
626 }
627 
628 /*
629  * When we die, we re-parent all our children, and try to:
630  * 1. give them to another thread in our thread group, if such a member exists
631  * 2. give it to the first ancestor process which prctl'd itself as a
632  *    child_subreaper for its children (like a service manager)
633  * 3. give it to the init process (PID 1) in our pid namespace
634  */
635 static struct task_struct *find_new_reaper(struct task_struct *father,
636 					   struct task_struct *child_reaper)
637 {
638 	struct task_struct *thread, *reaper;
639 
640 	thread = find_alive_thread(father);
641 	if (thread)
642 		return thread;
643 
644 	if (father->signal->has_child_subreaper) {
645 		unsigned int ns_level = task_pid(father)->level;
646 		/*
647 		 * Find the first ->is_child_subreaper ancestor in our pid_ns.
648 		 * We can't check reaper != child_reaper to ensure we do not
649 		 * cross the namespaces, the exiting parent could be injected
650 		 * by setns() + fork().
651 		 * We check pid->level, this is slightly more efficient than
652 		 * task_active_pid_ns(reaper) != task_active_pid_ns(father).
653 		 */
654 		for (reaper = father->real_parent;
655 		     task_pid(reaper)->level == ns_level;
656 		     reaper = reaper->real_parent) {
657 			if (reaper == &init_task)
658 				break;
659 			if (!reaper->signal->is_child_subreaper)
660 				continue;
661 			thread = find_alive_thread(reaper);
662 			if (thread)
663 				return thread;
664 		}
665 	}
666 
667 	return child_reaper;
668 }
669 
670 /*
671 * Any that need to be release_task'd are put on the @dead list.
672  */
673 static void reparent_leader(struct task_struct *father, struct task_struct *p,
674 				struct list_head *dead)
675 {
676 	if (unlikely(p->exit_state == EXIT_DEAD))
677 		return;
678 
679 	/* We don't want people slaying init. */
680 	p->exit_signal = SIGCHLD;
681 
682 	/* If it has exited notify the new parent about this child's death. */
683 	if (!p->ptrace &&
684 	    p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) {
685 		if (do_notify_parent(p, p->exit_signal)) {
686 			p->exit_state = EXIT_DEAD;
687 			list_add(&p->ptrace_entry, dead);
688 		}
689 	}
690 
691 	kill_orphaned_pgrp(p, father);
692 }
693 
694 /*
695  * Make init inherit all the child processes
696  */
697 static void forget_original_parent(struct task_struct *father,
698 					struct list_head *dead)
699 {
700 	struct task_struct *p, *t, *reaper;
701 
702 	if (unlikely(!list_empty(&father->ptraced)))
703 		exit_ptrace(father, dead);
704 
705 	/* Can drop and reacquire tasklist_lock */
706 	reaper = find_child_reaper(father, dead);
707 	if (list_empty(&father->children))
708 		return;
709 
710 	reaper = find_new_reaper(father, reaper);
711 	list_for_each_entry(p, &father->children, sibling) {
712 		for_each_thread(p, t) {
713 			RCU_INIT_POINTER(t->real_parent, reaper);
714 			BUG_ON((!t->ptrace) != (rcu_access_pointer(t->parent) == father));
715 			if (likely(!t->ptrace))
716 				t->parent = t->real_parent;
717 			if (t->pdeath_signal)
718 				group_send_sig_info(t->pdeath_signal,
719 						    SEND_SIG_NOINFO, t,
720 						    PIDTYPE_TGID);
721 		}
722 		/*
723 		 * If this is a threaded reparent there is no need to
724 		 * notify anyone anything has happened.
725 		 */
726 		if (!same_thread_group(reaper, father))
727 			reparent_leader(father, p, dead);
728 	}
729 	list_splice_tail_init(&father->children, &reaper->children);
730 }
731 
732 /*
733  * Send signals to all our closest relatives so that they know
734  * to properly mourn us..
735  */
736 static void exit_notify(struct task_struct *tsk, int group_dead)
737 {
738 	bool autoreap;
739 	struct task_struct *p, *n;
740 	LIST_HEAD(dead);
741 
742 	write_lock_irq(&tasklist_lock);
743 	forget_original_parent(tsk, &dead);
744 
745 	if (group_dead)
746 		kill_orphaned_pgrp(tsk->group_leader, NULL);
747 
748 	tsk->exit_state = EXIT_ZOMBIE;
749 
750 	if (unlikely(tsk->ptrace)) {
751 		int sig = thread_group_leader(tsk) &&
752 				thread_group_empty(tsk) &&
753 				!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 unsigned long stack_not_used(struct task_struct *p)
783 {
784 	unsigned long *n = end_of_stack(p);
785 
786 	do {	/* Skip over canary */
787 # ifdef CONFIG_STACK_GROWSUP
788 		n--;
789 # else
790 		n++;
791 # endif
792 	} while (!*n);
793 
794 # ifdef CONFIG_STACK_GROWSUP
795 	return (unsigned long)end_of_stack(p) - (unsigned long)n;
796 # else
797 	return (unsigned long)n - (unsigned long)end_of_stack(p);
798 # endif
799 }
800 
801 /* Count the maximum pages reached in kernel stacks */
802 static inline void kstack_histogram(unsigned long used_stack)
803 {
804 #ifdef CONFIG_VM_EVENT_COUNTERS
805 	if (used_stack <= 1024)
806 		count_vm_event(KSTACK_1K);
807 #if THREAD_SIZE > 1024
808 	else if (used_stack <= 2048)
809 		count_vm_event(KSTACK_2K);
810 #endif
811 #if THREAD_SIZE > 2048
812 	else if (used_stack <= 4096)
813 		count_vm_event(KSTACK_4K);
814 #endif
815 #if THREAD_SIZE > 4096
816 	else if (used_stack <= 8192)
817 		count_vm_event(KSTACK_8K);
818 #endif
819 #if THREAD_SIZE > 8192
820 	else if (used_stack <= 16384)
821 		count_vm_event(KSTACK_16K);
822 #endif
823 #if THREAD_SIZE > 16384
824 	else if (used_stack <= 32768)
825 		count_vm_event(KSTACK_32K);
826 #endif
827 #if THREAD_SIZE > 32768
828 	else if (used_stack <= 65536)
829 		count_vm_event(KSTACK_64K);
830 #endif
831 #if THREAD_SIZE > 65536
832 	else
833 		count_vm_event(KSTACK_REST);
834 #endif
835 #endif /* CONFIG_VM_EVENT_COUNTERS */
836 }
837 
838 static void check_stack_usage(void)
839 {
840 	static DEFINE_SPINLOCK(low_water_lock);
841 	static int lowest_to_date = THREAD_SIZE;
842 	unsigned long free;
843 
844 	free = stack_not_used(current);
845 	kstack_histogram(THREAD_SIZE - free);
846 
847 	if (free >= lowest_to_date)
848 		return;
849 
850 	spin_lock(&low_water_lock);
851 	if (free < lowest_to_date) {
852 		pr_info("%s (%d) used greatest stack depth: %lu bytes left\n",
853 			current->comm, task_pid_nr(current), free);
854 		lowest_to_date = free;
855 	}
856 	spin_unlock(&low_water_lock);
857 }
858 #else
859 static inline void check_stack_usage(void) {}
860 #endif
861 
862 static void synchronize_group_exit(struct task_struct *tsk, long code)
863 {
864 	struct sighand_struct *sighand = tsk->sighand;
865 	struct signal_struct *signal = tsk->signal;
866 	struct core_state *core_state;
867 
868 	spin_lock_irq(&sighand->siglock);
869 	signal->quick_threads--;
870 	if ((signal->quick_threads == 0) &&
871 	    !(signal->flags & SIGNAL_GROUP_EXIT)) {
872 		signal->flags = SIGNAL_GROUP_EXIT;
873 		signal->group_exit_code = code;
874 		signal->group_stop_count = 0;
875 	}
876 	/*
877 	 * Serialize with any possible pending coredump.
878 	 * We must hold siglock around checking core_state
879 	 * and setting PF_POSTCOREDUMP.  The core-inducing thread
880 	 * will increment ->nr_threads for each thread in the
881 	 * group without PF_POSTCOREDUMP set.
882 	 */
883 	tsk->flags |= PF_POSTCOREDUMP;
884 	core_state = signal->core_state;
885 	spin_unlock_irq(&sighand->siglock);
886 
887 	if (unlikely(core_state))
888 		coredump_task_exit(tsk, core_state);
889 }
890 
891 void __noreturn do_exit(long code)
892 {
893 	struct task_struct *tsk = current;
894 	int group_dead;
895 
896 	WARN_ON(irqs_disabled());
897 	WARN_ON(tsk->plug);
898 
899 	kcov_task_exit(tsk);
900 	kmsan_task_exit(tsk);
901 
902 	synchronize_group_exit(tsk, code);
903 	ptrace_event(PTRACE_EVENT_EXIT, code);
904 	user_events_exit(tsk);
905 
906 	io_uring_files_cancel();
907 	exit_signals(tsk);  /* sets PF_EXITING */
908 
909 	seccomp_filter_release(tsk);
910 
911 	acct_update_integrals(tsk);
912 	group_dead = atomic_dec_and_test(&tsk->signal->live);
913 	if (group_dead) {
914 		/*
915 		 * If the last thread of global init has exited, panic
916 		 * immediately to get a useable coredump.
917 		 */
918 		if (unlikely(is_global_init(tsk)))
919 			panic("Attempted to kill init! exitcode=0x%08x\n",
920 				tsk->signal->group_exit_code ?: (int)code);
921 
922 #ifdef CONFIG_POSIX_TIMERS
923 		hrtimer_cancel(&tsk->signal->real_timer);
924 		exit_itimers(tsk);
925 #endif
926 		if (tsk->mm)
927 			setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
928 	}
929 	acct_collect(code, group_dead);
930 	if (group_dead)
931 		tty_audit_exit();
932 	audit_free(tsk);
933 
934 	tsk->exit_code = code;
935 	taskstats_exit(tsk, group_dead);
936 	trace_sched_process_exit(tsk, group_dead);
937 
938 	/*
939 	 * Since sampling can touch ->mm, make sure to stop everything before we
940 	 * tear it down.
941 	 *
942 	 * Also flushes inherited counters to the parent - before the parent
943 	 * gets woken up by child-exit notifications.
944 	 */
945 	perf_event_exit_task(tsk);
946 
947 	exit_mm();
948 
949 	if (group_dead)
950 		acct_process();
951 
952 	exit_sem(tsk);
953 	exit_shm(tsk);
954 	exit_files(tsk);
955 	exit_fs(tsk);
956 	if (group_dead)
957 		disassociate_ctty(1);
958 	exit_task_namespaces(tsk);
959 	exit_task_work(tsk);
960 	exit_thread(tsk);
961 
962 	sched_autogroup_exit_task(tsk);
963 	cgroup_exit(tsk);
964 
965 	/*
966 	 * FIXME: do that only when needed, using sched_exit tracepoint
967 	 */
968 	flush_ptrace_hw_breakpoint(tsk);
969 
970 	exit_tasks_rcu_start();
971 	exit_notify(tsk, group_dead);
972 	proc_exit_connector(tsk);
973 	mpol_put_task_policy(tsk);
974 #ifdef CONFIG_FUTEX
975 	if (unlikely(current->pi_state_cache))
976 		kfree(current->pi_state_cache);
977 #endif
978 	/*
979 	 * Make sure we are holding no locks:
980 	 */
981 	debug_check_no_locks_held();
982 
983 	if (tsk->io_context)
984 		exit_io_context(tsk);
985 
986 	if (tsk->splice_pipe)
987 		free_pipe_info(tsk->splice_pipe);
988 
989 	if (tsk->task_frag.page)
990 		put_page(tsk->task_frag.page);
991 
992 	exit_task_stack_account(tsk);
993 
994 	check_stack_usage();
995 	preempt_disable();
996 	if (tsk->nr_dirtied)
997 		__this_cpu_add(dirty_throttle_leaks, tsk->nr_dirtied);
998 	exit_rcu();
999 	exit_tasks_rcu_finish();
1000 
1001 	lockdep_free_task(tsk);
1002 	do_task_dead();
1003 }
1004 
1005 void __noreturn make_task_dead(int signr)
1006 {
1007 	/*
1008 	 * Take the task off the cpu after something catastrophic has
1009 	 * happened.
1010 	 *
1011 	 * We can get here from a kernel oops, sometimes with preemption off.
1012 	 * Start by checking for critical errors.
1013 	 * Then fix up important state like USER_DS and preemption.
1014 	 * Then do everything else.
1015 	 */
1016 	struct task_struct *tsk = current;
1017 	unsigned int limit;
1018 
1019 	if (unlikely(in_interrupt()))
1020 		panic("Aiee, killing interrupt handler!");
1021 	if (unlikely(!tsk->pid))
1022 		panic("Attempted to kill the idle task!");
1023 
1024 	if (unlikely(irqs_disabled())) {
1025 		pr_info("note: %s[%d] exited with irqs disabled\n",
1026 			current->comm, task_pid_nr(current));
1027 		local_irq_enable();
1028 	}
1029 	if (unlikely(in_atomic())) {
1030 		pr_info("note: %s[%d] exited with preempt_count %d\n",
1031 			current->comm, task_pid_nr(current),
1032 			preempt_count());
1033 		preempt_count_set(PREEMPT_ENABLED);
1034 	}
1035 
1036 	/*
1037 	 * Every time the system oopses, if the oops happens while a reference
1038 	 * to an object was held, the reference leaks.
1039 	 * If the oops doesn't also leak memory, repeated oopsing can cause
1040 	 * reference counters to wrap around (if they're not using refcount_t).
1041 	 * This means that repeated oopsing can make unexploitable-looking bugs
1042 	 * exploitable through repeated oopsing.
1043 	 * To make sure this can't happen, place an upper bound on how often the
1044 	 * kernel may oops without panic().
1045 	 */
1046 	limit = READ_ONCE(oops_limit);
1047 	if (atomic_inc_return(&oops_count) >= limit && limit)
1048 		panic("Oopsed too often (kernel.oops_limit is %d)", limit);
1049 
1050 	/*
1051 	 * We're taking recursive faults here in make_task_dead. Safest is to just
1052 	 * leave this task alone and wait for reboot.
1053 	 */
1054 	if (unlikely(tsk->flags & PF_EXITING)) {
1055 		pr_alert("Fixing recursive fault but reboot is needed!\n");
1056 		futex_exit_recursive(tsk);
1057 		tsk->exit_state = EXIT_DEAD;
1058 		refcount_inc(&tsk->rcu_users);
1059 		do_task_dead();
1060 	}
1061 
1062 	do_exit(signr);
1063 }
1064 
1065 SYSCALL_DEFINE1(exit, int, error_code)
1066 {
1067 	do_exit((error_code&0xff)<<8);
1068 }
1069 
1070 /*
1071  * Take down every thread in the group.  This is called by fatal signals
1072  * as well as by sys_exit_group (below).
1073  */
1074 void __noreturn
1075 do_group_exit(int exit_code)
1076 {
1077 	struct signal_struct *sig = current->signal;
1078 
1079 	if (sig->flags & SIGNAL_GROUP_EXIT)
1080 		exit_code = sig->group_exit_code;
1081 	else if (sig->group_exec_task)
1082 		exit_code = 0;
1083 	else {
1084 		struct sighand_struct *const sighand = current->sighand;
1085 
1086 		spin_lock_irq(&sighand->siglock);
1087 		if (sig->flags & SIGNAL_GROUP_EXIT)
1088 			/* Another thread got here before we took the lock.  */
1089 			exit_code = sig->group_exit_code;
1090 		else if (sig->group_exec_task)
1091 			exit_code = 0;
1092 		else {
1093 			sig->group_exit_code = exit_code;
1094 			sig->flags = SIGNAL_GROUP_EXIT;
1095 			zap_other_threads(current);
1096 		}
1097 		spin_unlock_irq(&sighand->siglock);
1098 	}
1099 
1100 	do_exit(exit_code);
1101 	/* NOTREACHED */
1102 }
1103 
1104 /*
1105  * this kills every thread in the thread group. Note that any externally
1106  * wait4()-ing process will get the correct exit code - even if this
1107  * thread is not the thread group leader.
1108  */
1109 SYSCALL_DEFINE1(exit_group, int, error_code)
1110 {
1111 	do_group_exit((error_code & 0xff) << 8);
1112 	/* NOTREACHED */
1113 	return 0;
1114 }
1115 
1116 static int eligible_pid(struct wait_opts *wo, struct task_struct *p)
1117 {
1118 	return	wo->wo_type == PIDTYPE_MAX ||
1119 		task_pid_type(p, wo->wo_type) == wo->wo_pid;
1120 }
1121 
1122 static int
1123 eligible_child(struct wait_opts *wo, bool ptrace, struct task_struct *p)
1124 {
1125 	if (!eligible_pid(wo, p))
1126 		return 0;
1127 
1128 	/*
1129 	 * Wait for all children (clone and not) if __WALL is set or
1130 	 * if it is traced by us.
1131 	 */
1132 	if (ptrace || (wo->wo_flags & __WALL))
1133 		return 1;
1134 
1135 	/*
1136 	 * Otherwise, wait for clone children *only* if __WCLONE is set;
1137 	 * otherwise, wait for non-clone children *only*.
1138 	 *
1139 	 * Note: a "clone" child here is one that reports to its parent
1140 	 * using a signal other than SIGCHLD, or a non-leader thread which
1141 	 * we can only see if it is traced by us.
1142 	 */
1143 	if ((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE))
1144 		return 0;
1145 
1146 	return 1;
1147 }
1148 
1149 /*
1150  * Handle sys_wait4 work for one task in state EXIT_ZOMBIE.  We hold
1151  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1152  * the lock and this task is uninteresting.  If we return nonzero, we have
1153  * released the lock and the system call should return.
1154  */
1155 static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p)
1156 {
1157 	int state, status;
1158 	pid_t pid = task_pid_vnr(p);
1159 	uid_t uid = from_kuid_munged(current_user_ns(), task_uid(p));
1160 	struct waitid_info *infop;
1161 
1162 	if (!likely(wo->wo_flags & WEXITED))
1163 		return 0;
1164 
1165 	if (unlikely(wo->wo_flags & WNOWAIT)) {
1166 		status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1167 			? p->signal->group_exit_code : p->exit_code;
1168 		get_task_struct(p);
1169 		read_unlock(&tasklist_lock);
1170 		sched_annotate_sleep();
1171 		if (wo->wo_rusage)
1172 			getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1173 		put_task_struct(p);
1174 		goto out_info;
1175 	}
1176 	/*
1177 	 * Move the task's state to DEAD/TRACE, only one thread can do this.
1178 	 */
1179 	state = (ptrace_reparented(p) && thread_group_leader(p)) ?
1180 		EXIT_TRACE : EXIT_DEAD;
1181 	if (cmpxchg(&p->exit_state, EXIT_ZOMBIE, state) != EXIT_ZOMBIE)
1182 		return 0;
1183 	/*
1184 	 * We own this thread, nobody else can reap it.
1185 	 */
1186 	read_unlock(&tasklist_lock);
1187 	sched_annotate_sleep();
1188 
1189 	/*
1190 	 * Check thread_group_leader() to exclude the traced sub-threads.
1191 	 */
1192 	if (state == EXIT_DEAD && thread_group_leader(p)) {
1193 		struct signal_struct *sig = p->signal;
1194 		struct signal_struct *psig = current->signal;
1195 		unsigned long maxrss;
1196 		u64 tgutime, tgstime;
1197 
1198 		/*
1199 		 * The resource counters for the group leader are in its
1200 		 * own task_struct.  Those for dead threads in the group
1201 		 * are in its signal_struct, as are those for the child
1202 		 * processes it has previously reaped.  All these
1203 		 * accumulate in the parent's signal_struct c* fields.
1204 		 *
1205 		 * We don't bother to take a lock here to protect these
1206 		 * p->signal fields because the whole thread group is dead
1207 		 * and nobody can change them.
1208 		 *
1209 		 * psig->stats_lock also protects us from our sub-threads
1210 		 * which can reap other children at the same time.
1211 		 *
1212 		 * We use thread_group_cputime_adjusted() to get times for
1213 		 * the thread group, which consolidates times for all threads
1214 		 * in the group including the group leader.
1215 		 */
1216 		thread_group_cputime_adjusted(p, &tgutime, &tgstime);
1217 		write_seqlock_irq(&psig->stats_lock);
1218 		psig->cutime += tgutime + sig->cutime;
1219 		psig->cstime += tgstime + sig->cstime;
1220 		psig->cgtime += task_gtime(p) + sig->gtime + sig->cgtime;
1221 		psig->cmin_flt +=
1222 			p->min_flt + sig->min_flt + sig->cmin_flt;
1223 		psig->cmaj_flt +=
1224 			p->maj_flt + sig->maj_flt + sig->cmaj_flt;
1225 		psig->cnvcsw +=
1226 			p->nvcsw + sig->nvcsw + sig->cnvcsw;
1227 		psig->cnivcsw +=
1228 			p->nivcsw + sig->nivcsw + sig->cnivcsw;
1229 		psig->cinblock +=
1230 			task_io_get_inblock(p) +
1231 			sig->inblock + sig->cinblock;
1232 		psig->coublock +=
1233 			task_io_get_oublock(p) +
1234 			sig->oublock + sig->coublock;
1235 		maxrss = max(sig->maxrss, sig->cmaxrss);
1236 		if (psig->cmaxrss < maxrss)
1237 			psig->cmaxrss = maxrss;
1238 		task_io_accounting_add(&psig->ioac, &p->ioac);
1239 		task_io_accounting_add(&psig->ioac, &sig->ioac);
1240 		write_sequnlock_irq(&psig->stats_lock);
1241 	}
1242 
1243 	if (wo->wo_rusage)
1244 		getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1245 	status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1246 		? p->signal->group_exit_code : p->exit_code;
1247 	wo->wo_stat = status;
1248 
1249 	if (state == EXIT_TRACE) {
1250 		write_lock_irq(&tasklist_lock);
1251 		/* We dropped tasklist, ptracer could die and untrace */
1252 		ptrace_unlink(p);
1253 
1254 		/* If parent wants a zombie, don't release it now */
1255 		state = EXIT_ZOMBIE;
1256 		if (do_notify_parent(p, p->exit_signal))
1257 			state = EXIT_DEAD;
1258 		p->exit_state = state;
1259 		write_unlock_irq(&tasklist_lock);
1260 	}
1261 	if (state == EXIT_DEAD)
1262 		release_task(p);
1263 
1264 out_info:
1265 	infop = wo->wo_info;
1266 	if (infop) {
1267 		if ((status & 0x7f) == 0) {
1268 			infop->cause = CLD_EXITED;
1269 			infop->status = status >> 8;
1270 		} else {
1271 			infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
1272 			infop->status = status & 0x7f;
1273 		}
1274 		infop->pid = pid;
1275 		infop->uid = uid;
1276 	}
1277 
1278 	return pid;
1279 }
1280 
1281 static int *task_stopped_code(struct task_struct *p, bool ptrace)
1282 {
1283 	if (ptrace) {
1284 		if (task_is_traced(p) && !(p->jobctl & JOBCTL_LISTENING))
1285 			return &p->exit_code;
1286 	} else {
1287 		if (p->signal->flags & SIGNAL_STOP_STOPPED)
1288 			return &p->signal->group_exit_code;
1289 	}
1290 	return NULL;
1291 }
1292 
1293 /**
1294  * wait_task_stopped - Wait for %TASK_STOPPED or %TASK_TRACED
1295  * @wo: wait options
1296  * @ptrace: is the wait for ptrace
1297  * @p: task to wait for
1298  *
1299  * Handle sys_wait4() work for %p in state %TASK_STOPPED or %TASK_TRACED.
1300  *
1301  * CONTEXT:
1302  * read_lock(&tasklist_lock), which is released if return value is
1303  * non-zero.  Also, grabs and releases @p->sighand->siglock.
1304  *
1305  * RETURNS:
1306  * 0 if wait condition didn't exist and search for other wait conditions
1307  * should continue.  Non-zero return, -errno on failure and @p's pid on
1308  * success, implies that tasklist_lock is released and wait condition
1309  * search should terminate.
1310  */
1311 static int wait_task_stopped(struct wait_opts *wo,
1312 				int ptrace, struct task_struct *p)
1313 {
1314 	struct waitid_info *infop;
1315 	int exit_code, *p_code, why;
1316 	uid_t uid = 0; /* unneeded, required by compiler */
1317 	pid_t pid;
1318 
1319 	/*
1320 	 * Traditionally we see ptrace'd stopped tasks regardless of options.
1321 	 */
1322 	if (!ptrace && !(wo->wo_flags & WUNTRACED))
1323 		return 0;
1324 
1325 	if (!task_stopped_code(p, ptrace))
1326 		return 0;
1327 
1328 	exit_code = 0;
1329 	spin_lock_irq(&p->sighand->siglock);
1330 
1331 	p_code = task_stopped_code(p, ptrace);
1332 	if (unlikely(!p_code))
1333 		goto unlock_sig;
1334 
1335 	exit_code = *p_code;
1336 	if (!exit_code)
1337 		goto unlock_sig;
1338 
1339 	if (!unlikely(wo->wo_flags & WNOWAIT))
1340 		*p_code = 0;
1341 
1342 	uid = from_kuid_munged(current_user_ns(), task_uid(p));
1343 unlock_sig:
1344 	spin_unlock_irq(&p->sighand->siglock);
1345 	if (!exit_code)
1346 		return 0;
1347 
1348 	/*
1349 	 * Now we are pretty sure this task is interesting.
1350 	 * Make sure it doesn't get reaped out from under us while we
1351 	 * give up the lock and then examine it below.  We don't want to
1352 	 * keep holding onto the tasklist_lock while we call getrusage and
1353 	 * possibly take page faults for user memory.
1354 	 */
1355 	get_task_struct(p);
1356 	pid = task_pid_vnr(p);
1357 	why = ptrace ? CLD_TRAPPED : CLD_STOPPED;
1358 	read_unlock(&tasklist_lock);
1359 	sched_annotate_sleep();
1360 	if (wo->wo_rusage)
1361 		getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1362 	put_task_struct(p);
1363 
1364 	if (likely(!(wo->wo_flags & WNOWAIT)))
1365 		wo->wo_stat = (exit_code << 8) | 0x7f;
1366 
1367 	infop = wo->wo_info;
1368 	if (infop) {
1369 		infop->cause = why;
1370 		infop->status = exit_code;
1371 		infop->pid = pid;
1372 		infop->uid = uid;
1373 	}
1374 	return pid;
1375 }
1376 
1377 /*
1378  * Handle do_wait work for one task in a live, non-stopped state.
1379  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1380  * the lock and this task is uninteresting.  If we return nonzero, we have
1381  * released the lock and the system call should return.
1382  */
1383 static int wait_task_continued(struct wait_opts *wo, struct task_struct *p)
1384 {
1385 	struct waitid_info *infop;
1386 	pid_t pid;
1387 	uid_t uid;
1388 
1389 	if (!unlikely(wo->wo_flags & WCONTINUED))
1390 		return 0;
1391 
1392 	if (!(p->signal->flags & SIGNAL_STOP_CONTINUED))
1393 		return 0;
1394 
1395 	spin_lock_irq(&p->sighand->siglock);
1396 	/* Re-check with the lock held.  */
1397 	if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) {
1398 		spin_unlock_irq(&p->sighand->siglock);
1399 		return 0;
1400 	}
1401 	if (!unlikely(wo->wo_flags & WNOWAIT))
1402 		p->signal->flags &= ~SIGNAL_STOP_CONTINUED;
1403 	uid = from_kuid_munged(current_user_ns(), task_uid(p));
1404 	spin_unlock_irq(&p->sighand->siglock);
1405 
1406 	pid = task_pid_vnr(p);
1407 	get_task_struct(p);
1408 	read_unlock(&tasklist_lock);
1409 	sched_annotate_sleep();
1410 	if (wo->wo_rusage)
1411 		getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1412 	put_task_struct(p);
1413 
1414 	infop = wo->wo_info;
1415 	if (!infop) {
1416 		wo->wo_stat = 0xffff;
1417 	} else {
1418 		infop->cause = CLD_CONTINUED;
1419 		infop->pid = pid;
1420 		infop->uid = uid;
1421 		infop->status = SIGCONT;
1422 	}
1423 	return pid;
1424 }
1425 
1426 /*
1427  * Consider @p for a wait by @parent.
1428  *
1429  * -ECHILD should be in ->notask_error before the first call.
1430  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1431  * Returns zero if the search for a child should continue;
1432  * then ->notask_error is 0 if @p is an eligible child,
1433  * or still -ECHILD.
1434  */
1435 static int wait_consider_task(struct wait_opts *wo, int ptrace,
1436 				struct task_struct *p)
1437 {
1438 	/*
1439 	 * We can race with wait_task_zombie() from another thread.
1440 	 * Ensure that EXIT_ZOMBIE -> EXIT_DEAD/EXIT_TRACE transition
1441 	 * can't confuse the checks below.
1442 	 */
1443 	int exit_state = READ_ONCE(p->exit_state);
1444 	int ret;
1445 
1446 	if (unlikely(exit_state == EXIT_DEAD))
1447 		return 0;
1448 
1449 	ret = eligible_child(wo, ptrace, p);
1450 	if (!ret)
1451 		return ret;
1452 
1453 	if (unlikely(exit_state == EXIT_TRACE)) {
1454 		/*
1455 		 * ptrace == 0 means we are the natural parent. In this case
1456 		 * we should clear notask_error, debugger will notify us.
1457 		 */
1458 		if (likely(!ptrace))
1459 			wo->notask_error = 0;
1460 		return 0;
1461 	}
1462 
1463 	if (likely(!ptrace) && unlikely(p->ptrace)) {
1464 		/*
1465 		 * If it is traced by its real parent's group, just pretend
1466 		 * the caller is ptrace_do_wait() and reap this child if it
1467 		 * is zombie.
1468 		 *
1469 		 * This also hides group stop state from real parent; otherwise
1470 		 * a single stop can be reported twice as group and ptrace stop.
1471 		 * If a ptracer wants to distinguish these two events for its
1472 		 * own children it should create a separate process which takes
1473 		 * the role of real parent.
1474 		 */
1475 		if (!ptrace_reparented(p))
1476 			ptrace = 1;
1477 	}
1478 
1479 	/* slay zombie? */
1480 	if (exit_state == EXIT_ZOMBIE) {
1481 		/* we don't reap group leaders with subthreads */
1482 		if (!delay_group_leader(p)) {
1483 			/*
1484 			 * A zombie ptracee is only visible to its ptracer.
1485 			 * Notification and reaping will be cascaded to the
1486 			 * real parent when the ptracer detaches.
1487 			 */
1488 			if (unlikely(ptrace) || likely(!p->ptrace))
1489 				return wait_task_zombie(wo, p);
1490 		}
1491 
1492 		/*
1493 		 * Allow access to stopped/continued state via zombie by
1494 		 * falling through.  Clearing of notask_error is complex.
1495 		 *
1496 		 * When !@ptrace:
1497 		 *
1498 		 * If WEXITED is set, notask_error should naturally be
1499 		 * cleared.  If not, subset of WSTOPPED|WCONTINUED is set,
1500 		 * so, if there are live subthreads, there are events to
1501 		 * wait for.  If all subthreads are dead, it's still safe
1502 		 * to clear - this function will be called again in finite
1503 		 * amount time once all the subthreads are released and
1504 		 * will then return without clearing.
1505 		 *
1506 		 * When @ptrace:
1507 		 *
1508 		 * Stopped state is per-task and thus can't change once the
1509 		 * target task dies.  Only continued and exited can happen.
1510 		 * Clear notask_error if WCONTINUED | WEXITED.
1511 		 */
1512 		if (likely(!ptrace) || (wo->wo_flags & (WCONTINUED | WEXITED)))
1513 			wo->notask_error = 0;
1514 	} else {
1515 		/*
1516 		 * @p is alive and it's gonna stop, continue or exit, so
1517 		 * there always is something to wait for.
1518 		 */
1519 		wo->notask_error = 0;
1520 	}
1521 
1522 	/*
1523 	 * Wait for stopped.  Depending on @ptrace, different stopped state
1524 	 * is used and the two don't interact with each other.
1525 	 */
1526 	ret = wait_task_stopped(wo, ptrace, p);
1527 	if (ret)
1528 		return ret;
1529 
1530 	/*
1531 	 * Wait for continued.  There's only one continued state and the
1532 	 * ptracer can consume it which can confuse the real parent.  Don't
1533 	 * use WCONTINUED from ptracer.  You don't need or want it.
1534 	 */
1535 	return wait_task_continued(wo, p);
1536 }
1537 
1538 /*
1539  * Do the work of do_wait() for one thread in the group, @tsk.
1540  *
1541  * -ECHILD should be in ->notask_error before the first call.
1542  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1543  * Returns zero if the search for a child should continue; then
1544  * ->notask_error is 0 if there were any eligible children,
1545  * or still -ECHILD.
1546  */
1547 static int do_wait_thread(struct wait_opts *wo, struct task_struct *tsk)
1548 {
1549 	struct task_struct *p;
1550 
1551 	list_for_each_entry(p, &tsk->children, sibling) {
1552 		int ret = wait_consider_task(wo, 0, p);
1553 
1554 		if (ret)
1555 			return ret;
1556 	}
1557 
1558 	return 0;
1559 }
1560 
1561 static int ptrace_do_wait(struct wait_opts *wo, struct task_struct *tsk)
1562 {
1563 	struct task_struct *p;
1564 
1565 	list_for_each_entry(p, &tsk->ptraced, ptrace_entry) {
1566 		int ret = wait_consider_task(wo, 1, p);
1567 
1568 		if (ret)
1569 			return ret;
1570 	}
1571 
1572 	return 0;
1573 }
1574 
1575 bool pid_child_should_wake(struct wait_opts *wo, struct task_struct *p)
1576 {
1577 	if (!eligible_pid(wo, p))
1578 		return false;
1579 
1580 	if ((wo->wo_flags & __WNOTHREAD) && wo->child_wait.private != p->parent)
1581 		return false;
1582 
1583 	return true;
1584 }
1585 
1586 static int child_wait_callback(wait_queue_entry_t *wait, unsigned mode,
1587 				int sync, void *key)
1588 {
1589 	struct wait_opts *wo = container_of(wait, struct wait_opts,
1590 						child_wait);
1591 	struct task_struct *p = key;
1592 
1593 	if (pid_child_should_wake(wo, p))
1594 		return default_wake_function(wait, mode, sync, key);
1595 
1596 	return 0;
1597 }
1598 
1599 void __wake_up_parent(struct task_struct *p, struct task_struct *parent)
1600 {
1601 	__wake_up_sync_key(&parent->signal->wait_chldexit,
1602 			   TASK_INTERRUPTIBLE, p);
1603 }
1604 
1605 static bool is_effectively_child(struct wait_opts *wo, bool ptrace,
1606 				 struct task_struct *target)
1607 {
1608 	struct task_struct *parent =
1609 		!ptrace ? target->real_parent : target->parent;
1610 
1611 	return current == parent || (!(wo->wo_flags & __WNOTHREAD) &&
1612 				     same_thread_group(current, parent));
1613 }
1614 
1615 /*
1616  * Optimization for waiting on PIDTYPE_PID. No need to iterate through child
1617  * and tracee lists to find the target task.
1618  */
1619 static int do_wait_pid(struct wait_opts *wo)
1620 {
1621 	bool ptrace;
1622 	struct task_struct *target;
1623 	int retval;
1624 
1625 	ptrace = false;
1626 	target = pid_task(wo->wo_pid, PIDTYPE_TGID);
1627 	if (target && is_effectively_child(wo, ptrace, target)) {
1628 		retval = wait_consider_task(wo, ptrace, target);
1629 		if (retval)
1630 			return retval;
1631 	}
1632 
1633 	ptrace = true;
1634 	target = pid_task(wo->wo_pid, PIDTYPE_PID);
1635 	if (target && target->ptrace &&
1636 	    is_effectively_child(wo, ptrace, target)) {
1637 		retval = wait_consider_task(wo, ptrace, target);
1638 		if (retval)
1639 			return retval;
1640 	}
1641 
1642 	return 0;
1643 }
1644 
1645 long __do_wait(struct wait_opts *wo)
1646 {
1647 	long retval;
1648 
1649 	/*
1650 	 * If there is nothing that can match our criteria, just get out.
1651 	 * We will clear ->notask_error to zero if we see any child that
1652 	 * might later match our criteria, even if we are not able to reap
1653 	 * it yet.
1654 	 */
1655 	wo->notask_error = -ECHILD;
1656 	if ((wo->wo_type < PIDTYPE_MAX) &&
1657 	   (!wo->wo_pid || !pid_has_task(wo->wo_pid, wo->wo_type)))
1658 		goto notask;
1659 
1660 	read_lock(&tasklist_lock);
1661 
1662 	if (wo->wo_type == PIDTYPE_PID) {
1663 		retval = do_wait_pid(wo);
1664 		if (retval)
1665 			return retval;
1666 	} else {
1667 		struct task_struct *tsk = current;
1668 
1669 		do {
1670 			retval = do_wait_thread(wo, tsk);
1671 			if (retval)
1672 				return retval;
1673 
1674 			retval = ptrace_do_wait(wo, tsk);
1675 			if (retval)
1676 				return retval;
1677 
1678 			if (wo->wo_flags & __WNOTHREAD)
1679 				break;
1680 		} while_each_thread(current, tsk);
1681 	}
1682 	read_unlock(&tasklist_lock);
1683 
1684 notask:
1685 	retval = wo->notask_error;
1686 	if (!retval && !(wo->wo_flags & WNOHANG))
1687 		return -ERESTARTSYS;
1688 
1689 	return retval;
1690 }
1691 
1692 static long do_wait(struct wait_opts *wo)
1693 {
1694 	int retval;
1695 
1696 	trace_sched_process_wait(wo->wo_pid);
1697 
1698 	init_waitqueue_func_entry(&wo->child_wait, child_wait_callback);
1699 	wo->child_wait.private = current;
1700 	add_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1701 
1702 	do {
1703 		set_current_state(TASK_INTERRUPTIBLE);
1704 		retval = __do_wait(wo);
1705 		if (retval != -ERESTARTSYS)
1706 			break;
1707 		if (signal_pending(current))
1708 			break;
1709 		schedule();
1710 	} while (1);
1711 
1712 	__set_current_state(TASK_RUNNING);
1713 	remove_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1714 	return retval;
1715 }
1716 
1717 int kernel_waitid_prepare(struct wait_opts *wo, int which, pid_t upid,
1718 			  struct waitid_info *infop, int options,
1719 			  struct rusage *ru)
1720 {
1721 	unsigned int f_flags = 0;
1722 	struct pid *pid = NULL;
1723 	enum pid_type type;
1724 
1725 	if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED|
1726 			__WNOTHREAD|__WCLONE|__WALL))
1727 		return -EINVAL;
1728 	if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
1729 		return -EINVAL;
1730 
1731 	switch (which) {
1732 	case P_ALL:
1733 		type = PIDTYPE_MAX;
1734 		break;
1735 	case P_PID:
1736 		type = PIDTYPE_PID;
1737 		if (upid <= 0)
1738 			return -EINVAL;
1739 
1740 		pid = find_get_pid(upid);
1741 		break;
1742 	case P_PGID:
1743 		type = PIDTYPE_PGID;
1744 		if (upid < 0)
1745 			return -EINVAL;
1746 
1747 		if (upid)
1748 			pid = find_get_pid(upid);
1749 		else
1750 			pid = get_task_pid(current, PIDTYPE_PGID);
1751 		break;
1752 	case P_PIDFD:
1753 		type = PIDTYPE_PID;
1754 		if (upid < 0)
1755 			return -EINVAL;
1756 
1757 		pid = pidfd_get_pid(upid, &f_flags);
1758 		if (IS_ERR(pid))
1759 			return PTR_ERR(pid);
1760 
1761 		break;
1762 	default:
1763 		return -EINVAL;
1764 	}
1765 
1766 	wo->wo_type	= type;
1767 	wo->wo_pid	= pid;
1768 	wo->wo_flags	= options;
1769 	wo->wo_info	= infop;
1770 	wo->wo_rusage	= ru;
1771 	if (f_flags & O_NONBLOCK)
1772 		wo->wo_flags |= WNOHANG;
1773 
1774 	return 0;
1775 }
1776 
1777 static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
1778 			  int options, struct rusage *ru)
1779 {
1780 	struct wait_opts wo;
1781 	long ret;
1782 
1783 	ret = kernel_waitid_prepare(&wo, which, upid, infop, options, ru);
1784 	if (ret)
1785 		return ret;
1786 
1787 	ret = do_wait(&wo);
1788 	if (!ret && !(options & WNOHANG) && (wo.wo_flags & WNOHANG))
1789 		ret = -EAGAIN;
1790 
1791 	put_pid(wo.wo_pid);
1792 	return ret;
1793 }
1794 
1795 SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
1796 		infop, int, options, struct rusage __user *, ru)
1797 {
1798 	struct rusage r;
1799 	struct waitid_info info = {.status = 0};
1800 	long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);
1801 	int signo = 0;
1802 
1803 	if (err > 0) {
1804 		signo = SIGCHLD;
1805 		err = 0;
1806 		if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1807 			return -EFAULT;
1808 	}
1809 	if (!infop)
1810 		return err;
1811 
1812 	if (!user_write_access_begin(infop, sizeof(*infop)))
1813 		return -EFAULT;
1814 
1815 	unsafe_put_user(signo, &infop->si_signo, Efault);
1816 	unsafe_put_user(0, &infop->si_errno, Efault);
1817 	unsafe_put_user(info.cause, &infop->si_code, Efault);
1818 	unsafe_put_user(info.pid, &infop->si_pid, Efault);
1819 	unsafe_put_user(info.uid, &infop->si_uid, Efault);
1820 	unsafe_put_user(info.status, &infop->si_status, Efault);
1821 	user_write_access_end();
1822 	return err;
1823 Efault:
1824 	user_write_access_end();
1825 	return -EFAULT;
1826 }
1827 
1828 long kernel_wait4(pid_t upid, int __user *stat_addr, int options,
1829 		  struct rusage *ru)
1830 {
1831 	struct wait_opts wo;
1832 	struct pid *pid = NULL;
1833 	enum pid_type type;
1834 	long ret;
1835 
1836 	if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
1837 			__WNOTHREAD|__WCLONE|__WALL))
1838 		return -EINVAL;
1839 
1840 	/* -INT_MIN is not defined */
1841 	if (upid == INT_MIN)
1842 		return -ESRCH;
1843 
1844 	if (upid == -1)
1845 		type = PIDTYPE_MAX;
1846 	else if (upid < 0) {
1847 		type = PIDTYPE_PGID;
1848 		pid = find_get_pid(-upid);
1849 	} else if (upid == 0) {
1850 		type = PIDTYPE_PGID;
1851 		pid = get_task_pid(current, PIDTYPE_PGID);
1852 	} else /* upid > 0 */ {
1853 		type = PIDTYPE_PID;
1854 		pid = find_get_pid(upid);
1855 	}
1856 
1857 	wo.wo_type	= type;
1858 	wo.wo_pid	= pid;
1859 	wo.wo_flags	= options | WEXITED;
1860 	wo.wo_info	= NULL;
1861 	wo.wo_stat	= 0;
1862 	wo.wo_rusage	= ru;
1863 	ret = do_wait(&wo);
1864 	put_pid(pid);
1865 	if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
1866 		ret = -EFAULT;
1867 
1868 	return ret;
1869 }
1870 
1871 int kernel_wait(pid_t pid, int *stat)
1872 {
1873 	struct wait_opts wo = {
1874 		.wo_type	= PIDTYPE_PID,
1875 		.wo_pid		= find_get_pid(pid),
1876 		.wo_flags	= WEXITED,
1877 	};
1878 	int ret;
1879 
1880 	ret = do_wait(&wo);
1881 	if (ret > 0 && wo.wo_stat)
1882 		*stat = wo.wo_stat;
1883 	put_pid(wo.wo_pid);
1884 	return ret;
1885 }
1886 
1887 SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
1888 		int, options, struct rusage __user *, ru)
1889 {
1890 	struct rusage r;
1891 	long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL);
1892 
1893 	if (err > 0) {
1894 		if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1895 			return -EFAULT;
1896 	}
1897 	return err;
1898 }
1899 
1900 #ifdef __ARCH_WANT_SYS_WAITPID
1901 
1902 /*
1903  * sys_waitpid() remains for compatibility. waitpid() should be
1904  * implemented by calling sys_wait4() from libc.a.
1905  */
1906 SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options)
1907 {
1908 	return kernel_wait4(pid, stat_addr, options, NULL);
1909 }
1910 
1911 #endif
1912 
1913 #ifdef CONFIG_COMPAT
1914 COMPAT_SYSCALL_DEFINE4(wait4,
1915 	compat_pid_t, pid,
1916 	compat_uint_t __user *, stat_addr,
1917 	int, options,
1918 	struct compat_rusage __user *, ru)
1919 {
1920 	struct rusage r;
1921 	long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL);
1922 	if (err > 0) {
1923 		if (ru && put_compat_rusage(&r, ru))
1924 			return -EFAULT;
1925 	}
1926 	return err;
1927 }
1928 
1929 COMPAT_SYSCALL_DEFINE5(waitid,
1930 		int, which, compat_pid_t, pid,
1931 		struct compat_siginfo __user *, infop, int, options,
1932 		struct compat_rusage __user *, uru)
1933 {
1934 	struct rusage ru;
1935 	struct waitid_info info = {.status = 0};
1936 	long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
1937 	int signo = 0;
1938 	if (err > 0) {
1939 		signo = SIGCHLD;
1940 		err = 0;
1941 		if (uru) {
1942 			/* kernel_waitid() overwrites everything in ru */
1943 			if (COMPAT_USE_64BIT_TIME)
1944 				err = copy_to_user(uru, &ru, sizeof(ru));
1945 			else
1946 				err = put_compat_rusage(&ru, uru);
1947 			if (err)
1948 				return -EFAULT;
1949 		}
1950 	}
1951 
1952 	if (!infop)
1953 		return err;
1954 
1955 	if (!user_write_access_begin(infop, sizeof(*infop)))
1956 		return -EFAULT;
1957 
1958 	unsafe_put_user(signo, &infop->si_signo, Efault);
1959 	unsafe_put_user(0, &infop->si_errno, Efault);
1960 	unsafe_put_user(info.cause, &infop->si_code, Efault);
1961 	unsafe_put_user(info.pid, &infop->si_pid, Efault);
1962 	unsafe_put_user(info.uid, &infop->si_uid, Efault);
1963 	unsafe_put_user(info.status, &infop->si_status, Efault);
1964 	user_write_access_end();
1965 	return err;
1966 Efault:
1967 	user_write_access_end();
1968 	return -EFAULT;
1969 }
1970 #endif
1971 
1972 /*
1973  * This needs to be __function_aligned as GCC implicitly makes any
1974  * implementation of abort() cold and drops alignment specified by
1975  * -falign-functions=N.
1976  *
1977  * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88345#c11
1978  */
1979 __weak __function_aligned void abort(void)
1980 {
1981 	BUG();
1982 
1983 	/* if that doesn't kill us, halt */
1984 	panic("Oops failed to kill thread");
1985 }
1986 EXPORT_SYMBOL(abort);
1987