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