• 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 
17 #ifdef CONFIG_QOS_CTRL
18 #include <linux/sched/qos_ctrl.h>
19 #endif
20 
21 #include <linux/interrupt.h>
22 #include <linux/module.h>
23 #include <linux/capability.h>
24 #include <linux/completion.h>
25 #include <linux/personality.h>
26 #include <linux/tty.h>
27 #include <linux/iocontext.h>
28 #include <linux/key.h>
29 #include <linux/cpu.h>
30 #include <linux/acct.h>
31 #include <linux/tsacct_kern.h>
32 #include <linux/file.h>
33 #include <linux/fdtable.h>
34 #include <linux/freezer.h>
35 #include <linux/binfmts.h>
36 #include <linux/nsproxy.h>
37 #include <linux/pid_namespace.h>
38 #include <linux/ptrace.h>
39 #include <linux/profile.h>
40 #include <linux/mount.h>
41 #include <linux/proc_fs.h>
42 #include <linux/kthread.h>
43 #include <linux/mempolicy.h>
44 #include <linux/taskstats_kern.h>
45 #include <linux/delayacct.h>
46 #include <linux/cgroup.h>
47 #include <linux/syscalls.h>
48 #include <linux/signal.h>
49 #include <linux/posix-timers.h>
50 #include <linux/cn_proc.h>
51 #include <linux/mutex.h>
52 #include <linux/futex.h>
53 #include <linux/pipe_fs_i.h>
54 #include <linux/audit.h> /* for audit_free() */
55 #include <linux/resource.h>
56 #include <linux/blkdev.h>
57 #include <linux/task_io_accounting_ops.h>
58 #include <linux/tracehook.h>
59 #include <linux/fs_struct.h>
60 #include <linux/init_task.h>
61 #include <linux/perf_event.h>
62 #include <trace/events/sched.h>
63 #include <linux/hw_breakpoint.h>
64 #include <linux/oom.h>
65 #include <linux/writeback.h>
66 #include <linux/shm.h>
67 #include <linux/kcov.h>
68 #include <linux/random.h>
69 #include <linux/rcuwait.h>
70 #include <linux/compat.h>
71 #include <linux/io_uring.h>
72 #include <linux/sysfs.h>
73 
74 #include <linux/uaccess.h>
75 #include <asm/unistd.h>
76 #include <asm/mmu_context.h>
77 
78 #include <linux/hck/lite_hck_ced.h>
79 #include <linux/hck/lite_hck_jit_memory.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 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 
kernel_exit_sysctls_init(void)100 static __init int kernel_exit_sysctls_init(void)
101 {
102 	register_sysctl_init("kernel", kern_exit_table);
103 	return 0;
104 }
105 late_initcall(kernel_exit_sysctls_init);
106 #endif
107 
108 static atomic_t oops_count = ATOMIC_INIT(0);
109 
110 #ifdef CONFIG_SYSFS
oops_count_show(struct kobject * kobj,struct kobj_attribute * attr,char * page)111 static ssize_t oops_count_show(struct kobject *kobj, struct kobj_attribute *attr,
112 			       char *page)
113 {
114 	return sysfs_emit(page, "%d\n", atomic_read(&oops_count));
115 }
116 
117 static struct kobj_attribute oops_count_attr = __ATTR_RO(oops_count);
118 
kernel_exit_sysfs_init(void)119 static __init int kernel_exit_sysfs_init(void)
120 {
121 	sysfs_add_file_to_group(kernel_kobj, &oops_count_attr.attr, NULL);
122 	return 0;
123 }
124 late_initcall(kernel_exit_sysfs_init);
125 #endif
126 
__unhash_process(struct task_struct * p,bool group_dead)127 static void __unhash_process(struct task_struct *p, bool group_dead)
128 {
129 	nr_threads--;
130 	detach_pid(p, PIDTYPE_PID);
131 	if (group_dead) {
132 		detach_pid(p, PIDTYPE_TGID);
133 		detach_pid(p, PIDTYPE_PGID);
134 		detach_pid(p, PIDTYPE_SID);
135 
136 		list_del_rcu(&p->tasks);
137 		list_del_init(&p->sibling);
138 		__this_cpu_dec(process_counts);
139 	}
140 	list_del_rcu(&p->thread_group);
141 	list_del_rcu(&p->thread_node);
142 }
143 
144 /*
145  * This function expects the tasklist_lock write-locked.
146  */
__exit_signal(struct task_struct * tsk)147 static void __exit_signal(struct task_struct *tsk)
148 {
149 	struct signal_struct *sig = tsk->signal;
150 	bool group_dead = thread_group_leader(tsk);
151 	struct sighand_struct *sighand;
152 	struct tty_struct *tty;
153 	u64 utime, stime;
154 
155 	sighand = rcu_dereference_check(tsk->sighand,
156 					lockdep_tasklist_lock_is_held());
157 	spin_lock(&sighand->siglock);
158 
159 #ifdef CONFIG_POSIX_TIMERS
160 	posix_cpu_timers_exit(tsk);
161 	if (group_dead)
162 		posix_cpu_timers_exit_group(tsk);
163 #endif
164 
165 	if (group_dead) {
166 		tty = sig->tty;
167 		sig->tty = NULL;
168 	} else {
169 		/*
170 		 * If there is any task waiting for the group exit
171 		 * then notify it:
172 		 */
173 		if (sig->notify_count > 0 && !--sig->notify_count)
174 			wake_up_process(sig->group_exit_task);
175 
176 		if (tsk == sig->curr_target)
177 			sig->curr_target = next_thread(tsk);
178 	}
179 
180 	add_device_randomness((const void*) &tsk->se.sum_exec_runtime,
181 			      sizeof(unsigned long long));
182 
183 	/*
184 	 * Accumulate here the counters for all threads as they die. We could
185 	 * skip the group leader because it is the last user of signal_struct,
186 	 * but we want to avoid the race with thread_group_cputime() which can
187 	 * see the empty ->thread_head list.
188 	 */
189 	task_cputime(tsk, &utime, &stime);
190 	write_seqlock(&sig->stats_lock);
191 	sig->utime += utime;
192 	sig->stime += stime;
193 	sig->gtime += task_gtime(tsk);
194 	sig->min_flt += tsk->min_flt;
195 	sig->maj_flt += tsk->maj_flt;
196 	sig->nvcsw += tsk->nvcsw;
197 	sig->nivcsw += tsk->nivcsw;
198 	sig->inblock += task_io_get_inblock(tsk);
199 	sig->oublock += task_io_get_oublock(tsk);
200 	task_io_accounting_add(&sig->ioac, &tsk->ioac);
201 	sig->sum_sched_runtime += tsk->se.sum_exec_runtime;
202 	sig->nr_threads--;
203 	__unhash_process(tsk, group_dead);
204 	write_sequnlock(&sig->stats_lock);
205 
206 	/*
207 	 * Do this under ->siglock, we can race with another thread
208 	 * doing sigqueue_free() if we have SIGQUEUE_PREALLOC signals.
209 	 */
210 	flush_sigqueue(&tsk->pending);
211 	tsk->sighand = NULL;
212 	spin_unlock(&sighand->siglock);
213 
214 	__cleanup_sighand(sighand);
215 	clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
216 	if (group_dead) {
217 		flush_sigqueue(&sig->shared_pending);
218 		tty_kref_put(tty);
219 	}
220 }
221 
delayed_put_task_struct(struct rcu_head * rhp)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 	perf_event_delayed_put(tsk);
227 	trace_sched_process_free(tsk);
228 	put_task_struct(tsk);
229 }
230 
put_task_struct_rcu_user(struct task_struct * task)231 void put_task_struct_rcu_user(struct task_struct *task)
232 {
233 	if (refcount_dec_and_test(&task->rcu_users))
234 		call_rcu(&task->rcu, delayed_put_task_struct);
235 }
236 
release_task(struct task_struct * p)237 void release_task(struct task_struct *p)
238 {
239 	struct task_struct *leader;
240 	struct pid *thread_pid;
241 	int zap_leader;
242 repeat:
243 	/* don't need to get the RCU readlock here - the process is dead and
244 	 * can't be modifying its own credentials. But shut RCU-lockdep up */
245 	rcu_read_lock();
246 	atomic_dec(&__task_cred(p)->user->processes);
247 	rcu_read_unlock();
248 
249 	cgroup_release(p);
250 
251 	write_lock_irq(&tasklist_lock);
252 	ptrace_release_task(p);
253 	thread_pid = get_pid(p->thread_pid);
254 	__exit_signal(p);
255 
256 	/*
257 	 * If we are the last non-leader member of the thread
258 	 * group, and the leader is zombie, then notify the
259 	 * group leader's parent process. (if it wants notification.)
260 	 */
261 	zap_leader = 0;
262 	leader = p->group_leader;
263 	if (leader != p && thread_group_empty(leader)
264 			&& leader->exit_state == EXIT_ZOMBIE) {
265 		/*
266 		 * If we were the last child thread and the leader has
267 		 * exited already, and the leader's parent ignores SIGCHLD,
268 		 * then we are the one who should release the leader.
269 		 */
270 		zap_leader = do_notify_parent(leader, leader->exit_signal);
271 		if (zap_leader)
272 			leader->exit_state = EXIT_DEAD;
273 	}
274 
275 	write_unlock_irq(&tasklist_lock);
276 	seccomp_filter_release(p);
277 	proc_flush_pid(thread_pid);
278 	put_pid(thread_pid);
279 	release_thread(p);
280 	put_task_struct_rcu_user(p);
281 
282 	p = leader;
283 	if (unlikely(zap_leader))
284 		goto repeat;
285 }
286 
rcuwait_wake_up(struct rcuwait * w)287 int rcuwait_wake_up(struct rcuwait *w)
288 {
289 	int ret = 0;
290 	struct task_struct *task;
291 
292 	rcu_read_lock();
293 
294 	/*
295 	 * Order condition vs @task, such that everything prior to the load
296 	 * of @task is visible. This is the condition as to why the user called
297 	 * rcuwait_wake() in the first place. Pairs with set_current_state()
298 	 * barrier (A) in rcuwait_wait_event().
299 	 *
300 	 *    WAIT                WAKE
301 	 *    [S] tsk = current	  [S] cond = true
302 	 *        MB (A)	      MB (B)
303 	 *    [L] cond		  [L] tsk
304 	 */
305 	smp_mb(); /* (B) */
306 
307 	task = rcu_dereference(w->task);
308 	if (task)
309 		ret = wake_up_process(task);
310 	rcu_read_unlock();
311 
312 	return ret;
313 }
314 EXPORT_SYMBOL_GPL(rcuwait_wake_up);
315 
316 /*
317  * Determine if a process group is "orphaned", according to the POSIX
318  * definition in 2.2.2.52.  Orphaned process groups are not to be affected
319  * by terminal-generated stop signals.  Newly orphaned process groups are
320  * to receive a SIGHUP and a SIGCONT.
321  *
322  * "I ask you, have you ever known what it is to be an orphan?"
323  */
will_become_orphaned_pgrp(struct pid * pgrp,struct task_struct * ignored_task)324 static int will_become_orphaned_pgrp(struct pid *pgrp,
325 					struct task_struct *ignored_task)
326 {
327 	struct task_struct *p;
328 
329 	do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
330 		if ((p == ignored_task) ||
331 		    (p->exit_state && thread_group_empty(p)) ||
332 		    is_global_init(p->real_parent))
333 			continue;
334 
335 		if (task_pgrp(p->real_parent) != pgrp &&
336 		    task_session(p->real_parent) == task_session(p))
337 			return 0;
338 	} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
339 
340 	return 1;
341 }
342 
is_current_pgrp_orphaned(void)343 int is_current_pgrp_orphaned(void)
344 {
345 	int retval;
346 
347 	read_lock(&tasklist_lock);
348 	retval = will_become_orphaned_pgrp(task_pgrp(current), NULL);
349 	read_unlock(&tasklist_lock);
350 
351 	return retval;
352 }
353 
has_stopped_jobs(struct pid * pgrp)354 static bool has_stopped_jobs(struct pid *pgrp)
355 {
356 	struct task_struct *p;
357 
358 	do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
359 		if (p->signal->flags & SIGNAL_STOP_STOPPED)
360 			return true;
361 	} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
362 
363 	return false;
364 }
365 
366 /*
367  * Check to see if any process groups have become orphaned as
368  * a result of our exiting, and if they have any stopped jobs,
369  * send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2)
370  */
371 static void
kill_orphaned_pgrp(struct task_struct * tsk,struct task_struct * parent)372 kill_orphaned_pgrp(struct task_struct *tsk, struct task_struct *parent)
373 {
374 	struct pid *pgrp = task_pgrp(tsk);
375 	struct task_struct *ignored_task = tsk;
376 
377 	if (!parent)
378 		/* exit: our father is in a different pgrp than
379 		 * we are and we were the only connection outside.
380 		 */
381 		parent = tsk->real_parent;
382 	else
383 		/* reparent: our child is in a different pgrp than
384 		 * we are, and it was the only connection outside.
385 		 */
386 		ignored_task = NULL;
387 
388 	if (task_pgrp(parent) != pgrp &&
389 	    task_session(parent) == task_session(tsk) &&
390 	    will_become_orphaned_pgrp(pgrp, ignored_task) &&
391 	    has_stopped_jobs(pgrp)) {
392 		__kill_pgrp_info(SIGHUP, SEND_SIG_PRIV, pgrp);
393 		__kill_pgrp_info(SIGCONT, SEND_SIG_PRIV, pgrp);
394 	}
395 }
396 
397 #ifdef CONFIG_MEMCG
398 /*
399  * A task is exiting.   If it owned this mm, find a new owner for the mm.
400  */
mm_update_next_owner(struct mm_struct * mm)401 void mm_update_next_owner(struct mm_struct *mm)
402 {
403 	struct task_struct *c, *g, *p = current;
404 
405 retry:
406 	/*
407 	 * If the exiting or execing task is not the owner, it's
408 	 * someone else's problem.
409 	 */
410 	if (mm->owner != p)
411 		return;
412 	/*
413 	 * The current owner is exiting/execing and there are no other
414 	 * candidates.  Do not leave the mm pointing to a possibly
415 	 * freed task structure.
416 	 */
417 	if (atomic_read(&mm->mm_users) <= 1) {
418 		WRITE_ONCE(mm->owner, NULL);
419 		return;
420 	}
421 
422 	read_lock(&tasklist_lock);
423 	/*
424 	 * Search in the children
425 	 */
426 	list_for_each_entry(c, &p->children, sibling) {
427 		if (c->mm == mm)
428 			goto assign_new_owner;
429 	}
430 
431 	/*
432 	 * Search in the siblings
433 	 */
434 	list_for_each_entry(c, &p->real_parent->children, sibling) {
435 		if (c->mm == mm)
436 			goto assign_new_owner;
437 	}
438 
439 	/*
440 	 * Search through everything else, we should not get here often.
441 	 */
442 	for_each_process(g) {
443 		if (g->flags & PF_KTHREAD)
444 			continue;
445 		for_each_thread(g, c) {
446 			if (c->mm == mm)
447 				goto assign_new_owner;
448 			if (c->mm)
449 				break;
450 		}
451 	}
452 	read_unlock(&tasklist_lock);
453 	/*
454 	 * We found no owner yet mm_users > 1: this implies that we are
455 	 * most likely racing with swapoff (try_to_unuse()) or /proc or
456 	 * ptrace or page migration (get_task_mm()).  Mark owner as NULL.
457 	 */
458 	WRITE_ONCE(mm->owner, NULL);
459 	return;
460 
461 assign_new_owner:
462 	BUG_ON(c == p);
463 	get_task_struct(c);
464 	/*
465 	 * The task_lock protects c->mm from changing.
466 	 * We always want mm->owner->mm == mm
467 	 */
468 	task_lock(c);
469 	/*
470 	 * Delay read_unlock() till we have the task_lock()
471 	 * to ensure that c does not slip away underneath us
472 	 */
473 	read_unlock(&tasklist_lock);
474 	if (c->mm != mm) {
475 		task_unlock(c);
476 		put_task_struct(c);
477 		goto retry;
478 	}
479 	WRITE_ONCE(mm->owner, c);
480 	task_unlock(c);
481 	put_task_struct(c);
482 }
483 #endif /* CONFIG_MEMCG */
484 
485 /*
486  * Turn us into a lazy TLB process if we
487  * aren't already..
488  */
exit_mm(void)489 static void exit_mm(void)
490 {
491 	struct mm_struct *mm = current->mm;
492 	struct core_state *core_state;
493 
494 	exit_mm_release(current, mm);
495 	if (!mm)
496 		return;
497 	sync_mm_rss(mm);
498 	/*
499 	 * Serialize with any possible pending coredump.
500 	 * We must hold mmap_lock around checking core_state
501 	 * and clearing tsk->mm.  The core-inducing thread
502 	 * will increment ->nr_threads for each thread in the
503 	 * group with ->mm != NULL.
504 	 */
505 	mmap_read_lock(mm);
506 	core_state = mm->core_state;
507 	if (core_state) {
508 		struct core_thread self;
509 
510 		mmap_read_unlock(mm);
511 
512 		self.task = current;
513 		if (self.task->flags & PF_SIGNALED)
514 			self.next = xchg(&core_state->dumper.next, &self);
515 		else
516 			self.task = NULL;
517 		/*
518 		 * Implies mb(), the result of xchg() must be visible
519 		 * to core_state->dumper.
520 		 */
521 		if (atomic_dec_and_test(&core_state->nr_threads))
522 			complete(&core_state->startup);
523 
524 		for (;;) {
525 			set_current_state(TASK_UNINTERRUPTIBLE);
526 			if (!self.task) /* see coredump_finish() */
527 				break;
528 			freezable_schedule();
529 		}
530 		__set_current_state(TASK_RUNNING);
531 		mmap_read_lock(mm);
532 	}
533 	mmgrab(mm);
534 	BUG_ON(mm != current->active_mm);
535 	/* more a memory barrier than a real lock */
536 	task_lock(current);
537 	current->mm = NULL;
538 	mmap_read_unlock(mm);
539 	enter_lazy_tlb(mm, current);
540 	task_unlock(current);
541 	mm_update_next_owner(mm);
542 	mmput(mm);
543 	if (test_thread_flag(TIF_MEMDIE))
544 		exit_oom_victim();
545 }
546 
find_alive_thread(struct task_struct * p)547 static struct task_struct *find_alive_thread(struct task_struct *p)
548 {
549 	struct task_struct *t;
550 
551 	for_each_thread(p, t) {
552 		if (!(t->flags & PF_EXITING))
553 			return t;
554 	}
555 	return NULL;
556 }
557 
find_child_reaper(struct task_struct * father,struct list_head * dead)558 static struct task_struct *find_child_reaper(struct task_struct *father,
559 						struct list_head *dead)
560 	__releases(&tasklist_lock)
561 	__acquires(&tasklist_lock)
562 {
563 	struct pid_namespace *pid_ns = task_active_pid_ns(father);
564 	struct task_struct *reaper = pid_ns->child_reaper;
565 	struct task_struct *p, *n;
566 
567 	if (likely(reaper != father))
568 		return reaper;
569 
570 	reaper = find_alive_thread(father);
571 	if (reaper) {
572 		pid_ns->child_reaper = reaper;
573 		return reaper;
574 	}
575 
576 	write_unlock_irq(&tasklist_lock);
577 
578 	list_for_each_entry_safe(p, n, dead, ptrace_entry) {
579 		list_del_init(&p->ptrace_entry);
580 		release_task(p);
581 	}
582 
583 	zap_pid_ns_processes(pid_ns);
584 	write_lock_irq(&tasklist_lock);
585 
586 	return father;
587 }
588 
589 /*
590  * When we die, we re-parent all our children, and try to:
591  * 1. give them to another thread in our thread group, if such a member exists
592  * 2. give it to the first ancestor process which prctl'd itself as a
593  *    child_subreaper for its children (like a service manager)
594  * 3. give it to the init process (PID 1) in our pid namespace
595  */
find_new_reaper(struct task_struct * father,struct task_struct * child_reaper)596 static struct task_struct *find_new_reaper(struct task_struct *father,
597 					   struct task_struct *child_reaper)
598 {
599 	struct task_struct *thread, *reaper;
600 
601 	thread = find_alive_thread(father);
602 	if (thread)
603 		return thread;
604 
605 	if (father->signal->has_child_subreaper) {
606 		unsigned int ns_level = task_pid(father)->level;
607 		/*
608 		 * Find the first ->is_child_subreaper ancestor in our pid_ns.
609 		 * We can't check reaper != child_reaper to ensure we do not
610 		 * cross the namespaces, the exiting parent could be injected
611 		 * by setns() + fork().
612 		 * We check pid->level, this is slightly more efficient than
613 		 * task_active_pid_ns(reaper) != task_active_pid_ns(father).
614 		 */
615 		for (reaper = father->real_parent;
616 		     task_pid(reaper)->level == ns_level;
617 		     reaper = reaper->real_parent) {
618 			if (reaper == &init_task)
619 				break;
620 			if (!reaper->signal->is_child_subreaper)
621 				continue;
622 			thread = find_alive_thread(reaper);
623 			if (thread)
624 				return thread;
625 		}
626 	}
627 
628 	return child_reaper;
629 }
630 
631 /*
632 * Any that need to be release_task'd are put on the @dead list.
633  */
reparent_leader(struct task_struct * father,struct task_struct * p,struct list_head * dead)634 static void reparent_leader(struct task_struct *father, struct task_struct *p,
635 				struct list_head *dead)
636 {
637 	if (unlikely(p->exit_state == EXIT_DEAD))
638 		return;
639 
640 	/* We don't want people slaying init. */
641 	p->exit_signal = SIGCHLD;
642 
643 	/* If it has exited notify the new parent about this child's death. */
644 	if (!p->ptrace &&
645 	    p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) {
646 		if (do_notify_parent(p, p->exit_signal)) {
647 			p->exit_state = EXIT_DEAD;
648 			list_add(&p->ptrace_entry, dead);
649 		}
650 	}
651 
652 	kill_orphaned_pgrp(p, father);
653 }
654 
655 /*
656  * This does two things:
657  *
658  * A.  Make init inherit all the child processes
659  * B.  Check to see if any process groups have become orphaned
660  *	as a result of our exiting, and if they have any stopped
661  *	jobs, send them a SIGHUP and then a SIGCONT.  (POSIX 3.2.2.2)
662  */
forget_original_parent(struct task_struct * father,struct list_head * dead)663 static void forget_original_parent(struct task_struct *father,
664 					struct list_head *dead)
665 {
666 	struct task_struct *p, *t, *reaper;
667 
668 	if (unlikely(!list_empty(&father->ptraced)))
669 		exit_ptrace(father, dead);
670 
671 	/* Can drop and reacquire tasklist_lock */
672 	reaper = find_child_reaper(father, dead);
673 	if (list_empty(&father->children))
674 		return;
675 
676 	reaper = find_new_reaper(father, reaper);
677 	list_for_each_entry(p, &father->children, sibling) {
678 		for_each_thread(p, t) {
679 			RCU_INIT_POINTER(t->real_parent, reaper);
680 			BUG_ON((!t->ptrace) != (rcu_access_pointer(t->parent) == father));
681 			if (likely(!t->ptrace))
682 				t->parent = t->real_parent;
683 			if (t->pdeath_signal)
684 				group_send_sig_info(t->pdeath_signal,
685 						    SEND_SIG_NOINFO, t,
686 						    PIDTYPE_TGID);
687 		}
688 		/*
689 		 * If this is a threaded reparent there is no need to
690 		 * notify anyone anything has happened.
691 		 */
692 		if (!same_thread_group(reaper, father))
693 			reparent_leader(father, p, dead);
694 	}
695 	list_splice_tail_init(&father->children, &reaper->children);
696 }
697 
698 /*
699  * Send signals to all our closest relatives so that they know
700  * to properly mourn us..
701  */
exit_notify(struct task_struct * tsk,int group_dead)702 static void exit_notify(struct task_struct *tsk, int group_dead)
703 {
704 	bool autoreap;
705 	struct task_struct *p, *n;
706 	LIST_HEAD(dead);
707 
708 	write_lock_irq(&tasklist_lock);
709 	forget_original_parent(tsk, &dead);
710 
711 	if (group_dead)
712 		kill_orphaned_pgrp(tsk->group_leader, NULL);
713 
714 	tsk->exit_state = EXIT_ZOMBIE;
715 	if (unlikely(tsk->ptrace)) {
716 		int sig = thread_group_leader(tsk) &&
717 				thread_group_empty(tsk) &&
718 				!ptrace_reparented(tsk) ?
719 			tsk->exit_signal : SIGCHLD;
720 		autoreap = do_notify_parent(tsk, sig);
721 	} else if (thread_group_leader(tsk)) {
722 		autoreap = thread_group_empty(tsk) &&
723 			do_notify_parent(tsk, tsk->exit_signal);
724 	} else {
725 		autoreap = true;
726 	}
727 
728 	if (autoreap) {
729 		tsk->exit_state = EXIT_DEAD;
730 		list_add(&tsk->ptrace_entry, &dead);
731 	}
732 
733 	/* mt-exec, de_thread() is waiting for group leader */
734 	if (unlikely(tsk->signal->notify_count < 0))
735 		wake_up_process(tsk->signal->group_exit_task);
736 	write_unlock_irq(&tasklist_lock);
737 
738 	list_for_each_entry_safe(p, n, &dead, ptrace_entry) {
739 		list_del_init(&p->ptrace_entry);
740 		release_task(p);
741 	}
742 }
743 
744 #ifdef CONFIG_DEBUG_STACK_USAGE
check_stack_usage(void)745 static void check_stack_usage(void)
746 {
747 	static DEFINE_SPINLOCK(low_water_lock);
748 	static int lowest_to_date = THREAD_SIZE;
749 	unsigned long free;
750 
751 	free = stack_not_used(current);
752 
753 	if (free >= lowest_to_date)
754 		return;
755 
756 	spin_lock(&low_water_lock);
757 	if (free < lowest_to_date) {
758 		pr_info("%s (%d) used greatest stack depth: %lu bytes left\n",
759 			current->comm, task_pid_nr(current), free);
760 		lowest_to_date = free;
761 	}
762 	spin_unlock(&low_water_lock);
763 }
764 #else
check_stack_usage(void)765 static inline void check_stack_usage(void) {}
766 #endif
767 
do_exit(long code)768 void __noreturn do_exit(long code)
769 {
770 	struct task_struct *tsk = current;
771 	int group_dead;
772 
773 	CALL_HCK_LITE_HOOK(exit_jit_memory_lhck, current);
774 
775 	/*
776 	 * We can get here from a kernel oops, sometimes with preemption off.
777 	 * Start by checking for critical errors.
778 	 * Then fix up important state like USER_DS and preemption.
779 	 * Then do everything else.
780 	 */
781 
782 	WARN_ON(blk_needs_flush_plug(tsk));
783 
784 	if (unlikely(in_interrupt()))
785 		panic("Aiee, killing interrupt handler!");
786 	if (unlikely(!tsk->pid))
787 		panic("Attempted to kill the idle task!");
788 
789 	/*
790 	 * If do_exit is called because this processes oopsed, it's possible
791 	 * that get_fs() was left as KERNEL_DS, so reset it to USER_DS before
792 	 * continuing. Amongst other possible reasons, this is to prevent
793 	 * mm_release()->clear_child_tid() from writing to a user-controlled
794 	 * kernel address.
795 	 */
796 	force_uaccess_begin();
797 
798 	if (unlikely(in_atomic())) {
799 		pr_info("note: %s[%d] exited with preempt_count %d\n",
800 			current->comm, task_pid_nr(current),
801 			preempt_count());
802 		preempt_count_set(PREEMPT_ENABLED);
803 	}
804 
805 	profile_task_exit(tsk);
806 	kcov_task_exit(tsk);
807 
808 	ptrace_event(PTRACE_EVENT_EXIT, code);
809 
810 	validate_creds_for_do_exit(tsk);
811 
812 	/*
813 	 * We're taking recursive faults here in do_exit. Safest is to just
814 	 * leave this task alone and wait for reboot.
815 	 */
816 	if (unlikely(tsk->flags & PF_EXITING)) {
817 		pr_alert("Fixing recursive fault but reboot is needed!\n");
818 		futex_exit_recursive(tsk);
819 		set_current_state(TASK_UNINTERRUPTIBLE);
820 		schedule();
821 	}
822 
823 	io_uring_files_cancel();
824 	exit_signals(tsk);  /* sets PF_EXITING */
825 	sched_exit(tsk);
826 
827 #ifdef CONFIG_QOS_CTRL
828 	sched_exit_qos_list(tsk);
829 #endif
830 
831 	/* sync mm's RSS info before statistics gathering */
832 	if (tsk->mm)
833 		sync_mm_rss(tsk->mm);
834 	acct_update_integrals(tsk);
835 	group_dead = atomic_dec_and_test(&tsk->signal->live);
836 	if (group_dead) {
837 		/*
838 		 * If the last thread of global init has exited, panic
839 		 * immediately to get a useable coredump.
840 		 */
841 		if (unlikely(is_global_init(tsk)))
842 			panic("Attempted to kill init! exitcode=0x%08x\n",
843 				tsk->signal->group_exit_code ?: (int)code);
844 
845 #ifdef CONFIG_POSIX_TIMERS
846 		hrtimer_cancel(&tsk->signal->real_timer);
847 		exit_itimers(tsk);
848 #endif
849 		if (tsk->mm)
850 			setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
851 	}
852 	acct_collect(code, group_dead);
853 	if (group_dead)
854 		tty_audit_exit();
855 	audit_free(tsk);
856 
857 	tsk->exit_code = code;
858 	taskstats_exit(tsk, group_dead);
859 
860 	/*
861 	 * Since sampling can touch ->mm, make sure to stop everything before we
862 	 * tear it down.
863 	 *
864 	 * Also flushes inherited counters to the parent - before the parent
865 	 * gets woken up by child-exit notifications.
866 	 */
867 	perf_event_exit_task(tsk);
868 
869 	exit_mm();
870 
871 	if (group_dead)
872 		acct_process();
873 	trace_sched_process_exit(tsk);
874 
875 	exit_sem(tsk);
876 	exit_shm(tsk);
877 	exit_files(tsk);
878 	exit_fs(tsk);
879 	if (group_dead)
880 		disassociate_ctty(1);
881 	exit_task_namespaces(tsk);
882 	exit_task_work(tsk);
883 	exit_thread(tsk);
884 
885 	sched_autogroup_exit_task(tsk);
886 	cgroup_exit(tsk);
887 
888 	/*
889 	 * FIXME: do that only when needed, using sched_exit tracepoint
890 	 */
891 	flush_ptrace_hw_breakpoint(tsk);
892 
893 	exit_tasks_rcu_start();
894 	exit_notify(tsk, group_dead);
895 	CALL_HCK_LITE_HOOK(ced_exit_lhck, tsk);
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 
do_wait(struct wait_opts * wo)1517 static long do_wait(struct wait_opts *wo)
1518 {
1519 	struct task_struct *tsk;
1520 	int retval;
1521 
1522 	trace_sched_process_wait(wo->wo_pid);
1523 
1524 	init_waitqueue_func_entry(&wo->child_wait, child_wait_callback);
1525 	wo->child_wait.private = current;
1526 	add_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1527 repeat:
1528 	/*
1529 	 * If there is nothing that can match our criteria, just get out.
1530 	 * We will clear ->notask_error to zero if we see any child that
1531 	 * might later match our criteria, even if we are not able to reap
1532 	 * it yet.
1533 	 */
1534 	wo->notask_error = -ECHILD;
1535 	if ((wo->wo_type < PIDTYPE_MAX) &&
1536 	   (!wo->wo_pid || !pid_has_task(wo->wo_pid, wo->wo_type)))
1537 		goto notask;
1538 
1539 	set_current_state(TASK_INTERRUPTIBLE);
1540 	read_lock(&tasklist_lock);
1541 	tsk = current;
1542 	do {
1543 		retval = do_wait_thread(wo, tsk);
1544 		if (retval)
1545 			goto end;
1546 
1547 		retval = ptrace_do_wait(wo, tsk);
1548 		if (retval)
1549 			goto end;
1550 
1551 		if (wo->wo_flags & __WNOTHREAD)
1552 			break;
1553 	} while_each_thread(current, tsk);
1554 	read_unlock(&tasklist_lock);
1555 
1556 notask:
1557 	retval = wo->notask_error;
1558 	if (!retval && !(wo->wo_flags & WNOHANG)) {
1559 		retval = -ERESTARTSYS;
1560 		if (!signal_pending(current)) {
1561 			schedule();
1562 			goto repeat;
1563 		}
1564 	}
1565 end:
1566 	__set_current_state(TASK_RUNNING);
1567 	remove_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1568 	return retval;
1569 }
1570 
kernel_waitid(int which,pid_t upid,struct waitid_info * infop,int options,struct rusage * ru)1571 static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
1572 			  int options, struct rusage *ru)
1573 {
1574 	struct wait_opts wo;
1575 	struct pid *pid = NULL;
1576 	enum pid_type type;
1577 	long ret;
1578 	unsigned int f_flags = 0;
1579 
1580 	if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED|
1581 			__WNOTHREAD|__WCLONE|__WALL))
1582 		return -EINVAL;
1583 	if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
1584 		return -EINVAL;
1585 
1586 	switch (which) {
1587 	case P_ALL:
1588 		type = PIDTYPE_MAX;
1589 		break;
1590 	case P_PID:
1591 		type = PIDTYPE_PID;
1592 		if (upid <= 0)
1593 			return -EINVAL;
1594 
1595 		pid = find_get_pid(upid);
1596 		break;
1597 	case P_PGID:
1598 		type = PIDTYPE_PGID;
1599 		if (upid < 0)
1600 			return -EINVAL;
1601 
1602 		if (upid)
1603 			pid = find_get_pid(upid);
1604 		else
1605 			pid = get_task_pid(current, PIDTYPE_PGID);
1606 		break;
1607 	case P_PIDFD:
1608 		type = PIDTYPE_PID;
1609 		if (upid < 0)
1610 			return -EINVAL;
1611 
1612 		pid = pidfd_get_pid(upid, &f_flags);
1613 		if (IS_ERR(pid))
1614 			return PTR_ERR(pid);
1615 
1616 		break;
1617 	default:
1618 		return -EINVAL;
1619 	}
1620 
1621 	wo.wo_type	= type;
1622 	wo.wo_pid	= pid;
1623 	wo.wo_flags	= options;
1624 	wo.wo_info	= infop;
1625 	wo.wo_rusage	= ru;
1626 	if (f_flags & O_NONBLOCK)
1627 		wo.wo_flags |= WNOHANG;
1628 
1629 	ret = do_wait(&wo);
1630 	if (!ret && !(options & WNOHANG) && (f_flags & O_NONBLOCK))
1631 		ret = -EAGAIN;
1632 
1633 	put_pid(pid);
1634 	return ret;
1635 }
1636 
SYSCALL_DEFINE5(waitid,int,which,pid_t,upid,struct siginfo __user *,infop,int,options,struct rusage __user *,ru)1637 SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
1638 		infop, int, options, struct rusage __user *, ru)
1639 {
1640 	struct rusage r;
1641 	struct waitid_info info = {.status = 0};
1642 	long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);
1643 	int signo = 0;
1644 
1645 	if (err > 0) {
1646 		signo = SIGCHLD;
1647 		err = 0;
1648 		if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1649 			return -EFAULT;
1650 	}
1651 	if (!infop)
1652 		return err;
1653 
1654 	if (!user_write_access_begin(infop, sizeof(*infop)))
1655 		return -EFAULT;
1656 
1657 	unsafe_put_user(signo, &infop->si_signo, Efault);
1658 	unsafe_put_user(0, &infop->si_errno, Efault);
1659 	unsafe_put_user(info.cause, &infop->si_code, Efault);
1660 	unsafe_put_user(info.pid, &infop->si_pid, Efault);
1661 	unsafe_put_user(info.uid, &infop->si_uid, Efault);
1662 	unsafe_put_user(info.status, &infop->si_status, Efault);
1663 	user_write_access_end();
1664 	return err;
1665 Efault:
1666 	user_write_access_end();
1667 	return -EFAULT;
1668 }
1669 
kernel_wait4(pid_t upid,int __user * stat_addr,int options,struct rusage * ru)1670 long kernel_wait4(pid_t upid, int __user *stat_addr, int options,
1671 		  struct rusage *ru)
1672 {
1673 	struct wait_opts wo;
1674 	struct pid *pid = NULL;
1675 	enum pid_type type;
1676 	long ret;
1677 
1678 	if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
1679 			__WNOTHREAD|__WCLONE|__WALL))
1680 		return -EINVAL;
1681 
1682 	/* -INT_MIN is not defined */
1683 	if (upid == INT_MIN)
1684 		return -ESRCH;
1685 
1686 	if (upid == -1)
1687 		type = PIDTYPE_MAX;
1688 	else if (upid < 0) {
1689 		type = PIDTYPE_PGID;
1690 		pid = find_get_pid(-upid);
1691 	} else if (upid == 0) {
1692 		type = PIDTYPE_PGID;
1693 		pid = get_task_pid(current, PIDTYPE_PGID);
1694 	} else /* upid > 0 */ {
1695 		type = PIDTYPE_PID;
1696 		pid = find_get_pid(upid);
1697 	}
1698 
1699 	wo.wo_type	= type;
1700 	wo.wo_pid	= pid;
1701 	wo.wo_flags	= options | WEXITED;
1702 	wo.wo_info	= NULL;
1703 	wo.wo_stat	= 0;
1704 	wo.wo_rusage	= ru;
1705 	ret = do_wait(&wo);
1706 	put_pid(pid);
1707 	if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
1708 		ret = -EFAULT;
1709 
1710 	return ret;
1711 }
1712 
kernel_wait(pid_t pid,int * stat)1713 int kernel_wait(pid_t pid, int *stat)
1714 {
1715 	struct wait_opts wo = {
1716 		.wo_type	= PIDTYPE_PID,
1717 		.wo_pid		= find_get_pid(pid),
1718 		.wo_flags	= WEXITED,
1719 	};
1720 	int ret;
1721 
1722 	ret = do_wait(&wo);
1723 	if (ret > 0 && wo.wo_stat)
1724 		*stat = wo.wo_stat;
1725 	put_pid(wo.wo_pid);
1726 	return ret;
1727 }
1728 
SYSCALL_DEFINE4(wait4,pid_t,upid,int __user *,stat_addr,int,options,struct rusage __user *,ru)1729 SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
1730 		int, options, struct rusage __user *, ru)
1731 {
1732 	struct rusage r;
1733 	long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL);
1734 
1735 	if (err > 0) {
1736 		if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1737 			return -EFAULT;
1738 	}
1739 	return err;
1740 }
1741 
1742 #ifdef __ARCH_WANT_SYS_WAITPID
1743 
1744 /*
1745  * sys_waitpid() remains for compatibility. waitpid() should be
1746  * implemented by calling sys_wait4() from libc.a.
1747  */
SYSCALL_DEFINE3(waitpid,pid_t,pid,int __user *,stat_addr,int,options)1748 SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options)
1749 {
1750 	return kernel_wait4(pid, stat_addr, options, NULL);
1751 }
1752 
1753 #endif
1754 
1755 #ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(wait4,compat_pid_t,pid,compat_uint_t __user *,stat_addr,int,options,struct compat_rusage __user *,ru)1756 COMPAT_SYSCALL_DEFINE4(wait4,
1757 	compat_pid_t, pid,
1758 	compat_uint_t __user *, stat_addr,
1759 	int, options,
1760 	struct compat_rusage __user *, ru)
1761 {
1762 	struct rusage r;
1763 	long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL);
1764 	if (err > 0) {
1765 		if (ru && put_compat_rusage(&r, ru))
1766 			return -EFAULT;
1767 	}
1768 	return err;
1769 }
1770 
COMPAT_SYSCALL_DEFINE5(waitid,int,which,compat_pid_t,pid,struct compat_siginfo __user *,infop,int,options,struct compat_rusage __user *,uru)1771 COMPAT_SYSCALL_DEFINE5(waitid,
1772 		int, which, compat_pid_t, pid,
1773 		struct compat_siginfo __user *, infop, int, options,
1774 		struct compat_rusage __user *, uru)
1775 {
1776 	struct rusage ru;
1777 	struct waitid_info info = {.status = 0};
1778 	long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
1779 	int signo = 0;
1780 	if (err > 0) {
1781 		signo = SIGCHLD;
1782 		err = 0;
1783 		if (uru) {
1784 			/* kernel_waitid() overwrites everything in ru */
1785 			if (COMPAT_USE_64BIT_TIME)
1786 				err = copy_to_user(uru, &ru, sizeof(ru));
1787 			else
1788 				err = put_compat_rusage(&ru, uru);
1789 			if (err)
1790 				return -EFAULT;
1791 		}
1792 	}
1793 
1794 	if (!infop)
1795 		return err;
1796 
1797 	if (!user_write_access_begin(infop, sizeof(*infop)))
1798 		return -EFAULT;
1799 
1800 	unsafe_put_user(signo, &infop->si_signo, Efault);
1801 	unsafe_put_user(0, &infop->si_errno, Efault);
1802 	unsafe_put_user(info.cause, &infop->si_code, Efault);
1803 	unsafe_put_user(info.pid, &infop->si_pid, Efault);
1804 	unsafe_put_user(info.uid, &infop->si_uid, Efault);
1805 	unsafe_put_user(info.status, &infop->si_status, Efault);
1806 	user_write_access_end();
1807 	return err;
1808 Efault:
1809 	user_write_access_end();
1810 	return -EFAULT;
1811 }
1812 #endif
1813 
1814 /**
1815  * thread_group_exited - check that a thread group has exited
1816  * @pid: tgid of thread group to be checked.
1817  *
1818  * Test if the thread group represented by tgid has exited (all
1819  * threads are zombies, dead or completely gone).
1820  *
1821  * Return: true if the thread group has exited. false otherwise.
1822  */
thread_group_exited(struct pid * pid)1823 bool thread_group_exited(struct pid *pid)
1824 {
1825 	struct task_struct *task;
1826 	bool exited;
1827 
1828 	rcu_read_lock();
1829 	task = pid_task(pid, PIDTYPE_PID);
1830 	exited = !task ||
1831 		(READ_ONCE(task->exit_state) && thread_group_empty(task));
1832 	rcu_read_unlock();
1833 
1834 	return exited;
1835 }
1836 EXPORT_SYMBOL(thread_group_exited);
1837 
abort(void)1838 __weak void abort(void)
1839 {
1840 	BUG();
1841 
1842 	/* if that doesn't kill us, halt */
1843 	panic("Oops failed to kill thread");
1844 }
1845 EXPORT_SYMBOL(abort);
1846