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