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