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