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