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