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