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