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