Linux 6.9-rc4
[sfrench/cifs-2.6.git] / kernel / fork.c
index b2b87d450b80b5e08899b1677848d466a643ead8..39a5046c2f0bf49e1bcade15c4c3c5574742b09d 100644 (file)
 #include <linux/fdtable.h>
 #include <linux/iocontext.h>
 #include <linux/key.h>
+#include <linux/kmsan.h>
 #include <linux/binfmts.h>
 #include <linux/mman.h>
 #include <linux/mmu_notifier.h>
-#include <linux/hmm.h>
 #include <linux/fs.h>
 #include <linux/mm.h>
-#include <linux/vmacache.h>
+#include <linux/mm_inline.h>
 #include <linux/nsproxy.h>
 #include <linux/capability.h>
 #include <linux/cpu.h>
@@ -53,6 +53,7 @@
 #include <linux/seccomp.h>
 #include <linux/swap.h>
 #include <linux/syscalls.h>
+#include <linux/syscall_user_dispatch.h>
 #include <linux/jiffies.h>
 #include <linux/futex.h>
 #include <linux/compat.h>
@@ -75,9 +76,7 @@
 #include <linux/freezer.h>
 #include <linux/delayacct.h>
 #include <linux/taskstats_kern.h>
-#include <linux/random.h>
 #include <linux/tty.h>
-#include <linux/blkdev.h>
 #include <linux/fs_struct.h>
 #include <linux/magic.h>
 #include <linux/perf_event.h>
 #include <linux/livepatch.h>
 #include <linux/thread_info.h>
 #include <linux/stackleak.h>
+#include <linux/kasan.h>
+#include <linux/scs.h>
+#include <linux/io_uring.h>
+#include <linux/bpf.h>
+#include <linux/stackprotector.h>
+#include <linux/user_events.h>
+#include <linux/iommu.h>
+#include <linux/rseq.h>
+#include <uapi/linux/pidfd.h>
+#include <linux/pidfs.h>
 
-#include <asm/pgtable.h>
 #include <asm/pgalloc.h>
 #include <linux/uaccess.h>
 #include <asm/mmu_context.h>
 unsigned long total_forks;     /* Handle normal Linux uptimes. */
 int nr_threads;                        /* The idle threads do not count.. */
 
-int max_threads;               /* tunable limit on nr_threads */
+static int max_threads;                /* tunable limit on nr_threads */
+
+#define NAMED_ARRAY_INDEX(x)   [x] = __stringify(x)
+
+static const char * const resident_page_types[] = {
+       NAMED_ARRAY_INDEX(MM_FILEPAGES),
+       NAMED_ARRAY_INDEX(MM_ANONPAGES),
+       NAMED_ARRAY_INDEX(MM_SWAPENTS),
+       NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
+};
 
 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
 
@@ -152,7 +169,6 @@ void __weak arch_release_task_struct(struct task_struct *tsk)
 {
 }
 
-#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
 static struct kmem_cache *task_struct_cachep;
 
 static inline struct task_struct *alloc_task_struct_node(int node)
@@ -164,9 +180,6 @@ static inline void free_task_struct(struct task_struct *tsk)
 {
        kmem_cache_free(task_struct_cachep, tsk);
 }
-#endif
-
-#ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
 
 /*
  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
@@ -174,7 +187,7 @@ static inline void free_task_struct(struct task_struct *tsk)
  */
 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
 
-#ifdef CONFIG_VMAP_STACK
+#  ifdef CONFIG_VMAP_STACK
 /*
  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
  * flush.  Try to minimize the number of calls by caching stacks.
@@ -182,6 +195,41 @@ static inline void free_task_struct(struct task_struct *tsk)
 #define NR_CACHED_STACKS 2
 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
 
+struct vm_stack {
+       struct rcu_head rcu;
+       struct vm_struct *stack_vm_area;
+};
+
+static bool try_release_thread_stack_to_cache(struct vm_struct *vm)
+{
+       unsigned int i;
+
+       for (i = 0; i < NR_CACHED_STACKS; i++) {
+               if (this_cpu_cmpxchg(cached_stacks[i], NULL, vm) != NULL)
+                       continue;
+               return true;
+       }
+       return false;
+}
+
+static void thread_stack_free_rcu(struct rcu_head *rh)
+{
+       struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu);
+
+       if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area))
+               return;
+
+       vfree(vm_stack);
+}
+
+static void thread_stack_delayed_free(struct task_struct *tsk)
+{
+       struct vm_stack *vm_stack = tsk->stack;
+
+       vm_stack->stack_vm_area = tsk->stack_vm_area;
+       call_rcu(&vm_stack->rcu, thread_stack_free_rcu);
+}
+
 static int free_vm_stack_cache(unsigned int cpu)
 {
        struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
@@ -199,11 +247,31 @@ static int free_vm_stack_cache(unsigned int cpu)
 
        return 0;
 }
-#endif
 
-static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
+static int memcg_charge_kernel_stack(struct vm_struct *vm)
 {
-#ifdef CONFIG_VMAP_STACK
+       int i;
+       int ret;
+       int nr_charged = 0;
+
+       BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
+
+       for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
+               ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
+               if (ret)
+                       goto err;
+               nr_charged++;
+       }
+       return 0;
+err:
+       for (i = 0; i < nr_charged; i++)
+               memcg_kmem_uncharge_page(vm->pages[i], 0);
+       return ret;
+}
+
+static int alloc_thread_stack_node(struct task_struct *tsk, int node)
+{
+       struct vm_struct *vm;
        void *stack;
        int i;
 
@@ -215,12 +283,22 @@ static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
                if (!s)
                        continue;
 
+               /* Reset stack metadata. */
+               kasan_unpoison_range(s->addr, THREAD_SIZE);
+
+               stack = kasan_reset_tag(s->addr);
+
                /* Clear stale pointers from reused stack. */
-               memset(s->addr, 0, THREAD_SIZE);
+               memset(stack, 0, THREAD_SIZE);
+
+               if (memcg_charge_kernel_stack(s)) {
+                       vfree(s->addr);
+                       return -ENOMEM;
+               }
 
                tsk->stack_vm_area = s;
-               tsk->stack = s->addr;
-               return s->addr;
+               tsk->stack = stack;
+               return 0;
        }
 
        /*
@@ -233,71 +311,96 @@ static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
                                     THREADINFO_GFP & ~__GFP_ACCOUNT,
                                     PAGE_KERNEL,
                                     0, node, __builtin_return_address(0));
+       if (!stack)
+               return -ENOMEM;
 
+       vm = find_vm_area(stack);
+       if (memcg_charge_kernel_stack(vm)) {
+               vfree(stack);
+               return -ENOMEM;
+       }
        /*
         * We can't call find_vm_area() in interrupt context, and
         * free_thread_stack() can be called in interrupt context,
         * so cache the vm_struct.
         */
-       if (stack) {
-               tsk->stack_vm_area = find_vm_area(stack);
-               tsk->stack = stack;
-       }
-       return stack;
-#else
-       struct page *page = alloc_pages_node(node, THREADINFO_GFP,
-                                            THREAD_SIZE_ORDER);
-
-       return page ? page_address(page) : NULL;
-#endif
+       tsk->stack_vm_area = vm;
+       stack = kasan_reset_tag(stack);
+       tsk->stack = stack;
+       return 0;
 }
 
-static inline void free_thread_stack(struct task_struct *tsk)
+static void free_thread_stack(struct task_struct *tsk)
 {
-#ifdef CONFIG_VMAP_STACK
-       struct vm_struct *vm = task_stack_vm_area(tsk);
+       if (!try_release_thread_stack_to_cache(tsk->stack_vm_area))
+               thread_stack_delayed_free(tsk);
 
-       if (vm) {
-               int i;
+       tsk->stack = NULL;
+       tsk->stack_vm_area = NULL;
+}
 
-               for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
-                       mod_memcg_page_state(vm->pages[i],
-                                            MEMCG_KERNEL_STACK_KB,
-                                            -(int)(PAGE_SIZE / 1024));
+#  else /* !CONFIG_VMAP_STACK */
 
-                       memcg_kmem_uncharge(vm->pages[i], 0);
-               }
+static void thread_stack_free_rcu(struct rcu_head *rh)
+{
+       __free_pages(virt_to_page(rh), THREAD_SIZE_ORDER);
+}
 
-               for (i = 0; i < NR_CACHED_STACKS; i++) {
-                       if (this_cpu_cmpxchg(cached_stacks[i],
-                                       NULL, tsk->stack_vm_area) != NULL)
-                               continue;
+static void thread_stack_delayed_free(struct task_struct *tsk)
+{
+       struct rcu_head *rh = tsk->stack;
 
-                       return;
-               }
+       call_rcu(rh, thread_stack_free_rcu);
+}
 
-               vfree_atomic(tsk->stack);
-               return;
+static int alloc_thread_stack_node(struct task_struct *tsk, int node)
+{
+       struct page *page = alloc_pages_node(node, THREADINFO_GFP,
+                                            THREAD_SIZE_ORDER);
+
+       if (likely(page)) {
+               tsk->stack = kasan_reset_tag(page_address(page));
+               return 0;
        }
-#endif
+       return -ENOMEM;
+}
 
-       __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
+static void free_thread_stack(struct task_struct *tsk)
+{
+       thread_stack_delayed_free(tsk);
+       tsk->stack = NULL;
 }
-# else
+
+#  endif /* CONFIG_VMAP_STACK */
+# else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
+
 static struct kmem_cache *thread_stack_cache;
 
-static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
-                                                 int node)
+static void thread_stack_free_rcu(struct rcu_head *rh)
+{
+       kmem_cache_free(thread_stack_cache, rh);
+}
+
+static void thread_stack_delayed_free(struct task_struct *tsk)
+{
+       struct rcu_head *rh = tsk->stack;
+
+       call_rcu(rh, thread_stack_free_rcu);
+}
+
+static int alloc_thread_stack_node(struct task_struct *tsk, int node)
 {
        unsigned long *stack;
        stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
+       stack = kasan_reset_tag(stack);
        tsk->stack = stack;
-       return stack;
+       return stack ? 0 : -ENOMEM;
 }
 
 static void free_thread_stack(struct task_struct *tsk)
 {
-       kmem_cache_free(thread_stack_cache, tsk->stack);
+       thread_stack_delayed_free(tsk);
+       tsk->stack = NULL;
 }
 
 void thread_stack_cache_init(void)
@@ -307,8 +410,8 @@ void thread_stack_cache_init(void)
                                        THREAD_SIZE, NULL);
        BUG_ON(thread_stack_cache == NULL);
 }
-# endif
-#endif
+
+# endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
 
 /* SLAB cache for signal_struct structures (tsk->signal) */
 static struct kmem_cache *signal_cachep;
@@ -328,13 +431,49 @@ static struct kmem_cache *vm_area_cachep;
 /* SLAB cache for mm_struct structures (tsk->mm) */
 static struct kmem_cache *mm_cachep;
 
+#ifdef CONFIG_PER_VMA_LOCK
+
+/* SLAB cache for vm_area_struct.lock */
+static struct kmem_cache *vma_lock_cachep;
+
+static bool vma_lock_alloc(struct vm_area_struct *vma)
+{
+       vma->vm_lock = kmem_cache_alloc(vma_lock_cachep, GFP_KERNEL);
+       if (!vma->vm_lock)
+               return false;
+
+       init_rwsem(&vma->vm_lock->lock);
+       vma->vm_lock_seq = -1;
+
+       return true;
+}
+
+static inline void vma_lock_free(struct vm_area_struct *vma)
+{
+       kmem_cache_free(vma_lock_cachep, vma->vm_lock);
+}
+
+#else /* CONFIG_PER_VMA_LOCK */
+
+static inline bool vma_lock_alloc(struct vm_area_struct *vma) { return true; }
+static inline void vma_lock_free(struct vm_area_struct *vma) {}
+
+#endif /* CONFIG_PER_VMA_LOCK */
+
 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
 {
        struct vm_area_struct *vma;
 
        vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
-       if (vma)
-               vma_init(vma, mm);
+       if (!vma)
+               return NULL;
+
+       vma_init(vma, mm);
+       if (!vma_lock_alloc(vma)) {
+               kmem_cache_free(vm_area_cachep, vma);
+               return NULL;
+       }
+
        return vma;
 }
 
