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