Skip to contentSkip to conversation

migrate ocfs2 DIO from buffer_head to iomap

RFC PATCH Superseded Heming Zhao 1 participant 5 messages Nov 18 – Nov 19 1 message not in the archive OCFS2

v7 of 10 Superseded Latest is v10 →

lore
Share & tools
lore

Heming Zhao

author reviewer
#0 lore raw

v7 cover migrate ocfs2 DIO from buffer_head to iomap

This patch set migrates ocfs2 Direct I/O (DIO) from buffer_head mode to iomap mode. And the code base is commit aebb72744764 (v7.4-rc3), and also merge Joseph's code and ideas from [1]:

V7 changelog:

Address sashiko's review comments. Main changes:

1. Adopt the latest iomap API and remove the iomap_ops structure.
2. Add a retry mechanism in ocfs2_dio_wr_map_blocks() to fix a data loss bug. Multiple concurrent writes are serialized by i_rwsem at submission time but completed asynchronously by ocfs2_dio_end_io(). When the unwritten extent conversion fails and finishes first, other threads' submissions would lose data but still return success.
3. Fix DIO alignment issues.
4. Fix several edge-case handling problems in the DIO write path.

Resend this patch set based on sashiko latest review comments:
- ref: https://sashiko.dev/#/patchset/20261117150053.18417-1-heming.zhao%40suse.com
- build issues with the latest iomap API
- comments contain some stale symbol names
- patch [2/3]: change the check of "map->pblk < past_eof" to "map->lblk < past_eof" in ocfs2_map_blocks()
- patch [3/3]: remove the dead w_unwritten_count field in
"struct ocfs2_write_ctxt"
- revise some commit log mistakes and a typo.

[1]:
https://gitee.com/anolis/storage-cloud-kernel/commit/ea3fe75e2060118ba093e90b1cd34fa382914b29

[2]:
https://sashiko.dev/#/patchset/20261103135605.22943-1-heming.zhao%40suse.com

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]/
v3 sashiko review:
https://sashiko.dev/#/patchset/20261018143319.22329-1-heming.zhao%40suse.com
v4 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v4 sashiko review:
https://sashiko.dev/#/patchset/20261103135605.22943-1-heming.zhao%40suse.com
v5 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v5 sashiko review:
https://sashiko.dev/#/patchset/20261105071930.16399-1-heming.zhao%40suse.com
v6 patch set:
https://lore.kernel.org/ocfs2-devel/[email protected]/
v6 sashiko review:
https://sashiko.dev/#/patchset/20261115154013.9379-1-heming.zhao%40suse.com

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

# test report

This patch set has been tested on 7.4-rc3 kernel with the following test cases.

The current code still needs some polishing. I hope sashiko can continue to find issues in v7, so I've only done a few basic tests so far.

## ltp

runltp -f dio -d /mnt/ocfs2/

results: passed

## xfstests

./check -g quick -T -b -s ocfs2 -e generic/081 \
-e generic/266 -e generic/272 -e generic/281 \
-e generic/338 -e generic/347 -e generic/361 \
-e generic/628 -e generic/629 -e generic/648 -e generic/650

OCFS2_MKFS_LOCAL_OPT="-b 2K -C 8K --fs-features=local --fs-feature-level=max-features"
Failures: generic/003 generic/056 generic/075 generic/091 generic/094 generic/112 generic/177 generic/211 generic/225 generic/263 generic/319 generic/321 generic/322 generic/329 generic/331 generic/370 generic/376 generic/424 generic/448 generic/467 generic/477 generic/481 generic/498 generic/510 generic/512 generic/513 generic/534 generic/537 generic/552 generic/557 generic/563 generic/564 generic/578 generic/588 generic/607 generic/620 generic/630 generic/755 generic/759 generic/760 generic/771 generic/777 generic/779 generic/784 ocfs2/001
Failed 45 of 632 tests

