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