projects/linux·blob v7.0-rc2 · refs

3311 lines · 81.0 KiB

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