-----------------------
Heming Zhao (3):
ocfs2: Add new ocfs2_map_blocks() to introduce iomap feature
ocfs2: switch DIO read path from buffer_head to iomap
ocfs2: switch dio write path from buffer_head to iomap

 fs/ocfs2/Kconfig |    2 +-
 fs/ocfs2/aops.c  | 1626 ++++++++++++++++++++++++++++++++++++----------
 fs/ocfs2/aops.h  |   42 +-
 fs/ocfs2/file.c  |  248 ++++++-
 fs/ocfs2/inode.h |    6 +
 fs/ocfs2/mmap.c  |    2 +-
 fs/ocfs2/ocfs2.h |   25 +-
 fs/ocfs2/super.c |    1 +
 8 files changed, 1533 insertions(+), 419 deletions(-)
Signature · 1 line
2.55.0
author reviewer
#1 lore raw

RFC PATCH v7 1/3 ocfs2: Add new ocfs2_map_blocks() to introduce iomap feature

As part of migrating OCFS2 DIO read/write code paths towards the modern and performant iomap framework, 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 4acdbb70882c..64fcf6eb3d89 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 114efc9111e4..8dd6edd7c1a1 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 e3bb3cc0b25a..b4583b3170e2 100644
@@ -514,7 +514,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.55.0
author reviewer
#2 lore raw

RFC PATCH v7 2/3 ocfs2: switch DIO read path from buffer_head to iomap

In reply to Heming Zhao

Migrate 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 (ocfs2_iomap_dio_ops_pr for PRMODE or ocfs2_iomap_dio_ops_ex for EXMODE). 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  |  60 ++++++++++++++++++++++----
 4 files changed, 161 insertions(+), 12 deletions(-)
fs/ocfs2/Kconfig +1 -0
index 2514d36cbe01..bf1678a5eb01 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 8dd6edd7c1a1..72de1e764a57 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 +51 -9

95 lines not on this page · raw message

Signature · 1 line
2.55.0
author reviewer
#3 lore raw

RFC PATCH v7 3/3 ocfs2: switch dio write path from buffer_head to iomap

In reply to Heming Zhao

Converts OCFS2's DIO write path from the legacy buffer_head infrastructure to the modern iomap framework.

The buffer_head based ocfs2_dio_wr_get_block() is replaced by ocfs2_dio_wr_map_blocks(). Instead of one cluster per call, it now 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 (hole, unwritten, written).

Implement ocfs2_dio_end_io() and ocfs2_dio_end_io_write() to handle IO completion. They convert UNWRITTEN extents, updates inode size (EOF).

In the buffer_head path, ocfs2_dio_wr_get_block() stores dwc in bh->b_private, enabling it to detect the first call for an IO chunk and invoke ocfs2_add_inode_to_orphan() to protect the extent allocation. However, iomap doesn't provide a similar private field. Therefore, moves ocfs2_add_inode_to_orphan() from ocfs2_dio_wr_map_blocks(the buffer_head counterpart to ocfs2_dio_wr_get_block()) to ocfs2_file_write_iter().

It is also impossible t pass The dwc to iomap_dio_ops.end_io, the iomap ->end_io callback cannot effectively distinguish between I/Os initiated by different threads concurrently. For example, when multiple DIO write threads operate on the same inode concurrently, the end_io callback without the dwc context may incorrectly delete an orphan inode created by another thread, leading to a crash. The fix is to move the orphan inode deletion from end_io into ocfs2_file_write_iter(). In ocfs2_file_write_iter(), inode_lock() serializes the write threads, and IOMAP_DIO_FORCE_WAIT ensures that the function only returns after the bio completes. This guarantees that i_size has already been updated when ocfs2_dio_del_orphan() is called.

iomap calls ->iomap_begin() once per mapping but ->end_io() once per io, and the latter only gets the kiocb, so the kiocb is used as the identity of the io: 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 with the cluster range it covers.

Doesn't like ocfs2_dio_wr_get_block(), move the zero operations from ocfs2_dio_wr_map_blocks() to ocfs2_file_write_iter(). If do the zeroing in ocfs2_dio_wr_map_blocks() would zero blocks that earlier mappings of this same dio have already written, as i_size is only updated at dio completion. this will makes xfstests generic/538 failure.

