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_page_state(first_page, 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
arch_task_cache_init(void)757 void __init __weak arch_task_cache_init(void) { }
758
759 /*
760 * set_max_threads
761 */
set_max_threads(unsigned int max_threads_suggested)762 static void set_max_threads(unsigned int max_threads_suggested)
763 {
764 u64 threads;
765 unsigned long nr_pages = totalram_pages();
766
767 /*
768 * The number of threads shall be limited such that the thread
769 * structures may only consume a small part of the available memory.
770 */
771 if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
772 threads = MAX_THREADS;
773 else
774 threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
775 (u64) THREAD_SIZE * 8UL);
776
777 if (threads > max_threads_suggested)
778 threads = max_threads_suggested;
779
780 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
781 }
782
783 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
784 /* Initialized by the architecture: */
785 int arch_task_struct_size __read_mostly;
786 #endif
787
788 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
task_struct_whitelist(unsigned long * offset,unsigned long * size)789 static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
790 {
791 /* Fetch thread_struct whitelist for the architecture. */
792 arch_thread_struct_whitelist(offset, size);
793
794 /*
795 * Handle zero-sized whitelist or empty thread_struct, otherwise
796 * adjust offset to position of thread_struct in task_struct.
797 */
798 if (unlikely(*size == 0))
799 *offset = 0;
800 else
801 *offset += offsetof(struct task_struct, thread);
802 }
803 #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
804
fork_init(void)805 void __init fork_init(void)
806 {
807 int i;
808 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
809 #ifndef ARCH_MIN_TASKALIGN
810 #define ARCH_MIN_TASKALIGN 0
811 #endif
812 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
813 unsigned long useroffset, usersize;
814
815 /* create a slab on which task_structs can be allocated */
816 task_struct_whitelist(&useroffset, &usersize);
817 task_struct_cachep = kmem_cache_create_usercopy("task_struct",
818 arch_task_struct_size, align,
819 SLAB_PANIC|SLAB_ACCOUNT,
820 useroffset, usersize, NULL);
821 #endif
822
823 /* do the arch specific task caches init */
824 arch_task_cache_init();
825
826 set_max_threads(MAX_THREADS);
827
828 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
829 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
830 init_task.signal->rlim[RLIMIT_SIGPENDING] =
831 init_task.signal->rlim[RLIMIT_NPROC];
832
833 for (i = 0; i < UCOUNT_COUNTS; i++) {
834 init_user_ns.ucount_max[i] = max_threads/2;
835 }
836
837 #ifdef CONFIG_VMAP_STACK
838 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
839 NULL, free_vm_stack_cache);
840 #endif
841
842 scs_init();
843
844 lockdep_init_task(&init_task);
845 uprobes_init();
846 }
847
arch_dup_task_struct(struct task_struct * dst,struct task_struct * src)848 int __weak arch_dup_task_struct(struct task_struct *dst,
849 struct task_struct *src)
850 {
851 *dst = *src;
852 return 0;
853 }
854
set_task_stack_end_magic(struct task_struct * tsk)855 void set_task_stack_end_magic(struct task_struct *tsk)
856 {
857 unsigned long *stackend;
858
859 stackend = end_of_stack(tsk);
860 *stackend = STACK_END_MAGIC; /* for overflow detection */
861 }
862
dup_task_struct(struct task_struct * orig,int node)863 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
864 {
865 struct task_struct *tsk;
866 unsigned long *stack;
867 struct vm_struct *stack_vm_area __maybe_unused;
868 int err;
869
870 if (node == NUMA_NO_NODE)
871 node = tsk_fork_get_node(orig);
872 tsk = alloc_task_struct_node(node);
873 if (!tsk)
874 return NULL;
875
876 stack = alloc_thread_stack_node(tsk, node);
877 if (!stack)
878 goto free_tsk;
879
880 if (memcg_charge_kernel_stack(tsk))
881 goto free_stack;
882
883 stack_vm_area = task_stack_vm_area(tsk);
884
885 err = arch_dup_task_struct(tsk, orig);
886
887 /*
888 * arch_dup_task_struct() clobbers the stack-related fields. Make
889 * sure they're properly initialized before using any stack-related
890 * functions again.
891 */
892 tsk->stack = stack;
893 #ifdef CONFIG_VMAP_STACK
894 tsk->stack_vm_area = stack_vm_area;
895 #endif
896 #ifdef CONFIG_THREAD_INFO_IN_TASK
897 refcount_set(&tsk->stack_refcount, 1);
898 #endif
899
900 if (err)
901 goto free_stack;
902
903 err = scs_prepare(tsk, node);
904 if (err)
905 goto free_stack;
906
907 #ifdef CONFIG_SECCOMP
908 /*
909 * We must handle setting up seccomp filters once we're under
910 * the sighand lock in case orig has changed between now and
911 * then. Until then, filter must be NULL to avoid messing up
912 * the usage counts on the error path calling free_task.
913 */
914 tsk->seccomp.filter = NULL;
915 #endif
916
917 setup_thread_stack(tsk, orig);
918 clear_user_return_notifier(tsk);
919 clear_tsk_need_resched(tsk);
920 set_task_stack_end_magic(tsk);
921
922 #ifdef CONFIG_STACKPROTECTOR
923 tsk->stack_canary = get_random_canary();
924 #endif
925 if (orig->cpus_ptr == &orig->cpus_mask)
926 tsk->cpus_ptr = &tsk->cpus_mask;
927
928 /*
929 * One for the user space visible state that goes away when reaped.
930 * One for the scheduler.
931 */
932 refcount_set(&tsk->rcu_users, 2);
933 /* One for the rcu users */
934 refcount_set(&tsk->usage, 1);
935 #ifdef CONFIG_BLK_DEV_IO_TRACE
936 tsk->btrace_seq = 0;
937 #endif
938 tsk->splice_pipe = NULL;
939 tsk->task_frag.page = NULL;
940 tsk->wake_q.next = NULL;
941
942 account_kernel_stack(tsk, 1);
943
944 kcov_task_init(tsk);
945
946 #ifdef CONFIG_FAULT_INJECTION
947 tsk->fail_nth = 0;
948 #endif
949
950 #ifdef CONFIG_BLK_CGROUP
951 tsk->throttle_queue = NULL;
952 tsk->use_memdelay = 0;
953 #endif
954
955 #ifdef CONFIG_MEMCG
956 tsk->active_memcg = NULL;
957 #endif
958 return tsk;
959
960 free_stack:
961 free_thread_stack(tsk);
962 free_tsk:
963 free_task_struct(tsk);
964 return NULL;
965 }
966
967 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
968
969 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
970
coredump_filter_setup(char * s)971 static int __init coredump_filter_setup(char *s)
972 {
973 default_dump_filter =
974 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
975 MMF_DUMP_FILTER_MASK;
976 return 1;
977 }
978
979 __setup("coredump_filter=", coredump_filter_setup);
980
981 #include <linux/init_task.h>
982
mm_init_aio(struct mm_struct * mm)983 static void mm_init_aio(struct mm_struct *mm)
984 {
985 #ifdef CONFIG_AIO
986 spin_lock_init(&mm->ioctx_lock);
987 mm->ioctx_table = NULL;
988 #endif
989 }
990
mm_clear_owner(struct mm_struct * mm,struct task_struct * p)991 static __always_inline void mm_clear_owner(struct mm_struct *mm,
992 struct task_struct *p)
993 {
994 #ifdef CONFIG_MEMCG
995 if (mm->owner == p)
996 WRITE_ONCE(mm->owner, NULL);
997 #endif
998 }
999
mm_init_owner(struct mm_struct * mm,struct task_struct * p)1000 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1001 {
1002 #ifdef CONFIG_MEMCG
1003 mm->owner = p;
1004 #endif
1005 }
1006
mm_init_uprobes_state(struct mm_struct * mm)1007 static void mm_init_uprobes_state(struct mm_struct *mm)
1008 {
1009 #ifdef CONFIG_UPROBES
1010 mm->uprobes_state.xol_area = NULL;
1011 #endif
1012 }
1013
mm_init(struct mm_struct * mm,struct task_struct * p,struct user_namespace * user_ns)1014 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1015 struct user_namespace *user_ns)
1016 {
1017 mm->mmap = NULL;
1018 mm->mm_rb = RB_ROOT;
1019 mm->vmacache_seqnum = 0;
1020 atomic_set(&mm->mm_users, 1);
1021 atomic_set(&mm->mm_count, 1);
1022 init_rwsem(&mm->mmap_sem);
1023 INIT_LIST_HEAD(&mm->mmlist);
1024 mm->core_state = NULL;
1025 mm_pgtables_bytes_init(mm);
1026 mm->map_count = 0;
1027 mm->locked_vm = 0;
1028 atomic64_set(&mm->pinned_vm, 0);
1029 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1030 spin_lock_init(&mm->page_table_lock);
1031 spin_lock_init(&mm->arg_lock);
1032 mm_init_cpumask(mm);
1033 mm_init_aio(mm);
1034 mm_init_owner(mm, p);
1035 RCU_INIT_POINTER(mm->exe_file, NULL);
1036 mmu_notifier_mm_init(mm);
1037 init_tlb_flush_pending(mm);
1038 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
1039 mm->pmd_huge_pte = NULL;
1040 #endif
1041 mm_init_uprobes_state(mm);
1042
1043 if (current->mm) {
1044 mm->flags = current->mm->flags & MMF_INIT_MASK;
1045 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1046 } else {
1047 mm->flags = default_dump_filter;
1048 mm->def_flags = 0;
1049 }
1050
1051 if (mm_alloc_pgd(mm))
1052 goto fail_nopgd;
1053
1054 if (init_new_context(p, mm))
1055 goto fail_nocontext;
1056
1057 mm->user_ns = get_user_ns(user_ns);
1058 return mm;
1059
1060 fail_nocontext:
1061 mm_free_pgd(mm);
1062 fail_nopgd:
1063 free_mm(mm);
1064 return NULL;
1065 }
1066
1067 /*
1068 * Allocate and initialize an mm_struct.
1069 */
mm_alloc(void)1070 struct mm_struct *mm_alloc(void)
1071 {
1072 struct mm_struct *mm;
1073
1074 mm = allocate_mm();
1075 if (!mm)
1076 return NULL;
1077
1078 memset(mm, 0, sizeof(*mm));
1079 return mm_init(mm, current, current_user_ns());
1080 }
1081
__mmput(struct mm_struct * mm)1082 static inline void __mmput(struct mm_struct *mm)
1083 {
1084 VM_BUG_ON(atomic_read(&mm->mm_users));
1085
1086 uprobe_clear_state(mm);
1087 exit_aio(mm);
1088 ksm_exit(mm);
1089 khugepaged_exit(mm); /* must run before exit_mmap */
1090 exit_mmap(mm);
1091 mm_put_huge_zero_page(mm);
1092 set_mm_exe_file(mm, NULL);
1093 if (!list_empty(&mm->mmlist)) {
1094 spin_lock(&mmlist_lock);
1095 list_del(&mm->mmlist);
1096 spin_unlock(&mmlist_lock);
1097 }
1098 if (mm->binfmt)
1099 module_put(mm->binfmt->module);
1100 mmdrop(mm);
1101 }
1102
1103 /*
1104 * Decrement the use count and release all resources for an mm.
1105 */
mmput(struct mm_struct * mm)1106 void mmput(struct mm_struct *mm)
1107 {
1108 might_sleep();
1109
1110 if (atomic_dec_and_test(&mm->mm_users))
1111 __mmput(mm);
1112 }
1113 EXPORT_SYMBOL_GPL(mmput);
1114
1115 #ifdef CONFIG_MMU
mmput_async_fn(struct work_struct * work)1116 static void mmput_async_fn(struct work_struct *work)
1117 {
1118 struct mm_struct *mm = container_of(work, struct mm_struct,
1119 async_put_work);
1120
1121 __mmput(mm);
1122 }
1123
mmput_async(struct mm_struct * mm)1124 void mmput_async(struct mm_struct *mm)
1125 {
1126 if (atomic_dec_and_test(&mm->mm_users)) {
1127 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1128 schedule_work(&mm->async_put_work);
1129 }
1130 }
1131 #endif
1132
1133 /**
1134 * set_mm_exe_file - change a reference to the mm's executable file
1135 *
1136 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1137 *
1138 * Main users are mmput() and sys_execve(). Callers prevent concurrent
1139 * invocations: in mmput() nobody alive left, in execve task is single
1140 * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
1141 * mm->exe_file, but does so without using set_mm_exe_file() in order
1142 * to do avoid the need for any locks.
1143 */
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1144 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1145 {
1146 struct file *old_exe_file;
1147
1148 /*
1149 * It is safe to dereference the exe_file without RCU as
1150 * this function is only called if nobody else can access
1151 * this mm -- see comment above for justification.
1152 */
1153 old_exe_file = rcu_dereference_raw(mm->exe_file);
1154
1155 if (new_exe_file)
1156 get_file(new_exe_file);
1157 rcu_assign_pointer(mm->exe_file, new_exe_file);
1158 if (old_exe_file)
1159 fput(old_exe_file);
1160 }
1161
1162 /**
1163 * get_mm_exe_file - acquire a reference to the mm's executable file
1164 *
1165 * Returns %NULL if mm has no associated executable file.
1166 * User must release file via fput().
1167 */
get_mm_exe_file(struct mm_struct * mm)1168 struct file *get_mm_exe_file(struct mm_struct *mm)
1169 {
1170 struct file *exe_file;
1171
1172 rcu_read_lock();
1173 exe_file = rcu_dereference(mm->exe_file);
1174 if (exe_file && !get_file_rcu(exe_file))
1175 exe_file = NULL;
1176 rcu_read_unlock();
1177 return exe_file;
1178 }
1179 EXPORT_SYMBOL(get_mm_exe_file);
1180
1181 /**
1182 * get_task_exe_file - acquire a reference to the task's executable file
1183 *
1184 * Returns %NULL if task's mm (if any) has no associated executable file or
1185 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1186 * User must release file via fput().
1187 */
get_task_exe_file(struct task_struct * task)1188 struct file *get_task_exe_file(struct task_struct *task)
1189 {
1190 struct file *exe_file = NULL;
1191 struct mm_struct *mm;
1192
1193 task_lock(task);
1194 mm = task->mm;
1195 if (mm) {
1196 if (!(task->flags & PF_KTHREAD))
1197 exe_file = get_mm_exe_file(mm);
1198 }
1199 task_unlock(task);
1200 return exe_file;
1201 }
1202 EXPORT_SYMBOL(get_task_exe_file);
1203
1204 /**
1205 * get_task_mm - acquire a reference to the task's mm
1206 *
1207 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1208 * this kernel workthread has transiently adopted a user mm with use_mm,
1209 * to do its AIO) is not set and if so returns a reference to it, after
1210 * bumping up the use count. User must release the mm via mmput()
1211 * after use. Typically used by /proc and ptrace.
1212 */
get_task_mm(struct task_struct * task)1213 struct mm_struct *get_task_mm(struct task_struct *task)
1214 {
1215 struct mm_struct *mm;
1216
1217 task_lock(task);
1218 mm = task->mm;
1219 if (mm) {
1220 if (task->flags & PF_KTHREAD)
1221 mm = NULL;
1222 else
1223 mmget(mm);
1224 }
1225 task_unlock(task);
1226 return mm;
1227 }
1228 EXPORT_SYMBOL_GPL(get_task_mm);
1229
mm_access(struct task_struct * task,unsigned int mode)1230 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1231 {
1232 struct mm_struct *mm;
1233 int err;
1234
1235 err = mutex_lock_killable(&task->signal->cred_guard_mutex);
1236 if (err)
1237 return ERR_PTR(err);
1238
1239 mm = get_task_mm(task);
1240 if (mm && mm != current->mm &&
1241 !ptrace_may_access(task, mode)) {
1242 mmput(mm);
1243 mm = ERR_PTR(-EACCES);
1244 }
1245 mutex_unlock(&task->signal->cred_guard_mutex);
1246
1247 return mm;
1248 }
1249
complete_vfork_done(struct task_struct * tsk)1250 static void complete_vfork_done(struct task_struct *tsk)
1251 {
1252 struct completion *vfork;
1253
1254 task_lock(tsk);
1255 vfork = tsk->vfork_done;
1256 if (likely(vfork)) {
1257 tsk->vfork_done = NULL;
1258 complete(vfork);
1259 }
1260 task_unlock(tsk);
1261 }
1262
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)1263 static int wait_for_vfork_done(struct task_struct *child,
1264 struct completion *vfork)
1265 {
1266 int killed;
1267
1268 freezer_do_not_count();
1269 cgroup_enter_frozen();
1270 killed = wait_for_completion_killable(vfork);
1271 cgroup_leave_frozen(false);
1272 freezer_count();
1273
1274 if (killed) {
1275 task_lock(child);
1276 child->vfork_done = NULL;
1277 task_unlock(child);
1278 }
1279
1280 put_task_struct(child);
1281 return killed;
1282 }
1283
1284 /* Please note the differences between mmput and mm_release.
1285 * mmput is called whenever we stop holding onto a mm_struct,
1286 * error success whatever.
1287 *
1288 * mm_release is called after a mm_struct has been removed
1289 * from the current process.
1290 *
1291 * This difference is important for error handling, when we
1292 * only half set up a mm_struct for a new process and need to restore
1293 * the old one. Because we mmput the new mm_struct before
1294 * restoring the old one. . .
1295 * Eric Biederman 10 January 1998
1296 */
mm_release(struct task_struct * tsk,struct mm_struct * mm)1297 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1298 {
1299 uprobe_free_utask(tsk);
1300
1301 /* Get rid of any cached register state */
1302 deactivate_mm(tsk, mm);
1303
1304 /*
1305 * Signal userspace if we're not exiting with a core dump
1306 * because we want to leave the value intact for debugging
1307 * purposes.
1308 */
1309 if (tsk->clear_child_tid) {
1310 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1311 atomic_read(&mm->mm_users) > 1) {
1312 /*
1313 * We don't check the error code - if userspace has
1314 * not set up a proper pointer then tough luck.
1315 */
1316 put_user(0, tsk->clear_child_tid);
1317 do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1318 1, NULL, NULL, 0, 0);
1319 }
1320 tsk->clear_child_tid = NULL;
1321 }
1322
1323 /*
1324 * All done, finally we can wake up parent and return this mm to him.
1325 * Also kthread_stop() uses this completion for synchronization.
1326 */
1327 if (tsk->vfork_done)
1328 complete_vfork_done(tsk);
1329 }
1330
exit_mm_release(struct task_struct * tsk,struct mm_struct * mm)1331 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1332 {
1333 futex_exit_release(tsk);
1334 mm_release(tsk, mm);
1335 }
1336
exec_mm_release(struct task_struct * tsk,struct mm_struct * mm)1337 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1338 {
1339 futex_exec_release(tsk);
1340 mm_release(tsk, mm);
1341 }
1342
1343 /**
1344 * dup_mm() - duplicates an existing mm structure
1345 * @tsk: the task_struct with which the new mm will be associated.
1346 * @oldmm: the mm to duplicate.
1347 *
1348 * Allocates a new mm structure and duplicates the provided @oldmm structure
1349 * content into it.
1350 *
1351 * Return: the duplicated mm or NULL on failure.
1352 */
dup_mm(struct task_struct * tsk,struct mm_struct * oldmm)1353 static struct mm_struct *dup_mm(struct task_struct *tsk,
1354 struct mm_struct *oldmm)
1355 {
1356 struct mm_struct *mm;
1357 int err;
1358
1359 mm = allocate_mm();
1360 if (!mm)
1361 goto fail_nomem;
1362
1363 memcpy(mm, oldmm, sizeof(*mm));
1364
1365 if (!mm_init(mm, tsk, mm->user_ns))
1366 goto fail_nomem;
1367
1368 err = dup_mmap(mm, oldmm);
1369 if (err)
1370 goto free_pt;
1371
1372 mm->hiwater_rss = get_mm_rss(mm);
1373 mm->hiwater_vm = mm->total_vm;
1374
1375 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1376 goto free_pt;
1377
1378 return mm;
1379
1380 free_pt:
1381 /* don't put binfmt in mmput, we haven't got module yet */
1382 mm->binfmt = NULL;
1383 mm_init_owner(mm, NULL);
1384 mmput(mm);
1385
1386 fail_nomem:
1387 return NULL;
1388 }
1389
copy_mm(unsigned long clone_flags,struct task_struct * tsk)1390 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1391 {
1392 struct mm_struct *mm, *oldmm;
1393 int retval;
1394
1395 tsk->min_flt = tsk->maj_flt = 0;
1396 tsk->nvcsw = tsk->nivcsw = 0;
1397 #ifdef CONFIG_DETECT_HUNG_TASK
1398 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1399 tsk->last_switch_time = 0;
1400 #endif
1401
1402 tsk->mm = NULL;
1403 tsk->active_mm = NULL;
1404
1405 /*
1406 * Are we cloning a kernel thread?
1407 *
1408 * We need to steal a active VM for that..
1409 */
1410 oldmm = current->mm;
1411 if (!oldmm)
1412 return 0;
1413
1414 /* initialize the new vmacache entries */
1415 vmacache_flush(tsk);
1416
1417 if (clone_flags & CLONE_VM) {
1418 mmget(oldmm);
1419 mm = oldmm;
1420 goto good_mm;
1421 }
1422
1423 retval = -ENOMEM;
1424 mm = dup_mm(tsk, current->mm);
1425 if (!mm)
1426 goto fail_nomem;
1427
1428 good_mm:
1429 tsk->mm = mm;
1430 tsk->active_mm = mm;
1431 return 0;
1432
1433 fail_nomem:
1434 return retval;
1435 }
1436
copy_fs(unsigned long clone_flags,struct task_struct * tsk)1437 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1438 {
1439 struct fs_struct *fs = current->fs;
1440 if (clone_flags & CLONE_FS) {
1441 /* tsk->fs is already what we want */
1442 spin_lock(&fs->lock);
1443 if (fs->in_exec) {
1444 spin_unlock(&fs->lock);
1445 return -EAGAIN;
1446 }
1447 fs->users++;
1448 spin_unlock(&fs->lock);
1449 return 0;
1450 }
1451 tsk->fs = copy_fs_struct(fs);
1452 if (!tsk->fs)
1453 return -ENOMEM;
1454 return 0;
1455 }
1456
copy_files(unsigned long clone_flags,struct task_struct * tsk)1457 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1458 {
1459 struct files_struct *oldf, *newf;
1460 int error = 0;
1461
1462 /*
1463 * A background process may not have any files ...
1464 */
1465 oldf = current->files;
1466 if (!oldf)
1467 goto out;
1468
1469 if (clone_flags & CLONE_FILES) {
1470 atomic_inc(&oldf->count);
1471 goto out;
1472 }
1473
1474 newf = dup_fd(oldf, &error);
1475 if (!newf)
1476 goto out;
1477
1478 tsk->files = newf;
1479 error = 0;
1480 out:
1481 return error;
1482 }
1483
copy_io(unsigned long clone_flags,struct task_struct * tsk)1484 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1485 {
1486 #ifdef CONFIG_BLOCK
1487 struct io_context *ioc = current->io_context;
1488 struct io_context *new_ioc;
1489
1490 if (!ioc)
1491 return 0;
1492 /*
1493 * Share io context with parent, if CLONE_IO is set
1494 */
1495 if (clone_flags & CLONE_IO) {
1496 ioc_task_link(ioc);
1497 tsk->io_context = ioc;
1498 } else if (ioprio_valid(ioc->ioprio)) {
1499 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1500 if (unlikely(!new_ioc))
1501 return -ENOMEM;
1502
1503 new_ioc->ioprio = ioc->ioprio;
1504 put_io_context(new_ioc);
1505 }
1506 #endif
1507 return 0;
1508 }
1509
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1510 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1511 {
1512 struct sighand_struct *sig;
1513
1514 if (clone_flags & CLONE_SIGHAND) {
1515 refcount_inc(¤t->sighand->count);
1516 return 0;
1517 }
1518 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1519 rcu_assign_pointer(tsk->sighand, sig);
1520 if (!sig)
1521 return -ENOMEM;
1522
1523 refcount_set(&sig->count, 1);
1524 spin_lock_irq(¤t->sighand->siglock);
1525 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1526 spin_unlock_irq(¤t->sighand->siglock);
1527 return 0;
1528 }
1529
__cleanup_sighand(struct sighand_struct * sighand)1530 void __cleanup_sighand(struct sighand_struct *sighand)
1531 {
1532 if (refcount_dec_and_test(&sighand->count)) {
1533 signalfd_cleanup(sighand);
1534 /*
1535 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1536 * without an RCU grace period, see __lock_task_sighand().
1537 */
1538 kmem_cache_free(sighand_cachep, sighand);
1539 }
1540 }
1541
1542 /*
1543 * Initialize POSIX timer handling for a thread group.
1544 */
posix_cpu_timers_init_group(struct signal_struct * sig)1545 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1546 {
1547 struct posix_cputimers *pct = &sig->posix_cputimers;
1548 unsigned long cpu_limit;
1549
1550 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1551 posix_cputimers_group_init(pct, cpu_limit);
1552 }
1553
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1554 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1555 {
1556 struct signal_struct *sig;
1557
1558 if (clone_flags & CLONE_THREAD)
1559 return 0;
1560
1561 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1562 tsk->signal = sig;
1563 if (!sig)
1564 return -ENOMEM;
1565
1566 sig->nr_threads = 1;
1567 atomic_set(&sig->live, 1);
1568 refcount_set(&sig->sigcnt, 1);
1569
1570 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1571 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1572 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1573
1574 init_waitqueue_head(&sig->wait_chldexit);
1575 sig->curr_target = tsk;
1576 init_sigpending(&sig->shared_pending);
1577 INIT_HLIST_HEAD(&sig->multiprocess);
1578 seqlock_init(&sig->stats_lock);
1579 prev_cputime_init(&sig->prev_cputime);
1580
1581 #ifdef CONFIG_POSIX_TIMERS
1582 INIT_LIST_HEAD(&sig->posix_timers);
1583 hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1584 sig->real_timer.function = it_real_fn;
1585 #endif
1586
1587 task_lock(current->group_leader);
1588 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1589 task_unlock(current->group_leader);
1590
1591 posix_cpu_timers_init_group(sig);
1592
1593 tty_audit_fork(sig);
1594 sched_autogroup_fork(sig);
1595
1596 sig->oom_score_adj = current->signal->oom_score_adj;
1597 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1598
1599 mutex_init(&sig->cred_guard_mutex);
1600
1601 return 0;
1602 }
1603
copy_seccomp(struct task_struct * p)1604 static void copy_seccomp(struct task_struct *p)
1605 {
1606 #ifdef CONFIG_SECCOMP
1607 /*
1608 * Must be called with sighand->lock held, which is common to
1609 * all threads in the group. Holding cred_guard_mutex is not
1610 * needed because this new task is not yet running and cannot
1611 * be racing exec.
1612 */
1613 assert_spin_locked(¤t->sighand->siglock);
1614
1615 /* Ref-count the new filter user, and assign it. */
1616 get_seccomp_filter(current);
1617 p->seccomp = current->seccomp;
1618
1619 /*
1620 * Explicitly enable no_new_privs here in case it got set
1621 * between the task_struct being duplicated and holding the
1622 * sighand lock. The seccomp state and nnp must be in sync.
1623 */
1624 if (task_no_new_privs(current))
1625 task_set_no_new_privs(p);
1626
1627 /*
1628 * If the parent gained a seccomp mode after copying thread
1629 * flags and between before we held the sighand lock, we have
1630 * to manually enable the seccomp thread flag here.
1631 */
1632 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1633 set_tsk_thread_flag(p, TIF_SECCOMP);
1634 #endif
1635 }
1636
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1637 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1638 {
1639 current->clear_child_tid = tidptr;
1640
1641 return task_pid_vnr(current);
1642 }
1643
rt_mutex_init_task(struct task_struct * p)1644 static void rt_mutex_init_task(struct task_struct *p)
1645 {
1646 raw_spin_lock_init(&p->pi_lock);
1647 #ifdef CONFIG_RT_MUTEXES
1648 p->pi_waiters = RB_ROOT_CACHED;
1649 p->pi_top_task = NULL;
1650 p->pi_blocked_on = NULL;
1651 #endif
1652 }
1653
init_task_pid_links(struct task_struct * task)1654 static inline void init_task_pid_links(struct task_struct *task)
1655 {
1656 enum pid_type type;
1657
1658 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1659 INIT_HLIST_NODE(&task->pid_links[type]);
1660 }
1661 }
1662
1663 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1664 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1665 {
1666 if (type == PIDTYPE_PID)
1667 task->thread_pid = pid;
1668 else
1669 task->signal->pids[type] = pid;
1670 }
1671
rcu_copy_process(struct task_struct * p)1672 static inline void rcu_copy_process(struct task_struct *p)
1673 {
1674 #ifdef CONFIG_PREEMPT_RCU
1675 p->rcu_read_lock_nesting = 0;
1676 p->rcu_read_unlock_special.s = 0;
1677 p->rcu_blocked_node = NULL;
1678 INIT_LIST_HEAD(&p->rcu_node_entry);
1679 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1680 #ifdef CONFIG_TASKS_RCU
1681 p->rcu_tasks_holdout = false;
1682 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1683 p->rcu_tasks_idle_cpu = -1;
1684 #endif /* #ifdef CONFIG_TASKS_RCU */
1685 }
1686
pidfd_pid(const struct file * file)1687 struct pid *pidfd_pid(const struct file *file)
1688 {
1689 if (file->f_op == &pidfd_fops)
1690 return file->private_data;
1691
1692 return ERR_PTR(-EBADF);
1693 }
1694
pidfd_release(struct inode * inode,struct file * file)1695 static int pidfd_release(struct inode *inode, struct file *file)
1696 {
1697 struct pid *pid = file->private_data;
1698
1699 file->private_data = NULL;
1700 put_pid(pid);
1701 return 0;
1702 }
1703
1704 #ifdef CONFIG_PROC_FS
pidfd_show_fdinfo(struct seq_file * m,struct file * f)1705 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1706 {
1707 struct pid_namespace *ns = proc_pid_ns(file_inode(m->file));
1708 struct pid *pid = f->private_data;
1709
1710 seq_put_decimal_ull(m, "Pid:\t", pid_nr_ns(pid, ns));
1711 seq_putc(m, '\n');
1712 }
1713 #endif
1714
1715 /*
1716 * Poll support for process exit notification.
1717 */
pidfd_poll(struct file * file,struct poll_table_struct * pts)1718 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1719 {
1720 struct task_struct *task;
1721 struct pid *pid = file->private_data;
1722 __poll_t poll_flags = 0;
1723
1724 poll_wait(file, &pid->wait_pidfd, pts);
1725
1726 rcu_read_lock();
1727 task = pid_task(pid, PIDTYPE_PID);
1728 /*
1729 * Inform pollers only when the whole thread group exits.
1730 * If the thread group leader exits before all other threads in the
1731 * group, then poll(2) should block, similar to the wait(2) family.
1732 */
1733 if (!task || (task->exit_state && thread_group_empty(task)))
1734 poll_flags = EPOLLIN | EPOLLRDNORM;
1735 rcu_read_unlock();
1736
1737 return poll_flags;
1738 }
1739
1740 const struct file_operations pidfd_fops = {
1741 .release = pidfd_release,
1742 .poll = pidfd_poll,
1743 #ifdef CONFIG_PROC_FS
1744 .show_fdinfo = pidfd_show_fdinfo,
1745 #endif
1746 };
1747
__delayed_free_task(struct rcu_head * rhp)1748 static void __delayed_free_task(struct rcu_head *rhp)
1749 {
1750 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1751
1752 free_task(tsk);
1753 }
1754
delayed_free_task(struct task_struct * tsk)1755 static __always_inline void delayed_free_task(struct task_struct *tsk)
1756 {
1757 if (IS_ENABLED(CONFIG_MEMCG))
1758 call_rcu(&tsk->rcu, __delayed_free_task);
1759 else
1760 free_task(tsk);
1761 }
1762
1763 /*
1764 * This creates a new process as a copy of the old one,
1765 * but does not actually start it yet.
1766 *
1767 * It copies the registers, and all the appropriate
1768 * parts of the process environment (as per the clone
1769 * flags). The actual kick-off is left to the caller.
1770 */
copy_process(struct pid * pid,int trace,int node,struct kernel_clone_args * args)1771 static __latent_entropy struct task_struct *copy_process(
1772 struct pid *pid,
1773 int trace,
1774 int node,
1775 struct kernel_clone_args *args)
1776 {
1777 int pidfd = -1, retval;
1778 struct task_struct *p;
1779 struct multiprocess_signals delayed;
1780 struct file *pidfile = NULL;
1781 u64 clone_flags = args->flags;
1782
1783 /*
1784 * Don't allow sharing the root directory with processes in a different
1785 * namespace
1786 */
1787 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1788 return ERR_PTR(-EINVAL);
1789
1790 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1791 return ERR_PTR(-EINVAL);
1792
1793 /*
1794 * Thread groups must share signals as well, and detached threads
1795 * can only be started up within the thread group.
1796 */
1797 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1798 return ERR_PTR(-EINVAL);
1799
1800 /*
1801 * Shared signal handlers imply shared VM. By way of the above,
1802 * thread groups also imply shared VM. Blocking this case allows
1803 * for various simplifications in other code.
1804 */
1805 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1806 return ERR_PTR(-EINVAL);
1807
1808 /*
1809 * Siblings of global init remain as zombies on exit since they are
1810 * not reaped by their parent (swapper). To solve this and to avoid
1811 * multi-rooted process trees, prevent global and container-inits
1812 * from creating siblings.
1813 */
1814 if ((clone_flags & CLONE_PARENT) &&
1815 current->signal->flags & SIGNAL_UNKILLABLE)
1816 return ERR_PTR(-EINVAL);
1817
1818 /*
1819 * If the new process will be in a different pid or user namespace
1820 * do not allow it to share a thread group with the forking task.
1821 */
1822 if (clone_flags & CLONE_THREAD) {
1823 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1824 (task_active_pid_ns(current) !=
1825 current->nsproxy->pid_ns_for_children))
1826 return ERR_PTR(-EINVAL);
1827 }
1828
1829 if (clone_flags & CLONE_PIDFD) {
1830 /*
1831 * - CLONE_DETACHED is blocked so that we can potentially
1832 * reuse it later for CLONE_PIDFD.
1833 * - CLONE_THREAD is blocked until someone really needs it.
1834 */
1835 if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1836 return ERR_PTR(-EINVAL);
1837 }
1838
1839 /*
1840 * Force any signals received before this point to be delivered
1841 * before the fork happens. Collect up signals sent to multiple
1842 * processes that happen during the fork and delay them so that
1843 * they appear to happen after the fork.
1844 */
1845 sigemptyset(&delayed.signal);
1846 INIT_HLIST_NODE(&delayed.node);
1847
1848 spin_lock_irq(¤t->sighand->siglock);
1849 if (!(clone_flags & CLONE_THREAD))
1850 hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
1851 recalc_sigpending();
1852 spin_unlock_irq(¤t->sighand->siglock);
1853 retval = -ERESTARTNOINTR;
1854 if (signal_pending(current))
1855 goto fork_out;
1856
1857 retval = -ENOMEM;
1858 p = dup_task_struct(current, node);
1859 if (!p)
1860 goto fork_out;
1861
1862 cpufreq_task_times_init(p);
1863
1864 /*
1865 * This _must_ happen before we call free_task(), i.e. before we jump
1866 * to any of the bad_fork_* labels. This is to avoid freeing
1867 * p->set_child_tid which is (ab)used as a kthread's data pointer for
1868 * kernel threads (PF_KTHREAD).
1869 */
1870 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
1871 /*
1872 * Clear TID on mm_release()?
1873 */
1874 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
1875
1876 ftrace_graph_init_task(p);
1877
1878 rt_mutex_init_task(p);
1879
1880 #ifdef CONFIG_PROVE_LOCKING
1881 DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1882 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1883 #endif
1884 retval = -EAGAIN;
1885 if (atomic_read(&p->real_cred->user->processes) >=
1886 task_rlimit(p, RLIMIT_NPROC)) {
1887 if (p->real_cred->user != INIT_USER &&
1888 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1889 goto bad_fork_free;
1890 }
1891 current->flags &= ~PF_NPROC_EXCEEDED;
1892
1893 retval = copy_creds(p, clone_flags);
1894 if (retval < 0)
1895 goto bad_fork_free;
1896
1897 /*
1898 * If multiple threads are within copy_process(), then this check
1899 * triggers too late. This doesn't hurt, the check is only there
1900 * to stop root fork bombs.
1901 */
1902 retval = -EAGAIN;
1903 if (nr_threads >= max_threads)
1904 goto bad_fork_cleanup_count;
1905
1906 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
1907 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1908 p->flags |= PF_FORKNOEXEC;
1909 INIT_LIST_HEAD(&p->children);
1910 INIT_LIST_HEAD(&p->sibling);
1911 rcu_copy_process(p);
1912 p->vfork_done = NULL;
1913 spin_lock_init(&p->alloc_lock);
1914
1915 init_sigpending(&p->pending);
1916
1917 p->utime = p->stime = p->gtime = 0;
1918 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1919 p->utimescaled = p->stimescaled = 0;
1920 #endif
1921 prev_cputime_init(&p->prev_cputime);
1922
1923 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1924 seqcount_init(&p->vtime.seqcount);
1925 p->vtime.starttime = 0;
1926 p->vtime.state = VTIME_INACTIVE;
1927 #endif
1928
1929 #if defined(SPLIT_RSS_COUNTING)
1930 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1931 #endif
1932
1933 p->default_timer_slack_ns = current->timer_slack_ns;
1934
1935 #ifdef CONFIG_PSI
1936 p->psi_flags = 0;
1937 #endif
1938
1939 task_io_accounting_init(&p->ioac);
1940 acct_clear_integrals(p);
1941
1942 posix_cputimers_init(&p->posix_cputimers);
1943
1944 p->io_context = NULL;
1945 audit_set_context(p, NULL);
1946 cgroup_fork(p);
1947 #ifdef CONFIG_NUMA
1948 p->mempolicy = mpol_dup(p->mempolicy);
1949 if (IS_ERR(p->mempolicy)) {
1950 retval = PTR_ERR(p->mempolicy);
1951 p->mempolicy = NULL;
1952 goto bad_fork_cleanup_threadgroup_lock;
1953 }
1954 #endif
1955 #ifdef CONFIG_CPUSETS
1956 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1957 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1958 seqcount_init(&p->mems_allowed_seq);
1959 #endif
1960 #ifdef CONFIG_TRACE_IRQFLAGS
1961 p->irq_events = 0;
1962 p->hardirqs_enabled = 0;
1963 p->hardirq_enable_ip = 0;
1964 p->hardirq_enable_event = 0;
1965 p->hardirq_disable_ip = _THIS_IP_;
1966 p->hardirq_disable_event = 0;
1967 p->softirqs_enabled = 1;
1968 p->softirq_enable_ip = _THIS_IP_;
1969 p->softirq_enable_event = 0;
1970 p->softirq_disable_ip = 0;
1971 p->softirq_disable_event = 0;
1972 p->hardirq_context = 0;
1973 p->softirq_context = 0;
1974 #endif
1975
1976 p->pagefault_disabled = 0;
1977
1978 #ifdef CONFIG_LOCKDEP
1979 lockdep_init_task(p);
1980 #endif
1981
1982 #ifdef CONFIG_DEBUG_MUTEXES
1983 p->blocked_on = NULL; /* not blocked yet */
1984 #endif
1985 #ifdef CONFIG_BCACHE
1986 p->sequential_io = 0;
1987 p->sequential_io_avg = 0;
1988 #endif
1989
1990 /* Perform scheduler related setup. Assign this task to a CPU. */
1991 retval = sched_fork(clone_flags, p);
1992 if (retval)
1993 goto bad_fork_cleanup_policy;
1994
1995 retval = perf_event_init_task(p);
1996 if (retval)
1997 goto bad_fork_cleanup_policy;
1998 retval = audit_alloc(p);
1999 if (retval)
2000 goto bad_fork_cleanup_perf;
2001 /* copy all the process information */
2002 shm_init_task(p);
2003 retval = security_task_alloc(p, clone_flags);
2004 if (retval)
2005 goto bad_fork_cleanup_audit;
2006 retval = copy_semundo(clone_flags, p);
2007 if (retval)
2008 goto bad_fork_cleanup_security;
2009 retval = copy_files(clone_flags, p);
2010 if (retval)
2011 goto bad_fork_cleanup_semundo;
2012 retval = copy_fs(clone_flags, p);
2013 if (retval)
2014 goto bad_fork_cleanup_files;
2015 retval = copy_sighand(clone_flags, p);
2016 if (retval)
2017 goto bad_fork_cleanup_fs;
2018 retval = copy_signal(clone_flags, p);
2019 if (retval)
2020 goto bad_fork_cleanup_sighand;
2021 retval = copy_mm(clone_flags, p);
2022 if (retval)
2023 goto bad_fork_cleanup_signal;
2024 retval = copy_namespaces(clone_flags, p);
2025 if (retval)
2026 goto bad_fork_cleanup_mm;
2027 retval = copy_io(clone_flags, p);
2028 if (retval)
2029 goto bad_fork_cleanup_namespaces;
2030 retval = copy_thread_tls(clone_flags, args->stack, args->stack_size, p,
2031 args->tls);
2032 if (retval)
2033 goto bad_fork_cleanup_io;
2034
2035 stackleak_task_init(p);
2036
2037 if (pid != &init_struct_pid) {
2038 pid = alloc_pid(p->nsproxy->pid_ns_for_children);
2039 if (IS_ERR(pid)) {
2040 retval = PTR_ERR(pid);
2041 goto bad_fork_cleanup_thread;
2042 }
2043 }
2044
2045 /*
2046 * This has to happen after we've potentially unshared the file
2047 * descriptor table (so that the pidfd doesn't leak into the child
2048 * if the fd table isn't shared).
2049 */
2050 if (clone_flags & CLONE_PIDFD) {
2051 retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2052 if (retval < 0)
2053 goto bad_fork_free_pid;
2054
2055 pidfd = retval;
2056
2057 pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2058 O_RDWR | O_CLOEXEC);
2059 if (IS_ERR(pidfile)) {
2060 put_unused_fd(pidfd);
2061 retval = PTR_ERR(pidfile);
2062 goto bad_fork_free_pid;
2063 }
2064 get_pid(pid); /* held by pidfile now */
2065
2066 retval = put_user(pidfd, args->pidfd);
2067 if (retval)
2068 goto bad_fork_put_pidfd;
2069 }
2070
2071 #ifdef CONFIG_BLOCK
2072 p->plug = NULL;
2073 #endif
2074 futex_init_task(p);
2075
2076 /*
2077 * sigaltstack should be cleared when sharing the same VM
2078 */
2079 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2080 sas_ss_reset(p);
2081
2082 /*
2083 * Syscall tracing and stepping should be turned off in the
2084 * child regardless of CLONE_PTRACE.
2085 */
2086 user_disable_single_step(p);
2087 clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2088 #ifdef TIF_SYSCALL_EMU
2089 clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2090 #endif
2091 clear_tsk_latency_tracing(p);
2092
2093 /* ok, now we should be set up.. */
2094 p->pid = pid_nr(pid);
2095 if (clone_flags & CLONE_THREAD) {
2096 p->exit_signal = -1;
2097 p->group_leader = current->group_leader;
2098 p->tgid = current->tgid;
2099 } else {
2100 if (clone_flags & CLONE_PARENT)
2101 p->exit_signal = current->group_leader->exit_signal;
2102 else
2103 p->exit_signal = args->exit_signal;
2104 p->group_leader = p;
2105 p->tgid = p->pid;
2106 }
2107
2108 p->nr_dirtied = 0;
2109 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2110 p->dirty_paused_when = 0;
2111
2112 p->pdeath_signal = 0;
2113 INIT_LIST_HEAD(&p->thread_group);
2114 p->task_works = NULL;
2115
2116 cgroup_threadgroup_change_begin(current);
2117 /*
2118 * Ensure that the cgroup subsystem policies allow the new process to be
2119 * forked. It should be noted the the new process's css_set can be changed
2120 * between here and cgroup_post_fork() if an organisation operation is in
2121 * progress.
2122 */
2123 retval = cgroup_can_fork(p);
2124 if (retval)
2125 goto bad_fork_cgroup_threadgroup_change_end;
2126
2127 /*
2128 * From this point on we must avoid any synchronous user-space
2129 * communication until we take the tasklist-lock. In particular, we do
2130 * not want user-space to be able to predict the process start-time by
2131 * stalling fork(2) after we recorded the start_time but before it is
2132 * visible to the system.
2133 */
2134
2135 p->start_time = ktime_get_ns();
2136 p->real_start_time = ktime_get_boottime_ns();
2137
2138 /*
2139 * Make it visible to the rest of the system, but dont wake it up yet.
2140 * Need tasklist lock for parent etc handling!
2141 */
2142 write_lock_irq(&tasklist_lock);
2143
2144 /* CLONE_PARENT re-uses the old parent */
2145 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2146 p->real_parent = current->real_parent;
2147 p->parent_exec_id = current->parent_exec_id;
2148 } else {
2149 p->real_parent = current;
2150 p->parent_exec_id = current->self_exec_id;
2151 }
2152
2153 klp_copy_process(p);
2154
2155 spin_lock(¤t->sighand->siglock);
2156
2157 /*
2158 * Copy seccomp details explicitly here, in case they were changed
2159 * before holding sighand lock.
2160 */
2161 copy_seccomp(p);
2162
2163 rseq_fork(p, clone_flags);
2164
2165 /* Don't start children in a dying pid namespace */
2166 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2167 retval = -ENOMEM;
2168 goto bad_fork_cancel_cgroup;
2169 }
2170
2171 /* Let kill terminate clone/fork in the middle */
2172 if (fatal_signal_pending(current)) {
2173 retval = -EINTR;
2174 goto bad_fork_cancel_cgroup;
2175 }
2176
2177 /* past the last point of failure */
2178 if (pidfile)
2179 fd_install(pidfd, pidfile);
2180
2181 init_task_pid_links(p);
2182 if (likely(p->pid)) {
2183 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2184
2185 init_task_pid(p, PIDTYPE_PID, pid);
2186 if (thread_group_leader(p)) {
2187 init_task_pid(p, PIDTYPE_TGID, pid);
2188 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2189 init_task_pid(p, PIDTYPE_SID, task_session(current));
2190
2191 if (is_child_reaper(pid)) {
2192 ns_of_pid(pid)->child_reaper = p;
2193 p->signal->flags |= SIGNAL_UNKILLABLE;
2194 }
2195 p->signal->shared_pending.signal = delayed.signal;
2196 p->signal->tty = tty_kref_get(current->signal->tty);
2197 /*
2198 * Inherit has_child_subreaper flag under the same
2199 * tasklist_lock with adding child to the process tree
2200 * for propagate_has_child_subreaper optimization.
2201 */
2202 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2203 p->real_parent->signal->is_child_subreaper;
2204 list_add_tail(&p->sibling, &p->real_parent->children);
2205 list_add_tail_rcu(&p->tasks, &init_task.tasks);
2206 attach_pid(p, PIDTYPE_TGID);
2207 attach_pid(p, PIDTYPE_PGID);
2208 attach_pid(p, PIDTYPE_SID);
2209 __this_cpu_inc(process_counts);
2210 } else {
2211 current->signal->nr_threads++;
2212 atomic_inc(¤t->signal->live);
2213 refcount_inc(¤t->signal->sigcnt);
2214 task_join_group_stop(p);
2215 list_add_tail_rcu(&p->thread_group,
2216 &p->group_leader->thread_group);
2217 list_add_tail_rcu(&p->thread_node,
2218 &p->signal->thread_head);
2219 }
2220 attach_pid(p, PIDTYPE_PID);
2221 nr_threads++;
2222 }
2223 total_forks++;
2224 hlist_del_init(&delayed.node);
2225 spin_unlock(¤t->sighand->siglock);
2226 syscall_tracepoint_update(p);
2227 write_unlock_irq(&tasklist_lock);
2228
2229 proc_fork_connector(p);
2230 cgroup_post_fork(p);
2231 cgroup_threadgroup_change_end(current);
2232 perf_event_fork(p);
2233
2234 trace_task_newtask(p, clone_flags);
2235 uprobe_copy_process(p, clone_flags);
2236
2237 return p;
2238
2239 bad_fork_cancel_cgroup:
2240 spin_unlock(¤t->sighand->siglock);
2241 write_unlock_irq(&tasklist_lock);
2242 cgroup_cancel_fork(p);
2243 bad_fork_cgroup_threadgroup_change_end:
2244 cgroup_threadgroup_change_end(current);
2245 bad_fork_put_pidfd:
2246 if (clone_flags & CLONE_PIDFD) {
2247 fput(pidfile);
2248 put_unused_fd(pidfd);
2249 }
2250 bad_fork_free_pid:
2251 if (pid != &init_struct_pid)
2252 free_pid(pid);
2253 bad_fork_cleanup_thread:
2254 exit_thread(p);
2255 bad_fork_cleanup_io:
2256 if (p->io_context)
2257 exit_io_context(p);
2258 bad_fork_cleanup_namespaces:
2259 exit_task_namespaces(p);
2260 bad_fork_cleanup_mm:
2261 if (p->mm) {
2262 mm_clear_owner(p->mm, p);
2263 mmput(p->mm);
2264 }
2265 bad_fork_cleanup_signal:
2266 if (!(clone_flags & CLONE_THREAD))
2267 free_signal_struct(p->signal);
2268 bad_fork_cleanup_sighand:
2269 __cleanup_sighand(p->sighand);
2270 bad_fork_cleanup_fs:
2271 exit_fs(p); /* blocking */
2272 bad_fork_cleanup_files:
2273 exit_files(p); /* blocking */
2274 bad_fork_cleanup_semundo:
2275 exit_sem(p);
2276 bad_fork_cleanup_security:
2277 security_task_free(p);
2278 bad_fork_cleanup_audit:
2279 audit_free(p);
2280 bad_fork_cleanup_perf:
2281 perf_event_free_task(p);
2282 bad_fork_cleanup_policy:
2283 lockdep_free_task(p);
2284 #ifdef CONFIG_NUMA
2285 mpol_put(p->mempolicy);
2286 bad_fork_cleanup_threadgroup_lock:
2287 #endif
2288 delayacct_tsk_free(p);
2289 bad_fork_cleanup_count:
2290 atomic_dec(&p->cred->user->processes);
2291 exit_creds(p);
2292 bad_fork_free:
2293 p->state = TASK_DEAD;
2294 put_task_stack(p);
2295 delayed_free_task(p);
2296 fork_out:
2297 spin_lock_irq(¤t->sighand->siglock);
2298 hlist_del_init(&delayed.node);
2299 spin_unlock_irq(¤t->sighand->siglock);
2300 return ERR_PTR(retval);
2301 }
2302
init_idle_pids(struct task_struct * idle)2303 static inline void init_idle_pids(struct task_struct *idle)
2304 {
2305 enum pid_type type;
2306
2307 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2308 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2309 init_task_pid(idle, type, &init_struct_pid);
2310 }
2311 }
2312
fork_idle(int cpu)2313 struct task_struct *fork_idle(int cpu)
2314 {
2315 struct task_struct *task;
2316 struct kernel_clone_args args = {
2317 .flags = CLONE_VM,
2318 };
2319
2320 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2321 if (!IS_ERR(task)) {
2322 init_idle_pids(task);
2323 init_idle(task, cpu);
2324 }
2325
2326 return task;
2327 }
2328
copy_init_mm(void)2329 struct mm_struct *copy_init_mm(void)
2330 {
2331 return dup_mm(NULL, &init_mm);
2332 }
2333
2334 /*
2335 * Ok, this is the main fork-routine.
2336 *
2337 * It copies the process, and if successful kick-starts
2338 * it and waits for it to finish using the VM if required.
2339 *
2340 * args->exit_signal is expected to be checked for sanity by the caller.
2341 */
_do_fork(struct kernel_clone_args * args)2342 long _do_fork(struct kernel_clone_args *args)
2343 {
2344 u64 clone_flags = args->flags;
2345 struct completion vfork;
2346 struct pid *pid;
2347 struct task_struct *p;
2348 int trace = 0;
2349 long nr;
2350
2351 /*
2352 * Determine whether and which event to report to ptracer. When
2353 * called from kernel_thread or CLONE_UNTRACED is explicitly
2354 * requested, no event is reported; otherwise, report if the event
2355 * for the type of forking is enabled.
2356 */
2357 if (!(clone_flags & CLONE_UNTRACED)) {
2358 if (clone_flags & CLONE_VFORK)
2359 trace = PTRACE_EVENT_VFORK;
2360 else if (args->exit_signal != SIGCHLD)
2361 trace = PTRACE_EVENT_CLONE;
2362 else
2363 trace = PTRACE_EVENT_FORK;
2364
2365 if (likely(!ptrace_event_enabled(current, trace)))
2366 trace = 0;
2367 }
2368
2369 p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2370 add_latent_entropy();
2371
2372 if (IS_ERR(p))
2373 return PTR_ERR(p);
2374
2375 cpufreq_task_times_alloc(p);
2376
2377 /*
2378 * Do this prior waking up the new thread - the thread pointer
2379 * might get invalid after that point, if the thread exits quickly.
2380 */
2381 trace_sched_process_fork(current, p);
2382
2383 pid = get_task_pid(p, PIDTYPE_PID);
2384 nr = pid_vnr(pid);
2385
2386 if (clone_flags & CLONE_PARENT_SETTID)
2387 put_user(nr, args->parent_tid);
2388
2389 if (clone_flags & CLONE_VFORK) {
2390 p->vfork_done = &vfork;
2391 init_completion(&vfork);
2392 get_task_struct(p);
2393 }
2394
2395 wake_up_new_task(p);
2396
2397 /* forking complete and child started to run, tell ptracer */
2398 if (unlikely(trace))
2399 ptrace_event_pid(trace, pid);
2400
2401 if (clone_flags & CLONE_VFORK) {
2402 if (!wait_for_vfork_done(p, &vfork))
2403 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2404 }
2405
2406 put_pid(pid);
2407 return nr;
2408 }
2409
legacy_clone_args_valid(const struct kernel_clone_args * kargs)2410 bool legacy_clone_args_valid(const struct kernel_clone_args *kargs)
2411 {
2412 /* clone(CLONE_PIDFD) uses parent_tidptr to return a pidfd */
2413 if ((kargs->flags & CLONE_PIDFD) &&
2414 (kargs->flags & CLONE_PARENT_SETTID))
2415 return false;
2416
2417 return true;
2418 }
2419
2420 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2421 /* For compatibility with architectures that call do_fork directly rather than
2422 * 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)2423 long do_fork(unsigned long clone_flags,
2424 unsigned long stack_start,
2425 unsigned long stack_size,
2426 int __user *parent_tidptr,
2427 int __user *child_tidptr)
2428 {
2429 struct kernel_clone_args args = {
2430 .flags = (clone_flags & ~CSIGNAL),
2431 .pidfd = parent_tidptr,
2432 .child_tid = child_tidptr,
2433 .parent_tid = parent_tidptr,
2434 .exit_signal = (clone_flags & CSIGNAL),
2435 .stack = stack_start,
2436 .stack_size = stack_size,
2437 };
2438
2439 if (!legacy_clone_args_valid(&args))
2440 return -EINVAL;
2441
2442 return _do_fork(&args);
2443 }
2444 #endif
2445
2446 /*
2447 * Create a kernel thread.
2448 */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)2449 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2450 {
2451 struct kernel_clone_args args = {
2452 .flags = ((flags | CLONE_VM | CLONE_UNTRACED) & ~CSIGNAL),
2453 .exit_signal = (flags & CSIGNAL),
2454 .stack = (unsigned long)fn,
2455 .stack_size = (unsigned long)arg,
2456 };
2457
2458 return _do_fork(&args);
2459 }
2460
2461 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)2462 SYSCALL_DEFINE0(fork)
2463 {
2464 #ifdef CONFIG_MMU
2465 struct kernel_clone_args args = {
2466 .exit_signal = SIGCHLD,
2467 };
2468
2469 return _do_fork(&args);
2470 #else
2471 /* can not support in nommu mode */
2472 return -EINVAL;
2473 #endif
2474 }
2475 #endif
2476
2477 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)2478 SYSCALL_DEFINE0(vfork)
2479 {
2480 struct kernel_clone_args args = {
2481 .flags = CLONE_VFORK | CLONE_VM,
2482 .exit_signal = SIGCHLD,
2483 };
2484
2485 return _do_fork(&args);
2486 }
2487 #endif
2488
2489 #ifdef __ARCH_WANT_SYS_CLONE
2490 #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)2491 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2492 int __user *, parent_tidptr,
2493 unsigned long, tls,
2494 int __user *, child_tidptr)
2495 #elif defined(CONFIG_CLONE_BACKWARDS2)
2496 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2497 int __user *, parent_tidptr,
2498 int __user *, child_tidptr,
2499 unsigned long, tls)
2500 #elif defined(CONFIG_CLONE_BACKWARDS3)
2501 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2502 int, stack_size,
2503 int __user *, parent_tidptr,
2504 int __user *, child_tidptr,
2505 unsigned long, tls)
2506 #else
2507 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2508 int __user *, parent_tidptr,
2509 int __user *, child_tidptr,
2510 unsigned long, tls)
2511 #endif
2512 {
2513 struct kernel_clone_args args = {
2514 .flags = (clone_flags & ~CSIGNAL),
2515 .pidfd = parent_tidptr,
2516 .child_tid = child_tidptr,
2517 .parent_tid = parent_tidptr,
2518 .exit_signal = (clone_flags & CSIGNAL),
2519 .stack = newsp,
2520 .tls = tls,
2521 };
2522
2523 if (!legacy_clone_args_valid(&args))
2524 return -EINVAL;
2525
2526 return _do_fork(&args);
2527 }
2528 #endif
2529
2530 #ifdef __ARCH_WANT_SYS_CLONE3
2531
2532 /*
2533 * copy_thread implementations handle CLONE_SETTLS by reading the TLS value from
2534 * the registers containing the syscall arguments for clone. This doesn't work
2535 * with clone3 since the TLS value is passed in clone_args instead.
2536 */
2537 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2538 #error clone3 requires copy_thread_tls support in arch
2539 #endif
2540
copy_clone_args_from_user(struct kernel_clone_args * kargs,struct clone_args __user * uargs,size_t usize)2541 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2542 struct clone_args __user *uargs,
2543 size_t usize)
2544 {
2545 int err;
2546 struct clone_args args;
2547
2548 if (unlikely(usize > PAGE_SIZE))
2549 return -E2BIG;
2550 if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
2551 return -EINVAL;
2552
2553 err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2554 if (err)
2555 return err;
2556
2557 /*
2558 * Verify that higher 32bits of exit_signal are unset and that
2559 * it is a valid signal
2560 */
2561 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2562 !valid_signal(args.exit_signal)))
2563 return -EINVAL;
2564
2565 *kargs = (struct kernel_clone_args){
2566 .flags = args.flags,
2567 .pidfd = u64_to_user_ptr(args.pidfd),
2568 .child_tid = u64_to_user_ptr(args.child_tid),
2569 .parent_tid = u64_to_user_ptr(args.parent_tid),
2570 .exit_signal = args.exit_signal,
2571 .stack = args.stack,
2572 .stack_size = args.stack_size,
2573 .tls = args.tls,
2574 };
2575
2576 return 0;
2577 }
2578
2579 /**
2580 * clone3_stack_valid - check and prepare stack
2581 * @kargs: kernel clone args
2582 *
2583 * Verify that the stack arguments userspace gave us are sane.
2584 * In addition, set the stack direction for userspace since it's easy for us to
2585 * determine.
2586 */
clone3_stack_valid(struct kernel_clone_args * kargs)2587 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2588 {
2589 if (kargs->stack == 0) {
2590 if (kargs->stack_size > 0)
2591 return false;
2592 } else {
2593 if (kargs->stack_size == 0)
2594 return false;
2595
2596 if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2597 return false;
2598
2599 #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2600 kargs->stack += kargs->stack_size;
2601 #endif
2602 }
2603
2604 return true;
2605 }
2606
clone3_args_valid(struct kernel_clone_args * kargs)2607 static bool clone3_args_valid(struct kernel_clone_args *kargs)
2608 {
2609 /*
2610 * All lower bits of the flag word are taken.
2611 * Verify that no other unknown flags are passed along.
2612 */
2613 if (kargs->flags & ~CLONE_LEGACY_FLAGS)
2614 return false;
2615
2616 /*
2617 * - make the CLONE_DETACHED bit reuseable for clone3
2618 * - make the CSIGNAL bits reuseable for clone3
2619 */
2620 if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
2621 return false;
2622
2623 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
2624 kargs->exit_signal)
2625 return false;
2626
2627 if (!clone3_stack_valid(kargs))
2628 return false;
2629
2630 return true;
2631 }
2632
2633 /**
2634 * clone3 - create a new process with specific properties
2635 * @uargs: argument structure
2636 * @size: size of @uargs
2637 *
2638 * clone3() is the extensible successor to clone()/clone2().
2639 * It takes a struct as argument that is versioned by its size.
2640 *
2641 * Return: On success, a positive PID for the child process.
2642 * On error, a negative errno number.
2643 */
SYSCALL_DEFINE2(clone3,struct clone_args __user *,uargs,size_t,size)2644 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
2645 {
2646 int err;
2647
2648 struct kernel_clone_args kargs;
2649
2650 err = copy_clone_args_from_user(&kargs, uargs, size);
2651 if (err)
2652 return err;
2653
2654 if (!clone3_args_valid(&kargs))
2655 return -EINVAL;
2656
2657 return _do_fork(&kargs);
2658 }
2659 #endif
2660
walk_process_tree(struct task_struct * top,proc_visitor visitor,void * data)2661 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2662 {
2663 struct task_struct *leader, *parent, *child;
2664 int res;
2665
2666 read_lock(&tasklist_lock);
2667 leader = top = top->group_leader;
2668 down:
2669 for_each_thread(leader, parent) {
2670 list_for_each_entry(child, &parent->children, sibling) {
2671 res = visitor(child, data);
2672 if (res) {
2673 if (res < 0)
2674 goto out;
2675 leader = child;
2676 goto down;
2677 }
2678 up:
2679 ;
2680 }
2681 }
2682
2683 if (leader != top) {
2684 child = leader;
2685 parent = child->real_parent;
2686 leader = parent->group_leader;
2687 goto up;
2688 }
2689 out:
2690 read_unlock(&tasklist_lock);
2691 }
2692
2693 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2694 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2695 #endif
2696
sighand_ctor(void * data)2697 static void sighand_ctor(void *data)
2698 {
2699 struct sighand_struct *sighand = data;
2700
2701 spin_lock_init(&sighand->siglock);
2702 init_waitqueue_head(&sighand->signalfd_wqh);
2703 }
2704
proc_caches_init(void)2705 void __init proc_caches_init(void)
2706 {
2707 unsigned int mm_size;
2708
2709 sighand_cachep = kmem_cache_create("sighand_cache",
2710 sizeof(struct sighand_struct), 0,
2711 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2712 SLAB_ACCOUNT, sighand_ctor);
2713 signal_cachep = kmem_cache_create("signal_cache",
2714 sizeof(struct signal_struct), 0,
2715 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2716 NULL);
2717 files_cachep = kmem_cache_create("files_cache",
2718 sizeof(struct files_struct), 0,
2719 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2720 NULL);
2721 fs_cachep = kmem_cache_create("fs_cache",
2722 sizeof(struct fs_struct), 0,
2723 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2724 NULL);
2725
2726 /*
2727 * The mm_cpumask is located at the end of mm_struct, and is
2728 * dynamically sized based on the maximum CPU number this system
2729 * can have, taking hotplug into account (nr_cpu_ids).
2730 */
2731 mm_size = sizeof(struct mm_struct) + cpumask_size();
2732
2733 mm_cachep = kmem_cache_create_usercopy("mm_struct",
2734 mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
2735 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2736 offsetof(struct mm_struct, saved_auxv),
2737 sizeof_field(struct mm_struct, saved_auxv),
2738 NULL);
2739 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2740 mmap_init();
2741 nsproxy_cache_init();
2742 }
2743
2744 /*
2745 * Check constraints on flags passed to the unshare system call.
2746 */
check_unshare_flags(unsigned long unshare_flags)2747 static int check_unshare_flags(unsigned long unshare_flags)
2748 {
2749 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2750 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2751 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2752 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2753 return -EINVAL;
2754 /*
2755 * Not implemented, but pretend it works if there is nothing
2756 * to unshare. Note that unsharing the address space or the
2757 * signal handlers also need to unshare the signal queues (aka
2758 * CLONE_THREAD).
2759 */
2760 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2761 if (!thread_group_empty(current))
2762 return -EINVAL;
2763 }
2764 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2765 if (refcount_read(¤t->sighand->count) > 1)
2766 return -EINVAL;
2767 }
2768 if (unshare_flags & CLONE_VM) {
2769 if (!current_is_single_threaded())
2770 return -EINVAL;
2771 }
2772
2773 return 0;
2774 }
2775
2776 /*
2777 * Unshare the filesystem structure if it is being shared
2778 */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)2779 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2780 {
2781 struct fs_struct *fs = current->fs;
2782
2783 if (!(unshare_flags & CLONE_FS) || !fs)
2784 return 0;
2785
2786 /* don't need lock here; in the worst case we'll do useless copy */
2787 if (fs->users == 1)
2788 return 0;
2789
2790 *new_fsp = copy_fs_struct(fs);
2791 if (!*new_fsp)
2792 return -ENOMEM;
2793
2794 return 0;
2795 }
2796
2797 /*
2798 * Unshare file descriptor table if it is being shared
2799 */
unshare_fd(unsigned long unshare_flags,struct files_struct ** new_fdp)2800 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2801 {
2802 struct files_struct *fd = current->files;
2803 int error = 0;
2804
2805 if ((unshare_flags & CLONE_FILES) &&
2806 (fd && atomic_read(&fd->count) > 1)) {
2807 *new_fdp = dup_fd(fd, &error);
2808 if (!*new_fdp)
2809 return error;
2810 }
2811
2812 return 0;
2813 }
2814
2815 /*
2816 * unshare allows a process to 'unshare' part of the process
2817 * context which was originally shared using clone. copy_*
2818 * functions used by do_fork() cannot be used here directly
2819 * because they modify an inactive task_struct that is being
2820 * constructed. Here we are modifying the current, active,
2821 * task_struct.
2822 */
ksys_unshare(unsigned long unshare_flags)2823 int ksys_unshare(unsigned long unshare_flags)
2824 {
2825 struct fs_struct *fs, *new_fs = NULL;
2826 struct files_struct *fd, *new_fd = NULL;
2827 struct cred *new_cred = NULL;
2828 struct nsproxy *new_nsproxy = NULL;
2829 int do_sysvsem = 0;
2830 int err;
2831
2832 /*
2833 * If unsharing a user namespace must also unshare the thread group
2834 * and unshare the filesystem root and working directories.
2835 */
2836 if (unshare_flags & CLONE_NEWUSER)
2837 unshare_flags |= CLONE_THREAD | CLONE_FS;
2838 /*
2839 * If unsharing vm, must also unshare signal handlers.
2840 */
2841 if (unshare_flags & CLONE_VM)
2842 unshare_flags |= CLONE_SIGHAND;
2843 /*
2844 * If unsharing a signal handlers, must also unshare the signal queues.
2845 */
2846 if (unshare_flags & CLONE_SIGHAND)
2847 unshare_flags |= CLONE_THREAD;
2848 /*
2849 * If unsharing namespace, must also unshare filesystem information.
2850 */
2851 if (unshare_flags & CLONE_NEWNS)
2852 unshare_flags |= CLONE_FS;
2853
2854 err = check_unshare_flags(unshare_flags);
2855 if (err)
2856 goto bad_unshare_out;
2857 /*
2858 * CLONE_NEWIPC must also detach from the undolist: after switching
2859 * to a new ipc namespace, the semaphore arrays from the old
2860 * namespace are unreachable.
2861 */
2862 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
2863 do_sysvsem = 1;
2864 err = unshare_fs(unshare_flags, &new_fs);
2865 if (err)
2866 goto bad_unshare_out;
2867 err = unshare_fd(unshare_flags, &new_fd);
2868 if (err)
2869 goto bad_unshare_cleanup_fs;
2870 err = unshare_userns(unshare_flags, &new_cred);
2871 if (err)
2872 goto bad_unshare_cleanup_fd;
2873 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2874 new_cred, new_fs);
2875 if (err)
2876 goto bad_unshare_cleanup_cred;
2877
2878 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
2879 if (do_sysvsem) {
2880 /*
2881 * CLONE_SYSVSEM is equivalent to sys_exit().
2882 */
2883 exit_sem(current);
2884 }
2885 if (unshare_flags & CLONE_NEWIPC) {
2886 /* Orphan segments in old ns (see sem above). */
2887 exit_shm(current);
2888 shm_init_task(current);
2889 }
2890
2891 if (new_nsproxy)
2892 switch_task_namespaces(current, new_nsproxy);
2893
2894 task_lock(current);
2895
2896 if (new_fs) {
2897 fs = current->fs;
2898 spin_lock(&fs->lock);
2899 current->fs = new_fs;
2900 if (--fs->users)
2901 new_fs = NULL;
2902 else
2903 new_fs = fs;
2904 spin_unlock(&fs->lock);
2905 }
2906
2907 if (new_fd) {
2908 fd = current->files;
2909 current->files = new_fd;
2910 new_fd = fd;
2911 }
2912
2913 task_unlock(current);
2914
2915 if (new_cred) {
2916 /* Install the new user namespace */
2917 commit_creds(new_cred);
2918 new_cred = NULL;
2919 }
2920 }
2921
2922 perf_event_namespaces(current);
2923
2924 bad_unshare_cleanup_cred:
2925 if (new_cred)
2926 put_cred(new_cred);
2927 bad_unshare_cleanup_fd:
2928 if (new_fd)
2929 put_files_struct(new_fd);
2930
2931 bad_unshare_cleanup_fs:
2932 if (new_fs)
2933 free_fs_struct(new_fs);
2934
2935 bad_unshare_out:
2936 return err;
2937 }
2938
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)2939 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2940 {
2941 return ksys_unshare(unshare_flags);
2942 }
2943
2944 /*
2945 * Helper to unshare the files of the current task.
2946 * We don't want to expose copy_files internals to
2947 * the exec layer of the kernel.
2948 */
2949
unshare_files(struct files_struct ** displaced)2950 int unshare_files(struct files_struct **displaced)
2951 {
2952 struct task_struct *task = current;
2953 struct files_struct *copy = NULL;
2954 int error;
2955
2956 error = unshare_fd(CLONE_FILES, ©);
2957 if (error || !copy) {
2958 *displaced = NULL;
2959 return error;
2960 }
2961 *displaced = task->files;
2962 task_lock(task);
2963 task->files = copy;
2964 task_unlock(task);
2965 return 0;
2966 }
2967
sysctl_max_threads(struct ctl_table * table,int write,void __user * buffer,size_t * lenp,loff_t * ppos)2968 int sysctl_max_threads(struct ctl_table *table, int write,
2969 void __user *buffer, size_t *lenp, loff_t *ppos)
2970 {
2971 struct ctl_table t;
2972 int ret;
2973 int threads = max_threads;
2974 int min = 1;
2975 int max = MAX_THREADS;
2976
2977 t = *table;
2978 t.data = &threads;
2979 t.extra1 = &min;
2980 t.extra2 = &max;
2981
2982 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2983 if (ret || !write)
2984 return ret;
2985
2986 max_threads = threads;
2987
2988 return 0;
2989 }
2990