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