@@ -342,90 +481,94 @@ struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
 {
        struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
 
-       if (new) {
-               *new = *orig;
-               INIT_LIST_HEAD(&new->anon_vma_chain);
+       if (!new)
+               return NULL;
+
+       ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
+       ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
+       /*
+        * orig->shared.rb may be modified concurrently, but the clone
+        * will be reinitialized.
+        */
+       data_race(memcpy(new, orig, sizeof(*new)));
+       if (!vma_lock_alloc(new)) {
+               kmem_cache_free(vm_area_cachep, new);
+               return NULL;
        }
+       INIT_LIST_HEAD(&new->anon_vma_chain);
+       vma_numab_state_init(new);
+       dup_anon_vma_name(orig, new);
+
        return new;
 }
 
-void vm_area_free(struct vm_area_struct *vma)
+void __vm_area_free(struct vm_area_struct *vma)
 {
+       vma_numab_state_free(vma);
+       free_anon_vma_name(vma);
+       vma_lock_free(vma);
        kmem_cache_free(vm_area_cachep, vma);
 }
 
-static void account_kernel_stack(struct task_struct *tsk, int account)
+#ifdef CONFIG_PER_VMA_LOCK
+static void vm_area_free_rcu_cb(struct rcu_head *head)
 {
-       void *stack = task_stack_page(tsk);
-       struct vm_struct *vm = task_stack_vm_area(tsk);
+       struct vm_area_struct *vma = container_of(head, struct vm_area_struct,
+                                                 vm_rcu);
+
+       /* The vma should not be locked while being destroyed. */
+       VM_BUG_ON_VMA(rwsem_is_locked(&vma->vm_lock->lock), vma);
+       __vm_area_free(vma);
+}
+#endif
 
-       BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
+void vm_area_free(struct vm_area_struct *vma)
+{
+#ifdef CONFIG_PER_VMA_LOCK
+       call_rcu(&vma->vm_rcu, vm_area_free_rcu_cb);
+#else
+       __vm_area_free(vma);
+#endif
+}
 
-       if (vm) {
+static void account_kernel_stack(struct task_struct *tsk, int account)
+{
+       if (IS_ENABLED(CONFIG_VMAP_STACK)) {
+               struct vm_struct *vm = task_stack_vm_area(tsk);
                int i;
 
-               BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
-
-               for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
-                       mod_zone_page_state(page_zone(vm->pages[i]),
-                                           NR_KERNEL_STACK_KB,
-                                           PAGE_SIZE / 1024 * account);
-               }
+               for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
+                       mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
+                                             account * (PAGE_SIZE / 1024));
        } else {
-               /*
-                * All stack pages are in the same zone and belong to the
-                * same memcg.
-                */
-               struct page *first_page = virt_to_page(stack);
+               void *stack = task_stack_page(tsk);
 
-               mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
-                                   THREAD_SIZE / 1024 * account);
-
-               mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
-                                    account * (THREAD_SIZE / 1024));
+               /* All stack pages are in the same node. */
+               mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
+                                     account * (THREAD_SIZE / 1024));
        }
 }
 
-static int memcg_charge_kernel_stack(struct task_struct *tsk)
+void exit_task_stack_account(struct task_struct *tsk)
 {
-#ifdef CONFIG_VMAP_STACK
-       struct vm_struct *vm = task_stack_vm_area(tsk);
-       int ret;
+       account_kernel_stack(tsk, -1);
 
-       if (vm) {
+       if (IS_ENABLED(CONFIG_VMAP_STACK)) {
+               struct vm_struct *vm;
                int i;
 
-               for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
-                       /*
-                        * If memcg_kmem_charge() fails, page->mem_cgroup
-                        * pointer is NULL, and both memcg_kmem_uncharge()
-                        * and mod_memcg_page_state() in free_thread_stack()
-                        * will ignore this page. So it's safe.
-                        */
-                       ret = memcg_kmem_charge(vm->pages[i], GFP_KERNEL, 0);
-                       if (ret)
-                               return ret;
-
-                       mod_memcg_page_state(vm->pages[i],
-                                            MEMCG_KERNEL_STACK_KB,
-                                            PAGE_SIZE / 1024);
-               }
+               vm = task_stack_vm_area(tsk);
+               for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
+                       memcg_kmem_uncharge_page(vm->pages[i], 0);
        }
-#endif
-       return 0;
 }
 
 static void release_task_stack(struct task_struct *tsk)
 {
-       if (WARN_ON(tsk->state != TASK_DEAD))
+       if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
                return;  /* Better to leak the stack than to free prematurely */
 
-       account_kernel_stack(tsk, -1);
        free_thread_stack(tsk);
-       tsk->stack = NULL;
-#ifdef CONFIG_VMAP_STACK
-       tsk->stack_vm_area = NULL;
-#endif
 }
 
 #ifdef CONFIG_THREAD_INFO_IN_TASK
@@ -438,6 +581,12 @@ void put_task_stack(struct task_struct *tsk)
 
 void free_task(struct task_struct *tsk)
 {
+#ifdef CONFIG_SECCOMP
+       WARN_ON_ONCE(tsk->seccomp.filter);
+#endif
+       release_user_cpus_ptr(tsk);
+       scs_release(tsk);
+
 #ifndef CONFIG_THREAD_INFO_IN_TASK
        /*
         * The task is finally done with both the stack and thread_info,
@@ -453,26 +602,40 @@ void free_task(struct task_struct *tsk)
 #endif
        rt_mutex_debug_task_free(tsk);
        ftrace_graph_exit_task(tsk);
-       put_seccomp_filter(tsk);
        arch_release_task_struct(tsk);
        if (tsk->flags & PF_KTHREAD)
                free_kthread_struct(tsk);
+       bpf_task_storage_free(tsk);
        free_task_struct(tsk);
 }
 EXPORT_SYMBOL(free_task);
 
+static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
+{
+       struct file *exe_file;
+
+       exe_file = get_mm_exe_file(oldmm);
+       RCU_INIT_POINTER(mm->exe_file, exe_file);
+       /*
+        * We depend on the oldmm having properly denied write access to the
+        * exe_file already.
+        */
+       if (exe_file && deny_write_access(exe_file))
+               pr_warn_once("deny_write_access() failed in %s\n", __func__);
+}
+
 #ifdef CONFIG_MMU
 static __latent_entropy int dup_mmap(struct mm_struct *mm,
                                        struct mm_struct *oldmm)
 {
-       struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
-       struct rb_node **rb_link, *rb_parent;
+       struct vm_area_struct *mpnt, *tmp;
        int retval;
-       unsigned long charge;
+       unsigned long charge = 0;
        LIST_HEAD(uf);
+       VMA_ITERATOR(vmi, mm, 0);
 
        uprobe_start_dup_mmap();
-       if (down_write_killable(&oldmm->mmap_sem)) {
+       if (mmap_write_lock_killable(oldmm)) {
                retval = -EINTR;
                goto fail_uprobe_end;
        }
@@ -481,31 +644,37 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,
        /*
         * Not linked in yet - no deadlock potential:
         */
-       down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
+       mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
 
        /* No ordering required: file already has been exposed. */
-       RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
+       dup_mm_exe_file(mm, oldmm);
 
        mm->total_vm = oldmm->total_vm;
        mm->data_vm = oldmm->data_vm;
        mm->exec_vm = oldmm->exec_vm;
        mm->stack_vm = oldmm->stack_vm;
 
-       rb_link = &mm->mm_rb.rb_node;
-       rb_parent = NULL;
-       pprev = &mm->mmap;
        retval = ksm_fork(mm, oldmm);
        if (retval)
                goto out;
-       retval = khugepaged_fork(mm, oldmm);
-       if (retval)
+       khugepaged_fork(mm, oldmm);
+
+       /* Use __mt_dup() to efficiently build an identical maple tree. */
+       retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
+       if (unlikely(retval))
                goto out;
 
-       prev = NULL;
-       for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
+       mt_clear_in_rcu(vmi.mas.tree);
+       for_each_vma(vmi, mpnt) {
                struct file *file;
 
+               vma_start_write(mpnt);
                if (mpnt->vm_flags & VM_DONTCOPY) {
+                       retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
+                                                   mpnt->vm_end, GFP_KERNEL);
+                       if (retval)
+                               goto loop_out;
+
                        vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
                        continue;
                }
@@ -516,7 +685,7 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,
                 */
                if (fatal_signal_pending(current)) {
                        retval = -EINTR;
-                       goto out;
+                       goto loop_out;
                }
                if (mpnt->vm_flags & VM_ACCOUNT) {
                        unsigned long len = vma_pages(mpnt);
@@ -536,25 +705,23 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,
                if (retval)
                        goto fail_nomem_anon_vma_fork;
                if (tmp->vm_flags & VM_WIPEONFORK) {
-                       /* VM_WIPEONFORK gets a clean slate in the child. */
+                       /*
+                        * VM_WIPEONFORK gets a clean slate in the child.
+                        * Don't prepare anon_vma until fault since we don't
+                        * copy page for current vma.
+                        */
                        tmp->anon_vma = NULL;
-                       if (anon_vma_prepare(tmp))
-                               goto fail_nomem_anon_vma_fork;
                } else if (anon_vma_fork(tmp, mpnt))
                        goto fail_nomem_anon_vma_fork;
-               tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
-               tmp->vm_next = tmp->vm_prev = NULL;
+               vm_flags_clear(tmp, VM_LOCKED_MASK);
                file = tmp->vm_file;
                if (file) {
-                       struct inode *inode = file_inode(file);
                        struct address_space *mapping = file->f_mapping;
 
                        get_file(file);
-                       if (tmp->vm_flags & VM_DENYWRITE)
-                               atomic_dec(&inode->i_writecount);
                        i_mmap_lock_write(mapping);
-                       if (tmp->vm_flags & VM_SHARED)
-                               atomic_inc(&mapping->i_mmap_writable);
+                       if (vma_is_shared_maywrite(tmp))
+                               mapping_allow_writable(mapping);
                        flush_dcache_mmap_lock(mapping);
                        /* insert tmp into the share list, just after mpnt */
                        vma_interval_tree_insert_after(tmp, mpnt,
@@ -564,45 +731,55 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,
                }
 
                /*
-                * Clear hugetlb-related page reserves for children. This only
-                * affects MAP_PRIVATE mappings. Faults generated by the child
-                * are not guaranteed to succeed, even if read-only
+                * Copy/update hugetlb private vma information.
                 */
                if (is_vm_hugetlb_page(tmp))
-                       reset_vma_resv_huge_pages(tmp);
+                       hugetlb_dup_vma_private(tmp);
 
                /*
-                * Link in the new vma and copy the page table entries.
+                * Link the vma into the MT. After using __mt_dup(), memory
+                * allocation is not necessary here, so it cannot fail.
                 */
-               *pprev = tmp;
-               pprev = &tmp->vm_next;
-               tmp->vm_prev = prev;
-               prev = tmp;
-
-               __vma_link_rb(mm, tmp, rb_link, rb_parent);
-               rb_link = &tmp->vm_rb.rb_right;
-               rb_parent = &tmp->vm_rb;
+               vma_iter_bulk_store(&vmi, tmp);
 
                mm->map_count++;
                if (!(tmp->vm_flags & VM_WIPEONFORK))
-                       retval = copy_page_range(mm, oldmm, mpnt);
+                       retval = copy_page_range(tmp, mpnt);
 
                if (tmp->vm_ops && tmp->vm_ops->open)
                        tmp->vm_ops->open(tmp);
 
-               if (retval)
-                       goto out;
+               if (retval) {
+                       mpnt = vma_next(&vmi);
+                       goto loop_out;
+               }
        }
        /* a new mm has just been created */
        retval = arch_dup_mmap(oldmm, mm);
+loop_out:
+       vma_iter_free(&vmi);
+       if (!retval) {
+               mt_set_in_rcu(vmi.mas.tree);
+       } else if (mpnt) {
+               /*
+                * The entire maple tree has already been duplicated. If the
+                * mmap duplication fails, mark the failure point with
+                * XA_ZERO_ENTRY. In exit_mmap(), if this marker is encountered,
+                * stop releasing VMAs that have not been duplicated after this
+                * point.
+                */
+               mas_set_range(&vmi.mas, mpnt->vm_start, mpnt->vm_end - 1);
+               mas_store(&vmi.mas, XA_ZERO_ENTRY);
+       }
 out:
-       up_write(&mm->mmap_sem);
+       mmap_write_unlock(mm);
        flush_tlb_mm(oldmm);
-       up_write(&oldmm->mmap_sem);
+       mmap_write_unlock(oldmm);
        dup_userfaultfd_complete(&uf);
 fail_uprobe_end:
        uprobe_end_dup_mmap();
        return retval;
+
 fail_nomem_anon_vma_fork:
        mpol_put(vma_policy(tmp));
 fail_nomem_policy:
@@ -610,7 +787,7 @@ fail_nomem_policy:
 fail_nomem:
        retval = -ENOMEM;
        vm_unacct_memory(charge);
-       goto out;
+       goto loop_out;
 }
 
 static inline int mm_alloc_pgd(struct mm_struct *mm)
@@ -628,9 +805,9 @@ static inline void mm_free_pgd(struct mm_struct *mm)
 #else
 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
 {
-       down_write(&oldmm->mmap_sem);
-       RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
-       up_write(&oldmm->mmap_sem);
+       mmap_write_lock(oldmm);
+       dup_mm_exe_file(mm, oldmm);
+       mmap_write_unlock(oldmm);
        return 0;
 }
 #define mm_alloc_pgd(mm)       (0)
@@ -641,12 +818,15 @@ static void check_mm(struct mm_struct *mm)
 {
        int i;
 
+       BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
+                        "Please make sure 'struct resident_page_types[]' is updated as well");
+
        for (i = 0; i < NR_MM_COUNTERS; i++) {
-               long x = atomic_long_read(&mm->rss_stat.count[i]);
+               long x = percpu_counter_sum(&mm->rss_stat[i]);
 
                if (unlikely(x))
-                       printk(KERN_ALERT "BUG: Bad rss-counter state "
-                                         "mm:%p idx:%d val:%ld\n", mm, i, x);
+                       pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
+                                mm, resident_page_types[i], x);
        }
 
        if (mm_pgtables_bytes(mm))
@@ -661,6 +841,67 @@ static void check_mm(struct mm_struct *mm)
 #define allocate_mm()  (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
 #define free_mm(mm)    (kmem_cache_free(mm_cachep, (mm)))
 
+static void do_check_lazy_tlb(void *arg)
+{
+       struct mm_struct *mm = arg;
+
+       WARN_ON_ONCE(current->active_mm == mm);
+}
+
+static void do_shoot_lazy_tlb(void *arg)
+{
+       struct mm_struct *mm = arg;
+
+       if (current->active_mm == mm) {
+               WARN_ON_ONCE(current->mm);
+               current->active_mm = &init_mm;
+               switch_mm(mm, &init_mm, current);
+       }
+}
+
+static void cleanup_lazy_tlbs(struct mm_struct *mm)
+{
+       if (!IS_ENABLED(CONFIG_MMU_LAZY_TLB_SHOOTDOWN)) {
+               /*
+                * In this case, lazy tlb mms are refounted and would not reach
+                * __mmdrop until all CPUs have switched away and mmdrop()ed.
+                */
+               return;
+       }
+
+       /*
+        * Lazy mm shootdown does not refcount "lazy tlb mm" usage, rather it
+        * requires lazy mm users to switch to another mm when the refcount
+        * drops to zero, before the mm is freed. This requires IPIs here to
+        * switch kernel threads to init_mm.
+        *
+        * archs that use IPIs to flush TLBs can piggy-back that lazy tlb mm
+        * switch with the final userspace teardown TLB flush which leaves the
+        * mm lazy on this CPU but no others, reducing the need for additional
+        * IPIs here. There are cases where a final IPI is still required here,
+        * such as the final mmdrop being performed on a different CPU than the
+        * one exiting, or kernel threads using the mm when userspace exits.
+        *
+        * IPI overheads have not found to be expensive, but they could be
+        * reduced in a number of possible ways, for example (roughly
+        * increasing order of complexity):
+        * - The last lazy reference created by exit_mm() could instead switch
+        *   to init_mm, however it's probable this will run on the same CPU
+        *   immediately afterwards, so this may not reduce IPIs much.
+        * - A batch of mms requiring IPIs could be gathered and freed at once.
+        * - CPUs store active_mm where it can be remotely checked without a
+        *   lock, to filter out false-positives in the cpumask.
+        * - After mm_users or mm_count reaches zero, switching away from the
+        *   mm could clear mm_cpumask to reduce some IPIs, perhaps together
+        *   with some batching or delaying of the final IPIs.
+        * - A delayed freeing and RCU-like quiescing sequence based on mm
+        *   switching to avoid IPIs completely.
+        */
+       on_each_cpu_mask(mm_cpumask(mm), do_shoot_lazy_tlb, (void *)mm, 1);
+       if (IS_ENABLED(CONFIG_DEBUG_VM_SHOOT_LAZIES))
+               on_each_cpu(do_check_lazy_tlb, (void *)mm, 1);
+}
+
 /*
  * Called when the last reference to the mm
  * is dropped: either by a lazy thread or by
@@ -670,13 +911,20 @@ void __mmdrop(struct mm_struct *mm)
 {
        BUG_ON(mm == &init_mm);
        WARN_ON_ONCE(mm == current->mm);
+
+       /* Ensure no CPUs are using this as their lazy tlb mm */
+       cleanup_lazy_tlbs(mm);
+
        WARN_ON_ONCE(mm == current->active_mm);
        mm_free_pgd(mm);
        destroy_context(mm);
-       hmm_mm_destroy(mm);
-       mmu_notifier_mm_destroy(mm);
+       mmu_notifier_subscriptions_destroy(mm);
        check_mm(mm);
        put_user_ns(mm->user_ns);
+       mm_pasid_drop(mm);
+       mm_destroy_cid(mm);
+       percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
+
        free_mm(mm);
 }
 EXPORT_SYMBOL_GPL(__mmdrop);
