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