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