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