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