kasan, fork: reset pointer tags of vmapped stacks
[linux-block.git] / kernel / fork.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
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
b3e58382 15#include <linux/anon_inodes.h>
1da177e4 16#include <linux/slab.h>
4eb5aaa3 17#include <linux/sched/autogroup.h>
6e84f315 18#include <linux/sched/mm.h>
f7ccbae4 19#include <linux/sched/coredump.h>
8703e8a4 20#include <linux/sched/user.h>
6a3827d7 21#include <linux/sched/numa_balancing.h>
03441a34 22#include <linux/sched/stat.h>
29930025 23#include <linux/sched/task.h>
68db0cf1 24#include <linux/sched/task_stack.h>
32ef5517 25#include <linux/sched/cputime.h>
b3e58382 26#include <linux/seq_file.h>
037741a6 27#include <linux/rtmutex.h>
1da177e4
LT
28#include <linux/init.h>
29#include <linux/unistd.h>
1da177e4
LT
30#include <linux/module.h>
31#include <linux/vmalloc.h>
32#include <linux/completion.h>
1da177e4
LT
33#include <linux/personality.h>
34#include <linux/mempolicy.h>
35#include <linux/sem.h>
36#include <linux/file.h>
9f3acc31 37#include <linux/fdtable.h>
da9cbc87 38#include <linux/iocontext.h>
1da177e4
LT
39#include <linux/key.h>
40#include <linux/binfmts.h>
41#include <linux/mman.h>
cddb8a5c 42#include <linux/mmu_notifier.h>
1da177e4 43#include <linux/fs.h>
615d6e87 44#include <linux/mm.h>
17fca131 45#include <linux/mm_inline.h>
615d6e87 46#include <linux/vmacache.h>
ab516013 47#include <linux/nsproxy.h>
c59ede7b 48#include <linux/capability.h>
1da177e4 49#include <linux/cpu.h>
b4f48b63 50#include <linux/cgroup.h>
1da177e4 51#include <linux/security.h>
a1e78772 52#include <linux/hugetlb.h>
e2cfabdf 53#include <linux/seccomp.h>
1da177e4
LT
54#include <linux/swap.h>
55#include <linux/syscalls.h>
56#include <linux/jiffies.h>
57#include <linux/futex.h>
8141c7f3 58#include <linux/compat.h>
207205a2 59#include <linux/kthread.h>
7c3ab738 60#include <linux/task_io_accounting_ops.h>
ab2af1f5 61#include <linux/rcupdate.h>
1da177e4
LT
62#include <linux/ptrace.h>
63#include <linux/mount.h>
64#include <linux/audit.h>
78fb7466 65#include <linux/memcontrol.h>
f201ae23 66#include <linux/ftrace.h>
5e2bf014 67#include <linux/proc_fs.h>
1da177e4
LT
68#include <linux/profile.h>
69#include <linux/rmap.h>
f8af4da3 70#include <linux/ksm.h>
1da177e4 71#include <linux/acct.h>
893e26e6 72#include <linux/userfaultfd_k.h>
8f0ab514 73#include <linux/tsacct_kern.h>
9f46080c 74#include <linux/cn_proc.h>
ba96a0c8 75#include <linux/freezer.h>
ca74e92b 76#include <linux/delayacct.h>
ad4ecbcb 77#include <linux/taskstats_kern.h>
0a425405 78#include <linux/random.h>
522ed776 79#include <linux/tty.h>
5ad4e53b 80#include <linux/fs_struct.h>
7c9f8861 81#include <linux/magic.h>
cdd6c482 82#include <linux/perf_event.h>
42c4ab41 83#include <linux/posix-timers.h>
8e7cac79 84#include <linux/user-return-notifier.h>
3d5992d2 85#include <linux/oom.h>
ba76149f 86#include <linux/khugepaged.h>
d80e731e 87#include <linux/signalfd.h>
0326f5a9 88#include <linux/uprobes.h>
a27bb332 89#include <linux/aio.h>
52f5684c 90#include <linux/compiler.h>
16db3d3f 91#include <linux/sysctl.h>
5c9a8750 92#include <linux/kcov.h>
d83a7cb3 93#include <linux/livepatch.h>
48ac3c18 94#include <linux/thread_info.h>
afaef01c 95#include <linux/stackleak.h>
eafb149e 96#include <linux/kasan.h>
d08b9f0c 97#include <linux/scs.h>
0f212204 98#include <linux/io_uring.h>
a10787e6 99#include <linux/bpf.h>
a6cbd440 100#include <linux/sched/mm.h>
1da177e4 101
1da177e4 102#include <asm/pgalloc.h>
7c0f6ba6 103#include <linux/uaccess.h>
1da177e4
LT
104#include <asm/mmu_context.h>
105#include <asm/cacheflush.h>
106#include <asm/tlbflush.h>
107
ad8d75ff
SR
108#include <trace/events/sched.h>
109
43d2b113
KH
110#define CREATE_TRACE_POINTS
111#include <trace/events/task.h>
112
ac1b398d
HS
113/*
114 * Minimum number of threads to boot the kernel
115 */
116#define MIN_THREADS 20
117
118/*
119 * Maximum number of threads
120 */
121#define MAX_THREADS FUTEX_TID_MASK
122
1da177e4
LT
123/*
124 * Protected counters by write_lock_irq(&tasklist_lock)
125 */
126unsigned long total_forks; /* Handle normal Linux uptimes. */
fb0a685c 127int nr_threads; /* The idle threads do not count.. */
1da177e4 128
8856ae4d 129static int max_threads; /* tunable limit on nr_threads */
1da177e4 130
8495f7e6
SPP
131#define NAMED_ARRAY_INDEX(x) [x] = __stringify(x)
132
133static const char * const resident_page_types[] = {
134 NAMED_ARRAY_INDEX(MM_FILEPAGES),
135 NAMED_ARRAY_INDEX(MM_ANONPAGES),
136 NAMED_ARRAY_INDEX(MM_SWAPENTS),
137 NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
138};
139
1da177e4
LT
140DEFINE_PER_CPU(unsigned long, process_counts) = 0;
141
c59923a1 142__cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
db1466b3
PM
143
144#ifdef CONFIG_PROVE_RCU
145int lockdep_tasklist_lock_is_held(void)
146{
147 return lockdep_is_held(&tasklist_lock);
148}
149EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
150#endif /* #ifdef CONFIG_PROVE_RCU */
1da177e4
LT
151
152int nr_processes(void)
153{
154 int cpu;
155 int total = 0;
156
1d510750 157 for_each_possible_cpu(cpu)
1da177e4
LT
158 total += per_cpu(process_counts, cpu);
159
160 return total;
161}
162
f19b9f74
AM
163void __weak arch_release_task_struct(struct task_struct *tsk)
164{
165}
166
f5e10287 167#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
e18b890b 168static struct kmem_cache *task_struct_cachep;
41101809
TG
169
170static inline struct task_struct *alloc_task_struct_node(int node)
171{
172 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
173}
174
41101809
TG
175static inline void free_task_struct(struct task_struct *tsk)
176{
41101809
TG
177 kmem_cache_free(task_struct_cachep, tsk);
178}
1da177e4
LT
179#endif
180
b235beea 181#ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
41101809 182
0d15d74a
TG
183/*
184 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
185 * kmemcache based allocator.
186 */
ba14a194 187# if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
ac496bf4 188
be9a2277 189# ifdef CONFIG_VMAP_STACK
ac496bf4
AL
190/*
191 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
192 * flush. Try to minimize the number of calls by caching stacks.
193 */
194#define NR_CACHED_STACKS 2
195static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19659c59 196
e540bf31
SAS
197struct vm_stack {
198 struct rcu_head rcu;
199 struct vm_struct *stack_vm_area;
200};
201
202static bool try_release_thread_stack_to_cache(struct vm_struct *vm)
203{
204 unsigned int i;
205
206 for (i = 0; i < NR_CACHED_STACKS; i++) {
207 if (this_cpu_cmpxchg(cached_stacks[i], NULL, vm) != NULL)
208 continue;
209 return true;
210 }
211 return false;
212}
213
214static void thread_stack_free_rcu(struct rcu_head *rh)
215{
216 struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu);
217
218 if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area))
219 return;
220
221 vfree(vm_stack);
222}
223
224static void thread_stack_delayed_free(struct task_struct *tsk)
225{
226 struct vm_stack *vm_stack = tsk->stack;
227
228 vm_stack->stack_vm_area = tsk->stack_vm_area;
229 call_rcu(&vm_stack->rcu, thread_stack_free_rcu);
230}
231
19659c59
HR
232static int free_vm_stack_cache(unsigned int cpu)
233{
234 struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
235 int i;
236
237 for (i = 0; i < NR_CACHED_STACKS; i++) {
238 struct vm_struct *vm_stack = cached_vm_stacks[i];
239
240 if (!vm_stack)
241 continue;
242
243 vfree(vm_stack->addr);
244 cached_vm_stacks[i] = NULL;
245 }
246
247 return 0;
248}
ac496bf4 249
1a03d3f1 250static int memcg_charge_kernel_stack(struct vm_struct *vm)
b69c49b7 251{
f1c1a9ee
SAS
252 int i;
253 int ret;
254
255 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
256 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
257
258 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
259 ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
260 if (ret)
261 goto err;
262 }
263 return 0;
264err:
265 /*
266 * If memcg_kmem_charge_page() fails, page's memory cgroup pointer is
267 * NULL, and memcg_kmem_uncharge_page() in free_thread_stack() will
268 * ignore this page.
269 */
270 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
271 memcg_kmem_uncharge_page(vm->pages[i], 0);
272 return ret;
273}
274
7865aba3 275static int alloc_thread_stack_node(struct task_struct *tsk, int node)
b69c49b7 276{
1a03d3f1 277 struct vm_struct *vm;
ac496bf4
AL
278 void *stack;
279 int i;
280
ac496bf4 281 for (i = 0; i < NR_CACHED_STACKS; i++) {
112166f8
CL
282 struct vm_struct *s;
283
284 s = this_cpu_xchg(cached_stacks[i], NULL);
ac496bf4
AL
285
286 if (!s)
287 continue;
ac496bf4 288
cebd0eb2
AK
289 /* Mark stack accessible for KASAN. */
290 kasan_unpoison_range(s->addr, THREAD_SIZE);
eafb149e 291
ca182551
KK
292 /* Clear stale pointers from reused stack. */
293 memset(s->addr, 0, THREAD_SIZE);
e01e8063 294
1a03d3f1 295 if (memcg_charge_kernel_stack(s)) {
f1c1a9ee
SAS
296 vfree(s->addr);
297 return -ENOMEM;
298 }
299
ac496bf4 300 tsk->stack_vm_area = s;
ba4a4574 301 tsk->stack = s->addr;
7865aba3 302 return 0;
ac496bf4 303 }
ac496bf4 304
9b6f7e16
RG
305 /*
306 * Allocated stacks are cached and later reused by new threads,
307 * so memcg accounting is performed manually on assigning/releasing
308 * stacks to tasks. Drop __GFP_ACCOUNT.
309 */
48ac3c18 310 stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
ac496bf4 311 VMALLOC_START, VMALLOC_END,
9b6f7e16 312 THREADINFO_GFP & ~__GFP_ACCOUNT,
ac496bf4
AL
313 PAGE_KERNEL,
314 0, node, __builtin_return_address(0));
7865aba3
SAS
315 if (!stack)
316 return -ENOMEM;
ba14a194 317
1a03d3f1
SAS
318 vm = find_vm_area(stack);
319 if (memcg_charge_kernel_stack(vm)) {
f1c1a9ee
SAS
320 vfree(stack);
321 return -ENOMEM;
322 }
ba14a194
AL
323 /*
324 * We can't call find_vm_area() in interrupt context, and
325 * free_thread_stack() can be called in interrupt context,
326 * so cache the vm_struct.
327 */
1a03d3f1 328 tsk->stack_vm_area = vm;
c08e6a12
AK
329 if (stack)
330 stack = kasan_reset_tag(stack);
7865aba3
SAS
331 tsk->stack = stack;
332 return 0;
b69c49b7
FT
333}
334
be9a2277 335static void free_thread_stack(struct task_struct *tsk)
b69c49b7 336{
e540bf31
SAS
337 if (!try_release_thread_stack_to_cache(tsk->stack_vm_area))
338 thread_stack_delayed_free(tsk);
9b6f7e16 339
be9a2277
SAS
340 tsk->stack = NULL;
341 tsk->stack_vm_area = NULL;
342}
ac496bf4 343
be9a2277 344# else /* !CONFIG_VMAP_STACK */
ac496bf4 345
e540bf31
SAS
346static void thread_stack_free_rcu(struct rcu_head *rh)
347{
348 __free_pages(virt_to_page(rh), THREAD_SIZE_ORDER);
349}
350
351static void thread_stack_delayed_free(struct task_struct *tsk)
352{
353 struct rcu_head *rh = tsk->stack;
354
355 call_rcu(rh, thread_stack_free_rcu);
356}
357
7865aba3 358static int alloc_thread_stack_node(struct task_struct *tsk, int node)
be9a2277 359{
4949148a
VD
360 struct page *page = alloc_pages_node(node, THREADINFO_GFP,
361 THREAD_SIZE_ORDER);
b6a84016 362
1bf4580e 363 if (likely(page)) {
8dcc1d34 364 tsk->stack = kasan_reset_tag(page_address(page));
7865aba3 365 return 0;
1bf4580e 366 }
7865aba3 367 return -ENOMEM;
b69c49b7
FT
368}
369
be9a2277 370static void free_thread_stack(struct task_struct *tsk)
b69c49b7 371{
e540bf31 372 thread_stack_delayed_free(tsk);
be9a2277 373 tsk->stack = NULL;
b69c49b7 374}
ac496bf4 375
be9a2277
SAS
376# endif /* CONFIG_VMAP_STACK */
377# else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
9b6f7e16 378
b235beea 379static struct kmem_cache *thread_stack_cache;
ac496bf4 380
e540bf31
SAS
381static void thread_stack_free_rcu(struct rcu_head *rh)
382{
383 kmem_cache_free(thread_stack_cache, rh);
384}
ac496bf4 385
e540bf31
SAS
386static void thread_stack_delayed_free(struct task_struct *tsk)
387{
388 struct rcu_head *rh = tsk->stack;
ac496bf4 389
e540bf31 390 call_rcu(rh, thread_stack_free_rcu);
b69c49b7 391}
0d15d74a 392
7865aba3 393static int alloc_thread_stack_node(struct task_struct *tsk, int node)
0d15d74a 394{
5eed6f1d
RR
395 unsigned long *stack;
396 stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
8dcc1d34 397 stack = kasan_reset_tag(stack);
5eed6f1d 398 tsk->stack = stack;
7865aba3 399 return stack ? 0 : -ENOMEM;
0d15d74a
TG
400}
401
ba14a194 402static void free_thread_stack(struct task_struct *tsk)
0d15d74a 403{
e540bf31 404 thread_stack_delayed_free(tsk);
be9a2277 405 tsk->stack = NULL;
0d15d74a
TG
406}
407
b235beea 408void thread_stack_cache_init(void)
0d15d74a 409{
f9d29946
DW
410 thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
411 THREAD_SIZE, THREAD_SIZE, 0, 0,
412 THREAD_SIZE, NULL);
b235beea 413 BUG_ON(thread_stack_cache == NULL);
0d15d74a 414}
be9a2277
SAS
415
416# endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
2bb0529c
SAS
417#else /* CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
418
7865aba3 419static int alloc_thread_stack_node(struct task_struct *tsk, int node)
2bb0529c
SAS
420{
421 unsigned long *stack;
422
423 stack = arch_alloc_thread_stack_node(tsk, node);
424 tsk->stack = stack;
7865aba3 425 return stack ? 0 : -ENOMEM;
2bb0529c
SAS
426}
427
428static void free_thread_stack(struct task_struct *tsk)
429{
430 arch_free_thread_stack(tsk);
431 tsk->stack = NULL;
432}
433
be9a2277 434#endif /* !CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
b69c49b7 435
1da177e4 436/* SLAB cache for signal_struct structures (tsk->signal) */
e18b890b 437static struct kmem_cache *signal_cachep;
1da177e4
LT
438
439/* SLAB cache for sighand_struct structures (tsk->sighand) */
e18b890b 440struct kmem_cache *sighand_cachep;
1da177e4
LT
441
442/* SLAB cache for files_struct structures (tsk->files) */
e18b890b 443struct kmem_cache *files_cachep;
1da177e4
LT
444
445/* SLAB cache for fs_struct structures (tsk->fs) */
e18b890b 446struct kmem_cache *fs_cachep;
1da177e4
LT
447
448/* SLAB cache for vm_area_struct structures */
3928d4f5 449static struct kmem_cache *vm_area_cachep;
1da177e4
LT
450
451/* SLAB cache for mm_struct structures (tsk->mm) */
e18b890b 452static struct kmem_cache *mm_cachep;
1da177e4 453
490fc053 454struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
3928d4f5 455{
a670468f 456 struct vm_area_struct *vma;
490fc053 457
a670468f 458 vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
027232da
KS
459 if (vma)
460 vma_init(vma, mm);
490fc053 461 return vma;
3928d4f5
LT
462}
463
464struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
465{
95faf699
LT
466 struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
467
468 if (new) {
cda099b3
QC
469 ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
470 ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
471 /*
472 * orig->shared.rb may be modified concurrently, but the clone
473 * will be reinitialized.
474 */
475 *new = data_race(*orig);
95faf699 476 INIT_LIST_HEAD(&new->anon_vma_chain);
e39a4b33 477 new->vm_next = new->vm_prev = NULL;
5c26f6ac 478 dup_anon_vma_name(orig, new);
95faf699
LT
479 }
480 return new;
3928d4f5
LT
481}
482
483void vm_area_free(struct vm_area_struct *vma)
484{
5c26f6ac 485 free_anon_vma_name(vma);
3928d4f5
LT
486 kmem_cache_free(vm_area_cachep, vma);
487}
488
ba14a194 489static void account_kernel_stack(struct task_struct *tsk, int account)
c6a7f572 490{
0ce055f8
SAS
491 if (IS_ENABLED(CONFIG_VMAP_STACK)) {
492 struct vm_struct *vm = task_stack_vm_area(tsk);
27faca83 493 int i;
ba14a194 494
27faca83
MS
495 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
496 mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
497 account * (PAGE_SIZE / 1024));
498 } else {
0ce055f8
SAS
499 void *stack = task_stack_page(tsk);
500
27faca83 501 /* All stack pages are in the same node. */
da3ceeff 502 mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
991e7673 503 account * (THREAD_SIZE / 1024));
27faca83 504 }
c6a7f572
KM
505}
506
1a03d3f1 507void exit_task_stack_account(struct task_struct *tsk)
9b6f7e16 508{
1a03d3f1 509 account_kernel_stack(tsk, -1);
991e7673 510
1a03d3f1
SAS
511 if (IS_ENABLED(CONFIG_VMAP_STACK)) {
512 struct vm_struct *vm;
9b6f7e16
RG
513 int i;
514
1a03d3f1
SAS
515 vm = task_stack_vm_area(tsk);
516 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
517 memcg_kmem_uncharge_page(vm->pages[i], 0);
9b6f7e16 518 }
9b6f7e16
RG
519}
520
68f24b08 521static void release_task_stack(struct task_struct *tsk)
1da177e4 522{
2f064a59 523 if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
405c0759
AL
524 return; /* Better to leak the stack than to free prematurely */
525
ba14a194 526 free_thread_stack(tsk);
68f24b08
AL
527}
528
529#ifdef CONFIG_THREAD_INFO_IN_TASK
530void put_task_stack(struct task_struct *tsk)
531{
f0b89d39 532 if (refcount_dec_and_test(&tsk->stack_refcount))
68f24b08
AL
533 release_task_stack(tsk);
534}
535#endif
536
537void free_task(struct task_struct *tsk)
538{
b90ca8ba 539 release_user_cpus_ptr(tsk);
d08b9f0c
ST
540 scs_release(tsk);
541
68f24b08
AL
542#ifndef CONFIG_THREAD_INFO_IN_TASK
543 /*
544 * The task is finally done with both the stack and thread_info,
545 * so free both.
546 */
547 release_task_stack(tsk);
548#else
549 /*
550 * If the task had a separate stack allocation, it should be gone
551 * by now.
552 */
f0b89d39 553 WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
68f24b08 554#endif
23f78d4a 555 rt_mutex_debug_task_free(tsk);
fb52607a 556 ftrace_graph_exit_task(tsk);
f19b9f74 557 arch_release_task_struct(tsk);
1da5c46f
ON
558 if (tsk->flags & PF_KTHREAD)
559 free_kthread_struct(tsk);
1da177e4
LT
560 free_task_struct(tsk);
561}
562EXPORT_SYMBOL(free_task);
563
fe69d560
DH
564static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
565{
566 struct file *exe_file;
567
568 exe_file = get_mm_exe_file(oldmm);
569 RCU_INIT_POINTER(mm->exe_file, exe_file);
570 /*
571 * We depend on the oldmm having properly denied write access to the
572 * exe_file already.
573 */
574 if (exe_file && deny_write_access(exe_file))
575 pr_warn_once("deny_write_access() failed in %s\n", __func__);
576}
577
d70f2a14
AM
578#ifdef CONFIG_MMU
579static __latent_entropy int dup_mmap(struct mm_struct *mm,
580 struct mm_struct *oldmm)
581{
582 struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
583 struct rb_node **rb_link, *rb_parent;
584 int retval;
585 unsigned long charge;
586 LIST_HEAD(uf);
587
588 uprobe_start_dup_mmap();
d8ed45c5 589 if (mmap_write_lock_killable(oldmm)) {
d70f2a14
AM
590 retval = -EINTR;
591 goto fail_uprobe_end;
592 }
593 flush_cache_dup_mm(oldmm);
594 uprobe_dup_mmap(oldmm, mm);
595 /*
596 * Not linked in yet - no deadlock potential:
597 */
aaa2cc56 598 mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
d70f2a14
AM
599
600 /* No ordering required: file already has been exposed. */
fe69d560 601 dup_mm_exe_file(mm, oldmm);
d70f2a14
AM
602
603 mm->total_vm = oldmm->total_vm;
604 mm->data_vm = oldmm->data_vm;
605 mm->exec_vm = oldmm->exec_vm;
606 mm->stack_vm = oldmm->stack_vm;
607
608 rb_link = &mm->mm_rb.rb_node;
609 rb_parent = NULL;
610 pprev = &mm->mmap;
611 retval = ksm_fork(mm, oldmm);
612 if (retval)
613 goto out;
614 retval = khugepaged_fork(mm, oldmm);
615 if (retval)
616 goto out;
617
618 prev = NULL;
619 for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
620 struct file *file;
621
622 if (mpnt->vm_flags & VM_DONTCOPY) {
623 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
624 continue;
625 }
626 charge = 0;
655c79bb
TH
627 /*
628 * Don't duplicate many vmas if we've been oom-killed (for
629 * example)
630 */
631 if (fatal_signal_pending(current)) {
632 retval = -EINTR;
633 goto out;
634 }
d70f2a14
AM
635 if (mpnt->vm_flags & VM_ACCOUNT) {
636 unsigned long len = vma_pages(mpnt);
637
638 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
639 goto fail_nomem;
640 charge = len;
641 }
3928d4f5 642 tmp = vm_area_dup(mpnt);
d70f2a14
AM
643 if (!tmp)
644 goto fail_nomem;
d70f2a14
AM
645 retval = vma_dup_policy(mpnt, tmp);
646 if (retval)
647 goto fail_nomem_policy;
648 tmp->vm_mm = mm;
649 retval = dup_userfaultfd(tmp, &uf);
650 if (retval)
651 goto fail_nomem_anon_vma_fork;
652 if (tmp->vm_flags & VM_WIPEONFORK) {
93949bb2
LX
653 /*
654 * VM_WIPEONFORK gets a clean slate in the child.
655 * Don't prepare anon_vma until fault since we don't
656 * copy page for current vma.
657 */
d70f2a14 658 tmp->anon_vma = NULL;
d70f2a14
AM
659 } else if (anon_vma_fork(tmp, mpnt))
660 goto fail_nomem_anon_vma_fork;
661 tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
d70f2a14
AM
662 file = tmp->vm_file;
663 if (file) {
d70f2a14
AM
664 struct address_space *mapping = file->f_mapping;
665
666 get_file(file);
d70f2a14
AM
667 i_mmap_lock_write(mapping);
668 if (tmp->vm_flags & VM_SHARED)
cf508b58 669 mapping_allow_writable(mapping);
d70f2a14
AM
670 flush_dcache_mmap_lock(mapping);
671 /* insert tmp into the share list, just after mpnt */
672 vma_interval_tree_insert_after(tmp, mpnt,
673 &mapping->i_mmap);
674 flush_dcache_mmap_unlock(mapping);
675 i_mmap_unlock_write(mapping);
676 }
677
678 /*
679 * Clear hugetlb-related page reserves for children. This only
680 * affects MAP_PRIVATE mappings. Faults generated by the child
681 * are not guaranteed to succeed, even if read-only
682 */
683 if (is_vm_hugetlb_page(tmp))
684 reset_vma_resv_huge_pages(tmp);
685
686 /*
687 * Link in the new vma and copy the page table entries.
688 */
689 *pprev = tmp;
690 pprev = &tmp->vm_next;
691 tmp->vm_prev = prev;
692 prev = tmp;
693
694 __vma_link_rb(mm, tmp, rb_link, rb_parent);
695 rb_link = &tmp->vm_rb.rb_right;
696 rb_parent = &tmp->vm_rb;
697
698 mm->map_count++;
699 if (!(tmp->vm_flags & VM_WIPEONFORK))
c78f4636 700 retval = copy_page_range(tmp, mpnt);
d70f2a14
AM
701
702 if (tmp->vm_ops && tmp->vm_ops->open)
703 tmp->vm_ops->open(tmp);
704
705 if (retval)
706 goto out;
707 }
708 /* a new mm has just been created */
1ed0cc5a 709 retval = arch_dup_mmap(oldmm, mm);
d70f2a14 710out:
d8ed45c5 711 mmap_write_unlock(mm);
d70f2a14 712 flush_tlb_mm(oldmm);
d8ed45c5 713 mmap_write_unlock(oldmm);
d70f2a14
AM
714 dup_userfaultfd_complete(&uf);
715fail_uprobe_end:
716 uprobe_end_dup_mmap();
717 return retval;
718fail_nomem_anon_vma_fork:
719 mpol_put(vma_policy(tmp));
720fail_nomem_policy:
3928d4f5 721 vm_area_free(tmp);
d70f2a14
AM
722fail_nomem:
723 retval = -ENOMEM;
724 vm_unacct_memory(charge);
725 goto out;
726}
727
728static inline int mm_alloc_pgd(struct mm_struct *mm)
729{
730 mm->pgd = pgd_alloc(mm);
731 if (unlikely(!mm->pgd))
732 return -ENOMEM;
733 return 0;
734}
735
736static inline void mm_free_pgd(struct mm_struct *mm)
737{
738 pgd_free(mm, mm->pgd);
739}
740#else
741static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
742{
d8ed45c5 743 mmap_write_lock(oldmm);
fe69d560 744 dup_mm_exe_file(mm, oldmm);
d8ed45c5 745 mmap_write_unlock(oldmm);
d70f2a14
AM
746 return 0;
747}
748#define mm_alloc_pgd(mm) (0)
749#define mm_free_pgd(mm)
750#endif /* CONFIG_MMU */
751
752static void check_mm(struct mm_struct *mm)
753{
754 int i;
755
8495f7e6
SPP
756 BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
757 "Please make sure 'struct resident_page_types[]' is updated as well");
758
d70f2a14
AM
759 for (i = 0; i < NR_MM_COUNTERS; i++) {
760 long x = atomic_long_read(&mm->rss_stat.count[i]);
761
762 if (unlikely(x))
8495f7e6
SPP
763 pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
764 mm, resident_page_types[i], x);
d70f2a14
AM
765 }
766
767 if (mm_pgtables_bytes(mm))
768 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
769 mm_pgtables_bytes(mm));
770
771#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
772 VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
773#endif
774}
775
776#define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
777#define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
778
779/*
780 * Called when the last reference to the mm
781 * is dropped: either by a lazy thread or by
782 * mmput. Free the page directory and the mm.
783 */
d34bc48f 784void __mmdrop(struct mm_struct *mm)
d70f2a14
AM
785{
786 BUG_ON(mm == &init_mm);
3eda69c9
MR
787 WARN_ON_ONCE(mm == current->mm);
788 WARN_ON_ONCE(mm == current->active_mm);
d70f2a14
AM
789 mm_free_pgd(mm);
790 destroy_context(mm);
984cfe4e 791 mmu_notifier_subscriptions_destroy(mm);
d70f2a14
AM
792 check_mm(mm);
793 put_user_ns(mm->user_ns);
794 free_mm(mm);
795}
d34bc48f 796EXPORT_SYMBOL_GPL(__mmdrop);
d70f2a14
AM
797
798static void mmdrop_async_fn(struct work_struct *work)
799{
800 struct mm_struct *mm;
801
802 mm = container_of(work, struct mm_struct, async_put_work);
803 __mmdrop(mm);
804}
805
806static void mmdrop_async(struct mm_struct *mm)
807{
808 if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
809 INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
810 schedule_work(&mm->async_put_work);
811 }
812}
813
ea6d290c
ON
814static inline void free_signal_struct(struct signal_struct *sig)
815{
97101eb4 816 taskstats_tgid_free(sig);
1c5354de 817 sched_autogroup_exit(sig);
7283094e
MH
818 /*
819 * __mmdrop is not safe to call from softirq context on x86 due to
820 * pgd_dtor so postpone it to the async context
821 */
26db62f1 822 if (sig->oom_mm)
7283094e 823 mmdrop_async(sig->oom_mm);
ea6d290c
ON
824 kmem_cache_free(signal_cachep, sig);
825}
826
827static inline void put_signal_struct(struct signal_struct *sig)
828{
60d4de3f 829 if (refcount_dec_and_test(&sig->sigcnt))
ea6d290c
ON
830 free_signal_struct(sig);
831}
832
158d9ebd 833void __put_task_struct(struct task_struct *tsk)
1da177e4 834{
270f722d 835 WARN_ON(!tsk->exit_state);
ec1d2819 836 WARN_ON(refcount_read(&tsk->usage));
1da177e4
LT
837 WARN_ON(tsk == current);
838
0f212204 839 io_uring_free(tsk);
2e91fa7f 840 cgroup_free(tsk);
16d51a59 841 task_numa_free(tsk, true);
1a2a4d06 842 security_task_free(tsk);
a10787e6 843 bpf_task_storage_free(tsk);
e0e81739 844 exit_creds(tsk);
35df17c5 845 delayacct_tsk_free(tsk);
ea6d290c 846 put_signal_struct(tsk->signal);
6e33cad0 847 sched_core_free(tsk);
2873cd31 848 free_task(tsk);
1da177e4 849}
77c100c8 850EXPORT_SYMBOL_GPL(__put_task_struct);
1da177e4 851
6c0a9fa6 852void __init __weak arch_task_cache_init(void) { }
61c4628b 853
ff691f6e
HS
854/*
855 * set_max_threads
856 */
16db3d3f 857static void set_max_threads(unsigned int max_threads_suggested)
ff691f6e 858{
ac1b398d 859 u64 threads;
ca79b0c2 860 unsigned long nr_pages = totalram_pages();
ff691f6e
HS
861
862 /*
ac1b398d
HS
863 * The number of threads shall be limited such that the thread
864 * structures may only consume a small part of the available memory.
ff691f6e 865 */
3d6357de 866 if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
ac1b398d
HS
867 threads = MAX_THREADS;
868 else
3d6357de 869 threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
ac1b398d
HS
870 (u64) THREAD_SIZE * 8UL);
871
16db3d3f
HS
872 if (threads > max_threads_suggested)
873 threads = max_threads_suggested;
874
ac1b398d 875 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
ff691f6e
HS
876}
877
5aaeb5c0
IM
878#ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
879/* Initialized by the architecture: */
880int arch_task_struct_size __read_mostly;
881#endif
0c8c0f03 882
4189ff23 883#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
5905429a
KC
884static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
885{
886 /* Fetch thread_struct whitelist for the architecture. */
887 arch_thread_struct_whitelist(offset, size);
888
889 /*
890 * Handle zero-sized whitelist or empty thread_struct, otherwise
891 * adjust offset to position of thread_struct in task_struct.
892 */
893 if (unlikely(*size == 0))
894 *offset = 0;
895 else
896 *offset += offsetof(struct task_struct, thread);
897}
4189ff23 898#endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
5905429a 899
ff691f6e 900void __init fork_init(void)
1da177e4 901{
25f9c081 902 int i;
f5e10287 903#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
1da177e4 904#ifndef ARCH_MIN_TASKALIGN
e274795e 905#define ARCH_MIN_TASKALIGN 0
1da177e4 906#endif
95cb64c1 907 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
5905429a 908 unsigned long useroffset, usersize;
e274795e 909
1da177e4 910 /* create a slab on which task_structs can be allocated */
5905429a
KC
911 task_struct_whitelist(&useroffset, &usersize);
912 task_struct_cachep = kmem_cache_create_usercopy("task_struct",
e274795e 913 arch_task_struct_size, align,
5905429a
KC
914 SLAB_PANIC|SLAB_ACCOUNT,
915 useroffset, usersize, NULL);
1da177e4
LT
916#endif
917
61c4628b
SS
918 /* do the arch specific task caches init */
919 arch_task_cache_init();
920
16db3d3f 921 set_max_threads(MAX_THREADS);
1da177e4
LT
922
923 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
924 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
925 init_task.signal->rlim[RLIMIT_SIGPENDING] =
926 init_task.signal->rlim[RLIMIT_NPROC];
b376c3e1 927
21d1c5e3 928 for (i = 0; i < MAX_PER_NAMESPACE_UCOUNTS; i++)
25f9c081 929 init_user_ns.ucount_max[i] = max_threads/2;
19659c59 930
5ddf994f
EB
931 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_NPROC, RLIM_INFINITY);
932 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE, RLIM_INFINITY);
933 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
934 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK, RLIM_INFINITY);
21d1c5e3 935
19659c59
HR
936#ifdef CONFIG_VMAP_STACK
937 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
938 NULL, free_vm_stack_cache);
939#endif
b09be676 940
d08b9f0c
ST
941 scs_init();
942
b09be676 943 lockdep_init_task(&init_task);
aad42dd4 944 uprobes_init();
1da177e4
LT
945}
946
52f5684c 947int __weak arch_dup_task_struct(struct task_struct *dst,
61c4628b
SS
948 struct task_struct *src)
949{
950 *dst = *src;
951 return 0;
952}
953
d4311ff1
AT
954void set_task_stack_end_magic(struct task_struct *tsk)
955{
956 unsigned long *stackend;
957
958 stackend = end_of_stack(tsk);
959 *stackend = STACK_END_MAGIC; /* for overflow detection */
960}
961
725fc629 962static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
1da177e4
LT
963{
964 struct task_struct *tsk;
3e26c149 965 int err;
1da177e4 966
725fc629
AK
967 if (node == NUMA_NO_NODE)
968 node = tsk_fork_get_node(orig);
504f52b5 969 tsk = alloc_task_struct_node(node);
1da177e4
LT
970 if (!tsk)
971 return NULL;
972
546c42b2
SAS
973 err = arch_dup_task_struct(tsk, orig);
974 if (err)
f19b9f74 975 goto free_tsk;
1da177e4 976
7865aba3
SAS
977 err = alloc_thread_stack_node(tsk, node);
978 if (err)
f19b9f74 979 goto free_tsk;
ba14a194 980
68f24b08 981#ifdef CONFIG_THREAD_INFO_IN_TASK
f0b89d39 982 refcount_set(&tsk->stack_refcount, 1);
68f24b08 983#endif
1a03d3f1 984 account_kernel_stack(tsk, 1);
164c33c6 985
d08b9f0c
ST
986 err = scs_prepare(tsk, node);
987 if (err)
988 goto free_stack;
989
dbd95212
KC
990#ifdef CONFIG_SECCOMP
991 /*
992 * We must handle setting up seccomp filters once we're under
993 * the sighand lock in case orig has changed between now and
994 * then. Until then, filter must be NULL to avoid messing up
995 * the usage counts on the error path calling free_task.
996 */
997 tsk->seccomp.filter = NULL;
998#endif
87bec58a
AM
999
1000 setup_thread_stack(tsk, orig);
8e7cac79 1001 clear_user_return_notifier(tsk);
f26f9aff 1002 clear_tsk_need_resched(tsk);
d4311ff1 1003 set_task_stack_end_magic(tsk);
1446e1df 1004 clear_syscall_work_syscall_user_dispatch(tsk);
1da177e4 1005
050e9baa 1006#ifdef CONFIG_STACKPROTECTOR
7cd815bc 1007 tsk->stack_canary = get_random_canary();
0a425405 1008#endif
3bd37062
SAS
1009 if (orig->cpus_ptr == &orig->cpus_mask)
1010 tsk->cpus_ptr = &tsk->cpus_mask;
b90ca8ba 1011 dup_user_cpus_ptr(tsk, orig, node);
0a425405 1012
fb0a685c 1013 /*
0ff7b2cf
EB
1014 * One for the user space visible state that goes away when reaped.
1015 * One for the scheduler.
fb0a685c 1016 */
0ff7b2cf
EB
1017 refcount_set(&tsk->rcu_users, 2);
1018 /* One for the rcu users */
1019 refcount_set(&tsk->usage, 1);
6c5c9341 1020#ifdef CONFIG_BLK_DEV_IO_TRACE
2056a782 1021 tsk->btrace_seq = 0;
6c5c9341 1022#endif
a0aa7f68 1023 tsk->splice_pipe = NULL;
5640f768 1024 tsk->task_frag.page = NULL;
093e5840 1025 tsk->wake_q.next = NULL;
e32cf5df 1026 tsk->worker_private = NULL;
c6a7f572 1027
5c9a8750 1028 kcov_task_init(tsk);
5fbda3ec 1029 kmap_local_fork(tsk);
5c9a8750 1030
e41d5818
DV
1031#ifdef CONFIG_FAULT_INJECTION
1032 tsk->fail_nth = 0;
1033#endif
1034
2c323017
JB
1035#ifdef CONFIG_BLK_CGROUP
1036 tsk->throttle_queue = NULL;
1037 tsk->use_memdelay = 0;
1038#endif
1039
a3d29e82
PZ
1040#ifdef CONFIG_IOMMU_SVA
1041 tsk->pasid_activated = 0;
1042#endif
1043
d46eb14b
SB
1044#ifdef CONFIG_MEMCG
1045 tsk->active_memcg = NULL;
1046#endif
1da177e4 1047 return tsk;
61c4628b 1048
b235beea 1049free_stack:
1a03d3f1 1050 exit_task_stack_account(tsk);
ba14a194 1051 free_thread_stack(tsk);
f19b9f74 1052free_tsk:
61c4628b
SS
1053 free_task_struct(tsk);
1054 return NULL;
1da177e4
LT
1055}
1056
23ff4440 1057__cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
1da177e4 1058
4cb0e11b
HK
1059static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
1060
1061static int __init coredump_filter_setup(char *s)
1062{
1063 default_dump_filter =
1064 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
1065 MMF_DUMP_FILTER_MASK;
1066 return 1;
1067}
1068
1069__setup("coredump_filter=", coredump_filter_setup);
1070
1da177e4
LT
1071#include <linux/init_task.h>
1072
858f0993
AD
1073static void mm_init_aio(struct mm_struct *mm)
1074{
1075#ifdef CONFIG_AIO
1076 spin_lock_init(&mm->ioctx_lock);
db446a08 1077 mm->ioctx_table = NULL;
858f0993
AD
1078#endif
1079}
1080
c3f3ce04
AA
1081static __always_inline void mm_clear_owner(struct mm_struct *mm,
1082 struct task_struct *p)
1083{
1084#ifdef CONFIG_MEMCG
1085 if (mm->owner == p)
1086 WRITE_ONCE(mm->owner, NULL);
1087#endif
1088}
1089
33144e84
VD
1090static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1091{
1092#ifdef CONFIG_MEMCG
1093 mm->owner = p;
1094#endif
1095}
1096
355627f5
EB
1097static void mm_init_uprobes_state(struct mm_struct *mm)
1098{
1099#ifdef CONFIG_UPROBES
1100 mm->uprobes_state.xol_area = NULL;
1101#endif
1102}
1103
bfedb589
EB
1104static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1105 struct user_namespace *user_ns)
1da177e4 1106{
41f727fd
VD
1107 mm->mmap = NULL;
1108 mm->mm_rb = RB_ROOT;
1109 mm->vmacache_seqnum = 0;
1da177e4
LT
1110 atomic_set(&mm->mm_users, 1);
1111 atomic_set(&mm->mm_count, 1);
57efa1fe 1112 seqcount_init(&mm->write_protect_seq);
d8ed45c5 1113 mmap_init_lock(mm);
1da177e4 1114 INIT_LIST_HEAD(&mm->mmlist);
af5b0f6a 1115 mm_pgtables_bytes_init(mm);
41f727fd
VD
1116 mm->map_count = 0;
1117 mm->locked_vm = 0;
70f8a3ca 1118 atomic64_set(&mm->pinned_vm, 0);
d559db08 1119 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1da177e4 1120 spin_lock_init(&mm->page_table_lock);
88aa7cc6 1121 spin_lock_init(&mm->arg_lock);
41f727fd 1122 mm_init_cpumask(mm);
858f0993 1123 mm_init_aio(mm);
cf475ad2 1124 mm_init_owner(mm, p);
a6cbd440 1125 mm_pasid_init(mm);
2b7e8665 1126 RCU_INIT_POINTER(mm->exe_file, NULL);
984cfe4e 1127 mmu_notifier_subscriptions_init(mm);
16af97dc 1128 init_tlb_flush_pending(mm);
41f727fd
VD
1129#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
1130 mm->pmd_huge_pte = NULL;
1131#endif
355627f5 1132 mm_init_uprobes_state(mm);
13db8c50 1133 hugetlb_count_init(mm);
1da177e4 1134
a0715cc2
AT
1135 if (current->mm) {
1136 mm->flags = current->mm->flags & MMF_INIT_MASK;
1137 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1138 } else {
1139 mm->flags = default_dump_filter;
1da177e4 1140 mm->def_flags = 0;
a0715cc2
AT
1141 }
1142
41f727fd
VD
1143 if (mm_alloc_pgd(mm))
1144 goto fail_nopgd;
1145
1146 if (init_new_context(p, mm))
1147 goto fail_nocontext;
78fb7466 1148
bfedb589 1149 mm->user_ns = get_user_ns(user_ns);
41f727fd
VD
1150 return mm;
1151
1152fail_nocontext:
1153 mm_free_pgd(mm);
1154fail_nopgd:
1da177e4
LT
1155 free_mm(mm);
1156 return NULL;
1157}
1158
1159/*
1160 * Allocate and initialize an mm_struct.
1161 */
fb0a685c 1162struct mm_struct *mm_alloc(void)
1da177e4 1163{
fb0a685c 1164 struct mm_struct *mm;
1da177e4
LT
1165
1166 mm = allocate_mm();
de03c72c
KM
1167 if (!mm)
1168 return NULL;
1169
1170 memset(mm, 0, sizeof(*mm));
bfedb589 1171 return mm_init(mm, current, current_user_ns());
1da177e4
LT
1172}
1173
ec8d7c14
MH
1174static inline void __mmput(struct mm_struct *mm)
1175{
1176 VM_BUG_ON(atomic_read(&mm->mm_users));
1177
1178 uprobe_clear_state(mm);
1179 exit_aio(mm);
1180 ksm_exit(mm);
1181 khugepaged_exit(mm); /* must run before exit_mmap */
1182 exit_mmap(mm);
6fcb52a5 1183 mm_put_huge_zero_page(mm);
ec8d7c14
MH
1184 set_mm_exe_file(mm, NULL);
1185 if (!list_empty(&mm->mmlist)) {
1186 spin_lock(&mmlist_lock);
1187 list_del(&mm->mmlist);
1188 spin_unlock(&mmlist_lock);
1189 }
1190 if (mm->binfmt)
1191 module_put(mm->binfmt->module);
701fac40 1192 mm_pasid_drop(mm);
ec8d7c14
MH
1193 mmdrop(mm);
1194}
1195
1da177e4
LT
1196/*
1197 * Decrement the use count and release all resources for an mm.
1198 */
1199void mmput(struct mm_struct *mm)
1200{
0ae26f1b
AM
1201 might_sleep();
1202
ec8d7c14
MH
1203 if (atomic_dec_and_test(&mm->mm_users))
1204 __mmput(mm);
1205}
1206EXPORT_SYMBOL_GPL(mmput);
1207
a1b2289c
SY
1208#ifdef CONFIG_MMU
1209static void mmput_async_fn(struct work_struct *work)
1210{
1211 struct mm_struct *mm = container_of(work, struct mm_struct,
1212 async_put_work);
1213
1214 __mmput(mm);
1215}
1216
1217void mmput_async(struct mm_struct *mm)
1218{
1219 if (atomic_dec_and_test(&mm->mm_users)) {
1220 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1221 schedule_work(&mm->async_put_work);
1222 }
1223}
1224#endif
1225
90f31d0e
KK
1226/**
1227 * set_mm_exe_file - change a reference to the mm's executable file
1228 *
1229 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1230 *
6e399cd1
DB
1231 * Main users are mmput() and sys_execve(). Callers prevent concurrent
1232 * invocations: in mmput() nobody alive left, in execve task is single
35d7bdc8 1233 * threaded.
fe69d560
DH
1234 *
1235 * Can only fail if new_exe_file != NULL.
90f31d0e 1236 */
fe69d560 1237int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
38646013 1238{
6e399cd1
DB
1239 struct file *old_exe_file;
1240
1241 /*
1242 * It is safe to dereference the exe_file without RCU as
1243 * this function is only called if nobody else can access
1244 * this mm -- see comment above for justification.
1245 */
1246 old_exe_file = rcu_dereference_raw(mm->exe_file);
90f31d0e 1247
fe69d560
DH
1248 if (new_exe_file) {
1249 /*
1250 * We expect the caller (i.e., sys_execve) to already denied
1251 * write access, so this is unlikely to fail.
1252 */
1253 if (unlikely(deny_write_access(new_exe_file)))
1254 return -EACCES;
38646013 1255 get_file(new_exe_file);
fe69d560 1256 }
90f31d0e 1257 rcu_assign_pointer(mm->exe_file, new_exe_file);
fe69d560
DH
1258 if (old_exe_file) {
1259 allow_write_access(old_exe_file);
90f31d0e 1260 fput(old_exe_file);
fe69d560
DH
1261 }
1262 return 0;
38646013
JS
1263}
1264
35d7bdc8
DH
1265/**
1266 * replace_mm_exe_file - replace a reference to the mm's executable file
1267 *
1268 * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
1269 * dealing with concurrent invocation and without grabbing the mmap lock in
1270 * write mode.
1271 *
1272 * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
1273 */
1274int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1275{
1276 struct vm_area_struct *vma;
1277 struct file *old_exe_file;
1278 int ret = 0;
1279
1280 /* Forbid mm->exe_file change if old file still mapped. */
1281 old_exe_file = get_mm_exe_file(mm);
1282 if (old_exe_file) {
1283 mmap_read_lock(mm);
1284 for (vma = mm->mmap; vma && !ret; vma = vma->vm_next) {
1285 if (!vma->vm_file)
1286 continue;
1287 if (path_equal(&vma->vm_file->f_path,
1288 &old_exe_file->f_path))
1289 ret = -EBUSY;
1290 }
1291 mmap_read_unlock(mm);
1292 fput(old_exe_file);
1293 if (ret)
1294 return ret;
1295 }
1296
1297 /* set the new file, lockless */
fe69d560
DH
1298 ret = deny_write_access(new_exe_file);
1299 if (ret)
1300 return -EACCES;
35d7bdc8 1301 get_file(new_exe_file);
fe69d560 1302
35d7bdc8 1303 old_exe_file = xchg(&mm->exe_file, new_exe_file);
fe69d560
DH
1304 if (old_exe_file) {
1305 /*
1306 * Don't race with dup_mmap() getting the file and disallowing
1307 * write access while someone might open the file writable.
1308 */
1309 mmap_read_lock(mm);
1310 allow_write_access(old_exe_file);
35d7bdc8 1311 fput(old_exe_file);
fe69d560
DH
1312 mmap_read_unlock(mm);
1313 }
35d7bdc8 1314 return 0;
38646013
JS
1315}
1316
90f31d0e
KK
1317/**
1318 * get_mm_exe_file - acquire a reference to the mm's executable file
1319 *
1320 * Returns %NULL if mm has no associated executable file.
1321 * User must release file via fput().
1322 */
38646013
JS
1323struct file *get_mm_exe_file(struct mm_struct *mm)
1324{
1325 struct file *exe_file;
1326
90f31d0e
KK
1327 rcu_read_lock();
1328 exe_file = rcu_dereference(mm->exe_file);
1329 if (exe_file && !get_file_rcu(exe_file))
1330 exe_file = NULL;
1331 rcu_read_unlock();
38646013
JS
1332 return exe_file;
1333}
1334
cd81a917
MG
1335/**
1336 * get_task_exe_file - acquire a reference to the task's executable file
1337 *
1338 * Returns %NULL if task's mm (if any) has no associated executable file or
1339 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1340 * User must release file via fput().
1341 */
1342struct file *get_task_exe_file(struct task_struct *task)
1343{
1344 struct file *exe_file = NULL;
1345 struct mm_struct *mm;
1346
1347 task_lock(task);
1348 mm = task->mm;
1349 if (mm) {
1350 if (!(task->flags & PF_KTHREAD))
1351 exe_file = get_mm_exe_file(mm);
1352 }
1353 task_unlock(task);
1354 return exe_file;
1355}
38646013 1356
1da177e4
LT
1357/**
1358 * get_task_mm - acquire a reference to the task's mm
1359 *
246bb0b1 1360 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1da177e4
LT
1361 * this kernel workthread has transiently adopted a user mm with use_mm,
1362 * to do its AIO) is not set and if so returns a reference to it, after
1363 * bumping up the use count. User must release the mm via mmput()
1364 * after use. Typically used by /proc and ptrace.
1365 */
1366struct mm_struct *get_task_mm(struct task_struct *task)
1367{
1368 struct mm_struct *mm;
1369
1370 task_lock(task);
1371 mm = task->mm;
1372 if (mm) {
246bb0b1 1373 if (task->flags & PF_KTHREAD)
1da177e4
LT
1374 mm = NULL;
1375 else
3fce371b 1376 mmget(mm);
1da177e4
LT
1377 }
1378 task_unlock(task);
1379 return mm;
1380}
1381EXPORT_SYMBOL_GPL(get_task_mm);
1382
8cdb878d
CY
1383struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1384{
1385 struct mm_struct *mm;
1386 int err;
1387
f7cfd871 1388 err = down_read_killable(&task->signal->exec_update_lock);
8cdb878d
CY
1389 if (err)
1390 return ERR_PTR(err);
1391
1392 mm = get_task_mm(task);
1393 if (mm && mm != current->mm &&
1394 !ptrace_may_access(task, mode)) {
1395 mmput(mm);
1396 mm = ERR_PTR(-EACCES);
1397 }
f7cfd871 1398 up_read(&task->signal->exec_update_lock);
8cdb878d
CY
1399
1400 return mm;
1401}
1402
57b59c4a 1403static void complete_vfork_done(struct task_struct *tsk)
c415c3b4 1404{
d68b46fe 1405 struct completion *vfork;
c415c3b4 1406
d68b46fe
ON
1407 task_lock(tsk);
1408 vfork = tsk->vfork_done;
1409 if (likely(vfork)) {
1410 tsk->vfork_done = NULL;
1411 complete(vfork);
1412 }
1413 task_unlock(tsk);
1414}
1415
1416static int wait_for_vfork_done(struct task_struct *child,
1417 struct completion *vfork)
1418{
1419 int killed;
1420
1421 freezer_do_not_count();
76f969e8 1422 cgroup_enter_frozen();
d68b46fe 1423 killed = wait_for_completion_killable(vfork);
76f969e8 1424 cgroup_leave_frozen(false);
d68b46fe
ON
1425 freezer_count();
1426
1427 if (killed) {
1428 task_lock(child);
1429 child->vfork_done = NULL;
1430 task_unlock(child);
1431 }
1432
1433 put_task_struct(child);
1434 return killed;
c415c3b4
ON
1435}
1436
1da177e4
LT
1437/* Please note the differences between mmput and mm_release.
1438 * mmput is called whenever we stop holding onto a mm_struct,
1439 * error success whatever.
1440 *
1441 * mm_release is called after a mm_struct has been removed
1442 * from the current process.
1443 *
1444 * This difference is important for error handling, when we
1445 * only half set up a mm_struct for a new process and need to restore
1446 * the old one. Because we mmput the new mm_struct before
1447 * restoring the old one. . .
1448 * Eric Biederman 10 January 1998
1449 */
4610ba7a 1450static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1da177e4 1451{
0326f5a9
SD
1452 uprobe_free_utask(tsk);
1453
1da177e4
LT
1454 /* Get rid of any cached register state */
1455 deactivate_mm(tsk, mm);
1456
fec1d011 1457 /*
735f2770
MH
1458 * Signal userspace if we're not exiting with a core dump
1459 * because we want to leave the value intact for debugging
1460 * purposes.
fec1d011 1461 */
9c8a8228 1462 if (tsk->clear_child_tid) {
92307383 1463 if (atomic_read(&mm->mm_users) > 1) {
9c8a8228
ED
1464 /*
1465 * We don't check the error code - if userspace has
1466 * not set up a proper pointer then tough luck.
1467 */
1468 put_user(0, tsk->clear_child_tid);
2de0db99
DB
1469 do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1470 1, NULL, NULL, 0, 0);
9c8a8228 1471 }
1da177e4 1472 tsk->clear_child_tid = NULL;
1da177e4 1473 }
f7505d64
KK
1474
1475 /*
1476 * All done, finally we can wake up parent and return this mm to him.
1477 * Also kthread_stop() uses this completion for synchronization.
1478 */
1479 if (tsk->vfork_done)
1480 complete_vfork_done(tsk);
1da177e4
LT
1481}
1482
4610ba7a
TG
1483void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1484{
150d7158 1485 futex_exit_release(tsk);
4610ba7a
TG
1486 mm_release(tsk, mm);
1487}
1488
1489void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1490{
150d7158 1491 futex_exec_release(tsk);
4610ba7a
TG
1492 mm_release(tsk, mm);
1493}
1494
13585fa0
NA
1495/**
1496 * dup_mm() - duplicates an existing mm structure
1497 * @tsk: the task_struct with which the new mm will be associated.
1498 * @oldmm: the mm to duplicate.
1499 *
1500 * Allocates a new mm structure and duplicates the provided @oldmm structure
1501 * content into it.
1502 *
1503 * Return: the duplicated mm or NULL on failure.
a0a7ec30 1504 */
13585fa0
NA
1505static struct mm_struct *dup_mm(struct task_struct *tsk,
1506 struct mm_struct *oldmm)
a0a7ec30 1507{
13585fa0 1508 struct mm_struct *mm;
a0a7ec30
JD
1509 int err;
1510
a0a7ec30
JD
1511 mm = allocate_mm();
1512 if (!mm)
1513 goto fail_nomem;
1514
1515 memcpy(mm, oldmm, sizeof(*mm));
1516
bfedb589 1517 if (!mm_init(mm, tsk, mm->user_ns))
a0a7ec30
JD
1518 goto fail_nomem;
1519
a0a7ec30
JD
1520 err = dup_mmap(mm, oldmm);
1521 if (err)
1522 goto free_pt;
1523
1524 mm->hiwater_rss = get_mm_rss(mm);
1525 mm->hiwater_vm = mm->total_vm;
1526
801460d0
HS
1527 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1528 goto free_pt;
1529
a0a7ec30
JD
1530 return mm;
1531
1532free_pt:
801460d0
HS
1533 /* don't put binfmt in mmput, we haven't got module yet */
1534 mm->binfmt = NULL;
c3f3ce04 1535 mm_init_owner(mm, NULL);
a0a7ec30
JD
1536 mmput(mm);
1537
1538fail_nomem:
1539 return NULL;
a0a7ec30
JD
1540}
1541
fb0a685c 1542static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1da177e4 1543{
fb0a685c 1544 struct mm_struct *mm, *oldmm;
1da177e4
LT
1545
1546 tsk->min_flt = tsk->maj_flt = 0;
1547 tsk->nvcsw = tsk->nivcsw = 0;
17406b82
MSB
1548#ifdef CONFIG_DETECT_HUNG_TASK
1549 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
a2e51445 1550 tsk->last_switch_time = 0;
17406b82 1551#endif
1da177e4
LT
1552
1553 tsk->mm = NULL;
1554 tsk->active_mm = NULL;
1555
1556 /*
1557 * Are we cloning a kernel thread?
1558 *
1559 * We need to steal a active VM for that..
1560 */
1561 oldmm = current->mm;
1562 if (!oldmm)
1563 return 0;
1564
615d6e87
DB
1565 /* initialize the new vmacache entries */
1566 vmacache_flush(tsk);
1567
1da177e4 1568 if (clone_flags & CLONE_VM) {
3fce371b 1569 mmget(oldmm);
1da177e4 1570 mm = oldmm;
a6895399
REB
1571 } else {
1572 mm = dup_mm(tsk, current->mm);
1573 if (!mm)
1574 return -ENOMEM;
1da177e4
LT
1575 }
1576
1da177e4
LT
1577 tsk->mm = mm;
1578 tsk->active_mm = mm;
1579 return 0;
1da177e4
LT
1580}
1581
a39bc516 1582static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1da177e4 1583{
498052bb 1584 struct fs_struct *fs = current->fs;
1da177e4 1585 if (clone_flags & CLONE_FS) {
498052bb 1586 /* tsk->fs is already what we want */
2a4419b5 1587 spin_lock(&fs->lock);
498052bb 1588 if (fs->in_exec) {
2a4419b5 1589 spin_unlock(&fs->lock);
498052bb
AV
1590 return -EAGAIN;
1591 }
1592 fs->users++;
2a4419b5 1593 spin_unlock(&fs->lock);
1da177e4
LT
1594 return 0;
1595 }
498052bb 1596 tsk->fs = copy_fs_struct(fs);
1da177e4
LT
1597 if (!tsk->fs)
1598 return -ENOMEM;
1599 return 0;
1600}
1601
fb0a685c 1602static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
a016f338
JD
1603{
1604 struct files_struct *oldf, *newf;
1605 int error = 0;
1606
1607 /*
1608 * A background process may not have any files ...
1609 */
1610 oldf = current->files;
1611 if (!oldf)
1612 goto out;
1613
1614 if (clone_flags & CLONE_FILES) {
1615 atomic_inc(&oldf->count);
1616 goto out;
1617 }
1618
60997c3d 1619 newf = dup_fd(oldf, NR_OPEN_MAX, &error);
a016f338
JD
1620 if (!newf)
1621 goto out;
1622
1623 tsk->files = newf;
1624 error = 0;
1625out:
1626 return error;
1627}
1628
a39bc516 1629static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1da177e4
LT
1630{
1631 struct sighand_struct *sig;
1632
60348802 1633 if (clone_flags & CLONE_SIGHAND) {
d036bda7 1634 refcount_inc(&current->sighand->count);
1da177e4
LT
1635 return 0;
1636 }
1637 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
0c282b06 1638 RCU_INIT_POINTER(tsk->sighand, sig);
1da177e4
LT
1639 if (!sig)
1640 return -ENOMEM;
9d7fb042 1641
d036bda7 1642 refcount_set(&sig->count, 1);
06e62a46 1643 spin_lock_irq(&current->sighand->siglock);
1da177e4 1644 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
06e62a46 1645 spin_unlock_irq(&current->sighand->siglock);
b612e5df
CB
1646
1647 /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1648 if (clone_flags & CLONE_CLEAR_SIGHAND)
1649 flush_signal_handlers(tsk, 0);
1650
1da177e4
LT
1651 return 0;
1652}
1653
a7e5328a 1654void __cleanup_sighand(struct sighand_struct *sighand)
c81addc9 1655{
d036bda7 1656 if (refcount_dec_and_test(&sighand->count)) {
d80e731e 1657 signalfd_cleanup(sighand);
392809b2 1658 /*
5f0d5a3a 1659 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
392809b2
ON
1660 * without an RCU grace period, see __lock_task_sighand().
1661 */
c81addc9 1662 kmem_cache_free(sighand_cachep, sighand);
d80e731e 1663 }
c81addc9
ON
1664}
1665
f06febc9
FM
1666/*
1667 * Initialize POSIX timer handling for a thread group.
1668 */
1669static void posix_cpu_timers_init_group(struct signal_struct *sig)
1670{
2b69942f 1671 struct posix_cputimers *pct = &sig->posix_cputimers;
78d7d407
JS
1672 unsigned long cpu_limit;
1673
316c1608 1674 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
3a245c0f 1675 posix_cputimers_group_init(pct, cpu_limit);
f06febc9
FM
1676}
1677
a39bc516 1678static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1da177e4
LT
1679{
1680 struct signal_struct *sig;
1da177e4 1681
4ab6c083 1682 if (clone_flags & CLONE_THREAD)
490dea45 1683 return 0;
490dea45 1684
a56704ef 1685 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1da177e4
LT
1686 tsk->signal = sig;
1687 if (!sig)
1688 return -ENOMEM;
1689
b3ac022c 1690 sig->nr_threads = 1;
1da177e4 1691 atomic_set(&sig->live, 1);
60d4de3f 1692 refcount_set(&sig->sigcnt, 1);
0c740d0a
ON
1693
1694 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1695 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1696 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1697
1da177e4 1698 init_waitqueue_head(&sig->wait_chldexit);
db51aecc 1699 sig->curr_target = tsk;
1da177e4 1700 init_sigpending(&sig->shared_pending);
c3ad2c3b 1701 INIT_HLIST_HEAD(&sig->multiprocess);
e78c3496 1702 seqlock_init(&sig->stats_lock);
9d7fb042 1703 prev_cputime_init(&sig->prev_cputime);
1da177e4 1704
baa73d9e 1705#ifdef CONFIG_POSIX_TIMERS
b18b6a9c 1706 INIT_LIST_HEAD(&sig->posix_timers);
c9cb2e3d 1707 hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1da177e4 1708 sig->real_timer.function = it_real_fn;
baa73d9e 1709#endif
1da177e4 1710
1da177e4
LT
1711 task_lock(current->group_leader);
1712 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1713 task_unlock(current->group_leader);
1714
6279a751
ON
1715 posix_cpu_timers_init_group(sig);
1716
522ed776 1717 tty_audit_fork(sig);
5091faa4 1718 sched_autogroup_fork(sig);
522ed776 1719
a63d83f4 1720 sig->oom_score_adj = current->signal->oom_score_adj;
dabb16f6 1721 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
28b83c51 1722
9b1bf12d 1723 mutex_init(&sig->cred_guard_mutex);
f7cfd871 1724 init_rwsem(&sig->exec_update_lock);
9b1bf12d 1725
1da177e4
LT
1726 return 0;
1727}
1728
dbd95212
KC
1729static void copy_seccomp(struct task_struct *p)
1730{
1731#ifdef CONFIG_SECCOMP
1732 /*
1733 * Must be called with sighand->lock held, which is common to
1734 * all threads in the group. Holding cred_guard_mutex is not
1735 * needed because this new task is not yet running and cannot
1736 * be racing exec.
1737 */
69f6a34b 1738 assert_spin_locked(&current->sighand->siglock);
dbd95212
KC
1739
1740 /* Ref-count the new filter user, and assign it. */
1741 get_seccomp_filter(current);
1742 p->seccomp = current->seccomp;
1743
1744 /*
1745 * Explicitly enable no_new_privs here in case it got set
1746 * between the task_struct being duplicated and holding the
1747 * sighand lock. The seccomp state and nnp must be in sync.
1748 */
1749 if (task_no_new_privs(current))
1750 task_set_no_new_privs(p);
1751
1752 /*
1753 * If the parent gained a seccomp mode after copying thread
1754 * flags and between before we held the sighand lock, we have
1755 * to manually enable the seccomp thread flag here.
1756 */
1757 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
23d67a54 1758 set_task_syscall_work(p, SECCOMP);
dbd95212
KC
1759#endif
1760}
1761
17da2bd9 1762SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1da177e4
LT
1763{
1764 current->clear_child_tid = tidptr;
1765
b488893a 1766 return task_pid_vnr(current);
1da177e4
LT
1767}
1768
a39bc516 1769static void rt_mutex_init_task(struct task_struct *p)
23f78d4a 1770{
1d615482 1771 raw_spin_lock_init(&p->pi_lock);
e29e175b 1772#ifdef CONFIG_RT_MUTEXES
a23ba907 1773 p->pi_waiters = RB_ROOT_CACHED;
e96a7705 1774 p->pi_top_task = NULL;
23f78d4a 1775 p->pi_blocked_on = NULL;
23f78d4a
IM
1776#endif
1777}
1778
2c470475
EB
1779static inline void init_task_pid_links(struct task_struct *task)
1780{
1781 enum pid_type type;
1782
96e1e984 1783 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
2c470475 1784 INIT_HLIST_NODE(&task->pid_links[type]);
2c470475
EB
1785}
1786
81907739
ON
1787static inline void
1788init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1789{
2c470475
EB
1790 if (type == PIDTYPE_PID)
1791 task->thread_pid = pid;
1792 else
1793 task->signal->pids[type] = pid;
81907739
ON
1794}
1795
6bfbaa51
IM
1796static inline void rcu_copy_process(struct task_struct *p)
1797{
1798#ifdef CONFIG_PREEMPT_RCU
1799 p->rcu_read_lock_nesting = 0;
1800 p->rcu_read_unlock_special.s = 0;
1801 p->rcu_blocked_node = NULL;
1802 INIT_LIST_HEAD(&p->rcu_node_entry);
1803#endif /* #ifdef CONFIG_PREEMPT_RCU */
1804#ifdef CONFIG_TASKS_RCU
1805 p->rcu_tasks_holdout = false;
1806 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1807 p->rcu_tasks_idle_cpu = -1;
1808#endif /* #ifdef CONFIG_TASKS_RCU */
d5f177d3
PM
1809#ifdef CONFIG_TASKS_TRACE_RCU
1810 p->trc_reader_nesting = 0;
276c4104 1811 p->trc_reader_special.s = 0;
d5f177d3
PM
1812 INIT_LIST_HEAD(&p->trc_holdout_list);
1813#endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
6bfbaa51
IM
1814}
1815
3695eae5
CB
1816struct pid *pidfd_pid(const struct file *file)
1817{
1818 if (file->f_op == &pidfd_fops)
1819 return file->private_data;
1820
1821 return ERR_PTR(-EBADF);
1822}
1823
b3e58382
CB
1824static int pidfd_release(struct inode *inode, struct file *file)
1825{
1826 struct pid *pid = file->private_data;
1827
1828 file->private_data = NULL;
1829 put_pid(pid);
1830 return 0;
1831}
1832
1833#ifdef CONFIG_PROC_FS
15d42eb2
CK
1834/**
1835 * pidfd_show_fdinfo - print information about a pidfd
1836 * @m: proc fdinfo file
1837 * @f: file referencing a pidfd
1838 *
1839 * Pid:
1840 * This function will print the pid that a given pidfd refers to in the
1841 * pid namespace of the procfs instance.
1842 * If the pid namespace of the process is not a descendant of the pid
1843 * namespace of the procfs instance 0 will be shown as its pid. This is
1844 * similar to calling getppid() on a process whose parent is outside of
1845 * its pid namespace.
1846 *
1847 * NSpid:
1848 * If pid namespaces are supported then this function will also print
1849 * the pid of a given pidfd refers to for all descendant pid namespaces
1850 * starting from the current pid namespace of the instance, i.e. the
1851 * Pid field and the first entry in the NSpid field will be identical.
1852 * If the pid namespace of the process is not a descendant of the pid
1853 * namespace of the procfs instance 0 will be shown as its first NSpid
1854 * entry and no others will be shown.
1855 * Note that this differs from the Pid and NSpid fields in
1856 * /proc/<pid>/status where Pid and NSpid are always shown relative to
1857 * the pid namespace of the procfs instance. The difference becomes
1858 * obvious when sending around a pidfd between pid namespaces from a
a8ca6b13 1859 * different branch of the tree, i.e. where no ancestral relation is
15d42eb2
CK
1860 * present between the pid namespaces:
1861 * - create two new pid namespaces ns1 and ns2 in the initial pid
1862 * namespace (also take care to create new mount namespaces in the
1863 * new pid namespace and mount procfs)
1864 * - create a process with a pidfd in ns1
1865 * - send pidfd from ns1 to ns2
1866 * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
1867 * have exactly one entry, which is 0
1868 */
b3e58382
CB
1869static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1870{
b3e58382 1871 struct pid *pid = f->private_data;
3d6d8da4
CB
1872 struct pid_namespace *ns;
1873 pid_t nr = -1;
15d42eb2 1874
3d6d8da4 1875 if (likely(pid_has_task(pid, PIDTYPE_PID))) {
9d78edea 1876 ns = proc_pid_ns(file_inode(m->file)->i_sb);
3d6d8da4
CB
1877 nr = pid_nr_ns(pid, ns);
1878 }
1879
1880 seq_put_decimal_ll(m, "Pid:\t", nr);
b3e58382 1881
15d42eb2 1882#ifdef CONFIG_PID_NS
3d6d8da4
CB
1883 seq_put_decimal_ll(m, "\nNSpid:\t", nr);
1884 if (nr > 0) {
15d42eb2 1885 int i;
b3e58382 1886
15d42eb2
CK
1887 /* If nr is non-zero it means that 'pid' is valid and that
1888 * ns, i.e. the pid namespace associated with the procfs
1889 * instance, is in the pid namespace hierarchy of pid.
1890 * Start at one below the already printed level.
1891 */
1892 for (i = ns->level + 1; i <= pid->level; i++)
3d6d8da4 1893 seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
15d42eb2
CK
1894 }
1895#endif
b3e58382
CB
1896 seq_putc(m, '\n');
1897}
1898#endif
1899
b53b0b9d
JFG
1900/*
1901 * Poll support for process exit notification.
1902 */
9e77716a 1903static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
b53b0b9d 1904{
b53b0b9d 1905 struct pid *pid = file->private_data;
9e77716a 1906 __poll_t poll_flags = 0;
b53b0b9d
JFG
1907
1908 poll_wait(file, &pid->wait_pidfd, pts);
1909
b53b0b9d
JFG
1910 /*
1911 * Inform pollers only when the whole thread group exits.
1912 * If the thread group leader exits before all other threads in the
1913 * group, then poll(2) should block, similar to the wait(2) family.
1914 */
38fd525a 1915 if (thread_group_exited(pid))
9e77716a 1916 poll_flags = EPOLLIN | EPOLLRDNORM;
b53b0b9d
JFG
1917
1918 return poll_flags;
1919}
1920
b3e58382
CB
1921const struct file_operations pidfd_fops = {
1922 .release = pidfd_release,
b53b0b9d 1923 .poll = pidfd_poll,
b3e58382
CB
1924#ifdef CONFIG_PROC_FS
1925 .show_fdinfo = pidfd_show_fdinfo,
1926#endif
1927};
1928
c3f3ce04
AA
1929static void __delayed_free_task(struct rcu_head *rhp)
1930{
1931 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1932
1933 free_task(tsk);
1934}
1935
1936static __always_inline void delayed_free_task(struct task_struct *tsk)
1937{
1938 if (IS_ENABLED(CONFIG_MEMCG))
1939 call_rcu(&tsk->rcu, __delayed_free_task);
1940 else
1941 free_task(tsk);
1942}
1943
67197a4f
SB
1944static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
1945{
1946 /* Skip if kernel thread */
1947 if (!tsk->mm)
1948 return;
1949
1950 /* Skip if spawning a thread or using vfork */
1951 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
1952 return;
1953
1954 /* We need to synchronize with __set_oom_adj */
1955 mutex_lock(&oom_adj_mutex);
1956 set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
1957 /* Update the values in case they were changed after copy_signal */
1958 tsk->signal->oom_score_adj = current->signal->oom_score_adj;
1959 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
1960 mutex_unlock(&oom_adj_mutex);
1961}
1962
1da177e4
LT
1963/*
1964 * This creates a new process as a copy of the old one,
1965 * but does not actually start it yet.
1966 *
1967 * It copies the registers, and all the appropriate
1968 * parts of the process environment (as per the clone
1969 * flags). The actual kick-off is left to the caller.
1970 */
0766f788 1971static __latent_entropy struct task_struct *copy_process(
09a05394 1972 struct pid *pid,
3033f14a 1973 int trace,
7f192e3c
CB
1974 int node,
1975 struct kernel_clone_args *args)
1da177e4 1976{
b3e58382 1977 int pidfd = -1, retval;
a24efe62 1978 struct task_struct *p;
c3ad2c3b 1979 struct multiprocess_signals delayed;
6fd2fe49 1980 struct file *pidfile = NULL;
7f192e3c 1981 u64 clone_flags = args->flags;
769071ac 1982 struct nsproxy *nsp = current->nsproxy;
1da177e4 1983
667b6094
MPS
1984 /*
1985 * Don't allow sharing the root directory with processes in a different
1986 * namespace
1987 */
1da177e4
LT
1988 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1989 return ERR_PTR(-EINVAL);
1990
e66eded8
EB
1991 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1992 return ERR_PTR(-EINVAL);
1993
1da177e4
LT
1994 /*
1995 * Thread groups must share signals as well, and detached threads
1996 * can only be started up within the thread group.
1997 */
1998 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1999 return ERR_PTR(-EINVAL);
2000
2001 /*
2002 * Shared signal handlers imply shared VM. By way of the above,
2003 * thread groups also imply shared VM. Blocking this case allows
2004 * for various simplifications in other code.
2005 */
2006 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2007 return ERR_PTR(-EINVAL);
2008
123be07b
SB
2009 /*
2010 * Siblings of global init remain as zombies on exit since they are
2011 * not reaped by their parent (swapper). To solve this and to avoid
2012 * multi-rooted process trees, prevent global and container-inits
2013 * from creating siblings.
2014 */
2015 if ((clone_flags & CLONE_PARENT) &&
2016 current->signal->flags & SIGNAL_UNKILLABLE)
2017 return ERR_PTR(-EINVAL);
2018
8382fcac 2019 /*
40a0d32d 2020 * If the new process will be in a different pid or user namespace
faf00da5 2021 * do not allow it to share a thread group with the forking task.
8382fcac 2022 */
faf00da5 2023 if (clone_flags & CLONE_THREAD) {
40a0d32d 2024 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
769071ac
AV
2025 (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2026 return ERR_PTR(-EINVAL);
2027 }
2028
2029 /*
2030 * If the new process will be in a different time namespace
2031 * do not allow it to share VM or a thread group with the forking task.
2032 */
2033 if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
2034 if (nsp->time_ns != nsp->time_ns_for_children)
40a0d32d
ON
2035 return ERR_PTR(-EINVAL);
2036 }
8382fcac 2037
b3e58382 2038 if (clone_flags & CLONE_PIDFD) {
b3e58382 2039 /*
b3e58382
CB
2040 * - CLONE_DETACHED is blocked so that we can potentially
2041 * reuse it later for CLONE_PIDFD.
2042 * - CLONE_THREAD is blocked until someone really needs it.
2043 */
7f192e3c 2044 if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
b3e58382 2045 return ERR_PTR(-EINVAL);
b3e58382
CB
2046 }
2047
c3ad2c3b
EB
2048 /*
2049 * Force any signals received before this point to be delivered
2050 * before the fork happens. Collect up signals sent to multiple
2051 * processes that happen during the fork and delay them so that
2052 * they appear to happen after the fork.
2053 */
2054 sigemptyset(&delayed.signal);
2055 INIT_HLIST_NODE(&delayed.node);
2056
2057 spin_lock_irq(&current->sighand->siglock);
2058 if (!(clone_flags & CLONE_THREAD))
2059 hlist_add_head(&delayed.node, &current->signal->multiprocess);
2060 recalc_sigpending();
2061 spin_unlock_irq(&current->sighand->siglock);
2062 retval = -ERESTARTNOINTR;
66ae0d1e 2063 if (task_sigpending(current))
c3ad2c3b
EB
2064 goto fork_out;
2065
1da177e4 2066 retval = -ENOMEM;
725fc629 2067 p = dup_task_struct(current, node);
1da177e4
LT
2068 if (!p)
2069 goto fork_out;
b16b3855
JA
2070 if (args->io_thread) {
2071 /*
2072 * Mark us an IO worker, and block any signal that isn't
2073 * fatal or STOP
2074 */
cc440e87 2075 p->flags |= PF_IO_WORKER;
b16b3855
JA
2076 siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2077 }
1da177e4 2078
7f192e3c 2079 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
4d6501dc
VN
2080 /*
2081 * Clear TID on mm_release()?
2082 */
7f192e3c 2083 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
4d6501dc 2084
f7e8b616
SR
2085 ftrace_graph_init_task(p);
2086
bea493a0
PZ
2087 rt_mutex_init_task(p);
2088
a21ee605 2089 lockdep_assert_irqs_enabled();
d12c1a37 2090#ifdef CONFIG_PROVE_LOCKING
de30a2b3
IM
2091 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2092#endif
8f2f9c4d
EB
2093 retval = copy_creds(p, clone_flags);
2094 if (retval < 0)
2095 goto bad_fork_free;
2096
1da177e4 2097 retval = -EAGAIN;
21d1c5e3 2098 if (is_ucounts_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
b57922b6
EP
2099 if (p->real_cred->user != INIT_USER &&
2100 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
8f2f9c4d 2101 goto bad_fork_cleanup_count;
1da177e4 2102 }
72fa5997 2103 current->flags &= ~PF_NPROC_EXCEEDED;
1da177e4 2104
1da177e4
LT
2105 /*
2106 * If multiple threads are within copy_process(), then this check
2107 * triggers too late. This doesn't hurt, the check is only there
2108 * to stop root fork bombs.
2109 */
04ec93fe 2110 retval = -EAGAIN;
c17d1a3a 2111 if (data_race(nr_threads >= max_threads))
1da177e4
LT
2112 goto bad_fork_cleanup_count;
2113
ca74e92b 2114 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
a8ea6fc9 2115 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
514ddb44 2116 p->flags |= PF_FORKNOEXEC;
1da177e4
LT
2117 INIT_LIST_HEAD(&p->children);
2118 INIT_LIST_HEAD(&p->sibling);
f41d911f 2119 rcu_copy_process(p);
1da177e4
LT
2120 p->vfork_done = NULL;
2121 spin_lock_init(&p->alloc_lock);
1da177e4 2122
1da177e4
LT
2123 init_sigpending(&p->pending);
2124
64861634 2125 p->utime = p->stime = p->gtime = 0;
40565b5a 2126#ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
64861634 2127 p->utimescaled = p->stimescaled = 0;
40565b5a 2128#endif
9d7fb042
PZ
2129 prev_cputime_init(&p->prev_cputime);
2130
6a61671b 2131#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
bac5b6b6
FW
2132 seqcount_init(&p->vtime.seqcount);
2133 p->vtime.starttime = 0;
2134 p->vtime.state = VTIME_INACTIVE;
6a61671b
FW
2135#endif
2136
0f212204
JA
2137#ifdef CONFIG_IO_URING
2138 p->io_uring = NULL;
2139#endif
2140
a3a2e76c
KH
2141#if defined(SPLIT_RSS_COUNTING)
2142 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2143#endif
172ba844 2144
6976675d
AV
2145 p->default_timer_slack_ns = current->timer_slack_ns;
2146
eb414681
JW
2147#ifdef CONFIG_PSI
2148 p->psi_flags = 0;
2149#endif
2150
5995477a 2151 task_io_accounting_init(&p->ioac);
1da177e4
LT
2152 acct_clear_integrals(p);
2153
3a245c0f 2154 posix_cputimers_init(&p->posix_cputimers);
1da177e4 2155
1da177e4 2156 p->io_context = NULL;
c0b0ae8a 2157 audit_set_context(p, NULL);
b4f48b63 2158 cgroup_fork(p);
40966e31
EB
2159 if (p->flags & PF_KTHREAD) {
2160 if (!set_kthread_struct(p))
ff8288ff 2161 goto bad_fork_cleanup_delayacct;
40966e31 2162 }
1da177e4 2163#ifdef CONFIG_NUMA
846a16bf 2164 p->mempolicy = mpol_dup(p->mempolicy);
fb0a685c
DRO
2165 if (IS_ERR(p->mempolicy)) {
2166 retval = PTR_ERR(p->mempolicy);
2167 p->mempolicy = NULL;
ff8288ff 2168 goto bad_fork_cleanup_delayacct;
fb0a685c 2169 }
1da177e4 2170#endif
778d3b0f
MH
2171#ifdef CONFIG_CPUSETS
2172 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2173 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
b7505861 2174 seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
778d3b0f 2175#endif
de30a2b3 2176#ifdef CONFIG_TRACE_IRQFLAGS
0584df9c
ME
2177 memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2178 p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2179 p->irqtrace.softirq_enable_ip = _THIS_IP_;
2180 p->softirqs_enabled = 1;
2181 p->softirq_context = 0;
de30a2b3 2182#endif
8bcbde54
DH
2183
2184 p->pagefault_disabled = 0;
2185
fbb9ce95 2186#ifdef CONFIG_LOCKDEP
b09be676 2187 lockdep_init_task(p);
fbb9ce95 2188#endif
1da177e4 2189
408894ee
IM
2190#ifdef CONFIG_DEBUG_MUTEXES
2191 p->blocked_on = NULL; /* not blocked yet */
2192#endif
cafe5635
KO
2193#ifdef CONFIG_BCACHE
2194 p->sequential_io = 0;
2195 p->sequential_io_avg = 0;
2196#endif
a10787e6
SL
2197#ifdef CONFIG_BPF_SYSCALL
2198 RCU_INIT_POINTER(p->bpf_storage, NULL);
c7603cfa 2199 p->bpf_ctx = NULL;
a10787e6 2200#endif
0f481406 2201
3c90e6e9 2202 /* Perform scheduler related setup. Assign this task to a CPU. */
aab03e05
DF
2203 retval = sched_fork(clone_flags, p);
2204 if (retval)
2205 goto bad_fork_cleanup_policy;
6ab423e0 2206
2b26f0aa 2207 retval = perf_event_init_task(p, clone_flags);
6ab423e0
PZ
2208 if (retval)
2209 goto bad_fork_cleanup_policy;
fb0a685c
DRO
2210 retval = audit_alloc(p);
2211 if (retval)
6c72e350 2212 goto bad_fork_cleanup_perf;
1da177e4 2213 /* copy all the process information */
ab602f79 2214 shm_init_task(p);
e4e55b47 2215 retval = security_task_alloc(p, clone_flags);
fb0a685c 2216 if (retval)
1da177e4 2217 goto bad_fork_cleanup_audit;
e4e55b47
TH
2218 retval = copy_semundo(clone_flags, p);
2219 if (retval)
2220 goto bad_fork_cleanup_security;
fb0a685c
DRO
2221 retval = copy_files(clone_flags, p);
2222 if (retval)
1da177e4 2223 goto bad_fork_cleanup_semundo;
fb0a685c
DRO
2224 retval = copy_fs(clone_flags, p);
2225 if (retval)
1da177e4 2226 goto bad_fork_cleanup_files;
fb0a685c
DRO
2227 retval = copy_sighand(clone_flags, p);
2228 if (retval)
1da177e4 2229 goto bad_fork_cleanup_fs;
fb0a685c
DRO
2230 retval = copy_signal(clone_flags, p);
2231 if (retval)
1da177e4 2232 goto bad_fork_cleanup_sighand;
fb0a685c
DRO
2233 retval = copy_mm(clone_flags, p);
2234 if (retval)
1da177e4 2235 goto bad_fork_cleanup_signal;
fb0a685c
DRO
2236 retval = copy_namespaces(clone_flags, p);
2237 if (retval)
d84f4f99 2238 goto bad_fork_cleanup_mm;
fb0a685c
DRO
2239 retval = copy_io(clone_flags, p);
2240 if (retval)
fd0928df 2241 goto bad_fork_cleanup_namespaces;
714acdbd 2242 retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
1da177e4 2243 if (retval)
fd0928df 2244 goto bad_fork_cleanup_io;
1da177e4 2245
afaef01c
AP
2246 stackleak_task_init(p);
2247
425fb2b4 2248 if (pid != &init_struct_pid) {
49cb2fc4
AR
2249 pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2250 args->set_tid_size);
35f71bc0
MH
2251 if (IS_ERR(pid)) {
2252 retval = PTR_ERR(pid);
0740aa5f 2253 goto bad_fork_cleanup_thread;
35f71bc0 2254 }
425fb2b4
PE
2255 }
2256
b3e58382
CB
2257 /*
2258 * This has to happen after we've potentially unshared the file
2259 * descriptor table (so that the pidfd doesn't leak into the child
2260 * if the fd table isn't shared).
2261 */
2262 if (clone_flags & CLONE_PIDFD) {
6fd2fe49 2263 retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
b3e58382
CB
2264 if (retval < 0)
2265 goto bad_fork_free_pid;
2266
2267 pidfd = retval;
6fd2fe49
AV
2268
2269 pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2270 O_RDWR | O_CLOEXEC);
2271 if (IS_ERR(pidfile)) {
2272 put_unused_fd(pidfd);
28dd29c0 2273 retval = PTR_ERR(pidfile);
6fd2fe49
AV
2274 goto bad_fork_free_pid;
2275 }
2276 get_pid(pid); /* held by pidfile now */
2277
7f192e3c 2278 retval = put_user(pidfd, args->pidfd);
b3e58382
CB
2279 if (retval)
2280 goto bad_fork_put_pidfd;
2281 }
2282
73c10101
JA
2283#ifdef CONFIG_BLOCK
2284 p->plug = NULL;
2285#endif
ba31c1a4
TG
2286 futex_init_task(p);
2287
f9a3879a
GM
2288 /*
2289 * sigaltstack should be cleared when sharing the same VM
2290 */
2291 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2a742138 2292 sas_ss_reset(p);
f9a3879a 2293
1da177e4 2294 /*
6580807d
ON
2295 * Syscall tracing and stepping should be turned off in the
2296 * child regardless of CLONE_PTRACE.
1da177e4 2297 */
6580807d 2298 user_disable_single_step(p);
64c19ba2 2299 clear_task_syscall_work(p, SYSCALL_TRACE);
64eb35f7
GKB
2300#if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2301 clear_task_syscall_work(p, SYSCALL_EMU);
ed75e8d5 2302#endif
e02c9b0d 2303 clear_tsk_latency_tracing(p);
1da177e4 2304
1da177e4 2305 /* ok, now we should be set up.. */
18c830df
ON
2306 p->pid = pid_nr(pid);
2307 if (clone_flags & CLONE_THREAD) {
18c830df
ON
2308 p->group_leader = current->group_leader;
2309 p->tgid = current->tgid;
2310 } else {
18c830df
ON
2311 p->group_leader = p;
2312 p->tgid = p->pid;
2313 }
5f8aadd8 2314
9d823e8f
WF
2315 p->nr_dirtied = 0;
2316 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
83712358 2317 p->dirty_paused_when = 0;
9d823e8f 2318
bb8cbbfe 2319 p->pdeath_signal = 0;
47e65328 2320 INIT_LIST_HEAD(&p->thread_group);
158e1645 2321 p->task_works = NULL;
ca7752ca 2322 clear_posix_cputimers_work(p);
1da177e4 2323
d741bf41
PZ
2324#ifdef CONFIG_KRETPROBES
2325 p->kretprobe_instances.first = NULL;
2326#endif
54ecbe6f
MH
2327#ifdef CONFIG_RETHOOK
2328 p->rethooks.first = NULL;
2329#endif
d741bf41 2330
7e47682e
AS
2331 /*
2332 * Ensure that the cgroup subsystem policies allow the new process to be
7b7b8a2c 2333 * forked. It should be noted that the new process's css_set can be changed
7e47682e
AS
2334 * between here and cgroup_post_fork() if an organisation operation is in
2335 * progress.
2336 */
ef2c41cf 2337 retval = cgroup_can_fork(p, args);
7e47682e 2338 if (retval)
5a5cf5cb 2339 goto bad_fork_put_pidfd;
7e47682e 2340
b1e82065
PZ
2341 /*
2342 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2343 * the new task on the correct runqueue. All this *before* the task
2344 * becomes visible.
2345 *
2346 * This isn't part of ->can_fork() because while the re-cloning is
2347 * cgroup specific, it unconditionally needs to place the task on a
2348 * runqueue.
2349 */
2350 sched_cgroup_fork(p, args);
2351
7b558513
DH
2352 /*
2353 * From this point on we must avoid any synchronous user-space
2354 * communication until we take the tasklist-lock. In particular, we do
2355 * not want user-space to be able to predict the process start-time by
2356 * stalling fork(2) after we recorded the start_time but before it is
2357 * visible to the system.
2358 */
2359
2360 p->start_time = ktime_get_ns();
cf25e24d 2361 p->start_boottime = ktime_get_boottime_ns();
7b558513 2362
18c830df
ON
2363 /*
2364 * Make it visible to the rest of the system, but dont wake it up yet.
2365 * Need tasklist lock for parent etc handling!
2366 */
1da177e4
LT
2367 write_lock_irq(&tasklist_lock);
2368
1da177e4 2369 /* CLONE_PARENT re-uses the old parent */
2d5516cb 2370 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
1da177e4 2371 p->real_parent = current->real_parent;
2d5516cb 2372 p->parent_exec_id = current->parent_exec_id;
b4e00444
EW
2373 if (clone_flags & CLONE_THREAD)
2374 p->exit_signal = -1;
2375 else
2376 p->exit_signal = current->group_leader->exit_signal;
2d5516cb 2377 } else {
1da177e4 2378 p->real_parent = current;
2d5516cb 2379 p->parent_exec_id = current->self_exec_id;
b4e00444 2380 p->exit_signal = args->exit_signal;
2d5516cb 2381 }
1da177e4 2382
d83a7cb3
JP
2383 klp_copy_process(p);
2384
85dd3f61
PZ
2385 sched_core_fork(p);
2386
3f17da69 2387 spin_lock(&current->sighand->siglock);
4a2c7a78 2388
dbd95212
KC
2389 /*
2390 * Copy seccomp details explicitly here, in case they were changed
2391 * before holding sighand lock.
2392 */
2393 copy_seccomp(p);
2394
d7822b1e
MD
2395 rseq_fork(p, clone_flags);
2396
4ca1d3ee 2397 /* Don't start children in a dying pid namespace */
e8cfbc24 2398 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
3fd37226
KT
2399 retval = -ENOMEM;
2400 goto bad_fork_cancel_cgroup;
2401 }
4a2c7a78 2402
7673bf55
EB
2403 /* Let kill terminate clone/fork in the middle */
2404 if (fatal_signal_pending(current)) {
2405 retval = -EINTR;
2406 goto bad_fork_cancel_cgroup;
2407 }
2408
2c470475 2409 init_task_pid_links(p);
73b9ebfe 2410 if (likely(p->pid)) {
4b9d33e6 2411 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
73b9ebfe 2412
81907739 2413 init_task_pid(p, PIDTYPE_PID, pid);
73b9ebfe 2414 if (thread_group_leader(p)) {
6883f81a 2415 init_task_pid(p, PIDTYPE_TGID, pid);
81907739
ON
2416 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2417 init_task_pid(p, PIDTYPE_SID, task_session(current));
2418
1c4042c2 2419 if (is_child_reaper(pid)) {
17cf22c3 2420 ns_of_pid(pid)->child_reaper = p;
1c4042c2
EB
2421 p->signal->flags |= SIGNAL_UNKILLABLE;
2422 }
c3ad2c3b 2423 p->signal->shared_pending.signal = delayed.signal;
9c9f4ded 2424 p->signal->tty = tty_kref_get(current->signal->tty);
749860ce
PT
2425 /*
2426 * Inherit has_child_subreaper flag under the same
2427 * tasklist_lock with adding child to the process tree
2428 * for propagate_has_child_subreaper optimization.
2429 */
2430 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2431 p->real_parent->signal->is_child_subreaper;
9cd80bbb 2432 list_add_tail(&p->sibling, &p->real_parent->children);
5e85d4ab 2433 list_add_tail_rcu(&p->tasks, &init_task.tasks);
6883f81a 2434 attach_pid(p, PIDTYPE_TGID);
81907739
ON
2435 attach_pid(p, PIDTYPE_PGID);
2436 attach_pid(p, PIDTYPE_SID);
909ea964 2437 __this_cpu_inc(process_counts);
80628ca0
ON
2438 } else {
2439 current->signal->nr_threads++;
2440 atomic_inc(&current->signal->live);
60d4de3f 2441 refcount_inc(&current->signal->sigcnt);
924de3b8 2442 task_join_group_stop(p);
80628ca0
ON
2443 list_add_tail_rcu(&p->thread_group,
2444 &p->group_leader->thread_group);
0c740d0a
ON
2445 list_add_tail_rcu(&p->thread_node,
2446 &p->signal->thread_head);
73b9ebfe 2447 }
81907739 2448 attach_pid(p, PIDTYPE_PID);
73b9ebfe 2449 nr_threads++;
1da177e4 2450 }
1da177e4 2451 total_forks++;
c3ad2c3b 2452 hlist_del_init(&delayed.node);
3f17da69 2453 spin_unlock(&current->sighand->siglock);
4af4206b 2454 syscall_tracepoint_update(p);
1da177e4 2455 write_unlock_irq(&tasklist_lock);
4af4206b 2456
ddc204b5
WL
2457 if (pidfile)
2458 fd_install(pidfd, pidfile);
2459
c13cf856 2460 proc_fork_connector(p);
b1e82065 2461 sched_post_fork(p);
ef2c41cf 2462 cgroup_post_fork(p, args);
cdd6c482 2463 perf_event_fork(p);
43d2b113
KH
2464
2465 trace_task_newtask(p, clone_flags);
3ab67966 2466 uprobe_copy_process(p, clone_flags);
43d2b113 2467
67197a4f
SB
2468 copy_oom_score_adj(clone_flags, p);
2469
1da177e4
LT
2470 return p;
2471
7e47682e 2472bad_fork_cancel_cgroup:
85dd3f61 2473 sched_core_free(p);
3fd37226
KT
2474 spin_unlock(&current->sighand->siglock);
2475 write_unlock_irq(&tasklist_lock);
ef2c41cf 2476 cgroup_cancel_fork(p, args);
b3e58382 2477bad_fork_put_pidfd:
6fd2fe49
AV
2478 if (clone_flags & CLONE_PIDFD) {
2479 fput(pidfile);
2480 put_unused_fd(pidfd);
2481 }
425fb2b4
PE
2482bad_fork_free_pid:
2483 if (pid != &init_struct_pid)
2484 free_pid(pid);
0740aa5f
JS
2485bad_fork_cleanup_thread:
2486 exit_thread(p);
fd0928df 2487bad_fork_cleanup_io:
b69f2292
LR
2488 if (p->io_context)
2489 exit_io_context(p);
ab516013 2490bad_fork_cleanup_namespaces:
444f378b 2491 exit_task_namespaces(p);
1da177e4 2492bad_fork_cleanup_mm:
c3f3ce04
AA
2493 if (p->mm) {
2494 mm_clear_owner(p->mm, p);
1da177e4 2495 mmput(p->mm);
c3f3ce04 2496 }
1da177e4 2497bad_fork_cleanup_signal:
4ab6c083 2498 if (!(clone_flags & CLONE_THREAD))
1c5354de 2499 free_signal_struct(p->signal);
1da177e4 2500bad_fork_cleanup_sighand:
a7e5328a 2501 __cleanup_sighand(p->sighand);
1da177e4
LT
2502bad_fork_cleanup_fs:
2503 exit_fs(p); /* blocking */
2504bad_fork_cleanup_files:
2505 exit_files(p); /* blocking */
2506bad_fork_cleanup_semundo:
2507 exit_sem(p);
e4e55b47
TH
2508bad_fork_cleanup_security:
2509 security_task_free(p);
1da177e4
LT
2510bad_fork_cleanup_audit:
2511 audit_free(p);
6c72e350 2512bad_fork_cleanup_perf:
cdd6c482 2513 perf_event_free_task(p);
6c72e350 2514bad_fork_cleanup_policy:
b09be676 2515 lockdep_free_task(p);
1da177e4 2516#ifdef CONFIG_NUMA
f0be3d32 2517 mpol_put(p->mempolicy);
1da177e4 2518#endif
ff8288ff 2519bad_fork_cleanup_delayacct:
35df17c5 2520 delayacct_tsk_free(p);
1da177e4 2521bad_fork_cleanup_count:
21d1c5e3 2522 dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
e0e81739 2523 exit_creds(p);
1da177e4 2524bad_fork_free:
2f064a59 2525 WRITE_ONCE(p->__state, TASK_DEAD);
1a03d3f1 2526 exit_task_stack_account(p);
68f24b08 2527 put_task_stack(p);
c3f3ce04 2528 delayed_free_task(p);
fe7d37d1 2529fork_out:
c3ad2c3b
EB
2530 spin_lock_irq(&current->sighand->siglock);
2531 hlist_del_init(&delayed.node);
2532 spin_unlock_irq(&current->sighand->siglock);
fe7d37d1 2533 return ERR_PTR(retval);
1da177e4
LT
2534}
2535
2c470475 2536static inline void init_idle_pids(struct task_struct *idle)
f106eee1
ON
2537{
2538 enum pid_type type;
2539
2540 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2c470475
EB
2541 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2542 init_task_pid(idle, type, &init_struct_pid);
f106eee1
ON
2543 }
2544}
2545
f1a0a376 2546struct task_struct * __init fork_idle(int cpu)
1da177e4 2547{
36c8b586 2548 struct task_struct *task;
7f192e3c
CB
2549 struct kernel_clone_args args = {
2550 .flags = CLONE_VM,
2551 };
2552
2553 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
f106eee1 2554 if (!IS_ERR(task)) {
2c470475 2555 init_idle_pids(task);
753ca4f3 2556 init_idle(task, cpu);
f106eee1 2557 }
73b9ebfe 2558
1da177e4
LT
2559 return task;
2560}
2561
13585fa0
NA
2562struct mm_struct *copy_init_mm(void)
2563{
2564 return dup_mm(NULL, &init_mm);
2565}
2566
cc440e87
JA
2567/*
2568 * This is like kernel_clone(), but shaved down and tailored to just
2569 * creating io_uring workers. It returns a created task, or an error pointer.
2570 * The returned task is inactive, and the caller must fire it up through
2571 * wake_up_new_task(p). All signals are blocked in the created task.
2572 */
2573struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2574{
2575 unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2576 CLONE_IO;
2577 struct kernel_clone_args args = {
2578 .flags = ((lower_32_bits(flags) | CLONE_VM |
2579 CLONE_UNTRACED) & ~CSIGNAL),
2580 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2581 .stack = (unsigned long)fn,
2582 .stack_size = (unsigned long)arg,
2583 .io_thread = 1,
2584 };
cc440e87 2585
b16b3855 2586 return copy_process(NULL, 0, node, &args);
cc440e87
JA
2587}
2588
1da177e4
LT
2589/*
2590 * Ok, this is the main fork-routine.
2591 *
2592 * It copies the process, and if successful kick-starts
2593 * it and waits for it to finish using the VM if required.
a0eb9abd
ES
2594 *
2595 * args->exit_signal is expected to be checked for sanity by the caller.
1da177e4 2596 */
cad6967a 2597pid_t kernel_clone(struct kernel_clone_args *args)
1da177e4 2598{
7f192e3c 2599 u64 clone_flags = args->flags;
9f5325aa
MPS
2600 struct completion vfork;
2601 struct pid *pid;
1da177e4
LT
2602 struct task_struct *p;
2603 int trace = 0;
cad6967a 2604 pid_t nr;
1da177e4 2605
3af8588c
CB
2606 /*
2607 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2608 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2609 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2610 * field in struct clone_args and it still doesn't make sense to have
2611 * them both point at the same memory location. Performing this check
2612 * here has the advantage that we don't need to have a separate helper
2613 * to check for legacy clone().
2614 */
2615 if ((args->flags & CLONE_PIDFD) &&
2616 (args->flags & CLONE_PARENT_SETTID) &&
2617 (args->pidfd == args->parent_tid))
2618 return -EINVAL;
2619
09a05394 2620 /*
4b9d33e6
TH
2621 * Determine whether and which event to report to ptracer. When
2622 * called from kernel_thread or CLONE_UNTRACED is explicitly
2623 * requested, no event is reported; otherwise, report if the event
2624 * for the type of forking is enabled.
09a05394 2625 */
e80d6661 2626 if (!(clone_flags & CLONE_UNTRACED)) {
4b9d33e6
TH
2627 if (clone_flags & CLONE_VFORK)
2628 trace = PTRACE_EVENT_VFORK;
7f192e3c 2629 else if (args->exit_signal != SIGCHLD)
4b9d33e6
TH
2630 trace = PTRACE_EVENT_CLONE;
2631 else
2632 trace = PTRACE_EVENT_FORK;
2633
2634 if (likely(!ptrace_event_enabled(current, trace)))
2635 trace = 0;
2636 }
1da177e4 2637
7f192e3c 2638 p = copy_process(NULL, trace, NUMA_NO_NODE, args);
38addce8 2639 add_latent_entropy();
9f5325aa
MPS
2640
2641 if (IS_ERR(p))
2642 return PTR_ERR(p);
2643
1da177e4
LT
2644 /*
2645 * Do this prior waking up the new thread - the thread pointer
2646 * might get invalid after that point, if the thread exits quickly.
2647 */
9f5325aa 2648 trace_sched_process_fork(current, p);
0a16b607 2649
9f5325aa
MPS
2650 pid = get_task_pid(p, PIDTYPE_PID);
2651 nr = pid_vnr(pid);
30e49c26 2652
9f5325aa 2653 if (clone_flags & CLONE_PARENT_SETTID)
7f192e3c 2654 put_user(nr, args->parent_tid);
a6f5e063 2655
9f5325aa
MPS
2656 if (clone_flags & CLONE_VFORK) {
2657 p->vfork_done = &vfork;
2658 init_completion(&vfork);
2659 get_task_struct(p);
2660 }
1da177e4 2661
9f5325aa 2662 wake_up_new_task(p);
09a05394 2663
9f5325aa
MPS
2664 /* forking complete and child started to run, tell ptracer */
2665 if (unlikely(trace))
2666 ptrace_event_pid(trace, pid);
4e52365f 2667
9f5325aa
MPS
2668 if (clone_flags & CLONE_VFORK) {
2669 if (!wait_for_vfork_done(p, &vfork))
2670 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
1da177e4 2671 }
9f5325aa
MPS
2672
2673 put_pid(pid);
92476d7f 2674 return nr;
1da177e4
LT
2675}
2676
2aa3a7f8
AV
2677/*
2678 * Create a kernel thread.
2679 */
2680pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2681{
7f192e3c 2682 struct kernel_clone_args args = {
3f2c788a
CB
2683 .flags = ((lower_32_bits(flags) | CLONE_VM |
2684 CLONE_UNTRACED) & ~CSIGNAL),
2685 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
7f192e3c
CB
2686 .stack = (unsigned long)fn,
2687 .stack_size = (unsigned long)arg,
2688 };
2689
cad6967a 2690 return kernel_clone(&args);
2aa3a7f8 2691}
2aa3a7f8 2692
d2125043
AV
2693#ifdef __ARCH_WANT_SYS_FORK
2694SYSCALL_DEFINE0(fork)
2695{
2696#ifdef CONFIG_MMU
7f192e3c
CB
2697 struct kernel_clone_args args = {
2698 .exit_signal = SIGCHLD,
2699 };
2700
cad6967a 2701 return kernel_clone(&args);
d2125043
AV
2702#else
2703 /* can not support in nommu mode */
5d59e182 2704 return -EINVAL;
d2125043
AV
2705#endif
2706}
2707#endif
2708
2709#ifdef __ARCH_WANT_SYS_VFORK
2710SYSCALL_DEFINE0(vfork)
2711{
7f192e3c
CB
2712 struct kernel_clone_args args = {
2713 .flags = CLONE_VFORK | CLONE_VM,
2714 .exit_signal = SIGCHLD,
2715 };
2716
cad6967a 2717 return kernel_clone(&args);
d2125043
AV
2718}
2719#endif
2720
2721#ifdef __ARCH_WANT_SYS_CLONE
2722#ifdef CONFIG_CLONE_BACKWARDS
2723SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2724 int __user *, parent_tidptr,
3033f14a 2725 unsigned long, tls,
d2125043
AV
2726 int __user *, child_tidptr)
2727#elif defined(CONFIG_CLONE_BACKWARDS2)
2728SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2729 int __user *, parent_tidptr,
2730 int __user *, child_tidptr,
3033f14a 2731 unsigned long, tls)
dfa9771a
MS
2732#elif defined(CONFIG_CLONE_BACKWARDS3)
2733SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2734 int, stack_size,
2735 int __user *, parent_tidptr,
2736 int __user *, child_tidptr,
3033f14a 2737 unsigned long, tls)
d2125043
AV
2738#else
2739SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2740 int __user *, parent_tidptr,
2741 int __user *, child_tidptr,
3033f14a 2742 unsigned long, tls)
d2125043
AV
2743#endif
2744{
7f192e3c 2745 struct kernel_clone_args args = {
3f2c788a 2746 .flags = (lower_32_bits(clone_flags) & ~CSIGNAL),
7f192e3c
CB
2747 .pidfd = parent_tidptr,
2748 .child_tid = child_tidptr,
2749 .parent_tid = parent_tidptr,
3f2c788a 2750 .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL),
7f192e3c
CB
2751 .stack = newsp,
2752 .tls = tls,
2753 };
2754
cad6967a 2755 return kernel_clone(&args);
7f192e3c 2756}
d68dbb0c 2757#endif
7f192e3c 2758
d68dbb0c 2759#ifdef __ARCH_WANT_SYS_CLONE3
dd499f7a 2760
7f192e3c
CB
2761noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2762 struct clone_args __user *uargs,
f14c234b 2763 size_t usize)
7f192e3c 2764{
f14c234b 2765 int err;
7f192e3c 2766 struct clone_args args;
49cb2fc4 2767 pid_t *kset_tid = kargs->set_tid;
7f192e3c 2768
a966dcfe
ES
2769 BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2770 CLONE_ARGS_SIZE_VER0);
2771 BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2772 CLONE_ARGS_SIZE_VER1);
2773 BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2774 CLONE_ARGS_SIZE_VER2);
2775 BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2776
f14c234b 2777 if (unlikely(usize > PAGE_SIZE))
7f192e3c 2778 return -E2BIG;
f14c234b 2779 if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
7f192e3c
CB
2780 return -EINVAL;
2781
f14c234b
AS
2782 err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2783 if (err)
2784 return err;
7f192e3c 2785
49cb2fc4
AR
2786 if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
2787 return -EINVAL;
2788
2789 if (unlikely(!args.set_tid && args.set_tid_size > 0))
2790 return -EINVAL;
2791
2792 if (unlikely(args.set_tid && args.set_tid_size == 0))
2793 return -EINVAL;
2794
a0eb9abd
ES
2795 /*
2796 * Verify that higher 32bits of exit_signal are unset and that
2797 * it is a valid signal
2798 */
2799 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2800 !valid_signal(args.exit_signal)))
2801 return -EINVAL;
2802
62173872
ES
2803 if ((args.flags & CLONE_INTO_CGROUP) &&
2804 (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
ef2c41cf
CB
2805 return -EINVAL;
2806
7f192e3c
CB
2807 *kargs = (struct kernel_clone_args){
2808 .flags = args.flags,
2809 .pidfd = u64_to_user_ptr(args.pidfd),
2810 .child_tid = u64_to_user_ptr(args.child_tid),
2811 .parent_tid = u64_to_user_ptr(args.parent_tid),
2812 .exit_signal = args.exit_signal,
2813 .stack = args.stack,
2814 .stack_size = args.stack_size,
2815 .tls = args.tls,
49cb2fc4 2816 .set_tid_size = args.set_tid_size,
ef2c41cf 2817 .cgroup = args.cgroup,
7f192e3c
CB
2818 };
2819
49cb2fc4
AR
2820 if (args.set_tid &&
2821 copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
2822 (kargs->set_tid_size * sizeof(pid_t))))
2823 return -EFAULT;
2824
2825 kargs->set_tid = kset_tid;
2826
7f192e3c
CB
2827 return 0;
2828}
2829
fa729c4d
CB
2830/**
2831 * clone3_stack_valid - check and prepare stack
2832 * @kargs: kernel clone args
2833 *
2834 * Verify that the stack arguments userspace gave us are sane.
2835 * In addition, set the stack direction for userspace since it's easy for us to
2836 * determine.
2837 */
2838static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2839{
2840 if (kargs->stack == 0) {
2841 if (kargs->stack_size > 0)
2842 return false;
2843 } else {
2844 if (kargs->stack_size == 0)
2845 return false;
2846
2847 if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2848 return false;
2849
2850#if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2851 kargs->stack += kargs->stack_size;
2852#endif
2853 }
2854
2855 return true;
2856}
2857
2858static bool clone3_args_valid(struct kernel_clone_args *kargs)
7f192e3c 2859{
b612e5df 2860 /* Verify that no unknown flags are passed along. */
ef2c41cf
CB
2861 if (kargs->flags &
2862 ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
7f192e3c
CB
2863 return false;
2864
2865 /*
a8ca6b13
XC
2866 * - make the CLONE_DETACHED bit reusable for clone3
2867 * - make the CSIGNAL bits reusable for clone3
7f192e3c
CB
2868 */
2869 if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
2870 return false;
2871
b612e5df
CB
2872 if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2873 (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2874 return false;
2875
7f192e3c
CB
2876 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
2877 kargs->exit_signal)
2878 return false;
2879
fa729c4d
CB
2880 if (!clone3_stack_valid(kargs))
2881 return false;
2882
7f192e3c
CB
2883 return true;
2884}
2885
501bd016
CB
2886/**
2887 * clone3 - create a new process with specific properties
2888 * @uargs: argument structure
2889 * @size: size of @uargs
2890 *
2891 * clone3() is the extensible successor to clone()/clone2().
2892 * It takes a struct as argument that is versioned by its size.
2893 *
2894 * Return: On success, a positive PID for the child process.
2895 * On error, a negative errno number.
2896 */
7f192e3c
CB
2897SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
2898{
2899 int err;
2900
2901 struct kernel_clone_args kargs;
49cb2fc4
AR
2902 pid_t set_tid[MAX_PID_NS_LEVEL];
2903
2904 kargs.set_tid = set_tid;
7f192e3c
CB
2905
2906 err = copy_clone_args_from_user(&kargs, uargs, size);
2907 if (err)
2908 return err;
2909
2910 if (!clone3_args_valid(&kargs))
2911 return -EINVAL;
2912
cad6967a 2913 return kernel_clone(&kargs);
d2125043
AV
2914}
2915#endif
2916
0f1b92cb
ON
2917void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2918{
2919 struct task_struct *leader, *parent, *child;
2920 int res;
2921
2922 read_lock(&tasklist_lock);
2923 leader = top = top->group_leader;
2924down:
2925 for_each_thread(leader, parent) {
2926 list_for_each_entry(child, &parent->children, sibling) {
2927 res = visitor(child, data);
2928 if (res) {
2929 if (res < 0)
2930 goto out;
2931 leader = child;
2932 goto down;
2933 }
2934up:
2935 ;
2936 }
2937 }
2938
2939 if (leader != top) {
2940 child = leader;
2941 parent = child->real_parent;
2942 leader = parent->group_leader;
2943 goto up;
2944 }
2945out:
2946 read_unlock(&tasklist_lock);
2947}
2948
5fd63b30
RT
2949#ifndef ARCH_MIN_MMSTRUCT_ALIGN
2950#define ARCH_MIN_MMSTRUCT_ALIGN 0
2951#endif
2952
51cc5068 2953static void sighand_ctor(void *data)
aa1757f9
ON
2954{
2955 struct sighand_struct *sighand = data;
2956
a35afb83 2957 spin_lock_init(&sighand->siglock);
b8fceee1 2958 init_waitqueue_head(&sighand->signalfd_wqh);
aa1757f9
ON
2959}
2960
1da177e4
LT
2961void __init proc_caches_init(void)
2962{
c1a2f7f0
RR
2963 unsigned int mm_size;
2964
1da177e4
LT
2965 sighand_cachep = kmem_cache_create("sighand_cache",
2966 sizeof(struct sighand_struct), 0,
5f0d5a3a 2967 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
75f296d9 2968 SLAB_ACCOUNT, sighand_ctor);
1da177e4
LT
2969 signal_cachep = kmem_cache_create("signal_cache",
2970 sizeof(struct signal_struct), 0,
75f296d9 2971 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056 2972 NULL);
20c2df83 2973 files_cachep = kmem_cache_create("files_cache",
1da177e4 2974 sizeof(struct files_struct), 0,
75f296d9 2975 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056 2976 NULL);
20c2df83 2977 fs_cachep = kmem_cache_create("fs_cache",
1da177e4 2978 sizeof(struct fs_struct), 0,
75f296d9 2979 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056 2980 NULL);
c1a2f7f0 2981
6345d24d 2982 /*
c1a2f7f0
RR
2983 * The mm_cpumask is located at the end of mm_struct, and is
2984 * dynamically sized based on the maximum CPU number this system
2985 * can have, taking hotplug into account (nr_cpu_ids).
6345d24d 2986 */
c1a2f7f0
RR
2987 mm_size = sizeof(struct mm_struct) + cpumask_size();
2988
07dcd7fe 2989 mm_cachep = kmem_cache_create_usercopy("mm_struct",
c1a2f7f0 2990 mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
75f296d9 2991 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
07dcd7fe
DW
2992 offsetof(struct mm_struct, saved_auxv),
2993 sizeof_field(struct mm_struct, saved_auxv),
5d097056
VD
2994 NULL);
2995 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
8feae131 2996 mmap_init();
66577193 2997 nsproxy_cache_init();
1da177e4 2998}
cf2e340f 2999
cf2e340f 3000/*
9bfb23fc 3001 * Check constraints on flags passed to the unshare system call.
cf2e340f 3002 */
9bfb23fc 3003static int check_unshare_flags(unsigned long unshare_flags)
cf2e340f 3004{
9bfb23fc
ON
3005 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
3006 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
50804fe3 3007 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
769071ac
AV
3008 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
3009 CLONE_NEWTIME))
9bfb23fc 3010 return -EINVAL;
cf2e340f 3011 /*
12c641ab
EB
3012 * Not implemented, but pretend it works if there is nothing
3013 * to unshare. Note that unsharing the address space or the
3014 * signal handlers also need to unshare the signal queues (aka
3015 * CLONE_THREAD).
cf2e340f 3016 */
9bfb23fc 3017 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
12c641ab
EB
3018 if (!thread_group_empty(current))
3019 return -EINVAL;
3020 }
3021 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
d036bda7 3022 if (refcount_read(&current->sighand->count) > 1)
12c641ab
EB
3023 return -EINVAL;
3024 }
3025 if (unshare_flags & CLONE_VM) {
3026 if (!current_is_single_threaded())
9bfb23fc
ON
3027 return -EINVAL;
3028 }
cf2e340f
JD
3029
3030 return 0;
3031}
3032
3033/*
99d1419d 3034 * Unshare the filesystem structure if it is being shared
cf2e340f
JD
3035 */
3036static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3037{
3038 struct fs_struct *fs = current->fs;
3039
498052bb
AV
3040 if (!(unshare_flags & CLONE_FS) || !fs)
3041 return 0;
3042
3043 /* don't need lock here; in the worst case we'll do useless copy */
3044 if (fs->users == 1)
3045 return 0;
3046
3047 *new_fsp = copy_fs_struct(fs);
3048 if (!*new_fsp)
3049 return -ENOMEM;
cf2e340f
JD
3050
3051 return 0;
3052}
3053
cf2e340f 3054/*
a016f338 3055 * Unshare file descriptor table if it is being shared
cf2e340f 3056 */
60997c3d
CB
3057int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
3058 struct files_struct **new_fdp)
cf2e340f
JD
3059{
3060 struct files_struct *fd = current->files;
a016f338 3061 int error = 0;
cf2e340f
JD
3062
3063 if ((unshare_flags & CLONE_FILES) &&
a016f338 3064 (fd && atomic_read(&fd->count) > 1)) {
60997c3d 3065 *new_fdp = dup_fd(fd, max_fds, &error);
a016f338
JD
3066 if (!*new_fdp)
3067 return error;
3068 }
cf2e340f
JD
3069
3070 return 0;
3071}
3072
cf2e340f
JD
3073/*
3074 * unshare allows a process to 'unshare' part of the process
3075 * context which was originally shared using clone. copy_*
cad6967a 3076 * functions used by kernel_clone() cannot be used here directly
cf2e340f
JD
3077 * because they modify an inactive task_struct that is being
3078 * constructed. Here we are modifying the current, active,
3079 * task_struct.
3080 */
9b32105e 3081int ksys_unshare(unsigned long unshare_flags)
cf2e340f 3082{
cf2e340f 3083 struct fs_struct *fs, *new_fs = NULL;
ba1f70dd 3084 struct files_struct *new_fd = NULL;
b2e0d987 3085 struct cred *new_cred = NULL;
cf7b708c 3086 struct nsproxy *new_nsproxy = NULL;
9edff4ab 3087 int do_sysvsem = 0;
9bfb23fc 3088 int err;
cf2e340f 3089
b2e0d987 3090 /*
faf00da5
EB
3091 * If unsharing a user namespace must also unshare the thread group
3092 * and unshare the filesystem root and working directories.
b2e0d987
EB
3093 */
3094 if (unshare_flags & CLONE_NEWUSER)
e66eded8 3095 unshare_flags |= CLONE_THREAD | CLONE_FS;
50804fe3
EB
3096 /*
3097 * If unsharing vm, must also unshare signal handlers.
3098 */
3099 if (unshare_flags & CLONE_VM)
3100 unshare_flags |= CLONE_SIGHAND;
12c641ab
EB
3101 /*
3102 * If unsharing a signal handlers, must also unshare the signal queues.
3103 */
3104 if (unshare_flags & CLONE_SIGHAND)
3105 unshare_flags |= CLONE_THREAD;
9bfb23fc
ON
3106 /*
3107 * If unsharing namespace, must also unshare filesystem information.
3108 */
3109 if (unshare_flags & CLONE_NEWNS)
3110 unshare_flags |= CLONE_FS;
50804fe3
EB
3111
3112 err = check_unshare_flags(unshare_flags);
3113 if (err)
3114 goto bad_unshare_out;
6013f67f
MS
3115 /*
3116 * CLONE_NEWIPC must also detach from the undolist: after switching
3117 * to a new ipc namespace, the semaphore arrays from the old
3118 * namespace are unreachable.
3119 */
3120 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
9edff4ab 3121 do_sysvsem = 1;
fb0a685c
DRO
3122 err = unshare_fs(unshare_flags, &new_fs);
3123 if (err)
9bfb23fc 3124 goto bad_unshare_out;
60997c3d 3125 err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
fb0a685c 3126 if (err)
9bfb23fc 3127 goto bad_unshare_cleanup_fs;
b2e0d987 3128 err = unshare_userns(unshare_flags, &new_cred);
fb0a685c 3129 if (err)
9edff4ab 3130 goto bad_unshare_cleanup_fd;
b2e0d987
EB
3131 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3132 new_cred, new_fs);
3133 if (err)
3134 goto bad_unshare_cleanup_cred;
c0b2fc31 3135
905ae01c
AG
3136 if (new_cred) {
3137 err = set_cred_ucounts(new_cred);
3138 if (err)
3139 goto bad_unshare_cleanup_cred;
3140 }
3141
b2e0d987 3142 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
9edff4ab
MS
3143 if (do_sysvsem) {
3144 /*
3145 * CLONE_SYSVSEM is equivalent to sys_exit().
3146 */
3147 exit_sem(current);
3148 }
ab602f79
JM
3149 if (unshare_flags & CLONE_NEWIPC) {
3150 /* Orphan segments in old ns (see sem above). */
3151 exit_shm(current);
3152 shm_init_task(current);
3153 }
ab516013 3154
6f977e6b 3155 if (new_nsproxy)
cf7b708c 3156 switch_task_namespaces(current, new_nsproxy);
cf2e340f 3157
cf7b708c
PE
3158 task_lock(current);
3159
cf2e340f
JD
3160 if (new_fs) {
3161 fs = current->fs;
2a4419b5 3162 spin_lock(&fs->lock);
cf2e340f 3163 current->fs = new_fs;
498052bb
AV
3164 if (--fs->users)
3165 new_fs = NULL;
3166 else
3167 new_fs = fs;
2a4419b5 3168 spin_unlock(&fs->lock);
cf2e340f
JD
3169 }
3170
ba1f70dd
RX
3171 if (new_fd)
3172 swap(current->files, new_fd);
cf2e340f
JD
3173
3174 task_unlock(current);
b2e0d987
EB
3175
3176 if (new_cred) {
3177 /* Install the new user namespace */
3178 commit_creds(new_cred);
3179 new_cred = NULL;
3180 }
cf2e340f
JD
3181 }
3182
e4222673
HB
3183 perf_event_namespaces(current);
3184
b2e0d987
EB
3185bad_unshare_cleanup_cred:
3186 if (new_cred)
3187 put_cred(new_cred);
cf2e340f
JD
3188bad_unshare_cleanup_fd:
3189 if (new_fd)
3190 put_files_struct(new_fd);
3191
cf2e340f
JD
3192bad_unshare_cleanup_fs:
3193 if (new_fs)
498052bb 3194 free_fs_struct(new_fs);
cf2e340f 3195
cf2e340f
JD
3196bad_unshare_out:
3197 return err;
3198}
3b125388 3199
9b32105e
DB
3200SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3201{
3202 return ksys_unshare(unshare_flags);
3203}
3204
3b125388
AV
3205/*
3206 * Helper to unshare the files of the current task.
3207 * We don't want to expose copy_files internals to
3208 * the exec layer of the kernel.
3209 */
3210
1f702603 3211int unshare_files(void)
3b125388
AV
3212{
3213 struct task_struct *task = current;
1f702603 3214 struct files_struct *old, *copy = NULL;
3b125388
AV
3215 int error;
3216
60997c3d 3217 error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
1f702603 3218 if (error || !copy)
3b125388 3219 return error;
1f702603
EB
3220
3221 old = task->files;
3b125388
AV
3222 task_lock(task);
3223 task->files = copy;
3224 task_unlock(task);
1f702603 3225 put_files_struct(old);
3b125388
AV
3226 return 0;
3227}
16db3d3f
HS
3228
3229int sysctl_max_threads(struct ctl_table *table, int write,
b0daa2c7 3230 void *buffer, size_t *lenp, loff_t *ppos)
16db3d3f
HS
3231{
3232 struct ctl_table t;
3233 int ret;
3234 int threads = max_threads;
b0f53dbc 3235 int min = 1;
16db3d3f
HS
3236 int max = MAX_THREADS;
3237
3238 t = *table;
3239 t.data = &threads;
3240 t.extra1 = &min;
3241 t.extra2 = &max;
3242
3243 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3244 if (ret || !write)
3245 return ret;
3246
b0f53dbc 3247 max_threads = threads;
16db3d3f
HS
3248
3249 return 0;
3250}