if (unlikely(oldfd == newfd))
                return -EINVAL;
 
+       if (newfd >= rlimit(RLIMIT_NOFILE))
+               return -EMFILE;
+
        spin_lock(&files->file_lock);
        err = expand_files(files, newfd);
        file = fcheck(oldfd);
 
 
        fdt = files_fdtable(files);
 
-       /*
-        * N.B. For clone tasks sharing a files structure, this test
-        * will limit the total number of files that can be opened.
-        */
-       if (nr >= rlimit(RLIMIT_NOFILE))
-               return -EMFILE;
-
        /* Do we need to expand? */
        if (nr < fdt->max_fds)
                return 0;
 {
        struct files_struct *files = current->files;
        unsigned int fd;
+       unsigned end = rlimit(RLIMIT_NOFILE);
        int error;
        struct fdtable *fdt;
 
        if (fd < fdt->max_fds)
                fd = find_next_zero_bit(fdt->open_fds, fdt->max_fds, fd);
 
+       /*
+        * N.B. For clone tasks sharing a files structure, this test
+        * will limit the total number of files that can be opened.
+        */
+       error = -EMFILE;
+       if (fd >= end)
+               goto out;
+
        error = expand_files(files, fd);
        if (error < 0)
                goto out;