xref: /linux/fs/ceph/inode.c (revision 8fe8e62f432f0a7a0292a328a73c6912b9a2b73b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 
4 #include <linux/module.h>
5 #include <linux/fs.h>
6 #include <linux/slab.h>
7 #include <linux/string.h>
8 #include <linux/uaccess.h>
9 #include <linux/kernel.h>
10 #include <linux/writeback.h>
11 #include <linux/vmalloc.h>
12 #include <linux/xattr.h>
13 #include <linux/posix_acl.h>
14 #include <linux/random.h>
15 #include <linux/sort.h>
16 #include <linux/iversion.h>
17 #include <linux/fscrypt.h>
18 
19 #include "super.h"
20 #include "mds_client.h"
21 #include "cache.h"
22 #include "crypto.h"
23 #include <linux/ceph/decode.h>
24 
25 /*
26  * Ceph inode operations
27  *
28  * Implement basic inode helpers (get, alloc) and inode ops (getattr,
29  * setattr, etc.), xattr helpers, and helpers for assimilating
30  * metadata returned by the MDS into our cache.
31  *
32  * Also define helpers for doing asynchronous writeback, invalidation,
33  * and truncation for the benefit of those who can't afford to block
34  * (typically because they are in the message handler path).
35  */
36 
37 static const struct inode_operations ceph_symlink_iops;
38 static const struct inode_operations ceph_encrypted_symlink_iops;
39 
40 static void ceph_inode_work(struct work_struct *work);
41 
42 /*
43  * find or create an inode, given the ceph ino number
44  */
45 static int ceph_set_ino_cb(struct inode *inode, void *data)
46 {
47 #if BITS_PER_LONG >= 64
48 	const struct ceph_vino *vino = data;
49 #endif
50 	struct ceph_inode_info *ci = ceph_inode(inode);
51 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
52 
53 #if BITS_PER_LONG >= 64
54 	inode->i_ino = vino->ino;
55 	ci->i_snap = vino->snap;
56 #else
57 	ci->i_vino = *(struct ceph_vino *)data;
58 	inode->i_ino = ceph_vino_to_ino_t(ci->i_vino);
59 #endif
60 
61 	inode_set_iversion_raw(inode, 0);
62 	percpu_counter_inc(&mdsc->metric.total_inodes);
63 
64 	return 0;
65 }
66 
67 /*
68  * Check if the parent inode matches the vino from directory reply info
69  */
70 static inline bool ceph_vino_matches_parent(struct inode *parent,
71 					    struct ceph_vino vino)
72 {
73 	return ceph_ino(parent) == vino.ino && ceph_snap(parent) == vino.snap;
74 }
75 
76 /*
77  * Validate that the directory inode referenced by @req->r_parent matches the
78  * inode number and snapshot id contained in the reply's directory record.  If
79  * they do not match – which can theoretically happen if the parent dentry was
80  * moved between the time the request was issued and the reply arrived – fall
81  * back to looking up the correct inode in the inode cache.
82  *
83  * A reference is *always* returned.  Callers that receive a different inode
84  * than the original @parent are responsible for dropping the extra reference
85  * once the reply has been processed.
86  */
87 static struct inode *ceph_get_reply_dir(struct super_block *sb,
88 					struct inode *parent,
89 					struct ceph_mds_reply_info_parsed *rinfo)
90 {
91 	struct ceph_vino vino;
92 
93 	if (unlikely(!rinfo->diri.in))
94 		return parent; /* nothing to compare against */
95 
96 	/* If we didn't have a cached parent inode to begin with, just bail out. */
97 	if (!parent)
98 		return NULL;
99 
100 	vino.ino  = le64_to_cpu(rinfo->diri.in->ino);
101 	vino.snap = le64_to_cpu(rinfo->diri.in->snapid);
102 
103 	if (likely(ceph_vino_matches_parent(parent, vino)))
104 		return parent; /* matches – use the original reference */
105 
106 	/* Mismatch – this should be rare.  Emit a WARN and obtain the correct inode. */
107 	WARN_ONCE(1, "ceph: reply dir mismatch (parent valid %llx.%llx reply %llx.%llx)\n",
108 		  ceph_ino(parent), ceph_snap(parent), vino.ino, vino.snap);
109 
110 	return ceph_get_inode(sb, vino, NULL);
111 }
112 
113 /**
114  * ceph_new_inode - allocate a new inode in advance of an expected create
115  * @dir: parent directory for new inode
116  * @dentry: dentry that may eventually point to new inode
117  * @mode: mode of new inode
118  * @as_ctx: pointer to inherited security context
119  *
120  * Allocate a new inode in advance of an operation to create a new inode.
121  * This allocates the inode and sets up the acl_sec_ctx with appropriate
122  * info for the new inode.
123  *
124  * Returns a pointer to the new inode or an ERR_PTR.
125  */
126 struct inode *ceph_new_inode(struct inode *dir, struct dentry *dentry,
127 			     umode_t *mode, struct ceph_acl_sec_ctx *as_ctx)
128 {
129 	int err;
130 	struct inode *inode;
131 
132 	inode = new_inode(dir->i_sb);
133 	if (!inode)
134 		return ERR_PTR(-ENOMEM);
135 
136 	inode->i_blkbits = CEPH_FSCRYPT_BLOCK_SHIFT;
137 
138 	if (!S_ISLNK(*mode)) {
139 		err = ceph_pre_init_acls(dir, mode, as_ctx);
140 		if (err < 0)
141 			goto out_err;
142 	}
143 
144 	inode_state_assign_raw(inode, 0);
145 	inode->i_mode = *mode;
146 
147 	err = ceph_security_init_secctx(dentry, *mode, as_ctx);
148 	if (err < 0)
149 		goto out_err;
150 
151 	/*
152 	 * We'll skip setting fscrypt context for snapshots, leaving that for
153 	 * the handle_reply().
154 	 */
155 	if (ceph_snap(dir) != CEPH_SNAPDIR) {
156 		err = ceph_fscrypt_prepare_context(dir, inode, as_ctx);
157 		if (err)
158 			goto out_err;
159 	}
160 
161 	return inode;
162 out_err:
163 	iput(inode);
164 	return ERR_PTR(err);
165 }
166 
167 void ceph_as_ctx_to_req(struct ceph_mds_request *req,
168 			struct ceph_acl_sec_ctx *as_ctx)
169 {
170 	if (as_ctx->pagelist) {
171 		req->r_pagelist = as_ctx->pagelist;
172 		as_ctx->pagelist = NULL;
173 	}
174 	ceph_fscrypt_as_ctx_to_req(req, as_ctx);
175 }
176 
177 /**
178  * ceph_get_inode - find or create/hash a new inode
179  * @sb: superblock to search and allocate in
180  * @vino: vino to search for
181  * @newino: optional new inode to insert if one isn't found (may be NULL)
182  *
183  * Search for or insert a new inode into the hash for the given vino, and
184  * return a reference to it. If new is non-NULL, its reference is consumed.
185  */
186 struct inode *ceph_get_inode(struct super_block *sb, struct ceph_vino vino,
187 			     struct inode *newino)
188 {
189 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(sb);
190 	struct ceph_client *cl = mdsc->fsc->client;
191 	struct inode *inode;
192 
193 	if (ceph_vino_is_reserved(vino))
194 		return ERR_PTR(-EREMOTEIO);
195 
196 	if (newino) {
197 		inode = inode_insert5(newino, (unsigned long)vino.ino,
198 				      ceph_ino_compare, ceph_set_ino_cb, &vino);
199 		if (inode != newino)
200 			iput(newino);
201 	} else {
202 		inode = iget5_locked(sb, (unsigned long)vino.ino,
203 				     ceph_ino_compare, ceph_set_ino_cb, &vino);
204 	}
205 
206 	if (!inode) {
207 		doutc(cl, "no inode found for %llx.%llx\n", vino.ino, vino.snap);
208 		return ERR_PTR(-ENOMEM);
209 	}
210 
211 	doutc(cl, "on %llx=%llx.%llx got %p new %d\n",
212 	      ceph_present_inode(inode), ceph_vinop(inode), inode,
213 	      !!(inode_state_read_once(inode) & I_NEW));
214 	return inode;
215 }
216 
217 /*
218  * get/construct snapdir inode for a given directory
219  */
220 struct inode *ceph_get_snapdir(struct inode *parent)
221 {
222 	struct ceph_client *cl = ceph_inode_to_client(parent);
223 	struct ceph_vino vino = {
224 		.ino = ceph_ino(parent),
225 		.snap = CEPH_SNAPDIR,
226 	};
227 	struct inode *inode = ceph_get_inode(parent->i_sb, vino, NULL);
228 	struct ceph_inode_info *ci = ceph_inode(inode);
229 	int ret = -ENOTDIR;
230 
231 	if (IS_ERR(inode))
232 		return inode;
233 
234 	if (!S_ISDIR(parent->i_mode)) {
235 		pr_warn_once_client(cl, "bad snapdir parent type (mode=0%o)\n",
236 				    parent->i_mode);
237 		goto err;
238 	}
239 
240 	if (!(inode_state_read_once(inode) & I_NEW) && !S_ISDIR(inode->i_mode)) {
241 		pr_warn_once_client(cl, "bad snapdir inode type (mode=0%o)\n",
242 				    inode->i_mode);
243 		goto err;
244 	}
245 
246 	inode->i_mode = parent->i_mode;
247 	inode->i_uid = parent->i_uid;
248 	inode->i_gid = parent->i_gid;
249 	inode_set_mtime_to_ts(inode, inode_get_mtime(parent));
250 	inode_set_ctime_to_ts(inode, inode_get_ctime(parent));
251 	inode_set_atime_to_ts(inode, inode_get_atime(parent));
252 	ci->i_rbytes = 0;
253 	ci->i_btime = ceph_inode(parent)->i_btime;
254 
255 #ifdef CONFIG_FS_ENCRYPTION
256 	/* if encrypted, just borrow fscrypt_auth from parent */
257 	if (IS_ENCRYPTED(parent)) {
258 		struct ceph_inode_info *pci = ceph_inode(parent);
259 
260 		ci->fscrypt_auth = kmemdup(pci->fscrypt_auth,
261 					   pci->fscrypt_auth_len,
262 					   GFP_KERNEL);
263 		if (ci->fscrypt_auth) {
264 			inode->i_flags |= S_ENCRYPTED;
265 			ci->fscrypt_auth_len = pci->fscrypt_auth_len;
266 		} else {
267 			doutc(cl, "Failed to alloc snapdir fscrypt_auth\n");
268 			ret = -ENOMEM;
269 			goto err;
270 		}
271 	}
272 #endif
273 	if (inode_state_read_once(inode) & I_NEW) {
274 		inode->i_op = &ceph_snapdir_iops;
275 		inode->i_fop = &ceph_snapdir_fops;
276 		ci->i_snap_caps = CEPH_CAP_PIN; /* so we can open */
277 		unlock_new_inode(inode);
278 	}
279 
280 	return inode;
281 err:
282 	if ((inode_state_read_once(inode) & I_NEW))
283 		discard_new_inode(inode);
284 	else
285 		iput(inode);
286 	return ERR_PTR(ret);
287 }
288 
289 const struct inode_operations ceph_file_iops = {
290 	.permission = ceph_permission,
291 	.setattr = ceph_setattr,
292 	.getattr = ceph_getattr,
293 	.listxattr = ceph_listxattr,
294 	.get_inode_acl = ceph_get_acl,
295 	.set_acl = ceph_set_acl,
296 };
297 
298 
299 /*
300  * We use a 'frag tree' to keep track of the MDS's directory fragments
301  * for a given inode (usually there is just a single fragment).  We
302  * need to know when a child frag is delegated to a new MDS, or when
303  * it is flagged as replicated, so we can direct our requests
304  * accordingly.
305  */
306 
307 /*
308  * find/create a frag in the tree
309  */
310 static struct ceph_inode_frag *__get_or_create_frag(struct ceph_inode_info *ci,
311 						    u32 f)
312 {
313 	struct inode *inode = &ci->netfs.inode;
314 	struct ceph_client *cl = ceph_inode_to_client(inode);
315 	struct rb_node **p;
316 	struct rb_node *parent = NULL;
317 	struct ceph_inode_frag *frag;
318 	int c;
319 
320 	p = &ci->i_fragtree.rb_node;
321 	while (*p) {
322 		parent = *p;
323 		frag = rb_entry(parent, struct ceph_inode_frag, node);
324 		c = ceph_frag_compare(f, frag->frag);
325 		if (c < 0)
326 			p = &(*p)->rb_left;
327 		else if (c > 0)
328 			p = &(*p)->rb_right;
329 		else
330 			return frag;
331 	}
332 
333 	frag = kmalloc_obj(*frag, GFP_NOFS);
334 	if (!frag)
335 		return ERR_PTR(-ENOMEM);
336 
337 	frag->frag = f;
338 	frag->split_by = 0;
339 	frag->mds = -1;
340 	frag->ndist = 0;
341 
342 	rb_link_node(&frag->node, parent, p);
343 	rb_insert_color(&frag->node, &ci->i_fragtree);
344 
345 	doutc(cl, "added %p %llx.%llx frag %x\n", inode, ceph_vinop(inode), f);
346 	return frag;
347 }
348 
349 /*
350  * find a specific frag @f
351  */
352 struct ceph_inode_frag *__ceph_find_frag(struct ceph_inode_info *ci, u32 f)
353 {
354 	struct rb_node *n = ci->i_fragtree.rb_node;
355 
356 	while (n) {
357 		struct ceph_inode_frag *frag =
358 			rb_entry(n, struct ceph_inode_frag, node);
359 		int c = ceph_frag_compare(f, frag->frag);
360 		if (c < 0)
361 			n = n->rb_left;
362 		else if (c > 0)
363 			n = n->rb_right;
364 		else
365 			return frag;
366 	}
367 	return NULL;
368 }
369 
370 /*
371  * Choose frag containing the given value @v.  If @pfrag is
372  * specified, copy the frag delegation info to the caller if
373  * it is present.
374  */
375 static u32 __ceph_choose_frag(struct ceph_inode_info *ci, u32 v,
376 			      struct ceph_inode_frag *pfrag, int *found)
377 {
378 	struct ceph_client *cl = ceph_inode_to_client(&ci->netfs.inode);
379 	u32 t = ceph_frag_make(0, 0);
380 	struct ceph_inode_frag *frag;
381 	unsigned nway, i;
382 	u32 n;
383 
384 	if (found)
385 		*found = 0;
386 
387 	while (1) {
388 		WARN_ON(!ceph_frag_contains_value(t, v));
389 		frag = __ceph_find_frag(ci, t);
390 		if (!frag)
391 			break; /* t is a leaf */
392 		if (frag->split_by == 0) {
393 			if (pfrag)
394 				memcpy(pfrag, frag, sizeof(*pfrag));
395 			if (found)
396 				*found = 1;
397 			break;
398 		}
399 
400 		/* choose child */
401 		nway = 1 << frag->split_by;
402 		doutc(cl, "frag(%x) %x splits by %d (%d ways)\n", v, t,
403 		      frag->split_by, nway);
404 		for (i = 0; i < nway; i++) {
405 			n = ceph_frag_make_child(t, frag->split_by, i);
406 			if (ceph_frag_contains_value(n, v)) {
407 				t = n;
408 				break;
409 			}
410 		}
411 		BUG_ON(i == nway);
412 	}
413 	doutc(cl, "frag(%x) = %x\n", v, t);
414 
415 	return t;
416 }
417 
418 u32 ceph_choose_frag(struct ceph_inode_info *ci, u32 v,
419 		     struct ceph_inode_frag *pfrag, int *found)
420 {
421 	u32 ret;
422 	mutex_lock(&ci->i_fragtree_mutex);
423 	ret = __ceph_choose_frag(ci, v, pfrag, found);
424 	mutex_unlock(&ci->i_fragtree_mutex);
425 	return ret;
426 }
427 
428 /*
429  * Process dirfrag (delegation) info from the mds.  Include leaf
430  * fragment in tree ONLY if ndist > 0.  Otherwise, only
431  * branches/splits are included in i_fragtree)
432  */
433 static int ceph_fill_dirfrag(struct inode *inode,
434 			     struct ceph_mds_reply_dirfrag *dirinfo)
435 {
436 	struct ceph_inode_info *ci = ceph_inode(inode);
437 	struct ceph_client *cl = ceph_inode_to_client(inode);
438 	struct ceph_inode_frag *frag;
439 	u32 id = le32_to_cpu(dirinfo->frag);
440 	int mds = le32_to_cpu(dirinfo->auth);
441 	int ndist = le32_to_cpu(dirinfo->ndist);
442 	int diri_auth = -1;
443 	int i;
444 	int err = 0;
445 
446 	spin_lock(&ci->i_ceph_lock);
447 	if (ci->i_auth_cap)
448 		diri_auth = ci->i_auth_cap->mds;
449 	spin_unlock(&ci->i_ceph_lock);
450 
451 	if (mds == -1) /* CDIR_AUTH_PARENT */
452 		mds = diri_auth;
453 
454 	mutex_lock(&ci->i_fragtree_mutex);
455 	if (ndist == 0 && mds == diri_auth) {
456 		/* no delegation info needed. */
457 		frag = __ceph_find_frag(ci, id);
458 		if (!frag)
459 			goto out;
460 		if (frag->split_by == 0) {
461 			/* tree leaf, remove */
462 			doutc(cl, "removed %p %llx.%llx frag %x (no ref)\n",
463 			      inode, ceph_vinop(inode), id);
464 			rb_erase(&frag->node, &ci->i_fragtree);
465 			kfree(frag);
466 		} else {
467 			/* tree branch, keep and clear */
468 			doutc(cl, "cleared %p %llx.%llx frag %x referral\n",
469 			      inode, ceph_vinop(inode), id);
470 			frag->mds = -1;
471 			frag->ndist = 0;
472 		}
473 		goto out;
474 	}
475 
476 
477 	/* find/add this frag to store mds delegation info */
478 	frag = __get_or_create_frag(ci, id);
479 	if (IS_ERR(frag)) {
480 		/* this is not the end of the world; we can continue
481 		   with bad/inaccurate delegation info */
482 		pr_err_client(cl, "ENOMEM on mds ref %p %llx.%llx fg %x\n",
483 			      inode, ceph_vinop(inode),
484 			      le32_to_cpu(dirinfo->frag));
485 		err = -ENOMEM;
486 		goto out;
487 	}
488 
489 	frag->mds = mds;
490 	frag->ndist = min_t(u32, ndist, CEPH_MAX_DIRFRAG_REP);
491 	for (i = 0; i < frag->ndist; i++)
492 		frag->dist[i] = le32_to_cpu(dirinfo->dist[i]);
493 	doutc(cl, "%p %llx.%llx frag %x ndist=%d\n", inode,
494 	      ceph_vinop(inode), frag->frag, frag->ndist);
495 
496 out:
497 	mutex_unlock(&ci->i_fragtree_mutex);
498 	return err;
499 }
500 
501 static int frag_tree_split_cmp(const void *l, const void *r)
502 {
503 	struct ceph_frag_tree_split *ls = (struct ceph_frag_tree_split*)l;
504 	struct ceph_frag_tree_split *rs = (struct ceph_frag_tree_split*)r;
505 	return ceph_frag_compare(le32_to_cpu(ls->frag),
506 				 le32_to_cpu(rs->frag));
507 }
508 
509 static bool is_frag_child(u32 f, struct ceph_inode_frag *frag)
510 {
511 	if (!frag)
512 		return f == ceph_frag_make(0, 0);
513 	if (ceph_frag_bits(f) != ceph_frag_bits(frag->frag) + frag->split_by)
514 		return false;
515 	return ceph_frag_contains_value(frag->frag, ceph_frag_value(f));
516 }
517 
518 static int ceph_fill_fragtree(struct inode *inode,
519 			      struct ceph_frag_tree_head *fragtree,
520 			      struct ceph_mds_reply_dirfrag *dirinfo)
521 {
522 	struct ceph_client *cl = ceph_inode_to_client(inode);
523 	struct ceph_inode_info *ci = ceph_inode(inode);
524 	struct ceph_inode_frag *frag, *prev_frag = NULL;
525 	struct rb_node *rb_node;
526 	unsigned i, split_by, nsplits;
527 	u32 id;
528 	bool update = false;
529 
530 	mutex_lock(&ci->i_fragtree_mutex);
531 	nsplits = le32_to_cpu(fragtree->nsplits);
532 	if (nsplits != ci->i_fragtree_nsplits) {
533 		update = true;
534 	} else if (nsplits) {
535 		i = get_random_u32_below(nsplits);
536 		id = le32_to_cpu(fragtree->splits[i].frag);
537 		if (!__ceph_find_frag(ci, id))
538 			update = true;
539 	} else if (!RB_EMPTY_ROOT(&ci->i_fragtree)) {
540 		rb_node = rb_first(&ci->i_fragtree);
541 		frag = rb_entry(rb_node, struct ceph_inode_frag, node);
542 		if (frag->frag != ceph_frag_make(0, 0) || rb_next(rb_node))
543 			update = true;
544 	}
545 	if (!update && dirinfo) {
546 		id = le32_to_cpu(dirinfo->frag);
547 		if (id != __ceph_choose_frag(ci, id, NULL, NULL))
548 			update = true;
549 	}
550 	if (!update)
551 		goto out_unlock;
552 
553 	if (nsplits > 1) {
554 		sort(fragtree->splits, nsplits, sizeof(fragtree->splits[0]),
555 		     frag_tree_split_cmp, NULL);
556 	}
557 
558 	doutc(cl, "%p %llx.%llx\n", inode, ceph_vinop(inode));
559 	rb_node = rb_first(&ci->i_fragtree);
560 	for (i = 0; i < nsplits; i++) {
561 		id = le32_to_cpu(fragtree->splits[i].frag);
562 		split_by = le32_to_cpu(fragtree->splits[i].by);
563 		if (split_by == 0 || ceph_frag_bits(id) + split_by > 24) {
564 			pr_err_client(cl, "%p %llx.%llx invalid split %d/%u, "
565 			       "frag %x split by %d\n", inode,
566 			       ceph_vinop(inode), i, nsplits, id, split_by);
567 			continue;
568 		}
569 		frag = NULL;
570 		while (rb_node) {
571 			frag = rb_entry(rb_node, struct ceph_inode_frag, node);
572 			if (ceph_frag_compare(frag->frag, id) >= 0) {
573 				if (frag->frag != id)
574 					frag = NULL;
575 				else
576 					rb_node = rb_next(rb_node);
577 				break;
578 			}
579 			rb_node = rb_next(rb_node);
580 			/* delete stale split/leaf node */
581 			if (frag->split_by > 0 ||
582 			    !is_frag_child(frag->frag, prev_frag)) {
583 				rb_erase(&frag->node, &ci->i_fragtree);
584 				if (frag->split_by > 0)
585 					ci->i_fragtree_nsplits--;
586 				kfree(frag);
587 			}
588 			frag = NULL;
589 		}
590 		if (!frag) {
591 			frag = __get_or_create_frag(ci, id);
592 			if (IS_ERR(frag))
593 				continue;
594 		}
595 		if (frag->split_by == 0)
596 			ci->i_fragtree_nsplits++;
597 		frag->split_by = split_by;
598 		doutc(cl, " frag %x split by %d\n", frag->frag, frag->split_by);
599 		prev_frag = frag;
600 	}
601 	while (rb_node) {
602 		frag = rb_entry(rb_node, struct ceph_inode_frag, node);
603 		rb_node = rb_next(rb_node);
604 		/* delete stale split/leaf node */
605 		if (frag->split_by > 0 ||
606 		    !is_frag_child(frag->frag, prev_frag)) {
607 			rb_erase(&frag->node, &ci->i_fragtree);
608 			if (frag->split_by > 0)
609 				ci->i_fragtree_nsplits--;
610 			kfree(frag);
611 		}
612 	}
613 out_unlock:
614 	mutex_unlock(&ci->i_fragtree_mutex);
615 	return 0;
616 }
617 
618 /*
619  * initialize a newly allocated inode.
620  */
621 struct inode *ceph_alloc_inode(struct super_block *sb)
622 {
623 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(sb);
624 	struct ceph_inode_info *ci;
625 	int i;
626 
627 	ci = alloc_inode_sb(sb, ceph_inode_cachep, GFP_NOFS);
628 	if (!ci)
629 		return NULL;
630 
631 	doutc(fsc->client, "%p\n", &ci->netfs.inode);
632 
633 	/* Set parameters for the netfs library */
634 	netfs_inode_init(&ci->netfs, &ceph_netfs_ops, false);
635 
636 	spin_lock_init(&ci->i_ceph_lock);
637 
638 	ci->i_version = 0;
639 	ceph_set_inline_version(ci, 0);
640 	ci->i_time_warp_seq = 0;
641 	ci->i_ceph_flags = 0;
642 	atomic64_set(&ci->i_ordered_count, 1);
643 	atomic64_set(&ci->i_release_count, 1);
644 	atomic64_set(&ci->i_complete_seq[0], 0);
645 	atomic64_set(&ci->i_complete_seq[1], 0);
646 	ci->i_symlink = NULL;
647 
648 	ci->i_max_bytes = 0;
649 	ci->i_max_files = 0;
650 	ci->i_subvolume_id = CEPH_SUBVOLUME_ID_NONE;
651 
652 	memset(&ci->i_dir_layout, 0, sizeof(ci->i_dir_layout));
653 	memset(&ci->i_cached_layout, 0, sizeof(ci->i_cached_layout));
654 	RCU_INIT_POINTER(ci->i_layout.pool_ns, NULL);
655 
656 	ci->i_fragtree = RB_ROOT;
657 	mutex_init(&ci->i_fragtree_mutex);
658 
659 	ci->i_xattrs.blob = NULL;
660 	ci->i_xattrs.prealloc_blob = NULL;
661 	ci->i_xattrs.dirty = false;
662 	ci->i_xattrs.index = RB_ROOT;
663 	ci->i_xattrs.count = 0;
664 	ci->i_xattrs.names_size = 0;
665 	ci->i_xattrs.vals_size = 0;
666 	ci->i_xattrs.version = 0;
667 	ci->i_xattrs.index_version = 0;
668 
669 	ci->i_caps = RB_ROOT;
670 	ci->i_auth_cap = NULL;
671 	ci->i_dirty_caps = 0;
672 	ci->i_flushing_caps = 0;
673 	INIT_LIST_HEAD(&ci->i_dirty_item);
674 	INIT_LIST_HEAD(&ci->i_flushing_item);
675 	ci->i_prealloc_cap_flush = NULL;
676 	INIT_LIST_HEAD(&ci->i_cap_flush_list);
677 	init_waitqueue_head(&ci->i_cap_wq);
678 	ci->i_hold_caps_max = 0;
679 	INIT_LIST_HEAD(&ci->i_cap_delay_list);
680 	INIT_LIST_HEAD(&ci->i_cap_snaps);
681 	ci->i_head_snapc = NULL;
682 	ci->i_snap_caps = 0;
683 	ci->i_last_cap_flush_ack = 0;
684 
685 	ci->i_last_rd = ci->i_last_wr = jiffies - 3600 * HZ;
686 	for (i = 0; i < CEPH_FILE_MODE_BITS; i++)
687 		ci->i_nr_by_mode[i] = 0;
688 
689 	mutex_init(&ci->i_truncate_mutex);
690 	ci->i_truncate_seq = 0;
691 	ci->i_truncate_size = 0;
692 	ci->i_truncate_pending = false;
693 	ci->i_truncate_shrank = false;
694 	ci->i_truncate_pagecache_size = 0;
695 
696 	ci->i_max_size = 0;
697 	ci->i_reported_size = 0;
698 	ci->i_wanted_max_size = 0;
699 	ci->i_requested_max_size = 0;
700 
701 	ci->i_pin_ref = 0;
702 	ci->i_rd_ref = 0;
703 	ci->i_rdcache_ref = 0;
704 	ci->i_wr_ref = 0;
705 	ci->i_wb_ref = 0;
706 	ci->i_fx_ref = 0;
707 	ci->i_wrbuffer_ref = 0;
708 	ci->i_wrbuffer_ref_head = 0;
709 	atomic_set(&ci->i_filelock_ref, 0);
710 	atomic_set(&ci->i_shared_gen, 1);
711 	ci->i_rdcache_gen = 0;
712 	ci->i_rdcache_revoking = 0;
713 
714 	INIT_LIST_HEAD(&ci->i_unsafe_dirops);
715 	INIT_LIST_HEAD(&ci->i_unsafe_iops);
716 	spin_lock_init(&ci->i_unsafe_lock);
717 
718 	ci->i_snap_realm = NULL;
719 	INIT_LIST_HEAD(&ci->i_snap_realm_item);
720 	INIT_LIST_HEAD(&ci->i_snap_flush_item);
721 
722 	INIT_WORK(&ci->i_work, ceph_inode_work);
723 	ci->i_work_mask = 0;
724 	memset(&ci->i_btime, '\0', sizeof(ci->i_btime));
725 #ifdef CONFIG_FS_ENCRYPTION
726 	ci->i_crypt_info = NULL;
727 	ci->fscrypt_auth = NULL;
728 	ci->fscrypt_auth_len = 0;
729 #endif
730 	return &ci->netfs.inode;
731 }
732 
733 void ceph_free_inode(struct inode *inode)
734 {
735 	struct ceph_inode_info *ci = ceph_inode(inode);
736 
737 	kfree(ci->i_symlink);
738 #ifdef CONFIG_FS_ENCRYPTION
739 	kfree(ci->fscrypt_auth);
740 #endif
741 	fscrypt_free_inode(inode);
742 	kmem_cache_free(ceph_inode_cachep, ci);
743 }
744 
745 void ceph_evict_inode(struct inode *inode)
746 {
747 	struct ceph_inode_info *ci = ceph_inode(inode);
748 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
749 	struct ceph_client *cl = ceph_inode_to_client(inode);
750 	struct ceph_inode_frag *frag;
751 	struct rb_node *n;
752 
753 	doutc(cl, "%p ino %llx.%llx\n", inode, ceph_vinop(inode));
754 
755 	percpu_counter_dec(&mdsc->metric.total_inodes);
756 
757 	ci->i_subvolume_id = CEPH_SUBVOLUME_ID_NONE;
758 
759 	netfs_wait_for_outstanding_io(inode);
760 	truncate_inode_pages_final(&inode->i_data);
761 	if (inode_state_read_once(inode) & I_PINNING_NETFS_WB)
762 		ceph_fscache_unuse_cookie(inode, true);
763 	clear_inode(inode);
764 
765 	ceph_fscache_unregister_inode_cookie(ci);
766 	fscrypt_put_encryption_info(inode);
767 
768 	__ceph_remove_caps(ci);
769 
770 	if (__ceph_has_quota(ci, QUOTA_GET_ANY))
771 		ceph_adjust_quota_realms_count(inode, false);
772 
773 	/*
774 	 * we may still have a snap_realm reference if there are stray
775 	 * caps in i_snap_caps.
776 	 */
777 	if (ci->i_snap_realm) {
778 		if (!ceph_in_snap(inode)) {
779 			doutc(cl, " dropping residual ref to snap realm %p\n",
780 			      ci->i_snap_realm);
781 			ceph_change_snap_realm(inode, NULL);
782 		} else {
783 			ceph_put_snapid_map(mdsc, ci->i_snapid_map);
784 			ci->i_snap_realm = NULL;
785 		}
786 	}
787 
788 	while ((n = rb_first(&ci->i_fragtree)) != NULL) {
789 		frag = rb_entry(n, struct ceph_inode_frag, node);
790 		rb_erase(n, &ci->i_fragtree);
791 		kfree(frag);
792 	}
793 	ci->i_fragtree_nsplits = 0;
794 
795 	__ceph_destroy_xattrs(ci);
796 	if (ci->i_xattrs.blob)
797 		ceph_buffer_put(ci->i_xattrs.blob);
798 	if (ci->i_xattrs.prealloc_blob)
799 		ceph_buffer_put(ci->i_xattrs.prealloc_blob);
800 
801 	ceph_put_string(rcu_dereference_raw(ci->i_layout.pool_ns));
802 	ceph_put_string(rcu_dereference_raw(ci->i_cached_layout.pool_ns));
803 }
804 
805 /*
806  * Decide whether to keep an inode once its last reference is gone.
807  *
808  * Dropping it here runs ceph_evict_inode(), which throws away the page
809  * cache along with the caps that still vouch for it.  Keep a regular
810  * file's inode while it has cached pages and still holds real caps, so
811  * that a close and reopen can serve reads from the page cache instead
812  * of re-reading everything from the OSDs.
813  *
814  * Such an inode is not pinned: it holds no reference of its own, and
815  * page reclaim frees its pages like any other file's.  It is not on the
816  * inode LRU either, since mapping_shrinkable() is false while real
817  * folios are present; emptying the mapping is what puts it there for
818  * the inode shrinker.  Unmount evicts it regardless, since
819  * evict_inodes() walks sb->s_inodes rather than the LRU.
820  *
821  * The retention is bypassed whenever fscrypt requires the inode to be
822  * evicted, e.g. after its encryption key has been removed: the page
823  * cache holds plaintext, so it has to go with the key.
824  * FS_IOC_REMOVE_ENCRYPTION_KEY relies on that, as it evicts the
825  * dentries and then expects the inodes to follow.  fscrypt is
826  * therefore asked before any of the retention below, and its answer is
827  * never overridden by it.
828  *
829  * Handing caps back to the MDS used to fall out of this eviction, so
830  * trim_caps_cb() sets CEPH_I_EVICT_ON_FINAL_IPUT_BIT to override the
831  * retention for one put when the MDS asks for its caps back.
832  *
833  * ->drop_inode() is called with inode->i_lock held, so i_ceph_lock
834  * cannot be taken here and i_caps is tested racily.  That is good
835  * enough: either answer only keeps or drops an inode that could have
836  * gone the other way.
837  */
838 int ceph_drop_inode(struct inode *inode)
839 {
840 	struct ceph_inode_info *ci = ceph_inode(inode);
841 
842 	/* the MDS asked for this one back */
843 	if (test_and_clear_bit(CEPH_I_EVICT_ON_FINAL_IPUT_BIT,
844 			       &ci->i_ceph_flags))
845 		return 1;
846 
847 	if (inode_generic_drop(inode))
848 		return 1;
849 
850 	if (fscrypt_drop_inode(inode))
851 		return 1;
852 
853 	if (ceph_inode_is_shutdown(inode))
854 		return 1;
855 
856 	/* nothing here worth keeping the inode for */
857 	if (!S_ISREG(inode->i_mode) || !inode->i_data.nrpages)
858 		return 1;
859 
860 	/* keep the pages only while the inode still holds real caps */
861 	return !__ceph_is_any_real_caps(ci);
862 }
863 
864 static inline blkcnt_t calc_inode_blocks(u64 size)
865 {
866 	return (size + (1<<9) - 1) >> 9;
867 }
868 
869 /*
870  * Helpers to fill in size, ctime, mtime, and atime.  We have to be
871  * careful because either the client or MDS may have more up to date
872  * info, depending on which capabilities are held, and whether
873  * time_warp_seq or truncate_seq have increased.  (Ordinarily, mtime
874  * and size are monotonically increasing, except when utimes() or
875  * truncate() increments the corresponding _seq values.)
876  */
877 int ceph_fill_file_size(struct inode *inode, int issued,
878 			u32 truncate_seq, u64 truncate_size, u64 size)
879 {
880 	struct ceph_client *cl = ceph_inode_to_client(inode);
881 	struct ceph_inode_info *ci = ceph_inode(inode);
882 	int queue_trunc = 0;
883 	loff_t isize = i_size_read(inode);
884 
885 	if (ceph_seq_cmp(truncate_seq, ci->i_truncate_seq) > 0 ||
886 	    (truncate_seq == ci->i_truncate_seq && size > isize)) {
887 		doutc(cl, "size %lld -> %llu\n", isize, size);
888 		if (size > 0 && S_ISDIR(inode->i_mode)) {
889 			pr_err_client(cl, "non-zero size for directory\n");
890 			size = 0;
891 		}
892 		i_size_write(inode, size);
893 		inode->i_blocks = calc_inode_blocks(size);
894 		/*
895 		 * If we're expanding, then we should be able to just update
896 		 * the existing cookie.
897 		 */
898 		if (size > isize)
899 			ceph_fscache_update(inode);
900 		ci->i_reported_size = size;
901 		if (truncate_seq != ci->i_truncate_seq) {
902 			doutc(cl, "truncate_seq %u -> %u\n",
903 			      ci->i_truncate_seq, truncate_seq);
904 			ci->i_truncate_seq = truncate_seq;
905 
906 			/* the MDS should have revoked these caps */
907 			WARN_ON_ONCE(issued & (CEPH_CAP_FILE_RD |
908 					       CEPH_CAP_FILE_LAZYIO));
909 			/*
910 			 * If we hold relevant caps, or in the case where we're
911 			 * not the only client referencing this file and we
912 			 * don't hold those caps, then we need to check whether
913 			 * the file is either opened or mmaped
914 			 */
915 			if ((issued & (CEPH_CAP_FILE_CACHE|
916 				       CEPH_CAP_FILE_BUFFER)) ||
917 			    mapping_mapped(inode->i_mapping) ||
918 			    __ceph_is_file_opened(ci)) {
919 				ci->i_truncate_pending = true;
920 				if (size < isize)
921 					ci->i_truncate_shrank = true;
922 				queue_trunc = 1;
923 			}
924 		}
925 	}
926 
927 	/*
928 	 * It's possible that the new sizes of the two consecutive
929 	 * size truncations will be in the same fscrypt last block,
930 	 * and we need to truncate the corresponding page caches
931 	 * anyway.
932 	 */
933 	if (ceph_seq_cmp(truncate_seq, ci->i_truncate_seq) >= 0) {
934 		doutc(cl, "truncate_size %lld -> %llu, encrypted %d\n",
935 		      ci->i_truncate_size, truncate_size,
936 		      !!IS_ENCRYPTED(inode));
937 
938 		ci->i_truncate_size = truncate_size;
939 
940 		if (IS_ENCRYPTED(inode)) {
941 			doutc(cl, "truncate_pagecache_size %lld -> %llu\n",
942 			      ci->i_truncate_pagecache_size, size);
943 			ci->i_truncate_pagecache_size = size;
944 		} else {
945 			ci->i_truncate_pagecache_size = truncate_size;
946 		}
947 	}
948 	return queue_trunc;
949 }
950 
951 /*
952  * Set the subvolume ID for an inode.
953  *
954  * The subvolume_id identifies which CephFS subvolume this inode belongs to.
955  * CEPH_SUBVOLUME_ID_NONE (0) means unknown/unset - the MDS only sends
956  * non-zero IDs for inodes within subvolumes.
957  *
958  * An inode's subvolume membership is immutable - once an inode is created
959  * in a subvolume, it stays there. Therefore, if we already have a valid
960  * (non-zero) subvolume_id and receive a different one, that indicates a bug.
961  */
962 void ceph_inode_set_subvolume(struct inode *inode, u64 subvolume_id)
963 {
964 	struct ceph_inode_info *ci;
965 	u64 old;
966 
967 	if (!inode || subvolume_id == CEPH_SUBVOLUME_ID_NONE)
968 		return;
969 
970 	ci = ceph_inode(inode);
971 	old = READ_ONCE(ci->i_subvolume_id);
972 
973 	if (old == subvolume_id)
974 		return;
975 
976 	if (old != CEPH_SUBVOLUME_ID_NONE) {
977 		/* subvolume_id should not change once set */
978 		WARN_ON_ONCE(1);
979 		return;
980 	}
981 
982 	WRITE_ONCE(ci->i_subvolume_id, subvolume_id);
983 }
984 
985 void ceph_fill_file_time(struct inode *inode, int issued,
986 			 u32 time_warp_seq, struct timespec64 *ctime,
987 			 struct timespec64 *mtime, struct timespec64 *atime)
988 {
989 	struct ceph_client *cl = ceph_inode_to_client(inode);
990 	struct ceph_inode_info *ci = ceph_inode(inode);
991 	struct timespec64 iatime = inode_get_atime(inode);
992 	struct timespec64 ictime = inode_get_ctime(inode);
993 	struct timespec64 imtime = inode_get_mtime(inode);
994 	int warn = 0;
995 
996 	if (issued & (CEPH_CAP_FILE_EXCL|
997 		      CEPH_CAP_FILE_WR|
998 		      CEPH_CAP_FILE_BUFFER|
999 		      CEPH_CAP_AUTH_EXCL|
1000 		      CEPH_CAP_XATTR_EXCL)) {
1001 		if (ci->i_version == 0 ||
1002 		    timespec64_compare(ctime, &ictime) > 0) {
1003 			doutc(cl, "ctime %ptSp -> %ptSp inc w/ cap\n", &ictime, ctime);
1004 			inode_set_ctime_to_ts(inode, *ctime);
1005 		}
1006 		if (ci->i_version == 0 ||
1007 		    ceph_seq_cmp(time_warp_seq, ci->i_time_warp_seq) > 0) {
1008 			/* the MDS did a utimes() */
1009 			doutc(cl, "mtime %ptSp -> %ptSp tw %d -> %d\n", &imtime, mtime,
1010 			      ci->i_time_warp_seq, time_warp_seq);
1011 
1012 			inode_set_mtime_to_ts(inode, *mtime);
1013 			inode_set_atime_to_ts(inode, *atime);
1014 			ci->i_time_warp_seq = time_warp_seq;
1015 		} else if (time_warp_seq == ci->i_time_warp_seq) {
1016 			/* nobody did utimes(); take the max */
1017 			if (timespec64_compare(mtime, &imtime) > 0) {
1018 				doutc(cl, "mtime %ptSp -> %ptSp inc\n", &imtime, mtime);
1019 				inode_set_mtime_to_ts(inode, *mtime);
1020 			}
1021 			if (timespec64_compare(atime, &iatime) > 0) {
1022 				doutc(cl, "atime %ptSp -> %ptSp inc\n", &iatime, atime);
1023 				inode_set_atime_to_ts(inode, *atime);
1024 			}
1025 		} else if (issued & CEPH_CAP_FILE_EXCL) {
1026 			/* we did a utimes(); ignore mds values */
1027 		} else {
1028 			warn = 1;
1029 		}
1030 	} else {
1031 		/* we have no write|excl caps; whatever the MDS says is true */
1032 		if (ceph_seq_cmp(time_warp_seq, ci->i_time_warp_seq) >= 0) {
1033 			inode_set_ctime_to_ts(inode, *ctime);
1034 			inode_set_mtime_to_ts(inode, *mtime);
1035 			inode_set_atime_to_ts(inode, *atime);
1036 			ci->i_time_warp_seq = time_warp_seq;
1037 		} else {
1038 			warn = 1;
1039 		}
1040 	}
1041 	if (warn) /* time_warp_seq shouldn't go backwards */
1042 		doutc(cl, "%p mds time_warp_seq %u < %u\n", inode,
1043 		      time_warp_seq, ci->i_time_warp_seq);
1044 }
1045 
1046 #if IS_ENABLED(CONFIG_FS_ENCRYPTION)
1047 static int decode_encrypted_symlink(struct ceph_mds_client *mdsc,
1048 				    const char *encsym,
1049 				    int enclen, u8 **decsym)
1050 {
1051 	struct ceph_client *cl = mdsc->fsc->client;
1052 	int declen;
1053 	u8 *sym;
1054 
1055 	sym = kmalloc(enclen + 1, GFP_NOFS);
1056 	if (!sym)
1057 		return -ENOMEM;
1058 
1059 	declen = base64_decode(encsym, enclen, sym, false, BASE64_IMAP);
1060 	if (declen < 0) {
1061 		pr_err_client(cl,
1062 			"can't decode symlink (%d). Content: %.*s\n",
1063 			declen, enclen, encsym);
1064 		kfree(sym);
1065 		return -EIO;
1066 	}
1067 	sym[declen] = '\0';
1068 	*decsym = sym;
1069 	return declen;
1070 }
1071 #else
1072 static int decode_encrypted_symlink(struct ceph_mds_client *mdsc,
1073 				    const char *encsym,
1074 				    int symlen, u8 **decsym)
1075 {
1076 	return -EOPNOTSUPP;
1077 }
1078 #endif
1079 
1080 /*
1081  * Populate an inode based on info from mds.  May be called on new or
1082  * existing inodes.
1083  */
1084 int ceph_fill_inode(struct inode *inode, struct folio *locked_folio,
1085 		    struct ceph_mds_reply_info_in *iinfo,
1086 		    struct ceph_mds_reply_dirfrag *dirinfo,
1087 		    struct ceph_mds_session *session, int cap_fmode,
1088 		    struct ceph_cap_reservation *caps_reservation)
1089 {
1090 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
1091 	struct ceph_client *cl = mdsc->fsc->client;
1092 	struct ceph_mds_reply_inode *info = iinfo->in;
1093 	struct ceph_inode_info *ci = ceph_inode(inode);
1094 	int issued, new_issued, info_caps;
1095 	struct timespec64 mtime, atime, ctime;
1096 	struct ceph_buffer *xattr_blob = NULL;
1097 	struct ceph_buffer *old_blob = NULL;
1098 	struct ceph_string *pool_ns = NULL;
1099 	struct ceph_cap *new_cap = NULL;
1100 	int err = 0;
1101 	bool wake = false;
1102 	bool queue_trunc = false;
1103 	bool new_version = false;
1104 	bool fill_inline = false;
1105 	umode_t mode = le32_to_cpu(info->mode);
1106 	dev_t rdev = le32_to_cpu(info->rdev);
1107 
1108 	lockdep_assert_held(&mdsc->snap_rwsem);
1109 
1110 	doutc(cl, "%p ino %llx.%llx v %llu had %llu\n", inode, ceph_vinop(inode),
1111 	      le64_to_cpu(info->version), ci->i_version);
1112 
1113 	/* Once I_NEW is cleared, we can't change type or dev numbers */
1114 	if (inode_state_read_once(inode) & I_NEW) {
1115 		inode->i_mode = mode;
1116 	} else {
1117 		if (inode_wrong_type(inode, mode)) {
1118 			pr_warn_once_client(cl,
1119 				"inode type changed! (ino %llx.%llx is 0%o, mds says 0%o)\n",
1120 				ceph_vinop(inode), inode->i_mode, mode);
1121 			return -ESTALE;
1122 		}
1123 
1124 		if ((S_ISCHR(mode) || S_ISBLK(mode)) && inode->i_rdev != rdev) {
1125 			pr_warn_once_client(cl,
1126 				"dev inode rdev changed! (ino %llx.%llx is %u:%u, mds says %u:%u)\n",
1127 				ceph_vinop(inode), MAJOR(inode->i_rdev),
1128 				MINOR(inode->i_rdev), MAJOR(rdev),
1129 				MINOR(rdev));
1130 			return -ESTALE;
1131 		}
1132 	}
1133 
1134 	info_caps = le32_to_cpu(info->cap.caps);
1135 
1136 	/* prealloc new cap struct */
1137 	if (info_caps && !ceph_in_snap(inode)) {
1138 		new_cap = ceph_get_cap(mdsc, caps_reservation);
1139 		if (!new_cap)
1140 			return -ENOMEM;
1141 	}
1142 
1143 	/*
1144 	 * prealloc xattr data, if it looks like we'll need it.  only
1145 	 * if len > 4 (meaning there are actually xattrs; the first 4
1146 	 * bytes are the xattr count).
1147 	 */
1148 	if (iinfo->xattr_len > 4) {
1149 		xattr_blob = ceph_buffer_new(iinfo->xattr_len, GFP_NOFS);
1150 		if (!xattr_blob)
1151 			pr_err_client(cl, "ENOMEM xattr blob %d bytes\n",
1152 				      iinfo->xattr_len);
1153 	}
1154 
1155 	if (iinfo->pool_ns_len > 0)
1156 		pool_ns = ceph_find_or_create_string(iinfo->pool_ns_data,
1157 						     iinfo->pool_ns_len);
1158 
1159 	if (ceph_in_snap(inode) && !ci->i_snapid_map)
1160 		ci->i_snapid_map = ceph_get_snapid_map(mdsc, ceph_snap(inode));
1161 
1162 	spin_lock(&ci->i_ceph_lock);
1163 
1164 	/*
1165 	 * provided version will be odd if inode value is projected,
1166 	 * even if stable.  skip the update if we have newer stable
1167 	 * info (ours>=theirs, e.g. due to racing mds replies), unless
1168 	 * we are getting projected (unstable) info (in which case the
1169 	 * version is odd, and we want ours>theirs).
1170 	 *   us   them
1171 	 *   2    2     skip
1172 	 *   3    2     skip
1173 	 *   3    3     update
1174 	 */
1175 	if (ci->i_version == 0 ||
1176 	    ((info->cap.flags & CEPH_CAP_FLAG_AUTH) &&
1177 	     le64_to_cpu(info->version) > (ci->i_version & ~1)))
1178 		new_version = true;
1179 
1180 	/* Update change_attribute */
1181 	inode_set_max_iversion_raw(inode, iinfo->change_attr);
1182 
1183 	__ceph_caps_issued(ci, &issued);
1184 	issued |= __ceph_caps_dirty(ci);
1185 	new_issued = ~issued & info_caps;
1186 
1187 	__ceph_update_quota(ci, iinfo->max_bytes, iinfo->max_files);
1188 	ceph_inode_set_subvolume(inode, iinfo->subvolume_id);
1189 
1190 #ifdef CONFIG_FS_ENCRYPTION
1191 	if (iinfo->fscrypt_auth_len &&
1192 	    ((inode_state_read_once(inode) & I_NEW) || (ci->fscrypt_auth_len == 0))) {
1193 		kfree(ci->fscrypt_auth);
1194 		ci->fscrypt_auth_len = iinfo->fscrypt_auth_len;
1195 		ci->fscrypt_auth = iinfo->fscrypt_auth;
1196 		iinfo->fscrypt_auth = NULL;
1197 		iinfo->fscrypt_auth_len = 0;
1198 		inode_set_flags(inode, S_ENCRYPTED, S_ENCRYPTED);
1199 	}
1200 #endif
1201 
1202 	if ((new_version || (new_issued & CEPH_CAP_AUTH_SHARED)) &&
1203 	    (issued & CEPH_CAP_AUTH_EXCL) == 0) {
1204 		inode->i_mode = mode;
1205 		inode->i_uid = make_kuid(&init_user_ns, le32_to_cpu(info->uid));
1206 		inode->i_gid = make_kgid(&init_user_ns, le32_to_cpu(info->gid));
1207 		doutc(cl, "%p %llx.%llx mode 0%o uid.gid %d.%d\n", inode,
1208 		      ceph_vinop(inode), inode->i_mode,
1209 		      from_kuid(&init_user_ns, inode->i_uid),
1210 		      from_kgid(&init_user_ns, inode->i_gid));
1211 		ceph_decode_timespec64(&ci->i_btime, &iinfo->btime);
1212 		ceph_decode_timespec64(&ci->i_snap_btime, &iinfo->snap_btime);
1213 	}
1214 
1215 	/* directories have fl_stripe_unit set to zero */
1216 	if (IS_ENCRYPTED(inode))
1217 		inode->i_blkbits = CEPH_FSCRYPT_BLOCK_SHIFT;
1218 	else if (le32_to_cpu(info->layout.fl_stripe_unit))
1219 		inode->i_blkbits =
1220 			fls(le32_to_cpu(info->layout.fl_stripe_unit)) - 1;
1221 	else
1222 		inode->i_blkbits = CEPH_BLOCK_SHIFT;
1223 
1224 	if ((new_version || (new_issued & CEPH_CAP_LINK_SHARED)) &&
1225 	    (issued & CEPH_CAP_LINK_EXCL) == 0)
1226 		set_nlink(inode, le32_to_cpu(info->nlink));
1227 
1228 	if (new_version || (new_issued & CEPH_CAP_ANY_RD)) {
1229 		/* be careful with mtime, atime, size */
1230 		ceph_decode_timespec64(&atime, &info->atime);
1231 		ceph_decode_timespec64(&mtime, &info->mtime);
1232 		ceph_decode_timespec64(&ctime, &info->ctime);
1233 		ceph_fill_file_time(inode, issued,
1234 				le32_to_cpu(info->time_warp_seq),
1235 				&ctime, &mtime, &atime);
1236 	}
1237 
1238 	if (new_version || (info_caps & CEPH_CAP_FILE_SHARED)) {
1239 		ci->i_files = le64_to_cpu(info->files);
1240 		ci->i_subdirs = le64_to_cpu(info->subdirs);
1241 	}
1242 
1243 	if (new_version ||
1244 	    (new_issued & (CEPH_CAP_ANY_FILE_RD | CEPH_CAP_ANY_FILE_WR))) {
1245 		u64 size = le64_to_cpu(info->size);
1246 		s64 old_pool = ci->i_layout.pool_id;
1247 		struct ceph_string *old_ns;
1248 
1249 		ceph_file_layout_from_legacy(&ci->i_layout, &info->layout);
1250 		old_ns = rcu_dereference_protected(ci->i_layout.pool_ns,
1251 					lockdep_is_held(&ci->i_ceph_lock));
1252 		rcu_assign_pointer(ci->i_layout.pool_ns, pool_ns);
1253 
1254 		if (ci->i_layout.pool_id != old_pool || pool_ns != old_ns)
1255 			clear_bit(CEPH_I_POOL_PERM_BIT, &ci->i_ceph_flags);
1256 
1257 		pool_ns = old_ns;
1258 
1259 		if (IS_ENCRYPTED(inode) && size &&
1260 		    iinfo->fscrypt_file_len == sizeof(__le64)) {
1261 			u64 fsize = __le64_to_cpu(*(__le64 *)iinfo->fscrypt_file);
1262 
1263 			if (size == round_up(fsize, CEPH_FSCRYPT_BLOCK_SIZE)) {
1264 				size = fsize;
1265 			} else {
1266 				pr_warn_client(cl,
1267 					"fscrypt size mismatch: size=%llu fscrypt_file=%llu, discarding fscrypt_file size.\n",
1268 					info->size, size);
1269 			}
1270 		}
1271 
1272 		queue_trunc = ceph_fill_file_size(inode, issued,
1273 					le32_to_cpu(info->truncate_seq),
1274 					le64_to_cpu(info->truncate_size),
1275 					size);
1276 		/* only update max_size on auth cap */
1277 		if ((info->cap.flags & CEPH_CAP_FLAG_AUTH) &&
1278 		    ci->i_max_size != le64_to_cpu(info->max_size)) {
1279 			doutc(cl, "max_size %lld -> %llu\n",
1280 			    ci->i_max_size, le64_to_cpu(info->max_size));
1281 			ci->i_max_size = le64_to_cpu(info->max_size);
1282 		}
1283 	}
1284 
1285 	/* layout and rstat are not tracked by capability, update them if
1286 	 * the inode info is from auth mds */
1287 	if (new_version || (info->cap.flags & CEPH_CAP_FLAG_AUTH)) {
1288 		if (S_ISDIR(inode->i_mode)) {
1289 			ci->i_dir_layout = iinfo->dir_layout;
1290 			ci->i_rbytes = le64_to_cpu(info->rbytes);
1291 			ci->i_rfiles = le64_to_cpu(info->rfiles);
1292 			ci->i_rsubdirs = le64_to_cpu(info->rsubdirs);
1293 			ci->i_dir_pin = iinfo->dir_pin;
1294 			ci->i_rsnaps = iinfo->rsnaps;
1295 			ceph_decode_timespec64(&ci->i_rctime, &info->rctime);
1296 		}
1297 	}
1298 
1299 	/* xattrs */
1300 	/* note that if i_xattrs.len <= 4, i_xattrs.data will still be NULL. */
1301 	if ((ci->i_xattrs.version == 0 || !(issued & CEPH_CAP_XATTR_EXCL))  &&
1302 	    le64_to_cpu(info->xattr_version) > ci->i_xattrs.version) {
1303 		if (ci->i_xattrs.blob)
1304 			old_blob = ci->i_xattrs.blob;
1305 		ci->i_xattrs.blob = xattr_blob;
1306 		if (xattr_blob)
1307 			memcpy(ci->i_xattrs.blob->vec.iov_base,
1308 			       iinfo->xattr_data, iinfo->xattr_len);
1309 		ci->i_xattrs.version = le64_to_cpu(info->xattr_version);
1310 		ceph_forget_all_cached_acls(inode);
1311 		ceph_security_invalidate_secctx(inode);
1312 		xattr_blob = NULL;
1313 	}
1314 
1315 	/* finally update i_version */
1316 	if (le64_to_cpu(info->version) > ci->i_version)
1317 		ci->i_version = le64_to_cpu(info->version);
1318 
1319 	inode->i_mapping->a_ops = &ceph_aops;
1320 
1321 	switch (inode->i_mode & S_IFMT) {
1322 	case S_IFIFO:
1323 	case S_IFBLK:
1324 	case S_IFCHR:
1325 	case S_IFSOCK:
1326 		inode->i_blkbits = PAGE_SHIFT;
1327 		init_special_inode(inode, inode->i_mode, rdev);
1328 		inode->i_op = &ceph_file_iops;
1329 		break;
1330 	case S_IFREG:
1331 		inode->i_op = &ceph_file_iops;
1332 		inode->i_fop = &ceph_file_fops;
1333 		break;
1334 	case S_IFLNK:
1335 		if (!ci->i_symlink) {
1336 			u32 symlen = iinfo->symlink_len;
1337 			char *sym;
1338 
1339 			spin_unlock(&ci->i_ceph_lock);
1340 
1341 			if (IS_ENCRYPTED(inode)) {
1342 				if (symlen != i_size_read(inode))
1343 					pr_err_client(cl,
1344 						"%p %llx.%llx BAD symlink size %lld\n",
1345 						inode, ceph_vinop(inode),
1346 						i_size_read(inode));
1347 
1348 				err = decode_encrypted_symlink(mdsc, iinfo->symlink,
1349 							       symlen, (u8 **)&sym);
1350 				if (err < 0) {
1351 					pr_err_client(cl,
1352 						"decoding encrypted symlink failed: %d\n",
1353 						err);
1354 					goto out;
1355 				}
1356 				symlen = err;
1357 				i_size_write(inode, symlen);
1358 				inode->i_blocks = calc_inode_blocks(symlen);
1359 			} else {
1360 				if (symlen != i_size_read(inode)) {
1361 					pr_err_client(cl,
1362 						"%p %llx.%llx BAD symlink size %lld\n",
1363 						inode, ceph_vinop(inode),
1364 						i_size_read(inode));
1365 					i_size_write(inode, symlen);
1366 					inode->i_blocks = calc_inode_blocks(symlen);
1367 				}
1368 
1369 				err = -ENOMEM;
1370 				sym = kstrndup(iinfo->symlink, symlen, GFP_NOFS);
1371 				if (!sym)
1372 					goto out;
1373 			}
1374 
1375 			spin_lock(&ci->i_ceph_lock);
1376 			if (!ci->i_symlink)
1377 				ci->i_symlink = sym;
1378 			else
1379 				kfree(sym); /* lost a race */
1380 		}
1381 
1382 		if (IS_ENCRYPTED(inode)) {
1383 			/*
1384 			 * Encrypted symlinks need to be decrypted before we can
1385 			 * cache their targets in i_link. Don't touch it here.
1386 			 */
1387 			inode->i_op = &ceph_encrypted_symlink_iops;
1388 		} else {
1389 			inode->i_link = ci->i_symlink;
1390 			inode->i_op = &ceph_symlink_iops;
1391 		}
1392 		break;
1393 	case S_IFDIR:
1394 		inode->i_op = &ceph_dir_iops;
1395 		inode->i_fop = &ceph_dir_fops;
1396 		break;
1397 	default:
1398 		pr_err_client(cl, "%p %llx.%llx BAD mode 0%o\n", inode,
1399 			      ceph_vinop(inode), inode->i_mode);
1400 	}
1401 
1402 	/* were we issued a capability? */
1403 	if (info_caps) {
1404 		if (!ceph_in_snap(inode)) {
1405 			ceph_add_cap(inode, session,
1406 				     le64_to_cpu(info->cap.cap_id),
1407 				     info_caps,
1408 				     le32_to_cpu(info->cap.wanted),
1409 				     le32_to_cpu(info->cap.seq),
1410 				     le32_to_cpu(info->cap.mseq),
1411 				     le64_to_cpu(info->cap.realm),
1412 				     info->cap.flags, &new_cap);
1413 
1414 			/* set dir completion flag? */
1415 			if (S_ISDIR(inode->i_mode) &&
1416 			    ci->i_files == 0 && ci->i_subdirs == 0 &&
1417 			    (info_caps & CEPH_CAP_FILE_SHARED) &&
1418 			    (issued & CEPH_CAP_FILE_EXCL) == 0 &&
1419 			    !__ceph_dir_is_complete(ci)) {
1420 				doutc(cl, " marking %p complete (empty)\n",
1421 				      inode);
1422 				i_size_write(inode, 0);
1423 				__ceph_dir_set_complete(ci,
1424 					atomic64_read(&ci->i_release_count),
1425 					atomic64_read(&ci->i_ordered_count));
1426 			}
1427 
1428 			wake = true;
1429 		} else {
1430 			doutc(cl, " %p got snap_caps %s\n", inode,
1431 			      ceph_cap_string(info_caps));
1432 			ci->i_snap_caps |= info_caps;
1433 		}
1434 	}
1435 
1436 	if (iinfo->inline_version > 0 &&
1437 	    iinfo->inline_version >= ceph_inline_version(ci)) {
1438 		int cache_caps = CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO;
1439 		ceph_set_inline_version(ci, iinfo->inline_version);
1440 		if (ceph_has_inline_data(ci) &&
1441 		    (locked_folio || (info_caps & cache_caps)))
1442 			fill_inline = true;
1443 	}
1444 
1445 	if (cap_fmode >= 0) {
1446 		if (!info_caps)
1447 			pr_warn_client(cl, "mds issued no caps on %llx.%llx\n",
1448 				       ceph_vinop(inode));
1449 		__ceph_touch_fmode(ci, mdsc, cap_fmode);
1450 	}
1451 
1452 	spin_unlock(&ci->i_ceph_lock);
1453 
1454 	ceph_fscache_register_inode_cookie(inode);
1455 
1456 	if (fill_inline)
1457 		ceph_fill_inline_data(inode, locked_folio,
1458 				      iinfo->inline_data, iinfo->inline_len);
1459 
1460 	if (wake)
1461 		wake_up_all(&ci->i_cap_wq);
1462 
1463 	/* queue truncate if we saw i_size decrease */
1464 	if (queue_trunc)
1465 		ceph_queue_vmtruncate(inode);
1466 
1467 	/* populate frag tree */
1468 	if (S_ISDIR(inode->i_mode))
1469 		ceph_fill_fragtree(inode, &info->fragtree, dirinfo);
1470 
1471 	/* update delegation info? */
1472 	if (dirinfo)
1473 		ceph_fill_dirfrag(inode, dirinfo);
1474 
1475 	err = 0;
1476 out:
1477 	if (new_cap)
1478 		ceph_put_cap(mdsc, new_cap);
1479 	ceph_buffer_put(old_blob);
1480 	ceph_buffer_put(xattr_blob);
1481 	ceph_put_string(pool_ns);
1482 	return err;
1483 }
1484 
1485 /*
1486  * caller should hold session s_mutex and dentry->d_lock.
1487  */
1488 static void __update_dentry_lease(struct inode *dir, struct dentry *dentry,
1489 				  struct ceph_mds_reply_lease *lease,
1490 				  struct ceph_mds_session *session,
1491 				  unsigned long from_time,
1492 				  struct ceph_mds_session **old_lease_session)
1493 {
1494 	struct ceph_client *cl = ceph_inode_to_client(dir);
1495 	struct ceph_dentry_info *di = ceph_dentry(dentry);
1496 	unsigned mask = le16_to_cpu(lease->mask);
1497 	long unsigned duration = le32_to_cpu(lease->duration_ms);
1498 	long unsigned ttl = from_time + (duration * HZ) / 1000;
1499 	long unsigned half_ttl = from_time + (duration * HZ / 2) / 1000;
1500 
1501 	doutc(cl, "%p duration %lu ms ttl %lu\n", dentry, duration, ttl);
1502 
1503 	/* only track leases on regular dentries */
1504 	if (ceph_in_snap(dir))
1505 		return;
1506 
1507 	if (mask & CEPH_LEASE_PRIMARY_LINK)
1508 		di->flags |= CEPH_DENTRY_PRIMARY_LINK;
1509 	else
1510 		di->flags &= ~CEPH_DENTRY_PRIMARY_LINK;
1511 
1512 	di->lease_shared_gen = atomic_read(&ceph_inode(dir)->i_shared_gen);
1513 	if (!(mask & CEPH_LEASE_VALID)) {
1514 		__ceph_dentry_dir_lease_touch(di);
1515 		return;
1516 	}
1517 
1518 	if (di->lease_gen == atomic_read(&session->s_cap_gen) &&
1519 	    time_before(ttl, di->time))
1520 		return;  /* we already have a newer lease. */
1521 
1522 	if (di->lease_session && di->lease_session != session) {
1523 		*old_lease_session = di->lease_session;
1524 		di->lease_session = NULL;
1525 	}
1526 
1527 	if (!di->lease_session)
1528 		di->lease_session = ceph_get_mds_session(session);
1529 	di->lease_gen = atomic_read(&session->s_cap_gen);
1530 	di->lease_seq = le32_to_cpu(lease->seq);
1531 	di->lease_renew_after = half_ttl;
1532 	di->lease_renew_from = 0;
1533 	di->time = ttl;
1534 
1535 	__ceph_dentry_lease_touch(di);
1536 }
1537 
1538 static inline void update_dentry_lease(struct inode *dir, struct dentry *dentry,
1539 					struct ceph_mds_reply_lease *lease,
1540 					struct ceph_mds_session *session,
1541 					unsigned long from_time)
1542 {
1543 	struct ceph_mds_session *old_lease_session = NULL;
1544 	spin_lock(&dentry->d_lock);
1545 	__update_dentry_lease(dir, dentry, lease, session, from_time,
1546 			      &old_lease_session);
1547 	spin_unlock(&dentry->d_lock);
1548 	ceph_put_mds_session(old_lease_session);
1549 }
1550 
1551 /*
1552  * update dentry lease without having parent inode locked
1553  */
1554 static void update_dentry_lease_careful(struct dentry *dentry,
1555 					struct ceph_mds_reply_lease *lease,
1556 					struct ceph_mds_session *session,
1557 					unsigned long from_time,
1558 					char *dname, u32 dname_len,
1559 					struct ceph_vino *pdvino,
1560 					struct ceph_vino *ptvino)
1561 
1562 {
1563 	struct inode *dir;
1564 	struct ceph_mds_session *old_lease_session = NULL;
1565 
1566 	spin_lock(&dentry->d_lock);
1567 	/* make sure dentry's name matches target */
1568 	if (dentry->d_name.len != dname_len ||
1569 	    memcmp(dentry->d_name.name, dname, dname_len))
1570 		goto out_unlock;
1571 
1572 	dir = d_inode(dentry->d_parent);
1573 	/* make sure parent matches dvino */
1574 	if (!ceph_ino_compare(dir, pdvino))
1575 		goto out_unlock;
1576 
1577 	/* make sure dentry's inode matches target. NULL ptvino means that
1578 	 * we expect a negative dentry */
1579 	if (ptvino) {
1580 		if (d_really_is_negative(dentry))
1581 			goto out_unlock;
1582 		if (!ceph_ino_compare(d_inode(dentry), ptvino))
1583 			goto out_unlock;
1584 	} else {
1585 		if (d_really_is_positive(dentry))
1586 			goto out_unlock;
1587 	}
1588 
1589 	__update_dentry_lease(dir, dentry, lease, session,
1590 			      from_time, &old_lease_session);
1591 out_unlock:
1592 	spin_unlock(&dentry->d_lock);
1593 	ceph_put_mds_session(old_lease_session);
1594 }
1595 
1596 /*
1597  * splice a dentry to an inode.
1598  * caller must hold directory i_rwsem for this to be safe.
1599  */
1600 static int splice_dentry(struct dentry **pdn, struct inode *in)
1601 {
1602 	struct ceph_client *cl = ceph_inode_to_client(in);
1603 	struct dentry *dn = *pdn;
1604 	struct dentry *realdn;
1605 
1606 	BUG_ON(d_inode(dn));
1607 
1608 	if (S_ISDIR(in->i_mode)) {
1609 		/* If inode is directory, d_splice_alias() below will remove
1610 		 * 'realdn' from its origin parent. We need to ensure that
1611 		 * origin parent's readdir cache will not reference 'realdn'
1612 		 */
1613 		realdn = d_find_any_alias(in);
1614 		if (realdn) {
1615 			struct ceph_dentry_info *di = ceph_dentry(realdn);
1616 			spin_lock(&realdn->d_lock);
1617 
1618 			realdn->d_op->d_prune(realdn);
1619 
1620 			di->time = jiffies;
1621 			di->lease_shared_gen = 0;
1622 			di->offset = 0;
1623 
1624 			spin_unlock(&realdn->d_lock);
1625 			dput(realdn);
1626 		}
1627 	}
1628 
1629 	/* dn must be unhashed */
1630 	if (!d_unhashed(dn))
1631 		d_drop(dn);
1632 	realdn = d_splice_alias(in, dn);
1633 	if (IS_ERR(realdn)) {
1634 		pr_err_client(cl, "error %ld %p inode %p ino %llx.%llx\n",
1635 			      PTR_ERR(realdn), dn, in, ceph_vinop(in));
1636 		return PTR_ERR(realdn);
1637 	}
1638 
1639 	if (realdn) {
1640 		doutc(cl, "dn %p (%d) spliced with %p (%d) inode %p ino %llx.%llx\n",
1641 		      dn, d_count(dn), realdn, d_count(realdn),
1642 		      d_inode(realdn), ceph_vinop(d_inode(realdn)));
1643 		dput(dn);
1644 		*pdn = realdn;
1645 	} else {
1646 		BUG_ON(!ceph_dentry(dn));
1647 		doutc(cl, "dn %p attached to %p ino %llx.%llx\n", dn,
1648 		      d_inode(dn), ceph_vinop(d_inode(dn)));
1649 	}
1650 	return 0;
1651 }
1652 
1653 /*
1654  * Incorporate results into the local cache.  This is either just
1655  * one inode, or a directory, dentry, and possibly linked-to inode (e.g.,
1656  * after a lookup).
1657  *
1658  * A reply may contain
1659  *         a directory inode along with a dentry.
1660  *  and/or a target inode
1661  *
1662  * Called with snap_rwsem (read).
1663  */
1664 int ceph_fill_trace(struct super_block *sb, struct ceph_mds_request *req)
1665 {
1666 	struct ceph_mds_session *session = req->r_session;
1667 	struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
1668 	struct inode *in = NULL;
1669 	struct ceph_vino tvino, dvino;
1670 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(sb);
1671 	struct ceph_client *cl = fsc->client;
1672 	struct inode *parent_dir = NULL;
1673 	int err = 0;
1674 
1675 	doutc(cl, "%p is_dentry %d is_target %d\n", req,
1676 	      rinfo->head->is_dentry, rinfo->head->is_target);
1677 
1678 	if (!rinfo->head->is_target && !rinfo->head->is_dentry) {
1679 		doutc(cl, "reply is empty!\n");
1680 		if (rinfo->head->result == 0 && req->r_parent)
1681 			ceph_invalidate_dir_request(req);
1682 		return 0;
1683 	}
1684 
1685 	if (rinfo->head->is_dentry) {
1686 		/*
1687 		 * r_parent may be stale, in cases when R_PARENT_LOCKED is not set,
1688 		 * so we need to get the correct inode
1689 		 */
1690 		parent_dir = ceph_get_reply_dir(sb, req->r_parent, rinfo);
1691 		if (unlikely(IS_ERR(parent_dir))) {
1692 			err = PTR_ERR(parent_dir);
1693 			goto done;
1694 		}
1695 		if (parent_dir) {
1696 			ceph_inode_set_subvolume(parent_dir,
1697 						 rinfo->diri.subvolume_id);
1698 			err = ceph_fill_inode(parent_dir, NULL, &rinfo->diri,
1699 					      rinfo->dirfrag, session, -1,
1700 					      &req->r_caps_reservation);
1701 			if (err < 0)
1702 				goto done;
1703 		} else {
1704 			WARN_ON_ONCE(1);
1705 		}
1706 
1707 		if (parent_dir && req->r_op == CEPH_MDS_OP_LOOKUPNAME &&
1708 		    test_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags) &&
1709 		    !test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags)) {
1710 			bool is_nokey = false;
1711 			struct qstr dname;
1712 			struct dentry *dn, *parent;
1713 			struct fscrypt_str oname = FSTR_INIT(NULL, 0);
1714 			struct ceph_fname fname = { .dir	= parent_dir,
1715 						    .name	= rinfo->dname,
1716 						    .ctext	= rinfo->altname,
1717 						    .name_len	= rinfo->dname_len,
1718 						    .ctext_len	= rinfo->altname_len };
1719 
1720 			BUG_ON(!rinfo->head->is_target);
1721 			BUG_ON(req->r_dentry);
1722 
1723 			parent = d_find_any_alias(parent_dir);
1724 			BUG_ON(!parent);
1725 
1726 			err = ceph_fname_alloc_buffer(parent_dir, &oname);
1727 			if (err < 0) {
1728 				dput(parent);
1729 				goto done;
1730 			}
1731 
1732 			err = ceph_fname_to_usr(&fname, NULL, &oname, &is_nokey);
1733 			if (err < 0) {
1734 				dput(parent);
1735 				ceph_fname_free_buffer(parent_dir, &oname);
1736 				goto done;
1737 			}
1738 			dname.name = oname.name;
1739 			dname.len = oname.len;
1740 			dname.hash = full_name_hash(parent, dname.name, dname.len);
1741 			tvino.ino = le64_to_cpu(rinfo->targeti.in->ino);
1742 			tvino.snap = le64_to_cpu(rinfo->targeti.in->snapid);
1743 retry_lookup:
1744 			dn = d_lookup(parent, &dname);
1745 			doutc(cl, "d_lookup on parent=%p name=%.*s got %p\n",
1746 			      parent, dname.len, dname.name, dn);
1747 
1748 			if (!dn) {
1749 				dn = d_alloc(parent, &dname);
1750 				doutc(cl, "d_alloc %p '%.*s' = %p\n", parent,
1751 				      dname.len, dname.name, dn);
1752 				if (!dn) {
1753 					dput(parent);
1754 					ceph_fname_free_buffer(parent_dir, &oname);
1755 					err = -ENOMEM;
1756 					goto done;
1757 				}
1758 				if (is_nokey) {
1759 					spin_lock(&dn->d_lock);
1760 					dn->d_flags |= DCACHE_NOKEY_NAME;
1761 					spin_unlock(&dn->d_lock);
1762 				}
1763 				err = 0;
1764 			} else if (d_really_is_positive(dn) &&
1765 				   (ceph_ino(d_inode(dn)) != tvino.ino ||
1766 				    ceph_snap(d_inode(dn)) != tvino.snap)) {
1767 				doutc(cl, " dn %p points to wrong inode %p\n",
1768 				      dn, d_inode(dn));
1769 				ceph_dir_clear_ordered(parent_dir);
1770 				d_delete(dn);
1771 				dput(dn);
1772 				goto retry_lookup;
1773 			}
1774 			ceph_fname_free_buffer(parent_dir, &oname);
1775 
1776 			req->r_dentry = dn;
1777 			dput(parent);
1778 		}
1779 	}
1780 
1781 	if (rinfo->head->is_target) {
1782 		/* Should be filled in by handle_reply */
1783 		BUG_ON(!req->r_target_inode);
1784 
1785 		in = req->r_target_inode;
1786 		ceph_inode_set_subvolume(in, rinfo->targeti.subvolume_id);
1787 		err = ceph_fill_inode(in, req->r_locked_folio, &rinfo->targeti,
1788 				NULL, session,
1789 				(!test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags) &&
1790 				 !test_bit(CEPH_MDS_R_ASYNC, &req->r_req_flags) &&
1791 				 rinfo->head->result == 0) ?  req->r_fmode : -1,
1792 				&req->r_caps_reservation);
1793 		if (err < 0) {
1794 			pr_err_client(cl, "badness %p %llx.%llx\n", in,
1795 				      ceph_vinop(in));
1796 			req->r_target_inode = NULL;
1797 			if (inode_state_read_once(in) & I_NEW)
1798 				discard_new_inode(in);
1799 			else
1800 				iput(in);
1801 			goto done;
1802 		}
1803 		if (inode_state_read_once(in) & I_NEW)
1804 			unlock_new_inode(in);
1805 	}
1806 
1807 	/*
1808 	 * ignore null lease/binding on snapdir ENOENT, or else we
1809 	 * will have trouble splicing in the virtual snapdir later
1810 	 */
1811 	if (rinfo->head->is_dentry &&
1812             !test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags) &&
1813 	    test_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags) &&
1814 	    (rinfo->head->is_target || strncmp(req->r_dentry->d_name.name,
1815 					       fsc->mount_options->snapdir_name,
1816 					       req->r_dentry->d_name.len))) {
1817 		/*
1818 		 * lookup link rename   : null -> possibly existing inode
1819 		 * mknod symlink mkdir  : null -> new inode
1820 		 * unlink               : linked -> null
1821 		 */
1822 		struct inode *dir = req->r_parent;
1823 		struct dentry *dn = req->r_dentry;
1824 		bool have_dir_cap, have_lease;
1825 
1826 		BUG_ON(!dn);
1827 		BUG_ON(!dir);
1828 		BUG_ON(d_inode(dn->d_parent) != dir);
1829 
1830 		dvino.ino = le64_to_cpu(rinfo->diri.in->ino);
1831 		dvino.snap = le64_to_cpu(rinfo->diri.in->snapid);
1832 
1833 		BUG_ON(ceph_ino(dir) != dvino.ino);
1834 		BUG_ON(ceph_snap(dir) != dvino.snap);
1835 
1836 		/* do we have a lease on the whole dir? */
1837 		have_dir_cap =
1838 			(le32_to_cpu(rinfo->diri.in->cap.caps) &
1839 			 CEPH_CAP_FILE_SHARED);
1840 
1841 		/* do we have a dn lease? */
1842 		have_lease = have_dir_cap ||
1843 			le32_to_cpu(rinfo->dlease->duration_ms);
1844 		if (!have_lease)
1845 			doutc(cl, "no dentry lease or dir cap\n");
1846 
1847 		/* rename? */
1848 		if (req->r_old_dentry && req->r_op == CEPH_MDS_OP_RENAME) {
1849 			struct inode *olddir = req->r_old_dentry_dir;
1850 			BUG_ON(!olddir);
1851 
1852 			doutc(cl, " src %p '%pd' dst %p '%pd'\n",
1853 			      req->r_old_dentry, req->r_old_dentry, dn, dn);
1854 			doutc(cl, "doing d_move %p -> %p\n", req->r_old_dentry, dn);
1855 
1856 			/* d_move screws up sibling dentries' offsets */
1857 			ceph_dir_clear_ordered(dir);
1858 			ceph_dir_clear_ordered(olddir);
1859 
1860 			d_move(req->r_old_dentry, dn);
1861 			doutc(cl, " src %p '%pd' dst %p '%pd'\n",
1862 			      req->r_old_dentry, req->r_old_dentry, dn, dn);
1863 
1864 			/* ensure target dentry is invalidated, despite
1865 			   rehashing bug in vfs_rename_dir */
1866 			ceph_invalidate_dentry_lease(dn);
1867 
1868 			doutc(cl, "dn %p gets new offset %lld\n",
1869 			      req->r_old_dentry,
1870 			      ceph_dentry(req->r_old_dentry)->offset);
1871 
1872 			/* swap r_dentry and r_old_dentry in case that
1873 			 * splice_dentry() gets called later. This is safe
1874 			 * because no other place will use them */
1875 			req->r_dentry = req->r_old_dentry;
1876 			req->r_old_dentry = dn;
1877 			dn = req->r_dentry;
1878 		}
1879 
1880 		/* null dentry? */
1881 		if (!rinfo->head->is_target) {
1882 			doutc(cl, "null dentry\n");
1883 			if (d_really_is_positive(dn)) {
1884 				doutc(cl, "d_delete %p\n", dn);
1885 				ceph_dir_clear_ordered(dir);
1886 				d_delete(dn);
1887 			} else if (have_lease) {
1888 				if (d_unhashed(dn) &&
1889 				    ceph_snap(dir) == CEPH_NOSNAP)
1890 					d_add(dn, NULL);
1891 			}
1892 
1893 			if (!d_unhashed(dn) && have_lease)
1894 				update_dentry_lease(dir, dn,
1895 						    rinfo->dlease, session,
1896 						    req->r_request_started);
1897 			goto done;
1898 		}
1899 
1900 		if (unlikely(!in)) {
1901 			err = -EINVAL;
1902 			goto done;
1903 		}
1904 
1905 		/* attach proper inode */
1906 		if (d_really_is_negative(dn)) {
1907 			ceph_dir_clear_ordered(dir);
1908 			ihold(in);
1909 			err = splice_dentry(&req->r_dentry, in);
1910 			if (err < 0)
1911 				goto done;
1912 			dn = req->r_dentry;  /* may have spliced */
1913 		} else if (d_really_is_positive(dn) && d_inode(dn) != in) {
1914 			doutc(cl, " %p links to %p %llx.%llx, not %llx.%llx\n",
1915 			      dn, d_inode(dn), ceph_vinop(d_inode(dn)),
1916 			      ceph_vinop(in));
1917 			d_invalidate(dn);
1918 			have_lease = false;
1919 		}
1920 
1921 		if (have_lease) {
1922 			update_dentry_lease(dir, dn,
1923 					    rinfo->dlease, session,
1924 					    req->r_request_started);
1925 		}
1926 		doutc(cl, " final dn %p\n", dn);
1927 	} else if ((req->r_op == CEPH_MDS_OP_LOOKUPSNAP ||
1928 		    req->r_op == CEPH_MDS_OP_MKSNAP) &&
1929 	           test_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags) &&
1930 		   !test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags)) {
1931 		struct inode *dir = req->r_parent;
1932 
1933 		/* fill out a snapdir LOOKUPSNAP dentry */
1934 		BUG_ON(!dir);
1935 		BUG_ON(ceph_snap(dir) != CEPH_SNAPDIR);
1936 		BUG_ON(!req->r_dentry);
1937 		doutc(cl, " linking snapped dir %p to dn %p\n", in,
1938 		      req->r_dentry);
1939 		ceph_dir_clear_ordered(dir);
1940 
1941 		if (unlikely(!in)) {
1942 			err = -EINVAL;
1943 			goto done;
1944 		}
1945 
1946 		ihold(in);
1947 		err = splice_dentry(&req->r_dentry, in);
1948 		if (err < 0)
1949 			goto done;
1950 	} else if (rinfo->head->is_dentry && req->r_dentry) {
1951 		/* parent inode is not locked, be careful */
1952 		struct ceph_vino *ptvino = NULL;
1953 		dvino.ino = le64_to_cpu(rinfo->diri.in->ino);
1954 		dvino.snap = le64_to_cpu(rinfo->diri.in->snapid);
1955 		if (rinfo->head->is_target) {
1956 			tvino.ino = le64_to_cpu(rinfo->targeti.in->ino);
1957 			tvino.snap = le64_to_cpu(rinfo->targeti.in->snapid);
1958 			ptvino = &tvino;
1959 		}
1960 		update_dentry_lease_careful(req->r_dentry, rinfo->dlease,
1961 					    session, req->r_request_started,
1962 					    rinfo->dname, rinfo->dname_len,
1963 					    &dvino, ptvino);
1964 	}
1965 done:
1966 	/* Drop extra ref from ceph_get_reply_dir() if it returned a new inode */
1967 	if (unlikely(!IS_ERR_OR_NULL(parent_dir) && parent_dir != req->r_parent))
1968 		iput(parent_dir);
1969 	doutc(cl, "done err=%d\n", err);
1970 	return err;
1971 }
1972 
1973 /*
1974  * Prepopulate our cache with readdir results, leases, etc.
1975  */
1976 static int readdir_prepopulate_inodes_only(struct ceph_mds_request *req,
1977 					   struct ceph_mds_session *session)
1978 {
1979 	struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
1980 	struct ceph_client *cl = session->s_mdsc->fsc->client;
1981 	int i, err = 0;
1982 
1983 	for (i = 0; i < rinfo->dir_nr; i++) {
1984 		struct ceph_mds_reply_dir_entry *rde = rinfo->dir_entries + i;
1985 		struct ceph_vino vino;
1986 		struct inode *in;
1987 		int rc;
1988 
1989 		vino.ino = le64_to_cpu(rde->inode.in->ino);
1990 		vino.snap = le64_to_cpu(rde->inode.in->snapid);
1991 
1992 		in = ceph_get_inode(req->r_dentry->d_sb, vino, NULL);
1993 		if (IS_ERR(in)) {
1994 			err = PTR_ERR(in);
1995 			doutc(cl, "badness got %d\n", err);
1996 			continue;
1997 		}
1998 		rc = ceph_fill_inode(in, NULL, &rde->inode, NULL, session,
1999 				     -1, &req->r_caps_reservation);
2000 		if (rc < 0) {
2001 			pr_err_client(cl, "inode badness on %p got %d\n", in,
2002 				      rc);
2003 			err = rc;
2004 			if (inode_state_read_once(in) & I_NEW) {
2005 				ihold(in);
2006 				discard_new_inode(in);
2007 			}
2008 		} else if (inode_state_read_once(in) & I_NEW) {
2009 			unlock_new_inode(in);
2010 		}
2011 
2012 		iput(in);
2013 	}
2014 
2015 	return err;
2016 }
2017 
2018 void ceph_readdir_cache_release(struct ceph_readdir_cache_control *ctl)
2019 {
2020 	if (ctl->folio) {
2021 		folio_release_kmap(ctl->folio, ctl->dentries);
2022 		ctl->folio = NULL;
2023 	}
2024 }
2025 
2026 static int fill_readdir_cache(struct inode *dir, struct dentry *dn,
2027 			      struct ceph_readdir_cache_control *ctl,
2028 			      struct ceph_mds_request *req)
2029 {
2030 	struct ceph_client *cl = ceph_inode_to_client(dir);
2031 	struct ceph_inode_info *ci = ceph_inode(dir);
2032 	unsigned nsize = PAGE_SIZE / sizeof(struct dentry*);
2033 	unsigned idx = ctl->index % nsize;
2034 	pgoff_t pgoff = ctl->index / nsize;
2035 
2036 	if (!ctl->folio || pgoff != ctl->folio->index) {
2037 		ceph_readdir_cache_release(ctl);
2038 		fgf_t fgf = FGP_LOCK;
2039 
2040 		if (idx == 0)
2041 			fgf |= FGP_ACCESSED | FGP_CREAT;
2042 
2043 		ctl->folio = __filemap_get_folio(&dir->i_data, pgoff,
2044 				fgf, mapping_gfp_mask(&dir->i_data));
2045 		if (IS_ERR(ctl->folio)) {
2046 			int err = PTR_ERR(ctl->folio);
2047 
2048 			ctl->folio = NULL;
2049 			ctl->index = -1;
2050 			return idx == 0 ? err : 0;
2051 		}
2052 		/* reading/filling the cache are serialized by
2053 		 * i_rwsem, no need to use folio lock */
2054 		folio_unlock(ctl->folio);
2055 		ctl->dentries = kmap_local_folio(ctl->folio, 0);
2056 		if (idx == 0)
2057 			memset(ctl->dentries, 0, PAGE_SIZE);
2058 	}
2059 
2060 	if (req->r_dir_release_cnt == atomic64_read(&ci->i_release_count) &&
2061 	    req->r_dir_ordered_cnt == atomic64_read(&ci->i_ordered_count)) {
2062 		doutc(cl, "dn %p idx %d\n", dn, ctl->index);
2063 		ctl->dentries[idx] = dn;
2064 		ctl->index++;
2065 	} else {
2066 		doutc(cl, "disable readdir cache\n");
2067 		ctl->index = -1;
2068 	}
2069 	return 0;
2070 }
2071 
2072 int ceph_readdir_prepopulate(struct ceph_mds_request *req,
2073 			     struct ceph_mds_session *session)
2074 {
2075 	struct dentry *parent = req->r_dentry;
2076 	struct inode *inode = d_inode(parent);
2077 	struct ceph_inode_info *ci = ceph_inode(inode);
2078 	struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
2079 	struct ceph_client *cl = session->s_mdsc->fsc->client;
2080 	struct qstr dname;
2081 	struct dentry *dn;
2082 	struct inode *in;
2083 	int err = 0, skipped = 0, ret, i;
2084 	u32 frag = le32_to_cpu(req->r_args.readdir.frag);
2085 	u32 last_hash = 0;
2086 	u32 fpos_offset;
2087 	struct ceph_readdir_cache_control cache_ctl = {};
2088 
2089 	if (test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags))
2090 		return readdir_prepopulate_inodes_only(req, session);
2091 
2092 	if (rinfo->hash_order) {
2093 		if (req->r_path2) {
2094 			last_hash = ceph_str_hash(ci->i_dir_layout.dl_dir_hash,
2095 						  req->r_path2,
2096 						  strlen(req->r_path2));
2097 			last_hash = ceph_frag_value(last_hash);
2098 		} else if (rinfo->offset_hash) {
2099 			/* mds understands offset_hash */
2100 			WARN_ON_ONCE(req->r_readdir_offset != 2);
2101 			last_hash = le32_to_cpu(req->r_args.readdir.offset_hash);
2102 		}
2103 	}
2104 
2105 	if (rinfo->dir_dir &&
2106 	    le32_to_cpu(rinfo->dir_dir->frag) != frag) {
2107 		doutc(cl, "got new frag %x -> %x\n", frag,
2108 			    le32_to_cpu(rinfo->dir_dir->frag));
2109 		frag = le32_to_cpu(rinfo->dir_dir->frag);
2110 		if (!rinfo->hash_order)
2111 			req->r_readdir_offset = 2;
2112 	}
2113 
2114 	if (le32_to_cpu(rinfo->head->op) == CEPH_MDS_OP_LSSNAP) {
2115 		doutc(cl, "%d items under SNAPDIR dn %p\n",
2116 		      rinfo->dir_nr, parent);
2117 	} else {
2118 		doutc(cl, "%d items under dn %p\n", rinfo->dir_nr, parent);
2119 		if (rinfo->dir_dir)
2120 			ceph_fill_dirfrag(d_inode(parent), rinfo->dir_dir);
2121 
2122 		if (ceph_frag_is_leftmost(frag) &&
2123 		    req->r_readdir_offset == 2 &&
2124 		    !(rinfo->hash_order && last_hash)) {
2125 			/* note dir version at start of readdir so we can
2126 			 * tell if any dentries get dropped */
2127 			req->r_dir_release_cnt =
2128 				atomic64_read(&ci->i_release_count);
2129 			req->r_dir_ordered_cnt =
2130 				atomic64_read(&ci->i_ordered_count);
2131 			req->r_readdir_cache_idx = 0;
2132 		}
2133 	}
2134 
2135 	cache_ctl.index = req->r_readdir_cache_idx;
2136 	fpos_offset = req->r_readdir_offset;
2137 
2138 	/* FIXME: release caps/leases if error occurs */
2139 	for (i = 0; i < rinfo->dir_nr; i++) {
2140 		struct ceph_mds_reply_dir_entry *rde = rinfo->dir_entries + i;
2141 		struct ceph_vino tvino;
2142 
2143 		dname.name = rde->name;
2144 		dname.len = rde->name_len;
2145 		dname.hash = full_name_hash(parent, dname.name, dname.len);
2146 
2147 		tvino.ino = le64_to_cpu(rde->inode.in->ino);
2148 		tvino.snap = le64_to_cpu(rde->inode.in->snapid);
2149 
2150 		if (rinfo->hash_order) {
2151 			u32 hash = ceph_frag_value(rde->raw_hash);
2152 			if (hash != last_hash)
2153 				fpos_offset = 2;
2154 			last_hash = hash;
2155 			rde->offset = ceph_make_fpos(hash, fpos_offset++, true);
2156 		} else {
2157 			rde->offset = ceph_make_fpos(frag, fpos_offset++, false);
2158 		}
2159 
2160 retry_lookup:
2161 		dn = d_lookup(parent, &dname);
2162 		doutc(cl, "d_lookup on parent=%p name=%.*s got %p\n",
2163 		      parent, dname.len, dname.name, dn);
2164 
2165 		if (!dn) {
2166 			dn = d_alloc(parent, &dname);
2167 			doutc(cl, "d_alloc %p '%.*s' = %p\n", parent,
2168 			      dname.len, dname.name, dn);
2169 			if (!dn) {
2170 				doutc(cl, "d_alloc badness\n");
2171 				err = -ENOMEM;
2172 				goto out;
2173 			}
2174 			if (rde->is_nokey) {
2175 				spin_lock(&dn->d_lock);
2176 				dn->d_flags |= DCACHE_NOKEY_NAME;
2177 				spin_unlock(&dn->d_lock);
2178 			}
2179 		} else if (d_really_is_positive(dn) &&
2180 			   (ceph_ino(d_inode(dn)) != tvino.ino ||
2181 			    ceph_snap(d_inode(dn)) != tvino.snap)) {
2182 			struct ceph_dentry_info *di = ceph_dentry(dn);
2183 			doutc(cl, " dn %p points to wrong inode %p\n",
2184 			      dn, d_inode(dn));
2185 
2186 			spin_lock(&dn->d_lock);
2187 			if (di->offset > 0 &&
2188 			    di->lease_shared_gen ==
2189 			    atomic_read(&ci->i_shared_gen)) {
2190 				__ceph_dir_clear_ordered(ci);
2191 				di->offset = 0;
2192 			}
2193 			spin_unlock(&dn->d_lock);
2194 
2195 			d_delete(dn);
2196 			dput(dn);
2197 			goto retry_lookup;
2198 		}
2199 
2200 		/* inode */
2201 		if (d_really_is_positive(dn)) {
2202 			in = d_inode(dn);
2203 		} else {
2204 			in = ceph_get_inode(parent->d_sb, tvino, NULL);
2205 			if (IS_ERR(in)) {
2206 				doutc(cl, "new_inode badness\n");
2207 				d_drop(dn);
2208 				dput(dn);
2209 				err = PTR_ERR(in);
2210 				goto out;
2211 			}
2212 		}
2213 
2214 		ret = ceph_fill_inode(in, NULL, &rde->inode, NULL, session,
2215 				      -1, &req->r_caps_reservation);
2216 		if (ret < 0) {
2217 			pr_err_client(cl, "badness on %p %llx.%llx\n", in,
2218 				      ceph_vinop(in));
2219 			if (d_really_is_negative(dn)) {
2220 				if (inode_state_read_once(in) & I_NEW) {
2221 					ihold(in);
2222 					discard_new_inode(in);
2223 				}
2224 				iput(in);
2225 			}
2226 			d_drop(dn);
2227 			err = ret;
2228 			goto next_item;
2229 		}
2230 		if (inode_state_read_once(in) & I_NEW)
2231 			unlock_new_inode(in);
2232 
2233 		if (d_really_is_negative(dn)) {
2234 			if (ceph_security_xattr_deadlock(in)) {
2235 				doutc(cl, " skip splicing dn %p to inode %p"
2236 				      " (security xattr deadlock)\n", dn, in);
2237 				iput(in);
2238 				skipped++;
2239 				goto next_item;
2240 			}
2241 
2242 			err = splice_dentry(&dn, in);
2243 			if (err < 0)
2244 				goto next_item;
2245 		}
2246 
2247 		ceph_dentry(dn)->offset = rde->offset;
2248 
2249 		update_dentry_lease(d_inode(parent), dn,
2250 				    rde->lease, req->r_session,
2251 				    req->r_request_started);
2252 
2253 		if (err == 0 && skipped == 0 && cache_ctl.index >= 0) {
2254 			ret = fill_readdir_cache(d_inode(parent), dn,
2255 						 &cache_ctl, req);
2256 			if (ret < 0)
2257 				err = ret;
2258 		}
2259 next_item:
2260 		dput(dn);
2261 	}
2262 out:
2263 	if (err == 0 && skipped == 0) {
2264 		set_bit(CEPH_MDS_R_DID_PREPOPULATE, &req->r_req_flags);
2265 		req->r_readdir_cache_idx = cache_ctl.index;
2266 	}
2267 	ceph_readdir_cache_release(&cache_ctl);
2268 	doutc(cl, "done\n");
2269 	return err;
2270 }
2271 
2272 bool ceph_inode_set_size(struct inode *inode, loff_t size)
2273 {
2274 	struct ceph_client *cl = ceph_inode_to_client(inode);
2275 	struct ceph_inode_info *ci = ceph_inode(inode);
2276 	bool ret;
2277 
2278 	spin_lock(&ci->i_ceph_lock);
2279 	doutc(cl, "set_size %p %llu -> %llu\n", inode, i_size_read(inode), size);
2280 	i_size_write(inode, size);
2281 	ceph_fscache_update(inode);
2282 	inode->i_blocks = calc_inode_blocks(size);
2283 
2284 	ret = __ceph_should_report_size(ci);
2285 
2286 	spin_unlock(&ci->i_ceph_lock);
2287 
2288 	return ret;
2289 }
2290 
2291 void ceph_queue_inode_work(struct inode *inode, int work_bit)
2292 {
2293 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
2294 	struct ceph_client *cl = fsc->client;
2295 	struct ceph_inode_info *ci = ceph_inode(inode);
2296 	set_bit(work_bit, &ci->i_work_mask);
2297 
2298 	ihold(inode);
2299 	if (queue_work(fsc->inode_wq, &ci->i_work)) {
2300 		doutc(cl, "%p %llx.%llx mask=%lx\n", inode,
2301 		      ceph_vinop(inode), ci->i_work_mask);
2302 	} else {
2303 		doutc(cl, "%p %llx.%llx already queued, mask=%lx\n",
2304 		      inode, ceph_vinop(inode), ci->i_work_mask);
2305 		iput(inode);
2306 	}
2307 }
2308 
2309 static void ceph_do_invalidate_pages(struct inode *inode)
2310 {
2311 	struct ceph_client *cl = ceph_inode_to_client(inode);
2312 	struct ceph_inode_info *ci = ceph_inode(inode);
2313 	u32 orig_gen;
2314 	int check = 0;
2315 
2316 	ceph_fscache_invalidate(inode, false);
2317 
2318 	mutex_lock(&ci->i_truncate_mutex);
2319 
2320 	if (ceph_inode_is_shutdown(inode)) {
2321 		pr_warn_ratelimited_client(cl,
2322 			"%p %llx.%llx is shut down\n", inode,
2323 			ceph_vinop(inode));
2324 		mapping_set_error(inode->i_mapping, -EIO);
2325 		truncate_pagecache(inode, 0);
2326 		mutex_unlock(&ci->i_truncate_mutex);
2327 		goto out;
2328 	}
2329 
2330 	spin_lock(&ci->i_ceph_lock);
2331 	doutc(cl, "%p %llx.%llx gen %d revoking %d\n", inode,
2332 	      ceph_vinop(inode), ci->i_rdcache_gen, ci->i_rdcache_revoking);
2333 	if (ci->i_rdcache_revoking != ci->i_rdcache_gen) {
2334 		if (__ceph_caps_revoking_other(ci, NULL, CEPH_CAP_FILE_CACHE))
2335 			check = 1;
2336 		spin_unlock(&ci->i_ceph_lock);
2337 		mutex_unlock(&ci->i_truncate_mutex);
2338 		goto out;
2339 	}
2340 	orig_gen = ci->i_rdcache_gen;
2341 	spin_unlock(&ci->i_ceph_lock);
2342 
2343 	if (invalidate_inode_pages2(inode->i_mapping) < 0) {
2344 		pr_err_client(cl, "invalidate_inode_pages2 %llx.%llx failed\n",
2345 			      ceph_vinop(inode));
2346 	}
2347 
2348 	spin_lock(&ci->i_ceph_lock);
2349 	if (orig_gen == ci->i_rdcache_gen &&
2350 	    orig_gen == ci->i_rdcache_revoking) {
2351 		doutc(cl, "%p %llx.%llx gen %d successful\n", inode,
2352 		      ceph_vinop(inode), ci->i_rdcache_gen);
2353 		ci->i_rdcache_revoking--;
2354 		check = 1;
2355 	} else {
2356 		doutc(cl, "%p %llx.%llx gen %d raced, now %d revoking %d\n",
2357 		      inode, ceph_vinop(inode), orig_gen, ci->i_rdcache_gen,
2358 		      ci->i_rdcache_revoking);
2359 		if (__ceph_caps_revoking_other(ci, NULL, CEPH_CAP_FILE_CACHE))
2360 			check = 1;
2361 	}
2362 	spin_unlock(&ci->i_ceph_lock);
2363 	mutex_unlock(&ci->i_truncate_mutex);
2364 out:
2365 	if (check)
2366 		ceph_check_caps(ci, 0);
2367 }
2368 
2369 /*
2370  * Make sure any pending truncation is applied before doing anything
2371  * that may depend on it.
2372  */
2373 void __ceph_do_pending_vmtruncate(struct inode *inode)
2374 {
2375 	struct ceph_client *cl = ceph_inode_to_client(inode);
2376 	struct ceph_inode_info *ci = ceph_inode(inode);
2377 	u64 to;
2378 	bool shrank;
2379 	int wrbuffer_refs, finish = 0;
2380 
2381 	mutex_lock(&ci->i_truncate_mutex);
2382 retry:
2383 	spin_lock(&ci->i_ceph_lock);
2384 	if (!ci->i_truncate_pending) {
2385 		doutc(cl, "%p %llx.%llx none pending\n", inode,
2386 		      ceph_vinop(inode));
2387 		spin_unlock(&ci->i_ceph_lock);
2388 		mutex_unlock(&ci->i_truncate_mutex);
2389 		return;
2390 	}
2391 
2392 	/*
2393 	 * make sure any dirty snapped pages are flushed before we
2394 	 * possibly truncate them.. so write AND block!
2395 	 */
2396 	if (ci->i_wrbuffer_ref_head < ci->i_wrbuffer_ref) {
2397 		spin_unlock(&ci->i_ceph_lock);
2398 		doutc(cl, "%p %llx.%llx flushing snaps first\n", inode,
2399 		      ceph_vinop(inode));
2400 		filemap_write_and_wait_range(&inode->i_data, 0,
2401 					     inode->i_sb->s_maxbytes);
2402 		goto retry;
2403 	}
2404 
2405 	/* there should be no reader or writer */
2406 	WARN_ON_ONCE(ci->i_rd_ref || ci->i_wr_ref);
2407 
2408 	shrank = ci->i_truncate_shrank;
2409 	to = ci->i_truncate_pagecache_size;
2410 	wrbuffer_refs = ci->i_wrbuffer_ref;
2411 	doutc(cl, "%p %llx.%llx (%d) to %lld\n", inode, ceph_vinop(inode),
2412 	      ci->i_truncate_pending, to);
2413 	spin_unlock(&ci->i_ceph_lock);
2414 
2415 	ceph_fscache_resize(inode, to, shrank);
2416 	truncate_pagecache(inode, to);
2417 
2418 	spin_lock(&ci->i_ceph_lock);
2419 	if (to == ci->i_truncate_pagecache_size) {
2420 		ci->i_truncate_shrank = false;
2421 		ci->i_truncate_pending = false;
2422 		finish = 1;
2423 	}
2424 	spin_unlock(&ci->i_ceph_lock);
2425 	if (!finish)
2426 		goto retry;
2427 
2428 	mutex_unlock(&ci->i_truncate_mutex);
2429 
2430 	if (wrbuffer_refs == 0)
2431 		ceph_check_caps(ci, 0);
2432 
2433 	wake_up_all(&ci->i_cap_wq);
2434 }
2435 
2436 static void ceph_inode_work(struct work_struct *work)
2437 {
2438 	struct ceph_inode_info *ci = container_of(work, struct ceph_inode_info,
2439 						 i_work);
2440 	struct inode *inode = &ci->netfs.inode;
2441 	struct ceph_client *cl = ceph_inode_to_client(inode);
2442 
2443 	if (test_and_clear_bit(CEPH_I_WORK_WRITEBACK, &ci->i_work_mask)) {
2444 		doutc(cl, "writeback %p %llx.%llx\n", inode, ceph_vinop(inode));
2445 		filemap_fdatawrite(&inode->i_data);
2446 	}
2447 	if (test_and_clear_bit(CEPH_I_WORK_INVALIDATE_PAGES, &ci->i_work_mask))
2448 		ceph_do_invalidate_pages(inode);
2449 
2450 	if (test_and_clear_bit(CEPH_I_WORK_VMTRUNCATE, &ci->i_work_mask))
2451 		__ceph_do_pending_vmtruncate(inode);
2452 
2453 	if (test_and_clear_bit(CEPH_I_WORK_CHECK_CAPS, &ci->i_work_mask))
2454 		ceph_check_caps(ci, 0);
2455 
2456 	if (test_and_clear_bit(CEPH_I_WORK_FLUSH_SNAPS, &ci->i_work_mask))
2457 		ceph_flush_snaps(ci, NULL);
2458 
2459 	iput(inode);
2460 }
2461 
2462 static const char *ceph_encrypted_get_link(struct dentry *dentry,
2463 					   struct inode *inode,
2464 					   struct delayed_call *done)
2465 {
2466 	struct ceph_inode_info *ci = ceph_inode(inode);
2467 
2468 	if (!dentry)
2469 		return ERR_PTR(-ECHILD);
2470 
2471 	return fscrypt_get_symlink(inode, ci->i_symlink, i_size_read(inode),
2472 				   done);
2473 }
2474 
2475 static int ceph_encrypted_symlink_getattr(const struct mnt_idmap *idmap,
2476 					  const struct path *path,
2477 					  struct kstat *stat, u32 request_mask,
2478 					  unsigned int query_flags)
2479 {
2480 	int ret;
2481 
2482 	ret = ceph_getattr(idmap, path, stat, request_mask, query_flags);
2483 	if (ret)
2484 		return ret;
2485 	return fscrypt_symlink_getattr(path, stat);
2486 }
2487 
2488 /*
2489  * symlinks
2490  */
2491 static const struct inode_operations ceph_symlink_iops = {
2492 	.get_link = simple_get_link,
2493 	.setattr = ceph_setattr,
2494 	.getattr = ceph_getattr,
2495 	.listxattr = ceph_listxattr,
2496 };
2497 
2498 static const struct inode_operations ceph_encrypted_symlink_iops = {
2499 	.get_link = ceph_encrypted_get_link,
2500 	.setattr = ceph_setattr,
2501 	.getattr = ceph_encrypted_symlink_getattr,
2502 	.listxattr = ceph_listxattr,
2503 };
2504 
2505 /*
2506  * Transfer the encrypted last block to the MDS and the MDS
2507  * will help update it when truncating a smaller size.
2508  *
2509  * We don't support a PAGE_SIZE that is smaller than the
2510  * CEPH_FSCRYPT_BLOCK_SIZE.
2511  */
2512 static int fill_fscrypt_truncate(struct inode *inode,
2513 				 struct ceph_mds_request *req,
2514 				 struct iattr *attr)
2515 {
2516 	struct ceph_client *cl = ceph_inode_to_client(inode);
2517 	struct ceph_inode_info *ci = ceph_inode(inode);
2518 	int boff = attr->ia_size % CEPH_FSCRYPT_BLOCK_SIZE;
2519 	loff_t pos, orig_pos = round_down(attr->ia_size,
2520 					  CEPH_FSCRYPT_BLOCK_SIZE);
2521 	u64 block = orig_pos >> CEPH_FSCRYPT_BLOCK_SHIFT;
2522 	struct ceph_pagelist *pagelist = NULL;
2523 	struct kvec iov = {0};
2524 	struct iov_iter iter;
2525 	struct page *page = NULL;
2526 	struct ceph_fscrypt_truncate_size_header header;
2527 	int retry_op = 0;
2528 	int len = CEPH_FSCRYPT_BLOCK_SIZE;
2529 	loff_t i_size = i_size_read(inode);
2530 	int got, ret, issued;
2531 	u64 objver;
2532 
2533 	ret = __ceph_get_caps(inode, NULL, CEPH_CAP_FILE_RD, 0, -1, &got);
2534 	if (ret < 0)
2535 		return ret;
2536 
2537 	issued = __ceph_caps_issued(ci, NULL);
2538 
2539 	doutc(cl, "size %lld -> %lld got cap refs on %s, issued %s\n",
2540 	      i_size, attr->ia_size, ceph_cap_string(got),
2541 	      ceph_cap_string(issued));
2542 
2543 	/* Try to writeback the dirty pagecaches */
2544 	if (issued & (CEPH_CAP_FILE_BUFFER)) {
2545 		loff_t lend = orig_pos + CEPH_FSCRYPT_BLOCK_SIZE - 1;
2546 
2547 		ret = filemap_write_and_wait_range(inode->i_mapping,
2548 						   orig_pos, lend);
2549 		if (ret < 0)
2550 			goto out;
2551 	}
2552 
2553 	page = alloc_page(GFP_KERNEL);
2554 	if (page == NULL) {
2555 		ret = -ENOMEM;
2556 		goto out;
2557 	}
2558 
2559 	pagelist = ceph_pagelist_alloc(GFP_KERNEL);
2560 	if (!pagelist) {
2561 		ret = -ENOMEM;
2562 		goto out;
2563 	}
2564 
2565 	iov.iov_base = kmap_local_page(page);
2566 	iov.iov_len = len;
2567 	iov_iter_kvec(&iter, READ, &iov, 1, len);
2568 
2569 	pos = orig_pos;
2570 	ret = __ceph_sync_read(inode, &pos, &iter, &retry_op, &objver);
2571 	if (ret < 0)
2572 		goto out;
2573 
2574 	/* Insert the header first */
2575 	header.ver = 1;
2576 	header.compat = 1;
2577 	header.change_attr = cpu_to_le64(inode_peek_iversion_raw(inode));
2578 
2579 	/*
2580 	 * Always set the block_size to CEPH_FSCRYPT_BLOCK_SIZE,
2581 	 * because in MDS it may need this to do the truncate.
2582 	 */
2583 	header.block_size = cpu_to_le32(CEPH_FSCRYPT_BLOCK_SIZE);
2584 
2585 	/*
2586 	 * If we hit a hole here, we should just skip filling
2587 	 * the fscrypt for the request, because once the fscrypt
2588 	 * is enabled, the file will be split into many blocks
2589 	 * with the size of CEPH_FSCRYPT_BLOCK_SIZE, if there
2590 	 * has a hole, the hole size should be multiple of block
2591 	 * size.
2592 	 *
2593 	 * If the Rados object doesn't exist, it will be set to 0.
2594 	 */
2595 	if (!objver) {
2596 		doutc(cl, "hit hole, ppos %lld < size %lld\n", pos, i_size);
2597 
2598 		header.data_len = cpu_to_le32(8 + 8 + 4);
2599 		header.file_offset = 0;
2600 		ret = 0;
2601 	} else {
2602 		header.data_len = cpu_to_le32(8 + 8 + 4 + CEPH_FSCRYPT_BLOCK_SIZE);
2603 		header.file_offset = cpu_to_le64(orig_pos);
2604 
2605 		doutc(cl, "encrypt block boff/bsize %d/%lu\n", boff,
2606 		      CEPH_FSCRYPT_BLOCK_SIZE);
2607 
2608 		/* truncate and zero out the extra contents for the last block */
2609 		memset(iov.iov_base + boff, 0, PAGE_SIZE - boff);
2610 
2611 		/* encrypt the last block */
2612 		ret = ceph_fscrypt_encrypt_block_inplace(inode, page,
2613 						    CEPH_FSCRYPT_BLOCK_SIZE,
2614 						    0, block);
2615 		if (ret)
2616 			goto out;
2617 	}
2618 
2619 	/* Insert the header */
2620 	ret = ceph_pagelist_append(pagelist, &header, sizeof(header));
2621 	if (ret)
2622 		goto out;
2623 
2624 	if (header.block_size) {
2625 		/* Append the last block contents to pagelist */
2626 		ret = ceph_pagelist_append(pagelist, iov.iov_base,
2627 					   CEPH_FSCRYPT_BLOCK_SIZE);
2628 		if (ret)
2629 			goto out;
2630 	}
2631 	req->r_pagelist = pagelist;
2632 out:
2633 	doutc(cl, "%p %llx.%llx size dropping cap refs on %s\n", inode,
2634 	      ceph_vinop(inode), ceph_cap_string(got));
2635 	ceph_put_cap_refs(ci, got);
2636 	if (iov.iov_base)
2637 		kunmap_local(iov.iov_base);
2638 	if (page)
2639 		__free_pages(page, 0);
2640 	if (ret && pagelist)
2641 		ceph_pagelist_release(pagelist);
2642 	return ret;
2643 }
2644 
2645 int __ceph_setattr(const struct mnt_idmap *idmap, struct inode *inode,
2646 		   struct iattr *attr, struct ceph_iattr *cia)
2647 {
2648 	struct ceph_inode_info *ci = ceph_inode(inode);
2649 	unsigned int ia_valid = attr->ia_valid;
2650 	struct ceph_mds_request *req;
2651 	struct ceph_mds_client *mdsc = ceph_sb_to_fs_client(inode->i_sb)->mdsc;
2652 	struct ceph_client *cl = ceph_inode_to_client(inode);
2653 	struct ceph_cap_flush *prealloc_cf;
2654 	loff_t isize = i_size_read(inode);
2655 	int issued;
2656 	int release = 0, dirtied = 0;
2657 	int mask = 0;
2658 	int err = 0;
2659 	int inode_dirty_flags = 0;
2660 	bool lock_snap_rwsem = false;
2661 	bool fill_fscrypt;
2662 	int truncate_retry = 20; /* The RMW will take around 50ms */
2663 	struct dentry *dentry;
2664 	char *path;
2665 	bool do_sync = false;
2666 
2667 	dentry = d_find_alias(inode);
2668 	if (!dentry) {
2669 		do_sync = true;
2670 	} else {
2671 		struct ceph_path_info path_info = {0};
2672 		path = ceph_mdsc_build_path(mdsc, dentry, &path_info, 0);
2673 		if (IS_ERR(path)) {
2674 			do_sync = true;
2675 			err = 0;
2676 		} else {
2677 			err = ceph_mds_check_access(mdsc, path, MAY_WRITE);
2678 		}
2679 		ceph_mdsc_free_path_info(&path_info);
2680 		dput(dentry);
2681 
2682 		/* For none EACCES cases will let the MDS do the mds auth check */
2683 		if (err == -EACCES) {
2684 			return err;
2685 		} else if (err < 0) {
2686 			do_sync = true;
2687 			err = 0;
2688 		}
2689 	}
2690 
2691 retry:
2692 	prealloc_cf = ceph_alloc_cap_flush();
2693 	if (!prealloc_cf)
2694 		return -ENOMEM;
2695 
2696 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_SETATTR,
2697 				       USE_AUTH_MDS);
2698 	if (IS_ERR(req)) {
2699 		ceph_free_cap_flush(prealloc_cf);
2700 		return PTR_ERR(req);
2701 	}
2702 
2703 	fill_fscrypt = false;
2704 	spin_lock(&ci->i_ceph_lock);
2705 	issued = __ceph_caps_issued(ci, NULL);
2706 
2707 	if (!ci->i_head_snapc &&
2708 	    (issued & (CEPH_CAP_ANY_EXCL | CEPH_CAP_FILE_WR))) {
2709 		lock_snap_rwsem = true;
2710 		if (!down_read_trylock(&mdsc->snap_rwsem)) {
2711 			spin_unlock(&ci->i_ceph_lock);
2712 			down_read(&mdsc->snap_rwsem);
2713 			spin_lock(&ci->i_ceph_lock);
2714 			issued = __ceph_caps_issued(ci, NULL);
2715 		}
2716 	}
2717 
2718 	doutc(cl, "%p %llx.%llx issued %s\n", inode, ceph_vinop(inode),
2719 	      ceph_cap_string(issued));
2720 #if IS_ENABLED(CONFIG_FS_ENCRYPTION)
2721 	if (cia && cia->fscrypt_auth) {
2722 		u32 len = ceph_fscrypt_auth_len(cia->fscrypt_auth);
2723 
2724 		if (len > sizeof(*cia->fscrypt_auth)) {
2725 			err = -EINVAL;
2726 			spin_unlock(&ci->i_ceph_lock);
2727 			goto out;
2728 		}
2729 
2730 		doutc(cl, "%p %llx.%llx fscrypt_auth len %u to %u)\n", inode,
2731 		      ceph_vinop(inode), ci->fscrypt_auth_len, len);
2732 
2733 		/* It should never be re-set once set */
2734 		WARN_ON_ONCE(ci->fscrypt_auth);
2735 
2736 		if (!do_sync && (issued & CEPH_CAP_AUTH_EXCL)) {
2737 			dirtied |= CEPH_CAP_AUTH_EXCL;
2738 			kfree(ci->fscrypt_auth);
2739 			ci->fscrypt_auth = (u8 *)cia->fscrypt_auth;
2740 			ci->fscrypt_auth_len = len;
2741 		} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
2742 			   ci->fscrypt_auth_len != len ||
2743 			   memcmp(ci->fscrypt_auth, cia->fscrypt_auth, len)) {
2744 			req->r_fscrypt_auth = cia->fscrypt_auth;
2745 			mask |= CEPH_SETATTR_FSCRYPT_AUTH;
2746 			release |= CEPH_CAP_AUTH_SHARED;
2747 		}
2748 		cia->fscrypt_auth = NULL;
2749 	}
2750 #else
2751 	if (cia && cia->fscrypt_auth) {
2752 		err = -EINVAL;
2753 		spin_unlock(&ci->i_ceph_lock);
2754 		goto out;
2755 	}
2756 #endif /* CONFIG_FS_ENCRYPTION */
2757 
2758 	if (ia_valid & ATTR_UID) {
2759 		kuid_t fsuid = from_vfsuid(idmap, i_user_ns(inode), attr->ia_vfsuid);
2760 
2761 		doutc(cl, "%p %llx.%llx uid %d -> %d\n", inode,
2762 		      ceph_vinop(inode),
2763 		      from_kuid(&init_user_ns, inode->i_uid),
2764 		      from_kuid(&init_user_ns, attr->ia_uid));
2765 		if (!do_sync && (issued & CEPH_CAP_AUTH_EXCL)) {
2766 			inode->i_uid = fsuid;
2767 			dirtied |= CEPH_CAP_AUTH_EXCL;
2768 		} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
2769 			   !uid_eq(fsuid, inode->i_uid)) {
2770 			req->r_args.setattr.uid = cpu_to_le32(
2771 				from_kuid(&init_user_ns, fsuid));
2772 			mask |= CEPH_SETATTR_UID;
2773 			release |= CEPH_CAP_AUTH_SHARED;
2774 		}
2775 	}
2776 	if (ia_valid & ATTR_GID) {
2777 		kgid_t fsgid = from_vfsgid(idmap, i_user_ns(inode), attr->ia_vfsgid);
2778 
2779 		doutc(cl, "%p %llx.%llx gid %d -> %d\n", inode,
2780 		      ceph_vinop(inode),
2781 		      from_kgid(&init_user_ns, inode->i_gid),
2782 		      from_kgid(&init_user_ns, attr->ia_gid));
2783 		if (!do_sync && (issued & CEPH_CAP_AUTH_EXCL)) {
2784 			inode->i_gid = fsgid;
2785 			dirtied |= CEPH_CAP_AUTH_EXCL;
2786 		} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
2787 			   !gid_eq(fsgid, inode->i_gid)) {
2788 			req->r_args.setattr.gid = cpu_to_le32(
2789 				from_kgid(&init_user_ns, fsgid));
2790 			mask |= CEPH_SETATTR_GID;
2791 			release |= CEPH_CAP_AUTH_SHARED;
2792 		}
2793 	}
2794 	if (ia_valid & ATTR_MODE) {
2795 		doutc(cl, "%p %llx.%llx mode 0%o -> 0%o\n", inode,
2796 		      ceph_vinop(inode), inode->i_mode, attr->ia_mode);
2797 		if (!do_sync && (issued & CEPH_CAP_AUTH_EXCL)) {
2798 			inode->i_mode = attr->ia_mode;
2799 			dirtied |= CEPH_CAP_AUTH_EXCL;
2800 		} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
2801 			   attr->ia_mode != inode->i_mode) {
2802 			inode->i_mode = attr->ia_mode;
2803 			req->r_args.setattr.mode = cpu_to_le32(attr->ia_mode);
2804 			mask |= CEPH_SETATTR_MODE;
2805 			release |= CEPH_CAP_AUTH_SHARED;
2806 		}
2807 	}
2808 
2809 	if (ia_valid & ATTR_ATIME) {
2810 		struct timespec64 atime = inode_get_atime(inode);
2811 
2812 		doutc(cl, "%p %llx.%llx atime %ptSp -> %ptSp\n",
2813 		      inode, ceph_vinop(inode), &atime, &attr->ia_atime);
2814 		if (!do_sync && (issued & CEPH_CAP_FILE_EXCL)) {
2815 			ci->i_time_warp_seq++;
2816 			inode_set_atime_to_ts(inode, attr->ia_atime);
2817 			dirtied |= CEPH_CAP_FILE_EXCL;
2818 		} else if (!do_sync && (issued & CEPH_CAP_FILE_WR) &&
2819 			   timespec64_compare(&atime,
2820 					      &attr->ia_atime) < 0) {
2821 			inode_set_atime_to_ts(inode, attr->ia_atime);
2822 			dirtied |= CEPH_CAP_FILE_WR;
2823 		} else if ((issued & CEPH_CAP_FILE_SHARED) == 0 ||
2824 			   !timespec64_equal(&atime, &attr->ia_atime)) {
2825 			ceph_encode_timespec64(&req->r_args.setattr.atime,
2826 					       &attr->ia_atime);
2827 			mask |= CEPH_SETATTR_ATIME;
2828 			release |= CEPH_CAP_FILE_SHARED |
2829 				   CEPH_CAP_FILE_RD | CEPH_CAP_FILE_WR;
2830 		}
2831 	}
2832 	if (ia_valid & ATTR_SIZE) {
2833 		doutc(cl, "%p %llx.%llx size %lld -> %lld\n", inode,
2834 		      ceph_vinop(inode), isize, attr->ia_size);
2835 		/*
2836 		 * Only when the new size is smaller and not aligned to
2837 		 * CEPH_FSCRYPT_BLOCK_SIZE will the RMW is needed.
2838 		 */
2839 		if (IS_ENCRYPTED(inode) && attr->ia_size < isize &&
2840 		    (attr->ia_size % CEPH_FSCRYPT_BLOCK_SIZE)) {
2841 			mask |= CEPH_SETATTR_SIZE;
2842 			release |= CEPH_CAP_FILE_SHARED | CEPH_CAP_FILE_EXCL |
2843 				   CEPH_CAP_FILE_RD | CEPH_CAP_FILE_WR;
2844 			set_bit(CEPH_MDS_R_FSCRYPT_FILE, &req->r_req_flags);
2845 			mask |= CEPH_SETATTR_FSCRYPT_FILE;
2846 			req->r_args.setattr.size =
2847 				cpu_to_le64(round_up(attr->ia_size,
2848 						     CEPH_FSCRYPT_BLOCK_SIZE));
2849 			req->r_args.setattr.old_size =
2850 				cpu_to_le64(round_up(isize,
2851 						     CEPH_FSCRYPT_BLOCK_SIZE));
2852 			req->r_fscrypt_file = attr->ia_size;
2853 			fill_fscrypt = true;
2854 		} else if (!do_sync && (issued & CEPH_CAP_FILE_EXCL) && attr->ia_size >= isize) {
2855 			if (attr->ia_size > isize) {
2856 				i_size_write(inode, attr->ia_size);
2857 				inode->i_blocks = calc_inode_blocks(attr->ia_size);
2858 				ci->i_reported_size = attr->ia_size;
2859 				dirtied |= CEPH_CAP_FILE_EXCL;
2860 				ia_valid |= ATTR_MTIME;
2861 			}
2862 		} else if ((issued & CEPH_CAP_FILE_SHARED) == 0 ||
2863 			   attr->ia_size != isize) {
2864 			mask |= CEPH_SETATTR_SIZE;
2865 			release |= CEPH_CAP_FILE_SHARED | CEPH_CAP_FILE_EXCL |
2866 				   CEPH_CAP_FILE_RD | CEPH_CAP_FILE_WR;
2867 			if (IS_ENCRYPTED(inode) && attr->ia_size) {
2868 				set_bit(CEPH_MDS_R_FSCRYPT_FILE, &req->r_req_flags);
2869 				mask |= CEPH_SETATTR_FSCRYPT_FILE;
2870 				req->r_args.setattr.size =
2871 					cpu_to_le64(round_up(attr->ia_size,
2872 							     CEPH_FSCRYPT_BLOCK_SIZE));
2873 				req->r_args.setattr.old_size =
2874 					cpu_to_le64(round_up(isize,
2875 							     CEPH_FSCRYPT_BLOCK_SIZE));
2876 				req->r_fscrypt_file = attr->ia_size;
2877 			} else {
2878 				req->r_args.setattr.size = cpu_to_le64(attr->ia_size);
2879 				req->r_args.setattr.old_size = cpu_to_le64(isize);
2880 				req->r_fscrypt_file = 0;
2881 			}
2882 		}
2883 	}
2884 	if (ia_valid & ATTR_MTIME) {
2885 		struct timespec64 mtime = inode_get_mtime(inode);
2886 
2887 		doutc(cl, "%p %llx.%llx mtime %ptSp -> %ptSp\n",
2888 		      inode, ceph_vinop(inode), &mtime, &attr->ia_mtime);
2889 		if (!do_sync && (issued & CEPH_CAP_FILE_EXCL)) {
2890 			ci->i_time_warp_seq++;
2891 			inode_set_mtime_to_ts(inode, attr->ia_mtime);
2892 			dirtied |= CEPH_CAP_FILE_EXCL;
2893 		} else if (!do_sync && (issued & CEPH_CAP_FILE_WR) &&
2894 			   timespec64_compare(&mtime, &attr->ia_mtime) < 0) {
2895 			inode_set_mtime_to_ts(inode, attr->ia_mtime);
2896 			dirtied |= CEPH_CAP_FILE_WR;
2897 		} else if ((issued & CEPH_CAP_FILE_SHARED) == 0 ||
2898 			   !timespec64_equal(&mtime, &attr->ia_mtime)) {
2899 			ceph_encode_timespec64(&req->r_args.setattr.mtime,
2900 					       &attr->ia_mtime);
2901 			mask |= CEPH_SETATTR_MTIME;
2902 			release |= CEPH_CAP_FILE_SHARED |
2903 				   CEPH_CAP_FILE_RD | CEPH_CAP_FILE_WR;
2904 		}
2905 	}
2906 
2907 	/* these do nothing */
2908 	if (ia_valid & ATTR_CTIME) {
2909 		struct timespec64 ictime = inode_get_ctime(inode);
2910 		bool only = (ia_valid & (ATTR_SIZE|ATTR_MTIME|ATTR_ATIME|
2911 					 ATTR_MODE|ATTR_UID|ATTR_GID)) == 0;
2912 		doutc(cl, "%p %llx.%llx ctime %ptSp -> %ptSp (%s)\n",
2913 		      inode, ceph_vinop(inode), &ictime, &attr->ia_ctime,
2914 		      only ? "ctime only" : "ignored");
2915 		if (only) {
2916 			/*
2917 			 * if kernel wants to dirty ctime but nothing else,
2918 			 * we need to choose a cap to dirty under, or do
2919 			 * a almost-no-op setattr
2920 			 */
2921 			if (issued & CEPH_CAP_AUTH_EXCL)
2922 				dirtied |= CEPH_CAP_AUTH_EXCL;
2923 			else if (issued & CEPH_CAP_FILE_EXCL)
2924 				dirtied |= CEPH_CAP_FILE_EXCL;
2925 			else if (issued & CEPH_CAP_XATTR_EXCL)
2926 				dirtied |= CEPH_CAP_XATTR_EXCL;
2927 			else
2928 				mask |= CEPH_SETATTR_CTIME;
2929 		}
2930 	}
2931 	if (ia_valid & ATTR_FILE)
2932 		doutc(cl, "%p %llx.%llx ATTR_FILE ... hrm!\n", inode,
2933 		      ceph_vinop(inode));
2934 
2935 	if (dirtied) {
2936 		inode_dirty_flags = __ceph_mark_dirty_caps(ci, dirtied,
2937 							   &prealloc_cf);
2938 		inode_set_ctime_to_ts(inode, attr->ia_ctime);
2939 		inode_inc_iversion_raw(inode);
2940 	}
2941 
2942 	release &= issued;
2943 	spin_unlock(&ci->i_ceph_lock);
2944 	if (lock_snap_rwsem) {
2945 		up_read(&mdsc->snap_rwsem);
2946 		lock_snap_rwsem = false;
2947 	}
2948 
2949 	if (inode_dirty_flags)
2950 		__mark_inode_dirty(inode, inode_dirty_flags);
2951 
2952 	if (mask) {
2953 		req->r_inode = inode;
2954 		ihold(inode);
2955 		req->r_inode_drop = release;
2956 		req->r_args.setattr.mask = cpu_to_le32(mask);
2957 		req->r_num_caps = 1;
2958 		req->r_stamp = attr->ia_ctime;
2959 		if (fill_fscrypt) {
2960 			err = fill_fscrypt_truncate(inode, req, attr);
2961 			if (err)
2962 				goto out;
2963 		}
2964 
2965 		/*
2966 		 * The truncate request will return -EAGAIN when the
2967 		 * last block has been updated just before the MDS
2968 		 * successfully gets the xlock for the FILE lock. To
2969 		 * avoid corrupting the file contents we need to retry
2970 		 * it.
2971 		 */
2972 		err = ceph_mdsc_do_request(mdsc, NULL, req);
2973 		if (err == -EAGAIN && truncate_retry--) {
2974 			doutc(cl, "%p %llx.%llx result=%d (%s locally, %d remote), retry it!\n",
2975 			      inode, ceph_vinop(inode), err,
2976 			      ceph_cap_string(dirtied), mask);
2977 			ceph_mdsc_put_request(req);
2978 			ceph_free_cap_flush(prealloc_cf);
2979 			goto retry;
2980 		}
2981 	}
2982 out:
2983 	doutc(cl, "%p %llx.%llx result=%d (%s locally, %d remote)\n", inode,
2984 	      ceph_vinop(inode), err, ceph_cap_string(dirtied), mask);
2985 
2986 	ceph_mdsc_put_request(req);
2987 	ceph_free_cap_flush(prealloc_cf);
2988 
2989 	if (err >= 0 && (mask & CEPH_SETATTR_SIZE))
2990 		__ceph_do_pending_vmtruncate(inode);
2991 
2992 	return err;
2993 }
2994 
2995 /*
2996  * setattr
2997  */
2998 int ceph_setattr(const struct mnt_idmap *idmap, struct dentry *dentry,
2999 		 struct iattr *attr)
3000 {
3001 	struct inode *inode = d_inode(dentry);
3002 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
3003 	int err;
3004 
3005 	if (ceph_in_snap(inode))
3006 		return -EROFS;
3007 
3008 	if (ceph_inode_is_shutdown(inode))
3009 		return -ESTALE;
3010 
3011 	err = fscrypt_prepare_setattr(dentry, attr);
3012 	if (err)
3013 		return err;
3014 
3015 	err = setattr_prepare(idmap, dentry, attr);
3016 	if (err != 0)
3017 		return err;
3018 
3019 	if ((attr->ia_valid & ATTR_SIZE) &&
3020 	    attr->ia_size > max(i_size_read(inode), fsc->max_file_size))
3021 		return -EFBIG;
3022 
3023 	if ((attr->ia_valid & ATTR_SIZE) &&
3024 	    ceph_quota_is_max_bytes_exceeded(inode, attr->ia_size))
3025 		return -EDQUOT;
3026 
3027 	err = __ceph_setattr(idmap, inode, attr, NULL);
3028 
3029 	if (err >= 0 && (attr->ia_valid & ATTR_MODE))
3030 		err = posix_acl_chmod(idmap, dentry, attr->ia_mode);
3031 
3032 	return err;
3033 }
3034 
3035 int ceph_try_to_choose_auth_mds(struct inode *inode, int mask)
3036 {
3037 	int issued = ceph_caps_issued(ceph_inode(inode));
3038 
3039 	/*
3040 	 * If any 'x' caps is issued we can just choose the auth MDS
3041 	 * instead of the random replica MDSes. Because only when the
3042 	 * Locker is in LOCK_EXEC state will the loner client could
3043 	 * get the 'x' caps. And if we send the getattr requests to
3044 	 * any replica MDS it must auth pin and tries to rdlock from
3045 	 * the auth MDS, and then the auth MDS need to do the Locker
3046 	 * state transition to LOCK_SYNC. And after that the lock state
3047 	 * will change back.
3048 	 *
3049 	 * This cost much when doing the Locker state transition and
3050 	 * usually will need to revoke caps from clients.
3051 	 *
3052 	 * And for the 'Xs' caps for getxattr we will also choose the
3053 	 * auth MDS, because the MDS side code is buggy due to setxattr
3054 	 * won't notify the replica MDSes when the values changed and
3055 	 * the replica MDS will return the old values. Though we will
3056 	 * fix it in MDS code, but this still makes sense for old ceph.
3057 	 */
3058 	if (((mask & CEPH_CAP_ANY_SHARED) && (issued & CEPH_CAP_ANY_EXCL))
3059 	    || (mask & (CEPH_STAT_RSTAT | CEPH_STAT_CAP_XATTR)))
3060 		return USE_AUTH_MDS;
3061 	else
3062 		return USE_ANY_MDS;
3063 }
3064 
3065 /*
3066  * Verify that we have a lease on the given mask.  If not,
3067  * do a getattr against an mds.
3068  */
3069 int __ceph_do_getattr(struct inode *inode, struct folio *locked_folio,
3070 		      int mask, bool force)
3071 {
3072 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(inode->i_sb);
3073 	struct ceph_client *cl = fsc->client;
3074 	struct ceph_mds_client *mdsc = fsc->mdsc;
3075 	struct ceph_mds_request *req;
3076 	int mode;
3077 	int err;
3078 
3079 	if (ceph_snap(inode) == CEPH_SNAPDIR) {
3080 		doutc(cl, "inode %p %llx.%llx SNAPDIR\n", inode,
3081 		      ceph_vinop(inode));
3082 		return 0;
3083 	}
3084 
3085 	doutc(cl, "inode %p %llx.%llx mask %s mode 0%o\n", inode,
3086 	      ceph_vinop(inode), ceph_cap_string(mask), inode->i_mode);
3087 	if (!force && ceph_caps_issued_mask_metric(ceph_inode(inode), mask, 1))
3088 			return 0;
3089 
3090 	mode = ceph_try_to_choose_auth_mds(inode, mask);
3091 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_GETATTR, mode);
3092 	if (IS_ERR(req))
3093 		return PTR_ERR(req);
3094 	req->r_inode = inode;
3095 	ihold(inode);
3096 	req->r_num_caps = 1;
3097 	req->r_args.getattr.mask = cpu_to_le32(mask);
3098 	req->r_locked_folio = locked_folio;
3099 	err = ceph_mdsc_do_request(mdsc, NULL, req);
3100 	if (locked_folio && err == 0) {
3101 		u64 inline_version = req->r_reply_info.targeti.inline_version;
3102 		if (inline_version == 0) {
3103 			/* the reply is supposed to contain inline data */
3104 			err = -EINVAL;
3105 		} else if (inline_version == CEPH_INLINE_NONE ||
3106 			   inline_version == 1) {
3107 			err = -ENODATA;
3108 		} else {
3109 			err = req->r_reply_info.targeti.inline_len;
3110 		}
3111 	}
3112 	ceph_mdsc_put_request(req);
3113 	doutc(cl, "result=%d\n", err);
3114 	return err;
3115 }
3116 
3117 int ceph_do_getvxattr(struct inode *inode, const char *name, void *value,
3118 		      size_t size)
3119 {
3120 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(inode->i_sb);
3121 	struct ceph_client *cl = fsc->client;
3122 	struct ceph_mds_client *mdsc = fsc->mdsc;
3123 	struct ceph_mds_request *req;
3124 	int mode = USE_AUTH_MDS;
3125 	int err;
3126 	char *xattr_value;
3127 	size_t xattr_value_len;
3128 
3129 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_GETVXATTR, mode);
3130 	if (IS_ERR(req)) {
3131 		err = -ENOMEM;
3132 		goto out;
3133 	}
3134 
3135 	req->r_feature_needed = CEPHFS_FEATURE_OP_GETVXATTR;
3136 	req->r_path2 = kstrdup(name, GFP_NOFS);
3137 	if (!req->r_path2) {
3138 		err = -ENOMEM;
3139 		goto put;
3140 	}
3141 
3142 	ihold(inode);
3143 	req->r_inode = inode;
3144 	err = ceph_mdsc_do_request(mdsc, NULL, req);
3145 	if (err < 0)
3146 		goto put;
3147 
3148 	xattr_value = req->r_reply_info.xattr_info.xattr_value;
3149 	xattr_value_len = req->r_reply_info.xattr_info.xattr_value_len;
3150 
3151 	doutc(cl, "xattr_value_len:%zu, size:%zu\n", xattr_value_len, size);
3152 
3153 	err = (int)xattr_value_len;
3154 	if (size == 0)
3155 		goto put;
3156 
3157 	if (xattr_value_len > size) {
3158 		err = -ERANGE;
3159 		goto put;
3160 	}
3161 
3162 	memcpy(value, xattr_value, xattr_value_len);
3163 put:
3164 	ceph_mdsc_put_request(req);
3165 out:
3166 	doutc(cl, "result=%d\n", err);
3167 	return err;
3168 }
3169 
3170 
3171 /*
3172  * Check inode permissions.  We verify we have a valid value for
3173  * the AUTH cap, then call the generic handler.
3174  */
3175 int ceph_permission(const struct mnt_idmap *idmap, struct inode *inode,
3176 		    int mask)
3177 {
3178 	int err;
3179 
3180 	if (mask & MAY_NOT_BLOCK)
3181 		return -ECHILD;
3182 
3183 	err = ceph_do_getattr(inode, CEPH_CAP_AUTH_SHARED, false);
3184 
3185 	if (!err)
3186 		err = generic_permission(idmap, inode, mask);
3187 	return err;
3188 }
3189 
3190 /* Craft a mask of needed caps given a set of requested statx attrs. */
3191 static int statx_to_caps(u32 want, umode_t mode)
3192 {
3193 	int mask = 0;
3194 
3195 	if (want & (STATX_MODE|STATX_UID|STATX_GID|STATX_CTIME|STATX_BTIME|STATX_CHANGE_COOKIE))
3196 		mask |= CEPH_CAP_AUTH_SHARED;
3197 
3198 	if (want & (STATX_NLINK|STATX_CTIME|STATX_CHANGE_COOKIE)) {
3199 		/*
3200 		 * The link count for directories depends on inode->i_subdirs,
3201 		 * and that is only updated when Fs caps are held.
3202 		 */
3203 		if (S_ISDIR(mode))
3204 			mask |= CEPH_CAP_FILE_SHARED;
3205 		else
3206 			mask |= CEPH_CAP_LINK_SHARED;
3207 	}
3208 
3209 	if (want & (STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_SIZE|STATX_BLOCKS|STATX_CHANGE_COOKIE))
3210 		mask |= CEPH_CAP_FILE_SHARED;
3211 
3212 	if (want & (STATX_CTIME|STATX_CHANGE_COOKIE))
3213 		mask |= CEPH_CAP_XATTR_SHARED;
3214 
3215 	return mask;
3216 }
3217 
3218 /*
3219  * Get all the attributes. If we have sufficient caps for the requested attrs,
3220  * then we can avoid talking to the MDS at all.
3221  */
3222 int ceph_getattr(const struct mnt_idmap *idmap, const struct path *path,
3223 		 struct kstat *stat, u32 request_mask, unsigned int flags)
3224 {
3225 	struct inode *inode = d_inode(path->dentry);
3226 	struct super_block *sb = inode->i_sb;
3227 	struct ceph_inode_info *ci = ceph_inode(inode);
3228 	u32 valid_mask = STATX_BASIC_STATS;
3229 	int err = 0;
3230 
3231 	if (ceph_inode_is_shutdown(inode))
3232 		return -ESTALE;
3233 
3234 	/* Skip the getattr altogether if we're asked not to sync */
3235 	if ((flags & AT_STATX_SYNC_TYPE) != AT_STATX_DONT_SYNC) {
3236 		err = ceph_do_getattr(inode,
3237 				statx_to_caps(request_mask, inode->i_mode),
3238 				flags & AT_STATX_FORCE_SYNC);
3239 		if (err)
3240 			return err;
3241 	}
3242 
3243 	generic_fillattr(idmap, request_mask, inode, stat);
3244 	stat->ino = ceph_present_inode(inode);
3245 
3246 	/*
3247 	 * btime on newly-allocated inodes is 0, so if this is still set to
3248 	 * that, then assume that it's not valid.
3249 	 */
3250 	if (ci->i_btime.tv_sec || ci->i_btime.tv_nsec) {
3251 		stat->btime = ci->i_btime;
3252 		valid_mask |= STATX_BTIME;
3253 	}
3254 
3255 	if (request_mask & STATX_CHANGE_COOKIE) {
3256 		stat->change_cookie = inode_peek_iversion_raw(inode);
3257 		valid_mask |= STATX_CHANGE_COOKIE;
3258 	}
3259 
3260 	if (!ceph_in_snap(inode))
3261 		stat->dev = sb->s_dev;
3262 	else
3263 		stat->dev = ci->i_snapid_map ? ci->i_snapid_map->dev : 0;
3264 
3265 	if (S_ISDIR(inode->i_mode)) {
3266 		if (ceph_test_mount_opt(ceph_sb_to_fs_client(sb), RBYTES)) {
3267 			stat->size = ci->i_rbytes;
3268 		} else if (ceph_snap(inode) == CEPH_SNAPDIR) {
3269 			struct ceph_inode_info *pci;
3270 			struct ceph_snap_realm *realm;
3271 			struct inode *parent;
3272 
3273 			parent = ceph_lookup_inode(sb, ceph_ino(inode));
3274 			if (IS_ERR(parent))
3275 				return PTR_ERR(parent);
3276 
3277 			pci = ceph_inode(parent);
3278 			spin_lock(&pci->i_ceph_lock);
3279 			realm = pci->i_snap_realm;
3280 			if (realm)
3281 				stat->size = realm->num_snaps;
3282 			else
3283 				stat->size = 0;
3284 			spin_unlock(&pci->i_ceph_lock);
3285 			iput(parent);
3286 		} else {
3287 			stat->size = ci->i_files + ci->i_subdirs;
3288 		}
3289 		stat->blocks = 0;
3290 		stat->blksize = 65536;
3291 		/*
3292 		 * Some applications rely on the number of st_nlink
3293 		 * value on directories to be either 0 (if unlinked)
3294 		 * or 2 + number of subdirectories.
3295 		 */
3296 		if (stat->nlink == 1)
3297 			/* '.' + '..' + subdirs */
3298 			stat->nlink = 1 + 1 + ci->i_subdirs;
3299 	}
3300 
3301 	stat->attributes |= STATX_ATTR_CHANGE_MONOTONIC;
3302 	if (IS_ENCRYPTED(inode))
3303 		stat->attributes |= STATX_ATTR_ENCRYPTED;
3304 	stat->attributes_mask |= (STATX_ATTR_CHANGE_MONOTONIC |
3305 				  STATX_ATTR_ENCRYPTED);
3306 
3307 	stat->result_mask = request_mask & valid_mask;
3308 	return err;
3309 }
3310 
3311 void ceph_inode_shutdown(struct inode *inode)
3312 {
3313 	struct ceph_inode_info *ci = ceph_inode(inode);
3314 	struct rb_node *p;
3315 	int iputs = 0;
3316 	bool invalidate = false;
3317 
3318 	spin_lock(&ci->i_ceph_lock);
3319 	set_bit(CEPH_I_SHUTDOWN_BIT, &ci->i_ceph_flags);
3320 	p = rb_first(&ci->i_caps);
3321 	while (p) {
3322 		struct ceph_cap *cap = rb_entry(p, struct ceph_cap, ci_node);
3323 
3324 		p = rb_next(p);
3325 		iputs += ceph_purge_inode_cap(inode, cap, &invalidate);
3326 	}
3327 	spin_unlock(&ci->i_ceph_lock);
3328 
3329 	/*
3330 	 * The caps are gone now, so wake up anyone waiting for them -- they
3331 	 * are never coming back and the waiters need to notice the shutdown
3332 	 * instead.  remove_session_caps_cb() does the same after purging.
3333 	 */
3334 	wake_up_all(&ci->i_cap_wq);
3335 
3336 	if (invalidate)
3337 		ceph_queue_invalidate(inode);
3338 	while (iputs--)
3339 		iput(inode);
3340 }
3341