---
 fs/ocfs2/Kconfig |    1 -
 fs/ocfs2/aops.c  | 1537 ++++++++++++++++++++++++++++++++++------------
 fs/ocfs2/aops.h  |   35 +-
 fs/ocfs2/file.c  |  188 +++++-
 fs/ocfs2/inode.h |    6 +
 fs/ocfs2/mmap.c  |    2 +-
 fs/ocfs2/super.c |    1 +
 7 files changed, 1320 insertions(+), 450 deletions(-)
fs/ocfs2/Kconfig +0 -1
index bf1678a5eb01..74bc2008ef0b 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 +1140 -397

1,926 lines not on this page · raw message

fs/ocfs2/aops.h +5 -30
index 72de1e764a57..6310fcf625e6 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);
 
@@ -39,7 +41,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);
 
 int ocfs2_read_inline_data(struct inode *inode, struct folio *folio,
 			   struct buffer_head *di_bh);
@@ -47,36 +50,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);
 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 +167 -21

246 lines not on this page · raw message

fs/ocfs2/inode.h +6 -0
index 07bd838e7843..cd377bc1cca8 100644
@@ -40,6 +40,12 @@ struct ocfs2_inode_info
 
 	/* Record unwritten extents during direct io. */
 	struct list_head		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;
 
 	/* protected by recovery_lock. */
 	struct inode			*ip_next_orphan;
