Skip to contentSkip to conversation

migrate ocfs2 DIO from buffer_head to iomap

RFC PATCH New Joseph Qi 1 participant 11 messages Dec 1 OCFS2

lore
Share & tools
lore

Joseph Qi

author maintainer
#0 lore raw

v14 cover migrate ocfs2 DIO from buffer_head to iomap

This patch set migrates ocfs2 Direct I/O (DIO) from the legacy buffer_head path to iomap, so ocfs2 stops being a user of __blockdev_direct_IO() and LEGACY_DIRECT_IO can be dropped.

Reads are served by ocfs2_iomap_begin() over ocfs2_map_blocks(). Writes get a mapping of as many clusters as one struct iomap can describe, allocate their whole contiguous range with a single ocfs2_add_inode_data() call, and convert the unwritten extents at completion. The kiocb is the identity of the I/O across ->iomap_begin() and ->end_io(), so the unwritten records and the append-DIO orphan entry belong to a specific write instead of to a buffer_head.

It is based on commit e5aad2bdbbee (next-20261127).

v14 changelog:

Rebased onto next-20261127. The rest are fixes from review of v13:

patch 2/10: the DIO read path calls __iomap_dio_rw() directly and so bypassed generic_file_read_iter(), which updates atime for DIO. Add file_accessed() so relatime's 24h rule and strictatime's per-read update are not lost, matching ext4 and xfs.

patch 7/10: a write that errors no longer converts its unwritten extents. iomap keeps dio->size counting bios that failed at completion, and a short write can leave the cluster tail unzeroed, so converting exposed stale disk blocks and swallowed the error. Leave the extents unwritten, drop the zeroed folios and return the error, as ext4 and xfs do. The orphan pid is now a strict ownership token: every path that leaves the entry zeroes it, and ocfs2_dio_clear_orphan() only removes the entry once i_size covers the write or nothing is allocated beyond i_size, so a later write cannot strand a failed write's excess clusters.

patch 8/10: the sub-page probe only checks the ends that are not page aligned (a page-aligned end is fully covered) and skips the tail lookup when it shares the head's block. The rw_lock upgrade re-runs ocfs2_prepare_inode_for_write() to refresh the inode and redo CoW across the lock drop. A demoted IOCB_NOWAIT write returns -EAGAIN before kiocb_modified() dirties the inode.

patch 9/10: clear the folio dirty bit once the zeroed buffers are written out, so a RWF_NOWAIT read does not see a clean folio as needing writeback. The failure path still refreshes i_blocks and records the fsync transaction.

patch 10/10: the buffered wait starts at min(pos, i_size), so an extending write also waits on the cluster containing i_size, which ocfs2_zero_extend() skips as unwritten while a dio is in flight.

patch 1/10, 3/10, 4/10, 5/10, 6/10: no functional change.

The overall design is as in v13:

patch 6/10 reworks the write context, the folio preparation and the unwritten extent tracking for multi-cluster mappings. Unwritten extents become a range with an owner instead of one entry per cluster carrying a physical address; the physical cluster is looked up at conversion time with ocfs2_get_clusters_uncached(). The buffer_head path is ported onto this and still maps one cluster per call, so behaviour is unchanged.

patch 7/10 switches the write path to iomap. ocfs2_dio_wr_map_blocks() replaces ocfs2_dio_wr_get_block() and hands out a mapping of as many clusters as one struct iomap can describe, up to 16MB, stopped at the first cluster of a different kind. Completion converts the recorded ranges and updates i_size. The orphan add and remove and the EOF gap zeroing move to ocfs2_file_write_iter(), where inode_lock() serializes the writers and IOMAP_DIO_FORCE_WAIT makes an extending write complete before the function returns. The kiocb passed in iomap_iter.private is the identity of the I/O, so the unwritten records belong to a specific write. ocfs2 no longer needs LEGACY_DIRECT_IO.

The mapping waits for unwritten records belonging to another dio before it takes the re-write fast path, and the unwritten check distinguishes its own records from a foreign one. Those two arrive together: a completion that fails part way has already converted clusters and dropped the locks but still owns the records and is about to write the zeroed head/tail buffers over them, so the fast path must not hand them out first.

Every path that falls back to generic_perform_write() upgrades the rw lock to EX, including the -ENOTBLK / zero-length bounce inside the direct branch. Under coherency=buffered a PR lock lets another node write the same range directly while this node does a read-modify-write in the page cache. The upgrade releases PR and takes EX as two requests, because a single upgrade can deadlock in the cluster lock manager when two nodes upgrade at once; the inode is re-prepared after the drop.

patch 8/10 keeps sub-page O_DIRECT overwrites of already-written blocks direct. v12.1 demoted every non-page-aligned write when i_blocksize(inode) < PAGE_SIZE, which on 16K and 64K page kernels is every ocfs2 volume, so all sub-page overwrites took an exclusive rw lock and failed IOCB_NOWAIT. Probe the partial blocks at the unaligned ends with a no-create lookup and demote only for a hole, an unwritten extent, or an extending write. The probe runs after generic_write_checks() has resolved O_APPEND and clamped the length and ocfs2_prepare_inode_for_write() has refreshed the inode.

patch 9/10 writes the zeroed head/tail buffers out at mapping time. They can be wholly beyond i_size until completion, and __block_write_full_folio() clears their dirty bit without submitting them, so the zeroes never reach the disk and the converted cluster exposes stale blocks. Submit every buffer first and wait in a second pass, so a cluster spanning many folios does not cost one round trip per folio.

patch 10/10 makes buffered writes wait for in-flight direct writes before deferring zeroing and unwritten conversion to them. A dio that fails or ends short leaves the cluster unwritten while the buffered data sits in a dirty folio, and it reads back as zeroes once that folio is evicted.

Two windows are left open deliberately:

- ocfs2_page_mkwrite() still defers zeroing and unwritten conversion to an in-flight dio without waiting for it. It holds no i_rwsem, and it is reachable through get_user_pages() from bio_iov_iter_get_pages() when the dio source buffer is an mmap of the same file, so a plain wait there would match the dio's own records and deadlock against itself. Closing it needs a way to exclude the current task's own in-flight dio first.
- a failed extending dio still leaves its orphan entry and the clusters it allocated beyond i_size for recovery. The in-memory marker is kept so the next extending write recovers them, but an unlink before that still strands the inode until an unclean recovery.

--------------

# test report

Single node, o2cb cluster stack.

## ocfs2 testsuite

single_run-WIP.sh -d /dev/vdb (40G), mkfs -b 4k -C 16k -N 4 --fs-features=usrquota,grpquota, on this revision (next-20261127).

79 PASSED, 3 FAILED, total runtime 5963 seconds. Two failures are buildkernel data=writeback and data=ordered, both failing in 0-1 seconds on a missing buildkernel log file, unrelated to the filesystem, as in the pre-series baseline. The third, xattr_test, fails identically on the base next-20261127 kernel with this series removed (flistxattr ERANGE in the -b 512 -C 4096 case), so it is not introduced by this series.

## xfstests

./check -E ocfs2.exclude <90 generic DIO tests> mkfs -b 4k -C 16k -N 4 --fs-features=usrquota,grpquota

52 pass, 10 fail, 28 not run. Per-test verdicts identical to the pre-conversion baseline. Failures: generic/091 generic/094 generic/219 generic/263 generic/326 generic/328 generic/521 generic/587 generic/617 generic/733 - all pre-existing.

Also run on a 1M cluster volume, so clustersize > PAGE_SIZE and the head/tail folio paths actually execute: sub-cluster O_DIRECT zeroing reads back from disk correctly, and four concurrent O_DIRECT writers over a shared region complete without corruption. A sub-page test on a 1K block volume confirms written-block sub-page O_DIRECT overwrites stay direct and a demoted IOCB_NOWAIT write returns -EAGAIN without touching mtime.

No WARNING, BUG or hung task in any run. One lockdep report is seen during generic/113, a mmap_lock -> ocfs2 inode cluster lock chain via ocfs2_mmap_prepare()/ocfs2_fiemap(); it does not fail the test and is in code this series does not change.

The DIO xfstests, 1M cluster and sub-page runs were done on the revision carrying the write-path fixes, whose ocfs2 write code is identical to this version; the ocfs2 testsuite above was run on this exact revision.

-------------
patchset history

v1 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v2 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v3 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v4 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v5 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v6 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v7 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v8 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v9 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v10 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v11 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v12 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v12.1 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v13 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/

Heming Zhao (7):
ocfs2: Add new ocfs2_map_blocks() to introduce iomap feature
ocfs2: switch DIO read path from buffer_head to iomap
ocfs2: add ocfs2_get_clusters_uncached()
ocfs2: refactor ocfs2_lock_allocators() and add a dio variant
ocfs2: record the fsync transaction when CoW makes clusters writable
ocfs2: rework the direct write context for multi-cluster mappings
ocfs2: switch dio write path from buffer_head to iomap

Joseph Qi (3):
ocfs2: keep sub-page overwrites of written blocks on direct I/O
ocfs2: write the dio zeroed head/tail buffers out before completion
ocfs2: make buffered writes wait for in-flight direct writes

 fs/ocfs2/Kconfig        |    2 +-
 fs/ocfs2/aops.c         | 2262 ++++++++++++++++++++++++++++++++-------
 fs/ocfs2/aops.h         |   45 +-
 fs/ocfs2/extent_map.c   |   34 +-
 fs/ocfs2/extent_map.h   |    3 +
 fs/ocfs2/file.c         |  381 ++++++-
 fs/ocfs2/inode.h        |    8 +
 fs/ocfs2/mmap.c         |    3 +-
 fs/ocfs2/ocfs2.h        |   25 +-
 fs/ocfs2/refcounttree.c |    2 +
 fs/ocfs2/suballoc.c     |   50 +-
 fs/ocfs2/suballoc.h     |    5 +
 fs/ocfs2/super.c        |    3 +
 13 files changed, 2374 insertions(+), 449 deletions(-)
Signature · 1 line
2.39.3
author maintainer
#1 lore raw

RFC PATCH v14 1/10 ocfs2: Add new ocfs2_map_blocks() to introduce iomap feature

From: Heming Zhao <[email protected]>

As part of migrating OCFS2 DIO read/write code paths towards the modern and performant iomap framework, here introduces ocfs2_map_blocks() to replace the legacy, high-overhead buffer_head based block mapping routines.

In addition, OCFS2_MAP_* flags are defined to bridge OCFS2 internal block mapping flags with the iomap API requirements.

Subsequent iomap integration patches will build on this core block mapping routine. The implementation draws inspiration from ext4_map_blocks().

---
 fs/ocfs2/aops.c  | 70 ++++++++++++++++++++++++++++++++++++++++++++++++
 fs/ocfs2/aops.h  |  2 ++
 fs/ocfs2/ocfs2.h | 25 ++++++++++++++++-
 3 files changed, 96 insertions(+), 1 deletion(-)
fs/ocfs2/aops.c +70 -0
index 4acdbb70882cd..64fcf6eb3d89b 100644
@@ -126,6 +126,76 @@ static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock,
 	return ret;
 }
 
+/* ocfs2 never allocates in this function */
+int ocfs2_map_blocks(struct inode *inode, struct ocfs2_map_block *map,
+		    int flags)
+{
+	int err = 0;
+	unsigned int ext_flags;
+	u64 max_blocks = map->len;
+	u64 p_blkno, count, past_eof;
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	int create = flags & OCFS2_GET_BLOCKS_CREATE;
+
+	if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_SYSTEM_FILE)
+		mlog(ML_NOTICE, "map_block on system inode 0x%p (%llu)\n",
+		     inode, inode->i_ino);
+
+	err = ocfs2_extent_map_get_blocks(inode, map->lblk, &p_blkno, &count,
+					  &ext_flags);
+	if (err) {
+		mlog(ML_ERROR, "get_blocks() failed, inode: 0x%p, "
+		     "block: %llu\n", inode, map->lblk);
+		goto bail;
+	}
+
+	if (max_blocks < count)
+		count = max_blocks;
+
+	map->pblk = p_blkno;
+	map->len = count;
+
+	/*
+	 * If we see this on a sparse file system, then a truncate has
+	 * raced us and removed the cluster. We treat this as a hole
+	 * and skip setting the iomap flags. The caller will set
+	 * iomap->type to IOMAP_HOLE.
+	 */
+	if (create && map->pblk == 0 && ocfs2_sparse_alloc(osb))
+		goto bail;
+
+	if (p_blkno) {
+		if (ext_flags & OCFS2_EXT_UNWRITTEN)
+			map->flags |= OCFS2_MAP_UNWRITTEN;
+		else
+			map->flags |= OCFS2_MAP_MAPPED;
+	}
+
+	if (!ocfs2_sparse_alloc(osb)) {
+		if (map->pblk == 0) {
+			err = -EIO;
+			mlog(ML_ERROR,
+			     "iblock = %llu p_blkno = %llu blkno=(%llu)\n",
+			     (unsigned long long)map->lblk,
+			     (unsigned long long)map->pblk,
+			     (unsigned long long)OCFS2_I(inode)->ip_blkno);
+			mlog(ML_ERROR, "Size %llu, clusters %u\n",
+			     (unsigned long long)i_size_read(inode),
+			     OCFS2_I(inode)->ip_clusters);
+			dump_stack();
+			goto bail;
+		}
+	}
+
+	past_eof = ocfs2_blocks_for_bytes(inode->i_sb, i_size_read(inode));
+
+	if (create && (map->lblk >= past_eof))
+		map->flags |= OCFS2_MAP_NEW;
+
+bail:
+	return err;
+}
+
 int ocfs2_get_block(struct inode *inode, sector_t iblock,
 		    struct buffer_head *bh_result, int create)
 {
fs/ocfs2/aops.h +2 -0
index 114efc9111e43..8dd6edd7c1a13 100644
@@ -42,6 +42,8 @@ int ocfs2_size_fits_inline_data(struct buffer_head *di_bh, u64 new_size);
 
 int ocfs2_get_block(struct inode *inode, sector_t iblock,
 		    struct buffer_head *bh_result, int create);
+int ocfs2_map_blocks(struct inode *inode, struct ocfs2_map_block *map,
+		    int flags);
 /* all ocfs2_dio_end_io()'s fault */
 #define ocfs2_iocb_is_rw_locked(iocb) \
 	test_bit(0, (unsigned long *)&iocb->private)
fs/ocfs2/ocfs2.h +24 -1
index 8bee145e48887..0c2674615c3d6 100644
@@ -515,7 +515,30 @@ struct ocfs2_super
 	struct ocfs2_filecheck_sysfs_entry osb_fc_ent;
 };
 
