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