@@ -722,18 +970,26 @@ void __put_task_struct(struct task_struct *tsk)
        WARN_ON(refcount_read(&tsk->usage));
        WARN_ON(tsk == current);
 
+       io_uring_free(tsk);
        cgroup_free(tsk);
-       task_numa_free(tsk);
+       task_numa_free(tsk, true);
        security_task_free(tsk);
        exit_creds(tsk);
        delayacct_tsk_free(tsk);
        put_signal_struct(tsk->signal);
-
-       if (!profile_handoff_task(tsk))
-               free_task(tsk);
+       sched_core_free(tsk);
+       free_task(tsk);
 }
 EXPORT_SYMBOL_GPL(__put_task_struct);
 
+void __put_task_struct_rcu_cb(struct rcu_head *rhp)
+{
+       struct task_struct *task = container_of(rhp, struct task_struct, rcu);
+
+       __put_task_struct(task);
+}
+EXPORT_SYMBOL_GPL(__put_task_struct_rcu_cb);
+
 void __init __weak arch_task_cache_init(void) { }
 
 /*
@@ -783,7 +1039,6 @@ static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
 void __init fork_init(void)
 {
        int i;
-#ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
 #ifndef ARCH_MIN_TASKALIGN
 #define ARCH_MIN_TASKALIGN     0
 #endif
@@ -796,7 +1051,6 @@ void __init fork_init(void)
                        arch_task_struct_size, align,
                        SLAB_PANIC|SLAB_ACCOUNT,
                        useroffset, usersize, NULL);
-#endif
 
        /* do the arch specific task caches init */
        arch_task_cache_init();
@@ -808,15 +1062,21 @@ void __init fork_init(void)
        init_task.signal->rlim[RLIMIT_SIGPENDING] =
                init_task.signal->rlim[RLIMIT_NPROC];
 
-       for (i = 0; i < UCOUNT_COUNTS; i++) {
+       for (i = 0; i < UCOUNT_COUNTS; i++)
                init_user_ns.ucount_max[i] = max_threads/2;
-       }
+
+       set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_NPROC,      RLIM_INFINITY);
+       set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE,   RLIM_INFINITY);
+       set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
+       set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK,    RLIM_INFINITY);
 
 #ifdef CONFIG_VMAP_STACK
        cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
                          NULL, free_vm_stack_cache);
 #endif
 
+       scs_init();
+
        lockdep_init_task(&init_task);
        uprobes_init();
 }
