From: Joseph Qi <joseph.qi@linux.alibaba.com>
To: Heming Zhao <heming.zhao@suse.com>, hch@lst.de
Cc: Andrew Morton <akpm@linux-foundation.org>,
Mark Fasheh <mark@fasheh.com>, Joel Becker <jlbec@evilplan.org>,
ocfs2-devel@lists.linux.dev, linux-kernel@vger.kernel.org,
Joseph Qi <joseph.qi@linux.alibaba.com>
Subject: [RFC PATCH v13 07/10] ocfs2: switch dio write path from buffer_head to iomap
Date: Mon, 30 Nov 2026 18:02:00 +0800 [thread overview]
Message-ID: <20261130100203.383093-8-joseph.qi@linux.alibaba.com> (raw)
In-Reply-To: <20261130100203.383093-1-joseph.qi@linux.alibaba.com>
From: Heming Zhao <heming.zhao@suse.com>
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.
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 after completing a prefix still has that prefix
on disk. Convert it and let iomap report dio->size, as the buffer_head
path did, instead of discarding it and returning only an errno. The
zeroed folios are only dropped when nothing is converted, so the prefix
keeps its zeroes.
Co-developed-by: Joseph Qi <joseph.qi@linux.alibaba.com>
Signed-off-by: Joseph Qi <joseph.qi@linux.alibaba.com>
Signed-off-by: Heming Zhao <heming.zhao@suse.com>
---
fs/ocfs2/Kconfig | 1 -
fs/ocfs2/aops.c | 1014 +++++++++++++++++++++++++++++++++-------------
fs/ocfs2/aops.h | 33 +-
fs/ocfs2/file.c | 272 +++++++++++--
fs/ocfs2/inode.h | 8 +-
fs/ocfs2/super.c | 2 +
6 files changed, 983 insertions(+), 347 deletions(-)
diff --git a/fs/ocfs2/Kconfig b/fs/ocfs2/Kconfig
index bf1678a5eb01e..74bc2008ef0bf 100644
--- a/fs/ocfs2/Kconfig
+++ b/fs/ocfs2/Kconfig
@@ -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
diff --git a/fs/ocfs2/aops.c b/fs/ocfs2/aops.c
index e3e28584e7410..66be8ae74b6f6 100644
--- a/fs/ocfs2/aops.c
+++ b/fs/ocfs2/aops.c
@@ -951,6 +951,8 @@ static void ocfs2_free_write_ctxt(struct inode *inode,
{
ocfs2_free_unwritten_list(inode, &wc->w_unwritten_list);
ocfs2_unlock_folios(wc);
+ /* After the folios are unlocked, like ocfs2_write_end_nolock(). */
+ ocfs2_run_deallocs(OCFS2_SB(inode->i_sb), &wc->w_dealloc);
brelse(wc->w_di_bh);
ocfs2_release_write_ctxt(wc);
}
@@ -1746,6 +1748,30 @@ ocfs2_find_unwritten(struct ocfs2_inode_info *oi, u32 cpos)
return NULL;
}
+/*
+ * Is there an entry, which does not belong to @owner, on the clusters
+ * [cpos, cend)? That is, is another dio which is still in flight in charge of
+ * some of them?
+ */
+static bool ocfs2_dio_foreign_unwritten(struct ocfs2_inode_info *oi,
+ u32 cpos, u32 cend, void *owner)
+{
+ struct ocfs2_unwritten_extent *ue;
+ bool found = false;
+
+ spin_lock(&oi->ip_lock);
+ list_for_each_entry(ue, &oi->ip_unwritten_list, ue_ip_node) {
+ if (ue->ue_owner != owner && ue->ue_cpos < cend &&
+ cpos < ue->ue_cpos + ue->ue_clusters) {
+ found = true;
+ break;
+ }
+ }
+ spin_unlock(&oi->ip_lock);
+
+ return found;
+}
+
/*
* 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
@@ -1784,6 +1810,17 @@ static void ocfs2_unwritten_check_locked(struct inode *inode,
*/
desc->c_needs_zero = 0;
desc->c_clear_unwritten = 0;
+ /* match its own entry */
+ if (wc->w_type == OCFS2_WRITE_DIRECT && wc->w_owner &&
+ ue->ue_owner == wc->w_owner)
+ desc->c_dio_unwritten = 1;
+ else
+ /*
+ * Not ours. A direct write never gets here, it waits
+ * for the entries of the other dios before it maps,
+ * see ocfs2_dio_wr_map_blocks().
+ */
+ WARN_ON_ONCE(wc->w_type == OCFS2_WRITE_DIRECT);
} else if (wc->w_type == OCFS2_WRITE_DIRECT) {
/* This direct write will doing zero. */
desc->c_clear_unwritten = 0;
@@ -2747,6 +2784,524 @@ static int ocfs2_write_end(const struct kiocb *iocb,
return ret;
}
+/*
+ * Prepare the area between i_size and a direct write that starts or ends
+ * beyond it. Must be called once per dio, before any io is issued, with
+ * i_rwsem and the rw lock held.
+ */
+int ocfs2_dio_zero_eof(struct inode *inode, loff_t pos, size_t count)
+{
+ struct ocfs2_inode_info *oi = OCFS2_I(inode);
+ struct buffer_head *di_bh = NULL;
+ int ret;
+ loff_t isize = i_size_read(inode);
+
+ if (pos + count <= isize)
+ return 0;
+
+ /*
+ * ocfs2_zero_tail() only zeroes a gap past i_size, so on a sparse
+ * volume there is nothing to do here and no need to take the cluster
+ * lock. The non-sparse path below always has allocation work left.
+ */
+ if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)) && pos <= isize)
+ return 0;
+
+ ret = ocfs2_inode_lock(inode, &di_bh, 1);
+ if (ret) {
+ mlog_errno(ret);
+ return ret;
+ }
+
+ down_write(&oi->ip_alloc_sem);
+ if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)))
+ ret = ocfs2_zero_tail(inode, di_bh, pos);
+ else
+ ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, count,
+ NULL);
+ if (ret < 0)
+ mlog_errno(ret);
+ up_write(&oi->ip_alloc_sem);
+
+ ocfs2_inode_unlock(inode, 1);
+ brelse(di_bh);
+ return ret;
+}
+
+/*
+ * The most a single mapping handed out for a direct write spans.
+ * It bounds the memory of the write context, one descriptor per
+ * cluster.
+ */
+#define OCFS2_DIO_MAX_MAP_BYTES (16U << 20)
+/* A mapping always leaves room for at least one whole cluster. */
+static_assert(OCFS2_DIO_MAX_MAP_BYTES > OCFS2_MAX_CLUSTERSIZE);
+
+/*
+ * Preparing a direct write of an unwritten or newly allocated cluster
+ * leaves the head and the tail folios of the cluster zeroed, mapped to the
+ * cluster's physical blocks and dirty in the page cache, outside the range
+ * iomap invalidates when the write is done. On failure the conversion does
+ * not happen; if the buffers are written back after the clusters have been
+ * freed and reused, they corrupt whatever owns them then.
+ *
+ * If no cluster was converted to written, the zeroes are not needed and the
+ * pages can simply be dropped. If some clusters were converted, their
+ * zeroes must reach the disk while the clusters are still ours. The
+ * head/tail can be fully beyond i_size until the io completes, and generic
+ * writeback refuses to write such folios, so write the buffer_heads
+ * directly, bypassing the i_size check.
+ *
+ * The folios are grabbed per cluster, and one of them can be before the
+ * range the caller passes (the head of the first cluster when the write
+ * starts inside of it), so the range is rounded out to whole clusters.
+ *
+ * Must be called with the folios unlocked and without the inode lock or
+ * ip_alloc_sem.
+ */
+static int ocfs2_write_range_buffers(struct inode *inode, loff_t start,
+ loff_t end)
+{
+ struct address_space *mapping = inode->i_mapping;
+ pgoff_t first = start >> PAGE_SHIFT;
+ pgoff_t last = (end - 1) >> PAGE_SHIFT;
+ pgoff_t index;
+ int ret = 0;
+
+ for (index = first; index <= last; index++) {
+ struct folio *folio = filemap_lock_folio(mapping, index);
+ struct buffer_head *bh, *head;
+ int err;
+
+ if (IS_ERR(folio)) {
+ if (PTR_ERR(folio) != -ENOENT && !ret)
+ ret = PTR_ERR(folio);
+ continue;
+ }
+
+ folio_wait_writeback(folio);
+ head = folio_buffers(folio);
+ if (head) {
+ bh = head;
+ do {
+ if (!buffer_dirty(bh))
+ goto next;
+ if (!buffer_mapped(bh) || !buffer_uptodate(bh) ||
+ buffer_delay(bh) || buffer_unwritten(bh)) {
+ if (!ret)
+ ret = -EIO;
+ goto next;
+ }
+
+ get_bh(bh);
+ err = sync_dirty_buffer(bh);
+ brelse(bh);
+ if (err && !ret)
+ ret = err;
+next:
+ bh = bh->b_this_page;
+ } while (bh != head);
+ }
+ folio_unlock(folio);
+ folio_put(folio);
+ }
+
+ return ret;
+}
+
+/*
+ * Drop, or write out and then drop, the page cache of one whole cluster.
+ * @start and @end are cluster aligned.
+ *
+ * Must be called with the folios unlocked and without the inode lock or
+ * ip_alloc_sem.
+ */
+static void ocfs2_dio_cleanup_range(struct inode *inode, loff_t start,
+ loff_t end, bool write_zeroes)
+{
+ struct address_space *mapping = inode->i_mapping;
+ int ret, werr = 0;
+
+ if (start >= end)
+ return;
+
+ if (!write_zeroes) {
+ /*
+ * No cluster was converted to written, so the zeroes are not
+ * needed. Discard the pages together with their dirty buffers
+ * instead of writing them out.
+ */
+ truncate_inode_pages_range(mapping, start, end - 1);
+ return;
+ }
+
+ werr = ocfs2_write_range_buffers(inode, start, end);
+ if (werr < 0)
+ mlog_errno(werr);
+
+ ret = invalidate_inode_pages2_range(mapping, start >> PAGE_SHIFT,
+ (end - 1) >> PAGE_SHIFT);
+ if (ret < 0) {
+ if (ret == -EBUSY && werr == 0) {
+ /*
+ * A faulting mmap redirtied a page after we wrote it;
+ * it is not ours to drop anymore.
+ */
+ } else {
+ mlog_errno(ret);
+ }
+ }
+}
+
+/*
+ * Clean up a run of clusters a direct write recorded. Only its first and its
+ * last cluster can hold folios the write zeroed: ocfs2_grab_folios_direct()
+ * fills a window for w_desc[0] and one for w_desc[w_clen - 1] and nothing else.
+ * The clusters in between are covered by the user range and have no page cache
+ * page from this write, but they can hold dirty folios of other writes sharing
+ * the cluster, which must not be dropped.
+ */
+static void ocfs2_dio_cleanup_clusters(struct inode *inode, u32 cpos,
+ u32 clusters, bool write_zeroes)
+{
+ unsigned int cshift = OCFS2_SB(inode->i_sb)->s_clustersize_bits;
+
+ ocfs2_dio_cleanup_range(inode, (loff_t)cpos << cshift,
+ (loff_t)(cpos + 1) << cshift, write_zeroes);
+ if (clusters > 1)
+ ocfs2_dio_cleanup_range(inode,
+ (loff_t)(cpos + clusters - 1) << cshift,
+ (loff_t)(cpos + clusters) << cshift,
+ write_zeroes);
+}
+
+/*
+ * The entries of ip_unwritten_list which belong to a direct write
+ * have been created while the write context was alive, they have to
+ * survive it: they stay until ocfs2_dio_end_io() has converted the
+ * clusters. Take them off the write context, so that it can be
+ * released.
+ */
+static void ocfs2_dio_detach_unwritten(struct ocfs2_write_ctxt *wc)
+{
+ struct ocfs2_unwritten_extent *ue, *tmp;
+
+ list_for_each_entry_safe(ue, tmp, &wc->w_unwritten_list, ue_node)
+ list_del_init(&ue->ue_node);
+}
+
+/*
+ * Map a range of a direct write, allocate the clusters if needed.
+ *
+ * Contrary to the single cluster it was before, a mapping spans as many
+ * clusters as iomap asks for, up to the first thing that makes it unfit to
+ * be handed out as one: the kind of the extent (hole, unwritten, written),
+ * a discontiguous extent, or the end of the file. The latter is the one
+ * place where the mapping is split on purpose:
+ *
+ * eof_blk
+ * |--------|---------|---------|---------
+ * |<-in file range-->|<-past eof range-->
+ *
+ * the part which is in the file is not NEW, it may have data which must
+ * not be zeroed. The part which is beyond it is NEW. As the file size is
+ * only changed when the io is done, both are told apart here.
+ *
+ * Whatever is unwritten and zeroed here is recorded in ip_unwritten_list
+ * for ocfs2_dio_end_io() to convert, find them there by @owner.
+ *
+ * @map->lblk and @map->len go in, the mapping goes out.
+ */
+static int ocfs2_dio_wr_map_blocks(struct inode *inode,
+ struct ocfs2_map_block *map,
+ unsigned int flags, void *owner)
+{
+ struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+ struct ocfs2_inode_info *oi = OCFS2_I(inode);
+ struct ocfs2_write_ctxt *wc;
+ struct ocfs2_write_cluster_desc *desc;
+ struct ocfs2_map_block probe;
+ struct buffer_head *di_bh = NULL;
+ unsigned int blkbits = inode->i_sb->s_blocksize_bits;
+ u64 bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
+ u64 lblk = map->lblk;
+ u64 req_len = map->len;
+ u64 eof_blk, cap_end;
+ loff_t pos = lblk << blkbits;
+ loff_t len, end, touched_end = 0;
+ u32 cstart, cend;
+ int ret = 0, unwritten;
+
+retry:
+ map->len = req_len;
+ map->flags = 0;
+ eof_blk = ocfs2_blocks_for_bytes(inode->i_sb, i_size_read(inode));
+
+ /* Do not hand out a mapping which is over the end of the file. */
+ if (lblk < eof_blk && lblk + map->len > eof_blk)
+ map->len = eof_blk - lblk;
+
+ map->len = min_t(u64, map->len, OCFS2_DIO_MAX_MAP_BYTES >> blkbits);
+
+ /*
+ * Compute the end of the cap in blocks directly. Near s_maxbytes the
+ * cluster number of pos + OCFS2_DIO_MAX_MAP_BYTES does not fit in the
+ * u32 argument of ocfs2_clusters_to_blocks(), and the truncated value
+ * would make the subtraction below wrap around.
+ */
+ cap_end = ((u64)pos + OCFS2_DIO_MAX_MAP_BYTES) >>
+ osb->s_clustersize_bits;
+ cap_end *= bpc;
+ map->len = min_t(u64, map->len, cap_end - lblk);
+
+ /*
+ * Unwritten clusters which another dio, still in flight, has recorded
+ * are not ours to map. That dio converts them when it is done, and it
+ * may not get there: it can fail or end short. If we reported them
+ * as MAPPED, our data would sit in an unwritten extent that nobody
+ * is going to make written, and would read back as zeroes, even though
+ * our write has succeeded. Reporting them as UNWRITTEN would have us
+ * convert them while that dio has not written its own data yet. So
+ * wait until it is finished. Afterwards the clusters are either
+ * written, or unwritten and nobody is in charge of them, then it is
+ * our job.
+ *
+ * This has to come before the re-write fast path below. A dio which
+ * fails part way through its conversion has already made some clusters
+ * written and dropped the locks, but it still owns the records and is
+ * about to write the zeroed head/tail buffers over them. The fast path
+ * would see those clusters as MAPPED and hand them out, and our data
+ * would be overwritten by those zeroes. The records are only removed
+ * after that cleanup, so waiting here excludes it.
+ *
+ * i_rwsem is held, no other dio can start and record clusters while
+ * we wait, only the completions of those in flight run, and they
+ * only remove entries. The inode lock and ip_alloc_sem, which
+ * ->end_io() takes to convert, must not be held here.
+ */
+ cstart = pos >> osb->s_clustersize_bits;
+ cend = ocfs2_clusters_for_bytes(inode->i_sb,
+ pos + ((loff_t)map->len << blkbits));
+ if (ocfs2_dio_foreign_unwritten(oi, cstart, cend, owner)) {
+ if (flags & IOMAP_NOWAIT)
+ return -EAGAIN;
+ ret = wait_event_killable(oi->ip_unwritten_wq,
+ !ocfs2_dio_foreign_unwritten(oi, cstart, cend,
+ owner));
+ if (ret)
+ return ret;
+ /* The file may have been extended and mapped in the meantime. */
+ goto retry;
+ }
+
+ /*
+ * This is the fast path for re-write. The range which is in the file
+ * has nothing to allocate nor to convert if it is mapped already. What
+ * changes the file size is done at the end of io, no matter what the
+ * mappings were.
+ */
+ if (lblk < eof_blk) {
+ probe = *map;
+ probe.flags = 0;
+ ret = ocfs2_lock_map_blocks(inode, &probe,
+ OCFS2_GET_BLOCKS_CREATE,
+ flags & IOMAP_NOWAIT);
+ if (ret == 0 && (probe.flags & OCFS2_MAP_MAPPED) &&
+ !(probe.flags & OCFS2_MAP_NEW)) {
+ *map = probe;
+ return 0;
+ }
+ ret = 0;
+ }
+
+ /* The allocation below sleeps on locks. */
+ if (flags & IOMAP_NOWAIT)
+ return -EAGAIN;
+
+ ret = ocfs2_inode_lock(inode, &di_bh, 1);
+ if (ret) {
+ mlog_errno(ret);
+ goto out;
+ }
+
+ down_write(&oi->ip_alloc_sem);
+
+ /*
+ * Only take what is of the same kind as what is at the start:
+ * all of it is a hole, or all of it is unwritten, or all of
+ * it is written, in one extent.
+ */
+ probe = *map;
+ probe.flags = 0;
+ ret = ocfs2_map_blocks(inode, &probe, 0);
+ if (ret) {
+ mlog_errno(ret);
+ goto unlock;
+ }
+ map->len = min_t(u64, map->len, probe.len);
+ len = map->len << blkbits;
+
+ /*
+ * Note, Zeroing the gap between i_size and the write is done
+ * once per dio by ocfs2_dio_zero_eof() before the io is issued.
+ */
+
+ /*
+ * Remember what this attempt covers: if it fails after it has
+ * zeroed the head/tail folios, the folios have to be cleaned up
+ * behind the locks, see out below. touched_end stays at pos when
+ * nothing was zeroed, and is 0 when the write context was never
+ * reached.
+ */
+ ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,
+ OCFS2_WRITE_DIRECT, NULL,
+ (void **)&wc, di_bh, NULL, owner,
+ &touched_end);
+ if (ret) {
+ if (ret != -ENOSPC && ret != -EDQUOT)
+ mlog_errno(ret);
+ goto unlock;
+ }
+
+ /*
+ * The write context says how many of the clusters are really there.
+ * It is within what we asked for, what is mapped is up to the end of
+ * the last of them.
+ */
+ desc = &wc->w_desc[0];
+ end = min_t(loff_t, pos + len,
+ ocfs2_clusters_to_bytes(inode->i_sb,
+ wc->w_cpos + wc->w_clen));
+
+ if (desc->c_phys == 0) {
+ ret = -EIO;
+ mlog_errno(ret);
+ if (wc->w_handle)
+ ocfs2_commit_trans(osb, wc->w_handle);
+ ocfs2_free_write_ctxt(inode, wc);
+ goto unlock;
+ }
+
+ map->pblk = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys) +
+ (lblk & (bpc - 1));
+ map->len = (end >> blkbits) - lblk;
+
+ /*
+ * Only report the mapping as UNWRITTEN when the cluster is newly
+ * allocated or was already unwritten and this write is the one who
+ * is going to convert it.
+ */
+ unwritten = ocfs2_desc_dio_unwritten(desc);
+ map->flags = unwritten ? OCFS2_MAP_UNWRITTEN : OCFS2_MAP_MAPPED;
+ if (unwritten || lblk >= eof_blk)
+ map->flags |= OCFS2_MAP_NEW;
+
+ ocfs2_dio_detach_unwritten(wc);
+ /* Here returns only two types: len (success), errno (failure). */
+ ret = ocfs2_write_end_nolock(inode->i_mapping, pos, end - pos,
+ end - pos, wc);
+ if (ret < 0) {
+ mlog_errno(ret);
+ goto unlock;
+ }
+ WARN_ON_ONCE(ret != end - pos);
+ ret = 0;
+
+unlock:
+ up_write(&oi->ip_alloc_sem);
+ ocfs2_inode_unlock(inode, 1);
+ brelse(di_bh);
+
+out:
+ /*
+ * ocfs2_write_begin_nolock() can already have zeroed and committed
+ * the head/tail folios before failing, in which case this mapping
+ * has no unwritten record for end_io() to find. Clean them up
+ * here. The folios have been unlocked by the failing path, and
+ * the successful paths must not clean anything.
+ */
+ if (ret < 0 && touched_end > pos) {
+ u32 cpos = pos >> osb->s_clustersize_bits;
+ u32 last = (touched_end - 1) >> osb->s_clustersize_bits;
+
+ ocfs2_dio_cleanup_clusters(inode, cpos, last - cpos + 1, false);
+ }
+
+ return ret;
+}
+
+/*
+ * Take the unwritten clusters recorded by the direct write @owner,
+ * off the inode's list, to a private list.
+ */
+static void ocfs2_dio_collect_unwritten(struct inode *inode, void *owner,
+ struct list_head *head)
+{
+ struct ocfs2_inode_info *oi = OCFS2_I(inode);
+ struct ocfs2_unwritten_extent *ue;
+
+ spin_lock(&oi->ip_lock);
+ list_for_each_entry(ue, &oi->ip_unwritten_list, ue_ip_node) {
+ if (ue->ue_owner == owner)
+ list_add_tail(&ue->ue_node, head);
+ }
+ spin_unlock(&oi->ip_lock);
+}
+
+/*
+ * Undo the orphan dir entry an extending direct write has added.
+ *
+ * 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.
+ *
+ * TODO: ocfs2_recover_orphans() still truncates to i_size, so dead-slot
+ * recovery can still free FALLOC_FL_KEEP_SIZE extents. That predates the
+ * iomap conversion.
+ */
+static void ocfs2_dio_clear_orphan_locked(struct inode *inode,
+ struct buffer_head *di_bh)
+{
+ struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+ struct ocfs2_inode_info *oi = OCFS2_I(inode);
+ struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
+ int ret = 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); /* leave the entry to the recovery */
+ return;
+ }
+
+ /*
+ * Only drop the marker once the entry is gone. Keeping it while the
+ * entry survives lets the next extending write recover it, see
+ * ocfs2_add_inode_to_orphan().
+ */
+ WRITE_ONCE(oi->ip_dio_orphan_pid, 0);
+}
+
+/*
+ * Does nothing when this task is not the one which added the entry.
+ * The rw_lock has to be held.
+ */
+void ocfs2_dio_clear_orphan(struct inode *inode)
+{
+ struct buffer_head *di_bh = NULL;
+
+ if (READ_ONCE(OCFS2_I(inode)->ip_dio_orphan_pid) !=
+ task_pid_nr(current))
+ return;
+
+ if (ocfs2_inode_lock(inode, &di_bh, 1) < 0)
+ return;
+ ocfs2_dio_clear_orphan_locked(inode, di_bh);
+ ocfs2_inode_unlock(inode, 1);
+ brelse(di_bh);
+}
+
/*
* Convert the unwritten extents of a direct write, which is finished,
* and change the file size if it has been extended.
@@ -2940,6 +3495,9 @@ static int ocfs2_dio_end_io_write(struct inode *inode,
meta_ac = NULL;
}
+ if (!ret && READ_ONCE(oi->ip_dio_orphan_pid) == task_pid_nr(current))
+ ocfs2_dio_clear_orphan_locked(inode, di_bh);
+
ocfs2_inode_unlock(inode, 1);
brelse(di_bh);
@@ -2948,292 +3506,14 @@ static int ocfs2_dio_end_io_write(struct inode *inode,
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;
- int dw_orphaned;
- pid_t dw_writer_pid;
-};
-
-static struct ocfs2_dio_write_ctxt *
-ocfs2_dio_alloc_write_ctx(struct buffer_head *bh, int *alloc)
-{
- struct ocfs2_dio_write_ctxt *dwc = NULL;
-
- if (bh->b_private)
- return bh->b_private;
-
- dwc = kmalloc_obj(struct ocfs2_dio_write_ctxt, GFP_NOFS);
- if (dwc == NULL)
- return NULL;
- INIT_LIST_HEAD(&dwc->dw_zero_list);
- dwc->dw_orphaned = 0;
- dwc->dw_writer_pid = task_pid_nr(current);
- bh->b_private = dwc;
- *alloc = 1;
-
- return dwc;
-}
-
-static void ocfs2_dio_free_write_ctx(struct inode *inode,
- struct ocfs2_dio_write_ctxt *dwc)
-{
- ocfs2_free_unwritten_list(inode, &dwc->dw_zero_list);
- kfree(dwc);
-}
-
-
/*
- * TODO: Make this into a generic get_blocks function.
- *
- * From do_direct_io in direct-io.c:
- * "So what we do is to permit the ->get_blocks function to populate
- * bh.b_size with the size of IO which is permitted at this offset and
- * this i_blkbits."
- *
- * This function is called directly from get_more_blocks in direct-io.c.
- *
- * called like this: dio->get_blocks(dio->inode, fs_startblk,
- * fs_count, map_bh, dio->rw == WRITE);
+ * The mapping for a direct write needs the owner, ocfs2_iomap_next() fetches
+ * it from iomap_iter.private, which is the kiocb ocfs2_file_write_iter() has
+ * called __iomap_dio_rw() with. ocfs2_dio_end_io() gets the same kiocb.
*/
-static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock,
- struct buffer_head *bh_result, int create)
-{
- struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
- struct ocfs2_inode_info *oi = OCFS2_I(inode);
- struct ocfs2_write_ctxt *wc;
- struct ocfs2_write_cluster_desc *desc = NULL;
- struct ocfs2_dio_write_ctxt *dwc = NULL;
- struct buffer_head *di_bh = NULL;
- u64 p_blkno;
- unsigned int i_blkbits = inode->i_sb->s_blocksize_bits;
- loff_t pos = iblock << i_blkbits;
- sector_t endblk = (i_size_read(inode) - 1) >> i_blkbits;
- unsigned len, total_len = bh_result->b_size;
- int ret = 0, first_get_block = 0;
-
- len = osb->s_clustersize - (pos & (osb->s_clustersize - 1));
- len = min(total_len, len);
-
- /*
- * bh_result->b_size is count in get_more_blocks according to write
- * "pos" and "end", we need map twice to return different buffer state:
- * 1. area in file size, not set NEW;
- * 2. area out file size, set NEW.
- *
- * iblock endblk
- * |--------|---------|---------|---------
- * |<-------area in file------->|
- */
-
- if ((iblock <= endblk) &&
- ((iblock + ((len - 1) >> i_blkbits)) > endblk))
- len = (endblk - iblock + 1) << i_blkbits;
-
- mlog(0, "get block of %llu at %llu:%u req %u\n",
- inode->i_ino, pos, len, total_len);
-
- /*
- * Because we need to change file size in ocfs2_dio_end_io_write(), or
- * we may need to add it to orphan dir. So can not fall to fast path
- * while file size will be changed.
- */
- if (pos + total_len <= i_size_read(inode)) {
-
- /* This is the fast path for re-write. */
- ret = ocfs2_lock_get_block(inode, iblock, bh_result, create);
- if (buffer_mapped(bh_result) &&
- !buffer_new(bh_result) &&
- ret == 0)
- goto out;
-
- /* Clear state set by ocfs2_get_block. */
- bh_result->b_state = 0;
- }
-
- dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block);
- if (unlikely(dwc == NULL)) {
- ret = -ENOMEM;
- mlog_errno(ret);
- goto out;
- }
-
- if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) >
- ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) &&
- !dwc->dw_orphaned) {
- /*
- * when we are going to alloc extents beyond file size, add the
- * inode to orphan dir, so we can recall those spaces when
- * system crashed during write.
- */
- ret = ocfs2_add_inode_to_orphan(osb, inode);
- if (ret < 0) {
- mlog_errno(ret);
- goto out;
- }
- dwc->dw_orphaned = 1;
- }
-
- ret = ocfs2_inode_lock(inode, &di_bh, 1);
- if (ret) {
- mlog_errno(ret);
- goto out;
- }
-
- down_write(&oi->ip_alloc_sem);
-
- if (first_get_block) {
- if (ocfs2_sparse_alloc(osb))
- ret = ocfs2_zero_tail(inode, di_bh, pos);
- else
- ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos,
- total_len, NULL);
- if (ret < 0) {
- mlog_errno(ret);
- goto unlock;
- }
- }
-
- ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,
- OCFS2_WRITE_DIRECT, NULL,
- (void **)&wc, di_bh, NULL, dwc, NULL);
- if (ret) {
- mlog_errno(ret);
- goto unlock;
- }
-
- desc = &wc->w_desc[0];
-
- p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys);
- BUG_ON(p_blkno == 0);
- p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1);
-
- map_bh(bh_result, inode->i_sb, p_blkno);
- bh_result->b_size = len;
- if (desc->c_needs_zero)
- set_buffer_new(bh_result);
-
- if (iblock > endblk)
- set_buffer_new(bh_result);
-
- /* May sleep in end_io. It should not happen in a irq context. So defer
- * it to dio work queue. */
- set_buffer_defer_completion(bh_result);
-
- if (!list_empty(&wc->w_unwritten_list)) {
- struct ocfs2_unwritten_extent *ue = NULL;
-
- ue = list_first_entry(&wc->w_unwritten_list,
- struct ocfs2_unwritten_extent,
- ue_node);
- BUG_ON(ue->ue_cpos != desc->c_cpos);
- list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list);
- }
-
- ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc);
- BUG_ON(ret != len);
- ret = 0;
-unlock:
- up_write(&oi->ip_alloc_sem);
- ocfs2_inode_unlock(inode, 1);
- brelse(di_bh);
-out:
- return ret;
-}
-
-/*
- * 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_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;
-
- /* this io's submitter should not have unlocked this before we could */
- BUG_ON(!ocfs2_iocb_is_rw_locked(iocb));
-
- if (bytes <= 0)
- mlog_ratelimited(ML_ERROR, "Direct IO failed, bytes = %lld",
- (long long)bytes);
- if (dwc) {
- if (bytes > 0)
- 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);
-
- level = ocfs2_iocb_rw_locked_level(iocb);
- ocfs2_rw_unlock(inode, level);
- return ret;
-}
-
-static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
-{
- struct file *file = iocb->ki_filp;
- struct inode *inode = file->f_mapping->host;
- struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
- get_block_t *get_block;
-
- /*
- * Fallback to buffered I/O if we see an inode without
- * extents.
- */
- if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
- return 0;
-
- /* Fallback to buffered I/O if we do not support append dio. */
- if (iocb->ki_pos + iter->count > i_size_read(inode) &&
- !ocfs2_supports_append_dio(osb))
- return 0;
-
- if (iov_iter_rw(iter) == READ)
- get_block = ocfs2_lock_get_block;
- else
- get_block = ocfs2_dio_wr_get_block;
-
- return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
- iter, get_block,
- ocfs2_dio_bh_end_io, 0);
-}
-
static int ocfs2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
- unsigned int flags, struct iomap *iomap, struct iomap *srcmap)
+ unsigned int flags, struct iomap *iomap, struct iomap *srcmap,
+ void *owner)
{
int ret;
struct ocfs2_map_block map;
@@ -3252,10 +3532,32 @@ static int ocfs2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
map.flags = 0;
if (flags & IOMAP_WRITE) {
- return -EOPNOTSUPP;
+ struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
+ struct ocfs2_inode_info *oi = OCFS2_I(inode);
+
+ /*
+ * Writes that span EOF might trigger an IO size update on
+ * completion, so consider them to be dirty for the purposes
+ * of O_DSYNC even if there is no other metadata changes
+ * pending or have been made here.
+ *
+ * Within i_size there can still be metadata which is not
+ * committed, for example the CoW done by
+ * ocfs2_prepare_inode_for_write(). If iomap is allowed to use
+ * the FUA-only fast path for that, it clears
+ * IOMAP_DIO_NEED_SYNC and skips generic_write_sync(), leaving
+ * the CoW extent tree changes uncommitted.
+ */
+ if (offset + length > i_size_read(inode) ||
+ !jbd2_transaction_committed(osb->journal->j_journal,
+ oi->i_datasync_tid))
+ iomap->flags |= IOMAP_F_DIRTY;
+
+ ret = ocfs2_dio_wr_map_blocks(inode, &map, flags, owner);
+ } else {
+ ret = ocfs2_lock_map_blocks(inode, &map, 0, flags & IOMAP_NOWAIT);
}
- ret = ocfs2_lock_map_blocks(inode, &map, 0, flags & IOMAP_NOWAIT);
if (ret < 0)
return ret;
@@ -3296,10 +3598,141 @@ int ocfs2_iomap_next(const struct iomap_iter *iter, struct iomap *iomap,
}
ret = ocfs2_iomap_begin(iter->inode, iter->pos, iter->len, iter->flags,
- iomap, srcmap);
+ iomap, srcmap, iter->private);
return ret < 0 ? ret : 1;
}
+/*
+ * Clean up the head/tail folios which the recording mappings of a direct
+ * write have zeroed. Each record covers a run of clusters whose folios
+ * were prepared; the zeroed folios are the ones in its first and its last
+ * cluster, and only those two are cleaned, see
+ * ocfs2_dio_cleanup_clusters(). The records are still on
+ * ip_unwritten_list, so no other direct write can take these clusters over
+ * while they are cleaned up.
+ *
+ * @write_zeroes is true when some of the clusters may have been converted
+ * to written and the zeroes have to reach the disk; otherwise the pages
+ * are dropped.
+ *
+ * Must be called before ocfs2_free_unwritten_list(), which wakes up the
+ * writes waiting for the clusters, and without the inode lock or
+ * ip_alloc_sem.
+ */
+static void ocfs2_dio_cleanup_pages(struct inode *inode,
+ struct list_head *head, bool write_zeroes)
+{
+ struct ocfs2_unwritten_extent *ue;
+
+ list_for_each_entry(ue, head, ue_node)
+ ocfs2_dio_cleanup_clusters(inode, ue->ue_cpos, ue->ue_clusters,
+ write_zeroes);
+}
+
+/*
+ * Direct I/O completion. Like the old buffer_head path
+ * ocfs2_dio_end_io(), we use the rw_lock (DLM lock) to protect
+ * io on one node from truncation on another, and drop it here
+ * once the io has completed.
+ *
+ * The rw_lock taken in ocfs2_file_{read,write}_iter() is released exactly
+ * once, but not always here. When kiocb_invalidate_pages() fails before any
+ * io is issued, __iomap_dio_rw() frees the dio and returns -ENOTBLK without
+ * calling ->end_io() at all, and ocfs2_file_write_iter() releases the lock
+ * itself. A -ENOTBLK part way through the iteration does come through here.
+ *
+ * It also is where the unwritten clusters of the write are made
+ * written, the ones ocfs2_iomap_begin() has recorded for this kiocb.
+ * The records go whatever the outcome of the io is.
+ *
+ * Mind the context. A write which needs nothing here, a plain
+ * overwrite, is completed by iomap from the bio completion, that is
+ * in interrupt context. ip_lock, which protects ip_unwritten_list,
+ * is not safe to be taken from there. That is no problem, as there is
+ * nothing recorded for such a write, and iomap defers the completion
+ * to a process context when there is: for the unwritten extents we
+ * have mapped (IOMAP_DIO_UNWRITTEN), for a write that extends i_size,
+ * or for any error.
+ *
+ * ocfs2_rw_unlock() itself is safe from interrupt context: it only drops
+ * the holder count under a spinlock and wakes the downconvert thread,
+ * which is what does the DLM work.
+ */
+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 &&
+ (!list_empty(&unwritten) ||
+ (offset + size > i_size_read(inode)))) {
+ /*
+ * A write that hit an error can still have a prefix on disk.
+ * Convert it and report the byte count, as the buffer_head
+ * path did, instead of leaving it to read back as zeroes.
+ */
+ ret = ocfs2_dio_end_io_write(inode, offset, size, &unwritten);
+ if (ret < 0) {
+ mlog_errno(ret);
+ /*
+ * The conversion failed part way, some of the
+ * clusters may already be written.
+ */
+ ocfs2_dio_cleanup_pages(inode, &unwritten, true);
+ }
+ } else if (error) {
+ /* Nothing is converted, the zeroes are not needed. */
+ ocfs2_dio_cleanup_pages(inode, &unwritten, false);
+ }
+
+ ocfs2_free_unwritten_list(inode, &unwritten);
+
+ /*
+ * A failed extending write keeps its orphan entry, and the clusters it
+ * allocated beyond i_size, for the recovery in
+ * ocfs2_add_inode_to_orphan() (or the one at mount time), see
+ * ocfs2_file_write_iter(). Do not call ocfs2_dio_clear_orphan() here:
+ * a plain successful overwrite can be completed in interrupt context,
+ * where the inode lock must not be taken.
+ */
+ ocfs2_rw_unlock(inode, level);
+
+ /*
+ * Returning 0 makes iomap report dio->size, so a write that hit an
+ * error after completing a prefix still returns the bytes it wrote.
+ */
+ return ret ? ret : (size ? 0 : error);
+}
+
+static int ocfs2_dio_end_io_w_pr(struct kiocb *iocb, ssize_t size,
+ int error, unsigned int flags)
+{
+ return ocfs2_dio_end_io(iocb, size, error, flags, 0);
+}
+
+static int ocfs2_dio_end_io_w_ex(struct kiocb *iocb, ssize_t size,
+ int error, unsigned int flags)
+{
+ return ocfs2_dio_end_io(iocb, size, error, flags, 1);
+}
+
static int ocfs2_dio_end_io_r_pr(struct kiocb *iocb, ssize_t size,
int error, unsigned int flags)
{
@@ -3314,6 +3747,14 @@ static int ocfs2_dio_end_io_r_pr(struct kiocb *iocb, ssize_t size,
return error;
}
+const struct iomap_dio_ops ocfs2_iomap_dio_ops_w_pr = {
+ .end_io = ocfs2_dio_end_io_w_pr,
+};
+
+const struct iomap_dio_ops ocfs2_iomap_dio_ops_w_ex = {
+ .end_io = ocfs2_dio_end_io_w_ex,
+};
+
const struct iomap_dio_ops ocfs2_iomap_dio_ops_r_pr = {
.end_io = ocfs2_dio_end_io_r_pr,
};
@@ -3325,7 +3766,6 @@ const struct address_space_operations ocfs2_aops = {
.writepages = ocfs2_writepages,
.write_begin = ocfs2_write_begin,
.write_end = ocfs2_write_end,
- .direct_IO = ocfs2_direct_IO,
.bmap = ocfs2_bmap,
.invalidate_folio = block_invalidate_folio,
.release_folio = ocfs2_release_folio,
diff --git a/fs/ocfs2/aops.h b/fs/ocfs2/aops.h
index 7946ef71259f4..c3e5df96fca47 100644
--- a/fs/ocfs2/aops.h
+++ b/fs/ocfs2/aops.h
@@ -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);
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 */
diff --git a/fs/ocfs2/file.c b/fs/ocfs2/file.c
index 3d717200d53a4..2e4973db105f3 100644
--- a/fs/ocfs2/file.c
+++ b/fs/ocfs2/file.c
@@ -48,6 +48,7 @@
#include "quota.h"
#include "refcounttree.h"
#include "ocfs2_trace.h"
+#include "namei.h"
#include "buffer_head_io.h"
@@ -135,6 +136,13 @@ static int ocfs2_file_open(struct inode *inode, struct file *file)
file->f_mode |= FMODE_NOWAIT;
+ /*
+ * Direct I/O is served through iomap_dio_rw() from
+ * ocfs2_file_{read,write}_iter() rather than an a_ops->direct_IO
+ * method, so advertise O_DIRECT capability explicitly here.
+ */
+ file->f_mode |= FMODE_CAN_ODIRECT;
+
leave:
return status;
}
@@ -1195,9 +1203,9 @@ int ocfs2_setattr(const struct mnt_idmap *idmap, struct dentry *dentry,
size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;
if (size_change) {
/*
- * Here we should wait dio to finish before inode lock
- * to avoid a deadlock between ocfs2_setattr() and
- * ocfs2_dio_end_io_write()
+ * Here we should wait for in-flight direct I/O to finish
+ * before taking the inode lock, to avoid a deadlock between
+ * ocfs2_setattr() and direct I/O completion.
*/
inode_dio_wait(inode);
@@ -2417,9 +2425,52 @@ static bool ocfs2_should_use_dio(struct kiocb *iocb, struct iov_iter *iter,
!ocfs2_supports_append_dio(osb))
return false;
+ /*
+ * A direct write which does not cover whole pages leaves the rest of
+ * the page untouched. iomap only zeroes the padding up to the file
+ * system block size, so on a file system with a block size smaller
+ * than the page size the untouched blocks would expose stale data
+ * once the cluster is marked written. Let buffered I/O handle it.
+ *
+ * TODO: Avoid unnecessarily demoting in-place sub-page overwrites
+ * to buffered I/O when i_blocksize(inode) < PAGE_SIZE.
+ */
+ if (iov_iter_rw(iter) == WRITE && i_blocksize(inode) < PAGE_SIZE &&
+ (!IS_ALIGNED(iocb->ki_pos, PAGE_SIZE) ||
+ !IS_ALIGNED(iocb->ki_pos + iter->count, PAGE_SIZE)))
+ return false;
+
return true;
}
+/*
+ * A direct write holds the rw lock PR under coherency=buffered, but when it
+ * ends up doing a buffered write, that write has to hold EX like any other
+ * buffered write: with only PR another node's direct write can run at the
+ * same time, and the read-modify-write this one does in the page cache races
+ * with it. The direct io is finished by now, nothing is in flight, so drop
+ * the PR and take EX instead of upgrading in one request, which can deadlock
+ * in the cluster lock manager when two nodes upgrade at once.
+ */
+static int ocfs2_dio_upgrade_rw_lock(struct inode *inode, int *rw_level)
+{
+ int ret;
+
+ if (*rw_level != 0)
+ return 0;
+
+ ocfs2_rw_unlock(inode, 0);
+ *rw_level = -1;
+
+ ret = ocfs2_rw_lock(inode, 1);
+ if (ret < 0) {
+ mlog_errno(ret);
+ return ret;
+ }
+ *rw_level = 1;
+ return 0;
+}
+
static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
struct iov_iter *from)
{
@@ -2434,9 +2485,13 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
OCFS2_MOUNT_COHERENCY_BUFFERED);
void *saved_ki_complete = NULL;
int append_write = ((iocb->ki_pos + count) >=
- i_size_read(inode) ? 1 : 0);
+ i_size_read(inode) ? 1 : 0) ||
+ iocb->ki_flags & IOCB_APPEND;
int direct_io = iocb->ki_flags & IOCB_DIRECT ? 1 : 0;
int nowait = iocb->ki_flags & IOCB_NOWAIT ? 1 : 0;
+ int dio_flags = 0;
+ unsigned int dio_align = bdev_logical_block_size(inode->i_sb->s_bdev);
+ bool use_dio = false;
if (trace_ocfs2_file_write_iter_enabled()) {
struct dentry *dentry = file->f_path.dentry;
@@ -2462,14 +2517,13 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
} else
inode_lock(inode);
- ocfs2_iocb_init_rw_locked(iocb);
-
/*
- * Concurrent O_DIRECT writes are allowed with
- * mount_option "coherency=buffered".
- * For append write, we must take rw EX.
+ * Concurrent O_DIRECT writes are allowed with mount_option
+ * "coherency=buffered". O_APPEND and a write which is extending at
+ * this point have to take rw EX.
*/
- rw_level = (!direct_io || full_coherency || append_write);
+ use_dio = direct_io && ocfs2_should_use_dio(iocb, from, inode);
+ rw_level = (!use_dio || full_coherency || append_write);
if (nowait)
ret = ocfs2_try_rw_lock(inode, rw_level);
@@ -2481,6 +2535,15 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
goto out_mutex;
}
+ /*
+ * A buffered write can block on cluster locks, allocation or
+ * writeback, none of which IOCB_NOWAIT allows.
+ */
+ if (nowait && !use_dio) {
+ ret = -EAGAIN;
+ goto out;
+ }
+
/*
* O_DIRECT writes with "coherency=full" need to take EX cluster
* inode_lock to guarantee coherency.
@@ -2519,6 +2582,10 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
goto out;
}
+ ret = kiocb_modified(iocb);
+ if (ret < 0)
+ goto out;
+
if (direct_io && !is_sync_kiocb(iocb) &&
ocfs2_is_io_unaligned(inode, count, iocb->ki_pos)) {
/*
@@ -2527,31 +2594,150 @@ 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);
+ if (use_dio) {
+ if (!IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(from),
+ dio_align)) {
+ ret = -EINVAL;
+ goto out;
+ }
- written = __generic_file_write_iter(iocb, from);
- /* buffered aio wouldn't have proper lock coverage today */
- BUG_ON(written == -EIOCBQUEUED && !direct_io);
+ /*
+ * Extending the file requires cluster locks and
+ * transactions, which IOCB_NOWAIT forbids.
+ */
+ if (nowait &&
+ ((iocb->ki_pos + count) > i_size_read(inode))) {
+ ret = -EAGAIN;
+ goto out;
+ }
- /*
- * deep in g_f_a_w_n()->ocfs2_direct_IO we pass in a ocfs2_dio_end_io
- * function pointer which is called when o_direct io completes so that
- * it can unlock our rw lock.
- * Unfortunately there are error cases which call end_io and others
- * that don't. so we don't have to unlock the rw_lock if either an
- * async dio is going to do it in the future or an end_io after an
- * error has already done it.
- */
- if ((written == -EIOCBQUEUED) || (!ocfs2_iocb_is_rw_locked(iocb))) {
- rw_level = -1;
+ if (iocb->ki_pos > i_size_read(inode) &&
+ fault_in_iov_iter_readable(from, count)) {
+ ret = -EFAULT;
+ goto out;
+ }
+
+ if ((iocb->ki_pos + count) > i_size_read(inode)) {
+ /*
+ * Complete before i_rwsem is dropped: i_size is only
+ * updated by ->end_io(), and the next writer would
+ * zero the gap between the size it still sees and its
+ * own write, over the data this one has just written.
+ */
+ dio_flags |= IOMAP_DIO_FORCE_WAIT;
+
+ if (ocfs2_clusters_for_bytes(inode->i_sb,
+ iocb->ki_pos + count) >
+ ocfs2_clusters_for_bytes(inode->i_sb,
+ i_size_read(inode))) {
+ /*
+ * when we are going to alloc extents beyond file
+ * size, add the inode to orphan dir, so we can
+ * recall those spaces when system crashed during
+ * write.
+ */
+ ret = ocfs2_add_inode_to_orphan(osb, inode);
+ if (ret < 0) {
+ mlog_errno(ret);
+ goto out;
+ }
+ WRITE_ONCE(OCFS2_I(inode)->ip_dio_orphan_pid,
+ task_pid_nr(current));
+ }
+ }
+
+ ret = ocfs2_dio_zero_eof(inode, iocb->ki_pos, count);
+ if (ret < 0)
+ goto out;
+
+ const struct iomap_dio_ops *dops = rw_level ?
+ &ocfs2_iomap_dio_ops_w_ex : &ocfs2_iomap_dio_ops_w_pr;
+ struct iomap_dio *dio;
+
+ /*
+ * The kiocb is the owner of the unwritten clusters which
+ * ->iomap_begin() records for ->end_io() to convert, see
+ * ocfs2_iomap_next().
+ */
+ dio = __iomap_dio_rw(iocb, from, ocfs2_iomap_next,
+ dops, dio_flags, iocb, 0);
+ if (dio == NULL) {
+ /* No I/O issued; rw_lock still held. */
+ written = 0;
+ } else if (IS_ERR(dio)) {
+ written = PTR_ERR(dio);
+ /*
+ * -EIOCBQUEUED: async I/O; end_io will drop the lock on
+ * completion. Any other error means no I/O started and
+ * end_io was not called, so the cleanup path below drops
+ * the lock.
+ */
+ if (written == -EIOCBQUEUED)
+ rw_level = -1;
+ } else {
+ /*
+ * Synchronous completion. iomap_dio_complete() runs
+ * end_io, which drops the lock unless the mapping
+ * bounced us back to buffered I/O (returns 0, lock
+ * retained).
+ */
+ written = iomap_dio_complete(dio);
+ if (written != 0)
+ rw_level = -1;
+ }
+
+ /*
+ * __iomap_dio_rw() returns -ENOTBLK when it could not
+ * invalidate the page cache for the DIO range (e.g. racing
+ * buffered/mmap I/O on the same file). Fall back to a
+ * buffered write for the remaining data, instead of
+ * leaking -ENOTBLK to userspace.
+ */
+ if (written == -ENOTBLK)
+ written = 0;
+ if (written == 0 && iov_iter_count(from)) {
+ if (nowait) {
+ ret = -EAGAIN;
+ goto out;
+ }
+ ret = ocfs2_dio_upgrade_rw_lock(inode, &rw_level);
+ if (ret)
+ goto out;
+ written = direct_write_fallback(iocb, from, 0,
+ generic_perform_write(iocb, from));
+ use_dio = false;
+ }
+ } else if (direct_io) {
+ /*
+ * userspace starts a DIO, we reject unaligned I/O even
+ * when DIO falls back to buffered I/O.
+ */
+ if (!IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(from),
+ dio_align)) {
+ ret = -EINVAL;
+ goto out;
+ }
+
+ if (nowait) {
+ ret = -EAGAIN;
+ goto out;
+ }
+ ret = ocfs2_dio_upgrade_rw_lock(inode, &rw_level);
+ if (ret)
+ goto out;
+ written = direct_write_fallback(iocb, from, 0,
+ generic_perform_write(iocb, from));
+ } else {
+ written = __generic_file_write_iter(iocb, from);
}
+ /* 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)) {
+ if (((file->f_flags & O_DSYNC) && !use_dio) || IS_SYNC(inode)) {
ret = filemap_fdatawrite_range(file->f_mapping,
iocb->ki_pos - written,
iocb->ki_pos - 1);
@@ -2571,11 +2757,39 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,
}
out:
+ /*
+ * IOMAP_DIO_FORCE_WAIT made an extending dio complete synchronously,
+ * so its end_io has already updated i_size.
+ */
if (saved_ki_complete)
xchg(&iocb->ki_complete, saved_ki_complete);
- if (rw_level != -1)
+ if (rw_level != -1) {
+ /*
+ * The orphan entry this write added is still there when no io
+ * was issued at all, or when the write bailed out before
+ * submitting it. The conversion in ocfs2_dio_end_io_write()
+ * has removed it on the success path; a failed io is left to
+ * the recovery. Remove it here for the former, while the
+ * rw_lock is still held.
+ *
+ * Clearing it takes the inode cluster lock, which blocks, so
+ * IOCB_NOWAIT must not go there. The marker stays for a later
+ * write or for the recovery.
+ */
+ if (!nowait)
+ ocfs2_dio_clear_orphan(inode);
ocfs2_rw_unlock(inode, rw_level);
+ }
+
+ /*
+ * A failed io leaves the entry for the recovery, and the marker with
+ * it: dropping the marker here would strand the entry, since the
+ * background orphan scan skips dio entries and ocfs2_delete_inode()
+ * will not wipe an inode that still has OCFS2_DIO_ORPHANED_FL set.
+ * ocfs2_dio_clear_orphan_locked() clears the marker when it removes
+ * the entry, and the next extending write recovers it otherwise.
+ */
out_mutex:
inode_unlock(inode);
diff --git a/fs/ocfs2/inode.h b/fs/ocfs2/inode.h
index 15a7d57aace51..1981dea8a764a 100644
--- a/fs/ocfs2/inode.h
+++ b/fs/ocfs2/inode.h
@@ -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;
diff --git a/fs/ocfs2/super.c b/fs/ocfs2/super.c
index 79670f8655801..c696c539f4162 100644
--- a/fs/ocfs2/super.c
+++ b/fs/ocfs2/super.c
@@ -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);
--
2.39.3
next prev parent reply other threads:[~2026-11-30 10:02 UTC|newest]
Thread overview: 12+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-30 10:01 [RFC PATCH v13 00/10] migrate ocfs2 DIO " Joseph Qi
2026-11-30 10:01 ` [RFC PATCH v13 01/10] ocfs2: Add new ocfs2_map_blocks() to introduce iomap feature Joseph Qi
2026-11-30 10:01 ` [RFC PATCH v13 02/10] ocfs2: switch DIO read path from buffer_head to iomap Joseph Qi
2026-11-30 10:01 ` [RFC PATCH v13 03/10] ocfs2: add ocfs2_get_clusters_uncached() Joseph Qi
2026-11-30 10:01 ` [RFC PATCH v13 04/10] ocfs2: refactor ocfs2_lock_allocators() and add a dio variant Joseph Qi
2026-11-30 10:01 ` [RFC PATCH v13 05/10] ocfs2: record the fsync transaction when CoW makes clusters writable Joseph Qi
2026-11-30 10:01 ` [RFC PATCH v13 06/10] ocfs2: rework the direct write context for multi-cluster mappings Joseph Qi
[not found] ` <sashiko-outbox-240858@kernel.org>
2026-11-30 12:00 ` Joseph Qi
2026-11-30 10:02 ` Joseph Qi [this message]
2026-11-30 10:02 ` [RFC PATCH v13 08/10] ocfs2: keep sub-page overwrites of written blocks on direct I/O Joseph Qi
2026-11-30 10:02 ` [RFC PATCH v13 09/10] ocfs2: write the dio zeroed head/tail buffers out before completion Joseph Qi
2026-11-30 10:02 ` [RFC PATCH v13 10/10] ocfs2: make buffered writes wait for in-flight direct writes Joseph Qi
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261130100203.383093-8-joseph.qi@linux.alibaba.com \
--to=joseph.qi@linux.alibaba.com \
--cc=akpm@linux-foundation.org \
--cc=hch@lst.de \
--cc=heming.zhao@suse.com \
--cc=jlbec@evilplan.org \
--cc=linux-kernel@vger.kernel.org \
--cc=mark@fasheh.com \
--cc=ocfs2-devel@lists.linux.dev \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®