fs/ocfs2/mmap.c +1 -1
index 6c570157caf1..885583302c0d 100644
@@ -90,7 +90,7 @@ 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);
 	if (err) {
 		if (err != -ENOSPC)
 			mlog_errno(err);
fs/ocfs2/super.c +1 -0
index 0781c5cbdb11..daa2034c4662 100644
@@ -1632,6 +1632,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.55.0

A message that is not in the archive (sent off-list or not yet received): [email protected]

author reviewer
#5 lore raw

Re: [RESEND RFC PATCH v7 3/3] ocfs2: switch dio write path from buffer_head to iomap

Quoted 85 lines · On 11/18/26 09:15, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [High] ocfs2: ocfs2_dio_del_orphan() runs after ocfs2_dio_end_io() drops rw_lock
- [High] ocfs2: ocfs2_dio_end_io_write() passes coalesced extent_map length to split
- [High] ocfs2: data corruption in ocfs2_unwritten_check() racing with in-flight DIO
- [High] ocfs2: broken DIO-to-buffered write fallback in ocfs2_file_write_iter()
- [High] ocfs2: ocfs2_dio_del_orphan() leaks post-EOF blocks and runs after rw_unlock
- [High] ocfs2: missing rw_level upgrade after reloading append_write in ocfs2_file_write_iter()
- [Medium] ocfs2: off-by-one cluster check on -ENOSPC in ocfs2_dio_wr_map_blocks()
--

commit 1082a6db1718b4d837aed6c96b2530e3289c1d22
Author: Heming Zhao <[email protected]>

ocfs2: switch dio write path from buffer_head to iomap

This commit converts the OCFS2 direct I/O write path from the legacy buffer_head infrastructure to the iomap framework.

Quoted 4 lines
fs/ocfs2/aops.c +0 -0
index 21cdc5c29331d..8f8d8e26457bb 100644

[ ... ]

Quoted 1 line
fs/ocfs2/aops.c +0 -0
@@ -1376,76 +1717,212 @@ static void ocfs2_set_target_boundaries(struct ocfs2_super *osb,

[ ... ]

Quoted 11 lines
fs/ocfs2/aops.c +8 -0
+static void ocfs2_unwritten_check(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;
 
+	if (!desc->c_needs_zero)
+		return;
 
+	spin_lock(&oi->ip_lock);

fs/ocfs2/aops.c static void ocfs2_set_target_boundaries(struct ocfs2_super *osb, · line 1788

Quoted 10 lines
fs/ocfs2/aops.c +10 -0
+	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;

[Severity: High]
Can a buffered write or mmap page fault lose data or expose uninitialized disk blocks when it hits an in-flight direct write's unwritten entry here?

Unlike direct writes, which wait on oi->ip_unwritten_wq in ocfs2_dio_wr_map_blocks(), buffered and mmap writes clear c_needs_zero and c_clear_unwritten and proceed while the direct write is still in flight:

CPU0 (async DIO write) CPU1 (mmap fault or buffered write)
ocfs2_dio_wr_map_blocks()
ocfs2_write_begin_nolock()
ocfs2_dio_add_unwritten()
up_write(&oi->ip_alloc_sem)
ocfs2_inode_unlock()
__ocfs2_page_mkwrite()
ocfs2_write_begin_nolock()
ocfs2_unwritten_check()
c_needs_zero = 0 c_clear_unwritten = 0
ocfs2_write_cluster()
/* skips mark_extent_written */
bio_iov_iter_get_pages()

     /* fails with -EFAULT */

ocfs2_dio_end_io()
ocfs2_free_unwritten_list() <-- extent stays OCFS2_EXT_UNWRITTEN

Quoted 11 lines

Because ocfs2_dio_wr_map_blocks() maps up to 16MB at once and drops ip_alloc_sem and the inode lock before iomap pins user pages or submits bios, the direct write can fail or stop short before reaching desc->c_cpos. When that happens, neither writer converts the extent to written, so after the dirty folio is written back and evicted, reads return zeroes. In addition, ocfs2_grab_folios_direct() only zeroes page cache folios in the first and last cluster of the direct write; a partial-page buffered write to a middle cluster with c_needs_zero == 0 passes new = 0 to ocfs2_map_folio_blocks(), which issues bh_read_nowait() on the unwritten extent and reads raw disk contents into the folio around the written bytes.

This issue predates this patch set and is not a regression introduced by this submission. We will leave it unaddressed for now.

PS: If we were to fix it, one approach would be to wait for unwritten extent conversion to complete at the buffered/mmap entry points. I had an AI try this approach, and it triggered more failures in xfstests.

Quoted 28 lines

[ ... ]

Quoted 1 line
fs/ocfs2/aops.c +0 -0
@@ -2285,95 +2909,149 @@ static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock,

[ ... ]

Quoted 6 lines
fs/ocfs2/aops.c +3 -1
+again:
  	ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,
  				       OCFS2_WRITE_DIRECT, NULL,
-				       (void **)&wc, di_bh, NULL);
+				       (void **)&wc, di_bh, NULL, owner);
+	if (ret == -ENOSPC &&

fs/ocfs2/aops.c static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock, · line 2945

Quoted 10 lines
fs/ocfs2/aops.c +10 -0
+	    ocfs2_bytes_to_clusters(inode->i_sb, pos + len) >
+	    ocfs2_bytes_to_clusters(inode->i_sb, pos) + 1) {
+		/*
+		 * There is not room for all of it, but maybe there is for
+		 * some, take the first cluster.
+		 */
+		len = min_t(loff_t, len, osb->s_clustersize -
+				(pos & (osb->s_clustersize - 1)));
+		goto again;
+	}

[Severity: Medium]
Does using ocfs2_bytes_to_clusters(inode->i_sb, pos + len) here skip the single-cluster fallback when a two-cluster write does not end on a cluster boundary?

Quoted 10 lines

ocfs2_alloc_write_ctxt() computes the end cluster as
(pos + len - 1) >> osb->s_clustersize_bits, whereas ocfs2_bytes_to_clusters() shifts pos + len right without rounding up. If a write spans clusters c and c + 1 with pos + len unaligned (for example, pos = 0 and
len = s_clustersize + 4096), ocfs2_bytes_to_clusters(inode->i_sb, pos + len) is c + 1, so c + 1 > c + 1 is false and the write fails with -ENOSPC instead of retrying with the first cluster. Using ocfs2_clusters_for_bytes(inode->i_sb, pos + len) (or checking ocfs2_bytes_to_clusters(inode->i_sb, pos + len - 1) > ocfs2_bytes_to_clusters(inode->i_sb, pos)) would match wc->w_clen > 1.

will follow the suggestion logic.

Quoted 54 lines

[ ... ]

Quoted 1 line
fs/ocfs2/aops.c +0 -0
@@ -2386,54 +3064,102 @@ static int ocfs2_dio_end_io_write(struct inode *inode,

[ ... ]

Quoted 16 lines
fs/ocfs2/aops.c +16 -0
+	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;
+
+				ret = ocfs2_get_clusters(inode, cpos, &phys,
+							 &num, &ext_flags);
+				if (ret < 0) {
+					mlog_errno(ret);
+					goto commit;
+				}
+				num = min(num, cend - cpos);

[ ... ]

fs/ocfs2/aops.c static int ocfs2_dio_end_io_write(struct inode *inode,

Quoted 3 lines
fs/ocfs2/aops.c +3 -0
+				ret = ocfs2_mark_extent_written(inode, &et,
+						handle, cpos, num, phys,
+						meta_ac, &dealloc);

[Severity: High]
Can ocfs2_mark_extent_written() fail with -EIO when two adjacent on-disk unwritten extent records are physically contiguous?

ocfs2_get_clusters() consults oi->ip_extent_map, where ocfs2_try_to_merge_extent_map() coalesces adjacent logically and physically contiguous records that have the same flags into a single cache entry even when they remain separate ocfs2_extent_rec entries on disk (for instance, across a leaf extent block boundary or after filling a hole between two unwritten extents). Passing that coalesced num to ocfs2_mark_extent_written() -> ocfs2_change_extent_flag() -> ocfs2_split_extent() trips the check that the split range fits within a single on-disk extent record:

fs/ocfs2/alloc.c:ocfs2_split_extent() {
     ...
	if ((le32_to_cpu(rec->e_cpos) + le16_to_cpu(rec->e_leaf_clusters)) <
	    (le32_to_cpu(split_rec->e_cpos) + le16_to_cpu(split_rec->e_leaf_clusters))) {
		ret = -EIO;
		mlog_errno(ret);
		goto out;
	}
     ...
}
Quoted 6 lines

This aborts unwritten conversion and the i_size update in ocfs2_dio_end_io_write(), leaving the written data marked unwritten on disk so subsequent reads return zeroes. Calling ocfs2_get_clusters_nocache() in ocfs2_dio_end_io_write() avoids both the -EIO and undercounting extents_to_split in pass 0.

agree, will follow above suggestion.

Quoted 68 lines

[ ... ]

Quoted 1 line
fs/ocfs2/aops.c +0 -0
@@ -2611,10 +3278,79 @@ int ocfs2_iomap_next(const struct iomap_iter *iter, struct iomap *iomap,

[ ... ]

Quoted 25 lines
fs/ocfs2/aops.c +25 -0
+static int ocfs2_dio_end_io(struct kiocb *iocb, ssize_t size,
+			int error, unsigned int flags, int level)
+{
+	struct inode *inode = file_inode(iocb->ki_filp);
+	loff_t offset = iocb->ki_pos;
+	bool recorded = error || (flags & IOMAP_DIO_UNWRITTEN);
+	LIST_HEAD(unwritten);
+	int ret = 0;
+
+	if (recorded)
+		ocfs2_dio_collect_unwritten(inode, iocb, &unwritten);
+
+	if (error)
+		mlog_ratelimited(ML_ERROR, "Direct IO failed, bytes = %lld errno:%d",
+				 (long long)size, error);
+
+	/* bounced back to buffered I/O, leave the rw_lock held */
+	if (size == 0 && error == 0) {
+		ocfs2_free_unwritten_list(inode, &unwritten);
+		return 0;
+	}
+
+	if (size && error == 0 &&
+	    (!list_empty(&unwritten) ||
+	     (offset + size > i_size_read(inode)))) {

fs/ocfs2/aops.c int ocfs2_iomap_next(const struct iomap_iter *iter, struct iomap *iomap, · line 3340

Quoted 10 lines
fs/ocfs2/aops.c +10 -0
+		ret = ocfs2_dio_end_io_write(inode, offset, size, &unwritten);
+		if (ret < 0)
+			mlog_errno(ret);
+	}
+
+	ocfs2_free_unwritten_list(inode, &unwritten);
+	ocfs2_rw_unlock(inode, level);
+
+	return ret ? ret : error;
+}

[Severity: High]
Does dropping ocfs2_rw_unlock() here before ocfs2_file_write_iter() calls ocfs2_dio_del_orphan() allow a writer on another node to race on the orphan entry?

inode_lock() only serializes writers on the local node; across the cluster, extending direct writes are serialized by the EX rw_lock. Because iomap_dio_complete() runs ocfs2_dio_end_io() before returning to ocfs2_file_write_iter(), the cluster rw_lock is released while OCFS2_DIO_ORPHANED_FL is still set on disk:

Node 1 Node 2
ocfs2_file_write_iter()
ocfs2_rw_lock(inode, 1)
ocfs2_add_inode_to_orphan()
...
iomap_dio_complete()

     ocfs2_dio_end_io()
       ocfs2_dio_end_io_write()
       ocfs2_rw_unlock(inode, 1)
                                   ocfs2_file_write_iter()
                                     ocfs2_rw_lock(inode, 1)
                                     ocfs2_add_inode_to_orphan()
                                       /* sees OCFS2_DIO_ORPHANED_FL,
                                        * cleans up and re-orphans for
                                        * Node 2's write */
Quoted 5 lines

ocfs2_dio_del_orphan()
ocfs2_del_inode_from_orphan() <-- removes Node 2's active orphan

If Node 2 crashes during its extending write, the blocks allocated beyond i_size will not be truncated during orphan recovery.

I will move del_orphan operation in end_io API (restore the old logic). btw, ocfs2 uses different node uses itself orphan:xxx to save orphan inode.

Quoted 45 lines
Quoted 5 lines
fs/ocfs2/file.c +0 -0
index 3d717200d53a4..334ee74dfdea3 100644

[ ... ]

Quoted 22 lines
fs/ocfs2/file.c +18 -0
@@ -2420,6 +2429,35 @@ static bool ocfs2_should_use_dio(struct kiocb *iocb, struct iov_iter *iter,
  	return true;
  }
 
+/*
+ * Remove the inode from the orphan dir after an appending direct write.
+ * Only the writer that added the inode (under i_rwsem) may remove it;
+ */
+static int ocfs2_dio_del_orphan(struct inode *inode)
+{
+	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+	struct buffer_head *di_bh = NULL;
+	struct ocfs2_dinode *di;
+	int ret;
+
+	ret = ocfs2_inode_lock(inode, &di_bh, 1);
+	if (ret < 0) {
+		mlog_errno(ret);
+		return ret;
+	}
+
+	di = (struct ocfs2_dinode *)di_bh->b_data;

fs/ocfs2/file.c static bool ocfs2_should_use_dio(struct kiocb *iocb, struct iov_iter *iter, · line 2459

Quoted 10 lines
fs/ocfs2/file.c +10 -0
+	if (di->i_flags & cpu_to_le32(OCFS2_DIO_ORPHANED_FL)) {
+		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);
+	return ret;
+}

[Severity: High]
Does ocfs2_dio_del_orphan() leak blocks allocated beyond EOF when an extending direct write fails or completes short?

Quoted 10 lines

In ocfs2_file_write_iter(), fault_in_iov_iter_readable() is only called when iocb->ki_pos > i_size_read(inode), so an append write starting at iocb->ki_pos == i_size_read(inode) with an unmapped user buffer allocates clusters in ocfs2_dio_wr_map_blocks() (and in ocfs2_dio_zero_eof() on non-sparse filesystems) before bio_iov_iter_get_pages() fails with -EFAULT. At the out: label, ocfs2_file_write_iter() unconditionally calls ocfs2_dio_del_orphan(), which deletes the orphan entry and clears OCFS2_DIO_ORPHANED_FL without calling ocfs2_truncate_file(inode, di_bh, i_size_read(inode)), leaving the blocks and quota allocated past i_size permanently attached to the inode.

I will fix this in next version.

Quoted 18 lines

[ ... ]

fs/ocfs2/file.c static ssize_t ocfs2_file_write_iter(struct kiocb *iocb, · line 2574

Quoted 9 lines
fs/ocfs2/file.c +3 -2
@@ -2527,26 +2569,123 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
  		saved_ki_complete = xchg(&iocb->ki_complete, NULL);
  	}
 
-	/* communicate with ocfs2_dio_end_io */
-	ocfs2_iocb_set_rw_locked(iocb, rw_level);
+	/* reload value after inode_lock() and cluster lock */
+	append_write = ((iocb->ki_pos + count) >=
+			i_size_read(inode) ? 1 : 0);

[Severity: High]
If append_write changes from 0 to 1 when reloaded here under coherency=buffered, does the extending direct write run with only a shared PR rw_lock?

Quoted 9 lines

rw_level is computed and passed to ocfs2_rw_lock() before generic_write_checks() updates iocb->ki_pos for O_APPEND / RWF_APPEND and before ocfs2_prepare_inode_for_write() refreshes i_size under the cluster lock. When direct_io == 1 and full_coherency == 0, if iocb->ki_pos + count was initially below the stale i_size (for example, an O_APPEND write with ki_pos == 0 and count < i_size), rw_level is 0 (PR). Reloading append_write to 1 here does not upgrade rw_level to 1 (EX), so orphan manipulation, EOF zeroing, block allocation, and i_size updates proceed under a shared PR rw_lock and use ocfs2_iomap_dio_ops_w_pr.

In my view, this is existing issue. ignore it.

Quoted 28 lines

[ ... ]

Quoted 9 lines
fs/ocfs2/file.c +9 -0
+		if (written == -ENOTBLK)
+			written = 0;
+		if (written == 0 && iov_iter_count(from)) {
+			written = direct_write_fallback(iocb, from, ret,
+					generic_perform_write(iocb, from));
+		}
+	} else {
+		iocb->ki_flags &= ~IOCB_DIRECT;
+		written = __generic_file_write_iter(iocb, from);

fs/ocfs2/file.c static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,

Quoted 10 lines
fs/ocfs2/file.c +3 -0
  	}
 
+	/* buffered aio wouldn't have proper lock coverage today */
+	BUG_ON(written == -EIOCBQUEUED && !direct_io);
+
  	if (unlikely(written <= 0))
  		goto out;
 
  	if (((file->f_flags & O_DSYNC) && !direct_io) ||
  	    IS_SYNC(inode)) {

[Severity: High]
When an O_DIRECT write falls back to buffered I/O here, are O_DSYNC, page cache flushing/invalidation, exclusive rw_lock coverage, and IOCB_NOWAIT handled properly?

Quoted 15 lines

In the else branch (!ocfs2_should_use_dio()), clearing IOCB_DIRECT before calling __generic_file_write_iter() causes it to skip direct_write_fallback(), so dirty pages are neither written back nor invalidated from the page cache. On both fallback paths, direct_io remains 1, which skips the ((file->f_flags & O_DSYNC) && !direct_io) block below and returns from an O_DSYNC write without forcing a journal commit or waiting on writeback. Moreover, if coherency=buffered and append_write == 0, both fallback paths perform buffered writes while holding only a shared PR rw_lock (rw_level == 0), and if IOCB_NOWAIT is set, they block in generic_perform_write() -> ocfs2_write_begin() instead of returning -EAGAIN or -EOPNOTSUPP. Also, in the -ENOTBLK fallback call to direct_write_fallback(), passing ret (the return value of ocfs2_dio_zero_eof(), which is 0) works only because written is 0; passing written would be clearer.

partly agree: direct_write_fallback() should use 0 instead of 'ret'. the direct fallback logic should be modified. Others are existing issues.

Thanks,
Heming