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