[PATCH 2/2] ceph: don't let a mapped write overwrite other clients' writes

From: Xiubo Li via B4 Relay

Date: Thu Dec 03 2026 - 19:22:23 EST


From: Xiubo Li <xiubo.li@xxxxxxxxx>

A store through a shared mapping dirties the whole folio. When the
client has Fw but not Fb, because other clients have the file open for
writing too (the MDS has its filelock in MIX), those clients may write
to the same folio meanwhile, and their writes complete at once, on the
OSDs. This client's folio is stale then, and its writeback overwrites
what they wrote. For example, client B maps a file and stores to bytes
0-15, client C does a pwrite() to bytes 2048-2063 and an fsync(): C's
bytes are lost when B's folio is written back. A pwrite() on B instead
of the store loses nothing, as it writes only the bytes it was given.

Keep a copy of the folio in ceph_page_mkwrite() when it gets dirty
without Fb (and without lazy I/O, which asks for no coherency), on the
ceph_dirty_range that lazy I/O already uses to track a folio's dirty
bytes. At writeback, gather such folios of one object together and
write back only what this client changed in them:

- Compare each folio with its copy. When there are at most two changed
ranges per run of contiguous folios, send just those ranges, as WRITE
ops straight from the folios. The bytes in between are left as other
clients wrote them.

- Otherwise send each run of folios whole, after a CMPEXT of the copy,
in the same request: the OSD writes it only if no other client wrote
there since. A request that loses the compare goes again with only
the changed ranges, and for a second after that the changed ranges
are sent at once, as other clients are writing to the file.

Whole runs go out when nobody else writes, as writes that do not cover
whole blocks cost the OSD more; a small store sends a few bytes, and
needs no compare.

As writepages_finish() does, a folio written back without Fc is dropped
from the page cache afterwards, so that the mapping reads what other
clients wrote from then on.

A byte that this client stored with the same value the copy holds,
after another client changed it, is taken as not changed: the other
client's write wins there, as if this store had come first. Disjoint
writes, the case above, are not affected.

Encrypted files, which go out in whole crypto blocks, and files cached
with fscache keep the old behaviour.

Tested on a vstart cluster with three kernel mounts of one fs (A, B, C),
on a KASAN + lockdep kernel, 3 rounds each; before is this branch
without the patch, after with it, no splats either way:

| Test | Before | After |
|--------------------------------------|---------------|-------------|
| B stores, C pwrite()s, same page (1) | C lost 30/30 | C lost 0/30 |
| B pwrite()s, C pwrite()s, same page | C lost 0/9 | C lost 0/9 |
| Edge cases (2) | 15/15 corrupt | 0/15 |
| Stripes, B+C store, A pwrite()s (3) | 6/6 corrupt | 0/6 |
| Stripes, A+C pwrite() only | 0/3 corrupt | 0/3 |
| B sees C's write after writeback (4) | 60/60 ok | 60/60 ok |
| fsx, file open on another client | 3/3 pass | 3/3 pass |

(1) B stores 8 bytes, C pwrite()s 8 other bytes, then B msync()s.
(2) Alex's case, 2 and 300 changed ranges, 64 pages, at EOF.
(3) Each client writes its own 64-byte stripes for 30s; before, 156K
to 158K bytes per run were not their owner's last write.
(4) And B's next store and msync() keep it.

Performance on a release config kernel: B stores 8 bytes into each of K
random pages of a 1 MiB file, then msync()s. In MIX, C has the file
open for writing; with "+C" it also pwrite()s 64 bytes at random offsets
all the time. Fb: B alone. 30s per run, median of 3-5 runs, before
and after alternating:

| Case | ops/s before | ops/s after | Change |
|--------------|--------------|-------------|--------|
| MIX, K=1 | 9403 | 9422 | +0.2% |
| MIX, K=16 | 2072 | 2089 | +0.8% |
| MIX+C, K=1 | 6677 | 6765 | +1.3% |
| MIX+C, K=16 | 1513 | 1502 | -0.7% |
| Fb, K=1 | 11577 | 12254 | +5.8% |
| Fb, K=16 | 5289 | 5275 | -0.3% |
| Fb, pwrite() | 8371 | 8457 | +1.0% |

msync() (fsync() for pwrite()) latency in us, before/after:

| Case | p50 | p90 | p99 | p99.9 |
|--------------|---------|---------|---------|-----------|
| MIX, K=1 | 76/75 | 93/90 | 352/322 | 555/517 |
| MIX, K=16 | 153/158 | 208/243 | 902/651 | 1587/994 |
| MIX+C, K=1 | 96/95 | 138/162 | 490/419 | 723/667 |
| MIX+C, K=16 | 190/197 | 339/352 | 719/741 | 1055/1161 |
| Fb, K=1 | 70/66 | 83/79 | 401/352 | 711/663 |
| Fb, K=16 | 128/123 | 147/143 | 514/557 | 845/940 |
| Fb, pwrite() | 97/96 | 136/134 | 725/734 | 1262/1237 |

The differences are within the run-to-run spread (about 10% for Fb,
K=1); Fb does not take the new path.

