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