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