]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - kernel/fork.c
futex: Move futex exit handling into futex code
[mirror_ubuntu-bionic-kernel.git] / kernel / fork.c
CommitLineData
1da177e4
LT
1/*
2 * linux/kernel/fork.c
3 *
4 * Copyright (C) 1991, 1992 Linus Torvalds
5 */
6
7/*
8 * 'fork.c' contains the help-routines for the 'fork' system call
9 * (see also entry.S and others).
10 * Fork is rather simple, once you get the hang of it, but the memory
11 * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
12 */
13
1da177e4 14#include <linux/slab.h>
4eb5aaa3 15#include <linux/sched/autogroup.h>
6e84f315 16#include <linux/sched/mm.h>
f7ccbae4 17#include <linux/sched/coredump.h>
8703e8a4 18#include <linux/sched/user.h>
6a3827d7 19#include <linux/sched/numa_balancing.h>
03441a34 20#include <linux/sched/stat.h>
29930025 21#include <linux/sched/task.h>
68db0cf1 22#include <linux/sched/task_stack.h>
32ef5517 23#include <linux/sched/cputime.h>
037741a6 24#include <linux/rtmutex.h>
1da177e4
LT
25#include <linux/init.h>
26#include <linux/unistd.h>
1da177e4
LT
27#include <linux/module.h>
28#include <linux/vmalloc.h>
29#include <linux/completion.h>
1da177e4
LT
30#include <linux/personality.h>
31#include <linux/mempolicy.h>
32#include <linux/sem.h>
33#include <linux/file.h>
9f3acc31 34#include <linux/fdtable.h>
da9cbc87 35#include <linux/iocontext.h>
1da177e4
LT
36#include <linux/key.h>
37#include <linux/binfmts.h>
38#include <linux/mman.h>
cddb8a5c 39#include <linux/mmu_notifier.h>
133ff0ea 40#include <linux/hmm.h>
1da177e4 41#include <linux/fs.h>
615d6e87
DB
42#include <linux/mm.h>
43#include <linux/vmacache.h>
ab516013 44#include <linux/nsproxy.h>
c59ede7b 45#include <linux/capability.h>
1da177e4 46#include <linux/cpu.h>
b4f48b63 47#include <linux/cgroup.h>
1da177e4 48#include <linux/security.h>
a1e78772 49#include <linux/hugetlb.h>
e2cfabdf 50#include <linux/seccomp.h>
1da177e4
LT
51#include <linux/swap.h>
52#include <linux/syscalls.h>
53#include <linux/jiffies.h>
54#include <linux/futex.h>
8141c7f3 55#include <linux/compat.h>
207205a2 56#include <linux/kthread.h>
7c3ab738 57#include <linux/task_io_accounting_ops.h>
ab2af1f5 58#include <linux/rcupdate.h>
1da177e4
LT
59#include <linux/ptrace.h>
60#include <linux/mount.h>
61#include <linux/audit.h>
78fb7466 62#include <linux/memcontrol.h>
f201ae23 63#include <linux/ftrace.h>
5e2bf014 64#include <linux/proc_fs.h>
1da177e4
LT
65#include <linux/profile.h>
66#include <linux/rmap.h>
f8af4da3 67#include <linux/ksm.h>
1da177e4 68#include <linux/acct.h>
893e26e6 69#include <linux/userfaultfd_k.h>
8f0ab514 70#include <linux/tsacct_kern.h>
9f46080c 71#include <linux/cn_proc.h>
ba96a0c8 72#include <linux/freezer.h>
ca74e92b 73#include <linux/delayacct.h>
ad4ecbcb 74#include <linux/taskstats_kern.h>
0a425405 75#include <linux/random.h>
522ed776 76#include <linux/tty.h>
fd0928df 77#include <linux/blkdev.h>
5ad4e53b 78#include <linux/fs_struct.h>
7c9f8861 79#include <linux/magic.h>
cdd6c482 80#include <linux/perf_event.h>
42c4ab41 81#include <linux/posix-timers.h>
8e7cac79 82#include <linux/user-return-notifier.h>
3d5992d2 83#include <linux/oom.h>
ba76149f 84#include <linux/khugepaged.h>
d80e731e 85#include <linux/signalfd.h>
0326f5a9 86#include <linux/uprobes.h>
a27bb332 87#include <linux/aio.h>
52f5684c 88#include <linux/compiler.h>
16db3d3f 89#include <linux/sysctl.h>
5c9a8750 90#include <linux/kcov.h>
d83a7cb3 91#include <linux/livepatch.h>
48ac3c18 92#include <linux/thread_info.h>
1da177e4
LT
93
94#include <asm/pgtable.h>
95#include <asm/pgalloc.h>
7c0f6ba6 96#include <linux/uaccess.h>
1da177e4
LT
97#include <asm/mmu_context.h>
98#include <asm/cacheflush.h>
99#include <asm/tlbflush.h>
100
ad8d75ff
SR
101#include <trace/events/sched.h>
102
43d2b113
KH
103#define CREATE_TRACE_POINTS
104#include <trace/events/task.h>
680f7875
SH
105#ifdef CONFIG_USER_NS
106extern int unprivileged_userns_clone;
107#else
108#define unprivileged_userns_clone 0
109#endif
43d2b113 110
ac1b398d
HS
111/*
112 * Minimum number of threads to boot the kernel
113 */
114#define MIN_THREADS 20
115
116/*
117 * Maximum number of threads
118 */
119#define MAX_THREADS FUTEX_TID_MASK
120
1da177e4
LT
121/*
122 * Protected counters by write_lock_irq(&tasklist_lock)
123 */
124unsigned long total_forks; /* Handle normal Linux uptimes. */
fb0a685c 125int nr_threads; /* The idle threads do not count.. */
1da177e4
LT
126
127int max_threads; /* tunable limit on nr_threads */
128
129DEFINE_PER_CPU(unsigned long, process_counts) = 0;
130
c59923a1 131__cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
db1466b3
PM
132
133#ifdef CONFIG_PROVE_RCU
134int lockdep_tasklist_lock_is_held(void)
135{
136 return lockdep_is_held(&tasklist_lock);
137}
138EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
139#endif /* #ifdef CONFIG_PROVE_RCU */
1da177e4
LT
140
141int nr_processes(void)
142{
143 int cpu;
144 int total = 0;
145
1d510750 146 for_each_possible_cpu(cpu)
1da177e4
LT
147 total += per_cpu(process_counts, cpu);
148
149 return total;
150}
151
f19b9f74
AM
152void __weak arch_release_task_struct(struct task_struct *tsk)
153{
154}
155
f5e10287 156#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
e18b890b 157static struct kmem_cache *task_struct_cachep;
41101809
TG
158
159static inline struct task_struct *alloc_task_struct_node(int node)
160{
161 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
162}
163
41101809
TG
164static inline void free_task_struct(struct task_struct *tsk)
165{
41101809
TG
166 kmem_cache_free(task_struct_cachep, tsk);
167}
1da177e4
LT
168#endif
169
b235beea 170#ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
41101809 171
0d15d74a
TG
172/*
173 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
174 * kmemcache based allocator.
175 */
ba14a194 176# if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
ac496bf4
AL
177
178#ifdef CONFIG_VMAP_STACK
179/*
180 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
181 * flush. Try to minimize the number of calls by caching stacks.
182 */
183#define NR_CACHED_STACKS 2
184static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19659c59
HR
185
186static int free_vm_stack_cache(unsigned int cpu)
187{
188 struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
189 int i;
190
191 for (i = 0; i < NR_CACHED_STACKS; i++) {
192 struct vm_struct *vm_stack = cached_vm_stacks[i];
193
194 if (!vm_stack)
195 continue;
196
197 vfree(vm_stack->addr);
198 cached_vm_stacks[i] = NULL;
199 }
200
201 return 0;
202}
ac496bf4
AL
203#endif
204
ba14a194 205static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
b69c49b7 206{
ba14a194 207#ifdef CONFIG_VMAP_STACK
ac496bf4
AL
208 void *stack;
209 int i;
210
ac496bf4 211 for (i = 0; i < NR_CACHED_STACKS; i++) {
112166f8
CL
212 struct vm_struct *s;
213
214 s = this_cpu_xchg(cached_stacks[i], NULL);
ac496bf4
AL
215
216 if (!s)
217 continue;
ac496bf4 218
ca182551
KK
219 /* Clear stale pointers from reused stack. */
220 memset(s->addr, 0, THREAD_SIZE);
c3169857 221
ac496bf4 222 tsk->stack_vm_area = s;
ac496bf4
AL
223 return s->addr;
224 }
ac496bf4 225
48ac3c18 226 stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
ac496bf4 227 VMALLOC_START, VMALLOC_END,
19809c2d 228 THREADINFO_GFP,
ac496bf4
AL
229 PAGE_KERNEL,
230 0, node, __builtin_return_address(0));
ba14a194
AL
231
232 /*
233 * We can't call find_vm_area() in interrupt context, and
234 * free_thread_stack() can be called in interrupt context,
235 * so cache the vm_struct.
236 */
237 if (stack)
238 tsk->stack_vm_area = find_vm_area(stack);
239 return stack;
240#else
4949148a
VD
241 struct page *page = alloc_pages_node(node, THREADINFO_GFP,
242 THREAD_SIZE_ORDER);
b6a84016
ED
243
244 return page ? page_address(page) : NULL;
ba14a194 245#endif
b69c49b7
FT
246}
247
ba14a194 248static inline void free_thread_stack(struct task_struct *tsk)
b69c49b7 249{
ac496bf4
AL
250#ifdef CONFIG_VMAP_STACK
251 if (task_stack_vm_area(tsk)) {
ac496bf4
AL
252 int i;
253
ac496bf4 254 for (i = 0; i < NR_CACHED_STACKS; i++) {
112166f8
CL
255 if (this_cpu_cmpxchg(cached_stacks[i],
256 NULL, tsk->stack_vm_area) != NULL)
ac496bf4
AL
257 continue;
258
ac496bf4
AL
259 return;
260 }
ac496bf4 261
0f110a9b 262 vfree_atomic(tsk->stack);
ac496bf4
AL
263 return;
264 }
265#endif
266
267 __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
b69c49b7 268}
0d15d74a 269# else
b235beea 270static struct kmem_cache *thread_stack_cache;
0d15d74a 271
9521d399 272static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
0d15d74a
TG
273 int node)
274{
b235beea 275 return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
0d15d74a
TG
276}
277
ba14a194 278static void free_thread_stack(struct task_struct *tsk)
0d15d74a 279{
ba14a194 280 kmem_cache_free(thread_stack_cache, tsk->stack);
0d15d74a
TG
281}
282
b235beea 283void thread_stack_cache_init(void)
0d15d74a 284{
b235beea 285 thread_stack_cache = kmem_cache_create("thread_stack", THREAD_SIZE,
0d15d74a 286 THREAD_SIZE, 0, NULL);
b235beea 287 BUG_ON(thread_stack_cache == NULL);
0d15d74a
TG
288}
289# endif
b69c49b7
FT
290#endif
291
1da177e4 292/* SLAB cache for signal_struct structures (tsk->signal) */
e18b890b 293static struct kmem_cache *signal_cachep;
1da177e4
LT
294
295/* SLAB cache for sighand_struct structures (tsk->sighand) */
e18b890b 296struct kmem_cache *sighand_cachep;
1da177e4
LT
297
298/* SLAB cache for files_struct structures (tsk->files) */
e18b890b 299struct kmem_cache *files_cachep;
1da177e4
LT
300
301/* SLAB cache for fs_struct structures (tsk->fs) */
e18b890b 302struct kmem_cache *fs_cachep;
1da177e4
LT
303
304/* SLAB cache for vm_area_struct structures */
e88c5cf9 305static struct kmem_cache *vm_area_cachep;
1da177e4
LT
306
307/* SLAB cache for mm_struct structures (tsk->mm) */
e18b890b 308static struct kmem_cache *mm_cachep;
1da177e4 309
0d2c7e02 310struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
e88c5cf9 311{
0d2c7e02
LT
312 struct vm_area_struct *vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
313
314 if (vma) {
315 vma->vm_mm = mm;
316 INIT_LIST_HEAD(&vma->anon_vma_chain);
317 }
318 return vma;
e88c5cf9
LT
319}
320
321struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
322{
ee8cad6e
LT
323 struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
324
325 if (new) {
326 *new = *orig;
327 INIT_LIST_HEAD(&new->anon_vma_chain);
328 }
329 return new;
e88c5cf9
LT
330}
331
332void vm_area_free(struct vm_area_struct *vma)
333{
334 kmem_cache_free(vm_area_cachep, vma);
335}
336
ba14a194 337static void account_kernel_stack(struct task_struct *tsk, int account)
c6a7f572 338{
ba14a194
AL
339 void *stack = task_stack_page(tsk);
340 struct vm_struct *vm = task_stack_vm_area(tsk);
341
342 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
343
344 if (vm) {
345 int i;
346
347 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
348
349 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
350 mod_zone_page_state(page_zone(vm->pages[i]),
351 NR_KERNEL_STACK_KB,
352 PAGE_SIZE / 1024 * account);
353 }
354
355 /* All stack pages belong to the same memcg. */
ed52be7b
JW
356 mod_memcg_page_state(vm->pages[0], MEMCG_KERNEL_STACK_KB,
357 account * (THREAD_SIZE / 1024));
ba14a194
AL
358 } else {
359 /*
360 * All stack pages are in the same zone and belong to the
361 * same memcg.
362 */
363 struct page *first_page = virt_to_page(stack);
364
365 mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
366 THREAD_SIZE / 1024 * account);
367
ed52be7b
JW
368 mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
369 account * (THREAD_SIZE / 1024));
ba14a194 370 }
c6a7f572
KM
371}
372
68f24b08 373static void release_task_stack(struct task_struct *tsk)
1da177e4 374{
405c0759
AL
375 if (WARN_ON(tsk->state != TASK_DEAD))
376 return; /* Better to leak the stack than to free prematurely */
377
ba14a194 378 account_kernel_stack(tsk, -1);
ba14a194 379 free_thread_stack(tsk);
68f24b08
AL
380 tsk->stack = NULL;
381#ifdef CONFIG_VMAP_STACK
382 tsk->stack_vm_area = NULL;
383#endif
384}
385
386#ifdef CONFIG_THREAD_INFO_IN_TASK
387void put_task_stack(struct task_struct *tsk)
388{
389 if (atomic_dec_and_test(&tsk->stack_refcount))
390 release_task_stack(tsk);
391}
392#endif
393
394void free_task(struct task_struct *tsk)
395{
396#ifndef CONFIG_THREAD_INFO_IN_TASK
397 /*
398 * The task is finally done with both the stack and thread_info,
399 * so free both.
400 */
401 release_task_stack(tsk);
402#else
403 /*
404 * If the task had a separate stack allocation, it should be gone
405 * by now.
406 */
407 WARN_ON_ONCE(atomic_read(&tsk->stack_refcount) != 0);
408#endif
23f78d4a 409 rt_mutex_debug_task_free(tsk);
fb52607a 410 ftrace_graph_exit_task(tsk);
e2cfabdf 411 put_seccomp_filter(tsk);
f19b9f74 412 arch_release_task_struct(tsk);
1da5c46f
ON
413 if (tsk->flags & PF_KTHREAD)
414 free_kthread_struct(tsk);
1da177e4
LT
415 free_task_struct(tsk);
416}
417EXPORT_SYMBOL(free_task);
418
ea6d290c
ON
419static inline void free_signal_struct(struct signal_struct *sig)
420{
97101eb4 421 taskstats_tgid_free(sig);
1c5354de 422 sched_autogroup_exit(sig);
7283094e
MH
423 /*
424 * __mmdrop is not safe to call from softirq context on x86 due to
425 * pgd_dtor so postpone it to the async context
426 */
26db62f1 427 if (sig->oom_mm)
7283094e 428 mmdrop_async(sig->oom_mm);
ea6d290c
ON
429 kmem_cache_free(signal_cachep, sig);
430}
431
432static inline void put_signal_struct(struct signal_struct *sig)
433{
1c5354de 434 if (atomic_dec_and_test(&sig->sigcnt))
ea6d290c
ON
435 free_signal_struct(sig);
436}
437
158d9ebd 438void __put_task_struct(struct task_struct *tsk)
1da177e4 439{
270f722d 440 WARN_ON(!tsk->exit_state);
1da177e4
LT
441 WARN_ON(atomic_read(&tsk->usage));
442 WARN_ON(tsk == current);
443
2e91fa7f 444 cgroup_free(tsk);
30197fa5 445 task_numa_free(tsk, true);
1a2a4d06 446 security_task_free(tsk);
e0e81739 447 exit_creds(tsk);
35df17c5 448 delayacct_tsk_free(tsk);
ea6d290c 449 put_signal_struct(tsk->signal);
1da177e4
LT
450
451 if (!profile_handoff_task(tsk))
452 free_task(tsk);
453}
77c100c8 454EXPORT_SYMBOL_GPL(__put_task_struct);
1da177e4 455
6c0a9fa6 456void __init __weak arch_task_cache_init(void) { }
61c4628b 457
ff691f6e
HS
458/*
459 * set_max_threads
460 */
16db3d3f 461static void set_max_threads(unsigned int max_threads_suggested)
ff691f6e 462{
ac1b398d 463 u64 threads;
ff691f6e
HS
464
465 /*
ac1b398d
HS
466 * The number of threads shall be limited such that the thread
467 * structures may only consume a small part of the available memory.
ff691f6e 468 */
ac1b398d
HS
469 if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
470 threads = MAX_THREADS;
471 else
472 threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
473 (u64) THREAD_SIZE * 8UL);
474
16db3d3f
HS
475 if (threads > max_threads_suggested)
476 threads = max_threads_suggested;
477
ac1b398d 478 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
ff691f6e
HS
479}
480
5aaeb5c0
IM
481#ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
482/* Initialized by the architecture: */
483int arch_task_struct_size __read_mostly;
484#endif
0c8c0f03 485
ff691f6e 486void __init fork_init(void)
1da177e4 487{
25f9c081 488 int i;
f5e10287 489#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
1da177e4 490#ifndef ARCH_MIN_TASKALIGN
e274795e 491#define ARCH_MIN_TASKALIGN 0
1da177e4 492#endif
95cb64c1 493 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
e274795e 494
1da177e4 495 /* create a slab on which task_structs can be allocated */
5d097056 496 task_struct_cachep = kmem_cache_create("task_struct",
e274795e 497 arch_task_struct_size, align,
75f296d9 498 SLAB_PANIC|SLAB_ACCOUNT, NULL);
1da177e4
LT
499#endif
500
61c4628b
SS
501 /* do the arch specific task caches init */
502 arch_task_cache_init();
503
16db3d3f 504 set_max_threads(MAX_THREADS);
1da177e4
LT
505
506 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
507 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
508 init_task.signal->rlim[RLIMIT_SIGPENDING] =
509 init_task.signal->rlim[RLIMIT_NPROC];
b376c3e1 510
25f9c081
EB
511 for (i = 0; i < UCOUNT_COUNTS; i++) {
512 init_user_ns.ucount_max[i] = max_threads/2;
513 }
19659c59
HR
514
515#ifdef CONFIG_VMAP_STACK
516 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
517 NULL, free_vm_stack_cache);
518#endif
b09be676
BP
519
520 lockdep_init_task(&init_task);
1da177e4
LT
521}
522
52f5684c 523int __weak arch_dup_task_struct(struct task_struct *dst,
61c4628b
SS
524 struct task_struct *src)
525{
526 *dst = *src;
527 return 0;
528}
529
d4311ff1
AT
530void set_task_stack_end_magic(struct task_struct *tsk)
531{
532 unsigned long *stackend;
533
534 stackend = end_of_stack(tsk);
535 *stackend = STACK_END_MAGIC; /* for overflow detection */
536}
537
725fc629 538static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
1da177e4
LT
539{
540 struct task_struct *tsk;
b235beea 541 unsigned long *stack;
ba14a194 542 struct vm_struct *stack_vm_area;
3e26c149 543 int err;
1da177e4 544
725fc629
AK
545 if (node == NUMA_NO_NODE)
546 node = tsk_fork_get_node(orig);
504f52b5 547 tsk = alloc_task_struct_node(node);
1da177e4
LT
548 if (!tsk)
549 return NULL;
550
b235beea
LT
551 stack = alloc_thread_stack_node(tsk, node);
552 if (!stack)
f19b9f74 553 goto free_tsk;
1da177e4 554
ba14a194
AL
555 stack_vm_area = task_stack_vm_area(tsk);
556
fb0a685c 557 err = arch_dup_task_struct(tsk, orig);
ba14a194
AL
558
559 /*
560 * arch_dup_task_struct() clobbers the stack-related fields. Make
561 * sure they're properly initialized before using any stack-related
562 * functions again.
563 */
564 tsk->stack = stack;
565#ifdef CONFIG_VMAP_STACK
566 tsk->stack_vm_area = stack_vm_area;
567#endif
68f24b08
AL
568#ifdef CONFIG_THREAD_INFO_IN_TASK
569 atomic_set(&tsk->stack_refcount, 1);
570#endif
ba14a194 571
164c33c6 572 if (err)
b235beea 573 goto free_stack;
164c33c6 574
dbd95212
KC
575#ifdef CONFIG_SECCOMP
576 /*
577 * We must handle setting up seccomp filters once we're under
578 * the sighand lock in case orig has changed between now and
579 * then. Until then, filter must be NULL to avoid messing up
580 * the usage counts on the error path calling free_task.
581 */
582 tsk->seccomp.filter = NULL;
583#endif
87bec58a
AM
584
585 setup_thread_stack(tsk, orig);
8e7cac79 586 clear_user_return_notifier(tsk);
f26f9aff 587 clear_tsk_need_resched(tsk);
d4311ff1 588 set_task_stack_end_magic(tsk);
1da177e4 589
0a425405 590#ifdef CONFIG_CC_STACKPROTECTOR
7cd815bc 591 tsk->stack_canary = get_random_canary();
0a425405
AV
592#endif
593
fb0a685c
DRO
594 /*
595 * One for us, one for whoever does the "release_task()" (usually
596 * parent)
597 */
598 atomic_set(&tsk->usage, 2);
6c5c9341 599#ifdef CONFIG_BLK_DEV_IO_TRACE
2056a782 600 tsk->btrace_seq = 0;
6c5c9341 601#endif
a0aa7f68 602 tsk->splice_pipe = NULL;
5640f768 603 tsk->task_frag.page = NULL;
093e5840 604 tsk->wake_q.next = NULL;
c6a7f572 605
ba14a194 606 account_kernel_stack(tsk, 1);
c6a7f572 607
5c9a8750
DV
608 kcov_task_init(tsk);
609
e41d5818
DV
610#ifdef CONFIG_FAULT_INJECTION
611 tsk->fail_nth = 0;
612#endif
613
1da177e4 614 return tsk;
61c4628b 615
b235beea 616free_stack:
ba14a194 617 free_thread_stack(tsk);
f19b9f74 618free_tsk:
61c4628b
SS
619 free_task_struct(tsk);
620 return NULL;
1da177e4
LT
621}
622
623#ifdef CONFIG_MMU
0766f788
ER
624static __latent_entropy int dup_mmap(struct mm_struct *mm,
625 struct mm_struct *oldmm)
1da177e4 626{
297c5eee 627 struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
1da177e4
LT
628 struct rb_node **rb_link, *rb_parent;
629 int retval;
630 unsigned long charge;
893e26e6 631 LIST_HEAD(uf);
1da177e4 632
32cdba1e 633 uprobe_start_dup_mmap();
7c051267
MH
634 if (down_write_killable(&oldmm->mmap_sem)) {
635 retval = -EINTR;
636 goto fail_uprobe_end;
637 }
ec8c0446 638 flush_cache_dup_mm(oldmm);
f8ac4ec9 639 uprobe_dup_mmap(oldmm, mm);
ad339451
IM
640 /*
641 * Not linked in yet - no deadlock potential:
642 */
643 down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
7ee78232 644
90f31d0e
KK
645 /* No ordering required: file already has been exposed. */
646 RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
647
4f7d4614 648 mm->total_vm = oldmm->total_vm;
84638335 649 mm->data_vm = oldmm->data_vm;
4f7d4614
VD
650 mm->exec_vm = oldmm->exec_vm;
651 mm->stack_vm = oldmm->stack_vm;
652
1da177e4
LT
653 rb_link = &mm->mm_rb.rb_node;
654 rb_parent = NULL;
655 pprev = &mm->mmap;
f8af4da3 656 retval = ksm_fork(mm, oldmm);
ba76149f
AA
657 if (retval)
658 goto out;
659 retval = khugepaged_fork(mm, oldmm);
f8af4da3
HD
660 if (retval)
661 goto out;
1da177e4 662
297c5eee 663 prev = NULL;
fd3e42fc 664 for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
1da177e4
LT
665 struct file *file;
666
667 if (mpnt->vm_flags & VM_DONTCOPY) {
84638335 668 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
1da177e4
LT
669 continue;
670 }
671 charge = 0;
32f0a536
TH
672 /*
673 * Don't duplicate many vmas if we've been oom-killed (for
674 * example)
675 */
676 if (fatal_signal_pending(current)) {
677 retval = -EINTR;
678 goto out;
679 }
1da177e4 680 if (mpnt->vm_flags & VM_ACCOUNT) {
b2412b7f
HS
681 unsigned long len = vma_pages(mpnt);
682
191c5424 683 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
1da177e4
LT
684 goto fail_nomem;
685 charge = len;
686 }
e88c5cf9 687 tmp = vm_area_dup(mpnt);
1da177e4
LT
688 if (!tmp)
689 goto fail_nomem;
ef0855d3
ON
690 retval = vma_dup_policy(mpnt, tmp);
691 if (retval)
1da177e4 692 goto fail_nomem_policy;
a247c3a9 693 tmp->vm_mm = mm;
893e26e6
PE
694 retval = dup_userfaultfd(tmp, &uf);
695 if (retval)
696 goto fail_nomem_anon_vma_fork;
d2cd9ede
RR
697 if (tmp->vm_flags & VM_WIPEONFORK) {
698 /* VM_WIPEONFORK gets a clean slate in the child. */
699 tmp->anon_vma = NULL;
700 if (anon_vma_prepare(tmp))
701 goto fail_nomem_anon_vma_fork;
702 } else if (anon_vma_fork(tmp, mpnt))
5beb4930 703 goto fail_nomem_anon_vma_fork;
893e26e6 704 tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
297c5eee 705 tmp->vm_next = tmp->vm_prev = NULL;
1da177e4
LT
706 file = tmp->vm_file;
707 if (file) {
496ad9aa 708 struct inode *inode = file_inode(file);
b88ed205
HD
709 struct address_space *mapping = file->f_mapping;
710
c088e31d 711 vma_get_file(tmp);
1da177e4
LT
712 if (tmp->vm_flags & VM_DENYWRITE)
713 atomic_dec(&inode->i_writecount);
83cde9e8 714 i_mmap_lock_write(mapping);
b88ed205 715 if (tmp->vm_flags & VM_SHARED)
4bb5f5d9 716 atomic_inc(&mapping->i_mmap_writable);
b88ed205
HD
717 flush_dcache_mmap_lock(mapping);
718 /* insert tmp into the share list, just after mpnt */
27ba0644
KS
719 vma_interval_tree_insert_after(tmp, mpnt,
720 &mapping->i_mmap);
b88ed205 721 flush_dcache_mmap_unlock(mapping);
83cde9e8 722 i_mmap_unlock_write(mapping);
1da177e4
LT
723 }
724
a1e78772
MG
725 /*
726 * Clear hugetlb-related page reserves for children. This only
727 * affects MAP_PRIVATE mappings. Faults generated by the child
728 * are not guaranteed to succeed, even if read-only
729 */
730 if (is_vm_hugetlb_page(tmp))
731 reset_vma_resv_huge_pages(tmp);
732
1da177e4 733 /*
7ee78232 734 * Link in the new vma and copy the page table entries.
1da177e4 735 */
1da177e4
LT
736 *pprev = tmp;
737 pprev = &tmp->vm_next;
297c5eee
LT
738 tmp->vm_prev = prev;
739 prev = tmp;
1da177e4
LT
740
741 __vma_link_rb(mm, tmp, rb_link, rb_parent);
742 rb_link = &tmp->vm_rb.rb_right;
743 rb_parent = &tmp->vm_rb;
744
745 mm->map_count++;
d2cd9ede
RR
746 if (!(tmp->vm_flags & VM_WIPEONFORK))
747 retval = copy_page_range(mm, oldmm, mpnt);
1da177e4
LT
748
749 if (tmp->vm_ops && tmp->vm_ops->open)
750 tmp->vm_ops->open(tmp);
751
752 if (retval)
753 goto out;
754 }
d6dd61c8 755 /* a new mm has just been created */
c10e83f5 756 retval = arch_dup_mmap(oldmm, mm);
1da177e4 757out:
7ee78232 758 up_write(&mm->mmap_sem);
fd3e42fc 759 flush_tlb_mm(oldmm);
1da177e4 760 up_write(&oldmm->mmap_sem);
893e26e6 761 dup_userfaultfd_complete(&uf);
7c051267 762fail_uprobe_end:
32cdba1e 763 uprobe_end_dup_mmap();
1da177e4 764 return retval;
5beb4930 765fail_nomem_anon_vma_fork:
ef0855d3 766 mpol_put(vma_policy(tmp));
1da177e4 767fail_nomem_policy:
e88c5cf9 768 vm_area_free(tmp);
1da177e4
LT
769fail_nomem:
770 retval = -ENOMEM;
771 vm_unacct_memory(charge);
772 goto out;
773}
774
fb0a685c 775static inline int mm_alloc_pgd(struct mm_struct *mm)
1da177e4
LT
776{
777 mm->pgd = pgd_alloc(mm);
778 if (unlikely(!mm->pgd))
779 return -ENOMEM;
780 return 0;
781}
782
fb0a685c 783static inline void mm_free_pgd(struct mm_struct *mm)
1da177e4 784{
5e541973 785 pgd_free(mm, mm->pgd);
1da177e4
LT
786}
787#else
90f31d0e
KK
788static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
789{
790 down_write(&oldmm->mmap_sem);
791 RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
792 up_write(&oldmm->mmap_sem);
793 return 0;
794}
1da177e4
LT
795#define mm_alloc_pgd(mm) (0)
796#define mm_free_pgd(mm)
797#endif /* CONFIG_MMU */
798
23ff4440 799__cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
1da177e4 800
e94b1766 801#define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
1da177e4
LT
802#define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
803
4cb0e11b
HK
804static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
805
806static int __init coredump_filter_setup(char *s)
807{
808 default_dump_filter =
809 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
810 MMF_DUMP_FILTER_MASK;
811 return 1;
812}
813
814__setup("coredump_filter=", coredump_filter_setup);
815
1da177e4
LT
816#include <linux/init_task.h>
817
858f0993
AD
818static void mm_init_aio(struct mm_struct *mm)
819{
820#ifdef CONFIG_AIO
821 spin_lock_init(&mm->ioctx_lock);
db446a08 822 mm->ioctx_table = NULL;
858f0993
AD
823#endif
824}
825
343ef896
AA
826static __always_inline void mm_clear_owner(struct mm_struct *mm,
827 struct task_struct *p)
828{
829#ifdef CONFIG_MEMCG
830 if (mm->owner == p)
831 WRITE_ONCE(mm->owner, NULL);
832#endif
833}
834
33144e84
VD
835static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
836{
837#ifdef CONFIG_MEMCG
838 mm->owner = p;
839#endif
840}
841
355627f5
EB
842static void mm_init_uprobes_state(struct mm_struct *mm)
843{
844#ifdef CONFIG_UPROBES
845 mm->uprobes_state.xol_area = NULL;
846#endif
847}
848
bfedb589
EB
849static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
850 struct user_namespace *user_ns)
1da177e4 851{
41f727fd
VD
852 mm->mmap = NULL;
853 mm->mm_rb = RB_ROOT;
854 mm->vmacache_seqnum = 0;
1da177e4
LT
855 atomic_set(&mm->mm_users, 1);
856 atomic_set(&mm->mm_count, 1);
857 init_rwsem(&mm->mmap_sem);
858 INIT_LIST_HEAD(&mm->mmlist);
999d9fc1 859 mm->core_state = NULL;
af5b0f6a 860 mm_pgtables_bytes_init(mm);
41f727fd
VD
861 mm->map_count = 0;
862 mm->locked_vm = 0;
ce65cefa 863 mm->pinned_vm = 0;
d559db08 864 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1da177e4 865 spin_lock_init(&mm->page_table_lock);
41f727fd 866 mm_init_cpumask(mm);
858f0993 867 mm_init_aio(mm);
cf475ad2 868 mm_init_owner(mm, p);
2b7e8665 869 RCU_INIT_POINTER(mm->exe_file, NULL);
41f727fd 870 mmu_notifier_mm_init(mm);
133ff0ea 871 hmm_mm_init(mm);
16af97dc 872 init_tlb_flush_pending(mm);
41f727fd
VD
873#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
874 mm->pmd_huge_pte = NULL;
875#endif
355627f5 876 mm_init_uprobes_state(mm);
1da177e4 877
a0715cc2
AT
878 if (current->mm) {
879 mm->flags = current->mm->flags & MMF_INIT_MASK;
880 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
881 } else {
882 mm->flags = default_dump_filter;
1da177e4 883 mm->def_flags = 0;
a0715cc2
AT
884 }
885
41f727fd
VD
886 if (mm_alloc_pgd(mm))
887 goto fail_nopgd;
888
889 if (init_new_context(p, mm))
890 goto fail_nocontext;
78fb7466 891
bfedb589 892 mm->user_ns = get_user_ns(user_ns);
41f727fd
VD
893 return mm;
894
895fail_nocontext:
896 mm_free_pgd(mm);
897fail_nopgd:
1da177e4
LT
898 free_mm(mm);
899 return NULL;
900}
901
c3f0327f
KK
902static void check_mm(struct mm_struct *mm)
903{
904 int i;
905
906 for (i = 0; i < NR_MM_COUNTERS; i++) {
907 long x = atomic_long_read(&mm->rss_stat.count[i]);
908
909 if (unlikely(x))
910 printk(KERN_ALERT "BUG: Bad rss-counter state "
911 "mm:%p idx:%d val:%ld\n", mm, i, x);
912 }
b30fe6c7 913
af5b0f6a
KS
914 if (mm_pgtables_bytes(mm))
915 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
916 mm_pgtables_bytes(mm));
b30fe6c7 917
e009bb30 918#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
96dad67f 919 VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
c3f0327f
KK
920#endif
921}
922
1da177e4
LT
923/*
924 * Allocate and initialize an mm_struct.
925 */
fb0a685c 926struct mm_struct *mm_alloc(void)
1da177e4 927{
fb0a685c 928 struct mm_struct *mm;
1da177e4
LT
929
930 mm = allocate_mm();
de03c72c
KM
931 if (!mm)
932 return NULL;
933
934 memset(mm, 0, sizeof(*mm));
bfedb589 935 return mm_init(mm, current, current_user_ns());
1da177e4
LT
936}
937
938/*
939 * Called when the last reference to the mm
940 * is dropped: either by a lazy thread or by
941 * mmput. Free the page directory and the mm.
942 */
7ad5b3a5 943void __mmdrop(struct mm_struct *mm)
1da177e4
LT
944{
945 BUG_ON(mm == &init_mm);
946 mm_free_pgd(mm);
947 destroy_context(mm);
133ff0ea 948 hmm_mm_destroy(mm);
cddb8a5c 949 mmu_notifier_mm_destroy(mm);
c3f0327f 950 check_mm(mm);
bfedb589 951 put_user_ns(mm->user_ns);
1da177e4
LT
952 free_mm(mm);
953}
6d4e4c4f 954EXPORT_SYMBOL_GPL(__mmdrop);
1da177e4 955
ec8d7c14
MH
956static inline void __mmput(struct mm_struct *mm)
957{
958 VM_BUG_ON(atomic_read(&mm->mm_users));
959
960 uprobe_clear_state(mm);
961 exit_aio(mm);
962 ksm_exit(mm);
963 khugepaged_exit(mm); /* must run before exit_mmap */
964 exit_mmap(mm);
6fcb52a5 965 mm_put_huge_zero_page(mm);
ec8d7c14
MH
966 set_mm_exe_file(mm, NULL);
967 if (!list_empty(&mm->mmlist)) {
968 spin_lock(&mmlist_lock);
969 list_del(&mm->mmlist);
970 spin_unlock(&mmlist_lock);
971 }
972 if (mm->binfmt)
973 module_put(mm->binfmt->module);
974 mmdrop(mm);
975}
976
1da177e4
LT
977/*
978 * Decrement the use count and release all resources for an mm.
979 */
980void mmput(struct mm_struct *mm)
981{
0ae26f1b
AM
982 might_sleep();
983
ec8d7c14
MH
984 if (atomic_dec_and_test(&mm->mm_users))
985 __mmput(mm);
986}
987EXPORT_SYMBOL_GPL(mmput);
988
a1b2289c
SY
989#ifdef CONFIG_MMU
990static void mmput_async_fn(struct work_struct *work)
991{
992 struct mm_struct *mm = container_of(work, struct mm_struct,
993 async_put_work);
994
995 __mmput(mm);
996}
997
998void mmput_async(struct mm_struct *mm)
999{
1000 if (atomic_dec_and_test(&mm->mm_users)) {
1001 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1002 schedule_work(&mm->async_put_work);
1003 }
1004}
1005#endif
1006
90f31d0e
KK
1007/**
1008 * set_mm_exe_file - change a reference to the mm's executable file
1009 *
1010 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1011 *
6e399cd1
DB
1012 * Main users are mmput() and sys_execve(). Callers prevent concurrent
1013 * invocations: in mmput() nobody alive left, in execve task is single
1014 * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
1015 * mm->exe_file, but does so without using set_mm_exe_file() in order
1016 * to do avoid the need for any locks.
90f31d0e 1017 */
38646013
JS
1018void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1019{
6e399cd1
DB
1020 struct file *old_exe_file;
1021
1022 /*
1023 * It is safe to dereference the exe_file without RCU as
1024 * this function is only called if nobody else can access
1025 * this mm -- see comment above for justification.
1026 */
1027 old_exe_file = rcu_dereference_raw(mm->exe_file);
90f31d0e 1028
38646013
JS
1029 if (new_exe_file)
1030 get_file(new_exe_file);
90f31d0e
KK
1031 rcu_assign_pointer(mm->exe_file, new_exe_file);
1032 if (old_exe_file)
1033 fput(old_exe_file);
38646013
JS
1034}
1035
90f31d0e
KK
1036/**
1037 * get_mm_exe_file - acquire a reference to the mm's executable file
1038 *
1039 * Returns %NULL if mm has no associated executable file.
1040 * User must release file via fput().
1041 */
38646013
JS
1042struct file *get_mm_exe_file(struct mm_struct *mm)
1043{
1044 struct file *exe_file;
1045
90f31d0e
KK
1046 rcu_read_lock();
1047 exe_file = rcu_dereference(mm->exe_file);
1048 if (exe_file && !get_file_rcu(exe_file))
1049 exe_file = NULL;
1050 rcu_read_unlock();
38646013
JS
1051 return exe_file;
1052}
11163348 1053EXPORT_SYMBOL(get_mm_exe_file);
38646013 1054
cd81a917
MG
1055/**
1056 * get_task_exe_file - acquire a reference to the task's executable file
1057 *
1058 * Returns %NULL if task's mm (if any) has no associated executable file or
1059 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1060 * User must release file via fput().
1061 */
1062struct file *get_task_exe_file(struct task_struct *task)
1063{
1064 struct file *exe_file = NULL;
1065 struct mm_struct *mm;
1066
1067 task_lock(task);
1068 mm = task->mm;
1069 if (mm) {
1070 if (!(task->flags & PF_KTHREAD))
1071 exe_file = get_mm_exe_file(mm);
1072 }
1073 task_unlock(task);
1074 return exe_file;
1075}
1076EXPORT_SYMBOL(get_task_exe_file);
38646013 1077
1da177e4
LT
1078/**
1079 * get_task_mm - acquire a reference to the task's mm
1080 *
246bb0b1 1081 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1da177e4
LT
1082 * this kernel workthread has transiently adopted a user mm with use_mm,
1083 * to do its AIO) is not set and if so returns a reference to it, after
1084 * bumping up the use count. User must release the mm via mmput()
1085 * after use. Typically used by /proc and ptrace.
1086 */
1087struct mm_struct *get_task_mm(struct task_struct *task)
1088{
1089 struct mm_struct *mm;
1090
1091 task_lock(task);
1092 mm = task->mm;
1093 if (mm) {
246bb0b1 1094 if (task->flags & PF_KTHREAD)
1da177e4
LT
1095 mm = NULL;
1096 else
3fce371b 1097 mmget(mm);
1da177e4
LT
1098 }
1099 task_unlock(task);
1100 return mm;
1101}
1102EXPORT_SYMBOL_GPL(get_task_mm);
1103
8cdb878d
CY
1104struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1105{
1106 struct mm_struct *mm;
1107 int err;
1108
1109 err = mutex_lock_killable(&task->signal->cred_guard_mutex);
1110 if (err)
1111 return ERR_PTR(err);
1112
1113 mm = get_task_mm(task);
1114 if (mm && mm != current->mm &&
1115 !ptrace_may_access(task, mode)) {
1116 mmput(mm);
1117 mm = ERR_PTR(-EACCES);
1118 }
1119 mutex_unlock(&task->signal->cred_guard_mutex);
1120
1121 return mm;
1122}
1123
57b59c4a 1124static void complete_vfork_done(struct task_struct *tsk)
c415c3b4 1125{
d68b46fe 1126 struct completion *vfork;
c415c3b4 1127
d68b46fe
ON
1128 task_lock(tsk);
1129 vfork = tsk->vfork_done;
1130 if (likely(vfork)) {
1131 tsk->vfork_done = NULL;
1132 complete(vfork);
1133 }
1134 task_unlock(tsk);
1135}
1136
1137static int wait_for_vfork_done(struct task_struct *child,
1138 struct completion *vfork)
1139{
1140 int killed;
1141
1142 freezer_do_not_count();
1143 killed = wait_for_completion_killable(vfork);
1144 freezer_count();
1145
1146 if (killed) {
1147 task_lock(child);
1148 child->vfork_done = NULL;
1149 task_unlock(child);
1150 }
1151
1152 put_task_struct(child);
1153 return killed;
c415c3b4
ON
1154}
1155
1da177e4
LT
1156/* Please note the differences between mmput and mm_release.
1157 * mmput is called whenever we stop holding onto a mm_struct,
1158 * error success whatever.
1159 *
1160 * mm_release is called after a mm_struct has been removed
1161 * from the current process.
1162 *
1163 * This difference is important for error handling, when we
1164 * only half set up a mm_struct for a new process and need to restore
1165 * the old one. Because we mmput the new mm_struct before
1166 * restoring the old one. . .
1167 * Eric Biederman 10 January 1998
1168 */
1169void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1170{
8141c7f3 1171 /* Get rid of any futexes when releasing the mm */
e891c8f7 1172 futex_mm_release(tsk);
8141c7f3 1173
0326f5a9
SD
1174 uprobe_free_utask(tsk);
1175
1da177e4
LT
1176 /* Get rid of any cached register state */
1177 deactivate_mm(tsk, mm);
1178
fec1d011 1179 /*
735f2770
MH
1180 * Signal userspace if we're not exiting with a core dump
1181 * because we want to leave the value intact for debugging
1182 * purposes.
fec1d011 1183 */
9c8a8228 1184 if (tsk->clear_child_tid) {
735f2770 1185 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
9c8a8228
ED
1186 atomic_read(&mm->mm_users) > 1) {
1187 /*
1188 * We don't check the error code - if userspace has
1189 * not set up a proper pointer then tough luck.
1190 */
1191 put_user(0, tsk->clear_child_tid);
1192 sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
1193 1, NULL, NULL, 0);
1194 }
1da177e4 1195 tsk->clear_child_tid = NULL;
1da177e4 1196 }
f7505d64
KK
1197
1198 /*
1199 * All done, finally we can wake up parent and return this mm to him.
1200 * Also kthread_stop() uses this completion for synchronization.
1201 */
1202 if (tsk->vfork_done)
1203 complete_vfork_done(tsk);
1da177e4
LT
1204}
1205
a0a7ec30
JD
1206/*
1207 * Allocate a new mm structure and copy contents from the
1208 * mm structure of the passed in task structure.
1209 */
ff252c1f 1210static struct mm_struct *dup_mm(struct task_struct *tsk)
a0a7ec30
JD
1211{
1212 struct mm_struct *mm, *oldmm = current->mm;
1213 int err;
1214
a0a7ec30
JD
1215 mm = allocate_mm();
1216 if (!mm)
1217 goto fail_nomem;
1218
1219 memcpy(mm, oldmm, sizeof(*mm));
1220
bfedb589 1221 if (!mm_init(mm, tsk, mm->user_ns))
a0a7ec30
JD
1222 goto fail_nomem;
1223
a0a7ec30
JD
1224 err = dup_mmap(mm, oldmm);
1225 if (err)
1226 goto free_pt;
1227
1228 mm->hiwater_rss = get_mm_rss(mm);
1229 mm->hiwater_vm = mm->total_vm;
1230
801460d0
HS
1231 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1232 goto free_pt;
1233
a0a7ec30
JD
1234 return mm;
1235
1236free_pt:
801460d0
HS
1237 /* don't put binfmt in mmput, we haven't got module yet */
1238 mm->binfmt = NULL;
343ef896 1239 mm_init_owner(mm, NULL);
a0a7ec30
JD
1240 mmput(mm);
1241
1242fail_nomem:
1243 return NULL;
a0a7ec30
JD
1244}
1245
fb0a685c 1246static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1da177e4 1247{
fb0a685c 1248 struct mm_struct *mm, *oldmm;
1da177e4
LT
1249 int retval;
1250
1251 tsk->min_flt = tsk->maj_flt = 0;
1252 tsk->nvcsw = tsk->nivcsw = 0;
17406b82
MSB
1253#ifdef CONFIG_DETECT_HUNG_TASK
1254 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1255#endif
1da177e4
LT
1256
1257 tsk->mm = NULL;
1258 tsk->active_mm = NULL;
1259
1260 /*
1261 * Are we cloning a kernel thread?
1262 *
1263 * We need to steal a active VM for that..
1264 */
1265 oldmm = current->mm;
1266 if (!oldmm)
1267 return 0;
1268
615d6e87
DB
1269 /* initialize the new vmacache entries */
1270 vmacache_flush(tsk);
1271
1da177e4 1272 if (clone_flags & CLONE_VM) {
3fce371b 1273 mmget(oldmm);
1da177e4 1274 mm = oldmm;
1da177e4
LT
1275 goto good_mm;
1276 }
1277
1278 retval = -ENOMEM;
a0a7ec30 1279 mm = dup_mm(tsk);
1da177e4
LT
1280 if (!mm)
1281 goto fail_nomem;
1282
1da177e4
LT
1283good_mm:
1284 tsk->mm = mm;
1285 tsk->active_mm = mm;
1286 return 0;
1287
1da177e4
LT
1288fail_nomem:
1289 return retval;
1da177e4
LT
1290}
1291
a39bc516 1292static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1da177e4 1293{
498052bb 1294 struct fs_struct *fs = current->fs;
1da177e4 1295 if (clone_flags & CLONE_FS) {
498052bb 1296 /* tsk->fs is already what we want */
2a4419b5 1297 spin_lock(&fs->lock);
498052bb 1298 if (fs->in_exec) {
2a4419b5 1299 spin_unlock(&fs->lock);
498052bb
AV
1300 return -EAGAIN;
1301 }
1302 fs->users++;
2a4419b5 1303 spin_unlock(&fs->lock);
1da177e4
LT
1304 return 0;
1305 }
498052bb 1306 tsk->fs = copy_fs_struct(fs);
1da177e4
LT
1307 if (!tsk->fs)
1308 return -ENOMEM;
1309 return 0;
1310}
1311
fb0a685c 1312static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
a016f338
JD
1313{
1314 struct files_struct *oldf, *newf;
1315 int error = 0;
1316
1317 /*
1318 * A background process may not have any files ...
1319 */
1320 oldf = current->files;
1321 if (!oldf)
1322 goto out;
1323
1324 if (clone_flags & CLONE_FILES) {
1325 atomic_inc(&oldf->count);
1326 goto out;
1327 }
1328
a016f338
JD
1329 newf = dup_fd(oldf, &error);
1330 if (!newf)
1331 goto out;
1332
1333 tsk->files = newf;
1334 error = 0;
1335out:
1336 return error;
1337}
1338
fadad878 1339static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
fd0928df
JA
1340{
1341#ifdef CONFIG_BLOCK
1342 struct io_context *ioc = current->io_context;
6e736be7 1343 struct io_context *new_ioc;
fd0928df
JA
1344
1345 if (!ioc)
1346 return 0;
fadad878
JA
1347 /*
1348 * Share io context with parent, if CLONE_IO is set
1349 */
1350 if (clone_flags & CLONE_IO) {
3d48749d
TH
1351 ioc_task_link(ioc);
1352 tsk->io_context = ioc;
fadad878 1353 } else if (ioprio_valid(ioc->ioprio)) {
6e736be7
TH
1354 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1355 if (unlikely(!new_ioc))
fd0928df
JA
1356 return -ENOMEM;
1357
6e736be7 1358 new_ioc->ioprio = ioc->ioprio;
11a3122f 1359 put_io_context(new_ioc);
fd0928df
JA
1360 }
1361#endif
1362 return 0;
1363}
1364
a39bc516 1365static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1da177e4
LT
1366{
1367 struct sighand_struct *sig;
1368
60348802 1369 if (clone_flags & CLONE_SIGHAND) {
1da177e4
LT
1370 atomic_inc(&current->sighand->count);
1371 return 0;
1372 }
1373 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
e56d0903 1374 rcu_assign_pointer(tsk->sighand, sig);
1da177e4
LT
1375 if (!sig)
1376 return -ENOMEM;
9d7fb042 1377
1da177e4 1378 atomic_set(&sig->count, 1);
9aa84979 1379 spin_lock_irq(&current->sighand->siglock);
1da177e4 1380 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
9aa84979 1381 spin_unlock_irq(&current->sighand->siglock);
1da177e4
LT
1382 return 0;
1383}
1384
a7e5328a 1385void __cleanup_sighand(struct sighand_struct *sighand)
c81addc9 1386{
d80e731e
ON
1387 if (atomic_dec_and_test(&sighand->count)) {
1388 signalfd_cleanup(sighand);
392809b2 1389 /*
5f0d5a3a 1390 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
392809b2
ON
1391 * without an RCU grace period, see __lock_task_sighand().
1392 */
c81addc9 1393 kmem_cache_free(sighand_cachep, sighand);
d80e731e 1394 }
c81addc9
ON
1395}
1396
b18b6a9c 1397#ifdef CONFIG_POSIX_TIMERS
f06febc9
FM
1398/*
1399 * Initialize POSIX timer handling for a thread group.
1400 */
1401static void posix_cpu_timers_init_group(struct signal_struct *sig)
1402{
78d7d407
JS
1403 unsigned long cpu_limit;
1404
316c1608 1405 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
78d7d407 1406 if (cpu_limit != RLIM_INFINITY) {
ebd7e7fc 1407 sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
d5c373eb 1408 sig->cputimer.running = true;
6279a751
ON
1409 }
1410
f06febc9
FM
1411 /* The timer lists. */
1412 INIT_LIST_HEAD(&sig->cpu_timers[0]);
1413 INIT_LIST_HEAD(&sig->cpu_timers[1]);
1414 INIT_LIST_HEAD(&sig->cpu_timers[2]);
1415}
b18b6a9c
NP
1416#else
1417static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1418#endif
f06febc9 1419
a39bc516 1420static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1da177e4
LT
1421{
1422 struct signal_struct *sig;
1da177e4 1423
4ab6c083 1424 if (clone_flags & CLONE_THREAD)
490dea45 1425 return 0;
490dea45 1426
a56704ef 1427 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1da177e4
LT
1428 tsk->signal = sig;
1429 if (!sig)
1430 return -ENOMEM;
1431
b3ac022c 1432 sig->nr_threads = 1;
1da177e4 1433 atomic_set(&sig->live, 1);
b3ac022c 1434 atomic_set(&sig->sigcnt, 1);
0c740d0a
ON
1435
1436 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1437 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1438 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1439
1da177e4 1440 init_waitqueue_head(&sig->wait_chldexit);
db51aecc 1441 sig->curr_target = tsk;
1da177e4 1442 init_sigpending(&sig->shared_pending);
e78c3496 1443 seqlock_init(&sig->stats_lock);
9d7fb042 1444 prev_cputime_init(&sig->prev_cputime);
1da177e4 1445
baa73d9e 1446#ifdef CONFIG_POSIX_TIMERS
b18b6a9c 1447 INIT_LIST_HEAD(&sig->posix_timers);
c9cb2e3d 1448 hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1da177e4 1449 sig->real_timer.function = it_real_fn;
baa73d9e 1450#endif
1da177e4 1451
1da177e4
LT
1452 task_lock(current->group_leader);
1453 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1454 task_unlock(current->group_leader);
1455
6279a751
ON
1456 posix_cpu_timers_init_group(sig);
1457
522ed776 1458 tty_audit_fork(sig);
5091faa4 1459 sched_autogroup_fork(sig);
522ed776 1460
a63d83f4 1461 sig->oom_score_adj = current->signal->oom_score_adj;
dabb16f6 1462 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
28b83c51 1463
9b1bf12d
KM
1464 mutex_init(&sig->cred_guard_mutex);
1465
1da177e4
LT
1466 return 0;
1467}
1468
dbd95212
KC
1469static void copy_seccomp(struct task_struct *p)
1470{
1471#ifdef CONFIG_SECCOMP
1472 /*
1473 * Must be called with sighand->lock held, which is common to
1474 * all threads in the group. Holding cred_guard_mutex is not
1475 * needed because this new task is not yet running and cannot
1476 * be racing exec.
1477 */
69f6a34b 1478 assert_spin_locked(&current->sighand->siglock);
dbd95212
KC
1479
1480 /* Ref-count the new filter user, and assign it. */
1481 get_seccomp_filter(current);
1482 p->seccomp = current->seccomp;
1483
1484 /*
1485 * Explicitly enable no_new_privs here in case it got set
1486 * between the task_struct being duplicated and holding the
1487 * sighand lock. The seccomp state and nnp must be in sync.
1488 */
1489 if (task_no_new_privs(current))
1490 task_set_no_new_privs(p);
1491
1492 /*
1493 * If the parent gained a seccomp mode after copying thread
1494 * flags and between before we held the sighand lock, we have
1495 * to manually enable the seccomp thread flag here.
1496 */
1497 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1498 set_tsk_thread_flag(p, TIF_SECCOMP);
1499#endif
1500}
1501
17da2bd9 1502SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1da177e4
LT
1503{
1504 current->clear_child_tid = tidptr;
1505
b488893a 1506 return task_pid_vnr(current);
1da177e4
LT
1507}
1508
a39bc516 1509static void rt_mutex_init_task(struct task_struct *p)
23f78d4a 1510{
1d615482 1511 raw_spin_lock_init(&p->pi_lock);
e29e175b 1512#ifdef CONFIG_RT_MUTEXES
a23ba907 1513 p->pi_waiters = RB_ROOT_CACHED;
e96a7705 1514 p->pi_top_task = NULL;
23f78d4a 1515 p->pi_blocked_on = NULL;
23f78d4a
IM
1516#endif
1517}
1518
b18b6a9c 1519#ifdef CONFIG_POSIX_TIMERS
f06febc9
FM
1520/*
1521 * Initialize POSIX timer handling for a single task.
1522 */
1523static void posix_cpu_timers_init(struct task_struct *tsk)
1524{
64861634
MS
1525 tsk->cputime_expires.prof_exp = 0;
1526 tsk->cputime_expires.virt_exp = 0;
f06febc9
FM
1527 tsk->cputime_expires.sched_exp = 0;
1528 INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1529 INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1530 INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1531}
b18b6a9c
NP
1532#else
1533static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1534#endif
f06febc9 1535
81907739
ON
1536static inline void
1537init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1538{
1539 task->pids[type].pid = pid;
1540}
1541
6bfbaa51
IM
1542static inline void rcu_copy_process(struct task_struct *p)
1543{
1544#ifdef CONFIG_PREEMPT_RCU
1545 p->rcu_read_lock_nesting = 0;
1546 p->rcu_read_unlock_special.s = 0;
1547 p->rcu_blocked_node = NULL;
1548 INIT_LIST_HEAD(&p->rcu_node_entry);
1549#endif /* #ifdef CONFIG_PREEMPT_RCU */
1550#ifdef CONFIG_TASKS_RCU
1551 p->rcu_tasks_holdout = false;
1552 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1553 p->rcu_tasks_idle_cpu = -1;
1554#endif /* #ifdef CONFIG_TASKS_RCU */
1555}
1556
343ef896
AA
1557static void __delayed_free_task(struct rcu_head *rhp)
1558{
1559 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1560
1561 free_task(tsk);
1562}
1563
1564static __always_inline void delayed_free_task(struct task_struct *tsk)
1565{
1566 if (IS_ENABLED(CONFIG_MEMCG))
1567 call_rcu(&tsk->rcu, __delayed_free_task);
1568 else
1569 free_task(tsk);
1570}
1571
1da177e4
LT
1572/*
1573 * This creates a new process as a copy of the old one,
1574 * but does not actually start it yet.
1575 *
1576 * It copies the registers, and all the appropriate
1577 * parts of the process environment (as per the clone
1578 * flags). The actual kick-off is left to the caller.
1579 */
0766f788
ER
1580static __latent_entropy struct task_struct *copy_process(
1581 unsigned long clone_flags,
36c8b586 1582 unsigned long stack_start,
36c8b586 1583 unsigned long stack_size,
36c8b586 1584 int __user *child_tidptr,
09a05394 1585 struct pid *pid,
3033f14a 1586 int trace,
725fc629
AK
1587 unsigned long tls,
1588 int node)
1da177e4
LT
1589{
1590 int retval;
a24efe62 1591 struct task_struct *p;
1da177e4
LT
1592
1593 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1594 return ERR_PTR(-EINVAL);
1595
e66eded8
EB
1596 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1597 return ERR_PTR(-EINVAL);
1598
680f7875
SH
1599 if ((clone_flags & CLONE_NEWUSER) && !unprivileged_userns_clone)
1600 if (!capable(CAP_SYS_ADMIN))
1601 return ERR_PTR(-EPERM);
1602
1da177e4
LT
1603 /*
1604 * Thread groups must share signals as well, and detached threads
1605 * can only be started up within the thread group.
1606 */
1607 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1608 return ERR_PTR(-EINVAL);
1609
1610 /*
1611 * Shared signal handlers imply shared VM. By way of the above,
1612 * thread groups also imply shared VM. Blocking this case allows
1613 * for various simplifications in other code.
1614 */
1615 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1616 return ERR_PTR(-EINVAL);
1617
123be07b
SB
1618 /*
1619 * Siblings of global init remain as zombies on exit since they are
1620 * not reaped by their parent (swapper). To solve this and to avoid
1621 * multi-rooted process trees, prevent global and container-inits
1622 * from creating siblings.
1623 */
1624 if ((clone_flags & CLONE_PARENT) &&
1625 current->signal->flags & SIGNAL_UNKILLABLE)
1626 return ERR_PTR(-EINVAL);
1627
8382fcac 1628 /*
40a0d32d 1629 * If the new process will be in a different pid or user namespace
faf00da5 1630 * do not allow it to share a thread group with the forking task.
8382fcac 1631 */
faf00da5 1632 if (clone_flags & CLONE_THREAD) {
40a0d32d
ON
1633 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1634 (task_active_pid_ns(current) !=
1635 current->nsproxy->pid_ns_for_children))
1636 return ERR_PTR(-EINVAL);
1637 }
8382fcac 1638
1da177e4 1639 retval = -ENOMEM;
725fc629 1640 p = dup_task_struct(current, node);
1da177e4
LT
1641 if (!p)
1642 goto fork_out;
1643
4d6501dc
VN
1644 /*
1645 * This _must_ happen before we call free_task(), i.e. before we jump
1646 * to any of the bad_fork_* labels. This is to avoid freeing
1647 * p->set_child_tid which is (ab)used as a kthread's data pointer for
1648 * kernel threads (PF_KTHREAD).
1649 */
1650 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1651 /*
1652 * Clear TID on mm_release()?
1653 */
1654 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
1655
f7e8b616
SR
1656 ftrace_graph_init_task(p);
1657
bea493a0
PZ
1658 rt_mutex_init_task(p);
1659
d12c1a37 1660#ifdef CONFIG_PROVE_LOCKING
de30a2b3
IM
1661 DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1662 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1663#endif
1da177e4 1664 retval = -EAGAIN;
3b11a1de 1665 if (atomic_read(&p->real_cred->user->processes) >=
78d7d407 1666 task_rlimit(p, RLIMIT_NPROC)) {
b57922b6
EP
1667 if (p->real_cred->user != INIT_USER &&
1668 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1da177e4
LT
1669 goto bad_fork_free;
1670 }
72fa5997 1671 current->flags &= ~PF_NPROC_EXCEEDED;
1da177e4 1672
f1752eec
DH
1673 retval = copy_creds(p, clone_flags);
1674 if (retval < 0)
1675 goto bad_fork_free;
1da177e4
LT
1676
1677 /*
1678 * If multiple threads are within copy_process(), then this check
1679 * triggers too late. This doesn't hurt, the check is only there
1680 * to stop root fork bombs.
1681 */
04ec93fe 1682 retval = -EAGAIN;
1da177e4
LT
1683 if (nr_threads >= max_threads)
1684 goto bad_fork_cleanup_count;
1685
ca74e92b 1686 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
c1de45ca 1687 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
514ddb44 1688 p->flags |= PF_FORKNOEXEC;
1da177e4
LT
1689 INIT_LIST_HEAD(&p->children);
1690 INIT_LIST_HEAD(&p->sibling);
f41d911f 1691 rcu_copy_process(p);
1da177e4
LT
1692 p->vfork_done = NULL;
1693 spin_lock_init(&p->alloc_lock);
1da177e4 1694
1da177e4
LT
1695 init_sigpending(&p->pending);
1696
64861634 1697 p->utime = p->stime = p->gtime = 0;
40565b5a 1698#ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
64861634 1699 p->utimescaled = p->stimescaled = 0;
40565b5a 1700#endif
9d7fb042
PZ
1701 prev_cputime_init(&p->prev_cputime);
1702
6a61671b 1703#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
bac5b6b6
FW
1704 seqcount_init(&p->vtime.seqcount);
1705 p->vtime.starttime = 0;
1706 p->vtime.state = VTIME_INACTIVE;
6a61671b
FW
1707#endif
1708
a3a2e76c
KH
1709#if defined(SPLIT_RSS_COUNTING)
1710 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1711#endif
172ba844 1712
6976675d
AV
1713 p->default_timer_slack_ns = current->timer_slack_ns;
1714
5995477a 1715 task_io_accounting_init(&p->ioac);
1da177e4
LT
1716 acct_clear_integrals(p);
1717
f06febc9 1718 posix_cpu_timers_init(p);
1da177e4 1719
1da177e4 1720 p->io_context = NULL;
1da177e4 1721 p->audit_context = NULL;
b4f48b63 1722 cgroup_fork(p);
1da177e4 1723#ifdef CONFIG_NUMA
846a16bf 1724 p->mempolicy = mpol_dup(p->mempolicy);
fb0a685c
DRO
1725 if (IS_ERR(p->mempolicy)) {
1726 retval = PTR_ERR(p->mempolicy);
1727 p->mempolicy = NULL;
e8604cb4 1728 goto bad_fork_cleanup_threadgroup_lock;
fb0a685c 1729 }
1da177e4 1730#endif
778d3b0f
MH
1731#ifdef CONFIG_CPUSETS
1732 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1733 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
cc9a6c87 1734 seqcount_init(&p->mems_allowed_seq);
778d3b0f 1735#endif
de30a2b3
IM
1736#ifdef CONFIG_TRACE_IRQFLAGS
1737 p->irq_events = 0;
1738 p->hardirqs_enabled = 0;
1739 p->hardirq_enable_ip = 0;
1740 p->hardirq_enable_event = 0;
1741 p->hardirq_disable_ip = _THIS_IP_;
1742 p->hardirq_disable_event = 0;
1743 p->softirqs_enabled = 1;
1744 p->softirq_enable_ip = _THIS_IP_;
1745 p->softirq_enable_event = 0;
1746 p->softirq_disable_ip = 0;
1747 p->softirq_disable_event = 0;
1748 p->hardirq_context = 0;
1749 p->softirq_context = 0;
1750#endif
8bcbde54
DH
1751
1752 p->pagefault_disabled = 0;
1753
fbb9ce95
IM
1754#ifdef CONFIG_LOCKDEP
1755 p->lockdep_depth = 0; /* no locks held yet */
1756 p->curr_chain_key = 0;
1757 p->lockdep_recursion = 0;
b09be676 1758 lockdep_init_task(p);
fbb9ce95 1759#endif
1da177e4 1760
408894ee
IM
1761#ifdef CONFIG_DEBUG_MUTEXES
1762 p->blocked_on = NULL; /* not blocked yet */
1763#endif
cafe5635
KO
1764#ifdef CONFIG_BCACHE
1765 p->sequential_io = 0;
1766 p->sequential_io_avg = 0;
1767#endif
09227ab6
JJ
1768#ifdef CONFIG_SECURITY
1769 p->security = NULL;
1770#endif
0f481406 1771
3c90e6e9 1772 /* Perform scheduler related setup. Assign this task to a CPU. */
aab03e05
DF
1773 retval = sched_fork(clone_flags, p);
1774 if (retval)
1775 goto bad_fork_cleanup_policy;
6ab423e0 1776
cdd6c482 1777 retval = perf_event_init_task(p);
6ab423e0
PZ
1778 if (retval)
1779 goto bad_fork_cleanup_policy;
fb0a685c
DRO
1780 retval = audit_alloc(p);
1781 if (retval)
6c72e350 1782 goto bad_fork_cleanup_perf;
1da177e4 1783 /* copy all the process information */
ab602f79 1784 shm_init_task(p);
e4e55b47 1785 retval = security_task_alloc(p, clone_flags);
fb0a685c 1786 if (retval)
1da177e4 1787 goto bad_fork_cleanup_audit;
e4e55b47
TH
1788 retval = copy_semundo(clone_flags, p);
1789 if (retval)
1790 goto bad_fork_cleanup_security;
fb0a685c
DRO
1791 retval = copy_files(clone_flags, p);
1792 if (retval)
1da177e4 1793 goto bad_fork_cleanup_semundo;
fb0a685c
DRO
1794 retval = copy_fs(clone_flags, p);
1795 if (retval)
1da177e4 1796 goto bad_fork_cleanup_files;
fb0a685c
DRO
1797 retval = copy_sighand(clone_flags, p);
1798 if (retval)
1da177e4 1799 goto bad_fork_cleanup_fs;
fb0a685c
DRO
1800 retval = copy_signal(clone_flags, p);
1801 if (retval)
1da177e4 1802 goto bad_fork_cleanup_sighand;
fb0a685c
DRO
1803 retval = copy_mm(clone_flags, p);
1804 if (retval)
1da177e4 1805 goto bad_fork_cleanup_signal;
fb0a685c
DRO
1806 retval = copy_namespaces(clone_flags, p);
1807 if (retval)
d84f4f99 1808 goto bad_fork_cleanup_mm;
fb0a685c
DRO
1809 retval = copy_io(clone_flags, p);
1810 if (retval)
fd0928df 1811 goto bad_fork_cleanup_namespaces;
3033f14a 1812 retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
1da177e4 1813 if (retval)
fd0928df 1814 goto bad_fork_cleanup_io;
1da177e4 1815
425fb2b4 1816 if (pid != &init_struct_pid) {
c2b1df2e 1817 pid = alloc_pid(p->nsproxy->pid_ns_for_children);
35f71bc0
MH
1818 if (IS_ERR(pid)) {
1819 retval = PTR_ERR(pid);
0740aa5f 1820 goto bad_fork_cleanup_thread;
35f71bc0 1821 }
425fb2b4
PE
1822 }
1823
73c10101
JA
1824#ifdef CONFIG_BLOCK
1825 p->plug = NULL;
1826#endif
e891c8f7
TG
1827 futex_init_task(p);
1828
f9a3879a
GM
1829 /*
1830 * sigaltstack should be cleared when sharing the same VM
1831 */
1832 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2a742138 1833 sas_ss_reset(p);
f9a3879a 1834
1da177e4 1835 /*
6580807d
ON
1836 * Syscall tracing and stepping should be turned off in the
1837 * child regardless of CLONE_PTRACE.
1da177e4 1838 */
6580807d 1839 user_disable_single_step(p);
1da177e4 1840 clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
ed75e8d5
LV
1841#ifdef TIF_SYSCALL_EMU
1842 clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1843#endif
9745512c 1844 clear_all_latency_tracing(p);
1da177e4 1845
1da177e4 1846 /* ok, now we should be set up.. */
18c830df
ON
1847 p->pid = pid_nr(pid);
1848 if (clone_flags & CLONE_THREAD) {
5f8aadd8 1849 p->exit_signal = -1;
18c830df
ON
1850 p->group_leader = current->group_leader;
1851 p->tgid = current->tgid;
1852 } else {
1853 if (clone_flags & CLONE_PARENT)
1854 p->exit_signal = current->group_leader->exit_signal;
1855 else
1856 p->exit_signal = (clone_flags & CSIGNAL);
1857 p->group_leader = p;
1858 p->tgid = p->pid;
1859 }
5f8aadd8 1860
9d823e8f
WF
1861 p->nr_dirtied = 0;
1862 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
83712358 1863 p->dirty_paused_when = 0;
9d823e8f 1864
bb8cbbfe 1865 p->pdeath_signal = 0;
47e65328 1866 INIT_LIST_HEAD(&p->thread_group);
158e1645 1867 p->task_works = NULL;
1da177e4 1868
780de9dd 1869 cgroup_threadgroup_change_begin(current);
7e47682e
AS
1870 /*
1871 * Ensure that the cgroup subsystem policies allow the new process to be
1872 * forked. It should be noted the the new process's css_set can be changed
1873 * between here and cgroup_post_fork() if an organisation operation is in
1874 * progress.
1875 */
b53202e6 1876 retval = cgroup_can_fork(p);
7e47682e
AS
1877 if (retval)
1878 goto bad_fork_free_pid;
1879
e78a7b49
DH
1880 /*
1881 * From this point on we must avoid any synchronous user-space
1882 * communication until we take the tasklist-lock. In particular, we do
1883 * not want user-space to be able to predict the process start-time by
1884 * stalling fork(2) after we recorded the start_time but before it is
1885 * visible to the system.
1886 */
1887
1888 p->start_time = ktime_get_ns();
1889 p->real_start_time = ktime_get_boot_ns();
1890
18c830df
ON
1891 /*
1892 * Make it visible to the rest of the system, but dont wake it up yet.
1893 * Need tasklist lock for parent etc handling!
1894 */
1da177e4
LT
1895 write_lock_irq(&tasklist_lock);
1896
1da177e4 1897 /* CLONE_PARENT re-uses the old parent */
2d5516cb 1898 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
1da177e4 1899 p->real_parent = current->real_parent;
2d5516cb
ON
1900 p->parent_exec_id = current->parent_exec_id;
1901 } else {
1da177e4 1902 p->real_parent = current;
2d5516cb
ON
1903 p->parent_exec_id = current->self_exec_id;
1904 }
1da177e4 1905
d83a7cb3
JP
1906 klp_copy_process(p);
1907
3f17da69 1908 spin_lock(&current->sighand->siglock);
4a2c7a78 1909
dbd95212
KC
1910 /*
1911 * Copy seccomp details explicitly here, in case they were changed
1912 * before holding sighand lock.
1913 */
1914 copy_seccomp(p);
1915
4a2c7a78
ON
1916 /*
1917 * Process group and session signals need to be delivered to just the
1918 * parent before the fork or both the parent and the child after the
1919 * fork. Restart if a signal comes in before we add the new process to
1920 * it's process group.
1921 * A fatal signal pending means that current will exit, so the new
1922 * thread can't slip out of an OOM kill (or normal SIGKILL).
fb0a685c 1923 */
23ff4440 1924 recalc_sigpending();
4a2c7a78 1925 if (signal_pending(current)) {
4a2c7a78 1926 retval = -ERESTARTNOINTR;
7e47682e 1927 goto bad_fork_cancel_cgroup;
4a2c7a78 1928 }
e8cfbc24 1929 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
3fd37226
KT
1930 retval = -ENOMEM;
1931 goto bad_fork_cancel_cgroup;
1932 }
4a2c7a78 1933
73b9ebfe 1934 if (likely(p->pid)) {
4b9d33e6 1935 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
73b9ebfe 1936
81907739 1937 init_task_pid(p, PIDTYPE_PID, pid);
73b9ebfe 1938 if (thread_group_leader(p)) {
81907739
ON
1939 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
1940 init_task_pid(p, PIDTYPE_SID, task_session(current));
1941
1c4042c2 1942 if (is_child_reaper(pid)) {
17cf22c3 1943 ns_of_pid(pid)->child_reaper = p;
1c4042c2
EB
1944 p->signal->flags |= SIGNAL_UNKILLABLE;
1945 }
73b9ebfe 1946
fea9d175 1947 p->signal->leader_pid = pid;
9c9f4ded 1948 p->signal->tty = tty_kref_get(current->signal->tty);
749860ce
PT
1949 /*
1950 * Inherit has_child_subreaper flag under the same
1951 * tasklist_lock with adding child to the process tree
1952 * for propagate_has_child_subreaper optimization.
1953 */
1954 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
1955 p->real_parent->signal->is_child_subreaper;
9cd80bbb 1956 list_add_tail(&p->sibling, &p->real_parent->children);
5e85d4ab 1957 list_add_tail_rcu(&p->tasks, &init_task.tasks);
81907739
ON
1958 attach_pid(p, PIDTYPE_PGID);
1959 attach_pid(p, PIDTYPE_SID);
909ea964 1960 __this_cpu_inc(process_counts);
80628ca0
ON
1961 } else {
1962 current->signal->nr_threads++;
1963 atomic_inc(&current->signal->live);
1964 atomic_inc(&current->signal->sigcnt);
80628ca0
ON
1965 list_add_tail_rcu(&p->thread_group,
1966 &p->group_leader->thread_group);
0c740d0a
ON
1967 list_add_tail_rcu(&p->thread_node,
1968 &p->signal->thread_head);
73b9ebfe 1969 }
81907739 1970 attach_pid(p, PIDTYPE_PID);
73b9ebfe 1971 nr_threads++;
1da177e4
LT
1972 }
1973
1da177e4 1974 total_forks++;
3f17da69 1975 spin_unlock(&current->sighand->siglock);
4af4206b 1976 syscall_tracepoint_update(p);
1da177e4 1977 write_unlock_irq(&tasklist_lock);
4af4206b 1978
c13cf856 1979 proc_fork_connector(p);
b53202e6 1980 cgroup_post_fork(p);
780de9dd 1981 cgroup_threadgroup_change_end(current);
cdd6c482 1982 perf_event_fork(p);
43d2b113
KH
1983
1984 trace_task_newtask(p, clone_flags);
3ab67966 1985 uprobe_copy_process(p, clone_flags);
43d2b113 1986
1da177e4
LT
1987 return p;
1988
7e47682e 1989bad_fork_cancel_cgroup:
3fd37226
KT
1990 spin_unlock(&current->sighand->siglock);
1991 write_unlock_irq(&tasklist_lock);
b53202e6 1992 cgroup_cancel_fork(p);
425fb2b4 1993bad_fork_free_pid:
780de9dd 1994 cgroup_threadgroup_change_end(current);
425fb2b4
PE
1995 if (pid != &init_struct_pid)
1996 free_pid(pid);
0740aa5f
JS
1997bad_fork_cleanup_thread:
1998 exit_thread(p);
fd0928df 1999bad_fork_cleanup_io:
b69f2292
LR
2000 if (p->io_context)
2001 exit_io_context(p);
ab516013 2002bad_fork_cleanup_namespaces:
444f378b 2003 exit_task_namespaces(p);
1da177e4 2004bad_fork_cleanup_mm:
343ef896
AA
2005 if (p->mm) {
2006 mm_clear_owner(p->mm, p);
1da177e4 2007 mmput(p->mm);
343ef896 2008 }
1da177e4 2009bad_fork_cleanup_signal:
4ab6c083 2010 if (!(clone_flags & CLONE_THREAD))
1c5354de 2011 free_signal_struct(p->signal);
1da177e4 2012bad_fork_cleanup_sighand:
a7e5328a 2013 __cleanup_sighand(p->sighand);
1da177e4
LT
2014bad_fork_cleanup_fs:
2015 exit_fs(p); /* blocking */
2016bad_fork_cleanup_files:
2017 exit_files(p); /* blocking */
2018bad_fork_cleanup_semundo:
2019 exit_sem(p);
e4e55b47
TH
2020bad_fork_cleanup_security:
2021 security_task_free(p);
1da177e4
LT
2022bad_fork_cleanup_audit:
2023 audit_free(p);
6c72e350 2024bad_fork_cleanup_perf:
cdd6c482 2025 perf_event_free_task(p);
6c72e350 2026bad_fork_cleanup_policy:
b09be676 2027 lockdep_free_task(p);
1da177e4 2028#ifdef CONFIG_NUMA
f0be3d32 2029 mpol_put(p->mempolicy);
e8604cb4 2030bad_fork_cleanup_threadgroup_lock:
1da177e4 2031#endif
35df17c5 2032 delayacct_tsk_free(p);
1da177e4 2033bad_fork_cleanup_count:
d84f4f99 2034 atomic_dec(&p->cred->user->processes);
e0e81739 2035 exit_creds(p);
1da177e4 2036bad_fork_free:
405c0759 2037 p->state = TASK_DEAD;
68f24b08 2038 put_task_stack(p);
343ef896 2039 delayed_free_task(p);
fe7d37d1
ON
2040fork_out:
2041 return ERR_PTR(retval);
1da177e4
LT
2042}
2043
f106eee1
ON
2044static inline void init_idle_pids(struct pid_link *links)
2045{
2046 enum pid_type type;
2047
2048 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2049 INIT_HLIST_NODE(&links[type].node); /* not really needed */
2050 links[type].pid = &init_struct_pid;
2051 }
2052}
2053
0db0628d 2054struct task_struct *fork_idle(int cpu)
1da177e4 2055{
36c8b586 2056 struct task_struct *task;
725fc629
AK
2057 task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
2058 cpu_to_node(cpu));
f106eee1
ON
2059 if (!IS_ERR(task)) {
2060 init_idle_pids(task->pids);
753ca4f3 2061 init_idle(task, cpu);
f106eee1 2062 }
73b9ebfe 2063
1da177e4
LT
2064 return task;
2065}
2066
1da177e4
LT
2067/*
2068 * Ok, this is the main fork-routine.
2069 *
2070 * It copies the process, and if successful kick-starts
2071 * it and waits for it to finish using the VM if required.
2072 */
3033f14a 2073long _do_fork(unsigned long clone_flags,
1da177e4 2074 unsigned long stack_start,
1da177e4
LT
2075 unsigned long stack_size,
2076 int __user *parent_tidptr,
3033f14a
JT
2077 int __user *child_tidptr,
2078 unsigned long tls)
1da177e4
LT
2079{
2080 struct task_struct *p;
2081 int trace = 0;
92476d7f 2082 long nr;
1da177e4 2083
09a05394 2084 /*
4b9d33e6
TH
2085 * Determine whether and which event to report to ptracer. When
2086 * called from kernel_thread or CLONE_UNTRACED is explicitly
2087 * requested, no event is reported; otherwise, report if the event
2088 * for the type of forking is enabled.
09a05394 2089 */
e80d6661 2090 if (!(clone_flags & CLONE_UNTRACED)) {
4b9d33e6
TH
2091 if (clone_flags & CLONE_VFORK)
2092 trace = PTRACE_EVENT_VFORK;
2093 else if ((clone_flags & CSIGNAL) != SIGCHLD)
2094 trace = PTRACE_EVENT_CLONE;
2095 else
2096 trace = PTRACE_EVENT_FORK;
2097
2098 if (likely(!ptrace_event_enabled(current, trace)))
2099 trace = 0;
2100 }
1da177e4 2101
62e791c1 2102 p = copy_process(clone_flags, stack_start, stack_size,
725fc629 2103 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
38addce8 2104 add_latent_entropy();
1da177e4
LT
2105 /*
2106 * Do this prior waking up the new thread - the thread pointer
2107 * might get invalid after that point, if the thread exits quickly.
2108 */
2109 if (!IS_ERR(p)) {
2110 struct completion vfork;
4e52365f 2111 struct pid *pid;
1da177e4 2112
0a16b607
MD
2113 trace_sched_process_fork(current, p);
2114
4e52365f
MD
2115 pid = get_task_pid(p, PIDTYPE_PID);
2116 nr = pid_vnr(pid);
30e49c26
PE
2117
2118 if (clone_flags & CLONE_PARENT_SETTID)
2119 put_user(nr, parent_tidptr);
a6f5e063 2120
1da177e4
LT
2121 if (clone_flags & CLONE_VFORK) {
2122 p->vfork_done = &vfork;
2123 init_completion(&vfork);
d68b46fe 2124 get_task_struct(p);
1da177e4
LT
2125 }
2126
3e51e3ed 2127 wake_up_new_task(p);
1da177e4 2128
4b9d33e6
TH
2129 /* forking complete and child started to run, tell ptracer */
2130 if (unlikely(trace))
4e52365f 2131 ptrace_event_pid(trace, pid);
09a05394 2132
1da177e4 2133 if (clone_flags & CLONE_VFORK) {
d68b46fe 2134 if (!wait_for_vfork_done(p, &vfork))
4e52365f 2135 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
1da177e4 2136 }
4e52365f
MD
2137
2138 put_pid(pid);
1da177e4 2139 } else {
92476d7f 2140 nr = PTR_ERR(p);
1da177e4 2141 }
92476d7f 2142 return nr;
1da177e4
LT
2143}
2144
3033f14a
JT
2145#ifndef CONFIG_HAVE_COPY_THREAD_TLS
2146/* For compatibility with architectures that call do_fork directly rather than
2147 * using the syscall entry points below. */
2148long do_fork(unsigned long clone_flags,
2149 unsigned long stack_start,
2150 unsigned long stack_size,
2151 int __user *parent_tidptr,
2152 int __user *child_tidptr)
2153{
2154 return _do_fork(clone_flags, stack_start, stack_size,
2155 parent_tidptr, child_tidptr, 0);
2156}
2157#endif
2158
2aa3a7f8
AV
2159/*
2160 * Create a kernel thread.
2161 */
2162pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2163{
3033f14a
JT
2164 return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
2165 (unsigned long)arg, NULL, NULL, 0);
2aa3a7f8 2166}
2aa3a7f8 2167
d2125043
AV
2168#ifdef __ARCH_WANT_SYS_FORK
2169SYSCALL_DEFINE0(fork)
2170{
2171#ifdef CONFIG_MMU
3033f14a 2172 return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
d2125043
AV
2173#else
2174 /* can not support in nommu mode */
5d59e182 2175 return -EINVAL;
d2125043
AV
2176#endif
2177}
2178#endif
2179
2180#ifdef __ARCH_WANT_SYS_VFORK
2181SYSCALL_DEFINE0(vfork)
2182{
3033f14a
JT
2183 return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
2184 0, NULL, NULL, 0);
d2125043
AV
2185}
2186#endif
2187
2188#ifdef __ARCH_WANT_SYS_CLONE
2189#ifdef CONFIG_CLONE_BACKWARDS
2190SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2191 int __user *, parent_tidptr,
3033f14a 2192 unsigned long, tls,
d2125043
AV
2193 int __user *, child_tidptr)
2194#elif defined(CONFIG_CLONE_BACKWARDS2)
2195SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2196 int __user *, parent_tidptr,
2197 int __user *, child_tidptr,
3033f14a 2198 unsigned long, tls)
dfa9771a
MS
2199#elif defined(CONFIG_CLONE_BACKWARDS3)
2200SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2201 int, stack_size,
2202 int __user *, parent_tidptr,
2203 int __user *, child_tidptr,
3033f14a 2204 unsigned long, tls)
d2125043
AV
2205#else
2206SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2207 int __user *, parent_tidptr,
2208 int __user *, child_tidptr,
3033f14a 2209 unsigned long, tls)
d2125043
AV
2210#endif
2211{
3033f14a 2212 return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
d2125043
AV
2213}
2214#endif
2215
0f1b92cb
ON
2216void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2217{
2218 struct task_struct *leader, *parent, *child;
2219 int res;
2220
2221 read_lock(&tasklist_lock);
2222 leader = top = top->group_leader;
2223down:
2224 for_each_thread(leader, parent) {
2225 list_for_each_entry(child, &parent->children, sibling) {
2226 res = visitor(child, data);
2227 if (res) {
2228 if (res < 0)
2229 goto out;
2230 leader = child;
2231 goto down;
2232 }
2233up:
2234 ;
2235 }
2236 }
2237
2238 if (leader != top) {
2239 child = leader;
2240 parent = child->real_parent;
2241 leader = parent->group_leader;
2242 goto up;
2243 }
2244out:
2245 read_unlock(&tasklist_lock);
2246}
2247
5fd63b30
RT
2248#ifndef ARCH_MIN_MMSTRUCT_ALIGN
2249#define ARCH_MIN_MMSTRUCT_ALIGN 0
2250#endif
2251
51cc5068 2252static void sighand_ctor(void *data)
aa1757f9
ON
2253{
2254 struct sighand_struct *sighand = data;
2255
a35afb83 2256 spin_lock_init(&sighand->siglock);
b8fceee1 2257 init_waitqueue_head(&sighand->signalfd_wqh);
aa1757f9
ON
2258}
2259
1da177e4
LT
2260void __init proc_caches_init(void)
2261{
2262 sighand_cachep = kmem_cache_create("sighand_cache",
2263 sizeof(struct sighand_struct), 0,
5f0d5a3a 2264 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
75f296d9 2265 SLAB_ACCOUNT, sighand_ctor);
1da177e4
LT
2266 signal_cachep = kmem_cache_create("signal_cache",
2267 sizeof(struct signal_struct), 0,
75f296d9 2268 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056 2269 NULL);
20c2df83 2270 files_cachep = kmem_cache_create("files_cache",
1da177e4 2271 sizeof(struct files_struct), 0,
75f296d9 2272 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056 2273 NULL);
20c2df83 2274 fs_cachep = kmem_cache_create("fs_cache",
1da177e4 2275 sizeof(struct fs_struct), 0,
75f296d9 2276 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056 2277 NULL);
6345d24d
LT
2278 /*
2279 * FIXME! The "sizeof(struct mm_struct)" currently includes the
2280 * whole struct cpumask for the OFFSTACK case. We could change
2281 * this to *only* allocate as much of it as required by the
2282 * maximum number of CPU's we can ever have. The cpumask_allocation
2283 * is at the end of the structure, exactly for that reason.
2284 */
1da177e4 2285 mm_cachep = kmem_cache_create("mm_struct",
5fd63b30 2286 sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
75f296d9 2287 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
5d097056
VD
2288 NULL);
2289 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
8feae131 2290 mmap_init();
66577193 2291 nsproxy_cache_init();
1da177e4 2292}
cf2e340f 2293
cf2e340f 2294/*
9bfb23fc 2295 * Check constraints on flags passed to the unshare system call.
cf2e340f 2296 */
9bfb23fc 2297static int check_unshare_flags(unsigned long unshare_flags)
cf2e340f 2298{
9bfb23fc
ON
2299 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2300 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
50804fe3 2301 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
a79a908f 2302 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
9bfb23fc 2303 return -EINVAL;
cf2e340f 2304 /*
12c641ab
EB
2305 * Not implemented, but pretend it works if there is nothing
2306 * to unshare. Note that unsharing the address space or the
2307 * signal handlers also need to unshare the signal queues (aka
2308 * CLONE_THREAD).
cf2e340f 2309 */
9bfb23fc 2310 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
12c641ab
EB
2311 if (!thread_group_empty(current))
2312 return -EINVAL;
2313 }
2314 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2315 if (atomic_read(&current->sighand->count) > 1)
2316 return -EINVAL;
2317 }
2318 if (unshare_flags & CLONE_VM) {
2319 if (!current_is_single_threaded())
9bfb23fc
ON
2320 return -EINVAL;
2321 }
cf2e340f
JD
2322
2323 return 0;
2324}
2325
2326/*
99d1419d 2327 * Unshare the filesystem structure if it is being shared
cf2e340f
JD
2328 */
2329static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2330{
2331 struct fs_struct *fs = current->fs;
2332
498052bb
AV
2333 if (!(unshare_flags & CLONE_FS) || !fs)
2334 return 0;
2335
2336 /* don't need lock here; in the worst case we'll do useless copy */
2337 if (fs->users == 1)
2338 return 0;
2339
2340 *new_fsp = copy_fs_struct(fs);
2341 if (!*new_fsp)
2342 return -ENOMEM;
cf2e340f
JD
2343
2344 return 0;
2345}
2346
cf2e340f 2347/*
a016f338 2348 * Unshare file descriptor table if it is being shared
cf2e340f
JD
2349 */
2350static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2351{
2352 struct files_struct *fd = current->files;
a016f338 2353 int error = 0;
cf2e340f
JD
2354
2355 if ((unshare_flags & CLONE_FILES) &&
a016f338
JD
2356 (fd && atomic_read(&fd->count) > 1)) {
2357 *new_fdp = dup_fd(fd, &error);
2358 if (!*new_fdp)
2359 return error;
2360 }
cf2e340f
JD
2361
2362 return 0;
2363}
2364
cf2e340f
JD
2365/*
2366 * unshare allows a process to 'unshare' part of the process
2367 * context which was originally shared using clone. copy_*
2368 * functions used by do_fork() cannot be used here directly
2369 * because they modify an inactive task_struct that is being
2370 * constructed. Here we are modifying the current, active,
2371 * task_struct.
2372 */
6559eed8 2373SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
cf2e340f 2374{
cf2e340f 2375 struct fs_struct *fs, *new_fs = NULL;
cf2e340f 2376 struct files_struct *fd, *new_fd = NULL;
b2e0d987 2377 struct cred *new_cred = NULL;
cf7b708c 2378 struct nsproxy *new_nsproxy = NULL;
9edff4ab 2379 int do_sysvsem = 0;
9bfb23fc 2380 int err;
cf2e340f 2381
b2e0d987 2382 /*
faf00da5
EB
2383 * If unsharing a user namespace must also unshare the thread group
2384 * and unshare the filesystem root and working directories.
b2e0d987
EB
2385 */
2386 if (unshare_flags & CLONE_NEWUSER)
e66eded8 2387 unshare_flags |= CLONE_THREAD | CLONE_FS;
50804fe3
EB
2388 /*
2389 * If unsharing vm, must also unshare signal handlers.
2390 */
2391 if (unshare_flags & CLONE_VM)
2392 unshare_flags |= CLONE_SIGHAND;
12c641ab
EB
2393 /*
2394 * If unsharing a signal handlers, must also unshare the signal queues.
2395 */
2396 if (unshare_flags & CLONE_SIGHAND)
2397 unshare_flags |= CLONE_THREAD;
9bfb23fc
ON
2398 /*
2399 * If unsharing namespace, must also unshare filesystem information.
2400 */
2401 if (unshare_flags & CLONE_NEWNS)
2402 unshare_flags |= CLONE_FS;
50804fe3 2403
680f7875
SH
2404 if ((unshare_flags & CLONE_NEWUSER) && !unprivileged_userns_clone) {
2405 err = -EPERM;
2406 if (!capable(CAP_SYS_ADMIN))
2407 goto bad_unshare_out;
2408 }
2409
50804fe3
EB
2410 err = check_unshare_flags(unshare_flags);
2411 if (err)
2412 goto bad_unshare_out;
6013f67f
MS
2413 /*
2414 * CLONE_NEWIPC must also detach from the undolist: after switching
2415 * to a new ipc namespace, the semaphore arrays from the old
2416 * namespace are unreachable.
2417 */
2418 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
9edff4ab 2419 do_sysvsem = 1;
fb0a685c
DRO
2420 err = unshare_fs(unshare_flags, &new_fs);
2421 if (err)
9bfb23fc 2422 goto bad_unshare_out;
fb0a685c
DRO
2423 err = unshare_fd(unshare_flags, &new_fd);
2424 if (err)
9bfb23fc 2425 goto bad_unshare_cleanup_fs;
b2e0d987 2426 err = unshare_userns(unshare_flags, &new_cred);
fb0a685c 2427 if (err)
9edff4ab 2428 goto bad_unshare_cleanup_fd;
b2e0d987
EB
2429 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2430 new_cred, new_fs);
2431 if (err)
2432 goto bad_unshare_cleanup_cred;
c0b2fc31 2433
b2e0d987 2434 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
9edff4ab
MS
2435 if (do_sysvsem) {
2436 /*
2437 * CLONE_SYSVSEM is equivalent to sys_exit().
2438 */
2439 exit_sem(current);
2440 }
ab602f79
JM
2441 if (unshare_flags & CLONE_NEWIPC) {
2442 /* Orphan segments in old ns (see sem above). */
2443 exit_shm(current);
2444 shm_init_task(current);
2445 }
ab516013 2446
6f977e6b 2447 if (new_nsproxy)
cf7b708c 2448 switch_task_namespaces(current, new_nsproxy);
cf2e340f 2449
cf7b708c
PE
2450 task_lock(current);
2451
cf2e340f
JD
2452 if (new_fs) {
2453 fs = current->fs;
2a4419b5 2454 spin_lock(&fs->lock);
cf2e340f 2455 current->fs = new_fs;
498052bb
AV
2456 if (--fs->users)
2457 new_fs = NULL;
2458 else
2459 new_fs = fs;
2a4419b5 2460 spin_unlock(&fs->lock);
cf2e340f
JD
2461 }
2462
cf2e340f
JD
2463 if (new_fd) {
2464 fd = current->files;
2465 current->files = new_fd;
2466 new_fd = fd;
2467 }
2468
2469 task_unlock(current);
b2e0d987
EB
2470
2471 if (new_cred) {
2472 /* Install the new user namespace */
2473 commit_creds(new_cred);
2474 new_cred = NULL;
2475 }
cf2e340f
JD
2476 }
2477
e4222673
HB
2478 perf_event_namespaces(current);
2479
b2e0d987
EB
2480bad_unshare_cleanup_cred:
2481 if (new_cred)
2482 put_cred(new_cred);
cf2e340f
JD
2483bad_unshare_cleanup_fd:
2484 if (new_fd)
2485 put_files_struct(new_fd);
2486
cf2e340f
JD
2487bad_unshare_cleanup_fs:
2488 if (new_fs)
498052bb 2489 free_fs_struct(new_fs);
cf2e340f 2490
cf2e340f
JD
2491bad_unshare_out:
2492 return err;
2493}
3b125388
AV
2494
2495/*
2496 * Helper to unshare the files of the current task.
2497 * We don't want to expose copy_files internals to
2498 * the exec layer of the kernel.
2499 */
2500
2501int unshare_files(struct files_struct **displaced)
2502{
2503 struct task_struct *task = current;
50704516 2504 struct files_struct *copy = NULL;
3b125388
AV
2505 int error;
2506
2507 error = unshare_fd(CLONE_FILES, &copy);
2508 if (error || !copy) {
2509 *displaced = NULL;
2510 return error;
2511 }
2512 *displaced = task->files;
2513 task_lock(task);
2514 task->files = copy;
2515 task_unlock(task);
2516 return 0;
2517}
16db3d3f
HS
2518
2519int sysctl_max_threads(struct ctl_table *table, int write,
2520 void __user *buffer, size_t *lenp, loff_t *ppos)
2521{
2522 struct ctl_table t;
2523 int ret;
2524 int threads = max_threads;
eb3794c5 2525 int min = 1;
16db3d3f
HS
2526 int max = MAX_THREADS;
2527
2528 t = *table;
2529 t.data = &threads;
2530 t.extra1 = &min;
2531 t.extra2 = &max;
2532
2533 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2534 if (ret || !write)
2535 return ret;
2536
eb3794c5 2537 max_threads = threads;
16db3d3f
HS
2538
2539 return 0;
2540}