projects/linux·blob v7.2-rc1 · refs

2033 lines · 50.4 KiB

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