xref: /openbmc/linux/fs/ceph/mds_client.c (revision ae213c44)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 
4 #include <linux/fs.h>
5 #include <linux/wait.h>
6 #include <linux/slab.h>
7 #include <linux/gfp.h>
8 #include <linux/sched.h>
9 #include <linux/debugfs.h>
10 #include <linux/seq_file.h>
11 #include <linux/ratelimit.h>
12 
13 #include "super.h"
14 #include "mds_client.h"
15 
16 #include <linux/ceph/ceph_features.h>
17 #include <linux/ceph/messenger.h>
18 #include <linux/ceph/decode.h>
19 #include <linux/ceph/pagelist.h>
20 #include <linux/ceph/auth.h>
21 #include <linux/ceph/debugfs.h>
22 
23 #define RECONNECT_MAX_SIZE (INT_MAX - PAGE_SIZE)
24 
25 /*
26  * A cluster of MDS (metadata server) daemons is responsible for
27  * managing the file system namespace (the directory hierarchy and
28  * inodes) and for coordinating shared access to storage.  Metadata is
29  * partitioning hierarchically across a number of servers, and that
30  * partition varies over time as the cluster adjusts the distribution
31  * in order to balance load.
32  *
33  * The MDS client is primarily responsible to managing synchronous
34  * metadata requests for operations like open, unlink, and so forth.
35  * If there is a MDS failure, we find out about it when we (possibly
36  * request and) receive a new MDS map, and can resubmit affected
37  * requests.
38  *
39  * For the most part, though, we take advantage of a lossless
40  * communications channel to the MDS, and do not need to worry about
41  * timing out or resubmitting requests.
42  *
43  * We maintain a stateful "session" with each MDS we interact with.
44  * Within each session, we sent periodic heartbeat messages to ensure
45  * any capabilities or leases we have been issues remain valid.  If
46  * the session times out and goes stale, our leases and capabilities
47  * are no longer valid.
48  */
49 
50 struct ceph_reconnect_state {
51 	struct ceph_mds_session *session;
52 	int nr_caps, nr_realms;
53 	struct ceph_pagelist *pagelist;
54 	unsigned msg_version;
55 	bool allow_multi;
56 };
57 
58 static void __wake_requests(struct ceph_mds_client *mdsc,
59 			    struct list_head *head);
60 static void ceph_cap_release_work(struct work_struct *work);
61 static void ceph_cap_reclaim_work(struct work_struct *work);
62 
63 static const struct ceph_connection_operations mds_con_ops;
64 
65 
66 /*
67  * mds reply parsing
68  */
69 
70 static int parse_reply_info_quota(void **p, void *end,
71 				  struct ceph_mds_reply_info_in *info)
72 {
73 	u8 struct_v, struct_compat;
74 	u32 struct_len;
75 
76 	ceph_decode_8_safe(p, end, struct_v, bad);
77 	ceph_decode_8_safe(p, end, struct_compat, bad);
78 	/* struct_v is expected to be >= 1. we only
79 	 * understand encoding with struct_compat == 1. */
80 	if (!struct_v || struct_compat != 1)
81 		goto bad;
82 	ceph_decode_32_safe(p, end, struct_len, bad);
83 	ceph_decode_need(p, end, struct_len, bad);
84 	end = *p + struct_len;
85 	ceph_decode_64_safe(p, end, info->max_bytes, bad);
86 	ceph_decode_64_safe(p, end, info->max_files, bad);
87 	*p = end;
88 	return 0;
89 bad:
90 	return -EIO;
91 }
92 
93 /*
94  * parse individual inode info
95  */
96 static int parse_reply_info_in(void **p, void *end,
97 			       struct ceph_mds_reply_info_in *info,
98 			       u64 features)
99 {
100 	int err = 0;
101 	u8 struct_v = 0;
102 
103 	if (features == (u64)-1) {
104 		u32 struct_len;
105 		u8 struct_compat;
106 		ceph_decode_8_safe(p, end, struct_v, bad);
107 		ceph_decode_8_safe(p, end, struct_compat, bad);
108 		/* struct_v is expected to be >= 1. we only understand
109 		 * encoding with struct_compat == 1. */
110 		if (!struct_v || struct_compat != 1)
111 			goto bad;
112 		ceph_decode_32_safe(p, end, struct_len, bad);
113 		ceph_decode_need(p, end, struct_len, bad);
114 		end = *p + struct_len;
115 	}
116 
117 	ceph_decode_need(p, end, sizeof(struct ceph_mds_reply_inode), bad);
118 	info->in = *p;
119 	*p += sizeof(struct ceph_mds_reply_inode) +
120 		sizeof(*info->in->fragtree.splits) *
121 		le32_to_cpu(info->in->fragtree.nsplits);
122 
123 	ceph_decode_32_safe(p, end, info->symlink_len, bad);
124 	ceph_decode_need(p, end, info->symlink_len, bad);
125 	info->symlink = *p;
126 	*p += info->symlink_len;
127 
128 	ceph_decode_copy_safe(p, end, &info->dir_layout,
129 			      sizeof(info->dir_layout), bad);
130 	ceph_decode_32_safe(p, end, info->xattr_len, bad);
131 	ceph_decode_need(p, end, info->xattr_len, bad);
132 	info->xattr_data = *p;
133 	*p += info->xattr_len;
134 
135 	if (features == (u64)-1) {
136 		/* inline data */
137 		ceph_decode_64_safe(p, end, info->inline_version, bad);
138 		ceph_decode_32_safe(p, end, info->inline_len, bad);
139 		ceph_decode_need(p, end, info->inline_len, bad);
140 		info->inline_data = *p;
141 		*p += info->inline_len;
142 		/* quota */
143 		err = parse_reply_info_quota(p, end, info);
144 		if (err < 0)
145 			goto out_bad;
146 		/* pool namespace */
147 		ceph_decode_32_safe(p, end, info->pool_ns_len, bad);
148 		if (info->pool_ns_len > 0) {
149 			ceph_decode_need(p, end, info->pool_ns_len, bad);
150 			info->pool_ns_data = *p;
151 			*p += info->pool_ns_len;
152 		}
153 		/* btime, change_attr */
154 		{
155 			struct ceph_timespec btime;
156 			u64 change_attr;
157 			ceph_decode_need(p, end, sizeof(btime), bad);
158 			ceph_decode_copy(p, &btime, sizeof(btime));
159 			ceph_decode_64_safe(p, end, change_attr, bad);
160 		}
161 
162 		/* dir pin */
163 		if (struct_v >= 2) {
164 			ceph_decode_32_safe(p, end, info->dir_pin, bad);
165 		} else {
166 			info->dir_pin = -ENODATA;
167 		}
168 
169 		*p = end;
170 	} else {
171 		if (features & CEPH_FEATURE_MDS_INLINE_DATA) {
172 			ceph_decode_64_safe(p, end, info->inline_version, bad);
173 			ceph_decode_32_safe(p, end, info->inline_len, bad);
174 			ceph_decode_need(p, end, info->inline_len, bad);
175 			info->inline_data = *p;
176 			*p += info->inline_len;
177 		} else
178 			info->inline_version = CEPH_INLINE_NONE;
179 
180 		if (features & CEPH_FEATURE_MDS_QUOTA) {
181 			err = parse_reply_info_quota(p, end, info);
182 			if (err < 0)
183 				goto out_bad;
184 		} else {
185 			info->max_bytes = 0;
186 			info->max_files = 0;
187 		}
188 
189 		info->pool_ns_len = 0;
190 		info->pool_ns_data = NULL;
191 		if (features & CEPH_FEATURE_FS_FILE_LAYOUT_V2) {
192 			ceph_decode_32_safe(p, end, info->pool_ns_len, bad);
193 			if (info->pool_ns_len > 0) {
194 				ceph_decode_need(p, end, info->pool_ns_len, bad);
195 				info->pool_ns_data = *p;
196 				*p += info->pool_ns_len;
197 			}
198 		}
199 
200 		info->dir_pin = -ENODATA;
201 	}
202 	return 0;
203 bad:
204 	err = -EIO;
205 out_bad:
206 	return err;
207 }
208 
209 static int parse_reply_info_dir(void **p, void *end,
210 				struct ceph_mds_reply_dirfrag **dirfrag,
211 				u64 features)
212 {
213 	if (features == (u64)-1) {
214 		u8 struct_v, struct_compat;
215 		u32 struct_len;
216 		ceph_decode_8_safe(p, end, struct_v, bad);
217 		ceph_decode_8_safe(p, end, struct_compat, bad);
218 		/* struct_v is expected to be >= 1. we only understand
219 		 * encoding whose struct_compat == 1. */
220 		if (!struct_v || struct_compat != 1)
221 			goto bad;
222 		ceph_decode_32_safe(p, end, struct_len, bad);
223 		ceph_decode_need(p, end, struct_len, bad);
224 		end = *p + struct_len;
225 	}
226 
227 	ceph_decode_need(p, end, sizeof(**dirfrag), bad);
228 	*dirfrag = *p;
229 	*p += sizeof(**dirfrag) + sizeof(u32) * le32_to_cpu((*dirfrag)->ndist);
230 	if (unlikely(*p > end))
231 		goto bad;
232 	if (features == (u64)-1)
233 		*p = end;
234 	return 0;
235 bad:
236 	return -EIO;
237 }
238 
239 static int parse_reply_info_lease(void **p, void *end,
240 				  struct ceph_mds_reply_lease **lease,
241 				  u64 features)
242 {
243 	if (features == (u64)-1) {
244 		u8 struct_v, struct_compat;
245 		u32 struct_len;
246 		ceph_decode_8_safe(p, end, struct_v, bad);
247 		ceph_decode_8_safe(p, end, struct_compat, bad);
248 		/* struct_v is expected to be >= 1. we only understand
249 		 * encoding whose struct_compat == 1. */
250 		if (!struct_v || struct_compat != 1)
251 			goto bad;
252 		ceph_decode_32_safe(p, end, struct_len, bad);
253 		ceph_decode_need(p, end, struct_len, bad);
254 		end = *p + struct_len;
255 	}
256 
257 	ceph_decode_need(p, end, sizeof(**lease), bad);
258 	*lease = *p;
259 	*p += sizeof(**lease);
260 	if (features == (u64)-1)
261 		*p = end;
262 	return 0;
263 bad:
264 	return -EIO;
265 }
266 
267 /*
268  * parse a normal reply, which may contain a (dir+)dentry and/or a
269  * target inode.
270  */
271 static int parse_reply_info_trace(void **p, void *end,
272 				  struct ceph_mds_reply_info_parsed *info,
273 				  u64 features)
274 {
275 	int err;
276 
277 	if (info->head->is_dentry) {
278 		err = parse_reply_info_in(p, end, &info->diri, features);
279 		if (err < 0)
280 			goto out_bad;
281 
282 		err = parse_reply_info_dir(p, end, &info->dirfrag, features);
283 		if (err < 0)
284 			goto out_bad;
285 
286 		ceph_decode_32_safe(p, end, info->dname_len, bad);
287 		ceph_decode_need(p, end, info->dname_len, bad);
288 		info->dname = *p;
289 		*p += info->dname_len;
290 
291 		err = parse_reply_info_lease(p, end, &info->dlease, features);
292 		if (err < 0)
293 			goto out_bad;
294 	}
295 
296 	if (info->head->is_target) {
297 		err = parse_reply_info_in(p, end, &info->targeti, features);
298 		if (err < 0)
299 			goto out_bad;
300 	}
301 
302 	if (unlikely(*p != end))
303 		goto bad;
304 	return 0;
305 
306 bad:
307 	err = -EIO;
308 out_bad:
309 	pr_err("problem parsing mds trace %d\n", err);
310 	return err;
311 }
312 
313 /*
314  * parse readdir results
315  */
316 static int parse_reply_info_readdir(void **p, void *end,
317 				struct ceph_mds_reply_info_parsed *info,
318 				u64 features)
319 {
320 	u32 num, i = 0;
321 	int err;
322 
323 	err = parse_reply_info_dir(p, end, &info->dir_dir, features);
324 	if (err < 0)
325 		goto out_bad;
326 
327 	ceph_decode_need(p, end, sizeof(num) + 2, bad);
328 	num = ceph_decode_32(p);
329 	{
330 		u16 flags = ceph_decode_16(p);
331 		info->dir_end = !!(flags & CEPH_READDIR_FRAG_END);
332 		info->dir_complete = !!(flags & CEPH_READDIR_FRAG_COMPLETE);
333 		info->hash_order = !!(flags & CEPH_READDIR_HASH_ORDER);
334 		info->offset_hash = !!(flags & CEPH_READDIR_OFFSET_HASH);
335 	}
336 	if (num == 0)
337 		goto done;
338 
339 	BUG_ON(!info->dir_entries);
340 	if ((unsigned long)(info->dir_entries + num) >
341 	    (unsigned long)info->dir_entries + info->dir_buf_size) {
342 		pr_err("dir contents are larger than expected\n");
343 		WARN_ON(1);
344 		goto bad;
345 	}
346 
347 	info->dir_nr = num;
348 	while (num) {
349 		struct ceph_mds_reply_dir_entry *rde = info->dir_entries + i;
350 		/* dentry */
351 		ceph_decode_32_safe(p, end, rde->name_len, bad);
352 		ceph_decode_need(p, end, rde->name_len, bad);
353 		rde->name = *p;
354 		*p += rde->name_len;
355 		dout("parsed dir dname '%.*s'\n", rde->name_len, rde->name);
356 
357 		/* dentry lease */
358 		err = parse_reply_info_lease(p, end, &rde->lease, features);
359 		if (err)
360 			goto out_bad;
361 		/* inode */
362 		err = parse_reply_info_in(p, end, &rde->inode, features);
363 		if (err < 0)
364 			goto out_bad;
365 		/* ceph_readdir_prepopulate() will update it */
366 		rde->offset = 0;
367 		i++;
368 		num--;
369 	}
370 
371 done:
372 	if (*p != end)
373 		goto bad;
374 	return 0;
375 
376 bad:
377 	err = -EIO;
378 out_bad:
379 	pr_err("problem parsing dir contents %d\n", err);
380 	return err;
381 }
382 
383 /*
384  * parse fcntl F_GETLK results
385  */
386 static int parse_reply_info_filelock(void **p, void *end,
387 				     struct ceph_mds_reply_info_parsed *info,
388 				     u64 features)
389 {
390 	if (*p + sizeof(*info->filelock_reply) > end)
391 		goto bad;
392 
393 	info->filelock_reply = *p;
394 	*p += sizeof(*info->filelock_reply);
395 
396 	if (unlikely(*p != end))
397 		goto bad;
398 	return 0;
399 
400 bad:
401 	return -EIO;
402 }
403 
404 /*
405  * parse create results
406  */
407 static int parse_reply_info_create(void **p, void *end,
408 				  struct ceph_mds_reply_info_parsed *info,
409 				  u64 features)
410 {
411 	if (features == (u64)-1 ||
412 	    (features & CEPH_FEATURE_REPLY_CREATE_INODE)) {
413 		if (*p == end) {
414 			info->has_create_ino = false;
415 		} else {
416 			info->has_create_ino = true;
417 			info->ino = ceph_decode_64(p);
418 		}
419 	}
420 
421 	if (unlikely(*p != end))
422 		goto bad;
423 	return 0;
424 
425 bad:
426 	return -EIO;
427 }
428 
429 /*
430  * parse extra results
431  */
432 static int parse_reply_info_extra(void **p, void *end,
433 				  struct ceph_mds_reply_info_parsed *info,
434 				  u64 features)
435 {
436 	u32 op = le32_to_cpu(info->head->op);
437 
438 	if (op == CEPH_MDS_OP_GETFILELOCK)
439 		return parse_reply_info_filelock(p, end, info, features);
440 	else if (op == CEPH_MDS_OP_READDIR || op == CEPH_MDS_OP_LSSNAP)
441 		return parse_reply_info_readdir(p, end, info, features);
442 	else if (op == CEPH_MDS_OP_CREATE)
443 		return parse_reply_info_create(p, end, info, features);
444 	else
445 		return -EIO;
446 }
447 
448 /*
449  * parse entire mds reply
450  */
451 static int parse_reply_info(struct ceph_msg *msg,
452 			    struct ceph_mds_reply_info_parsed *info,
453 			    u64 features)
454 {
455 	void *p, *end;
456 	u32 len;
457 	int err;
458 
459 	info->head = msg->front.iov_base;
460 	p = msg->front.iov_base + sizeof(struct ceph_mds_reply_head);
461 	end = p + msg->front.iov_len - sizeof(struct ceph_mds_reply_head);
462 
463 	/* trace */
464 	ceph_decode_32_safe(&p, end, len, bad);
465 	if (len > 0) {
466 		ceph_decode_need(&p, end, len, bad);
467 		err = parse_reply_info_trace(&p, p+len, info, features);
468 		if (err < 0)
469 			goto out_bad;
470 	}
471 
472 	/* extra */
473 	ceph_decode_32_safe(&p, end, len, bad);
474 	if (len > 0) {
475 		ceph_decode_need(&p, end, len, bad);
476 		err = parse_reply_info_extra(&p, p+len, info, features);
477 		if (err < 0)
478 			goto out_bad;
479 	}
480 
481 	/* snap blob */
482 	ceph_decode_32_safe(&p, end, len, bad);
483 	info->snapblob_len = len;
484 	info->snapblob = p;
485 	p += len;
486 
487 	if (p != end)
488 		goto bad;
489 	return 0;
490 
491 bad:
492 	err = -EIO;
493 out_bad:
494 	pr_err("mds parse_reply err %d\n", err);
495 	return err;
496 }
497 
498 static void destroy_reply_info(struct ceph_mds_reply_info_parsed *info)
499 {
500 	if (!info->dir_entries)
501 		return;
502 	free_pages((unsigned long)info->dir_entries, get_order(info->dir_buf_size));
503 }
504 
505 
506 /*
507  * sessions
508  */
509 const char *ceph_session_state_name(int s)
510 {
511 	switch (s) {
512 	case CEPH_MDS_SESSION_NEW: return "new";
513 	case CEPH_MDS_SESSION_OPENING: return "opening";
514 	case CEPH_MDS_SESSION_OPEN: return "open";
515 	case CEPH_MDS_SESSION_HUNG: return "hung";
516 	case CEPH_MDS_SESSION_CLOSING: return "closing";
517 	case CEPH_MDS_SESSION_RESTARTING: return "restarting";
518 	case CEPH_MDS_SESSION_RECONNECTING: return "reconnecting";
519 	case CEPH_MDS_SESSION_REJECTED: return "rejected";
520 	default: return "???";
521 	}
522 }
523 
524 static struct ceph_mds_session *get_session(struct ceph_mds_session *s)
525 {
526 	if (refcount_inc_not_zero(&s->s_ref)) {
527 		dout("mdsc get_session %p %d -> %d\n", s,
528 		     refcount_read(&s->s_ref)-1, refcount_read(&s->s_ref));
529 		return s;
530 	} else {
531 		dout("mdsc get_session %p 0 -- FAIL\n", s);
532 		return NULL;
533 	}
534 }
535 
536 void ceph_put_mds_session(struct ceph_mds_session *s)
537 {
538 	dout("mdsc put_session %p %d -> %d\n", s,
539 	     refcount_read(&s->s_ref), refcount_read(&s->s_ref)-1);
540 	if (refcount_dec_and_test(&s->s_ref)) {
541 		if (s->s_auth.authorizer)
542 			ceph_auth_destroy_authorizer(s->s_auth.authorizer);
543 		kfree(s);
544 	}
545 }
546 
547 /*
548  * called under mdsc->mutex
549  */
550 struct ceph_mds_session *__ceph_lookup_mds_session(struct ceph_mds_client *mdsc,
551 						   int mds)
552 {
553 	if (mds >= mdsc->max_sessions || !mdsc->sessions[mds])
554 		return NULL;
555 	return get_session(mdsc->sessions[mds]);
556 }
557 
558 static bool __have_session(struct ceph_mds_client *mdsc, int mds)
559 {
560 	if (mds >= mdsc->max_sessions || !mdsc->sessions[mds])
561 		return false;
562 	else
563 		return true;
564 }
565 
566 static int __verify_registered_session(struct ceph_mds_client *mdsc,
567 				       struct ceph_mds_session *s)
568 {
569 	if (s->s_mds >= mdsc->max_sessions ||
570 	    mdsc->sessions[s->s_mds] != s)
571 		return -ENOENT;
572 	return 0;
573 }
574 
575 /*
576  * create+register a new session for given mds.
577  * called under mdsc->mutex.
578  */
579 static struct ceph_mds_session *register_session(struct ceph_mds_client *mdsc,
580 						 int mds)
581 {
582 	struct ceph_mds_session *s;
583 
584 	if (mds >= mdsc->mdsmap->m_num_mds)
585 		return ERR_PTR(-EINVAL);
586 
587 	s = kzalloc(sizeof(*s), GFP_NOFS);
588 	if (!s)
589 		return ERR_PTR(-ENOMEM);
590 
591 	if (mds >= mdsc->max_sessions) {
592 		int newmax = 1 << get_count_order(mds + 1);
593 		struct ceph_mds_session **sa;
594 
595 		dout("%s: realloc to %d\n", __func__, newmax);
596 		sa = kcalloc(newmax, sizeof(void *), GFP_NOFS);
597 		if (!sa)
598 			goto fail_realloc;
599 		if (mdsc->sessions) {
600 			memcpy(sa, mdsc->sessions,
601 			       mdsc->max_sessions * sizeof(void *));
602 			kfree(mdsc->sessions);
603 		}
604 		mdsc->sessions = sa;
605 		mdsc->max_sessions = newmax;
606 	}
607 
608 	dout("%s: mds%d\n", __func__, mds);
609 	s->s_mdsc = mdsc;
610 	s->s_mds = mds;
611 	s->s_state = CEPH_MDS_SESSION_NEW;
612 	s->s_ttl = 0;
613 	s->s_seq = 0;
614 	mutex_init(&s->s_mutex);
615 
616 	ceph_con_init(&s->s_con, s, &mds_con_ops, &mdsc->fsc->client->msgr);
617 
618 	spin_lock_init(&s->s_gen_ttl_lock);
619 	s->s_cap_gen = 1;
620 	s->s_cap_ttl = jiffies - 1;
621 
622 	spin_lock_init(&s->s_cap_lock);
623 	s->s_renew_requested = 0;
624 	s->s_renew_seq = 0;
625 	INIT_LIST_HEAD(&s->s_caps);
626 	s->s_nr_caps = 0;
627 	s->s_trim_caps = 0;
628 	refcount_set(&s->s_ref, 1);
629 	INIT_LIST_HEAD(&s->s_waiting);
630 	INIT_LIST_HEAD(&s->s_unsafe);
631 	s->s_num_cap_releases = 0;
632 	s->s_cap_reconnect = 0;
633 	s->s_cap_iterator = NULL;
634 	INIT_LIST_HEAD(&s->s_cap_releases);
635 	INIT_WORK(&s->s_cap_release_work, ceph_cap_release_work);
636 
637 	INIT_LIST_HEAD(&s->s_cap_flushing);
638 
639 	mdsc->sessions[mds] = s;
640 	atomic_inc(&mdsc->num_sessions);
641 	refcount_inc(&s->s_ref);  /* one ref to sessions[], one to caller */
642 
643 	ceph_con_open(&s->s_con, CEPH_ENTITY_TYPE_MDS, mds,
644 		      ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
645 
646 	return s;
647 
648 fail_realloc:
649 	kfree(s);
650 	return ERR_PTR(-ENOMEM);
651 }
652 
653 /*
654  * called under mdsc->mutex
655  */
656 static void __unregister_session(struct ceph_mds_client *mdsc,
657 			       struct ceph_mds_session *s)
658 {
659 	dout("__unregister_session mds%d %p\n", s->s_mds, s);
660 	BUG_ON(mdsc->sessions[s->s_mds] != s);
661 	mdsc->sessions[s->s_mds] = NULL;
662 	s->s_state = 0;
663 	ceph_con_close(&s->s_con);
664 	ceph_put_mds_session(s);
665 	atomic_dec(&mdsc->num_sessions);
666 }
667 
668 /*
669  * drop session refs in request.
670  *
671  * should be last request ref, or hold mdsc->mutex
672  */
673 static void put_request_session(struct ceph_mds_request *req)
674 {
675 	if (req->r_session) {
676 		ceph_put_mds_session(req->r_session);
677 		req->r_session = NULL;
678 	}
679 }
680 
681 void ceph_mdsc_release_request(struct kref *kref)
682 {
683 	struct ceph_mds_request *req = container_of(kref,
684 						    struct ceph_mds_request,
685 						    r_kref);
686 	destroy_reply_info(&req->r_reply_info);
687 	if (req->r_request)
688 		ceph_msg_put(req->r_request);
689 	if (req->r_reply)
690 		ceph_msg_put(req->r_reply);
691 	if (req->r_inode) {
692 		ceph_put_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
693 		iput(req->r_inode);
694 	}
695 	if (req->r_parent)
696 		ceph_put_cap_refs(ceph_inode(req->r_parent), CEPH_CAP_PIN);
697 	iput(req->r_target_inode);
698 	if (req->r_dentry)
699 		dput(req->r_dentry);
700 	if (req->r_old_dentry)
701 		dput(req->r_old_dentry);
702 	if (req->r_old_dentry_dir) {
703 		/*
704 		 * track (and drop pins for) r_old_dentry_dir
705 		 * separately, since r_old_dentry's d_parent may have
706 		 * changed between the dir mutex being dropped and
707 		 * this request being freed.
708 		 */
709 		ceph_put_cap_refs(ceph_inode(req->r_old_dentry_dir),
710 				  CEPH_CAP_PIN);
711 		iput(req->r_old_dentry_dir);
712 	}
713 	kfree(req->r_path1);
714 	kfree(req->r_path2);
715 	if (req->r_pagelist)
716 		ceph_pagelist_release(req->r_pagelist);
717 	put_request_session(req);
718 	ceph_unreserve_caps(req->r_mdsc, &req->r_caps_reservation);
719 	kfree(req);
720 }
721 
722 DEFINE_RB_FUNCS(request, struct ceph_mds_request, r_tid, r_node)
723 
724 /*
725  * lookup session, bump ref if found.
726  *
727  * called under mdsc->mutex.
728  */
729 static struct ceph_mds_request *
730 lookup_get_request(struct ceph_mds_client *mdsc, u64 tid)
731 {
732 	struct ceph_mds_request *req;
733 
734 	req = lookup_request(&mdsc->request_tree, tid);
735 	if (req)
736 		ceph_mdsc_get_request(req);
737 
738 	return req;
739 }
740 
741 /*
742  * Register an in-flight request, and assign a tid.  Link to directory
743  * are modifying (if any).
744  *
745  * Called under mdsc->mutex.
746  */
747 static void __register_request(struct ceph_mds_client *mdsc,
748 			       struct ceph_mds_request *req,
749 			       struct inode *dir)
750 {
751 	int ret = 0;
752 
753 	req->r_tid = ++mdsc->last_tid;
754 	if (req->r_num_caps) {
755 		ret = ceph_reserve_caps(mdsc, &req->r_caps_reservation,
756 					req->r_num_caps);
757 		if (ret < 0) {
758 			pr_err("__register_request %p "
759 			       "failed to reserve caps: %d\n", req, ret);
760 			/* set req->r_err to fail early from __do_request */
761 			req->r_err = ret;
762 			return;
763 		}
764 	}
765 	dout("__register_request %p tid %lld\n", req, req->r_tid);
766 	ceph_mdsc_get_request(req);
767 	insert_request(&mdsc->request_tree, req);
768 
769 	req->r_uid = current_fsuid();
770 	req->r_gid = current_fsgid();
771 
772 	if (mdsc->oldest_tid == 0 && req->r_op != CEPH_MDS_OP_SETFILELOCK)
773 		mdsc->oldest_tid = req->r_tid;
774 
775 	if (dir) {
776 		ihold(dir);
777 		req->r_unsafe_dir = dir;
778 	}
779 }
780 
781 static void __unregister_request(struct ceph_mds_client *mdsc,
782 				 struct ceph_mds_request *req)
783 {
784 	dout("__unregister_request %p tid %lld\n", req, req->r_tid);
785 
786 	/* Never leave an unregistered request on an unsafe list! */
787 	list_del_init(&req->r_unsafe_item);
788 
789 	if (req->r_tid == mdsc->oldest_tid) {
790 		struct rb_node *p = rb_next(&req->r_node);
791 		mdsc->oldest_tid = 0;
792 		while (p) {
793 			struct ceph_mds_request *next_req =
794 				rb_entry(p, struct ceph_mds_request, r_node);
795 			if (next_req->r_op != CEPH_MDS_OP_SETFILELOCK) {
796 				mdsc->oldest_tid = next_req->r_tid;
797 				break;
798 			}
799 			p = rb_next(p);
800 		}
801 	}
802 
803 	erase_request(&mdsc->request_tree, req);
804 
805 	if (req->r_unsafe_dir  &&
806 	    test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags)) {
807 		struct ceph_inode_info *ci = ceph_inode(req->r_unsafe_dir);
808 		spin_lock(&ci->i_unsafe_lock);
809 		list_del_init(&req->r_unsafe_dir_item);
810 		spin_unlock(&ci->i_unsafe_lock);
811 	}
812 	if (req->r_target_inode &&
813 	    test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags)) {
814 		struct ceph_inode_info *ci = ceph_inode(req->r_target_inode);
815 		spin_lock(&ci->i_unsafe_lock);
816 		list_del_init(&req->r_unsafe_target_item);
817 		spin_unlock(&ci->i_unsafe_lock);
818 	}
819 
820 	if (req->r_unsafe_dir) {
821 		iput(req->r_unsafe_dir);
822 		req->r_unsafe_dir = NULL;
823 	}
824 
825 	complete_all(&req->r_safe_completion);
826 
827 	ceph_mdsc_put_request(req);
828 }
829 
830 /*
831  * Walk back up the dentry tree until we hit a dentry representing a
832  * non-snapshot inode. We do this using the rcu_read_lock (which must be held
833  * when calling this) to ensure that the objects won't disappear while we're
834  * working with them. Once we hit a candidate dentry, we attempt to take a
835  * reference to it, and return that as the result.
836  */
837 static struct inode *get_nonsnap_parent(struct dentry *dentry)
838 {
839 	struct inode *inode = NULL;
840 
841 	while (dentry && !IS_ROOT(dentry)) {
842 		inode = d_inode_rcu(dentry);
843 		if (!inode || ceph_snap(inode) == CEPH_NOSNAP)
844 			break;
845 		dentry = dentry->d_parent;
846 	}
847 	if (inode)
848 		inode = igrab(inode);
849 	return inode;
850 }
851 
852 /*
853  * Choose mds to send request to next.  If there is a hint set in the
854  * request (e.g., due to a prior forward hint from the mds), use that.
855  * Otherwise, consult frag tree and/or caps to identify the
856  * appropriate mds.  If all else fails, choose randomly.
857  *
858  * Called under mdsc->mutex.
859  */
860 static int __choose_mds(struct ceph_mds_client *mdsc,
861 			struct ceph_mds_request *req)
862 {
863 	struct inode *inode;
864 	struct ceph_inode_info *ci;
865 	struct ceph_cap *cap;
866 	int mode = req->r_direct_mode;
867 	int mds = -1;
868 	u32 hash = req->r_direct_hash;
869 	bool is_hash = test_bit(CEPH_MDS_R_DIRECT_IS_HASH, &req->r_req_flags);
870 
871 	/*
872 	 * is there a specific mds we should try?  ignore hint if we have
873 	 * no session and the mds is not up (active or recovering).
874 	 */
875 	if (req->r_resend_mds >= 0 &&
876 	    (__have_session(mdsc, req->r_resend_mds) ||
877 	     ceph_mdsmap_get_state(mdsc->mdsmap, req->r_resend_mds) > 0)) {
878 		dout("choose_mds using resend_mds mds%d\n",
879 		     req->r_resend_mds);
880 		return req->r_resend_mds;
881 	}
882 
883 	if (mode == USE_RANDOM_MDS)
884 		goto random;
885 
886 	inode = NULL;
887 	if (req->r_inode) {
888 		if (ceph_snap(req->r_inode) != CEPH_SNAPDIR) {
889 			inode = req->r_inode;
890 			ihold(inode);
891 		} else {
892 			/* req->r_dentry is non-null for LSSNAP request */
893 			rcu_read_lock();
894 			inode = get_nonsnap_parent(req->r_dentry);
895 			rcu_read_unlock();
896 			dout("__choose_mds using snapdir's parent %p\n", inode);
897 		}
898 	} else if (req->r_dentry) {
899 		/* ignore race with rename; old or new d_parent is okay */
900 		struct dentry *parent;
901 		struct inode *dir;
902 
903 		rcu_read_lock();
904 		parent = req->r_dentry->d_parent;
905 		dir = req->r_parent ? : d_inode_rcu(parent);
906 
907 		if (!dir || dir->i_sb != mdsc->fsc->sb) {
908 			/*  not this fs or parent went negative */
909 			inode = d_inode(req->r_dentry);
910 			if (inode)
911 				ihold(inode);
912 		} else if (ceph_snap(dir) != CEPH_NOSNAP) {
913 			/* direct snapped/virtual snapdir requests
914 			 * based on parent dir inode */
915 			inode = get_nonsnap_parent(parent);
916 			dout("__choose_mds using nonsnap parent %p\n", inode);
917 		} else {
918 			/* dentry target */
919 			inode = d_inode(req->r_dentry);
920 			if (!inode || mode == USE_AUTH_MDS) {
921 				/* dir + name */
922 				inode = igrab(dir);
923 				hash = ceph_dentry_hash(dir, req->r_dentry);
924 				is_hash = true;
925 			} else {
926 				ihold(inode);
927 			}
928 		}
929 		rcu_read_unlock();
930 	}
931 
932 	dout("__choose_mds %p is_hash=%d (%d) mode %d\n", inode, (int)is_hash,
933 	     (int)hash, mode);
934 	if (!inode)
935 		goto random;
936 	ci = ceph_inode(inode);
937 
938 	if (is_hash && S_ISDIR(inode->i_mode)) {
939 		struct ceph_inode_frag frag;
940 		int found;
941 
942 		ceph_choose_frag(ci, hash, &frag, &found);
943 		if (found) {
944 			if (mode == USE_ANY_MDS && frag.ndist > 0) {
945 				u8 r;
946 
947 				/* choose a random replica */
948 				get_random_bytes(&r, 1);
949 				r %= frag.ndist;
950 				mds = frag.dist[r];
951 				dout("choose_mds %p %llx.%llx "
952 				     "frag %u mds%d (%d/%d)\n",
953 				     inode, ceph_vinop(inode),
954 				     frag.frag, mds,
955 				     (int)r, frag.ndist);
956 				if (ceph_mdsmap_get_state(mdsc->mdsmap, mds) >=
957 				    CEPH_MDS_STATE_ACTIVE)
958 					goto out;
959 			}
960 
961 			/* since this file/dir wasn't known to be
962 			 * replicated, then we want to look for the
963 			 * authoritative mds. */
964 			mode = USE_AUTH_MDS;
965 			if (frag.mds >= 0) {
966 				/* choose auth mds */
967 				mds = frag.mds;
968 				dout("choose_mds %p %llx.%llx "
969 				     "frag %u mds%d (auth)\n",
970 				     inode, ceph_vinop(inode), frag.frag, mds);
971 				if (ceph_mdsmap_get_state(mdsc->mdsmap, mds) >=
972 				    CEPH_MDS_STATE_ACTIVE)
973 					goto out;
974 			}
975 		}
976 	}
977 
978 	spin_lock(&ci->i_ceph_lock);
979 	cap = NULL;
980 	if (mode == USE_AUTH_MDS)
981 		cap = ci->i_auth_cap;
982 	if (!cap && !RB_EMPTY_ROOT(&ci->i_caps))
983 		cap = rb_entry(rb_first(&ci->i_caps), struct ceph_cap, ci_node);
984 	if (!cap) {
985 		spin_unlock(&ci->i_ceph_lock);
986 		iput(inode);
987 		goto random;
988 	}
989 	mds = cap->session->s_mds;
990 	dout("choose_mds %p %llx.%llx mds%d (%scap %p)\n",
991 	     inode, ceph_vinop(inode), mds,
992 	     cap == ci->i_auth_cap ? "auth " : "", cap);
993 	spin_unlock(&ci->i_ceph_lock);
994 out:
995 	iput(inode);
996 	return mds;
997 
998 random:
999 	mds = ceph_mdsmap_get_random_mds(mdsc->mdsmap);
1000 	dout("choose_mds chose random mds%d\n", mds);
1001 	return mds;
1002 }
1003 
1004 
1005 /*
1006  * session messages
1007  */
1008 static struct ceph_msg *create_session_msg(u32 op, u64 seq)
1009 {
1010 	struct ceph_msg *msg;
1011 	struct ceph_mds_session_head *h;
1012 
1013 	msg = ceph_msg_new(CEPH_MSG_CLIENT_SESSION, sizeof(*h), GFP_NOFS,
1014 			   false);
1015 	if (!msg) {
1016 		pr_err("create_session_msg ENOMEM creating msg\n");
1017 		return NULL;
1018 	}
1019 	h = msg->front.iov_base;
1020 	h->op = cpu_to_le32(op);
1021 	h->seq = cpu_to_le64(seq);
1022 
1023 	return msg;
1024 }
1025 
1026 static void encode_supported_features(void **p, void *end)
1027 {
1028 	static const unsigned char bits[] = CEPHFS_FEATURES_CLIENT_SUPPORTED;
1029 	static const size_t count = ARRAY_SIZE(bits);
1030 
1031 	if (count > 0) {
1032 		size_t i;
1033 		size_t size = ((size_t)bits[count - 1] + 64) / 64 * 8;
1034 
1035 		BUG_ON(*p + 4 + size > end);
1036 		ceph_encode_32(p, size);
1037 		memset(*p, 0, size);
1038 		for (i = 0; i < count; i++)
1039 			((unsigned char*)(*p))[i / 8] |= 1 << (bits[i] % 8);
1040 		*p += size;
1041 	} else {
1042 		BUG_ON(*p + 4 > end);
1043 		ceph_encode_32(p, 0);
1044 	}
1045 }
1046 
1047 /*
1048  * session message, specialization for CEPH_SESSION_REQUEST_OPEN
1049  * to include additional client metadata fields.
1050  */
1051 static struct ceph_msg *create_session_open_msg(struct ceph_mds_client *mdsc, u64 seq)
1052 {
1053 	struct ceph_msg *msg;
1054 	struct ceph_mds_session_head *h;
1055 	int i = -1;
1056 	int extra_bytes = 0;
1057 	int metadata_key_count = 0;
1058 	struct ceph_options *opt = mdsc->fsc->client->options;
1059 	struct ceph_mount_options *fsopt = mdsc->fsc->mount_options;
1060 	void *p, *end;
1061 
1062 	const char* metadata[][2] = {
1063 		{"hostname", mdsc->nodename},
1064 		{"kernel_version", init_utsname()->release},
1065 		{"entity_id", opt->name ? : ""},
1066 		{"root", fsopt->server_path ? : "/"},
1067 		{NULL, NULL}
1068 	};
1069 
1070 	/* Calculate serialized length of metadata */
1071 	extra_bytes = 4;  /* map length */
1072 	for (i = 0; metadata[i][0]; ++i) {
1073 		extra_bytes += 8 + strlen(metadata[i][0]) +
1074 			strlen(metadata[i][1]);
1075 		metadata_key_count++;
1076 	}
1077 	/* supported feature */
1078 	extra_bytes += 4 + 8;
1079 
1080 	/* Allocate the message */
1081 	msg = ceph_msg_new(CEPH_MSG_CLIENT_SESSION, sizeof(*h) + extra_bytes,
1082 			   GFP_NOFS, false);
1083 	if (!msg) {
1084 		pr_err("create_session_msg ENOMEM creating msg\n");
1085 		return NULL;
1086 	}
1087 	p = msg->front.iov_base;
1088 	end = p + msg->front.iov_len;
1089 
1090 	h = p;
1091 	h->op = cpu_to_le32(CEPH_SESSION_REQUEST_OPEN);
1092 	h->seq = cpu_to_le64(seq);
1093 
1094 	/*
1095 	 * Serialize client metadata into waiting buffer space, using
1096 	 * the format that userspace expects for map<string, string>
1097 	 *
1098 	 * ClientSession messages with metadata are v2
1099 	 */
1100 	msg->hdr.version = cpu_to_le16(3);
1101 	msg->hdr.compat_version = cpu_to_le16(1);
1102 
1103 	/* The write pointer, following the session_head structure */
1104 	p += sizeof(*h);
1105 
1106 	/* Number of entries in the map */
1107 	ceph_encode_32(&p, metadata_key_count);
1108 
1109 	/* Two length-prefixed strings for each entry in the map */
1110 	for (i = 0; metadata[i][0]; ++i) {
1111 		size_t const key_len = strlen(metadata[i][0]);
1112 		size_t const val_len = strlen(metadata[i][1]);
1113 
1114 		ceph_encode_32(&p, key_len);
1115 		memcpy(p, metadata[i][0], key_len);
1116 		p += key_len;
1117 		ceph_encode_32(&p, val_len);
1118 		memcpy(p, metadata[i][1], val_len);
1119 		p += val_len;
1120 	}
1121 
1122 	encode_supported_features(&p, end);
1123 	msg->front.iov_len = p - msg->front.iov_base;
1124 	msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1125 
1126 	return msg;
1127 }
1128 
1129 /*
1130  * send session open request.
1131  *
1132  * called under mdsc->mutex
1133  */
1134 static int __open_session(struct ceph_mds_client *mdsc,
1135 			  struct ceph_mds_session *session)
1136 {
1137 	struct ceph_msg *msg;
1138 	int mstate;
1139 	int mds = session->s_mds;
1140 
1141 	/* wait for mds to go active? */
1142 	mstate = ceph_mdsmap_get_state(mdsc->mdsmap, mds);
1143 	dout("open_session to mds%d (%s)\n", mds,
1144 	     ceph_mds_state_name(mstate));
1145 	session->s_state = CEPH_MDS_SESSION_OPENING;
1146 	session->s_renew_requested = jiffies;
1147 
1148 	/* send connect message */
1149 	msg = create_session_open_msg(mdsc, session->s_seq);
1150 	if (!msg)
1151 		return -ENOMEM;
1152 	ceph_con_send(&session->s_con, msg);
1153 	return 0;
1154 }
1155 
1156 /*
1157  * open sessions for any export targets for the given mds
1158  *
1159  * called under mdsc->mutex
1160  */
1161 static struct ceph_mds_session *
1162 __open_export_target_session(struct ceph_mds_client *mdsc, int target)
1163 {
1164 	struct ceph_mds_session *session;
1165 
1166 	session = __ceph_lookup_mds_session(mdsc, target);
1167 	if (!session) {
1168 		session = register_session(mdsc, target);
1169 		if (IS_ERR(session))
1170 			return session;
1171 	}
1172 	if (session->s_state == CEPH_MDS_SESSION_NEW ||
1173 	    session->s_state == CEPH_MDS_SESSION_CLOSING)
1174 		__open_session(mdsc, session);
1175 
1176 	return session;
1177 }
1178 
1179 struct ceph_mds_session *
1180 ceph_mdsc_open_export_target_session(struct ceph_mds_client *mdsc, int target)
1181 {
1182 	struct ceph_mds_session *session;
1183 
1184 	dout("open_export_target_session to mds%d\n", target);
1185 
1186 	mutex_lock(&mdsc->mutex);
1187 	session = __open_export_target_session(mdsc, target);
1188 	mutex_unlock(&mdsc->mutex);
1189 
1190 	return session;
1191 }
1192 
1193 static void __open_export_target_sessions(struct ceph_mds_client *mdsc,
1194 					  struct ceph_mds_session *session)
1195 {
1196 	struct ceph_mds_info *mi;
1197 	struct ceph_mds_session *ts;
1198 	int i, mds = session->s_mds;
1199 
1200 	if (mds >= mdsc->mdsmap->m_num_mds)
1201 		return;
1202 
1203 	mi = &mdsc->mdsmap->m_info[mds];
1204 	dout("open_export_target_sessions for mds%d (%d targets)\n",
1205 	     session->s_mds, mi->num_export_targets);
1206 
1207 	for (i = 0; i < mi->num_export_targets; i++) {
1208 		ts = __open_export_target_session(mdsc, mi->export_targets[i]);
1209 		if (!IS_ERR(ts))
1210 			ceph_put_mds_session(ts);
1211 	}
1212 }
1213 
1214 void ceph_mdsc_open_export_target_sessions(struct ceph_mds_client *mdsc,
1215 					   struct ceph_mds_session *session)
1216 {
1217 	mutex_lock(&mdsc->mutex);
1218 	__open_export_target_sessions(mdsc, session);
1219 	mutex_unlock(&mdsc->mutex);
1220 }
1221 
1222 /*
1223  * session caps
1224  */
1225 
1226 static void detach_cap_releases(struct ceph_mds_session *session,
1227 				struct list_head *target)
1228 {
1229 	lockdep_assert_held(&session->s_cap_lock);
1230 
1231 	list_splice_init(&session->s_cap_releases, target);
1232 	session->s_num_cap_releases = 0;
1233 	dout("dispose_cap_releases mds%d\n", session->s_mds);
1234 }
1235 
1236 static void dispose_cap_releases(struct ceph_mds_client *mdsc,
1237 				 struct list_head *dispose)
1238 {
1239 	while (!list_empty(dispose)) {
1240 		struct ceph_cap *cap;
1241 		/* zero out the in-progress message */
1242 		cap = list_first_entry(dispose, struct ceph_cap, session_caps);
1243 		list_del(&cap->session_caps);
1244 		ceph_put_cap(mdsc, cap);
1245 	}
1246 }
1247 
1248 static void cleanup_session_requests(struct ceph_mds_client *mdsc,
1249 				     struct ceph_mds_session *session)
1250 {
1251 	struct ceph_mds_request *req;
1252 	struct rb_node *p;
1253 
1254 	dout("cleanup_session_requests mds%d\n", session->s_mds);
1255 	mutex_lock(&mdsc->mutex);
1256 	while (!list_empty(&session->s_unsafe)) {
1257 		req = list_first_entry(&session->s_unsafe,
1258 				       struct ceph_mds_request, r_unsafe_item);
1259 		pr_warn_ratelimited(" dropping unsafe request %llu\n",
1260 				    req->r_tid);
1261 		__unregister_request(mdsc, req);
1262 	}
1263 	/* zero r_attempts, so kick_requests() will re-send requests */
1264 	p = rb_first(&mdsc->request_tree);
1265 	while (p) {
1266 		req = rb_entry(p, struct ceph_mds_request, r_node);
1267 		p = rb_next(p);
1268 		if (req->r_session &&
1269 		    req->r_session->s_mds == session->s_mds)
1270 			req->r_attempts = 0;
1271 	}
1272 	mutex_unlock(&mdsc->mutex);
1273 }
1274 
1275 /*
1276  * Helper to safely iterate over all caps associated with a session, with
1277  * special care taken to handle a racing __ceph_remove_cap().
1278  *
1279  * Caller must hold session s_mutex.
1280  */
1281 int ceph_iterate_session_caps(struct ceph_mds_session *session,
1282 			      int (*cb)(struct inode *, struct ceph_cap *,
1283 					void *), void *arg)
1284 {
1285 	struct list_head *p;
1286 	struct ceph_cap *cap;
1287 	struct inode *inode, *last_inode = NULL;
1288 	struct ceph_cap *old_cap = NULL;
1289 	int ret;
1290 
1291 	dout("iterate_session_caps %p mds%d\n", session, session->s_mds);
1292 	spin_lock(&session->s_cap_lock);
1293 	p = session->s_caps.next;
1294 	while (p != &session->s_caps) {
1295 		cap = list_entry(p, struct ceph_cap, session_caps);
1296 		inode = igrab(&cap->ci->vfs_inode);
1297 		if (!inode) {
1298 			p = p->next;
1299 			continue;
1300 		}
1301 		session->s_cap_iterator = cap;
1302 		spin_unlock(&session->s_cap_lock);
1303 
1304 		if (last_inode) {
1305 			iput(last_inode);
1306 			last_inode = NULL;
1307 		}
1308 		if (old_cap) {
1309 			ceph_put_cap(session->s_mdsc, old_cap);
1310 			old_cap = NULL;
1311 		}
1312 
1313 		ret = cb(inode, cap, arg);
1314 		last_inode = inode;
1315 
1316 		spin_lock(&session->s_cap_lock);
1317 		p = p->next;
1318 		if (!cap->ci) {
1319 			dout("iterate_session_caps  finishing cap %p removal\n",
1320 			     cap);
1321 			BUG_ON(cap->session != session);
1322 			cap->session = NULL;
1323 			list_del_init(&cap->session_caps);
1324 			session->s_nr_caps--;
1325 			if (cap->queue_release)
1326 				__ceph_queue_cap_release(session, cap);
1327 			else
1328 				old_cap = cap;  /* put_cap it w/o locks held */
1329 		}
1330 		if (ret < 0)
1331 			goto out;
1332 	}
1333 	ret = 0;
1334 out:
1335 	session->s_cap_iterator = NULL;
1336 	spin_unlock(&session->s_cap_lock);
1337 
1338 	iput(last_inode);
1339 	if (old_cap)
1340 		ceph_put_cap(session->s_mdsc, old_cap);
1341 
1342 	return ret;
1343 }
1344 
1345 static int remove_session_caps_cb(struct inode *inode, struct ceph_cap *cap,
1346 				  void *arg)
1347 {
1348 	struct ceph_fs_client *fsc = (struct ceph_fs_client *)arg;
1349 	struct ceph_inode_info *ci = ceph_inode(inode);
1350 	LIST_HEAD(to_remove);
1351 	bool drop = false;
1352 	bool invalidate = false;
1353 
1354 	dout("removing cap %p, ci is %p, inode is %p\n",
1355 	     cap, ci, &ci->vfs_inode);
1356 	spin_lock(&ci->i_ceph_lock);
1357 	if (cap->mds_wanted | cap->issued)
1358 		ci->i_ceph_flags |= CEPH_I_CAP_DROPPED;
1359 	__ceph_remove_cap(cap, false);
1360 	if (!ci->i_auth_cap) {
1361 		struct ceph_cap_flush *cf;
1362 		struct ceph_mds_client *mdsc = fsc->mdsc;
1363 
1364 		if (ci->i_wrbuffer_ref > 0 &&
1365 		    READ_ONCE(fsc->mount_state) == CEPH_MOUNT_SHUTDOWN)
1366 			invalidate = true;
1367 
1368 		while (!list_empty(&ci->i_cap_flush_list)) {
1369 			cf = list_first_entry(&ci->i_cap_flush_list,
1370 					      struct ceph_cap_flush, i_list);
1371 			list_move(&cf->i_list, &to_remove);
1372 		}
1373 
1374 		spin_lock(&mdsc->cap_dirty_lock);
1375 
1376 		list_for_each_entry(cf, &to_remove, i_list)
1377 			list_del(&cf->g_list);
1378 
1379 		if (!list_empty(&ci->i_dirty_item)) {
1380 			pr_warn_ratelimited(
1381 				" dropping dirty %s state for %p %lld\n",
1382 				ceph_cap_string(ci->i_dirty_caps),
1383 				inode, ceph_ino(inode));
1384 			ci->i_dirty_caps = 0;
1385 			list_del_init(&ci->i_dirty_item);
1386 			drop = true;
1387 		}
1388 		if (!list_empty(&ci->i_flushing_item)) {
1389 			pr_warn_ratelimited(
1390 				" dropping dirty+flushing %s state for %p %lld\n",
1391 				ceph_cap_string(ci->i_flushing_caps),
1392 				inode, ceph_ino(inode));
1393 			ci->i_flushing_caps = 0;
1394 			list_del_init(&ci->i_flushing_item);
1395 			mdsc->num_cap_flushing--;
1396 			drop = true;
1397 		}
1398 		spin_unlock(&mdsc->cap_dirty_lock);
1399 
1400 		if (atomic_read(&ci->i_filelock_ref) > 0) {
1401 			/* make further file lock syscall return -EIO */
1402 			ci->i_ceph_flags |= CEPH_I_ERROR_FILELOCK;
1403 			pr_warn_ratelimited(" dropping file locks for %p %lld\n",
1404 					    inode, ceph_ino(inode));
1405 		}
1406 
1407 		if (!ci->i_dirty_caps && ci->i_prealloc_cap_flush) {
1408 			list_add(&ci->i_prealloc_cap_flush->i_list, &to_remove);
1409 			ci->i_prealloc_cap_flush = NULL;
1410 		}
1411 
1412                if (drop &&
1413                   ci->i_wrbuffer_ref_head == 0 &&
1414                   ci->i_wr_ref == 0 &&
1415                   ci->i_dirty_caps == 0 &&
1416                   ci->i_flushing_caps == 0) {
1417                       ceph_put_snap_context(ci->i_head_snapc);
1418                       ci->i_head_snapc = NULL;
1419                }
1420 	}
1421 	spin_unlock(&ci->i_ceph_lock);
1422 	while (!list_empty(&to_remove)) {
1423 		struct ceph_cap_flush *cf;
1424 		cf = list_first_entry(&to_remove,
1425 				      struct ceph_cap_flush, i_list);
1426 		list_del(&cf->i_list);
1427 		ceph_free_cap_flush(cf);
1428 	}
1429 
1430 	wake_up_all(&ci->i_cap_wq);
1431 	if (invalidate)
1432 		ceph_queue_invalidate(inode);
1433 	if (drop)
1434 		iput(inode);
1435 	return 0;
1436 }
1437 
1438 /*
1439  * caller must hold session s_mutex
1440  */
1441 static void remove_session_caps(struct ceph_mds_session *session)
1442 {
1443 	struct ceph_fs_client *fsc = session->s_mdsc->fsc;
1444 	struct super_block *sb = fsc->sb;
1445 	LIST_HEAD(dispose);
1446 
1447 	dout("remove_session_caps on %p\n", session);
1448 	ceph_iterate_session_caps(session, remove_session_caps_cb, fsc);
1449 
1450 	wake_up_all(&fsc->mdsc->cap_flushing_wq);
1451 
1452 	spin_lock(&session->s_cap_lock);
1453 	if (session->s_nr_caps > 0) {
1454 		struct inode *inode;
1455 		struct ceph_cap *cap, *prev = NULL;
1456 		struct ceph_vino vino;
1457 		/*
1458 		 * iterate_session_caps() skips inodes that are being
1459 		 * deleted, we need to wait until deletions are complete.
1460 		 * __wait_on_freeing_inode() is designed for the job,
1461 		 * but it is not exported, so use lookup inode function
1462 		 * to access it.
1463 		 */
1464 		while (!list_empty(&session->s_caps)) {
1465 			cap = list_entry(session->s_caps.next,
1466 					 struct ceph_cap, session_caps);
1467 			if (cap == prev)
1468 				break;
1469 			prev = cap;
1470 			vino = cap->ci->i_vino;
1471 			spin_unlock(&session->s_cap_lock);
1472 
1473 			inode = ceph_find_inode(sb, vino);
1474 			iput(inode);
1475 
1476 			spin_lock(&session->s_cap_lock);
1477 		}
1478 	}
1479 
1480 	// drop cap expires and unlock s_cap_lock
1481 	detach_cap_releases(session, &dispose);
1482 
1483 	BUG_ON(session->s_nr_caps > 0);
1484 	BUG_ON(!list_empty(&session->s_cap_flushing));
1485 	spin_unlock(&session->s_cap_lock);
1486 	dispose_cap_releases(session->s_mdsc, &dispose);
1487 }
1488 
1489 enum {
1490 	RECONNECT,
1491 	RENEWCAPS,
1492 	FORCE_RO,
1493 };
1494 
1495 /*
1496  * wake up any threads waiting on this session's caps.  if the cap is
1497  * old (didn't get renewed on the client reconnect), remove it now.
1498  *
1499  * caller must hold s_mutex.
1500  */
1501 static int wake_up_session_cb(struct inode *inode, struct ceph_cap *cap,
1502 			      void *arg)
1503 {
1504 	struct ceph_inode_info *ci = ceph_inode(inode);
1505 	unsigned long ev = (unsigned long)arg;
1506 
1507 	if (ev == RECONNECT) {
1508 		spin_lock(&ci->i_ceph_lock);
1509 		ci->i_wanted_max_size = 0;
1510 		ci->i_requested_max_size = 0;
1511 		spin_unlock(&ci->i_ceph_lock);
1512 	} else if (ev == RENEWCAPS) {
1513 		if (cap->cap_gen < cap->session->s_cap_gen) {
1514 			/* mds did not re-issue stale cap */
1515 			spin_lock(&ci->i_ceph_lock);
1516 			cap->issued = cap->implemented = CEPH_CAP_PIN;
1517 			/* make sure mds knows what we want */
1518 			if (__ceph_caps_file_wanted(ci) & ~cap->mds_wanted)
1519 				ci->i_ceph_flags |= CEPH_I_CAP_DROPPED;
1520 			spin_unlock(&ci->i_ceph_lock);
1521 		}
1522 	} else if (ev == FORCE_RO) {
1523 	}
1524 	wake_up_all(&ci->i_cap_wq);
1525 	return 0;
1526 }
1527 
1528 static void wake_up_session_caps(struct ceph_mds_session *session, int ev)
1529 {
1530 	dout("wake_up_session_caps %p mds%d\n", session, session->s_mds);
1531 	ceph_iterate_session_caps(session, wake_up_session_cb,
1532 				  (void *)(unsigned long)ev);
1533 }
1534 
1535 /*
1536  * Send periodic message to MDS renewing all currently held caps.  The
1537  * ack will reset the expiration for all caps from this session.
1538  *
1539  * caller holds s_mutex
1540  */
1541 static int send_renew_caps(struct ceph_mds_client *mdsc,
1542 			   struct ceph_mds_session *session)
1543 {
1544 	struct ceph_msg *msg;
1545 	int state;
1546 
1547 	if (time_after_eq(jiffies, session->s_cap_ttl) &&
1548 	    time_after_eq(session->s_cap_ttl, session->s_renew_requested))
1549 		pr_info("mds%d caps stale\n", session->s_mds);
1550 	session->s_renew_requested = jiffies;
1551 
1552 	/* do not try to renew caps until a recovering mds has reconnected
1553 	 * with its clients. */
1554 	state = ceph_mdsmap_get_state(mdsc->mdsmap, session->s_mds);
1555 	if (state < CEPH_MDS_STATE_RECONNECT) {
1556 		dout("send_renew_caps ignoring mds%d (%s)\n",
1557 		     session->s_mds, ceph_mds_state_name(state));
1558 		return 0;
1559 	}
1560 
1561 	dout("send_renew_caps to mds%d (%s)\n", session->s_mds,
1562 		ceph_mds_state_name(state));
1563 	msg = create_session_msg(CEPH_SESSION_REQUEST_RENEWCAPS,
1564 				 ++session->s_renew_seq);
1565 	if (!msg)
1566 		return -ENOMEM;
1567 	ceph_con_send(&session->s_con, msg);
1568 	return 0;
1569 }
1570 
1571 static int send_flushmsg_ack(struct ceph_mds_client *mdsc,
1572 			     struct ceph_mds_session *session, u64 seq)
1573 {
1574 	struct ceph_msg *msg;
1575 
1576 	dout("send_flushmsg_ack to mds%d (%s)s seq %lld\n",
1577 	     session->s_mds, ceph_session_state_name(session->s_state), seq);
1578 	msg = create_session_msg(CEPH_SESSION_FLUSHMSG_ACK, seq);
1579 	if (!msg)
1580 		return -ENOMEM;
1581 	ceph_con_send(&session->s_con, msg);
1582 	return 0;
1583 }
1584 
1585 
1586 /*
1587  * Note new cap ttl, and any transition from stale -> not stale (fresh?).
1588  *
1589  * Called under session->s_mutex
1590  */
1591 static void renewed_caps(struct ceph_mds_client *mdsc,
1592 			 struct ceph_mds_session *session, int is_renew)
1593 {
1594 	int was_stale;
1595 	int wake = 0;
1596 
1597 	spin_lock(&session->s_cap_lock);
1598 	was_stale = is_renew && time_after_eq(jiffies, session->s_cap_ttl);
1599 
1600 	session->s_cap_ttl = session->s_renew_requested +
1601 		mdsc->mdsmap->m_session_timeout*HZ;
1602 
1603 	if (was_stale) {
1604 		if (time_before(jiffies, session->s_cap_ttl)) {
1605 			pr_info("mds%d caps renewed\n", session->s_mds);
1606 			wake = 1;
1607 		} else {
1608 			pr_info("mds%d caps still stale\n", session->s_mds);
1609 		}
1610 	}
1611 	dout("renewed_caps mds%d ttl now %lu, was %s, now %s\n",
1612 	     session->s_mds, session->s_cap_ttl, was_stale ? "stale" : "fresh",
1613 	     time_before(jiffies, session->s_cap_ttl) ? "stale" : "fresh");
1614 	spin_unlock(&session->s_cap_lock);
1615 
1616 	if (wake)
1617 		wake_up_session_caps(session, RENEWCAPS);
1618 }
1619 
1620 /*
1621  * send a session close request
1622  */
1623 static int request_close_session(struct ceph_mds_client *mdsc,
1624 				 struct ceph_mds_session *session)
1625 {
1626 	struct ceph_msg *msg;
1627 
1628 	dout("request_close_session mds%d state %s seq %lld\n",
1629 	     session->s_mds, ceph_session_state_name(session->s_state),
1630 	     session->s_seq);
1631 	msg = create_session_msg(CEPH_SESSION_REQUEST_CLOSE, session->s_seq);
1632 	if (!msg)
1633 		return -ENOMEM;
1634 	ceph_con_send(&session->s_con, msg);
1635 	return 1;
1636 }
1637 
1638 /*
1639  * Called with s_mutex held.
1640  */
1641 static int __close_session(struct ceph_mds_client *mdsc,
1642 			 struct ceph_mds_session *session)
1643 {
1644 	if (session->s_state >= CEPH_MDS_SESSION_CLOSING)
1645 		return 0;
1646 	session->s_state = CEPH_MDS_SESSION_CLOSING;
1647 	return request_close_session(mdsc, session);
1648 }
1649 
1650 static bool drop_negative_children(struct dentry *dentry)
1651 {
1652 	struct dentry *child;
1653 	bool all_negative = true;
1654 
1655 	if (!d_is_dir(dentry))
1656 		goto out;
1657 
1658 	spin_lock(&dentry->d_lock);
1659 	list_for_each_entry(child, &dentry->d_subdirs, d_child) {
1660 		if (d_really_is_positive(child)) {
1661 			all_negative = false;
1662 			break;
1663 		}
1664 	}
1665 	spin_unlock(&dentry->d_lock);
1666 
1667 	if (all_negative)
1668 		shrink_dcache_parent(dentry);
1669 out:
1670 	return all_negative;
1671 }
1672 
1673 /*
1674  * Trim old(er) caps.
1675  *
1676  * Because we can't cache an inode without one or more caps, we do
1677  * this indirectly: if a cap is unused, we prune its aliases, at which
1678  * point the inode will hopefully get dropped to.
1679  *
1680  * Yes, this is a bit sloppy.  Our only real goal here is to respond to
1681  * memory pressure from the MDS, though, so it needn't be perfect.
1682  */
1683 static int trim_caps_cb(struct inode *inode, struct ceph_cap *cap, void *arg)
1684 {
1685 	struct ceph_mds_session *session = arg;
1686 	struct ceph_inode_info *ci = ceph_inode(inode);
1687 	int used, wanted, oissued, mine;
1688 
1689 	if (session->s_trim_caps <= 0)
1690 		return -1;
1691 
1692 	spin_lock(&ci->i_ceph_lock);
1693 	mine = cap->issued | cap->implemented;
1694 	used = __ceph_caps_used(ci);
1695 	wanted = __ceph_caps_file_wanted(ci);
1696 	oissued = __ceph_caps_issued_other(ci, cap);
1697 
1698 	dout("trim_caps_cb %p cap %p mine %s oissued %s used %s wanted %s\n",
1699 	     inode, cap, ceph_cap_string(mine), ceph_cap_string(oissued),
1700 	     ceph_cap_string(used), ceph_cap_string(wanted));
1701 	if (cap == ci->i_auth_cap) {
1702 		if (ci->i_dirty_caps || ci->i_flushing_caps ||
1703 		    !list_empty(&ci->i_cap_snaps))
1704 			goto out;
1705 		if ((used | wanted) & CEPH_CAP_ANY_WR)
1706 			goto out;
1707 		/* Note: it's possible that i_filelock_ref becomes non-zero
1708 		 * after dropping auth caps. It doesn't hurt because reply
1709 		 * of lock mds request will re-add auth caps. */
1710 		if (atomic_read(&ci->i_filelock_ref) > 0)
1711 			goto out;
1712 	}
1713 	/* The inode has cached pages, but it's no longer used.
1714 	 * we can safely drop it */
1715 	if (wanted == 0 && used == CEPH_CAP_FILE_CACHE &&
1716 	    !(oissued & CEPH_CAP_FILE_CACHE)) {
1717 	  used = 0;
1718 	  oissued = 0;
1719 	}
1720 	if ((used | wanted) & ~oissued & mine)
1721 		goto out;   /* we need these caps */
1722 
1723 	if (oissued) {
1724 		/* we aren't the only cap.. just remove us */
1725 		__ceph_remove_cap(cap, true);
1726 		session->s_trim_caps--;
1727 	} else {
1728 		struct dentry *dentry;
1729 		/* try dropping referring dentries */
1730 		spin_unlock(&ci->i_ceph_lock);
1731 		dentry = d_find_any_alias(inode);
1732 		if (dentry && drop_negative_children(dentry)) {
1733 			int count;
1734 			dput(dentry);
1735 			d_prune_aliases(inode);
1736 			count = atomic_read(&inode->i_count);
1737 			if (count == 1)
1738 				session->s_trim_caps--;
1739 			dout("trim_caps_cb %p cap %p pruned, count now %d\n",
1740 			     inode, cap, count);
1741 		} else {
1742 			dput(dentry);
1743 		}
1744 		return 0;
1745 	}
1746 
1747 out:
1748 	spin_unlock(&ci->i_ceph_lock);
1749 	return 0;
1750 }
1751 
1752 /*
1753  * Trim session cap count down to some max number.
1754  */
1755 int ceph_trim_caps(struct ceph_mds_client *mdsc,
1756 		   struct ceph_mds_session *session,
1757 		   int max_caps)
1758 {
1759 	int trim_caps = session->s_nr_caps - max_caps;
1760 
1761 	dout("trim_caps mds%d start: %d / %d, trim %d\n",
1762 	     session->s_mds, session->s_nr_caps, max_caps, trim_caps);
1763 	if (trim_caps > 0) {
1764 		session->s_trim_caps = trim_caps;
1765 		ceph_iterate_session_caps(session, trim_caps_cb, session);
1766 		dout("trim_caps mds%d done: %d / %d, trimmed %d\n",
1767 		     session->s_mds, session->s_nr_caps, max_caps,
1768 			trim_caps - session->s_trim_caps);
1769 		session->s_trim_caps = 0;
1770 	}
1771 
1772 	ceph_flush_cap_releases(mdsc, session);
1773 	return 0;
1774 }
1775 
1776 static int check_caps_flush(struct ceph_mds_client *mdsc,
1777 			    u64 want_flush_tid)
1778 {
1779 	int ret = 1;
1780 
1781 	spin_lock(&mdsc->cap_dirty_lock);
1782 	if (!list_empty(&mdsc->cap_flush_list)) {
1783 		struct ceph_cap_flush *cf =
1784 			list_first_entry(&mdsc->cap_flush_list,
1785 					 struct ceph_cap_flush, g_list);
1786 		if (cf->tid <= want_flush_tid) {
1787 			dout("check_caps_flush still flushing tid "
1788 			     "%llu <= %llu\n", cf->tid, want_flush_tid);
1789 			ret = 0;
1790 		}
1791 	}
1792 	spin_unlock(&mdsc->cap_dirty_lock);
1793 	return ret;
1794 }
1795 
1796 /*
1797  * flush all dirty inode data to disk.
1798  *
1799  * returns true if we've flushed through want_flush_tid
1800  */
1801 static void wait_caps_flush(struct ceph_mds_client *mdsc,
1802 			    u64 want_flush_tid)
1803 {
1804 	dout("check_caps_flush want %llu\n", want_flush_tid);
1805 
1806 	wait_event(mdsc->cap_flushing_wq,
1807 		   check_caps_flush(mdsc, want_flush_tid));
1808 
1809 	dout("check_caps_flush ok, flushed thru %llu\n", want_flush_tid);
1810 }
1811 
1812 /*
1813  * called under s_mutex
1814  */
1815 static void ceph_send_cap_releases(struct ceph_mds_client *mdsc,
1816 				   struct ceph_mds_session *session)
1817 {
1818 	struct ceph_msg *msg = NULL;
1819 	struct ceph_mds_cap_release *head;
1820 	struct ceph_mds_cap_item *item;
1821 	struct ceph_osd_client *osdc = &mdsc->fsc->client->osdc;
1822 	struct ceph_cap *cap;
1823 	LIST_HEAD(tmp_list);
1824 	int num_cap_releases;
1825 	__le32	barrier, *cap_barrier;
1826 
1827 	down_read(&osdc->lock);
1828 	barrier = cpu_to_le32(osdc->epoch_barrier);
1829 	up_read(&osdc->lock);
1830 
1831 	spin_lock(&session->s_cap_lock);
1832 again:
1833 	list_splice_init(&session->s_cap_releases, &tmp_list);
1834 	num_cap_releases = session->s_num_cap_releases;
1835 	session->s_num_cap_releases = 0;
1836 	spin_unlock(&session->s_cap_lock);
1837 
1838 	while (!list_empty(&tmp_list)) {
1839 		if (!msg) {
1840 			msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPRELEASE,
1841 					PAGE_SIZE, GFP_NOFS, false);
1842 			if (!msg)
1843 				goto out_err;
1844 			head = msg->front.iov_base;
1845 			head->num = cpu_to_le32(0);
1846 			msg->front.iov_len = sizeof(*head);
1847 
1848 			msg->hdr.version = cpu_to_le16(2);
1849 			msg->hdr.compat_version = cpu_to_le16(1);
1850 		}
1851 
1852 		cap = list_first_entry(&tmp_list, struct ceph_cap,
1853 					session_caps);
1854 		list_del(&cap->session_caps);
1855 		num_cap_releases--;
1856 
1857 		head = msg->front.iov_base;
1858 		put_unaligned_le32(get_unaligned_le32(&head->num) + 1,
1859 				   &head->num);
1860 		item = msg->front.iov_base + msg->front.iov_len;
1861 		item->ino = cpu_to_le64(cap->cap_ino);
1862 		item->cap_id = cpu_to_le64(cap->cap_id);
1863 		item->migrate_seq = cpu_to_le32(cap->mseq);
1864 		item->seq = cpu_to_le32(cap->issue_seq);
1865 		msg->front.iov_len += sizeof(*item);
1866 
1867 		ceph_put_cap(mdsc, cap);
1868 
1869 		if (le32_to_cpu(head->num) == CEPH_CAPS_PER_RELEASE) {
1870 			// Append cap_barrier field
1871 			cap_barrier = msg->front.iov_base + msg->front.iov_len;
1872 			*cap_barrier = barrier;
1873 			msg->front.iov_len += sizeof(*cap_barrier);
1874 
1875 			msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1876 			dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1877 			ceph_con_send(&session->s_con, msg);
1878 			msg = NULL;
1879 		}
1880 	}
1881 
1882 	BUG_ON(num_cap_releases != 0);
1883 
1884 	spin_lock(&session->s_cap_lock);
1885 	if (!list_empty(&session->s_cap_releases))
1886 		goto again;
1887 	spin_unlock(&session->s_cap_lock);
1888 
1889 	if (msg) {
1890 		// Append cap_barrier field
1891 		cap_barrier = msg->front.iov_base + msg->front.iov_len;
1892 		*cap_barrier = barrier;
1893 		msg->front.iov_len += sizeof(*cap_barrier);
1894 
1895 		msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1896 		dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1897 		ceph_con_send(&session->s_con, msg);
1898 	}
1899 	return;
1900 out_err:
1901 	pr_err("send_cap_releases mds%d, failed to allocate message\n",
1902 		session->s_mds);
1903 	spin_lock(&session->s_cap_lock);
1904 	list_splice(&tmp_list, &session->s_cap_releases);
1905 	session->s_num_cap_releases += num_cap_releases;
1906 	spin_unlock(&session->s_cap_lock);
1907 }
1908 
1909 static void ceph_cap_release_work(struct work_struct *work)
1910 {
1911 	struct ceph_mds_session *session =
1912 		container_of(work, struct ceph_mds_session, s_cap_release_work);
1913 
1914 	mutex_lock(&session->s_mutex);
1915 	if (session->s_state == CEPH_MDS_SESSION_OPEN ||
1916 	    session->s_state == CEPH_MDS_SESSION_HUNG)
1917 		ceph_send_cap_releases(session->s_mdsc, session);
1918 	mutex_unlock(&session->s_mutex);
1919 	ceph_put_mds_session(session);
1920 }
1921 
1922 void ceph_flush_cap_releases(struct ceph_mds_client *mdsc,
1923 		             struct ceph_mds_session *session)
1924 {
1925 	if (mdsc->stopping)
1926 		return;
1927 
1928 	get_session(session);
1929 	if (queue_work(mdsc->fsc->cap_wq,
1930 		       &session->s_cap_release_work)) {
1931 		dout("cap release work queued\n");
1932 	} else {
1933 		ceph_put_mds_session(session);
1934 		dout("failed to queue cap release work\n");
1935 	}
1936 }
1937 
1938 /*
1939  * caller holds session->s_cap_lock
1940  */
1941 void __ceph_queue_cap_release(struct ceph_mds_session *session,
1942 			      struct ceph_cap *cap)
1943 {
1944 	list_add_tail(&cap->session_caps, &session->s_cap_releases);
1945 	session->s_num_cap_releases++;
1946 
1947 	if (!(session->s_num_cap_releases % CEPH_CAPS_PER_RELEASE))
1948 		ceph_flush_cap_releases(session->s_mdsc, session);
1949 }
1950 
1951 static void ceph_cap_reclaim_work(struct work_struct *work)
1952 {
1953 	struct ceph_mds_client *mdsc =
1954 		container_of(work, struct ceph_mds_client, cap_reclaim_work);
1955 	int ret = ceph_trim_dentries(mdsc);
1956 	if (ret == -EAGAIN)
1957 		ceph_queue_cap_reclaim_work(mdsc);
1958 }
1959 
1960 void ceph_queue_cap_reclaim_work(struct ceph_mds_client *mdsc)
1961 {
1962 	if (mdsc->stopping)
1963 		return;
1964 
1965         if (queue_work(mdsc->fsc->cap_wq, &mdsc->cap_reclaim_work)) {
1966                 dout("caps reclaim work queued\n");
1967         } else {
1968                 dout("failed to queue caps release work\n");
1969         }
1970 }
1971 
1972 void ceph_reclaim_caps_nr(struct ceph_mds_client *mdsc, int nr)
1973 {
1974 	int val;
1975 	if (!nr)
1976 		return;
1977 	val = atomic_add_return(nr, &mdsc->cap_reclaim_pending);
1978 	if (!(val % CEPH_CAPS_PER_RELEASE)) {
1979 		atomic_set(&mdsc->cap_reclaim_pending, 0);
1980 		ceph_queue_cap_reclaim_work(mdsc);
1981 	}
1982 }
1983 
1984 /*
1985  * requests
1986  */
1987 
1988 int ceph_alloc_readdir_reply_buffer(struct ceph_mds_request *req,
1989 				    struct inode *dir)
1990 {
1991 	struct ceph_inode_info *ci = ceph_inode(dir);
1992 	struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
1993 	struct ceph_mount_options *opt = req->r_mdsc->fsc->mount_options;
1994 	size_t size = sizeof(struct ceph_mds_reply_dir_entry);
1995 	int order, num_entries;
1996 
1997 	spin_lock(&ci->i_ceph_lock);
1998 	num_entries = ci->i_files + ci->i_subdirs;
1999 	spin_unlock(&ci->i_ceph_lock);
2000 	num_entries = max(num_entries, 1);
2001 	num_entries = min(num_entries, opt->max_readdir);
2002 
2003 	order = get_order(size * num_entries);
2004 	while (order >= 0) {
2005 		rinfo->dir_entries = (void*)__get_free_pages(GFP_KERNEL |
2006 							     __GFP_NOWARN,
2007 							     order);
2008 		if (rinfo->dir_entries)
2009 			break;
2010 		order--;
2011 	}
2012 	if (!rinfo->dir_entries)
2013 		return -ENOMEM;
2014 
2015 	num_entries = (PAGE_SIZE << order) / size;
2016 	num_entries = min(num_entries, opt->max_readdir);
2017 
2018 	rinfo->dir_buf_size = PAGE_SIZE << order;
2019 	req->r_num_caps = num_entries + 1;
2020 	req->r_args.readdir.max_entries = cpu_to_le32(num_entries);
2021 	req->r_args.readdir.max_bytes = cpu_to_le32(opt->max_readdir_bytes);
2022 	return 0;
2023 }
2024 
2025 /*
2026  * Create an mds request.
2027  */
2028 struct ceph_mds_request *
2029 ceph_mdsc_create_request(struct ceph_mds_client *mdsc, int op, int mode)
2030 {
2031 	struct ceph_mds_request *req = kzalloc(sizeof(*req), GFP_NOFS);
2032 	struct timespec64 ts;
2033 
2034 	if (!req)
2035 		return ERR_PTR(-ENOMEM);
2036 
2037 	mutex_init(&req->r_fill_mutex);
2038 	req->r_mdsc = mdsc;
2039 	req->r_started = jiffies;
2040 	req->r_resend_mds = -1;
2041 	INIT_LIST_HEAD(&req->r_unsafe_dir_item);
2042 	INIT_LIST_HEAD(&req->r_unsafe_target_item);
2043 	req->r_fmode = -1;
2044 	kref_init(&req->r_kref);
2045 	RB_CLEAR_NODE(&req->r_node);
2046 	INIT_LIST_HEAD(&req->r_wait);
2047 	init_completion(&req->r_completion);
2048 	init_completion(&req->r_safe_completion);
2049 	INIT_LIST_HEAD(&req->r_unsafe_item);
2050 
2051 	ktime_get_coarse_real_ts64(&ts);
2052 	req->r_stamp = timespec64_trunc(ts, mdsc->fsc->sb->s_time_gran);
2053 
2054 	req->r_op = op;
2055 	req->r_direct_mode = mode;
2056 	return req;
2057 }
2058 
2059 /*
2060  * return oldest (lowest) request, tid in request tree, 0 if none.
2061  *
2062  * called under mdsc->mutex.
2063  */
2064 static struct ceph_mds_request *__get_oldest_req(struct ceph_mds_client *mdsc)
2065 {
2066 	if (RB_EMPTY_ROOT(&mdsc->request_tree))
2067 		return NULL;
2068 	return rb_entry(rb_first(&mdsc->request_tree),
2069 			struct ceph_mds_request, r_node);
2070 }
2071 
2072 static inline  u64 __get_oldest_tid(struct ceph_mds_client *mdsc)
2073 {
2074 	return mdsc->oldest_tid;
2075 }
2076 
2077 /*
2078  * Build a dentry's path.  Allocate on heap; caller must kfree.  Based
2079  * on build_path_from_dentry in fs/cifs/dir.c.
2080  *
2081  * If @stop_on_nosnap, generate path relative to the first non-snapped
2082  * inode.
2083  *
2084  * Encode hidden .snap dirs as a double /, i.e.
2085  *   foo/.snap/bar -> foo//bar
2086  */
2087 char *ceph_mdsc_build_path(struct dentry *dentry, int *plen, u64 *pbase,
2088 			   int stop_on_nosnap)
2089 {
2090 	struct dentry *temp;
2091 	char *path;
2092 	int pos;
2093 	unsigned seq;
2094 	u64 base;
2095 
2096 	if (!dentry)
2097 		return ERR_PTR(-EINVAL);
2098 
2099 	path = __getname();
2100 	if (!path)
2101 		return ERR_PTR(-ENOMEM);
2102 retry:
2103 	pos = PATH_MAX - 1;
2104 	path[pos] = '\0';
2105 
2106 	seq = read_seqbegin(&rename_lock);
2107 	rcu_read_lock();
2108 	temp = dentry;
2109 	for (;;) {
2110 		struct inode *inode;
2111 
2112 		spin_lock(&temp->d_lock);
2113 		inode = d_inode(temp);
2114 		if (inode && ceph_snap(inode) == CEPH_SNAPDIR) {
2115 			dout("build_path path+%d: %p SNAPDIR\n",
2116 			     pos, temp);
2117 		} else if (stop_on_nosnap && inode &&
2118 			   ceph_snap(inode) == CEPH_NOSNAP) {
2119 			spin_unlock(&temp->d_lock);
2120 			break;
2121 		} else {
2122 			pos -= temp->d_name.len;
2123 			if (pos < 0) {
2124 				spin_unlock(&temp->d_lock);
2125 				break;
2126 			}
2127 			memcpy(path + pos, temp->d_name.name, temp->d_name.len);
2128 		}
2129 		spin_unlock(&temp->d_lock);
2130 		temp = temp->d_parent;
2131 
2132 		/* Are we at the root? */
2133 		if (IS_ROOT(temp))
2134 			break;
2135 
2136 		/* Are we out of buffer? */
2137 		if (--pos < 0)
2138 			break;
2139 
2140 		path[pos] = '/';
2141 	}
2142 	base = ceph_ino(d_inode(temp));
2143 	rcu_read_unlock();
2144 	if (pos < 0 || read_seqretry(&rename_lock, seq)) {
2145 		pr_err("build_path did not end path lookup where "
2146 		       "expected, pos is %d\n", pos);
2147 		/* presumably this is only possible if racing with a
2148 		   rename of one of the parent directories (we can not
2149 		   lock the dentries above us to prevent this, but
2150 		   retrying should be harmless) */
2151 		goto retry;
2152 	}
2153 
2154 	*pbase = base;
2155 	*plen = PATH_MAX - 1 - pos;
2156 	dout("build_path on %p %d built %llx '%.*s'\n",
2157 	     dentry, d_count(dentry), base, *plen, path + pos);
2158 	return path + pos;
2159 }
2160 
2161 static int build_dentry_path(struct dentry *dentry, struct inode *dir,
2162 			     const char **ppath, int *ppathlen, u64 *pino,
2163 			     bool *pfreepath, bool parent_locked)
2164 {
2165 	char *path;
2166 
2167 	rcu_read_lock();
2168 	if (!dir)
2169 		dir = d_inode_rcu(dentry->d_parent);
2170 	if (dir && parent_locked && ceph_snap(dir) == CEPH_NOSNAP) {
2171 		*pino = ceph_ino(dir);
2172 		rcu_read_unlock();
2173 		*ppath = dentry->d_name.name;
2174 		*ppathlen = dentry->d_name.len;
2175 		return 0;
2176 	}
2177 	rcu_read_unlock();
2178 	path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
2179 	if (IS_ERR(path))
2180 		return PTR_ERR(path);
2181 	*ppath = path;
2182 	*pfreepath = true;
2183 	return 0;
2184 }
2185 
2186 static int build_inode_path(struct inode *inode,
2187 			    const char **ppath, int *ppathlen, u64 *pino,
2188 			    bool *pfreepath)
2189 {
2190 	struct dentry *dentry;
2191 	char *path;
2192 
2193 	if (ceph_snap(inode) == CEPH_NOSNAP) {
2194 		*pino = ceph_ino(inode);
2195 		*ppathlen = 0;
2196 		return 0;
2197 	}
2198 	dentry = d_find_alias(inode);
2199 	path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
2200 	dput(dentry);
2201 	if (IS_ERR(path))
2202 		return PTR_ERR(path);
2203 	*ppath = path;
2204 	*pfreepath = true;
2205 	return 0;
2206 }
2207 
2208 /*
2209  * request arguments may be specified via an inode *, a dentry *, or
2210  * an explicit ino+path.
2211  */
2212 static int set_request_path_attr(struct inode *rinode, struct dentry *rdentry,
2213 				  struct inode *rdiri, const char *rpath,
2214 				  u64 rino, const char **ppath, int *pathlen,
2215 				  u64 *ino, bool *freepath, bool parent_locked)
2216 {
2217 	int r = 0;
2218 
2219 	if (rinode) {
2220 		r = build_inode_path(rinode, ppath, pathlen, ino, freepath);
2221 		dout(" inode %p %llx.%llx\n", rinode, ceph_ino(rinode),
2222 		     ceph_snap(rinode));
2223 	} else if (rdentry) {
2224 		r = build_dentry_path(rdentry, rdiri, ppath, pathlen, ino,
2225 					freepath, parent_locked);
2226 		dout(" dentry %p %llx/%.*s\n", rdentry, *ino, *pathlen,
2227 		     *ppath);
2228 	} else if (rpath || rino) {
2229 		*ino = rino;
2230 		*ppath = rpath;
2231 		*pathlen = rpath ? strlen(rpath) : 0;
2232 		dout(" path %.*s\n", *pathlen, rpath);
2233 	}
2234 
2235 	return r;
2236 }
2237 
2238 /*
2239  * called under mdsc->mutex
2240  */
2241 static struct ceph_msg *create_request_message(struct ceph_mds_client *mdsc,
2242 					       struct ceph_mds_request *req,
2243 					       int mds, bool drop_cap_releases)
2244 {
2245 	struct ceph_msg *msg;
2246 	struct ceph_mds_request_head *head;
2247 	const char *path1 = NULL;
2248 	const char *path2 = NULL;
2249 	u64 ino1 = 0, ino2 = 0;
2250 	int pathlen1 = 0, pathlen2 = 0;
2251 	bool freepath1 = false, freepath2 = false;
2252 	int len;
2253 	u16 releases;
2254 	void *p, *end;
2255 	int ret;
2256 
2257 	ret = set_request_path_attr(req->r_inode, req->r_dentry,
2258 			      req->r_parent, req->r_path1, req->r_ino1.ino,
2259 			      &path1, &pathlen1, &ino1, &freepath1,
2260 			      test_bit(CEPH_MDS_R_PARENT_LOCKED,
2261 					&req->r_req_flags));
2262 	if (ret < 0) {
2263 		msg = ERR_PTR(ret);
2264 		goto out;
2265 	}
2266 
2267 	/* If r_old_dentry is set, then assume that its parent is locked */
2268 	ret = set_request_path_attr(NULL, req->r_old_dentry,
2269 			      req->r_old_dentry_dir,
2270 			      req->r_path2, req->r_ino2.ino,
2271 			      &path2, &pathlen2, &ino2, &freepath2, true);
2272 	if (ret < 0) {
2273 		msg = ERR_PTR(ret);
2274 		goto out_free1;
2275 	}
2276 
2277 	len = sizeof(*head) +
2278 		pathlen1 + pathlen2 + 2*(1 + sizeof(u32) + sizeof(u64)) +
2279 		sizeof(struct ceph_timespec);
2280 
2281 	/* calculate (max) length for cap releases */
2282 	len += sizeof(struct ceph_mds_request_release) *
2283 		(!!req->r_inode_drop + !!req->r_dentry_drop +
2284 		 !!req->r_old_inode_drop + !!req->r_old_dentry_drop);
2285 	if (req->r_dentry_drop)
2286 		len += pathlen1;
2287 	if (req->r_old_dentry_drop)
2288 		len += pathlen2;
2289 
2290 	msg = ceph_msg_new2(CEPH_MSG_CLIENT_REQUEST, len, 1, GFP_NOFS, false);
2291 	if (!msg) {
2292 		msg = ERR_PTR(-ENOMEM);
2293 		goto out_free2;
2294 	}
2295 
2296 	msg->hdr.version = cpu_to_le16(2);
2297 	msg->hdr.tid = cpu_to_le64(req->r_tid);
2298 
2299 	head = msg->front.iov_base;
2300 	p = msg->front.iov_base + sizeof(*head);
2301 	end = msg->front.iov_base + msg->front.iov_len;
2302 
2303 	head->mdsmap_epoch = cpu_to_le32(mdsc->mdsmap->m_epoch);
2304 	head->op = cpu_to_le32(req->r_op);
2305 	head->caller_uid = cpu_to_le32(from_kuid(&init_user_ns, req->r_uid));
2306 	head->caller_gid = cpu_to_le32(from_kgid(&init_user_ns, req->r_gid));
2307 	head->args = req->r_args;
2308 
2309 	ceph_encode_filepath(&p, end, ino1, path1);
2310 	ceph_encode_filepath(&p, end, ino2, path2);
2311 
2312 	/* make note of release offset, in case we need to replay */
2313 	req->r_request_release_offset = p - msg->front.iov_base;
2314 
2315 	/* cap releases */
2316 	releases = 0;
2317 	if (req->r_inode_drop)
2318 		releases += ceph_encode_inode_release(&p,
2319 		      req->r_inode ? req->r_inode : d_inode(req->r_dentry),
2320 		      mds, req->r_inode_drop, req->r_inode_unless, 0);
2321 	if (req->r_dentry_drop)
2322 		releases += ceph_encode_dentry_release(&p, req->r_dentry,
2323 				req->r_parent, mds, req->r_dentry_drop,
2324 				req->r_dentry_unless);
2325 	if (req->r_old_dentry_drop)
2326 		releases += ceph_encode_dentry_release(&p, req->r_old_dentry,
2327 				req->r_old_dentry_dir, mds,
2328 				req->r_old_dentry_drop,
2329 				req->r_old_dentry_unless);
2330 	if (req->r_old_inode_drop)
2331 		releases += ceph_encode_inode_release(&p,
2332 		      d_inode(req->r_old_dentry),
2333 		      mds, req->r_old_inode_drop, req->r_old_inode_unless, 0);
2334 
2335 	if (drop_cap_releases) {
2336 		releases = 0;
2337 		p = msg->front.iov_base + req->r_request_release_offset;
2338 	}
2339 
2340 	head->num_releases = cpu_to_le16(releases);
2341 
2342 	/* time stamp */
2343 	{
2344 		struct ceph_timespec ts;
2345 		ceph_encode_timespec64(&ts, &req->r_stamp);
2346 		ceph_encode_copy(&p, &ts, sizeof(ts));
2347 	}
2348 
2349 	BUG_ON(p > end);
2350 	msg->front.iov_len = p - msg->front.iov_base;
2351 	msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
2352 
2353 	if (req->r_pagelist) {
2354 		struct ceph_pagelist *pagelist = req->r_pagelist;
2355 		ceph_msg_data_add_pagelist(msg, pagelist);
2356 		msg->hdr.data_len = cpu_to_le32(pagelist->length);
2357 	} else {
2358 		msg->hdr.data_len = 0;
2359 	}
2360 
2361 	msg->hdr.data_off = cpu_to_le16(0);
2362 
2363 out_free2:
2364 	if (freepath2)
2365 		ceph_mdsc_free_path((char *)path2, pathlen2);
2366 out_free1:
2367 	if (freepath1)
2368 		ceph_mdsc_free_path((char *)path1, pathlen1);
2369 out:
2370 	return msg;
2371 }
2372 
2373 /*
2374  * called under mdsc->mutex if error, under no mutex if
2375  * success.
2376  */
2377 static void complete_request(struct ceph_mds_client *mdsc,
2378 			     struct ceph_mds_request *req)
2379 {
2380 	if (req->r_callback)
2381 		req->r_callback(mdsc, req);
2382 	complete_all(&req->r_completion);
2383 }
2384 
2385 /*
2386  * called under mdsc->mutex
2387  */
2388 static int __prepare_send_request(struct ceph_mds_client *mdsc,
2389 				  struct ceph_mds_request *req,
2390 				  int mds, bool drop_cap_releases)
2391 {
2392 	struct ceph_mds_request_head *rhead;
2393 	struct ceph_msg *msg;
2394 	int flags = 0;
2395 
2396 	req->r_attempts++;
2397 	if (req->r_inode) {
2398 		struct ceph_cap *cap =
2399 			ceph_get_cap_for_mds(ceph_inode(req->r_inode), mds);
2400 
2401 		if (cap)
2402 			req->r_sent_on_mseq = cap->mseq;
2403 		else
2404 			req->r_sent_on_mseq = -1;
2405 	}
2406 	dout("prepare_send_request %p tid %lld %s (attempt %d)\n", req,
2407 	     req->r_tid, ceph_mds_op_name(req->r_op), req->r_attempts);
2408 
2409 	if (test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags)) {
2410 		void *p;
2411 		/*
2412 		 * Replay.  Do not regenerate message (and rebuild
2413 		 * paths, etc.); just use the original message.
2414 		 * Rebuilding paths will break for renames because
2415 		 * d_move mangles the src name.
2416 		 */
2417 		msg = req->r_request;
2418 		rhead = msg->front.iov_base;
2419 
2420 		flags = le32_to_cpu(rhead->flags);
2421 		flags |= CEPH_MDS_FLAG_REPLAY;
2422 		rhead->flags = cpu_to_le32(flags);
2423 
2424 		if (req->r_target_inode)
2425 			rhead->ino = cpu_to_le64(ceph_ino(req->r_target_inode));
2426 
2427 		rhead->num_retry = req->r_attempts - 1;
2428 
2429 		/* remove cap/dentry releases from message */
2430 		rhead->num_releases = 0;
2431 
2432 		/* time stamp */
2433 		p = msg->front.iov_base + req->r_request_release_offset;
2434 		{
2435 			struct ceph_timespec ts;
2436 			ceph_encode_timespec64(&ts, &req->r_stamp);
2437 			ceph_encode_copy(&p, &ts, sizeof(ts));
2438 		}
2439 
2440 		msg->front.iov_len = p - msg->front.iov_base;
2441 		msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
2442 		return 0;
2443 	}
2444 
2445 	if (req->r_request) {
2446 		ceph_msg_put(req->r_request);
2447 		req->r_request = NULL;
2448 	}
2449 	msg = create_request_message(mdsc, req, mds, drop_cap_releases);
2450 	if (IS_ERR(msg)) {
2451 		req->r_err = PTR_ERR(msg);
2452 		return PTR_ERR(msg);
2453 	}
2454 	req->r_request = msg;
2455 
2456 	rhead = msg->front.iov_base;
2457 	rhead->oldest_client_tid = cpu_to_le64(__get_oldest_tid(mdsc));
2458 	if (test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags))
2459 		flags |= CEPH_MDS_FLAG_REPLAY;
2460 	if (req->r_parent)
2461 		flags |= CEPH_MDS_FLAG_WANT_DENTRY;
2462 	rhead->flags = cpu_to_le32(flags);
2463 	rhead->num_fwd = req->r_num_fwd;
2464 	rhead->num_retry = req->r_attempts - 1;
2465 	rhead->ino = 0;
2466 
2467 	dout(" r_parent = %p\n", req->r_parent);
2468 	return 0;
2469 }
2470 
2471 /*
2472  * send request, or put it on the appropriate wait list.
2473  */
2474 static void __do_request(struct ceph_mds_client *mdsc,
2475 			struct ceph_mds_request *req)
2476 {
2477 	struct ceph_mds_session *session = NULL;
2478 	int mds = -1;
2479 	int err = 0;
2480 
2481 	if (req->r_err || test_bit(CEPH_MDS_R_GOT_RESULT, &req->r_req_flags)) {
2482 		if (test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags))
2483 			__unregister_request(mdsc, req);
2484 		return;
2485 	}
2486 
2487 	if (req->r_timeout &&
2488 	    time_after_eq(jiffies, req->r_started + req->r_timeout)) {
2489 		dout("do_request timed out\n");
2490 		err = -EIO;
2491 		goto finish;
2492 	}
2493 	if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN) {
2494 		dout("do_request forced umount\n");
2495 		err = -EIO;
2496 		goto finish;
2497 	}
2498 	if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_MOUNTING) {
2499 		if (mdsc->mdsmap_err) {
2500 			err = mdsc->mdsmap_err;
2501 			dout("do_request mdsmap err %d\n", err);
2502 			goto finish;
2503 		}
2504 		if (mdsc->mdsmap->m_epoch == 0) {
2505 			dout("do_request no mdsmap, waiting for map\n");
2506 			list_add(&req->r_wait, &mdsc->waiting_for_map);
2507 			return;
2508 		}
2509 		if (!(mdsc->fsc->mount_options->flags &
2510 		      CEPH_MOUNT_OPT_MOUNTWAIT) &&
2511 		    !ceph_mdsmap_is_cluster_available(mdsc->mdsmap)) {
2512 			err = -ENOENT;
2513 			pr_info("probably no mds server is up\n");
2514 			goto finish;
2515 		}
2516 	}
2517 
2518 	put_request_session(req);
2519 
2520 	mds = __choose_mds(mdsc, req);
2521 	if (mds < 0 ||
2522 	    ceph_mdsmap_get_state(mdsc->mdsmap, mds) < CEPH_MDS_STATE_ACTIVE) {
2523 		dout("do_request no mds or not active, waiting for map\n");
2524 		list_add(&req->r_wait, &mdsc->waiting_for_map);
2525 		return;
2526 	}
2527 
2528 	/* get, open session */
2529 	session = __ceph_lookup_mds_session(mdsc, mds);
2530 	if (!session) {
2531 		session = register_session(mdsc, mds);
2532 		if (IS_ERR(session)) {
2533 			err = PTR_ERR(session);
2534 			goto finish;
2535 		}
2536 	}
2537 	req->r_session = get_session(session);
2538 
2539 	dout("do_request mds%d session %p state %s\n", mds, session,
2540 	     ceph_session_state_name(session->s_state));
2541 	if (session->s_state != CEPH_MDS_SESSION_OPEN &&
2542 	    session->s_state != CEPH_MDS_SESSION_HUNG) {
2543 		if (session->s_state == CEPH_MDS_SESSION_REJECTED) {
2544 			err = -EACCES;
2545 			goto out_session;
2546 		}
2547 		if (session->s_state == CEPH_MDS_SESSION_NEW ||
2548 		    session->s_state == CEPH_MDS_SESSION_CLOSING)
2549 			__open_session(mdsc, session);
2550 		list_add(&req->r_wait, &session->s_waiting);
2551 		goto out_session;
2552 	}
2553 
2554 	/* send request */
2555 	req->r_resend_mds = -1;   /* forget any previous mds hint */
2556 
2557 	if (req->r_request_started == 0)   /* note request start time */
2558 		req->r_request_started = jiffies;
2559 
2560 	err = __prepare_send_request(mdsc, req, mds, false);
2561 	if (!err) {
2562 		ceph_msg_get(req->r_request);
2563 		ceph_con_send(&session->s_con, req->r_request);
2564 	}
2565 
2566 out_session:
2567 	ceph_put_mds_session(session);
2568 finish:
2569 	if (err) {
2570 		dout("__do_request early error %d\n", err);
2571 		req->r_err = err;
2572 		complete_request(mdsc, req);
2573 		__unregister_request(mdsc, req);
2574 	}
2575 	return;
2576 }
2577 
2578 /*
2579  * called under mdsc->mutex
2580  */
2581 static void __wake_requests(struct ceph_mds_client *mdsc,
2582 			    struct list_head *head)
2583 {
2584 	struct ceph_mds_request *req;
2585 	LIST_HEAD(tmp_list);
2586 
2587 	list_splice_init(head, &tmp_list);
2588 
2589 	while (!list_empty(&tmp_list)) {
2590 		req = list_entry(tmp_list.next,
2591 				 struct ceph_mds_request, r_wait);
2592 		list_del_init(&req->r_wait);
2593 		dout(" wake request %p tid %llu\n", req, req->r_tid);
2594 		__do_request(mdsc, req);
2595 	}
2596 }
2597 
2598 /*
2599  * Wake up threads with requests pending for @mds, so that they can
2600  * resubmit their requests to a possibly different mds.
2601  */
2602 static void kick_requests(struct ceph_mds_client *mdsc, int mds)
2603 {
2604 	struct ceph_mds_request *req;
2605 	struct rb_node *p = rb_first(&mdsc->request_tree);
2606 
2607 	dout("kick_requests mds%d\n", mds);
2608 	while (p) {
2609 		req = rb_entry(p, struct ceph_mds_request, r_node);
2610 		p = rb_next(p);
2611 		if (test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags))
2612 			continue;
2613 		if (req->r_attempts > 0)
2614 			continue; /* only new requests */
2615 		if (req->r_session &&
2616 		    req->r_session->s_mds == mds) {
2617 			dout(" kicking tid %llu\n", req->r_tid);
2618 			list_del_init(&req->r_wait);
2619 			__do_request(mdsc, req);
2620 		}
2621 	}
2622 }
2623 
2624 int ceph_mdsc_submit_request(struct ceph_mds_client *mdsc, struct inode *dir,
2625 			      struct ceph_mds_request *req)
2626 {
2627 	int err;
2628 
2629 	/* take CAP_PIN refs for r_inode, r_parent, r_old_dentry */
2630 	if (req->r_inode)
2631 		ceph_get_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
2632 	if (req->r_parent)
2633 		ceph_get_cap_refs(ceph_inode(req->r_parent), CEPH_CAP_PIN);
2634 	if (req->r_old_dentry_dir)
2635 		ceph_get_cap_refs(ceph_inode(req->r_old_dentry_dir),
2636 				  CEPH_CAP_PIN);
2637 
2638 	dout("submit_request on %p for inode %p\n", req, dir);
2639 	mutex_lock(&mdsc->mutex);
2640 	__register_request(mdsc, req, dir);
2641 	__do_request(mdsc, req);
2642 	err = req->r_err;
2643 	mutex_unlock(&mdsc->mutex);
2644 	return err;
2645 }
2646 
2647 static int ceph_mdsc_wait_request(struct ceph_mds_client *mdsc,
2648 				  struct ceph_mds_request *req)
2649 {
2650 	int err;
2651 
2652 	/* wait */
2653 	dout("do_request waiting\n");
2654 	if (!req->r_timeout && req->r_wait_for_completion) {
2655 		err = req->r_wait_for_completion(mdsc, req);
2656 	} else {
2657 		long timeleft = wait_for_completion_killable_timeout(
2658 					&req->r_completion,
2659 					ceph_timeout_jiffies(req->r_timeout));
2660 		if (timeleft > 0)
2661 			err = 0;
2662 		else if (!timeleft)
2663 			err = -EIO;  /* timed out */
2664 		else
2665 			err = timeleft;  /* killed */
2666 	}
2667 	dout("do_request waited, got %d\n", err);
2668 	mutex_lock(&mdsc->mutex);
2669 
2670 	/* only abort if we didn't race with a real reply */
2671 	if (test_bit(CEPH_MDS_R_GOT_RESULT, &req->r_req_flags)) {
2672 		err = le32_to_cpu(req->r_reply_info.head->result);
2673 	} else if (err < 0) {
2674 		dout("aborted request %lld with %d\n", req->r_tid, err);
2675 
2676 		/*
2677 		 * ensure we aren't running concurrently with
2678 		 * ceph_fill_trace or ceph_readdir_prepopulate, which
2679 		 * rely on locks (dir mutex) held by our caller.
2680 		 */
2681 		mutex_lock(&req->r_fill_mutex);
2682 		req->r_err = err;
2683 		set_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags);
2684 		mutex_unlock(&req->r_fill_mutex);
2685 
2686 		if (req->r_parent &&
2687 		    (req->r_op & CEPH_MDS_OP_WRITE))
2688 			ceph_invalidate_dir_request(req);
2689 	} else {
2690 		err = req->r_err;
2691 	}
2692 
2693 	mutex_unlock(&mdsc->mutex);
2694 	return err;
2695 }
2696 
2697 /*
2698  * Synchrously perform an mds request.  Take care of all of the
2699  * session setup, forwarding, retry details.
2700  */
2701 int ceph_mdsc_do_request(struct ceph_mds_client *mdsc,
2702 			 struct inode *dir,
2703 			 struct ceph_mds_request *req)
2704 {
2705 	int err;
2706 
2707 	dout("do_request on %p\n", req);
2708 
2709 	/* issue */
2710 	err = ceph_mdsc_submit_request(mdsc, dir, req);
2711 	if (!err)
2712 		err = ceph_mdsc_wait_request(mdsc, req);
2713 	dout("do_request %p done, result %d\n", req, err);
2714 	return err;
2715 }
2716 
2717 /*
2718  * Invalidate dir's completeness, dentry lease state on an aborted MDS
2719  * namespace request.
2720  */
2721 void ceph_invalidate_dir_request(struct ceph_mds_request *req)
2722 {
2723 	struct inode *dir = req->r_parent;
2724 	struct inode *old_dir = req->r_old_dentry_dir;
2725 
2726 	dout("invalidate_dir_request %p %p (complete, lease(s))\n", dir, old_dir);
2727 
2728 	ceph_dir_clear_complete(dir);
2729 	if (old_dir)
2730 		ceph_dir_clear_complete(old_dir);
2731 	if (req->r_dentry)
2732 		ceph_invalidate_dentry_lease(req->r_dentry);
2733 	if (req->r_old_dentry)
2734 		ceph_invalidate_dentry_lease(req->r_old_dentry);
2735 }
2736 
2737 /*
2738  * Handle mds reply.
2739  *
2740  * We take the session mutex and parse and process the reply immediately.
2741  * This preserves the logical ordering of replies, capabilities, etc., sent
2742  * by the MDS as they are applied to our local cache.
2743  */
2744 static void handle_reply(struct ceph_mds_session *session, struct ceph_msg *msg)
2745 {
2746 	struct ceph_mds_client *mdsc = session->s_mdsc;
2747 	struct ceph_mds_request *req;
2748 	struct ceph_mds_reply_head *head = msg->front.iov_base;
2749 	struct ceph_mds_reply_info_parsed *rinfo;  /* parsed reply info */
2750 	struct ceph_snap_realm *realm;
2751 	u64 tid;
2752 	int err, result;
2753 	int mds = session->s_mds;
2754 
2755 	if (msg->front.iov_len < sizeof(*head)) {
2756 		pr_err("mdsc_handle_reply got corrupt (short) reply\n");
2757 		ceph_msg_dump(msg);
2758 		return;
2759 	}
2760 
2761 	/* get request, session */
2762 	tid = le64_to_cpu(msg->hdr.tid);
2763 	mutex_lock(&mdsc->mutex);
2764 	req = lookup_get_request(mdsc, tid);
2765 	if (!req) {
2766 		dout("handle_reply on unknown tid %llu\n", tid);
2767 		mutex_unlock(&mdsc->mutex);
2768 		return;
2769 	}
2770 	dout("handle_reply %p\n", req);
2771 
2772 	/* correct session? */
2773 	if (req->r_session != session) {
2774 		pr_err("mdsc_handle_reply got %llu on session mds%d"
2775 		       " not mds%d\n", tid, session->s_mds,
2776 		       req->r_session ? req->r_session->s_mds : -1);
2777 		mutex_unlock(&mdsc->mutex);
2778 		goto out;
2779 	}
2780 
2781 	/* dup? */
2782 	if ((test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags) && !head->safe) ||
2783 	    (test_bit(CEPH_MDS_R_GOT_SAFE, &req->r_req_flags) && head->safe)) {
2784 		pr_warn("got a dup %s reply on %llu from mds%d\n",
2785 			   head->safe ? "safe" : "unsafe", tid, mds);
2786 		mutex_unlock(&mdsc->mutex);
2787 		goto out;
2788 	}
2789 	if (test_bit(CEPH_MDS_R_GOT_SAFE, &req->r_req_flags)) {
2790 		pr_warn("got unsafe after safe on %llu from mds%d\n",
2791 			   tid, mds);
2792 		mutex_unlock(&mdsc->mutex);
2793 		goto out;
2794 	}
2795 
2796 	result = le32_to_cpu(head->result);
2797 
2798 	/*
2799 	 * Handle an ESTALE
2800 	 * if we're not talking to the authority, send to them
2801 	 * if the authority has changed while we weren't looking,
2802 	 * send to new authority
2803 	 * Otherwise we just have to return an ESTALE
2804 	 */
2805 	if (result == -ESTALE) {
2806 		dout("got ESTALE on request %llu\n", req->r_tid);
2807 		req->r_resend_mds = -1;
2808 		if (req->r_direct_mode != USE_AUTH_MDS) {
2809 			dout("not using auth, setting for that now\n");
2810 			req->r_direct_mode = USE_AUTH_MDS;
2811 			__do_request(mdsc, req);
2812 			mutex_unlock(&mdsc->mutex);
2813 			goto out;
2814 		} else  {
2815 			int mds = __choose_mds(mdsc, req);
2816 			if (mds >= 0 && mds != req->r_session->s_mds) {
2817 				dout("but auth changed, so resending\n");
2818 				__do_request(mdsc, req);
2819 				mutex_unlock(&mdsc->mutex);
2820 				goto out;
2821 			}
2822 		}
2823 		dout("have to return ESTALE on request %llu\n", req->r_tid);
2824 	}
2825 
2826 
2827 	if (head->safe) {
2828 		set_bit(CEPH_MDS_R_GOT_SAFE, &req->r_req_flags);
2829 		__unregister_request(mdsc, req);
2830 
2831 		if (test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags)) {
2832 			/*
2833 			 * We already handled the unsafe response, now do the
2834 			 * cleanup.  No need to examine the response; the MDS
2835 			 * doesn't include any result info in the safe
2836 			 * response.  And even if it did, there is nothing
2837 			 * useful we could do with a revised return value.
2838 			 */
2839 			dout("got safe reply %llu, mds%d\n", tid, mds);
2840 
2841 			/* last unsafe request during umount? */
2842 			if (mdsc->stopping && !__get_oldest_req(mdsc))
2843 				complete_all(&mdsc->safe_umount_waiters);
2844 			mutex_unlock(&mdsc->mutex);
2845 			goto out;
2846 		}
2847 	} else {
2848 		set_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags);
2849 		list_add_tail(&req->r_unsafe_item, &req->r_session->s_unsafe);
2850 		if (req->r_unsafe_dir) {
2851 			struct ceph_inode_info *ci =
2852 					ceph_inode(req->r_unsafe_dir);
2853 			spin_lock(&ci->i_unsafe_lock);
2854 			list_add_tail(&req->r_unsafe_dir_item,
2855 				      &ci->i_unsafe_dirops);
2856 			spin_unlock(&ci->i_unsafe_lock);
2857 		}
2858 	}
2859 
2860 	dout("handle_reply tid %lld result %d\n", tid, result);
2861 	rinfo = &req->r_reply_info;
2862 	if (test_bit(CEPHFS_FEATURE_REPLY_ENCODING, &session->s_features))
2863 		err = parse_reply_info(msg, rinfo, (u64)-1);
2864 	else
2865 		err = parse_reply_info(msg, rinfo, session->s_con.peer_features);
2866 	mutex_unlock(&mdsc->mutex);
2867 
2868 	mutex_lock(&session->s_mutex);
2869 	if (err < 0) {
2870 		pr_err("mdsc_handle_reply got corrupt reply mds%d(tid:%lld)\n", mds, tid);
2871 		ceph_msg_dump(msg);
2872 		goto out_err;
2873 	}
2874 
2875 	/* snap trace */
2876 	realm = NULL;
2877 	if (rinfo->snapblob_len) {
2878 		down_write(&mdsc->snap_rwsem);
2879 		ceph_update_snap_trace(mdsc, rinfo->snapblob,
2880 				rinfo->snapblob + rinfo->snapblob_len,
2881 				le32_to_cpu(head->op) == CEPH_MDS_OP_RMSNAP,
2882 				&realm);
2883 		downgrade_write(&mdsc->snap_rwsem);
2884 	} else {
2885 		down_read(&mdsc->snap_rwsem);
2886 	}
2887 
2888 	/* insert trace into our cache */
2889 	mutex_lock(&req->r_fill_mutex);
2890 	current->journal_info = req;
2891 	err = ceph_fill_trace(mdsc->fsc->sb, req);
2892 	if (err == 0) {
2893 		if (result == 0 && (req->r_op == CEPH_MDS_OP_READDIR ||
2894 				    req->r_op == CEPH_MDS_OP_LSSNAP))
2895 			ceph_readdir_prepopulate(req, req->r_session);
2896 	}
2897 	current->journal_info = NULL;
2898 	mutex_unlock(&req->r_fill_mutex);
2899 
2900 	up_read(&mdsc->snap_rwsem);
2901 	if (realm)
2902 		ceph_put_snap_realm(mdsc, realm);
2903 
2904 	if (err == 0) {
2905 		if (req->r_target_inode &&
2906 		    test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags)) {
2907 			struct ceph_inode_info *ci =
2908 				ceph_inode(req->r_target_inode);
2909 			spin_lock(&ci->i_unsafe_lock);
2910 			list_add_tail(&req->r_unsafe_target_item,
2911 				      &ci->i_unsafe_iops);
2912 			spin_unlock(&ci->i_unsafe_lock);
2913 		}
2914 
2915 		ceph_unreserve_caps(mdsc, &req->r_caps_reservation);
2916 	}
2917 out_err:
2918 	mutex_lock(&mdsc->mutex);
2919 	if (!test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags)) {
2920 		if (err) {
2921 			req->r_err = err;
2922 		} else {
2923 			req->r_reply =  ceph_msg_get(msg);
2924 			set_bit(CEPH_MDS_R_GOT_RESULT, &req->r_req_flags);
2925 		}
2926 	} else {
2927 		dout("reply arrived after request %lld was aborted\n", tid);
2928 	}
2929 	mutex_unlock(&mdsc->mutex);
2930 
2931 	mutex_unlock(&session->s_mutex);
2932 
2933 	/* kick calling process */
2934 	complete_request(mdsc, req);
2935 out:
2936 	ceph_mdsc_put_request(req);
2937 	return;
2938 }
2939 
2940 
2941 
2942 /*
2943  * handle mds notification that our request has been forwarded.
2944  */
2945 static void handle_forward(struct ceph_mds_client *mdsc,
2946 			   struct ceph_mds_session *session,
2947 			   struct ceph_msg *msg)
2948 {
2949 	struct ceph_mds_request *req;
2950 	u64 tid = le64_to_cpu(msg->hdr.tid);
2951 	u32 next_mds;
2952 	u32 fwd_seq;
2953 	int err = -EINVAL;
2954 	void *p = msg->front.iov_base;
2955 	void *end = p + msg->front.iov_len;
2956 
2957 	ceph_decode_need(&p, end, 2*sizeof(u32), bad);
2958 	next_mds = ceph_decode_32(&p);
2959 	fwd_seq = ceph_decode_32(&p);
2960 
2961 	mutex_lock(&mdsc->mutex);
2962 	req = lookup_get_request(mdsc, tid);
2963 	if (!req) {
2964 		dout("forward tid %llu to mds%d - req dne\n", tid, next_mds);
2965 		goto out;  /* dup reply? */
2966 	}
2967 
2968 	if (test_bit(CEPH_MDS_R_ABORTED, &req->r_req_flags)) {
2969 		dout("forward tid %llu aborted, unregistering\n", tid);
2970 		__unregister_request(mdsc, req);
2971 	} else if (fwd_seq <= req->r_num_fwd) {
2972 		dout("forward tid %llu to mds%d - old seq %d <= %d\n",
2973 		     tid, next_mds, req->r_num_fwd, fwd_seq);
2974 	} else {
2975 		/* resend. forward race not possible; mds would drop */
2976 		dout("forward tid %llu to mds%d (we resend)\n", tid, next_mds);
2977 		BUG_ON(req->r_err);
2978 		BUG_ON(test_bit(CEPH_MDS_R_GOT_RESULT, &req->r_req_flags));
2979 		req->r_attempts = 0;
2980 		req->r_num_fwd = fwd_seq;
2981 		req->r_resend_mds = next_mds;
2982 		put_request_session(req);
2983 		__do_request(mdsc, req);
2984 	}
2985 	ceph_mdsc_put_request(req);
2986 out:
2987 	mutex_unlock(&mdsc->mutex);
2988 	return;
2989 
2990 bad:
2991 	pr_err("mdsc_handle_forward decode error err=%d\n", err);
2992 }
2993 
2994 static int __decode_and_drop_session_metadata(void **p, void *end)
2995 {
2996 	/* map<string,string> */
2997 	u32 n;
2998 	ceph_decode_32_safe(p, end, n, bad);
2999 	while (n-- > 0) {
3000 		u32 len;
3001 		ceph_decode_32_safe(p, end, len, bad);
3002 		ceph_decode_need(p, end, len, bad);
3003 		*p += len;
3004 		ceph_decode_32_safe(p, end, len, bad);
3005 		ceph_decode_need(p, end, len, bad);
3006 		*p += len;
3007 	}
3008 	return 0;
3009 bad:
3010 	return -1;
3011 }
3012 
3013 /*
3014  * handle a mds session control message
3015  */
3016 static void handle_session(struct ceph_mds_session *session,
3017 			   struct ceph_msg *msg)
3018 {
3019 	struct ceph_mds_client *mdsc = session->s_mdsc;
3020 	int mds = session->s_mds;
3021 	int msg_version = le16_to_cpu(msg->hdr.version);
3022 	void *p = msg->front.iov_base;
3023 	void *end = p + msg->front.iov_len;
3024 	struct ceph_mds_session_head *h;
3025 	u32 op;
3026 	u64 seq;
3027 	unsigned long features = 0;
3028 	int wake = 0;
3029 
3030 	/* decode */
3031 	ceph_decode_need(&p, end, sizeof(*h), bad);
3032 	h = p;
3033 	p += sizeof(*h);
3034 
3035 	op = le32_to_cpu(h->op);
3036 	seq = le64_to_cpu(h->seq);
3037 
3038 	if (msg_version >= 3) {
3039 		u32 len;
3040 		/* version >= 2, metadata */
3041 		if (__decode_and_drop_session_metadata(&p, end) < 0)
3042 			goto bad;
3043 		/* version >= 3, feature bits */
3044 		ceph_decode_32_safe(&p, end, len, bad);
3045 		ceph_decode_need(&p, end, len, bad);
3046 		memcpy(&features, p, min_t(size_t, len, sizeof(features)));
3047 		p += len;
3048 	}
3049 
3050 	mutex_lock(&mdsc->mutex);
3051 	if (op == CEPH_SESSION_CLOSE) {
3052 		get_session(session);
3053 		__unregister_session(mdsc, session);
3054 	}
3055 	/* FIXME: this ttl calculation is generous */
3056 	session->s_ttl = jiffies + HZ*mdsc->mdsmap->m_session_autoclose;
3057 	mutex_unlock(&mdsc->mutex);
3058 
3059 	mutex_lock(&session->s_mutex);
3060 
3061 	dout("handle_session mds%d %s %p state %s seq %llu\n",
3062 	     mds, ceph_session_op_name(op), session,
3063 	     ceph_session_state_name(session->s_state), seq);
3064 
3065 	if (session->s_state == CEPH_MDS_SESSION_HUNG) {
3066 		session->s_state = CEPH_MDS_SESSION_OPEN;
3067 		pr_info("mds%d came back\n", session->s_mds);
3068 	}
3069 
3070 	switch (op) {
3071 	case CEPH_SESSION_OPEN:
3072 		if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
3073 			pr_info("mds%d reconnect success\n", session->s_mds);
3074 		session->s_state = CEPH_MDS_SESSION_OPEN;
3075 		session->s_features = features;
3076 		renewed_caps(mdsc, session, 0);
3077 		wake = 1;
3078 		if (mdsc->stopping)
3079 			__close_session(mdsc, session);
3080 		break;
3081 
3082 	case CEPH_SESSION_RENEWCAPS:
3083 		if (session->s_renew_seq == seq)
3084 			renewed_caps(mdsc, session, 1);
3085 		break;
3086 
3087 	case CEPH_SESSION_CLOSE:
3088 		if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
3089 			pr_info("mds%d reconnect denied\n", session->s_mds);
3090 		cleanup_session_requests(mdsc, session);
3091 		remove_session_caps(session);
3092 		wake = 2; /* for good measure */
3093 		wake_up_all(&mdsc->session_close_wq);
3094 		break;
3095 
3096 	case CEPH_SESSION_STALE:
3097 		pr_info("mds%d caps went stale, renewing\n",
3098 			session->s_mds);
3099 		spin_lock(&session->s_gen_ttl_lock);
3100 		session->s_cap_gen++;
3101 		session->s_cap_ttl = jiffies - 1;
3102 		spin_unlock(&session->s_gen_ttl_lock);
3103 		send_renew_caps(mdsc, session);
3104 		break;
3105 
3106 	case CEPH_SESSION_RECALL_STATE:
3107 		ceph_trim_caps(mdsc, session, le32_to_cpu(h->max_caps));
3108 		break;
3109 
3110 	case CEPH_SESSION_FLUSHMSG:
3111 		send_flushmsg_ack(mdsc, session, seq);
3112 		break;
3113 
3114 	case CEPH_SESSION_FORCE_RO:
3115 		dout("force_session_readonly %p\n", session);
3116 		spin_lock(&session->s_cap_lock);
3117 		session->s_readonly = true;
3118 		spin_unlock(&session->s_cap_lock);
3119 		wake_up_session_caps(session, FORCE_RO);
3120 		break;
3121 
3122 	case CEPH_SESSION_REJECT:
3123 		WARN_ON(session->s_state != CEPH_MDS_SESSION_OPENING);
3124 		pr_info("mds%d rejected session\n", session->s_mds);
3125 		session->s_state = CEPH_MDS_SESSION_REJECTED;
3126 		cleanup_session_requests(mdsc, session);
3127 		remove_session_caps(session);
3128 		wake = 2; /* for good measure */
3129 		break;
3130 
3131 	default:
3132 		pr_err("mdsc_handle_session bad op %d mds%d\n", op, mds);
3133 		WARN_ON(1);
3134 	}
3135 
3136 	mutex_unlock(&session->s_mutex);
3137 	if (wake) {
3138 		mutex_lock(&mdsc->mutex);
3139 		__wake_requests(mdsc, &session->s_waiting);
3140 		if (wake == 2)
3141 			kick_requests(mdsc, mds);
3142 		mutex_unlock(&mdsc->mutex);
3143 	}
3144 	if (op == CEPH_SESSION_CLOSE)
3145 		ceph_put_mds_session(session);
3146 	return;
3147 
3148 bad:
3149 	pr_err("mdsc_handle_session corrupt message mds%d len %d\n", mds,
3150 	       (int)msg->front.iov_len);
3151 	ceph_msg_dump(msg);
3152 	return;
3153 }
3154 
3155 
3156 /*
3157  * called under session->mutex.
3158  */
3159 static void replay_unsafe_requests(struct ceph_mds_client *mdsc,
3160 				   struct ceph_mds_session *session)
3161 {
3162 	struct ceph_mds_request *req, *nreq;
3163 	struct rb_node *p;
3164 	int err;
3165 
3166 	dout("replay_unsafe_requests mds%d\n", session->s_mds);
3167 
3168 	mutex_lock(&mdsc->mutex);
3169 	list_for_each_entry_safe(req, nreq, &session->s_unsafe, r_unsafe_item) {
3170 		err = __prepare_send_request(mdsc, req, session->s_mds, true);
3171 		if (!err) {
3172 			ceph_msg_get(req->r_request);
3173 			ceph_con_send(&session->s_con, req->r_request);
3174 		}
3175 	}
3176 
3177 	/*
3178 	 * also re-send old requests when MDS enters reconnect stage. So that MDS
3179 	 * can process completed request in clientreplay stage.
3180 	 */
3181 	p = rb_first(&mdsc->request_tree);
3182 	while (p) {
3183 		req = rb_entry(p, struct ceph_mds_request, r_node);
3184 		p = rb_next(p);
3185 		if (test_bit(CEPH_MDS_R_GOT_UNSAFE, &req->r_req_flags))
3186 			continue;
3187 		if (req->r_attempts == 0)
3188 			continue; /* only old requests */
3189 		if (req->r_session &&
3190 		    req->r_session->s_mds == session->s_mds) {
3191 			err = __prepare_send_request(mdsc, req,
3192 						     session->s_mds, true);
3193 			if (!err) {
3194 				ceph_msg_get(req->r_request);
3195 				ceph_con_send(&session->s_con, req->r_request);
3196 			}
3197 		}
3198 	}
3199 	mutex_unlock(&mdsc->mutex);
3200 }
3201 
3202 static int send_reconnect_partial(struct ceph_reconnect_state *recon_state)
3203 {
3204 	struct ceph_msg *reply;
3205 	struct ceph_pagelist *_pagelist;
3206 	struct page *page;
3207 	__le32 *addr;
3208 	int err = -ENOMEM;
3209 
3210 	if (!recon_state->allow_multi)
3211 		return -ENOSPC;
3212 
3213 	/* can't handle message that contains both caps and realm */
3214 	BUG_ON(!recon_state->nr_caps == !recon_state->nr_realms);
3215 
3216 	/* pre-allocate new pagelist */
3217 	_pagelist = ceph_pagelist_alloc(GFP_NOFS);
3218 	if (!_pagelist)
3219 		return -ENOMEM;
3220 
3221 	reply = ceph_msg_new2(CEPH_MSG_CLIENT_RECONNECT, 0, 1, GFP_NOFS, false);
3222 	if (!reply)
3223 		goto fail_msg;
3224 
3225 	/* placeholder for nr_caps */
3226 	err = ceph_pagelist_encode_32(_pagelist, 0);
3227 	if (err < 0)
3228 		goto fail;
3229 
3230 	if (recon_state->nr_caps) {
3231 		/* currently encoding caps */
3232 		err = ceph_pagelist_encode_32(recon_state->pagelist, 0);
3233 		if (err)
3234 			goto fail;
3235 	} else {
3236 		/* placeholder for nr_realms (currently encoding relams) */
3237 		err = ceph_pagelist_encode_32(_pagelist, 0);
3238 		if (err < 0)
3239 			goto fail;
3240 	}
3241 
3242 	err = ceph_pagelist_encode_8(recon_state->pagelist, 1);
3243 	if (err)
3244 		goto fail;
3245 
3246 	page = list_first_entry(&recon_state->pagelist->head, struct page, lru);
3247 	addr = kmap_atomic(page);
3248 	if (recon_state->nr_caps) {
3249 		/* currently encoding caps */
3250 		*addr = cpu_to_le32(recon_state->nr_caps);
3251 	} else {
3252 		/* currently encoding relams */
3253 		*(addr + 1) = cpu_to_le32(recon_state->nr_realms);
3254 	}
3255 	kunmap_atomic(addr);
3256 
3257 	reply->hdr.version = cpu_to_le16(5);
3258 	reply->hdr.compat_version = cpu_to_le16(4);
3259 
3260 	reply->hdr.data_len = cpu_to_le32(recon_state->pagelist->length);
3261 	ceph_msg_data_add_pagelist(reply, recon_state->pagelist);
3262 
3263 	ceph_con_send(&recon_state->session->s_con, reply);
3264 	ceph_pagelist_release(recon_state->pagelist);
3265 
3266 	recon_state->pagelist = _pagelist;
3267 	recon_state->nr_caps = 0;
3268 	recon_state->nr_realms = 0;
3269 	recon_state->msg_version = 5;
3270 	return 0;
3271 fail:
3272 	ceph_msg_put(reply);
3273 fail_msg:
3274 	ceph_pagelist_release(_pagelist);
3275 	return err;
3276 }
3277 
3278 /*
3279  * Encode information about a cap for a reconnect with the MDS.
3280  */
3281 static int encode_caps_cb(struct inode *inode, struct ceph_cap *cap,
3282 			  void *arg)
3283 {
3284 	union {
3285 		struct ceph_mds_cap_reconnect v2;
3286 		struct ceph_mds_cap_reconnect_v1 v1;
3287 	} rec;
3288 	struct ceph_inode_info *ci = cap->ci;
3289 	struct ceph_reconnect_state *recon_state = arg;
3290 	struct ceph_pagelist *pagelist = recon_state->pagelist;
3291 	int err;
3292 	u64 snap_follows;
3293 
3294 	dout(" adding %p ino %llx.%llx cap %p %lld %s\n",
3295 	     inode, ceph_vinop(inode), cap, cap->cap_id,
3296 	     ceph_cap_string(cap->issued));
3297 
3298 	spin_lock(&ci->i_ceph_lock);
3299 	cap->seq = 0;        /* reset cap seq */
3300 	cap->issue_seq = 0;  /* and issue_seq */
3301 	cap->mseq = 0;       /* and migrate_seq */
3302 	cap->cap_gen = cap->session->s_cap_gen;
3303 
3304 	if (recon_state->msg_version >= 2) {
3305 		rec.v2.cap_id = cpu_to_le64(cap->cap_id);
3306 		rec.v2.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
3307 		rec.v2.issued = cpu_to_le32(cap->issued);
3308 		rec.v2.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
3309 		rec.v2.pathbase = 0;
3310 		rec.v2.flock_len = (__force __le32)
3311 			((ci->i_ceph_flags & CEPH_I_ERROR_FILELOCK) ? 0 : 1);
3312 	} else {
3313 		rec.v1.cap_id = cpu_to_le64(cap->cap_id);
3314 		rec.v1.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
3315 		rec.v1.issued = cpu_to_le32(cap->issued);
3316 		rec.v1.size = cpu_to_le64(inode->i_size);
3317 		ceph_encode_timespec64(&rec.v1.mtime, &inode->i_mtime);
3318 		ceph_encode_timespec64(&rec.v1.atime, &inode->i_atime);
3319 		rec.v1.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
3320 		rec.v1.pathbase = 0;
3321 	}
3322 
3323 	if (list_empty(&ci->i_cap_snaps)) {
3324 		snap_follows = ci->i_head_snapc ? ci->i_head_snapc->seq : 0;
3325 	} else {
3326 		struct ceph_cap_snap *capsnap =
3327 			list_first_entry(&ci->i_cap_snaps,
3328 					 struct ceph_cap_snap, ci_item);
3329 		snap_follows = capsnap->follows;
3330 	}
3331 	spin_unlock(&ci->i_ceph_lock);
3332 
3333 	if (recon_state->msg_version >= 2) {
3334 		int num_fcntl_locks, num_flock_locks;
3335 		struct ceph_filelock *flocks = NULL;
3336 		size_t struct_len, total_len = sizeof(u64);
3337 		u8 struct_v = 0;
3338 
3339 encode_again:
3340 		if (rec.v2.flock_len) {
3341 			ceph_count_locks(inode, &num_fcntl_locks, &num_flock_locks);
3342 		} else {
3343 			num_fcntl_locks = 0;
3344 			num_flock_locks = 0;
3345 		}
3346 		if (num_fcntl_locks + num_flock_locks > 0) {
3347 			flocks = kmalloc_array(num_fcntl_locks + num_flock_locks,
3348 					       sizeof(struct ceph_filelock),
3349 					       GFP_NOFS);
3350 			if (!flocks) {
3351 				err = -ENOMEM;
3352 				goto out_err;
3353 			}
3354 			err = ceph_encode_locks_to_buffer(inode, flocks,
3355 							  num_fcntl_locks,
3356 							  num_flock_locks);
3357 			if (err) {
3358 				kfree(flocks);
3359 				flocks = NULL;
3360 				if (err == -ENOSPC)
3361 					goto encode_again;
3362 				goto out_err;
3363 			}
3364 		} else {
3365 			kfree(flocks);
3366 			flocks = NULL;
3367 		}
3368 
3369 		if (recon_state->msg_version >= 3) {
3370 			/* version, compat_version and struct_len */
3371 			total_len += 2 * sizeof(u8) + sizeof(u32);
3372 			struct_v = 2;
3373 		}
3374 		/*
3375 		 * number of encoded locks is stable, so copy to pagelist
3376 		 */
3377 		struct_len = 2 * sizeof(u32) +
3378 			    (num_fcntl_locks + num_flock_locks) *
3379 			    sizeof(struct ceph_filelock);
3380 		rec.v2.flock_len = cpu_to_le32(struct_len);
3381 
3382 		struct_len += sizeof(u32) + sizeof(rec.v2);
3383 
3384 		if (struct_v >= 2)
3385 			struct_len += sizeof(u64); /* snap_follows */
3386 
3387 		total_len += struct_len;
3388 
3389 		if (pagelist->length + total_len > RECONNECT_MAX_SIZE) {
3390 			err = send_reconnect_partial(recon_state);
3391 			if (err)
3392 				goto out_freeflocks;
3393 			pagelist = recon_state->pagelist;
3394 		}
3395 
3396 		err = ceph_pagelist_reserve(pagelist, total_len);
3397 		if (err)
3398 			goto out_freeflocks;
3399 
3400 		ceph_pagelist_encode_64(pagelist, ceph_ino(inode));
3401 		if (recon_state->msg_version >= 3) {
3402 			ceph_pagelist_encode_8(pagelist, struct_v);
3403 			ceph_pagelist_encode_8(pagelist, 1);
3404 			ceph_pagelist_encode_32(pagelist, struct_len);
3405 		}
3406 		ceph_pagelist_encode_string(pagelist, NULL, 0);
3407 		ceph_pagelist_append(pagelist, &rec, sizeof(rec.v2));
3408 		ceph_locks_to_pagelist(flocks, pagelist,
3409 				       num_fcntl_locks, num_flock_locks);
3410 		if (struct_v >= 2)
3411 			ceph_pagelist_encode_64(pagelist, snap_follows);
3412 out_freeflocks:
3413 		kfree(flocks);
3414 	} else {
3415 		u64 pathbase = 0;
3416 		int pathlen = 0;
3417 		char *path = NULL;
3418 		struct dentry *dentry;
3419 
3420 		dentry = d_find_alias(inode);
3421 		if (dentry) {
3422 			path = ceph_mdsc_build_path(dentry,
3423 						&pathlen, &pathbase, 0);
3424 			dput(dentry);
3425 			if (IS_ERR(path)) {
3426 				err = PTR_ERR(path);
3427 				goto out_err;
3428 			}
3429 			rec.v1.pathbase = cpu_to_le64(pathbase);
3430 		}
3431 
3432 		err = ceph_pagelist_reserve(pagelist,
3433 					    sizeof(u64) + sizeof(u32) +
3434 					    pathlen + sizeof(rec.v1));
3435 		if (err) {
3436 			goto out_freepath;
3437 		}
3438 
3439 		ceph_pagelist_encode_64(pagelist, ceph_ino(inode));
3440 		ceph_pagelist_encode_string(pagelist, path, pathlen);
3441 		ceph_pagelist_append(pagelist, &rec, sizeof(rec.v1));
3442 out_freepath:
3443 		ceph_mdsc_free_path(path, pathlen);
3444 	}
3445 
3446 out_err:
3447 	if (err >= 0)
3448 		recon_state->nr_caps++;
3449 	return err;
3450 }
3451 
3452 static int encode_snap_realms(struct ceph_mds_client *mdsc,
3453 			      struct ceph_reconnect_state *recon_state)
3454 {
3455 	struct rb_node *p;
3456 	struct ceph_pagelist *pagelist = recon_state->pagelist;
3457 	int err = 0;
3458 
3459 	if (recon_state->msg_version >= 4) {
3460 		err = ceph_pagelist_encode_32(pagelist, mdsc->num_snap_realms);
3461 		if (err < 0)
3462 			goto fail;
3463 	}
3464 
3465 	/*
3466 	 * snaprealms.  we provide mds with the ino, seq (version), and
3467 	 * parent for all of our realms.  If the mds has any newer info,
3468 	 * it will tell us.
3469 	 */
3470 	for (p = rb_first(&mdsc->snap_realms); p; p = rb_next(p)) {
3471 		struct ceph_snap_realm *realm =
3472 		       rb_entry(p, struct ceph_snap_realm, node);
3473 		struct ceph_mds_snaprealm_reconnect sr_rec;
3474 
3475 		if (recon_state->msg_version >= 4) {
3476 			size_t need = sizeof(u8) * 2 + sizeof(u32) +
3477 				      sizeof(sr_rec);
3478 
3479 			if (pagelist->length + need > RECONNECT_MAX_SIZE) {
3480 				err = send_reconnect_partial(recon_state);
3481 				if (err)
3482 					goto fail;
3483 				pagelist = recon_state->pagelist;
3484 			}
3485 
3486 			err = ceph_pagelist_reserve(pagelist, need);
3487 			if (err)
3488 				goto fail;
3489 
3490 			ceph_pagelist_encode_8(pagelist, 1);
3491 			ceph_pagelist_encode_8(pagelist, 1);
3492 			ceph_pagelist_encode_32(pagelist, sizeof(sr_rec));
3493 		}
3494 
3495 		dout(" adding snap realm %llx seq %lld parent %llx\n",
3496 		     realm->ino, realm->seq, realm->parent_ino);
3497 		sr_rec.ino = cpu_to_le64(realm->ino);
3498 		sr_rec.seq = cpu_to_le64(realm->seq);
3499 		sr_rec.parent = cpu_to_le64(realm->parent_ino);
3500 
3501 		err = ceph_pagelist_append(pagelist, &sr_rec, sizeof(sr_rec));
3502 		if (err)
3503 			goto fail;
3504 
3505 		recon_state->nr_realms++;
3506 	}
3507 fail:
3508 	return err;
3509 }
3510 
3511 
3512 /*
3513  * If an MDS fails and recovers, clients need to reconnect in order to
3514  * reestablish shared state.  This includes all caps issued through
3515  * this session _and_ the snap_realm hierarchy.  Because it's not
3516  * clear which snap realms the mds cares about, we send everything we
3517  * know about.. that ensures we'll then get any new info the
3518  * recovering MDS might have.
3519  *
3520  * This is a relatively heavyweight operation, but it's rare.
3521  *
3522  * called with mdsc->mutex held.
3523  */
3524 static void send_mds_reconnect(struct ceph_mds_client *mdsc,
3525 			       struct ceph_mds_session *session)
3526 {
3527 	struct ceph_msg *reply;
3528 	int mds = session->s_mds;
3529 	int err = -ENOMEM;
3530 	struct ceph_reconnect_state recon_state = {
3531 		.session = session,
3532 	};
3533 	LIST_HEAD(dispose);
3534 
3535 	pr_info("mds%d reconnect start\n", mds);
3536 
3537 	recon_state.pagelist = ceph_pagelist_alloc(GFP_NOFS);
3538 	if (!recon_state.pagelist)
3539 		goto fail_nopagelist;
3540 
3541 	reply = ceph_msg_new2(CEPH_MSG_CLIENT_RECONNECT, 0, 1, GFP_NOFS, false);
3542 	if (!reply)
3543 		goto fail_nomsg;
3544 
3545 	mutex_lock(&session->s_mutex);
3546 	session->s_state = CEPH_MDS_SESSION_RECONNECTING;
3547 	session->s_seq = 0;
3548 
3549 	dout("session %p state %s\n", session,
3550 	     ceph_session_state_name(session->s_state));
3551 
3552 	spin_lock(&session->s_gen_ttl_lock);
3553 	session->s_cap_gen++;
3554 	spin_unlock(&session->s_gen_ttl_lock);
3555 
3556 	spin_lock(&session->s_cap_lock);
3557 	/* don't know if session is readonly */
3558 	session->s_readonly = 0;
3559 	/*
3560 	 * notify __ceph_remove_cap() that we are composing cap reconnect.
3561 	 * If a cap get released before being added to the cap reconnect,
3562 	 * __ceph_remove_cap() should skip queuing cap release.
3563 	 */
3564 	session->s_cap_reconnect = 1;
3565 	/* drop old cap expires; we're about to reestablish that state */
3566 	detach_cap_releases(session, &dispose);
3567 	spin_unlock(&session->s_cap_lock);
3568 	dispose_cap_releases(mdsc, &dispose);
3569 
3570 	/* trim unused caps to reduce MDS's cache rejoin time */
3571 	if (mdsc->fsc->sb->s_root)
3572 		shrink_dcache_parent(mdsc->fsc->sb->s_root);
3573 
3574 	ceph_con_close(&session->s_con);
3575 	ceph_con_open(&session->s_con,
3576 		      CEPH_ENTITY_TYPE_MDS, mds,
3577 		      ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
3578 
3579 	/* replay unsafe requests */
3580 	replay_unsafe_requests(mdsc, session);
3581 
3582 	ceph_early_kick_flushing_caps(mdsc, session);
3583 
3584 	down_read(&mdsc->snap_rwsem);
3585 
3586 	/* placeholder for nr_caps */
3587 	err = ceph_pagelist_encode_32(recon_state.pagelist, 0);
3588 	if (err)
3589 		goto fail;
3590 
3591 	if (test_bit(CEPHFS_FEATURE_MULTI_RECONNECT, &session->s_features)) {
3592 		recon_state.msg_version = 3;
3593 		recon_state.allow_multi = true;
3594 	} else if (session->s_con.peer_features & CEPH_FEATURE_MDSENC) {
3595 		recon_state.msg_version = 3;
3596 	} else {
3597 		recon_state.msg_version = 2;
3598 	}
3599 	/* trsaverse this session's caps */
3600 	err = ceph_iterate_session_caps(session, encode_caps_cb, &recon_state);
3601 
3602 	spin_lock(&session->s_cap_lock);
3603 	session->s_cap_reconnect = 0;
3604 	spin_unlock(&session->s_cap_lock);
3605 
3606 	if (err < 0)
3607 		goto fail;
3608 
3609 	/* check if all realms can be encoded into current message */
3610 	if (mdsc->num_snap_realms) {
3611 		size_t total_len =
3612 			recon_state.pagelist->length +
3613 			mdsc->num_snap_realms *
3614 			sizeof(struct ceph_mds_snaprealm_reconnect);
3615 		if (recon_state.msg_version >= 4) {
3616 			/* number of realms */
3617 			total_len += sizeof(u32);
3618 			/* version, compat_version and struct_len */
3619 			total_len += mdsc->num_snap_realms *
3620 				     (2 * sizeof(u8) + sizeof(u32));
3621 		}
3622 		if (total_len > RECONNECT_MAX_SIZE) {
3623 			if (!recon_state.allow_multi) {
3624 				err = -ENOSPC;
3625 				goto fail;
3626 			}
3627 			if (recon_state.nr_caps) {
3628 				err = send_reconnect_partial(&recon_state);
3629 				if (err)
3630 					goto fail;
3631 			}
3632 			recon_state.msg_version = 5;
3633 		}
3634 	}
3635 
3636 	err = encode_snap_realms(mdsc, &recon_state);
3637 	if (err < 0)
3638 		goto fail;
3639 
3640 	if (recon_state.msg_version >= 5) {
3641 		err = ceph_pagelist_encode_8(recon_state.pagelist, 0);
3642 		if (err < 0)
3643 			goto fail;
3644 	}
3645 
3646 	if (recon_state.nr_caps || recon_state.nr_realms) {
3647 		struct page *page =
3648 			list_first_entry(&recon_state.pagelist->head,
3649 					struct page, lru);
3650 		__le32 *addr = kmap_atomic(page);
3651 		if (recon_state.nr_caps) {
3652 			WARN_ON(recon_state.nr_realms != mdsc->num_snap_realms);
3653 			*addr = cpu_to_le32(recon_state.nr_caps);
3654 		} else if (recon_state.msg_version >= 4) {
3655 			*(addr + 1) = cpu_to_le32(recon_state.nr_realms);
3656 		}
3657 		kunmap_atomic(addr);
3658 	}
3659 
3660 	reply->hdr.version = cpu_to_le16(recon_state.msg_version);
3661 	if (recon_state.msg_version >= 4)
3662 		reply->hdr.compat_version = cpu_to_le16(4);
3663 
3664 	reply->hdr.data_len = cpu_to_le32(recon_state.pagelist->length);
3665 	ceph_msg_data_add_pagelist(reply, recon_state.pagelist);
3666 
3667 	ceph_con_send(&session->s_con, reply);
3668 
3669 	mutex_unlock(&session->s_mutex);
3670 
3671 	mutex_lock(&mdsc->mutex);
3672 	__wake_requests(mdsc, &session->s_waiting);
3673 	mutex_unlock(&mdsc->mutex);
3674 
3675 	up_read(&mdsc->snap_rwsem);
3676 	ceph_pagelist_release(recon_state.pagelist);
3677 	return;
3678 
3679 fail:
3680 	ceph_msg_put(reply);
3681 	up_read(&mdsc->snap_rwsem);
3682 	mutex_unlock(&session->s_mutex);
3683 fail_nomsg:
3684 	ceph_pagelist_release(recon_state.pagelist);
3685 fail_nopagelist:
3686 	pr_err("error %d preparing reconnect for mds%d\n", err, mds);
3687 	return;
3688 }
3689 
3690 
3691 /*
3692  * compare old and new mdsmaps, kicking requests
3693  * and closing out old connections as necessary
3694  *
3695  * called under mdsc->mutex.
3696  */
3697 static void check_new_map(struct ceph_mds_client *mdsc,
3698 			  struct ceph_mdsmap *newmap,
3699 			  struct ceph_mdsmap *oldmap)
3700 {
3701 	int i;
3702 	int oldstate, newstate;
3703 	struct ceph_mds_session *s;
3704 
3705 	dout("check_new_map new %u old %u\n",
3706 	     newmap->m_epoch, oldmap->m_epoch);
3707 
3708 	for (i = 0; i < oldmap->m_num_mds && i < mdsc->max_sessions; i++) {
3709 		if (!mdsc->sessions[i])
3710 			continue;
3711 		s = mdsc->sessions[i];
3712 		oldstate = ceph_mdsmap_get_state(oldmap, i);
3713 		newstate = ceph_mdsmap_get_state(newmap, i);
3714 
3715 		dout("check_new_map mds%d state %s%s -> %s%s (session %s)\n",
3716 		     i, ceph_mds_state_name(oldstate),
3717 		     ceph_mdsmap_is_laggy(oldmap, i) ? " (laggy)" : "",
3718 		     ceph_mds_state_name(newstate),
3719 		     ceph_mdsmap_is_laggy(newmap, i) ? " (laggy)" : "",
3720 		     ceph_session_state_name(s->s_state));
3721 
3722 		if (i >= newmap->m_num_mds ||
3723 		    memcmp(ceph_mdsmap_get_addr(oldmap, i),
3724 			   ceph_mdsmap_get_addr(newmap, i),
3725 			   sizeof(struct ceph_entity_addr))) {
3726 			if (s->s_state == CEPH_MDS_SESSION_OPENING) {
3727 				/* the session never opened, just close it
3728 				 * out now */
3729 				get_session(s);
3730 				__unregister_session(mdsc, s);
3731 				__wake_requests(mdsc, &s->s_waiting);
3732 				ceph_put_mds_session(s);
3733 			} else if (i >= newmap->m_num_mds) {
3734 				/* force close session for stopped mds */
3735 				get_session(s);
3736 				__unregister_session(mdsc, s);
3737 				__wake_requests(mdsc, &s->s_waiting);
3738 				kick_requests(mdsc, i);
3739 				mutex_unlock(&mdsc->mutex);
3740 
3741 				mutex_lock(&s->s_mutex);
3742 				cleanup_session_requests(mdsc, s);
3743 				remove_session_caps(s);
3744 				mutex_unlock(&s->s_mutex);
3745 
3746 				ceph_put_mds_session(s);
3747 
3748 				mutex_lock(&mdsc->mutex);
3749 			} else {
3750 				/* just close it */
3751 				mutex_unlock(&mdsc->mutex);
3752 				mutex_lock(&s->s_mutex);
3753 				mutex_lock(&mdsc->mutex);
3754 				ceph_con_close(&s->s_con);
3755 				mutex_unlock(&s->s_mutex);
3756 				s->s_state = CEPH_MDS_SESSION_RESTARTING;
3757 			}
3758 		} else if (oldstate == newstate) {
3759 			continue;  /* nothing new with this mds */
3760 		}
3761 
3762 		/*
3763 		 * send reconnect?
3764 		 */
3765 		if (s->s_state == CEPH_MDS_SESSION_RESTARTING &&
3766 		    newstate >= CEPH_MDS_STATE_RECONNECT) {
3767 			mutex_unlock(&mdsc->mutex);
3768 			send_mds_reconnect(mdsc, s);
3769 			mutex_lock(&mdsc->mutex);
3770 		}
3771 
3772 		/*
3773 		 * kick request on any mds that has gone active.
3774 		 */
3775 		if (oldstate < CEPH_MDS_STATE_ACTIVE &&
3776 		    newstate >= CEPH_MDS_STATE_ACTIVE) {
3777 			if (oldstate != CEPH_MDS_STATE_CREATING &&
3778 			    oldstate != CEPH_MDS_STATE_STARTING)
3779 				pr_info("mds%d recovery completed\n", s->s_mds);
3780 			kick_requests(mdsc, i);
3781 			ceph_kick_flushing_caps(mdsc, s);
3782 			wake_up_session_caps(s, RECONNECT);
3783 		}
3784 	}
3785 
3786 	for (i = 0; i < newmap->m_num_mds && i < mdsc->max_sessions; i++) {
3787 		s = mdsc->sessions[i];
3788 		if (!s)
3789 			continue;
3790 		if (!ceph_mdsmap_is_laggy(newmap, i))
3791 			continue;
3792 		if (s->s_state == CEPH_MDS_SESSION_OPEN ||
3793 		    s->s_state == CEPH_MDS_SESSION_HUNG ||
3794 		    s->s_state == CEPH_MDS_SESSION_CLOSING) {
3795 			dout(" connecting to export targets of laggy mds%d\n",
3796 			     i);
3797 			__open_export_target_sessions(mdsc, s);
3798 		}
3799 	}
3800 }
3801 
3802 
3803 
3804 /*
3805  * leases
3806  */
3807 
3808 /*
3809  * caller must hold session s_mutex, dentry->d_lock
3810  */
3811 void __ceph_mdsc_drop_dentry_lease(struct dentry *dentry)
3812 {
3813 	struct ceph_dentry_info *di = ceph_dentry(dentry);
3814 
3815 	ceph_put_mds_session(di->lease_session);
3816 	di->lease_session = NULL;
3817 }
3818 
3819 static void handle_lease(struct ceph_mds_client *mdsc,
3820 			 struct ceph_mds_session *session,
3821 			 struct ceph_msg *msg)
3822 {
3823 	struct super_block *sb = mdsc->fsc->sb;
3824 	struct inode *inode;
3825 	struct dentry *parent, *dentry;
3826 	struct ceph_dentry_info *di;
3827 	int mds = session->s_mds;
3828 	struct ceph_mds_lease *h = msg->front.iov_base;
3829 	u32 seq;
3830 	struct ceph_vino vino;
3831 	struct qstr dname;
3832 	int release = 0;
3833 
3834 	dout("handle_lease from mds%d\n", mds);
3835 
3836 	/* decode */
3837 	if (msg->front.iov_len < sizeof(*h) + sizeof(u32))
3838 		goto bad;
3839 	vino.ino = le64_to_cpu(h->ino);
3840 	vino.snap = CEPH_NOSNAP;
3841 	seq = le32_to_cpu(h->seq);
3842 	dname.len = get_unaligned_le32(h + 1);
3843 	if (msg->front.iov_len < sizeof(*h) + sizeof(u32) + dname.len)
3844 		goto bad;
3845 	dname.name = (void *)(h + 1) + sizeof(u32);
3846 
3847 	/* lookup inode */
3848 	inode = ceph_find_inode(sb, vino);
3849 	dout("handle_lease %s, ino %llx %p %.*s\n",
3850 	     ceph_lease_op_name(h->action), vino.ino, inode,
3851 	     dname.len, dname.name);
3852 
3853 	mutex_lock(&session->s_mutex);
3854 	session->s_seq++;
3855 
3856 	if (!inode) {
3857 		dout("handle_lease no inode %llx\n", vino.ino);
3858 		goto release;
3859 	}
3860 
3861 	/* dentry */
3862 	parent = d_find_alias(inode);
3863 	if (!parent) {
3864 		dout("no parent dentry on inode %p\n", inode);
3865 		WARN_ON(1);
3866 		goto release;  /* hrm... */
3867 	}
3868 	dname.hash = full_name_hash(parent, dname.name, dname.len);
3869 	dentry = d_lookup(parent, &dname);
3870 	dput(parent);
3871 	if (!dentry)
3872 		goto release;
3873 
3874 	spin_lock(&dentry->d_lock);
3875 	di = ceph_dentry(dentry);
3876 	switch (h->action) {
3877 	case CEPH_MDS_LEASE_REVOKE:
3878 		if (di->lease_session == session) {
3879 			if (ceph_seq_cmp(di->lease_seq, seq) > 0)
3880 				h->seq = cpu_to_le32(di->lease_seq);
3881 			__ceph_mdsc_drop_dentry_lease(dentry);
3882 		}
3883 		release = 1;
3884 		break;
3885 
3886 	case CEPH_MDS_LEASE_RENEW:
3887 		if (di->lease_session == session &&
3888 		    di->lease_gen == session->s_cap_gen &&
3889 		    di->lease_renew_from &&
3890 		    di->lease_renew_after == 0) {
3891 			unsigned long duration =
3892 				msecs_to_jiffies(le32_to_cpu(h->duration_ms));
3893 
3894 			di->lease_seq = seq;
3895 			di->time = di->lease_renew_from + duration;
3896 			di->lease_renew_after = di->lease_renew_from +
3897 				(duration >> 1);
3898 			di->lease_renew_from = 0;
3899 		}
3900 		break;
3901 	}
3902 	spin_unlock(&dentry->d_lock);
3903 	dput(dentry);
3904 
3905 	if (!release)
3906 		goto out;
3907 
3908 release:
3909 	/* let's just reuse the same message */
3910 	h->action = CEPH_MDS_LEASE_REVOKE_ACK;
3911 	ceph_msg_get(msg);
3912 	ceph_con_send(&session->s_con, msg);
3913 
3914 out:
3915 	iput(inode);
3916 	mutex_unlock(&session->s_mutex);
3917 	return;
3918 
3919 bad:
3920 	pr_err("corrupt lease message\n");
3921 	ceph_msg_dump(msg);
3922 }
3923 
3924 void ceph_mdsc_lease_send_msg(struct ceph_mds_session *session,
3925 			      struct inode *inode,
3926 			      struct dentry *dentry, char action,
3927 			      u32 seq)
3928 {
3929 	struct ceph_msg *msg;
3930 	struct ceph_mds_lease *lease;
3931 	int len = sizeof(*lease) + sizeof(u32);
3932 	int dnamelen = 0;
3933 
3934 	dout("lease_send_msg inode %p dentry %p %s to mds%d\n",
3935 	     inode, dentry, ceph_lease_op_name(action), session->s_mds);
3936 	dnamelen = dentry->d_name.len;
3937 	len += dnamelen;
3938 
3939 	msg = ceph_msg_new(CEPH_MSG_CLIENT_LEASE, len, GFP_NOFS, false);
3940 	if (!msg)
3941 		return;
3942 	lease = msg->front.iov_base;
3943 	lease->action = action;
3944 	lease->ino = cpu_to_le64(ceph_vino(inode).ino);
3945 	lease->first = lease->last = cpu_to_le64(ceph_vino(inode).snap);
3946 	lease->seq = cpu_to_le32(seq);
3947 	put_unaligned_le32(dnamelen, lease + 1);
3948 	memcpy((void *)(lease + 1) + 4, dentry->d_name.name, dnamelen);
3949 
3950 	/*
3951 	 * if this is a preemptive lease RELEASE, no need to
3952 	 * flush request stream, since the actual request will
3953 	 * soon follow.
3954 	 */
3955 	msg->more_to_follow = (action == CEPH_MDS_LEASE_RELEASE);
3956 
3957 	ceph_con_send(&session->s_con, msg);
3958 }
3959 
3960 /*
3961  * lock unlock sessions, to wait ongoing session activities
3962  */
3963 static void lock_unlock_sessions(struct ceph_mds_client *mdsc)
3964 {
3965 	int i;
3966 
3967 	mutex_lock(&mdsc->mutex);
3968 	for (i = 0; i < mdsc->max_sessions; i++) {
3969 		struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
3970 		if (!s)
3971 			continue;
3972 		mutex_unlock(&mdsc->mutex);
3973 		mutex_lock(&s->s_mutex);
3974 		mutex_unlock(&s->s_mutex);
3975 		ceph_put_mds_session(s);
3976 		mutex_lock(&mdsc->mutex);
3977 	}
3978 	mutex_unlock(&mdsc->mutex);
3979 }
3980 
3981 
3982 
3983 /*
3984  * delayed work -- periodically trim expired leases, renew caps with mds
3985  */
3986 static void schedule_delayed(struct ceph_mds_client *mdsc)
3987 {
3988 	int delay = 5;
3989 	unsigned hz = round_jiffies_relative(HZ * delay);
3990 	schedule_delayed_work(&mdsc->delayed_work, hz);
3991 }
3992 
3993 static void delayed_work(struct work_struct *work)
3994 {
3995 	int i;
3996 	struct ceph_mds_client *mdsc =
3997 		container_of(work, struct ceph_mds_client, delayed_work.work);
3998 	int renew_interval;
3999 	int renew_caps;
4000 
4001 	dout("mdsc delayed_work\n");
4002 
4003 	mutex_lock(&mdsc->mutex);
4004 	renew_interval = mdsc->mdsmap->m_session_timeout >> 2;
4005 	renew_caps = time_after_eq(jiffies, HZ*renew_interval +
4006 				   mdsc->last_renew_caps);
4007 	if (renew_caps)
4008 		mdsc->last_renew_caps = jiffies;
4009 
4010 	for (i = 0; i < mdsc->max_sessions; i++) {
4011 		struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
4012 		if (!s)
4013 			continue;
4014 		if (s->s_state == CEPH_MDS_SESSION_CLOSING) {
4015 			dout("resending session close request for mds%d\n",
4016 			     s->s_mds);
4017 			request_close_session(mdsc, s);
4018 			ceph_put_mds_session(s);
4019 			continue;
4020 		}
4021 		if (s->s_ttl && time_after(jiffies, s->s_ttl)) {
4022 			if (s->s_state == CEPH_MDS_SESSION_OPEN) {
4023 				s->s_state = CEPH_MDS_SESSION_HUNG;
4024 				pr_info("mds%d hung\n", s->s_mds);
4025 			}
4026 		}
4027 		if (s->s_state < CEPH_MDS_SESSION_OPEN) {
4028 			/* this mds is failed or recovering, just wait */
4029 			ceph_put_mds_session(s);
4030 			continue;
4031 		}
4032 		mutex_unlock(&mdsc->mutex);
4033 
4034 		mutex_lock(&s->s_mutex);
4035 		if (renew_caps)
4036 			send_renew_caps(mdsc, s);
4037 		else
4038 			ceph_con_keepalive(&s->s_con);
4039 		if (s->s_state == CEPH_MDS_SESSION_OPEN ||
4040 		    s->s_state == CEPH_MDS_SESSION_HUNG)
4041 			ceph_send_cap_releases(mdsc, s);
4042 		mutex_unlock(&s->s_mutex);
4043 		ceph_put_mds_session(s);
4044 
4045 		mutex_lock(&mdsc->mutex);
4046 	}
4047 	mutex_unlock(&mdsc->mutex);
4048 
4049 	ceph_check_delayed_caps(mdsc);
4050 
4051 	ceph_queue_cap_reclaim_work(mdsc);
4052 
4053 	ceph_trim_snapid_map(mdsc);
4054 
4055 	schedule_delayed(mdsc);
4056 }
4057 
4058 int ceph_mdsc_init(struct ceph_fs_client *fsc)
4059 
4060 {
4061 	struct ceph_mds_client *mdsc;
4062 
4063 	mdsc = kzalloc(sizeof(struct ceph_mds_client), GFP_NOFS);
4064 	if (!mdsc)
4065 		return -ENOMEM;
4066 	mdsc->fsc = fsc;
4067 	mutex_init(&mdsc->mutex);
4068 	mdsc->mdsmap = kzalloc(sizeof(*mdsc->mdsmap), GFP_NOFS);
4069 	if (!mdsc->mdsmap) {
4070 		kfree(mdsc);
4071 		return -ENOMEM;
4072 	}
4073 
4074 	fsc->mdsc = mdsc;
4075 	init_completion(&mdsc->safe_umount_waiters);
4076 	init_waitqueue_head(&mdsc->session_close_wq);
4077 	INIT_LIST_HEAD(&mdsc->waiting_for_map);
4078 	mdsc->sessions = NULL;
4079 	atomic_set(&mdsc->num_sessions, 0);
4080 	mdsc->max_sessions = 0;
4081 	mdsc->stopping = 0;
4082 	atomic64_set(&mdsc->quotarealms_count, 0);
4083 	mdsc->quotarealms_inodes = RB_ROOT;
4084 	mutex_init(&mdsc->quotarealms_inodes_mutex);
4085 	mdsc->last_snap_seq = 0;
4086 	init_rwsem(&mdsc->snap_rwsem);
4087 	mdsc->snap_realms = RB_ROOT;
4088 	INIT_LIST_HEAD(&mdsc->snap_empty);
4089 	mdsc->num_snap_realms = 0;
4090 	spin_lock_init(&mdsc->snap_empty_lock);
4091 	mdsc->last_tid = 0;
4092 	mdsc->oldest_tid = 0;
4093 	mdsc->request_tree = RB_ROOT;
4094 	INIT_DELAYED_WORK(&mdsc->delayed_work, delayed_work);
4095 	mdsc->last_renew_caps = jiffies;
4096 	INIT_LIST_HEAD(&mdsc->cap_delay_list);
4097 	spin_lock_init(&mdsc->cap_delay_lock);
4098 	INIT_LIST_HEAD(&mdsc->snap_flush_list);
4099 	spin_lock_init(&mdsc->snap_flush_lock);
4100 	mdsc->last_cap_flush_tid = 1;
4101 	INIT_LIST_HEAD(&mdsc->cap_flush_list);
4102 	INIT_LIST_HEAD(&mdsc->cap_dirty);
4103 	INIT_LIST_HEAD(&mdsc->cap_dirty_migrating);
4104 	mdsc->num_cap_flushing = 0;
4105 	spin_lock_init(&mdsc->cap_dirty_lock);
4106 	init_waitqueue_head(&mdsc->cap_flushing_wq);
4107 	INIT_WORK(&mdsc->cap_reclaim_work, ceph_cap_reclaim_work);
4108 	atomic_set(&mdsc->cap_reclaim_pending, 0);
4109 
4110 	spin_lock_init(&mdsc->dentry_list_lock);
4111 	INIT_LIST_HEAD(&mdsc->dentry_leases);
4112 	INIT_LIST_HEAD(&mdsc->dentry_dir_leases);
4113 
4114 	ceph_caps_init(mdsc);
4115 	ceph_adjust_caps_max_min(mdsc, fsc->mount_options);
4116 
4117 	spin_lock_init(&mdsc->snapid_map_lock);
4118 	mdsc->snapid_map_tree = RB_ROOT;
4119 	INIT_LIST_HEAD(&mdsc->snapid_map_lru);
4120 
4121 	init_rwsem(&mdsc->pool_perm_rwsem);
4122 	mdsc->pool_perm_tree = RB_ROOT;
4123 
4124 	strscpy(mdsc->nodename, utsname()->nodename,
4125 		sizeof(mdsc->nodename));
4126 	return 0;
4127 }
4128 
4129 /*
4130  * Wait for safe replies on open mds requests.  If we time out, drop
4131  * all requests from the tree to avoid dangling dentry refs.
4132  */
4133 static void wait_requests(struct ceph_mds_client *mdsc)
4134 {
4135 	struct ceph_options *opts = mdsc->fsc->client->options;
4136 	struct ceph_mds_request *req;
4137 
4138 	mutex_lock(&mdsc->mutex);
4139 	if (__get_oldest_req(mdsc)) {
4140 		mutex_unlock(&mdsc->mutex);
4141 
4142 		dout("wait_requests waiting for requests\n");
4143 		wait_for_completion_timeout(&mdsc->safe_umount_waiters,
4144 				    ceph_timeout_jiffies(opts->mount_timeout));
4145 
4146 		/* tear down remaining requests */
4147 		mutex_lock(&mdsc->mutex);
4148 		while ((req = __get_oldest_req(mdsc))) {
4149 			dout("wait_requests timed out on tid %llu\n",
4150 			     req->r_tid);
4151 			__unregister_request(mdsc, req);
4152 		}
4153 	}
4154 	mutex_unlock(&mdsc->mutex);
4155 	dout("wait_requests done\n");
4156 }
4157 
4158 /*
4159  * called before mount is ro, and before dentries are torn down.
4160  * (hmm, does this still race with new lookups?)
4161  */
4162 void ceph_mdsc_pre_umount(struct ceph_mds_client *mdsc)
4163 {
4164 	dout("pre_umount\n");
4165 	mdsc->stopping = 1;
4166 
4167 	lock_unlock_sessions(mdsc);
4168 	ceph_flush_dirty_caps(mdsc);
4169 	wait_requests(mdsc);
4170 
4171 	/*
4172 	 * wait for reply handlers to drop their request refs and
4173 	 * their inode/dcache refs
4174 	 */
4175 	ceph_msgr_flush();
4176 
4177 	ceph_cleanup_quotarealms_inodes(mdsc);
4178 }
4179 
4180 /*
4181  * wait for all write mds requests to flush.
4182  */
4183 static void wait_unsafe_requests(struct ceph_mds_client *mdsc, u64 want_tid)
4184 {
4185 	struct ceph_mds_request *req = NULL, *nextreq;
4186 	struct rb_node *n;
4187 
4188 	mutex_lock(&mdsc->mutex);
4189 	dout("wait_unsafe_requests want %lld\n", want_tid);
4190 restart:
4191 	req = __get_oldest_req(mdsc);
4192 	while (req && req->r_tid <= want_tid) {
4193 		/* find next request */
4194 		n = rb_next(&req->r_node);
4195 		if (n)
4196 			nextreq = rb_entry(n, struct ceph_mds_request, r_node);
4197 		else
4198 			nextreq = NULL;
4199 		if (req->r_op != CEPH_MDS_OP_SETFILELOCK &&
4200 		    (req->r_op & CEPH_MDS_OP_WRITE)) {
4201 			/* write op */
4202 			ceph_mdsc_get_request(req);
4203 			if (nextreq)
4204 				ceph_mdsc_get_request(nextreq);
4205 			mutex_unlock(&mdsc->mutex);
4206 			dout("wait_unsafe_requests  wait on %llu (want %llu)\n",
4207 			     req->r_tid, want_tid);
4208 			wait_for_completion(&req->r_safe_completion);
4209 			mutex_lock(&mdsc->mutex);
4210 			ceph_mdsc_put_request(req);
4211 			if (!nextreq)
4212 				break;  /* next dne before, so we're done! */
4213 			if (RB_EMPTY_NODE(&nextreq->r_node)) {
4214 				/* next request was removed from tree */
4215 				ceph_mdsc_put_request(nextreq);
4216 				goto restart;
4217 			}
4218 			ceph_mdsc_put_request(nextreq);  /* won't go away */
4219 		}
4220 		req = nextreq;
4221 	}
4222 	mutex_unlock(&mdsc->mutex);
4223 	dout("wait_unsafe_requests done\n");
4224 }
4225 
4226 void ceph_mdsc_sync(struct ceph_mds_client *mdsc)
4227 {
4228 	u64 want_tid, want_flush;
4229 
4230 	if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN)
4231 		return;
4232 
4233 	dout("sync\n");
4234 	mutex_lock(&mdsc->mutex);
4235 	want_tid = mdsc->last_tid;
4236 	mutex_unlock(&mdsc->mutex);
4237 
4238 	ceph_flush_dirty_caps(mdsc);
4239 	spin_lock(&mdsc->cap_dirty_lock);
4240 	want_flush = mdsc->last_cap_flush_tid;
4241 	if (!list_empty(&mdsc->cap_flush_list)) {
4242 		struct ceph_cap_flush *cf =
4243 			list_last_entry(&mdsc->cap_flush_list,
4244 					struct ceph_cap_flush, g_list);
4245 		cf->wake = true;
4246 	}
4247 	spin_unlock(&mdsc->cap_dirty_lock);
4248 
4249 	dout("sync want tid %lld flush_seq %lld\n",
4250 	     want_tid, want_flush);
4251 
4252 	wait_unsafe_requests(mdsc, want_tid);
4253 	wait_caps_flush(mdsc, want_flush);
4254 }
4255 
4256 /*
4257  * true if all sessions are closed, or we force unmount
4258  */
4259 static bool done_closing_sessions(struct ceph_mds_client *mdsc, int skipped)
4260 {
4261 	if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN)
4262 		return true;
4263 	return atomic_read(&mdsc->num_sessions) <= skipped;
4264 }
4265 
4266 /*
4267  * called after sb is ro.
4268  */
4269 void ceph_mdsc_close_sessions(struct ceph_mds_client *mdsc)
4270 {
4271 	struct ceph_options *opts = mdsc->fsc->client->options;
4272 	struct ceph_mds_session *session;
4273 	int i;
4274 	int skipped = 0;
4275 
4276 	dout("close_sessions\n");
4277 
4278 	/* close sessions */
4279 	mutex_lock(&mdsc->mutex);
4280 	for (i = 0; i < mdsc->max_sessions; i++) {
4281 		session = __ceph_lookup_mds_session(mdsc, i);
4282 		if (!session)
4283 			continue;
4284 		mutex_unlock(&mdsc->mutex);
4285 		mutex_lock(&session->s_mutex);
4286 		if (__close_session(mdsc, session) <= 0)
4287 			skipped++;
4288 		mutex_unlock(&session->s_mutex);
4289 		ceph_put_mds_session(session);
4290 		mutex_lock(&mdsc->mutex);
4291 	}
4292 	mutex_unlock(&mdsc->mutex);
4293 
4294 	dout("waiting for sessions to close\n");
4295 	wait_event_timeout(mdsc->session_close_wq,
4296 			   done_closing_sessions(mdsc, skipped),
4297 			   ceph_timeout_jiffies(opts->mount_timeout));
4298 
4299 	/* tear down remaining sessions */
4300 	mutex_lock(&mdsc->mutex);
4301 	for (i = 0; i < mdsc->max_sessions; i++) {
4302 		if (mdsc->sessions[i]) {
4303 			session = get_session(mdsc->sessions[i]);
4304 			__unregister_session(mdsc, session);
4305 			mutex_unlock(&mdsc->mutex);
4306 			mutex_lock(&session->s_mutex);
4307 			remove_session_caps(session);
4308 			mutex_unlock(&session->s_mutex);
4309 			ceph_put_mds_session(session);
4310 			mutex_lock(&mdsc->mutex);
4311 		}
4312 	}
4313 	WARN_ON(!list_empty(&mdsc->cap_delay_list));
4314 	mutex_unlock(&mdsc->mutex);
4315 
4316 	ceph_cleanup_snapid_map(mdsc);
4317 	ceph_cleanup_empty_realms(mdsc);
4318 
4319 	cancel_work_sync(&mdsc->cap_reclaim_work);
4320 	cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
4321 
4322 	dout("stopped\n");
4323 }
4324 
4325 void ceph_mdsc_force_umount(struct ceph_mds_client *mdsc)
4326 {
4327 	struct ceph_mds_session *session;
4328 	int mds;
4329 
4330 	dout("force umount\n");
4331 
4332 	mutex_lock(&mdsc->mutex);
4333 	for (mds = 0; mds < mdsc->max_sessions; mds++) {
4334 		session = __ceph_lookup_mds_session(mdsc, mds);
4335 		if (!session)
4336 			continue;
4337 		mutex_unlock(&mdsc->mutex);
4338 		mutex_lock(&session->s_mutex);
4339 		__close_session(mdsc, session);
4340 		if (session->s_state == CEPH_MDS_SESSION_CLOSING) {
4341 			cleanup_session_requests(mdsc, session);
4342 			remove_session_caps(session);
4343 		}
4344 		mutex_unlock(&session->s_mutex);
4345 		ceph_put_mds_session(session);
4346 		mutex_lock(&mdsc->mutex);
4347 		kick_requests(mdsc, mds);
4348 	}
4349 	__wake_requests(mdsc, &mdsc->waiting_for_map);
4350 	mutex_unlock(&mdsc->mutex);
4351 }
4352 
4353 static void ceph_mdsc_stop(struct ceph_mds_client *mdsc)
4354 {
4355 	dout("stop\n");
4356 	cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
4357 	if (mdsc->mdsmap)
4358 		ceph_mdsmap_destroy(mdsc->mdsmap);
4359 	kfree(mdsc->sessions);
4360 	ceph_caps_finalize(mdsc);
4361 	ceph_pool_perm_destroy(mdsc);
4362 }
4363 
4364 void ceph_mdsc_destroy(struct ceph_fs_client *fsc)
4365 {
4366 	struct ceph_mds_client *mdsc = fsc->mdsc;
4367 	dout("mdsc_destroy %p\n", mdsc);
4368 
4369 	if (!mdsc)
4370 		return;
4371 
4372 	/* flush out any connection work with references to us */
4373 	ceph_msgr_flush();
4374 
4375 	ceph_mdsc_stop(mdsc);
4376 
4377 	fsc->mdsc = NULL;
4378 	kfree(mdsc);
4379 	dout("mdsc_destroy %p done\n", mdsc);
4380 }
4381 
4382 void ceph_mdsc_handle_fsmap(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
4383 {
4384 	struct ceph_fs_client *fsc = mdsc->fsc;
4385 	const char *mds_namespace = fsc->mount_options->mds_namespace;
4386 	void *p = msg->front.iov_base;
4387 	void *end = p + msg->front.iov_len;
4388 	u32 epoch;
4389 	u32 map_len;
4390 	u32 num_fs;
4391 	u32 mount_fscid = (u32)-1;
4392 	u8 struct_v, struct_cv;
4393 	int err = -EINVAL;
4394 
4395 	ceph_decode_need(&p, end, sizeof(u32), bad);
4396 	epoch = ceph_decode_32(&p);
4397 
4398 	dout("handle_fsmap epoch %u\n", epoch);
4399 
4400 	ceph_decode_need(&p, end, 2 + sizeof(u32), bad);
4401 	struct_v = ceph_decode_8(&p);
4402 	struct_cv = ceph_decode_8(&p);
4403 	map_len = ceph_decode_32(&p);
4404 
4405 	ceph_decode_need(&p, end, sizeof(u32) * 3, bad);
4406 	p += sizeof(u32) * 2; /* skip epoch and legacy_client_fscid */
4407 
4408 	num_fs = ceph_decode_32(&p);
4409 	while (num_fs-- > 0) {
4410 		void *info_p, *info_end;
4411 		u32 info_len;
4412 		u8 info_v, info_cv;
4413 		u32 fscid, namelen;
4414 
4415 		ceph_decode_need(&p, end, 2 + sizeof(u32), bad);
4416 		info_v = ceph_decode_8(&p);
4417 		info_cv = ceph_decode_8(&p);
4418 		info_len = ceph_decode_32(&p);
4419 		ceph_decode_need(&p, end, info_len, bad);
4420 		info_p = p;
4421 		info_end = p + info_len;
4422 		p = info_end;
4423 
4424 		ceph_decode_need(&info_p, info_end, sizeof(u32) * 2, bad);
4425 		fscid = ceph_decode_32(&info_p);
4426 		namelen = ceph_decode_32(&info_p);
4427 		ceph_decode_need(&info_p, info_end, namelen, bad);
4428 
4429 		if (mds_namespace &&
4430 		    strlen(mds_namespace) == namelen &&
4431 		    !strncmp(mds_namespace, (char *)info_p, namelen)) {
4432 			mount_fscid = fscid;
4433 			break;
4434 		}
4435 	}
4436 
4437 	ceph_monc_got_map(&fsc->client->monc, CEPH_SUB_FSMAP, epoch);
4438 	if (mount_fscid != (u32)-1) {
4439 		fsc->client->monc.fs_cluster_id = mount_fscid;
4440 		ceph_monc_want_map(&fsc->client->monc, CEPH_SUB_MDSMAP,
4441 				   0, true);
4442 		ceph_monc_renew_subs(&fsc->client->monc);
4443 	} else {
4444 		err = -ENOENT;
4445 		goto err_out;
4446 	}
4447 	return;
4448 
4449 bad:
4450 	pr_err("error decoding fsmap\n");
4451 err_out:
4452 	mutex_lock(&mdsc->mutex);
4453 	mdsc->mdsmap_err = err;
4454 	__wake_requests(mdsc, &mdsc->waiting_for_map);
4455 	mutex_unlock(&mdsc->mutex);
4456 }
4457 
4458 /*
4459  * handle mds map update.
4460  */
4461 void ceph_mdsc_handle_mdsmap(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
4462 {
4463 	u32 epoch;
4464 	u32 maplen;
4465 	void *p = msg->front.iov_base;
4466 	void *end = p + msg->front.iov_len;
4467 	struct ceph_mdsmap *newmap, *oldmap;
4468 	struct ceph_fsid fsid;
4469 	int err = -EINVAL;
4470 
4471 	ceph_decode_need(&p, end, sizeof(fsid)+2*sizeof(u32), bad);
4472 	ceph_decode_copy(&p, &fsid, sizeof(fsid));
4473 	if (ceph_check_fsid(mdsc->fsc->client, &fsid) < 0)
4474 		return;
4475 	epoch = ceph_decode_32(&p);
4476 	maplen = ceph_decode_32(&p);
4477 	dout("handle_map epoch %u len %d\n", epoch, (int)maplen);
4478 
4479 	/* do we need it? */
4480 	mutex_lock(&mdsc->mutex);
4481 	if (mdsc->mdsmap && epoch <= mdsc->mdsmap->m_epoch) {
4482 		dout("handle_map epoch %u <= our %u\n",
4483 		     epoch, mdsc->mdsmap->m_epoch);
4484 		mutex_unlock(&mdsc->mutex);
4485 		return;
4486 	}
4487 
4488 	newmap = ceph_mdsmap_decode(&p, end);
4489 	if (IS_ERR(newmap)) {
4490 		err = PTR_ERR(newmap);
4491 		goto bad_unlock;
4492 	}
4493 
4494 	/* swap into place */
4495 	if (mdsc->mdsmap) {
4496 		oldmap = mdsc->mdsmap;
4497 		mdsc->mdsmap = newmap;
4498 		check_new_map(mdsc, newmap, oldmap);
4499 		ceph_mdsmap_destroy(oldmap);
4500 	} else {
4501 		mdsc->mdsmap = newmap;  /* first mds map */
4502 	}
4503 	mdsc->fsc->max_file_size = min((loff_t)mdsc->mdsmap->m_max_file_size,
4504 					MAX_LFS_FILESIZE);
4505 
4506 	__wake_requests(mdsc, &mdsc->waiting_for_map);
4507 	ceph_monc_got_map(&mdsc->fsc->client->monc, CEPH_SUB_MDSMAP,
4508 			  mdsc->mdsmap->m_epoch);
4509 
4510 	mutex_unlock(&mdsc->mutex);
4511 	schedule_delayed(mdsc);
4512 	return;
4513 
4514 bad_unlock:
4515 	mutex_unlock(&mdsc->mutex);
4516 bad:
4517 	pr_err("error decoding mdsmap %d\n", err);
4518 	return;
4519 }
4520 
4521 static struct ceph_connection *con_get(struct ceph_connection *con)
4522 {
4523 	struct ceph_mds_session *s = con->private;
4524 
4525 	if (get_session(s)) {
4526 		dout("mdsc con_get %p ok (%d)\n", s, refcount_read(&s->s_ref));
4527 		return con;
4528 	}
4529 	dout("mdsc con_get %p FAIL\n", s);
4530 	return NULL;
4531 }
4532 
4533 static void con_put(struct ceph_connection *con)
4534 {
4535 	struct ceph_mds_session *s = con->private;
4536 
4537 	dout("mdsc con_put %p (%d)\n", s, refcount_read(&s->s_ref) - 1);
4538 	ceph_put_mds_session(s);
4539 }
4540 
4541 /*
4542  * if the client is unresponsive for long enough, the mds will kill
4543  * the session entirely.
4544  */
4545 static void peer_reset(struct ceph_connection *con)
4546 {
4547 	struct ceph_mds_session *s = con->private;
4548 	struct ceph_mds_client *mdsc = s->s_mdsc;
4549 
4550 	pr_warn("mds%d closed our session\n", s->s_mds);
4551 	send_mds_reconnect(mdsc, s);
4552 }
4553 
4554 static void dispatch(struct ceph_connection *con, struct ceph_msg *msg)
4555 {
4556 	struct ceph_mds_session *s = con->private;
4557 	struct ceph_mds_client *mdsc = s->s_mdsc;
4558 	int type = le16_to_cpu(msg->hdr.type);
4559 
4560 	mutex_lock(&mdsc->mutex);
4561 	if (__verify_registered_session(mdsc, s) < 0) {
4562 		mutex_unlock(&mdsc->mutex);
4563 		goto out;
4564 	}
4565 	mutex_unlock(&mdsc->mutex);
4566 
4567 	switch (type) {
4568 	case CEPH_MSG_MDS_MAP:
4569 		ceph_mdsc_handle_mdsmap(mdsc, msg);
4570 		break;
4571 	case CEPH_MSG_FS_MAP_USER:
4572 		ceph_mdsc_handle_fsmap(mdsc, msg);
4573 		break;
4574 	case CEPH_MSG_CLIENT_SESSION:
4575 		handle_session(s, msg);
4576 		break;
4577 	case CEPH_MSG_CLIENT_REPLY:
4578 		handle_reply(s, msg);
4579 		break;
4580 	case CEPH_MSG_CLIENT_REQUEST_FORWARD:
4581 		handle_forward(mdsc, s, msg);
4582 		break;
4583 	case CEPH_MSG_CLIENT_CAPS:
4584 		ceph_handle_caps(s, msg);
4585 		break;
4586 	case CEPH_MSG_CLIENT_SNAP:
4587 		ceph_handle_snap(mdsc, s, msg);
4588 		break;
4589 	case CEPH_MSG_CLIENT_LEASE:
4590 		handle_lease(mdsc, s, msg);
4591 		break;
4592 	case CEPH_MSG_CLIENT_QUOTA:
4593 		ceph_handle_quota(mdsc, s, msg);
4594 		break;
4595 
4596 	default:
4597 		pr_err("received unknown message type %d %s\n", type,
4598 		       ceph_msg_type_name(type));
4599 	}
4600 out:
4601 	ceph_msg_put(msg);
4602 }
4603 
4604 /*
4605  * authentication
4606  */
4607 
4608 /*
4609  * Note: returned pointer is the address of a structure that's
4610  * managed separately.  Caller must *not* attempt to free it.
4611  */
4612 static struct ceph_auth_handshake *get_authorizer(struct ceph_connection *con,
4613 					int *proto, int force_new)
4614 {
4615 	struct ceph_mds_session *s = con->private;
4616 	struct ceph_mds_client *mdsc = s->s_mdsc;
4617 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
4618 	struct ceph_auth_handshake *auth = &s->s_auth;
4619 
4620 	if (force_new && auth->authorizer) {
4621 		ceph_auth_destroy_authorizer(auth->authorizer);
4622 		auth->authorizer = NULL;
4623 	}
4624 	if (!auth->authorizer) {
4625 		int ret = ceph_auth_create_authorizer(ac, CEPH_ENTITY_TYPE_MDS,
4626 						      auth);
4627 		if (ret)
4628 			return ERR_PTR(ret);
4629 	} else {
4630 		int ret = ceph_auth_update_authorizer(ac, CEPH_ENTITY_TYPE_MDS,
4631 						      auth);
4632 		if (ret)
4633 			return ERR_PTR(ret);
4634 	}
4635 	*proto = ac->protocol;
4636 
4637 	return auth;
4638 }
4639 
4640 static int add_authorizer_challenge(struct ceph_connection *con,
4641 				    void *challenge_buf, int challenge_buf_len)
4642 {
4643 	struct ceph_mds_session *s = con->private;
4644 	struct ceph_mds_client *mdsc = s->s_mdsc;
4645 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
4646 
4647 	return ceph_auth_add_authorizer_challenge(ac, s->s_auth.authorizer,
4648 					    challenge_buf, challenge_buf_len);
4649 }
4650 
4651 static int verify_authorizer_reply(struct ceph_connection *con)
4652 {
4653 	struct ceph_mds_session *s = con->private;
4654 	struct ceph_mds_client *mdsc = s->s_mdsc;
4655 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
4656 
4657 	return ceph_auth_verify_authorizer_reply(ac, s->s_auth.authorizer);
4658 }
4659 
4660 static int invalidate_authorizer(struct ceph_connection *con)
4661 {
4662 	struct ceph_mds_session *s = con->private;
4663 	struct ceph_mds_client *mdsc = s->s_mdsc;
4664 	struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
4665 
4666 	ceph_auth_invalidate_authorizer(ac, CEPH_ENTITY_TYPE_MDS);
4667 
4668 	return ceph_monc_validate_auth(&mdsc->fsc->client->monc);
4669 }
4670 
4671 static struct ceph_msg *mds_alloc_msg(struct ceph_connection *con,
4672 				struct ceph_msg_header *hdr, int *skip)
4673 {
4674 	struct ceph_msg *msg;
4675 	int type = (int) le16_to_cpu(hdr->type);
4676 	int front_len = (int) le32_to_cpu(hdr->front_len);
4677 
4678 	if (con->in_msg)
4679 		return con->in_msg;
4680 
4681 	*skip = 0;
4682 	msg = ceph_msg_new(type, front_len, GFP_NOFS, false);
4683 	if (!msg) {
4684 		pr_err("unable to allocate msg type %d len %d\n",
4685 		       type, front_len);
4686 		return NULL;
4687 	}
4688 
4689 	return msg;
4690 }
4691 
4692 static int mds_sign_message(struct ceph_msg *msg)
4693 {
4694        struct ceph_mds_session *s = msg->con->private;
4695        struct ceph_auth_handshake *auth = &s->s_auth;
4696 
4697        return ceph_auth_sign_message(auth, msg);
4698 }
4699 
4700 static int mds_check_message_signature(struct ceph_msg *msg)
4701 {
4702        struct ceph_mds_session *s = msg->con->private;
4703        struct ceph_auth_handshake *auth = &s->s_auth;
4704 
4705        return ceph_auth_check_message_signature(auth, msg);
4706 }
4707 
4708 static const struct ceph_connection_operations mds_con_ops = {
4709 	.get = con_get,
4710 	.put = con_put,
4711 	.dispatch = dispatch,
4712 	.get_authorizer = get_authorizer,
4713 	.add_authorizer_challenge = add_authorizer_challenge,
4714 	.verify_authorizer_reply = verify_authorizer_reply,
4715 	.invalidate_authorizer = invalidate_authorizer,
4716 	.peer_reset = peer_reset,
4717 	.alloc_msg = mds_alloc_msg,
4718 	.sign_message = mds_sign_message,
4719 	.check_message_signature = mds_check_message_signature,
4720 };
4721 
4722 /* eof */
4723