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