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