1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/kernel/fork.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 */
7
8 /*
9 * 'fork.c' contains the help-routines for the 'fork' system call
10 * (see also entry.S and others).
11 * Fork is rather simple, once you get the hang of it, but the memory
12 * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
13 */
14
15 #include <linux/anon_inodes.h>
16 #include <linux/slab.h>
17 #include <linux/sched/autogroup.h>
18 #include <linux/sched/mm.h>
19 #include <linux/sched/coredump.h>
20 #include <linux/sched/user.h>
21 #include <linux/sched/numa_balancing.h>
22 #include <linux/sched/stat.h>
23 #include <linux/sched/task.h>
24 #include <linux/sched/task_stack.h>
25 #include <linux/sched/cputime.h>
26 #include <linux/seq_file.h>
27 #include <linux/rtmutex.h>
28 #include <linux/init.h>
29 #include <linux/unistd.h>
30 #include <linux/module.h>
31 #include <linux/vmalloc.h>
32 #include <linux/completion.h>
33 #include <linux/personality.h>
34 #include <linux/mempolicy.h>
35 #include <linux/sem.h>
36 #include <linux/file.h>
37 #include <linux/fdtable.h>
38 #include <linux/iocontext.h>
39 #include <linux/key.h>
40 #include <linux/binfmts.h>
41 #include <linux/mman.h>
42 #include <linux/mmu_notifier.h>
43 #include <linux/fs.h>
44 #include <linux/mm.h>
45 #include <linux/vmacache.h>
46 #include <linux/nsproxy.h>
47 #include <linux/capability.h>
48 #include <linux/cpu.h>
49 #include <linux/cgroup.h>
50 #include <linux/security.h>
51 #include <linux/hugetlb.h>
52 #include <linux/seccomp.h>
53 #include <linux/swap.h>
54 #include <linux/syscalls.h>
55 #include <linux/jiffies.h>
56 #include <linux/futex.h>
57 #include <linux/compat.h>
58 #include <linux/kthread.h>
59 #include <linux/task_io_accounting_ops.h>
60 #include <linux/rcupdate.h>
61 #include <linux/ptrace.h>
62 #include <linux/mount.h>
63 #include <linux/audit.h>
64 #include <linux/memcontrol.h>
65 #include <linux/ftrace.h>
66 #include <linux/proc_fs.h>
67 #include <linux/profile.h>
68 #include <linux/rmap.h>
69 #include <linux/ksm.h>
70 #include <linux/acct.h>
71 #include <linux/userfaultfd_k.h>
72 #include <linux/tsacct_kern.h>
73 #include <linux/cn_proc.h>
74 #include <linux/freezer.h>
75 #include <linux/delayacct.h>
76 #include <linux/taskstats_kern.h>
77 #include <linux/random.h>
78 #include <linux/tty.h>
79 #include <linux/blkdev.h>
80 #include <linux/fs_struct.h>
81 #include <linux/magic.h>
82 #include <linux/perf_event.h>
83 #include <linux/posix-timers.h>
84 #include <linux/user-return-notifier.h>
85 #include <linux/oom.h>
86 #include <linux/khugepaged.h>
87 #include <linux/signalfd.h>
88 #include <linux/uprobes.h>
89 #include <linux/aio.h>
90 #include <linux/compiler.h>
91 #include <linux/sysctl.h>
92 #include <linux/kcov.h>
93 #include <linux/livepatch.h>
94 #include <linux/thread_info.h>
95 #include <linux/stackleak.h>
96 #include <linux/kasan.h>
97 #include <linux/scs.h>
98 #include <linux/io_uring.h>
99 #include <linux/cpufreq_times.h>
100
101 #include <asm/pgalloc.h>
102 #include <linux/uaccess.h>
103 #include <asm/mmu_context.h>
104 #include <asm/cacheflush.h>
105 #include <asm/tlbflush.h>
106
107 #include <trace/events/sched.h>
108
109 #define CREATE_TRACE_POINTS
110 #include <trace/events/task.h>
111
112 #undef CREATE_TRACE_POINTS
113 #include <trace/hooks/sched.h>
114 /*
115 * Minimum number of threads to boot the kernel
116 */
117 #define MIN_THREADS 20
118
119 /*
120 * Maximum number of threads
121 */
122 #define MAX_THREADS FUTEX_TID_MASK
123
124 EXPORT_TRACEPOINT_SYMBOL_GPL(task_newtask);
125
126 /*
127 * Protected counters by write_lock_irq(&tasklist_lock)
128 */
129 unsigned long total_forks; /* Handle normal Linux uptimes. */
130 int nr_threads; /* The idle threads do not count.. */
131
132 static int max_threads; /* tunable limit on nr_threads */
133
134 #define NAMED_ARRAY_INDEX(x) [x] = __stringify(x)
135
136 static const char * const resident_page_types[] = {
137 NAMED_ARRAY_INDEX(MM_FILEPAGES),
138 NAMED_ARRAY_INDEX(MM_ANONPAGES),
139 NAMED_ARRAY_INDEX(MM_SWAPENTS),
140 NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
141 };
142
143 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
144
145 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
146 EXPORT_SYMBOL_GPL(tasklist_lock);
147
148 #ifdef CONFIG_PROVE_RCU
lockdep_tasklist_lock_is_held(void)149 int lockdep_tasklist_lock_is_held(void)
150 {
151 return lockdep_is_held(&tasklist_lock);
152 }
153 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
154 #endif /* #ifdef CONFIG_PROVE_RCU */
155
nr_processes(void)156 int nr_processes(void)
157 {
158 int cpu;
159 int total = 0;
160
161 for_each_possible_cpu(cpu)
162 total += per_cpu(process_counts, cpu);
163
164 return total;
165 }
166
arch_release_task_struct(struct task_struct * tsk)167 void __weak arch_release_task_struct(struct task_struct *tsk)
168 {
169 }
170
171 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
172 static struct kmem_cache *task_struct_cachep;
173
alloc_task_struct_node(int node)174 static inline struct task_struct *alloc_task_struct_node(int node)
175 {
176 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
177 }
178
free_task_struct(struct task_struct * tsk)179 static inline void free_task_struct(struct task_struct *tsk)
180 {
181 kmem_cache_free(task_struct_cachep, tsk);
182 }
183 #endif
184
185 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
186
187 /*
188 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
189 * kmemcache based allocator.
190 */
191 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
192
193 #ifdef CONFIG_VMAP_STACK
194 /*
195 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
196 * flush. Try to minimize the number of calls by caching stacks.
197 */
198 #define NR_CACHED_STACKS 2
199 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
200
free_vm_stack_cache(unsigned int cpu)201 static int free_vm_stack_cache(unsigned int cpu)
202 {
203 struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
204 int i;
205
206 for (i = 0; i < NR_CACHED_STACKS; i++) {
207 struct vm_struct *vm_stack = cached_vm_stacks[i];
208
209 if (!vm_stack)
210 continue;
211
212 vfree(vm_stack->addr);
213 cached_vm_stacks[i] = NULL;
214 }
215
216 return 0;
217 }
218 #endif
219
alloc_thread_stack_node(struct task_struct * tsk,int node)220 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
221 {
222 #ifdef CONFIG_VMAP_STACK
223 void *stack;
224 int i;
225
226 for (i = 0; i < NR_CACHED_STACKS; i++) {
227 struct vm_struct *s;
228
229 s = this_cpu_xchg(cached_stacks[i], NULL);
230
231 if (!s)
232 continue;
233
234 /* Mark stack accessible for KASAN. */
235 kasan_unpoison_range(s->addr, THREAD_SIZE);
236
237 /* Clear stale pointers from reused stack. */
238 memset(s->addr, 0, THREAD_SIZE);
239
240 tsk->stack_vm_area = s;
241 tsk->stack = s->addr;
242 return s->addr;
243 }
244
245 /*
246 * Allocated stacks are cached and later reused by new threads,
247 * so memcg accounting is performed manually on assigning/releasing
248 * stacks to tasks. Drop __GFP_ACCOUNT.
249 */
250 stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
251 VMALLOC_START, VMALLOC_END,
252 THREADINFO_GFP & ~__GFP_ACCOUNT,
253 PAGE_KERNEL,
254 0, node, __builtin_return_address(0));
255
256 /*
257 * We can't call find_vm_area() in interrupt context, and
258 * free_thread_stack() can be called in interrupt context,
259 * so cache the vm_struct.
260 */
261 if (stack) {
262 tsk->stack_vm_area = find_vm_area(stack);
263 tsk->stack = stack;
264 }
265 return stack;
266 #else
267 struct page *page = alloc_pages_node(node, THREADINFO_GFP,
268 THREAD_SIZE_ORDER);
269
270 if (likely(page)) {
271 tsk->stack = kasan_reset_tag(page_address(page));
272 return tsk->stack;
273 }
274 return NULL;
275 #endif
276 }
277
free_thread_stack(struct task_struct * tsk)278 static inline void free_thread_stack(struct task_struct *tsk)
279 {
280 #ifdef CONFIG_VMAP_STACK
281 struct vm_struct *vm = task_stack_vm_area(tsk);
282
283 if (vm) {
284 int i;
285
286 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
287 memcg_kmem_uncharge_page(vm->pages[i], 0);
288
289 for (i = 0; i < NR_CACHED_STACKS; i++) {
290 if (this_cpu_cmpxchg(cached_stacks[i],
291 NULL, tsk->stack_vm_area) != NULL)
292 continue;
293
294 return;
295 }
296
297 vfree_atomic(tsk->stack);
298 return;
299 }
300 #endif
301
302 __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
303 }
304 # else
305 static struct kmem_cache *thread_stack_cache;
306
alloc_thread_stack_node(struct task_struct * tsk,int node)307 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
308 int node)
309 {
310 unsigned long *stack;
311 stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
312 stack = kasan_reset_tag(stack);
313 tsk->stack = stack;
314 return stack;
315 }
316
free_thread_stack(struct task_struct * tsk)317 static void free_thread_stack(struct task_struct *tsk)
318 {
319 kmem_cache_free(thread_stack_cache, tsk->stack);
320 }
321
thread_stack_cache_init(void)322 void thread_stack_cache_init(void)
323 {
324 thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
325 THREAD_SIZE, THREAD_SIZE, 0, 0,
326 THREAD_SIZE, NULL);
327 BUG_ON(thread_stack_cache == NULL);
328 }
329 # endif
330 #endif
331
332 /* SLAB cache for signal_struct structures (tsk->signal) */
333 static struct kmem_cache *signal_cachep;
334
335 /* SLAB cache for sighand_struct structures (tsk->sighand) */
336 struct kmem_cache *sighand_cachep;
337
338 /* SLAB cache for files_struct structures (tsk->files) */
339 struct kmem_cache *files_cachep;
340
341 /* SLAB cache for fs_struct structures (tsk->fs) */
342 struct kmem_cache *fs_cachep;
343
344 /* SLAB cache for vm_area_struct structures */
345 static struct kmem_cache *vm_area_cachep;
346
347 /* SLAB cache for mm_struct structures (tsk->mm) */
348 static struct kmem_cache *mm_cachep;
349
vm_area_alloc(struct mm_struct * mm)350 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
351 {
352 struct vm_area_struct *vma;
353
354 vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
355 if (vma)
356 vma_init(vma, mm);
357 return vma;
358 }
359
vm_area_dup(struct vm_area_struct * orig)360 struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
361 {
362 struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
363
364 if (new) {
365 ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
366 ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
367 /*
368 * orig->shared.rb may be modified concurrently, but the clone
369 * will be reinitialized.
370 */
371 *new = data_race(*orig);
372 INIT_VMA(new);
373 new->vm_next = new->vm_prev = NULL;
374 }
375 return new;
376 }
377
vm_area_free(struct vm_area_struct * vma)378 void vm_area_free(struct vm_area_struct *vma)
379 {
380 kmem_cache_free(vm_area_cachep, vma);
381 }
382
account_kernel_stack(struct task_struct * tsk,int account)383 static void account_kernel_stack(struct task_struct *tsk, int account)
384 {
385 void *stack = task_stack_page(tsk);
386 struct vm_struct *vm = task_stack_vm_area(tsk);
387
388
389 /* All stack pages are in the same node. */
390 if (vm)
391 mod_lruvec_page_state(vm->pages[0], NR_KERNEL_STACK_KB,
392 account * (THREAD_SIZE / 1024));
393 else
394 mod_lruvec_slab_state(stack, NR_KERNEL_STACK_KB,
395 account * (THREAD_SIZE / 1024));
396 }
397
memcg_charge_kernel_stack(struct task_struct * tsk)398 static int memcg_charge_kernel_stack(struct task_struct *tsk)
399 {
400 #ifdef CONFIG_VMAP_STACK
401 struct vm_struct *vm = task_stack_vm_area(tsk);
402 int ret;
403
404 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
405
406 if (vm) {
407 int i;
408
409 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
410
411 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
412 /*
413 * If memcg_kmem_charge_page() fails, page->mem_cgroup
414 * pointer is NULL, and memcg_kmem_uncharge_page() in
415 * free_thread_stack() will ignore this page.
416 */
417 ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL,
418 0);
419 if (ret)
420 return ret;
421 }
422 }
423 #endif
424 return 0;
425 }
426
release_task_stack(struct task_struct * tsk)427 static void release_task_stack(struct task_struct *tsk)
428 {
429 if (WARN_ON(tsk->state != TASK_DEAD))
430 return; /* Better to leak the stack than to free prematurely */
431
432 account_kernel_stack(tsk, -1);
433 free_thread_stack(tsk);
434 tsk->stack = NULL;
435 #ifdef CONFIG_VMAP_STACK
436 tsk->stack_vm_area = NULL;
437 #endif
438 }
439
440 #ifdef CONFIG_THREAD_INFO_IN_TASK
put_task_stack(struct task_struct * tsk)441 void put_task_stack(struct task_struct *tsk)
442 {
443 if (refcount_dec_and_test(&tsk->stack_refcount))
444 release_task_stack(tsk);
445 }
446 EXPORT_SYMBOL_GPL(put_task_stack);
447 #endif
448
free_task(struct task_struct * tsk)449 void free_task(struct task_struct *tsk)
450 {
451 #ifdef CONFIG_SECCOMP
452 WARN_ON_ONCE(tsk->seccomp.filter);
453 #endif
454 cpufreq_task_times_exit(tsk);
455 scs_release(tsk);
456
457 trace_android_vh_free_task(tsk);
458 #ifndef CONFIG_THREAD_INFO_IN_TASK
459 /*
460 * The task is finally done with both the stack and thread_info,
461 * so free both.
462 */
463 release_task_stack(tsk);
464 #else
465 /*
466 * If the task had a separate stack allocation, it should be gone
467 * by now.
468 */
469 WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
470 #endif
471 rt_mutex_debug_task_free(tsk);
472 ftrace_graph_exit_task(tsk);
473 arch_release_task_struct(tsk);
474 if (tsk->flags & PF_KTHREAD)
475 free_kthread_struct(tsk);
476 free_task_struct(tsk);
477 }
478 EXPORT_SYMBOL(free_task);
479
480 #ifdef CONFIG_MMU
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)481 static __latent_entropy int dup_mmap(struct mm_struct *mm,
482 struct mm_struct *oldmm)
483 {
484 struct vm_area_struct *mpnt, *tmp, *prev, **pprev, *last = NULL;
485 struct rb_node **rb_link, *rb_parent;
486 int retval;
487 unsigned long charge;
488 LIST_HEAD(uf);
489
490 uprobe_start_dup_mmap();
491 if (mmap_write_lock_killable(oldmm)) {
492 retval = -EINTR;
493 goto fail_uprobe_end;
494 }
495 flush_cache_dup_mm(oldmm);
496 uprobe_dup_mmap(oldmm, mm);
497 /*
498 * Not linked in yet - no deadlock potential:
499 */
500 mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
501
502 /* No ordering required: file already has been exposed. */
503 RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
504
505 mm->total_vm = oldmm->total_vm;
506 mm->data_vm = oldmm->data_vm;
507 mm->exec_vm = oldmm->exec_vm;
508 mm->stack_vm = oldmm->stack_vm;
509
510 rb_link = &mm->mm_rb.rb_node;
511 rb_parent = NULL;
512 pprev = &mm->mmap;
513 retval = ksm_fork(mm, oldmm);
514 if (retval)
515 goto out;
516 retval = khugepaged_fork(mm, oldmm);
517 if (retval)
518 goto out;
519
520 prev = NULL;
521 for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
522 struct file *file;
523
524 if (mpnt->vm_flags & VM_DONTCOPY) {
525 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
526 continue;
527 }
528 charge = 0;
529 /*
530 * Don't duplicate many vmas if we've been oom-killed (for
531 * example)
532 */
533 if (fatal_signal_pending(current)) {
534 retval = -EINTR;
535 goto out;
536 }
537 if (mpnt->vm_flags & VM_ACCOUNT) {
538 unsigned long len = vma_pages(mpnt);
539
540 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
541 goto fail_nomem;
542 charge = len;
543 }
544 tmp = vm_area_dup(mpnt);
545 if (!tmp)
546 goto fail_nomem;
547 retval = vma_dup_policy(mpnt, tmp);
548 if (retval)
549 goto fail_nomem_policy;
550 tmp->vm_mm = mm;
551 retval = dup_userfaultfd(tmp, &uf);
552 if (retval)
553 goto fail_nomem_anon_vma_fork;
554 if (tmp->vm_flags & VM_WIPEONFORK) {
555 /*
556 * VM_WIPEONFORK gets a clean slate in the child.
557 * Don't prepare anon_vma until fault since we don't
558 * copy page for current vma.
559 */
560 tmp->anon_vma = NULL;
561 } else if (anon_vma_fork(tmp, mpnt))
562 goto fail_nomem_anon_vma_fork;
563 tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
564 file = tmp->vm_file;
565 if (file) {
566 struct inode *inode = file_inode(file);
567 struct address_space *mapping = file->f_mapping;
568
569 get_file(file);
570 if (tmp->vm_flags & VM_DENYWRITE)
571 put_write_access(inode);
572 i_mmap_lock_write(mapping);
573 if (tmp->vm_flags & VM_SHARED)
574 mapping_allow_writable(mapping);
575 flush_dcache_mmap_lock(mapping);
576 /* insert tmp into the share list, just after mpnt */
577 vma_interval_tree_insert_after(tmp, mpnt,
578 &mapping->i_mmap);
579 flush_dcache_mmap_unlock(mapping);
580 i_mmap_unlock_write(mapping);
581 }
582
583 /*
584 * Clear hugetlb-related page reserves for children. This only
585 * affects MAP_PRIVATE mappings. Faults generated by the child
586 * are not guaranteed to succeed, even if read-only
587 */
588 if (is_vm_hugetlb_page(tmp))
589 reset_vma_resv_huge_pages(tmp);
590
591 /*
592 * Link in the new vma and copy the page table entries.
593 */
594 *pprev = tmp;
595 pprev = &tmp->vm_next;
596 tmp->vm_prev = prev;
597 prev = tmp;
598
599 __vma_link_rb(mm, tmp, rb_link, rb_parent);
600 rb_link = &tmp->vm_rb.rb_right;
601 rb_parent = &tmp->vm_rb;
602
603 mm->map_count++;
604 if (!(tmp->vm_flags & VM_WIPEONFORK)) {
605 if (IS_ENABLED(CONFIG_SPECULATIVE_PAGE_FAULT)) {
606 /*
607 * Mark this VMA as changing to prevent the
608 * speculative page fault hanlder to process
609 * it until the TLB are flushed below.
610 */
611 last = mpnt;
612 vm_write_begin(mpnt);
613 }
614 retval = copy_page_range(tmp, mpnt);
615 }
616
617 if (tmp->vm_ops && tmp->vm_ops->open)
618 tmp->vm_ops->open(tmp);
619
620 if (retval)
621 goto out;
622 }
623 /* a new mm has just been created */
624 retval = arch_dup_mmap(oldmm, mm);
625 out:
626 mmap_write_unlock(mm);
627 flush_tlb_mm(oldmm);
628
629 if (IS_ENABLED(CONFIG_SPECULATIVE_PAGE_FAULT)) {
630 /*
631 * Since the TLB has been flush, we can safely unmark the
632 * copied VMAs and allows the speculative page fault handler to
633 * process them again.
634 * Walk back the VMA list from the last marked VMA.
635 */
636 for (; last; last = last->vm_prev) {
637 if (last->vm_flags & VM_DONTCOPY)
638 continue;
639 if (!(last->vm_flags & VM_WIPEONFORK))
640 vm_write_end(last);
641 }
642 }
643
644 mmap_write_unlock(oldmm);
645 dup_userfaultfd_complete(&uf);
646 fail_uprobe_end:
647 uprobe_end_dup_mmap();
648 return retval;
649 fail_nomem_anon_vma_fork:
650 mpol_put(vma_policy(tmp));
651 fail_nomem_policy:
652 vm_area_free(tmp);
653 fail_nomem:
654 retval = -ENOMEM;
655 vm_unacct_memory(charge);
656 goto out;
657 }
658
mm_alloc_pgd(struct mm_struct * mm)659 static inline int mm_alloc_pgd(struct mm_struct *mm)
660 {
661 mm->pgd = pgd_alloc(mm);
662 if (unlikely(!mm->pgd))
663 return -ENOMEM;
664 return 0;
665 }
666
mm_free_pgd(struct mm_struct * mm)667 static inline void mm_free_pgd(struct mm_struct *mm)
668 {
669 pgd_free(mm, mm->pgd);
670 }
671 #else
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)672 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
673 {
674 mmap_write_lock(oldmm);
675 RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
676 mmap_write_unlock(oldmm);
677 return 0;
678 }
679 #define mm_alloc_pgd(mm) (0)
680 #define mm_free_pgd(mm)
681 #endif /* CONFIG_MMU */
682
check_mm(struct mm_struct * mm)683 static void check_mm(struct mm_struct *mm)
684 {
685 int i;
686
687 BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
688 "Please make sure 'struct resident_page_types[]' is updated as well");
689
690 for (i = 0; i < NR_MM_COUNTERS; i++) {
691 long x = atomic_long_read(&mm->rss_stat.count[i]);
692
693 if (unlikely(x))
694 pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
695 mm, resident_page_types[i], x);
696 }
697
698 if (mm_pgtables_bytes(mm))
699 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
700 mm_pgtables_bytes(mm));
701
702 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
703 VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
704 #endif
705 }
706
707 #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
708 #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
709
710 /*
711 * Called when the last reference to the mm
712 * is dropped: either by a lazy thread or by
713 * mmput. Free the page directory and the mm.
714 */
__mmdrop(struct mm_struct * mm)715 void __mmdrop(struct mm_struct *mm)
716 {
717 BUG_ON(mm == &init_mm);
718 WARN_ON_ONCE(mm == current->mm);
719 WARN_ON_ONCE(mm == current->active_mm);
720 mm_free_pgd(mm);
721 destroy_context(mm);
722 mmu_notifier_subscriptions_destroy(mm);
723 check_mm(mm);
724 put_user_ns(mm->user_ns);
725 free_mm(mm);
726 }
727 EXPORT_SYMBOL_GPL(__mmdrop);
728
mmdrop_async_fn(struct work_struct * work)729 static void mmdrop_async_fn(struct work_struct *work)
730 {
731 struct mm_struct *mm;
732
733 mm = container_of(work, struct mm_struct, async_put_work);
734 __mmdrop(mm);
735 }
736
mmdrop_async(struct mm_struct * mm)737 static void mmdrop_async(struct mm_struct *mm)
738 {
739 if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
740 INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
741 schedule_work(&mm->async_put_work);
742 }
743 }
744
free_signal_struct(struct signal_struct * sig)745 static inline void free_signal_struct(struct signal_struct *sig)
746 {
747 taskstats_tgid_free(sig);
748 sched_autogroup_exit(sig);
749 /*
750 * __mmdrop is not safe to call from softirq context on x86 due to
751 * pgd_dtor so postpone it to the async context
752 */
753 if (sig->oom_mm)
754 mmdrop_async(sig->oom_mm);
755 kmem_cache_free(signal_cachep, sig);
756 }
757
put_signal_struct(struct signal_struct * sig)758 static inline void put_signal_struct(struct signal_struct *sig)
759 {
760 if (refcount_dec_and_test(&sig->sigcnt))
761 free_signal_struct(sig);
762 }
763
__put_task_struct(struct task_struct * tsk)764 void __put_task_struct(struct task_struct *tsk)
765 {
766 WARN_ON(!tsk->exit_state);
767 WARN_ON(refcount_read(&tsk->usage));
768 WARN_ON(tsk == current);
769
770 io_uring_free(tsk);
771 cgroup_free(tsk);
772 task_numa_free(tsk, true);
773 security_task_free(tsk);
774 exit_creds(tsk);
775 delayacct_tsk_free(tsk);
776 put_signal_struct(tsk->signal);
777
778 if (!profile_handoff_task(tsk))
779 free_task(tsk);
780 }
781 EXPORT_SYMBOL_GPL(__put_task_struct);
782
__put_task_struct_rcu_cb(struct rcu_head * rhp)783 void __put_task_struct_rcu_cb(struct rcu_head *rhp)
784 {
785 struct task_struct *task = container_of(rhp, struct task_struct, rcu);
786
787 __put_task_struct(task);
788 }
789 EXPORT_SYMBOL_GPL(__put_task_struct_rcu_cb);
790
arch_task_cache_init(void)791 void __init __weak arch_task_cache_init(void) { }
792
793 /*
794 * set_max_threads
795 */
set_max_threads(unsigned int max_threads_suggested)796 static void set_max_threads(unsigned int max_threads_suggested)
797 {
798 u64 threads;
799 unsigned long nr_pages = totalram_pages();
800
801 /*
802 * The number of threads shall be limited such that the thread
803 * structures may only consume a small part of the available memory.
804 */
805 if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
806 threads = MAX_THREADS;
807 else
808 threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
809 (u64) THREAD_SIZE * 8UL);
810
811 if (threads > max_threads_suggested)
812 threads = max_threads_suggested;
813
814 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
815 }
816
817 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
818 /* Initialized by the architecture: */
819 int arch_task_struct_size __read_mostly;
820 #endif
821
822 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
task_struct_whitelist(unsigned long * offset,unsigned long * size)823 static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
824 {
825 /* Fetch thread_struct whitelist for the architecture. */
826 arch_thread_struct_whitelist(offset, size);
827
828 /*
829 * Handle zero-sized whitelist or empty thread_struct, otherwise
830 * adjust offset to position of thread_struct in task_struct.
831 */
832 if (unlikely(*size == 0))
833 *offset = 0;
834 else
835 *offset += offsetof(struct task_struct, thread);
836 }
837 #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
838
fork_init(void)839 void __init fork_init(void)
840 {
841 int i;
842 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
843 #ifndef ARCH_MIN_TASKALIGN
844 #define ARCH_MIN_TASKALIGN 0
845 #endif
846 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
847 unsigned long useroffset, usersize;
848
849 /* create a slab on which task_structs can be allocated */
850 task_struct_whitelist(&useroffset, &usersize);
851 task_struct_cachep = kmem_cache_create_usercopy("task_struct",
852 arch_task_struct_size, align,
853 SLAB_PANIC|SLAB_ACCOUNT,
854 useroffset, usersize, NULL);
855 #endif
856
857 /* do the arch specific task caches init */
858 arch_task_cache_init();
859
860 set_max_threads(MAX_THREADS);
861
862 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
863 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
864 init_task.signal->rlim[RLIMIT_SIGPENDING] =
865 init_task.signal->rlim[RLIMIT_NPROC];
866
867 for (i = 0; i < UCOUNT_COUNTS; i++) {
868 init_user_ns.ucount_max[i] = max_threads/2;
869 }
870
871 #ifdef CONFIG_VMAP_STACK
872 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
873 NULL, free_vm_stack_cache);
874 #endif
875
876 scs_init();
877
878 lockdep_init_task(&init_task);
879 uprobes_init();
880 }
881
arch_dup_task_struct(struct task_struct * dst,struct task_struct * src)882 int __weak arch_dup_task_struct(struct task_struct *dst,
883 struct task_struct *src)
884 {
885 *dst = *src;
886 return 0;
887 }
888
set_task_stack_end_magic(struct task_struct * tsk)889 void set_task_stack_end_magic(struct task_struct *tsk)
890 {
891 unsigned long *stackend;
892
893 stackend = end_of_stack(tsk);
894 *stackend = STACK_END_MAGIC; /* for overflow detection */
895 }
896
dup_task_struct(struct task_struct * orig,int node)897 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
898 {
899 struct task_struct *tsk;
900 unsigned long *stack;
901 struct vm_struct *stack_vm_area __maybe_unused;
902 int err;
903
904 if (node == NUMA_NO_NODE)
905 node = tsk_fork_get_node(orig);
906 tsk = alloc_task_struct_node(node);
907 if (!tsk)
908 return NULL;
909
910 stack = alloc_thread_stack_node(tsk, node);
911 if (!stack)
912 goto free_tsk;
913
914 if (memcg_charge_kernel_stack(tsk))
915 goto free_stack;
916
917 stack_vm_area = task_stack_vm_area(tsk);
918
919 err = arch_dup_task_struct(tsk, orig);
920
921 /*
922 * arch_dup_task_struct() clobbers the stack-related fields. Make
923 * sure they're properly initialized before using any stack-related
924 * functions again.
925 */
926 tsk->stack = stack;
927 #ifdef CONFIG_VMAP_STACK
928 tsk->stack_vm_area = stack_vm_area;
929 #endif
930 #ifdef CONFIG_THREAD_INFO_IN_TASK
931 refcount_set(&tsk->stack_refcount, 1);
932 #endif
933
934 if (err)
935 goto free_stack;
936
937 err = scs_prepare(tsk, node);
938 if (err)
939 goto free_stack;
940
941 #ifdef CONFIG_SECCOMP
942 /*
943 * We must handle setting up seccomp filters once we're under
944 * the sighand lock in case orig has changed between now and
945 * then. Until then, filter must be NULL to avoid messing up
946 * the usage counts on the error path calling free_task.
947 */
948 tsk->seccomp.filter = NULL;
949 #endif
950
951 setup_thread_stack(tsk, orig);
952 clear_user_return_notifier(tsk);
953 clear_tsk_need_resched(tsk);
954 set_task_stack_end_magic(tsk);
955
956 #ifdef CONFIG_STACKPROTECTOR
957 tsk->stack_canary = get_random_canary();
958 #endif
959 if (orig->cpus_ptr == &orig->cpus_mask)
960 tsk->cpus_ptr = &tsk->cpus_mask;
961
962 /*
963 * One for the user space visible state that goes away when reaped.
964 * One for the scheduler.
965 */
966 refcount_set(&tsk->rcu_users, 2);
967 /* One for the rcu users */
968 refcount_set(&tsk->usage, 1);
969 #ifdef CONFIG_BLK_DEV_IO_TRACE
970 tsk->btrace_seq = 0;
971 #endif
972 tsk->splice_pipe = NULL;
973 tsk->task_frag.page = NULL;
974 tsk->wake_q.next = NULL;
975 tsk->pf_io_worker = NULL;
976
977 account_kernel_stack(tsk, 1);
978
979 kcov_task_init(tsk);
980
981 #ifdef CONFIG_FAULT_INJECTION
982 tsk->fail_nth = 0;
983 #endif
984
985 #ifdef CONFIG_BLK_CGROUP
986 tsk->throttle_queue = NULL;
987 tsk->use_memdelay = 0;
988 #endif
989
990 #ifdef CONFIG_MEMCG
991 tsk->active_memcg = NULL;
992 #endif
993
994 android_init_vendor_data(tsk, 1);
995 android_init_oem_data(tsk, 1);
996
997 trace_android_vh_dup_task_struct(tsk, orig);
998 return tsk;
999
1000 free_stack:
1001 free_thread_stack(tsk);
1002 free_tsk:
1003 free_task_struct(tsk);
1004 return NULL;
1005 }
1006
1007 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
1008
1009 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
1010
coredump_filter_setup(char * s)1011 static int __init coredump_filter_setup(char *s)
1012 {
1013 default_dump_filter =
1014 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
1015 MMF_DUMP_FILTER_MASK;
1016 return 1;
1017 }
1018
1019 __setup("coredump_filter=", coredump_filter_setup);
1020
1021 #include <linux/init_task.h>
1022
mm_init_aio(struct mm_struct * mm)1023 static void mm_init_aio(struct mm_struct *mm)
1024 {
1025 #ifdef CONFIG_AIO
1026 spin_lock_init(&mm->ioctx_lock);
1027 mm->ioctx_table = NULL;
1028 #endif
1029 }
1030
mm_clear_owner(struct mm_struct * mm,struct task_struct * p)1031 static __always_inline void mm_clear_owner(struct mm_struct *mm,
1032 struct task_struct *p)
1033 {
1034 #ifdef CONFIG_MEMCG
1035 if (mm->owner == p)
1036 WRITE_ONCE(mm->owner, NULL);
1037 #endif
1038 }
1039
mm_init_owner(struct mm_struct * mm,struct task_struct * p)1040 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1041 {
1042 #ifdef CONFIG_MEMCG
1043 mm->owner = p;
1044 #endif
1045 }
1046
mm_init_pasid(struct mm_struct * mm)1047 static void mm_init_pasid(struct mm_struct *mm)
1048 {
1049 #ifdef CONFIG_IOMMU_SUPPORT
1050 mm->pasid = INIT_PASID;
1051 #endif
1052 }
1053
mm_init_uprobes_state(struct mm_struct * mm)1054 static void mm_init_uprobes_state(struct mm_struct *mm)
1055 {
1056 #ifdef CONFIG_UPROBES
1057 mm->uprobes_state.xol_area = NULL;
1058 #endif
1059 }
1060
mm_init(struct mm_struct * mm,struct task_struct * p,struct user_namespace * user_ns)1061 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1062 struct user_namespace *user_ns)
1063 {
1064 mm->mmap = NULL;
1065 mm->mm_rb = RB_ROOT;
1066 mm->vmacache_seqnum = 0;
1067 #ifdef CONFIG_SPECULATIVE_PAGE_FAULT
1068 rwlock_init(&mm->mm_rb_lock);
1069 #endif
1070 atomic_set(&mm->mm_users, 1);
1071 atomic_set(&mm->mm_count, 1);
1072 seqcount_init(&mm->write_protect_seq);
1073 mmap_init_lock(mm);
1074 INIT_LIST_HEAD(&mm->mmlist);
1075 mm->core_state = NULL;
1076 mm_pgtables_bytes_init(mm);
1077 mm->map_count = 0;
1078 mm->locked_vm = 0;
1079 atomic_set(&mm->has_pinned, 0);
1080 atomic64_set(&mm->pinned_vm, 0);
1081 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1082 spin_lock_init(&mm->page_table_lock);
1083 spin_lock_init(&mm->arg_lock);
1084 mm_init_cpumask(mm);
1085 mm_init_aio(mm);
1086 mm_init_owner(mm, p);
1087 mm_init_pasid(mm);
1088 RCU_INIT_POINTER(mm->exe_file, NULL);
1089 if (!mmu_notifier_subscriptions_init(mm))
1090 goto fail_nopgd;
1091 init_tlb_flush_pending(mm);
1092 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
1093 mm->pmd_huge_pte = NULL;
1094 #endif
1095 mm_init_uprobes_state(mm);
1096 hugetlb_count_init(mm);
1097
1098 if (current->mm) {
1099 mm->flags = current->mm->flags & MMF_INIT_MASK;
1100 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1101 } else {
1102 mm->flags = default_dump_filter;
1103 mm->def_flags = 0;
1104 }
1105
1106 if (mm_alloc_pgd(mm))
1107 goto fail_nopgd;
1108
1109 if (init_new_context(p, mm))
1110 goto fail_nocontext;
1111
1112 mm->user_ns = get_user_ns(user_ns);
1113 return mm;
1114
1115 fail_nocontext:
1116 mm_free_pgd(mm);
1117 fail_nopgd:
1118 free_mm(mm);
1119 return NULL;
1120 }
1121
1122 /*
1123 * Allocate and initialize an mm_struct.
1124 */
mm_alloc(void)1125 struct mm_struct *mm_alloc(void)
1126 {
1127 struct mm_struct *mm;
1128
1129 mm = allocate_mm();
1130 if (!mm)
1131 return NULL;
1132
1133 memset(mm, 0, sizeof(*mm));
1134 return mm_init(mm, current, current_user_ns());
1135 }
1136
__mmput(struct mm_struct * mm)1137 static inline void __mmput(struct mm_struct *mm)
1138 {
1139 VM_BUG_ON(atomic_read(&mm->mm_users));
1140
1141 uprobe_clear_state(mm);
1142 exit_aio(mm);
1143 ksm_exit(mm);
1144 khugepaged_exit(mm); /* must run before exit_mmap */
1145 exit_mmap(mm);
1146 mm_put_huge_zero_page(mm);
1147 set_mm_exe_file(mm, NULL);
1148 if (!list_empty(&mm->mmlist)) {
1149 spin_lock(&mmlist_lock);
1150 list_del(&mm->mmlist);
1151 spin_unlock(&mmlist_lock);
1152 }
1153 if (mm->binfmt)
1154 module_put(mm->binfmt->module);
1155 mmdrop(mm);
1156 }
1157
1158 /*
1159 * Decrement the use count and release all resources for an mm.
1160 */
mmput(struct mm_struct * mm)1161 void mmput(struct mm_struct *mm)
1162 {
1163 might_sleep();
1164
1165 if (atomic_dec_and_test(&mm->mm_users)) {
1166 trace_android_vh_mmput(NULL);
1167 __mmput(mm);
1168 }
1169 }
1170 EXPORT_SYMBOL_GPL(mmput);
1171
1172 #ifdef CONFIG_MMU
mmput_async_fn(struct work_struct * work)1173 static void mmput_async_fn(struct work_struct *work)
1174 {
1175 struct mm_struct *mm = container_of(work, struct mm_struct,
1176 async_put_work);
1177
1178 __mmput(mm);
1179 }
1180
mmput_async(struct mm_struct * mm)1181 void mmput_async(struct mm_struct *mm)
1182 {
1183 if (atomic_dec_and_test(&mm->mm_users)) {
1184 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1185 schedule_work(&mm->async_put_work);
1186 }
1187 }
1188 EXPORT_SYMBOL_GPL(mmput_async);
1189 #endif
1190
1191 /**
1192 * set_mm_exe_file - change a reference to the mm's executable file
1193 *
1194 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1195 *
1196 * Main users are mmput() and sys_execve(). Callers prevent concurrent
1197 * invocations: in mmput() nobody alive left, in execve task is single
1198 * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
1199 * mm->exe_file, but does so without using set_mm_exe_file() in order
1200 * to do avoid the need for any locks.
1201 */
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1202 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1203 {
1204 struct file *old_exe_file;
1205
1206 /*
1207 * It is safe to dereference the exe_file without RCU as
1208 * this function is only called if nobody else can access
1209 * this mm -- see comment above for justification.
1210 */
1211 old_exe_file = rcu_dereference_raw(mm->exe_file);
1212
1213 if (new_exe_file)
1214 get_file(new_exe_file);
1215 rcu_assign_pointer(mm->exe_file, new_exe_file);
1216 if (old_exe_file)
1217 fput(old_exe_file);
1218 }
1219
1220 /**
1221 * get_mm_exe_file - acquire a reference to the mm's executable file
1222 *
1223 * Returns %NULL if mm has no associated executable file.
1224 * User must release file via fput().
1225 */
get_mm_exe_file(struct mm_struct * mm)1226 struct file *get_mm_exe_file(struct mm_struct *mm)
1227 {
1228 struct file *exe_file;
1229
1230 rcu_read_lock();
1231 exe_file = rcu_dereference(mm->exe_file);
1232 if (exe_file && !get_file_rcu(exe_file))
1233 exe_file = NULL;
1234 rcu_read_unlock();
1235 return exe_file;
1236 }
1237 EXPORT_SYMBOL(get_mm_exe_file);
1238
1239 /**
1240 * get_task_exe_file - acquire a reference to the task's executable file
1241 *
1242 * Returns %NULL if task's mm (if any) has no associated executable file or
1243 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1244 * User must release file via fput().
1245 */
get_task_exe_file(struct task_struct * task)1246 struct file *get_task_exe_file(struct task_struct *task)
1247 {
1248 struct file *exe_file = NULL;
1249 struct mm_struct *mm;
1250
1251 task_lock(task);
1252 mm = task->mm;
1253 if (mm) {
1254 if (!(task->flags & PF_KTHREAD))
1255 exe_file = get_mm_exe_file(mm);
1256 }
1257 task_unlock(task);
1258 return exe_file;
1259 }
1260 EXPORT_SYMBOL(get_task_exe_file);
1261
1262 /**
1263 * get_task_mm - acquire a reference to the task's mm
1264 *
1265 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1266 * this kernel workthread has transiently adopted a user mm with use_mm,
1267 * to do its AIO) is not set and if so returns a reference to it, after
1268 * bumping up the use count. User must release the mm via mmput()
1269 * after use. Typically used by /proc and ptrace.
1270 */
get_task_mm(struct task_struct * task)1271 struct mm_struct *get_task_mm(struct task_struct *task)
1272 {
1273 struct mm_struct *mm;
1274
1275 task_lock(task);
1276 mm = task->mm;
1277 if (mm) {
1278 if (task->flags & PF_KTHREAD)
1279 mm = NULL;
1280 else
1281 mmget(mm);
1282 }
1283 task_unlock(task);
1284 return mm;
1285 }
1286 EXPORT_SYMBOL_GPL(get_task_mm);
1287
mm_access(struct task_struct * task,unsigned int mode)1288 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1289 {
1290 struct mm_struct *mm;
1291 int err;
1292
1293 err = down_read_killable(&task->signal->exec_update_lock);
1294 if (err)
1295 return ERR_PTR(err);
1296
1297 mm = get_task_mm(task);
1298 if (mm && mm != current->mm &&
1299 !ptrace_may_access(task, mode)) {
1300 mmput(mm);
1301 mm = ERR_PTR(-EACCES);
1302 }
1303 up_read(&task->signal->exec_update_lock);
1304
1305 return mm;
1306 }
1307
complete_vfork_done(struct task_struct * tsk)1308 static void complete_vfork_done(struct task_struct *tsk)
1309 {
1310 struct completion *vfork;
1311
1312 task_lock(tsk);
1313 vfork = tsk->vfork_done;
1314 if (likely(vfork)) {
1315 tsk->vfork_done = NULL;
1316 complete(vfork);
1317 }
1318 task_unlock(tsk);
1319 }
1320
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)1321 static int wait_for_vfork_done(struct task_struct *child,
1322 struct completion *vfork)
1323 {
1324 int killed;
1325
1326 freezer_do_not_count();
1327 cgroup_enter_frozen();
1328 killed = wait_for_completion_killable(vfork);
1329 cgroup_leave_frozen(false);
1330 freezer_count();
1331
1332 if (killed) {
1333 task_lock(child);
1334 child->vfork_done = NULL;
1335 task_unlock(child);
1336 }
1337
1338 put_task_struct(child);
1339 return killed;
1340 }
1341
1342 /* Please note the differences between mmput and mm_release.
1343 * mmput is called whenever we stop holding onto a mm_struct,
1344 * error success whatever.
1345 *
1346 * mm_release is called after a mm_struct has been removed
1347 * from the current process.
1348 *
1349 * This difference is important for error handling, when we
1350 * only half set up a mm_struct for a new process and need to restore
1351 * the old one. Because we mmput the new mm_struct before
1352 * restoring the old one. . .
1353 * Eric Biederman 10 January 1998
1354 */
mm_release(struct task_struct * tsk,struct mm_struct * mm)1355 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1356 {
1357 uprobe_free_utask(tsk);
1358
1359 /* Get rid of any cached register state */
1360 deactivate_mm(tsk, mm);
1361
1362 /*
1363 * Signal userspace if we're not exiting with a core dump
1364 * because we want to leave the value intact for debugging
1365 * purposes.
1366 */
1367 if (tsk->clear_child_tid) {
1368 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1369 atomic_read(&mm->mm_users) > 1) {
1370 /*
1371 * We don't check the error code - if userspace has
1372 * not set up a proper pointer then tough luck.
1373 */
1374 put_user(0, tsk->clear_child_tid);
1375 do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1376 1, NULL, NULL, 0, 0);
1377 }
1378 tsk->clear_child_tid = NULL;
1379 }
1380
1381 /*
1382 * All done, finally we can wake up parent and return this mm to him.
1383 * Also kthread_stop() uses this completion for synchronization.
1384 */
1385 if (tsk->vfork_done)
1386 complete_vfork_done(tsk);
1387 }
1388
exit_mm_release(struct task_struct * tsk,struct mm_struct * mm)1389 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1390 {
1391 futex_exit_release(tsk);
1392 mm_release(tsk, mm);
1393 }
1394
exec_mm_release(struct task_struct * tsk,struct mm_struct * mm)1395 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1396 {
1397 futex_exec_release(tsk);
1398 mm_release(tsk, mm);
1399 }
1400
1401 /**
1402 * dup_mm() - duplicates an existing mm structure
1403 * @tsk: the task_struct with which the new mm will be associated.
1404 * @oldmm: the mm to duplicate.
1405 *
1406 * Allocates a new mm structure and duplicates the provided @oldmm structure
1407 * content into it.
1408 *
1409 * Return: the duplicated mm or NULL on failure.
1410 */
dup_mm(struct task_struct * tsk,struct mm_struct * oldmm)1411 static struct mm_struct *dup_mm(struct task_struct *tsk,
1412 struct mm_struct *oldmm)
1413 {
1414 struct mm_struct *mm;
1415 int err;
1416
1417 mm = allocate_mm();
1418 if (!mm)
1419 goto fail_nomem;
1420
1421 memcpy(mm, oldmm, sizeof(*mm));
1422
1423 if (!mm_init(mm, tsk, mm->user_ns))
1424 goto fail_nomem;
1425
1426 err = dup_mmap(mm, oldmm);
1427 if (err)
1428 goto free_pt;
1429
1430 mm->hiwater_rss = get_mm_rss(mm);
1431 mm->hiwater_vm = mm->total_vm;
1432
1433 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1434 goto free_pt;
1435
1436 return mm;
1437
1438 free_pt:
1439 /* don't put binfmt in mmput, we haven't got module yet */
1440 mm->binfmt = NULL;
1441 mm_init_owner(mm, NULL);
1442 mmput(mm);
1443
1444 fail_nomem:
1445 return NULL;
1446 }
1447
copy_mm(unsigned long clone_flags,struct task_struct * tsk)1448 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1449 {
1450 struct mm_struct *mm, *oldmm;
1451 int retval;
1452
1453 tsk->min_flt = tsk->maj_flt = 0;
1454 tsk->nvcsw = tsk->nivcsw = 0;
1455 #ifdef CONFIG_DETECT_HUNG_TASK
1456 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1457 tsk->last_switch_time = 0;
1458 #endif
1459
1460 tsk->mm = NULL;
1461 tsk->active_mm = NULL;
1462
1463 /*
1464 * Are we cloning a kernel thread?
1465 *
1466 * We need to steal a active VM for that..
1467 */
1468 oldmm = current->mm;
1469 if (!oldmm)
1470 return 0;
1471
1472 /* initialize the new vmacache entries */
1473 vmacache_flush(tsk);
1474
1475 if (clone_flags & CLONE_VM) {
1476 mmget(oldmm);
1477 mm = oldmm;
1478 goto good_mm;
1479 }
1480
1481 retval = -ENOMEM;
1482 mm = dup_mm(tsk, current->mm);
1483 if (!mm)
1484 goto fail_nomem;
1485
1486 good_mm:
1487 tsk->mm = mm;
1488 tsk->active_mm = mm;
1489 return 0;
1490
1491 fail_nomem:
1492 return retval;
1493 }
1494
copy_fs(unsigned long clone_flags,struct task_struct * tsk)1495 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1496 {
1497 struct fs_struct *fs = current->fs;
1498 if (clone_flags & CLONE_FS) {
1499 /* tsk->fs is already what we want */
1500 spin_lock(&fs->lock);
1501 if (fs->in_exec) {
1502 spin_unlock(&fs->lock);
1503 return -EAGAIN;
1504 }
1505 fs->users++;
1506 spin_unlock(&fs->lock);
1507 return 0;
1508 }
1509 tsk->fs = copy_fs_struct(fs);
1510 if (!tsk->fs)
1511 return -ENOMEM;
1512 return 0;
1513 }
1514
copy_files(unsigned long clone_flags,struct task_struct * tsk)1515 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1516 {
1517 struct files_struct *oldf, *newf;
1518 int error = 0;
1519
1520 /*
1521 * A background process may not have any files ...
1522 */
1523 oldf = current->files;
1524 if (!oldf)
1525 goto out;
1526
1527 if (clone_flags & CLONE_FILES) {
1528 atomic_inc(&oldf->count);
1529 goto out;
1530 }
1531
1532 newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1533 if (!newf)
1534 goto out;
1535
1536 tsk->files = newf;
1537 error = 0;
1538 out:
1539 return error;
1540 }
1541
copy_io(unsigned long clone_flags,struct task_struct * tsk)1542 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1543 {
1544 #ifdef CONFIG_BLOCK
1545 struct io_context *ioc = current->io_context;
1546 struct io_context *new_ioc;
1547
1548 if (!ioc)
1549 return 0;
1550 /*
1551 * Share io context with parent, if CLONE_IO is set
1552 */
1553 if (clone_flags & CLONE_IO) {
1554 ioc_task_link(ioc);
1555 tsk->io_context = ioc;
1556 } else if (ioprio_valid(ioc->ioprio)) {
1557 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1558 if (unlikely(!new_ioc))
1559 return -ENOMEM;
1560
1561 new_ioc->ioprio = ioc->ioprio;
1562 put_io_context(new_ioc);
1563 }
1564 #endif
1565 return 0;
1566 }
1567
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1568 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1569 {
1570 struct sighand_struct *sig;
1571
1572 if (clone_flags & CLONE_SIGHAND) {
1573 refcount_inc(¤t->sighand->count);
1574 return 0;
1575 }
1576 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1577 RCU_INIT_POINTER(tsk->sighand, sig);
1578 if (!sig)
1579 return -ENOMEM;
1580
1581 refcount_set(&sig->count, 1);
1582 spin_lock_irq(¤t->sighand->siglock);
1583 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1584 spin_unlock_irq(¤t->sighand->siglock);
1585
1586 /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1587 if (clone_flags & CLONE_CLEAR_SIGHAND)
1588 flush_signal_handlers(tsk, 0);
1589
1590 return 0;
1591 }
1592
__cleanup_sighand(struct sighand_struct * sighand)1593 void __cleanup_sighand(struct sighand_struct *sighand)
1594 {
1595 if (refcount_dec_and_test(&sighand->count)) {
1596 signalfd_cleanup(sighand);
1597 /*
1598 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1599 * without an RCU grace period, see __lock_task_sighand().
1600 */
1601 kmem_cache_free(sighand_cachep, sighand);
1602 }
1603 }
1604
1605 /*
1606 * Initialize POSIX timer handling for a thread group.
1607 */
posix_cpu_timers_init_group(struct signal_struct * sig)1608 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1609 {
1610 struct posix_cputimers *pct = &sig->posix_cputimers;
1611 unsigned long cpu_limit;
1612
1613 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1614 posix_cputimers_group_init(pct, cpu_limit);
1615 }
1616
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1617 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1618 {
1619 struct signal_struct *sig;
1620
1621 if (clone_flags & CLONE_THREAD)
1622 return 0;
1623
1624 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1625 tsk->signal = sig;
1626 if (!sig)
1627 return -ENOMEM;
1628
1629 sig->nr_threads = 1;
1630 atomic_set(&sig->live, 1);
1631 refcount_set(&sig->sigcnt, 1);
1632
1633 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1634 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1635 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1636
1637 init_waitqueue_head(&sig->wait_chldexit);
1638 sig->curr_target = tsk;
1639 init_sigpending(&sig->shared_pending);
1640 INIT_HLIST_HEAD(&sig->multiprocess);
1641 seqlock_init(&sig->stats_lock);
1642 prev_cputime_init(&sig->prev_cputime);
1643
1644 #ifdef CONFIG_POSIX_TIMERS
1645 INIT_LIST_HEAD(&sig->posix_timers);
1646 hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1647 sig->real_timer.function = it_real_fn;
1648 #endif
1649
1650 task_lock(current->group_leader);
1651 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1652 task_unlock(current->group_leader);
1653
1654 posix_cpu_timers_init_group(sig);
1655
1656 tty_audit_fork(sig);
1657 sched_autogroup_fork(sig);
1658
1659 sig->oom_score_adj = current->signal->oom_score_adj;
1660 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1661
1662 mutex_init(&sig->cred_guard_mutex);
1663 init_rwsem(&sig->exec_update_lock);
1664
1665 return 0;
1666 }
1667
copy_seccomp(struct task_struct * p)1668 static void copy_seccomp(struct task_struct *p)
1669 {
1670 #ifdef CONFIG_SECCOMP
1671 /*
1672 * Must be called with sighand->lock held, which is common to
1673 * all threads in the group. Holding cred_guard_mutex is not
1674 * needed because this new task is not yet running and cannot
1675 * be racing exec.
1676 */
1677 assert_spin_locked(¤t->sighand->siglock);
1678
1679 /* Ref-count the new filter user, and assign it. */
1680 get_seccomp_filter(current);
1681 p->seccomp = current->seccomp;
1682
1683 /*
1684 * Explicitly enable no_new_privs here in case it got set
1685 * between the task_struct being duplicated and holding the
1686 * sighand lock. The seccomp state and nnp must be in sync.
1687 */
1688 if (task_no_new_privs(current))
1689 task_set_no_new_privs(p);
1690
1691 /*
1692 * If the parent gained a seccomp mode after copying thread
1693 * flags and between before we held the sighand lock, we have
1694 * to manually enable the seccomp thread flag here.
1695 */
1696 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1697 set_tsk_thread_flag(p, TIF_SECCOMP);
1698 #endif
1699 }
1700
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1701 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1702 {
1703 current->clear_child_tid = tidptr;
1704
1705 return task_pid_vnr(current);
1706 }
1707
rt_mutex_init_task(struct task_struct * p)1708 static void rt_mutex_init_task(struct task_struct *p)
1709 {
1710 raw_spin_lock_init(&p->pi_lock);
1711 #ifdef CONFIG_RT_MUTEXES
1712 p->pi_waiters = RB_ROOT_CACHED;
1713 p->pi_top_task = NULL;
1714 p->pi_blocked_on = NULL;
1715 #endif
1716 }
1717
init_task_pid_links(struct task_struct * task)1718 static inline void init_task_pid_links(struct task_struct *task)
1719 {
1720 enum pid_type type;
1721
1722 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1723 INIT_HLIST_NODE(&task->pid_links[type]);
1724 }
1725 }
1726
1727 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1728 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1729 {
1730 if (type == PIDTYPE_PID)
1731 task->thread_pid = pid;
1732 else
1733 task->signal->pids[type] = pid;
1734 }
1735
rcu_copy_process(struct task_struct * p)1736 static inline void rcu_copy_process(struct task_struct *p)
1737 {
1738 #ifdef CONFIG_PREEMPT_RCU
1739 p->rcu_read_lock_nesting = 0;
1740 p->rcu_read_unlock_special.s = 0;
1741 p->rcu_blocked_node = NULL;
1742 INIT_LIST_HEAD(&p->rcu_node_entry);
1743 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1744 #ifdef CONFIG_TASKS_RCU
1745 p->rcu_tasks_holdout = false;
1746 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1747 p->rcu_tasks_idle_cpu = -1;
1748 #endif /* #ifdef CONFIG_TASKS_RCU */
1749 #ifdef CONFIG_TASKS_TRACE_RCU
1750 p->trc_reader_nesting = 0;
1751 p->trc_reader_special.s = 0;
1752 INIT_LIST_HEAD(&p->trc_holdout_list);
1753 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
1754 }
1755
pidfd_pid(const struct file * file)1756 struct pid *pidfd_pid(const struct file *file)
1757 {
1758 if (file->f_op == &pidfd_fops)
1759 return file->private_data;
1760
1761 return ERR_PTR(-EBADF);
1762 }
1763
pidfd_release(struct inode * inode,struct file * file)1764 static int pidfd_release(struct inode *inode, struct file *file)
1765 {
1766 struct pid *pid = file->private_data;
1767
1768 file->private_data = NULL;
1769 put_pid(pid);
1770 return 0;
1771 }
1772
1773 #ifdef CONFIG_PROC_FS
1774 /**
1775 * pidfd_show_fdinfo - print information about a pidfd
1776 * @m: proc fdinfo file
1777 * @f: file referencing a pidfd
1778 *
1779 * Pid:
1780 * This function will print the pid that a given pidfd refers to in the
1781 * pid namespace of the procfs instance.
1782 * If the pid namespace of the process is not a descendant of the pid
1783 * namespace of the procfs instance 0 will be shown as its pid. This is
1784 * similar to calling getppid() on a process whose parent is outside of
1785 * its pid namespace.
1786 *
1787 * NSpid:
1788 * If pid namespaces are supported then this function will also print
1789 * the pid of a given pidfd refers to for all descendant pid namespaces
1790 * starting from the current pid namespace of the instance, i.e. the
1791 * Pid field and the first entry in the NSpid field will be identical.
1792 * If the pid namespace of the process is not a descendant of the pid
1793 * namespace of the procfs instance 0 will be shown as its first NSpid
1794 * entry and no others will be shown.
1795 * Note that this differs from the Pid and NSpid fields in
1796 * /proc/<pid>/status where Pid and NSpid are always shown relative to
1797 * the pid namespace of the procfs instance. The difference becomes
1798 * obvious when sending around a pidfd between pid namespaces from a
1799 * different branch of the tree, i.e. where no ancestoral relation is
1800 * present between the pid namespaces:
1801 * - create two new pid namespaces ns1 and ns2 in the initial pid
1802 * namespace (also take care to create new mount namespaces in the
1803 * new pid namespace and mount procfs)
1804 * - create a process with a pidfd in ns1
1805 * - send pidfd from ns1 to ns2
1806 * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
1807 * have exactly one entry, which is 0
1808 */
pidfd_show_fdinfo(struct seq_file * m,struct file * f)1809 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1810 {
1811 struct pid *pid = f->private_data;
1812 struct pid_namespace *ns;
1813 pid_t nr = -1;
1814
1815 if (likely(pid_has_task(pid, PIDTYPE_PID))) {
1816 ns = proc_pid_ns(file_inode(m->file)->i_sb);
1817 nr = pid_nr_ns(pid, ns);
1818 }
1819
1820 seq_put_decimal_ll(m, "Pid:\t", nr);
1821
1822 #ifdef CONFIG_PID_NS
1823 seq_put_decimal_ll(m, "\nNSpid:\t", nr);
1824 if (nr > 0) {
1825 int i;
1826
1827 /* If nr is non-zero it means that 'pid' is valid and that
1828 * ns, i.e. the pid namespace associated with the procfs
1829 * instance, is in the pid namespace hierarchy of pid.
1830 * Start at one below the already printed level.
1831 */
1832 for (i = ns->level + 1; i <= pid->level; i++)
1833 seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
1834 }
1835 #endif
1836 seq_putc(m, '\n');
1837 }
1838 #endif
1839
1840 /*
1841 * Poll support for process exit notification.
1842 */
pidfd_poll(struct file * file,struct poll_table_struct * pts)1843 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1844 {
1845 struct pid *pid = file->private_data;
1846 __poll_t poll_flags = 0;
1847
1848 poll_wait(file, &pid->wait_pidfd, pts);
1849
1850 /*
1851 * Inform pollers only when the whole thread group exits.
1852 * If the thread group leader exits before all other threads in the
1853 * group, then poll(2) should block, similar to the wait(2) family.
1854 */
1855 if (thread_group_exited(pid))
1856 poll_flags = EPOLLIN | EPOLLRDNORM;
1857
1858 return poll_flags;
1859 }
1860
1861 const struct file_operations pidfd_fops = {
1862 .release = pidfd_release,
1863 .poll = pidfd_poll,
1864 #ifdef CONFIG_PROC_FS
1865 .show_fdinfo = pidfd_show_fdinfo,
1866 #endif
1867 };
1868
__delayed_free_task(struct rcu_head * rhp)1869 static void __delayed_free_task(struct rcu_head *rhp)
1870 {
1871 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1872
1873 free_task(tsk);
1874 }
1875
delayed_free_task(struct task_struct * tsk)1876 static __always_inline void delayed_free_task(struct task_struct *tsk)
1877 {
1878 if (IS_ENABLED(CONFIG_MEMCG))
1879 call_rcu(&tsk->rcu, __delayed_free_task);
1880 else
1881 free_task(tsk);
1882 }
1883
copy_oom_score_adj(u64 clone_flags,struct task_struct * tsk)1884 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
1885 {
1886 /* Skip if kernel thread */
1887 if (!tsk->mm)
1888 return;
1889
1890 /* Skip if spawning a thread or using vfork */
1891 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
1892 return;
1893
1894 /* We need to synchronize with __set_oom_adj */
1895 mutex_lock(&oom_adj_mutex);
1896 set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
1897 /* Update the values in case they were changed after copy_signal */
1898 tsk->signal->oom_score_adj = current->signal->oom_score_adj;
1899 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
1900 mutex_unlock(&oom_adj_mutex);
1901 }
1902
1903 /*
1904 * This creates a new process as a copy of the old one,
1905 * but does not actually start it yet.
1906 *
1907 * It copies the registers, and all the appropriate
1908 * parts of the process environment (as per the clone
1909 * flags). The actual kick-off is left to the caller.
1910 */
copy_process(struct pid * pid,int trace,int node,struct kernel_clone_args * args)1911 static __latent_entropy struct task_struct *copy_process(
1912 struct pid *pid,
1913 int trace,
1914 int node,
1915 struct kernel_clone_args *args)
1916 {
1917 int pidfd = -1, retval;
1918 struct task_struct *p;
1919 struct multiprocess_signals delayed;
1920 struct file *pidfile = NULL;
1921 u64 clone_flags = args->flags;
1922 struct nsproxy *nsp = current->nsproxy;
1923
1924 /*
1925 * Don't allow sharing the root directory with processes in a different
1926 * namespace
1927 */
1928 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1929 return ERR_PTR(-EINVAL);
1930
1931 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1932 return ERR_PTR(-EINVAL);
1933
1934 /*
1935 * Thread groups must share signals as well, and detached threads
1936 * can only be started up within the thread group.
1937 */
1938 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1939 return ERR_PTR(-EINVAL);
1940
1941 /*
1942 * Shared signal handlers imply shared VM. By way of the above,
1943 * thread groups also imply shared VM. Blocking this case allows
1944 * for various simplifications in other code.
1945 */
1946 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1947 return ERR_PTR(-EINVAL);
1948
1949 /*
1950 * Siblings of global init remain as zombies on exit since they are
1951 * not reaped by their parent (swapper). To solve this and to avoid
1952 * multi-rooted process trees, prevent global and container-inits
1953 * from creating siblings.
1954 */
1955 if ((clone_flags & CLONE_PARENT) &&
1956 current->signal->flags & SIGNAL_UNKILLABLE)
1957 return ERR_PTR(-EINVAL);
1958
1959 /*
1960 * If the new process will be in a different pid or user namespace
1961 * do not allow it to share a thread group with the forking task.
1962 */
1963 if (clone_flags & CLONE_THREAD) {
1964 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1965 (task_active_pid_ns(current) != nsp->pid_ns_for_children))
1966 return ERR_PTR(-EINVAL);
1967 }
1968
1969 /*
1970 * If the new process will be in a different time namespace
1971 * do not allow it to share VM or a thread group with the forking task.
1972 */
1973 if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
1974 if (nsp->time_ns != nsp->time_ns_for_children)
1975 return ERR_PTR(-EINVAL);
1976 }
1977
1978 if (clone_flags & CLONE_PIDFD) {
1979 /*
1980 * - CLONE_DETACHED is blocked so that we can potentially
1981 * reuse it later for CLONE_PIDFD.
1982 * - CLONE_THREAD is blocked until someone really needs it.
1983 */
1984 if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1985 return ERR_PTR(-EINVAL);
1986 }
1987
1988 /*
1989 * Force any signals received before this point to be delivered
1990 * before the fork happens. Collect up signals sent to multiple
1991 * processes that happen during the fork and delay them so that
1992 * they appear to happen after the fork.
1993 */
1994 sigemptyset(&delayed.signal);
1995 INIT_HLIST_NODE(&delayed.node);
1996
1997 spin_lock_irq(¤t->sighand->siglock);
1998 if (!(clone_flags & CLONE_THREAD))
1999 hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2000 recalc_sigpending();
2001 spin_unlock_irq(¤t->sighand->siglock);
2002 retval = -ERESTARTNOINTR;
2003 if (task_sigpending(current))
2004 goto fork_out;
2005
2006 retval = -ENOMEM;
2007 p = dup_task_struct(current, node);
2008 if (!p)
2009 goto fork_out;
2010 if (args->io_thread) {
2011 /*
2012 * Mark us an IO worker, and block any signal that isn't
2013 * fatal or STOP
2014 */
2015 p->flags |= PF_IO_WORKER;
2016 siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2017 }
2018
2019 cpufreq_task_times_init(p);
2020
2021 /*
2022 * This _must_ happen before we call free_task(), i.e. before we jump
2023 * to any of the bad_fork_* labels. This is to avoid freeing
2024 * p->set_child_tid which is (ab)used as a kthread's data pointer for
2025 * kernel threads (PF_KTHREAD).
2026 */
2027 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2028 /*
2029 * Clear TID on mm_release()?
2030 */
2031 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2032
2033 ftrace_graph_init_task(p);
2034
2035 rt_mutex_init_task(p);
2036
2037 lockdep_assert_irqs_enabled();
2038 #ifdef CONFIG_PROVE_LOCKING
2039 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2040 #endif
2041 retval = -EAGAIN;
2042 if (atomic_read(&p->real_cred->user->processes) >=
2043 task_rlimit(p, RLIMIT_NPROC)) {
2044 if (p->real_cred->user != INIT_USER &&
2045 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2046 goto bad_fork_free;
2047 }
2048 current->flags &= ~PF_NPROC_EXCEEDED;
2049
2050 retval = copy_creds(p, clone_flags);
2051 if (retval < 0)
2052 goto bad_fork_free;
2053
2054 /*
2055 * If multiple threads are within copy_process(), then this check
2056 * triggers too late. This doesn't hurt, the check is only there
2057 * to stop root fork bombs.
2058 */
2059 retval = -EAGAIN;
2060 if (data_race(nr_threads >= max_threads))
2061 goto bad_fork_cleanup_count;
2062
2063 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
2064 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
2065 p->flags |= PF_FORKNOEXEC;
2066 INIT_LIST_HEAD(&p->children);
2067 INIT_LIST_HEAD(&p->sibling);
2068 rcu_copy_process(p);
2069 p->vfork_done = NULL;
2070 spin_lock_init(&p->alloc_lock);
2071
2072 init_sigpending(&p->pending);
2073
2074 p->utime = p->stime = p->gtime = 0;
2075 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2076 p->utimescaled = p->stimescaled = 0;
2077 #endif
2078 prev_cputime_init(&p->prev_cputime);
2079
2080 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2081 seqcount_init(&p->vtime.seqcount);
2082 p->vtime.starttime = 0;
2083 p->vtime.state = VTIME_INACTIVE;
2084 #endif
2085
2086 #ifdef CONFIG_IO_URING
2087 p->io_uring = NULL;
2088 #endif
2089
2090 #if defined(SPLIT_RSS_COUNTING)
2091 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2092 #endif
2093
2094 p->default_timer_slack_ns = current->timer_slack_ns;
2095
2096 #ifdef CONFIG_PSI
2097 p->psi_flags = 0;
2098 #endif
2099
2100 task_io_accounting_init(&p->ioac);
2101 acct_clear_integrals(p);
2102
2103 posix_cputimers_init(&p->posix_cputimers);
2104
2105 p->io_context = NULL;
2106 audit_set_context(p, NULL);
2107 cgroup_fork(p);
2108 #ifdef CONFIG_NUMA
2109 p->mempolicy = mpol_dup(p->mempolicy);
2110 if (IS_ERR(p->mempolicy)) {
2111 retval = PTR_ERR(p->mempolicy);
2112 p->mempolicy = NULL;
2113 goto bad_fork_cleanup_threadgroup_lock;
2114 }
2115 #endif
2116 #ifdef CONFIG_CPUSETS
2117 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2118 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2119 seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2120 #endif
2121 #ifdef CONFIG_TRACE_IRQFLAGS
2122 memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2123 p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2124 p->irqtrace.softirq_enable_ip = _THIS_IP_;
2125 p->softirqs_enabled = 1;
2126 p->softirq_context = 0;
2127 #endif
2128
2129 p->pagefault_disabled = 0;
2130
2131 #ifdef CONFIG_LOCKDEP
2132 lockdep_init_task(p);
2133 #endif
2134
2135 #ifdef CONFIG_DEBUG_MUTEXES
2136 p->blocked_on = NULL; /* not blocked yet */
2137 #endif
2138 #ifdef CONFIG_BCACHE
2139 p->sequential_io = 0;
2140 p->sequential_io_avg = 0;
2141 #endif
2142
2143 /* Perform scheduler related setup. Assign this task to a CPU. */
2144 retval = sched_fork(clone_flags, p);
2145 if (retval)
2146 goto bad_fork_cleanup_policy;
2147
2148 retval = perf_event_init_task(p);
2149 if (retval)
2150 goto bad_fork_cleanup_policy;
2151 retval = audit_alloc(p);
2152 if (retval)
2153 goto bad_fork_cleanup_perf;
2154 /* copy all the process information */
2155 shm_init_task(p);
2156 retval = security_task_alloc(p, clone_flags);
2157 if (retval)
2158 goto bad_fork_cleanup_audit;
2159 retval = copy_semundo(clone_flags, p);
2160 if (retval)
2161 goto bad_fork_cleanup_security;
2162 retval = copy_files(clone_flags, p);
2163 if (retval)
2164 goto bad_fork_cleanup_semundo;
2165 retval = copy_fs(clone_flags, p);
2166 if (retval)
2167 goto bad_fork_cleanup_files;
2168 retval = copy_sighand(clone_flags, p);
2169 if (retval)
2170 goto bad_fork_cleanup_fs;
2171 retval = copy_signal(clone_flags, p);
2172 if (retval)
2173 goto bad_fork_cleanup_sighand;
2174 retval = copy_mm(clone_flags, p);
2175 if (retval)
2176 goto bad_fork_cleanup_signal;
2177 retval = copy_namespaces(clone_flags, p);
2178 if (retval)
2179 goto bad_fork_cleanup_mm;
2180 retval = copy_io(clone_flags, p);
2181 if (retval)
2182 goto bad_fork_cleanup_namespaces;
2183 retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
2184 if (retval)
2185 goto bad_fork_cleanup_io;
2186
2187 stackleak_task_init(p);
2188
2189 if (pid != &init_struct_pid) {
2190 pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2191 args->set_tid_size);
2192 if (IS_ERR(pid)) {
2193 retval = PTR_ERR(pid);
2194 goto bad_fork_cleanup_thread;
2195 }
2196 }
2197
2198 /*
2199 * This has to happen after we've potentially unshared the file
2200 * descriptor table (so that the pidfd doesn't leak into the child
2201 * if the fd table isn't shared).
2202 */
2203 if (clone_flags & CLONE_PIDFD) {
2204 retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2205 if (retval < 0)
2206 goto bad_fork_free_pid;
2207
2208 pidfd = retval;
2209
2210 pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2211 O_RDWR | O_CLOEXEC);
2212 if (IS_ERR(pidfile)) {
2213 put_unused_fd(pidfd);
2214 retval = PTR_ERR(pidfile);
2215 goto bad_fork_free_pid;
2216 }
2217 get_pid(pid); /* held by pidfile now */
2218
2219 retval = put_user(pidfd, args->pidfd);
2220 if (retval)
2221 goto bad_fork_put_pidfd;
2222 }
2223
2224 #ifdef CONFIG_BLOCK
2225 p->plug = NULL;
2226 #endif
2227 futex_init_task(p);
2228
2229 /*
2230 * sigaltstack should be cleared when sharing the same VM
2231 */
2232 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2233 sas_ss_reset(p);
2234
2235 /*
2236 * Syscall tracing and stepping should be turned off in the
2237 * child regardless of CLONE_PTRACE.
2238 */
2239 user_disable_single_step(p);
2240 clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2241 #ifdef TIF_SYSCALL_EMU
2242 clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2243 #endif
2244 clear_tsk_latency_tracing(p);
2245
2246 /* ok, now we should be set up.. */
2247 p->pid = pid_nr(pid);
2248 if (clone_flags & CLONE_THREAD) {
2249 p->group_leader = current->group_leader;
2250 p->tgid = current->tgid;
2251 } else {
2252 p->group_leader = p;
2253 p->tgid = p->pid;
2254 }
2255
2256 p->nr_dirtied = 0;
2257 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2258 p->dirty_paused_when = 0;
2259
2260 p->pdeath_signal = 0;
2261 INIT_LIST_HEAD(&p->thread_group);
2262 p->task_works = NULL;
2263 clear_posix_cputimers_work(p);
2264
2265 /*
2266 * Ensure that the cgroup subsystem policies allow the new process to be
2267 * forked. It should be noted that the new process's css_set can be changed
2268 * between here and cgroup_post_fork() if an organisation operation is in
2269 * progress.
2270 */
2271 retval = cgroup_can_fork(p, args);
2272 if (retval)
2273 goto bad_fork_put_pidfd;
2274
2275 /*
2276 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2277 * the new task on the correct runqueue. All this *before* the task
2278 * becomes visible.
2279 *
2280 * This isn't part of ->can_fork() because while the re-cloning is
2281 * cgroup specific, it unconditionally needs to place the task on a
2282 * runqueue.
2283 */
2284 sched_cgroup_fork(p, args);
2285
2286 /*
2287 * From this point on we must avoid any synchronous user-space
2288 * communication until we take the tasklist-lock. In particular, we do
2289 * not want user-space to be able to predict the process start-time by
2290 * stalling fork(2) after we recorded the start_time but before it is
2291 * visible to the system.
2292 */
2293
2294 p->start_time = ktime_get_ns();
2295 p->start_boottime = ktime_get_boottime_ns();
2296
2297 /*
2298 * Make it visible to the rest of the system, but dont wake it up yet.
2299 * Need tasklist lock for parent etc handling!
2300 */
2301 write_lock_irq(&tasklist_lock);
2302
2303 /* CLONE_PARENT re-uses the old parent */
2304 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2305 p->real_parent = current->real_parent;
2306 p->parent_exec_id = current->parent_exec_id;
2307 if (clone_flags & CLONE_THREAD)
2308 p->exit_signal = -1;
2309 else
2310 p->exit_signal = current->group_leader->exit_signal;
2311 } else {
2312 p->real_parent = current;
2313 p->parent_exec_id = current->self_exec_id;
2314 p->exit_signal = args->exit_signal;
2315 }
2316
2317 klp_copy_process(p);
2318
2319 spin_lock(¤t->sighand->siglock);
2320
2321 rseq_fork(p, clone_flags);
2322
2323 /* Don't start children in a dying pid namespace */
2324 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2325 retval = -ENOMEM;
2326 goto bad_fork_cancel_cgroup;
2327 }
2328
2329 /* Let kill terminate clone/fork in the middle */
2330 if (fatal_signal_pending(current)) {
2331 retval = -EINTR;
2332 goto bad_fork_cancel_cgroup;
2333 }
2334
2335 /* No more failure paths after this point. */
2336
2337 /*
2338 * Copy seccomp details explicitly here, in case they were changed
2339 * before holding sighand lock.
2340 */
2341 copy_seccomp(p);
2342
2343 init_task_pid_links(p);
2344 if (likely(p->pid)) {
2345 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2346
2347 init_task_pid(p, PIDTYPE_PID, pid);
2348 if (thread_group_leader(p)) {
2349 init_task_pid(p, PIDTYPE_TGID, pid);
2350 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2351 init_task_pid(p, PIDTYPE_SID, task_session(current));
2352
2353 if (is_child_reaper(pid)) {
2354 ns_of_pid(pid)->child_reaper = p;
2355 p->signal->flags |= SIGNAL_UNKILLABLE;
2356 }
2357 p->signal->shared_pending.signal = delayed.signal;
2358 p->signal->tty = tty_kref_get(current->signal->tty);
2359 /*
2360 * Inherit has_child_subreaper flag under the same
2361 * tasklist_lock with adding child to the process tree
2362 * for propagate_has_child_subreaper optimization.
2363 */
2364 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2365 p->real_parent->signal->is_child_subreaper;
2366 list_add_tail(&p->sibling, &p->real_parent->children);
2367 list_add_tail_rcu(&p->tasks, &init_task.tasks);
2368 attach_pid(p, PIDTYPE_TGID);
2369 attach_pid(p, PIDTYPE_PGID);
2370 attach_pid(p, PIDTYPE_SID);
2371 __this_cpu_inc(process_counts);
2372 } else {
2373 current->signal->nr_threads++;
2374 atomic_inc(¤t->signal->live);
2375 refcount_inc(¤t->signal->sigcnt);
2376 task_join_group_stop(p);
2377 list_add_tail_rcu(&p->thread_group,
2378 &p->group_leader->thread_group);
2379 list_add_tail_rcu(&p->thread_node,
2380 &p->signal->thread_head);
2381 }
2382 attach_pid(p, PIDTYPE_PID);
2383 nr_threads++;
2384 }
2385 total_forks++;
2386 hlist_del_init(&delayed.node);
2387 spin_unlock(¤t->sighand->siglock);
2388 syscall_tracepoint_update(p);
2389 write_unlock_irq(&tasklist_lock);
2390
2391 if (pidfile)
2392 fd_install(pidfd, pidfile);
2393
2394 proc_fork_connector(p);
2395 sched_post_fork(p);
2396 cgroup_post_fork(p, args);
2397 perf_event_fork(p);
2398
2399 trace_task_newtask(p, clone_flags);
2400 uprobe_copy_process(p, clone_flags);
2401
2402 copy_oom_score_adj(clone_flags, p);
2403
2404 return p;
2405
2406 bad_fork_cancel_cgroup:
2407 spin_unlock(¤t->sighand->siglock);
2408 write_unlock_irq(&tasklist_lock);
2409 cgroup_cancel_fork(p, args);
2410 bad_fork_put_pidfd:
2411 if (clone_flags & CLONE_PIDFD) {
2412 fput(pidfile);
2413 put_unused_fd(pidfd);
2414 }
2415 bad_fork_free_pid:
2416 if (pid != &init_struct_pid)
2417 free_pid(pid);
2418 bad_fork_cleanup_thread:
2419 exit_thread(p);
2420 bad_fork_cleanup_io:
2421 if (p->io_context)
2422 exit_io_context(p);
2423 bad_fork_cleanup_namespaces:
2424 exit_task_namespaces(p);
2425 bad_fork_cleanup_mm:
2426 if (p->mm) {
2427 mm_clear_owner(p->mm, p);
2428 mmput(p->mm);
2429 }
2430 bad_fork_cleanup_signal:
2431 if (!(clone_flags & CLONE_THREAD))
2432 free_signal_struct(p->signal);
2433 bad_fork_cleanup_sighand:
2434 __cleanup_sighand(p->sighand);
2435 bad_fork_cleanup_fs:
2436 exit_fs(p); /* blocking */
2437 bad_fork_cleanup_files:
2438 exit_files(p); /* blocking */
2439 bad_fork_cleanup_semundo:
2440 exit_sem(p);
2441 bad_fork_cleanup_security:
2442 security_task_free(p);
2443 bad_fork_cleanup_audit:
2444 audit_free(p);
2445 bad_fork_cleanup_perf:
2446 perf_event_free_task(p);
2447 bad_fork_cleanup_policy:
2448 lockdep_free_task(p);
2449 #ifdef CONFIG_NUMA
2450 mpol_put(p->mempolicy);
2451 bad_fork_cleanup_threadgroup_lock:
2452 #endif
2453 delayacct_tsk_free(p);
2454 bad_fork_cleanup_count:
2455 atomic_dec(&p->cred->user->processes);
2456 exit_creds(p);
2457 bad_fork_free:
2458 p->state = TASK_DEAD;
2459 put_task_stack(p);
2460 delayed_free_task(p);
2461 fork_out:
2462 spin_lock_irq(¤t->sighand->siglock);
2463 hlist_del_init(&delayed.node);
2464 spin_unlock_irq(¤t->sighand->siglock);
2465 return ERR_PTR(retval);
2466 }
2467
init_idle_pids(struct task_struct * idle)2468 static inline void init_idle_pids(struct task_struct *idle)
2469 {
2470 enum pid_type type;
2471
2472 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2473 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2474 init_task_pid(idle, type, &init_struct_pid);
2475 }
2476 }
2477
fork_idle(int cpu)2478 struct task_struct * __init fork_idle(int cpu)
2479 {
2480 struct task_struct *task;
2481 struct kernel_clone_args args = {
2482 .flags = CLONE_VM,
2483 };
2484
2485 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2486 if (!IS_ERR(task)) {
2487 init_idle_pids(task);
2488 init_idle(task, cpu);
2489 }
2490
2491 return task;
2492 }
2493
2494 /*
2495 * This is like kernel_clone(), but shaved down and tailored to just
2496 * creating io_uring workers. It returns a created task, or an error pointer.
2497 * The returned task is inactive, and the caller must fire it up through
2498 * wake_up_new_task(p). All signals are blocked in the created task.
2499 */
create_io_thread(int (* fn)(void *),void * arg,int node)2500 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2501 {
2502 unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2503 CLONE_IO;
2504 struct kernel_clone_args args = {
2505 .flags = ((lower_32_bits(flags) | CLONE_VM |
2506 CLONE_UNTRACED) & ~CSIGNAL),
2507 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2508 .stack = (unsigned long)fn,
2509 .stack_size = (unsigned long)arg,
2510 .io_thread = 1,
2511 };
2512
2513 return copy_process(NULL, 0, node, &args);
2514 }
2515
2516 /*
2517 * Ok, this is the main fork-routine.
2518 *
2519 * It copies the process, and if successful kick-starts
2520 * it and waits for it to finish using the VM if required.
2521 *
2522 * args->exit_signal is expected to be checked for sanity by the caller.
2523 */
kernel_clone(struct kernel_clone_args * args)2524 pid_t kernel_clone(struct kernel_clone_args *args)
2525 {
2526 u64 clone_flags = args->flags;
2527 struct completion vfork;
2528 struct pid *pid;
2529 struct task_struct *p;
2530 int trace = 0;
2531 pid_t nr;
2532
2533 /*
2534 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2535 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2536 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2537 * field in struct clone_args and it still doesn't make sense to have
2538 * them both point at the same memory location. Performing this check
2539 * here has the advantage that we don't need to have a separate helper
2540 * to check for legacy clone().
2541 */
2542 if ((args->flags & CLONE_PIDFD) &&
2543 (args->flags & CLONE_PARENT_SETTID) &&
2544 (args->pidfd == args->parent_tid))
2545 return -EINVAL;
2546
2547 /*
2548 * Determine whether and which event to report to ptracer. When
2549 * called from kernel_thread or CLONE_UNTRACED is explicitly
2550 * requested, no event is reported; otherwise, report if the event
2551 * for the type of forking is enabled.
2552 */
2553 if (!(clone_flags & CLONE_UNTRACED)) {
2554 if (clone_flags & CLONE_VFORK)
2555 trace = PTRACE_EVENT_VFORK;
2556 else if (args->exit_signal != SIGCHLD)
2557 trace = PTRACE_EVENT_CLONE;
2558 else
2559 trace = PTRACE_EVENT_FORK;
2560
2561 if (likely(!ptrace_event_enabled(current, trace)))
2562 trace = 0;
2563 }
2564
2565 p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2566 add_latent_entropy();
2567
2568 if (IS_ERR(p))
2569 return PTR_ERR(p);
2570
2571 cpufreq_task_times_alloc(p);
2572
2573 /*
2574 * Do this prior waking up the new thread - the thread pointer
2575 * might get invalid after that point, if the thread exits quickly.
2576 */
2577 trace_sched_process_fork(current, p);
2578
2579 pid = get_task_pid(p, PIDTYPE_PID);
2580 nr = pid_vnr(pid);
2581
2582 if (clone_flags & CLONE_PARENT_SETTID)
2583 put_user(nr, args->parent_tid);
2584
2585 if (clone_flags & CLONE_VFORK) {
2586 p->vfork_done = &vfork;
2587 init_completion(&vfork);
2588 get_task_struct(p);
2589 }
2590
2591 wake_up_new_task(p);
2592
2593 /* forking complete and child started to run, tell ptracer */
2594 if (unlikely(trace))
2595 ptrace_event_pid(trace, pid);
2596
2597 if (clone_flags & CLONE_VFORK) {
2598 if (!wait_for_vfork_done(p, &vfork))
2599 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2600 }
2601
2602 put_pid(pid);
2603 return nr;
2604 }
2605
2606 /*
2607 * Create a kernel thread.
2608 */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)2609 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2610 {
2611 struct kernel_clone_args args = {
2612 .flags = ((lower_32_bits(flags) | CLONE_VM |
2613 CLONE_UNTRACED) & ~CSIGNAL),
2614 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2615 .stack = (unsigned long)fn,
2616 .stack_size = (unsigned long)arg,
2617 };
2618
2619 return kernel_clone(&args);
2620 }
2621
2622 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)2623 SYSCALL_DEFINE0(fork)
2624 {
2625 #ifdef CONFIG_MMU
2626 struct kernel_clone_args args = {
2627 .exit_signal = SIGCHLD,
2628 };
2629
2630 return kernel_clone(&args);
2631 #else
2632 /* can not support in nommu mode */
2633 return -EINVAL;
2634 #endif
2635 }
2636 #endif
2637
2638 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)2639 SYSCALL_DEFINE0(vfork)
2640 {
2641 struct kernel_clone_args args = {
2642 .flags = CLONE_VFORK | CLONE_VM,
2643 .exit_signal = SIGCHLD,
2644 };
2645
2646 return kernel_clone(&args);
2647 }
2648 #endif
2649
2650 #ifdef __ARCH_WANT_SYS_CLONE
2651 #ifdef CONFIG_CLONE_BACKWARDS
SYSCALL_DEFINE5(clone,unsigned long,clone_flags,unsigned long,newsp,int __user *,parent_tidptr,unsigned long,tls,int __user *,child_tidptr)2652 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2653 int __user *, parent_tidptr,
2654 unsigned long, tls,
2655 int __user *, child_tidptr)
2656 #elif defined(CONFIG_CLONE_BACKWARDS2)
2657 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2658 int __user *, parent_tidptr,
2659 int __user *, child_tidptr,
2660 unsigned long, tls)
2661 #elif defined(CONFIG_CLONE_BACKWARDS3)
2662 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2663 int, stack_size,
2664 int __user *, parent_tidptr,
2665 int __user *, child_tidptr,
2666 unsigned long, tls)
2667 #else
2668 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2669 int __user *, parent_tidptr,
2670 int __user *, child_tidptr,
2671 unsigned long, tls)
2672 #endif
2673 {
2674 struct kernel_clone_args args = {
2675 .flags = (lower_32_bits(clone_flags) & ~CSIGNAL),
2676 .pidfd = parent_tidptr,
2677 .child_tid = child_tidptr,
2678 .parent_tid = parent_tidptr,
2679 .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL),
2680 .stack = newsp,
2681 .tls = tls,
2682 };
2683
2684 return kernel_clone(&args);
2685 }
2686 #endif
2687
2688 #ifdef __ARCH_WANT_SYS_CLONE3
2689
copy_clone_args_from_user(struct kernel_clone_args * kargs,struct clone_args __user * uargs,size_t usize)2690 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2691 struct clone_args __user *uargs,
2692 size_t usize)
2693 {
2694 int err;
2695 struct clone_args args;
2696 pid_t *kset_tid = kargs->set_tid;
2697
2698 BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2699 CLONE_ARGS_SIZE_VER0);
2700 BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2701 CLONE_ARGS_SIZE_VER1);
2702 BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2703 CLONE_ARGS_SIZE_VER2);
2704 BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2705
2706 if (unlikely(usize > PAGE_SIZE))
2707 return -E2BIG;
2708 if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
2709 return -EINVAL;
2710
2711 err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2712 if (err)
2713 return err;
2714
2715 if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
2716 return -EINVAL;
2717
2718 if (unlikely(!args.set_tid && args.set_tid_size > 0))
2719 return -EINVAL;
2720
2721 if (unlikely(args.set_tid && args.set_tid_size == 0))
2722 return -EINVAL;
2723
2724 /*
2725 * Verify that higher 32bits of exit_signal are unset and that
2726 * it is a valid signal
2727 */
2728 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2729 !valid_signal(args.exit_signal)))
2730 return -EINVAL;
2731
2732 if ((args.flags & CLONE_INTO_CGROUP) &&
2733 (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2734 return -EINVAL;
2735
2736 *kargs = (struct kernel_clone_args){
2737 .flags = args.flags,
2738 .pidfd = u64_to_user_ptr(args.pidfd),
2739 .child_tid = u64_to_user_ptr(args.child_tid),
2740 .parent_tid = u64_to_user_ptr(args.parent_tid),
2741 .exit_signal = args.exit_signal,
2742 .stack = args.stack,
2743 .stack_size = args.stack_size,
2744 .tls = args.tls,
2745 .set_tid_size = args.set_tid_size,
2746 .cgroup = args.cgroup,
2747 };
2748
2749 if (args.set_tid &&
2750 copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
2751 (kargs->set_tid_size * sizeof(pid_t))))
2752 return -EFAULT;
2753
2754 kargs->set_tid = kset_tid;
2755
2756 return 0;
2757 }
2758
2759 /**
2760 * clone3_stack_valid - check and prepare stack
2761 * @kargs: kernel clone args
2762 *
2763 * Verify that the stack arguments userspace gave us are sane.
2764 * In addition, set the stack direction for userspace since it's easy for us to
2765 * determine.
2766 */
clone3_stack_valid(struct kernel_clone_args * kargs)2767 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2768 {
2769 if (kargs->stack == 0) {
2770 if (kargs->stack_size > 0)
2771 return false;
2772 } else {
2773 if (kargs->stack_size == 0)
2774 return false;
2775
2776 if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2777 return false;
2778
2779 #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2780 kargs->stack += kargs->stack_size;
2781 #endif
2782 }
2783
2784 return true;
2785 }
2786
clone3_args_valid(struct kernel_clone_args * kargs)2787 static bool clone3_args_valid(struct kernel_clone_args *kargs)
2788 {
2789 /* Verify that no unknown flags are passed along. */
2790 if (kargs->flags &
2791 ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
2792 return false;
2793
2794 /*
2795 * - make the CLONE_DETACHED bit reuseable for clone3
2796 * - make the CSIGNAL bits reuseable for clone3
2797 */
2798 if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
2799 return false;
2800
2801 if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2802 (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2803 return false;
2804
2805 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
2806 kargs->exit_signal)
2807 return false;
2808
2809 if (!clone3_stack_valid(kargs))
2810 return false;
2811
2812 return true;
2813 }
2814
2815 /**
2816 * clone3 - create a new process with specific properties
2817 * @uargs: argument structure
2818 * @size: size of @uargs
2819 *
2820 * clone3() is the extensible successor to clone()/clone2().
2821 * It takes a struct as argument that is versioned by its size.
2822 *
2823 * Return: On success, a positive PID for the child process.
2824 * On error, a negative errno number.
2825 */
SYSCALL_DEFINE2(clone3,struct clone_args __user *,uargs,size_t,size)2826 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
2827 {
2828 int err;
2829
2830 struct kernel_clone_args kargs;
2831 pid_t set_tid[MAX_PID_NS_LEVEL];
2832
2833 kargs.set_tid = set_tid;
2834
2835 err = copy_clone_args_from_user(&kargs, uargs, size);
2836 if (err)
2837 return err;
2838
2839 if (!clone3_args_valid(&kargs))
2840 return -EINVAL;
2841
2842 return kernel_clone(&kargs);
2843 }
2844 #endif
2845
walk_process_tree(struct task_struct * top,proc_visitor visitor,void * data)2846 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2847 {
2848 struct task_struct *leader, *parent, *child;
2849 int res;
2850
2851 read_lock(&tasklist_lock);
2852 leader = top = top->group_leader;
2853 down:
2854 for_each_thread(leader, parent) {
2855 list_for_each_entry(child, &parent->children, sibling) {
2856 res = visitor(child, data);
2857 if (res) {
2858 if (res < 0)
2859 goto out;
2860 leader = child;
2861 goto down;
2862 }
2863 up:
2864 ;
2865 }
2866 }
2867
2868 if (leader != top) {
2869 child = leader;
2870 parent = child->real_parent;
2871 leader = parent->group_leader;
2872 goto up;
2873 }
2874 out:
2875 read_unlock(&tasklist_lock);
2876 }
2877
2878 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2879 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2880 #endif
2881
sighand_ctor(void * data)2882 static void sighand_ctor(void *data)
2883 {
2884 struct sighand_struct *sighand = data;
2885
2886 spin_lock_init(&sighand->siglock);
2887 init_waitqueue_head(&sighand->signalfd_wqh);
2888 }
2889
mm_cache_init(void)2890 void __init mm_cache_init(void)
2891 {
2892 unsigned int mm_size;
2893
2894 /*
2895 * The mm_cpumask is located at the end of mm_struct, and is
2896 * dynamically sized based on the maximum CPU number this system
2897 * can have, taking hotplug into account (nr_cpu_ids).
2898 */
2899 mm_size = sizeof(struct mm_struct) + cpumask_size();
2900
2901 mm_cachep = kmem_cache_create_usercopy("mm_struct",
2902 mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
2903 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2904 offsetof(struct mm_struct, saved_auxv),
2905 sizeof_field(struct mm_struct, saved_auxv),
2906 NULL);
2907 }
2908
proc_caches_init(void)2909 void __init proc_caches_init(void)
2910 {
2911 sighand_cachep = kmem_cache_create("sighand_cache",
2912 sizeof(struct sighand_struct), 0,
2913 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2914 SLAB_ACCOUNT, sighand_ctor);
2915 signal_cachep = kmem_cache_create("signal_cache",
2916 sizeof(struct signal_struct), 0,
2917 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2918 NULL);
2919 files_cachep = kmem_cache_create("files_cache",
2920 sizeof(struct files_struct), 0,
2921 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2922 NULL);
2923 fs_cachep = kmem_cache_create("fs_cache",
2924 sizeof(struct fs_struct), 0,
2925 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2926 NULL);
2927
2928 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2929 mmap_init();
2930 nsproxy_cache_init();
2931 }
2932
2933 /*
2934 * Check constraints on flags passed to the unshare system call.
2935 */
check_unshare_flags(unsigned long unshare_flags)2936 static int check_unshare_flags(unsigned long unshare_flags)
2937 {
2938 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2939 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2940 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2941 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
2942 CLONE_NEWTIME))
2943 return -EINVAL;
2944 /*
2945 * Not implemented, but pretend it works if there is nothing
2946 * to unshare. Note that unsharing the address space or the
2947 * signal handlers also need to unshare the signal queues (aka
2948 * CLONE_THREAD).
2949 */
2950 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2951 if (!thread_group_empty(current))
2952 return -EINVAL;
2953 }
2954 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2955 if (refcount_read(¤t->sighand->count) > 1)
2956 return -EINVAL;
2957 }
2958 if (unshare_flags & CLONE_VM) {
2959 if (!current_is_single_threaded())
2960 return -EINVAL;
2961 }
2962
2963 return 0;
2964 }
2965
2966 /*
2967 * Unshare the filesystem structure if it is being shared
2968 */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)2969 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2970 {
2971 struct fs_struct *fs = current->fs;
2972
2973 if (!(unshare_flags & CLONE_FS) || !fs)
2974 return 0;
2975
2976 /* don't need lock here; in the worst case we'll do useless copy */
2977 if (fs->users == 1)
2978 return 0;
2979
2980 *new_fsp = copy_fs_struct(fs);
2981 if (!*new_fsp)
2982 return -ENOMEM;
2983
2984 return 0;
2985 }
2986
2987 /*
2988 * Unshare file descriptor table if it is being shared
2989 */
unshare_fd(unsigned long unshare_flags,unsigned int max_fds,struct files_struct ** new_fdp)2990 int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
2991 struct files_struct **new_fdp)
2992 {
2993 struct files_struct *fd = current->files;
2994 int error = 0;
2995
2996 if ((unshare_flags & CLONE_FILES) &&
2997 (fd && atomic_read(&fd->count) > 1)) {
2998 *new_fdp = dup_fd(fd, max_fds, &error);
2999 if (!*new_fdp)
3000 return error;
3001 }
3002
3003 return 0;
3004 }
3005
3006 /*
3007 * unshare allows a process to 'unshare' part of the process
3008 * context which was originally shared using clone. copy_*
3009 * functions used by kernel_clone() cannot be used here directly
3010 * because they modify an inactive task_struct that is being
3011 * constructed. Here we are modifying the current, active,
3012 * task_struct.
3013 */
ksys_unshare(unsigned long unshare_flags)3014 int ksys_unshare(unsigned long unshare_flags)
3015 {
3016 struct fs_struct *fs, *new_fs = NULL;
3017 struct files_struct *fd, *new_fd = NULL;
3018 struct cred *new_cred = NULL;
3019 struct nsproxy *new_nsproxy = NULL;
3020 int do_sysvsem = 0;
3021 int err;
3022
3023 /*
3024 * If unsharing a user namespace must also unshare the thread group
3025 * and unshare the filesystem root and working directories.
3026 */
3027 if (unshare_flags & CLONE_NEWUSER)
3028 unshare_flags |= CLONE_THREAD | CLONE_FS;
3029 /*
3030 * If unsharing vm, must also unshare signal handlers.
3031 */
3032 if (unshare_flags & CLONE_VM)
3033 unshare_flags |= CLONE_SIGHAND;
3034 /*
3035 * If unsharing a signal handlers, must also unshare the signal queues.
3036 */
3037 if (unshare_flags & CLONE_SIGHAND)
3038 unshare_flags |= CLONE_THREAD;
3039 /*
3040 * If unsharing namespace, must also unshare filesystem information.
3041 */
3042 if (unshare_flags & CLONE_NEWNS)
3043 unshare_flags |= CLONE_FS;
3044
3045 err = check_unshare_flags(unshare_flags);
3046 if (err)
3047 goto bad_unshare_out;
3048 /*
3049 * CLONE_NEWIPC must also detach from the undolist: after switching
3050 * to a new ipc namespace, the semaphore arrays from the old
3051 * namespace are unreachable.
3052 */
3053 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
3054 do_sysvsem = 1;
3055 err = unshare_fs(unshare_flags, &new_fs);
3056 if (err)
3057 goto bad_unshare_out;
3058 err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3059 if (err)
3060 goto bad_unshare_cleanup_fs;
3061 err = unshare_userns(unshare_flags, &new_cred);
3062 if (err)
3063 goto bad_unshare_cleanup_fd;
3064 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3065 new_cred, new_fs);
3066 if (err)
3067 goto bad_unshare_cleanup_cred;
3068
3069 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
3070 if (do_sysvsem) {
3071 /*
3072 * CLONE_SYSVSEM is equivalent to sys_exit().
3073 */
3074 exit_sem(current);
3075 }
3076 if (unshare_flags & CLONE_NEWIPC) {
3077 /* Orphan segments in old ns (see sem above). */
3078 exit_shm(current);
3079 shm_init_task(current);
3080 }
3081
3082 if (new_nsproxy)
3083 switch_task_namespaces(current, new_nsproxy);
3084
3085 task_lock(current);
3086
3087 if (new_fs) {
3088 fs = current->fs;
3089 spin_lock(&fs->lock);
3090 current->fs = new_fs;
3091 if (--fs->users)
3092 new_fs = NULL;
3093 else
3094 new_fs = fs;
3095 spin_unlock(&fs->lock);
3096 }
3097
3098 if (new_fd) {
3099 fd = current->files;
3100 current->files = new_fd;
3101 new_fd = fd;
3102 }
3103
3104 task_unlock(current);
3105
3106 if (new_cred) {
3107 /* Install the new user namespace */
3108 commit_creds(new_cred);
3109 new_cred = NULL;
3110 }
3111 }
3112
3113 perf_event_namespaces(current);
3114
3115 bad_unshare_cleanup_cred:
3116 if (new_cred)
3117 put_cred(new_cred);
3118 bad_unshare_cleanup_fd:
3119 if (new_fd)
3120 put_files_struct(new_fd);
3121
3122 bad_unshare_cleanup_fs:
3123 if (new_fs)
3124 free_fs_struct(new_fs);
3125
3126 bad_unshare_out:
3127 return err;
3128 }
3129
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)3130 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3131 {
3132 return ksys_unshare(unshare_flags);
3133 }
3134
3135 /*
3136 * Helper to unshare the files of the current task.
3137 * We don't want to expose copy_files internals to
3138 * the exec layer of the kernel.
3139 */
3140
unshare_files(struct files_struct ** displaced)3141 int unshare_files(struct files_struct **displaced)
3142 {
3143 struct task_struct *task = current;
3144 struct files_struct *copy = NULL;
3145 int error;
3146
3147 error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, ©);
3148 if (error || !copy) {
3149 *displaced = NULL;
3150 return error;
3151 }
3152 *displaced = task->files;
3153 task_lock(task);
3154 task->files = copy;
3155 task_unlock(task);
3156 return 0;
3157 }
3158
sysctl_max_threads(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3159 int sysctl_max_threads(struct ctl_table *table, int write,
3160 void *buffer, size_t *lenp, loff_t *ppos)
3161 {
3162 struct ctl_table t;
3163 int ret;
3164 int threads = max_threads;
3165 int min = 1;
3166 int max = MAX_THREADS;
3167
3168 t = *table;
3169 t.data = &threads;
3170 t.extra1 = &min;
3171 t.extra2 = &max;
3172
3173 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3174 if (ret || !write)
3175 return ret;
3176
3177 max_threads = threads;
3178
3179 return 0;
3180 }
3181