@@ -839,8 +1099,6 @@ void set_task_stack_end_magic(struct task_struct *tsk)
 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
 {
        struct task_struct *tsk;
-       unsigned long *stack;
-       struct vm_struct *stack_vm_area __maybe_unused;
        int err;
 
        if (node == NUMA_NO_NODE)
@@ -849,30 +1107,20 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
        if (!tsk)
                return NULL;
 
-       stack = alloc_thread_stack_node(tsk, node);
-       if (!stack)
+       err = arch_dup_task_struct(tsk, orig);
+       if (err)
                goto free_tsk;
 
-       if (memcg_charge_kernel_stack(tsk))
-               goto free_stack;
-
-       stack_vm_area = task_stack_vm_area(tsk);
-
-       err = arch_dup_task_struct(tsk, orig);
+       err = alloc_thread_stack_node(tsk, node);
+       if (err)
+               goto free_tsk;
 
-       /*
-        * arch_dup_task_struct() clobbers the stack-related fields.  Make
-        * sure they're properly initialized before using any stack-related
-        * functions again.
-        */
-       tsk->stack = stack;
-#ifdef CONFIG_VMAP_STACK
-       tsk->stack_vm_area = stack_vm_area;
-#endif
 #ifdef CONFIG_THREAD_INFO_IN_TASK
        refcount_set(&tsk->stack_refcount, 1);
 #endif
+       account_kernel_stack(tsk, 1);
 
+       err = scs_prepare(tsk, node);
        if (err)
                goto free_stack;
 
@@ -890,42 +1138,65 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
        clear_user_return_notifier(tsk);
        clear_tsk_need_resched(tsk);
        set_task_stack_end_magic(tsk);
+       clear_syscall_work_syscall_user_dispatch(tsk);
 
 #ifdef CONFIG_STACKPROTECTOR
        tsk->stack_canary = get_random_canary();
 #endif
+       if (orig->cpus_ptr == &orig->cpus_mask)
+               tsk->cpus_ptr = &tsk->cpus_mask;
+       dup_user_cpus_ptr(tsk, orig, node);
 
        /*
-        * One for us, one for whoever does the "release_task()" (usually
-        * parent)
+        * One for the user space visible state that goes away when reaped.
+        * One for the scheduler.
         */
-       refcount_set(&tsk->usage, 2);
+       refcount_set(&tsk->rcu_users, 2);
+       /* One for the rcu users */
+       refcount_set(&tsk->usage, 1);
 #ifdef CONFIG_BLK_DEV_IO_TRACE
        tsk->btrace_seq = 0;
 #endif
        tsk->splice_pipe = NULL;
        tsk->task_frag.page = NULL;
        tsk->wake_q.next = NULL;
-
-       account_kernel_stack(tsk, 1);
+       tsk->worker_private = NULL;
 
        kcov_task_init(tsk);
+       kmsan_task_create(tsk);
+       kmap_local_fork(tsk);
 
 #ifdef CONFIG_FAULT_INJECTION
        tsk->fail_nth = 0;
 #endif
 
 #ifdef CONFIG_BLK_CGROUP
-       tsk->throttle_queue = NULL;
+       tsk->throttle_disk = NULL;
        tsk->use_memdelay = 0;
 #endif
 
+#ifdef CONFIG_ARCH_HAS_CPU_PASID
+       tsk->pasid_activated = 0;
+#endif
+
 #ifdef CONFIG_MEMCG
        tsk->active_memcg = NULL;
 #endif
+
+#ifdef CONFIG_CPU_SUP_INTEL
+       tsk->reported_split_lock = 0;
+#endif
+
+#ifdef CONFIG_SCHED_MM_CID
+       tsk->mm_cid = -1;
+       tsk->last_mm_cid = -1;
+       tsk->mm_cid_active = 0;
+       tsk->migrate_from_cpu = -1;
+#endif
        return tsk;
 
 free_stack:
+       exit_task_stack_account(tsk);
        free_thread_stack(tsk);
 free_tsk:
        free_task_struct(tsk);
@@ -982,14 +1253,16 @@ static void mm_init_uprobes_state(struct mm_struct *mm)
 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
        struct user_namespace *user_ns)
 {
-       mm->mmap = NULL;
-       mm->mm_rb = RB_ROOT;
-       mm->vmacache_seqnum = 0;
+       mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
+       mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
        atomic_set(&mm->mm_users, 1);
        atomic_set(&mm->mm_count, 1);
-       init_rwsem(&mm->mmap_sem);
+       seqcount_init(&mm->write_protect_seq);
+       mmap_init_lock(mm);
        INIT_LIST_HEAD(&mm->mmlist);
-       mm->core_state = NULL;
+#ifdef CONFIG_PER_VMA_LOCK
+       mm->mm_lock_seq = 0;
+#endif
        mm_pgtables_bytes_init(mm);
        mm->map_count = 0;
        mm->locked_vm = 0;
@@ -1000,17 +1273,18 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
        mm_init_cpumask(mm);
        mm_init_aio(mm);
        mm_init_owner(mm, p);
+       mm_pasid_init(mm);
        RCU_INIT_POINTER(mm->exe_file, NULL);
-       mmu_notifier_mm_init(mm);
-       hmm_mm_init(mm);
+       mmu_notifier_subscriptions_init(mm);
        init_tlb_flush_pending(mm);
 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
        mm->pmd_huge_pte = NULL;
 #endif
        mm_init_uprobes_state(mm);
+       hugetlb_count_init(mm);
 
        if (current->mm) {
-               mm->flags = current->mm->flags & MMF_INIT_MASK;
+               mm->flags = mmf_init_flags(current->mm->flags);
                mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
        } else {
                mm->flags = default_dump_filter;
@@ -1023,9 +1297,21 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
        if (init_new_context(p, mm))
                goto fail_nocontext;
 
+       if (mm_alloc_cid(mm))
+               goto fail_cid;
+
+       if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
+                                    NR_MM_COUNTERS))
+               goto fail_pcpu;
+
        mm->user_ns = get_user_ns(user_ns);
+       lru_gen_init_mm(mm);
        return mm;
 
+fail_pcpu:
+       mm_destroy_cid(mm);
+fail_cid:
+       destroy_context(mm);
 fail_nocontext:
        mm_free_pgd(mm);
 fail_nopgd:
@@ -1066,6 +1352,7 @@ static inline void __mmput(struct mm_struct *mm)
        }
        if (mm->binfmt)
                module_put(mm->binfmt->module);
+       lru_gen_del_mm(mm);
        mmdrop(mm);
 }
 
@@ -1097,20 +1384,23 @@ void mmput_async(struct mm_struct *mm)
                schedule_work(&mm->async_put_work);
        }
 }
+EXPORT_SYMBOL_GPL(mmput_async);
 #endif
 
 /**
  * set_mm_exe_file - change a reference to the mm's executable file
+ * @mm: The mm to change.
+ * @new_exe_file: The new file to use.
  *
  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
  *
  * Main users are mmput() and sys_execve(). Callers prevent concurrent
- * invocations: in mmput() nobody alive left, in execve task is single
- * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
- * mm->exe_file, but does so without using set_mm_exe_file() in order
- * to do avoid the need for any locks.
+ * invocations: in mmput() nobody alive left, in execve it happens before
+ * the new mm is made visible to anyone.
+ *
+ * Can only fail if new_exe_file != NULL.
  */
-void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
+int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
 {
        struct file *old_exe_file;
 
@@ -1121,15 +1411,79 @@ void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
         */
        old_exe_file = rcu_dereference_raw(mm->exe_file);
 
-       if (new_exe_file)
+       if (new_exe_file) {
+               /*
+                * We expect the caller (i.e., sys_execve) to already denied
+                * write access, so this is unlikely to fail.
+                */
+               if (unlikely(deny_write_access(new_exe_file)))
+                       return -EACCES;
                get_file(new_exe_file);
+       }
        rcu_assign_pointer(mm->exe_file, new_exe_file);
-       if (old_exe_file)
+       if (old_exe_file) {
+               allow_write_access(old_exe_file);
                fput(old_exe_file);
+       }
+       return 0;
+}
+
+/**
+ * replace_mm_exe_file - replace a reference to the mm's executable file
+ * @mm: The mm to change.
+ * @new_exe_file: The new file to use.
+ *
+ * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
+ *
+ * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
+ */
+int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
+{
+       struct vm_area_struct *vma;
+       struct file *old_exe_file;
+       int ret = 0;
+
+       /* Forbid mm->exe_file change if old file still mapped. */
+       old_exe_file = get_mm_exe_file(mm);
+       if (old_exe_file) {
+               VMA_ITERATOR(vmi, mm, 0);
+               mmap_read_lock(mm);
+               for_each_vma(vmi, vma) {
+                       if (!vma->vm_file)
+                               continue;
+                       if (path_equal(&vma->vm_file->f_path,
+                                      &old_exe_file->f_path)) {
+                               ret = -EBUSY;
+                               break;
+                       }
+               }
+               mmap_read_unlock(mm);
+               fput(old_exe_file);
+               if (ret)
+                       return ret;
+       }
+
+       ret = deny_write_access(new_exe_file);
+       if (ret)
+               return -EACCES;
+       get_file(new_exe_file);
+
+       /* set the new file */
+       mmap_write_lock(mm);
+       old_exe_file = rcu_dereference_raw(mm->exe_file);
+       rcu_assign_pointer(mm->exe_file, new_exe_file);
+       mmap_write_unlock(mm);
+
+       if (old_exe_file) {
+               allow_write_access(old_exe_file);
+               fput(old_exe_file);
+       }
+       return 0;
 }
 
 /**
  * get_mm_exe_file - acquire a reference to the mm's executable file
+ * @mm: The mm of interest.
  *
  * Returns %NULL if mm has no associated executable file.
  * User must release file via fput().
@@ -1139,16 +1493,14 @@ struct file *get_mm_exe_file(struct mm_struct *mm)
        struct file *exe_file;
 
        rcu_read_lock();
-       exe_file = rcu_dereference(mm->exe_file);
-       if (exe_file && !get_file_rcu(exe_file))
-               exe_file = NULL;
+       exe_file = get_file_rcu(&mm->exe_file);
        rcu_read_unlock();
        return exe_file;
 }
-EXPORT_SYMBOL(get_mm_exe_file);
 
 /**
  * get_task_exe_file - acquire a reference to the task's executable file
+ * @task: The task.
  *
  * Returns %NULL if task's mm (if any) has no associated executable file or
  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
@@ -1168,10 +1520,10 @@ struct file *get_task_exe_file(struct task_struct *task)
        task_unlock(task);
        return exe_file;
 }
-EXPORT_SYMBOL(get_task_exe_file);
 
 /**
  * get_task_mm - acquire a reference to the task's mm
+ * @task: The task.
  *
  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
  * this kernel workthread has transiently adopted a user mm with use_mm,
@@ -1201,7 +1553,7 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
        struct mm_struct *mm;
        int err;
 
-       err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
+       err =  down_read_killable(&task->signal->exec_update_lock);
        if (err)
                return ERR_PTR(err);
 
@@ -1211,7 +1563,7 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
                mmput(mm);
                mm = ERR_PTR(-EACCES);
        }
-       mutex_unlock(&task->signal->cred_guard_mutex);
+       up_read(&task->signal->exec_update_lock);
 
        return mm;
 }
@@ -1232,13 +1584,12 @@ static void complete_vfork_done(struct task_struct *tsk)
 static int wait_for_vfork_done(struct task_struct *child,
                                struct completion *vfork)
 {
+       unsigned int state = TASK_KILLABLE|TASK_FREEZABLE;
        int killed;
 
-       freezer_do_not_count();
        cgroup_enter_frozen();
-       killed = wait_for_completion_killable(vfork);
+       killed = wait_for_completion_state(vfork, state);
        cgroup_leave_frozen(false);
-       freezer_count();
 
        if (killed) {
                task_lock(child);
@@ -1263,24 +1614,8 @@ static int wait_for_vfork_done(struct task_struct *child,
  * restoring the old one. . .
  * Eric Biederman 10 January 1998
  */
-void mm_release(struct task_struct *tsk, struct mm_struct *mm)
+static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
 {
-       /* Get rid of any futexes when releasing the mm */
-#ifdef CONFIG_FUTEX
-       if (unlikely(tsk->robust_list)) {
-               exit_robust_list(tsk);
-               tsk->robust_list = NULL;
-       }
-#ifdef CONFIG_COMPAT
-       if (unlikely(tsk->compat_robust_list)) {
-               compat_exit_robust_list(tsk);
-               tsk->compat_robust_list = NULL;
-       }
-#endif
-       if (unlikely(!list_empty(&tsk->pi_state_list)))
-               exit_pi_state_list(tsk);
-#endif
-
        uprobe_free_utask(tsk);
 
        /* Get rid of any cached register state */
@@ -1292,8 +1627,7 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
         * purposes.
         */
        if (tsk->clear_child_tid) {
-               if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
-                   atomic_read(&mm->mm_users) > 1) {
+               if (atomic_read(&mm->mm_users) > 1) {
                        /*
                         * We don't check the error code - if userspace has
                         * not set up a proper pointer then tough luck.
@@ -1313,6 +1647,18 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
                complete_vfork_done(tsk);
 }
 
+void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
+{
+       futex_exit_release(tsk);
+       mm_release(tsk, mm);
+}
+
+void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
+{
+       futex_exec_release(tsk);
+       mm_release(tsk, mm);
+}
+
 /**
  * dup_mm() - duplicates an existing mm structure
  * @tsk: the task_struct with which the new mm will be associated.
@@ -1363,7 +1709,6 @@ fail_nomem:
 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
 {
        struct mm_struct *mm, *oldmm;
-       int retval;
 
        tsk->min_flt = tsk->maj_flt = 0;
        tsk->nvcsw = tsk->nivcsw = 0;
@@ -1384,27 +1729,19 @@ static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
        if (!oldmm)
                return 0;
 
-       /* initialize the new vmacache entries */
-       vmacache_flush(tsk);
-
        if (clone_flags & CLONE_VM) {
                mmget(oldmm);
                mm = oldmm;
-               goto good_mm;
+       } else {
+               mm = dup_mm(tsk, current->mm);
+               if (!mm)
+                       return -ENOMEM;
        }
 
-       retval = -ENOMEM;
-       mm = dup_mm(tsk, current->mm);
-       if (!mm)
-               goto fail_nomem;
-
-good_mm:
        tsk->mm = mm;
        tsk->active_mm = mm;
+       sched_mm_cid_fork(tsk);
        return 0;
-
-fail_nomem:
-       return retval;
 }
 
 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
@@ -1413,6 +1750,7 @@ static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
        if (clone_flags & CLONE_FS) {
                /* tsk->fs is already what we want */
                spin_lock(&fs->lock);
+               /* "users" and "in_exec" locked for check_unsafe_exec() */
                if (fs->in_exec) {
                        spin_unlock(&fs->lock);
                        return -EAGAIN;
@@ -1427,7 +1765,8 @@ static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
        return 0;
 }
 
-static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
+static int copy_files(unsigned long clone_flags, struct task_struct *tsk,
+                     int no_files)
 {
        struct files_struct *oldf, *newf;
        int error = 0;
@@ -1439,12 +1778,17 @@ static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
        if (!oldf)
                goto out;
 
+       if (no_files) {
+               tsk->files = NULL;
+               goto out;
+       }
+
        if (clone_flags & CLONE_FILES) {
                atomic_inc(&oldf->count);
                goto out;
        }
 
-       newf = dup_fd(oldf, &error);
+       newf = dup_fd(oldf, NR_OPEN_MAX, &error);
        if (!newf)
                goto out;
 
@@ -1454,32 +1798,6 @@ out:
        return error;
 }
 
-static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
-{
-#ifdef CONFIG_BLOCK
-       struct io_context *ioc = current->io_context;
-       struct io_context *new_ioc;
-
-       if (!ioc)
-               return 0;
-       /*
-        * Share io context with parent, if CLONE_IO is set
-        */
-       if (clone_flags & CLONE_IO) {
-               ioc_task_link(ioc);
-               tsk->io_context = ioc;
-       } else if (ioprio_valid(ioc->ioprio)) {
-               new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
-               if (unlikely(!new_ioc))
-                       return -ENOMEM;
-
-               new_ioc->ioprio = ioc->ioprio;
-               put_io_context(new_ioc);
-       }
-#endif
-       return 0;
-}
-
 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
 {
        struct sighand_struct *sig;
@@ -1489,7 +1807,7 @@ static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
                return 0;
        }
        sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
-       rcu_assign_pointer(tsk->sighand, sig);
+       RCU_INIT_POINTER(tsk->sighand, sig);
        if (!sig)
                return -ENOMEM;
 
@@ -1497,6 +1815,11 @@ static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
        spin_lock_irq(&current->sighand->siglock);
        memcpy(sig->action, current->sighand->action, sizeof(sig->action));
        spin_unlock_irq(&current->sighand->siglock);
+
+       /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
+       if (clone_flags & CLONE_CLEAR_SIGHAND)
+               flush_signal_handlers(tsk, 0);
+
        return 0;
 }
 
@@ -1512,28 +1835,17 @@ void __cleanup_sighand(struct sighand_struct *sighand)
        }
 }
 
