* if the fd table isn't shared).
         */
        if (clone_flags & CLONE_PIDFD) {
-               retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
+               /* Note that no task has been attached to @pid yet. */
+               retval = __pidfd_prepare(pid, O_RDWR | O_CLOEXEC, &pidfile);
                if (retval < 0)
                        goto bad_fork_free_pid;
-
                pidfd = retval;
 
-               pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
-                                             O_RDWR | O_CLOEXEC);
-               if (IS_ERR(pidfile)) {
-                       put_unused_fd(pidfd);
-                       retval = PTR_ERR(pidfile);
-                       goto bad_fork_free_pid;
-               }
-               get_pid(pid);   /* held by pidfile now */
-
                retval = put_user(pidfd, args->pidfd);
                if (retval)
                        goto bad_fork_put_pidfd;