xref: /linux/fs/ceph/dir.c (revision 8fe8e62f432f0a7a0292a328a73c6912b9a2b73b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 
4 #include <linux/spinlock.h>
5 #include <linux/namei.h>
6 #include <linux/slab.h>
7 #include <linux/sched.h>
8 #include <linux/xattr.h>
9 
10 #include "super.h"
11 #include "mds_client.h"
12 #include "crypto.h"
13 
14 /*
15  * Directory operations: readdir, lookup, create, link, unlink,
16  * rename, etc.
17  */
18 
19 /*
20  * Ceph MDS operations are specified in terms of a base ino and
21  * relative path.  Thus, the client can specify an operation on a
22  * specific inode (e.g., a getattr due to fstat(2)), or as a path
23  * relative to, say, the root directory.
24  *
25  * Normally, we limit ourselves to strict inode ops (no path component)
26  * or dentry operations (a single path component relative to an ino).  The
27  * exception to this is open_root_dentry(), which will open the mount
28  * point by name.
29  */
30 
31 const struct dentry_operations ceph_dentry_ops;
32 
33 static bool __dentry_lease_is_valid(struct ceph_dentry_info *di);
34 static int __dir_lease_try_check(const struct dentry *dentry);
35 
36 /*
37  * Initialize ceph dentry state.
38  */
39 static int ceph_d_init(struct dentry *dentry)
40 {
41 	struct ceph_dentry_info *di;
42 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dentry->d_sb);
43 
44 	di = kmem_cache_zalloc(ceph_dentry_cachep, GFP_KERNEL);
45 	if (!di)
46 		return -ENOMEM;          /* oh well */
47 
48 	di->dentry = dentry;
49 	di->lease_session = NULL;
50 	di->time = jiffies;
51 	dentry->d_fsdata = di;
52 	INIT_LIST_HEAD(&di->lease_list);
53 
54 	atomic64_inc(&mdsc->metric.total_dentries);
55 
56 	return 0;
57 }
58 
59 /*
60  * for f_pos for readdir:
61  * - hash order:
62  *	(0xff << 52) | ((24 bits hash) << 28) |
63  *	(the nth entry has hash collision);
64  * - frag+name order;
65  *	((frag value) << 28) | (the nth entry in frag);
66  */
67 #define OFFSET_BITS	28
68 #define OFFSET_MASK	((1 << OFFSET_BITS) - 1)
69 #define HASH_ORDER	(0xffull << (OFFSET_BITS + 24))
70 loff_t ceph_make_fpos(unsigned high, unsigned off, bool hash_order)
71 {
72 	loff_t fpos = ((loff_t)high << 28) | (loff_t)off;
73 	if (hash_order)
74 		fpos |= HASH_ORDER;
75 	return fpos;
76 }
77 
78 static bool is_hash_order(loff_t p)
79 {
80 	return (p & HASH_ORDER) == HASH_ORDER;
81 }
82 
83 static unsigned fpos_frag(loff_t p)
84 {
85 	return p >> OFFSET_BITS;
86 }
87 
88 static unsigned fpos_hash(loff_t p)
89 {
90 	return ceph_frag_value(fpos_frag(p));
91 }
92 
93 static unsigned fpos_off(loff_t p)
94 {
95 	return p & OFFSET_MASK;
96 }
97 
98 static int fpos_cmp(loff_t l, loff_t r)
99 {
100 	int v = ceph_frag_compare(fpos_frag(l), fpos_frag(r));
101 	if (v)
102 		return v;
103 	return (int)(fpos_off(l) - fpos_off(r));
104 }
105 
106 /*
107  * make note of the last dentry we read, so we can
108  * continue at the same lexicographical point,
109  * regardless of what dir changes take place on the
110  * server.
111  */
112 static int note_last_dentry(struct ceph_fs_client *fsc,
113 			    struct ceph_dir_file_info *dfi,
114 			    const char *name,
115 		            int len, unsigned next_offset)
116 {
117 	char *buf = kmalloc(len+1, GFP_KERNEL);
118 	if (!buf)
119 		return -ENOMEM;
120 	kfree(dfi->last_name);
121 	dfi->last_name = buf;
122 	memcpy(dfi->last_name, name, len);
123 	dfi->last_name[len] = 0;
124 	dfi->next_offset = next_offset;
125 	doutc(fsc->client, "'%s'\n", dfi->last_name);
126 	return 0;
127 }
128 
129 
130 static struct dentry *
131 __dcache_find_get_entry(struct dentry *parent, u64 idx,
132 			struct ceph_readdir_cache_control *cache_ctl)
133 {
134 	struct inode *dir = d_inode(parent);
135 	struct ceph_client *cl = ceph_inode_to_client(dir);
136 	struct dentry *dentry;
137 	unsigned idx_mask = (PAGE_SIZE / sizeof(struct dentry *)) - 1;
138 	loff_t ptr_pos = idx * sizeof(struct dentry *);
139 	pgoff_t ptr_pgoff = ptr_pos >> PAGE_SHIFT;
140 
141 	if (ptr_pos >= i_size_read(dir))
142 		return NULL;
143 
144 	if (!cache_ctl->folio || ptr_pgoff != cache_ctl->folio->index) {
145 		ceph_readdir_cache_release(cache_ctl);
146 		cache_ctl->folio = filemap_lock_folio(&dir->i_data, ptr_pgoff);
147 		if (IS_ERR(cache_ctl->folio)) {
148 			cache_ctl->folio = NULL;
149 			doutc(cl, " folio %lu not found\n", ptr_pgoff);
150 			return ERR_PTR(-EAGAIN);
151 		}
152 		/* reading/filling the cache are serialized by
153 		   i_rwsem, no need to use folio lock */
154 		folio_unlock(cache_ctl->folio);
155 		cache_ctl->dentries = kmap_local_folio(cache_ctl->folio, 0);
156 	}
157 
158 	cache_ctl->index = idx & idx_mask;
159 
160 	rcu_read_lock();
161 	spin_lock(&parent->d_lock);
162 	/* check i_size again here, because empty directory can be
163 	 * marked as complete while not holding the i_rwsem. */
164 	if (ceph_dir_is_complete_ordered(dir) && ptr_pos < i_size_read(dir))
165 		dentry = cache_ctl->dentries[cache_ctl->index];
166 	else
167 		dentry = NULL;
168 	spin_unlock(&parent->d_lock);
169 	if (dentry && !lockref_get_not_dead(&dentry->d_lockref))
170 		dentry = NULL;
171 	rcu_read_unlock();
172 	return dentry ? : ERR_PTR(-EAGAIN);
173 }
174 
175 /*
176  * When possible, we try to satisfy a readdir by peeking at the
177  * dcache.  We make this work by carefully ordering dentries on
178  * d_children when we initially get results back from the MDS, and
179  * falling back to a "normal" sync readdir if any dentries in the dir
180  * are dropped.
181  *
182  * Complete dir indicates that we have all dentries in the dir.  It is
183  * defined IFF we hold CEPH_CAP_FILE_SHARED (which will be revoked by
184  * the MDS if/when the directory is modified).
185  */
186 static int __dcache_readdir(struct file *file,  struct dir_context *ctx,
187 			    int shared_gen)
188 {
189 	struct ceph_dir_file_info *dfi = file->private_data;
190 	struct dentry *parent = file->f_path.dentry;
191 	struct inode *dir = d_inode(parent);
192 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(dir);
193 	struct ceph_client *cl = ceph_inode_to_client(dir);
194 	struct dentry *dentry, *last = NULL;
195 	struct ceph_dentry_info *di;
196 	struct ceph_readdir_cache_control cache_ctl = {};
197 	u64 idx = 0;
198 	int err = 0;
199 
200 	doutc(cl, "%p %llx.%llx v%u at %llx\n", dir, ceph_vinop(dir),
201 	      (unsigned)shared_gen, ctx->pos);
202 
203 	/* search start position */
204 	if (ctx->pos > 2) {
205 		u64 count = div_u64(i_size_read(dir), sizeof(struct dentry *));
206 		while (count > 0) {
207 			u64 step = count >> 1;
208 			dentry = __dcache_find_get_entry(parent, idx + step,
209 							 &cache_ctl);
210 			if (!dentry) {
211 				/* use linear search */
212 				idx = 0;
213 				break;
214 			}
215 			if (IS_ERR(dentry)) {
216 				err = PTR_ERR(dentry);
217 				goto out;
218 			}
219 			di = ceph_dentry(dentry);
220 			spin_lock(&dentry->d_lock);
221 			if (fpos_cmp(di->offset, ctx->pos) < 0) {
222 				idx += step + 1;
223 				count -= step + 1;
224 			} else {
225 				count = step;
226 			}
227 			spin_unlock(&dentry->d_lock);
228 			dput(dentry);
229 		}
230 
231 		doutc(cl, "%p %llx.%llx cache idx %llu\n", dir,
232 		      ceph_vinop(dir), idx);
233 	}
234 
235 
236 	for (;;) {
237 		bool emit_dentry = false;
238 		dentry = __dcache_find_get_entry(parent, idx++, &cache_ctl);
239 		if (!dentry) {
240 			dfi->file_info.flags |= CEPH_F_ATEND;
241 			err = 0;
242 			break;
243 		}
244 		if (IS_ERR(dentry)) {
245 			err = PTR_ERR(dentry);
246 			goto out;
247 		}
248 
249 		spin_lock(&dentry->d_lock);
250 		di = ceph_dentry(dentry);
251 		if (d_unhashed(dentry) ||
252 		    d_really_is_negative(dentry) ||
253 		    di->lease_shared_gen != shared_gen ||
254 		    ((dentry->d_flags & DCACHE_NOKEY_NAME) &&
255 		     fscrypt_has_encryption_key(dir))) {
256 			spin_unlock(&dentry->d_lock);
257 			dput(dentry);
258 			err = -EAGAIN;
259 			goto out;
260 		}
261 		if (fpos_cmp(ctx->pos, di->offset) <= 0) {
262 			__ceph_dentry_dir_lease_touch(di);
263 			emit_dentry = true;
264 		}
265 		spin_unlock(&dentry->d_lock);
266 
267 		if (emit_dentry) {
268 			doutc(cl, " %llx dentry %p %pd %p\n", di->offset,
269 			      dentry, dentry, d_inode(dentry));
270 			ctx->pos = di->offset;
271 			if (!dir_emit(ctx, dentry->d_name.name,
272 				      dentry->d_name.len, ceph_present_inode(d_inode(dentry)),
273 				      d_inode(dentry)->i_mode >> 12)) {
274 				dput(dentry);
275 				err = 0;
276 				break;
277 			}
278 			ctx->pos++;
279 
280 			if (last)
281 				dput(last);
282 			last = dentry;
283 		} else {
284 			dput(dentry);
285 		}
286 	}
287 out:
288 	ceph_readdir_cache_release(&cache_ctl);
289 	if (last) {
290 		int ret;
291 		di = ceph_dentry(last);
292 		ret = note_last_dentry(fsc, dfi, last->d_name.name,
293 				       last->d_name.len,
294 				       fpos_off(di->offset) + 1);
295 		if (ret < 0)
296 			err = ret;
297 		dput(last);
298 		/* last_name no longer match cache index */
299 		if (dfi->readdir_cache_idx >= 0) {
300 			dfi->readdir_cache_idx = -1;
301 			dfi->dir_release_count = 0;
302 		}
303 	}
304 	return err;
305 }
306 
307 static bool need_send_readdir(struct ceph_dir_file_info *dfi, loff_t pos)
308 {
309 	if (!dfi->last_readdir)
310 		return true;
311 	if (is_hash_order(pos))
312 		return !ceph_frag_contains_value(dfi->frag, fpos_hash(pos));
313 	else
314 		return dfi->frag != fpos_frag(pos);
315 }
316 
317 static int ceph_readdir(struct file *file, struct dir_context *ctx)
318 {
319 	struct ceph_dir_file_info *dfi = file->private_data;
320 	struct inode *inode = file_inode(file);
321 	struct ceph_inode_info *ci = ceph_inode(inode);
322 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
323 	struct ceph_mds_client *mdsc = fsc->mdsc;
324 	struct ceph_client *cl = fsc->client;
325 	int i;
326 	int err;
327 	unsigned frag = -1;
328 	struct ceph_mds_reply_info_parsed *rinfo;
329 
330 	doutc(cl, "%p %llx.%llx file %p pos %llx\n", inode,
331 	      ceph_vinop(inode), file, ctx->pos);
332 	if (dfi->file_info.flags & CEPH_F_ATEND)
333 		return 0;
334 
335 	/* always start with . and .. */
336 	if (ctx->pos == 0) {
337 		doutc(cl, "%p %llx.%llx off 0 -> '.'\n", inode,
338 		      ceph_vinop(inode));
339 		if (!dir_emit(ctx, ".", 1, ceph_present_inode(inode),
340 			    inode->i_mode >> 12))
341 			return 0;
342 		ctx->pos = 1;
343 	}
344 	if (ctx->pos == 1) {
345 		u64 ino;
346 		struct dentry *dentry = file->f_path.dentry;
347 
348 		spin_lock(&dentry->d_lock);
349 		ino = ceph_present_inode(dentry->d_parent->d_inode);
350 		spin_unlock(&dentry->d_lock);
351 
352 		doutc(cl, "%p %llx.%llx off 1 -> '..'\n", inode,
353 		      ceph_vinop(inode));
354 		if (!dir_emit(ctx, "..", 2, ino, inode->i_mode >> 12))
355 			return 0;
356 		ctx->pos = 2;
357 	}
358 
359 	err = ceph_fscrypt_prepare_readdir(inode);
360 	if (err < 0)
361 		return err;
362 
363 	spin_lock(&ci->i_ceph_lock);
364 	/* request Fx cap. if have Fx, we don't need to release Fs cap
365 	 * for later create/unlink. */
366 	__ceph_touch_fmode(ci, mdsc, CEPH_FILE_MODE_WR);
367 	/* can we use the dcache? */
368 	if (ceph_test_mount_opt(fsc, DCACHE) &&
369 	    !ceph_test_mount_opt(fsc, NOASYNCREADDIR) &&
370 	    ceph_snap(inode) != CEPH_SNAPDIR &&
371 	    __ceph_dir_is_complete_ordered(ci) &&
372 	    __ceph_caps_issued_mask_metric(ci, CEPH_CAP_FILE_SHARED, 1)) {
373 		int shared_gen = atomic_read(&ci->i_shared_gen);
374 
375 		spin_unlock(&ci->i_ceph_lock);
376 		err = __dcache_readdir(file, ctx, shared_gen);
377 		if (err != -EAGAIN)
378 			return err;
379 	} else {
380 		spin_unlock(&ci->i_ceph_lock);
381 	}
382 
383 	/* proceed with a normal readdir */
384 more:
385 	/* do we have the correct frag content buffered? */
386 	if (need_send_readdir(dfi, ctx->pos)) {
387 		struct ceph_mds_request *req;
388 		int op = ceph_snap(inode) == CEPH_SNAPDIR ?
389 			CEPH_MDS_OP_LSSNAP : CEPH_MDS_OP_READDIR;
390 
391 		/* discard old result, if any */
392 		if (dfi->last_readdir) {
393 			ceph_mdsc_put_request(dfi->last_readdir);
394 			dfi->last_readdir = NULL;
395 		}
396 
397 		if (is_hash_order(ctx->pos)) {
398 			/* fragtree isn't always accurate. choose frag
399 			 * based on previous reply when possible. */
400 			if (frag == (unsigned)-1)
401 				frag = ceph_choose_frag(ci, fpos_hash(ctx->pos),
402 							NULL, NULL);
403 		} else {
404 			frag = fpos_frag(ctx->pos);
405 		}
406 
407 		doutc(cl, "fetching %p %llx.%llx frag %x offset '%s'\n",
408 		      inode, ceph_vinop(inode), frag, dfi->last_name);
409 		req = ceph_mdsc_create_request(mdsc, op, USE_AUTH_MDS);
410 		if (IS_ERR(req))
411 			return PTR_ERR(req);
412 
413 		err = ceph_alloc_readdir_reply_buffer(req, inode);
414 		if (err) {
415 			ceph_mdsc_put_request(req);
416 			return err;
417 		}
418 		/* hints to request -> mds selection code */
419 		req->r_direct_mode = USE_AUTH_MDS;
420 		if (op == CEPH_MDS_OP_READDIR) {
421 			req->r_direct_hash = ceph_frag_value(frag);
422 			__set_bit(CEPH_MDS_R_DIRECT_IS_HASH, &req->r_req_flags);
423 			req->r_inode_drop = CEPH_CAP_FILE_EXCL;
424 		}
425 		if (dfi->last_name) {
426 			int len = strlen(dfi->last_name);
427 
428 			req->r_path2 = kzalloc(NAME_MAX + 1, GFP_KERNEL);
429 			if (!req->r_path2) {
430 				ceph_mdsc_put_request(req);
431 				return -ENOMEM;
432 			}
433 			memcpy(req->r_path2, dfi->last_name, len);
434 
435 			err = ceph_encode_encrypted_dname(inode, req->r_path2, len);
436 			if (err < 0) {
437 				ceph_mdsc_put_request(req);
438 				return err;
439 			}
440 		} else if (is_hash_order(ctx->pos)) {
441 			req->r_args.readdir.offset_hash =
442 				cpu_to_le32(fpos_hash(ctx->pos));
443 		}
444 
445 		req->r_dir_release_cnt = dfi->dir_release_count;
446 		req->r_dir_ordered_cnt = dfi->dir_ordered_count;
447 		req->r_readdir_cache_idx = dfi->readdir_cache_idx;
448 		req->r_readdir_offset = dfi->next_offset;
449 		req->r_args.readdir.frag = cpu_to_le32(frag);
450 		req->r_args.readdir.flags =
451 				cpu_to_le16(CEPH_READDIR_REPLY_BITFLAGS);
452 
453 		req->r_inode = inode;
454 		ihold(inode);
455 		req->r_dentry = dget(file->f_path.dentry);
456 		err = ceph_mdsc_do_request(mdsc, NULL, req);
457 		if (err < 0) {
458 			ceph_mdsc_put_request(req);
459 			return err;
460 		}
461 		doutc(cl, "%p %llx.%llx got and parsed readdir result=%d"
462 		      "on frag %x, end=%d, complete=%d, hash_order=%d\n",
463 		      inode, ceph_vinop(inode), err, frag,
464 		      (int)req->r_reply_info.dir_end,
465 		      (int)req->r_reply_info.dir_complete,
466 		      (int)req->r_reply_info.hash_order);
467 
468 		rinfo = &req->r_reply_info;
469 		if (WARN_ON_ONCE(!rinfo->dir_dir)) {
470 			ceph_mdsc_put_request(req);
471 			return -EIO;
472 		}
473 		if (le32_to_cpu(rinfo->dir_dir->frag) != frag) {
474 			frag = le32_to_cpu(rinfo->dir_dir->frag);
475 			if (!rinfo->hash_order) {
476 				dfi->next_offset = req->r_readdir_offset;
477 				/* adjust ctx->pos to beginning of frag */
478 				ctx->pos = ceph_make_fpos(frag,
479 							  dfi->next_offset,
480 							  false);
481 			}
482 		}
483 
484 		dfi->frag = frag;
485 		dfi->last_readdir = req;
486 
487 		if (test_bit(CEPH_MDS_R_DID_PREPOPULATE, &req->r_req_flags)) {
488 			dfi->readdir_cache_idx = req->r_readdir_cache_idx;
489 			if (dfi->readdir_cache_idx < 0) {
490 				/* preclude from marking dir ordered */
491 				dfi->dir_ordered_count = 0;
492 			} else if (ceph_frag_is_leftmost(frag) &&
493 				   dfi->next_offset == 2) {
494 				/* note dir version at start of readdir so
495 				 * we can tell if any dentries get dropped */
496 				dfi->dir_release_count = req->r_dir_release_cnt;
497 				dfi->dir_ordered_count = req->r_dir_ordered_cnt;
498 			}
499 		} else {
500 			doutc(cl, "%p %llx.%llx !did_prepopulate\n", inode,
501 			      ceph_vinop(inode));
502 			/* disable readdir cache */
503 			dfi->readdir_cache_idx = -1;
504 			/* preclude from marking dir complete */
505 			dfi->dir_release_count = 0;
506 		}
507 
508 		/* note next offset and last dentry name */
509 		if (rinfo->dir_nr > 0) {
510 			struct ceph_mds_reply_dir_entry *rde =
511 					rinfo->dir_entries + (rinfo->dir_nr-1);
512 			unsigned next_offset = req->r_reply_info.dir_end ?
513 					2 : (fpos_off(rde->offset) + 1);
514 			err = note_last_dentry(fsc, dfi, rde->name,
515 					       rde->name_len, next_offset);
516 			if (err) {
517 				ceph_mdsc_put_request(dfi->last_readdir);
518 				dfi->last_readdir = NULL;
519 				return err;
520 			}
521 		} else if (req->r_reply_info.dir_end) {
522 			dfi->next_offset = 2;
523 			/* keep last name */
524 		}
525 	}
526 
527 	rinfo = &dfi->last_readdir->r_reply_info;
528 	doutc(cl, "%p %llx.%llx frag %x num %d pos %llx chunk first %llx\n",
529 	      inode, ceph_vinop(inode), dfi->frag, rinfo->dir_nr, ctx->pos,
530 	      rinfo->dir_nr ? rinfo->dir_entries[0].offset : 0LL);
531 
532 	i = 0;
533 	/* search start position */
534 	if (rinfo->dir_nr > 0) {
535 		int step, nr = rinfo->dir_nr;
536 		while (nr > 0) {
537 			step = nr >> 1;
538 			if (rinfo->dir_entries[i + step].offset < ctx->pos) {
539 				i +=  step + 1;
540 				nr -= step + 1;
541 			} else {
542 				nr = step;
543 			}
544 		}
545 	}
546 	for (; i < rinfo->dir_nr; i++) {
547 		struct ceph_mds_reply_dir_entry *rde = rinfo->dir_entries + i;
548 
549 		if (rde->offset < ctx->pos) {
550 			pr_warn_client(cl,
551 				"%p %llx.%llx rde->offset 0x%llx ctx->pos 0x%llx\n",
552 				inode, ceph_vinop(inode), rde->offset, ctx->pos);
553 			ceph_mdsc_put_request(dfi->last_readdir);
554 			dfi->last_readdir = NULL;
555 			return -EIO;
556 		}
557 
558 		if (WARN_ON_ONCE(!rde->inode.in)) {
559 			ceph_mdsc_put_request(dfi->last_readdir);
560 			dfi->last_readdir = NULL;
561 			return -EIO;
562 		}
563 
564 		ctx->pos = rde->offset;
565 		doutc(cl, "%p %llx.%llx (%d/%d) -> %llx '%.*s' %p\n", inode,
566 		      ceph_vinop(inode), i, rinfo->dir_nr, ctx->pos,
567 		      rde->name_len, rde->name, &rde->inode.in);
568 
569 		if (!dir_emit(ctx, rde->name, rde->name_len,
570 			      ceph_present_ino(inode->i_sb, le64_to_cpu(rde->inode.in->ino)),
571 			      le32_to_cpu(rde->inode.in->mode) >> 12)) {
572 			/*
573 			 * NOTE: Here no need to put the 'dfi->last_readdir',
574 			 * because when dir_emit stops us it's most likely
575 			 * doesn't have enough memory, etc. So for next readdir
576 			 * it will continue.
577 			 */
578 			doutc(cl, "filldir stopping us...\n");
579 			return 0;
580 		}
581 
582 		/* Reset the lengths to their original allocated vals */
583 		ctx->pos++;
584 	}
585 
586 	ceph_mdsc_put_request(dfi->last_readdir);
587 	dfi->last_readdir = NULL;
588 
589 	if (dfi->next_offset > 2) {
590 		frag = dfi->frag;
591 		goto more;
592 	}
593 
594 	/* more frags? */
595 	if (!ceph_frag_is_rightmost(dfi->frag)) {
596 		frag = ceph_frag_next(dfi->frag);
597 		if (is_hash_order(ctx->pos)) {
598 			loff_t new_pos = ceph_make_fpos(ceph_frag_value(frag),
599 							dfi->next_offset, true);
600 			if (new_pos > ctx->pos)
601 				ctx->pos = new_pos;
602 			/* keep last_name */
603 		} else {
604 			ctx->pos = ceph_make_fpos(frag, dfi->next_offset,
605 							false);
606 			kfree(dfi->last_name);
607 			dfi->last_name = NULL;
608 		}
609 		doutc(cl, "%p %llx.%llx next frag is %x\n", inode,
610 		      ceph_vinop(inode), frag);
611 		goto more;
612 	}
613 	dfi->file_info.flags |= CEPH_F_ATEND;
614 
615 	/*
616 	 * if dir_release_count still matches the dir, no dentries
617 	 * were released during the whole readdir, and we should have
618 	 * the complete dir contents in our cache.
619 	 */
620 	if (atomic64_read(&ci->i_release_count) ==
621 					dfi->dir_release_count) {
622 		spin_lock(&ci->i_ceph_lock);
623 		if (dfi->dir_ordered_count ==
624 				atomic64_read(&ci->i_ordered_count)) {
625 			doutc(cl, " marking %p %llx.%llx complete and ordered\n",
626 			      inode, ceph_vinop(inode));
627 			/* use i_size to track number of entries in
628 			 * readdir cache */
629 			BUG_ON(dfi->readdir_cache_idx < 0);
630 			i_size_write(inode, dfi->readdir_cache_idx *
631 				     sizeof(struct dentry*));
632 		} else {
633 			doutc(cl, " marking %llx.%llx complete\n",
634 			      ceph_vinop(inode));
635 		}
636 		__ceph_dir_set_complete(ci, dfi->dir_release_count,
637 					dfi->dir_ordered_count);
638 		spin_unlock(&ci->i_ceph_lock);
639 	}
640 	doutc(cl, "%p %llx.%llx file %p done.\n", inode, ceph_vinop(inode),
641 	      file);
642 	return 0;
643 }
644 
645 static void reset_readdir(struct ceph_dir_file_info *dfi)
646 {
647 	if (dfi->last_readdir) {
648 		ceph_mdsc_put_request(dfi->last_readdir);
649 		dfi->last_readdir = NULL;
650 	}
651 	kfree(dfi->last_name);
652 	dfi->last_name = NULL;
653 	dfi->dir_release_count = 0;
654 	dfi->readdir_cache_idx = -1;
655 	dfi->next_offset = 2;  /* compensate for . and .. */
656 	dfi->file_info.flags &= ~CEPH_F_ATEND;
657 }
658 
659 /*
660  * discard buffered readdir content on seekdir(0), or seek to new frag,
661  * or seek prior to current chunk
662  */
663 static bool need_reset_readdir(struct ceph_dir_file_info *dfi, loff_t new_pos)
664 {
665 	struct ceph_mds_reply_info_parsed *rinfo;
666 	loff_t chunk_offset;
667 	if (new_pos == 0)
668 		return true;
669 	if (is_hash_order(new_pos)) {
670 		/* no need to reset last_name for a forward seek when
671 		 * dentries are sorted in hash order */
672 	} else if (dfi->frag != fpos_frag(new_pos)) {
673 		return true;
674 	}
675 	rinfo = dfi->last_readdir ? &dfi->last_readdir->r_reply_info : NULL;
676 	if (!rinfo || !rinfo->dir_nr)
677 		return true;
678 	chunk_offset = rinfo->dir_entries[0].offset;
679 	return new_pos < chunk_offset ||
680 	       is_hash_order(new_pos) != is_hash_order(chunk_offset);
681 }
682 
683 static loff_t ceph_dir_llseek(struct file *file, loff_t offset, int whence)
684 {
685 	struct ceph_dir_file_info *dfi = file->private_data;
686 	struct inode *inode = file->f_mapping->host;
687 	struct ceph_client *cl = ceph_inode_to_client(inode);
688 	loff_t retval;
689 
690 	inode_lock(inode);
691 	retval = -EINVAL;
692 	switch (whence) {
693 	case SEEK_CUR:
694 		offset += file->f_pos;
695 		break;
696 	case SEEK_SET:
697 		break;
698 	case SEEK_END:
699 		retval = -EOPNOTSUPP;
700 		goto out;
701 	default:
702 		goto out;
703 	}
704 
705 	if (offset >= 0) {
706 		if (need_reset_readdir(dfi, offset)) {
707 			doutc(cl, "%p %llx.%llx dropping %p content\n",
708 			      inode, ceph_vinop(inode), file);
709 			reset_readdir(dfi);
710 		} else if (is_hash_order(offset) && offset > file->f_pos) {
711 			/* for hash offset, we don't know if a forward seek
712 			 * is within same frag */
713 			dfi->dir_release_count = 0;
714 			dfi->readdir_cache_idx = -1;
715 		}
716 
717 		if (offset != file->f_pos) {
718 			file->f_pos = offset;
719 			dfi->file_info.flags &= ~CEPH_F_ATEND;
720 		}
721 		retval = offset;
722 	}
723 out:
724 	inode_unlock(inode);
725 	return retval;
726 }
727 
728 /*
729  * Handle lookups for the hidden .snap directory.
730  */
731 struct dentry *ceph_handle_snapdir(struct ceph_mds_request *req,
732 				   struct dentry *dentry)
733 {
734 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(dentry->d_sb);
735 	struct inode *parent = d_inode(dentry->d_parent); /* we hold i_rwsem */
736 	struct ceph_client *cl = ceph_inode_to_client(parent);
737 
738 	/* .snap dir? */
739 	if (!ceph_in_snap(parent) &&
740 	    strcmp(dentry->d_name.name, fsc->mount_options->snapdir_name) == 0) {
741 		struct dentry *res;
742 		struct inode *inode = ceph_get_snapdir(parent);
743 
744 		res = d_splice_alias(inode, dentry);
745 		doutc(cl, "ENOENT on snapdir %p '%pd', linking to "
746 		      "snapdir %p %llx.%llx. Spliced dentry %p\n",
747 		      dentry, dentry, inode, ceph_vinop(inode), res);
748 		if (res)
749 			dentry = res;
750 	}
751 	return dentry;
752 }
753 
754 /*
755  * Figure out final result of a lookup/open request.
756  *
757  * Mainly, make sure we return the final req->r_dentry (if it already
758  * existed) in place of the original VFS-provided dentry when they
759  * differ.
760  *
761  * Gracefully handle the case where the MDS replies with -ENOENT and
762  * no trace (which it may do, at its discretion, e.g., if it doesn't
763  * care to issue a lease on the negative dentry).
764  */
765 struct dentry *ceph_finish_lookup(struct ceph_mds_request *req,
766 				  struct dentry *dentry, int err)
767 {
768 	struct ceph_client *cl = req->r_mdsc->fsc->client;
769 
770 	if (err == -ENOENT) {
771 		/* no trace? */
772 		err = 0;
773 		if (!req->r_reply_info.head->is_dentry) {
774 			doutc(cl,
775 			      "ENOENT and no trace, dentry %p inode %llx.%llx\n",
776 			      dentry, ceph_vinop(d_inode(dentry)));
777 			if (d_really_is_positive(dentry)) {
778 				d_drop(dentry);
779 				err = -ENOENT;
780 			} else {
781 				if (d_unhashed(dentry)) {
782 					struct inode *parent =
783 						d_inode(dentry->d_parent);
784 					if (!parent ||
785 					    ceph_snap(parent) == CEPH_NOSNAP)
786 						d_add(dentry, NULL);
787 				}
788 			}
789 		}
790 	}
791 	if (err)
792 		dentry = ERR_PTR(err);
793 	else if (dentry != req->r_dentry)
794 		dentry = dget(req->r_dentry);   /* we got spliced */
795 	else
796 		dentry = NULL;
797 	return dentry;
798 }
799 
800 static bool is_root_ceph_dentry(struct inode *inode, struct dentry *dentry)
801 {
802 	return ceph_ino(inode) == CEPH_INO_ROOT &&
803 		strncmp(dentry->d_name.name, ".ceph", 5) == 0;
804 }
805 
806 /*
807  * Look up a single dir entry.  If there is a lookup intent, inform
808  * the MDS so that it gets our 'caps wanted' value in a single op.
809  */
810 static struct dentry *ceph_lookup(struct inode *dir, struct dentry *dentry,
811 				  unsigned int flags)
812 {
813 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(dir->i_sb);
814 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
815 	struct ceph_client *cl = fsc->client;
816 	struct ceph_mds_request *req;
817 	int op;
818 	int mask;
819 	int err;
820 
821 	doutc(cl, "%p %llx.%llx/'%pd' dentry %p\n", dir, ceph_vinop(dir),
822 	      dentry, dentry);
823 
824 	if (dentry->d_name.len > NAME_MAX)
825 		return ERR_PTR(-ENAMETOOLONG);
826 
827 	if (IS_ENCRYPTED(dir)) {
828 		bool had_key = fscrypt_has_encryption_key(dir);
829 
830 		err = fscrypt_prepare_lookup_partial(dir, dentry);
831 		if (err < 0)
832 			return ERR_PTR(err);
833 
834 		/* mark directory as incomplete if it has been unlocked */
835 		if (!had_key && fscrypt_has_encryption_key(dir))
836 			ceph_dir_clear_complete(dir);
837 	}
838 
839 	/* can we conclude ENOENT locally? */
840 	if (d_really_is_negative(dentry)) {
841 		struct ceph_inode_info *ci = ceph_inode(dir);
842 		struct ceph_dentry_info *di = ceph_dentry(dentry);
843 
844 		spin_lock(&ci->i_ceph_lock);
845 		doutc(cl, " dir %llx.%llx flags are 0x%lx\n",
846 		      ceph_vinop(dir), ci->i_ceph_flags);
847 		if (strncmp(dentry->d_name.name,
848 			    fsc->mount_options->snapdir_name,
849 			    dentry->d_name.len) &&
850 		    !is_root_ceph_dentry(dir, dentry) &&
851 		    ceph_test_mount_opt(fsc, DCACHE) &&
852 		    ceph_snap(dir) == CEPH_NOSNAP &&
853 		    __ceph_dir_is_complete(ci) &&
854 		    __ceph_caps_issued_mask_metric(ci, CEPH_CAP_FILE_SHARED, 1)) {
855 			__ceph_touch_fmode(ci, mdsc, CEPH_FILE_MODE_RD);
856 			spin_unlock(&ci->i_ceph_lock);
857 			doutc(cl, " dir %llx.%llx complete, -ENOENT\n",
858 			      ceph_vinop(dir));
859 			if (d_unhashed(dentry))
860 				d_add(dentry, NULL);
861 			di->lease_shared_gen = atomic_read(&ci->i_shared_gen);
862 			return NULL;
863 		}
864 		spin_unlock(&ci->i_ceph_lock);
865 	}
866 
867 	op = ceph_snap(dir) == CEPH_SNAPDIR ?
868 		CEPH_MDS_OP_LOOKUPSNAP : CEPH_MDS_OP_LOOKUP;
869 	req = ceph_mdsc_create_request(mdsc, op, USE_ANY_MDS);
870 	if (IS_ERR(req))
871 		return ERR_CAST(req);
872 	req->r_dentry = dget(dentry);
873 	req->r_num_caps = 2;
874 
875 	mask = CEPH_STAT_CAP_INODE | CEPH_CAP_AUTH_SHARED;
876 	if (ceph_security_xattr_wanted(dir))
877 		mask |= CEPH_CAP_XATTR_SHARED;
878 	req->r_args.getattr.mask = cpu_to_le32(mask);
879 
880 	ihold(dir);
881 	req->r_parent = dir;
882 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
883 	err = ceph_mdsc_do_request(mdsc, NULL, req);
884 	if (err == -ENOENT) {
885 		struct dentry *res;
886 
887 		res = ceph_handle_snapdir(req, dentry);
888 		if (IS_ERR(res)) {
889 			err = PTR_ERR(res);
890 		} else {
891 			dentry = res;
892 			err = 0;
893 		}
894 	}
895 	dentry = ceph_finish_lookup(req, dentry, err);
896 	ceph_mdsc_put_request(req);  /* will dput(dentry) */
897 	doutc(cl, "result=%p\n", dentry);
898 	return dentry;
899 }
900 
901 /*
902  * If we do a create but get no trace back from the MDS, follow up with
903  * a lookup (the VFS expects us to link up the provided dentry).
904  */
905 int ceph_handle_notrace_create(struct inode *dir, struct dentry *dentry)
906 {
907 	struct dentry *result = ceph_lookup(dir, dentry, 0);
908 
909 	if (result && !IS_ERR(result)) {
910 		/*
911 		 * We created the item, then did a lookup, and found
912 		 * it was already linked to another inode we already
913 		 * had in our cache (and thus got spliced). To not
914 		 * confuse VFS (especially when inode is a directory),
915 		 * we don't link our dentry to that inode, return an
916 		 * error instead.
917 		 *
918 		 * This event should be rare and it happens only when
919 		 * we talk to old MDS. Recent MDS does not send traceless
920 		 * reply for request that creates new inode.
921 		 */
922 		d_drop(result);
923 		return -ESTALE;
924 	}
925 	return PTR_ERR(result);
926 }
927 
928 static int ceph_mknod(const struct mnt_idmap *idmap, struct inode *dir,
929 		      struct dentry *dentry, umode_t mode, dev_t rdev)
930 {
931 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
932 	struct ceph_client *cl = mdsc->fsc->client;
933 	struct ceph_mds_request *req;
934 	struct ceph_acl_sec_ctx as_ctx = {};
935 	int err;
936 
937 	if (ceph_in_snap(dir))
938 		return -EROFS;
939 
940 	err = ceph_wait_on_conflict_unlink(dentry);
941 	if (err)
942 		return err;
943 
944 	if (ceph_quota_is_max_files_exceeded(dir)) {
945 		err = -EDQUOT;
946 		goto out;
947 	}
948 
949 	doutc(cl, "%p %llx.%llx/'%pd' dentry %p mode 0%ho rdev %d\n",
950 	      dir, ceph_vinop(dir), dentry, dentry, mode, rdev);
951 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_MKNOD, USE_AUTH_MDS);
952 	if (IS_ERR(req)) {
953 		err = PTR_ERR(req);
954 		goto out;
955 	}
956 
957 	req->r_new_inode = ceph_new_inode(dir, dentry, &mode, &as_ctx);
958 	if (IS_ERR(req->r_new_inode)) {
959 		err = PTR_ERR(req->r_new_inode);
960 		req->r_new_inode = NULL;
961 		goto out_req;
962 	}
963 
964 	if (S_ISREG(mode) && IS_ENCRYPTED(dir))
965 		set_bit(CEPH_MDS_R_FSCRYPT_FILE, &req->r_req_flags);
966 
967 	req->r_dentry = dget(dentry);
968 	req->r_num_caps = 2;
969 	req->r_parent = dir;
970 	ihold(dir);
971 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
972 	req->r_mnt_idmap = mnt_idmap_get(idmap);
973 	req->r_args.mknod.mode = cpu_to_le32(mode);
974 	req->r_args.mknod.rdev = cpu_to_le32(rdev);
975 	req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_AUTH_EXCL |
976 			     CEPH_CAP_XATTR_EXCL;
977 	req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
978 
979 	ceph_as_ctx_to_req(req, &as_ctx);
980 
981 	err = ceph_mdsc_do_request(mdsc, dir, req);
982 	if (!err && !req->r_reply_info.head->is_dentry)
983 		err = ceph_handle_notrace_create(dir, dentry);
984 out_req:
985 	ceph_mdsc_put_request(req);
986 out:
987 	if (!err)
988 		ceph_init_inode_acls(d_inode(dentry), &as_ctx);
989 	else
990 		d_drop(dentry);
991 	ceph_release_acl_sec_ctx(&as_ctx);
992 	return err;
993 }
994 
995 static int ceph_create(const struct mnt_idmap *idmap, struct inode *dir,
996 		       struct dentry *dentry, umode_t mode)
997 {
998 	return ceph_mknod(idmap, dir, dentry, mode, 0);
999 }
1000 
1001 #if IS_ENABLED(CONFIG_FS_ENCRYPTION)
1002 static int prep_encrypted_symlink_target(struct ceph_mds_request *req,
1003 					 const char *dest)
1004 {
1005 	int err;
1006 	int len = strlen(dest);
1007 	struct fscrypt_str osd_link = FSTR_INIT(NULL, 0);
1008 
1009 	err = fscrypt_prepare_symlink(req->r_parent, dest, len, PATH_MAX,
1010 				      &osd_link);
1011 	if (err)
1012 		goto out;
1013 
1014 	err = fscrypt_encrypt_symlink(req->r_new_inode, dest, len, &osd_link);
1015 	if (err)
1016 		goto out;
1017 
1018 	req->r_path2 = kmalloc(BASE64_CHARS(osd_link.len) + 1, GFP_KERNEL);
1019 	if (!req->r_path2) {
1020 		err = -ENOMEM;
1021 		goto out;
1022 	}
1023 
1024 	len = base64_encode(osd_link.name, osd_link.len,
1025 			    req->r_path2, false, BASE64_IMAP);
1026 	req->r_path2[len] = '\0';
1027 out:
1028 	fscrypt_fname_free_buffer(&osd_link);
1029 	return err;
1030 }
1031 #else
1032 static int prep_encrypted_symlink_target(struct ceph_mds_request *req,
1033 					 const char *dest)
1034 {
1035 	return -EOPNOTSUPP;
1036 }
1037 #endif
1038 
1039 static int ceph_symlink(const struct mnt_idmap *idmap, struct inode *dir,
1040 			struct dentry *dentry, const char *dest)
1041 {
1042 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
1043 	struct ceph_client *cl = mdsc->fsc->client;
1044 	struct ceph_mds_request *req;
1045 	struct ceph_acl_sec_ctx as_ctx = {};
1046 	umode_t mode = S_IFLNK | 0777;
1047 	int err;
1048 
1049 	if (ceph_in_snap(dir))
1050 		return -EROFS;
1051 
1052 	err = ceph_wait_on_conflict_unlink(dentry);
1053 	if (err)
1054 		return err;
1055 
1056 	if (ceph_quota_is_max_files_exceeded(dir)) {
1057 		err = -EDQUOT;
1058 		goto out;
1059 	}
1060 
1061 	doutc(cl, "%p %llx.%llx/'%pd' to '%s'\n", dir, ceph_vinop(dir), dentry,
1062 	      dest);
1063 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_SYMLINK, USE_AUTH_MDS);
1064 	if (IS_ERR(req)) {
1065 		err = PTR_ERR(req);
1066 		goto out;
1067 	}
1068 
1069 	req->r_new_inode = ceph_new_inode(dir, dentry, &mode, &as_ctx);
1070 	if (IS_ERR(req->r_new_inode)) {
1071 		err = PTR_ERR(req->r_new_inode);
1072 		req->r_new_inode = NULL;
1073 		goto out_req;
1074 	}
1075 
1076 	req->r_parent = dir;
1077 	ihold(dir);
1078 
1079 	if (IS_ENCRYPTED(req->r_new_inode)) {
1080 		err = prep_encrypted_symlink_target(req, dest);
1081 		if (err)
1082 			goto out_req;
1083 	} else {
1084 		req->r_path2 = kstrdup(dest, GFP_KERNEL);
1085 		if (!req->r_path2) {
1086 			err = -ENOMEM;
1087 			goto out_req;
1088 		}
1089 	}
1090 
1091 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
1092 	req->r_mnt_idmap = mnt_idmap_get(idmap);
1093 	req->r_dentry = dget(dentry);
1094 	req->r_num_caps = 2;
1095 	req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_AUTH_EXCL |
1096 			     CEPH_CAP_XATTR_EXCL;
1097 	req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
1098 
1099 	ceph_as_ctx_to_req(req, &as_ctx);
1100 
1101 	err = ceph_mdsc_do_request(mdsc, dir, req);
1102 	if (!err && !req->r_reply_info.head->is_dentry)
1103 		err = ceph_handle_notrace_create(dir, dentry);
1104 out_req:
1105 	ceph_mdsc_put_request(req);
1106 out:
1107 	if (err)
1108 		d_drop(dentry);
1109 	ceph_release_acl_sec_ctx(&as_ctx);
1110 	return err;
1111 }
1112 
1113 static struct dentry *ceph_mkdir(const struct mnt_idmap *idmap, struct inode *dir,
1114 				 struct dentry *dentry, umode_t mode)
1115 {
1116 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
1117 	struct ceph_client *cl = mdsc->fsc->client;
1118 	struct ceph_mds_request *req;
1119 	struct ceph_acl_sec_ctx as_ctx = {};
1120 	struct dentry *ret;
1121 	int err;
1122 	int op;
1123 
1124 	err = ceph_wait_on_conflict_unlink(dentry);
1125 	if (err)
1126 		return ERR_PTR(err);
1127 
1128 	if (ceph_snap(dir) == CEPH_SNAPDIR) {
1129 		/* mkdir .snap/foo is a MKSNAP */
1130 		op = CEPH_MDS_OP_MKSNAP;
1131 		doutc(cl, "mksnap %llx.%llx/'%pd' dentry %p\n",
1132 		      ceph_vinop(dir), dentry, dentry);
1133 	} else if (!ceph_in_snap(dir)) {
1134 		doutc(cl, "mkdir %llx.%llx/'%pd' dentry %p mode 0%ho\n",
1135 		      ceph_vinop(dir), dentry, dentry, mode);
1136 		op = CEPH_MDS_OP_MKDIR;
1137 	} else {
1138 		ret = ERR_PTR(-EROFS);
1139 		goto out;
1140 	}
1141 
1142 	if (op == CEPH_MDS_OP_MKDIR &&
1143 	    ceph_quota_is_max_files_exceeded(dir)) {
1144 		ret = ERR_PTR(-EDQUOT);
1145 		goto out;
1146 	}
1147 	if ((op == CEPH_MDS_OP_MKSNAP) && IS_ENCRYPTED(dir) &&
1148 	    !fscrypt_has_encryption_key(dir)) {
1149 		ret = ERR_PTR(-ENOKEY);
1150 		goto out;
1151 	}
1152 
1153 
1154 	req = ceph_mdsc_create_request(mdsc, op, USE_AUTH_MDS);
1155 	if (IS_ERR(req)) {
1156 		ret = ERR_CAST(req);
1157 		goto out;
1158 	}
1159 
1160 	req->r_new_inode = ceph_new_inode(dir, dentry, &mode, &as_ctx);
1161 	if (IS_ERR(req->r_new_inode)) {
1162 		ret = ERR_CAST(req->r_new_inode);
1163 		req->r_new_inode = NULL;
1164 		goto out_req;
1165 	}
1166 
1167 	req->r_dentry = dget(dentry);
1168 	req->r_num_caps = 2;
1169 	req->r_parent = dir;
1170 	ihold(dir);
1171 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
1172 	if (op == CEPH_MDS_OP_MKDIR)
1173 		req->r_mnt_idmap = mnt_idmap_get(idmap);
1174 	req->r_args.mkdir.mode = cpu_to_le32(mode);
1175 	req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_AUTH_EXCL |
1176 			     CEPH_CAP_XATTR_EXCL;
1177 	req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
1178 
1179 	ceph_as_ctx_to_req(req, &as_ctx);
1180 
1181 	err = ceph_mdsc_do_request(mdsc, dir, req);
1182 	if (!err &&
1183 	    !req->r_reply_info.head->is_target &&
1184 	    !req->r_reply_info.head->is_dentry)
1185 		err = ceph_handle_notrace_create(dir, dentry);
1186 	ret = err ? ERR_PTR(err) : NULL;
1187 out_req:
1188 	if (!IS_ERR(ret) && req->r_dentry != dentry)
1189 		/* Some other dentry was spliced in */
1190 		ret = dget(req->r_dentry);
1191 	ceph_mdsc_put_request(req);
1192 out:
1193 	if (!IS_ERR(ret)) {
1194 		if (ret)
1195 			dentry = ret;
1196 		ceph_init_inode_acls(d_inode(dentry), &as_ctx);
1197 	} else {
1198 		d_drop(dentry);
1199 	}
1200 	ceph_release_acl_sec_ctx(&as_ctx);
1201 	return ret;
1202 }
1203 
1204 static int ceph_link(struct dentry *old_dentry, struct inode *dir,
1205 		     struct dentry *dentry)
1206 {
1207 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
1208 	struct ceph_client *cl = mdsc->fsc->client;
1209 	struct ceph_mds_request *req;
1210 	int err;
1211 
1212 	if (dentry->d_flags & DCACHE_DISCONNECTED)
1213 		return -EINVAL;
1214 
1215 	err = ceph_wait_on_conflict_unlink(dentry);
1216 	if (err)
1217 		return err;
1218 
1219 	if (ceph_in_snap(dir))
1220 		return -EROFS;
1221 
1222 	err = fscrypt_prepare_link(old_dentry, dir, dentry);
1223 	if (err)
1224 		return err;
1225 
1226 	doutc(cl, "%p %llx.%llx/'%pd' to '%pd'\n", dir, ceph_vinop(dir),
1227 	      old_dentry, dentry);
1228 	req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_LINK, USE_AUTH_MDS);
1229 	if (IS_ERR(req)) {
1230 		d_drop(dentry);
1231 		return PTR_ERR(req);
1232 	}
1233 	req->r_dentry = dget(dentry);
1234 	req->r_num_caps = 2;
1235 	req->r_old_dentry = dget(old_dentry);
1236 	/*
1237 	 * The old_dentry maybe a DCACHE_DISCONNECTED dentry, then we
1238 	 * will just pass the ino# to MDSs.
1239 	 */
1240 	if (old_dentry->d_flags & DCACHE_DISCONNECTED)
1241 		req->r_ino2 = ceph_vino(d_inode(old_dentry));
1242 	req->r_parent = dir;
1243 	ihold(dir);
1244 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
1245 	req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_XATTR_EXCL;
1246 	req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
1247 	/* release LINK_SHARED on source inode (mds will lock it) */
1248 	req->r_old_inode_drop = CEPH_CAP_LINK_SHARED | CEPH_CAP_LINK_EXCL;
1249 	err = ceph_mdsc_do_request(mdsc, dir, req);
1250 	if (err) {
1251 		d_drop(dentry);
1252 	} else if (!req->r_reply_info.head->is_dentry) {
1253 		ihold(d_inode(old_dentry));
1254 		d_instantiate(dentry, d_inode(old_dentry));
1255 	}
1256 	ceph_mdsc_put_request(req);
1257 	return err;
1258 }
1259 
1260 static void ceph_async_unlink_cb(struct ceph_mds_client *mdsc,
1261 				 struct ceph_mds_request *req)
1262 {
1263 	struct dentry *dentry = req->r_dentry;
1264 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(dentry->d_sb);
1265 	struct ceph_client *cl = fsc->client;
1266 	struct ceph_dentry_info *di = ceph_dentry(dentry);
1267 	int result = req->r_err ? req->r_err :
1268 			le32_to_cpu(req->r_reply_info.head->result);
1269 
1270 	if (!test_bit(CEPH_DENTRY_ASYNC_UNLINK_BIT, &di->flags))
1271 		pr_warn_client(cl,
1272 			"dentry %p:%pd async unlink bit is not set\n",
1273 			dentry, dentry);
1274 
1275 	spin_lock(&fsc->async_unlink_conflict_lock);
1276 	hash_del_rcu(&di->hnode);
1277 	spin_unlock(&fsc->async_unlink_conflict_lock);
1278 
1279 	spin_lock(&dentry->d_lock);
1280 	clear_and_wake_up_bit(CEPH_DENTRY_ASYNC_UNLINK_BIT, &di->flags);
1281 	spin_unlock(&dentry->d_lock);
1282 
1283 	synchronize_rcu();
1284 
1285 	if (result == -EJUKEBOX)
1286 		goto out;
1287 
1288 	/* If op failed, mark everyone involved for errors */
1289 	if (result) {
1290 		struct ceph_path_info path_info = {0};
1291 		char *path = ceph_mdsc_build_path(mdsc, dentry, &path_info, 0);
1292 
1293 		/* mark error on parent + clear complete */
1294 		mapping_set_error(req->r_parent->i_mapping, result);
1295 		ceph_dir_clear_complete(req->r_parent);
1296 
1297 		/* drop the dentry -- we don't know its status */
1298 		if (!d_unhashed(dentry))
1299 			d_drop(dentry);
1300 
1301 		/* mark inode itself for an error (since metadata is bogus) */
1302 		mapping_set_error(req->r_old_inode->i_mapping, result);
1303 
1304 		pr_warn_client(cl, "failure path=(%llx)%s result=%d!\n",
1305 			       path_info.vino.ino, IS_ERR(path) ? "<<bad>>" : path, result);
1306 		ceph_mdsc_free_path_info(&path_info);
1307 	}
1308 out:
1309 	iput(req->r_old_inode);
1310 	ceph_mdsc_release_dir_caps(req);
1311 }
1312 
1313 static int get_caps_for_async_unlink(struct inode *dir, struct dentry *dentry)
1314 {
1315 	struct ceph_inode_info *ci = ceph_inode(dir);
1316 	struct ceph_dentry_info *di;
1317 	int got = 0, want = CEPH_CAP_FILE_EXCL | CEPH_CAP_DIR_UNLINK;
1318 
1319 	spin_lock(&ci->i_ceph_lock);
1320 	if ((__ceph_caps_issued(ci, NULL) & want) == want) {
1321 		ceph_take_cap_refs(ci, want, false);
1322 		got = want;
1323 	}
1324 	spin_unlock(&ci->i_ceph_lock);
1325 
1326 	/* If we didn't get anything, return 0 */
1327 	if (!got)
1328 		return 0;
1329 
1330         spin_lock(&dentry->d_lock);
1331         di = ceph_dentry(dentry);
1332 	/*
1333 	 * - We are holding Fx, which implies Fs caps.
1334 	 * - Only support async unlink for primary linkage
1335 	 */
1336 	if (atomic_read(&ci->i_shared_gen) != di->lease_shared_gen ||
1337 	    !(di->flags & CEPH_DENTRY_PRIMARY_LINK))
1338 		want = 0;
1339         spin_unlock(&dentry->d_lock);
1340 
1341 	/* Do we still want what we've got? */
1342 	if (want == got)
1343 		return got;
1344 
1345 	ceph_put_cap_refs(ci, got);
1346 	return 0;
1347 }
1348 
1349 /*
1350  * rmdir and unlink are differ only by the metadata op code
1351  */
1352 static int ceph_unlink(struct inode *dir, struct dentry *dentry)
1353 {
1354 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(dir->i_sb);
1355 	struct ceph_client *cl = fsc->client;
1356 	struct ceph_mds_client *mdsc = fsc->mdsc;
1357 	struct inode *inode = d_inode(dentry);
1358 	struct ceph_inode_info *ci = ceph_inode(inode);
1359 	struct ceph_mds_request *req;
1360 	bool try_async = ceph_test_mount_opt(fsc, ASYNC_DIROPS);
1361 	struct dentry *dn;
1362 	int err = -EROFS;
1363 	int op;
1364 	char *path;
1365 
1366 	if (ceph_snap(dir) == CEPH_SNAPDIR) {
1367 		/* rmdir .snap/foo is RMSNAP */
1368 		doutc(cl, "rmsnap %llx.%llx/'%pd' dn\n", ceph_vinop(dir),
1369 		      dentry);
1370 		op = CEPH_MDS_OP_RMSNAP;
1371 	} else if (!ceph_in_snap(dir)) {
1372 		doutc(cl, "unlink/rmdir %llx.%llx/'%pd' inode %llx.%llx\n",
1373 		      ceph_vinop(dir), dentry, ceph_vinop(inode));
1374 		op = d_is_dir(dentry) ?
1375 			CEPH_MDS_OP_RMDIR : CEPH_MDS_OP_UNLINK;
1376 	} else
1377 		goto out;
1378 
1379 	dn = d_find_alias(dir);
1380 	if (!dn) {
1381 		try_async = false;
1382 	} else {
1383 		struct ceph_path_info path_info = {0};
1384 		path = ceph_mdsc_build_path(mdsc, dn, &path_info, 0);
1385 		if (IS_ERR(path)) {
1386 			try_async = false;
1387 			err = 0;
1388 		} else {
1389 			err = ceph_mds_check_access(mdsc, path, MAY_WRITE);
1390 		}
1391 		ceph_mdsc_free_path_info(&path_info);
1392 		dput(dn);
1393 
1394 		/* For none EACCES cases will let the MDS do the mds auth check */
1395 		if (err == -EACCES) {
1396 			return err;
1397 		} else if (err < 0) {
1398 			try_async = false;
1399 			err = 0;
1400 		}
1401 	}
1402 
1403 retry:
1404 	req = ceph_mdsc_create_request(mdsc, op, USE_AUTH_MDS);
1405 	if (IS_ERR(req)) {
1406 		err = PTR_ERR(req);
1407 		goto out;
1408 	}
1409 	req->r_dentry = dget(dentry);
1410 	req->r_num_caps = 2;
1411 	req->r_parent = dir;
1412 	ihold(dir);
1413 	req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_XATTR_EXCL;
1414 	req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
1415 	req->r_inode_drop = ceph_drop_caps_for_unlink(inode);
1416 
1417 	if (try_async && op == CEPH_MDS_OP_UNLINK &&
1418 	    (req->r_dir_caps = get_caps_for_async_unlink(dir, dentry))) {
1419 		struct ceph_dentry_info *di = ceph_dentry(dentry);
1420 
1421 		doutc(cl, "async unlink on %llx.%llx/'%pd' caps=%s",
1422 		      ceph_vinop(dir), dentry,
1423 		      ceph_cap_string(req->r_dir_caps));
1424 		set_bit(CEPH_MDS_R_ASYNC, &req->r_req_flags);
1425 		req->r_callback = ceph_async_unlink_cb;
1426 		req->r_old_inode = d_inode(dentry);
1427 		ihold(req->r_old_inode);
1428 
1429 		spin_lock(&dentry->d_lock);
1430 		di->flags |= CEPH_DENTRY_ASYNC_UNLINK;
1431 		spin_unlock(&dentry->d_lock);
1432 
1433 		spin_lock(&fsc->async_unlink_conflict_lock);
1434 		hash_add_rcu(fsc->async_unlink_conflict, &di->hnode,
1435 			     dentry->d_name.hash);
1436 		spin_unlock(&fsc->async_unlink_conflict_lock);
1437 
1438 		err = ceph_mdsc_submit_request(mdsc, dir, req);
1439 		if (!err) {
1440 			/*
1441 			 * We have enough caps, so we assume that the unlink
1442 			 * will succeed. Fix up the target inode and dcache.
1443 			 */
1444 
1445 			/*
1446 			 * Protect the i_nlink update with i_ceph_lock
1447 			 * to precent racing against ceph_fill_inode()
1448 			 * handling our completion on a worker thread
1449 			 * and don't decrement if i_nlink has already
1450 			 * been updated to zero by this completion.
1451 			 */
1452 			spin_lock(&ci->i_ceph_lock);
1453 			if (inode->i_nlink > 0)
1454 				drop_nlink(inode);
1455 			spin_unlock(&ci->i_ceph_lock);
1456 
1457 			d_delete(dentry);
1458 		} else {
1459 			spin_lock(&fsc->async_unlink_conflict_lock);
1460 			hash_del_rcu(&di->hnode);
1461 			spin_unlock(&fsc->async_unlink_conflict_lock);
1462 
1463 			spin_lock(&dentry->d_lock);
1464 			di->flags &= ~CEPH_DENTRY_ASYNC_UNLINK;
1465 			spin_unlock(&dentry->d_lock);
1466 
1467 			if (err == -EJUKEBOX) {
1468 				try_async = false;
1469 				ceph_mdsc_put_request(req);
1470 				goto retry;
1471 			}
1472 		}
1473 	} else {
1474 		set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
1475 		err = ceph_mdsc_do_request(mdsc, dir, req);
1476 		if (!err && !req->r_reply_info.head->is_dentry)
1477 			d_delete(dentry);
1478 	}
1479 
1480 	ceph_mdsc_put_request(req);
1481 out:
1482 	return err;
1483 }
1484 
1485 static int ceph_rename(const struct mnt_idmap *idmap, struct inode *old_dir,
1486 		       struct dentry *old_dentry, struct inode *new_dir,
1487 		       struct dentry *new_dentry, unsigned int flags)
1488 {
1489 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(old_dir->i_sb);
1490 	struct ceph_client *cl = mdsc->fsc->client;
1491 	struct ceph_mds_request *req;
1492 	int op = CEPH_MDS_OP_RENAME;
1493 	int err;
1494 
1495 	if (flags)
1496 		return -EINVAL;
1497 
1498 	if (ceph_snap(old_dir) != ceph_snap(new_dir))
1499 		return -EXDEV;
1500 	if (ceph_in_snap(old_dir)) {
1501 		if (old_dir == new_dir && ceph_snap(old_dir) == CEPH_SNAPDIR)
1502 			op = CEPH_MDS_OP_RENAMESNAP;
1503 		else
1504 			return -EROFS;
1505 	}
1506 	/* don't allow cross-quota renames */
1507 	if ((old_dir != new_dir) &&
1508 	    (!ceph_quota_is_same_realm(old_dir, new_dir)))
1509 		return -EXDEV;
1510 
1511 	err = ceph_wait_on_conflict_unlink(new_dentry);
1512 	if (err)
1513 		return err;
1514 
1515 	err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
1516 				     flags);
1517 	if (err)
1518 		return err;
1519 
1520 	doutc(cl, "%llx.%llx/'%pd' to %llx.%llx/'%pd'\n",
1521 	      ceph_vinop(old_dir), old_dentry, ceph_vinop(new_dir),
1522 	      new_dentry);
1523 	req = ceph_mdsc_create_request(mdsc, op, USE_AUTH_MDS);
1524 	if (IS_ERR(req))
1525 		return PTR_ERR(req);
1526 	ihold(old_dir);
1527 	req->r_dentry = dget(new_dentry);
1528 	req->r_num_caps = 2;
1529 	req->r_old_dentry = dget(old_dentry);
1530 	req->r_old_dentry_dir = old_dir;
1531 	req->r_parent = new_dir;
1532 	ihold(new_dir);
1533 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
1534 	req->r_old_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_XATTR_EXCL;
1535 	req->r_old_dentry_unless = CEPH_CAP_FILE_EXCL;
1536 	req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_XATTR_EXCL;
1537 	req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
1538 	/* release LINK_RDCACHE on source inode (mds will lock it) */
1539 	req->r_old_inode_drop = CEPH_CAP_LINK_SHARED | CEPH_CAP_LINK_EXCL;
1540 	if (d_really_is_positive(new_dentry)) {
1541 		req->r_inode_drop =
1542 			ceph_drop_caps_for_unlink(d_inode(new_dentry));
1543 	}
1544 	err = ceph_mdsc_do_request(mdsc, old_dir, req);
1545 	if (!err && !req->r_reply_info.head->is_dentry) {
1546 		/*
1547 		 * Normally d_move() is done by fill_trace (called by
1548 		 * do_request, above).  If there is no trace, we need
1549 		 * to do it here.
1550 		 */
1551 		d_move(old_dentry, new_dentry);
1552 	}
1553 	ceph_mdsc_put_request(req);
1554 	return err;
1555 }
1556 
1557 /*
1558  * Move dentry to tail of mdsc->dentry_leases list when lease is updated.
1559  * Leases at front of the list will expire first. (Assume all leases have
1560  * similar duration)
1561  *
1562  * Called under dentry->d_lock.
1563  */
1564 void __ceph_dentry_lease_touch(struct ceph_dentry_info *di)
1565 {
1566 	struct dentry *dn = di->dentry;
1567 	struct ceph_mds_client *mdsc = ceph_sb_to_fs_client(dn->d_sb)->mdsc;
1568 	struct ceph_client *cl = mdsc->fsc->client;
1569 
1570 	doutc(cl, "%p %p '%pd'\n", di, dn, dn);
1571 
1572 	di->flags |= CEPH_DENTRY_LEASE_LIST;
1573 	if (di->flags & CEPH_DENTRY_SHRINK_LIST) {
1574 		di->flags |= CEPH_DENTRY_REFERENCED;
1575 		return;
1576 	}
1577 
1578 	spin_lock(&mdsc->dentry_list_lock);
1579 	list_move_tail(&di->lease_list, &mdsc->dentry_leases);
1580 	spin_unlock(&mdsc->dentry_list_lock);
1581 }
1582 
1583 static void __dentry_dir_lease_touch(struct ceph_mds_client* mdsc,
1584 				     struct ceph_dentry_info *di)
1585 {
1586 	di->flags &= ~(CEPH_DENTRY_LEASE_LIST | CEPH_DENTRY_REFERENCED);
1587 	di->lease_gen = 0;
1588 	di->time = jiffies;
1589 	list_move_tail(&di->lease_list, &mdsc->dentry_dir_leases);
1590 }
1591 
1592 /*
1593  * When dir lease is used, add dentry to tail of mdsc->dentry_dir_leases
1594  * list if it's not in the list, otherwise set 'referenced' flag.
1595  *
1596  * Called under dentry->d_lock.
1597  */
1598 void __ceph_dentry_dir_lease_touch(struct ceph_dentry_info *di)
1599 {
1600 	struct dentry *dn = di->dentry;
1601 	struct ceph_mds_client *mdsc = ceph_sb_to_fs_client(dn->d_sb)->mdsc;
1602 	struct ceph_client *cl = mdsc->fsc->client;
1603 
1604 	doutc(cl, "%p %p '%pd' (offset 0x%llx)\n", di, dn, dn, di->offset);
1605 
1606 	if (!list_empty(&di->lease_list)) {
1607 		if (di->flags & CEPH_DENTRY_LEASE_LIST) {
1608 			/* don't remove dentry from dentry lease list
1609 			 * if its lease is valid */
1610 			if (__dentry_lease_is_valid(di))
1611 				return;
1612 		} else {
1613 			di->flags |= CEPH_DENTRY_REFERENCED;
1614 			return;
1615 		}
1616 	}
1617 
1618 	if (di->flags & CEPH_DENTRY_SHRINK_LIST) {
1619 		di->flags |= CEPH_DENTRY_REFERENCED;
1620 		di->flags &= ~CEPH_DENTRY_LEASE_LIST;
1621 		return;
1622 	}
1623 
1624 	spin_lock(&mdsc->dentry_list_lock);
1625 	__dentry_dir_lease_touch(mdsc, di);
1626 	spin_unlock(&mdsc->dentry_list_lock);
1627 }
1628 
1629 static void __dentry_lease_unlist(struct ceph_dentry_info *di)
1630 {
1631 	struct ceph_mds_client *mdsc;
1632 	if (di->flags & CEPH_DENTRY_SHRINK_LIST)
1633 		return;
1634 	if (list_empty(&di->lease_list))
1635 		return;
1636 
1637 	mdsc = ceph_sb_to_fs_client(di->dentry->d_sb)->mdsc;
1638 	spin_lock(&mdsc->dentry_list_lock);
1639 	list_del_init(&di->lease_list);
1640 	spin_unlock(&mdsc->dentry_list_lock);
1641 }
1642 
1643 /*
1644  * Result of __dir_lease_check() and __dentry_lease_check().
1645  */
1646 enum lease_check_result {
1647 	KEEP,
1648 	DELETE,
1649 	TOUCH,
1650 	STOP,
1651 };
1652 
1653 struct ceph_lease_walk_control {
1654 	bool dir_lease;
1655 	bool expire_dir_lease;
1656 	unsigned long nr_to_scan;
1657 	unsigned long dir_lease_ttl;
1658 };
1659 
1660 static enum lease_check_result __dir_lease_check(const struct dentry *,
1661 						 struct ceph_lease_walk_control *);
1662 static enum lease_check_result __dentry_lease_check(const struct dentry *);
1663 
1664 static unsigned long
1665 __dentry_leases_walk(struct ceph_mds_client *mdsc,
1666 		     struct ceph_lease_walk_control *lwc)
1667 {
1668 	struct ceph_dentry_info *di, *tmp;
1669 	struct dentry *dentry, *last = NULL;
1670 	struct list_head* list;
1671         LIST_HEAD(dispose);
1672 	unsigned long freed = 0;
1673 
1674 	list = lwc->dir_lease ? &mdsc->dentry_dir_leases : &mdsc->dentry_leases;
1675 	spin_lock(&mdsc->dentry_list_lock);
1676 	list_for_each_entry_safe(di, tmp, list, lease_list) {
1677 		enum lease_check_result ret = KEEP;
1678 
1679 		if (!lwc->nr_to_scan)
1680 			break;
1681 		--lwc->nr_to_scan;
1682 
1683 		dentry = di->dentry;
1684 		if (last == dentry)
1685 			break;
1686 
1687 		if (!spin_trylock(&dentry->d_lock))
1688 			continue;
1689 
1690 		if (lockref_is_dead(&dentry->d_lockref)) {
1691 			list_del_init(&di->lease_list);
1692 			goto next;
1693 		}
1694 
1695 		if (lwc->dir_lease)
1696 			ret = __dir_lease_check(dentry, lwc);
1697 		else
1698 			ret = __dentry_lease_check(dentry);
1699 		if (ret == TOUCH) {
1700 			/* move it into tail of dir lease list */
1701 			__dentry_dir_lease_touch(mdsc, di);
1702 			if (!last)
1703 				last = dentry;
1704 		} else if (ret == DELETE) {
1705 			/* stale lease */
1706 			di->flags &= ~CEPH_DENTRY_REFERENCED;
1707 			if (dentry->d_lockref.count > 0) {
1708 				/* update_dentry_lease() will re-add
1709 				 * it to lease list, or
1710 				 * ceph_d_delete() will return 1 when
1711 				 * last reference is dropped */
1712 				list_del_init(&di->lease_list);
1713 			} else {
1714 				di->flags |= CEPH_DENTRY_SHRINK_LIST;
1715 				list_move_tail(&di->lease_list, &dispose);
1716 				dget_dlock(dentry);
1717 			}
1718 		}
1719 next:
1720 		spin_unlock(&dentry->d_lock);
1721 		if (ret == STOP)
1722 			break;
1723 	}
1724 	spin_unlock(&mdsc->dentry_list_lock);
1725 
1726 	while (!list_empty(&dispose)) {
1727 		di = list_first_entry(&dispose, struct ceph_dentry_info,
1728 				      lease_list);
1729 		dentry = di->dentry;
1730 		spin_lock(&dentry->d_lock);
1731 
1732 		list_del_init(&di->lease_list);
1733 		di->flags &= ~CEPH_DENTRY_SHRINK_LIST;
1734 		if (di->flags & CEPH_DENTRY_REFERENCED) {
1735 			spin_lock(&mdsc->dentry_list_lock);
1736 			if (di->flags & CEPH_DENTRY_LEASE_LIST) {
1737 				list_add_tail(&di->lease_list,
1738 					      &mdsc->dentry_leases);
1739 			} else {
1740 				__dentry_dir_lease_touch(mdsc, di);
1741 			}
1742 			spin_unlock(&mdsc->dentry_list_lock);
1743 		} else {
1744 			freed++;
1745 		}
1746 
1747 		spin_unlock(&dentry->d_lock);
1748 		/* ceph_d_delete() does the trick */
1749 		dput(dentry);
1750 	}
1751 	return freed;
1752 }
1753 
1754 static enum lease_check_result __dentry_lease_check(const struct dentry *dentry)
1755 {
1756 	struct ceph_dentry_info *di = ceph_dentry(dentry);
1757 	int ret;
1758 
1759 	if (__dentry_lease_is_valid(di))
1760 		return STOP;
1761 	ret = __dir_lease_try_check(dentry);
1762 	if (ret == -EBUSY)
1763 		return KEEP;
1764 	if (ret > 0)
1765 		return TOUCH;
1766 	return DELETE;
1767 }
1768 
1769 static enum lease_check_result __dir_lease_check(const struct dentry *dentry,
1770 						 struct ceph_lease_walk_control *lwc)
1771 {
1772 	struct ceph_dentry_info *di = ceph_dentry(dentry);
1773 
1774 	int ret = __dir_lease_try_check(dentry);
1775 	if (ret == -EBUSY)
1776 		return KEEP;
1777 	if (ret > 0) {
1778 		if (time_before(jiffies, di->time + lwc->dir_lease_ttl))
1779 			return STOP;
1780 		if (!lwc->expire_dir_lease)
1781 			return KEEP;
1782 		/* Move dentry to tail of dir lease list if we don't want
1783 		 * to delete it. So dentries in the list are checked in a
1784 		 * round robin manner */
1785 		if (dentry->d_lockref.count > 0 ||
1786 		    (di->flags & CEPH_DENTRY_REFERENCED))
1787 			return TOUCH;
1788 		/* invalidate dir lease */
1789 		di->lease_shared_gen = 0;
1790 	}
1791 	return DELETE;
1792 }
1793 
1794 int ceph_trim_dentries(struct ceph_mds_client *mdsc)
1795 {
1796 	struct ceph_lease_walk_control lwc;
1797 	unsigned long count;
1798 	unsigned long freed;
1799 
1800 	spin_lock(&mdsc->caps_list_lock);
1801         if (mdsc->caps_use_max > 0 &&
1802             mdsc->caps_use_count > mdsc->caps_use_max)
1803 		count = mdsc->caps_use_count - mdsc->caps_use_max;
1804 	else
1805 		count = 0;
1806         spin_unlock(&mdsc->caps_list_lock);
1807 
1808 	lwc.dir_lease = false;
1809 	lwc.nr_to_scan  = CEPH_CAPS_PER_RELEASE * 2;
1810 	freed = __dentry_leases_walk(mdsc, &lwc);
1811 	if (freed > 0 && !lwc.nr_to_scan) /* more invalid leases */
1812 		return -EAGAIN;
1813 
1814 	if (lwc.nr_to_scan < CEPH_CAPS_PER_RELEASE)
1815 		lwc.nr_to_scan = CEPH_CAPS_PER_RELEASE;
1816 
1817 	lwc.dir_lease = true;
1818 	lwc.expire_dir_lease = freed < count;
1819 	lwc.dir_lease_ttl = mdsc->fsc->mount_options->caps_wanted_delay_max * HZ;
1820 	freed +=__dentry_leases_walk(mdsc, &lwc);
1821 	if (freed == 0 && count == 0)
1822 		/* no progress possible currently, retry futile */
1823 		return 0;
1824 
1825 	if (!lwc.nr_to_scan) /* more to check */
1826 		return -EAGAIN;
1827 
1828 	return freed > 0 ? 1 : 0;
1829 }
1830 
1831 /*
1832  * Ensure a dentry lease will no longer revalidate.
1833  */
1834 void ceph_invalidate_dentry_lease(struct dentry *dentry)
1835 {
1836 	struct ceph_dentry_info *di = ceph_dentry(dentry);
1837 	spin_lock(&dentry->d_lock);
1838 	di->time = jiffies;
1839 	di->lease_shared_gen = 0;
1840 	di->flags &= ~CEPH_DENTRY_PRIMARY_LINK;
1841 	__dentry_lease_unlist(di);
1842 	spin_unlock(&dentry->d_lock);
1843 }
1844 
1845 /*
1846  * Check if dentry lease is valid.  If not, delete the lease.  Try to
1847  * renew if the least is more than half up.
1848  */
1849 static bool __dentry_lease_is_valid(struct ceph_dentry_info *di)
1850 {
1851 	struct ceph_mds_session *session;
1852 
1853 	if (!di->lease_gen)
1854 		return false;
1855 
1856 	session = di->lease_session;
1857 	if (session) {
1858 		u32 gen;
1859 		unsigned long ttl;
1860 
1861 		gen = atomic_read(&session->s_cap_gen);
1862 		ttl = session->s_cap_ttl;
1863 
1864 		if (di->lease_gen == gen &&
1865 		    time_before(jiffies, ttl) &&
1866 		    time_before(jiffies, di->time))
1867 			return true;
1868 	}
1869 	di->lease_gen = 0;
1870 	return false;
1871 }
1872 
1873 static int dentry_lease_is_valid(struct dentry *dentry, unsigned int flags)
1874 {
1875 	struct ceph_dentry_info *di;
1876 	struct ceph_mds_session *session = NULL;
1877 	struct ceph_mds_client *mdsc = ceph_sb_to_fs_client(dentry->d_sb)->mdsc;
1878 	struct ceph_client *cl = mdsc->fsc->client;
1879 	u32 seq = 0;
1880 	int valid = 0;
1881 
1882 	spin_lock(&dentry->d_lock);
1883 	di = ceph_dentry(dentry);
1884 	if (di && __dentry_lease_is_valid(di)) {
1885 		valid = 1;
1886 
1887 		if (di->lease_renew_after &&
1888 		    time_after(jiffies, di->lease_renew_after)) {
1889 			/*
1890 			 * We should renew. If we're in RCU walk mode
1891 			 * though, we can't do that so just return
1892 			 * -ECHILD.
1893 			 */
1894 			if (flags & LOOKUP_RCU) {
1895 				valid = -ECHILD;
1896 			} else {
1897 				session = ceph_get_mds_session(di->lease_session);
1898 				seq = di->lease_seq;
1899 				di->lease_renew_after = 0;
1900 				di->lease_renew_from = jiffies;
1901 			}
1902 		}
1903 	}
1904 	spin_unlock(&dentry->d_lock);
1905 
1906 	if (session) {
1907 		ceph_mdsc_lease_send_msg(session, dentry,
1908 					 CEPH_MDS_LEASE_RENEW, seq);
1909 		ceph_put_mds_session(session);
1910 	}
1911 	doutc(cl, "dentry %p = %d\n", dentry, valid);
1912 	return valid;
1913 }
1914 
1915 /*
1916  * Called under dentry->d_lock.
1917  */
1918 static int __dir_lease_try_check(const struct dentry *dentry)
1919 {
1920 	struct ceph_dentry_info *di = ceph_dentry(dentry);
1921 	struct inode *dir;
1922 	struct ceph_inode_info *ci;
1923 	int valid = 0;
1924 
1925 	if (!di->lease_shared_gen)
1926 		return 0;
1927 	if (IS_ROOT(dentry))
1928 		return 0;
1929 
1930 	dir = d_inode(dentry->d_parent);
1931 	ci = ceph_inode(dir);
1932 
1933 	if (spin_trylock(&ci->i_ceph_lock)) {
1934 		if (atomic_read(&ci->i_shared_gen) == di->lease_shared_gen &&
1935 		    __ceph_caps_issued_mask(ci, CEPH_CAP_FILE_SHARED, 0))
1936 			valid = 1;
1937 		spin_unlock(&ci->i_ceph_lock);
1938 	} else {
1939 		valid = -EBUSY;
1940 	}
1941 
1942 	if (!valid)
1943 		di->lease_shared_gen = 0;
1944 	return valid;
1945 }
1946 
1947 /*
1948  * Check if directory-wide content lease/cap is valid.
1949  */
1950 static int dir_lease_is_valid(struct inode *dir, struct dentry *dentry,
1951 			      struct ceph_mds_client *mdsc)
1952 {
1953 	struct ceph_inode_info *ci = ceph_inode(dir);
1954 	struct ceph_client *cl = mdsc->fsc->client;
1955 	int valid;
1956 	int shared_gen;
1957 
1958 	spin_lock(&ci->i_ceph_lock);
1959 	valid = __ceph_caps_issued_mask(ci, CEPH_CAP_FILE_SHARED, 1);
1960 	if (valid) {
1961 		__ceph_touch_fmode(ci, mdsc, CEPH_FILE_MODE_RD);
1962 		shared_gen = atomic_read(&ci->i_shared_gen);
1963 	}
1964 	spin_unlock(&ci->i_ceph_lock);
1965 	if (valid) {
1966 		struct ceph_dentry_info *di;
1967 		spin_lock(&dentry->d_lock);
1968 		di = ceph_dentry(dentry);
1969 		if (dir == d_inode(dentry->d_parent) &&
1970 		    di && di->lease_shared_gen == shared_gen)
1971 			__ceph_dentry_dir_lease_touch(di);
1972 		else
1973 			valid = 0;
1974 		spin_unlock(&dentry->d_lock);
1975 	}
1976 	doutc(cl, "dir %p %llx.%llx v%u dentry %p '%pd' = %d\n", dir,
1977 	      ceph_vinop(dir), (unsigned)atomic_read(&ci->i_shared_gen),
1978 	      dentry, dentry, valid);
1979 	return valid;
1980 }
1981 
1982 /*
1983  * Check if cached dentry can be trusted.
1984  */
1985 static int ceph_d_revalidate(struct inode *dir, const struct qstr *name,
1986 			     struct dentry *dentry, unsigned int flags)
1987 {
1988 	struct ceph_mds_client *mdsc = ceph_sb_to_fs_client(dentry->d_sb)->mdsc;
1989 	struct ceph_client *cl = mdsc->fsc->client;
1990 	int valid = 0;
1991 	struct inode *inode;
1992 
1993 	valid = fscrypt_d_revalidate(dir, name, dentry, flags);
1994 	if (valid <= 0)
1995 		return valid;
1996 
1997 	inode = d_inode_rcu(dentry);
1998 
1999 	doutc(cl, "%p '%pd' inode %p offset 0x%llx nokey %d\n",
2000 	      dentry, dentry, inode, ceph_dentry(dentry)->offset,
2001 	      !!(dentry->d_flags & DCACHE_NOKEY_NAME));
2002 
2003 	mdsc = ceph_sb_to_fs_client(dir->i_sb)->mdsc;
2004 
2005 	/* always trust cached snapped dentries, snapdir dentry */
2006 	if (ceph_in_snap(dir)) {
2007 		doutc(cl, "%p '%pd' inode %p is SNAPPED\n", dentry,
2008 		      dentry, inode);
2009 		valid = 1;
2010 	} else if (inode && ceph_snap(inode) == CEPH_SNAPDIR) {
2011 		valid = 1;
2012 	} else {
2013 		valid = dentry_lease_is_valid(dentry, flags);
2014 		if (valid == -ECHILD)
2015 			return valid;
2016 		if (valid || dir_lease_is_valid(dir, dentry, mdsc)) {
2017 			if (inode)
2018 				valid = ceph_is_any_caps(inode);
2019 			else
2020 				valid = 1;
2021 		}
2022 	}
2023 
2024 	if (!valid) {
2025 		struct ceph_mds_request *req;
2026 		int op, err;
2027 		u32 mask;
2028 
2029 		if (flags & LOOKUP_RCU)
2030 			return -ECHILD;
2031 
2032 		percpu_counter_inc(&mdsc->metric.d_lease_mis);
2033 
2034 		op = ceph_snap(dir) == CEPH_SNAPDIR ?
2035 			CEPH_MDS_OP_LOOKUPSNAP : CEPH_MDS_OP_LOOKUP;
2036 		req = ceph_mdsc_create_request(mdsc, op, USE_ANY_MDS);
2037 		if (!IS_ERR(req)) {
2038 			req->r_dentry = dget(dentry);
2039 			req->r_num_caps = 2;
2040 			req->r_parent = dir;
2041 			ihold(dir);
2042 
2043 			req->r_dname = name;
2044 
2045 			mask = CEPH_STAT_CAP_INODE | CEPH_CAP_AUTH_SHARED;
2046 			if (ceph_security_xattr_wanted(dir))
2047 				mask |= CEPH_CAP_XATTR_SHARED;
2048 			req->r_args.getattr.mask = cpu_to_le32(mask);
2049 
2050 			err = ceph_mdsc_do_request(mdsc, NULL, req);
2051 			switch (err) {
2052 			case 0:
2053 				if (d_really_is_positive(dentry) &&
2054 				    d_inode(dentry) == req->r_target_inode)
2055 					valid = 1;
2056 				break;
2057 			case -ENOENT:
2058 				if (d_really_is_negative(dentry))
2059 					valid = 1;
2060 				fallthrough;
2061 			default:
2062 				break;
2063 			}
2064 			ceph_mdsc_put_request(req);
2065 			doutc(cl, "%p '%pd', lookup result=%d\n", dentry,
2066 			      dentry, err);
2067 		}
2068 	} else {
2069 		percpu_counter_inc(&mdsc->metric.d_lease_hit);
2070 	}
2071 
2072 	doutc(cl, "%p '%pd' %s\n", dentry, dentry, valid ? "valid" : "invalid");
2073 	if (!valid)
2074 		ceph_dir_clear_complete(dir);
2075 	return valid;
2076 }
2077 
2078 /*
2079  * Delete unused dentry that doesn't have valid lease
2080  *
2081  * Called under dentry->d_lock.
2082  */
2083 static int ceph_d_delete(const struct dentry *dentry)
2084 {
2085 	struct ceph_dentry_info *di;
2086 
2087 	/* won't release caps */
2088 	if (d_really_is_negative(dentry))
2089 		return 0;
2090 	if (ceph_in_snap(d_inode(dentry)))
2091 		return 0;
2092 	/* valid lease? */
2093 	di = ceph_dentry(dentry);
2094 	if (di) {
2095 		if (__dentry_lease_is_valid(di))
2096 			return 0;
2097 		if (__dir_lease_try_check(dentry))
2098 			return 0;
2099 	}
2100 	return 1;
2101 }
2102 
2103 /*
2104  * Release our ceph_dentry_info.
2105  */
2106 static void ceph_d_release(struct dentry *dentry)
2107 {
2108 	struct ceph_dentry_info *di = ceph_dentry(dentry);
2109 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(dentry->d_sb);
2110 
2111 	doutc(fsc->client, "dentry %p '%pd'\n", dentry, dentry);
2112 
2113 	atomic64_dec(&fsc->mdsc->metric.total_dentries);
2114 
2115 	spin_lock(&dentry->d_lock);
2116 	__dentry_lease_unlist(di);
2117 	dentry->d_fsdata = NULL;
2118 	spin_unlock(&dentry->d_lock);
2119 
2120 	ceph_put_mds_session(di->lease_session);
2121 	kmem_cache_free(ceph_dentry_cachep, di);
2122 }
2123 
2124 /*
2125  * When the VFS prunes a dentry from the cache, we need to clear the
2126  * complete flag on the parent directory.
2127  *
2128  * Called under dentry->d_lock.
2129  */
2130 static void ceph_d_prune(struct dentry *dentry)
2131 {
2132 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dentry->d_sb);
2133 	struct ceph_client *cl = mdsc->fsc->client;
2134 	struct ceph_inode_info *dir_ci;
2135 	struct ceph_dentry_info *di;
2136 
2137 	doutc(cl, "dentry %p '%pd'\n", dentry, dentry);
2138 
2139 	/* do we have a valid parent? */
2140 	if (IS_ROOT(dentry))
2141 		return;
2142 
2143 	/* we hold d_lock, so d_parent is stable */
2144 	dir_ci = ceph_inode(d_inode(dentry->d_parent));
2145 	if (ceph_snap(&dir_ci->netfs.inode) == CEPH_SNAPDIR)
2146 		return;
2147 
2148 	/* who calls d_delete() should also disable dcache readdir */
2149 	if (d_really_is_negative(dentry))
2150 		return;
2151 
2152 	/* d_fsdata does not get cleared until d_release */
2153 	if (!d_unhashed(dentry)) {
2154 		__ceph_dir_clear_complete(dir_ci);
2155 		return;
2156 	}
2157 
2158 	/* Disable dcache readdir just in case that someone called d_drop()
2159 	 * or d_invalidate(), but MDS didn't revoke CEPH_CAP_FILE_SHARED
2160 	 * properly (dcache readdir is still enabled) */
2161 	di = ceph_dentry(dentry);
2162 	if (di->offset > 0 &&
2163 	    di->lease_shared_gen == atomic_read(&dir_ci->i_shared_gen))
2164 		__ceph_dir_clear_ordered(dir_ci);
2165 }
2166 
2167 /*
2168  * read() on a dir.  This weird interface hack only works if mounted
2169  * with '-o dirstat'.
2170  */
2171 static ssize_t ceph_read_dir(struct file *file, char __user *buf, size_t size,
2172 			     loff_t *ppos)
2173 {
2174 	struct ceph_dir_file_info *dfi = file->private_data;
2175 	struct inode *inode = file_inode(file);
2176 	struct ceph_inode_info *ci = ceph_inode(inode);
2177 	int left;
2178 	const int bufsize = 1024;
2179 
2180 	if (!ceph_test_mount_opt(ceph_sb_to_fs_client(inode->i_sb), DIRSTAT))
2181 		return -EISDIR;
2182 
2183 	if (!dfi->dir_info) {
2184 		dfi->dir_info = kmalloc(bufsize, GFP_KERNEL);
2185 		if (!dfi->dir_info)
2186 			return -ENOMEM;
2187 		dfi->dir_info_len =
2188 			snprintf(dfi->dir_info, bufsize,
2189 				"entries:   %20lld\n"
2190 				" files:    %20lld\n"
2191 				" subdirs:  %20lld\n"
2192 				"rentries:  %20lld\n"
2193 				" rfiles:   %20lld\n"
2194 				" rsubdirs: %20lld\n"
2195 				"rbytes:    %20lld\n"
2196 				"rctime:    %ptSp\n",
2197 				ci->i_files + ci->i_subdirs,
2198 				ci->i_files,
2199 				ci->i_subdirs,
2200 				ci->i_rfiles + ci->i_rsubdirs,
2201 				ci->i_rfiles,
2202 				ci->i_rsubdirs,
2203 				ci->i_rbytes,
2204 				&ci->i_rctime);
2205 	}
2206 
2207 	if (*ppos >= dfi->dir_info_len)
2208 		return 0;
2209 	size = min_t(unsigned, size, dfi->dir_info_len-*ppos);
2210 	left = copy_to_user(buf, dfi->dir_info + *ppos, size);
2211 	if (left == size)
2212 		return -EFAULT;
2213 	*ppos += (size - left);
2214 	return size - left;
2215 }
2216 
2217 
2218 
2219 /*
2220  * Return name hash for a given dentry.  This is dependent on
2221  * the parent directory's hash function.
2222  */
2223 unsigned ceph_dentry_hash(struct inode *dir, struct dentry *dn)
2224 {
2225 	struct ceph_inode_info *dci = ceph_inode(dir);
2226 	unsigned hash;
2227 
2228 	switch (dci->i_dir_layout.dl_dir_hash) {
2229 	case 0:	/* for backward compat */
2230 	case CEPH_STR_HASH_LINUX:
2231 		return dn->d_name.hash;
2232 
2233 	default:
2234 		spin_lock(&dn->d_lock);
2235 		hash = ceph_str_hash(dci->i_dir_layout.dl_dir_hash,
2236 				     dn->d_name.name, dn->d_name.len);
2237 		spin_unlock(&dn->d_lock);
2238 		return hash;
2239 	}
2240 }
2241 
2242 WRAP_DIR_ITER(ceph_readdir) // FIXME!
2243 const struct file_operations ceph_dir_fops = {
2244 	.read = ceph_read_dir,
2245 	.iterate_shared = shared_ceph_readdir,
2246 	.llseek = ceph_dir_llseek,
2247 	.open = ceph_open,
2248 	.release = ceph_release,
2249 	.unlocked_ioctl = ceph_ioctl,
2250 	.compat_ioctl = compat_ptr_ioctl,
2251 	.fsync = ceph_fsync,
2252 	.lock = ceph_lock,
2253 	.flock = ceph_flock,
2254 };
2255 
2256 const struct file_operations ceph_snapdir_fops = {
2257 	.iterate_shared = shared_ceph_readdir,
2258 	.llseek = ceph_dir_llseek,
2259 	.open = ceph_open,
2260 	.release = ceph_release,
2261 };
2262 
2263 const struct inode_operations ceph_dir_iops = {
2264 	.lookup = ceph_lookup,
2265 	.permission = ceph_permission,
2266 	.getattr = ceph_getattr,
2267 	.setattr = ceph_setattr,
2268 	.listxattr = ceph_listxattr,
2269 	.get_inode_acl = ceph_get_acl,
2270 	.set_acl = ceph_set_acl,
2271 	.mknod = ceph_mknod,
2272 	.symlink = ceph_symlink,
2273 	.mkdir = ceph_mkdir,
2274 	.link = ceph_link,
2275 	.unlink = ceph_unlink,
2276 	.rmdir = ceph_unlink,
2277 	.rename = ceph_rename,
2278 	.create = ceph_create,
2279 	.atomic_open = ceph_atomic_open,
2280 };
2281 
2282 const struct inode_operations ceph_snapdir_iops = {
2283 	.lookup = ceph_lookup,
2284 	.permission = ceph_permission,
2285 	.getattr = ceph_getattr,
2286 	.mkdir = ceph_mkdir,
2287 	.rmdir = ceph_unlink,
2288 	.rename = ceph_rename,
2289 };
2290 
2291 const struct dentry_operations ceph_dentry_ops = {
2292 	.d_revalidate = ceph_d_revalidate,
2293 	.d_delete = ceph_d_delete,
2294 	.d_release = ceph_d_release,
2295 	.d_prune = ceph_d_prune,
2296 	.d_init = ceph_d_init,
2297 };
2298