-#ifdef CONFIG_POSIX_TIMERS
 /*
  * Initialize POSIX timer handling for a thread group.
  */
 static void posix_cpu_timers_init_group(struct signal_struct *sig)
 {
+       struct posix_cputimers *pct = &sig->posix_cputimers;
        unsigned long cpu_limit;
 
        cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
-       if (cpu_limit != RLIM_INFINITY) {
-               sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
-               sig->cputimer.running = true;
-       }
-
-       /* The timer lists. */
-       INIT_LIST_HEAD(&sig->cpu_timers[0]);
-       INIT_LIST_HEAD(&sig->cpu_timers[1]);
-       INIT_LIST_HEAD(&sig->cpu_timers[2]);
+       posix_cputimers_group_init(pct, cpu_limit);
 }
-#else
-static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
-#endif
 
 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
 {
@@ -1548,6 +1860,7 @@ static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
                return -ENOMEM;
 
        sig->nr_threads = 1;
+       sig->quick_threads = 1;
        atomic_set(&sig->live, 1);
        refcount_set(&sig->sigcnt, 1);
 
@@ -1581,6 +1894,7 @@ static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
        sig->oom_score_adj_min = current->signal->oom_score_adj_min;
 
        mutex_init(&sig->cred_guard_mutex);
+       init_rwsem(&sig->exec_update_lock);
 
        return 0;
 }
@@ -1614,7 +1928,7 @@ static void copy_seccomp(struct task_struct *p)
         * to manually enable the seccomp thread flag here.
         */
        if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
-               set_tsk_thread_flag(p, TIF_SECCOMP);
+               set_task_syscall_work(p, SECCOMP);
 #endif
 }
 
@@ -1635,30 +1949,12 @@ static void rt_mutex_init_task(struct task_struct *p)
 #endif
 }
 
-#ifdef CONFIG_POSIX_TIMERS
-/*
- * Initialize POSIX timer handling for a single task.
- */
-static void posix_cpu_timers_init(struct task_struct *tsk)
-{
-       tsk->cputime_expires.prof_exp = 0;
-       tsk->cputime_expires.virt_exp = 0;
-       tsk->cputime_expires.sched_exp = 0;
-       INIT_LIST_HEAD(&tsk->cpu_timers[0]);
-       INIT_LIST_HEAD(&tsk->cpu_timers[1]);
-       INIT_LIST_HEAD(&tsk->cpu_timers[2]);
-}
-#else
-static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
-#endif
-
 static inline void init_task_pid_links(struct task_struct *task)
 {
        enum pid_type type;
 
-       for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
+       for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
                INIT_HLIST_NODE(&task->pid_links[type]);
-       }
 }
 
 static inline void
@@ -1682,59 +1978,102 @@ static inline void rcu_copy_process(struct task_struct *p)
        p->rcu_tasks_holdout = false;
        INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
        p->rcu_tasks_idle_cpu = -1;
+       INIT_LIST_HEAD(&p->rcu_tasks_exit_list);
 #endif /* #ifdef CONFIG_TASKS_RCU */
+#ifdef CONFIG_TASKS_TRACE_RCU
+       p->trc_reader_nesting = 0;
+       p->trc_reader_special.s = 0;
+       INIT_LIST_HEAD(&p->trc_holdout_list);
+       INIT_LIST_HEAD(&p->trc_blkd_node);
+#endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
 }
 
-static int pidfd_release(struct inode *inode, struct file *file)
+/**
+ * __pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
+ * @pid:   the struct pid for which to create a pidfd
+ * @flags: flags of the new @pidfd
+ * @ret: Where to return the file for the pidfd.
+ *
+ * Allocate a new file that stashes @pid and reserve a new pidfd number in the
+ * caller's file descriptor table. The pidfd is reserved but not installed yet.
+ *
+ * The helper doesn't perform checks on @pid which makes it useful for pidfds
+ * created via CLONE_PIDFD where @pid has no task attached when the pidfd and
+ * pidfd file are prepared.
+ *
+ * If this function returns successfully the caller is responsible to either
+ * call fd_install() passing the returned pidfd and pidfd file as arguments in
+ * order to install the pidfd into its file descriptor table or they must use
+ * put_unused_fd() and fput() on the returned pidfd and pidfd file
+ * respectively.
+ *
+ * This function is useful when a pidfd must already be reserved but there
+ * might still be points of failure afterwards and the caller wants to ensure
+ * that no pidfd is leaked into its file descriptor table.
+ *
+ * Return: On success, a reserved pidfd is returned from the function and a new
+ *         pidfd file is returned in the last argument to the function. On
+ *         error, a negative error code is returned from the function and the
+ *         last argument remains unchanged.
+ */
+static int __pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
 {
-       struct pid *pid = file->private_data;
-
-       file->private_data = NULL;
-       put_pid(pid);
-       return 0;
-}
+       int pidfd;
+       struct file *pidfd_file;
 
-#ifdef CONFIG_PROC_FS
-static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
-{
-       struct pid_namespace *ns = proc_pid_ns(file_inode(m->file));
-       struct pid *pid = f->private_data;
+       pidfd = get_unused_fd_flags(O_CLOEXEC);
+       if (pidfd < 0)
+               return pidfd;
 
-       seq_put_decimal_ull(m, "Pid:\t", pid_nr_ns(pid, ns));
-       seq_putc(m, '\n');
+       pidfd_file = pidfs_alloc_file(pid, flags | O_RDWR);
+       if (IS_ERR(pidfd_file)) {
+               put_unused_fd(pidfd);
+               return PTR_ERR(pidfd_file);
+       }
+       /*
+        * anon_inode_getfile() ignores everything outside of the
+        * O_ACCMODE | O_NONBLOCK mask, set PIDFD_THREAD manually.
+        */
+       pidfd_file->f_flags |= (flags & PIDFD_THREAD);
+       *ret = pidfd_file;
+       return pidfd;
 }
-#endif
-
-const struct file_operations pidfd_fops = {
-       .release = pidfd_release,
-#ifdef CONFIG_PROC_FS
-       .show_fdinfo = pidfd_show_fdinfo,
-#endif
-};
 
 /**
- * pidfd_create() - Create a new pid file descriptor.
+ * pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
+ * @pid:   the struct pid for which to create a pidfd
+ * @flags: flags of the new @pidfd
+ * @ret: Where to return the pidfd.
+ *
+ * Allocate a new file that stashes @pid and reserve a new pidfd number in the
+ * caller's file descriptor table. The pidfd is reserved but not installed yet.
  *
- * @pid:  struct pid that the pidfd will reference
+ * The helper verifies that @pid is still in use, without PIDFD_THREAD the
+ * task identified by @pid must be a thread-group leader.
  *
- * This creates a new pid file descriptor with the O_CLOEXEC flag set.
+ * If this function returns successfully the caller is responsible to either
+ * call fd_install() passing the returned pidfd and pidfd file as arguments in
+ * order to install the pidfd into its file descriptor table or they must use
+ * put_unused_fd() and fput() on the returned pidfd and pidfd file
+ * respectively.
  *
- * Note, that this function can only be called after the fd table has
- * been unshared to avoid leaking the pidfd to the new process.
+ * This function is useful when a pidfd must already be reserved but there
+ * might still be points of failure afterwards and the caller wants to ensure
+ * that no pidfd is leaked into its file descriptor table.
  *
- * Return: On success, a cloexec pidfd is returned.
- *         On error, a negative errno number will be returned.
+ * Return: On success, a reserved pidfd is returned from the function and a new
+ *         pidfd file is returned in the last argument to the function. On
+ *         error, a negative error code is returned from the function and the
+ *         last argument remains unchanged.
  */
-static int pidfd_create(struct pid *pid)
+int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
 {
-       int fd;
+       bool thread = flags & PIDFD_THREAD;
 
-       fd = anon_inode_getfd("[pidfd]", &pidfd_fops, get_pid(pid),
-                             O_RDWR | O_CLOEXEC);
-       if (fd < 0)
-               put_pid(pid);
+       if (!pid || !pid_has_task(pid, thread ? PIDTYPE_PID : PIDTYPE_TGID))
+               return -EINVAL;
 
-       return fd;
+       return __pidfd_prepare(pid, flags, ret);
 }
 
 static void __delayed_free_task(struct rcu_head *rhp)
@@ -1752,6 +2091,37 @@ static __always_inline void delayed_free_task(struct task_struct *tsk)
                free_task(tsk);
 }
 
+static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
+{
+       /* Skip if kernel thread */
+       if (!tsk->mm)
+               return;
+
+       /* Skip if spawning a thread or using vfork */
+       if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
+               return;
+
+       /* We need to synchronize with __set_oom_adj */
+       mutex_lock(&oom_adj_mutex);
+       set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
+       /* Update the values in case they were changed after copy_signal */
+       tsk->signal->oom_score_adj = current->signal->oom_score_adj;
+       tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
+       mutex_unlock(&oom_adj_mutex);
+}
+
+#ifdef CONFIG_RV
+static void rv_task_fork(struct task_struct *p)
+{
+       int i;
+
+       for (i = 0; i < RV_PER_TASK_MONITORS; i++)
+               p->rv[i].da_mon.monitoring = false;
+}
+#else
+#define rv_task_fork(p) do {} while (0)
+#endif
+
 /*
  * This creates a new process as a copy of the old one,
  * but does not actually start it yet.
@@ -1760,20 +2130,18 @@ static __always_inline void delayed_free_task(struct task_struct *tsk)
  * parts of the process environment (as per the clone
  * flags). The actual kick-off is left to the caller.
  */
