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