1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/kernel/fork.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 */
7
8 /*
9 * 'fork.c' contains the help-routines for the 'fork' system call
10 * (see also entry.S and others).
11 * Fork is rather simple, once you get the hang of it, but the memory
12 * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
13 */
14
15 #include <linux/anon_inodes.h>
16 #include <linux/slab.h>
17 #include <linux/sched/autogroup.h>
18 #include <linux/sched/mm.h>
19 #include <linux/sched/coredump.h>
20 #include <linux/sched/user.h>
21 #include <linux/sched/numa_balancing.h>
22 #include <linux/sched/stat.h>
23 #include <linux/sched/task.h>
24 #include <linux/sched/task_stack.h>
25 #include <linux/sched/cputime.h>
26 #include <linux/seq_file.h>
27 #include <linux/rtmutex.h>
28 #include <linux/init.h>
29 #include <linux/unistd.h>
30 #include <linux/module.h>
31 #include <linux/vmalloc.h>
32 #include <linux/completion.h>
33 #include <linux/personality.h>
34 #include <linux/mempolicy.h>
35 #include <linux/sem.h>
36 #include <linux/file.h>
37 #include <linux/fdtable.h>
38 #include <linux/iocontext.h>
39 #include <linux/key.h>
40 #include <linux/kmsan.h>
41 #include <linux/binfmts.h>
42 #include <linux/mman.h>
43 #include <linux/mmu_notifier.h>
44 #include <linux/fs.h>
45 #include <linux/mm.h>
46 #include <linux/mm_inline.h>
47 #include <linux/nsproxy.h>
48 #include <linux/capability.h>
49 #include <linux/cpu.h>
50 #include <linux/cgroup.h>
51 #include <linux/security.h>
52 #include <linux/hugetlb.h>
53 #include <linux/seccomp.h>
54 #include <linux/swap.h>
55 #include <linux/syscalls.h>
56 #include <linux/jiffies.h>
57 #include <linux/futex.h>
58 #include <linux/compat.h>
59 #include <linux/kthread.h>
60 #include <linux/task_io_accounting_ops.h>
61 #include <linux/rcupdate.h>
62 #include <linux/ptrace.h>
63 #include <linux/mount.h>
64 #include <linux/audit.h>
65 #include <linux/memcontrol.h>
66 #include <linux/ftrace.h>
67 #include <linux/proc_fs.h>
68 #include <linux/profile.h>
69 #include <linux/rmap.h>
70 #include <linux/ksm.h>
71 #include <linux/acct.h>
72 #include <linux/userfaultfd_k.h>
73 #include <linux/tsacct_kern.h>
74 #include <linux/cn_proc.h>
75 #include <linux/freezer.h>
76 #include <linux/delayacct.h>
77 #include <linux/taskstats_kern.h>
78 #include <linux/random.h>
79 #include <linux/tty.h>
80 #include <linux/fs_struct.h>
81 #include <linux/magic.h>
82 #include <linux/perf_event.h>
83 #include <linux/posix-timers.h>
84 #include <linux/user-return-notifier.h>
85 #include <linux/oom.h>
86 #include <linux/khugepaged.h>
87 #include <linux/signalfd.h>
88 #include <linux/uprobes.h>
89 #include <linux/aio.h>
90 #include <linux/compiler.h>
91 #include <linux/sysctl.h>
92 #include <linux/kcov.h>
93 #include <linux/livepatch.h>
94 #include <linux/thread_info.h>
95 #include <linux/stackleak.h>
96 #include <linux/kasan.h>
97 #include <linux/scs.h>
98 #include <linux/io_uring.h>
99 #include <linux/bpf.h>
100 #include <linux/cpufreq_times.h>
101
102 #include <asm/pgalloc.h>
103 #include <linux/uaccess.h>
104 #include <asm/mmu_context.h>
105 #include <asm/cacheflush.h>
106 #include <asm/tlbflush.h>
107
108 #include <trace/events/sched.h>
109
110 #define CREATE_TRACE_POINTS
111 #include <trace/events/task.h>
112
113 #undef CREATE_TRACE_POINTS
114 #include <trace/hooks/sched.h>
115 /*
116 * Minimum number of threads to boot the kernel
117 */
118 #define MIN_THREADS 20
119
120 /*
121 * Maximum number of threads
122 */
123 #define MAX_THREADS FUTEX_TID_MASK
124
125 EXPORT_TRACEPOINT_SYMBOL_GPL(task_newtask);
126 EXPORT_TRACEPOINT_SYMBOL_GPL(task_rename);
127
128 /*
129 * Protected counters by write_lock_irq(&tasklist_lock)
130 */
131 unsigned long total_forks; /* Handle normal Linux uptimes. */
132 int nr_threads; /* The idle threads do not count.. */
133
134 static int max_threads; /* tunable limit on nr_threads */
135
136 #define NAMED_ARRAY_INDEX(x) [x] = __stringify(x)
137
138 static const char * const resident_page_types[] = {
139 NAMED_ARRAY_INDEX(MM_FILEPAGES),
140 NAMED_ARRAY_INDEX(MM_ANONPAGES),
141 NAMED_ARRAY_INDEX(MM_SWAPENTS),
142 NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
143 };
144
145 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
146
147 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
148 EXPORT_SYMBOL_GPL(tasklist_lock);
149
150 #ifdef CONFIG_PROVE_RCU
lockdep_tasklist_lock_is_held(void)151 int lockdep_tasklist_lock_is_held(void)
152 {
153 return lockdep_is_held(&tasklist_lock);
154 }
155 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
156 #endif /* #ifdef CONFIG_PROVE_RCU */
157
nr_processes(void)158 int nr_processes(void)
159 {
160 int cpu;
161 int total = 0;
162
163 for_each_possible_cpu(cpu)
164 total += per_cpu(process_counts, cpu);
165
166 return total;
167 }
168
arch_release_task_struct(struct task_struct * tsk)169 void __weak arch_release_task_struct(struct task_struct *tsk)
170 {
171 }
172
173 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
174 static struct kmem_cache *task_struct_cachep;
175
alloc_task_struct_node(int node)176 static inline struct task_struct *alloc_task_struct_node(int node)
177 {
178 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
179 }
180
free_task_struct(struct task_struct * tsk)181 static inline void free_task_struct(struct task_struct *tsk)
182 {
183 kmem_cache_free(task_struct_cachep, tsk);
184 }
185 #endif
186
187 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
188
189 /*
190 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
191 * kmemcache based allocator.
192 */
193 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
194
195 # ifdef CONFIG_VMAP_STACK
196 /*
197 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
198 * flush. Try to minimize the number of calls by caching stacks.
199 */
200 #define NR_CACHED_STACKS 2
201 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
202
203 struct vm_stack {
204 struct rcu_head rcu;
205 struct vm_struct *stack_vm_area;
206 };
207
try_release_thread_stack_to_cache(struct vm_struct * vm)208 static bool try_release_thread_stack_to_cache(struct vm_struct *vm)
209 {
210 unsigned int i;
211
212 for (i = 0; i < NR_CACHED_STACKS; i++) {
213 if (this_cpu_cmpxchg(cached_stacks[i], NULL, vm) != NULL)
214 continue;
215 return true;
216 }
217 return false;
218 }
219
thread_stack_free_rcu(struct rcu_head * rh)220 static void thread_stack_free_rcu(struct rcu_head *rh)
221 {
222 struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu);
223
224 if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area))
225 return;
226
227 vfree(vm_stack);
228 }
229
thread_stack_delayed_free(struct task_struct * tsk)230 static void thread_stack_delayed_free(struct task_struct *tsk)
231 {
232 struct vm_stack *vm_stack = tsk->stack;
233
234 vm_stack->stack_vm_area = tsk->stack_vm_area;
235 call_rcu(&vm_stack->rcu, thread_stack_free_rcu);
236 }
237
free_vm_stack_cache(unsigned int cpu)238 static int free_vm_stack_cache(unsigned int cpu)
239 {
240 struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
241 int i;
242
243 for (i = 0; i < NR_CACHED_STACKS; i++) {
244 struct vm_struct *vm_stack = cached_vm_stacks[i];
245
246 if (!vm_stack)
247 continue;
248
249 vfree(vm_stack->addr);
250 cached_vm_stacks[i] = NULL;
251 }
252
253 return 0;
254 }
255
memcg_charge_kernel_stack(struct vm_struct * vm)256 static int memcg_charge_kernel_stack(struct vm_struct *vm)
257 {
258 int i;
259 int ret;
260
261 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
262 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
263
264 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
265 ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
266 if (ret)
267 goto err;
268 }
269 return 0;
270 err:
271 /*
272 * If memcg_kmem_charge_page() fails, page's memory cgroup pointer is
273 * NULL, and memcg_kmem_uncharge_page() in free_thread_stack() will
274 * ignore this page.
275 */
276 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
277 memcg_kmem_uncharge_page(vm->pages[i], 0);
278 return ret;
279 }
280
alloc_thread_stack_node(struct task_struct * tsk,int node)281 static int alloc_thread_stack_node(struct task_struct *tsk, int node)
282 {
283 struct vm_struct *vm;
284 void *stack;
285 int i;
286
287 for (i = 0; i < NR_CACHED_STACKS; i++) {
288 struct vm_struct *s;
289
290 s = this_cpu_xchg(cached_stacks[i], NULL);
291
292 if (!s)
293 continue;
294
295 /* Reset stack metadata. */
296 kasan_unpoison_range(s->addr, THREAD_SIZE);
297
298 stack = kasan_reset_tag(s->addr);
299
300 /* Clear stale pointers from reused stack. */
301 memset(stack, 0, THREAD_SIZE);
302
303 if (memcg_charge_kernel_stack(s)) {
304 vfree(s->addr);
305 return -ENOMEM;
306 }
307
308 tsk->stack_vm_area = s;
309 tsk->stack = stack;
310 return 0;
311 }
312
313 /*
314 * Allocated stacks are cached and later reused by new threads,
315 * so memcg accounting is performed manually on assigning/releasing
316 * stacks to tasks. Drop __GFP_ACCOUNT.
317 */
318 stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
319 VMALLOC_START, VMALLOC_END,
320 THREADINFO_GFP & ~__GFP_ACCOUNT,
321 PAGE_KERNEL,
322 0, node, __builtin_return_address(0));
323 if (!stack)
324 return -ENOMEM;
325
326 vm = find_vm_area(stack);
327 if (memcg_charge_kernel_stack(vm)) {
328 vfree(stack);
329 return -ENOMEM;
330 }
331 /*
332 * We can't call find_vm_area() in interrupt context, and
333 * free_thread_stack() can be called in interrupt context,
334 * so cache the vm_struct.
335 */
336 tsk->stack_vm_area = vm;
337 stack = kasan_reset_tag(stack);
338 tsk->stack = stack;
339 return 0;
340 }
341
free_thread_stack(struct task_struct * tsk)342 static void free_thread_stack(struct task_struct *tsk)
343 {
344 if (!try_release_thread_stack_to_cache(tsk->stack_vm_area))
345 thread_stack_delayed_free(tsk);
346
347 tsk->stack = NULL;
348 tsk->stack_vm_area = NULL;
349 }
350
351 # else /* !CONFIG_VMAP_STACK */
352
thread_stack_free_rcu(struct rcu_head * rh)353 static void thread_stack_free_rcu(struct rcu_head *rh)
354 {
355 __free_pages(virt_to_page(rh), THREAD_SIZE_ORDER);
356 }
357
thread_stack_delayed_free(struct task_struct * tsk)358 static void thread_stack_delayed_free(struct task_struct *tsk)
359 {
360 struct rcu_head *rh = tsk->stack;
361
362 call_rcu(rh, thread_stack_free_rcu);
363 }
364
alloc_thread_stack_node(struct task_struct * tsk,int node)365 static int alloc_thread_stack_node(struct task_struct *tsk, int node)
366 {
367 struct page *page = alloc_pages_node(node, THREADINFO_GFP,
368 THREAD_SIZE_ORDER);
369
370 if (likely(page)) {
371 tsk->stack = kasan_reset_tag(page_address(page));
372 return 0;
373 }
374 return -ENOMEM;
375 }
376
free_thread_stack(struct task_struct * tsk)377 static void free_thread_stack(struct task_struct *tsk)
378 {
379 thread_stack_delayed_free(tsk);
380 tsk->stack = NULL;
381 }
382
383 # endif /* CONFIG_VMAP_STACK */
384 # else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
385
386 static struct kmem_cache *thread_stack_cache;
387
thread_stack_free_rcu(struct rcu_head * rh)388 static void thread_stack_free_rcu(struct rcu_head *rh)
389 {
390 kmem_cache_free(thread_stack_cache, rh);
391 }
392
thread_stack_delayed_free(struct task_struct * tsk)393 static void thread_stack_delayed_free(struct task_struct *tsk)
394 {
395 struct rcu_head *rh = tsk->stack;
396
397 call_rcu(rh, thread_stack_free_rcu);
398 }
399
alloc_thread_stack_node(struct task_struct * tsk,int node)400 static int alloc_thread_stack_node(struct task_struct *tsk, int node)
401 {
402 unsigned long *stack;
403 stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
404 stack = kasan_reset_tag(stack);
405 tsk->stack = stack;
406 return stack ? 0 : -ENOMEM;
407 }
408
free_thread_stack(struct task_struct * tsk)409 static void free_thread_stack(struct task_struct *tsk)
410 {
411 thread_stack_delayed_free(tsk);
412 tsk->stack = NULL;
413 }
414
thread_stack_cache_init(void)415 void thread_stack_cache_init(void)
416 {
417 thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
418 THREAD_SIZE, THREAD_SIZE, 0, 0,
419 THREAD_SIZE, NULL);
420 BUG_ON(thread_stack_cache == NULL);
421 }
422
423 # endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
424 #else /* CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
425
alloc_thread_stack_node(struct task_struct * tsk,int node)426 static int alloc_thread_stack_node(struct task_struct *tsk, int node)
427 {
428 unsigned long *stack;
429
430 stack = arch_alloc_thread_stack_node(tsk, node);
431 tsk->stack = stack;
432 return stack ? 0 : -ENOMEM;
433 }
434
free_thread_stack(struct task_struct * tsk)435 static void free_thread_stack(struct task_struct *tsk)
436 {
437 arch_free_thread_stack(tsk);
438 tsk->stack = NULL;
439 }
440
441 #endif /* !CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
442
443 /* SLAB cache for signal_struct structures (tsk->signal) */
444 static struct kmem_cache *signal_cachep;
445
446 /* SLAB cache for sighand_struct structures (tsk->sighand) */
447 struct kmem_cache *sighand_cachep;
448
449 /* SLAB cache for files_struct structures (tsk->files) */
450 struct kmem_cache *files_cachep;
451
452 /* SLAB cache for fs_struct structures (tsk->fs) */
453 struct kmem_cache *fs_cachep;
454
455 /* SLAB cache for vm_area_struct structures */
456 static struct kmem_cache *vm_area_cachep;
457
458 /* SLAB cache for mm_struct structures (tsk->mm) */
459 static struct kmem_cache *mm_cachep;
460
461 #ifdef CONFIG_PER_VMA_LOCK
462
463 /* SLAB cache for vm_area_struct.lock */
464 static struct kmem_cache *vma_lock_cachep;
465
vma_lock_alloc(struct vm_area_struct * vma)466 static bool vma_lock_alloc(struct vm_area_struct *vma)
467 {
468 vma->vm_lock = kmem_cache_alloc(vma_lock_cachep, GFP_KERNEL);
469 if (!vma->vm_lock)
470 return false;
471
472 init_rwsem(&vma->vm_lock->lock);
473 vma->vm_lock_seq = -1;
474
475 return true;
476 }
477
vma_lock_free(struct vm_area_struct * vma)478 static inline void vma_lock_free(struct vm_area_struct *vma)
479 {
480 kmem_cache_free(vma_lock_cachep, vma->vm_lock);
481 }
482
483 #else /* CONFIG_PER_VMA_LOCK */
484
vma_lock_alloc(struct vm_area_struct * vma)485 static inline bool vma_lock_alloc(struct vm_area_struct *vma) { return true; }
vma_lock_free(struct vm_area_struct * vma)486 static inline void vma_lock_free(struct vm_area_struct *vma) {}
487
488 #endif /* CONFIG_PER_VMA_LOCK */
489
vm_area_alloc(struct mm_struct * mm)490 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
491 {
492 struct vm_area_struct *vma;
493
494 vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
495 if (!vma)
496 return NULL;
497
498 vma_init(vma, mm);
499 if (!vma_lock_alloc(vma)) {
500 kmem_cache_free(vm_area_cachep, vma);
501 return NULL;
502 }
503
504 return vma;
505 }
506
vm_area_dup(struct vm_area_struct * orig)507 struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
508 {
509 struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
510
511 if (!new)
512 return NULL;
513
514 ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
515 ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
516 /*
517 * orig->shared.rb may be modified concurrently, but the clone
518 * will be reinitialized.
519 */
520 data_race(memcpy(new, orig, sizeof(*new)));
521 if (!vma_lock_alloc(new)) {
522 kmem_cache_free(vm_area_cachep, new);
523 return NULL;
524 }
525 INIT_LIST_HEAD(&new->anon_vma_chain);
526 dup_anon_vma_name(orig, new);
527
528 return new;
529 }
530
__vm_area_free(struct vm_area_struct * vma)531 void __vm_area_free(struct vm_area_struct *vma)
532 {
533 free_anon_vma_name(vma);
534 vma_lock_free(vma);
535 kmem_cache_free(vm_area_cachep, vma);
536 }
537
538 #ifdef CONFIG_PER_VMA_LOCK
vm_area_free_rcu_cb(struct rcu_head * head)539 static void vm_area_free_rcu_cb(struct rcu_head *head)
540 {
541 struct vm_area_struct *vma = container_of(head, struct vm_area_struct,
542 vm_rcu);
543
544 /* The vma should not be locked while being destroyed. */
545 VM_BUG_ON_VMA(rwsem_is_locked(&vma->vm_lock->lock), vma);
546 __vm_area_free(vma);
547 }
548 #endif
549
vm_area_free(struct vm_area_struct * vma)550 void vm_area_free(struct vm_area_struct *vma)
551 {
552 #ifdef CONFIG_PER_VMA_LOCK
553 call_rcu(&vma->vm_rcu, vm_area_free_rcu_cb);
554 #else
555 __vm_area_free(vma);
556 #endif
557 }
558
account_kernel_stack(struct task_struct * tsk,int account)559 static void account_kernel_stack(struct task_struct *tsk, int account)
560 {
561 if (IS_ENABLED(CONFIG_VMAP_STACK)) {
562 struct vm_struct *vm = task_stack_vm_area(tsk);
563 int i;
564
565 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
566 mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
567 account * (PAGE_SIZE / 1024));
568 } else {
569 void *stack = task_stack_page(tsk);
570
571 /* All stack pages are in the same node. */
572 mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
573 account * (THREAD_SIZE / 1024));
574 }
575 }
576
exit_task_stack_account(struct task_struct * tsk)577 void exit_task_stack_account(struct task_struct *tsk)
578 {
579 account_kernel_stack(tsk, -1);
580
581 if (IS_ENABLED(CONFIG_VMAP_STACK)) {
582 struct vm_struct *vm;
583 int i;
584
585 vm = task_stack_vm_area(tsk);
586 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
587 memcg_kmem_uncharge_page(vm->pages[i], 0);
588 }
589 }
590
release_task_stack(struct task_struct * tsk)591 static void release_task_stack(struct task_struct *tsk)
592 {
593 if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
594 return; /* Better to leak the stack than to free prematurely */
595
596 free_thread_stack(tsk);
597 }
598
599 #ifdef CONFIG_THREAD_INFO_IN_TASK
put_task_stack(struct task_struct * tsk)600 void put_task_stack(struct task_struct *tsk)
601 {
602 if (refcount_dec_and_test(&tsk->stack_refcount))
603 release_task_stack(tsk);
604 }
605 #endif
606
free_task(struct task_struct * tsk)607 void free_task(struct task_struct *tsk)
608 {
609 #ifdef CONFIG_SECCOMP
610 WARN_ON_ONCE(tsk->seccomp.filter);
611 #endif
612 cpufreq_task_times_exit(tsk);
613 release_user_cpus_ptr(tsk);
614 scs_release(tsk);
615
616 trace_android_vh_free_task(tsk);
617 #ifndef CONFIG_THREAD_INFO_IN_TASK
618 /*
619 * The task is finally done with both the stack and thread_info,
620 * so free both.
621 */
622 release_task_stack(tsk);
623 #else
624 /*
625 * If the task had a separate stack allocation, it should be gone
626 * by now.
627 */
628 WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
629 #endif
630 rt_mutex_debug_task_free(tsk);
631 ftrace_graph_exit_task(tsk);
632 arch_release_task_struct(tsk);
633 if (tsk->flags & PF_KTHREAD)
634 free_kthread_struct(tsk);
635 bpf_task_storage_free(tsk);
636 free_task_struct(tsk);
637 }
638 EXPORT_SYMBOL(free_task);
639
dup_mm_exe_file(struct mm_struct * mm,struct mm_struct * oldmm)640 static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
641 {
642 struct file *exe_file;
643
644 exe_file = get_mm_exe_file(oldmm);
645 RCU_INIT_POINTER(mm->exe_file, exe_file);
646 /*
647 * We depend on the oldmm having properly denied write access to the
648 * exe_file already.
649 */
650 if (exe_file && deny_write_access(exe_file))
651 pr_warn_once("deny_write_access() failed in %s\n", __func__);
652 }
653
654 #ifdef CONFIG_MMU
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)655 static __latent_entropy int dup_mmap(struct mm_struct *mm,
656 struct mm_struct *oldmm)
657 {
658 struct vm_area_struct *mpnt, *tmp;
659 int retval;
660 unsigned long charge = 0;
661 LIST_HEAD(uf);
662 MA_STATE(mas, &mm->mm_mt, 0, 0);
663
664 uprobe_start_dup_mmap();
665 if (mmap_write_lock_killable(oldmm)) {
666 retval = -EINTR;
667 goto fail_uprobe_end;
668 }
669 flush_cache_dup_mm(oldmm);
670 uprobe_dup_mmap(oldmm, mm);
671 /*
672 * Not linked in yet - no deadlock potential:
673 */
674 mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
675
676 /* No ordering required: file already has been exposed. */
677 dup_mm_exe_file(mm, oldmm);
678
679 mm->total_vm = oldmm->total_vm;
680 mm->data_vm = oldmm->data_vm;
681 mm->exec_vm = oldmm->exec_vm;
682 mm->stack_vm = oldmm->stack_vm;
683
684 retval = ksm_fork(mm, oldmm);
685 if (retval)
686 goto out;
687 khugepaged_fork(mm, oldmm);
688
689 /* Use __mt_dup() to efficiently build an identical maple tree. */
690 retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
691 if (unlikely(retval))
692 goto out;
693
694 mt_clear_in_rcu(mas.tree);
695 mas_for_each(&mas, mpnt, ULONG_MAX) {
696 struct file *file;
697
698 vma_start_write(mpnt);
699 if (mpnt->vm_flags & VM_DONTCOPY) {
700 __mas_set_range(&mas, mpnt->vm_start, mpnt->vm_end - 1);
701 mas_store_gfp(&mas, NULL, GFP_KERNEL);
702 if (unlikely(mas_is_err(&mas))) {
703 retval = -ENOMEM;
704 goto loop_out;
705 }
706 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
707 continue;
708 }
709 charge = 0;
710 /*
711 * Don't duplicate many vmas if we've been oom-killed (for
712 * example)
713 */
714 if (fatal_signal_pending(current)) {
715 retval = -EINTR;
716 goto loop_out;
717 }
718 if (mpnt->vm_flags & VM_ACCOUNT) {
719 unsigned long len = vma_pages(mpnt);
720
721 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
722 goto fail_nomem;
723 charge = len;
724 }
725 tmp = vm_area_dup(mpnt);
726 if (!tmp)
727 goto fail_nomem;
728 retval = vma_dup_policy(mpnt, tmp);
729 if (retval)
730 goto fail_nomem_policy;
731 tmp->vm_mm = mm;
732 retval = dup_userfaultfd(tmp, &uf);
733 if (retval)
734 goto fail_nomem_anon_vma_fork;
735 if (tmp->vm_flags & VM_WIPEONFORK) {
736 /*
737 * VM_WIPEONFORK gets a clean slate in the child.
738 * Don't prepare anon_vma until fault since we don't
739 * copy page for current vma.
740 */
741 tmp->anon_vma = NULL;
742 } else if (anon_vma_fork(tmp, mpnt))
743 goto fail_nomem_anon_vma_fork;
744 vm_flags_clear(tmp, VM_LOCKED_MASK);
745 file = tmp->vm_file;
746 if (file) {
747 struct address_space *mapping = file->f_mapping;
748
749 get_file(file);
750 i_mmap_lock_write(mapping);
751 if (tmp->vm_flags & VM_SHARED)
752 mapping_allow_writable(mapping);
753 flush_dcache_mmap_lock(mapping);
754 /* insert tmp into the share list, just after mpnt */
755 vma_interval_tree_insert_after(tmp, mpnt,
756 &mapping->i_mmap);
757 flush_dcache_mmap_unlock(mapping);
758 i_mmap_unlock_write(mapping);
759 }
760
761 /*
762 * Copy/update hugetlb private vma information.
763 */
764 if (is_vm_hugetlb_page(tmp))
765 hugetlb_dup_vma_private(tmp);
766
767 /*
768 * Link the vma into the MT. After using __mt_dup(), memory
769 * allocation is not necessary here, so it cannot fail.
770 */
771 mas.index = tmp->vm_start;
772 mas.last = tmp->vm_end - 1;
773 mas_store(&mas, tmp);
774
775 mm->map_count++;
776 if (!(tmp->vm_flags & VM_WIPEONFORK))
777 retval = copy_page_range(tmp, mpnt);
778
779 if (tmp->vm_ops && tmp->vm_ops->open)
780 tmp->vm_ops->open(tmp);
781
782 if (retval) {
783 mpnt = mas_find(&mas, ULONG_MAX);
784 goto loop_out;
785 }
786 }
787 /* a new mm has just been created */
788 retval = arch_dup_mmap(oldmm, mm);
789 loop_out:
790 mas_destroy(&mas);
791 if (!retval) {
792 mt_set_in_rcu(mas.tree);
793 } else if (mpnt) {
794 /*
795 * The entire maple tree has already been duplicated. If the
796 * mmap duplication fails, mark the failure point with
797 * XA_ZERO_ENTRY. In exit_mmap(), if this marker is encountered,
798 * stop releasing VMAs that have not been duplicated after this
799 * point.
800 */
801 mas_set_range(&mas, mpnt->vm_start, mpnt->vm_end - 1);
802 mas_store(&mas, XA_ZERO_ENTRY);
803 }
804 out:
805 mmap_write_unlock(mm);
806 flush_tlb_mm(oldmm);
807 mmap_write_unlock(oldmm);
808 dup_userfaultfd_complete(&uf);
809 fail_uprobe_end:
810 uprobe_end_dup_mmap();
811 return retval;
812
813 fail_nomem_anon_vma_fork:
814 mpol_put(vma_policy(tmp));
815 fail_nomem_policy:
816 vm_area_free(tmp);
817 fail_nomem:
818 retval = -ENOMEM;
819 vm_unacct_memory(charge);
820 goto loop_out;
821 }
822
mm_alloc_pgd(struct mm_struct * mm)823 static inline int mm_alloc_pgd(struct mm_struct *mm)
824 {
825 mm->pgd = pgd_alloc(mm);
826 if (unlikely(!mm->pgd))
827 return -ENOMEM;
828 return 0;
829 }
830
mm_free_pgd(struct mm_struct * mm)831 static inline void mm_free_pgd(struct mm_struct *mm)
832 {
833 pgd_free(mm, mm->pgd);
834 }
835 #else
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)836 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
837 {
838 mmap_write_lock(oldmm);
839 dup_mm_exe_file(mm, oldmm);
840 mmap_write_unlock(oldmm);
841 return 0;
842 }
843 #define mm_alloc_pgd(mm) (0)
844 #define mm_free_pgd(mm)
845 #endif /* CONFIG_MMU */
846
check_mm(struct mm_struct * mm)847 static void check_mm(struct mm_struct *mm)
848 {
849 int i;
850
851 BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
852 "Please make sure 'struct resident_page_types[]' is updated as well");
853
854 for (i = 0; i < NR_MM_COUNTERS; i++) {
855 long x = atomic_long_read(&mm->rss_stat.count[i]);
856
857 if (unlikely(x))
858 pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
859 mm, resident_page_types[i], x);
860 }
861
862 if (mm_pgtables_bytes(mm))
863 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
864 mm_pgtables_bytes(mm));
865
866 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
867 VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
868 #endif
869 }
870
871 #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
872 #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
873
874 /*
875 * Called when the last reference to the mm
876 * is dropped: either by a lazy thread or by
877 * mmput. Free the page directory and the mm.
878 */
__mmdrop(struct mm_struct * mm)879 void __mmdrop(struct mm_struct *mm)
880 {
881 BUG_ON(mm == &init_mm);
882 WARN_ON_ONCE(mm == current->mm);
883 WARN_ON_ONCE(mm == current->active_mm);
884 mm_free_pgd(mm);
885 destroy_context(mm);
886 mmu_notifier_subscriptions_destroy(mm);
887 check_mm(mm);
888 put_user_ns(mm->user_ns);
889 mm_pasid_drop(mm);
890 free_mm(mm);
891 }
892 EXPORT_SYMBOL_GPL(__mmdrop);
893
mmdrop_async_fn(struct work_struct * work)894 static void mmdrop_async_fn(struct work_struct *work)
895 {
896 struct mm_struct *mm;
897
898 mm = container_of(work, struct mm_struct, async_put_work);
899 __mmdrop(mm);
900 }
901
mmdrop_async(struct mm_struct * mm)902 static void mmdrop_async(struct mm_struct *mm)
903 {
904 if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
905 INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
906 schedule_work(&mm->async_put_work);
907 }
908 }
909
free_signal_struct(struct signal_struct * sig)910 static inline void free_signal_struct(struct signal_struct *sig)
911 {
912 taskstats_tgid_free(sig);
913 sched_autogroup_exit(sig);
914 /*
915 * __mmdrop is not safe to call from softirq context on x86 due to
916 * pgd_dtor so postpone it to the async context
917 */
918 if (sig->oom_mm)
919 mmdrop_async(sig->oom_mm);
920 kmem_cache_free(signal_cachep, sig);
921 }
922
put_signal_struct(struct signal_struct * sig)923 static inline void put_signal_struct(struct signal_struct *sig)
924 {
925 if (refcount_dec_and_test(&sig->sigcnt))
926 free_signal_struct(sig);
927 }
928
__put_task_struct(struct task_struct * tsk)929 void __put_task_struct(struct task_struct *tsk)
930 {
931 WARN_ON(!tsk->exit_state);
932 WARN_ON(refcount_read(&tsk->usage));
933 WARN_ON(tsk == current);
934
935 io_uring_free(tsk);
936 cgroup_free(tsk);
937 task_numa_free(tsk, true);
938 security_task_free(tsk);
939 exit_creds(tsk);
940 delayacct_tsk_free(tsk);
941 put_signal_struct(tsk->signal);
942 sched_core_free(tsk);
943 free_task(tsk);
944 }
945 EXPORT_SYMBOL_GPL(__put_task_struct);
946
__put_task_struct_rcu_cb(struct rcu_head * rhp)947 void __put_task_struct_rcu_cb(struct rcu_head *rhp)
948 {
949 struct task_struct *task = container_of(rhp, struct task_struct, rcu);
950
951 __put_task_struct(task);
952 }
953 EXPORT_SYMBOL_GPL(__put_task_struct_rcu_cb);
954
arch_task_cache_init(void)955 void __init __weak arch_task_cache_init(void) { }
956
957 /*
958 * set_max_threads
959 */
set_max_threads(unsigned int max_threads_suggested)960 static void set_max_threads(unsigned int max_threads_suggested)
961 {
962 u64 threads;
963 unsigned long nr_pages = totalram_pages();
964
965 /*
966 * The number of threads shall be limited such that the thread
967 * structures may only consume a small part of the available memory.
968 */
969 if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
970 threads = MAX_THREADS;
971 else
972 threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
973 (u64) THREAD_SIZE * 8UL);
974
975 if (threads > max_threads_suggested)
976 threads = max_threads_suggested;
977
978 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
979 }
980
981 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
982 /* Initialized by the architecture: */
983 int arch_task_struct_size __read_mostly;
984 #endif
985
986 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
task_struct_whitelist(unsigned long * offset,unsigned long * size)987 static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
988 {
989 /* Fetch thread_struct whitelist for the architecture. */
990 arch_thread_struct_whitelist(offset, size);
991
992 /*
993 * Handle zero-sized whitelist or empty thread_struct, otherwise
994 * adjust offset to position of thread_struct in task_struct.
995 */
996 if (unlikely(*size == 0))
997 *offset = 0;
998 else
999 *offset += offsetof(struct task_struct, thread);
1000 }
1001 #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
1002
fork_init(void)1003 void __init fork_init(void)
1004 {
1005 int i;
1006 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
1007 #ifndef ARCH_MIN_TASKALIGN
1008 #define ARCH_MIN_TASKALIGN 0
1009 #endif
1010 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
1011 unsigned long useroffset, usersize;
1012
1013 /* create a slab on which task_structs can be allocated */
1014 task_struct_whitelist(&useroffset, &usersize);
1015 task_struct_cachep = kmem_cache_create_usercopy("task_struct",
1016 arch_task_struct_size, align,
1017 SLAB_PANIC|SLAB_ACCOUNT,
1018 useroffset, usersize, NULL);
1019 #endif
1020
1021 /* do the arch specific task caches init */
1022 arch_task_cache_init();
1023
1024 set_max_threads(MAX_THREADS);
1025
1026 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
1027 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
1028 init_task.signal->rlim[RLIMIT_SIGPENDING] =
1029 init_task.signal->rlim[RLIMIT_NPROC];
1030
1031 for (i = 0; i < UCOUNT_COUNTS; i++)
1032 init_user_ns.ucount_max[i] = max_threads/2;
1033
1034 set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_NPROC, RLIM_INFINITY);
1035 set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE, RLIM_INFINITY);
1036 set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
1037 set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK, RLIM_INFINITY);
1038
1039 #ifdef CONFIG_VMAP_STACK
1040 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
1041 NULL, free_vm_stack_cache);
1042 #endif
1043
1044 scs_init();
1045
1046 lockdep_init_task(&init_task);
1047 uprobes_init();
1048 }
1049
arch_dup_task_struct(struct task_struct * dst,struct task_struct * src)1050 int __weak arch_dup_task_struct(struct task_struct *dst,
1051 struct task_struct *src)
1052 {
1053 *dst = *src;
1054 return 0;
1055 }
1056
set_task_stack_end_magic(struct task_struct * tsk)1057 void set_task_stack_end_magic(struct task_struct *tsk)
1058 {
1059 unsigned long *stackend;
1060
1061 stackend = end_of_stack(tsk);
1062 *stackend = STACK_END_MAGIC; /* for overflow detection */
1063 }
1064
dup_task_struct(struct task_struct * orig,int node)1065 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
1066 {
1067 struct task_struct *tsk;
1068 int err;
1069
1070 if (node == NUMA_NO_NODE)
1071 node = tsk_fork_get_node(orig);
1072 tsk = alloc_task_struct_node(node);
1073 if (!tsk)
1074 return NULL;
1075
1076 err = arch_dup_task_struct(tsk, orig);
1077 if (err)
1078 goto free_tsk;
1079
1080 err = alloc_thread_stack_node(tsk, node);
1081 if (err)
1082 goto free_tsk;
1083
1084 #ifdef CONFIG_THREAD_INFO_IN_TASK
1085 refcount_set(&tsk->stack_refcount, 1);
1086 #endif
1087 account_kernel_stack(tsk, 1);
1088
1089 err = scs_prepare(tsk, node);
1090 if (err)
1091 goto free_stack;
1092
1093 #ifdef CONFIG_SECCOMP
1094 /*
1095 * We must handle setting up seccomp filters once we're under
1096 * the sighand lock in case orig has changed between now and
1097 * then. Until then, filter must be NULL to avoid messing up
1098 * the usage counts on the error path calling free_task.
1099 */
1100 tsk->seccomp.filter = NULL;
1101 #endif
1102
1103 setup_thread_stack(tsk, orig);
1104 clear_user_return_notifier(tsk);
1105 clear_tsk_need_resched(tsk);
1106 set_task_stack_end_magic(tsk);
1107 clear_syscall_work_syscall_user_dispatch(tsk);
1108
1109 #ifdef CONFIG_STACKPROTECTOR
1110 tsk->stack_canary = get_random_canary();
1111 #endif
1112 if (orig->cpus_ptr == &orig->cpus_mask)
1113 tsk->cpus_ptr = &tsk->cpus_mask;
1114 dup_user_cpus_ptr(tsk, orig, node);
1115
1116 /*
1117 * One for the user space visible state that goes away when reaped.
1118 * One for the scheduler.
1119 */
1120 refcount_set(&tsk->rcu_users, 2);
1121 /* One for the rcu users */
1122 refcount_set(&tsk->usage, 1);
1123 #ifdef CONFIG_BLK_DEV_IO_TRACE
1124 tsk->btrace_seq = 0;
1125 #endif
1126 tsk->splice_pipe = NULL;
1127 tsk->task_frag.page = NULL;
1128 tsk->wake_q.next = NULL;
1129 tsk->worker_private = NULL;
1130
1131 kcov_task_init(tsk);
1132 kmsan_task_create(tsk);
1133 kmap_local_fork(tsk);
1134
1135 #ifdef CONFIG_FAULT_INJECTION
1136 tsk->fail_nth = 0;
1137 #endif
1138
1139 #ifdef CONFIG_BLK_CGROUP
1140 tsk->throttle_queue = NULL;
1141 tsk->use_memdelay = 0;
1142 #endif
1143
1144 #ifdef CONFIG_IOMMU_SVA
1145 tsk->pasid_activated = 0;
1146 #endif
1147
1148 #ifdef CONFIG_MEMCG
1149 tsk->active_memcg = NULL;
1150 #endif
1151
1152 #ifdef CONFIG_CPU_SUP_INTEL
1153 tsk->reported_split_lock = 0;
1154 #endif
1155
1156 android_init_vendor_data(tsk, 1);
1157 android_init_oem_data(tsk, 1);
1158
1159 trace_android_vh_dup_task_struct(tsk, orig);
1160 return tsk;
1161
1162 free_stack:
1163 exit_task_stack_account(tsk);
1164 free_thread_stack(tsk);
1165 free_tsk:
1166 free_task_struct(tsk);
1167 return NULL;
1168 }
1169
1170 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
1171
1172 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
1173
coredump_filter_setup(char * s)1174 static int __init coredump_filter_setup(char *s)
1175 {
1176 default_dump_filter =
1177 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
1178 MMF_DUMP_FILTER_MASK;
1179 return 1;
1180 }
1181
1182 __setup("coredump_filter=", coredump_filter_setup);
1183
1184 #include <linux/init_task.h>
1185
mm_init_aio(struct mm_struct * mm)1186 static void mm_init_aio(struct mm_struct *mm)
1187 {
1188 #ifdef CONFIG_AIO
1189 spin_lock_init(&mm->ioctx_lock);
1190 mm->ioctx_table = NULL;
1191 #endif
1192 }
1193
mm_clear_owner(struct mm_struct * mm,struct task_struct * p)1194 static __always_inline void mm_clear_owner(struct mm_struct *mm,
1195 struct task_struct *p)
1196 {
1197 #ifdef CONFIG_MEMCG
1198 if (mm->owner == p)
1199 WRITE_ONCE(mm->owner, NULL);
1200 #endif
1201 }
1202
mm_init_owner(struct mm_struct * mm,struct task_struct * p)1203 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1204 {
1205 #ifdef CONFIG_MEMCG
1206 mm->owner = p;
1207 #endif
1208 }
1209
mm_init_uprobes_state(struct mm_struct * mm)1210 static void mm_init_uprobes_state(struct mm_struct *mm)
1211 {
1212 #ifdef CONFIG_UPROBES
1213 mm->uprobes_state.xol_area = NULL;
1214 #endif
1215 }
1216
mm_init(struct mm_struct * mm,struct task_struct * p,struct user_namespace * user_ns)1217 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1218 struct user_namespace *user_ns)
1219 {
1220 mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
1221 mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
1222 atomic_set(&mm->mm_users, 1);
1223 atomic_set(&mm->mm_count, 1);
1224 seqcount_init(&mm->write_protect_seq);
1225 mmap_init_lock(mm);
1226 INIT_LIST_HEAD(&mm->mmlist);
1227 #ifdef CONFIG_PER_VMA_LOCK
1228 mm->mm_lock_seq = 0;
1229 #endif
1230 mm_pgtables_bytes_init(mm);
1231 mm->map_count = 0;
1232 mm->locked_vm = 0;
1233 atomic64_set(&mm->pinned_vm, 0);
1234 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1235 spin_lock_init(&mm->page_table_lock);
1236 spin_lock_init(&mm->arg_lock);
1237 mm_init_cpumask(mm);
1238 mm_init_aio(mm);
1239 mm_init_owner(mm, p);
1240 mm_pasid_init(mm);
1241 RCU_INIT_POINTER(mm->exe_file, NULL);
1242 mmu_notifier_subscriptions_init(mm);
1243 init_tlb_flush_pending(mm);
1244 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
1245 mm->pmd_huge_pte = NULL;
1246 #endif
1247 mm_init_uprobes_state(mm);
1248 hugetlb_count_init(mm);
1249
1250 if (current->mm) {
1251 mm->flags = current->mm->flags & MMF_INIT_MASK;
1252 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1253 } else {
1254 mm->flags = default_dump_filter;
1255 mm->def_flags = 0;
1256 }
1257
1258 if (mm_alloc_pgd(mm))
1259 goto fail_nopgd;
1260
1261 if (init_new_context(p, mm))
1262 goto fail_nocontext;
1263
1264 mm->user_ns = get_user_ns(user_ns);
1265 lru_gen_init_mm(mm);
1266 return mm;
1267
1268 fail_nocontext:
1269 mm_free_pgd(mm);
1270 fail_nopgd:
1271 free_mm(mm);
1272 return NULL;
1273 }
1274
1275 /*
1276 * Allocate and initialize an mm_struct.
1277 */
mm_alloc(void)1278 struct mm_struct *mm_alloc(void)
1279 {
1280 struct mm_struct *mm;
1281
1282 mm = allocate_mm();
1283 if (!mm)
1284 return NULL;
1285
1286 memset(mm, 0, sizeof(*mm));
1287 return mm_init(mm, current, current_user_ns());
1288 }
1289
__mmput(struct mm_struct * mm)1290 static inline void __mmput(struct mm_struct *mm)
1291 {
1292 VM_BUG_ON(atomic_read(&mm->mm_users));
1293
1294 uprobe_clear_state(mm);
1295 exit_aio(mm);
1296 ksm_exit(mm);
1297 khugepaged_exit(mm); /* must run before exit_mmap */
1298 exit_mmap(mm);
1299 mm_put_huge_zero_page(mm);
1300 set_mm_exe_file(mm, NULL);
1301 if (!list_empty(&mm->mmlist)) {
1302 spin_lock(&mmlist_lock);
1303 list_del(&mm->mmlist);
1304 spin_unlock(&mmlist_lock);
1305 }
1306 if (mm->binfmt)
1307 module_put(mm->binfmt->module);
1308 lru_gen_del_mm(mm);
1309 mmdrop(mm);
1310 }
1311
1312 /*
1313 * Decrement the use count and release all resources for an mm.
1314 */
mmput(struct mm_struct * mm)1315 void mmput(struct mm_struct *mm)
1316 {
1317 might_sleep();
1318
1319 if (atomic_dec_and_test(&mm->mm_users)) {
1320 trace_android_vh_mmput(mm);
1321 __mmput(mm);
1322 }
1323 }
1324 EXPORT_SYMBOL_GPL(mmput);
1325
1326 #ifdef CONFIG_MMU
mmput_async_fn(struct work_struct * work)1327 static void mmput_async_fn(struct work_struct *work)
1328 {
1329 struct mm_struct *mm = container_of(work, struct mm_struct,
1330 async_put_work);
1331
1332 __mmput(mm);
1333 }
1334
mmput_async(struct mm_struct * mm)1335 void mmput_async(struct mm_struct *mm)
1336 {
1337 if (atomic_dec_and_test(&mm->mm_users)) {
1338 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1339 schedule_work(&mm->async_put_work);
1340 }
1341 }
1342 EXPORT_SYMBOL_GPL(mmput_async);
1343 #endif
1344
1345 /**
1346 * set_mm_exe_file - change a reference to the mm's executable file
1347 *
1348 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1349 *
1350 * Main users are mmput() and sys_execve(). Callers prevent concurrent
1351 * invocations: in mmput() nobody alive left, in execve task is single
1352 * threaded.
1353 *
1354 * Can only fail if new_exe_file != NULL.
1355 */
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1356 int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1357 {
1358 struct file *old_exe_file;
1359
1360 /*
1361 * It is safe to dereference the exe_file without RCU as
1362 * this function is only called if nobody else can access
1363 * this mm -- see comment above for justification.
1364 */
1365 old_exe_file = rcu_dereference_raw(mm->exe_file);
1366
1367 if (new_exe_file) {
1368 /*
1369 * We expect the caller (i.e., sys_execve) to already denied
1370 * write access, so this is unlikely to fail.
1371 */
1372 if (unlikely(deny_write_access(new_exe_file)))
1373 return -EACCES;
1374 get_file(new_exe_file);
1375 }
1376 rcu_assign_pointer(mm->exe_file, new_exe_file);
1377 if (old_exe_file) {
1378 allow_write_access(old_exe_file);
1379 fput(old_exe_file);
1380 }
1381 return 0;
1382 }
1383
1384 /**
1385 * replace_mm_exe_file - replace a reference to the mm's executable file
1386 *
1387 * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
1388 * dealing with concurrent invocation and without grabbing the mmap lock in
1389 * write mode.
1390 *
1391 * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
1392 */
replace_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1393 int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1394 {
1395 struct vm_area_struct *vma;
1396 struct file *old_exe_file;
1397 int ret = 0;
1398
1399 /* Forbid mm->exe_file change if old file still mapped. */
1400 old_exe_file = get_mm_exe_file(mm);
1401 if (old_exe_file) {
1402 VMA_ITERATOR(vmi, mm, 0);
1403 mmap_read_lock(mm);
1404 for_each_vma(vmi, vma) {
1405 if (!vma->vm_file)
1406 continue;
1407 if (path_equal(&vma->vm_file->f_path,
1408 &old_exe_file->f_path)) {
1409 ret = -EBUSY;
1410 break;
1411 }
1412 }
1413 mmap_read_unlock(mm);
1414 fput(old_exe_file);
1415 if (ret)
1416 return ret;
1417 }
1418
1419 /* set the new file, lockless */
1420 ret = deny_write_access(new_exe_file);
1421 if (ret)
1422 return -EACCES;
1423 get_file(new_exe_file);
1424
1425 old_exe_file = xchg(&mm->exe_file, new_exe_file);
1426 if (old_exe_file) {
1427 /*
1428 * Don't race with dup_mmap() getting the file and disallowing
1429 * write access while someone might open the file writable.
1430 */
1431 mmap_read_lock(mm);
1432 allow_write_access(old_exe_file);
1433 fput(old_exe_file);
1434 mmap_read_unlock(mm);
1435 }
1436 return 0;
1437 }
1438
1439 /**
1440 * get_mm_exe_file - acquire a reference to the mm's executable file
1441 *
1442 * Returns %NULL if mm has no associated executable file.
1443 * User must release file via fput().
1444 */
get_mm_exe_file(struct mm_struct * mm)1445 struct file *get_mm_exe_file(struct mm_struct *mm)
1446 {
1447 struct file *exe_file;
1448
1449 rcu_read_lock();
1450 exe_file = rcu_dereference(mm->exe_file);
1451 if (exe_file && !get_file_rcu(exe_file))
1452 exe_file = NULL;
1453 rcu_read_unlock();
1454 return exe_file;
1455 }
1456
1457 /**
1458 * get_task_exe_file - acquire a reference to the task's executable file
1459 *
1460 * Returns %NULL if task's mm (if any) has no associated executable file or
1461 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1462 * User must release file via fput().
1463 */
get_task_exe_file(struct task_struct * task)1464 struct file *get_task_exe_file(struct task_struct *task)
1465 {
1466 struct file *exe_file = NULL;
1467 struct mm_struct *mm;
1468
1469 task_lock(task);
1470 mm = task->mm;
1471 if (mm) {
1472 if (!(task->flags & PF_KTHREAD))
1473 exe_file = get_mm_exe_file(mm);
1474 }
1475 task_unlock(task);
1476 return exe_file;
1477 }
1478
1479 /**
1480 * get_task_mm - acquire a reference to the task's mm
1481 *
1482 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1483 * this kernel workthread has transiently adopted a user mm with use_mm,
1484 * to do its AIO) is not set and if so returns a reference to it, after
1485 * bumping up the use count. User must release the mm via mmput()
1486 * after use. Typically used by /proc and ptrace.
1487 */
get_task_mm(struct task_struct * task)1488 struct mm_struct *get_task_mm(struct task_struct *task)
1489 {
1490 struct mm_struct *mm;
1491
1492 task_lock(task);
1493 mm = task->mm;
1494 if (mm) {
1495 if (task->flags & PF_KTHREAD)
1496 mm = NULL;
1497 else
1498 mmget(mm);
1499 }
1500 task_unlock(task);
1501 return mm;
1502 }
1503 EXPORT_SYMBOL_GPL(get_task_mm);
1504
mm_access(struct task_struct * task,unsigned int mode)1505 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1506 {
1507 struct mm_struct *mm;
1508 int err;
1509
1510 err = down_read_killable(&task->signal->exec_update_lock);
1511 if (err)
1512 return ERR_PTR(err);
1513
1514 mm = get_task_mm(task);
1515 if (mm && mm != current->mm &&
1516 !ptrace_may_access(task, mode)) {
1517 mmput(mm);
1518 mm = ERR_PTR(-EACCES);
1519 }
1520 up_read(&task->signal->exec_update_lock);
1521
1522 return mm;
1523 }
1524
complete_vfork_done(struct task_struct * tsk)1525 static void complete_vfork_done(struct task_struct *tsk)
1526 {
1527 struct completion *vfork;
1528
1529 task_lock(tsk);
1530 vfork = tsk->vfork_done;
1531 if (likely(vfork)) {
1532 tsk->vfork_done = NULL;
1533 complete(vfork);
1534 }
1535 task_unlock(tsk);
1536 }
1537
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)1538 static int wait_for_vfork_done(struct task_struct *child,
1539 struct completion *vfork)
1540 {
1541 unsigned int state = TASK_UNINTERRUPTIBLE|TASK_KILLABLE|TASK_FREEZABLE;
1542 int killed;
1543
1544 cgroup_enter_frozen();
1545 killed = wait_for_completion_state(vfork, state);
1546 cgroup_leave_frozen(false);
1547
1548 if (killed) {
1549 task_lock(child);
1550 child->vfork_done = NULL;
1551 task_unlock(child);
1552 }
1553
1554 put_task_struct(child);
1555 return killed;
1556 }
1557
1558 /* Please note the differences between mmput and mm_release.
1559 * mmput is called whenever we stop holding onto a mm_struct,
1560 * error success whatever.
1561 *
1562 * mm_release is called after a mm_struct has been removed
1563 * from the current process.
1564 *
1565 * This difference is important for error handling, when we
1566 * only half set up a mm_struct for a new process and need to restore
1567 * the old one. Because we mmput the new mm_struct before
1568 * restoring the old one. . .
1569 * Eric Biederman 10 January 1998
1570 */
mm_release(struct task_struct * tsk,struct mm_struct * mm)1571 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1572 {
1573 uprobe_free_utask(tsk);
1574
1575 /* Get rid of any cached register state */
1576 deactivate_mm(tsk, mm);
1577
1578 /*
1579 * Signal userspace if we're not exiting with a core dump
1580 * because we want to leave the value intact for debugging
1581 * purposes.
1582 */
1583 if (tsk->clear_child_tid) {
1584 if (atomic_read(&mm->mm_users) > 1) {
1585 /*
1586 * We don't check the error code - if userspace has
1587 * not set up a proper pointer then tough luck.
1588 */
1589 put_user(0, tsk->clear_child_tid);
1590 do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1591 1, NULL, NULL, 0, 0);
1592 }
1593 tsk->clear_child_tid = NULL;
1594 }
1595
1596 /*
1597 * All done, finally we can wake up parent and return this mm to him.
1598 * Also kthread_stop() uses this completion for synchronization.
1599 */
1600 if (tsk->vfork_done)
1601 complete_vfork_done(tsk);
1602 }
1603
exit_mm_release(struct task_struct * tsk,struct mm_struct * mm)1604 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1605 {
1606 futex_exit_release(tsk);
1607 mm_release(tsk, mm);
1608 }
1609
exec_mm_release(struct task_struct * tsk,struct mm_struct * mm)1610 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1611 {
1612 futex_exec_release(tsk);
1613 mm_release(tsk, mm);
1614 }
1615
1616 /**
1617 * dup_mm() - duplicates an existing mm structure
1618 * @tsk: the task_struct with which the new mm will be associated.
1619 * @oldmm: the mm to duplicate.
1620 *
1621 * Allocates a new mm structure and duplicates the provided @oldmm structure
1622 * content into it.
1623 *
1624 * Return: the duplicated mm or NULL on failure.
1625 */
dup_mm(struct task_struct * tsk,struct mm_struct * oldmm)1626 static struct mm_struct *dup_mm(struct task_struct *tsk,
1627 struct mm_struct *oldmm)
1628 {
1629 struct mm_struct *mm;
1630 int err;
1631
1632 mm = allocate_mm();
1633 if (!mm)
1634 goto fail_nomem;
1635
1636 memcpy(mm, oldmm, sizeof(*mm));
1637
1638 if (!mm_init(mm, tsk, mm->user_ns))
1639 goto fail_nomem;
1640
1641 err = dup_mmap(mm, oldmm);
1642 if (err)
1643 goto free_pt;
1644
1645 mm->hiwater_rss = get_mm_rss(mm);
1646 mm->hiwater_vm = mm->total_vm;
1647
1648 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1649 goto free_pt;
1650
1651 return mm;
1652
1653 free_pt:
1654 /* don't put binfmt in mmput, we haven't got module yet */
1655 mm->binfmt = NULL;
1656 mm_init_owner(mm, NULL);
1657 mmput(mm);
1658
1659 fail_nomem:
1660 return NULL;
1661 }
1662
copy_mm(unsigned long clone_flags,struct task_struct * tsk)1663 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1664 {
1665 struct mm_struct *mm, *oldmm;
1666
1667 tsk->min_flt = tsk->maj_flt = 0;
1668 tsk->nvcsw = tsk->nivcsw = 0;
1669 #ifdef CONFIG_DETECT_HUNG_TASK
1670 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1671 tsk->last_switch_time = 0;
1672 #endif
1673
1674 tsk->mm = NULL;
1675 tsk->active_mm = NULL;
1676
1677 /*
1678 * Are we cloning a kernel thread?
1679 *
1680 * We need to steal a active VM for that..
1681 */
1682 oldmm = current->mm;
1683 if (!oldmm)
1684 return 0;
1685
1686 if (clone_flags & CLONE_VM) {
1687 mmget(oldmm);
1688 mm = oldmm;
1689 } else {
1690 mm = dup_mm(tsk, current->mm);
1691 if (!mm)
1692 return -ENOMEM;
1693 }
1694
1695 tsk->mm = mm;
1696 tsk->active_mm = mm;
1697 return 0;
1698 }
1699
copy_fs(unsigned long clone_flags,struct task_struct * tsk)1700 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1701 {
1702 struct fs_struct *fs = current->fs;
1703 if (clone_flags & CLONE_FS) {
1704 /* tsk->fs is already what we want */
1705 spin_lock(&fs->lock);
1706 if (fs->in_exec) {
1707 spin_unlock(&fs->lock);
1708 return -EAGAIN;
1709 }
1710 fs->users++;
1711 spin_unlock(&fs->lock);
1712 return 0;
1713 }
1714 tsk->fs = copy_fs_struct(fs);
1715 if (!tsk->fs)
1716 return -ENOMEM;
1717 return 0;
1718 }
1719
copy_files(unsigned long clone_flags,struct task_struct * tsk)1720 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1721 {
1722 struct files_struct *oldf, *newf;
1723 int error = 0;
1724
1725 /*
1726 * A background process may not have any files ...
1727 */
1728 oldf = current->files;
1729 if (!oldf)
1730 goto out;
1731
1732 if (clone_flags & CLONE_FILES) {
1733 atomic_inc(&oldf->count);
1734 goto out;
1735 }
1736
1737 newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1738 if (!newf)
1739 goto out;
1740
1741 tsk->files = newf;
1742 error = 0;
1743 out:
1744 return error;
1745 }
1746
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1747 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1748 {
1749 struct sighand_struct *sig;
1750
1751 if (clone_flags & CLONE_SIGHAND) {
1752 refcount_inc(¤t->sighand->count);
1753 return 0;
1754 }
1755 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1756 RCU_INIT_POINTER(tsk->sighand, sig);
1757 if (!sig)
1758 return -ENOMEM;
1759
1760 refcount_set(&sig->count, 1);
1761 spin_lock_irq(¤t->sighand->siglock);
1762 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1763 spin_unlock_irq(¤t->sighand->siglock);
1764
1765 /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1766 if (clone_flags & CLONE_CLEAR_SIGHAND)
1767 flush_signal_handlers(tsk, 0);
1768
1769 return 0;
1770 }
1771
__cleanup_sighand(struct sighand_struct * sighand)1772 void __cleanup_sighand(struct sighand_struct *sighand)
1773 {
1774 if (refcount_dec_and_test(&sighand->count)) {
1775 signalfd_cleanup(sighand);
1776 /*
1777 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1778 * without an RCU grace period, see __lock_task_sighand().
1779 */
1780 kmem_cache_free(sighand_cachep, sighand);
1781 }
1782 }
1783
1784 /*
1785 * Initialize POSIX timer handling for a thread group.
1786 */
posix_cpu_timers_init_group(struct signal_struct * sig)1787 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1788 {
1789 struct posix_cputimers *pct = &sig->posix_cputimers;
1790 unsigned long cpu_limit;
1791
1792 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1793 posix_cputimers_group_init(pct, cpu_limit);
1794 }
1795
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1796 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1797 {
1798 struct signal_struct *sig;
1799
1800 if (clone_flags & CLONE_THREAD)
1801 return 0;
1802
1803 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1804 tsk->signal = sig;
1805 if (!sig)
1806 return -ENOMEM;
1807
1808 sig->nr_threads = 1;
1809 sig->quick_threads = 1;
1810 atomic_set(&sig->live, 1);
1811 refcount_set(&sig->sigcnt, 1);
1812
1813 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1814 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1815 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1816
1817 init_waitqueue_head(&sig->wait_chldexit);
1818 sig->curr_target = tsk;
1819 init_sigpending(&sig->shared_pending);
1820 INIT_HLIST_HEAD(&sig->multiprocess);
1821 seqlock_init(&sig->stats_lock);
1822 prev_cputime_init(&sig->prev_cputime);
1823
1824 #ifdef CONFIG_POSIX_TIMERS
1825 INIT_LIST_HEAD(&sig->posix_timers);
1826 hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1827 sig->real_timer.function = it_real_fn;
1828 #endif
1829
1830 task_lock(current->group_leader);
1831 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1832 task_unlock(current->group_leader);
1833
1834 posix_cpu_timers_init_group(sig);
1835
1836 tty_audit_fork(sig);
1837 sched_autogroup_fork(sig);
1838
1839 sig->oom_score_adj = current->signal->oom_score_adj;
1840 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1841
1842 mutex_init(&sig->cred_guard_mutex);
1843 init_rwsem(&sig->exec_update_lock);
1844
1845 return 0;
1846 }
1847
copy_seccomp(struct task_struct * p)1848 static void copy_seccomp(struct task_struct *p)
1849 {
1850 #ifdef CONFIG_SECCOMP
1851 /*
1852 * Must be called with sighand->lock held, which is common to
1853 * all threads in the group. Holding cred_guard_mutex is not
1854 * needed because this new task is not yet running and cannot
1855 * be racing exec.
1856 */
1857 assert_spin_locked(¤t->sighand->siglock);
1858
1859 /* Ref-count the new filter user, and assign it. */
1860 get_seccomp_filter(current);
1861 p->seccomp = current->seccomp;
1862
1863 /*
1864 * Explicitly enable no_new_privs here in case it got set
1865 * between the task_struct being duplicated and holding the
1866 * sighand lock. The seccomp state and nnp must be in sync.
1867 */
1868 if (task_no_new_privs(current))
1869 task_set_no_new_privs(p);
1870
1871 /*
1872 * If the parent gained a seccomp mode after copying thread
1873 * flags and between before we held the sighand lock, we have
1874 * to manually enable the seccomp thread flag here.
1875 */
1876 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1877 set_task_syscall_work(p, SECCOMP);
1878 #endif
1879 }
1880
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1881 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1882 {
1883 current->clear_child_tid = tidptr;
1884
1885 return task_pid_vnr(current);
1886 }
1887
rt_mutex_init_task(struct task_struct * p)1888 static void rt_mutex_init_task(struct task_struct *p)
1889 {
1890 raw_spin_lock_init(&p->pi_lock);
1891 #ifdef CONFIG_RT_MUTEXES
1892 p->pi_waiters = RB_ROOT_CACHED;
1893 p->pi_top_task = NULL;
1894 p->pi_blocked_on = NULL;
1895 #endif
1896 }
1897
init_task_pid_links(struct task_struct * task)1898 static inline void init_task_pid_links(struct task_struct *task)
1899 {
1900 enum pid_type type;
1901
1902 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
1903 INIT_HLIST_NODE(&task->pid_links[type]);
1904 }
1905
1906 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1907 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1908 {
1909 if (type == PIDTYPE_PID)
1910 task->thread_pid = pid;
1911 else
1912 task->signal->pids[type] = pid;
1913 }
1914
rcu_copy_process(struct task_struct * p)1915 static inline void rcu_copy_process(struct task_struct *p)
1916 {
1917 #ifdef CONFIG_PREEMPT_RCU
1918 p->rcu_read_lock_nesting = 0;
1919 p->rcu_read_unlock_special.s = 0;
1920 p->rcu_blocked_node = NULL;
1921 INIT_LIST_HEAD(&p->rcu_node_entry);
1922 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1923 #ifdef CONFIG_TASKS_RCU
1924 p->rcu_tasks_holdout = false;
1925 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1926 p->rcu_tasks_idle_cpu = -1;
1927 #endif /* #ifdef CONFIG_TASKS_RCU */
1928 #ifdef CONFIG_TASKS_TRACE_RCU
1929 p->trc_reader_nesting = 0;
1930 p->trc_reader_special.s = 0;
1931 INIT_LIST_HEAD(&p->trc_holdout_list);
1932 INIT_LIST_HEAD(&p->trc_blkd_node);
1933 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
1934 }
1935
pidfd_pid(const struct file * file)1936 struct pid *pidfd_pid(const struct file *file)
1937 {
1938 if (file->f_op == &pidfd_fops)
1939 return file->private_data;
1940
1941 return ERR_PTR(-EBADF);
1942 }
1943
pidfd_release(struct inode * inode,struct file * file)1944 static int pidfd_release(struct inode *inode, struct file *file)
1945 {
1946 struct pid *pid = file->private_data;
1947
1948 file->private_data = NULL;
1949 put_pid(pid);
1950 return 0;
1951 }
1952
1953 #ifdef CONFIG_PROC_FS
1954 /**
1955 * pidfd_show_fdinfo - print information about a pidfd
1956 * @m: proc fdinfo file
1957 * @f: file referencing a pidfd
1958 *
1959 * Pid:
1960 * This function will print the pid that a given pidfd refers to in the
1961 * pid namespace of the procfs instance.
1962 * If the pid namespace of the process is not a descendant of the pid
1963 * namespace of the procfs instance 0 will be shown as its pid. This is
1964 * similar to calling getppid() on a process whose parent is outside of
1965 * its pid namespace.
1966 *
1967 * NSpid:
1968 * If pid namespaces are supported then this function will also print
1969 * the pid of a given pidfd refers to for all descendant pid namespaces
1970 * starting from the current pid namespace of the instance, i.e. the
1971 * Pid field and the first entry in the NSpid field will be identical.
1972 * If the pid namespace of the process is not a descendant of the pid
1973 * namespace of the procfs instance 0 will be shown as its first NSpid
1974 * entry and no others will be shown.
1975 * Note that this differs from the Pid and NSpid fields in
1976 * /proc/<pid>/status where Pid and NSpid are always shown relative to
1977 * the pid namespace of the procfs instance. The difference becomes
1978 * obvious when sending around a pidfd between pid namespaces from a
1979 * different branch of the tree, i.e. where no ancestral relation is
1980 * present between the pid namespaces:
1981 * - create two new pid namespaces ns1 and ns2 in the initial pid
1982 * namespace (also take care to create new mount namespaces in the
1983 * new pid namespace and mount procfs)
1984 * - create a process with a pidfd in ns1
1985 * - send pidfd from ns1 to ns2
1986 * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
1987 * have exactly one entry, which is 0
1988 */
pidfd_show_fdinfo(struct seq_file * m,struct file * f)1989 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1990 {
1991 struct pid *pid = f->private_data;
1992 struct pid_namespace *ns;
1993 pid_t nr = -1;
1994
1995 if (likely(pid_has_task(pid, PIDTYPE_PID))) {
1996 ns = proc_pid_ns(file_inode(m->file)->i_sb);
1997 nr = pid_nr_ns(pid, ns);
1998 }
1999
2000 seq_put_decimal_ll(m, "Pid:\t", nr);
2001
2002 #ifdef CONFIG_PID_NS
2003 seq_put_decimal_ll(m, "\nNSpid:\t", nr);
2004 if (nr > 0) {
2005 int i;
2006
2007 /* If nr is non-zero it means that 'pid' is valid and that
2008 * ns, i.e. the pid namespace associated with the procfs
2009 * instance, is in the pid namespace hierarchy of pid.
2010 * Start at one below the already printed level.
2011 */
2012 for (i = ns->level + 1; i <= pid->level; i++)
2013 seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
2014 }
2015 #endif
2016 seq_putc(m, '\n');
2017 }
2018 #endif
2019
2020 /*
2021 * Poll support for process exit notification.
2022 */
pidfd_poll(struct file * file,struct poll_table_struct * pts)2023 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
2024 {
2025 struct pid *pid = file->private_data;
2026 __poll_t poll_flags = 0;
2027
2028 poll_wait(file, &pid->wait_pidfd, pts);
2029
2030 /*
2031 * Inform pollers only when the whole thread group exits.
2032 * If the thread group leader exits before all other threads in the
2033 * group, then poll(2) should block, similar to the wait(2) family.
2034 */
2035 if (thread_group_exited(pid))
2036 poll_flags = EPOLLIN | EPOLLRDNORM;
2037
2038 return poll_flags;
2039 }
2040
2041 const struct file_operations pidfd_fops = {
2042 .release = pidfd_release,
2043 .poll = pidfd_poll,
2044 #ifdef CONFIG_PROC_FS
2045 .show_fdinfo = pidfd_show_fdinfo,
2046 #endif
2047 };
2048
__delayed_free_task(struct rcu_head * rhp)2049 static void __delayed_free_task(struct rcu_head *rhp)
2050 {
2051 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
2052
2053 free_task(tsk);
2054 }
2055
delayed_free_task(struct task_struct * tsk)2056 static __always_inline void delayed_free_task(struct task_struct *tsk)
2057 {
2058 if (IS_ENABLED(CONFIG_MEMCG))
2059 call_rcu(&tsk->rcu, __delayed_free_task);
2060 else
2061 free_task(tsk);
2062 }
2063
copy_oom_score_adj(u64 clone_flags,struct task_struct * tsk)2064 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
2065 {
2066 /* Skip if kernel thread */
2067 if (!tsk->mm)
2068 return;
2069
2070 /* Skip if spawning a thread or using vfork */
2071 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
2072 return;
2073
2074 /* We need to synchronize with __set_oom_adj */
2075 mutex_lock(&oom_adj_mutex);
2076 set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
2077 /* Update the values in case they were changed after copy_signal */
2078 tsk->signal->oom_score_adj = current->signal->oom_score_adj;
2079 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
2080 mutex_unlock(&oom_adj_mutex);
2081 }
2082
2083 #ifdef CONFIG_RV
rv_task_fork(struct task_struct * p)2084 static void rv_task_fork(struct task_struct *p)
2085 {
2086 int i;
2087
2088 for (i = 0; i < RV_PER_TASK_MONITORS; i++)
2089 p->rv[i].da_mon.monitoring = false;
2090 }
2091 #else
2092 #define rv_task_fork(p) do {} while (0)
2093 #endif
2094
2095 /*
2096 * This creates a new process as a copy of the old one,
2097 * but does not actually start it yet.
2098 *
2099 * It copies the registers, and all the appropriate
2100 * parts of the process environment (as per the clone
2101 * flags). The actual kick-off is left to the caller.
2102 */
copy_process(struct pid * pid,int trace,int node,struct kernel_clone_args * args)2103 static __latent_entropy struct task_struct *copy_process(
2104 struct pid *pid,
2105 int trace,
2106 int node,
2107 struct kernel_clone_args *args)
2108 {
2109 int pidfd = -1, retval;
2110 struct task_struct *p;
2111 struct multiprocess_signals delayed;
2112 struct file *pidfile = NULL;
2113 const u64 clone_flags = args->flags;
2114 struct nsproxy *nsp = current->nsproxy;
2115
2116 /*
2117 * Don't allow sharing the root directory with processes in a different
2118 * namespace
2119 */
2120 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2121 return ERR_PTR(-EINVAL);
2122
2123 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2124 return ERR_PTR(-EINVAL);
2125
2126 /*
2127 * Thread groups must share signals as well, and detached threads
2128 * can only be started up within the thread group.
2129 */
2130 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2131 return ERR_PTR(-EINVAL);
2132
2133 /*
2134 * Shared signal handlers imply shared VM. By way of the above,
2135 * thread groups also imply shared VM. Blocking this case allows
2136 * for various simplifications in other code.
2137 */
2138 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2139 return ERR_PTR(-EINVAL);
2140
2141 /*
2142 * Siblings of global init remain as zombies on exit since they are
2143 * not reaped by their parent (swapper). To solve this and to avoid
2144 * multi-rooted process trees, prevent global and container-inits
2145 * from creating siblings.
2146 */
2147 if ((clone_flags & CLONE_PARENT) &&
2148 current->signal->flags & SIGNAL_UNKILLABLE)
2149 return ERR_PTR(-EINVAL);
2150
2151 /*
2152 * If the new process will be in a different pid or user namespace
2153 * do not allow it to share a thread group with the forking task.
2154 */
2155 if (clone_flags & CLONE_THREAD) {
2156 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2157 (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2158 return ERR_PTR(-EINVAL);
2159 }
2160
2161 /*
2162 * If the new process will be in a different time namespace
2163 * do not allow it to share VM or a thread group with the forking task.
2164 */
2165 if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
2166 if (nsp->time_ns != nsp->time_ns_for_children)
2167 return ERR_PTR(-EINVAL);
2168 }
2169
2170 if (clone_flags & CLONE_PIDFD) {
2171 /*
2172 * - CLONE_DETACHED is blocked so that we can potentially
2173 * reuse it later for CLONE_PIDFD.
2174 * - CLONE_THREAD is blocked until someone really needs it.
2175 */
2176 if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
2177 return ERR_PTR(-EINVAL);
2178 }
2179
2180 /*
2181 * Force any signals received before this point to be delivered
2182 * before the fork happens. Collect up signals sent to multiple
2183 * processes that happen during the fork and delay them so that
2184 * they appear to happen after the fork.
2185 */
2186 sigemptyset(&delayed.signal);
2187 INIT_HLIST_NODE(&delayed.node);
2188
2189 spin_lock_irq(¤t->sighand->siglock);
2190 if (!(clone_flags & CLONE_THREAD))
2191 hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2192 recalc_sigpending();
2193 spin_unlock_irq(¤t->sighand->siglock);
2194 retval = -ERESTARTNOINTR;
2195 if (task_sigpending(current))
2196 goto fork_out;
2197
2198 retval = -ENOMEM;
2199 p = dup_task_struct(current, node);
2200 if (!p)
2201 goto fork_out;
2202 p->flags &= ~PF_KTHREAD;
2203 if (args->kthread)
2204 p->flags |= PF_KTHREAD;
2205 if (args->io_thread) {
2206 /*
2207 * Mark us an IO worker, and block any signal that isn't
2208 * fatal or STOP
2209 */
2210 p->flags |= PF_IO_WORKER;
2211 siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2212 }
2213
2214 cpufreq_task_times_init(p);
2215
2216 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2217 /*
2218 * Clear TID on mm_release()?
2219 */
2220 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2221
2222 ftrace_graph_init_task(p);
2223
2224 rt_mutex_init_task(p);
2225
2226 lockdep_assert_irqs_enabled();
2227 #ifdef CONFIG_PROVE_LOCKING
2228 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2229 #endif
2230 retval = copy_creds(p, clone_flags);
2231 if (retval < 0)
2232 goto bad_fork_free;
2233
2234 retval = -EAGAIN;
2235 if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2236 if (p->real_cred->user != INIT_USER &&
2237 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2238 goto bad_fork_cleanup_count;
2239 }
2240 current->flags &= ~PF_NPROC_EXCEEDED;
2241
2242 /*
2243 * If multiple threads are within copy_process(), then this check
2244 * triggers too late. This doesn't hurt, the check is only there
2245 * to stop root fork bombs.
2246 */
2247 retval = -EAGAIN;
2248 if (data_race(nr_threads >= max_threads))
2249 goto bad_fork_cleanup_count;
2250
2251 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
2252 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2253 p->flags |= PF_FORKNOEXEC;
2254 INIT_LIST_HEAD(&p->children);
2255 INIT_LIST_HEAD(&p->sibling);
2256 rcu_copy_process(p);
2257 p->vfork_done = NULL;
2258 spin_lock_init(&p->alloc_lock);
2259
2260 init_sigpending(&p->pending);
2261
2262 p->utime = p->stime = p->gtime = 0;
2263 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2264 p->utimescaled = p->stimescaled = 0;
2265 #endif
2266 prev_cputime_init(&p->prev_cputime);
2267
2268 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2269 seqcount_init(&p->vtime.seqcount);
2270 p->vtime.starttime = 0;
2271 p->vtime.state = VTIME_INACTIVE;
2272 #endif
2273
2274 #ifdef CONFIG_IO_URING
2275 p->io_uring = NULL;
2276 #endif
2277
2278 #if defined(SPLIT_RSS_COUNTING)
2279 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2280 #endif
2281
2282 p->default_timer_slack_ns = current->timer_slack_ns;
2283
2284 #ifdef CONFIG_PSI
2285 p->psi_flags = 0;
2286 #endif
2287
2288 task_io_accounting_init(&p->ioac);
2289 acct_clear_integrals(p);
2290
2291 posix_cputimers_init(&p->posix_cputimers);
2292
2293 p->io_context = NULL;
2294 audit_set_context(p, NULL);
2295 cgroup_fork(p);
2296 if (args->kthread) {
2297 if (!set_kthread_struct(p))
2298 goto bad_fork_cleanup_delayacct;
2299 }
2300 #ifdef CONFIG_NUMA
2301 p->mempolicy = mpol_dup(p->mempolicy);
2302 if (IS_ERR(p->mempolicy)) {
2303 retval = PTR_ERR(p->mempolicy);
2304 p->mempolicy = NULL;
2305 goto bad_fork_cleanup_delayacct;
2306 }
2307 #endif
2308 #ifdef CONFIG_CPUSETS
2309 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2310 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2311 seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2312 #endif
2313 #ifdef CONFIG_TRACE_IRQFLAGS
2314 memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2315 p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2316 p->irqtrace.softirq_enable_ip = _THIS_IP_;
2317 p->softirqs_enabled = 1;
2318 p->softirq_context = 0;
2319 #endif
2320
2321 p->pagefault_disabled = 0;
2322
2323 #ifdef CONFIG_LOCKDEP
2324 lockdep_init_task(p);
2325 #endif
2326
2327 #ifdef CONFIG_DEBUG_MUTEXES
2328 p->blocked_on = NULL; /* not blocked yet */
2329 #endif
2330 #ifdef CONFIG_BCACHE
2331 p->sequential_io = 0;
2332 p->sequential_io_avg = 0;
2333 #endif
2334 #ifdef CONFIG_BPF_SYSCALL
2335 RCU_INIT_POINTER(p->bpf_storage, NULL);
2336 p->bpf_ctx = NULL;
2337 #endif
2338
2339 /* Perform scheduler related setup. Assign this task to a CPU. */
2340 retval = sched_fork(clone_flags, p);
2341 if (retval)
2342 goto bad_fork_cleanup_policy;
2343
2344 retval = perf_event_init_task(p, clone_flags);
2345 if (retval)
2346 goto bad_fork_cleanup_policy;
2347 retval = audit_alloc(p);
2348 if (retval)
2349 goto bad_fork_cleanup_perf;
2350 /* copy all the process information */
2351 shm_init_task(p);
2352 retval = security_task_alloc(p, clone_flags);
2353 if (retval)
2354 goto bad_fork_cleanup_audit;
2355 retval = copy_semundo(clone_flags, p);
2356 if (retval)
2357 goto bad_fork_cleanup_security;
2358 retval = copy_files(clone_flags, p);
2359 if (retval)
2360 goto bad_fork_cleanup_semundo;
2361 retval = copy_fs(clone_flags, p);
2362 if (retval)
2363 goto bad_fork_cleanup_files;
2364 retval = copy_sighand(clone_flags, p);
2365 if (retval)
2366 goto bad_fork_cleanup_fs;
2367 retval = copy_signal(clone_flags, p);
2368 if (retval)
2369 goto bad_fork_cleanup_sighand;
2370 retval = copy_mm(clone_flags, p);
2371 if (retval)
2372 goto bad_fork_cleanup_signal;
2373 retval = copy_namespaces(clone_flags, p);
2374 if (retval)
2375 goto bad_fork_cleanup_mm;
2376 retval = copy_io(clone_flags, p);
2377 if (retval)
2378 goto bad_fork_cleanup_namespaces;
2379 retval = copy_thread(p, args);
2380 if (retval)
2381 goto bad_fork_cleanup_io;
2382
2383 stackleak_task_init(p);
2384
2385 if (pid != &init_struct_pid) {
2386 pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2387 args->set_tid_size);
2388 if (IS_ERR(pid)) {
2389 retval = PTR_ERR(pid);
2390 goto bad_fork_cleanup_thread;
2391 }
2392 }
2393
2394 /*
2395 * This has to happen after we've potentially unshared the file
2396 * descriptor table (so that the pidfd doesn't leak into the child
2397 * if the fd table isn't shared).
2398 */
2399 if (clone_flags & CLONE_PIDFD) {
2400 retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2401 if (retval < 0)
2402 goto bad_fork_free_pid;
2403
2404 pidfd = retval;
2405
2406 pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2407 O_RDWR | O_CLOEXEC);
2408 if (IS_ERR(pidfile)) {
2409 put_unused_fd(pidfd);
2410 retval = PTR_ERR(pidfile);
2411 goto bad_fork_free_pid;
2412 }
2413 get_pid(pid); /* held by pidfile now */
2414
2415 retval = put_user(pidfd, args->pidfd);
2416 if (retval)
2417 goto bad_fork_put_pidfd;
2418 }
2419
2420 #ifdef CONFIG_BLOCK
2421 p->plug = NULL;
2422 #endif
2423 futex_init_task(p);
2424
2425 /*
2426 * sigaltstack should be cleared when sharing the same VM
2427 */
2428 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2429 sas_ss_reset(p);
2430
2431 /*
2432 * Syscall tracing and stepping should be turned off in the
2433 * child regardless of CLONE_PTRACE.
2434 */
2435 user_disable_single_step(p);
2436 clear_task_syscall_work(p, SYSCALL_TRACE);
2437 #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2438 clear_task_syscall_work(p, SYSCALL_EMU);
2439 #endif
2440 clear_tsk_latency_tracing(p);
2441
2442 /* ok, now we should be set up.. */
2443 p->pid = pid_nr(pid);
2444 if (clone_flags & CLONE_THREAD) {
2445 p->group_leader = current->group_leader;
2446 p->tgid = current->tgid;
2447 } else {
2448 p->group_leader = p;
2449 p->tgid = p->pid;
2450 }
2451
2452 p->nr_dirtied = 0;
2453 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2454 p->dirty_paused_when = 0;
2455
2456 p->pdeath_signal = 0;
2457 INIT_LIST_HEAD(&p->thread_group);
2458 p->task_works = NULL;
2459 clear_posix_cputimers_work(p);
2460
2461 #ifdef CONFIG_KRETPROBES
2462 p->kretprobe_instances.first = NULL;
2463 #endif
2464 #ifdef CONFIG_RETHOOK
2465 p->rethooks.first = NULL;
2466 #endif
2467
2468 /*
2469 * Ensure that the cgroup subsystem policies allow the new process to be
2470 * forked. It should be noted that the new process's css_set can be changed
2471 * between here and cgroup_post_fork() if an organisation operation is in
2472 * progress.
2473 */
2474 retval = cgroup_can_fork(p, args);
2475 if (retval)
2476 goto bad_fork_put_pidfd;
2477
2478 /*
2479 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2480 * the new task on the correct runqueue. All this *before* the task
2481 * becomes visible.
2482 *
2483 * This isn't part of ->can_fork() because while the re-cloning is
2484 * cgroup specific, it unconditionally needs to place the task on a
2485 * runqueue.
2486 */
2487 sched_cgroup_fork(p, args);
2488
2489 /*
2490 * From this point on we must avoid any synchronous user-space
2491 * communication until we take the tasklist-lock. In particular, we do
2492 * not want user-space to be able to predict the process start-time by
2493 * stalling fork(2) after we recorded the start_time but before it is
2494 * visible to the system.
2495 */
2496
2497 p->start_time = ktime_get_ns();
2498 p->start_boottime = ktime_get_boottime_ns();
2499
2500 /*
2501 * Make it visible to the rest of the system, but dont wake it up yet.
2502 * Need tasklist lock for parent etc handling!
2503 */
2504 write_lock_irq(&tasklist_lock);
2505
2506 /* CLONE_PARENT re-uses the old parent */
2507 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2508 p->real_parent = current->real_parent;
2509 p->parent_exec_id = current->parent_exec_id;
2510 if (clone_flags & CLONE_THREAD)
2511 p->exit_signal = -1;
2512 else
2513 p->exit_signal = current->group_leader->exit_signal;
2514 } else {
2515 p->real_parent = current;
2516 p->parent_exec_id = current->self_exec_id;
2517 p->exit_signal = args->exit_signal;
2518 }
2519
2520 klp_copy_process(p);
2521
2522 sched_core_fork(p);
2523
2524 spin_lock(¤t->sighand->siglock);
2525
2526 rv_task_fork(p);
2527
2528 rseq_fork(p, clone_flags);
2529
2530 /* Don't start children in a dying pid namespace */
2531 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2532 retval = -ENOMEM;
2533 goto bad_fork_cancel_cgroup;
2534 }
2535
2536 /* Let kill terminate clone/fork in the middle */
2537 if (fatal_signal_pending(current)) {
2538 retval = -EINTR;
2539 goto bad_fork_cancel_cgroup;
2540 }
2541
2542 /* No more failure paths after this point. */
2543
2544 /*
2545 * Copy seccomp details explicitly here, in case they were changed
2546 * before holding sighand lock.
2547 */
2548 copy_seccomp(p);
2549
2550 init_task_pid_links(p);
2551 if (likely(p->pid)) {
2552 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2553
2554 init_task_pid(p, PIDTYPE_PID, pid);
2555 if (thread_group_leader(p)) {
2556 init_task_pid(p, PIDTYPE_TGID, pid);
2557 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2558 init_task_pid(p, PIDTYPE_SID, task_session(current));
2559
2560 if (is_child_reaper(pid)) {
2561 ns_of_pid(pid)->child_reaper = p;
2562 p->signal->flags |= SIGNAL_UNKILLABLE;
2563 }
2564 p->signal->shared_pending.signal = delayed.signal;
2565 p->signal->tty = tty_kref_get(current->signal->tty);
2566 /*
2567 * Inherit has_child_subreaper flag under the same
2568 * tasklist_lock with adding child to the process tree
2569 * for propagate_has_child_subreaper optimization.
2570 */
2571 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2572 p->real_parent->signal->is_child_subreaper;
2573 list_add_tail(&p->sibling, &p->real_parent->children);
2574 list_add_tail_rcu(&p->tasks, &init_task.tasks);
2575 attach_pid(p, PIDTYPE_TGID);
2576 attach_pid(p, PIDTYPE_PGID);
2577 attach_pid(p, PIDTYPE_SID);
2578 __this_cpu_inc(process_counts);
2579 } else {
2580 current->signal->nr_threads++;
2581 current->signal->quick_threads++;
2582 atomic_inc(¤t->signal->live);
2583 refcount_inc(¤t->signal->sigcnt);
2584 task_join_group_stop(p);
2585 list_add_tail_rcu(&p->thread_group,
2586 &p->group_leader->thread_group);
2587 list_add_tail_rcu(&p->thread_node,
2588 &p->signal->thread_head);
2589 }
2590 attach_pid(p, PIDTYPE_PID);
2591 nr_threads++;
2592 }
2593 trace_android_vh_copy_process(current, nr_threads, current->signal->nr_threads);
2594 total_forks++;
2595 hlist_del_init(&delayed.node);
2596 spin_unlock(¤t->sighand->siglock);
2597 syscall_tracepoint_update(p);
2598 write_unlock_irq(&tasklist_lock);
2599
2600 if (pidfile)
2601 fd_install(pidfd, pidfile);
2602
2603 proc_fork_connector(p);
2604 sched_post_fork(p);
2605 cgroup_post_fork(p, args);
2606 perf_event_fork(p);
2607
2608 trace_task_newtask(p, clone_flags);
2609 uprobe_copy_process(p, clone_flags);
2610
2611 copy_oom_score_adj(clone_flags, p);
2612
2613 return p;
2614
2615 bad_fork_cancel_cgroup:
2616 sched_core_free(p);
2617 spin_unlock(¤t->sighand->siglock);
2618 write_unlock_irq(&tasklist_lock);
2619 cgroup_cancel_fork(p, args);
2620 bad_fork_put_pidfd:
2621 if (clone_flags & CLONE_PIDFD) {
2622 fput(pidfile);
2623 put_unused_fd(pidfd);
2624 }
2625 bad_fork_free_pid:
2626 if (pid != &init_struct_pid)
2627 free_pid(pid);
2628 bad_fork_cleanup_thread:
2629 exit_thread(p);
2630 bad_fork_cleanup_io:
2631 if (p->io_context)
2632 exit_io_context(p);
2633 bad_fork_cleanup_namespaces:
2634 exit_task_namespaces(p);
2635 bad_fork_cleanup_mm:
2636 if (p->mm) {
2637 mm_clear_owner(p->mm, p);
2638 mmput(p->mm);
2639 }
2640 bad_fork_cleanup_signal:
2641 if (!(clone_flags & CLONE_THREAD))
2642 free_signal_struct(p->signal);
2643 bad_fork_cleanup_sighand:
2644 __cleanup_sighand(p->sighand);
2645 bad_fork_cleanup_fs:
2646 exit_fs(p); /* blocking */
2647 bad_fork_cleanup_files:
2648 exit_files(p); /* blocking */
2649 bad_fork_cleanup_semundo:
2650 exit_sem(p);
2651 bad_fork_cleanup_security:
2652 security_task_free(p);
2653 bad_fork_cleanup_audit:
2654 audit_free(p);
2655 bad_fork_cleanup_perf:
2656 perf_event_free_task(p);
2657 bad_fork_cleanup_policy:
2658 lockdep_free_task(p);
2659 #ifdef CONFIG_NUMA
2660 mpol_put(p->mempolicy);
2661 #endif
2662 bad_fork_cleanup_delayacct:
2663 delayacct_tsk_free(p);
2664 bad_fork_cleanup_count:
2665 dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2666 exit_creds(p);
2667 bad_fork_free:
2668 WRITE_ONCE(p->__state, TASK_DEAD);
2669 exit_task_stack_account(p);
2670 put_task_stack(p);
2671 delayed_free_task(p);
2672 fork_out:
2673 spin_lock_irq(¤t->sighand->siglock);
2674 hlist_del_init(&delayed.node);
2675 spin_unlock_irq(¤t->sighand->siglock);
2676 return ERR_PTR(retval);
2677 }
2678
init_idle_pids(struct task_struct * idle)2679 static inline void init_idle_pids(struct task_struct *idle)
2680 {
2681 enum pid_type type;
2682
2683 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2684 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2685 init_task_pid(idle, type, &init_struct_pid);
2686 }
2687 }
2688
idle_dummy(void * dummy)2689 static int idle_dummy(void *dummy)
2690 {
2691 /* This function is never called */
2692 return 0;
2693 }
2694
fork_idle(int cpu)2695 struct task_struct * __init fork_idle(int cpu)
2696 {
2697 struct task_struct *task;
2698 struct kernel_clone_args args = {
2699 .flags = CLONE_VM,
2700 .fn = &idle_dummy,
2701 .fn_arg = NULL,
2702 .kthread = 1,
2703 .idle = 1,
2704 };
2705
2706 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2707 if (!IS_ERR(task)) {
2708 init_idle_pids(task);
2709 init_idle(task, cpu);
2710 }
2711
2712 return task;
2713 }
2714
2715 /*
2716 * This is like kernel_clone(), but shaved down and tailored to just
2717 * creating io_uring workers. It returns a created task, or an error pointer.
2718 * The returned task is inactive, and the caller must fire it up through
2719 * wake_up_new_task(p). All signals are blocked in the created task.
2720 */
create_io_thread(int (* fn)(void *),void * arg,int node)2721 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2722 {
2723 unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2724 CLONE_IO;
2725 struct kernel_clone_args args = {
2726 .flags = ((lower_32_bits(flags) | CLONE_VM |
2727 CLONE_UNTRACED) & ~CSIGNAL),
2728 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2729 .fn = fn,
2730 .fn_arg = arg,
2731 .io_thread = 1,
2732 };
2733
2734 return copy_process(NULL, 0, node, &args);
2735 }
2736
2737 /*
2738 * Ok, this is the main fork-routine.
2739 *
2740 * It copies the process, and if successful kick-starts
2741 * it and waits for it to finish using the VM if required.
2742 *
2743 * args->exit_signal is expected to be checked for sanity by the caller.
2744 */
kernel_clone(struct kernel_clone_args * args)2745 pid_t kernel_clone(struct kernel_clone_args *args)
2746 {
2747 u64 clone_flags = args->flags;
2748 struct completion vfork;
2749 struct pid *pid;
2750 struct task_struct *p;
2751 int trace = 0;
2752 pid_t nr;
2753
2754 /*
2755 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2756 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2757 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2758 * field in struct clone_args and it still doesn't make sense to have
2759 * them both point at the same memory location. Performing this check
2760 * here has the advantage that we don't need to have a separate helper
2761 * to check for legacy clone().
2762 */
2763 if ((args->flags & CLONE_PIDFD) &&
2764 (args->flags & CLONE_PARENT_SETTID) &&
2765 (args->pidfd == args->parent_tid))
2766 return -EINVAL;
2767
2768 /*
2769 * Determine whether and which event to report to ptracer. When
2770 * called from kernel_thread or CLONE_UNTRACED is explicitly
2771 * requested, no event is reported; otherwise, report if the event
2772 * for the type of forking is enabled.
2773 */
2774 if (!(clone_flags & CLONE_UNTRACED)) {
2775 if (clone_flags & CLONE_VFORK)
2776 trace = PTRACE_EVENT_VFORK;
2777 else if (args->exit_signal != SIGCHLD)
2778 trace = PTRACE_EVENT_CLONE;
2779 else
2780 trace = PTRACE_EVENT_FORK;
2781
2782 if (likely(!ptrace_event_enabled(current, trace)))
2783 trace = 0;
2784 }
2785
2786 p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2787 add_latent_entropy();
2788
2789 if (IS_ERR(p))
2790 return PTR_ERR(p);
2791
2792 cpufreq_task_times_alloc(p);
2793
2794 /*
2795 * Do this prior waking up the new thread - the thread pointer
2796 * might get invalid after that point, if the thread exits quickly.
2797 */
2798 trace_sched_process_fork(current, p);
2799
2800 pid = get_task_pid(p, PIDTYPE_PID);
2801 nr = pid_vnr(pid);
2802
2803 if (clone_flags & CLONE_PARENT_SETTID)
2804 put_user(nr, args->parent_tid);
2805
2806 if (clone_flags & CLONE_VFORK) {
2807 p->vfork_done = &vfork;
2808 init_completion(&vfork);
2809 get_task_struct(p);
2810 }
2811
2812 if (IS_ENABLED(CONFIG_LRU_GEN) && !(clone_flags & CLONE_VM)) {
2813 /* lock the task to synchronize with memcg migration */
2814 task_lock(p);
2815 lru_gen_add_mm(p->mm);
2816 task_unlock(p);
2817 }
2818
2819 wake_up_new_task(p);
2820
2821 /* forking complete and child started to run, tell ptracer */
2822 if (unlikely(trace))
2823 ptrace_event_pid(trace, pid);
2824
2825 if (clone_flags & CLONE_VFORK) {
2826 if (!wait_for_vfork_done(p, &vfork))
2827 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2828 }
2829
2830 put_pid(pid);
2831 return nr;
2832 }
2833
2834 /*
2835 * Create a kernel thread.
2836 */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)2837 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2838 {
2839 struct kernel_clone_args args = {
2840 .flags = ((lower_32_bits(flags) | CLONE_VM |
2841 CLONE_UNTRACED) & ~CSIGNAL),
2842 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2843 .fn = fn,
2844 .fn_arg = arg,
2845 .kthread = 1,
2846 };
2847
2848 return kernel_clone(&args);
2849 }
2850
2851 /*
2852 * Create a user mode thread.
2853 */
user_mode_thread(int (* fn)(void *),void * arg,unsigned long flags)2854 pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags)
2855 {
2856 struct kernel_clone_args args = {
2857 .flags = ((lower_32_bits(flags) | CLONE_VM |
2858 CLONE_UNTRACED) & ~CSIGNAL),
2859 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2860 .fn = fn,
2861 .fn_arg = arg,
2862 };
2863
2864 return kernel_clone(&args);
2865 }
2866
2867 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)2868 SYSCALL_DEFINE0(fork)
2869 {
2870 #ifdef CONFIG_MMU
2871 struct kernel_clone_args args = {
2872 .exit_signal = SIGCHLD,
2873 };
2874
2875 return kernel_clone(&args);
2876 #else
2877 /* can not support in nommu mode */
2878 return -EINVAL;
2879 #endif
2880 }
2881 #endif
2882
2883 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)2884 SYSCALL_DEFINE0(vfork)
2885 {
2886 struct kernel_clone_args args = {
2887 .flags = CLONE_VFORK | CLONE_VM,
2888 .exit_signal = SIGCHLD,
2889 };
2890
2891 return kernel_clone(&args);
2892 }
2893 #endif
2894
2895 #ifdef __ARCH_WANT_SYS_CLONE
2896 #ifdef CONFIG_CLONE_BACKWARDS
SYSCALL_DEFINE5(clone,unsigned long,clone_flags,unsigned long,newsp,int __user *,parent_tidptr,unsigned long,tls,int __user *,child_tidptr)2897 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2898 int __user *, parent_tidptr,
2899 unsigned long, tls,
2900 int __user *, child_tidptr)
2901 #elif defined(CONFIG_CLONE_BACKWARDS2)
2902 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2903 int __user *, parent_tidptr,
2904 int __user *, child_tidptr,
2905 unsigned long, tls)
2906 #elif defined(CONFIG_CLONE_BACKWARDS3)
2907 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2908 int, stack_size,
2909 int __user *, parent_tidptr,
2910 int __user *, child_tidptr,
2911 unsigned long, tls)
2912 #else
2913 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2914 int __user *, parent_tidptr,
2915 int __user *, child_tidptr,
2916 unsigned long, tls)
2917 #endif
2918 {
2919 struct kernel_clone_args args = {
2920 .flags = (lower_32_bits(clone_flags) & ~CSIGNAL),
2921 .pidfd = parent_tidptr,
2922 .child_tid = child_tidptr,
2923 .parent_tid = parent_tidptr,
2924 .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL),
2925 .stack = newsp,
2926 .tls = tls,
2927 };
2928
2929 return kernel_clone(&args);
2930 }
2931 #endif
2932
2933 #ifdef __ARCH_WANT_SYS_CLONE3
2934
copy_clone_args_from_user(struct kernel_clone_args * kargs,struct clone_args __user * uargs,size_t usize)2935 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2936 struct clone_args __user *uargs,
2937 size_t usize)
2938 {
2939 int err;
2940 struct clone_args args;
2941 pid_t *kset_tid = kargs->set_tid;
2942
2943 BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2944 CLONE_ARGS_SIZE_VER0);
2945 BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2946 CLONE_ARGS_SIZE_VER1);
2947 BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2948 CLONE_ARGS_SIZE_VER2);
2949 BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2950
2951 if (unlikely(usize > PAGE_SIZE))
2952 return -E2BIG;
2953 if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
2954 return -EINVAL;
2955
2956 err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2957 if (err)
2958 return err;
2959
2960 if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
2961 return -EINVAL;
2962
2963 if (unlikely(!args.set_tid && args.set_tid_size > 0))
2964 return -EINVAL;
2965
2966 if (unlikely(args.set_tid && args.set_tid_size == 0))
2967 return -EINVAL;
2968
2969 /*
2970 * Verify that higher 32bits of exit_signal are unset and that
2971 * it is a valid signal
2972 */
2973 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2974 !valid_signal(args.exit_signal)))
2975 return -EINVAL;
2976
2977 if ((args.flags & CLONE_INTO_CGROUP) &&
2978 (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2979 return -EINVAL;
2980
2981 *kargs = (struct kernel_clone_args){
2982 .flags = args.flags,
2983 .pidfd = u64_to_user_ptr(args.pidfd),
2984 .child_tid = u64_to_user_ptr(args.child_tid),
2985 .parent_tid = u64_to_user_ptr(args.parent_tid),
2986 .exit_signal = args.exit_signal,
2987 .stack = args.stack,
2988 .stack_size = args.stack_size,
2989 .tls = args.tls,
2990 .set_tid_size = args.set_tid_size,
2991 .cgroup = args.cgroup,
2992 };
2993
2994 if (args.set_tid &&
2995 copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
2996 (kargs->set_tid_size * sizeof(pid_t))))
2997 return -EFAULT;
2998
2999 kargs->set_tid = kset_tid;
3000
3001 return 0;
3002 }
3003
3004 /**
3005 * clone3_stack_valid - check and prepare stack
3006 * @kargs: kernel clone args
3007 *
3008 * Verify that the stack arguments userspace gave us are sane.
3009 * In addition, set the stack direction for userspace since it's easy for us to
3010 * determine.
3011 */
clone3_stack_valid(struct kernel_clone_args * kargs)3012 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
3013 {
3014 if (kargs->stack == 0) {
3015 if (kargs->stack_size > 0)
3016 return false;
3017 } else {
3018 if (kargs->stack_size == 0)
3019 return false;
3020
3021 if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
3022 return false;
3023
3024 #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
3025 kargs->stack += kargs->stack_size;
3026 #endif
3027 }
3028
3029 return true;
3030 }
3031
clone3_args_valid(struct kernel_clone_args * kargs)3032 static bool clone3_args_valid(struct kernel_clone_args *kargs)
3033 {
3034 /* Verify that no unknown flags are passed along. */
3035 if (kargs->flags &
3036 ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
3037 return false;
3038
3039 /*
3040 * - make the CLONE_DETACHED bit reusable for clone3
3041 * - make the CSIGNAL bits reusable for clone3
3042 */
3043 if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
3044 return false;
3045
3046 if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
3047 (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
3048 return false;
3049
3050 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
3051 kargs->exit_signal)
3052 return false;
3053
3054 if (!clone3_stack_valid(kargs))
3055 return false;
3056
3057 return true;
3058 }
3059
3060 /**
3061 * clone3 - create a new process with specific properties
3062 * @uargs: argument structure
3063 * @size: size of @uargs
3064 *
3065 * clone3() is the extensible successor to clone()/clone2().
3066 * It takes a struct as argument that is versioned by its size.
3067 *
3068 * Return: On success, a positive PID for the child process.
3069 * On error, a negative errno number.
3070 */
SYSCALL_DEFINE2(clone3,struct clone_args __user *,uargs,size_t,size)3071 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
3072 {
3073 int err;
3074
3075 struct kernel_clone_args kargs;
3076 pid_t set_tid[MAX_PID_NS_LEVEL];
3077
3078 kargs.set_tid = set_tid;
3079
3080 err = copy_clone_args_from_user(&kargs, uargs, size);
3081 if (err)
3082 return err;
3083
3084 if (!clone3_args_valid(&kargs))
3085 return -EINVAL;
3086
3087 return kernel_clone(&kargs);
3088 }
3089 #endif
3090
walk_process_tree(struct task_struct * top,proc_visitor visitor,void * data)3091 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
3092 {
3093 struct task_struct *leader, *parent, *child;
3094 int res;
3095
3096 read_lock(&tasklist_lock);
3097 leader = top = top->group_leader;
3098 down:
3099 for_each_thread(leader, parent) {
3100 list_for_each_entry(child, &parent->children, sibling) {
3101 res = visitor(child, data);
3102 if (res) {
3103 if (res < 0)
3104 goto out;
3105 leader = child;
3106 goto down;
3107 }
3108 up:
3109 ;
3110 }
3111 }
3112
3113 if (leader != top) {
3114 child = leader;
3115 parent = child->real_parent;
3116 leader = parent->group_leader;
3117 goto up;
3118 }
3119 out:
3120 read_unlock(&tasklist_lock);
3121 }
3122
3123 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
3124 #define ARCH_MIN_MMSTRUCT_ALIGN 0
3125 #endif
3126
sighand_ctor(void * data)3127 static void sighand_ctor(void *data)
3128 {
3129 struct sighand_struct *sighand = data;
3130
3131 spin_lock_init(&sighand->siglock);
3132 init_waitqueue_head(&sighand->signalfd_wqh);
3133 }
3134
mm_cache_init(void)3135 void __init mm_cache_init(void)
3136 {
3137 unsigned int mm_size;
3138
3139 /*
3140 * The mm_cpumask is located at the end of mm_struct, and is
3141 * dynamically sized based on the maximum CPU number this system
3142 * can have, taking hotplug into account (nr_cpu_ids).
3143 */
3144 mm_size = sizeof(struct mm_struct) + cpumask_size();
3145
3146 mm_cachep = kmem_cache_create_usercopy("mm_struct",
3147 mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
3148 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3149 offsetof(struct mm_struct, saved_auxv),
3150 sizeof_field(struct mm_struct, saved_auxv),
3151 NULL);
3152 }
3153
proc_caches_init(void)3154 void __init proc_caches_init(void)
3155 {
3156 sighand_cachep = kmem_cache_create("sighand_cache",
3157 sizeof(struct sighand_struct), 0,
3158 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
3159 SLAB_ACCOUNT, sighand_ctor);
3160 signal_cachep = kmem_cache_create("signal_cache",
3161 sizeof(struct signal_struct), 0,
3162 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3163 NULL);
3164 files_cachep = kmem_cache_create("files_cache",
3165 sizeof(struct files_struct), 0,
3166 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3167 NULL);
3168 fs_cachep = kmem_cache_create("fs_cache",
3169 sizeof(struct fs_struct), 0,
3170 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3171 NULL);
3172
3173 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
3174 #ifdef CONFIG_PER_VMA_LOCK
3175 vma_lock_cachep = KMEM_CACHE(vma_lock, SLAB_PANIC|SLAB_ACCOUNT);
3176 #endif
3177 mmap_init();
3178 nsproxy_cache_init();
3179 }
3180
3181 /*
3182 * Check constraints on flags passed to the unshare system call.
3183 */
check_unshare_flags(unsigned long unshare_flags)3184 static int check_unshare_flags(unsigned long unshare_flags)
3185 {
3186 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
3187 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
3188 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
3189 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
3190 CLONE_NEWTIME))
3191 return -EINVAL;
3192 /*
3193 * Not implemented, but pretend it works if there is nothing
3194 * to unshare. Note that unsharing the address space or the
3195 * signal handlers also need to unshare the signal queues (aka
3196 * CLONE_THREAD).
3197 */
3198 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
3199 if (!thread_group_empty(current))
3200 return -EINVAL;
3201 }
3202 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
3203 if (refcount_read(¤t->sighand->count) > 1)
3204 return -EINVAL;
3205 }
3206 if (unshare_flags & CLONE_VM) {
3207 if (!current_is_single_threaded())
3208 return -EINVAL;
3209 }
3210
3211 return 0;
3212 }
3213
3214 /*
3215 * Unshare the filesystem structure if it is being shared
3216 */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)3217 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3218 {
3219 struct fs_struct *fs = current->fs;
3220
3221 if (!(unshare_flags & CLONE_FS) || !fs)
3222 return 0;
3223
3224 /* don't need lock here; in the worst case we'll do useless copy */
3225 if (fs->users == 1)
3226 return 0;
3227
3228 *new_fsp = copy_fs_struct(fs);
3229 if (!*new_fsp)
3230 return -ENOMEM;
3231
3232 return 0;
3233 }
3234
3235 /*
3236 * Unshare file descriptor table if it is being shared
3237 */
unshare_fd(unsigned long unshare_flags,unsigned int max_fds,struct files_struct ** new_fdp)3238 int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
3239 struct files_struct **new_fdp)
3240 {
3241 struct files_struct *fd = current->files;
3242 int error = 0;
3243
3244 if ((unshare_flags & CLONE_FILES) &&
3245 (fd && atomic_read(&fd->count) > 1)) {
3246 *new_fdp = dup_fd(fd, max_fds, &error);
3247 if (!*new_fdp)
3248 return error;
3249 }
3250
3251 return 0;
3252 }
3253
3254 /*
3255 * unshare allows a process to 'unshare' part of the process
3256 * context which was originally shared using clone. copy_*
3257 * functions used by kernel_clone() cannot be used here directly
3258 * because they modify an inactive task_struct that is being
3259 * constructed. Here we are modifying the current, active,
3260 * task_struct.
3261 */
ksys_unshare(unsigned long unshare_flags)3262 int ksys_unshare(unsigned long unshare_flags)
3263 {
3264 struct fs_struct *fs, *new_fs = NULL;
3265 struct files_struct *new_fd = NULL;
3266 struct cred *new_cred = NULL;
3267 struct nsproxy *new_nsproxy = NULL;
3268 int do_sysvsem = 0;
3269 int err;
3270
3271 /*
3272 * If unsharing a user namespace must also unshare the thread group
3273 * and unshare the filesystem root and working directories.
3274 */
3275 if (unshare_flags & CLONE_NEWUSER)
3276 unshare_flags |= CLONE_THREAD | CLONE_FS;
3277 /*
3278 * If unsharing vm, must also unshare signal handlers.
3279 */
3280 if (unshare_flags & CLONE_VM)
3281 unshare_flags |= CLONE_SIGHAND;
3282 /*
3283 * If unsharing a signal handlers, must also unshare the signal queues.
3284 */
3285 if (unshare_flags & CLONE_SIGHAND)
3286 unshare_flags |= CLONE_THREAD;
3287 /*
3288 * If unsharing namespace, must also unshare filesystem information.
3289 */
3290 if (unshare_flags & CLONE_NEWNS)
3291 unshare_flags |= CLONE_FS;
3292
3293 err = check_unshare_flags(unshare_flags);
3294 if (err)
3295 goto bad_unshare_out;
3296 /*
3297 * CLONE_NEWIPC must also detach from the undolist: after switching
3298 * to a new ipc namespace, the semaphore arrays from the old
3299 * namespace are unreachable.
3300 */
3301 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
3302 do_sysvsem = 1;
3303 err = unshare_fs(unshare_flags, &new_fs);
3304 if (err)
3305 goto bad_unshare_out;
3306 err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3307 if (err)
3308 goto bad_unshare_cleanup_fs;
3309 err = unshare_userns(unshare_flags, &new_cred);
3310 if (err)
3311 goto bad_unshare_cleanup_fd;
3312 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3313 new_cred, new_fs);
3314 if (err)
3315 goto bad_unshare_cleanup_cred;
3316
3317 if (new_cred) {
3318 err = set_cred_ucounts(new_cred);
3319 if (err)
3320 goto bad_unshare_cleanup_cred;
3321 }
3322
3323 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
3324 if (do_sysvsem) {
3325 /*
3326 * CLONE_SYSVSEM is equivalent to sys_exit().
3327 */
3328 exit_sem(current);
3329 }
3330 if (unshare_flags & CLONE_NEWIPC) {
3331 /* Orphan segments in old ns (see sem above). */
3332 exit_shm(current);
3333 shm_init_task(current);
3334 }
3335
3336 if (new_nsproxy)
3337 switch_task_namespaces(current, new_nsproxy);
3338
3339 task_lock(current);
3340
3341 if (new_fs) {
3342 fs = current->fs;
3343 spin_lock(&fs->lock);
3344 current->fs = new_fs;
3345 if (--fs->users)
3346 new_fs = NULL;
3347 else
3348 new_fs = fs;
3349 spin_unlock(&fs->lock);
3350 }
3351
3352 if (new_fd)
3353 swap(current->files, new_fd);
3354
3355 task_unlock(current);
3356
3357 if (new_cred) {
3358 /* Install the new user namespace */
3359 commit_creds(new_cred);
3360 new_cred = NULL;
3361 }
3362 }
3363
3364 perf_event_namespaces(current);
3365
3366 bad_unshare_cleanup_cred:
3367 if (new_cred)
3368 put_cred(new_cred);
3369 bad_unshare_cleanup_fd:
3370 if (new_fd)
3371 put_files_struct(new_fd);
3372
3373 bad_unshare_cleanup_fs:
3374 if (new_fs)
3375 free_fs_struct(new_fs);
3376
3377 bad_unshare_out:
3378 return err;
3379 }
3380
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)3381 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3382 {
3383 return ksys_unshare(unshare_flags);
3384 }
3385
3386 /*
3387 * Helper to unshare the files of the current task.
3388 * We don't want to expose copy_files internals to
3389 * the exec layer of the kernel.
3390 */
3391
unshare_files(void)3392 int unshare_files(void)
3393 {
3394 struct task_struct *task = current;
3395 struct files_struct *old, *copy = NULL;
3396 int error;
3397
3398 error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, ©);
3399 if (error || !copy)
3400 return error;
3401
3402 old = task->files;
3403 task_lock(task);
3404 task->files = copy;
3405 task_unlock(task);
3406 put_files_struct(old);
3407 return 0;
3408 }
3409
sysctl_max_threads(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3410 int sysctl_max_threads(struct ctl_table *table, int write,
3411 void *buffer, size_t *lenp, loff_t *ppos)
3412 {
3413 struct ctl_table t;
3414 int ret;
3415 int threads = max_threads;
3416 int min = 1;
3417 int max = MAX_THREADS;
3418
3419 t = *table;
3420 t.data = &threads;
3421 t.extra1 = &min;
3422 t.extra2 = &max;
3423
3424 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3425 if (ret || !write)
3426 return ret;
3427
3428 max_threads = threads;
3429
3430 return 0;
3431 }
3432