Reported-by: Alex Markuze <amarkuze@xxxxxxxxxx>
Signed-off-by: Xiubo Li <xiubo.li@xxxxxxxxx>
---
fs/ceph/addr.c | 757 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
fs/ceph/inode.c | 1 +
fs/ceph/super.h | 1 +
3 files changed, 713 insertions(+), 46 deletions(-)

diff --git a/fs/ceph/addr.c b/fs/ceph/addr.c
index de3431f28ba9..4041efb37d3a 100644
--- a/fs/ceph/addr.c
+++ b/fs/ceph/addr.c
@@ -91,6 +91,7 @@ struct ceph_dirty_range {
struct ceph_snap_context *snapc;
unsigned int start, end; /* dirty bytes within the folio */
bool whole; /* dirtied as a whole after all */
+ struct folio *base; /* see ceph_folio_keep_base() */
struct rcu_head rcu;
};

@@ -121,10 +122,67 @@ static struct ceph_snap_context *ceph_folio_detach_snapc(struct folio *folio)
if (!dr)
return priv;
snapc = dr->snapc;
+ if (dr->base)
+ folio_put(dr->base);
kfree_rcu(dr, rcu);
return snapc;
}

+/*
+ * A store through a shared mapping may dirty a folio without the buffer
+ * cap (Fb), when other clients have the file open for writing too (the
+ * MDS has its filelock in MIX). Other clients may then write to the
+ * file, in this folio too, without this client knowing: its folio is
+ * stale, and writing it back whole would overwrite what they wrote,
+ * even after their write completed.
+ *
+ * So keep a copy of the folio as it was when it got dirty (it then gets
+ * write-protected again before it is written back, so a later store
+ * comes back here), and write back only what this client changed in it:
+ * ceph_write_kept().
+ *
+ * With the folio locked, after it has just been dirtied, as a whole. If
+ * the memory for the copy cannot be had, the folio goes out whole, as
+ * it always did.
+ */
+static void ceph_folio_keep_base(struct folio *folio)
+{
+ struct ceph_dirty_range *dr;
+ struct folio *base;
+ unsigned int nofs;
+
+ if (WARN_ON_ONCE(__ceph_dirty_range(folio->private) ||
+ !folio->private))
+ return;
+
+ nofs = memalloc_nofs_save();
+ base = folio_alloc(GFP_KERNEL, folio_order(folio));
+ dr = kmalloc_obj(*dr, GFP_KERNEL);
+ memalloc_nofs_restore(nofs);
+ if (!base || !dr) {
+ if (base)
+ folio_put(base);
+ kfree(dr);
+ return;
+ }
+ folio_copy(base, folio);
+ dr->snapc = folio_get_private(folio);
+ dr->start = 0;
+ dr->end = folio_size(folio);
+ dr->whole = true;
+ dr->base = base;
+ folio_change_private(folio,
+ (void *)((unsigned long)dr | CEPH_FOLIO_DIRTY_RANGE));
+}
+
+/* With the folio locked */
+static struct folio *ceph_folio_base(const struct folio *folio)
+{
+ struct ceph_dirty_range *dr = __ceph_dirty_range(folio->private);
+
+ return dr ? dr->base : NULL;
+}
+
/*
* Drop the dirty state of a folio that will not be written back, with
* the folio locked: its snap context and dirty range, its Fb cap ref and
@@ -1025,6 +1083,543 @@ static u64 get_writepages_data_length(struct inode *inode,
return ret;
}

+/* The OSD fails a CMPEXT with -MAX_ERRNO - <offset of the first mismatch> */
+#define CEPH_CMPEXT_MISMATCH(err) ((err) <= -MAX_ERRNO)
+
+/*
+ * For this long after a compare was lost on an inode, send only the
+ * changed bytes of its folios right away, see ceph_write_kept().
+ */
+#define CEPH_KEPT_CONFLICT_HOLD HZ
+
+/* A CMPEXT and a WRITE per run of folios */
+#define CEPH_MERGE_EXTS_PER_REQ (CEPH_OSD_MAX_OPS / 2)
+#define CEPH_MERGE_MAX_EXTS (4 * CEPH_MERGE_EXTS_PER_REQ)
+#define CEPH_MERGE_MAX_FOLIOS 32
+
+/* Requests with the changed bytes in flight at once */
+#define CEPH_DIFF_INFLIGHT 8
+
+/*
+ * A run of folios that ceph_folio_keep_base() kept a copy of, contiguous
+ * in the file and in one object.
+ */
+struct ceph_merge_ext {
+ u64 off; /* file offset */
+ u64 objoff; /* offset in the object */
+ size_t len;
+ int first, nr; /* its folios: folios[first, first + nr) */
+ int pg; /* its first page in pages[] */
+};
+
+/* Folios to write back together, see ceph_process_folio_batch() */
+struct ceph_merge_batch {
+ struct folio *folios[CEPH_MERGE_MAX_FOLIOS];
+ struct ceph_merge_ext ext[CEPH_MERGE_MAX_EXTS];
+ /* for ceph_write_kept(): the folios' pages, then their copies' */
+ struct page *pages[2 * CEPH_MERGE_MAX_FOLIOS];
+ u64 objnum;
+ int nr_folios, nr_exts;
+};
+
+/* Bytes of a run of folios that differ from the copy */
+struct ceph_diff_run {
+ u32 off; /* from the start of the run of folios */
+ u32 len;
+};
+
+/*
+ * Find the bytes of @ext's folios that differ from the copies kept of
+ * them. Store the ranges in @runs, unless it is NULL, and return how
+ * many there are, or @max + 1 if there are more than @max.
+ */
+static int ceph_ext_diff(const struct ceph_merge_ext *ext,
+ struct folio **folios, struct ceph_diff_run *runs,
+ int max)
+{
+ bool open = false;
+ size_t o = 0;
+ int nr = 0, f;
+
+ for (f = ext->first; f < ext->first + ext->nr; f++) {
+ struct folio *folio = folios[f];
+ struct folio *base = ceph_folio_base(folio);
+ size_t flen = min_t(size_t, folio_size(folio), ext->len - o);
+ size_t p;
+
+ for (p = 0; p < flen; p += PAGE_SIZE) {
+ size_t plen = min_t(size_t, PAGE_SIZE, flen - p);
+ const u8 *cur = kmap_local_folio(folio, p);
+ const u8 *b = kmap_local_folio(base, p);
+ size_t i = 0;
+
+ while (i < plen) {
+ bool diff;
+
+ /* skip what is unchanged a word at a time */
+ while (!open && IS_ALIGNED(i, sizeof(long)) &&
+ i + sizeof(long) <= plen &&
+ *(const unsigned long *)(cur + i) ==
+ *(const unsigned long *)(b + i))
+ i += sizeof(long);
+ if (i == plen)
+ break;
+
+ diff = cur[i] != b[i];
+ if (diff && !open) {
+ if (nr == max) {
+ kunmap_local(b);
+ kunmap_local(cur);
+ return max + 1;
+ }
+ if (runs) {
+ runs[nr].off = o + p + i;
+ runs[nr].len = 0;
+ }
+ nr++;
+ open = true;
+ } else if (!diff) {
+ open = false;
+ }
+ if (open && runs)
+ runs[nr - 1].len++;
+ i++;
+ }
+ kunmap_local(b);
+ kunmap_local(cur);
+ }
+ o += flen;
+ }
+ return nr;
+}
+
+/*
+ * Find the changed ranges of @ext[0..@n) into @runs, at most @max of
+ * them, and note in @ext_of which run of folios each one is in. Returns
+ * how many there are, or @max + 1 if there are more.
+ */
+static int ceph_diff_runs(struct ceph_merge_ext *ext, int n,
+ struct folio **folios, struct ceph_diff_run *runs,
+ int *ext_of, int max)
+{
+ int i, k, nr, total = 0;
+
+ for (i = 0; i < n; i++) {
+ nr = ceph_ext_diff(&ext[i], folios, runs + total, max - total);
+ if (nr > max - total)
+ return max + 1;
+ for (k = 0; k < nr; k++)
+ ext_of[total + k] = i;
+ total += nr;
+ }
+ return total;
+}
+
+/*
+ * Send only the @total ranges @runs of @ext that this client changed, as
+ * ceph_diff_runs() found them, each as a WRITE op, straight from the
+ * folios' @pages. The bytes it did not change are left as other clients
+ * wrote them. Every request carries this client's own changes only, so
+ * they need no order among themselves.
+ */
+static int ceph_send_diff(struct inode *inode, struct page **pages,
+ struct ceph_merge_ext *ext,
+ const struct ceph_diff_run *runs, const int *ext_of,
+ int total, struct ceph_snap_context *snapc,
+ struct ceph_writeback_ctl *ceph_wbc)
+{
+ struct ceph_inode_info *ci = ceph_inode(inode);
+ struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
+ struct ceph_osd_client *osdc = &fsc->client->osdc;
+ struct ceph_osd_request *reqs[CEPH_DIFF_INFLIGHT] = {};
+ size_t bytes[CEPH_DIFF_INFLIGHT] = {};
+ int i, r, nreq = 0, err = 0, err2;
+
+ for (r = 0; r < total && !err; nreq++) {
+ int slot = nreq % CEPH_DIFF_INFLIGHT;
+ int ops = min(total - r, CEPH_OSD_MAX_OPS);
+ struct ceph_osd_request *req;
+ u64 wlen, tsize;
+ u32 tseq;
+ int k;
+
+ if (reqs[slot]) {
+ err2 = ceph_osdc_wait_request(osdc, reqs[slot]);
+ ceph_update_write_metrics(&fsc->mdsc->metric,
+ reqs[slot]->r_start_latency,
+ reqs[slot]->r_end_latency,
+ bytes[slot], err2);
+ ceph_osdc_put_request(reqs[slot]);
+ reqs[slot] = NULL;
+ if (err2) {
+ err = err2;
+ break;
+ }
+ }
+
+ wlen = runs[r].len;
+ req = ceph_osdc_new_request(osdc, &ci->i_layout,
+ ceph_vino(inode),
+ ext[ext_of[r]].off + runs[r].off,
+ &wlen, 0, ops, CEPH_OSD_OP_WRITE,
+ CEPH_OSD_FLAG_WRITE, snapc,
+ ceph_wbc->truncate_seq,
+ ceph_wbc->truncate_size, false);
+ if (IS_ERR(req)) {
+ err = PTR_ERR(req);
+ break;
+ }
+ if (WARN_ON_ONCE(wlen != runs[r].len)) {
+ ceph_osdc_put_request(req);
+ err = -EIO;
+ break;
+ }
+ tsize = req->r_ops[0].extent.truncate_size;
+ tseq = req->r_ops[0].extent.truncate_seq;
+ bytes[slot] = 0;
+ for (k = 0; k < ops; k++, r++) {
+ const struct ceph_merge_ext *e = &ext[ext_of[r]];
+
+ if (k)
+ osd_req_op_extent_init(req, k,
+ CEPH_OSD_OP_WRITE,
+ e->objoff + runs[r].off,
+ runs[r].len, tsize, tseq);
+ osd_req_op_extent_osd_data_pages(req, k,
+ pages + e->pg + (runs[r].off >> PAGE_SHIFT),
+ runs[r].len, offset_in_page(runs[r].off),
+ false, false);
+ bytes[slot] += runs[r].len;
+ }
+ req->r_mtime = inode_get_mtime(inode);
+ ceph_osdc_start_request(osdc, req);
+ reqs[slot] = req;
+ }
+ for (i = 0; i < CEPH_DIFF_INFLIGHT; i++) {
+ if (!reqs[i])
+ continue;
+ err2 = ceph_osdc_wait_request(osdc, reqs[i]);
+ ceph_update_write_metrics(&fsc->mdsc->metric,
+ reqs[i]->r_start_latency,
+ reqs[i]->r_end_latency, bytes[i], err2);
+ ceph_osdc_put_request(reqs[i]);
+ if (!err)
+ err = err2;
+ }
+ return err;
+}
+
+static int ceph_write_diff(struct inode *inode, struct folio **folios,
+ struct page **pages, struct ceph_merge_ext *ext,
+ int n, struct ceph_snap_context *snapc,
+ struct ceph_writeback_ctl *ceph_wbc)
+{
+ struct ceph_diff_run *runs;
+ int *ext_of;
+ int i, total = 0, err;
+
+ for (i = 0; i < n; i++)
+ total += ceph_ext_diff(&ext[i], folios, NULL, INT_MAX);
+ if (!total)
+ return 0;
+ runs = kvmalloc_array(total, sizeof(*runs), GFP_NOFS);
+ ext_of = kvmalloc_array(total, sizeof(*ext_of), GFP_NOFS);
+ if (!runs || !ext_of) {
+ kvfree(ext_of);
+ kvfree(runs);
+ return -ENOMEM;
+ }
+ ceph_diff_runs(ext, n, folios, runs, ext_of, total);
+ err = ceph_send_diff(inode, pages, ext, runs, ext_of, total, snapc,
+ ceph_wbc);
+ kvfree(ext_of);
+ kvfree(runs);
+ return err;
+}
+
+/*
+ * Write back the runs @ext[0..@n) of the locked @folios, which
+ * ceph_folio_keep_base() kept a copy of when they got dirty. See there.
+ * The runs are all in one object.
+ *
+ * Send the folios whole, each run after a compare of the object's bytes
+ * against the copy, in the same request: the OSD writes a request only
+ * if no other client wrote there since. The requests are all in flight
+ * at once.
+ *
+ * A request that lost its compare goes again with only the bytes this
+ * client changed: the bytes it did not change are left as other clients
+ * wrote them meanwhile. That is what a merge of the folio with what is
+ * there now would write, in one more round trip, and without a read.
+ * Whole folios go out when nobody else writes, though: writes that do
+ * not cover whole blocks are more work for the OSD. For a while after a
+ * lost compare, the changed bytes are sent right away.
+ *
+ * A byte this client set to the value it had in the copy, after another
+ * client changed it, is taken as not changed: that store is ordered
+ * before the other client's write.
+ *
+ * Returns 0 or a negative error.
+ */
+static int ceph_write_kept(struct inode *inode, struct folio **folios,
+ struct ceph_merge_ext *ext, int n,
+ struct page **pgbuf,
+ struct ceph_snap_context *snapc,
+ struct ceph_writeback_ctl *ceph_wbc)
+{
+ struct ceph_inode_info *ci = ceph_inode(inode);
+ struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
+ struct ceph_client *cl = fsc->client;
+ struct ceph_osd_client *osdc = &fsc->client->osdc;
+ int nreq = DIV_ROUND_UP(n, CEPH_MERGE_EXTS_PER_REQ);
+ struct ceph_osd_request *reqs[DIV_ROUND_UP(CEPH_MERGE_MAX_EXTS,
+ CEPH_MERGE_EXTS_PER_REQ)];
+ struct page **pages, **bpages;
+ unsigned long conflict = READ_ONCE(ci->i_kept_conflict);
+ int i, q, f, npages = 0, nlost = 0, err = 0, err2;
+
+ for (i = 0; i < n; i++)
+ for (f = ext[i].first; f < ext[i].first + ext[i].nr; f++)
+ npages += folio_nr_pages(folios[f]);
+ if (pgbuf && npages <= CEPH_MERGE_MAX_FOLIOS) {
+ /* no allocation for order-0 folios gathered in a batch */
+ pages = pgbuf;
+ bpages = pgbuf + npages;
+ } else {
+ pgbuf = NULL;
+ pages = kmalloc_array(npages, sizeof(*pages), GFP_NOFS);
+ bpages = kmalloc_array(npages, sizeof(*bpages), GFP_NOFS);
+ if (!pages || !bpages) {
+ kfree(bpages);
+ kfree(pages);
+ return -ENOMEM;
+ }
+ }
+ npages = 0;
+ for (i = 0; i < n; i++) {
+ ext[i].pg = npages;
+ for (f = ext[i].first; f < ext[i].first + ext[i].nr; f++) {
+ struct folio *base = ceph_folio_base(folios[f]);
+ int pg;
+
+ for (pg = 0; pg < folio_nr_pages(folios[f]); pg++) {
+ pages[npages] = folio_page(folios[f], pg);
+ bpages[npages++] = folio_page(base, pg);
+ }
+ }
+ }
+
+ if (!time_in_range(jiffies, conflict,
+ conflict + CEPH_KEPT_CONFLICT_HOLD)) {
+ struct ceph_diff_run runs[2 * CEPH_MERGE_MAX_EXTS];
+ int ext_of[2 * CEPH_MERGE_MAX_EXTS];
+ int total = ceph_diff_runs(ext, n, folios, runs, ext_of,
+ 2 * n);
+
+ if (total <= 2 * n) {
+ err = total ? ceph_send_diff(inode, pages, ext, runs,
+ ext_of, total, snapc,
+ ceph_wbc) : 0;
+ goto out;
+ }
+ }
+ if (time_in_range(jiffies, conflict,
+ conflict + CEPH_KEPT_CONFLICT_HOLD)) {
+ err = ceph_write_diff(inode, folios, pages, ext, n, snapc,
+ ceph_wbc);
+ goto out;
+ }
+
+ for (q = 0; q < nreq; q++) {
+ struct ceph_merge_ext *qe = &ext[q * CEPH_MERGE_EXTS_PER_REQ];
+ int m = min(n - q * CEPH_MERGE_EXTS_PER_REQ,
+ CEPH_MERGE_EXTS_PER_REQ);
+ struct ceph_osd_request *req;
+ u64 wlen = qe[0].len, tsize;
+ u32 tseq;
+
+ req = ceph_osdc_new_request(osdc, &ci->i_layout,
+ ceph_vino(inode), qe[0].off, &wlen,
+ 1, 2 * m, CEPH_OSD_OP_WRITE,
+ CEPH_OSD_FLAG_WRITE, snapc,
+ ceph_wbc->truncate_seq,
+ ceph_wbc->truncate_size, false);
+ if (IS_ERR(req)) {
+ reqs[q] = NULL;
+ err = PTR_ERR(req);
+ continue;
+ }
+ if (WARN_ON_ONCE(wlen != qe[0].len)) {
+ /* a folio crosses an object boundary */
+ ceph_osdc_put_request(req);
+ reqs[q] = NULL;
+ err = -EIO;
+ continue;
+ }
+ tsize = req->r_ops[1].extent.truncate_size;
+ tseq = req->r_ops[1].extent.truncate_seq;
+ for (i = 0; i < m; i++) {
+ const struct ceph_merge_ext *e = &qe[i];
+
+ osd_req_op_extent_init(req, 2 * i, CEPH_OSD_OP_CMPEXT,
+ e->objoff, e->len, tsize, tseq);
+ osd_req_op_extent_osd_data_pages(req, 2 * i,
+ bpages + e->pg, e->len,
+ 0, false, false);
+ if (i)
+ osd_req_op_extent_init(req, 2 * i + 1,
+ CEPH_OSD_OP_WRITE,
+ e->objoff, e->len,
+ tsize, tseq);
+ osd_req_op_extent_osd_data_pages(req, 2 * i + 1,
+ pages + e->pg, e->len,
+ 0, false, false);
+ }
+ req->r_mtime = inode_get_mtime(inode);
+ ceph_osdc_start_request(osdc, req);
+ reqs[q] = req;
+ }
+
+ for (q = 0; q < nreq; q++) {
+ struct ceph_merge_ext *qe = &ext[q * CEPH_MERGE_EXTS_PER_REQ];
+ int m = min(n - q * CEPH_MERGE_EXTS_PER_REQ,
+ CEPH_MERGE_EXTS_PER_REQ);
+ size_t bytes = 0;
+
+ if (!reqs[q])
+ continue;
+ err2 = ceph_osdc_wait_request(osdc, reqs[q]);
+ for (i = 0; i < m; i++)
+ bytes += qe[i].len;
+ ceph_update_write_metrics(&fsc->mdsc->metric,
+ reqs[q]->r_start_latency,
+ reqs[q]->r_end_latency, bytes,
+ CEPH_CMPEXT_MISMATCH(err2) ? 0 : err2);
+ ceph_osdc_put_request(reqs[q]);
+ if (CEPH_CMPEXT_MISMATCH(err2)) {
+ /* lost the compare: send what this client changed */
+ nlost++;
+ WRITE_ONCE(ci->i_kept_conflict, jiffies);
+ err2 = ceph_write_diff(inode, folios, pages, qe, m,
+ snapc, ceph_wbc);
+ }
+ if (!err)
+ err = err2;
+ }
+ doutc(cl, "%llx.%llx %llu~%zu %d runs of folios, %d requests lost the compare\n",
+ ceph_vinop(inode), ext[0].off, ext[0].len, n, nlost);
+out:
+ if (!pgbuf) {
+ kfree(bpages);
+ kfree(pages);
+ }
+ return err;
+}
+
+/*
+ * Add the locked @folio, cleaned for writeback, to @mb. False if it does
+ * not fit: another object, or too many runs or folios.
+ */
+static bool ceph_merge_batch_add(struct inode *inode,
+ struct ceph_merge_batch *mb,
+ struct folio *folio, loff_t i_size)
+{
+ struct ceph_inode_info *ci = ceph_inode(inode);
+ struct ceph_merge_ext *last = NULL;
+ u64 off = folio_pos(folio), objnum, objoff;
+ size_t len = min_t(u64, folio_size(folio), i_size - off);
+ u32 xlen;
+
+ if (mb->nr_folios == CEPH_MERGE_MAX_FOLIOS)
+ return false;
+ ceph_calc_file_object_mapping(&ci->i_layout, off, len,
+ &objnum, &objoff, &xlen);
+ if (mb->nr_exts) {
+ if (objnum != mb->objnum)
+ return false;
+ last = &mb->ext[mb->nr_exts - 1];
+ if (last->off + last->len != off ||
+ last->objoff + last->len != objoff)
+ last = NULL;
+ }
+ if (last) {
+ last->len += len;
+ last->nr++;
+ } else {
+ if (mb->nr_exts == CEPH_MERGE_MAX_EXTS)
+ return false;
+ mb->ext[mb->nr_exts++] = (struct ceph_merge_ext) {
+ .off = off, .objoff = objoff, .len = len,
+ .first = mb->nr_folios, .nr = 1,
+ };
+ }
+ mb->objnum = objnum;
+ mb->folios[mb->nr_folios++] = folio;
+ return true;
+}
+
+/*
+ * Finish the writeback of the locked @folio, of snap context @snapc,
+ * with result @err (0 or a negative error).
+ */
+static int ceph_folio_write_done(struct inode *inode,
+ struct writeback_control *wbc,
+ struct folio *folio,
+ struct ceph_snap_context *snapc, int err)
+{
+ struct ceph_inode_info *ci = ceph_inode(inode);
+ struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
+ struct ceph_client *cl = fsc->client;
+ struct ceph_snap_context *oldest;
+
+ if (err < 0) {
+ struct writeback_control tmp_wbc;
+
+ if (!wbc)
+ wbc = &tmp_wbc;
+ if (err == -ERESTARTSYS || err == -ENOMEM) {
+ /*
+ * killed by SIGKILL, or no memory for the copies
+ * ceph_write_kept() needs: try again later
+ */
+ doutc(cl, "%llx.%llx interrupted page %p\n",
+ ceph_vinop(inode), folio);
+ folio_redirty_for_writepage(wbc, folio);
+ folio_end_writeback(folio);
+ if (atomic_long_dec_return(&fsc->writeback_count) <
+ CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
+ fsc->write_congested = false;
+ return err;
+ }
+ if (err == -EBLOCKLISTED)
+ fsc->blocklisted = true;
+ doutc(cl, "%llx.%llx setting mapping error %d %p\n",
+ ceph_vinop(inode), err, folio);
+ mapping_set_error(&inode->i_data, err);
+ wbc->pages_skipped++;
+ } else {
+ doutc(cl, "%llx.%llx cleaned page %p\n",
+ ceph_vinop(inode), folio);
+ err = 0; /* vfs expects us to return 0 */
+ }
+ oldest = ceph_folio_detach_snapc(folio);
+ WARN_ON_ONCE(oldest != snapc);
+ folio_end_writeback(folio);
+ ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
+ ceph_put_snap_context(snapc); /* page's reference */
+
+ if (atomic64_dec_return(&fsc->mdsc->dirty_folios) <= 0) {
+ wake_up_all(&fsc->mdsc->flush_end_wq);
+ WARN_ON(atomic64_read(&fsc->mdsc->dirty_folios) < 0);
+ }
+
+ if (atomic_long_dec_return(&fsc->writeback_count) <
+ CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
+ fsc->write_congested = false;
+
+ return err;
+}
+
/*
* Write a folio, but leave it locked.
*
@@ -1110,6 +1705,23 @@ static int write_folio_nounlock(struct folio *folio,
CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb))
fsc->write_congested = true;

+ if (ceph_folio_base(folio)) {
+ struct ceph_merge_ext ext = {
+ .off = page_off, .len = len, .first = 0, .nr = 1,
+ };
+ u64 objnum;
+ u32 xlen;
+
+ /* kept whole, see ceph_folio_keep_base() */
+ WARN_ON_ONCE(start);
+ ceph_calc_file_object_mapping(&ci->i_layout, page_off, len,
+ &objnum, &ext.objoff, &xlen);
+ folio_start_writeback(folio);
+ err = ceph_write_kept(inode, &folio, &ext, 1, NULL, snapc,
+ &ceph_wbc);
+ goto written;
+ }
+
req = ceph_osdc_new_request(osdc, &ci->i_layout, ceph_vino(inode),
page_off, &wlen, 0, 1, CEPH_OSD_OP_WRITE,
CEPH_OSD_FLAG_WRITE, snapc,
@@ -1167,51 +1779,8 @@ static int write_folio_nounlock(struct folio *folio,
req->r_end_latency);
fscrypt_free_bounce_page(bounce_page);
ceph_osdc_put_request(req);
- if (err == 0)
- err = len;
-
- if (err < 0) {
- struct writeback_control tmp_wbc;
- if (!wbc)
- wbc = &tmp_wbc;
- if (err == -ERESTARTSYS) {
- /* killed by SIGKILL */
- doutc(cl, "%llx.%llx interrupted page %p\n",
- ceph_vinop(inode), folio);
- folio_redirty_for_writepage(wbc, folio);
- folio_end_writeback(folio);
- if (atomic_long_dec_return(&fsc->writeback_count) <
- CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
- fsc->write_congested = false;
- return err;
- }
- if (err == -EBLOCKLISTED)
- fsc->blocklisted = true;
- doutc(cl, "%llx.%llx setting mapping error %d %p\n",
- ceph_vinop(inode), err, folio);
- mapping_set_error(&inode->i_data, err);
- wbc->pages_skipped++;
- } else {
- doutc(cl, "%llx.%llx cleaned page %p\n",
- ceph_vinop(inode), folio);
- err = 0; /* vfs expects us to return 0 */
- }
- oldest = ceph_folio_detach_snapc(folio);
- WARN_ON_ONCE(oldest != snapc);
- folio_end_writeback(folio);
- ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
- ceph_put_snap_context(snapc); /* page's reference */
-
- if (atomic64_dec_return(&fsc->mdsc->dirty_folios) <= 0) {
- wake_up_all(&fsc->mdsc->flush_end_wq);
- WARN_ON(atomic64_read(&fsc->mdsc->dirty_folios) < 0);
- }
-
- if (atomic_long_dec_return(&fsc->writeback_count) <
- CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
- fsc->write_congested = false;
-
- return err;
+written:
+ return ceph_folio_write_done(inode, wbc, folio, snapc, err);
}

/*
@@ -1674,6 +2243,37 @@ static inline int move_dirty_folio_in_page_array(struct address_space *mapping,
return 0;
}

+/* Write back the folios gathered in @mb, then unlock and release them. */
+static void ceph_merge_batch_flush(struct inode *inode,
+ struct writeback_control *wbc,
+ struct ceph_writeback_ctl *ceph_wbc,
+ struct ceph_merge_batch *mb)
+{
+ struct ceph_inode_info *ci = ceph_inode(inode);
+ bool remove_folio;
+ int i, err;
+
+ if (!mb->nr_folios)
+ return;
+ err = ceph_write_kept(inode, mb->folios, mb->ext, mb->nr_exts,
+ mb->pages, ceph_wbc->snapc, ceph_wbc);
+ /* as writepages_finish() does: without the cache cap drop them */
+ remove_folio = !(ceph_caps_issued(ci) &
+ (CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO));
+ for (i = 0; i < mb->nr_folios; i++) {
+ struct folio *folio = mb->folios[i];
+
+ ceph_folio_write_done(inode, wbc, folio,
+ ceph_folio_snap_context(folio), err);
+ if (remove_folio && !folio_test_dirty(folio))
+ generic_error_remove_folio(inode->i_mapping, folio);
+ folio_unlock(folio);
+ folio_put(folio);
+ }
+ mb->nr_folios = 0;
+ mb->nr_exts = 0;
+}
+
static
void ceph_process_folio_batch(struct address_space *mapping,
struct writeback_control *wbc,
@@ -1682,6 +2282,7 @@ void ceph_process_folio_batch(struct address_space *mapping,
struct inode *inode = mapping->host;
struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
struct ceph_client *cl = fsc->client;
+ struct ceph_merge_batch *mb = NULL;
struct folio *folio = NULL;
u64 start, end;
unsigned i;
@@ -1707,7 +2308,7 @@ void ceph_process_folio_batch(struct address_space *mapping,
continue;
}

- if (ceph_wbc->locked_pages == 0)
+ if (ceph_wbc->locked_pages == 0 && !(mb && mb->nr_folios))
folio_lock(folio);
else if (!folio_trylock(folio))
break;
@@ -1724,6 +2325,52 @@ void ceph_process_folio_batch(struct address_space *mapping,
break;
}

+ /*
+ * Of a folio dirtied through a shared mapping without Fb,
+ * only the bytes changed go out, see ceph_write_kept(),
+ * together with others like it in the same object: first
+ * send what was gathered for a plain write so far.
+ */
+ if (ceph_folio_base(folio)) {
+ if (ceph_wbc->locked_pages) {
+ folio_unlock(folio);
+ break;
+ }
+ if (!folio_clear_dirty_for_io(folio)) {
+ folio_unlock(folio);
+ folio_put(folio);
+ ceph_wbc->fbatch.folios[i] = NULL;
+ continue;
+ }
+ wbc->nr_to_write -= folio_nr_pages(folio);
+ if (!mb)
+ mb = kzalloc_obj(*mb, GFP_NOFS);
+ if (!mb) {
+ /* on its own then */
+ rc = write_folio_nounlock(folio, wbc);
+ if (rc < 0)
+ doutc(cl, "%llx.%llx folio %p: %d\n",
+ ceph_vinop(inode), folio, rc);
+ folio_unlock(folio);
+ folio_put(folio);
+ ceph_wbc->fbatch.folios[i] = NULL;
+ continue;
+ }
+ if (!ceph_merge_batch_add(inode, mb, folio,
+ ceph_wbc->i_size)) {
+ ceph_merge_batch_flush(inode, wbc, ceph_wbc, mb);
+ WARN_ON_ONCE(!ceph_merge_batch_add(inode, mb, folio,
+ ceph_wbc->i_size));
+ }
+ folio_start_writeback(folio);
+ if (is_write_congestion_happened(fsc))
+ fsc->write_congested = true;
+ ceph_wbc->fbatch.folios[i] = NULL;
+ continue;
+ }
+ if (mb)
+ ceph_merge_batch_flush(inode, wbc, ceph_wbc, mb);
+
/*
* Nor may it need an extent beyond the request's ops: check
* that before the folio is cleaned, as redirtying it would
@@ -1785,6 +2432,10 @@ void ceph_process_folio_batch(struct address_space *mapping,
ceph_wbc->len += end - start;
}

+ if (mb) {
+ ceph_merge_batch_flush(inode, wbc, ceph_wbc, mb);
+ kfree(mb);
+ }
ceph_wbc->processed_in_fbatch = i;
}

@@ -2841,6 +3492,7 @@ static vm_fault_t ceph_page_mkwrite(struct vm_fault *vmf)
loff_t size = i_size_read(inode);
size_t len;
int want, got, err;
+ bool keep_base;
sigset_t oldset;
vm_fault_t ret = VM_FAULT_SIGBUS;

@@ -2911,6 +3563,15 @@ static vm_fault_t ceph_page_mkwrite(struct vm_fault *vmf)
goto retry_caps;
}

+ /*
+ * Neither Fb nor lazy I/O: other clients may write to the file
+ * meanwhile, see ceph_folio_keep_base(). (Not for encrypted
+ * files, which go out in whole crypto blocks, nor with fscache,
+ * which caches what is written back.)
+ */
+ keep_base = !(got & (CEPH_CAP_FILE_BUFFER | CEPH_CAP_FILE_LAZYIO)) &&
+ !IS_ENCRYPTED(inode) && !ceph_is_cache_enabled(inode);
+
/* Update time before taking folio lock */
file_update_time(vma->vm_file);
inode_inc_iversion_raw(inode);
@@ -2928,9 +3589,13 @@ static vm_fault_t ceph_page_mkwrite(struct vm_fault *vmf)

snapc = ceph_find_incompatible(folio);
if (!snapc) {
+ bool was_dirty = folio_test_dirty(folio);
+
/* success. we'll keep the folio locked. */
folio_mark_dirty(folio);
ceph_folio_dirty_whole(folio);
+ if (!was_dirty && keep_base)
+ ceph_folio_keep_base(folio);
ret = VM_FAULT_LOCKED;
break;
}
diff --git a/fs/ceph/inode.c b/fs/ceph/inode.c
index 151879b402c4..77ebf4e54529 100644
--- a/fs/ceph/inode.c
+++ b/fs/ceph/inode.c
@@ -676,6 +676,7 @@ struct inode *ceph_alloc_inode(struct super_block *sb)
INIT_LIST_HEAD(&ci->i_cap_flush_list);
init_waitqueue_head(&ci->i_cap_wq);
ci->i_hold_caps_max = 0;
+ ci->i_kept_conflict = jiffies - 2 * HZ;
INIT_LIST_HEAD(&ci->i_cap_delay_list);
INIT_LIST_HEAD(&ci->i_cap_snaps);
ci->i_head_snapc = NULL;
diff --git a/fs/ceph/super.h b/fs/ceph/super.h
index 978dd7be1778..391e055d2a33 100644
--- a/fs/ceph/super.h
+++ b/fs/ceph/super.h
@@ -477,6 +477,7 @@ struct ceph_inode_info {
struct list_head i_cap_flush_list;
wait_queue_head_t i_cap_wq; /* threads waiting on a capability */
unsigned long i_hold_caps_max; /* jiffies */
+ unsigned long i_kept_conflict; /* jiffies, see ceph_write_kept() */
struct list_head i_cap_delay_list; /* for delayed cap release to mds */
struct list_head i_cap_snaps; /* snapped state pending flush to mds */
struct ceph_snap_context *i_head_snapc; /* set if wr_buffer_head > 0 or

--
2.53.0