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