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