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