projects/linux·blob 4982d355 · refs

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