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