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