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