-#define OCFS2_SB(sb)	    ((struct ocfs2_super *)(sb)->s_fs_info)
+/*
+ * Logical to physical block mapping, used by ocfs2_map_blocks()
+ *
+ * This structure is used to pass requests into ocfs2_map_blocks()
+ * as well as to store the information returned by ocfs2_map_blocks().
+ * It takes less room on the stack than a struct buffer_head.
+ */
+#define OCFS2_MAP_NEW			BIT(BH_New)
+#define OCFS2_MAP_MAPPED		BIT(BH_Mapped)
+#define OCFS2_MAP_UNWRITTEN		BIT(BH_Unwritten)
+#define OCFS2_MAP_FLAGS		(OCFS2_MAP_NEW | OCFS2_MAP_MAPPED |\
+				 OCFS2_MAP_UNWRITTEN)
+
+struct ocfs2_map_block {
+	u64 pblk; /* physical block# */
+	u64 lblk; /* logical block# */
+	u64 len;  /* number of block */
+	unsigned int flags;
+};
+
+/* Flags used by ocfs2_map_blocks() */
+#define OCFS2_GET_BLOCKS_CREATE	(0x0001)
+
+#define OCFS2_SB(sb)	((struct ocfs2_super *)(sb)->s_fs_info)
 
 /* Useful typedef for passing around journal access functions */
 typedef int (*ocfs2_journal_access_func)(handle_t *handle,
Signature · 1 line
2.39.3
author maintainer
#2 lore raw

RFC PATCH v14 2/10 ocfs2: switch DIO read path from buffer_head to iomap

In reply to Joseph Qi

From: Heming Zhao <[email protected]>

Migrates the DIO read path from the legacy buffer_head infrastructure to the modern and more efficient iomap framework.

Under the current code, ocfs2 holds a cluster lock during DIO via ocfs2_iocb_set_rw_locked(), and releases the cluster lock in ocfs2_dio_end_io() via ocfs2_iocb_clear_rw_locked(). The lock level is stashed in iocb->private.

However, iomap DIO owns that field (it stores a bio there for polled I/O and unconditionally clears it before calling ->end_io). Any side-channel state packed into iocb->private is corrupted, which trips the end_io lock-state check.

Instead, encode the unlock level by passing distinct iomap_dio_ops methods e.g.: ocfs2_iomap_dio_ops_r_pr ocfs2_iomap_dio_ops_w_pr for PRMODE or ocfs2_iomap_dio_ops_w_ex for EXMODE. Also note that the ops_w_{pr|ex} are defined in a later patch.

Additionally, the *_iter() functions use the split __iomap_dio_rw() + iomap_dio_complete() API so they can determine unambiguously, from the return value, whether the completion handler already dropped the lock (real I/O, sync or -EIOCBQUEUED) or whether the caller must drop it (no I/O issued, or buffered fallback).

The new function ocfs2_iomap_begin() performs a similar role to ocfs2_get_block(). While ocfs2_get_block() retrieves only one block per call, ocfs2_iomap_begin() can handle multiple blocks at once.

---
 fs/ocfs2/Kconfig |   1 +
 fs/ocfs2/aops.c  | 107 +++++++++++++++++++++++++++++++++++++++++++++--
 fs/ocfs2/aops.h  |   5 +++
 fs/ocfs2/file.c  |  67 +++++++++++++++++++++++++----
 4 files changed, 168 insertions(+), 12 deletions(-)
fs/ocfs2/Kconfig +1 -0
index 2514d36cbe015..bf1678a5eb01e 100644
@@ -7,6 +7,7 @@ config OCFS2_FS
 	select CRC32
 	select QUOTA
 	select QUOTA_TREE
+	select FS_IOMAP
 	select FS_POSIX_ACL
 	select LEGACY_DIRECT_IO
 	help
fs/ocfs2/aops.c +104 -3

138 lines not on this page · raw message

fs/ocfs2/aops.h +5 -0
index 8dd6edd7c1a13..72de1e764a578 100644
@@ -7,6 +7,11 @@
 #define OCFS2_AOPS_H
 
 #include <linux/fs.h>
+#include <linux/iomap.h>
+
+extern const struct iomap_dio_ops ocfs2_iomap_dio_ops_r_pr;
+int ocfs2_iomap_next(const struct iomap_iter *iter, struct iomap *iomap,
+			    struct iomap *srcmap);
 
 int ocfs2_map_folio_blocks(struct folio *folio, u64 *p_blkno,
 			  struct inode *inode, unsigned int from,
fs/ocfs2/file.c +58 -9

102 lines not on this page · raw message

Signature · 1 line
2.39.3
author maintainer
#3 lore raw

RFC PATCH v14 3/10 ocfs2: add ocfs2_get_clusters_uncached()

In reply to Joseph Qi

From: Heming Zhao <[email protected]>

ocfs2_get_clusters() consults the extent map cache, which merges adjacent on-disk records into one. A caller that needs to operate on one on-disk record at a time cannot use it: the returned range may span several records, and inserting the lookup result back into the cache is not wanted either.

Factor the lookup into __ocfs2_get_clusters() with a cache flag and add ocfs2_get_clusters_uncached(), which reads the extent tree directly and leaves the cache alone. ocfs2_get_clusters() keeps its current behaviour.

No functional change.

---
 fs/ocfs2/extent_map.c | 34 ++++++++++++++++++++++++++--------
 fs/ocfs2/extent_map.h |  3 +++
 2 files changed, 29 insertions(+), 8 deletions(-)
fs/ocfs2/extent_map.c +26 -8
index eb5dcd17d4375..2510e68fbde85 100644
@@ -602,9 +602,9 @@ int ocfs2_xattr_get_clusters(struct inode *inode, u32 v_cluster,
 	return ret;
 }
 
-int ocfs2_get_clusters(struct inode *inode, u32 v_cluster,
-		       u32 *p_cluster, u32 *num_clusters,
-		       unsigned int *extent_flags)
+static int __ocfs2_get_clusters(struct inode *inode, u32 v_cluster,
+				u32 *p_cluster, u32 *num_clusters,
+				unsigned int *extent_flags, bool cache)
 {
 	int ret;
 	unsigned int hole_len, flags = 0;
@@ -617,10 +617,12 @@ int ocfs2_get_clusters(struct inode *inode, u32 v_cluster,
 		goto out;
 	}
 
-	ret = ocfs2_extent_map_lookup(inode, v_cluster, p_cluster,
-				      num_clusters, extent_flags);
-	if (ret == 0)
-		goto out;
+	if (cache) {
+		ret = ocfs2_extent_map_lookup(inode, v_cluster, p_cluster,
+					      num_clusters, extent_flags);
+		if (ret == 0)
+			goto out;
+	}
 
 	ret = ocfs2_read_inode_block(inode, &di_bh);
 	if (ret) {
@@ -650,7 +652,8 @@ int ocfs2_get_clusters(struct inode *inode, u32 v_cluster,
 					      p_cluster, num_clusters);
 		flags = rec.e_flags;
 
-		ocfs2_extent_map_insert_rec(inode, &rec);
+		if (cache)
+			ocfs2_extent_map_insert_rec(inode, &rec);
 	}
 
 	if (extent_flags)
@@ -661,6 +664,21 @@ int ocfs2_get_clusters(struct inode *inode, u32 v_cluster,
 	return ret;
 }
 
+int ocfs2_get_clusters(struct inode *inode, u32 v_cluster, u32 *p_cluster,
+		       u32 *num_clusters, unsigned int *extent_flags)
+{
+	return __ocfs2_get_clusters(inode, v_cluster, p_cluster, num_clusters,
+				    extent_flags, true);
+}
+
+int ocfs2_get_clusters_uncached(struct inode *inode, u32 v_cluster,
+				u32 *p_cluster, u32 *num_clusters,
+				unsigned int *extent_flags)
+{
+	return __ocfs2_get_clusters(inode, v_cluster, p_cluster, num_clusters,
+				    extent_flags, false);
+}
+
 /*
  * This expects alloc_sem to be held. The allocation cannot change at
  * all while the map is in the process of being updated.
fs/ocfs2/extent_map.h +3 -0
index bc4ed59fb9257..b5b2d511ef9d5 100644
@@ -32,6 +32,9 @@ void ocfs2_extent_map_insert_rec(struct inode *inode,
 
 int ocfs2_get_clusters(struct inode *inode, u32 v_cluster, u32 *p_cluster,
 		       u32 *num_clusters, unsigned int *extent_flags);
+int ocfs2_get_clusters_uncached(struct inode *inode, u32 v_cluster,
+				u32 *p_cluster, u32 *num_clusters,
+				unsigned int *extent_flags);
 int ocfs2_extent_map_get_blocks(struct inode *inode, u64 v_blkno, u64 *p_blkno,
 				u64 *ret_count, unsigned int *extent_flags);
 
Signature · 1 line
2.39.3
author maintainer
#4 lore raw

RFC PATCH v14 4/10 ocfs2: refactor ocfs2_lock_allocators() and add a dio variant

In reply to Joseph Qi

From: Heming Zhao <[email protected]>

ocfs2_lock_allocators() derives the worst case number of extent records from clusters_to_add + 2 * extents_to_split, which assumes the caller inserts one record per cluster. A direct write does not: it allocates its whole contiguous range with a single ocfs2_add_inode_data() call, and ocfs2_add_clusters_in_btree() makes exactly one ocfs2_insert_extent() call, so at most one record is added. It does not split an extent either, because unwritten extents are converted when the io is done.

Factor the reservation into __ocfs2_lock_allocators() taking max_recs_needed directly. ocfs2_lock_allocators() keeps its current computation, and ocfs2_lock_allocators_dio() passes one record when there is anything to allocate.

Reserving metadata is still driven by ocfs2_num_free_extents(), which counts the free records in the rightmost leaf - the same block ocfs2_figure_insert_type() tests - so a tree that needs to grow still gets a metadata reservation.

No functional change for existing callers.

---
 fs/ocfs2/suballoc.c | 50 +++++++++++++++++++++++++++++++++++++++------
 fs/ocfs2/suballoc.h |  5 +++++
 2 files changed, 49 insertions(+), 6 deletions(-)
fs/ocfs2/suballoc.c +44 -6
index 23c9fbb31cbd1..8c7e7b50efbc9 100644
@@ -3242,15 +3242,20 @@ int ocfs2_release_clusters(handle_t *handle,
  *
  * File systems which don't support holes call this from
  * ocfs2_extend_allocation().
+ *
+ * @clusters_to_add is the number of data clusters to reserve.
+ * @max_recs_needed is the worst case number of extent records this
+ * allocation can add.  It is not always @clusters_to_add: a direct write
+ * inserts its whole contiguous range with one ocfs2_add_inode_data() call.
  */
-int ocfs2_lock_allocators(struct inode *inode,
-			  struct ocfs2_extent_tree *et,
-			  u32 clusters_to_add, u32 extents_to_split,
-			  struct ocfs2_alloc_context **data_ac,
-			  struct ocfs2_alloc_context **meta_ac)
+static int __ocfs2_lock_allocators(struct inode *inode,
+				   struct ocfs2_extent_tree *et,
+				   u32 clusters_to_add,
+				   u32 max_recs_needed,
+				   struct ocfs2_alloc_context **data_ac,
+				   struct ocfs2_alloc_context **meta_ac)
 {
 	int ret = 0, num_free_extents;
-	unsigned int max_recs_needed = clusters_to_add + 2 * extents_to_split;
 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
 
 	*meta_ac = NULL;
@@ -3314,6 +3319,39 @@ int ocfs2_lock_allocators(struct inode *inode,
 	return ret;
 }
 
+/*
+ * Reserve for an allocation which may add one extent record per cluster.  A
+ * buffered write inserts each cluster separately, and splitting an unwritten
+ * extent can add two more records.
+ */
+int ocfs2_lock_allocators(struct inode *inode,
+			  struct ocfs2_extent_tree *et,
+			  u32 clusters_to_add, u32 extents_to_split,
+			  struct ocfs2_alloc_context **data_ac,
+			  struct ocfs2_alloc_context **meta_ac)
+{
+	return __ocfs2_lock_allocators(inode, et, clusters_to_add,
+				       clusters_to_add + 2 * extents_to_split,
+				       data_ac, meta_ac);
+}
+
+/*
+ * A direct write allocates its whole contiguous range with a single
+ * ocfs2_add_inode_data() call, which inserts at most one extent record, and
+ * it does not split an extent here (unwritten extents are converted when the
+ * io is done).
+ */
+int ocfs2_lock_allocators_dio(struct inode *inode,
+			      struct ocfs2_extent_tree *et,
+			      u32 clusters_to_add,
+			      struct ocfs2_alloc_context **data_ac,
+			      struct ocfs2_alloc_context **meta_ac)
+{
+	return __ocfs2_lock_allocators(inode, et, clusters_to_add,
+				       clusters_to_add ? 1 : 0,
+				       data_ac, meta_ac);
+}
+
 /*
  * Read the inode specified by blkno to get suballoc_slot and
  * suballoc_bit.
fs/ocfs2/suballoc.h +5 -0
index 6042abc032f96..b1b725857fc6e 100644
@@ -203,6 +203,11 @@ int ocfs2_lock_allocators(struct inode *inode, struct ocfs2_extent_tree *et,
 			  u32 clusters_to_add, u32 extents_to_split,
 			  struct ocfs2_alloc_context **data_ac,
 			  struct ocfs2_alloc_context **meta_ac);
+int ocfs2_lock_allocators_dio(struct inode *inode,
+			      struct ocfs2_extent_tree *et,
+			      u32 clusters_to_add,
+			      struct ocfs2_alloc_context **data_ac,
+			      struct ocfs2_alloc_context **meta_ac);
 
 int ocfs2_test_inode_bit(struct ocfs2_super *osb, u64 blkno, int *res);
 
Signature · 1 line
2.39.3
author maintainer
#5 lore raw

RFC PATCH v14 5/10 ocfs2: record the fsync transaction when CoW makes clusters writable

In reply to Joseph Qi

From: Heming Zhao <[email protected]>

ocfs2_make_clusters_writable() changes the extent tree to break a refcount sharing, but it does not record the transaction in the inode's datasync tid. A subsequent O_DSYNC or fsync that relies on i_datasync_tid can therefore consider the CoW already committed and skip waiting for it.

Record it on the success path, like the other extent tree changes do.

Fixes 6f70fa519976 ("ocfs2: Add CoW support.")
---
 fs/ocfs2/refcounttree.c | 2 ++
 1 file changed, 2 insertions(+)
fs/ocfs2/refcounttree.c +2 -0
index 4f13b5a6faa7d..485104aab14e6 100644
@@ -3360,6 +3360,8 @@ static int ocfs2_make_clusters_writable(struct super_block *sb,
 	}
 
 out_commit:
+	if (!ret)
+		ocfs2_update_inode_fsync_trans(handle, context->inode, 1);
 	ocfs2_commit_trans(osb, handle);
 
 out:
Signature · 1 line
2.39.3
author maintainer
#6 lore raw

RFC PATCH v14 6/10 ocfs2: rework the direct write context for multi-cluster mappings

In reply to Joseph Qi

From: Heming Zhao <[email protected]>

The direct write path maps one cluster per ->get_block() call, so the write context, the folio preparation and the unwritten extent tracking are all built around a single cluster. A mapping that spans many clusters needs none of that re-done per cluster.

Rework the write context to describe a range:

- ocfs2_alloc_write_ctxt() allocates one descriptor per cluster of the requested range, and ocfs2_dio_trim_write_ctxt() cuts it at the first cluster that is not of the same kind as the first, so a mapping is all hole, all unwritten or all written, and contiguous on disk.
- ocfs2_dio_alloc_clusters() allocates the whole contiguous range with one ocfs2_add_inode_data() call and shortens the write if the allocator returns less, using ocfs2_lock_allocators_dio() to reserve for it.
- ocfs2_grab_folios_direct() and ocfs2_prepare_cluster_folios() prepare the folios of the first and the last cluster only; the clusters in between are covered by the user range and need no page cache page. ocfs2_dio_need_zero_folios() decides whether any folio is needed at all.
- ocfs2_write_clusters_direct() zeroing is limited to the head and tail windows, so it does not touch blocks an earlier mapping of the same write has already written.

Unwritten extents are recorded as a range with an owner instead of one entry per cluster carrying a physical address:

- struct ocfs2_unwritten_extent gains ue_owner and ue_clusters and loses ue_phys; the physical cluster is looked up at conversion time with ocfs2_get_clusters_uncached(), because the extent map cache merges adjacent records and the conversion works one record at a time.
- ocfs2_dio_add_unwritten() records the runs of clusters a write zeroed, and ocfs2_unwritten_check_locked() only consults the list. The list is walked once per write context under a single ip_lock hold rather than once per cluster.
- ocfs2_dio_end_io_write() converts the recorded ranges, clipping them to the bytes actually written, and updates i_size.
- ip_unwritten_wq is added and ocfs2_free_unwritten_list() wakes it, so a later patch can wait for the entries of another write.

ocfs2_write_begin_nolock() takes the owner and returns the end of the range it touched, so a caller can clean up the head and tail folios after it has dropped the locks and freed the write context. The buffered and mmap callers pass NULL.

The buffer_head direct write path is ported onto this: get_block() passes the dio write context as the owner and splices the recorded range into it, and completion converts the ranges through ocfs2_dio_end_io_write(). It still maps one cluster per call, so behaviour is unchanged.

The buffer_head path keeps its own concurrency behaviour here. The unwritten check still just defers to whichever write recorded the cluster, without distinguishing an owner, because the wait for foreign records is added with the iomap mapping in the next patch. And the orphan entry get_block() adds is removed in ocfs2_dio_bh_end_io(), as the old ocfs2_dio_end_io_write() did: leaving it set makes the next extending write recover it by truncating to i_size, freeing clusters another write has just allocated.

---
 fs/ocfs2/aops.c  | 1273 +++++++++++++++++++++++++++++++++++-----------
 fs/ocfs2/aops.h  |    3 +-
 fs/ocfs2/inode.h |    2 +
 fs/ocfs2/mmap.c  |    3 +-
 fs/ocfs2/super.c |    1 +
 5 files changed, 986 insertions(+), 296 deletions(-)
fs/ocfs2/aops.c +979 -294
index 21cdc5c29331d..e3e28584e7410 100644
@@ -114,26 +114,19 @@ static int ocfs2_symlink_get_block(struct inode *inode, sector_t iblock,
 	return err;
 }
 
-static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock,
-		    struct buffer_head *bh_result, int create)
-{
-	int ret = 0;
-	struct ocfs2_inode_info *oi = OCFS2_I(inode);
-
-	down_read(&oi->ip_alloc_sem);
-	ret = ocfs2_get_block(inode, iblock, bh_result, create);
-	up_read(&oi->ip_alloc_sem);
-
-	return ret;
-}
-
 static int ocfs2_lock_map_blocks(struct inode *inode,
-				 struct ocfs2_map_block *map, int flags)
+				 struct ocfs2_map_block *map, int flags,
+				 bool nowait)
 {
 	int ret = 0;
 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 
-	down_read(&oi->ip_alloc_sem);
+	if (nowait) {
+		if (!down_read_trylock(&oi->ip_alloc_sem))
+			return -EAGAIN;
+	} else {
+		down_read(&oi->ip_alloc_sem);
+	}
 	ret = ocfs2_map_blocks(inode, map, flags);
 	up_read(&oi->ip_alloc_sem);
 
@@ -756,11 +749,26 @@ int ocfs2_map_folio_blocks(struct folio *folio, u64 *p_blkno,
 
 #define OCFS2_MAX_CLUSTERS_PER_PAGE	(PAGE_SIZE / OCFS2_MIN_CLUSTERSIZE)
 
+/*
+ * Describe a range of clusters whose extents are (or were just allocated as)
+ * unwritten, and which a direct write is going to convert once its io has
+ * finished (see ocfs2_dio_end_io_write()).
+ *
+ * The entry is linked on oi->ip_unwritten_list for as long as the dio is in
+ * flight, so that buffered writers see the clusters are already taken care of
+ * and do not zero them under the dio.  iomap gives ->end_io() nothing but the
+ * kiocb, so ue_owner is how the entries created by ->iomap_begin() are found
+ * again at end_io time: it is the kiocb which __iomap_dio_rw() was called with.
+ *
+ * ue_node is used to chain the entries on a private list: the wc during
+ * write_begin, a local list in end_io.
+ */
 struct ocfs2_unwritten_extent {
 	struct list_head	ue_node;
 	struct list_head	ue_ip_node;
 	u32			ue_cpos;
-	u32			ue_phys;
+	u32			ue_clusters;
+	void			*ue_owner;
 };
 
 /*
@@ -773,9 +781,16 @@ struct ocfs2_write_cluster_desc {
 	 * Give this a unique field because c_phys eventually gets
 	 * filled.
 	 */
-	unsigned	c_new;
-	unsigned	c_clear_unwritten;
-	unsigned	c_needs_zero;
+	unsigned int	c_new;
+	unsigned int	c_clear_unwritten;
+	unsigned int	c_needs_zero;
+	/*
+	 * Direct write only: this cluster is unwritten and this very dio
+	 * (ue_owner) is going to convert it, either because it zeroed it in
+	 * this write_begin or because an earlier ->iomap_begin() of the same
+	 * dio did.  The mapping has to be reported as unwritten.
+	 */
+	unsigned int	c_dio_unwritten;
 };
 
 struct ocfs2_write_ctxt {
@@ -789,7 +804,13 @@ struct ocfs2_write_ctxt {
 	/* Type of caller. Must be one of buffer, mmap, direct.  */
 	ocfs2_write_type_t		w_type;
 
-	struct ocfs2_write_cluster_desc	w_desc[OCFS2_MAX_CLUSTERS_PER_PAGE];
+	/*
+	 * One descriptor per cluster of the write.  Buffered and mmap writes
+	 * never span more than a page, so the inline array is enough for them.
+	 * A direct write may span many clusters, w_desc is then allocated.
+	 */
+	struct ocfs2_write_cluster_desc	*w_desc;
+	struct ocfs2_write_cluster_desc	w_desc_inline[OCFS2_MAX_CLUSTERS_PER_PAGE];
 
 	/*
 	 * This is true if page_size > cluster_size.
@@ -812,7 +833,8 @@ struct ocfs2_write_ctxt {
 	 * zero's.
 	 */
 	unsigned int			w_num_folios;
-	struct folio			*w_folios[OCFS2_MAX_CTXT_PAGES];
+	struct folio			**w_folios;
+	struct folio			*w_folios_inline[OCFS2_MAX_CTXT_PAGES];
 	struct folio			*w_target_folio;
 
 	/*
@@ -839,7 +861,17 @@ struct ocfs2_write_ctxt {
 	struct ocfs2_cached_dealloc_ctxt w_dealloc;
 
 	struct list_head		w_unwritten_list;
-	unsigned int			w_unwritten_count;
+
+	/* Direct write only: the dio which owns the unwritten entries. */
+	void				*w_owner;
+
+	/*
+	 * Direct write only: clusters we reserved quota and allocator bits
+	 * for, but which could not be allocated in one go (the allocator
+	 * returned a shorter contiguous chunk).  The write was shortened, the
+	 * caller maps the remainder with its next ->iomap_begin().
+	 */
+	unsigned int			w_clusters_unused;
 };
 
 void ocfs2_unlock_and_free_folios(struct folio **folios, int num_folios)
@@ -883,6 +915,7 @@ static void ocfs2_free_unwritten_list(struct inode *inode,
 {
 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 	struct ocfs2_unwritten_extent *ue = NULL, *tmp = NULL;
+	bool freed = false;
 
 	list_for_each_entry_safe(ue, tmp, head, ue_node) {
 		list_del(&ue->ue_node);
@@ -890,7 +923,27 @@ static void ocfs2_free_unwritten_list(struct inode *inode,
 		list_del(&ue->ue_ip_node);
 		spin_unlock(&oi->ip_lock);
 		kfree(ue);
+		freed = true;
 	}
+
+	/* A direct write may be waiting for these, see ocfs2_dio_wr_map_blocks(). */
+	if (freed)
+		wake_up_all(&oi->ip_unwritten_wq);
+}
+
+static void ocfs2_release_write_ctxt(struct ocfs2_write_ctxt *wc)
+{
+	if (wc->w_desc != wc->w_desc_inline)
+		kvfree(wc->w_desc);
+
+	/*
+	 * The folios in w_folios array already unlocked and
+	 * put by ocfs2_unlock_folios()
+	 */
+	if (wc->w_folios != wc->w_folios_inline)
+		kfree(wc->w_folios);
+
+	kfree(wc);
 }
 
 static void ocfs2_free_write_ctxt(struct inode *inode,
@@ -899,13 +952,22 @@ static void ocfs2_free_write_ctxt(struct inode *inode,
 	ocfs2_free_unwritten_list(inode, &wc->w_unwritten_list);
 	ocfs2_unlock_folios(wc);
 	brelse(wc->w_di_bh);
-	kfree(wc);
+	ocfs2_release_write_ctxt(wc);
 }
 
+/*
+ * TODO, performance improvements:
+ * With 4KB clusters and a 16MB mapping (OCFS2_DIO_MAX_MAP_BYTES),
+ * wc->w_clen is 4096, so every mapping call allocates and frees a 96KB
+ * array under ocfs2_inode_lock() and ip_alloc_sem, and
+ * ocfs2_write_clusters_direct() redundantly loops over wc->w_clen
+ * calling ocfs2_get_clusters() again even when c_new is 0 and
+ * ocfs2_populate_write_desc() already populated c_phys.
+ */
 static int ocfs2_alloc_write_ctxt(struct ocfs2_write_ctxt **wcp,
 				  struct ocfs2_super *osb, loff_t pos,
 				  unsigned len, ocfs2_write_type_t type,
-				  struct buffer_head *di_bh)
+				  struct buffer_head *di_bh, void *owner)
 {
 	u32 cend;
 	struct ocfs2_write_ctxt *wc;
@@ -914,10 +976,46 @@ static int ocfs2_alloc_write_ctxt(struct ocfs2_write_ctxt **wcp,
 	if (!wc)
 		return -ENOMEM;
 
+	wc->w_desc = wc->w_desc_inline;
+	wc->w_folios = wc->w_folios_inline;
+	wc->w_owner = owner;
 	wc->w_cpos = pos >> osb->s_clustersize_bits;
 	wc->w_first_new_cpos = UINT_MAX;
 	cend = (pos + len - 1) >> osb->s_clustersize_bits;
 	wc->w_clen = cend - wc->w_cpos + 1;
+
+	/*
+	 * Only a direct write can span more clusters than fit in a page.
+	 * It needs the folios of the first and of the last cluster at most,
+	 * see ocfs2_grab_folios_for_write().
+	 */
+	if (wc->w_clen > ARRAY_SIZE(wc->w_desc_inline)) {
+		if (WARN_ON_ONCE(type != OCFS2_WRITE_DIRECT)) {
+			ocfs2_release_write_ctxt(wc);
+			return -EINVAL;
+		}
+		wc->w_desc = kvcalloc(wc->w_clen, sizeof(*wc->w_desc),
+				      GFP_NOFS);
+		if (!wc->w_desc) {
+			wc->w_desc = wc->w_desc_inline;
+			ocfs2_release_write_ctxt(wc);
+			return -ENOMEM;
+		}
+	}
+
+	/* ref ocfs2_grab_folios_direct() comments for the logic "2 *" */
+	if (type == OCFS2_WRITE_DIRECT &&
+	    2 * ocfs2_pages_per_cluster(osb->sb) >
+			ARRAY_SIZE(wc->w_folios_inline)) {
+		wc->w_folios = kcalloc(2 * ocfs2_pages_per_cluster(osb->sb),
+				       sizeof(*wc->w_folios), GFP_NOFS);
+		if (!wc->w_folios) {
+			wc->w_folios = wc->w_folios_inline;
+			ocfs2_release_write_ctxt(wc);
+			return -ENOMEM;
+		}
+	}
+
 	get_bh(di_bh);
 	wc->w_di_bh = di_bh;
 	wc->w_type = type;
@@ -1084,7 +1182,85 @@ static int ocfs2_prepare_folio_for_write(struct inode *inode, u64 *p_blkno,
 }
 
 /*
- * This function will only grab one clusters worth of pages.
+ * Grab the folios a direct write has to take care of, w_folios is laid out as
+ * two windows of one cluster's worth of pages each:
+ *
+ *   [0, ppc)    the pages of the first cluster of the write
+ *   [ppc, 2ppc) the pages of the last cluster of the write
+ *
+ * A direct write goes to the disk directly, so the pages inside of the user
+ * range are not touched and stay NULL. The clusters in the middle of the
+ * write are covered by the user range entirely and need nothing at all. Only
+ * the head cluster before the user range and the tail cluster after it can have
+ * pages which are not going to be overwritten, those must be zeroed through the
+ * page cache if the cluster is new or unwritten (c_needs_zero).
+ *
+ * If the write is made of just one cluster, there is only the first window.
+ *
+ * Like for the buffered write, nothing past the end of the file is needed, the
+ * tail is then cut at max(user range end, i_size).
+ */
+static int ocfs2_grab_folios_direct(struct address_space *mapping,
+		struct ocfs2_write_ctxt *wc, loff_t user_pos, unsigned user_len)
+{
+	struct inode *inode = mapping->host;
+	unsigned int ppc = ocfs2_pages_per_cluster(inode->i_sb);
+	unsigned long target_index = user_pos >> PAGE_SHIFT;
+	unsigned long end_index = (user_pos + user_len - 1) >> PAGE_SHIFT;
+	loff_t last_byte = max_t(loff_t, user_pos + user_len,
+				 i_size_read(inode));
+	unsigned long last_index = ((last_byte - 1) >> PAGE_SHIFT) + 1;
+	unsigned int nr_win = wc->w_clen > 1 ? 2 : 1;
+	int ret = 0, win, i;
+
+	wc->w_num_folios = 0;
+
+	for (win = 0; win < nr_win; win++) {
+		struct ocfs2_write_cluster_desc *desc =
+			win ? &wc->w_desc[wc->w_clen - 1] : &wc->w_desc[0];
+		unsigned long start;
+
+		if (!desc->c_needs_zero)
+			continue;
+
+		start = ocfs2_align_clusters_to_page_index(inode->i_sb,
+							    desc->c_cpos);
+
+		for (i = 0; i < ppc; i++) {
+			unsigned long index = start + i;
+			struct folio *folio;
+
+			if (index >= last_index)
+				break;
+
+			/* Track the slots in use, for the unlock/commit loops. */
+			wc->w_num_folios = max_t(unsigned int, wc->w_num_folios,
+						 win * ppc + i + 1);
+
+			/* The direct io target has no page cache page here. */
+			if (index >= target_index && index <= end_index)
+				continue;
+
+			folio = __filemap_get_folio(mapping, index,
+					FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
+					GFP_NOFS);
+			if (IS_ERR(folio)) {
+				ret = PTR_ERR(folio);
+				mlog_errno(ret);
+				goto out;
+			}
+			wc->w_folios[win * ppc + i] = folio;
+			folio_wait_stable(folio);
+		}
+	}
+out:
+	return ret;
+}
+
+/*
+ * This function will only grab one clusters worth of pages, except for a
+ * direct write which gets the pages around the user range of up to two
+ * clusters, see ocfs2_grab_folios_direct().
  */
 static int ocfs2_grab_folios_for_write(struct address_space *mapping,
 		struct ocfs2_write_ctxt *wc, u32 cpos, loff_t user_pos,
@@ -1095,6 +1271,10 @@ static int ocfs2_grab_folios_for_write(struct address_space *mapping,
 	struct inode *inode = mapping->host;
 	loff_t last_byte;
 
+	if (wc->w_type == OCFS2_WRITE_DIRECT)
+		return ocfs2_grab_folios_direct(mapping, wc, user_pos,
+						user_len);
+
 	target_index = user_pos >> PAGE_SHIFT;
 
 	/*
@@ -1146,11 +1326,6 @@ static int ocfs2_grab_folios_for_write(struct address_space *mapping,
 			folio_get(mmap_folio);
 			wc->w_folios[i] = mmap_folio;
 			wc->w_target_locked = true;
-		} else if (index >= target_index && index <= end_index &&
-			   wc->w_type == OCFS2_WRITE_DIRECT) {
-			/* Direct write has no mapping page. */
-			wc->w_folios[i] = NULL;
-			continue;
 		} else {
 			wc->w_folios[i] = __filemap_get_folio(mapping, index,
 					FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
@@ -1173,6 +1348,61 @@ static int ocfs2_grab_folios_for_write(struct address_space *mapping,
 	return ret;
 }
 
+/*
+ * Get the physical location of a cluster and prepare the folios [fstart, fend)
+ * of w_folios, which belong to it, for the write.
+ */
+static int ocfs2_prepare_cluster_folios(struct address_space *mapping,
+					u32 *phys, unsigned int should_zero,
+					struct ocfs2_write_ctxt *wc, u32 cpos,
+					loff_t user_pos, unsigned user_len,
+					unsigned int fstart, unsigned int fend)
+{
+	int ret, i;
+	u64 p_blkno;
+	struct inode *inode = mapping->host;
+	int bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
+
+	/*
+	 * The only reason this should fail is due to an inability to
+	 * find the extent added.
+	 */
+	ret = ocfs2_get_clusters(inode, cpos, phys, NULL, NULL);
+	if (ret < 0) {
+		mlog(ML_ERROR, "Get physical blkno failed for inode %llu, "
+			    "at logical cluster %u",
+			    (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos);
+		return ret;
+	}
+
+	BUG_ON(*phys == 0);
+
+	p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, *phys);
+	if (!should_zero)
+		p_blkno += (user_pos >> inode->i_sb->s_blocksize_bits) & (u64)(bpc - 1);
+
+	for (i = fstart; i < fend; i++) {
+		int tmpret;
+
+		/* This is the direct io target page. */
+		if (wc->w_folios[i] == NULL) {
+			p_blkno += (1 << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits));
+			continue;
+		}
+
+		tmpret = ocfs2_prepare_folio_for_write(inode, &p_blkno, wc,
+				wc->w_folios[i], cpos, user_pos, user_len,
+				should_zero);
+		if (tmpret) {
+			mlog_errno(tmpret);
+			if (ret == 0)
+				ret = tmpret;
+		}
+	}
+
+	return ret;
+}
+
 /*
  * Prepare a single cluster for write one cluster into the file.
  */
@@ -1185,11 +1415,9 @@ static int ocfs2_write_cluster(struct address_space *mapping,
 			       struct ocfs2_write_ctxt *wc, u32 cpos,
 			       loff_t user_pos, unsigned user_len)
 {
-	int ret, i;
-	u64 p_blkno;
+	int ret;
 	struct inode *inode = mapping->host;
 	struct ocfs2_extent_tree et;
-	int bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
 
 	if (new) {
 		u32 tmp_pos;
@@ -1231,52 +1459,176 @@ static int ocfs2_write_cluster(struct address_space *mapping,
 		}
 	}
 
+	ret = ocfs2_prepare_cluster_folios(mapping, phys, should_zero, wc, cpos,
+					   user_pos, user_len, 0,
+					   wc->w_num_folios);
+
 	/*
-	 * The only reason this should fail is due to an inability to
-	 * find the extent added.
+	 * We only have cleanup to do in case of allocating write.
 	 */
-	ret = ocfs2_get_clusters(inode, cpos, phys, NULL, NULL);
+	if (ret && new)
+		ocfs2_write_failure(inode, wc, user_pos, user_len);
+
+out:
+
+	return ret;
+}
+
+/*
+ * A direct write allocates all the clusters it needs in one go, the same way
+ * ocfs2_extend_allocation() does.  The new extent is unwritten, it is converted
+ * when the io is done, see ocfs2_dio_end_io_write().
+ *
+ * Only one call is made, which means one chunk of contiguous clusters.  The
+ * allocator may return less than we asked for.  We don't try again, that would
+ * need more credits and the chunks would not be contiguous on the disk, which
+ * the caller needs as it hands out a single mapping.  The write is just made
+ * shorter, the caller maps the rest with its next ->iomap_begin().
+ */
+static int ocfs2_dio_alloc_clusters(struct inode *inode,
+				    struct ocfs2_write_ctxt *wc,
+				    struct ocfs2_alloc_context *data_ac,
+				    struct ocfs2_alloc_context *meta_ac)
+{
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	unsigned int ppc = ocfs2_pages_per_cluster(inode->i_sb);
+	enum ocfs2_alloc_restarted why = RESTART_NONE;
+	u32 cpos = wc->w_cpos, got;
+	int ret, i;
+
+	ret = ocfs2_add_inode_data(osb, inode, &cpos, wc->w_clen, 1,
+				   wc->w_di_bh, wc->w_handle, data_ac, meta_ac,
+				   &why);
+	got = cpos - wc->w_cpos;
+	if (ret == -EAGAIN && why == RESTART_TRANS && got)
+		ret = 0;
+	if (ret == -EAGAIN) {
+		/*
+		 * We reserved the metadata for it up front, we do not
+		 * expect to be here.
+		 */
+		mlog(ML_ERROR, "Inode %llu: EAGAIN (%d) during dio allocation\n",
+		     (unsigned long long)OCFS2_I(inode)->ip_blkno, why);
+		ret = -ENOSPC;
+	}
 	if (ret < 0) {
-		mlog(ML_ERROR, "Get physical blkno failed for inode %llu, "
-			    "at logical cluster %u",
-			    (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos);
-		goto out;
+		if (ret != -ENOSPC)
+			mlog_errno(ret);
+		return ret;
 	}
 
-	BUG_ON(*phys == 0);
-
-	p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, *phys);
-	if (!should_zero)
-		p_blkno += (user_pos >> inode->i_sb->s_blocksize_bits) & (u64)(bpc - 1);
+	if (got < wc->w_clen) {
+		/*
+		 * Cut the write short.  What is left of it is not for us to
+		 * zero anymore, the last cluster we have now is covered by the
+		 * user range entirely.  Drop the folios of the old last
+		 * cluster.
+		 */
+		wc->w_clusters_unused = wc->w_clen - got;
+		wc->w_clen = got;
 
-	for (i = 0; i < wc->w_num_folios; i++) {
-		int tmpret;
+		for (i = ppc; i < 2 * ppc; i++) {
+			struct folio *folio = wc->w_folios[i];
 
-		/* This is the direct io target page. */
-		if (wc->w_folios[i] == NULL) {
-			p_blkno += (1 << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits));
-			continue;
+			if (!folio)
+				continue;
+			folio_unlock(folio);
+			folio_mark_accessed(folio);
+			folio_put(folio);
+			wc->w_folios[i] = NULL;
 		}
+		if (wc->w_num_folios > ppc)
+			wc->w_num_folios = ppc;
+	}
 
-		tmpret = ocfs2_prepare_folio_for_write(inode, &p_blkno, wc,
-				wc->w_folios[i], cpos, user_pos, user_len,
-				should_zero);
-		if (tmpret) {
-			mlog_errno(tmpret);
-			if (ret == 0)
-				ret = tmpret;
+	return 0;
+}
+
+/*
+ * A direct write goes to the disk, it only needs the clusters allocated, the
+ * folios around the user range zeroed and the physical location of each
+ * cluster.  The latter is what the iomap mapping is made of.
+ */
+static int ocfs2_write_clusters_direct(struct address_space *mapping,
+				       struct ocfs2_alloc_context *data_ac,
+				       struct ocfs2_alloc_context *meta_ac,
+				       struct ocfs2_write_ctxt *wc,
+				       loff_t pos, unsigned len)
+{
+	struct inode *inode = mapping->host;
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	unsigned int ppc = ocfs2_pages_per_cluster(inode->i_sb);
+	struct ocfs2_write_cluster_desc *desc;
+	loff_t end = pos + len;
+	int ret, i, win;
+	u32 phys, num;
+
+	if (wc->w_desc[0].c_new) {
+		ret = ocfs2_dio_alloc_clusters(inode, wc, data_ac, meta_ac);
+		if (ret)
+			return ret;
+		end = min_t(loff_t, end,
+			    ocfs2_clusters_to_bytes(inode->i_sb,
+						    wc->w_cpos + wc->w_clen));
+	}
+
+	/*
+	 * Fill in the physical location of the clusters, an extent covers as
+	 * many of them as it can.
+	 */
+	for (i = 0; i < wc->w_clen; ) {
+		desc = &wc->w_desc[i];
+
+		ret = ocfs2_get_clusters(inode, desc->c_cpos, &phys, &num,
+					 NULL);
+		if (ret) {
+			mlog_errno(ret);
+			return ret;
+		}
+		if (!phys) {
+			mlog(ML_ERROR, "Inode %llu: no cluster at %u after dio allocation\n",
+			     (unsigned long long)OCFS2_I(inode)->ip_blkno,
+			     desc->c_cpos);
+			return -EIO;
 		}
+		for (; num && i < wc->w_clen; i++, num--, phys++)
+			wc->w_desc[i].c_phys = phys;
 	}
 
 	/*
-	 * We only have cleanup to do in case of allocating write.
+	 * The folios are only there for the first and the last cluster,
+	 * the ones in the middle are written by the dio as a whole.
 	 */
-	if (ret && new)
-		ocfs2_write_failure(inode, wc, user_pos, user_len);
+	for (win = 0; win < (wc->w_clen > 1 ? 2 : 1); win++) {
+		unsigned int fstart = win * ppc;
+		unsigned int fend = min(wc->w_num_folios, fstart + ppc);
+		loff_t cpos_byte;
+		unsigned int local_len;
+		loff_t user_pos;
+
+		desc = win ? &wc->w_desc[wc->w_clen - 1] : &wc->w_desc[0];
+		if (!desc->c_needs_zero || fend <= fstart)
+			continue;
 
-out:
+		/* The part of the user range which is in this cluster. */
+		cpos_byte = ocfs2_clusters_to_bytes(inode->i_sb, desc->c_cpos);
+		user_pos = max_t(loff_t, pos, cpos_byte);
+		local_len = min_t(loff_t, end,
+				  cpos_byte + osb->s_clustersize) - user_pos;
 
-	return ret;
+		ret = ocfs2_prepare_cluster_folios(mapping, &desc->c_phys,
+						   desc->c_needs_zero, wc,
+						   desc->c_cpos, user_pos,
+						   local_len, fstart, fend);
+		if (ret) {
+			mlog_errno(ret);
+			if (desc->c_new)
+				ocfs2_write_failure(inode, wc, pos, len);
+			return ret;
+		}
+	}
+
+	return 0;
 }
 
 static int ocfs2_write_cluster_by_desc(struct address_space *mapping,
@@ -1291,6 +1643,10 @@ static int ocfs2_write_cluster_by_desc(struct address_space *mapping,
 	struct ocfs2_write_cluster_desc *desc;
 	struct ocfs2_super *osb = OCFS2_SB(mapping->host->i_sb);
 
+	if (wc->w_type == OCFS2_WRITE_DIRECT)
+		return ocfs2_write_clusters_direct(mapping, data_ac, meta_ac,
+						   wc, pos, len);
+
 	for (i = 0; i < wc->w_clen; i++) {
 		desc = &wc->w_desc[i];
 
@@ -1375,67 +1731,174 @@ static void ocfs2_set_target_boundaries(struct ocfs2_super *osb,
 	}
 }
 
+/*
+ * Find the entry which covers a cluster.  Must be called with ip_lock held.
+ */
+static struct ocfs2_unwritten_extent *
+ocfs2_find_unwritten(struct ocfs2_inode_info *oi, u32 cpos)
+{
+	struct ocfs2_unwritten_extent *ue;
+
+	list_for_each_entry(ue, &oi->ip_unwritten_list, ue_ip_node) {
+		if (cpos >= ue->ue_cpos && cpos - ue->ue_cpos < ue->ue_clusters)
+			return ue;
+	}
+	return NULL;
+}
+
 /*
  * Check if this extent is marked UNWRITTEN by direct io. If so, we need not to
  * do the zero work. And should not to clear UNWRITTEN since it will be cleared
  * by the direct io procedure.
- * If this is a new extent that allocated by direct io, we should mark it in
- * the ip_unwritten_list.
+ *
+ * A direct write never clears UNWRITTEN here, that is done when its io is
+ * finished. The clusters it is going to zero are not put to the
+ * ip_unwritten_list by this function, see ocfs2_dio_add_unwritten(), as the
+ * write might get shortened afterwards.
+ *
+ * TODO:
+ * Buffered writes or mmap page_mkwrite faults clear c_needs_zero and
+ * c_clear_unwritten, relying on the in-flight direct write to zero the cluster
+ * and convert the extent. If the direct write fails after
+ * ocfs2_dio_wr_map_blocks() drops ip_alloc_sem and ocfs2_inode_lock() before
+ * user pages are pinned or bios are submitted or rw_lock, they will lose data
+ * or expose uninitialized disk blocks.
  */
-static int ocfs2_unwritten_check(struct inode *inode,
-				 struct ocfs2_write_ctxt *wc,
-				 struct ocfs2_write_cluster_desc *desc)
+static void ocfs2_unwritten_check_locked(struct inode *inode,
+					 struct ocfs2_write_ctxt *wc,
+					 struct ocfs2_write_cluster_desc *desc)
 {
 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
-	struct ocfs2_unwritten_extent *ue = NULL, *new = NULL;
-	int ret = 0;
+	struct ocfs2_unwritten_extent *ue;
 
 	if (!desc->c_needs_zero)
-		return 0;
+		return;
 
-retry:
-	spin_lock(&oi->ip_lock);
-	/* Needs not to zero no metter buffer or direct. The one who is zero
-	 * the cluster is doing zero. And he will clear unwritten after all
-	 * cluster io finished. */
-	list_for_each_entry(ue, &oi->ip_unwritten_list, ue_ip_node) {
-		if (desc->c_cpos == ue->ue_cpos) {
-			BUG_ON(desc->c_new);
-			desc->c_needs_zero = 0;
-			desc->c_clear_unwritten = 0;
-			goto unlock;
-		}
+	ue = ocfs2_find_unwritten(oi, desc->c_cpos);
+	/* A hole (c_new is 1) can not be on the list, don't trust it if it is. */
+	if (ue && !WARN_ON_ONCE(desc->c_new)) {
+		/*
+		 * Needs not to zero no matter buffer or direct. The one who is
+		 * zero the cluster is doing zero. And he will clear unwritten
+		 * after all cluster io finished.
+		 */
+		desc->c_needs_zero = 0;
+		desc->c_clear_unwritten = 0;
+	} else if (wc->w_type == OCFS2_WRITE_DIRECT) {
+		/* This direct write will doing zero. */
+		desc->c_clear_unwritten = 0;
 	}
-
-	if (wc->w_type != OCFS2_WRITE_DIRECT)
-		goto unlock;
-
-	if (new == NULL) {
-		spin_unlock(&oi->ip_lock);
-		new = kmalloc_obj(struct ocfs2_unwritten_extent, GFP_NOFS);
-		if (new == NULL) {
-			ret = -ENOMEM;
-			goto out;
-		}
-		goto retry;
-	}
-	/* This direct write will doing zero. */
-	new->ue_cpos = desc->c_cpos;
-	new->ue_phys = desc->c_phys;
-	desc->c_clear_unwritten = 0;
-	list_add_tail(&new->ue_ip_node, &oi->ip_unwritten_list);
-	list_add_tail(&new->ue_node, &wc->w_unwritten_list);
-	wc->w_unwritten_count++;
-	new = NULL;
-unlock:
-	spin_unlock(&oi->ip_lock);
-out:
-	kfree(new);
-	return ret;
 }
 
 /*
- * Populate each single-cluster write descriptor in the write context
+ * Is the cluster reported as unwritten to iomap?
+ * Returns true for unwritten, false for mapped.
+ */
+static inline bool ocfs2_desc_dio_unwritten(struct ocfs2_write_cluster_desc *d)
+{
+	/*
+	 * c_needs_zero: whether this mapping needs to be zeroed
+	 * c_dio_unwritten: whether the conversion is my job
+	 *
+	 * c_needs_zero | c_dio_unwritten | source place             | reports
+	 * ----------------------------------------------------------------
+	 *     0        |      0          | written extent           | MAPPED
+	 *              |                 | (a direct write never    |
+	 *              |                 | sees an unwritten one    |
+	 *              |                 | owned by another dio, it |
+	 *              |                 | waits for it first)      |
+	 * ------------------------------------------------------------------
+	 *     1        |      0          | buffered/mmap write;     | UNWRITTEN
+	 *              |                 | transitional state before|
+	 *              |                 | ocfs2_dio_add_unwritten  |
+	 * ------------------------------------------------------------------
+	 *     0        |      1          | unwritten check          | UNWRITTEN
+	 *              |                 | found its own entry      |
+	 * ------------------------------------------------------------------
+	 *     1        |      1          | ocfs2_dio_add_unwritten  | UNWRITTEN
+	 */
+	return d->c_needs_zero || d->c_dio_unwritten;
+}
+
+/*
+ * iomap takes one mapping which is of one type and contiguous on the disk.
+ * Cut the clusters of a direct write at the first one which is not like the
+ * first, they are mapped by the next ->iomap_begin().  Also, the clusters to
+ * be allocated are all new or none of them is.
+ *
+ * Returns the number of clusters to be allocated.
+ */
+static unsigned int ocfs2_dio_trim_write_ctxt(struct ocfs2_write_ctxt *wc)
+{
+	struct ocfs2_write_cluster_desc *first = &wc->w_desc[0];
+	u32 i;
+
+	for (i = 1; i < wc->w_clen; i++) {
+		struct ocfs2_write_cluster_desc *d = &wc->w_desc[i];
+
+		if (d->c_new != first->c_new ||
+		    ocfs2_desc_dio_unwritten(d) !=
+				ocfs2_desc_dio_unwritten(first))
+			break;
+		/* mapped clusters */
+		if (!d->c_new && d->c_phys != d[-1].c_phys + 1)
+			break;
+	}
+	wc->w_clen = i;
+
+	/*
+	 * c_new is 0 for mapped clusters, which means they are not
+	 * allocated by this write.
+	 */
+	return first->c_new ? wc->w_clen : 0;
+}
+
+/*
+ * Record the clusters a direct write zeroed (or is going to convert) in
+ * ip_unwritten_list, until ocfs2_dio_end_io_write() converts them.  The
+ * entries are also on wc->w_unwritten_list, so that they are freed with the
+ * write context if the write fails. Once the write has succeeded, the caller
+ * detaches them from it, see ocfs2_dio_detach_unwritten().
+ */
+static int ocfs2_dio_add_unwritten(struct inode *inode,
+				   struct ocfs2_write_ctxt *wc)
+{
+	struct ocfs2_inode_info *oi = OCFS2_I(inode);
+	struct ocfs2_unwritten_extent *ue;
+	u32 i, j;
+
+	for (i = 0; i < wc->w_clen; i = j) {
+		j = i + 1;
+		if (!wc->w_desc[i].c_needs_zero)
+			continue;
+		while (j < wc->w_clen && wc->w_desc[j].c_needs_zero)
+			j++;
+
+		ue = kmalloc_obj(struct ocfs2_unwritten_extent, GFP_NOFS);
+		if (!ue)
+			return -ENOMEM;
+		ue->ue_cpos = wc->w_desc[i].c_cpos;
+		ue->ue_clusters = j - i;
+		ue->ue_owner = wc->w_owner;
+		INIT_LIST_HEAD(&ue->ue_ip_node);
+		list_add_tail(&ue->ue_node, &wc->w_unwritten_list);
+	}
+
+	spin_lock(&oi->ip_lock);
+	list_for_each_entry(ue, &wc->w_unwritten_list, ue_node)
+		list_add_tail(&ue->ue_ip_node, &oi->ip_unwritten_list);
+	spin_unlock(&oi->ip_lock);
+
+	for (i = 0; i < wc->w_clen; i++) {
+		if (wc->w_desc[i].c_needs_zero)
+			wc->w_desc[i].c_dio_unwritten = 1;
+	}
+
+	return 0;
+}
+
+/*
+ * Populate each single-cluster write descriptor in the write context
  * with information about the i/o to be done.
  *
  * Returns the number of clusters that will have to be allocated, as
@@ -1518,15 +1981,19 @@ static int ocfs2_populate_write_desc(struct inode *inode,
 			desc->c_needs_zero = 1;
 		}
 
-		ret = ocfs2_unwritten_check(inode, wc, desc);
-		if (ret) {
-			mlog_errno(ret);
-			goto out;
-		}
-
 		num_clusters--;
 	}
 
+	/*
+	 * One ip_lock hold for the whole range.  A direct write can span
+	 * thousands of clusters and taking the lock per cluster costs a
+	 * round trip each.
+	 */
+	spin_lock(&OCFS2_I(inode)->ip_lock);
+	for (i = 0; i < wc->w_clen; i++)
+		ocfs2_unwritten_check_locked(inode, wc, &wc->w_desc[i]);
+	spin_unlock(&OCFS2_I(inode)->ip_lock);
+
 	ret = 0;
 out:
 	return ret;
@@ -1707,10 +2174,57 @@ static int ocfs2_zero_tail(struct inode *inode, struct buffer_head *di_bh,
 	return ret;
 }
 
+/*
+ * Does a direct write have folios to zero around its user range?
+ * See ocfs2_grab_folios_direct(), this has to agree with it.
+ */
+static bool ocfs2_dio_need_zero_folios(struct inode *inode,
+				       struct ocfs2_write_ctxt *wc,
+				       loff_t pos, unsigned len)
+{
+	unsigned int ppc = ocfs2_pages_per_cluster(inode->i_sb);
+	unsigned long target_index = pos >> PAGE_SHIFT;
+	unsigned long end_index = (pos + len - 1) >> PAGE_SHIFT;
+	loff_t last_byte = max_t(loff_t, pos + len, i_size_read(inode));
+	unsigned long last_index = ((last_byte - 1) >> PAGE_SHIFT) + 1;
+	unsigned int nr_win = wc->w_clen > 1 ? 2 : 1;
+	int win, i;
+
+	for (win = 0; win < nr_win; win++) {
+		struct ocfs2_write_cluster_desc *desc =
+			win ? &wc->w_desc[wc->w_clen - 1] : &wc->w_desc[0];
+		unsigned long start;
+
+		if (!desc->c_needs_zero)
+			continue;
+
+		start = ocfs2_align_clusters_to_page_index(inode->i_sb,
+							    desc->c_cpos);
+		for (i = 0; i < ppc && start + i < last_index; i++) {
+			if (start + i < target_index || start + i > end_index)
+				return true;
+		}
+	}
+	return false;
+}
+
+/*
+ * A buffered write is cut by the caller into pieces of up to a page, and the
+ * clusters it touches have to fit in a page.
+ *
+ * A direct write is not, it may span many clusters, which are all of the same
+ * kind: all of them are to be allocated or none is, and either all of them are
+ * unwritten or none is.  How many of the clusters asked for are used is up to
+ * this function, see w_clen of the returned context.
+ *
+ * @owner is only used by a direct write, it is what ocfs2_dio_end_io_write()
+ * finds the unwritten clusters recorded for this write by.
+ */
 int ocfs2_write_begin_nolock(struct address_space *mapping,
 		loff_t pos, unsigned len, ocfs2_write_type_t type,
 		struct folio **foliop, void **fsdata,
-		struct buffer_head *di_bh, struct folio *mmap_folio)
+		struct buffer_head *di_bh, struct folio *mmap_folio,
+		void *owner, loff_t *touched_end)
 {
 	int ret, cluster_of_pages, credits = OCFS2_INODE_UPDATE_CREDITS;
 	unsigned int clusters_to_alloc, extents_to_split, clusters_need = 0;
@@ -1723,15 +2237,21 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 	handle_t *handle;
 	struct ocfs2_extent_tree et;
 	int try_free = 1, ret1;
+	u32 prev_clusters, added;
+
+	/* Nothing of ours is in the page cache until the clusters are written. */
+	if (touched_end)
+		*touched_end = pos;
 
 try_again:
-	ret = ocfs2_alloc_write_ctxt(&wc, osb, pos, len, type, di_bh);
+	ret = ocfs2_alloc_write_ctxt(&wc, osb, pos, len, type, di_bh, owner);
 	if (ret) {
 		mlog_errno(ret);
 		return ret;
 	}
 
-	if (ocfs2_supports_inline_data(osb)) {
+	/* A direct write is never inline, it is not even allowed to start. */
+	if (type != OCFS2_WRITE_DIRECT && ocfs2_supports_inline_data(osb)) {
 		ret = ocfs2_try_to_write_inline_data(mapping, inode, pos, len,
 						     mmap_folio, wc);
 		if (ret == 1) {
@@ -1744,7 +2264,7 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 		}
 	}
 
-	/* Direct io change i_size late, should not zero tail here. */
+	/* Direct io change i_size itself, should not zero tail here. */
 	if (type != OCFS2_WRITE_DIRECT) {
 		if (ocfs2_sparse_alloc(osb))
 			ret = ocfs2_zero_tail(inode, di_bh, pos);
@@ -1777,6 +2297,18 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 		mlog_errno(ret);
 		goto out;
 	}
+
+	if (type == OCFS2_WRITE_DIRECT) {
+		/*
+		 * Direct write never splits an extent here, they are converted
+		 * when the io is done. What it can do is to allocate.
+		 */
+		extents_to_split = 0;
+		clusters_to_alloc = ocfs2_dio_trim_write_ctxt(wc);
+		len = min_t(loff_t, len,
+			    ocfs2_clusters_to_bytes(inode->i_sb,
+						    wc->w_cpos + wc->w_clen) - pos);
+	}
 	clusters_need += clusters_to_alloc;
 
 	di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
@@ -1796,15 +2328,22 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 	 */
 	if (clusters_to_alloc || extents_to_split) {
 		/*
-		 * XXX: We are stretching the limits of
-		 * ocfs2_lock_allocators(). It greatly over-estimates
-		 * the work to be done.
+		 * A direct write gets all its clusters from one
+		 * ocfs2_add_inode_data() call, which adds at most one
+		 * extent record.  A buffered write adds one record per
+		 * cluster and may have to split unwritten extents.
 		 */
 		ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode),
 					      wc->w_di_bh);
-		ret = ocfs2_lock_allocators(inode, &et,
-					    clusters_to_alloc, extents_to_split,
-					    &data_ac, &meta_ac);
+		if (type == OCFS2_WRITE_DIRECT)
+			ret = ocfs2_lock_allocators_dio(inode, &et,
+							clusters_to_alloc,
+							&data_ac, &meta_ac);
+		else
+			ret = ocfs2_lock_allocators(inode, &et,
+						    clusters_to_alloc,
+						    extents_to_split,
+						    &data_ac, &meta_ac);
 		if (ret) {
 			mlog_errno(ret);
 			goto out;
@@ -1815,13 +2354,24 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 
 		credits = ocfs2_calc_extend_credits(inode->i_sb,
 						    &di->id2.i_list);
-	} else if (type == OCFS2_WRITE_DIRECT)
-		/* direct write needs not to start trans if no extents alloc. */
-		goto success;
+	} else if (type == OCFS2_WRITE_DIRECT) {
+		/*
+		 * Direct write needs not to start trans if no extents alloc,
+		 * unless there are folios to zero.
+		 */
+		if (!ocfs2_dio_need_zero_folios(inode, wc, pos, len)) {
+			ret = ocfs2_dio_add_unwritten(inode, wc);
+			if (ret) {
+				mlog_errno(ret);
+				goto out;
+			}
+			goto success;
+		}
+	}
 
 	/*
 	 * We have to zero sparse allocated clusters, unwritten extent clusters,
-	 * and non-sparse clusters we just extended.  For non-sparse writes,
+	 * and non-sparse clusters we just extended. For non-sparse writes,
 	 * we know zeros will only be needed in the first and/or last cluster.
 	 */
 	if (wc->w_clen && (wc->w_desc[0].c_needs_zero ||
@@ -1841,6 +2391,14 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 
 	wc->w_handle = handle;
 
+	/*
+	 * Nobody else changes the clusters of the inode while we hold
+	 * ip_alloc_sem, what has been added since is ours.
+	 */
+	spin_lock(&OCFS2_I(inode)->ip_lock);
+	prev_clusters = OCFS2_I(inode)->ip_clusters;
+	spin_unlock(&OCFS2_I(inode)->ip_lock);
+
 	if (clusters_to_alloc) {
 		ret = dquot_alloc_space_nodirty(inode,
 			ocfs2_clusters_to_bytes(osb->sb, clusters_to_alloc));
@@ -1881,11 +2439,34 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 
 	ret = ocfs2_write_cluster_by_desc(mapping, data_ac, meta_ac, wc, pos,
 					  len);
+	if (wc->w_clusters_unused) {
+		/* A direct write got a shorter chunk than reserved. */
+		dquot_free_space(inode,
+			ocfs2_clusters_to_bytes(osb->sb, wc->w_clusters_unused));
+		clusters_to_alloc -= wc->w_clusters_unused;
+		wc->w_clusters_unused = 0;
+	}
+	/*
+	 * w_clen is final now, so this is the range whose head and tail
+	 * folios may have been zeroed, whether or not the write succeeded.
+	 * The caller needs it to clean up behind the locks.
+	 */
+	if (touched_end)
+		*touched_end = ocfs2_clusters_to_bytes(inode->i_sb,
+						       wc->w_cpos + wc->w_clen);
 	if (ret) {
 		mlog_errno(ret);
 		goto out_quota;
 	}
 
+	if (type == OCFS2_WRITE_DIRECT) {
+		ret = ocfs2_dio_add_unwritten(inode, wc);
+		if (ret) {
+			mlog_errno(ret);
+			goto out_quota;
+		}
+	}
+
 	if (data_ac)
 		ocfs2_free_alloc_context(data_ac);
 	if (meta_ac)
@@ -1897,9 +2478,17 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 	*fsdata = wc;
 	return 0;
 out_quota:
-	if (clusters_to_alloc)
+	/*
+	 * Give back the quota of the clusters which were not allocated. Those
+	 * which already are in the extent tree stay, and so does their quota.
+	 */
+	spin_lock(&OCFS2_I(inode)->ip_lock);
+	added = OCFS2_I(inode)->ip_clusters - prev_clusters;
+	spin_unlock(&OCFS2_I(inode)->ip_lock);
+	if (clusters_to_alloc > added)
 		dquot_free_space(inode,
-			  ocfs2_clusters_to_bytes(osb->sb, clusters_to_alloc));
+			ocfs2_clusters_to_bytes(osb->sb,
+				clusters_to_alloc - added));
 out_commit:
 	ocfs2_commit_trans(osb, handle);
 
@@ -1968,7 +2557,7 @@ static int ocfs2_write_begin(const struct kiocb *iocb,
 	down_write(&OCFS2_I(inode)->ip_alloc_sem);
 
 	ret = ocfs2_write_begin_nolock(mapping, pos, len, OCFS2_WRITE_BUFFER,
-				       foliop, fsdata, di_bh, NULL);
+				       foliop, fsdata, di_bh, NULL, NULL, NULL);
 	if (ret) {
 		mlog_errno(ret);
 		goto out_fail;
@@ -2110,11 +2699,18 @@ int ocfs2_write_end_nolock(struct address_space *mapping, loff_t pos,
 		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
 		di->i_mtime = di->i_ctime = cpu_to_le64(inode_get_mtime_sec(inode));
 		di->i_mtime_nsec = di->i_ctime_nsec = cpu_to_le32(inode_get_mtime_nsec(inode));
-		if (handle)
-			ocfs2_update_inode_fsync_trans(handle, inode, 1);
+	} else if (wc->w_type == OCFS2_WRITE_DIRECT) {
+		/*
+		 * Direct io does not update i_size here, but a hole allocation
+		 * changed ip_clusters.  Record the transaction which allocated
+		 * and zeroed the clusters so O_DSYNC / fsync waits for it.
+		 */
+		inode->i_blocks = ocfs2_inode_sector_count(inode);
 	}
-	if (handle)
+	if (handle) {
+		ocfs2_update_inode_fsync_trans(handle, inode, 1);
 		ocfs2_journal_dirty(handle, wc->w_di_bh);
+	}
 
 out:
 	/* unlock pages before dealloc since it needs acquiring j_trans_barrier
@@ -2130,7 +2726,7 @@ int ocfs2_write_end_nolock(struct address_space *mapping, loff_t pos,
 	ocfs2_run_deallocs(osb, &wc->w_dealloc);
 
 	brelse(wc->w_di_bh);
-	kfree(wc);
+	ocfs2_release_write_ctxt(wc);
 
 	return copied;
 }
@@ -2151,9 +2747,222 @@ static int ocfs2_write_end(const struct kiocb *iocb,
 	return ret;
 }
 
+/*
+ * Convert the unwritten extents of a direct write, which is finished,
+ * and change the file size if it has been extended.
+ *
+ * @head are the clusters the write has zeroed or allocated, recorded by
+ * ocfs2_dio_wr_map_blocks(). Those which are not covered by the data
+ * written, [offset, offset + bytes), are left unwritten.
+ */
+static int ocfs2_dio_end_io_write(struct inode *inode,
+				  loff_t offset,
+				  ssize_t bytes,
+				  struct list_head *head)
+{
+	struct ocfs2_cached_dealloc_ctxt dealloc;
+	struct ocfs2_extent_tree et;
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	struct ocfs2_inode_info *oi = OCFS2_I(inode);
+	struct ocfs2_unwritten_extent *ue;
+	struct buffer_head *di_bh = NULL;
+	struct ocfs2_dinode *di;
+	struct ocfs2_alloc_context *data_ac = NULL;
+	struct ocfs2_alloc_context *meta_ac = NULL;
+	handle_t *handle = NULL;
+	loff_t end = offset + bytes;
+	int ret = 0, credits = 0, batch = 0, pass;
+	u32 first_cpos, last_cpos;
+	u32 extents_to_split = 0;
+
+	first_cpos = offset >> osb->s_clustersize_bits;
+	last_cpos = ocfs2_clusters_for_bytes(inode->i_sb, end);
+
+	ocfs2_init_dealloc_ctxt(&dealloc);
+
+	ret = ocfs2_inode_lock(inode, &di_bh, 1);
+	if (ret < 0) {
+		mlog_errno(ret);
+		goto out;
+	}
+
+	down_write(&oi->ip_alloc_sem);
+	di = (struct ocfs2_dinode *)di_bh->b_data;
+
+	ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), di_bh);
+
+	/*
+	 * Attach dealloc with extent tree in case that we may reuse extents
+	 * which are already unlinked from current extent tree due to extent
+	 * rotation and merging.
+	 */
+	et.et_dealloc = &dealloc;
+
+	/*
+	 * Two passes over the clusters which are recorded: the first one
+	 * counts the unwritten extents, the allocators we need depend on
+	 * it. The second one converts them.
+	 */
+	for (pass = 0; pass < 2; pass++) {
+		list_for_each_entry(ue, head, ue_node) {
+			u32 cpos = max(ue->ue_cpos, first_cpos);
+			u32 cend = min(ue->ue_cpos + ue->ue_clusters, last_cpos);
+
+			while (cpos < cend) {
+				unsigned int ext_flags;
+				u32 phys, num;
+
+				/*
+				 * Bypass the extent map cache: it merges
+				 * adjacent on-disk records, and
+				 * ocfs2_mark_extent_written() below works on
+				 * one record at a time.
+				 */
+				ret = ocfs2_get_clusters_uncached(inode, cpos,
+								  &phys, &num,
+								  &ext_flags);
+				if (ret < 0) {
+					mlog_errno(ret);
+					goto commit;
+				}
+				num = min(num, cend - cpos);
+				if (WARN_ON_ONCE(!num)) {
+					ret = -EIO;
+					goto commit;
+				}
+
+				if (!phys || !(ext_flags & OCFS2_EXT_UNWRITTEN)) {
+					cpos += num;
+					continue;
+				}
+
+				if (pass == 0) {
+					extents_to_split++;
+					cpos += num;
+					continue;
+				}
+
+				/* pass == 1 */
+				if (!handle) {
+					handle = ocfs2_start_trans(osb, credits);
+					if (IS_ERR(handle)) {
+						ret = PTR_ERR(handle);
+						handle = NULL;
+						mlog_errno(ret);
+						goto unlock;
+					}
+					ret = ocfs2_journal_access_di(handle,
+						INODE_CACHE(inode), di_bh,
+						OCFS2_JOURNAL_ACCESS_WRITE);
+					if (ret) {
+						mlog_errno(ret);
+						goto commit;
+					}
+				}
+				ret = ocfs2_assure_trans_credits(handle, credits);
+				if (ret < 0) {
+					mlog_errno(ret);
+					goto commit;
+				}
+
+				ret = ocfs2_mark_extent_written(inode, &et,
+						handle, cpos, num, phys,
+						meta_ac, &dealloc);
+				if (ret < 0) {
+					mlog_errno(ret);
+					goto commit;
+				}
+				cpos += num;
+
+				if (++batch == OCFS2_DIO_MARK_EXTENT_BATCH) {
+					ocfs2_update_inode_fsync_trans(handle,
+								       inode, 1);
+					ocfs2_commit_trans(osb, handle);
+					handle = NULL;
+					batch = 0;
+				}
+			}
+		}
+
+		if (pass == 0) {
+			if (extents_to_split) {
+				ret = ocfs2_lock_allocators(inode, &et, 0,
+						extents_to_split,
+						&data_ac, &meta_ac);
+				if (ret) {
+					mlog_errno(ret);
+					goto unlock;
+				}
+			}
+			credits = ocfs2_calc_extend_credits(inode->i_sb,
+							    &di->id2.i_list);
+		}
+	}
+
+	/*
+	 * The conversion itself does not change the cluster count, but an
+	 * allocation done in write_begin/write_end may not have refreshed
+	 * i_blocks.  ocfs2_set_inode_size() does it for an extending write;
+	 * do it here for the within-i_size case too.
+	 */
+	inode->i_blocks = ocfs2_inode_sector_count(inode);
+
+	if (end > i_size_read(inode)) {
+		if (!handle) {
+			handle = ocfs2_start_trans(osb, credits);
+			if (IS_ERR(handle)) {
+				ret = PTR_ERR(handle);
+				handle = NULL;
+				mlog_errno(ret);
+				goto unlock;
+			}
+		}
+		ret = ocfs2_set_inode_size(handle, inode, di_bh, end);
+		if (ret < 0)
+			mlog_errno(ret);
+	}
+
+commit:
+	if (handle) {
+		ocfs2_update_inode_fsync_trans(handle, inode, 1);
+		ocfs2_commit_trans(osb, handle);
+	}
+
+unlock:
+	up_write(&oi->ip_alloc_sem);
+
+	if (data_ac) {
+		ocfs2_free_alloc_context(data_ac);
+		data_ac = NULL;
+	}
+	if (meta_ac) {
+		ocfs2_free_alloc_context(meta_ac);
+		meta_ac = NULL;
+	}
+
+	ocfs2_inode_unlock(inode, 1);
+	brelse(di_bh);
+
+out:
+	ocfs2_run_deallocs(osb, &dealloc);
+	return ret;
+}
+
+static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock,
+		    struct buffer_head *bh_result, int create)
+{
+	int ret = 0;
+	struct ocfs2_inode_info *oi = OCFS2_I(inode);
+
+	down_read(&oi->ip_alloc_sem);
+	ret = ocfs2_get_block(inode, iblock, bh_result, create);
+	up_read(&oi->ip_alloc_sem);
+
+	return ret;
+}
+
 struct ocfs2_dio_write_ctxt {
 	struct list_head	dw_zero_list;
-	unsigned		dw_zero_count;
 	int			dw_orphaned;
 	pid_t			dw_writer_pid;
 };
@@ -2170,7 +2979,6 @@ ocfs2_dio_alloc_write_ctx(struct buffer_head *bh, int *alloc)
 	if (dwc == NULL)
 		return NULL;
 	INIT_LIST_HEAD(&dwc->dw_zero_list);
-	dwc->dw_zero_count = 0;
 	dwc->dw_orphaned = 0;
 	dwc->dw_writer_pid = task_pid_nr(current);
 	bh->b_private = dwc;
@@ -2186,6 +2994,7 @@ static void ocfs2_dio_free_write_ctx(struct inode *inode,
 	kfree(dwc);
 }
 
+
 /*
  * TODO: Make this into a generic get_blocks function.
  *
@@ -2299,7 +3108,7 @@ static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock,
 
 	ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,
 				       OCFS2_WRITE_DIRECT, NULL,
-				       (void **)&wc, di_bh, NULL);
+				       (void **)&wc, di_bh, NULL, dwc, NULL);
 	if (ret) {
 		mlog_errno(ret);
 		goto unlock;
@@ -2330,11 +3139,7 @@ static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock,
 				      struct ocfs2_unwritten_extent,
 				      ue_node);
 		BUG_ON(ue->ue_cpos != desc->c_cpos);
-		/* The physical address may be 0, fill it. */
-		ue->ue_phys = desc->c_phys;
-
 		list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list);
-		dwc->dw_zero_count += wc->w_unwritten_count;
 	}
 
 	ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc);
@@ -2348,152 +3153,18 @@ static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock,
 	return ret;
 }
 
-static int ocfs2_dio_end_io_write(struct inode *inode,
-				  struct ocfs2_dio_write_ctxt *dwc,
-				  loff_t offset,
-				  ssize_t bytes)
-{
-	struct ocfs2_cached_dealloc_ctxt dealloc;
-	struct ocfs2_extent_tree et;
-	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
-	struct ocfs2_inode_info *oi = OCFS2_I(inode);
-	struct ocfs2_unwritten_extent *ue = NULL;
-	struct buffer_head *di_bh = NULL;
-	struct ocfs2_dinode *di;
-	struct ocfs2_alloc_context *data_ac = NULL;
-	struct ocfs2_alloc_context *meta_ac = NULL;
-	handle_t *handle = NULL;
-	loff_t end = offset + bytes;
-	int ret = 0, credits = 0, batch = 0;
-
-	ocfs2_init_dealloc_ctxt(&dealloc);
-
-	/* We do clear unwritten, delete orphan, change i_size here. If neither
-	 * of these happen, we can skip all this. */
-	if (list_empty(&dwc->dw_zero_list) &&
-	    end <= i_size_read(inode) &&
-	    !dwc->dw_orphaned)
-		goto out;
-
-	ret = ocfs2_inode_lock(inode, &di_bh, 1);
-	if (ret < 0) {
-		mlog_errno(ret);
-		goto out;
-	}
-
-	down_write(&oi->ip_alloc_sem);
-	di = (struct ocfs2_dinode *)di_bh->b_data;
-
-	ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), di_bh);
-
-	/* Attach dealloc with extent tree in case that we may reuse extents
-	 * which are already unlinked from current extent tree due to extent
-	 * rotation and merging.
-	 */
-	et.et_dealloc = &dealloc;
-
-	ret = ocfs2_lock_allocators(inode, &et, 0, dwc->dw_zero_count*2,
-				    &data_ac, &meta_ac);
-	if (ret) {
-		mlog_errno(ret);
-		goto unlock;
-	}
-
-	credits = ocfs2_calc_extend_credits(inode->i_sb, &di->id2.i_list);
-
-	list_for_each_entry(ue, &dwc->dw_zero_list, ue_node) {
-		if (!handle) {
-			handle = ocfs2_start_trans(osb, credits);
-			if (IS_ERR(handle)) {
-				ret = PTR_ERR(handle);
-				mlog_errno(ret);
-				goto unlock;
-			}
-			ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
-					OCFS2_JOURNAL_ACCESS_WRITE);
-			if (ret) {
-				mlog_errno(ret);
-				goto commit;
-			}
-		}
-		ret = ocfs2_assure_trans_credits(handle, credits);
-		if (ret < 0) {
-			mlog_errno(ret);
-			goto commit;
-		}
-		ret = ocfs2_mark_extent_written(inode, &et, handle,
-						ue->ue_cpos, 1,
-						ue->ue_phys,
-						meta_ac, &dealloc);
-		if (ret < 0) {
-			mlog_errno(ret);
-			goto commit;
-		}
-
-		if (++batch == OCFS2_DIO_MARK_EXTENT_BATCH) {
-			ocfs2_commit_trans(osb, handle);
-			handle = NULL;
-			batch = 0;
-		}
-	}
-
-	if (end > i_size_read(inode)) {
-		if (!handle) {
-			handle = ocfs2_start_trans(osb, credits);
-			if (IS_ERR(handle)) {
-				ret = PTR_ERR(handle);
-				mlog_errno(ret);
-				goto unlock;
-			}
-		}
-		ret = ocfs2_set_inode_size(handle, inode, di_bh, end);
-		if (ret < 0)
-			mlog_errno(ret);
-	}
-
-commit:
-	if (handle)
-		ocfs2_commit_trans(osb, handle);
-unlock:
-	up_write(&oi->ip_alloc_sem);
-
-	if (data_ac) {
-		ocfs2_free_alloc_context(data_ac);
-		data_ac = NULL;
-	}
-	if (meta_ac) {
-		ocfs2_free_alloc_context(meta_ac);
-		meta_ac = NULL;
-	}
-
-	/* everything looks good, let's start the cleanup */
-	if (!ret && dwc->dw_orphaned) {
-		BUG_ON(dwc->dw_writer_pid != task_pid_nr(current));
-
-		ret = ocfs2_del_inode_from_orphan(osb, inode, di_bh, 0, 0);
-		if (ret < 0)
-			mlog_errno(ret);
-	}
-	ocfs2_inode_unlock(inode, 1);
-	brelse(di_bh);
-out:
-	ocfs2_run_deallocs(osb, &dealloc);
-	ocfs2_dio_free_write_ctx(inode, dwc);
-
-	return ret;
-}
-
 /*
- * ocfs2_dio_end_io is called by the dio core when a dio is finished.  We're
- * particularly interested in the aio/dio case.  We use the rw_lock DLM lock
- * to protect io on one node from truncation on another.
+ * ocfs2_dio_bh_end_io() is called by the buffer_head dio core when a dio is
+ * finished.  The rw_lock DLM lock protects io on one node from truncation on
+ * another.
  */
-static int ocfs2_dio_end_io(struct kiocb *iocb,
-			    loff_t offset,
-			    ssize_t bytes,
-			    void *private)
+static int ocfs2_dio_bh_end_io(struct kiocb *iocb, loff_t offset,
+			       ssize_t bytes, void *private)
 {
 	struct inode *inode = file_inode(iocb->ki_filp);
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	struct ocfs2_dio_write_ctxt *dwc = private;
+	struct buffer_head *di_bh = NULL;
 	int level;
 	int ret = 0;
 
@@ -2503,12 +3174,26 @@ static int ocfs2_dio_end_io(struct kiocb *iocb,
 	if (bytes <= 0)
 		mlog_ratelimited(ML_ERROR, "Direct IO failed, bytes = %lld",
 				 (long long)bytes);
-	if (private) {
+	if (dwc) {
 		if (bytes > 0)
-			ret = ocfs2_dio_end_io_write(inode, private, offset,
-						     bytes);
-		else
-			ocfs2_dio_free_write_ctx(inode, private);
+			ret = ocfs2_dio_end_io_write(inode, offset, bytes,
+						     &dwc->dw_zero_list);
+		/*
+		 * The entry get_block() added has to go here, while the write
+		 * is the one that added it.  Leaving it set makes the next
+		 * extending write recover it by truncating to i_size, which
+		 * frees clusters another write has just allocated.
+		 */
+		if (!ret && dwc->dw_orphaned &&
+		    ocfs2_inode_lock(inode, &di_bh, 1) == 0) {
+			ret = ocfs2_del_inode_from_orphan(osb, inode, di_bh,
+							  0, 0);
+			if (ret < 0)
+				mlog_errno(ret);
+			ocfs2_inode_unlock(inode, 1);
+			brelse(di_bh);
+		}
+		ocfs2_dio_free_write_ctx(inode, dwc);
 	}
 
 	ocfs2_iocb_clear_rw_locked(iocb);
@@ -2544,7 +3229,7 @@ static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
 
 	return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
 				    iter, get_block,
-				    ocfs2_dio_end_io, 0);
+				    ocfs2_dio_bh_end_io, 0);
 }
 
 static int ocfs2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
@@ -2570,7 +3255,7 @@ static int ocfs2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
 		return -EOPNOTSUPP;
 	}
 
-	ret = ocfs2_lock_map_blocks(inode, &map, 0);
+	ret = ocfs2_lock_map_blocks(inode, &map, 0, flags & IOMAP_NOWAIT);
 	if (ret < 0)
 		return ret;
 
@@ -2640,8 +3325,8 @@ const struct address_space_operations ocfs2_aops = {
 	.writepages		= ocfs2_writepages,
 	.write_begin		= ocfs2_write_begin,
 	.write_end		= ocfs2_write_end,
-	.bmap			= ocfs2_bmap,
 	.direct_IO		= ocfs2_direct_IO,
+	.bmap			= ocfs2_bmap,
 	.invalidate_folio	= block_invalidate_folio,
 	.release_folio		= ocfs2_release_folio,
 	.migrate_folio		= buffer_migrate_folio,
fs/ocfs2/aops.h +2 -1
index 72de1e764a578..7946ef71259f4 100644
@@ -39,7 +39,8 @@ typedef enum {
 int ocfs2_write_begin_nolock(struct address_space *mapping,
 		loff_t pos, unsigned len, ocfs2_write_type_t type,
 		struct folio **foliop, void **fsdata,
-		struct buffer_head *di_bh, struct folio *mmap_folio);
+		struct buffer_head *di_bh, struct folio *mmap_folio,
+		void *owner, loff_t *touched_end);
 
 int ocfs2_read_inline_data(struct inode *inode, struct folio *folio,
 			   struct buffer_head *di_bh);
fs/ocfs2/inode.h +2 -0
index 07bd838e7843d..15a7d57aace51 100644
@@ -40,6 +40,8 @@ struct ocfs2_inode_info
 
 	/* Record unwritten extents during direct io. */
 	struct list_head		ip_unwritten_list;
+	/* Woken when entries leave ip_unwritten_list. */
+	wait_queue_head_t		ip_unwritten_wq;
 
 	/* protected by recovery_lock. */
 	struct inode			*ip_next_orphan;
fs/ocfs2/mmap.c +2 -1
index 1c03f45e8965d..5fed596a265ce 100644
@@ -90,7 +90,8 @@ static vm_fault_t __ocfs2_page_mkwrite(struct file *file,
 		len = ((size - 1) & ~PAGE_MASK) + 1;
 
 	err = ocfs2_write_begin_nolock(mapping, pos, len, OCFS2_WRITE_MMAP,
-				       &locked_folio, &fsdata, di_bh, folio);
+				       &locked_folio, &fsdata, di_bh, folio,
+				       NULL, NULL);
 	if (err) {
 		if (err != -ENOSPC)
 			mlog_errno(err);
fs/ocfs2/super.c +1 -0
index cb9db90300b81..79670f8655801 100644
@@ -1651,6 +1651,7 @@ static void ocfs2_inode_init_once(void *data)
 	ocfs2_extent_map_init(&oi->vfs_inode);
 	INIT_LIST_HEAD(&oi->ip_io_markers);
 	INIT_LIST_HEAD(&oi->ip_unwritten_list);
+	init_waitqueue_head(&oi->ip_unwritten_wq);
 	oi->ip_dir_start_lookup = 0;
 	init_rwsem(&oi->ip_alloc_sem);
 	init_rwsem(&oi->ip_xattr_sem);
Signature · 1 line
2.39.3
author maintainer
#7 lore raw

RFC PATCH v14 7/10 ocfs2: switch dio write path from buffer_head to iomap

In reply to Joseph Qi

From: Heming Zhao <[email protected]>

Replace ocfs2_dio_wr_get_block() with ocfs2_dio_wr_map_blocks(), which hands iomap a mapping of as many clusters as can be described by a single struct iomap: up to 16MB, stopped at the first cluster that is not of the same kind as the first one. ocfs2_iomap_begin() serves writes through it, and ocfs2_dio_end_io() converts the unwritten extents the write recorded and updates the inode size.

In the buffer_head path, ocfs2_dio_wr_get_block() stores dwc in bh->b_private, which lets it detect the first call for an I/O chunk and invoke ocfs2_add_inode_to_orphan() to protect the extent allocation. iomap provides no similar private field, so ocfs2_add_inode_to_orphan() moves to ocfs2_file_write_iter().

It is also impossible to pass the dwc to iomap_dio_ops.end_io: the callback cannot distinguish between I/Os initiated by different threads concurrently, and without that context it could delete an orphan entry created by another thread. The orphan removal therefore moves to ocfs2_file_write_iter() as well, where inode_lock() serializes the writers and IOMAP_DIO_FORCE_WAIT makes an extending write complete before the function returns, so i_size is already updated when the entry is removed.

iomap calls ->iomap_begin() once per mapping but ->end_io() once per I/O, and the latter only gets the kiocb, so the kiocb is the identity of the I/O: ocfs2_file_write_iter() passes it in iomap_iter.private, ocfs2_iomap_next() forwards it to ocfs2_dio_wr_map_blocks(), and each unwritten record stores it in ue_owner. ocfs2_dio_collect_unwritten() finds the records of one I/O by that owner.

A direct write waits for unwritten records belonging to another dio before it takes the re-write fast path, not after. A completion which fails part way through its conversion has already made some clusters written and dropped ip_alloc_sem and the inode lock, but it still owns the records and is about to write the zeroed head/tail buffers over those clusters. The fast path would see them as MAPPED and hand them out, and the new data would be overwritten by those zeroes. The records are only removed after that cleanup, so waiting first excludes the whole window. Under IOMAP_NOWAIT the wait becomes -EAGAIN.

Unlike ocfs2_dio_wr_get_block(), the zeroing of the gap between i_size and the write is done once per dio by ocfs2_dio_zero_eof() before the io is issued. Zeroing it per mapping would zero blocks that earlier mappings of this same dio have already written, because i_size is only updated at completion; that made xfstests generic/538 fail.

On failure only the first and the last cluster of the touched range are cleaned up, through ocfs2_dio_cleanup_clusters(): those are the only clusters ocfs2_grab_folios_direct() fills folio windows for, and the clusters in between can hold dirty folios of other writes sharing the cluster. ocfs2_write_range_buffers() writes the buffers directly when some clusters may already have been converted, because generic writeback refuses to submit folios beyond i_size.

ocfs2_dio_clear_orphan_locked() only removes the orphan entry. Clusters beyond i_size are left alone: there is no on-disk way to tell what this write allocated from unwritten extents preallocated with fallocate(FALLOC_FL_KEEP_SIZE), so truncating to i_size would free the preallocated space as well. They stay until a later truncate or recovery. The in-memory marker is only dropped once the entry is really gone, so a failed write leaves it for the next extending write to recover, which ocfs2_add_inode_to_orphan() already does before adding its own.

The pid marker is a strict ownership token: every path that leaves the entry behind zeroes ip_dio_orphan_pid, so a later write by the same task cannot match it and remove the entry without the truncate recovery. ocfs2_dio_clear_orphan() only removes the entry once i_size covers the range the write meant to write, or nothing is allocated beyond i_size; otherwise it leaves the entry for recovery and gives up ownership.

Writes that span EOF may trigger an i_size update at completion, and within i_size there can still be uncommitted metadata such as the CoW done by ocfs2_prepare_inode_for_write(). Both set IOMAP_F_DIRTY so iomap cannot take the FUA-only fast path, which would clear IOMAP_DIO_NEED_SYNC and skip generic_write_sync(), leaving that metadata uncommitted for O_DSYNC.

With the write path on iomap, ocfs2 no longer needs LEGACY_DIRECT_IO.

A buffered write needs the rw lock EX, so every path that falls back to generic_perform_write() upgrades first: the -ENOTBLK / zero-length bounce inside the direct branch as well as the demoted direct branch. Under coherency=buffered a PR lock would let another node write the same range directly while this node does a read-modify-write in the page cache. ocfs2_dio_upgrade_rw_lock() drops PR and takes EX rather than asking for one upgrade, which can deadlock in the cluster lock manager when two nodes upgrade at once.

ip_dio_orphan_pid is reset in ocfs2_alloc_inode(), not only in the slab constructor. The slab object is reused for a new inode, and a stale pid that happens to be reused by another task would let an unrelated write match the marker and delete a crash-left orphan entry without the truncate recovery, leaking the clusters beyond i_size.

Clearing the orphan entry takes the inode cluster lock, which blocks, so IOCB_NOWAIT does not go there. The marker stays for a later write or for the recovery.

ocfs2_free_write_ctxt() runs the cached deallocs after unlocking the folios, like ocfs2_write_end_nolock() does. Without it the error paths that free a write context lose the extents it had cached for deletion.

A write that hits an error does not convert its unwritten extents. iomap keeps dio->size counting bios that failed at completion, and a short write can leave the tail of the last cluster unzeroed, so converting [offset, offset + size) would mark uninitialized disk blocks written and expose stale data. Leave the extents unwritten, drop the zeroed folios and return the error, as ext4 and xfs do; the extents read back as zeroes until a later write converts them.

---
 fs/ocfs2/Kconfig |    1 -
 fs/ocfs2/aops.c  | 1043 +++++++++++++++++++++++++++++++++-------------
 fs/ocfs2/aops.h  |   33 +-
 fs/ocfs2/file.c  |  275 ++++++++++--
 fs/ocfs2/inode.h |    8 +-
 fs/ocfs2/super.c |    2 +
 6 files changed, 1015 insertions(+), 347 deletions(-)
fs/ocfs2/Kconfig +0 -1
index bf1678a5eb01e..74bc2008ef0bf 100644
@@ -9,7 +9,6 @@ config OCFS2_FS
 	select QUOTA_TREE
 	select FS_IOMAP
 	select FS_POSIX_ACL
-	select LEGACY_DIRECT_IO
 	help
 	  OCFS2 is a general purpose extent based shared disk cluster file
 	  system with many similarities to ext3. It supports 64 bit inode
fs/ocfs2/aops.c +756 -287

1,111 lines not on this page · raw message

fs/ocfs2/aops.h +4 -29
index 7946ef71259f4..7336df15ca3a0 100644
@@ -10,6 +10,8 @@
 #include <linux/iomap.h>
 
 extern const struct iomap_dio_ops ocfs2_iomap_dio_ops_r_pr;
+extern const struct iomap_dio_ops ocfs2_iomap_dio_ops_w_pr;
+extern const struct iomap_dio_ops ocfs2_iomap_dio_ops_w_ex;
 int ocfs2_iomap_next(const struct iomap_iter *iter, struct iomap *iomap,
 			    struct iomap *srcmap);
 
@@ -48,36 +50,9 @@ int ocfs2_size_fits_inline_data(struct buffer_head *di_bh, u64 new_size);
 
 int ocfs2_get_block(struct inode *inode, sector_t iblock,
 		    struct buffer_head *bh_result, int create);
+int ocfs2_dio_zero_eof(struct inode *inode, loff_t pos, size_t count);
+void ocfs2_dio_clear_orphan(struct inode *inode, loff_t end);
 int ocfs2_map_blocks(struct inode *inode, struct ocfs2_map_block *map,
 		    int flags);
-/* all ocfs2_dio_end_io()'s fault */
-#define ocfs2_iocb_is_rw_locked(iocb) \
-	test_bit(0, (unsigned long *)&iocb->private)
-static inline void ocfs2_iocb_set_rw_locked(struct kiocb *iocb, int level)
-{
-	set_bit(0, (unsigned long *)&iocb->private);
-	if (level)
-		set_bit(1, (unsigned long *)&iocb->private);
-	else
-		clear_bit(1, (unsigned long *)&iocb->private);
-}
-
-/*
- * Using a named enum representing lock types in terms of #N bit stored in
- * iocb->private, which is going to be used for communication between
- * ocfs2_dio_end_io() and ocfs2_file_write/read_iter().
- */
-enum ocfs2_iocb_lock_bits {
-	OCFS2_IOCB_RW_LOCK = 0,
-	OCFS2_IOCB_RW_LOCK_LEVEL,
-	OCFS2_IOCB_NUM_LOCKS
-};
-
-#define ocfs2_iocb_init_rw_locked(iocb) \
-	(iocb->private = NULL)
-#define ocfs2_iocb_clear_rw_locked(iocb) \
-	clear_bit(OCFS2_IOCB_RW_LOCK, (unsigned long *)&iocb->private)
-#define ocfs2_iocb_rw_locked_level(iocb) \
-	test_bit(OCFS2_IOCB_RW_LOCK_LEVEL, (unsigned long *)&iocb->private)
 
 #endif /* OCFS2_FILE_H */
fs/ocfs2/file.c +246 -29

353 lines not on this page · raw message

fs/ocfs2/inode.h +7 -1
index 15a7d57aace51..1981dea8a764a 100644
@@ -40,9 +40,15 @@ struct ocfs2_inode_info
 
 	/* Record unwritten extents during direct io. */
 	struct list_head		ip_unwritten_list;
-	/* Woken when entries leave ip_unwritten_list. */
+	/*
+	 * Woken when entries leave ip_unwritten_list. A direct write waits
+	 * on it for the entries of the other dios, see
+	 * ocfs2_dio_wr_map_blocks().
+	 */
 	wait_queue_head_t		ip_unwritten_wq;
 
+	pid_t				ip_dio_orphan_pid;
+
 	/* protected by recovery_lock. */
 	struct inode			*ip_next_orphan;
 
fs/ocfs2/super.c +2 -0
index 79670f8655801..c696c539f4162 100644
@@ -557,6 +557,7 @@ static struct inode *ocfs2_alloc_inode(struct super_block *sb)
 
 	oi->i_sync_tid = 0;
 	oi->i_datasync_tid = 0;
+	oi->ip_dio_orphan_pid = 0;
 	memset(&oi->i_dquot, 0, sizeof(oi->i_dquot));
 
 	jbd2_journal_init_jbd_inode(&oi->ip_jinode, &oi->vfs_inode);
@@ -1660,6 +1661,7 @@ static void ocfs2_inode_init_once(void *data)
 	oi->ip_blkno = 0ULL;
 	oi->ip_clusters = 0;
 	oi->ip_next_orphan = NULL;
+	oi->ip_dio_orphan_pid = 0;
 
 	ocfs2_resv_init_once(&oi->ip_la_data_resv);
 
Signature · 1 line
2.39.3
author maintainer
#8 lore raw

RFC PATCH v14 8/10 ocfs2: keep sub-page overwrites of written blocks on direct I/O

In reply to Joseph Qi

ocfs2_should_use_dio() demotes every non-page-aligned write to buffered I/O when i_blocksize(inode) < PAGE_SIZE. The zeroing hazard it guards against only exists when a partial block at either end is a hole or an unwritten extent, or the write extends the file; a pure in-place overwrite of already-written blocks needs no zeroing at all. On 16K or 64K page kernels every ocfs2 file system has blocksize < PAGE_SIZE, so all sub-page O_DIRECT overwrites were taking an exclusive rw lock, failing IOCB_NOWAIT and going through page-cache writeback.

Probe the partial blocks at both ends with a no-create lookup and demote only when one of them is not already mapped and written, or the write extends i_size.

Do this only at the second ocfs2_should_use_dio() call site, after generic_write_checks() has resolved O_APPEND and clamped the length and ocfs2_prepare_inode_for_write() has refreshed the inode. At the first site ki_pos and count are not final, so the range cannot be probed there; leaving it undemoted is safe because the buffered path upgrades the rw lock later.

That second call site is added here. A write demoted after generic_write_checks() has already been handed a PR rw lock by the first evaluation, and the buffered write it falls into needs EX, so it goes through ocfs2_dio_upgrade_rw_lock() like the other fallback paths.

The rw lock is held across the probe, so no other node can punch or truncate the range underneath it.

---
 fs/ocfs2/aops.c | 52 +++++++++++++++++++++++++++++++++++++
 fs/ocfs2/aops.h |  2 ++
 fs/ocfs2/file.c | 69 ++++++++++++++++++++++++++++++++++++++-----------
 3 files changed, 108 insertions(+), 15 deletions(-)
fs/ocfs2/aops.c +52 -0
index 491410430f8fd..68f5888757fbc 100644
@@ -2828,6 +2828,58 @@ int ocfs2_dio_zero_eof(struct inode *inode, loff_t pos, size_t count)
 	return ret;
 }
 
+/*
+ * A direct write which does not cover whole pages leaves the rest of the
+ * page untouched, and iomap only zeroes the padding up to the file system
+ * block size.  That is safe only when the partial blocks at both ends are
+ * already allocated and written; a hole or an unwritten extent there would
+ * expose stale data once the cluster is marked written.  Let buffered I/O
+ * handle those.
+ *
+ * Called with the rw lock held, so no other node can punch or truncate the
+ * range underneath us.
+ */
+bool ocfs2_dio_subpage_needs_buffered(struct inode *inode, loff_t pos,
+				      size_t count, bool nowait)
+{
+	unsigned int blkbits = inode->i_blkbits;
+	struct ocfs2_map_block map;
+	int ret;
+
+	if (i_blocksize(inode) >= PAGE_SIZE)
+		return false;
+	if (IS_ALIGNED(pos, PAGE_SIZE) && IS_ALIGNED(pos + count, PAGE_SIZE))
+		return false;
+	if (pos + count > i_size_read(inode))
+		return true;
+
+	/*
+	 * A page-aligned end is block-aligned and fully covered, so it leaves
+	 * no partial block to check.  Only probe the ends the write does not
+	 * cover whole, and skip the tail when it shares the head's block.
+	 */
+	if (!IS_ALIGNED(pos, PAGE_SIZE)) {
+		map.lblk = pos >> blkbits;
+		map.len = 1;
+		map.flags = 0;
+		ret = ocfs2_lock_map_blocks(inode, &map, 0, nowait);
+		if (ret || !(map.flags & OCFS2_MAP_MAPPED))
+			return true;
+	}
+
+	if (!IS_ALIGNED(pos + count, PAGE_SIZE) &&
+	    ((pos + count - 1) >> blkbits) != (pos >> blkbits)) {
+		map.lblk = (pos + count - 1) >> blkbits;
+		map.len = 1;
+		map.flags = 0;
+		ret = ocfs2_lock_map_blocks(inode, &map, 0, nowait);
+		if (ret || !(map.flags & OCFS2_MAP_MAPPED))
+			return true;
+	}
+
+	return false;
+}
+
 /*
  * The most a single mapping handed out for a direct write spans.
  * It bounds the memory of the write context, one descriptor per
fs/ocfs2/aops.h +2 -0
index 7336df15ca3a0..38a977938223a 100644
@@ -51,6 +51,8 @@ int ocfs2_size_fits_inline_data(struct buffer_head *di_bh, u64 new_size);
 int ocfs2_get_block(struct inode *inode, sector_t iblock,
 		    struct buffer_head *bh_result, int create);
 int ocfs2_dio_zero_eof(struct inode *inode, loff_t pos, size_t count);
+bool ocfs2_dio_subpage_needs_buffered(struct inode *inode, loff_t pos,
+				      size_t count, bool nowait);
 void ocfs2_dio_clear_orphan(struct inode *inode, loff_t end);
 int ocfs2_map_blocks(struct inode *inode, struct ocfs2_map_block *map,
 		    int flags);
fs/ocfs2/file.c +54 -15

81 lines not on this page · raw message

Signature · 1 line
2.39.3
author maintainer
#9 lore raw

RFC PATCH v14 9/10 ocfs2: write the dio zeroed head/tail buffers out before completion

In reply to Joseph Qi

Preparing a direct write of a new or unwritten cluster zeroes the head and tail folios outside the user range and leaves them dirty in the page cache, outside the range iomap invalidates. They can be wholly beyond i_size until ocfs2_dio_end_io_write() updates it at completion.

Writeback will not submit such buffers. ocfs2_writepages() uses mpage_writepages(), which for a folio at or past i_size falls through to block_write_full_folio(), and __block_write_full_folio() does:

	if (block > last_block) {
		clear_buffer_dirty(bh);
		set_buffer_uptodate(bh);
	}

So if writeback runs before the conversion, the zeroes are discarded without ever reaching the disk, the folio is left clean, and the cluster exposes stale blocks once ocfs2_dio_end_io_write() marks it written. A short write leaves the zeroed tail folios of the unconverted trailing clusters dirty in the same way.

ocfs2_dio_cleanup_pages(..., true) cannot fix this: it only runs when the conversion fails, and even then the buffers may already have been cleaned or the folio reclaimed, so ocfs2_write_range_buffers() finds nothing to write. The zeroes have to reach the disk while the clusters are still ours and the folios are still locked.

Write them in ocfs2_write_end_nolock() for a direct write, right after block_commit_write() has marked them dirty. Submit every buffer first and wait in a second pass, so a cluster spanning hundreds of folios does not cost one round trip per folio. submit_bh()/wait_on_buffer() bypass the i_size check, which is the point.

The folio lock keeps the buffers alive and excludes any other io on them, so no extra buffer reference is taken and a write error seen in the wait pass can only come from the submit pass. ip_alloc_sem, the inode cluster lock and an open journal handle are held; the data io needs no journal progress, so there is no cycle with a commit that is blocked on our handle and waiting for the folio lock. IOMAP_NOWAIT never reaches here, ocfs2_dio_wr_map_blocks() returns -EAGAIN before the allocation path.

This makes the zeroing io synchronous in the mapping path instead of deferring it to background writeback. That io was always required; iomap issues its own block-size padding the same way through iomap_dio_zero().

---
 fs/ocfs2/aops.c | 120 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 120 insertions(+)
fs/ocfs2/aops.c +120 -0
index 68f5888757fbc..81e374f1d4f77 100644
@@ -2635,6 +2635,113 @@ static void ocfs2_write_end_inline(struct inode *inode, loff_t pos,
 	     le16_to_cpu(di->i_dyn_features));
 }
 
+/*
+ * The head/tail folios a direct write zeroed are outside the range iomap
+ * invalidates, and they can be wholly beyond i_size until ->end_io() updates
+ * it.  Writeback will not submit such buffers: __block_write_full_folio()
+ * clears their dirty bit without writing them, so the zeroes would never
+ * reach the disk and the cluster would expose stale blocks once
+ * ocfs2_dio_end_io_write() converts it.  Flushing at completion is too late,
+ * by then the buffers may already have been cleaned or the folio reclaimed.
+ * Write them here, while the folios are locked and the clusters are ours.
+ *
+ * The folio lock keeps the buffers alive and excludes any other io on them,
+ * so no extra buffer reference is needed and a write error seen in the second
+ * pass can only come from the first.
+ */
+static int ocfs2_dio_write_zero_folios(struct ocfs2_write_ctxt *wc)
+{
+	int i, ret = 0;
+
+	/* Submit them all before waiting, a cluster can span many folios. */
+	for (i = 0; i < wc->w_num_folios; i++) {
+		struct folio *folio = wc->w_folios[i];
+		struct buffer_head *bh, *head;
+
+		if (!folio)
+			continue;
+		head = folio_buffers(folio);
+		if (!head)
+			continue;
+
+		bh = head;
+		do {
+			lock_buffer(bh);
+			/*
+			 * Clear a stale error bit from an earlier writeback; no
+			 * write of this operation has completed yet, so only the
+			 * wait pass below may latch an error into ret.
+			 */
+			clear_buffer_write_io_error(bh);
+			if (!buffer_dirty(bh)) {
+				unlock_buffer(bh);
+				goto next;
+			}
+			if (!buffer_mapped(bh) || !buffer_uptodate(bh) ||
+			    buffer_delay(bh) || buffer_unwritten(bh)) {
+				unlock_buffer(bh);
+				if (!ret)
+					ret = -EIO;
+				goto next;
+			}
+			clear_buffer_dirty(bh);
+			bh_submit(bh, REQ_OP_WRITE | REQ_SYNC, bh_end_write);
+next:
+			bh = bh->b_this_page;
+		} while (bh != head);
+	}
+
+	for (i = 0; i < wc->w_num_folios; i++) {
+		struct folio *folio = wc->w_folios[i];
+		struct buffer_head *bh, *head;
+
+		if (!folio)
+			continue;
+		head = folio_buffers(folio);
+		if (!head)
+			continue;
+
+		bh = head;
+		do {
+			wait_on_buffer(bh);
+			if (buffer_write_io_error(bh) && !ret)
+				ret = -EIO;
+			bh = bh->b_this_page;
+		} while (bh != head);
+	}
+
+	/*
+	 * The zeroes are on disk now.  block_commit_write() also marked the
+	 * folios dirty; drop that bit once every buffer is clean, so a
+	 * RWF_NOWAIT read does not see a clean folio as needing writeback.
+	 */
+	if (!ret) {
+		for (i = 0; i < wc->w_num_folios; i++) {
+			struct folio *folio = wc->w_folios[i];
+			struct buffer_head *bh, *head;
+			bool dirty = false;
+
+			if (!folio)
+				continue;
+			head = folio_buffers(folio);
+			if (!head)
+				continue;
+			bh = head;
+			do {
+				if (buffer_dirty(bh)) {
+					dirty = true;
+					break;
+				}
+				bh = bh->b_this_page;
+			} while (bh != head);
+			if (!dirty)
+				folio_clear_dirty_for_io(folio);
+		}
+	}
+
+	return ret;
+}
+
 int ocfs2_write_end_nolock(struct address_space *mapping, loff_t pos,
 		unsigned len, unsigned copied, void *fsdata)
 {
@@ -2723,6 +2830,19 @@ int ocfs2_write_end_nolock(struct address_space *mapping, loff_t pos,
 		}
 	}
 
+	if (wc->w_type == OCFS2_WRITE_DIRECT) {
+		ret = ocfs2_dio_write_zero_folios(wc);
+		if (ret) {
+			copied = ret;
+			/*
+			 * On failure out_write_size still runs: the allocation
+			 * is committed below regardless, so refresh i_blocks and
+			 * record the fsync transaction; a first-mapping failure
+			 * has no end_io to do it later.
+			 */
+		}
+	}
+
 out_write_size:
 	/* Direct io do not update i_size here. */
 	if (wc->w_type != OCFS2_WRITE_DIRECT) {
Signature · 1 line
2.39.3
author maintainer
#10 lore raw

RFC PATCH v14 10/10 ocfs2: make buffered writes wait for in-flight direct writes

In reply to Joseph Qi

ocfs2_unwritten_check() lets a buffered write skip zeroing and unwritten conversion for a cluster that an in-flight direct write has put on ip_unwritten_list, on the assumption that the dio will convert it. The dio only converts the range it actually completed, and converts nothing at all when it fails, so a dio which ends short or errors leaves the cluster unwritten while the buffered data sits in a dirty folio. Once that folio is written back and evicted the data reads back as zeroes.

Wait for foreign entries on ip_unwritten_wq before taking any lock in ocfs2_write_begin(), the same way ocfs2_dio_wr_map_blocks() already does. The wait must be outside ip_alloc_sem and the inode cluster lock because ocfs2_dio_end_io_write() takes both to convert. Every caller holds i_rwsem and entries are only added under it, so the set can only shrink and no retry loop is needed. The folio is not locked yet at this point, so there is no ordering conflict with ocfs2_grab_folios_direct().

page_mkwrite is deliberately left alone. It holds no i_rwsem, so entries can appear between the wait and taking ip_alloc_sem, and it is reachable through get_user_pages() from bio_iov_iter_get_pages() when the dio source buffer is an mmap of the same file. Waiting there with no owner would match the dio's own entries, which are only removed at end_io, and deadlock against itself. The mmap window therefore remains open and needs a way to exclude the current task's own in-flight dio first.

Fixes 4506cfb6f8ca ("ocfs2: record UNWRITTEN extents when populate write desc")
---
 fs/ocfs2/aops.c | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
fs/ocfs2/aops.c +37 -0
index 81e374f1d4f77..a7634e92e72e8 100644
@@ -2569,6 +2569,39 @@ int ocfs2_write_begin_nolock(struct address_space *mapping,
 	return ret;
 }
 
+/*
+ * Wait for direct writes still in flight on [pos, pos + len) to finish.
+ * A buffered write must not defer its zeroing to a dio which may never
+ * convert the cluster: if that dio ends short or fails, the cluster stays
+ * unwritten on disk and the buffered data reads back as zeroes.
+ *
+ * Must be called without ip_alloc_sem or the inode cluster lock held,
+ * because ocfs2_dio_end_io_write() takes both to convert.  i_rwsem is held
+ * by every caller and all entries are added under it, so the set can only
+ * shrink while we wait and no retry is needed.
+ */
+static int ocfs2_wait_foreign_unwritten(struct inode *inode, loff_t pos,
+					unsigned int len)
+{
+	struct ocfs2_inode_info *oi = OCFS2_I(inode);
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	/*
+	 * An extending write zeroes the gap from i_size, so wait on the
+	 * cluster containing i_size too: a dio there may still convert it
+	 * after ocfs2_zero_extend() skipped it as unwritten, exposing the
+	 * unzeroed tail below the new i_size.
+	 */
+	u32 cstart = min_t(loff_t, pos, i_size_read(inode)) >>
+		     osb->s_clustersize_bits;
+	u32 cend = ocfs2_clusters_for_bytes(inode->i_sb, pos + len);
+
+	if (!ocfs2_dio_foreign_unwritten(oi, cstart, cend, NULL))
+		return 0;
+
+	return wait_event_killable(oi->ip_unwritten_wq,
+			!ocfs2_dio_foreign_unwritten(oi, cstart, cend, NULL));
+}
+
 static int ocfs2_write_begin(const struct kiocb *iocb,
 			     struct address_space *mapping,
 			     loff_t pos, unsigned len,
@@ -2578,6 +2611,10 @@ static int ocfs2_write_begin(const struct kiocb *iocb,
 	struct buffer_head *di_bh = NULL;
 	struct inode *inode = mapping->host;
 
+	ret = ocfs2_wait_foreign_unwritten(inode, pos, len);
+	if (ret)
+		return ret;
+
 	ret = ocfs2_inode_lock(inode, &di_bh, 1);
 	if (ret) {
 		mlog_errno(ret);
Signature · 1 line
2.39.3