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