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