-static __latent_entropy struct task_struct *copy_process(
-                                       unsigned long clone_flags,
-                                       unsigned long stack_start,
-                                       unsigned long stack_size,
-                                       int __user *parent_tidptr,
-                                       int __user *child_tidptr,
+__latent_entropy struct task_struct *copy_process(
                                        struct pid *pid,
                                        int trace,
-                                       unsigned long tls,
-                                       int node)
+                                       int node,
+                                       struct kernel_clone_args *args)
 {
        int pidfd = -1, retval;
        struct task_struct *p;
        struct multiprocess_signals delayed;
+       struct file *pidfile = NULL;
+       const u64 clone_flags = args->flags;
+       struct nsproxy *nsp = current->nsproxy;
 
        /*
         * Don't allow sharing the root directory with processes in a different
@@ -1816,33 +2184,16 @@ static __latent_entropy struct task_struct *copy_process(
         */
        if (clone_flags & CLONE_THREAD) {
                if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
-                   (task_active_pid_ns(current) !=
-                               current->nsproxy->pid_ns_for_children))
+                   (task_active_pid_ns(current) != nsp->pid_ns_for_children))
                        return ERR_PTR(-EINVAL);
        }
 
        if (clone_flags & CLONE_PIDFD) {
-               int reserved;
-
                /*
-                * - CLONE_PARENT_SETTID is useless for pidfds and also
-                *   parent_tidptr is used to return pidfds.
                 * - CLONE_DETACHED is blocked so that we can potentially
                 *   reuse it later for CLONE_PIDFD.
-                * - CLONE_THREAD is blocked until someone really needs it.
-                */
-               if (clone_flags &
-                   (CLONE_DETACHED | CLONE_PARENT_SETTID | CLONE_THREAD))
-                       return ERR_PTR(-EINVAL);
-
-               /*
-                * Verify that parent_tidptr is sane so we can potentially
-                * reuse it later.
                 */
-               if (get_user(reserved, parent_tidptr))
-                       return ERR_PTR(-EFAULT);
-
-               if (reserved != 0)
+               if (clone_flags & CLONE_DETACHED)
                        return ERR_PTR(-EINVAL);
        }
 
