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