@@ -1164,15 +1164,6 @@ ssize_t btrfs_buffered_write(struct kioc
int extents_locked;
bool force_page_uptodate = false;
- /*
- * Fault pages before locking them in prepare_one_folio()
- * to avoid recursive lock
- */
- if (unlikely(fault_in_iov_iter_readable(i, write_bytes))) {
- ret = -EFAULT;
- break;
- }
-
only_release_metadata = false;
sector_offset = pos & (fs_info->sectorsize - 1);
@@ -1314,6 +1305,17 @@ again:
cond_resched();
+ /*
+ * Fault pages in a slow path after dropping folio
+ * lock. This avoids the chance of deadlocking in
+ * the fault handler.
+ */
+ if (unlikely(copied == 0) &&
+ (fault_in_iov_iter_readable(i, write_bytes) == write_bytes)) {
+ ret = -EFAULT;
+ break;
+ }
+
pos += copied;
num_written += copied;
}