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 */
87 static unsigned int oops_limit = 10000;
88
89 #ifdef CONFIG_SYSCTL
90 static 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
kernel_exit_sysctls_init(void)100 static __init int kernel_exit_sysctls_init(void)
101 {
102 register_sysctl_init("kernel", kern_exit_table);
103 return 0;
104 }
105 late_initcall(kernel_exit_sysctls_init);
106 #endif
107
108 static atomic_t oops_count = ATOMIC_INIT(0);
109
110 #ifdef CONFIG_SYSFS
oops_count_show(struct kobject * kobj,struct kobj_attribute * attr,char * page)111 static ssize_t oops_count_show(struct kobject *kobj, struct kobj_attribute *attr,
112 char *page)
113 {
114 return sysfs_emit(page, "%d\n", atomic_read(&oops_count));
115 }
116
117 static struct kobj_attribute oops_count_attr = __ATTR_RO(oops_count);
118
kernel_exit_sysfs_init(void)119 static __init int kernel_exit_sysfs_init(void)
120 {
121 sysfs_add_file_to_group(kernel_kobj, &oops_count_attr.attr, NULL);
122 return 0;
123 }
124 late_initcall(kernel_exit_sysfs_init);
125 #endif
126
127 /*
128 * For things release_task() would like to do *after* tasklist_lock is released.
129 */
130 struct release_task_post {
131 struct pid *pids[PIDTYPE_MAX];
132 };
133
__unhash_process(struct release_task_post * post,struct task_struct * p,bool group_dead)134 static 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 */
__exit_signal(struct release_task_post * post,struct task_struct * tsk)159 static 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
delayed_put_task_struct(struct rcu_head * rhp)223 static 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
put_task_struct_rcu_user(struct task_struct * task)234 void 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
release_thread(struct task_struct * dead_task)240 void __weak release_thread(struct task_struct *dead_task)
241 {
242 }
243
release_task(struct task_struct * p)244 void 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;
250 repeat:
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
rcuwait_wake_up(struct rcuwait * w)314 int 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 }
341 EXPORT_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 */
will_become_orphaned_pgrp(struct pid * pgrp,struct task_struct * ignored_task)351 static 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
is_current_pgrp_orphaned(void)370 int 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
has_stopped_jobs(struct pid * pgrp)381 static 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 */
398 static void
kill_orphaned_pgrp(struct task_struct * tsk,struct task_struct * parent)399 kill_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
coredump_task_exit(struct task_struct * tsk,struct core_state * core_state)424 static 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 */
__try_to_set_owner(struct task_struct * tsk,struct mm_struct * mm)452 static 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
try_to_set_owner(struct task_struct * g,struct mm_struct * mm)468 static 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 */
mm_update_next_owner(struct mm_struct * mm)487 void 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 /*
547 * Turn us into a lazy TLB process if we
548 * aren't already..
549 */
exit_mm(void)550 static void exit_mm(void)
551 {
552 struct mm_struct *mm = current->mm;
553
554 exit_mm_release(current, mm);
555 if (!mm)
556 return;
557 mmap_read_lock(mm);
558 mmgrab_lazy_tlb(mm);
559 BUG_ON(mm != current->active_mm);
560 /* more a memory barrier than a real lock */
561 task_lock(current);
562 /*
563 * When a thread stops operating on an address space, the loop
564 * in membarrier_private_expedited() may not observe that
565 * tsk->mm, and the loop in membarrier_global_expedited() may
566 * not observe a MEMBARRIER_STATE_GLOBAL_EXPEDITED
567 * rq->membarrier_state, so those would not issue an IPI.
568 * Membarrier requires a memory barrier after accessing
569 * user-space memory, before clearing tsk->mm or the
570 * rq->membarrier_state.
571 */
572 smp_mb__after_spinlock();
573 local_irq_disable();
574 current->mm = NULL;
575 membarrier_update_current_mm(NULL);
576 enter_lazy_tlb(mm, current);
577 local_irq_enable();
578 task_unlock(current);
579 mmap_read_unlock(mm);
580 mm_update_next_owner(mm);
581 mmput(mm);
582 if (test_thread_flag(TIF_MEMDIE))
583 exit_oom_victim();
584 }
585
find_alive_thread(struct task_struct * p)586 static struct task_struct *find_alive_thread(struct task_struct *p)
587 {
588 struct task_struct *t;
589
590 for_each_thread(p, t) {
591 if (!(t->flags & PF_EXITING))
592 return t;
593 }
594 return NULL;
595 }
596
find_child_reaper(struct task_struct * father,struct list_head * dead)597 static struct task_struct *find_child_reaper(struct task_struct *father,
598 struct list_head *dead)
599 __releases(&tasklist_lock)
600 __acquires(&tasklist_lock)
601 {
602 struct pid_namespace *pid_ns = task_active_pid_ns(father);
603 struct task_struct *reaper = pid_ns->child_reaper;
604 struct task_struct *p, *n;
605
606 if (likely(reaper != father))
607 return reaper;
608
609 reaper = find_alive_thread(father);
610 if (reaper) {
611 pid_ns->child_reaper = reaper;
612 return reaper;
613 }
614
615 write_unlock_irq(&tasklist_lock);
616
617 list_for_each_entry_safe(p, n, dead, ptrace_entry) {
618 list_del_init(&p->ptrace_entry);
619 release_task(p);
620 }
621
622 zap_pid_ns_processes(pid_ns);
623 write_lock_irq(&tasklist_lock);
624
625 return father;
626 }
627
628 /*
629 * When we die, we re-parent all our children, and try to:
630 * 1. give them to another thread in our thread group, if such a member exists
631 * 2. give it to the first ancestor process which prctl'd itself as a
632 * child_subreaper for its children (like a service manager)
633 * 3. give it to the init process (PID 1) in our pid namespace
634 */
find_new_reaper(struct task_struct * father,struct task_struct * child_reaper)635 static struct task_struct *find_new_reaper(struct task_struct *father,
636 struct task_struct *child_reaper)
637 {
638 struct task_struct *thread, *reaper;
639
640 thread = find_alive_thread(father);
641 if (thread)
642 return thread;
643
644 if (father->signal->has_child_subreaper) {
645 unsigned int ns_level = task_pid(father)->level;
646 /*
647 * Find the first ->is_child_subreaper ancestor in our pid_ns.
648 * We can't check reaper != child_reaper to ensure we do not
649 * cross the namespaces, the exiting parent could be injected
650 * by setns() + fork().
651 * We check pid->level, this is slightly more efficient than
652 * task_active_pid_ns(reaper) != task_active_pid_ns(father).
653 */
654 for (reaper = father->real_parent;
655 task_pid(reaper)->level == ns_level;
656 reaper = reaper->real_parent) {
657 if (reaper == &init_task)
658 break;
659 if (!reaper->signal->is_child_subreaper)
660 continue;
661 thread = find_alive_thread(reaper);
662 if (thread)
663 return thread;
664 }
665 }
666
667 return child_reaper;
668 }
669
670 /*
671 * Any that need to be release_task'd are put on the @dead list.
672 */
reparent_leader(struct task_struct * father,struct task_struct * p,struct list_head * dead)673 static void reparent_leader(struct task_struct *father, struct task_struct *p,
674 struct list_head *dead)
675 {
676 if (unlikely(p->exit_state == EXIT_DEAD))
677 return;
678
679 /* We don't want people slaying init. */
680 p->exit_signal = SIGCHLD;
681
682 /* If it has exited notify the new parent about this child's death. */
683 if (!p->ptrace &&
684 p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) {
685 if (do_notify_parent(p, p->exit_signal)) {
686 p->exit_state = EXIT_DEAD;
687 list_add(&p->ptrace_entry, dead);
688 }
689 }
690
691 kill_orphaned_pgrp(p, father);
692 }
693
694 /*
695 * Make init inherit all the child processes
696 */
forget_original_parent(struct task_struct * father,struct list_head * dead)697 static void forget_original_parent(struct task_struct *father,
698 struct list_head *dead)
699 {
700 struct task_struct *p, *t, *reaper;
701
702 if (unlikely(!list_empty(&father->ptraced)))
703 exit_ptrace(father, dead);
704
705 /* Can drop and reacquire tasklist_lock */
706 reaper = find_child_reaper(father, dead);
707 if (list_empty(&father->children))
708 return;
709
710 reaper = find_new_reaper(father, reaper);
711 list_for_each_entry(p, &father->children, sibling) {
712 for_each_thread(p, t) {
713 RCU_INIT_POINTER(t->real_parent, reaper);
714 BUG_ON((!t->ptrace) != (rcu_access_pointer(t->parent) == father));
715 if (likely(!t->ptrace))
716 t->parent = t->real_parent;
717 if (t->pdeath_signal)
718 group_send_sig_info(t->pdeath_signal,
719 SEND_SIG_NOINFO, t,
720 PIDTYPE_TGID);
721 }
722 /*
723 * If this is a threaded reparent there is no need to
724 * notify anyone anything has happened.
725 */
726 if (!same_thread_group(reaper, father))
727 reparent_leader(father, p, dead);
728 }
729 list_splice_tail_init(&father->children, &reaper->children);
730 }
731
732 /*
733 * Send signals to all our closest relatives so that they know
734 * to properly mourn us..
735 */
exit_notify(struct task_struct * tsk,int group_dead)736 static void exit_notify(struct task_struct *tsk, int group_dead)
737 {
738 bool autoreap;
739 struct task_struct *p, *n;
740 LIST_HEAD(dead);
741
742 write_lock_irq(&tasklist_lock);
743 forget_original_parent(tsk, &dead);
744
745 if (group_dead)
746 kill_orphaned_pgrp(tsk->group_leader, NULL);
747
748 tsk->exit_state = EXIT_ZOMBIE;
749
750 if (unlikely(tsk->ptrace)) {
751 int sig = thread_group_leader(tsk) &&
752 thread_group_empty(tsk) &&
753 !ptrace_reparented(tsk) ?
754 tsk->exit_signal : SIGCHLD;
755 autoreap = do_notify_parent(tsk, sig);
756 } else if (thread_group_leader(tsk)) {
757 autoreap = thread_group_empty(tsk) &&
758 do_notify_parent(tsk, tsk->exit_signal);
759 } else {
760 autoreap = true;
761 /* untraced sub-thread */
762 do_notify_pidfd(tsk);
763 }
764
765 if (autoreap) {
766 tsk->exit_state = EXIT_DEAD;
767 list_add(&tsk->ptrace_entry, &dead);
768 }
769
770 /* mt-exec, de_thread() is waiting for group leader */
771 if (unlikely(tsk->signal->notify_count < 0))
772 wake_up_process(tsk->signal->group_exec_task);
773 write_unlock_irq(&tasklist_lock);
774
775 list_for_each_entry_safe(p, n, &dead, ptrace_entry) {
776 list_del_init(&p->ptrace_entry);
777 release_task(p);
778 }
779 }
780
781 #ifdef CONFIG_DEBUG_STACK_USAGE
782 #ifdef CONFIG_STACK_GROWSUP
stack_not_used(struct task_struct * p)783 unsigned long stack_not_used(struct task_struct *p)
784 {
785 unsigned long *n = end_of_stack(p);
786
787 do { /* Skip over canary */
788 n--;
789 } while (!*n);
790
791 return (unsigned long)end_of_stack(p) - (unsigned long)n;
792 }
793 #else /* !CONFIG_STACK_GROWSUP */
stack_not_used(struct task_struct * p)794 unsigned long stack_not_used(struct task_struct *p)
795 {
796 unsigned long *n = end_of_stack(p);
797
798 do { /* Skip over canary */
799 n++;
800 } while (!*n);
801
802 return (unsigned long)n - (unsigned long)end_of_stack(p);
803 }
804 #endif /* CONFIG_STACK_GROWSUP */
805
806 /* Count the maximum pages reached in kernel stacks */
kstack_histogram(unsigned long used_stack)807 static inline void kstack_histogram(unsigned long used_stack)
808 {
809 #ifdef CONFIG_VM_EVENT_COUNTERS
810 if (used_stack <= 1024)
811 count_vm_event(KSTACK_1K);
812 #if THREAD_SIZE > 1024
813 else if (used_stack <= 2048)
814 count_vm_event(KSTACK_2K);
815 #endif
816 #if THREAD_SIZE > 2048
817 else if (used_stack <= 4096)
818 count_vm_event(KSTACK_4K);
819 #endif
820 #if THREAD_SIZE > 4096
821 else if (used_stack <= 8192)
822 count_vm_event(KSTACK_8K);
823 #endif
824 #if THREAD_SIZE > 8192
825 else if (used_stack <= 16384)
826 count_vm_event(KSTACK_16K);
827 #endif
828 #if THREAD_SIZE > 16384
829 else if (used_stack <= 32768)
830 count_vm_event(KSTACK_32K);
831 #endif
832 #if THREAD_SIZE > 32768
833 else if (used_stack <= 65536)
834 count_vm_event(KSTACK_64K);
835 #endif
836 #if THREAD_SIZE > 65536
837 else
838 count_vm_event(KSTACK_REST);
839 #endif
840 #endif /* CONFIG_VM_EVENT_COUNTERS */
841 }
842
check_stack_usage(void)843 static void check_stack_usage(void)
844 {
845 static DEFINE_SPINLOCK(low_water_lock);
846 static int lowest_to_date = THREAD_SIZE;
847 unsigned long free;
848
849 free = stack_not_used(current);
850 kstack_histogram(THREAD_SIZE - free);
851
852 if (free >= lowest_to_date)
853 return;
854
855 spin_lock(&low_water_lock);
856 if (free < lowest_to_date) {
857 pr_info("%s (%d) used greatest stack depth: %lu bytes left\n",
858 current->comm, task_pid_nr(current), free);
859 lowest_to_date = free;
860 }
861 spin_unlock(&low_water_lock);
862 }
863 #else /* !CONFIG_DEBUG_STACK_USAGE */
check_stack_usage(void)864 static inline void check_stack_usage(void) {}
865 #endif /* CONFIG_DEBUG_STACK_USAGE */
866
synchronize_group_exit(struct task_struct * tsk,long code)867 static void synchronize_group_exit(struct task_struct *tsk, long code)
868 {
869 struct sighand_struct *sighand = tsk->sighand;
870 struct signal_struct *signal = tsk->signal;
871 struct core_state *core_state;
872
873 spin_lock_irq(&sighand->siglock);
874 signal->quick_threads--;
875 if ((signal->quick_threads == 0) &&
876 !(signal->flags & SIGNAL_GROUP_EXIT)) {
877 signal->flags = SIGNAL_GROUP_EXIT;
878 signal->group_exit_code = code;
879 signal->group_stop_count = 0;
880 }
881 /*
882 * Serialize with any possible pending coredump.
883 * We must hold siglock around checking core_state
884 * and setting PF_POSTCOREDUMP. The core-inducing thread
885 * will increment ->nr_threads for each thread in the
886 * group without PF_POSTCOREDUMP set.
887 */
888 tsk->flags |= PF_POSTCOREDUMP;
889 core_state = signal->core_state;
890 spin_unlock_irq(&sighand->siglock);
891
892 if (unlikely(core_state))
893 coredump_task_exit(tsk, core_state);
894 }
895
do_exit(long code)896 void __noreturn do_exit(long code)
897 {
898 struct task_struct *tsk = current;
899 int group_dead;
900
901 WARN_ON(irqs_disabled());
902 WARN_ON(tsk->plug);
903
904 kcov_task_exit(tsk);
905 kmsan_task_exit(tsk);
906
907 synchronize_group_exit(tsk, code);
908 ptrace_event(PTRACE_EVENT_EXIT, code);
909 user_events_exit(tsk);
910
911 io_uring_files_cancel();
912 sched_mm_cid_exit(tsk);
913 exit_signals(tsk); /* sets PF_EXITING */
914
915 seccomp_filter_release(tsk);
916
917 acct_update_integrals(tsk);
918 group_dead = atomic_dec_and_test(&tsk->signal->live);
919 if (group_dead) {
920 /*
921 * If the last thread of global init has exited, panic
922 * immediately to get a useable coredump.
923 */
924 if (unlikely(is_global_init(tsk)))
925 panic("Attempted to kill init! exitcode=0x%08x\n",
926 tsk->signal->group_exit_code ?: (int)code);
927
928 #ifdef CONFIG_POSIX_TIMERS
929 hrtimer_cancel(&tsk->signal->real_timer);
930 exit_itimers(tsk);
931 #endif
932 if (tsk->mm)
933 setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
934 }
935 acct_collect(code, group_dead);
936 if (group_dead)
937 tty_audit_exit();
938 audit_free(tsk);
939
940 tsk->exit_code = code;
941 taskstats_exit(tsk, group_dead);
942 trace_sched_process_exit(tsk, group_dead);
943
944 /*
945 * Since sampling can touch ->mm, make sure to stop everything before we
946 * tear it down.
947 *
948 * Also flushes inherited counters to the parent - before the parent
949 * gets woken up by child-exit notifications.
950 */
951 perf_event_exit_task(tsk);
952 /*
953 * PF_EXITING (above) ensures unwind_deferred_request() will no
954 * longer add new unwinds. While exit_mm() (below) will destroy the
955 * abaility to do unwinds. So flush any pending unwinds here.
956 */
957 unwind_deferred_task_exit(tsk);
958
959 exit_mm();
960
961 if (group_dead)
962 acct_process();
963
964 exit_sem(tsk);
965 exit_shm(tsk);
966 exit_files(tsk);
967 exit_fs(tsk);
968 if (group_dead)
969 disassociate_ctty(1);
970 exit_nsproxy_namespaces(tsk);
971 exit_task_work(tsk);
972 exit_thread(tsk);
973
974 sched_autogroup_exit_task(tsk);
975 cgroup_task_exit(tsk);
976
977 /*
978 * FIXME: do that only when needed, using sched_exit tracepoint
979 */
980 flush_ptrace_hw_breakpoint(tsk);
981
982 exit_tasks_rcu_start();
983 exit_notify(tsk, group_dead);
984 proc_exit_connector(tsk);
985 mpol_put_task_policy(tsk);
986 #ifdef CONFIG_FUTEX
987 if (unlikely(current->pi_state_cache))
988 kfree(current->pi_state_cache);
989 #endif
990 /*
991 * Make sure we are holding no locks:
992 */
993 debug_check_no_locks_held();
994
995 if (tsk->io_context)
996 exit_io_context(tsk);
997
998 if (tsk->splice_pipe)
999 free_pipe_info(tsk->splice_pipe);
1000
1001 if (tsk->task_frag.page)
1002 put_page(tsk->task_frag.page);
1003
1004 exit_task_stack_account(tsk);
1005
1006 check_stack_usage();
1007 preempt_disable();
1008 if (tsk->nr_dirtied)
1009 __this_cpu_add(dirty_throttle_leaks, tsk->nr_dirtied);
1010 exit_rcu();
1011 exit_tasks_rcu_finish();
1012
1013 lockdep_free_task(tsk);
1014 do_task_dead();
1015 }
1016
make_task_dead(int signr)1017 void __noreturn make_task_dead(int signr)
1018 {
1019 /*
1020 * Take the task off the cpu after something catastrophic has
1021 * happened.
1022 *
1023 * We can get here from a kernel oops, sometimes with preemption off.
1024 * Start by checking for critical errors.
1025 * Then fix up important state like USER_DS and preemption.
1026 * Then do everything else.
1027 */
1028 struct task_struct *tsk = current;
1029 unsigned int limit;
1030
1031 if (unlikely(in_interrupt()))
1032 panic("Aiee, killing interrupt handler!");
1033 if (unlikely(!tsk->pid))
1034 panic("Attempted to kill the idle task!");
1035
1036 if (unlikely(irqs_disabled())) {
1037 pr_info("note: %s[%d] exited with irqs disabled\n",
1038 current->comm, task_pid_nr(current));
1039 local_irq_enable();
1040 }
1041 if (unlikely(in_atomic())) {
1042 pr_info("note: %s[%d] exited with preempt_count %d\n",
1043 current->comm, task_pid_nr(current),
1044 preempt_count());
1045 preempt_count_set(PREEMPT_ENABLED);
1046 }
1047
1048 /*
1049 * Every time the system oopses, if the oops happens while a reference
1050 * to an object was held, the reference leaks.
1051 * If the oops doesn't also leak memory, repeated oopsing can cause
1052 * reference counters to wrap around (if they're not using refcount_t).
1053 * This means that repeated oopsing can make unexploitable-looking bugs
1054 * exploitable through repeated oopsing.
1055 * To make sure this can't happen, place an upper bound on how often the
1056 * kernel may oops without panic().
1057 */
1058 limit = READ_ONCE(oops_limit);
1059 if (atomic_inc_return(&oops_count) >= limit && limit)
1060 panic("Oopsed too often (kernel.oops_limit is %d)", limit);
1061
1062 /*
1063 * We're taking recursive faults here in make_task_dead. Safest is to just
1064 * leave this task alone and wait for reboot.
1065 */
1066 if (unlikely(tsk->flags & PF_EXITING)) {
1067 pr_alert("Fixing recursive fault but reboot is needed!\n");
1068 futex_exit_recursive(tsk);
1069 tsk->exit_state = EXIT_DEAD;
1070 refcount_inc(&tsk->rcu_users);
1071 do_task_dead();
1072 }
1073
1074 do_exit(signr);
1075 }
1076
SYSCALL_DEFINE1(exit,int,error_code)1077 SYSCALL_DEFINE1(exit, int, error_code)
1078 {
1079 do_exit((error_code&0xff)<<8);
1080 }
1081
1082 /*
1083 * Take down every thread in the group. This is called by fatal signals
1084 * as well as by sys_exit_group (below).
1085 */
1086 void __noreturn
do_group_exit(int exit_code)1087 do_group_exit(int exit_code)
1088 {
1089 struct signal_struct *sig = current->signal;
1090
1091 if (sig->flags & SIGNAL_GROUP_EXIT)
1092 exit_code = sig->group_exit_code;
1093 else if (sig->group_exec_task)
1094 exit_code = 0;
1095 else {
1096 struct sighand_struct *const sighand = current->sighand;
1097
1098 spin_lock_irq(&sighand->siglock);
1099 if (sig->flags & SIGNAL_GROUP_EXIT)
1100 /* Another thread got here before we took the lock. */
1101 exit_code = sig->group_exit_code;
1102 else if (sig->group_exec_task)
1103 exit_code = 0;
1104 else {
1105 sig->group_exit_code = exit_code;
1106 sig->flags = SIGNAL_GROUP_EXIT;
1107 zap_other_threads(current);
1108 }
1109 spin_unlock_irq(&sighand->siglock);
1110 }
1111
1112 do_exit(exit_code);
1113 /* NOTREACHED */
1114 }
1115
1116 /*
1117 * this kills every thread in the thread group. Note that any externally
1118 * wait4()-ing process will get the correct exit code - even if this
1119 * thread is not the thread group leader.
1120 */
SYSCALL_DEFINE1(exit_group,int,error_code)1121 SYSCALL_DEFINE1(exit_group, int, error_code)
1122 {
1123 do_group_exit((error_code & 0xff) << 8);
1124 /* NOTREACHED */
1125 return 0;
1126 }
1127
eligible_pid(struct wait_opts * wo,struct task_struct * p)1128 static int eligible_pid(struct wait_opts *wo, struct task_struct *p)
1129 {
1130 return wo->wo_type == PIDTYPE_MAX ||
1131 task_pid_type(p, wo->wo_type) == wo->wo_pid;
1132 }
1133
1134 static int
eligible_child(struct wait_opts * wo,bool ptrace,struct task_struct * p)1135 eligible_child(struct wait_opts *wo, bool ptrace, struct task_struct *p)
1136 {
1137 if (!eligible_pid(wo, p))
1138 return 0;
1139
1140 /*
1141 * Wait for all children (clone and not) if __WALL is set or
1142 * if it is traced by us.
1143 */
1144 if (ptrace || (wo->wo_flags & __WALL))
1145 return 1;
1146
1147 /*
1148 * Otherwise, wait for clone children *only* if __WCLONE is set;
1149 * otherwise, wait for non-clone children *only*.
1150 *
1151 * Note: a "clone" child here is one that reports to its parent
1152 * using a signal other than SIGCHLD, or a non-leader thread which
1153 * we can only see if it is traced by us.
1154 */
1155 if ((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE))
1156 return 0;
1157
1158 return 1;
1159 }
1160
1161 /*
1162 * Handle sys_wait4 work for one task in state EXIT_ZOMBIE. We hold
1163 * read_lock(&tasklist_lock) on entry. If we return zero, we still hold
1164 * the lock and this task is uninteresting. If we return nonzero, we have
1165 * released the lock and the system call should return.
1166 */
wait_task_zombie(struct wait_opts * wo,struct task_struct * p)1167 static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p)
1168 {
1169 int state, status;
1170 pid_t pid = task_pid_vnr(p);
1171 uid_t uid = from_kuid_munged(current_user_ns(), task_uid(p));
1172 struct waitid_info *infop;
1173
1174 if (!likely(wo->wo_flags & WEXITED))
1175 return 0;
1176
1177 if (unlikely(wo->wo_flags & WNOWAIT)) {
1178 status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1179 ? p->signal->group_exit_code : p->exit_code;
1180 get_task_struct(p);
1181 read_unlock(&tasklist_lock);
1182 sched_annotate_sleep();
1183 if (wo->wo_rusage)
1184 getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1185 put_task_struct(p);
1186 goto out_info;
1187 }
1188 /*
1189 * Move the task's state to DEAD/TRACE, only one thread can do this.
1190 */
1191 state = (ptrace_reparented(p) && thread_group_leader(p)) ?
1192 EXIT_TRACE : EXIT_DEAD;
1193 if (cmpxchg(&p->exit_state, EXIT_ZOMBIE, state) != EXIT_ZOMBIE)
1194 return 0;
1195 /*
1196 * We own this thread, nobody else can reap it.
1197 */
1198 read_unlock(&tasklist_lock);
1199 sched_annotate_sleep();
1200
1201 /*
1202 * Check thread_group_leader() to exclude the traced sub-threads.
1203 */
1204 if (state == EXIT_DEAD && thread_group_leader(p)) {
1205 struct signal_struct *sig = p->signal;
1206 struct signal_struct *psig = current->signal;
1207 unsigned long maxrss;
1208 u64 tgutime, tgstime;
1209
1210 /*
1211 * The resource counters for the group leader are in its
1212 * own task_struct. Those for dead threads in the group
1213 * are in its signal_struct, as are those for the child
1214 * processes it has previously reaped. All these
1215 * accumulate in the parent's signal_struct c* fields.
1216 *
1217 * We don't bother to take a lock here to protect these
1218 * p->signal fields because the whole thread group is dead
1219 * and nobody can change them.
1220 *
1221 * psig->stats_lock also protects us from our sub-threads
1222 * which can reap other children at the same time.
1223 *
1224 * We use thread_group_cputime_adjusted() to get times for
1225 * the thread group, which consolidates times for all threads
1226 * in the group including the group leader.
1227 */
1228 thread_group_cputime_adjusted(p, &tgutime, &tgstime);
1229 write_seqlock_irq(&psig->stats_lock);
1230 psig->cutime += tgutime + sig->cutime;
1231 psig->cstime += tgstime + sig->cstime;
1232 psig->cgtime += task_gtime(p) + sig->gtime + sig->cgtime;
1233 psig->cmin_flt +=
1234 p->min_flt + sig->min_flt + sig->cmin_flt;
1235 psig->cmaj_flt +=
1236 p->maj_flt + sig->maj_flt + sig->cmaj_flt;
1237 psig->cnvcsw +=
1238 p->nvcsw + sig->nvcsw + sig->cnvcsw;
1239 psig->cnivcsw +=
1240 p->nivcsw + sig->nivcsw + sig->cnivcsw;
1241 psig->cinblock +=
1242 task_io_get_inblock(p) +
1243 sig->inblock + sig->cinblock;
1244 psig->coublock +=
1245 task_io_get_oublock(p) +
1246 sig->oublock + sig->coublock;
1247 maxrss = max(sig->maxrss, sig->cmaxrss);
1248 if (psig->cmaxrss < maxrss)
1249 psig->cmaxrss = maxrss;
1250 task_io_accounting_add(&psig->ioac, &p->ioac);
1251 task_io_accounting_add(&psig->ioac, &sig->ioac);
1252 write_sequnlock_irq(&psig->stats_lock);
1253 }
1254
1255 if (wo->wo_rusage)
1256 getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1257 status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1258 ? p->signal->group_exit_code : p->exit_code;
1259 wo->wo_stat = status;
1260
1261 if (state == EXIT_TRACE) {
1262 write_lock_irq(&tasklist_lock);
1263 /* We dropped tasklist, ptracer could die and untrace */
1264 ptrace_unlink(p);
1265
1266 /* If parent wants a zombie, don't release it now */
1267 state = EXIT_ZOMBIE;
1268 if (do_notify_parent(p, p->exit_signal))
1269 state = EXIT_DEAD;
1270 p->exit_state = state;
1271 write_unlock_irq(&tasklist_lock);
1272 }
1273 if (state == EXIT_DEAD)
1274 release_task(p);
1275
1276 out_info:
1277 infop = wo->wo_info;
1278 if (infop) {
1279 if ((status & 0x7f) == 0) {
1280 infop->cause = CLD_EXITED;
1281 infop->status = status >> 8;
1282 } else {
1283 infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
1284 infop->status = status & 0x7f;
1285 }
1286 infop->pid = pid;
1287 infop->uid = uid;
1288 }
1289
1290 return pid;
1291 }
1292
task_stopped_code(struct task_struct * p,bool ptrace)1293 static int *task_stopped_code(struct task_struct *p, bool ptrace)
1294 {
1295 if (ptrace) {
1296 if (task_is_traced(p) && !(p->jobctl & JOBCTL_LISTENING))
1297 return &p->exit_code;
1298 } else {
1299 if (p->signal->flags & SIGNAL_STOP_STOPPED)
1300 return &p->signal->group_exit_code;
1301 }
1302 return NULL;
1303 }
1304
1305 /**
1306 * wait_task_stopped - Wait for %TASK_STOPPED or %TASK_TRACED
1307 * @wo: wait options
1308 * @ptrace: is the wait for ptrace
1309 * @p: task to wait for
1310 *
1311 * Handle sys_wait4() work for %p in state %TASK_STOPPED or %TASK_TRACED.
1312 *
1313 * CONTEXT:
1314 * read_lock(&tasklist_lock), which is released if return value is
1315 * non-zero. Also, grabs and releases @p->sighand->siglock.
1316 *
1317 * RETURNS:
1318 * 0 if wait condition didn't exist and search for other wait conditions
1319 * should continue. Non-zero return, -errno on failure and @p's pid on
1320 * success, implies that tasklist_lock is released and wait condition
1321 * search should terminate.
1322 */
wait_task_stopped(struct wait_opts * wo,int ptrace,struct task_struct * p)1323 static int wait_task_stopped(struct wait_opts *wo,
1324 int ptrace, struct task_struct *p)
1325 {
1326 struct waitid_info *infop;
1327 int exit_code, *p_code, why;
1328 uid_t uid = 0; /* unneeded, required by compiler */
1329 pid_t pid;
1330
1331 /*
1332 * Traditionally we see ptrace'd stopped tasks regardless of options.
1333 */
1334 if (!ptrace && !(wo->wo_flags & WUNTRACED))
1335 return 0;
1336
1337 if (!task_stopped_code(p, ptrace))
1338 return 0;
1339
1340 exit_code = 0;
1341 spin_lock_irq(&p->sighand->siglock);
1342
1343 p_code = task_stopped_code(p, ptrace);
1344 if (unlikely(!p_code))
1345 goto unlock_sig;
1346
1347 exit_code = *p_code;
1348 if (!exit_code)
1349 goto unlock_sig;
1350
1351 if (!unlikely(wo->wo_flags & WNOWAIT))
1352 *p_code = 0;
1353
1354 uid = from_kuid_munged(current_user_ns(), task_uid(p));
1355 unlock_sig:
1356 spin_unlock_irq(&p->sighand->siglock);
1357 if (!exit_code)
1358 return 0;
1359
1360 /*
1361 * Now we are pretty sure this task is interesting.
1362 * Make sure it doesn't get reaped out from under us while we
1363 * give up the lock and then examine it below. We don't want to
1364 * keep holding onto the tasklist_lock while we call getrusage and
1365 * possibly take page faults for user memory.
1366 */
1367 get_task_struct(p);
1368 pid = task_pid_vnr(p);
1369 why = ptrace ? CLD_TRAPPED : CLD_STOPPED;
1370 read_unlock(&tasklist_lock);
1371 sched_annotate_sleep();
1372 if (wo->wo_rusage)
1373 getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1374 put_task_struct(p);
1375
1376 if (likely(!(wo->wo_flags & WNOWAIT)))
1377 wo->wo_stat = (exit_code << 8) | 0x7f;
1378
1379 infop = wo->wo_info;
1380 if (infop) {
1381 infop->cause = why;
1382 infop->status = exit_code;
1383 infop->pid = pid;
1384 infop->uid = uid;
1385 }
1386 return pid;
1387 }
1388
1389 /*
1390 * Handle do_wait work for one task in a live, non-stopped state.
1391 * read_lock(&tasklist_lock) on entry. If we return zero, we still hold
1392 * the lock and this task is uninteresting. If we return nonzero, we have
1393 * released the lock and the system call should return.
1394 */
wait_task_continued(struct wait_opts * wo,struct task_struct * p)1395 static int wait_task_continued(struct wait_opts *wo, struct task_struct *p)
1396 {
1397 struct waitid_info *infop;
1398 pid_t pid;
1399 uid_t uid;
1400
1401 if (!unlikely(wo->wo_flags & WCONTINUED))
1402 return 0;
1403
1404 if (!(p->signal->flags & SIGNAL_STOP_CONTINUED))
1405 return 0;
1406
1407 spin_lock_irq(&p->sighand->siglock);
1408 /* Re-check with the lock held. */
1409 if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) {
1410 spin_unlock_irq(&p->sighand->siglock);
1411 return 0;
1412 }
1413 if (!unlikely(wo->wo_flags & WNOWAIT))
1414 p->signal->flags &= ~SIGNAL_STOP_CONTINUED;
1415 uid = from_kuid_munged(current_user_ns(), task_uid(p));
1416 spin_unlock_irq(&p->sighand->siglock);
1417
1418 pid = task_pid_vnr(p);
1419 get_task_struct(p);
1420 read_unlock(&tasklist_lock);
1421 sched_annotate_sleep();
1422 if (wo->wo_rusage)
1423 getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
1424 put_task_struct(p);
1425
1426 infop = wo->wo_info;
1427 if (!infop) {
1428 wo->wo_stat = 0xffff;
1429 } else {
1430 infop->cause = CLD_CONTINUED;
1431 infop->pid = pid;
1432 infop->uid = uid;
1433 infop->status = SIGCONT;
1434 }
1435 return pid;
1436 }
1437
1438 /*
1439 * Consider @p for a wait by @parent.
1440 *
1441 * -ECHILD should be in ->notask_error before the first call.
1442 * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1443 * Returns zero if the search for a child should continue;
1444 * then ->notask_error is 0 if @p is an eligible child,
1445 * or still -ECHILD.
1446 */
wait_consider_task(struct wait_opts * wo,int ptrace,struct task_struct * p)1447 static int wait_consider_task(struct wait_opts *wo, int ptrace,
1448 struct task_struct *p)
1449 {
1450 /*
1451 * We can race with wait_task_zombie() from another thread.
1452 * Ensure that EXIT_ZOMBIE -> EXIT_DEAD/EXIT_TRACE transition
1453 * can't confuse the checks below.
1454 */
1455 int exit_state = READ_ONCE(p->exit_state);
1456 int ret;
1457
1458 if (unlikely(exit_state == EXIT_DEAD))
1459 return 0;
1460
1461 ret = eligible_child(wo, ptrace, p);
1462 if (!ret)
1463 return ret;
1464
1465 if (unlikely(exit_state == EXIT_TRACE)) {
1466 /*
1467 * ptrace == 0 means we are the natural parent. In this case
1468 * we should clear notask_error, debugger will notify us.
1469 */
1470 if (likely(!ptrace))
1471 wo->notask_error = 0;
1472 return 0;
1473 }
1474
1475 if (likely(!ptrace) && unlikely(p->ptrace)) {
1476 /*
1477 * If it is traced by its real parent's group, just pretend
1478 * the caller is ptrace_do_wait() and reap this child if it
1479 * is zombie.
1480 *
1481 * This also hides group stop state from real parent; otherwise
1482 * a single stop can be reported twice as group and ptrace stop.
1483 * If a ptracer wants to distinguish these two events for its
1484 * own children it should create a separate process which takes
1485 * the role of real parent.
1486 */
1487 if (!ptrace_reparented(p))
1488 ptrace = 1;
1489 }
1490
1491 /* slay zombie? */
1492 if (exit_state == EXIT_ZOMBIE) {
1493 /* we don't reap group leaders with subthreads */
1494 if (!delay_group_leader(p)) {
1495 /*
1496 * A zombie ptracee is only visible to its ptracer.
1497 * Notification and reaping will be cascaded to the
1498 * real parent when the ptracer detaches.
1499 */
1500 if (unlikely(ptrace) || likely(!p->ptrace))
1501 return wait_task_zombie(wo, p);
1502 }
1503
1504 /*
1505 * Allow access to stopped/continued state via zombie by
1506 * falling through. Clearing of notask_error is complex.
1507 *
1508 * When !@ptrace:
1509 *
1510 * If WEXITED is set, notask_error should naturally be
1511 * cleared. If not, subset of WSTOPPED|WCONTINUED is set,
1512 * so, if there are live subthreads, there are events to
1513 * wait for. If all subthreads are dead, it's still safe
1514 * to clear - this function will be called again in finite
1515 * amount time once all the subthreads are released and
1516 * will then return without clearing.
1517 *
1518 * When @ptrace:
1519 *
1520 * Stopped state is per-task and thus can't change once the
1521 * target task dies. Only continued and exited can happen.
1522 * Clear notask_error if WCONTINUED | WEXITED.
1523 */
1524 if (likely(!ptrace) || (wo->wo_flags & (WCONTINUED | WEXITED)))
1525 wo->notask_error = 0;
1526 } else {
1527 /*
1528 * @p is alive and it's gonna stop, continue or exit, so
1529 * there always is something to wait for.
1530 */
1531 wo->notask_error = 0;
1532 }
1533
1534 /*
1535 * Wait for stopped. Depending on @ptrace, different stopped state
1536 * is used and the two don't interact with each other.
1537 */
1538 ret = wait_task_stopped(wo, ptrace, p);
1539 if (ret)
1540 return ret;
1541
1542 /*
1543 * Wait for continued. There's only one continued state and the
1544 * ptracer can consume it which can confuse the real parent. Don't
1545 * use WCONTINUED from ptracer. You don't need or want it.
1546 */
1547 return wait_task_continued(wo, p);
1548 }
1549
1550 /*
1551 * Do the work of do_wait() for one thread in the group, @tsk.
1552 *
1553 * -ECHILD should be in ->notask_error before the first call.
1554 * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1555 * Returns zero if the search for a child should continue; then
1556 * ->notask_error is 0 if there were any eligible children,
1557 * or still -ECHILD.
1558 */
do_wait_thread(struct wait_opts * wo,struct task_struct * tsk)1559 static int do_wait_thread(struct wait_opts *wo, struct task_struct *tsk)
1560 {
1561 struct task_struct *p;
1562
1563 list_for_each_entry(p, &tsk->children, sibling) {
1564 int ret = wait_consider_task(wo, 0, p);
1565
1566 if (ret)
1567 return ret;
1568 }
1569
1570 return 0;
1571 }
1572
ptrace_do_wait(struct wait_opts * wo,struct task_struct * tsk)1573 static int ptrace_do_wait(struct wait_opts *wo, struct task_struct *tsk)
1574 {
1575 struct task_struct *p;
1576
1577 list_for_each_entry(p, &tsk->ptraced, ptrace_entry) {
1578 int ret = wait_consider_task(wo, 1, p);
1579
1580 if (ret)
1581 return ret;
1582 }
1583
1584 return 0;
1585 }
1586
pid_child_should_wake(struct wait_opts * wo,struct task_struct * p)1587 bool pid_child_should_wake(struct wait_opts *wo, struct task_struct *p)
1588 {
1589 if (!eligible_pid(wo, p))
1590 return false;
1591
1592 if ((wo->wo_flags & __WNOTHREAD) && wo->child_wait.private != p->parent)
1593 return false;
1594
1595 return true;
1596 }
1597
child_wait_callback(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)1598 static int child_wait_callback(wait_queue_entry_t *wait, unsigned mode,
1599 int sync, void *key)
1600 {
1601 struct wait_opts *wo = container_of(wait, struct wait_opts,
1602 child_wait);
1603 struct task_struct *p = key;
1604
1605 if (pid_child_should_wake(wo, p))
1606 return default_wake_function(wait, mode, sync, key);
1607
1608 return 0;
1609 }
1610
__wake_up_parent(struct task_struct * p,struct task_struct * parent)1611 void __wake_up_parent(struct task_struct *p, struct task_struct *parent)
1612 {
1613 __wake_up_sync_key(&parent->signal->wait_chldexit,
1614 TASK_INTERRUPTIBLE, p);
1615 }
1616
is_effectively_child(struct wait_opts * wo,bool ptrace,struct task_struct * target)1617 static bool is_effectively_child(struct wait_opts *wo, bool ptrace,
1618 struct task_struct *target)
1619 {
1620 struct task_struct *parent =
1621 !ptrace ? target->real_parent : target->parent;
1622
1623 return current == parent || (!(wo->wo_flags & __WNOTHREAD) &&
1624 same_thread_group(current, parent));
1625 }
1626
1627 /*
1628 * Optimization for waiting on PIDTYPE_PID. No need to iterate through child
1629 * and tracee lists to find the target task.
1630 */
do_wait_pid(struct wait_opts * wo)1631 static int do_wait_pid(struct wait_opts *wo)
1632 {
1633 bool ptrace;
1634 struct task_struct *target;
1635 int retval;
1636
1637 ptrace = false;
1638 target = pid_task(wo->wo_pid, PIDTYPE_TGID);
1639 if (target && is_effectively_child(wo, ptrace, target)) {
1640 retval = wait_consider_task(wo, ptrace, target);
1641 if (retval)
1642 return retval;
1643 }
1644
1645 ptrace = true;
1646 target = pid_task(wo->wo_pid, PIDTYPE_PID);
1647 if (target && target->ptrace &&
1648 is_effectively_child(wo, ptrace, target)) {
1649 retval = wait_consider_task(wo, ptrace, target);
1650 if (retval)
1651 return retval;
1652 }
1653
1654 return 0;
1655 }
1656
__do_wait(struct wait_opts * wo)1657 long __do_wait(struct wait_opts *wo)
1658 {
1659 long retval;
1660
1661 /*
1662 * If there is nothing that can match our criteria, just get out.
1663 * We will clear ->notask_error to zero if we see any child that
1664 * might later match our criteria, even if we are not able to reap
1665 * it yet.
1666 */
1667 wo->notask_error = -ECHILD;
1668 if ((wo->wo_type < PIDTYPE_MAX) &&
1669 (!wo->wo_pid || !pid_has_task(wo->wo_pid, wo->wo_type)))
1670 goto notask;
1671
1672 read_lock(&tasklist_lock);
1673
1674 if (wo->wo_type == PIDTYPE_PID) {
1675 retval = do_wait_pid(wo);
1676 if (retval)
1677 return retval;
1678 } else {
1679 struct task_struct *tsk = current;
1680
1681 do {
1682 retval = do_wait_thread(wo, tsk);
1683 if (retval)
1684 return retval;
1685
1686 retval = ptrace_do_wait(wo, tsk);
1687 if (retval)
1688 return retval;
1689
1690 if (wo->wo_flags & __WNOTHREAD)
1691 break;
1692 } while_each_thread(current, tsk);
1693 }
1694 read_unlock(&tasklist_lock);
1695
1696 notask:
1697 retval = wo->notask_error;
1698 if (!retval && !(wo->wo_flags & WNOHANG))
1699 return -ERESTARTSYS;
1700
1701 return retval;
1702 }
1703
do_wait(struct wait_opts * wo)1704 static long do_wait(struct wait_opts *wo)
1705 {
1706 int retval;
1707
1708 trace_sched_process_wait(wo->wo_pid);
1709
1710 init_waitqueue_func_entry(&wo->child_wait, child_wait_callback);
1711 wo->child_wait.private = current;
1712 add_wait_queue(¤t->signal->wait_chldexit, &wo->child_wait);
1713
1714 do {
1715 set_current_state(TASK_INTERRUPTIBLE);
1716 retval = __do_wait(wo);
1717 if (retval != -ERESTARTSYS)
1718 break;
1719 if (signal_pending(current))
1720 break;
1721 schedule();
1722 } while (1);
1723
1724 __set_current_state(TASK_RUNNING);
1725 remove_wait_queue(¤t->signal->wait_chldexit, &wo->child_wait);
1726 return retval;
1727 }
1728
kernel_waitid_prepare(struct wait_opts * wo,int which,pid_t upid,struct waitid_info * infop,int options,struct rusage * ru)1729 int kernel_waitid_prepare(struct wait_opts *wo, int which, pid_t upid,
1730 struct waitid_info *infop, int options,
1731 struct rusage *ru)
1732 {
1733 unsigned int f_flags = 0;
1734 struct pid *pid = NULL;
1735 enum pid_type type;
1736
1737 if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED|
1738 __WNOTHREAD|__WCLONE|__WALL))
1739 return -EINVAL;
1740 if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
1741 return -EINVAL;
1742
1743 switch (which) {
1744 case P_ALL:
1745 type = PIDTYPE_MAX;
1746 break;
1747 case P_PID:
1748 type = PIDTYPE_PID;
1749 if (upid <= 0)
1750 return -EINVAL;
1751
1752 pid = find_get_pid(upid);
1753 break;
1754 case P_PGID:
1755 type = PIDTYPE_PGID;
1756 if (upid < 0)
1757 return -EINVAL;
1758
1759 if (upid)
1760 pid = find_get_pid(upid);
1761 else
1762 pid = get_task_pid(current, PIDTYPE_PGID);
1763 break;
1764 case P_PIDFD:
1765 type = PIDTYPE_PID;
1766 if (upid < 0)
1767 return -EINVAL;
1768
1769 pid = pidfd_get_pid(upid, &f_flags);
1770 if (IS_ERR(pid))
1771 return PTR_ERR(pid);
1772
1773 break;
1774 default:
1775 return -EINVAL;
1776 }
1777
1778 wo->wo_type = type;
1779 wo->wo_pid = pid;
1780 wo->wo_flags = options;
1781 wo->wo_info = infop;
1782 wo->wo_rusage = ru;
1783 if (f_flags & O_NONBLOCK)
1784 wo->wo_flags |= WNOHANG;
1785
1786 return 0;
1787 }
1788
kernel_waitid(int which,pid_t upid,struct waitid_info * infop,int options,struct rusage * ru)1789 static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
1790 int options, struct rusage *ru)
1791 {
1792 struct wait_opts wo;
1793 long ret;
1794
1795 ret = kernel_waitid_prepare(&wo, which, upid, infop, options, ru);
1796 if (ret)
1797 return ret;
1798
1799 ret = do_wait(&wo);
1800 if (!ret && !(options & WNOHANG) && (wo.wo_flags & WNOHANG))
1801 ret = -EAGAIN;
1802
1803 put_pid(wo.wo_pid);
1804 return ret;
1805 }
1806
SYSCALL_DEFINE5(waitid,int,which,pid_t,upid,struct siginfo __user *,infop,int,options,struct rusage __user *,ru)1807 SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
1808 infop, int, options, struct rusage __user *, ru)
1809 {
1810 struct rusage r;
1811 struct waitid_info info = {.status = 0};
1812 long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);
1813 int signo = 0;
1814
1815 if (err > 0) {
1816 signo = SIGCHLD;
1817 err = 0;
1818 if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1819 return -EFAULT;
1820 }
1821 if (!infop)
1822 return err;
1823
1824 if (!user_write_access_begin(infop, sizeof(*infop)))
1825 return -EFAULT;
1826
1827 unsafe_put_user(signo, &infop->si_signo, Efault);
1828 unsafe_put_user(0, &infop->si_errno, Efault);
1829 unsafe_put_user(info.cause, &infop->si_code, Efault);
1830 unsafe_put_user(info.pid, &infop->si_pid, Efault);
1831 unsafe_put_user(info.uid, &infop->si_uid, Efault);
1832 unsafe_put_user(info.status, &infop->si_status, Efault);
1833 user_write_access_end();
1834 return err;
1835 Efault:
1836 user_write_access_end();
1837 return -EFAULT;
1838 }
1839
kernel_wait4(pid_t upid,int __user * stat_addr,int options,struct rusage * ru)1840 long kernel_wait4(pid_t upid, int __user *stat_addr, int options,
1841 struct rusage *ru)
1842 {
1843 struct wait_opts wo;
1844 struct pid *pid = NULL;
1845 enum pid_type type;
1846 long ret;
1847
1848 if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
1849 __WNOTHREAD|__WCLONE|__WALL))
1850 return -EINVAL;
1851
1852 /* -INT_MIN is not defined */
1853 if (upid == INT_MIN)
1854 return -ESRCH;
1855
1856 if (upid == -1)
1857 type = PIDTYPE_MAX;
1858 else if (upid < 0) {
1859 type = PIDTYPE_PGID;
1860 pid = find_get_pid(-upid);
1861 } else if (upid == 0) {
1862 type = PIDTYPE_PGID;
1863 pid = get_task_pid(current, PIDTYPE_PGID);
1864 } else /* upid > 0 */ {
1865 type = PIDTYPE_PID;
1866 pid = find_get_pid(upid);
1867 }
1868
1869 wo.wo_type = type;
1870 wo.wo_pid = pid;
1871 wo.wo_flags = options | WEXITED;
1872 wo.wo_info = NULL;
1873 wo.wo_stat = 0;
1874 wo.wo_rusage = ru;
1875 ret = do_wait(&wo);
1876 put_pid(pid);
1877 if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
1878 ret = -EFAULT;
1879
1880 return ret;
1881 }
1882
kernel_wait(pid_t pid,int * stat)1883 int kernel_wait(pid_t pid, int *stat)
1884 {
1885 struct wait_opts wo = {
1886 .wo_type = PIDTYPE_PID,
1887 .wo_pid = find_get_pid(pid),
1888 .wo_flags = WEXITED,
1889 };
1890 int ret;
1891
1892 ret = do_wait(&wo);
1893 if (ret > 0 && wo.wo_stat)
1894 *stat = wo.wo_stat;
1895 put_pid(wo.wo_pid);
1896 return ret;
1897 }
1898
SYSCALL_DEFINE4(wait4,pid_t,upid,int __user *,stat_addr,int,options,struct rusage __user *,ru)1899 SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
1900 int, options, struct rusage __user *, ru)
1901 {
1902 struct rusage r;
1903 long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL);
1904
1905 if (err > 0) {
1906 if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
1907 return -EFAULT;
1908 }
1909 return err;
1910 }
1911
1912 #ifdef __ARCH_WANT_SYS_WAITPID
1913
1914 /*
1915 * sys_waitpid() remains for compatibility. waitpid() should be
1916 * implemented by calling sys_wait4() from libc.a.
1917 */
SYSCALL_DEFINE3(waitpid,pid_t,pid,int __user *,stat_addr,int,options)1918 SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options)
1919 {
1920 return kernel_wait4(pid, stat_addr, options, NULL);
1921 }
1922
1923 #endif
1924
1925 #ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(wait4,compat_pid_t,pid,compat_uint_t __user *,stat_addr,int,options,struct compat_rusage __user *,ru)1926 COMPAT_SYSCALL_DEFINE4(wait4,
1927 compat_pid_t, pid,
1928 compat_uint_t __user *, stat_addr,
1929 int, options,
1930 struct compat_rusage __user *, ru)
1931 {
1932 struct rusage r;
1933 long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL);
1934 if (err > 0) {
1935 if (ru && put_compat_rusage(&r, ru))
1936 return -EFAULT;
1937 }
1938 return err;
1939 }
1940
COMPAT_SYSCALL_DEFINE5(waitid,int,which,compat_pid_t,pid,struct compat_siginfo __user *,infop,int,options,struct compat_rusage __user *,uru)1941 COMPAT_SYSCALL_DEFINE5(waitid,
1942 int, which, compat_pid_t, pid,
1943 struct compat_siginfo __user *, infop, int, options,
1944 struct compat_rusage __user *, uru)
1945 {
1946 struct rusage ru;
1947 struct waitid_info info = {.status = 0};
1948 long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
1949 int signo = 0;
1950 if (err > 0) {
1951 signo = SIGCHLD;
1952 err = 0;
1953 if (uru) {
1954 /* kernel_waitid() overwrites everything in ru */
1955 if (COMPAT_USE_64BIT_TIME)
1956 err = copy_to_user(uru, &ru, sizeof(ru));
1957 else
1958 err = put_compat_rusage(&ru, uru);
1959 if (err)
1960 return -EFAULT;
1961 }
1962 }
1963
1964 if (!infop)
1965 return err;
1966
1967 if (!user_write_access_begin(infop, sizeof(*infop)))
1968 return -EFAULT;
1969
1970 unsafe_put_user(signo, &infop->si_signo, Efault);
1971 unsafe_put_user(0, &infop->si_errno, Efault);
1972 unsafe_put_user(info.cause, &infop->si_code, Efault);
1973 unsafe_put_user(info.pid, &infop->si_pid, Efault);
1974 unsafe_put_user(info.uid, &infop->si_uid, Efault);
1975 unsafe_put_user(info.status, &infop->si_status, Efault);
1976 user_write_access_end();
1977 return err;
1978 Efault:
1979 user_write_access_end();
1980 return -EFAULT;
1981 }
1982 #endif
1983
1984 /*
1985 * This needs to be __function_aligned as GCC implicitly makes any
1986 * implementation of abort() cold and drops alignment specified by
1987 * -falign-functions=N.
1988 *
1989 * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88345#c11
1990 */
abort(void)1991 __weak __function_aligned void abort(void)
1992 {
1993 BUG();
1994
1995 /* if that doesn't kill us, halt */
1996 panic("Oops failed to kill thread");
1997 }
1998 EXPORT_SYMBOL(abort);
1999