@@ -1861,58 +2212,67 @@ static __latent_entropy struct task_struct *copy_process(
        recalc_sigpending();
        spin_unlock_irq(&current->sighand->siglock);
        retval = -ERESTARTNOINTR;
-       if (signal_pending(current))
+       if (task_sigpending(current))
                goto fork_out;
 
        retval = -ENOMEM;
        p = dup_task_struct(current, node);
        if (!p)
                goto fork_out;
+       p->flags &= ~PF_KTHREAD;
+       if (args->kthread)
+               p->flags |= PF_KTHREAD;
+       if (args->user_worker) {
+               /*
+                * Mark us a user worker, and block any signal that isn't
+                * fatal or STOP
+                */
+               p->flags |= PF_USER_WORKER;
+               siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
+       }
+       if (args->io_thread)
+               p->flags |= PF_IO_WORKER;
 
-       /*
-        * This _must_ happen before we call free_task(), i.e. before we jump
-        * to any of the bad_fork_* labels. This is to avoid freeing
-        * p->set_child_tid which is (ab)used as a kthread's data pointer for
-        * kernel threads (PF_KTHREAD).
-        */
-       p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
+       if (args->name)
+               strscpy_pad(p->comm, args->name, sizeof(p->comm));
+
+       p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
        /*
         * Clear TID on mm_release()?
         */
-       p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
+       p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
 
        ftrace_graph_init_task(p);
 
        rt_mutex_init_task(p);
 
+       lockdep_assert_irqs_enabled();
 #ifdef CONFIG_PROVE_LOCKING
-       DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
        DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
 #endif
+       retval = copy_creds(p, clone_flags);
+       if (retval < 0)
+               goto bad_fork_free;
+
        retval = -EAGAIN;
-       if (atomic_read(&p->real_cred->user->processes) >=
-                       task_rlimit(p, RLIMIT_NPROC)) {
+       if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
                if (p->real_cred->user != INIT_USER &&
                    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
-                       goto bad_fork_free;
+                       goto bad_fork_cleanup_count;
        }
        current->flags &= ~PF_NPROC_EXCEEDED;
 
-       retval = copy_creds(p, clone_flags);
-       if (retval < 0)
-               goto bad_fork_free;
-
        /*
         * If multiple threads are within copy_process(), then this check
         * triggers too late. This doesn't hurt, the check is only there
         * to stop root fork bombs.
         */
        retval = -EAGAIN;
-       if (nr_threads >= max_threads)
+       if (data_race(nr_threads >= max_threads))
                goto bad_fork_cleanup_count;
 
        delayacct_tsk_init(p);  /* Must remain after dup_task_struct() */
-       p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
+       p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
        p->flags |= PF_FORKNOEXEC;
        INIT_LIST_HEAD(&p->children);
        INIT_LIST_HEAD(&p->sibling);
@@ -1934,8 +2294,8 @@ static __latent_entropy struct task_struct *copy_process(
        p->vtime.state = VTIME_INACTIVE;
 #endif
 
-#if defined(SPLIT_RSS_COUNTING)
-       memset(&p->rss_stat, 0, sizeof(p->rss_stat));
+#ifdef CONFIG_IO_URING
+       p->io_uring = NULL;
 #endif
 
        p->default_timer_slack_ns = current->timer_slack_ns;
@@ -1947,46 +2307,39 @@ static __latent_entropy struct task_struct *copy_process(
        task_io_accounting_init(&p->ioac);
        acct_clear_integrals(p);
 
-       posix_cpu_timers_init(p);
+       posix_cputimers_init(&p->posix_cputimers);
 
        p->io_context = NULL;
        audit_set_context(p, NULL);
        cgroup_fork(p);
+       if (args->kthread) {
+               if (!set_kthread_struct(p))
+                       goto bad_fork_cleanup_delayacct;
+       }
 #ifdef CONFIG_NUMA
        p->mempolicy = mpol_dup(p->mempolicy);
        if (IS_ERR(p->mempolicy)) {
                retval = PTR_ERR(p->mempolicy);
                p->mempolicy = NULL;
-               goto bad_fork_cleanup_threadgroup_lock;
+               goto bad_fork_cleanup_delayacct;
        }
 #endif
 #ifdef CONFIG_CPUSETS
        p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
        p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
-       seqcount_init(&p->mems_allowed_seq);
+       seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
 #endif
 #ifdef CONFIG_TRACE_IRQFLAGS
-       p->irq_events = 0;
-       p->hardirqs_enabled = 0;
-       p->hardirq_enable_ip = 0;
-       p->hardirq_enable_event = 0;
-       p->hardirq_disable_ip = _THIS_IP_;
-       p->hardirq_disable_event = 0;
-       p->softirqs_enabled = 1;
-       p->softirq_enable_ip = _THIS_IP_;
-       p->softirq_enable_event = 0;
-       p->softirq_disable_ip = 0;
-       p->softirq_disable_event = 0;
-       p->hardirq_context = 0;
-       p->softirq_context = 0;
+       memset(&p->irqtrace, 0, sizeof(p->irqtrace));
+       p->irqtrace.hardirq_disable_ip  = _THIS_IP_;
+       p->irqtrace.softirq_enable_ip   = _THIS_IP_;
+       p->softirqs_enabled             = 1;
+       p->softirq_context              = 0;
 #endif
 
        p->pagefault_disabled = 0;
 
 #ifdef CONFIG_LOCKDEP
-       p->lockdep_depth = 0; /* no locks held yet */
-       p->curr_chain_key = 0;
-       p->lockdep_recursion = 0;
        lockdep_init_task(p);
 #endif
 
@@ -1997,13 +2350,17 @@ static __latent_entropy struct task_struct *copy_process(
        p->sequential_io        = 0;
        p->sequential_io_avg    = 0;
 #endif
+#ifdef CONFIG_BPF_SYSCALL
+       RCU_INIT_POINTER(p->bpf_storage, NULL);
+       p->bpf_ctx = NULL;
+#endif
 
        /* Perform scheduler related setup. Assign this task to a CPU. */
        retval = sched_fork(clone_flags, p);
        if (retval)
                goto bad_fork_cleanup_policy;
 
-       retval = perf_event_init_task(p);
+       retval = perf_event_init_task(p, clone_flags);
        if (retval)
                goto bad_fork_cleanup_policy;
        retval = audit_alloc(p);
@@ -2017,7 +2374,7 @@ static __latent_entropy struct task_struct *copy_process(
        retval = copy_semundo(clone_flags, p);
        if (retval)
                goto bad_fork_cleanup_security;
-       retval = copy_files(clone_flags, p);
+       retval = copy_files(clone_flags, p, args->no_files);
        if (retval)
                goto bad_fork_cleanup_semundo;
        retval = copy_fs(clone_flags, p);
@@ -2038,14 +2395,15 @@ static __latent_entropy struct task_struct *copy_process(
        retval = copy_io(clone_flags, p);
        if (retval)
                goto bad_fork_cleanup_namespaces;
-       retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
+       retval = copy_thread(p, args);
        if (retval)
                goto bad_fork_cleanup_io;
 
        stackleak_task_init(p);
 
        if (pid != &init_struct_pid) {
-               pid = alloc_pid(p->nsproxy->pid_ns_for_children);
+               pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
+                               args->set_tid_size);
                if (IS_ERR(pid)) {
                        retval = PTR_ERR(pid);
                        goto bad_fork_cleanup_thread;
@@ -2058,12 +2416,15 @@ static __latent_entropy struct task_struct *copy_process(
         * if the fd table isn't shared).
         */
        if (clone_flags & CLONE_PIDFD) {
-               retval = pidfd_create(pid);
+               int flags = (clone_flags & CLONE_THREAD) ? PIDFD_THREAD : 0;
+
+               /* Note that no task has been attached to @pid yet. */
+               retval = __pidfd_prepare(pid, flags, &pidfile);
                if (retval < 0)
                        goto bad_fork_free_pid;
-
                pidfd = retval;
-               retval = put_user(pidfd, parent_tidptr);
+
+               retval = put_user(pidfd, args->pidfd);
                if (retval)
                        goto bad_fork_put_pidfd;
        }
@@ -2071,14 +2432,8 @@ static __latent_entropy struct task_struct *copy_process(
 #ifdef CONFIG_BLOCK
        p->plug = NULL;
 #endif
-#ifdef CONFIG_FUTEX
-       p->robust_list = NULL;
-#ifdef CONFIG_COMPAT
-       p->compat_robust_list = NULL;
-#endif
-       INIT_LIST_HEAD(&p->pi_state_list);
-       p->pi_state_cache = NULL;
-#endif
+       futex_init_task(p);
+
        /*
         * sigaltstack should be cleared when sharing the same VM
         */
@@ -2090,23 +2445,18 @@ static __latent_entropy struct task_struct *copy_process(
         * child regardless of CLONE_PTRACE.
         */
        user_disable_single_step(p);
-       clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
-#ifdef TIF_SYSCALL_EMU
-       clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
+       clear_task_syscall_work(p, SYSCALL_TRACE);
+#if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
+       clear_task_syscall_work(p, SYSCALL_EMU);
 #endif
        clear_tsk_latency_tracing(p);
 
        /* ok, now we should be set up.. */
        p->pid = pid_nr(pid);
        if (clone_flags & CLONE_THREAD) {
-               p->exit_signal = -1;
                p->group_leader = current->group_leader;
                p->tgid = current->tgid;
        } else {
-               if (clone_flags & CLONE_PARENT)
-                       p->exit_signal = current->group_leader->exit_signal;
-               else
-                       p->exit_signal = (clone_flags & CSIGNAL);
                p->group_leader = p;
                p->tgid = p->pid;
        }
@@ -2116,19 +2466,36 @@ static __latent_entropy struct task_struct *copy_process(
        p->dirty_paused_when = 0;
 
        p->pdeath_signal = 0;
-       INIT_LIST_HEAD(&p->thread_group);
        p->task_works = NULL;
+       clear_posix_cputimers_work(p);
+
+#ifdef CONFIG_KRETPROBES
+       p->kretprobe_instances.first = NULL;
+#endif
+#ifdef CONFIG_RETHOOK
+       p->rethooks.first = NULL;
+#endif
 
-       cgroup_threadgroup_change_begin(current);
        /*
         * Ensure that the cgroup subsystem policies allow the new process to be
-        * forked. It should be noted the the new process's css_set can be changed
+        * forked. It should be noted that the new process's css_set can be changed
         * between here and cgroup_post_fork() if an organisation operation is in
         * progress.
         */
-       retval = cgroup_can_fork(p);
+       retval = cgroup_can_fork(p, args);
        if (retval)
-               goto bad_fork_cgroup_threadgroup_change_end;
+               goto bad_fork_put_pidfd;
+
+       /*
+        * Now that the cgroups are pinned, re-clone the parent cgroup and put
+        * the new task on the correct runqueue. All this *before* the task
+        * becomes visible.
+        *
+        * This isn't part of ->can_fork() because while the re-cloning is
+        * cgroup specific, it unconditionally needs to place the task on a
+        * runqueue.
+        */
+       sched_cgroup_fork(p, args);
 
        /*
         * From this point on we must avoid any synchronous user-space
@@ -2139,7 +2506,7 @@ static __latent_entropy struct task_struct *copy_process(
         */
 
        p->start_time = ktime_get_ns();
-       p->real_start_time = ktime_get_boot_ns();
+       p->start_boottime = ktime_get_boottime_ns();
 
        /*
         * Make it visible to the rest of the system, but dont wake it up yet.
@@ -2151,20 +2518,23 @@ static __latent_entropy struct task_struct *copy_process(
        if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
                p->real_parent = current->real_parent;
                p->parent_exec_id = current->parent_exec_id;
+               if (clone_flags & CLONE_THREAD)
+                       p->exit_signal = -1;
+               else
+                       p->exit_signal = current->group_leader->exit_signal;
        } else {
                p->real_parent = current;
                p->parent_exec_id = current->self_exec_id;
+               p->exit_signal = args->exit_signal;
        }
 
        klp_copy_process(p);
 
+       sched_core_fork(p);
+
        spin_lock(&current->sighand->siglock);
 
-       /*
-        * Copy seccomp details explicitly here, in case they were changed
-        * before holding sighand lock.
-        */
-       copy_seccomp(p);
+       rv_task_fork(p);
 
        rseq_fork(p, clone_flags);
 
@@ -2180,6 +2550,13 @@ static __latent_entropy struct task_struct *copy_process(
                goto bad_fork_cancel_cgroup;
        }
 
+       /* No more failure paths after this point. */
+
+       /*
+        * Copy seccomp details explicitly here, in case they were changed
+        * before holding sighand lock.
+        */
+       copy_seccomp(p);
 
        init_task_pid_links(p);
        if (likely(p->pid)) {
@@ -2212,11 +2589,10 @@ static __latent_entropy struct task_struct *copy_process(
                        __this_cpu_inc(process_counts);
                } else {
                        current->signal->nr_threads++;
+                       current->signal->quick_threads++;
                        atomic_inc(&current->signal->live);
                        refcount_inc(&current->signal->sigcnt);
                        task_join_group_stop(p);
-                       list_add_tail_rcu(&p->thread_group,
-                                         &p->group_leader->thread_group);
                        list_add_tail_rcu(&p->thread_node,
                                          &p->signal->thread_head);
                }
@@ -2229,25 +2605,32 @@ static __latent_entropy struct task_struct *copy_process(
        syscall_tracepoint_update(p);
        write_unlock_irq(&tasklist_lock);
 
+       if (pidfile)
+               fd_install(pidfd, pidfile);
+
        proc_fork_connector(p);
-       cgroup_post_fork(p);
-       cgroup_threadgroup_change_end(current);
+       sched_post_fork(p);
+       cgroup_post_fork(p, args);
        perf_event_fork(p);
 
        trace_task_newtask(p, clone_flags);
        uprobe_copy_process(p, clone_flags);
+       user_events_fork(p, clone_flags);
+
+       copy_oom_score_adj(clone_flags, p);
 
        return p;
 
 bad_fork_cancel_cgroup:
+       sched_core_free(p);
        spin_unlock(&current->sighand->siglock);
        write_unlock_irq(&tasklist_lock);
-       cgroup_cancel_fork(p);
-bad_fork_cgroup_threadgroup_change_end:
-       cgroup_threadgroup_change_end(current);
+       cgroup_cancel_fork(p, args);
 bad_fork_put_pidfd:
-       if (clone_flags & CLONE_PIDFD)
-               ksys_close(pidfd);
+       if (clone_flags & CLONE_PIDFD) {
+               fput(pidfile);
+               put_unused_fd(pidfd);
+       }
 bad_fork_free_pid:
        if (pid != &init_struct_pid)
                free_pid(pid);
@@ -2284,14 +2667,15 @@ bad_fork_cleanup_policy:
        lockdep_free_task(p);
 #ifdef CONFIG_NUMA
        mpol_put(p->mempolicy);
-bad_fork_cleanup_threadgroup_lock:
 #endif
+bad_fork_cleanup_delayacct:
        delayacct_tsk_free(p);
 bad_fork_cleanup_count:
-       atomic_dec(&p->cred->user->processes);
+       dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
        exit_creds(p);
 bad_fork_free:
-       p->state = TASK_DEAD;
+       WRITE_ONCE(p->__state, TASK_DEAD);
+       exit_task_stack_account(p);
        put_task_stack(p);
        delayed_free_task(p);
 fork_out:
@@ -2311,11 +2695,24 @@ static inline void init_idle_pids(struct task_struct *idle)
        }
 }
 
-struct task_struct *fork_idle(int cpu)
+static int idle_dummy(void *dummy)
+{
+       /* This function is never called */
+       return 0;
+}
+
+struct task_struct * __init fork_idle(int cpu)
 {
        struct task_struct *task;
-       task = copy_process(CLONE_VM, 0, 0, NULL, NULL, &init_struct_pid, 0, 0,
-                           cpu_to_node(cpu));
+       struct kernel_clone_args args = {
+               .flags          = CLONE_VM,
+               .fn             = &idle_dummy,
+               .fn_arg         = NULL,
+               .kthread        = 1,
+               .idle           = 1,
+       };
+
+       task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
        if (!IS_ERR(task)) {
                init_idle_pids(task);
                init_idle(task, cpu);
@@ -2324,9 +2721,27 @@ struct task_struct *fork_idle(int cpu)
        return task;
 }
 
-struct mm_struct *copy_init_mm(void)
+/*
+ * This is like kernel_clone(), but shaved down and tailored to just
+ * creating io_uring workers. It returns a created task, or an error pointer.
+ * The returned task is inactive, and the caller must fire it up through
+ * wake_up_new_task(p). All signals are blocked in the created task.
+ */
+struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
 {
-       return dup_mm(NULL, &init_mm);
+       unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
+                               CLONE_IO;
+       struct kernel_clone_args args = {
+               .flags          = ((lower_32_bits(flags) | CLONE_VM |
+                                   CLONE_UNTRACED) & ~CSIGNAL),
+               .exit_signal    = (lower_32_bits(flags) & CSIGNAL),
+               .fn             = fn,
+               .fn_arg         = arg,
+               .io_thread      = 1,
+               .user_worker    = 1,
+       };
+
+       return copy_process(NULL, 0, node, &args);
 }
 
 /*
@@ -2334,19 +2749,31 @@ struct mm_struct *copy_init_mm(void)
  *
  * It copies the process, and if successful kick-starts
  * it and waits for it to finish using the VM if required.
+ *
+ * args->exit_signal is expected to be checked for sanity by the caller.
  */
-long _do_fork(unsigned long clone_flags,
-             unsigned long stack_start,
-             unsigned long stack_size,
-             int __user *parent_tidptr,
-             int __user *child_tidptr,
-             unsigned long tls)
+pid_t kernel_clone(struct kernel_clone_args *args)
 {
+       u64 clone_flags = args->flags;
        struct completion vfork;
        struct pid *pid;
        struct task_struct *p;
        int trace = 0;
-       long nr;
+       pid_t nr;
+
+       /*
+        * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
+        * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
+        * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
+        * field in struct clone_args and it still doesn't make sense to have
+        * them both point at the same memory location. Performing this check
+        * here has the advantage that we don't need to have a separate helper
+        * to check for legacy clone().
+        */
+       if ((clone_flags & CLONE_PIDFD) &&
+           (clone_flags & CLONE_PARENT_SETTID) &&
+           (args->pidfd == args->parent_tid))
+               return -EINVAL;
 
        /*
         * Determine whether and which event to report to ptracer.  When
@@ -2357,7 +2784,7 @@ long _do_fork(unsigned long clone_flags,
        if (!(clone_flags & CLONE_UNTRACED)) {
                if (clone_flags & CLONE_VFORK)
                        trace = PTRACE_EVENT_VFORK;
-               else if ((clone_flags & CSIGNAL) != SIGCHLD)
+               else if (args->exit_signal != SIGCHLD)
                        trace = PTRACE_EVENT_CLONE;
                else
                        trace = PTRACE_EVENT_FORK;
@@ -2366,8 +2793,7 @@ long _do_fork(unsigned long clone_flags,
                        trace = 0;
        }
 
-       p = copy_process(clone_flags, stack_start, stack_size, parent_tidptr,
-                        child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
+       p = copy_process(NULL, trace, NUMA_NO_NODE, args);
        add_latent_entropy();
 
        if (IS_ERR(p))
@@ -2383,7 +2809,7 @@ long _do_fork(unsigned long clone_flags,
        nr = pid_vnr(pid);
 
        if (clone_flags & CLONE_PARENT_SETTID)
-               put_user(nr, parent_tidptr);
+               put_user(nr, args->parent_tid);
 
        if (clone_flags & CLONE_VFORK) {
                p->vfork_done = &vfork;
@@ -2391,6 +2817,13 @@ long _do_fork(unsigned long clone_flags,
                get_task_struct(p);
        }
 
+       if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) {
+               /* lock the task to synchronize with memcg migration */
+               task_lock(p);
+               lru_gen_add_mm(p->mm);
+               task_unlock(p);
+       }
+
        wake_up_new_task(p);
 
        /* forking complete and child started to run, tell ptracer */
@@ -2406,34 +2839,50 @@ long _do_fork(unsigned long clone_flags,
        return nr;
 }
 
-#ifndef CONFIG_HAVE_COPY_THREAD_TLS
-/* For compatibility with architectures that call do_fork directly rather than
- * using the syscall entry points below. */
-long do_fork(unsigned long clone_flags,
-             unsigned long stack_start,
-             unsigned long stack_size,
-             int __user *parent_tidptr,
-             int __user *child_tidptr)
+/*
+ * Create a kernel thread.
+ */
+pid_t kernel_thread(int (*fn)(void *), void *arg, const char *name,
+                   unsigned long flags)
 {
-       return _do_fork(clone_flags, stack_start, stack_size,
-                       parent_tidptr, child_tidptr, 0);
+       struct kernel_clone_args args = {
+               .flags          = ((lower_32_bits(flags) | CLONE_VM |
+                                   CLONE_UNTRACED) & ~CSIGNAL),
+               .exit_signal    = (lower_32_bits(flags) & CSIGNAL),
+               .fn             = fn,
+               .fn_arg         = arg,
+               .name           = name,
+               .kthread        = 1,
+       };
+
+       return kernel_clone(&args);
 }
-#endif
 
 /*
- * Create a kernel thread.
+ * Create a user mode thread.
  */
-pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
+pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags)
 {
-       return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
-               (unsigned long)arg, NULL, NULL, 0);
+       struct kernel_clone_args args = {
+               .flags          = ((lower_32_bits(flags) | CLONE_VM |
+                                   CLONE_UNTRACED) & ~CSIGNAL),
+               .exit_signal    = (lower_32_bits(flags) & CSIGNAL),
+               .fn             = fn,
+               .fn_arg         = arg,
+       };
+
+       return kernel_clone(&args);
 }
 
 #ifdef __ARCH_WANT_SYS_FORK
 SYSCALL_DEFINE0(fork)
 {
 #ifdef CONFIG_MMU
-       return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
+       struct kernel_clone_args args = {
+               .exit_signal = SIGCHLD,
+       };
+
+       return kernel_clone(&args);
 #else
        /* can not support in nommu mode */
        return -EINVAL;
@@ -2444,8 +2893,12 @@ SYSCALL_DEFINE0(fork)
 #ifdef __ARCH_WANT_SYS_VFORK
 SYSCALL_DEFINE0(vfork)
 {
-       return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
-                       0, NULL, NULL, 0);
+       struct kernel_clone_args args = {
+               .flags          = CLONE_VFORK | CLONE_VM,
+               .exit_signal    = SIGCHLD,
+       };
+
+       return kernel_clone(&args);
 }
 #endif
 
@@ -2473,7 +2926,175 @@ SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
                 unsigned long, tls)
 #endif
 {
-       return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
+       struct kernel_clone_args args = {
+               .flags          = (lower_32_bits(clone_flags) & ~CSIGNAL),
+               .pidfd          = parent_tidptr,
+               .child_tid      = child_tidptr,
+               .parent_tid     = parent_tidptr,
+               .exit_signal    = (lower_32_bits(clone_flags) & CSIGNAL),
+               .stack          = newsp,
+               .tls            = tls,
+       };
+
+       return kernel_clone(&args);
+}
+#endif
+
+#ifdef __ARCH_WANT_SYS_CLONE3
+
+noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
+                                             struct clone_args __user *uargs,
+                                             size_t usize)
+{
+       int err;
+       struct clone_args args;
+       pid_t *kset_tid = kargs->set_tid;
+
+       BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
+                    CLONE_ARGS_SIZE_VER0);
+       BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
+                    CLONE_ARGS_SIZE_VER1);
+       BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
+                    CLONE_ARGS_SIZE_VER2);
+       BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
+
+       if (unlikely(usize > PAGE_SIZE))
+               return -E2BIG;
+       if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
+               return -EINVAL;
+
+       err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
+       if (err)
+               return err;
+
+       if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
+               return -EINVAL;
+
+       if (unlikely(!args.set_tid && args.set_tid_size > 0))
+               return -EINVAL;
+
+       if (unlikely(args.set_tid && args.set_tid_size == 0))
+               return -EINVAL;
+
+       /*
+        * Verify that higher 32bits of exit_signal are unset and that
+        * it is a valid signal
+        */
+       if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
+                    !valid_signal(args.exit_signal)))
+               return -EINVAL;
+
+       if ((args.flags & CLONE_INTO_CGROUP) &&
+           (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
+               return -EINVAL;
+
+       *kargs = (struct kernel_clone_args){
+               .flags          = args.flags,
+               .pidfd          = u64_to_user_ptr(args.pidfd),
+               .child_tid      = u64_to_user_ptr(args.child_tid),
+               .parent_tid     = u64_to_user_ptr(args.parent_tid),
+               .exit_signal    = args.exit_signal,
+               .stack          = args.stack,
+               .stack_size     = args.stack_size,
+               .tls            = args.tls,
+               .set_tid_size   = args.set_tid_size,
+               .cgroup         = args.cgroup,
+       };
+
+       if (args.set_tid &&
+               copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
+                       (kargs->set_tid_size * sizeof(pid_t))))
+               return -EFAULT;
+
+       kargs->set_tid = kset_tid;
+
+       return 0;
+}
+
+/**
+ * clone3_stack_valid - check and prepare stack
+ * @kargs: kernel clone args
+ *
+ * Verify that the stack arguments userspace gave us are sane.
+ * In addition, set the stack direction for userspace since it's easy for us to
+ * determine.
+ */
+static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
+{
+       if (kargs->stack == 0) {
+               if (kargs->stack_size > 0)
+                       return false;
+       } else {
+               if (kargs->stack_size == 0)
+                       return false;
+
+               if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
+                       return false;
+
+#if !defined(CONFIG_STACK_GROWSUP)
+               kargs->stack += kargs->stack_size;
+#endif
+       }
+
+       return true;
+}
+
+static bool clone3_args_valid(struct kernel_clone_args *kargs)
+{
+       /* Verify that no unknown flags are passed along. */
+       if (kargs->flags &
+           ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
+               return false;
+
+       /*
+        * - make the CLONE_DETACHED bit reusable for clone3
+        * - make the CSIGNAL bits reusable for clone3
+        */
+       if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
+               return false;
+
+       if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
+           (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
+               return false;
+
+       if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
+           kargs->exit_signal)
+               return false;
+
+       if (!clone3_stack_valid(kargs))
+               return false;
+
+       return true;
+}
+
+/**
+ * sys_clone3 - create a new process with specific properties
+ * @uargs: argument structure
+ * @size:  size of @uargs
+ *
+ * clone3() is the extensible successor to clone()/clone2().
+ * It takes a struct as argument that is versioned by its size.
+ *
+ * Return: On success, a positive PID for the child process.
+ *         On error, a negative errno number.
+ */
+SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
+{
+       int err;
+
+       struct kernel_clone_args kargs;
+       pid_t set_tid[MAX_PID_NS_LEVEL];
+
+       kargs.set_tid = set_tid;
+
+       err = copy_clone_args_from_user(&kargs, uargs, size);
+       if (err)
+               return err;
+
+       if (!clone3_args_valid(&kargs))
+               return -EINVAL;
+
+       return kernel_clone(&kargs);
 }
 #endif
 
@@ -2521,10 +3142,27 @@ static void sighand_ctor(void *data)
        init_waitqueue_head(&sighand->signalfd_wqh);
 }
 
-void __init proc_caches_init(void)
+void __init mm_cache_init(void)
 {
        unsigned int mm_size;
 
+       /*
+        * The mm_cpumask is located at the end of mm_struct, and is
+        * dynamically sized based on the maximum CPU number this system
+        * can have, taking hotplug into account (nr_cpu_ids).
+        */
+       mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
+
+       mm_cachep = kmem_cache_create_usercopy("mm_struct",
+                       mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
+                       SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
+                       offsetof(struct mm_struct, saved_auxv),
+                       sizeof_field(struct mm_struct, saved_auxv),
+                       NULL);
+}
+
+void __init proc_caches_init(void)
+{
        sighand_cachep = kmem_cache_create("sighand_cache",
                        sizeof(struct sighand_struct), 0,
                        SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
@@ -2542,20 +3180,10 @@ void __init proc_caches_init(void)
                        SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
                        NULL);
 
-       /*
-        * The mm_cpumask is located at the end of mm_struct, and is
-        * dynamically sized based on the maximum CPU number this system
-        * can have, taking hotplug into account (nr_cpu_ids).
-        */
-       mm_size = sizeof(struct mm_struct) + cpumask_size();
-
-       mm_cachep = kmem_cache_create_usercopy("mm_struct",
-                       mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
-                       SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
-                       offsetof(struct mm_struct, saved_auxv),
-                       sizeof_field(struct mm_struct, saved_auxv),
-                       NULL);
        vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
+#ifdef CONFIG_PER_VMA_LOCK
+       vma_lock_cachep = KMEM_CACHE(vma_lock, SLAB_PANIC|SLAB_ACCOUNT);
+#endif
        mmap_init();
        nsproxy_cache_init();
 }
@@ -2568,7 +3196,8 @@ static int check_unshare_flags(unsigned long unshare_flags)
        if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
                                CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
                                CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
-                               CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
+                               CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
+                               CLONE_NEWTIME))
                return -EINVAL;
        /*
         * Not implemented, but pretend it works if there is nothing
@@ -2616,14 +3245,15 @@ static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
 /*
  * Unshare file descriptor table if it is being shared
  */
-static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
+int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
+              struct files_struct **new_fdp)
 {
        struct files_struct *fd = current->files;
        int error = 0;
 
        if ((unshare_flags & CLONE_FILES) &&
            (fd && atomic_read(&fd->count) > 1)) {
-               *new_fdp = dup_fd(fd, &error);
+               *new_fdp = dup_fd(fd, max_fds, &error);
                if (!*new_fdp)
                        return error;
        }
@@ -2634,7 +3264,7 @@ static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp
 /*
  * unshare allows a process to 'unshare' part of the process
  * context which was originally shared using clone.  copy_*
- * functions used by do_fork() cannot be used here directly
+ * functions used by kernel_clone() cannot be used here directly
  * because they modify an inactive task_struct that is being
  * constructed. Here we are modifying the current, active,
  * task_struct.
@@ -2642,7 +3272,7 @@ static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp
 int ksys_unshare(unsigned long unshare_flags)
 {
        struct fs_struct *fs, *new_fs = NULL;
-       struct files_struct *fd, *new_fd = NULL;
+       struct files_struct *new_fd = NULL;
        struct cred *new_cred = NULL;
        struct nsproxy *new_nsproxy = NULL;
        int do_sysvsem = 0;
@@ -2683,7 +3313,7 @@ int ksys_unshare(unsigned long unshare_flags)
        err = unshare_fs(unshare_flags, &new_fs);
        if (err)
                goto bad_unshare_out;
-       err = unshare_fd(unshare_flags, &new_fd);
+       err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
        if (err)
                goto bad_unshare_cleanup_fs;
        err = unshare_userns(unshare_flags, &new_cred);
@@ -2694,6 +3324,12 @@ int ksys_unshare(unsigned long unshare_flags)
        if (err)
                goto bad_unshare_cleanup_cred;
 
+       if (new_cred) {
+               err = set_cred_ucounts(new_cred);
+               if (err)
+                       goto bad_unshare_cleanup_cred;
+       }
+
        if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
                if (do_sysvsem) {
                        /*
@@ -2723,11 +3359,8 @@ int ksys_unshare(unsigned long unshare_flags)
                        spin_unlock(&fs->lock);
                }
 
-               if (new_fd) {
-                       fd = current->files;
-                       current->files = new_fd;
-                       new_fd = fd;
-               }
+               if (new_fd)
+                       swap(current->files, new_fd);
 
                task_unlock(current);
 
@@ -2766,31 +3399,31 @@ SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
  *     the exec layer of the kernel.
  */
 
-int unshare_files(struct files_struct **displaced)
+int unshare_files(void)
 {
        struct task_struct *task = current;
-       struct files_struct *copy = NULL;
+       struct files_struct *old, *copy = NULL;
        int error;
 
-       error = unshare_fd(CLONE_FILES, &copy);
-       if (error || !copy) {
-               *displaced = NULL;
+       error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
+       if (error || !copy)
                return error;
-       }
-       *displaced = task->files;
+
+       old = task->files;
        task_lock(task);
        task->files = copy;
        task_unlock(task);
+       put_files_struct(old);
        return 0;
 }
 
 int sysctl_max_threads(struct ctl_table *table, int write,
-                      void __user *buffer, size_t *lenp, loff_t *ppos)
+                      void *buffer, size_t *lenp, loff_t *ppos)
 {
        struct ctl_table t;
        int ret;
        int threads = max_threads;
-       int min = MIN_THREADS;
+       int min = 1;
        int max = MAX_THREADS;
 
        t = *table;
@@ -2802,7 +3435,7 @@ int sysctl_max_threads(struct ctl_table *table, int write,
        if (ret || !write)
                return ret;
 
-       set_max_threads(threads);
+       max_threads = threads;
 
        return 0;
 }