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