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