xref: /openbmc/linux/fs/ceph/addr.c (revision 1587db11)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 
4 #include <linux/backing-dev.h>
5 #include <linux/fs.h>
6 #include <linux/mm.h>
7 #include <linux/swap.h>
8 #include <linux/pagemap.h>
9 #include <linux/slab.h>
10 #include <linux/pagevec.h>
11 #include <linux/task_io_accounting_ops.h>
12 #include <linux/signal.h>
13 #include <linux/iversion.h>
14 #include <linux/ktime.h>
15 #include <linux/netfs.h>
16 
17 #include "super.h"
18 #include "mds_client.h"
19 #include "cache.h"
20 #include "metric.h"
21 #include "crypto.h"
22 #include <linux/ceph/osd_client.h>
23 #include <linux/ceph/striper.h>
24 
25 /*
26  * Ceph address space ops.
27  *
28  * There are a few funny things going on here.
29  *
30  * The page->private field is used to reference a struct
31  * ceph_snap_context for _every_ dirty page.  This indicates which
32  * snapshot the page was logically dirtied in, and thus which snap
33  * context needs to be associated with the osd write during writeback.
34  *
35  * Similarly, struct ceph_inode_info maintains a set of counters to
36  * count dirty pages on the inode.  In the absence of snapshots,
37  * i_wrbuffer_ref == i_wrbuffer_ref_head == the dirty page count.
38  *
39  * When a snapshot is taken (that is, when the client receives
40  * notification that a snapshot was taken), each inode with caps and
41  * with dirty pages (dirty pages implies there is a cap) gets a new
42  * ceph_cap_snap in the i_cap_snaps list (which is sorted in ascending
43  * order, new snaps go to the tail).  The i_wrbuffer_ref_head count is
44  * moved to capsnap->dirty. (Unless a sync write is currently in
45  * progress.  In that case, the capsnap is said to be "pending", new
46  * writes cannot start, and the capsnap isn't "finalized" until the
47  * write completes (or fails) and a final size/mtime for the inode for
48  * that snap can be settled upon.)  i_wrbuffer_ref_head is reset to 0.
49  *
50  * On writeback, we must submit writes to the osd IN SNAP ORDER.  So,
51  * we look for the first capsnap in i_cap_snaps and write out pages in
52  * that snap context _only_.  Then we move on to the next capsnap,
53  * eventually reaching the "live" or "head" context (i.e., pages that
54  * are not yet snapped) and are writing the most recently dirtied
55  * pages.
56  *
57  * Invalidate and so forth must take care to ensure the dirty page
58  * accounting is preserved.
59  */
60 
61 #define CONGESTION_ON_THRESH(congestion_kb) (congestion_kb >> (PAGE_SHIFT-10))
62 #define CONGESTION_OFF_THRESH(congestion_kb)				\
63 	(CONGESTION_ON_THRESH(congestion_kb) -				\
64 	 (CONGESTION_ON_THRESH(congestion_kb) >> 2))
65 
66 static int ceph_netfs_check_write_begin(struct file *file, loff_t pos, unsigned int len,
67 					struct folio **foliop, void **_fsdata);
68 
69 static inline struct ceph_snap_context *page_snap_context(struct page *page)
70 {
71 	if (PagePrivate(page))
72 		return (void *)page->private;
73 	return NULL;
74 }
75 
76 /*
77  * Dirty a page.  Optimistically adjust accounting, on the assumption
78  * that we won't race with invalidate.  If we do, readjust.
79  */
80 static bool ceph_dirty_folio(struct address_space *mapping, struct folio *folio)
81 {
82 	struct inode *inode;
83 	struct ceph_inode_info *ci;
84 	struct ceph_snap_context *snapc;
85 
86 	if (folio_test_dirty(folio)) {
87 		dout("%p dirty_folio %p idx %lu -- already dirty\n",
88 		     mapping->host, folio, folio->index);
89 		VM_BUG_ON_FOLIO(!folio_test_private(folio), folio);
90 		return false;
91 	}
92 
93 	inode = mapping->host;
94 	ci = ceph_inode(inode);
95 
96 	/* dirty the head */
97 	spin_lock(&ci->i_ceph_lock);
98 	if (__ceph_have_pending_cap_snap(ci)) {
99 		struct ceph_cap_snap *capsnap =
100 				list_last_entry(&ci->i_cap_snaps,
101 						struct ceph_cap_snap,
102 						ci_item);
103 		snapc = ceph_get_snap_context(capsnap->context);
104 		capsnap->dirty_pages++;
105 	} else {
106 		BUG_ON(!ci->i_head_snapc);
107 		snapc = ceph_get_snap_context(ci->i_head_snapc);
108 		++ci->i_wrbuffer_ref_head;
109 	}
110 	if (ci->i_wrbuffer_ref == 0)
111 		ihold(inode);
112 	++ci->i_wrbuffer_ref;
113 	dout("%p dirty_folio %p idx %lu head %d/%d -> %d/%d "
114 	     "snapc %p seq %lld (%d snaps)\n",
115 	     mapping->host, folio, folio->index,
116 	     ci->i_wrbuffer_ref-1, ci->i_wrbuffer_ref_head-1,
117 	     ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head,
118 	     snapc, snapc->seq, snapc->num_snaps);
119 	spin_unlock(&ci->i_ceph_lock);
120 
121 	/*
122 	 * Reference snap context in folio->private.  Also set
123 	 * PagePrivate so that we get invalidate_folio callback.
124 	 */
125 	VM_WARN_ON_FOLIO(folio->private, folio);
126 	folio_attach_private(folio, snapc);
127 
128 	return ceph_fscache_dirty_folio(mapping, folio);
129 }
130 
131 /*
132  * If we are truncating the full folio (i.e. offset == 0), adjust the
133  * dirty folio counters appropriately.  Only called if there is private
134  * data on the folio.
135  */
136 static void ceph_invalidate_folio(struct folio *folio, size_t offset,
137 				size_t length)
138 {
139 	struct inode *inode;
140 	struct ceph_inode_info *ci;
141 	struct ceph_snap_context *snapc;
142 
143 	inode = folio->mapping->host;
144 	ci = ceph_inode(inode);
145 
146 	if (offset != 0 || length != folio_size(folio)) {
147 		dout("%p invalidate_folio idx %lu partial dirty page %zu~%zu\n",
148 		     inode, folio->index, offset, length);
149 		return;
150 	}
151 
152 	WARN_ON(!folio_test_locked(folio));
153 	if (folio_test_private(folio)) {
154 		dout("%p invalidate_folio idx %lu full dirty page\n",
155 		     inode, folio->index);
156 
157 		snapc = folio_detach_private(folio);
158 		ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
159 		ceph_put_snap_context(snapc);
160 	}
161 
162 	folio_wait_fscache(folio);
163 }
164 
165 static bool ceph_release_folio(struct folio *folio, gfp_t gfp)
166 {
167 	struct inode *inode = folio->mapping->host;
168 
169 	dout("%llx:%llx release_folio idx %lu (%sdirty)\n",
170 	     ceph_vinop(inode),
171 	     folio->index, folio_test_dirty(folio) ? "" : "not ");
172 
173 	if (folio_test_private(folio))
174 		return false;
175 
176 	if (folio_test_fscache(folio)) {
177 		if (current_is_kswapd() || !(gfp & __GFP_FS))
178 			return false;
179 		folio_wait_fscache(folio);
180 	}
181 	ceph_fscache_note_page_release(inode);
182 	return true;
183 }
184 
185 static void ceph_netfs_expand_readahead(struct netfs_io_request *rreq)
186 {
187 	struct inode *inode = rreq->inode;
188 	struct ceph_inode_info *ci = ceph_inode(inode);
189 	struct ceph_file_layout *lo = &ci->i_layout;
190 	unsigned long max_pages = inode->i_sb->s_bdi->ra_pages;
191 	loff_t end = rreq->start + rreq->len, new_end;
192 	struct ceph_netfs_request_data *priv = rreq->netfs_priv;
193 	unsigned long max_len;
194 	u32 blockoff;
195 
196 	if (priv) {
197 		/* Readahead is disabled by posix_fadvise POSIX_FADV_RANDOM */
198 		if (priv->file_ra_disabled)
199 			max_pages = 0;
200 		else
201 			max_pages = priv->file_ra_pages;
202 
203 	}
204 
205 	/* Readahead is disabled */
206 	if (!max_pages)
207 		return;
208 
209 	max_len = max_pages << PAGE_SHIFT;
210 
211 	/*
212 	 * Try to expand the length forward by rounding up it to the next
213 	 * block, but do not exceed the file size, unless the original
214 	 * request already exceeds it.
215 	 */
216 	new_end = min(round_up(end, lo->stripe_unit), rreq->i_size);
217 	if (new_end > end && new_end <= rreq->start + max_len)
218 		rreq->len = new_end - rreq->start;
219 
220 	/* Try to expand the start downward */
221 	div_u64_rem(rreq->start, lo->stripe_unit, &blockoff);
222 	if (rreq->len + blockoff <= max_len) {
223 		rreq->start -= blockoff;
224 		rreq->len += blockoff;
225 	}
226 }
227 
228 static bool ceph_netfs_clamp_length(struct netfs_io_subrequest *subreq)
229 {
230 	struct inode *inode = subreq->rreq->inode;
231 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
232 	struct ceph_inode_info *ci = ceph_inode(inode);
233 	u64 objno, objoff;
234 	u32 xlen;
235 
236 	/* Truncate the extent at the end of the current block */
237 	ceph_calc_file_object_mapping(&ci->i_layout, subreq->start, subreq->len,
238 				      &objno, &objoff, &xlen);
239 	subreq->len = min(xlen, fsc->mount_options->rsize);
240 	return true;
241 }
242 
243 static void finish_netfs_read(struct ceph_osd_request *req)
244 {
245 	struct inode *inode = req->r_inode;
246 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
247 	struct ceph_osd_data *osd_data = osd_req_op_extent_osd_data(req, 0);
248 	struct netfs_io_subrequest *subreq = req->r_priv;
249 	struct ceph_osd_req_op *op = &req->r_ops[0];
250 	int err = req->r_result;
251 	bool sparse = (op->op == CEPH_OSD_OP_SPARSE_READ);
252 
253 	ceph_update_read_metrics(&fsc->mdsc->metric, req->r_start_latency,
254 				 req->r_end_latency, osd_data->length, err);
255 
256 	dout("%s: result %d subreq->len=%zu i_size=%lld\n", __func__, req->r_result,
257 	     subreq->len, i_size_read(req->r_inode));
258 
259 	/* no object means success but no data */
260 	if (err == -ENOENT)
261 		err = 0;
262 	else if (err == -EBLOCKLISTED)
263 		fsc->blocklisted = true;
264 
265 	if (err >= 0) {
266 		if (sparse && err > 0)
267 			err = ceph_sparse_ext_map_end(op);
268 		if (err < subreq->len)
269 			__set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags);
270 		if (IS_ENCRYPTED(inode) && err > 0) {
271 			err = ceph_fscrypt_decrypt_extents(inode,
272 					osd_data->pages, subreq->start,
273 					op->extent.sparse_ext,
274 					op->extent.sparse_ext_cnt);
275 			if (err > subreq->len)
276 				err = subreq->len;
277 		}
278 	}
279 
280 	if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGES) {
281 		ceph_put_page_vector(osd_data->pages,
282 				     calc_pages_for(osd_data->alignment,
283 					osd_data->length), false);
284 	}
285 	netfs_subreq_terminated(subreq, err, false);
286 	iput(req->r_inode);
287 	ceph_dec_osd_stopping_blocker(fsc->mdsc);
288 }
289 
290 static bool ceph_netfs_issue_op_inline(struct netfs_io_subrequest *subreq)
291 {
292 	struct netfs_io_request *rreq = subreq->rreq;
293 	struct inode *inode = rreq->inode;
294 	struct ceph_mds_reply_info_parsed *rinfo;
295 	struct ceph_mds_reply_info_in *iinfo;
296 	struct ceph_mds_request *req;
297 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
298 	struct ceph_inode_info *ci = ceph_inode(inode);
299 	struct iov_iter iter;
300 	ssize_t err = 0;
301 	size_t len;
302 	int mode;
303 
304 	__set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags);
305 	__clear_bit(NETFS_SREQ_COPY_TO_CACHE, &subreq->flags);
306 
307 	if (subreq->start >= inode->i_size)
308 		goto out;
309 
310 	/* We need to fetch the inline data. */
311 	mode = ceph_try_to_choose_auth_mds(inode, CEPH_STAT_CAP_INLINE_DATA);
312 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_GETATTR, mode);
313 	if (IS_ERR(req)) {
314 		err = PTR_ERR(req);
315 		goto out;
316 	}
317 	req->r_ino1 = ci->i_vino;
318 	req->r_args.getattr.mask = cpu_to_le32(CEPH_STAT_CAP_INLINE_DATA);
319 	req->r_num_caps = 2;
320 
321 	err = ceph_mdsc_do_request(mdsc, NULL, req);
322 	if (err < 0)
323 		goto out;
324 
325 	rinfo = &req->r_reply_info;
326 	iinfo = &rinfo->targeti;
327 	if (iinfo->inline_version == CEPH_INLINE_NONE) {
328 		/* The data got uninlined */
329 		ceph_mdsc_put_request(req);
330 		return false;
331 	}
332 
333 	len = min_t(size_t, iinfo->inline_len - subreq->start, subreq->len);
334 	iov_iter_xarray(&iter, ITER_DEST, &rreq->mapping->i_pages, subreq->start, len);
335 	err = copy_to_iter(iinfo->inline_data + subreq->start, len, &iter);
336 	if (err == 0)
337 		err = -EFAULT;
338 
339 	ceph_mdsc_put_request(req);
340 out:
341 	netfs_subreq_terminated(subreq, err, false);
342 	return true;
343 }
344 
345 static void ceph_netfs_issue_read(struct netfs_io_subrequest *subreq)
346 {
347 	struct netfs_io_request *rreq = subreq->rreq;
348 	struct inode *inode = rreq->inode;
349 	struct ceph_inode_info *ci = ceph_inode(inode);
350 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
351 	struct ceph_osd_request *req = NULL;
352 	struct ceph_vino vino = ceph_vino(inode);
353 	struct iov_iter iter;
354 	int err = 0;
355 	u64 len = subreq->len;
356 	bool sparse = IS_ENCRYPTED(inode) || ceph_test_mount_opt(fsc, SPARSEREAD);
357 	u64 off = subreq->start;
358 
359 	if (ceph_inode_is_shutdown(inode)) {
360 		err = -EIO;
361 		goto out;
362 	}
363 
364 	if (ceph_has_inline_data(ci) && ceph_netfs_issue_op_inline(subreq))
365 		return;
366 
367 	ceph_fscrypt_adjust_off_and_len(inode, &off, &len);
368 
369 	req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout, vino,
370 			off, &len, 0, 1, sparse ? CEPH_OSD_OP_SPARSE_READ : CEPH_OSD_OP_READ,
371 			CEPH_OSD_FLAG_READ | fsc->client->osdc.client->options->read_from_replica,
372 			NULL, ci->i_truncate_seq, ci->i_truncate_size, false);
373 	if (IS_ERR(req)) {
374 		err = PTR_ERR(req);
375 		req = NULL;
376 		goto out;
377 	}
378 
379 	if (sparse) {
380 		err = ceph_alloc_sparse_ext_map(&req->r_ops[0]);
381 		if (err)
382 			goto out;
383 	}
384 
385 	dout("%s: pos=%llu orig_len=%zu len=%llu\n", __func__, subreq->start, subreq->len, len);
386 
387 	iov_iter_xarray(&iter, ITER_DEST, &rreq->mapping->i_pages, subreq->start, len);
388 
389 	/*
390 	 * FIXME: For now, use CEPH_OSD_DATA_TYPE_PAGES instead of _ITER for
391 	 * encrypted inodes. We'd need infrastructure that handles an iov_iter
392 	 * instead of page arrays, and we don't have that as of yet. Once the
393 	 * dust settles on the write helpers and encrypt/decrypt routines for
394 	 * netfs, we should be able to rework this.
395 	 */
396 	if (IS_ENCRYPTED(inode)) {
397 		struct page **pages;
398 		size_t page_off;
399 
400 		err = iov_iter_get_pages_alloc2(&iter, &pages, len, &page_off);
401 		if (err < 0) {
402 			dout("%s: iov_ter_get_pages_alloc returned %d\n",
403 			     __func__, err);
404 			goto out;
405 		}
406 
407 		/* should always give us a page-aligned read */
408 		WARN_ON_ONCE(page_off);
409 		len = err;
410 		err = 0;
411 
412 		osd_req_op_extent_osd_data_pages(req, 0, pages, len, 0, false,
413 						 false);
414 	} else {
415 		osd_req_op_extent_osd_iter(req, 0, &iter);
416 	}
417 	if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
418 		err = -EIO;
419 		goto out;
420 	}
421 	req->r_callback = finish_netfs_read;
422 	req->r_priv = subreq;
423 	req->r_inode = inode;
424 	ihold(inode);
425 
426 	ceph_osdc_start_request(req->r_osdc, req);
427 out:
428 	ceph_osdc_put_request(req);
429 	if (err)
430 		netfs_subreq_terminated(subreq, err, false);
431 	dout("%s: result %d\n", __func__, err);
432 }
433 
434 static int ceph_init_request(struct netfs_io_request *rreq, struct file *file)
435 {
436 	struct inode *inode = rreq->inode;
437 	int got = 0, want = CEPH_CAP_FILE_CACHE;
438 	struct ceph_netfs_request_data *priv;
439 	int ret = 0;
440 
441 	if (rreq->origin != NETFS_READAHEAD)
442 		return 0;
443 
444 	priv = kzalloc(sizeof(*priv), GFP_NOFS);
445 	if (!priv)
446 		return -ENOMEM;
447 
448 	if (file) {
449 		struct ceph_rw_context *rw_ctx;
450 		struct ceph_file_info *fi = file->private_data;
451 
452 		priv->file_ra_pages = file->f_ra.ra_pages;
453 		priv->file_ra_disabled = file->f_mode & FMODE_RANDOM;
454 
455 		rw_ctx = ceph_find_rw_context(fi);
456 		if (rw_ctx) {
457 			rreq->netfs_priv = priv;
458 			return 0;
459 		}
460 	}
461 
462 	/*
463 	 * readahead callers do not necessarily hold Fcb caps
464 	 * (e.g. fadvise, madvise).
465 	 */
466 	ret = ceph_try_get_caps(inode, CEPH_CAP_FILE_RD, want, true, &got);
467 	if (ret < 0) {
468 		dout("start_read %p, error getting cap\n", inode);
469 		goto out;
470 	}
471 
472 	if (!(got & want)) {
473 		dout("start_read %p, no cache cap\n", inode);
474 		ret = -EACCES;
475 		goto out;
476 	}
477 	if (ret == 0) {
478 		ret = -EACCES;
479 		goto out;
480 	}
481 
482 	priv->caps = got;
483 	rreq->netfs_priv = priv;
484 
485 out:
486 	if (ret < 0)
487 		kfree(priv);
488 
489 	return ret;
490 }
491 
492 static void ceph_netfs_free_request(struct netfs_io_request *rreq)
493 {
494 	struct ceph_netfs_request_data *priv = rreq->netfs_priv;
495 
496 	if (!priv)
497 		return;
498 
499 	if (priv->caps)
500 		ceph_put_cap_refs(ceph_inode(rreq->inode), priv->caps);
501 	kfree(priv);
502 	rreq->netfs_priv = NULL;
503 }
504 
505 const struct netfs_request_ops ceph_netfs_ops = {
506 	.init_request		= ceph_init_request,
507 	.free_request		= ceph_netfs_free_request,
508 	.begin_cache_operation	= ceph_begin_cache_operation,
509 	.issue_read		= ceph_netfs_issue_read,
510 	.expand_readahead	= ceph_netfs_expand_readahead,
511 	.clamp_length		= ceph_netfs_clamp_length,
512 	.check_write_begin	= ceph_netfs_check_write_begin,
513 };
514 
515 #ifdef CONFIG_CEPH_FSCACHE
516 static void ceph_set_page_fscache(struct page *page)
517 {
518 	set_page_fscache(page);
519 }
520 
521 static void ceph_fscache_write_terminated(void *priv, ssize_t error, bool was_async)
522 {
523 	struct inode *inode = priv;
524 
525 	if (IS_ERR_VALUE(error) && error != -ENOBUFS)
526 		ceph_fscache_invalidate(inode, false);
527 }
528 
529 static void ceph_fscache_write_to_cache(struct inode *inode, u64 off, u64 len, bool caching)
530 {
531 	struct ceph_inode_info *ci = ceph_inode(inode);
532 	struct fscache_cookie *cookie = ceph_fscache_cookie(ci);
533 
534 	fscache_write_to_cache(cookie, inode->i_mapping, off, len, i_size_read(inode),
535 			       ceph_fscache_write_terminated, inode, caching);
536 }
537 #else
538 static inline void ceph_set_page_fscache(struct page *page)
539 {
540 }
541 
542 static inline void ceph_fscache_write_to_cache(struct inode *inode, u64 off, u64 len, bool caching)
543 {
544 }
545 #endif /* CONFIG_CEPH_FSCACHE */
546 
547 struct ceph_writeback_ctl
548 {
549 	loff_t i_size;
550 	u64 truncate_size;
551 	u32 truncate_seq;
552 	bool size_stable;
553 	bool head_snapc;
554 };
555 
556 /*
557  * Get ref for the oldest snapc for an inode with dirty data... that is, the
558  * only snap context we are allowed to write back.
559  */
560 static struct ceph_snap_context *
561 get_oldest_context(struct inode *inode, struct ceph_writeback_ctl *ctl,
562 		   struct ceph_snap_context *page_snapc)
563 {
564 	struct ceph_inode_info *ci = ceph_inode(inode);
565 	struct ceph_snap_context *snapc = NULL;
566 	struct ceph_cap_snap *capsnap = NULL;
567 
568 	spin_lock(&ci->i_ceph_lock);
569 	list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
570 		dout(" cap_snap %p snapc %p has %d dirty pages\n", capsnap,
571 		     capsnap->context, capsnap->dirty_pages);
572 		if (!capsnap->dirty_pages)
573 			continue;
574 
575 		/* get i_size, truncate_{seq,size} for page_snapc? */
576 		if (snapc && capsnap->context != page_snapc)
577 			continue;
578 
579 		if (ctl) {
580 			if (capsnap->writing) {
581 				ctl->i_size = i_size_read(inode);
582 				ctl->size_stable = false;
583 			} else {
584 				ctl->i_size = capsnap->size;
585 				ctl->size_stable = true;
586 			}
587 			ctl->truncate_size = capsnap->truncate_size;
588 			ctl->truncate_seq = capsnap->truncate_seq;
589 			ctl->head_snapc = false;
590 		}
591 
592 		if (snapc)
593 			break;
594 
595 		snapc = ceph_get_snap_context(capsnap->context);
596 		if (!page_snapc ||
597 		    page_snapc == snapc ||
598 		    page_snapc->seq > snapc->seq)
599 			break;
600 	}
601 	if (!snapc && ci->i_wrbuffer_ref_head) {
602 		snapc = ceph_get_snap_context(ci->i_head_snapc);
603 		dout(" head snapc %p has %d dirty pages\n",
604 		     snapc, ci->i_wrbuffer_ref_head);
605 		if (ctl) {
606 			ctl->i_size = i_size_read(inode);
607 			ctl->truncate_size = ci->i_truncate_size;
608 			ctl->truncate_seq = ci->i_truncate_seq;
609 			ctl->size_stable = false;
610 			ctl->head_snapc = true;
611 		}
612 	}
613 	spin_unlock(&ci->i_ceph_lock);
614 	return snapc;
615 }
616 
617 static u64 get_writepages_data_length(struct inode *inode,
618 				      struct page *page, u64 start)
619 {
620 	struct ceph_inode_info *ci = ceph_inode(inode);
621 	struct ceph_snap_context *snapc;
622 	struct ceph_cap_snap *capsnap = NULL;
623 	u64 end = i_size_read(inode);
624 	u64 ret;
625 
626 	snapc = page_snap_context(ceph_fscrypt_pagecache_page(page));
627 	if (snapc != ci->i_head_snapc) {
628 		bool found = false;
629 		spin_lock(&ci->i_ceph_lock);
630 		list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
631 			if (capsnap->context == snapc) {
632 				if (!capsnap->writing)
633 					end = capsnap->size;
634 				found = true;
635 				break;
636 			}
637 		}
638 		spin_unlock(&ci->i_ceph_lock);
639 		WARN_ON(!found);
640 	}
641 	if (end > ceph_fscrypt_page_offset(page) + thp_size(page))
642 		end = ceph_fscrypt_page_offset(page) + thp_size(page);
643 	ret = end > start ? end - start : 0;
644 	if (ret && fscrypt_is_bounce_page(page))
645 		ret = round_up(ret, CEPH_FSCRYPT_BLOCK_SIZE);
646 	return ret;
647 }
648 
649 /*
650  * Write a single page, but leave the page locked.
651  *
652  * If we get a write error, mark the mapping for error, but still adjust the
653  * dirty page accounting (i.e., page is no longer dirty).
654  */
655 static int writepage_nounlock(struct page *page, struct writeback_control *wbc)
656 {
657 	struct folio *folio = page_folio(page);
658 	struct inode *inode = page->mapping->host;
659 	struct ceph_inode_info *ci = ceph_inode(inode);
660 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
661 	struct ceph_snap_context *snapc, *oldest;
662 	loff_t page_off = page_offset(page);
663 	int err;
664 	loff_t len = thp_size(page);
665 	loff_t wlen;
666 	struct ceph_writeback_ctl ceph_wbc;
667 	struct ceph_osd_client *osdc = &fsc->client->osdc;
668 	struct ceph_osd_request *req;
669 	bool caching = ceph_is_cache_enabled(inode);
670 	struct page *bounce_page = NULL;
671 
672 	dout("writepage %p idx %lu\n", page, page->index);
673 
674 	if (ceph_inode_is_shutdown(inode))
675 		return -EIO;
676 
677 	/* verify this is a writeable snap context */
678 	snapc = page_snap_context(page);
679 	if (!snapc) {
680 		dout("writepage %p page %p not dirty?\n", inode, page);
681 		return 0;
682 	}
683 	oldest = get_oldest_context(inode, &ceph_wbc, snapc);
684 	if (snapc->seq > oldest->seq) {
685 		dout("writepage %p page %p snapc %p not writeable - noop\n",
686 		     inode, page, snapc);
687 		/* we should only noop if called by kswapd */
688 		WARN_ON(!(current->flags & PF_MEMALLOC));
689 		ceph_put_snap_context(oldest);
690 		redirty_page_for_writepage(wbc, page);
691 		return 0;
692 	}
693 	ceph_put_snap_context(oldest);
694 
695 	/* is this a partial page at end of file? */
696 	if (page_off >= ceph_wbc.i_size) {
697 		dout("folio at %lu beyond eof %llu\n", folio->index,
698 				ceph_wbc.i_size);
699 		folio_invalidate(folio, 0, folio_size(folio));
700 		return 0;
701 	}
702 
703 	if (ceph_wbc.i_size < page_off + len)
704 		len = ceph_wbc.i_size - page_off;
705 
706 	wlen = IS_ENCRYPTED(inode) ? round_up(len, CEPH_FSCRYPT_BLOCK_SIZE) : len;
707 	dout("writepage %p page %p index %lu on %llu~%llu snapc %p seq %lld\n",
708 	     inode, page, page->index, page_off, wlen, snapc, snapc->seq);
709 
710 	if (atomic_long_inc_return(&fsc->writeback_count) >
711 	    CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb))
712 		fsc->write_congested = true;
713 
714 	req = ceph_osdc_new_request(osdc, &ci->i_layout, ceph_vino(inode),
715 				    page_off, &wlen, 0, 1, CEPH_OSD_OP_WRITE,
716 				    CEPH_OSD_FLAG_WRITE, snapc,
717 				    ceph_wbc.truncate_seq,
718 				    ceph_wbc.truncate_size, true);
719 	if (IS_ERR(req)) {
720 		redirty_page_for_writepage(wbc, page);
721 		return PTR_ERR(req);
722 	}
723 
724 	if (wlen < len)
725 		len = wlen;
726 
727 	set_page_writeback(page);
728 	if (caching)
729 		ceph_set_page_fscache(page);
730 	ceph_fscache_write_to_cache(inode, page_off, len, caching);
731 
732 	if (IS_ENCRYPTED(inode)) {
733 		bounce_page = fscrypt_encrypt_pagecache_blocks(page,
734 						    CEPH_FSCRYPT_BLOCK_SIZE, 0,
735 						    GFP_NOFS);
736 		if (IS_ERR(bounce_page)) {
737 			redirty_page_for_writepage(wbc, page);
738 			end_page_writeback(page);
739 			ceph_osdc_put_request(req);
740 			return PTR_ERR(bounce_page);
741 		}
742 	}
743 
744 	/* it may be a short write due to an object boundary */
745 	WARN_ON_ONCE(len > thp_size(page));
746 	osd_req_op_extent_osd_data_pages(req, 0,
747 			bounce_page ? &bounce_page : &page, wlen, 0,
748 			false, false);
749 	dout("writepage %llu~%llu (%llu bytes, %sencrypted)\n",
750 	     page_off, len, wlen, IS_ENCRYPTED(inode) ? "" : "not ");
751 
752 	req->r_mtime = inode->i_mtime;
753 	ceph_osdc_start_request(osdc, req);
754 	err = ceph_osdc_wait_request(osdc, req);
755 
756 	ceph_update_write_metrics(&fsc->mdsc->metric, req->r_start_latency,
757 				  req->r_end_latency, len, err);
758 	fscrypt_free_bounce_page(bounce_page);
759 	ceph_osdc_put_request(req);
760 	if (err == 0)
761 		err = len;
762 
763 	if (err < 0) {
764 		struct writeback_control tmp_wbc;
765 		if (!wbc)
766 			wbc = &tmp_wbc;
767 		if (err == -ERESTARTSYS) {
768 			/* killed by SIGKILL */
769 			dout("writepage interrupted page %p\n", page);
770 			redirty_page_for_writepage(wbc, page);
771 			end_page_writeback(page);
772 			return err;
773 		}
774 		if (err == -EBLOCKLISTED)
775 			fsc->blocklisted = true;
776 		dout("writepage setting page/mapping error %d %p\n",
777 		     err, page);
778 		mapping_set_error(&inode->i_data, err);
779 		wbc->pages_skipped++;
780 	} else {
781 		dout("writepage cleaned page %p\n", page);
782 		err = 0;  /* vfs expects us to return 0 */
783 	}
784 	oldest = detach_page_private(page);
785 	WARN_ON_ONCE(oldest != snapc);
786 	end_page_writeback(page);
787 	ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
788 	ceph_put_snap_context(snapc);  /* page's reference */
789 
790 	if (atomic_long_dec_return(&fsc->writeback_count) <
791 	    CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
792 		fsc->write_congested = false;
793 
794 	return err;
795 }
796 
797 static int ceph_writepage(struct page *page, struct writeback_control *wbc)
798 {
799 	int err;
800 	struct inode *inode = page->mapping->host;
801 	BUG_ON(!inode);
802 	ihold(inode);
803 
804 	if (wbc->sync_mode == WB_SYNC_NONE &&
805 	    ceph_inode_to_fs_client(inode)->write_congested) {
806 		redirty_page_for_writepage(wbc, page);
807 		return AOP_WRITEPAGE_ACTIVATE;
808 	}
809 
810 	wait_on_page_fscache(page);
811 
812 	err = writepage_nounlock(page, wbc);
813 	if (err == -ERESTARTSYS) {
814 		/* direct memory reclaimer was killed by SIGKILL. return 0
815 		 * to prevent caller from setting mapping/page error */
816 		err = 0;
817 	}
818 	unlock_page(page);
819 	iput(inode);
820 	return err;
821 }
822 
823 /*
824  * async writeback completion handler.
825  *
826  * If we get an error, set the mapping error bit, but not the individual
827  * page error bits.
828  */
829 static void writepages_finish(struct ceph_osd_request *req)
830 {
831 	struct inode *inode = req->r_inode;
832 	struct ceph_inode_info *ci = ceph_inode(inode);
833 	struct ceph_osd_data *osd_data;
834 	struct page *page;
835 	int num_pages, total_pages = 0;
836 	int i, j;
837 	int rc = req->r_result;
838 	struct ceph_snap_context *snapc = req->r_snapc;
839 	struct address_space *mapping = inode->i_mapping;
840 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
841 	unsigned int len = 0;
842 	bool remove_page;
843 
844 	dout("writepages_finish %p rc %d\n", inode, rc);
845 	if (rc < 0) {
846 		mapping_set_error(mapping, rc);
847 		ceph_set_error_write(ci);
848 		if (rc == -EBLOCKLISTED)
849 			fsc->blocklisted = true;
850 	} else {
851 		ceph_clear_error_write(ci);
852 	}
853 
854 	/*
855 	 * We lost the cache cap, need to truncate the page before
856 	 * it is unlocked, otherwise we'd truncate it later in the
857 	 * page truncation thread, possibly losing some data that
858 	 * raced its way in
859 	 */
860 	remove_page = !(ceph_caps_issued(ci) &
861 			(CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO));
862 
863 	/* clean all pages */
864 	for (i = 0; i < req->r_num_ops; i++) {
865 		if (req->r_ops[i].op != CEPH_OSD_OP_WRITE) {
866 			pr_warn("%s incorrect op %d req %p index %d tid %llu\n",
867 				__func__, req->r_ops[i].op, req, i, req->r_tid);
868 			break;
869 		}
870 
871 		osd_data = osd_req_op_extent_osd_data(req, i);
872 		BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_PAGES);
873 		len += osd_data->length;
874 		num_pages = calc_pages_for((u64)osd_data->alignment,
875 					   (u64)osd_data->length);
876 		total_pages += num_pages;
877 		for (j = 0; j < num_pages; j++) {
878 			page = osd_data->pages[j];
879 			if (fscrypt_is_bounce_page(page)) {
880 				page = fscrypt_pagecache_page(page);
881 				fscrypt_free_bounce_page(osd_data->pages[j]);
882 				osd_data->pages[j] = page;
883 			}
884 			BUG_ON(!page);
885 			WARN_ON(!PageUptodate(page));
886 
887 			if (atomic_long_dec_return(&fsc->writeback_count) <
888 			     CONGESTION_OFF_THRESH(
889 					fsc->mount_options->congestion_kb))
890 				fsc->write_congested = false;
891 
892 			ceph_put_snap_context(detach_page_private(page));
893 			end_page_writeback(page);
894 			dout("unlocking %p\n", page);
895 
896 			if (remove_page)
897 				generic_error_remove_page(inode->i_mapping,
898 							  page);
899 
900 			unlock_page(page);
901 		}
902 		dout("writepages_finish %p wrote %llu bytes cleaned %d pages\n",
903 		     inode, osd_data->length, rc >= 0 ? num_pages : 0);
904 
905 		release_pages(osd_data->pages, num_pages);
906 	}
907 
908 	ceph_update_write_metrics(&fsc->mdsc->metric, req->r_start_latency,
909 				  req->r_end_latency, len, rc);
910 
911 	ceph_put_wrbuffer_cap_refs(ci, total_pages, snapc);
912 
913 	osd_data = osd_req_op_extent_osd_data(req, 0);
914 	if (osd_data->pages_from_pool)
915 		mempool_free(osd_data->pages, ceph_wb_pagevec_pool);
916 	else
917 		kfree(osd_data->pages);
918 	ceph_osdc_put_request(req);
919 	ceph_dec_osd_stopping_blocker(fsc->mdsc);
920 }
921 
922 /*
923  * initiate async writeback
924  */
925 static int ceph_writepages_start(struct address_space *mapping,
926 				 struct writeback_control *wbc)
927 {
928 	struct inode *inode = mapping->host;
929 	struct ceph_inode_info *ci = ceph_inode(inode);
930 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
931 	struct ceph_vino vino = ceph_vino(inode);
932 	pgoff_t index, start_index, end = -1;
933 	struct ceph_snap_context *snapc = NULL, *last_snapc = NULL, *pgsnapc;
934 	struct folio_batch fbatch;
935 	int rc = 0;
936 	unsigned int wsize = i_blocksize(inode);
937 	struct ceph_osd_request *req = NULL;
938 	struct ceph_writeback_ctl ceph_wbc;
939 	bool should_loop, range_whole = false;
940 	bool done = false;
941 	bool caching = ceph_is_cache_enabled(inode);
942 	xa_mark_t tag;
943 
944 	if (wbc->sync_mode == WB_SYNC_NONE &&
945 	    fsc->write_congested)
946 		return 0;
947 
948 	dout("writepages_start %p (mode=%s)\n", inode,
949 	     wbc->sync_mode == WB_SYNC_NONE ? "NONE" :
950 	     (wbc->sync_mode == WB_SYNC_ALL ? "ALL" : "HOLD"));
951 
952 	if (ceph_inode_is_shutdown(inode)) {
953 		if (ci->i_wrbuffer_ref > 0) {
954 			pr_warn_ratelimited(
955 				"writepage_start %p %lld forced umount\n",
956 				inode, ceph_ino(inode));
957 		}
958 		mapping_set_error(mapping, -EIO);
959 		return -EIO; /* we're in a forced umount, don't write! */
960 	}
961 	if (fsc->mount_options->wsize < wsize)
962 		wsize = fsc->mount_options->wsize;
963 
964 	folio_batch_init(&fbatch);
965 
966 	start_index = wbc->range_cyclic ? mapping->writeback_index : 0;
967 	index = start_index;
968 
969 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) {
970 		tag = PAGECACHE_TAG_TOWRITE;
971 	} else {
972 		tag = PAGECACHE_TAG_DIRTY;
973 	}
974 retry:
975 	/* find oldest snap context with dirty data */
976 	snapc = get_oldest_context(inode, &ceph_wbc, NULL);
977 	if (!snapc) {
978 		/* hmm, why does writepages get called when there
979 		   is no dirty data? */
980 		dout(" no snap context with dirty data?\n");
981 		goto out;
982 	}
983 	dout(" oldest snapc is %p seq %lld (%d snaps)\n",
984 	     snapc, snapc->seq, snapc->num_snaps);
985 
986 	should_loop = false;
987 	if (ceph_wbc.head_snapc && snapc != last_snapc) {
988 		/* where to start/end? */
989 		if (wbc->range_cyclic) {
990 			index = start_index;
991 			end = -1;
992 			if (index > 0)
993 				should_loop = true;
994 			dout(" cyclic, start at %lu\n", index);
995 		} else {
996 			index = wbc->range_start >> PAGE_SHIFT;
997 			end = wbc->range_end >> PAGE_SHIFT;
998 			if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
999 				range_whole = true;
1000 			dout(" not cyclic, %lu to %lu\n", index, end);
1001 		}
1002 	} else if (!ceph_wbc.head_snapc) {
1003 		/* Do not respect wbc->range_{start,end}. Dirty pages
1004 		 * in that range can be associated with newer snapc.
1005 		 * They are not writeable until we write all dirty pages
1006 		 * associated with 'snapc' get written */
1007 		if (index > 0)
1008 			should_loop = true;
1009 		dout(" non-head snapc, range whole\n");
1010 	}
1011 
1012 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
1013 		tag_pages_for_writeback(mapping, index, end);
1014 
1015 	ceph_put_snap_context(last_snapc);
1016 	last_snapc = snapc;
1017 
1018 	while (!done && index <= end) {
1019 		int num_ops = 0, op_idx;
1020 		unsigned i, nr_folios, max_pages, locked_pages = 0;
1021 		struct page **pages = NULL, **data_pages;
1022 		struct page *page;
1023 		pgoff_t strip_unit_end = 0;
1024 		u64 offset = 0, len = 0;
1025 		bool from_pool = false;
1026 
1027 		max_pages = wsize >> PAGE_SHIFT;
1028 
1029 get_more_pages:
1030 		nr_folios = filemap_get_folios_tag(mapping, &index,
1031 						   end, tag, &fbatch);
1032 		dout("pagevec_lookup_range_tag got %d\n", nr_folios);
1033 		if (!nr_folios && !locked_pages)
1034 			break;
1035 		for (i = 0; i < nr_folios && locked_pages < max_pages; i++) {
1036 			page = &fbatch.folios[i]->page;
1037 			dout("? %p idx %lu\n", page, page->index);
1038 			if (locked_pages == 0)
1039 				lock_page(page);  /* first page */
1040 			else if (!trylock_page(page))
1041 				break;
1042 
1043 			/* only dirty pages, or our accounting breaks */
1044 			if (unlikely(!PageDirty(page)) ||
1045 			    unlikely(page->mapping != mapping)) {
1046 				dout("!dirty or !mapping %p\n", page);
1047 				unlock_page(page);
1048 				continue;
1049 			}
1050 			/* only if matching snap context */
1051 			pgsnapc = page_snap_context(page);
1052 			if (pgsnapc != snapc) {
1053 				dout("page snapc %p %lld != oldest %p %lld\n",
1054 				     pgsnapc, pgsnapc->seq, snapc, snapc->seq);
1055 				if (!should_loop &&
1056 				    !ceph_wbc.head_snapc &&
1057 				    wbc->sync_mode != WB_SYNC_NONE)
1058 					should_loop = true;
1059 				unlock_page(page);
1060 				continue;
1061 			}
1062 			if (page_offset(page) >= ceph_wbc.i_size) {
1063 				struct folio *folio = page_folio(page);
1064 
1065 				dout("folio at %lu beyond eof %llu\n",
1066 				     folio->index, ceph_wbc.i_size);
1067 				if ((ceph_wbc.size_stable ||
1068 				    folio_pos(folio) >= i_size_read(inode)) &&
1069 				    folio_clear_dirty_for_io(folio))
1070 					folio_invalidate(folio, 0,
1071 							folio_size(folio));
1072 				folio_unlock(folio);
1073 				continue;
1074 			}
1075 			if (strip_unit_end && (page->index > strip_unit_end)) {
1076 				dout("end of strip unit %p\n", page);
1077 				unlock_page(page);
1078 				break;
1079 			}
1080 			if (PageWriteback(page) || PageFsCache(page)) {
1081 				if (wbc->sync_mode == WB_SYNC_NONE) {
1082 					dout("%p under writeback\n", page);
1083 					unlock_page(page);
1084 					continue;
1085 				}
1086 				dout("waiting on writeback %p\n", page);
1087 				wait_on_page_writeback(page);
1088 				wait_on_page_fscache(page);
1089 			}
1090 
1091 			if (!clear_page_dirty_for_io(page)) {
1092 				dout("%p !clear_page_dirty_for_io\n", page);
1093 				unlock_page(page);
1094 				continue;
1095 			}
1096 
1097 			/*
1098 			 * We have something to write.  If this is
1099 			 * the first locked page this time through,
1100 			 * calculate max possinle write size and
1101 			 * allocate a page array
1102 			 */
1103 			if (locked_pages == 0) {
1104 				u64 objnum;
1105 				u64 objoff;
1106 				u32 xlen;
1107 
1108 				/* prepare async write request */
1109 				offset = (u64)page_offset(page);
1110 				ceph_calc_file_object_mapping(&ci->i_layout,
1111 							      offset, wsize,
1112 							      &objnum, &objoff,
1113 							      &xlen);
1114 				len = xlen;
1115 
1116 				num_ops = 1;
1117 				strip_unit_end = page->index +
1118 					((len - 1) >> PAGE_SHIFT);
1119 
1120 				BUG_ON(pages);
1121 				max_pages = calc_pages_for(0, (u64)len);
1122 				pages = kmalloc_array(max_pages,
1123 						      sizeof(*pages),
1124 						      GFP_NOFS);
1125 				if (!pages) {
1126 					from_pool = true;
1127 					pages = mempool_alloc(ceph_wb_pagevec_pool, GFP_NOFS);
1128 					BUG_ON(!pages);
1129 				}
1130 
1131 				len = 0;
1132 			} else if (page->index !=
1133 				   (offset + len) >> PAGE_SHIFT) {
1134 				if (num_ops >= (from_pool ?  CEPH_OSD_SLAB_OPS :
1135 							     CEPH_OSD_MAX_OPS)) {
1136 					redirty_page_for_writepage(wbc, page);
1137 					unlock_page(page);
1138 					break;
1139 				}
1140 
1141 				num_ops++;
1142 				offset = (u64)page_offset(page);
1143 				len = 0;
1144 			}
1145 
1146 			/* note position of first page in fbatch */
1147 			dout("%p will write page %p idx %lu\n",
1148 			     inode, page, page->index);
1149 
1150 			if (atomic_long_inc_return(&fsc->writeback_count) >
1151 			    CONGESTION_ON_THRESH(
1152 				    fsc->mount_options->congestion_kb))
1153 				fsc->write_congested = true;
1154 
1155 			if (IS_ENCRYPTED(inode)) {
1156 				pages[locked_pages] =
1157 					fscrypt_encrypt_pagecache_blocks(page,
1158 						PAGE_SIZE, 0,
1159 						locked_pages ? GFP_NOWAIT : GFP_NOFS);
1160 				if (IS_ERR(pages[locked_pages])) {
1161 					if (PTR_ERR(pages[locked_pages]) == -EINVAL)
1162 						pr_err("%s: inode->i_blkbits=%hhu\n",
1163 							__func__, inode->i_blkbits);
1164 					/* better not fail on first page! */
1165 					BUG_ON(locked_pages == 0);
1166 					pages[locked_pages] = NULL;
1167 					redirty_page_for_writepage(wbc, page);
1168 					unlock_page(page);
1169 					break;
1170 				}
1171 				++locked_pages;
1172 			} else {
1173 				pages[locked_pages++] = page;
1174 			}
1175 
1176 			fbatch.folios[i] = NULL;
1177 			len += thp_size(page);
1178 		}
1179 
1180 		/* did we get anything? */
1181 		if (!locked_pages)
1182 			goto release_folios;
1183 		if (i) {
1184 			unsigned j, n = 0;
1185 			/* shift unused page to beginning of fbatch */
1186 			for (j = 0; j < nr_folios; j++) {
1187 				if (!fbatch.folios[j])
1188 					continue;
1189 				if (n < j)
1190 					fbatch.folios[n] = fbatch.folios[j];
1191 				n++;
1192 			}
1193 			fbatch.nr = n;
1194 
1195 			if (nr_folios && i == nr_folios &&
1196 			    locked_pages < max_pages) {
1197 				dout("reached end fbatch, trying for more\n");
1198 				folio_batch_release(&fbatch);
1199 				goto get_more_pages;
1200 			}
1201 		}
1202 
1203 new_request:
1204 		offset = ceph_fscrypt_page_offset(pages[0]);
1205 		len = wsize;
1206 
1207 		req = ceph_osdc_new_request(&fsc->client->osdc,
1208 					&ci->i_layout, vino,
1209 					offset, &len, 0, num_ops,
1210 					CEPH_OSD_OP_WRITE, CEPH_OSD_FLAG_WRITE,
1211 					snapc, ceph_wbc.truncate_seq,
1212 					ceph_wbc.truncate_size, false);
1213 		if (IS_ERR(req)) {
1214 			req = ceph_osdc_new_request(&fsc->client->osdc,
1215 						&ci->i_layout, vino,
1216 						offset, &len, 0,
1217 						min(num_ops,
1218 						    CEPH_OSD_SLAB_OPS),
1219 						CEPH_OSD_OP_WRITE,
1220 						CEPH_OSD_FLAG_WRITE,
1221 						snapc, ceph_wbc.truncate_seq,
1222 						ceph_wbc.truncate_size, true);
1223 			BUG_ON(IS_ERR(req));
1224 		}
1225 		BUG_ON(len < ceph_fscrypt_page_offset(pages[locked_pages - 1]) +
1226 			     thp_size(pages[locked_pages - 1]) - offset);
1227 
1228 		if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
1229 			rc = -EIO;
1230 			goto release_folios;
1231 		}
1232 		req->r_callback = writepages_finish;
1233 		req->r_inode = inode;
1234 
1235 		/* Format the osd request message and submit the write */
1236 		len = 0;
1237 		data_pages = pages;
1238 		op_idx = 0;
1239 		for (i = 0; i < locked_pages; i++) {
1240 			struct page *page = ceph_fscrypt_pagecache_page(pages[i]);
1241 
1242 			u64 cur_offset = page_offset(page);
1243 			/*
1244 			 * Discontinuity in page range? Ceph can handle that by just passing
1245 			 * multiple extents in the write op.
1246 			 */
1247 			if (offset + len != cur_offset) {
1248 				/* If it's full, stop here */
1249 				if (op_idx + 1 == req->r_num_ops)
1250 					break;
1251 
1252 				/* Kick off an fscache write with what we have so far. */
1253 				ceph_fscache_write_to_cache(inode, offset, len, caching);
1254 
1255 				/* Start a new extent */
1256 				osd_req_op_extent_dup_last(req, op_idx,
1257 							   cur_offset - offset);
1258 				dout("writepages got pages at %llu~%llu\n",
1259 				     offset, len);
1260 				osd_req_op_extent_osd_data_pages(req, op_idx,
1261 							data_pages, len, 0,
1262 							from_pool, false);
1263 				osd_req_op_extent_update(req, op_idx, len);
1264 
1265 				len = 0;
1266 				offset = cur_offset;
1267 				data_pages = pages + i;
1268 				op_idx++;
1269 			}
1270 
1271 			set_page_writeback(page);
1272 			if (caching)
1273 				ceph_set_page_fscache(page);
1274 			len += thp_size(page);
1275 		}
1276 		ceph_fscache_write_to_cache(inode, offset, len, caching);
1277 
1278 		if (ceph_wbc.size_stable) {
1279 			len = min(len, ceph_wbc.i_size - offset);
1280 		} else if (i == locked_pages) {
1281 			/* writepages_finish() clears writeback pages
1282 			 * according to the data length, so make sure
1283 			 * data length covers all locked pages */
1284 			u64 min_len = len + 1 - thp_size(page);
1285 			len = get_writepages_data_length(inode, pages[i - 1],
1286 							 offset);
1287 			len = max(len, min_len);
1288 		}
1289 		if (IS_ENCRYPTED(inode))
1290 			len = round_up(len, CEPH_FSCRYPT_BLOCK_SIZE);
1291 
1292 		dout("writepages got pages at %llu~%llu\n", offset, len);
1293 
1294 		if (IS_ENCRYPTED(inode) &&
1295 		    ((offset | len) & ~CEPH_FSCRYPT_BLOCK_MASK))
1296 			pr_warn("%s: bad encrypted write offset=%lld len=%llu\n",
1297 				__func__, offset, len);
1298 
1299 		osd_req_op_extent_osd_data_pages(req, op_idx, data_pages, len,
1300 						 0, from_pool, false);
1301 		osd_req_op_extent_update(req, op_idx, len);
1302 
1303 		BUG_ON(op_idx + 1 != req->r_num_ops);
1304 
1305 		from_pool = false;
1306 		if (i < locked_pages) {
1307 			BUG_ON(num_ops <= req->r_num_ops);
1308 			num_ops -= req->r_num_ops;
1309 			locked_pages -= i;
1310 
1311 			/* allocate new pages array for next request */
1312 			data_pages = pages;
1313 			pages = kmalloc_array(locked_pages, sizeof(*pages),
1314 					      GFP_NOFS);
1315 			if (!pages) {
1316 				from_pool = true;
1317 				pages = mempool_alloc(ceph_wb_pagevec_pool, GFP_NOFS);
1318 				BUG_ON(!pages);
1319 			}
1320 			memcpy(pages, data_pages + i,
1321 			       locked_pages * sizeof(*pages));
1322 			memset(data_pages + i, 0,
1323 			       locked_pages * sizeof(*pages));
1324 		} else {
1325 			BUG_ON(num_ops != req->r_num_ops);
1326 			index = pages[i - 1]->index + 1;
1327 			/* request message now owns the pages array */
1328 			pages = NULL;
1329 		}
1330 
1331 		req->r_mtime = inode->i_mtime;
1332 		ceph_osdc_start_request(&fsc->client->osdc, req);
1333 		req = NULL;
1334 
1335 		wbc->nr_to_write -= i;
1336 		if (pages)
1337 			goto new_request;
1338 
1339 		/*
1340 		 * We stop writing back only if we are not doing
1341 		 * integrity sync. In case of integrity sync we have to
1342 		 * keep going until we have written all the pages
1343 		 * we tagged for writeback prior to entering this loop.
1344 		 */
1345 		if (wbc->nr_to_write <= 0 && wbc->sync_mode == WB_SYNC_NONE)
1346 			done = true;
1347 
1348 release_folios:
1349 		dout("folio_batch release on %d folios (%p)\n", (int)fbatch.nr,
1350 		     fbatch.nr ? fbatch.folios[0] : NULL);
1351 		folio_batch_release(&fbatch);
1352 	}
1353 
1354 	if (should_loop && !done) {
1355 		/* more to do; loop back to beginning of file */
1356 		dout("writepages looping back to beginning of file\n");
1357 		end = start_index - 1; /* OK even when start_index == 0 */
1358 
1359 		/* to write dirty pages associated with next snapc,
1360 		 * we need to wait until current writes complete */
1361 		if (wbc->sync_mode != WB_SYNC_NONE &&
1362 		    start_index == 0 && /* all dirty pages were checked */
1363 		    !ceph_wbc.head_snapc) {
1364 			struct page *page;
1365 			unsigned i, nr;
1366 			index = 0;
1367 			while ((index <= end) &&
1368 			       (nr = filemap_get_folios_tag(mapping, &index,
1369 						(pgoff_t)-1,
1370 						PAGECACHE_TAG_WRITEBACK,
1371 						&fbatch))) {
1372 				for (i = 0; i < nr; i++) {
1373 					page = &fbatch.folios[i]->page;
1374 					if (page_snap_context(page) != snapc)
1375 						continue;
1376 					wait_on_page_writeback(page);
1377 				}
1378 				folio_batch_release(&fbatch);
1379 				cond_resched();
1380 			}
1381 		}
1382 
1383 		start_index = 0;
1384 		index = 0;
1385 		goto retry;
1386 	}
1387 
1388 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1389 		mapping->writeback_index = index;
1390 
1391 out:
1392 	ceph_osdc_put_request(req);
1393 	ceph_put_snap_context(last_snapc);
1394 	dout("writepages dend - startone, rc = %d\n", rc);
1395 	return rc;
1396 }
1397 
1398 
1399 
1400 /*
1401  * See if a given @snapc is either writeable, or already written.
1402  */
1403 static int context_is_writeable_or_written(struct inode *inode,
1404 					   struct ceph_snap_context *snapc)
1405 {
1406 	struct ceph_snap_context *oldest = get_oldest_context(inode, NULL, NULL);
1407 	int ret = !oldest || snapc->seq <= oldest->seq;
1408 
1409 	ceph_put_snap_context(oldest);
1410 	return ret;
1411 }
1412 
1413 /**
1414  * ceph_find_incompatible - find an incompatible context and return it
1415  * @page: page being dirtied
1416  *
1417  * We are only allowed to write into/dirty a page if the page is
1418  * clean, or already dirty within the same snap context. Returns a
1419  * conflicting context if there is one, NULL if there isn't, or a
1420  * negative error code on other errors.
1421  *
1422  * Must be called with page lock held.
1423  */
1424 static struct ceph_snap_context *
1425 ceph_find_incompatible(struct page *page)
1426 {
1427 	struct inode *inode = page->mapping->host;
1428 	struct ceph_inode_info *ci = ceph_inode(inode);
1429 
1430 	if (ceph_inode_is_shutdown(inode)) {
1431 		dout(" page %p %llx:%llx is shutdown\n", page,
1432 		     ceph_vinop(inode));
1433 		return ERR_PTR(-ESTALE);
1434 	}
1435 
1436 	for (;;) {
1437 		struct ceph_snap_context *snapc, *oldest;
1438 
1439 		wait_on_page_writeback(page);
1440 
1441 		snapc = page_snap_context(page);
1442 		if (!snapc || snapc == ci->i_head_snapc)
1443 			break;
1444 
1445 		/*
1446 		 * this page is already dirty in another (older) snap
1447 		 * context!  is it writeable now?
1448 		 */
1449 		oldest = get_oldest_context(inode, NULL, NULL);
1450 		if (snapc->seq > oldest->seq) {
1451 			/* not writeable -- return it for the caller to deal with */
1452 			ceph_put_snap_context(oldest);
1453 			dout(" page %p snapc %p not current or oldest\n", page, snapc);
1454 			return ceph_get_snap_context(snapc);
1455 		}
1456 		ceph_put_snap_context(oldest);
1457 
1458 		/* yay, writeable, do it now (without dropping page lock) */
1459 		dout(" page %p snapc %p not current, but oldest\n", page, snapc);
1460 		if (clear_page_dirty_for_io(page)) {
1461 			int r = writepage_nounlock(page, NULL);
1462 			if (r < 0)
1463 				return ERR_PTR(r);
1464 		}
1465 	}
1466 	return NULL;
1467 }
1468 
1469 static int ceph_netfs_check_write_begin(struct file *file, loff_t pos, unsigned int len,
1470 					struct folio **foliop, void **_fsdata)
1471 {
1472 	struct inode *inode = file_inode(file);
1473 	struct ceph_inode_info *ci = ceph_inode(inode);
1474 	struct ceph_snap_context *snapc;
1475 
1476 	snapc = ceph_find_incompatible(folio_page(*foliop, 0));
1477 	if (snapc) {
1478 		int r;
1479 
1480 		folio_unlock(*foliop);
1481 		folio_put(*foliop);
1482 		*foliop = NULL;
1483 		if (IS_ERR(snapc))
1484 			return PTR_ERR(snapc);
1485 
1486 		ceph_queue_writeback(inode);
1487 		r = wait_event_killable(ci->i_cap_wq,
1488 					context_is_writeable_or_written(inode, snapc));
1489 		ceph_put_snap_context(snapc);
1490 		return r == 0 ? -EAGAIN : r;
1491 	}
1492 	return 0;
1493 }
1494 
1495 /*
1496  * We are only allowed to write into/dirty the page if the page is
1497  * clean, or already dirty within the same snap context.
1498  */
1499 static int ceph_write_begin(struct file *file, struct address_space *mapping,
1500 			    loff_t pos, unsigned len,
1501 			    struct page **pagep, void **fsdata)
1502 {
1503 	struct inode *inode = file_inode(file);
1504 	struct ceph_inode_info *ci = ceph_inode(inode);
1505 	struct folio *folio = NULL;
1506 	int r;
1507 
1508 	r = netfs_write_begin(&ci->netfs, file, inode->i_mapping, pos, len, &folio, NULL);
1509 	if (r < 0)
1510 		return r;
1511 
1512 	folio_wait_fscache(folio);
1513 	WARN_ON_ONCE(!folio_test_locked(folio));
1514 	*pagep = &folio->page;
1515 	return 0;
1516 }
1517 
1518 /*
1519  * we don't do anything in here that simple_write_end doesn't do
1520  * except adjust dirty page accounting
1521  */
1522 static int ceph_write_end(struct file *file, struct address_space *mapping,
1523 			  loff_t pos, unsigned len, unsigned copied,
1524 			  struct page *subpage, void *fsdata)
1525 {
1526 	struct folio *folio = page_folio(subpage);
1527 	struct inode *inode = file_inode(file);
1528 	bool check_cap = false;
1529 
1530 	dout("write_end file %p inode %p folio %p %d~%d (%d)\n", file,
1531 	     inode, folio, (int)pos, (int)copied, (int)len);
1532 
1533 	if (!folio_test_uptodate(folio)) {
1534 		/* just return that nothing was copied on a short copy */
1535 		if (copied < len) {
1536 			copied = 0;
1537 			goto out;
1538 		}
1539 		folio_mark_uptodate(folio);
1540 	}
1541 
1542 	/* did file size increase? */
1543 	if (pos+copied > i_size_read(inode))
1544 		check_cap = ceph_inode_set_size(inode, pos+copied);
1545 
1546 	folio_mark_dirty(folio);
1547 
1548 out:
1549 	folio_unlock(folio);
1550 	folio_put(folio);
1551 
1552 	if (check_cap)
1553 		ceph_check_caps(ceph_inode(inode), CHECK_CAPS_AUTHONLY);
1554 
1555 	return copied;
1556 }
1557 
1558 const struct address_space_operations ceph_aops = {
1559 	.read_folio = netfs_read_folio,
1560 	.readahead = netfs_readahead,
1561 	.writepage = ceph_writepage,
1562 	.writepages = ceph_writepages_start,
1563 	.write_begin = ceph_write_begin,
1564 	.write_end = ceph_write_end,
1565 	.dirty_folio = ceph_dirty_folio,
1566 	.invalidate_folio = ceph_invalidate_folio,
1567 	.release_folio = ceph_release_folio,
1568 	.direct_IO = noop_direct_IO,
1569 };
1570 
1571 static void ceph_block_sigs(sigset_t *oldset)
1572 {
1573 	sigset_t mask;
1574 	siginitsetinv(&mask, sigmask(SIGKILL));
1575 	sigprocmask(SIG_BLOCK, &mask, oldset);
1576 }
1577 
1578 static void ceph_restore_sigs(sigset_t *oldset)
1579 {
1580 	sigprocmask(SIG_SETMASK, oldset, NULL);
1581 }
1582 
1583 /*
1584  * vm ops
1585  */
1586 static vm_fault_t ceph_filemap_fault(struct vm_fault *vmf)
1587 {
1588 	struct vm_area_struct *vma = vmf->vma;
1589 	struct inode *inode = file_inode(vma->vm_file);
1590 	struct ceph_inode_info *ci = ceph_inode(inode);
1591 	struct ceph_file_info *fi = vma->vm_file->private_data;
1592 	loff_t off = (loff_t)vmf->pgoff << PAGE_SHIFT;
1593 	int want, got, err;
1594 	sigset_t oldset;
1595 	vm_fault_t ret = VM_FAULT_SIGBUS;
1596 
1597 	if (ceph_inode_is_shutdown(inode))
1598 		return ret;
1599 
1600 	ceph_block_sigs(&oldset);
1601 
1602 	dout("filemap_fault %p %llx.%llx %llu trying to get caps\n",
1603 	     inode, ceph_vinop(inode), off);
1604 	if (fi->fmode & CEPH_FILE_MODE_LAZY)
1605 		want = CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO;
1606 	else
1607 		want = CEPH_CAP_FILE_CACHE;
1608 
1609 	got = 0;
1610 	err = ceph_get_caps(vma->vm_file, CEPH_CAP_FILE_RD, want, -1, &got);
1611 	if (err < 0)
1612 		goto out_restore;
1613 
1614 	dout("filemap_fault %p %llu got cap refs on %s\n",
1615 	     inode, off, ceph_cap_string(got));
1616 
1617 	if ((got & (CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO)) ||
1618 	    !ceph_has_inline_data(ci)) {
1619 		CEPH_DEFINE_RW_CONTEXT(rw_ctx, got);
1620 		ceph_add_rw_context(fi, &rw_ctx);
1621 		ret = filemap_fault(vmf);
1622 		ceph_del_rw_context(fi, &rw_ctx);
1623 		dout("filemap_fault %p %llu drop cap refs %s ret %x\n",
1624 		     inode, off, ceph_cap_string(got), ret);
1625 	} else
1626 		err = -EAGAIN;
1627 
1628 	ceph_put_cap_refs(ci, got);
1629 
1630 	if (err != -EAGAIN)
1631 		goto out_restore;
1632 
1633 	/* read inline data */
1634 	if (off >= PAGE_SIZE) {
1635 		/* does not support inline data > PAGE_SIZE */
1636 		ret = VM_FAULT_SIGBUS;
1637 	} else {
1638 		struct address_space *mapping = inode->i_mapping;
1639 		struct page *page;
1640 
1641 		filemap_invalidate_lock_shared(mapping);
1642 		page = find_or_create_page(mapping, 0,
1643 				mapping_gfp_constraint(mapping, ~__GFP_FS));
1644 		if (!page) {
1645 			ret = VM_FAULT_OOM;
1646 			goto out_inline;
1647 		}
1648 		err = __ceph_do_getattr(inode, page,
1649 					 CEPH_STAT_CAP_INLINE_DATA, true);
1650 		if (err < 0 || off >= i_size_read(inode)) {
1651 			unlock_page(page);
1652 			put_page(page);
1653 			ret = vmf_error(err);
1654 			goto out_inline;
1655 		}
1656 		if (err < PAGE_SIZE)
1657 			zero_user_segment(page, err, PAGE_SIZE);
1658 		else
1659 			flush_dcache_page(page);
1660 		SetPageUptodate(page);
1661 		vmf->page = page;
1662 		ret = VM_FAULT_MAJOR | VM_FAULT_LOCKED;
1663 out_inline:
1664 		filemap_invalidate_unlock_shared(mapping);
1665 		dout("filemap_fault %p %llu read inline data ret %x\n",
1666 		     inode, off, ret);
1667 	}
1668 out_restore:
1669 	ceph_restore_sigs(&oldset);
1670 	if (err < 0)
1671 		ret = vmf_error(err);
1672 
1673 	return ret;
1674 }
1675 
1676 static vm_fault_t ceph_page_mkwrite(struct vm_fault *vmf)
1677 {
1678 	struct vm_area_struct *vma = vmf->vma;
1679 	struct inode *inode = file_inode(vma->vm_file);
1680 	struct ceph_inode_info *ci = ceph_inode(inode);
1681 	struct ceph_file_info *fi = vma->vm_file->private_data;
1682 	struct ceph_cap_flush *prealloc_cf;
1683 	struct page *page = vmf->page;
1684 	loff_t off = page_offset(page);
1685 	loff_t size = i_size_read(inode);
1686 	size_t len;
1687 	int want, got, err;
1688 	sigset_t oldset;
1689 	vm_fault_t ret = VM_FAULT_SIGBUS;
1690 
1691 	if (ceph_inode_is_shutdown(inode))
1692 		return ret;
1693 
1694 	prealloc_cf = ceph_alloc_cap_flush();
1695 	if (!prealloc_cf)
1696 		return VM_FAULT_OOM;
1697 
1698 	sb_start_pagefault(inode->i_sb);
1699 	ceph_block_sigs(&oldset);
1700 
1701 	if (off + thp_size(page) <= size)
1702 		len = thp_size(page);
1703 	else
1704 		len = offset_in_thp(page, size);
1705 
1706 	dout("page_mkwrite %p %llx.%llx %llu~%zd getting caps i_size %llu\n",
1707 	     inode, ceph_vinop(inode), off, len, size);
1708 	if (fi->fmode & CEPH_FILE_MODE_LAZY)
1709 		want = CEPH_CAP_FILE_BUFFER | CEPH_CAP_FILE_LAZYIO;
1710 	else
1711 		want = CEPH_CAP_FILE_BUFFER;
1712 
1713 	got = 0;
1714 	err = ceph_get_caps(vma->vm_file, CEPH_CAP_FILE_WR, want, off + len, &got);
1715 	if (err < 0)
1716 		goto out_free;
1717 
1718 	dout("page_mkwrite %p %llu~%zd got cap refs on %s\n",
1719 	     inode, off, len, ceph_cap_string(got));
1720 
1721 	/* Update time before taking page lock */
1722 	file_update_time(vma->vm_file);
1723 	inode_inc_iversion_raw(inode);
1724 
1725 	do {
1726 		struct ceph_snap_context *snapc;
1727 
1728 		lock_page(page);
1729 
1730 		if (page_mkwrite_check_truncate(page, inode) < 0) {
1731 			unlock_page(page);
1732 			ret = VM_FAULT_NOPAGE;
1733 			break;
1734 		}
1735 
1736 		snapc = ceph_find_incompatible(page);
1737 		if (!snapc) {
1738 			/* success.  we'll keep the page locked. */
1739 			set_page_dirty(page);
1740 			ret = VM_FAULT_LOCKED;
1741 			break;
1742 		}
1743 
1744 		unlock_page(page);
1745 
1746 		if (IS_ERR(snapc)) {
1747 			ret = VM_FAULT_SIGBUS;
1748 			break;
1749 		}
1750 
1751 		ceph_queue_writeback(inode);
1752 		err = wait_event_killable(ci->i_cap_wq,
1753 				context_is_writeable_or_written(inode, snapc));
1754 		ceph_put_snap_context(snapc);
1755 	} while (err == 0);
1756 
1757 	if (ret == VM_FAULT_LOCKED) {
1758 		int dirty;
1759 		spin_lock(&ci->i_ceph_lock);
1760 		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
1761 					       &prealloc_cf);
1762 		spin_unlock(&ci->i_ceph_lock);
1763 		if (dirty)
1764 			__mark_inode_dirty(inode, dirty);
1765 	}
1766 
1767 	dout("page_mkwrite %p %llu~%zd dropping cap refs on %s ret %x\n",
1768 	     inode, off, len, ceph_cap_string(got), ret);
1769 	ceph_put_cap_refs_async(ci, got);
1770 out_free:
1771 	ceph_restore_sigs(&oldset);
1772 	sb_end_pagefault(inode->i_sb);
1773 	ceph_free_cap_flush(prealloc_cf);
1774 	if (err < 0)
1775 		ret = vmf_error(err);
1776 	return ret;
1777 }
1778 
1779 void ceph_fill_inline_data(struct inode *inode, struct page *locked_page,
1780 			   char	*data, size_t len)
1781 {
1782 	struct address_space *mapping = inode->i_mapping;
1783 	struct page *page;
1784 
1785 	if (locked_page) {
1786 		page = locked_page;
1787 	} else {
1788 		if (i_size_read(inode) == 0)
1789 			return;
1790 		page = find_or_create_page(mapping, 0,
1791 					   mapping_gfp_constraint(mapping,
1792 					   ~__GFP_FS));
1793 		if (!page)
1794 			return;
1795 		if (PageUptodate(page)) {
1796 			unlock_page(page);
1797 			put_page(page);
1798 			return;
1799 		}
1800 	}
1801 
1802 	dout("fill_inline_data %p %llx.%llx len %zu locked_page %p\n",
1803 	     inode, ceph_vinop(inode), len, locked_page);
1804 
1805 	if (len > 0) {
1806 		void *kaddr = kmap_atomic(page);
1807 		memcpy(kaddr, data, len);
1808 		kunmap_atomic(kaddr);
1809 	}
1810 
1811 	if (page != locked_page) {
1812 		if (len < PAGE_SIZE)
1813 			zero_user_segment(page, len, PAGE_SIZE);
1814 		else
1815 			flush_dcache_page(page);
1816 
1817 		SetPageUptodate(page);
1818 		unlock_page(page);
1819 		put_page(page);
1820 	}
1821 }
1822 
1823 int ceph_uninline_data(struct file *file)
1824 {
1825 	struct inode *inode = file_inode(file);
1826 	struct ceph_inode_info *ci = ceph_inode(inode);
1827 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
1828 	struct ceph_osd_request *req = NULL;
1829 	struct ceph_cap_flush *prealloc_cf = NULL;
1830 	struct folio *folio = NULL;
1831 	u64 inline_version = CEPH_INLINE_NONE;
1832 	struct page *pages[1];
1833 	int err = 0;
1834 	u64 len;
1835 
1836 	spin_lock(&ci->i_ceph_lock);
1837 	inline_version = ci->i_inline_version;
1838 	spin_unlock(&ci->i_ceph_lock);
1839 
1840 	dout("uninline_data %p %llx.%llx inline_version %llu\n",
1841 	     inode, ceph_vinop(inode), inline_version);
1842 
1843 	if (ceph_inode_is_shutdown(inode)) {
1844 		err = -EIO;
1845 		goto out;
1846 	}
1847 
1848 	if (inline_version == CEPH_INLINE_NONE)
1849 		return 0;
1850 
1851 	prealloc_cf = ceph_alloc_cap_flush();
1852 	if (!prealloc_cf)
1853 		return -ENOMEM;
1854 
1855 	if (inline_version == 1) /* initial version, no data */
1856 		goto out_uninline;
1857 
1858 	folio = read_mapping_folio(inode->i_mapping, 0, file);
1859 	if (IS_ERR(folio)) {
1860 		err = PTR_ERR(folio);
1861 		goto out;
1862 	}
1863 
1864 	folio_lock(folio);
1865 
1866 	len = i_size_read(inode);
1867 	if (len > folio_size(folio))
1868 		len = folio_size(folio);
1869 
1870 	req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
1871 				    ceph_vino(inode), 0, &len, 0, 1,
1872 				    CEPH_OSD_OP_CREATE, CEPH_OSD_FLAG_WRITE,
1873 				    NULL, 0, 0, false);
1874 	if (IS_ERR(req)) {
1875 		err = PTR_ERR(req);
1876 		goto out_unlock;
1877 	}
1878 
1879 	req->r_mtime = inode->i_mtime;
1880 	ceph_osdc_start_request(&fsc->client->osdc, req);
1881 	err = ceph_osdc_wait_request(&fsc->client->osdc, req);
1882 	ceph_osdc_put_request(req);
1883 	if (err < 0)
1884 		goto out_unlock;
1885 
1886 	req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
1887 				    ceph_vino(inode), 0, &len, 1, 3,
1888 				    CEPH_OSD_OP_WRITE, CEPH_OSD_FLAG_WRITE,
1889 				    NULL, ci->i_truncate_seq,
1890 				    ci->i_truncate_size, false);
1891 	if (IS_ERR(req)) {
1892 		err = PTR_ERR(req);
1893 		goto out_unlock;
1894 	}
1895 
1896 	pages[0] = folio_page(folio, 0);
1897 	osd_req_op_extent_osd_data_pages(req, 1, pages, len, 0, false, false);
1898 
1899 	{
1900 		__le64 xattr_buf = cpu_to_le64(inline_version);
1901 		err = osd_req_op_xattr_init(req, 0, CEPH_OSD_OP_CMPXATTR,
1902 					    "inline_version", &xattr_buf,
1903 					    sizeof(xattr_buf),
1904 					    CEPH_OSD_CMPXATTR_OP_GT,
1905 					    CEPH_OSD_CMPXATTR_MODE_U64);
1906 		if (err)
1907 			goto out_put_req;
1908 	}
1909 
1910 	{
1911 		char xattr_buf[32];
1912 		int xattr_len = snprintf(xattr_buf, sizeof(xattr_buf),
1913 					 "%llu", inline_version);
1914 		err = osd_req_op_xattr_init(req, 2, CEPH_OSD_OP_SETXATTR,
1915 					    "inline_version",
1916 					    xattr_buf, xattr_len, 0, 0);
1917 		if (err)
1918 			goto out_put_req;
1919 	}
1920 
1921 	req->r_mtime = inode->i_mtime;
1922 	ceph_osdc_start_request(&fsc->client->osdc, req);
1923 	err = ceph_osdc_wait_request(&fsc->client->osdc, req);
1924 
1925 	ceph_update_write_metrics(&fsc->mdsc->metric, req->r_start_latency,
1926 				  req->r_end_latency, len, err);
1927 
1928 out_uninline:
1929 	if (!err) {
1930 		int dirty;
1931 
1932 		/* Set to CAP_INLINE_NONE and dirty the caps */
1933 		down_read(&fsc->mdsc->snap_rwsem);
1934 		spin_lock(&ci->i_ceph_lock);
1935 		ci->i_inline_version = CEPH_INLINE_NONE;
1936 		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR, &prealloc_cf);
1937 		spin_unlock(&ci->i_ceph_lock);
1938 		up_read(&fsc->mdsc->snap_rwsem);
1939 		if (dirty)
1940 			__mark_inode_dirty(inode, dirty);
1941 	}
1942 out_put_req:
1943 	ceph_osdc_put_request(req);
1944 	if (err == -ECANCELED)
1945 		err = 0;
1946 out_unlock:
1947 	if (folio) {
1948 		folio_unlock(folio);
1949 		folio_put(folio);
1950 	}
1951 out:
1952 	ceph_free_cap_flush(prealloc_cf);
1953 	dout("uninline_data %p %llx.%llx inline_version %llu = %d\n",
1954 	     inode, ceph_vinop(inode), inline_version, err);
1955 	return err;
1956 }
1957 
1958 static const struct vm_operations_struct ceph_vmops = {
1959 	.fault		= ceph_filemap_fault,
1960 	.page_mkwrite	= ceph_page_mkwrite,
1961 };
1962 
1963 int ceph_mmap(struct file *file, struct vm_area_struct *vma)
1964 {
1965 	struct address_space *mapping = file->f_mapping;
1966 
1967 	if (!mapping->a_ops->read_folio)
1968 		return -ENOEXEC;
1969 	vma->vm_ops = &ceph_vmops;
1970 	return 0;
1971 }
1972 
1973 enum {
1974 	POOL_READ	= 1,
1975 	POOL_WRITE	= 2,
1976 };
1977 
1978 static int __ceph_pool_perm_get(struct ceph_inode_info *ci,
1979 				s64 pool, struct ceph_string *pool_ns)
1980 {
1981 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(&ci->netfs.inode);
1982 	struct ceph_mds_client *mdsc = fsc->mdsc;
1983 	struct ceph_osd_request *rd_req = NULL, *wr_req = NULL;
1984 	struct rb_node **p, *parent;
1985 	struct ceph_pool_perm *perm;
1986 	struct page **pages;
1987 	size_t pool_ns_len;
1988 	int err = 0, err2 = 0, have = 0;
1989 
1990 	down_read(&mdsc->pool_perm_rwsem);
1991 	p = &mdsc->pool_perm_tree.rb_node;
1992 	while (*p) {
1993 		perm = rb_entry(*p, struct ceph_pool_perm, node);
1994 		if (pool < perm->pool)
1995 			p = &(*p)->rb_left;
1996 		else if (pool > perm->pool)
1997 			p = &(*p)->rb_right;
1998 		else {
1999 			int ret = ceph_compare_string(pool_ns,
2000 						perm->pool_ns,
2001 						perm->pool_ns_len);
2002 			if (ret < 0)
2003 				p = &(*p)->rb_left;
2004 			else if (ret > 0)
2005 				p = &(*p)->rb_right;
2006 			else {
2007 				have = perm->perm;
2008 				break;
2009 			}
2010 		}
2011 	}
2012 	up_read(&mdsc->pool_perm_rwsem);
2013 	if (*p)
2014 		goto out;
2015 
2016 	if (pool_ns)
2017 		dout("__ceph_pool_perm_get pool %lld ns %.*s no perm cached\n",
2018 		     pool, (int)pool_ns->len, pool_ns->str);
2019 	else
2020 		dout("__ceph_pool_perm_get pool %lld no perm cached\n", pool);
2021 
2022 	down_write(&mdsc->pool_perm_rwsem);
2023 	p = &mdsc->pool_perm_tree.rb_node;
2024 	parent = NULL;
2025 	while (*p) {
2026 		parent = *p;
2027 		perm = rb_entry(parent, struct ceph_pool_perm, node);
2028 		if (pool < perm->pool)
2029 			p = &(*p)->rb_left;
2030 		else if (pool > perm->pool)
2031 			p = &(*p)->rb_right;
2032 		else {
2033 			int ret = ceph_compare_string(pool_ns,
2034 						perm->pool_ns,
2035 						perm->pool_ns_len);
2036 			if (ret < 0)
2037 				p = &(*p)->rb_left;
2038 			else if (ret > 0)
2039 				p = &(*p)->rb_right;
2040 			else {
2041 				have = perm->perm;
2042 				break;
2043 			}
2044 		}
2045 	}
2046 	if (*p) {
2047 		up_write(&mdsc->pool_perm_rwsem);
2048 		goto out;
2049 	}
2050 
2051 	rd_req = ceph_osdc_alloc_request(&fsc->client->osdc, NULL,
2052 					 1, false, GFP_NOFS);
2053 	if (!rd_req) {
2054 		err = -ENOMEM;
2055 		goto out_unlock;
2056 	}
2057 
2058 	rd_req->r_flags = CEPH_OSD_FLAG_READ;
2059 	osd_req_op_init(rd_req, 0, CEPH_OSD_OP_STAT, 0);
2060 	rd_req->r_base_oloc.pool = pool;
2061 	if (pool_ns)
2062 		rd_req->r_base_oloc.pool_ns = ceph_get_string(pool_ns);
2063 	ceph_oid_printf(&rd_req->r_base_oid, "%llx.00000000", ci->i_vino.ino);
2064 
2065 	err = ceph_osdc_alloc_messages(rd_req, GFP_NOFS);
2066 	if (err)
2067 		goto out_unlock;
2068 
2069 	wr_req = ceph_osdc_alloc_request(&fsc->client->osdc, NULL,
2070 					 1, false, GFP_NOFS);
2071 	if (!wr_req) {
2072 		err = -ENOMEM;
2073 		goto out_unlock;
2074 	}
2075 
2076 	wr_req->r_flags = CEPH_OSD_FLAG_WRITE;
2077 	osd_req_op_init(wr_req, 0, CEPH_OSD_OP_CREATE, CEPH_OSD_OP_FLAG_EXCL);
2078 	ceph_oloc_copy(&wr_req->r_base_oloc, &rd_req->r_base_oloc);
2079 	ceph_oid_copy(&wr_req->r_base_oid, &rd_req->r_base_oid);
2080 
2081 	err = ceph_osdc_alloc_messages(wr_req, GFP_NOFS);
2082 	if (err)
2083 		goto out_unlock;
2084 
2085 	/* one page should be large enough for STAT data */
2086 	pages = ceph_alloc_page_vector(1, GFP_KERNEL);
2087 	if (IS_ERR(pages)) {
2088 		err = PTR_ERR(pages);
2089 		goto out_unlock;
2090 	}
2091 
2092 	osd_req_op_raw_data_in_pages(rd_req, 0, pages, PAGE_SIZE,
2093 				     0, false, true);
2094 	ceph_osdc_start_request(&fsc->client->osdc, rd_req);
2095 
2096 	wr_req->r_mtime = ci->netfs.inode.i_mtime;
2097 	ceph_osdc_start_request(&fsc->client->osdc, wr_req);
2098 
2099 	err = ceph_osdc_wait_request(&fsc->client->osdc, rd_req);
2100 	err2 = ceph_osdc_wait_request(&fsc->client->osdc, wr_req);
2101 
2102 	if (err >= 0 || err == -ENOENT)
2103 		have |= POOL_READ;
2104 	else if (err != -EPERM) {
2105 		if (err == -EBLOCKLISTED)
2106 			fsc->blocklisted = true;
2107 		goto out_unlock;
2108 	}
2109 
2110 	if (err2 == 0 || err2 == -EEXIST)
2111 		have |= POOL_WRITE;
2112 	else if (err2 != -EPERM) {
2113 		if (err2 == -EBLOCKLISTED)
2114 			fsc->blocklisted = true;
2115 		err = err2;
2116 		goto out_unlock;
2117 	}
2118 
2119 	pool_ns_len = pool_ns ? pool_ns->len : 0;
2120 	perm = kmalloc(sizeof(*perm) + pool_ns_len + 1, GFP_NOFS);
2121 	if (!perm) {
2122 		err = -ENOMEM;
2123 		goto out_unlock;
2124 	}
2125 
2126 	perm->pool = pool;
2127 	perm->perm = have;
2128 	perm->pool_ns_len = pool_ns_len;
2129 	if (pool_ns_len > 0)
2130 		memcpy(perm->pool_ns, pool_ns->str, pool_ns_len);
2131 	perm->pool_ns[pool_ns_len] = 0;
2132 
2133 	rb_link_node(&perm->node, parent, p);
2134 	rb_insert_color(&perm->node, &mdsc->pool_perm_tree);
2135 	err = 0;
2136 out_unlock:
2137 	up_write(&mdsc->pool_perm_rwsem);
2138 
2139 	ceph_osdc_put_request(rd_req);
2140 	ceph_osdc_put_request(wr_req);
2141 out:
2142 	if (!err)
2143 		err = have;
2144 	if (pool_ns)
2145 		dout("__ceph_pool_perm_get pool %lld ns %.*s result = %d\n",
2146 		     pool, (int)pool_ns->len, pool_ns->str, err);
2147 	else
2148 		dout("__ceph_pool_perm_get pool %lld result = %d\n", pool, err);
2149 	return err;
2150 }
2151 
2152 int ceph_pool_perm_check(struct inode *inode, int need)
2153 {
2154 	struct ceph_inode_info *ci = ceph_inode(inode);
2155 	struct ceph_string *pool_ns;
2156 	s64 pool;
2157 	int ret, flags;
2158 
2159 	/* Only need to do this for regular files */
2160 	if (!S_ISREG(inode->i_mode))
2161 		return 0;
2162 
2163 	if (ci->i_vino.snap != CEPH_NOSNAP) {
2164 		/*
2165 		 * Pool permission check needs to write to the first object.
2166 		 * But for snapshot, head of the first object may have alread
2167 		 * been deleted. Skip check to avoid creating orphan object.
2168 		 */
2169 		return 0;
2170 	}
2171 
2172 	if (ceph_test_mount_opt(ceph_inode_to_fs_client(inode),
2173 				NOPOOLPERM))
2174 		return 0;
2175 
2176 	spin_lock(&ci->i_ceph_lock);
2177 	flags = ci->i_ceph_flags;
2178 	pool = ci->i_layout.pool_id;
2179 	spin_unlock(&ci->i_ceph_lock);
2180 check:
2181 	if (flags & CEPH_I_POOL_PERM) {
2182 		if ((need & CEPH_CAP_FILE_RD) && !(flags & CEPH_I_POOL_RD)) {
2183 			dout("ceph_pool_perm_check pool %lld no read perm\n",
2184 			     pool);
2185 			return -EPERM;
2186 		}
2187 		if ((need & CEPH_CAP_FILE_WR) && !(flags & CEPH_I_POOL_WR)) {
2188 			dout("ceph_pool_perm_check pool %lld no write perm\n",
2189 			     pool);
2190 			return -EPERM;
2191 		}
2192 		return 0;
2193 	}
2194 
2195 	pool_ns = ceph_try_get_string(ci->i_layout.pool_ns);
2196 	ret = __ceph_pool_perm_get(ci, pool, pool_ns);
2197 	ceph_put_string(pool_ns);
2198 	if (ret < 0)
2199 		return ret;
2200 
2201 	flags = CEPH_I_POOL_PERM;
2202 	if (ret & POOL_READ)
2203 		flags |= CEPH_I_POOL_RD;
2204 	if (ret & POOL_WRITE)
2205 		flags |= CEPH_I_POOL_WR;
2206 
2207 	spin_lock(&ci->i_ceph_lock);
2208 	if (pool == ci->i_layout.pool_id &&
2209 	    pool_ns == rcu_dereference_raw(ci->i_layout.pool_ns)) {
2210 		ci->i_ceph_flags |= flags;
2211         } else {
2212 		pool = ci->i_layout.pool_id;
2213 		flags = ci->i_ceph_flags;
2214 	}
2215 	spin_unlock(&ci->i_ceph_lock);
2216 	goto check;
2217 }
2218 
2219 void ceph_pool_perm_destroy(struct ceph_mds_client *mdsc)
2220 {
2221 	struct ceph_pool_perm *perm;
2222 	struct rb_node *n;
2223 
2224 	while (!RB_EMPTY_ROOT(&mdsc->pool_perm_tree)) {
2225 		n = rb_first(&mdsc->pool_perm_tree);
2226 		perm = rb_entry(n, struct ceph_pool_perm, node);
2227 		rb_erase(n, &mdsc->pool_perm_tree);
2228 		kfree(perm);
2229 	}
2230 }
2231